[email protected] | d528f8b | 2012-05-11 17:31:08 | [diff] [blame] | 1 | #!/usr/bin/env python |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2 | # |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 3 | # Copyright (c) 2009 Google Inc. All rights reserved. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 4 | # |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 5 | # Redistribution and use in source and binary forms, with or without |
| 6 | # modification, are permitted provided that the following conditions are |
| 7 | # met: |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 8 | # |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 9 | # * Redistributions of source code must retain the above copyright |
| 10 | # notice, this list of conditions and the following disclaimer. |
| 11 | # * Redistributions in binary form must reproduce the above |
| 12 | # copyright notice, this list of conditions and the following disclaimer |
| 13 | # in the documentation and/or other materials provided with the |
| 14 | # distribution. |
| 15 | # * Neither the name of Google Inc. nor the names of its |
| 16 | # contributors may be used to endorse or promote products derived from |
| 17 | # this software without specific prior written permission. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 18 | # |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 19 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
| 20 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
| 21 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
| 22 | # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT |
| 23 | # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
| 24 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
| 25 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
| 26 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
| 27 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
| 28 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
| 29 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 30 | |
| 31 | # Here are some issues that I've had people identify in my code during reviews, |
| 32 | # that I think are possible to flag automatically in a lint tool. If these were |
| 33 | # caught by lint, it would save time both for myself and that of my reviewers. |
| 34 | # Most likely, some of these are beyond the scope of the current lint framework, |
| 35 | # but I think it is valuable to retain these wish-list items even if they cannot |
| 36 | # be immediately implemented. |
| 37 | # |
| 38 | # Suggestions |
| 39 | # ----------- |
| 40 | # - Check for no 'explicit' for multi-arg ctor |
| 41 | # - Check for boolean assign RHS in parens |
| 42 | # - Check for ctor initializer-list colon position and spacing |
| 43 | # - Check that if there's a ctor, there should be a dtor |
| 44 | # - Check accessors that return non-pointer member variables are |
| 45 | # declared const |
| 46 | # - Check accessors that return non-const pointer member vars are |
| 47 | # *not* declared const |
| 48 | # - Check for using public includes for testing |
| 49 | # - Check for spaces between brackets in one-line inline method |
| 50 | # - Check for no assert() |
| 51 | # - Check for spaces surrounding operators |
| 52 | # - Check for 0 in pointer context (should be NULL) |
| 53 | # - Check for 0 in char context (should be '\0') |
| 54 | # - Check for camel-case method name conventions for methods |
| 55 | # that are not simple inline getters and setters |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 56 | # - Do not indent namespace contents |
| 57 | # - Avoid inlining non-trivial constructors in header files |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 58 | # - Check for old-school (void) cast for call-sites of functions |
| 59 | # ignored return value |
| 60 | # - Check gUnit usage of anonymous namespace |
| 61 | # - Check for class declaration order (typedefs, consts, enums, |
| 62 | # ctor(s?), dtor, friend declarations, methods, member vars) |
| 63 | # |
| 64 | |
| 65 | """Does google-lint on c++ files. |
| 66 | |
| 67 | The goal of this script is to identify places in the code that *may* |
| 68 | be in non-compliance with google style. It does not attempt to fix |
| 69 | up these problems -- the point is to educate. It does also not |
| 70 | attempt to find all problems, or to ensure that everything it does |
| 71 | find is legitimately a problem. |
| 72 | |
| 73 | In particular, we can get very confused by /* and // inside strings! |
| 74 | We do a small hack, which is to ignore //'s with "'s after them on the |
| 75 | same line, but it is far from perfect (in either direction). |
| 76 | """ |
| 77 | |
| 78 | import codecs |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 79 | import copy |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 80 | import getopt |
| 81 | import math # for log |
| 82 | import os |
| 83 | import re |
| 84 | import sre_compile |
| 85 | import string |
| 86 | import sys |
| 87 | import unicodedata |
| 88 | |
| 89 | |
| 90 | _USAGE = """ |
| 91 | Syntax: cpplint.py [--verbose=#] [--output=vs7] [--filter=-x,+y,...] |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 92 | [--counting=total|toplevel|detailed] |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 93 | <file> [file] ... |
| 94 | |
| 95 | The style guidelines this tries to follow are those in |
| 96 | http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml |
| 97 | |
| 98 | Every problem is given a confidence score from 1-5, with 5 meaning we are |
| 99 | certain of the problem, and 1 meaning it could be a legitimate construct. |
| 100 | This will miss some errors, and is not a substitute for a code review. |
| 101 | |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 102 | To suppress false-positive errors of a certain category, add a |
| 103 | 'NOLINT(category)' comment to the line. NOLINT or NOLINT(*) |
| 104 | suppresses errors of all categories on that line. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 105 | |
| 106 | The files passed in will be linted; at least one file must be provided. |
| 107 | Linted extensions are .cc, .cpp, and .h. Other file types will be ignored. |
| 108 | |
| 109 | Flags: |
| 110 | |
| 111 | output=vs7 |
| 112 | By default, the output is formatted to ease emacs parsing. Visual Studio |
| 113 | compatible output (vs7) may also be used. Other formats are unsupported. |
| 114 | |
| 115 | verbose=# |
| 116 | Specify a number 0-5 to restrict errors to certain verbosity levels. |
| 117 | |
| 118 | filter=-x,+y,... |
| 119 | Specify a comma-separated list of category-filters to apply: only |
| 120 | error messages whose category names pass the filters will be printed. |
| 121 | (Category names are printed with the message and look like |
| 122 | "[whitespace/indent]".) Filters are evaluated left to right. |
| 123 | "-FOO" and "FOO" means "do not print categories that start with FOO". |
| 124 | "+FOO" means "do print categories that start with FOO". |
| 125 | |
| 126 | Examples: --filter=-whitespace,+whitespace/braces |
| 127 | --filter=whitespace,runtime/printf,+runtime/printf_format |
| 128 | --filter=-,+build/include_what_you_use |
| 129 | |
| 130 | To see a list of all the categories used in cpplint, pass no arg: |
| 131 | --filter= |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 132 | |
| 133 | counting=total|toplevel|detailed |
| 134 | The total number of errors found is always printed. If |
| 135 | 'toplevel' is provided, then the count of errors in each of |
| 136 | the top-level categories like 'build' and 'whitespace' will |
| 137 | also be printed. If 'detailed' is provided, then a count |
| 138 | is provided for each category like 'build/class'. |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 139 | |
| 140 | root=subdir |
| 141 | The root directory used for deriving header guard CPP variable. |
| 142 | By default, the header guard CPP variable is calculated as the relative |
| 143 | path to the directory that contains .git, .hg, or .svn. When this flag |
| 144 | is specified, the relative path is calculated from the specified |
| 145 | directory. If the specified directory does not exist, this flag is |
| 146 | ignored. |
| 147 | |
| 148 | Examples: |
| 149 | Assuing that src/.git exists, the header guard CPP variables for |
| 150 | src/chrome/browser/ui/browser.h are: |
| 151 | |
| 152 | No flag => CHROME_BROWSER_UI_BROWSER_H_ |
| 153 | --root=chrome => BROWSER_UI_BROWSER_H_ |
| 154 | --root=chrome/browser => UI_BROWSER_H_ |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 155 | """ |
| 156 | |
| 157 | # We categorize each error message we print. Here are the categories. |
| 158 | # We want an explicit list so we can list them all in cpplint --filter=. |
| 159 | # If you add a new error message with a new category, add it to the list |
| 160 | # here! cpplint_unittest.py should tell you if you forget to do this. |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 161 | # \ used for clearer layout -- pylint: disable-msg=C6013 |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 162 | _ERROR_CATEGORIES = [ |
| 163 | 'build/class', |
| 164 | 'build/deprecated', |
| 165 | 'build/endif_comment', |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 166 | 'build/explicit_make_pair', |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 167 | 'build/forward_decl', |
| 168 | 'build/header_guard', |
| 169 | 'build/include', |
| 170 | 'build/include_alpha', |
| 171 | 'build/include_order', |
| 172 | 'build/include_what_you_use', |
| 173 | 'build/namespaces', |
| 174 | 'build/printf_format', |
| 175 | 'build/storage_class', |
| 176 | 'legal/copyright', |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 177 | 'readability/alt_tokens', |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 178 | 'readability/braces', |
| 179 | 'readability/casting', |
| 180 | 'readability/check', |
| 181 | 'readability/constructors', |
| 182 | 'readability/fn_size', |
| 183 | 'readability/function', |
| 184 | 'readability/multiline_comment', |
| 185 | 'readability/multiline_string', |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 186 | 'readability/namespace', |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 187 | 'readability/nolint', |
| 188 | 'readability/streams', |
| 189 | 'readability/todo', |
| 190 | 'readability/utf8', |
| 191 | 'runtime/arrays', |
| 192 | 'runtime/casting', |
| 193 | 'runtime/explicit', |
| 194 | 'runtime/int', |
| 195 | 'runtime/init', |
| 196 | 'runtime/invalid_increment', |
| 197 | 'runtime/member_string_references', |
| 198 | 'runtime/memset', |
| 199 | 'runtime/operator', |
| 200 | 'runtime/printf', |
| 201 | 'runtime/printf_format', |
| 202 | 'runtime/references', |
| 203 | 'runtime/rtti', |
| 204 | 'runtime/sizeof', |
| 205 | 'runtime/string', |
| 206 | 'runtime/threadsafe_fn', |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 207 | 'whitespace/blank_line', |
| 208 | 'whitespace/braces', |
| 209 | 'whitespace/comma', |
| 210 | 'whitespace/comments', |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 211 | 'whitespace/empty_loop_body', |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 212 | 'whitespace/end_of_line', |
| 213 | 'whitespace/ending_newline', |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 214 | 'whitespace/forcolon', |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 215 | 'whitespace/indent', |
| 216 | 'whitespace/labels', |
| 217 | 'whitespace/line_length', |
| 218 | 'whitespace/newline', |
| 219 | 'whitespace/operators', |
| 220 | 'whitespace/parens', |
| 221 | 'whitespace/semicolon', |
| 222 | 'whitespace/tab', |
| 223 | 'whitespace/todo' |
| 224 | ] |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 225 | |
| 226 | # The default state of the category filter. This is overrided by the --filter= |
| 227 | # flag. By default all errors are on, so only add here categories that should be |
| 228 | # off by default (i.e., categories that must be enabled by the --filter= flags). |
| 229 | # All entries here should start with a '-' or '+', as in the --filter= flag. |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 230 | _DEFAULT_FILTERS = ['-build/include_alpha'] |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 231 | |
| 232 | # We used to check for high-bit characters, but after much discussion we |
| 233 | # decided those were OK, as long as they were in UTF-8 and didn't represent |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 234 | # hard-coded international strings, which belong in a separate i18n file. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 235 | |
| 236 | # Headers that we consider STL headers. |
| 237 | _STL_HEADERS = frozenset([ |
| 238 | 'algobase.h', 'algorithm', 'alloc.h', 'bitset', 'deque', 'exception', |
| 239 | 'function.h', 'functional', 'hash_map', 'hash_map.h', 'hash_set', |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 240 | 'hash_set.h', 'iterator', 'list', 'list.h', 'map', 'memory', 'new', |
| 241 | 'pair.h', 'pthread_alloc', 'queue', 'set', 'set.h', 'sstream', 'stack', |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 242 | 'stl_alloc.h', 'stl_relops.h', 'type_traits.h', |
| 243 | 'utility', 'vector', 'vector.h', |
| 244 | ]) |
| 245 | |
| 246 | |
| 247 | # Non-STL C++ system headers. |
| 248 | _CPP_HEADERS = frozenset([ |
| 249 | 'algo.h', 'builtinbuf.h', 'bvector.h', 'cassert', 'cctype', |
| 250 | 'cerrno', 'cfloat', 'ciso646', 'climits', 'clocale', 'cmath', |
| 251 | 'complex', 'complex.h', 'csetjmp', 'csignal', 'cstdarg', 'cstddef', |
| 252 | 'cstdio', 'cstdlib', 'cstring', 'ctime', 'cwchar', 'cwctype', |
| 253 | 'defalloc.h', 'deque.h', 'editbuf.h', 'exception', 'fstream', |
| 254 | 'fstream.h', 'hashtable.h', 'heap.h', 'indstream.h', 'iomanip', |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 255 | 'iomanip.h', 'ios', 'iosfwd', 'iostream', 'iostream.h', 'istream', |
| 256 | 'istream.h', 'iterator.h', 'limits', 'map.h', 'multimap.h', 'multiset.h', |
| 257 | 'numeric', 'ostream', 'ostream.h', 'parsestream.h', 'pfstream.h', |
| 258 | 'PlotFile.h', 'procbuf.h', 'pthread_alloc.h', 'rope', 'rope.h', |
| 259 | 'ropeimpl.h', 'SFile.h', 'slist', 'slist.h', 'stack.h', 'stdexcept', |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 260 | 'stdiostream.h', 'streambuf.h', 'stream.h', 'strfile.h', 'string', |
| 261 | 'strstream', 'strstream.h', 'tempbuf.h', 'tree.h', 'typeinfo', 'valarray', |
| 262 | ]) |
| 263 | |
| 264 | |
| 265 | # Assertion macros. These are defined in base/logging.h and |
| 266 | # testing/base/gunit.h. Note that the _M versions need to come first |
| 267 | # for substring matching to work. |
| 268 | _CHECK_MACROS = [ |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 269 | 'DCHECK', 'CHECK', |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 270 | 'EXPECT_TRUE_M', 'EXPECT_TRUE', |
| 271 | 'ASSERT_TRUE_M', 'ASSERT_TRUE', |
| 272 | 'EXPECT_FALSE_M', 'EXPECT_FALSE', |
| 273 | 'ASSERT_FALSE_M', 'ASSERT_FALSE', |
| 274 | ] |
| 275 | |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 276 | # Replacement macros for CHECK/DCHECK/EXPECT_TRUE/EXPECT_FALSE |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 277 | _CHECK_REPLACEMENT = dict([(m, {}) for m in _CHECK_MACROS]) |
| 278 | |
| 279 | for op, replacement in [('==', 'EQ'), ('!=', 'NE'), |
| 280 | ('>=', 'GE'), ('>', 'GT'), |
| 281 | ('<=', 'LE'), ('<', 'LT')]: |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 282 | _CHECK_REPLACEMENT['DCHECK'][op] = 'DCHECK_%s' % replacement |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 283 | _CHECK_REPLACEMENT['CHECK'][op] = 'CHECK_%s' % replacement |
| 284 | _CHECK_REPLACEMENT['EXPECT_TRUE'][op] = 'EXPECT_%s' % replacement |
| 285 | _CHECK_REPLACEMENT['ASSERT_TRUE'][op] = 'ASSERT_%s' % replacement |
| 286 | _CHECK_REPLACEMENT['EXPECT_TRUE_M'][op] = 'EXPECT_%s_M' % replacement |
| 287 | _CHECK_REPLACEMENT['ASSERT_TRUE_M'][op] = 'ASSERT_%s_M' % replacement |
| 288 | |
| 289 | for op, inv_replacement in [('==', 'NE'), ('!=', 'EQ'), |
| 290 | ('>=', 'LT'), ('>', 'LE'), |
| 291 | ('<=', 'GT'), ('<', 'GE')]: |
| 292 | _CHECK_REPLACEMENT['EXPECT_FALSE'][op] = 'EXPECT_%s' % inv_replacement |
| 293 | _CHECK_REPLACEMENT['ASSERT_FALSE'][op] = 'ASSERT_%s' % inv_replacement |
| 294 | _CHECK_REPLACEMENT['EXPECT_FALSE_M'][op] = 'EXPECT_%s_M' % inv_replacement |
| 295 | _CHECK_REPLACEMENT['ASSERT_FALSE_M'][op] = 'ASSERT_%s_M' % inv_replacement |
| 296 | |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 297 | # Alternative tokens and their replacements. For full list, see section 2.5 |
| 298 | # Alternative tokens [lex.digraph] in the C++ standard. |
| 299 | # |
| 300 | # Digraphs (such as '%:') are not included here since it's a mess to |
| 301 | # match those on a word boundary. |
| 302 | _ALT_TOKEN_REPLACEMENT = { |
| 303 | 'and': '&&', |
| 304 | 'bitor': '|', |
| 305 | 'or': '||', |
| 306 | 'xor': '^', |
| 307 | 'compl': '~', |
| 308 | 'bitand': '&', |
| 309 | 'and_eq': '&=', |
| 310 | 'or_eq': '|=', |
| 311 | 'xor_eq': '^=', |
| 312 | 'not': '!', |
| 313 | 'not_eq': '!=' |
| 314 | } |
| 315 | |
| 316 | # Compile regular expression that matches all the above keywords. The "[ =()]" |
| 317 | # bit is meant to avoid matching these keywords outside of boolean expressions. |
| 318 | # |
| 319 | # False positives include C-style multi-line comments (http://go/nsiut ) |
| 320 | # and multi-line strings (http://go/beujw ), but those have always been |
| 321 | # troublesome for cpplint. |
| 322 | _ALT_TOKEN_REPLACEMENT_PATTERN = re.compile( |
| 323 | r'[ =()](' + ('|'.join(_ALT_TOKEN_REPLACEMENT.keys())) + r')(?=[ (]|$)') |
| 324 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 325 | |
| 326 | # These constants define types of headers for use with |
| 327 | # _IncludeState.CheckNextIncludeOrder(). |
| 328 | _C_SYS_HEADER = 1 |
| 329 | _CPP_SYS_HEADER = 2 |
| 330 | _LIKELY_MY_HEADER = 3 |
| 331 | _POSSIBLE_MY_HEADER = 4 |
| 332 | _OTHER_HEADER = 5 |
| 333 | |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 334 | # These constants define the current inline assembly state |
| 335 | _NO_ASM = 0 # Outside of inline assembly block |
| 336 | _INSIDE_ASM = 1 # Inside inline assembly block |
| 337 | _END_ASM = 2 # Last line of inline assembly block |
| 338 | _BLOCK_ASM = 3 # The whole block is an inline assembly block |
| 339 | |
| 340 | # Match start of assembly blocks |
| 341 | _MATCH_ASM = re.compile(r'^\s*(?:asm|_asm|__asm|__asm__)' |
| 342 | r'(?:\s+(volatile|__volatile__))?' |
| 343 | r'\s*[{(]') |
| 344 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 345 | |
| 346 | _regexp_compile_cache = {} |
| 347 | |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 348 | # Finds occurrences of NOLINT or NOLINT(...). |
| 349 | _RE_SUPPRESSION = re.compile(r'\bNOLINT\b(\([^)]*\))?') |
| 350 | |
| 351 | # {str, set(int)}: a map from error categories to sets of linenumbers |
| 352 | # on which those errors are expected and should be suppressed. |
| 353 | _error_suppressions = {} |
| 354 | |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 355 | # The root directory used for deriving header guard CPP variable. |
| 356 | # This is set by --root flag. |
| 357 | _root = None |
| 358 | |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 359 | def ParseNolintSuppressions(filename, raw_line, linenum, error): |
| 360 | """Updates the global list of error-suppressions. |
| 361 | |
| 362 | Parses any NOLINT comments on the current line, updating the global |
| 363 | error_suppressions store. Reports an error if the NOLINT comment |
| 364 | was malformed. |
| 365 | |
| 366 | Args: |
| 367 | filename: str, the name of the input file. |
| 368 | raw_line: str, the line of input text, with comments. |
| 369 | linenum: int, the number of the current line. |
| 370 | error: function, an error handler. |
| 371 | """ |
| 372 | # FIXME(adonovan): "NOLINT(" is misparsed as NOLINT(*). |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 373 | matched = _RE_SUPPRESSION.search(raw_line) |
| 374 | if matched: |
| 375 | category = matched.group(1) |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 376 | if category in (None, '(*)'): # => "suppress all" |
| 377 | _error_suppressions.setdefault(None, set()).add(linenum) |
| 378 | else: |
| 379 | if category.startswith('(') and category.endswith(')'): |
| 380 | category = category[1:-1] |
| 381 | if category in _ERROR_CATEGORIES: |
| 382 | _error_suppressions.setdefault(category, set()).add(linenum) |
| 383 | else: |
| 384 | error(filename, linenum, 'readability/nolint', 5, |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 385 | 'Unknown NOLINT error category: %s' % category) |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 386 | |
| 387 | |
| 388 | def ResetNolintSuppressions(): |
| 389 | "Resets the set of NOLINT suppressions to empty." |
| 390 | _error_suppressions.clear() |
| 391 | |
| 392 | |
| 393 | def IsErrorSuppressedByNolint(category, linenum): |
| 394 | """Returns true if the specified error category is suppressed on this line. |
| 395 | |
| 396 | Consults the global error_suppressions map populated by |
| 397 | ParseNolintSuppressions/ResetNolintSuppressions. |
| 398 | |
| 399 | Args: |
| 400 | category: str, the category of the error. |
| 401 | linenum: int, the current line number. |
| 402 | Returns: |
| 403 | bool, True iff the error should be suppressed due to a NOLINT comment. |
| 404 | """ |
| 405 | return (linenum in _error_suppressions.get(category, set()) or |
| 406 | linenum in _error_suppressions.get(None, set())) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 407 | |
| 408 | def Match(pattern, s): |
| 409 | """Matches the string with the pattern, caching the compiled regexp.""" |
| 410 | # The regexp compilation caching is inlined in both Match and Search for |
| 411 | # performance reasons; factoring it out into a separate function turns out |
| 412 | # to be noticeably expensive. |
| 413 | if not pattern in _regexp_compile_cache: |
| 414 | _regexp_compile_cache[pattern] = sre_compile.compile(pattern) |
| 415 | return _regexp_compile_cache[pattern].match(s) |
| 416 | |
| 417 | |
| 418 | def Search(pattern, s): |
| 419 | """Searches the string for the pattern, caching the compiled regexp.""" |
| 420 | if not pattern in _regexp_compile_cache: |
| 421 | _regexp_compile_cache[pattern] = sre_compile.compile(pattern) |
| 422 | return _regexp_compile_cache[pattern].search(s) |
| 423 | |
| 424 | |
| 425 | class _IncludeState(dict): |
| 426 | """Tracks line numbers for includes, and the order in which includes appear. |
| 427 | |
| 428 | As a dict, an _IncludeState object serves as a mapping between include |
| 429 | filename and line number on which that file was included. |
| 430 | |
| 431 | Call CheckNextIncludeOrder() once for each header in the file, passing |
| 432 | in the type constants defined above. Calls in an illegal order will |
| 433 | raise an _IncludeError with an appropriate error message. |
| 434 | |
| 435 | """ |
| 436 | # self._section will move monotonically through this set. If it ever |
| 437 | # needs to move backwards, CheckNextIncludeOrder will raise an error. |
| 438 | _INITIAL_SECTION = 0 |
| 439 | _MY_H_SECTION = 1 |
| 440 | _C_SECTION = 2 |
| 441 | _CPP_SECTION = 3 |
| 442 | _OTHER_H_SECTION = 4 |
| 443 | |
| 444 | _TYPE_NAMES = { |
| 445 | _C_SYS_HEADER: 'C system header', |
| 446 | _CPP_SYS_HEADER: 'C++ system header', |
| 447 | _LIKELY_MY_HEADER: 'header this file implements', |
| 448 | _POSSIBLE_MY_HEADER: 'header this file may implement', |
| 449 | _OTHER_HEADER: 'other header', |
| 450 | } |
| 451 | _SECTION_NAMES = { |
| 452 | _INITIAL_SECTION: "... nothing. (This can't be an error.)", |
| 453 | _MY_H_SECTION: 'a header this file implements', |
| 454 | _C_SECTION: 'C system header', |
| 455 | _CPP_SECTION: 'C++ system header', |
| 456 | _OTHER_H_SECTION: 'other header', |
| 457 | } |
| 458 | |
| 459 | def __init__(self): |
| 460 | dict.__init__(self) |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 461 | # The name of the current section. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 462 | self._section = self._INITIAL_SECTION |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 463 | # The path of last found header. |
| 464 | self._last_header = '' |
| 465 | |
| 466 | def CanonicalizeAlphabeticalOrder(self, header_path): |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 467 | """Returns a path canonicalized for alphabetical comparison. |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 468 | |
| 469 | - replaces "-" with "_" so they both cmp the same. |
| 470 | - removes '-inl' since we don't require them to be after the main header. |
| 471 | - lowercase everything, just in case. |
| 472 | |
| 473 | Args: |
| 474 | header_path: Path to be canonicalized. |
| 475 | |
| 476 | Returns: |
| 477 | Canonicalized path. |
| 478 | """ |
| 479 | return header_path.replace('-inl.h', '.h').replace('-', '_').lower() |
| 480 | |
| 481 | def IsInAlphabeticalOrder(self, header_path): |
| 482 | """Check if a header is in alphabetical order with the previous header. |
| 483 | |
| 484 | Args: |
| 485 | header_path: Header to be checked. |
| 486 | |
| 487 | Returns: |
| 488 | Returns true if the header is in alphabetical order. |
| 489 | """ |
| 490 | canonical_header = self.CanonicalizeAlphabeticalOrder(header_path) |
| 491 | if self._last_header > canonical_header: |
| 492 | return False |
| 493 | self._last_header = canonical_header |
| 494 | return True |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 495 | |
| 496 | def CheckNextIncludeOrder(self, header_type): |
| 497 | """Returns a non-empty error message if the next header is out of order. |
| 498 | |
| 499 | This function also updates the internal state to be ready to check |
| 500 | the next include. |
| 501 | |
| 502 | Args: |
| 503 | header_type: One of the _XXX_HEADER constants defined above. |
| 504 | |
| 505 | Returns: |
| 506 | The empty string if the header is in the right order, or an |
| 507 | error message describing what's wrong. |
| 508 | |
| 509 | """ |
| 510 | error_message = ('Found %s after %s' % |
| 511 | (self._TYPE_NAMES[header_type], |
| 512 | self._SECTION_NAMES[self._section])) |
| 513 | |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 514 | last_section = self._section |
| 515 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 516 | if header_type == _C_SYS_HEADER: |
| 517 | if self._section <= self._C_SECTION: |
| 518 | self._section = self._C_SECTION |
| 519 | else: |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 520 | self._last_header = '' |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 521 | return error_message |
| 522 | elif header_type == _CPP_SYS_HEADER: |
| 523 | if self._section <= self._CPP_SECTION: |
| 524 | self._section = self._CPP_SECTION |
| 525 | else: |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 526 | self._last_header = '' |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 527 | return error_message |
| 528 | elif header_type == _LIKELY_MY_HEADER: |
| 529 | if self._section <= self._MY_H_SECTION: |
| 530 | self._section = self._MY_H_SECTION |
| 531 | else: |
| 532 | self._section = self._OTHER_H_SECTION |
| 533 | elif header_type == _POSSIBLE_MY_HEADER: |
| 534 | if self._section <= self._MY_H_SECTION: |
| 535 | self._section = self._MY_H_SECTION |
| 536 | else: |
| 537 | # This will always be the fallback because we're not sure |
| 538 | # enough that the header is associated with this file. |
| 539 | self._section = self._OTHER_H_SECTION |
| 540 | else: |
| 541 | assert header_type == _OTHER_HEADER |
| 542 | self._section = self._OTHER_H_SECTION |
| 543 | |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 544 | if last_section != self._section: |
| 545 | self._last_header = '' |
| 546 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 547 | return '' |
| 548 | |
| 549 | |
| 550 | class _CppLintState(object): |
| 551 | """Maintains module-wide state..""" |
| 552 | |
| 553 | def __init__(self): |
| 554 | self.verbose_level = 1 # global setting. |
| 555 | self.error_count = 0 # global count of reported errors |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 556 | # filters to apply when emitting error messages |
| 557 | self.filters = _DEFAULT_FILTERS[:] |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 558 | self.counting = 'total' # In what way are we counting errors? |
| 559 | self.errors_by_category = {} # string to int dict storing error counts |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 560 | |
| 561 | # output format: |
| 562 | # "emacs" - format that emacs can parse (default) |
| 563 | # "vs7" - format that Microsoft Visual Studio 7 can parse |
| 564 | self.output_format = 'emacs' |
| 565 | |
| 566 | def SetOutputFormat(self, output_format): |
| 567 | """Sets the output format for errors.""" |
| 568 | self.output_format = output_format |
| 569 | |
| 570 | def SetVerboseLevel(self, level): |
| 571 | """Sets the module's verbosity, and returns the previous setting.""" |
| 572 | last_verbose_level = self.verbose_level |
| 573 | self.verbose_level = level |
| 574 | return last_verbose_level |
| 575 | |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 576 | def SetCountingStyle(self, counting_style): |
| 577 | """Sets the module's counting options.""" |
| 578 | self.counting = counting_style |
| 579 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 580 | def SetFilters(self, filters): |
| 581 | """Sets the error-message filters. |
| 582 | |
| 583 | These filters are applied when deciding whether to emit a given |
| 584 | error message. |
| 585 | |
| 586 | Args: |
| 587 | filters: A string of comma-separated filters (eg "+whitespace/indent"). |
| 588 | Each filter should start with + or -; else we die. |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 589 | |
| 590 | Raises: |
| 591 | ValueError: The comma-separated filters did not all start with '+' or '-'. |
| 592 | E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter" |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 593 | """ |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 594 | # Default filters always have less priority than the flag ones. |
| 595 | self.filters = _DEFAULT_FILTERS[:] |
| 596 | for filt in filters.split(','): |
| 597 | clean_filt = filt.strip() |
| 598 | if clean_filt: |
| 599 | self.filters.append(clean_filt) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 600 | for filt in self.filters: |
| 601 | if not (filt.startswith('+') or filt.startswith('-')): |
| 602 | raise ValueError('Every filter in --filters must start with + or -' |
| 603 | ' (%s does not)' % filt) |
| 604 | |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 605 | def ResetErrorCounts(self): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 606 | """Sets the module's error statistic back to zero.""" |
| 607 | self.error_count = 0 |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 608 | self.errors_by_category = {} |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 609 | |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 610 | def IncrementErrorCount(self, category): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 611 | """Bumps the module's error statistic.""" |
| 612 | self.error_count += 1 |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 613 | if self.counting in ('toplevel', 'detailed'): |
| 614 | if self.counting != 'detailed': |
| 615 | category = category.split('/')[0] |
| 616 | if category not in self.errors_by_category: |
| 617 | self.errors_by_category[category] = 0 |
| 618 | self.errors_by_category[category] += 1 |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 619 | |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 620 | def PrintErrorCounts(self): |
| 621 | """Print a summary of errors by category, and the total.""" |
| 622 | for category, count in self.errors_by_category.iteritems(): |
| 623 | sys.stderr.write('Category \'%s\' errors found: %d\n' % |
| 624 | (category, count)) |
| 625 | sys.stderr.write('Total errors found: %d\n' % self.error_count) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 626 | |
| 627 | _cpplint_state = _CppLintState() |
| 628 | |
| 629 | |
| 630 | def _OutputFormat(): |
| 631 | """Gets the module's output format.""" |
| 632 | return _cpplint_state.output_format |
| 633 | |
| 634 | |
| 635 | def _SetOutputFormat(output_format): |
| 636 | """Sets the module's output format.""" |
| 637 | _cpplint_state.SetOutputFormat(output_format) |
| 638 | |
| 639 | |
| 640 | def _VerboseLevel(): |
| 641 | """Returns the module's verbosity setting.""" |
| 642 | return _cpplint_state.verbose_level |
| 643 | |
| 644 | |
| 645 | def _SetVerboseLevel(level): |
| 646 | """Sets the module's verbosity, and returns the previous setting.""" |
| 647 | return _cpplint_state.SetVerboseLevel(level) |
| 648 | |
| 649 | |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 650 | def _SetCountingStyle(level): |
| 651 | """Sets the module's counting options.""" |
| 652 | _cpplint_state.SetCountingStyle(level) |
| 653 | |
| 654 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 655 | def _Filters(): |
| 656 | """Returns the module's list of output filters, as a list.""" |
| 657 | return _cpplint_state.filters |
| 658 | |
| 659 | |
| 660 | def _SetFilters(filters): |
| 661 | """Sets the module's error-message filters. |
| 662 | |
| 663 | These filters are applied when deciding whether to emit a given |
| 664 | error message. |
| 665 | |
| 666 | Args: |
| 667 | filters: A string of comma-separated filters (eg "whitespace/indent"). |
| 668 | Each filter should start with + or -; else we die. |
| 669 | """ |
| 670 | _cpplint_state.SetFilters(filters) |
| 671 | |
| 672 | |
| 673 | class _FunctionState(object): |
| 674 | """Tracks current function name and the number of lines in its body.""" |
| 675 | |
| 676 | _NORMAL_TRIGGER = 250 # for --v=0, 500 for --v=1, etc. |
| 677 | _TEST_TRIGGER = 400 # about 50% more than _NORMAL_TRIGGER. |
| 678 | |
| 679 | def __init__(self): |
| 680 | self.in_a_function = False |
| 681 | self.lines_in_function = 0 |
| 682 | self.current_function = '' |
| 683 | |
| 684 | def Begin(self, function_name): |
| 685 | """Start analyzing function body. |
| 686 | |
| 687 | Args: |
| 688 | function_name: The name of the function being tracked. |
| 689 | """ |
| 690 | self.in_a_function = True |
| 691 | self.lines_in_function = 0 |
| 692 | self.current_function = function_name |
| 693 | |
| 694 | def Count(self): |
| 695 | """Count line in current function body.""" |
| 696 | if self.in_a_function: |
| 697 | self.lines_in_function += 1 |
| 698 | |
| 699 | def Check(self, error, filename, linenum): |
| 700 | """Report if too many lines in function body. |
| 701 | |
| 702 | Args: |
| 703 | error: The function to call with any errors found. |
| 704 | filename: The name of the current file. |
| 705 | linenum: The number of the line to check. |
| 706 | """ |
| 707 | if Match(r'T(EST|est)', self.current_function): |
| 708 | base_trigger = self._TEST_TRIGGER |
| 709 | else: |
| 710 | base_trigger = self._NORMAL_TRIGGER |
| 711 | trigger = base_trigger * 2**_VerboseLevel() |
| 712 | |
| 713 | if self.lines_in_function > trigger: |
| 714 | error_level = int(math.log(self.lines_in_function / base_trigger, 2)) |
| 715 | # 50 => 0, 100 => 1, 200 => 2, 400 => 3, 800 => 4, 1600 => 5, ... |
| 716 | if error_level > 5: |
| 717 | error_level = 5 |
| 718 | error(filename, linenum, 'readability/fn_size', error_level, |
| 719 | 'Small and focused functions are preferred:' |
| 720 | ' %s has %d non-comment lines' |
| 721 | ' (error triggered by exceeding %d lines).' % ( |
| 722 | self.current_function, self.lines_in_function, trigger)) |
| 723 | |
| 724 | def End(self): |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 725 | """Stop analyzing function body.""" |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 726 | self.in_a_function = False |
| 727 | |
| 728 | |
| 729 | class _IncludeError(Exception): |
| 730 | """Indicates a problem with the include order in a file.""" |
| 731 | pass |
| 732 | |
| 733 | |
| 734 | class FileInfo: |
| 735 | """Provides utility functions for filenames. |
| 736 | |
| 737 | FileInfo provides easy access to the components of a file's path |
| 738 | relative to the project root. |
| 739 | """ |
| 740 | |
| 741 | def __init__(self, filename): |
| 742 | self._filename = filename |
| 743 | |
| 744 | def FullName(self): |
| 745 | """Make Windows paths like Unix.""" |
| 746 | return os.path.abspath(self._filename).replace('\\', '/') |
| 747 | |
| 748 | def RepositoryName(self): |
| 749 | """FullName after removing the local path to the repository. |
| 750 | |
| 751 | If we have a real absolute path name here we can try to do something smart: |
| 752 | detecting the root of the checkout and truncating /path/to/checkout from |
| 753 | the name so that we get header guards that don't include things like |
| 754 | "C:\Documents and Settings\..." or "/home/username/..." in them and thus |
| 755 | people on different computers who have checked the source out to different |
| 756 | locations won't see bogus errors. |
| 757 | """ |
| 758 | fullname = self.FullName() |
| 759 | |
| 760 | if os.path.exists(fullname): |
| 761 | project_dir = os.path.dirname(fullname) |
| 762 | |
| 763 | if os.path.exists(os.path.join(project_dir, ".svn")): |
| 764 | # If there's a .svn file in the current directory, we recursively look |
| 765 | # up the directory tree for the top of the SVN checkout |
| 766 | root_dir = project_dir |
| 767 | one_up_dir = os.path.dirname(root_dir) |
| 768 | while os.path.exists(os.path.join(one_up_dir, ".svn")): |
| 769 | root_dir = os.path.dirname(root_dir) |
| 770 | one_up_dir = os.path.dirname(one_up_dir) |
| 771 | |
| 772 | prefix = os.path.commonprefix([root_dir, project_dir]) |
| 773 | return fullname[len(prefix) + 1:] |
| 774 | |
[email protected] | 7956a87 | 2011-11-30 01:44:03 | [diff] [blame] | 775 | # Not SVN <= 1.6? Try to find a git, hg, or svn top level directory by |
| 776 | # searching up from the current path. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 777 | root_dir = os.path.dirname(fullname) |
| 778 | while (root_dir != os.path.dirname(root_dir) and |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 779 | not os.path.exists(os.path.join(root_dir, ".git")) and |
[email protected] | 7956a87 | 2011-11-30 01:44:03 | [diff] [blame] | 780 | not os.path.exists(os.path.join(root_dir, ".hg")) and |
| 781 | not os.path.exists(os.path.join(root_dir, ".svn"))): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 782 | root_dir = os.path.dirname(root_dir) |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 783 | |
| 784 | if (os.path.exists(os.path.join(root_dir, ".git")) or |
[email protected] | 7956a87 | 2011-11-30 01:44:03 | [diff] [blame] | 785 | os.path.exists(os.path.join(root_dir, ".hg")) or |
| 786 | os.path.exists(os.path.join(root_dir, ".svn"))): |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 787 | prefix = os.path.commonprefix([root_dir, project_dir]) |
| 788 | return fullname[len(prefix) + 1:] |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 789 | |
| 790 | # Don't know what to do; header guard warnings may be wrong... |
| 791 | return fullname |
| 792 | |
| 793 | def Split(self): |
| 794 | """Splits the file into the directory, basename, and extension. |
| 795 | |
| 796 | For 'chrome/browser/browser.cc', Split() would |
| 797 | return ('chrome/browser', 'browser', '.cc') |
| 798 | |
| 799 | Returns: |
| 800 | A tuple of (directory, basename, extension). |
| 801 | """ |
| 802 | |
| 803 | googlename = self.RepositoryName() |
| 804 | project, rest = os.path.split(googlename) |
| 805 | return (project,) + os.path.splitext(rest) |
| 806 | |
| 807 | def BaseName(self): |
| 808 | """File base name - text after the final slash, before the final period.""" |
| 809 | return self.Split()[1] |
| 810 | |
| 811 | def Extension(self): |
| 812 | """File extension - text following the final period.""" |
| 813 | return self.Split()[2] |
| 814 | |
| 815 | def NoExtension(self): |
| 816 | """File has no source file extension.""" |
| 817 | return '/'.join(self.Split()[0:2]) |
| 818 | |
| 819 | def IsSource(self): |
| 820 | """File has a source file extension.""" |
| 821 | return self.Extension()[1:] in ('c', 'cc', 'cpp', 'cxx') |
| 822 | |
| 823 | |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 824 | def _ShouldPrintError(category, confidence, linenum): |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 825 | """If confidence >= verbose, category passes filter and is not suppressed.""" |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 826 | |
| 827 | # There are three ways we might decide not to print an error message: |
| 828 | # a "NOLINT(category)" comment appears in the source, |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 829 | # the verbosity level isn't high enough, or the filters filter it out. |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 830 | if IsErrorSuppressedByNolint(category, linenum): |
| 831 | return False |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 832 | if confidence < _cpplint_state.verbose_level: |
| 833 | return False |
| 834 | |
| 835 | is_filtered = False |
| 836 | for one_filter in _Filters(): |
| 837 | if one_filter.startswith('-'): |
| 838 | if category.startswith(one_filter[1:]): |
| 839 | is_filtered = True |
| 840 | elif one_filter.startswith('+'): |
| 841 | if category.startswith(one_filter[1:]): |
| 842 | is_filtered = False |
| 843 | else: |
| 844 | assert False # should have been checked for in SetFilter. |
| 845 | if is_filtered: |
| 846 | return False |
| 847 | |
| 848 | return True |
| 849 | |
| 850 | |
| 851 | def Error(filename, linenum, category, confidence, message): |
| 852 | """Logs the fact we've found a lint error. |
| 853 | |
| 854 | We log where the error was found, and also our confidence in the error, |
| 855 | that is, how certain we are this is a legitimate style regression, and |
| 856 | not a misidentification or a use that's sometimes justified. |
| 857 | |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 858 | False positives can be suppressed by the use of |
| 859 | "cpplint(category)" comments on the offending line. These are |
| 860 | parsed into _error_suppressions. |
| 861 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 862 | Args: |
| 863 | filename: The name of the file containing the error. |
| 864 | linenum: The number of the line containing the error. |
| 865 | category: A string used to describe the "category" this bug |
| 866 | falls under: "whitespace", say, or "runtime". Categories |
| 867 | may have a hierarchy separated by slashes: "whitespace/indent". |
| 868 | confidence: A number from 1-5 representing a confidence score for |
| 869 | the error, with 5 meaning that we are certain of the problem, |
| 870 | and 1 meaning that it could be a legitimate construct. |
| 871 | message: The error message. |
| 872 | """ |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 873 | if _ShouldPrintError(category, confidence, linenum): |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 874 | _cpplint_state.IncrementErrorCount(category) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 875 | if _cpplint_state.output_format == 'vs7': |
| 876 | sys.stderr.write('%s(%s): %s [%s] [%d]\n' % ( |
| 877 | filename, linenum, message, category, confidence)) |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 878 | elif _cpplint_state.output_format == 'eclipse': |
| 879 | sys.stderr.write('%s:%s: warning: %s [%s] [%d]\n' % ( |
| 880 | filename, linenum, message, category, confidence)) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 881 | else: |
| 882 | sys.stderr.write('%s:%s: %s [%s] [%d]\n' % ( |
| 883 | filename, linenum, message, category, confidence)) |
| 884 | |
| 885 | |
| 886 | # Matches standard C++ escape esequences per 2.13.2.3 of the C++ standard. |
| 887 | _RE_PATTERN_CLEANSE_LINE_ESCAPES = re.compile( |
| 888 | r'\\([abfnrtv?"\\\']|\d+|x[0-9a-fA-F]+)') |
| 889 | # Matches strings. Escape codes should already be removed by ESCAPES. |
| 890 | _RE_PATTERN_CLEANSE_LINE_DOUBLE_QUOTES = re.compile(r'"[^"]*"') |
| 891 | # Matches characters. Escape codes should already be removed by ESCAPES. |
| 892 | _RE_PATTERN_CLEANSE_LINE_SINGLE_QUOTES = re.compile(r"'.'") |
| 893 | # Matches multi-line C++ comments. |
| 894 | # This RE is a little bit more complicated than one might expect, because we |
| 895 | # have to take care of space removals tools so we can handle comments inside |
| 896 | # statements better. |
| 897 | # The current rule is: We only clear spaces from both sides when we're at the |
| 898 | # end of the line. Otherwise, we try to remove spaces from the right side, |
| 899 | # if this doesn't work we try on left side but only if there's a non-character |
| 900 | # on the right. |
| 901 | _RE_PATTERN_CLEANSE_LINE_C_COMMENTS = re.compile( |
| 902 | r"""(\s*/\*.*\*/\s*$| |
| 903 | /\*.*\*/\s+| |
| 904 | \s+/\*.*\*/(?=\W)| |
| 905 | /\*.*\*/)""", re.VERBOSE) |
| 906 | |
| 907 | |
| 908 | def IsCppString(line): |
| 909 | """Does line terminate so, that the next symbol is in string constant. |
| 910 | |
| 911 | This function does not consider single-line nor multi-line comments. |
| 912 | |
| 913 | Args: |
| 914 | line: is a partial line of code starting from the 0..n. |
| 915 | |
| 916 | Returns: |
| 917 | True, if next character appended to 'line' is inside a |
| 918 | string constant. |
| 919 | """ |
| 920 | |
| 921 | line = line.replace(r'\\', 'XX') # after this, \\" does not match to \" |
| 922 | return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1 |
| 923 | |
| 924 | |
| 925 | def FindNextMultiLineCommentStart(lines, lineix): |
| 926 | """Find the beginning marker for a multiline comment.""" |
| 927 | while lineix < len(lines): |
| 928 | if lines[lineix].strip().startswith('/*'): |
| 929 | # Only return this marker if the comment goes beyond this line |
| 930 | if lines[lineix].strip().find('*/', 2) < 0: |
| 931 | return lineix |
| 932 | lineix += 1 |
| 933 | return len(lines) |
| 934 | |
| 935 | |
| 936 | def FindNextMultiLineCommentEnd(lines, lineix): |
| 937 | """We are inside a comment, find the end marker.""" |
| 938 | while lineix < len(lines): |
| 939 | if lines[lineix].strip().endswith('*/'): |
| 940 | return lineix |
| 941 | lineix += 1 |
| 942 | return len(lines) |
| 943 | |
| 944 | |
| 945 | def RemoveMultiLineCommentsFromRange(lines, begin, end): |
| 946 | """Clears a range of lines for multi-line comments.""" |
| 947 | # Having // dummy comments makes the lines non-empty, so we will not get |
| 948 | # unnecessary blank line warnings later in the code. |
| 949 | for i in range(begin, end): |
| 950 | lines[i] = '// dummy' |
| 951 | |
| 952 | |
| 953 | def RemoveMultiLineComments(filename, lines, error): |
| 954 | """Removes multiline (c-style) comments from lines.""" |
| 955 | lineix = 0 |
| 956 | while lineix < len(lines): |
| 957 | lineix_begin = FindNextMultiLineCommentStart(lines, lineix) |
| 958 | if lineix_begin >= len(lines): |
| 959 | return |
| 960 | lineix_end = FindNextMultiLineCommentEnd(lines, lineix_begin) |
| 961 | if lineix_end >= len(lines): |
| 962 | error(filename, lineix_begin + 1, 'readability/multiline_comment', 5, |
| 963 | 'Could not find end of multi-line comment') |
| 964 | return |
| 965 | RemoveMultiLineCommentsFromRange(lines, lineix_begin, lineix_end + 1) |
| 966 | lineix = lineix_end + 1 |
| 967 | |
| 968 | |
| 969 | def CleanseComments(line): |
| 970 | """Removes //-comments and single-line C-style /* */ comments. |
| 971 | |
| 972 | Args: |
| 973 | line: A line of C++ source. |
| 974 | |
| 975 | Returns: |
| 976 | The line with single-line comments removed. |
| 977 | """ |
| 978 | commentpos = line.find('//') |
| 979 | if commentpos != -1 and not IsCppString(line[:commentpos]): |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 980 | line = line[:commentpos].rstrip() |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 981 | # get rid of /* ... */ |
| 982 | return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line) |
| 983 | |
| 984 | |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 985 | class CleansedLines(object): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 986 | """Holds 3 copies of all lines with different preprocessing applied to them. |
| 987 | |
| 988 | 1) elided member contains lines without strings and comments, |
| 989 | 2) lines member contains lines without comments, and |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 990 | 3) raw_lines member contains all the lines without processing. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 991 | All these three members are of <type 'list'>, and of the same length. |
| 992 | """ |
| 993 | |
| 994 | def __init__(self, lines): |
| 995 | self.elided = [] |
| 996 | self.lines = [] |
| 997 | self.raw_lines = lines |
| 998 | self.num_lines = len(lines) |
| 999 | for linenum in range(len(lines)): |
| 1000 | self.lines.append(CleanseComments(lines[linenum])) |
| 1001 | elided = self._CollapseStrings(lines[linenum]) |
| 1002 | self.elided.append(CleanseComments(elided)) |
| 1003 | |
| 1004 | def NumLines(self): |
| 1005 | """Returns the number of lines represented.""" |
| 1006 | return self.num_lines |
| 1007 | |
| 1008 | @staticmethod |
| 1009 | def _CollapseStrings(elided): |
| 1010 | """Collapses strings and chars on a line to simple "" or '' blocks. |
| 1011 | |
| 1012 | We nix strings first so we're not fooled by text like '"http://"' |
| 1013 | |
| 1014 | Args: |
| 1015 | elided: The line being processed. |
| 1016 | |
| 1017 | Returns: |
| 1018 | The line with collapsed strings. |
| 1019 | """ |
| 1020 | if not _RE_PATTERN_INCLUDE.match(elided): |
| 1021 | # Remove escaped characters first to make quote/single quote collapsing |
| 1022 | # basic. Things that look like escaped characters shouldn't occur |
| 1023 | # outside of strings and chars. |
| 1024 | elided = _RE_PATTERN_CLEANSE_LINE_ESCAPES.sub('', elided) |
| 1025 | elided = _RE_PATTERN_CLEANSE_LINE_SINGLE_QUOTES.sub("''", elided) |
| 1026 | elided = _RE_PATTERN_CLEANSE_LINE_DOUBLE_QUOTES.sub('""', elided) |
| 1027 | return elided |
| 1028 | |
| 1029 | |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 1030 | def FindEndOfExpressionInLine(line, startpos, depth, startchar, endchar): |
| 1031 | """Find the position just after the matching endchar. |
| 1032 | |
| 1033 | Args: |
| 1034 | line: a CleansedLines line. |
| 1035 | startpos: start searching at this position. |
| 1036 | depth: nesting level at startpos. |
| 1037 | startchar: expression opening character. |
| 1038 | endchar: expression closing character. |
| 1039 | |
| 1040 | Returns: |
| 1041 | Index just after endchar. |
| 1042 | """ |
| 1043 | for i in xrange(startpos, len(line)): |
| 1044 | if line[i] == startchar: |
| 1045 | depth += 1 |
| 1046 | elif line[i] == endchar: |
| 1047 | depth -= 1 |
| 1048 | if depth == 0: |
| 1049 | return i + 1 |
| 1050 | return -1 |
| 1051 | |
| 1052 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1053 | def CloseExpression(clean_lines, linenum, pos): |
| 1054 | """If input points to ( or { or [, finds the position that closes it. |
| 1055 | |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 1056 | If lines[linenum][pos] points to a '(' or '{' or '[', finds the |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1057 | linenum/pos that correspond to the closing of the expression. |
| 1058 | |
| 1059 | Args: |
| 1060 | clean_lines: A CleansedLines instance containing the file. |
| 1061 | linenum: The number of the line to check. |
| 1062 | pos: A position on the line. |
| 1063 | |
| 1064 | Returns: |
| 1065 | A tuple (line, linenum, pos) pointer *past* the closing brace, or |
| 1066 | (line, len(lines), -1) if we never find a close. Note we ignore |
| 1067 | strings and comments when matching; and the line we return is the |
| 1068 | 'cleansed' line at linenum. |
| 1069 | """ |
| 1070 | |
| 1071 | line = clean_lines.elided[linenum] |
| 1072 | startchar = line[pos] |
| 1073 | if startchar not in '({[': |
| 1074 | return (line, clean_lines.NumLines(), -1) |
| 1075 | if startchar == '(': endchar = ')' |
| 1076 | if startchar == '[': endchar = ']' |
| 1077 | if startchar == '{': endchar = '}' |
| 1078 | |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 1079 | # Check first line |
| 1080 | end_pos = FindEndOfExpressionInLine(line, pos, 0, startchar, endchar) |
| 1081 | if end_pos > -1: |
| 1082 | return (line, linenum, end_pos) |
| 1083 | tail = line[pos:] |
| 1084 | num_open = tail.count(startchar) - tail.count(endchar) |
| 1085 | while linenum < clean_lines.NumLines() - 1: |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1086 | linenum += 1 |
| 1087 | line = clean_lines.elided[linenum] |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 1088 | delta = line.count(startchar) - line.count(endchar) |
| 1089 | if num_open + delta <= 0: |
| 1090 | return (line, linenum, |
| 1091 | FindEndOfExpressionInLine(line, 0, num_open, startchar, endchar)) |
| 1092 | num_open += delta |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1093 | |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 1094 | # Did not find endchar before end of file, give up |
| 1095 | return (line, clean_lines.NumLines(), -1) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1096 | |
| 1097 | def CheckForCopyright(filename, lines, error): |
| 1098 | """Logs an error if no Copyright message appears at the top of the file.""" |
| 1099 | |
| 1100 | # We'll say it should occur by line 10. Don't forget there's a |
| 1101 | # dummy line at the front. |
| 1102 | for line in xrange(1, min(len(lines), 11)): |
| 1103 | if re.search(r'Copyright', lines[line], re.I): break |
| 1104 | else: # means no copyright line was found |
| 1105 | error(filename, 0, 'legal/copyright', 5, |
| 1106 | 'No copyright message found. ' |
| 1107 | 'You should have a line: "Copyright [year] <Copyright Owner>"') |
| 1108 | |
| 1109 | |
| 1110 | def GetHeaderGuardCPPVariable(filename): |
| 1111 | """Returns the CPP variable that should be used as a header guard. |
| 1112 | |
| 1113 | Args: |
| 1114 | filename: The name of a C++ header file. |
| 1115 | |
| 1116 | Returns: |
| 1117 | The CPP variable that should be used as a header guard in the |
| 1118 | named file. |
| 1119 | |
| 1120 | """ |
| 1121 | |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 1122 | # Restores original filename in case that cpplint is invoked from Emacs's |
| 1123 | # flymake. |
| 1124 | filename = re.sub(r'_flymake\.h$', '.h', filename) |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 1125 | filename = re.sub(r'/\.flymake/([^/]*)$', r'/\1', filename) |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 1126 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1127 | fileinfo = FileInfo(filename) |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 1128 | file_path_from_root = fileinfo.RepositoryName() |
| 1129 | if _root: |
| 1130 | file_path_from_root = re.sub('^' + _root + os.sep, '', file_path_from_root) |
| 1131 | return re.sub(r'[-./\s]', '_', file_path_from_root).upper() + '_' |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1132 | |
| 1133 | |
| 1134 | def CheckForHeaderGuard(filename, lines, error): |
| 1135 | """Checks that the file contains a header guard. |
| 1136 | |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 1137 | Logs an error if no #ifndef header guard is present. For other |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1138 | headers, checks that the full pathname is used. |
| 1139 | |
| 1140 | Args: |
| 1141 | filename: The name of the C++ header file. |
| 1142 | lines: An array of strings, each representing a line of the file. |
| 1143 | error: The function to call with any errors found. |
| 1144 | """ |
| 1145 | |
| 1146 | cppvar = GetHeaderGuardCPPVariable(filename) |
| 1147 | |
| 1148 | ifndef = None |
| 1149 | ifndef_linenum = 0 |
| 1150 | define = None |
| 1151 | endif = None |
| 1152 | endif_linenum = 0 |
| 1153 | for linenum, line in enumerate(lines): |
| 1154 | linesplit = line.split() |
| 1155 | if len(linesplit) >= 2: |
| 1156 | # find the first occurrence of #ifndef and #define, save arg |
| 1157 | if not ifndef and linesplit[0] == '#ifndef': |
| 1158 | # set ifndef to the header guard presented on the #ifndef line. |
| 1159 | ifndef = linesplit[1] |
| 1160 | ifndef_linenum = linenum |
| 1161 | if not define and linesplit[0] == '#define': |
| 1162 | define = linesplit[1] |
| 1163 | # find the last occurrence of #endif, save entire line |
| 1164 | if line.startswith('#endif'): |
| 1165 | endif = line |
| 1166 | endif_linenum = linenum |
| 1167 | |
[email protected] | c452fea | 2012-01-26 21:10:45 | [diff] [blame] | 1168 | if not ifndef: |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1169 | error(filename, 0, 'build/header_guard', 5, |
| 1170 | 'No #ifndef header guard found, suggested CPP variable is: %s' % |
| 1171 | cppvar) |
| 1172 | return |
| 1173 | |
[email protected] | c452fea | 2012-01-26 21:10:45 | [diff] [blame] | 1174 | if not define: |
| 1175 | error(filename, 0, 'build/header_guard', 5, |
| 1176 | 'No #define header guard found, suggested CPP variable is: %s' % |
| 1177 | cppvar) |
| 1178 | return |
| 1179 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1180 | # The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__ |
| 1181 | # for backward compatibility. |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 1182 | if ifndef != cppvar: |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1183 | error_level = 0 |
| 1184 | if ifndef != cppvar + '_': |
| 1185 | error_level = 5 |
| 1186 | |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 1187 | ParseNolintSuppressions(filename, lines[ifndef_linenum], ifndef_linenum, |
| 1188 | error) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1189 | error(filename, ifndef_linenum, 'build/header_guard', error_level, |
| 1190 | '#ifndef header guard has wrong style, please use: %s' % cppvar) |
| 1191 | |
[email protected] | c452fea | 2012-01-26 21:10:45 | [diff] [blame] | 1192 | if define != ifndef: |
| 1193 | error(filename, 0, 'build/header_guard', 5, |
| 1194 | '#ifndef and #define don\'t match, suggested CPP variable is: %s' % |
| 1195 | cppvar) |
| 1196 | return |
| 1197 | |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 1198 | if endif != ('#endif // %s' % cppvar): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1199 | error_level = 0 |
| 1200 | if endif != ('#endif // %s' % (cppvar + '_')): |
| 1201 | error_level = 5 |
| 1202 | |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 1203 | ParseNolintSuppressions(filename, lines[endif_linenum], endif_linenum, |
| 1204 | error) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1205 | error(filename, endif_linenum, 'build/header_guard', error_level, |
| 1206 | '#endif line should be "#endif // %s"' % cppvar) |
| 1207 | |
| 1208 | |
| 1209 | def CheckForUnicodeReplacementCharacters(filename, lines, error): |
| 1210 | """Logs an error for each line containing Unicode replacement characters. |
| 1211 | |
| 1212 | These indicate that either the file contained invalid UTF-8 (likely) |
| 1213 | or Unicode replacement characters (which it shouldn't). Note that |
| 1214 | it's possible for this to throw off line numbering if the invalid |
| 1215 | UTF-8 occurred adjacent to a newline. |
| 1216 | |
| 1217 | Args: |
| 1218 | filename: The name of the current file. |
| 1219 | lines: An array of strings, each representing a line of the file. |
| 1220 | error: The function to call with any errors found. |
| 1221 | """ |
| 1222 | for linenum, line in enumerate(lines): |
| 1223 | if u'\ufffd' in line: |
| 1224 | error(filename, linenum, 'readability/utf8', 5, |
| 1225 | 'Line contains invalid UTF-8 (or Unicode replacement character).') |
| 1226 | |
| 1227 | |
| 1228 | def CheckForNewlineAtEOF(filename, lines, error): |
| 1229 | """Logs an error if there is no newline char at the end of the file. |
| 1230 | |
| 1231 | Args: |
| 1232 | filename: The name of the current file. |
| 1233 | lines: An array of strings, each representing a line of the file. |
| 1234 | error: The function to call with any errors found. |
| 1235 | """ |
| 1236 | |
| 1237 | # The array lines() was created by adding two newlines to the |
| 1238 | # original file (go figure), then splitting on \n. |
| 1239 | # To verify that the file ends in \n, we just have to make sure the |
| 1240 | # last-but-two element of lines() exists and is empty. |
| 1241 | if len(lines) < 3 or lines[-2]: |
| 1242 | error(filename, len(lines) - 2, 'whitespace/ending_newline', 5, |
| 1243 | 'Could not find a newline character at the end of the file.') |
| 1244 | |
| 1245 | |
| 1246 | def CheckForMultilineCommentsAndStrings(filename, clean_lines, linenum, error): |
| 1247 | """Logs an error if we see /* ... */ or "..." that extend past one line. |
| 1248 | |
| 1249 | /* ... */ comments are legit inside macros, for one line. |
| 1250 | Otherwise, we prefer // comments, so it's ok to warn about the |
| 1251 | other. Likewise, it's ok for strings to extend across multiple |
| 1252 | lines, as long as a line continuation character (backslash) |
| 1253 | terminates each line. Although not currently prohibited by the C++ |
| 1254 | style guide, it's ugly and unnecessary. We don't do well with either |
| 1255 | in this lint program, so we warn about both. |
| 1256 | |
| 1257 | Args: |
| 1258 | filename: The name of the current file. |
| 1259 | clean_lines: A CleansedLines instance containing the file. |
| 1260 | linenum: The number of the line to check. |
| 1261 | error: The function to call with any errors found. |
| 1262 | """ |
| 1263 | line = clean_lines.elided[linenum] |
| 1264 | |
| 1265 | # Remove all \\ (escaped backslashes) from the line. They are OK, and the |
| 1266 | # second (escaped) slash may trigger later \" detection erroneously. |
| 1267 | line = line.replace('\\\\', '') |
| 1268 | |
| 1269 | if line.count('/*') > line.count('*/'): |
| 1270 | error(filename, linenum, 'readability/multiline_comment', 5, |
| 1271 | 'Complex multi-line /*...*/-style comment found. ' |
| 1272 | 'Lint may give bogus warnings. ' |
| 1273 | 'Consider replacing these with //-style comments, ' |
| 1274 | 'with #if 0...#endif, ' |
| 1275 | 'or with more clearly structured multi-line comments.') |
| 1276 | |
| 1277 | if (line.count('"') - line.count('\\"')) % 2: |
| 1278 | error(filename, linenum, 'readability/multiline_string', 5, |
| 1279 | 'Multi-line string ("...") found. This lint script doesn\'t ' |
| 1280 | 'do well with such strings, and may give bogus warnings. They\'re ' |
| 1281 | 'ugly and unnecessary, and you should use concatenation instead".') |
| 1282 | |
| 1283 | |
| 1284 | threading_list = ( |
| 1285 | ('asctime(', 'asctime_r('), |
| 1286 | ('ctime(', 'ctime_r('), |
| 1287 | ('getgrgid(', 'getgrgid_r('), |
| 1288 | ('getgrnam(', 'getgrnam_r('), |
| 1289 | ('getlogin(', 'getlogin_r('), |
| 1290 | ('getpwnam(', 'getpwnam_r('), |
| 1291 | ('getpwuid(', 'getpwuid_r('), |
| 1292 | ('gmtime(', 'gmtime_r('), |
| 1293 | ('localtime(', 'localtime_r('), |
| 1294 | ('rand(', 'rand_r('), |
| 1295 | ('readdir(', 'readdir_r('), |
| 1296 | ('strtok(', 'strtok_r('), |
| 1297 | ('ttyname(', 'ttyname_r('), |
| 1298 | ) |
| 1299 | |
| 1300 | |
| 1301 | def CheckPosixThreading(filename, clean_lines, linenum, error): |
| 1302 | """Checks for calls to thread-unsafe functions. |
| 1303 | |
| 1304 | Much code has been originally written without consideration of |
| 1305 | multi-threading. Also, engineers are relying on their old experience; |
| 1306 | they have learned posix before threading extensions were added. These |
| 1307 | tests guide the engineers to use thread-safe functions (when using |
| 1308 | posix directly). |
| 1309 | |
| 1310 | Args: |
| 1311 | filename: The name of the current file. |
| 1312 | clean_lines: A CleansedLines instance containing the file. |
| 1313 | linenum: The number of the line to check. |
| 1314 | error: The function to call with any errors found. |
| 1315 | """ |
| 1316 | line = clean_lines.elided[linenum] |
| 1317 | for single_thread_function, multithread_safe_function in threading_list: |
| 1318 | ix = line.find(single_thread_function) |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 1319 | # Comparisons made explicit for clarity -- pylint: disable-msg=C6403 |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1320 | if ix >= 0 and (ix == 0 or (not line[ix - 1].isalnum() and |
| 1321 | line[ix - 1] not in ('_', '.', '>'))): |
| 1322 | error(filename, linenum, 'runtime/threadsafe_fn', 2, |
| 1323 | 'Consider using ' + multithread_safe_function + |
| 1324 | '...) instead of ' + single_thread_function + |
| 1325 | '...) for improved thread safety.') |
| 1326 | |
| 1327 | |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 1328 | # Matches invalid increment: *count++, which moves pointer instead of |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 1329 | # incrementing a value. |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 1330 | _RE_PATTERN_INVALID_INCREMENT = re.compile( |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 1331 | r'^\s*\*\w+(\+\+|--);') |
| 1332 | |
| 1333 | |
| 1334 | def CheckInvalidIncrement(filename, clean_lines, linenum, error): |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 1335 | """Checks for invalid increment *count++. |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 1336 | |
| 1337 | For example following function: |
| 1338 | void increment_counter(int* count) { |
| 1339 | *count++; |
| 1340 | } |
| 1341 | is invalid, because it effectively does count++, moving pointer, and should |
| 1342 | be replaced with ++*count, (*count)++ or *count += 1. |
| 1343 | |
| 1344 | Args: |
| 1345 | filename: The name of the current file. |
| 1346 | clean_lines: A CleansedLines instance containing the file. |
| 1347 | linenum: The number of the line to check. |
| 1348 | error: The function to call with any errors found. |
| 1349 | """ |
| 1350 | line = clean_lines.elided[linenum] |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 1351 | if _RE_PATTERN_INVALID_INCREMENT.match(line): |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 1352 | error(filename, linenum, 'runtime/invalid_increment', 5, |
| 1353 | 'Changing pointer instead of value (or unused value of operator*).') |
| 1354 | |
| 1355 | |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 1356 | class _BlockInfo(object): |
| 1357 | """Stores information about a generic block of code.""" |
| 1358 | |
| 1359 | def __init__(self, seen_open_brace): |
| 1360 | self.seen_open_brace = seen_open_brace |
| 1361 | self.open_parentheses = 0 |
| 1362 | self.inline_asm = _NO_ASM |
| 1363 | |
| 1364 | def CheckBegin(self, filename, clean_lines, linenum, error): |
| 1365 | """Run checks that applies to text up to the opening brace. |
| 1366 | |
| 1367 | This is mostly for checking the text after the class identifier |
| 1368 | and the "{", usually where the base class is specified. For other |
| 1369 | blocks, there isn't much to check, so we always pass. |
| 1370 | |
| 1371 | Args: |
| 1372 | filename: The name of the current file. |
| 1373 | clean_lines: A CleansedLines instance containing the file. |
| 1374 | linenum: The number of the line to check. |
| 1375 | error: The function to call with any errors found. |
| 1376 | """ |
| 1377 | pass |
| 1378 | |
| 1379 | def CheckEnd(self, filename, clean_lines, linenum, error): |
| 1380 | """Run checks that applies to text after the closing brace. |
| 1381 | |
| 1382 | This is mostly used for checking end of namespace comments. |
| 1383 | |
| 1384 | Args: |
| 1385 | filename: The name of the current file. |
| 1386 | clean_lines: A CleansedLines instance containing the file. |
| 1387 | linenum: The number of the line to check. |
| 1388 | error: The function to call with any errors found. |
| 1389 | """ |
| 1390 | pass |
| 1391 | |
| 1392 | |
| 1393 | class _ClassInfo(_BlockInfo): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1394 | """Stores information about a class.""" |
| 1395 | |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 1396 | def __init__(self, name, class_or_struct, clean_lines, linenum): |
| 1397 | _BlockInfo.__init__(self, False) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1398 | self.name = name |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 1399 | self.starting_linenum = linenum |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1400 | self.is_derived = False |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 1401 | if class_or_struct == 'struct': |
| 1402 | self.access = 'public' |
| 1403 | else: |
| 1404 | self.access = 'private' |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1405 | |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 1406 | # Try to find the end of the class. This will be confused by things like: |
| 1407 | # class A { |
| 1408 | # } *x = { ... |
| 1409 | # |
| 1410 | # But it's still good enough for CheckSectionSpacing. |
| 1411 | self.last_line = 0 |
| 1412 | depth = 0 |
| 1413 | for i in range(linenum, clean_lines.NumLines()): |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 1414 | line = clean_lines.elided[i] |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 1415 | depth += line.count('{') - line.count('}') |
| 1416 | if not depth: |
| 1417 | self.last_line = i |
| 1418 | break |
| 1419 | |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 1420 | def CheckBegin(self, filename, clean_lines, linenum, error): |
| 1421 | # Look for a bare ':' |
| 1422 | if Search('(^|[^:]):($|[^:])', clean_lines.elided[linenum]): |
| 1423 | self.is_derived = True |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1424 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1425 | |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 1426 | class _NamespaceInfo(_BlockInfo): |
| 1427 | """Stores information about a namespace.""" |
| 1428 | |
| 1429 | def __init__(self, name, linenum): |
| 1430 | _BlockInfo.__init__(self, False) |
| 1431 | self.name = name or '' |
| 1432 | self.starting_linenum = linenum |
| 1433 | |
| 1434 | def CheckEnd(self, filename, clean_lines, linenum, error): |
| 1435 | """Check end of namespace comments.""" |
| 1436 | line = clean_lines.raw_lines[linenum] |
| 1437 | |
| 1438 | # Check how many lines is enclosed in this namespace. Don't issue |
| 1439 | # warning for missing namespace comments if there aren't enough |
| 1440 | # lines. However, do apply checks if there is already an end of |
| 1441 | # namespace comment and it's incorrect. |
| 1442 | # |
| 1443 | # TODO(unknown): We always want to check end of namespace comments |
| 1444 | # if a namespace is large, but sometimes we also want to apply the |
| 1445 | # check if a short namespace contained nontrivial things (something |
| 1446 | # other than forward declarations). There is currently no logic on |
| 1447 | # deciding what these nontrivial things are, so this check is |
| 1448 | # triggered by namespace size only, which works most of the time. |
| 1449 | if (linenum - self.starting_linenum < 10 |
| 1450 | and not Match(r'};*\s*(//|/\*).*\bnamespace\b', line)): |
| 1451 | return |
| 1452 | |
| 1453 | # Look for matching comment at end of namespace. |
| 1454 | # |
| 1455 | # Note that we accept C style "/* */" comments for terminating |
| 1456 | # namespaces, so that code that terminate namespaces inside |
| 1457 | # preprocessor macros can be cpplint clean. Example: http://go/nxpiz |
| 1458 | # |
| 1459 | # We also accept stuff like "// end of namespace <name>." with the |
| 1460 | # period at the end. |
| 1461 | # |
| 1462 | # Besides these, we don't accept anything else, otherwise we might |
| 1463 | # get false negatives when existing comment is a substring of the |
| 1464 | # expected namespace. Example: http://go/ldkdc, http://cl/23548205 |
| 1465 | if self.name: |
| 1466 | # Named namespace |
| 1467 | if not Match((r'};*\s*(//|/\*).*\bnamespace\s+' + re.escape(self.name) + |
| 1468 | r'[\*/\.\\\s]*$'), |
| 1469 | line): |
| 1470 | error(filename, linenum, 'readability/namespace', 5, |
| 1471 | 'Namespace should be terminated with "// namespace %s"' % |
| 1472 | self.name) |
| 1473 | else: |
| 1474 | # Anonymous namespace |
| 1475 | if not Match(r'};*\s*(//|/\*).*\bnamespace[\*/\.\\\s]*$', line): |
| 1476 | error(filename, linenum, 'readability/namespace', 5, |
| 1477 | 'Namespace should be terminated with "// namespace"') |
| 1478 | |
| 1479 | |
| 1480 | class _PreprocessorInfo(object): |
| 1481 | """Stores checkpoints of nesting stacks when #if/#else is seen.""" |
| 1482 | |
| 1483 | def __init__(self, stack_before_if): |
| 1484 | # The entire nesting stack before #if |
| 1485 | self.stack_before_if = stack_before_if |
| 1486 | |
| 1487 | # The entire nesting stack up to #else |
| 1488 | self.stack_before_else = [] |
| 1489 | |
| 1490 | # Whether we have already seen #else or #elif |
| 1491 | self.seen_else = False |
| 1492 | |
| 1493 | |
| 1494 | class _NestingState(object): |
| 1495 | """Holds states related to parsing braces.""" |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1496 | |
| 1497 | def __init__(self): |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 1498 | # Stack for tracking all braces. An object is pushed whenever we |
| 1499 | # see a "{", and popped when we see a "}". Only 3 types of |
| 1500 | # objects are possible: |
| 1501 | # - _ClassInfo: a class or struct. |
| 1502 | # - _NamespaceInfo: a namespace. |
| 1503 | # - _BlockInfo: some other type of block. |
| 1504 | self.stack = [] |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1505 | |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 1506 | # Stack of _PreprocessorInfo objects. |
| 1507 | self.pp_stack = [] |
| 1508 | |
| 1509 | def SeenOpenBrace(self): |
| 1510 | """Check if we have seen the opening brace for the innermost block. |
| 1511 | |
| 1512 | Returns: |
| 1513 | True if we have seen the opening brace, False if the innermost |
| 1514 | block is still expecting an opening brace. |
| 1515 | """ |
| 1516 | return (not self.stack) or self.stack[-1].seen_open_brace |
| 1517 | |
| 1518 | def InNamespaceBody(self): |
| 1519 | """Check if we are currently one level inside a namespace body. |
| 1520 | |
| 1521 | Returns: |
| 1522 | True if top of the stack is a namespace block, False otherwise. |
| 1523 | """ |
| 1524 | return self.stack and isinstance(self.stack[-1], _NamespaceInfo) |
| 1525 | |
| 1526 | def UpdatePreprocessor(self, line): |
| 1527 | """Update preprocessor stack. |
| 1528 | |
| 1529 | We need to handle preprocessors due to classes like this: |
| 1530 | #ifdef SWIG |
| 1531 | struct ResultDetailsPageElementExtensionPoint { |
| 1532 | #else |
| 1533 | struct ResultDetailsPageElementExtensionPoint : public Extension { |
| 1534 | #endif |
| 1535 | (see http://go/qwddn for original example) |
| 1536 | |
| 1537 | We make the following assumptions (good enough for most files): |
| 1538 | - Preprocessor condition evaluates to true from #if up to first |
| 1539 | #else/#elif/#endif. |
| 1540 | |
| 1541 | - Preprocessor condition evaluates to false from #else/#elif up |
| 1542 | to #endif. We still perform lint checks on these lines, but |
| 1543 | these do not affect nesting stack. |
| 1544 | |
| 1545 | Args: |
| 1546 | line: current line to check. |
| 1547 | """ |
| 1548 | if Match(r'^\s*#\s*(if|ifdef|ifndef)\b', line): |
| 1549 | # Beginning of #if block, save the nesting stack here. The saved |
| 1550 | # stack will allow us to restore the parsing state in the #else case. |
| 1551 | self.pp_stack.append(_PreprocessorInfo(copy.deepcopy(self.stack))) |
| 1552 | elif Match(r'^\s*#\s*(else|elif)\b', line): |
| 1553 | # Beginning of #else block |
| 1554 | if self.pp_stack: |
| 1555 | if not self.pp_stack[-1].seen_else: |
| 1556 | # This is the first #else or #elif block. Remember the |
| 1557 | # whole nesting stack up to this point. This is what we |
| 1558 | # keep after the #endif. |
| 1559 | self.pp_stack[-1].seen_else = True |
| 1560 | self.pp_stack[-1].stack_before_else = copy.deepcopy(self.stack) |
| 1561 | |
| 1562 | # Restore the stack to how it was before the #if |
| 1563 | self.stack = copy.deepcopy(self.pp_stack[-1].stack_before_if) |
| 1564 | else: |
| 1565 | # TODO(unknown): unexpected #else, issue warning? |
| 1566 | pass |
| 1567 | elif Match(r'^\s*#\s*endif\b', line): |
| 1568 | # End of #if or #else blocks. |
| 1569 | if self.pp_stack: |
| 1570 | # If we saw an #else, we will need to restore the nesting |
| 1571 | # stack to its former state before the #else, otherwise we |
| 1572 | # will just continue from where we left off. |
| 1573 | if self.pp_stack[-1].seen_else: |
| 1574 | # Here we can just use a shallow copy since we are the last |
| 1575 | # reference to it. |
| 1576 | self.stack = self.pp_stack[-1].stack_before_else |
| 1577 | # Drop the corresponding #if |
| 1578 | self.pp_stack.pop() |
| 1579 | else: |
| 1580 | # TODO(unknown): unexpected #endif, issue warning? |
| 1581 | pass |
| 1582 | |
| 1583 | def Update(self, filename, clean_lines, linenum, error): |
| 1584 | """Update nesting state with current line. |
| 1585 | |
| 1586 | Args: |
| 1587 | filename: The name of the current file. |
| 1588 | clean_lines: A CleansedLines instance containing the file. |
| 1589 | linenum: The number of the line to check. |
| 1590 | error: The function to call with any errors found. |
| 1591 | """ |
| 1592 | line = clean_lines.elided[linenum] |
| 1593 | |
| 1594 | # Update pp_stack first |
| 1595 | self.UpdatePreprocessor(line) |
| 1596 | |
| 1597 | # Count parentheses. This is to avoid adding struct arguments to |
| 1598 | # the nesting stack. |
| 1599 | if self.stack: |
| 1600 | inner_block = self.stack[-1] |
| 1601 | depth_change = line.count('(') - line.count(')') |
| 1602 | inner_block.open_parentheses += depth_change |
| 1603 | |
| 1604 | # Also check if we are starting or ending an inline assembly block. |
| 1605 | if inner_block.inline_asm in (_NO_ASM, _END_ASM): |
| 1606 | if (depth_change != 0 and |
| 1607 | inner_block.open_parentheses == 1 and |
| 1608 | _MATCH_ASM.match(line)): |
| 1609 | # Enter assembly block |
| 1610 | inner_block.inline_asm = _INSIDE_ASM |
| 1611 | else: |
| 1612 | # Not entering assembly block. If previous line was _END_ASM, |
| 1613 | # we will now shift to _NO_ASM state. |
| 1614 | inner_block.inline_asm = _NO_ASM |
| 1615 | elif (inner_block.inline_asm == _INSIDE_ASM and |
| 1616 | inner_block.open_parentheses == 0): |
| 1617 | # Exit assembly block |
| 1618 | inner_block.inline_asm = _END_ASM |
| 1619 | |
| 1620 | # Consume namespace declaration at the beginning of the line. Do |
| 1621 | # this in a loop so that we catch same line declarations like this: |
| 1622 | # namespace proto2 { namespace bridge { class MessageSet; } } |
| 1623 | while True: |
| 1624 | # Match start of namespace. The "\b\s*" below catches namespace |
| 1625 | # declarations even if it weren't followed by a whitespace, this |
| 1626 | # is so that we don't confuse our namespace checker. The |
| 1627 | # missing spaces will be flagged by CheckSpacing. |
| 1628 | namespace_decl_match = Match(r'^\s*namespace\b\s*([:\w]+)?(.*)$', line) |
| 1629 | if not namespace_decl_match: |
| 1630 | break |
| 1631 | |
| 1632 | new_namespace = _NamespaceInfo(namespace_decl_match.group(1), linenum) |
| 1633 | self.stack.append(new_namespace) |
| 1634 | |
| 1635 | line = namespace_decl_match.group(2) |
| 1636 | if line.find('{') != -1: |
| 1637 | new_namespace.seen_open_brace = True |
| 1638 | line = line[line.find('{') + 1:] |
| 1639 | |
| 1640 | # Look for a class declaration in whatever is left of the line |
| 1641 | # after parsing namespaces. The regexp accounts for decorated classes |
| 1642 | # such as in: |
| 1643 | # class LOCKABLE API Object { |
| 1644 | # }; |
| 1645 | # |
| 1646 | # Templates with class arguments may confuse the parser, for example: |
| 1647 | # template <class T |
| 1648 | # class Comparator = less<T>, |
| 1649 | # class Vector = vector<T> > |
| 1650 | # class HeapQueue { |
| 1651 | # |
| 1652 | # Because this parser has no nesting state about templates, by the |
| 1653 | # time it saw "class Comparator", it may think that it's a new class. |
| 1654 | # Nested templates have a similar problem: |
| 1655 | # template < |
| 1656 | # typename ExportedType, |
| 1657 | # typename TupleType, |
| 1658 | # template <typename, typename> class ImplTemplate> |
| 1659 | # |
| 1660 | # To avoid these cases, we ignore classes that are followed by '=' or '>' |
| 1661 | class_decl_match = Match( |
| 1662 | r'\s*(template\s*<[\w\s<>,:]*>\s*)?' |
| 1663 | '(class|struct)\s+([A-Z_]+\s+)*(\w+(?:::\w+)*)' |
| 1664 | '(([^=>]|<[^<>]*>)*)$', line) |
| 1665 | if (class_decl_match and |
| 1666 | (not self.stack or self.stack[-1].open_parentheses == 0)): |
| 1667 | self.stack.append(_ClassInfo( |
| 1668 | class_decl_match.group(4), class_decl_match.group(2), |
| 1669 | clean_lines, linenum)) |
| 1670 | line = class_decl_match.group(5) |
| 1671 | |
| 1672 | # If we have not yet seen the opening brace for the innermost block, |
| 1673 | # run checks here. |
| 1674 | if not self.SeenOpenBrace(): |
| 1675 | self.stack[-1].CheckBegin(filename, clean_lines, linenum, error) |
| 1676 | |
| 1677 | # Update access control if we are inside a class/struct |
| 1678 | if self.stack and isinstance(self.stack[-1], _ClassInfo): |
| 1679 | access_match = Match(r'\s*(public|private|protected)\s*:', line) |
| 1680 | if access_match: |
| 1681 | self.stack[-1].access = access_match.group(1) |
| 1682 | |
| 1683 | # Consume braces or semicolons from what's left of the line |
| 1684 | while True: |
| 1685 | # Match first brace, semicolon, or closed parenthesis. |
| 1686 | matched = Match(r'^[^{;)}]*([{;)}])(.*)$', line) |
| 1687 | if not matched: |
| 1688 | break |
| 1689 | |
| 1690 | token = matched.group(1) |
| 1691 | if token == '{': |
| 1692 | # If namespace or class hasn't seen a opening brace yet, mark |
| 1693 | # namespace/class head as complete. Push a new block onto the |
| 1694 | # stack otherwise. |
| 1695 | if not self.SeenOpenBrace(): |
| 1696 | self.stack[-1].seen_open_brace = True |
| 1697 | else: |
| 1698 | self.stack.append(_BlockInfo(True)) |
| 1699 | if _MATCH_ASM.match(line): |
| 1700 | self.stack[-1].inline_asm = _BLOCK_ASM |
| 1701 | elif token == ';' or token == ')': |
| 1702 | # If we haven't seen an opening brace yet, but we already saw |
| 1703 | # a semicolon, this is probably a forward declaration. Pop |
| 1704 | # the stack for these. |
| 1705 | # |
| 1706 | # Similarly, if we haven't seen an opening brace yet, but we |
| 1707 | # already saw a closing parenthesis, then these are probably |
| 1708 | # function arguments with extra "class" or "struct" keywords. |
| 1709 | # Also pop these stack for these. |
| 1710 | if not self.SeenOpenBrace(): |
| 1711 | self.stack.pop() |
| 1712 | else: # token == '}' |
| 1713 | # Perform end of block checks and pop the stack. |
| 1714 | if self.stack: |
| 1715 | self.stack[-1].CheckEnd(filename, clean_lines, linenum, error) |
| 1716 | self.stack.pop() |
| 1717 | line = matched.group(2) |
| 1718 | |
| 1719 | def InnermostClass(self): |
| 1720 | """Get class info on the top of the stack. |
| 1721 | |
| 1722 | Returns: |
| 1723 | A _ClassInfo object if we are inside a class, or None otherwise. |
| 1724 | """ |
| 1725 | for i in range(len(self.stack), 0, -1): |
| 1726 | classinfo = self.stack[i - 1] |
| 1727 | if isinstance(classinfo, _ClassInfo): |
| 1728 | return classinfo |
| 1729 | return None |
| 1730 | |
| 1731 | def CheckClassFinished(self, filename, error): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1732 | """Checks that all classes have been completely parsed. |
| 1733 | |
| 1734 | Call this when all lines in a file have been processed. |
| 1735 | Args: |
| 1736 | filename: The name of the current file. |
| 1737 | error: The function to call with any errors found. |
| 1738 | """ |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 1739 | # Note: This test can result in false positives if #ifdef constructs |
| 1740 | # get in the way of brace matching. See the testBuildClass test in |
| 1741 | # cpplint_unittest.py for an example of this. |
| 1742 | for obj in self.stack: |
| 1743 | if isinstance(obj, _ClassInfo): |
| 1744 | error(filename, obj.starting_linenum, 'build/class', 5, |
| 1745 | 'Failed to find complete declaration of class %s' % |
| 1746 | obj.name) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1747 | |
| 1748 | |
| 1749 | def CheckForNonStandardConstructs(filename, clean_lines, linenum, |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 1750 | nesting_state, error): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1751 | """Logs an error if we see certain non-ANSI constructs ignored by gcc-2. |
| 1752 | |
| 1753 | Complain about several constructs which gcc-2 accepts, but which are |
| 1754 | not standard C++. Warning about these in lint is one way to ease the |
| 1755 | transition to new compilers. |
| 1756 | - put storage class first (e.g. "static const" instead of "const static"). |
| 1757 | - "%lld" instead of %qd" in printf-type functions. |
| 1758 | - "%1$d" is non-standard in printf-type functions. |
| 1759 | - "\%" is an undefined character escape sequence. |
| 1760 | - text after #endif is not allowed. |
| 1761 | - invalid inner-style forward declaration. |
| 1762 | - >? and <? operators, and their >?= and <?= cousins. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1763 | |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 1764 | Additionally, check for constructor/destructor style violations and reference |
| 1765 | members, as it is very convenient to do so while checking for |
| 1766 | gcc-2 compliance. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1767 | |
| 1768 | Args: |
| 1769 | filename: The name of the current file. |
| 1770 | clean_lines: A CleansedLines instance containing the file. |
| 1771 | linenum: The number of the line to check. |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 1772 | nesting_state: A _NestingState instance which maintains information about |
| 1773 | the current stack of nested blocks being parsed. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1774 | error: A callable to which errors are reported, which takes 4 arguments: |
| 1775 | filename, line number, error level, and message |
| 1776 | """ |
| 1777 | |
| 1778 | # Remove comments from the line, but leave in strings for now. |
| 1779 | line = clean_lines.lines[linenum] |
| 1780 | |
| 1781 | if Search(r'printf\s*\(.*".*%[-+ ]?\d*q', line): |
| 1782 | error(filename, linenum, 'runtime/printf_format', 3, |
| 1783 | '%q in format strings is deprecated. Use %ll instead.') |
| 1784 | |
| 1785 | if Search(r'printf\s*\(.*".*%\d+\$', line): |
| 1786 | error(filename, linenum, 'runtime/printf_format', 2, |
| 1787 | '%N$ formats are unconventional. Try rewriting to avoid them.') |
| 1788 | |
| 1789 | # Remove escaped backslashes before looking for undefined escapes. |
| 1790 | line = line.replace('\\\\', '') |
| 1791 | |
| 1792 | if Search(r'("|\').*\\(%|\[|\(|{)', line): |
| 1793 | error(filename, linenum, 'build/printf_format', 3, |
| 1794 | '%, [, (, and { are undefined character escapes. Unescape them.') |
| 1795 | |
| 1796 | # For the rest, work with both comments and strings removed. |
| 1797 | line = clean_lines.elided[linenum] |
| 1798 | |
| 1799 | if Search(r'\b(const|volatile|void|char|short|int|long' |
| 1800 | r'|float|double|signed|unsigned' |
| 1801 | r'|schar|u?int8|u?int16|u?int32|u?int64)' |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 1802 | r'\s+(register|static|extern|typedef)\b', |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1803 | line): |
| 1804 | error(filename, linenum, 'build/storage_class', 5, |
| 1805 | 'Storage class (static, extern, typedef, etc) should be first.') |
| 1806 | |
| 1807 | if Match(r'\s*#\s*endif\s*[^/\s]+', line): |
| 1808 | error(filename, linenum, 'build/endif_comment', 5, |
| 1809 | 'Uncommented text after #endif is non-standard. Use a comment.') |
| 1810 | |
| 1811 | if Match(r'\s*class\s+(\w+\s*::\s*)+\w+\s*;', line): |
| 1812 | error(filename, linenum, 'build/forward_decl', 5, |
| 1813 | 'Inner-style forward declarations are invalid. Remove this line.') |
| 1814 | |
| 1815 | if Search(r'(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?', |
| 1816 | line): |
| 1817 | error(filename, linenum, 'build/deprecated', 3, |
| 1818 | '>? and <? (max and min) operators are non-standard and deprecated.') |
| 1819 | |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 1820 | if Search(r'^\s*const\s*string\s*&\s*\w+\s*;', line): |
| 1821 | # TODO(unknown): Could it be expanded safely to arbitrary references, |
| 1822 | # without triggering too many false positives? The first |
| 1823 | # attempt triggered 5 warnings for mostly benign code in the regtest, hence |
| 1824 | # the restriction. |
| 1825 | # Here's the original regexp, for the reference: |
| 1826 | # type_name = r'\w+((\s*::\s*\w+)|(\s*<\s*\w+?\s*>))?' |
| 1827 | # r'\s*const\s*' + type_name + '\s*&\s*\w+\s*;' |
| 1828 | error(filename, linenum, 'runtime/member_string_references', 2, |
| 1829 | 'const string& members are dangerous. It is much better to use ' |
| 1830 | 'alternatives, such as pointers or simple constants.') |
| 1831 | |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 1832 | # Everything else in this function operates on class declarations. |
| 1833 | # Return early if the top of the nesting stack is not a class, or if |
| 1834 | # the class head is not completed yet. |
| 1835 | classinfo = nesting_state.InnermostClass() |
| 1836 | if not classinfo or not classinfo.seen_open_brace: |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1837 | return |
| 1838 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1839 | # The class may have been declared with namespace or classname qualifiers. |
| 1840 | # The constructor and destructor will not have those qualifiers. |
| 1841 | base_classname = classinfo.name.split('::')[-1] |
| 1842 | |
| 1843 | # Look for single-argument constructors that aren't marked explicit. |
| 1844 | # Technically a valid construct, but against style. |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 1845 | args = Match(r'\s+(?:inline\s+)?%s\s*\(([^,()]+)\)' |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1846 | % re.escape(base_classname), |
| 1847 | line) |
| 1848 | if (args and |
| 1849 | args.group(1) != 'void' and |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 1850 | not Match(r'(const\s+)?%s\s*(?:<\w+>\s*)?&' % re.escape(base_classname), |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1851 | args.group(1).strip())): |
| 1852 | error(filename, linenum, 'runtime/explicit', 5, |
| 1853 | 'Single-argument constructors should be marked explicit.') |
| 1854 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1855 | |
| 1856 | def CheckSpacingForFunctionCall(filename, line, linenum, error): |
| 1857 | """Checks for the correctness of various spacing around function calls. |
| 1858 | |
| 1859 | Args: |
| 1860 | filename: The name of the current file. |
| 1861 | line: The text of the line to check. |
| 1862 | linenum: The number of the line to check. |
| 1863 | error: The function to call with any errors found. |
| 1864 | """ |
| 1865 | |
| 1866 | # Since function calls often occur inside if/for/while/switch |
| 1867 | # expressions - which have their own, more liberal conventions - we |
| 1868 | # first see if we should be looking inside such an expression for a |
| 1869 | # function call, to which we can apply more strict standards. |
| 1870 | fncall = line # if there's no control flow construct, look at whole line |
| 1871 | for pattern in (r'\bif\s*\((.*)\)\s*{', |
| 1872 | r'\bfor\s*\((.*)\)\s*{', |
| 1873 | r'\bwhile\s*\((.*)\)\s*[{;]', |
| 1874 | r'\bswitch\s*\((.*)\)\s*{'): |
| 1875 | match = Search(pattern, line) |
| 1876 | if match: |
| 1877 | fncall = match.group(1) # look inside the parens for function calls |
| 1878 | break |
| 1879 | |
| 1880 | # Except in if/for/while/switch, there should never be space |
| 1881 | # immediately inside parens (eg "f( 3, 4 )"). We make an exception |
| 1882 | # for nested parens ( (a+b) + c ). Likewise, there should never be |
| 1883 | # a space before a ( when it's a function argument. I assume it's a |
| 1884 | # function argument when the char before the whitespace is legal in |
| 1885 | # a function name (alnum + _) and we're not starting a macro. Also ignore |
| 1886 | # pointers and references to arrays and functions coz they're too tricky: |
| 1887 | # we use a very simple way to recognize these: |
| 1888 | # " (something)(maybe-something)" or |
| 1889 | # " (something)(maybe-something," or |
| 1890 | # " (something)[something]" |
| 1891 | # Note that we assume the contents of [] to be short enough that |
| 1892 | # they'll never need to wrap. |
| 1893 | if ( # Ignore control structures. |
| 1894 | not Search(r'\b(if|for|while|switch|return|delete)\b', fncall) and |
| 1895 | # Ignore pointers/references to functions. |
| 1896 | not Search(r' \([^)]+\)\([^)]*(\)|,$)', fncall) and |
| 1897 | # Ignore pointers/references to arrays. |
| 1898 | not Search(r' \([^)]+\)\[[^\]]+\]', fncall)): |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 1899 | if Search(r'\w\s*\(\s(?!\s*\\$)', fncall): # a ( used for a fn call |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1900 | error(filename, linenum, 'whitespace/parens', 4, |
| 1901 | 'Extra space after ( in function call') |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 1902 | elif Search(r'\(\s+(?!(\s*\\)|\()', fncall): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1903 | error(filename, linenum, 'whitespace/parens', 2, |
| 1904 | 'Extra space after (') |
| 1905 | if (Search(r'\w\s+\(', fncall) and |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 1906 | not Search(r'#\s*define|typedef', fncall) and |
| 1907 | not Search(r'\w\s+\((\w+::)?\*\w+\)\(', fncall)): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1908 | error(filename, linenum, 'whitespace/parens', 4, |
| 1909 | 'Extra space before ( in function call') |
| 1910 | # If the ) is followed only by a newline or a { + newline, assume it's |
| 1911 | # part of a control statement (if/while/etc), and don't complain |
| 1912 | if Search(r'[^)]\s+\)\s*[^{\s]', fncall): |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 1913 | # If the closing parenthesis is preceded by only whitespaces, |
| 1914 | # try to give a more descriptive error message. |
| 1915 | if Search(r'^\s+\)', fncall): |
| 1916 | error(filename, linenum, 'whitespace/parens', 2, |
| 1917 | 'Closing ) should be moved to the previous line') |
| 1918 | else: |
| 1919 | error(filename, linenum, 'whitespace/parens', 2, |
| 1920 | 'Extra space before )') |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1921 | |
| 1922 | |
| 1923 | def IsBlankLine(line): |
| 1924 | """Returns true if the given line is blank. |
| 1925 | |
| 1926 | We consider a line to be blank if the line is empty or consists of |
| 1927 | only white spaces. |
| 1928 | |
| 1929 | Args: |
| 1930 | line: A line of a string. |
| 1931 | |
| 1932 | Returns: |
| 1933 | True, if the given line is blank. |
| 1934 | """ |
| 1935 | return not line or line.isspace() |
| 1936 | |
| 1937 | |
| 1938 | def CheckForFunctionLengths(filename, clean_lines, linenum, |
| 1939 | function_state, error): |
| 1940 | """Reports for long function bodies. |
| 1941 | |
| 1942 | For an overview why this is done, see: |
| 1943 | http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions |
| 1944 | |
| 1945 | Uses a simplistic algorithm assuming other style guidelines |
| 1946 | (especially spacing) are followed. |
| 1947 | Only checks unindented functions, so class members are unchecked. |
| 1948 | Trivial bodies are unchecked, so constructors with huge initializer lists |
| 1949 | may be missed. |
| 1950 | Blank/comment lines are not counted so as to avoid encouraging the removal |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 1951 | of vertical space and comments just to get through a lint check. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1952 | NOLINT *on the last line of a function* disables this check. |
| 1953 | |
| 1954 | Args: |
| 1955 | filename: The name of the current file. |
| 1956 | clean_lines: A CleansedLines instance containing the file. |
| 1957 | linenum: The number of the line to check. |
| 1958 | function_state: Current function name and lines in body so far. |
| 1959 | error: The function to call with any errors found. |
| 1960 | """ |
| 1961 | lines = clean_lines.lines |
| 1962 | line = lines[linenum] |
| 1963 | raw = clean_lines.raw_lines |
| 1964 | raw_line = raw[linenum] |
| 1965 | joined_line = '' |
| 1966 | |
| 1967 | starting_func = False |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 1968 | regexp = r'(\w(\w|::|\*|\&|\s)*)\(' # decls * & space::name( ... |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1969 | match_result = Match(regexp, line) |
| 1970 | if match_result: |
| 1971 | # If the name is all caps and underscores, figure it's a macro and |
| 1972 | # ignore it, unless it's TEST or TEST_F. |
| 1973 | function_name = match_result.group(1).split()[-1] |
| 1974 | if function_name == 'TEST' or function_name == 'TEST_F' or ( |
| 1975 | not Match(r'[A-Z_]+$', function_name)): |
| 1976 | starting_func = True |
| 1977 | |
| 1978 | if starting_func: |
| 1979 | body_found = False |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 1980 | for start_linenum in xrange(linenum, clean_lines.NumLines()): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1981 | start_line = lines[start_linenum] |
| 1982 | joined_line += ' ' + start_line.lstrip() |
| 1983 | if Search(r'(;|})', start_line): # Declarations and trivial functions |
| 1984 | body_found = True |
| 1985 | break # ... ignore |
| 1986 | elif Search(r'{', start_line): |
| 1987 | body_found = True |
| 1988 | function = Search(r'((\w|:)*)\(', line).group(1) |
| 1989 | if Match(r'TEST', function): # Handle TEST... macros |
| 1990 | parameter_regexp = Search(r'(\(.*\))', joined_line) |
| 1991 | if parameter_regexp: # Ignore bad syntax |
| 1992 | function += parameter_regexp.group(1) |
| 1993 | else: |
| 1994 | function += '()' |
| 1995 | function_state.Begin(function) |
| 1996 | break |
| 1997 | if not body_found: |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 1998 | # No body for the function (or evidence of a non-function) was found. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1999 | error(filename, linenum, 'readability/fn_size', 5, |
| 2000 | 'Lint failed to find start of function body.') |
| 2001 | elif Match(r'^\}\s*$', line): # function end |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 2002 | function_state.Check(error, filename, linenum) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2003 | function_state.End() |
| 2004 | elif not Match(r'^\s*$', line): |
| 2005 | function_state.Count() # Count non-blank/non-comment lines. |
| 2006 | |
| 2007 | |
| 2008 | _RE_PATTERN_TODO = re.compile(r'^//(\s*)TODO(\(.+?\))?:?(\s|$)?') |
| 2009 | |
| 2010 | |
| 2011 | def CheckComment(comment, filename, linenum, error): |
| 2012 | """Checks for common mistakes in TODO comments. |
| 2013 | |
| 2014 | Args: |
| 2015 | comment: The text of the comment from the line in question. |
| 2016 | filename: The name of the current file. |
| 2017 | linenum: The number of the line to check. |
| 2018 | error: The function to call with any errors found. |
| 2019 | """ |
| 2020 | match = _RE_PATTERN_TODO.match(comment) |
| 2021 | if match: |
| 2022 | # One whitespace is correct; zero whitespace is handled elsewhere. |
| 2023 | leading_whitespace = match.group(1) |
| 2024 | if len(leading_whitespace) > 1: |
| 2025 | error(filename, linenum, 'whitespace/todo', 2, |
| 2026 | 'Too many spaces before TODO') |
| 2027 | |
| 2028 | username = match.group(2) |
| 2029 | if not username: |
| 2030 | error(filename, linenum, 'readability/todo', 2, |
| 2031 | 'Missing username in TODO; it should look like ' |
| 2032 | '"// TODO(my_username): Stuff."') |
| 2033 | |
| 2034 | middle_whitespace = match.group(3) |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 2035 | # Comparisons made explicit for correctness -- pylint: disable-msg=C6403 |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2036 | if middle_whitespace != ' ' and middle_whitespace != '': |
| 2037 | error(filename, linenum, 'whitespace/todo', 2, |
| 2038 | 'TODO(my_username) should be followed by a space') |
| 2039 | |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2040 | def CheckAccess(filename, clean_lines, linenum, nesting_state, error): |
| 2041 | """Checks for improper use of DISALLOW* macros. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2042 | |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2043 | Args: |
| 2044 | filename: The name of the current file. |
| 2045 | clean_lines: A CleansedLines instance containing the file. |
| 2046 | linenum: The number of the line to check. |
| 2047 | nesting_state: A _NestingState instance which maintains information about |
| 2048 | the current stack of nested blocks being parsed. |
| 2049 | error: The function to call with any errors found. |
| 2050 | """ |
| 2051 | line = clean_lines.elided[linenum] # get rid of comments and strings |
| 2052 | |
| 2053 | matched = Match((r'\s*(DISALLOW_COPY_AND_ASSIGN|' |
| 2054 | r'DISALLOW_EVIL_CONSTRUCTORS|' |
| 2055 | r'DISALLOW_IMPLICIT_CONSTRUCTORS)'), line) |
| 2056 | if not matched: |
| 2057 | return |
| 2058 | if nesting_state.stack and isinstance(nesting_state.stack[-1], _ClassInfo): |
| 2059 | if nesting_state.stack[-1].access != 'private': |
| 2060 | error(filename, linenum, 'readability/constructors', 3, |
| 2061 | '%s must be in the private: section' % matched.group(1)) |
| 2062 | |
| 2063 | else: |
| 2064 | # Found DISALLOW* macro outside a class declaration, or perhaps it |
| 2065 | # was used inside a function when it should have been part of the |
| 2066 | # class declaration. We could issue a warning here, but it |
| 2067 | # probably resulted in a compiler error already. |
| 2068 | pass |
| 2069 | |
| 2070 | |
| 2071 | def FindNextMatchingAngleBracket(clean_lines, linenum, init_suffix): |
| 2072 | """Find the corresponding > to close a template. |
| 2073 | |
| 2074 | Args: |
| 2075 | clean_lines: A CleansedLines instance containing the file. |
| 2076 | linenum: Current line number. |
| 2077 | init_suffix: Remainder of the current line after the initial <. |
| 2078 | |
| 2079 | Returns: |
| 2080 | True if a matching bracket exists. |
| 2081 | """ |
| 2082 | line = init_suffix |
| 2083 | nesting_stack = ['<'] |
| 2084 | while True: |
| 2085 | # Find the next operator that can tell us whether < is used as an |
| 2086 | # opening bracket or as a less-than operator. We only want to |
| 2087 | # warn on the latter case. |
| 2088 | # |
| 2089 | # We could also check all other operators and terminate the search |
| 2090 | # early, e.g. if we got something like this "a<b+c", the "<" is |
| 2091 | # most likely a less-than operator, but then we will get false |
| 2092 | # positives for default arguments (e.g. http://go/prccd) and |
| 2093 | # other template expressions (e.g. http://go/oxcjq). |
| 2094 | match = Search(r'^[^<>(),;\[\]]*([<>(),;\[\]])(.*)$', line) |
| 2095 | if match: |
| 2096 | # Found an operator, update nesting stack |
| 2097 | operator = match.group(1) |
| 2098 | line = match.group(2) |
| 2099 | |
| 2100 | if nesting_stack[-1] == '<': |
| 2101 | # Expecting closing angle bracket |
| 2102 | if operator in ('<', '(', '['): |
| 2103 | nesting_stack.append(operator) |
| 2104 | elif operator == '>': |
| 2105 | nesting_stack.pop() |
| 2106 | if not nesting_stack: |
| 2107 | # Found matching angle bracket |
| 2108 | return True |
| 2109 | elif operator == ',': |
| 2110 | # Got a comma after a bracket, this is most likely a template |
| 2111 | # argument. We have not seen a closing angle bracket yet, but |
| 2112 | # it's probably a few lines later if we look for it, so just |
| 2113 | # return early here. |
| 2114 | return True |
| 2115 | else: |
| 2116 | # Got some other operator. |
| 2117 | return False |
| 2118 | |
| 2119 | else: |
| 2120 | # Expecting closing parenthesis or closing bracket |
| 2121 | if operator in ('<', '(', '['): |
| 2122 | nesting_stack.append(operator) |
| 2123 | elif operator in (')', ']'): |
| 2124 | # We don't bother checking for matching () or []. If we got |
| 2125 | # something like (] or [), it would have been a syntax error. |
| 2126 | nesting_stack.pop() |
| 2127 | |
| 2128 | else: |
| 2129 | # Scan the next line |
| 2130 | linenum += 1 |
| 2131 | if linenum >= len(clean_lines.elided): |
| 2132 | break |
| 2133 | line = clean_lines.elided[linenum] |
| 2134 | |
| 2135 | # Exhausted all remaining lines and still no matching angle bracket. |
| 2136 | # Most likely the input was incomplete, otherwise we should have |
| 2137 | # seen a semicolon and returned early. |
| 2138 | return True |
| 2139 | |
| 2140 | |
| 2141 | def FindPreviousMatchingAngleBracket(clean_lines, linenum, init_prefix): |
| 2142 | """Find the corresponding < that started a template. |
| 2143 | |
| 2144 | Args: |
| 2145 | clean_lines: A CleansedLines instance containing the file. |
| 2146 | linenum: Current line number. |
| 2147 | init_prefix: Part of the current line before the initial >. |
| 2148 | |
| 2149 | Returns: |
| 2150 | True if a matching bracket exists. |
| 2151 | """ |
| 2152 | line = init_prefix |
| 2153 | nesting_stack = ['>'] |
| 2154 | while True: |
| 2155 | # Find the previous operator |
| 2156 | match = Search(r'^(.*)([<>(),;\[\]])[^<>(),;\[\]]*$', line) |
| 2157 | if match: |
| 2158 | # Found an operator, update nesting stack |
| 2159 | operator = match.group(2) |
| 2160 | line = match.group(1) |
| 2161 | |
| 2162 | if nesting_stack[-1] == '>': |
| 2163 | # Expecting opening angle bracket |
| 2164 | if operator in ('>', ')', ']'): |
| 2165 | nesting_stack.append(operator) |
| 2166 | elif operator == '<': |
| 2167 | nesting_stack.pop() |
| 2168 | if not nesting_stack: |
| 2169 | # Found matching angle bracket |
| 2170 | return True |
| 2171 | elif operator == ',': |
| 2172 | # Got a comma before a bracket, this is most likely a |
| 2173 | # template argument. The opening angle bracket is probably |
| 2174 | # there if we look for it, so just return early here. |
| 2175 | return True |
| 2176 | else: |
| 2177 | # Got some other operator. |
| 2178 | return False |
| 2179 | |
| 2180 | else: |
| 2181 | # Expecting opening parenthesis or opening bracket |
| 2182 | if operator in ('>', ')', ']'): |
| 2183 | nesting_stack.append(operator) |
| 2184 | elif operator in ('(', '['): |
| 2185 | nesting_stack.pop() |
| 2186 | |
| 2187 | else: |
| 2188 | # Scan the previous line |
| 2189 | linenum -= 1 |
| 2190 | if linenum < 0: |
| 2191 | break |
| 2192 | line = clean_lines.elided[linenum] |
| 2193 | |
| 2194 | # Exhausted all earlier lines and still no matching angle bracket. |
| 2195 | return False |
| 2196 | |
| 2197 | |
| 2198 | def CheckSpacing(filename, clean_lines, linenum, nesting_state, error): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2199 | """Checks for the correctness of various spacing issues in the code. |
| 2200 | |
| 2201 | Things we check for: spaces around operators, spaces after |
| 2202 | if/for/while/switch, no spaces around parens in function calls, two |
| 2203 | spaces between code and comment, don't start a block with a blank |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 2204 | line, don't end a function with a blank line, don't add a blank line |
| 2205 | after public/protected/private, don't have too many blank lines in a row. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2206 | |
| 2207 | Args: |
| 2208 | filename: The name of the current file. |
| 2209 | clean_lines: A CleansedLines instance containing the file. |
| 2210 | linenum: The number of the line to check. |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2211 | nesting_state: A _NestingState instance which maintains information about |
| 2212 | the current stack of nested blocks being parsed. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2213 | error: The function to call with any errors found. |
| 2214 | """ |
| 2215 | |
| 2216 | raw = clean_lines.raw_lines |
| 2217 | line = raw[linenum] |
| 2218 | |
| 2219 | # Before nixing comments, check if the line is blank for no good |
| 2220 | # reason. This includes the first line after a block is opened, and |
| 2221 | # blank lines at the end of a function (ie, right before a line like '}' |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2222 | # |
| 2223 | # Skip all the blank line checks if we are immediately inside a |
| 2224 | # namespace body. In other words, don't issue blank line warnings |
| 2225 | # for this block: |
| 2226 | # namespace { |
| 2227 | # |
| 2228 | # } |
| 2229 | # |
| 2230 | # A warning about missing end of namespace comments will be issued instead. |
| 2231 | if IsBlankLine(line) and not nesting_state.InNamespaceBody(): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2232 | elided = clean_lines.elided |
| 2233 | prev_line = elided[linenum - 1] |
| 2234 | prevbrace = prev_line.rfind('{') |
| 2235 | # TODO(unknown): Don't complain if line before blank line, and line after, |
| 2236 | # both start with alnums and are indented the same amount. |
| 2237 | # This ignores whitespace at the start of a namespace block |
| 2238 | # because those are not usually indented. |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2239 | if prevbrace != -1 and prev_line[prevbrace:].find('}') == -1: |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2240 | # OK, we have a blank line at the start of a code block. Before we |
| 2241 | # complain, we check if it is an exception to the rule: The previous |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 2242 | # non-empty line has the parameters of a function header that are indented |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2243 | # 4 spaces (because they did not fit in a 80 column line when placed on |
| 2244 | # the same line as the function name). We also check for the case where |
| 2245 | # the previous line is indented 6 spaces, which may happen when the |
| 2246 | # initializers of a constructor do not fit into a 80 column line. |
| 2247 | exception = False |
| 2248 | if Match(r' {6}\w', prev_line): # Initializer list? |
| 2249 | # We are looking for the opening column of initializer list, which |
| 2250 | # should be indented 4 spaces to cause 6 space indentation afterwards. |
| 2251 | search_position = linenum-2 |
| 2252 | while (search_position >= 0 |
| 2253 | and Match(r' {6}\w', elided[search_position])): |
| 2254 | search_position -= 1 |
| 2255 | exception = (search_position >= 0 |
| 2256 | and elided[search_position][:5] == ' :') |
| 2257 | else: |
| 2258 | # Search for the function arguments or an initializer list. We use a |
| 2259 | # simple heuristic here: If the line is indented 4 spaces; and we have a |
| 2260 | # closing paren, without the opening paren, followed by an opening brace |
| 2261 | # or colon (for initializer lists) we assume that it is the last line of |
| 2262 | # a function header. If we have a colon indented 4 spaces, it is an |
| 2263 | # initializer list. |
| 2264 | exception = (Match(r' {4}\w[^\(]*\)\s*(const\s*)?(\{\s*$|:)', |
| 2265 | prev_line) |
| 2266 | or Match(r' {4}:', prev_line)) |
| 2267 | |
| 2268 | if not exception: |
| 2269 | error(filename, linenum, 'whitespace/blank_line', 2, |
| 2270 | 'Blank line at the start of a code block. Is this needed?') |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2271 | # Ignore blank lines at the end of a block in a long if-else |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2272 | # chain, like this: |
| 2273 | # if (condition1) { |
| 2274 | # // Something followed by a blank line |
| 2275 | # |
| 2276 | # } else if (condition2) { |
| 2277 | # // Something else |
| 2278 | # } |
| 2279 | if linenum + 1 < clean_lines.NumLines(): |
| 2280 | next_line = raw[linenum + 1] |
| 2281 | if (next_line |
| 2282 | and Match(r'\s*}', next_line) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2283 | and next_line.find('} else ') == -1): |
| 2284 | error(filename, linenum, 'whitespace/blank_line', 3, |
| 2285 | 'Blank line at the end of a code block. Is this needed?') |
| 2286 | |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 2287 | matched = Match(r'\s*(public|protected|private):', prev_line) |
| 2288 | if matched: |
| 2289 | error(filename, linenum, 'whitespace/blank_line', 3, |
| 2290 | 'Do not leave a blank line after "%s:"' % matched.group(1)) |
| 2291 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2292 | # Next, we complain if there's a comment too near the text |
| 2293 | commentpos = line.find('//') |
| 2294 | if commentpos != -1: |
| 2295 | # Check if the // may be in quotes. If so, ignore it |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 2296 | # Comparisons made explicit for clarity -- pylint: disable-msg=C6403 |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2297 | if (line.count('"', 0, commentpos) - |
| 2298 | line.count('\\"', 0, commentpos)) % 2 == 0: # not in quotes |
| 2299 | # Allow one space for new scopes, two spaces otherwise: |
| 2300 | if (not Match(r'^\s*{ //', line) and |
| 2301 | ((commentpos >= 1 and |
| 2302 | line[commentpos-1] not in string.whitespace) or |
| 2303 | (commentpos >= 2 and |
| 2304 | line[commentpos-2] not in string.whitespace))): |
| 2305 | error(filename, linenum, 'whitespace/comments', 2, |
| 2306 | 'At least two spaces is best between code and comments') |
| 2307 | # There should always be a space between the // and the comment |
| 2308 | commentend = commentpos + 2 |
| 2309 | if commentend < len(line) and not line[commentend] == ' ': |
| 2310 | # but some lines are exceptions -- e.g. if they're big |
| 2311 | # comment delimiters like: |
| 2312 | # //---------------------------------------------------------- |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 2313 | # or are an empty C++ style Doxygen comment, like: |
| 2314 | # /// |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 2315 | # or they begin with multiple slashes followed by a space: |
| 2316 | # //////// Header comment |
| 2317 | match = (Search(r'[=/-]{4,}\s*$', line[commentend:]) or |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 2318 | Search(r'^/$', line[commentend:]) or |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 2319 | Search(r'^/+ ', line[commentend:])) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2320 | if not match: |
| 2321 | error(filename, linenum, 'whitespace/comments', 4, |
| 2322 | 'Should have a space between // and comment') |
| 2323 | CheckComment(line[commentpos:], filename, linenum, error) |
| 2324 | |
| 2325 | line = clean_lines.elided[linenum] # get rid of comments and strings |
| 2326 | |
| 2327 | # Don't try to do spacing checks for operator methods |
| 2328 | line = re.sub(r'operator(==|!=|<|<<|<=|>=|>>|>)\(', 'operator\(', line) |
| 2329 | |
| 2330 | # We allow no-spaces around = within an if: "if ( (a=Foo()) == 0 )". |
| 2331 | # Otherwise not. Note we only check for non-spaces on *both* sides; |
| 2332 | # sometimes people put non-spaces on one side when aligning ='s among |
| 2333 | # many lines (not that this is behavior that I approve of...) |
| 2334 | if Search(r'[\w.]=[\w.]', line) and not Search(r'\b(if|while) ', line): |
| 2335 | error(filename, linenum, 'whitespace/operators', 4, |
| 2336 | 'Missing spaces around =') |
| 2337 | |
| 2338 | # It's ok not to have spaces around binary operators like + - * /, but if |
| 2339 | # there's too little whitespace, we get concerned. It's hard to tell, |
| 2340 | # though, so we punt on this one for now. TODO. |
| 2341 | |
| 2342 | # You should always have whitespace around binary operators. |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2343 | # |
| 2344 | # Check <= and >= first to avoid false positives with < and >, then |
| 2345 | # check non-include lines for spacing around < and >. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2346 | match = Search(r'[^<>=!\s](==|!=|<=|>=)[^<>=!\s]', line) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2347 | if match: |
| 2348 | error(filename, linenum, 'whitespace/operators', 3, |
| 2349 | 'Missing spaces around %s' % match.group(1)) |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2350 | # We allow no-spaces around << when used like this: 10<<20, but |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2351 | # not otherwise (particularly, not when used as streams) |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2352 | match = Search(r'(\S)(?:L|UL|ULL|l|ul|ull)?<<(\S)', line) |
| 2353 | if match and not (match.group(1).isdigit() and match.group(2).isdigit()): |
| 2354 | error(filename, linenum, 'whitespace/operators', 3, |
| 2355 | 'Missing spaces around <<') |
| 2356 | elif not Match(r'#.*include', line): |
| 2357 | # Avoid false positives on -> |
| 2358 | reduced_line = line.replace('->', '') |
| 2359 | |
| 2360 | # Look for < that is not surrounded by spaces. This is only |
| 2361 | # triggered if both sides are missing spaces, even though |
| 2362 | # technically should should flag if at least one side is missing a |
| 2363 | # space. This is done to avoid some false positives with shifts. |
| 2364 | match = Search(r'[^\s<]<([^\s=<].*)', reduced_line) |
| 2365 | if (match and |
| 2366 | not FindNextMatchingAngleBracket(clean_lines, linenum, match.group(1))): |
| 2367 | error(filename, linenum, 'whitespace/operators', 3, |
| 2368 | 'Missing spaces around <') |
| 2369 | |
| 2370 | # Look for > that is not surrounded by spaces. Similar to the |
| 2371 | # above, we only trigger if both sides are missing spaces to avoid |
| 2372 | # false positives with shifts. |
| 2373 | match = Search(r'^(.*[^\s>])>[^\s=>]', reduced_line) |
| 2374 | if (match and |
| 2375 | not FindPreviousMatchingAngleBracket(clean_lines, linenum, |
| 2376 | match.group(1))): |
| 2377 | error(filename, linenum, 'whitespace/operators', 3, |
| 2378 | 'Missing spaces around >') |
| 2379 | |
| 2380 | # We allow no-spaces around >> for almost anything. This is because |
| 2381 | # C++11 allows ">>" to close nested templates, which accounts for |
| 2382 | # most cases when ">>" is not followed by a space. |
| 2383 | # |
| 2384 | # We still warn on ">>" followed by alpha character, because that is |
| 2385 | # likely due to ">>" being used for right shifts, e.g.: |
| 2386 | # value >> alpha |
| 2387 | # |
| 2388 | # When ">>" is used to close templates, the alphanumeric letter that |
| 2389 | # follows would be part of an identifier, and there should still be |
| 2390 | # a space separating the template type and the identifier. |
| 2391 | # type<type<type>> alpha |
| 2392 | match = Search(r'>>[a-zA-Z_]', line) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2393 | if match: |
| 2394 | error(filename, linenum, 'whitespace/operators', 3, |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2395 | 'Missing spaces around >>') |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2396 | |
| 2397 | # There shouldn't be space around unary operators |
| 2398 | match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line) |
| 2399 | if match: |
| 2400 | error(filename, linenum, 'whitespace/operators', 4, |
| 2401 | 'Extra space for operator %s' % match.group(1)) |
| 2402 | |
| 2403 | # A pet peeve of mine: no spaces after an if, while, switch, or for |
| 2404 | match = Search(r' (if\(|for\(|while\(|switch\()', line) |
| 2405 | if match: |
| 2406 | error(filename, linenum, 'whitespace/parens', 5, |
| 2407 | 'Missing space before ( in %s' % match.group(1)) |
| 2408 | |
| 2409 | # For if/for/while/switch, the left and right parens should be |
| 2410 | # consistent about how many spaces are inside the parens, and |
| 2411 | # there should either be zero or one spaces inside the parens. |
| 2412 | # We don't want: "if ( foo)" or "if ( foo )". |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 2413 | # Exception: "for ( ; foo; bar)" and "for (foo; bar; )" are allowed. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2414 | match = Search(r'\b(if|for|while|switch)\s*' |
| 2415 | r'\(([ ]*)(.).*[^ ]+([ ]*)\)\s*{\s*$', |
| 2416 | line) |
| 2417 | if match: |
| 2418 | if len(match.group(2)) != len(match.group(4)): |
| 2419 | if not (match.group(3) == ';' and |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 2420 | len(match.group(2)) == 1 + len(match.group(4)) or |
| 2421 | not match.group(2) and Search(r'\bfor\s*\(.*; \)', line)): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2422 | error(filename, linenum, 'whitespace/parens', 5, |
| 2423 | 'Mismatching spaces inside () in %s' % match.group(1)) |
| 2424 | if not len(match.group(2)) in [0, 1]: |
| 2425 | error(filename, linenum, 'whitespace/parens', 5, |
| 2426 | 'Should have zero or one spaces inside ( and ) in %s' % |
| 2427 | match.group(1)) |
| 2428 | |
| 2429 | # You should always have a space after a comma (either as fn arg or operator) |
| 2430 | if Search(r',[^\s]', line): |
| 2431 | error(filename, linenum, 'whitespace/comma', 3, |
| 2432 | 'Missing space after ,') |
| 2433 | |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 2434 | # You should always have a space after a semicolon |
| 2435 | # except for few corner cases |
| 2436 | # TODO(unknown): clarify if 'if (1) { return 1;}' is requires one more |
| 2437 | # space after ; |
| 2438 | if Search(r';[^\s};\\)/]', line): |
| 2439 | error(filename, linenum, 'whitespace/semicolon', 3, |
| 2440 | 'Missing space after ;') |
| 2441 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2442 | # Next we will look for issues with function calls. |
| 2443 | CheckSpacingForFunctionCall(filename, line, linenum, error) |
| 2444 | |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 2445 | # Except after an opening paren, or after another opening brace (in case of |
| 2446 | # an initializer list, for instance), you should have spaces before your |
| 2447 | # braces. And since you should never have braces at the beginning of a line, |
| 2448 | # this is an easy test. |
| 2449 | if Search(r'[^ ({]{', line): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2450 | error(filename, linenum, 'whitespace/braces', 5, |
| 2451 | 'Missing space before {') |
| 2452 | |
| 2453 | # Make sure '} else {' has spaces. |
| 2454 | if Search(r'}else', line): |
| 2455 | error(filename, linenum, 'whitespace/braces', 5, |
| 2456 | 'Missing space before else') |
| 2457 | |
| 2458 | # You shouldn't have spaces before your brackets, except maybe after |
| 2459 | # 'delete []' or 'new char * []'. |
| 2460 | if Search(r'\w\s+\[', line) and not Search(r'delete\s+\[', line): |
| 2461 | error(filename, linenum, 'whitespace/braces', 5, |
| 2462 | 'Extra space before [') |
| 2463 | |
| 2464 | # You shouldn't have a space before a semicolon at the end of the line. |
| 2465 | # There's a special case for "for" since the style guide allows space before |
| 2466 | # the semicolon there. |
| 2467 | if Search(r':\s*;\s*$', line): |
| 2468 | error(filename, linenum, 'whitespace/semicolon', 5, |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2469 | 'Semicolon defining empty statement. Use {} instead.') |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2470 | elif Search(r'^\s*;\s*$', line): |
| 2471 | error(filename, linenum, 'whitespace/semicolon', 5, |
| 2472 | 'Line contains only semicolon. If this should be an empty statement, ' |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2473 | 'use {} instead.') |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2474 | elif (Search(r'\s+;\s*$', line) and |
| 2475 | not Search(r'\bfor\b', line)): |
| 2476 | error(filename, linenum, 'whitespace/semicolon', 5, |
| 2477 | 'Extra space before last semicolon. If this should be an empty ' |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2478 | 'statement, use {} instead.') |
| 2479 | |
| 2480 | # In range-based for, we wanted spaces before and after the colon, but |
| 2481 | # not around "::" tokens that might appear. |
| 2482 | if (Search('for *\(.*[^:]:[^: ]', line) or |
| 2483 | Search('for *\(.*[^: ]:[^:]', line)): |
| 2484 | error(filename, linenum, 'whitespace/forcolon', 2, |
| 2485 | 'Missing space around colon in range-based for loop') |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2486 | |
| 2487 | |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 2488 | def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error): |
| 2489 | """Checks for additional blank line issues related to sections. |
| 2490 | |
| 2491 | Currently the only thing checked here is blank line before protected/private. |
| 2492 | |
| 2493 | Args: |
| 2494 | filename: The name of the current file. |
| 2495 | clean_lines: A CleansedLines instance containing the file. |
| 2496 | class_info: A _ClassInfo objects. |
| 2497 | linenum: The number of the line to check. |
| 2498 | error: The function to call with any errors found. |
| 2499 | """ |
| 2500 | # Skip checks if the class is small, where small means 25 lines or less. |
| 2501 | # 25 lines seems like a good cutoff since that's the usual height of |
| 2502 | # terminals, and any class that can't fit in one screen can't really |
| 2503 | # be considered "small". |
| 2504 | # |
| 2505 | # Also skip checks if we are on the first line. This accounts for |
| 2506 | # classes that look like |
| 2507 | # class Foo { public: ... }; |
| 2508 | # |
| 2509 | # If we didn't find the end of the class, last_line would be zero, |
| 2510 | # and the check will be skipped by the first condition. |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2511 | if (class_info.last_line - class_info.starting_linenum <= 24 or |
| 2512 | linenum <= class_info.starting_linenum): |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 2513 | return |
| 2514 | |
| 2515 | matched = Match(r'\s*(public|protected|private):', clean_lines.lines[linenum]) |
| 2516 | if matched: |
| 2517 | # Issue warning if the line before public/protected/private was |
| 2518 | # not a blank line, but don't do this if the previous line contains |
| 2519 | # "class" or "struct". This can happen two ways: |
| 2520 | # - We are at the beginning of the class. |
| 2521 | # - We are forward-declaring an inner class that is semantically |
| 2522 | # private, but needed to be public for implementation reasons. |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2523 | # Also ignores cases where the previous line ends with a backslash as can be |
| 2524 | # common when defining classes in C macros. |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 2525 | prev_line = clean_lines.lines[linenum - 1] |
| 2526 | if (not IsBlankLine(prev_line) and |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2527 | not Search(r'\b(class|struct)\b', prev_line) and |
| 2528 | not Search(r'\\$', prev_line)): |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 2529 | # Try a bit harder to find the beginning of the class. This is to |
| 2530 | # account for multi-line base-specifier lists, e.g.: |
| 2531 | # class Derived |
| 2532 | # : public Base { |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2533 | end_class_head = class_info.starting_linenum |
| 2534 | for i in range(class_info.starting_linenum, linenum): |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 2535 | if Search(r'\{\s*$', clean_lines.lines[i]): |
| 2536 | end_class_head = i |
| 2537 | break |
| 2538 | if end_class_head < linenum - 1: |
| 2539 | error(filename, linenum, 'whitespace/blank_line', 3, |
| 2540 | '"%s:" should be preceded by a blank line' % matched.group(1)) |
| 2541 | |
| 2542 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2543 | def GetPreviousNonBlankLine(clean_lines, linenum): |
| 2544 | """Return the most recent non-blank line and its line number. |
| 2545 | |
| 2546 | Args: |
| 2547 | clean_lines: A CleansedLines instance containing the file contents. |
| 2548 | linenum: The number of the line to check. |
| 2549 | |
| 2550 | Returns: |
| 2551 | A tuple with two elements. The first element is the contents of the last |
| 2552 | non-blank line before the current line, or the empty string if this is the |
| 2553 | first non-blank line. The second is the line number of that line, or -1 |
| 2554 | if this is the first non-blank line. |
| 2555 | """ |
| 2556 | |
| 2557 | prevlinenum = linenum - 1 |
| 2558 | while prevlinenum >= 0: |
| 2559 | prevline = clean_lines.elided[prevlinenum] |
| 2560 | if not IsBlankLine(prevline): # if not a blank line... |
| 2561 | return (prevline, prevlinenum) |
| 2562 | prevlinenum -= 1 |
| 2563 | return ('', -1) |
| 2564 | |
| 2565 | |
| 2566 | def CheckBraces(filename, clean_lines, linenum, error): |
| 2567 | """Looks for misplaced braces (e.g. at the end of line). |
| 2568 | |
| 2569 | Args: |
| 2570 | filename: The name of the current file. |
| 2571 | clean_lines: A CleansedLines instance containing the file. |
| 2572 | linenum: The number of the line to check. |
| 2573 | error: The function to call with any errors found. |
| 2574 | """ |
| 2575 | |
| 2576 | line = clean_lines.elided[linenum] # get rid of comments and strings |
| 2577 | |
| 2578 | if Match(r'\s*{\s*$', line): |
| 2579 | # We allow an open brace to start a line in the case where someone |
| 2580 | # is using braces in a block to explicitly create a new scope, |
| 2581 | # which is commonly used to control the lifetime of |
| 2582 | # stack-allocated variables. We don't detect this perfectly: we |
| 2583 | # just don't complain if the last non-whitespace character on the |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2584 | # previous non-blank line is ';', ':', '{', or '}', or if the previous |
| 2585 | # line starts a preprocessor block. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2586 | prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2587 | if (not Search(r'[;:}{]\s*$', prevline) and |
| 2588 | not Match(r'\s*#', prevline)): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2589 | error(filename, linenum, 'whitespace/braces', 4, |
| 2590 | '{ should almost always be at the end of the previous line') |
| 2591 | |
| 2592 | # An else clause should be on the same line as the preceding closing brace. |
| 2593 | if Match(r'\s*else\s*', line): |
| 2594 | prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] |
| 2595 | if Match(r'\s*}\s*$', prevline): |
| 2596 | error(filename, linenum, 'whitespace/newline', 4, |
| 2597 | 'An else should appear on the same line as the preceding }') |
| 2598 | |
| 2599 | # If braces come on one side of an else, they should be on both. |
| 2600 | # However, we have to worry about "else if" that spans multiple lines! |
| 2601 | if Search(r'}\s*else[^{]*$', line) or Match(r'[^}]*else\s*{', line): |
| 2602 | if Search(r'}\s*else if([^{]*)$', line): # could be multi-line if |
| 2603 | # find the ( after the if |
| 2604 | pos = line.find('else if') |
| 2605 | pos = line.find('(', pos) |
| 2606 | if pos > 0: |
| 2607 | (endline, _, endpos) = CloseExpression(clean_lines, linenum, pos) |
| 2608 | if endline[endpos:].find('{') == -1: # must be brace after if |
| 2609 | error(filename, linenum, 'readability/braces', 5, |
| 2610 | 'If an else has a brace on one side, it should have it on both') |
| 2611 | else: # common case: else not followed by a multi-line if |
| 2612 | error(filename, linenum, 'readability/braces', 5, |
| 2613 | 'If an else has a brace on one side, it should have it on both') |
| 2614 | |
| 2615 | # Likewise, an else should never have the else clause on the same line |
| 2616 | if Search(r'\belse [^\s{]', line) and not Search(r'\belse if\b', line): |
| 2617 | error(filename, linenum, 'whitespace/newline', 4, |
| 2618 | 'Else clause should never be on same line as else (use 2 lines)') |
| 2619 | |
| 2620 | # In the same way, a do/while should never be on one line |
| 2621 | if Match(r'\s*do [^\s{]', line): |
| 2622 | error(filename, linenum, 'whitespace/newline', 4, |
| 2623 | 'do/while clauses should not be on a single line') |
| 2624 | |
| 2625 | # Braces shouldn't be followed by a ; unless they're defining a struct |
| 2626 | # or initializing an array. |
| 2627 | # We can't tell in general, but we can for some common cases. |
| 2628 | prevlinenum = linenum |
| 2629 | while True: |
| 2630 | (prevline, prevlinenum) = GetPreviousNonBlankLine(clean_lines, prevlinenum) |
| 2631 | if Match(r'\s+{.*}\s*;', line) and not prevline.count(';'): |
| 2632 | line = prevline + line |
| 2633 | else: |
| 2634 | break |
| 2635 | if (Search(r'{.*}\s*;', line) and |
| 2636 | line.count('{') == line.count('}') and |
| 2637 | not Search(r'struct|class|enum|\s*=\s*{', line)): |
| 2638 | error(filename, linenum, 'readability/braces', 4, |
| 2639 | "You don't need a ; after a }") |
| 2640 | |
| 2641 | |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2642 | def CheckEmptyLoopBody(filename, clean_lines, linenum, error): |
| 2643 | """Loop for empty loop body with only a single semicolon. |
| 2644 | |
| 2645 | Args: |
| 2646 | filename: The name of the current file. |
| 2647 | clean_lines: A CleansedLines instance containing the file. |
| 2648 | linenum: The number of the line to check. |
| 2649 | error: The function to call with any errors found. |
| 2650 | """ |
| 2651 | |
| 2652 | # Search for loop keywords at the beginning of the line. Because only |
| 2653 | # whitespaces are allowed before the keywords, this will also ignore most |
| 2654 | # do-while-loops, since those lines should start with closing brace. |
| 2655 | line = clean_lines.elided[linenum] |
| 2656 | if Match(r'\s*(for|while)\s*\(', line): |
| 2657 | # Find the end of the conditional expression |
| 2658 | (end_line, end_linenum, end_pos) = CloseExpression( |
| 2659 | clean_lines, linenum, line.find('(')) |
| 2660 | |
| 2661 | # Output warning if what follows the condition expression is a semicolon. |
| 2662 | # No warning for all other cases, including whitespace or newline, since we |
| 2663 | # have a separate check for semicolons preceded by whitespace. |
| 2664 | if end_pos >= 0 and Match(r';', end_line[end_pos:]): |
| 2665 | error(filename, end_linenum, 'whitespace/empty_loop_body', 5, |
| 2666 | 'Empty loop bodies should use {} or continue') |
| 2667 | |
| 2668 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2669 | def ReplaceableCheck(operator, macro, line): |
| 2670 | """Determine whether a basic CHECK can be replaced with a more specific one. |
| 2671 | |
| 2672 | For example suggest using CHECK_EQ instead of CHECK(a == b) and |
| 2673 | similarly for CHECK_GE, CHECK_GT, CHECK_LE, CHECK_LT, CHECK_NE. |
| 2674 | |
| 2675 | Args: |
| 2676 | operator: The C++ operator used in the CHECK. |
| 2677 | macro: The CHECK or EXPECT macro being called. |
| 2678 | line: The current source line. |
| 2679 | |
| 2680 | Returns: |
| 2681 | True if the CHECK can be replaced with a more specific one. |
| 2682 | """ |
| 2683 | |
| 2684 | # This matches decimal and hex integers, strings, and chars (in that order). |
| 2685 | match_constant = r'([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')' |
| 2686 | |
| 2687 | # Expression to match two sides of the operator with something that |
| 2688 | # looks like a literal, since CHECK(x == iterator) won't compile. |
| 2689 | # This means we can't catch all the cases where a more specific |
| 2690 | # CHECK is possible, but it's less annoying than dealing with |
| 2691 | # extraneous warnings. |
| 2692 | match_this = (r'\s*' + macro + r'\((\s*' + |
| 2693 | match_constant + r'\s*' + operator + r'[^<>].*|' |
| 2694 | r'.*[^<>]' + operator + r'\s*' + match_constant + |
| 2695 | r'\s*\))') |
| 2696 | |
| 2697 | # Don't complain about CHECK(x == NULL) or similar because |
| 2698 | # CHECK_EQ(x, NULL) won't compile (requires a cast). |
| 2699 | # Also, don't complain about more complex boolean expressions |
| 2700 | # involving && or || such as CHECK(a == b || c == d). |
| 2701 | return Match(match_this, line) and not Search(r'NULL|&&|\|\|', line) |
| 2702 | |
| 2703 | |
| 2704 | def CheckCheck(filename, clean_lines, linenum, error): |
| 2705 | """Checks the use of CHECK and EXPECT macros. |
| 2706 | |
| 2707 | Args: |
| 2708 | filename: The name of the current file. |
| 2709 | clean_lines: A CleansedLines instance containing the file. |
| 2710 | linenum: The number of the line to check. |
| 2711 | error: The function to call with any errors found. |
| 2712 | """ |
| 2713 | |
| 2714 | # Decide the set of replacement macros that should be suggested |
| 2715 | raw_lines = clean_lines.raw_lines |
| 2716 | current_macro = '' |
| 2717 | for macro in _CHECK_MACROS: |
| 2718 | if raw_lines[linenum].find(macro) >= 0: |
| 2719 | current_macro = macro |
| 2720 | break |
| 2721 | if not current_macro: |
| 2722 | # Don't waste time here if line doesn't contain 'CHECK' or 'EXPECT' |
| 2723 | return |
| 2724 | |
| 2725 | line = clean_lines.elided[linenum] # get rid of comments and strings |
| 2726 | |
| 2727 | # Encourage replacing plain CHECKs with CHECK_EQ/CHECK_NE/etc. |
| 2728 | for operator in ['==', '!=', '>=', '>', '<=', '<']: |
| 2729 | if ReplaceableCheck(operator, current_macro, line): |
| 2730 | error(filename, linenum, 'readability/check', 2, |
| 2731 | 'Consider using %s instead of %s(a %s b)' % ( |
| 2732 | _CHECK_REPLACEMENT[current_macro][operator], |
| 2733 | current_macro, operator)) |
| 2734 | break |
| 2735 | |
| 2736 | |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2737 | def CheckAltTokens(filename, clean_lines, linenum, error): |
| 2738 | """Check alternative keywords being used in boolean expressions. |
| 2739 | |
| 2740 | Args: |
| 2741 | filename: The name of the current file. |
| 2742 | clean_lines: A CleansedLines instance containing the file. |
| 2743 | linenum: The number of the line to check. |
| 2744 | error: The function to call with any errors found. |
| 2745 | """ |
| 2746 | line = clean_lines.elided[linenum] |
| 2747 | |
| 2748 | # Avoid preprocessor lines |
| 2749 | if Match(r'^\s*#', line): |
| 2750 | return |
| 2751 | |
| 2752 | # Last ditch effort to avoid multi-line comments. This will not help |
| 2753 | # if the comment started before the current line or ended after the |
| 2754 | # current line, but it catches most of the false positives. At least, |
| 2755 | # it provides a way to workaround this warning for people who use |
| 2756 | # multi-line comments in preprocessor macros. |
| 2757 | # |
| 2758 | # TODO(unknown): remove this once cpplint has better support for |
| 2759 | # multi-line comments. |
| 2760 | if line.find('/*') >= 0 or line.find('*/') >= 0: |
| 2761 | return |
| 2762 | |
| 2763 | for match in _ALT_TOKEN_REPLACEMENT_PATTERN.finditer(line): |
| 2764 | error(filename, linenum, 'readability/alt_tokens', 2, |
| 2765 | 'Use operator %s instead of %s' % ( |
| 2766 | _ALT_TOKEN_REPLACEMENT[match.group(1)], match.group(1))) |
| 2767 | |
| 2768 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2769 | def GetLineWidth(line): |
| 2770 | """Determines the width of the line in column positions. |
| 2771 | |
| 2772 | Args: |
| 2773 | line: A string, which may be a Unicode string. |
| 2774 | |
| 2775 | Returns: |
| 2776 | The width of the line in column positions, accounting for Unicode |
| 2777 | combining characters and wide characters. |
| 2778 | """ |
| 2779 | if isinstance(line, unicode): |
| 2780 | width = 0 |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 2781 | for uc in unicodedata.normalize('NFC', line): |
| 2782 | if unicodedata.east_asian_width(uc) in ('W', 'F'): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2783 | width += 2 |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 2784 | elif not unicodedata.combining(uc): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2785 | width += 1 |
| 2786 | return width |
| 2787 | else: |
| 2788 | return len(line) |
| 2789 | |
| 2790 | |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2791 | def CheckStyle(filename, clean_lines, linenum, file_extension, nesting_state, |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 2792 | error): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2793 | """Checks rules from the 'C++ style rules' section of cppguide.html. |
| 2794 | |
| 2795 | Most of these rules are hard to test (naming, comment style), but we |
| 2796 | do what we can. In particular we check for 2-space indents, line lengths, |
| 2797 | tab usage, spaces inside code, etc. |
| 2798 | |
| 2799 | Args: |
| 2800 | filename: The name of the current file. |
| 2801 | clean_lines: A CleansedLines instance containing the file. |
| 2802 | linenum: The number of the line to check. |
| 2803 | file_extension: The extension (without the dot) of the filename. |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2804 | nesting_state: A _NestingState instance which maintains information about |
| 2805 | the current stack of nested blocks being parsed. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2806 | error: The function to call with any errors found. |
| 2807 | """ |
| 2808 | |
| 2809 | raw_lines = clean_lines.raw_lines |
| 2810 | line = raw_lines[linenum] |
| 2811 | |
| 2812 | if line.find('\t') != -1: |
| 2813 | error(filename, linenum, 'whitespace/tab', 1, |
| 2814 | 'Tab found; better to use spaces') |
| 2815 | |
| 2816 | # One or three blank spaces at the beginning of the line is weird; it's |
| 2817 | # hard to reconcile that with 2-space indents. |
| 2818 | # NOTE: here are the conditions rob pike used for his tests. Mine aren't |
| 2819 | # as sophisticated, but it may be worth becoming so: RLENGTH==initial_spaces |
| 2820 | # if(RLENGTH > 20) complain = 0; |
| 2821 | # if(match($0, " +(error|private|public|protected):")) complain = 0; |
| 2822 | # if(match(prev, "&& *$")) complain = 0; |
| 2823 | # if(match(prev, "\\|\\| *$")) complain = 0; |
| 2824 | # if(match(prev, "[\",=><] *$")) complain = 0; |
| 2825 | # if(match($0, " <<")) complain = 0; |
| 2826 | # if(match(prev, " +for \\(")) complain = 0; |
| 2827 | # if(prevodd && match(prevprev, " +for \\(")) complain = 0; |
| 2828 | initial_spaces = 0 |
| 2829 | cleansed_line = clean_lines.elided[linenum] |
| 2830 | while initial_spaces < len(line) and line[initial_spaces] == ' ': |
| 2831 | initial_spaces += 1 |
| 2832 | if line and line[-1].isspace(): |
| 2833 | error(filename, linenum, 'whitespace/end_of_line', 4, |
| 2834 | 'Line ends in whitespace. Consider deleting these extra spaces.') |
| 2835 | # There are certain situations we allow one space, notably for labels |
| 2836 | elif ((initial_spaces == 1 or initial_spaces == 3) and |
| 2837 | not Match(r'\s*\w+\s*:\s*$', cleansed_line)): |
| 2838 | error(filename, linenum, 'whitespace/indent', 3, |
| 2839 | 'Weird number of spaces at line-start. ' |
| 2840 | 'Are you using a 2-space indent?') |
| 2841 | # Labels should always be indented at least one space. |
| 2842 | elif not initial_spaces and line[:2] != '//' and Search(r'[^:]:\s*$', |
| 2843 | line): |
| 2844 | error(filename, linenum, 'whitespace/labels', 4, |
| 2845 | 'Labels should always be indented at least one space. ' |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 2846 | 'If this is a member-initializer list in a constructor or ' |
| 2847 | 'the base class list in a class definition, the colon should ' |
| 2848 | 'be on the following line.') |
| 2849 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2850 | |
| 2851 | # Check if the line is a header guard. |
| 2852 | is_header_guard = False |
| 2853 | if file_extension == 'h': |
| 2854 | cppvar = GetHeaderGuardCPPVariable(filename) |
| 2855 | if (line.startswith('#ifndef %s' % cppvar) or |
| 2856 | line.startswith('#define %s' % cppvar) or |
| 2857 | line.startswith('#endif // %s' % cppvar)): |
| 2858 | is_header_guard = True |
| 2859 | # #include lines and header guards can be long, since there's no clean way to |
| 2860 | # split them. |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 2861 | # |
| 2862 | # URLs can be long too. It's possible to split these, but it makes them |
| 2863 | # harder to cut&paste. |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 2864 | # |
| 2865 | # The "$Id:...$" comment may also get very long without it being the |
| 2866 | # developers fault. |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 2867 | if (not line.startswith('#include') and not is_header_guard and |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 2868 | not Match(r'^\s*//.*http(s?)://\S*$', line) and |
| 2869 | not Match(r'^// \$Id:.*#[0-9]+ \$$', line)): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2870 | line_width = GetLineWidth(line) |
| 2871 | if line_width > 100: |
| 2872 | error(filename, linenum, 'whitespace/line_length', 4, |
| 2873 | 'Lines should very rarely be longer than 100 characters') |
| 2874 | elif line_width > 80: |
| 2875 | error(filename, linenum, 'whitespace/line_length', 2, |
| 2876 | 'Lines should be <= 80 characters long') |
| 2877 | |
| 2878 | if (cleansed_line.count(';') > 1 and |
| 2879 | # for loops are allowed two ;'s (and may run over two lines). |
| 2880 | cleansed_line.find('for') == -1 and |
| 2881 | (GetPreviousNonBlankLine(clean_lines, linenum)[0].find('for') == -1 or |
| 2882 | GetPreviousNonBlankLine(clean_lines, linenum)[0].find(';') != -1) and |
| 2883 | # It's ok to have many commands in a switch case that fits in 1 line |
| 2884 | not ((cleansed_line.find('case ') != -1 or |
| 2885 | cleansed_line.find('default:') != -1) and |
| 2886 | cleansed_line.find('break;') != -1)): |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2887 | error(filename, linenum, 'whitespace/newline', 0, |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2888 | 'More than one command on the same line') |
| 2889 | |
| 2890 | # Some more style checks |
| 2891 | CheckBraces(filename, clean_lines, linenum, error) |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2892 | CheckEmptyLoopBody(filename, clean_lines, linenum, error) |
| 2893 | CheckAccess(filename, clean_lines, linenum, nesting_state, error) |
| 2894 | CheckSpacing(filename, clean_lines, linenum, nesting_state, error) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2895 | CheckCheck(filename, clean_lines, linenum, error) |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2896 | CheckAltTokens(filename, clean_lines, linenum, error) |
| 2897 | classinfo = nesting_state.InnermostClass() |
| 2898 | if classinfo: |
| 2899 | CheckSectionSpacing(filename, clean_lines, classinfo, linenum, error) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2900 | |
| 2901 | |
| 2902 | _RE_PATTERN_INCLUDE_NEW_STYLE = re.compile(r'#include +"[^/]+\.h"') |
| 2903 | _RE_PATTERN_INCLUDE = re.compile(r'^\s*#\s*include\s*([<"])([^>"]*)[>"].*$') |
| 2904 | # Matches the first component of a filename delimited by -s and _s. That is: |
| 2905 | # _RE_FIRST_COMPONENT.match('foo').group(0) == 'foo' |
| 2906 | # _RE_FIRST_COMPONENT.match('foo.cc').group(0) == 'foo' |
| 2907 | # _RE_FIRST_COMPONENT.match('foo-bar_baz.cc').group(0) == 'foo' |
| 2908 | # _RE_FIRST_COMPONENT.match('foo_bar-baz.cc').group(0) == 'foo' |
| 2909 | _RE_FIRST_COMPONENT = re.compile(r'^[^-_.]+') |
| 2910 | |
| 2911 | |
| 2912 | def _DropCommonSuffixes(filename): |
| 2913 | """Drops common suffixes like _test.cc or -inl.h from filename. |
| 2914 | |
| 2915 | For example: |
| 2916 | >>> _DropCommonSuffixes('foo/foo-inl.h') |
| 2917 | 'foo/foo' |
| 2918 | >>> _DropCommonSuffixes('foo/bar/foo.cc') |
| 2919 | 'foo/bar/foo' |
| 2920 | >>> _DropCommonSuffixes('foo/foo_internal.h') |
| 2921 | 'foo/foo' |
| 2922 | >>> _DropCommonSuffixes('foo/foo_unusualinternal.h') |
| 2923 | 'foo/foo_unusualinternal' |
| 2924 | |
| 2925 | Args: |
| 2926 | filename: The input filename. |
| 2927 | |
| 2928 | Returns: |
| 2929 | The filename with the common suffix removed. |
| 2930 | """ |
| 2931 | for suffix in ('test.cc', 'regtest.cc', 'unittest.cc', |
| 2932 | 'inl.h', 'impl.h', 'internal.h'): |
| 2933 | if (filename.endswith(suffix) and len(filename) > len(suffix) and |
| 2934 | filename[-len(suffix) - 1] in ('-', '_')): |
| 2935 | return filename[:-len(suffix) - 1] |
| 2936 | return os.path.splitext(filename)[0] |
| 2937 | |
| 2938 | |
| 2939 | def _IsTestFilename(filename): |
| 2940 | """Determines if the given filename has a suffix that identifies it as a test. |
| 2941 | |
| 2942 | Args: |
| 2943 | filename: The input filename. |
| 2944 | |
| 2945 | Returns: |
| 2946 | True if 'filename' looks like a test, False otherwise. |
| 2947 | """ |
| 2948 | if (filename.endswith('_test.cc') or |
| 2949 | filename.endswith('_unittest.cc') or |
| 2950 | filename.endswith('_regtest.cc')): |
| 2951 | return True |
| 2952 | else: |
| 2953 | return False |
| 2954 | |
| 2955 | |
| 2956 | def _ClassifyInclude(fileinfo, include, is_system): |
| 2957 | """Figures out what kind of header 'include' is. |
| 2958 | |
| 2959 | Args: |
| 2960 | fileinfo: The current file cpplint is running over. A FileInfo instance. |
| 2961 | include: The path to a #included file. |
| 2962 | is_system: True if the #include used <> rather than "". |
| 2963 | |
| 2964 | Returns: |
| 2965 | One of the _XXX_HEADER constants. |
| 2966 | |
| 2967 | For example: |
| 2968 | >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'stdio.h', True) |
| 2969 | _C_SYS_HEADER |
| 2970 | >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'string', True) |
| 2971 | _CPP_SYS_HEADER |
| 2972 | >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', False) |
| 2973 | _LIKELY_MY_HEADER |
| 2974 | >>> _ClassifyInclude(FileInfo('foo/foo_unknown_extension.cc'), |
| 2975 | ... 'bar/foo_other_ext.h', False) |
| 2976 | _POSSIBLE_MY_HEADER |
| 2977 | >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/bar.h', False) |
| 2978 | _OTHER_HEADER |
| 2979 | """ |
| 2980 | # This is a list of all standard c++ header files, except |
| 2981 | # those already checked for above. |
| 2982 | is_stl_h = include in _STL_HEADERS |
| 2983 | is_cpp_h = is_stl_h or include in _CPP_HEADERS |
| 2984 | |
| 2985 | if is_system: |
| 2986 | if is_cpp_h: |
| 2987 | return _CPP_SYS_HEADER |
| 2988 | else: |
| 2989 | return _C_SYS_HEADER |
| 2990 | |
| 2991 | # If the target file and the include we're checking share a |
| 2992 | # basename when we drop common extensions, and the include |
| 2993 | # lives in . , then it's likely to be owned by the target file. |
| 2994 | target_dir, target_base = ( |
| 2995 | os.path.split(_DropCommonSuffixes(fileinfo.RepositoryName()))) |
| 2996 | include_dir, include_base = os.path.split(_DropCommonSuffixes(include)) |
| 2997 | if target_base == include_base and ( |
| 2998 | include_dir == target_dir or |
| 2999 | include_dir == os.path.normpath(target_dir + '/../public')): |
| 3000 | return _LIKELY_MY_HEADER |
| 3001 | |
| 3002 | # If the target and include share some initial basename |
| 3003 | # component, it's possible the target is implementing the |
| 3004 | # include, so it's allowed to be first, but we'll never |
| 3005 | # complain if it's not there. |
| 3006 | target_first_component = _RE_FIRST_COMPONENT.match(target_base) |
| 3007 | include_first_component = _RE_FIRST_COMPONENT.match(include_base) |
| 3008 | if (target_first_component and include_first_component and |
| 3009 | target_first_component.group(0) == |
| 3010 | include_first_component.group(0)): |
| 3011 | return _POSSIBLE_MY_HEADER |
| 3012 | |
| 3013 | return _OTHER_HEADER |
| 3014 | |
| 3015 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3016 | |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 3017 | def CheckIncludeLine(filename, clean_lines, linenum, include_state, error): |
| 3018 | """Check rules that are applicable to #include lines. |
| 3019 | |
| 3020 | Strings on #include lines are NOT removed from elided line, to make |
| 3021 | certain tasks easier. However, to prevent false positives, checks |
| 3022 | applicable to #include lines in CheckLanguage must be put here. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3023 | |
| 3024 | Args: |
| 3025 | filename: The name of the current file. |
| 3026 | clean_lines: A CleansedLines instance containing the file. |
| 3027 | linenum: The number of the line to check. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3028 | include_state: An _IncludeState instance in which the headers are inserted. |
| 3029 | error: The function to call with any errors found. |
| 3030 | """ |
| 3031 | fileinfo = FileInfo(filename) |
| 3032 | |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 3033 | line = clean_lines.lines[linenum] |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3034 | |
| 3035 | # "include" should use the new style "foo/bar.h" instead of just "bar.h" |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 3036 | if _RE_PATTERN_INCLUDE_NEW_STYLE.search(line): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3037 | error(filename, linenum, 'build/include', 4, |
| 3038 | 'Include the directory when naming .h files') |
| 3039 | |
| 3040 | # we shouldn't include a file more than once. actually, there are a |
| 3041 | # handful of instances where doing so is okay, but in general it's |
| 3042 | # not. |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 3043 | match = _RE_PATTERN_INCLUDE.search(line) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3044 | if match: |
| 3045 | include = match.group(2) |
| 3046 | is_system = (match.group(1) == '<') |
| 3047 | if include in include_state: |
| 3048 | error(filename, linenum, 'build/include', 4, |
| 3049 | '"%s" already included at %s:%s' % |
| 3050 | (include, filename, include_state[include])) |
| 3051 | else: |
| 3052 | include_state[include] = linenum |
| 3053 | |
| 3054 | # We want to ensure that headers appear in the right order: |
| 3055 | # 1) for foo.cc, foo.h (preferred location) |
| 3056 | # 2) c system files |
| 3057 | # 3) cpp system files |
| 3058 | # 4) for foo.cc, foo.h (deprecated location) |
| 3059 | # 5) other google headers |
| 3060 | # |
| 3061 | # We classify each include statement as one of those 5 types |
| 3062 | # using a number of techniques. The include_state object keeps |
| 3063 | # track of the highest type seen, and complains if we see a |
| 3064 | # lower type after that. |
| 3065 | error_message = include_state.CheckNextIncludeOrder( |
| 3066 | _ClassifyInclude(fileinfo, include, is_system)) |
| 3067 | if error_message: |
| 3068 | error(filename, linenum, 'build/include_order', 4, |
| 3069 | '%s. Should be: %s.h, c system, c++ system, other.' % |
| 3070 | (error_message, fileinfo.BaseName())) |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 3071 | if not include_state.IsInAlphabeticalOrder(include): |
| 3072 | error(filename, linenum, 'build/include_alpha', 4, |
| 3073 | 'Include "%s" not in alphabetical order' % include) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3074 | |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 3075 | # Look for any of the stream classes that are part of standard C++. |
| 3076 | match = _RE_PATTERN_INCLUDE.match(line) |
| 3077 | if match: |
| 3078 | include = match.group(2) |
| 3079 | if Match(r'(f|ind|io|i|o|parse|pf|stdio|str|)?stream$', include): |
| 3080 | # Many unit tests use cout, so we exempt them. |
| 3081 | if not _IsTestFilename(filename): |
| 3082 | error(filename, linenum, 'readability/streams', 3, |
| 3083 | 'Streams are highly discouraged.') |
| 3084 | |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 3085 | |
| 3086 | def _GetTextInside(text, start_pattern): |
| 3087 | """Retrieves all the text between matching open and close parentheses. |
| 3088 | |
| 3089 | Given a string of lines and a regular expression string, retrieve all the text |
| 3090 | following the expression and between opening punctuation symbols like |
| 3091 | (, [, or {, and the matching close-punctuation symbol. This properly nested |
| 3092 | occurrences of the punctuations, so for the text like |
| 3093 | printf(a(), b(c())); |
| 3094 | a call to _GetTextInside(text, r'printf\(') will return 'a(), b(c())'. |
| 3095 | start_pattern must match string having an open punctuation symbol at the end. |
| 3096 | |
| 3097 | Args: |
| 3098 | text: The lines to extract text. Its comments and strings must be elided. |
| 3099 | It can be single line and can span multiple lines. |
| 3100 | start_pattern: The regexp string indicating where to start extracting |
| 3101 | the text. |
| 3102 | Returns: |
| 3103 | The extracted text. |
| 3104 | None if either the opening string or ending punctuation could not be found. |
| 3105 | """ |
| 3106 | # TODO(sugawarayu): Audit cpplint.py to see what places could be profitably |
| 3107 | # rewritten to use _GetTextInside (and use inferior regexp matching today). |
| 3108 | |
| 3109 | # Give opening punctuations to get the matching close-punctuations. |
| 3110 | matching_punctuation = {'(': ')', '{': '}', '[': ']'} |
| 3111 | closing_punctuation = set(matching_punctuation.itervalues()) |
| 3112 | |
| 3113 | # Find the position to start extracting text. |
| 3114 | match = re.search(start_pattern, text, re.M) |
| 3115 | if not match: # start_pattern not found in text. |
| 3116 | return None |
| 3117 | start_position = match.end(0) |
| 3118 | |
| 3119 | assert start_position > 0, ( |
| 3120 | 'start_pattern must ends with an opening punctuation.') |
| 3121 | assert text[start_position - 1] in matching_punctuation, ( |
| 3122 | 'start_pattern must ends with an opening punctuation.') |
| 3123 | # Stack of closing punctuations we expect to have in text after position. |
| 3124 | punctuation_stack = [matching_punctuation[text[start_position - 1]]] |
| 3125 | position = start_position |
| 3126 | while punctuation_stack and position < len(text): |
| 3127 | if text[position] == punctuation_stack[-1]: |
| 3128 | punctuation_stack.pop() |
| 3129 | elif text[position] in closing_punctuation: |
| 3130 | # A closing punctuation without matching opening punctuations. |
| 3131 | return None |
| 3132 | elif text[position] in matching_punctuation: |
| 3133 | punctuation_stack.append(matching_punctuation[text[position]]) |
| 3134 | position += 1 |
| 3135 | if punctuation_stack: |
| 3136 | # Opening punctuations left without matching close-punctuations. |
| 3137 | return None |
| 3138 | # punctuations match. |
| 3139 | return text[start_position:position - 1] |
| 3140 | |
| 3141 | |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 3142 | def CheckLanguage(filename, clean_lines, linenum, file_extension, include_state, |
| 3143 | error): |
| 3144 | """Checks rules from the 'C++ language rules' section of cppguide.html. |
| 3145 | |
| 3146 | Some of these rules are hard to test (function overloading, using |
| 3147 | uint32 inappropriately), but we do the best we can. |
| 3148 | |
| 3149 | Args: |
| 3150 | filename: The name of the current file. |
| 3151 | clean_lines: A CleansedLines instance containing the file. |
| 3152 | linenum: The number of the line to check. |
| 3153 | file_extension: The extension (without the dot) of the filename. |
| 3154 | include_state: An _IncludeState instance in which the headers are inserted. |
| 3155 | error: The function to call with any errors found. |
| 3156 | """ |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3157 | # If the line is empty or consists of entirely a comment, no need to |
| 3158 | # check it. |
| 3159 | line = clean_lines.elided[linenum] |
| 3160 | if not line: |
| 3161 | return |
| 3162 | |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 3163 | match = _RE_PATTERN_INCLUDE.search(line) |
| 3164 | if match: |
| 3165 | CheckIncludeLine(filename, clean_lines, linenum, include_state, error) |
| 3166 | return |
| 3167 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3168 | # Create an extended_line, which is the concatenation of the current and |
| 3169 | # next lines, for more effective checking of code that may span more than one |
| 3170 | # line. |
| 3171 | if linenum + 1 < clean_lines.NumLines(): |
| 3172 | extended_line = line + clean_lines.elided[linenum + 1] |
| 3173 | else: |
| 3174 | extended_line = line |
| 3175 | |
| 3176 | # Make Windows paths like Unix. |
| 3177 | fullname = os.path.abspath(filename).replace('\\', '/') |
| 3178 | |
| 3179 | # TODO(unknown): figure out if they're using default arguments in fn proto. |
| 3180 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3181 | # Check for non-const references in functions. This is tricky because & |
| 3182 | # is also used to take the address of something. We allow <> for templates, |
| 3183 | # (ignoring whatever is between the braces) and : for classes. |
| 3184 | # These are complicated re's. They try to capture the following: |
| 3185 | # paren (for fn-prototype start), typename, &, varname. For the const |
| 3186 | # version, we're willing for const to be before typename or after |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 3187 | # Don't check the implementation on same line. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3188 | fnline = line.split('{', 1)[0] |
| 3189 | if (len(re.findall(r'\([^()]*\b(?:[\w:]|<[^()]*>)+(\s?&|&\s?)\w+', fnline)) > |
| 3190 | len(re.findall(r'\([^()]*\bconst\s+(?:typename\s+)?(?:struct\s+)?' |
| 3191 | r'(?:[\w:]|<[^()]*>)+(\s?&|&\s?)\w+', fnline)) + |
| 3192 | len(re.findall(r'\([^()]*\b(?:[\w:]|<[^()]*>)+\s+const(\s?&|&\s?)[\w]+', |
| 3193 | fnline))): |
| 3194 | |
| 3195 | # We allow non-const references in a few standard places, like functions |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 3196 | # called "swap()" or iostream operators like "<<" or ">>". We also filter |
| 3197 | # out for loops, which lint otherwise mistakenly thinks are functions. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3198 | if not Search( |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 3199 | r'(for|swap|Swap|operator[<>][<>])\s*\(\s*' |
| 3200 | r'(?:(?:typename\s*)?[\w:]|<.*>)+\s*&', |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3201 | fnline): |
| 3202 | error(filename, linenum, 'runtime/references', 2, |
| 3203 | 'Is this a non-const reference? ' |
| 3204 | 'If so, make const or use a pointer.') |
| 3205 | |
| 3206 | # Check to see if they're using an conversion function cast. |
| 3207 | # I just try to capture the most common basic types, though there are more. |
| 3208 | # Parameterless conversion functions, such as bool(), are allowed as they are |
| 3209 | # probably a member operator declaration or default constructor. |
| 3210 | match = Search( |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 3211 | r'(\bnew\s+)?\b' # Grab 'new' operator, if it's there |
| 3212 | r'(int|float|double|bool|char|int32|uint32|int64|uint64)\([^)]', line) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3213 | if match: |
| 3214 | # gMock methods are defined using some variant of MOCK_METHODx(name, type) |
| 3215 | # where type may be float(), int(string), etc. Without context they are |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 3216 | # virtually indistinguishable from int(x) casts. Likewise, gMock's |
| 3217 | # MockCallback takes a template parameter of the form return_type(arg_type), |
| 3218 | # which looks much like the cast we're trying to detect. |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 3219 | if (match.group(1) is None and # If new operator, then this isn't a cast |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 3220 | not (Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line) or |
| 3221 | Match(r'^\s*MockCallback<.*>', line))): |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 3222 | # Try a bit harder to catch gmock lines: the only place where |
| 3223 | # something looks like an old-style cast is where we declare the |
| 3224 | # return type of the mocked method, and the only time when we |
| 3225 | # are missing context is if MOCK_METHOD was split across |
| 3226 | # multiple lines (for example http://go/hrfhr ), so we only need |
| 3227 | # to check the previous line for MOCK_METHOD. |
| 3228 | if (linenum == 0 or |
| 3229 | not Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(\S+,\s*$', |
| 3230 | clean_lines.elided[linenum - 1])): |
| 3231 | error(filename, linenum, 'readability/casting', 4, |
| 3232 | 'Using deprecated casting style. ' |
| 3233 | 'Use static_cast<%s>(...) instead' % |
| 3234 | match.group(2)) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3235 | |
| 3236 | CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum], |
| 3237 | 'static_cast', |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 3238 | r'\((int|float|double|bool|char|u?int(16|32|64))\)', error) |
| 3239 | |
| 3240 | # This doesn't catch all cases. Consider (const char * const)"hello". |
| 3241 | # |
| 3242 | # (char *) "foo" should always be a const_cast (reinterpret_cast won't |
| 3243 | # compile). |
| 3244 | if CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum], |
| 3245 | 'const_cast', r'\((char\s?\*+\s?)\)\s*"', error): |
| 3246 | pass |
| 3247 | else: |
| 3248 | # Check pointer casts for other than string constants |
| 3249 | CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum], |
| 3250 | 'reinterpret_cast', r'\((\w+\s?\*+\s?)\)', error) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3251 | |
| 3252 | # In addition, we look for people taking the address of a cast. This |
| 3253 | # is dangerous -- casts can assign to temporaries, so the pointer doesn't |
| 3254 | # point where you think. |
| 3255 | if Search( |
| 3256 | r'(&\([^)]+\)[\w(])|(&(static|dynamic|reinterpret)_cast\b)', line): |
| 3257 | error(filename, linenum, 'runtime/casting', 4, |
| 3258 | ('Are you taking an address of a cast? ' |
| 3259 | 'This is dangerous: could be a temp var. ' |
| 3260 | 'Take the address before doing the cast, rather than after')) |
| 3261 | |
| 3262 | # Check for people declaring static/global STL strings at the top level. |
| 3263 | # This is dangerous because the C++ language does not guarantee that |
| 3264 | # globals with constructors are initialized before the first access. |
| 3265 | match = Match( |
| 3266 | r'((?:|static +)(?:|const +))string +([a-zA-Z0-9_:]+)\b(.*)', |
| 3267 | line) |
| 3268 | # Make sure it's not a function. |
| 3269 | # Function template specialization looks like: "string foo<Type>(...". |
| 3270 | # Class template definitions look like: "string Foo<Type>::Method(...". |
| 3271 | if match and not Match(r'\s*(<.*>)?(::[a-zA-Z0-9_]+)?\s*\(([^"]|$)', |
| 3272 | match.group(3)): |
| 3273 | error(filename, linenum, 'runtime/string', 4, |
| 3274 | 'For a static/global string constant, use a C style string instead: ' |
| 3275 | '"%schar %s[]".' % |
| 3276 | (match.group(1), match.group(2))) |
| 3277 | |
| 3278 | # Check that we're not using RTTI outside of testing code. |
| 3279 | if Search(r'\bdynamic_cast<', line) and not _IsTestFilename(filename): |
| 3280 | error(filename, linenum, 'runtime/rtti', 5, |
| 3281 | 'Do not use dynamic_cast<>. If you need to cast within a class ' |
| 3282 | "hierarchy, use static_cast<> to upcast. Google doesn't support " |
| 3283 | 'RTTI.') |
| 3284 | |
| 3285 | if Search(r'\b([A-Za-z0-9_]*_)\(\1\)', line): |
| 3286 | error(filename, linenum, 'runtime/init', 4, |
| 3287 | 'You seem to be initializing a member variable with itself.') |
| 3288 | |
| 3289 | if file_extension == 'h': |
| 3290 | # TODO(unknown): check that 1-arg constructors are explicit. |
| 3291 | # How to tell it's a constructor? |
| 3292 | # (handled in CheckForNonStandardConstructs for now) |
| 3293 | # TODO(unknown): check that classes have DISALLOW_EVIL_CONSTRUCTORS |
| 3294 | # (level 1 error) |
| 3295 | pass |
| 3296 | |
| 3297 | # Check if people are using the verboten C basic types. The only exception |
| 3298 | # we regularly allow is "unsigned short port" for port. |
| 3299 | if Search(r'\bshort port\b', line): |
| 3300 | if not Search(r'\bunsigned short port\b', line): |
| 3301 | error(filename, linenum, 'runtime/int', 4, |
| 3302 | 'Use "unsigned short" for ports, not "short"') |
| 3303 | else: |
| 3304 | match = Search(r'\b(short|long(?! +double)|long long)\b', line) |
| 3305 | if match: |
| 3306 | error(filename, linenum, 'runtime/int', 4, |
| 3307 | 'Use int16/int64/etc, rather than the C type %s' % match.group(1)) |
| 3308 | |
| 3309 | # When snprintf is used, the second argument shouldn't be a literal. |
| 3310 | match = Search(r'snprintf\s*\(([^,]*),\s*([0-9]*)\s*,', line) |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 3311 | if match and match.group(2) != '0': |
| 3312 | # If 2nd arg is zero, snprintf is used to calculate size. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3313 | error(filename, linenum, 'runtime/printf', 3, |
| 3314 | 'If you can, use sizeof(%s) instead of %s as the 2nd arg ' |
| 3315 | 'to snprintf.' % (match.group(1), match.group(2))) |
| 3316 | |
| 3317 | # Check if some verboten C functions are being used. |
| 3318 | if Search(r'\bsprintf\b', line): |
| 3319 | error(filename, linenum, 'runtime/printf', 5, |
| 3320 | 'Never use sprintf. Use snprintf instead.') |
| 3321 | match = Search(r'\b(strcpy|strcat)\b', line) |
| 3322 | if match: |
| 3323 | error(filename, linenum, 'runtime/printf', 4, |
| 3324 | 'Almost always, snprintf is better than %s' % match.group(1)) |
| 3325 | |
| 3326 | if Search(r'\bsscanf\b', line): |
| 3327 | error(filename, linenum, 'runtime/printf', 1, |
| 3328 | 'sscanf can be ok, but is slow and can overflow buffers.') |
| 3329 | |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 3330 | # Check if some verboten operator overloading is going on |
| 3331 | # TODO(unknown): catch out-of-line unary operator&: |
| 3332 | # class X {}; |
| 3333 | # int operator&(const X& x) { return 42; } // unary operator& |
| 3334 | # The trick is it's hard to tell apart from binary operator&: |
| 3335 | # class Y { int operator&(const Y& x) { return 23; } }; // binary operator& |
| 3336 | if Search(r'\boperator\s*&\s*\(\s*\)', line): |
| 3337 | error(filename, linenum, 'runtime/operator', 4, |
| 3338 | 'Unary operator& is dangerous. Do not use it.') |
| 3339 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3340 | # Check for suspicious usage of "if" like |
| 3341 | # } if (a == b) { |
| 3342 | if Search(r'\}\s*if\s*\(', line): |
| 3343 | error(filename, linenum, 'readability/braces', 4, |
| 3344 | 'Did you mean "else if"? If not, start a new line for "if".') |
| 3345 | |
| 3346 | # Check for potential format string bugs like printf(foo). |
| 3347 | # We constrain the pattern not to pick things like DocidForPrintf(foo). |
| 3348 | # Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str()) |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 3349 | # TODO(sugawarayu): Catch the following case. Need to change the calling |
| 3350 | # convention of the whole function to process multiple line to handle it. |
| 3351 | # printf( |
| 3352 | # boy_this_is_a_really_long_variable_that_cannot_fit_on_the_prev_line); |
| 3353 | printf_args = _GetTextInside(line, r'(?i)\b(string)?printf\s*\(') |
| 3354 | if printf_args: |
| 3355 | match = Match(r'([\w.\->()]+)$', printf_args) |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 3356 | if match and match.group(1) != '__VA_ARGS__': |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 3357 | function_name = re.search(r'\b((?:string)?printf)\s*\(', |
| 3358 | line, re.I).group(1) |
| 3359 | error(filename, linenum, 'runtime/printf', 4, |
| 3360 | 'Potential format string bug. Do %s("%%s", %s) instead.' |
| 3361 | % (function_name, match.group(1))) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3362 | |
| 3363 | # Check for potential memset bugs like memset(buf, sizeof(buf), 0). |
| 3364 | match = Search(r'memset\s*\(([^,]*),\s*([^,]*),\s*0\s*\)', line) |
| 3365 | if match and not Match(r"^''|-?[0-9]+|0x[0-9A-Fa-f]$", match.group(2)): |
| 3366 | error(filename, linenum, 'runtime/memset', 4, |
| 3367 | 'Did you mean "memset(%s, 0, %s)"?' |
| 3368 | % (match.group(1), match.group(2))) |
| 3369 | |
| 3370 | if Search(r'\busing namespace\b', line): |
| 3371 | error(filename, linenum, 'build/namespaces', 5, |
| 3372 | 'Do not use namespace using-directives. ' |
| 3373 | 'Use using-declarations instead.') |
| 3374 | |
| 3375 | # Detect variable-length arrays. |
| 3376 | match = Match(r'\s*(.+::)?(\w+) [a-z]\w*\[(.+)];', line) |
| 3377 | if (match and match.group(2) != 'return' and match.group(2) != 'delete' and |
| 3378 | match.group(3).find(']') == -1): |
| 3379 | # Split the size using space and arithmetic operators as delimiters. |
| 3380 | # If any of the resulting tokens are not compile time constants then |
| 3381 | # report the error. |
| 3382 | tokens = re.split(r'\s|\+|\-|\*|\/|<<|>>]', match.group(3)) |
| 3383 | is_const = True |
| 3384 | skip_next = False |
| 3385 | for tok in tokens: |
| 3386 | if skip_next: |
| 3387 | skip_next = False |
| 3388 | continue |
| 3389 | |
| 3390 | if Search(r'sizeof\(.+\)', tok): continue |
| 3391 | if Search(r'arraysize\(\w+\)', tok): continue |
| 3392 | |
| 3393 | tok = tok.lstrip('(') |
| 3394 | tok = tok.rstrip(')') |
| 3395 | if not tok: continue |
| 3396 | if Match(r'\d+', tok): continue |
| 3397 | if Match(r'0[xX][0-9a-fA-F]+', tok): continue |
| 3398 | if Match(r'k[A-Z0-9]\w*', tok): continue |
| 3399 | if Match(r'(.+::)?k[A-Z0-9]\w*', tok): continue |
| 3400 | if Match(r'(.+::)?[A-Z][A-Z0-9_]*', tok): continue |
| 3401 | # A catch all for tricky sizeof cases, including 'sizeof expression', |
| 3402 | # 'sizeof(*type)', 'sizeof(const type)', 'sizeof(struct StructName)' |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 3403 | # requires skipping the next token because we split on ' ' and '*'. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3404 | if tok.startswith('sizeof'): |
| 3405 | skip_next = True |
| 3406 | continue |
| 3407 | is_const = False |
| 3408 | break |
| 3409 | if not is_const: |
| 3410 | error(filename, linenum, 'runtime/arrays', 1, |
| 3411 | 'Do not use variable-length arrays. Use an appropriately named ' |
| 3412 | "('k' followed by CamelCase) compile-time constant for the size.") |
| 3413 | |
| 3414 | # If DISALLOW_EVIL_CONSTRUCTORS, DISALLOW_COPY_AND_ASSIGN, or |
| 3415 | # DISALLOW_IMPLICIT_CONSTRUCTORS is present, then it should be the last thing |
| 3416 | # in the class declaration. |
| 3417 | match = Match( |
| 3418 | (r'\s*' |
| 3419 | r'(DISALLOW_(EVIL_CONSTRUCTORS|COPY_AND_ASSIGN|IMPLICIT_CONSTRUCTORS))' |
| 3420 | r'\(.*\);$'), |
| 3421 | line) |
| 3422 | if match and linenum + 1 < clean_lines.NumLines(): |
| 3423 | next_line = clean_lines.elided[linenum + 1] |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 3424 | # We allow some, but not all, declarations of variables to be present |
| 3425 | # in the statement that defines the class. The [\w\*,\s]* fragment of |
| 3426 | # the regular expression below allows users to declare instances of |
| 3427 | # the class or pointers to instances, but not less common types such |
| 3428 | # as function pointers or arrays. It's a tradeoff between allowing |
| 3429 | # reasonable code and avoiding trying to parse more C++ using regexps. |
| 3430 | if not Search(r'^\s*}[\w\*,\s]*;', next_line): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3431 | error(filename, linenum, 'readability/constructors', 3, |
| 3432 | match.group(1) + ' should be the last thing in the class') |
| 3433 | |
| 3434 | # Check for use of unnamed namespaces in header files. Registration |
| 3435 | # macros are typically OK, so we allow use of "namespace {" on lines |
| 3436 | # that end with backslashes. |
| 3437 | if (file_extension == 'h' |
| 3438 | and Search(r'\bnamespace\s*{', line) |
| 3439 | and line[-1] != '\\'): |
| 3440 | error(filename, linenum, 'build/namespaces', 4, |
| 3441 | 'Do not use unnamed namespaces in header files. See ' |
| 3442 | 'http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces' |
| 3443 | ' for more information.') |
| 3444 | |
| 3445 | |
| 3446 | def CheckCStyleCast(filename, linenum, line, raw_line, cast_type, pattern, |
| 3447 | error): |
| 3448 | """Checks for a C-style cast by looking for the pattern. |
| 3449 | |
| 3450 | This also handles sizeof(type) warnings, due to similarity of content. |
| 3451 | |
| 3452 | Args: |
| 3453 | filename: The name of the current file. |
| 3454 | linenum: The number of the line to check. |
| 3455 | line: The line of code to check. |
| 3456 | raw_line: The raw line of code to check, with comments. |
| 3457 | cast_type: The string for the C++ cast to recommend. This is either |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 3458 | reinterpret_cast, static_cast, or const_cast, depending. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3459 | pattern: The regular expression used to find C-style casts. |
| 3460 | error: The function to call with any errors found. |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 3461 | |
| 3462 | Returns: |
| 3463 | True if an error was emitted. |
| 3464 | False otherwise. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3465 | """ |
| 3466 | match = Search(pattern, line) |
| 3467 | if not match: |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 3468 | return False |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3469 | |
| 3470 | # e.g., sizeof(int) |
| 3471 | sizeof_match = Match(r'.*sizeof\s*$', line[0:match.start(1) - 1]) |
| 3472 | if sizeof_match: |
| 3473 | error(filename, linenum, 'runtime/sizeof', 1, |
| 3474 | 'Using sizeof(type). Use sizeof(varname) instead if possible') |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 3475 | return True |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3476 | |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 3477 | # operator++(int) and operator--(int) |
| 3478 | if (line[0:match.start(1) - 1].endswith(' operator++') or |
| 3479 | line[0:match.start(1) - 1].endswith(' operator--')): |
| 3480 | return False |
| 3481 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3482 | remainder = line[match.end(0):] |
| 3483 | |
| 3484 | # The close paren is for function pointers as arguments to a function. |
| 3485 | # eg, void foo(void (*bar)(int)); |
| 3486 | # The semicolon check is a more basic function check; also possibly a |
| 3487 | # function pointer typedef. |
| 3488 | # eg, void foo(int); or void foo(int) const; |
| 3489 | # The equals check is for function pointer assignment. |
| 3490 | # eg, void *(*foo)(int) = ... |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 3491 | # The > is for MockCallback<...> ... |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3492 | # |
| 3493 | # Right now, this will only catch cases where there's a single argument, and |
| 3494 | # it's unnamed. It should probably be expanded to check for multiple |
| 3495 | # arguments with some unnamed. |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 3496 | function_match = Match(r'\s*(\)|=|(const)?\s*(;|\{|throw\(\)|>))', remainder) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3497 | if function_match: |
| 3498 | if (not function_match.group(3) or |
| 3499 | function_match.group(3) == ';' or |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 3500 | ('MockCallback<' not in raw_line and |
| 3501 | '/*' not in raw_line)): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3502 | error(filename, linenum, 'readability/function', 3, |
| 3503 | 'All parameters should be named in a function') |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 3504 | return True |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3505 | |
| 3506 | # At this point, all that should be left is actual casts. |
| 3507 | error(filename, linenum, 'readability/casting', 4, |
| 3508 | 'Using C-style cast. Use %s<%s>(...) instead' % |
| 3509 | (cast_type, match.group(1))) |
| 3510 | |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 3511 | return True |
| 3512 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3513 | |
| 3514 | _HEADERS_CONTAINING_TEMPLATES = ( |
| 3515 | ('<deque>', ('deque',)), |
| 3516 | ('<functional>', ('unary_function', 'binary_function', |
| 3517 | 'plus', 'minus', 'multiplies', 'divides', 'modulus', |
| 3518 | 'negate', |
| 3519 | 'equal_to', 'not_equal_to', 'greater', 'less', |
| 3520 | 'greater_equal', 'less_equal', |
| 3521 | 'logical_and', 'logical_or', 'logical_not', |
| 3522 | 'unary_negate', 'not1', 'binary_negate', 'not2', |
| 3523 | 'bind1st', 'bind2nd', |
| 3524 | 'pointer_to_unary_function', |
| 3525 | 'pointer_to_binary_function', |
| 3526 | 'ptr_fun', |
| 3527 | 'mem_fun_t', 'mem_fun', 'mem_fun1_t', 'mem_fun1_ref_t', |
| 3528 | 'mem_fun_ref_t', |
| 3529 | 'const_mem_fun_t', 'const_mem_fun1_t', |
| 3530 | 'const_mem_fun_ref_t', 'const_mem_fun1_ref_t', |
| 3531 | 'mem_fun_ref', |
| 3532 | )), |
| 3533 | ('<limits>', ('numeric_limits',)), |
| 3534 | ('<list>', ('list',)), |
| 3535 | ('<map>', ('map', 'multimap',)), |
| 3536 | ('<memory>', ('allocator',)), |
| 3537 | ('<queue>', ('queue', 'priority_queue',)), |
| 3538 | ('<set>', ('set', 'multiset',)), |
| 3539 | ('<stack>', ('stack',)), |
| 3540 | ('<string>', ('char_traits', 'basic_string',)), |
| 3541 | ('<utility>', ('pair',)), |
| 3542 | ('<vector>', ('vector',)), |
| 3543 | |
| 3544 | # gcc extensions. |
| 3545 | # Note: std::hash is their hash, ::hash is our hash |
| 3546 | ('<hash_map>', ('hash_map', 'hash_multimap',)), |
| 3547 | ('<hash_set>', ('hash_set', 'hash_multiset',)), |
| 3548 | ('<slist>', ('slist',)), |
| 3549 | ) |
| 3550 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3551 | _RE_PATTERN_STRING = re.compile(r'\bstring\b') |
| 3552 | |
| 3553 | _re_pattern_algorithm_header = [] |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 3554 | for _template in ('copy', 'max', 'min', 'min_element', 'sort', 'swap', |
| 3555 | 'transform'): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3556 | # Match max<type>(..., ...), max(..., ...), but not foo->max, foo.max or |
| 3557 | # type::max(). |
| 3558 | _re_pattern_algorithm_header.append( |
| 3559 | (re.compile(r'[^>.]\b' + _template + r'(<.*?>)?\([^\)]'), |
| 3560 | _template, |
| 3561 | '<algorithm>')) |
| 3562 | |
| 3563 | _re_pattern_templates = [] |
| 3564 | for _header, _templates in _HEADERS_CONTAINING_TEMPLATES: |
| 3565 | for _template in _templates: |
| 3566 | _re_pattern_templates.append( |
| 3567 | (re.compile(r'(\<|\b)' + _template + r'\s*\<'), |
| 3568 | _template + '<>', |
| 3569 | _header)) |
| 3570 | |
| 3571 | |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 3572 | def FilesBelongToSameModule(filename_cc, filename_h): |
| 3573 | """Check if these two filenames belong to the same module. |
| 3574 | |
| 3575 | The concept of a 'module' here is a as follows: |
| 3576 | foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the |
| 3577 | same 'module' if they are in the same directory. |
| 3578 | some/path/public/xyzzy and some/path/internal/xyzzy are also considered |
| 3579 | to belong to the same module here. |
| 3580 | |
| 3581 | If the filename_cc contains a longer path than the filename_h, for example, |
| 3582 | '/absolute/path/to/base/sysinfo.cc', and this file would include |
| 3583 | 'base/sysinfo.h', this function also produces the prefix needed to open the |
| 3584 | header. This is used by the caller of this function to more robustly open the |
| 3585 | header file. We don't have access to the real include paths in this context, |
| 3586 | so we need this guesswork here. |
| 3587 | |
| 3588 | Known bugs: tools/base/bar.cc and base/bar.h belong to the same module |
| 3589 | according to this implementation. Because of this, this function gives |
| 3590 | some false positives. This should be sufficiently rare in practice. |
| 3591 | |
| 3592 | Args: |
| 3593 | filename_cc: is the path for the .cc file |
| 3594 | filename_h: is the path for the header path |
| 3595 | |
| 3596 | Returns: |
| 3597 | Tuple with a bool and a string: |
| 3598 | bool: True if filename_cc and filename_h belong to the same module. |
| 3599 | string: the additional prefix needed to open the header file. |
| 3600 | """ |
| 3601 | |
| 3602 | if not filename_cc.endswith('.cc'): |
| 3603 | return (False, '') |
| 3604 | filename_cc = filename_cc[:-len('.cc')] |
| 3605 | if filename_cc.endswith('_unittest'): |
| 3606 | filename_cc = filename_cc[:-len('_unittest')] |
| 3607 | elif filename_cc.endswith('_test'): |
| 3608 | filename_cc = filename_cc[:-len('_test')] |
| 3609 | filename_cc = filename_cc.replace('/public/', '/') |
| 3610 | filename_cc = filename_cc.replace('/internal/', '/') |
| 3611 | |
| 3612 | if not filename_h.endswith('.h'): |
| 3613 | return (False, '') |
| 3614 | filename_h = filename_h[:-len('.h')] |
| 3615 | if filename_h.endswith('-inl'): |
| 3616 | filename_h = filename_h[:-len('-inl')] |
| 3617 | filename_h = filename_h.replace('/public/', '/') |
| 3618 | filename_h = filename_h.replace('/internal/', '/') |
| 3619 | |
| 3620 | files_belong_to_same_module = filename_cc.endswith(filename_h) |
| 3621 | common_path = '' |
| 3622 | if files_belong_to_same_module: |
| 3623 | common_path = filename_cc[:-len(filename_h)] |
| 3624 | return files_belong_to_same_module, common_path |
| 3625 | |
| 3626 | |
| 3627 | def UpdateIncludeState(filename, include_state, io=codecs): |
| 3628 | """Fill up the include_state with new includes found from the file. |
| 3629 | |
| 3630 | Args: |
| 3631 | filename: the name of the header to read. |
| 3632 | include_state: an _IncludeState instance in which the headers are inserted. |
| 3633 | io: The io factory to use to read the file. Provided for testability. |
| 3634 | |
| 3635 | Returns: |
| 3636 | True if a header was succesfully added. False otherwise. |
| 3637 | """ |
| 3638 | headerfile = None |
| 3639 | try: |
| 3640 | headerfile = io.open(filename, 'r', 'utf8', 'replace') |
| 3641 | except IOError: |
| 3642 | return False |
| 3643 | linenum = 0 |
| 3644 | for line in headerfile: |
| 3645 | linenum += 1 |
| 3646 | clean_line = CleanseComments(line) |
| 3647 | match = _RE_PATTERN_INCLUDE.search(clean_line) |
| 3648 | if match: |
| 3649 | include = match.group(2) |
| 3650 | # The value formatting is cute, but not really used right now. |
| 3651 | # What matters here is that the key is in include_state. |
| 3652 | include_state.setdefault(include, '%s:%d' % (filename, linenum)) |
| 3653 | return True |
| 3654 | |
| 3655 | |
| 3656 | def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error, |
| 3657 | io=codecs): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3658 | """Reports for missing stl includes. |
| 3659 | |
| 3660 | This function will output warnings to make sure you are including the headers |
| 3661 | necessary for the stl containers and functions that you use. We only give one |
| 3662 | reason to include a header. For example, if you use both equal_to<> and |
| 3663 | less<> in a .h file, only one (the latter in the file) of these will be |
| 3664 | reported as a reason to include the <functional>. |
| 3665 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3666 | Args: |
| 3667 | filename: The name of the current file. |
| 3668 | clean_lines: A CleansedLines instance containing the file. |
| 3669 | include_state: An _IncludeState instance. |
| 3670 | error: The function to call with any errors found. |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 3671 | io: The IO factory to use to read the header file. Provided for unittest |
| 3672 | injection. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3673 | """ |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3674 | required = {} # A map of header name to linenumber and the template entity. |
| 3675 | # Example of required: { '<functional>': (1219, 'less<>') } |
| 3676 | |
| 3677 | for linenum in xrange(clean_lines.NumLines()): |
| 3678 | line = clean_lines.elided[linenum] |
| 3679 | if not line or line[0] == '#': |
| 3680 | continue |
| 3681 | |
| 3682 | # String is special -- it is a non-templatized type in STL. |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 3683 | matched = _RE_PATTERN_STRING.search(line) |
| 3684 | if matched: |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 3685 | # Don't warn about strings in non-STL namespaces: |
| 3686 | # (We check only the first match per line; good enough.) |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 3687 | prefix = line[:matched.start()] |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 3688 | if prefix.endswith('std::') or not prefix.endswith('::'): |
| 3689 | required['<string>'] = (linenum, 'string') |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3690 | |
| 3691 | for pattern, template, header in _re_pattern_algorithm_header: |
| 3692 | if pattern.search(line): |
| 3693 | required[header] = (linenum, template) |
| 3694 | |
| 3695 | # The following function is just a speed up, no semantics are changed. |
| 3696 | if not '<' in line: # Reduces the cpu time usage by skipping lines. |
| 3697 | continue |
| 3698 | |
| 3699 | for pattern, template, header in _re_pattern_templates: |
| 3700 | if pattern.search(line): |
| 3701 | required[header] = (linenum, template) |
| 3702 | |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 3703 | # The policy is that if you #include something in foo.h you don't need to |
| 3704 | # include it again in foo.cc. Here, we will look at possible includes. |
| 3705 | # Let's copy the include_state so it is only messed up within this function. |
| 3706 | include_state = include_state.copy() |
| 3707 | |
| 3708 | # Did we find the header for this file (if any) and succesfully load it? |
| 3709 | header_found = False |
| 3710 | |
| 3711 | # Use the absolute path so that matching works properly. |
[email protected] | 8f92756 | 2012-01-30 19:51:28 | [diff] [blame] | 3712 | abs_filename = FileInfo(filename).FullName() |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 3713 | |
| 3714 | # For Emacs's flymake. |
| 3715 | # If cpplint is invoked from Emacs's flymake, a temporary file is generated |
| 3716 | # by flymake and that file name might end with '_flymake.cc'. In that case, |
| 3717 | # restore original file name here so that the corresponding header file can be |
| 3718 | # found. |
| 3719 | # e.g. If the file name is 'foo_flymake.cc', we should search for 'foo.h' |
| 3720 | # instead of 'foo_flymake.h' |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 3721 | abs_filename = re.sub(r'_flymake\.cc$', '.cc', abs_filename) |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 3722 | |
| 3723 | # include_state is modified during iteration, so we iterate over a copy of |
| 3724 | # the keys. |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 3725 | header_keys = include_state.keys() |
| 3726 | for header in header_keys: |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 3727 | (same_module, common_path) = FilesBelongToSameModule(abs_filename, header) |
| 3728 | fullpath = common_path + header |
| 3729 | if same_module and UpdateIncludeState(fullpath, include_state, io): |
| 3730 | header_found = True |
| 3731 | |
| 3732 | # If we can't find the header file for a .cc, assume it's because we don't |
| 3733 | # know where to look. In that case we'll give up as we're not sure they |
| 3734 | # didn't include it in the .h file. |
| 3735 | # TODO(unknown): Do a better job of finding .h files so we are confident that |
| 3736 | # not having the .h file means there isn't one. |
| 3737 | if filename.endswith('.cc') and not header_found: |
| 3738 | return |
| 3739 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3740 | # All the lines have been processed, report the errors found. |
| 3741 | for required_header_unstripped in required: |
| 3742 | template = required[required_header_unstripped][1] |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3743 | if required_header_unstripped.strip('<>"') not in include_state: |
| 3744 | error(filename, required[required_header_unstripped][0], |
| 3745 | 'build/include_what_you_use', 4, |
| 3746 | 'Add #include ' + required_header_unstripped + ' for ' + template) |
| 3747 | |
| 3748 | |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 3749 | _RE_PATTERN_EXPLICIT_MAKEPAIR = re.compile(r'\bmake_pair\s*<') |
| 3750 | |
| 3751 | |
| 3752 | def CheckMakePairUsesDeduction(filename, clean_lines, linenum, error): |
| 3753 | """Check that make_pair's template arguments are deduced. |
| 3754 | |
| 3755 | G++ 4.6 in C++0x mode fails badly if make_pair's template arguments are |
| 3756 | specified explicitly, and such use isn't intended in any case. |
| 3757 | |
| 3758 | Args: |
| 3759 | filename: The name of the current file. |
| 3760 | clean_lines: A CleansedLines instance containing the file. |
| 3761 | linenum: The number of the line to check. |
| 3762 | error: The function to call with any errors found. |
| 3763 | """ |
| 3764 | raw = clean_lines.raw_lines |
| 3765 | line = raw[linenum] |
| 3766 | match = _RE_PATTERN_EXPLICIT_MAKEPAIR.search(line) |
| 3767 | if match: |
| 3768 | error(filename, linenum, 'build/explicit_make_pair', |
| 3769 | 4, # 4 = high confidence |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 3770 | 'For C++11-compatibility, omit template arguments from make_pair' |
| 3771 | ' OR use pair directly OR if appropriate, construct a pair directly') |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 3772 | |
| 3773 | |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 3774 | def ProcessLine(filename, file_extension, clean_lines, line, |
| 3775 | include_state, function_state, nesting_state, error, |
| 3776 | extra_check_functions=[]): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3777 | """Processes a single line in the file. |
| 3778 | |
| 3779 | Args: |
| 3780 | filename: Filename of the file that is being processed. |
| 3781 | file_extension: The extension (dot not included) of the file. |
| 3782 | clean_lines: An array of strings, each representing a line of the file, |
| 3783 | with comments stripped. |
| 3784 | line: Number of line being processed. |
| 3785 | include_state: An _IncludeState instance in which the headers are inserted. |
| 3786 | function_state: A _FunctionState instance which counts function lines, etc. |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 3787 | nesting_state: A _NestingState instance which maintains information about |
| 3788 | the current stack of nested blocks being parsed. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3789 | error: A callable to which errors are reported, which takes 4 arguments: |
| 3790 | filename, line number, error level, and message |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 3791 | extra_check_functions: An array of additional check functions that will be |
| 3792 | run on each source line. Each function takes 4 |
| 3793 | arguments: filename, clean_lines, line, error |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3794 | """ |
| 3795 | raw_lines = clean_lines.raw_lines |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 3796 | ParseNolintSuppressions(filename, raw_lines[line], line, error) |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 3797 | nesting_state.Update(filename, clean_lines, line, error) |
| 3798 | if nesting_state.stack and nesting_state.stack[-1].inline_asm != _NO_ASM: |
| 3799 | return |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3800 | CheckForFunctionLengths(filename, clean_lines, line, function_state, error) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3801 | CheckForMultilineCommentsAndStrings(filename, clean_lines, line, error) |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 3802 | CheckStyle(filename, clean_lines, line, file_extension, nesting_state, error) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3803 | CheckLanguage(filename, clean_lines, line, file_extension, include_state, |
| 3804 | error) |
| 3805 | CheckForNonStandardConstructs(filename, clean_lines, line, |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 3806 | nesting_state, error) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3807 | CheckPosixThreading(filename, clean_lines, line, error) |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 3808 | CheckInvalidIncrement(filename, clean_lines, line, error) |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 3809 | CheckMakePairUsesDeduction(filename, clean_lines, line, error) |
| 3810 | for check_fn in extra_check_functions: |
| 3811 | check_fn(filename, clean_lines, line, error) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3812 | |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 3813 | def ProcessFileData(filename, file_extension, lines, error, |
| 3814 | extra_check_functions=[]): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3815 | """Performs lint checks and reports any errors to the given error function. |
| 3816 | |
| 3817 | Args: |
| 3818 | filename: Filename of the file that is being processed. |
| 3819 | file_extension: The extension (dot not included) of the file. |
| 3820 | lines: An array of strings, each representing a line of the file, with the |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 3821 | last element being empty if the file is terminated with a newline. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3822 | error: A callable to which errors are reported, which takes 4 arguments: |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 3823 | filename, line number, error level, and message |
| 3824 | extra_check_functions: An array of additional check functions that will be |
| 3825 | run on each source line. Each function takes 4 |
| 3826 | arguments: filename, clean_lines, line, error |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3827 | """ |
| 3828 | lines = (['// marker so line numbers and indices both start at 1'] + lines + |
| 3829 | ['// marker so line numbers end in a known way']) |
| 3830 | |
| 3831 | include_state = _IncludeState() |
| 3832 | function_state = _FunctionState() |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 3833 | nesting_state = _NestingState() |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3834 | |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 3835 | ResetNolintSuppressions() |
| 3836 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3837 | CheckForCopyright(filename, lines, error) |
| 3838 | |
| 3839 | if file_extension == 'h': |
| 3840 | CheckForHeaderGuard(filename, lines, error) |
| 3841 | |
| 3842 | RemoveMultiLineComments(filename, lines, error) |
| 3843 | clean_lines = CleansedLines(lines) |
| 3844 | for line in xrange(clean_lines.NumLines()): |
| 3845 | ProcessLine(filename, file_extension, clean_lines, line, |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 3846 | include_state, function_state, nesting_state, error, |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 3847 | extra_check_functions) |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 3848 | nesting_state.CheckClassFinished(filename, error) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3849 | |
| 3850 | CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error) |
| 3851 | |
| 3852 | # We check here rather than inside ProcessLine so that we see raw |
| 3853 | # lines rather than "cleaned" lines. |
| 3854 | CheckForUnicodeReplacementCharacters(filename, lines, error) |
| 3855 | |
| 3856 | CheckForNewlineAtEOF(filename, lines, error) |
| 3857 | |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 3858 | def ProcessFile(filename, vlevel, extra_check_functions=[]): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3859 | """Does google-lint on a single file. |
| 3860 | |
| 3861 | Args: |
| 3862 | filename: The name of the file to parse. |
| 3863 | |
| 3864 | vlevel: The level of errors to report. Every error of confidence |
| 3865 | >= verbose_level will be reported. 0 is a good default. |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 3866 | |
| 3867 | extra_check_functions: An array of additional check functions that will be |
| 3868 | run on each source line. Each function takes 4 |
| 3869 | arguments: filename, clean_lines, line, error |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3870 | """ |
| 3871 | |
| 3872 | _SetVerboseLevel(vlevel) |
| 3873 | |
| 3874 | try: |
| 3875 | # Support the UNIX convention of using "-" for stdin. Note that |
| 3876 | # we are not opening the file with universal newline support |
| 3877 | # (which codecs doesn't support anyway), so the resulting lines do |
| 3878 | # contain trailing '\r' characters if we are reading a file that |
| 3879 | # has CRLF endings. |
| 3880 | # If after the split a trailing '\r' is present, it is removed |
| 3881 | # below. If it is not expected to be present (i.e. os.linesep != |
| 3882 | # '\r\n' as in Windows), a warning is issued below if this file |
| 3883 | # is processed. |
| 3884 | |
| 3885 | if filename == '-': |
| 3886 | lines = codecs.StreamReaderWriter(sys.stdin, |
| 3887 | codecs.getreader('utf8'), |
| 3888 | codecs.getwriter('utf8'), |
| 3889 | 'replace').read().split('\n') |
| 3890 | else: |
| 3891 | lines = codecs.open(filename, 'r', 'utf8', 'replace').read().split('\n') |
| 3892 | |
| 3893 | carriage_return_found = False |
| 3894 | # Remove trailing '\r'. |
| 3895 | for linenum in range(len(lines)): |
| 3896 | if lines[linenum].endswith('\r'): |
| 3897 | lines[linenum] = lines[linenum].rstrip('\r') |
| 3898 | carriage_return_found = True |
| 3899 | |
| 3900 | except IOError: |
| 3901 | sys.stderr.write( |
| 3902 | "Skipping input '%s': Can't open for reading\n" % filename) |
| 3903 | return |
| 3904 | |
| 3905 | # Note, if no dot is found, this will give the entire filename as the ext. |
| 3906 | file_extension = filename[filename.rfind('.') + 1:] |
| 3907 | |
| 3908 | # When reading from stdin, the extension is unknown, so no cpplint tests |
| 3909 | # should rely on the extension. |
| 3910 | if (filename != '-' and file_extension != 'cc' and file_extension != 'h' |
| 3911 | and file_extension != 'cpp'): |
| 3912 | sys.stderr.write('Ignoring %s; not a .cc or .h file\n' % filename) |
| 3913 | else: |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 3914 | ProcessFileData(filename, file_extension, lines, Error, |
| 3915 | extra_check_functions) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3916 | if carriage_return_found and os.linesep != '\r\n': |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 3917 | # Use 0 for linenum since outputting only one error for potentially |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3918 | # several lines. |
| 3919 | Error(filename, 0, 'whitespace/newline', 1, |
| 3920 | 'One or more unexpected \\r (^M) found;' |
| 3921 | 'better to use only a \\n') |
| 3922 | |
| 3923 | sys.stderr.write('Done processing %s\n' % filename) |
| 3924 | |
| 3925 | |
| 3926 | def PrintUsage(message): |
| 3927 | """Prints a brief usage string and exits, optionally with an error message. |
| 3928 | |
| 3929 | Args: |
| 3930 | message: The optional error message. |
| 3931 | """ |
| 3932 | sys.stderr.write(_USAGE) |
| 3933 | if message: |
| 3934 | sys.exit('\nFATAL ERROR: ' + message) |
| 3935 | else: |
| 3936 | sys.exit(1) |
| 3937 | |
| 3938 | |
| 3939 | def PrintCategories(): |
| 3940 | """Prints a list of all the error-categories used by error messages. |
| 3941 | |
| 3942 | These are the categories used to filter messages via --filter. |
| 3943 | """ |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 3944 | sys.stderr.write(''.join(' %s\n' % cat for cat in _ERROR_CATEGORIES)) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3945 | sys.exit(0) |
| 3946 | |
| 3947 | |
| 3948 | def ParseArguments(args): |
| 3949 | """Parses the command line arguments. |
| 3950 | |
| 3951 | This may set the output format and verbosity level as side-effects. |
| 3952 | |
| 3953 | Args: |
| 3954 | args: The command line arguments: |
| 3955 | |
| 3956 | Returns: |
| 3957 | The list of filenames to lint. |
| 3958 | """ |
| 3959 | try: |
| 3960 | (opts, filenames) = getopt.getopt(args, '', ['help', 'output=', 'verbose=', |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 3961 | 'counting=', |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 3962 | 'filter=', |
| 3963 | 'root=']) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3964 | except getopt.GetoptError: |
| 3965 | PrintUsage('Invalid arguments.') |
| 3966 | |
| 3967 | verbosity = _VerboseLevel() |
| 3968 | output_format = _OutputFormat() |
| 3969 | filters = '' |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 3970 | counting_style = '' |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3971 | |
| 3972 | for (opt, val) in opts: |
| 3973 | if opt == '--help': |
| 3974 | PrintUsage(None) |
| 3975 | elif opt == '--output': |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 3976 | if not val in ('emacs', 'vs7', 'eclipse'): |
| 3977 | PrintUsage('The only allowed output formats are emacs, vs7 and eclipse.') |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3978 | output_format = val |
| 3979 | elif opt == '--verbose': |
| 3980 | verbosity = int(val) |
| 3981 | elif opt == '--filter': |
| 3982 | filters = val |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 3983 | if not filters: |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3984 | PrintCategories() |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 3985 | elif opt == '--counting': |
| 3986 | if val not in ('total', 'toplevel', 'detailed'): |
| 3987 | PrintUsage('Valid counting options are total, toplevel, and detailed') |
| 3988 | counting_style = val |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 3989 | elif opt == '--root': |
| 3990 | global _root |
| 3991 | _root = val |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3992 | |
| 3993 | if not filenames: |
| 3994 | PrintUsage('No files were specified.') |
| 3995 | |
| 3996 | _SetOutputFormat(output_format) |
| 3997 | _SetVerboseLevel(verbosity) |
| 3998 | _SetFilters(filters) |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 3999 | _SetCountingStyle(counting_style) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 4000 | |
| 4001 | return filenames |
| 4002 | |
| 4003 | |
| 4004 | def main(): |
| 4005 | filenames = ParseArguments(sys.argv[1:]) |
| 4006 | |
| 4007 | # Change stderr to write with replacement characters so we don't die |
| 4008 | # if we try to print something containing non-ASCII characters. |
| 4009 | sys.stderr = codecs.StreamReaderWriter(sys.stderr, |
| 4010 | codecs.getreader('utf8'), |
| 4011 | codecs.getwriter('utf8'), |
| 4012 | 'replace') |
| 4013 | |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 4014 | _cpplint_state.ResetErrorCounts() |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 4015 | for filename in filenames: |
| 4016 | ProcessFile(filename, _cpplint_state.verbose_level) |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 4017 | _cpplint_state.PrintErrorCounts() |
| 4018 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 4019 | sys.exit(_cpplint_state.error_count > 0) |
| 4020 | |
| 4021 | |
| 4022 | if __name__ == '__main__': |
| 4023 | main() |