annotate lint/cpplint.py @ 0:582cbe817f2c

- Initial add of support code and modules. Not everything is working yet.
author tomwalters
date Fri, 12 Feb 2010 12:31:23 +0000
parents
children
rev   line source
tomwalters@0 1 #!/usr/bin/python
tomwalters@0 2 #
tomwalters@0 3 # Copyright (c) 2009 Google Inc. All rights reserved.
tomwalters@0 4 #
tomwalters@0 5 # Redistribution and use in source and binary forms, with or without
tomwalters@0 6 # modification, are permitted provided that the following conditions are
tomwalters@0 7 # met:
tomwalters@0 8 #
tomwalters@0 9 # * Redistributions of source code must retain the above copyright
tomwalters@0 10 # notice, this list of conditions and the following disclaimer.
tomwalters@0 11 # * Redistributions in binary form must reproduce the above
tomwalters@0 12 # copyright notice, this list of conditions and the following disclaimer
tomwalters@0 13 # in the documentation and/or other materials provided with the
tomwalters@0 14 # distribution.
tomwalters@0 15 # * Neither the name of Google Inc. nor the names of its
tomwalters@0 16 # contributors may be used to endorse or promote products derived from
tomwalters@0 17 # this software without specific prior written permission.
tomwalters@0 18 #
tomwalters@0 19 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
tomwalters@0 20 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
tomwalters@0 21 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
tomwalters@0 22 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
tomwalters@0 23 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
tomwalters@0 24 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
tomwalters@0 25 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
tomwalters@0 26 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
tomwalters@0 27 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
tomwalters@0 28 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
tomwalters@0 29 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
tomwalters@0 30
tomwalters@0 31 # Here are some issues that I've had people identify in my code during reviews,
tomwalters@0 32 # that I think are possible to flag automatically in a lint tool. If these were
tomwalters@0 33 # caught by lint, it would save time both for myself and that of my reviewers.
tomwalters@0 34 # Most likely, some of these are beyond the scope of the current lint framework,
tomwalters@0 35 # but I think it is valuable to retain these wish-list items even if they cannot
tomwalters@0 36 # be immediately implemented.
tomwalters@0 37 #
tomwalters@0 38 # Suggestions
tomwalters@0 39 # -----------
tomwalters@0 40 # - Check for no 'explicit' for multi-arg ctor
tomwalters@0 41 # - Check for boolean assign RHS in parens
tomwalters@0 42 # - Check for ctor initializer-list colon position and spacing
tomwalters@0 43 # - Check that if there's a ctor, there should be a dtor
tomwalters@0 44 # - Check accessors that return non-pointer member variables are
tomwalters@0 45 # declared const
tomwalters@0 46 # - Check accessors that return non-const pointer member vars are
tomwalters@0 47 # *not* declared const
tomwalters@0 48 # - Check for using public includes for testing
tomwalters@0 49 # - Check for spaces between brackets in one-line inline method
tomwalters@0 50 # - Check for no assert()
tomwalters@0 51 # - Check for spaces surrounding operators
tomwalters@0 52 # - Check for 0 in pointer context (should be NULL)
tomwalters@0 53 # - Check for 0 in char context (should be '\0')
tomwalters@0 54 # - Check for camel-case method name conventions for methods
tomwalters@0 55 # that are not simple inline getters and setters
tomwalters@0 56 # - Check that base classes have virtual destructors
tomwalters@0 57 # put " // namespace" after } that closes a namespace, with
tomwalters@0 58 # namespace's name after 'namespace' if it is named.
tomwalters@0 59 # - Do not indent namespace contents
tomwalters@0 60 # - Avoid inlining non-trivial constructors in header files
tomwalters@0 61 # include base/basictypes.h if DISALLOW_EVIL_CONSTRUCTORS is used
tomwalters@0 62 # - Check for old-school (void) cast for call-sites of functions
tomwalters@0 63 # ignored return value
tomwalters@0 64 # - Check gUnit usage of anonymous namespace
tomwalters@0 65 # - Check for class declaration order (typedefs, consts, enums,
tomwalters@0 66 # ctor(s?), dtor, friend declarations, methods, member vars)
tomwalters@0 67 #
tomwalters@0 68
tomwalters@0 69 """Does google-lint on c++ files.
tomwalters@0 70
tomwalters@0 71 The goal of this script is to identify places in the code that *may*
tomwalters@0 72 be in non-compliance with google style. It does not attempt to fix
tomwalters@0 73 up these problems -- the point is to educate. It does also not
tomwalters@0 74 attempt to find all problems, or to ensure that everything it does
tomwalters@0 75 find is legitimately a problem.
tomwalters@0 76
tomwalters@0 77 In particular, we can get very confused by /* and // inside strings!
tomwalters@0 78 We do a small hack, which is to ignore //'s with "'s after them on the
tomwalters@0 79 same line, but it is far from perfect (in either direction).
tomwalters@0 80 """
tomwalters@0 81
tomwalters@0 82 import codecs
tomwalters@0 83 import getopt
tomwalters@0 84 import math # for log
tomwalters@0 85 import os
tomwalters@0 86 import re
tomwalters@0 87 import sre_compile
tomwalters@0 88 import string
tomwalters@0 89 import sys
tomwalters@0 90 import unicodedata
tomwalters@0 91
tomwalters@0 92
tomwalters@0 93 _USAGE = """
tomwalters@0 94 Syntax: cpplint.py [--verbose=#] [--output=vs7] [--filter=-x,+y,...]
tomwalters@0 95 [--counting=total|toplevel|detailed]
tomwalters@0 96 <file> [file] ...
tomwalters@0 97
tomwalters@0 98 The style guidelines this tries to follow are those in
tomwalters@0 99 http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml
tomwalters@0 100
tomwalters@0 101 Every problem is given a confidence score from 1-5, with 5 meaning we are
tomwalters@0 102 certain of the problem, and 1 meaning it could be a legitimate construct.
tomwalters@0 103 This will miss some errors, and is not a substitute for a code review.
tomwalters@0 104
tomwalters@0 105 To prevent specific lines from being linted, add a '// NOLINT' comment to the
tomwalters@0 106 end of the line.
tomwalters@0 107
tomwalters@0 108 The files passed in will be linted; at least one file must be provided.
tomwalters@0 109 Linted extensions are .cc, .cpp, and .h. Other file types will be ignored.
tomwalters@0 110
tomwalters@0 111 Flags:
tomwalters@0 112
tomwalters@0 113 output=vs7
tomwalters@0 114 By default, the output is formatted to ease emacs parsing. Visual Studio
tomwalters@0 115 compatible output (vs7) may also be used. Other formats are unsupported.
tomwalters@0 116
tomwalters@0 117 verbose=#
tomwalters@0 118 Specify a number 0-5 to restrict errors to certain verbosity levels.
tomwalters@0 119
tomwalters@0 120 filter=-x,+y,...
tomwalters@0 121 Specify a comma-separated list of category-filters to apply: only
tomwalters@0 122 error messages whose category names pass the filters will be printed.
tomwalters@0 123 (Category names are printed with the message and look like
tomwalters@0 124 "[whitespace/indent]".) Filters are evaluated left to right.
tomwalters@0 125 "-FOO" and "FOO" means "do not print categories that start with FOO".
tomwalters@0 126 "+FOO" means "do print categories that start with FOO".
tomwalters@0 127
tomwalters@0 128 Examples: --filter=-whitespace,+whitespace/braces
tomwalters@0 129 --filter=whitespace,runtime/printf,+runtime/printf_format
tomwalters@0 130 --filter=-,+build/include_what_you_use
tomwalters@0 131
tomwalters@0 132 To see a list of all the categories used in cpplint, pass no arg:
tomwalters@0 133 --filter=
tomwalters@0 134
tomwalters@0 135 counting=total|toplevel|detailed
tomwalters@0 136 The total number of errors found is always printed. If
tomwalters@0 137 'toplevel' is provided, then the count of errors in each of
tomwalters@0 138 the top-level categories like 'build' and 'whitespace' will
tomwalters@0 139 also be printed. If 'detailed' is provided, then a count
tomwalters@0 140 is provided for each category like 'build/class'.
tomwalters@0 141 """
tomwalters@0 142
tomwalters@0 143 # We categorize each error message we print. Here are the categories.
tomwalters@0 144 # We want an explicit list so we can list them all in cpplint --filter=.
tomwalters@0 145 # If you add a new error message with a new category, add it to the list
tomwalters@0 146 # here! cpplint_unittest.py should tell you if you forget to do this.
tomwalters@0 147 # \ used for clearer layout -- pylint: disable-msg=C6013
tomwalters@0 148 _ERROR_CATEGORIES = '''\
tomwalters@0 149 build/class
tomwalters@0 150 build/deprecated
tomwalters@0 151 build/endif_comment
tomwalters@0 152 build/forward_decl
tomwalters@0 153 build/header_guard
tomwalters@0 154 build/include
tomwalters@0 155 build/include_alpha
tomwalters@0 156 build/include_order
tomwalters@0 157 build/include_what_you_use
tomwalters@0 158 build/namespaces
tomwalters@0 159 build/printf_format
tomwalters@0 160 build/storage_class
tomwalters@0 161 legal/copyright
tomwalters@0 162 readability/braces
tomwalters@0 163 readability/casting
tomwalters@0 164 readability/check
tomwalters@0 165 readability/constructors
tomwalters@0 166 readability/fn_size
tomwalters@0 167 readability/function
tomwalters@0 168 readability/multiline_comment
tomwalters@0 169 readability/multiline_string
tomwalters@0 170 readability/streams
tomwalters@0 171 readability/todo
tomwalters@0 172 readability/utf8
tomwalters@0 173 runtime/arrays
tomwalters@0 174 runtime/casting
tomwalters@0 175 runtime/explicit
tomwalters@0 176 runtime/int
tomwalters@0 177 runtime/init
tomwalters@0 178 runtime/invalid_increment
tomwalters@0 179 runtime/member_string_references
tomwalters@0 180 runtime/memset
tomwalters@0 181 runtime/operator
tomwalters@0 182 runtime/printf
tomwalters@0 183 runtime/printf_format
tomwalters@0 184 runtime/references
tomwalters@0 185 runtime/rtti
tomwalters@0 186 runtime/sizeof
tomwalters@0 187 runtime/string
tomwalters@0 188 runtime/threadsafe_fn
tomwalters@0 189 runtime/virtual
tomwalters@0 190 whitespace/blank_line
tomwalters@0 191 whitespace/braces
tomwalters@0 192 whitespace/comma
tomwalters@0 193 whitespace/comments
tomwalters@0 194 whitespace/end_of_line
tomwalters@0 195 whitespace/ending_newline
tomwalters@0 196 whitespace/indent
tomwalters@0 197 whitespace/labels
tomwalters@0 198 whitespace/line_length
tomwalters@0 199 whitespace/newline
tomwalters@0 200 whitespace/operators
tomwalters@0 201 whitespace/parens
tomwalters@0 202 whitespace/semicolon
tomwalters@0 203 whitespace/tab
tomwalters@0 204 whitespace/todo
tomwalters@0 205 '''
tomwalters@0 206
tomwalters@0 207 # The default state of the category filter. This is overrided by the --filter=
tomwalters@0 208 # flag. By default all errors are on, so only add here categories that should be
tomwalters@0 209 # off by default (i.e., categories that must be enabled by the --filter= flags).
tomwalters@0 210 # All entries here should start with a '-' or '+', as in the --filter= flag.
tomwalters@0 211 _DEFAULT_FILTERS = [ '-build/include_alpha' ]
tomwalters@0 212
tomwalters@0 213 # We used to check for high-bit characters, but after much discussion we
tomwalters@0 214 # decided those were OK, as long as they were in UTF-8 and didn't represent
tomwalters@0 215 # hard-coded international strings, which belong in a seperate i18n file.
tomwalters@0 216
tomwalters@0 217 # Headers that we consider STL headers.
tomwalters@0 218 _STL_HEADERS = frozenset([
tomwalters@0 219 'algobase.h', 'algorithm', 'alloc.h', 'bitset', 'deque', 'exception',
tomwalters@0 220 'function.h', 'functional', 'hash_map', 'hash_map.h', 'hash_set',
tomwalters@0 221 'hash_set.h', 'iterator', 'list', 'list.h', 'map', 'memory', 'pair.h',
tomwalters@0 222 'pthread_alloc', 'queue', 'set', 'set.h', 'sstream', 'stack',
tomwalters@0 223 'stl_alloc.h', 'stl_relops.h', 'type_traits.h',
tomwalters@0 224 'utility', 'vector', 'vector.h',
tomwalters@0 225 ])
tomwalters@0 226
tomwalters@0 227
tomwalters@0 228 # Non-STL C++ system headers.
tomwalters@0 229 _CPP_HEADERS = frozenset([
tomwalters@0 230 'algo.h', 'builtinbuf.h', 'bvector.h', 'cassert', 'cctype',
tomwalters@0 231 'cerrno', 'cfloat', 'ciso646', 'climits', 'clocale', 'cmath',
tomwalters@0 232 'complex', 'complex.h', 'csetjmp', 'csignal', 'cstdarg', 'cstddef',
tomwalters@0 233 'cstdio', 'cstdlib', 'cstring', 'ctime', 'cwchar', 'cwctype',
tomwalters@0 234 'defalloc.h', 'deque.h', 'editbuf.h', 'exception', 'fstream',
tomwalters@0 235 'fstream.h', 'hashtable.h', 'heap.h', 'indstream.h', 'iomanip',
tomwalters@0 236 'iomanip.h', 'ios', 'iosfwd', 'iostream', 'iostream.h', 'istream.h',
tomwalters@0 237 'iterator.h', 'limits', 'map.h', 'multimap.h', 'multiset.h',
tomwalters@0 238 'numeric', 'ostream.h', 'parsestream.h', 'pfstream.h', 'PlotFile.h',
tomwalters@0 239 'procbuf.h', 'pthread_alloc.h', 'rope', 'rope.h', 'ropeimpl.h',
tomwalters@0 240 'SFile.h', 'slist', 'slist.h', 'stack.h', 'stdexcept',
tomwalters@0 241 'stdiostream.h', 'streambuf.h', 'stream.h', 'strfile.h', 'string',
tomwalters@0 242 'strstream', 'strstream.h', 'tempbuf.h', 'tree.h', 'typeinfo', 'valarray',
tomwalters@0 243 ])
tomwalters@0 244
tomwalters@0 245
tomwalters@0 246 # Assertion macros. These are defined in base/logging.h and
tomwalters@0 247 # testing/base/gunit.h. Note that the _M versions need to come first
tomwalters@0 248 # for substring matching to work.
tomwalters@0 249 _CHECK_MACROS = [
tomwalters@0 250 'DCHECK', 'CHECK',
tomwalters@0 251 'EXPECT_TRUE_M', 'EXPECT_TRUE',
tomwalters@0 252 'ASSERT_TRUE_M', 'ASSERT_TRUE',
tomwalters@0 253 'EXPECT_FALSE_M', 'EXPECT_FALSE',
tomwalters@0 254 'ASSERT_FALSE_M', 'ASSERT_FALSE',
tomwalters@0 255 ]
tomwalters@0 256
tomwalters@0 257 # Replacement macros for CHECK/DCHECK/EXPECT_TRUE/EXPECT_FALSE
tomwalters@0 258 _CHECK_REPLACEMENT = dict([(m, {}) for m in _CHECK_MACROS])
tomwalters@0 259
tomwalters@0 260 for op, replacement in [('==', 'EQ'), ('!=', 'NE'),
tomwalters@0 261 ('>=', 'GE'), ('>', 'GT'),
tomwalters@0 262 ('<=', 'LE'), ('<', 'LT')]:
tomwalters@0 263 _CHECK_REPLACEMENT['DCHECK'][op] = 'DCHECK_%s' % replacement
tomwalters@0 264 _CHECK_REPLACEMENT['CHECK'][op] = 'CHECK_%s' % replacement
tomwalters@0 265 _CHECK_REPLACEMENT['EXPECT_TRUE'][op] = 'EXPECT_%s' % replacement
tomwalters@0 266 _CHECK_REPLACEMENT['ASSERT_TRUE'][op] = 'ASSERT_%s' % replacement
tomwalters@0 267 _CHECK_REPLACEMENT['EXPECT_TRUE_M'][op] = 'EXPECT_%s_M' % replacement
tomwalters@0 268 _CHECK_REPLACEMENT['ASSERT_TRUE_M'][op] = 'ASSERT_%s_M' % replacement
tomwalters@0 269
tomwalters@0 270 for op, inv_replacement in [('==', 'NE'), ('!=', 'EQ'),
tomwalters@0 271 ('>=', 'LT'), ('>', 'LE'),
tomwalters@0 272 ('<=', 'GT'), ('<', 'GE')]:
tomwalters@0 273 _CHECK_REPLACEMENT['EXPECT_FALSE'][op] = 'EXPECT_%s' % inv_replacement
tomwalters@0 274 _CHECK_REPLACEMENT['ASSERT_FALSE'][op] = 'ASSERT_%s' % inv_replacement
tomwalters@0 275 _CHECK_REPLACEMENT['EXPECT_FALSE_M'][op] = 'EXPECT_%s_M' % inv_replacement
tomwalters@0 276 _CHECK_REPLACEMENT['ASSERT_FALSE_M'][op] = 'ASSERT_%s_M' % inv_replacement
tomwalters@0 277
tomwalters@0 278
tomwalters@0 279 # These constants define types of headers for use with
tomwalters@0 280 # _IncludeState.CheckNextIncludeOrder().
tomwalters@0 281 _C_SYS_HEADER = 1
tomwalters@0 282 _CPP_SYS_HEADER = 2
tomwalters@0 283 _LIKELY_MY_HEADER = 3
tomwalters@0 284 _POSSIBLE_MY_HEADER = 4
tomwalters@0 285 _OTHER_HEADER = 5
tomwalters@0 286
tomwalters@0 287
tomwalters@0 288 _regexp_compile_cache = {}
tomwalters@0 289
tomwalters@0 290
tomwalters@0 291 def Match(pattern, s):
tomwalters@0 292 """Matches the string with the pattern, caching the compiled regexp."""
tomwalters@0 293 # The regexp compilation caching is inlined in both Match and Search for
tomwalters@0 294 # performance reasons; factoring it out into a separate function turns out
tomwalters@0 295 # to be noticeably expensive.
tomwalters@0 296 if not pattern in _regexp_compile_cache:
tomwalters@0 297 _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
tomwalters@0 298 return _regexp_compile_cache[pattern].match(s)
tomwalters@0 299
tomwalters@0 300
tomwalters@0 301 def Search(pattern, s):
tomwalters@0 302 """Searches the string for the pattern, caching the compiled regexp."""
tomwalters@0 303 if not pattern in _regexp_compile_cache:
tomwalters@0 304 _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
tomwalters@0 305 return _regexp_compile_cache[pattern].search(s)
tomwalters@0 306
tomwalters@0 307
tomwalters@0 308 class _IncludeState(dict):
tomwalters@0 309 """Tracks line numbers for includes, and the order in which includes appear.
tomwalters@0 310
tomwalters@0 311 As a dict, an _IncludeState object serves as a mapping between include
tomwalters@0 312 filename and line number on which that file was included.
tomwalters@0 313
tomwalters@0 314 Call CheckNextIncludeOrder() once for each header in the file, passing
tomwalters@0 315 in the type constants defined above. Calls in an illegal order will
tomwalters@0 316 raise an _IncludeError with an appropriate error message.
tomwalters@0 317
tomwalters@0 318 """
tomwalters@0 319 # self._section will move monotonically through this set. If it ever
tomwalters@0 320 # needs to move backwards, CheckNextIncludeOrder will raise an error.
tomwalters@0 321 _INITIAL_SECTION = 0
tomwalters@0 322 _MY_H_SECTION = 1
tomwalters@0 323 _C_SECTION = 2
tomwalters@0 324 _CPP_SECTION = 3
tomwalters@0 325 _OTHER_H_SECTION = 4
tomwalters@0 326
tomwalters@0 327 _TYPE_NAMES = {
tomwalters@0 328 _C_SYS_HEADER: 'C system header',
tomwalters@0 329 _CPP_SYS_HEADER: 'C++ system header',
tomwalters@0 330 _LIKELY_MY_HEADER: 'header this file implements',
tomwalters@0 331 _POSSIBLE_MY_HEADER: 'header this file may implement',
tomwalters@0 332 _OTHER_HEADER: 'other header',
tomwalters@0 333 }
tomwalters@0 334 _SECTION_NAMES = {
tomwalters@0 335 _INITIAL_SECTION: "... nothing. (This can't be an error.)",
tomwalters@0 336 _MY_H_SECTION: 'a header this file implements',
tomwalters@0 337 _C_SECTION: 'C system header',
tomwalters@0 338 _CPP_SECTION: 'C++ system header',
tomwalters@0 339 _OTHER_H_SECTION: 'other header',
tomwalters@0 340 }
tomwalters@0 341
tomwalters@0 342 def __init__(self):
tomwalters@0 343 dict.__init__(self)
tomwalters@0 344 # The name of the current section.
tomwalters@0 345 self._section = self._INITIAL_SECTION
tomwalters@0 346 # The path of last found header.
tomwalters@0 347 self._last_header = ''
tomwalters@0 348
tomwalters@0 349 def CanonicalizeAlphabeticalOrder(self, header_path):
tomwalters@0 350 """Returns a path canonicalized for alphabetical comparisson.
tomwalters@0 351
tomwalters@0 352 - replaces "-" with "_" so they both cmp the same.
tomwalters@0 353 - removes '-inl' since we don't require them to be after the main header.
tomwalters@0 354 - lowercase everything, just in case.
tomwalters@0 355
tomwalters@0 356 Args:
tomwalters@0 357 header_path: Path to be canonicalized.
tomwalters@0 358
tomwalters@0 359 Returns:
tomwalters@0 360 Canonicalized path.
tomwalters@0 361 """
tomwalters@0 362 return header_path.replace('-inl.h', '.h').replace('-', '_').lower()
tomwalters@0 363
tomwalters@0 364 def IsInAlphabeticalOrder(self, header_path):
tomwalters@0 365 """Check if a header is in alphabetical order with the previous header.
tomwalters@0 366
tomwalters@0 367 Args:
tomwalters@0 368 header_path: Header to be checked.
tomwalters@0 369
tomwalters@0 370 Returns:
tomwalters@0 371 Returns true if the header is in alphabetical order.
tomwalters@0 372 """
tomwalters@0 373 canonical_header = self.CanonicalizeAlphabeticalOrder(header_path)
tomwalters@0 374 if self._last_header > canonical_header:
tomwalters@0 375 return False
tomwalters@0 376 self._last_header = canonical_header
tomwalters@0 377 return True
tomwalters@0 378
tomwalters@0 379 def CheckNextIncludeOrder(self, header_type):
tomwalters@0 380 """Returns a non-empty error message if the next header is out of order.
tomwalters@0 381
tomwalters@0 382 This function also updates the internal state to be ready to check
tomwalters@0 383 the next include.
tomwalters@0 384
tomwalters@0 385 Args:
tomwalters@0 386 header_type: One of the _XXX_HEADER constants defined above.
tomwalters@0 387
tomwalters@0 388 Returns:
tomwalters@0 389 The empty string if the header is in the right order, or an
tomwalters@0 390 error message describing what's wrong.
tomwalters@0 391
tomwalters@0 392 """
tomwalters@0 393 error_message = ('Found %s after %s' %
tomwalters@0 394 (self._TYPE_NAMES[header_type],
tomwalters@0 395 self._SECTION_NAMES[self._section]))
tomwalters@0 396
tomwalters@0 397 last_section = self._section
tomwalters@0 398
tomwalters@0 399 if header_type == _C_SYS_HEADER:
tomwalters@0 400 if self._section <= self._C_SECTION:
tomwalters@0 401 self._section = self._C_SECTION
tomwalters@0 402 else:
tomwalters@0 403 self._last_header = ''
tomwalters@0 404 return error_message
tomwalters@0 405 elif header_type == _CPP_SYS_HEADER:
tomwalters@0 406 if self._section <= self._CPP_SECTION:
tomwalters@0 407 self._section = self._CPP_SECTION
tomwalters@0 408 else:
tomwalters@0 409 self._last_header = ''
tomwalters@0 410 return error_message
tomwalters@0 411 elif header_type == _LIKELY_MY_HEADER:
tomwalters@0 412 if self._section <= self._MY_H_SECTION:
tomwalters@0 413 self._section = self._MY_H_SECTION
tomwalters@0 414 else:
tomwalters@0 415 self._section = self._OTHER_H_SECTION
tomwalters@0 416 elif header_type == _POSSIBLE_MY_HEADER:
tomwalters@0 417 if self._section <= self._MY_H_SECTION:
tomwalters@0 418 self._section = self._MY_H_SECTION
tomwalters@0 419 else:
tomwalters@0 420 # This will always be the fallback because we're not sure
tomwalters@0 421 # enough that the header is associated with this file.
tomwalters@0 422 self._section = self._OTHER_H_SECTION
tomwalters@0 423 else:
tomwalters@0 424 assert header_type == _OTHER_HEADER
tomwalters@0 425 self._section = self._OTHER_H_SECTION
tomwalters@0 426
tomwalters@0 427 if last_section != self._section:
tomwalters@0 428 self._last_header = ''
tomwalters@0 429
tomwalters@0 430 return ''
tomwalters@0 431
tomwalters@0 432
tomwalters@0 433 class _CppLintState(object):
tomwalters@0 434 """Maintains module-wide state.."""
tomwalters@0 435
tomwalters@0 436 def __init__(self):
tomwalters@0 437 self.verbose_level = 1 # global setting.
tomwalters@0 438 self.error_count = 0 # global count of reported errors
tomwalters@0 439 # filters to apply when emitting error messages
tomwalters@0 440 self.filters = _DEFAULT_FILTERS[:]
tomwalters@0 441 self.counting = 'total' # In what way are we counting errors?
tomwalters@0 442 self.errors_by_category = {} # string to int dict storing error counts
tomwalters@0 443
tomwalters@0 444 # output format:
tomwalters@0 445 # "emacs" - format that emacs can parse (default)
tomwalters@0 446 # "vs7" - format that Microsoft Visual Studio 7 can parse
tomwalters@0 447 self.output_format = 'emacs'
tomwalters@0 448
tomwalters@0 449 def SetOutputFormat(self, output_format):
tomwalters@0 450 """Sets the output format for errors."""
tomwalters@0 451 self.output_format = output_format
tomwalters@0 452
tomwalters@0 453 def SetVerboseLevel(self, level):
tomwalters@0 454 """Sets the module's verbosity, and returns the previous setting."""
tomwalters@0 455 last_verbose_level = self.verbose_level
tomwalters@0 456 self.verbose_level = level
tomwalters@0 457 return last_verbose_level
tomwalters@0 458
tomwalters@0 459 def SetCountingStyle(self, counting_style):
tomwalters@0 460 """Sets the module's counting options."""
tomwalters@0 461 self.counting = counting_style
tomwalters@0 462
tomwalters@0 463 def SetFilters(self, filters):
tomwalters@0 464 """Sets the error-message filters.
tomwalters@0 465
tomwalters@0 466 These filters are applied when deciding whether to emit a given
tomwalters@0 467 error message.
tomwalters@0 468
tomwalters@0 469 Args:
tomwalters@0 470 filters: A string of comma-separated filters (eg "+whitespace/indent").
tomwalters@0 471 Each filter should start with + or -; else we die.
tomwalters@0 472
tomwalters@0 473 Raises:
tomwalters@0 474 ValueError: The comma-separated filters did not all start with '+' or '-'.
tomwalters@0 475 E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter"
tomwalters@0 476 """
tomwalters@0 477 # Default filters always have less priority than the flag ones.
tomwalters@0 478 self.filters = _DEFAULT_FILTERS[:]
tomwalters@0 479 for filt in filters.split(','):
tomwalters@0 480 clean_filt = filt.strip()
tomwalters@0 481 if clean_filt:
tomwalters@0 482 self.filters.append(clean_filt)
tomwalters@0 483 for filt in self.filters:
tomwalters@0 484 if not (filt.startswith('+') or filt.startswith('-')):
tomwalters@0 485 raise ValueError('Every filter in --filters must start with + or -'
tomwalters@0 486 ' (%s does not)' % filt)
tomwalters@0 487
tomwalters@0 488 def ResetErrorCounts(self):
tomwalters@0 489 """Sets the module's error statistic back to zero."""
tomwalters@0 490 self.error_count = 0
tomwalters@0 491 self.errors_by_category = {}
tomwalters@0 492
tomwalters@0 493 def IncrementErrorCount(self, category):
tomwalters@0 494 """Bumps the module's error statistic."""
tomwalters@0 495 self.error_count += 1
tomwalters@0 496 if self.counting in ('toplevel', 'detailed'):
tomwalters@0 497 if self.counting != 'detailed':
tomwalters@0 498 category = category.split('/')[0]
tomwalters@0 499 if category not in self.errors_by_category:
tomwalters@0 500 self.errors_by_category[category] = 0
tomwalters@0 501 self.errors_by_category[category] += 1
tomwalters@0 502
tomwalters@0 503 def PrintErrorCounts(self):
tomwalters@0 504 """Print a summary of errors by category, and the total."""
tomwalters@0 505 for category, count in self.errors_by_category.iteritems():
tomwalters@0 506 sys.stderr.write('Category \'%s\' errors found: %d\n' %
tomwalters@0 507 (category, count))
tomwalters@0 508 sys.stderr.write('Total errors found: %d\n' % self.error_count)
tomwalters@0 509
tomwalters@0 510 _cpplint_state = _CppLintState()
tomwalters@0 511
tomwalters@0 512
tomwalters@0 513 def _OutputFormat():
tomwalters@0 514 """Gets the module's output format."""
tomwalters@0 515 return _cpplint_state.output_format
tomwalters@0 516
tomwalters@0 517
tomwalters@0 518 def _SetOutputFormat(output_format):
tomwalters@0 519 """Sets the module's output format."""
tomwalters@0 520 _cpplint_state.SetOutputFormat(output_format)
tomwalters@0 521
tomwalters@0 522
tomwalters@0 523 def _VerboseLevel():
tomwalters@0 524 """Returns the module's verbosity setting."""
tomwalters@0 525 return _cpplint_state.verbose_level
tomwalters@0 526
tomwalters@0 527
tomwalters@0 528 def _SetVerboseLevel(level):
tomwalters@0 529 """Sets the module's verbosity, and returns the previous setting."""
tomwalters@0 530 return _cpplint_state.SetVerboseLevel(level)
tomwalters@0 531
tomwalters@0 532
tomwalters@0 533 def _SetCountingStyle(level):
tomwalters@0 534 """Sets the module's counting options."""
tomwalters@0 535 _cpplint_state.SetCountingStyle(level)
tomwalters@0 536
tomwalters@0 537
tomwalters@0 538 def _Filters():
tomwalters@0 539 """Returns the module's list of output filters, as a list."""
tomwalters@0 540 return _cpplint_state.filters
tomwalters@0 541
tomwalters@0 542
tomwalters@0 543 def _SetFilters(filters):
tomwalters@0 544 """Sets the module's error-message filters.
tomwalters@0 545
tomwalters@0 546 These filters are applied when deciding whether to emit a given
tomwalters@0 547 error message.
tomwalters@0 548
tomwalters@0 549 Args:
tomwalters@0 550 filters: A string of comma-separated filters (eg "whitespace/indent").
tomwalters@0 551 Each filter should start with + or -; else we die.
tomwalters@0 552 """
tomwalters@0 553 _cpplint_state.SetFilters(filters)
tomwalters@0 554
tomwalters@0 555
tomwalters@0 556 class _FunctionState(object):
tomwalters@0 557 """Tracks current function name and the number of lines in its body."""
tomwalters@0 558
tomwalters@0 559 _NORMAL_TRIGGER = 250 # for --v=0, 500 for --v=1, etc.
tomwalters@0 560 _TEST_TRIGGER = 400 # about 50% more than _NORMAL_TRIGGER.
tomwalters@0 561
tomwalters@0 562 def __init__(self):
tomwalters@0 563 self.in_a_function = False
tomwalters@0 564 self.lines_in_function = 0
tomwalters@0 565 self.current_function = ''
tomwalters@0 566
tomwalters@0 567 def Begin(self, function_name):
tomwalters@0 568 """Start analyzing function body.
tomwalters@0 569
tomwalters@0 570 Args:
tomwalters@0 571 function_name: The name of the function being tracked.
tomwalters@0 572 """
tomwalters@0 573 self.in_a_function = True
tomwalters@0 574 self.lines_in_function = 0
tomwalters@0 575 self.current_function = function_name
tomwalters@0 576
tomwalters@0 577 def Count(self):
tomwalters@0 578 """Count line in current function body."""
tomwalters@0 579 if self.in_a_function:
tomwalters@0 580 self.lines_in_function += 1
tomwalters@0 581
tomwalters@0 582 def Check(self, error, filename, linenum):
tomwalters@0 583 """Report if too many lines in function body.
tomwalters@0 584
tomwalters@0 585 Args:
tomwalters@0 586 error: The function to call with any errors found.
tomwalters@0 587 filename: The name of the current file.
tomwalters@0 588 linenum: The number of the line to check.
tomwalters@0 589 """
tomwalters@0 590 if Match(r'T(EST|est)', self.current_function):
tomwalters@0 591 base_trigger = self._TEST_TRIGGER
tomwalters@0 592 else:
tomwalters@0 593 base_trigger = self._NORMAL_TRIGGER
tomwalters@0 594 trigger = base_trigger * 2**_VerboseLevel()
tomwalters@0 595
tomwalters@0 596 if self.lines_in_function > trigger:
tomwalters@0 597 error_level = int(math.log(self.lines_in_function / base_trigger, 2))
tomwalters@0 598 # 50 => 0, 100 => 1, 200 => 2, 400 => 3, 800 => 4, 1600 => 5, ...
tomwalters@0 599 if error_level > 5:
tomwalters@0 600 error_level = 5
tomwalters@0 601 error(filename, linenum, 'readability/fn_size', error_level,
tomwalters@0 602 'Small and focused functions are preferred:'
tomwalters@0 603 ' %s has %d non-comment lines'
tomwalters@0 604 ' (error triggered by exceeding %d lines).' % (
tomwalters@0 605 self.current_function, self.lines_in_function, trigger))
tomwalters@0 606
tomwalters@0 607 def End(self):
tomwalters@0 608 """Stop analizing function body."""
tomwalters@0 609 self.in_a_function = False
tomwalters@0 610
tomwalters@0 611
tomwalters@0 612 class _IncludeError(Exception):
tomwalters@0 613 """Indicates a problem with the include order in a file."""
tomwalters@0 614 pass
tomwalters@0 615
tomwalters@0 616
tomwalters@0 617 class FileInfo:
tomwalters@0 618 """Provides utility functions for filenames.
tomwalters@0 619
tomwalters@0 620 FileInfo provides easy access to the components of a file's path
tomwalters@0 621 relative to the project root.
tomwalters@0 622 """
tomwalters@0 623
tomwalters@0 624 def __init__(self, filename):
tomwalters@0 625 self._filename = filename
tomwalters@0 626
tomwalters@0 627 def FullName(self):
tomwalters@0 628 """Make Windows paths like Unix."""
tomwalters@0 629 return os.path.abspath(self._filename).replace('\\', '/')
tomwalters@0 630
tomwalters@0 631 def RepositoryName(self):
tomwalters@0 632 """FullName after removing the local path to the repository.
tomwalters@0 633
tomwalters@0 634 If we have a real absolute path name here we can try to do something smart:
tomwalters@0 635 detecting the root of the checkout and truncating /path/to/checkout from
tomwalters@0 636 the name so that we get header guards that don't include things like
tomwalters@0 637 "C:\Documents and Settings\..." or "/home/username/..." in them and thus
tomwalters@0 638 people on different computers who have checked the source out to different
tomwalters@0 639 locations won't see bogus errors.
tomwalters@0 640 """
tomwalters@0 641 fullname = self.FullName()
tomwalters@0 642
tomwalters@0 643 if os.path.exists(fullname):
tomwalters@0 644 project_dir = os.path.dirname(fullname)
tomwalters@0 645
tomwalters@0 646 if os.path.exists(os.path.join(project_dir, ".svn")):
tomwalters@0 647 # If there's a .svn file in the current directory, we recursively look
tomwalters@0 648 # up the directory tree for the top of the SVN checkout
tomwalters@0 649 root_dir = project_dir
tomwalters@0 650 one_up_dir = os.path.dirname(root_dir)
tomwalters@0 651 while os.path.exists(os.path.join(one_up_dir, ".svn")):
tomwalters@0 652 root_dir = os.path.dirname(root_dir)
tomwalters@0 653 one_up_dir = os.path.dirname(one_up_dir)
tomwalters@0 654
tomwalters@0 655 prefix = os.path.commonprefix([root_dir, project_dir])
tomwalters@0 656 return fullname[len(prefix) + 1:]
tomwalters@0 657
tomwalters@0 658 # Not SVN? Try to find a git or hg top level directory by searching up
tomwalters@0 659 # from the current path.
tomwalters@0 660 root_dir = os.path.dirname(fullname)
tomwalters@0 661 while (root_dir != os.path.dirname(root_dir) and
tomwalters@0 662 not os.path.exists(os.path.join(root_dir, ".git")) and
tomwalters@0 663 not os.path.exists(os.path.join(root_dir, ".hg"))):
tomwalters@0 664 root_dir = os.path.dirname(root_dir)
tomwalters@0 665 if (os.path.exists(os.path.join(root_dir, ".git")) or
tomwalters@0 666 os.path.exists(os.path.join(root_dir, ".hg"))):
tomwalters@0 667 prefix = os.path.commonprefix([root_dir, project_dir])
tomwalters@0 668 return fullname[len(prefix) + 1:]
tomwalters@0 669
tomwalters@0 670 # Don't know what to do; header guard warnings may be wrong...
tomwalters@0 671 return fullname
tomwalters@0 672
tomwalters@0 673 def Split(self):
tomwalters@0 674 """Splits the file into the directory, basename, and extension.
tomwalters@0 675
tomwalters@0 676 For 'chrome/browser/browser.cc', Split() would
tomwalters@0 677 return ('chrome/browser', 'browser', '.cc')
tomwalters@0 678
tomwalters@0 679 Returns:
tomwalters@0 680 A tuple of (directory, basename, extension).
tomwalters@0 681 """
tomwalters@0 682
tomwalters@0 683 googlename = self.RepositoryName()
tomwalters@0 684 project, rest = os.path.split(googlename)
tomwalters@0 685 return (project,) + os.path.splitext(rest)
tomwalters@0 686
tomwalters@0 687 def BaseName(self):
tomwalters@0 688 """File base name - text after the final slash, before the final period."""
tomwalters@0 689 return self.Split()[1]
tomwalters@0 690
tomwalters@0 691 def Extension(self):
tomwalters@0 692 """File extension - text following the final period."""
tomwalters@0 693 return self.Split()[2]
tomwalters@0 694
tomwalters@0 695 def NoExtension(self):
tomwalters@0 696 """File has no source file extension."""
tomwalters@0 697 return '/'.join(self.Split()[0:2])
tomwalters@0 698
tomwalters@0 699 def IsSource(self):
tomwalters@0 700 """File has a source file extension."""
tomwalters@0 701 return self.Extension()[1:] in ('c', 'cc', 'cpp', 'cxx')
tomwalters@0 702
tomwalters@0 703
tomwalters@0 704 def _ShouldPrintError(category, confidence):
tomwalters@0 705 """Returns true iff confidence >= verbose, and category passes filter."""
tomwalters@0 706 # There are two ways we might decide not to print an error message:
tomwalters@0 707 # the verbosity level isn't high enough, or the filters filter it out.
tomwalters@0 708 if confidence < _cpplint_state.verbose_level:
tomwalters@0 709 return False
tomwalters@0 710
tomwalters@0 711 is_filtered = False
tomwalters@0 712 for one_filter in _Filters():
tomwalters@0 713 if one_filter.startswith('-'):
tomwalters@0 714 if category.startswith(one_filter[1:]):
tomwalters@0 715 is_filtered = True
tomwalters@0 716 elif one_filter.startswith('+'):
tomwalters@0 717 if category.startswith(one_filter[1:]):
tomwalters@0 718 is_filtered = False
tomwalters@0 719 else:
tomwalters@0 720 assert False # should have been checked for in SetFilter.
tomwalters@0 721 if is_filtered:
tomwalters@0 722 return False
tomwalters@0 723
tomwalters@0 724 return True
tomwalters@0 725
tomwalters@0 726
tomwalters@0 727 def Error(filename, linenum, category, confidence, message):
tomwalters@0 728 """Logs the fact we've found a lint error.
tomwalters@0 729
tomwalters@0 730 We log where the error was found, and also our confidence in the error,
tomwalters@0 731 that is, how certain we are this is a legitimate style regression, and
tomwalters@0 732 not a misidentification or a use that's sometimes justified.
tomwalters@0 733
tomwalters@0 734 Args:
tomwalters@0 735 filename: The name of the file containing the error.
tomwalters@0 736 linenum: The number of the line containing the error.
tomwalters@0 737 category: A string used to describe the "category" this bug
tomwalters@0 738 falls under: "whitespace", say, or "runtime". Categories
tomwalters@0 739 may have a hierarchy separated by slashes: "whitespace/indent".
tomwalters@0 740 confidence: A number from 1-5 representing a confidence score for
tomwalters@0 741 the error, with 5 meaning that we are certain of the problem,
tomwalters@0 742 and 1 meaning that it could be a legitimate construct.
tomwalters@0 743 message: The error message.
tomwalters@0 744 """
tomwalters@0 745 # There are two ways we might decide not to print an error message:
tomwalters@0 746 # the verbosity level isn't high enough, or the filters filter it out.
tomwalters@0 747 if _ShouldPrintError(category, confidence):
tomwalters@0 748 _cpplint_state.IncrementErrorCount(category)
tomwalters@0 749 if _cpplint_state.output_format == 'vs7':
tomwalters@0 750 sys.stderr.write('%s(%s): %s [%s] [%d]\n' % (
tomwalters@0 751 filename, linenum, message, category, confidence))
tomwalters@0 752 else:
tomwalters@0 753 sys.stderr.write('%s:%s: %s [%s] [%d]\n' % (
tomwalters@0 754 filename, linenum, message, category, confidence))
tomwalters@0 755
tomwalters@0 756
tomwalters@0 757 # Matches standard C++ escape esequences per 2.13.2.3 of the C++ standard.
tomwalters@0 758 _RE_PATTERN_CLEANSE_LINE_ESCAPES = re.compile(
tomwalters@0 759 r'\\([abfnrtv?"\\\']|\d+|x[0-9a-fA-F]+)')
tomwalters@0 760 # Matches strings. Escape codes should already be removed by ESCAPES.
tomwalters@0 761 _RE_PATTERN_CLEANSE_LINE_DOUBLE_QUOTES = re.compile(r'"[^"]*"')
tomwalters@0 762 # Matches characters. Escape codes should already be removed by ESCAPES.
tomwalters@0 763 _RE_PATTERN_CLEANSE_LINE_SINGLE_QUOTES = re.compile(r"'.'")
tomwalters@0 764 # Matches multi-line C++ comments.
tomwalters@0 765 # This RE is a little bit more complicated than one might expect, because we
tomwalters@0 766 # have to take care of space removals tools so we can handle comments inside
tomwalters@0 767 # statements better.
tomwalters@0 768 # The current rule is: We only clear spaces from both sides when we're at the
tomwalters@0 769 # end of the line. Otherwise, we try to remove spaces from the right side,
tomwalters@0 770 # if this doesn't work we try on left side but only if there's a non-character
tomwalters@0 771 # on the right.
tomwalters@0 772 _RE_PATTERN_CLEANSE_LINE_C_COMMENTS = re.compile(
tomwalters@0 773 r"""(\s*/\*.*\*/\s*$|
tomwalters@0 774 /\*.*\*/\s+|
tomwalters@0 775 \s+/\*.*\*/(?=\W)|
tomwalters@0 776 /\*.*\*/)""", re.VERBOSE)
tomwalters@0 777
tomwalters@0 778
tomwalters@0 779 def IsCppString(line):
tomwalters@0 780 """Does line terminate so, that the next symbol is in string constant.
tomwalters@0 781
tomwalters@0 782 This function does not consider single-line nor multi-line comments.
tomwalters@0 783
tomwalters@0 784 Args:
tomwalters@0 785 line: is a partial line of code starting from the 0..n.
tomwalters@0 786
tomwalters@0 787 Returns:
tomwalters@0 788 True, if next character appended to 'line' is inside a
tomwalters@0 789 string constant.
tomwalters@0 790 """
tomwalters@0 791
tomwalters@0 792 line = line.replace(r'\\', 'XX') # after this, \\" does not match to \"
tomwalters@0 793 return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1
tomwalters@0 794
tomwalters@0 795
tomwalters@0 796 def FindNextMultiLineCommentStart(lines, lineix):
tomwalters@0 797 """Find the beginning marker for a multiline comment."""
tomwalters@0 798 while lineix < len(lines):
tomwalters@0 799 if lines[lineix].strip().startswith('/*'):
tomwalters@0 800 # Only return this marker if the comment goes beyond this line
tomwalters@0 801 if lines[lineix].strip().find('*/', 2) < 0:
tomwalters@0 802 return lineix
tomwalters@0 803 lineix += 1
tomwalters@0 804 return len(lines)
tomwalters@0 805
tomwalters@0 806
tomwalters@0 807 def FindNextMultiLineCommentEnd(lines, lineix):
tomwalters@0 808 """We are inside a comment, find the end marker."""
tomwalters@0 809 while lineix < len(lines):
tomwalters@0 810 if lines[lineix].strip().endswith('*/'):
tomwalters@0 811 return lineix
tomwalters@0 812 lineix += 1
tomwalters@0 813 return len(lines)
tomwalters@0 814
tomwalters@0 815
tomwalters@0 816 def RemoveMultiLineCommentsFromRange(lines, begin, end):
tomwalters@0 817 """Clears a range of lines for multi-line comments."""
tomwalters@0 818 # Having // dummy comments makes the lines non-empty, so we will not get
tomwalters@0 819 # unnecessary blank line warnings later in the code.
tomwalters@0 820 for i in range(begin, end):
tomwalters@0 821 lines[i] = '// dummy'
tomwalters@0 822
tomwalters@0 823
tomwalters@0 824 def RemoveMultiLineComments(filename, lines, error):
tomwalters@0 825 """Removes multiline (c-style) comments from lines."""
tomwalters@0 826 lineix = 0
tomwalters@0 827 while lineix < len(lines):
tomwalters@0 828 lineix_begin = FindNextMultiLineCommentStart(lines, lineix)
tomwalters@0 829 if lineix_begin >= len(lines):
tomwalters@0 830 return
tomwalters@0 831 lineix_end = FindNextMultiLineCommentEnd(lines, lineix_begin)
tomwalters@0 832 if lineix_end >= len(lines):
tomwalters@0 833 error(filename, lineix_begin + 1, 'readability/multiline_comment', 5,
tomwalters@0 834 'Could not find end of multi-line comment')
tomwalters@0 835 return
tomwalters@0 836 RemoveMultiLineCommentsFromRange(lines, lineix_begin, lineix_end + 1)
tomwalters@0 837 lineix = lineix_end + 1
tomwalters@0 838
tomwalters@0 839
tomwalters@0 840 def CleanseComments(line):
tomwalters@0 841 """Removes //-comments and single-line C-style /* */ comments.
tomwalters@0 842
tomwalters@0 843 Args:
tomwalters@0 844 line: A line of C++ source.
tomwalters@0 845
tomwalters@0 846 Returns:
tomwalters@0 847 The line with single-line comments removed.
tomwalters@0 848 """
tomwalters@0 849 commentpos = line.find('//')
tomwalters@0 850 if commentpos != -1 and not IsCppString(line[:commentpos]):
tomwalters@0 851 line = line[:commentpos]
tomwalters@0 852 # get rid of /* ... */
tomwalters@0 853 return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line)
tomwalters@0 854
tomwalters@0 855
tomwalters@0 856 class CleansedLines(object):
tomwalters@0 857 """Holds 3 copies of all lines with different preprocessing applied to them.
tomwalters@0 858
tomwalters@0 859 1) elided member contains lines without strings and comments,
tomwalters@0 860 2) lines member contains lines without comments, and
tomwalters@0 861 3) raw member contains all the lines without processing.
tomwalters@0 862 All these three members are of <type 'list'>, and of the same length.
tomwalters@0 863 """
tomwalters@0 864
tomwalters@0 865 def __init__(self, lines):
tomwalters@0 866 self.elided = []
tomwalters@0 867 self.lines = []
tomwalters@0 868 self.raw_lines = lines
tomwalters@0 869 self.num_lines = len(lines)
tomwalters@0 870 for linenum in range(len(lines)):
tomwalters@0 871 self.lines.append(CleanseComments(lines[linenum]))
tomwalters@0 872 elided = self._CollapseStrings(lines[linenum])
tomwalters@0 873 self.elided.append(CleanseComments(elided))
tomwalters@0 874
tomwalters@0 875 def NumLines(self):
tomwalters@0 876 """Returns the number of lines represented."""
tomwalters@0 877 return self.num_lines
tomwalters@0 878
tomwalters@0 879 @staticmethod
tomwalters@0 880 def _CollapseStrings(elided):
tomwalters@0 881 """Collapses strings and chars on a line to simple "" or '' blocks.
tomwalters@0 882
tomwalters@0 883 We nix strings first so we're not fooled by text like '"http://"'
tomwalters@0 884
tomwalters@0 885 Args:
tomwalters@0 886 elided: The line being processed.
tomwalters@0 887
tomwalters@0 888 Returns:
tomwalters@0 889 The line with collapsed strings.
tomwalters@0 890 """
tomwalters@0 891 if not _RE_PATTERN_INCLUDE.match(elided):
tomwalters@0 892 # Remove escaped characters first to make quote/single quote collapsing
tomwalters@0 893 # basic. Things that look like escaped characters shouldn't occur
tomwalters@0 894 # outside of strings and chars.
tomwalters@0 895 elided = _RE_PATTERN_CLEANSE_LINE_ESCAPES.sub('', elided)
tomwalters@0 896 elided = _RE_PATTERN_CLEANSE_LINE_SINGLE_QUOTES.sub("''", elided)
tomwalters@0 897 elided = _RE_PATTERN_CLEANSE_LINE_DOUBLE_QUOTES.sub('""', elided)
tomwalters@0 898 return elided
tomwalters@0 899
tomwalters@0 900
tomwalters@0 901 def CloseExpression(clean_lines, linenum, pos):
tomwalters@0 902 """If input points to ( or { or [, finds the position that closes it.
tomwalters@0 903
tomwalters@0 904 If lines[linenum][pos] points to a '(' or '{' or '[', finds the the
tomwalters@0 905 linenum/pos that correspond to the closing of the expression.
tomwalters@0 906
tomwalters@0 907 Args:
tomwalters@0 908 clean_lines: A CleansedLines instance containing the file.
tomwalters@0 909 linenum: The number of the line to check.
tomwalters@0 910 pos: A position on the line.
tomwalters@0 911
tomwalters@0 912 Returns:
tomwalters@0 913 A tuple (line, linenum, pos) pointer *past* the closing brace, or
tomwalters@0 914 (line, len(lines), -1) if we never find a close. Note we ignore
tomwalters@0 915 strings and comments when matching; and the line we return is the
tomwalters@0 916 'cleansed' line at linenum.
tomwalters@0 917 """
tomwalters@0 918
tomwalters@0 919 line = clean_lines.elided[linenum]
tomwalters@0 920 startchar = line[pos]
tomwalters@0 921 if startchar not in '({[':
tomwalters@0 922 return (line, clean_lines.NumLines(), -1)
tomwalters@0 923 if startchar == '(': endchar = ')'
tomwalters@0 924 if startchar == '[': endchar = ']'
tomwalters@0 925 if startchar == '{': endchar = '}'
tomwalters@0 926
tomwalters@0 927 num_open = line.count(startchar) - line.count(endchar)
tomwalters@0 928 while linenum < clean_lines.NumLines() and num_open > 0:
tomwalters@0 929 linenum += 1
tomwalters@0 930 line = clean_lines.elided[linenum]
tomwalters@0 931 num_open += line.count(startchar) - line.count(endchar)
tomwalters@0 932 # OK, now find the endchar that actually got us back to even
tomwalters@0 933 endpos = len(line)
tomwalters@0 934 while num_open >= 0:
tomwalters@0 935 endpos = line.rfind(')', 0, endpos)
tomwalters@0 936 num_open -= 1 # chopped off another )
tomwalters@0 937 return (line, linenum, endpos + 1)
tomwalters@0 938
tomwalters@0 939
tomwalters@0 940 def CheckForCopyright(filename, lines, error):
tomwalters@0 941 """Logs an error if no Copyright message appears at the top of the file."""
tomwalters@0 942
tomwalters@0 943 # We'll say it should occur by line 10. Don't forget there's a
tomwalters@0 944 # dummy line at the front.
tomwalters@0 945 for line in xrange(1, min(len(lines), 11)):
tomwalters@0 946 if re.search(r'Copyright', lines[line], re.I): break
tomwalters@0 947 else: # means no copyright line was found
tomwalters@0 948 error(filename, 0, 'legal/copyright', 5,
tomwalters@0 949 'No copyright message found. '
tomwalters@0 950 'You should have a line: "Copyright [year] <Copyright Owner>"')
tomwalters@0 951
tomwalters@0 952
tomwalters@0 953 def GetHeaderGuardCPPVariable(filename):
tomwalters@0 954 """Returns the CPP variable that should be used as a header guard.
tomwalters@0 955
tomwalters@0 956 Args:
tomwalters@0 957 filename: The name of a C++ header file.
tomwalters@0 958
tomwalters@0 959 Returns:
tomwalters@0 960 The CPP variable that should be used as a header guard in the
tomwalters@0 961 named file.
tomwalters@0 962
tomwalters@0 963 """
tomwalters@0 964
tomwalters@0 965 fileinfo = FileInfo(filename)
tomwalters@0 966 return re.sub(r'[-./\s]', '_', fileinfo.RepositoryName()).upper() + '_'
tomwalters@0 967
tomwalters@0 968
tomwalters@0 969 def CheckForHeaderGuard(filename, lines, error):
tomwalters@0 970 """Checks that the file contains a header guard.
tomwalters@0 971
tomwalters@0 972 Logs an error if no #ifndef header guard is present. For other
tomwalters@0 973 headers, checks that the full pathname is used.
tomwalters@0 974
tomwalters@0 975 Args:
tomwalters@0 976 filename: The name of the C++ header file.
tomwalters@0 977 lines: An array of strings, each representing a line of the file.
tomwalters@0 978 error: The function to call with any errors found.
tomwalters@0 979 """
tomwalters@0 980
tomwalters@0 981 cppvar = GetHeaderGuardCPPVariable(filename)
tomwalters@0 982
tomwalters@0 983 ifndef = None
tomwalters@0 984 ifndef_linenum = 0
tomwalters@0 985 define = None
tomwalters@0 986 endif = None
tomwalters@0 987 endif_linenum = 0
tomwalters@0 988 for linenum, line in enumerate(lines):
tomwalters@0 989 linesplit = line.split()
tomwalters@0 990 if len(linesplit) >= 2:
tomwalters@0 991 # find the first occurrence of #ifndef and #define, save arg
tomwalters@0 992 if not ifndef and linesplit[0] == '#ifndef':
tomwalters@0 993 # set ifndef to the header guard presented on the #ifndef line.
tomwalters@0 994 ifndef = linesplit[1]
tomwalters@0 995 ifndef_linenum = linenum
tomwalters@0 996 if not define and linesplit[0] == '#define':
tomwalters@0 997 define = linesplit[1]
tomwalters@0 998 # find the last occurrence of #endif, save entire line
tomwalters@0 999 if line.startswith('#endif'):
tomwalters@0 1000 endif = line
tomwalters@0 1001 endif_linenum = linenum
tomwalters@0 1002
tomwalters@0 1003 if not ifndef or not define or ifndef != define:
tomwalters@0 1004 error(filename, 0, 'build/header_guard', 5,
tomwalters@0 1005 'No #ifndef header guard found, suggested CPP variable is: %s' %
tomwalters@0 1006 cppvar)
tomwalters@0 1007 return
tomwalters@0 1008
tomwalters@0 1009 # The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__
tomwalters@0 1010 # for backward compatibility.
tomwalters@0 1011 if ifndef != cppvar and not Search(r'\bNOLINT\b', lines[ifndef_linenum]):
tomwalters@0 1012 error_level = 0
tomwalters@0 1013 if ifndef != cppvar + '_':
tomwalters@0 1014 error_level = 5
tomwalters@0 1015
tomwalters@0 1016 error(filename, ifndef_linenum, 'build/header_guard', error_level,
tomwalters@0 1017 '#ifndef header guard has wrong style, please use: %s' % cppvar)
tomwalters@0 1018
tomwalters@0 1019 if (endif != ('#endif // %s' % cppvar) and
tomwalters@0 1020 not Search(r'\bNOLINT\b', lines[endif_linenum])):
tomwalters@0 1021 error_level = 0
tomwalters@0 1022 if endif != ('#endif // %s' % (cppvar + '_')):
tomwalters@0 1023 error_level = 5
tomwalters@0 1024
tomwalters@0 1025 error(filename, endif_linenum, 'build/header_guard', error_level,
tomwalters@0 1026 '#endif line should be "#endif // %s"' % cppvar)
tomwalters@0 1027
tomwalters@0 1028
tomwalters@0 1029 def CheckForUnicodeReplacementCharacters(filename, lines, error):
tomwalters@0 1030 """Logs an error for each line containing Unicode replacement characters.
tomwalters@0 1031
tomwalters@0 1032 These indicate that either the file contained invalid UTF-8 (likely)
tomwalters@0 1033 or Unicode replacement characters (which it shouldn't). Note that
tomwalters@0 1034 it's possible for this to throw off line numbering if the invalid
tomwalters@0 1035 UTF-8 occurred adjacent to a newline.
tomwalters@0 1036
tomwalters@0 1037 Args:
tomwalters@0 1038 filename: The name of the current file.
tomwalters@0 1039 lines: An array of strings, each representing a line of the file.
tomwalters@0 1040 error: The function to call with any errors found.
tomwalters@0 1041 """
tomwalters@0 1042 for linenum, line in enumerate(lines):
tomwalters@0 1043 if u'\ufffd' in line:
tomwalters@0 1044 error(filename, linenum, 'readability/utf8', 5,
tomwalters@0 1045 'Line contains invalid UTF-8 (or Unicode replacement character).')
tomwalters@0 1046
tomwalters@0 1047
tomwalters@0 1048 def CheckForNewlineAtEOF(filename, lines, error):
tomwalters@0 1049 """Logs an error if there is no newline char at the end of the file.
tomwalters@0 1050
tomwalters@0 1051 Args:
tomwalters@0 1052 filename: The name of the current file.
tomwalters@0 1053 lines: An array of strings, each representing a line of the file.
tomwalters@0 1054 error: The function to call with any errors found.
tomwalters@0 1055 """
tomwalters@0 1056
tomwalters@0 1057 # The array lines() was created by adding two newlines to the
tomwalters@0 1058 # original file (go figure), then splitting on \n.
tomwalters@0 1059 # To verify that the file ends in \n, we just have to make sure the
tomwalters@0 1060 # last-but-two element of lines() exists and is empty.
tomwalters@0 1061 if len(lines) < 3 or lines[-2]:
tomwalters@0 1062 error(filename, len(lines) - 2, 'whitespace/ending_newline', 5,
tomwalters@0 1063 'Could not find a newline character at the end of the file.')
tomwalters@0 1064
tomwalters@0 1065
tomwalters@0 1066 def CheckForMultilineCommentsAndStrings(filename, clean_lines, linenum, error):
tomwalters@0 1067 """Logs an error if we see /* ... */ or "..." that extend past one line.
tomwalters@0 1068
tomwalters@0 1069 /* ... */ comments are legit inside macros, for one line.
tomwalters@0 1070 Otherwise, we prefer // comments, so it's ok to warn about the
tomwalters@0 1071 other. Likewise, it's ok for strings to extend across multiple
tomwalters@0 1072 lines, as long as a line continuation character (backslash)
tomwalters@0 1073 terminates each line. Although not currently prohibited by the C++
tomwalters@0 1074 style guide, it's ugly and unnecessary. We don't do well with either
tomwalters@0 1075 in this lint program, so we warn about both.
tomwalters@0 1076
tomwalters@0 1077 Args:
tomwalters@0 1078 filename: The name of the current file.
tomwalters@0 1079 clean_lines: A CleansedLines instance containing the file.
tomwalters@0 1080 linenum: The number of the line to check.
tomwalters@0 1081 error: The function to call with any errors found.
tomwalters@0 1082 """
tomwalters@0 1083 line = clean_lines.elided[linenum]
tomwalters@0 1084
tomwalters@0 1085 # Remove all \\ (escaped backslashes) from the line. They are OK, and the
tomwalters@0 1086 # second (escaped) slash may trigger later \" detection erroneously.
tomwalters@0 1087 line = line.replace('\\\\', '')
tomwalters@0 1088
tomwalters@0 1089 if line.count('/*') > line.count('*/'):
tomwalters@0 1090 error(filename, linenum, 'readability/multiline_comment', 5,
tomwalters@0 1091 'Complex multi-line /*...*/-style comment found. '
tomwalters@0 1092 'Lint may give bogus warnings. '
tomwalters@0 1093 'Consider replacing these with //-style comments, '
tomwalters@0 1094 'with #if 0...#endif, '
tomwalters@0 1095 'or with more clearly structured multi-line comments.')
tomwalters@0 1096
tomwalters@0 1097 if (line.count('"') - line.count('\\"')) % 2:
tomwalters@0 1098 error(filename, linenum, 'readability/multiline_string', 5,
tomwalters@0 1099 'Multi-line string ("...") found. This lint script doesn\'t '
tomwalters@0 1100 'do well with such strings, and may give bogus warnings. They\'re '
tomwalters@0 1101 'ugly and unnecessary, and you should use concatenation instead".')
tomwalters@0 1102
tomwalters@0 1103
tomwalters@0 1104 threading_list = (
tomwalters@0 1105 ('asctime(', 'asctime_r('),
tomwalters@0 1106 ('ctime(', 'ctime_r('),
tomwalters@0 1107 ('getgrgid(', 'getgrgid_r('),
tomwalters@0 1108 ('getgrnam(', 'getgrnam_r('),
tomwalters@0 1109 ('getlogin(', 'getlogin_r('),
tomwalters@0 1110 ('getpwnam(', 'getpwnam_r('),
tomwalters@0 1111 ('getpwuid(', 'getpwuid_r('),
tomwalters@0 1112 ('gmtime(', 'gmtime_r('),
tomwalters@0 1113 ('localtime(', 'localtime_r('),
tomwalters@0 1114 ('rand(', 'rand_r('),
tomwalters@0 1115 ('readdir(', 'readdir_r('),
tomwalters@0 1116 ('strtok(', 'strtok_r('),
tomwalters@0 1117 ('ttyname(', 'ttyname_r('),
tomwalters@0 1118 )
tomwalters@0 1119
tomwalters@0 1120
tomwalters@0 1121 def CheckPosixThreading(filename, clean_lines, linenum, error):
tomwalters@0 1122 """Checks for calls to thread-unsafe functions.
tomwalters@0 1123
tomwalters@0 1124 Much code has been originally written without consideration of
tomwalters@0 1125 multi-threading. Also, engineers are relying on their old experience;
tomwalters@0 1126 they have learned posix before threading extensions were added. These
tomwalters@0 1127 tests guide the engineers to use thread-safe functions (when using
tomwalters@0 1128 posix directly).
tomwalters@0 1129
tomwalters@0 1130 Args:
tomwalters@0 1131 filename: The name of the current file.
tomwalters@0 1132 clean_lines: A CleansedLines instance containing the file.
tomwalters@0 1133 linenum: The number of the line to check.
tomwalters@0 1134 error: The function to call with any errors found.
tomwalters@0 1135 """
tomwalters@0 1136 line = clean_lines.elided[linenum]
tomwalters@0 1137 for single_thread_function, multithread_safe_function in threading_list:
tomwalters@0 1138 ix = line.find(single_thread_function)
tomwalters@0 1139 # Comparisons made explicit for clarity -- pylint: disable-msg=C6403
tomwalters@0 1140 if ix >= 0 and (ix == 0 or (not line[ix - 1].isalnum() and
tomwalters@0 1141 line[ix - 1] not in ('_', '.', '>'))):
tomwalters@0 1142 error(filename, linenum, 'runtime/threadsafe_fn', 2,
tomwalters@0 1143 'Consider using ' + multithread_safe_function +
tomwalters@0 1144 '...) instead of ' + single_thread_function +
tomwalters@0 1145 '...) for improved thread safety.')
tomwalters@0 1146
tomwalters@0 1147
tomwalters@0 1148 # Matches invalid increment: *count++, which moves pointer instead of
tomwalters@0 1149 # incrementing a value.
tomwalters@0 1150 _RE_PATTERN_INVALID_INCREMENT = re.compile(
tomwalters@0 1151 r'^\s*\*\w+(\+\+|--);')
tomwalters@0 1152
tomwalters@0 1153
tomwalters@0 1154 def CheckInvalidIncrement(filename, clean_lines, linenum, error):
tomwalters@0 1155 """Checks for invalid increment *count++.
tomwalters@0 1156
tomwalters@0 1157 For example following function:
tomwalters@0 1158 void increment_counter(int* count) {
tomwalters@0 1159 *count++;
tomwalters@0 1160 }
tomwalters@0 1161 is invalid, because it effectively does count++, moving pointer, and should
tomwalters@0 1162 be replaced with ++*count, (*count)++ or *count += 1.
tomwalters@0 1163
tomwalters@0 1164 Args:
tomwalters@0 1165 filename: The name of the current file.
tomwalters@0 1166 clean_lines: A CleansedLines instance containing the file.
tomwalters@0 1167 linenum: The number of the line to check.
tomwalters@0 1168 error: The function to call with any errors found.
tomwalters@0 1169 """
tomwalters@0 1170 line = clean_lines.elided[linenum]
tomwalters@0 1171 if _RE_PATTERN_INVALID_INCREMENT.match(line):
tomwalters@0 1172 error(filename, linenum, 'runtime/invalid_increment', 5,
tomwalters@0 1173 'Changing pointer instead of value (or unused value of operator*).')
tomwalters@0 1174
tomwalters@0 1175
tomwalters@0 1176 class _ClassInfo(object):
tomwalters@0 1177 """Stores information about a class."""
tomwalters@0 1178
tomwalters@0 1179 def __init__(self, name, linenum):
tomwalters@0 1180 self.name = name
tomwalters@0 1181 self.linenum = linenum
tomwalters@0 1182 self.seen_open_brace = False
tomwalters@0 1183 self.is_derived = False
tomwalters@0 1184 self.virtual_method_linenumber = None
tomwalters@0 1185 self.has_virtual_destructor = False
tomwalters@0 1186 self.brace_depth = 0
tomwalters@0 1187
tomwalters@0 1188
tomwalters@0 1189 class _ClassState(object):
tomwalters@0 1190 """Holds the current state of the parse relating to class declarations.
tomwalters@0 1191
tomwalters@0 1192 It maintains a stack of _ClassInfos representing the parser's guess
tomwalters@0 1193 as to the current nesting of class declarations. The innermost class
tomwalters@0 1194 is at the top (back) of the stack. Typically, the stack will either
tomwalters@0 1195 be empty or have exactly one entry.
tomwalters@0 1196 """
tomwalters@0 1197
tomwalters@0 1198 def __init__(self):
tomwalters@0 1199 self.classinfo_stack = []
tomwalters@0 1200
tomwalters@0 1201 def CheckFinished(self, filename, error):
tomwalters@0 1202 """Checks that all classes have been completely parsed.
tomwalters@0 1203
tomwalters@0 1204 Call this when all lines in a file have been processed.
tomwalters@0 1205 Args:
tomwalters@0 1206 filename: The name of the current file.
tomwalters@0 1207 error: The function to call with any errors found.
tomwalters@0 1208 """
tomwalters@0 1209 if self.classinfo_stack:
tomwalters@0 1210 # Note: This test can result in false positives if #ifdef constructs
tomwalters@0 1211 # get in the way of brace matching. See the testBuildClass test in
tomwalters@0 1212 # cpplint_unittest.py for an example of this.
tomwalters@0 1213 error(filename, self.classinfo_stack[0].linenum, 'build/class', 5,
tomwalters@0 1214 'Failed to find complete declaration of class %s' %
tomwalters@0 1215 self.classinfo_stack[0].name)
tomwalters@0 1216
tomwalters@0 1217
tomwalters@0 1218 def CheckForNonStandardConstructs(filename, clean_lines, linenum,
tomwalters@0 1219 class_state, error):
tomwalters@0 1220 """Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
tomwalters@0 1221
tomwalters@0 1222 Complain about several constructs which gcc-2 accepts, but which are
tomwalters@0 1223 not standard C++. Warning about these in lint is one way to ease the
tomwalters@0 1224 transition to new compilers.
tomwalters@0 1225 - put storage class first (e.g. "static const" instead of "const static").
tomwalters@0 1226 - "%lld" instead of %qd" in printf-type functions.
tomwalters@0 1227 - "%1$d" is non-standard in printf-type functions.
tomwalters@0 1228 - "\%" is an undefined character escape sequence.
tomwalters@0 1229 - text after #endif is not allowed.
tomwalters@0 1230 - invalid inner-style forward declaration.
tomwalters@0 1231 - >? and <? operators, and their >?= and <?= cousins.
tomwalters@0 1232 - classes with virtual methods need virtual destructors (compiler warning
tomwalters@0 1233 available, but not turned on yet.)
tomwalters@0 1234
tomwalters@0 1235 Additionally, check for constructor/destructor style violations and reference
tomwalters@0 1236 members, as it is very convenient to do so while checking for
tomwalters@0 1237 gcc-2 compliance.
tomwalters@0 1238
tomwalters@0 1239 Args:
tomwalters@0 1240 filename: The name of the current file.
tomwalters@0 1241 clean_lines: A CleansedLines instance containing the file.
tomwalters@0 1242 linenum: The number of the line to check.
tomwalters@0 1243 class_state: A _ClassState instance which maintains information about
tomwalters@0 1244 the current stack of nested class declarations being parsed.
tomwalters@0 1245 error: A callable to which errors are reported, which takes 4 arguments:
tomwalters@0 1246 filename, line number, error level, and message
tomwalters@0 1247 """
tomwalters@0 1248
tomwalters@0 1249 # Remove comments from the line, but leave in strings for now.
tomwalters@0 1250 line = clean_lines.lines[linenum]
tomwalters@0 1251
tomwalters@0 1252 if Search(r'printf\s*\(.*".*%[-+ ]?\d*q', line):
tomwalters@0 1253 error(filename, linenum, 'runtime/printf_format', 3,
tomwalters@0 1254 '%q in format strings is deprecated. Use %ll instead.')
tomwalters@0 1255
tomwalters@0 1256 if Search(r'printf\s*\(.*".*%\d+\$', line):
tomwalters@0 1257 error(filename, linenum, 'runtime/printf_format', 2,
tomwalters@0 1258 '%N$ formats are unconventional. Try rewriting to avoid them.')
tomwalters@0 1259
tomwalters@0 1260 # Remove escaped backslashes before looking for undefined escapes.
tomwalters@0 1261 line = line.replace('\\\\', '')
tomwalters@0 1262
tomwalters@0 1263 if Search(r'("|\').*\\(%|\[|\(|{)', line):
tomwalters@0 1264 error(filename, linenum, 'build/printf_format', 3,
tomwalters@0 1265 '%, [, (, and { are undefined character escapes. Unescape them.')
tomwalters@0 1266
tomwalters@0 1267 # For the rest, work with both comments and strings removed.
tomwalters@0 1268 line = clean_lines.elided[linenum]
tomwalters@0 1269
tomwalters@0 1270 if Search(r'\b(const|volatile|void|char|short|int|long'
tomwalters@0 1271 r'|float|double|signed|unsigned'
tomwalters@0 1272 r'|schar|u?int8|u?int16|u?int32|u?int64)'
tomwalters@0 1273 r'\s+(auto|register|static|extern|typedef)\b',
tomwalters@0 1274 line):
tomwalters@0 1275 error(filename, linenum, 'build/storage_class', 5,
tomwalters@0 1276 'Storage class (static, extern, typedef, etc) should be first.')
tomwalters@0 1277
tomwalters@0 1278 if Match(r'\s*#\s*endif\s*[^/\s]+', line):
tomwalters@0 1279 error(filename, linenum, 'build/endif_comment', 5,
tomwalters@0 1280 'Uncommented text after #endif is non-standard. Use a comment.')
tomwalters@0 1281
tomwalters@0 1282 if Match(r'\s*class\s+(\w+\s*::\s*)+\w+\s*;', line):
tomwalters@0 1283 error(filename, linenum, 'build/forward_decl', 5,
tomwalters@0 1284 'Inner-style forward declarations are invalid. Remove this line.')
tomwalters@0 1285
tomwalters@0 1286 if Search(r'(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?',
tomwalters@0 1287 line):
tomwalters@0 1288 error(filename, linenum, 'build/deprecated', 3,
tomwalters@0 1289 '>? and <? (max and min) operators are non-standard and deprecated.')
tomwalters@0 1290
tomwalters@0 1291 if Search(r'^\s*const\s*string\s*&\s*\w+\s*;', line):
tomwalters@0 1292 # TODO(unknown): Could it be expanded safely to arbitrary references,
tomwalters@0 1293 # without triggering too many false positives? The first
tomwalters@0 1294 # attempt triggered 5 warnings for mostly benign code in the regtest, hence
tomwalters@0 1295 # the restriction.
tomwalters@0 1296 # Here's the original regexp, for the reference:
tomwalters@0 1297 # type_name = r'\w+((\s*::\s*\w+)|(\s*<\s*\w+?\s*>))?'
tomwalters@0 1298 # r'\s*const\s*' + type_name + '\s*&\s*\w+\s*;'
tomwalters@0 1299 error(filename, linenum, 'runtime/member_string_references', 2,
tomwalters@0 1300 'const string& members are dangerous. It is much better to use '
tomwalters@0 1301 'alternatives, such as pointers or simple constants.')
tomwalters@0 1302
tomwalters@0 1303 # Track class entry and exit, and attempt to find cases within the
tomwalters@0 1304 # class declaration that don't meet the C++ style
tomwalters@0 1305 # guidelines. Tracking is very dependent on the code matching Google
tomwalters@0 1306 # style guidelines, but it seems to perform well enough in testing
tomwalters@0 1307 # to be a worthwhile addition to the checks.
tomwalters@0 1308 classinfo_stack = class_state.classinfo_stack
tomwalters@0 1309 # Look for a class declaration
tomwalters@0 1310 class_decl_match = Match(
tomwalters@0 1311 r'\s*(template\s*<[\w\s<>,:]*>\s*)?(class|struct)\s+(\w+(::\w+)*)', line)
tomwalters@0 1312 if class_decl_match:
tomwalters@0 1313 classinfo_stack.append(_ClassInfo(class_decl_match.group(3), linenum))
tomwalters@0 1314
tomwalters@0 1315 # Everything else in this function uses the top of the stack if it's
tomwalters@0 1316 # not empty.
tomwalters@0 1317 if not classinfo_stack:
tomwalters@0 1318 return
tomwalters@0 1319
tomwalters@0 1320 classinfo = classinfo_stack[-1]
tomwalters@0 1321
tomwalters@0 1322 # If the opening brace hasn't been seen look for it and also
tomwalters@0 1323 # parent class declarations.
tomwalters@0 1324 if not classinfo.seen_open_brace:
tomwalters@0 1325 # If the line has a ';' in it, assume it's a forward declaration or
tomwalters@0 1326 # a single-line class declaration, which we won't process.
tomwalters@0 1327 if line.find(';') != -1:
tomwalters@0 1328 classinfo_stack.pop()
tomwalters@0 1329 return
tomwalters@0 1330 classinfo.seen_open_brace = (line.find('{') != -1)
tomwalters@0 1331 # Look for a bare ':'
tomwalters@0 1332 if Search('(^|[^:]):($|[^:])', line):
tomwalters@0 1333 classinfo.is_derived = True
tomwalters@0 1334 if not classinfo.seen_open_brace:
tomwalters@0 1335 return # Everything else in this function is for after open brace
tomwalters@0 1336
tomwalters@0 1337 # The class may have been declared with namespace or classname qualifiers.
tomwalters@0 1338 # The constructor and destructor will not have those qualifiers.
tomwalters@0 1339 base_classname = classinfo.name.split('::')[-1]
tomwalters@0 1340
tomwalters@0 1341 # Look for single-argument constructors that aren't marked explicit.
tomwalters@0 1342 # Technically a valid construct, but against style.
tomwalters@0 1343 args = Match(r'(?<!explicit)\s+%s\s*\(([^,()]+)\)'
tomwalters@0 1344 % re.escape(base_classname),
tomwalters@0 1345 line)
tomwalters@0 1346 if (args and
tomwalters@0 1347 args.group(1) != 'void' and
tomwalters@0 1348 not Match(r'(const\s+)?%s\s*&' % re.escape(base_classname),
tomwalters@0 1349 args.group(1).strip())):
tomwalters@0 1350 error(filename, linenum, 'runtime/explicit', 5,
tomwalters@0 1351 'Single-argument constructors should be marked explicit.')
tomwalters@0 1352
tomwalters@0 1353 # Look for methods declared virtual.
tomwalters@0 1354 if Search(r'\bvirtual\b', line):
tomwalters@0 1355 classinfo.virtual_method_linenumber = linenum
tomwalters@0 1356 # Only look for a destructor declaration on the same line. It would
tomwalters@0 1357 # be extremely unlikely for the destructor declaration to occupy
tomwalters@0 1358 # more than one line.
tomwalters@0 1359 if Search(r'~%s\s*\(' % base_classname, line):
tomwalters@0 1360 classinfo.has_virtual_destructor = True
tomwalters@0 1361
tomwalters@0 1362 # Look for class end.
tomwalters@0 1363 brace_depth = classinfo.brace_depth
tomwalters@0 1364 brace_depth = brace_depth + line.count('{') - line.count('}')
tomwalters@0 1365 if brace_depth <= 0:
tomwalters@0 1366 classinfo = classinfo_stack.pop()
tomwalters@0 1367 # Try to detect missing virtual destructor declarations.
tomwalters@0 1368 # For now, only warn if a non-derived class with virtual methods lacks
tomwalters@0 1369 # a virtual destructor. This is to make it less likely that people will
tomwalters@0 1370 # declare derived virtual destructors without declaring the base
tomwalters@0 1371 # destructor virtual.
tomwalters@0 1372 if ((classinfo.virtual_method_linenumber is not None) and
tomwalters@0 1373 (not classinfo.has_virtual_destructor) and
tomwalters@0 1374 (not classinfo.is_derived)): # Only warn for base classes
tomwalters@0 1375 error(filename, classinfo.linenum, 'runtime/virtual', 4,
tomwalters@0 1376 'The class %s probably needs a virtual destructor due to '
tomwalters@0 1377 'having virtual method(s), one declared at line %d.'
tomwalters@0 1378 % (classinfo.name, classinfo.virtual_method_linenumber))
tomwalters@0 1379 else:
tomwalters@0 1380 classinfo.brace_depth = brace_depth
tomwalters@0 1381
tomwalters@0 1382
tomwalters@0 1383 def CheckSpacingForFunctionCall(filename, line, linenum, error):
tomwalters@0 1384 """Checks for the correctness of various spacing around function calls.
tomwalters@0 1385
tomwalters@0 1386 Args:
tomwalters@0 1387 filename: The name of the current file.
tomwalters@0 1388 line: The text of the line to check.
tomwalters@0 1389 linenum: The number of the line to check.
tomwalters@0 1390 error: The function to call with any errors found.
tomwalters@0 1391 """
tomwalters@0 1392
tomwalters@0 1393 # Since function calls often occur inside if/for/while/switch
tomwalters@0 1394 # expressions - which have their own, more liberal conventions - we
tomwalters@0 1395 # first see if we should be looking inside such an expression for a
tomwalters@0 1396 # function call, to which we can apply more strict standards.
tomwalters@0 1397 fncall = line # if there's no control flow construct, look at whole line
tomwalters@0 1398 for pattern in (r'\bif\s*\((.*)\)\s*{',
tomwalters@0 1399 r'\bfor\s*\((.*)\)\s*{',
tomwalters@0 1400 r'\bwhile\s*\((.*)\)\s*[{;]',
tomwalters@0 1401 r'\bswitch\s*\((.*)\)\s*{'):
tomwalters@0 1402 match = Search(pattern, line)
tomwalters@0 1403 if match:
tomwalters@0 1404 fncall = match.group(1) # look inside the parens for function calls
tomwalters@0 1405 break
tomwalters@0 1406
tomwalters@0 1407 # Except in if/for/while/switch, there should never be space
tomwalters@0 1408 # immediately inside parens (eg "f( 3, 4 )"). We make an exception
tomwalters@0 1409 # for nested parens ( (a+b) + c ). Likewise, there should never be
tomwalters@0 1410 # a space before a ( when it's a function argument. I assume it's a
tomwalters@0 1411 # function argument when the char before the whitespace is legal in
tomwalters@0 1412 # a function name (alnum + _) and we're not starting a macro. Also ignore
tomwalters@0 1413 # pointers and references to arrays and functions coz they're too tricky:
tomwalters@0 1414 # we use a very simple way to recognize these:
tomwalters@0 1415 # " (something)(maybe-something)" or
tomwalters@0 1416 # " (something)(maybe-something," or
tomwalters@0 1417 # " (something)[something]"
tomwalters@0 1418 # Note that we assume the contents of [] to be short enough that
tomwalters@0 1419 # they'll never need to wrap.
tomwalters@0 1420 if ( # Ignore control structures.
tomwalters@0 1421 not Search(r'\b(if|for|while|switch|return|delete)\b', fncall) and
tomwalters@0 1422 # Ignore pointers/references to functions.
tomwalters@0 1423 not Search(r' \([^)]+\)\([^)]*(\)|,$)', fncall) and
tomwalters@0 1424 # Ignore pointers/references to arrays.
tomwalters@0 1425 not Search(r' \([^)]+\)\[[^\]]+\]', fncall)):
tomwalters@0 1426 if Search(r'\w\s*\(\s(?!\s*\\$)', fncall): # a ( used for a fn call
tomwalters@0 1427 error(filename, linenum, 'whitespace/parens', 4,
tomwalters@0 1428 'Extra space after ( in function call')
tomwalters@0 1429 elif Search(r'\(\s+(?!(\s*\\)|\()', fncall):
tomwalters@0 1430 error(filename, linenum, 'whitespace/parens', 2,
tomwalters@0 1431 'Extra space after (')
tomwalters@0 1432 if (Search(r'\w\s+\(', fncall) and
tomwalters@0 1433 not Search(r'#\s*define|typedef', fncall)):
tomwalters@0 1434 error(filename, linenum, 'whitespace/parens', 4,
tomwalters@0 1435 'Extra space before ( in function call')
tomwalters@0 1436 # If the ) is followed only by a newline or a { + newline, assume it's
tomwalters@0 1437 # part of a control statement (if/while/etc), and don't complain
tomwalters@0 1438 if Search(r'[^)]\s+\)\s*[^{\s]', fncall):
tomwalters@0 1439 error(filename, linenum, 'whitespace/parens', 2,
tomwalters@0 1440 'Extra space before )')
tomwalters@0 1441
tomwalters@0 1442
tomwalters@0 1443 def IsBlankLine(line):
tomwalters@0 1444 """Returns true if the given line is blank.
tomwalters@0 1445
tomwalters@0 1446 We consider a line to be blank if the line is empty or consists of
tomwalters@0 1447 only white spaces.
tomwalters@0 1448
tomwalters@0 1449 Args:
tomwalters@0 1450 line: A line of a string.
tomwalters@0 1451
tomwalters@0 1452 Returns:
tomwalters@0 1453 True, if the given line is blank.
tomwalters@0 1454 """
tomwalters@0 1455 return not line or line.isspace()
tomwalters@0 1456
tomwalters@0 1457
tomwalters@0 1458 def CheckForFunctionLengths(filename, clean_lines, linenum,
tomwalters@0 1459 function_state, error):
tomwalters@0 1460 """Reports for long function bodies.
tomwalters@0 1461
tomwalters@0 1462 For an overview why this is done, see:
tomwalters@0 1463 http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions
tomwalters@0 1464
tomwalters@0 1465 Uses a simplistic algorithm assuming other style guidelines
tomwalters@0 1466 (especially spacing) are followed.
tomwalters@0 1467 Only checks unindented functions, so class members are unchecked.
tomwalters@0 1468 Trivial bodies are unchecked, so constructors with huge initializer lists
tomwalters@0 1469 may be missed.
tomwalters@0 1470 Blank/comment lines are not counted so as to avoid encouraging the removal
tomwalters@0 1471 of vertical space and commments just to get through a lint check.
tomwalters@0 1472 NOLINT *on the last line of a function* disables this check.
tomwalters@0 1473
tomwalters@0 1474 Args:
tomwalters@0 1475 filename: The name of the current file.
tomwalters@0 1476 clean_lines: A CleansedLines instance containing the file.
tomwalters@0 1477 linenum: The number of the line to check.
tomwalters@0 1478 function_state: Current function name and lines in body so far.
tomwalters@0 1479 error: The function to call with any errors found.
tomwalters@0 1480 """
tomwalters@0 1481 lines = clean_lines.lines
tomwalters@0 1482 line = lines[linenum]
tomwalters@0 1483 raw = clean_lines.raw_lines
tomwalters@0 1484 raw_line = raw[linenum]
tomwalters@0 1485 joined_line = ''
tomwalters@0 1486
tomwalters@0 1487 starting_func = False
tomwalters@0 1488 regexp = r'(\w(\w|::|\*|\&|\s)*)\(' # decls * & space::name( ...
tomwalters@0 1489 match_result = Match(regexp, line)
tomwalters@0 1490 if match_result:
tomwalters@0 1491 # If the name is all caps and underscores, figure it's a macro and
tomwalters@0 1492 # ignore it, unless it's TEST or TEST_F.
tomwalters@0 1493 function_name = match_result.group(1).split()[-1]
tomwalters@0 1494 if function_name == 'TEST' or function_name == 'TEST_F' or (
tomwalters@0 1495 not Match(r'[A-Z_]+$', function_name)):
tomwalters@0 1496 starting_func = True
tomwalters@0 1497
tomwalters@0 1498 if starting_func:
tomwalters@0 1499 body_found = False
tomwalters@0 1500 for start_linenum in xrange(linenum, clean_lines.NumLines()):
tomwalters@0 1501 start_line = lines[start_linenum]
tomwalters@0 1502 joined_line += ' ' + start_line.lstrip()
tomwalters@0 1503 if Search(r'(;|})', start_line): # Declarations and trivial functions
tomwalters@0 1504 body_found = True
tomwalters@0 1505 break # ... ignore
tomwalters@0 1506 elif Search(r'{', start_line):
tomwalters@0 1507 body_found = True
tomwalters@0 1508 function = Search(r'((\w|:)*)\(', line).group(1)
tomwalters@0 1509 if Match(r'TEST', function): # Handle TEST... macros
tomwalters@0 1510 parameter_regexp = Search(r'(\(.*\))', joined_line)
tomwalters@0 1511 if parameter_regexp: # Ignore bad syntax
tomwalters@0 1512 function += parameter_regexp.group(1)
tomwalters@0 1513 else:
tomwalters@0 1514 function += '()'
tomwalters@0 1515 function_state.Begin(function)
tomwalters@0 1516 break
tomwalters@0 1517 if not body_found:
tomwalters@0 1518 # No body for the function (or evidence of a non-function) was found.
tomwalters@0 1519 error(filename, linenum, 'readability/fn_size', 5,
tomwalters@0 1520 'Lint failed to find start of function body.')
tomwalters@0 1521 elif Match(r'^\}\s*$', line): # function end
tomwalters@0 1522 if not Search(r'\bNOLINT\b', raw_line):
tomwalters@0 1523 function_state.Check(error, filename, linenum)
tomwalters@0 1524 function_state.End()
tomwalters@0 1525 elif not Match(r'^\s*$', line):
tomwalters@0 1526 function_state.Count() # Count non-blank/non-comment lines.
tomwalters@0 1527
tomwalters@0 1528
tomwalters@0 1529 _RE_PATTERN_TODO = re.compile(r'^//(\s*)TODO(\(.+?\))?:?(\s|$)?')
tomwalters@0 1530
tomwalters@0 1531
tomwalters@0 1532 def CheckComment(comment, filename, linenum, error):
tomwalters@0 1533 """Checks for common mistakes in TODO comments.
tomwalters@0 1534
tomwalters@0 1535 Args:
tomwalters@0 1536 comment: The text of the comment from the line in question.
tomwalters@0 1537 filename: The name of the current file.
tomwalters@0 1538 linenum: The number of the line to check.
tomwalters@0 1539 error: The function to call with any errors found.
tomwalters@0 1540 """
tomwalters@0 1541 match = _RE_PATTERN_TODO.match(comment)
tomwalters@0 1542 if match:
tomwalters@0 1543 # One whitespace is correct; zero whitespace is handled elsewhere.
tomwalters@0 1544 leading_whitespace = match.group(1)
tomwalters@0 1545 if len(leading_whitespace) > 1:
tomwalters@0 1546 error(filename, linenum, 'whitespace/todo', 2,
tomwalters@0 1547 'Too many spaces before TODO')
tomwalters@0 1548
tomwalters@0 1549 username = match.group(2)
tomwalters@0 1550 if not username:
tomwalters@0 1551 error(filename, linenum, 'readability/todo', 2,
tomwalters@0 1552 'Missing username in TODO; it should look like '
tomwalters@0 1553 '"// TODO(my_username): Stuff."')
tomwalters@0 1554
tomwalters@0 1555 middle_whitespace = match.group(3)
tomwalters@0 1556 # Comparisons made explicit for correctness -- pylint: disable-msg=C6403
tomwalters@0 1557 if middle_whitespace != ' ' and middle_whitespace != '':
tomwalters@0 1558 error(filename, linenum, 'whitespace/todo', 2,
tomwalters@0 1559 'TODO(my_username) should be followed by a space')
tomwalters@0 1560
tomwalters@0 1561
tomwalters@0 1562 def CheckSpacing(filename, clean_lines, linenum, error):
tomwalters@0 1563 """Checks for the correctness of various spacing issues in the code.
tomwalters@0 1564
tomwalters@0 1565 Things we check for: spaces around operators, spaces after
tomwalters@0 1566 if/for/while/switch, no spaces around parens in function calls, two
tomwalters@0 1567 spaces between code and comment, don't start a block with a blank
tomwalters@0 1568 line, don't end a function with a blank line, don't have too many
tomwalters@0 1569 blank lines in a row.
tomwalters@0 1570
tomwalters@0 1571 Args:
tomwalters@0 1572 filename: The name of the current file.
tomwalters@0 1573 clean_lines: A CleansedLines instance containing the file.
tomwalters@0 1574 linenum: The number of the line to check.
tomwalters@0 1575 error: The function to call with any errors found.
tomwalters@0 1576 """
tomwalters@0 1577
tomwalters@0 1578 raw = clean_lines.raw_lines
tomwalters@0 1579 line = raw[linenum]
tomwalters@0 1580
tomwalters@0 1581 # Before nixing comments, check if the line is blank for no good
tomwalters@0 1582 # reason. This includes the first line after a block is opened, and
tomwalters@0 1583 # blank lines at the end of a function (ie, right before a line like '}'
tomwalters@0 1584 if IsBlankLine(line):
tomwalters@0 1585 elided = clean_lines.elided
tomwalters@0 1586 prev_line = elided[linenum - 1]
tomwalters@0 1587 prevbrace = prev_line.rfind('{')
tomwalters@0 1588 # TODO(unknown): Don't complain if line before blank line, and line after,
tomwalters@0 1589 # both start with alnums and are indented the same amount.
tomwalters@0 1590 # This ignores whitespace at the start of a namespace block
tomwalters@0 1591 # because those are not usually indented.
tomwalters@0 1592 if (prevbrace != -1 and prev_line[prevbrace:].find('}') == -1
tomwalters@0 1593 and prev_line[:prevbrace].find('namespace') == -1):
tomwalters@0 1594 # OK, we have a blank line at the start of a code block. Before we
tomwalters@0 1595 # complain, we check if it is an exception to the rule: The previous
tomwalters@0 1596 # non-empty line has the paramters of a function header that are indented
tomwalters@0 1597 # 4 spaces (because they did not fit in a 80 column line when placed on
tomwalters@0 1598 # the same line as the function name). We also check for the case where
tomwalters@0 1599 # the previous line is indented 6 spaces, which may happen when the
tomwalters@0 1600 # initializers of a constructor do not fit into a 80 column line.
tomwalters@0 1601 exception = False
tomwalters@0 1602 if Match(r' {6}\w', prev_line): # Initializer list?
tomwalters@0 1603 # We are looking for the opening column of initializer list, which
tomwalters@0 1604 # should be indented 4 spaces to cause 6 space indentation afterwards.
tomwalters@0 1605 search_position = linenum-2
tomwalters@0 1606 while (search_position >= 0
tomwalters@0 1607 and Match(r' {6}\w', elided[search_position])):
tomwalters@0 1608 search_position -= 1
tomwalters@0 1609 exception = (search_position >= 0
tomwalters@0 1610 and elided[search_position][:5] == ' :')
tomwalters@0 1611 else:
tomwalters@0 1612 # Search for the function arguments or an initializer list. We use a
tomwalters@0 1613 # simple heuristic here: If the line is indented 4 spaces; and we have a
tomwalters@0 1614 # closing paren, without the opening paren, followed by an opening brace
tomwalters@0 1615 # or colon (for initializer lists) we assume that it is the last line of
tomwalters@0 1616 # a function header. If we have a colon indented 4 spaces, it is an
tomwalters@0 1617 # initializer list.
tomwalters@0 1618 exception = (Match(r' {4}\w[^\(]*\)\s*(const\s*)?(\{\s*$|:)',
tomwalters@0 1619 prev_line)
tomwalters@0 1620 or Match(r' {4}:', prev_line))
tomwalters@0 1621
tomwalters@0 1622 if not exception:
tomwalters@0 1623 error(filename, linenum, 'whitespace/blank_line', 2,
tomwalters@0 1624 'Blank line at the start of a code block. Is this needed?')
tomwalters@0 1625 # This doesn't ignore whitespace at the end of a namespace block
tomwalters@0 1626 # because that is too hard without pairing open/close braces;
tomwalters@0 1627 # however, a special exception is made for namespace closing
tomwalters@0 1628 # brackets which have a comment containing "namespace".
tomwalters@0 1629 #
tomwalters@0 1630 # Also, ignore blank lines at the end of a block in a long if-else
tomwalters@0 1631 # chain, like this:
tomwalters@0 1632 # if (condition1) {
tomwalters@0 1633 # // Something followed by a blank line
tomwalters@0 1634 #
tomwalters@0 1635 # } else if (condition2) {
tomwalters@0 1636 # // Something else
tomwalters@0 1637 # }
tomwalters@0 1638 if linenum + 1 < clean_lines.NumLines():
tomwalters@0 1639 next_line = raw[linenum + 1]
tomwalters@0 1640 if (next_line
tomwalters@0 1641 and Match(r'\s*}', next_line)
tomwalters@0 1642 and next_line.find('namespace') == -1
tomwalters@0 1643 and next_line.find('} else ') == -1):
tomwalters@0 1644 error(filename, linenum, 'whitespace/blank_line', 3,
tomwalters@0 1645 'Blank line at the end of a code block. Is this needed?')
tomwalters@0 1646
tomwalters@0 1647 # Next, we complain if there's a comment too near the text
tomwalters@0 1648 commentpos = line.find('//')
tomwalters@0 1649 if commentpos != -1:
tomwalters@0 1650 # Check if the // may be in quotes. If so, ignore it
tomwalters@0 1651 # Comparisons made explicit for clarity -- pylint: disable-msg=C6403
tomwalters@0 1652 if (line.count('"', 0, commentpos) -
tomwalters@0 1653 line.count('\\"', 0, commentpos)) % 2 == 0: # not in quotes
tomwalters@0 1654 # Allow one space for new scopes, two spaces otherwise:
tomwalters@0 1655 if (not Match(r'^\s*{ //', line) and
tomwalters@0 1656 ((commentpos >= 1 and
tomwalters@0 1657 line[commentpos-1] not in string.whitespace) or
tomwalters@0 1658 (commentpos >= 2 and
tomwalters@0 1659 line[commentpos-2] not in string.whitespace))):
tomwalters@0 1660 error(filename, linenum, 'whitespace/comments', 2,
tomwalters@0 1661 'At least two spaces is best between code and comments')
tomwalters@0 1662 # There should always be a space between the // and the comment
tomwalters@0 1663 commentend = commentpos + 2
tomwalters@0 1664 if commentend < len(line) and not line[commentend] == ' ':
tomwalters@0 1665 # but some lines are exceptions -- e.g. if they're big
tomwalters@0 1666 # comment delimiters like:
tomwalters@0 1667 # //----------------------------------------------------------
tomwalters@0 1668 # or they begin with multiple slashes followed by a space:
tomwalters@0 1669 # //////// Header comment
tomwalters@0 1670 match = (Search(r'[=/-]{4,}\s*$', line[commentend:]) or
tomwalters@0 1671 Search(r'^/+ ', line[commentend:]))
tomwalters@0 1672 if not match:
tomwalters@0 1673 error(filename, linenum, 'whitespace/comments', 4,
tomwalters@0 1674 'Should have a space between // and comment')
tomwalters@0 1675 CheckComment(line[commentpos:], filename, linenum, error)
tomwalters@0 1676
tomwalters@0 1677 line = clean_lines.elided[linenum] # get rid of comments and strings
tomwalters@0 1678
tomwalters@0 1679 # Don't try to do spacing checks for operator methods
tomwalters@0 1680 line = re.sub(r'operator(==|!=|<|<<|<=|>=|>>|>)\(', 'operator\(', line)
tomwalters@0 1681
tomwalters@0 1682 # We allow no-spaces around = within an if: "if ( (a=Foo()) == 0 )".
tomwalters@0 1683 # Otherwise not. Note we only check for non-spaces on *both* sides;
tomwalters@0 1684 # sometimes people put non-spaces on one side when aligning ='s among
tomwalters@0 1685 # many lines (not that this is behavior that I approve of...)
tomwalters@0 1686 if Search(r'[\w.]=[\w.]', line) and not Search(r'\b(if|while) ', line):
tomwalters@0 1687 error(filename, linenum, 'whitespace/operators', 4,
tomwalters@0 1688 'Missing spaces around =')
tomwalters@0 1689
tomwalters@0 1690 # It's ok not to have spaces around binary operators like + - * /, but if
tomwalters@0 1691 # there's too little whitespace, we get concerned. It's hard to tell,
tomwalters@0 1692 # though, so we punt on this one for now. TODO.
tomwalters@0 1693
tomwalters@0 1694 # You should always have whitespace around binary operators.
tomwalters@0 1695 # Alas, we can't test < or > because they're legitimately used sans spaces
tomwalters@0 1696 # (a->b, vector<int> a). The only time we can tell is a < with no >, and
tomwalters@0 1697 # only if it's not template params list spilling into the next line.
tomwalters@0 1698 match = Search(r'[^<>=!\s](==|!=|<=|>=)[^<>=!\s]', line)
tomwalters@0 1699 if not match:
tomwalters@0 1700 # Note that while it seems that the '<[^<]*' term in the following
tomwalters@0 1701 # regexp could be simplified to '<.*', which would indeed match
tomwalters@0 1702 # the same class of strings, the [^<] means that searching for the
tomwalters@0 1703 # regexp takes linear rather than quadratic time.
tomwalters@0 1704 if not Search(r'<[^<]*,\s*$', line): # template params spill
tomwalters@0 1705 match = Search(r'[^<>=!\s](<)[^<>=!\s]([^>]|->)*$', line)
tomwalters@0 1706 if match:
tomwalters@0 1707 error(filename, linenum, 'whitespace/operators', 3,
tomwalters@0 1708 'Missing spaces around %s' % match.group(1))
tomwalters@0 1709 # We allow no-spaces around << and >> when used like this: 10<<20, but
tomwalters@0 1710 # not otherwise (particularly, not when used as streams)
tomwalters@0 1711 match = Search(r'[^0-9\s](<<|>>)[^0-9\s]', line)
tomwalters@0 1712 if match:
tomwalters@0 1713 error(filename, linenum, 'whitespace/operators', 3,
tomwalters@0 1714 'Missing spaces around %s' % match.group(1))
tomwalters@0 1715
tomwalters@0 1716 # There shouldn't be space around unary operators
tomwalters@0 1717 match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line)
tomwalters@0 1718 if match:
tomwalters@0 1719 error(filename, linenum, 'whitespace/operators', 4,
tomwalters@0 1720 'Extra space for operator %s' % match.group(1))
tomwalters@0 1721
tomwalters@0 1722 # A pet peeve of mine: no spaces after an if, while, switch, or for
tomwalters@0 1723 match = Search(r' (if\(|for\(|while\(|switch\()', line)
tomwalters@0 1724 if match:
tomwalters@0 1725 error(filename, linenum, 'whitespace/parens', 5,
tomwalters@0 1726 'Missing space before ( in %s' % match.group(1))
tomwalters@0 1727
tomwalters@0 1728 # For if/for/while/switch, the left and right parens should be
tomwalters@0 1729 # consistent about how many spaces are inside the parens, and
tomwalters@0 1730 # there should either be zero or one spaces inside the parens.
tomwalters@0 1731 # We don't want: "if ( foo)" or "if ( foo )".
tomwalters@0 1732 # Exception: "for ( ; foo; bar)" and "for (foo; bar; )" are allowed.
tomwalters@0 1733 match = Search(r'\b(if|for|while|switch)\s*'
tomwalters@0 1734 r'\(([ ]*)(.).*[^ ]+([ ]*)\)\s*{\s*$',
tomwalters@0 1735 line)
tomwalters@0 1736 if match:
tomwalters@0 1737 if len(match.group(2)) != len(match.group(4)):
tomwalters@0 1738 if not (match.group(3) == ';' and
tomwalters@0 1739 len(match.group(2)) == 1 + len(match.group(4)) or
tomwalters@0 1740 not match.group(2) and Search(r'\bfor\s*\(.*; \)', line)):
tomwalters@0 1741 error(filename, linenum, 'whitespace/parens', 5,
tomwalters@0 1742 'Mismatching spaces inside () in %s' % match.group(1))
tomwalters@0 1743 if not len(match.group(2)) in [0, 1]:
tomwalters@0 1744 error(filename, linenum, 'whitespace/parens', 5,
tomwalters@0 1745 'Should have zero or one spaces inside ( and ) in %s' %
tomwalters@0 1746 match.group(1))
tomwalters@0 1747
tomwalters@0 1748 # You should always have a space after a comma (either as fn arg or operator)
tomwalters@0 1749 if Search(r',[^\s]', line):
tomwalters@0 1750 error(filename, linenum, 'whitespace/comma', 3,
tomwalters@0 1751 'Missing space after ,')
tomwalters@0 1752
tomwalters@0 1753 # Next we will look for issues with function calls.
tomwalters@0 1754 CheckSpacingForFunctionCall(filename, line, linenum, error)
tomwalters@0 1755
tomwalters@0 1756 # Except after an opening paren, you should have spaces before your braces.
tomwalters@0 1757 # And since you should never have braces at the beginning of a line, this is
tomwalters@0 1758 # an easy test.
tomwalters@0 1759 if Search(r'[^ (]{', line):
tomwalters@0 1760 error(filename, linenum, 'whitespace/braces', 5,
tomwalters@0 1761 'Missing space before {')
tomwalters@0 1762
tomwalters@0 1763 # Make sure '} else {' has spaces.
tomwalters@0 1764 if Search(r'}else', line):
tomwalters@0 1765 error(filename, linenum, 'whitespace/braces', 5,
tomwalters@0 1766 'Missing space before else')
tomwalters@0 1767
tomwalters@0 1768 # You shouldn't have spaces before your brackets, except maybe after
tomwalters@0 1769 # 'delete []' or 'new char * []'.
tomwalters@0 1770 if Search(r'\w\s+\[', line) and not Search(r'delete\s+\[', line):
tomwalters@0 1771 error(filename, linenum, 'whitespace/braces', 5,
tomwalters@0 1772 'Extra space before [')
tomwalters@0 1773
tomwalters@0 1774 # You shouldn't have a space before a semicolon at the end of the line.
tomwalters@0 1775 # There's a special case for "for" since the style guide allows space before
tomwalters@0 1776 # the semicolon there.
tomwalters@0 1777 if Search(r':\s*;\s*$', line):
tomwalters@0 1778 error(filename, linenum, 'whitespace/semicolon', 5,
tomwalters@0 1779 'Semicolon defining empty statement. Use { } instead.')
tomwalters@0 1780 elif Search(r'^\s*;\s*$', line):
tomwalters@0 1781 error(filename, linenum, 'whitespace/semicolon', 5,
tomwalters@0 1782 'Line contains only semicolon. If this should be an empty statement, '
tomwalters@0 1783 'use { } instead.')
tomwalters@0 1784 elif (Search(r'\s+;\s*$', line) and
tomwalters@0 1785 not Search(r'\bfor\b', line)):
tomwalters@0 1786 error(filename, linenum, 'whitespace/semicolon', 5,
tomwalters@0 1787 'Extra space before last semicolon. If this should be an empty '
tomwalters@0 1788 'statement, use { } instead.')
tomwalters@0 1789
tomwalters@0 1790
tomwalters@0 1791 def GetPreviousNonBlankLine(clean_lines, linenum):
tomwalters@0 1792 """Return the most recent non-blank line and its line number.
tomwalters@0 1793
tomwalters@0 1794 Args:
tomwalters@0 1795 clean_lines: A CleansedLines instance containing the file contents.
tomwalters@0 1796 linenum: The number of the line to check.
tomwalters@0 1797
tomwalters@0 1798 Returns:
tomwalters@0 1799 A tuple with two elements. The first element is the contents of the last
tomwalters@0 1800 non-blank line before the current line, or the empty string if this is the
tomwalters@0 1801 first non-blank line. The second is the line number of that line, or -1
tomwalters@0 1802 if this is the first non-blank line.
tomwalters@0 1803 """
tomwalters@0 1804
tomwalters@0 1805 prevlinenum = linenum - 1
tomwalters@0 1806 while prevlinenum >= 0:
tomwalters@0 1807 prevline = clean_lines.elided[prevlinenum]
tomwalters@0 1808 if not IsBlankLine(prevline): # if not a blank line...
tomwalters@0 1809 return (prevline, prevlinenum)
tomwalters@0 1810 prevlinenum -= 1
tomwalters@0 1811 return ('', -1)
tomwalters@0 1812
tomwalters@0 1813
tomwalters@0 1814 def CheckBraces(filename, clean_lines, linenum, error):
tomwalters@0 1815 """Looks for misplaced braces (e.g. at the end of line).
tomwalters@0 1816
tomwalters@0 1817 Args:
tomwalters@0 1818 filename: The name of the current file.
tomwalters@0 1819 clean_lines: A CleansedLines instance containing the file.
tomwalters@0 1820 linenum: The number of the line to check.
tomwalters@0 1821 error: The function to call with any errors found.
tomwalters@0 1822 """
tomwalters@0 1823
tomwalters@0 1824 line = clean_lines.elided[linenum] # get rid of comments and strings
tomwalters@0 1825
tomwalters@0 1826 if Match(r'\s*{\s*$', line):
tomwalters@0 1827 # We allow an open brace to start a line in the case where someone
tomwalters@0 1828 # is using braces in a block to explicitly create a new scope,
tomwalters@0 1829 # which is commonly used to control the lifetime of
tomwalters@0 1830 # stack-allocated variables. We don't detect this perfectly: we
tomwalters@0 1831 # just don't complain if the last non-whitespace character on the
tomwalters@0 1832 # previous non-blank line is ';', ':', '{', or '}'.
tomwalters@0 1833 prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
tomwalters@0 1834 if not Search(r'[;:}{]\s*$', prevline):
tomwalters@0 1835 error(filename, linenum, 'whitespace/braces', 4,
tomwalters@0 1836 '{ should almost always be at the end of the previous line')
tomwalters@0 1837
tomwalters@0 1838 # An else clause should be on the same line as the preceding closing brace.
tomwalters@0 1839 if Match(r'\s*else\s*', line):
tomwalters@0 1840 prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
tomwalters@0 1841 if Match(r'\s*}\s*$', prevline):
tomwalters@0 1842 error(filename, linenum, 'whitespace/newline', 4,
tomwalters@0 1843 'An else should appear on the same line as the preceding }')
tomwalters@0 1844
tomwalters@0 1845 # If braces come on one side of an else, they should be on both.
tomwalters@0 1846 # However, we have to worry about "else if" that spans multiple lines!
tomwalters@0 1847 if Search(r'}\s*else[^{]*$', line) or Match(r'[^}]*else\s*{', line):
tomwalters@0 1848 if Search(r'}\s*else if([^{]*)$', line): # could be multi-line if
tomwalters@0 1849 # find the ( after the if
tomwalters@0 1850 pos = line.find('else if')
tomwalters@0 1851 pos = line.find('(', pos)
tomwalters@0 1852 if pos > 0:
tomwalters@0 1853 (endline, _, endpos) = CloseExpression(clean_lines, linenum, pos)
tomwalters@0 1854 if endline[endpos:].find('{') == -1: # must be brace after if
tomwalters@0 1855 error(filename, linenum, 'readability/braces', 5,
tomwalters@0 1856 'If an else has a brace on one side, it should have it on both')
tomwalters@0 1857 else: # common case: else not followed by a multi-line if
tomwalters@0 1858 error(filename, linenum, 'readability/braces', 5,
tomwalters@0 1859 'If an else has a brace on one side, it should have it on both')
tomwalters@0 1860
tomwalters@0 1861 # Likewise, an else should never have the else clause on the same line
tomwalters@0 1862 if Search(r'\belse [^\s{]', line) and not Search(r'\belse if\b', line):
tomwalters@0 1863 error(filename, linenum, 'whitespace/newline', 4,
tomwalters@0 1864 'Else clause should never be on same line as else (use 2 lines)')
tomwalters@0 1865
tomwalters@0 1866 # In the same way, a do/while should never be on one line
tomwalters@0 1867 if Match(r'\s*do [^\s{]', line):
tomwalters@0 1868 error(filename, linenum, 'whitespace/newline', 4,
tomwalters@0 1869 'do/while clauses should not be on a single line')
tomwalters@0 1870
tomwalters@0 1871 # Braces shouldn't be followed by a ; unless they're defining a struct
tomwalters@0 1872 # or initializing an array.
tomwalters@0 1873 # We can't tell in general, but we can for some common cases.
tomwalters@0 1874 prevlinenum = linenum
tomwalters@0 1875 while True:
tomwalters@0 1876 (prevline, prevlinenum) = GetPreviousNonBlankLine(clean_lines, prevlinenum)
tomwalters@0 1877 if Match(r'\s+{.*}\s*;', line) and not prevline.count(';'):
tomwalters@0 1878 line = prevline + line
tomwalters@0 1879 else:
tomwalters@0 1880 break
tomwalters@0 1881 if (Search(r'{.*}\s*;', line) and
tomwalters@0 1882 line.count('{') == line.count('}') and
tomwalters@0 1883 not Search(r'struct|class|enum|\s*=\s*{', line)):
tomwalters@0 1884 error(filename, linenum, 'readability/braces', 4,
tomwalters@0 1885 "You don't need a ; after a }")
tomwalters@0 1886
tomwalters@0 1887
tomwalters@0 1888 def ReplaceableCheck(operator, macro, line):
tomwalters@0 1889 """Determine whether a basic CHECK can be replaced with a more specific one.
tomwalters@0 1890
tomwalters@0 1891 For example suggest using CHECK_EQ instead of CHECK(a == b) and
tomwalters@0 1892 similarly for CHECK_GE, CHECK_GT, CHECK_LE, CHECK_LT, CHECK_NE.
tomwalters@0 1893
tomwalters@0 1894 Args:
tomwalters@0 1895 operator: The C++ operator used in the CHECK.
tomwalters@0 1896 macro: The CHECK or EXPECT macro being called.
tomwalters@0 1897 line: The current source line.
tomwalters@0 1898
tomwalters@0 1899 Returns:
tomwalters@0 1900 True if the CHECK can be replaced with a more specific one.
tomwalters@0 1901 """
tomwalters@0 1902
tomwalters@0 1903 # This matches decimal and hex integers, strings, and chars (in that order).
tomwalters@0 1904 match_constant = r'([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')'
tomwalters@0 1905
tomwalters@0 1906 # Expression to match two sides of the operator with something that
tomwalters@0 1907 # looks like a literal, since CHECK(x == iterator) won't compile.
tomwalters@0 1908 # This means we can't catch all the cases where a more specific
tomwalters@0 1909 # CHECK is possible, but it's less annoying than dealing with
tomwalters@0 1910 # extraneous warnings.
tomwalters@0 1911 match_this = (r'\s*' + macro + r'\((\s*' +
tomwalters@0 1912 match_constant + r'\s*' + operator + r'[^<>].*|'
tomwalters@0 1913 r'.*[^<>]' + operator + r'\s*' + match_constant +
tomwalters@0 1914 r'\s*\))')
tomwalters@0 1915
tomwalters@0 1916 # Don't complain about CHECK(x == NULL) or similar because
tomwalters@0 1917 # CHECK_EQ(x, NULL) won't compile (requires a cast).
tomwalters@0 1918 # Also, don't complain about more complex boolean expressions
tomwalters@0 1919 # involving && or || such as CHECK(a == b || c == d).
tomwalters@0 1920 return Match(match_this, line) and not Search(r'NULL|&&|\|\|', line)
tomwalters@0 1921
tomwalters@0 1922
tomwalters@0 1923 def CheckCheck(filename, clean_lines, linenum, error):
tomwalters@0 1924 """Checks the use of CHECK and EXPECT macros.
tomwalters@0 1925
tomwalters@0 1926 Args:
tomwalters@0 1927 filename: The name of the current file.
tomwalters@0 1928 clean_lines: A CleansedLines instance containing the file.
tomwalters@0 1929 linenum: The number of the line to check.
tomwalters@0 1930 error: The function to call with any errors found.
tomwalters@0 1931 """
tomwalters@0 1932
tomwalters@0 1933 # Decide the set of replacement macros that should be suggested
tomwalters@0 1934 raw_lines = clean_lines.raw_lines
tomwalters@0 1935 current_macro = ''
tomwalters@0 1936 for macro in _CHECK_MACROS:
tomwalters@0 1937 if raw_lines[linenum].find(macro) >= 0:
tomwalters@0 1938 current_macro = macro
tomwalters@0 1939 break
tomwalters@0 1940 if not current_macro:
tomwalters@0 1941 # Don't waste time here if line doesn't contain 'CHECK' or 'EXPECT'
tomwalters@0 1942 return
tomwalters@0 1943
tomwalters@0 1944 line = clean_lines.elided[linenum] # get rid of comments and strings
tomwalters@0 1945
tomwalters@0 1946 # Encourage replacing plain CHECKs with CHECK_EQ/CHECK_NE/etc.
tomwalters@0 1947 for operator in ['==', '!=', '>=', '>', '<=', '<']:
tomwalters@0 1948 if ReplaceableCheck(operator, current_macro, line):
tomwalters@0 1949 error(filename, linenum, 'readability/check', 2,
tomwalters@0 1950 'Consider using %s instead of %s(a %s b)' % (
tomwalters@0 1951 _CHECK_REPLACEMENT[current_macro][operator],
tomwalters@0 1952 current_macro, operator))
tomwalters@0 1953 break
tomwalters@0 1954
tomwalters@0 1955
tomwalters@0 1956 def GetLineWidth(line):
tomwalters@0 1957 """Determines the width of the line in column positions.
tomwalters@0 1958
tomwalters@0 1959 Args:
tomwalters@0 1960 line: A string, which may be a Unicode string.
tomwalters@0 1961
tomwalters@0 1962 Returns:
tomwalters@0 1963 The width of the line in column positions, accounting for Unicode
tomwalters@0 1964 combining characters and wide characters.
tomwalters@0 1965 """
tomwalters@0 1966 if isinstance(line, unicode):
tomwalters@0 1967 width = 0
tomwalters@0 1968 for c in unicodedata.normalize('NFC', line):
tomwalters@0 1969 if unicodedata.east_asian_width(c) in ('W', 'F'):
tomwalters@0 1970 width += 2
tomwalters@0 1971 elif not unicodedata.combining(c):
tomwalters@0 1972 width += 1
tomwalters@0 1973 return width
tomwalters@0 1974 else:
tomwalters@0 1975 return len(line)
tomwalters@0 1976
tomwalters@0 1977
tomwalters@0 1978 def CheckStyle(filename, clean_lines, linenum, file_extension, error):
tomwalters@0 1979 """Checks rules from the 'C++ style rules' section of cppguide.html.
tomwalters@0 1980
tomwalters@0 1981 Most of these rules are hard to test (naming, comment style), but we
tomwalters@0 1982 do what we can. In particular we check for 2-space indents, line lengths,
tomwalters@0 1983 tab usage, spaces inside code, etc.
tomwalters@0 1984
tomwalters@0 1985 Args:
tomwalters@0 1986 filename: The name of the current file.
tomwalters@0 1987 clean_lines: A CleansedLines instance containing the file.
tomwalters@0 1988 linenum: The number of the line to check.
tomwalters@0 1989 file_extension: The extension (without the dot) of the filename.
tomwalters@0 1990 error: The function to call with any errors found.
tomwalters@0 1991 """
tomwalters@0 1992
tomwalters@0 1993 raw_lines = clean_lines.raw_lines
tomwalters@0 1994 line = raw_lines[linenum]
tomwalters@0 1995
tomwalters@0 1996 if line.find('\t') != -1:
tomwalters@0 1997 error(filename, linenum, 'whitespace/tab', 1,
tomwalters@0 1998 'Tab found; better to use spaces')
tomwalters@0 1999
tomwalters@0 2000 # One or three blank spaces at the beginning of the line is weird; it's
tomwalters@0 2001 # hard to reconcile that with 2-space indents.
tomwalters@0 2002 # NOTE: here are the conditions rob pike used for his tests. Mine aren't
tomwalters@0 2003 # as sophisticated, but it may be worth becoming so: RLENGTH==initial_spaces
tomwalters@0 2004 # if(RLENGTH > 20) complain = 0;
tomwalters@0 2005 # if(match($0, " +(error|private|public|protected):")) complain = 0;
tomwalters@0 2006 # if(match(prev, "&& *$")) complain = 0;
tomwalters@0 2007 # if(match(prev, "\\|\\| *$")) complain = 0;
tomwalters@0 2008 # if(match(prev, "[\",=><] *$")) complain = 0;
tomwalters@0 2009 # if(match($0, " <<")) complain = 0;
tomwalters@0 2010 # if(match(prev, " +for \\(")) complain = 0;
tomwalters@0 2011 # if(prevodd && match(prevprev, " +for \\(")) complain = 0;
tomwalters@0 2012 initial_spaces = 0
tomwalters@0 2013 cleansed_line = clean_lines.elided[linenum]
tomwalters@0 2014 while initial_spaces < len(line) and line[initial_spaces] == ' ':
tomwalters@0 2015 initial_spaces += 1
tomwalters@0 2016 if line and line[-1].isspace():
tomwalters@0 2017 error(filename, linenum, 'whitespace/end_of_line', 4,
tomwalters@0 2018 'Line ends in whitespace. Consider deleting these extra spaces.')
tomwalters@0 2019 # There are certain situations we allow one space, notably for labels
tomwalters@0 2020 elif ((initial_spaces == 1 or initial_spaces == 3) and
tomwalters@0 2021 not Match(r'\s*\w+\s*:\s*$', cleansed_line)):
tomwalters@0 2022 error(filename, linenum, 'whitespace/indent', 3,
tomwalters@0 2023 'Weird number of spaces at line-start. '
tomwalters@0 2024 'Are you using a 2-space indent?')
tomwalters@0 2025 # Labels should always be indented at least one space.
tomwalters@0 2026 elif not initial_spaces and line[:2] != '//' and Search(r'[^:]:\s*$',
tomwalters@0 2027 line):
tomwalters@0 2028 error(filename, linenum, 'whitespace/labels', 4,
tomwalters@0 2029 'Labels should always be indented at least one space. '
tomwalters@0 2030 'If this is a member-initializer list in a constructor, '
tomwalters@0 2031 'the colon should be on the line after the definition header.')
tomwalters@0 2032
tomwalters@0 2033 # Check if the line is a header guard.
tomwalters@0 2034 is_header_guard = False
tomwalters@0 2035 if file_extension == 'h':
tomwalters@0 2036 cppvar = GetHeaderGuardCPPVariable(filename)
tomwalters@0 2037 if (line.startswith('#ifndef %s' % cppvar) or
tomwalters@0 2038 line.startswith('#define %s' % cppvar) or
tomwalters@0 2039 line.startswith('#endif // %s' % cppvar)):
tomwalters@0 2040 is_header_guard = True
tomwalters@0 2041 # #include lines and header guards can be long, since there's no clean way to
tomwalters@0 2042 # split them.
tomwalters@0 2043 #
tomwalters@0 2044 # URLs can be long too. It's possible to split these, but it makes them
tomwalters@0 2045 # harder to cut&paste.
tomwalters@0 2046 if (not line.startswith('#include') and not is_header_guard and
tomwalters@0 2047 not Match(r'^\s*//.*http(s?)://\S*$', line)):
tomwalters@0 2048 line_width = GetLineWidth(line)
tomwalters@0 2049 if line_width > 100:
tomwalters@0 2050 error(filename, linenum, 'whitespace/line_length', 4,
tomwalters@0 2051 'Lines should very rarely be longer than 100 characters')
tomwalters@0 2052 elif line_width > 80:
tomwalters@0 2053 error(filename, linenum, 'whitespace/line_length', 2,
tomwalters@0 2054 'Lines should be <= 80 characters long')
tomwalters@0 2055
tomwalters@0 2056 if (cleansed_line.count(';') > 1 and
tomwalters@0 2057 # for loops are allowed two ;'s (and may run over two lines).
tomwalters@0 2058 cleansed_line.find('for') == -1 and
tomwalters@0 2059 (GetPreviousNonBlankLine(clean_lines, linenum)[0].find('for') == -1 or
tomwalters@0 2060 GetPreviousNonBlankLine(clean_lines, linenum)[0].find(';') != -1) and
tomwalters@0 2061 # It's ok to have many commands in a switch case that fits in 1 line
tomwalters@0 2062 not ((cleansed_line.find('case ') != -1 or
tomwalters@0 2063 cleansed_line.find('default:') != -1) and
tomwalters@0 2064 cleansed_line.find('break;') != -1)):
tomwalters@0 2065 error(filename, linenum, 'whitespace/newline', 4,
tomwalters@0 2066 'More than one command on the same line')
tomwalters@0 2067
tomwalters@0 2068 # Some more style checks
tomwalters@0 2069 CheckBraces(filename, clean_lines, linenum, error)
tomwalters@0 2070 CheckSpacing(filename, clean_lines, linenum, error)
tomwalters@0 2071 CheckCheck(filename, clean_lines, linenum, error)
tomwalters@0 2072
tomwalters@0 2073
tomwalters@0 2074 _RE_PATTERN_INCLUDE_NEW_STYLE = re.compile(r'#include +"[^/]+\.h"')
tomwalters@0 2075 _RE_PATTERN_INCLUDE = re.compile(r'^\s*#\s*include\s*([<"])([^>"]*)[>"].*$')
tomwalters@0 2076 # Matches the first component of a filename delimited by -s and _s. That is:
tomwalters@0 2077 # _RE_FIRST_COMPONENT.match('foo').group(0) == 'foo'
tomwalters@0 2078 # _RE_FIRST_COMPONENT.match('foo.cc').group(0) == 'foo'
tomwalters@0 2079 # _RE_FIRST_COMPONENT.match('foo-bar_baz.cc').group(0) == 'foo'
tomwalters@0 2080 # _RE_FIRST_COMPONENT.match('foo_bar-baz.cc').group(0) == 'foo'
tomwalters@0 2081 _RE_FIRST_COMPONENT = re.compile(r'^[^-_.]+')
tomwalters@0 2082
tomwalters@0 2083
tomwalters@0 2084 def _DropCommonSuffixes(filename):
tomwalters@0 2085 """Drops common suffixes like _test.cc or -inl.h from filename.
tomwalters@0 2086
tomwalters@0 2087 For example:
tomwalters@0 2088 >>> _DropCommonSuffixes('foo/foo-inl.h')
tomwalters@0 2089 'foo/foo'
tomwalters@0 2090 >>> _DropCommonSuffixes('foo/bar/foo.cc')
tomwalters@0 2091 'foo/bar/foo'
tomwalters@0 2092 >>> _DropCommonSuffixes('foo/foo_internal.h')
tomwalters@0 2093 'foo/foo'
tomwalters@0 2094 >>> _DropCommonSuffixes('foo/foo_unusualinternal.h')
tomwalters@0 2095 'foo/foo_unusualinternal'
tomwalters@0 2096
tomwalters@0 2097 Args:
tomwalters@0 2098 filename: The input filename.
tomwalters@0 2099
tomwalters@0 2100 Returns:
tomwalters@0 2101 The filename with the common suffix removed.
tomwalters@0 2102 """
tomwalters@0 2103 for suffix in ('test.cc', 'regtest.cc', 'unittest.cc',
tomwalters@0 2104 'inl.h', 'impl.h', 'internal.h'):
tomwalters@0 2105 if (filename.endswith(suffix) and len(filename) > len(suffix) and
tomwalters@0 2106 filename[-len(suffix) - 1] in ('-', '_')):
tomwalters@0 2107 return filename[:-len(suffix) - 1]
tomwalters@0 2108 return os.path.splitext(filename)[0]
tomwalters@0 2109
tomwalters@0 2110
tomwalters@0 2111 def _IsTestFilename(filename):
tomwalters@0 2112 """Determines if the given filename has a suffix that identifies it as a test.
tomwalters@0 2113
tomwalters@0 2114 Args:
tomwalters@0 2115 filename: The input filename.
tomwalters@0 2116
tomwalters@0 2117 Returns:
tomwalters@0 2118 True if 'filename' looks like a test, False otherwise.
tomwalters@0 2119 """
tomwalters@0 2120 if (filename.endswith('_test.cc') or
tomwalters@0 2121 filename.endswith('_unittest.cc') or
tomwalters@0 2122 filename.endswith('_regtest.cc')):
tomwalters@0 2123 return True
tomwalters@0 2124 else:
tomwalters@0 2125 return False
tomwalters@0 2126
tomwalters@0 2127
tomwalters@0 2128 def _ClassifyInclude(fileinfo, include, is_system):
tomwalters@0 2129 """Figures out what kind of header 'include' is.
tomwalters@0 2130
tomwalters@0 2131 Args:
tomwalters@0 2132 fileinfo: The current file cpplint is running over. A FileInfo instance.
tomwalters@0 2133 include: The path to a #included file.
tomwalters@0 2134 is_system: True if the #include used <> rather than "".
tomwalters@0 2135
tomwalters@0 2136 Returns:
tomwalters@0 2137 One of the _XXX_HEADER constants.
tomwalters@0 2138
tomwalters@0 2139 For example:
tomwalters@0 2140 >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'stdio.h', True)
tomwalters@0 2141 _C_SYS_HEADER
tomwalters@0 2142 >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'string', True)
tomwalters@0 2143 _CPP_SYS_HEADER
tomwalters@0 2144 >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', False)
tomwalters@0 2145 _LIKELY_MY_HEADER
tomwalters@0 2146 >>> _ClassifyInclude(FileInfo('foo/foo_unknown_extension.cc'),
tomwalters@0 2147 ... 'bar/foo_other_ext.h', False)
tomwalters@0 2148 _POSSIBLE_MY_HEADER
tomwalters@0 2149 >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/bar.h', False)
tomwalters@0 2150 _OTHER_HEADER
tomwalters@0 2151 """
tomwalters@0 2152 # This is a list of all standard c++ header files, except
tomwalters@0 2153 # those already checked for above.
tomwalters@0 2154 is_stl_h = include in _STL_HEADERS
tomwalters@0 2155 is_cpp_h = is_stl_h or include in _CPP_HEADERS
tomwalters@0 2156
tomwalters@0 2157 if is_system:
tomwalters@0 2158 if is_cpp_h:
tomwalters@0 2159 return _CPP_SYS_HEADER
tomwalters@0 2160 else:
tomwalters@0 2161 return _C_SYS_HEADER
tomwalters@0 2162
tomwalters@0 2163 # If the target file and the include we're checking share a
tomwalters@0 2164 # basename when we drop common extensions, and the include
tomwalters@0 2165 # lives in . , then it's likely to be owned by the target file.
tomwalters@0 2166 target_dir, target_base = (
tomwalters@0 2167 os.path.split(_DropCommonSuffixes(fileinfo.RepositoryName())))
tomwalters@0 2168 include_dir, include_base = os.path.split(_DropCommonSuffixes(include))
tomwalters@0 2169 if target_base == include_base and (
tomwalters@0 2170 include_dir == target_dir or
tomwalters@0 2171 include_dir == os.path.normpath(target_dir + '/../public')):
tomwalters@0 2172 return _LIKELY_MY_HEADER
tomwalters@0 2173
tomwalters@0 2174 # If the target and include share some initial basename
tomwalters@0 2175 # component, it's possible the target is implementing the
tomwalters@0 2176 # include, so it's allowed to be first, but we'll never
tomwalters@0 2177 # complain if it's not there.
tomwalters@0 2178 target_first_component = _RE_FIRST_COMPONENT.match(target_base)
tomwalters@0 2179 include_first_component = _RE_FIRST_COMPONENT.match(include_base)
tomwalters@0 2180 if (target_first_component and include_first_component and
tomwalters@0 2181 target_first_component.group(0) ==
tomwalters@0 2182 include_first_component.group(0)):
tomwalters@0 2183 return _POSSIBLE_MY_HEADER
tomwalters@0 2184
tomwalters@0 2185 return _OTHER_HEADER
tomwalters@0 2186
tomwalters@0 2187
tomwalters@0 2188
tomwalters@0 2189 def CheckIncludeLine(filename, clean_lines, linenum, include_state, error):
tomwalters@0 2190 """Check rules that are applicable to #include lines.
tomwalters@0 2191
tomwalters@0 2192 Strings on #include lines are NOT removed from elided line, to make
tomwalters@0 2193 certain tasks easier. However, to prevent false positives, checks
tomwalters@0 2194 applicable to #include lines in CheckLanguage must be put here.
tomwalters@0 2195
tomwalters@0 2196 Args:
tomwalters@0 2197 filename: The name of the current file.
tomwalters@0 2198 clean_lines: A CleansedLines instance containing the file.
tomwalters@0 2199 linenum: The number of the line to check.
tomwalters@0 2200 include_state: An _IncludeState instance in which the headers are inserted.
tomwalters@0 2201 error: The function to call with any errors found.
tomwalters@0 2202 """
tomwalters@0 2203 fileinfo = FileInfo(filename)
tomwalters@0 2204
tomwalters@0 2205 line = clean_lines.lines[linenum]
tomwalters@0 2206
tomwalters@0 2207 # "include" should use the new style "foo/bar.h" instead of just "bar.h"
tomwalters@0 2208 if _RE_PATTERN_INCLUDE_NEW_STYLE.search(line):
tomwalters@0 2209 error(filename, linenum, 'build/include', 4,
tomwalters@0 2210 'Include the directory when naming .h files')
tomwalters@0 2211
tomwalters@0 2212 # we shouldn't include a file more than once. actually, there are a
tomwalters@0 2213 # handful of instances where doing so is okay, but in general it's
tomwalters@0 2214 # not.
tomwalters@0 2215 match = _RE_PATTERN_INCLUDE.search(line)
tomwalters@0 2216 if match:
tomwalters@0 2217 include = match.group(2)
tomwalters@0 2218 is_system = (match.group(1) == '<')
tomwalters@0 2219 if include in include_state:
tomwalters@0 2220 error(filename, linenum, 'build/include', 4,
tomwalters@0 2221 '"%s" already included at %s:%s' %
tomwalters@0 2222 (include, filename, include_state[include]))
tomwalters@0 2223 else:
tomwalters@0 2224 include_state[include] = linenum
tomwalters@0 2225
tomwalters@0 2226 # We want to ensure that headers appear in the right order:
tomwalters@0 2227 # 1) for foo.cc, foo.h (preferred location)
tomwalters@0 2228 # 2) c system files
tomwalters@0 2229 # 3) cpp system files
tomwalters@0 2230 # 4) for foo.cc, foo.h (deprecated location)
tomwalters@0 2231 # 5) other google headers
tomwalters@0 2232 #
tomwalters@0 2233 # We classify each include statement as one of those 5 types
tomwalters@0 2234 # using a number of techniques. The include_state object keeps
tomwalters@0 2235 # track of the highest type seen, and complains if we see a
tomwalters@0 2236 # lower type after that.
tomwalters@0 2237 error_message = include_state.CheckNextIncludeOrder(
tomwalters@0 2238 _ClassifyInclude(fileinfo, include, is_system))
tomwalters@0 2239 if error_message:
tomwalters@0 2240 error(filename, linenum, 'build/include_order', 4,
tomwalters@0 2241 '%s. Should be: %s.h, c system, c++ system, other.' %
tomwalters@0 2242 (error_message, fileinfo.BaseName()))
tomwalters@0 2243 if not include_state.IsInAlphabeticalOrder(include):
tomwalters@0 2244 error(filename, linenum, 'build/include_alpha', 4,
tomwalters@0 2245 'Include "%s" not in alphabetical order' % include)
tomwalters@0 2246
tomwalters@0 2247 # Look for any of the stream classes that are part of standard C++.
tomwalters@0 2248 match = _RE_PATTERN_INCLUDE.match(line)
tomwalters@0 2249 if match:
tomwalters@0 2250 include = match.group(2)
tomwalters@0 2251 if Match(r'(f|ind|io|i|o|parse|pf|stdio|str|)?stream$', include):
tomwalters@0 2252 # Many unit tests use cout, so we exempt them.
tomwalters@0 2253 if not _IsTestFilename(filename):
tomwalters@0 2254 error(filename, linenum, 'readability/streams', 3,
tomwalters@0 2255 'Streams are highly discouraged.')
tomwalters@0 2256
tomwalters@0 2257 def CheckLanguage(filename, clean_lines, linenum, file_extension, include_state,
tomwalters@0 2258 error):
tomwalters@0 2259 """Checks rules from the 'C++ language rules' section of cppguide.html.
tomwalters@0 2260
tomwalters@0 2261 Some of these rules are hard to test (function overloading, using
tomwalters@0 2262 uint32 inappropriately), but we do the best we can.
tomwalters@0 2263
tomwalters@0 2264 Args:
tomwalters@0 2265 filename: The name of the current file.
tomwalters@0 2266 clean_lines: A CleansedLines instance containing the file.
tomwalters@0 2267 linenum: The number of the line to check.
tomwalters@0 2268 file_extension: The extension (without the dot) of the filename.
tomwalters@0 2269 include_state: An _IncludeState instance in which the headers are inserted.
tomwalters@0 2270 error: The function to call with any errors found.
tomwalters@0 2271 """
tomwalters@0 2272 # If the line is empty or consists of entirely a comment, no need to
tomwalters@0 2273 # check it.
tomwalters@0 2274 line = clean_lines.elided[linenum]
tomwalters@0 2275 if not line:
tomwalters@0 2276 return
tomwalters@0 2277
tomwalters@0 2278 match = _RE_PATTERN_INCLUDE.search(line)
tomwalters@0 2279 if match:
tomwalters@0 2280 CheckIncludeLine(filename, clean_lines, linenum, include_state, error)
tomwalters@0 2281 return
tomwalters@0 2282
tomwalters@0 2283 # Create an extended_line, which is the concatenation of the current and
tomwalters@0 2284 # next lines, for more effective checking of code that may span more than one
tomwalters@0 2285 # line.
tomwalters@0 2286 if linenum + 1 < clean_lines.NumLines():
tomwalters@0 2287 extended_line = line + clean_lines.elided[linenum + 1]
tomwalters@0 2288 else:
tomwalters@0 2289 extended_line = line
tomwalters@0 2290
tomwalters@0 2291 # Make Windows paths like Unix.
tomwalters@0 2292 fullname = os.path.abspath(filename).replace('\\', '/')
tomwalters@0 2293
tomwalters@0 2294 # TODO(unknown): figure out if they're using default arguments in fn proto.
tomwalters@0 2295
tomwalters@0 2296 # Check for non-const references in functions. This is tricky because &
tomwalters@0 2297 # is also used to take the address of something. We allow <> for templates,
tomwalters@0 2298 # (ignoring whatever is between the braces) and : for classes.
tomwalters@0 2299 # These are complicated re's. They try to capture the following:
tomwalters@0 2300 # paren (for fn-prototype start), typename, &, varname. For the const
tomwalters@0 2301 # version, we're willing for const to be before typename or after
tomwalters@0 2302 # Don't check the implemention on same line.
tomwalters@0 2303 fnline = line.split('{', 1)[0]
tomwalters@0 2304 if (len(re.findall(r'\([^()]*\b(?:[\w:]|<[^()]*>)+(\s?&|&\s?)\w+', fnline)) >
tomwalters@0 2305 len(re.findall(r'\([^()]*\bconst\s+(?:typename\s+)?(?:struct\s+)?'
tomwalters@0 2306 r'(?:[\w:]|<[^()]*>)+(\s?&|&\s?)\w+', fnline)) +
tomwalters@0 2307 len(re.findall(r'\([^()]*\b(?:[\w:]|<[^()]*>)+\s+const(\s?&|&\s?)[\w]+',
tomwalters@0 2308 fnline))):
tomwalters@0 2309
tomwalters@0 2310 # We allow non-const references in a few standard places, like functions
tomwalters@0 2311 # called "swap()" or iostream operators like "<<" or ">>".
tomwalters@0 2312 if not Search(
tomwalters@0 2313 r'(swap|Swap|operator[<>][<>])\s*\(\s*(?:[\w:]|<.*>)+\s*&',
tomwalters@0 2314 fnline):
tomwalters@0 2315 error(filename, linenum, 'runtime/references', 2,
tomwalters@0 2316 'Is this a non-const reference? '
tomwalters@0 2317 'If so, make const or use a pointer.')
tomwalters@0 2318
tomwalters@0 2319 # Check to see if they're using an conversion function cast.
tomwalters@0 2320 # I just try to capture the most common basic types, though there are more.
tomwalters@0 2321 # Parameterless conversion functions, such as bool(), are allowed as they are
tomwalters@0 2322 # probably a member operator declaration or default constructor.
tomwalters@0 2323 match = Search(
tomwalters@0 2324 r'(\bnew\s+)?\b' # Grab 'new' operator, if it's there
tomwalters@0 2325 r'(int|float|double|bool|char|int32|uint32|int64|uint64)\([^)]', line)
tomwalters@0 2326 if match:
tomwalters@0 2327 # gMock methods are defined using some variant of MOCK_METHODx(name, type)
tomwalters@0 2328 # where type may be float(), int(string), etc. Without context they are
tomwalters@0 2329 # virtually indistinguishable from int(x) casts.
tomwalters@0 2330 if (match.group(1) is None and # If new operator, then this isn't a cast
tomwalters@0 2331 not Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line)):
tomwalters@0 2332 error(filename, linenum, 'readability/casting', 4,
tomwalters@0 2333 'Using deprecated casting style. '
tomwalters@0 2334 'Use static_cast<%s>(...) instead' %
tomwalters@0 2335 match.group(2))
tomwalters@0 2336
tomwalters@0 2337 CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum],
tomwalters@0 2338 'static_cast',
tomwalters@0 2339 r'\((int|float|double|bool|char|u?int(16|32|64))\)',
tomwalters@0 2340 error)
tomwalters@0 2341 # This doesn't catch all cases. Consider (const char * const)"hello".
tomwalters@0 2342 CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum],
tomwalters@0 2343 'reinterpret_cast', r'\((\w+\s?\*+\s?)\)', error)
tomwalters@0 2344
tomwalters@0 2345 # In addition, we look for people taking the address of a cast. This
tomwalters@0 2346 # is dangerous -- casts can assign to temporaries, so the pointer doesn't
tomwalters@0 2347 # point where you think.
tomwalters@0 2348 if Search(
tomwalters@0 2349 r'(&\([^)]+\)[\w(])|(&(static|dynamic|reinterpret)_cast\b)', line):
tomwalters@0 2350 error(filename, linenum, 'runtime/casting', 4,
tomwalters@0 2351 ('Are you taking an address of a cast? '
tomwalters@0 2352 'This is dangerous: could be a temp var. '
tomwalters@0 2353 'Take the address before doing the cast, rather than after'))
tomwalters@0 2354
tomwalters@0 2355 # Check for people declaring static/global STL strings at the top level.
tomwalters@0 2356 # This is dangerous because the C++ language does not guarantee that
tomwalters@0 2357 # globals with constructors are initialized before the first access.
tomwalters@0 2358 match = Match(
tomwalters@0 2359 r'((?:|static +)(?:|const +))string +([a-zA-Z0-9_:]+)\b(.*)',
tomwalters@0 2360 line)
tomwalters@0 2361 # Make sure it's not a function.
tomwalters@0 2362 # Function template specialization looks like: "string foo<Type>(...".
tomwalters@0 2363 # Class template definitions look like: "string Foo<Type>::Method(...".
tomwalters@0 2364 if match and not Match(r'\s*(<.*>)?(::[a-zA-Z0-9_]+)?\s*\(([^"]|$)',
tomwalters@0 2365 match.group(3)):
tomwalters@0 2366 error(filename, linenum, 'runtime/string', 4,
tomwalters@0 2367 'For a static/global string constant, use a C style string instead: '
tomwalters@0 2368 '"%schar %s[]".' %
tomwalters@0 2369 (match.group(1), match.group(2)))
tomwalters@0 2370
tomwalters@0 2371 # Check that we're not using RTTI outside of testing code.
tomwalters@0 2372 if Search(r'\bdynamic_cast<', line) and not _IsTestFilename(filename):
tomwalters@0 2373 error(filename, linenum, 'runtime/rtti', 5,
tomwalters@0 2374 'Do not use dynamic_cast<>. If you need to cast within a class '
tomwalters@0 2375 "hierarchy, use static_cast<> to upcast. Google doesn't support "
tomwalters@0 2376 'RTTI.')
tomwalters@0 2377
tomwalters@0 2378 if Search(r'\b([A-Za-z0-9_]*_)\(\1\)', line):
tomwalters@0 2379 error(filename, linenum, 'runtime/init', 4,
tomwalters@0 2380 'You seem to be initializing a member variable with itself.')
tomwalters@0 2381
tomwalters@0 2382 if file_extension == 'h':
tomwalters@0 2383 # TODO(unknown): check that 1-arg constructors are explicit.
tomwalters@0 2384 # How to tell it's a constructor?
tomwalters@0 2385 # (handled in CheckForNonStandardConstructs for now)
tomwalters@0 2386 # TODO(unknown): check that classes have DISALLOW_EVIL_CONSTRUCTORS
tomwalters@0 2387 # (level 1 error)
tomwalters@0 2388 pass
tomwalters@0 2389
tomwalters@0 2390 # Check if people are using the verboten C basic types. The only exception
tomwalters@0 2391 # we regularly allow is "unsigned short port" for port.
tomwalters@0 2392 if Search(r'\bshort port\b', line):
tomwalters@0 2393 if not Search(r'\bunsigned short port\b', line):
tomwalters@0 2394 error(filename, linenum, 'runtime/int', 4,
tomwalters@0 2395 'Use "unsigned short" for ports, not "short"')
tomwalters@0 2396 else:
tomwalters@0 2397 match = Search(r'\b(short|long(?! +double)|long long)\b', line)
tomwalters@0 2398 if match:
tomwalters@0 2399 error(filename, linenum, 'runtime/int', 4,
tomwalters@0 2400 'Use int16/int64/etc, rather than the C type %s' % match.group(1))
tomwalters@0 2401
tomwalters@0 2402 # When snprintf is used, the second argument shouldn't be a literal.
tomwalters@0 2403 match = Search(r'snprintf\s*\(([^,]*),\s*([0-9]*)\s*,', line)
tomwalters@0 2404 if match:
tomwalters@0 2405 error(filename, linenum, 'runtime/printf', 3,
tomwalters@0 2406 'If you can, use sizeof(%s) instead of %s as the 2nd arg '
tomwalters@0 2407 'to snprintf.' % (match.group(1), match.group(2)))
tomwalters@0 2408
tomwalters@0 2409 # Check if some verboten C functions are being used.
tomwalters@0 2410 if Search(r'\bsprintf\b', line):
tomwalters@0 2411 error(filename, linenum, 'runtime/printf', 5,
tomwalters@0 2412 'Never use sprintf. Use snprintf instead.')
tomwalters@0 2413 match = Search(r'\b(strcpy|strcat)\b', line)
tomwalters@0 2414 if match:
tomwalters@0 2415 error(filename, linenum, 'runtime/printf', 4,
tomwalters@0 2416 'Almost always, snprintf is better than %s' % match.group(1))
tomwalters@0 2417
tomwalters@0 2418 if Search(r'\bsscanf\b', line):
tomwalters@0 2419 error(filename, linenum, 'runtime/printf', 1,
tomwalters@0 2420 'sscanf can be ok, but is slow and can overflow buffers.')
tomwalters@0 2421
tomwalters@0 2422 # Check if some verboten operator overloading is going on
tomwalters@0 2423 # TODO(unknown): catch out-of-line unary operator&:
tomwalters@0 2424 # class X {};
tomwalters@0 2425 # int operator&(const X& x) { return 42; } // unary operator&
tomwalters@0 2426 # The trick is it's hard to tell apart from binary operator&:
tomwalters@0 2427 # class Y { int operator&(const Y& x) { return 23; } }; // binary operator&
tomwalters@0 2428 if Search(r'\boperator\s*&\s*\(\s*\)', line):
tomwalters@0 2429 error(filename, linenum, 'runtime/operator', 4,
tomwalters@0 2430 'Unary operator& is dangerous. Do not use it.')
tomwalters@0 2431
tomwalters@0 2432 # Check for suspicious usage of "if" like
tomwalters@0 2433 # } if (a == b) {
tomwalters@0 2434 if Search(r'\}\s*if\s*\(', line):
tomwalters@0 2435 error(filename, linenum, 'readability/braces', 4,
tomwalters@0 2436 'Did you mean "else if"? If not, start a new line for "if".')
tomwalters@0 2437
tomwalters@0 2438 # Check for potential format string bugs like printf(foo).
tomwalters@0 2439 # We constrain the pattern not to pick things like DocidForPrintf(foo).
tomwalters@0 2440 # Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str())
tomwalters@0 2441 match = re.search(r'\b((?:string)?printf)\s*\(([\w.\->()]+)\)', line, re.I)
tomwalters@0 2442 if match:
tomwalters@0 2443 error(filename, linenum, 'runtime/printf', 4,
tomwalters@0 2444 'Potential format string bug. Do %s("%%s", %s) instead.'
tomwalters@0 2445 % (match.group(1), match.group(2)))
tomwalters@0 2446
tomwalters@0 2447 # Check for potential memset bugs like memset(buf, sizeof(buf), 0).
tomwalters@0 2448 match = Search(r'memset\s*\(([^,]*),\s*([^,]*),\s*0\s*\)', line)
tomwalters@0 2449 if match and not Match(r"^''|-?[0-9]+|0x[0-9A-Fa-f]$", match.group(2)):
tomwalters@0 2450 error(filename, linenum, 'runtime/memset', 4,
tomwalters@0 2451 'Did you mean "memset(%s, 0, %s)"?'
tomwalters@0 2452 % (match.group(1), match.group(2)))
tomwalters@0 2453
tomwalters@0 2454 if Search(r'\busing namespace\b', line):
tomwalters@0 2455 error(filename, linenum, 'build/namespaces', 5,
tomwalters@0 2456 'Do not use namespace using-directives. '
tomwalters@0 2457 'Use using-declarations instead.')
tomwalters@0 2458
tomwalters@0 2459 # Detect variable-length arrays.
tomwalters@0 2460 match = Match(r'\s*(.+::)?(\w+) [a-z]\w*\[(.+)];', line)
tomwalters@0 2461 if (match and match.group(2) != 'return' and match.group(2) != 'delete' and
tomwalters@0 2462 match.group(3).find(']') == -1):
tomwalters@0 2463 # Split the size using space and arithmetic operators as delimiters.
tomwalters@0 2464 # If any of the resulting tokens are not compile time constants then
tomwalters@0 2465 # report the error.
tomwalters@0 2466 tokens = re.split(r'\s|\+|\-|\*|\/|<<|>>]', match.group(3))
tomwalters@0 2467 is_const = True
tomwalters@0 2468 skip_next = False
tomwalters@0 2469 for tok in tokens:
tomwalters@0 2470 if skip_next:
tomwalters@0 2471 skip_next = False
tomwalters@0 2472 continue
tomwalters@0 2473
tomwalters@0 2474 if Search(r'sizeof\(.+\)', tok): continue
tomwalters@0 2475 if Search(r'arraysize\(\w+\)', tok): continue
tomwalters@0 2476
tomwalters@0 2477 tok = tok.lstrip('(')
tomwalters@0 2478 tok = tok.rstrip(')')
tomwalters@0 2479 if not tok: continue
tomwalters@0 2480 if Match(r'\d+', tok): continue
tomwalters@0 2481 if Match(r'0[xX][0-9a-fA-F]+', tok): continue
tomwalters@0 2482 if Match(r'k[A-Z0-9]\w*', tok): continue
tomwalters@0 2483 if Match(r'(.+::)?k[A-Z0-9]\w*', tok): continue
tomwalters@0 2484 if Match(r'(.+::)?[A-Z][A-Z0-9_]*', tok): continue
tomwalters@0 2485 # A catch all for tricky sizeof cases, including 'sizeof expression',
tomwalters@0 2486 # 'sizeof(*type)', 'sizeof(const type)', 'sizeof(struct StructName)'
tomwalters@0 2487 # requires skipping the next token becasue we split on ' ' and '*'.
tomwalters@0 2488 if tok.startswith('sizeof'):
tomwalters@0 2489 skip_next = True
tomwalters@0 2490 continue
tomwalters@0 2491 is_const = False
tomwalters@0 2492 break
tomwalters@0 2493 if not is_const:
tomwalters@0 2494 error(filename, linenum, 'runtime/arrays', 1,
tomwalters@0 2495 'Do not use variable-length arrays. Use an appropriately named '
tomwalters@0 2496 "('k' followed by CamelCase) compile-time constant for the size.")
tomwalters@0 2497
tomwalters@0 2498 # If DISALLOW_EVIL_CONSTRUCTORS, DISALLOW_COPY_AND_ASSIGN, or
tomwalters@0 2499 # DISALLOW_IMPLICIT_CONSTRUCTORS is present, then it should be the last thing
tomwalters@0 2500 # in the class declaration.
tomwalters@0 2501 match = Match(
tomwalters@0 2502 (r'\s*'
tomwalters@0 2503 r'(DISALLOW_(EVIL_CONSTRUCTORS|COPY_AND_ASSIGN|IMPLICIT_CONSTRUCTORS))'
tomwalters@0 2504 r'\(.*\);$'),
tomwalters@0 2505 line)
tomwalters@0 2506 if match and linenum + 1 < clean_lines.NumLines():
tomwalters@0 2507 next_line = clean_lines.elided[linenum + 1]
tomwalters@0 2508 if not Search(r'^\s*};', next_line):
tomwalters@0 2509 error(filename, linenum, 'readability/constructors', 3,
tomwalters@0 2510 match.group(1) + ' should be the last thing in the class')
tomwalters@0 2511
tomwalters@0 2512 # Check for use of unnamed namespaces in header files. Registration
tomwalters@0 2513 # macros are typically OK, so we allow use of "namespace {" on lines
tomwalters@0 2514 # that end with backslashes.
tomwalters@0 2515 if (file_extension == 'h'
tomwalters@0 2516 and Search(r'\bnamespace\s*{', line)
tomwalters@0 2517 and line[-1] != '\\'):
tomwalters@0 2518 error(filename, linenum, 'build/namespaces', 4,
tomwalters@0 2519 'Do not use unnamed namespaces in header files. See '
tomwalters@0 2520 'http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces'
tomwalters@0 2521 ' for more information.')
tomwalters@0 2522
tomwalters@0 2523
tomwalters@0 2524 def CheckCStyleCast(filename, linenum, line, raw_line, cast_type, pattern,
tomwalters@0 2525 error):
tomwalters@0 2526 """Checks for a C-style cast by looking for the pattern.
tomwalters@0 2527
tomwalters@0 2528 This also handles sizeof(type) warnings, due to similarity of content.
tomwalters@0 2529
tomwalters@0 2530 Args:
tomwalters@0 2531 filename: The name of the current file.
tomwalters@0 2532 linenum: The number of the line to check.
tomwalters@0 2533 line: The line of code to check.
tomwalters@0 2534 raw_line: The raw line of code to check, with comments.
tomwalters@0 2535 cast_type: The string for the C++ cast to recommend. This is either
tomwalters@0 2536 reinterpret_cast or static_cast, depending.
tomwalters@0 2537 pattern: The regular expression used to find C-style casts.
tomwalters@0 2538 error: The function to call with any errors found.
tomwalters@0 2539 """
tomwalters@0 2540 match = Search(pattern, line)
tomwalters@0 2541 if not match:
tomwalters@0 2542 return
tomwalters@0 2543
tomwalters@0 2544 # e.g., sizeof(int)
tomwalters@0 2545 sizeof_match = Match(r'.*sizeof\s*$', line[0:match.start(1) - 1])
tomwalters@0 2546 if sizeof_match:
tomwalters@0 2547 error(filename, linenum, 'runtime/sizeof', 1,
tomwalters@0 2548 'Using sizeof(type). Use sizeof(varname) instead if possible')
tomwalters@0 2549 return
tomwalters@0 2550
tomwalters@0 2551 remainder = line[match.end(0):]
tomwalters@0 2552
tomwalters@0 2553 # The close paren is for function pointers as arguments to a function.
tomwalters@0 2554 # eg, void foo(void (*bar)(int));
tomwalters@0 2555 # The semicolon check is a more basic function check; also possibly a
tomwalters@0 2556 # function pointer typedef.
tomwalters@0 2557 # eg, void foo(int); or void foo(int) const;
tomwalters@0 2558 # The equals check is for function pointer assignment.
tomwalters@0 2559 # eg, void *(*foo)(int) = ...
tomwalters@0 2560 #
tomwalters@0 2561 # Right now, this will only catch cases where there's a single argument, and
tomwalters@0 2562 # it's unnamed. It should probably be expanded to check for multiple
tomwalters@0 2563 # arguments with some unnamed.
tomwalters@0 2564 function_match = Match(r'\s*(\)|=|(const)?\s*(;|\{|throw\(\)))', remainder)
tomwalters@0 2565 if function_match:
tomwalters@0 2566 if (not function_match.group(3) or
tomwalters@0 2567 function_match.group(3) == ';' or
tomwalters@0 2568 raw_line.find('/*') < 0):
tomwalters@0 2569 error(filename, linenum, 'readability/function', 3,
tomwalters@0 2570 'All parameters should be named in a function')
tomwalters@0 2571 return
tomwalters@0 2572
tomwalters@0 2573 # At this point, all that should be left is actual casts.
tomwalters@0 2574 error(filename, linenum, 'readability/casting', 4,
tomwalters@0 2575 'Using C-style cast. Use %s<%s>(...) instead' %
tomwalters@0 2576 (cast_type, match.group(1)))
tomwalters@0 2577
tomwalters@0 2578
tomwalters@0 2579 _HEADERS_CONTAINING_TEMPLATES = (
tomwalters@0 2580 ('<deque>', ('deque',)),
tomwalters@0 2581 ('<functional>', ('unary_function', 'binary_function',
tomwalters@0 2582 'plus', 'minus', 'multiplies', 'divides', 'modulus',
tomwalters@0 2583 'negate',
tomwalters@0 2584 'equal_to', 'not_equal_to', 'greater', 'less',
tomwalters@0 2585 'greater_equal', 'less_equal',
tomwalters@0 2586 'logical_and', 'logical_or', 'logical_not',
tomwalters@0 2587 'unary_negate', 'not1', 'binary_negate', 'not2',
tomwalters@0 2588 'bind1st', 'bind2nd',
tomwalters@0 2589 'pointer_to_unary_function',
tomwalters@0 2590 'pointer_to_binary_function',
tomwalters@0 2591 'ptr_fun',
tomwalters@0 2592 'mem_fun_t', 'mem_fun', 'mem_fun1_t', 'mem_fun1_ref_t',
tomwalters@0 2593 'mem_fun_ref_t',
tomwalters@0 2594 'const_mem_fun_t', 'const_mem_fun1_t',
tomwalters@0 2595 'const_mem_fun_ref_t', 'const_mem_fun1_ref_t',
tomwalters@0 2596 'mem_fun_ref',
tomwalters@0 2597 )),
tomwalters@0 2598 ('<limits>', ('numeric_limits',)),
tomwalters@0 2599 ('<list>', ('list',)),
tomwalters@0 2600 ('<map>', ('map', 'multimap',)),
tomwalters@0 2601 ('<memory>', ('allocator',)),
tomwalters@0 2602 ('<queue>', ('queue', 'priority_queue',)),
tomwalters@0 2603 ('<set>', ('set', 'multiset',)),
tomwalters@0 2604 ('<stack>', ('stack',)),
tomwalters@0 2605 ('<string>', ('char_traits', 'basic_string',)),
tomwalters@0 2606 ('<utility>', ('pair',)),
tomwalters@0 2607 ('<vector>', ('vector',)),
tomwalters@0 2608
tomwalters@0 2609 # gcc extensions.
tomwalters@0 2610 # Note: std::hash is their hash, ::hash is our hash
tomwalters@0 2611 ('<hash_map>', ('hash_map', 'hash_multimap',)),
tomwalters@0 2612 ('<hash_set>', ('hash_set', 'hash_multiset',)),
tomwalters@0 2613 ('<slist>', ('slist',)),
tomwalters@0 2614 )
tomwalters@0 2615
tomwalters@0 2616 _HEADERS_ACCEPTED_BUT_NOT_PROMOTED = {
tomwalters@0 2617 # We can trust with reasonable confidence that map gives us pair<>, too.
tomwalters@0 2618 'pair<>': ('map', 'multimap', 'hash_map', 'hash_multimap')
tomwalters@0 2619 }
tomwalters@0 2620
tomwalters@0 2621 _RE_PATTERN_STRING = re.compile(r'\bstring\b')
tomwalters@0 2622
tomwalters@0 2623 _re_pattern_algorithm_header = []
tomwalters@0 2624 for _template in ('copy', 'max', 'min', 'min_element', 'sort', 'swap',
tomwalters@0 2625 'transform'):
tomwalters@0 2626 # Match max<type>(..., ...), max(..., ...), but not foo->max, foo.max or
tomwalters@0 2627 # type::max().
tomwalters@0 2628 _re_pattern_algorithm_header.append(
tomwalters@0 2629 (re.compile(r'[^>.]\b' + _template + r'(<.*?>)?\([^\)]'),
tomwalters@0 2630 _template,
tomwalters@0 2631 '<algorithm>'))
tomwalters@0 2632
tomwalters@0 2633 _re_pattern_templates = []
tomwalters@0 2634 for _header, _templates in _HEADERS_CONTAINING_TEMPLATES:
tomwalters@0 2635 for _template in _templates:
tomwalters@0 2636 _re_pattern_templates.append(
tomwalters@0 2637 (re.compile(r'(\<|\b)' + _template + r'\s*\<'),
tomwalters@0 2638 _template + '<>',
tomwalters@0 2639 _header))
tomwalters@0 2640
tomwalters@0 2641
tomwalters@0 2642 def FilesBelongToSameModule(filename_cc, filename_h):
tomwalters@0 2643 """Check if these two filenames belong to the same module.
tomwalters@0 2644
tomwalters@0 2645 The concept of a 'module' here is a as follows:
tomwalters@0 2646 foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the
tomwalters@0 2647 same 'module' if they are in the same directory.
tomwalters@0 2648 some/path/public/xyzzy and some/path/internal/xyzzy are also considered
tomwalters@0 2649 to belong to the same module here.
tomwalters@0 2650
tomwalters@0 2651 If the filename_cc contains a longer path than the filename_h, for example,
tomwalters@0 2652 '/absolute/path/to/base/sysinfo.cc', and this file would include
tomwalters@0 2653 'base/sysinfo.h', this function also produces the prefix needed to open the
tomwalters@0 2654 header. This is used by the caller of this function to more robustly open the
tomwalters@0 2655 header file. We don't have access to the real include paths in this context,
tomwalters@0 2656 so we need this guesswork here.
tomwalters@0 2657
tomwalters@0 2658 Known bugs: tools/base/bar.cc and base/bar.h belong to the same module
tomwalters@0 2659 according to this implementation. Because of this, this function gives
tomwalters@0 2660 some false positives. This should be sufficiently rare in practice.
tomwalters@0 2661
tomwalters@0 2662 Args:
tomwalters@0 2663 filename_cc: is the path for the .cc file
tomwalters@0 2664 filename_h: is the path for the header path
tomwalters@0 2665
tomwalters@0 2666 Returns:
tomwalters@0 2667 Tuple with a bool and a string:
tomwalters@0 2668 bool: True if filename_cc and filename_h belong to the same module.
tomwalters@0 2669 string: the additional prefix needed to open the header file.
tomwalters@0 2670 """
tomwalters@0 2671
tomwalters@0 2672 if not filename_cc.endswith('.cc'):
tomwalters@0 2673 return (False, '')
tomwalters@0 2674 filename_cc = filename_cc[:-len('.cc')]
tomwalters@0 2675 if filename_cc.endswith('_unittest'):
tomwalters@0 2676 filename_cc = filename_cc[:-len('_unittest')]
tomwalters@0 2677 elif filename_cc.endswith('_test'):
tomwalters@0 2678 filename_cc = filename_cc[:-len('_test')]
tomwalters@0 2679 filename_cc = filename_cc.replace('/public/', '/')
tomwalters@0 2680 filename_cc = filename_cc.replace('/internal/', '/')
tomwalters@0 2681
tomwalters@0 2682 if not filename_h.endswith('.h'):
tomwalters@0 2683 return (False, '')
tomwalters@0 2684 filename_h = filename_h[:-len('.h')]
tomwalters@0 2685 if filename_h.endswith('-inl'):
tomwalters@0 2686 filename_h = filename_h[:-len('-inl')]
tomwalters@0 2687 filename_h = filename_h.replace('/public/', '/')
tomwalters@0 2688 filename_h = filename_h.replace('/internal/', '/')
tomwalters@0 2689
tomwalters@0 2690 files_belong_to_same_module = filename_cc.endswith(filename_h)
tomwalters@0 2691 common_path = ''
tomwalters@0 2692 if files_belong_to_same_module:
tomwalters@0 2693 common_path = filename_cc[:-len(filename_h)]
tomwalters@0 2694 return files_belong_to_same_module, common_path
tomwalters@0 2695
tomwalters@0 2696
tomwalters@0 2697 def UpdateIncludeState(filename, include_state, io=codecs):
tomwalters@0 2698 """Fill up the include_state with new includes found from the file.
tomwalters@0 2699
tomwalters@0 2700 Args:
tomwalters@0 2701 filename: the name of the header to read.
tomwalters@0 2702 include_state: an _IncludeState instance in which the headers are inserted.
tomwalters@0 2703 io: The io factory to use to read the file. Provided for testability.
tomwalters@0 2704
tomwalters@0 2705 Returns:
tomwalters@0 2706 True if a header was succesfully added. False otherwise.
tomwalters@0 2707 """
tomwalters@0 2708 headerfile = None
tomwalters@0 2709 try:
tomwalters@0 2710 headerfile = io.open(filename, 'r', 'utf8', 'replace')
tomwalters@0 2711 except IOError:
tomwalters@0 2712 return False
tomwalters@0 2713 linenum = 0
tomwalters@0 2714 for line in headerfile:
tomwalters@0 2715 linenum += 1
tomwalters@0 2716 clean_line = CleanseComments(line)
tomwalters@0 2717 match = _RE_PATTERN_INCLUDE.search(clean_line)
tomwalters@0 2718 if match:
tomwalters@0 2719 include = match.group(2)
tomwalters@0 2720 # The value formatting is cute, but not really used right now.
tomwalters@0 2721 # What matters here is that the key is in include_state.
tomwalters@0 2722 include_state.setdefault(include, '%s:%d' % (filename, linenum))
tomwalters@0 2723 return True
tomwalters@0 2724
tomwalters@0 2725
tomwalters@0 2726 def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error,
tomwalters@0 2727 io=codecs):
tomwalters@0 2728 """Reports for missing stl includes.
tomwalters@0 2729
tomwalters@0 2730 This function will output warnings to make sure you are including the headers
tomwalters@0 2731 necessary for the stl containers and functions that you use. We only give one
tomwalters@0 2732 reason to include a header. For example, if you use both equal_to<> and
tomwalters@0 2733 less<> in a .h file, only one (the latter in the file) of these will be
tomwalters@0 2734 reported as a reason to include the <functional>.
tomwalters@0 2735
tomwalters@0 2736 Args:
tomwalters@0 2737 filename: The name of the current file.
tomwalters@0 2738 clean_lines: A CleansedLines instance containing the file.
tomwalters@0 2739 include_state: An _IncludeState instance.
tomwalters@0 2740 error: The function to call with any errors found.
tomwalters@0 2741 io: The IO factory to use to read the header file. Provided for unittest
tomwalters@0 2742 injection.
tomwalters@0 2743 """
tomwalters@0 2744 required = {} # A map of header name to linenumber and the template entity.
tomwalters@0 2745 # Example of required: { '<functional>': (1219, 'less<>') }
tomwalters@0 2746
tomwalters@0 2747 for linenum in xrange(clean_lines.NumLines()):
tomwalters@0 2748 line = clean_lines.elided[linenum]
tomwalters@0 2749 if not line or line[0] == '#':
tomwalters@0 2750 continue
tomwalters@0 2751
tomwalters@0 2752 # String is special -- it is a non-templatized type in STL.
tomwalters@0 2753 if _RE_PATTERN_STRING.search(line):
tomwalters@0 2754 required['<string>'] = (linenum, 'string')
tomwalters@0 2755
tomwalters@0 2756 for pattern, template, header in _re_pattern_algorithm_header:
tomwalters@0 2757 if pattern.search(line):
tomwalters@0 2758 required[header] = (linenum, template)
tomwalters@0 2759
tomwalters@0 2760 # The following function is just a speed up, no semantics are changed.
tomwalters@0 2761 if not '<' in line: # Reduces the cpu time usage by skipping lines.
tomwalters@0 2762 continue
tomwalters@0 2763
tomwalters@0 2764 for pattern, template, header in _re_pattern_templates:
tomwalters@0 2765 if pattern.search(line):
tomwalters@0 2766 required[header] = (linenum, template)
tomwalters@0 2767
tomwalters@0 2768 # The policy is that if you #include something in foo.h you don't need to
tomwalters@0 2769 # include it again in foo.cc. Here, we will look at possible includes.
tomwalters@0 2770 # Let's copy the include_state so it is only messed up within this function.
tomwalters@0 2771 include_state = include_state.copy()
tomwalters@0 2772
tomwalters@0 2773 # Did we find the header for this file (if any) and succesfully load it?
tomwalters@0 2774 header_found = False
tomwalters@0 2775
tomwalters@0 2776 # Use the absolute path so that matching works properly.
tomwalters@0 2777 abs_filename = os.path.abspath(filename)
tomwalters@0 2778
tomwalters@0 2779 # For Emacs's flymake.
tomwalters@0 2780 # If cpplint is invoked from Emacs's flymake, a temporary file is generated
tomwalters@0 2781 # by flymake and that file name might end with '_flymake.cc'. In that case,
tomwalters@0 2782 # restore original file name here so that the corresponding header file can be
tomwalters@0 2783 # found.
tomwalters@0 2784 # e.g. If the file name is 'foo_flymake.cc', we should search for 'foo.h'
tomwalters@0 2785 # instead of 'foo_flymake.h'
tomwalters@0 2786 emacs_flymake_suffix = '_flymake.cc'
tomwalters@0 2787 if abs_filename.endswith(emacs_flymake_suffix):
tomwalters@0 2788 abs_filename = abs_filename[:-len(emacs_flymake_suffix)] + '.cc'
tomwalters@0 2789
tomwalters@0 2790 # include_state is modified during iteration, so we iterate over a copy of
tomwalters@0 2791 # the keys.
tomwalters@0 2792 for header in include_state.keys(): #NOLINT
tomwalters@0 2793 (same_module, common_path) = FilesBelongToSameModule(abs_filename, header)
tomwalters@0 2794 fullpath = common_path + header
tomwalters@0 2795 if same_module and UpdateIncludeState(fullpath, include_state, io):
tomwalters@0 2796 header_found = True
tomwalters@0 2797
tomwalters@0 2798 # If we can't find the header file for a .cc, assume it's because we don't
tomwalters@0 2799 # know where to look. In that case we'll give up as we're not sure they
tomwalters@0 2800 # didn't include it in the .h file.
tomwalters@0 2801 # TODO(unknown): Do a better job of finding .h files so we are confident that
tomwalters@0 2802 # not having the .h file means there isn't one.
tomwalters@0 2803 if filename.endswith('.cc') and not header_found:
tomwalters@0 2804 return
tomwalters@0 2805
tomwalters@0 2806 # All the lines have been processed, report the errors found.
tomwalters@0 2807 for required_header_unstripped in required:
tomwalters@0 2808 template = required[required_header_unstripped][1]
tomwalters@0 2809 if template in _HEADERS_ACCEPTED_BUT_NOT_PROMOTED:
tomwalters@0 2810 headers = _HEADERS_ACCEPTED_BUT_NOT_PROMOTED[template]
tomwalters@0 2811 if [True for header in headers if header in include_state]:
tomwalters@0 2812 continue
tomwalters@0 2813 if required_header_unstripped.strip('<>"') not in include_state:
tomwalters@0 2814 error(filename, required[required_header_unstripped][0],
tomwalters@0 2815 'build/include_what_you_use', 4,
tomwalters@0 2816 'Add #include ' + required_header_unstripped + ' for ' + template)
tomwalters@0 2817
tomwalters@0 2818
tomwalters@0 2819 def ProcessLine(filename, file_extension,
tomwalters@0 2820 clean_lines, line, include_state, function_state,
tomwalters@0 2821 class_state, error):
tomwalters@0 2822 """Processes a single line in the file.
tomwalters@0 2823
tomwalters@0 2824 Args:
tomwalters@0 2825 filename: Filename of the file that is being processed.
tomwalters@0 2826 file_extension: The extension (dot not included) of the file.
tomwalters@0 2827 clean_lines: An array of strings, each representing a line of the file,
tomwalters@0 2828 with comments stripped.
tomwalters@0 2829 line: Number of line being processed.
tomwalters@0 2830 include_state: An _IncludeState instance in which the headers are inserted.
tomwalters@0 2831 function_state: A _FunctionState instance which counts function lines, etc.
tomwalters@0 2832 class_state: A _ClassState instance which maintains information about
tomwalters@0 2833 the current stack of nested class declarations being parsed.
tomwalters@0 2834 error: A callable to which errors are reported, which takes 4 arguments:
tomwalters@0 2835 filename, line number, error level, and message
tomwalters@0 2836
tomwalters@0 2837 """
tomwalters@0 2838 raw_lines = clean_lines.raw_lines
tomwalters@0 2839 CheckForFunctionLengths(filename, clean_lines, line, function_state, error)
tomwalters@0 2840 if Search(r'\bNOLINT\b', raw_lines[line]): # ignore nolint lines
tomwalters@0 2841 return
tomwalters@0 2842 CheckForMultilineCommentsAndStrings(filename, clean_lines, line, error)
tomwalters@0 2843 CheckStyle(filename, clean_lines, line, file_extension, error)
tomwalters@0 2844 CheckLanguage(filename, clean_lines, line, file_extension, include_state,
tomwalters@0 2845 error)
tomwalters@0 2846 CheckForNonStandardConstructs(filename, clean_lines, line,
tomwalters@0 2847 class_state, error)
tomwalters@0 2848 CheckPosixThreading(filename, clean_lines, line, error)
tomwalters@0 2849 CheckInvalidIncrement(filename, clean_lines, line, error)
tomwalters@0 2850
tomwalters@0 2851
tomwalters@0 2852 def ProcessFileData(filename, file_extension, lines, error):
tomwalters@0 2853 """Performs lint checks and reports any errors to the given error function.
tomwalters@0 2854
tomwalters@0 2855 Args:
tomwalters@0 2856 filename: Filename of the file that is being processed.
tomwalters@0 2857 file_extension: The extension (dot not included) of the file.
tomwalters@0 2858 lines: An array of strings, each representing a line of the file, with the
tomwalters@0 2859 last element being empty if the file is termined with a newline.
tomwalters@0 2860 error: A callable to which errors are reported, which takes 4 arguments:
tomwalters@0 2861 """
tomwalters@0 2862 lines = (['// marker so line numbers and indices both start at 1'] + lines +
tomwalters@0 2863 ['// marker so line numbers end in a known way'])
tomwalters@0 2864
tomwalters@0 2865 include_state = _IncludeState()
tomwalters@0 2866 function_state = _FunctionState()
tomwalters@0 2867 class_state = _ClassState()
tomwalters@0 2868
tomwalters@0 2869 CheckForCopyright(filename, lines, error)
tomwalters@0 2870
tomwalters@0 2871 if file_extension == 'h':
tomwalters@0 2872 CheckForHeaderGuard(filename, lines, error)
tomwalters@0 2873
tomwalters@0 2874 RemoveMultiLineComments(filename, lines, error)
tomwalters@0 2875 clean_lines = CleansedLines(lines)
tomwalters@0 2876 for line in xrange(clean_lines.NumLines()):
tomwalters@0 2877 ProcessLine(filename, file_extension, clean_lines, line,
tomwalters@0 2878 include_state, function_state, class_state, error)
tomwalters@0 2879 class_state.CheckFinished(filename, error)
tomwalters@0 2880
tomwalters@0 2881 CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error)
tomwalters@0 2882
tomwalters@0 2883 # We check here rather than inside ProcessLine so that we see raw
tomwalters@0 2884 # lines rather than "cleaned" lines.
tomwalters@0 2885 CheckForUnicodeReplacementCharacters(filename, lines, error)
tomwalters@0 2886
tomwalters@0 2887 CheckForNewlineAtEOF(filename, lines, error)
tomwalters@0 2888
tomwalters@0 2889
tomwalters@0 2890 def ProcessFile(filename, vlevel):
tomwalters@0 2891 """Does google-lint on a single file.
tomwalters@0 2892
tomwalters@0 2893 Args:
tomwalters@0 2894 filename: The name of the file to parse.
tomwalters@0 2895
tomwalters@0 2896 vlevel: The level of errors to report. Every error of confidence
tomwalters@0 2897 >= verbose_level will be reported. 0 is a good default.
tomwalters@0 2898 """
tomwalters@0 2899
tomwalters@0 2900 _SetVerboseLevel(vlevel)
tomwalters@0 2901
tomwalters@0 2902 try:
tomwalters@0 2903 # Support the UNIX convention of using "-" for stdin. Note that
tomwalters@0 2904 # we are not opening the file with universal newline support
tomwalters@0 2905 # (which codecs doesn't support anyway), so the resulting lines do
tomwalters@0 2906 # contain trailing '\r' characters if we are reading a file that
tomwalters@0 2907 # has CRLF endings.
tomwalters@0 2908 # If after the split a trailing '\r' is present, it is removed
tomwalters@0 2909 # below. If it is not expected to be present (i.e. os.linesep !=
tomwalters@0 2910 # '\r\n' as in Windows), a warning is issued below if this file
tomwalters@0 2911 # is processed.
tomwalters@0 2912
tomwalters@0 2913 if filename == '-':
tomwalters@0 2914 lines = codecs.StreamReaderWriter(sys.stdin,
tomwalters@0 2915 codecs.getreader('utf8'),
tomwalters@0 2916 codecs.getwriter('utf8'),
tomwalters@0 2917 'replace').read().split('\n')
tomwalters@0 2918 else:
tomwalters@0 2919 lines = codecs.open(filename, 'r', 'utf8', 'replace').read().split('\n')
tomwalters@0 2920
tomwalters@0 2921 carriage_return_found = False
tomwalters@0 2922 # Remove trailing '\r'.
tomwalters@0 2923 for linenum in range(len(lines)):
tomwalters@0 2924 if lines[linenum].endswith('\r'):
tomwalters@0 2925 lines[linenum] = lines[linenum].rstrip('\r')
tomwalters@0 2926 carriage_return_found = True
tomwalters@0 2927
tomwalters@0 2928 except IOError:
tomwalters@0 2929 sys.stderr.write(
tomwalters@0 2930 "Skipping input '%s': Can't open for reading\n" % filename)
tomwalters@0 2931 return
tomwalters@0 2932
tomwalters@0 2933 # Note, if no dot is found, this will give the entire filename as the ext.
tomwalters@0 2934 file_extension = filename[filename.rfind('.') + 1:]
tomwalters@0 2935
tomwalters@0 2936 # When reading from stdin, the extension is unknown, so no cpplint tests
tomwalters@0 2937 # should rely on the extension.
tomwalters@0 2938 if (filename != '-' and file_extension != 'cc' and file_extension != 'h'
tomwalters@0 2939 and file_extension != 'cpp'):
tomwalters@0 2940 sys.stderr.write('Ignoring %s; not a .cc or .h file\n' % filename)
tomwalters@0 2941 else:
tomwalters@0 2942 ProcessFileData(filename, file_extension, lines, Error)
tomwalters@0 2943 if carriage_return_found and os.linesep != '\r\n':
tomwalters@0 2944 # Use 0 for linenum since outputing only one error for potentially
tomwalters@0 2945 # several lines.
tomwalters@0 2946 Error(filename, 0, 'whitespace/newline', 1,
tomwalters@0 2947 'One or more unexpected \\r (^M) found;'
tomwalters@0 2948 'better to use only a \\n')
tomwalters@0 2949
tomwalters@0 2950 sys.stderr.write('Done processing %s\n' % filename)
tomwalters@0 2951
tomwalters@0 2952
tomwalters@0 2953 def PrintUsage(message):
tomwalters@0 2954 """Prints a brief usage string and exits, optionally with an error message.
tomwalters@0 2955
tomwalters@0 2956 Args:
tomwalters@0 2957 message: The optional error message.
tomwalters@0 2958 """
tomwalters@0 2959 sys.stderr.write(_USAGE)
tomwalters@0 2960 if message:
tomwalters@0 2961 sys.exit('\nFATAL ERROR: ' + message)
tomwalters@0 2962 else:
tomwalters@0 2963 sys.exit(1)
tomwalters@0 2964
tomwalters@0 2965
tomwalters@0 2966 def PrintCategories():
tomwalters@0 2967 """Prints a list of all the error-categories used by error messages.
tomwalters@0 2968
tomwalters@0 2969 These are the categories used to filter messages via --filter.
tomwalters@0 2970 """
tomwalters@0 2971 sys.stderr.write(_ERROR_CATEGORIES)
tomwalters@0 2972 sys.exit(0)
tomwalters@0 2973
tomwalters@0 2974
tomwalters@0 2975 def ParseArguments(args):
tomwalters@0 2976 """Parses the command line arguments.
tomwalters@0 2977
tomwalters@0 2978 This may set the output format and verbosity level as side-effects.
tomwalters@0 2979
tomwalters@0 2980 Args:
tomwalters@0 2981 args: The command line arguments:
tomwalters@0 2982
tomwalters@0 2983 Returns:
tomwalters@0 2984 The list of filenames to lint.
tomwalters@0 2985 """
tomwalters@0 2986 try:
tomwalters@0 2987 (opts, filenames) = getopt.getopt(args, '', ['help', 'output=', 'verbose=',
tomwalters@0 2988 'counting=',
tomwalters@0 2989 'filter='])
tomwalters@0 2990 except getopt.GetoptError:
tomwalters@0 2991 PrintUsage('Invalid arguments.')
tomwalters@0 2992
tomwalters@0 2993 verbosity = _VerboseLevel()
tomwalters@0 2994 output_format = _OutputFormat()
tomwalters@0 2995 filters = ''
tomwalters@0 2996 counting_style = ''
tomwalters@0 2997
tomwalters@0 2998 for (opt, val) in opts:
tomwalters@0 2999 if opt == '--help':
tomwalters@0 3000 PrintUsage(None)
tomwalters@0 3001 elif opt == '--output':
tomwalters@0 3002 if not val in ('emacs', 'vs7'):
tomwalters@0 3003 PrintUsage('The only allowed output formats are emacs and vs7.')
tomwalters@0 3004 output_format = val
tomwalters@0 3005 elif opt == '--verbose':
tomwalters@0 3006 verbosity = int(val)
tomwalters@0 3007 elif opt == '--filter':
tomwalters@0 3008 filters = val
tomwalters@0 3009 if not filters:
tomwalters@0 3010 PrintCategories()
tomwalters@0 3011 elif opt == '--counting':
tomwalters@0 3012 if val not in ('total', 'toplevel', 'detailed'):
tomwalters@0 3013 PrintUsage('Valid counting options are total, toplevel, and detailed')
tomwalters@0 3014 counting_style = val
tomwalters@0 3015
tomwalters@0 3016 if not filenames:
tomwalters@0 3017 PrintUsage('No files were specified.')
tomwalters@0 3018
tomwalters@0 3019 _SetOutputFormat(output_format)
tomwalters@0 3020 _SetVerboseLevel(verbosity)
tomwalters@0 3021 _SetFilters(filters)
tomwalters@0 3022 _SetCountingStyle(counting_style)
tomwalters@0 3023
tomwalters@0 3024 return filenames
tomwalters@0 3025
tomwalters@0 3026
tomwalters@0 3027 def main():
tomwalters@0 3028 filenames = ParseArguments(sys.argv[1:])
tomwalters@0 3029
tomwalters@0 3030 # Change stderr to write with replacement characters so we don't die
tomwalters@0 3031 # if we try to print something containing non-ASCII characters.
tomwalters@0 3032 sys.stderr = codecs.StreamReaderWriter(sys.stderr,
tomwalters@0 3033 codecs.getreader('utf8'),
tomwalters@0 3034 codecs.getwriter('utf8'),
tomwalters@0 3035 'replace')
tomwalters@0 3036
tomwalters@0 3037 _cpplint_state.ResetErrorCounts()
tomwalters@0 3038 for filename in filenames:
tomwalters@0 3039 ProcessFile(filename, _cpplint_state.verbose_level)
tomwalters@0 3040 _cpplint_state.PrintErrorCounts()
tomwalters@0 3041
tomwalters@0 3042 sys.exit(_cpplint_state.error_count > 0)
tomwalters@0 3043
tomwalters@0 3044
tomwalters@0 3045 if __name__ == '__main__':
tomwalters@0 3046 main()