+++ /dev/null
-#!/usr/bin/env python\r
-#\r
-# Copyright (c) 2009 Google Inc. All rights reserved.\r
-#\r
-# Redistribution and use in source and binary forms, with or without\r
-# modification, are permitted provided that the following conditions are\r
-# met:\r
-#\r
-# * Redistributions of source code must retain the above copyright\r
-# notice, this list of conditions and the following disclaimer.\r
-# * Redistributions in binary form must reproduce the above\r
-# copyright notice, this list of conditions and the following disclaimer\r
-# in the documentation and/or other materials provided with the\r
-# distribution.\r
-# * Neither the name of Google Inc. nor the names of its\r
-# contributors may be used to endorse or promote products derived from\r
-# this software without specific prior written permission.\r
-#\r
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r
-# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\r
-# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\r
-# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\r
-# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\r
-# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\r
-# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\r
-# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\r
-# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\r
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r
-\r
-"""Does google-lint on c++ files.\r
-\r
-The goal of this script is to identify places in the code that *may*\r
-be in non-compliance with google style. It does not attempt to fix\r
-up these problems -- the point is to educate. It does also not\r
-attempt to find all problems, or to ensure that everything it does\r
-find is legitimately a problem.\r
-\r
-In particular, we can get very confused by /* and // inside strings!\r
-We do a small hack, which is to ignore //'s with "'s after them on the\r
-same line, but it is far from perfect (in either direction).\r
-"""\r
-\r
-import codecs\r
-import copy\r
-import getopt\r
-import math # for log\r
-import os\r
-import re\r
-import sre_compile\r
-import string\r
-import sys\r
-import unicodedata\r
-\r
-\r
-_USAGE = """\r
-Syntax: cpplint.py [--verbose=#] [--output=vs7] [--filter=-x,+y,...]\r
- [--counting=total|toplevel|detailed] [--root=subdir]\r
- [--linelength=digits] [--headers=x,y,...]\r
- <file> [file] ...\r
-\r
- The style guidelines this tries to follow are those in\r
- https://google-styleguide.googlecode.com/svn/trunk/cppguide.xml\r
-\r
- Every problem is given a confidence score from 1-5, with 5 meaning we are\r
- certain of the problem, and 1 meaning it could be a legitimate construct.\r
- This will miss some errors, and is not a substitute for a code review.\r
-\r
- To suppress false-positive errors of a certain category, add a\r
- 'NOLINT(category)' comment to the line. NOLINT or NOLINT(*)\r
- suppresses errors of all categories on that line.\r
-\r
- The files passed in will be linted; at least one file must be provided.\r
- Default linted extensions are .cc, .cpp, .cu, .cuh and .h. Change the\r
- extensions with the --extensions flag.\r
-\r
- Flags:\r
-\r
- output=vs7\r
- By default, the output is formatted to ease emacs parsing. Visual Studio\r
- compatible output (vs7) may also be used. Other formats are unsupported.\r
-\r
- verbose=#\r
- Specify a number 0-5 to restrict errors to certain verbosity levels.\r
-\r
- filter=-x,+y,...\r
- Specify a comma-separated list of category-filters to apply: only\r
- error messages whose category names pass the filters will be printed.\r
- (Category names are printed with the message and look like\r
- "[whitespace/indent]".) Filters are evaluated left to right.\r
- "-FOO" and "FOO" means "do not print categories that start with FOO".\r
- "+FOO" means "do print categories that start with FOO".\r
-\r
- Examples: --filter=-whitespace,+whitespace/braces\r
- --filter=whitespace,runtime/printf,+runtime/printf_format\r
- --filter=-,+build/include_what_you_use\r
-\r
- To see a list of all the categories used in cpplint, pass no arg:\r
- --filter=\r
-\r
- counting=total|toplevel|detailed\r
- The total number of errors found is always printed. If\r
- 'toplevel' is provided, then the count of errors in each of\r
- the top-level categories like 'build' and 'whitespace' will\r
- also be printed. If 'detailed' is provided, then a count\r
- is provided for each category like 'build/class'.\r
-\r
- root=subdir\r
- The root directory used for deriving header guard CPP variable.\r
- By default, the header guard CPP variable is calculated as the relative\r
- path to the directory that contains .git, .hg, or .svn. When this flag\r
- is specified, the relative path is calculated from the specified\r
- directory. If the specified directory does not exist, this flag is\r
- ignored.\r
-\r
- Examples:\r
- Assuming that src/.git exists, the header guard CPP variables for\r
- src/chrome/browser/ui/browser.h are:\r
-\r
- No flag => CHROME_BROWSER_UI_BROWSER_H_\r
- --root=chrome => BROWSER_UI_BROWSER_H_\r
- --root=chrome/browser => UI_BROWSER_H_\r
-\r
- linelength=digits\r
- This is the allowed line length for the project. The default value is\r
- 80 characters.\r
-\r
- Examples:\r
- --linelength=120\r
-\r
- extensions=extension,extension,...\r
- The allowed file extensions that cpplint will check\r
-\r
- Examples:\r
- --extensions=hpp,cpp\r
-\r
- headers=x,y,...\r
- The header extensions that cpplint will treat as .h in checks. Values are\r
- automatically added to --extensions list.\r
-\r
- Examples:\r
- --headers=hpp,hxx\r
- --headers=hpp\r
-\r
- cpplint.py supports per-directory configurations specified in CPPLINT.cfg\r
- files. CPPLINT.cfg file can contain a number of key=value pairs.\r
- Currently the following options are supported:\r
-\r
- set noparent\r
- filter=+filter1,-filter2,...\r
- exclude_files=regex\r
- linelength=80\r
- root=subdir\r
- headers=x,y,...\r
-\r
- "set noparent" option prevents cpplint from traversing directory tree\r
- upwards looking for more .cfg files in parent directories. This option\r
- is usually placed in the top-level project directory.\r
-\r
- The "filter" option is similar in function to --filter flag. It specifies\r
- message filters in addition to the |_DEFAULT_FILTERS| and those specified\r
- through --filter command-line flag.\r
-\r
- "exclude_files" allows to specify a regular expression to be matched against\r
- a file name. If the expression matches, the file is skipped and not run\r
- through liner.\r
-\r
- "linelength" allows to specify the allowed line length for the project.\r
-\r
- The "root" option is similar in function to the --root flag (see example\r
- above).\r
- \r
- The "headers" option is similar in function to the --headers flag \r
- (see example above).\r
-\r
- CPPLINT.cfg has an effect on files in the same directory and all\r
- sub-directories, unless overridden by a nested configuration file.\r
-\r
- Example file:\r
- filter=-build/include_order,+build/include_alpha\r
- exclude_files=.*\.cc\r
-\r
- The above example disables build/include_order warning and enables\r
- build/include_alpha as well as excludes all .cc from being\r
- processed by linter, in the current directory (where the .cfg\r
- file is located) and all sub-directories.\r
-"""\r
-\r
-# We categorize each error message we print. Here are the categories.\r
-# We want an explicit list so we can list them all in cpplint --filter=.\r
-# If you add a new error message with a new category, add it to the list\r
-# here! cpplint_unittest.py should tell you if you forget to do this.\r
-_ERROR_CATEGORIES = [\r
- 'build/class',\r
- 'build/c++11',\r
- 'build/c++14',\r
- 'build/c++tr1',\r
- 'build/deprecated',\r
- 'build/endif_comment',\r
- 'build/explicit_make_pair',\r
- 'build/forward_decl',\r
- 'build/header_guard',\r
- 'build/include',\r
- 'build/include_alpha',\r
- 'build/include_order',\r
- 'build/include_what_you_use',\r
- 'build/namespaces',\r
- 'build/printf_format',\r
- 'build/storage_class',\r
- 'legal/copyright',\r
- 'readability/alt_tokens',\r
- 'readability/braces',\r
- 'readability/casting',\r
- 'readability/check',\r
- 'readability/constructors',\r
- 'readability/fn_size',\r
- 'readability/inheritance',\r
- 'readability/multiline_comment',\r
- 'readability/multiline_string',\r
- 'readability/namespace',\r
- 'readability/nolint',\r
- 'readability/nul',\r
- 'readability/strings',\r
- 'readability/todo',\r
- 'readability/utf8',\r
- 'runtime/arrays',\r
- 'runtime/casting',\r
- 'runtime/explicit',\r
- 'runtime/int',\r
- 'runtime/init',\r
- 'runtime/invalid_increment',\r
- 'runtime/member_string_references',\r
- 'runtime/memset',\r
- 'runtime/indentation_namespace',\r
- 'runtime/operator',\r
- 'runtime/printf',\r
- 'runtime/printf_format',\r
- 'runtime/references',\r
- 'runtime/string',\r
- 'runtime/threadsafe_fn',\r
- 'runtime/vlog',\r
- 'whitespace/blank_line',\r
- 'whitespace/braces',\r
- 'whitespace/comma',\r
- 'whitespace/comments',\r
- 'whitespace/empty_conditional_body',\r
- 'whitespace/empty_if_body',\r
- 'whitespace/empty_loop_body',\r
- 'whitespace/end_of_line',\r
- 'whitespace/ending_newline',\r
- 'whitespace/forcolon',\r
- 'whitespace/indent',\r
- 'whitespace/line_length',\r
- 'whitespace/newline',\r
- 'whitespace/operators',\r
- 'whitespace/parens',\r
- 'whitespace/semicolon',\r
- 'whitespace/tab',\r
- 'whitespace/todo',\r
- ]\r
-\r
-# These error categories are no longer enforced by cpplint, but for backwards-\r
-# compatibility they may still appear in NOLINT comments.\r
-_LEGACY_ERROR_CATEGORIES = [\r
- 'readability/streams',\r
- 'readability/function',\r
- ]\r
-\r
-# The default state of the category filter. This is overridden by the --filter=\r
-# flag. By default all errors are on, so only add here categories that should be\r
-# off by default (i.e., categories that must be enabled by the --filter= flags).\r
-# All entries here should start with a '-' or '+', as in the --filter= flag.\r
-_DEFAULT_FILTERS = ['-build/include_alpha']\r
-\r
-# The default list of categories suppressed for C (not C++) files.\r
-_DEFAULT_C_SUPPRESSED_CATEGORIES = [\r
- 'readability/casting',\r
- ]\r
-\r
-# The default list of categories suppressed for Linux Kernel files.\r
-_DEFAULT_KERNEL_SUPPRESSED_CATEGORIES = [\r
- 'whitespace/tab',\r
- ]\r
-\r
-# We used to check for high-bit characters, but after much discussion we\r
-# decided those were OK, as long as they were in UTF-8 and didn't represent\r
-# hard-coded international strings, which belong in a separate i18n file.\r
-\r
-# C++ headers\r
-_CPP_HEADERS = frozenset([\r
- # Legacy\r
- 'algobase.h',\r
- 'algo.h',\r
- 'alloc.h',\r
- 'builtinbuf.h',\r
- 'bvector.h',\r
- 'complex.h',\r
- 'defalloc.h',\r
- 'deque.h',\r
- 'editbuf.h',\r
- 'fstream.h',\r
- 'function.h',\r
- 'hash_map',\r
- 'hash_map.h',\r
- 'hash_set',\r
- 'hash_set.h',\r
- 'hashtable.h',\r
- 'heap.h',\r
- 'indstream.h',\r
- 'iomanip.h',\r
- 'iostream.h',\r
- 'istream.h',\r
- 'iterator.h',\r
- 'list.h',\r
- 'map.h',\r
- 'multimap.h',\r
- 'multiset.h',\r
- 'ostream.h',\r
- 'pair.h',\r
- 'parsestream.h',\r
- 'pfstream.h',\r
- 'procbuf.h',\r
- 'pthread_alloc',\r
- 'pthread_alloc.h',\r
- 'rope',\r
- 'rope.h',\r
- 'ropeimpl.h',\r
- 'set.h',\r
- 'slist',\r
- 'slist.h',\r
- 'stack.h',\r
- 'stdiostream.h',\r
- 'stl_alloc.h',\r
- 'stl_relops.h',\r
- 'streambuf.h',\r
- 'stream.h',\r
- 'strfile.h',\r
- 'strstream.h',\r
- 'tempbuf.h',\r
- 'tree.h',\r
- 'type_traits.h',\r
- 'vector.h',\r
- # 17.6.1.2 C++ library headers\r
- 'algorithm',\r
- 'array',\r
- 'atomic',\r
- 'bitset',\r
- 'chrono',\r
- 'codecvt',\r
- 'complex',\r
- 'condition_variable',\r
- 'deque',\r
- 'exception',\r
- 'forward_list',\r
- 'fstream',\r
- 'functional',\r
- 'future',\r
- 'initializer_list',\r
- 'iomanip',\r
- 'ios',\r
- 'iosfwd',\r
- 'iostream',\r
- 'istream',\r
- 'iterator',\r
- 'limits',\r
- 'list',\r
- 'locale',\r
- 'map',\r
- 'memory',\r
- 'mutex',\r
- 'new',\r
- 'numeric',\r
- 'ostream',\r
- 'queue',\r
- 'random',\r
- 'ratio',\r
- 'regex',\r
- 'scoped_allocator',\r
- 'set',\r
- 'sstream',\r
- 'stack',\r
- 'stdexcept',\r
- 'streambuf',\r
- 'string',\r
- 'strstream',\r
- 'system_error',\r
- 'thread',\r
- 'tuple',\r
- 'typeindex',\r
- 'typeinfo',\r
- 'type_traits',\r
- 'unordered_map',\r
- 'unordered_set',\r
- 'utility',\r
- 'valarray',\r
- 'vector',\r
- # 17.6.1.2 C++ headers for C library facilities\r
- 'cassert',\r
- 'ccomplex',\r
- 'cctype',\r
- 'cerrno',\r
- 'cfenv',\r
- 'cfloat',\r
- 'cinttypes',\r
- 'ciso646',\r
- 'climits',\r
- 'clocale',\r
- 'cmath',\r
- 'csetjmp',\r
- 'csignal',\r
- 'cstdalign',\r
- 'cstdarg',\r
- 'cstdbool',\r
- 'cstddef',\r
- 'cstdint',\r
- 'cstdio',\r
- 'cstdlib',\r
- 'cstring',\r
- 'ctgmath',\r
- 'ctime',\r
- 'cuchar',\r
- 'cwchar',\r
- 'cwctype',\r
- ])\r
-\r
-# Type names\r
-_TYPES = re.compile(\r
- r'^(?:'\r
- # [dcl.type.simple]\r
- r'(char(16_t|32_t)?)|wchar_t|'\r
- r'bool|short|int|long|signed|unsigned|float|double|'\r
- # [support.types]\r
- r'(ptrdiff_t|size_t|max_align_t|nullptr_t)|'\r
- # [cstdint.syn]\r
- r'(u?int(_fast|_least)?(8|16|32|64)_t)|'\r
- r'(u?int(max|ptr)_t)|'\r
- r')$')\r
-\r
-\r
-# These headers are excluded from [build/include] and [build/include_order]\r
-# checks:\r
-# - Anything not following google file name conventions (containing an\r
-# uppercase character, such as Python.h or nsStringAPI.h, for example).\r
-# - Lua headers.\r
-_THIRD_PARTY_HEADERS_PATTERN = re.compile(\r
- r'^(?:[^/]*[A-Z][^/]*\.h|lua\.h|lauxlib\.h|lualib\.h)$')\r
-\r
-# Pattern for matching FileInfo.BaseName() against test file name\r
-_TEST_FILE_SUFFIX = r'(_test|_unittest|_regtest)$'\r
-\r
-# Pattern that matches only complete whitespace, possibly across multiple lines.\r
-_EMPTY_CONDITIONAL_BODY_PATTERN = re.compile(r'^\s*$', re.DOTALL)\r
-\r
-# Assertion macros. These are defined in base/logging.h and\r
-# testing/base/public/gunit.h.\r
-_CHECK_MACROS = [\r
- 'DCHECK', 'CHECK',\r
- 'EXPECT_TRUE', 'ASSERT_TRUE',\r
- 'EXPECT_FALSE', 'ASSERT_FALSE',\r
- ]\r
-\r
-# Replacement macros for CHECK/DCHECK/EXPECT_TRUE/EXPECT_FALSE\r
-_CHECK_REPLACEMENT = dict([(m, {}) for m in _CHECK_MACROS])\r
-\r
-for op, replacement in [('==', 'EQ'), ('!=', 'NE'),\r
- ('>=', 'GE'), ('>', 'GT'),\r
- ('<=', 'LE'), ('<', 'LT')]:\r
- _CHECK_REPLACEMENT['DCHECK'][op] = 'DCHECK_%s' % replacement\r
- _CHECK_REPLACEMENT['CHECK'][op] = 'CHECK_%s' % replacement\r
- _CHECK_REPLACEMENT['EXPECT_TRUE'][op] = 'EXPECT_%s' % replacement\r
- _CHECK_REPLACEMENT['ASSERT_TRUE'][op] = 'ASSERT_%s' % replacement\r
-\r
-for op, inv_replacement in [('==', 'NE'), ('!=', 'EQ'),\r
- ('>=', 'LT'), ('>', 'LE'),\r
- ('<=', 'GT'), ('<', 'GE')]:\r
- _CHECK_REPLACEMENT['EXPECT_FALSE'][op] = 'EXPECT_%s' % inv_replacement\r
- _CHECK_REPLACEMENT['ASSERT_FALSE'][op] = 'ASSERT_%s' % inv_replacement\r
-\r
-# Alternative tokens and their replacements. For full list, see section 2.5\r
-# Alternative tokens [lex.digraph] in the C++ standard.\r
-#\r
-# Digraphs (such as '%:') are not included here since it's a mess to\r
-# match those on a word boundary.\r
-_ALT_TOKEN_REPLACEMENT = {\r
- 'and': '&&',\r
- 'bitor': '|',\r
- 'or': '||',\r
- 'xor': '^',\r
- 'compl': '~',\r
- 'bitand': '&',\r
- 'and_eq': '&=',\r
- 'or_eq': '|=',\r
- 'xor_eq': '^=',\r
- 'not': '!',\r
- 'not_eq': '!='\r
- }\r
-\r
-# Compile regular expression that matches all the above keywords. The "[ =()]"\r
-# bit is meant to avoid matching these keywords outside of boolean expressions.\r
-#\r
-# False positives include C-style multi-line comments and multi-line strings\r
-# but those have always been troublesome for cpplint.\r
-_ALT_TOKEN_REPLACEMENT_PATTERN = re.compile(\r
- r'[ =()](' + ('|'.join(_ALT_TOKEN_REPLACEMENT.keys())) + r')(?=[ (]|$)')\r
-\r
-\r
-# These constants define types of headers for use with\r
-# _IncludeState.CheckNextIncludeOrder().\r
-_C_SYS_HEADER = 1\r
-_CPP_SYS_HEADER = 2\r
-_LIKELY_MY_HEADER = 3\r
-_POSSIBLE_MY_HEADER = 4\r
-_OTHER_HEADER = 5\r
-\r
-# These constants define the current inline assembly state\r
-_NO_ASM = 0 # Outside of inline assembly block\r
-_INSIDE_ASM = 1 # Inside inline assembly block\r
-_END_ASM = 2 # Last line of inline assembly block\r
-_BLOCK_ASM = 3 # The whole block is an inline assembly block\r
-\r
-# Match start of assembly blocks\r
-_MATCH_ASM = re.compile(r'^\s*(?:asm|_asm|__asm|__asm__)'\r
- r'(?:\s+(volatile|__volatile__))?'\r
- r'\s*[{(]')\r
-\r
-# Match strings that indicate we're working on a C (not C++) file.\r
-_SEARCH_C_FILE = re.compile(r'\b(?:LINT_C_FILE|'\r
- r'vim?:\s*.*(\s*|:)filetype=c(\s*|:|$))')\r
-\r
-# Match string that indicates we're working on a Linux Kernel file.\r
-_SEARCH_KERNEL_FILE = re.compile(r'\b(?:LINT_KERNEL_FILE)')\r
-\r
-_regexp_compile_cache = {}\r
-\r
-# {str, set(int)}: a map from error categories to sets of linenumbers\r
-# on which those errors are expected and should be suppressed.\r
-_error_suppressions = {}\r
-\r
-# The root directory used for deriving header guard CPP variable.\r
-# This is set by --root flag.\r
-_root = None\r
-\r
-# The allowed line length of files.\r
-# This is set by --linelength flag.\r
-_line_length = 80\r
-\r
-# The allowed extensions for file names\r
-# This is set by --extensions flag.\r
-_valid_extensions = set(['cc', 'h', 'cpp', 'cu', 'cuh'])\r
-\r
-# Treat all headers starting with 'h' equally: .h, .hpp, .hxx etc.\r
-# This is set by --headers flag.\r
-_hpp_headers = set(['h'])\r
-\r
-# {str, bool}: a map from error categories to booleans which indicate if the\r
-# category should be suppressed for every line.\r
-_global_error_suppressions = {}\r
-\r
-def ProcessHppHeadersOption(val):\r
- global _hpp_headers\r
- try:\r
- _hpp_headers = set(val.split(','))\r
- # Automatically append to extensions list so it does not have to be set 2 times\r
- _valid_extensions.update(_hpp_headers)\r
- except ValueError:\r
- PrintUsage('Header extensions must be comma seperated list.')\r
-\r
-def IsHeaderExtension(file_extension):\r
- return file_extension in _hpp_headers\r
-\r
-def ParseNolintSuppressions(filename, raw_line, linenum, error):\r
- """Updates the global list of line error-suppressions.\r
-\r
- Parses any NOLINT comments on the current line, updating the global\r
- error_suppressions store. Reports an error if the NOLINT comment\r
- was malformed.\r
-\r
- Args:\r
- filename: str, the name of the input file.\r
- raw_line: str, the line of input text, with comments.\r
- linenum: int, the number of the current line.\r
- error: function, an error handler.\r
- """\r
- matched = Search(r'\bNOLINT(NEXTLINE)?\b(\([^)]+\))?', raw_line)\r
- if matched:\r
- if matched.group(1):\r
- suppressed_line = linenum + 1\r
- else:\r
- suppressed_line = linenum\r
- category = matched.group(2)\r
- if category in (None, '(*)'): # => "suppress all"\r
- _error_suppressions.setdefault(None, set()).add(suppressed_line)\r
- else:\r
- if category.startswith('(') and category.endswith(')'):\r
- category = category[1:-1]\r
- if category in _ERROR_CATEGORIES:\r
- _error_suppressions.setdefault(category, set()).add(suppressed_line)\r
- elif category not in _LEGACY_ERROR_CATEGORIES:\r
- error(filename, linenum, 'readability/nolint', 5,\r
- 'Unknown NOLINT error category: %s' % category)\r
-\r
-\r
-def ProcessGlobalSuppresions(lines):\r
- """Updates the list of global error suppressions.\r
-\r
- Parses any lint directives in the file that have global effect.\r
-\r
- Args:\r
- lines: An array of strings, each representing a line of the file, with the\r
- last element being empty if the file is terminated with a newline.\r
- """\r
- for line in lines:\r
- if _SEARCH_C_FILE.search(line):\r
- for category in _DEFAULT_C_SUPPRESSED_CATEGORIES:\r
- _global_error_suppressions[category] = True\r
- if _SEARCH_KERNEL_FILE.search(line):\r
- for category in _DEFAULT_KERNEL_SUPPRESSED_CATEGORIES:\r
- _global_error_suppressions[category] = True\r
-\r
-\r
-def ResetNolintSuppressions():\r
- """Resets the set of NOLINT suppressions to empty."""\r
- _error_suppressions.clear()\r
- _global_error_suppressions.clear()\r
-\r
-\r
-def IsErrorSuppressedByNolint(category, linenum):\r
- """Returns true if the specified error category is suppressed on this line.\r
-\r
- Consults the global error_suppressions map populated by\r
- ParseNolintSuppressions/ProcessGlobalSuppresions/ResetNolintSuppressions.\r
-\r
- Args:\r
- category: str, the category of the error.\r
- linenum: int, the current line number.\r
- Returns:\r
- bool, True iff the error should be suppressed due to a NOLINT comment or\r
- global suppression.\r
- """\r
- return (_global_error_suppressions.get(category, False) or\r
- linenum in _error_suppressions.get(category, set()) or\r
- linenum in _error_suppressions.get(None, set()))\r
-\r
-\r
-def Match(pattern, s):\r
- """Matches the string with the pattern, caching the compiled regexp."""\r
- # The regexp compilation caching is inlined in both Match and Search for\r
- # performance reasons; factoring it out into a separate function turns out\r
- # to be noticeably expensive.\r
- if pattern not in _regexp_compile_cache:\r
- _regexp_compile_cache[pattern] = sre_compile.compile(pattern)\r
- return _regexp_compile_cache[pattern].match(s)\r
-\r
-\r
-def ReplaceAll(pattern, rep, s):\r
- """Replaces instances of pattern in a string with a replacement.\r
-\r
- The compiled regex is kept in a cache shared by Match and Search.\r
-\r
- Args:\r
- pattern: regex pattern\r
- rep: replacement text\r
- s: search string\r
-\r
- Returns:\r
- string with replacements made (or original string if no replacements)\r
- """\r
- if pattern not in _regexp_compile_cache:\r
- _regexp_compile_cache[pattern] = sre_compile.compile(pattern)\r
- return _regexp_compile_cache[pattern].sub(rep, s)\r
-\r
-\r
-def Search(pattern, s):\r
- """Searches the string for the pattern, caching the compiled regexp."""\r
- if pattern not in _regexp_compile_cache:\r
- _regexp_compile_cache[pattern] = sre_compile.compile(pattern)\r
- return _regexp_compile_cache[pattern].search(s)\r
-\r
-\r
-def _IsSourceExtension(s):\r
- """File extension (excluding dot) matches a source file extension."""\r
- return s in ('c', 'cc', 'cpp', 'cxx')\r
-\r
-\r
-class _IncludeState(object):\r
- """Tracks line numbers for includes, and the order in which includes appear.\r
-\r
- include_list contains list of lists of (header, line number) pairs.\r
- It's a lists of lists rather than just one flat list to make it\r
- easier to update across preprocessor boundaries.\r
-\r
- Call CheckNextIncludeOrder() once for each header in the file, passing\r
- in the type constants defined above. Calls in an illegal order will\r
- raise an _IncludeError with an appropriate error message.\r
-\r
- """\r
- # self._section will move monotonically through this set. If it ever\r
- # needs to move backwards, CheckNextIncludeOrder will raise an error.\r
- _INITIAL_SECTION = 0\r
- _MY_H_SECTION = 1\r
- _C_SECTION = 2\r
- _CPP_SECTION = 3\r
- _OTHER_H_SECTION = 4\r
-\r
- _TYPE_NAMES = {\r
- _C_SYS_HEADER: 'C system header',\r
- _CPP_SYS_HEADER: 'C++ system header',\r
- _LIKELY_MY_HEADER: 'header this file implements',\r
- _POSSIBLE_MY_HEADER: 'header this file may implement',\r
- _OTHER_HEADER: 'other header',\r
- }\r
- _SECTION_NAMES = {\r
- _INITIAL_SECTION: "... nothing. (This can't be an error.)",\r
- _MY_H_SECTION: 'a header this file implements',\r
- _C_SECTION: 'C system header',\r
- _CPP_SECTION: 'C++ system header',\r
- _OTHER_H_SECTION: 'other header',\r
- }\r
-\r
- def __init__(self):\r
- self.include_list = [[]]\r
- self.ResetSection('')\r
-\r
- def FindHeader(self, header):\r
- """Check if a header has already been included.\r
-\r
- Args:\r
- header: header to check.\r
- Returns:\r
- Line number of previous occurrence, or -1 if the header has not\r
- been seen before.\r
- """\r
- for section_list in self.include_list:\r
- for f in section_list:\r
- if f[0] == header:\r
- return f[1]\r
- return -1\r
-\r
- def ResetSection(self, directive):\r
- """Reset section checking for preprocessor directive.\r
-\r
- Args:\r
- directive: preprocessor directive (e.g. "if", "else").\r
- """\r
- # The name of the current section.\r
- self._section = self._INITIAL_SECTION\r
- # The path of last found header.\r
- self._last_header = ''\r
-\r
- # Update list of includes. Note that we never pop from the\r
- # include list.\r
- if directive in ('if', 'ifdef', 'ifndef'):\r
- self.include_list.append([])\r
- elif directive in ('else', 'elif'):\r
- self.include_list[-1] = []\r
-\r
- def SetLastHeader(self, header_path):\r
- self._last_header = header_path\r
-\r
- def CanonicalizeAlphabeticalOrder(self, header_path):\r
- """Returns a path canonicalized for alphabetical comparison.\r
-\r
- - replaces "-" with "_" so they both cmp the same.\r
- - removes '-inl' since we don't require them to be after the main header.\r
- - lowercase everything, just in case.\r
-\r
- Args:\r
- header_path: Path to be canonicalized.\r
-\r
- Returns:\r
- Canonicalized path.\r
- """\r
- return header_path.replace('-inl.h', '.h').replace('-', '_').lower()\r
-\r
- def IsInAlphabeticalOrder(self, clean_lines, linenum, header_path):\r
- """Check if a header is in alphabetical order with the previous header.\r
-\r
- Args:\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- header_path: Canonicalized header to be checked.\r
-\r
- Returns:\r
- Returns true if the header is in alphabetical order.\r
- """\r
- # If previous section is different from current section, _last_header will\r
- # be reset to empty string, so it's always less than current header.\r
- #\r
- # If previous line was a blank line, assume that the headers are\r
- # intentionally sorted the way they are.\r
- if (self._last_header > header_path and\r
- Match(r'^\s*#\s*include\b', clean_lines.elided[linenum - 1])):\r
- return False\r
- return True\r
-\r
- def CheckNextIncludeOrder(self, header_type):\r
- """Returns a non-empty error message if the next header is out of order.\r
-\r
- This function also updates the internal state to be ready to check\r
- the next include.\r
-\r
- Args:\r
- header_type: One of the _XXX_HEADER constants defined above.\r
-\r
- Returns:\r
- The empty string if the header is in the right order, or an\r
- error message describing what's wrong.\r
-\r
- """\r
- error_message = ('Found %s after %s' %\r
- (self._TYPE_NAMES[header_type],\r
- self._SECTION_NAMES[self._section]))\r
-\r
- last_section = self._section\r
-\r
- if header_type == _C_SYS_HEADER:\r
- if self._section <= self._C_SECTION:\r
- self._section = self._C_SECTION\r
- else:\r
- self._last_header = ''\r
- return error_message\r
- elif header_type == _CPP_SYS_HEADER:\r
- if self._section <= self._CPP_SECTION:\r
- self._section = self._CPP_SECTION\r
- else:\r
- self._last_header = ''\r
- return error_message\r
- elif header_type == _LIKELY_MY_HEADER:\r
- if self._section <= self._MY_H_SECTION:\r
- self._section = self._MY_H_SECTION\r
- else:\r
- self._section = self._OTHER_H_SECTION\r
- elif header_type == _POSSIBLE_MY_HEADER:\r
- if self._section <= self._MY_H_SECTION:\r
- self._section = self._MY_H_SECTION\r
- else:\r
- # This will always be the fallback because we're not sure\r
- # enough that the header is associated with this file.\r
- self._section = self._OTHER_H_SECTION\r
- else:\r
- assert header_type == _OTHER_HEADER\r
- self._section = self._OTHER_H_SECTION\r
-\r
- if last_section != self._section:\r
- self._last_header = ''\r
-\r
- return ''\r
-\r
-\r
-class _CppLintState(object):\r
- """Maintains module-wide state.."""\r
-\r
- def __init__(self):\r
- self.verbose_level = 1 # global setting.\r
- self.error_count = 0 # global count of reported errors\r
- # filters to apply when emitting error messages\r
- self.filters = _DEFAULT_FILTERS[:]\r
- # backup of filter list. Used to restore the state after each file.\r
- self._filters_backup = self.filters[:]\r
- self.counting = 'total' # In what way are we counting errors?\r
- self.errors_by_category = {} # string to int dict storing error counts\r
-\r
- # output format:\r
- # "emacs" - format that emacs can parse (default)\r
- # "vs7" - format that Microsoft Visual Studio 7 can parse\r
- self.output_format = 'emacs'\r
-\r
- def SetOutputFormat(self, output_format):\r
- """Sets the output format for errors."""\r
- self.output_format = output_format\r
-\r
- def SetVerboseLevel(self, level):\r
- """Sets the module's verbosity, and returns the previous setting."""\r
- last_verbose_level = self.verbose_level\r
- self.verbose_level = level\r
- return last_verbose_level\r
-\r
- def SetCountingStyle(self, counting_style):\r
- """Sets the module's counting options."""\r
- self.counting = counting_style\r
-\r
- def SetFilters(self, filters):\r
- """Sets the error-message filters.\r
-\r
- These filters are applied when deciding whether to emit a given\r
- error message.\r
-\r
- Args:\r
- filters: A string of comma-separated filters (eg "+whitespace/indent").\r
- Each filter should start with + or -; else we die.\r
-\r
- Raises:\r
- ValueError: The comma-separated filters did not all start with '+' or '-'.\r
- E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter"\r
- """\r
- # Default filters always have less priority than the flag ones.\r
- self.filters = _DEFAULT_FILTERS[:]\r
- self.AddFilters(filters)\r
-\r
- def AddFilters(self, filters):\r
- """ Adds more filters to the existing list of error-message filters. """\r
- for filt in filters.split(','):\r
- clean_filt = filt.strip()\r
- if clean_filt:\r
- self.filters.append(clean_filt)\r
- for filt in self.filters:\r
- if not (filt.startswith('+') or filt.startswith('-')):\r
- raise ValueError('Every filter in --filters must start with + or -'\r
- ' (%s does not)' % filt)\r
-\r
- def BackupFilters(self):\r
- """ Saves the current filter list to backup storage."""\r
- self._filters_backup = self.filters[:]\r
-\r
- def RestoreFilters(self):\r
- """ Restores filters previously backed up."""\r
- self.filters = self._filters_backup[:]\r
-\r
- def ResetErrorCounts(self):\r
- """Sets the module's error statistic back to zero."""\r
- self.error_count = 0\r
- self.errors_by_category = {}\r
-\r
- def IncrementErrorCount(self, category):\r
- """Bumps the module's error statistic."""\r
- self.error_count += 1\r
- if self.counting in ('toplevel', 'detailed'):\r
- if self.counting != 'detailed':\r
- category = category.split('/')[0]\r
- if category not in self.errors_by_category:\r
- self.errors_by_category[category] = 0\r
- self.errors_by_category[category] += 1\r
-\r
- def PrintErrorCounts(self):\r
- """Print a summary of errors by category, and the total."""\r
- for category, count in self.errors_by_category.iteritems():\r
- sys.stderr.write('Category \'%s\' errors found: %d\n' %\r
- (category, count))\r
- sys.stdout.write('Total errors found: %d\n' % self.error_count)\r
-\r
-_cpplint_state = _CppLintState()\r
-\r
-\r
-def _OutputFormat():\r
- """Gets the module's output format."""\r
- return _cpplint_state.output_format\r
-\r
-\r
-def _SetOutputFormat(output_format):\r
- """Sets the module's output format."""\r
- _cpplint_state.SetOutputFormat(output_format)\r
-\r
-\r
-def _VerboseLevel():\r
- """Returns the module's verbosity setting."""\r
- return _cpplint_state.verbose_level\r
-\r
-\r
-def _SetVerboseLevel(level):\r
- """Sets the module's verbosity, and returns the previous setting."""\r
- return _cpplint_state.SetVerboseLevel(level)\r
-\r
-\r
-def _SetCountingStyle(level):\r
- """Sets the module's counting options."""\r
- _cpplint_state.SetCountingStyle(level)\r
-\r
-\r
-def _Filters():\r
- """Returns the module's list of output filters, as a list."""\r
- return _cpplint_state.filters\r
-\r
-\r
-def _SetFilters(filters):\r
- """Sets the module's error-message filters.\r
-\r
- These filters are applied when deciding whether to emit a given\r
- error message.\r
-\r
- Args:\r
- filters: A string of comma-separated filters (eg "whitespace/indent").\r
- Each filter should start with + or -; else we die.\r
- """\r
- _cpplint_state.SetFilters(filters)\r
-\r
-def _AddFilters(filters):\r
- """Adds more filter overrides.\r
-\r
- Unlike _SetFilters, this function does not reset the current list of filters\r
- available.\r
-\r
- Args:\r
- filters: A string of comma-separated filters (eg "whitespace/indent").\r
- Each filter should start with + or -; else we die.\r
- """\r
- _cpplint_state.AddFilters(filters)\r
-\r
-def _BackupFilters():\r
- """ Saves the current filter list to backup storage."""\r
- _cpplint_state.BackupFilters()\r
-\r
-def _RestoreFilters():\r
- """ Restores filters previously backed up."""\r
- _cpplint_state.RestoreFilters()\r
-\r
-class _FunctionState(object):\r
- """Tracks current function name and the number of lines in its body."""\r
-\r
- _NORMAL_TRIGGER = 250 # for --v=0, 500 for --v=1, etc.\r
- _TEST_TRIGGER = 400 # about 50% more than _NORMAL_TRIGGER.\r
-\r
- def __init__(self):\r
- self.in_a_function = False\r
- self.lines_in_function = 0\r
- self.current_function = ''\r
-\r
- def Begin(self, function_name):\r
- """Start analyzing function body.\r
-\r
- Args:\r
- function_name: The name of the function being tracked.\r
- """\r
- self.in_a_function = True\r
- self.lines_in_function = 0\r
- self.current_function = function_name\r
-\r
- def Count(self):\r
- """Count line in current function body."""\r
- if self.in_a_function:\r
- self.lines_in_function += 1\r
-\r
- def Check(self, error, filename, linenum):\r
- """Report if too many lines in function body.\r
-\r
- Args:\r
- error: The function to call with any errors found.\r
- filename: The name of the current file.\r
- linenum: The number of the line to check.\r
- """\r
- if not self.in_a_function:\r
- return\r
-\r
- if Match(r'T(EST|est)', self.current_function):\r
- base_trigger = self._TEST_TRIGGER\r
- else:\r
- base_trigger = self._NORMAL_TRIGGER\r
- trigger = base_trigger * 2**_VerboseLevel()\r
-\r
- if self.lines_in_function > trigger:\r
- error_level = int(math.log(self.lines_in_function / base_trigger, 2))\r
- # 50 => 0, 100 => 1, 200 => 2, 400 => 3, 800 => 4, 1600 => 5, ...\r
- if error_level > 5:\r
- error_level = 5\r
- error(filename, linenum, 'readability/fn_size', error_level,\r
- 'Small and focused functions are preferred:'\r
- ' %s has %d non-comment lines'\r
- ' (error triggered by exceeding %d lines).' % (\r
- self.current_function, self.lines_in_function, trigger))\r
-\r
- def End(self):\r
- """Stop analyzing function body."""\r
- self.in_a_function = False\r
-\r
-\r
-class _IncludeError(Exception):\r
- """Indicates a problem with the include order in a file."""\r
- pass\r
-\r
-\r
-class FileInfo(object):\r
- """Provides utility functions for filenames.\r
-\r
- FileInfo provides easy access to the components of a file's path\r
- relative to the project root.\r
- """\r
-\r
- def __init__(self, filename):\r
- self._filename = filename\r
-\r
- def FullName(self):\r
- """Make Windows paths like Unix."""\r
- return os.path.abspath(self._filename).replace('\\', '/')\r
-\r
- def RepositoryName(self):\r
- """FullName after removing the local path to the repository.\r
-\r
- If we have a real absolute path name here we can try to do something smart:\r
- detecting the root of the checkout and truncating /path/to/checkout from\r
- the name so that we get header guards that don't include things like\r
- "C:\Documents and Settings\..." or "/home/username/..." in them and thus\r
- people on different computers who have checked the source out to different\r
- locations won't see bogus errors.\r
- """\r
- fullname = self.FullName()\r
-\r
- if os.path.exists(fullname):\r
- project_dir = os.path.dirname(fullname)\r
-\r
- if os.path.exists(os.path.join(project_dir, ".svn")):\r
- # If there's a .svn file in the current directory, we recursively look\r
- # up the directory tree for the top of the SVN checkout\r
- root_dir = project_dir\r
- one_up_dir = os.path.dirname(root_dir)\r
- while os.path.exists(os.path.join(one_up_dir, ".svn")):\r
- root_dir = os.path.dirname(root_dir)\r
- one_up_dir = os.path.dirname(one_up_dir)\r
-\r
- prefix = os.path.commonprefix([root_dir, project_dir])\r
- return fullname[len(prefix) + 1:]\r
-\r
- # Not SVN <= 1.6? Try to find a git, hg, or svn top level directory by\r
- # searching up from the current path.\r
- root_dir = current_dir = os.path.dirname(fullname)\r
- while current_dir != os.path.dirname(current_dir):\r
- if (os.path.exists(os.path.join(current_dir, ".git")) or\r
- os.path.exists(os.path.join(current_dir, ".hg")) or\r
- os.path.exists(os.path.join(current_dir, ".svn"))):\r
- root_dir = current_dir\r
- current_dir = os.path.dirname(current_dir)\r
-\r
- if (os.path.exists(os.path.join(root_dir, ".git")) or\r
- os.path.exists(os.path.join(root_dir, ".hg")) or\r
- os.path.exists(os.path.join(root_dir, ".svn"))):\r
- prefix = os.path.commonprefix([root_dir, project_dir])\r
- return fullname[len(prefix) + 1:]\r
-\r
- # Don't know what to do; header guard warnings may be wrong...\r
- return fullname\r
-\r
- def Split(self):\r
- """Splits the file into the directory, basename, and extension.\r
-\r
- For 'chrome/browser/browser.cc', Split() would\r
- return ('chrome/browser', 'browser', '.cc')\r
-\r
- Returns:\r
- A tuple of (directory, basename, extension).\r
- """\r
-\r
- googlename = self.RepositoryName()\r
- project, rest = os.path.split(googlename)\r
- return (project,) + os.path.splitext(rest)\r
-\r
- def BaseName(self):\r
- """File base name - text after the final slash, before the final period."""\r
- return self.Split()[1]\r
-\r
- def Extension(self):\r
- """File extension - text following the final period."""\r
- return self.Split()[2]\r
-\r
- def NoExtension(self):\r
- """File has no source file extension."""\r
- return '/'.join(self.Split()[0:2])\r
-\r
- def IsSource(self):\r
- """File has a source file extension."""\r
- return _IsSourceExtension(self.Extension()[1:])\r
-\r
-\r
-def _ShouldPrintError(category, confidence, linenum):\r
- """If confidence >= verbose, category passes filter and is not suppressed."""\r
-\r
- # There are three ways we might decide not to print an error message:\r
- # a "NOLINT(category)" comment appears in the source,\r
- # the verbosity level isn't high enough, or the filters filter it out.\r
- if IsErrorSuppressedByNolint(category, linenum):\r
- return False\r
-\r
- if confidence < _cpplint_state.verbose_level:\r
- return False\r
-\r
- is_filtered = False\r
- for one_filter in _Filters():\r
- if one_filter.startswith('-'):\r
- if category.startswith(one_filter[1:]):\r
- is_filtered = True\r
- elif one_filter.startswith('+'):\r
- if category.startswith(one_filter[1:]):\r
- is_filtered = False\r
- else:\r
- assert False # should have been checked for in SetFilter.\r
- if is_filtered:\r
- return False\r
-\r
- return True\r
-\r
-\r
-def Error(filename, linenum, category, confidence, message):\r
- """Logs the fact we've found a lint error.\r
-\r
- We log where the error was found, and also our confidence in the error,\r
- that is, how certain we are this is a legitimate style regression, and\r
- not a misidentification or a use that's sometimes justified.\r
-\r
- False positives can be suppressed by the use of\r
- "cpplint(category)" comments on the offending line. These are\r
- parsed into _error_suppressions.\r
-\r
- Args:\r
- filename: The name of the file containing the error.\r
- linenum: The number of the line containing the error.\r
- category: A string used to describe the "category" this bug\r
- falls under: "whitespace", say, or "runtime". Categories\r
- may have a hierarchy separated by slashes: "whitespace/indent".\r
- confidence: A number from 1-5 representing a confidence score for\r
- the error, with 5 meaning that we are certain of the problem,\r
- and 1 meaning that it could be a legitimate construct.\r
- message: The error message.\r
- """\r
- if _ShouldPrintError(category, confidence, linenum):\r
- _cpplint_state.IncrementErrorCount(category)\r
- if _cpplint_state.output_format == 'vs7':\r
- sys.stderr.write('%s(%s): error cpplint: [%s] %s [%d]\n' % (\r
- filename, linenum, category, message, confidence))\r
- elif _cpplint_state.output_format == 'eclipse':\r
- sys.stderr.write('%s:%s: warning: %s [%s] [%d]\n' % (\r
- filename, linenum, message, category, confidence))\r
- else:\r
- sys.stderr.write('%s:%s: %s [%s] [%d]\n' % (\r
- filename, linenum, message, category, confidence))\r
-\r
-\r
-# Matches standard C++ escape sequences per 2.13.2.3 of the C++ standard.\r
-_RE_PATTERN_CLEANSE_LINE_ESCAPES = re.compile(\r
- r'\\([abfnrtv?"\\\']|\d+|x[0-9a-fA-F]+)')\r
-# Match a single C style comment on the same line.\r
-_RE_PATTERN_C_COMMENTS = r'/\*(?:[^*]|\*(?!/))*\*/'\r
-# Matches multi-line C style comments.\r
-# This RE is a little bit more complicated than one might expect, because we\r
-# have to take care of space removals tools so we can handle comments inside\r
-# statements better.\r
-# The current rule is: We only clear spaces from both sides when we're at the\r
-# end of the line. Otherwise, we try to remove spaces from the right side,\r
-# if this doesn't work we try on left side but only if there's a non-character\r
-# on the right.\r
-_RE_PATTERN_CLEANSE_LINE_C_COMMENTS = re.compile(\r
- r'(\s*' + _RE_PATTERN_C_COMMENTS + r'\s*$|' +\r
- _RE_PATTERN_C_COMMENTS + r'\s+|' +\r
- r'\s+' + _RE_PATTERN_C_COMMENTS + r'(?=\W)|' +\r
- _RE_PATTERN_C_COMMENTS + r')')\r
-\r
-\r
-def IsCppString(line):\r
- """Does line terminate so, that the next symbol is in string constant.\r
-\r
- This function does not consider single-line nor multi-line comments.\r
-\r
- Args:\r
- line: is a partial line of code starting from the 0..n.\r
-\r
- Returns:\r
- True, if next character appended to 'line' is inside a\r
- string constant.\r
- """\r
-\r
- line = line.replace(r'\\', 'XX') # after this, \\" does not match to \"\r
- return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1\r
-\r
-\r
-def CleanseRawStrings(raw_lines):\r
- """Removes C++11 raw strings from lines.\r
-\r
- Before:\r
- static const char kData[] = R"(\r
- multi-line string\r
- )";\r
-\r
- After:\r
- static const char kData[] = ""\r
- (replaced by blank line)\r
- "";\r
-\r
- Args:\r
- raw_lines: list of raw lines.\r
-\r
- Returns:\r
- list of lines with C++11 raw strings replaced by empty strings.\r
- """\r
-\r
- delimiter = None\r
- lines_without_raw_strings = []\r
- for line in raw_lines:\r
- if delimiter:\r
- # Inside a raw string, look for the end\r
- end = line.find(delimiter)\r
- if end >= 0:\r
- # Found the end of the string, match leading space for this\r
- # line and resume copying the original lines, and also insert\r
- # a "" on the last line.\r
- leading_space = Match(r'^(\s*)\S', line)\r
- line = leading_space.group(1) + '""' + line[end + len(delimiter):]\r
- delimiter = None\r
- else:\r
- # Haven't found the end yet, append a blank line.\r
- line = '""'\r
-\r
- # Look for beginning of a raw string, and replace them with\r
- # empty strings. This is done in a loop to handle multiple raw\r
- # strings on the same line.\r
- while delimiter is None:\r
- # Look for beginning of a raw string.\r
- # See 2.14.15 [lex.string] for syntax.\r
- #\r
- # Once we have matched a raw string, we check the prefix of the\r
- # line to make sure that the line is not part of a single line\r
- # comment. It's done this way because we remove raw strings\r
- # before removing comments as opposed to removing comments\r
- # before removing raw strings. This is because there are some\r
- # cpplint checks that requires the comments to be preserved, but\r
- # we don't want to check comments that are inside raw strings.\r
- matched = Match(r'^(.*?)\b(?:R|u8R|uR|UR|LR)"([^\s\\()]*)\((.*)$', line)\r
- if (matched and\r
- not Match(r'^([^\'"]|\'(\\.|[^\'])*\'|"(\\.|[^"])*")*//',\r
- matched.group(1))):\r
- delimiter = ')' + matched.group(2) + '"'\r
-\r
- end = matched.group(3).find(delimiter)\r
- if end >= 0:\r
- # Raw string ended on same line\r
- line = (matched.group(1) + '""' +\r
- matched.group(3)[end + len(delimiter):])\r
- delimiter = None\r
- else:\r
- # Start of a multi-line raw string\r
- line = matched.group(1) + '""'\r
- else:\r
- break\r
-\r
- lines_without_raw_strings.append(line)\r
-\r
- # TODO(unknown): if delimiter is not None here, we might want to\r
- # emit a warning for unterminated string.\r
- return lines_without_raw_strings\r
-\r
-\r
-def FindNextMultiLineCommentStart(lines, lineix):\r
- """Find the beginning marker for a multiline comment."""\r
- while lineix < len(lines):\r
- if lines[lineix].strip().startswith('/*'):\r
- # Only return this marker if the comment goes beyond this line\r
- if lines[lineix].strip().find('*/', 2) < 0:\r
- return lineix\r
- lineix += 1\r
- return len(lines)\r
-\r
-\r
-def FindNextMultiLineCommentEnd(lines, lineix):\r
- """We are inside a comment, find the end marker."""\r
- while lineix < len(lines):\r
- if lines[lineix].strip().endswith('*/'):\r
- return lineix\r
- lineix += 1\r
- return len(lines)\r
-\r
-\r
-def RemoveMultiLineCommentsFromRange(lines, begin, end):\r
- """Clears a range of lines for multi-line comments."""\r
- # Having // dummy comments makes the lines non-empty, so we will not get\r
- # unnecessary blank line warnings later in the code.\r
- for i in range(begin, end):\r
- lines[i] = '/**/'\r
-\r
-\r
-def RemoveMultiLineComments(filename, lines, error):\r
- """Removes multiline (c-style) comments from lines."""\r
- lineix = 0\r
- while lineix < len(lines):\r
- lineix_begin = FindNextMultiLineCommentStart(lines, lineix)\r
- if lineix_begin >= len(lines):\r
- return\r
- lineix_end = FindNextMultiLineCommentEnd(lines, lineix_begin)\r
- if lineix_end >= len(lines):\r
- error(filename, lineix_begin + 1, 'readability/multiline_comment', 5,\r
- 'Could not find end of multi-line comment')\r
- return\r
- RemoveMultiLineCommentsFromRange(lines, lineix_begin, lineix_end + 1)\r
- lineix = lineix_end + 1\r
-\r
-\r
-def CleanseComments(line):\r
- """Removes //-comments and single-line C-style /* */ comments.\r
-\r
- Args:\r
- line: A line of C++ source.\r
-\r
- Returns:\r
- The line with single-line comments removed.\r
- """\r
- commentpos = line.find('//')\r
- if commentpos != -1 and not IsCppString(line[:commentpos]):\r
- line = line[:commentpos].rstrip()\r
- # get rid of /* ... */\r
- return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line)\r
-\r
-\r
-class CleansedLines(object):\r
- """Holds 4 copies of all lines with different preprocessing applied to them.\r
-\r
- 1) elided member contains lines without strings and comments.\r
- 2) lines member contains lines without comments.\r
- 3) raw_lines member contains all the lines without processing.\r
- 4) lines_without_raw_strings member is same as raw_lines, but with C++11 raw\r
- strings removed.\r
- All these members are of <type 'list'>, and of the same length.\r
- """\r
-\r
- def __init__(self, lines):\r
- self.elided = []\r
- self.lines = []\r
- self.raw_lines = lines\r
- self.num_lines = len(lines)\r
- self.lines_without_raw_strings = CleanseRawStrings(lines)\r
- for linenum in range(len(self.lines_without_raw_strings)):\r
- self.lines.append(CleanseComments(\r
- self.lines_without_raw_strings[linenum]))\r
- elided = self._CollapseStrings(self.lines_without_raw_strings[linenum])\r
- self.elided.append(CleanseComments(elided))\r
-\r
- def NumLines(self):\r
- """Returns the number of lines represented."""\r
- return self.num_lines\r
-\r
- @staticmethod\r
- def _CollapseStrings(elided):\r
- """Collapses strings and chars on a line to simple "" or '' blocks.\r
-\r
- We nix strings first so we're not fooled by text like '"http://"'\r
-\r
- Args:\r
- elided: The line being processed.\r
-\r
- Returns:\r
- The line with collapsed strings.\r
- """\r
- if _RE_PATTERN_INCLUDE.match(elided):\r
- return elided\r
-\r
- # Remove escaped characters first to make quote/single quote collapsing\r
- # basic. Things that look like escaped characters shouldn't occur\r
- # outside of strings and chars.\r
- elided = _RE_PATTERN_CLEANSE_LINE_ESCAPES.sub('', elided)\r
-\r
- # Replace quoted strings and digit separators. Both single quotes\r
- # and double quotes are processed in the same loop, otherwise\r
- # nested quotes wouldn't work.\r
- collapsed = ''\r
- while True:\r
- # Find the first quote character\r
- match = Match(r'^([^\'"]*)([\'"])(.*)$', elided)\r
- if not match:\r
- collapsed += elided\r
- break\r
- head, quote, tail = match.groups()\r
-\r
- if quote == '"':\r
- # Collapse double quoted strings\r
- second_quote = tail.find('"')\r
- if second_quote >= 0:\r
- collapsed += head + '""'\r
- elided = tail[second_quote + 1:]\r
- else:\r
- # Unmatched double quote, don't bother processing the rest\r
- # of the line since this is probably a multiline string.\r
- collapsed += elided\r
- break\r
- else:\r
- # Found single quote, check nearby text to eliminate digit separators.\r
- #\r
- # There is no special handling for floating point here, because\r
- # the integer/fractional/exponent parts would all be parsed\r
- # correctly as long as there are digits on both sides of the\r
- # separator. So we are fine as long as we don't see something\r
- # like "0.'3" (gcc 4.9.0 will not allow this literal).\r
- if Search(r'\b(?:0[bBxX]?|[1-9])[0-9a-fA-F]*$', head):\r
- match_literal = Match(r'^((?:\'?[0-9a-zA-Z_])*)(.*)$', "'" + tail)\r
- collapsed += head + match_literal.group(1).replace("'", '')\r
- elided = match_literal.group(2)\r
- else:\r
- second_quote = tail.find('\'')\r
- if second_quote >= 0:\r
- collapsed += head + "''"\r
- elided = tail[second_quote + 1:]\r
- else:\r
- # Unmatched single quote\r
- collapsed += elided\r
- break\r
-\r
- return collapsed\r
-\r
-\r
-def FindEndOfExpressionInLine(line, startpos, stack):\r
- """Find the position just after the end of current parenthesized expression.\r
-\r
- Args:\r
- line: a CleansedLines line.\r
- startpos: start searching at this position.\r
- stack: nesting stack at startpos.\r
-\r
- Returns:\r
- On finding matching end: (index just after matching end, None)\r
- On finding an unclosed expression: (-1, None)\r
- Otherwise: (-1, new stack at end of this line)\r
- """\r
- for i in xrange(startpos, len(line)):\r
- char = line[i]\r
- if char in '([{':\r
- # Found start of parenthesized expression, push to expression stack\r
- stack.append(char)\r
- elif char == '<':\r
- # Found potential start of template argument list\r
- if i > 0 and line[i - 1] == '<':\r
- # Left shift operator\r
- if stack and stack[-1] == '<':\r
- stack.pop()\r
- if not stack:\r
- return (-1, None)\r
- elif i > 0 and Search(r'\boperator\s*$', line[0:i]):\r
- # operator<, don't add to stack\r
- continue\r
- else:\r
- # Tentative start of template argument list\r
- stack.append('<')\r
- elif char in ')]}':\r
- # Found end of parenthesized expression.\r
- #\r
- # If we are currently expecting a matching '>', the pending '<'\r
- # must have been an operator. Remove them from expression stack.\r
- while stack and stack[-1] == '<':\r
- stack.pop()\r
- if not stack:\r
- return (-1, None)\r
- if ((stack[-1] == '(' and char == ')') or\r
- (stack[-1] == '[' and char == ']') or\r
- (stack[-1] == '{' and char == '}')):\r
- stack.pop()\r
- if not stack:\r
- return (i + 1, None)\r
- else:\r
- # Mismatched parentheses\r
- return (-1, None)\r
- elif char == '>':\r
- # Found potential end of template argument list.\r
-\r
- # Ignore "->" and operator functions\r
- if (i > 0 and\r
- (line[i - 1] == '-' or Search(r'\boperator\s*$', line[0:i - 1]))):\r
- continue\r
-\r
- # Pop the stack if there is a matching '<'. Otherwise, ignore\r
- # this '>' since it must be an operator.\r
- if stack:\r
- if stack[-1] == '<':\r
- stack.pop()\r
- if not stack:\r
- return (i + 1, None)\r
- elif char == ';':\r
- # Found something that look like end of statements. If we are currently\r
- # expecting a '>', the matching '<' must have been an operator, since\r
- # template argument list should not contain statements.\r
- while stack and stack[-1] == '<':\r
- stack.pop()\r
- if not stack:\r
- return (-1, None)\r
-\r
- # Did not find end of expression or unbalanced parentheses on this line\r
- return (-1, stack)\r
-\r
-\r
-def CloseExpression(clean_lines, linenum, pos):\r
- """If input points to ( or { or [ or <, finds the position that closes it.\r
-\r
- If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the\r
- linenum/pos that correspond to the closing of the expression.\r
-\r
- TODO(unknown): cpplint spends a fair bit of time matching parentheses.\r
- Ideally we would want to index all opening and closing parentheses once\r
- and have CloseExpression be just a simple lookup, but due to preprocessor\r
- tricks, this is not so easy.\r
-\r
- Args:\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- pos: A position on the line.\r
-\r
- Returns:\r
- A tuple (line, linenum, pos) pointer *past* the closing brace, or\r
- (line, len(lines), -1) if we never find a close. Note we ignore\r
- strings and comments when matching; and the line we return is the\r
- 'cleansed' line at linenum.\r
- """\r
-\r
- line = clean_lines.elided[linenum]\r
- if (line[pos] not in '({[<') or Match(r'<[<=]', line[pos:]):\r
- return (line, clean_lines.NumLines(), -1)\r
-\r
- # Check first line\r
- (end_pos, stack) = FindEndOfExpressionInLine(line, pos, [])\r
- if end_pos > -1:\r
- return (line, linenum, end_pos)\r
-\r
- # Continue scanning forward\r
- while stack and linenum < clean_lines.NumLines() - 1:\r
- linenum += 1\r
- line = clean_lines.elided[linenum]\r
- (end_pos, stack) = FindEndOfExpressionInLine(line, 0, stack)\r
- if end_pos > -1:\r
- return (line, linenum, end_pos)\r
-\r
- # Did not find end of expression before end of file, give up\r
- return (line, clean_lines.NumLines(), -1)\r
-\r
-\r
-def FindStartOfExpressionInLine(line, endpos, stack):\r
- """Find position at the matching start of current expression.\r
-\r
- This is almost the reverse of FindEndOfExpressionInLine, but note\r
- that the input position and returned position differs by 1.\r
-\r
- Args:\r
- line: a CleansedLines line.\r
- endpos: start searching at this position.\r
- stack: nesting stack at endpos.\r
-\r
- Returns:\r
- On finding matching start: (index at matching start, None)\r
- On finding an unclosed expression: (-1, None)\r
- Otherwise: (-1, new stack at beginning of this line)\r
- """\r
- i = endpos\r
- while i >= 0:\r
- char = line[i]\r
- if char in ')]}':\r
- # Found end of expression, push to expression stack\r
- stack.append(char)\r
- elif char == '>':\r
- # Found potential end of template argument list.\r
- #\r
- # Ignore it if it's a "->" or ">=" or "operator>"\r
- if (i > 0 and\r
- (line[i - 1] == '-' or\r
- Match(r'\s>=\s', line[i - 1:]) or\r
- Search(r'\boperator\s*$', line[0:i]))):\r
- i -= 1\r
- else:\r
- stack.append('>')\r
- elif char == '<':\r
- # Found potential start of template argument list\r
- if i > 0 and line[i - 1] == '<':\r
- # Left shift operator\r
- i -= 1\r
- else:\r
- # If there is a matching '>', we can pop the expression stack.\r
- # Otherwise, ignore this '<' since it must be an operator.\r
- if stack and stack[-1] == '>':\r
- stack.pop()\r
- if not stack:\r
- return (i, None)\r
- elif char in '([{':\r
- # Found start of expression.\r
- #\r
- # If there are any unmatched '>' on the stack, they must be\r
- # operators. Remove those.\r
- while stack and stack[-1] == '>':\r
- stack.pop()\r
- if not stack:\r
- return (-1, None)\r
- if ((char == '(' and stack[-1] == ')') or\r
- (char == '[' and stack[-1] == ']') or\r
- (char == '{' and stack[-1] == '}')):\r
- stack.pop()\r
- if not stack:\r
- return (i, None)\r
- else:\r
- # Mismatched parentheses\r
- return (-1, None)\r
- elif char == ';':\r
- # Found something that look like end of statements. If we are currently\r
- # expecting a '<', the matching '>' must have been an operator, since\r
- # template argument list should not contain statements.\r
- while stack and stack[-1] == '>':\r
- stack.pop()\r
- if not stack:\r
- return (-1, None)\r
-\r
- i -= 1\r
-\r
- return (-1, stack)\r
-\r
-\r
-def ReverseCloseExpression(clean_lines, linenum, pos):\r
- """If input points to ) or } or ] or >, finds the position that opens it.\r
-\r
- If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the\r
- linenum/pos that correspond to the opening of the expression.\r
-\r
- Args:\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- pos: A position on the line.\r
-\r
- Returns:\r
- A tuple (line, linenum, pos) pointer *at* the opening brace, or\r
- (line, 0, -1) if we never find the matching opening brace. Note\r
- we ignore strings and comments when matching; and the line we\r
- return is the 'cleansed' line at linenum.\r
- """\r
- line = clean_lines.elided[linenum]\r
- if line[pos] not in ')}]>':\r
- return (line, 0, -1)\r
-\r
- # Check last line\r
- (start_pos, stack) = FindStartOfExpressionInLine(line, pos, [])\r
- if start_pos > -1:\r
- return (line, linenum, start_pos)\r
-\r
- # Continue scanning backward\r
- while stack and linenum > 0:\r
- linenum -= 1\r
- line = clean_lines.elided[linenum]\r
- (start_pos, stack) = FindStartOfExpressionInLine(line, len(line) - 1, stack)\r
- if start_pos > -1:\r
- return (line, linenum, start_pos)\r
-\r
- # Did not find start of expression before beginning of file, give up\r
- return (line, 0, -1)\r
-\r
-\r
-def CheckForCopyright(filename, lines, error):\r
- """Logs an error if no Copyright message appears at the top of the file."""\r
-\r
- # We'll say it should occur by line 10. Don't forget there's a\r
- # dummy line at the front.\r
- for line in xrange(1, min(len(lines), 11)):\r
- if re.search(r'Copyright', lines[line], re.I): break\r
- else: # means no copyright line was found\r
- error(filename, 0, 'legal/copyright', 5,\r
- 'No copyright message found. '\r
- 'You should have a line: "Copyright [year] <Copyright Owner>"')\r
-\r
-\r
-def GetIndentLevel(line):\r
- """Return the number of leading spaces in line.\r
-\r
- Args:\r
- line: A string to check.\r
-\r
- Returns:\r
- An integer count of leading spaces, possibly zero.\r
- """\r
- indent = Match(r'^( *)\S', line)\r
- if indent:\r
- return len(indent.group(1))\r
- else:\r
- return 0\r
-\r
-\r
-def GetHeaderGuardCPPVariable(filename):\r
- """Returns the CPP variable that should be used as a header guard.\r
-\r
- Args:\r
- filename: The name of a C++ header file.\r
-\r
- Returns:\r
- The CPP variable that should be used as a header guard in the\r
- named file.\r
-\r
- """\r
-\r
- # Restores original filename in case that cpplint is invoked from Emacs's\r
- # flymake.\r
- filename = re.sub(r'_flymake\.h$', '.h', filename)\r
- filename = re.sub(r'/\.flymake/([^/]*)$', r'/\1', filename)\r
- # Replace 'c++' with 'cpp'.\r
- filename = filename.replace('C++', 'cpp').replace('c++', 'cpp')\r
-\r
- fileinfo = FileInfo(filename)\r
- file_path_from_root = fileinfo.RepositoryName()\r
- if _root:\r
- suffix = os.sep\r
- # On Windows using directory separator will leave us with\r
- # "bogus escape error" unless we properly escape regex.\r
- if suffix == '\\':\r
- suffix += '\\'\r
- file_path_from_root = re.sub('^' + _root + suffix, '', file_path_from_root)\r
- return re.sub(r'[^a-zA-Z0-9]', '_', file_path_from_root).upper() + '_'\r
-\r
-\r
-def CheckForHeaderGuard(filename, clean_lines, error):\r
- """Checks that the file contains a header guard.\r
-\r
- Logs an error if no #ifndef header guard is present. For other\r
- headers, checks that the full pathname is used.\r
-\r
- Args:\r
- filename: The name of the C++ header file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- error: The function to call with any errors found.\r
- """\r
-\r
- # Don't check for header guards if there are error suppression\r
- # comments somewhere in this file.\r
- #\r
- # Because this is silencing a warning for a nonexistent line, we\r
- # only support the very specific NOLINT(build/header_guard) syntax,\r
- # and not the general NOLINT or NOLINT(*) syntax.\r
- raw_lines = clean_lines.lines_without_raw_strings\r
- for i in raw_lines:\r
- if Search(r'//\s*NOLINT\(build/header_guard\)', i):\r
- return\r
-\r
- cppvar = GetHeaderGuardCPPVariable(filename)\r
-\r
- ifndef = ''\r
- ifndef_linenum = 0\r
- define = ''\r
- endif = ''\r
- endif_linenum = 0\r
- for linenum, line in enumerate(raw_lines):\r
- linesplit = line.split()\r
- if len(linesplit) >= 2:\r
- # find the first occurrence of #ifndef and #define, save arg\r
- if not ifndef and linesplit[0] == '#ifndef':\r
- # set ifndef to the header guard presented on the #ifndef line.\r
- ifndef = linesplit[1]\r
- ifndef_linenum = linenum\r
- if not define and linesplit[0] == '#define':\r
- define = linesplit[1]\r
- # find the last occurrence of #endif, save entire line\r
- if line.startswith('#endif'):\r
- endif = line\r
- endif_linenum = linenum\r
-\r
- if not ifndef or not define or ifndef != define:\r
- error(filename, 0, 'build/header_guard', 5,\r
- 'No #ifndef header guard found, suggested CPP variable is: %s' %\r
- cppvar)\r
- return\r
-\r
- # The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__\r
- # for backward compatibility.\r
- if ifndef != cppvar:\r
- error_level = 0\r
- if ifndef != cppvar + '_':\r
- error_level = 5\r
-\r
- ParseNolintSuppressions(filename, raw_lines[ifndef_linenum], ifndef_linenum,\r
- error)\r
- error(filename, ifndef_linenum, 'build/header_guard', error_level,\r
- '#ifndef header guard has wrong style, please use: %s' % cppvar)\r
-\r
- # Check for "//" comments on endif line.\r
- ParseNolintSuppressions(filename, raw_lines[endif_linenum], endif_linenum,\r
- error)\r
- match = Match(r'#endif\s*//\s*' + cppvar + r'(_)?\b', endif)\r
- if match:\r
- if match.group(1) == '_':\r
- # Issue low severity warning for deprecated double trailing underscore\r
- error(filename, endif_linenum, 'build/header_guard', 0,\r
- '#endif line should be "#endif // %s"' % cppvar)\r
- return\r
-\r
- # Didn't find the corresponding "//" comment. If this file does not\r
- # contain any "//" comments at all, it could be that the compiler\r
- # only wants "/**/" comments, look for those instead.\r
- no_single_line_comments = True\r
- for i in xrange(1, len(raw_lines) - 1):\r
- line = raw_lines[i]\r
- if Match(r'^(?:(?:\'(?:\.|[^\'])*\')|(?:"(?:\.|[^"])*")|[^\'"])*//', line):\r
- no_single_line_comments = False\r
- break\r
-\r
- if no_single_line_comments:\r
- match = Match(r'#endif\s*/\*\s*' + cppvar + r'(_)?\s*\*/', endif)\r
- if match:\r
- if match.group(1) == '_':\r
- # Low severity warning for double trailing underscore\r
- error(filename, endif_linenum, 'build/header_guard', 0,\r
- '#endif line should be "#endif /* %s */"' % cppvar)\r
- return\r
-\r
- # Didn't find anything\r
- error(filename, endif_linenum, 'build/header_guard', 5,\r
- '#endif line should be "#endif // %s"' % cppvar)\r
-\r
-\r
-def CheckHeaderFileIncluded(filename, include_state, error):\r
- """Logs an error if a .cc file does not include its header."""\r
-\r
- # Do not check test files\r
- fileinfo = FileInfo(filename)\r
- if Search(_TEST_FILE_SUFFIX, fileinfo.BaseName()):\r
- return\r
-\r
- headerfile = filename[0:len(filename) - len(fileinfo.Extension())] + '.h'\r
- if not os.path.exists(headerfile):\r
- return\r
- headername = FileInfo(headerfile).RepositoryName()\r
- first_include = 0\r
- for section_list in include_state.include_list:\r
- for f in section_list:\r
- if headername in f[0] or f[0] in headername:\r
- return\r
- if not first_include:\r
- first_include = f[1]\r
-\r
- error(filename, first_include, 'build/include', 5,\r
- '%s should include its header file %s' % (fileinfo.RepositoryName(),\r
- headername))\r
-\r
-\r
-def CheckForBadCharacters(filename, lines, error):\r
- """Logs an error for each line containing bad characters.\r
-\r
- Two kinds of bad characters:\r
-\r
- 1. Unicode replacement characters: These indicate that either the file\r
- contained invalid UTF-8 (likely) or Unicode replacement characters (which\r
- it shouldn't). Note that it's possible for this to throw off line\r
- numbering if the invalid UTF-8 occurred adjacent to a newline.\r
-\r
- 2. NUL bytes. These are problematic for some tools.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- lines: An array of strings, each representing a line of the file.\r
- error: The function to call with any errors found.\r
- """\r
- for linenum, line in enumerate(lines):\r
- if u'\ufffd' in line:\r
- error(filename, linenum, 'readability/utf8', 5,\r
- 'Line contains invalid UTF-8 (or Unicode replacement character).')\r
- if '\0' in line:\r
- error(filename, linenum, 'readability/nul', 5, 'Line contains NUL byte.')\r
-\r
-\r
-def CheckForNewlineAtEOF(filename, lines, error):\r
- """Logs an error if there is no newline char at the end of the file.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- lines: An array of strings, each representing a line of the file.\r
- error: The function to call with any errors found.\r
- """\r
-\r
- # The array lines() was created by adding two newlines to the\r
- # original file (go figure), then splitting on \n.\r
- # To verify that the file ends in \n, we just have to make sure the\r
- # last-but-two element of lines() exists and is empty.\r
- if len(lines) < 3 or lines[-2]:\r
- error(filename, len(lines) - 2, 'whitespace/ending_newline', 5,\r
- 'Could not find a newline character at the end of the file.')\r
-\r
-\r
-def CheckForMultilineCommentsAndStrings(filename, clean_lines, linenum, error):\r
- """Logs an error if we see /* ... */ or "..." that extend past one line.\r
-\r
- /* ... */ comments are legit inside macros, for one line.\r
- Otherwise, we prefer // comments, so it's ok to warn about the\r
- other. Likewise, it's ok for strings to extend across multiple\r
- lines, as long as a line continuation character (backslash)\r
- terminates each line. Although not currently prohibited by the C++\r
- style guide, it's ugly and unnecessary. We don't do well with either\r
- in this lint program, so we warn about both.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- error: The function to call with any errors found.\r
- """\r
- line = clean_lines.elided[linenum]\r
-\r
- # Remove all \\ (escaped backslashes) from the line. They are OK, and the\r
- # second (escaped) slash may trigger later \" detection erroneously.\r
- line = line.replace('\\\\', '')\r
-\r
- if line.count('/*') > line.count('*/'):\r
- error(filename, linenum, 'readability/multiline_comment', 5,\r
- 'Complex multi-line /*...*/-style comment found. '\r
- 'Lint may give bogus warnings. '\r
- 'Consider replacing these with //-style comments, '\r
- 'with #if 0...#endif, '\r
- 'or with more clearly structured multi-line comments.')\r
-\r
- if (line.count('"') - line.count('\\"')) % 2:\r
- error(filename, linenum, 'readability/multiline_string', 5,\r
- 'Multi-line string ("...") found. This lint script doesn\'t '\r
- 'do well with such strings, and may give bogus warnings. '\r
- 'Use C++11 raw strings or concatenation instead.')\r
-\r
-\r
-# (non-threadsafe name, thread-safe alternative, validation pattern)\r
-#\r
-# The validation pattern is used to eliminate false positives such as:\r
-# _rand(); // false positive due to substring match.\r
-# ->rand(); // some member function rand().\r
-# ACMRandom rand(seed); // some variable named rand.\r
-# ISAACRandom rand(); // another variable named rand.\r
-#\r
-# Basically we require the return value of these functions to be used\r
-# in some expression context on the same line by matching on some\r
-# operator before the function name. This eliminates constructors and\r
-# member function calls.\r
-_UNSAFE_FUNC_PREFIX = r'(?:[-+*/=%^&|(<]\s*|>\s+)'\r
-_THREADING_LIST = (\r
- ('asctime(', 'asctime_r(', _UNSAFE_FUNC_PREFIX + r'asctime\([^)]+\)'),\r
- ('ctime(', 'ctime_r(', _UNSAFE_FUNC_PREFIX + r'ctime\([^)]+\)'),\r
- ('getgrgid(', 'getgrgid_r(', _UNSAFE_FUNC_PREFIX + r'getgrgid\([^)]+\)'),\r
- ('getgrnam(', 'getgrnam_r(', _UNSAFE_FUNC_PREFIX + r'getgrnam\([^)]+\)'),\r
- ('getlogin(', 'getlogin_r(', _UNSAFE_FUNC_PREFIX + r'getlogin\(\)'),\r
- ('getpwnam(', 'getpwnam_r(', _UNSAFE_FUNC_PREFIX + r'getpwnam\([^)]+\)'),\r
- ('getpwuid(', 'getpwuid_r(', _UNSAFE_FUNC_PREFIX + r'getpwuid\([^)]+\)'),\r
- ('gmtime(', 'gmtime_r(', _UNSAFE_FUNC_PREFIX + r'gmtime\([^)]+\)'),\r
- ('localtime(', 'localtime_r(', _UNSAFE_FUNC_PREFIX + r'localtime\([^)]+\)'),\r
- ('rand(', 'rand_r(', _UNSAFE_FUNC_PREFIX + r'rand\(\)'),\r
- ('strtok(', 'strtok_r(',\r
- _UNSAFE_FUNC_PREFIX + r'strtok\([^)]+\)'),\r
- ('ttyname(', 'ttyname_r(', _UNSAFE_FUNC_PREFIX + r'ttyname\([^)]+\)'),\r
- )\r
-\r
-\r
-def CheckPosixThreading(filename, clean_lines, linenum, error):\r
- """Checks for calls to thread-unsafe functions.\r
-\r
- Much code has been originally written without consideration of\r
- multi-threading. Also, engineers are relying on their old experience;\r
- they have learned posix before threading extensions were added. These\r
- tests guide the engineers to use thread-safe functions (when using\r
- posix directly).\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- error: The function to call with any errors found.\r
- """\r
- line = clean_lines.elided[linenum]\r
- for single_thread_func, multithread_safe_func, pattern in _THREADING_LIST:\r
- # Additional pattern matching check to confirm that this is the\r
- # function we are looking for\r
- if Search(pattern, line):\r
- error(filename, linenum, 'runtime/threadsafe_fn', 2,\r
- 'Consider using ' + multithread_safe_func +\r
- '...) instead of ' + single_thread_func +\r
- '...) for improved thread safety.')\r
-\r
-\r
-def CheckVlogArguments(filename, clean_lines, linenum, error):\r
- """Checks that VLOG() is only used for defining a logging level.\r
-\r
- For example, VLOG(2) is correct. VLOG(INFO), VLOG(WARNING), VLOG(ERROR), and\r
- VLOG(FATAL) are not.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- error: The function to call with any errors found.\r
- """\r
- line = clean_lines.elided[linenum]\r
- if Search(r'\bVLOG\((INFO|ERROR|WARNING|DFATAL|FATAL)\)', line):\r
- error(filename, linenum, 'runtime/vlog', 5,\r
- 'VLOG() should be used with numeric verbosity level. '\r
- 'Use LOG() if you want symbolic severity levels.')\r
-\r
-# Matches invalid increment: *count++, which moves pointer instead of\r
-# incrementing a value.\r
-_RE_PATTERN_INVALID_INCREMENT = re.compile(\r
- r'^\s*\*\w+(\+\+|--);')\r
-\r
-\r
-def CheckInvalidIncrement(filename, clean_lines, linenum, error):\r
- """Checks for invalid increment *count++.\r
-\r
- For example following function:\r
- void increment_counter(int* count) {\r
- *count++;\r
- }\r
- is invalid, because it effectively does count++, moving pointer, and should\r
- be replaced with ++*count, (*count)++ or *count += 1.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- error: The function to call with any errors found.\r
- """\r
- line = clean_lines.elided[linenum]\r
- if _RE_PATTERN_INVALID_INCREMENT.match(line):\r
- error(filename, linenum, 'runtime/invalid_increment', 5,\r
- 'Changing pointer instead of value (or unused value of operator*).')\r
-\r
-\r
-def IsMacroDefinition(clean_lines, linenum):\r
- if Search(r'^#define', clean_lines[linenum]):\r
- return True\r
-\r
- if linenum > 0 and Search(r'\\$', clean_lines[linenum - 1]):\r
- return True\r
-\r
- return False\r
-\r
-\r
-def IsForwardClassDeclaration(clean_lines, linenum):\r
- return Match(r'^\s*(\btemplate\b)*.*class\s+\w+;\s*$', clean_lines[linenum])\r
-\r
-\r
-class _BlockInfo(object):\r
- """Stores information about a generic block of code."""\r
-\r
- def __init__(self, linenum, seen_open_brace):\r
- self.starting_linenum = linenum\r
- self.seen_open_brace = seen_open_brace\r
- self.open_parentheses = 0\r
- self.inline_asm = _NO_ASM\r
- self.check_namespace_indentation = False\r
-\r
- def CheckBegin(self, filename, clean_lines, linenum, error):\r
- """Run checks that applies to text up to the opening brace.\r
-\r
- This is mostly for checking the text after the class identifier\r
- and the "{", usually where the base class is specified. For other\r
- blocks, there isn't much to check, so we always pass.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- error: The function to call with any errors found.\r
- """\r
- pass\r
-\r
- def CheckEnd(self, filename, clean_lines, linenum, error):\r
- """Run checks that applies to text after the closing brace.\r
-\r
- This is mostly used for checking end of namespace comments.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- error: The function to call with any errors found.\r
- """\r
- pass\r
-\r
- def IsBlockInfo(self):\r
- """Returns true if this block is a _BlockInfo.\r
-\r
- This is convenient for verifying that an object is an instance of\r
- a _BlockInfo, but not an instance of any of the derived classes.\r
-\r
- Returns:\r
- True for this class, False for derived classes.\r
- """\r
- return self.__class__ == _BlockInfo\r
-\r
-\r
-class _ExternCInfo(_BlockInfo):\r
- """Stores information about an 'extern "C"' block."""\r
-\r
- def __init__(self, linenum):\r
- _BlockInfo.__init__(self, linenum, True)\r
-\r
-\r
-class _ClassInfo(_BlockInfo):\r
- """Stores information about a class."""\r
-\r
- def __init__(self, name, class_or_struct, clean_lines, linenum):\r
- _BlockInfo.__init__(self, linenum, False)\r
- self.name = name\r
- self.is_derived = False\r
- self.check_namespace_indentation = True\r
- if class_or_struct == 'struct':\r
- self.access = 'public'\r
- self.is_struct = True\r
- else:\r
- self.access = 'private'\r
- self.is_struct = False\r
-\r
- # Remember initial indentation level for this class. Using raw_lines here\r
- # instead of elided to account for leading comments.\r
- self.class_indent = GetIndentLevel(clean_lines.raw_lines[linenum])\r
-\r
- # Try to find the end of the class. This will be confused by things like:\r
- # class A {\r
- # } *x = { ...\r
- #\r
- # But it's still good enough for CheckSectionSpacing.\r
- self.last_line = 0\r
- depth = 0\r
- for i in range(linenum, clean_lines.NumLines()):\r
- line = clean_lines.elided[i]\r
- depth += line.count('{') - line.count('}')\r
- if not depth:\r
- self.last_line = i\r
- break\r
-\r
- def CheckBegin(self, filename, clean_lines, linenum, error):\r
- # Look for a bare ':'\r
- if Search('(^|[^:]):($|[^:])', clean_lines.elided[linenum]):\r
- self.is_derived = True\r
-\r
- def CheckEnd(self, filename, clean_lines, linenum, error):\r
- # If there is a DISALLOW macro, it should appear near the end of\r
- # the class.\r
- seen_last_thing_in_class = False\r
- for i in xrange(linenum - 1, self.starting_linenum, -1):\r
- match = Search(\r
- r'\b(DISALLOW_COPY_AND_ASSIGN|DISALLOW_IMPLICIT_CONSTRUCTORS)\(' +\r
- self.name + r'\)',\r
- clean_lines.elided[i])\r
- if match:\r
- if seen_last_thing_in_class:\r
- error(filename, i, 'readability/constructors', 3,\r
- match.group(1) + ' should be the last thing in the class')\r
- break\r
-\r
- if not Match(r'^\s*$', clean_lines.elided[i]):\r
- seen_last_thing_in_class = True\r
-\r
- # Check that closing brace is aligned with beginning of the class.\r
- # Only do this if the closing brace is indented by only whitespaces.\r
- # This means we will not check single-line class definitions.\r
- indent = Match(r'^( *)\}', clean_lines.elided[linenum])\r
- if indent and len(indent.group(1)) != self.class_indent:\r
- if self.is_struct:\r
- parent = 'struct ' + self.name\r
- else:\r
- parent = 'class ' + self.name\r
- error(filename, linenum, 'whitespace/indent', 3,\r
- 'Closing brace should be aligned with beginning of %s' % parent)\r
-\r
-\r
-class _NamespaceInfo(_BlockInfo):\r
- """Stores information about a namespace."""\r
-\r
- def __init__(self, name, linenum):\r
- _BlockInfo.__init__(self, linenum, False)\r
- self.name = name or ''\r
- self.check_namespace_indentation = True\r
-\r
- def CheckEnd(self, filename, clean_lines, linenum, error):\r
- """Check end of namespace comments."""\r
- line = clean_lines.raw_lines[linenum]\r
-\r
- # Check how many lines is enclosed in this namespace. Don't issue\r
- # warning for missing namespace comments if there aren't enough\r
- # lines. However, do apply checks if there is already an end of\r
- # namespace comment and it's incorrect.\r
- #\r
- # TODO(unknown): We always want to check end of namespace comments\r
- # if a namespace is large, but sometimes we also want to apply the\r
- # check if a short namespace contained nontrivial things (something\r
- # other than forward declarations). There is currently no logic on\r
- # deciding what these nontrivial things are, so this check is\r
- # triggered by namespace size only, which works most of the time.\r
- if (linenum - self.starting_linenum < 10\r
- and not Match(r'^\s*};*\s*(//|/\*).*\bnamespace\b', line)):\r
- return\r
-\r
- # Look for matching comment at end of namespace.\r
- #\r
- # Note that we accept C style "/* */" comments for terminating\r
- # namespaces, so that code that terminate namespaces inside\r
- # preprocessor macros can be cpplint clean.\r
- #\r
- # We also accept stuff like "// end of namespace <name>." with the\r
- # period at the end.\r
- #\r
- # Besides these, we don't accept anything else, otherwise we might\r
- # get false negatives when existing comment is a substring of the\r
- # expected namespace.\r
- if self.name:\r
- # Named namespace\r
- if not Match((r'^\s*};*\s*(//|/\*).*\bnamespace\s+' +\r
- re.escape(self.name) + r'[\*/\.\\\s]*$'),\r
- line):\r
- error(filename, linenum, 'readability/namespace', 5,\r
- 'Namespace should be terminated with "// namespace %s"' %\r
- self.name)\r
- else:\r
- # Anonymous namespace\r
- if not Match(r'^\s*};*\s*(//|/\*).*\bnamespace[\*/\.\\\s]*$', line):\r
- # If "// namespace anonymous" or "// anonymous namespace (more text)",\r
- # mention "// anonymous namespace" as an acceptable form\r
- if Match(r'^\s*}.*\b(namespace anonymous|anonymous namespace)\b', line):\r
- error(filename, linenum, 'readability/namespace', 5,\r
- 'Anonymous namespace should be terminated with "// namespace"'\r
- ' or "// anonymous namespace"')\r
- else:\r
- error(filename, linenum, 'readability/namespace', 5,\r
- 'Anonymous namespace should be terminated with "// namespace"')\r
-\r
-\r
-class _PreprocessorInfo(object):\r
- """Stores checkpoints of nesting stacks when #if/#else is seen."""\r
-\r
- def __init__(self, stack_before_if):\r
- # The entire nesting stack before #if\r
- self.stack_before_if = stack_before_if\r
-\r
- # The entire nesting stack up to #else\r
- self.stack_before_else = []\r
-\r
- # Whether we have already seen #else or #elif\r
- self.seen_else = False\r
-\r
-\r
-class NestingState(object):\r
- """Holds states related to parsing braces."""\r
-\r
- def __init__(self):\r
- # Stack for tracking all braces. An object is pushed whenever we\r
- # see a "{", and popped when we see a "}". Only 3 types of\r
- # objects are possible:\r
- # - _ClassInfo: a class or struct.\r
- # - _NamespaceInfo: a namespace.\r
- # - _BlockInfo: some other type of block.\r
- self.stack = []\r
-\r
- # Top of the previous stack before each Update().\r
- #\r
- # Because the nesting_stack is updated at the end of each line, we\r
- # had to do some convoluted checks to find out what is the current\r
- # scope at the beginning of the line. This check is simplified by\r
- # saving the previous top of nesting stack.\r
- #\r
- # We could save the full stack, but we only need the top. Copying\r
- # the full nesting stack would slow down cpplint by ~10%.\r
- self.previous_stack_top = []\r
-\r
- # Stack of _PreprocessorInfo objects.\r
- self.pp_stack = []\r
-\r
- def SeenOpenBrace(self):\r
- """Check if we have seen the opening brace for the innermost block.\r
-\r
- Returns:\r
- True if we have seen the opening brace, False if the innermost\r
- block is still expecting an opening brace.\r
- """\r
- return (not self.stack) or self.stack[-1].seen_open_brace\r
-\r
- def InNamespaceBody(self):\r
- """Check if we are currently one level inside a namespace body.\r
-\r
- Returns:\r
- True if top of the stack is a namespace block, False otherwise.\r
- """\r
- return self.stack and isinstance(self.stack[-1], _NamespaceInfo)\r
-\r
- def InExternC(self):\r
- """Check if we are currently one level inside an 'extern "C"' block.\r
-\r
- Returns:\r
- True if top of the stack is an extern block, False otherwise.\r
- """\r
- return self.stack and isinstance(self.stack[-1], _ExternCInfo)\r
-\r
- def InClassDeclaration(self):\r
- """Check if we are currently one level inside a class or struct declaration.\r
-\r
- Returns:\r
- True if top of the stack is a class/struct, False otherwise.\r
- """\r
- return self.stack and isinstance(self.stack[-1], _ClassInfo)\r
-\r
- def InAsmBlock(self):\r
- """Check if we are currently one level inside an inline ASM block.\r
-\r
- Returns:\r
- True if the top of the stack is a block containing inline ASM.\r
- """\r
- return self.stack and self.stack[-1].inline_asm != _NO_ASM\r
-\r
- def InTemplateArgumentList(self, clean_lines, linenum, pos):\r
- """Check if current position is inside template argument list.\r
-\r
- Args:\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- pos: position just after the suspected template argument.\r
- Returns:\r
- True if (linenum, pos) is inside template arguments.\r
- """\r
- while linenum < clean_lines.NumLines():\r
- # Find the earliest character that might indicate a template argument\r
- line = clean_lines.elided[linenum]\r
- match = Match(r'^[^{};=\[\]\.<>]*(.)', line[pos:])\r
- if not match:\r
- linenum += 1\r
- pos = 0\r
- continue\r
- token = match.group(1)\r
- pos += len(match.group(0))\r
-\r
- # These things do not look like template argument list:\r
- # class Suspect {\r
- # class Suspect x; }\r
- if token in ('{', '}', ';'): return False\r
-\r
- # These things look like template argument list:\r
- # template <class Suspect>\r
- # template <class Suspect = default_value>\r
- # template <class Suspect[]>\r
- # template <class Suspect...>\r
- if token in ('>', '=', '[', ']', '.'): return True\r
-\r
- # Check if token is an unmatched '<'.\r
- # If not, move on to the next character.\r
- if token != '<':\r
- pos += 1\r
- if pos >= len(line):\r
- linenum += 1\r
- pos = 0\r
- continue\r
-\r
- # We can't be sure if we just find a single '<', and need to\r
- # find the matching '>'.\r
- (_, end_line, end_pos) = CloseExpression(clean_lines, linenum, pos - 1)\r
- if end_pos < 0:\r
- # Not sure if template argument list or syntax error in file\r
- return False\r
- linenum = end_line\r
- pos = end_pos\r
- return False\r
-\r
- def UpdatePreprocessor(self, line):\r
- """Update preprocessor stack.\r
-\r
- We need to handle preprocessors due to classes like this:\r
- #ifdef SWIG\r
- struct ResultDetailsPageElementExtensionPoint {\r
- #else\r
- struct ResultDetailsPageElementExtensionPoint : public Extension {\r
- #endif\r
-\r
- We make the following assumptions (good enough for most files):\r
- - Preprocessor condition evaluates to true from #if up to first\r
- #else/#elif/#endif.\r
-\r
- - Preprocessor condition evaluates to false from #else/#elif up\r
- to #endif. We still perform lint checks on these lines, but\r
- these do not affect nesting stack.\r
-\r
- Args:\r
- line: current line to check.\r
- """\r
- if Match(r'^\s*#\s*(if|ifdef|ifndef)\b', line):\r
- # Beginning of #if block, save the nesting stack here. The saved\r
- # stack will allow us to restore the parsing state in the #else case.\r
- self.pp_stack.append(_PreprocessorInfo(copy.deepcopy(self.stack)))\r
- elif Match(r'^\s*#\s*(else|elif)\b', line):\r
- # Beginning of #else block\r
- if self.pp_stack:\r
- if not self.pp_stack[-1].seen_else:\r
- # This is the first #else or #elif block. Remember the\r
- # whole nesting stack up to this point. This is what we\r
- # keep after the #endif.\r
- self.pp_stack[-1].seen_else = True\r
- self.pp_stack[-1].stack_before_else = copy.deepcopy(self.stack)\r
-\r
- # Restore the stack to how it was before the #if\r
- self.stack = copy.deepcopy(self.pp_stack[-1].stack_before_if)\r
- else:\r
- # TODO(unknown): unexpected #else, issue warning?\r
- pass\r
- elif Match(r'^\s*#\s*endif\b', line):\r
- # End of #if or #else blocks.\r
- if self.pp_stack:\r
- # If we saw an #else, we will need to restore the nesting\r
- # stack to its former state before the #else, otherwise we\r
- # will just continue from where we left off.\r
- if self.pp_stack[-1].seen_else:\r
- # Here we can just use a shallow copy since we are the last\r
- # reference to it.\r
- self.stack = self.pp_stack[-1].stack_before_else\r
- # Drop the corresponding #if\r
- self.pp_stack.pop()\r
- else:\r
- # TODO(unknown): unexpected #endif, issue warning?\r
- pass\r
-\r
- # TODO(unknown): Update() is too long, but we will refactor later.\r
- def Update(self, filename, clean_lines, linenum, error):\r
- """Update nesting state with current line.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- error: The function to call with any errors found.\r
- """\r
- line = clean_lines.elided[linenum]\r
-\r
- # Remember top of the previous nesting stack.\r
- #\r
- # The stack is always pushed/popped and not modified in place, so\r
- # we can just do a shallow copy instead of copy.deepcopy. Using\r
- # deepcopy would slow down cpplint by ~28%.\r
- if self.stack:\r
- self.previous_stack_top = self.stack[-1]\r
- else:\r
- self.previous_stack_top = None\r
-\r
- # Update pp_stack\r
- self.UpdatePreprocessor(line)\r
-\r
- # Count parentheses. This is to avoid adding struct arguments to\r
- # the nesting stack.\r
- if self.stack:\r
- inner_block = self.stack[-1]\r
- depth_change = line.count('(') - line.count(')')\r
- inner_block.open_parentheses += depth_change\r
-\r
- # Also check if we are starting or ending an inline assembly block.\r
- if inner_block.inline_asm in (_NO_ASM, _END_ASM):\r
- if (depth_change != 0 and\r
- inner_block.open_parentheses == 1 and\r
- _MATCH_ASM.match(line)):\r
- # Enter assembly block\r
- inner_block.inline_asm = _INSIDE_ASM\r
- else:\r
- # Not entering assembly block. If previous line was _END_ASM,\r
- # we will now shift to _NO_ASM state.\r
- inner_block.inline_asm = _NO_ASM\r
- elif (inner_block.inline_asm == _INSIDE_ASM and\r
- inner_block.open_parentheses == 0):\r
- # Exit assembly block\r
- inner_block.inline_asm = _END_ASM\r
-\r
- # Consume namespace declaration at the beginning of the line. Do\r
- # this in a loop so that we catch same line declarations like this:\r
- # namespace proto2 { namespace bridge { class MessageSet; } }\r
- while True:\r
- # Match start of namespace. The "\b\s*" below catches namespace\r
- # declarations even if it weren't followed by a whitespace, this\r
- # is so that we don't confuse our namespace checker. The\r
- # missing spaces will be flagged by CheckSpacing.\r
- namespace_decl_match = Match(r'^\s*namespace\b\s*([:\w]+)?(.*)$', line)\r
- if not namespace_decl_match:\r
- break\r
-\r
- new_namespace = _NamespaceInfo(namespace_decl_match.group(1), linenum)\r
- self.stack.append(new_namespace)\r
-\r
- line = namespace_decl_match.group(2)\r
- if line.find('{') != -1:\r
- new_namespace.seen_open_brace = True\r
- line = line[line.find('{') + 1:]\r
-\r
- # Look for a class declaration in whatever is left of the line\r
- # after parsing namespaces. The regexp accounts for decorated classes\r
- # such as in:\r
- # class LOCKABLE API Object {\r
- # };\r
- class_decl_match = Match(\r
- r'^(\s*(?:template\s*<[\w\s<>,:]*>\s*)?'\r
- r'(class|struct)\s+(?:[A-Z_]+\s+)*(\w+(?:::\w+)*))'\r
- r'(.*)$', line)\r
- if (class_decl_match and\r
- (not self.stack or self.stack[-1].open_parentheses == 0)):\r
- # We do not want to accept classes that are actually template arguments:\r
- # template <class Ignore1,\r
- # class Ignore2 = Default<Args>,\r
- # template <Args> class Ignore3>\r
- # void Function() {};\r
- #\r
- # To avoid template argument cases, we scan forward and look for\r
- # an unmatched '>'. If we see one, assume we are inside a\r
- # template argument list.\r
- end_declaration = len(class_decl_match.group(1))\r
- if not self.InTemplateArgumentList(clean_lines, linenum, end_declaration):\r
- self.stack.append(_ClassInfo(\r
- class_decl_match.group(3), class_decl_match.group(2),\r
- clean_lines, linenum))\r
- line = class_decl_match.group(4)\r
-\r
- # If we have not yet seen the opening brace for the innermost block,\r
- # run checks here.\r
- if not self.SeenOpenBrace():\r
- self.stack[-1].CheckBegin(filename, clean_lines, linenum, error)\r
-\r
- # Update access control if we are inside a class/struct\r
- if self.stack and isinstance(self.stack[-1], _ClassInfo):\r
- classinfo = self.stack[-1]\r
- access_match = Match(\r
- r'^(.*)\b(public|private|protected|signals)(\s+(?:slots\s*)?)?'\r
- r':(?:[^:]|$)',\r
- line)\r
- if access_match:\r
- classinfo.access = access_match.group(2)\r
-\r
- # Check that access keywords are indented +1 space. Skip this\r
- # check if the keywords are not preceded by whitespaces.\r
- indent = access_match.group(1)\r
- if (len(indent) != classinfo.class_indent + 1 and\r
- Match(r'^\s*$', indent)):\r
- if classinfo.is_struct:\r
- parent = 'struct ' + classinfo.name\r
- else:\r
- parent = 'class ' + classinfo.name\r
- slots = ''\r
- if access_match.group(3):\r
- slots = access_match.group(3)\r
- error(filename, linenum, 'whitespace/indent', 3,\r
- '%s%s: should be indented +1 space inside %s' % (\r
- access_match.group(2), slots, parent))\r
-\r
- # Consume braces or semicolons from what's left of the line\r
- while True:\r
- # Match first brace, semicolon, or closed parenthesis.\r
- matched = Match(r'^[^{;)}]*([{;)}])(.*)$', line)\r
- if not matched:\r
- break\r
-\r
- token = matched.group(1)\r
- if token == '{':\r
- # If namespace or class hasn't seen a opening brace yet, mark\r
- # namespace/class head as complete. Push a new block onto the\r
- # stack otherwise.\r
- if not self.SeenOpenBrace():\r
- self.stack[-1].seen_open_brace = True\r
- elif Match(r'^extern\s*"[^"]*"\s*\{', line):\r
- self.stack.append(_ExternCInfo(linenum))\r
- else:\r
- self.stack.append(_BlockInfo(linenum, True))\r
- if _MATCH_ASM.match(line):\r
- self.stack[-1].inline_asm = _BLOCK_ASM\r
-\r
- elif token == ';' or token == ')':\r
- # If we haven't seen an opening brace yet, but we already saw\r
- # a semicolon, this is probably a forward declaration. Pop\r
- # the stack for these.\r
- #\r
- # Similarly, if we haven't seen an opening brace yet, but we\r
- # already saw a closing parenthesis, then these are probably\r
- # function arguments with extra "class" or "struct" keywords.\r
- # Also pop these stack for these.\r
- if not self.SeenOpenBrace():\r
- self.stack.pop()\r
- else: # token == '}'\r
- # Perform end of block checks and pop the stack.\r
- if self.stack:\r
- self.stack[-1].CheckEnd(filename, clean_lines, linenum, error)\r
- self.stack.pop()\r
- line = matched.group(2)\r
-\r
- def InnermostClass(self):\r
- """Get class info on the top of the stack.\r
-\r
- Returns:\r
- A _ClassInfo object if we are inside a class, or None otherwise.\r
- """\r
- for i in range(len(self.stack), 0, -1):\r
- classinfo = self.stack[i - 1]\r
- if isinstance(classinfo, _ClassInfo):\r
- return classinfo\r
- return None\r
-\r
- def CheckCompletedBlocks(self, filename, error):\r
- """Checks that all classes and namespaces have been completely parsed.\r
-\r
- Call this when all lines in a file have been processed.\r
- Args:\r
- filename: The name of the current file.\r
- error: The function to call with any errors found.\r
- """\r
- # Note: This test can result in false positives if #ifdef constructs\r
- # get in the way of brace matching. See the testBuildClass test in\r
- # cpplint_unittest.py for an example of this.\r
- for obj in self.stack:\r
- if isinstance(obj, _ClassInfo):\r
- error(filename, obj.starting_linenum, 'build/class', 5,\r
- 'Failed to find complete declaration of class %s' %\r
- obj.name)\r
- elif isinstance(obj, _NamespaceInfo):\r
- error(filename, obj.starting_linenum, 'build/namespaces', 5,\r
- 'Failed to find complete declaration of namespace %s' %\r
- obj.name)\r
-\r
-\r
-def CheckForNonStandardConstructs(filename, clean_lines, linenum,\r
- nesting_state, error):\r
- r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2.\r
-\r
- Complain about several constructs which gcc-2 accepts, but which are\r
- not standard C++. Warning about these in lint is one way to ease the\r
- transition to new compilers.\r
- - put storage class first (e.g. "static const" instead of "const static").\r
- - "%lld" instead of %qd" in printf-type functions.\r
- - "%1$d" is non-standard in printf-type functions.\r
- - "\%" is an undefined character escape sequence.\r
- - text after #endif is not allowed.\r
- - invalid inner-style forward declaration.\r
- - >? and <? operators, and their >?= and <?= cousins.\r
-\r
- Additionally, check for constructor/destructor style violations and reference\r
- members, as it is very convenient to do so while checking for\r
- gcc-2 compliance.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- nesting_state: A NestingState instance which maintains information about\r
- the current stack of nested blocks being parsed.\r
- error: A callable to which errors are reported, which takes 4 arguments:\r
- filename, line number, error level, and message\r
- """\r
-\r
- # Remove comments from the line, but leave in strings for now.\r
- line = clean_lines.lines[linenum]\r
-\r
- if Search(r'printf\s*\(.*".*%[-+ ]?\d*q', line):\r
- error(filename, linenum, 'runtime/printf_format', 3,\r
- '%q in format strings is deprecated. Use %ll instead.')\r
-\r
- if Search(r'printf\s*\(.*".*%\d+\$', line):\r
- error(filename, linenum, 'runtime/printf_format', 2,\r
- '%N$ formats are unconventional. Try rewriting to avoid them.')\r
-\r
- # Remove escaped backslashes before looking for undefined escapes.\r
- line = line.replace('\\\\', '')\r
-\r
- if Search(r'("|\').*\\(%|\[|\(|{)', line):\r
- error(filename, linenum, 'build/printf_format', 3,\r
- '%, [, (, and { are undefined character escapes. Unescape them.')\r
-\r
- # For the rest, work with both comments and strings removed.\r
- line = clean_lines.elided[linenum]\r
-\r
- if Search(r'\b(const|volatile|void|char|short|int|long'\r
- r'|float|double|signed|unsigned'\r
- r'|schar|u?int8|u?int16|u?int32|u?int64)'\r
- r'\s+(register|static|extern|typedef)\b',\r
- line):\r
- error(filename, linenum, 'build/storage_class', 5,\r
- 'Storage-class specifier (static, extern, typedef, etc) should be '\r
- 'at the beginning of the declaration.')\r
-\r
- if Match(r'\s*#\s*endif\s*[^/\s]+', line):\r
- error(filename, linenum, 'build/endif_comment', 5,\r
- 'Uncommented text after #endif is non-standard. Use a comment.')\r
-\r
- if Match(r'\s*class\s+(\w+\s*::\s*)+\w+\s*;', line):\r
- error(filename, linenum, 'build/forward_decl', 5,\r
- 'Inner-style forward declarations are invalid. Remove this line.')\r
-\r
- if Search(r'(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?',\r
- line):\r
- error(filename, linenum, 'build/deprecated', 3,\r
- '>? and <? (max and min) operators are non-standard and deprecated.')\r
-\r
- if Search(r'^\s*const\s*string\s*&\s*\w+\s*;', line):\r
- # TODO(unknown): Could it be expanded safely to arbitrary references,\r
- # without triggering too many false positives? The first\r
- # attempt triggered 5 warnings for mostly benign code in the regtest, hence\r
- # the restriction.\r
- # Here's the original regexp, for the reference:\r
- # type_name = r'\w+((\s*::\s*\w+)|(\s*<\s*\w+?\s*>))?'\r
- # r'\s*const\s*' + type_name + '\s*&\s*\w+\s*;'\r
- error(filename, linenum, 'runtime/member_string_references', 2,\r
- 'const string& members are dangerous. It is much better to use '\r
- 'alternatives, such as pointers or simple constants.')\r
-\r
- # Everything else in this function operates on class declarations.\r
- # Return early if the top of the nesting stack is not a class, or if\r
- # the class head is not completed yet.\r
- classinfo = nesting_state.InnermostClass()\r
- if not classinfo or not classinfo.seen_open_brace:\r
- return\r
-\r
- # The class may have been declared with namespace or classname qualifiers.\r
- # The constructor and destructor will not have those qualifiers.\r
- base_classname = classinfo.name.split('::')[-1]\r
-\r
- # Look for single-argument constructors that aren't marked explicit.\r
- # Technically a valid construct, but against style.\r
- explicit_constructor_match = Match(\r
- r'\s+(?:(?:inline|constexpr)\s+)*(explicit\s+)?'\r
- r'(?:(?:inline|constexpr)\s+)*%s\s*'\r
- r'\(((?:[^()]|\([^()]*\))*)\)'\r
- % re.escape(base_classname),\r
- line)\r
-\r
- if explicit_constructor_match:\r
- is_marked_explicit = explicit_constructor_match.group(1)\r
-\r
- if not explicit_constructor_match.group(2):\r
- constructor_args = []\r
- else:\r
- constructor_args = explicit_constructor_match.group(2).split(',')\r
-\r
- # collapse arguments so that commas in template parameter lists and function\r
- # argument parameter lists don't split arguments in two\r
- i = 0\r
- while i < len(constructor_args):\r
- constructor_arg = constructor_args[i]\r
- while (constructor_arg.count('<') > constructor_arg.count('>') or\r
- constructor_arg.count('(') > constructor_arg.count(')')):\r
- constructor_arg += ',' + constructor_args[i + 1]\r
- del constructor_args[i + 1]\r
- constructor_args[i] = constructor_arg\r
- i += 1\r
-\r
- defaulted_args = [arg for arg in constructor_args if '=' in arg]\r
- noarg_constructor = (not constructor_args or # empty arg list\r
- # 'void' arg specifier\r
- (len(constructor_args) == 1 and\r
- constructor_args[0].strip() == 'void'))\r
- onearg_constructor = ((len(constructor_args) == 1 and # exactly one arg\r
- not noarg_constructor) or\r
- # all but at most one arg defaulted\r
- (len(constructor_args) >= 1 and\r
- not noarg_constructor and\r
- len(defaulted_args) >= len(constructor_args) - 1))\r
- initializer_list_constructor = bool(\r
- onearg_constructor and\r
- Search(r'\bstd\s*::\s*initializer_list\b', constructor_args[0]))\r
- copy_constructor = bool(\r
- onearg_constructor and\r
- Match(r'(const\s+)?%s(\s*<[^>]*>)?(\s+const)?\s*(?:<\w+>\s*)?&'\r
- % re.escape(base_classname), constructor_args[0].strip()))\r
-\r
- if (not is_marked_explicit and\r
- onearg_constructor and\r
- not initializer_list_constructor and\r
- not copy_constructor):\r
- if defaulted_args:\r
- error(filename, linenum, 'runtime/explicit', 5,\r
- 'Constructors callable with one argument '\r
- 'should be marked explicit.')\r
- else:\r
- error(filename, linenum, 'runtime/explicit', 5,\r
- 'Single-parameter constructors should be marked explicit.')\r
- elif is_marked_explicit and not onearg_constructor:\r
- if noarg_constructor:\r
- error(filename, linenum, 'runtime/explicit', 5,\r
- 'Zero-parameter constructors should not be marked explicit.')\r
-\r
-\r
-def CheckSpacingForFunctionCall(filename, clean_lines, linenum, error):\r
- """Checks for the correctness of various spacing around function calls.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- error: The function to call with any errors found.\r
- """\r
- line = clean_lines.elided[linenum]\r
-\r
- # Since function calls often occur inside if/for/while/switch\r
- # expressions - which have their own, more liberal conventions - we\r
- # first see if we should be looking inside such an expression for a\r
- # function call, to which we can apply more strict standards.\r
- fncall = line # if there's no control flow construct, look at whole line\r
- for pattern in (r'\bif\s*\((.*)\)\s*{',\r
- r'\bfor\s*\((.*)\)\s*{',\r
- r'\bwhile\s*\((.*)\)\s*[{;]',\r
- r'\bswitch\s*\((.*)\)\s*{'):\r
- match = Search(pattern, line)\r
- if match:\r
- fncall = match.group(1) # look inside the parens for function calls\r
- break\r
-\r
- # Except in if/for/while/switch, there should never be space\r
- # immediately inside parens (eg "f( 3, 4 )"). We make an exception\r
- # for nested parens ( (a+b) + c ). Likewise, there should never be\r
- # a space before a ( when it's a function argument. I assume it's a\r
- # function argument when the char before the whitespace is legal in\r
- # a function name (alnum + _) and we're not starting a macro. Also ignore\r
- # pointers and references to arrays and functions coz they're too tricky:\r
- # we use a very simple way to recognize these:\r
- # " (something)(maybe-something)" or\r
- # " (something)(maybe-something," or\r
- # " (something)[something]"\r
- # Note that we assume the contents of [] to be short enough that\r
- # they'll never need to wrap.\r
- if ( # Ignore control structures.\r
- not Search(r'\b(if|for|while|switch|return|new|delete|catch|sizeof)\b',\r
- fncall) and\r
- # Ignore pointers/references to functions.\r
- not Search(r' \([^)]+\)\([^)]*(\)|,$)', fncall) and\r
- # Ignore pointers/references to arrays.\r
- not Search(r' \([^)]+\)\[[^\]]+\]', fncall)):\r
- if Search(r'\w\s*\(\s(?!\s*\\$)', fncall): # a ( used for a fn call\r
- error(filename, linenum, 'whitespace/parens', 4,\r
- 'Extra space after ( in function call')\r
- elif Search(r'\(\s+(?!(\s*\\)|\()', fncall):\r
- error(filename, linenum, 'whitespace/parens', 2,\r
- 'Extra space after (')\r
- if (Search(r'\w\s+\(', fncall) and\r
- not Search(r'_{0,2}asm_{0,2}\s+_{0,2}volatile_{0,2}\s+\(', fncall) and\r
- not Search(r'#\s*define|typedef|using\s+\w+\s*=', fncall) and\r
- not Search(r'\w\s+\((\w+::)*\*\w+\)\(', fncall) and\r
- not Search(r'\bcase\s+\(', fncall)):\r
- # TODO(unknown): Space after an operator function seem to be a common\r
- # error, silence those for now by restricting them to highest verbosity.\r
- if Search(r'\boperator_*\b', line):\r
- error(filename, linenum, 'whitespace/parens', 0,\r
- 'Extra space before ( in function call')\r
- else:\r
- error(filename, linenum, 'whitespace/parens', 4,\r
- 'Extra space before ( in function call')\r
- # If the ) is followed only by a newline or a { + newline, assume it's\r
- # part of a control statement (if/while/etc), and don't complain\r
- if Search(r'[^)]\s+\)\s*[^{\s]', fncall):\r
- # If the closing parenthesis is preceded by only whitespaces,\r
- # try to give a more descriptive error message.\r
- if Search(r'^\s+\)', fncall):\r
- error(filename, linenum, 'whitespace/parens', 2,\r
- 'Closing ) should be moved to the previous line')\r
- else:\r
- error(filename, linenum, 'whitespace/parens', 2,\r
- 'Extra space before )')\r
-\r
-\r
-def IsBlankLine(line):\r
- """Returns true if the given line is blank.\r
-\r
- We consider a line to be blank if the line is empty or consists of\r
- only white spaces.\r
-\r
- Args:\r
- line: A line of a string.\r
-\r
- Returns:\r
- True, if the given line is blank.\r
- """\r
- return not line or line.isspace()\r
-\r
-\r
-def CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line,\r
- error):\r
- is_namespace_indent_item = (\r
- len(nesting_state.stack) > 1 and\r
- nesting_state.stack[-1].check_namespace_indentation and\r
- isinstance(nesting_state.previous_stack_top, _NamespaceInfo) and\r
- nesting_state.previous_stack_top == nesting_state.stack[-2])\r
-\r
- if ShouldCheckNamespaceIndentation(nesting_state, is_namespace_indent_item,\r
- clean_lines.elided, line):\r
- CheckItemIndentationInNamespace(filename, clean_lines.elided,\r
- line, error)\r
-\r
-\r
-def CheckForFunctionLengths(filename, clean_lines, linenum,\r
- function_state, error):\r
- """Reports for long function bodies.\r
-\r
- For an overview why this is done, see:\r
- https://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions\r
-\r
- Uses a simplistic algorithm assuming other style guidelines\r
- (especially spacing) are followed.\r
- Only checks unindented functions, so class members are unchecked.\r
- Trivial bodies are unchecked, so constructors with huge initializer lists\r
- may be missed.\r
- Blank/comment lines are not counted so as to avoid encouraging the removal\r
- of vertical space and comments just to get through a lint check.\r
- NOLINT *on the last line of a function* disables this check.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- function_state: Current function name and lines in body so far.\r
- error: The function to call with any errors found.\r
- """\r
- lines = clean_lines.lines\r
- line = lines[linenum]\r
- joined_line = ''\r
-\r
- starting_func = False\r
- regexp = r'(\w(\w|::|\*|\&|\s)*)\(' # decls * & space::name( ...\r
- match_result = Match(regexp, line)\r
- if match_result:\r
- # If the name is all caps and underscores, figure it's a macro and\r
- # ignore it, unless it's TEST or TEST_F.\r
- function_name = match_result.group(1).split()[-1]\r
- if function_name == 'TEST' or function_name == 'TEST_F' or (\r
- not Match(r'[A-Z_]+$', function_name)):\r
- starting_func = True\r
-\r
- if starting_func:\r
- body_found = False\r
- for start_linenum in xrange(linenum, clean_lines.NumLines()):\r
- start_line = lines[start_linenum]\r
- joined_line += ' ' + start_line.lstrip()\r
- if Search(r'(;|})', start_line): # Declarations and trivial functions\r
- body_found = True\r
- break # ... ignore\r
- elif Search(r'{', start_line):\r
- body_found = True\r
- function = Search(r'((\w|:)*)\(', line).group(1)\r
- if Match(r'TEST', function): # Handle TEST... macros\r
- parameter_regexp = Search(r'(\(.*\))', joined_line)\r
- if parameter_regexp: # Ignore bad syntax\r
- function += parameter_regexp.group(1)\r
- else:\r
- function += '()'\r
- function_state.Begin(function)\r
- break\r
- if not body_found:\r
- # No body for the function (or evidence of a non-function) was found.\r
- error(filename, linenum, 'readability/fn_size', 5,\r
- 'Lint failed to find start of function body.')\r
- elif Match(r'^\}\s*$', line): # function end\r
- function_state.Check(error, filename, linenum)\r
- function_state.End()\r
- elif not Match(r'^\s*$', line):\r
- function_state.Count() # Count non-blank/non-comment lines.\r
-\r
-\r
-_RE_PATTERN_TODO = re.compile(r'^//(\s*)TODO(\(.+?\))?:?(\s|$)?')\r
-\r
-\r
-def CheckComment(line, filename, linenum, next_line_start, error):\r
- """Checks for common mistakes in comments.\r
-\r
- Args:\r
- line: The line in question.\r
- filename: The name of the current file.\r
- linenum: The number of the line to check.\r
- next_line_start: The first non-whitespace column of the next line.\r
- error: The function to call with any errors found.\r
- """\r
- commentpos = line.find('//')\r
- if commentpos != -1:\r
- # Check if the // may be in quotes. If so, ignore it\r
- if re.sub(r'\\.', '', line[0:commentpos]).count('"') % 2 == 0:\r
- # Allow one space for new scopes, two spaces otherwise:\r
- if (not (Match(r'^.*{ *//', line) and next_line_start == commentpos) and\r
- ((commentpos >= 1 and\r
- line[commentpos-1] not in string.whitespace) or\r
- (commentpos >= 2 and\r
- line[commentpos-2] not in string.whitespace))):\r
- error(filename, linenum, 'whitespace/comments', 2,\r
- 'At least two spaces is best between code and comments')\r
-\r
- # Checks for common mistakes in TODO comments.\r
- comment = line[commentpos:]\r
- match = _RE_PATTERN_TODO.match(comment)\r
- if match:\r
- # One whitespace is correct; zero whitespace is handled elsewhere.\r
- leading_whitespace = match.group(1)\r
- if len(leading_whitespace) > 1:\r
- error(filename, linenum, 'whitespace/todo', 2,\r
- 'Too many spaces before TODO')\r
-\r
- username = match.group(2)\r
- if not username:\r
- error(filename, linenum, 'readability/todo', 2,\r
- 'Missing username in TODO; it should look like '\r
- '"// TODO(my_username): Stuff."')\r
-\r
- middle_whitespace = match.group(3)\r
- # Comparisons made explicit for correctness -- pylint: disable=g-explicit-bool-comparison\r
- if middle_whitespace != ' ' and middle_whitespace != '':\r
- error(filename, linenum, 'whitespace/todo', 2,\r
- 'TODO(my_username) should be followed by a space')\r
-\r
- # If the comment contains an alphanumeric character, there\r
- # should be a space somewhere between it and the // unless\r
- # it's a /// or //! Doxygen comment.\r
- if (Match(r'//[^ ]*\w', comment) and\r
- not Match(r'(///|//\!)(\s+|$)', comment)):\r
- error(filename, linenum, 'whitespace/comments', 4,\r
- 'Should have a space between // and comment')\r
-\r
-\r
-def CheckSpacing(filename, clean_lines, linenum, nesting_state, error):\r
- """Checks for the correctness of various spacing issues in the code.\r
-\r
- Things we check for: spaces around operators, spaces after\r
- if/for/while/switch, no spaces around parens in function calls, two\r
- spaces between code and comment, don't start a block with a blank\r
- line, don't end a function with a blank line, don't add a blank line\r
- after public/protected/private, don't have too many blank lines in a row.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- nesting_state: A NestingState instance which maintains information about\r
- the current stack of nested blocks being parsed.\r
- error: The function to call with any errors found.\r
- """\r
-\r
- # Don't use "elided" lines here, otherwise we can't check commented lines.\r
- # Don't want to use "raw" either, because we don't want to check inside C++11\r
- # raw strings,\r
- raw = clean_lines.lines_without_raw_strings\r
- line = raw[linenum]\r
-\r
- # Before nixing comments, check if the line is blank for no good\r
- # reason. This includes the first line after a block is opened, and\r
- # blank lines at the end of a function (ie, right before a line like '}'\r
- #\r
- # Skip all the blank line checks if we are immediately inside a\r
- # namespace body. In other words, don't issue blank line warnings\r
- # for this block:\r
- # namespace {\r
- #\r
- # }\r
- #\r
- # A warning about missing end of namespace comments will be issued instead.\r
- #\r
- # Also skip blank line checks for 'extern "C"' blocks, which are formatted\r
- # like namespaces.\r
- if (IsBlankLine(line) and\r
- not nesting_state.InNamespaceBody() and\r
- not nesting_state.InExternC()):\r
- elided = clean_lines.elided\r
- prev_line = elided[linenum - 1]\r
- prevbrace = prev_line.rfind('{')\r
- # TODO(unknown): Don't complain if line before blank line, and line after,\r
- # both start with alnums and are indented the same amount.\r
- # This ignores whitespace at the start of a namespace block\r
- # because those are not usually indented.\r
- if prevbrace != -1 and prev_line[prevbrace:].find('}') == -1:\r
- # OK, we have a blank line at the start of a code block. Before we\r
- # complain, we check if it is an exception to the rule: The previous\r
- # non-empty line has the parameters of a function header that are indented\r
- # 4 spaces (because they did not fit in a 80 column line when placed on\r
- # the same line as the function name). We also check for the case where\r
- # the previous line is indented 6 spaces, which may happen when the\r
- # initializers of a constructor do not fit into a 80 column line.\r
- exception = False\r
- if Match(r' {6}\w', prev_line): # Initializer list?\r
- # We are looking for the opening column of initializer list, which\r
- # should be indented 4 spaces to cause 6 space indentation afterwards.\r
- search_position = linenum-2\r
- while (search_position >= 0\r
- and Match(r' {6}\w', elided[search_position])):\r
- search_position -= 1\r
- exception = (search_position >= 0\r
- and elided[search_position][:5] == ' :')\r
- else:\r
- # Search for the function arguments or an initializer list. We use a\r
- # simple heuristic here: If the line is indented 4 spaces; and we have a\r
- # closing paren, without the opening paren, followed by an opening brace\r
- # or colon (for initializer lists) we assume that it is the last line of\r
- # a function header. If we have a colon indented 4 spaces, it is an\r
- # initializer list.\r
- exception = (Match(r' {4}\w[^\(]*\)\s*(const\s*)?(\{\s*$|:)',\r
- prev_line)\r
- or Match(r' {4}:', prev_line))\r
-\r
- if not exception:\r
- error(filename, linenum, 'whitespace/blank_line', 2,\r
- 'Redundant blank line at the start of a code block '\r
- 'should be deleted.')\r
- # Ignore blank lines at the end of a block in a long if-else\r
- # chain, like this:\r
- # if (condition1) {\r
- # // Something followed by a blank line\r
- #\r
- # } else if (condition2) {\r
- # // Something else\r
- # }\r
- if linenum + 1 < clean_lines.NumLines():\r
- next_line = raw[linenum + 1]\r
- if (next_line\r
- and Match(r'\s*}', next_line)\r
- and next_line.find('} else ') == -1):\r
- error(filename, linenum, 'whitespace/blank_line', 3,\r
- 'Redundant blank line at the end of a code block '\r
- 'should be deleted.')\r
-\r
- matched = Match(r'\s*(public|protected|private):', prev_line)\r
- if matched:\r
- error(filename, linenum, 'whitespace/blank_line', 3,\r
- 'Do not leave a blank line after "%s:"' % matched.group(1))\r
-\r
- # Next, check comments\r
- next_line_start = 0\r
- if linenum + 1 < clean_lines.NumLines():\r
- next_line = raw[linenum + 1]\r
- next_line_start = len(next_line) - len(next_line.lstrip())\r
- CheckComment(line, filename, linenum, next_line_start, error)\r
-\r
- # get rid of comments and strings\r
- line = clean_lines.elided[linenum]\r
-\r
- # You shouldn't have spaces before your brackets, except maybe after\r
- # 'delete []' or 'return []() {};'\r
- if Search(r'\w\s+\[', line) and not Search(r'(?:delete|return)\s+\[', line):\r
- error(filename, linenum, 'whitespace/braces', 5,\r
- 'Extra space before [')\r
-\r
- # In range-based for, we wanted spaces before and after the colon, but\r
- # not around "::" tokens that might appear.\r
- if (Search(r'for *\(.*[^:]:[^: ]', line) or\r
- Search(r'for *\(.*[^: ]:[^:]', line)):\r
- error(filename, linenum, 'whitespace/forcolon', 2,\r
- 'Missing space around colon in range-based for loop')\r
-\r
-\r
-def CheckOperatorSpacing(filename, clean_lines, linenum, error):\r
- """Checks for horizontal spacing around operators.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- error: The function to call with any errors found.\r
- """\r
- line = clean_lines.elided[linenum]\r
-\r
- # Don't try to do spacing checks for operator methods. Do this by\r
- # replacing the troublesome characters with something else,\r
- # preserving column position for all other characters.\r
- #\r
- # The replacement is done repeatedly to avoid false positives from\r
- # operators that call operators.\r
- while True:\r
- match = Match(r'^(.*\boperator\b)(\S+)(\s*\(.*)$', line)\r
- if match:\r
- line = match.group(1) + ('_' * len(match.group(2))) + match.group(3)\r
- else:\r
- break\r
-\r
- # We allow no-spaces around = within an if: "if ( (a=Foo()) == 0 )".\r
- # Otherwise not. Note we only check for non-spaces on *both* sides;\r
- # sometimes people put non-spaces on one side when aligning ='s among\r
- # many lines (not that this is behavior that I approve of...)\r
- if ((Search(r'[\w.]=', line) or\r
- Search(r'=[\w.]', line))\r
- and not Search(r'\b(if|while|for) ', line)\r
- # Operators taken from [lex.operators] in C++11 standard.\r
- and not Search(r'(>=|<=|==|!=|&=|\^=|\|=|\+=|\*=|\/=|\%=)', line)\r
- and not Search(r'operator=', line)):\r
- error(filename, linenum, 'whitespace/operators', 4,\r
- 'Missing spaces around =')\r
-\r
- # It's ok not to have spaces around binary operators like + - * /, but if\r
- # there's too little whitespace, we get concerned. It's hard to tell,\r
- # though, so we punt on this one for now. TODO.\r
-\r
- # You should always have whitespace around binary operators.\r
- #\r
- # Check <= and >= first to avoid false positives with < and >, then\r
- # check non-include lines for spacing around < and >.\r
- #\r
- # If the operator is followed by a comma, assume it's be used in a\r
- # macro context and don't do any checks. This avoids false\r
- # positives.\r
- #\r
- # Note that && is not included here. This is because there are too\r
- # many false positives due to RValue references.\r
- match = Search(r'[^<>=!\s](==|!=|<=|>=|\|\|)[^<>=!\s,;\)]', line)\r
- if match:\r
- error(filename, linenum, 'whitespace/operators', 3,\r
- 'Missing spaces around %s' % match.group(1))\r
- elif not Match(r'#.*include', line):\r
- # Look for < that is not surrounded by spaces. This is only\r
- # triggered if both sides are missing spaces, even though\r
- # technically should should flag if at least one side is missing a\r
- # space. This is done to avoid some false positives with shifts.\r
- match = Match(r'^(.*[^\s<])<[^\s=<,]', line)\r
- if match:\r
- (_, _, end_pos) = CloseExpression(\r
- clean_lines, linenum, len(match.group(1)))\r
- if end_pos <= -1:\r
- error(filename, linenum, 'whitespace/operators', 3,\r
- 'Missing spaces around <')\r
-\r
- # Look for > that is not surrounded by spaces. Similar to the\r
- # above, we only trigger if both sides are missing spaces to avoid\r
- # false positives with shifts.\r
- match = Match(r'^(.*[^-\s>])>[^\s=>,]', line)\r
- if match:\r
- (_, _, start_pos) = ReverseCloseExpression(\r
- clean_lines, linenum, len(match.group(1)))\r
- if start_pos <= -1:\r
- error(filename, linenum, 'whitespace/operators', 3,\r
- 'Missing spaces around >')\r
-\r
- # We allow no-spaces around << when used like this: 10<<20, but\r
- # not otherwise (particularly, not when used as streams)\r
- #\r
- # We also allow operators following an opening parenthesis, since\r
- # those tend to be macros that deal with operators.\r
- match = Search(r'(operator|[^\s(<])(?:L|UL|LL|ULL|l|ul|ll|ull)?<<([^\s,=<])', line)\r
- if (match and not (match.group(1).isdigit() and match.group(2).isdigit()) and\r
- not (match.group(1) == 'operator' and match.group(2) == ';')):\r
- error(filename, linenum, 'whitespace/operators', 3,\r
- 'Missing spaces around <<')\r
-\r
- # We allow no-spaces around >> for almost anything. This is because\r
- # C++11 allows ">>" to close nested templates, which accounts for\r
- # most cases when ">>" is not followed by a space.\r
- #\r
- # We still warn on ">>" followed by alpha character, because that is\r
- # likely due to ">>" being used for right shifts, e.g.:\r
- # value >> alpha\r
- #\r
- # When ">>" is used to close templates, the alphanumeric letter that\r
- # follows would be part of an identifier, and there should still be\r
- # a space separating the template type and the identifier.\r
- # type<type<type>> alpha\r
- match = Search(r'>>[a-zA-Z_]', line)\r
- if match:\r
- error(filename, linenum, 'whitespace/operators', 3,\r
- 'Missing spaces around >>')\r
-\r
- # There shouldn't be space around unary operators\r
- match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line)\r
- if match:\r
- error(filename, linenum, 'whitespace/operators', 4,\r
- 'Extra space for operator %s' % match.group(1))\r
-\r
-\r
-def CheckParenthesisSpacing(filename, clean_lines, linenum, error):\r
- """Checks for horizontal spacing around parentheses.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- error: The function to call with any errors found.\r
- """\r
- line = clean_lines.elided[linenum]\r
-\r
- # No spaces after an if, while, switch, or for\r
- match = Search(r' (if\(|for\(|while\(|switch\()', line)\r
- if match:\r
- error(filename, linenum, 'whitespace/parens', 5,\r
- 'Missing space before ( in %s' % match.group(1))\r
-\r
- # For if/for/while/switch, the left and right parens should be\r
- # consistent about how many spaces are inside the parens, and\r
- # there should either be zero or one spaces inside the parens.\r
- # We don't want: "if ( foo)" or "if ( foo )".\r
- # Exception: "for ( ; foo; bar)" and "for (foo; bar; )" are allowed.\r
- match = Search(r'\b(if|for|while|switch)\s*'\r
- r'\(([ ]*)(.).*[^ ]+([ ]*)\)\s*{\s*$',\r
- line)\r
- if match:\r
- if len(match.group(2)) != len(match.group(4)):\r
- if not (match.group(3) == ';' and\r
- len(match.group(2)) == 1 + len(match.group(4)) or\r
- not match.group(2) and Search(r'\bfor\s*\(.*; \)', line)):\r
- error(filename, linenum, 'whitespace/parens', 5,\r
- 'Mismatching spaces inside () in %s' % match.group(1))\r
- if len(match.group(2)) not in [0, 1]:\r
- error(filename, linenum, 'whitespace/parens', 5,\r
- 'Should have zero or one spaces inside ( and ) in %s' %\r
- match.group(1))\r
-\r
-\r
-def CheckCommaSpacing(filename, clean_lines, linenum, error):\r
- """Checks for horizontal spacing near commas and semicolons.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- error: The function to call with any errors found.\r
- """\r
- raw = clean_lines.lines_without_raw_strings\r
- line = clean_lines.elided[linenum]\r
-\r
- # You should always have a space after a comma (either as fn arg or operator)\r
- #\r
- # This does not apply when the non-space character following the\r
- # comma is another comma, since the only time when that happens is\r
- # for empty macro arguments.\r
- #\r
- # We run this check in two passes: first pass on elided lines to\r
- # verify that lines contain missing whitespaces, second pass on raw\r
- # lines to confirm that those missing whitespaces are not due to\r
- # elided comments.\r
- if (Search(r',[^,\s]', ReplaceAll(r'\boperator\s*,\s*\(', 'F(', line)) and\r
- Search(r',[^,\s]', raw[linenum])):\r
- error(filename, linenum, 'whitespace/comma', 3,\r
- 'Missing space after ,')\r
-\r
- # You should always have a space after a semicolon\r
- # except for few corner cases\r
- # TODO(unknown): clarify if 'if (1) { return 1;}' is requires one more\r
- # space after ;\r
- if Search(r';[^\s};\\)/]', line):\r
- error(filename, linenum, 'whitespace/semicolon', 3,\r
- 'Missing space after ;')\r
-\r
-\r
-def _IsType(clean_lines, nesting_state, expr):\r
- """Check if expression looks like a type name, returns true if so.\r
-\r
- Args:\r
- clean_lines: A CleansedLines instance containing the file.\r
- nesting_state: A NestingState instance which maintains information about\r
- the current stack of nested blocks being parsed.\r
- expr: The expression to check.\r
- Returns:\r
- True, if token looks like a type.\r
- """\r
- # Keep only the last token in the expression\r
- last_word = Match(r'^.*(\b\S+)$', expr)\r
- if last_word:\r
- token = last_word.group(1)\r
- else:\r
- token = expr\r
-\r
- # Match native types and stdint types\r
- if _TYPES.match(token):\r
- return True\r
-\r
- # Try a bit harder to match templated types. Walk up the nesting\r
- # stack until we find something that resembles a typename\r
- # declaration for what we are looking for.\r
- typename_pattern = (r'\b(?:typename|class|struct)\s+' + re.escape(token) +\r
- r'\b')\r
- block_index = len(nesting_state.stack) - 1\r
- while block_index >= 0:\r
- if isinstance(nesting_state.stack[block_index], _NamespaceInfo):\r
- return False\r
-\r
- # Found where the opening brace is. We want to scan from this\r
- # line up to the beginning of the function, minus a few lines.\r
- # template <typename Type1, // stop scanning here\r
- # ...>\r
- # class C\r
- # : public ... { // start scanning here\r
- last_line = nesting_state.stack[block_index].starting_linenum\r
-\r
- next_block_start = 0\r
- if block_index > 0:\r
- next_block_start = nesting_state.stack[block_index - 1].starting_linenum\r
- first_line = last_line\r
- while first_line >= next_block_start:\r
- if clean_lines.elided[first_line].find('template') >= 0:\r
- break\r
- first_line -= 1\r
- if first_line < next_block_start:\r
- # Didn't find any "template" keyword before reaching the next block,\r
- # there are probably no template things to check for this block\r
- block_index -= 1\r
- continue\r
-\r
- # Look for typename in the specified range\r
- for i in xrange(first_line, last_line + 1, 1):\r
- if Search(typename_pattern, clean_lines.elided[i]):\r
- return True\r
- block_index -= 1\r
-\r
- return False\r
-\r
-\r
-def CheckBracesSpacing(filename, clean_lines, linenum, nesting_state, error):\r
- """Checks for horizontal spacing near commas.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- nesting_state: A NestingState instance which maintains information about\r
- the current stack of nested blocks being parsed.\r
- error: The function to call with any errors found.\r
- """\r
- line = clean_lines.elided[linenum]\r
-\r
- # Except after an opening paren, or after another opening brace (in case of\r
- # an initializer list, for instance), you should have spaces before your\r
- # braces when they are delimiting blocks, classes, namespaces etc.\r
- # And since you should never have braces at the beginning of a line,\r
- # this is an easy test. Except that braces used for initialization don't\r
- # follow the same rule; we often don't want spaces before those.\r
- match = Match(r'^(.*[^ ({>]){', line)\r
-\r
- if match:\r
- # Try a bit harder to check for brace initialization. This\r
- # happens in one of the following forms:\r
- # Constructor() : initializer_list_{} { ... }\r
- # Constructor{}.MemberFunction()\r
- # Type variable{};\r
- # FunctionCall(type{}, ...);\r
- # LastArgument(..., type{});\r
- # LOG(INFO) << type{} << " ...";\r
- # map_of_type[{...}] = ...;\r
- # ternary = expr ? new type{} : nullptr;\r
- # OuterTemplate<InnerTemplateConstructor<Type>{}>\r
- #\r
- # We check for the character following the closing brace, and\r
- # silence the warning if it's one of those listed above, i.e.\r
- # "{.;,)<>]:".\r
- #\r
- # To account for nested initializer list, we allow any number of\r
- # closing braces up to "{;,)<". We can't simply silence the\r
- # warning on first sight of closing brace, because that would\r
- # cause false negatives for things that are not initializer lists.\r
- # Silence this: But not this:\r
- # Outer{ if (...) {\r
- # Inner{...} if (...){ // Missing space before {\r
- # }; }\r
- #\r
- # There is a false negative with this approach if people inserted\r
- # spurious semicolons, e.g. "if (cond){};", but we will catch the\r
- # spurious semicolon with a separate check.\r
- leading_text = match.group(1)\r
- (endline, endlinenum, endpos) = CloseExpression(\r
- clean_lines, linenum, len(match.group(1)))\r
- trailing_text = ''\r
- if endpos > -1:\r
- trailing_text = endline[endpos:]\r
- for offset in xrange(endlinenum + 1,\r
- min(endlinenum + 3, clean_lines.NumLines() - 1)):\r
- trailing_text += clean_lines.elided[offset]\r
- # We also suppress warnings for `uint64_t{expression}` etc., as the style\r
- # guide recommends brace initialization for integral types to avoid\r
- # overflow/truncation.\r
- if (not Match(r'^[\s}]*[{.;,)<>\]:]', trailing_text)\r
- and not _IsType(clean_lines, nesting_state, leading_text)):\r
- error(filename, linenum, 'whitespace/braces', 5,\r
- 'Missing space before {')\r
-\r
- # Make sure '} else {' has spaces.\r
- if Search(r'}else', line):\r
- error(filename, linenum, 'whitespace/braces', 5,\r
- 'Missing space before else')\r
-\r
- # You shouldn't have a space before a semicolon at the end of the line.\r
- # There's a special case for "for" since the style guide allows space before\r
- # the semicolon there.\r
- if Search(r':\s*;\s*$', line):\r
- error(filename, linenum, 'whitespace/semicolon', 5,\r
- 'Semicolon defining empty statement. Use {} instead.')\r
- elif Search(r'^\s*;\s*$', line):\r
- error(filename, linenum, 'whitespace/semicolon', 5,\r
- 'Line contains only semicolon. If this should be an empty statement, '\r
- 'use {} instead.')\r
- elif (Search(r'\s+;\s*$', line) and\r
- not Search(r'\bfor\b', line)):\r
- error(filename, linenum, 'whitespace/semicolon', 5,\r
- 'Extra space before last semicolon. If this should be an empty '\r
- 'statement, use {} instead.')\r
-\r
-\r
-def IsDecltype(clean_lines, linenum, column):\r
- """Check if the token ending on (linenum, column) is decltype().\r
-\r
- Args:\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: the number of the line to check.\r
- column: end column of the token to check.\r
- Returns:\r
- True if this token is decltype() expression, False otherwise.\r
- """\r
- (text, _, start_col) = ReverseCloseExpression(clean_lines, linenum, column)\r
- if start_col < 0:\r
- return False\r
- if Search(r'\bdecltype\s*$', text[0:start_col]):\r
- return True\r
- return False\r
-\r
-\r
-def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error):\r
- """Checks for additional blank line issues related to sections.\r
-\r
- Currently the only thing checked here is blank line before protected/private.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- class_info: A _ClassInfo objects.\r
- linenum: The number of the line to check.\r
- error: The function to call with any errors found.\r
- """\r
- # Skip checks if the class is small, where small means 25 lines or less.\r
- # 25 lines seems like a good cutoff since that's the usual height of\r
- # terminals, and any class that can't fit in one screen can't really\r
- # be considered "small".\r
- #\r
- # Also skip checks if we are on the first line. This accounts for\r
- # classes that look like\r
- # class Foo { public: ... };\r
- #\r
- # If we didn't find the end of the class, last_line would be zero,\r
- # and the check will be skipped by the first condition.\r
- if (class_info.last_line - class_info.starting_linenum <= 24 or\r
- linenum <= class_info.starting_linenum):\r
- return\r
-\r
- matched = Match(r'\s*(public|protected|private):', clean_lines.lines[linenum])\r
- if matched:\r
- # Issue warning if the line before public/protected/private was\r
- # not a blank line, but don't do this if the previous line contains\r
- # "class" or "struct". This can happen two ways:\r
- # - We are at the beginning of the class.\r
- # - We are forward-declaring an inner class that is semantically\r
- # private, but needed to be public for implementation reasons.\r
- # Also ignores cases where the previous line ends with a backslash as can be\r
- # common when defining classes in C macros.\r
- prev_line = clean_lines.lines[linenum - 1]\r
- if (not IsBlankLine(prev_line) and\r
- not Search(r'\b(class|struct)\b', prev_line) and\r
- not Search(r'\\$', prev_line)):\r
- # Try a bit harder to find the beginning of the class. This is to\r
- # account for multi-line base-specifier lists, e.g.:\r
- # class Derived\r
- # : public Base {\r
- end_class_head = class_info.starting_linenum\r
- for i in range(class_info.starting_linenum, linenum):\r
- if Search(r'\{\s*$', clean_lines.lines[i]):\r
- end_class_head = i\r
- break\r
- if end_class_head < linenum - 1:\r
- error(filename, linenum, 'whitespace/blank_line', 3,\r
- '"%s:" should be preceded by a blank line' % matched.group(1))\r
-\r
-\r
-def GetPreviousNonBlankLine(clean_lines, linenum):\r
- """Return the most recent non-blank line and its line number.\r
-\r
- Args:\r
- clean_lines: A CleansedLines instance containing the file contents.\r
- linenum: The number of the line to check.\r
-\r
- Returns:\r
- A tuple with two elements. The first element is the contents of the last\r
- non-blank line before the current line, or the empty string if this is the\r
- first non-blank line. The second is the line number of that line, or -1\r
- if this is the first non-blank line.\r
- """\r
-\r
- prevlinenum = linenum - 1\r
- while prevlinenum >= 0:\r
- prevline = clean_lines.elided[prevlinenum]\r
- if not IsBlankLine(prevline): # if not a blank line...\r
- return (prevline, prevlinenum)\r
- prevlinenum -= 1\r
- return ('', -1)\r
-\r
-\r
-def CheckBraces(filename, clean_lines, linenum, error):\r
- """Looks for misplaced braces (e.g. at the end of line).\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- error: The function to call with any errors found.\r
- """\r
-\r
- line = clean_lines.elided[linenum] # get rid of comments and strings\r
-\r
- if Match(r'\s*{\s*$', line):\r
- # We allow an open brace to start a line in the case where someone is using\r
- # braces in a block to explicitly create a new scope, which is commonly used\r
- # to control the lifetime of stack-allocated variables. Braces are also\r
- # used for brace initializers inside function calls. We don't detect this\r
- # perfectly: we just don't complain if the last non-whitespace character on\r
- # the previous non-blank line is ',', ';', ':', '(', '{', or '}', or if the\r
- # previous line starts a preprocessor block. We also allow a brace on the\r
- # following line if it is part of an array initialization and would not fit\r
- # within the 80 character limit of the preceding line.\r
- prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]\r
- if (not Search(r'[,;:}{(]\s*$', prevline) and\r
- not Match(r'\s*#', prevline) and\r
- not (GetLineWidth(prevline) > _line_length - 2 and '[]' in prevline)):\r
- error(filename, linenum, 'whitespace/braces', 4,\r
- '{ should almost always be at the end of the previous line')\r
-\r
- # An else clause should be on the same line as the preceding closing brace.\r
- if Match(r'\s*else\b\s*(?:if\b|\{|$)', line):\r
- prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]\r
- if Match(r'\s*}\s*$', prevline):\r
- error(filename, linenum, 'whitespace/newline', 4,\r
- 'An else should appear on the same line as the preceding }')\r
-\r
- # If braces come on one side of an else, they should be on both.\r
- # However, we have to worry about "else if" that spans multiple lines!\r
- if Search(r'else if\s*\(', line): # could be multi-line if\r
- brace_on_left = bool(Search(r'}\s*else if\s*\(', line))\r
- # find the ( after the if\r
- pos = line.find('else if')\r
- pos = line.find('(', pos)\r
- if pos > 0:\r
- (endline, _, endpos) = CloseExpression(clean_lines, linenum, pos)\r
- brace_on_right = endline[endpos:].find('{') != -1\r
- if brace_on_left != brace_on_right: # must be brace after if\r
- error(filename, linenum, 'readability/braces', 5,\r
- 'If an else has a brace on one side, it should have it on both')\r
- elif Search(r'}\s*else[^{]*$', line) or Match(r'[^}]*else\s*{', line):\r
- error(filename, linenum, 'readability/braces', 5,\r
- 'If an else has a brace on one side, it should have it on both')\r
-\r
- # Likewise, an else should never have the else clause on the same line\r
- if Search(r'\belse [^\s{]', line) and not Search(r'\belse if\b', line):\r
- error(filename, linenum, 'whitespace/newline', 4,\r
- 'Else clause should never be on same line as else (use 2 lines)')\r
-\r
- # In the same way, a do/while should never be on one line\r
- if Match(r'\s*do [^\s{]', line):\r
- error(filename, linenum, 'whitespace/newline', 4,\r
- 'do/while clauses should not be on a single line')\r
-\r
- # Check single-line if/else bodies. The style guide says 'curly braces are not\r
- # required for single-line statements'. We additionally allow multi-line,\r
- # single statements, but we reject anything with more than one semicolon in\r
- # it. This means that the first semicolon after the if should be at the end of\r
- # its line, and the line after that should have an indent level equal to or\r
- # lower than the if. We also check for ambiguous if/else nesting without\r
- # braces.\r
- if_else_match = Search(r'\b(if\s*\(|else\b)', line)\r
- if if_else_match and not Match(r'\s*#', line):\r
- if_indent = GetIndentLevel(line)\r
- endline, endlinenum, endpos = line, linenum, if_else_match.end()\r
- if_match = Search(r'\bif\s*\(', line)\r
- if if_match:\r
- # This could be a multiline if condition, so find the end first.\r
- pos = if_match.end() - 1\r
- (endline, endlinenum, endpos) = CloseExpression(clean_lines, linenum, pos)\r
- # Check for an opening brace, either directly after the if or on the next\r
- # line. If found, this isn't a single-statement conditional.\r
- if (not Match(r'\s*{', endline[endpos:])\r
- and not (Match(r'\s*$', endline[endpos:])\r
- and endlinenum < (len(clean_lines.elided) - 1)\r
- and Match(r'\s*{', clean_lines.elided[endlinenum + 1]))):\r
- while (endlinenum < len(clean_lines.elided)\r
- and ';' not in clean_lines.elided[endlinenum][endpos:]):\r
- endlinenum += 1\r
- endpos = 0\r
- if endlinenum < len(clean_lines.elided):\r
- endline = clean_lines.elided[endlinenum]\r
- # We allow a mix of whitespace and closing braces (e.g. for one-liner\r
- # methods) and a single \ after the semicolon (for macros)\r
- endpos = endline.find(';')\r
- if not Match(r';[\s}]*(\\?)$', endline[endpos:]):\r
- # Semicolon isn't the last character, there's something trailing.\r
- # Output a warning if the semicolon is not contained inside\r
- # a lambda expression.\r
- if not Match(r'^[^{};]*\[[^\[\]]*\][^{}]*\{[^{}]*\}\s*\)*[;,]\s*$',\r
- endline):\r
- error(filename, linenum, 'readability/braces', 4,\r
- 'If/else bodies with multiple statements require braces')\r
- elif endlinenum < len(clean_lines.elided) - 1:\r
- # Make sure the next line is dedented\r
- next_line = clean_lines.elided[endlinenum + 1]\r
- next_indent = GetIndentLevel(next_line)\r
- # With ambiguous nested if statements, this will error out on the\r
- # if that *doesn't* match the else, regardless of whether it's the\r
- # inner one or outer one.\r
- if (if_match and Match(r'\s*else\b', next_line)\r
- and next_indent != if_indent):\r
- error(filename, linenum, 'readability/braces', 4,\r
- 'Else clause should be indented at the same level as if. '\r
- 'Ambiguous nested if/else chains require braces.')\r
- elif next_indent > if_indent:\r
- error(filename, linenum, 'readability/braces', 4,\r
- 'If/else bodies with multiple statements require braces')\r
-\r
-\r
-def CheckTrailingSemicolon(filename, clean_lines, linenum, error):\r
- """Looks for redundant trailing semicolon.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- error: The function to call with any errors found.\r
- """\r
-\r
- line = clean_lines.elided[linenum]\r
-\r
- # Block bodies should not be followed by a semicolon. Due to C++11\r
- # brace initialization, there are more places where semicolons are\r
- # required than not, so we use a whitelist approach to check these\r
- # rather than a blacklist. These are the places where "};" should\r
- # be replaced by just "}":\r
- # 1. Some flavor of block following closing parenthesis:\r
- # for (;;) {};\r
- # while (...) {};\r
- # switch (...) {};\r
- # Function(...) {};\r
- # if (...) {};\r
- # if (...) else if (...) {};\r
- #\r
- # 2. else block:\r
- # if (...) else {};\r
- #\r
- # 3. const member function:\r
- # Function(...) const {};\r
- #\r
- # 4. Block following some statement:\r
- # x = 42;\r
- # {};\r
- #\r
- # 5. Block at the beginning of a function:\r
- # Function(...) {\r
- # {};\r
- # }\r
- #\r
- # Note that naively checking for the preceding "{" will also match\r
- # braces inside multi-dimensional arrays, but this is fine since\r
- # that expression will not contain semicolons.\r
- #\r
- # 6. Block following another block:\r
- # while (true) {}\r
- # {};\r
- #\r
- # 7. End of namespaces:\r
- # namespace {};\r
- #\r
- # These semicolons seems far more common than other kinds of\r
- # redundant semicolons, possibly due to people converting classes\r
- # to namespaces. For now we do not warn for this case.\r
- #\r
- # Try matching case 1 first.\r
- match = Match(r'^(.*\)\s*)\{', line)\r
- if match:\r
- # Matched closing parenthesis (case 1). Check the token before the\r
- # matching opening parenthesis, and don't warn if it looks like a\r
- # macro. This avoids these false positives:\r
- # - macro that defines a base class\r
- # - multi-line macro that defines a base class\r
- # - macro that defines the whole class-head\r
- #\r
- # But we still issue warnings for macros that we know are safe to\r
- # warn, specifically:\r
- # - TEST, TEST_F, TEST_P, MATCHER, MATCHER_P\r
- # - TYPED_TEST\r
- # - INTERFACE_DEF\r
- # - EXCLUSIVE_LOCKS_REQUIRED, SHARED_LOCKS_REQUIRED, LOCKS_EXCLUDED:\r
- #\r
- # We implement a whitelist of safe macros instead of a blacklist of\r
- # unsafe macros, even though the latter appears less frequently in\r
- # google code and would have been easier to implement. This is because\r
- # the downside for getting the whitelist wrong means some extra\r
- # semicolons, while the downside for getting the blacklist wrong\r
- # would result in compile errors.\r
- #\r
- # In addition to macros, we also don't want to warn on\r
- # - Compound literals\r
- # - Lambdas\r
- # - alignas specifier with anonymous structs\r
- # - decltype\r
- closing_brace_pos = match.group(1).rfind(')')\r
- opening_parenthesis = ReverseCloseExpression(\r
- clean_lines, linenum, closing_brace_pos)\r
- if opening_parenthesis[2] > -1:\r
- line_prefix = opening_parenthesis[0][0:opening_parenthesis[2]]\r
- macro = Search(r'\b([A-Z_][A-Z0-9_]*)\s*$', line_prefix)\r
- func = Match(r'^(.*\])\s*$', line_prefix)\r
- if ((macro and\r
- macro.group(1) not in (\r
- 'TEST', 'TEST_F', 'MATCHER', 'MATCHER_P', 'TYPED_TEST',\r
- 'EXCLUSIVE_LOCKS_REQUIRED', 'SHARED_LOCKS_REQUIRED',\r
- 'LOCKS_EXCLUDED', 'INTERFACE_DEF')) or\r
- (func and not Search(r'\boperator\s*\[\s*\]', func.group(1))) or\r
- Search(r'\b(?:struct|union)\s+alignas\s*$', line_prefix) or\r
- Search(r'\bdecltype$', line_prefix) or\r
- Search(r'\s+=\s*$', line_prefix)):\r
- match = None\r
- if (match and\r
- opening_parenthesis[1] > 1 and\r
- Search(r'\]\s*$', clean_lines.elided[opening_parenthesis[1] - 1])):\r
- # Multi-line lambda-expression\r
- match = None\r
-\r
- else:\r
- # Try matching cases 2-3.\r
- match = Match(r'^(.*(?:else|\)\s*const)\s*)\{', line)\r
- if not match:\r
- # Try matching cases 4-6. These are always matched on separate lines.\r
- #\r
- # Note that we can't simply concatenate the previous line to the\r
- # current line and do a single match, otherwise we may output\r
- # duplicate warnings for the blank line case:\r
- # if (cond) {\r
- # // blank line\r
- # }\r
- prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]\r
- if prevline and Search(r'[;{}]\s*$', prevline):\r
- match = Match(r'^(\s*)\{', line)\r
-\r
- # Check matching closing brace\r
- if match:\r
- (endline, endlinenum, endpos) = CloseExpression(\r
- clean_lines, linenum, len(match.group(1)))\r
- if endpos > -1 and Match(r'^\s*;', endline[endpos:]):\r
- # Current {} pair is eligible for semicolon check, and we have found\r
- # the redundant semicolon, output warning here.\r
- #\r
- # Note: because we are scanning forward for opening braces, and\r
- # outputting warnings for the matching closing brace, if there are\r
- # nested blocks with trailing semicolons, we will get the error\r
- # messages in reversed order.\r
-\r
- # We need to check the line forward for NOLINT\r
- raw_lines = clean_lines.raw_lines\r
- ParseNolintSuppressions(filename, raw_lines[endlinenum-1], endlinenum-1,\r
- error)\r
- ParseNolintSuppressions(filename, raw_lines[endlinenum], endlinenum,\r
- error)\r
-\r
- error(filename, endlinenum, 'readability/braces', 4,\r
- "You don't need a ; after a }")\r
-\r
-\r
-def CheckEmptyBlockBody(filename, clean_lines, linenum, error):\r
- """Look for empty loop/conditional body with only a single semicolon.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- error: The function to call with any errors found.\r
- """\r
-\r
- # Search for loop keywords at the beginning of the line. Because only\r
- # whitespaces are allowed before the keywords, this will also ignore most\r
- # do-while-loops, since those lines should start with closing brace.\r
- #\r
- # We also check "if" blocks here, since an empty conditional block\r
- # is likely an error.\r
- line = clean_lines.elided[linenum]\r
- matched = Match(r'\s*(for|while|if)\s*\(', line)\r
- if matched:\r
- # Find the end of the conditional expression.\r
- (end_line, end_linenum, end_pos) = CloseExpression(\r
- clean_lines, linenum, line.find('('))\r
-\r
- # Output warning if what follows the condition expression is a semicolon.\r
- # No warning for all other cases, including whitespace or newline, since we\r
- # have a separate check for semicolons preceded by whitespace.\r
- if end_pos >= 0 and Match(r';', end_line[end_pos:]):\r
- if matched.group(1) == 'if':\r
- error(filename, end_linenum, 'whitespace/empty_conditional_body', 5,\r
- 'Empty conditional bodies should use {}')\r
- else:\r
- error(filename, end_linenum, 'whitespace/empty_loop_body', 5,\r
- 'Empty loop bodies should use {} or continue')\r
-\r
- # Check for if statements that have completely empty bodies (no comments)\r
- # and no else clauses.\r
- if end_pos >= 0 and matched.group(1) == 'if':\r
- # Find the position of the opening { for the if statement.\r
- # Return without logging an error if it has no brackets.\r
- opening_linenum = end_linenum\r
- opening_line_fragment = end_line[end_pos:]\r
- # Loop until EOF or find anything that's not whitespace or opening {.\r
- while not Search(r'^\s*\{', opening_line_fragment):\r
- if Search(r'^(?!\s*$)', opening_line_fragment):\r
- # Conditional has no brackets.\r
- return\r
- opening_linenum += 1\r
- if opening_linenum == len(clean_lines.elided):\r
- # Couldn't find conditional's opening { or any code before EOF.\r
- return\r
- opening_line_fragment = clean_lines.elided[opening_linenum]\r
- # Set opening_line (opening_line_fragment may not be entire opening line).\r
- opening_line = clean_lines.elided[opening_linenum]\r
-\r
- # Find the position of the closing }.\r
- opening_pos = opening_line_fragment.find('{')\r
- if opening_linenum == end_linenum:\r
- # We need to make opening_pos relative to the start of the entire line.\r
- opening_pos += end_pos\r
- (closing_line, closing_linenum, closing_pos) = CloseExpression(\r
- clean_lines, opening_linenum, opening_pos)\r
- if closing_pos < 0:\r
- return\r
-\r
- # Now construct the body of the conditional. This consists of the portion\r
- # of the opening line after the {, all lines until the closing line,\r
- # and the portion of the closing line before the }.\r
- if (clean_lines.raw_lines[opening_linenum] !=\r
- CleanseComments(clean_lines.raw_lines[opening_linenum])):\r
- # Opening line ends with a comment, so conditional isn't empty.\r
- return\r
- if closing_linenum > opening_linenum:\r
- # Opening line after the {. Ignore comments here since we checked above.\r
- body = list(opening_line[opening_pos+1:])\r
- # All lines until closing line, excluding closing line, with comments.\r
- body.extend(clean_lines.raw_lines[opening_linenum+1:closing_linenum])\r
- # Closing line before the }. Won't (and can't) have comments.\r
- body.append(clean_lines.elided[closing_linenum][:closing_pos-1])\r
- body = '\n'.join(body)\r
- else:\r
- # If statement has brackets and fits on a single line.\r
- body = opening_line[opening_pos+1:closing_pos-1]\r
-\r
- # Check if the body is empty\r
- if not _EMPTY_CONDITIONAL_BODY_PATTERN.search(body):\r
- return\r
- # The body is empty. Now make sure there's not an else clause.\r
- current_linenum = closing_linenum\r
- current_line_fragment = closing_line[closing_pos:]\r
- # Loop until EOF or find anything that's not whitespace or else clause.\r
- while Search(r'^\s*$|^(?=\s*else)', current_line_fragment):\r
- if Search(r'^(?=\s*else)', current_line_fragment):\r
- # Found an else clause, so don't log an error.\r
- return\r
- current_linenum += 1\r
- if current_linenum == len(clean_lines.elided):\r
- break\r
- current_line_fragment = clean_lines.elided[current_linenum]\r
-\r
- # The body is empty and there's no else clause until EOF or other code.\r
- error(filename, end_linenum, 'whitespace/empty_if_body', 4,\r
- ('If statement had no body and no else clause'))\r
-\r
-\r
-def FindCheckMacro(line):\r
- """Find a replaceable CHECK-like macro.\r
-\r
- Args:\r
- line: line to search on.\r
- Returns:\r
- (macro name, start position), or (None, -1) if no replaceable\r
- macro is found.\r
- """\r
- for macro in _CHECK_MACROS:\r
- i = line.find(macro)\r
- if i >= 0:\r
- # Find opening parenthesis. Do a regular expression match here\r
- # to make sure that we are matching the expected CHECK macro, as\r
- # opposed to some other macro that happens to contain the CHECK\r
- # substring.\r
- matched = Match(r'^(.*\b' + macro + r'\s*)\(', line)\r
- if not matched:\r
- continue\r
- return (macro, len(matched.group(1)))\r
- return (None, -1)\r
-\r
-\r
-def CheckCheck(filename, clean_lines, linenum, error):\r
- """Checks the use of CHECK and EXPECT macros.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- error: The function to call with any errors found.\r
- """\r
-\r
- # Decide the set of replacement macros that should be suggested\r
- lines = clean_lines.elided\r
- (check_macro, start_pos) = FindCheckMacro(lines[linenum])\r
- if not check_macro:\r
- return\r
-\r
- # Find end of the boolean expression by matching parentheses\r
- (last_line, end_line, end_pos) = CloseExpression(\r
- clean_lines, linenum, start_pos)\r
- if end_pos < 0:\r
- return\r
-\r
- # If the check macro is followed by something other than a\r
- # semicolon, assume users will log their own custom error messages\r
- # and don't suggest any replacements.\r
- if not Match(r'\s*;', last_line[end_pos:]):\r
- return\r
-\r
- if linenum == end_line:\r
- expression = lines[linenum][start_pos + 1:end_pos - 1]\r
- else:\r
- expression = lines[linenum][start_pos + 1:]\r
- for i in xrange(linenum + 1, end_line):\r
- expression += lines[i]\r
- expression += last_line[0:end_pos - 1]\r
-\r
- # Parse expression so that we can take parentheses into account.\r
- # This avoids false positives for inputs like "CHECK((a < 4) == b)",\r
- # which is not replaceable by CHECK_LE.\r
- lhs = ''\r
- rhs = ''\r
- operator = None\r
- while expression:\r
- matched = Match(r'^\s*(<<|<<=|>>|>>=|->\*|->|&&|\|\||'\r
- r'==|!=|>=|>|<=|<|\()(.*)$', expression)\r
- if matched:\r
- token = matched.group(1)\r
- if token == '(':\r
- # Parenthesized operand\r
- expression = matched.group(2)\r
- (end, _) = FindEndOfExpressionInLine(expression, 0, ['('])\r
- if end < 0:\r
- return # Unmatched parenthesis\r
- lhs += '(' + expression[0:end]\r
- expression = expression[end:]\r
- elif token in ('&&', '||'):\r
- # Logical and/or operators. This means the expression\r
- # contains more than one term, for example:\r
- # CHECK(42 < a && a < b);\r
- #\r
- # These are not replaceable with CHECK_LE, so bail out early.\r
- return\r
- elif token in ('<<', '<<=', '>>', '>>=', '->*', '->'):\r
- # Non-relational operator\r
- lhs += token\r
- expression = matched.group(2)\r
- else:\r
- # Relational operator\r
- operator = token\r
- rhs = matched.group(2)\r
- break\r
- else:\r
- # Unparenthesized operand. Instead of appending to lhs one character\r
- # at a time, we do another regular expression match to consume several\r
- # characters at once if possible. Trivial benchmark shows that this\r
- # is more efficient when the operands are longer than a single\r
- # character, which is generally the case.\r
- matched = Match(r'^([^-=!<>()&|]+)(.*)$', expression)\r
- if not matched:\r
- matched = Match(r'^(\s*\S)(.*)$', expression)\r
- if not matched:\r
- break\r
- lhs += matched.group(1)\r
- expression = matched.group(2)\r
-\r
- # Only apply checks if we got all parts of the boolean expression\r
- if not (lhs and operator and rhs):\r
- return\r
-\r
- # Check that rhs do not contain logical operators. We already know\r
- # that lhs is fine since the loop above parses out && and ||.\r
- if rhs.find('&&') > -1 or rhs.find('||') > -1:\r
- return\r
-\r
- # At least one of the operands must be a constant literal. This is\r
- # to avoid suggesting replacements for unprintable things like\r
- # CHECK(variable != iterator)\r
- #\r
- # The following pattern matches decimal, hex integers, strings, and\r
- # characters (in that order).\r
- lhs = lhs.strip()\r
- rhs = rhs.strip()\r
- match_constant = r'^([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')$'\r
- if Match(match_constant, lhs) or Match(match_constant, rhs):\r
- # Note: since we know both lhs and rhs, we can provide a more\r
- # descriptive error message like:\r
- # Consider using CHECK_EQ(x, 42) instead of CHECK(x == 42)\r
- # Instead of:\r
- # Consider using CHECK_EQ instead of CHECK(a == b)\r
- #\r
- # We are still keeping the less descriptive message because if lhs\r
- # or rhs gets long, the error message might become unreadable.\r
- error(filename, linenum, 'readability/check', 2,\r
- 'Consider using %s instead of %s(a %s b)' % (\r
- _CHECK_REPLACEMENT[check_macro][operator],\r
- check_macro, operator))\r
-\r
-\r
-def CheckAltTokens(filename, clean_lines, linenum, error):\r
- """Check alternative keywords being used in boolean expressions.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- error: The function to call with any errors found.\r
- """\r
- line = clean_lines.elided[linenum]\r
-\r
- # Avoid preprocessor lines\r
- if Match(r'^\s*#', line):\r
- return\r
-\r
- # Last ditch effort to avoid multi-line comments. This will not help\r
- # if the comment started before the current line or ended after the\r
- # current line, but it catches most of the false positives. At least,\r
- # it provides a way to workaround this warning for people who use\r
- # multi-line comments in preprocessor macros.\r
- #\r
- # TODO(unknown): remove this once cpplint has better support for\r
- # multi-line comments.\r
- if line.find('/*') >= 0 or line.find('*/') >= 0:\r
- return\r
-\r
- for match in _ALT_TOKEN_REPLACEMENT_PATTERN.finditer(line):\r
- error(filename, linenum, 'readability/alt_tokens', 2,\r
- 'Use operator %s instead of %s' % (\r
- _ALT_TOKEN_REPLACEMENT[match.group(1)], match.group(1)))\r
-\r
-\r
-def GetLineWidth(line):\r
- """Determines the width of the line in column positions.\r
-\r
- Args:\r
- line: A string, which may be a Unicode string.\r
-\r
- Returns:\r
- The width of the line in column positions, accounting for Unicode\r
- combining characters and wide characters.\r
- """\r
- if isinstance(line, unicode):\r
- width = 0\r
- for uc in unicodedata.normalize('NFC', line):\r
- if unicodedata.east_asian_width(uc) in ('W', 'F'):\r
- width += 2\r
- elif not unicodedata.combining(uc):\r
- width += 1\r
- return width\r
- else:\r
- return len(line)\r
-\r
-\r
-def CheckStyle(filename, clean_lines, linenum, file_extension, nesting_state,\r
- error):\r
- """Checks rules from the 'C++ style rules' section of cppguide.html.\r
-\r
- Most of these rules are hard to test (naming, comment style), but we\r
- do what we can. In particular we check for 2-space indents, line lengths,\r
- tab usage, spaces inside code, etc.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- file_extension: The extension (without the dot) of the filename.\r
- nesting_state: A NestingState instance which maintains information about\r
- the current stack of nested blocks being parsed.\r
- error: The function to call with any errors found.\r
- """\r
-\r
- # Don't use "elided" lines here, otherwise we can't check commented lines.\r
- # Don't want to use "raw" either, because we don't want to check inside C++11\r
- # raw strings,\r
- raw_lines = clean_lines.lines_without_raw_strings\r
- line = raw_lines[linenum]\r
- prev = raw_lines[linenum - 1] if linenum > 0 else ''\r
-\r
- if line.find('\t') != -1:\r
- error(filename, linenum, 'whitespace/tab', 1,\r
- 'Tab found; better to use spaces')\r
-\r
- # One or three blank spaces at the beginning of the line is weird; it's\r
- # hard to reconcile that with 2-space indents.\r
- # NOTE: here are the conditions rob pike used for his tests. Mine aren't\r
- # as sophisticated, but it may be worth becoming so: RLENGTH==initial_spaces\r
- # if(RLENGTH > 20) complain = 0;\r
- # if(match($0, " +(error|private|public|protected):")) complain = 0;\r
- # if(match(prev, "&& *$")) complain = 0;\r
- # if(match(prev, "\\|\\| *$")) complain = 0;\r
- # if(match(prev, "[\",=><] *$")) complain = 0;\r
- # if(match($0, " <<")) complain = 0;\r
- # if(match(prev, " +for \\(")) complain = 0;\r
- # if(prevodd && match(prevprev, " +for \\(")) complain = 0;\r
- scope_or_label_pattern = r'\s*\w+\s*:\s*\\?$'\r
- classinfo = nesting_state.InnermostClass()\r
- initial_spaces = 0\r
- cleansed_line = clean_lines.elided[linenum]\r
- while initial_spaces < len(line) and line[initial_spaces] == ' ':\r
- initial_spaces += 1\r
- # There are certain situations we allow one space, notably for\r
- # section labels, and also lines containing multi-line raw strings.\r
- # We also don't check for lines that look like continuation lines\r
- # (of lines ending in double quotes, commas, equals, or angle brackets)\r
- # because the rules for how to indent those are non-trivial.\r
- if (not Search(r'[",=><] *$', prev) and\r
- (initial_spaces == 1 or initial_spaces == 3) and\r
- not Match(scope_or_label_pattern, cleansed_line) and\r
- not (clean_lines.raw_lines[linenum] != line and\r
- Match(r'^\s*""', line))):\r
- error(filename, linenum, 'whitespace/indent', 3,\r
- 'Weird number of spaces at line-start. '\r
- 'Are you using a 2-space indent?')\r
-\r
- if line and line[-1].isspace():\r
- error(filename, linenum, 'whitespace/end_of_line', 4,\r
- 'Line ends in whitespace. Consider deleting these extra spaces.')\r
-\r
- # Check if the line is a header guard.\r
- is_header_guard = False\r
- if IsHeaderExtension(file_extension):\r
- cppvar = GetHeaderGuardCPPVariable(filename)\r
- if (line.startswith('#ifndef %s' % cppvar) or\r
- line.startswith('#define %s' % cppvar) or\r
- line.startswith('#endif // %s' % cppvar)):\r
- is_header_guard = True\r
- # #include lines and header guards can be long, since there's no clean way to\r
- # split them.\r
- #\r
- # URLs can be long too. It's possible to split these, but it makes them\r
- # harder to cut&paste.\r
- #\r
- # The "$Id:...$" comment may also get very long without it being the\r
- # developers fault.\r
- if (not line.startswith('#include') and not is_header_guard and\r
- not Match(r'^\s*//.*http(s?)://\S*$', line) and\r
- not Match(r'^\s*//\s*[^\s]*$', line) and\r
- not Match(r'^// \$Id:.*#[0-9]+ \$$', line)):\r
- line_width = GetLineWidth(line)\r
- if line_width > _line_length:\r
- error(filename, linenum, 'whitespace/line_length', 2,\r
- 'Lines should be <= %i characters long' % _line_length)\r
-\r
- if (cleansed_line.count(';') > 1 and\r
- # for loops are allowed two ;'s (and may run over two lines).\r
- cleansed_line.find('for') == -1 and\r
- (GetPreviousNonBlankLine(clean_lines, linenum)[0].find('for') == -1 or\r
- GetPreviousNonBlankLine(clean_lines, linenum)[0].find(';') != -1) and\r
- # It's ok to have many commands in a switch case that fits in 1 line\r
- not ((cleansed_line.find('case ') != -1 or\r
- cleansed_line.find('default:') != -1) and\r
- cleansed_line.find('break;') != -1)):\r
- error(filename, linenum, 'whitespace/newline', 0,\r
- 'More than one command on the same line')\r
-\r
- # Some more style checks\r
- CheckBraces(filename, clean_lines, linenum, error)\r
- CheckTrailingSemicolon(filename, clean_lines, linenum, error)\r
- CheckEmptyBlockBody(filename, clean_lines, linenum, error)\r
- CheckSpacing(filename, clean_lines, linenum, nesting_state, error)\r
- CheckOperatorSpacing(filename, clean_lines, linenum, error)\r
- CheckParenthesisSpacing(filename, clean_lines, linenum, error)\r
- CheckCommaSpacing(filename, clean_lines, linenum, error)\r
- CheckBracesSpacing(filename, clean_lines, linenum, nesting_state, error)\r
- CheckSpacingForFunctionCall(filename, clean_lines, linenum, error)\r
- CheckCheck(filename, clean_lines, linenum, error)\r
- CheckAltTokens(filename, clean_lines, linenum, error)\r
- classinfo = nesting_state.InnermostClass()\r
- if classinfo:\r
- CheckSectionSpacing(filename, clean_lines, classinfo, linenum, error)\r
-\r
-\r
-_RE_PATTERN_INCLUDE = re.compile(r'^\s*#\s*include\s*([<"])([^>"]*)[>"].*$')\r
-# Matches the first component of a filename delimited by -s and _s. That is:\r
-# _RE_FIRST_COMPONENT.match('foo').group(0) == 'foo'\r
-# _RE_FIRST_COMPONENT.match('foo.cc').group(0) == 'foo'\r
-# _RE_FIRST_COMPONENT.match('foo-bar_baz.cc').group(0) == 'foo'\r
-# _RE_FIRST_COMPONENT.match('foo_bar-baz.cc').group(0) == 'foo'\r
-_RE_FIRST_COMPONENT = re.compile(r'^[^-_.]+')\r
-\r
-\r
-def _DropCommonSuffixes(filename):\r
- """Drops common suffixes like _test.cc or -inl.h from filename.\r
-\r
- For example:\r
- >>> _DropCommonSuffixes('foo/foo-inl.h')\r
- 'foo/foo'\r
- >>> _DropCommonSuffixes('foo/bar/foo.cc')\r
- 'foo/bar/foo'\r
- >>> _DropCommonSuffixes('foo/foo_internal.h')\r
- 'foo/foo'\r
- >>> _DropCommonSuffixes('foo/foo_unusualinternal.h')\r
- 'foo/foo_unusualinternal'\r
-\r
- Args:\r
- filename: The input filename.\r
-\r
- Returns:\r
- The filename with the common suffix removed.\r
- """\r
- for suffix in ('test.cc', 'regtest.cc', 'unittest.cc',\r
- 'inl.h', 'impl.h', 'internal.h'):\r
- if (filename.endswith(suffix) and len(filename) > len(suffix) and\r
- filename[-len(suffix) - 1] in ('-', '_')):\r
- return filename[:-len(suffix) - 1]\r
- return os.path.splitext(filename)[0]\r
-\r
-\r
-def _ClassifyInclude(fileinfo, include, is_system):\r
- """Figures out what kind of header 'include' is.\r
-\r
- Args:\r
- fileinfo: The current file cpplint is running over. A FileInfo instance.\r
- include: The path to a #included file.\r
- is_system: True if the #include used <> rather than "".\r
-\r
- Returns:\r
- One of the _XXX_HEADER constants.\r
-\r
- For example:\r
- >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'stdio.h', True)\r
- _C_SYS_HEADER\r
- >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'string', True)\r
- _CPP_SYS_HEADER\r
- >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', False)\r
- _LIKELY_MY_HEADER\r
- >>> _ClassifyInclude(FileInfo('foo/foo_unknown_extension.cc'),\r
- ... 'bar/foo_other_ext.h', False)\r
- _POSSIBLE_MY_HEADER\r
- >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/bar.h', False)\r
- _OTHER_HEADER\r
- """\r
- # This is a list of all standard c++ header files, except\r
- # those already checked for above.\r
- is_cpp_h = include in _CPP_HEADERS\r
-\r
- if is_system:\r
- if is_cpp_h:\r
- return _CPP_SYS_HEADER\r
- else:\r
- return _C_SYS_HEADER\r
-\r
- # If the target file and the include we're checking share a\r
- # basename when we drop common extensions, and the include\r
- # lives in . , then it's likely to be owned by the target file.\r
- target_dir, target_base = (\r
- os.path.split(_DropCommonSuffixes(fileinfo.RepositoryName())))\r
- include_dir, include_base = os.path.split(_DropCommonSuffixes(include))\r
- if target_base == include_base and (\r
- include_dir == target_dir or\r
- include_dir == os.path.normpath(target_dir + '/../public')):\r
- return _LIKELY_MY_HEADER\r
-\r
- # If the target and include share some initial basename\r
- # component, it's possible the target is implementing the\r
- # include, so it's allowed to be first, but we'll never\r
- # complain if it's not there.\r
- target_first_component = _RE_FIRST_COMPONENT.match(target_base)\r
- include_first_component = _RE_FIRST_COMPONENT.match(include_base)\r
- if (target_first_component and include_first_component and\r
- target_first_component.group(0) ==\r
- include_first_component.group(0)):\r
- return _POSSIBLE_MY_HEADER\r
-\r
- return _OTHER_HEADER\r
-\r
-\r
-\r
-def CheckIncludeLine(filename, clean_lines, linenum, include_state, error):\r
- """Check rules that are applicable to #include lines.\r
-\r
- Strings on #include lines are NOT removed from elided line, to make\r
- certain tasks easier. However, to prevent false positives, checks\r
- applicable to #include lines in CheckLanguage must be put here.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- include_state: An _IncludeState instance in which the headers are inserted.\r
- error: The function to call with any errors found.\r
- """\r
- fileinfo = FileInfo(filename)\r
- line = clean_lines.lines[linenum]\r
-\r
- # "include" should use the new style "foo/bar.h" instead of just "bar.h"\r
- # Only do this check if the included header follows google naming\r
- # conventions. If not, assume that it's a 3rd party API that\r
- # requires special include conventions.\r
- #\r
- # We also make an exception for Lua headers, which follow google\r
- # naming convention but not the include convention.\r
- match = Match(r'#include\s*"([^/]+\.h)"', line)\r
- if match and not _THIRD_PARTY_HEADERS_PATTERN.match(match.group(1)):\r
- error(filename, linenum, 'build/include', 4,\r
- 'Include the directory when naming .h files')\r
-\r
- # we shouldn't include a file more than once. actually, there are a\r
- # handful of instances where doing so is okay, but in general it's\r
- # not.\r
- match = _RE_PATTERN_INCLUDE.search(line)\r
- if match:\r
- include = match.group(2)\r
- is_system = (match.group(1) == '<')\r
- duplicate_line = include_state.FindHeader(include)\r
- if duplicate_line >= 0:\r
- error(filename, linenum, 'build/include', 4,\r
- '"%s" already included at %s:%s' %\r
- (include, filename, duplicate_line))\r
- elif (include.endswith('.cc') and\r
- os.path.dirname(fileinfo.RepositoryName()) != os.path.dirname(include)):\r
- error(filename, linenum, 'build/include', 4,\r
- 'Do not include .cc files from other packages')\r
- elif not _THIRD_PARTY_HEADERS_PATTERN.match(include):\r
- include_state.include_list[-1].append((include, linenum))\r
-\r
- # We want to ensure that headers appear in the right order:\r
- # 1) for foo.cc, foo.h (preferred location)\r
- # 2) c system files\r
- # 3) cpp system files\r
- # 4) for foo.cc, foo.h (deprecated location)\r
- # 5) other google headers\r
- #\r
- # We classify each include statement as one of those 5 types\r
- # using a number of techniques. The include_state object keeps\r
- # track of the highest type seen, and complains if we see a\r
- # lower type after that.\r
- error_message = include_state.CheckNextIncludeOrder(\r
- _ClassifyInclude(fileinfo, include, is_system))\r
- if error_message:\r
- error(filename, linenum, 'build/include_order', 4,\r
- '%s. Should be: %s.h, c system, c++ system, other.' %\r
- (error_message, fileinfo.BaseName()))\r
- canonical_include = include_state.CanonicalizeAlphabeticalOrder(include)\r
- if not include_state.IsInAlphabeticalOrder(\r
- clean_lines, linenum, canonical_include):\r
- error(filename, linenum, 'build/include_alpha', 4,\r
- 'Include "%s" not in alphabetical order' % include)\r
- include_state.SetLastHeader(canonical_include)\r
-\r
-\r
-\r
-def _GetTextInside(text, start_pattern):\r
- r"""Retrieves all the text between matching open and close parentheses.\r
-\r
- Given a string of lines and a regular expression string, retrieve all the text\r
- following the expression and between opening punctuation symbols like\r
- (, [, or {, and the matching close-punctuation symbol. This properly nested\r
- occurrences of the punctuations, so for the text like\r
- printf(a(), b(c()));\r
- a call to _GetTextInside(text, r'printf\(') will return 'a(), b(c())'.\r
- start_pattern must match string having an open punctuation symbol at the end.\r
-\r
- Args:\r
- text: The lines to extract text. Its comments and strings must be elided.\r
- It can be single line and can span multiple lines.\r
- start_pattern: The regexp string indicating where to start extracting\r
- the text.\r
- Returns:\r
- The extracted text.\r
- None if either the opening string or ending punctuation could not be found.\r
- """\r
- # TODO(unknown): Audit cpplint.py to see what places could be profitably\r
- # rewritten to use _GetTextInside (and use inferior regexp matching today).\r
-\r
- # Give opening punctuations to get the matching close-punctuations.\r
- matching_punctuation = {'(': ')', '{': '}', '[': ']'}\r
- closing_punctuation = set(matching_punctuation.itervalues())\r
-\r
- # Find the position to start extracting text.\r
- match = re.search(start_pattern, text, re.M)\r
- if not match: # start_pattern not found in text.\r
- return None\r
- start_position = match.end(0)\r
-\r
- assert start_position > 0, (\r
- 'start_pattern must ends with an opening punctuation.')\r
- assert text[start_position - 1] in matching_punctuation, (\r
- 'start_pattern must ends with an opening punctuation.')\r
- # Stack of closing punctuations we expect to have in text after position.\r
- punctuation_stack = [matching_punctuation[text[start_position - 1]]]\r
- position = start_position\r
- while punctuation_stack and position < len(text):\r
- if text[position] == punctuation_stack[-1]:\r
- punctuation_stack.pop()\r
- elif text[position] in closing_punctuation:\r
- # A closing punctuation without matching opening punctuations.\r
- return None\r
- elif text[position] in matching_punctuation:\r
- punctuation_stack.append(matching_punctuation[text[position]])\r
- position += 1\r
- if punctuation_stack:\r
- # Opening punctuations left without matching close-punctuations.\r
- return None\r
- # punctuations match.\r
- return text[start_position:position - 1]\r
-\r
-\r
-# Patterns for matching call-by-reference parameters.\r
-#\r
-# Supports nested templates up to 2 levels deep using this messy pattern:\r
-# < (?: < (?: < [^<>]*\r
-# >\r
-# | [^<>] )*\r
-# >\r
-# | [^<>] )*\r
-# >\r
-_RE_PATTERN_IDENT = r'[_a-zA-Z]\w*' # =~ [[:alpha:]][[:alnum:]]*\r
-_RE_PATTERN_TYPE = (\r
- r'(?:const\s+)?(?:typename\s+|class\s+|struct\s+|union\s+|enum\s+)?'\r
- r'(?:\w|'\r
- r'\s*<(?:<(?:<[^<>]*>|[^<>])*>|[^<>])*>|'\r
- r'::)+')\r
-# A call-by-reference parameter ends with '& identifier'.\r
-_RE_PATTERN_REF_PARAM = re.compile(\r
- r'(' + _RE_PATTERN_TYPE + r'(?:\s*(?:\bconst\b|[*]))*\s*'\r
- r'&\s*' + _RE_PATTERN_IDENT + r')\s*(?:=[^,()]+)?[,)]')\r
-# A call-by-const-reference parameter either ends with 'const& identifier'\r
-# or looks like 'const type& identifier' when 'type' is atomic.\r
-_RE_PATTERN_CONST_REF_PARAM = (\r
- r'(?:.*\s*\bconst\s*&\s*' + _RE_PATTERN_IDENT +\r
- r'|const\s+' + _RE_PATTERN_TYPE + r'\s*&\s*' + _RE_PATTERN_IDENT + r')')\r
-# Stream types.\r
-_RE_PATTERN_REF_STREAM_PARAM = (\r
- r'(?:.*stream\s*&\s*' + _RE_PATTERN_IDENT + r')')\r
-\r
-\r
-def CheckLanguage(filename, clean_lines, linenum, file_extension,\r
- include_state, nesting_state, error):\r
- """Checks rules from the 'C++ language rules' section of cppguide.html.\r
-\r
- Some of these rules are hard to test (function overloading, using\r
- uint32 inappropriately), but we do the best we can.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- file_extension: The extension (without the dot) of the filename.\r
- include_state: An _IncludeState instance in which the headers are inserted.\r
- nesting_state: A NestingState instance which maintains information about\r
- the current stack of nested blocks being parsed.\r
- error: The function to call with any errors found.\r
- """\r
- # If the line is empty or consists of entirely a comment, no need to\r
- # check it.\r
- line = clean_lines.elided[linenum]\r
- if not line:\r
- return\r
-\r
- match = _RE_PATTERN_INCLUDE.search(line)\r
- if match:\r
- CheckIncludeLine(filename, clean_lines, linenum, include_state, error)\r
- return\r
-\r
- # Reset include state across preprocessor directives. This is meant\r
- # to silence warnings for conditional includes.\r
- match = Match(r'^\s*#\s*(if|ifdef|ifndef|elif|else|endif)\b', line)\r
- if match:\r
- include_state.ResetSection(match.group(1))\r
-\r
- # Make Windows paths like Unix.\r
- fullname = os.path.abspath(filename).replace('\\', '/')\r
-\r
- # Perform other checks now that we are sure that this is not an include line\r
- CheckCasts(filename, clean_lines, linenum, error)\r
- CheckGlobalStatic(filename, clean_lines, linenum, error)\r
- CheckPrintf(filename, clean_lines, linenum, error)\r
-\r
- if IsHeaderExtension(file_extension):\r
- # TODO(unknown): check that 1-arg constructors are explicit.\r
- # How to tell it's a constructor?\r
- # (handled in CheckForNonStandardConstructs for now)\r
- # TODO(unknown): check that classes declare or disable copy/assign\r
- # (level 1 error)\r
- pass\r
-\r
- # Check if people are using the verboten C basic types. The only exception\r
- # we regularly allow is "unsigned short port" for port.\r
- if Search(r'\bshort port\b', line):\r
- if not Search(r'\bunsigned short port\b', line):\r
- error(filename, linenum, 'runtime/int', 4,\r
- 'Use "unsigned short" for ports, not "short"')\r
- else:\r
- match = Search(r'\b(short|long(?! +double)|long long)\b', line)\r
- if match:\r
- error(filename, linenum, 'runtime/int', 4,\r
- 'Use int16/int64/etc, rather than the C type %s' % match.group(1))\r
-\r
- # Check if some verboten operator overloading is going on\r
- # TODO(unknown): catch out-of-line unary operator&:\r
- # class X {};\r
- # int operator&(const X& x) { return 42; } // unary operator&\r
- # The trick is it's hard to tell apart from binary operator&:\r
- # class Y { int operator&(const Y& x) { return 23; } }; // binary operator&\r
- if Search(r'\boperator\s*&\s*\(\s*\)', line):\r
- error(filename, linenum, 'runtime/operator', 4,\r
- 'Unary operator& is dangerous. Do not use it.')\r
-\r
- # Check for suspicious usage of "if" like\r
- # } if (a == b) {\r
- if Search(r'\}\s*if\s*\(', line):\r
- error(filename, linenum, 'readability/braces', 4,\r
- 'Did you mean "else if"? If not, start a new line for "if".')\r
-\r
- # Check for potential format string bugs like printf(foo).\r
- # We constrain the pattern not to pick things like DocidForPrintf(foo).\r
- # Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str())\r
- # TODO(unknown): Catch the following case. Need to change the calling\r
- # convention of the whole function to process multiple line to handle it.\r
- # printf(\r
- # boy_this_is_a_really_long_variable_that_cannot_fit_on_the_prev_line);\r
- printf_args = _GetTextInside(line, r'(?i)\b(string)?printf\s*\(')\r
- if printf_args:\r
- match = Match(r'([\w.\->()]+)$', printf_args)\r
- if match and match.group(1) != '__VA_ARGS__':\r
- function_name = re.search(r'\b((?:string)?printf)\s*\(',\r
- line, re.I).group(1)\r
- error(filename, linenum, 'runtime/printf', 4,\r
- 'Potential format string bug. Do %s("%%s", %s) instead.'\r
- % (function_name, match.group(1)))\r
-\r
- # Check for potential memset bugs like memset(buf, sizeof(buf), 0).\r
- match = Search(r'memset\s*\(([^,]*),\s*([^,]*),\s*0\s*\)', line)\r
- if match and not Match(r"^''|-?[0-9]+|0x[0-9A-Fa-f]$", match.group(2)):\r
- error(filename, linenum, 'runtime/memset', 4,\r
- 'Did you mean "memset(%s, 0, %s)"?'\r
- % (match.group(1), match.group(2)))\r
-\r
- if Search(r'\busing namespace\b', line):\r
- error(filename, linenum, 'build/namespaces', 5,\r
- 'Do not use namespace using-directives. '\r
- 'Use using-declarations instead.')\r
-\r
- # Detect variable-length arrays.\r
- match = Match(r'\s*(.+::)?(\w+) [a-z]\w*\[(.+)];', line)\r
- if (match and match.group(2) != 'return' and match.group(2) != 'delete' and\r
- match.group(3).find(']') == -1):\r
- # Split the size using space and arithmetic operators as delimiters.\r
- # If any of the resulting tokens are not compile time constants then\r
- # report the error.\r
- tokens = re.split(r'\s|\+|\-|\*|\/|<<|>>]', match.group(3))\r
- is_const = True\r
- skip_next = False\r
- for tok in tokens:\r
- if skip_next:\r
- skip_next = False\r
- continue\r
-\r
- if Search(r'sizeof\(.+\)', tok): continue\r
- if Search(r'arraysize\(\w+\)', tok): continue\r
-\r
- tok = tok.lstrip('(')\r
- tok = tok.rstrip(')')\r
- if not tok: continue\r
- if Match(r'\d+', tok): continue\r
- if Match(r'0[xX][0-9a-fA-F]+', tok): continue\r
- if Match(r'k[A-Z0-9]\w*', tok): continue\r
- if Match(r'(.+::)?k[A-Z0-9]\w*', tok): continue\r
- if Match(r'(.+::)?[A-Z][A-Z0-9_]*', tok): continue\r
- # A catch all for tricky sizeof cases, including 'sizeof expression',\r
- # 'sizeof(*type)', 'sizeof(const type)', 'sizeof(struct StructName)'\r
- # requires skipping the next token because we split on ' ' and '*'.\r
- if tok.startswith('sizeof'):\r
- skip_next = True\r
- continue\r
- is_const = False\r
- break\r
- if not is_const:\r
- error(filename, linenum, 'runtime/arrays', 1,\r
- 'Do not use variable-length arrays. Use an appropriately named '\r
- "('k' followed by CamelCase) compile-time constant for the size.")\r
-\r
- # Check for use of unnamed namespaces in header files. Registration\r
- # macros are typically OK, so we allow use of "namespace {" on lines\r
- # that end with backslashes.\r
- if (IsHeaderExtension(file_extension)\r
- and Search(r'\bnamespace\s*{', line)\r
- and line[-1] != '\\'):\r
- error(filename, linenum, 'build/namespaces', 4,\r
- 'Do not use unnamed namespaces in header files. See '\r
- 'https://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces'\r
- ' for more information.')\r
-\r
-\r
-def CheckGlobalStatic(filename, clean_lines, linenum, error):\r
- """Check for unsafe global or static objects.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- error: The function to call with any errors found.\r
- """\r
- line = clean_lines.elided[linenum]\r
-\r
- # Match two lines at a time to support multiline declarations\r
- if linenum + 1 < clean_lines.NumLines() and not Search(r'[;({]', line):\r
- line += clean_lines.elided[linenum + 1].strip()\r
-\r
- # Check for people declaring static/global STL strings at the top level.\r
- # This is dangerous because the C++ language does not guarantee that\r
- # globals with constructors are initialized before the first access, and\r
- # also because globals can be destroyed when some threads are still running.\r
- # TODO(unknown): Generalize this to also find static unique_ptr instances.\r
- # TODO(unknown): File bugs for clang-tidy to find these.\r
- match = Match(\r
- r'((?:|static +)(?:|const +))(?::*std::)?string( +const)? +'\r
- r'([a-zA-Z0-9_:]+)\b(.*)',\r
- line)\r
-\r
- # Remove false positives:\r
- # - String pointers (as opposed to values).\r
- # string *pointer\r
- # const string *pointer\r
- # string const *pointer\r
- # string *const pointer\r
- #\r
- # - Functions and template specializations.\r
- # string Function<Type>(...\r
- # string Class<Type>::Method(...\r
- #\r
- # - Operators. These are matched separately because operator names\r
- # cross non-word boundaries, and trying to match both operators\r
- # and functions at the same time would decrease accuracy of\r
- # matching identifiers.\r
- # string Class::operator*()\r
- if (match and\r
- not Search(r'\bstring\b(\s+const)?\s*[\*\&]\s*(const\s+)?\w', line) and\r
- not Search(r'\boperator\W', line) and\r
- not Match(r'\s*(<.*>)?(::[a-zA-Z0-9_]+)*\s*\(([^"]|$)', match.group(4))):\r
- if Search(r'\bconst\b', line):\r
- error(filename, linenum, 'runtime/string', 4,\r
- 'For a static/global string constant, use a C style string '\r
- 'instead: "%schar%s %s[]".' %\r
- (match.group(1), match.group(2) or '', match.group(3)))\r
- else:\r
- error(filename, linenum, 'runtime/string', 4,\r
- 'Static/global string variables are not permitted.')\r
-\r
- if (Search(r'\b([A-Za-z0-9_]*_)\(\1\)', line) or\r
- Search(r'\b([A-Za-z0-9_]*_)\(CHECK_NOTNULL\(\1\)\)', line)):\r
- error(filename, linenum, 'runtime/init', 4,\r
- 'You seem to be initializing a member variable with itself.')\r
-\r
-\r
-def CheckPrintf(filename, clean_lines, linenum, error):\r
- """Check for printf related issues.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- error: The function to call with any errors found.\r
- """\r
- line = clean_lines.elided[linenum]\r
-\r
- # When snprintf is used, the second argument shouldn't be a literal.\r
- match = Search(r'snprintf\s*\(([^,]*),\s*([0-9]*)\s*,', line)\r
- if match and match.group(2) != '0':\r
- # If 2nd arg is zero, snprintf is used to calculate size.\r
- error(filename, linenum, 'runtime/printf', 3,\r
- 'If you can, use sizeof(%s) instead of %s as the 2nd arg '\r
- 'to snprintf.' % (match.group(1), match.group(2)))\r
-\r
- # Check if some verboten C functions are being used.\r
- if Search(r'\bsprintf\s*\(', line):\r
- error(filename, linenum, 'runtime/printf', 5,\r
- 'Never use sprintf. Use snprintf instead.')\r
- match = Search(r'\b(strcpy|strcat)\s*\(', line)\r
- if match:\r
- error(filename, linenum, 'runtime/printf', 4,\r
- 'Almost always, snprintf is better than %s' % match.group(1))\r
-\r
-\r
-def IsDerivedFunction(clean_lines, linenum):\r
- """Check if current line contains an inherited function.\r
-\r
- Args:\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- Returns:\r
- True if current line contains a function with "override"\r
- virt-specifier.\r
- """\r
- # Scan back a few lines for start of current function\r
- for i in xrange(linenum, max(-1, linenum - 10), -1):\r
- match = Match(r'^([^()]*\w+)\(', clean_lines.elided[i])\r
- if match:\r
- # Look for "override" after the matching closing parenthesis\r
- line, _, closing_paren = CloseExpression(\r
- clean_lines, i, len(match.group(1)))\r
- return (closing_paren >= 0 and\r
- Search(r'\boverride\b', line[closing_paren:]))\r
- return False\r
-\r
-\r
-def IsOutOfLineMethodDefinition(clean_lines, linenum):\r
- """Check if current line contains an out-of-line method definition.\r
-\r
- Args:\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- Returns:\r
- True if current line contains an out-of-line method definition.\r
- """\r
- # Scan back a few lines for start of current function\r
- for i in xrange(linenum, max(-1, linenum - 10), -1):\r
- if Match(r'^([^()]*\w+)\(', clean_lines.elided[i]):\r
- return Match(r'^[^()]*\w+::\w+\(', clean_lines.elided[i]) is not None\r
- return False\r
-\r
-\r
-def IsInitializerList(clean_lines, linenum):\r
- """Check if current line is inside constructor initializer list.\r
-\r
- Args:\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- Returns:\r
- True if current line appears to be inside constructor initializer\r
- list, False otherwise.\r
- """\r
- for i in xrange(linenum, 1, -1):\r
- line = clean_lines.elided[i]\r
- if i == linenum:\r
- remove_function_body = Match(r'^(.*)\{\s*$', line)\r
- if remove_function_body:\r
- line = remove_function_body.group(1)\r
-\r
- if Search(r'\s:\s*\w+[({]', line):\r
- # A lone colon tend to indicate the start of a constructor\r
- # initializer list. It could also be a ternary operator, which\r
- # also tend to appear in constructor initializer lists as\r
- # opposed to parameter lists.\r
- return True\r
- if Search(r'\}\s*,\s*$', line):\r
- # A closing brace followed by a comma is probably the end of a\r
- # brace-initialized member in constructor initializer list.\r
- return True\r
- if Search(r'[{};]\s*$', line):\r
- # Found one of the following:\r
- # - A closing brace or semicolon, probably the end of the previous\r
- # function.\r
- # - An opening brace, probably the start of current class or namespace.\r
- #\r
- # Current line is probably not inside an initializer list since\r
- # we saw one of those things without seeing the starting colon.\r
- return False\r
-\r
- # Got to the beginning of the file without seeing the start of\r
- # constructor initializer list.\r
- return False\r
-\r
-\r
-def CheckForNonConstReference(filename, clean_lines, linenum,\r
- nesting_state, error):\r
- """Check for non-const references.\r
-\r
- Separate from CheckLanguage since it scans backwards from current\r
- line, instead of scanning forward.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- nesting_state: A NestingState instance which maintains information about\r
- the current stack of nested blocks being parsed.\r
- error: The function to call with any errors found.\r
- """\r
- # Do nothing if there is no '&' on current line.\r
- line = clean_lines.elided[linenum]\r
- if '&' not in line:\r
- return\r
-\r
- # If a function is inherited, current function doesn't have much of\r
- # a choice, so any non-const references should not be blamed on\r
- # derived function.\r
- if IsDerivedFunction(clean_lines, linenum):\r
- return\r
-\r
- # Don't warn on out-of-line method definitions, as we would warn on the\r
- # in-line declaration, if it isn't marked with 'override'.\r
- if IsOutOfLineMethodDefinition(clean_lines, linenum):\r
- return\r
-\r
- # Long type names may be broken across multiple lines, usually in one\r
- # of these forms:\r
- # LongType\r
- # ::LongTypeContinued &identifier\r
- # LongType::\r
- # LongTypeContinued &identifier\r
- # LongType<\r
- # ...>::LongTypeContinued &identifier\r
- #\r
- # If we detected a type split across two lines, join the previous\r
- # line to current line so that we can match const references\r
- # accordingly.\r
- #\r
- # Note that this only scans back one line, since scanning back\r
- # arbitrary number of lines would be expensive. If you have a type\r
- # that spans more than 2 lines, please use a typedef.\r
- if linenum > 1:\r
- previous = None\r
- if Match(r'\s*::(?:[\w<>]|::)+\s*&\s*\S', line):\r
- # previous_line\n + ::current_line\r
- previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+[\w<>])\s*$',\r
- clean_lines.elided[linenum - 1])\r
- elif Match(r'\s*[a-zA-Z_]([\w<>]|::)+\s*&\s*\S', line):\r
- # previous_line::\n + current_line\r
- previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+::)\s*$',\r
- clean_lines.elided[linenum - 1])\r
- if previous:\r
- line = previous.group(1) + line.lstrip()\r
- else:\r
- # Check for templated parameter that is split across multiple lines\r
- endpos = line.rfind('>')\r
- if endpos > -1:\r
- (_, startline, startpos) = ReverseCloseExpression(\r
- clean_lines, linenum, endpos)\r
- if startpos > -1 and startline < linenum:\r
- # Found the matching < on an earlier line, collect all\r
- # pieces up to current line.\r
- line = ''\r
- for i in xrange(startline, linenum + 1):\r
- line += clean_lines.elided[i].strip()\r
-\r
- # Check for non-const references in function parameters. A single '&' may\r
- # found in the following places:\r
- # inside expression: binary & for bitwise AND\r
- # inside expression: unary & for taking the address of something\r
- # inside declarators: reference parameter\r
- # We will exclude the first two cases by checking that we are not inside a\r
- # function body, including one that was just introduced by a trailing '{'.\r
- # TODO(unknown): Doesn't account for 'catch(Exception& e)' [rare].\r
- if (nesting_state.previous_stack_top and\r
- not (isinstance(nesting_state.previous_stack_top, _ClassInfo) or\r
- isinstance(nesting_state.previous_stack_top, _NamespaceInfo))):\r
- # Not at toplevel, not within a class, and not within a namespace\r
- return\r
-\r
- # Avoid initializer lists. We only need to scan back from the\r
- # current line for something that starts with ':'.\r
- #\r
- # We don't need to check the current line, since the '&' would\r
- # appear inside the second set of parentheses on the current line as\r
- # opposed to the first set.\r
- if linenum > 0:\r
- for i in xrange(linenum - 1, max(0, linenum - 10), -1):\r
- previous_line = clean_lines.elided[i]\r
- if not Search(r'[),]\s*$', previous_line):\r
- break\r
- if Match(r'^\s*:\s+\S', previous_line):\r
- return\r
-\r
- # Avoid preprocessors\r
- if Search(r'\\\s*$', line):\r
- return\r
-\r
- # Avoid constructor initializer lists\r
- if IsInitializerList(clean_lines, linenum):\r
- return\r
-\r
- # We allow non-const references in a few standard places, like functions\r
- # called "swap()" or iostream operators like "<<" or ">>". Do not check\r
- # those function parameters.\r
- #\r
- # We also accept & in static_assert, which looks like a function but\r
- # it's actually a declaration expression.\r
- whitelisted_functions = (r'(?:[sS]wap(?:<\w:+>)?|'\r
- r'operator\s*[<>][<>]|'\r
- r'static_assert|COMPILE_ASSERT'\r
- r')\s*\(')\r
- if Search(whitelisted_functions, line):\r
- return\r
- elif not Search(r'\S+\([^)]*$', line):\r
- # Don't see a whitelisted function on this line. Actually we\r
- # didn't see any function name on this line, so this is likely a\r
- # multi-line parameter list. Try a bit harder to catch this case.\r
- for i in xrange(2):\r
- if (linenum > i and\r
- Search(whitelisted_functions, clean_lines.elided[linenum - i - 1])):\r
- return\r
-\r
- decls = ReplaceAll(r'{[^}]*}', ' ', line) # exclude function body\r
- for parameter in re.findall(_RE_PATTERN_REF_PARAM, decls):\r
- if (not Match(_RE_PATTERN_CONST_REF_PARAM, parameter) and\r
- not Match(_RE_PATTERN_REF_STREAM_PARAM, parameter)):\r
- error(filename, linenum, 'runtime/references', 2,\r
- 'Is this a non-const reference? '\r
- 'If so, make const or use a pointer: ' +\r
- ReplaceAll(' *<', '<', parameter))\r
-\r
-\r
-def CheckCasts(filename, clean_lines, linenum, error):\r
- """Various cast related checks.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- error: The function to call with any errors found.\r
- """\r
- line = clean_lines.elided[linenum]\r
-\r
- # Check to see if they're using an conversion function cast.\r
- # I just try to capture the most common basic types, though there are more.\r
- # Parameterless conversion functions, such as bool(), are allowed as they are\r
- # probably a member operator declaration or default constructor.\r
- match = Search(\r
- r'(\bnew\s+(?:const\s+)?|\S<\s*(?:const\s+)?)?\b'\r
- r'(int|float|double|bool|char|int32|uint32|int64|uint64)'\r
- r'(\([^)].*)', line)\r
- expecting_function = ExpectingFunctionArgs(clean_lines, linenum)\r
- if match and not expecting_function:\r
- matched_type = match.group(2)\r
-\r
- # matched_new_or_template is used to silence two false positives:\r
- # - New operators\r
- # - Template arguments with function types\r
- #\r
- # For template arguments, we match on types immediately following\r
- # an opening bracket without any spaces. This is a fast way to\r
- # silence the common case where the function type is the first\r
- # template argument. False negative with less-than comparison is\r
- # avoided because those operators are usually followed by a space.\r
- #\r
- # function<double(double)> // bracket + no space = false positive\r
- # value < double(42) // bracket + space = true positive\r
- matched_new_or_template = match.group(1)\r
-\r
- # Avoid arrays by looking for brackets that come after the closing\r
- # parenthesis.\r
- if Match(r'\([^()]+\)\s*\[', match.group(3)):\r
- return\r
-\r
- # Other things to ignore:\r
- # - Function pointers\r
- # - Casts to pointer types\r
- # - Placement new\r
- # - Alias declarations\r
- matched_funcptr = match.group(3)\r
- if (matched_new_or_template is None and\r
- not (matched_funcptr and\r
- (Match(r'\((?:[^() ]+::\s*\*\s*)?[^() ]+\)\s*\(',\r
- matched_funcptr) or\r
- matched_funcptr.startswith('(*)'))) and\r
- not Match(r'\s*using\s+\S+\s*=\s*' + matched_type, line) and\r
- not Search(r'new\(\S+\)\s*' + matched_type, line)):\r
- error(filename, linenum, 'readability/casting', 4,\r
- 'Using deprecated casting style. '\r
- 'Use static_cast<%s>(...) instead' %\r
- matched_type)\r
-\r
- if not expecting_function:\r
- CheckCStyleCast(filename, clean_lines, linenum, 'static_cast',\r
- r'\((int|float|double|bool|char|u?int(16|32|64))\)', error)\r
-\r
- # This doesn't catch all cases. Consider (const char * const)"hello".\r
- #\r
- # (char *) "foo" should always be a const_cast (reinterpret_cast won't\r
- # compile).\r
- if CheckCStyleCast(filename, clean_lines, linenum, 'const_cast',\r
- r'\((char\s?\*+\s?)\)\s*"', error):\r
- pass\r
- else:\r
- # Check pointer casts for other than string constants\r
- CheckCStyleCast(filename, clean_lines, linenum, 'reinterpret_cast',\r
- r'\((\w+\s?\*+\s?)\)', error)\r
-\r
- # In addition, we look for people taking the address of a cast. This\r
- # is dangerous -- casts can assign to temporaries, so the pointer doesn't\r
- # point where you think.\r
- #\r
- # Some non-identifier character is required before the '&' for the\r
- # expression to be recognized as a cast. These are casts:\r
- # expression = &static_cast<int*>(temporary());\r
- # function(&(int*)(temporary()));\r
- #\r
- # This is not a cast:\r
- # reference_type&(int* function_param);\r
- match = Search(\r
- r'(?:[^\w]&\(([^)*][^)]*)\)[\w(])|'\r
- r'(?:[^\w]&(static|dynamic|down|reinterpret)_cast\b)', line)\r
- if match:\r
- # Try a better error message when the & is bound to something\r
- # dereferenced by the casted pointer, as opposed to the casted\r
- # pointer itself.\r
- parenthesis_error = False\r
- match = Match(r'^(.*&(?:static|dynamic|down|reinterpret)_cast\b)<', line)\r
- if match:\r
- _, y1, x1 = CloseExpression(clean_lines, linenum, len(match.group(1)))\r
- if x1 >= 0 and clean_lines.elided[y1][x1] == '(':\r
- _, y2, x2 = CloseExpression(clean_lines, y1, x1)\r
- if x2 >= 0:\r
- extended_line = clean_lines.elided[y2][x2:]\r
- if y2 < clean_lines.NumLines() - 1:\r
- extended_line += clean_lines.elided[y2 + 1]\r
- if Match(r'\s*(?:->|\[)', extended_line):\r
- parenthesis_error = True\r
-\r
- if parenthesis_error:\r
- error(filename, linenum, 'readability/casting', 4,\r
- ('Are you taking an address of something dereferenced '\r
- 'from a cast? Wrapping the dereferenced expression in '\r
- 'parentheses will make the binding more obvious'))\r
- else:\r
- error(filename, linenum, 'runtime/casting', 4,\r
- ('Are you taking an address of a cast? '\r
- 'This is dangerous: could be a temp var. '\r
- 'Take the address before doing the cast, rather than after'))\r
-\r
-\r
-def CheckCStyleCast(filename, clean_lines, linenum, cast_type, pattern, error):\r
- """Checks for a C-style cast by looking for the pattern.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- cast_type: The string for the C++ cast to recommend. This is either\r
- reinterpret_cast, static_cast, or const_cast, depending.\r
- pattern: The regular expression used to find C-style casts.\r
- error: The function to call with any errors found.\r
-\r
- Returns:\r
- True if an error was emitted.\r
- False otherwise.\r
- """\r
- line = clean_lines.elided[linenum]\r
- match = Search(pattern, line)\r
- if not match:\r
- return False\r
-\r
- # Exclude lines with keywords that tend to look like casts\r
- context = line[0:match.start(1) - 1]\r
- if Match(r'.*\b(?:sizeof|alignof|alignas|[_A-Z][_A-Z0-9]*)\s*$', context):\r
- return False\r
-\r
- # Try expanding current context to see if we one level of\r
- # parentheses inside a macro.\r
- if linenum > 0:\r
- for i in xrange(linenum - 1, max(0, linenum - 5), -1):\r
- context = clean_lines.elided[i] + context\r
- if Match(r'.*\b[_A-Z][_A-Z0-9]*\s*\((?:\([^()]*\)|[^()])*$', context):\r
- return False\r
-\r
- # operator++(int) and operator--(int)\r
- if context.endswith(' operator++') or context.endswith(' operator--'):\r
- return False\r
-\r
- # A single unnamed argument for a function tends to look like old style cast.\r
- # If we see those, don't issue warnings for deprecated casts.\r
- remainder = line[match.end(0):]\r
- if Match(r'^\s*(?:;|const\b|throw\b|final\b|override\b|[=>{),]|->)',\r
- remainder):\r
- return False\r
-\r
- # At this point, all that should be left is actual casts.\r
- error(filename, linenum, 'readability/casting', 4,\r
- 'Using C-style cast. Use %s<%s>(...) instead' %\r
- (cast_type, match.group(1)))\r
-\r
- return True\r
-\r
-\r
-def ExpectingFunctionArgs(clean_lines, linenum):\r
- """Checks whether where function type arguments are expected.\r
-\r
- Args:\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
-\r
- Returns:\r
- True if the line at 'linenum' is inside something that expects arguments\r
- of function types.\r
- """\r
- line = clean_lines.elided[linenum]\r
- return (Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line) or\r
- (linenum >= 2 and\r
- (Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\((?:\S+,)?\s*$',\r
- clean_lines.elided[linenum - 1]) or\r
- Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\(\s*$',\r
- clean_lines.elided[linenum - 2]) or\r
- Search(r'\bstd::m?function\s*\<\s*$',\r
- clean_lines.elided[linenum - 1]))))\r
-\r
-\r
-_HEADERS_CONTAINING_TEMPLATES = (\r
- ('<deque>', ('deque',)),\r
- ('<functional>', ('unary_function', 'binary_function',\r
- 'plus', 'minus', 'multiplies', 'divides', 'modulus',\r
- 'negate',\r
- 'equal_to', 'not_equal_to', 'greater', 'less',\r
- 'greater_equal', 'less_equal',\r
- 'logical_and', 'logical_or', 'logical_not',\r
- 'unary_negate', 'not1', 'binary_negate', 'not2',\r
- 'bind1st', 'bind2nd',\r
- 'pointer_to_unary_function',\r
- 'pointer_to_binary_function',\r
- 'ptr_fun',\r
- 'mem_fun_t', 'mem_fun', 'mem_fun1_t', 'mem_fun1_ref_t',\r
- 'mem_fun_ref_t',\r
- 'const_mem_fun_t', 'const_mem_fun1_t',\r
- 'const_mem_fun_ref_t', 'const_mem_fun1_ref_t',\r
- 'mem_fun_ref',\r
- )),\r
- ('<limits>', ('numeric_limits',)),\r
- ('<list>', ('list',)),\r
- ('<map>', ('map', 'multimap',)),\r
- ('<memory>', ('allocator', 'make_shared', 'make_unique', 'shared_ptr',\r
- 'unique_ptr', 'weak_ptr')),\r
- ('<queue>', ('queue', 'priority_queue',)),\r
- ('<set>', ('set', 'multiset',)),\r
- ('<stack>', ('stack',)),\r
- ('<string>', ('char_traits', 'basic_string',)),\r
- ('<tuple>', ('tuple',)),\r
- ('<unordered_map>', ('unordered_map', 'unordered_multimap')),\r
- ('<unordered_set>', ('unordered_set', 'unordered_multiset')),\r
- ('<utility>', ('pair',)),\r
- ('<vector>', ('vector',)),\r
-\r
- # gcc extensions.\r
- # Note: std::hash is their hash, ::hash is our hash\r
- ('<hash_map>', ('hash_map', 'hash_multimap',)),\r
- ('<hash_set>', ('hash_set', 'hash_multiset',)),\r
- ('<slist>', ('slist',)),\r
- )\r
-\r
-_HEADERS_MAYBE_TEMPLATES = (\r
- ('<algorithm>', ('copy', 'max', 'min', 'min_element', 'sort',\r
- 'transform',\r
- )),\r
- ('<utility>', ('forward', 'make_pair', 'move', 'swap')),\r
- )\r
-\r
-_RE_PATTERN_STRING = re.compile(r'\bstring\b')\r
-\r
-_re_pattern_headers_maybe_templates = []\r
-for _header, _templates in _HEADERS_MAYBE_TEMPLATES:\r
- for _template in _templates:\r
- # Match max<type>(..., ...), max(..., ...), but not foo->max, foo.max or\r
- # type::max().\r
- _re_pattern_headers_maybe_templates.append(\r
- (re.compile(r'[^>.]\b' + _template + r'(<.*?>)?\([^\)]'),\r
- _template,\r
- _header))\r
-\r
-# Other scripts may reach in and modify this pattern.\r
-_re_pattern_templates = []\r
-for _header, _templates in _HEADERS_CONTAINING_TEMPLATES:\r
- for _template in _templates:\r
- _re_pattern_templates.append(\r
- (re.compile(r'(\<|\b)' + _template + r'\s*\<'),\r
- _template + '<>',\r
- _header))\r
-\r
-\r
-def FilesBelongToSameModule(filename_cc, filename_h):\r
- """Check if these two filenames belong to the same module.\r
-\r
- The concept of a 'module' here is a as follows:\r
- foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the\r
- same 'module' if they are in the same directory.\r
- some/path/public/xyzzy and some/path/internal/xyzzy are also considered\r
- to belong to the same module here.\r
-\r
- If the filename_cc contains a longer path than the filename_h, for example,\r
- '/absolute/path/to/base/sysinfo.cc', and this file would include\r
- 'base/sysinfo.h', this function also produces the prefix needed to open the\r
- header. This is used by the caller of this function to more robustly open the\r
- header file. We don't have access to the real include paths in this context,\r
- so we need this guesswork here.\r
-\r
- Known bugs: tools/base/bar.cc and base/bar.h belong to the same module\r
- according to this implementation. Because of this, this function gives\r
- some false positives. This should be sufficiently rare in practice.\r
-\r
- Args:\r
- filename_cc: is the path for the .cc file\r
- filename_h: is the path for the header path\r
-\r
- Returns:\r
- Tuple with a bool and a string:\r
- bool: True if filename_cc and filename_h belong to the same module.\r
- string: the additional prefix needed to open the header file.\r
- """\r
-\r
- fileinfo = FileInfo(filename_cc)\r
- if not fileinfo.IsSource():\r
- return (False, '')\r
- filename_cc = filename_cc[:-len(fileinfo.Extension())]\r
- matched_test_suffix = Search(_TEST_FILE_SUFFIX, fileinfo.BaseName())\r
- if matched_test_suffix:\r
- filename_cc = filename_cc[:-len(matched_test_suffix.group(1))]\r
- filename_cc = filename_cc.replace('/public/', '/')\r
- filename_cc = filename_cc.replace('/internal/', '/')\r
-\r
- if not filename_h.endswith('.h'):\r
- return (False, '')\r
- filename_h = filename_h[:-len('.h')]\r
- if filename_h.endswith('-inl'):\r
- filename_h = filename_h[:-len('-inl')]\r
- filename_h = filename_h.replace('/public/', '/')\r
- filename_h = filename_h.replace('/internal/', '/')\r
-\r
- files_belong_to_same_module = filename_cc.endswith(filename_h)\r
- common_path = ''\r
- if files_belong_to_same_module:\r
- common_path = filename_cc[:-len(filename_h)]\r
- return files_belong_to_same_module, common_path\r
-\r
-\r
-def UpdateIncludeState(filename, include_dict, io=codecs):\r
- """Fill up the include_dict with new includes found from the file.\r
-\r
- Args:\r
- filename: the name of the header to read.\r
- include_dict: a dictionary in which the headers are inserted.\r
- io: The io factory to use to read the file. Provided for testability.\r
-\r
- Returns:\r
- True if a header was successfully added. False otherwise.\r
- """\r
- headerfile = None\r
- try:\r
- headerfile = io.open(filename, 'r', 'utf8', 'replace')\r
- except IOError:\r
- return False\r
- linenum = 0\r
- for line in headerfile:\r
- linenum += 1\r
- clean_line = CleanseComments(line)\r
- match = _RE_PATTERN_INCLUDE.search(clean_line)\r
- if match:\r
- include = match.group(2)\r
- include_dict.setdefault(include, linenum)\r
- return True\r
-\r
-\r
-def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error,\r
- io=codecs):\r
- """Reports for missing stl includes.\r
-\r
- This function will output warnings to make sure you are including the headers\r
- necessary for the stl containers and functions that you use. We only give one\r
- reason to include a header. For example, if you use both equal_to<> and\r
- less<> in a .h file, only one (the latter in the file) of these will be\r
- reported as a reason to include the <functional>.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- include_state: An _IncludeState instance.\r
- error: The function to call with any errors found.\r
- io: The IO factory to use to read the header file. Provided for unittest\r
- injection.\r
- """\r
- required = {} # A map of header name to linenumber and the template entity.\r
- # Example of required: { '<functional>': (1219, 'less<>') }\r
-\r
- for linenum in xrange(clean_lines.NumLines()):\r
- line = clean_lines.elided[linenum]\r
- if not line or line[0] == '#':\r
- continue\r
-\r
- # String is special -- it is a non-templatized type in STL.\r
- matched = _RE_PATTERN_STRING.search(line)\r
- if matched:\r
- # Don't warn about strings in non-STL namespaces:\r
- # (We check only the first match per line; good enough.)\r
- prefix = line[:matched.start()]\r
- if prefix.endswith('std::') or not prefix.endswith('::'):\r
- required['<string>'] = (linenum, 'string')\r
-\r
- for pattern, template, header in _re_pattern_headers_maybe_templates:\r
- if pattern.search(line):\r
- required[header] = (linenum, template)\r
-\r
- # The following function is just a speed up, no semantics are changed.\r
- if not '<' in line: # Reduces the cpu time usage by skipping lines.\r
- continue\r
-\r
- for pattern, template, header in _re_pattern_templates:\r
- matched = pattern.search(line)\r
- if matched:\r
- # Don't warn about IWYU in non-STL namespaces:\r
- # (We check only the first match per line; good enough.)\r
- prefix = line[:matched.start()]\r
- if prefix.endswith('std::') or not prefix.endswith('::'):\r
- required[header] = (linenum, template)\r
-\r
- # The policy is that if you #include something in foo.h you don't need to\r
- # include it again in foo.cc. Here, we will look at possible includes.\r
- # Let's flatten the include_state include_list and copy it into a dictionary.\r
- include_dict = dict([item for sublist in include_state.include_list\r
- for item in sublist])\r
-\r
- # Did we find the header for this file (if any) and successfully load it?\r
- header_found = False\r
-\r
- # Use the absolute path so that matching works properly.\r
- abs_filename = FileInfo(filename).FullName()\r
-\r
- # For Emacs's flymake.\r
- # If cpplint is invoked from Emacs's flymake, a temporary file is generated\r
- # by flymake and that file name might end with '_flymake.cc'. In that case,\r
- # restore original file name here so that the corresponding header file can be\r
- # found.\r
- # e.g. If the file name is 'foo_flymake.cc', we should search for 'foo.h'\r
- # instead of 'foo_flymake.h'\r
- abs_filename = re.sub(r'_flymake\.cc$', '.cc', abs_filename)\r
-\r
- # include_dict is modified during iteration, so we iterate over a copy of\r
- # the keys.\r
- header_keys = include_dict.keys()\r
- for header in header_keys:\r
- (same_module, common_path) = FilesBelongToSameModule(abs_filename, header)\r
- fullpath = common_path + header\r
- if same_module and UpdateIncludeState(fullpath, include_dict, io):\r
- header_found = True\r
-\r
- # If we can't find the header file for a .cc, assume it's because we don't\r
- # know where to look. In that case we'll give up as we're not sure they\r
- # didn't include it in the .h file.\r
- # TODO(unknown): Do a better job of finding .h files so we are confident that\r
- # not having the .h file means there isn't one.\r
- if filename.endswith('.cc') and not header_found:\r
- return\r
-\r
- # All the lines have been processed, report the errors found.\r
- for required_header_unstripped in required:\r
- template = required[required_header_unstripped][1]\r
- if required_header_unstripped.strip('<>"') not in include_dict:\r
- error(filename, required[required_header_unstripped][0],\r
- 'build/include_what_you_use', 4,\r
- 'Add #include ' + required_header_unstripped + ' for ' + template)\r
-\r
-\r
-_RE_PATTERN_EXPLICIT_MAKEPAIR = re.compile(r'\bmake_pair\s*<')\r
-\r
-\r
-def CheckMakePairUsesDeduction(filename, clean_lines, linenum, error):\r
- """Check that make_pair's template arguments are deduced.\r
-\r
- G++ 4.6 in C++11 mode fails badly if make_pair's template arguments are\r
- specified explicitly, and such use isn't intended in any case.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- error: The function to call with any errors found.\r
- """\r
- line = clean_lines.elided[linenum]\r
- match = _RE_PATTERN_EXPLICIT_MAKEPAIR.search(line)\r
- if match:\r
- error(filename, linenum, 'build/explicit_make_pair',\r
- 4, # 4 = high confidence\r
- 'For C++11-compatibility, omit template arguments from make_pair'\r
- ' OR use pair directly OR if appropriate, construct a pair directly')\r
-\r
-\r
-def CheckRedundantVirtual(filename, clean_lines, linenum, error):\r
- """Check if line contains a redundant "virtual" function-specifier.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- error: The function to call with any errors found.\r
- """\r
- # Look for "virtual" on current line.\r
- line = clean_lines.elided[linenum]\r
- virtual = Match(r'^(.*)(\bvirtual\b)(.*)$', line)\r
- if not virtual: return\r
-\r
- # Ignore "virtual" keywords that are near access-specifiers. These\r
- # are only used in class base-specifier and do not apply to member\r
- # functions.\r
- if (Search(r'\b(public|protected|private)\s+$', virtual.group(1)) or\r
- Match(r'^\s+(public|protected|private)\b', virtual.group(3))):\r
- return\r
-\r
- # Ignore the "virtual" keyword from virtual base classes. Usually\r
- # there is a column on the same line in these cases (virtual base\r
- # classes are rare in google3 because multiple inheritance is rare).\r
- if Match(r'^.*[^:]:[^:].*$', line): return\r
-\r
- # Look for the next opening parenthesis. This is the start of the\r
- # parameter list (possibly on the next line shortly after virtual).\r
- # TODO(unknown): doesn't work if there are virtual functions with\r
- # decltype() or other things that use parentheses, but csearch suggests\r
- # that this is rare.\r
- end_col = -1\r
- end_line = -1\r
- start_col = len(virtual.group(2))\r
- for start_line in xrange(linenum, min(linenum + 3, clean_lines.NumLines())):\r
- line = clean_lines.elided[start_line][start_col:]\r
- parameter_list = Match(r'^([^(]*)\(', line)\r
- if parameter_list:\r
- # Match parentheses to find the end of the parameter list\r
- (_, end_line, end_col) = CloseExpression(\r
- clean_lines, start_line, start_col + len(parameter_list.group(1)))\r
- break\r
- start_col = 0\r
-\r
- if end_col < 0:\r
- return # Couldn't find end of parameter list, give up\r
-\r
- # Look for "override" or "final" after the parameter list\r
- # (possibly on the next few lines).\r
- for i in xrange(end_line, min(end_line + 3, clean_lines.NumLines())):\r
- line = clean_lines.elided[i][end_col:]\r
- match = Search(r'\b(override|final)\b', line)\r
- if match:\r
- error(filename, linenum, 'readability/inheritance', 4,\r
- ('"virtual" is redundant since function is '\r
- 'already declared as "%s"' % match.group(1)))\r
-\r
- # Set end_col to check whole lines after we are done with the\r
- # first line.\r
- end_col = 0\r
- if Search(r'[^\w]\s*$', line):\r
- break\r
-\r
-\r
-def CheckRedundantOverrideOrFinal(filename, clean_lines, linenum, error):\r
- """Check if line contains a redundant "override" or "final" virt-specifier.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- error: The function to call with any errors found.\r
- """\r
- # Look for closing parenthesis nearby. We need one to confirm where\r
- # the declarator ends and where the virt-specifier starts to avoid\r
- # false positives.\r
- line = clean_lines.elided[linenum]\r
- declarator_end = line.rfind(')')\r
- if declarator_end >= 0:\r
- fragment = line[declarator_end:]\r
- else:\r
- if linenum > 1 and clean_lines.elided[linenum - 1].rfind(')') >= 0:\r
- fragment = line\r
- else:\r
- return\r
-\r
- # Check that at most one of "override" or "final" is present, not both\r
- if Search(r'\boverride\b', fragment) and Search(r'\bfinal\b', fragment):\r
- error(filename, linenum, 'readability/inheritance', 4,\r
- ('"override" is redundant since function is '\r
- 'already declared as "final"'))\r
-\r
-\r
-\r
-\r
-# Returns true if we are at a new block, and it is directly\r
-# inside of a namespace.\r
-def IsBlockInNameSpace(nesting_state, is_forward_declaration):\r
- """Checks that the new block is directly in a namespace.\r
-\r
- Args:\r
- nesting_state: The _NestingState object that contains info about our state.\r
- is_forward_declaration: If the class is a forward declared class.\r
- Returns:\r
- Whether or not the new block is directly in a namespace.\r
- """\r
- if is_forward_declaration:\r
- if len(nesting_state.stack) >= 1 and (\r
- isinstance(nesting_state.stack[-1], _NamespaceInfo)):\r
- return True\r
- else:\r
- return False\r
-\r
- return (len(nesting_state.stack) > 1 and\r
- nesting_state.stack[-1].check_namespace_indentation and\r
- isinstance(nesting_state.stack[-2], _NamespaceInfo))\r
-\r
-\r
-def ShouldCheckNamespaceIndentation(nesting_state, is_namespace_indent_item,\r
- raw_lines_no_comments, linenum):\r
- """This method determines if we should apply our namespace indentation check.\r
-\r
- Args:\r
- nesting_state: The current nesting state.\r
- is_namespace_indent_item: If we just put a new class on the stack, True.\r
- If the top of the stack is not a class, or we did not recently\r
- add the class, False.\r
- raw_lines_no_comments: The lines without the comments.\r
- linenum: The current line number we are processing.\r
-\r
- Returns:\r
- True if we should apply our namespace indentation check. Currently, it\r
- only works for classes and namespaces inside of a namespace.\r
- """\r
-\r
- is_forward_declaration = IsForwardClassDeclaration(raw_lines_no_comments,\r
- linenum)\r
-\r
- if not (is_namespace_indent_item or is_forward_declaration):\r
- return False\r
-\r
- # If we are in a macro, we do not want to check the namespace indentation.\r
- if IsMacroDefinition(raw_lines_no_comments, linenum):\r
- return False\r
-\r
- return IsBlockInNameSpace(nesting_state, is_forward_declaration)\r
-\r
-\r
-# Call this method if the line is directly inside of a namespace.\r
-# If the line above is blank (excluding comments) or the start of\r
-# an inner namespace, it cannot be indented.\r
-def CheckItemIndentationInNamespace(filename, raw_lines_no_comments, linenum,\r
- error):\r
- line = raw_lines_no_comments[linenum]\r
- if Match(r'^\s+', line):\r
- error(filename, linenum, 'runtime/indentation_namespace', 4,\r
- 'Do not indent within a namespace')\r
-\r
-\r
-def ProcessLine(filename, file_extension, clean_lines, line,\r
- include_state, function_state, nesting_state, error,\r
- extra_check_functions=[]):\r
- """Processes a single line in the file.\r
-\r
- Args:\r
- filename: Filename of the file that is being processed.\r
- file_extension: The extension (dot not included) of the file.\r
- clean_lines: An array of strings, each representing a line of the file,\r
- with comments stripped.\r
- line: Number of line being processed.\r
- include_state: An _IncludeState instance in which the headers are inserted.\r
- function_state: A _FunctionState instance which counts function lines, etc.\r
- nesting_state: A NestingState instance which maintains information about\r
- the current stack of nested blocks being parsed.\r
- error: A callable to which errors are reported, which takes 4 arguments:\r
- filename, line number, error level, and message\r
- extra_check_functions: An array of additional check functions that will be\r
- run on each source line. Each function takes 4\r
- arguments: filename, clean_lines, line, error\r
- """\r
- raw_lines = clean_lines.raw_lines\r
- ParseNolintSuppressions(filename, raw_lines[line], line, error)\r
- nesting_state.Update(filename, clean_lines, line, error)\r
- CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line,\r
- error)\r
- if nesting_state.InAsmBlock(): return\r
- CheckForFunctionLengths(filename, clean_lines, line, function_state, error)\r
- CheckForMultilineCommentsAndStrings(filename, clean_lines, line, error)\r
- CheckStyle(filename, clean_lines, line, file_extension, nesting_state, error)\r
- CheckLanguage(filename, clean_lines, line, file_extension, include_state,\r
- nesting_state, error)\r
- CheckForNonConstReference(filename, clean_lines, line, nesting_state, error)\r
- CheckForNonStandardConstructs(filename, clean_lines, line,\r
- nesting_state, error)\r
- CheckVlogArguments(filename, clean_lines, line, error)\r
- CheckPosixThreading(filename, clean_lines, line, error)\r
- CheckInvalidIncrement(filename, clean_lines, line, error)\r
- CheckMakePairUsesDeduction(filename, clean_lines, line, error)\r
- CheckRedundantVirtual(filename, clean_lines, line, error)\r
- CheckRedundantOverrideOrFinal(filename, clean_lines, line, error)\r
- for check_fn in extra_check_functions:\r
- check_fn(filename, clean_lines, line, error)\r
-\r
-def FlagCxx11Features(filename, clean_lines, linenum, error):\r
- """Flag those c++11 features that we only allow in certain places.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- error: The function to call with any errors found.\r
- """\r
- line = clean_lines.elided[linenum]\r
-\r
- include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line)\r
-\r
- # Flag unapproved C++ TR1 headers.\r
- if include and include.group(1).startswith('tr1/'):\r
- error(filename, linenum, 'build/c++tr1', 5,\r
- ('C++ TR1 headers such as <%s> are unapproved.') % include.group(1))\r
-\r
- # Flag unapproved C++11 headers.\r
- if include and include.group(1) in ('cfenv',\r
- 'condition_variable',\r
- 'fenv.h',\r
- 'future',\r
- 'mutex',\r
- 'thread',\r
- 'chrono',\r
- 'ratio',\r
- 'regex',\r
- 'system_error',\r
- ):\r
- error(filename, linenum, 'build/c++11', 5,\r
- ('<%s> is an unapproved C++11 header.') % include.group(1))\r
-\r
- # The only place where we need to worry about C++11 keywords and library\r
- # features in preprocessor directives is in macro definitions.\r
- if Match(r'\s*#', line) and not Match(r'\s*#\s*define\b', line): return\r
-\r
- # These are classes and free functions. The classes are always\r
- # mentioned as std::*, but we only catch the free functions if\r
- # they're not found by ADL. They're alphabetical by header.\r
- for top_name in (\r
- # type_traits\r
- 'alignment_of',\r
- 'aligned_union',\r
- ):\r
- if Search(r'\bstd::%s\b' % top_name, line):\r
- error(filename, linenum, 'build/c++11', 5,\r
- ('std::%s is an unapproved C++11 class or function. Send c-style '\r
- 'an example of where it would make your code more readable, and '\r
- 'they may let you use it.') % top_name)\r
-\r
-\r
-def FlagCxx14Features(filename, clean_lines, linenum, error):\r
- """Flag those C++14 features that we restrict.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- error: The function to call with any errors found.\r
- """\r
- line = clean_lines.elided[linenum]\r
-\r
- include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line)\r
-\r
- # Flag unapproved C++14 headers.\r
- if include and include.group(1) in ('scoped_allocator', 'shared_mutex'):\r
- error(filename, linenum, 'build/c++14', 5,\r
- ('<%s> is an unapproved C++14 header.') % include.group(1))\r
-\r
-\r
-def ProcessFileData(filename, file_extension, lines, error,\r
- extra_check_functions=[]):\r
- """Performs lint checks and reports any errors to the given error function.\r
-\r
- Args:\r
- filename: Filename of the file that is being processed.\r
- file_extension: The extension (dot not included) of the file.\r
- lines: An array of strings, each representing a line of the file, with the\r
- last element being empty if the file is terminated with a newline.\r
- error: A callable to which errors are reported, which takes 4 arguments:\r
- filename, line number, error level, and message\r
- extra_check_functions: An array of additional check functions that will be\r
- run on each source line. Each function takes 4\r
- arguments: filename, clean_lines, line, error\r
- """\r
- lines = (['// marker so line numbers and indices both start at 1'] + lines +\r
- ['// marker so line numbers end in a known way'])\r
-\r
- include_state = _IncludeState()\r
- function_state = _FunctionState()\r
- nesting_state = NestingState()\r
-\r
- ResetNolintSuppressions()\r
-\r
- CheckForCopyright(filename, lines, error)\r
- ProcessGlobalSuppresions(lines)\r
- RemoveMultiLineComments(filename, lines, error)\r
- clean_lines = CleansedLines(lines)\r
-\r
- if IsHeaderExtension(file_extension):\r
- CheckForHeaderGuard(filename, clean_lines, error)\r
-\r
- for line in xrange(clean_lines.NumLines()):\r
- ProcessLine(filename, file_extension, clean_lines, line,\r
- include_state, function_state, nesting_state, error,\r
- extra_check_functions)\r
- FlagCxx11Features(filename, clean_lines, line, error)\r
- nesting_state.CheckCompletedBlocks(filename, error)\r
-\r
- CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error)\r
-\r
- # Check that the .cc file has included its header if it exists.\r
- if _IsSourceExtension(file_extension):\r
- CheckHeaderFileIncluded(filename, include_state, error)\r
-\r
- # We check here rather than inside ProcessLine so that we see raw\r
- # lines rather than "cleaned" lines.\r
- CheckForBadCharacters(filename, lines, error)\r
-\r
- CheckForNewlineAtEOF(filename, lines, error)\r
-\r
-def ProcessConfigOverrides(filename):\r
- """ Loads the configuration files and processes the config overrides.\r
-\r
- Args:\r
- filename: The name of the file being processed by the linter.\r
-\r
- Returns:\r
- False if the current |filename| should not be processed further.\r
- """\r
-\r
- abs_filename = os.path.abspath(filename)\r
- cfg_filters = []\r
- keep_looking = True\r
- while keep_looking:\r
- abs_path, base_name = os.path.split(abs_filename)\r
- if not base_name:\r
- break # Reached the root directory.\r
-\r
- cfg_file = os.path.join(abs_path, "CPPLINT.cfg")\r
- abs_filename = abs_path\r
- if not os.path.isfile(cfg_file):\r
- continue\r
-\r
- try:\r
- with open(cfg_file) as file_handle:\r
- for line in file_handle:\r
- line, _, _ = line.partition('#') # Remove comments.\r
- if not line.strip():\r
- continue\r
-\r
- name, _, val = line.partition('=')\r
- name = name.strip()\r
- val = val.strip()\r
- if name == 'set noparent':\r
- keep_looking = False\r
- elif name == 'filter':\r
- cfg_filters.append(val)\r
- elif name == 'exclude_files':\r
- # When matching exclude_files pattern, use the base_name of\r
- # the current file name or the directory name we are processing.\r
- # For example, if we are checking for lint errors in /foo/bar/baz.cc\r
- # and we found the .cfg file at /foo/CPPLINT.cfg, then the config\r
- # file's "exclude_files" filter is meant to be checked against "bar"\r
- # and not "baz" nor "bar/baz.cc".\r
- if base_name:\r
- pattern = re.compile(val)\r
- if pattern.match(base_name):\r
- sys.stderr.write('Ignoring "%s": file excluded by "%s". '\r
- 'File path component "%s" matches '\r
- 'pattern "%s"\n' %\r
- (filename, cfg_file, base_name, val))\r
- return False\r
- elif name == 'linelength':\r
- global _line_length\r
- try:\r
- _line_length = int(val)\r
- except ValueError:\r
- sys.stderr.write('Line length must be numeric.')\r
- elif name == 'root':\r
- global _root\r
- _root = val\r
- elif name == 'headers':\r
- ProcessHppHeadersOption(val)\r
- else:\r
- sys.stderr.write(\r
- 'Invalid configuration option (%s) in file %s\n' %\r
- (name, cfg_file))\r
-\r
- except IOError:\r
- sys.stderr.write(\r
- "Skipping config file '%s': Can't open for reading\n" % cfg_file)\r
- keep_looking = False\r
-\r
- # Apply all the accumulated filters in reverse order (top-level directory\r
- # config options having the least priority).\r
- for filter in reversed(cfg_filters):\r
- _AddFilters(filter)\r
-\r
- return True\r
-\r
-\r
-def ProcessFile(filename, vlevel, extra_check_functions=[]):\r
- """Does google-lint on a single file.\r
-\r
- Args:\r
- filename: The name of the file to parse.\r
-\r
- vlevel: The level of errors to report. Every error of confidence\r
- >= verbose_level will be reported. 0 is a good default.\r
-\r
- extra_check_functions: An array of additional check functions that will be\r
- run on each source line. Each function takes 4\r
- arguments: filename, clean_lines, line, error\r
- """\r
-\r
- _SetVerboseLevel(vlevel)\r
- _BackupFilters()\r
-\r
- if not ProcessConfigOverrides(filename):\r
- _RestoreFilters()\r
- return\r
-\r
- lf_lines = []\r
- crlf_lines = []\r
- try:\r
- # Support the UNIX convention of using "-" for stdin. Note that\r
- # we are not opening the file with universal newline support\r
- # (which codecs doesn't support anyway), so the resulting lines do\r
- # contain trailing '\r' characters if we are reading a file that\r
- # has CRLF endings.\r
- # If after the split a trailing '\r' is present, it is removed\r
- # below.\r
- if filename == '-':\r
- lines = codecs.StreamReaderWriter(sys.stdin,\r
- codecs.getreader('utf8'),\r
- codecs.getwriter('utf8'),\r
- 'replace').read().split('\n')\r
- else:\r
- lines = codecs.open(filename, 'r', 'utf8', 'replace').read().split('\n')\r
-\r
- # Remove trailing '\r'.\r
- # The -1 accounts for the extra trailing blank line we get from split()\r
- for linenum in range(len(lines) - 1):\r
- if lines[linenum].endswith('\r'):\r
- lines[linenum] = lines[linenum].rstrip('\r')\r
- crlf_lines.append(linenum + 1)\r
- else:\r
- lf_lines.append(linenum + 1)\r
-\r
- except IOError:\r
- sys.stderr.write(\r
- "Skipping input '%s': Can't open for reading\n" % filename)\r
- _RestoreFilters()\r
- return\r
-\r
- # Note, if no dot is found, this will give the entire filename as the ext.\r
- file_extension = filename[filename.rfind('.') + 1:]\r
-\r
- # When reading from stdin, the extension is unknown, so no cpplint tests\r
- # should rely on the extension.\r
- if filename != '-' and file_extension not in _valid_extensions:\r
- sys.stderr.write('Ignoring %s; not a valid file name '\r
- '(%s)\n' % (filename, ', '.join(_valid_extensions)))\r
- else:\r
- ProcessFileData(filename, file_extension, lines, Error,\r
- extra_check_functions)\r
-\r
- # If end-of-line sequences are a mix of LF and CR-LF, issue\r
- # warnings on the lines with CR.\r
- #\r
- # Don't issue any warnings if all lines are uniformly LF or CR-LF,\r
- # since critique can handle these just fine, and the style guide\r
- # doesn't dictate a particular end of line sequence.\r
- #\r
- # We can't depend on os.linesep to determine what the desired\r
- # end-of-line sequence should be, since that will return the\r
- # server-side end-of-line sequence.\r
- if lf_lines and crlf_lines:\r
- # Warn on every line with CR. An alternative approach might be to\r
- # check whether the file is mostly CRLF or just LF, and warn on the\r
- # minority, we bias toward LF here since most tools prefer LF.\r
- for linenum in crlf_lines:\r
- Error(filename, linenum, 'whitespace/newline', 1,\r
- 'Unexpected \\r (^M) found; better to use only \\n')\r
-\r
- sys.stdout.write('Done processing %s\n' % filename)\r
- _RestoreFilters()\r
-\r
-\r
-def PrintUsage(message):\r
- """Prints a brief usage string and exits, optionally with an error message.\r
-\r
- Args:\r
- message: The optional error message.\r
- """\r
- sys.stderr.write(_USAGE)\r
- if message:\r
- sys.exit('\nFATAL ERROR: ' + message)\r
- else:\r
- sys.exit(1)\r
-\r
-\r
-def PrintCategories():\r
- """Prints a list of all the error-categories used by error messages.\r
-\r
- These are the categories used to filter messages via --filter.\r
- """\r
- sys.stderr.write(''.join(' %s\n' % cat for cat in _ERROR_CATEGORIES))\r
- sys.exit(0)\r
-\r
-\r
-def ParseArguments(args):\r
- """Parses the command line arguments.\r
-\r
- This may set the output format and verbosity level as side-effects.\r
-\r
- Args:\r
- args: The command line arguments:\r
-\r
- Returns:\r
- The list of filenames to lint.\r
- """\r
- try:\r
- (opts, filenames) = getopt.getopt(args, '', ['help', 'output=', 'verbose=',\r
- 'counting=',\r
- 'filter=',\r
- 'root=',\r
- 'linelength=',\r
- 'extensions=',\r
- 'headers='])\r
- except getopt.GetoptError:\r
- PrintUsage('Invalid arguments.')\r
-\r
- verbosity = _VerboseLevel()\r
- output_format = _OutputFormat()\r
- filters = ''\r
- counting_style = ''\r
-\r
- for (opt, val) in opts:\r
- if opt == '--help':\r
- PrintUsage(None)\r
- elif opt == '--output':\r
- if val not in ('emacs', 'vs7', 'eclipse'):\r
- PrintUsage('The only allowed output formats are emacs, vs7 and eclipse.')\r
- output_format = val\r
- elif opt == '--verbose':\r
- verbosity = int(val)\r
- elif opt == '--filter':\r
- filters = val\r
- if not filters:\r
- PrintCategories()\r
- elif opt == '--counting':\r
- if val not in ('total', 'toplevel', 'detailed'):\r
- PrintUsage('Valid counting options are total, toplevel, and detailed')\r
- counting_style = val\r
- elif opt == '--root':\r
- global _root\r
- _root = val\r
- elif opt == '--linelength':\r
- global _line_length\r
- try:\r
- _line_length = int(val)\r
- except ValueError:\r
- PrintUsage('Line length must be digits.')\r
- elif opt == '--extensions':\r
- global _valid_extensions\r
- try:\r
- _valid_extensions = set(val.split(','))\r
- except ValueError:\r
- PrintUsage('Extensions must be comma seperated list.')\r
- elif opt == '--headers':\r
- ProcessHppHeadersOption(val)\r
-\r
- if not filenames:\r
- PrintUsage('No files were specified.')\r
-\r
- _SetOutputFormat(output_format)\r
- _SetVerboseLevel(verbosity)\r
- _SetFilters(filters)\r
- _SetCountingStyle(counting_style)\r
-\r
- return filenames\r
-\r
-\r
-def main():\r
- filenames = ParseArguments(sys.argv[1:])\r
-\r
- # Change stderr to write with replacement characters so we don't die\r
- # if we try to print something containing non-ASCII characters.\r
- sys.stderr = codecs.StreamReaderWriter(sys.stderr,\r
- codecs.getreader('utf8'),\r
- codecs.getwriter('utf8'),\r
- 'replace')\r
-\r
- _cpplint_state.ResetErrorCounts()\r
- for filename in filenames:\r
- ProcessFile(filename, _cpplint_state.verbose_level)\r
- _cpplint_state.PrintErrorCounts()\r
-\r
- sys.exit(_cpplint_state.error_count > 0)\r
-\r
-\r
-if __name__ == '__main__':\r
- main()\r
+++ /dev/null
-#!/usr/bin/env python\r
-#\r
-# Copyright (c) 2009 Google Inc. All rights reserved.\r
-#\r
-# Redistribution and use in source and binary forms, with or without\r
-# modification, are permitted provided that the following conditions are\r
-# met:\r
-#\r
-# * Redistributions of source code must retain the above copyright\r
-# notice, this list of conditions and the following disclaimer.\r
-# * Redistributions in binary form must reproduce the above\r
-# copyright notice, this list of conditions and the following disclaimer\r
-# in the documentation and/or other materials provided with the\r
-# distribution.\r
-# * Neither the name of Google Inc. nor the names of its\r
-# contributors may be used to endorse or promote products derived from\r
-# this software without specific prior written permission.\r
-#\r
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r
-# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\r
-# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\r
-# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\r
-# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\r
-# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\r
-# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\r
-# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\r
-# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\r
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r
-\r
-"""Does google-lint on c++ files.\r
-\r
-The goal of this script is to identify places in the code that *may*\r
-be in non-compliance with google style. It does not attempt to fix\r
-up these problems -- the point is to educate. It does also not\r
-attempt to find all problems, or to ensure that everything it does\r
-find is legitimately a problem.\r
-\r
-In particular, we can get very confused by /* and // inside strings!\r
-We do a small hack, which is to ignore //'s with "'s after them on the\r
-same line, but it is far from perfect (in either direction).\r
-"""\r
-\r
-import codecs\r
-import copy\r
-import getopt\r
-import math # for log\r
-import os\r
-import re\r
-import sre_compile\r
-import string\r
-import sys\r
-import unicodedata\r
-\r
-\r
-_USAGE = """\r
-Syntax: cpplint.py [--verbose=#] [--output=vs7] [--filter=-x,+y,...]\r
- [--counting=total|toplevel|detailed] [--root=subdir]\r
- [--linelength=digits] [--headers=x,y,...]\r
- <file> [file] ...\r
-\r
- The style guidelines this tries to follow are those in\r
- https://google-styleguide.googlecode.com/svn/trunk/cppguide.xml\r
-\r
- Every problem is given a confidence score from 1-5, with 5 meaning we are\r
- certain of the problem, and 1 meaning it could be a legitimate construct.\r
- This will miss some errors, and is not a substitute for a code review.\r
-\r
- To suppress false-positive errors of a certain category, add a\r
- 'NOLINT(category)' comment to the line. NOLINT or NOLINT(*)\r
- suppresses errors of all categories on that line.\r
-\r
- The files passed in will be linted; at least one file must be provided.\r
- Default linted extensions are .cc, .cpp, .cu, .cuh and .h. Change the\r
- extensions with the --extensions flag.\r
-\r
- Flags:\r
-\r
- output=vs7\r
- By default, the output is formatted to ease emacs parsing. Visual Studio\r
- compatible output (vs7) may also be used. Other formats are unsupported.\r
-\r
- verbose=#\r
- Specify a number 0-5 to restrict errors to certain verbosity levels.\r
-\r
- filter=-x,+y,...\r
- Specify a comma-separated list of category-filters to apply: only\r
- error messages whose category names pass the filters will be printed.\r
- (Category names are printed with the message and look like\r
- "[whitespace/indent]".) Filters are evaluated left to right.\r
- "-FOO" and "FOO" means "do not print categories that start with FOO".\r
- "+FOO" means "do print categories that start with FOO".\r
-\r
- Examples: --filter=-whitespace,+whitespace/braces\r
- --filter=whitespace,runtime/printf,+runtime/printf_format\r
- --filter=-,+build/include_what_you_use\r
-\r
- To see a list of all the categories used in cpplint, pass no arg:\r
- --filter=\r
-\r
- counting=total|toplevel|detailed\r
- The total number of errors found is always printed. If\r
- 'toplevel' is provided, then the count of errors in each of\r
- the top-level categories like 'build' and 'whitespace' will\r
- also be printed. If 'detailed' is provided, then a count\r
- is provided for each category like 'build/class'.\r
-\r
- root=subdir\r
- The root directory used for deriving header guard CPP variable.\r
- By default, the header guard CPP variable is calculated as the relative\r
- path to the directory that contains .git, .hg, or .svn. When this flag\r
- is specified, the relative path is calculated from the specified\r
- directory. If the specified directory does not exist, this flag is\r
- ignored.\r
-\r
- Examples:\r
- Assuming that src/.git exists, the header guard CPP variables for\r
- src/chrome/browser/ui/browser.h are:\r
-\r
- No flag => CHROME_BROWSER_UI_BROWSER_H_\r
- --root=chrome => BROWSER_UI_BROWSER_H_\r
- --root=chrome/browser => UI_BROWSER_H_\r
-\r
- linelength=digits\r
- This is the allowed line length for the project. The default value is\r
- 80 characters.\r
-\r
- Examples:\r
- --linelength=120\r
-\r
- extensions=extension,extension,...\r
- The allowed file extensions that cpplint will check\r
-\r
- Examples:\r
- --extensions=hpp,cpp\r
-\r
- headers=x,y,...\r
- The header extensions that cpplint will treat as .h in checks. Values are\r
- automatically added to --extensions list.\r
-\r
- Examples:\r
- --headers=hpp,hxx\r
- --headers=hpp\r
-\r
- cpplint.py supports per-directory configurations specified in CPPLINT.cfg\r
- files. CPPLINT.cfg file can contain a number of key=value pairs.\r
- Currently the following options are supported:\r
-\r
- set noparent\r
- filter=+filter1,-filter2,...\r
- exclude_files=regex\r
- linelength=80\r
- root=subdir\r
- headers=x,y,...\r
-\r
- "set noparent" option prevents cpplint from traversing directory tree\r
- upwards looking for more .cfg files in parent directories. This option\r
- is usually placed in the top-level project directory.\r
-\r
- The "filter" option is similar in function to --filter flag. It specifies\r
- message filters in addition to the |_DEFAULT_FILTERS| and those specified\r
- through --filter command-line flag.\r
-\r
- "exclude_files" allows to specify a regular expression to be matched against\r
- a file name. If the expression matches, the file is skipped and not run\r
- through liner.\r
-\r
- "linelength" allows to specify the allowed line length for the project.\r
-\r
- The "root" option is similar in function to the --root flag (see example\r
- above).\r
- \r
- The "headers" option is similar in function to the --headers flag \r
- (see example above).\r
-\r
- CPPLINT.cfg has an effect on files in the same directory and all\r
- sub-directories, unless overridden by a nested configuration file.\r
-\r
- Example file:\r
- filter=-build/include_order,+build/include_alpha\r
- exclude_files=.*\.cc\r
-\r
- The above example disables build/include_order warning and enables\r
- build/include_alpha as well as excludes all .cc from being\r
- processed by linter, in the current directory (where the .cfg\r
- file is located) and all sub-directories.\r
-"""\r
-\r
-# We categorize each error message we print. Here are the categories.\r
-# We want an explicit list so we can list them all in cpplint --filter=.\r
-# If you add a new error message with a new category, add it to the list\r
-# here! cpplint_unittest.py should tell you if you forget to do this.\r
-_ERROR_CATEGORIES = [\r
- 'build/class',\r
- 'build/c++11',\r
- 'build/c++14',\r
- 'build/c++tr1',\r
- 'build/deprecated',\r
- 'build/endif_comment',\r
- 'build/explicit_make_pair',\r
- 'build/forward_decl',\r
- 'build/header_guard',\r
- 'build/include',\r
- 'build/include_alpha',\r
- 'build/include_order',\r
- 'build/include_what_you_use',\r
- 'build/namespaces',\r
- 'build/printf_format',\r
- 'build/storage_class',\r
- 'legal/copyright',\r
- 'readability/alt_tokens',\r
- 'readability/braces',\r
- 'readability/casting',\r
- 'readability/check',\r
- 'readability/constructors',\r
- 'readability/fn_size',\r
- 'readability/inheritance',\r
- 'readability/multiline_comment',\r
- 'readability/multiline_string',\r
- 'readability/namespace',\r
- 'readability/nolint',\r
- 'readability/nul',\r
- 'readability/strings',\r
- 'readability/todo',\r
- 'readability/utf8',\r
- 'runtime/arrays',\r
- 'runtime/casting',\r
- 'runtime/explicit',\r
- 'runtime/int',\r
- 'runtime/init',\r
- 'runtime/invalid_increment',\r
- 'runtime/member_string_references',\r
- 'runtime/memset',\r
- 'runtime/indentation_namespace',\r
- 'runtime/operator',\r
- 'runtime/printf',\r
- 'runtime/printf_format',\r
- 'runtime/references',\r
- 'runtime/string',\r
- 'runtime/threadsafe_fn',\r
- 'runtime/vlog',\r
- 'whitespace/blank_line',\r
- 'whitespace/braces',\r
- 'whitespace/comma',\r
- 'whitespace/comments',\r
- 'whitespace/empty_conditional_body',\r
- 'whitespace/empty_if_body',\r
- 'whitespace/empty_loop_body',\r
- 'whitespace/end_of_line',\r
- 'whitespace/ending_newline',\r
- 'whitespace/forcolon',\r
- 'whitespace/indent',\r
- 'whitespace/line_length',\r
- 'whitespace/newline',\r
- 'whitespace/operators',\r
- 'whitespace/parens',\r
- 'whitespace/semicolon',\r
- 'whitespace/tab',\r
- 'whitespace/todo',\r
- ]\r
-\r
-# These error categories are no longer enforced by cpplint, but for backwards-\r
-# compatibility they may still appear in NOLINT comments.\r
-_LEGACY_ERROR_CATEGORIES = [\r
- 'readability/streams',\r
- 'readability/function',\r
- ]\r
-\r
-# The default state of the category filter. This is overridden by the --filter=\r
-# flag. By default all errors are on, so only add here categories that should be\r
-# off by default (i.e., categories that must be enabled by the --filter= flags).\r
-# All entries here should start with a '-' or '+', as in the --filter= flag.\r
-_DEFAULT_FILTERS = ['-build/include_alpha']\r
-\r
-# The default list of categories suppressed for C (not C++) files.\r
-_DEFAULT_C_SUPPRESSED_CATEGORIES = [\r
- 'readability/casting',\r
- ]\r
-\r
-# The default list of categories suppressed for Linux Kernel files.\r
-_DEFAULT_KERNEL_SUPPRESSED_CATEGORIES = [\r
- 'whitespace/tab',\r
- ]\r
-\r
-# We used to check for high-bit characters, but after much discussion we\r
-# decided those were OK, as long as they were in UTF-8 and didn't represent\r
-# hard-coded international strings, which belong in a separate i18n file.\r
-\r
-# C++ headers\r
-_CPP_HEADERS = frozenset([\r
- # Legacy\r
- 'algobase.h',\r
- 'algo.h',\r
- 'alloc.h',\r
- 'builtinbuf.h',\r
- 'bvector.h',\r
- 'complex.h',\r
- 'defalloc.h',\r
- 'deque.h',\r
- 'editbuf.h',\r
- 'fstream.h',\r
- 'function.h',\r
- 'hash_map',\r
- 'hash_map.h',\r
- 'hash_set',\r
- 'hash_set.h',\r
- 'hashtable.h',\r
- 'heap.h',\r
- 'indstream.h',\r
- 'iomanip.h',\r
- 'iostream.h',\r
- 'istream.h',\r
- 'iterator.h',\r
- 'list.h',\r
- 'map.h',\r
- 'multimap.h',\r
- 'multiset.h',\r
- 'ostream.h',\r
- 'pair.h',\r
- 'parsestream.h',\r
- 'pfstream.h',\r
- 'procbuf.h',\r
- 'pthread_alloc',\r
- 'pthread_alloc.h',\r
- 'rope',\r
- 'rope.h',\r
- 'ropeimpl.h',\r
- 'set.h',\r
- 'slist',\r
- 'slist.h',\r
- 'stack.h',\r
- 'stdiostream.h',\r
- 'stl_alloc.h',\r
- 'stl_relops.h',\r
- 'streambuf.h',\r
- 'stream.h',\r
- 'strfile.h',\r
- 'strstream.h',\r
- 'tempbuf.h',\r
- 'tree.h',\r
- 'type_traits.h',\r
- 'vector.h',\r
- # 17.6.1.2 C++ library headers\r
- 'algorithm',\r
- 'array',\r
- 'atomic',\r
- 'bitset',\r
- 'chrono',\r
- 'codecvt',\r
- 'complex',\r
- 'condition_variable',\r
- 'deque',\r
- 'exception',\r
- 'forward_list',\r
- 'fstream',\r
- 'functional',\r
- 'future',\r
- 'initializer_list',\r
- 'iomanip',\r
- 'ios',\r
- 'iosfwd',\r
- 'iostream',\r
- 'istream',\r
- 'iterator',\r
- 'limits',\r
- 'list',\r
- 'locale',\r
- 'map',\r
- 'memory',\r
- 'mutex',\r
- 'new',\r
- 'numeric',\r
- 'ostream',\r
- 'queue',\r
- 'random',\r
- 'ratio',\r
- 'regex',\r
- 'scoped_allocator',\r
- 'set',\r
- 'sstream',\r
- 'stack',\r
- 'stdexcept',\r
- 'streambuf',\r
- 'string',\r
- 'strstream',\r
- 'system_error',\r
- 'thread',\r
- 'tuple',\r
- 'typeindex',\r
- 'typeinfo',\r
- 'type_traits',\r
- 'unordered_map',\r
- 'unordered_set',\r
- 'utility',\r
- 'valarray',\r
- 'vector',\r
- # 17.6.1.2 C++ headers for C library facilities\r
- 'cassert',\r
- 'ccomplex',\r
- 'cctype',\r
- 'cerrno',\r
- 'cfenv',\r
- 'cfloat',\r
- 'cinttypes',\r
- 'ciso646',\r
- 'climits',\r
- 'clocale',\r
- 'cmath',\r
- 'csetjmp',\r
- 'csignal',\r
- 'cstdalign',\r
- 'cstdarg',\r
- 'cstdbool',\r
- 'cstddef',\r
- 'cstdint',\r
- 'cstdio',\r
- 'cstdlib',\r
- 'cstring',\r
- 'ctgmath',\r
- 'ctime',\r
- 'cuchar',\r
- 'cwchar',\r
- 'cwctype',\r
- ])\r
-\r
-# Type names\r
-_TYPES = re.compile(\r
- r'^(?:'\r
- # [dcl.type.simple]\r
- r'(char(16_t|32_t)?)|wchar_t|'\r
- r'bool|short|int|long|signed|unsigned|float|double|'\r
- # [support.types]\r
- r'(ptrdiff_t|size_t|max_align_t|nullptr_t)|'\r
- # [cstdint.syn]\r
- r'(u?int(_fast|_least)?(8|16|32|64)_t)|'\r
- r'(u?int(max|ptr)_t)|'\r
- r')$')\r
-\r
-\r
-# These headers are excluded from [build/include] and [build/include_order]\r
-# checks:\r
-# - Anything not following google file name conventions (containing an\r
-# uppercase character, such as Python.h or nsStringAPI.h, for example).\r
-# - Lua headers.\r
-_THIRD_PARTY_HEADERS_PATTERN = re.compile(\r
- r'^(?:[^/]*[A-Z][^/]*\.h|lua\.h|lauxlib\.h|lualib\.h)$')\r
-\r
-# Pattern for matching FileInfo.BaseName() against test file name\r
-_TEST_FILE_SUFFIX = r'(_test|_unittest|_regtest)$'\r
-\r
-# Pattern that matches only complete whitespace, possibly across multiple lines.\r
-_EMPTY_CONDITIONAL_BODY_PATTERN = re.compile(r'^\s*$', re.DOTALL)\r
-\r
-# Assertion macros. These are defined in base/logging.h and\r
-# testing/base/public/gunit.h.\r
-_CHECK_MACROS = [\r
- 'DCHECK', 'CHECK',\r
- 'EXPECT_TRUE', 'ASSERT_TRUE',\r
- 'EXPECT_FALSE', 'ASSERT_FALSE',\r
- ]\r
-\r
-# Replacement macros for CHECK/DCHECK/EXPECT_TRUE/EXPECT_FALSE\r
-_CHECK_REPLACEMENT = dict([(m, {}) for m in _CHECK_MACROS])\r
-\r
-for op, replacement in [('==', 'EQ'), ('!=', 'NE'),\r
- ('>=', 'GE'), ('>', 'GT'),\r
- ('<=', 'LE'), ('<', 'LT')]:\r
- _CHECK_REPLACEMENT['DCHECK'][op] = 'DCHECK_%s' % replacement\r
- _CHECK_REPLACEMENT['CHECK'][op] = 'CHECK_%s' % replacement\r
- _CHECK_REPLACEMENT['EXPECT_TRUE'][op] = 'EXPECT_%s' % replacement\r
- _CHECK_REPLACEMENT['ASSERT_TRUE'][op] = 'ASSERT_%s' % replacement\r
-\r
-for op, inv_replacement in [('==', 'NE'), ('!=', 'EQ'),\r
- ('>=', 'LT'), ('>', 'LE'),\r
- ('<=', 'GT'), ('<', 'GE')]:\r
- _CHECK_REPLACEMENT['EXPECT_FALSE'][op] = 'EXPECT_%s' % inv_replacement\r
- _CHECK_REPLACEMENT['ASSERT_FALSE'][op] = 'ASSERT_%s' % inv_replacement\r
-\r
-# Alternative tokens and their replacements. For full list, see section 2.5\r
-# Alternative tokens [lex.digraph] in the C++ standard.\r
-#\r
-# Digraphs (such as '%:') are not included here since it's a mess to\r
-# match those on a word boundary.\r
-_ALT_TOKEN_REPLACEMENT = {\r
- 'and': '&&',\r
- 'bitor': '|',\r
- 'or': '||',\r
- 'xor': '^',\r
- 'compl': '~',\r
- 'bitand': '&',\r
- 'and_eq': '&=',\r
- 'or_eq': '|=',\r
- 'xor_eq': '^=',\r
- 'not': '!',\r
- 'not_eq': '!='\r
- }\r
-\r
-# Compile regular expression that matches all the above keywords. The "[ =()]"\r
-# bit is meant to avoid matching these keywords outside of boolean expressions.\r
-#\r
-# False positives include C-style multi-line comments and multi-line strings\r
-# but those have always been troublesome for cpplint.\r
-_ALT_TOKEN_REPLACEMENT_PATTERN = re.compile(\r
- r'[ =()](' + ('|'.join(_ALT_TOKEN_REPLACEMENT.keys())) + r')(?=[ (]|$)')\r
-\r
-\r
-# These constants define types of headers for use with\r
-# _IncludeState.CheckNextIncludeOrder().\r
-_C_SYS_HEADER = 1\r
-_CPP_SYS_HEADER = 2\r
-_LIKELY_MY_HEADER = 3\r
-_POSSIBLE_MY_HEADER = 4\r
-_OTHER_HEADER = 5\r
-\r
-# These constants define the current inline assembly state\r
-_NO_ASM = 0 # Outside of inline assembly block\r
-_INSIDE_ASM = 1 # Inside inline assembly block\r
-_END_ASM = 2 # Last line of inline assembly block\r
-_BLOCK_ASM = 3 # The whole block is an inline assembly block\r
-\r
-# Match start of assembly blocks\r
-_MATCH_ASM = re.compile(r'^\s*(?:asm|_asm|__asm|__asm__)'\r
- r'(?:\s+(volatile|__volatile__))?'\r
- r'\s*[{(]')\r
-\r
-# Match strings that indicate we're working on a C (not C++) file.\r
-_SEARCH_C_FILE = re.compile(r'\b(?:LINT_C_FILE|'\r
- r'vim?:\s*.*(\s*|:)filetype=c(\s*|:|$))')\r
-\r
-# Match string that indicates we're working on a Linux Kernel file.\r
-_SEARCH_KERNEL_FILE = re.compile(r'\b(?:LINT_KERNEL_FILE)')\r
-\r
-_regexp_compile_cache = {}\r
-\r
-# {str, set(int)}: a map from error categories to sets of linenumbers\r
-# on which those errors are expected and should be suppressed.\r
-_error_suppressions = {}\r
-\r
-# The root directory used for deriving header guard CPP variable.\r
-# This is set by --root flag.\r
-_root = None\r
-\r
-# The allowed line length of files.\r
-# This is set by --linelength flag.\r
-_line_length = 80\r
-\r
-# The allowed extensions for file names\r
-# This is set by --extensions flag.\r
-_valid_extensions = set(['cc', 'h', 'cpp', 'cu', 'cuh'])\r
-\r
-# Treat all headers starting with 'h' equally: .h, .hpp, .hxx etc.\r
-# This is set by --headers flag.\r
-_hpp_headers = set(['h'])\r
-\r
-# {str, bool}: a map from error categories to booleans which indicate if the\r
-# category should be suppressed for every line.\r
-_global_error_suppressions = {}\r
-\r
-def ProcessHppHeadersOption(val):\r
- global _hpp_headers\r
- try:\r
- _hpp_headers = set(val.split(','))\r
- # Automatically append to extensions list so it does not have to be set 2 times\r
- _valid_extensions.update(_hpp_headers)\r
- except ValueError:\r
- PrintUsage('Header extensions must be comma seperated list.')\r
-\r
-def IsHeaderExtension(file_extension):\r
- return file_extension in _hpp_headers\r
-\r
-def ParseNolintSuppressions(filename, raw_line, linenum, error):\r
- """Updates the global list of line error-suppressions.\r
-\r
- Parses any NOLINT comments on the current line, updating the global\r
- error_suppressions store. Reports an error if the NOLINT comment\r
- was malformed.\r
-\r
- Args:\r
- filename: str, the name of the input file.\r
- raw_line: str, the line of input text, with comments.\r
- linenum: int, the number of the current line.\r
- error: function, an error handler.\r
- """\r
- matched = Search(r'\bNOLINT(NEXTLINE)?\b(\([^)]+\))?', raw_line)\r
- if matched:\r
- if matched.group(1):\r
- suppressed_line = linenum + 1\r
- else:\r
- suppressed_line = linenum\r
- category = matched.group(2)\r
- if category in (None, '(*)'): # => "suppress all"\r
- _error_suppressions.setdefault(None, set()).add(suppressed_line)\r
- else:\r
- if category.startswith('(') and category.endswith(')'):\r
- category = category[1:-1]\r
- if category in _ERROR_CATEGORIES:\r
- _error_suppressions.setdefault(category, set()).add(suppressed_line)\r
- elif category not in _LEGACY_ERROR_CATEGORIES:\r
- error(filename, linenum, 'readability/nolint', 5,\r
- 'Unknown NOLINT error category: %s' % category)\r
-\r
-\r
-def ProcessGlobalSuppresions(lines):\r
- """Updates the list of global error suppressions.\r
-\r
- Parses any lint directives in the file that have global effect.\r
-\r
- Args:\r
- lines: An array of strings, each representing a line of the file, with the\r
- last element being empty if the file is terminated with a newline.\r
- """\r
- for line in lines:\r
- if _SEARCH_C_FILE.search(line):\r
- for category in _DEFAULT_C_SUPPRESSED_CATEGORIES:\r
- _global_error_suppressions[category] = True\r
- if _SEARCH_KERNEL_FILE.search(line):\r
- for category in _DEFAULT_KERNEL_SUPPRESSED_CATEGORIES:\r
- _global_error_suppressions[category] = True\r
-\r
-\r
-def ResetNolintSuppressions():\r
- """Resets the set of NOLINT suppressions to empty."""\r
- _error_suppressions.clear()\r
- _global_error_suppressions.clear()\r
-\r
-\r
-def IsErrorSuppressedByNolint(category, linenum):\r
- """Returns true if the specified error category is suppressed on this line.\r
-\r
- Consults the global error_suppressions map populated by\r
- ParseNolintSuppressions/ProcessGlobalSuppresions/ResetNolintSuppressions.\r
-\r
- Args:\r
- category: str, the category of the error.\r
- linenum: int, the current line number.\r
- Returns:\r
- bool, True iff the error should be suppressed due to a NOLINT comment or\r
- global suppression.\r
- """\r
- return (_global_error_suppressions.get(category, False) or\r
- linenum in _error_suppressions.get(category, set()) or\r
- linenum in _error_suppressions.get(None, set()))\r
-\r
-\r
-def Match(pattern, s):\r
- """Matches the string with the pattern, caching the compiled regexp."""\r
- # The regexp compilation caching is inlined in both Match and Search for\r
- # performance reasons; factoring it out into a separate function turns out\r
- # to be noticeably expensive.\r
- if pattern not in _regexp_compile_cache:\r
- _regexp_compile_cache[pattern] = sre_compile.compile(pattern)\r
- return _regexp_compile_cache[pattern].match(s)\r
-\r
-\r
-def ReplaceAll(pattern, rep, s):\r
- """Replaces instances of pattern in a string with a replacement.\r
-\r
- The compiled regex is kept in a cache shared by Match and Search.\r
-\r
- Args:\r
- pattern: regex pattern\r
- rep: replacement text\r
- s: search string\r
-\r
- Returns:\r
- string with replacements made (or original string if no replacements)\r
- """\r
- if pattern not in _regexp_compile_cache:\r
- _regexp_compile_cache[pattern] = sre_compile.compile(pattern)\r
- return _regexp_compile_cache[pattern].sub(rep, s)\r
-\r
-\r
-def Search(pattern, s):\r
- """Searches the string for the pattern, caching the compiled regexp."""\r
- if pattern not in _regexp_compile_cache:\r
- _regexp_compile_cache[pattern] = sre_compile.compile(pattern)\r
- return _regexp_compile_cache[pattern].search(s)\r
-\r
-\r
-def _IsSourceExtension(s):\r
- """File extension (excluding dot) matches a source file extension."""\r
- return s in ('c', 'cc', 'cpp', 'cxx')\r
-\r
-\r
-class _IncludeState(object):\r
- """Tracks line numbers for includes, and the order in which includes appear.\r
-\r
- include_list contains list of lists of (header, line number) pairs.\r
- It's a lists of lists rather than just one flat list to make it\r
- easier to update across preprocessor boundaries.\r
-\r
- Call CheckNextIncludeOrder() once for each header in the file, passing\r
- in the type constants defined above. Calls in an illegal order will\r
- raise an _IncludeError with an appropriate error message.\r
-\r
- """\r
- # self._section will move monotonically through this set. If it ever\r
- # needs to move backwards, CheckNextIncludeOrder will raise an error.\r
- _INITIAL_SECTION = 0\r
- _MY_H_SECTION = 1\r
- _C_SECTION = 2\r
- _CPP_SECTION = 3\r
- _OTHER_H_SECTION = 4\r
-\r
- _TYPE_NAMES = {\r
- _C_SYS_HEADER: 'C system header',\r
- _CPP_SYS_HEADER: 'C++ system header',\r
- _LIKELY_MY_HEADER: 'header this file implements',\r
- _POSSIBLE_MY_HEADER: 'header this file may implement',\r
- _OTHER_HEADER: 'other header',\r
- }\r
- _SECTION_NAMES = {\r
- _INITIAL_SECTION: "... nothing. (This can't be an error.)",\r
- _MY_H_SECTION: 'a header this file implements',\r
- _C_SECTION: 'C system header',\r
- _CPP_SECTION: 'C++ system header',\r
- _OTHER_H_SECTION: 'other header',\r
- }\r
-\r
- def __init__(self):\r
- self.include_list = [[]]\r
- self.ResetSection('')\r
-\r
- def FindHeader(self, header):\r
- """Check if a header has already been included.\r
-\r
- Args:\r
- header: header to check.\r
- Returns:\r
- Line number of previous occurrence, or -1 if the header has not\r
- been seen before.\r
- """\r
- for section_list in self.include_list:\r
- for f in section_list:\r
- if f[0] == header:\r
- return f[1]\r
- return -1\r
-\r
- def ResetSection(self, directive):\r
- """Reset section checking for preprocessor directive.\r
-\r
- Args:\r
- directive: preprocessor directive (e.g. "if", "else").\r
- """\r
- # The name of the current section.\r
- self._section = self._INITIAL_SECTION\r
- # The path of last found header.\r
- self._last_header = ''\r
-\r
- # Update list of includes. Note that we never pop from the\r
- # include list.\r
- if directive in ('if', 'ifdef', 'ifndef'):\r
- self.include_list.append([])\r
- elif directive in ('else', 'elif'):\r
- self.include_list[-1] = []\r
-\r
- def SetLastHeader(self, header_path):\r
- self._last_header = header_path\r
-\r
- def CanonicalizeAlphabeticalOrder(self, header_path):\r
- """Returns a path canonicalized for alphabetical comparison.\r
-\r
- - replaces "-" with "_" so they both cmp the same.\r
- - removes '-inl' since we don't require them to be after the main header.\r
- - lowercase everything, just in case.\r
-\r
- Args:\r
- header_path: Path to be canonicalized.\r
-\r
- Returns:\r
- Canonicalized path.\r
- """\r
- return header_path.replace('-inl.h', '.h').replace('-', '_').lower()\r
-\r
- def IsInAlphabeticalOrder(self, clean_lines, linenum, header_path):\r
- """Check if a header is in alphabetical order with the previous header.\r
-\r
- Args:\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- header_path: Canonicalized header to be checked.\r
-\r
- Returns:\r
- Returns true if the header is in alphabetical order.\r
- """\r
- # If previous section is different from current section, _last_header will\r
- # be reset to empty string, so it's always less than current header.\r
- #\r
- # If previous line was a blank line, assume that the headers are\r
- # intentionally sorted the way they are.\r
- if (self._last_header > header_path and\r
- Match(r'^\s*#\s*include\b', clean_lines.elided[linenum - 1])):\r
- return False\r
- return True\r
-\r
- def CheckNextIncludeOrder(self, header_type):\r
- """Returns a non-empty error message if the next header is out of order.\r
-\r
- This function also updates the internal state to be ready to check\r
- the next include.\r
-\r
- Args:\r
- header_type: One of the _XXX_HEADER constants defined above.\r
-\r
- Returns:\r
- The empty string if the header is in the right order, or an\r
- error message describing what's wrong.\r
-\r
- """\r
- error_message = ('Found %s after %s' %\r
- (self._TYPE_NAMES[header_type],\r
- self._SECTION_NAMES[self._section]))\r
-\r
- last_section = self._section\r
-\r
- if header_type == _C_SYS_HEADER:\r
- if self._section <= self._C_SECTION:\r
- self._section = self._C_SECTION\r
- else:\r
- self._last_header = ''\r
- return error_message\r
- elif header_type == _CPP_SYS_HEADER:\r
- if self._section <= self._CPP_SECTION:\r
- self._section = self._CPP_SECTION\r
- else:\r
- self._last_header = ''\r
- return error_message\r
- elif header_type == _LIKELY_MY_HEADER:\r
- if self._section <= self._MY_H_SECTION:\r
- self._section = self._MY_H_SECTION\r
- else:\r
- self._section = self._OTHER_H_SECTION\r
- elif header_type == _POSSIBLE_MY_HEADER:\r
- if self._section <= self._MY_H_SECTION:\r
- self._section = self._MY_H_SECTION\r
- else:\r
- # This will always be the fallback because we're not sure\r
- # enough that the header is associated with this file.\r
- self._section = self._OTHER_H_SECTION\r
- else:\r
- assert header_type == _OTHER_HEADER\r
- self._section = self._OTHER_H_SECTION\r
-\r
- if last_section != self._section:\r
- self._last_header = ''\r
-\r
- return ''\r
-\r
-\r
-class _CppLintState(object):\r
- """Maintains module-wide state.."""\r
-\r
- def __init__(self):\r
- self.verbose_level = 1 # global setting.\r
- self.error_count = 0 # global count of reported errors\r
- # filters to apply when emitting error messages\r
- self.filters = _DEFAULT_FILTERS[:]\r
- # backup of filter list. Used to restore the state after each file.\r
- self._filters_backup = self.filters[:]\r
- self.counting = 'total' # In what way are we counting errors?\r
- self.errors_by_category = {} # string to int dict storing error counts\r
-\r
- # output format:\r
- # "emacs" - format that emacs can parse (default)\r
- # "vs7" - format that Microsoft Visual Studio 7 can parse\r
- self.output_format = 'emacs'\r
-\r
- def SetOutputFormat(self, output_format):\r
- """Sets the output format for errors."""\r
- self.output_format = output_format\r
-\r
- def SetVerboseLevel(self, level):\r
- """Sets the module's verbosity, and returns the previous setting."""\r
- last_verbose_level = self.verbose_level\r
- self.verbose_level = level\r
- return last_verbose_level\r
-\r
- def SetCountingStyle(self, counting_style):\r
- """Sets the module's counting options."""\r
- self.counting = counting_style\r
-\r
- def SetFilters(self, filters):\r
- """Sets the error-message filters.\r
-\r
- These filters are applied when deciding whether to emit a given\r
- error message.\r
-\r
- Args:\r
- filters: A string of comma-separated filters (eg "+whitespace/indent").\r
- Each filter should start with + or -; else we die.\r
-\r
- Raises:\r
- ValueError: The comma-separated filters did not all start with '+' or '-'.\r
- E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter"\r
- """\r
- # Default filters always have less priority than the flag ones.\r
- self.filters = _DEFAULT_FILTERS[:]\r
- self.AddFilters(filters)\r
-\r
- def AddFilters(self, filters):\r
- """ Adds more filters to the existing list of error-message filters. """\r
- for filt in filters.split(','):\r
- clean_filt = filt.strip()\r
- if clean_filt:\r
- self.filters.append(clean_filt)\r
- for filt in self.filters:\r
- if not (filt.startswith('+') or filt.startswith('-')):\r
- raise ValueError('Every filter in --filters must start with + or -'\r
- ' (%s does not)' % filt)\r
-\r
- def BackupFilters(self):\r
- """ Saves the current filter list to backup storage."""\r
- self._filters_backup = self.filters[:]\r
-\r
- def RestoreFilters(self):\r
- """ Restores filters previously backed up."""\r
- self.filters = self._filters_backup[:]\r
-\r
- def ResetErrorCounts(self):\r
- """Sets the module's error statistic back to zero."""\r
- self.error_count = 0\r
- self.errors_by_category = {}\r
-\r
- def IncrementErrorCount(self, category):\r
- """Bumps the module's error statistic."""\r
- self.error_count += 1\r
- if self.counting in ('toplevel', 'detailed'):\r
- if self.counting != 'detailed':\r
- category = category.split('/')[0]\r
- if category not in self.errors_by_category:\r
- self.errors_by_category[category] = 0\r
- self.errors_by_category[category] += 1\r
-\r
- def PrintErrorCounts(self):\r
- """Print a summary of errors by category, and the total."""\r
- for category, count in self.errors_by_category.iteritems():\r
- sys.stderr.write('Category \'%s\' errors found: %d\n' %\r
- (category, count))\r
- sys.stdout.write('Total errors found: %d\n' % self.error_count)\r
-\r
-_cpplint_state = _CppLintState()\r
-\r
-\r
-def _OutputFormat():\r
- """Gets the module's output format."""\r
- return _cpplint_state.output_format\r
-\r
-\r
-def _SetOutputFormat(output_format):\r
- """Sets the module's output format."""\r
- _cpplint_state.SetOutputFormat(output_format)\r
-\r
-\r
-def _VerboseLevel():\r
- """Returns the module's verbosity setting."""\r
- return _cpplint_state.verbose_level\r
-\r
-\r
-def _SetVerboseLevel(level):\r
- """Sets the module's verbosity, and returns the previous setting."""\r
- return _cpplint_state.SetVerboseLevel(level)\r
-\r
-\r
-def _SetCountingStyle(level):\r
- """Sets the module's counting options."""\r
- _cpplint_state.SetCountingStyle(level)\r
-\r
-\r
-def _Filters():\r
- """Returns the module's list of output filters, as a list."""\r
- return _cpplint_state.filters\r
-\r
-\r
-def _SetFilters(filters):\r
- """Sets the module's error-message filters.\r
-\r
- These filters are applied when deciding whether to emit a given\r
- error message.\r
-\r
- Args:\r
- filters: A string of comma-separated filters (eg "whitespace/indent").\r
- Each filter should start with + or -; else we die.\r
- """\r
- _cpplint_state.SetFilters(filters)\r
-\r
-def _AddFilters(filters):\r
- """Adds more filter overrides.\r
-\r
- Unlike _SetFilters, this function does not reset the current list of filters\r
- available.\r
-\r
- Args:\r
- filters: A string of comma-separated filters (eg "whitespace/indent").\r
- Each filter should start with + or -; else we die.\r
- """\r
- _cpplint_state.AddFilters(filters)\r
-\r
-def _BackupFilters():\r
- """ Saves the current filter list to backup storage."""\r
- _cpplint_state.BackupFilters()\r
-\r
-def _RestoreFilters():\r
- """ Restores filters previously backed up."""\r
- _cpplint_state.RestoreFilters()\r
-\r
-class _FunctionState(object):\r
- """Tracks current function name and the number of lines in its body."""\r
-\r
- _NORMAL_TRIGGER = 250 # for --v=0, 500 for --v=1, etc.\r
- _TEST_TRIGGER = 400 # about 50% more than _NORMAL_TRIGGER.\r
-\r
- def __init__(self):\r
- self.in_a_function = False\r
- self.lines_in_function = 0\r
- self.current_function = ''\r
-\r
- def Begin(self, function_name):\r
- """Start analyzing function body.\r
-\r
- Args:\r
- function_name: The name of the function being tracked.\r
- """\r
- self.in_a_function = True\r
- self.lines_in_function = 0\r
- self.current_function = function_name\r
-\r
- def Count(self):\r
- """Count line in current function body."""\r
- if self.in_a_function:\r
- self.lines_in_function += 1\r
-\r
- def Check(self, error, filename, linenum):\r
- """Report if too many lines in function body.\r
-\r
- Args:\r
- error: The function to call with any errors found.\r
- filename: The name of the current file.\r
- linenum: The number of the line to check.\r
- """\r
- if not self.in_a_function:\r
- return\r
-\r
- if Match(r'T(EST|est)', self.current_function):\r
- base_trigger = self._TEST_TRIGGER\r
- else:\r
- base_trigger = self._NORMAL_TRIGGER\r
- trigger = base_trigger * 2**_VerboseLevel()\r
-\r
- if self.lines_in_function > trigger:\r
- error_level = int(math.log(self.lines_in_function / base_trigger, 2))\r
- # 50 => 0, 100 => 1, 200 => 2, 400 => 3, 800 => 4, 1600 => 5, ...\r
- if error_level > 5:\r
- error_level = 5\r
- error(filename, linenum, 'readability/fn_size', error_level,\r
- 'Small and focused functions are preferred:'\r
- ' %s has %d non-comment lines'\r
- ' (error triggered by exceeding %d lines).' % (\r
- self.current_function, self.lines_in_function, trigger))\r
-\r
- def End(self):\r
- """Stop analyzing function body."""\r
- self.in_a_function = False\r
-\r
-\r
-class _IncludeError(Exception):\r
- """Indicates a problem with the include order in a file."""\r
- pass\r
-\r
-\r
-class FileInfo(object):\r
- """Provides utility functions for filenames.\r
-\r
- FileInfo provides easy access to the components of a file's path\r
- relative to the project root.\r
- """\r
-\r
- def __init__(self, filename):\r
- self._filename = filename\r
-\r
- def FullName(self):\r
- """Make Windows paths like Unix."""\r
- return os.path.abspath(self._filename).replace('\\', '/')\r
-\r
- def RepositoryName(self):\r
- """FullName after removing the local path to the repository.\r
-\r
- If we have a real absolute path name here we can try to do something smart:\r
- detecting the root of the checkout and truncating /path/to/checkout from\r
- the name so that we get header guards that don't include things like\r
- "C:\Documents and Settings\..." or "/home/username/..." in them and thus\r
- people on different computers who have checked the source out to different\r
- locations won't see bogus errors.\r
- """\r
- fullname = self.FullName()\r
-\r
- if os.path.exists(fullname):\r
- project_dir = os.path.dirname(fullname)\r
-\r
- if os.path.exists(os.path.join(project_dir, ".svn")):\r
- # If there's a .svn file in the current directory, we recursively look\r
- # up the directory tree for the top of the SVN checkout\r
- root_dir = project_dir\r
- one_up_dir = os.path.dirname(root_dir)\r
- while os.path.exists(os.path.join(one_up_dir, ".svn")):\r
- root_dir = os.path.dirname(root_dir)\r
- one_up_dir = os.path.dirname(one_up_dir)\r
-\r
- prefix = os.path.commonprefix([root_dir, project_dir])\r
- return fullname[len(prefix) + 1:]\r
-\r
- # Not SVN <= 1.6? Try to find a git, hg, or svn top level directory by\r
- # searching up from the current path.\r
- root_dir = current_dir = os.path.dirname(fullname)\r
- while current_dir != os.path.dirname(current_dir):\r
- if (os.path.exists(os.path.join(current_dir, ".git")) or\r
- os.path.exists(os.path.join(current_dir, ".hg")) or\r
- os.path.exists(os.path.join(current_dir, ".svn"))):\r
- root_dir = current_dir\r
- current_dir = os.path.dirname(current_dir)\r
-\r
- if (os.path.exists(os.path.join(root_dir, ".git")) or\r
- os.path.exists(os.path.join(root_dir, ".hg")) or\r
- os.path.exists(os.path.join(root_dir, ".svn"))):\r
- prefix = os.path.commonprefix([root_dir, project_dir])\r
- return fullname[len(prefix) + 1:]\r
-\r
- # Don't know what to do; header guard warnings may be wrong...\r
- return fullname\r
-\r
- def Split(self):\r
- """Splits the file into the directory, basename, and extension.\r
-\r
- For 'chrome/browser/browser.cc', Split() would\r
- return ('chrome/browser', 'browser', '.cc')\r
-\r
- Returns:\r
- A tuple of (directory, basename, extension).\r
- """\r
-\r
- googlename = self.RepositoryName()\r
- project, rest = os.path.split(googlename)\r
- return (project,) + os.path.splitext(rest)\r
-\r
- def BaseName(self):\r
- """File base name - text after the final slash, before the final period."""\r
- return self.Split()[1]\r
-\r
- def Extension(self):\r
- """File extension - text following the final period."""\r
- return self.Split()[2]\r
-\r
- def NoExtension(self):\r
- """File has no source file extension."""\r
- return '/'.join(self.Split()[0:2])\r
-\r
- def IsSource(self):\r
- """File has a source file extension."""\r
- return _IsSourceExtension(self.Extension()[1:])\r
-\r
-\r
-def _ShouldPrintError(category, confidence, linenum):\r
- """If confidence >= verbose, category passes filter and is not suppressed."""\r
-\r
- # There are three ways we might decide not to print an error message:\r
- # a "NOLINT(category)" comment appears in the source,\r
- # the verbosity level isn't high enough, or the filters filter it out.\r
- if IsErrorSuppressedByNolint(category, linenum):\r
- return False\r
-\r
- if confidence < _cpplint_state.verbose_level:\r
- return False\r
-\r
- is_filtered = False\r
- for one_filter in _Filters():\r
- if one_filter.startswith('-'):\r
- if category.startswith(one_filter[1:]):\r
- is_filtered = True\r
- elif one_filter.startswith('+'):\r
- if category.startswith(one_filter[1:]):\r
- is_filtered = False\r
- else:\r
- assert False # should have been checked for in SetFilter.\r
- if is_filtered:\r
- return False\r
-\r
- return True\r
-\r
-\r
-def Error(filename, linenum, category, confidence, message):\r
- """Logs the fact we've found a lint error.\r
-\r
- We log where the error was found, and also our confidence in the error,\r
- that is, how certain we are this is a legitimate style regression, and\r
- not a misidentification or a use that's sometimes justified.\r
-\r
- False positives can be suppressed by the use of\r
- "cpplint(category)" comments on the offending line. These are\r
- parsed into _error_suppressions.\r
-\r
- Args:\r
- filename: The name of the file containing the error.\r
- linenum: The number of the line containing the error.\r
- category: A string used to describe the "category" this bug\r
- falls under: "whitespace", say, or "runtime". Categories\r
- may have a hierarchy separated by slashes: "whitespace/indent".\r
- confidence: A number from 1-5 representing a confidence score for\r
- the error, with 5 meaning that we are certain of the problem,\r
- and 1 meaning that it could be a legitimate construct.\r
- message: The error message.\r
- """\r
- if _ShouldPrintError(category, confidence, linenum):\r
- _cpplint_state.IncrementErrorCount(category)\r
- if _cpplint_state.output_format == 'vs7':\r
- sys.stderr.write('%s(%s): error cpplint: [%s] %s [%d]\n' % (\r
- filename, linenum, category, message, confidence))\r
- elif _cpplint_state.output_format == 'eclipse':\r
- sys.stderr.write('%s:%s: warning: %s [%s] [%d]\n' % (\r
- filename, linenum, message, category, confidence))\r
- else:\r
- sys.stderr.write('%s:%s: %s [%s] [%d]\n' % (\r
- filename, linenum, message, category, confidence))\r
-\r
-\r
-# Matches standard C++ escape sequences per 2.13.2.3 of the C++ standard.\r
-_RE_PATTERN_CLEANSE_LINE_ESCAPES = re.compile(\r
- r'\\([abfnrtv?"\\\']|\d+|x[0-9a-fA-F]+)')\r
-# Match a single C style comment on the same line.\r
-_RE_PATTERN_C_COMMENTS = r'/\*(?:[^*]|\*(?!/))*\*/'\r
-# Matches multi-line C style comments.\r
-# This RE is a little bit more complicated than one might expect, because we\r
-# have to take care of space removals tools so we can handle comments inside\r
-# statements better.\r
-# The current rule is: We only clear spaces from both sides when we're at the\r
-# end of the line. Otherwise, we try to remove spaces from the right side,\r
-# if this doesn't work we try on left side but only if there's a non-character\r
-# on the right.\r
-_RE_PATTERN_CLEANSE_LINE_C_COMMENTS = re.compile(\r
- r'(\s*' + _RE_PATTERN_C_COMMENTS + r'\s*$|' +\r
- _RE_PATTERN_C_COMMENTS + r'\s+|' +\r
- r'\s+' + _RE_PATTERN_C_COMMENTS + r'(?=\W)|' +\r
- _RE_PATTERN_C_COMMENTS + r')')\r
-\r
-\r
-def IsCppString(line):\r
- """Does line terminate so, that the next symbol is in string constant.\r
-\r
- This function does not consider single-line nor multi-line comments.\r
-\r
- Args:\r
- line: is a partial line of code starting from the 0..n.\r
-\r
- Returns:\r
- True, if next character appended to 'line' is inside a\r
- string constant.\r
- """\r
-\r
- line = line.replace(r'\\', 'XX') # after this, \\" does not match to \"\r
- return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1\r
-\r
-\r
-def CleanseRawStrings(raw_lines):\r
- """Removes C++11 raw strings from lines.\r
-\r
- Before:\r
- static const char kData[] = R"(\r
- multi-line string\r
- )";\r
-\r
- After:\r
- static const char kData[] = ""\r
- (replaced by blank line)\r
- "";\r
-\r
- Args:\r
- raw_lines: list of raw lines.\r
-\r
- Returns:\r
- list of lines with C++11 raw strings replaced by empty strings.\r
- """\r
-\r
- delimiter = None\r
- lines_without_raw_strings = []\r
- for line in raw_lines:\r
- if delimiter:\r
- # Inside a raw string, look for the end\r
- end = line.find(delimiter)\r
- if end >= 0:\r
- # Found the end of the string, match leading space for this\r
- # line and resume copying the original lines, and also insert\r
- # a "" on the last line.\r
- leading_space = Match(r'^(\s*)\S', line)\r
- line = leading_space.group(1) + '""' + line[end + len(delimiter):]\r
- delimiter = None\r
- else:\r
- # Haven't found the end yet, append a blank line.\r
- line = '""'\r
-\r
- # Look for beginning of a raw string, and replace them with\r
- # empty strings. This is done in a loop to handle multiple raw\r
- # strings on the same line.\r
- while delimiter is None:\r
- # Look for beginning of a raw string.\r
- # See 2.14.15 [lex.string] for syntax.\r
- #\r
- # Once we have matched a raw string, we check the prefix of the\r
- # line to make sure that the line is not part of a single line\r
- # comment. It's done this way because we remove raw strings\r
- # before removing comments as opposed to removing comments\r
- # before removing raw strings. This is because there are some\r
- # cpplint checks that requires the comments to be preserved, but\r
- # we don't want to check comments that are inside raw strings.\r
- matched = Match(r'^(.*?)\b(?:R|u8R|uR|UR|LR)"([^\s\\()]*)\((.*)$', line)\r
- if (matched and\r
- not Match(r'^([^\'"]|\'(\\.|[^\'])*\'|"(\\.|[^"])*")*//',\r
- matched.group(1))):\r
- delimiter = ')' + matched.group(2) + '"'\r
-\r
- end = matched.group(3).find(delimiter)\r
- if end >= 0:\r
- # Raw string ended on same line\r
- line = (matched.group(1) + '""' +\r
- matched.group(3)[end + len(delimiter):])\r
- delimiter = None\r
- else:\r
- # Start of a multi-line raw string\r
- line = matched.group(1) + '""'\r
- else:\r
- break\r
-\r
- lines_without_raw_strings.append(line)\r
-\r
- # TODO(unknown): if delimiter is not None here, we might want to\r
- # emit a warning for unterminated string.\r
- return lines_without_raw_strings\r
-\r
-\r
-def FindNextMultiLineCommentStart(lines, lineix):\r
- """Find the beginning marker for a multiline comment."""\r
- while lineix < len(lines):\r
- if lines[lineix].strip().startswith('/*'):\r
- # Only return this marker if the comment goes beyond this line\r
- if lines[lineix].strip().find('*/', 2) < 0:\r
- return lineix\r
- lineix += 1\r
- return len(lines)\r
-\r
-\r
-def FindNextMultiLineCommentEnd(lines, lineix):\r
- """We are inside a comment, find the end marker."""\r
- while lineix < len(lines):\r
- if lines[lineix].strip().endswith('*/'):\r
- return lineix\r
- lineix += 1\r
- return len(lines)\r
-\r
-\r
-def RemoveMultiLineCommentsFromRange(lines, begin, end):\r
- """Clears a range of lines for multi-line comments."""\r
- # Having // dummy comments makes the lines non-empty, so we will not get\r
- # unnecessary blank line warnings later in the code.\r
- for i in range(begin, end):\r
- lines[i] = '/**/'\r
-\r
-\r
-def RemoveMultiLineComments(filename, lines, error):\r
- """Removes multiline (c-style) comments from lines."""\r
- lineix = 0\r
- while lineix < len(lines):\r
- lineix_begin = FindNextMultiLineCommentStart(lines, lineix)\r
- if lineix_begin >= len(lines):\r
- return\r
- lineix_end = FindNextMultiLineCommentEnd(lines, lineix_begin)\r
- if lineix_end >= len(lines):\r
- error(filename, lineix_begin + 1, 'readability/multiline_comment', 5,\r
- 'Could not find end of multi-line comment')\r
- return\r
- RemoveMultiLineCommentsFromRange(lines, lineix_begin, lineix_end + 1)\r
- lineix = lineix_end + 1\r
-\r
-\r
-def CleanseComments(line):\r
- """Removes //-comments and single-line C-style /* */ comments.\r
-\r
- Args:\r
- line: A line of C++ source.\r
-\r
- Returns:\r
- The line with single-line comments removed.\r
- """\r
- commentpos = line.find('//')\r
- if commentpos != -1 and not IsCppString(line[:commentpos]):\r
- line = line[:commentpos].rstrip()\r
- # get rid of /* ... */\r
- return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line)\r
-\r
-\r
-class CleansedLines(object):\r
- """Holds 4 copies of all lines with different preprocessing applied to them.\r
-\r
- 1) elided member contains lines without strings and comments.\r
- 2) lines member contains lines without comments.\r
- 3) raw_lines member contains all the lines without processing.\r
- 4) lines_without_raw_strings member is same as raw_lines, but with C++11 raw\r
- strings removed.\r
- All these members are of <type 'list'>, and of the same length.\r
- """\r
-\r
- def __init__(self, lines):\r
- self.elided = []\r
- self.lines = []\r
- self.raw_lines = lines\r
- self.num_lines = len(lines)\r
- self.lines_without_raw_strings = CleanseRawStrings(lines)\r
- for linenum in range(len(self.lines_without_raw_strings)):\r
- self.lines.append(CleanseComments(\r
- self.lines_without_raw_strings[linenum]))\r
- elided = self._CollapseStrings(self.lines_without_raw_strings[linenum])\r
- self.elided.append(CleanseComments(elided))\r
-\r
- def NumLines(self):\r
- """Returns the number of lines represented."""\r
- return self.num_lines\r
-\r
- @staticmethod\r
- def _CollapseStrings(elided):\r
- """Collapses strings and chars on a line to simple "" or '' blocks.\r
-\r
- We nix strings first so we're not fooled by text like '"http://"'\r
-\r
- Args:\r
- elided: The line being processed.\r
-\r
- Returns:\r
- The line with collapsed strings.\r
- """\r
- if _RE_PATTERN_INCLUDE.match(elided):\r
- return elided\r
-\r
- # Remove escaped characters first to make quote/single quote collapsing\r
- # basic. Things that look like escaped characters shouldn't occur\r
- # outside of strings and chars.\r
- elided = _RE_PATTERN_CLEANSE_LINE_ESCAPES.sub('', elided)\r
-\r
- # Replace quoted strings and digit separators. Both single quotes\r
- # and double quotes are processed in the same loop, otherwise\r
- # nested quotes wouldn't work.\r
- collapsed = ''\r
- while True:\r
- # Find the first quote character\r
- match = Match(r'^([^\'"]*)([\'"])(.*)$', elided)\r
- if not match:\r
- collapsed += elided\r
- break\r
- head, quote, tail = match.groups()\r
-\r
- if quote == '"':\r
- # Collapse double quoted strings\r
- second_quote = tail.find('"')\r
- if second_quote >= 0:\r
- collapsed += head + '""'\r
- elided = tail[second_quote + 1:]\r
- else:\r
- # Unmatched double quote, don't bother processing the rest\r
- # of the line since this is probably a multiline string.\r
- collapsed += elided\r
- break\r
- else:\r
- # Found single quote, check nearby text to eliminate digit separators.\r
- #\r
- # There is no special handling for floating point here, because\r
- # the integer/fractional/exponent parts would all be parsed\r
- # correctly as long as there are digits on both sides of the\r
- # separator. So we are fine as long as we don't see something\r
- # like "0.'3" (gcc 4.9.0 will not allow this literal).\r
- if Search(r'\b(?:0[bBxX]?|[1-9])[0-9a-fA-F]*$', head):\r
- match_literal = Match(r'^((?:\'?[0-9a-zA-Z_])*)(.*)$', "'" + tail)\r
- collapsed += head + match_literal.group(1).replace("'", '')\r
- elided = match_literal.group(2)\r
- else:\r
- second_quote = tail.find('\'')\r
- if second_quote >= 0:\r
- collapsed += head + "''"\r
- elided = tail[second_quote + 1:]\r
- else:\r
- # Unmatched single quote\r
- collapsed += elided\r
- break\r
-\r
- return collapsed\r
-\r
-\r
-def FindEndOfExpressionInLine(line, startpos, stack):\r
- """Find the position just after the end of current parenthesized expression.\r
-\r
- Args:\r
- line: a CleansedLines line.\r
- startpos: start searching at this position.\r
- stack: nesting stack at startpos.\r
-\r
- Returns:\r
- On finding matching end: (index just after matching end, None)\r
- On finding an unclosed expression: (-1, None)\r
- Otherwise: (-1, new stack at end of this line)\r
- """\r
- for i in xrange(startpos, len(line)):\r
- char = line[i]\r
- if char in '([{':\r
- # Found start of parenthesized expression, push to expression stack\r
- stack.append(char)\r
- elif char == '<':\r
- # Found potential start of template argument list\r
- if i > 0 and line[i - 1] == '<':\r
- # Left shift operator\r
- if stack and stack[-1] == '<':\r
- stack.pop()\r
- if not stack:\r
- return (-1, None)\r
- elif i > 0 and Search(r'\boperator\s*$', line[0:i]):\r
- # operator<, don't add to stack\r
- continue\r
- else:\r
- # Tentative start of template argument list\r
- stack.append('<')\r
- elif char in ')]}':\r
- # Found end of parenthesized expression.\r
- #\r
- # If we are currently expecting a matching '>', the pending '<'\r
- # must have been an operator. Remove them from expression stack.\r
- while stack and stack[-1] == '<':\r
- stack.pop()\r
- if not stack:\r
- return (-1, None)\r
- if ((stack[-1] == '(' and char == ')') or\r
- (stack[-1] == '[' and char == ']') or\r
- (stack[-1] == '{' and char == '}')):\r
- stack.pop()\r
- if not stack:\r
- return (i + 1, None)\r
- else:\r
- # Mismatched parentheses\r
- return (-1, None)\r
- elif char == '>':\r
- # Found potential end of template argument list.\r
-\r
- # Ignore "->" and operator functions\r
- if (i > 0 and\r
- (line[i - 1] == '-' or Search(r'\boperator\s*$', line[0:i - 1]))):\r
- continue\r
-\r
- # Pop the stack if there is a matching '<'. Otherwise, ignore\r
- # this '>' since it must be an operator.\r
- if stack:\r
- if stack[-1] == '<':\r
- stack.pop()\r
- if not stack:\r
- return (i + 1, None)\r
- elif char == ';':\r
- # Found something that look like end of statements. If we are currently\r
- # expecting a '>', the matching '<' must have been an operator, since\r
- # template argument list should not contain statements.\r
- while stack and stack[-1] == '<':\r
- stack.pop()\r
- if not stack:\r
- return (-1, None)\r
-\r
- # Did not find end of expression or unbalanced parentheses on this line\r
- return (-1, stack)\r
-\r
-\r
-def CloseExpression(clean_lines, linenum, pos):\r
- """If input points to ( or { or [ or <, finds the position that closes it.\r
-\r
- If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the\r
- linenum/pos that correspond to the closing of the expression.\r
-\r
- TODO(unknown): cpplint spends a fair bit of time matching parentheses.\r
- Ideally we would want to index all opening and closing parentheses once\r
- and have CloseExpression be just a simple lookup, but due to preprocessor\r
- tricks, this is not so easy.\r
-\r
- Args:\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- pos: A position on the line.\r
-\r
- Returns:\r
- A tuple (line, linenum, pos) pointer *past* the closing brace, or\r
- (line, len(lines), -1) if we never find a close. Note we ignore\r
- strings and comments when matching; and the line we return is the\r
- 'cleansed' line at linenum.\r
- """\r
-\r
- line = clean_lines.elided[linenum]\r
- if (line[pos] not in '({[<') or Match(r'<[<=]', line[pos:]):\r
- return (line, clean_lines.NumLines(), -1)\r
-\r
- # Check first line\r
- (end_pos, stack) = FindEndOfExpressionInLine(line, pos, [])\r
- if end_pos > -1:\r
- return (line, linenum, end_pos)\r
-\r
- # Continue scanning forward\r
- while stack and linenum < clean_lines.NumLines() - 1:\r
- linenum += 1\r
- line = clean_lines.elided[linenum]\r
- (end_pos, stack) = FindEndOfExpressionInLine(line, 0, stack)\r
- if end_pos > -1:\r
- return (line, linenum, end_pos)\r
-\r
- # Did not find end of expression before end of file, give up\r
- return (line, clean_lines.NumLines(), -1)\r
-\r
-\r
-def FindStartOfExpressionInLine(line, endpos, stack):\r
- """Find position at the matching start of current expression.\r
-\r
- This is almost the reverse of FindEndOfExpressionInLine, but note\r
- that the input position and returned position differs by 1.\r
-\r
- Args:\r
- line: a CleansedLines line.\r
- endpos: start searching at this position.\r
- stack: nesting stack at endpos.\r
-\r
- Returns:\r
- On finding matching start: (index at matching start, None)\r
- On finding an unclosed expression: (-1, None)\r
- Otherwise: (-1, new stack at beginning of this line)\r
- """\r
- i = endpos\r
- while i >= 0:\r
- char = line[i]\r
- if char in ')]}':\r
- # Found end of expression, push to expression stack\r
- stack.append(char)\r
- elif char == '>':\r
- # Found potential end of template argument list.\r
- #\r
- # Ignore it if it's a "->" or ">=" or "operator>"\r
- if (i > 0 and\r
- (line[i - 1] == '-' or\r
- Match(r'\s>=\s', line[i - 1:]) or\r
- Search(r'\boperator\s*$', line[0:i]))):\r
- i -= 1\r
- else:\r
- stack.append('>')\r
- elif char == '<':\r
- # Found potential start of template argument list\r
- if i > 0 and line[i - 1] == '<':\r
- # Left shift operator\r
- i -= 1\r
- else:\r
- # If there is a matching '>', we can pop the expression stack.\r
- # Otherwise, ignore this '<' since it must be an operator.\r
- if stack and stack[-1] == '>':\r
- stack.pop()\r
- if not stack:\r
- return (i, None)\r
- elif char in '([{':\r
- # Found start of expression.\r
- #\r
- # If there are any unmatched '>' on the stack, they must be\r
- # operators. Remove those.\r
- while stack and stack[-1] == '>':\r
- stack.pop()\r
- if not stack:\r
- return (-1, None)\r
- if ((char == '(' and stack[-1] == ')') or\r
- (char == '[' and stack[-1] == ']') or\r
- (char == '{' and stack[-1] == '}')):\r
- stack.pop()\r
- if not stack:\r
- return (i, None)\r
- else:\r
- # Mismatched parentheses\r
- return (-1, None)\r
- elif char == ';':\r
- # Found something that look like end of statements. If we are currently\r
- # expecting a '<', the matching '>' must have been an operator, since\r
- # template argument list should not contain statements.\r
- while stack and stack[-1] == '>':\r
- stack.pop()\r
- if not stack:\r
- return (-1, None)\r
-\r
- i -= 1\r
-\r
- return (-1, stack)\r
-\r
-\r
-def ReverseCloseExpression(clean_lines, linenum, pos):\r
- """If input points to ) or } or ] or >, finds the position that opens it.\r
-\r
- If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the\r
- linenum/pos that correspond to the opening of the expression.\r
-\r
- Args:\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- pos: A position on the line.\r
-\r
- Returns:\r
- A tuple (line, linenum, pos) pointer *at* the opening brace, or\r
- (line, 0, -1) if we never find the matching opening brace. Note\r
- we ignore strings and comments when matching; and the line we\r
- return is the 'cleansed' line at linenum.\r
- """\r
- line = clean_lines.elided[linenum]\r
- if line[pos] not in ')}]>':\r
- return (line, 0, -1)\r
-\r
- # Check last line\r
- (start_pos, stack) = FindStartOfExpressionInLine(line, pos, [])\r
- if start_pos > -1:\r
- return (line, linenum, start_pos)\r
-\r
- # Continue scanning backward\r
- while stack and linenum > 0:\r
- linenum -= 1\r
- line = clean_lines.elided[linenum]\r
- (start_pos, stack) = FindStartOfExpressionInLine(line, len(line) - 1, stack)\r
- if start_pos > -1:\r
- return (line, linenum, start_pos)\r
-\r
- # Did not find start of expression before beginning of file, give up\r
- return (line, 0, -1)\r
-\r
-\r
-def CheckForCopyright(filename, lines, error):\r
- """Logs an error if no Copyright message appears at the top of the file."""\r
-\r
- # We'll say it should occur by line 10. Don't forget there's a\r
- # dummy line at the front.\r
- for line in xrange(1, min(len(lines), 11)):\r
- if re.search(r'Copyright', lines[line], re.I): break\r
- else: # means no copyright line was found\r
- error(filename, 0, 'legal/copyright', 5,\r
- 'No copyright message found. '\r
- 'You should have a line: "Copyright [year] <Copyright Owner>"')\r
-\r
-\r
-def GetIndentLevel(line):\r
- """Return the number of leading spaces in line.\r
-\r
- Args:\r
- line: A string to check.\r
-\r
- Returns:\r
- An integer count of leading spaces, possibly zero.\r
- """\r
- indent = Match(r'^( *)\S', line)\r
- if indent:\r
- return len(indent.group(1))\r
- else:\r
- return 0\r
-\r
-\r
-def GetHeaderGuardCPPVariable(filename):\r
- """Returns the CPP variable that should be used as a header guard.\r
-\r
- Args:\r
- filename: The name of a C++ header file.\r
-\r
- Returns:\r
- The CPP variable that should be used as a header guard in the\r
- named file.\r
-\r
- """\r
-\r
- # Restores original filename in case that cpplint is invoked from Emacs's\r
- # flymake.\r
- filename = re.sub(r'_flymake\.h$', '.h', filename)\r
- filename = re.sub(r'/\.flymake/([^/]*)$', r'/\1', filename)\r
- # Replace 'c++' with 'cpp'.\r
- filename = filename.replace('C++', 'cpp').replace('c++', 'cpp')\r
-\r
- fileinfo = FileInfo(filename)\r
- file_path_from_root = fileinfo.RepositoryName()\r
- if _root:\r
- suffix = os.sep\r
- # On Windows using directory separator will leave us with\r
- # "bogus escape error" unless we properly escape regex.\r
- if suffix == '\\':\r
- suffix += '\\'\r
- file_path_from_root = re.sub('^' + _root + suffix, '', file_path_from_root)\r
- return re.sub(r'[^a-zA-Z0-9]', '_', file_path_from_root).upper() + '_'\r
-\r
-\r
-def CheckForHeaderGuard(filename, clean_lines, error):\r
- """Checks that the file contains a header guard.\r
-\r
- Logs an error if no #ifndef header guard is present. For other\r
- headers, checks that the full pathname is used.\r
-\r
- Args:\r
- filename: The name of the C++ header file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- error: The function to call with any errors found.\r
- """\r
-\r
- # Don't check for header guards if there are error suppression\r
- # comments somewhere in this file.\r
- #\r
- # Because this is silencing a warning for a nonexistent line, we\r
- # only support the very specific NOLINT(build/header_guard) syntax,\r
- # and not the general NOLINT or NOLINT(*) syntax.\r
- raw_lines = clean_lines.lines_without_raw_strings\r
- for i in raw_lines:\r
- if Search(r'//\s*NOLINT\(build/header_guard\)', i):\r
- return\r
-\r
- cppvar = GetHeaderGuardCPPVariable(filename)\r
-\r
- ifndef = ''\r
- ifndef_linenum = 0\r
- define = ''\r
- endif = ''\r
- endif_linenum = 0\r
- for linenum, line in enumerate(raw_lines):\r
- linesplit = line.split()\r
- if len(linesplit) >= 2:\r
- # find the first occurrence of #ifndef and #define, save arg\r
- if not ifndef and linesplit[0] == '#ifndef':\r
- # set ifndef to the header guard presented on the #ifndef line.\r
- ifndef = linesplit[1]\r
- ifndef_linenum = linenum\r
- if not define and linesplit[0] == '#define':\r
- define = linesplit[1]\r
- # find the last occurrence of #endif, save entire line\r
- if line.startswith('#endif'):\r
- endif = line\r
- endif_linenum = linenum\r
-\r
- if not ifndef or not define or ifndef != define:\r
- error(filename, 0, 'build/header_guard', 5,\r
- 'No #ifndef header guard found, suggested CPP variable is: %s' %\r
- cppvar)\r
- return\r
-\r
- # The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__\r
- # for backward compatibility.\r
- if ifndef != cppvar:\r
- error_level = 0\r
- if ifndef != cppvar + '_':\r
- error_level = 5\r
-\r
- ParseNolintSuppressions(filename, raw_lines[ifndef_linenum], ifndef_linenum,\r
- error)\r
- error(filename, ifndef_linenum, 'build/header_guard', error_level,\r
- '#ifndef header guard has wrong style, please use: %s' % cppvar)\r
-\r
- # Check for "//" comments on endif line.\r
- ParseNolintSuppressions(filename, raw_lines[endif_linenum], endif_linenum,\r
- error)\r
- match = Match(r'#endif\s*//\s*' + cppvar + r'(_)?\b', endif)\r
- if match:\r
- if match.group(1) == '_':\r
- # Issue low severity warning for deprecated double trailing underscore\r
- error(filename, endif_linenum, 'build/header_guard', 0,\r
- '#endif line should be "#endif // %s"' % cppvar)\r
- return\r
-\r
- # Didn't find the corresponding "//" comment. If this file does not\r
- # contain any "//" comments at all, it could be that the compiler\r
- # only wants "/**/" comments, look for those instead.\r
- no_single_line_comments = True\r
- for i in xrange(1, len(raw_lines) - 1):\r
- line = raw_lines[i]\r
- if Match(r'^(?:(?:\'(?:\.|[^\'])*\')|(?:"(?:\.|[^"])*")|[^\'"])*//', line):\r
- no_single_line_comments = False\r
- break\r
-\r
- if no_single_line_comments:\r
- match = Match(r'#endif\s*/\*\s*' + cppvar + r'(_)?\s*\*/', endif)\r
- if match:\r
- if match.group(1) == '_':\r
- # Low severity warning for double trailing underscore\r
- error(filename, endif_linenum, 'build/header_guard', 0,\r
- '#endif line should be "#endif /* %s */"' % cppvar)\r
- return\r
-\r
- # Didn't find anything\r
- error(filename, endif_linenum, 'build/header_guard', 5,\r
- '#endif line should be "#endif // %s"' % cppvar)\r
-\r
-\r
-def CheckHeaderFileIncluded(filename, include_state, error):\r
- """Logs an error if a .cc file does not include its header."""\r
-\r
- # Do not check test files\r
- fileinfo = FileInfo(filename)\r
- if Search(_TEST_FILE_SUFFIX, fileinfo.BaseName()):\r
- return\r
-\r
- headerfile = filename[0:len(filename) - len(fileinfo.Extension())] + '.h'\r
- if not os.path.exists(headerfile):\r
- return\r
- headername = FileInfo(headerfile).RepositoryName()\r
- first_include = 0\r
- for section_list in include_state.include_list:\r
- for f in section_list:\r
- if headername in f[0] or f[0] in headername:\r
- return\r
- if not first_include:\r
- first_include = f[1]\r
-\r
- error(filename, first_include, 'build/include', 5,\r
- '%s should include its header file %s' % (fileinfo.RepositoryName(),\r
- headername))\r
-\r
-\r
-def CheckForBadCharacters(filename, lines, error):\r
- """Logs an error for each line containing bad characters.\r
-\r
- Two kinds of bad characters:\r
-\r
- 1. Unicode replacement characters: These indicate that either the file\r
- contained invalid UTF-8 (likely) or Unicode replacement characters (which\r
- it shouldn't). Note that it's possible for this to throw off line\r
- numbering if the invalid UTF-8 occurred adjacent to a newline.\r
-\r
- 2. NUL bytes. These are problematic for some tools.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- lines: An array of strings, each representing a line of the file.\r
- error: The function to call with any errors found.\r
- """\r
- for linenum, line in enumerate(lines):\r
- if u'\ufffd' in line:\r
- error(filename, linenum, 'readability/utf8', 5,\r
- 'Line contains invalid UTF-8 (or Unicode replacement character).')\r
- if '\0' in line:\r
- error(filename, linenum, 'readability/nul', 5, 'Line contains NUL byte.')\r
-\r
-\r
-def CheckForNewlineAtEOF(filename, lines, error):\r
- """Logs an error if there is no newline char at the end of the file.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- lines: An array of strings, each representing a line of the file.\r
- error: The function to call with any errors found.\r
- """\r
-\r
- # The array lines() was created by adding two newlines to the\r
- # original file (go figure), then splitting on \n.\r
- # To verify that the file ends in \n, we just have to make sure the\r
- # last-but-two element of lines() exists and is empty.\r
- if len(lines) < 3 or lines[-2]:\r
- error(filename, len(lines) - 2, 'whitespace/ending_newline', 5,\r
- 'Could not find a newline character at the end of the file.')\r
-\r
-\r
-def CheckForMultilineCommentsAndStrings(filename, clean_lines, linenum, error):\r
- """Logs an error if we see /* ... */ or "..." that extend past one line.\r
-\r
- /* ... */ comments are legit inside macros, for one line.\r
- Otherwise, we prefer // comments, so it's ok to warn about the\r
- other. Likewise, it's ok for strings to extend across multiple\r
- lines, as long as a line continuation character (backslash)\r
- terminates each line. Although not currently prohibited by the C++\r
- style guide, it's ugly and unnecessary. We don't do well with either\r
- in this lint program, so we warn about both.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- error: The function to call with any errors found.\r
- """\r
- line = clean_lines.elided[linenum]\r
-\r
- # Remove all \\ (escaped backslashes) from the line. They are OK, and the\r
- # second (escaped) slash may trigger later \" detection erroneously.\r
- line = line.replace('\\\\', '')\r
-\r
- if line.count('/*') > line.count('*/'):\r
- error(filename, linenum, 'readability/multiline_comment', 5,\r
- 'Complex multi-line /*...*/-style comment found. '\r
- 'Lint may give bogus warnings. '\r
- 'Consider replacing these with //-style comments, '\r
- 'with #if 0...#endif, '\r
- 'or with more clearly structured multi-line comments.')\r
-\r
- if (line.count('"') - line.count('\\"')) % 2:\r
- error(filename, linenum, 'readability/multiline_string', 5,\r
- 'Multi-line string ("...") found. This lint script doesn\'t '\r
- 'do well with such strings, and may give bogus warnings. '\r
- 'Use C++11 raw strings or concatenation instead.')\r
-\r
-\r
-# (non-threadsafe name, thread-safe alternative, validation pattern)\r
-#\r
-# The validation pattern is used to eliminate false positives such as:\r
-# _rand(); // false positive due to substring match.\r
-# ->rand(); // some member function rand().\r
-# ACMRandom rand(seed); // some variable named rand.\r
-# ISAACRandom rand(); // another variable named rand.\r
-#\r
-# Basically we require the return value of these functions to be used\r
-# in some expression context on the same line by matching on some\r
-# operator before the function name. This eliminates constructors and\r
-# member function calls.\r
-_UNSAFE_FUNC_PREFIX = r'(?:[-+*/=%^&|(<]\s*|>\s+)'\r
-_THREADING_LIST = (\r
- ('asctime(', 'asctime_r(', _UNSAFE_FUNC_PREFIX + r'asctime\([^)]+\)'),\r
- ('ctime(', 'ctime_r(', _UNSAFE_FUNC_PREFIX + r'ctime\([^)]+\)'),\r
- ('getgrgid(', 'getgrgid_r(', _UNSAFE_FUNC_PREFIX + r'getgrgid\([^)]+\)'),\r
- ('getgrnam(', 'getgrnam_r(', _UNSAFE_FUNC_PREFIX + r'getgrnam\([^)]+\)'),\r
- ('getlogin(', 'getlogin_r(', _UNSAFE_FUNC_PREFIX + r'getlogin\(\)'),\r
- ('getpwnam(', 'getpwnam_r(', _UNSAFE_FUNC_PREFIX + r'getpwnam\([^)]+\)'),\r
- ('getpwuid(', 'getpwuid_r(', _UNSAFE_FUNC_PREFIX + r'getpwuid\([^)]+\)'),\r
- ('gmtime(', 'gmtime_r(', _UNSAFE_FUNC_PREFIX + r'gmtime\([^)]+\)'),\r
- ('localtime(', 'localtime_r(', _UNSAFE_FUNC_PREFIX + r'localtime\([^)]+\)'),\r
- ('rand(', 'rand_r(', _UNSAFE_FUNC_PREFIX + r'rand\(\)'),\r
- ('strtok(', 'strtok_r(',\r
- _UNSAFE_FUNC_PREFIX + r'strtok\([^)]+\)'),\r
- ('ttyname(', 'ttyname_r(', _UNSAFE_FUNC_PREFIX + r'ttyname\([^)]+\)'),\r
- )\r
-\r
-\r
-def CheckPosixThreading(filename, clean_lines, linenum, error):\r
- """Checks for calls to thread-unsafe functions.\r
-\r
- Much code has been originally written without consideration of\r
- multi-threading. Also, engineers are relying on their old experience;\r
- they have learned posix before threading extensions were added. These\r
- tests guide the engineers to use thread-safe functions (when using\r
- posix directly).\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- error: The function to call with any errors found.\r
- """\r
- line = clean_lines.elided[linenum]\r
- for single_thread_func, multithread_safe_func, pattern in _THREADING_LIST:\r
- # Additional pattern matching check to confirm that this is the\r
- # function we are looking for\r
- if Search(pattern, line):\r
- error(filename, linenum, 'runtime/threadsafe_fn', 2,\r
- 'Consider using ' + multithread_safe_func +\r
- '...) instead of ' + single_thread_func +\r
- '...) for improved thread safety.')\r
-\r
-\r
-def CheckVlogArguments(filename, clean_lines, linenum, error):\r
- """Checks that VLOG() is only used for defining a logging level.\r
-\r
- For example, VLOG(2) is correct. VLOG(INFO), VLOG(WARNING), VLOG(ERROR), and\r
- VLOG(FATAL) are not.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- error: The function to call with any errors found.\r
- """\r
- line = clean_lines.elided[linenum]\r
- if Search(r'\bVLOG\((INFO|ERROR|WARNING|DFATAL|FATAL)\)', line):\r
- error(filename, linenum, 'runtime/vlog', 5,\r
- 'VLOG() should be used with numeric verbosity level. '\r
- 'Use LOG() if you want symbolic severity levels.')\r
-\r
-# Matches invalid increment: *count++, which moves pointer instead of\r
-# incrementing a value.\r
-_RE_PATTERN_INVALID_INCREMENT = re.compile(\r
- r'^\s*\*\w+(\+\+|--);')\r
-\r
-\r
-def CheckInvalidIncrement(filename, clean_lines, linenum, error):\r
- """Checks for invalid increment *count++.\r
-\r
- For example following function:\r
- void increment_counter(int* count) {\r
- *count++;\r
- }\r
- is invalid, because it effectively does count++, moving pointer, and should\r
- be replaced with ++*count, (*count)++ or *count += 1.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- error: The function to call with any errors found.\r
- """\r
- line = clean_lines.elided[linenum]\r
- if _RE_PATTERN_INVALID_INCREMENT.match(line):\r
- error(filename, linenum, 'runtime/invalid_increment', 5,\r
- 'Changing pointer instead of value (or unused value of operator*).')\r
-\r
-\r
-def IsMacroDefinition(clean_lines, linenum):\r
- if Search(r'^#define', clean_lines[linenum]):\r
- return True\r
-\r
- if linenum > 0 and Search(r'\\$', clean_lines[linenum - 1]):\r
- return True\r
-\r
- return False\r
-\r
-\r
-def IsForwardClassDeclaration(clean_lines, linenum):\r
- return Match(r'^\s*(\btemplate\b)*.*class\s+\w+;\s*$', clean_lines[linenum])\r
-\r
-\r
-class _BlockInfo(object):\r
- """Stores information about a generic block of code."""\r
-\r
- def __init__(self, linenum, seen_open_brace):\r
- self.starting_linenum = linenum\r
- self.seen_open_brace = seen_open_brace\r
- self.open_parentheses = 0\r
- self.inline_asm = _NO_ASM\r
- self.check_namespace_indentation = False\r
-\r
- def CheckBegin(self, filename, clean_lines, linenum, error):\r
- """Run checks that applies to text up to the opening brace.\r
-\r
- This is mostly for checking the text after the class identifier\r
- and the "{", usually where the base class is specified. For other\r
- blocks, there isn't much to check, so we always pass.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- error: The function to call with any errors found.\r
- """\r
- pass\r
-\r
- def CheckEnd(self, filename, clean_lines, linenum, error):\r
- """Run checks that applies to text after the closing brace.\r
-\r
- This is mostly used for checking end of namespace comments.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- error: The function to call with any errors found.\r
- """\r
- pass\r
-\r
- def IsBlockInfo(self):\r
- """Returns true if this block is a _BlockInfo.\r
-\r
- This is convenient for verifying that an object is an instance of\r
- a _BlockInfo, but not an instance of any of the derived classes.\r
-\r
- Returns:\r
- True for this class, False for derived classes.\r
- """\r
- return self.__class__ == _BlockInfo\r
-\r
-\r
-class _ExternCInfo(_BlockInfo):\r
- """Stores information about an 'extern "C"' block."""\r
-\r
- def __init__(self, linenum):\r
- _BlockInfo.__init__(self, linenum, True)\r
-\r
-\r
-class _ClassInfo(_BlockInfo):\r
- """Stores information about a class."""\r
-\r
- def __init__(self, name, class_or_struct, clean_lines, linenum):\r
- _BlockInfo.__init__(self, linenum, False)\r
- self.name = name\r
- self.is_derived = False\r
- self.check_namespace_indentation = True\r
- if class_or_struct == 'struct':\r
- self.access = 'public'\r
- self.is_struct = True\r
- else:\r
- self.access = 'private'\r
- self.is_struct = False\r
-\r
- # Remember initial indentation level for this class. Using raw_lines here\r
- # instead of elided to account for leading comments.\r
- self.class_indent = GetIndentLevel(clean_lines.raw_lines[linenum])\r
-\r
- # Try to find the end of the class. This will be confused by things like:\r
- # class A {\r
- # } *x = { ...\r
- #\r
- # But it's still good enough for CheckSectionSpacing.\r
- self.last_line = 0\r
- depth = 0\r
- for i in range(linenum, clean_lines.NumLines()):\r
- line = clean_lines.elided[i]\r
- depth += line.count('{') - line.count('}')\r
- if not depth:\r
- self.last_line = i\r
- break\r
-\r
- def CheckBegin(self, filename, clean_lines, linenum, error):\r
- # Look for a bare ':'\r
- if Search('(^|[^:]):($|[^:])', clean_lines.elided[linenum]):\r
- self.is_derived = True\r
-\r
- def CheckEnd(self, filename, clean_lines, linenum, error):\r
- # If there is a DISALLOW macro, it should appear near the end of\r
- # the class.\r
- seen_last_thing_in_class = False\r
- for i in xrange(linenum - 1, self.starting_linenum, -1):\r
- match = Search(\r
- r'\b(DISALLOW_COPY_AND_ASSIGN|DISALLOW_IMPLICIT_CONSTRUCTORS)\(' +\r
- self.name + r'\)',\r
- clean_lines.elided[i])\r
- if match:\r
- if seen_last_thing_in_class:\r
- error(filename, i, 'readability/constructors', 3,\r
- match.group(1) + ' should be the last thing in the class')\r
- break\r
-\r
- if not Match(r'^\s*$', clean_lines.elided[i]):\r
- seen_last_thing_in_class = True\r
-\r
- # Check that closing brace is aligned with beginning of the class.\r
- # Only do this if the closing brace is indented by only whitespaces.\r
- # This means we will not check single-line class definitions.\r
- indent = Match(r'^( *)\}', clean_lines.elided[linenum])\r
- if indent and len(indent.group(1)) != self.class_indent:\r
- if self.is_struct:\r
- parent = 'struct ' + self.name\r
- else:\r
- parent = 'class ' + self.name\r
- error(filename, linenum, 'whitespace/indent', 3,\r
- 'Closing brace should be aligned with beginning of %s' % parent)\r
-\r
-\r
-class _NamespaceInfo(_BlockInfo):\r
- """Stores information about a namespace."""\r
-\r
- def __init__(self, name, linenum):\r
- _BlockInfo.__init__(self, linenum, False)\r
- self.name = name or ''\r
- self.check_namespace_indentation = True\r
-\r
- def CheckEnd(self, filename, clean_lines, linenum, error):\r
- """Check end of namespace comments."""\r
- line = clean_lines.raw_lines[linenum]\r
-\r
- # Check how many lines is enclosed in this namespace. Don't issue\r
- # warning for missing namespace comments if there aren't enough\r
- # lines. However, do apply checks if there is already an end of\r
- # namespace comment and it's incorrect.\r
- #\r
- # TODO(unknown): We always want to check end of namespace comments\r
- # if a namespace is large, but sometimes we also want to apply the\r
- # check if a short namespace contained nontrivial things (something\r
- # other than forward declarations). There is currently no logic on\r
- # deciding what these nontrivial things are, so this check is\r
- # triggered by namespace size only, which works most of the time.\r
- if (linenum - self.starting_linenum < 10\r
- and not Match(r'^\s*};*\s*(//|/\*).*\bnamespace\b', line)):\r
- return\r
-\r
- # Look for matching comment at end of namespace.\r
- #\r
- # Note that we accept C style "/* */" comments for terminating\r
- # namespaces, so that code that terminate namespaces inside\r
- # preprocessor macros can be cpplint clean.\r
- #\r
- # We also accept stuff like "// end of namespace <name>." with the\r
- # period at the end.\r
- #\r
- # Besides these, we don't accept anything else, otherwise we might\r
- # get false negatives when existing comment is a substring of the\r
- # expected namespace.\r
- if self.name:\r
- # Named namespace\r
- if not Match((r'^\s*};*\s*(//|/\*).*\bnamespace\s+' +\r
- re.escape(self.name) + r'[\*/\.\\\s]*$'),\r
- line):\r
- error(filename, linenum, 'readability/namespace', 5,\r
- 'Namespace should be terminated with "// namespace %s"' %\r
- self.name)\r
- else:\r
- # Anonymous namespace\r
- if not Match(r'^\s*};*\s*(//|/\*).*\bnamespace[\*/\.\\\s]*$', line):\r
- # If "// namespace anonymous" or "// anonymous namespace (more text)",\r
- # mention "// anonymous namespace" as an acceptable form\r
- if Match(r'^\s*}.*\b(namespace anonymous|anonymous namespace)\b', line):\r
- error(filename, linenum, 'readability/namespace', 5,\r
- 'Anonymous namespace should be terminated with "// namespace"'\r
- ' or "// anonymous namespace"')\r
- else:\r
- error(filename, linenum, 'readability/namespace', 5,\r
- 'Anonymous namespace should be terminated with "// namespace"')\r
-\r
-\r
-class _PreprocessorInfo(object):\r
- """Stores checkpoints of nesting stacks when #if/#else is seen."""\r
-\r
- def __init__(self, stack_before_if):\r
- # The entire nesting stack before #if\r
- self.stack_before_if = stack_before_if\r
-\r
- # The entire nesting stack up to #else\r
- self.stack_before_else = []\r
-\r
- # Whether we have already seen #else or #elif\r
- self.seen_else = False\r
-\r
-\r
-class NestingState(object):\r
- """Holds states related to parsing braces."""\r
-\r
- def __init__(self):\r
- # Stack for tracking all braces. An object is pushed whenever we\r
- # see a "{", and popped when we see a "}". Only 3 types of\r
- # objects are possible:\r
- # - _ClassInfo: a class or struct.\r
- # - _NamespaceInfo: a namespace.\r
- # - _BlockInfo: some other type of block.\r
- self.stack = []\r
-\r
- # Top of the previous stack before each Update().\r
- #\r
- # Because the nesting_stack is updated at the end of each line, we\r
- # had to do some convoluted checks to find out what is the current\r
- # scope at the beginning of the line. This check is simplified by\r
- # saving the previous top of nesting stack.\r
- #\r
- # We could save the full stack, but we only need the top. Copying\r
- # the full nesting stack would slow down cpplint by ~10%.\r
- self.previous_stack_top = []\r
-\r
- # Stack of _PreprocessorInfo objects.\r
- self.pp_stack = []\r
-\r
- def SeenOpenBrace(self):\r
- """Check if we have seen the opening brace for the innermost block.\r
-\r
- Returns:\r
- True if we have seen the opening brace, False if the innermost\r
- block is still expecting an opening brace.\r
- """\r
- return (not self.stack) or self.stack[-1].seen_open_brace\r
-\r
- def InNamespaceBody(self):\r
- """Check if we are currently one level inside a namespace body.\r
-\r
- Returns:\r
- True if top of the stack is a namespace block, False otherwise.\r
- """\r
- return self.stack and isinstance(self.stack[-1], _NamespaceInfo)\r
-\r
- def InExternC(self):\r
- """Check if we are currently one level inside an 'extern "C"' block.\r
-\r
- Returns:\r
- True if top of the stack is an extern block, False otherwise.\r
- """\r
- return self.stack and isinstance(self.stack[-1], _ExternCInfo)\r
-\r
- def InClassDeclaration(self):\r
- """Check if we are currently one level inside a class or struct declaration.\r
-\r
- Returns:\r
- True if top of the stack is a class/struct, False otherwise.\r
- """\r
- return self.stack and isinstance(self.stack[-1], _ClassInfo)\r
-\r
- def InAsmBlock(self):\r
- """Check if we are currently one level inside an inline ASM block.\r
-\r
- Returns:\r
- True if the top of the stack is a block containing inline ASM.\r
- """\r
- return self.stack and self.stack[-1].inline_asm != _NO_ASM\r
-\r
- def InTemplateArgumentList(self, clean_lines, linenum, pos):\r
- """Check if current position is inside template argument list.\r
-\r
- Args:\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- pos: position just after the suspected template argument.\r
- Returns:\r
- True if (linenum, pos) is inside template arguments.\r
- """\r
- while linenum < clean_lines.NumLines():\r
- # Find the earliest character that might indicate a template argument\r
- line = clean_lines.elided[linenum]\r
- match = Match(r'^[^{};=\[\]\.<>]*(.)', line[pos:])\r
- if not match:\r
- linenum += 1\r
- pos = 0\r
- continue\r
- token = match.group(1)\r
- pos += len(match.group(0))\r
-\r
- # These things do not look like template argument list:\r
- # class Suspect {\r
- # class Suspect x; }\r
- if token in ('{', '}', ';'): return False\r
-\r
- # These things look like template argument list:\r
- # template <class Suspect>\r
- # template <class Suspect = default_value>\r
- # template <class Suspect[]>\r
- # template <class Suspect...>\r
- if token in ('>', '=', '[', ']', '.'): return True\r
-\r
- # Check if token is an unmatched '<'.\r
- # If not, move on to the next character.\r
- if token != '<':\r
- pos += 1\r
- if pos >= len(line):\r
- linenum += 1\r
- pos = 0\r
- continue\r
-\r
- # We can't be sure if we just find a single '<', and need to\r
- # find the matching '>'.\r
- (_, end_line, end_pos) = CloseExpression(clean_lines, linenum, pos - 1)\r
- if end_pos < 0:\r
- # Not sure if template argument list or syntax error in file\r
- return False\r
- linenum = end_line\r
- pos = end_pos\r
- return False\r
-\r
- def UpdatePreprocessor(self, line):\r
- """Update preprocessor stack.\r
-\r
- We need to handle preprocessors due to classes like this:\r
- #ifdef SWIG\r
- struct ResultDetailsPageElementExtensionPoint {\r
- #else\r
- struct ResultDetailsPageElementExtensionPoint : public Extension {\r
- #endif\r
-\r
- We make the following assumptions (good enough for most files):\r
- - Preprocessor condition evaluates to true from #if up to first\r
- #else/#elif/#endif.\r
-\r
- - Preprocessor condition evaluates to false from #else/#elif up\r
- to #endif. We still perform lint checks on these lines, but\r
- these do not affect nesting stack.\r
-\r
- Args:\r
- line: current line to check.\r
- """\r
- if Match(r'^\s*#\s*(if|ifdef|ifndef)\b', line):\r
- # Beginning of #if block, save the nesting stack here. The saved\r
- # stack will allow us to restore the parsing state in the #else case.\r
- self.pp_stack.append(_PreprocessorInfo(copy.deepcopy(self.stack)))\r
- elif Match(r'^\s*#\s*(else|elif)\b', line):\r
- # Beginning of #else block\r
- if self.pp_stack:\r
- if not self.pp_stack[-1].seen_else:\r
- # This is the first #else or #elif block. Remember the\r
- # whole nesting stack up to this point. This is what we\r
- # keep after the #endif.\r
- self.pp_stack[-1].seen_else = True\r
- self.pp_stack[-1].stack_before_else = copy.deepcopy(self.stack)\r
-\r
- # Restore the stack to how it was before the #if\r
- self.stack = copy.deepcopy(self.pp_stack[-1].stack_before_if)\r
- else:\r
- # TODO(unknown): unexpected #else, issue warning?\r
- pass\r
- elif Match(r'^\s*#\s*endif\b', line):\r
- # End of #if or #else blocks.\r
- if self.pp_stack:\r
- # If we saw an #else, we will need to restore the nesting\r
- # stack to its former state before the #else, otherwise we\r
- # will just continue from where we left off.\r
- if self.pp_stack[-1].seen_else:\r
- # Here we can just use a shallow copy since we are the last\r
- # reference to it.\r
- self.stack = self.pp_stack[-1].stack_before_else\r
- # Drop the corresponding #if\r
- self.pp_stack.pop()\r
- else:\r
- # TODO(unknown): unexpected #endif, issue warning?\r
- pass\r
-\r
- # TODO(unknown): Update() is too long, but we will refactor later.\r
- def Update(self, filename, clean_lines, linenum, error):\r
- """Update nesting state with current line.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- error: The function to call with any errors found.\r
- """\r
- line = clean_lines.elided[linenum]\r
-\r
- # Remember top of the previous nesting stack.\r
- #\r
- # The stack is always pushed/popped and not modified in place, so\r
- # we can just do a shallow copy instead of copy.deepcopy. Using\r
- # deepcopy would slow down cpplint by ~28%.\r
- if self.stack:\r
- self.previous_stack_top = self.stack[-1]\r
- else:\r
- self.previous_stack_top = None\r
-\r
- # Update pp_stack\r
- self.UpdatePreprocessor(line)\r
-\r
- # Count parentheses. This is to avoid adding struct arguments to\r
- # the nesting stack.\r
- if self.stack:\r
- inner_block = self.stack[-1]\r
- depth_change = line.count('(') - line.count(')')\r
- inner_block.open_parentheses += depth_change\r
-\r
- # Also check if we are starting or ending an inline assembly block.\r
- if inner_block.inline_asm in (_NO_ASM, _END_ASM):\r
- if (depth_change != 0 and\r
- inner_block.open_parentheses == 1 and\r
- _MATCH_ASM.match(line)):\r
- # Enter assembly block\r
- inner_block.inline_asm = _INSIDE_ASM\r
- else:\r
- # Not entering assembly block. If previous line was _END_ASM,\r
- # we will now shift to _NO_ASM state.\r
- inner_block.inline_asm = _NO_ASM\r
- elif (inner_block.inline_asm == _INSIDE_ASM and\r
- inner_block.open_parentheses == 0):\r
- # Exit assembly block\r
- inner_block.inline_asm = _END_ASM\r
-\r
- # Consume namespace declaration at the beginning of the line. Do\r
- # this in a loop so that we catch same line declarations like this:\r
- # namespace proto2 { namespace bridge { class MessageSet; } }\r
- while True:\r
- # Match start of namespace. The "\b\s*" below catches namespace\r
- # declarations even if it weren't followed by a whitespace, this\r
- # is so that we don't confuse our namespace checker. The\r
- # missing spaces will be flagged by CheckSpacing.\r
- namespace_decl_match = Match(r'^\s*namespace\b\s*([:\w]+)?(.*)$', line)\r
- if not namespace_decl_match:\r
- break\r
-\r
- new_namespace = _NamespaceInfo(namespace_decl_match.group(1), linenum)\r
- self.stack.append(new_namespace)\r
-\r
- line = namespace_decl_match.group(2)\r
- if line.find('{') != -1:\r
- new_namespace.seen_open_brace = True\r
- line = line[line.find('{') + 1:]\r
-\r
- # Look for a class declaration in whatever is left of the line\r
- # after parsing namespaces. The regexp accounts for decorated classes\r
- # such as in:\r
- # class LOCKABLE API Object {\r
- # };\r
- class_decl_match = Match(\r
- r'^(\s*(?:template\s*<[\w\s<>,:]*>\s*)?'\r
- r'(class|struct)\s+(?:[A-Z_]+\s+)*(\w+(?:::\w+)*))'\r
- r'(.*)$', line)\r
- if (class_decl_match and\r
- (not self.stack or self.stack[-1].open_parentheses == 0)):\r
- # We do not want to accept classes that are actually template arguments:\r
- # template <class Ignore1,\r
- # class Ignore2 = Default<Args>,\r
- # template <Args> class Ignore3>\r
- # void Function() {};\r
- #\r
- # To avoid template argument cases, we scan forward and look for\r
- # an unmatched '>'. If we see one, assume we are inside a\r
- # template argument list.\r
- end_declaration = len(class_decl_match.group(1))\r
- if not self.InTemplateArgumentList(clean_lines, linenum, end_declaration):\r
- self.stack.append(_ClassInfo(\r
- class_decl_match.group(3), class_decl_match.group(2),\r
- clean_lines, linenum))\r
- line = class_decl_match.group(4)\r
-\r
- # If we have not yet seen the opening brace for the innermost block,\r
- # run checks here.\r
- if not self.SeenOpenBrace():\r
- self.stack[-1].CheckBegin(filename, clean_lines, linenum, error)\r
-\r
- # Update access control if we are inside a class/struct\r
- if self.stack and isinstance(self.stack[-1], _ClassInfo):\r
- classinfo = self.stack[-1]\r
- access_match = Match(\r
- r'^(.*)\b(public|private|protected|signals)(\s+(?:slots\s*)?)?'\r
- r':(?:[^:]|$)',\r
- line)\r
- if access_match:\r
- classinfo.access = access_match.group(2)\r
-\r
- # Check that access keywords are indented +1 space. Skip this\r
- # check if the keywords are not preceded by whitespaces.\r
- indent = access_match.group(1)\r
- if (len(indent) != classinfo.class_indent + 1 and\r
- Match(r'^\s*$', indent)):\r
- if classinfo.is_struct:\r
- parent = 'struct ' + classinfo.name\r
- else:\r
- parent = 'class ' + classinfo.name\r
- slots = ''\r
- if access_match.group(3):\r
- slots = access_match.group(3)\r
- error(filename, linenum, 'whitespace/indent', 3,\r
- '%s%s: should be indented +1 space inside %s' % (\r
- access_match.group(2), slots, parent))\r
-\r
- # Consume braces or semicolons from what's left of the line\r
- while True:\r
- # Match first brace, semicolon, or closed parenthesis.\r
- matched = Match(r'^[^{;)}]*([{;)}])(.*)$', line)\r
- if not matched:\r
- break\r
-\r
- token = matched.group(1)\r
- if token == '{':\r
- # If namespace or class hasn't seen a opening brace yet, mark\r
- # namespace/class head as complete. Push a new block onto the\r
- # stack otherwise.\r
- if not self.SeenOpenBrace():\r
- self.stack[-1].seen_open_brace = True\r
- elif Match(r'^extern\s*"[^"]*"\s*\{', line):\r
- self.stack.append(_ExternCInfo(linenum))\r
- else:\r
- self.stack.append(_BlockInfo(linenum, True))\r
- if _MATCH_ASM.match(line):\r
- self.stack[-1].inline_asm = _BLOCK_ASM\r
-\r
- elif token == ';' or token == ')':\r
- # If we haven't seen an opening brace yet, but we already saw\r
- # a semicolon, this is probably a forward declaration. Pop\r
- # the stack for these.\r
- #\r
- # Similarly, if we haven't seen an opening brace yet, but we\r
- # already saw a closing parenthesis, then these are probably\r
- # function arguments with extra "class" or "struct" keywords.\r
- # Also pop these stack for these.\r
- if not self.SeenOpenBrace():\r
- self.stack.pop()\r
- else: # token == '}'\r
- # Perform end of block checks and pop the stack.\r
- if self.stack:\r
- self.stack[-1].CheckEnd(filename, clean_lines, linenum, error)\r
- self.stack.pop()\r
- line = matched.group(2)\r
-\r
- def InnermostClass(self):\r
- """Get class info on the top of the stack.\r
-\r
- Returns:\r
- A _ClassInfo object if we are inside a class, or None otherwise.\r
- """\r
- for i in range(len(self.stack), 0, -1):\r
- classinfo = self.stack[i - 1]\r
- if isinstance(classinfo, _ClassInfo):\r
- return classinfo\r
- return None\r
-\r
- def CheckCompletedBlocks(self, filename, error):\r
- """Checks that all classes and namespaces have been completely parsed.\r
-\r
- Call this when all lines in a file have been processed.\r
- Args:\r
- filename: The name of the current file.\r
- error: The function to call with any errors found.\r
- """\r
- # Note: This test can result in false positives if #ifdef constructs\r
- # get in the way of brace matching. See the testBuildClass test in\r
- # cpplint_unittest.py for an example of this.\r
- for obj in self.stack:\r
- if isinstance(obj, _ClassInfo):\r
- error(filename, obj.starting_linenum, 'build/class', 5,\r
- 'Failed to find complete declaration of class %s' %\r
- obj.name)\r
- elif isinstance(obj, _NamespaceInfo):\r
- error(filename, obj.starting_linenum, 'build/namespaces', 5,\r
- 'Failed to find complete declaration of namespace %s' %\r
- obj.name)\r
-\r
-\r
-def CheckForNonStandardConstructs(filename, clean_lines, linenum,\r
- nesting_state, error):\r
- r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2.\r
-\r
- Complain about several constructs which gcc-2 accepts, but which are\r
- not standard C++. Warning about these in lint is one way to ease the\r
- transition to new compilers.\r
- - put storage class first (e.g. "static const" instead of "const static").\r
- - "%lld" instead of %qd" in printf-type functions.\r
- - "%1$d" is non-standard in printf-type functions.\r
- - "\%" is an undefined character escape sequence.\r
- - text after #endif is not allowed.\r
- - invalid inner-style forward declaration.\r
- - >? and <? operators, and their >?= and <?= cousins.\r
-\r
- Additionally, check for constructor/destructor style violations and reference\r
- members, as it is very convenient to do so while checking for\r
- gcc-2 compliance.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- nesting_state: A NestingState instance which maintains information about\r
- the current stack of nested blocks being parsed.\r
- error: A callable to which errors are reported, which takes 4 arguments:\r
- filename, line number, error level, and message\r
- """\r
-\r
- # Remove comments from the line, but leave in strings for now.\r
- line = clean_lines.lines[linenum]\r
-\r
- if Search(r'printf\s*\(.*".*%[-+ ]?\d*q', line):\r
- error(filename, linenum, 'runtime/printf_format', 3,\r
- '%q in format strings is deprecated. Use %ll instead.')\r
-\r
- if Search(r'printf\s*\(.*".*%\d+\$', line):\r
- error(filename, linenum, 'runtime/printf_format', 2,\r
- '%N$ formats are unconventional. Try rewriting to avoid them.')\r
-\r
- # Remove escaped backslashes before looking for undefined escapes.\r
- line = line.replace('\\\\', '')\r
-\r
- if Search(r'("|\').*\\(%|\[|\(|{)', line):\r
- error(filename, linenum, 'build/printf_format', 3,\r
- '%, [, (, and { are undefined character escapes. Unescape them.')\r
-\r
- # For the rest, work with both comments and strings removed.\r
- line = clean_lines.elided[linenum]\r
-\r
- if Search(r'\b(const|volatile|void|char|short|int|long'\r
- r'|float|double|signed|unsigned'\r
- r'|schar|u?int8|u?int16|u?int32|u?int64)'\r
- r'\s+(register|static|extern|typedef)\b',\r
- line):\r
- error(filename, linenum, 'build/storage_class', 5,\r
- 'Storage-class specifier (static, extern, typedef, etc) should be '\r
- 'at the beginning of the declaration.')\r
-\r
- if Match(r'\s*#\s*endif\s*[^/\s]+', line):\r
- error(filename, linenum, 'build/endif_comment', 5,\r
- 'Uncommented text after #endif is non-standard. Use a comment.')\r
-\r
- if Match(r'\s*class\s+(\w+\s*::\s*)+\w+\s*;', line):\r
- error(filename, linenum, 'build/forward_decl', 5,\r
- 'Inner-style forward declarations are invalid. Remove this line.')\r
-\r
- if Search(r'(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?',\r
- line):\r
- error(filename, linenum, 'build/deprecated', 3,\r
- '>? and <? (max and min) operators are non-standard and deprecated.')\r
-\r
- if Search(r'^\s*const\s*string\s*&\s*\w+\s*;', line):\r
- # TODO(unknown): Could it be expanded safely to arbitrary references,\r
- # without triggering too many false positives? The first\r
- # attempt triggered 5 warnings for mostly benign code in the regtest, hence\r
- # the restriction.\r
- # Here's the original regexp, for the reference:\r
- # type_name = r'\w+((\s*::\s*\w+)|(\s*<\s*\w+?\s*>))?'\r
- # r'\s*const\s*' + type_name + '\s*&\s*\w+\s*;'\r
- error(filename, linenum, 'runtime/member_string_references', 2,\r
- 'const string& members are dangerous. It is much better to use '\r
- 'alternatives, such as pointers or simple constants.')\r
-\r
- # Everything else in this function operates on class declarations.\r
- # Return early if the top of the nesting stack is not a class, or if\r
- # the class head is not completed yet.\r
- classinfo = nesting_state.InnermostClass()\r
- if not classinfo or not classinfo.seen_open_brace:\r
- return\r
-\r
- # The class may have been declared with namespace or classname qualifiers.\r
- # The constructor and destructor will not have those qualifiers.\r
- base_classname = classinfo.name.split('::')[-1]\r
-\r
- # Look for single-argument constructors that aren't marked explicit.\r
- # Technically a valid construct, but against style.\r
- explicit_constructor_match = Match(\r
- r'\s+(?:(?:inline|constexpr)\s+)*(explicit\s+)?'\r
- r'(?:(?:inline|constexpr)\s+)*%s\s*'\r
- r'\(((?:[^()]|\([^()]*\))*)\)'\r
- % re.escape(base_classname),\r
- line)\r
-\r
- if explicit_constructor_match:\r
- is_marked_explicit = explicit_constructor_match.group(1)\r
-\r
- if not explicit_constructor_match.group(2):\r
- constructor_args = []\r
- else:\r
- constructor_args = explicit_constructor_match.group(2).split(',')\r
-\r
- # collapse arguments so that commas in template parameter lists and function\r
- # argument parameter lists don't split arguments in two\r
- i = 0\r
- while i < len(constructor_args):\r
- constructor_arg = constructor_args[i]\r
- while (constructor_arg.count('<') > constructor_arg.count('>') or\r
- constructor_arg.count('(') > constructor_arg.count(')')):\r
- constructor_arg += ',' + constructor_args[i + 1]\r
- del constructor_args[i + 1]\r
- constructor_args[i] = constructor_arg\r
- i += 1\r
-\r
- defaulted_args = [arg for arg in constructor_args if '=' in arg]\r
- noarg_constructor = (not constructor_args or # empty arg list\r
- # 'void' arg specifier\r
- (len(constructor_args) == 1 and\r
- constructor_args[0].strip() == 'void'))\r
- onearg_constructor = ((len(constructor_args) == 1 and # exactly one arg\r
- not noarg_constructor) or\r
- # all but at most one arg defaulted\r
- (len(constructor_args) >= 1 and\r
- not noarg_constructor and\r
- len(defaulted_args) >= len(constructor_args) - 1))\r
- initializer_list_constructor = bool(\r
- onearg_constructor and\r
- Search(r'\bstd\s*::\s*initializer_list\b', constructor_args[0]))\r
- copy_constructor = bool(\r
- onearg_constructor and\r
- Match(r'(const\s+)?%s(\s*<[^>]*>)?(\s+const)?\s*(?:<\w+>\s*)?&'\r
- % re.escape(base_classname), constructor_args[0].strip()))\r
-\r
- if (not is_marked_explicit and\r
- onearg_constructor and\r
- not initializer_list_constructor and\r
- not copy_constructor):\r
- if defaulted_args:\r
- error(filename, linenum, 'runtime/explicit', 5,\r
- 'Constructors callable with one argument '\r
- 'should be marked explicit.')\r
- else:\r
- error(filename, linenum, 'runtime/explicit', 5,\r
- 'Single-parameter constructors should be marked explicit.')\r
- elif is_marked_explicit and not onearg_constructor:\r
- if noarg_constructor:\r
- error(filename, linenum, 'runtime/explicit', 5,\r
- 'Zero-parameter constructors should not be marked explicit.')\r
-\r
-\r
-def CheckSpacingForFunctionCall(filename, clean_lines, linenum, error):\r
- """Checks for the correctness of various spacing around function calls.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- error: The function to call with any errors found.\r
- """\r
- line = clean_lines.elided[linenum]\r
-\r
- # Since function calls often occur inside if/for/while/switch\r
- # expressions - which have their own, more liberal conventions - we\r
- # first see if we should be looking inside such an expression for a\r
- # function call, to which we can apply more strict standards.\r
- fncall = line # if there's no control flow construct, look at whole line\r
- for pattern in (r'\bif\s*\((.*)\)\s*{',\r
- r'\bfor\s*\((.*)\)\s*{',\r
- r'\bwhile\s*\((.*)\)\s*[{;]',\r
- r'\bswitch\s*\((.*)\)\s*{'):\r
- match = Search(pattern, line)\r
- if match:\r
- fncall = match.group(1) # look inside the parens for function calls\r
- break\r
-\r
- # Except in if/for/while/switch, there should never be space\r
- # immediately inside parens (eg "f( 3, 4 )"). We make an exception\r
- # for nested parens ( (a+b) + c ). Likewise, there should never be\r
- # a space before a ( when it's a function argument. I assume it's a\r
- # function argument when the char before the whitespace is legal in\r
- # a function name (alnum + _) and we're not starting a macro. Also ignore\r
- # pointers and references to arrays and functions coz they're too tricky:\r
- # we use a very simple way to recognize these:\r
- # " (something)(maybe-something)" or\r
- # " (something)(maybe-something," or\r
- # " (something)[something]"\r
- # Note that we assume the contents of [] to be short enough that\r
- # they'll never need to wrap.\r
- if ( # Ignore control structures.\r
- not Search(r'\b(if|for|while|switch|return|new|delete|catch|sizeof)\b',\r
- fncall) and\r
- # Ignore pointers/references to functions.\r
- not Search(r' \([^)]+\)\([^)]*(\)|,$)', fncall) and\r
- # Ignore pointers/references to arrays.\r
- not Search(r' \([^)]+\)\[[^\]]+\]', fncall)):\r
- if Search(r'\w\s*\(\s(?!\s*\\$)', fncall): # a ( used for a fn call\r
- error(filename, linenum, 'whitespace/parens', 4,\r
- 'Extra space after ( in function call')\r
- elif Search(r'\(\s+(?!(\s*\\)|\()', fncall):\r
- error(filename, linenum, 'whitespace/parens', 2,\r
- 'Extra space after (')\r
- if (Search(r'\w\s+\(', fncall) and\r
- not Search(r'_{0,2}asm_{0,2}\s+_{0,2}volatile_{0,2}\s+\(', fncall) and\r
- not Search(r'#\s*define|typedef|using\s+\w+\s*=', fncall) and\r
- not Search(r'\w\s+\((\w+::)*\*\w+\)\(', fncall) and\r
- not Search(r'\bcase\s+\(', fncall)):\r
- # TODO(unknown): Space after an operator function seem to be a common\r
- # error, silence those for now by restricting them to highest verbosity.\r
- if Search(r'\boperator_*\b', line):\r
- error(filename, linenum, 'whitespace/parens', 0,\r
- 'Extra space before ( in function call')\r
- else:\r
- error(filename, linenum, 'whitespace/parens', 4,\r
- 'Extra space before ( in function call')\r
- # If the ) is followed only by a newline or a { + newline, assume it's\r
- # part of a control statement (if/while/etc), and don't complain\r
- if Search(r'[^)]\s+\)\s*[^{\s]', fncall):\r
- # If the closing parenthesis is preceded by only whitespaces,\r
- # try to give a more descriptive error message.\r
- if Search(r'^\s+\)', fncall):\r
- error(filename, linenum, 'whitespace/parens', 2,\r
- 'Closing ) should be moved to the previous line')\r
- else:\r
- error(filename, linenum, 'whitespace/parens', 2,\r
- 'Extra space before )')\r
-\r
-\r
-def IsBlankLine(line):\r
- """Returns true if the given line is blank.\r
-\r
- We consider a line to be blank if the line is empty or consists of\r
- only white spaces.\r
-\r
- Args:\r
- line: A line of a string.\r
-\r
- Returns:\r
- True, if the given line is blank.\r
- """\r
- return not line or line.isspace()\r
-\r
-\r
-def CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line,\r
- error):\r
- is_namespace_indent_item = (\r
- len(nesting_state.stack) > 1 and\r
- nesting_state.stack[-1].check_namespace_indentation and\r
- isinstance(nesting_state.previous_stack_top, _NamespaceInfo) and\r
- nesting_state.previous_stack_top == nesting_state.stack[-2])\r
-\r
- if ShouldCheckNamespaceIndentation(nesting_state, is_namespace_indent_item,\r
- clean_lines.elided, line):\r
- CheckItemIndentationInNamespace(filename, clean_lines.elided,\r
- line, error)\r
-\r
-\r
-def CheckForFunctionLengths(filename, clean_lines, linenum,\r
- function_state, error):\r
- """Reports for long function bodies.\r
-\r
- For an overview why this is done, see:\r
- https://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions\r
-\r
- Uses a simplistic algorithm assuming other style guidelines\r
- (especially spacing) are followed.\r
- Only checks unindented functions, so class members are unchecked.\r
- Trivial bodies are unchecked, so constructors with huge initializer lists\r
- may be missed.\r
- Blank/comment lines are not counted so as to avoid encouraging the removal\r
- of vertical space and comments just to get through a lint check.\r
- NOLINT *on the last line of a function* disables this check.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- function_state: Current function name and lines in body so far.\r
- error: The function to call with any errors found.\r
- """\r
- lines = clean_lines.lines\r
- line = lines[linenum]\r
- joined_line = ''\r
-\r
- starting_func = False\r
- regexp = r'(\w(\w|::|\*|\&|\s)*)\(' # decls * & space::name( ...\r
- match_result = Match(regexp, line)\r
- if match_result:\r
- # If the name is all caps and underscores, figure it's a macro and\r
- # ignore it, unless it's TEST or TEST_F.\r
- function_name = match_result.group(1).split()[-1]\r
- if function_name == 'TEST' or function_name == 'TEST_F' or (\r
- not Match(r'[A-Z_]+$', function_name)):\r
- starting_func = True\r
-\r
- if starting_func:\r
- body_found = False\r
- for start_linenum in xrange(linenum, clean_lines.NumLines()):\r
- start_line = lines[start_linenum]\r
- joined_line += ' ' + start_line.lstrip()\r
- if Search(r'(;|})', start_line): # Declarations and trivial functions\r
- body_found = True\r
- break # ... ignore\r
- elif Search(r'{', start_line):\r
- body_found = True\r
- function = Search(r'((\w|:)*)\(', line).group(1)\r
- if Match(r'TEST', function): # Handle TEST... macros\r
- parameter_regexp = Search(r'(\(.*\))', joined_line)\r
- if parameter_regexp: # Ignore bad syntax\r
- function += parameter_regexp.group(1)\r
- else:\r
- function += '()'\r
- function_state.Begin(function)\r
- break\r
- if not body_found:\r
- # No body for the function (or evidence of a non-function) was found.\r
- error(filename, linenum, 'readability/fn_size', 5,\r
- 'Lint failed to find start of function body.')\r
- elif Match(r'^\}\s*$', line): # function end\r
- function_state.Check(error, filename, linenum)\r
- function_state.End()\r
- elif not Match(r'^\s*$', line):\r
- function_state.Count() # Count non-blank/non-comment lines.\r
-\r
-\r
-_RE_PATTERN_TODO = re.compile(r'^//(\s*)TODO(\(.+?\))?:?(\s|$)?')\r
-\r
-\r
-def CheckComment(line, filename, linenum, next_line_start, error):\r
- """Checks for common mistakes in comments.\r
-\r
- Args:\r
- line: The line in question.\r
- filename: The name of the current file.\r
- linenum: The number of the line to check.\r
- next_line_start: The first non-whitespace column of the next line.\r
- error: The function to call with any errors found.\r
- """\r
- commentpos = line.find('//')\r
- if commentpos != -1:\r
- # Check if the // may be in quotes. If so, ignore it\r
- if re.sub(r'\\.', '', line[0:commentpos]).count('"') % 2 == 0:\r
- # Allow one space for new scopes, two spaces otherwise:\r
- if (not (Match(r'^.*{ *//', line) and next_line_start == commentpos) and\r
- ((commentpos >= 1 and\r
- line[commentpos-1] not in string.whitespace) or\r
- (commentpos >= 2 and\r
- line[commentpos-2] not in string.whitespace))):\r
- error(filename, linenum, 'whitespace/comments', 2,\r
- 'At least two spaces is best between code and comments')\r
-\r
- # Checks for common mistakes in TODO comments.\r
- comment = line[commentpos:]\r
- match = _RE_PATTERN_TODO.match(comment)\r
- if match:\r
- # One whitespace is correct; zero whitespace is handled elsewhere.\r
- leading_whitespace = match.group(1)\r
- if len(leading_whitespace) > 1:\r
- error(filename, linenum, 'whitespace/todo', 2,\r
- 'Too many spaces before TODO')\r
-\r
- username = match.group(2)\r
- if not username:\r
- error(filename, linenum, 'readability/todo', 2,\r
- 'Missing username in TODO; it should look like '\r
- '"// TODO(my_username): Stuff."')\r
-\r
- middle_whitespace = match.group(3)\r
- # Comparisons made explicit for correctness -- pylint: disable=g-explicit-bool-comparison\r
- if middle_whitespace != ' ' and middle_whitespace != '':\r
- error(filename, linenum, 'whitespace/todo', 2,\r
- 'TODO(my_username) should be followed by a space')\r
-\r
- # If the comment contains an alphanumeric character, there\r
- # should be a space somewhere between it and the // unless\r
- # it's a /// or //! Doxygen comment.\r
- if (Match(r'//[^ ]*\w', comment) and\r
- not Match(r'(///|//\!)(\s+|$)', comment)):\r
- error(filename, linenum, 'whitespace/comments', 4,\r
- 'Should have a space between // and comment')\r
-\r
-\r
-def CheckSpacing(filename, clean_lines, linenum, nesting_state, error):\r
- """Checks for the correctness of various spacing issues in the code.\r
-\r
- Things we check for: spaces around operators, spaces after\r
- if/for/while/switch, no spaces around parens in function calls, two\r
- spaces between code and comment, don't start a block with a blank\r
- line, don't end a function with a blank line, don't add a blank line\r
- after public/protected/private, don't have too many blank lines in a row.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- nesting_state: A NestingState instance which maintains information about\r
- the current stack of nested blocks being parsed.\r
- error: The function to call with any errors found.\r
- """\r
-\r
- # Don't use "elided" lines here, otherwise we can't check commented lines.\r
- # Don't want to use "raw" either, because we don't want to check inside C++11\r
- # raw strings,\r
- raw = clean_lines.lines_without_raw_strings\r
- line = raw[linenum]\r
-\r
- # Before nixing comments, check if the line is blank for no good\r
- # reason. This includes the first line after a block is opened, and\r
- # blank lines at the end of a function (ie, right before a line like '}'\r
- #\r
- # Skip all the blank line checks if we are immediately inside a\r
- # namespace body. In other words, don't issue blank line warnings\r
- # for this block:\r
- # namespace {\r
- #\r
- # }\r
- #\r
- # A warning about missing end of namespace comments will be issued instead.\r
- #\r
- # Also skip blank line checks for 'extern "C"' blocks, which are formatted\r
- # like namespaces.\r
- if (IsBlankLine(line) and\r
- not nesting_state.InNamespaceBody() and\r
- not nesting_state.InExternC()):\r
- elided = clean_lines.elided\r
- prev_line = elided[linenum - 1]\r
- prevbrace = prev_line.rfind('{')\r
- # TODO(unknown): Don't complain if line before blank line, and line after,\r
- # both start with alnums and are indented the same amount.\r
- # This ignores whitespace at the start of a namespace block\r
- # because those are not usually indented.\r
- if prevbrace != -1 and prev_line[prevbrace:].find('}') == -1:\r
- # OK, we have a blank line at the start of a code block. Before we\r
- # complain, we check if it is an exception to the rule: The previous\r
- # non-empty line has the parameters of a function header that are indented\r
- # 4 spaces (because they did not fit in a 80 column line when placed on\r
- # the same line as the function name). We also check for the case where\r
- # the previous line is indented 6 spaces, which may happen when the\r
- # initializers of a constructor do not fit into a 80 column line.\r
- exception = False\r
- if Match(r' {6}\w', prev_line): # Initializer list?\r
- # We are looking for the opening column of initializer list, which\r
- # should be indented 4 spaces to cause 6 space indentation afterwards.\r
- search_position = linenum-2\r
- while (search_position >= 0\r
- and Match(r' {6}\w', elided[search_position])):\r
- search_position -= 1\r
- exception = (search_position >= 0\r
- and elided[search_position][:5] == ' :')\r
- else:\r
- # Search for the function arguments or an initializer list. We use a\r
- # simple heuristic here: If the line is indented 4 spaces; and we have a\r
- # closing paren, without the opening paren, followed by an opening brace\r
- # or colon (for initializer lists) we assume that it is the last line of\r
- # a function header. If we have a colon indented 4 spaces, it is an\r
- # initializer list.\r
- exception = (Match(r' {4}\w[^\(]*\)\s*(const\s*)?(\{\s*$|:)',\r
- prev_line)\r
- or Match(r' {4}:', prev_line))\r
-\r
- if not exception:\r
- error(filename, linenum, 'whitespace/blank_line', 2,\r
- 'Redundant blank line at the start of a code block '\r
- 'should be deleted.')\r
- # Ignore blank lines at the end of a block in a long if-else\r
- # chain, like this:\r
- # if (condition1) {\r
- # // Something followed by a blank line\r
- #\r
- # } else if (condition2) {\r
- # // Something else\r
- # }\r
- if linenum + 1 < clean_lines.NumLines():\r
- next_line = raw[linenum + 1]\r
- if (next_line\r
- and Match(r'\s*}', next_line)\r
- and next_line.find('} else ') == -1):\r
- error(filename, linenum, 'whitespace/blank_line', 3,\r
- 'Redundant blank line at the end of a code block '\r
- 'should be deleted.')\r
-\r
- matched = Match(r'\s*(public|protected|private):', prev_line)\r
- if matched:\r
- error(filename, linenum, 'whitespace/blank_line', 3,\r
- 'Do not leave a blank line after "%s:"' % matched.group(1))\r
-\r
- # Next, check comments\r
- next_line_start = 0\r
- if linenum + 1 < clean_lines.NumLines():\r
- next_line = raw[linenum + 1]\r
- next_line_start = len(next_line) - len(next_line.lstrip())\r
- CheckComment(line, filename, linenum, next_line_start, error)\r
-\r
- # get rid of comments and strings\r
- line = clean_lines.elided[linenum]\r
-\r
- # You shouldn't have spaces before your brackets, except maybe after\r
- # 'delete []' or 'return []() {};'\r
- if Search(r'\w\s+\[', line) and not Search(r'(?:delete|return)\s+\[', line):\r
- error(filename, linenum, 'whitespace/braces', 5,\r
- 'Extra space before [')\r
-\r
- # In range-based for, we wanted spaces before and after the colon, but\r
- # not around "::" tokens that might appear.\r
- if (Search(r'for *\(.*[^:]:[^: ]', line) or\r
- Search(r'for *\(.*[^: ]:[^:]', line)):\r
- error(filename, linenum, 'whitespace/forcolon', 2,\r
- 'Missing space around colon in range-based for loop')\r
-\r
-\r
-def CheckOperatorSpacing(filename, clean_lines, linenum, error):\r
- """Checks for horizontal spacing around operators.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- error: The function to call with any errors found.\r
- """\r
- line = clean_lines.elided[linenum]\r
-\r
- # Don't try to do spacing checks for operator methods. Do this by\r
- # replacing the troublesome characters with something else,\r
- # preserving column position for all other characters.\r
- #\r
- # The replacement is done repeatedly to avoid false positives from\r
- # operators that call operators.\r
- while True:\r
- match = Match(r'^(.*\boperator\b)(\S+)(\s*\(.*)$', line)\r
- if match:\r
- line = match.group(1) + ('_' * len(match.group(2))) + match.group(3)\r
- else:\r
- break\r
-\r
- # We allow no-spaces around = within an if: "if ( (a=Foo()) == 0 )".\r
- # Otherwise not. Note we only check for non-spaces on *both* sides;\r
- # sometimes people put non-spaces on one side when aligning ='s among\r
- # many lines (not that this is behavior that I approve of...)\r
- if ((Search(r'[\w.]=', line) or\r
- Search(r'=[\w.]', line))\r
- and not Search(r'\b(if|while|for) ', line)\r
- # Operators taken from [lex.operators] in C++11 standard.\r
- and not Search(r'(>=|<=|==|!=|&=|\^=|\|=|\+=|\*=|\/=|\%=)', line)\r
- and not Search(r'operator=', line)):\r
- error(filename, linenum, 'whitespace/operators', 4,\r
- 'Missing spaces around =')\r
-\r
- # It's ok not to have spaces around binary operators like + - * /, but if\r
- # there's too little whitespace, we get concerned. It's hard to tell,\r
- # though, so we punt on this one for now. TODO.\r
-\r
- # You should always have whitespace around binary operators.\r
- #\r
- # Check <= and >= first to avoid false positives with < and >, then\r
- # check non-include lines for spacing around < and >.\r
- #\r
- # If the operator is followed by a comma, assume it's be used in a\r
- # macro context and don't do any checks. This avoids false\r
- # positives.\r
- #\r
- # Note that && is not included here. This is because there are too\r
- # many false positives due to RValue references.\r
- match = Search(r'[^<>=!\s](==|!=|<=|>=|\|\|)[^<>=!\s,;\)]', line)\r
- if match:\r
- error(filename, linenum, 'whitespace/operators', 3,\r
- 'Missing spaces around %s' % match.group(1))\r
- elif not Match(r'#.*include', line):\r
- # Look for < that is not surrounded by spaces. This is only\r
- # triggered if both sides are missing spaces, even though\r
- # technically should should flag if at least one side is missing a\r
- # space. This is done to avoid some false positives with shifts.\r
- match = Match(r'^(.*[^\s<])<[^\s=<,]', line)\r
- if match:\r
- (_, _, end_pos) = CloseExpression(\r
- clean_lines, linenum, len(match.group(1)))\r
- if end_pos <= -1:\r
- error(filename, linenum, 'whitespace/operators', 3,\r
- 'Missing spaces around <')\r
-\r
- # Look for > that is not surrounded by spaces. Similar to the\r
- # above, we only trigger if both sides are missing spaces to avoid\r
- # false positives with shifts.\r
- match = Match(r'^(.*[^-\s>])>[^\s=>,]', line)\r
- if match:\r
- (_, _, start_pos) = ReverseCloseExpression(\r
- clean_lines, linenum, len(match.group(1)))\r
- if start_pos <= -1:\r
- error(filename, linenum, 'whitespace/operators', 3,\r
- 'Missing spaces around >')\r
-\r
- # We allow no-spaces around << when used like this: 10<<20, but\r
- # not otherwise (particularly, not when used as streams)\r
- #\r
- # We also allow operators following an opening parenthesis, since\r
- # those tend to be macros that deal with operators.\r
- match = Search(r'(operator|[^\s(<])(?:L|UL|LL|ULL|l|ul|ll|ull)?<<([^\s,=<])', line)\r
- if (match and not (match.group(1).isdigit() and match.group(2).isdigit()) and\r
- not (match.group(1) == 'operator' and match.group(2) == ';')):\r
- error(filename, linenum, 'whitespace/operators', 3,\r
- 'Missing spaces around <<')\r
-\r
- # We allow no-spaces around >> for almost anything. This is because\r
- # C++11 allows ">>" to close nested templates, which accounts for\r
- # most cases when ">>" is not followed by a space.\r
- #\r
- # We still warn on ">>" followed by alpha character, because that is\r
- # likely due to ">>" being used for right shifts, e.g.:\r
- # value >> alpha\r
- #\r
- # When ">>" is used to close templates, the alphanumeric letter that\r
- # follows would be part of an identifier, and there should still be\r
- # a space separating the template type and the identifier.\r
- # type<type<type>> alpha\r
- match = Search(r'>>[a-zA-Z_]', line)\r
- if match:\r
- error(filename, linenum, 'whitespace/operators', 3,\r
- 'Missing spaces around >>')\r
-\r
- # There shouldn't be space around unary operators\r
- match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line)\r
- if match:\r
- error(filename, linenum, 'whitespace/operators', 4,\r
- 'Extra space for operator %s' % match.group(1))\r
-\r
-\r
-def CheckParenthesisSpacing(filename, clean_lines, linenum, error):\r
- """Checks for horizontal spacing around parentheses.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- error: The function to call with any errors found.\r
- """\r
- line = clean_lines.elided[linenum]\r
-\r
- # No spaces after an if, while, switch, or for\r
- match = Search(r' (if\(|for\(|while\(|switch\()', line)\r
- if match:\r
- error(filename, linenum, 'whitespace/parens', 5,\r
- 'Missing space before ( in %s' % match.group(1))\r
-\r
- # For if/for/while/switch, the left and right parens should be\r
- # consistent about how many spaces are inside the parens, and\r
- # there should either be zero or one spaces inside the parens.\r
- # We don't want: "if ( foo)" or "if ( foo )".\r
- # Exception: "for ( ; foo; bar)" and "for (foo; bar; )" are allowed.\r
- match = Search(r'\b(if|for|while|switch)\s*'\r
- r'\(([ ]*)(.).*[^ ]+([ ]*)\)\s*{\s*$',\r
- line)\r
- if match:\r
- if len(match.group(2)) != len(match.group(4)):\r
- if not (match.group(3) == ';' and\r
- len(match.group(2)) == 1 + len(match.group(4)) or\r
- not match.group(2) and Search(r'\bfor\s*\(.*; \)', line)):\r
- error(filename, linenum, 'whitespace/parens', 5,\r
- 'Mismatching spaces inside () in %s' % match.group(1))\r
- if len(match.group(2)) not in [0, 1]:\r
- error(filename, linenum, 'whitespace/parens', 5,\r
- 'Should have zero or one spaces inside ( and ) in %s' %\r
- match.group(1))\r
-\r
-\r
-def CheckCommaSpacing(filename, clean_lines, linenum, error):\r
- """Checks for horizontal spacing near commas and semicolons.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- error: The function to call with any errors found.\r
- """\r
- raw = clean_lines.lines_without_raw_strings\r
- line = clean_lines.elided[linenum]\r
-\r
- # You should always have a space after a comma (either as fn arg or operator)\r
- #\r
- # This does not apply when the non-space character following the\r
- # comma is another comma, since the only time when that happens is\r
- # for empty macro arguments.\r
- #\r
- # We run this check in two passes: first pass on elided lines to\r
- # verify that lines contain missing whitespaces, second pass on raw\r
- # lines to confirm that those missing whitespaces are not due to\r
- # elided comments.\r
- if (Search(r',[^,\s]', ReplaceAll(r'\boperator\s*,\s*\(', 'F(', line)) and\r
- Search(r',[^,\s]', raw[linenum])):\r
- error(filename, linenum, 'whitespace/comma', 3,\r
- 'Missing space after ,')\r
-\r
- # You should always have a space after a semicolon\r
- # except for few corner cases\r
- # TODO(unknown): clarify if 'if (1) { return 1;}' is requires one more\r
- # space after ;\r
- if Search(r';[^\s};\\)/]', line):\r
- error(filename, linenum, 'whitespace/semicolon', 3,\r
- 'Missing space after ;')\r
-\r
-\r
-def _IsType(clean_lines, nesting_state, expr):\r
- """Check if expression looks like a type name, returns true if so.\r
-\r
- Args:\r
- clean_lines: A CleansedLines instance containing the file.\r
- nesting_state: A NestingState instance which maintains information about\r
- the current stack of nested blocks being parsed.\r
- expr: The expression to check.\r
- Returns:\r
- True, if token looks like a type.\r
- """\r
- # Keep only the last token in the expression\r
- last_word = Match(r'^.*(\b\S+)$', expr)\r
- if last_word:\r
- token = last_word.group(1)\r
- else:\r
- token = expr\r
-\r
- # Match native types and stdint types\r
- if _TYPES.match(token):\r
- return True\r
-\r
- # Try a bit harder to match templated types. Walk up the nesting\r
- # stack until we find something that resembles a typename\r
- # declaration for what we are looking for.\r
- typename_pattern = (r'\b(?:typename|class|struct)\s+' + re.escape(token) +\r
- r'\b')\r
- block_index = len(nesting_state.stack) - 1\r
- while block_index >= 0:\r
- if isinstance(nesting_state.stack[block_index], _NamespaceInfo):\r
- return False\r
-\r
- # Found where the opening brace is. We want to scan from this\r
- # line up to the beginning of the function, minus a few lines.\r
- # template <typename Type1, // stop scanning here\r
- # ...>\r
- # class C\r
- # : public ... { // start scanning here\r
- last_line = nesting_state.stack[block_index].starting_linenum\r
-\r
- next_block_start = 0\r
- if block_index > 0:\r
- next_block_start = nesting_state.stack[block_index - 1].starting_linenum\r
- first_line = last_line\r
- while first_line >= next_block_start:\r
- if clean_lines.elided[first_line].find('template') >= 0:\r
- break\r
- first_line -= 1\r
- if first_line < next_block_start:\r
- # Didn't find any "template" keyword before reaching the next block,\r
- # there are probably no template things to check for this block\r
- block_index -= 1\r
- continue\r
-\r
- # Look for typename in the specified range\r
- for i in xrange(first_line, last_line + 1, 1):\r
- if Search(typename_pattern, clean_lines.elided[i]):\r
- return True\r
- block_index -= 1\r
-\r
- return False\r
-\r
-\r
-def CheckBracesSpacing(filename, clean_lines, linenum, nesting_state, error):\r
- """Checks for horizontal spacing near commas.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- nesting_state: A NestingState instance which maintains information about\r
- the current stack of nested blocks being parsed.\r
- error: The function to call with any errors found.\r
- """\r
- line = clean_lines.elided[linenum]\r
-\r
- # Except after an opening paren, or after another opening brace (in case of\r
- # an initializer list, for instance), you should have spaces before your\r
- # braces when they are delimiting blocks, classes, namespaces etc.\r
- # And since you should never have braces at the beginning of a line,\r
- # this is an easy test. Except that braces used for initialization don't\r
- # follow the same rule; we often don't want spaces before those.\r
- match = Match(r'^(.*[^ ({>]){', line)\r
-\r
- if match:\r
- # Try a bit harder to check for brace initialization. This\r
- # happens in one of the following forms:\r
- # Constructor() : initializer_list_{} { ... }\r
- # Constructor{}.MemberFunction()\r
- # Type variable{};\r
- # FunctionCall(type{}, ...);\r
- # LastArgument(..., type{});\r
- # LOG(INFO) << type{} << " ...";\r
- # map_of_type[{...}] = ...;\r
- # ternary = expr ? new type{} : nullptr;\r
- # OuterTemplate<InnerTemplateConstructor<Type>{}>\r
- #\r
- # We check for the character following the closing brace, and\r
- # silence the warning if it's one of those listed above, i.e.\r
- # "{.;,)<>]:".\r
- #\r
- # To account for nested initializer list, we allow any number of\r
- # closing braces up to "{;,)<". We can't simply silence the\r
- # warning on first sight of closing brace, because that would\r
- # cause false negatives for things that are not initializer lists.\r
- # Silence this: But not this:\r
- # Outer{ if (...) {\r
- # Inner{...} if (...){ // Missing space before {\r
- # }; }\r
- #\r
- # There is a false negative with this approach if people inserted\r
- # spurious semicolons, e.g. "if (cond){};", but we will catch the\r
- # spurious semicolon with a separate check.\r
- leading_text = match.group(1)\r
- (endline, endlinenum, endpos) = CloseExpression(\r
- clean_lines, linenum, len(match.group(1)))\r
- trailing_text = ''\r
- if endpos > -1:\r
- trailing_text = endline[endpos:]\r
- for offset in xrange(endlinenum + 1,\r
- min(endlinenum + 3, clean_lines.NumLines() - 1)):\r
- trailing_text += clean_lines.elided[offset]\r
- # We also suppress warnings for `uint64_t{expression}` etc., as the style\r
- # guide recommends brace initialization for integral types to avoid\r
- # overflow/truncation.\r
- if (not Match(r'^[\s}]*[{.;,)<>\]:]', trailing_text)\r
- and not _IsType(clean_lines, nesting_state, leading_text)):\r
- error(filename, linenum, 'whitespace/braces', 5,\r
- 'Missing space before {')\r
-\r
- # Make sure '} else {' has spaces.\r
- if Search(r'}else', line):\r
- error(filename, linenum, 'whitespace/braces', 5,\r
- 'Missing space before else')\r
-\r
- # You shouldn't have a space before a semicolon at the end of the line.\r
- # There's a special case for "for" since the style guide allows space before\r
- # the semicolon there.\r
- if Search(r':\s*;\s*$', line):\r
- error(filename, linenum, 'whitespace/semicolon', 5,\r
- 'Semicolon defining empty statement. Use {} instead.')\r
- elif Search(r'^\s*;\s*$', line):\r
- error(filename, linenum, 'whitespace/semicolon', 5,\r
- 'Line contains only semicolon. If this should be an empty statement, '\r
- 'use {} instead.')\r
- elif (Search(r'\s+;\s*$', line) and\r
- not Search(r'\bfor\b', line)):\r
- error(filename, linenum, 'whitespace/semicolon', 5,\r
- 'Extra space before last semicolon. If this should be an empty '\r
- 'statement, use {} instead.')\r
-\r
-\r
-def IsDecltype(clean_lines, linenum, column):\r
- """Check if the token ending on (linenum, column) is decltype().\r
-\r
- Args:\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: the number of the line to check.\r
- column: end column of the token to check.\r
- Returns:\r
- True if this token is decltype() expression, False otherwise.\r
- """\r
- (text, _, start_col) = ReverseCloseExpression(clean_lines, linenum, column)\r
- if start_col < 0:\r
- return False\r
- if Search(r'\bdecltype\s*$', text[0:start_col]):\r
- return True\r
- return False\r
-\r
-\r
-def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error):\r
- """Checks for additional blank line issues related to sections.\r
-\r
- Currently the only thing checked here is blank line before protected/private.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- class_info: A _ClassInfo objects.\r
- linenum: The number of the line to check.\r
- error: The function to call with any errors found.\r
- """\r
- # Skip checks if the class is small, where small means 25 lines or less.\r
- # 25 lines seems like a good cutoff since that's the usual height of\r
- # terminals, and any class that can't fit in one screen can't really\r
- # be considered "small".\r
- #\r
- # Also skip checks if we are on the first line. This accounts for\r
- # classes that look like\r
- # class Foo { public: ... };\r
- #\r
- # If we didn't find the end of the class, last_line would be zero,\r
- # and the check will be skipped by the first condition.\r
- if (class_info.last_line - class_info.starting_linenum <= 24 or\r
- linenum <= class_info.starting_linenum):\r
- return\r
-\r
- matched = Match(r'\s*(public|protected|private):', clean_lines.lines[linenum])\r
- if matched:\r
- # Issue warning if the line before public/protected/private was\r
- # not a blank line, but don't do this if the previous line contains\r
- # "class" or "struct". This can happen two ways:\r
- # - We are at the beginning of the class.\r
- # - We are forward-declaring an inner class that is semantically\r
- # private, but needed to be public for implementation reasons.\r
- # Also ignores cases where the previous line ends with a backslash as can be\r
- # common when defining classes in C macros.\r
- prev_line = clean_lines.lines[linenum - 1]\r
- if (not IsBlankLine(prev_line) and\r
- not Search(r'\b(class|struct)\b', prev_line) and\r
- not Search(r'\\$', prev_line)):\r
- # Try a bit harder to find the beginning of the class. This is to\r
- # account for multi-line base-specifier lists, e.g.:\r
- # class Derived\r
- # : public Base {\r
- end_class_head = class_info.starting_linenum\r
- for i in range(class_info.starting_linenum, linenum):\r
- if Search(r'\{\s*$', clean_lines.lines[i]):\r
- end_class_head = i\r
- break\r
- if end_class_head < linenum - 1:\r
- error(filename, linenum, 'whitespace/blank_line', 3,\r
- '"%s:" should be preceded by a blank line' % matched.group(1))\r
-\r
-\r
-def GetPreviousNonBlankLine(clean_lines, linenum):\r
- """Return the most recent non-blank line and its line number.\r
-\r
- Args:\r
- clean_lines: A CleansedLines instance containing the file contents.\r
- linenum: The number of the line to check.\r
-\r
- Returns:\r
- A tuple with two elements. The first element is the contents of the last\r
- non-blank line before the current line, or the empty string if this is the\r
- first non-blank line. The second is the line number of that line, or -1\r
- if this is the first non-blank line.\r
- """\r
-\r
- prevlinenum = linenum - 1\r
- while prevlinenum >= 0:\r
- prevline = clean_lines.elided[prevlinenum]\r
- if not IsBlankLine(prevline): # if not a blank line...\r
- return (prevline, prevlinenum)\r
- prevlinenum -= 1\r
- return ('', -1)\r
-\r
-\r
-def CheckBraces(filename, clean_lines, linenum, error):\r
- """Looks for misplaced braces (e.g. at the end of line).\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- error: The function to call with any errors found.\r
- """\r
-\r
- line = clean_lines.elided[linenum] # get rid of comments and strings\r
-\r
- if Match(r'\s*{\s*$', line):\r
- # We allow an open brace to start a line in the case where someone is using\r
- # braces in a block to explicitly create a new scope, which is commonly used\r
- # to control the lifetime of stack-allocated variables. Braces are also\r
- # used for brace initializers inside function calls. We don't detect this\r
- # perfectly: we just don't complain if the last non-whitespace character on\r
- # the previous non-blank line is ',', ';', ':', '(', '{', or '}', or if the\r
- # previous line starts a preprocessor block. We also allow a brace on the\r
- # following line if it is part of an array initialization and would not fit\r
- # within the 80 character limit of the preceding line.\r
- prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]\r
- if (not Search(r'[,;:}{(]\s*$', prevline) and\r
- not Match(r'\s*#', prevline) and\r
- not (GetLineWidth(prevline) > _line_length - 2 and '[]' in prevline)):\r
- error(filename, linenum, 'whitespace/braces', 4,\r
- '{ should almost always be at the end of the previous line')\r
-\r
- # An else clause should be on the same line as the preceding closing brace.\r
- if Match(r'\s*else\b\s*(?:if\b|\{|$)', line):\r
- prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]\r
- if Match(r'\s*}\s*$', prevline):\r
- error(filename, linenum, 'whitespace/newline', 4,\r
- 'An else should appear on the same line as the preceding }')\r
-\r
- # If braces come on one side of an else, they should be on both.\r
- # However, we have to worry about "else if" that spans multiple lines!\r
- if Search(r'else if\s*\(', line): # could be multi-line if\r
- brace_on_left = bool(Search(r'}\s*else if\s*\(', line))\r
- # find the ( after the if\r
- pos = line.find('else if')\r
- pos = line.find('(', pos)\r
- if pos > 0:\r
- (endline, _, endpos) = CloseExpression(clean_lines, linenum, pos)\r
- brace_on_right = endline[endpos:].find('{') != -1\r
- if brace_on_left != brace_on_right: # must be brace after if\r
- error(filename, linenum, 'readability/braces', 5,\r
- 'If an else has a brace on one side, it should have it on both')\r
- elif Search(r'}\s*else[^{]*$', line) or Match(r'[^}]*else\s*{', line):\r
- error(filename, linenum, 'readability/braces', 5,\r
- 'If an else has a brace on one side, it should have it on both')\r
-\r
- # Likewise, an else should never have the else clause on the same line\r
- if Search(r'\belse [^\s{]', line) and not Search(r'\belse if\b', line):\r
- error(filename, linenum, 'whitespace/newline', 4,\r
- 'Else clause should never be on same line as else (use 2 lines)')\r
-\r
- # In the same way, a do/while should never be on one line\r
- if Match(r'\s*do [^\s{]', line):\r
- error(filename, linenum, 'whitespace/newline', 4,\r
- 'do/while clauses should not be on a single line')\r
-\r
- # Check single-line if/else bodies. The style guide says 'curly braces are not\r
- # required for single-line statements'. We additionally allow multi-line,\r
- # single statements, but we reject anything with more than one semicolon in\r
- # it. This means that the first semicolon after the if should be at the end of\r
- # its line, and the line after that should have an indent level equal to or\r
- # lower than the if. We also check for ambiguous if/else nesting without\r
- # braces.\r
- if_else_match = Search(r'\b(if\s*\(|else\b)', line)\r
- if if_else_match and not Match(r'\s*#', line):\r
- if_indent = GetIndentLevel(line)\r
- endline, endlinenum, endpos = line, linenum, if_else_match.end()\r
- if_match = Search(r'\bif\s*\(', line)\r
- if if_match:\r
- # This could be a multiline if condition, so find the end first.\r
- pos = if_match.end() - 1\r
- (endline, endlinenum, endpos) = CloseExpression(clean_lines, linenum, pos)\r
- # Check for an opening brace, either directly after the if or on the next\r
- # line. If found, this isn't a single-statement conditional.\r
- if (not Match(r'\s*{', endline[endpos:])\r
- and not (Match(r'\s*$', endline[endpos:])\r
- and endlinenum < (len(clean_lines.elided) - 1)\r
- and Match(r'\s*{', clean_lines.elided[endlinenum + 1]))):\r
- while (endlinenum < len(clean_lines.elided)\r
- and ';' not in clean_lines.elided[endlinenum][endpos:]):\r
- endlinenum += 1\r
- endpos = 0\r
- if endlinenum < len(clean_lines.elided):\r
- endline = clean_lines.elided[endlinenum]\r
- # We allow a mix of whitespace and closing braces (e.g. for one-liner\r
- # methods) and a single \ after the semicolon (for macros)\r
- endpos = endline.find(';')\r
- if not Match(r';[\s}]*(\\?)$', endline[endpos:]):\r
- # Semicolon isn't the last character, there's something trailing.\r
- # Output a warning if the semicolon is not contained inside\r
- # a lambda expression.\r
- if not Match(r'^[^{};]*\[[^\[\]]*\][^{}]*\{[^{}]*\}\s*\)*[;,]\s*$',\r
- endline):\r
- error(filename, linenum, 'readability/braces', 4,\r
- 'If/else bodies with multiple statements require braces')\r
- elif endlinenum < len(clean_lines.elided) - 1:\r
- # Make sure the next line is dedented\r
- next_line = clean_lines.elided[endlinenum + 1]\r
- next_indent = GetIndentLevel(next_line)\r
- # With ambiguous nested if statements, this will error out on the\r
- # if that *doesn't* match the else, regardless of whether it's the\r
- # inner one or outer one.\r
- if (if_match and Match(r'\s*else\b', next_line)\r
- and next_indent != if_indent):\r
- error(filename, linenum, 'readability/braces', 4,\r
- 'Else clause should be indented at the same level as if. '\r
- 'Ambiguous nested if/else chains require braces.')\r
- elif next_indent > if_indent:\r
- error(filename, linenum, 'readability/braces', 4,\r
- 'If/else bodies with multiple statements require braces')\r
-\r
-\r
-def CheckTrailingSemicolon(filename, clean_lines, linenum, error):\r
- """Looks for redundant trailing semicolon.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- error: The function to call with any errors found.\r
- """\r
-\r
- line = clean_lines.elided[linenum]\r
-\r
- # Block bodies should not be followed by a semicolon. Due to C++11\r
- # brace initialization, there are more places where semicolons are\r
- # required than not, so we use a whitelist approach to check these\r
- # rather than a blacklist. These are the places where "};" should\r
- # be replaced by just "}":\r
- # 1. Some flavor of block following closing parenthesis:\r
- # for (;;) {};\r
- # while (...) {};\r
- # switch (...) {};\r
- # Function(...) {};\r
- # if (...) {};\r
- # if (...) else if (...) {};\r
- #\r
- # 2. else block:\r
- # if (...) else {};\r
- #\r
- # 3. const member function:\r
- # Function(...) const {};\r
- #\r
- # 4. Block following some statement:\r
- # x = 42;\r
- # {};\r
- #\r
- # 5. Block at the beginning of a function:\r
- # Function(...) {\r
- # {};\r
- # }\r
- #\r
- # Note that naively checking for the preceding "{" will also match\r
- # braces inside multi-dimensional arrays, but this is fine since\r
- # that expression will not contain semicolons.\r
- #\r
- # 6. Block following another block:\r
- # while (true) {}\r
- # {};\r
- #\r
- # 7. End of namespaces:\r
- # namespace {};\r
- #\r
- # These semicolons seems far more common than other kinds of\r
- # redundant semicolons, possibly due to people converting classes\r
- # to namespaces. For now we do not warn for this case.\r
- #\r
- # Try matching case 1 first.\r
- match = Match(r'^(.*\)\s*)\{', line)\r
- if match:\r
- # Matched closing parenthesis (case 1). Check the token before the\r
- # matching opening parenthesis, and don't warn if it looks like a\r
- # macro. This avoids these false positives:\r
- # - macro that defines a base class\r
- # - multi-line macro that defines a base class\r
- # - macro that defines the whole class-head\r
- #\r
- # But we still issue warnings for macros that we know are safe to\r
- # warn, specifically:\r
- # - TEST, TEST_F, TEST_P, MATCHER, MATCHER_P\r
- # - TYPED_TEST\r
- # - INTERFACE_DEF\r
- # - EXCLUSIVE_LOCKS_REQUIRED, SHARED_LOCKS_REQUIRED, LOCKS_EXCLUDED:\r
- #\r
- # We implement a whitelist of safe macros instead of a blacklist of\r
- # unsafe macros, even though the latter appears less frequently in\r
- # google code and would have been easier to implement. This is because\r
- # the downside for getting the whitelist wrong means some extra\r
- # semicolons, while the downside for getting the blacklist wrong\r
- # would result in compile errors.\r
- #\r
- # In addition to macros, we also don't want to warn on\r
- # - Compound literals\r
- # - Lambdas\r
- # - alignas specifier with anonymous structs\r
- # - decltype\r
- closing_brace_pos = match.group(1).rfind(')')\r
- opening_parenthesis = ReverseCloseExpression(\r
- clean_lines, linenum, closing_brace_pos)\r
- if opening_parenthesis[2] > -1:\r
- line_prefix = opening_parenthesis[0][0:opening_parenthesis[2]]\r
- macro = Search(r'\b([A-Z_][A-Z0-9_]*)\s*$', line_prefix)\r
- func = Match(r'^(.*\])\s*$', line_prefix)\r
- if ((macro and\r
- macro.group(1) not in (\r
- 'TEST', 'TEST_F', 'MATCHER', 'MATCHER_P', 'TYPED_TEST',\r
- 'EXCLUSIVE_LOCKS_REQUIRED', 'SHARED_LOCKS_REQUIRED',\r
- 'LOCKS_EXCLUDED', 'INTERFACE_DEF')) or\r
- (func and not Search(r'\boperator\s*\[\s*\]', func.group(1))) or\r
- Search(r'\b(?:struct|union)\s+alignas\s*$', line_prefix) or\r
- Search(r'\bdecltype$', line_prefix) or\r
- Search(r'\s+=\s*$', line_prefix)):\r
- match = None\r
- if (match and\r
- opening_parenthesis[1] > 1 and\r
- Search(r'\]\s*$', clean_lines.elided[opening_parenthesis[1] - 1])):\r
- # Multi-line lambda-expression\r
- match = None\r
-\r
- else:\r
- # Try matching cases 2-3.\r
- match = Match(r'^(.*(?:else|\)\s*const)\s*)\{', line)\r
- if not match:\r
- # Try matching cases 4-6. These are always matched on separate lines.\r
- #\r
- # Note that we can't simply concatenate the previous line to the\r
- # current line and do a single match, otherwise we may output\r
- # duplicate warnings for the blank line case:\r
- # if (cond) {\r
- # // blank line\r
- # }\r
- prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]\r
- if prevline and Search(r'[;{}]\s*$', prevline):\r
- match = Match(r'^(\s*)\{', line)\r
-\r
- # Check matching closing brace\r
- if match:\r
- (endline, endlinenum, endpos) = CloseExpression(\r
- clean_lines, linenum, len(match.group(1)))\r
- if endpos > -1 and Match(r'^\s*;', endline[endpos:]):\r
- # Current {} pair is eligible for semicolon check, and we have found\r
- # the redundant semicolon, output warning here.\r
- #\r
- # Note: because we are scanning forward for opening braces, and\r
- # outputting warnings for the matching closing brace, if there are\r
- # nested blocks with trailing semicolons, we will get the error\r
- # messages in reversed order.\r
-\r
- # We need to check the line forward for NOLINT\r
- raw_lines = clean_lines.raw_lines\r
- ParseNolintSuppressions(filename, raw_lines[endlinenum-1], endlinenum-1,\r
- error)\r
- ParseNolintSuppressions(filename, raw_lines[endlinenum], endlinenum,\r
- error)\r
-\r
- error(filename, endlinenum, 'readability/braces', 4,\r
- "You don't need a ; after a }")\r
-\r
-\r
-def CheckEmptyBlockBody(filename, clean_lines, linenum, error):\r
- """Look for empty loop/conditional body with only a single semicolon.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- error: The function to call with any errors found.\r
- """\r
-\r
- # Search for loop keywords at the beginning of the line. Because only\r
- # whitespaces are allowed before the keywords, this will also ignore most\r
- # do-while-loops, since those lines should start with closing brace.\r
- #\r
- # We also check "if" blocks here, since an empty conditional block\r
- # is likely an error.\r
- line = clean_lines.elided[linenum]\r
- matched = Match(r'\s*(for|while|if)\s*\(', line)\r
- if matched:\r
- # Find the end of the conditional expression.\r
- (end_line, end_linenum, end_pos) = CloseExpression(\r
- clean_lines, linenum, line.find('('))\r
-\r
- # Output warning if what follows the condition expression is a semicolon.\r
- # No warning for all other cases, including whitespace or newline, since we\r
- # have a separate check for semicolons preceded by whitespace.\r
- if end_pos >= 0 and Match(r';', end_line[end_pos:]):\r
- if matched.group(1) == 'if':\r
- error(filename, end_linenum, 'whitespace/empty_conditional_body', 5,\r
- 'Empty conditional bodies should use {}')\r
- else:\r
- error(filename, end_linenum, 'whitespace/empty_loop_body', 5,\r
- 'Empty loop bodies should use {} or continue')\r
-\r
- # Check for if statements that have completely empty bodies (no comments)\r
- # and no else clauses.\r
- if end_pos >= 0 and matched.group(1) == 'if':\r
- # Find the position of the opening { for the if statement.\r
- # Return without logging an error if it has no brackets.\r
- opening_linenum = end_linenum\r
- opening_line_fragment = end_line[end_pos:]\r
- # Loop until EOF or find anything that's not whitespace or opening {.\r
- while not Search(r'^\s*\{', opening_line_fragment):\r
- if Search(r'^(?!\s*$)', opening_line_fragment):\r
- # Conditional has no brackets.\r
- return\r
- opening_linenum += 1\r
- if opening_linenum == len(clean_lines.elided):\r
- # Couldn't find conditional's opening { or any code before EOF.\r
- return\r
- opening_line_fragment = clean_lines.elided[opening_linenum]\r
- # Set opening_line (opening_line_fragment may not be entire opening line).\r
- opening_line = clean_lines.elided[opening_linenum]\r
-\r
- # Find the position of the closing }.\r
- opening_pos = opening_line_fragment.find('{')\r
- if opening_linenum == end_linenum:\r
- # We need to make opening_pos relative to the start of the entire line.\r
- opening_pos += end_pos\r
- (closing_line, closing_linenum, closing_pos) = CloseExpression(\r
- clean_lines, opening_linenum, opening_pos)\r
- if closing_pos < 0:\r
- return\r
-\r
- # Now construct the body of the conditional. This consists of the portion\r
- # of the opening line after the {, all lines until the closing line,\r
- # and the portion of the closing line before the }.\r
- if (clean_lines.raw_lines[opening_linenum] !=\r
- CleanseComments(clean_lines.raw_lines[opening_linenum])):\r
- # Opening line ends with a comment, so conditional isn't empty.\r
- return\r
- if closing_linenum > opening_linenum:\r
- # Opening line after the {. Ignore comments here since we checked above.\r
- body = list(opening_line[opening_pos+1:])\r
- # All lines until closing line, excluding closing line, with comments.\r
- body.extend(clean_lines.raw_lines[opening_linenum+1:closing_linenum])\r
- # Closing line before the }. Won't (and can't) have comments.\r
- body.append(clean_lines.elided[closing_linenum][:closing_pos-1])\r
- body = '\n'.join(body)\r
- else:\r
- # If statement has brackets and fits on a single line.\r
- body = opening_line[opening_pos+1:closing_pos-1]\r
-\r
- # Check if the body is empty\r
- if not _EMPTY_CONDITIONAL_BODY_PATTERN.search(body):\r
- return\r
- # The body is empty. Now make sure there's not an else clause.\r
- current_linenum = closing_linenum\r
- current_line_fragment = closing_line[closing_pos:]\r
- # Loop until EOF or find anything that's not whitespace or else clause.\r
- while Search(r'^\s*$|^(?=\s*else)', current_line_fragment):\r
- if Search(r'^(?=\s*else)', current_line_fragment):\r
- # Found an else clause, so don't log an error.\r
- return\r
- current_linenum += 1\r
- if current_linenum == len(clean_lines.elided):\r
- break\r
- current_line_fragment = clean_lines.elided[current_linenum]\r
-\r
- # The body is empty and there's no else clause until EOF or other code.\r
- error(filename, end_linenum, 'whitespace/empty_if_body', 4,\r
- ('If statement had no body and no else clause'))\r
-\r
-\r
-def FindCheckMacro(line):\r
- """Find a replaceable CHECK-like macro.\r
-\r
- Args:\r
- line: line to search on.\r
- Returns:\r
- (macro name, start position), or (None, -1) if no replaceable\r
- macro is found.\r
- """\r
- for macro in _CHECK_MACROS:\r
- i = line.find(macro)\r
- if i >= 0:\r
- # Find opening parenthesis. Do a regular expression match here\r
- # to make sure that we are matching the expected CHECK macro, as\r
- # opposed to some other macro that happens to contain the CHECK\r
- # substring.\r
- matched = Match(r'^(.*\b' + macro + r'\s*)\(', line)\r
- if not matched:\r
- continue\r
- return (macro, len(matched.group(1)))\r
- return (None, -1)\r
-\r
-\r
-def CheckCheck(filename, clean_lines, linenum, error):\r
- """Checks the use of CHECK and EXPECT macros.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- error: The function to call with any errors found.\r
- """\r
-\r
- # Decide the set of replacement macros that should be suggested\r
- lines = clean_lines.elided\r
- (check_macro, start_pos) = FindCheckMacro(lines[linenum])\r
- if not check_macro:\r
- return\r
-\r
- # Find end of the boolean expression by matching parentheses\r
- (last_line, end_line, end_pos) = CloseExpression(\r
- clean_lines, linenum, start_pos)\r
- if end_pos < 0:\r
- return\r
-\r
- # If the check macro is followed by something other than a\r
- # semicolon, assume users will log their own custom error messages\r
- # and don't suggest any replacements.\r
- if not Match(r'\s*;', last_line[end_pos:]):\r
- return\r
-\r
- if linenum == end_line:\r
- expression = lines[linenum][start_pos + 1:end_pos - 1]\r
- else:\r
- expression = lines[linenum][start_pos + 1:]\r
- for i in xrange(linenum + 1, end_line):\r
- expression += lines[i]\r
- expression += last_line[0:end_pos - 1]\r
-\r
- # Parse expression so that we can take parentheses into account.\r
- # This avoids false positives for inputs like "CHECK((a < 4) == b)",\r
- # which is not replaceable by CHECK_LE.\r
- lhs = ''\r
- rhs = ''\r
- operator = None\r
- while expression:\r
- matched = Match(r'^\s*(<<|<<=|>>|>>=|->\*|->|&&|\|\||'\r
- r'==|!=|>=|>|<=|<|\()(.*)$', expression)\r
- if matched:\r
- token = matched.group(1)\r
- if token == '(':\r
- # Parenthesized operand\r
- expression = matched.group(2)\r
- (end, _) = FindEndOfExpressionInLine(expression, 0, ['('])\r
- if end < 0:\r
- return # Unmatched parenthesis\r
- lhs += '(' + expression[0:end]\r
- expression = expression[end:]\r
- elif token in ('&&', '||'):\r
- # Logical and/or operators. This means the expression\r
- # contains more than one term, for example:\r
- # CHECK(42 < a && a < b);\r
- #\r
- # These are not replaceable with CHECK_LE, so bail out early.\r
- return\r
- elif token in ('<<', '<<=', '>>', '>>=', '->*', '->'):\r
- # Non-relational operator\r
- lhs += token\r
- expression = matched.group(2)\r
- else:\r
- # Relational operator\r
- operator = token\r
- rhs = matched.group(2)\r
- break\r
- else:\r
- # Unparenthesized operand. Instead of appending to lhs one character\r
- # at a time, we do another regular expression match to consume several\r
- # characters at once if possible. Trivial benchmark shows that this\r
- # is more efficient when the operands are longer than a single\r
- # character, which is generally the case.\r
- matched = Match(r'^([^-=!<>()&|]+)(.*)$', expression)\r
- if not matched:\r
- matched = Match(r'^(\s*\S)(.*)$', expression)\r
- if not matched:\r
- break\r
- lhs += matched.group(1)\r
- expression = matched.group(2)\r
-\r
- # Only apply checks if we got all parts of the boolean expression\r
- if not (lhs and operator and rhs):\r
- return\r
-\r
- # Check that rhs do not contain logical operators. We already know\r
- # that lhs is fine since the loop above parses out && and ||.\r
- if rhs.find('&&') > -1 or rhs.find('||') > -1:\r
- return\r
-\r
- # At least one of the operands must be a constant literal. This is\r
- # to avoid suggesting replacements for unprintable things like\r
- # CHECK(variable != iterator)\r
- #\r
- # The following pattern matches decimal, hex integers, strings, and\r
- # characters (in that order).\r
- lhs = lhs.strip()\r
- rhs = rhs.strip()\r
- match_constant = r'^([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')$'\r
- if Match(match_constant, lhs) or Match(match_constant, rhs):\r
- # Note: since we know both lhs and rhs, we can provide a more\r
- # descriptive error message like:\r
- # Consider using CHECK_EQ(x, 42) instead of CHECK(x == 42)\r
- # Instead of:\r
- # Consider using CHECK_EQ instead of CHECK(a == b)\r
- #\r
- # We are still keeping the less descriptive message because if lhs\r
- # or rhs gets long, the error message might become unreadable.\r
- error(filename, linenum, 'readability/check', 2,\r
- 'Consider using %s instead of %s(a %s b)' % (\r
- _CHECK_REPLACEMENT[check_macro][operator],\r
- check_macro, operator))\r
-\r
-\r
-def CheckAltTokens(filename, clean_lines, linenum, error):\r
- """Check alternative keywords being used in boolean expressions.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- error: The function to call with any errors found.\r
- """\r
- line = clean_lines.elided[linenum]\r
-\r
- # Avoid preprocessor lines\r
- if Match(r'^\s*#', line):\r
- return\r
-\r
- # Last ditch effort to avoid multi-line comments. This will not help\r
- # if the comment started before the current line or ended after the\r
- # current line, but it catches most of the false positives. At least,\r
- # it provides a way to workaround this warning for people who use\r
- # multi-line comments in preprocessor macros.\r
- #\r
- # TODO(unknown): remove this once cpplint has better support for\r
- # multi-line comments.\r
- if line.find('/*') >= 0 or line.find('*/') >= 0:\r
- return\r
-\r
- for match in _ALT_TOKEN_REPLACEMENT_PATTERN.finditer(line):\r
- error(filename, linenum, 'readability/alt_tokens', 2,\r
- 'Use operator %s instead of %s' % (\r
- _ALT_TOKEN_REPLACEMENT[match.group(1)], match.group(1)))\r
-\r
-\r
-def GetLineWidth(line):\r
- """Determines the width of the line in column positions.\r
-\r
- Args:\r
- line: A string, which may be a Unicode string.\r
-\r
- Returns:\r
- The width of the line in column positions, accounting for Unicode\r
- combining characters and wide characters.\r
- """\r
- if isinstance(line, unicode):\r
- width = 0\r
- for uc in unicodedata.normalize('NFC', line):\r
- if unicodedata.east_asian_width(uc) in ('W', 'F'):\r
- width += 2\r
- elif not unicodedata.combining(uc):\r
- width += 1\r
- return width\r
- else:\r
- return len(line)\r
-\r
-\r
-def CheckStyle(filename, clean_lines, linenum, file_extension, nesting_state,\r
- error):\r
- """Checks rules from the 'C++ style rules' section of cppguide.html.\r
-\r
- Most of these rules are hard to test (naming, comment style), but we\r
- do what we can. In particular we check for 2-space indents, line lengths,\r
- tab usage, spaces inside code, etc.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- file_extension: The extension (without the dot) of the filename.\r
- nesting_state: A NestingState instance which maintains information about\r
- the current stack of nested blocks being parsed.\r
- error: The function to call with any errors found.\r
- """\r
-\r
- # Don't use "elided" lines here, otherwise we can't check commented lines.\r
- # Don't want to use "raw" either, because we don't want to check inside C++11\r
- # raw strings,\r
- raw_lines = clean_lines.lines_without_raw_strings\r
- line = raw_lines[linenum]\r
- prev = raw_lines[linenum - 1] if linenum > 0 else ''\r
-\r
- if line.find('\t') != -1:\r
- error(filename, linenum, 'whitespace/tab', 1,\r
- 'Tab found; better to use spaces')\r
-\r
- # One or three blank spaces at the beginning of the line is weird; it's\r
- # hard to reconcile that with 2-space indents.\r
- # NOTE: here are the conditions rob pike used for his tests. Mine aren't\r
- # as sophisticated, but it may be worth becoming so: RLENGTH==initial_spaces\r
- # if(RLENGTH > 20) complain = 0;\r
- # if(match($0, " +(error|private|public|protected):")) complain = 0;\r
- # if(match(prev, "&& *$")) complain = 0;\r
- # if(match(prev, "\\|\\| *$")) complain = 0;\r
- # if(match(prev, "[\",=><] *$")) complain = 0;\r
- # if(match($0, " <<")) complain = 0;\r
- # if(match(prev, " +for \\(")) complain = 0;\r
- # if(prevodd && match(prevprev, " +for \\(")) complain = 0;\r
- scope_or_label_pattern = r'\s*\w+\s*:\s*\\?$'\r
- classinfo = nesting_state.InnermostClass()\r
- initial_spaces = 0\r
- cleansed_line = clean_lines.elided[linenum]\r
- while initial_spaces < len(line) and line[initial_spaces] == ' ':\r
- initial_spaces += 1\r
- # There are certain situations we allow one space, notably for\r
- # section labels, and also lines containing multi-line raw strings.\r
- # We also don't check for lines that look like continuation lines\r
- # (of lines ending in double quotes, commas, equals, or angle brackets)\r
- # because the rules for how to indent those are non-trivial.\r
- if (not Search(r'[",=><] *$', prev) and\r
- (initial_spaces == 1 or initial_spaces == 3) and\r
- not Match(scope_or_label_pattern, cleansed_line) and\r
- not (clean_lines.raw_lines[linenum] != line and\r
- Match(r'^\s*""', line))):\r
- error(filename, linenum, 'whitespace/indent', 3,\r
- 'Weird number of spaces at line-start. '\r
- 'Are you using a 2-space indent?')\r
-\r
- if line and line[-1].isspace():\r
- error(filename, linenum, 'whitespace/end_of_line', 4,\r
- 'Line ends in whitespace. Consider deleting these extra spaces.')\r
-\r
- # Check if the line is a header guard.\r
- is_header_guard = False\r
- if IsHeaderExtension(file_extension):\r
- cppvar = GetHeaderGuardCPPVariable(filename)\r
- if (line.startswith('#ifndef %s' % cppvar) or\r
- line.startswith('#define %s' % cppvar) or\r
- line.startswith('#endif // %s' % cppvar)):\r
- is_header_guard = True\r
- # #include lines and header guards can be long, since there's no clean way to\r
- # split them.\r
- #\r
- # URLs can be long too. It's possible to split these, but it makes them\r
- # harder to cut&paste.\r
- #\r
- # The "$Id:...$" comment may also get very long without it being the\r
- # developers fault.\r
- if (not line.startswith('#include') and not is_header_guard and\r
- not Match(r'^\s*//.*http(s?)://\S*$', line) and\r
- not Match(r'^\s*//\s*[^\s]*$', line) and\r
- not Match(r'^// \$Id:.*#[0-9]+ \$$', line)):\r
- line_width = GetLineWidth(line)\r
- if line_width > _line_length:\r
- error(filename, linenum, 'whitespace/line_length', 2,\r
- 'Lines should be <= %i characters long' % _line_length)\r
-\r
- if (cleansed_line.count(';') > 1 and\r
- # for loops are allowed two ;'s (and may run over two lines).\r
- cleansed_line.find('for') == -1 and\r
- (GetPreviousNonBlankLine(clean_lines, linenum)[0].find('for') == -1 or\r
- GetPreviousNonBlankLine(clean_lines, linenum)[0].find(';') != -1) and\r
- # It's ok to have many commands in a switch case that fits in 1 line\r
- not ((cleansed_line.find('case ') != -1 or\r
- cleansed_line.find('default:') != -1) and\r
- cleansed_line.find('break;') != -1)):\r
- error(filename, linenum, 'whitespace/newline', 0,\r
- 'More than one command on the same line')\r
-\r
- # Some more style checks\r
- CheckBraces(filename, clean_lines, linenum, error)\r
- CheckTrailingSemicolon(filename, clean_lines, linenum, error)\r
- CheckEmptyBlockBody(filename, clean_lines, linenum, error)\r
- CheckSpacing(filename, clean_lines, linenum, nesting_state, error)\r
- CheckOperatorSpacing(filename, clean_lines, linenum, error)\r
- CheckParenthesisSpacing(filename, clean_lines, linenum, error)\r
- CheckCommaSpacing(filename, clean_lines, linenum, error)\r
- CheckBracesSpacing(filename, clean_lines, linenum, nesting_state, error)\r
- CheckSpacingForFunctionCall(filename, clean_lines, linenum, error)\r
- CheckCheck(filename, clean_lines, linenum, error)\r
- CheckAltTokens(filename, clean_lines, linenum, error)\r
- classinfo = nesting_state.InnermostClass()\r
- if classinfo:\r
- CheckSectionSpacing(filename, clean_lines, classinfo, linenum, error)\r
-\r
-\r
-_RE_PATTERN_INCLUDE = re.compile(r'^\s*#\s*include\s*([<"])([^>"]*)[>"].*$')\r
-# Matches the first component of a filename delimited by -s and _s. That is:\r
-# _RE_FIRST_COMPONENT.match('foo').group(0) == 'foo'\r
-# _RE_FIRST_COMPONENT.match('foo.cc').group(0) == 'foo'\r
-# _RE_FIRST_COMPONENT.match('foo-bar_baz.cc').group(0) == 'foo'\r
-# _RE_FIRST_COMPONENT.match('foo_bar-baz.cc').group(0) == 'foo'\r
-_RE_FIRST_COMPONENT = re.compile(r'^[^-_.]+')\r
-\r
-\r
-def _DropCommonSuffixes(filename):\r
- """Drops common suffixes like _test.cc or -inl.h from filename.\r
-\r
- For example:\r
- >>> _DropCommonSuffixes('foo/foo-inl.h')\r
- 'foo/foo'\r
- >>> _DropCommonSuffixes('foo/bar/foo.cc')\r
- 'foo/bar/foo'\r
- >>> _DropCommonSuffixes('foo/foo_internal.h')\r
- 'foo/foo'\r
- >>> _DropCommonSuffixes('foo/foo_unusualinternal.h')\r
- 'foo/foo_unusualinternal'\r
-\r
- Args:\r
- filename: The input filename.\r
-\r
- Returns:\r
- The filename with the common suffix removed.\r
- """\r
- for suffix in ('test.cc', 'regtest.cc', 'unittest.cc',\r
- 'inl.h', 'impl.h', 'internal.h'):\r
- if (filename.endswith(suffix) and len(filename) > len(suffix) and\r
- filename[-len(suffix) - 1] in ('-', '_')):\r
- return filename[:-len(suffix) - 1]\r
- return os.path.splitext(filename)[0]\r
-\r
-\r
-def _ClassifyInclude(fileinfo, include, is_system):\r
- """Figures out what kind of header 'include' is.\r
-\r
- Args:\r
- fileinfo: The current file cpplint is running over. A FileInfo instance.\r
- include: The path to a #included file.\r
- is_system: True if the #include used <> rather than "".\r
-\r
- Returns:\r
- One of the _XXX_HEADER constants.\r
-\r
- For example:\r
- >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'stdio.h', True)\r
- _C_SYS_HEADER\r
- >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'string', True)\r
- _CPP_SYS_HEADER\r
- >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', False)\r
- _LIKELY_MY_HEADER\r
- >>> _ClassifyInclude(FileInfo('foo/foo_unknown_extension.cc'),\r
- ... 'bar/foo_other_ext.h', False)\r
- _POSSIBLE_MY_HEADER\r
- >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/bar.h', False)\r
- _OTHER_HEADER\r
- """\r
- # This is a list of all standard c++ header files, except\r
- # those already checked for above.\r
- is_cpp_h = include in _CPP_HEADERS\r
-\r
- if is_system:\r
- if is_cpp_h:\r
- return _CPP_SYS_HEADER\r
- else:\r
- return _C_SYS_HEADER\r
-\r
- # If the target file and the include we're checking share a\r
- # basename when we drop common extensions, and the include\r
- # lives in . , then it's likely to be owned by the target file.\r
- target_dir, target_base = (\r
- os.path.split(_DropCommonSuffixes(fileinfo.RepositoryName())))\r
- include_dir, include_base = os.path.split(_DropCommonSuffixes(include))\r
- if target_base == include_base and (\r
- include_dir == target_dir or\r
- include_dir == os.path.normpath(target_dir + '/../public')):\r
- return _LIKELY_MY_HEADER\r
-\r
- # If the target and include share some initial basename\r
- # component, it's possible the target is implementing the\r
- # include, so it's allowed to be first, but we'll never\r
- # complain if it's not there.\r
- target_first_component = _RE_FIRST_COMPONENT.match(target_base)\r
- include_first_component = _RE_FIRST_COMPONENT.match(include_base)\r
- if (target_first_component and include_first_component and\r
- target_first_component.group(0) ==\r
- include_first_component.group(0)):\r
- return _POSSIBLE_MY_HEADER\r
-\r
- return _OTHER_HEADER\r
-\r
-\r
-\r
-def CheckIncludeLine(filename, clean_lines, linenum, include_state, error):\r
- """Check rules that are applicable to #include lines.\r
-\r
- Strings on #include lines are NOT removed from elided line, to make\r
- certain tasks easier. However, to prevent false positives, checks\r
- applicable to #include lines in CheckLanguage must be put here.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- include_state: An _IncludeState instance in which the headers are inserted.\r
- error: The function to call with any errors found.\r
- """\r
- fileinfo = FileInfo(filename)\r
- line = clean_lines.lines[linenum]\r
-\r
- # "include" should use the new style "foo/bar.h" instead of just "bar.h"\r
- # Only do this check if the included header follows google naming\r
- # conventions. If not, assume that it's a 3rd party API that\r
- # requires special include conventions.\r
- #\r
- # We also make an exception for Lua headers, which follow google\r
- # naming convention but not the include convention.\r
- match = Match(r'#include\s*"([^/]+\.h)"', line)\r
- if match and not _THIRD_PARTY_HEADERS_PATTERN.match(match.group(1)):\r
- error(filename, linenum, 'build/include', 4,\r
- 'Include the directory when naming .h files')\r
-\r
- # we shouldn't include a file more than once. actually, there are a\r
- # handful of instances where doing so is okay, but in general it's\r
- # not.\r
- match = _RE_PATTERN_INCLUDE.search(line)\r
- if match:\r
- include = match.group(2)\r
- is_system = (match.group(1) == '<')\r
- duplicate_line = include_state.FindHeader(include)\r
- if duplicate_line >= 0:\r
- error(filename, linenum, 'build/include', 4,\r
- '"%s" already included at %s:%s' %\r
- (include, filename, duplicate_line))\r
- elif (include.endswith('.cc') and\r
- os.path.dirname(fileinfo.RepositoryName()) != os.path.dirname(include)):\r
- error(filename, linenum, 'build/include', 4,\r
- 'Do not include .cc files from other packages')\r
- elif not _THIRD_PARTY_HEADERS_PATTERN.match(include):\r
- include_state.include_list[-1].append((include, linenum))\r
-\r
- # We want to ensure that headers appear in the right order:\r
- # 1) for foo.cc, foo.h (preferred location)\r
- # 2) c system files\r
- # 3) cpp system files\r
- # 4) for foo.cc, foo.h (deprecated location)\r
- # 5) other google headers\r
- #\r
- # We classify each include statement as one of those 5 types\r
- # using a number of techniques. The include_state object keeps\r
- # track of the highest type seen, and complains if we see a\r
- # lower type after that.\r
- error_message = include_state.CheckNextIncludeOrder(\r
- _ClassifyInclude(fileinfo, include, is_system))\r
- if error_message:\r
- error(filename, linenum, 'build/include_order', 4,\r
- '%s. Should be: %s.h, c system, c++ system, other.' %\r
- (error_message, fileinfo.BaseName()))\r
- canonical_include = include_state.CanonicalizeAlphabeticalOrder(include)\r
- if not include_state.IsInAlphabeticalOrder(\r
- clean_lines, linenum, canonical_include):\r
- error(filename, linenum, 'build/include_alpha', 4,\r
- 'Include "%s" not in alphabetical order' % include)\r
- include_state.SetLastHeader(canonical_include)\r
-\r
-\r
-\r
-def _GetTextInside(text, start_pattern):\r
- r"""Retrieves all the text between matching open and close parentheses.\r
-\r
- Given a string of lines and a regular expression string, retrieve all the text\r
- following the expression and between opening punctuation symbols like\r
- (, [, or {, and the matching close-punctuation symbol. This properly nested\r
- occurrences of the punctuations, so for the text like\r
- printf(a(), b(c()));\r
- a call to _GetTextInside(text, r'printf\(') will return 'a(), b(c())'.\r
- start_pattern must match string having an open punctuation symbol at the end.\r
-\r
- Args:\r
- text: The lines to extract text. Its comments and strings must be elided.\r
- It can be single line and can span multiple lines.\r
- start_pattern: The regexp string indicating where to start extracting\r
- the text.\r
- Returns:\r
- The extracted text.\r
- None if either the opening string or ending punctuation could not be found.\r
- """\r
- # TODO(unknown): Audit cpplint.py to see what places could be profitably\r
- # rewritten to use _GetTextInside (and use inferior regexp matching today).\r
-\r
- # Give opening punctuations to get the matching close-punctuations.\r
- matching_punctuation = {'(': ')', '{': '}', '[': ']'}\r
- closing_punctuation = set(matching_punctuation.itervalues())\r
-\r
- # Find the position to start extracting text.\r
- match = re.search(start_pattern, text, re.M)\r
- if not match: # start_pattern not found in text.\r
- return None\r
- start_position = match.end(0)\r
-\r
- assert start_position > 0, (\r
- 'start_pattern must ends with an opening punctuation.')\r
- assert text[start_position - 1] in matching_punctuation, (\r
- 'start_pattern must ends with an opening punctuation.')\r
- # Stack of closing punctuations we expect to have in text after position.\r
- punctuation_stack = [matching_punctuation[text[start_position - 1]]]\r
- position = start_position\r
- while punctuation_stack and position < len(text):\r
- if text[position] == punctuation_stack[-1]:\r
- punctuation_stack.pop()\r
- elif text[position] in closing_punctuation:\r
- # A closing punctuation without matching opening punctuations.\r
- return None\r
- elif text[position] in matching_punctuation:\r
- punctuation_stack.append(matching_punctuation[text[position]])\r
- position += 1\r
- if punctuation_stack:\r
- # Opening punctuations left without matching close-punctuations.\r
- return None\r
- # punctuations match.\r
- return text[start_position:position - 1]\r
-\r
-\r
-# Patterns for matching call-by-reference parameters.\r
-#\r
-# Supports nested templates up to 2 levels deep using this messy pattern:\r
-# < (?: < (?: < [^<>]*\r
-# >\r
-# | [^<>] )*\r
-# >\r
-# | [^<>] )*\r
-# >\r
-_RE_PATTERN_IDENT = r'[_a-zA-Z]\w*' # =~ [[:alpha:]][[:alnum:]]*\r
-_RE_PATTERN_TYPE = (\r
- r'(?:const\s+)?(?:typename\s+|class\s+|struct\s+|union\s+|enum\s+)?'\r
- r'(?:\w|'\r
- r'\s*<(?:<(?:<[^<>]*>|[^<>])*>|[^<>])*>|'\r
- r'::)+')\r
-# A call-by-reference parameter ends with '& identifier'.\r
-_RE_PATTERN_REF_PARAM = re.compile(\r
- r'(' + _RE_PATTERN_TYPE + r'(?:\s*(?:\bconst\b|[*]))*\s*'\r
- r'&\s*' + _RE_PATTERN_IDENT + r')\s*(?:=[^,()]+)?[,)]')\r
-# A call-by-const-reference parameter either ends with 'const& identifier'\r
-# or looks like 'const type& identifier' when 'type' is atomic.\r
-_RE_PATTERN_CONST_REF_PARAM = (\r
- r'(?:.*\s*\bconst\s*&\s*' + _RE_PATTERN_IDENT +\r
- r'|const\s+' + _RE_PATTERN_TYPE + r'\s*&\s*' + _RE_PATTERN_IDENT + r')')\r
-# Stream types.\r
-_RE_PATTERN_REF_STREAM_PARAM = (\r
- r'(?:.*stream\s*&\s*' + _RE_PATTERN_IDENT + r')')\r
-\r
-\r
-def CheckLanguage(filename, clean_lines, linenum, file_extension,\r
- include_state, nesting_state, error):\r
- """Checks rules from the 'C++ language rules' section of cppguide.html.\r
-\r
- Some of these rules are hard to test (function overloading, using\r
- uint32 inappropriately), but we do the best we can.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- file_extension: The extension (without the dot) of the filename.\r
- include_state: An _IncludeState instance in which the headers are inserted.\r
- nesting_state: A NestingState instance which maintains information about\r
- the current stack of nested blocks being parsed.\r
- error: The function to call with any errors found.\r
- """\r
- # If the line is empty or consists of entirely a comment, no need to\r
- # check it.\r
- line = clean_lines.elided[linenum]\r
- if not line:\r
- return\r
-\r
- match = _RE_PATTERN_INCLUDE.search(line)\r
- if match:\r
- CheckIncludeLine(filename, clean_lines, linenum, include_state, error)\r
- return\r
-\r
- # Reset include state across preprocessor directives. This is meant\r
- # to silence warnings for conditional includes.\r
- match = Match(r'^\s*#\s*(if|ifdef|ifndef|elif|else|endif)\b', line)\r
- if match:\r
- include_state.ResetSection(match.group(1))\r
-\r
- # Make Windows paths like Unix.\r
- fullname = os.path.abspath(filename).replace('\\', '/')\r
-\r
- # Perform other checks now that we are sure that this is not an include line\r
- CheckCasts(filename, clean_lines, linenum, error)\r
- CheckGlobalStatic(filename, clean_lines, linenum, error)\r
- CheckPrintf(filename, clean_lines, linenum, error)\r
-\r
- if IsHeaderExtension(file_extension):\r
- # TODO(unknown): check that 1-arg constructors are explicit.\r
- # How to tell it's a constructor?\r
- # (handled in CheckForNonStandardConstructs for now)\r
- # TODO(unknown): check that classes declare or disable copy/assign\r
- # (level 1 error)\r
- pass\r
-\r
- # Check if people are using the verboten C basic types. The only exception\r
- # we regularly allow is "unsigned short port" for port.\r
- if Search(r'\bshort port\b', line):\r
- if not Search(r'\bunsigned short port\b', line):\r
- error(filename, linenum, 'runtime/int', 4,\r
- 'Use "unsigned short" for ports, not "short"')\r
- else:\r
- match = Search(r'\b(short|long(?! +double)|long long)\b', line)\r
- if match:\r
- error(filename, linenum, 'runtime/int', 4,\r
- 'Use int16/int64/etc, rather than the C type %s' % match.group(1))\r
-\r
- # Check if some verboten operator overloading is going on\r
- # TODO(unknown): catch out-of-line unary operator&:\r
- # class X {};\r
- # int operator&(const X& x) { return 42; } // unary operator&\r
- # The trick is it's hard to tell apart from binary operator&:\r
- # class Y { int operator&(const Y& x) { return 23; } }; // binary operator&\r
- if Search(r'\boperator\s*&\s*\(\s*\)', line):\r
- error(filename, linenum, 'runtime/operator', 4,\r
- 'Unary operator& is dangerous. Do not use it.')\r
-\r
- # Check for suspicious usage of "if" like\r
- # } if (a == b) {\r
- if Search(r'\}\s*if\s*\(', line):\r
- error(filename, linenum, 'readability/braces', 4,\r
- 'Did you mean "else if"? If not, start a new line for "if".')\r
-\r
- # Check for potential format string bugs like printf(foo).\r
- # We constrain the pattern not to pick things like DocidForPrintf(foo).\r
- # Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str())\r
- # TODO(unknown): Catch the following case. Need to change the calling\r
- # convention of the whole function to process multiple line to handle it.\r
- # printf(\r
- # boy_this_is_a_really_long_variable_that_cannot_fit_on_the_prev_line);\r
- printf_args = _GetTextInside(line, r'(?i)\b(string)?printf\s*\(')\r
- if printf_args:\r
- match = Match(r'([\w.\->()]+)$', printf_args)\r
- if match and match.group(1) != '__VA_ARGS__':\r
- function_name = re.search(r'\b((?:string)?printf)\s*\(',\r
- line, re.I).group(1)\r
- error(filename, linenum, 'runtime/printf', 4,\r
- 'Potential format string bug. Do %s("%%s", %s) instead.'\r
- % (function_name, match.group(1)))\r
-\r
- # Check for potential memset bugs like memset(buf, sizeof(buf), 0).\r
- match = Search(r'memset\s*\(([^,]*),\s*([^,]*),\s*0\s*\)', line)\r
- if match and not Match(r"^''|-?[0-9]+|0x[0-9A-Fa-f]$", match.group(2)):\r
- error(filename, linenum, 'runtime/memset', 4,\r
- 'Did you mean "memset(%s, 0, %s)"?'\r
- % (match.group(1), match.group(2)))\r
-\r
- if Search(r'\busing namespace\b', line):\r
- error(filename, linenum, 'build/namespaces', 5,\r
- 'Do not use namespace using-directives. '\r
- 'Use using-declarations instead.')\r
-\r
- # Detect variable-length arrays.\r
- match = Match(r'\s*(.+::)?(\w+) [a-z]\w*\[(.+)];', line)\r
- if (match and match.group(2) != 'return' and match.group(2) != 'delete' and\r
- match.group(3).find(']') == -1):\r
- # Split the size using space and arithmetic operators as delimiters.\r
- # If any of the resulting tokens are not compile time constants then\r
- # report the error.\r
- tokens = re.split(r'\s|\+|\-|\*|\/|<<|>>]', match.group(3))\r
- is_const = True\r
- skip_next = False\r
- for tok in tokens:\r
- if skip_next:\r
- skip_next = False\r
- continue\r
-\r
- if Search(r'sizeof\(.+\)', tok): continue\r
- if Search(r'arraysize\(\w+\)', tok): continue\r
-\r
- tok = tok.lstrip('(')\r
- tok = tok.rstrip(')')\r
- if not tok: continue\r
- if Match(r'\d+', tok): continue\r
- if Match(r'0[xX][0-9a-fA-F]+', tok): continue\r
- if Match(r'k[A-Z0-9]\w*', tok): continue\r
- if Match(r'(.+::)?k[A-Z0-9]\w*', tok): continue\r
- if Match(r'(.+::)?[A-Z][A-Z0-9_]*', tok): continue\r
- # A catch all for tricky sizeof cases, including 'sizeof expression',\r
- # 'sizeof(*type)', 'sizeof(const type)', 'sizeof(struct StructName)'\r
- # requires skipping the next token because we split on ' ' and '*'.\r
- if tok.startswith('sizeof'):\r
- skip_next = True\r
- continue\r
- is_const = False\r
- break\r
- if not is_const:\r
- error(filename, linenum, 'runtime/arrays', 1,\r
- 'Do not use variable-length arrays. Use an appropriately named '\r
- "('k' followed by CamelCase) compile-time constant for the size.")\r
-\r
- # Check for use of unnamed namespaces in header files. Registration\r
- # macros are typically OK, so we allow use of "namespace {" on lines\r
- # that end with backslashes.\r
- if (IsHeaderExtension(file_extension)\r
- and Search(r'\bnamespace\s*{', line)\r
- and line[-1] != '\\'):\r
- error(filename, linenum, 'build/namespaces', 4,\r
- 'Do not use unnamed namespaces in header files. See '\r
- 'https://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces'\r
- ' for more information.')\r
-\r
-\r
-def CheckGlobalStatic(filename, clean_lines, linenum, error):\r
- """Check for unsafe global or static objects.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- error: The function to call with any errors found.\r
- """\r
- line = clean_lines.elided[linenum]\r
-\r
- # Match two lines at a time to support multiline declarations\r
- if linenum + 1 < clean_lines.NumLines() and not Search(r'[;({]', line):\r
- line += clean_lines.elided[linenum + 1].strip()\r
-\r
- # Check for people declaring static/global STL strings at the top level.\r
- # This is dangerous because the C++ language does not guarantee that\r
- # globals with constructors are initialized before the first access, and\r
- # also because globals can be destroyed when some threads are still running.\r
- # TODO(unknown): Generalize this to also find static unique_ptr instances.\r
- # TODO(unknown): File bugs for clang-tidy to find these.\r
- match = Match(\r
- r'((?:|static +)(?:|const +))(?::*std::)?string( +const)? +'\r
- r'([a-zA-Z0-9_:]+)\b(.*)',\r
- line)\r
-\r
- # Remove false positives:\r
- # - String pointers (as opposed to values).\r
- # string *pointer\r
- # const string *pointer\r
- # string const *pointer\r
- # string *const pointer\r
- #\r
- # - Functions and template specializations.\r
- # string Function<Type>(...\r
- # string Class<Type>::Method(...\r
- #\r
- # - Operators. These are matched separately because operator names\r
- # cross non-word boundaries, and trying to match both operators\r
- # and functions at the same time would decrease accuracy of\r
- # matching identifiers.\r
- # string Class::operator*()\r
- if (match and\r
- not Search(r'\bstring\b(\s+const)?\s*[\*\&]\s*(const\s+)?\w', line) and\r
- not Search(r'\boperator\W', line) and\r
- not Match(r'\s*(<.*>)?(::[a-zA-Z0-9_]+)*\s*\(([^"]|$)', match.group(4))):\r
- if Search(r'\bconst\b', line):\r
- error(filename, linenum, 'runtime/string', 4,\r
- 'For a static/global string constant, use a C style string '\r
- 'instead: "%schar%s %s[]".' %\r
- (match.group(1), match.group(2) or '', match.group(3)))\r
- else:\r
- error(filename, linenum, 'runtime/string', 4,\r
- 'Static/global string variables are not permitted.')\r
-\r
- if (Search(r'\b([A-Za-z0-9_]*_)\(\1\)', line) or\r
- Search(r'\b([A-Za-z0-9_]*_)\(CHECK_NOTNULL\(\1\)\)', line)):\r
- error(filename, linenum, 'runtime/init', 4,\r
- 'You seem to be initializing a member variable with itself.')\r
-\r
-\r
-def CheckPrintf(filename, clean_lines, linenum, error):\r
- """Check for printf related issues.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- error: The function to call with any errors found.\r
- """\r
- line = clean_lines.elided[linenum]\r
-\r
- # When snprintf is used, the second argument shouldn't be a literal.\r
- match = Search(r'snprintf\s*\(([^,]*),\s*([0-9]*)\s*,', line)\r
- if match and match.group(2) != '0':\r
- # If 2nd arg is zero, snprintf is used to calculate size.\r
- error(filename, linenum, 'runtime/printf', 3,\r
- 'If you can, use sizeof(%s) instead of %s as the 2nd arg '\r
- 'to snprintf.' % (match.group(1), match.group(2)))\r
-\r
- # Check if some verboten C functions are being used.\r
- if Search(r'\bsprintf\s*\(', line):\r
- error(filename, linenum, 'runtime/printf', 5,\r
- 'Never use sprintf. Use snprintf instead.')\r
- match = Search(r'\b(strcpy|strcat)\s*\(', line)\r
- if match:\r
- error(filename, linenum, 'runtime/printf', 4,\r
- 'Almost always, snprintf is better than %s' % match.group(1))\r
-\r
-\r
-def IsDerivedFunction(clean_lines, linenum):\r
- """Check if current line contains an inherited function.\r
-\r
- Args:\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- Returns:\r
- True if current line contains a function with "override"\r
- virt-specifier.\r
- """\r
- # Scan back a few lines for start of current function\r
- for i in xrange(linenum, max(-1, linenum - 10), -1):\r
- match = Match(r'^([^()]*\w+)\(', clean_lines.elided[i])\r
- if match:\r
- # Look for "override" after the matching closing parenthesis\r
- line, _, closing_paren = CloseExpression(\r
- clean_lines, i, len(match.group(1)))\r
- return (closing_paren >= 0 and\r
- Search(r'\boverride\b', line[closing_paren:]))\r
- return False\r
-\r
-\r
-def IsOutOfLineMethodDefinition(clean_lines, linenum):\r
- """Check if current line contains an out-of-line method definition.\r
-\r
- Args:\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- Returns:\r
- True if current line contains an out-of-line method definition.\r
- """\r
- # Scan back a few lines for start of current function\r
- for i in xrange(linenum, max(-1, linenum - 10), -1):\r
- if Match(r'^([^()]*\w+)\(', clean_lines.elided[i]):\r
- return Match(r'^[^()]*\w+::\w+\(', clean_lines.elided[i]) is not None\r
- return False\r
-\r
-\r
-def IsInitializerList(clean_lines, linenum):\r
- """Check if current line is inside constructor initializer list.\r
-\r
- Args:\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- Returns:\r
- True if current line appears to be inside constructor initializer\r
- list, False otherwise.\r
- """\r
- for i in xrange(linenum, 1, -1):\r
- line = clean_lines.elided[i]\r
- if i == linenum:\r
- remove_function_body = Match(r'^(.*)\{\s*$', line)\r
- if remove_function_body:\r
- line = remove_function_body.group(1)\r
-\r
- if Search(r'\s:\s*\w+[({]', line):\r
- # A lone colon tend to indicate the start of a constructor\r
- # initializer list. It could also be a ternary operator, which\r
- # also tend to appear in constructor initializer lists as\r
- # opposed to parameter lists.\r
- return True\r
- if Search(r'\}\s*,\s*$', line):\r
- # A closing brace followed by a comma is probably the end of a\r
- # brace-initialized member in constructor initializer list.\r
- return True\r
- if Search(r'[{};]\s*$', line):\r
- # Found one of the following:\r
- # - A closing brace or semicolon, probably the end of the previous\r
- # function.\r
- # - An opening brace, probably the start of current class or namespace.\r
- #\r
- # Current line is probably not inside an initializer list since\r
- # we saw one of those things without seeing the starting colon.\r
- return False\r
-\r
- # Got to the beginning of the file without seeing the start of\r
- # constructor initializer list.\r
- return False\r
-\r
-\r
-def CheckForNonConstReference(filename, clean_lines, linenum,\r
- nesting_state, error):\r
- """Check for non-const references.\r
-\r
- Separate from CheckLanguage since it scans backwards from current\r
- line, instead of scanning forward.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- nesting_state: A NestingState instance which maintains information about\r
- the current stack of nested blocks being parsed.\r
- error: The function to call with any errors found.\r
- """\r
- # Do nothing if there is no '&' on current line.\r
- line = clean_lines.elided[linenum]\r
- if '&' not in line:\r
- return\r
-\r
- # If a function is inherited, current function doesn't have much of\r
- # a choice, so any non-const references should not be blamed on\r
- # derived function.\r
- if IsDerivedFunction(clean_lines, linenum):\r
- return\r
-\r
- # Don't warn on out-of-line method definitions, as we would warn on the\r
- # in-line declaration, if it isn't marked with 'override'.\r
- if IsOutOfLineMethodDefinition(clean_lines, linenum):\r
- return\r
-\r
- # Long type names may be broken across multiple lines, usually in one\r
- # of these forms:\r
- # LongType\r
- # ::LongTypeContinued &identifier\r
- # LongType::\r
- # LongTypeContinued &identifier\r
- # LongType<\r
- # ...>::LongTypeContinued &identifier\r
- #\r
- # If we detected a type split across two lines, join the previous\r
- # line to current line so that we can match const references\r
- # accordingly.\r
- #\r
- # Note that this only scans back one line, since scanning back\r
- # arbitrary number of lines would be expensive. If you have a type\r
- # that spans more than 2 lines, please use a typedef.\r
- if linenum > 1:\r
- previous = None\r
- if Match(r'\s*::(?:[\w<>]|::)+\s*&\s*\S', line):\r
- # previous_line\n + ::current_line\r
- previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+[\w<>])\s*$',\r
- clean_lines.elided[linenum - 1])\r
- elif Match(r'\s*[a-zA-Z_]([\w<>]|::)+\s*&\s*\S', line):\r
- # previous_line::\n + current_line\r
- previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+::)\s*$',\r
- clean_lines.elided[linenum - 1])\r
- if previous:\r
- line = previous.group(1) + line.lstrip()\r
- else:\r
- # Check for templated parameter that is split across multiple lines\r
- endpos = line.rfind('>')\r
- if endpos > -1:\r
- (_, startline, startpos) = ReverseCloseExpression(\r
- clean_lines, linenum, endpos)\r
- if startpos > -1 and startline < linenum:\r
- # Found the matching < on an earlier line, collect all\r
- # pieces up to current line.\r
- line = ''\r
- for i in xrange(startline, linenum + 1):\r
- line += clean_lines.elided[i].strip()\r
-\r
- # Check for non-const references in function parameters. A single '&' may\r
- # found in the following places:\r
- # inside expression: binary & for bitwise AND\r
- # inside expression: unary & for taking the address of something\r
- # inside declarators: reference parameter\r
- # We will exclude the first two cases by checking that we are not inside a\r
- # function body, including one that was just introduced by a trailing '{'.\r
- # TODO(unknown): Doesn't account for 'catch(Exception& e)' [rare].\r
- if (nesting_state.previous_stack_top and\r
- not (isinstance(nesting_state.previous_stack_top, _ClassInfo) or\r
- isinstance(nesting_state.previous_stack_top, _NamespaceInfo))):\r
- # Not at toplevel, not within a class, and not within a namespace\r
- return\r
-\r
- # Avoid initializer lists. We only need to scan back from the\r
- # current line for something that starts with ':'.\r
- #\r
- # We don't need to check the current line, since the '&' would\r
- # appear inside the second set of parentheses on the current line as\r
- # opposed to the first set.\r
- if linenum > 0:\r
- for i in xrange(linenum - 1, max(0, linenum - 10), -1):\r
- previous_line = clean_lines.elided[i]\r
- if not Search(r'[),]\s*$', previous_line):\r
- break\r
- if Match(r'^\s*:\s+\S', previous_line):\r
- return\r
-\r
- # Avoid preprocessors\r
- if Search(r'\\\s*$', line):\r
- return\r
-\r
- # Avoid constructor initializer lists\r
- if IsInitializerList(clean_lines, linenum):\r
- return\r
-\r
- # We allow non-const references in a few standard places, like functions\r
- # called "swap()" or iostream operators like "<<" or ">>". Do not check\r
- # those function parameters.\r
- #\r
- # We also accept & in static_assert, which looks like a function but\r
- # it's actually a declaration expression.\r
- whitelisted_functions = (r'(?:[sS]wap(?:<\w:+>)?|'\r
- r'operator\s*[<>][<>]|'\r
- r'static_assert|COMPILE_ASSERT'\r
- r')\s*\(')\r
- if Search(whitelisted_functions, line):\r
- return\r
- elif not Search(r'\S+\([^)]*$', line):\r
- # Don't see a whitelisted function on this line. Actually we\r
- # didn't see any function name on this line, so this is likely a\r
- # multi-line parameter list. Try a bit harder to catch this case.\r
- for i in xrange(2):\r
- if (linenum > i and\r
- Search(whitelisted_functions, clean_lines.elided[linenum - i - 1])):\r
- return\r
-\r
- decls = ReplaceAll(r'{[^}]*}', ' ', line) # exclude function body\r
- for parameter in re.findall(_RE_PATTERN_REF_PARAM, decls):\r
- if (not Match(_RE_PATTERN_CONST_REF_PARAM, parameter) and\r
- not Match(_RE_PATTERN_REF_STREAM_PARAM, parameter)):\r
- error(filename, linenum, 'runtime/references', 2,\r
- 'Is this a non-const reference? '\r
- 'If so, make const or use a pointer: ' +\r
- ReplaceAll(' *<', '<', parameter))\r
-\r
-\r
-def CheckCasts(filename, clean_lines, linenum, error):\r
- """Various cast related checks.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- error: The function to call with any errors found.\r
- """\r
- line = clean_lines.elided[linenum]\r
-\r
- # Check to see if they're using an conversion function cast.\r
- # I just try to capture the most common basic types, though there are more.\r
- # Parameterless conversion functions, such as bool(), are allowed as they are\r
- # probably a member operator declaration or default constructor.\r
- match = Search(\r
- r'(\bnew\s+(?:const\s+)?|\S<\s*(?:const\s+)?)?\b'\r
- r'(int|float|double|bool|char|int32|uint32|int64|uint64)'\r
- r'(\([^)].*)', line)\r
- expecting_function = ExpectingFunctionArgs(clean_lines, linenum)\r
- if match and not expecting_function:\r
- matched_type = match.group(2)\r
-\r
- # matched_new_or_template is used to silence two false positives:\r
- # - New operators\r
- # - Template arguments with function types\r
- #\r
- # For template arguments, we match on types immediately following\r
- # an opening bracket without any spaces. This is a fast way to\r
- # silence the common case where the function type is the first\r
- # template argument. False negative with less-than comparison is\r
- # avoided because those operators are usually followed by a space.\r
- #\r
- # function<double(double)> // bracket + no space = false positive\r
- # value < double(42) // bracket + space = true positive\r
- matched_new_or_template = match.group(1)\r
-\r
- # Avoid arrays by looking for brackets that come after the closing\r
- # parenthesis.\r
- if Match(r'\([^()]+\)\s*\[', match.group(3)):\r
- return\r
-\r
- # Other things to ignore:\r
- # - Function pointers\r
- # - Casts to pointer types\r
- # - Placement new\r
- # - Alias declarations\r
- matched_funcptr = match.group(3)\r
- if (matched_new_or_template is None and\r
- not (matched_funcptr and\r
- (Match(r'\((?:[^() ]+::\s*\*\s*)?[^() ]+\)\s*\(',\r
- matched_funcptr) or\r
- matched_funcptr.startswith('(*)'))) and\r
- not Match(r'\s*using\s+\S+\s*=\s*' + matched_type, line) and\r
- not Search(r'new\(\S+\)\s*' + matched_type, line)):\r
- error(filename, linenum, 'readability/casting', 4,\r
- 'Using deprecated casting style. '\r
- 'Use static_cast<%s>(...) instead' %\r
- matched_type)\r
-\r
- if not expecting_function:\r
- CheckCStyleCast(filename, clean_lines, linenum, 'static_cast',\r
- r'\((int|float|double|bool|char|u?int(16|32|64))\)', error)\r
-\r
- # This doesn't catch all cases. Consider (const char * const)"hello".\r
- #\r
- # (char *) "foo" should always be a const_cast (reinterpret_cast won't\r
- # compile).\r
- if CheckCStyleCast(filename, clean_lines, linenum, 'const_cast',\r
- r'\((char\s?\*+\s?)\)\s*"', error):\r
- pass\r
- else:\r
- # Check pointer casts for other than string constants\r
- CheckCStyleCast(filename, clean_lines, linenum, 'reinterpret_cast',\r
- r'\((\w+\s?\*+\s?)\)', error)\r
-\r
- # In addition, we look for people taking the address of a cast. This\r
- # is dangerous -- casts can assign to temporaries, so the pointer doesn't\r
- # point where you think.\r
- #\r
- # Some non-identifier character is required before the '&' for the\r
- # expression to be recognized as a cast. These are casts:\r
- # expression = &static_cast<int*>(temporary());\r
- # function(&(int*)(temporary()));\r
- #\r
- # This is not a cast:\r
- # reference_type&(int* function_param);\r
- match = Search(\r
- r'(?:[^\w]&\(([^)*][^)]*)\)[\w(])|'\r
- r'(?:[^\w]&(static|dynamic|down|reinterpret)_cast\b)', line)\r
- if match:\r
- # Try a better error message when the & is bound to something\r
- # dereferenced by the casted pointer, as opposed to the casted\r
- # pointer itself.\r
- parenthesis_error = False\r
- match = Match(r'^(.*&(?:static|dynamic|down|reinterpret)_cast\b)<', line)\r
- if match:\r
- _, y1, x1 = CloseExpression(clean_lines, linenum, len(match.group(1)))\r
- if x1 >= 0 and clean_lines.elided[y1][x1] == '(':\r
- _, y2, x2 = CloseExpression(clean_lines, y1, x1)\r
- if x2 >= 0:\r
- extended_line = clean_lines.elided[y2][x2:]\r
- if y2 < clean_lines.NumLines() - 1:\r
- extended_line += clean_lines.elided[y2 + 1]\r
- if Match(r'\s*(?:->|\[)', extended_line):\r
- parenthesis_error = True\r
-\r
- if parenthesis_error:\r
- error(filename, linenum, 'readability/casting', 4,\r
- ('Are you taking an address of something dereferenced '\r
- 'from a cast? Wrapping the dereferenced expression in '\r
- 'parentheses will make the binding more obvious'))\r
- else:\r
- error(filename, linenum, 'runtime/casting', 4,\r
- ('Are you taking an address of a cast? '\r
- 'This is dangerous: could be a temp var. '\r
- 'Take the address before doing the cast, rather than after'))\r
-\r
-\r
-def CheckCStyleCast(filename, clean_lines, linenum, cast_type, pattern, error):\r
- """Checks for a C-style cast by looking for the pattern.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- cast_type: The string for the C++ cast to recommend. This is either\r
- reinterpret_cast, static_cast, or const_cast, depending.\r
- pattern: The regular expression used to find C-style casts.\r
- error: The function to call with any errors found.\r
-\r
- Returns:\r
- True if an error was emitted.\r
- False otherwise.\r
- """\r
- line = clean_lines.elided[linenum]\r
- match = Search(pattern, line)\r
- if not match:\r
- return False\r
-\r
- # Exclude lines with keywords that tend to look like casts\r
- context = line[0:match.start(1) - 1]\r
- if Match(r'.*\b(?:sizeof|alignof|alignas|[_A-Z][_A-Z0-9]*)\s*$', context):\r
- return False\r
-\r
- # Try expanding current context to see if we one level of\r
- # parentheses inside a macro.\r
- if linenum > 0:\r
- for i in xrange(linenum - 1, max(0, linenum - 5), -1):\r
- context = clean_lines.elided[i] + context\r
- if Match(r'.*\b[_A-Z][_A-Z0-9]*\s*\((?:\([^()]*\)|[^()])*$', context):\r
- return False\r
-\r
- # operator++(int) and operator--(int)\r
- if context.endswith(' operator++') or context.endswith(' operator--'):\r
- return False\r
-\r
- # A single unnamed argument for a function tends to look like old style cast.\r
- # If we see those, don't issue warnings for deprecated casts.\r
- remainder = line[match.end(0):]\r
- if Match(r'^\s*(?:;|const\b|throw\b|final\b|override\b|[=>{),]|->)',\r
- remainder):\r
- return False\r
-\r
- # At this point, all that should be left is actual casts.\r
- error(filename, linenum, 'readability/casting', 4,\r
- 'Using C-style cast. Use %s<%s>(...) instead' %\r
- (cast_type, match.group(1)))\r
-\r
- return True\r
-\r
-\r
-def ExpectingFunctionArgs(clean_lines, linenum):\r
- """Checks whether where function type arguments are expected.\r
-\r
- Args:\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
-\r
- Returns:\r
- True if the line at 'linenum' is inside something that expects arguments\r
- of function types.\r
- """\r
- line = clean_lines.elided[linenum]\r
- return (Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line) or\r
- (linenum >= 2 and\r
- (Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\((?:\S+,)?\s*$',\r
- clean_lines.elided[linenum - 1]) or\r
- Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\(\s*$',\r
- clean_lines.elided[linenum - 2]) or\r
- Search(r'\bstd::m?function\s*\<\s*$',\r
- clean_lines.elided[linenum - 1]))))\r
-\r
-\r
-_HEADERS_CONTAINING_TEMPLATES = (\r
- ('<deque>', ('deque',)),\r
- ('<functional>', ('unary_function', 'binary_function',\r
- 'plus', 'minus', 'multiplies', 'divides', 'modulus',\r
- 'negate',\r
- 'equal_to', 'not_equal_to', 'greater', 'less',\r
- 'greater_equal', 'less_equal',\r
- 'logical_and', 'logical_or', 'logical_not',\r
- 'unary_negate', 'not1', 'binary_negate', 'not2',\r
- 'bind1st', 'bind2nd',\r
- 'pointer_to_unary_function',\r
- 'pointer_to_binary_function',\r
- 'ptr_fun',\r
- 'mem_fun_t', 'mem_fun', 'mem_fun1_t', 'mem_fun1_ref_t',\r
- 'mem_fun_ref_t',\r
- 'const_mem_fun_t', 'const_mem_fun1_t',\r
- 'const_mem_fun_ref_t', 'const_mem_fun1_ref_t',\r
- 'mem_fun_ref',\r
- )),\r
- ('<limits>', ('numeric_limits',)),\r
- ('<list>', ('list',)),\r
- ('<map>', ('map', 'multimap',)),\r
- ('<memory>', ('allocator', 'make_shared', 'make_unique', 'shared_ptr',\r
- 'unique_ptr', 'weak_ptr')),\r
- ('<queue>', ('queue', 'priority_queue',)),\r
- ('<set>', ('set', 'multiset',)),\r
- ('<stack>', ('stack',)),\r
- ('<string>', ('char_traits', 'basic_string',)),\r
- ('<tuple>', ('tuple',)),\r
- ('<unordered_map>', ('unordered_map', 'unordered_multimap')),\r
- ('<unordered_set>', ('unordered_set', 'unordered_multiset')),\r
- ('<utility>', ('pair',)),\r
- ('<vector>', ('vector',)),\r
-\r
- # gcc extensions.\r
- # Note: std::hash is their hash, ::hash is our hash\r
- ('<hash_map>', ('hash_map', 'hash_multimap',)),\r
- ('<hash_set>', ('hash_set', 'hash_multiset',)),\r
- ('<slist>', ('slist',)),\r
- )\r
-\r
-_HEADERS_MAYBE_TEMPLATES = (\r
- ('<algorithm>', ('copy', 'max', 'min', 'min_element', 'sort',\r
- 'transform',\r
- )),\r
- ('<utility>', ('forward', 'make_pair', 'move', 'swap')),\r
- )\r
-\r
-_RE_PATTERN_STRING = re.compile(r'\bstring\b')\r
-\r
-_re_pattern_headers_maybe_templates = []\r
-for _header, _templates in _HEADERS_MAYBE_TEMPLATES:\r
- for _template in _templates:\r
- # Match max<type>(..., ...), max(..., ...), but not foo->max, foo.max or\r
- # type::max().\r
- _re_pattern_headers_maybe_templates.append(\r
- (re.compile(r'[^>.]\b' + _template + r'(<.*?>)?\([^\)]'),\r
- _template,\r
- _header))\r
-\r
-# Other scripts may reach in and modify this pattern.\r
-_re_pattern_templates = []\r
-for _header, _templates in _HEADERS_CONTAINING_TEMPLATES:\r
- for _template in _templates:\r
- _re_pattern_templates.append(\r
- (re.compile(r'(\<|\b)' + _template + r'\s*\<'),\r
- _template + '<>',\r
- _header))\r
-\r
-\r
-def FilesBelongToSameModule(filename_cc, filename_h):\r
- """Check if these two filenames belong to the same module.\r
-\r
- The concept of a 'module' here is a as follows:\r
- foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the\r
- same 'module' if they are in the same directory.\r
- some/path/public/xyzzy and some/path/internal/xyzzy are also considered\r
- to belong to the same module here.\r
-\r
- If the filename_cc contains a longer path than the filename_h, for example,\r
- '/absolute/path/to/base/sysinfo.cc', and this file would include\r
- 'base/sysinfo.h', this function also produces the prefix needed to open the\r
- header. This is used by the caller of this function to more robustly open the\r
- header file. We don't have access to the real include paths in this context,\r
- so we need this guesswork here.\r
-\r
- Known bugs: tools/base/bar.cc and base/bar.h belong to the same module\r
- according to this implementation. Because of this, this function gives\r
- some false positives. This should be sufficiently rare in practice.\r
-\r
- Args:\r
- filename_cc: is the path for the .cc file\r
- filename_h: is the path for the header path\r
-\r
- Returns:\r
- Tuple with a bool and a string:\r
- bool: True if filename_cc and filename_h belong to the same module.\r
- string: the additional prefix needed to open the header file.\r
- """\r
-\r
- fileinfo = FileInfo(filename_cc)\r
- if not fileinfo.IsSource():\r
- return (False, '')\r
- filename_cc = filename_cc[:-len(fileinfo.Extension())]\r
- matched_test_suffix = Search(_TEST_FILE_SUFFIX, fileinfo.BaseName())\r
- if matched_test_suffix:\r
- filename_cc = filename_cc[:-len(matched_test_suffix.group(1))]\r
- filename_cc = filename_cc.replace('/public/', '/')\r
- filename_cc = filename_cc.replace('/internal/', '/')\r
-\r
- if not filename_h.endswith('.h'):\r
- return (False, '')\r
- filename_h = filename_h[:-len('.h')]\r
- if filename_h.endswith('-inl'):\r
- filename_h = filename_h[:-len('-inl')]\r
- filename_h = filename_h.replace('/public/', '/')\r
- filename_h = filename_h.replace('/internal/', '/')\r
-\r
- files_belong_to_same_module = filename_cc.endswith(filename_h)\r
- common_path = ''\r
- if files_belong_to_same_module:\r
- common_path = filename_cc[:-len(filename_h)]\r
- return files_belong_to_same_module, common_path\r
-\r
-\r
-def UpdateIncludeState(filename, include_dict, io=codecs):\r
- """Fill up the include_dict with new includes found from the file.\r
-\r
- Args:\r
- filename: the name of the header to read.\r
- include_dict: a dictionary in which the headers are inserted.\r
- io: The io factory to use to read the file. Provided for testability.\r
-\r
- Returns:\r
- True if a header was successfully added. False otherwise.\r
- """\r
- headerfile = None\r
- try:\r
- headerfile = io.open(filename, 'r', 'utf8', 'replace')\r
- except IOError:\r
- return False\r
- linenum = 0\r
- for line in headerfile:\r
- linenum += 1\r
- clean_line = CleanseComments(line)\r
- match = _RE_PATTERN_INCLUDE.search(clean_line)\r
- if match:\r
- include = match.group(2)\r
- include_dict.setdefault(include, linenum)\r
- return True\r
-\r
-\r
-def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error,\r
- io=codecs):\r
- """Reports for missing stl includes.\r
-\r
- This function will output warnings to make sure you are including the headers\r
- necessary for the stl containers and functions that you use. We only give one\r
- reason to include a header. For example, if you use both equal_to<> and\r
- less<> in a .h file, only one (the latter in the file) of these will be\r
- reported as a reason to include the <functional>.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- include_state: An _IncludeState instance.\r
- error: The function to call with any errors found.\r
- io: The IO factory to use to read the header file. Provided for unittest\r
- injection.\r
- """\r
- required = {} # A map of header name to linenumber and the template entity.\r
- # Example of required: { '<functional>': (1219, 'less<>') }\r
-\r
- for linenum in xrange(clean_lines.NumLines()):\r
- line = clean_lines.elided[linenum]\r
- if not line or line[0] == '#':\r
- continue\r
-\r
- # String is special -- it is a non-templatized type in STL.\r
- matched = _RE_PATTERN_STRING.search(line)\r
- if matched:\r
- # Don't warn about strings in non-STL namespaces:\r
- # (We check only the first match per line; good enough.)\r
- prefix = line[:matched.start()]\r
- if prefix.endswith('std::') or not prefix.endswith('::'):\r
- required['<string>'] = (linenum, 'string')\r
-\r
- for pattern, template, header in _re_pattern_headers_maybe_templates:\r
- if pattern.search(line):\r
- required[header] = (linenum, template)\r
-\r
- # The following function is just a speed up, no semantics are changed.\r
- if not '<' in line: # Reduces the cpu time usage by skipping lines.\r
- continue\r
-\r
- for pattern, template, header in _re_pattern_templates:\r
- matched = pattern.search(line)\r
- if matched:\r
- # Don't warn about IWYU in non-STL namespaces:\r
- # (We check only the first match per line; good enough.)\r
- prefix = line[:matched.start()]\r
- if prefix.endswith('std::') or not prefix.endswith('::'):\r
- required[header] = (linenum, template)\r
-\r
- # The policy is that if you #include something in foo.h you don't need to\r
- # include it again in foo.cc. Here, we will look at possible includes.\r
- # Let's flatten the include_state include_list and copy it into a dictionary.\r
- include_dict = dict([item for sublist in include_state.include_list\r
- for item in sublist])\r
-\r
- # Did we find the header for this file (if any) and successfully load it?\r
- header_found = False\r
-\r
- # Use the absolute path so that matching works properly.\r
- abs_filename = FileInfo(filename).FullName()\r
-\r
- # For Emacs's flymake.\r
- # If cpplint is invoked from Emacs's flymake, a temporary file is generated\r
- # by flymake and that file name might end with '_flymake.cc'. In that case,\r
- # restore original file name here so that the corresponding header file can be\r
- # found.\r
- # e.g. If the file name is 'foo_flymake.cc', we should search for 'foo.h'\r
- # instead of 'foo_flymake.h'\r
- abs_filename = re.sub(r'_flymake\.cc$', '.cc', abs_filename)\r
-\r
- # include_dict is modified during iteration, so we iterate over a copy of\r
- # the keys.\r
- header_keys = include_dict.keys()\r
- for header in header_keys:\r
- (same_module, common_path) = FilesBelongToSameModule(abs_filename, header)\r
- fullpath = common_path + header\r
- if same_module and UpdateIncludeState(fullpath, include_dict, io):\r
- header_found = True\r
-\r
- # If we can't find the header file for a .cc, assume it's because we don't\r
- # know where to look. In that case we'll give up as we're not sure they\r
- # didn't include it in the .h file.\r
- # TODO(unknown): Do a better job of finding .h files so we are confident that\r
- # not having the .h file means there isn't one.\r
- if filename.endswith('.cc') and not header_found:\r
- return\r
-\r
- # All the lines have been processed, report the errors found.\r
- for required_header_unstripped in required:\r
- template = required[required_header_unstripped][1]\r
- if required_header_unstripped.strip('<>"') not in include_dict:\r
- error(filename, required[required_header_unstripped][0],\r
- 'build/include_what_you_use', 4,\r
- 'Add #include ' + required_header_unstripped + ' for ' + template)\r
-\r
-\r
-_RE_PATTERN_EXPLICIT_MAKEPAIR = re.compile(r'\bmake_pair\s*<')\r
-\r
-\r
-def CheckMakePairUsesDeduction(filename, clean_lines, linenum, error):\r
- """Check that make_pair's template arguments are deduced.\r
-\r
- G++ 4.6 in C++11 mode fails badly if make_pair's template arguments are\r
- specified explicitly, and such use isn't intended in any case.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- error: The function to call with any errors found.\r
- """\r
- line = clean_lines.elided[linenum]\r
- match = _RE_PATTERN_EXPLICIT_MAKEPAIR.search(line)\r
- if match:\r
- error(filename, linenum, 'build/explicit_make_pair',\r
- 4, # 4 = high confidence\r
- 'For C++11-compatibility, omit template arguments from make_pair'\r
- ' OR use pair directly OR if appropriate, construct a pair directly')\r
-\r
-\r
-def CheckRedundantVirtual(filename, clean_lines, linenum, error):\r
- """Check if line contains a redundant "virtual" function-specifier.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- error: The function to call with any errors found.\r
- """\r
- # Look for "virtual" on current line.\r
- line = clean_lines.elided[linenum]\r
- virtual = Match(r'^(.*)(\bvirtual\b)(.*)$', line)\r
- if not virtual: return\r
-\r
- # Ignore "virtual" keywords that are near access-specifiers. These\r
- # are only used in class base-specifier and do not apply to member\r
- # functions.\r
- if (Search(r'\b(public|protected|private)\s+$', virtual.group(1)) or\r
- Match(r'^\s+(public|protected|private)\b', virtual.group(3))):\r
- return\r
-\r
- # Ignore the "virtual" keyword from virtual base classes. Usually\r
- # there is a column on the same line in these cases (virtual base\r
- # classes are rare in google3 because multiple inheritance is rare).\r
- if Match(r'^.*[^:]:[^:].*$', line): return\r
-\r
- # Look for the next opening parenthesis. This is the start of the\r
- # parameter list (possibly on the next line shortly after virtual).\r
- # TODO(unknown): doesn't work if there are virtual functions with\r
- # decltype() or other things that use parentheses, but csearch suggests\r
- # that this is rare.\r
- end_col = -1\r
- end_line = -1\r
- start_col = len(virtual.group(2))\r
- for start_line in xrange(linenum, min(linenum + 3, clean_lines.NumLines())):\r
- line = clean_lines.elided[start_line][start_col:]\r
- parameter_list = Match(r'^([^(]*)\(', line)\r
- if parameter_list:\r
- # Match parentheses to find the end of the parameter list\r
- (_, end_line, end_col) = CloseExpression(\r
- clean_lines, start_line, start_col + len(parameter_list.group(1)))\r
- break\r
- start_col = 0\r
-\r
- if end_col < 0:\r
- return # Couldn't find end of parameter list, give up\r
-\r
- # Look for "override" or "final" after the parameter list\r
- # (possibly on the next few lines).\r
- for i in xrange(end_line, min(end_line + 3, clean_lines.NumLines())):\r
- line = clean_lines.elided[i][end_col:]\r
- match = Search(r'\b(override|final)\b', line)\r
- if match:\r
- error(filename, linenum, 'readability/inheritance', 4,\r
- ('"virtual" is redundant since function is '\r
- 'already declared as "%s"' % match.group(1)))\r
-\r
- # Set end_col to check whole lines after we are done with the\r
- # first line.\r
- end_col = 0\r
- if Search(r'[^\w]\s*$', line):\r
- break\r
-\r
-\r
-def CheckRedundantOverrideOrFinal(filename, clean_lines, linenum, error):\r
- """Check if line contains a redundant "override" or "final" virt-specifier.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- error: The function to call with any errors found.\r
- """\r
- # Look for closing parenthesis nearby. We need one to confirm where\r
- # the declarator ends and where the virt-specifier starts to avoid\r
- # false positives.\r
- line = clean_lines.elided[linenum]\r
- declarator_end = line.rfind(')')\r
- if declarator_end >= 0:\r
- fragment = line[declarator_end:]\r
- else:\r
- if linenum > 1 and clean_lines.elided[linenum - 1].rfind(')') >= 0:\r
- fragment = line\r
- else:\r
- return\r
-\r
- # Check that at most one of "override" or "final" is present, not both\r
- if Search(r'\boverride\b', fragment) and Search(r'\bfinal\b', fragment):\r
- error(filename, linenum, 'readability/inheritance', 4,\r
- ('"override" is redundant since function is '\r
- 'already declared as "final"'))\r
-\r
-\r
-\r
-\r
-# Returns true if we are at a new block, and it is directly\r
-# inside of a namespace.\r
-def IsBlockInNameSpace(nesting_state, is_forward_declaration):\r
- """Checks that the new block is directly in a namespace.\r
-\r
- Args:\r
- nesting_state: The _NestingState object that contains info about our state.\r
- is_forward_declaration: If the class is a forward declared class.\r
- Returns:\r
- Whether or not the new block is directly in a namespace.\r
- """\r
- if is_forward_declaration:\r
- if len(nesting_state.stack) >= 1 and (\r
- isinstance(nesting_state.stack[-1], _NamespaceInfo)):\r
- return True\r
- else:\r
- return False\r
-\r
- return (len(nesting_state.stack) > 1 and\r
- nesting_state.stack[-1].check_namespace_indentation and\r
- isinstance(nesting_state.stack[-2], _NamespaceInfo))\r
-\r
-\r
-def ShouldCheckNamespaceIndentation(nesting_state, is_namespace_indent_item,\r
- raw_lines_no_comments, linenum):\r
- """This method determines if we should apply our namespace indentation check.\r
-\r
- Args:\r
- nesting_state: The current nesting state.\r
- is_namespace_indent_item: If we just put a new class on the stack, True.\r
- If the top of the stack is not a class, or we did not recently\r
- add the class, False.\r
- raw_lines_no_comments: The lines without the comments.\r
- linenum: The current line number we are processing.\r
-\r
- Returns:\r
- True if we should apply our namespace indentation check. Currently, it\r
- only works for classes and namespaces inside of a namespace.\r
- """\r
-\r
- is_forward_declaration = IsForwardClassDeclaration(raw_lines_no_comments,\r
- linenum)\r
-\r
- if not (is_namespace_indent_item or is_forward_declaration):\r
- return False\r
-\r
- # If we are in a macro, we do not want to check the namespace indentation.\r
- if IsMacroDefinition(raw_lines_no_comments, linenum):\r
- return False\r
-\r
- return IsBlockInNameSpace(nesting_state, is_forward_declaration)\r
-\r
-\r
-# Call this method if the line is directly inside of a namespace.\r
-# If the line above is blank (excluding comments) or the start of\r
-# an inner namespace, it cannot be indented.\r
-def CheckItemIndentationInNamespace(filename, raw_lines_no_comments, linenum,\r
- error):\r
- line = raw_lines_no_comments[linenum]\r
- if Match(r'^\s+', line):\r
- error(filename, linenum, 'runtime/indentation_namespace', 4,\r
- 'Do not indent within a namespace')\r
-\r
-\r
-def ProcessLine(filename, file_extension, clean_lines, line,\r
- include_state, function_state, nesting_state, error,\r
- extra_check_functions=[]):\r
- """Processes a single line in the file.\r
-\r
- Args:\r
- filename: Filename of the file that is being processed.\r
- file_extension: The extension (dot not included) of the file.\r
- clean_lines: An array of strings, each representing a line of the file,\r
- with comments stripped.\r
- line: Number of line being processed.\r
- include_state: An _IncludeState instance in which the headers are inserted.\r
- function_state: A _FunctionState instance which counts function lines, etc.\r
- nesting_state: A NestingState instance which maintains information about\r
- the current stack of nested blocks being parsed.\r
- error: A callable to which errors are reported, which takes 4 arguments:\r
- filename, line number, error level, and message\r
- extra_check_functions: An array of additional check functions that will be\r
- run on each source line. Each function takes 4\r
- arguments: filename, clean_lines, line, error\r
- """\r
- raw_lines = clean_lines.raw_lines\r
- ParseNolintSuppressions(filename, raw_lines[line], line, error)\r
- nesting_state.Update(filename, clean_lines, line, error)\r
- CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line,\r
- error)\r
- if nesting_state.InAsmBlock(): return\r
- CheckForFunctionLengths(filename, clean_lines, line, function_state, error)\r
- CheckForMultilineCommentsAndStrings(filename, clean_lines, line, error)\r
- CheckStyle(filename, clean_lines, line, file_extension, nesting_state, error)\r
- CheckLanguage(filename, clean_lines, line, file_extension, include_state,\r
- nesting_state, error)\r
- CheckForNonConstReference(filename, clean_lines, line, nesting_state, error)\r
- CheckForNonStandardConstructs(filename, clean_lines, line,\r
- nesting_state, error)\r
- CheckVlogArguments(filename, clean_lines, line, error)\r
- CheckPosixThreading(filename, clean_lines, line, error)\r
- CheckInvalidIncrement(filename, clean_lines, line, error)\r
- CheckMakePairUsesDeduction(filename, clean_lines, line, error)\r
- CheckRedundantVirtual(filename, clean_lines, line, error)\r
- CheckRedundantOverrideOrFinal(filename, clean_lines, line, error)\r
- for check_fn in extra_check_functions:\r
- check_fn(filename, clean_lines, line, error)\r
-\r
-def FlagCxx11Features(filename, clean_lines, linenum, error):\r
- """Flag those c++11 features that we only allow in certain places.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- error: The function to call with any errors found.\r
- """\r
- line = clean_lines.elided[linenum]\r
-\r
- include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line)\r
-\r
- # Flag unapproved C++ TR1 headers.\r
- if include and include.group(1).startswith('tr1/'):\r
- error(filename, linenum, 'build/c++tr1', 5,\r
- ('C++ TR1 headers such as <%s> are unapproved.') % include.group(1))\r
-\r
- # Flag unapproved C++11 headers.\r
- if include and include.group(1) in ('cfenv',\r
- 'condition_variable',\r
- 'fenv.h',\r
- 'future',\r
- 'mutex',\r
- 'thread',\r
- 'chrono',\r
- 'ratio',\r
- 'regex',\r
- 'system_error',\r
- ):\r
- error(filename, linenum, 'build/c++11', 5,\r
- ('<%s> is an unapproved C++11 header.') % include.group(1))\r
-\r
- # The only place where we need to worry about C++11 keywords and library\r
- # features in preprocessor directives is in macro definitions.\r
- if Match(r'\s*#', line) and not Match(r'\s*#\s*define\b', line): return\r
-\r
- # These are classes and free functions. The classes are always\r
- # mentioned as std::*, but we only catch the free functions if\r
- # they're not found by ADL. They're alphabetical by header.\r
- for top_name in (\r
- # type_traits\r
- 'alignment_of',\r
- 'aligned_union',\r
- ):\r
- if Search(r'\bstd::%s\b' % top_name, line):\r
- error(filename, linenum, 'build/c++11', 5,\r
- ('std::%s is an unapproved C++11 class or function. Send c-style '\r
- 'an example of where it would make your code more readable, and '\r
- 'they may let you use it.') % top_name)\r
-\r
-\r
-def FlagCxx14Features(filename, clean_lines, linenum, error):\r
- """Flag those C++14 features that we restrict.\r
-\r
- Args:\r
- filename: The name of the current file.\r
- clean_lines: A CleansedLines instance containing the file.\r
- linenum: The number of the line to check.\r
- error: The function to call with any errors found.\r
- """\r
- line = clean_lines.elided[linenum]\r
-\r
- include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line)\r
-\r
- # Flag unapproved C++14 headers.\r
- if include and include.group(1) in ('scoped_allocator', 'shared_mutex'):\r
- error(filename, linenum, 'build/c++14', 5,\r
- ('<%s> is an unapproved C++14 header.') % include.group(1))\r
-\r
-\r
-def ProcessFileData(filename, file_extension, lines, error,\r
- extra_check_functions=[]):\r
- """Performs lint checks and reports any errors to the given error function.\r
-\r
- Args:\r
- filename: Filename of the file that is being processed.\r
- file_extension: The extension (dot not included) of the file.\r
- lines: An array of strings, each representing a line of the file, with the\r
- last element being empty if the file is terminated with a newline.\r
- error: A callable to which errors are reported, which takes 4 arguments:\r
- filename, line number, error level, and message\r
- extra_check_functions: An array of additional check functions that will be\r
- run on each source line. Each function takes 4\r
- arguments: filename, clean_lines, line, error\r
- """\r
- lines = (['// marker so line numbers and indices both start at 1'] + lines +\r
- ['// marker so line numbers end in a known way'])\r
-\r
- include_state = _IncludeState()\r
- function_state = _FunctionState()\r
- nesting_state = NestingState()\r
-\r
- ResetNolintSuppressions()\r
-\r
- CheckForCopyright(filename, lines, error)\r
- ProcessGlobalSuppresions(lines)\r
- RemoveMultiLineComments(filename, lines, error)\r
- clean_lines = CleansedLines(lines)\r
-\r
- if IsHeaderExtension(file_extension):\r
- CheckForHeaderGuard(filename, clean_lines, error)\r
-\r
- for line in xrange(clean_lines.NumLines()):\r
- ProcessLine(filename, file_extension, clean_lines, line,\r
- include_state, function_state, nesting_state, error,\r
- extra_check_functions)\r
- FlagCxx11Features(filename, clean_lines, line, error)\r
- nesting_state.CheckCompletedBlocks(filename, error)\r
-\r
- CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error)\r
-\r
- # Check that the .cc file has included its header if it exists.\r
- if _IsSourceExtension(file_extension):\r
- CheckHeaderFileIncluded(filename, include_state, error)\r
-\r
- # We check here rather than inside ProcessLine so that we see raw\r
- # lines rather than "cleaned" lines.\r
- CheckForBadCharacters(filename, lines, error)\r
-\r
- CheckForNewlineAtEOF(filename, lines, error)\r
-\r
-def ProcessConfigOverrides(filename):\r
- """ Loads the configuration files and processes the config overrides.\r
-\r
- Args:\r
- filename: The name of the file being processed by the linter.\r
-\r
- Returns:\r
- False if the current |filename| should not be processed further.\r
- """\r
-\r
- abs_filename = os.path.abspath(filename)\r
- cfg_filters = []\r
- keep_looking = True\r
- while keep_looking:\r
- abs_path, base_name = os.path.split(abs_filename)\r
- if not base_name:\r
- break # Reached the root directory.\r
-\r
- cfg_file = os.path.join(abs_path, "CPPLINT.cfg")\r
- abs_filename = abs_path\r
- if not os.path.isfile(cfg_file):\r
- continue\r
-\r
- try:\r
- with open(cfg_file) as file_handle:\r
- for line in file_handle:\r
- line, _, _ = line.partition('#') # Remove comments.\r
- if not line.strip():\r
- continue\r
-\r
- name, _, val = line.partition('=')\r
- name = name.strip()\r
- val = val.strip()\r
- if name == 'set noparent':\r
- keep_looking = False\r
- elif name == 'filter':\r
- cfg_filters.append(val)\r
- elif name == 'exclude_files':\r
- # When matching exclude_files pattern, use the base_name of\r
- # the current file name or the directory name we are processing.\r
- # For example, if we are checking for lint errors in /foo/bar/baz.cc\r
- # and we found the .cfg file at /foo/CPPLINT.cfg, then the config\r
- # file's "exclude_files" filter is meant to be checked against "bar"\r
- # and not "baz" nor "bar/baz.cc".\r
- if base_name:\r
- pattern = re.compile(val)\r
- if pattern.match(base_name):\r
- sys.stderr.write('Ignoring "%s": file excluded by "%s". '\r
- 'File path component "%s" matches '\r
- 'pattern "%s"\n' %\r
- (filename, cfg_file, base_name, val))\r
- return False\r
- elif name == 'linelength':\r
- global _line_length\r
- try:\r
- _line_length = int(val)\r
- except ValueError:\r
- sys.stderr.write('Line length must be numeric.')\r
- elif name == 'root':\r
- global _root\r
- _root = val\r
- elif name == 'headers':\r
- ProcessHppHeadersOption(val)\r
- else:\r
- sys.stderr.write(\r
- 'Invalid configuration option (%s) in file %s\n' %\r
- (name, cfg_file))\r
-\r
- except IOError:\r
- sys.stderr.write(\r
- "Skipping config file '%s': Can't open for reading\n" % cfg_file)\r
- keep_looking = False\r
-\r
- # Apply all the accumulated filters in reverse order (top-level directory\r
- # config options having the least priority).\r
- for filter in reversed(cfg_filters):\r
- _AddFilters(filter)\r
-\r
- return True\r
-\r
-\r
-def ProcessFile(filename, vlevel, extra_check_functions=[]):\r
- """Does google-lint on a single file.\r
-\r
- Args:\r
- filename: The name of the file to parse.\r
-\r
- vlevel: The level of errors to report. Every error of confidence\r
- >= verbose_level will be reported. 0 is a good default.\r
-\r
- extra_check_functions: An array of additional check functions that will be\r
- run on each source line. Each function takes 4\r
- arguments: filename, clean_lines, line, error\r
- """\r
-\r
- _SetVerboseLevel(vlevel)\r
- _BackupFilters()\r
-\r
- if not ProcessConfigOverrides(filename):\r
- _RestoreFilters()\r
- return\r
-\r
- lf_lines = []\r
- crlf_lines = []\r
- try:\r
- # Support the UNIX convention of using "-" for stdin. Note that\r
- # we are not opening the file with universal newline support\r
- # (which codecs doesn't support anyway), so the resulting lines do\r
- # contain trailing '\r' characters if we are reading a file that\r
- # has CRLF endings.\r
- # If after the split a trailing '\r' is present, it is removed\r
- # below.\r
- if filename == '-':\r
- lines = codecs.StreamReaderWriter(sys.stdin,\r
- codecs.getreader('utf8'),\r
- codecs.getwriter('utf8'),\r
- 'replace').read().split('\n')\r
- else:\r
- lines = codecs.open(filename, 'r', 'utf8', 'replace').read().split('\n')\r
-\r
- # Remove trailing '\r'.\r
- # The -1 accounts for the extra trailing blank line we get from split()\r
- for linenum in range(len(lines) - 1):\r
- if lines[linenum].endswith('\r'):\r
- lines[linenum] = lines[linenum].rstrip('\r')\r
- crlf_lines.append(linenum + 1)\r
- else:\r
- lf_lines.append(linenum + 1)\r
-\r
- except IOError:\r
- sys.stderr.write(\r
- "Skipping input '%s': Can't open for reading\n" % filename)\r
- _RestoreFilters()\r
- return\r
-\r
- # Note, if no dot is found, this will give the entire filename as the ext.\r
- file_extension = filename[filename.rfind('.') + 1:]\r
-\r
- # When reading from stdin, the extension is unknown, so no cpplint tests\r
- # should rely on the extension.\r
- if filename != '-' and file_extension not in _valid_extensions:\r
- sys.stderr.write('Ignoring %s; not a valid file name '\r
- '(%s)\n' % (filename, ', '.join(_valid_extensions)))\r
- else:\r
- ProcessFileData(filename, file_extension, lines, Error,\r
- extra_check_functions)\r
-\r
- # If end-of-line sequences are a mix of LF and CR-LF, issue\r
- # warnings on the lines with CR.\r
- #\r
- # Don't issue any warnings if all lines are uniformly LF or CR-LF,\r
- # since critique can handle these just fine, and the style guide\r
- # doesn't dictate a particular end of line sequence.\r
- #\r
- # We can't depend on os.linesep to determine what the desired\r
- # end-of-line sequence should be, since that will return the\r
- # server-side end-of-line sequence.\r
- if lf_lines and crlf_lines:\r
- # Warn on every line with CR. An alternative approach might be to\r
- # check whether the file is mostly CRLF or just LF, and warn on the\r
- # minority, we bias toward LF here since most tools prefer LF.\r
- for linenum in crlf_lines:\r
- Error(filename, linenum, 'whitespace/newline', 1,\r
- 'Unexpected \\r (^M) found; better to use only \\n')\r
-\r
- sys.stdout.write('Done processing %s\n' % filename)\r
- _RestoreFilters()\r
-\r
-\r
-def PrintUsage(message):\r
- """Prints a brief usage string and exits, optionally with an error message.\r
-\r
- Args:\r
- message: The optional error message.\r
- """\r
- sys.stderr.write(_USAGE)\r
- if message:\r
- sys.exit('\nFATAL ERROR: ' + message)\r
- else:\r
- sys.exit(1)\r
-\r
-\r
-def PrintCategories():\r
- """Prints a list of all the error-categories used by error messages.\r
-\r
- These are the categories used to filter messages via --filter.\r
- """\r
- sys.stderr.write(''.join(' %s\n' % cat for cat in _ERROR_CATEGORIES))\r
- sys.exit(0)\r
-\r
-\r
-def ParseArguments(args):\r
- """Parses the command line arguments.\r
-\r
- This may set the output format and verbosity level as side-effects.\r
-\r
- Args:\r
- args: The command line arguments:\r
-\r
- Returns:\r
- The list of filenames to lint.\r
- """\r
- try:\r
- (opts, filenames) = getopt.getopt(args, '', ['help', 'output=', 'verbose=',\r
- 'counting=',\r
- 'filter=',\r
- 'root=',\r
- 'linelength=',\r
- 'extensions=',\r
- 'headers='])\r
- except getopt.GetoptError:\r
- PrintUsage('Invalid arguments.')\r
-\r
- verbosity = _VerboseLevel()\r
- output_format = _OutputFormat()\r
- filters = ''\r
- counting_style = ''\r
-\r
- for (opt, val) in opts:\r
- if opt == '--help':\r
- PrintUsage(None)\r
- elif opt == '--output':\r
- if val not in ('emacs', 'vs7', 'eclipse'):\r
- PrintUsage('The only allowed output formats are emacs, vs7 and eclipse.')\r
- output_format = val\r
- elif opt == '--verbose':\r
- verbosity = int(val)\r
- elif opt == '--filter':\r
- filters = val\r
- if not filters:\r
- PrintCategories()\r
- elif opt == '--counting':\r
- if val not in ('total', 'toplevel', 'detailed'):\r
- PrintUsage('Valid counting options are total, toplevel, and detailed')\r
- counting_style = val\r
- elif opt == '--root':\r
- global _root\r
- _root = val\r
- elif opt == '--linelength':\r
- global _line_length\r
- try:\r
- _line_length = int(val)\r
- except ValueError:\r
- PrintUsage('Line length must be digits.')\r
- elif opt == '--extensions':\r
- global _valid_extensions\r
- try:\r
- _valid_extensions = set(val.split(','))\r
- except ValueError:\r
- PrintUsage('Extensions must be comma seperated list.')\r
- elif opt == '--headers':\r
- ProcessHppHeadersOption(val)\r
-\r
- if not filenames:\r
- PrintUsage('No files were specified.')\r
-\r
- _SetOutputFormat(output_format)\r
- _SetVerboseLevel(verbosity)\r
- _SetFilters(filters)\r
- _SetCountingStyle(counting_style)\r
-\r
- return filenames\r
-\r
-\r
-def main():\r
- filenames = ParseArguments(sys.argv[1:])\r
-\r
- # Change stderr to write with replacement characters so we don't die\r
- # if we try to print something containing non-ASCII characters.\r
- sys.stderr = codecs.StreamReaderWriter(sys.stderr,\r
- codecs.getreader('utf8'),\r
- codecs.getwriter('utf8'),\r
- 'replace')\r
-\r
- _cpplint_state.ResetErrorCounts()\r
- for filename in filenames:\r
- ProcessFile(filename, _cpplint_state.verbose_level)\r
- _cpplint_state.PrintErrorCounts()\r
-\r
- sys.exit(_cpplint_state.error_count > 0)\r
-\r
-\r
-if __name__ == '__main__':\r
- main()\r