• Home
  • Raw
  • Download

Lines Matching +full:lint +full:- +full:py +full:- +full:build

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
139 is provided for each category like 'build/class'.
148 with SVN). In addition, users of non-mainstream version control systems
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:
169 .git, .hg, or .svn but can also be controlled with the --repository flag.
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
260 The above example disables build/include_order warning and enables
261 build/include_alpha as well as excludes all .cc from being
263 file is located) and all sub-directories.
267 # We want an explicit list so we can list them all in cpplint --filter=.
269 # here! cpplint_unittest.py should tell you if you forget to do this.
271 'build/class',
272 'build/c++11',
273 'build/c++14',
274 'build/c++tr1',
275 'build/deprecated',
276 'build/endif_comment',
277 'build/explicit_make_pair',
278 'build/forward_decl',
279 'build/header_guard',
280 'build/include',
281 'build/include_subdir',
282 'build/include_alpha',
283 'build/include_order',
284 'build/include_what_you_use',
285 'build/namespaces_literals',
286 'build/namespaces',
287 'build/printf_format',
288 'build/storage_class',
341 # These error categories are no longer enforced by cpplint, but for backwards-
348 # The default state of the category filter. This is overridden by the --filter=
350 # off by default (i.e., categories that must be enabled by the --filter= flags).
351 # All entries here should start with a '-' or '+', as in the --filter= flag.
352 _DEFAULT_FILTERS = ['-build/include_alpha']
364 # We used to check for high-bit characters, but after much discussion we
365 # decided those were OK, as long as they were in UTF-8 and didn't represent
366 # hard-coded international strings, which belong in a separate i18n file.
531 # These headers are excluded from [build/include] and [build/include_order]
533 # - Anything not following google file name conventions (containing an
535 # - Lua headers.
537 r'^(?:[^/]*[A-Z][^/]*\.h|lua\.h|lauxlib\.h|lualib\.h)$')
593 # False positives include C-style multi-line comments and multi-line strings
632 # This is set by --root flag.
638 # This is set by the --repository flag.
641 # Files to exclude from linting. This is set by the --exclude flag.
648 # This is set by --linelength flag.
654 # -- pylint: disable=redefined-builtin
660 # -- pylint: disable=redefined-builtin
664 # -- pylint: disable=no-member
680 # This is set by --headers flag.
703 # This is set by --extensions flag
715 """Updates the global list of line error-suppressions.
738 category = category[1:-1]
749 Parses any lint directives in the file that have global effect.
875 Line number of previous occurrence, or -1 if the header has not
882 return -1
900 self.include_list[-1] = []
908 - replaces "-" with "_" so they both cmp the same.
909 - removes '-inl' since we don't require them to be after the main header.
910 - lowercase everything, just in case.
918 return header_path.replace('-inl.h', '.h').replace('-', '_').lower()
937 Match(r'^\s*#\s*include\b', clean_lines.elided[linenum - 1])):
942 """Returns a non-empty error message if the next header is out of order.
996 """Maintains module-wide state.."""
1007 self.quiet = False # Suppress non-error messagess?
1010 # "emacs" - format that emacs can parse (default)
1011 # "eclipse" - format that eclipse can parse
1012 # "vs7" - format that Microsoft Visual Studio 7 can parse
1013 # "junit" - format that Jenkins, Bamboo, etc can parse
1042 """Sets the error-message filters.
1048 filters: A string of comma-separated filters (eg "+whitespace/indent").
1049 Each filter should start with + or -; else we die.
1052 ValueError: The comma-separated filters did not all start with '+' or '-'.
1053 E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter"
1060 """ Adds more filters to the existing list of error-message filters. """
1066 if not (filt.startswith('+') or filt.startswith('-')):
1067 raise ValueError('Every filter in --filters must start with + or -'
1155 xml_decl = '<?xml version="1.0" encoding="UTF-8" ?>\n'
1156 return xml_decl + xml.etree.ElementTree.tostring(testsuite, 'utf-8').decode('utf-8')
1201 """Sets the module's error-message filters.
1207 filters: A string of comma-separated filters (eg "whitespace/indent").
1208 Each filter should start with + or -; else we die.
1219 filters: A string of comma-separated filters (eg "whitespace/indent").
1220 Each filter should start with + or -; else we die.
1235 _NORMAL_TRIGGER = 250 # for --v=0, 500 for --v=1, etc.
1282 ' %s has %d non-comment lines'
1385 """File base name - text after the final slash, before the final period."""
1389 """File extension - text following the final period, includes that period."""
1415 if one_filter.startswith('-'):
1430 """Logs the fact we've found a lint error.
1446 confidence: A number from 1-5 representing a confidence score for
1469 r'\\([abfnrtv?"\\\']|\d+|x[0-9a-fA-F]+)')
1472 # Matches multi-line C style comments.
1478 # if this doesn't work we try on left side but only if there's a non-character
1490 This function does not consider single-line nor multi-line comments.
1501 return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1
1509 multi-line string
1568 # Start of a multi-line raw string
1601 """Clears a range of lines for multi-line comments."""
1602 # Having // dummy comments makes the lines non-empty, so we will not get
1609 """Removes multiline (c-style) comments from lines."""
1618 'Could not find end of multi-line comment')
1625 """Removes //-comments and single-line C-style /* */ comments.
1631 The line with single-line comments removed.
1634 if commentpos != -1 and not IsCppString(line[:commentpos]):
1718 if Search(r'\b(?:0[bBxX]?|[1-9])[0-9a-fA-F]*$', head):
1719 match_literal = Match(r'^((?:\'?[0-9a-zA-Z_])*)(.*)$', "'" + tail)
1745 On finding an unclosed expression: (-1, None)
1746 Otherwise: (-1, new stack at end of this line)
1755 if i > 0 and line[i - 1] == '<':
1757 if stack and stack[-1] == '<':
1760 return (-1, None)
1772 while stack and stack[-1] == '<':
1775 return (-1, None)
1776 if ((stack[-1] == '(' and char == ')') or
1777 (stack[-1] == '[' and char == ']') or
1778 (stack[-1] == '{' and char == '}')):
1784 return (-1, None)
1788 # Ignore "->" and operator functions
1790 (line[i - 1] == '-' or Search(r'\boperator\s*$', line[0:i - 1]))):
1796 if stack[-1] == '<':
1804 while stack and stack[-1] == '<':
1807 return (-1, None)
1810 return (-1, stack)
1831 (line, len(lines), -1) if we never find a close. Note we ignore
1838 return (line, clean_lines.NumLines(), -1)
1842 if end_pos > -1:
1846 while stack and linenum < clean_lines.NumLines() - 1:
1850 if end_pos > -1:
1854 return (line, clean_lines.NumLines(), -1)
1870 On finding an unclosed expression: (-1, None)
1871 Otherwise: (-1, new stack at beginning of this line)
1882 # Ignore it if it's a "->" or ">=" or "operator>"
1884 (line[i - 1] == '-' or
1885 Match(r'\s>=\s', line[i - 1:]) or
1887 i -= 1
1892 if i > 0 and line[i - 1] == '<':
1894 i -= 1
1898 if stack and stack[-1] == '>':
1907 while stack and stack[-1] == '>':
1910 return (-1, None)
1911 if ((char == '(' and stack[-1] == ')') or
1912 (char == '[' and stack[-1] == ']') or
1913 (char == '{' and stack[-1] == '}')):
1919 return (-1, None)
1924 while stack and stack[-1] == '>':
1927 return (-1, None)
1929 i -= 1
1931 return (-1, stack)
1947 (line, 0, -1) if we never find the matching opening brace. Note
1953 return (line, 0, -1)
1957 if start_pos > -1:
1962 linenum -= 1
1964 (start_pos, stack) = FindStartOfExpressionInLine(line, len(line) - 1, stack)
1965 if start_pos > -1:
1969 return (line, 0, -1)
2052 # Process the file path with the --root flag if it was set.
2059 # f(['x', 'y'], ['w, z']) -> None (not a valid prefix)
2062 # f(['a, 'b', 'c', 'd'], ['a', 'b']) -> ['c', 'd']
2066 # --root=subdir , lstrips subdir from the header guard
2077 # --root=.. , will prepend the outer directory to the header guard
2094 # --root=FAKE_DIR is ignored
2098 return re.sub(r'[^a-zA-Z0-9]', '_', file_path_from_root).upper() + '_'
2117 # only support the very specific NOLINT(build/header_guard) syntax,
2121 if Search(r'//\s*NOLINT\(build/header_guard\)', i):
2152 error(filename, 0, 'build/header_guard', 5,
2166 error(filename, ifndef_linenum, 'build/header_guard', error_level,
2176 error(filename, endif_linenum, 'build/header_guard', 0,
2184 for i in xrange(1, len(raw_lines) - 1):
2195 error(filename, endif_linenum, 'build/header_guard', 0,
2200 error(filename, endif_linenum, 'build/header_guard', 5,
2213 basefilename = filename[0:len(filename) - len(fileinfo.Extension())]
2226 error(filename, first_include, 'build/include', 5,
2237 contained invalid UTF-8 (likely) or Unicode replacement characters (which
2239 numbering if the invalid UTF-8 occurred adjacent to a newline.
2251 'Line contains invalid UTF-8 (or Unicode replacement character).')
2268 # last-but-two element of lines() exists and is empty.
2269 if len(lines) < 3 or lines[-2]:
2270 error(filename, len(lines) - 2, 'whitespace/ending_newline', 5,
2283 in this lint program, so we warn about both.
2299 'Complex multi-line /*...*/-style comment found. '
2300 'Lint may give bogus warnings. '
2301 'Consider replacing these with //-style comments, '
2303 'or with more clearly structured multi-line comments.')
2305 if (line.count('"') - line.count('\\"')) % 2:
2307 'Multi-line string ("...") found. This lint script doesn\'t '
2312 # (non-threadsafe name, thread-safe alternative, validation pattern)
2316 # ->rand(); // some member function rand().
2324 _UNSAFE_FUNC_PREFIX = r'(?:[-+*/=%^&|(<]\s*|>\s+)'
2343 """Checks for calls to thread-unsafe functions.
2346 multi-threading. Also, engineers are relying on their old experience;
2348 tests guide the engineers to use thread-safe functions (when using
2389 r'^\s*\*\w+(\+\+|--);')
2418 if linenum > 0 and Search(r'\\$', clean_lines[linenum - 1]):
2513 depth += line.count('{') - line.count('}')
2527 for i in xrange(linenum - 1, self.starting_linenum, -1):
2543 # This means we will not check single-line class definitions.
2577 if (linenum - self.starting_linenum < 10
2636 # - _ClassInfo: a class or struct.
2637 # - _NamespaceInfo: a namespace.
2638 # - _BlockInfo: some other type of block.
2662 return (not self.stack) or self.stack[-1].seen_open_brace
2670 return self.stack and isinstance(self.stack[-1], _NamespaceInfo)
2678 return self.stack and isinstance(self.stack[-1], _ExternCInfo)
2686 return self.stack and isinstance(self.stack[-1], _ClassInfo)
2694 return self.stack and self.stack[-1].inline_asm != _NO_ASM
2740 (_, end_line, end_pos) = CloseExpression(clean_lines, linenum, pos - 1)
2759 - Preprocessor condition evaluates to true from #if up to first
2762 - Preprocessor condition evaluates to false from #else/#elif up
2763 to #endif. We still perform lint checks on these lines, but
2776 if not self.pp_stack[-1].seen_else:
2780 self.pp_stack[-1].seen_else = True
2781 self.pp_stack[-1].stack_before_else = copy.deepcopy(self.stack)
2784 self.stack = copy.deepcopy(self.pp_stack[-1].stack_before_if)
2794 if self.pp_stack[-1].seen_else:
2797 self.stack = self.pp_stack[-1].stack_before_else
2822 self.previous_stack_top = self.stack[-1]
2832 inner_block = self.stack[-1]
2833 depth_change = line.count('(') - line.count(')')
2868 if line.find('{') != -1:
2879 r'(class|struct)\s+(?:[A-Z_]+\s+)*(\w+(?:::\w+)*))'
2882 (not self.stack or self.stack[-1].open_parentheses == 0)):
2902 self.stack[-1].CheckBegin(filename, clean_lines, linenum, error)
2905 if self.stack and isinstance(self.stack[-1], _ClassInfo):
2906 classinfo = self.stack[-1]
2943 self.stack[-1].seen_open_brace = True
2949 self.stack[-1].inline_asm = _BLOCK_ASM
2965 self.stack[-1].CheckEnd(filename, clean_lines, linenum, error)
2975 for i in range(len(self.stack), 0, -1):
2976 classinfo = self.stack[i - 1]
2991 # cpplint_unittest.py for an example of this.
2994 error(filename, obj.starting_linenum, 'build/class', 5,
2998 error(filename, obj.starting_linenum, 'build/namespaces', 5,
3005 r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
3007 Complain about several constructs which gcc-2 accepts, but which are
3008 not standard C++. Warning about these in lint is one way to ease the
3010 - put storage class first (e.g. "static const" instead of "const static").
3011 - "%lld" instead of %qd" in printf-type functions.
3012 - "%1$d" is non-standard in printf-type functions.
3013 - "\%" is an undefined character escape sequence.
3014 - text after #endif is not allowed.
3015 - invalid inner-style forward declaration.
3016 - >? and <? operators, and their >?= and <?= cousins.
3020 gcc-2 compliance.
3035 if Search(r'printf\s*\(.*".*%[-+ ]?\d*q', line):
3047 error(filename, linenum, 'build/printf_format', 3,
3058 error(filename, linenum, 'build/storage_class', 5,
3059 'Storage-class specifier (static, extern, typedef, etc) should be '
3063 error(filename, linenum, 'build/endif_comment', 5,
3064 'Uncommented text after #endif is non-standard. Use a comment.')
3067 error(filename, linenum, 'build/forward_decl', 5,
3068 'Inner-style forward declarations are invalid. Remove this line.')
3070 if Search(r'(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?',
3072 error(filename, linenum, 'build/deprecated', 3,
3073 '>? and <? (max and min) operators are non-standard and deprecated.')
3096 base_classname = classinfo.name.split('::')[-1]
3098 # Look for single-argument constructors that aren't marked explicit.
3138 len(defaulted_args) >= len(constructor_args) - 1) or
3160 'Single-parameter constructors should be marked explicit.')
3164 'Zero-parameter constructors should not be marked explicit.')
3179 # expressions - which have their own, more liberal conventions - we
3200 # " (something)(maybe-something)" or
3201 # " (something)(maybe-something," or
3263 nesting_state.stack[-1].check_namespace_indentation and
3265 nesting_state.previous_stack_top == nesting_state.stack[-2])
3278 https://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions
3286 of vertical space and comments just to get through a lint check.
3306 function_name = match_result.group(1).split()[-1]
3308 not Match(r'[A-Z_]+$', function_name)):
3331 # No body for the function (or evidence of a non-function) was found.
3333 'Lint failed to find start of function body.')
3338 function_state.Count() # Count non-blank/non-comment lines.
3351 next_line_start: The first non-whitespace column of the next line.
3355 if commentpos != -1:
3361 line[commentpos-1] not in string.whitespace) or
3363 line[commentpos-2] not in string.whitespace))):
3384 # Comparisons made explicit for correctness -- pylint: disable=g-explicit-bool-comparison
3441 prev_line = elided[linenum - 1]
3447 if prevbrace != -1 and prev_line[prevbrace:].find('}') == -1:
3450 # non-empty line has the parameters of a function header that are indented
3459 search_position = linenum-2
3462 search_position -= 1
3480 # Ignore blank lines at the end of a block in a long if-else
3492 and next_line.find('} else ') == -1):
3506 next_line_start = len(next_line) - len(next_line.lstrip())
3518 # In range-based for, we wanted spaces before and after the colon, but
3523 'Missing space around colon in range-based for loop')
3550 # We allow no-spaces around = within an if: "if ( (a=Foo()) == 0 )".
3551 # Otherwise not. Note we only check for non-spaces on *both* sides;
3552 # sometimes people put non-spaces on one side when aligning ='s among
3563 # It's ok not to have spaces around binary operators like + - * /, but if
3570 # check non-include lines for spacing around < and >.
3591 if end_pos <= -1:
3598 match = Match(r'^(.*[^-\s>])>[^\s=>,]', line)
3602 if start_pos <= -1:
3606 # We allow no-spaces around << when used like this: 10<<20, but
3617 # We allow no-spaces around >> for almost anything. This is because
3629 match = Search(r'>>[a-zA-Z_]', line)
3635 match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line)
3693 # This does not apply when the non-space character following the
3742 block_index = len(nesting_state.stack) - 1
3757 next_block_start = nesting_state.stack[block_index - 1].starting_linenum
3762 first_line -= 1
3766 block_index -= 1
3773 block_index -= 1
3832 if endpos > -1:
3835 min(endlinenum + 3, clean_lines.NumLines() - 1)):
3907 if (class_info.last_line - class_info.starting_linenum <= 24 or
3916 # - We are at the beginning of the class.
3917 # - We are forward-declaring an inner class that is semantically
3921 prev_line = clean_lines.lines[linenum - 1]
3926 # account for multi-line base-specifier lists, e.g.:
3934 if end_class_head < linenum - 1:
3940 """Return the most recent non-blank line and its line number.
3948 non-blank line before the current line, or the empty string if this is the
3949 first non-blank line. The second is the line number of that line, or -1
3950 if this is the first non-blank line.
3953 prevlinenum = linenum - 1
3958 prevlinenum -= 1
3959 return ('', -1)
3977 # to control the lifetime of stack-allocated variables. Braces are also
3979 # perfectly: we just don't complain if the last non-whitespace character on
3980 # the previous non-blank line is ',', ';', ':', '(', '{', or '}', or if the
3987 not (GetLineWidth(prevline) > _line_length - 2 and '[]' in prevline)):
4000 if Search(r'else if\s*\(', line): # could be multi-line if
4007 brace_on_right = endline[endpos:].find('{') != -1
4025 # Check single-line if/else bodies. The style guide says 'curly braces are not
4026 # required for single-line statements'. We additionally allow multi-line,
4039 pos = if_match.end() - 1
4042 # line. If found, this isn't a single-statement conditional.
4045 and endlinenum < (len(clean_lines.elided) - 1)
4053 # We allow a mix of whitespace and closing braces (e.g. for one-liner
4064 elif endlinenum < len(clean_lines.elided) - 1:
4122 # braces inside multi-dimensional arrays, but this is fine since
4142 # - macro that defines a base class
4143 # - multi-line macro that defines a base class
4144 # - macro that defines the whole class-head
4148 # - TEST, TEST_F, TEST_P, MATCHER, MATCHER_P
4149 # - TYPED_TEST
4150 # - INTERFACE_DEF
4151 # - EXCLUSIVE_LOCKS_REQUIRED, SHARED_LOCKS_REQUIRED, LOCKS_EXCLUDED:
4161 # - Compound literals
4162 # - Lambdas
4163 # - alignas specifier with anonymous structs
4164 # - decltype
4168 if opening_parenthesis[2] > -1:
4170 macro = Search(r'\b([A-Z_][A-Z0-9_]*)\s*$', line_prefix)
4184 Search(r'\]\s*$', clean_lines.elided[opening_parenthesis[1] - 1])):
4185 # Multi-line lambda-expression
4189 # Try matching cases 2-3.
4192 # Try matching cases 4-6. These are always matched on separate lines.
4208 if endpos > -1 and Match(r'^\s*;', endline[endpos:]):
4219 ParseNolintSuppressions(filename, raw_lines[endlinenum-1], endlinenum-1,
4240 # do-while-loops, since those lines should start with closing brace.
4305 bodylist.append(clean_lines.elided[closing_linenum][:closing_pos-1])
4309 body = opening_line[opening_pos+1:closing_pos-1]
4333 """Find a replaceable CHECK-like macro.
4338 (macro name, start position), or (None, -1) if no replaceable
4352 return (None, -1)
4384 expression = lines[linenum][start_pos + 1:end_pos - 1]
4389 expression += last_line[0:end_pos - 1]
4398 matched = Match(r'^\s*(<<|<<=|>>|>>=|->\*|->|&&|\|\||'
4417 elif token in ('<<', '<<=', '>>', '>>=', '->*', '->'):
4418 # Non-relational operator
4432 matched = Match(r'^([^-=!<>()&|]+)(.*)$', expression)
4446 if rhs.find('&&') > -1 or rhs.find('||') > -1:
4457 match_constant = r'^([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')$'
4488 # Last ditch effort to avoid multi-line comments. This will not help
4492 # multi-line comments in preprocessor macros.
4495 # multi-line comments.
4522 # https://mail.python.org/pipermail/python-list/2012-August/628809.html
4529 width -= 1
4542 do what we can. In particular we check for 2-space indents, line lengths,
4560 prev = raw_lines[linenum - 1] if linenum > 0 else ''
4562 if line.find('\t') != -1:
4567 # hard to reconcile that with 2-space indents.
4585 # section labels, and also lines containing multi-line raw strings.
4588 # because the rules for how to indent those are non-trivial.
4595 'Weird number of spaces at line-start. '
4596 'Are you using a 2-space indent?')
4598 if line and line[-1].isspace():
4624 not Match(r'^// \$Id:.*#[0-9]+ \$$', line) and
4636 cleansed_line.find('for') == -1 and
4637 (GetPreviousNonBlankLine(clean_lines, linenum)[0].find('for') == -1 or
4638 GetPreviousNonBlankLine(clean_lines, linenum)[0].find(';') != -1) and
4640 not ((cleansed_line.find('case ') != -1 or
4641 cleansed_line.find('default:') != -1) and
4642 cleansed_line.find('break;') != -1)):
4664 # Matches the first component of a filename delimited by -s and _s. That is:
4667 # _RE_FIRST_COMPONENT.match('foo-bar_baz.cc').group(0) == 'foo'
4668 # _RE_FIRST_COMPONENT.match('foo_bar-baz.cc').group(0) == 'foo'
4669 _RE_FIRST_COMPONENT = re.compile(r'^[^-_.]+')
4673 """Drops common suffixes like _test.cc or -inl.h from filename.
4676 >>> _DropCommonSuffixes('foo/foo-inl.h')
4697 filename[-len(suffix) - 1] in ('-', '_')):
4698 return filename[:-len(suffix) - 1]
4794 error(filename, linenum, 'build/include_subdir', 4,
4806 error(filename, linenum, 'build/include', 4,
4814 error(filename, linenum, 'build/include', 4,
4819 include_state.include_list[-1].append((include, linenum))
4835 error(filename, linenum, 'build/include_order', 4,
4841 error(filename, linenum, 'build/include_alpha', 4,
4852 (, [, or {, and the matching close-punctuation symbol. This properly nested
4867 # TODO(unknown): Audit cpplint.py to see what places could be profitably
4870 # Give opening punctuations to get the matching close-punctuations.
4882 assert text[start_position - 1] in matching_punctuation, (
4885 punctuation_stack = [matching_punctuation[text[start_position - 1]]]
4888 if text[position] == punctuation_stack[-1]:
4897 # Opening punctuations left without matching close-punctuations.
4900 return text[start_position:position - 1]
4903 # Patterns for matching call-by-reference parameters.
4912 _RE_PATTERN_IDENT = r'[_a-zA-Z]\w*' # =~ [[:alpha:]][[:alnum:]]*
4918 # A call-by-reference parameter ends with '& identifier'.
4922 # A call-by-const-reference parameter either ends with 'const& identifier'
4973 # TODO(unknown): check that 1-arg constructors are explicit.
4993 # TODO(unknown): catch out-of-line unary operator&:
5010 # Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str())
5017 match = Match(r'([\w.\->()]+)$', printf_args)
5027 if match and not Match(r"^''|-?[0-9]+|0x[0-9A-Fa-f]$", match.group(2)):
5034 error(filename, linenum, 'build/namespaces_literals', 5,
5035 'Do not use namespace using-directives. '
5036 'Use using-declarations instead.')
5038 error(filename, linenum, 'build/namespaces', 5,
5039 'Do not use namespace using-directives. '
5040 'Use using-declarations instead.')
5042 # Detect variable-length arrays.
5043 match = Match(r'\s*(.+::)?(\w+) [a-z]\w*\[(.+)];', line)
5045 match.group(3).find(']') == -1):
5049 tokens = re.split(r'\s|\+|\-|\*|\/|<<|>>]', match.group(3))
5064 if Match(r'0[xX][0-9a-fA-F]+', tok): continue
5065 if Match(r'k[A-Z0-9]\w*', tok): continue
5066 if Match(r'(.+::)?k[A-Z0-9]\w*', tok): continue
5067 if Match(r'(.+::)?[A-Z][A-Z0-9_]*', tok): continue
5078 'Do not use variable-length arrays. Use an appropriately named '
5079 "('k' followed by CamelCase) compile-time constant for the size.")
5086 and line[-1] != '\\'):
5087 error(filename, linenum, 'build/namespaces', 4,
5089 'https://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces'
5113 # TODO(unknown): File bugs for clang-tidy to find these.
5116 r'([a-zA-Z0-9_:]+)\b(.*)',
5120 # - String pointers (as opposed to values).
5126 # - Functions and template specializations.
5130 # - Operators. These are matched separately because operator names
5131 # cross non-word boundaries, and trying to match both operators
5138 not Match(r'\s*(<.*>)?(::[a-zA-Z0-9_]+)*\s*\(([^"]|$)', match.group(4))):
5148 if (Search(r'\b([A-Za-z0-9_]*_)\(\1\)', line) or
5149 Search(r'\b([A-Za-z0-9_]*_)\(CHECK_NOTNULL\(\1\)\)', line)):
5166 match = Search(r'snprintf\s*\(([^,]*),\s*([0-9]*)\s*,', line)
5191 virt-specifier.
5194 for i in xrange(linenum, max(-1, linenum - 10), -1):
5206 """Check if current line contains an out-of-line method definition.
5212 True if current line contains an out-of-line method definition.
5215 for i in xrange(linenum, max(-1, linenum - 10), -1):
5231 for i in xrange(linenum, 1, -1):
5246 # brace-initialized member in constructor initializer list.
5250 # - A closing brace or semicolon, probably the end of the previous
5252 # - An opening brace, probably the start of current class or namespace.
5265 """Check for non-const references.
5284 # a choice, so any non-const references should not be blamed on
5289 # Don't warn on out-of-line method definitions, as we would warn on the
5290 # in-line declaration, if it isn't marked with 'override'.
5315 clean_lines.elided[linenum - 1])
5316 elif Match(r'\s*[a-zA-Z_]([\w<>]|::)+\s*&\s*\S', line):
5319 clean_lines.elided[linenum - 1])
5325 if endpos > -1:
5328 if startpos > -1 and startline < linenum:
5335 # Check for non-const references in function parameters. A single '&' may
5356 for i in xrange(linenum - 1, max(0, linenum - 10), -1):
5371 # We allow non-const references in a few standard places, like functions
5386 # multi-line parameter list. Try a bit harder to catch this case.
5389 Search(whitelisted_functions, clean_lines.elided[linenum - i - 1])):
5397 'Is this a non-const reference? '
5426 # - New operators
5427 # - Template arguments with function types
5432 # template argument. False negative with less-than comparison is
5445 # - Function pointers
5446 # - Casts to pointer types
5447 # - Placement new
5448 # - Alias declarations
5479 # is dangerous -- casts can assign to temporaries, so the pointer doesn't
5482 # Some non-identifier character is required before the '&' for the
5504 if y2 < clean_lines.NumLines() - 1:
5506 if Match(r'\s*(?:->|\[)', extended_line):
5522 """Checks for a C-style cast by looking for the pattern.
5530 pattern: The regular expression used to find C-style casts.
5543 context = line[0:match.start(1) - 1]
5544 if Match(r'.*\b(?:sizeof|alignof|alignas|[_A-Z][_A-Z0-9]*)\s*$', context):
5550 for i in xrange(linenum - 1, max(0, linenum - 5), -1):
5552 if Match(r'.*\b[_A-Z][_A-Z0-9]*\s*\((?:\([^()]*\)|[^()])*$', context):
5555 # operator++(int) and operator--(int)
5556 if context.endswith(' operator++') or context.endswith(' operator--'):
5562 if Match(r'^\s*(?:;|const\b|throw\b|final\b|override\b|[=>{),]|->)',
5568 'Using C-style cast. Use %s<%s>(...) instead' %
5589 clean_lines.elided[linenum - 1]) or
5591 clean_lines.elided[linenum - 2]) or
5593 clean_lines.elided[linenum - 1]))))
5649 # Match max<type>(..., ...), max(..., ...), but not foo->max, foo.max or
5670 foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the
5703 filename_cc = filename_cc[:-(len(fileinfo_cc.Extension()))]
5706 filename_cc = filename_cc[:-len(matched_test_suffix.group(1))]
5711 filename_h = filename_h[:-(len(fileinfo_h.Extension()))]
5712 if filename_h.endswith('-inl'):
5713 filename_h = filename_h[:-len('-inl')]
5720 common_path = filename_cc[:-len(filename_h)]
5777 # String is special -- it is a non-templatized type in STL.
5780 # Don't warn about strings in non-STL namespaces:
5797 # Don't warn about IWYU in non-STL namespaces:
5848 'build/include_what_you_use', 4,
5870 error(filename, linenum, 'build/explicit_make_pair',
5872 'For C++11-compatibility, omit template arguments from make_pair'
5877 """Check if line contains a redundant "virtual" function-specifier.
5890 # Ignore "virtual" keywords that are near access-specifiers. These
5891 # are only used in class base-specifier and do not apply to member
5907 end_col = -1
5908 end_line = -1
5941 """Check if line contains a redundant "override" or "final" virt-specifier.
5950 # the declarator ends and where the virt-specifier starts to avoid
5957 if linenum > 1 and clean_lines.elided[linenum - 1].rfind(')') >= 0:
5984 isinstance(nesting_state.stack[-1], _NamespaceInfo))
5988 nesting_state.stack[-1].check_namespace_indentation and
5989 isinstance(nesting_state.stack[-2], _NamespaceInfo))
6093 error(filename, linenum, 'build/c++tr1', 5,
6108 error(filename, linenum, 'build/c++11', 5,
6124 error(filename, linenum, 'build/c++11', 5,
6125 ('std::%s is an unapproved C++11 class or function. Send c-style '
6145 error(filename, linenum, 'build/c++14', 5,
6151 """Performs lint checks and reports any errors to the given error function.
6240 # For example, if we are checking for lint errors in /foo/bar/baz.cc
6248 # Suppress "Ignoring file" warning when using --quiet.
6267 sys.stderr.write('Extensions should be a comma-separated list of values;'
6286 # Apply all the accumulated filters in reverse order (top-level directory
6295 """Does google-lint on a single file.
6319 # Support the UNIX convention of using "-" for stdin. Note that
6326 if filename == '-':
6335 # The -1 accounts for the extra trailing blank line we get from split()
6336 for linenum in range(len(lines) - 1):
6354 if filename != '-' and file_extension not in GetAllExtensions():
6361 # If end-of-line sequences are a mix of LF and CR-LF, issue
6364 # Don't issue any warnings if all lines are uniformly LF or CR-LF,
6369 # end-of-line sequence should be, since that will return the
6370 # server-side end-of-line sequence.
6379 # Suppress printing anything if --quiet was passed unless the error
6409 """Prints a list of all the error-categories used by error messages.
6411 These are the categories used to filter messages via --filter.
6420 This may set the output format and verbosity level as side-effects.
6426 The list of filenames to lint.
6453 if opt == '--help':
6455 if opt == '--version':
6457 elif opt == '--output':
6462 elif opt == '--quiet':
6464 elif opt == '--verbose' or opt == '--v':
6466 elif opt == '--filter':
6470 elif opt == '--counting':
6474 elif opt == '--root':
6477 elif opt == '--repository':
6480 elif opt == '--linelength':
6486 elif opt == '--exclude':
6491 elif opt == '--extensions':
6497 elif opt == '--headers':
6499 elif opt == '--recursive':
6552 """Filters out files listed in the --exclude command line switch. File paths
6563 # if we try to print something containing non-ASCII characters.
6569 # If --quiet is passed, suppress printing error count unless there are errors.