blob: f74eff79f9ec9cd86a008a05c276bc94e18a8747 [file] [log] [blame]
erg@chromium.orgd528f8b2012-05-11 17:31:08 +00001#!/usr/bin/env python
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002#
erg@google.com26970fa2009-11-17 18:07:32 +00003# Copyright (c) 2009 Google Inc. All rights reserved.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004#
erg@google.com26970fa2009-11-17 18:07:32 +00005# Redistribution and use in source and binary forms, with or without
6# modification, are permitted provided that the following conditions are
7# met:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00008#
erg@google.com26970fa2009-11-17 18:07:32 +00009# * Redistributions of source code must retain the above copyright
10# notice, this list of conditions and the following disclaimer.
11# * Redistributions in binary form must reproduce the above
12# copyright notice, this list of conditions and the following disclaimer
13# in the documentation and/or other materials provided with the
14# distribution.
15# * Neither the name of Google Inc. nor the names of its
16# contributors may be used to endorse or promote products derived from
17# this software without specific prior written permission.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000018#
erg@google.com26970fa2009-11-17 18:07:32 +000019# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000030
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000031"""Does google-lint on c++ files.
32
33The goal of this script is to identify places in the code that *may*
34be in non-compliance with google style. It does not attempt to fix
35up these problems -- the point is to educate. It does also not
36attempt to find all problems, or to ensure that everything it does
37find is legitimately a problem.
38
39In particular, we can get very confused by /* and // inside strings!
40We do a small hack, which is to ignore //'s with "'s after them on the
41same line, but it is far from perfect (in either direction).
42"""
43
44import codecs
mazda@chromium.org3fffcec2013-06-07 01:04:53 +000045import copy
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000046import getopt
47import math # for log
48import os
49import re
50import sre_compile
51import string
52import sys
53import unicodedata
54
55
56_USAGE = """
57Syntax: cpplint.py [--verbose=#] [--output=vs7] [--filter=-x,+y,...]
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +000058 [--counting=total|toplevel|detailed] [--root=subdir]
59 [--linelength=digits]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000060 <file> [file] ...
61
62 The style guidelines this tries to follow are those in
avakulenko@chromium.org764ce712016-05-06 23:03:41 +000063 https://google-styleguide.googlecode.com/svn/trunk/cppguide.xml
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000064
65 Every problem is given a confidence score from 1-5, with 5 meaning we are
66 certain of the problem, and 1 meaning it could be a legitimate construct.
67 This will miss some errors, and is not a substitute for a code review.
68
erg@google.com35589e62010-11-17 18:58:16 +000069 To suppress false-positive errors of a certain category, add a
70 'NOLINT(category)' comment to the line. NOLINT or NOLINT(*)
71 suppresses errors of all categories on that line.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000072
73 The files passed in will be linted; at least one file must be provided.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +000074 Default linted extensions are .cc, .cpp, .cu, .cuh and .h. Change the
75 extensions with the --extensions flag.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000076
77 Flags:
78
79 output=vs7
80 By default, the output is formatted to ease emacs parsing. Visual Studio
81 compatible output (vs7) may also be used. Other formats are unsupported.
82
83 verbose=#
84 Specify a number 0-5 to restrict errors to certain verbosity levels.
85
86 filter=-x,+y,...
87 Specify a comma-separated list of category-filters to apply: only
88 error messages whose category names pass the filters will be printed.
89 (Category names are printed with the message and look like
90 "[whitespace/indent]".) Filters are evaluated left to right.
91 "-FOO" and "FOO" means "do not print categories that start with FOO".
92 "+FOO" means "do print categories that start with FOO".
93
94 Examples: --filter=-whitespace,+whitespace/braces
95 --filter=whitespace,runtime/printf,+runtime/printf_format
96 --filter=-,+build/include_what_you_use
97
98 To see a list of all the categories used in cpplint, pass no arg:
99 --filter=
erg@google.com26970fa2009-11-17 18:07:32 +0000100
101 counting=total|toplevel|detailed
102 The total number of errors found is always printed. If
103 'toplevel' is provided, then the count of errors in each of
104 the top-level categories like 'build' and 'whitespace' will
105 also be printed. If 'detailed' is provided, then a count
106 is provided for each category like 'build/class'.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +0000107
108 root=subdir
109 The root directory used for deriving header guard CPP variable.
110 By default, the header guard CPP variable is calculated as the relative
111 path to the directory that contains .git, .hg, or .svn. When this flag
112 is specified, the relative path is calculated from the specified
113 directory. If the specified directory does not exist, this flag is
114 ignored.
115
116 Examples:
avakulenko@google.comd39bbb52014-06-04 22:55:20 +0000117 Assuming that src/.git exists, the header guard CPP variables for
mazda@chromium.org3fffcec2013-06-07 01:04:53 +0000118 src/chrome/browser/ui/browser.h are:
119
120 No flag => CHROME_BROWSER_UI_BROWSER_H_
121 --root=chrome => BROWSER_UI_BROWSER_H_
122 --root=chrome/browser => UI_BROWSER_H_
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000123
124 linelength=digits
125 This is the allowed line length for the project. The default value is
126 80 characters.
127
128 Examples:
129 --linelength=120
130
131 extensions=extension,extension,...
132 The allowed file extensions that cpplint will check
133
134 Examples:
135 --extensions=hpp,cpp
avakulenko@google.com17449932014-07-28 22:13:33 +0000136
137 cpplint.py supports per-directory configurations specified in CPPLINT.cfg
138 files. CPPLINT.cfg file can contain a number of key=value pairs.
139 Currently the following options are supported:
140
141 set noparent
142 filter=+filter1,-filter2,...
143 exclude_files=regex
avakulenko@google.com68a4fa62014-08-25 16:26:18 +0000144 linelength=80
avakulenko@google.com17449932014-07-28 22:13:33 +0000145
146 "set noparent" option prevents cpplint from traversing directory tree
147 upwards looking for more .cfg files in parent directories. This option
148 is usually placed in the top-level project directory.
149
150 The "filter" option is similar in function to --filter flag. It specifies
151 message filters in addition to the |_DEFAULT_FILTERS| and those specified
152 through --filter command-line flag.
153
154 "exclude_files" allows to specify a regular expression to be matched against
155 a file name. If the expression matches, the file is skipped and not run
156 through liner.
157
avakulenko@google.com68a4fa62014-08-25 16:26:18 +0000158 "linelength" allows to specify the allowed line length for the project.
159
avakulenko@google.com17449932014-07-28 22:13:33 +0000160 CPPLINT.cfg has an effect on files in the same directory and all
161 sub-directories, unless overridden by a nested configuration file.
162
163 Example file:
164 filter=-build/include_order,+build/include_alpha
165 exclude_files=.*\.cc
166
167 The above example disables build/include_order warning and enables
168 build/include_alpha as well as excludes all .cc from being
169 processed by linter, in the current directory (where the .cfg
170 file is located) and all sub-directories.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000171"""
172
173# We categorize each error message we print. Here are the categories.
174# We want an explicit list so we can list them all in cpplint --filter=.
175# If you add a new error message with a new category, add it to the list
176# here! cpplint_unittest.py should tell you if you forget to do this.
erg@google.com35589e62010-11-17 18:58:16 +0000177_ERROR_CATEGORIES = [
avakulenko@google.com255f2be2014-12-05 22:19:55 +0000178 'build/class',
179 'build/c++11',
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000180 'build/c++14',
181 'build/c++tr1',
avakulenko@google.com255f2be2014-12-05 22:19:55 +0000182 'build/deprecated',
183 'build/endif_comment',
184 'build/explicit_make_pair',
185 'build/forward_decl',
186 'build/header_guard',
187 'build/include',
188 'build/include_alpha',
189 'build/include_order',
190 'build/include_what_you_use',
191 'build/namespaces',
192 'build/printf_format',
193 'build/storage_class',
194 'legal/copyright',
195 'readability/alt_tokens',
196 'readability/braces',
197 'readability/casting',
198 'readability/check',
199 'readability/constructors',
200 'readability/fn_size',
avakulenko@google.com255f2be2014-12-05 22:19:55 +0000201 'readability/inheritance',
202 'readability/multiline_comment',
203 'readability/multiline_string',
204 'readability/namespace',
205 'readability/nolint',
206 'readability/nul',
207 'readability/strings',
208 'readability/todo',
209 'readability/utf8',
210 'runtime/arrays',
211 'runtime/casting',
212 'runtime/explicit',
213 'runtime/int',
214 'runtime/init',
215 'runtime/invalid_increment',
216 'runtime/member_string_references',
217 'runtime/memset',
218 'runtime/indentation_namespace',
219 'runtime/operator',
220 'runtime/printf',
221 'runtime/printf_format',
222 'runtime/references',
223 'runtime/string',
224 'runtime/threadsafe_fn',
225 'runtime/vlog',
226 'whitespace/blank_line',
227 'whitespace/braces',
228 'whitespace/comma',
229 'whitespace/comments',
230 'whitespace/empty_conditional_body',
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000231 'whitespace/empty_if_body',
avakulenko@google.com255f2be2014-12-05 22:19:55 +0000232 'whitespace/empty_loop_body',
233 'whitespace/end_of_line',
234 'whitespace/ending_newline',
235 'whitespace/forcolon',
236 'whitespace/indent',
237 'whitespace/line_length',
238 'whitespace/newline',
239 'whitespace/operators',
240 'whitespace/parens',
241 'whitespace/semicolon',
242 'whitespace/tab',
243 'whitespace/todo',
244 ]
245
246# These error categories are no longer enforced by cpplint, but for backwards-
247# compatibility they may still appear in NOLINT comments.
248_LEGACY_ERROR_CATEGORIES = [
249 'readability/streams',
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000250 'readability/function',
avakulenko@google.com255f2be2014-12-05 22:19:55 +0000251 ]
erg@google.com6317a9c2009-06-25 00:28:19 +0000252
avakulenko@google.comd39bbb52014-06-04 22:55:20 +0000253# The default state of the category filter. This is overridden by the --filter=
erg@google.com6317a9c2009-06-25 00:28:19 +0000254# flag. By default all errors are on, so only add here categories that should be
255# off by default (i.e., categories that must be enabled by the --filter= flags).
256# All entries here should start with a '-' or '+', as in the --filter= flag.
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +0000257_DEFAULT_FILTERS = ['-build/include_alpha']
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000258
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000259# The default list of categories suppressed for C (not C++) files.
260_DEFAULT_C_SUPPRESSED_CATEGORIES = [
261 'readability/casting',
262 ]
263
264# The default list of categories suppressed for Linux Kernel files.
265_DEFAULT_KERNEL_SUPPRESSED_CATEGORIES = [
266 'whitespace/tab',
267 ]
268
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000269# We used to check for high-bit characters, but after much discussion we
270# decided those were OK, as long as they were in UTF-8 and didn't represent
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +0000271# hard-coded international strings, which belong in a separate i18n file.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000272
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000273# C++ headers
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000274_CPP_HEADERS = frozenset([
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000275 # Legacy
276 'algobase.h',
277 'algo.h',
278 'alloc.h',
279 'builtinbuf.h',
280 'bvector.h',
281 'complex.h',
282 'defalloc.h',
283 'deque.h',
284 'editbuf.h',
285 'fstream.h',
286 'function.h',
287 'hash_map',
288 'hash_map.h',
289 'hash_set',
290 'hash_set.h',
291 'hashtable.h',
292 'heap.h',
293 'indstream.h',
294 'iomanip.h',
295 'iostream.h',
296 'istream.h',
297 'iterator.h',
298 'list.h',
299 'map.h',
300 'multimap.h',
301 'multiset.h',
302 'ostream.h',
303 'pair.h',
304 'parsestream.h',
305 'pfstream.h',
306 'procbuf.h',
307 'pthread_alloc',
308 'pthread_alloc.h',
309 'rope',
310 'rope.h',
311 'ropeimpl.h',
312 'set.h',
313 'slist',
314 'slist.h',
315 'stack.h',
316 'stdiostream.h',
317 'stl_alloc.h',
318 'stl_relops.h',
319 'streambuf.h',
320 'stream.h',
321 'strfile.h',
322 'strstream.h',
323 'tempbuf.h',
324 'tree.h',
325 'type_traits.h',
326 'vector.h',
327 # 17.6.1.2 C++ library headers
328 'algorithm',
329 'array',
330 'atomic',
331 'bitset',
332 'chrono',
333 'codecvt',
334 'complex',
335 'condition_variable',
336 'deque',
337 'exception',
338 'forward_list',
339 'fstream',
340 'functional',
341 'future',
342 'initializer_list',
343 'iomanip',
344 'ios',
345 'iosfwd',
346 'iostream',
347 'istream',
348 'iterator',
349 'limits',
350 'list',
351 'locale',
352 'map',
353 'memory',
354 'mutex',
355 'new',
356 'numeric',
357 'ostream',
358 'queue',
359 'random',
360 'ratio',
361 'regex',
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000362 'scoped_allocator',
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000363 'set',
364 'sstream',
365 'stack',
366 'stdexcept',
367 'streambuf',
368 'string',
369 'strstream',
370 'system_error',
371 'thread',
372 'tuple',
373 'typeindex',
374 'typeinfo',
375 'type_traits',
376 'unordered_map',
377 'unordered_set',
378 'utility',
379 'valarray',
380 'vector',
381 # 17.6.1.2 C++ headers for C library facilities
382 'cassert',
383 'ccomplex',
384 'cctype',
385 'cerrno',
386 'cfenv',
387 'cfloat',
388 'cinttypes',
389 'ciso646',
390 'climits',
391 'clocale',
392 'cmath',
393 'csetjmp',
394 'csignal',
395 'cstdalign',
396 'cstdarg',
397 'cstdbool',
398 'cstddef',
399 'cstdint',
400 'cstdio',
401 'cstdlib',
402 'cstring',
403 'ctgmath',
404 'ctime',
405 'cuchar',
406 'cwchar',
407 'cwctype',
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000408 ])
409
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000410# Type names
411_TYPES = re.compile(
412 r'^(?:'
413 # [dcl.type.simple]
414 r'(char(16_t|32_t)?)|wchar_t|'
415 r'bool|short|int|long|signed|unsigned|float|double|'
416 # [support.types]
417 r'(ptrdiff_t|size_t|max_align_t|nullptr_t)|'
418 # [cstdint.syn]
419 r'(u?int(_fast|_least)?(8|16|32|64)_t)|'
420 r'(u?int(max|ptr)_t)|'
421 r')$')
422
avakulenko@google.comd39bbb52014-06-04 22:55:20 +0000423
avakulenko@google.com59146752014-08-11 20:20:55 +0000424# These headers are excluded from [build/include] and [build/include_order]
425# checks:
426# - Anything not following google file name conventions (containing an
427# uppercase character, such as Python.h or nsStringAPI.h, for example).
428# - Lua headers.
429_THIRD_PARTY_HEADERS_PATTERN = re.compile(
430 r'^(?:[^/]*[A-Z][^/]*\.h|lua\.h|lauxlib\.h|lualib\.h)$')
431
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000432# Pattern for matching FileInfo.BaseName() against test file name
433_TEST_FILE_SUFFIX = r'(_test|_unittest|_regtest)$'
434
435# Pattern that matches only complete whitespace, possibly across multiple lines.
436_EMPTY_CONDITIONAL_BODY_PATTERN = re.compile(r'^\s*$', re.DOTALL)
avakulenko@google.com59146752014-08-11 20:20:55 +0000437
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000438# Assertion macros. These are defined in base/logging.h and
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000439# testing/base/public/gunit.h.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000440_CHECK_MACROS = [
erg@google.com6317a9c2009-06-25 00:28:19 +0000441 'DCHECK', 'CHECK',
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000442 'EXPECT_TRUE', 'ASSERT_TRUE',
443 'EXPECT_FALSE', 'ASSERT_FALSE',
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000444 ]
445
erg@google.com6317a9c2009-06-25 00:28:19 +0000446# Replacement macros for CHECK/DCHECK/EXPECT_TRUE/EXPECT_FALSE
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000447_CHECK_REPLACEMENT = dict([(m, {}) for m in _CHECK_MACROS])
448
449for op, replacement in [('==', 'EQ'), ('!=', 'NE'),
450 ('>=', 'GE'), ('>', 'GT'),
451 ('<=', 'LE'), ('<', 'LT')]:
erg@google.com6317a9c2009-06-25 00:28:19 +0000452 _CHECK_REPLACEMENT['DCHECK'][op] = 'DCHECK_%s' % replacement
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000453 _CHECK_REPLACEMENT['CHECK'][op] = 'CHECK_%s' % replacement
454 _CHECK_REPLACEMENT['EXPECT_TRUE'][op] = 'EXPECT_%s' % replacement
455 _CHECK_REPLACEMENT['ASSERT_TRUE'][op] = 'ASSERT_%s' % replacement
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000456
457for op, inv_replacement in [('==', 'NE'), ('!=', 'EQ'),
458 ('>=', 'LT'), ('>', 'LE'),
459 ('<=', 'GT'), ('<', 'GE')]:
460 _CHECK_REPLACEMENT['EXPECT_FALSE'][op] = 'EXPECT_%s' % inv_replacement
461 _CHECK_REPLACEMENT['ASSERT_FALSE'][op] = 'ASSERT_%s' % inv_replacement
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000462
mazda@chromium.org3fffcec2013-06-07 01:04:53 +0000463# Alternative tokens and their replacements. For full list, see section 2.5
464# Alternative tokens [lex.digraph] in the C++ standard.
465#
466# Digraphs (such as '%:') are not included here since it's a mess to
467# match those on a word boundary.
468_ALT_TOKEN_REPLACEMENT = {
469 'and': '&&',
470 'bitor': '|',
471 'or': '||',
472 'xor': '^',
473 'compl': '~',
474 'bitand': '&',
475 'and_eq': '&=',
476 'or_eq': '|=',
477 'xor_eq': '^=',
478 'not': '!',
479 'not_eq': '!='
480 }
481
482# Compile regular expression that matches all the above keywords. The "[ =()]"
483# bit is meant to avoid matching these keywords outside of boolean expressions.
484#
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000485# False positives include C-style multi-line comments and multi-line strings
486# but those have always been troublesome for cpplint.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +0000487_ALT_TOKEN_REPLACEMENT_PATTERN = re.compile(
488 r'[ =()](' + ('|'.join(_ALT_TOKEN_REPLACEMENT.keys())) + r')(?=[ (]|$)')
489
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000490
491# These constants define types of headers for use with
492# _IncludeState.CheckNextIncludeOrder().
493_C_SYS_HEADER = 1
494_CPP_SYS_HEADER = 2
495_LIKELY_MY_HEADER = 3
496_POSSIBLE_MY_HEADER = 4
497_OTHER_HEADER = 5
498
mazda@chromium.org3fffcec2013-06-07 01:04:53 +0000499# These constants define the current inline assembly state
500_NO_ASM = 0 # Outside of inline assembly block
501_INSIDE_ASM = 1 # Inside inline assembly block
502_END_ASM = 2 # Last line of inline assembly block
503_BLOCK_ASM = 3 # The whole block is an inline assembly block
504
505# Match start of assembly blocks
506_MATCH_ASM = re.compile(r'^\s*(?:asm|_asm|__asm|__asm__)'
507 r'(?:\s+(volatile|__volatile__))?'
508 r'\s*[{(]')
509
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000510# Match strings that indicate we're working on a C (not C++) file.
511_SEARCH_C_FILE = re.compile(r'\b(?:LINT_C_FILE|'
512 r'vim?:\s*.*(\s*|:)filetype=c(\s*|:|$))')
513
514# Match string that indicates we're working on a Linux Kernel file.
515_SEARCH_KERNEL_FILE = re.compile(r'\b(?:LINT_KERNEL_FILE)')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000516
517_regexp_compile_cache = {}
518
erg@google.com35589e62010-11-17 18:58:16 +0000519# {str, set(int)}: a map from error categories to sets of linenumbers
520# on which those errors are expected and should be suppressed.
521_error_suppressions = {}
522
mazda@chromium.org3fffcec2013-06-07 01:04:53 +0000523# The root directory used for deriving header guard CPP variable.
524# This is set by --root flag.
525_root = None
526
sdefresne263e9282016-07-19 02:14:22 -0700527# The project root directory. Used for deriving header guard CPP variable.
528# This is set by --project_root flag. Must be an absolute path.
529_project_root = None
530
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000531# The allowed line length of files.
532# This is set by --linelength flag.
533_line_length = 80
534
535# The allowed extensions for file names
536# This is set by --extensions flag.
537_valid_extensions = set(['cc', 'h', 'cpp', 'cu', 'cuh'])
538
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000539# {str, bool}: a map from error categories to booleans which indicate if the
540# category should be suppressed for every line.
541_global_error_suppressions = {}
542
543
erg@google.com35589e62010-11-17 18:58:16 +0000544def ParseNolintSuppressions(filename, raw_line, linenum, error):
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000545 """Updates the global list of line error-suppressions.
erg@google.com35589e62010-11-17 18:58:16 +0000546
547 Parses any NOLINT comments on the current line, updating the global
548 error_suppressions store. Reports an error if the NOLINT comment
549 was malformed.
550
551 Args:
552 filename: str, the name of the input file.
553 raw_line: str, the line of input text, with comments.
554 linenum: int, the number of the current line.
555 error: function, an error handler.
556 """
avakulenko@google.com59146752014-08-11 20:20:55 +0000557 matched = Search(r'\bNOLINT(NEXTLINE)?\b(\([^)]+\))?', raw_line)
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +0000558 if matched:
avakulenko@google.com59146752014-08-11 20:20:55 +0000559 if matched.group(1):
560 suppressed_line = linenum + 1
561 else:
562 suppressed_line = linenum
563 category = matched.group(2)
erg@google.com35589e62010-11-17 18:58:16 +0000564 if category in (None, '(*)'): # => "suppress all"
avakulenko@google.com59146752014-08-11 20:20:55 +0000565 _error_suppressions.setdefault(None, set()).add(suppressed_line)
erg@google.com35589e62010-11-17 18:58:16 +0000566 else:
567 if category.startswith('(') and category.endswith(')'):
568 category = category[1:-1]
569 if category in _ERROR_CATEGORIES:
avakulenko@google.com59146752014-08-11 20:20:55 +0000570 _error_suppressions.setdefault(category, set()).add(suppressed_line)
avakulenko@google.com255f2be2014-12-05 22:19:55 +0000571 elif category not in _LEGACY_ERROR_CATEGORIES:
erg@google.com35589e62010-11-17 18:58:16 +0000572 error(filename, linenum, 'readability/nolint', 5,
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +0000573 'Unknown NOLINT error category: %s' % category)
erg@google.com35589e62010-11-17 18:58:16 +0000574
575
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000576def ProcessGlobalSuppresions(lines):
577 """Updates the list of global error suppressions.
578
579 Parses any lint directives in the file that have global effect.
580
581 Args:
582 lines: An array of strings, each representing a line of the file, with the
583 last element being empty if the file is terminated with a newline.
584 """
585 for line in lines:
586 if _SEARCH_C_FILE.search(line):
587 for category in _DEFAULT_C_SUPPRESSED_CATEGORIES:
588 _global_error_suppressions[category] = True
589 if _SEARCH_KERNEL_FILE.search(line):
590 for category in _DEFAULT_KERNEL_SUPPRESSED_CATEGORIES:
591 _global_error_suppressions[category] = True
592
593
erg@google.com35589e62010-11-17 18:58:16 +0000594def ResetNolintSuppressions():
avakulenko@google.com59146752014-08-11 20:20:55 +0000595 """Resets the set of NOLINT suppressions to empty."""
erg@google.com35589e62010-11-17 18:58:16 +0000596 _error_suppressions.clear()
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000597 _global_error_suppressions.clear()
erg@google.com35589e62010-11-17 18:58:16 +0000598
599
600def IsErrorSuppressedByNolint(category, linenum):
601 """Returns true if the specified error category is suppressed on this line.
602
603 Consults the global error_suppressions map populated by
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000604 ParseNolintSuppressions/ProcessGlobalSuppresions/ResetNolintSuppressions.
erg@google.com35589e62010-11-17 18:58:16 +0000605
606 Args:
607 category: str, the category of the error.
608 linenum: int, the current line number.
609 Returns:
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000610 bool, True iff the error should be suppressed due to a NOLINT comment or
611 global suppression.
erg@google.com35589e62010-11-17 18:58:16 +0000612 """
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000613 return (_global_error_suppressions.get(category, False) or
614 linenum in _error_suppressions.get(category, set()) or
erg@google.com35589e62010-11-17 18:58:16 +0000615 linenum in _error_suppressions.get(None, set()))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000616
avakulenko@google.comd39bbb52014-06-04 22:55:20 +0000617
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000618def Match(pattern, s):
619 """Matches the string with the pattern, caching the compiled regexp."""
620 # The regexp compilation caching is inlined in both Match and Search for
621 # performance reasons; factoring it out into a separate function turns out
622 # to be noticeably expensive.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000623 if pattern not in _regexp_compile_cache:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000624 _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
625 return _regexp_compile_cache[pattern].match(s)
626
627
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000628def ReplaceAll(pattern, rep, s):
629 """Replaces instances of pattern in a string with a replacement.
630
631 The compiled regex is kept in a cache shared by Match and Search.
632
633 Args:
634 pattern: regex pattern
635 rep: replacement text
636 s: search string
637
638 Returns:
639 string with replacements made (or original string if no replacements)
640 """
641 if pattern not in _regexp_compile_cache:
642 _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
643 return _regexp_compile_cache[pattern].sub(rep, s)
644
645
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000646def Search(pattern, s):
647 """Searches the string for the pattern, caching the compiled regexp."""
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000648 if pattern not in _regexp_compile_cache:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000649 _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
650 return _regexp_compile_cache[pattern].search(s)
651
652
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000653def _IsSourceExtension(s):
654 """File extension (excluding dot) matches a source file extension."""
655 return s in ('c', 'cc', 'cpp', 'cxx')
656
657
avakulenko@google.com59146752014-08-11 20:20:55 +0000658class _IncludeState(object):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000659 """Tracks line numbers for includes, and the order in which includes appear.
660
avakulenko@google.com59146752014-08-11 20:20:55 +0000661 include_list contains list of lists of (header, line number) pairs.
662 It's a lists of lists rather than just one flat list to make it
663 easier to update across preprocessor boundaries.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000664
665 Call CheckNextIncludeOrder() once for each header in the file, passing
666 in the type constants defined above. Calls in an illegal order will
667 raise an _IncludeError with an appropriate error message.
668
669 """
670 # self._section will move monotonically through this set. If it ever
671 # needs to move backwards, CheckNextIncludeOrder will raise an error.
672 _INITIAL_SECTION = 0
673 _MY_H_SECTION = 1
674 _C_SECTION = 2
675 _CPP_SECTION = 3
676 _OTHER_H_SECTION = 4
677
678 _TYPE_NAMES = {
679 _C_SYS_HEADER: 'C system header',
680 _CPP_SYS_HEADER: 'C++ system header',
681 _LIKELY_MY_HEADER: 'header this file implements',
682 _POSSIBLE_MY_HEADER: 'header this file may implement',
683 _OTHER_HEADER: 'other header',
684 }
685 _SECTION_NAMES = {
686 _INITIAL_SECTION: "... nothing. (This can't be an error.)",
687 _MY_H_SECTION: 'a header this file implements',
688 _C_SECTION: 'C system header',
689 _CPP_SECTION: 'C++ system header',
690 _OTHER_H_SECTION: 'other header',
691 }
692
693 def __init__(self):
avakulenko@google.com59146752014-08-11 20:20:55 +0000694 self.include_list = [[]]
695 self.ResetSection('')
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000696
avakulenko@google.com59146752014-08-11 20:20:55 +0000697 def FindHeader(self, header):
698 """Check if a header has already been included.
699
700 Args:
701 header: header to check.
702 Returns:
703 Line number of previous occurrence, or -1 if the header has not
704 been seen before.
705 """
706 for section_list in self.include_list:
707 for f in section_list:
708 if f[0] == header:
709 return f[1]
710 return -1
711
712 def ResetSection(self, directive):
713 """Reset section checking for preprocessor directive.
714
715 Args:
716 directive: preprocessor directive (e.g. "if", "else").
717 """
erg@google.com26970fa2009-11-17 18:07:32 +0000718 # The name of the current section.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000719 self._section = self._INITIAL_SECTION
erg@google.com26970fa2009-11-17 18:07:32 +0000720 # The path of last found header.
721 self._last_header = ''
722
avakulenko@google.com59146752014-08-11 20:20:55 +0000723 # Update list of includes. Note that we never pop from the
724 # include list.
725 if directive in ('if', 'ifdef', 'ifndef'):
726 self.include_list.append([])
727 elif directive in ('else', 'elif'):
728 self.include_list[-1] = []
729
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000730 def SetLastHeader(self, header_path):
731 self._last_header = header_path
732
erg@google.com26970fa2009-11-17 18:07:32 +0000733 def CanonicalizeAlphabeticalOrder(self, header_path):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +0000734 """Returns a path canonicalized for alphabetical comparison.
erg@google.com26970fa2009-11-17 18:07:32 +0000735
736 - replaces "-" with "_" so they both cmp the same.
737 - removes '-inl' since we don't require them to be after the main header.
738 - lowercase everything, just in case.
739
740 Args:
741 header_path: Path to be canonicalized.
742
743 Returns:
744 Canonicalized path.
745 """
746 return header_path.replace('-inl.h', '.h').replace('-', '_').lower()
747
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000748 def IsInAlphabeticalOrder(self, clean_lines, linenum, header_path):
erg@google.com26970fa2009-11-17 18:07:32 +0000749 """Check if a header is in alphabetical order with the previous header.
750
751 Args:
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000752 clean_lines: A CleansedLines instance containing the file.
753 linenum: The number of the line to check.
754 header_path: Canonicalized header to be checked.
erg@google.com26970fa2009-11-17 18:07:32 +0000755
756 Returns:
757 Returns true if the header is in alphabetical order.
758 """
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000759 # If previous section is different from current section, _last_header will
760 # be reset to empty string, so it's always less than current header.
761 #
762 # If previous line was a blank line, assume that the headers are
763 # intentionally sorted the way they are.
764 if (self._last_header > header_path and
avakulenko@google.com255f2be2014-12-05 22:19:55 +0000765 Match(r'^\s*#\s*include\b', clean_lines.elided[linenum - 1])):
erg@google.com26970fa2009-11-17 18:07:32 +0000766 return False
erg@google.com26970fa2009-11-17 18:07:32 +0000767 return True
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000768
769 def CheckNextIncludeOrder(self, header_type):
770 """Returns a non-empty error message if the next header is out of order.
771
772 This function also updates the internal state to be ready to check
773 the next include.
774
775 Args:
776 header_type: One of the _XXX_HEADER constants defined above.
777
778 Returns:
779 The empty string if the header is in the right order, or an
780 error message describing what's wrong.
781
782 """
783 error_message = ('Found %s after %s' %
784 (self._TYPE_NAMES[header_type],
785 self._SECTION_NAMES[self._section]))
786
erg@google.com26970fa2009-11-17 18:07:32 +0000787 last_section = self._section
788
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000789 if header_type == _C_SYS_HEADER:
790 if self._section <= self._C_SECTION:
791 self._section = self._C_SECTION
792 else:
erg@google.com26970fa2009-11-17 18:07:32 +0000793 self._last_header = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000794 return error_message
795 elif header_type == _CPP_SYS_HEADER:
796 if self._section <= self._CPP_SECTION:
797 self._section = self._CPP_SECTION
798 else:
erg@google.com26970fa2009-11-17 18:07:32 +0000799 self._last_header = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000800 return error_message
801 elif header_type == _LIKELY_MY_HEADER:
802 if self._section <= self._MY_H_SECTION:
803 self._section = self._MY_H_SECTION
804 else:
805 self._section = self._OTHER_H_SECTION
806 elif header_type == _POSSIBLE_MY_HEADER:
807 if self._section <= self._MY_H_SECTION:
808 self._section = self._MY_H_SECTION
809 else:
810 # This will always be the fallback because we're not sure
811 # enough that the header is associated with this file.
812 self._section = self._OTHER_H_SECTION
813 else:
814 assert header_type == _OTHER_HEADER
815 self._section = self._OTHER_H_SECTION
816
erg@google.com26970fa2009-11-17 18:07:32 +0000817 if last_section != self._section:
818 self._last_header = ''
819
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000820 return ''
821
822
823class _CppLintState(object):
824 """Maintains module-wide state.."""
825
826 def __init__(self):
827 self.verbose_level = 1 # global setting.
828 self.error_count = 0 # global count of reported errors
erg@google.com6317a9c2009-06-25 00:28:19 +0000829 # filters to apply when emitting error messages
830 self.filters = _DEFAULT_FILTERS[:]
avakulenko@google.com17449932014-07-28 22:13:33 +0000831 # backup of filter list. Used to restore the state after each file.
832 self._filters_backup = self.filters[:]
erg@google.com26970fa2009-11-17 18:07:32 +0000833 self.counting = 'total' # In what way are we counting errors?
834 self.errors_by_category = {} # string to int dict storing error counts
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000835
836 # output format:
837 # "emacs" - format that emacs can parse (default)
838 # "vs7" - format that Microsoft Visual Studio 7 can parse
839 self.output_format = 'emacs'
840
841 def SetOutputFormat(self, output_format):
842 """Sets the output format for errors."""
843 self.output_format = output_format
844
845 def SetVerboseLevel(self, level):
846 """Sets the module's verbosity, and returns the previous setting."""
847 last_verbose_level = self.verbose_level
848 self.verbose_level = level
849 return last_verbose_level
850
erg@google.com26970fa2009-11-17 18:07:32 +0000851 def SetCountingStyle(self, counting_style):
852 """Sets the module's counting options."""
853 self.counting = counting_style
854
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000855 def SetFilters(self, filters):
856 """Sets the error-message filters.
857
858 These filters are applied when deciding whether to emit a given
859 error message.
860
861 Args:
862 filters: A string of comma-separated filters (eg "+whitespace/indent").
863 Each filter should start with + or -; else we die.
erg@google.com6317a9c2009-06-25 00:28:19 +0000864
865 Raises:
866 ValueError: The comma-separated filters did not all start with '+' or '-'.
867 E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter"
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000868 """
erg@google.com6317a9c2009-06-25 00:28:19 +0000869 # Default filters always have less priority than the flag ones.
870 self.filters = _DEFAULT_FILTERS[:]
avakulenko@google.com17449932014-07-28 22:13:33 +0000871 self.AddFilters(filters)
872
873 def AddFilters(self, filters):
874 """ Adds more filters to the existing list of error-message filters. """
erg@google.com6317a9c2009-06-25 00:28:19 +0000875 for filt in filters.split(','):
876 clean_filt = filt.strip()
877 if clean_filt:
878 self.filters.append(clean_filt)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000879 for filt in self.filters:
880 if not (filt.startswith('+') or filt.startswith('-')):
881 raise ValueError('Every filter in --filters must start with + or -'
882 ' (%s does not)' % filt)
883
avakulenko@google.com17449932014-07-28 22:13:33 +0000884 def BackupFilters(self):
885 """ Saves the current filter list to backup storage."""
886 self._filters_backup = self.filters[:]
887
888 def RestoreFilters(self):
889 """ Restores filters previously backed up."""
890 self.filters = self._filters_backup[:]
891
erg@google.com26970fa2009-11-17 18:07:32 +0000892 def ResetErrorCounts(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000893 """Sets the module's error statistic back to zero."""
894 self.error_count = 0
erg@google.com26970fa2009-11-17 18:07:32 +0000895 self.errors_by_category = {}
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000896
erg@google.com26970fa2009-11-17 18:07:32 +0000897 def IncrementErrorCount(self, category):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000898 """Bumps the module's error statistic."""
899 self.error_count += 1
erg@google.com26970fa2009-11-17 18:07:32 +0000900 if self.counting in ('toplevel', 'detailed'):
901 if self.counting != 'detailed':
902 category = category.split('/')[0]
903 if category not in self.errors_by_category:
904 self.errors_by_category[category] = 0
905 self.errors_by_category[category] += 1
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000906
erg@google.com26970fa2009-11-17 18:07:32 +0000907 def PrintErrorCounts(self):
908 """Print a summary of errors by category, and the total."""
909 for category, count in self.errors_by_category.iteritems():
910 sys.stderr.write('Category \'%s\' errors found: %d\n' %
911 (category, count))
912 sys.stderr.write('Total errors found: %d\n' % self.error_count)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000913
914_cpplint_state = _CppLintState()
915
916
917def _OutputFormat():
918 """Gets the module's output format."""
919 return _cpplint_state.output_format
920
921
922def _SetOutputFormat(output_format):
923 """Sets the module's output format."""
924 _cpplint_state.SetOutputFormat(output_format)
925
926
927def _VerboseLevel():
928 """Returns the module's verbosity setting."""
929 return _cpplint_state.verbose_level
930
931
932def _SetVerboseLevel(level):
933 """Sets the module's verbosity, and returns the previous setting."""
934 return _cpplint_state.SetVerboseLevel(level)
935
936
erg@google.com26970fa2009-11-17 18:07:32 +0000937def _SetCountingStyle(level):
938 """Sets the module's counting options."""
939 _cpplint_state.SetCountingStyle(level)
940
941
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000942def _Filters():
943 """Returns the module's list of output filters, as a list."""
944 return _cpplint_state.filters
945
946
947def _SetFilters(filters):
948 """Sets the module's error-message filters.
949
950 These filters are applied when deciding whether to emit a given
951 error message.
952
953 Args:
954 filters: A string of comma-separated filters (eg "whitespace/indent").
955 Each filter should start with + or -; else we die.
956 """
957 _cpplint_state.SetFilters(filters)
958
avakulenko@google.com17449932014-07-28 22:13:33 +0000959def _AddFilters(filters):
960 """Adds more filter overrides.
avakulenko@google.com59146752014-08-11 20:20:55 +0000961
avakulenko@google.com17449932014-07-28 22:13:33 +0000962 Unlike _SetFilters, this function does not reset the current list of filters
963 available.
964
965 Args:
966 filters: A string of comma-separated filters (eg "whitespace/indent").
967 Each filter should start with + or -; else we die.
968 """
969 _cpplint_state.AddFilters(filters)
970
971def _BackupFilters():
972 """ Saves the current filter list to backup storage."""
973 _cpplint_state.BackupFilters()
974
975def _RestoreFilters():
976 """ Restores filters previously backed up."""
977 _cpplint_state.RestoreFilters()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000978
979class _FunctionState(object):
980 """Tracks current function name and the number of lines in its body."""
981
982 _NORMAL_TRIGGER = 250 # for --v=0, 500 for --v=1, etc.
983 _TEST_TRIGGER = 400 # about 50% more than _NORMAL_TRIGGER.
984
985 def __init__(self):
986 self.in_a_function = False
987 self.lines_in_function = 0
988 self.current_function = ''
989
990 def Begin(self, function_name):
991 """Start analyzing function body.
992
993 Args:
994 function_name: The name of the function being tracked.
995 """
996 self.in_a_function = True
997 self.lines_in_function = 0
998 self.current_function = function_name
999
1000 def Count(self):
1001 """Count line in current function body."""
1002 if self.in_a_function:
1003 self.lines_in_function += 1
1004
1005 def Check(self, error, filename, linenum):
1006 """Report if too many lines in function body.
1007
1008 Args:
1009 error: The function to call with any errors found.
1010 filename: The name of the current file.
1011 linenum: The number of the line to check.
1012 """
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00001013 if not self.in_a_function:
1014 return
1015
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001016 if Match(r'T(EST|est)', self.current_function):
1017 base_trigger = self._TEST_TRIGGER
1018 else:
1019 base_trigger = self._NORMAL_TRIGGER
1020 trigger = base_trigger * 2**_VerboseLevel()
1021
1022 if self.lines_in_function > trigger:
1023 error_level = int(math.log(self.lines_in_function / base_trigger, 2))
1024 # 50 => 0, 100 => 1, 200 => 2, 400 => 3, 800 => 4, 1600 => 5, ...
1025 if error_level > 5:
1026 error_level = 5
1027 error(filename, linenum, 'readability/fn_size', error_level,
1028 'Small and focused functions are preferred:'
1029 ' %s has %d non-comment lines'
1030 ' (error triggered by exceeding %d lines).' % (
1031 self.current_function, self.lines_in_function, trigger))
1032
1033 def End(self):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00001034 """Stop analyzing function body."""
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001035 self.in_a_function = False
1036
1037
1038class _IncludeError(Exception):
1039 """Indicates a problem with the include order in a file."""
1040 pass
1041
1042
avakulenko@google.com59146752014-08-11 20:20:55 +00001043class FileInfo(object):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001044 """Provides utility functions for filenames.
1045
1046 FileInfo provides easy access to the components of a file's path
1047 relative to the project root.
1048 """
1049
1050 def __init__(self, filename):
1051 self._filename = filename
1052
1053 def FullName(self):
1054 """Make Windows paths like Unix."""
1055 return os.path.abspath(self._filename).replace('\\', '/')
1056
1057 def RepositoryName(self):
1058 """FullName after removing the local path to the repository.
1059
1060 If we have a real absolute path name here we can try to do something smart:
1061 detecting the root of the checkout and truncating /path/to/checkout from
1062 the name so that we get header guards that don't include things like
1063 "C:\Documents and Settings\..." or "/home/username/..." in them and thus
1064 people on different computers who have checked the source out to different
1065 locations won't see bogus errors.
1066 """
1067 fullname = self.FullName()
1068
1069 if os.path.exists(fullname):
1070 project_dir = os.path.dirname(fullname)
1071
sdefresne263e9282016-07-19 02:14:22 -07001072 if _project_root:
1073 prefix = os.path.commonprefix([_project_root, project_dir])
1074 return fullname[len(prefix) + 1:]
1075
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001076 if os.path.exists(os.path.join(project_dir, ".svn")):
1077 # If there's a .svn file in the current directory, we recursively look
1078 # up the directory tree for the top of the SVN checkout
1079 root_dir = project_dir
1080 one_up_dir = os.path.dirname(root_dir)
1081 while os.path.exists(os.path.join(one_up_dir, ".svn")):
1082 root_dir = os.path.dirname(root_dir)
1083 one_up_dir = os.path.dirname(one_up_dir)
1084
1085 prefix = os.path.commonprefix([root_dir, project_dir])
1086 return fullname[len(prefix) + 1:]
1087
erg@chromium.org7956a872011-11-30 01:44:03 +00001088 # Not SVN <= 1.6? Try to find a git, hg, or svn top level directory by
1089 # searching up from the current path.
kjellander@chromium.org95a5ad82016-04-22 19:29:18 +00001090 root_dir = os.path.dirname(fullname)
1091 while (root_dir != os.path.dirname(root_dir) and
1092 not os.path.exists(os.path.join(root_dir, ".git")) and
1093 not os.path.exists(os.path.join(root_dir, ".hg")) and
1094 not os.path.exists(os.path.join(root_dir, ".svn"))):
1095 root_dir = os.path.dirname(root_dir)
erg@google.com35589e62010-11-17 18:58:16 +00001096
1097 if (os.path.exists(os.path.join(root_dir, ".git")) or
erg@chromium.org7956a872011-11-30 01:44:03 +00001098 os.path.exists(os.path.join(root_dir, ".hg")) or
1099 os.path.exists(os.path.join(root_dir, ".svn"))):
erg@google.com35589e62010-11-17 18:58:16 +00001100 prefix = os.path.commonprefix([root_dir, project_dir])
1101 return fullname[len(prefix) + 1:]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001102
1103 # Don't know what to do; header guard warnings may be wrong...
1104 return fullname
1105
1106 def Split(self):
1107 """Splits the file into the directory, basename, and extension.
1108
1109 For 'chrome/browser/browser.cc', Split() would
1110 return ('chrome/browser', 'browser', '.cc')
1111
1112 Returns:
1113 A tuple of (directory, basename, extension).
1114 """
1115
1116 googlename = self.RepositoryName()
1117 project, rest = os.path.split(googlename)
1118 return (project,) + os.path.splitext(rest)
1119
1120 def BaseName(self):
1121 """File base name - text after the final slash, before the final period."""
1122 return self.Split()[1]
1123
1124 def Extension(self):
1125 """File extension - text following the final period."""
1126 return self.Split()[2]
1127
1128 def NoExtension(self):
1129 """File has no source file extension."""
1130 return '/'.join(self.Split()[0:2])
1131
1132 def IsSource(self):
1133 """File has a source file extension."""
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00001134 return _IsSourceExtension(self.Extension()[1:])
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001135
1136
erg@google.com35589e62010-11-17 18:58:16 +00001137def _ShouldPrintError(category, confidence, linenum):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00001138 """If confidence >= verbose, category passes filter and is not suppressed."""
erg@google.com35589e62010-11-17 18:58:16 +00001139
1140 # There are three ways we might decide not to print an error message:
1141 # a "NOLINT(category)" comment appears in the source,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001142 # the verbosity level isn't high enough, or the filters filter it out.
erg@google.com35589e62010-11-17 18:58:16 +00001143 if IsErrorSuppressedByNolint(category, linenum):
1144 return False
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001145
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001146 if confidence < _cpplint_state.verbose_level:
1147 return False
1148
1149 is_filtered = False
1150 for one_filter in _Filters():
1151 if one_filter.startswith('-'):
1152 if category.startswith(one_filter[1:]):
1153 is_filtered = True
1154 elif one_filter.startswith('+'):
1155 if category.startswith(one_filter[1:]):
1156 is_filtered = False
1157 else:
1158 assert False # should have been checked for in SetFilter.
1159 if is_filtered:
1160 return False
1161
1162 return True
1163
1164
1165def Error(filename, linenum, category, confidence, message):
1166 """Logs the fact we've found a lint error.
1167
1168 We log where the error was found, and also our confidence in the error,
1169 that is, how certain we are this is a legitimate style regression, and
1170 not a misidentification or a use that's sometimes justified.
1171
erg@google.com35589e62010-11-17 18:58:16 +00001172 False positives can be suppressed by the use of
1173 "cpplint(category)" comments on the offending line. These are
1174 parsed into _error_suppressions.
1175
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001176 Args:
1177 filename: The name of the file containing the error.
1178 linenum: The number of the line containing the error.
1179 category: A string used to describe the "category" this bug
1180 falls under: "whitespace", say, or "runtime". Categories
1181 may have a hierarchy separated by slashes: "whitespace/indent".
1182 confidence: A number from 1-5 representing a confidence score for
1183 the error, with 5 meaning that we are certain of the problem,
1184 and 1 meaning that it could be a legitimate construct.
1185 message: The error message.
1186 """
erg@google.com35589e62010-11-17 18:58:16 +00001187 if _ShouldPrintError(category, confidence, linenum):
erg@google.com26970fa2009-11-17 18:07:32 +00001188 _cpplint_state.IncrementErrorCount(category)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001189 if _cpplint_state.output_format == 'vs7':
1190 sys.stderr.write('%s(%s): %s [%s] [%d]\n' % (
1191 filename, linenum, message, category, confidence))
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001192 elif _cpplint_state.output_format == 'eclipse':
1193 sys.stderr.write('%s:%s: warning: %s [%s] [%d]\n' % (
1194 filename, linenum, message, category, confidence))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001195 else:
1196 sys.stderr.write('%s:%s: %s [%s] [%d]\n' % (
1197 filename, linenum, message, category, confidence))
1198
1199
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001200# Matches standard C++ escape sequences per 2.13.2.3 of the C++ standard.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001201_RE_PATTERN_CLEANSE_LINE_ESCAPES = re.compile(
1202 r'\\([abfnrtv?"\\\']|\d+|x[0-9a-fA-F]+)')
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001203# Match a single C style comment on the same line.
1204_RE_PATTERN_C_COMMENTS = r'/\*(?:[^*]|\*(?!/))*\*/'
1205# Matches multi-line C style comments.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001206# This RE is a little bit more complicated than one might expect, because we
1207# have to take care of space removals tools so we can handle comments inside
1208# statements better.
1209# The current rule is: We only clear spaces from both sides when we're at the
1210# end of the line. Otherwise, we try to remove spaces from the right side,
1211# if this doesn't work we try on left side but only if there's a non-character
1212# on the right.
1213_RE_PATTERN_CLEANSE_LINE_C_COMMENTS = re.compile(
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001214 r'(\s*' + _RE_PATTERN_C_COMMENTS + r'\s*$|' +
1215 _RE_PATTERN_C_COMMENTS + r'\s+|' +
1216 r'\s+' + _RE_PATTERN_C_COMMENTS + r'(?=\W)|' +
1217 _RE_PATTERN_C_COMMENTS + r')')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001218
1219
1220def IsCppString(line):
1221 """Does line terminate so, that the next symbol is in string constant.
1222
1223 This function does not consider single-line nor multi-line comments.
1224
1225 Args:
1226 line: is a partial line of code starting from the 0..n.
1227
1228 Returns:
1229 True, if next character appended to 'line' is inside a
1230 string constant.
1231 """
1232
1233 line = line.replace(r'\\', 'XX') # after this, \\" does not match to \"
1234 return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1
1235
1236
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001237def CleanseRawStrings(raw_lines):
1238 """Removes C++11 raw strings from lines.
1239
1240 Before:
1241 static const char kData[] = R"(
1242 multi-line string
1243 )";
1244
1245 After:
1246 static const char kData[] = ""
1247 (replaced by blank line)
1248 "";
1249
1250 Args:
1251 raw_lines: list of raw lines.
1252
1253 Returns:
1254 list of lines with C++11 raw strings replaced by empty strings.
1255 """
1256
1257 delimiter = None
1258 lines_without_raw_strings = []
1259 for line in raw_lines:
1260 if delimiter:
1261 # Inside a raw string, look for the end
1262 end = line.find(delimiter)
1263 if end >= 0:
1264 # Found the end of the string, match leading space for this
1265 # line and resume copying the original lines, and also insert
1266 # a "" on the last line.
1267 leading_space = Match(r'^(\s*)\S', line)
1268 line = leading_space.group(1) + '""' + line[end + len(delimiter):]
1269 delimiter = None
1270 else:
1271 # Haven't found the end yet, append a blank line.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001272 line = '""'
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001273
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001274 # Look for beginning of a raw string, and replace them with
1275 # empty strings. This is done in a loop to handle multiple raw
1276 # strings on the same line.
1277 while delimiter is None:
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001278 # Look for beginning of a raw string.
1279 # See 2.14.15 [lex.string] for syntax.
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00001280 #
1281 # Once we have matched a raw string, we check the prefix of the
1282 # line to make sure that the line is not part of a single line
1283 # comment. It's done this way because we remove raw strings
1284 # before removing comments as opposed to removing comments
1285 # before removing raw strings. This is because there are some
1286 # cpplint checks that requires the comments to be preserved, but
1287 # we don't want to check comments that are inside raw strings.
1288 matched = Match(r'^(.*?)\b(?:R|u8R|uR|UR|LR)"([^\s\\()]*)\((.*)$', line)
1289 if (matched and
1290 not Match(r'^([^\'"]|\'(\\.|[^\'])*\'|"(\\.|[^"])*")*//',
1291 matched.group(1))):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001292 delimiter = ')' + matched.group(2) + '"'
1293
1294 end = matched.group(3).find(delimiter)
1295 if end >= 0:
1296 # Raw string ended on same line
1297 line = (matched.group(1) + '""' +
1298 matched.group(3)[end + len(delimiter):])
1299 delimiter = None
1300 else:
1301 # Start of a multi-line raw string
1302 line = matched.group(1) + '""'
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001303 else:
1304 break
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001305
1306 lines_without_raw_strings.append(line)
1307
1308 # TODO(unknown): if delimiter is not None here, we might want to
1309 # emit a warning for unterminated string.
1310 return lines_without_raw_strings
1311
1312
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001313def FindNextMultiLineCommentStart(lines, lineix):
1314 """Find the beginning marker for a multiline comment."""
1315 while lineix < len(lines):
1316 if lines[lineix].strip().startswith('/*'):
1317 # Only return this marker if the comment goes beyond this line
1318 if lines[lineix].strip().find('*/', 2) < 0:
1319 return lineix
1320 lineix += 1
1321 return len(lines)
1322
1323
1324def FindNextMultiLineCommentEnd(lines, lineix):
1325 """We are inside a comment, find the end marker."""
1326 while lineix < len(lines):
1327 if lines[lineix].strip().endswith('*/'):
1328 return lineix
1329 lineix += 1
1330 return len(lines)
1331
1332
1333def RemoveMultiLineCommentsFromRange(lines, begin, end):
1334 """Clears a range of lines for multi-line comments."""
1335 # Having // dummy comments makes the lines non-empty, so we will not get
1336 # unnecessary blank line warnings later in the code.
1337 for i in range(begin, end):
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001338 lines[i] = '/**/'
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001339
1340
1341def RemoveMultiLineComments(filename, lines, error):
1342 """Removes multiline (c-style) comments from lines."""
1343 lineix = 0
1344 while lineix < len(lines):
1345 lineix_begin = FindNextMultiLineCommentStart(lines, lineix)
1346 if lineix_begin >= len(lines):
1347 return
1348 lineix_end = FindNextMultiLineCommentEnd(lines, lineix_begin)
1349 if lineix_end >= len(lines):
1350 error(filename, lineix_begin + 1, 'readability/multiline_comment', 5,
1351 'Could not find end of multi-line comment')
1352 return
1353 RemoveMultiLineCommentsFromRange(lines, lineix_begin, lineix_end + 1)
1354 lineix = lineix_end + 1
1355
1356
1357def CleanseComments(line):
1358 """Removes //-comments and single-line C-style /* */ comments.
1359
1360 Args:
1361 line: A line of C++ source.
1362
1363 Returns:
1364 The line with single-line comments removed.
1365 """
1366 commentpos = line.find('//')
1367 if commentpos != -1 and not IsCppString(line[:commentpos]):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00001368 line = line[:commentpos].rstrip()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001369 # get rid of /* ... */
1370 return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line)
1371
1372
erg@google.com6317a9c2009-06-25 00:28:19 +00001373class CleansedLines(object):
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001374 """Holds 4 copies of all lines with different preprocessing applied to them.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001375
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001376 1) elided member contains lines without strings and comments.
1377 2) lines member contains lines without comments.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001378 3) raw_lines member contains all the lines without processing.
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001379 4) lines_without_raw_strings member is same as raw_lines, but with C++11 raw
1380 strings removed.
1381 All these members are of <type 'list'>, and of the same length.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001382 """
1383
1384 def __init__(self, lines):
1385 self.elided = []
1386 self.lines = []
1387 self.raw_lines = lines
1388 self.num_lines = len(lines)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001389 self.lines_without_raw_strings = CleanseRawStrings(lines)
1390 for linenum in range(len(self.lines_without_raw_strings)):
1391 self.lines.append(CleanseComments(
1392 self.lines_without_raw_strings[linenum]))
1393 elided = self._CollapseStrings(self.lines_without_raw_strings[linenum])
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001394 self.elided.append(CleanseComments(elided))
1395
1396 def NumLines(self):
1397 """Returns the number of lines represented."""
1398 return self.num_lines
1399
1400 @staticmethod
1401 def _CollapseStrings(elided):
1402 """Collapses strings and chars on a line to simple "" or '' blocks.
1403
1404 We nix strings first so we're not fooled by text like '"http://"'
1405
1406 Args:
1407 elided: The line being processed.
1408
1409 Returns:
1410 The line with collapsed strings.
1411 """
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001412 if _RE_PATTERN_INCLUDE.match(elided):
1413 return elided
1414
1415 # Remove escaped characters first to make quote/single quote collapsing
1416 # basic. Things that look like escaped characters shouldn't occur
1417 # outside of strings and chars.
1418 elided = _RE_PATTERN_CLEANSE_LINE_ESCAPES.sub('', elided)
1419
1420 # Replace quoted strings and digit separators. Both single quotes
1421 # and double quotes are processed in the same loop, otherwise
1422 # nested quotes wouldn't work.
1423 collapsed = ''
1424 while True:
1425 # Find the first quote character
1426 match = Match(r'^([^\'"]*)([\'"])(.*)$', elided)
1427 if not match:
1428 collapsed += elided
1429 break
1430 head, quote, tail = match.groups()
1431
1432 if quote == '"':
1433 # Collapse double quoted strings
1434 second_quote = tail.find('"')
1435 if second_quote >= 0:
1436 collapsed += head + '""'
1437 elided = tail[second_quote + 1:]
1438 else:
1439 # Unmatched double quote, don't bother processing the rest
1440 # of the line since this is probably a multiline string.
1441 collapsed += elided
1442 break
1443 else:
1444 # Found single quote, check nearby text to eliminate digit separators.
1445 #
1446 # There is no special handling for floating point here, because
1447 # the integer/fractional/exponent parts would all be parsed
1448 # correctly as long as there are digits on both sides of the
1449 # separator. So we are fine as long as we don't see something
1450 # like "0.'3" (gcc 4.9.0 will not allow this literal).
1451 if Search(r'\b(?:0[bBxX]?|[1-9])[0-9a-fA-F]*$', head):
1452 match_literal = Match(r'^((?:\'?[0-9a-zA-Z_])*)(.*)$', "'" + tail)
1453 collapsed += head + match_literal.group(1).replace("'", '')
1454 elided = match_literal.group(2)
1455 else:
1456 second_quote = tail.find('\'')
1457 if second_quote >= 0:
1458 collapsed += head + "''"
1459 elided = tail[second_quote + 1:]
1460 else:
1461 # Unmatched single quote
1462 collapsed += elided
1463 break
1464
1465 return collapsed
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001466
1467
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001468def FindEndOfExpressionInLine(line, startpos, stack):
1469 """Find the position just after the end of current parenthesized expression.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001470
1471 Args:
1472 line: a CleansedLines line.
1473 startpos: start searching at this position.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001474 stack: nesting stack at startpos.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001475
1476 Returns:
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001477 On finding matching end: (index just after matching end, None)
1478 On finding an unclosed expression: (-1, None)
1479 Otherwise: (-1, new stack at end of this line)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001480 """
1481 for i in xrange(startpos, len(line)):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001482 char = line[i]
1483 if char in '([{':
1484 # Found start of parenthesized expression, push to expression stack
1485 stack.append(char)
1486 elif char == '<':
1487 # Found potential start of template argument list
1488 if i > 0 and line[i - 1] == '<':
1489 # Left shift operator
1490 if stack and stack[-1] == '<':
1491 stack.pop()
1492 if not stack:
1493 return (-1, None)
1494 elif i > 0 and Search(r'\boperator\s*$', line[0:i]):
1495 # operator<, don't add to stack
1496 continue
1497 else:
1498 # Tentative start of template argument list
1499 stack.append('<')
1500 elif char in ')]}':
1501 # Found end of parenthesized expression.
1502 #
1503 # If we are currently expecting a matching '>', the pending '<'
1504 # must have been an operator. Remove them from expression stack.
1505 while stack and stack[-1] == '<':
1506 stack.pop()
1507 if not stack:
1508 return (-1, None)
1509 if ((stack[-1] == '(' and char == ')') or
1510 (stack[-1] == '[' and char == ']') or
1511 (stack[-1] == '{' and char == '}')):
1512 stack.pop()
1513 if not stack:
1514 return (i + 1, None)
1515 else:
1516 # Mismatched parentheses
1517 return (-1, None)
1518 elif char == '>':
1519 # Found potential end of template argument list.
1520
1521 # Ignore "->" and operator functions
1522 if (i > 0 and
1523 (line[i - 1] == '-' or Search(r'\boperator\s*$', line[0:i - 1]))):
1524 continue
1525
1526 # Pop the stack if there is a matching '<'. Otherwise, ignore
1527 # this '>' since it must be an operator.
1528 if stack:
1529 if stack[-1] == '<':
1530 stack.pop()
1531 if not stack:
1532 return (i + 1, None)
1533 elif char == ';':
1534 # Found something that look like end of statements. If we are currently
1535 # expecting a '>', the matching '<' must have been an operator, since
1536 # template argument list should not contain statements.
1537 while stack and stack[-1] == '<':
1538 stack.pop()
1539 if not stack:
1540 return (-1, None)
1541
1542 # Did not find end of expression or unbalanced parentheses on this line
1543 return (-1, stack)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001544
1545
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001546def CloseExpression(clean_lines, linenum, pos):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001547 """If input points to ( or { or [ or <, finds the position that closes it.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001548
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001549 If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001550 linenum/pos that correspond to the closing of the expression.
1551
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001552 TODO(unknown): cpplint spends a fair bit of time matching parentheses.
1553 Ideally we would want to index all opening and closing parentheses once
1554 and have CloseExpression be just a simple lookup, but due to preprocessor
1555 tricks, this is not so easy.
1556
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001557 Args:
1558 clean_lines: A CleansedLines instance containing the file.
1559 linenum: The number of the line to check.
1560 pos: A position on the line.
1561
1562 Returns:
1563 A tuple (line, linenum, pos) pointer *past* the closing brace, or
1564 (line, len(lines), -1) if we never find a close. Note we ignore
1565 strings and comments when matching; and the line we return is the
1566 'cleansed' line at linenum.
1567 """
1568
1569 line = clean_lines.elided[linenum]
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001570 if (line[pos] not in '({[<') or Match(r'<[<=]', line[pos:]):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001571 return (line, clean_lines.NumLines(), -1)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001572
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001573 # Check first line
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001574 (end_pos, stack) = FindEndOfExpressionInLine(line, pos, [])
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001575 if end_pos > -1:
1576 return (line, linenum, end_pos)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001577
1578 # Continue scanning forward
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001579 while stack and linenum < clean_lines.NumLines() - 1:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001580 linenum += 1
1581 line = clean_lines.elided[linenum]
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001582 (end_pos, stack) = FindEndOfExpressionInLine(line, 0, stack)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001583 if end_pos > -1:
1584 return (line, linenum, end_pos)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001585
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001586 # Did not find end of expression before end of file, give up
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001587 return (line, clean_lines.NumLines(), -1)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001588
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001589
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001590def FindStartOfExpressionInLine(line, endpos, stack):
1591 """Find position at the matching start of current expression.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001592
1593 This is almost the reverse of FindEndOfExpressionInLine, but note
1594 that the input position and returned position differs by 1.
1595
1596 Args:
1597 line: a CleansedLines line.
1598 endpos: start searching at this position.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001599 stack: nesting stack at endpos.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001600
1601 Returns:
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001602 On finding matching start: (index at matching start, None)
1603 On finding an unclosed expression: (-1, None)
1604 Otherwise: (-1, new stack at beginning of this line)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001605 """
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001606 i = endpos
1607 while i >= 0:
1608 char = line[i]
1609 if char in ')]}':
1610 # Found end of expression, push to expression stack
1611 stack.append(char)
1612 elif char == '>':
1613 # Found potential end of template argument list.
1614 #
1615 # Ignore it if it's a "->" or ">=" or "operator>"
1616 if (i > 0 and
1617 (line[i - 1] == '-' or
1618 Match(r'\s>=\s', line[i - 1:]) or
1619 Search(r'\boperator\s*$', line[0:i]))):
1620 i -= 1
1621 else:
1622 stack.append('>')
1623 elif char == '<':
1624 # Found potential start of template argument list
1625 if i > 0 and line[i - 1] == '<':
1626 # Left shift operator
1627 i -= 1
1628 else:
1629 # If there is a matching '>', we can pop the expression stack.
1630 # Otherwise, ignore this '<' since it must be an operator.
1631 if stack and stack[-1] == '>':
1632 stack.pop()
1633 if not stack:
1634 return (i, None)
1635 elif char in '([{':
1636 # Found start of expression.
1637 #
1638 # If there are any unmatched '>' on the stack, they must be
1639 # operators. Remove those.
1640 while stack and stack[-1] == '>':
1641 stack.pop()
1642 if not stack:
1643 return (-1, None)
1644 if ((char == '(' and stack[-1] == ')') or
1645 (char == '[' and stack[-1] == ']') or
1646 (char == '{' and stack[-1] == '}')):
1647 stack.pop()
1648 if not stack:
1649 return (i, None)
1650 else:
1651 # Mismatched parentheses
1652 return (-1, None)
1653 elif char == ';':
1654 # Found something that look like end of statements. If we are currently
1655 # expecting a '<', the matching '>' must have been an operator, since
1656 # template argument list should not contain statements.
1657 while stack and stack[-1] == '>':
1658 stack.pop()
1659 if not stack:
1660 return (-1, None)
1661
1662 i -= 1
1663
1664 return (-1, stack)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001665
1666
1667def ReverseCloseExpression(clean_lines, linenum, pos):
1668 """If input points to ) or } or ] or >, finds the position that opens it.
1669
1670 If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the
1671 linenum/pos that correspond to the opening of the expression.
1672
1673 Args:
1674 clean_lines: A CleansedLines instance containing the file.
1675 linenum: The number of the line to check.
1676 pos: A position on the line.
1677
1678 Returns:
1679 A tuple (line, linenum, pos) pointer *at* the opening brace, or
1680 (line, 0, -1) if we never find the matching opening brace. Note
1681 we ignore strings and comments when matching; and the line we
1682 return is the 'cleansed' line at linenum.
1683 """
1684 line = clean_lines.elided[linenum]
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001685 if line[pos] not in ')}]>':
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001686 return (line, 0, -1)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001687
1688 # Check last line
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001689 (start_pos, stack) = FindStartOfExpressionInLine(line, pos, [])
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001690 if start_pos > -1:
1691 return (line, linenum, start_pos)
1692
1693 # Continue scanning backward
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001694 while stack and linenum > 0:
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001695 linenum -= 1
1696 line = clean_lines.elided[linenum]
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001697 (start_pos, stack) = FindStartOfExpressionInLine(line, len(line) - 1, stack)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001698 if start_pos > -1:
1699 return (line, linenum, start_pos)
1700
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001701 # Did not find start of expression before beginning of file, give up
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001702 return (line, 0, -1)
1703
1704
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001705def CheckForCopyright(filename, lines, error):
1706 """Logs an error if no Copyright message appears at the top of the file."""
1707
1708 # We'll say it should occur by line 10. Don't forget there's a
1709 # dummy line at the front.
1710 for line in xrange(1, min(len(lines), 11)):
1711 if re.search(r'Copyright', lines[line], re.I): break
1712 else: # means no copyright line was found
1713 error(filename, 0, 'legal/copyright', 5,
1714 'No copyright message found. '
1715 'You should have a line: "Copyright [year] <Copyright Owner>"')
1716
1717
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001718def GetIndentLevel(line):
1719 """Return the number of leading spaces in line.
1720
1721 Args:
1722 line: A string to check.
1723
1724 Returns:
1725 An integer count of leading spaces, possibly zero.
1726 """
1727 indent = Match(r'^( *)\S', line)
1728 if indent:
1729 return len(indent.group(1))
1730 else:
1731 return 0
1732
1733
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001734def GetHeaderGuardCPPVariable(filename):
1735 """Returns the CPP variable that should be used as a header guard.
1736
1737 Args:
1738 filename: The name of a C++ header file.
1739
1740 Returns:
1741 The CPP variable that should be used as a header guard in the
1742 named file.
1743
1744 """
1745
erg@google.com35589e62010-11-17 18:58:16 +00001746 # Restores original filename in case that cpplint is invoked from Emacs's
1747 # flymake.
1748 filename = re.sub(r'_flymake\.h$', '.h', filename)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001749 filename = re.sub(r'/\.flymake/([^/]*)$', r'/\1', filename)
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001750 # Replace 'c++' with 'cpp'.
1751 filename = filename.replace('C++', 'cpp').replace('c++', 'cpp')
skym@chromium.org3990c412016-02-05 20:55:12 +00001752
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001753 fileinfo = FileInfo(filename)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001754 file_path_from_root = fileinfo.RepositoryName()
1755 if _root:
1756 file_path_from_root = re.sub('^' + _root + os.sep, '', file_path_from_root)
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001757 return re.sub(r'[^a-zA-Z0-9]', '_', file_path_from_root).upper() + '_'
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001758
1759
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001760def CheckForHeaderGuard(filename, clean_lines, error):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001761 """Checks that the file contains a header guard.
1762
erg@google.com6317a9c2009-06-25 00:28:19 +00001763 Logs an error if no #ifndef header guard is present. For other
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001764 headers, checks that the full pathname is used.
1765
1766 Args:
1767 filename: The name of the C++ header file.
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001768 clean_lines: A CleansedLines instance containing the file.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001769 error: The function to call with any errors found.
1770 """
1771
avakulenko@google.com59146752014-08-11 20:20:55 +00001772 # Don't check for header guards if there are error suppression
1773 # comments somewhere in this file.
1774 #
1775 # Because this is silencing a warning for a nonexistent line, we
1776 # only support the very specific NOLINT(build/header_guard) syntax,
1777 # and not the general NOLINT or NOLINT(*) syntax.
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001778 raw_lines = clean_lines.lines_without_raw_strings
1779 for i in raw_lines:
avakulenko@google.com59146752014-08-11 20:20:55 +00001780 if Search(r'//\s*NOLINT\(build/header_guard\)', i):
1781 return
1782
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001783 cppvar = GetHeaderGuardCPPVariable(filename)
1784
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001785 ifndef = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001786 ifndef_linenum = 0
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001787 define = ''
1788 endif = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001789 endif_linenum = 0
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001790 for linenum, line in enumerate(raw_lines):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001791 linesplit = line.split()
1792 if len(linesplit) >= 2:
1793 # find the first occurrence of #ifndef and #define, save arg
1794 if not ifndef and linesplit[0] == '#ifndef':
1795 # set ifndef to the header guard presented on the #ifndef line.
1796 ifndef = linesplit[1]
1797 ifndef_linenum = linenum
1798 if not define and linesplit[0] == '#define':
1799 define = linesplit[1]
1800 # find the last occurrence of #endif, save entire line
1801 if line.startswith('#endif'):
1802 endif = line
1803 endif_linenum = linenum
1804
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001805 if not ifndef or not define or ifndef != define:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001806 error(filename, 0, 'build/header_guard', 5,
1807 'No #ifndef header guard found, suggested CPP variable is: %s' %
1808 cppvar)
1809 return
1810
1811 # The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__
1812 # for backward compatibility.
erg@google.com35589e62010-11-17 18:58:16 +00001813 if ifndef != cppvar:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001814 error_level = 0
1815 if ifndef != cppvar + '_':
1816 error_level = 5
1817
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001818 ParseNolintSuppressions(filename, raw_lines[ifndef_linenum], ifndef_linenum,
erg@google.com35589e62010-11-17 18:58:16 +00001819 error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001820 error(filename, ifndef_linenum, 'build/header_guard', error_level,
1821 '#ifndef header guard has wrong style, please use: %s' % cppvar)
1822
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001823 # Check for "//" comments on endif line.
1824 ParseNolintSuppressions(filename, raw_lines[endif_linenum], endif_linenum,
1825 error)
1826 match = Match(r'#endif\s*//\s*' + cppvar + r'(_)?\b', endif)
1827 if match:
1828 if match.group(1) == '_':
1829 # Issue low severity warning for deprecated double trailing underscore
1830 error(filename, endif_linenum, 'build/header_guard', 0,
1831 '#endif line should be "#endif // %s"' % cppvar)
erg@chromium.orgc452fea2012-01-26 21:10:45 +00001832 return
1833
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001834 # Didn't find the corresponding "//" comment. If this file does not
1835 # contain any "//" comments at all, it could be that the compiler
1836 # only wants "/**/" comments, look for those instead.
1837 no_single_line_comments = True
1838 for i in xrange(1, len(raw_lines) - 1):
1839 line = raw_lines[i]
1840 if Match(r'^(?:(?:\'(?:\.|[^\'])*\')|(?:"(?:\.|[^"])*")|[^\'"])*//', line):
1841 no_single_line_comments = False
1842 break
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001843
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001844 if no_single_line_comments:
1845 match = Match(r'#endif\s*/\*\s*' + cppvar + r'(_)?\s*\*/', endif)
1846 if match:
1847 if match.group(1) == '_':
1848 # Low severity warning for double trailing underscore
1849 error(filename, endif_linenum, 'build/header_guard', 0,
1850 '#endif line should be "#endif /* %s */"' % cppvar)
1851 return
1852
1853 # Didn't find anything
1854 error(filename, endif_linenum, 'build/header_guard', 5,
1855 '#endif line should be "#endif // %s"' % cppvar)
1856
1857
1858def CheckHeaderFileIncluded(filename, include_state, error):
1859 """Logs an error if a .cc file does not include its header."""
1860
1861 # Do not check test files
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00001862 fileinfo = FileInfo(filename)
1863 if Search(_TEST_FILE_SUFFIX, fileinfo.BaseName()):
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001864 return
1865
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00001866 headerfile = filename[0:len(filename) - len(fileinfo.Extension())] + '.h'
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001867 if not os.path.exists(headerfile):
1868 return
1869 headername = FileInfo(headerfile).RepositoryName()
1870 first_include = 0
1871 for section_list in include_state.include_list:
1872 for f in section_list:
1873 if headername in f[0] or f[0] in headername:
1874 return
1875 if not first_include:
1876 first_include = f[1]
1877
1878 error(filename, first_include, 'build/include', 5,
1879 '%s should include its header file %s' % (fileinfo.RepositoryName(),
1880 headername))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001881
1882
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001883def CheckForBadCharacters(filename, lines, error):
1884 """Logs an error for each line containing bad characters.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001885
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001886 Two kinds of bad characters:
1887
1888 1. Unicode replacement characters: These indicate that either the file
1889 contained invalid UTF-8 (likely) or Unicode replacement characters (which
1890 it shouldn't). Note that it's possible for this to throw off line
1891 numbering if the invalid UTF-8 occurred adjacent to a newline.
1892
1893 2. NUL bytes. These are problematic for some tools.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001894
1895 Args:
1896 filename: The name of the current file.
1897 lines: An array of strings, each representing a line of the file.
1898 error: The function to call with any errors found.
1899 """
1900 for linenum, line in enumerate(lines):
1901 if u'\ufffd' in line:
1902 error(filename, linenum, 'readability/utf8', 5,
1903 'Line contains invalid UTF-8 (or Unicode replacement character).')
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001904 if '\0' in line:
1905 error(filename, linenum, 'readability/nul', 5, 'Line contains NUL byte.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001906
1907
1908def CheckForNewlineAtEOF(filename, lines, error):
1909 """Logs an error if there is no newline char at the end of the file.
1910
1911 Args:
1912 filename: The name of the current file.
1913 lines: An array of strings, each representing a line of the file.
1914 error: The function to call with any errors found.
1915 """
1916
1917 # The array lines() was created by adding two newlines to the
1918 # original file (go figure), then splitting on \n.
1919 # To verify that the file ends in \n, we just have to make sure the
1920 # last-but-two element of lines() exists and is empty.
1921 if len(lines) < 3 or lines[-2]:
1922 error(filename, len(lines) - 2, 'whitespace/ending_newline', 5,
1923 'Could not find a newline character at the end of the file.')
1924
1925
1926def CheckForMultilineCommentsAndStrings(filename, clean_lines, linenum, error):
1927 """Logs an error if we see /* ... */ or "..." that extend past one line.
1928
1929 /* ... */ comments are legit inside macros, for one line.
1930 Otherwise, we prefer // comments, so it's ok to warn about the
1931 other. Likewise, it's ok for strings to extend across multiple
1932 lines, as long as a line continuation character (backslash)
1933 terminates each line. Although not currently prohibited by the C++
1934 style guide, it's ugly and unnecessary. We don't do well with either
1935 in this lint program, so we warn about both.
1936
1937 Args:
1938 filename: The name of the current file.
1939 clean_lines: A CleansedLines instance containing the file.
1940 linenum: The number of the line to check.
1941 error: The function to call with any errors found.
1942 """
1943 line = clean_lines.elided[linenum]
1944
1945 # Remove all \\ (escaped backslashes) from the line. They are OK, and the
1946 # second (escaped) slash may trigger later \" detection erroneously.
1947 line = line.replace('\\\\', '')
1948
1949 if line.count('/*') > line.count('*/'):
1950 error(filename, linenum, 'readability/multiline_comment', 5,
1951 'Complex multi-line /*...*/-style comment found. '
1952 'Lint may give bogus warnings. '
1953 'Consider replacing these with //-style comments, '
1954 'with #if 0...#endif, '
1955 'or with more clearly structured multi-line comments.')
1956
1957 if (line.count('"') - line.count('\\"')) % 2:
1958 error(filename, linenum, 'readability/multiline_string', 5,
1959 'Multi-line string ("...") found. This lint script doesn\'t '
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001960 'do well with such strings, and may give bogus warnings. '
1961 'Use C++11 raw strings or concatenation instead.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001962
1963
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001964# (non-threadsafe name, thread-safe alternative, validation pattern)
1965#
1966# The validation pattern is used to eliminate false positives such as:
1967# _rand(); // false positive due to substring match.
1968# ->rand(); // some member function rand().
1969# ACMRandom rand(seed); // some variable named rand.
1970# ISAACRandom rand(); // another variable named rand.
1971#
1972# Basically we require the return value of these functions to be used
1973# in some expression context on the same line by matching on some
1974# operator before the function name. This eliminates constructors and
1975# member function calls.
1976_UNSAFE_FUNC_PREFIX = r'(?:[-+*/=%^&|(<]\s*|>\s+)'
1977_THREADING_LIST = (
1978 ('asctime(', 'asctime_r(', _UNSAFE_FUNC_PREFIX + r'asctime\([^)]+\)'),
1979 ('ctime(', 'ctime_r(', _UNSAFE_FUNC_PREFIX + r'ctime\([^)]+\)'),
1980 ('getgrgid(', 'getgrgid_r(', _UNSAFE_FUNC_PREFIX + r'getgrgid\([^)]+\)'),
1981 ('getgrnam(', 'getgrnam_r(', _UNSAFE_FUNC_PREFIX + r'getgrnam\([^)]+\)'),
1982 ('getlogin(', 'getlogin_r(', _UNSAFE_FUNC_PREFIX + r'getlogin\(\)'),
1983 ('getpwnam(', 'getpwnam_r(', _UNSAFE_FUNC_PREFIX + r'getpwnam\([^)]+\)'),
1984 ('getpwuid(', 'getpwuid_r(', _UNSAFE_FUNC_PREFIX + r'getpwuid\([^)]+\)'),
1985 ('gmtime(', 'gmtime_r(', _UNSAFE_FUNC_PREFIX + r'gmtime\([^)]+\)'),
1986 ('localtime(', 'localtime_r(', _UNSAFE_FUNC_PREFIX + r'localtime\([^)]+\)'),
1987 ('rand(', 'rand_r(', _UNSAFE_FUNC_PREFIX + r'rand\(\)'),
1988 ('strtok(', 'strtok_r(',
1989 _UNSAFE_FUNC_PREFIX + r'strtok\([^)]+\)'),
1990 ('ttyname(', 'ttyname_r(', _UNSAFE_FUNC_PREFIX + r'ttyname\([^)]+\)'),
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001991 )
1992
1993
1994def CheckPosixThreading(filename, clean_lines, linenum, error):
1995 """Checks for calls to thread-unsafe functions.
1996
1997 Much code has been originally written without consideration of
1998 multi-threading. Also, engineers are relying on their old experience;
1999 they have learned posix before threading extensions were added. These
2000 tests guide the engineers to use thread-safe functions (when using
2001 posix directly).
2002
2003 Args:
2004 filename: The name of the current file.
2005 clean_lines: A CleansedLines instance containing the file.
2006 linenum: The number of the line to check.
2007 error: The function to call with any errors found.
2008 """
2009 line = clean_lines.elided[linenum]
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002010 for single_thread_func, multithread_safe_func, pattern in _THREADING_LIST:
2011 # Additional pattern matching check to confirm that this is the
2012 # function we are looking for
2013 if Search(pattern, line):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002014 error(filename, linenum, 'runtime/threadsafe_fn', 2,
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002015 'Consider using ' + multithread_safe_func +
2016 '...) instead of ' + single_thread_func +
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002017 '...) for improved thread safety.')
2018
2019
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002020def CheckVlogArguments(filename, clean_lines, linenum, error):
2021 """Checks that VLOG() is only used for defining a logging level.
2022
2023 For example, VLOG(2) is correct. VLOG(INFO), VLOG(WARNING), VLOG(ERROR), and
2024 VLOG(FATAL) are not.
2025
2026 Args:
2027 filename: The name of the current file.
2028 clean_lines: A CleansedLines instance containing the file.
2029 linenum: The number of the line to check.
2030 error: The function to call with any errors found.
2031 """
2032 line = clean_lines.elided[linenum]
2033 if Search(r'\bVLOG\((INFO|ERROR|WARNING|DFATAL|FATAL)\)', line):
2034 error(filename, linenum, 'runtime/vlog', 5,
2035 'VLOG() should be used with numeric verbosity level. '
2036 'Use LOG() if you want symbolic severity levels.')
2037
erg@google.com26970fa2009-11-17 18:07:32 +00002038# Matches invalid increment: *count++, which moves pointer instead of
erg@google.com6317a9c2009-06-25 00:28:19 +00002039# incrementing a value.
erg@google.com26970fa2009-11-17 18:07:32 +00002040_RE_PATTERN_INVALID_INCREMENT = re.compile(
erg@google.com6317a9c2009-06-25 00:28:19 +00002041 r'^\s*\*\w+(\+\+|--);')
2042
2043
2044def CheckInvalidIncrement(filename, clean_lines, linenum, error):
erg@google.com26970fa2009-11-17 18:07:32 +00002045 """Checks for invalid increment *count++.
erg@google.com6317a9c2009-06-25 00:28:19 +00002046
2047 For example following function:
2048 void increment_counter(int* count) {
2049 *count++;
2050 }
2051 is invalid, because it effectively does count++, moving pointer, and should
2052 be replaced with ++*count, (*count)++ or *count += 1.
2053
2054 Args:
2055 filename: The name of the current file.
2056 clean_lines: A CleansedLines instance containing the file.
2057 linenum: The number of the line to check.
2058 error: The function to call with any errors found.
2059 """
2060 line = clean_lines.elided[linenum]
erg@google.com26970fa2009-11-17 18:07:32 +00002061 if _RE_PATTERN_INVALID_INCREMENT.match(line):
erg@google.com6317a9c2009-06-25 00:28:19 +00002062 error(filename, linenum, 'runtime/invalid_increment', 5,
2063 'Changing pointer instead of value (or unused value of operator*).')
2064
2065
avakulenko@google.com59146752014-08-11 20:20:55 +00002066def IsMacroDefinition(clean_lines, linenum):
2067 if Search(r'^#define', clean_lines[linenum]):
2068 return True
2069
2070 if linenum > 0 and Search(r'\\$', clean_lines[linenum - 1]):
2071 return True
2072
2073 return False
2074
2075
2076def IsForwardClassDeclaration(clean_lines, linenum):
2077 return Match(r'^\s*(\btemplate\b)*.*class\s+\w+;\s*$', clean_lines[linenum])
2078
2079
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002080class _BlockInfo(object):
2081 """Stores information about a generic block of code."""
2082
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002083 def __init__(self, linenum, seen_open_brace):
2084 self.starting_linenum = linenum
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002085 self.seen_open_brace = seen_open_brace
2086 self.open_parentheses = 0
2087 self.inline_asm = _NO_ASM
avakulenko@google.com59146752014-08-11 20:20:55 +00002088 self.check_namespace_indentation = False
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002089
2090 def CheckBegin(self, filename, clean_lines, linenum, error):
2091 """Run checks that applies to text up to the opening brace.
2092
2093 This is mostly for checking the text after the class identifier
2094 and the "{", usually where the base class is specified. For other
2095 blocks, there isn't much to check, so we always pass.
2096
2097 Args:
2098 filename: The name of the current file.
2099 clean_lines: A CleansedLines instance containing the file.
2100 linenum: The number of the line to check.
2101 error: The function to call with any errors found.
2102 """
2103 pass
2104
2105 def CheckEnd(self, filename, clean_lines, linenum, error):
2106 """Run checks that applies to text after the closing brace.
2107
2108 This is mostly used for checking end of namespace comments.
2109
2110 Args:
2111 filename: The name of the current file.
2112 clean_lines: A CleansedLines instance containing the file.
2113 linenum: The number of the line to check.
2114 error: The function to call with any errors found.
2115 """
2116 pass
2117
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002118 def IsBlockInfo(self):
2119 """Returns true if this block is a _BlockInfo.
2120
2121 This is convenient for verifying that an object is an instance of
2122 a _BlockInfo, but not an instance of any of the derived classes.
2123
2124 Returns:
2125 True for this class, False for derived classes.
2126 """
2127 return self.__class__ == _BlockInfo
2128
2129
2130class _ExternCInfo(_BlockInfo):
2131 """Stores information about an 'extern "C"' block."""
2132
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002133 def __init__(self, linenum):
2134 _BlockInfo.__init__(self, linenum, True)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002135
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002136
2137class _ClassInfo(_BlockInfo):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002138 """Stores information about a class."""
2139
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002140 def __init__(self, name, class_or_struct, clean_lines, linenum):
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002141 _BlockInfo.__init__(self, linenum, False)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002142 self.name = name
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002143 self.is_derived = False
avakulenko@google.com59146752014-08-11 20:20:55 +00002144 self.check_namespace_indentation = True
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002145 if class_or_struct == 'struct':
2146 self.access = 'public'
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002147 self.is_struct = True
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002148 else:
2149 self.access = 'private'
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002150 self.is_struct = False
2151
2152 # Remember initial indentation level for this class. Using raw_lines here
2153 # instead of elided to account for leading comments.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002154 self.class_indent = GetIndentLevel(clean_lines.raw_lines[linenum])
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002155
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00002156 # Try to find the end of the class. This will be confused by things like:
2157 # class A {
2158 # } *x = { ...
2159 #
2160 # But it's still good enough for CheckSectionSpacing.
2161 self.last_line = 0
2162 depth = 0
2163 for i in range(linenum, clean_lines.NumLines()):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002164 line = clean_lines.elided[i]
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00002165 depth += line.count('{') - line.count('}')
2166 if not depth:
2167 self.last_line = i
2168 break
2169
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002170 def CheckBegin(self, filename, clean_lines, linenum, error):
2171 # Look for a bare ':'
2172 if Search('(^|[^:]):($|[^:])', clean_lines.elided[linenum]):
2173 self.is_derived = True
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002174
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002175 def CheckEnd(self, filename, clean_lines, linenum, error):
avakulenko@google.com255f2be2014-12-05 22:19:55 +00002176 # If there is a DISALLOW macro, it should appear near the end of
2177 # the class.
2178 seen_last_thing_in_class = False
2179 for i in xrange(linenum - 1, self.starting_linenum, -1):
2180 match = Search(
2181 r'\b(DISALLOW_COPY_AND_ASSIGN|DISALLOW_IMPLICIT_CONSTRUCTORS)\(' +
2182 self.name + r'\)',
2183 clean_lines.elided[i])
2184 if match:
2185 if seen_last_thing_in_class:
2186 error(filename, i, 'readability/constructors', 3,
2187 match.group(1) + ' should be the last thing in the class')
2188 break
2189
2190 if not Match(r'^\s*$', clean_lines.elided[i]):
2191 seen_last_thing_in_class = True
2192
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002193 # Check that closing brace is aligned with beginning of the class.
2194 # Only do this if the closing brace is indented by only whitespaces.
2195 # This means we will not check single-line class definitions.
2196 indent = Match(r'^( *)\}', clean_lines.elided[linenum])
2197 if indent and len(indent.group(1)) != self.class_indent:
2198 if self.is_struct:
2199 parent = 'struct ' + self.name
2200 else:
2201 parent = 'class ' + self.name
2202 error(filename, linenum, 'whitespace/indent', 3,
2203 'Closing brace should be aligned with beginning of %s' % parent)
2204
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002205
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002206class _NamespaceInfo(_BlockInfo):
2207 """Stores information about a namespace."""
2208
2209 def __init__(self, name, linenum):
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002210 _BlockInfo.__init__(self, linenum, False)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002211 self.name = name or ''
avakulenko@google.com59146752014-08-11 20:20:55 +00002212 self.check_namespace_indentation = True
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002213
2214 def CheckEnd(self, filename, clean_lines, linenum, error):
2215 """Check end of namespace comments."""
2216 line = clean_lines.raw_lines[linenum]
2217
2218 # Check how many lines is enclosed in this namespace. Don't issue
2219 # warning for missing namespace comments if there aren't enough
2220 # lines. However, do apply checks if there is already an end of
2221 # namespace comment and it's incorrect.
2222 #
2223 # TODO(unknown): We always want to check end of namespace comments
2224 # if a namespace is large, but sometimes we also want to apply the
2225 # check if a short namespace contained nontrivial things (something
2226 # other than forward declarations). There is currently no logic on
2227 # deciding what these nontrivial things are, so this check is
2228 # triggered by namespace size only, which works most of the time.
2229 if (linenum - self.starting_linenum < 10
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002230 and not Match(r'^\s*};*\s*(//|/\*).*\bnamespace\b', line)):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002231 return
2232
2233 # Look for matching comment at end of namespace.
2234 #
2235 # Note that we accept C style "/* */" comments for terminating
2236 # namespaces, so that code that terminate namespaces inside
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002237 # preprocessor macros can be cpplint clean.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002238 #
2239 # We also accept stuff like "// end of namespace <name>." with the
2240 # period at the end.
2241 #
2242 # Besides these, we don't accept anything else, otherwise we might
2243 # get false negatives when existing comment is a substring of the
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002244 # expected namespace.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002245 if self.name:
2246 # Named namespace
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002247 if not Match((r'^\s*};*\s*(//|/\*).*\bnamespace\s+' +
2248 re.escape(self.name) + r'[\*/\.\\\s]*$'),
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002249 line):
2250 error(filename, linenum, 'readability/namespace', 5,
2251 'Namespace should be terminated with "// namespace %s"' %
2252 self.name)
2253 else:
2254 # Anonymous namespace
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002255 if not Match(r'^\s*};*\s*(//|/\*).*\bnamespace[\*/\.\\\s]*$', line):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002256 # If "// namespace anonymous" or "// anonymous namespace (more text)",
2257 # mention "// anonymous namespace" as an acceptable form
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002258 if Match(r'^\s*}.*\b(namespace anonymous|anonymous namespace)\b', line):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002259 error(filename, linenum, 'readability/namespace', 5,
2260 'Anonymous namespace should be terminated with "// namespace"'
2261 ' or "// anonymous namespace"')
2262 else:
2263 error(filename, linenum, 'readability/namespace', 5,
2264 'Anonymous namespace should be terminated with "// namespace"')
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002265
2266
2267class _PreprocessorInfo(object):
2268 """Stores checkpoints of nesting stacks when #if/#else is seen."""
2269
2270 def __init__(self, stack_before_if):
2271 # The entire nesting stack before #if
2272 self.stack_before_if = stack_before_if
2273
2274 # The entire nesting stack up to #else
2275 self.stack_before_else = []
2276
2277 # Whether we have already seen #else or #elif
2278 self.seen_else = False
2279
2280
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002281class NestingState(object):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002282 """Holds states related to parsing braces."""
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002283
2284 def __init__(self):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002285 # Stack for tracking all braces. An object is pushed whenever we
2286 # see a "{", and popped when we see a "}". Only 3 types of
2287 # objects are possible:
2288 # - _ClassInfo: a class or struct.
2289 # - _NamespaceInfo: a namespace.
2290 # - _BlockInfo: some other type of block.
2291 self.stack = []
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002292
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002293 # Top of the previous stack before each Update().
2294 #
2295 # Because the nesting_stack is updated at the end of each line, we
2296 # had to do some convoluted checks to find out what is the current
2297 # scope at the beginning of the line. This check is simplified by
2298 # saving the previous top of nesting stack.
2299 #
2300 # We could save the full stack, but we only need the top. Copying
2301 # the full nesting stack would slow down cpplint by ~10%.
2302 self.previous_stack_top = []
2303
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002304 # Stack of _PreprocessorInfo objects.
2305 self.pp_stack = []
2306
2307 def SeenOpenBrace(self):
2308 """Check if we have seen the opening brace for the innermost block.
2309
2310 Returns:
2311 True if we have seen the opening brace, False if the innermost
2312 block is still expecting an opening brace.
2313 """
2314 return (not self.stack) or self.stack[-1].seen_open_brace
2315
2316 def InNamespaceBody(self):
2317 """Check if we are currently one level inside a namespace body.
2318
2319 Returns:
2320 True if top of the stack is a namespace block, False otherwise.
2321 """
2322 return self.stack and isinstance(self.stack[-1], _NamespaceInfo)
2323
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002324 def InExternC(self):
2325 """Check if we are currently one level inside an 'extern "C"' block.
2326
2327 Returns:
2328 True if top of the stack is an extern block, False otherwise.
2329 """
2330 return self.stack and isinstance(self.stack[-1], _ExternCInfo)
2331
2332 def InClassDeclaration(self):
2333 """Check if we are currently one level inside a class or struct declaration.
2334
2335 Returns:
2336 True if top of the stack is a class/struct, False otherwise.
2337 """
2338 return self.stack and isinstance(self.stack[-1], _ClassInfo)
2339
2340 def InAsmBlock(self):
2341 """Check if we are currently one level inside an inline ASM block.
2342
2343 Returns:
2344 True if the top of the stack is a block containing inline ASM.
2345 """
2346 return self.stack and self.stack[-1].inline_asm != _NO_ASM
2347
2348 def InTemplateArgumentList(self, clean_lines, linenum, pos):
2349 """Check if current position is inside template argument list.
2350
2351 Args:
2352 clean_lines: A CleansedLines instance containing the file.
2353 linenum: The number of the line to check.
2354 pos: position just after the suspected template argument.
2355 Returns:
2356 True if (linenum, pos) is inside template arguments.
2357 """
2358 while linenum < clean_lines.NumLines():
2359 # Find the earliest character that might indicate a template argument
2360 line = clean_lines.elided[linenum]
2361 match = Match(r'^[^{};=\[\]\.<>]*(.)', line[pos:])
2362 if not match:
2363 linenum += 1
2364 pos = 0
2365 continue
2366 token = match.group(1)
2367 pos += len(match.group(0))
2368
2369 # These things do not look like template argument list:
2370 # class Suspect {
2371 # class Suspect x; }
2372 if token in ('{', '}', ';'): return False
2373
2374 # These things look like template argument list:
2375 # template <class Suspect>
2376 # template <class Suspect = default_value>
2377 # template <class Suspect[]>
2378 # template <class Suspect...>
2379 if token in ('>', '=', '[', ']', '.'): return True
2380
2381 # Check if token is an unmatched '<'.
2382 # If not, move on to the next character.
2383 if token != '<':
2384 pos += 1
2385 if pos >= len(line):
2386 linenum += 1
2387 pos = 0
2388 continue
2389
2390 # We can't be sure if we just find a single '<', and need to
2391 # find the matching '>'.
2392 (_, end_line, end_pos) = CloseExpression(clean_lines, linenum, pos - 1)
2393 if end_pos < 0:
2394 # Not sure if template argument list or syntax error in file
2395 return False
2396 linenum = end_line
2397 pos = end_pos
2398 return False
2399
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002400 def UpdatePreprocessor(self, line):
2401 """Update preprocessor stack.
2402
2403 We need to handle preprocessors due to classes like this:
2404 #ifdef SWIG
2405 struct ResultDetailsPageElementExtensionPoint {
2406 #else
2407 struct ResultDetailsPageElementExtensionPoint : public Extension {
2408 #endif
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002409
2410 We make the following assumptions (good enough for most files):
2411 - Preprocessor condition evaluates to true from #if up to first
2412 #else/#elif/#endif.
2413
2414 - Preprocessor condition evaluates to false from #else/#elif up
2415 to #endif. We still perform lint checks on these lines, but
2416 these do not affect nesting stack.
2417
2418 Args:
2419 line: current line to check.
2420 """
2421 if Match(r'^\s*#\s*(if|ifdef|ifndef)\b', line):
2422 # Beginning of #if block, save the nesting stack here. The saved
2423 # stack will allow us to restore the parsing state in the #else case.
2424 self.pp_stack.append(_PreprocessorInfo(copy.deepcopy(self.stack)))
2425 elif Match(r'^\s*#\s*(else|elif)\b', line):
2426 # Beginning of #else block
2427 if self.pp_stack:
2428 if not self.pp_stack[-1].seen_else:
2429 # This is the first #else or #elif block. Remember the
2430 # whole nesting stack up to this point. This is what we
2431 # keep after the #endif.
2432 self.pp_stack[-1].seen_else = True
2433 self.pp_stack[-1].stack_before_else = copy.deepcopy(self.stack)
2434
2435 # Restore the stack to how it was before the #if
2436 self.stack = copy.deepcopy(self.pp_stack[-1].stack_before_if)
2437 else:
2438 # TODO(unknown): unexpected #else, issue warning?
2439 pass
2440 elif Match(r'^\s*#\s*endif\b', line):
2441 # End of #if or #else blocks.
2442 if self.pp_stack:
2443 # If we saw an #else, we will need to restore the nesting
2444 # stack to its former state before the #else, otherwise we
2445 # will just continue from where we left off.
2446 if self.pp_stack[-1].seen_else:
2447 # Here we can just use a shallow copy since we are the last
2448 # reference to it.
2449 self.stack = self.pp_stack[-1].stack_before_else
2450 # Drop the corresponding #if
2451 self.pp_stack.pop()
2452 else:
2453 # TODO(unknown): unexpected #endif, issue warning?
2454 pass
2455
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002456 # TODO(unknown): Update() is too long, but we will refactor later.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002457 def Update(self, filename, clean_lines, linenum, error):
2458 """Update nesting state with current line.
2459
2460 Args:
2461 filename: The name of the current file.
2462 clean_lines: A CleansedLines instance containing the file.
2463 linenum: The number of the line to check.
2464 error: The function to call with any errors found.
2465 """
2466 line = clean_lines.elided[linenum]
2467
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002468 # Remember top of the previous nesting stack.
2469 #
2470 # The stack is always pushed/popped and not modified in place, so
2471 # we can just do a shallow copy instead of copy.deepcopy. Using
2472 # deepcopy would slow down cpplint by ~28%.
2473 if self.stack:
2474 self.previous_stack_top = self.stack[-1]
2475 else:
2476 self.previous_stack_top = None
2477
2478 # Update pp_stack
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002479 self.UpdatePreprocessor(line)
2480
2481 # Count parentheses. This is to avoid adding struct arguments to
2482 # the nesting stack.
2483 if self.stack:
2484 inner_block = self.stack[-1]
2485 depth_change = line.count('(') - line.count(')')
2486 inner_block.open_parentheses += depth_change
2487
2488 # Also check if we are starting or ending an inline assembly block.
2489 if inner_block.inline_asm in (_NO_ASM, _END_ASM):
2490 if (depth_change != 0 and
2491 inner_block.open_parentheses == 1 and
2492 _MATCH_ASM.match(line)):
2493 # Enter assembly block
2494 inner_block.inline_asm = _INSIDE_ASM
2495 else:
2496 # Not entering assembly block. If previous line was _END_ASM,
2497 # we will now shift to _NO_ASM state.
2498 inner_block.inline_asm = _NO_ASM
2499 elif (inner_block.inline_asm == _INSIDE_ASM and
2500 inner_block.open_parentheses == 0):
2501 # Exit assembly block
2502 inner_block.inline_asm = _END_ASM
2503
2504 # Consume namespace declaration at the beginning of the line. Do
2505 # this in a loop so that we catch same line declarations like this:
2506 # namespace proto2 { namespace bridge { class MessageSet; } }
2507 while True:
2508 # Match start of namespace. The "\b\s*" below catches namespace
2509 # declarations even if it weren't followed by a whitespace, this
2510 # is so that we don't confuse our namespace checker. The
2511 # missing spaces will be flagged by CheckSpacing.
2512 namespace_decl_match = Match(r'^\s*namespace\b\s*([:\w]+)?(.*)$', line)
2513 if not namespace_decl_match:
2514 break
2515
2516 new_namespace = _NamespaceInfo(namespace_decl_match.group(1), linenum)
2517 self.stack.append(new_namespace)
2518
2519 line = namespace_decl_match.group(2)
2520 if line.find('{') != -1:
2521 new_namespace.seen_open_brace = True
2522 line = line[line.find('{') + 1:]
2523
2524 # Look for a class declaration in whatever is left of the line
2525 # after parsing namespaces. The regexp accounts for decorated classes
2526 # such as in:
2527 # class LOCKABLE API Object {
2528 # };
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002529 class_decl_match = Match(
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002530 r'^(\s*(?:template\s*<[\w\s<>,:]*>\s*)?'
2531 r'(class|struct)\s+(?:[A-Z_]+\s+)*(\w+(?:::\w+)*))'
2532 r'(.*)$', line)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002533 if (class_decl_match and
2534 (not self.stack or self.stack[-1].open_parentheses == 0)):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002535 # We do not want to accept classes that are actually template arguments:
2536 # template <class Ignore1,
2537 # class Ignore2 = Default<Args>,
2538 # template <Args> class Ignore3>
2539 # void Function() {};
2540 #
2541 # To avoid template argument cases, we scan forward and look for
2542 # an unmatched '>'. If we see one, assume we are inside a
2543 # template argument list.
2544 end_declaration = len(class_decl_match.group(1))
2545 if not self.InTemplateArgumentList(clean_lines, linenum, end_declaration):
2546 self.stack.append(_ClassInfo(
2547 class_decl_match.group(3), class_decl_match.group(2),
2548 clean_lines, linenum))
2549 line = class_decl_match.group(4)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002550
2551 # If we have not yet seen the opening brace for the innermost block,
2552 # run checks here.
2553 if not self.SeenOpenBrace():
2554 self.stack[-1].CheckBegin(filename, clean_lines, linenum, error)
2555
2556 # Update access control if we are inside a class/struct
2557 if self.stack and isinstance(self.stack[-1], _ClassInfo):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002558 classinfo = self.stack[-1]
2559 access_match = Match(
2560 r'^(.*)\b(public|private|protected|signals)(\s+(?:slots\s*)?)?'
2561 r':(?:[^:]|$)',
2562 line)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002563 if access_match:
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002564 classinfo.access = access_match.group(2)
2565
2566 # Check that access keywords are indented +1 space. Skip this
2567 # check if the keywords are not preceded by whitespaces.
2568 indent = access_match.group(1)
2569 if (len(indent) != classinfo.class_indent + 1 and
2570 Match(r'^\s*$', indent)):
2571 if classinfo.is_struct:
2572 parent = 'struct ' + classinfo.name
2573 else:
2574 parent = 'class ' + classinfo.name
2575 slots = ''
2576 if access_match.group(3):
2577 slots = access_match.group(3)
2578 error(filename, linenum, 'whitespace/indent', 3,
2579 '%s%s: should be indented +1 space inside %s' % (
2580 access_match.group(2), slots, parent))
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002581
2582 # Consume braces or semicolons from what's left of the line
2583 while True:
2584 # Match first brace, semicolon, or closed parenthesis.
2585 matched = Match(r'^[^{;)}]*([{;)}])(.*)$', line)
2586 if not matched:
2587 break
2588
2589 token = matched.group(1)
2590 if token == '{':
2591 # If namespace or class hasn't seen a opening brace yet, mark
2592 # namespace/class head as complete. Push a new block onto the
2593 # stack otherwise.
2594 if not self.SeenOpenBrace():
2595 self.stack[-1].seen_open_brace = True
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002596 elif Match(r'^extern\s*"[^"]*"\s*\{', line):
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002597 self.stack.append(_ExternCInfo(linenum))
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002598 else:
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002599 self.stack.append(_BlockInfo(linenum, True))
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002600 if _MATCH_ASM.match(line):
2601 self.stack[-1].inline_asm = _BLOCK_ASM
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002602
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002603 elif token == ';' or token == ')':
2604 # If we haven't seen an opening brace yet, but we already saw
2605 # a semicolon, this is probably a forward declaration. Pop
2606 # the stack for these.
2607 #
2608 # Similarly, if we haven't seen an opening brace yet, but we
2609 # already saw a closing parenthesis, then these are probably
2610 # function arguments with extra "class" or "struct" keywords.
2611 # Also pop these stack for these.
2612 if not self.SeenOpenBrace():
2613 self.stack.pop()
2614 else: # token == '}'
2615 # Perform end of block checks and pop the stack.
2616 if self.stack:
2617 self.stack[-1].CheckEnd(filename, clean_lines, linenum, error)
2618 self.stack.pop()
2619 line = matched.group(2)
2620
2621 def InnermostClass(self):
2622 """Get class info on the top of the stack.
2623
2624 Returns:
2625 A _ClassInfo object if we are inside a class, or None otherwise.
2626 """
2627 for i in range(len(self.stack), 0, -1):
2628 classinfo = self.stack[i - 1]
2629 if isinstance(classinfo, _ClassInfo):
2630 return classinfo
2631 return None
2632
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002633 def CheckCompletedBlocks(self, filename, error):
2634 """Checks that all classes and namespaces have been completely parsed.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002635
2636 Call this when all lines in a file have been processed.
2637 Args:
2638 filename: The name of the current file.
2639 error: The function to call with any errors found.
2640 """
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002641 # Note: This test can result in false positives if #ifdef constructs
2642 # get in the way of brace matching. See the testBuildClass test in
2643 # cpplint_unittest.py for an example of this.
2644 for obj in self.stack:
2645 if isinstance(obj, _ClassInfo):
2646 error(filename, obj.starting_linenum, 'build/class', 5,
2647 'Failed to find complete declaration of class %s' %
2648 obj.name)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002649 elif isinstance(obj, _NamespaceInfo):
2650 error(filename, obj.starting_linenum, 'build/namespaces', 5,
2651 'Failed to find complete declaration of namespace %s' %
2652 obj.name)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002653
2654
2655def CheckForNonStandardConstructs(filename, clean_lines, linenum,
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002656 nesting_state, error):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002657 r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002658
2659 Complain about several constructs which gcc-2 accepts, but which are
2660 not standard C++. Warning about these in lint is one way to ease the
2661 transition to new compilers.
2662 - put storage class first (e.g. "static const" instead of "const static").
2663 - "%lld" instead of %qd" in printf-type functions.
2664 - "%1$d" is non-standard in printf-type functions.
2665 - "\%" is an undefined character escape sequence.
2666 - text after #endif is not allowed.
2667 - invalid inner-style forward declaration.
2668 - >? and <? operators, and their >?= and <?= cousins.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002669
erg@google.com26970fa2009-11-17 18:07:32 +00002670 Additionally, check for constructor/destructor style violations and reference
2671 members, as it is very convenient to do so while checking for
2672 gcc-2 compliance.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002673
2674 Args:
2675 filename: The name of the current file.
2676 clean_lines: A CleansedLines instance containing the file.
2677 linenum: The number of the line to check.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002678 nesting_state: A NestingState instance which maintains information about
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002679 the current stack of nested blocks being parsed.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002680 error: A callable to which errors are reported, which takes 4 arguments:
2681 filename, line number, error level, and message
2682 """
2683
2684 # Remove comments from the line, but leave in strings for now.
2685 line = clean_lines.lines[linenum]
2686
2687 if Search(r'printf\s*\(.*".*%[-+ ]?\d*q', line):
2688 error(filename, linenum, 'runtime/printf_format', 3,
2689 '%q in format strings is deprecated. Use %ll instead.')
2690
2691 if Search(r'printf\s*\(.*".*%\d+\$', line):
2692 error(filename, linenum, 'runtime/printf_format', 2,
2693 '%N$ formats are unconventional. Try rewriting to avoid them.')
2694
2695 # Remove escaped backslashes before looking for undefined escapes.
2696 line = line.replace('\\\\', '')
2697
2698 if Search(r'("|\').*\\(%|\[|\(|{)', line):
2699 error(filename, linenum, 'build/printf_format', 3,
2700 '%, [, (, and { are undefined character escapes. Unescape them.')
2701
2702 # For the rest, work with both comments and strings removed.
2703 line = clean_lines.elided[linenum]
2704
2705 if Search(r'\b(const|volatile|void|char|short|int|long'
2706 r'|float|double|signed|unsigned'
2707 r'|schar|u?int8|u?int16|u?int32|u?int64)'
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002708 r'\s+(register|static|extern|typedef)\b',
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002709 line):
2710 error(filename, linenum, 'build/storage_class', 5,
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002711 'Storage-class specifier (static, extern, typedef, etc) should be '
2712 'at the beginning of the declaration.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002713
2714 if Match(r'\s*#\s*endif\s*[^/\s]+', line):
2715 error(filename, linenum, 'build/endif_comment', 5,
2716 'Uncommented text after #endif is non-standard. Use a comment.')
2717
2718 if Match(r'\s*class\s+(\w+\s*::\s*)+\w+\s*;', line):
2719 error(filename, linenum, 'build/forward_decl', 5,
2720 'Inner-style forward declarations are invalid. Remove this line.')
2721
2722 if Search(r'(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?',
2723 line):
2724 error(filename, linenum, 'build/deprecated', 3,
2725 '>? and <? (max and min) operators are non-standard and deprecated.')
2726
erg@google.com26970fa2009-11-17 18:07:32 +00002727 if Search(r'^\s*const\s*string\s*&\s*\w+\s*;', line):
2728 # TODO(unknown): Could it be expanded safely to arbitrary references,
2729 # without triggering too many false positives? The first
2730 # attempt triggered 5 warnings for mostly benign code in the regtest, hence
2731 # the restriction.
2732 # Here's the original regexp, for the reference:
2733 # type_name = r'\w+((\s*::\s*\w+)|(\s*<\s*\w+?\s*>))?'
2734 # r'\s*const\s*' + type_name + '\s*&\s*\w+\s*;'
2735 error(filename, linenum, 'runtime/member_string_references', 2,
2736 'const string& members are dangerous. It is much better to use '
2737 'alternatives, such as pointers or simple constants.')
2738
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002739 # Everything else in this function operates on class declarations.
2740 # Return early if the top of the nesting stack is not a class, or if
2741 # the class head is not completed yet.
2742 classinfo = nesting_state.InnermostClass()
2743 if not classinfo or not classinfo.seen_open_brace:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002744 return
2745
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002746 # The class may have been declared with namespace or classname qualifiers.
2747 # The constructor and destructor will not have those qualifiers.
2748 base_classname = classinfo.name.split('::')[-1]
2749
2750 # Look for single-argument constructors that aren't marked explicit.
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002751 # Technically a valid construct, but against style.
avakulenko@google.com59146752014-08-11 20:20:55 +00002752 explicit_constructor_match = Match(
2753 r'\s+(?:inline\s+)?(explicit\s+)?(?:inline\s+)?%s\s*'
2754 r'\(((?:[^()]|\([^()]*\))*)\)'
2755 % re.escape(base_classname),
2756 line)
2757
2758 if explicit_constructor_match:
2759 is_marked_explicit = explicit_constructor_match.group(1)
2760
2761 if not explicit_constructor_match.group(2):
2762 constructor_args = []
2763 else:
2764 constructor_args = explicit_constructor_match.group(2).split(',')
2765
2766 # collapse arguments so that commas in template parameter lists and function
2767 # argument parameter lists don't split arguments in two
2768 i = 0
2769 while i < len(constructor_args):
2770 constructor_arg = constructor_args[i]
2771 while (constructor_arg.count('<') > constructor_arg.count('>') or
2772 constructor_arg.count('(') > constructor_arg.count(')')):
2773 constructor_arg += ',' + constructor_args[i + 1]
2774 del constructor_args[i + 1]
2775 constructor_args[i] = constructor_arg
2776 i += 1
2777
2778 defaulted_args = [arg for arg in constructor_args if '=' in arg]
2779 noarg_constructor = (not constructor_args or # empty arg list
2780 # 'void' arg specifier
2781 (len(constructor_args) == 1 and
2782 constructor_args[0].strip() == 'void'))
2783 onearg_constructor = ((len(constructor_args) == 1 and # exactly one arg
2784 not noarg_constructor) or
2785 # all but at most one arg defaulted
2786 (len(constructor_args) >= 1 and
2787 not noarg_constructor and
2788 len(defaulted_args) >= len(constructor_args) - 1))
2789 initializer_list_constructor = bool(
2790 onearg_constructor and
2791 Search(r'\bstd\s*::\s*initializer_list\b', constructor_args[0]))
2792 copy_constructor = bool(
2793 onearg_constructor and
2794 Match(r'(const\s+)?%s(\s*<[^>]*>)?(\s+const)?\s*(?:<\w+>\s*)?&'
2795 % re.escape(base_classname), constructor_args[0].strip()))
2796
2797 if (not is_marked_explicit and
2798 onearg_constructor and
2799 not initializer_list_constructor and
2800 not copy_constructor):
2801 if defaulted_args:
2802 error(filename, linenum, 'runtime/explicit', 5,
2803 'Constructors callable with one argument '
2804 'should be marked explicit.')
2805 else:
2806 error(filename, linenum, 'runtime/explicit', 5,
2807 'Single-parameter constructors should be marked explicit.')
2808 elif is_marked_explicit and not onearg_constructor:
2809 if noarg_constructor:
2810 error(filename, linenum, 'runtime/explicit', 5,
2811 'Zero-parameter constructors should not be marked explicit.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002812
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002813
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002814def CheckSpacingForFunctionCall(filename, clean_lines, linenum, error):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002815 """Checks for the correctness of various spacing around function calls.
2816
2817 Args:
2818 filename: The name of the current file.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002819 clean_lines: A CleansedLines instance containing the file.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002820 linenum: The number of the line to check.
2821 error: The function to call with any errors found.
2822 """
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002823 line = clean_lines.elided[linenum]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002824
2825 # Since function calls often occur inside if/for/while/switch
2826 # expressions - which have their own, more liberal conventions - we
2827 # first see if we should be looking inside such an expression for a
2828 # function call, to which we can apply more strict standards.
2829 fncall = line # if there's no control flow construct, look at whole line
2830 for pattern in (r'\bif\s*\((.*)\)\s*{',
2831 r'\bfor\s*\((.*)\)\s*{',
2832 r'\bwhile\s*\((.*)\)\s*[{;]',
2833 r'\bswitch\s*\((.*)\)\s*{'):
2834 match = Search(pattern, line)
2835 if match:
2836 fncall = match.group(1) # look inside the parens for function calls
2837 break
2838
2839 # Except in if/for/while/switch, there should never be space
2840 # immediately inside parens (eg "f( 3, 4 )"). We make an exception
2841 # for nested parens ( (a+b) + c ). Likewise, there should never be
2842 # a space before a ( when it's a function argument. I assume it's a
2843 # function argument when the char before the whitespace is legal in
2844 # a function name (alnum + _) and we're not starting a macro. Also ignore
2845 # pointers and references to arrays and functions coz they're too tricky:
2846 # we use a very simple way to recognize these:
2847 # " (something)(maybe-something)" or
2848 # " (something)(maybe-something," or
2849 # " (something)[something]"
2850 # Note that we assume the contents of [] to be short enough that
2851 # they'll never need to wrap.
2852 if ( # Ignore control structures.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002853 not Search(r'\b(if|for|while|switch|return|new|delete|catch|sizeof)\b',
2854 fncall) and
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002855 # Ignore pointers/references to functions.
2856 not Search(r' \([^)]+\)\([^)]*(\)|,$)', fncall) and
2857 # Ignore pointers/references to arrays.
2858 not Search(r' \([^)]+\)\[[^\]]+\]', fncall)):
erg@google.com6317a9c2009-06-25 00:28:19 +00002859 if Search(r'\w\s*\(\s(?!\s*\\$)', fncall): # a ( used for a fn call
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002860 error(filename, linenum, 'whitespace/parens', 4,
2861 'Extra space after ( in function call')
erg@google.com6317a9c2009-06-25 00:28:19 +00002862 elif Search(r'\(\s+(?!(\s*\\)|\()', fncall):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002863 error(filename, linenum, 'whitespace/parens', 2,
2864 'Extra space after (')
2865 if (Search(r'\w\s+\(', fncall) and
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002866 not Search(r'_{0,2}asm_{0,2}\s+_{0,2}volatile_{0,2}\s+\(', fncall) and
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002867 not Search(r'#\s*define|typedef|using\s+\w+\s*=', fncall) and
avakulenko@google.com255f2be2014-12-05 22:19:55 +00002868 not Search(r'\w\s+\((\w+::)*\*\w+\)\(', fncall) and
2869 not Search(r'\bcase\s+\(', fncall)):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002870 # TODO(unknown): Space after an operator function seem to be a common
2871 # error, silence those for now by restricting them to highest verbosity.
2872 if Search(r'\boperator_*\b', line):
2873 error(filename, linenum, 'whitespace/parens', 0,
2874 'Extra space before ( in function call')
2875 else:
2876 error(filename, linenum, 'whitespace/parens', 4,
2877 'Extra space before ( in function call')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002878 # If the ) is followed only by a newline or a { + newline, assume it's
2879 # part of a control statement (if/while/etc), and don't complain
2880 if Search(r'[^)]\s+\)\s*[^{\s]', fncall):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00002881 # If the closing parenthesis is preceded by only whitespaces,
2882 # try to give a more descriptive error message.
2883 if Search(r'^\s+\)', fncall):
2884 error(filename, linenum, 'whitespace/parens', 2,
2885 'Closing ) should be moved to the previous line')
2886 else:
2887 error(filename, linenum, 'whitespace/parens', 2,
2888 'Extra space before )')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002889
2890
2891def IsBlankLine(line):
2892 """Returns true if the given line is blank.
2893
2894 We consider a line to be blank if the line is empty or consists of
2895 only white spaces.
2896
2897 Args:
2898 line: A line of a string.
2899
2900 Returns:
2901 True, if the given line is blank.
2902 """
2903 return not line or line.isspace()
2904
2905
avakulenko@google.com59146752014-08-11 20:20:55 +00002906def CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line,
2907 error):
2908 is_namespace_indent_item = (
2909 len(nesting_state.stack) > 1 and
2910 nesting_state.stack[-1].check_namespace_indentation and
2911 isinstance(nesting_state.previous_stack_top, _NamespaceInfo) and
2912 nesting_state.previous_stack_top == nesting_state.stack[-2])
2913
2914 if ShouldCheckNamespaceIndentation(nesting_state, is_namespace_indent_item,
2915 clean_lines.elided, line):
2916 CheckItemIndentationInNamespace(filename, clean_lines.elided,
2917 line, error)
2918
2919
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002920def CheckForFunctionLengths(filename, clean_lines, linenum,
2921 function_state, error):
2922 """Reports for long function bodies.
2923
2924 For an overview why this is done, see:
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002925 https://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002926
2927 Uses a simplistic algorithm assuming other style guidelines
2928 (especially spacing) are followed.
2929 Only checks unindented functions, so class members are unchecked.
2930 Trivial bodies are unchecked, so constructors with huge initializer lists
2931 may be missed.
2932 Blank/comment lines are not counted so as to avoid encouraging the removal
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00002933 of vertical space and comments just to get through a lint check.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002934 NOLINT *on the last line of a function* disables this check.
2935
2936 Args:
2937 filename: The name of the current file.
2938 clean_lines: A CleansedLines instance containing the file.
2939 linenum: The number of the line to check.
2940 function_state: Current function name and lines in body so far.
2941 error: The function to call with any errors found.
2942 """
2943 lines = clean_lines.lines
2944 line = lines[linenum]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002945 joined_line = ''
2946
2947 starting_func = False
erg@google.com6317a9c2009-06-25 00:28:19 +00002948 regexp = r'(\w(\w|::|\*|\&|\s)*)\(' # decls * & space::name( ...
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002949 match_result = Match(regexp, line)
2950 if match_result:
2951 # If the name is all caps and underscores, figure it's a macro and
2952 # ignore it, unless it's TEST or TEST_F.
2953 function_name = match_result.group(1).split()[-1]
2954 if function_name == 'TEST' or function_name == 'TEST_F' or (
2955 not Match(r'[A-Z_]+$', function_name)):
2956 starting_func = True
2957
2958 if starting_func:
2959 body_found = False
erg@google.com6317a9c2009-06-25 00:28:19 +00002960 for start_linenum in xrange(linenum, clean_lines.NumLines()):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002961 start_line = lines[start_linenum]
2962 joined_line += ' ' + start_line.lstrip()
2963 if Search(r'(;|})', start_line): # Declarations and trivial functions
2964 body_found = True
2965 break # ... ignore
2966 elif Search(r'{', start_line):
2967 body_found = True
2968 function = Search(r'((\w|:)*)\(', line).group(1)
2969 if Match(r'TEST', function): # Handle TEST... macros
2970 parameter_regexp = Search(r'(\(.*\))', joined_line)
2971 if parameter_regexp: # Ignore bad syntax
2972 function += parameter_regexp.group(1)
2973 else:
2974 function += '()'
2975 function_state.Begin(function)
2976 break
2977 if not body_found:
erg@google.com6317a9c2009-06-25 00:28:19 +00002978 # No body for the function (or evidence of a non-function) was found.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002979 error(filename, linenum, 'readability/fn_size', 5,
2980 'Lint failed to find start of function body.')
2981 elif Match(r'^\}\s*$', line): # function end
erg@google.com35589e62010-11-17 18:58:16 +00002982 function_state.Check(error, filename, linenum)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002983 function_state.End()
2984 elif not Match(r'^\s*$', line):
2985 function_state.Count() # Count non-blank/non-comment lines.
2986
2987
2988_RE_PATTERN_TODO = re.compile(r'^//(\s*)TODO(\(.+?\))?:?(\s|$)?')
2989
2990
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002991def CheckComment(line, filename, linenum, next_line_start, error):
2992 """Checks for common mistakes in comments.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002993
2994 Args:
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002995 line: The line in question.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002996 filename: The name of the current file.
2997 linenum: The number of the line to check.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002998 next_line_start: The first non-whitespace column of the next line.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002999 error: The function to call with any errors found.
3000 """
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003001 commentpos = line.find('//')
3002 if commentpos != -1:
3003 # Check if the // may be in quotes. If so, ignore it
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003004 if re.sub(r'\\.', '', line[0:commentpos]).count('"') % 2 == 0:
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003005 # Allow one space for new scopes, two spaces otherwise:
3006 if (not (Match(r'^.*{ *//', line) and next_line_start == commentpos) and
3007 ((commentpos >= 1 and
3008 line[commentpos-1] not in string.whitespace) or
3009 (commentpos >= 2 and
3010 line[commentpos-2] not in string.whitespace))):
3011 error(filename, linenum, 'whitespace/comments', 2,
3012 'At least two spaces is best between code and comments')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003013
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003014 # Checks for common mistakes in TODO comments.
3015 comment = line[commentpos:]
3016 match = _RE_PATTERN_TODO.match(comment)
3017 if match:
3018 # One whitespace is correct; zero whitespace is handled elsewhere.
3019 leading_whitespace = match.group(1)
3020 if len(leading_whitespace) > 1:
3021 error(filename, linenum, 'whitespace/todo', 2,
3022 'Too many spaces before TODO')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003023
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003024 username = match.group(2)
3025 if not username:
3026 error(filename, linenum, 'readability/todo', 2,
3027 'Missing username in TODO; it should look like '
3028 '"// TODO(my_username): Stuff."')
3029
3030 middle_whitespace = match.group(3)
3031 # Comparisons made explicit for correctness -- pylint: disable=g-explicit-bool-comparison
3032 if middle_whitespace != ' ' and middle_whitespace != '':
3033 error(filename, linenum, 'whitespace/todo', 2,
3034 'TODO(my_username) should be followed by a space')
3035
3036 # If the comment contains an alphanumeric character, there
avakulenko@google.com255f2be2014-12-05 22:19:55 +00003037 # should be a space somewhere between it and the // unless
3038 # it's a /// or //! Doxygen comment.
3039 if (Match(r'//[^ ]*\w', comment) and
3040 not Match(r'(///|//\!)(\s+|$)', comment)):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003041 error(filename, linenum, 'whitespace/comments', 4,
3042 'Should have a space between // and comment')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003043
avakulenko@google.com255f2be2014-12-05 22:19:55 +00003044
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003045def CheckAccess(filename, clean_lines, linenum, nesting_state, error):
3046 """Checks for improper use of DISALLOW* macros.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003047
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003048 Args:
3049 filename: The name of the current file.
3050 clean_lines: A CleansedLines instance containing the file.
3051 linenum: The number of the line to check.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003052 nesting_state: A NestingState instance which maintains information about
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003053 the current stack of nested blocks being parsed.
3054 error: The function to call with any errors found.
3055 """
3056 line = clean_lines.elided[linenum] # get rid of comments and strings
3057
3058 matched = Match((r'\s*(DISALLOW_COPY_AND_ASSIGN|'
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003059 r'DISALLOW_IMPLICIT_CONSTRUCTORS)'), line)
3060 if not matched:
3061 return
3062 if nesting_state.stack and isinstance(nesting_state.stack[-1], _ClassInfo):
3063 if nesting_state.stack[-1].access != 'private':
3064 error(filename, linenum, 'readability/constructors', 3,
3065 '%s must be in the private: section' % matched.group(1))
3066
3067 else:
3068 # Found DISALLOW* macro outside a class declaration, or perhaps it
3069 # was used inside a function when it should have been part of the
3070 # class declaration. We could issue a warning here, but it
3071 # probably resulted in a compiler error already.
3072 pass
3073
3074
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003075def CheckSpacing(filename, clean_lines, linenum, nesting_state, error):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003076 """Checks for the correctness of various spacing issues in the code.
3077
3078 Things we check for: spaces around operators, spaces after
3079 if/for/while/switch, no spaces around parens in function calls, two
3080 spaces between code and comment, don't start a block with a blank
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003081 line, don't end a function with a blank line, don't add a blank line
3082 after public/protected/private, don't have too many blank lines in a row.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003083
3084 Args:
3085 filename: The name of the current file.
3086 clean_lines: A CleansedLines instance containing the file.
3087 linenum: The number of the line to check.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003088 nesting_state: A NestingState instance which maintains information about
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003089 the current stack of nested blocks being parsed.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003090 error: The function to call with any errors found.
3091 """
3092
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003093 # Don't use "elided" lines here, otherwise we can't check commented lines.
3094 # Don't want to use "raw" either, because we don't want to check inside C++11
3095 # raw strings,
3096 raw = clean_lines.lines_without_raw_strings
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003097 line = raw[linenum]
3098
3099 # Before nixing comments, check if the line is blank for no good
3100 # reason. This includes the first line after a block is opened, and
3101 # blank lines at the end of a function (ie, right before a line like '}'
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003102 #
3103 # Skip all the blank line checks if we are immediately inside a
3104 # namespace body. In other words, don't issue blank line warnings
3105 # for this block:
3106 # namespace {
3107 #
3108 # }
3109 #
3110 # A warning about missing end of namespace comments will be issued instead.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003111 #
3112 # Also skip blank line checks for 'extern "C"' blocks, which are formatted
3113 # like namespaces.
3114 if (IsBlankLine(line) and
3115 not nesting_state.InNamespaceBody() and
3116 not nesting_state.InExternC()):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003117 elided = clean_lines.elided
3118 prev_line = elided[linenum - 1]
3119 prevbrace = prev_line.rfind('{')
3120 # TODO(unknown): Don't complain if line before blank line, and line after,
3121 # both start with alnums and are indented the same amount.
3122 # This ignores whitespace at the start of a namespace block
3123 # because those are not usually indented.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003124 if prevbrace != -1 and prev_line[prevbrace:].find('}') == -1:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003125 # OK, we have a blank line at the start of a code block. Before we
3126 # complain, we check if it is an exception to the rule: The previous
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003127 # non-empty line has the parameters of a function header that are indented
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003128 # 4 spaces (because they did not fit in a 80 column line when placed on
3129 # the same line as the function name). We also check for the case where
3130 # the previous line is indented 6 spaces, which may happen when the
3131 # initializers of a constructor do not fit into a 80 column line.
3132 exception = False
3133 if Match(r' {6}\w', prev_line): # Initializer list?
3134 # We are looking for the opening column of initializer list, which
3135 # should be indented 4 spaces to cause 6 space indentation afterwards.
3136 search_position = linenum-2
3137 while (search_position >= 0
3138 and Match(r' {6}\w', elided[search_position])):
3139 search_position -= 1
3140 exception = (search_position >= 0
3141 and elided[search_position][:5] == ' :')
3142 else:
3143 # Search for the function arguments or an initializer list. We use a
3144 # simple heuristic here: If the line is indented 4 spaces; and we have a
3145 # closing paren, without the opening paren, followed by an opening brace
3146 # or colon (for initializer lists) we assume that it is the last line of
3147 # a function header. If we have a colon indented 4 spaces, it is an
3148 # initializer list.
3149 exception = (Match(r' {4}\w[^\(]*\)\s*(const\s*)?(\{\s*$|:)',
3150 prev_line)
3151 or Match(r' {4}:', prev_line))
3152
3153 if not exception:
3154 error(filename, linenum, 'whitespace/blank_line', 2,
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003155 'Redundant blank line at the start of a code block '
3156 'should be deleted.')
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003157 # Ignore blank lines at the end of a block in a long if-else
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003158 # chain, like this:
3159 # if (condition1) {
3160 # // Something followed by a blank line
3161 #
3162 # } else if (condition2) {
3163 # // Something else
3164 # }
3165 if linenum + 1 < clean_lines.NumLines():
3166 next_line = raw[linenum + 1]
3167 if (next_line
3168 and Match(r'\s*}', next_line)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003169 and next_line.find('} else ') == -1):
3170 error(filename, linenum, 'whitespace/blank_line', 3,
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003171 'Redundant blank line at the end of a code block '
3172 'should be deleted.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003173
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003174 matched = Match(r'\s*(public|protected|private):', prev_line)
3175 if matched:
3176 error(filename, linenum, 'whitespace/blank_line', 3,
3177 'Do not leave a blank line after "%s:"' % matched.group(1))
3178
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003179 # Next, check comments
3180 next_line_start = 0
3181 if linenum + 1 < clean_lines.NumLines():
3182 next_line = raw[linenum + 1]
3183 next_line_start = len(next_line) - len(next_line.lstrip())
3184 CheckComment(line, filename, linenum, next_line_start, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003185
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003186 # get rid of comments and strings
3187 line = clean_lines.elided[linenum]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003188
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003189 # You shouldn't have spaces before your brackets, except maybe after
3190 # 'delete []' or 'return []() {};'
3191 if Search(r'\w\s+\[', line) and not Search(r'(?:delete|return)\s+\[', line):
3192 error(filename, linenum, 'whitespace/braces', 5,
3193 'Extra space before [')
3194
3195 # In range-based for, we wanted spaces before and after the colon, but
3196 # not around "::" tokens that might appear.
3197 if (Search(r'for *\(.*[^:]:[^: ]', line) or
3198 Search(r'for *\(.*[^: ]:[^:]', line)):
3199 error(filename, linenum, 'whitespace/forcolon', 2,
3200 'Missing space around colon in range-based for loop')
3201
3202
3203def CheckOperatorSpacing(filename, clean_lines, linenum, error):
3204 """Checks for horizontal spacing around operators.
3205
3206 Args:
3207 filename: The name of the current file.
3208 clean_lines: A CleansedLines instance containing the file.
3209 linenum: The number of the line to check.
3210 error: The function to call with any errors found.
3211 """
3212 line = clean_lines.elided[linenum]
3213
3214 # Don't try to do spacing checks for operator methods. Do this by
3215 # replacing the troublesome characters with something else,
3216 # preserving column position for all other characters.
3217 #
3218 # The replacement is done repeatedly to avoid false positives from
3219 # operators that call operators.
3220 while True:
3221 match = Match(r'^(.*\boperator\b)(\S+)(\s*\(.*)$', line)
3222 if match:
3223 line = match.group(1) + ('_' * len(match.group(2))) + match.group(3)
3224 else:
3225 break
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003226
3227 # We allow no-spaces around = within an if: "if ( (a=Foo()) == 0 )".
3228 # Otherwise not. Note we only check for non-spaces on *both* sides;
3229 # sometimes people put non-spaces on one side when aligning ='s among
3230 # many lines (not that this is behavior that I approve of...)
avakulenko@google.com255f2be2014-12-05 22:19:55 +00003231 if ((Search(r'[\w.]=', line) or
3232 Search(r'=[\w.]', line))
3233 and not Search(r'\b(if|while|for) ', line)
3234 # Operators taken from [lex.operators] in C++11 standard.
3235 and not Search(r'(>=|<=|==|!=|&=|\^=|\|=|\+=|\*=|\/=|\%=)', line)
3236 and not Search(r'operator=', line)):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003237 error(filename, linenum, 'whitespace/operators', 4,
3238 'Missing spaces around =')
3239
3240 # It's ok not to have spaces around binary operators like + - * /, but if
3241 # there's too little whitespace, we get concerned. It's hard to tell,
3242 # though, so we punt on this one for now. TODO.
3243
3244 # You should always have whitespace around binary operators.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003245 #
3246 # Check <= and >= first to avoid false positives with < and >, then
3247 # check non-include lines for spacing around < and >.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003248 #
3249 # If the operator is followed by a comma, assume it's be used in a
3250 # macro context and don't do any checks. This avoids false
3251 # positives.
3252 #
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003253 # Note that && is not included here. This is because there are too
3254 # many false positives due to RValue references.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003255 match = Search(r'[^<>=!\s](==|!=|<=|>=|\|\|)[^<>=!\s,;\)]', line)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003256 if match:
3257 error(filename, linenum, 'whitespace/operators', 3,
3258 'Missing spaces around %s' % match.group(1))
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003259 elif not Match(r'#.*include', line):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003260 # Look for < that is not surrounded by spaces. This is only
3261 # triggered if both sides are missing spaces, even though
3262 # technically should should flag if at least one side is missing a
3263 # space. This is done to avoid some false positives with shifts.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003264 match = Match(r'^(.*[^\s<])<[^\s=<,]', line)
3265 if match:
3266 (_, _, end_pos) = CloseExpression(
3267 clean_lines, linenum, len(match.group(1)))
3268 if end_pos <= -1:
3269 error(filename, linenum, 'whitespace/operators', 3,
3270 'Missing spaces around <')
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003271
3272 # Look for > that is not surrounded by spaces. Similar to the
3273 # above, we only trigger if both sides are missing spaces to avoid
3274 # false positives with shifts.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003275 match = Match(r'^(.*[^-\s>])>[^\s=>,]', line)
3276 if match:
3277 (_, _, start_pos) = ReverseCloseExpression(
3278 clean_lines, linenum, len(match.group(1)))
3279 if start_pos <= -1:
3280 error(filename, linenum, 'whitespace/operators', 3,
3281 'Missing spaces around >')
3282
3283 # We allow no-spaces around << when used like this: 10<<20, but
3284 # not otherwise (particularly, not when used as streams)
avakulenko@google.com59146752014-08-11 20:20:55 +00003285 #
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003286 # We also allow operators following an opening parenthesis, since
3287 # those tend to be macros that deal with operators.
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003288 match = Search(r'(operator|[^\s(<])(?:L|UL|LL|ULL|l|ul|ll|ull)?<<([^\s,=<])', line)
avakulenko@google.com255f2be2014-12-05 22:19:55 +00003289 if (match and not (match.group(1).isdigit() and match.group(2).isdigit()) and
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003290 not (match.group(1) == 'operator' and match.group(2) == ';')):
3291 error(filename, linenum, 'whitespace/operators', 3,
3292 'Missing spaces around <<')
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003293
3294 # We allow no-spaces around >> for almost anything. This is because
3295 # C++11 allows ">>" to close nested templates, which accounts for
3296 # most cases when ">>" is not followed by a space.
3297 #
3298 # We still warn on ">>" followed by alpha character, because that is
3299 # likely due to ">>" being used for right shifts, e.g.:
3300 # value >> alpha
3301 #
3302 # When ">>" is used to close templates, the alphanumeric letter that
3303 # follows would be part of an identifier, and there should still be
3304 # a space separating the template type and the identifier.
3305 # type<type<type>> alpha
3306 match = Search(r'>>[a-zA-Z_]', line)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003307 if match:
3308 error(filename, linenum, 'whitespace/operators', 3,
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003309 'Missing spaces around >>')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003310
3311 # There shouldn't be space around unary operators
3312 match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line)
3313 if match:
3314 error(filename, linenum, 'whitespace/operators', 4,
3315 'Extra space for operator %s' % match.group(1))
3316
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003317
3318def CheckParenthesisSpacing(filename, clean_lines, linenum, error):
3319 """Checks for horizontal spacing around parentheses.
3320
3321 Args:
3322 filename: The name of the current file.
3323 clean_lines: A CleansedLines instance containing the file.
3324 linenum: The number of the line to check.
3325 error: The function to call with any errors found.
3326 """
3327 line = clean_lines.elided[linenum]
3328
3329 # No spaces after an if, while, switch, or for
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003330 match = Search(r' (if\(|for\(|while\(|switch\()', line)
3331 if match:
3332 error(filename, linenum, 'whitespace/parens', 5,
3333 'Missing space before ( in %s' % match.group(1))
3334
3335 # For if/for/while/switch, the left and right parens should be
3336 # consistent about how many spaces are inside the parens, and
3337 # there should either be zero or one spaces inside the parens.
3338 # We don't want: "if ( foo)" or "if ( foo )".
erg@google.com6317a9c2009-06-25 00:28:19 +00003339 # Exception: "for ( ; foo; bar)" and "for (foo; bar; )" are allowed.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003340 match = Search(r'\b(if|for|while|switch)\s*'
3341 r'\(([ ]*)(.).*[^ ]+([ ]*)\)\s*{\s*$',
3342 line)
3343 if match:
3344 if len(match.group(2)) != len(match.group(4)):
3345 if not (match.group(3) == ';' and
erg@google.com6317a9c2009-06-25 00:28:19 +00003346 len(match.group(2)) == 1 + len(match.group(4)) or
3347 not match.group(2) and Search(r'\bfor\s*\(.*; \)', line)):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003348 error(filename, linenum, 'whitespace/parens', 5,
3349 'Mismatching spaces inside () in %s' % match.group(1))
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003350 if len(match.group(2)) not in [0, 1]:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003351 error(filename, linenum, 'whitespace/parens', 5,
3352 'Should have zero or one spaces inside ( and ) in %s' %
3353 match.group(1))
3354
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003355
3356def CheckCommaSpacing(filename, clean_lines, linenum, error):
3357 """Checks for horizontal spacing near commas and semicolons.
3358
3359 Args:
3360 filename: The name of the current file.
3361 clean_lines: A CleansedLines instance containing the file.
3362 linenum: The number of the line to check.
3363 error: The function to call with any errors found.
3364 """
3365 raw = clean_lines.lines_without_raw_strings
3366 line = clean_lines.elided[linenum]
3367
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003368 # You should always have a space after a comma (either as fn arg or operator)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003369 #
3370 # This does not apply when the non-space character following the
3371 # comma is another comma, since the only time when that happens is
3372 # for empty macro arguments.
3373 #
3374 # We run this check in two passes: first pass on elided lines to
3375 # verify that lines contain missing whitespaces, second pass on raw
3376 # lines to confirm that those missing whitespaces are not due to
3377 # elided comments.
avakulenko@google.com59146752014-08-11 20:20:55 +00003378 if (Search(r',[^,\s]', ReplaceAll(r'\boperator\s*,\s*\(', 'F(', line)) and
3379 Search(r',[^,\s]', raw[linenum])):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003380 error(filename, linenum, 'whitespace/comma', 3,
3381 'Missing space after ,')
3382
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003383 # You should always have a space after a semicolon
3384 # except for few corner cases
3385 # TODO(unknown): clarify if 'if (1) { return 1;}' is requires one more
3386 # space after ;
3387 if Search(r';[^\s};\\)/]', line):
3388 error(filename, linenum, 'whitespace/semicolon', 3,
3389 'Missing space after ;')
3390
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003391
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003392def _IsType(clean_lines, nesting_state, expr):
3393 """Check if expression looks like a type name, returns true if so.
3394
3395 Args:
3396 clean_lines: A CleansedLines instance containing the file.
3397 nesting_state: A NestingState instance which maintains information about
3398 the current stack of nested blocks being parsed.
3399 expr: The expression to check.
3400 Returns:
3401 True, if token looks like a type.
3402 """
3403 # Keep only the last token in the expression
3404 last_word = Match(r'^.*(\b\S+)$', expr)
3405 if last_word:
3406 token = last_word.group(1)
3407 else:
3408 token = expr
3409
3410 # Match native types and stdint types
3411 if _TYPES.match(token):
3412 return True
3413
3414 # Try a bit harder to match templated types. Walk up the nesting
3415 # stack until we find something that resembles a typename
3416 # declaration for what we are looking for.
3417 typename_pattern = (r'\b(?:typename|class|struct)\s+' + re.escape(token) +
3418 r'\b')
3419 block_index = len(nesting_state.stack) - 1
3420 while block_index >= 0:
3421 if isinstance(nesting_state.stack[block_index], _NamespaceInfo):
3422 return False
3423
3424 # Found where the opening brace is. We want to scan from this
3425 # line up to the beginning of the function, minus a few lines.
3426 # template <typename Type1, // stop scanning here
3427 # ...>
3428 # class C
3429 # : public ... { // start scanning here
3430 last_line = nesting_state.stack[block_index].starting_linenum
3431
3432 next_block_start = 0
3433 if block_index > 0:
3434 next_block_start = nesting_state.stack[block_index - 1].starting_linenum
3435 first_line = last_line
3436 while first_line >= next_block_start:
3437 if clean_lines.elided[first_line].find('template') >= 0:
3438 break
3439 first_line -= 1
3440 if first_line < next_block_start:
3441 # Didn't find any "template" keyword before reaching the next block,
3442 # there are probably no template things to check for this block
3443 block_index -= 1
3444 continue
3445
3446 # Look for typename in the specified range
3447 for i in xrange(first_line, last_line + 1, 1):
3448 if Search(typename_pattern, clean_lines.elided[i]):
3449 return True
3450 block_index -= 1
3451
3452 return False
3453
3454
3455def CheckBracesSpacing(filename, clean_lines, linenum, nesting_state, error):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003456 """Checks for horizontal spacing near commas.
3457
3458 Args:
3459 filename: The name of the current file.
3460 clean_lines: A CleansedLines instance containing the file.
3461 linenum: The number of the line to check.
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003462 nesting_state: A NestingState instance which maintains information about
3463 the current stack of nested blocks being parsed.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003464 error: The function to call with any errors found.
3465 """
3466 line = clean_lines.elided[linenum]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003467
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003468 # Except after an opening paren, or after another opening brace (in case of
3469 # an initializer list, for instance), you should have spaces before your
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003470 # braces when they are delimiting blocks, classes, namespaces etc.
3471 # And since you should never have braces at the beginning of a line,
3472 # this is an easy test. Except that braces used for initialization don't
3473 # follow the same rule; we often don't want spaces before those.
avakulenko@google.com255f2be2014-12-05 22:19:55 +00003474 match = Match(r'^(.*[^ ({>]){', line)
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003475
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003476 if match:
3477 # Try a bit harder to check for brace initialization. This
3478 # happens in one of the following forms:
3479 # Constructor() : initializer_list_{} { ... }
3480 # Constructor{}.MemberFunction()
3481 # Type variable{};
3482 # FunctionCall(type{}, ...);
3483 # LastArgument(..., type{});
3484 # LOG(INFO) << type{} << " ...";
3485 # map_of_type[{...}] = ...;
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003486 # ternary = expr ? new type{} : nullptr;
3487 # OuterTemplate<InnerTemplateConstructor<Type>{}>
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003488 #
3489 # We check for the character following the closing brace, and
3490 # silence the warning if it's one of those listed above, i.e.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003491 # "{.;,)<>]:".
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003492 #
3493 # To account for nested initializer list, we allow any number of
3494 # closing braces up to "{;,)<". We can't simply silence the
3495 # warning on first sight of closing brace, because that would
3496 # cause false negatives for things that are not initializer lists.
3497 # Silence this: But not this:
3498 # Outer{ if (...) {
3499 # Inner{...} if (...){ // Missing space before {
3500 # }; }
3501 #
3502 # There is a false negative with this approach if people inserted
3503 # spurious semicolons, e.g. "if (cond){};", but we will catch the
3504 # spurious semicolon with a separate check.
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003505 leading_text = match.group(1)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003506 (endline, endlinenum, endpos) = CloseExpression(
3507 clean_lines, linenum, len(match.group(1)))
3508 trailing_text = ''
3509 if endpos > -1:
3510 trailing_text = endline[endpos:]
3511 for offset in xrange(endlinenum + 1,
3512 min(endlinenum + 3, clean_lines.NumLines() - 1)):
3513 trailing_text += clean_lines.elided[offset]
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003514 # We also suppress warnings for `uint64_t{expression}` etc., as the style
3515 # guide recommends brace initialization for integral types to avoid
3516 # overflow/truncation.
3517 if (not Match(r'^[\s}]*[{.;,)<>\]:]', trailing_text)
3518 and not _IsType(clean_lines, nesting_state, leading_text)):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003519 error(filename, linenum, 'whitespace/braces', 5,
3520 'Missing space before {')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003521
3522 # Make sure '} else {' has spaces.
3523 if Search(r'}else', line):
3524 error(filename, linenum, 'whitespace/braces', 5,
3525 'Missing space before else')
3526
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003527 # You shouldn't have a space before a semicolon at the end of the line.
3528 # There's a special case for "for" since the style guide allows space before
3529 # the semicolon there.
3530 if Search(r':\s*;\s*$', line):
3531 error(filename, linenum, 'whitespace/semicolon', 5,
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003532 'Semicolon defining empty statement. Use {} instead.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003533 elif Search(r'^\s*;\s*$', line):
3534 error(filename, linenum, 'whitespace/semicolon', 5,
3535 'Line contains only semicolon. If this should be an empty statement, '
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003536 'use {} instead.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003537 elif (Search(r'\s+;\s*$', line) and
3538 not Search(r'\bfor\b', line)):
3539 error(filename, linenum, 'whitespace/semicolon', 5,
3540 'Extra space before last semicolon. If this should be an empty '
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003541 'statement, use {} instead.')
3542
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003543
3544def IsDecltype(clean_lines, linenum, column):
3545 """Check if the token ending on (linenum, column) is decltype().
3546
3547 Args:
3548 clean_lines: A CleansedLines instance containing the file.
3549 linenum: the number of the line to check.
3550 column: end column of the token to check.
3551 Returns:
3552 True if this token is decltype() expression, False otherwise.
3553 """
3554 (text, _, start_col) = ReverseCloseExpression(clean_lines, linenum, column)
3555 if start_col < 0:
3556 return False
3557 if Search(r'\bdecltype\s*$', text[0:start_col]):
3558 return True
3559 return False
3560
3561
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003562def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error):
3563 """Checks for additional blank line issues related to sections.
3564
3565 Currently the only thing checked here is blank line before protected/private.
3566
3567 Args:
3568 filename: The name of the current file.
3569 clean_lines: A CleansedLines instance containing the file.
3570 class_info: A _ClassInfo objects.
3571 linenum: The number of the line to check.
3572 error: The function to call with any errors found.
3573 """
3574 # Skip checks if the class is small, where small means 25 lines or less.
3575 # 25 lines seems like a good cutoff since that's the usual height of
3576 # terminals, and any class that can't fit in one screen can't really
3577 # be considered "small".
3578 #
3579 # Also skip checks if we are on the first line. This accounts for
3580 # classes that look like
3581 # class Foo { public: ... };
3582 #
3583 # If we didn't find the end of the class, last_line would be zero,
3584 # and the check will be skipped by the first condition.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003585 if (class_info.last_line - class_info.starting_linenum <= 24 or
3586 linenum <= class_info.starting_linenum):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003587 return
3588
3589 matched = Match(r'\s*(public|protected|private):', clean_lines.lines[linenum])
3590 if matched:
3591 # Issue warning if the line before public/protected/private was
3592 # not a blank line, but don't do this if the previous line contains
3593 # "class" or "struct". This can happen two ways:
3594 # - We are at the beginning of the class.
3595 # - We are forward-declaring an inner class that is semantically
3596 # private, but needed to be public for implementation reasons.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003597 # Also ignores cases where the previous line ends with a backslash as can be
3598 # common when defining classes in C macros.
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003599 prev_line = clean_lines.lines[linenum - 1]
3600 if (not IsBlankLine(prev_line) and
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003601 not Search(r'\b(class|struct)\b', prev_line) and
3602 not Search(r'\\$', prev_line)):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003603 # Try a bit harder to find the beginning of the class. This is to
3604 # account for multi-line base-specifier lists, e.g.:
3605 # class Derived
3606 # : public Base {
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003607 end_class_head = class_info.starting_linenum
3608 for i in range(class_info.starting_linenum, linenum):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003609 if Search(r'\{\s*$', clean_lines.lines[i]):
3610 end_class_head = i
3611 break
3612 if end_class_head < linenum - 1:
3613 error(filename, linenum, 'whitespace/blank_line', 3,
3614 '"%s:" should be preceded by a blank line' % matched.group(1))
3615
3616
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003617def GetPreviousNonBlankLine(clean_lines, linenum):
3618 """Return the most recent non-blank line and its line number.
3619
3620 Args:
3621 clean_lines: A CleansedLines instance containing the file contents.
3622 linenum: The number of the line to check.
3623
3624 Returns:
3625 A tuple with two elements. The first element is the contents of the last
3626 non-blank line before the current line, or the empty string if this is the
3627 first non-blank line. The second is the line number of that line, or -1
3628 if this is the first non-blank line.
3629 """
3630
3631 prevlinenum = linenum - 1
3632 while prevlinenum >= 0:
3633 prevline = clean_lines.elided[prevlinenum]
3634 if not IsBlankLine(prevline): # if not a blank line...
3635 return (prevline, prevlinenum)
3636 prevlinenum -= 1
3637 return ('', -1)
3638
3639
3640def CheckBraces(filename, clean_lines, linenum, error):
3641 """Looks for misplaced braces (e.g. at the end of line).
3642
3643 Args:
3644 filename: The name of the current file.
3645 clean_lines: A CleansedLines instance containing the file.
3646 linenum: The number of the line to check.
3647 error: The function to call with any errors found.
3648 """
3649
3650 line = clean_lines.elided[linenum] # get rid of comments and strings
3651
3652 if Match(r'\s*{\s*$', line):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003653 # We allow an open brace to start a line in the case where someone is using
3654 # braces in a block to explicitly create a new scope, which is commonly used
3655 # to control the lifetime of stack-allocated variables. Braces are also
3656 # used for brace initializers inside function calls. We don't detect this
3657 # perfectly: we just don't complain if the last non-whitespace character on
3658 # the previous non-blank line is ',', ';', ':', '(', '{', or '}', or if the
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003659 # previous line starts a preprocessor block. We also allow a brace on the
3660 # following line if it is part of an array initialization and would not fit
3661 # within the 80 character limit of the preceding line.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003662 prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003663 if (not Search(r'[,;:}{(]\s*$', prevline) and
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003664 not Match(r'\s*#', prevline) and
3665 not (GetLineWidth(prevline) > _line_length - 2 and '[]' in prevline)):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003666 error(filename, linenum, 'whitespace/braces', 4,
3667 '{ should almost always be at the end of the previous line')
3668
3669 # An else clause should be on the same line as the preceding closing brace.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003670 if Match(r'\s*else\b\s*(?:if\b|\{|$)', line):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003671 prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
3672 if Match(r'\s*}\s*$', prevline):
3673 error(filename, linenum, 'whitespace/newline', 4,
3674 'An else should appear on the same line as the preceding }')
3675
3676 # If braces come on one side of an else, they should be on both.
3677 # However, we have to worry about "else if" that spans multiple lines!
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003678 if Search(r'else if\s*\(', line): # could be multi-line if
3679 brace_on_left = bool(Search(r'}\s*else if\s*\(', line))
3680 # find the ( after the if
3681 pos = line.find('else if')
3682 pos = line.find('(', pos)
3683 if pos > 0:
3684 (endline, _, endpos) = CloseExpression(clean_lines, linenum, pos)
3685 brace_on_right = endline[endpos:].find('{') != -1
3686 if brace_on_left != brace_on_right: # must be brace after if
3687 error(filename, linenum, 'readability/braces', 5,
3688 'If an else has a brace on one side, it should have it on both')
3689 elif Search(r'}\s*else[^{]*$', line) or Match(r'[^}]*else\s*{', line):
3690 error(filename, linenum, 'readability/braces', 5,
3691 'If an else has a brace on one side, it should have it on both')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003692
3693 # Likewise, an else should never have the else clause on the same line
3694 if Search(r'\belse [^\s{]', line) and not Search(r'\belse if\b', line):
3695 error(filename, linenum, 'whitespace/newline', 4,
3696 'Else clause should never be on same line as else (use 2 lines)')
3697
3698 # In the same way, a do/while should never be on one line
3699 if Match(r'\s*do [^\s{]', line):
3700 error(filename, linenum, 'whitespace/newline', 4,
3701 'do/while clauses should not be on a single line')
3702
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003703 # Check single-line if/else bodies. The style guide says 'curly braces are not
3704 # required for single-line statements'. We additionally allow multi-line,
3705 # single statements, but we reject anything with more than one semicolon in
3706 # it. This means that the first semicolon after the if should be at the end of
3707 # its line, and the line after that should have an indent level equal to or
3708 # lower than the if. We also check for ambiguous if/else nesting without
3709 # braces.
3710 if_else_match = Search(r'\b(if\s*\(|else\b)', line)
3711 if if_else_match and not Match(r'\s*#', line):
3712 if_indent = GetIndentLevel(line)
3713 endline, endlinenum, endpos = line, linenum, if_else_match.end()
3714 if_match = Search(r'\bif\s*\(', line)
3715 if if_match:
3716 # This could be a multiline if condition, so find the end first.
3717 pos = if_match.end() - 1
3718 (endline, endlinenum, endpos) = CloseExpression(clean_lines, linenum, pos)
3719 # Check for an opening brace, either directly after the if or on the next
3720 # line. If found, this isn't a single-statement conditional.
3721 if (not Match(r'\s*{', endline[endpos:])
3722 and not (Match(r'\s*$', endline[endpos:])
3723 and endlinenum < (len(clean_lines.elided) - 1)
3724 and Match(r'\s*{', clean_lines.elided[endlinenum + 1]))):
3725 while (endlinenum < len(clean_lines.elided)
3726 and ';' not in clean_lines.elided[endlinenum][endpos:]):
3727 endlinenum += 1
3728 endpos = 0
3729 if endlinenum < len(clean_lines.elided):
3730 endline = clean_lines.elided[endlinenum]
3731 # We allow a mix of whitespace and closing braces (e.g. for one-liner
3732 # methods) and a single \ after the semicolon (for macros)
3733 endpos = endline.find(';')
3734 if not Match(r';[\s}]*(\\?)$', endline[endpos:]):
avakulenko@google.com59146752014-08-11 20:20:55 +00003735 # Semicolon isn't the last character, there's something trailing.
3736 # Output a warning if the semicolon is not contained inside
3737 # a lambda expression.
3738 if not Match(r'^[^{};]*\[[^\[\]]*\][^{}]*\{[^{}]*\}\s*\)*[;,]\s*$',
3739 endline):
3740 error(filename, linenum, 'readability/braces', 4,
3741 'If/else bodies with multiple statements require braces')
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003742 elif endlinenum < len(clean_lines.elided) - 1:
3743 # Make sure the next line is dedented
3744 next_line = clean_lines.elided[endlinenum + 1]
3745 next_indent = GetIndentLevel(next_line)
3746 # With ambiguous nested if statements, this will error out on the
3747 # if that *doesn't* match the else, regardless of whether it's the
3748 # inner one or outer one.
3749 if (if_match and Match(r'\s*else\b', next_line)
3750 and next_indent != if_indent):
3751 error(filename, linenum, 'readability/braces', 4,
3752 'Else clause should be indented at the same level as if. '
3753 'Ambiguous nested if/else chains require braces.')
3754 elif next_indent > if_indent:
3755 error(filename, linenum, 'readability/braces', 4,
3756 'If/else bodies with multiple statements require braces')
3757
3758
3759def CheckTrailingSemicolon(filename, clean_lines, linenum, error):
3760 """Looks for redundant trailing semicolon.
3761
3762 Args:
3763 filename: The name of the current file.
3764 clean_lines: A CleansedLines instance containing the file.
3765 linenum: The number of the line to check.
3766 error: The function to call with any errors found.
3767 """
3768
3769 line = clean_lines.elided[linenum]
3770
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003771 # Block bodies should not be followed by a semicolon. Due to C++11
3772 # brace initialization, there are more places where semicolons are
3773 # required than not, so we use a whitelist approach to check these
3774 # rather than a blacklist. These are the places where "};" should
3775 # be replaced by just "}":
3776 # 1. Some flavor of block following closing parenthesis:
3777 # for (;;) {};
3778 # while (...) {};
3779 # switch (...) {};
3780 # Function(...) {};
3781 # if (...) {};
3782 # if (...) else if (...) {};
3783 #
3784 # 2. else block:
3785 # if (...) else {};
3786 #
3787 # 3. const member function:
3788 # Function(...) const {};
3789 #
3790 # 4. Block following some statement:
3791 # x = 42;
3792 # {};
3793 #
3794 # 5. Block at the beginning of a function:
3795 # Function(...) {
3796 # {};
3797 # }
3798 #
3799 # Note that naively checking for the preceding "{" will also match
3800 # braces inside multi-dimensional arrays, but this is fine since
3801 # that expression will not contain semicolons.
3802 #
3803 # 6. Block following another block:
3804 # while (true) {}
3805 # {};
3806 #
3807 # 7. End of namespaces:
3808 # namespace {};
3809 #
3810 # These semicolons seems far more common than other kinds of
3811 # redundant semicolons, possibly due to people converting classes
3812 # to namespaces. For now we do not warn for this case.
3813 #
3814 # Try matching case 1 first.
3815 match = Match(r'^(.*\)\s*)\{', line)
3816 if match:
3817 # Matched closing parenthesis (case 1). Check the token before the
3818 # matching opening parenthesis, and don't warn if it looks like a
3819 # macro. This avoids these false positives:
3820 # - macro that defines a base class
3821 # - multi-line macro that defines a base class
3822 # - macro that defines the whole class-head
3823 #
3824 # But we still issue warnings for macros that we know are safe to
3825 # warn, specifically:
3826 # - TEST, TEST_F, TEST_P, MATCHER, MATCHER_P
3827 # - TYPED_TEST
3828 # - INTERFACE_DEF
3829 # - EXCLUSIVE_LOCKS_REQUIRED, SHARED_LOCKS_REQUIRED, LOCKS_EXCLUDED:
3830 #
3831 # We implement a whitelist of safe macros instead of a blacklist of
3832 # unsafe macros, even though the latter appears less frequently in
3833 # google code and would have been easier to implement. This is because
3834 # the downside for getting the whitelist wrong means some extra
3835 # semicolons, while the downside for getting the blacklist wrong
3836 # would result in compile errors.
3837 #
avakulenko@google.com255f2be2014-12-05 22:19:55 +00003838 # In addition to macros, we also don't want to warn on
3839 # - Compound literals
3840 # - Lambdas
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003841 # - alignas specifier with anonymous structs
3842 # - decltype
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003843 closing_brace_pos = match.group(1).rfind(')')
3844 opening_parenthesis = ReverseCloseExpression(
3845 clean_lines, linenum, closing_brace_pos)
3846 if opening_parenthesis[2] > -1:
3847 line_prefix = opening_parenthesis[0][0:opening_parenthesis[2]]
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003848 macro = Search(r'\b([A-Z_][A-Z0-9_]*)\s*$', line_prefix)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003849 func = Match(r'^(.*\])\s*$', line_prefix)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003850 if ((macro and
3851 macro.group(1) not in (
3852 'TEST', 'TEST_F', 'MATCHER', 'MATCHER_P', 'TYPED_TEST',
3853 'EXCLUSIVE_LOCKS_REQUIRED', 'SHARED_LOCKS_REQUIRED',
3854 'LOCKS_EXCLUDED', 'INTERFACE_DEF')) or
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003855 (func and not Search(r'\boperator\s*\[\s*\]', func.group(1))) or
avakulenko@google.com255f2be2014-12-05 22:19:55 +00003856 Search(r'\b(?:struct|union)\s+alignas\s*$', line_prefix) or
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003857 Search(r'\bdecltype$', line_prefix) or
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003858 Search(r'\s+=\s*$', line_prefix)):
3859 match = None
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003860 if (match and
3861 opening_parenthesis[1] > 1 and
3862 Search(r'\]\s*$', clean_lines.elided[opening_parenthesis[1] - 1])):
3863 # Multi-line lambda-expression
3864 match = None
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003865
3866 else:
3867 # Try matching cases 2-3.
3868 match = Match(r'^(.*(?:else|\)\s*const)\s*)\{', line)
3869 if not match:
3870 # Try matching cases 4-6. These are always matched on separate lines.
3871 #
3872 # Note that we can't simply concatenate the previous line to the
3873 # current line and do a single match, otherwise we may output
3874 # duplicate warnings for the blank line case:
3875 # if (cond) {
3876 # // blank line
3877 # }
3878 prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
3879 if prevline and Search(r'[;{}]\s*$', prevline):
3880 match = Match(r'^(\s*)\{', line)
3881
3882 # Check matching closing brace
3883 if match:
3884 (endline, endlinenum, endpos) = CloseExpression(
3885 clean_lines, linenum, len(match.group(1)))
3886 if endpos > -1 and Match(r'^\s*;', endline[endpos:]):
3887 # Current {} pair is eligible for semicolon check, and we have found
3888 # the redundant semicolon, output warning here.
3889 #
3890 # Note: because we are scanning forward for opening braces, and
3891 # outputting warnings for the matching closing brace, if there are
3892 # nested blocks with trailing semicolons, we will get the error
3893 # messages in reversed order.
3894 error(filename, endlinenum, 'readability/braces', 4,
3895 "You don't need a ; after a }")
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003896
3897
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003898def CheckEmptyBlockBody(filename, clean_lines, linenum, error):
3899 """Look for empty loop/conditional body with only a single semicolon.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003900
3901 Args:
3902 filename: The name of the current file.
3903 clean_lines: A CleansedLines instance containing the file.
3904 linenum: The number of the line to check.
3905 error: The function to call with any errors found.
3906 """
3907
3908 # Search for loop keywords at the beginning of the line. Because only
3909 # whitespaces are allowed before the keywords, this will also ignore most
3910 # do-while-loops, since those lines should start with closing brace.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003911 #
3912 # We also check "if" blocks here, since an empty conditional block
3913 # is likely an error.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003914 line = clean_lines.elided[linenum]
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003915 matched = Match(r'\s*(for|while|if)\s*\(', line)
3916 if matched:
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003917 # Find the end of the conditional expression.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003918 (end_line, end_linenum, end_pos) = CloseExpression(
3919 clean_lines, linenum, line.find('('))
3920
3921 # Output warning if what follows the condition expression is a semicolon.
3922 # No warning for all other cases, including whitespace or newline, since we
3923 # have a separate check for semicolons preceded by whitespace.
3924 if end_pos >= 0 and Match(r';', end_line[end_pos:]):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003925 if matched.group(1) == 'if':
3926 error(filename, end_linenum, 'whitespace/empty_conditional_body', 5,
3927 'Empty conditional bodies should use {}')
3928 else:
3929 error(filename, end_linenum, 'whitespace/empty_loop_body', 5,
3930 'Empty loop bodies should use {} or continue')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003931
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003932 # Check for if statements that have completely empty bodies (no comments)
3933 # and no else clauses.
3934 if end_pos >= 0 and matched.group(1) == 'if':
3935 # Find the position of the opening { for the if statement.
3936 # Return without logging an error if it has no brackets.
3937 opening_linenum = end_linenum
3938 opening_line_fragment = end_line[end_pos:]
3939 # Loop until EOF or find anything that's not whitespace or opening {.
3940 while not Search(r'^\s*\{', opening_line_fragment):
3941 if Search(r'^(?!\s*$)', opening_line_fragment):
3942 # Conditional has no brackets.
3943 return
3944 opening_linenum += 1
3945 if opening_linenum == len(clean_lines.elided):
3946 # Couldn't find conditional's opening { or any code before EOF.
3947 return
3948 opening_line_fragment = clean_lines.elided[opening_linenum]
3949 # Set opening_line (opening_line_fragment may not be entire opening line).
3950 opening_line = clean_lines.elided[opening_linenum]
3951
3952 # Find the position of the closing }.
3953 opening_pos = opening_line_fragment.find('{')
3954 if opening_linenum == end_linenum:
3955 # We need to make opening_pos relative to the start of the entire line.
3956 opening_pos += end_pos
3957 (closing_line, closing_linenum, closing_pos) = CloseExpression(
3958 clean_lines, opening_linenum, opening_pos)
3959 if closing_pos < 0:
3960 return
3961
3962 # Now construct the body of the conditional. This consists of the portion
3963 # of the opening line after the {, all lines until the closing line,
3964 # and the portion of the closing line before the }.
3965 if (clean_lines.raw_lines[opening_linenum] !=
3966 CleanseComments(clean_lines.raw_lines[opening_linenum])):
3967 # Opening line ends with a comment, so conditional isn't empty.
3968 return
3969 if closing_linenum > opening_linenum:
3970 # Opening line after the {. Ignore comments here since we checked above.
3971 body = list(opening_line[opening_pos+1:])
3972 # All lines until closing line, excluding closing line, with comments.
3973 body.extend(clean_lines.raw_lines[opening_linenum+1:closing_linenum])
3974 # Closing line before the }. Won't (and can't) have comments.
3975 body.append(clean_lines.elided[closing_linenum][:closing_pos-1])
3976 body = '\n'.join(body)
3977 else:
3978 # If statement has brackets and fits on a single line.
3979 body = opening_line[opening_pos+1:closing_pos-1]
3980
3981 # Check if the body is empty
3982 if not _EMPTY_CONDITIONAL_BODY_PATTERN.search(body):
3983 return
3984 # The body is empty. Now make sure there's not an else clause.
3985 current_linenum = closing_linenum
3986 current_line_fragment = closing_line[closing_pos:]
3987 # Loop until EOF or find anything that's not whitespace or else clause.
3988 while Search(r'^\s*$|^(?=\s*else)', current_line_fragment):
3989 if Search(r'^(?=\s*else)', current_line_fragment):
3990 # Found an else clause, so don't log an error.
3991 return
3992 current_linenum += 1
3993 if current_linenum == len(clean_lines.elided):
3994 break
3995 current_line_fragment = clean_lines.elided[current_linenum]
3996
3997 # The body is empty and there's no else clause until EOF or other code.
3998 error(filename, end_linenum, 'whitespace/empty_if_body', 4,
3999 ('If statement had no body and no else clause'))
4000
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004001
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004002def FindCheckMacro(line):
4003 """Find a replaceable CHECK-like macro.
4004
4005 Args:
4006 line: line to search on.
4007 Returns:
4008 (macro name, start position), or (None, -1) if no replaceable
4009 macro is found.
4010 """
4011 for macro in _CHECK_MACROS:
4012 i = line.find(macro)
4013 if i >= 0:
4014 # Find opening parenthesis. Do a regular expression match here
4015 # to make sure that we are matching the expected CHECK macro, as
4016 # opposed to some other macro that happens to contain the CHECK
4017 # substring.
4018 matched = Match(r'^(.*\b' + macro + r'\s*)\(', line)
4019 if not matched:
4020 continue
4021 return (macro, len(matched.group(1)))
4022 return (None, -1)
4023
4024
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004025def CheckCheck(filename, clean_lines, linenum, error):
4026 """Checks the use of CHECK and EXPECT macros.
4027
4028 Args:
4029 filename: The name of the current file.
4030 clean_lines: A CleansedLines instance containing the file.
4031 linenum: The number of the line to check.
4032 error: The function to call with any errors found.
4033 """
4034
4035 # Decide the set of replacement macros that should be suggested
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004036 lines = clean_lines.elided
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004037 (check_macro, start_pos) = FindCheckMacro(lines[linenum])
4038 if not check_macro:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004039 return
4040
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004041 # Find end of the boolean expression by matching parentheses
4042 (last_line, end_line, end_pos) = CloseExpression(
4043 clean_lines, linenum, start_pos)
4044 if end_pos < 0:
4045 return
avakulenko@google.com59146752014-08-11 20:20:55 +00004046
4047 # If the check macro is followed by something other than a
4048 # semicolon, assume users will log their own custom error messages
4049 # and don't suggest any replacements.
4050 if not Match(r'\s*;', last_line[end_pos:]):
4051 return
4052
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004053 if linenum == end_line:
4054 expression = lines[linenum][start_pos + 1:end_pos - 1]
4055 else:
4056 expression = lines[linenum][start_pos + 1:]
4057 for i in xrange(linenum + 1, end_line):
4058 expression += lines[i]
4059 expression += last_line[0:end_pos - 1]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004060
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004061 # Parse expression so that we can take parentheses into account.
4062 # This avoids false positives for inputs like "CHECK((a < 4) == b)",
4063 # which is not replaceable by CHECK_LE.
4064 lhs = ''
4065 rhs = ''
4066 operator = None
4067 while expression:
4068 matched = Match(r'^\s*(<<|<<=|>>|>>=|->\*|->|&&|\|\||'
4069 r'==|!=|>=|>|<=|<|\()(.*)$', expression)
4070 if matched:
4071 token = matched.group(1)
4072 if token == '(':
4073 # Parenthesized operand
4074 expression = matched.group(2)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004075 (end, _) = FindEndOfExpressionInLine(expression, 0, ['('])
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004076 if end < 0:
4077 return # Unmatched parenthesis
4078 lhs += '(' + expression[0:end]
4079 expression = expression[end:]
4080 elif token in ('&&', '||'):
4081 # Logical and/or operators. This means the expression
4082 # contains more than one term, for example:
4083 # CHECK(42 < a && a < b);
4084 #
4085 # These are not replaceable with CHECK_LE, so bail out early.
4086 return
4087 elif token in ('<<', '<<=', '>>', '>>=', '->*', '->'):
4088 # Non-relational operator
4089 lhs += token
4090 expression = matched.group(2)
4091 else:
4092 # Relational operator
4093 operator = token
4094 rhs = matched.group(2)
4095 break
4096 else:
4097 # Unparenthesized operand. Instead of appending to lhs one character
4098 # at a time, we do another regular expression match to consume several
4099 # characters at once if possible. Trivial benchmark shows that this
4100 # is more efficient when the operands are longer than a single
4101 # character, which is generally the case.
4102 matched = Match(r'^([^-=!<>()&|]+)(.*)$', expression)
4103 if not matched:
4104 matched = Match(r'^(\s*\S)(.*)$', expression)
4105 if not matched:
4106 break
4107 lhs += matched.group(1)
4108 expression = matched.group(2)
4109
4110 # Only apply checks if we got all parts of the boolean expression
4111 if not (lhs and operator and rhs):
4112 return
4113
4114 # Check that rhs do not contain logical operators. We already know
4115 # that lhs is fine since the loop above parses out && and ||.
4116 if rhs.find('&&') > -1 or rhs.find('||') > -1:
4117 return
4118
4119 # At least one of the operands must be a constant literal. This is
4120 # to avoid suggesting replacements for unprintable things like
4121 # CHECK(variable != iterator)
4122 #
4123 # The following pattern matches decimal, hex integers, strings, and
4124 # characters (in that order).
4125 lhs = lhs.strip()
4126 rhs = rhs.strip()
4127 match_constant = r'^([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')$'
4128 if Match(match_constant, lhs) or Match(match_constant, rhs):
4129 # Note: since we know both lhs and rhs, we can provide a more
4130 # descriptive error message like:
4131 # Consider using CHECK_EQ(x, 42) instead of CHECK(x == 42)
4132 # Instead of:
4133 # Consider using CHECK_EQ instead of CHECK(a == b)
4134 #
4135 # We are still keeping the less descriptive message because if lhs
4136 # or rhs gets long, the error message might become unreadable.
4137 error(filename, linenum, 'readability/check', 2,
4138 'Consider using %s instead of %s(a %s b)' % (
4139 _CHECK_REPLACEMENT[check_macro][operator],
4140 check_macro, operator))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004141
4142
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004143def CheckAltTokens(filename, clean_lines, linenum, error):
4144 """Check alternative keywords being used in boolean expressions.
4145
4146 Args:
4147 filename: The name of the current file.
4148 clean_lines: A CleansedLines instance containing the file.
4149 linenum: The number of the line to check.
4150 error: The function to call with any errors found.
4151 """
4152 line = clean_lines.elided[linenum]
4153
4154 # Avoid preprocessor lines
4155 if Match(r'^\s*#', line):
4156 return
4157
4158 # Last ditch effort to avoid multi-line comments. This will not help
4159 # if the comment started before the current line or ended after the
4160 # current line, but it catches most of the false positives. At least,
4161 # it provides a way to workaround this warning for people who use
4162 # multi-line comments in preprocessor macros.
4163 #
4164 # TODO(unknown): remove this once cpplint has better support for
4165 # multi-line comments.
4166 if line.find('/*') >= 0 or line.find('*/') >= 0:
4167 return
4168
4169 for match in _ALT_TOKEN_REPLACEMENT_PATTERN.finditer(line):
4170 error(filename, linenum, 'readability/alt_tokens', 2,
4171 'Use operator %s instead of %s' % (
4172 _ALT_TOKEN_REPLACEMENT[match.group(1)], match.group(1)))
4173
4174
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004175def GetLineWidth(line):
4176 """Determines the width of the line in column positions.
4177
4178 Args:
4179 line: A string, which may be a Unicode string.
4180
4181 Returns:
4182 The width of the line in column positions, accounting for Unicode
4183 combining characters and wide characters.
4184 """
4185 if isinstance(line, unicode):
4186 width = 0
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004187 for uc in unicodedata.normalize('NFC', line):
4188 if unicodedata.east_asian_width(uc) in ('W', 'F'):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004189 width += 2
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004190 elif not unicodedata.combining(uc):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004191 width += 1
4192 return width
4193 else:
4194 return len(line)
4195
4196
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004197def CheckStyle(filename, clean_lines, linenum, file_extension, nesting_state,
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004198 error):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004199 """Checks rules from the 'C++ style rules' section of cppguide.html.
4200
4201 Most of these rules are hard to test (naming, comment style), but we
4202 do what we can. In particular we check for 2-space indents, line lengths,
4203 tab usage, spaces inside code, etc.
4204
4205 Args:
4206 filename: The name of the current file.
4207 clean_lines: A CleansedLines instance containing the file.
4208 linenum: The number of the line to check.
4209 file_extension: The extension (without the dot) of the filename.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004210 nesting_state: A NestingState instance which maintains information about
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004211 the current stack of nested blocks being parsed.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004212 error: The function to call with any errors found.
4213 """
4214
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004215 # Don't use "elided" lines here, otherwise we can't check commented lines.
4216 # Don't want to use "raw" either, because we don't want to check inside C++11
4217 # raw strings,
4218 raw_lines = clean_lines.lines_without_raw_strings
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004219 line = raw_lines[linenum]
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004220 prev = raw_lines[linenum - 1] if linenum > 0 else ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004221
4222 if line.find('\t') != -1:
4223 error(filename, linenum, 'whitespace/tab', 1,
4224 'Tab found; better to use spaces')
4225
4226 # One or three blank spaces at the beginning of the line is weird; it's
4227 # hard to reconcile that with 2-space indents.
4228 # NOTE: here are the conditions rob pike used for his tests. Mine aren't
4229 # as sophisticated, but it may be worth becoming so: RLENGTH==initial_spaces
4230 # if(RLENGTH > 20) complain = 0;
4231 # if(match($0, " +(error|private|public|protected):")) complain = 0;
4232 # if(match(prev, "&& *$")) complain = 0;
4233 # if(match(prev, "\\|\\| *$")) complain = 0;
4234 # if(match(prev, "[\",=><] *$")) complain = 0;
4235 # if(match($0, " <<")) complain = 0;
4236 # if(match(prev, " +for \\(")) complain = 0;
4237 # if(prevodd && match(prevprev, " +for \\(")) complain = 0;
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004238 scope_or_label_pattern = r'\s*\w+\s*:\s*\\?$'
4239 classinfo = nesting_state.InnermostClass()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004240 initial_spaces = 0
4241 cleansed_line = clean_lines.elided[linenum]
4242 while initial_spaces < len(line) and line[initial_spaces] == ' ':
4243 initial_spaces += 1
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004244 # There are certain situations we allow one space, notably for
4245 # section labels, and also lines containing multi-line raw strings.
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004246 # We also don't check for lines that look like continuation lines
4247 # (of lines ending in double quotes, commas, equals, or angle brackets)
4248 # because the rules for how to indent those are non-trivial.
4249 if (not Search(r'[",=><] *$', prev) and
4250 (initial_spaces == 1 or initial_spaces == 3) and
4251 not Match(scope_or_label_pattern, cleansed_line) and
4252 not (clean_lines.raw_lines[linenum] != line and
4253 Match(r'^\s*""', line))):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004254 error(filename, linenum, 'whitespace/indent', 3,
4255 'Weird number of spaces at line-start. '
4256 'Are you using a 2-space indent?')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004257
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004258 if line and line[-1].isspace():
4259 error(filename, linenum, 'whitespace/end_of_line', 4,
4260 'Line ends in whitespace. Consider deleting these extra spaces.')
4261
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004262 # Check if the line is a header guard.
4263 is_header_guard = False
4264 if file_extension == 'h':
4265 cppvar = GetHeaderGuardCPPVariable(filename)
4266 if (line.startswith('#ifndef %s' % cppvar) or
4267 line.startswith('#define %s' % cppvar) or
4268 line.startswith('#endif // %s' % cppvar)):
4269 is_header_guard = True
4270 # #include lines and header guards can be long, since there's no clean way to
4271 # split them.
erg@google.com6317a9c2009-06-25 00:28:19 +00004272 #
4273 # URLs can be long too. It's possible to split these, but it makes them
4274 # harder to cut&paste.
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004275 #
4276 # The "$Id:...$" comment may also get very long without it being the
4277 # developers fault.
erg@google.com6317a9c2009-06-25 00:28:19 +00004278 if (not line.startswith('#include') and not is_header_guard and
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004279 not Match(r'^\s*//.*http(s?)://\S*$', line) and
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004280 not Match(r'^\s*//\s*[^\s]*$', line) and
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004281 not Match(r'^// \$Id:.*#[0-9]+ \$$', line)):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004282 line_width = GetLineWidth(line)
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004283 if line_width > _line_length:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004284 error(filename, linenum, 'whitespace/line_length', 2,
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004285 'Lines should be <= %i characters long' % _line_length)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004286
4287 if (cleansed_line.count(';') > 1 and
4288 # for loops are allowed two ;'s (and may run over two lines).
4289 cleansed_line.find('for') == -1 and
4290 (GetPreviousNonBlankLine(clean_lines, linenum)[0].find('for') == -1 or
4291 GetPreviousNonBlankLine(clean_lines, linenum)[0].find(';') != -1) and
4292 # It's ok to have many commands in a switch case that fits in 1 line
4293 not ((cleansed_line.find('case ') != -1 or
4294 cleansed_line.find('default:') != -1) and
4295 cleansed_line.find('break;') != -1)):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004296 error(filename, linenum, 'whitespace/newline', 0,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004297 'More than one command on the same line')
4298
4299 # Some more style checks
4300 CheckBraces(filename, clean_lines, linenum, error)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004301 CheckTrailingSemicolon(filename, clean_lines, linenum, error)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004302 CheckEmptyBlockBody(filename, clean_lines, linenum, error)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004303 CheckAccess(filename, clean_lines, linenum, nesting_state, error)
4304 CheckSpacing(filename, clean_lines, linenum, nesting_state, error)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004305 CheckOperatorSpacing(filename, clean_lines, linenum, error)
4306 CheckParenthesisSpacing(filename, clean_lines, linenum, error)
4307 CheckCommaSpacing(filename, clean_lines, linenum, error)
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004308 CheckBracesSpacing(filename, clean_lines, linenum, nesting_state, error)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004309 CheckSpacingForFunctionCall(filename, clean_lines, linenum, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004310 CheckCheck(filename, clean_lines, linenum, error)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004311 CheckAltTokens(filename, clean_lines, linenum, error)
4312 classinfo = nesting_state.InnermostClass()
4313 if classinfo:
4314 CheckSectionSpacing(filename, clean_lines, classinfo, linenum, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004315
4316
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004317_RE_PATTERN_INCLUDE = re.compile(r'^\s*#\s*include\s*([<"])([^>"]*)[>"].*$')
4318# Matches the first component of a filename delimited by -s and _s. That is:
4319# _RE_FIRST_COMPONENT.match('foo').group(0) == 'foo'
4320# _RE_FIRST_COMPONENT.match('foo.cc').group(0) == 'foo'
4321# _RE_FIRST_COMPONENT.match('foo-bar_baz.cc').group(0) == 'foo'
4322# _RE_FIRST_COMPONENT.match('foo_bar-baz.cc').group(0) == 'foo'
4323_RE_FIRST_COMPONENT = re.compile(r'^[^-_.]+')
4324
4325
4326def _DropCommonSuffixes(filename):
4327 """Drops common suffixes like _test.cc or -inl.h from filename.
4328
4329 For example:
4330 >>> _DropCommonSuffixes('foo/foo-inl.h')
4331 'foo/foo'
4332 >>> _DropCommonSuffixes('foo/bar/foo.cc')
4333 'foo/bar/foo'
4334 >>> _DropCommonSuffixes('foo/foo_internal.h')
4335 'foo/foo'
4336 >>> _DropCommonSuffixes('foo/foo_unusualinternal.h')
4337 'foo/foo_unusualinternal'
4338
4339 Args:
4340 filename: The input filename.
4341
4342 Returns:
4343 The filename with the common suffix removed.
4344 """
4345 for suffix in ('test.cc', 'regtest.cc', 'unittest.cc',
4346 'inl.h', 'impl.h', 'internal.h'):
4347 if (filename.endswith(suffix) and len(filename) > len(suffix) and
4348 filename[-len(suffix) - 1] in ('-', '_')):
4349 return filename[:-len(suffix) - 1]
4350 return os.path.splitext(filename)[0]
4351
4352
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004353def _ClassifyInclude(fileinfo, include, is_system):
4354 """Figures out what kind of header 'include' is.
4355
4356 Args:
4357 fileinfo: The current file cpplint is running over. A FileInfo instance.
4358 include: The path to a #included file.
4359 is_system: True if the #include used <> rather than "".
4360
4361 Returns:
4362 One of the _XXX_HEADER constants.
4363
4364 For example:
4365 >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'stdio.h', True)
4366 _C_SYS_HEADER
4367 >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'string', True)
4368 _CPP_SYS_HEADER
4369 >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', False)
4370 _LIKELY_MY_HEADER
4371 >>> _ClassifyInclude(FileInfo('foo/foo_unknown_extension.cc'),
4372 ... 'bar/foo_other_ext.h', False)
4373 _POSSIBLE_MY_HEADER
4374 >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/bar.h', False)
4375 _OTHER_HEADER
4376 """
4377 # This is a list of all standard c++ header files, except
4378 # those already checked for above.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004379 is_cpp_h = include in _CPP_HEADERS
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004380
4381 if is_system:
4382 if is_cpp_h:
4383 return _CPP_SYS_HEADER
4384 else:
4385 return _C_SYS_HEADER
4386
4387 # If the target file and the include we're checking share a
4388 # basename when we drop common extensions, and the include
4389 # lives in . , then it's likely to be owned by the target file.
4390 target_dir, target_base = (
4391 os.path.split(_DropCommonSuffixes(fileinfo.RepositoryName())))
4392 include_dir, include_base = os.path.split(_DropCommonSuffixes(include))
4393 if target_base == include_base and (
4394 include_dir == target_dir or
4395 include_dir == os.path.normpath(target_dir + '/../public')):
4396 return _LIKELY_MY_HEADER
4397
4398 # If the target and include share some initial basename
4399 # component, it's possible the target is implementing the
4400 # include, so it's allowed to be first, but we'll never
4401 # complain if it's not there.
4402 target_first_component = _RE_FIRST_COMPONENT.match(target_base)
4403 include_first_component = _RE_FIRST_COMPONENT.match(include_base)
4404 if (target_first_component and include_first_component and
4405 target_first_component.group(0) ==
4406 include_first_component.group(0)):
4407 return _POSSIBLE_MY_HEADER
4408
4409 return _OTHER_HEADER
4410
4411
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004412
erg@google.com6317a9c2009-06-25 00:28:19 +00004413def CheckIncludeLine(filename, clean_lines, linenum, include_state, error):
4414 """Check rules that are applicable to #include lines.
4415
4416 Strings on #include lines are NOT removed from elided line, to make
4417 certain tasks easier. However, to prevent false positives, checks
4418 applicable to #include lines in CheckLanguage must be put here.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004419
4420 Args:
4421 filename: The name of the current file.
4422 clean_lines: A CleansedLines instance containing the file.
4423 linenum: The number of the line to check.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004424 include_state: An _IncludeState instance in which the headers are inserted.
4425 error: The function to call with any errors found.
4426 """
4427 fileinfo = FileInfo(filename)
erg@google.com6317a9c2009-06-25 00:28:19 +00004428 line = clean_lines.lines[linenum]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004429
4430 # "include" should use the new style "foo/bar.h" instead of just "bar.h"
avakulenko@google.com59146752014-08-11 20:20:55 +00004431 # Only do this check if the included header follows google naming
4432 # conventions. If not, assume that it's a 3rd party API that
4433 # requires special include conventions.
4434 #
4435 # We also make an exception for Lua headers, which follow google
4436 # naming convention but not the include convention.
4437 match = Match(r'#include\s*"([^/]+\.h)"', line)
4438 if match and not _THIRD_PARTY_HEADERS_PATTERN.match(match.group(1)):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004439 error(filename, linenum, 'build/include', 4,
4440 'Include the directory when naming .h files')
4441
4442 # we shouldn't include a file more than once. actually, there are a
4443 # handful of instances where doing so is okay, but in general it's
4444 # not.
erg@google.com6317a9c2009-06-25 00:28:19 +00004445 match = _RE_PATTERN_INCLUDE.search(line)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004446 if match:
4447 include = match.group(2)
4448 is_system = (match.group(1) == '<')
avakulenko@google.com59146752014-08-11 20:20:55 +00004449 duplicate_line = include_state.FindHeader(include)
4450 if duplicate_line >= 0:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004451 error(filename, linenum, 'build/include', 4,
4452 '"%s" already included at %s:%s' %
avakulenko@google.com59146752014-08-11 20:20:55 +00004453 (include, filename, duplicate_line))
avakulenko@google.com255f2be2014-12-05 22:19:55 +00004454 elif (include.endswith('.cc') and
4455 os.path.dirname(fileinfo.RepositoryName()) != os.path.dirname(include)):
4456 error(filename, linenum, 'build/include', 4,
4457 'Do not include .cc files from other packages')
avakulenko@google.com59146752014-08-11 20:20:55 +00004458 elif not _THIRD_PARTY_HEADERS_PATTERN.match(include):
4459 include_state.include_list[-1].append((include, linenum))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004460
4461 # We want to ensure that headers appear in the right order:
4462 # 1) for foo.cc, foo.h (preferred location)
4463 # 2) c system files
4464 # 3) cpp system files
4465 # 4) for foo.cc, foo.h (deprecated location)
4466 # 5) other google headers
4467 #
4468 # We classify each include statement as one of those 5 types
4469 # using a number of techniques. The include_state object keeps
4470 # track of the highest type seen, and complains if we see a
4471 # lower type after that.
4472 error_message = include_state.CheckNextIncludeOrder(
4473 _ClassifyInclude(fileinfo, include, is_system))
4474 if error_message:
4475 error(filename, linenum, 'build/include_order', 4,
4476 '%s. Should be: %s.h, c system, c++ system, other.' %
4477 (error_message, fileinfo.BaseName()))
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004478 canonical_include = include_state.CanonicalizeAlphabeticalOrder(include)
4479 if not include_state.IsInAlphabeticalOrder(
4480 clean_lines, linenum, canonical_include):
erg@google.com26970fa2009-11-17 18:07:32 +00004481 error(filename, linenum, 'build/include_alpha', 4,
4482 'Include "%s" not in alphabetical order' % include)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004483 include_state.SetLastHeader(canonical_include)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004484
erg@google.com6317a9c2009-06-25 00:28:19 +00004485
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004486
4487def _GetTextInside(text, start_pattern):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004488 r"""Retrieves all the text between matching open and close parentheses.
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004489
4490 Given a string of lines and a regular expression string, retrieve all the text
4491 following the expression and between opening punctuation symbols like
4492 (, [, or {, and the matching close-punctuation symbol. This properly nested
4493 occurrences of the punctuations, so for the text like
4494 printf(a(), b(c()));
4495 a call to _GetTextInside(text, r'printf\(') will return 'a(), b(c())'.
4496 start_pattern must match string having an open punctuation symbol at the end.
4497
4498 Args:
4499 text: The lines to extract text. Its comments and strings must be elided.
4500 It can be single line and can span multiple lines.
4501 start_pattern: The regexp string indicating where to start extracting
4502 the text.
4503 Returns:
4504 The extracted text.
4505 None if either the opening string or ending punctuation could not be found.
4506 """
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004507 # TODO(unknown): Audit cpplint.py to see what places could be profitably
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004508 # rewritten to use _GetTextInside (and use inferior regexp matching today).
4509
4510 # Give opening punctuations to get the matching close-punctuations.
4511 matching_punctuation = {'(': ')', '{': '}', '[': ']'}
4512 closing_punctuation = set(matching_punctuation.itervalues())
4513
4514 # Find the position to start extracting text.
4515 match = re.search(start_pattern, text, re.M)
4516 if not match: # start_pattern not found in text.
4517 return None
4518 start_position = match.end(0)
4519
4520 assert start_position > 0, (
4521 'start_pattern must ends with an opening punctuation.')
4522 assert text[start_position - 1] in matching_punctuation, (
4523 'start_pattern must ends with an opening punctuation.')
4524 # Stack of closing punctuations we expect to have in text after position.
4525 punctuation_stack = [matching_punctuation[text[start_position - 1]]]
4526 position = start_position
4527 while punctuation_stack and position < len(text):
4528 if text[position] == punctuation_stack[-1]:
4529 punctuation_stack.pop()
4530 elif text[position] in closing_punctuation:
4531 # A closing punctuation without matching opening punctuations.
4532 return None
4533 elif text[position] in matching_punctuation:
4534 punctuation_stack.append(matching_punctuation[text[position]])
4535 position += 1
4536 if punctuation_stack:
4537 # Opening punctuations left without matching close-punctuations.
4538 return None
4539 # punctuations match.
4540 return text[start_position:position - 1]
4541
4542
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004543# Patterns for matching call-by-reference parameters.
4544#
4545# Supports nested templates up to 2 levels deep using this messy pattern:
4546# < (?: < (?: < [^<>]*
4547# >
4548# | [^<>] )*
4549# >
4550# | [^<>] )*
4551# >
4552_RE_PATTERN_IDENT = r'[_a-zA-Z]\w*' # =~ [[:alpha:]][[:alnum:]]*
4553_RE_PATTERN_TYPE = (
4554 r'(?:const\s+)?(?:typename\s+|class\s+|struct\s+|union\s+|enum\s+)?'
4555 r'(?:\w|'
4556 r'\s*<(?:<(?:<[^<>]*>|[^<>])*>|[^<>])*>|'
4557 r'::)+')
4558# A call-by-reference parameter ends with '& identifier'.
4559_RE_PATTERN_REF_PARAM = re.compile(
4560 r'(' + _RE_PATTERN_TYPE + r'(?:\s*(?:\bconst\b|[*]))*\s*'
4561 r'&\s*' + _RE_PATTERN_IDENT + r')\s*(?:=[^,()]+)?[,)]')
4562# A call-by-const-reference parameter either ends with 'const& identifier'
4563# or looks like 'const type& identifier' when 'type' is atomic.
4564_RE_PATTERN_CONST_REF_PARAM = (
4565 r'(?:.*\s*\bconst\s*&\s*' + _RE_PATTERN_IDENT +
4566 r'|const\s+' + _RE_PATTERN_TYPE + r'\s*&\s*' + _RE_PATTERN_IDENT + r')')
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004567# Stream types.
4568_RE_PATTERN_REF_STREAM_PARAM = (
4569 r'(?:.*stream\s*&\s*' + _RE_PATTERN_IDENT + r')')
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004570
4571
4572def CheckLanguage(filename, clean_lines, linenum, file_extension,
4573 include_state, nesting_state, error):
erg@google.com6317a9c2009-06-25 00:28:19 +00004574 """Checks rules from the 'C++ language rules' section of cppguide.html.
4575
4576 Some of these rules are hard to test (function overloading, using
4577 uint32 inappropriately), but we do the best we can.
4578
4579 Args:
4580 filename: The name of the current file.
4581 clean_lines: A CleansedLines instance containing the file.
4582 linenum: The number of the line to check.
4583 file_extension: The extension (without the dot) of the filename.
4584 include_state: An _IncludeState instance in which the headers are inserted.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004585 nesting_state: A NestingState instance which maintains information about
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004586 the current stack of nested blocks being parsed.
erg@google.com6317a9c2009-06-25 00:28:19 +00004587 error: The function to call with any errors found.
4588 """
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004589 # If the line is empty or consists of entirely a comment, no need to
4590 # check it.
4591 line = clean_lines.elided[linenum]
4592 if not line:
4593 return
4594
erg@google.com6317a9c2009-06-25 00:28:19 +00004595 match = _RE_PATTERN_INCLUDE.search(line)
4596 if match:
4597 CheckIncludeLine(filename, clean_lines, linenum, include_state, error)
4598 return
4599
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004600 # Reset include state across preprocessor directives. This is meant
4601 # to silence warnings for conditional includes.
avakulenko@google.com59146752014-08-11 20:20:55 +00004602 match = Match(r'^\s*#\s*(if|ifdef|ifndef|elif|else|endif)\b', line)
4603 if match:
4604 include_state.ResetSection(match.group(1))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004605
4606 # Make Windows paths like Unix.
4607 fullname = os.path.abspath(filename).replace('\\', '/')
skym@chromium.org3990c412016-02-05 20:55:12 +00004608
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004609 # Perform other checks now that we are sure that this is not an include line
4610 CheckCasts(filename, clean_lines, linenum, error)
4611 CheckGlobalStatic(filename, clean_lines, linenum, error)
4612 CheckPrintf(filename, clean_lines, linenum, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004613
4614 if file_extension == 'h':
4615 # TODO(unknown): check that 1-arg constructors are explicit.
4616 # How to tell it's a constructor?
4617 # (handled in CheckForNonStandardConstructs for now)
avakulenko@google.com59146752014-08-11 20:20:55 +00004618 # TODO(unknown): check that classes declare or disable copy/assign
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004619 # (level 1 error)
4620 pass
4621
4622 # Check if people are using the verboten C basic types. The only exception
4623 # we regularly allow is "unsigned short port" for port.
4624 if Search(r'\bshort port\b', line):
4625 if not Search(r'\bunsigned short port\b', line):
4626 error(filename, linenum, 'runtime/int', 4,
4627 'Use "unsigned short" for ports, not "short"')
4628 else:
4629 match = Search(r'\b(short|long(?! +double)|long long)\b', line)
4630 if match:
4631 error(filename, linenum, 'runtime/int', 4,
4632 'Use int16/int64/etc, rather than the C type %s' % match.group(1))
4633
erg@google.com26970fa2009-11-17 18:07:32 +00004634 # Check if some verboten operator overloading is going on
4635 # TODO(unknown): catch out-of-line unary operator&:
4636 # class X {};
4637 # int operator&(const X& x) { return 42; } // unary operator&
4638 # The trick is it's hard to tell apart from binary operator&:
4639 # class Y { int operator&(const Y& x) { return 23; } }; // binary operator&
4640 if Search(r'\boperator\s*&\s*\(\s*\)', line):
4641 error(filename, linenum, 'runtime/operator', 4,
4642 'Unary operator& is dangerous. Do not use it.')
4643
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004644 # Check for suspicious usage of "if" like
4645 # } if (a == b) {
4646 if Search(r'\}\s*if\s*\(', line):
4647 error(filename, linenum, 'readability/braces', 4,
4648 'Did you mean "else if"? If not, start a new line for "if".')
4649
4650 # Check for potential format string bugs like printf(foo).
4651 # We constrain the pattern not to pick things like DocidForPrintf(foo).
4652 # Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str())
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004653 # TODO(unknown): Catch the following case. Need to change the calling
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004654 # convention of the whole function to process multiple line to handle it.
4655 # printf(
4656 # boy_this_is_a_really_long_variable_that_cannot_fit_on_the_prev_line);
4657 printf_args = _GetTextInside(line, r'(?i)\b(string)?printf\s*\(')
4658 if printf_args:
4659 match = Match(r'([\w.\->()]+)$', printf_args)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004660 if match and match.group(1) != '__VA_ARGS__':
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004661 function_name = re.search(r'\b((?:string)?printf)\s*\(',
4662 line, re.I).group(1)
4663 error(filename, linenum, 'runtime/printf', 4,
4664 'Potential format string bug. Do %s("%%s", %s) instead.'
4665 % (function_name, match.group(1)))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004666
4667 # Check for potential memset bugs like memset(buf, sizeof(buf), 0).
4668 match = Search(r'memset\s*\(([^,]*),\s*([^,]*),\s*0\s*\)', line)
4669 if match and not Match(r"^''|-?[0-9]+|0x[0-9A-Fa-f]$", match.group(2)):
4670 error(filename, linenum, 'runtime/memset', 4,
4671 'Did you mean "memset(%s, 0, %s)"?'
4672 % (match.group(1), match.group(2)))
4673
4674 if Search(r'\busing namespace\b', line):
4675 error(filename, linenum, 'build/namespaces', 5,
4676 'Do not use namespace using-directives. '
4677 'Use using-declarations instead.')
4678
4679 # Detect variable-length arrays.
4680 match = Match(r'\s*(.+::)?(\w+) [a-z]\w*\[(.+)];', line)
4681 if (match and match.group(2) != 'return' and match.group(2) != 'delete' and
4682 match.group(3).find(']') == -1):
4683 # Split the size using space and arithmetic operators as delimiters.
4684 # If any of the resulting tokens are not compile time constants then
4685 # report the error.
4686 tokens = re.split(r'\s|\+|\-|\*|\/|<<|>>]', match.group(3))
4687 is_const = True
4688 skip_next = False
4689 for tok in tokens:
4690 if skip_next:
4691 skip_next = False
4692 continue
4693
4694 if Search(r'sizeof\(.+\)', tok): continue
4695 if Search(r'arraysize\(\w+\)', tok): continue
4696
4697 tok = tok.lstrip('(')
4698 tok = tok.rstrip(')')
4699 if not tok: continue
4700 if Match(r'\d+', tok): continue
4701 if Match(r'0[xX][0-9a-fA-F]+', tok): continue
4702 if Match(r'k[A-Z0-9]\w*', tok): continue
4703 if Match(r'(.+::)?k[A-Z0-9]\w*', tok): continue
4704 if Match(r'(.+::)?[A-Z][A-Z0-9_]*', tok): continue
4705 # A catch all for tricky sizeof cases, including 'sizeof expression',
4706 # 'sizeof(*type)', 'sizeof(const type)', 'sizeof(struct StructName)'
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004707 # requires skipping the next token because we split on ' ' and '*'.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004708 if tok.startswith('sizeof'):
4709 skip_next = True
4710 continue
4711 is_const = False
4712 break
4713 if not is_const:
4714 error(filename, linenum, 'runtime/arrays', 1,
4715 'Do not use variable-length arrays. Use an appropriately named '
4716 "('k' followed by CamelCase) compile-time constant for the size.")
4717
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004718 # Check for use of unnamed namespaces in header files. Registration
4719 # macros are typically OK, so we allow use of "namespace {" on lines
4720 # that end with backslashes.
4721 if (file_extension == 'h'
4722 and Search(r'\bnamespace\s*{', line)
4723 and line[-1] != '\\'):
4724 error(filename, linenum, 'build/namespaces', 4,
4725 'Do not use unnamed namespaces in header files. See '
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004726 'https://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces'
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004727 ' for more information.')
4728
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004729
4730def CheckGlobalStatic(filename, clean_lines, linenum, error):
4731 """Check for unsafe global or static objects.
4732
4733 Args:
4734 filename: The name of the current file.
4735 clean_lines: A CleansedLines instance containing the file.
4736 linenum: The number of the line to check.
4737 error: The function to call with any errors found.
4738 """
4739 line = clean_lines.elided[linenum]
4740
avakulenko@google.com59146752014-08-11 20:20:55 +00004741 # Match two lines at a time to support multiline declarations
4742 if linenum + 1 < clean_lines.NumLines() and not Search(r'[;({]', line):
4743 line += clean_lines.elided[linenum + 1].strip()
4744
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004745 # Check for people declaring static/global STL strings at the top level.
4746 # This is dangerous because the C++ language does not guarantee that
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004747 # globals with constructors are initialized before the first access, and
4748 # also because globals can be destroyed when some threads are still running.
4749 # TODO(unknown): Generalize this to also find static unique_ptr instances.
4750 # TODO(unknown): File bugs for clang-tidy to find these.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004751 match = Match(
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004752 r'((?:|static +)(?:|const +))(?::*std::)?string( +const)? +'
4753 r'([a-zA-Z0-9_:]+)\b(.*)',
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004754 line)
avakulenko@google.com59146752014-08-11 20:20:55 +00004755
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004756 # Remove false positives:
4757 # - String pointers (as opposed to values).
4758 # string *pointer
4759 # const string *pointer
4760 # string const *pointer
4761 # string *const pointer
4762 #
4763 # - Functions and template specializations.
4764 # string Function<Type>(...
4765 # string Class<Type>::Method(...
4766 #
4767 # - Operators. These are matched separately because operator names
4768 # cross non-word boundaries, and trying to match both operators
4769 # and functions at the same time would decrease accuracy of
4770 # matching identifiers.
4771 # string Class::operator*()
4772 if (match and
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004773 not Search(r'\bstring\b(\s+const)?\s*[\*\&]\s*(const\s+)?\w', line) and
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004774 not Search(r'\boperator\W', line) and
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004775 not Match(r'\s*(<.*>)?(::[a-zA-Z0-9_]+)*\s*\(([^"]|$)', match.group(4))):
4776 if Search(r'\bconst\b', line):
4777 error(filename, linenum, 'runtime/string', 4,
4778 'For a static/global string constant, use a C style string '
4779 'instead: "%schar%s %s[]".' %
4780 (match.group(1), match.group(2) or '', match.group(3)))
4781 else:
4782 error(filename, linenum, 'runtime/string', 4,
4783 'Static/global string variables are not permitted.')
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004784
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004785 if (Search(r'\b([A-Za-z0-9_]*_)\(\1\)', line) or
4786 Search(r'\b([A-Za-z0-9_]*_)\(CHECK_NOTNULL\(\1\)\)', line)):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004787 error(filename, linenum, 'runtime/init', 4,
4788 'You seem to be initializing a member variable with itself.')
4789
4790
4791def CheckPrintf(filename, clean_lines, linenum, error):
4792 """Check for printf related issues.
4793
4794 Args:
4795 filename: The name of the current file.
4796 clean_lines: A CleansedLines instance containing the file.
4797 linenum: The number of the line to check.
4798 error: The function to call with any errors found.
4799 """
4800 line = clean_lines.elided[linenum]
4801
4802 # When snprintf is used, the second argument shouldn't be a literal.
4803 match = Search(r'snprintf\s*\(([^,]*),\s*([0-9]*)\s*,', line)
4804 if match and match.group(2) != '0':
4805 # If 2nd arg is zero, snprintf is used to calculate size.
4806 error(filename, linenum, 'runtime/printf', 3,
4807 'If you can, use sizeof(%s) instead of %s as the 2nd arg '
4808 'to snprintf.' % (match.group(1), match.group(2)))
4809
4810 # Check if some verboten C functions are being used.
avakulenko@google.com59146752014-08-11 20:20:55 +00004811 if Search(r'\bsprintf\s*\(', line):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004812 error(filename, linenum, 'runtime/printf', 5,
4813 'Never use sprintf. Use snprintf instead.')
avakulenko@google.com59146752014-08-11 20:20:55 +00004814 match = Search(r'\b(strcpy|strcat)\s*\(', line)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004815 if match:
4816 error(filename, linenum, 'runtime/printf', 4,
4817 'Almost always, snprintf is better than %s' % match.group(1))
4818
4819
4820def IsDerivedFunction(clean_lines, linenum):
4821 """Check if current line contains an inherited function.
4822
4823 Args:
4824 clean_lines: A CleansedLines instance containing the file.
4825 linenum: The number of the line to check.
4826 Returns:
4827 True if current line contains a function with "override"
4828 virt-specifier.
4829 """
avakulenko@google.com59146752014-08-11 20:20:55 +00004830 # Scan back a few lines for start of current function
4831 for i in xrange(linenum, max(-1, linenum - 10), -1):
4832 match = Match(r'^([^()]*\w+)\(', clean_lines.elided[i])
4833 if match:
4834 # Look for "override" after the matching closing parenthesis
4835 line, _, closing_paren = CloseExpression(
4836 clean_lines, i, len(match.group(1)))
4837 return (closing_paren >= 0 and
4838 Search(r'\boverride\b', line[closing_paren:]))
4839 return False
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004840
4841
avakulenko@google.com255f2be2014-12-05 22:19:55 +00004842def IsOutOfLineMethodDefinition(clean_lines, linenum):
4843 """Check if current line contains an out-of-line method definition.
4844
4845 Args:
4846 clean_lines: A CleansedLines instance containing the file.
4847 linenum: The number of the line to check.
4848 Returns:
4849 True if current line contains an out-of-line method definition.
4850 """
4851 # Scan back a few lines for start of current function
4852 for i in xrange(linenum, max(-1, linenum - 10), -1):
4853 if Match(r'^([^()]*\w+)\(', clean_lines.elided[i]):
4854 return Match(r'^[^()]*\w+::\w+\(', clean_lines.elided[i]) is not None
4855 return False
4856
4857
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004858def IsInitializerList(clean_lines, linenum):
4859 """Check if current line is inside constructor initializer list.
4860
4861 Args:
4862 clean_lines: A CleansedLines instance containing the file.
4863 linenum: The number of the line to check.
4864 Returns:
4865 True if current line appears to be inside constructor initializer
4866 list, False otherwise.
4867 """
4868 for i in xrange(linenum, 1, -1):
4869 line = clean_lines.elided[i]
4870 if i == linenum:
4871 remove_function_body = Match(r'^(.*)\{\s*$', line)
4872 if remove_function_body:
4873 line = remove_function_body.group(1)
4874
4875 if Search(r'\s:\s*\w+[({]', line):
4876 # A lone colon tend to indicate the start of a constructor
4877 # initializer list. It could also be a ternary operator, which
4878 # also tend to appear in constructor initializer lists as
4879 # opposed to parameter lists.
4880 return True
4881 if Search(r'\}\s*,\s*$', line):
4882 # A closing brace followed by a comma is probably the end of a
4883 # brace-initialized member in constructor initializer list.
4884 return True
4885 if Search(r'[{};]\s*$', line):
4886 # Found one of the following:
4887 # - A closing brace or semicolon, probably the end of the previous
4888 # function.
4889 # - An opening brace, probably the start of current class or namespace.
4890 #
4891 # Current line is probably not inside an initializer list since
4892 # we saw one of those things without seeing the starting colon.
4893 return False
4894
4895 # Got to the beginning of the file without seeing the start of
4896 # constructor initializer list.
4897 return False
4898
4899
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004900def CheckForNonConstReference(filename, clean_lines, linenum,
4901 nesting_state, error):
4902 """Check for non-const references.
4903
4904 Separate from CheckLanguage since it scans backwards from current
4905 line, instead of scanning forward.
4906
4907 Args:
4908 filename: The name of the current file.
4909 clean_lines: A CleansedLines instance containing the file.
4910 linenum: The number of the line to check.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004911 nesting_state: A NestingState instance which maintains information about
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004912 the current stack of nested blocks being parsed.
4913 error: The function to call with any errors found.
4914 """
4915 # Do nothing if there is no '&' on current line.
4916 line = clean_lines.elided[linenum]
4917 if '&' not in line:
4918 return
4919
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004920 # If a function is inherited, current function doesn't have much of
4921 # a choice, so any non-const references should not be blamed on
4922 # derived function.
4923 if IsDerivedFunction(clean_lines, linenum):
4924 return
4925
avakulenko@google.com255f2be2014-12-05 22:19:55 +00004926 # Don't warn on out-of-line method definitions, as we would warn on the
4927 # in-line declaration, if it isn't marked with 'override'.
4928 if IsOutOfLineMethodDefinition(clean_lines, linenum):
4929 return
4930
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004931 # Long type names may be broken across multiple lines, usually in one
4932 # of these forms:
4933 # LongType
4934 # ::LongTypeContinued &identifier
4935 # LongType::
4936 # LongTypeContinued &identifier
4937 # LongType<
4938 # ...>::LongTypeContinued &identifier
4939 #
4940 # If we detected a type split across two lines, join the previous
4941 # line to current line so that we can match const references
4942 # accordingly.
4943 #
4944 # Note that this only scans back one line, since scanning back
4945 # arbitrary number of lines would be expensive. If you have a type
4946 # that spans more than 2 lines, please use a typedef.
4947 if linenum > 1:
4948 previous = None
4949 if Match(r'\s*::(?:[\w<>]|::)+\s*&\s*\S', line):
4950 # previous_line\n + ::current_line
4951 previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+[\w<>])\s*$',
4952 clean_lines.elided[linenum - 1])
4953 elif Match(r'\s*[a-zA-Z_]([\w<>]|::)+\s*&\s*\S', line):
4954 # previous_line::\n + current_line
4955 previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+::)\s*$',
4956 clean_lines.elided[linenum - 1])
4957 if previous:
4958 line = previous.group(1) + line.lstrip()
4959 else:
4960 # Check for templated parameter that is split across multiple lines
4961 endpos = line.rfind('>')
4962 if endpos > -1:
4963 (_, startline, startpos) = ReverseCloseExpression(
4964 clean_lines, linenum, endpos)
4965 if startpos > -1 and startline < linenum:
4966 # Found the matching < on an earlier line, collect all
4967 # pieces up to current line.
4968 line = ''
4969 for i in xrange(startline, linenum + 1):
4970 line += clean_lines.elided[i].strip()
4971
4972 # Check for non-const references in function parameters. A single '&' may
4973 # found in the following places:
4974 # inside expression: binary & for bitwise AND
4975 # inside expression: unary & for taking the address of something
4976 # inside declarators: reference parameter
4977 # We will exclude the first two cases by checking that we are not inside a
4978 # function body, including one that was just introduced by a trailing '{'.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004979 # TODO(unknown): Doesn't account for 'catch(Exception& e)' [rare].
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004980 if (nesting_state.previous_stack_top and
4981 not (isinstance(nesting_state.previous_stack_top, _ClassInfo) or
4982 isinstance(nesting_state.previous_stack_top, _NamespaceInfo))):
4983 # Not at toplevel, not within a class, and not within a namespace
4984 return
4985
avakulenko@google.com59146752014-08-11 20:20:55 +00004986 # Avoid initializer lists. We only need to scan back from the
4987 # current line for something that starts with ':'.
4988 #
4989 # We don't need to check the current line, since the '&' would
4990 # appear inside the second set of parentheses on the current line as
4991 # opposed to the first set.
4992 if linenum > 0:
4993 for i in xrange(linenum - 1, max(0, linenum - 10), -1):
4994 previous_line = clean_lines.elided[i]
4995 if not Search(r'[),]\s*$', previous_line):
4996 break
4997 if Match(r'^\s*:\s+\S', previous_line):
4998 return
4999
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005000 # Avoid preprocessors
5001 if Search(r'\\\s*$', line):
5002 return
5003
5004 # Avoid constructor initializer lists
5005 if IsInitializerList(clean_lines, linenum):
5006 return
5007
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005008 # We allow non-const references in a few standard places, like functions
5009 # called "swap()" or iostream operators like "<<" or ">>". Do not check
5010 # those function parameters.
5011 #
5012 # We also accept & in static_assert, which looks like a function but
5013 # it's actually a declaration expression.
5014 whitelisted_functions = (r'(?:[sS]wap(?:<\w:+>)?|'
5015 r'operator\s*[<>][<>]|'
5016 r'static_assert|COMPILE_ASSERT'
5017 r')\s*\(')
5018 if Search(whitelisted_functions, line):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005019 return
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005020 elif not Search(r'\S+\([^)]*$', line):
5021 # Don't see a whitelisted function on this line. Actually we
5022 # didn't see any function name on this line, so this is likely a
5023 # multi-line parameter list. Try a bit harder to catch this case.
5024 for i in xrange(2):
5025 if (linenum > i and
5026 Search(whitelisted_functions, clean_lines.elided[linenum - i - 1])):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005027 return
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005028
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005029 decls = ReplaceAll(r'{[^}]*}', ' ', line) # exclude function body
5030 for parameter in re.findall(_RE_PATTERN_REF_PARAM, decls):
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005031 if (not Match(_RE_PATTERN_CONST_REF_PARAM, parameter) and
5032 not Match(_RE_PATTERN_REF_STREAM_PARAM, parameter)):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005033 error(filename, linenum, 'runtime/references', 2,
5034 'Is this a non-const reference? '
5035 'If so, make const or use a pointer: ' +
5036 ReplaceAll(' *<', '<', parameter))
5037
5038
5039def CheckCasts(filename, clean_lines, linenum, error):
5040 """Various cast related checks.
5041
5042 Args:
5043 filename: The name of the current file.
5044 clean_lines: A CleansedLines instance containing the file.
5045 linenum: The number of the line to check.
5046 error: The function to call with any errors found.
5047 """
5048 line = clean_lines.elided[linenum]
5049
5050 # Check to see if they're using an conversion function cast.
5051 # I just try to capture the most common basic types, though there are more.
5052 # Parameterless conversion functions, such as bool(), are allowed as they are
5053 # probably a member operator declaration or default constructor.
5054 match = Search(
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005055 r'(\bnew\s+(?:const\s+)?|\S<\s*(?:const\s+)?)?\b'
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005056 r'(int|float|double|bool|char|int32|uint32|int64|uint64)'
5057 r'(\([^)].*)', line)
5058 expecting_function = ExpectingFunctionArgs(clean_lines, linenum)
5059 if match and not expecting_function:
5060 matched_type = match.group(2)
5061
5062 # matched_new_or_template is used to silence two false positives:
5063 # - New operators
5064 # - Template arguments with function types
5065 #
5066 # For template arguments, we match on types immediately following
5067 # an opening bracket without any spaces. This is a fast way to
5068 # silence the common case where the function type is the first
5069 # template argument. False negative with less-than comparison is
5070 # avoided because those operators are usually followed by a space.
5071 #
5072 # function<double(double)> // bracket + no space = false positive
5073 # value < double(42) // bracket + space = true positive
5074 matched_new_or_template = match.group(1)
5075
avakulenko@google.com59146752014-08-11 20:20:55 +00005076 # Avoid arrays by looking for brackets that come after the closing
5077 # parenthesis.
5078 if Match(r'\([^()]+\)\s*\[', match.group(3)):
5079 return
5080
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005081 # Other things to ignore:
5082 # - Function pointers
5083 # - Casts to pointer types
5084 # - Placement new
5085 # - Alias declarations
5086 matched_funcptr = match.group(3)
5087 if (matched_new_or_template is None and
5088 not (matched_funcptr and
5089 (Match(r'\((?:[^() ]+::\s*\*\s*)?[^() ]+\)\s*\(',
5090 matched_funcptr) or
5091 matched_funcptr.startswith('(*)'))) and
5092 not Match(r'\s*using\s+\S+\s*=\s*' + matched_type, line) and
5093 not Search(r'new\(\S+\)\s*' + matched_type, line)):
5094 error(filename, linenum, 'readability/casting', 4,
5095 'Using deprecated casting style. '
5096 'Use static_cast<%s>(...) instead' %
5097 matched_type)
5098
5099 if not expecting_function:
avakulenko@google.com59146752014-08-11 20:20:55 +00005100 CheckCStyleCast(filename, clean_lines, linenum, 'static_cast',
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005101 r'\((int|float|double|bool|char|u?int(16|32|64))\)', error)
5102
5103 # This doesn't catch all cases. Consider (const char * const)"hello".
5104 #
5105 # (char *) "foo" should always be a const_cast (reinterpret_cast won't
5106 # compile).
avakulenko@google.com59146752014-08-11 20:20:55 +00005107 if CheckCStyleCast(filename, clean_lines, linenum, 'const_cast',
5108 r'\((char\s?\*+\s?)\)\s*"', error):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005109 pass
5110 else:
5111 # Check pointer casts for other than string constants
avakulenko@google.com59146752014-08-11 20:20:55 +00005112 CheckCStyleCast(filename, clean_lines, linenum, 'reinterpret_cast',
5113 r'\((\w+\s?\*+\s?)\)', error)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005114
5115 # In addition, we look for people taking the address of a cast. This
5116 # is dangerous -- casts can assign to temporaries, so the pointer doesn't
5117 # point where you think.
avakulenko@google.com59146752014-08-11 20:20:55 +00005118 #
5119 # Some non-identifier character is required before the '&' for the
5120 # expression to be recognized as a cast. These are casts:
5121 # expression = &static_cast<int*>(temporary());
5122 # function(&(int*)(temporary()));
5123 #
5124 # This is not a cast:
5125 # reference_type&(int* function_param);
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005126 match = Search(
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005127 r'(?:[^\w]&\(([^)*][^)]*)\)[\w(])|'
avakulenko@google.com59146752014-08-11 20:20:55 +00005128 r'(?:[^\w]&(static|dynamic|down|reinterpret)_cast\b)', line)
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005129 if match:
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005130 # Try a better error message when the & is bound to something
5131 # dereferenced by the casted pointer, as opposed to the casted
5132 # pointer itself.
5133 parenthesis_error = False
5134 match = Match(r'^(.*&(?:static|dynamic|down|reinterpret)_cast\b)<', line)
5135 if match:
5136 _, y1, x1 = CloseExpression(clean_lines, linenum, len(match.group(1)))
5137 if x1 >= 0 and clean_lines.elided[y1][x1] == '(':
5138 _, y2, x2 = CloseExpression(clean_lines, y1, x1)
5139 if x2 >= 0:
5140 extended_line = clean_lines.elided[y2][x2:]
5141 if y2 < clean_lines.NumLines() - 1:
5142 extended_line += clean_lines.elided[y2 + 1]
5143 if Match(r'\s*(?:->|\[)', extended_line):
5144 parenthesis_error = True
5145
5146 if parenthesis_error:
5147 error(filename, linenum, 'readability/casting', 4,
5148 ('Are you taking an address of something dereferenced '
5149 'from a cast? Wrapping the dereferenced expression in '
5150 'parentheses will make the binding more obvious'))
5151 else:
5152 error(filename, linenum, 'runtime/casting', 4,
5153 ('Are you taking an address of a cast? '
5154 'This is dangerous: could be a temp var. '
5155 'Take the address before doing the cast, rather than after'))
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005156
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005157
avakulenko@google.com59146752014-08-11 20:20:55 +00005158def CheckCStyleCast(filename, clean_lines, linenum, cast_type, pattern, error):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005159 """Checks for a C-style cast by looking for the pattern.
5160
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005161 Args:
5162 filename: The name of the current file.
avakulenko@google.com59146752014-08-11 20:20:55 +00005163 clean_lines: A CleansedLines instance containing the file.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005164 linenum: The number of the line to check.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005165 cast_type: The string for the C++ cast to recommend. This is either
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005166 reinterpret_cast, static_cast, or const_cast, depending.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005167 pattern: The regular expression used to find C-style casts.
5168 error: The function to call with any errors found.
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005169
5170 Returns:
5171 True if an error was emitted.
5172 False otherwise.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005173 """
avakulenko@google.com59146752014-08-11 20:20:55 +00005174 line = clean_lines.elided[linenum]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005175 match = Search(pattern, line)
5176 if not match:
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005177 return False
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005178
avakulenko@google.com59146752014-08-11 20:20:55 +00005179 # Exclude lines with keywords that tend to look like casts
5180 context = line[0:match.start(1) - 1]
5181 if Match(r'.*\b(?:sizeof|alignof|alignas|[_A-Z][_A-Z0-9]*)\s*$', context):
5182 return False
5183
5184 # Try expanding current context to see if we one level of
5185 # parentheses inside a macro.
5186 if linenum > 0:
5187 for i in xrange(linenum - 1, max(0, linenum - 5), -1):
5188 context = clean_lines.elided[i] + context
5189 if Match(r'.*\b[_A-Z][_A-Z0-9]*\s*\((?:\([^()]*\)|[^()])*$', context):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005190 return False
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005191
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005192 # operator++(int) and operator--(int)
avakulenko@google.com59146752014-08-11 20:20:55 +00005193 if context.endswith(' operator++') or context.endswith(' operator--'):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005194 return False
5195
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005196 # A single unnamed argument for a function tends to look like old style cast.
5197 # If we see those, don't issue warnings for deprecated casts.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005198 remainder = line[match.end(0):]
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005199 if Match(r'^\s*(?:;|const\b|throw\b|final\b|override\b|[=>{),]|->)',
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005200 remainder):
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005201 return False
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005202
5203 # At this point, all that should be left is actual casts.
5204 error(filename, linenum, 'readability/casting', 4,
5205 'Using C-style cast. Use %s<%s>(...) instead' %
5206 (cast_type, match.group(1)))
5207
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005208 return True
5209
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005210
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005211def ExpectingFunctionArgs(clean_lines, linenum):
5212 """Checks whether where function type arguments are expected.
5213
5214 Args:
5215 clean_lines: A CleansedLines instance containing the file.
5216 linenum: The number of the line to check.
5217
5218 Returns:
5219 True if the line at 'linenum' is inside something that expects arguments
5220 of function types.
5221 """
5222 line = clean_lines.elided[linenum]
5223 return (Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line) or
5224 (linenum >= 2 and
5225 (Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\((?:\S+,)?\s*$',
5226 clean_lines.elided[linenum - 1]) or
5227 Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\(\s*$',
5228 clean_lines.elided[linenum - 2]) or
5229 Search(r'\bstd::m?function\s*\<\s*$',
5230 clean_lines.elided[linenum - 1]))))
5231
5232
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005233_HEADERS_CONTAINING_TEMPLATES = (
5234 ('<deque>', ('deque',)),
5235 ('<functional>', ('unary_function', 'binary_function',
5236 'plus', 'minus', 'multiplies', 'divides', 'modulus',
5237 'negate',
5238 'equal_to', 'not_equal_to', 'greater', 'less',
5239 'greater_equal', 'less_equal',
5240 'logical_and', 'logical_or', 'logical_not',
5241 'unary_negate', 'not1', 'binary_negate', 'not2',
5242 'bind1st', 'bind2nd',
5243 'pointer_to_unary_function',
5244 'pointer_to_binary_function',
5245 'ptr_fun',
5246 'mem_fun_t', 'mem_fun', 'mem_fun1_t', 'mem_fun1_ref_t',
5247 'mem_fun_ref_t',
5248 'const_mem_fun_t', 'const_mem_fun1_t',
5249 'const_mem_fun_ref_t', 'const_mem_fun1_ref_t',
5250 'mem_fun_ref',
5251 )),
5252 ('<limits>', ('numeric_limits',)),
5253 ('<list>', ('list',)),
5254 ('<map>', ('map', 'multimap',)),
lhchavez2d1b6da2016-07-13 10:40:01 -07005255 ('<memory>', ('allocator', 'make_shared', 'make_unique', 'shared_ptr',
5256 'unique_ptr', 'weak_ptr')),
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005257 ('<queue>', ('queue', 'priority_queue',)),
5258 ('<set>', ('set', 'multiset',)),
5259 ('<stack>', ('stack',)),
5260 ('<string>', ('char_traits', 'basic_string',)),
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005261 ('<tuple>', ('tuple',)),
lhchavez2d1b6da2016-07-13 10:40:01 -07005262 ('<unordered_map>', ('unordered_map', 'unordered_multimap')),
5263 ('<unordered_set>', ('unordered_set', 'unordered_multiset')),
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005264 ('<utility>', ('pair',)),
5265 ('<vector>', ('vector',)),
5266
5267 # gcc extensions.
5268 # Note: std::hash is their hash, ::hash is our hash
5269 ('<hash_map>', ('hash_map', 'hash_multimap',)),
5270 ('<hash_set>', ('hash_set', 'hash_multiset',)),
5271 ('<slist>', ('slist',)),
5272 )
5273
skym@chromium.org3990c412016-02-05 20:55:12 +00005274_HEADERS_MAYBE_TEMPLATES = (
5275 ('<algorithm>', ('copy', 'max', 'min', 'min_element', 'sort',
5276 'transform',
5277 )),
lhchavez2d1b6da2016-07-13 10:40:01 -07005278 ('<utility>', ('forward', 'make_pair', 'move', 'swap')),
skym@chromium.org3990c412016-02-05 20:55:12 +00005279 )
5280
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005281_RE_PATTERN_STRING = re.compile(r'\bstring\b')
5282
skym@chromium.org3990c412016-02-05 20:55:12 +00005283_re_pattern_headers_maybe_templates = []
5284for _header, _templates in _HEADERS_MAYBE_TEMPLATES:
5285 for _template in _templates:
5286 # Match max<type>(..., ...), max(..., ...), but not foo->max, foo.max or
5287 # type::max().
5288 _re_pattern_headers_maybe_templates.append(
5289 (re.compile(r'[^>.]\b' + _template + r'(<.*?>)?\([^\)]'),
5290 _template,
5291 _header))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005292
skym@chromium.org3990c412016-02-05 20:55:12 +00005293# Other scripts may reach in and modify this pattern.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005294_re_pattern_templates = []
5295for _header, _templates in _HEADERS_CONTAINING_TEMPLATES:
5296 for _template in _templates:
5297 _re_pattern_templates.append(
5298 (re.compile(r'(\<|\b)' + _template + r'\s*\<'),
5299 _template + '<>',
5300 _header))
5301
5302
erg@google.com6317a9c2009-06-25 00:28:19 +00005303def FilesBelongToSameModule(filename_cc, filename_h):
5304 """Check if these two filenames belong to the same module.
5305
5306 The concept of a 'module' here is a as follows:
5307 foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the
5308 same 'module' if they are in the same directory.
5309 some/path/public/xyzzy and some/path/internal/xyzzy are also considered
5310 to belong to the same module here.
5311
5312 If the filename_cc contains a longer path than the filename_h, for example,
5313 '/absolute/path/to/base/sysinfo.cc', and this file would include
5314 'base/sysinfo.h', this function also produces the prefix needed to open the
5315 header. This is used by the caller of this function to more robustly open the
5316 header file. We don't have access to the real include paths in this context,
5317 so we need this guesswork here.
5318
5319 Known bugs: tools/base/bar.cc and base/bar.h belong to the same module
5320 according to this implementation. Because of this, this function gives
5321 some false positives. This should be sufficiently rare in practice.
5322
5323 Args:
5324 filename_cc: is the path for the .cc file
5325 filename_h: is the path for the header path
5326
5327 Returns:
5328 Tuple with a bool and a string:
5329 bool: True if filename_cc and filename_h belong to the same module.
5330 string: the additional prefix needed to open the header file.
5331 """
5332
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005333 fileinfo = FileInfo(filename_cc)
5334 if not fileinfo.IsSource():
erg@google.com6317a9c2009-06-25 00:28:19 +00005335 return (False, '')
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005336 filename_cc = filename_cc[:-len(fileinfo.Extension())]
5337 matched_test_suffix = Search(_TEST_FILE_SUFFIX, fileinfo.BaseName())
5338 if matched_test_suffix:
5339 filename_cc = filename_cc[:-len(matched_test_suffix.group(1))]
erg@google.com6317a9c2009-06-25 00:28:19 +00005340 filename_cc = filename_cc.replace('/public/', '/')
5341 filename_cc = filename_cc.replace('/internal/', '/')
5342
5343 if not filename_h.endswith('.h'):
5344 return (False, '')
5345 filename_h = filename_h[:-len('.h')]
5346 if filename_h.endswith('-inl'):
5347 filename_h = filename_h[:-len('-inl')]
5348 filename_h = filename_h.replace('/public/', '/')
5349 filename_h = filename_h.replace('/internal/', '/')
5350
5351 files_belong_to_same_module = filename_cc.endswith(filename_h)
5352 common_path = ''
5353 if files_belong_to_same_module:
5354 common_path = filename_cc[:-len(filename_h)]
5355 return files_belong_to_same_module, common_path
5356
5357
avakulenko@google.com59146752014-08-11 20:20:55 +00005358def UpdateIncludeState(filename, include_dict, io=codecs):
5359 """Fill up the include_dict with new includes found from the file.
erg@google.com6317a9c2009-06-25 00:28:19 +00005360
5361 Args:
5362 filename: the name of the header to read.
avakulenko@google.com59146752014-08-11 20:20:55 +00005363 include_dict: a dictionary in which the headers are inserted.
erg@google.com6317a9c2009-06-25 00:28:19 +00005364 io: The io factory to use to read the file. Provided for testability.
5365
5366 Returns:
avakulenko@google.com59146752014-08-11 20:20:55 +00005367 True if a header was successfully added. False otherwise.
erg@google.com6317a9c2009-06-25 00:28:19 +00005368 """
5369 headerfile = None
5370 try:
5371 headerfile = io.open(filename, 'r', 'utf8', 'replace')
5372 except IOError:
5373 return False
5374 linenum = 0
5375 for line in headerfile:
5376 linenum += 1
5377 clean_line = CleanseComments(line)
5378 match = _RE_PATTERN_INCLUDE.search(clean_line)
5379 if match:
5380 include = match.group(2)
avakulenko@google.com59146752014-08-11 20:20:55 +00005381 include_dict.setdefault(include, linenum)
erg@google.com6317a9c2009-06-25 00:28:19 +00005382 return True
5383
5384
5385def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error,
5386 io=codecs):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005387 """Reports for missing stl includes.
5388
5389 This function will output warnings to make sure you are including the headers
5390 necessary for the stl containers and functions that you use. We only give one
5391 reason to include a header. For example, if you use both equal_to<> and
5392 less<> in a .h file, only one (the latter in the file) of these will be
5393 reported as a reason to include the <functional>.
5394
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005395 Args:
5396 filename: The name of the current file.
5397 clean_lines: A CleansedLines instance containing the file.
5398 include_state: An _IncludeState instance.
5399 error: The function to call with any errors found.
erg@google.com6317a9c2009-06-25 00:28:19 +00005400 io: The IO factory to use to read the header file. Provided for unittest
5401 injection.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005402 """
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005403 required = {} # A map of header name to linenumber and the template entity.
5404 # Example of required: { '<functional>': (1219, 'less<>') }
5405
5406 for linenum in xrange(clean_lines.NumLines()):
5407 line = clean_lines.elided[linenum]
5408 if not line or line[0] == '#':
5409 continue
5410
5411 # String is special -- it is a non-templatized type in STL.
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005412 matched = _RE_PATTERN_STRING.search(line)
5413 if matched:
erg@google.com35589e62010-11-17 18:58:16 +00005414 # Don't warn about strings in non-STL namespaces:
5415 # (We check only the first match per line; good enough.)
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005416 prefix = line[:matched.start()]
erg@google.com35589e62010-11-17 18:58:16 +00005417 if prefix.endswith('std::') or not prefix.endswith('::'):
5418 required['<string>'] = (linenum, 'string')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005419
skym@chromium.org3990c412016-02-05 20:55:12 +00005420 for pattern, template, header in _re_pattern_headers_maybe_templates:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005421 if pattern.search(line):
5422 required[header] = (linenum, template)
5423
5424 # The following function is just a speed up, no semantics are changed.
5425 if not '<' in line: # Reduces the cpu time usage by skipping lines.
5426 continue
5427
5428 for pattern, template, header in _re_pattern_templates:
lhchavez9b2173c2016-07-13 10:20:07 -07005429 matched = pattern.search(line)
5430 if matched:
5431 # Don't warn about IWYU in non-STL namespaces:
5432 # (We check only the first match per line; good enough.)
5433 prefix = line[:matched.start()]
5434 if prefix.endswith('std::') or not prefix.endswith('::'):
5435 required[header] = (linenum, template)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005436
erg@google.com6317a9c2009-06-25 00:28:19 +00005437 # The policy is that if you #include something in foo.h you don't need to
5438 # include it again in foo.cc. Here, we will look at possible includes.
avakulenko@google.com59146752014-08-11 20:20:55 +00005439 # Let's flatten the include_state include_list and copy it into a dictionary.
5440 include_dict = dict([item for sublist in include_state.include_list
5441 for item in sublist])
erg@google.com6317a9c2009-06-25 00:28:19 +00005442
avakulenko@google.com59146752014-08-11 20:20:55 +00005443 # Did we find the header for this file (if any) and successfully load it?
erg@google.com6317a9c2009-06-25 00:28:19 +00005444 header_found = False
5445
5446 # Use the absolute path so that matching works properly.
erg@chromium.org8f927562012-01-30 19:51:28 +00005447 abs_filename = FileInfo(filename).FullName()
erg@google.com6317a9c2009-06-25 00:28:19 +00005448
5449 # For Emacs's flymake.
5450 # If cpplint is invoked from Emacs's flymake, a temporary file is generated
5451 # by flymake and that file name might end with '_flymake.cc'. In that case,
5452 # restore original file name here so that the corresponding header file can be
5453 # found.
5454 # e.g. If the file name is 'foo_flymake.cc', we should search for 'foo.h'
5455 # instead of 'foo_flymake.h'
erg@google.com35589e62010-11-17 18:58:16 +00005456 abs_filename = re.sub(r'_flymake\.cc$', '.cc', abs_filename)
erg@google.com6317a9c2009-06-25 00:28:19 +00005457
avakulenko@google.com59146752014-08-11 20:20:55 +00005458 # include_dict is modified during iteration, so we iterate over a copy of
erg@google.com6317a9c2009-06-25 00:28:19 +00005459 # the keys.
avakulenko@google.com59146752014-08-11 20:20:55 +00005460 header_keys = include_dict.keys()
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005461 for header in header_keys:
erg@google.com6317a9c2009-06-25 00:28:19 +00005462 (same_module, common_path) = FilesBelongToSameModule(abs_filename, header)
5463 fullpath = common_path + header
avakulenko@google.com59146752014-08-11 20:20:55 +00005464 if same_module and UpdateIncludeState(fullpath, include_dict, io):
erg@google.com6317a9c2009-06-25 00:28:19 +00005465 header_found = True
5466
5467 # If we can't find the header file for a .cc, assume it's because we don't
5468 # know where to look. In that case we'll give up as we're not sure they
5469 # didn't include it in the .h file.
5470 # TODO(unknown): Do a better job of finding .h files so we are confident that
5471 # not having the .h file means there isn't one.
5472 if filename.endswith('.cc') and not header_found:
5473 return
5474
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005475 # All the lines have been processed, report the errors found.
5476 for required_header_unstripped in required:
5477 template = required[required_header_unstripped][1]
avakulenko@google.com59146752014-08-11 20:20:55 +00005478 if required_header_unstripped.strip('<>"') not in include_dict:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005479 error(filename, required[required_header_unstripped][0],
5480 'build/include_what_you_use', 4,
5481 'Add #include ' + required_header_unstripped + ' for ' + template)
5482
5483
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005484_RE_PATTERN_EXPLICIT_MAKEPAIR = re.compile(r'\bmake_pair\s*<')
5485
5486
5487def CheckMakePairUsesDeduction(filename, clean_lines, linenum, error):
5488 """Check that make_pair's template arguments are deduced.
5489
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005490 G++ 4.6 in C++11 mode fails badly if make_pair's template arguments are
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005491 specified explicitly, and such use isn't intended in any case.
5492
5493 Args:
5494 filename: The name of the current file.
5495 clean_lines: A CleansedLines instance containing the file.
5496 linenum: The number of the line to check.
5497 error: The function to call with any errors found.
5498 """
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005499 line = clean_lines.elided[linenum]
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005500 match = _RE_PATTERN_EXPLICIT_MAKEPAIR.search(line)
5501 if match:
5502 error(filename, linenum, 'build/explicit_make_pair',
5503 4, # 4 = high confidence
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005504 'For C++11-compatibility, omit template arguments from make_pair'
5505 ' OR use pair directly OR if appropriate, construct a pair directly')
avakulenko@google.com59146752014-08-11 20:20:55 +00005506
5507
avakulenko@google.com59146752014-08-11 20:20:55 +00005508def CheckRedundantVirtual(filename, clean_lines, linenum, error):
5509 """Check if line contains a redundant "virtual" function-specifier.
5510
5511 Args:
5512 filename: The name of the current file.
5513 clean_lines: A CleansedLines instance containing the file.
5514 linenum: The number of the line to check.
5515 error: The function to call with any errors found.
5516 """
5517 # Look for "virtual" on current line.
5518 line = clean_lines.elided[linenum]
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005519 virtual = Match(r'^(.*)(\bvirtual\b)(.*)$', line)
avakulenko@google.com59146752014-08-11 20:20:55 +00005520 if not virtual: return
5521
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005522 # Ignore "virtual" keywords that are near access-specifiers. These
5523 # are only used in class base-specifier and do not apply to member
5524 # functions.
5525 if (Search(r'\b(public|protected|private)\s+$', virtual.group(1)) or
5526 Match(r'^\s+(public|protected|private)\b', virtual.group(3))):
5527 return
5528
5529 # Ignore the "virtual" keyword from virtual base classes. Usually
5530 # there is a column on the same line in these cases (virtual base
5531 # classes are rare in google3 because multiple inheritance is rare).
5532 if Match(r'^.*[^:]:[^:].*$', line): return
5533
avakulenko@google.com59146752014-08-11 20:20:55 +00005534 # Look for the next opening parenthesis. This is the start of the
5535 # parameter list (possibly on the next line shortly after virtual).
5536 # TODO(unknown): doesn't work if there are virtual functions with
5537 # decltype() or other things that use parentheses, but csearch suggests
5538 # that this is rare.
5539 end_col = -1
5540 end_line = -1
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005541 start_col = len(virtual.group(2))
avakulenko@google.com59146752014-08-11 20:20:55 +00005542 for start_line in xrange(linenum, min(linenum + 3, clean_lines.NumLines())):
5543 line = clean_lines.elided[start_line][start_col:]
5544 parameter_list = Match(r'^([^(]*)\(', line)
5545 if parameter_list:
5546 # Match parentheses to find the end of the parameter list
5547 (_, end_line, end_col) = CloseExpression(
5548 clean_lines, start_line, start_col + len(parameter_list.group(1)))
5549 break
5550 start_col = 0
5551
5552 if end_col < 0:
5553 return # Couldn't find end of parameter list, give up
5554
5555 # Look for "override" or "final" after the parameter list
5556 # (possibly on the next few lines).
5557 for i in xrange(end_line, min(end_line + 3, clean_lines.NumLines())):
5558 line = clean_lines.elided[i][end_col:]
5559 match = Search(r'\b(override|final)\b', line)
5560 if match:
5561 error(filename, linenum, 'readability/inheritance', 4,
5562 ('"virtual" is redundant since function is '
5563 'already declared as "%s"' % match.group(1)))
5564
5565 # Set end_col to check whole lines after we are done with the
5566 # first line.
5567 end_col = 0
5568 if Search(r'[^\w]\s*$', line):
5569 break
5570
5571
5572def CheckRedundantOverrideOrFinal(filename, clean_lines, linenum, error):
5573 """Check if line contains a redundant "override" or "final" virt-specifier.
5574
5575 Args:
5576 filename: The name of the current file.
5577 clean_lines: A CleansedLines instance containing the file.
5578 linenum: The number of the line to check.
5579 error: The function to call with any errors found.
5580 """
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005581 # Look for closing parenthesis nearby. We need one to confirm where
5582 # the declarator ends and where the virt-specifier starts to avoid
5583 # false positives.
avakulenko@google.com59146752014-08-11 20:20:55 +00005584 line = clean_lines.elided[linenum]
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005585 declarator_end = line.rfind(')')
5586 if declarator_end >= 0:
5587 fragment = line[declarator_end:]
5588 else:
5589 if linenum > 1 and clean_lines.elided[linenum - 1].rfind(')') >= 0:
5590 fragment = line
5591 else:
5592 return
5593
5594 # Check that at most one of "override" or "final" is present, not both
5595 if Search(r'\boverride\b', fragment) and Search(r'\bfinal\b', fragment):
avakulenko@google.com59146752014-08-11 20:20:55 +00005596 error(filename, linenum, 'readability/inheritance', 4,
5597 ('"override" is redundant since function is '
5598 'already declared as "final"'))
5599
5600
5601
5602
5603# Returns true if we are at a new block, and it is directly
5604# inside of a namespace.
5605def IsBlockInNameSpace(nesting_state, is_forward_declaration):
5606 """Checks that the new block is directly in a namespace.
5607
5608 Args:
5609 nesting_state: The _NestingState object that contains info about our state.
5610 is_forward_declaration: If the class is a forward declared class.
5611 Returns:
5612 Whether or not the new block is directly in a namespace.
5613 """
5614 if is_forward_declaration:
5615 if len(nesting_state.stack) >= 1 and (
5616 isinstance(nesting_state.stack[-1], _NamespaceInfo)):
5617 return True
5618 else:
5619 return False
5620
5621 return (len(nesting_state.stack) > 1 and
5622 nesting_state.stack[-1].check_namespace_indentation and
5623 isinstance(nesting_state.stack[-2], _NamespaceInfo))
5624
5625
5626def ShouldCheckNamespaceIndentation(nesting_state, is_namespace_indent_item,
5627 raw_lines_no_comments, linenum):
5628 """This method determines if we should apply our namespace indentation check.
5629
5630 Args:
5631 nesting_state: The current nesting state.
5632 is_namespace_indent_item: If we just put a new class on the stack, True.
5633 If the top of the stack is not a class, or we did not recently
5634 add the class, False.
5635 raw_lines_no_comments: The lines without the comments.
5636 linenum: The current line number we are processing.
5637
5638 Returns:
5639 True if we should apply our namespace indentation check. Currently, it
5640 only works for classes and namespaces inside of a namespace.
5641 """
5642
5643 is_forward_declaration = IsForwardClassDeclaration(raw_lines_no_comments,
5644 linenum)
5645
5646 if not (is_namespace_indent_item or is_forward_declaration):
5647 return False
5648
5649 # If we are in a macro, we do not want to check the namespace indentation.
5650 if IsMacroDefinition(raw_lines_no_comments, linenum):
5651 return False
5652
5653 return IsBlockInNameSpace(nesting_state, is_forward_declaration)
5654
5655
5656# Call this method if the line is directly inside of a namespace.
5657# If the line above is blank (excluding comments) or the start of
5658# an inner namespace, it cannot be indented.
5659def CheckItemIndentationInNamespace(filename, raw_lines_no_comments, linenum,
5660 error):
5661 line = raw_lines_no_comments[linenum]
5662 if Match(r'^\s+', line):
5663 error(filename, linenum, 'runtime/indentation_namespace', 4,
5664 'Do not indent within a namespace')
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005665
5666
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005667def ProcessLine(filename, file_extension, clean_lines, line,
5668 include_state, function_state, nesting_state, error,
5669 extra_check_functions=[]):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005670 """Processes a single line in the file.
5671
5672 Args:
5673 filename: Filename of the file that is being processed.
5674 file_extension: The extension (dot not included) of the file.
5675 clean_lines: An array of strings, each representing a line of the file,
5676 with comments stripped.
5677 line: Number of line being processed.
5678 include_state: An _IncludeState instance in which the headers are inserted.
5679 function_state: A _FunctionState instance which counts function lines, etc.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005680 nesting_state: A NestingState instance which maintains information about
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005681 the current stack of nested blocks being parsed.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005682 error: A callable to which errors are reported, which takes 4 arguments:
5683 filename, line number, error level, and message
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005684 extra_check_functions: An array of additional check functions that will be
5685 run on each source line. Each function takes 4
5686 arguments: filename, clean_lines, line, error
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005687 """
5688 raw_lines = clean_lines.raw_lines
erg@google.com35589e62010-11-17 18:58:16 +00005689 ParseNolintSuppressions(filename, raw_lines[line], line, error)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005690 nesting_state.Update(filename, clean_lines, line, error)
avakulenko@google.com59146752014-08-11 20:20:55 +00005691 CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line,
5692 error)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005693 if nesting_state.InAsmBlock(): return
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005694 CheckForFunctionLengths(filename, clean_lines, line, function_state, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005695 CheckForMultilineCommentsAndStrings(filename, clean_lines, line, error)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005696 CheckStyle(filename, clean_lines, line, file_extension, nesting_state, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005697 CheckLanguage(filename, clean_lines, line, file_extension, include_state,
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005698 nesting_state, error)
5699 CheckForNonConstReference(filename, clean_lines, line, nesting_state, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005700 CheckForNonStandardConstructs(filename, clean_lines, line,
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005701 nesting_state, error)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005702 CheckVlogArguments(filename, clean_lines, line, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005703 CheckPosixThreading(filename, clean_lines, line, error)
erg@google.com6317a9c2009-06-25 00:28:19 +00005704 CheckInvalidIncrement(filename, clean_lines, line, error)
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005705 CheckMakePairUsesDeduction(filename, clean_lines, line, error)
avakulenko@google.com59146752014-08-11 20:20:55 +00005706 CheckRedundantVirtual(filename, clean_lines, line, error)
5707 CheckRedundantOverrideOrFinal(filename, clean_lines, line, error)
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005708 for check_fn in extra_check_functions:
5709 check_fn(filename, clean_lines, line, error)
avakulenko@google.com17449932014-07-28 22:13:33 +00005710
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005711def FlagCxx11Features(filename, clean_lines, linenum, error):
5712 """Flag those c++11 features that we only allow in certain places.
5713
5714 Args:
5715 filename: The name of the current file.
5716 clean_lines: A CleansedLines instance containing the file.
5717 linenum: The number of the line to check.
5718 error: The function to call with any errors found.
5719 """
5720 line = clean_lines.elided[linenum]
5721
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005722 include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line)
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005723
5724 # Flag unapproved C++ TR1 headers.
5725 if include and include.group(1).startswith('tr1/'):
5726 error(filename, linenum, 'build/c++tr1', 5,
5727 ('C++ TR1 headers such as <%s> are unapproved.') % include.group(1))
5728
5729 # Flag unapproved C++11 headers.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005730 if include and include.group(1) in ('cfenv',
5731 'condition_variable',
5732 'fenv.h',
5733 'future',
5734 'mutex',
5735 'thread',
5736 'chrono',
5737 'ratio',
5738 'regex',
5739 'system_error',
5740 ):
5741 error(filename, linenum, 'build/c++11', 5,
5742 ('<%s> is an unapproved C++11 header.') % include.group(1))
5743
5744 # The only place where we need to worry about C++11 keywords and library
5745 # features in preprocessor directives is in macro definitions.
5746 if Match(r'\s*#', line) and not Match(r'\s*#\s*define\b', line): return
5747
5748 # These are classes and free functions. The classes are always
5749 # mentioned as std::*, but we only catch the free functions if
5750 # they're not found by ADL. They're alphabetical by header.
5751 for top_name in (
5752 # type_traits
5753 'alignment_of',
5754 'aligned_union',
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005755 ):
5756 if Search(r'\bstd::%s\b' % top_name, line):
5757 error(filename, linenum, 'build/c++11', 5,
5758 ('std::%s is an unapproved C++11 class or function. Send c-style '
5759 'an example of where it would make your code more readable, and '
5760 'they may let you use it.') % top_name)
5761
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005762
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005763def FlagCxx14Features(filename, clean_lines, linenum, error):
5764 """Flag those C++14 features that we restrict.
5765
5766 Args:
5767 filename: The name of the current file.
5768 clean_lines: A CleansedLines instance containing the file.
5769 linenum: The number of the line to check.
5770 error: The function to call with any errors found.
5771 """
5772 line = clean_lines.elided[linenum]
5773
5774 include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line)
5775
5776 # Flag unapproved C++14 headers.
5777 if include and include.group(1) in ('scoped_allocator', 'shared_mutex'):
5778 error(filename, linenum, 'build/c++14', 5,
5779 ('<%s> is an unapproved C++14 header.') % include.group(1))
5780
5781
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005782def ProcessFileData(filename, file_extension, lines, error,
5783 extra_check_functions=[]):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005784 """Performs lint checks and reports any errors to the given error function.
5785
5786 Args:
5787 filename: Filename of the file that is being processed.
5788 file_extension: The extension (dot not included) of the file.
5789 lines: An array of strings, each representing a line of the file, with the
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005790 last element being empty if the file is terminated with a newline.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005791 error: A callable to which errors are reported, which takes 4 arguments:
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005792 filename, line number, error level, and message
5793 extra_check_functions: An array of additional check functions that will be
5794 run on each source line. Each function takes 4
5795 arguments: filename, clean_lines, line, error
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005796 """
5797 lines = (['// marker so line numbers and indices both start at 1'] + lines +
5798 ['// marker so line numbers end in a known way'])
5799
5800 include_state = _IncludeState()
5801 function_state = _FunctionState()
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005802 nesting_state = NestingState()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005803
erg@google.com35589e62010-11-17 18:58:16 +00005804 ResetNolintSuppressions()
5805
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005806 CheckForCopyright(filename, lines, error)
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005807 ProcessGlobalSuppresions(lines)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005808 RemoveMultiLineComments(filename, lines, error)
5809 clean_lines = CleansedLines(lines)
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005810
5811 if file_extension == 'h':
5812 CheckForHeaderGuard(filename, clean_lines, error)
5813
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005814 for line in xrange(clean_lines.NumLines()):
5815 ProcessLine(filename, file_extension, clean_lines, line,
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005816 include_state, function_state, nesting_state, error,
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005817 extra_check_functions)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005818 FlagCxx11Features(filename, clean_lines, line, error)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005819 nesting_state.CheckCompletedBlocks(filename, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005820
5821 CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error)
skym@chromium.org3990c412016-02-05 20:55:12 +00005822
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005823 # Check that the .cc file has included its header if it exists.
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005824 if _IsSourceExtension(file_extension):
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005825 CheckHeaderFileIncluded(filename, include_state, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005826
5827 # We check here rather than inside ProcessLine so that we see raw
5828 # lines rather than "cleaned" lines.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005829 CheckForBadCharacters(filename, lines, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005830
5831 CheckForNewlineAtEOF(filename, lines, error)
5832
avakulenko@google.com17449932014-07-28 22:13:33 +00005833def ProcessConfigOverrides(filename):
5834 """ Loads the configuration files and processes the config overrides.
5835
5836 Args:
5837 filename: The name of the file being processed by the linter.
5838
5839 Returns:
5840 False if the current |filename| should not be processed further.
5841 """
5842
5843 abs_filename = os.path.abspath(filename)
5844 cfg_filters = []
5845 keep_looking = True
5846 while keep_looking:
5847 abs_path, base_name = os.path.split(abs_filename)
5848 if not base_name:
5849 break # Reached the root directory.
5850
5851 cfg_file = os.path.join(abs_path, "CPPLINT.cfg")
5852 abs_filename = abs_path
5853 if not os.path.isfile(cfg_file):
5854 continue
5855
5856 try:
5857 with open(cfg_file) as file_handle:
5858 for line in file_handle:
5859 line, _, _ = line.partition('#') # Remove comments.
5860 if not line.strip():
5861 continue
5862
5863 name, _, val = line.partition('=')
5864 name = name.strip()
5865 val = val.strip()
5866 if name == 'set noparent':
5867 keep_looking = False
5868 elif name == 'filter':
5869 cfg_filters.append(val)
5870 elif name == 'exclude_files':
5871 # When matching exclude_files pattern, use the base_name of
5872 # the current file name or the directory name we are processing.
5873 # For example, if we are checking for lint errors in /foo/bar/baz.cc
5874 # and we found the .cfg file at /foo/CPPLINT.cfg, then the config
5875 # file's "exclude_files" filter is meant to be checked against "bar"
5876 # and not "baz" nor "bar/baz.cc".
5877 if base_name:
5878 pattern = re.compile(val)
5879 if pattern.match(base_name):
5880 sys.stderr.write('Ignoring "%s": file excluded by "%s". '
5881 'File path component "%s" matches '
5882 'pattern "%s"\n' %
5883 (filename, cfg_file, base_name, val))
5884 return False
avakulenko@google.com68a4fa62014-08-25 16:26:18 +00005885 elif name == 'linelength':
5886 global _line_length
5887 try:
5888 _line_length = int(val)
5889 except ValueError:
5890 sys.stderr.write('Line length must be numeric.')
avakulenko@google.com17449932014-07-28 22:13:33 +00005891 else:
5892 sys.stderr.write(
5893 'Invalid configuration option (%s) in file %s\n' %
5894 (name, cfg_file))
5895
5896 except IOError:
5897 sys.stderr.write(
5898 "Skipping config file '%s': Can't open for reading\n" % cfg_file)
5899 keep_looking = False
5900
5901 # Apply all the accumulated filters in reverse order (top-level directory
5902 # config options having the least priority).
5903 for filter in reversed(cfg_filters):
5904 _AddFilters(filter)
5905
5906 return True
5907
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005908
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005909def ProcessFile(filename, vlevel, extra_check_functions=[]):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005910 """Does google-lint on a single file.
5911
5912 Args:
5913 filename: The name of the file to parse.
5914
5915 vlevel: The level of errors to report. Every error of confidence
5916 >= verbose_level will be reported. 0 is a good default.
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005917
5918 extra_check_functions: An array of additional check functions that will be
5919 run on each source line. Each function takes 4
5920 arguments: filename, clean_lines, line, error
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005921 """
5922
5923 _SetVerboseLevel(vlevel)
avakulenko@google.com17449932014-07-28 22:13:33 +00005924 _BackupFilters()
5925
5926 if not ProcessConfigOverrides(filename):
5927 _RestoreFilters()
5928 return
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005929
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005930 lf_lines = []
5931 crlf_lines = []
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005932 try:
5933 # Support the UNIX convention of using "-" for stdin. Note that
5934 # we are not opening the file with universal newline support
5935 # (which codecs doesn't support anyway), so the resulting lines do
5936 # contain trailing '\r' characters if we are reading a file that
5937 # has CRLF endings.
5938 # If after the split a trailing '\r' is present, it is removed
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005939 # below.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005940 if filename == '-':
5941 lines = codecs.StreamReaderWriter(sys.stdin,
5942 codecs.getreader('utf8'),
5943 codecs.getwriter('utf8'),
5944 'replace').read().split('\n')
5945 else:
5946 lines = codecs.open(filename, 'r', 'utf8', 'replace').read().split('\n')
5947
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005948 # Remove trailing '\r'.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005949 # The -1 accounts for the extra trailing blank line we get from split()
5950 for linenum in range(len(lines) - 1):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005951 if lines[linenum].endswith('\r'):
5952 lines[linenum] = lines[linenum].rstrip('\r')
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005953 crlf_lines.append(linenum + 1)
5954 else:
5955 lf_lines.append(linenum + 1)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005956
5957 except IOError:
5958 sys.stderr.write(
5959 "Skipping input '%s': Can't open for reading\n" % filename)
avakulenko@google.com17449932014-07-28 22:13:33 +00005960 _RestoreFilters()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005961 return
5962
5963 # Note, if no dot is found, this will give the entire filename as the ext.
5964 file_extension = filename[filename.rfind('.') + 1:]
5965
5966 # When reading from stdin, the extension is unknown, so no cpplint tests
5967 # should rely on the extension.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005968 if filename != '-' and file_extension not in _valid_extensions:
5969 sys.stderr.write('Ignoring %s; not a valid file name '
5970 '(%s)\n' % (filename, ', '.join(_valid_extensions)))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005971 else:
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005972 ProcessFileData(filename, file_extension, lines, Error,
5973 extra_check_functions)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005974
5975 # If end-of-line sequences are a mix of LF and CR-LF, issue
5976 # warnings on the lines with CR.
5977 #
5978 # Don't issue any warnings if all lines are uniformly LF or CR-LF,
5979 # since critique can handle these just fine, and the style guide
5980 # doesn't dictate a particular end of line sequence.
5981 #
5982 # We can't depend on os.linesep to determine what the desired
5983 # end-of-line sequence should be, since that will return the
5984 # server-side end-of-line sequence.
5985 if lf_lines and crlf_lines:
5986 # Warn on every line with CR. An alternative approach might be to
5987 # check whether the file is mostly CRLF or just LF, and warn on the
5988 # minority, we bias toward LF here since most tools prefer LF.
5989 for linenum in crlf_lines:
5990 Error(filename, linenum, 'whitespace/newline', 1,
5991 'Unexpected \\r (^M) found; better to use only \\n')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005992
5993 sys.stderr.write('Done processing %s\n' % filename)
avakulenko@google.com17449932014-07-28 22:13:33 +00005994 _RestoreFilters()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005995
5996
5997def PrintUsage(message):
5998 """Prints a brief usage string and exits, optionally with an error message.
5999
6000 Args:
6001 message: The optional error message.
6002 """
6003 sys.stderr.write(_USAGE)
6004 if message:
6005 sys.exit('\nFATAL ERROR: ' + message)
6006 else:
6007 sys.exit(1)
6008
6009
6010def PrintCategories():
6011 """Prints a list of all the error-categories used by error messages.
6012
6013 These are the categories used to filter messages via --filter.
6014 """
erg@google.com35589e62010-11-17 18:58:16 +00006015 sys.stderr.write(''.join(' %s\n' % cat for cat in _ERROR_CATEGORIES))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006016 sys.exit(0)
6017
6018
6019def ParseArguments(args):
6020 """Parses the command line arguments.
6021
6022 This may set the output format and verbosity level as side-effects.
6023
6024 Args:
6025 args: The command line arguments:
6026
6027 Returns:
6028 The list of filenames to lint.
6029 """
6030 try:
6031 (opts, filenames) = getopt.getopt(args, '', ['help', 'output=', 'verbose=',
erg@google.com26970fa2009-11-17 18:07:32 +00006032 'counting=',
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00006033 'filter=',
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00006034 'root=',
6035 'linelength=',
sdefresne263e9282016-07-19 02:14:22 -07006036 'extensions=',
6037 'project_root='])
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006038 except getopt.GetoptError:
6039 PrintUsage('Invalid arguments.')
6040
6041 verbosity = _VerboseLevel()
6042 output_format = _OutputFormat()
6043 filters = ''
erg@google.com26970fa2009-11-17 18:07:32 +00006044 counting_style = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006045
6046 for (opt, val) in opts:
6047 if opt == '--help':
6048 PrintUsage(None)
6049 elif opt == '--output':
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00006050 if val not in ('emacs', 'vs7', 'eclipse'):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00006051 PrintUsage('The only allowed output formats are emacs, vs7 and eclipse.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006052 output_format = val
6053 elif opt == '--verbose':
6054 verbosity = int(val)
6055 elif opt == '--filter':
6056 filters = val
erg@google.com6317a9c2009-06-25 00:28:19 +00006057 if not filters:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006058 PrintCategories()
erg@google.com26970fa2009-11-17 18:07:32 +00006059 elif opt == '--counting':
6060 if val not in ('total', 'toplevel', 'detailed'):
6061 PrintUsage('Valid counting options are total, toplevel, and detailed')
6062 counting_style = val
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00006063 elif opt == '--root':
6064 global _root
6065 _root = val
sdefresne263e9282016-07-19 02:14:22 -07006066 elif opt == '--project_root':
6067 global _project_root
6068 _project_root = val
6069 if not os.path.isabs(_project_root):
6070 PrintUsage('Project root must be an absolute path.')
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00006071 elif opt == '--linelength':
6072 global _line_length
6073 try:
6074 _line_length = int(val)
6075 except ValueError:
6076 PrintUsage('Line length must be digits.')
6077 elif opt == '--extensions':
6078 global _valid_extensions
6079 try:
6080 _valid_extensions = set(val.split(','))
6081 except ValueError:
qyearsley12fa6ff2016-08-24 09:18:40 -07006082 PrintUsage('Extensions must be comma separated list.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006083
6084 if not filenames:
6085 PrintUsage('No files were specified.')
6086
6087 _SetOutputFormat(output_format)
6088 _SetVerboseLevel(verbosity)
6089 _SetFilters(filters)
erg@google.com26970fa2009-11-17 18:07:32 +00006090 _SetCountingStyle(counting_style)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006091
6092 return filenames
6093
6094
6095def main():
6096 filenames = ParseArguments(sys.argv[1:])
6097
6098 # Change stderr to write with replacement characters so we don't die
6099 # if we try to print something containing non-ASCII characters.
6100 sys.stderr = codecs.StreamReaderWriter(sys.stderr,
6101 codecs.getreader('utf8'),
6102 codecs.getwriter('utf8'),
6103 'replace')
6104
erg@google.com26970fa2009-11-17 18:07:32 +00006105 _cpplint_state.ResetErrorCounts()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006106 for filename in filenames:
6107 ProcessFile(filename, _cpplint_state.verbose_level)
erg@google.com26970fa2009-11-17 18:07:32 +00006108 _cpplint_state.PrintErrorCounts()
6109
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006110 sys.exit(_cpplint_state.error_count > 0)
6111
6112
6113if __name__ == '__main__':
6114 main()