annotate trunk/lint/cpplint.py @ 706:f8e90b5d85fd tip

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