blob: 0d4a799d565a4ad20907b75bb89157a5b1b169a3 [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
agablef39c3332016-09-26 09:35:42 -070031# pylint: skip-file
32
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000033"""Does google-lint on c++ files.
34
35The goal of this script is to identify places in the code that *may*
36be in non-compliance with google style. It does not attempt to fix
37up these problems -- the point is to educate. It does also not
38attempt to find all problems, or to ensure that everything it does
39find is legitimately a problem.
40
41In particular, we can get very confused by /* and // inside strings!
42We do a small hack, which is to ignore //'s with "'s after them on the
43same line, but it is far from perfect (in either direction).
44"""
45
46import codecs
mazda@chromium.org3fffcec2013-06-07 01:04:53 +000047import copy
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000048import getopt
49import math # for log
50import os
51import re
52import sre_compile
53import string
54import sys
55import unicodedata
56
57
Edward Lemur6d31ed52019-12-02 23:00:00 +000058_USAGE = r"""
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000059Syntax: cpplint.py [--verbose=#] [--output=vs7] [--filter=-x,+y,...]
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +000060 [--counting=total|toplevel|detailed] [--root=subdir]
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +000061 [--linelength=digits]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000062 <file> [file] ...
63
64 The style guidelines this tries to follow are those in
Alexandr Ilinff294c32017-04-27 15:57:40 +020065 https://google.github.io/styleguide/cppguide.html
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000066
67 Every problem is given a confidence score from 1-5, with 5 meaning we are
68 certain of the problem, and 1 meaning it could be a legitimate construct.
69 This will miss some errors, and is not a substitute for a code review.
70
erg@google.com35589e62010-11-17 18:58:16 +000071 To suppress false-positive errors of a certain category, add a
72 'NOLINT(category)' comment to the line. NOLINT or NOLINT(*)
73 suppresses errors of all categories on that line.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000074
75 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 +000076 Default linted extensions are .cc, .cpp, .cu, .cuh and .h. Change the
77 extensions with the --extensions flag.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000078
79 Flags:
80
81 output=vs7
82 By default, the output is formatted to ease emacs parsing. Visual Studio
83 compatible output (vs7) may also be used. Other formats are unsupported.
84
85 verbose=#
86 Specify a number 0-5 to restrict errors to certain verbosity levels.
87
88 filter=-x,+y,...
89 Specify a comma-separated list of category-filters to apply: only
90 error messages whose category names pass the filters will be printed.
91 (Category names are printed with the message and look like
92 "[whitespace/indent]".) Filters are evaluated left to right.
93 "-FOO" and "FOO" means "do not print categories that start with FOO".
94 "+FOO" means "do print categories that start with FOO".
95
96 Examples: --filter=-whitespace,+whitespace/braces
97 --filter=whitespace,runtime/printf,+runtime/printf_format
98 --filter=-,+build/include_what_you_use
99
100 To see a list of all the categories used in cpplint, pass no arg:
101 --filter=
erg@google.com26970fa2009-11-17 18:07:32 +0000102
103 counting=total|toplevel|detailed
104 The total number of errors found is always printed. If
105 'toplevel' is provided, then the count of errors in each of
106 the top-level categories like 'build' and 'whitespace' will
107 also be printed. If 'detailed' is provided, then a count
108 is provided for each category like 'build/class'.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +0000109
110 root=subdir
111 The root directory used for deriving header guard CPP variable.
112 By default, the header guard CPP variable is calculated as the relative
113 path to the directory that contains .git, .hg, or .svn. When this flag
114 is specified, the relative path is calculated from the specified
115 directory. If the specified directory does not exist, this flag is
116 ignored.
117
118 Examples:
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +0000119 Assuming that src/.git exists, the header guard CPP variables for
120 src/chrome/browser/ui/browser.h are:
mazda@chromium.org3fffcec2013-06-07 01:04:53 +0000121
122 No flag => CHROME_BROWSER_UI_BROWSER_H_
123 --root=chrome => BROWSER_UI_BROWSER_H_
124 --root=chrome/browser => UI_BROWSER_H_
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000125
126 linelength=digits
127 This is the allowed line length for the project. The default value is
128 80 characters.
129
130 Examples:
131 --linelength=120
132
133 extensions=extension,extension,...
134 The allowed file extensions that cpplint will check
135
136 Examples:
137 --extensions=hpp,cpp
avakulenko@google.com17449932014-07-28 22:13:33 +0000138
139 cpplint.py supports per-directory configurations specified in CPPLINT.cfg
140 files. CPPLINT.cfg file can contain a number of key=value pairs.
141 Currently the following options are supported:
142
143 set noparent
144 filter=+filter1,-filter2,...
145 exclude_files=regex
avakulenko@google.com68a4fa62014-08-25 16:26:18 +0000146 linelength=80
avakulenko@google.com17449932014-07-28 22:13:33 +0000147
148 "set noparent" option prevents cpplint from traversing directory tree
149 upwards looking for more .cfg files in parent directories. This option
150 is usually placed in the top-level project directory.
151
152 The "filter" option is similar in function to --filter flag. It specifies
153 message filters in addition to the |_DEFAULT_FILTERS| and those specified
154 through --filter command-line flag.
155
156 "exclude_files" allows to specify a regular expression to be matched against
157 a file name. If the expression matches, the file is skipped and not run
158 through liner.
159
avakulenko@google.com68a4fa62014-08-25 16:26:18 +0000160 "linelength" allows to specify the allowed line length for the project.
161
avakulenko@google.com17449932014-07-28 22:13:33 +0000162 CPPLINT.cfg has an effect on files in the same directory and all
163 sub-directories, unless overridden by a nested configuration file.
164
165 Example file:
166 filter=-build/include_order,+build/include_alpha
167 exclude_files=.*\.cc
168
169 The above example disables build/include_order warning and enables
170 build/include_alpha as well as excludes all .cc from being
171 processed by linter, in the current directory (where the .cfg
172 file is located) and all sub-directories.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000173"""
174
175# We categorize each error message we print. Here are the categories.
176# We want an explicit list so we can list them all in cpplint --filter=.
177# If you add a new error message with a new category, add it to the list
178# here! cpplint_unittest.py should tell you if you forget to do this.
erg@google.com35589e62010-11-17 18:58:16 +0000179_ERROR_CATEGORIES = [
avakulenko@google.com255f2be2014-12-05 22:19:55 +0000180 'build/class',
181 'build/c++11',
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000182 'build/c++14',
183 'build/c++tr1',
avakulenko@google.com255f2be2014-12-05 22:19:55 +0000184 'build/deprecated',
185 'build/endif_comment',
186 'build/explicit_make_pair',
187 'build/forward_decl',
188 'build/header_guard',
189 'build/include',
190 'build/include_alpha',
Fletcher Woodruff11b34152020-04-23 21:21:40 +0000191 'build/include_directory',
avakulenko@google.com255f2be2014-12-05 22:19:55 +0000192 'build/include_order',
193 'build/include_what_you_use',
194 'build/namespaces',
195 'build/printf_format',
196 'build/storage_class',
197 'legal/copyright',
198 'readability/alt_tokens',
199 'readability/braces',
200 'readability/casting',
201 'readability/check',
202 'readability/constructors',
203 'readability/fn_size',
avakulenko@google.com255f2be2014-12-05 22:19:55 +0000204 'readability/inheritance',
205 'readability/multiline_comment',
206 'readability/multiline_string',
207 'readability/namespace',
208 'readability/nolint',
209 'readability/nul',
210 'readability/strings',
211 'readability/todo',
212 'readability/utf8',
213 'runtime/arrays',
214 'runtime/casting',
215 'runtime/explicit',
216 'runtime/int',
217 'runtime/init',
218 'runtime/invalid_increment',
219 'runtime/member_string_references',
220 'runtime/memset',
221 'runtime/indentation_namespace',
222 'runtime/operator',
223 'runtime/printf',
224 'runtime/printf_format',
225 'runtime/references',
226 'runtime/string',
227 'runtime/threadsafe_fn',
228 'runtime/vlog',
229 'whitespace/blank_line',
230 'whitespace/braces',
231 'whitespace/comma',
232 'whitespace/comments',
233 'whitespace/empty_conditional_body',
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000234 'whitespace/empty_if_body',
avakulenko@google.com255f2be2014-12-05 22:19:55 +0000235 'whitespace/empty_loop_body',
236 'whitespace/end_of_line',
237 'whitespace/ending_newline',
238 'whitespace/forcolon',
239 'whitespace/indent',
240 'whitespace/line_length',
241 'whitespace/newline',
242 'whitespace/operators',
243 'whitespace/parens',
244 'whitespace/semicolon',
245 'whitespace/tab',
246 'whitespace/todo',
247 ]
248
249# These error categories are no longer enforced by cpplint, but for backwards-
250# compatibility they may still appear in NOLINT comments.
251_LEGACY_ERROR_CATEGORIES = [
252 'readability/streams',
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000253 'readability/function',
avakulenko@google.com255f2be2014-12-05 22:19:55 +0000254 ]
erg@google.com6317a9c2009-06-25 00:28:19 +0000255
avakulenko@google.comd39bbb52014-06-04 22:55:20 +0000256# The default state of the category filter. This is overridden by the --filter=
erg@google.com6317a9c2009-06-25 00:28:19 +0000257# flag. By default all errors are on, so only add here categories that should be
258# off by default (i.e., categories that must be enabled by the --filter= flags).
259# All entries here should start with a '-' or '+', as in the --filter= flag.
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +0000260_DEFAULT_FILTERS = ['-build/include_alpha']
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000261
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000262# The default list of categories suppressed for C (not C++) files.
263_DEFAULT_C_SUPPRESSED_CATEGORIES = [
264 'readability/casting',
265 ]
266
267# The default list of categories suppressed for Linux Kernel files.
268_DEFAULT_KERNEL_SUPPRESSED_CATEGORIES = [
269 'whitespace/tab',
270 ]
271
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000272# We used to check for high-bit characters, but after much discussion we
273# decided those were OK, as long as they were in UTF-8 and didn't represent
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +0000274# hard-coded international strings, which belong in a separate i18n file.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000275
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000276# C++ headers
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000277_CPP_HEADERS = frozenset([
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000278 # Legacy
279 'algobase.h',
280 'algo.h',
281 'alloc.h',
282 'builtinbuf.h',
283 'bvector.h',
284 'complex.h',
285 'defalloc.h',
286 'deque.h',
287 'editbuf.h',
288 'fstream.h',
289 'function.h',
290 'hash_map',
291 'hash_map.h',
292 'hash_set',
293 'hash_set.h',
294 'hashtable.h',
295 'heap.h',
296 'indstream.h',
297 'iomanip.h',
298 'iostream.h',
299 'istream.h',
300 'iterator.h',
301 'list.h',
302 'map.h',
303 'multimap.h',
304 'multiset.h',
305 'ostream.h',
306 'pair.h',
307 'parsestream.h',
308 'pfstream.h',
309 'procbuf.h',
310 'pthread_alloc',
311 'pthread_alloc.h',
312 'rope',
313 'rope.h',
314 'ropeimpl.h',
315 'set.h',
316 'slist',
317 'slist.h',
318 'stack.h',
319 'stdiostream.h',
320 'stl_alloc.h',
321 'stl_relops.h',
322 'streambuf.h',
323 'stream.h',
324 'strfile.h',
325 'strstream.h',
326 'tempbuf.h',
327 'tree.h',
328 'type_traits.h',
329 'vector.h',
330 # 17.6.1.2 C++ library headers
331 'algorithm',
332 'array',
333 'atomic',
334 'bitset',
335 'chrono',
336 'codecvt',
337 'complex',
338 'condition_variable',
339 'deque',
340 'exception',
341 'forward_list',
342 'fstream',
343 'functional',
344 'future',
345 'initializer_list',
346 'iomanip',
347 'ios',
348 'iosfwd',
349 'iostream',
350 'istream',
351 'iterator',
352 'limits',
353 'list',
354 'locale',
355 'map',
356 'memory',
357 'mutex',
358 'new',
359 'numeric',
360 'ostream',
361 'queue',
362 'random',
363 'ratio',
364 'regex',
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000365 'scoped_allocator',
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000366 'set',
367 'sstream',
368 'stack',
369 'stdexcept',
370 'streambuf',
371 'string',
Jasper Chapman-Black9ab047e2019-11-07 15:51:54 +0000372 'string_view',
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000373 'strstream',
374 'system_error',
375 'thread',
376 'tuple',
377 'typeindex',
378 'typeinfo',
379 'type_traits',
380 'unordered_map',
381 'unordered_set',
382 'utility',
383 'valarray',
384 'vector',
385 # 17.6.1.2 C++ headers for C library facilities
386 'cassert',
387 'ccomplex',
388 'cctype',
389 'cerrno',
390 'cfenv',
391 'cfloat',
392 'cinttypes',
393 'ciso646',
394 'climits',
395 'clocale',
396 'cmath',
397 'csetjmp',
398 'csignal',
399 'cstdalign',
400 'cstdarg',
401 'cstdbool',
402 'cstddef',
403 'cstdint',
404 'cstdio',
405 'cstdlib',
406 'cstring',
407 'ctgmath',
408 'ctime',
409 'cuchar',
410 'cwchar',
411 'cwctype',
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000412 ])
413
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000414# Type names
415_TYPES = re.compile(
416 r'^(?:'
417 # [dcl.type.simple]
418 r'(char(16_t|32_t)?)|wchar_t|'
419 r'bool|short|int|long|signed|unsigned|float|double|'
420 # [support.types]
421 r'(ptrdiff_t|size_t|max_align_t|nullptr_t)|'
422 # [cstdint.syn]
423 r'(u?int(_fast|_least)?(8|16|32|64)_t)|'
424 r'(u?int(max|ptr)_t)|'
425 r')$')
426
avakulenko@google.comd39bbb52014-06-04 22:55:20 +0000427
Fletcher Woodruff11b34152020-04-23 21:21:40 +0000428# These headers are excluded from [build/include], [build/include_directory],
429# and [build/include_order] checks:
avakulenko@google.com59146752014-08-11 20:20:55 +0000430# - Anything not following google file name conventions (containing an
431# uppercase character, such as Python.h or nsStringAPI.h, for example).
432# - Lua headers.
433_THIRD_PARTY_HEADERS_PATTERN = re.compile(
434 r'^(?:[^/]*[A-Z][^/]*\.h|lua\.h|lauxlib\.h|lualib\.h)$')
435
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000436# Pattern for matching FileInfo.BaseName() against test file name
437_TEST_FILE_SUFFIX = r'(_test|_unittest|_regtest)$'
438
439# Pattern that matches only complete whitespace, possibly across multiple lines.
440_EMPTY_CONDITIONAL_BODY_PATTERN = re.compile(r'^\s*$', re.DOTALL)
avakulenko@google.com59146752014-08-11 20:20:55 +0000441
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000442# Assertion macros. These are defined in base/logging.h and
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000443# testing/base/public/gunit.h.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000444_CHECK_MACROS = [
erg@google.com6317a9c2009-06-25 00:28:19 +0000445 'DCHECK', 'CHECK',
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000446 'EXPECT_TRUE', 'ASSERT_TRUE',
447 'EXPECT_FALSE', 'ASSERT_FALSE',
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000448 ]
449
erg@google.com6317a9c2009-06-25 00:28:19 +0000450# Replacement macros for CHECK/DCHECK/EXPECT_TRUE/EXPECT_FALSE
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000451_CHECK_REPLACEMENT = dict([(m, {}) for m in _CHECK_MACROS])
452
453for op, replacement in [('==', 'EQ'), ('!=', 'NE'),
454 ('>=', 'GE'), ('>', 'GT'),
455 ('<=', 'LE'), ('<', 'LT')]:
erg@google.com6317a9c2009-06-25 00:28:19 +0000456 _CHECK_REPLACEMENT['DCHECK'][op] = 'DCHECK_%s' % replacement
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000457 _CHECK_REPLACEMENT['CHECK'][op] = 'CHECK_%s' % replacement
458 _CHECK_REPLACEMENT['EXPECT_TRUE'][op] = 'EXPECT_%s' % replacement
459 _CHECK_REPLACEMENT['ASSERT_TRUE'][op] = 'ASSERT_%s' % replacement
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000460
461for op, inv_replacement in [('==', 'NE'), ('!=', 'EQ'),
462 ('>=', 'LT'), ('>', 'LE'),
463 ('<=', 'GT'), ('<', 'GE')]:
464 _CHECK_REPLACEMENT['EXPECT_FALSE'][op] = 'EXPECT_%s' % inv_replacement
465 _CHECK_REPLACEMENT['ASSERT_FALSE'][op] = 'ASSERT_%s' % inv_replacement
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000466
mazda@chromium.org3fffcec2013-06-07 01:04:53 +0000467# Alternative tokens and their replacements. For full list, see section 2.5
468# Alternative tokens [lex.digraph] in the C++ standard.
469#
470# Digraphs (such as '%:') are not included here since it's a mess to
471# match those on a word boundary.
472_ALT_TOKEN_REPLACEMENT = {
473 'and': '&&',
474 'bitor': '|',
475 'or': '||',
476 'xor': '^',
477 'compl': '~',
478 'bitand': '&',
479 'and_eq': '&=',
480 'or_eq': '|=',
481 'xor_eq': '^=',
482 'not': '!',
483 'not_eq': '!='
484 }
485
486# Compile regular expression that matches all the above keywords. The "[ =()]"
487# bit is meant to avoid matching these keywords outside of boolean expressions.
488#
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000489# False positives include C-style multi-line comments and multi-line strings
490# but those have always been troublesome for cpplint.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +0000491_ALT_TOKEN_REPLACEMENT_PATTERN = re.compile(
492 r'[ =()](' + ('|'.join(_ALT_TOKEN_REPLACEMENT.keys())) + r')(?=[ (]|$)')
493
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000494
495# These constants define types of headers for use with
496# _IncludeState.CheckNextIncludeOrder().
497_C_SYS_HEADER = 1
498_CPP_SYS_HEADER = 2
499_LIKELY_MY_HEADER = 3
500_POSSIBLE_MY_HEADER = 4
501_OTHER_HEADER = 5
502
mazda@chromium.org3fffcec2013-06-07 01:04:53 +0000503# These constants define the current inline assembly state
504_NO_ASM = 0 # Outside of inline assembly block
505_INSIDE_ASM = 1 # Inside inline assembly block
506_END_ASM = 2 # Last line of inline assembly block
507_BLOCK_ASM = 3 # The whole block is an inline assembly block
508
509# Match start of assembly blocks
510_MATCH_ASM = re.compile(r'^\s*(?:asm|_asm|__asm|__asm__)'
511 r'(?:\s+(volatile|__volatile__))?'
512 r'\s*[{(]')
513
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000514# Match strings that indicate we're working on a C (not C++) file.
515_SEARCH_C_FILE = re.compile(r'\b(?:LINT_C_FILE|'
516 r'vim?:\s*.*(\s*|:)filetype=c(\s*|:|$))')
517
518# Match string that indicates we're working on a Linux Kernel file.
519_SEARCH_KERNEL_FILE = re.compile(r'\b(?:LINT_KERNEL_FILE)')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000520
521_regexp_compile_cache = {}
522
erg@google.com35589e62010-11-17 18:58:16 +0000523# {str, set(int)}: a map from error categories to sets of linenumbers
524# on which those errors are expected and should be suppressed.
525_error_suppressions = {}
526
mazda@chromium.org3fffcec2013-06-07 01:04:53 +0000527# The root directory used for deriving header guard CPP variable.
528# This is set by --root flag.
529_root = None
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +0000530
531# The project root directory. Used for deriving header guard CPP variable.
532# This is set by --project_root flag. Must be an absolute path.
533_project_root = None
sdefresne263e9282016-07-19 02:14:22 -0700534
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000535# The allowed line length of files.
536# This is set by --linelength flag.
537_line_length = 80
538
539# The allowed extensions for file names
540# This is set by --extensions flag.
541_valid_extensions = set(['cc', 'h', 'cpp', 'cu', 'cuh'])
542
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000543# {str, bool}: a map from error categories to booleans which indicate if the
544# category should be suppressed for every line.
545_global_error_suppressions = {}
546
547
erg@google.com35589e62010-11-17 18:58:16 +0000548def ParseNolintSuppressions(filename, raw_line, linenum, error):
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000549 """Updates the global list of line error-suppressions.
erg@google.com35589e62010-11-17 18:58:16 +0000550
551 Parses any NOLINT comments on the current line, updating the global
552 error_suppressions store. Reports an error if the NOLINT comment
553 was malformed.
554
555 Args:
556 filename: str, the name of the input file.
557 raw_line: str, the line of input text, with comments.
558 linenum: int, the number of the current line.
559 error: function, an error handler.
560 """
avakulenko@google.com59146752014-08-11 20:20:55 +0000561 matched = Search(r'\bNOLINT(NEXTLINE)?\b(\([^)]+\))?', raw_line)
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +0000562 if matched:
avakulenko@google.com59146752014-08-11 20:20:55 +0000563 if matched.group(1):
564 suppressed_line = linenum + 1
565 else:
566 suppressed_line = linenum
567 category = matched.group(2)
erg@google.com35589e62010-11-17 18:58:16 +0000568 if category in (None, '(*)'): # => "suppress all"
avakulenko@google.com59146752014-08-11 20:20:55 +0000569 _error_suppressions.setdefault(None, set()).add(suppressed_line)
erg@google.com35589e62010-11-17 18:58:16 +0000570 else:
571 if category.startswith('(') and category.endswith(')'):
572 category = category[1:-1]
573 if category in _ERROR_CATEGORIES:
avakulenko@google.com59146752014-08-11 20:20:55 +0000574 _error_suppressions.setdefault(category, set()).add(suppressed_line)
avakulenko@google.com255f2be2014-12-05 22:19:55 +0000575 elif category not in _LEGACY_ERROR_CATEGORIES:
erg@google.com35589e62010-11-17 18:58:16 +0000576 error(filename, linenum, 'readability/nolint', 5,
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +0000577 'Unknown NOLINT error category: %s' % category)
erg@google.com35589e62010-11-17 18:58:16 +0000578
579
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000580def ProcessGlobalSuppresions(lines):
581 """Updates the list of global error suppressions.
582
583 Parses any lint directives in the file that have global effect.
584
585 Args:
586 lines: An array of strings, each representing a line of the file, with the
587 last element being empty if the file is terminated with a newline.
588 """
589 for line in lines:
590 if _SEARCH_C_FILE.search(line):
591 for category in _DEFAULT_C_SUPPRESSED_CATEGORIES:
592 _global_error_suppressions[category] = True
593 if _SEARCH_KERNEL_FILE.search(line):
594 for category in _DEFAULT_KERNEL_SUPPRESSED_CATEGORIES:
595 _global_error_suppressions[category] = True
596
597
erg@google.com35589e62010-11-17 18:58:16 +0000598def ResetNolintSuppressions():
avakulenko@google.com59146752014-08-11 20:20:55 +0000599 """Resets the set of NOLINT suppressions to empty."""
erg@google.com35589e62010-11-17 18:58:16 +0000600 _error_suppressions.clear()
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000601 _global_error_suppressions.clear()
erg@google.com35589e62010-11-17 18:58:16 +0000602
603
604def IsErrorSuppressedByNolint(category, linenum):
605 """Returns true if the specified error category is suppressed on this line.
606
607 Consults the global error_suppressions map populated by
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000608 ParseNolintSuppressions/ProcessGlobalSuppresions/ResetNolintSuppressions.
erg@google.com35589e62010-11-17 18:58:16 +0000609
610 Args:
611 category: str, the category of the error.
612 linenum: int, the current line number.
613 Returns:
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000614 bool, True iff the error should be suppressed due to a NOLINT comment or
615 global suppression.
erg@google.com35589e62010-11-17 18:58:16 +0000616 """
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000617 return (_global_error_suppressions.get(category, False) or
618 linenum in _error_suppressions.get(category, set()) or
erg@google.com35589e62010-11-17 18:58:16 +0000619 linenum in _error_suppressions.get(None, set()))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000620
avakulenko@google.comd39bbb52014-06-04 22:55:20 +0000621
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000622def Match(pattern, s):
623 """Matches the string with the pattern, caching the compiled regexp."""
624 # The regexp compilation caching is inlined in both Match and Search for
625 # performance reasons; factoring it out into a separate function turns out
626 # to be noticeably expensive.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000627 if pattern not in _regexp_compile_cache:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000628 _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
629 return _regexp_compile_cache[pattern].match(s)
630
631
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000632def ReplaceAll(pattern, rep, s):
633 """Replaces instances of pattern in a string with a replacement.
634
635 The compiled regex is kept in a cache shared by Match and Search.
636
637 Args:
638 pattern: regex pattern
639 rep: replacement text
640 s: search string
641
642 Returns:
643 string with replacements made (or original string if no replacements)
644 """
645 if pattern not in _regexp_compile_cache:
646 _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
647 return _regexp_compile_cache[pattern].sub(rep, s)
648
649
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000650def Search(pattern, s):
651 """Searches the string for the pattern, caching the compiled regexp."""
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000652 if pattern not in _regexp_compile_cache:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000653 _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
654 return _regexp_compile_cache[pattern].search(s)
655
656
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000657def _IsSourceExtension(s):
658 """File extension (excluding dot) matches a source file extension."""
659 return s in ('c', 'cc', 'cpp', 'cxx')
660
661
avakulenko@google.com59146752014-08-11 20:20:55 +0000662class _IncludeState(object):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000663 """Tracks line numbers for includes, and the order in which includes appear.
664
avakulenko@google.com59146752014-08-11 20:20:55 +0000665 include_list contains list of lists of (header, line number) pairs.
666 It's a lists of lists rather than just one flat list to make it
667 easier to update across preprocessor boundaries.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000668
669 Call CheckNextIncludeOrder() once for each header in the file, passing
670 in the type constants defined above. Calls in an illegal order will
671 raise an _IncludeError with an appropriate error message.
672
673 """
674 # self._section will move monotonically through this set. If it ever
675 # needs to move backwards, CheckNextIncludeOrder will raise an error.
676 _INITIAL_SECTION = 0
677 _MY_H_SECTION = 1
678 _C_SECTION = 2
679 _CPP_SECTION = 3
680 _OTHER_H_SECTION = 4
681
682 _TYPE_NAMES = {
683 _C_SYS_HEADER: 'C system header',
684 _CPP_SYS_HEADER: 'C++ system header',
685 _LIKELY_MY_HEADER: 'header this file implements',
686 _POSSIBLE_MY_HEADER: 'header this file may implement',
687 _OTHER_HEADER: 'other header',
688 }
689 _SECTION_NAMES = {
690 _INITIAL_SECTION: "... nothing. (This can't be an error.)",
691 _MY_H_SECTION: 'a header this file implements',
692 _C_SECTION: 'C system header',
693 _CPP_SECTION: 'C++ system header',
694 _OTHER_H_SECTION: 'other header',
695 }
696
697 def __init__(self):
avakulenko@google.com59146752014-08-11 20:20:55 +0000698 self.include_list = [[]]
699 self.ResetSection('')
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000700
avakulenko@google.com59146752014-08-11 20:20:55 +0000701 def FindHeader(self, header):
702 """Check if a header has already been included.
703
704 Args:
705 header: header to check.
706 Returns:
707 Line number of previous occurrence, or -1 if the header has not
708 been seen before.
709 """
710 for section_list in self.include_list:
711 for f in section_list:
712 if f[0] == header:
713 return f[1]
714 return -1
715
716 def ResetSection(self, directive):
717 """Reset section checking for preprocessor directive.
718
719 Args:
720 directive: preprocessor directive (e.g. "if", "else").
721 """
erg@google.com26970fa2009-11-17 18:07:32 +0000722 # The name of the current section.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000723 self._section = self._INITIAL_SECTION
erg@google.com26970fa2009-11-17 18:07:32 +0000724 # The path of last found header.
725 self._last_header = ''
726
avakulenko@google.com59146752014-08-11 20:20:55 +0000727 # Update list of includes. Note that we never pop from the
728 # include list.
729 if directive in ('if', 'ifdef', 'ifndef'):
730 self.include_list.append([])
731 elif directive in ('else', 'elif'):
732 self.include_list[-1] = []
733
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000734 def SetLastHeader(self, header_path):
735 self._last_header = header_path
736
erg@google.com26970fa2009-11-17 18:07:32 +0000737 def CanonicalizeAlphabeticalOrder(self, header_path):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +0000738 """Returns a path canonicalized for alphabetical comparison.
erg@google.com26970fa2009-11-17 18:07:32 +0000739
740 - replaces "-" with "_" so they both cmp the same.
741 - removes '-inl' since we don't require them to be after the main header.
742 - lowercase everything, just in case.
743
744 Args:
745 header_path: Path to be canonicalized.
746
747 Returns:
748 Canonicalized path.
749 """
750 return header_path.replace('-inl.h', '.h').replace('-', '_').lower()
751
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000752 def IsInAlphabeticalOrder(self, clean_lines, linenum, header_path):
erg@google.com26970fa2009-11-17 18:07:32 +0000753 """Check if a header is in alphabetical order with the previous header.
754
755 Args:
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000756 clean_lines: A CleansedLines instance containing the file.
757 linenum: The number of the line to check.
758 header_path: Canonicalized header to be checked.
erg@google.com26970fa2009-11-17 18:07:32 +0000759
760 Returns:
761 Returns true if the header is in alphabetical order.
762 """
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000763 # If previous section is different from current section, _last_header will
764 # be reset to empty string, so it's always less than current header.
765 #
766 # If previous line was a blank line, assume that the headers are
767 # intentionally sorted the way they are.
768 if (self._last_header > header_path and
avakulenko@google.com255f2be2014-12-05 22:19:55 +0000769 Match(r'^\s*#\s*include\b', clean_lines.elided[linenum - 1])):
erg@google.com26970fa2009-11-17 18:07:32 +0000770 return False
erg@google.com26970fa2009-11-17 18:07:32 +0000771 return True
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000772
773 def CheckNextIncludeOrder(self, header_type):
774 """Returns a non-empty error message if the next header is out of order.
775
776 This function also updates the internal state to be ready to check
777 the next include.
778
779 Args:
780 header_type: One of the _XXX_HEADER constants defined above.
781
782 Returns:
783 The empty string if the header is in the right order, or an
784 error message describing what's wrong.
785
786 """
787 error_message = ('Found %s after %s' %
788 (self._TYPE_NAMES[header_type],
789 self._SECTION_NAMES[self._section]))
790
erg@google.com26970fa2009-11-17 18:07:32 +0000791 last_section = self._section
792
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000793 if header_type == _C_SYS_HEADER:
794 if self._section <= self._C_SECTION:
795 self._section = self._C_SECTION
796 else:
erg@google.com26970fa2009-11-17 18:07:32 +0000797 self._last_header = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000798 return error_message
799 elif header_type == _CPP_SYS_HEADER:
800 if self._section <= self._CPP_SECTION:
801 self._section = self._CPP_SECTION
802 else:
erg@google.com26970fa2009-11-17 18:07:32 +0000803 self._last_header = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000804 return error_message
805 elif header_type == _LIKELY_MY_HEADER:
806 if self._section <= self._MY_H_SECTION:
807 self._section = self._MY_H_SECTION
808 else:
809 self._section = self._OTHER_H_SECTION
810 elif header_type == _POSSIBLE_MY_HEADER:
811 if self._section <= self._MY_H_SECTION:
812 self._section = self._MY_H_SECTION
813 else:
814 # This will always be the fallback because we're not sure
815 # enough that the header is associated with this file.
816 self._section = self._OTHER_H_SECTION
817 else:
818 assert header_type == _OTHER_HEADER
819 self._section = self._OTHER_H_SECTION
820
erg@google.com26970fa2009-11-17 18:07:32 +0000821 if last_section != self._section:
822 self._last_header = ''
823
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000824 return ''
825
826
827class _CppLintState(object):
828 """Maintains module-wide state.."""
829
830 def __init__(self):
831 self.verbose_level = 1 # global setting.
832 self.error_count = 0 # global count of reported errors
erg@google.com6317a9c2009-06-25 00:28:19 +0000833 # filters to apply when emitting error messages
834 self.filters = _DEFAULT_FILTERS[:]
avakulenko@google.com17449932014-07-28 22:13:33 +0000835 # backup of filter list. Used to restore the state after each file.
836 self._filters_backup = self.filters[:]
erg@google.com26970fa2009-11-17 18:07:32 +0000837 self.counting = 'total' # In what way are we counting errors?
838 self.errors_by_category = {} # string to int dict storing error counts
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000839
840 # output format:
841 # "emacs" - format that emacs can parse (default)
842 # "vs7" - format that Microsoft Visual Studio 7 can parse
843 self.output_format = 'emacs'
844
845 def SetOutputFormat(self, output_format):
846 """Sets the output format for errors."""
847 self.output_format = output_format
848
849 def SetVerboseLevel(self, level):
850 """Sets the module's verbosity, and returns the previous setting."""
851 last_verbose_level = self.verbose_level
852 self.verbose_level = level
853 return last_verbose_level
854
erg@google.com26970fa2009-11-17 18:07:32 +0000855 def SetCountingStyle(self, counting_style):
856 """Sets the module's counting options."""
857 self.counting = counting_style
858
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000859 def SetFilters(self, filters):
860 """Sets the error-message filters.
861
862 These filters are applied when deciding whether to emit a given
863 error message.
864
865 Args:
866 filters: A string of comma-separated filters (eg "+whitespace/indent").
867 Each filter should start with + or -; else we die.
erg@google.com6317a9c2009-06-25 00:28:19 +0000868
869 Raises:
870 ValueError: The comma-separated filters did not all start with '+' or '-'.
871 E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter"
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000872 """
erg@google.com6317a9c2009-06-25 00:28:19 +0000873 # Default filters always have less priority than the flag ones.
874 self.filters = _DEFAULT_FILTERS[:]
avakulenko@google.com17449932014-07-28 22:13:33 +0000875 self.AddFilters(filters)
876
877 def AddFilters(self, filters):
878 """ Adds more filters to the existing list of error-message filters. """
erg@google.com6317a9c2009-06-25 00:28:19 +0000879 for filt in filters.split(','):
880 clean_filt = filt.strip()
881 if clean_filt:
882 self.filters.append(clean_filt)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000883 for filt in self.filters:
884 if not (filt.startswith('+') or filt.startswith('-')):
885 raise ValueError('Every filter in --filters must start with + or -'
886 ' (%s does not)' % filt)
887
avakulenko@google.com17449932014-07-28 22:13:33 +0000888 def BackupFilters(self):
889 """ Saves the current filter list to backup storage."""
890 self._filters_backup = self.filters[:]
891
892 def RestoreFilters(self):
893 """ Restores filters previously backed up."""
894 self.filters = self._filters_backup[:]
895
erg@google.com26970fa2009-11-17 18:07:32 +0000896 def ResetErrorCounts(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000897 """Sets the module's error statistic back to zero."""
898 self.error_count = 0
erg@google.com26970fa2009-11-17 18:07:32 +0000899 self.errors_by_category = {}
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000900
erg@google.com26970fa2009-11-17 18:07:32 +0000901 def IncrementErrorCount(self, category):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000902 """Bumps the module's error statistic."""
903 self.error_count += 1
erg@google.com26970fa2009-11-17 18:07:32 +0000904 if self.counting in ('toplevel', 'detailed'):
905 if self.counting != 'detailed':
906 category = category.split('/')[0]
907 if category not in self.errors_by_category:
908 self.errors_by_category[category] = 0
909 self.errors_by_category[category] += 1
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000910
erg@google.com26970fa2009-11-17 18:07:32 +0000911 def PrintErrorCounts(self):
912 """Print a summary of errors by category, and the total."""
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000913 for category, count in self.errors_by_category.items():
erg@google.com26970fa2009-11-17 18:07:32 +0000914 sys.stderr.write('Category \'%s\' errors found: %d\n' %
915 (category, count))
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +0000916 sys.stderr.write('Total errors found: %d\n' % self.error_count)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000917
918_cpplint_state = _CppLintState()
919
920
921def _OutputFormat():
922 """Gets the module's output format."""
923 return _cpplint_state.output_format
924
925
926def _SetOutputFormat(output_format):
927 """Sets the module's output format."""
928 _cpplint_state.SetOutputFormat(output_format)
929
930
931def _VerboseLevel():
932 """Returns the module's verbosity setting."""
933 return _cpplint_state.verbose_level
934
935
936def _SetVerboseLevel(level):
937 """Sets the module's verbosity, and returns the previous setting."""
938 return _cpplint_state.SetVerboseLevel(level)
939
940
erg@google.com26970fa2009-11-17 18:07:32 +0000941def _SetCountingStyle(level):
942 """Sets the module's counting options."""
943 _cpplint_state.SetCountingStyle(level)
944
945
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000946def _Filters():
947 """Returns the module's list of output filters, as a list."""
948 return _cpplint_state.filters
949
950
951def _SetFilters(filters):
952 """Sets the module's error-message filters.
953
954 These filters are applied when deciding whether to emit a given
955 error message.
956
957 Args:
958 filters: A string of comma-separated filters (eg "whitespace/indent").
959 Each filter should start with + or -; else we die.
960 """
961 _cpplint_state.SetFilters(filters)
962
avakulenko@google.com17449932014-07-28 22:13:33 +0000963def _AddFilters(filters):
964 """Adds more filter overrides.
avakulenko@google.com59146752014-08-11 20:20:55 +0000965
avakulenko@google.com17449932014-07-28 22:13:33 +0000966 Unlike _SetFilters, this function does not reset the current list of filters
967 available.
968
969 Args:
970 filters: A string of comma-separated filters (eg "whitespace/indent").
971 Each filter should start with + or -; else we die.
972 """
973 _cpplint_state.AddFilters(filters)
974
975def _BackupFilters():
976 """ Saves the current filter list to backup storage."""
977 _cpplint_state.BackupFilters()
978
979def _RestoreFilters():
980 """ Restores filters previously backed up."""
981 _cpplint_state.RestoreFilters()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000982
983class _FunctionState(object):
984 """Tracks current function name and the number of lines in its body."""
985
986 _NORMAL_TRIGGER = 250 # for --v=0, 500 for --v=1, etc.
987 _TEST_TRIGGER = 400 # about 50% more than _NORMAL_TRIGGER.
988
989 def __init__(self):
990 self.in_a_function = False
991 self.lines_in_function = 0
992 self.current_function = ''
993
994 def Begin(self, function_name):
995 """Start analyzing function body.
996
997 Args:
998 function_name: The name of the function being tracked.
999 """
1000 self.in_a_function = True
1001 self.lines_in_function = 0
1002 self.current_function = function_name
1003
1004 def Count(self):
1005 """Count line in current function body."""
1006 if self.in_a_function:
1007 self.lines_in_function += 1
1008
1009 def Check(self, error, filename, linenum):
1010 """Report if too many lines in function body.
1011
1012 Args:
1013 error: The function to call with any errors found.
1014 filename: The name of the current file.
1015 linenum: The number of the line to check.
1016 """
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00001017 if not self.in_a_function:
1018 return
1019
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001020 if Match(r'T(EST|est)', self.current_function):
1021 base_trigger = self._TEST_TRIGGER
1022 else:
1023 base_trigger = self._NORMAL_TRIGGER
1024 trigger = base_trigger * 2**_VerboseLevel()
1025
1026 if self.lines_in_function > trigger:
1027 error_level = int(math.log(self.lines_in_function / base_trigger, 2))
1028 # 50 => 0, 100 => 1, 200 => 2, 400 => 3, 800 => 4, 1600 => 5, ...
1029 if error_level > 5:
1030 error_level = 5
1031 error(filename, linenum, 'readability/fn_size', error_level,
1032 'Small and focused functions are preferred:'
1033 ' %s has %d non-comment lines'
1034 ' (error triggered by exceeding %d lines).' % (
1035 self.current_function, self.lines_in_function, trigger))
1036
1037 def End(self):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00001038 """Stop analyzing function body."""
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001039 self.in_a_function = False
1040
1041
1042class _IncludeError(Exception):
1043 """Indicates a problem with the include order in a file."""
1044 pass
1045
1046
avakulenko@google.com59146752014-08-11 20:20:55 +00001047class FileInfo(object):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001048 """Provides utility functions for filenames.
1049
1050 FileInfo provides easy access to the components of a file's path
1051 relative to the project root.
1052 """
1053
1054 def __init__(self, filename):
1055 self._filename = filename
1056
1057 def FullName(self):
1058 """Make Windows paths like Unix."""
1059 return os.path.abspath(self._filename).replace('\\', '/')
1060
1061 def RepositoryName(self):
Edward Lemur6d31ed52019-12-02 23:00:00 +00001062 r"""FullName after removing the local path to the repository.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001063
1064 If we have a real absolute path name here we can try to do something smart:
1065 detecting the root of the checkout and truncating /path/to/checkout from
1066 the name so that we get header guards that don't include things like
1067 "C:\Documents and Settings\..." or "/home/username/..." in them and thus
1068 people on different computers who have checked the source out to different
1069 locations won't see bogus errors.
1070 """
1071 fullname = self.FullName()
1072
1073 if os.path.exists(fullname):
1074 project_dir = os.path.dirname(fullname)
1075
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00001076 if _project_root:
1077 prefix = os.path.commonprefix([_project_root, project_dir])
1078 return fullname[len(prefix) + 1:]
1079
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001080 if os.path.exists(os.path.join(project_dir, ".svn")):
1081 # If there's a .svn file in the current directory, we recursively look
1082 # up the directory tree for the top of the SVN checkout
1083 root_dir = project_dir
1084 one_up_dir = os.path.dirname(root_dir)
1085 while os.path.exists(os.path.join(one_up_dir, ".svn")):
1086 root_dir = os.path.dirname(root_dir)
1087 one_up_dir = os.path.dirname(one_up_dir)
1088
1089 prefix = os.path.commonprefix([root_dir, project_dir])
1090 return fullname[len(prefix) + 1:]
1091
erg@chromium.org7956a872011-11-30 01:44:03 +00001092 # Not SVN <= 1.6? Try to find a git, hg, or svn top level directory by
1093 # searching up from the current path.
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00001094 root_dir = os.path.dirname(fullname)
1095 while (root_dir != os.path.dirname(root_dir) and
1096 not os.path.exists(os.path.join(root_dir, ".git")) and
1097 not os.path.exists(os.path.join(root_dir, ".hg")) and
1098 not os.path.exists(os.path.join(root_dir, ".svn"))):
1099 root_dir = os.path.dirname(root_dir)
erg@google.com35589e62010-11-17 18:58:16 +00001100
1101 if (os.path.exists(os.path.join(root_dir, ".git")) or
erg@chromium.org7956a872011-11-30 01:44:03 +00001102 os.path.exists(os.path.join(root_dir, ".hg")) or
1103 os.path.exists(os.path.join(root_dir, ".svn"))):
erg@google.com35589e62010-11-17 18:58:16 +00001104 prefix = os.path.commonprefix([root_dir, project_dir])
1105 return fullname[len(prefix) + 1:]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001106
1107 # Don't know what to do; header guard warnings may be wrong...
1108 return fullname
1109
1110 def Split(self):
1111 """Splits the file into the directory, basename, and extension.
1112
1113 For 'chrome/browser/browser.cc', Split() would
1114 return ('chrome/browser', 'browser', '.cc')
1115
1116 Returns:
1117 A tuple of (directory, basename, extension).
1118 """
1119
1120 googlename = self.RepositoryName()
1121 project, rest = os.path.split(googlename)
1122 return (project,) + os.path.splitext(rest)
1123
1124 def BaseName(self):
1125 """File base name - text after the final slash, before the final period."""
1126 return self.Split()[1]
1127
1128 def Extension(self):
1129 """File extension - text following the final period."""
1130 return self.Split()[2]
1131
1132 def NoExtension(self):
1133 """File has no source file extension."""
1134 return '/'.join(self.Split()[0:2])
1135
1136 def IsSource(self):
1137 """File has a source file extension."""
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00001138 return _IsSourceExtension(self.Extension()[1:])
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001139
1140
erg@google.com35589e62010-11-17 18:58:16 +00001141def _ShouldPrintError(category, confidence, linenum):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00001142 """If confidence >= verbose, category passes filter and is not suppressed."""
erg@google.com35589e62010-11-17 18:58:16 +00001143
1144 # There are three ways we might decide not to print an error message:
1145 # a "NOLINT(category)" comment appears in the source,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001146 # the verbosity level isn't high enough, or the filters filter it out.
erg@google.com35589e62010-11-17 18:58:16 +00001147 if IsErrorSuppressedByNolint(category, linenum):
1148 return False
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001149
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001150 if confidence < _cpplint_state.verbose_level:
1151 return False
1152
1153 is_filtered = False
1154 for one_filter in _Filters():
1155 if one_filter.startswith('-'):
1156 if category.startswith(one_filter[1:]):
1157 is_filtered = True
1158 elif one_filter.startswith('+'):
1159 if category.startswith(one_filter[1:]):
1160 is_filtered = False
1161 else:
1162 assert False # should have been checked for in SetFilter.
1163 if is_filtered:
1164 return False
1165
1166 return True
1167
1168
1169def Error(filename, linenum, category, confidence, message):
1170 """Logs the fact we've found a lint error.
1171
1172 We log where the error was found, and also our confidence in the error,
1173 that is, how certain we are this is a legitimate style regression, and
1174 not a misidentification or a use that's sometimes justified.
1175
erg@google.com35589e62010-11-17 18:58:16 +00001176 False positives can be suppressed by the use of
1177 "cpplint(category)" comments on the offending line. These are
1178 parsed into _error_suppressions.
1179
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001180 Args:
1181 filename: The name of the file containing the error.
1182 linenum: The number of the line containing the error.
1183 category: A string used to describe the "category" this bug
1184 falls under: "whitespace", say, or "runtime". Categories
1185 may have a hierarchy separated by slashes: "whitespace/indent".
1186 confidence: A number from 1-5 representing a confidence score for
1187 the error, with 5 meaning that we are certain of the problem,
1188 and 1 meaning that it could be a legitimate construct.
1189 message: The error message.
1190 """
erg@google.com35589e62010-11-17 18:58:16 +00001191 if _ShouldPrintError(category, confidence, linenum):
erg@google.com26970fa2009-11-17 18:07:32 +00001192 _cpplint_state.IncrementErrorCount(category)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001193 if _cpplint_state.output_format == 'vs7':
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00001194 sys.stderr.write('%s(%s): %s [%s] [%d]\n' % (
1195 filename, linenum, message, category, confidence))
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001196 elif _cpplint_state.output_format == 'eclipse':
1197 sys.stderr.write('%s:%s: warning: %s [%s] [%d]\n' % (
1198 filename, linenum, message, category, confidence))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001199 else:
1200 sys.stderr.write('%s:%s: %s [%s] [%d]\n' % (
1201 filename, linenum, message, category, confidence))
1202
1203
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001204# Matches standard C++ escape sequences per 2.13.2.3 of the C++ standard.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001205_RE_PATTERN_CLEANSE_LINE_ESCAPES = re.compile(
1206 r'\\([abfnrtv?"\\\']|\d+|x[0-9a-fA-F]+)')
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001207# Match a single C style comment on the same line.
1208_RE_PATTERN_C_COMMENTS = r'/\*(?:[^*]|\*(?!/))*\*/'
1209# Matches multi-line C style comments.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001210# This RE is a little bit more complicated than one might expect, because we
1211# have to take care of space removals tools so we can handle comments inside
1212# statements better.
1213# The current rule is: We only clear spaces from both sides when we're at the
1214# end of the line. Otherwise, we try to remove spaces from the right side,
1215# if this doesn't work we try on left side but only if there's a non-character
1216# on the right.
1217_RE_PATTERN_CLEANSE_LINE_C_COMMENTS = re.compile(
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001218 r'(\s*' + _RE_PATTERN_C_COMMENTS + r'\s*$|' +
1219 _RE_PATTERN_C_COMMENTS + r'\s+|' +
1220 r'\s+' + _RE_PATTERN_C_COMMENTS + r'(?=\W)|' +
1221 _RE_PATTERN_C_COMMENTS + r')')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001222
1223
1224def IsCppString(line):
1225 """Does line terminate so, that the next symbol is in string constant.
1226
1227 This function does not consider single-line nor multi-line comments.
1228
1229 Args:
1230 line: is a partial line of code starting from the 0..n.
1231
1232 Returns:
1233 True, if next character appended to 'line' is inside a
1234 string constant.
1235 """
1236
1237 line = line.replace(r'\\', 'XX') # after this, \\" does not match to \"
1238 return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1
1239
1240
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001241def CleanseRawStrings(raw_lines):
1242 """Removes C++11 raw strings from lines.
1243
1244 Before:
1245 static const char kData[] = R"(
1246 multi-line string
1247 )";
1248
1249 After:
1250 static const char kData[] = ""
1251 (replaced by blank line)
1252 "";
1253
1254 Args:
1255 raw_lines: list of raw lines.
1256
1257 Returns:
1258 list of lines with C++11 raw strings replaced by empty strings.
1259 """
1260
1261 delimiter = None
1262 lines_without_raw_strings = []
1263 for line in raw_lines:
1264 if delimiter:
1265 # Inside a raw string, look for the end
1266 end = line.find(delimiter)
1267 if end >= 0:
1268 # Found the end of the string, match leading space for this
1269 # line and resume copying the original lines, and also insert
1270 # a "" on the last line.
1271 leading_space = Match(r'^(\s*)\S', line)
1272 line = leading_space.group(1) + '""' + line[end + len(delimiter):]
1273 delimiter = None
1274 else:
1275 # Haven't found the end yet, append a blank line.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001276 line = '""'
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001277
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001278 # Look for beginning of a raw string, and replace them with
1279 # empty strings. This is done in a loop to handle multiple raw
1280 # strings on the same line.
1281 while delimiter is None:
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001282 # Look for beginning of a raw string.
1283 # See 2.14.15 [lex.string] for syntax.
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00001284 #
1285 # Once we have matched a raw string, we check the prefix of the
1286 # line to make sure that the line is not part of a single line
1287 # comment. It's done this way because we remove raw strings
1288 # before removing comments as opposed to removing comments
1289 # before removing raw strings. This is because there are some
1290 # cpplint checks that requires the comments to be preserved, but
1291 # we don't want to check comments that are inside raw strings.
1292 matched = Match(r'^(.*?)\b(?:R|u8R|uR|UR|LR)"([^\s\\()]*)\((.*)$', line)
1293 if (matched and
1294 not Match(r'^([^\'"]|\'(\\.|[^\'])*\'|"(\\.|[^"])*")*//',
1295 matched.group(1))):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001296 delimiter = ')' + matched.group(2) + '"'
1297
1298 end = matched.group(3).find(delimiter)
1299 if end >= 0:
1300 # Raw string ended on same line
1301 line = (matched.group(1) + '""' +
1302 matched.group(3)[end + len(delimiter):])
1303 delimiter = None
1304 else:
1305 # Start of a multi-line raw string
1306 line = matched.group(1) + '""'
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001307 else:
1308 break
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001309
1310 lines_without_raw_strings.append(line)
1311
1312 # TODO(unknown): if delimiter is not None here, we might want to
1313 # emit a warning for unterminated string.
1314 return lines_without_raw_strings
1315
1316
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001317def FindNextMultiLineCommentStart(lines, lineix):
1318 """Find the beginning marker for a multiline comment."""
1319 while lineix < len(lines):
1320 if lines[lineix].strip().startswith('/*'):
1321 # Only return this marker if the comment goes beyond this line
1322 if lines[lineix].strip().find('*/', 2) < 0:
1323 return lineix
1324 lineix += 1
1325 return len(lines)
1326
1327
1328def FindNextMultiLineCommentEnd(lines, lineix):
1329 """We are inside a comment, find the end marker."""
1330 while lineix < len(lines):
1331 if lines[lineix].strip().endswith('*/'):
1332 return lineix
1333 lineix += 1
1334 return len(lines)
1335
1336
1337def RemoveMultiLineCommentsFromRange(lines, begin, end):
1338 """Clears a range of lines for multi-line comments."""
1339 # Having // dummy comments makes the lines non-empty, so we will not get
1340 # unnecessary blank line warnings later in the code.
1341 for i in range(begin, end):
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001342 lines[i] = '/**/'
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001343
1344
1345def RemoveMultiLineComments(filename, lines, error):
1346 """Removes multiline (c-style) comments from lines."""
1347 lineix = 0
1348 while lineix < len(lines):
1349 lineix_begin = FindNextMultiLineCommentStart(lines, lineix)
1350 if lineix_begin >= len(lines):
1351 return
1352 lineix_end = FindNextMultiLineCommentEnd(lines, lineix_begin)
1353 if lineix_end >= len(lines):
1354 error(filename, lineix_begin + 1, 'readability/multiline_comment', 5,
1355 'Could not find end of multi-line comment')
1356 return
1357 RemoveMultiLineCommentsFromRange(lines, lineix_begin, lineix_end + 1)
1358 lineix = lineix_end + 1
1359
1360
1361def CleanseComments(line):
1362 """Removes //-comments and single-line C-style /* */ comments.
1363
1364 Args:
1365 line: A line of C++ source.
1366
1367 Returns:
1368 The line with single-line comments removed.
1369 """
1370 commentpos = line.find('//')
1371 if commentpos != -1 and not IsCppString(line[:commentpos]):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00001372 line = line[:commentpos].rstrip()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001373 # get rid of /* ... */
1374 return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line)
1375
1376
erg@google.com6317a9c2009-06-25 00:28:19 +00001377class CleansedLines(object):
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001378 """Holds 4 copies of all lines with different preprocessing applied to them.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001379
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001380 1) elided member contains lines without strings and comments.
1381 2) lines member contains lines without comments.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001382 3) raw_lines member contains all the lines without processing.
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001383 4) lines_without_raw_strings member is same as raw_lines, but with C++11 raw
1384 strings removed.
1385 All these members are of <type 'list'>, and of the same length.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001386 """
1387
1388 def __init__(self, lines):
1389 self.elided = []
1390 self.lines = []
1391 self.raw_lines = lines
1392 self.num_lines = len(lines)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001393 self.lines_without_raw_strings = CleanseRawStrings(lines)
1394 for linenum in range(len(self.lines_without_raw_strings)):
1395 self.lines.append(CleanseComments(
1396 self.lines_without_raw_strings[linenum]))
1397 elided = self._CollapseStrings(self.lines_without_raw_strings[linenum])
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001398 self.elided.append(CleanseComments(elided))
1399
1400 def NumLines(self):
1401 """Returns the number of lines represented."""
1402 return self.num_lines
1403
1404 @staticmethod
1405 def _CollapseStrings(elided):
1406 """Collapses strings and chars on a line to simple "" or '' blocks.
1407
1408 We nix strings first so we're not fooled by text like '"http://"'
1409
1410 Args:
1411 elided: The line being processed.
1412
1413 Returns:
1414 The line with collapsed strings.
1415 """
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001416 if _RE_PATTERN_INCLUDE.match(elided):
1417 return elided
1418
1419 # Remove escaped characters first to make quote/single quote collapsing
1420 # basic. Things that look like escaped characters shouldn't occur
1421 # outside of strings and chars.
1422 elided = _RE_PATTERN_CLEANSE_LINE_ESCAPES.sub('', elided)
1423
1424 # Replace quoted strings and digit separators. Both single quotes
1425 # and double quotes are processed in the same loop, otherwise
1426 # nested quotes wouldn't work.
1427 collapsed = ''
1428 while True:
1429 # Find the first quote character
1430 match = Match(r'^([^\'"]*)([\'"])(.*)$', elided)
1431 if not match:
1432 collapsed += elided
1433 break
1434 head, quote, tail = match.groups()
1435
1436 if quote == '"':
1437 # Collapse double quoted strings
1438 second_quote = tail.find('"')
1439 if second_quote >= 0:
1440 collapsed += head + '""'
1441 elided = tail[second_quote + 1:]
1442 else:
1443 # Unmatched double quote, don't bother processing the rest
1444 # of the line since this is probably a multiline string.
1445 collapsed += elided
1446 break
1447 else:
1448 # Found single quote, check nearby text to eliminate digit separators.
1449 #
1450 # There is no special handling for floating point here, because
1451 # the integer/fractional/exponent parts would all be parsed
1452 # correctly as long as there are digits on both sides of the
1453 # separator. So we are fine as long as we don't see something
1454 # like "0.'3" (gcc 4.9.0 will not allow this literal).
1455 if Search(r'\b(?:0[bBxX]?|[1-9])[0-9a-fA-F]*$', head):
1456 match_literal = Match(r'^((?:\'?[0-9a-zA-Z_])*)(.*)$', "'" + tail)
1457 collapsed += head + match_literal.group(1).replace("'", '')
1458 elided = match_literal.group(2)
1459 else:
1460 second_quote = tail.find('\'')
1461 if second_quote >= 0:
1462 collapsed += head + "''"
1463 elided = tail[second_quote + 1:]
1464 else:
1465 # Unmatched single quote
1466 collapsed += elided
1467 break
1468
1469 return collapsed
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001470
1471
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001472def FindEndOfExpressionInLine(line, startpos, stack):
1473 """Find the position just after the end of current parenthesized expression.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001474
1475 Args:
1476 line: a CleansedLines line.
1477 startpos: start searching at this position.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001478 stack: nesting stack at startpos.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001479
1480 Returns:
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001481 On finding matching end: (index just after matching end, None)
1482 On finding an unclosed expression: (-1, None)
1483 Otherwise: (-1, new stack at end of this line)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001484 """
Edward Lemur6d31ed52019-12-02 23:00:00 +00001485 for i in range(startpos, len(line)):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001486 char = line[i]
1487 if char in '([{':
1488 # Found start of parenthesized expression, push to expression stack
1489 stack.append(char)
1490 elif char == '<':
1491 # Found potential start of template argument list
1492 if i > 0 and line[i - 1] == '<':
1493 # Left shift operator
1494 if stack and stack[-1] == '<':
1495 stack.pop()
1496 if not stack:
1497 return (-1, None)
1498 elif i > 0 and Search(r'\boperator\s*$', line[0:i]):
1499 # operator<, don't add to stack
1500 continue
1501 else:
1502 # Tentative start of template argument list
1503 stack.append('<')
1504 elif char in ')]}':
1505 # Found end of parenthesized expression.
1506 #
1507 # If we are currently expecting a matching '>', the pending '<'
1508 # must have been an operator. Remove them from expression stack.
1509 while stack and stack[-1] == '<':
1510 stack.pop()
1511 if not stack:
1512 return (-1, None)
1513 if ((stack[-1] == '(' and char == ')') or
1514 (stack[-1] == '[' and char == ']') or
1515 (stack[-1] == '{' and char == '}')):
1516 stack.pop()
1517 if not stack:
1518 return (i + 1, None)
1519 else:
1520 # Mismatched parentheses
1521 return (-1, None)
1522 elif char == '>':
1523 # Found potential end of template argument list.
1524
1525 # Ignore "->" and operator functions
1526 if (i > 0 and
1527 (line[i - 1] == '-' or Search(r'\boperator\s*$', line[0:i - 1]))):
1528 continue
1529
1530 # Pop the stack if there is a matching '<'. Otherwise, ignore
1531 # this '>' since it must be an operator.
1532 if stack:
1533 if stack[-1] == '<':
1534 stack.pop()
1535 if not stack:
1536 return (i + 1, None)
1537 elif char == ';':
1538 # Found something that look like end of statements. If we are currently
1539 # expecting a '>', the matching '<' must have been an operator, since
1540 # template argument list should not contain statements.
1541 while stack and stack[-1] == '<':
1542 stack.pop()
1543 if not stack:
1544 return (-1, None)
1545
1546 # Did not find end of expression or unbalanced parentheses on this line
1547 return (-1, stack)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001548
1549
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001550def CloseExpression(clean_lines, linenum, pos):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001551 """If input points to ( or { or [ or <, finds the position that closes it.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001552
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001553 If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001554 linenum/pos that correspond to the closing of the expression.
1555
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001556 TODO(unknown): cpplint spends a fair bit of time matching parentheses.
1557 Ideally we would want to index all opening and closing parentheses once
1558 and have CloseExpression be just a simple lookup, but due to preprocessor
1559 tricks, this is not so easy.
1560
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001561 Args:
1562 clean_lines: A CleansedLines instance containing the file.
1563 linenum: The number of the line to check.
1564 pos: A position on the line.
1565
1566 Returns:
1567 A tuple (line, linenum, pos) pointer *past* the closing brace, or
1568 (line, len(lines), -1) if we never find a close. Note we ignore
1569 strings and comments when matching; and the line we return is the
1570 'cleansed' line at linenum.
1571 """
1572
1573 line = clean_lines.elided[linenum]
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001574 if (line[pos] not in '({[<') or Match(r'<[<=]', line[pos:]):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001575 return (line, clean_lines.NumLines(), -1)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001576
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001577 # Check first line
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001578 (end_pos, stack) = FindEndOfExpressionInLine(line, pos, [])
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001579 if end_pos > -1:
1580 return (line, linenum, end_pos)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001581
1582 # Continue scanning forward
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001583 while stack and linenum < clean_lines.NumLines() - 1:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001584 linenum += 1
1585 line = clean_lines.elided[linenum]
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001586 (end_pos, stack) = FindEndOfExpressionInLine(line, 0, stack)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001587 if end_pos > -1:
1588 return (line, linenum, end_pos)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001589
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001590 # Did not find end of expression before end of file, give up
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001591 return (line, clean_lines.NumLines(), -1)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001592
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001593
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001594def FindStartOfExpressionInLine(line, endpos, stack):
1595 """Find position at the matching start of current expression.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001596
1597 This is almost the reverse of FindEndOfExpressionInLine, but note
1598 that the input position and returned position differs by 1.
1599
1600 Args:
1601 line: a CleansedLines line.
1602 endpos: start searching at this position.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001603 stack: nesting stack at endpos.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001604
1605 Returns:
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001606 On finding matching start: (index at matching start, None)
1607 On finding an unclosed expression: (-1, None)
1608 Otherwise: (-1, new stack at beginning of this line)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001609 """
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001610 i = endpos
1611 while i >= 0:
1612 char = line[i]
1613 if char in ')]}':
1614 # Found end of expression, push to expression stack
1615 stack.append(char)
1616 elif char == '>':
1617 # Found potential end of template argument list.
1618 #
1619 # Ignore it if it's a "->" or ">=" or "operator>"
1620 if (i > 0 and
1621 (line[i - 1] == '-' or
1622 Match(r'\s>=\s', line[i - 1:]) or
1623 Search(r'\boperator\s*$', line[0:i]))):
1624 i -= 1
1625 else:
1626 stack.append('>')
1627 elif char == '<':
1628 # Found potential start of template argument list
1629 if i > 0 and line[i - 1] == '<':
1630 # Left shift operator
1631 i -= 1
1632 else:
1633 # If there is a matching '>', we can pop the expression stack.
1634 # Otherwise, ignore this '<' since it must be an operator.
1635 if stack and stack[-1] == '>':
1636 stack.pop()
1637 if not stack:
1638 return (i, None)
1639 elif char in '([{':
1640 # Found start of expression.
1641 #
1642 # If there are any unmatched '>' on the stack, they must be
1643 # operators. Remove those.
1644 while stack and stack[-1] == '>':
1645 stack.pop()
1646 if not stack:
1647 return (-1, None)
1648 if ((char == '(' and stack[-1] == ')') or
1649 (char == '[' and stack[-1] == ']') or
1650 (char == '{' and stack[-1] == '}')):
1651 stack.pop()
1652 if not stack:
1653 return (i, None)
1654 else:
1655 # Mismatched parentheses
1656 return (-1, None)
1657 elif char == ';':
1658 # Found something that look like end of statements. If we are currently
1659 # expecting a '<', the matching '>' must have been an operator, since
1660 # template argument list should not contain statements.
1661 while stack and stack[-1] == '>':
1662 stack.pop()
1663 if not stack:
1664 return (-1, None)
1665
1666 i -= 1
1667
1668 return (-1, stack)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001669
1670
1671def ReverseCloseExpression(clean_lines, linenum, pos):
1672 """If input points to ) or } or ] or >, finds the position that opens it.
1673
1674 If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the
1675 linenum/pos that correspond to the opening of the expression.
1676
1677 Args:
1678 clean_lines: A CleansedLines instance containing the file.
1679 linenum: The number of the line to check.
1680 pos: A position on the line.
1681
1682 Returns:
1683 A tuple (line, linenum, pos) pointer *at* the opening brace, or
1684 (line, 0, -1) if we never find the matching opening brace. Note
1685 we ignore strings and comments when matching; and the line we
1686 return is the 'cleansed' line at linenum.
1687 """
1688 line = clean_lines.elided[linenum]
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001689 if line[pos] not in ')}]>':
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001690 return (line, 0, -1)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001691
1692 # Check last line
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001693 (start_pos, stack) = FindStartOfExpressionInLine(line, pos, [])
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001694 if start_pos > -1:
1695 return (line, linenum, start_pos)
1696
1697 # Continue scanning backward
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001698 while stack and linenum > 0:
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001699 linenum -= 1
1700 line = clean_lines.elided[linenum]
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001701 (start_pos, stack) = FindStartOfExpressionInLine(line, len(line) - 1, stack)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001702 if start_pos > -1:
1703 return (line, linenum, start_pos)
1704
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001705 # Did not find start of expression before beginning of file, give up
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001706 return (line, 0, -1)
1707
1708
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001709def CheckForCopyright(filename, lines, error):
1710 """Logs an error if no Copyright message appears at the top of the file."""
1711
1712 # We'll say it should occur by line 10. Don't forget there's a
1713 # dummy line at the front.
Edward Lemur6d31ed52019-12-02 23:00:00 +00001714 for line in range(1, min(len(lines), 11)):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001715 if re.search(r'Copyright', lines[line], re.I): break
1716 else: # means no copyright line was found
1717 error(filename, 0, 'legal/copyright', 5,
1718 'No copyright message found. '
1719 'You should have a line: "Copyright [year] <Copyright Owner>"')
1720
1721
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001722def GetIndentLevel(line):
1723 """Return the number of leading spaces in line.
1724
1725 Args:
1726 line: A string to check.
1727
1728 Returns:
1729 An integer count of leading spaces, possibly zero.
1730 """
1731 indent = Match(r'^( *)\S', line)
1732 if indent:
1733 return len(indent.group(1))
1734 else:
1735 return 0
1736
1737
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001738def GetHeaderGuardCPPVariable(filename):
1739 """Returns the CPP variable that should be used as a header guard.
1740
1741 Args:
1742 filename: The name of a C++ header file.
1743
1744 Returns:
1745 The CPP variable that should be used as a header guard in the
1746 named file.
1747
1748 """
1749
erg@google.com35589e62010-11-17 18:58:16 +00001750 # Restores original filename in case that cpplint is invoked from Emacs's
1751 # flymake.
1752 filename = re.sub(r'_flymake\.h$', '.h', filename)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001753 filename = re.sub(r'/\.flymake/([^/]*)$', r'/\1', filename)
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001754 # Replace 'c++' with 'cpp'.
1755 filename = filename.replace('C++', 'cpp').replace('c++', 'cpp')
skym@chromium.org3990c412016-02-05 20:55:12 +00001756
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001757 fileinfo = FileInfo(filename)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001758 file_path_from_root = fileinfo.RepositoryName()
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00001759 if _root:
1760 file_path_from_root = re.sub('^' + _root + os.sep, '', file_path_from_root)
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001761 return re.sub(r'[^a-zA-Z0-9]', '_', file_path_from_root).upper() + '_'
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001762
1763
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001764def CheckForHeaderGuard(filename, clean_lines, error):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001765 """Checks that the file contains a header guard.
1766
erg@google.com6317a9c2009-06-25 00:28:19 +00001767 Logs an error if no #ifndef header guard is present. For other
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001768 headers, checks that the full pathname is used.
1769
1770 Args:
1771 filename: The name of the C++ header file.
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001772 clean_lines: A CleansedLines instance containing the file.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001773 error: The function to call with any errors found.
1774 """
1775
avakulenko@google.com59146752014-08-11 20:20:55 +00001776 # Don't check for header guards if there are error suppression
1777 # comments somewhere in this file.
1778 #
1779 # Because this is silencing a warning for a nonexistent line, we
1780 # only support the very specific NOLINT(build/header_guard) syntax,
1781 # and not the general NOLINT or NOLINT(*) syntax.
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001782 raw_lines = clean_lines.lines_without_raw_strings
1783 for i in raw_lines:
avakulenko@google.com59146752014-08-11 20:20:55 +00001784 if Search(r'//\s*NOLINT\(build/header_guard\)', i):
1785 return
1786
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001787 cppvar = GetHeaderGuardCPPVariable(filename)
1788
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001789 ifndef = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001790 ifndef_linenum = 0
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001791 define = ''
1792 endif = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001793 endif_linenum = 0
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001794 for linenum, line in enumerate(raw_lines):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001795 linesplit = line.split()
1796 if len(linesplit) >= 2:
1797 # find the first occurrence of #ifndef and #define, save arg
1798 if not ifndef and linesplit[0] == '#ifndef':
1799 # set ifndef to the header guard presented on the #ifndef line.
1800 ifndef = linesplit[1]
1801 ifndef_linenum = linenum
1802 if not define and linesplit[0] == '#define':
1803 define = linesplit[1]
1804 # find the last occurrence of #endif, save entire line
1805 if line.startswith('#endif'):
1806 endif = line
1807 endif_linenum = linenum
1808
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001809 if not ifndef or not define or ifndef != define:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001810 error(filename, 0, 'build/header_guard', 5,
1811 'No #ifndef header guard found, suggested CPP variable is: %s' %
1812 cppvar)
1813 return
1814
1815 # The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__
1816 # for backward compatibility.
erg@google.com35589e62010-11-17 18:58:16 +00001817 if ifndef != cppvar:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001818 error_level = 0
1819 if ifndef != cppvar + '_':
1820 error_level = 5
1821
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001822 ParseNolintSuppressions(filename, raw_lines[ifndef_linenum], ifndef_linenum,
erg@google.com35589e62010-11-17 18:58:16 +00001823 error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001824 error(filename, ifndef_linenum, 'build/header_guard', error_level,
1825 '#ifndef header guard has wrong style, please use: %s' % cppvar)
1826
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001827 # Check for "//" comments on endif line.
1828 ParseNolintSuppressions(filename, raw_lines[endif_linenum], endif_linenum,
1829 error)
1830 match = Match(r'#endif\s*//\s*' + cppvar + r'(_)?\b', endif)
1831 if match:
1832 if match.group(1) == '_':
1833 # Issue low severity warning for deprecated double trailing underscore
1834 error(filename, endif_linenum, 'build/header_guard', 0,
1835 '#endif line should be "#endif // %s"' % cppvar)
erg@chromium.orgc452fea2012-01-26 21:10:45 +00001836 return
1837
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001838 # Didn't find the corresponding "//" comment. If this file does not
1839 # contain any "//" comments at all, it could be that the compiler
1840 # only wants "/**/" comments, look for those instead.
1841 no_single_line_comments = True
Edward Lemur6d31ed52019-12-02 23:00:00 +00001842 for i in range(1, len(raw_lines) - 1):
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001843 line = raw_lines[i]
1844 if Match(r'^(?:(?:\'(?:\.|[^\'])*\')|(?:"(?:\.|[^"])*")|[^\'"])*//', line):
1845 no_single_line_comments = False
1846 break
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001847
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001848 if no_single_line_comments:
1849 match = Match(r'#endif\s*/\*\s*' + cppvar + r'(_)?\s*\*/', endif)
1850 if match:
1851 if match.group(1) == '_':
1852 # Low severity warning for double trailing underscore
1853 error(filename, endif_linenum, 'build/header_guard', 0,
1854 '#endif line should be "#endif /* %s */"' % cppvar)
1855 return
1856
1857 # Didn't find anything
1858 error(filename, endif_linenum, 'build/header_guard', 5,
1859 '#endif line should be "#endif // %s"' % cppvar)
1860
1861
1862def CheckHeaderFileIncluded(filename, include_state, error):
1863 """Logs an error if a .cc file does not include its header."""
1864
1865 # Do not check test files
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00001866 fileinfo = FileInfo(filename)
1867 if Search(_TEST_FILE_SUFFIX, fileinfo.BaseName()):
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001868 return
1869
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00001870 headerfile = filename[0:len(filename) - len(fileinfo.Extension())] + '.h'
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001871 if not os.path.exists(headerfile):
1872 return
1873 headername = FileInfo(headerfile).RepositoryName()
1874 first_include = 0
1875 for section_list in include_state.include_list:
1876 for f in section_list:
1877 if headername in f[0] or f[0] in headername:
1878 return
1879 if not first_include:
1880 first_include = f[1]
1881
1882 error(filename, first_include, 'build/include', 5,
1883 '%s should include its header file %s' % (fileinfo.RepositoryName(),
1884 headername))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001885
1886
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001887def CheckForBadCharacters(filename, lines, error):
1888 """Logs an error for each line containing bad characters.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001889
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001890 Two kinds of bad characters:
1891
1892 1. Unicode replacement characters: These indicate that either the file
1893 contained invalid UTF-8 (likely) or Unicode replacement characters (which
1894 it shouldn't). Note that it's possible for this to throw off line
1895 numbering if the invalid UTF-8 occurred adjacent to a newline.
1896
1897 2. NUL bytes. These are problematic for some tools.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001898
1899 Args:
1900 filename: The name of the current file.
1901 lines: An array of strings, each representing a line of the file.
1902 error: The function to call with any errors found.
1903 """
1904 for linenum, line in enumerate(lines):
1905 if u'\ufffd' in line:
1906 error(filename, linenum, 'readability/utf8', 5,
1907 'Line contains invalid UTF-8 (or Unicode replacement character).')
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001908 if '\0' in line:
1909 error(filename, linenum, 'readability/nul', 5, 'Line contains NUL byte.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001910
1911
1912def CheckForNewlineAtEOF(filename, lines, error):
1913 """Logs an error if there is no newline char at the end of the file.
1914
1915 Args:
1916 filename: The name of the current file.
1917 lines: An array of strings, each representing a line of the file.
1918 error: The function to call with any errors found.
1919 """
1920
1921 # The array lines() was created by adding two newlines to the
1922 # original file (go figure), then splitting on \n.
1923 # To verify that the file ends in \n, we just have to make sure the
1924 # last-but-two element of lines() exists and is empty.
1925 if len(lines) < 3 or lines[-2]:
1926 error(filename, len(lines) - 2, 'whitespace/ending_newline', 5,
1927 'Could not find a newline character at the end of the file.')
1928
1929
1930def CheckForMultilineCommentsAndStrings(filename, clean_lines, linenum, error):
1931 """Logs an error if we see /* ... */ or "..." that extend past one line.
1932
1933 /* ... */ comments are legit inside macros, for one line.
1934 Otherwise, we prefer // comments, so it's ok to warn about the
1935 other. Likewise, it's ok for strings to extend across multiple
1936 lines, as long as a line continuation character (backslash)
1937 terminates each line. Although not currently prohibited by the C++
1938 style guide, it's ugly and unnecessary. We don't do well with either
1939 in this lint program, so we warn about both.
1940
1941 Args:
1942 filename: The name of the current file.
1943 clean_lines: A CleansedLines instance containing the file.
1944 linenum: The number of the line to check.
1945 error: The function to call with any errors found.
1946 """
1947 line = clean_lines.elided[linenum]
1948
1949 # Remove all \\ (escaped backslashes) from the line. They are OK, and the
1950 # second (escaped) slash may trigger later \" detection erroneously.
1951 line = line.replace('\\\\', '')
1952
1953 if line.count('/*') > line.count('*/'):
1954 error(filename, linenum, 'readability/multiline_comment', 5,
1955 'Complex multi-line /*...*/-style comment found. '
1956 'Lint may give bogus warnings. '
1957 'Consider replacing these with //-style comments, '
1958 'with #if 0...#endif, '
1959 'or with more clearly structured multi-line comments.')
1960
1961 if (line.count('"') - line.count('\\"')) % 2:
1962 error(filename, linenum, 'readability/multiline_string', 5,
1963 'Multi-line string ("...") found. This lint script doesn\'t '
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001964 'do well with such strings, and may give bogus warnings. '
1965 'Use C++11 raw strings or concatenation instead.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001966
1967
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001968# (non-threadsafe name, thread-safe alternative, validation pattern)
1969#
1970# The validation pattern is used to eliminate false positives such as:
1971# _rand(); // false positive due to substring match.
1972# ->rand(); // some member function rand().
1973# ACMRandom rand(seed); // some variable named rand.
1974# ISAACRandom rand(); // another variable named rand.
1975#
1976# Basically we require the return value of these functions to be used
1977# in some expression context on the same line by matching on some
1978# operator before the function name. This eliminates constructors and
1979# member function calls.
1980_UNSAFE_FUNC_PREFIX = r'(?:[-+*/=%^&|(<]\s*|>\s+)'
1981_THREADING_LIST = (
1982 ('asctime(', 'asctime_r(', _UNSAFE_FUNC_PREFIX + r'asctime\([^)]+\)'),
1983 ('ctime(', 'ctime_r(', _UNSAFE_FUNC_PREFIX + r'ctime\([^)]+\)'),
1984 ('getgrgid(', 'getgrgid_r(', _UNSAFE_FUNC_PREFIX + r'getgrgid\([^)]+\)'),
1985 ('getgrnam(', 'getgrnam_r(', _UNSAFE_FUNC_PREFIX + r'getgrnam\([^)]+\)'),
1986 ('getlogin(', 'getlogin_r(', _UNSAFE_FUNC_PREFIX + r'getlogin\(\)'),
1987 ('getpwnam(', 'getpwnam_r(', _UNSAFE_FUNC_PREFIX + r'getpwnam\([^)]+\)'),
1988 ('getpwuid(', 'getpwuid_r(', _UNSAFE_FUNC_PREFIX + r'getpwuid\([^)]+\)'),
1989 ('gmtime(', 'gmtime_r(', _UNSAFE_FUNC_PREFIX + r'gmtime\([^)]+\)'),
1990 ('localtime(', 'localtime_r(', _UNSAFE_FUNC_PREFIX + r'localtime\([^)]+\)'),
1991 ('rand(', 'rand_r(', _UNSAFE_FUNC_PREFIX + r'rand\(\)'),
1992 ('strtok(', 'strtok_r(',
1993 _UNSAFE_FUNC_PREFIX + r'strtok\([^)]+\)'),
1994 ('ttyname(', 'ttyname_r(', _UNSAFE_FUNC_PREFIX + r'ttyname\([^)]+\)'),
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001995 )
1996
1997
1998def CheckPosixThreading(filename, clean_lines, linenum, error):
1999 """Checks for calls to thread-unsafe functions.
2000
2001 Much code has been originally written without consideration of
2002 multi-threading. Also, engineers are relying on their old experience;
2003 they have learned posix before threading extensions were added. These
2004 tests guide the engineers to use thread-safe functions (when using
2005 posix directly).
2006
2007 Args:
2008 filename: The name of the current file.
2009 clean_lines: A CleansedLines instance containing the file.
2010 linenum: The number of the line to check.
2011 error: The function to call with any errors found.
2012 """
2013 line = clean_lines.elided[linenum]
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002014 for single_thread_func, multithread_safe_func, pattern in _THREADING_LIST:
2015 # Additional pattern matching check to confirm that this is the
2016 # function we are looking for
2017 if Search(pattern, line):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002018 error(filename, linenum, 'runtime/threadsafe_fn', 2,
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002019 'Consider using ' + multithread_safe_func +
2020 '...) instead of ' + single_thread_func +
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002021 '...) for improved thread safety.')
2022
2023
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002024def CheckVlogArguments(filename, clean_lines, linenum, error):
2025 """Checks that VLOG() is only used for defining a logging level.
2026
2027 For example, VLOG(2) is correct. VLOG(INFO), VLOG(WARNING), VLOG(ERROR), and
2028 VLOG(FATAL) are not.
2029
2030 Args:
2031 filename: The name of the current file.
2032 clean_lines: A CleansedLines instance containing the file.
2033 linenum: The number of the line to check.
2034 error: The function to call with any errors found.
2035 """
2036 line = clean_lines.elided[linenum]
2037 if Search(r'\bVLOG\((INFO|ERROR|WARNING|DFATAL|FATAL)\)', line):
2038 error(filename, linenum, 'runtime/vlog', 5,
2039 'VLOG() should be used with numeric verbosity level. '
2040 'Use LOG() if you want symbolic severity levels.')
2041
erg@google.com26970fa2009-11-17 18:07:32 +00002042# Matches invalid increment: *count++, which moves pointer instead of
erg@google.com6317a9c2009-06-25 00:28:19 +00002043# incrementing a value.
erg@google.com26970fa2009-11-17 18:07:32 +00002044_RE_PATTERN_INVALID_INCREMENT = re.compile(
erg@google.com6317a9c2009-06-25 00:28:19 +00002045 r'^\s*\*\w+(\+\+|--);')
2046
2047
2048def CheckInvalidIncrement(filename, clean_lines, linenum, error):
erg@google.com26970fa2009-11-17 18:07:32 +00002049 """Checks for invalid increment *count++.
erg@google.com6317a9c2009-06-25 00:28:19 +00002050
2051 For example following function:
2052 void increment_counter(int* count) {
2053 *count++;
2054 }
2055 is invalid, because it effectively does count++, moving pointer, and should
2056 be replaced with ++*count, (*count)++ or *count += 1.
2057
2058 Args:
2059 filename: The name of the current file.
2060 clean_lines: A CleansedLines instance containing the file.
2061 linenum: The number of the line to check.
2062 error: The function to call with any errors found.
2063 """
2064 line = clean_lines.elided[linenum]
erg@google.com26970fa2009-11-17 18:07:32 +00002065 if _RE_PATTERN_INVALID_INCREMENT.match(line):
erg@google.com6317a9c2009-06-25 00:28:19 +00002066 error(filename, linenum, 'runtime/invalid_increment', 5,
2067 'Changing pointer instead of value (or unused value of operator*).')
2068
2069
avakulenko@google.com59146752014-08-11 20:20:55 +00002070def IsMacroDefinition(clean_lines, linenum):
2071 if Search(r'^#define', clean_lines[linenum]):
2072 return True
2073
2074 if linenum > 0 and Search(r'\\$', clean_lines[linenum - 1]):
2075 return True
2076
2077 return False
2078
2079
2080def IsForwardClassDeclaration(clean_lines, linenum):
2081 return Match(r'^\s*(\btemplate\b)*.*class\s+\w+;\s*$', clean_lines[linenum])
2082
2083
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002084class _BlockInfo(object):
2085 """Stores information about a generic block of code."""
2086
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002087 def __init__(self, linenum, seen_open_brace):
2088 self.starting_linenum = linenum
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002089 self.seen_open_brace = seen_open_brace
2090 self.open_parentheses = 0
2091 self.inline_asm = _NO_ASM
avakulenko@google.com59146752014-08-11 20:20:55 +00002092 self.check_namespace_indentation = False
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002093
2094 def CheckBegin(self, filename, clean_lines, linenum, error):
2095 """Run checks that applies to text up to the opening brace.
2096
2097 This is mostly for checking the text after the class identifier
2098 and the "{", usually where the base class is specified. For other
2099 blocks, there isn't much to check, so we always pass.
2100
2101 Args:
2102 filename: The name of the current file.
2103 clean_lines: A CleansedLines instance containing the file.
2104 linenum: The number of the line to check.
2105 error: The function to call with any errors found.
2106 """
2107 pass
2108
2109 def CheckEnd(self, filename, clean_lines, linenum, error):
2110 """Run checks that applies to text after the closing brace.
2111
2112 This is mostly used for checking end of namespace comments.
2113
2114 Args:
2115 filename: The name of the current file.
2116 clean_lines: A CleansedLines instance containing the file.
2117 linenum: The number of the line to check.
2118 error: The function to call with any errors found.
2119 """
2120 pass
2121
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002122 def IsBlockInfo(self):
2123 """Returns true if this block is a _BlockInfo.
2124
2125 This is convenient for verifying that an object is an instance of
2126 a _BlockInfo, but not an instance of any of the derived classes.
2127
2128 Returns:
2129 True for this class, False for derived classes.
2130 """
2131 return self.__class__ == _BlockInfo
2132
2133
2134class _ExternCInfo(_BlockInfo):
2135 """Stores information about an 'extern "C"' block."""
2136
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002137 def __init__(self, linenum):
2138 _BlockInfo.__init__(self, linenum, True)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002139
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002140
2141class _ClassInfo(_BlockInfo):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002142 """Stores information about a class."""
2143
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002144 def __init__(self, name, class_or_struct, clean_lines, linenum):
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002145 _BlockInfo.__init__(self, linenum, False)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002146 self.name = name
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002147 self.is_derived = False
avakulenko@google.com59146752014-08-11 20:20:55 +00002148 self.check_namespace_indentation = True
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002149 if class_or_struct == 'struct':
2150 self.access = 'public'
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002151 self.is_struct = True
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002152 else:
2153 self.access = 'private'
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002154 self.is_struct = False
2155
2156 # Remember initial indentation level for this class. Using raw_lines here
2157 # instead of elided to account for leading comments.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002158 self.class_indent = GetIndentLevel(clean_lines.raw_lines[linenum])
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002159
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00002160 # Try to find the end of the class. This will be confused by things like:
2161 # class A {
2162 # } *x = { ...
2163 #
2164 # But it's still good enough for CheckSectionSpacing.
2165 self.last_line = 0
2166 depth = 0
2167 for i in range(linenum, clean_lines.NumLines()):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002168 line = clean_lines.elided[i]
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00002169 depth += line.count('{') - line.count('}')
2170 if not depth:
2171 self.last_line = i
2172 break
2173
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002174 def CheckBegin(self, filename, clean_lines, linenum, error):
2175 # Look for a bare ':'
2176 if Search('(^|[^:]):($|[^:])', clean_lines.elided[linenum]):
2177 self.is_derived = True
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002178
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002179 def CheckEnd(self, filename, clean_lines, linenum, error):
avakulenko@google.com255f2be2014-12-05 22:19:55 +00002180 # If there is a DISALLOW macro, it should appear near the end of
2181 # the class.
2182 seen_last_thing_in_class = False
Edward Lemur6d31ed52019-12-02 23:00:00 +00002183 for i in range(linenum - 1, self.starting_linenum, -1):
avakulenko@google.com255f2be2014-12-05 22:19:55 +00002184 match = Search(
2185 r'\b(DISALLOW_COPY_AND_ASSIGN|DISALLOW_IMPLICIT_CONSTRUCTORS)\(' +
2186 self.name + r'\)',
2187 clean_lines.elided[i])
2188 if match:
2189 if seen_last_thing_in_class:
2190 error(filename, i, 'readability/constructors', 3,
2191 match.group(1) + ' should be the last thing in the class')
2192 break
2193
2194 if not Match(r'^\s*$', clean_lines.elided[i]):
2195 seen_last_thing_in_class = True
2196
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002197 # Check that closing brace is aligned with beginning of the class.
2198 # Only do this if the closing brace is indented by only whitespaces.
2199 # This means we will not check single-line class definitions.
2200 indent = Match(r'^( *)\}', clean_lines.elided[linenum])
2201 if indent and len(indent.group(1)) != self.class_indent:
2202 if self.is_struct:
2203 parent = 'struct ' + self.name
2204 else:
2205 parent = 'class ' + self.name
2206 error(filename, linenum, 'whitespace/indent', 3,
2207 'Closing brace should be aligned with beginning of %s' % parent)
2208
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002209
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002210class _NamespaceInfo(_BlockInfo):
2211 """Stores information about a namespace."""
2212
2213 def __init__(self, name, linenum):
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002214 _BlockInfo.__init__(self, linenum, False)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002215 self.name = name or ''
avakulenko@google.com59146752014-08-11 20:20:55 +00002216 self.check_namespace_indentation = True
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002217
2218 def CheckEnd(self, filename, clean_lines, linenum, error):
2219 """Check end of namespace comments."""
2220 line = clean_lines.raw_lines[linenum]
2221
2222 # Check how many lines is enclosed in this namespace. Don't issue
2223 # warning for missing namespace comments if there aren't enough
2224 # lines. However, do apply checks if there is already an end of
2225 # namespace comment and it's incorrect.
2226 #
2227 # TODO(unknown): We always want to check end of namespace comments
2228 # if a namespace is large, but sometimes we also want to apply the
2229 # check if a short namespace contained nontrivial things (something
2230 # other than forward declarations). There is currently no logic on
2231 # deciding what these nontrivial things are, so this check is
2232 # triggered by namespace size only, which works most of the time.
2233 if (linenum - self.starting_linenum < 10
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002234 and not Match(r'^\s*};*\s*(//|/\*).*\bnamespace\b', line)):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002235 return
2236
2237 # Look for matching comment at end of namespace.
2238 #
2239 # Note that we accept C style "/* */" comments for terminating
2240 # namespaces, so that code that terminate namespaces inside
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002241 # preprocessor macros can be cpplint clean.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002242 #
2243 # We also accept stuff like "// end of namespace <name>." with the
2244 # period at the end.
2245 #
2246 # Besides these, we don't accept anything else, otherwise we might
2247 # get false negatives when existing comment is a substring of the
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002248 # expected namespace.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002249 if self.name:
2250 # Named namespace
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002251 if not Match((r'^\s*};*\s*(//|/\*).*\bnamespace\s+' +
2252 re.escape(self.name) + r'[\*/\.\\\s]*$'),
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002253 line):
2254 error(filename, linenum, 'readability/namespace', 5,
2255 'Namespace should be terminated with "// namespace %s"' %
2256 self.name)
2257 else:
2258 # Anonymous namespace
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002259 if not Match(r'^\s*};*\s*(//|/\*).*\bnamespace[\*/\.\\\s]*$', line):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002260 # If "// namespace anonymous" or "// anonymous namespace (more text)",
2261 # mention "// anonymous namespace" as an acceptable form
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002262 if Match(r'^\s*}.*\b(namespace anonymous|anonymous namespace)\b', line):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002263 error(filename, linenum, 'readability/namespace', 5,
2264 'Anonymous namespace should be terminated with "// namespace"'
2265 ' or "// anonymous namespace"')
2266 else:
2267 error(filename, linenum, 'readability/namespace', 5,
2268 'Anonymous namespace should be terminated with "// namespace"')
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002269
2270
2271class _PreprocessorInfo(object):
2272 """Stores checkpoints of nesting stacks when #if/#else is seen."""
2273
2274 def __init__(self, stack_before_if):
2275 # The entire nesting stack before #if
2276 self.stack_before_if = stack_before_if
2277
2278 # The entire nesting stack up to #else
2279 self.stack_before_else = []
2280
2281 # Whether we have already seen #else or #elif
2282 self.seen_else = False
2283
2284
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002285class NestingState(object):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002286 """Holds states related to parsing braces."""
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002287
2288 def __init__(self):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002289 # Stack for tracking all braces. An object is pushed whenever we
2290 # see a "{", and popped when we see a "}". Only 3 types of
2291 # objects are possible:
2292 # - _ClassInfo: a class or struct.
2293 # - _NamespaceInfo: a namespace.
2294 # - _BlockInfo: some other type of block.
2295 self.stack = []
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002296
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002297 # Top of the previous stack before each Update().
2298 #
2299 # Because the nesting_stack is updated at the end of each line, we
2300 # had to do some convoluted checks to find out what is the current
2301 # scope at the beginning of the line. This check is simplified by
2302 # saving the previous top of nesting stack.
2303 #
2304 # We could save the full stack, but we only need the top. Copying
2305 # the full nesting stack would slow down cpplint by ~10%.
2306 self.previous_stack_top = []
2307
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002308 # Stack of _PreprocessorInfo objects.
2309 self.pp_stack = []
2310
2311 def SeenOpenBrace(self):
2312 """Check if we have seen the opening brace for the innermost block.
2313
2314 Returns:
2315 True if we have seen the opening brace, False if the innermost
2316 block is still expecting an opening brace.
2317 """
2318 return (not self.stack) or self.stack[-1].seen_open_brace
2319
2320 def InNamespaceBody(self):
2321 """Check if we are currently one level inside a namespace body.
2322
2323 Returns:
2324 True if top of the stack is a namespace block, False otherwise.
2325 """
2326 return self.stack and isinstance(self.stack[-1], _NamespaceInfo)
2327
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002328 def InExternC(self):
2329 """Check if we are currently one level inside an 'extern "C"' block.
2330
2331 Returns:
2332 True if top of the stack is an extern block, False otherwise.
2333 """
2334 return self.stack and isinstance(self.stack[-1], _ExternCInfo)
2335
2336 def InClassDeclaration(self):
2337 """Check if we are currently one level inside a class or struct declaration.
2338
2339 Returns:
2340 True if top of the stack is a class/struct, False otherwise.
2341 """
2342 return self.stack and isinstance(self.stack[-1], _ClassInfo)
2343
2344 def InAsmBlock(self):
2345 """Check if we are currently one level inside an inline ASM block.
2346
2347 Returns:
2348 True if the top of the stack is a block containing inline ASM.
2349 """
2350 return self.stack and self.stack[-1].inline_asm != _NO_ASM
2351
2352 def InTemplateArgumentList(self, clean_lines, linenum, pos):
2353 """Check if current position is inside template argument list.
2354
2355 Args:
2356 clean_lines: A CleansedLines instance containing the file.
2357 linenum: The number of the line to check.
2358 pos: position just after the suspected template argument.
2359 Returns:
2360 True if (linenum, pos) is inside template arguments.
2361 """
2362 while linenum < clean_lines.NumLines():
2363 # Find the earliest character that might indicate a template argument
2364 line = clean_lines.elided[linenum]
2365 match = Match(r'^[^{};=\[\]\.<>]*(.)', line[pos:])
2366 if not match:
2367 linenum += 1
2368 pos = 0
2369 continue
2370 token = match.group(1)
2371 pos += len(match.group(0))
2372
2373 # These things do not look like template argument list:
2374 # class Suspect {
2375 # class Suspect x; }
2376 if token in ('{', '}', ';'): return False
2377
2378 # These things look like template argument list:
2379 # template <class Suspect>
2380 # template <class Suspect = default_value>
2381 # template <class Suspect[]>
2382 # template <class Suspect...>
2383 if token in ('>', '=', '[', ']', '.'): return True
2384
2385 # Check if token is an unmatched '<'.
2386 # If not, move on to the next character.
2387 if token != '<':
2388 pos += 1
2389 if pos >= len(line):
2390 linenum += 1
2391 pos = 0
2392 continue
2393
2394 # We can't be sure if we just find a single '<', and need to
2395 # find the matching '>'.
2396 (_, end_line, end_pos) = CloseExpression(clean_lines, linenum, pos - 1)
2397 if end_pos < 0:
2398 # Not sure if template argument list or syntax error in file
2399 return False
2400 linenum = end_line
2401 pos = end_pos
2402 return False
2403
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002404 def UpdatePreprocessor(self, line):
2405 """Update preprocessor stack.
2406
2407 We need to handle preprocessors due to classes like this:
2408 #ifdef SWIG
2409 struct ResultDetailsPageElementExtensionPoint {
2410 #else
2411 struct ResultDetailsPageElementExtensionPoint : public Extension {
2412 #endif
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002413
2414 We make the following assumptions (good enough for most files):
2415 - Preprocessor condition evaluates to true from #if up to first
2416 #else/#elif/#endif.
2417
2418 - Preprocessor condition evaluates to false from #else/#elif up
2419 to #endif. We still perform lint checks on these lines, but
2420 these do not affect nesting stack.
2421
2422 Args:
2423 line: current line to check.
2424 """
2425 if Match(r'^\s*#\s*(if|ifdef|ifndef)\b', line):
2426 # Beginning of #if block, save the nesting stack here. The saved
2427 # stack will allow us to restore the parsing state in the #else case.
2428 self.pp_stack.append(_PreprocessorInfo(copy.deepcopy(self.stack)))
2429 elif Match(r'^\s*#\s*(else|elif)\b', line):
2430 # Beginning of #else block
2431 if self.pp_stack:
2432 if not self.pp_stack[-1].seen_else:
2433 # This is the first #else or #elif block. Remember the
2434 # whole nesting stack up to this point. This is what we
2435 # keep after the #endif.
2436 self.pp_stack[-1].seen_else = True
2437 self.pp_stack[-1].stack_before_else = copy.deepcopy(self.stack)
2438
2439 # Restore the stack to how it was before the #if
2440 self.stack = copy.deepcopy(self.pp_stack[-1].stack_before_if)
2441 else:
2442 # TODO(unknown): unexpected #else, issue warning?
2443 pass
2444 elif Match(r'^\s*#\s*endif\b', line):
2445 # End of #if or #else blocks.
2446 if self.pp_stack:
2447 # If we saw an #else, we will need to restore the nesting
2448 # stack to its former state before the #else, otherwise we
2449 # will just continue from where we left off.
2450 if self.pp_stack[-1].seen_else:
2451 # Here we can just use a shallow copy since we are the last
2452 # reference to it.
2453 self.stack = self.pp_stack[-1].stack_before_else
2454 # Drop the corresponding #if
2455 self.pp_stack.pop()
2456 else:
2457 # TODO(unknown): unexpected #endif, issue warning?
2458 pass
2459
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002460 # TODO(unknown): Update() is too long, but we will refactor later.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002461 def Update(self, filename, clean_lines, linenum, error):
2462 """Update nesting state with current line.
2463
2464 Args:
2465 filename: The name of the current file.
2466 clean_lines: A CleansedLines instance containing the file.
2467 linenum: The number of the line to check.
2468 error: The function to call with any errors found.
2469 """
2470 line = clean_lines.elided[linenum]
2471
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002472 # Remember top of the previous nesting stack.
2473 #
2474 # The stack is always pushed/popped and not modified in place, so
2475 # we can just do a shallow copy instead of copy.deepcopy. Using
2476 # deepcopy would slow down cpplint by ~28%.
2477 if self.stack:
2478 self.previous_stack_top = self.stack[-1]
2479 else:
2480 self.previous_stack_top = None
2481
2482 # Update pp_stack
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002483 self.UpdatePreprocessor(line)
2484
2485 # Count parentheses. This is to avoid adding struct arguments to
2486 # the nesting stack.
2487 if self.stack:
2488 inner_block = self.stack[-1]
2489 depth_change = line.count('(') - line.count(')')
2490 inner_block.open_parentheses += depth_change
2491
2492 # Also check if we are starting or ending an inline assembly block.
2493 if inner_block.inline_asm in (_NO_ASM, _END_ASM):
2494 if (depth_change != 0 and
2495 inner_block.open_parentheses == 1 and
2496 _MATCH_ASM.match(line)):
2497 # Enter assembly block
2498 inner_block.inline_asm = _INSIDE_ASM
2499 else:
2500 # Not entering assembly block. If previous line was _END_ASM,
2501 # we will now shift to _NO_ASM state.
2502 inner_block.inline_asm = _NO_ASM
2503 elif (inner_block.inline_asm == _INSIDE_ASM and
2504 inner_block.open_parentheses == 0):
2505 # Exit assembly block
2506 inner_block.inline_asm = _END_ASM
2507
2508 # Consume namespace declaration at the beginning of the line. Do
2509 # this in a loop so that we catch same line declarations like this:
2510 # namespace proto2 { namespace bridge { class MessageSet; } }
2511 while True:
2512 # Match start of namespace. The "\b\s*" below catches namespace
2513 # declarations even if it weren't followed by a whitespace, this
2514 # is so that we don't confuse our namespace checker. The
2515 # missing spaces will be flagged by CheckSpacing.
2516 namespace_decl_match = Match(r'^\s*namespace\b\s*([:\w]+)?(.*)$', line)
2517 if not namespace_decl_match:
2518 break
2519
2520 new_namespace = _NamespaceInfo(namespace_decl_match.group(1), linenum)
2521 self.stack.append(new_namespace)
2522
2523 line = namespace_decl_match.group(2)
2524 if line.find('{') != -1:
2525 new_namespace.seen_open_brace = True
2526 line = line[line.find('{') + 1:]
2527
2528 # Look for a class declaration in whatever is left of the line
2529 # after parsing namespaces. The regexp accounts for decorated classes
2530 # such as in:
2531 # class LOCKABLE API Object {
2532 # };
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002533 class_decl_match = Match(
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002534 r'^(\s*(?:template\s*<[\w\s<>,:]*>\s*)?'
Clemens Hammacher2cc6e252018-12-20 08:40:19 +00002535 r'(class|struct)\s+(?:[A-Z0-9_]+\s+)*(\w+(?:::\w+)*))'
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002536 r'(.*)$', line)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002537 if (class_decl_match and
2538 (not self.stack or self.stack[-1].open_parentheses == 0)):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002539 # We do not want to accept classes that are actually template arguments:
2540 # template <class Ignore1,
2541 # class Ignore2 = Default<Args>,
2542 # template <Args> class Ignore3>
2543 # void Function() {};
2544 #
2545 # To avoid template argument cases, we scan forward and look for
2546 # an unmatched '>'. If we see one, assume we are inside a
2547 # template argument list.
2548 end_declaration = len(class_decl_match.group(1))
2549 if not self.InTemplateArgumentList(clean_lines, linenum, end_declaration):
2550 self.stack.append(_ClassInfo(
2551 class_decl_match.group(3), class_decl_match.group(2),
2552 clean_lines, linenum))
2553 line = class_decl_match.group(4)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002554
2555 # If we have not yet seen the opening brace for the innermost block,
2556 # run checks here.
2557 if not self.SeenOpenBrace():
2558 self.stack[-1].CheckBegin(filename, clean_lines, linenum, error)
2559
2560 # Update access control if we are inside a class/struct
2561 if self.stack and isinstance(self.stack[-1], _ClassInfo):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002562 classinfo = self.stack[-1]
2563 access_match = Match(
2564 r'^(.*)\b(public|private|protected|signals)(\s+(?:slots\s*)?)?'
2565 r':(?:[^:]|$)',
2566 line)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002567 if access_match:
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002568 classinfo.access = access_match.group(2)
2569
2570 # Check that access keywords are indented +1 space. Skip this
2571 # check if the keywords are not preceded by whitespaces.
2572 indent = access_match.group(1)
2573 if (len(indent) != classinfo.class_indent + 1 and
2574 Match(r'^\s*$', indent)):
2575 if classinfo.is_struct:
2576 parent = 'struct ' + classinfo.name
2577 else:
2578 parent = 'class ' + classinfo.name
2579 slots = ''
2580 if access_match.group(3):
2581 slots = access_match.group(3)
2582 error(filename, linenum, 'whitespace/indent', 3,
2583 '%s%s: should be indented +1 space inside %s' % (
2584 access_match.group(2), slots, parent))
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002585
2586 # Consume braces or semicolons from what's left of the line
2587 while True:
2588 # Match first brace, semicolon, or closed parenthesis.
2589 matched = Match(r'^[^{;)}]*([{;)}])(.*)$', line)
2590 if not matched:
2591 break
2592
2593 token = matched.group(1)
2594 if token == '{':
2595 # If namespace or class hasn't seen a opening brace yet, mark
2596 # namespace/class head as complete. Push a new block onto the
2597 # stack otherwise.
2598 if not self.SeenOpenBrace():
2599 self.stack[-1].seen_open_brace = True
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002600 elif Match(r'^extern\s*"[^"]*"\s*\{', line):
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002601 self.stack.append(_ExternCInfo(linenum))
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002602 else:
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002603 self.stack.append(_BlockInfo(linenum, True))
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002604 if _MATCH_ASM.match(line):
2605 self.stack[-1].inline_asm = _BLOCK_ASM
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002606
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002607 elif token == ';' or token == ')':
2608 # If we haven't seen an opening brace yet, but we already saw
2609 # a semicolon, this is probably a forward declaration. Pop
2610 # the stack for these.
2611 #
2612 # Similarly, if we haven't seen an opening brace yet, but we
2613 # already saw a closing parenthesis, then these are probably
2614 # function arguments with extra "class" or "struct" keywords.
2615 # Also pop these stack for these.
2616 if not self.SeenOpenBrace():
2617 self.stack.pop()
2618 else: # token == '}'
2619 # Perform end of block checks and pop the stack.
2620 if self.stack:
2621 self.stack[-1].CheckEnd(filename, clean_lines, linenum, error)
2622 self.stack.pop()
2623 line = matched.group(2)
2624
2625 def InnermostClass(self):
2626 """Get class info on the top of the stack.
2627
2628 Returns:
2629 A _ClassInfo object if we are inside a class, or None otherwise.
2630 """
2631 for i in range(len(self.stack), 0, -1):
2632 classinfo = self.stack[i - 1]
2633 if isinstance(classinfo, _ClassInfo):
2634 return classinfo
2635 return None
2636
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002637 def CheckCompletedBlocks(self, filename, error):
2638 """Checks that all classes and namespaces have been completely parsed.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002639
2640 Call this when all lines in a file have been processed.
2641 Args:
2642 filename: The name of the current file.
2643 error: The function to call with any errors found.
2644 """
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002645 # Note: This test can result in false positives if #ifdef constructs
2646 # get in the way of brace matching. See the testBuildClass test in
2647 # cpplint_unittest.py for an example of this.
2648 for obj in self.stack:
2649 if isinstance(obj, _ClassInfo):
2650 error(filename, obj.starting_linenum, 'build/class', 5,
2651 'Failed to find complete declaration of class %s' %
2652 obj.name)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002653 elif isinstance(obj, _NamespaceInfo):
2654 error(filename, obj.starting_linenum, 'build/namespaces', 5,
2655 'Failed to find complete declaration of namespace %s' %
2656 obj.name)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002657
2658
2659def CheckForNonStandardConstructs(filename, clean_lines, linenum,
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002660 nesting_state, error):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002661 r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002662
2663 Complain about several constructs which gcc-2 accepts, but which are
2664 not standard C++. Warning about these in lint is one way to ease the
2665 transition to new compilers.
2666 - put storage class first (e.g. "static const" instead of "const static").
2667 - "%lld" instead of %qd" in printf-type functions.
2668 - "%1$d" is non-standard in printf-type functions.
2669 - "\%" is an undefined character escape sequence.
2670 - text after #endif is not allowed.
2671 - invalid inner-style forward declaration.
2672 - >? and <? operators, and their >?= and <?= cousins.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002673
erg@google.com26970fa2009-11-17 18:07:32 +00002674 Additionally, check for constructor/destructor style violations and reference
2675 members, as it is very convenient to do so while checking for
2676 gcc-2 compliance.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002677
2678 Args:
2679 filename: The name of the current file.
2680 clean_lines: A CleansedLines instance containing the file.
2681 linenum: The number of the line to check.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002682 nesting_state: A NestingState instance which maintains information about
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002683 the current stack of nested blocks being parsed.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002684 error: A callable to which errors are reported, which takes 4 arguments:
2685 filename, line number, error level, and message
2686 """
2687
2688 # Remove comments from the line, but leave in strings for now.
2689 line = clean_lines.lines[linenum]
2690
2691 if Search(r'printf\s*\(.*".*%[-+ ]?\d*q', line):
2692 error(filename, linenum, 'runtime/printf_format', 3,
2693 '%q in format strings is deprecated. Use %ll instead.')
2694
2695 if Search(r'printf\s*\(.*".*%\d+\$', line):
2696 error(filename, linenum, 'runtime/printf_format', 2,
2697 '%N$ formats are unconventional. Try rewriting to avoid them.')
2698
2699 # Remove escaped backslashes before looking for undefined escapes.
2700 line = line.replace('\\\\', '')
2701
2702 if Search(r'("|\').*\\(%|\[|\(|{)', line):
2703 error(filename, linenum, 'build/printf_format', 3,
2704 '%, [, (, and { are undefined character escapes. Unescape them.')
2705
2706 # For the rest, work with both comments and strings removed.
2707 line = clean_lines.elided[linenum]
2708
2709 if Search(r'\b(const|volatile|void|char|short|int|long'
2710 r'|float|double|signed|unsigned'
2711 r'|schar|u?int8|u?int16|u?int32|u?int64)'
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002712 r'\s+(register|static|extern|typedef)\b',
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002713 line):
2714 error(filename, linenum, 'build/storage_class', 5,
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002715 'Storage-class specifier (static, extern, typedef, etc) should be '
2716 'at the beginning of the declaration.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002717
2718 if Match(r'\s*#\s*endif\s*[^/\s]+', line):
2719 error(filename, linenum, 'build/endif_comment', 5,
2720 'Uncommented text after #endif is non-standard. Use a comment.')
2721
2722 if Match(r'\s*class\s+(\w+\s*::\s*)+\w+\s*;', line):
2723 error(filename, linenum, 'build/forward_decl', 5,
2724 'Inner-style forward declarations are invalid. Remove this line.')
2725
2726 if Search(r'(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?',
2727 line):
2728 error(filename, linenum, 'build/deprecated', 3,
2729 '>? and <? (max and min) operators are non-standard and deprecated.')
2730
erg@google.com26970fa2009-11-17 18:07:32 +00002731 if Search(r'^\s*const\s*string\s*&\s*\w+\s*;', line):
2732 # TODO(unknown): Could it be expanded safely to arbitrary references,
2733 # without triggering too many false positives? The first
2734 # attempt triggered 5 warnings for mostly benign code in the regtest, hence
2735 # the restriction.
2736 # Here's the original regexp, for the reference:
2737 # type_name = r'\w+((\s*::\s*\w+)|(\s*<\s*\w+?\s*>))?'
2738 # r'\s*const\s*' + type_name + '\s*&\s*\w+\s*;'
2739 error(filename, linenum, 'runtime/member_string_references', 2,
2740 'const string& members are dangerous. It is much better to use '
2741 'alternatives, such as pointers or simple constants.')
2742
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002743 # Everything else in this function operates on class declarations.
2744 # Return early if the top of the nesting stack is not a class, or if
2745 # the class head is not completed yet.
2746 classinfo = nesting_state.InnermostClass()
2747 if not classinfo or not classinfo.seen_open_brace:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002748 return
2749
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002750 # The class may have been declared with namespace or classname qualifiers.
2751 # The constructor and destructor will not have those qualifiers.
2752 base_classname = classinfo.name.split('::')[-1]
2753
2754 # Look for single-argument constructors that aren't marked explicit.
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002755 # Technically a valid construct, but against style.
avakulenko@google.com59146752014-08-11 20:20:55 +00002756 explicit_constructor_match = Match(
danakjd7f56752017-02-22 11:45:06 -05002757 r'\s+(?:(?:inline|constexpr)\s+)*(explicit\s+)?'
2758 r'(?:(?:inline|constexpr)\s+)*%s\s*'
avakulenko@google.com59146752014-08-11 20:20:55 +00002759 r'\(((?:[^()]|\([^()]*\))*)\)'
2760 % re.escape(base_classname),
2761 line)
2762
2763 if explicit_constructor_match:
2764 is_marked_explicit = explicit_constructor_match.group(1)
2765
2766 if not explicit_constructor_match.group(2):
2767 constructor_args = []
2768 else:
2769 constructor_args = explicit_constructor_match.group(2).split(',')
2770
2771 # collapse arguments so that commas in template parameter lists and function
2772 # argument parameter lists don't split arguments in two
2773 i = 0
2774 while i < len(constructor_args):
2775 constructor_arg = constructor_args[i]
2776 while (constructor_arg.count('<') > constructor_arg.count('>') or
2777 constructor_arg.count('(') > constructor_arg.count(')')):
2778 constructor_arg += ',' + constructor_args[i + 1]
2779 del constructor_args[i + 1]
2780 constructor_args[i] = constructor_arg
2781 i += 1
2782
2783 defaulted_args = [arg for arg in constructor_args if '=' in arg]
2784 noarg_constructor = (not constructor_args or # empty arg list
2785 # 'void' arg specifier
2786 (len(constructor_args) == 1 and
2787 constructor_args[0].strip() == 'void'))
2788 onearg_constructor = ((len(constructor_args) == 1 and # exactly one arg
2789 not noarg_constructor) or
2790 # all but at most one arg defaulted
2791 (len(constructor_args) >= 1 and
2792 not noarg_constructor and
2793 len(defaulted_args) >= len(constructor_args) - 1))
2794 initializer_list_constructor = bool(
2795 onearg_constructor and
2796 Search(r'\bstd\s*::\s*initializer_list\b', constructor_args[0]))
2797 copy_constructor = bool(
2798 onearg_constructor and
2799 Match(r'(const\s+)?%s(\s*<[^>]*>)?(\s+const)?\s*(?:<\w+>\s*)?&'
2800 % re.escape(base_classname), constructor_args[0].strip()))
2801
2802 if (not is_marked_explicit and
2803 onearg_constructor and
2804 not initializer_list_constructor and
2805 not copy_constructor):
2806 if defaulted_args:
2807 error(filename, linenum, 'runtime/explicit', 5,
2808 'Constructors callable with one argument '
2809 'should be marked explicit.')
2810 else:
2811 error(filename, linenum, 'runtime/explicit', 5,
2812 'Single-parameter constructors should be marked explicit.')
2813 elif is_marked_explicit and not onearg_constructor:
2814 if noarg_constructor:
2815 error(filename, linenum, 'runtime/explicit', 5,
2816 'Zero-parameter constructors should not be marked explicit.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002817
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002818
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002819def CheckSpacingForFunctionCall(filename, clean_lines, linenum, error):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002820 """Checks for the correctness of various spacing around function calls.
2821
2822 Args:
2823 filename: The name of the current file.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002824 clean_lines: A CleansedLines instance containing the file.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002825 linenum: The number of the line to check.
2826 error: The function to call with any errors found.
2827 """
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002828 line = clean_lines.elided[linenum]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002829
2830 # Since function calls often occur inside if/for/while/switch
2831 # expressions - which have their own, more liberal conventions - we
2832 # first see if we should be looking inside such an expression for a
2833 # function call, to which we can apply more strict standards.
2834 fncall = line # if there's no control flow construct, look at whole line
2835 for pattern in (r'\bif\s*\((.*)\)\s*{',
2836 r'\bfor\s*\((.*)\)\s*{',
2837 r'\bwhile\s*\((.*)\)\s*[{;]',
2838 r'\bswitch\s*\((.*)\)\s*{'):
2839 match = Search(pattern, line)
2840 if match:
2841 fncall = match.group(1) # look inside the parens for function calls
2842 break
2843
2844 # Except in if/for/while/switch, there should never be space
2845 # immediately inside parens (eg "f( 3, 4 )"). We make an exception
2846 # for nested parens ( (a+b) + c ). Likewise, there should never be
2847 # a space before a ( when it's a function argument. I assume it's a
2848 # function argument when the char before the whitespace is legal in
2849 # a function name (alnum + _) and we're not starting a macro. Also ignore
2850 # pointers and references to arrays and functions coz they're too tricky:
2851 # we use a very simple way to recognize these:
2852 # " (something)(maybe-something)" or
2853 # " (something)(maybe-something," or
2854 # " (something)[something]"
2855 # Note that we assume the contents of [] to be short enough that
2856 # they'll never need to wrap.
2857 if ( # Ignore control structures.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002858 not Search(r'\b(if|for|while|switch|return|new|delete|catch|sizeof)\b',
2859 fncall) and
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002860 # Ignore pointers/references to functions.
2861 not Search(r' \([^)]+\)\([^)]*(\)|,$)', fncall) and
2862 # Ignore pointers/references to arrays.
2863 not Search(r' \([^)]+\)\[[^\]]+\]', fncall)):
erg@google.com6317a9c2009-06-25 00:28:19 +00002864 if Search(r'\w\s*\(\s(?!\s*\\$)', fncall): # a ( used for a fn call
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002865 error(filename, linenum, 'whitespace/parens', 4,
2866 'Extra space after ( in function call')
erg@google.com6317a9c2009-06-25 00:28:19 +00002867 elif Search(r'\(\s+(?!(\s*\\)|\()', fncall):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002868 error(filename, linenum, 'whitespace/parens', 2,
2869 'Extra space after (')
2870 if (Search(r'\w\s+\(', fncall) and
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002871 not Search(r'_{0,2}asm_{0,2}\s+_{0,2}volatile_{0,2}\s+\(', fncall) and
Bruce Dawson3e87cea2020-04-30 17:56:07 +00002872 not Search(r'#\s*define|typedef|__except|using\s+\w+\s*=', fncall) and
avakulenko@google.com255f2be2014-12-05 22:19:55 +00002873 not Search(r'\w\s+\((\w+::)*\*\w+\)\(', fncall) and
2874 not Search(r'\bcase\s+\(', fncall)):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002875 # TODO(unknown): Space after an operator function seem to be a common
2876 # error, silence those for now by restricting them to highest verbosity.
2877 if Search(r'\boperator_*\b', line):
2878 error(filename, linenum, 'whitespace/parens', 0,
2879 'Extra space before ( in function call')
2880 else:
2881 error(filename, linenum, 'whitespace/parens', 4,
2882 'Extra space before ( in function call')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002883 # If the ) is followed only by a newline or a { + newline, assume it's
2884 # part of a control statement (if/while/etc), and don't complain
2885 if Search(r'[^)]\s+\)\s*[^{\s]', fncall):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00002886 # If the closing parenthesis is preceded by only whitespaces,
2887 # try to give a more descriptive error message.
2888 if Search(r'^\s+\)', fncall):
2889 error(filename, linenum, 'whitespace/parens', 2,
2890 'Closing ) should be moved to the previous line')
2891 else:
2892 error(filename, linenum, 'whitespace/parens', 2,
2893 'Extra space before )')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002894
2895
2896def IsBlankLine(line):
2897 """Returns true if the given line is blank.
2898
2899 We consider a line to be blank if the line is empty or consists of
2900 only white spaces.
2901
2902 Args:
2903 line: A line of a string.
2904
2905 Returns:
2906 True, if the given line is blank.
2907 """
2908 return not line or line.isspace()
2909
2910
avakulenko@google.com59146752014-08-11 20:20:55 +00002911def CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line,
2912 error):
2913 is_namespace_indent_item = (
2914 len(nesting_state.stack) > 1 and
2915 nesting_state.stack[-1].check_namespace_indentation and
2916 isinstance(nesting_state.previous_stack_top, _NamespaceInfo) and
2917 nesting_state.previous_stack_top == nesting_state.stack[-2])
2918
2919 if ShouldCheckNamespaceIndentation(nesting_state, is_namespace_indent_item,
2920 clean_lines.elided, line):
2921 CheckItemIndentationInNamespace(filename, clean_lines.elided,
2922 line, error)
2923
2924
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002925def CheckForFunctionLengths(filename, clean_lines, linenum,
2926 function_state, error):
2927 """Reports for long function bodies.
2928
2929 For an overview why this is done, see:
Alexandr Ilinff294c32017-04-27 15:57:40 +02002930 https://google.github.io/styleguide/cppguide.html#Write_Short_Functions
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002931
2932 Uses a simplistic algorithm assuming other style guidelines
2933 (especially spacing) are followed.
2934 Only checks unindented functions, so class members are unchecked.
2935 Trivial bodies are unchecked, so constructors with huge initializer lists
2936 may be missed.
2937 Blank/comment lines are not counted so as to avoid encouraging the removal
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00002938 of vertical space and comments just to get through a lint check.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002939 NOLINT *on the last line of a function* disables this check.
2940
2941 Args:
2942 filename: The name of the current file.
2943 clean_lines: A CleansedLines instance containing the file.
2944 linenum: The number of the line to check.
2945 function_state: Current function name and lines in body so far.
2946 error: The function to call with any errors found.
2947 """
2948 lines = clean_lines.lines
2949 line = lines[linenum]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002950 joined_line = ''
2951
2952 starting_func = False
erg@google.com6317a9c2009-06-25 00:28:19 +00002953 regexp = r'(\w(\w|::|\*|\&|\s)*)\(' # decls * & space::name( ...
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002954 match_result = Match(regexp, line)
2955 if match_result:
2956 # If the name is all caps and underscores, figure it's a macro and
2957 # ignore it, unless it's TEST or TEST_F.
2958 function_name = match_result.group(1).split()[-1]
2959 if function_name == 'TEST' or function_name == 'TEST_F' or (
Quinten Yearsley48099572019-02-22 21:13:37 +00002960 not Match(r'[A-Z_0-9]+$', function_name)):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002961 starting_func = True
2962
2963 if starting_func:
2964 body_found = False
Edward Lemur6d31ed52019-12-02 23:00:00 +00002965 for start_linenum in range(linenum, clean_lines.NumLines()):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002966 start_line = lines[start_linenum]
2967 joined_line += ' ' + start_line.lstrip()
2968 if Search(r'(;|})', start_line): # Declarations and trivial functions
2969 body_found = True
2970 break # ... ignore
2971 elif Search(r'{', start_line):
2972 body_found = True
2973 function = Search(r'((\w|:)*)\(', line).group(1)
2974 if Match(r'TEST', function): # Handle TEST... macros
2975 parameter_regexp = Search(r'(\(.*\))', joined_line)
2976 if parameter_regexp: # Ignore bad syntax
2977 function += parameter_regexp.group(1)
2978 else:
2979 function += '()'
2980 function_state.Begin(function)
2981 break
2982 if not body_found:
erg@google.com6317a9c2009-06-25 00:28:19 +00002983 # No body for the function (or evidence of a non-function) was found.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002984 error(filename, linenum, 'readability/fn_size', 5,
2985 'Lint failed to find start of function body.')
2986 elif Match(r'^\}\s*$', line): # function end
erg@google.com35589e62010-11-17 18:58:16 +00002987 function_state.Check(error, filename, linenum)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002988 function_state.End()
2989 elif not Match(r'^\s*$', line):
2990 function_state.Count() # Count non-blank/non-comment lines.
2991
2992
2993_RE_PATTERN_TODO = re.compile(r'^//(\s*)TODO(\(.+?\))?:?(\s|$)?')
2994
2995
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002996def CheckComment(line, filename, linenum, next_line_start, error):
2997 """Checks for common mistakes in comments.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002998
2999 Args:
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003000 line: The line in question.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003001 filename: The name of the current file.
3002 linenum: The number of the line to check.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003003 next_line_start: The first non-whitespace column of the next line.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003004 error: The function to call with any errors found.
3005 """
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003006 commentpos = line.find('//')
3007 if commentpos != -1:
3008 # Check if the // may be in quotes. If so, ignore it
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003009 if re.sub(r'\\.', '', line[0:commentpos]).count('"') % 2 == 0:
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003010 # Allow one space for new scopes, two spaces otherwise:
3011 if (not (Match(r'^.*{ *//', line) and next_line_start == commentpos) and
3012 ((commentpos >= 1 and
3013 line[commentpos-1] not in string.whitespace) or
3014 (commentpos >= 2 and
3015 line[commentpos-2] not in string.whitespace))):
3016 error(filename, linenum, 'whitespace/comments', 2,
3017 'At least two spaces is best between code and comments')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003018
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003019 # Checks for common mistakes in TODO comments.
3020 comment = line[commentpos:]
3021 match = _RE_PATTERN_TODO.match(comment)
3022 if match:
3023 # One whitespace is correct; zero whitespace is handled elsewhere.
3024 leading_whitespace = match.group(1)
3025 if len(leading_whitespace) > 1:
3026 error(filename, linenum, 'whitespace/todo', 2,
3027 'Too many spaces before TODO')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003028
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003029 username = match.group(2)
3030 if not username:
3031 error(filename, linenum, 'readability/todo', 2,
3032 'Missing username in TODO; it should look like '
3033 '"// TODO(my_username): Stuff."')
3034
3035 middle_whitespace = match.group(3)
3036 # Comparisons made explicit for correctness -- pylint: disable=g-explicit-bool-comparison
3037 if middle_whitespace != ' ' and middle_whitespace != '':
3038 error(filename, linenum, 'whitespace/todo', 2,
3039 'TODO(my_username) should be followed by a space')
3040
3041 # If the comment contains an alphanumeric character, there
avakulenko@google.com255f2be2014-12-05 22:19:55 +00003042 # should be a space somewhere between it and the // unless
3043 # it's a /// or //! Doxygen comment.
3044 if (Match(r'//[^ ]*\w', comment) and
3045 not Match(r'(///|//\!)(\s+|$)', comment)):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003046 error(filename, linenum, 'whitespace/comments', 4,
3047 'Should have a space between // and comment')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003048
avakulenko@google.com255f2be2014-12-05 22:19:55 +00003049
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003050def CheckSpacing(filename, clean_lines, linenum, nesting_state, error):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003051 """Checks for the correctness of various spacing issues in the code.
3052
3053 Things we check for: spaces around operators, spaces after
3054 if/for/while/switch, no spaces around parens in function calls, two
3055 spaces between code and comment, don't start a block with a blank
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003056 line, don't end a function with a blank line, don't add a blank line
3057 after public/protected/private, don't have too many blank lines in a row.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003058
3059 Args:
3060 filename: The name of the current file.
3061 clean_lines: A CleansedLines instance containing the file.
3062 linenum: The number of the line to check.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003063 nesting_state: A NestingState instance which maintains information about
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003064 the current stack of nested blocks being parsed.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003065 error: The function to call with any errors found.
3066 """
3067
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003068 # Don't use "elided" lines here, otherwise we can't check commented lines.
3069 # Don't want to use "raw" either, because we don't want to check inside C++11
3070 # raw strings,
3071 raw = clean_lines.lines_without_raw_strings
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003072 line = raw[linenum]
3073
3074 # Before nixing comments, check if the line is blank for no good
3075 # reason. This includes the first line after a block is opened, and
3076 # blank lines at the end of a function (ie, right before a line like '}'
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003077 #
3078 # Skip all the blank line checks if we are immediately inside a
3079 # namespace body. In other words, don't issue blank line warnings
3080 # for this block:
3081 # namespace {
3082 #
3083 # }
3084 #
3085 # A warning about missing end of namespace comments will be issued instead.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003086 #
3087 # Also skip blank line checks for 'extern "C"' blocks, which are formatted
3088 # like namespaces.
3089 if (IsBlankLine(line) and
3090 not nesting_state.InNamespaceBody() and
3091 not nesting_state.InExternC()):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003092 elided = clean_lines.elided
3093 prev_line = elided[linenum - 1]
3094 prevbrace = prev_line.rfind('{')
3095 # TODO(unknown): Don't complain if line before blank line, and line after,
3096 # both start with alnums and are indented the same amount.
3097 # This ignores whitespace at the start of a namespace block
3098 # because those are not usually indented.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003099 if prevbrace != -1 and prev_line[prevbrace:].find('}') == -1:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003100 # OK, we have a blank line at the start of a code block. Before we
3101 # complain, we check if it is an exception to the rule: The previous
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003102 # non-empty line has the parameters of a function header that are indented
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003103 # 4 spaces (because they did not fit in a 80 column line when placed on
3104 # the same line as the function name). We also check for the case where
3105 # the previous line is indented 6 spaces, which may happen when the
3106 # initializers of a constructor do not fit into a 80 column line.
3107 exception = False
3108 if Match(r' {6}\w', prev_line): # Initializer list?
3109 # We are looking for the opening column of initializer list, which
3110 # should be indented 4 spaces to cause 6 space indentation afterwards.
3111 search_position = linenum-2
3112 while (search_position >= 0
3113 and Match(r' {6}\w', elided[search_position])):
3114 search_position -= 1
3115 exception = (search_position >= 0
3116 and elided[search_position][:5] == ' :')
3117 else:
3118 # Search for the function arguments or an initializer list. We use a
3119 # simple heuristic here: If the line is indented 4 spaces; and we have a
3120 # closing paren, without the opening paren, followed by an opening brace
3121 # or colon (for initializer lists) we assume that it is the last line of
3122 # a function header. If we have a colon indented 4 spaces, it is an
3123 # initializer list.
3124 exception = (Match(r' {4}\w[^\(]*\)\s*(const\s*)?(\{\s*$|:)',
3125 prev_line)
3126 or Match(r' {4}:', prev_line))
3127
3128 if not exception:
3129 error(filename, linenum, 'whitespace/blank_line', 2,
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003130 'Redundant blank line at the start of a code block '
3131 'should be deleted.')
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003132 # Ignore blank lines at the end of a block in a long if-else
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003133 # chain, like this:
3134 # if (condition1) {
3135 # // Something followed by a blank line
3136 #
3137 # } else if (condition2) {
3138 # // Something else
3139 # }
3140 if linenum + 1 < clean_lines.NumLines():
3141 next_line = raw[linenum + 1]
3142 if (next_line
3143 and Match(r'\s*}', next_line)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003144 and next_line.find('} else ') == -1):
3145 error(filename, linenum, 'whitespace/blank_line', 3,
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003146 'Redundant blank line at the end of a code block '
3147 'should be deleted.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003148
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003149 matched = Match(r'\s*(public|protected|private):', prev_line)
3150 if matched:
3151 error(filename, linenum, 'whitespace/blank_line', 3,
3152 'Do not leave a blank line after "%s:"' % matched.group(1))
3153
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003154 # Next, check comments
3155 next_line_start = 0
3156 if linenum + 1 < clean_lines.NumLines():
3157 next_line = raw[linenum + 1]
3158 next_line_start = len(next_line) - len(next_line.lstrip())
3159 CheckComment(line, filename, linenum, next_line_start, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003160
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003161 # get rid of comments and strings
3162 line = clean_lines.elided[linenum]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003163
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003164 # You shouldn't have spaces before your brackets, except maybe after
Derek Morrisb8265f12020-04-16 18:40:27 +00003165 # 'delete []' or 'return []() {};', or in the case of c++ attributes
3166 # like 'class [[clang::lto_visibility_public]] MyClass'.
3167 if (Search(r'\w\s+\[', line)
3168 and not Search(r'(?:delete|return)\s+\[', line)
3169 and not Search(r'\s+\[\[', line)):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003170 error(filename, linenum, 'whitespace/braces', 5,
3171 'Extra space before [')
3172
3173 # In range-based for, we wanted spaces before and after the colon, but
3174 # not around "::" tokens that might appear.
3175 if (Search(r'for *\(.*[^:]:[^: ]', line) or
3176 Search(r'for *\(.*[^: ]:[^:]', line)):
3177 error(filename, linenum, 'whitespace/forcolon', 2,
3178 'Missing space around colon in range-based for loop')
3179
3180
3181def CheckOperatorSpacing(filename, clean_lines, linenum, error):
3182 """Checks for horizontal spacing around operators.
3183
3184 Args:
3185 filename: The name of the current file.
3186 clean_lines: A CleansedLines instance containing the file.
3187 linenum: The number of the line to check.
3188 error: The function to call with any errors found.
3189 """
3190 line = clean_lines.elided[linenum]
3191
3192 # Don't try to do spacing checks for operator methods. Do this by
3193 # replacing the troublesome characters with something else,
3194 # preserving column position for all other characters.
3195 #
3196 # The replacement is done repeatedly to avoid false positives from
3197 # operators that call operators.
3198 while True:
3199 match = Match(r'^(.*\boperator\b)(\S+)(\s*\(.*)$', line)
3200 if match:
3201 line = match.group(1) + ('_' * len(match.group(2))) + match.group(3)
3202 else:
3203 break
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003204
3205 # We allow no-spaces around = within an if: "if ( (a=Foo()) == 0 )".
3206 # Otherwise not. Note we only check for non-spaces on *both* sides;
3207 # sometimes people put non-spaces on one side when aligning ='s among
3208 # many lines (not that this is behavior that I approve of...)
avakulenko@google.com255f2be2014-12-05 22:19:55 +00003209 if ((Search(r'[\w.]=', line) or
3210 Search(r'=[\w.]', line))
3211 and not Search(r'\b(if|while|for) ', line)
3212 # Operators taken from [lex.operators] in C++11 standard.
3213 and not Search(r'(>=|<=|==|!=|&=|\^=|\|=|\+=|\*=|\/=|\%=)', line)
3214 and not Search(r'operator=', line)):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003215 error(filename, linenum, 'whitespace/operators', 4,
3216 'Missing spaces around =')
3217
3218 # It's ok not to have spaces around binary operators like + - * /, but if
3219 # there's too little whitespace, we get concerned. It's hard to tell,
3220 # though, so we punt on this one for now. TODO.
3221
3222 # You should always have whitespace around binary operators.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003223 #
3224 # Check <= and >= first to avoid false positives with < and >, then
3225 # check non-include lines for spacing around < and >.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003226 #
3227 # If the operator is followed by a comma, assume it's be used in a
3228 # macro context and don't do any checks. This avoids false
3229 # positives.
3230 #
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003231 # Note that && is not included here. This is because there are too
3232 # many false positives due to RValue references.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003233 match = Search(r'[^<>=!\s](==|!=|<=|>=|\|\|)[^<>=!\s,;\)]', line)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003234 if match:
3235 error(filename, linenum, 'whitespace/operators', 3,
3236 'Missing spaces around %s' % match.group(1))
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003237 elif not Match(r'#.*include', line):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003238 # Look for < that is not surrounded by spaces. This is only
3239 # triggered if both sides are missing spaces, even though
3240 # technically should should flag if at least one side is missing a
3241 # space. This is done to avoid some false positives with shifts.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003242 match = Match(r'^(.*[^\s<])<[^\s=<,]', line)
3243 if match:
3244 (_, _, end_pos) = CloseExpression(
3245 clean_lines, linenum, len(match.group(1)))
3246 if end_pos <= -1:
3247 error(filename, linenum, 'whitespace/operators', 3,
3248 'Missing spaces around <')
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003249
3250 # Look for > that is not surrounded by spaces. Similar to the
3251 # above, we only trigger if both sides are missing spaces to avoid
3252 # false positives with shifts.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003253 match = Match(r'^(.*[^-\s>])>[^\s=>,]', line)
3254 if match:
3255 (_, _, start_pos) = ReverseCloseExpression(
3256 clean_lines, linenum, len(match.group(1)))
3257 if start_pos <= -1:
3258 error(filename, linenum, 'whitespace/operators', 3,
3259 'Missing spaces around >')
3260
3261 # We allow no-spaces around << when used like this: 10<<20, but
3262 # not otherwise (particularly, not when used as streams)
avakulenko@google.com59146752014-08-11 20:20:55 +00003263 #
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003264 # We also allow operators following an opening parenthesis, since
3265 # those tend to be macros that deal with operators.
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003266 match = Search(r'(operator|[^\s(<])(?:L|UL|LL|ULL|l|ul|ll|ull)?<<([^\s,=<])', line)
avakulenko@google.com255f2be2014-12-05 22:19:55 +00003267 if (match and not (match.group(1).isdigit() and match.group(2).isdigit()) and
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003268 not (match.group(1) == 'operator' and match.group(2) == ';')):
3269 error(filename, linenum, 'whitespace/operators', 3,
3270 'Missing spaces around <<')
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003271
3272 # We allow no-spaces around >> for almost anything. This is because
3273 # C++11 allows ">>" to close nested templates, which accounts for
3274 # most cases when ">>" is not followed by a space.
3275 #
3276 # We still warn on ">>" followed by alpha character, because that is
3277 # likely due to ">>" being used for right shifts, e.g.:
3278 # value >> alpha
3279 #
3280 # When ">>" is used to close templates, the alphanumeric letter that
3281 # follows would be part of an identifier, and there should still be
3282 # a space separating the template type and the identifier.
3283 # type<type<type>> alpha
3284 match = Search(r'>>[a-zA-Z_]', line)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003285 if match:
3286 error(filename, linenum, 'whitespace/operators', 3,
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003287 'Missing spaces around >>')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003288
3289 # There shouldn't be space around unary operators
3290 match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line)
3291 if match:
3292 error(filename, linenum, 'whitespace/operators', 4,
3293 'Extra space for operator %s' % match.group(1))
3294
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003295
3296def CheckParenthesisSpacing(filename, clean_lines, linenum, error):
3297 """Checks for horizontal spacing around parentheses.
3298
3299 Args:
3300 filename: The name of the current file.
3301 clean_lines: A CleansedLines instance containing the file.
3302 linenum: The number of the line to check.
3303 error: The function to call with any errors found.
3304 """
3305 line = clean_lines.elided[linenum]
3306
3307 # No spaces after an if, while, switch, or for
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003308 match = Search(r' (if\(|for\(|while\(|switch\()', line)
3309 if match:
3310 error(filename, linenum, 'whitespace/parens', 5,
3311 'Missing space before ( in %s' % match.group(1))
3312
3313 # For if/for/while/switch, the left and right parens should be
3314 # consistent about how many spaces are inside the parens, and
3315 # there should either be zero or one spaces inside the parens.
3316 # We don't want: "if ( foo)" or "if ( foo )".
erg@google.com6317a9c2009-06-25 00:28:19 +00003317 # Exception: "for ( ; foo; bar)" and "for (foo; bar; )" are allowed.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003318 match = Search(r'\b(if|for|while|switch)\s*'
3319 r'\(([ ]*)(.).*[^ ]+([ ]*)\)\s*{\s*$',
3320 line)
3321 if match:
3322 if len(match.group(2)) != len(match.group(4)):
3323 if not (match.group(3) == ';' and
erg@google.com6317a9c2009-06-25 00:28:19 +00003324 len(match.group(2)) == 1 + len(match.group(4)) or
3325 not match.group(2) and Search(r'\bfor\s*\(.*; \)', line)):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003326 error(filename, linenum, 'whitespace/parens', 5,
3327 'Mismatching spaces inside () in %s' % match.group(1))
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003328 if len(match.group(2)) not in [0, 1]:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003329 error(filename, linenum, 'whitespace/parens', 5,
3330 'Should have zero or one spaces inside ( and ) in %s' %
3331 match.group(1))
3332
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003333
3334def CheckCommaSpacing(filename, clean_lines, linenum, error):
3335 """Checks for horizontal spacing near commas and semicolons.
3336
3337 Args:
3338 filename: The name of the current file.
3339 clean_lines: A CleansedLines instance containing the file.
3340 linenum: The number of the line to check.
3341 error: The function to call with any errors found.
3342 """
3343 raw = clean_lines.lines_without_raw_strings
3344 line = clean_lines.elided[linenum]
3345
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003346 # 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 +00003347 #
3348 # This does not apply when the non-space character following the
3349 # comma is another comma, since the only time when that happens is
3350 # for empty macro arguments.
3351 #
3352 # We run this check in two passes: first pass on elided lines to
3353 # verify that lines contain missing whitespaces, second pass on raw
3354 # lines to confirm that those missing whitespaces are not due to
3355 # elided comments.
avakulenko@google.com59146752014-08-11 20:20:55 +00003356 if (Search(r',[^,\s]', ReplaceAll(r'\boperator\s*,\s*\(', 'F(', line)) and
3357 Search(r',[^,\s]', raw[linenum])):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003358 error(filename, linenum, 'whitespace/comma', 3,
3359 'Missing space after ,')
3360
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003361 # You should always have a space after a semicolon
3362 # except for few corner cases
3363 # TODO(unknown): clarify if 'if (1) { return 1;}' is requires one more
3364 # space after ;
3365 if Search(r';[^\s};\\)/]', line):
3366 error(filename, linenum, 'whitespace/semicolon', 3,
3367 'Missing space after ;')
3368
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003369
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003370def _IsType(clean_lines, nesting_state, expr):
3371 """Check if expression looks like a type name, returns true if so.
3372
3373 Args:
3374 clean_lines: A CleansedLines instance containing the file.
3375 nesting_state: A NestingState instance which maintains information about
3376 the current stack of nested blocks being parsed.
3377 expr: The expression to check.
3378 Returns:
3379 True, if token looks like a type.
3380 """
3381 # Keep only the last token in the expression
3382 last_word = Match(r'^.*(\b\S+)$', expr)
3383 if last_word:
3384 token = last_word.group(1)
3385 else:
3386 token = expr
3387
3388 # Match native types and stdint types
3389 if _TYPES.match(token):
3390 return True
3391
3392 # Try a bit harder to match templated types. Walk up the nesting
3393 # stack until we find something that resembles a typename
3394 # declaration for what we are looking for.
3395 typename_pattern = (r'\b(?:typename|class|struct)\s+' + re.escape(token) +
3396 r'\b')
3397 block_index = len(nesting_state.stack) - 1
3398 while block_index >= 0:
3399 if isinstance(nesting_state.stack[block_index], _NamespaceInfo):
3400 return False
3401
3402 # Found where the opening brace is. We want to scan from this
3403 # line up to the beginning of the function, minus a few lines.
3404 # template <typename Type1, // stop scanning here
3405 # ...>
3406 # class C
3407 # : public ... { // start scanning here
3408 last_line = nesting_state.stack[block_index].starting_linenum
3409
3410 next_block_start = 0
3411 if block_index > 0:
3412 next_block_start = nesting_state.stack[block_index - 1].starting_linenum
3413 first_line = last_line
3414 while first_line >= next_block_start:
3415 if clean_lines.elided[first_line].find('template') >= 0:
3416 break
3417 first_line -= 1
3418 if first_line < next_block_start:
3419 # Didn't find any "template" keyword before reaching the next block,
3420 # there are probably no template things to check for this block
3421 block_index -= 1
3422 continue
3423
3424 # Look for typename in the specified range
Edward Lemur6d31ed52019-12-02 23:00:00 +00003425 for i in range(first_line, last_line + 1, 1):
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003426 if Search(typename_pattern, clean_lines.elided[i]):
3427 return True
3428 block_index -= 1
3429
3430 return False
3431
3432
3433def CheckBracesSpacing(filename, clean_lines, linenum, nesting_state, error):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003434 """Checks for horizontal spacing near commas.
3435
3436 Args:
3437 filename: The name of the current file.
3438 clean_lines: A CleansedLines instance containing the file.
3439 linenum: The number of the line to check.
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003440 nesting_state: A NestingState instance which maintains information about
3441 the current stack of nested blocks being parsed.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003442 error: The function to call with any errors found.
3443 """
3444 line = clean_lines.elided[linenum]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003445
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003446 # Except after an opening paren, or after another opening brace (in case of
3447 # an initializer list, for instance), you should have spaces before your
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003448 # braces when they are delimiting blocks, classes, namespaces etc.
3449 # And since you should never have braces at the beginning of a line,
3450 # this is an easy test. Except that braces used for initialization don't
3451 # follow the same rule; we often don't want spaces before those.
avakulenko@google.com255f2be2014-12-05 22:19:55 +00003452 match = Match(r'^(.*[^ ({>]){', line)
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003453
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003454 if match:
3455 # Try a bit harder to check for brace initialization. This
3456 # happens in one of the following forms:
3457 # Constructor() : initializer_list_{} { ... }
3458 # Constructor{}.MemberFunction()
3459 # Type variable{};
3460 # FunctionCall(type{}, ...);
3461 # LastArgument(..., type{});
3462 # LOG(INFO) << type{} << " ...";
3463 # map_of_type[{...}] = ...;
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003464 # ternary = expr ? new type{} : nullptr;
3465 # OuterTemplate<InnerTemplateConstructor<Type>{}>
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003466 #
3467 # We check for the character following the closing brace, and
3468 # silence the warning if it's one of those listed above, i.e.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003469 # "{.;,)<>]:".
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003470 #
3471 # To account for nested initializer list, we allow any number of
3472 # closing braces up to "{;,)<". We can't simply silence the
3473 # warning on first sight of closing brace, because that would
3474 # cause false negatives for things that are not initializer lists.
3475 # Silence this: But not this:
3476 # Outer{ if (...) {
3477 # Inner{...} if (...){ // Missing space before {
3478 # }; }
3479 #
3480 # There is a false negative with this approach if people inserted
3481 # spurious semicolons, e.g. "if (cond){};", but we will catch the
3482 # spurious semicolon with a separate check.
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003483 leading_text = match.group(1)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003484 (endline, endlinenum, endpos) = CloseExpression(
3485 clean_lines, linenum, len(match.group(1)))
3486 trailing_text = ''
3487 if endpos > -1:
3488 trailing_text = endline[endpos:]
Edward Lemur6d31ed52019-12-02 23:00:00 +00003489 for offset in range(endlinenum + 1,
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003490 min(endlinenum + 3, clean_lines.NumLines() - 1)):
3491 trailing_text += clean_lines.elided[offset]
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003492 # We also suppress warnings for `uint64_t{expression}` etc., as the style
3493 # guide recommends brace initialization for integral types to avoid
3494 # overflow/truncation.
3495 if (not Match(r'^[\s}]*[{.;,)<>\]:]', trailing_text)
3496 and not _IsType(clean_lines, nesting_state, leading_text)):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003497 error(filename, linenum, 'whitespace/braces', 5,
3498 'Missing space before {')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003499
3500 # Make sure '} else {' has spaces.
3501 if Search(r'}else', line):
3502 error(filename, linenum, 'whitespace/braces', 5,
3503 'Missing space before else')
3504
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003505 # You shouldn't have a space before a semicolon at the end of the line.
3506 # There's a special case for "for" since the style guide allows space before
3507 # the semicolon there.
3508 if Search(r':\s*;\s*$', line):
3509 error(filename, linenum, 'whitespace/semicolon', 5,
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003510 'Semicolon defining empty statement. Use {} instead.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003511 elif Search(r'^\s*;\s*$', line):
3512 error(filename, linenum, 'whitespace/semicolon', 5,
3513 'Line contains only semicolon. If this should be an empty statement, '
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003514 'use {} instead.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003515 elif (Search(r'\s+;\s*$', line) and
3516 not Search(r'\bfor\b', line)):
3517 error(filename, linenum, 'whitespace/semicolon', 5,
3518 'Extra space before last semicolon. If this should be an empty '
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003519 'statement, use {} instead.')
3520
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003521
3522def IsDecltype(clean_lines, linenum, column):
3523 """Check if the token ending on (linenum, column) is decltype().
3524
3525 Args:
3526 clean_lines: A CleansedLines instance containing the file.
3527 linenum: the number of the line to check.
3528 column: end column of the token to check.
3529 Returns:
3530 True if this token is decltype() expression, False otherwise.
3531 """
3532 (text, _, start_col) = ReverseCloseExpression(clean_lines, linenum, column)
3533 if start_col < 0:
3534 return False
3535 if Search(r'\bdecltype\s*$', text[0:start_col]):
3536 return True
3537 return False
3538
3539
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003540def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error):
3541 """Checks for additional blank line issues related to sections.
3542
3543 Currently the only thing checked here is blank line before protected/private.
3544
3545 Args:
3546 filename: The name of the current file.
3547 clean_lines: A CleansedLines instance containing the file.
3548 class_info: A _ClassInfo objects.
3549 linenum: The number of the line to check.
3550 error: The function to call with any errors found.
3551 """
3552 # Skip checks if the class is small, where small means 25 lines or less.
3553 # 25 lines seems like a good cutoff since that's the usual height of
3554 # terminals, and any class that can't fit in one screen can't really
3555 # be considered "small".
3556 #
3557 # Also skip checks if we are on the first line. This accounts for
3558 # classes that look like
3559 # class Foo { public: ... };
3560 #
3561 # If we didn't find the end of the class, last_line would be zero,
3562 # and the check will be skipped by the first condition.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003563 if (class_info.last_line - class_info.starting_linenum <= 24 or
3564 linenum <= class_info.starting_linenum):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003565 return
3566
3567 matched = Match(r'\s*(public|protected|private):', clean_lines.lines[linenum])
3568 if matched:
3569 # Issue warning if the line before public/protected/private was
3570 # not a blank line, but don't do this if the previous line contains
3571 # "class" or "struct". This can happen two ways:
3572 # - We are at the beginning of the class.
3573 # - We are forward-declaring an inner class that is semantically
3574 # private, but needed to be public for implementation reasons.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003575 # Also ignores cases where the previous line ends with a backslash as can be
3576 # common when defining classes in C macros.
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003577 prev_line = clean_lines.lines[linenum - 1]
3578 if (not IsBlankLine(prev_line) and
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003579 not Search(r'\b(class|struct)\b', prev_line) and
3580 not Search(r'\\$', prev_line)):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003581 # Try a bit harder to find the beginning of the class. This is to
3582 # account for multi-line base-specifier lists, e.g.:
3583 # class Derived
3584 # : public Base {
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003585 end_class_head = class_info.starting_linenum
3586 for i in range(class_info.starting_linenum, linenum):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003587 if Search(r'\{\s*$', clean_lines.lines[i]):
3588 end_class_head = i
3589 break
3590 if end_class_head < linenum - 1:
3591 error(filename, linenum, 'whitespace/blank_line', 3,
3592 '"%s:" should be preceded by a blank line' % matched.group(1))
3593
3594
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003595def GetPreviousNonBlankLine(clean_lines, linenum):
3596 """Return the most recent non-blank line and its line number.
3597
3598 Args:
3599 clean_lines: A CleansedLines instance containing the file contents.
3600 linenum: The number of the line to check.
3601
3602 Returns:
3603 A tuple with two elements. The first element is the contents of the last
3604 non-blank line before the current line, or the empty string if this is the
3605 first non-blank line. The second is the line number of that line, or -1
3606 if this is the first non-blank line.
3607 """
3608
3609 prevlinenum = linenum - 1
3610 while prevlinenum >= 0:
3611 prevline = clean_lines.elided[prevlinenum]
3612 if not IsBlankLine(prevline): # if not a blank line...
3613 return (prevline, prevlinenum)
3614 prevlinenum -= 1
3615 return ('', -1)
3616
3617
3618def CheckBraces(filename, clean_lines, linenum, error):
3619 """Looks for misplaced braces (e.g. at the end of line).
3620
3621 Args:
3622 filename: The name of the current file.
3623 clean_lines: A CleansedLines instance containing the file.
3624 linenum: The number of the line to check.
3625 error: The function to call with any errors found.
3626 """
3627
3628 line = clean_lines.elided[linenum] # get rid of comments and strings
3629
3630 if Match(r'\s*{\s*$', line):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003631 # We allow an open brace to start a line in the case where someone is using
3632 # braces in a block to explicitly create a new scope, which is commonly used
3633 # to control the lifetime of stack-allocated variables. Braces are also
3634 # used for brace initializers inside function calls. We don't detect this
3635 # perfectly: we just don't complain if the last non-whitespace character on
3636 # the previous non-blank line is ',', ';', ':', '(', '{', or '}', or if the
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003637 # previous line starts a preprocessor block. We also allow a brace on the
3638 # following line if it is part of an array initialization and would not fit
3639 # within the 80 character limit of the preceding line.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003640 prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003641 if (not Search(r'[,;:}{(]\s*$', prevline) and
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003642 not Match(r'\s*#', prevline) and
3643 not (GetLineWidth(prevline) > _line_length - 2 and '[]' in prevline)):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003644 error(filename, linenum, 'whitespace/braces', 4,
3645 '{ should almost always be at the end of the previous line')
3646
3647 # An else clause should be on the same line as the preceding closing brace.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003648 if Match(r'\s*else\b\s*(?:if\b|\{|$)', line):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003649 prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
3650 if Match(r'\s*}\s*$', prevline):
3651 error(filename, linenum, 'whitespace/newline', 4,
3652 'An else should appear on the same line as the preceding }')
3653
3654 # If braces come on one side of an else, they should be on both.
3655 # However, we have to worry about "else if" that spans multiple lines!
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003656 if Search(r'else if\s*\(', line): # could be multi-line if
3657 brace_on_left = bool(Search(r'}\s*else if\s*\(', line))
3658 # find the ( after the if
3659 pos = line.find('else if')
3660 pos = line.find('(', pos)
3661 if pos > 0:
3662 (endline, _, endpos) = CloseExpression(clean_lines, linenum, pos)
3663 brace_on_right = endline[endpos:].find('{') != -1
3664 if brace_on_left != brace_on_right: # must be brace after if
3665 error(filename, linenum, 'readability/braces', 5,
3666 'If an else has a brace on one side, it should have it on both')
3667 elif Search(r'}\s*else[^{]*$', line) or Match(r'[^}]*else\s*{', line):
3668 error(filename, linenum, 'readability/braces', 5,
3669 'If an else has a brace on one side, it should have it on both')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003670
3671 # Likewise, an else should never have the else clause on the same line
3672 if Search(r'\belse [^\s{]', line) and not Search(r'\belse if\b', line):
3673 error(filename, linenum, 'whitespace/newline', 4,
3674 'Else clause should never be on same line as else (use 2 lines)')
3675
3676 # In the same way, a do/while should never be on one line
3677 if Match(r'\s*do [^\s{]', line):
3678 error(filename, linenum, 'whitespace/newline', 4,
3679 'do/while clauses should not be on a single line')
3680
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003681 # Check single-line if/else bodies. The style guide says 'curly braces are not
3682 # required for single-line statements'. We additionally allow multi-line,
3683 # single statements, but we reject anything with more than one semicolon in
3684 # it. This means that the first semicolon after the if should be at the end of
3685 # its line, and the line after that should have an indent level equal to or
3686 # lower than the if. We also check for ambiguous if/else nesting without
3687 # braces.
3688 if_else_match = Search(r'\b(if\s*\(|else\b)', line)
3689 if if_else_match and not Match(r'\s*#', line):
3690 if_indent = GetIndentLevel(line)
3691 endline, endlinenum, endpos = line, linenum, if_else_match.end()
3692 if_match = Search(r'\bif\s*\(', line)
3693 if if_match:
3694 # This could be a multiline if condition, so find the end first.
3695 pos = if_match.end() - 1
3696 (endline, endlinenum, endpos) = CloseExpression(clean_lines, linenum, pos)
3697 # Check for an opening brace, either directly after the if or on the next
3698 # line. If found, this isn't a single-statement conditional.
3699 if (not Match(r'\s*{', endline[endpos:])
3700 and not (Match(r'\s*$', endline[endpos:])
3701 and endlinenum < (len(clean_lines.elided) - 1)
3702 and Match(r'\s*{', clean_lines.elided[endlinenum + 1]))):
3703 while (endlinenum < len(clean_lines.elided)
3704 and ';' not in clean_lines.elided[endlinenum][endpos:]):
3705 endlinenum += 1
3706 endpos = 0
3707 if endlinenum < len(clean_lines.elided):
3708 endline = clean_lines.elided[endlinenum]
3709 # We allow a mix of whitespace and closing braces (e.g. for one-liner
3710 # methods) and a single \ after the semicolon (for macros)
3711 endpos = endline.find(';')
3712 if not Match(r';[\s}]*(\\?)$', endline[endpos:]):
avakulenko@google.com59146752014-08-11 20:20:55 +00003713 # Semicolon isn't the last character, there's something trailing.
3714 # Output a warning if the semicolon is not contained inside
3715 # a lambda expression.
3716 if not Match(r'^[^{};]*\[[^\[\]]*\][^{}]*\{[^{}]*\}\s*\)*[;,]\s*$',
3717 endline):
3718 error(filename, linenum, 'readability/braces', 4,
3719 'If/else bodies with multiple statements require braces')
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003720 elif endlinenum < len(clean_lines.elided) - 1:
3721 # Make sure the next line is dedented
3722 next_line = clean_lines.elided[endlinenum + 1]
3723 next_indent = GetIndentLevel(next_line)
3724 # With ambiguous nested if statements, this will error out on the
3725 # if that *doesn't* match the else, regardless of whether it's the
3726 # inner one or outer one.
3727 if (if_match and Match(r'\s*else\b', next_line)
3728 and next_indent != if_indent):
3729 error(filename, linenum, 'readability/braces', 4,
3730 'Else clause should be indented at the same level as if. '
3731 'Ambiguous nested if/else chains require braces.')
3732 elif next_indent > if_indent:
3733 error(filename, linenum, 'readability/braces', 4,
3734 'If/else bodies with multiple statements require braces')
3735
3736
3737def CheckTrailingSemicolon(filename, clean_lines, linenum, error):
3738 """Looks for redundant trailing semicolon.
3739
3740 Args:
3741 filename: The name of the current file.
3742 clean_lines: A CleansedLines instance containing the file.
3743 linenum: The number of the line to check.
3744 error: The function to call with any errors found.
3745 """
3746
3747 line = clean_lines.elided[linenum]
3748
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003749 # Block bodies should not be followed by a semicolon. Due to C++11
3750 # brace initialization, there are more places where semicolons are
Ayu Ishii09858612020-06-26 18:00:52 +00003751 # required than not, so we use an allowlist approach to check these
3752 # rather than a blocklist. These are the places where "};" should
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003753 # be replaced by just "}":
3754 # 1. Some flavor of block following closing parenthesis:
3755 # for (;;) {};
3756 # while (...) {};
3757 # switch (...) {};
3758 # Function(...) {};
3759 # if (...) {};
3760 # if (...) else if (...) {};
3761 #
3762 # 2. else block:
3763 # if (...) else {};
3764 #
3765 # 3. const member function:
3766 # Function(...) const {};
3767 #
3768 # 4. Block following some statement:
3769 # x = 42;
3770 # {};
3771 #
3772 # 5. Block at the beginning of a function:
3773 # Function(...) {
3774 # {};
3775 # }
3776 #
3777 # Note that naively checking for the preceding "{" will also match
3778 # braces inside multi-dimensional arrays, but this is fine since
3779 # that expression will not contain semicolons.
3780 #
3781 # 6. Block following another block:
3782 # while (true) {}
3783 # {};
3784 #
3785 # 7. End of namespaces:
3786 # namespace {};
3787 #
3788 # These semicolons seems far more common than other kinds of
3789 # redundant semicolons, possibly due to people converting classes
3790 # to namespaces. For now we do not warn for this case.
3791 #
3792 # Try matching case 1 first.
3793 match = Match(r'^(.*\)\s*)\{', line)
3794 if match:
3795 # Matched closing parenthesis (case 1). Check the token before the
3796 # matching opening parenthesis, and don't warn if it looks like a
3797 # macro. This avoids these false positives:
3798 # - macro that defines a base class
3799 # - multi-line macro that defines a base class
3800 # - macro that defines the whole class-head
3801 #
3802 # But we still issue warnings for macros that we know are safe to
3803 # warn, specifically:
3804 # - TEST, TEST_F, TEST_P, MATCHER, MATCHER_P
3805 # - TYPED_TEST
3806 # - INTERFACE_DEF
3807 # - EXCLUSIVE_LOCKS_REQUIRED, SHARED_LOCKS_REQUIRED, LOCKS_EXCLUDED:
3808 #
Ayu Ishii09858612020-06-26 18:00:52 +00003809 # We implement an allowlist of safe macros instead of a blocklist of
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003810 # unsafe macros, even though the latter appears less frequently in
Ayu Ishii09858612020-06-26 18:00:52 +00003811 # google code and would have been easier to implement. This is because
3812 # the downside for getting the allowlist wrong means some extra
3813 # semicolons, while the downside for getting the blocklist wrong
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003814 # would result in compile errors.
3815 #
avakulenko@google.com255f2be2014-12-05 22:19:55 +00003816 # In addition to macros, we also don't want to warn on
3817 # - Compound literals
3818 # - Lambdas
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003819 # - alignas specifier with anonymous structs
3820 # - decltype
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003821 closing_brace_pos = match.group(1).rfind(')')
3822 opening_parenthesis = ReverseCloseExpression(
3823 clean_lines, linenum, closing_brace_pos)
3824 if opening_parenthesis[2] > -1:
3825 line_prefix = opening_parenthesis[0][0:opening_parenthesis[2]]
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003826 macro = Search(r'\b([A-Z_][A-Z0-9_]*)\s*$', line_prefix)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003827 func = Match(r'^(.*\])\s*$', line_prefix)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003828 if ((macro and
3829 macro.group(1) not in (
3830 'TEST', 'TEST_F', 'MATCHER', 'MATCHER_P', 'TYPED_TEST',
3831 'EXCLUSIVE_LOCKS_REQUIRED', 'SHARED_LOCKS_REQUIRED',
3832 'LOCKS_EXCLUDED', 'INTERFACE_DEF')) or
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003833 (func and not Search(r'\boperator\s*\[\s*\]', func.group(1))) or
avakulenko@google.com255f2be2014-12-05 22:19:55 +00003834 Search(r'\b(?:struct|union)\s+alignas\s*$', line_prefix) or
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003835 Search(r'\bdecltype$', line_prefix) or
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003836 Search(r'\s+=\s*$', line_prefix)):
3837 match = None
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003838 if (match and
3839 opening_parenthesis[1] > 1 and
3840 Search(r'\]\s*$', clean_lines.elided[opening_parenthesis[1] - 1])):
3841 # Multi-line lambda-expression
3842 match = None
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003843
3844 else:
3845 # Try matching cases 2-3.
3846 match = Match(r'^(.*(?:else|\)\s*const)\s*)\{', line)
3847 if not match:
3848 # Try matching cases 4-6. These are always matched on separate lines.
3849 #
3850 # Note that we can't simply concatenate the previous line to the
3851 # current line and do a single match, otherwise we may output
3852 # duplicate warnings for the blank line case:
3853 # if (cond) {
3854 # // blank line
3855 # }
3856 prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
3857 if prevline and Search(r'[;{}]\s*$', prevline):
3858 match = Match(r'^(\s*)\{', line)
3859
3860 # Check matching closing brace
3861 if match:
3862 (endline, endlinenum, endpos) = CloseExpression(
3863 clean_lines, linenum, len(match.group(1)))
3864 if endpos > -1 and Match(r'^\s*;', endline[endpos:]):
3865 # Current {} pair is eligible for semicolon check, and we have found
3866 # the redundant semicolon, output warning here.
3867 #
3868 # Note: because we are scanning forward for opening braces, and
3869 # outputting warnings for the matching closing brace, if there are
3870 # nested blocks with trailing semicolons, we will get the error
3871 # messages in reversed order.
3872 error(filename, endlinenum, 'readability/braces', 4,
3873 "You don't need a ; after a }")
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003874
3875
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003876def CheckEmptyBlockBody(filename, clean_lines, linenum, error):
3877 """Look for empty loop/conditional body with only a single semicolon.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003878
3879 Args:
3880 filename: The name of the current file.
3881 clean_lines: A CleansedLines instance containing the file.
3882 linenum: The number of the line to check.
3883 error: The function to call with any errors found.
3884 """
3885
3886 # Search for loop keywords at the beginning of the line. Because only
3887 # whitespaces are allowed before the keywords, this will also ignore most
3888 # do-while-loops, since those lines should start with closing brace.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003889 #
3890 # We also check "if" blocks here, since an empty conditional block
3891 # is likely an error.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003892 line = clean_lines.elided[linenum]
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003893 matched = Match(r'\s*(for|while|if)\s*\(', line)
3894 if matched:
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003895 # Find the end of the conditional expression.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003896 (end_line, end_linenum, end_pos) = CloseExpression(
3897 clean_lines, linenum, line.find('('))
3898
3899 # Output warning if what follows the condition expression is a semicolon.
3900 # No warning for all other cases, including whitespace or newline, since we
3901 # have a separate check for semicolons preceded by whitespace.
3902 if end_pos >= 0 and Match(r';', end_line[end_pos:]):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003903 if matched.group(1) == 'if':
3904 error(filename, end_linenum, 'whitespace/empty_conditional_body', 5,
3905 'Empty conditional bodies should use {}')
3906 else:
3907 error(filename, end_linenum, 'whitespace/empty_loop_body', 5,
3908 'Empty loop bodies should use {} or continue')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003909
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003910 # Check for if statements that have completely empty bodies (no comments)
3911 # and no else clauses.
3912 if end_pos >= 0 and matched.group(1) == 'if':
3913 # Find the position of the opening { for the if statement.
3914 # Return without logging an error if it has no brackets.
3915 opening_linenum = end_linenum
3916 opening_line_fragment = end_line[end_pos:]
3917 # Loop until EOF or find anything that's not whitespace or opening {.
3918 while not Search(r'^\s*\{', opening_line_fragment):
3919 if Search(r'^(?!\s*$)', opening_line_fragment):
3920 # Conditional has no brackets.
3921 return
3922 opening_linenum += 1
3923 if opening_linenum == len(clean_lines.elided):
3924 # Couldn't find conditional's opening { or any code before EOF.
3925 return
3926 opening_line_fragment = clean_lines.elided[opening_linenum]
3927 # Set opening_line (opening_line_fragment may not be entire opening line).
3928 opening_line = clean_lines.elided[opening_linenum]
3929
3930 # Find the position of the closing }.
3931 opening_pos = opening_line_fragment.find('{')
3932 if opening_linenum == end_linenum:
3933 # We need to make opening_pos relative to the start of the entire line.
3934 opening_pos += end_pos
3935 (closing_line, closing_linenum, closing_pos) = CloseExpression(
3936 clean_lines, opening_linenum, opening_pos)
3937 if closing_pos < 0:
3938 return
3939
3940 # Now construct the body of the conditional. This consists of the portion
3941 # of the opening line after the {, all lines until the closing line,
3942 # and the portion of the closing line before the }.
3943 if (clean_lines.raw_lines[opening_linenum] !=
3944 CleanseComments(clean_lines.raw_lines[opening_linenum])):
3945 # Opening line ends with a comment, so conditional isn't empty.
3946 return
3947 if closing_linenum > opening_linenum:
3948 # Opening line after the {. Ignore comments here since we checked above.
3949 body = list(opening_line[opening_pos+1:])
3950 # All lines until closing line, excluding closing line, with comments.
3951 body.extend(clean_lines.raw_lines[opening_linenum+1:closing_linenum])
3952 # Closing line before the }. Won't (and can't) have comments.
3953 body.append(clean_lines.elided[closing_linenum][:closing_pos-1])
3954 body = '\n'.join(body)
3955 else:
3956 # If statement has brackets and fits on a single line.
3957 body = opening_line[opening_pos+1:closing_pos-1]
3958
3959 # Check if the body is empty
3960 if not _EMPTY_CONDITIONAL_BODY_PATTERN.search(body):
3961 return
3962 # The body is empty. Now make sure there's not an else clause.
3963 current_linenum = closing_linenum
3964 current_line_fragment = closing_line[closing_pos:]
3965 # Loop until EOF or find anything that's not whitespace or else clause.
3966 while Search(r'^\s*$|^(?=\s*else)', current_line_fragment):
3967 if Search(r'^(?=\s*else)', current_line_fragment):
3968 # Found an else clause, so don't log an error.
3969 return
3970 current_linenum += 1
3971 if current_linenum == len(clean_lines.elided):
3972 break
3973 current_line_fragment = clean_lines.elided[current_linenum]
3974
3975 # The body is empty and there's no else clause until EOF or other code.
3976 error(filename, end_linenum, 'whitespace/empty_if_body', 4,
3977 ('If statement had no body and no else clause'))
3978
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003979
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003980def FindCheckMacro(line):
3981 """Find a replaceable CHECK-like macro.
3982
3983 Args:
3984 line: line to search on.
3985 Returns:
3986 (macro name, start position), or (None, -1) if no replaceable
3987 macro is found.
3988 """
3989 for macro in _CHECK_MACROS:
3990 i = line.find(macro)
3991 if i >= 0:
3992 # Find opening parenthesis. Do a regular expression match here
3993 # to make sure that we are matching the expected CHECK macro, as
3994 # opposed to some other macro that happens to contain the CHECK
3995 # substring.
3996 matched = Match(r'^(.*\b' + macro + r'\s*)\(', line)
3997 if not matched:
3998 continue
3999 return (macro, len(matched.group(1)))
4000 return (None, -1)
4001
4002
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004003def CheckCheck(filename, clean_lines, linenum, error):
4004 """Checks the use of CHECK and EXPECT macros.
4005
4006 Args:
4007 filename: The name of the current file.
4008 clean_lines: A CleansedLines instance containing the file.
4009 linenum: The number of the line to check.
4010 error: The function to call with any errors found.
4011 """
4012
4013 # Decide the set of replacement macros that should be suggested
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004014 lines = clean_lines.elided
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004015 (check_macro, start_pos) = FindCheckMacro(lines[linenum])
4016 if not check_macro:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004017 return
4018
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004019 # Find end of the boolean expression by matching parentheses
4020 (last_line, end_line, end_pos) = CloseExpression(
4021 clean_lines, linenum, start_pos)
4022 if end_pos < 0:
4023 return
avakulenko@google.com59146752014-08-11 20:20:55 +00004024
4025 # If the check macro is followed by something other than a
4026 # semicolon, assume users will log their own custom error messages
4027 # and don't suggest any replacements.
4028 if not Match(r'\s*;', last_line[end_pos:]):
4029 return
4030
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004031 if linenum == end_line:
4032 expression = lines[linenum][start_pos + 1:end_pos - 1]
4033 else:
4034 expression = lines[linenum][start_pos + 1:]
Edward Lemur6d31ed52019-12-02 23:00:00 +00004035 for i in range(linenum + 1, end_line):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004036 expression += lines[i]
4037 expression += last_line[0:end_pos - 1]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004038
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004039 # Parse expression so that we can take parentheses into account.
4040 # This avoids false positives for inputs like "CHECK((a < 4) == b)",
4041 # which is not replaceable by CHECK_LE.
4042 lhs = ''
4043 rhs = ''
4044 operator = None
4045 while expression:
4046 matched = Match(r'^\s*(<<|<<=|>>|>>=|->\*|->|&&|\|\||'
4047 r'==|!=|>=|>|<=|<|\()(.*)$', expression)
4048 if matched:
4049 token = matched.group(1)
4050 if token == '(':
4051 # Parenthesized operand
4052 expression = matched.group(2)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004053 (end, _) = FindEndOfExpressionInLine(expression, 0, ['('])
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004054 if end < 0:
4055 return # Unmatched parenthesis
4056 lhs += '(' + expression[0:end]
4057 expression = expression[end:]
4058 elif token in ('&&', '||'):
4059 # Logical and/or operators. This means the expression
4060 # contains more than one term, for example:
4061 # CHECK(42 < a && a < b);
4062 #
4063 # These are not replaceable with CHECK_LE, so bail out early.
4064 return
4065 elif token in ('<<', '<<=', '>>', '>>=', '->*', '->'):
4066 # Non-relational operator
4067 lhs += token
4068 expression = matched.group(2)
4069 else:
4070 # Relational operator
4071 operator = token
4072 rhs = matched.group(2)
4073 break
4074 else:
4075 # Unparenthesized operand. Instead of appending to lhs one character
4076 # at a time, we do another regular expression match to consume several
4077 # characters at once if possible. Trivial benchmark shows that this
4078 # is more efficient when the operands are longer than a single
4079 # character, which is generally the case.
4080 matched = Match(r'^([^-=!<>()&|]+)(.*)$', expression)
4081 if not matched:
4082 matched = Match(r'^(\s*\S)(.*)$', expression)
4083 if not matched:
4084 break
4085 lhs += matched.group(1)
4086 expression = matched.group(2)
4087
4088 # Only apply checks if we got all parts of the boolean expression
4089 if not (lhs and operator and rhs):
4090 return
4091
4092 # Check that rhs do not contain logical operators. We already know
4093 # that lhs is fine since the loop above parses out && and ||.
4094 if rhs.find('&&') > -1 or rhs.find('||') > -1:
4095 return
4096
4097 # At least one of the operands must be a constant literal. This is
4098 # to avoid suggesting replacements for unprintable things like
4099 # CHECK(variable != iterator)
4100 #
4101 # The following pattern matches decimal, hex integers, strings, and
4102 # characters (in that order).
4103 lhs = lhs.strip()
4104 rhs = rhs.strip()
4105 match_constant = r'^([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')$'
4106 if Match(match_constant, lhs) or Match(match_constant, rhs):
4107 # Note: since we know both lhs and rhs, we can provide a more
4108 # descriptive error message like:
4109 # Consider using CHECK_EQ(x, 42) instead of CHECK(x == 42)
4110 # Instead of:
4111 # Consider using CHECK_EQ instead of CHECK(a == b)
4112 #
4113 # We are still keeping the less descriptive message because if lhs
4114 # or rhs gets long, the error message might become unreadable.
4115 error(filename, linenum, 'readability/check', 2,
4116 'Consider using %s instead of %s(a %s b)' % (
4117 _CHECK_REPLACEMENT[check_macro][operator],
4118 check_macro, operator))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004119
4120
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004121def CheckAltTokens(filename, clean_lines, linenum, error):
4122 """Check alternative keywords being used in boolean expressions.
4123
4124 Args:
4125 filename: The name of the current file.
4126 clean_lines: A CleansedLines instance containing the file.
4127 linenum: The number of the line to check.
4128 error: The function to call with any errors found.
4129 """
4130 line = clean_lines.elided[linenum]
4131
4132 # Avoid preprocessor lines
4133 if Match(r'^\s*#', line):
4134 return
4135
4136 # Last ditch effort to avoid multi-line comments. This will not help
4137 # if the comment started before the current line or ended after the
4138 # current line, but it catches most of the false positives. At least,
4139 # it provides a way to workaround this warning for people who use
4140 # multi-line comments in preprocessor macros.
4141 #
4142 # TODO(unknown): remove this once cpplint has better support for
4143 # multi-line comments.
4144 if line.find('/*') >= 0 or line.find('*/') >= 0:
4145 return
4146
4147 for match in _ALT_TOKEN_REPLACEMENT_PATTERN.finditer(line):
4148 error(filename, linenum, 'readability/alt_tokens', 2,
4149 'Use operator %s instead of %s' % (
4150 _ALT_TOKEN_REPLACEMENT[match.group(1)], match.group(1)))
4151
4152
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004153def GetLineWidth(line):
4154 """Determines the width of the line in column positions.
4155
4156 Args:
4157 line: A string, which may be a Unicode string.
4158
4159 Returns:
4160 The width of the line in column positions, accounting for Unicode
4161 combining characters and wide characters.
4162 """
Edward Lemur6d31ed52019-12-02 23:00:00 +00004163 if sys.version_info == 2 and isinstance(line, unicode):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004164 width = 0
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004165 for uc in unicodedata.normalize('NFC', line):
4166 if unicodedata.east_asian_width(uc) in ('W', 'F'):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004167 width += 2
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004168 elif not unicodedata.combining(uc):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004169 width += 1
4170 return width
4171 else:
4172 return len(line)
4173
4174
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004175def CheckStyle(filename, clean_lines, linenum, file_extension, nesting_state,
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004176 error):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004177 """Checks rules from the 'C++ style rules' section of cppguide.html.
4178
4179 Most of these rules are hard to test (naming, comment style), but we
4180 do what we can. In particular we check for 2-space indents, line lengths,
4181 tab usage, spaces inside code, etc.
4182
4183 Args:
4184 filename: The name of the current file.
4185 clean_lines: A CleansedLines instance containing the file.
4186 linenum: The number of the line to check.
4187 file_extension: The extension (without the dot) of the filename.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004188 nesting_state: A NestingState instance which maintains information about
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004189 the current stack of nested blocks being parsed.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004190 error: The function to call with any errors found.
4191 """
4192
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004193 # Don't use "elided" lines here, otherwise we can't check commented lines.
4194 # Don't want to use "raw" either, because we don't want to check inside C++11
4195 # raw strings,
4196 raw_lines = clean_lines.lines_without_raw_strings
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004197 line = raw_lines[linenum]
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004198 prev = raw_lines[linenum - 1] if linenum > 0 else ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004199
4200 if line.find('\t') != -1:
4201 error(filename, linenum, 'whitespace/tab', 1,
4202 'Tab found; better to use spaces')
4203
4204 # One or three blank spaces at the beginning of the line is weird; it's
4205 # hard to reconcile that with 2-space indents.
4206 # NOTE: here are the conditions rob pike used for his tests. Mine aren't
4207 # as sophisticated, but it may be worth becoming so: RLENGTH==initial_spaces
4208 # if(RLENGTH > 20) complain = 0;
4209 # if(match($0, " +(error|private|public|protected):")) complain = 0;
4210 # if(match(prev, "&& *$")) complain = 0;
4211 # if(match(prev, "\\|\\| *$")) complain = 0;
4212 # if(match(prev, "[\",=><] *$")) complain = 0;
4213 # if(match($0, " <<")) complain = 0;
4214 # if(match(prev, " +for \\(")) complain = 0;
4215 # if(prevodd && match(prevprev, " +for \\(")) complain = 0;
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004216 scope_or_label_pattern = r'\s*\w+\s*:\s*\\?$'
4217 classinfo = nesting_state.InnermostClass()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004218 initial_spaces = 0
4219 cleansed_line = clean_lines.elided[linenum]
4220 while initial_spaces < len(line) and line[initial_spaces] == ' ':
4221 initial_spaces += 1
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004222 # There are certain situations we allow one space, notably for
4223 # section labels, and also lines containing multi-line raw strings.
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004224 # We also don't check for lines that look like continuation lines
4225 # (of lines ending in double quotes, commas, equals, or angle brackets)
4226 # because the rules for how to indent those are non-trivial.
4227 if (not Search(r'[",=><] *$', prev) and
4228 (initial_spaces == 1 or initial_spaces == 3) and
4229 not Match(scope_or_label_pattern, cleansed_line) and
4230 not (clean_lines.raw_lines[linenum] != line and
4231 Match(r'^\s*""', line))):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004232 error(filename, linenum, 'whitespace/indent', 3,
4233 'Weird number of spaces at line-start. '
4234 'Are you using a 2-space indent?')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004235
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004236 if line and line[-1].isspace():
4237 error(filename, linenum, 'whitespace/end_of_line', 4,
4238 'Line ends in whitespace. Consider deleting these extra spaces.')
4239
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004240 # Check if the line is a header guard.
4241 is_header_guard = False
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00004242 if file_extension == 'h':
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004243 cppvar = GetHeaderGuardCPPVariable(filename)
4244 if (line.startswith('#ifndef %s' % cppvar) or
4245 line.startswith('#define %s' % cppvar) or
4246 line.startswith('#endif // %s' % cppvar)):
4247 is_header_guard = True
4248 # #include lines and header guards can be long, since there's no clean way to
4249 # split them.
erg@google.com6317a9c2009-06-25 00:28:19 +00004250 #
4251 # URLs can be long too. It's possible to split these, but it makes them
4252 # harder to cut&paste.
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004253 #
4254 # The "$Id:...$" comment may also get very long without it being the
4255 # developers fault.
erg@google.com6317a9c2009-06-25 00:28:19 +00004256 if (not line.startswith('#include') and not is_header_guard and
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004257 not Match(r'^\s*//.*http(s?)://\S*$', line) and
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004258 not Match(r'^\s*//\s*[^\s]*$', line) and
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004259 not Match(r'^// \$Id:.*#[0-9]+ \$$', line)):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004260 line_width = GetLineWidth(line)
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004261 if line_width > _line_length:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004262 error(filename, linenum, 'whitespace/line_length', 2,
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004263 'Lines should be <= %i characters long' % _line_length)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004264
4265 if (cleansed_line.count(';') > 1 and
4266 # for loops are allowed two ;'s (and may run over two lines).
4267 cleansed_line.find('for') == -1 and
4268 (GetPreviousNonBlankLine(clean_lines, linenum)[0].find('for') == -1 or
4269 GetPreviousNonBlankLine(clean_lines, linenum)[0].find(';') != -1) and
4270 # It's ok to have many commands in a switch case that fits in 1 line
4271 not ((cleansed_line.find('case ') != -1 or
4272 cleansed_line.find('default:') != -1) and
4273 cleansed_line.find('break;') != -1)):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004274 error(filename, linenum, 'whitespace/newline', 0,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004275 'More than one command on the same line')
4276
4277 # Some more style checks
4278 CheckBraces(filename, clean_lines, linenum, error)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004279 CheckTrailingSemicolon(filename, clean_lines, linenum, error)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004280 CheckEmptyBlockBody(filename, clean_lines, linenum, error)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004281 CheckSpacing(filename, clean_lines, linenum, nesting_state, error)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004282 CheckOperatorSpacing(filename, clean_lines, linenum, error)
4283 CheckParenthesisSpacing(filename, clean_lines, linenum, error)
4284 CheckCommaSpacing(filename, clean_lines, linenum, error)
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004285 CheckBracesSpacing(filename, clean_lines, linenum, nesting_state, error)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004286 CheckSpacingForFunctionCall(filename, clean_lines, linenum, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004287 CheckCheck(filename, clean_lines, linenum, error)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004288 CheckAltTokens(filename, clean_lines, linenum, error)
4289 classinfo = nesting_state.InnermostClass()
4290 if classinfo:
4291 CheckSectionSpacing(filename, clean_lines, classinfo, linenum, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004292
4293
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004294_RE_PATTERN_INCLUDE = re.compile(r'^\s*#\s*include\s*([<"])([^>"]*)[>"].*$')
4295# Matches the first component of a filename delimited by -s and _s. That is:
4296# _RE_FIRST_COMPONENT.match('foo').group(0) == 'foo'
4297# _RE_FIRST_COMPONENT.match('foo.cc').group(0) == 'foo'
4298# _RE_FIRST_COMPONENT.match('foo-bar_baz.cc').group(0) == 'foo'
4299# _RE_FIRST_COMPONENT.match('foo_bar-baz.cc').group(0) == 'foo'
4300_RE_FIRST_COMPONENT = re.compile(r'^[^-_.]+')
4301
4302
4303def _DropCommonSuffixes(filename):
4304 """Drops common suffixes like _test.cc or -inl.h from filename.
4305
4306 For example:
4307 >>> _DropCommonSuffixes('foo/foo-inl.h')
4308 'foo/foo'
4309 >>> _DropCommonSuffixes('foo/bar/foo.cc')
4310 'foo/bar/foo'
4311 >>> _DropCommonSuffixes('foo/foo_internal.h')
4312 'foo/foo'
4313 >>> _DropCommonSuffixes('foo/foo_unusualinternal.h')
4314 'foo/foo_unusualinternal'
4315
4316 Args:
4317 filename: The input filename.
4318
4319 Returns:
4320 The filename with the common suffix removed.
4321 """
4322 for suffix in ('test.cc', 'regtest.cc', 'unittest.cc',
4323 'inl.h', 'impl.h', 'internal.h'):
4324 if (filename.endswith(suffix) and len(filename) > len(suffix) and
4325 filename[-len(suffix) - 1] in ('-', '_')):
4326 return filename[:-len(suffix) - 1]
4327 return os.path.splitext(filename)[0]
4328
4329
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004330def _ClassifyInclude(fileinfo, include, is_system):
4331 """Figures out what kind of header 'include' is.
4332
4333 Args:
4334 fileinfo: The current file cpplint is running over. A FileInfo instance.
4335 include: The path to a #included file.
4336 is_system: True if the #include used <> rather than "".
4337
4338 Returns:
4339 One of the _XXX_HEADER constants.
4340
4341 For example:
4342 >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'stdio.h', True)
4343 _C_SYS_HEADER
4344 >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'string', True)
4345 _CPP_SYS_HEADER
4346 >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', False)
4347 _LIKELY_MY_HEADER
4348 >>> _ClassifyInclude(FileInfo('foo/foo_unknown_extension.cc'),
4349 ... 'bar/foo_other_ext.h', False)
4350 _POSSIBLE_MY_HEADER
4351 >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/bar.h', False)
4352 _OTHER_HEADER
4353 """
4354 # This is a list of all standard c++ header files, except
4355 # those already checked for above.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004356 is_cpp_h = include in _CPP_HEADERS
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004357
4358 if is_system:
4359 if is_cpp_h:
4360 return _CPP_SYS_HEADER
4361 else:
4362 return _C_SYS_HEADER
4363
4364 # If the target file and the include we're checking share a
4365 # basename when we drop common extensions, and the include
4366 # lives in . , then it's likely to be owned by the target file.
4367 target_dir, target_base = (
4368 os.path.split(_DropCommonSuffixes(fileinfo.RepositoryName())))
4369 include_dir, include_base = os.path.split(_DropCommonSuffixes(include))
4370 if target_base == include_base and (
4371 include_dir == target_dir or
4372 include_dir == os.path.normpath(target_dir + '/../public')):
4373 return _LIKELY_MY_HEADER
4374
4375 # If the target and include share some initial basename
4376 # component, it's possible the target is implementing the
4377 # include, so it's allowed to be first, but we'll never
4378 # complain if it's not there.
4379 target_first_component = _RE_FIRST_COMPONENT.match(target_base)
4380 include_first_component = _RE_FIRST_COMPONENT.match(include_base)
4381 if (target_first_component and include_first_component and
4382 target_first_component.group(0) ==
4383 include_first_component.group(0)):
4384 return _POSSIBLE_MY_HEADER
4385
4386 return _OTHER_HEADER
4387
4388
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004389
erg@google.com6317a9c2009-06-25 00:28:19 +00004390def CheckIncludeLine(filename, clean_lines, linenum, include_state, error):
4391 """Check rules that are applicable to #include lines.
4392
4393 Strings on #include lines are NOT removed from elided line, to make
4394 certain tasks easier. However, to prevent false positives, checks
4395 applicable to #include lines in CheckLanguage must be put here.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004396
4397 Args:
4398 filename: The name of the current file.
4399 clean_lines: A CleansedLines instance containing the file.
4400 linenum: The number of the line to check.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004401 include_state: An _IncludeState instance in which the headers are inserted.
4402 error: The function to call with any errors found.
4403 """
4404 fileinfo = FileInfo(filename)
erg@google.com6317a9c2009-06-25 00:28:19 +00004405 line = clean_lines.lines[linenum]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004406
4407 # "include" should use the new style "foo/bar.h" instead of just "bar.h"
avakulenko@google.com59146752014-08-11 20:20:55 +00004408 # Only do this check if the included header follows google naming
4409 # conventions. If not, assume that it's a 3rd party API that
4410 # requires special include conventions.
4411 #
4412 # We also make an exception for Lua headers, which follow google
4413 # naming convention but not the include convention.
4414 match = Match(r'#include\s*"([^/]+\.h)"', line)
4415 if match and not _THIRD_PARTY_HEADERS_PATTERN.match(match.group(1)):
Fletcher Woodruff11b34152020-04-23 21:21:40 +00004416 error(filename, linenum, 'build/include_directory', 4,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004417 'Include the directory when naming .h files')
4418
4419 # we shouldn't include a file more than once. actually, there are a
4420 # handful of instances where doing so is okay, but in general it's
4421 # not.
erg@google.com6317a9c2009-06-25 00:28:19 +00004422 match = _RE_PATTERN_INCLUDE.search(line)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004423 if match:
4424 include = match.group(2)
4425 is_system = (match.group(1) == '<')
avakulenko@google.com59146752014-08-11 20:20:55 +00004426 duplicate_line = include_state.FindHeader(include)
4427 if duplicate_line >= 0:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004428 error(filename, linenum, 'build/include', 4,
4429 '"%s" already included at %s:%s' %
avakulenko@google.com59146752014-08-11 20:20:55 +00004430 (include, filename, duplicate_line))
avakulenko@google.com255f2be2014-12-05 22:19:55 +00004431 elif (include.endswith('.cc') and
4432 os.path.dirname(fileinfo.RepositoryName()) != os.path.dirname(include)):
4433 error(filename, linenum, 'build/include', 4,
4434 'Do not include .cc files from other packages')
avakulenko@google.com59146752014-08-11 20:20:55 +00004435 elif not _THIRD_PARTY_HEADERS_PATTERN.match(include):
4436 include_state.include_list[-1].append((include, linenum))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004437
4438 # We want to ensure that headers appear in the right order:
4439 # 1) for foo.cc, foo.h (preferred location)
4440 # 2) c system files
4441 # 3) cpp system files
4442 # 4) for foo.cc, foo.h (deprecated location)
4443 # 5) other google headers
4444 #
4445 # We classify each include statement as one of those 5 types
4446 # using a number of techniques. The include_state object keeps
4447 # track of the highest type seen, and complains if we see a
4448 # lower type after that.
4449 error_message = include_state.CheckNextIncludeOrder(
4450 _ClassifyInclude(fileinfo, include, is_system))
4451 if error_message:
4452 error(filename, linenum, 'build/include_order', 4,
4453 '%s. Should be: %s.h, c system, c++ system, other.' %
4454 (error_message, fileinfo.BaseName()))
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004455 canonical_include = include_state.CanonicalizeAlphabeticalOrder(include)
4456 if not include_state.IsInAlphabeticalOrder(
4457 clean_lines, linenum, canonical_include):
erg@google.com26970fa2009-11-17 18:07:32 +00004458 error(filename, linenum, 'build/include_alpha', 4,
4459 'Include "%s" not in alphabetical order' % include)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004460 include_state.SetLastHeader(canonical_include)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004461
erg@google.com6317a9c2009-06-25 00:28:19 +00004462
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004463
4464def _GetTextInside(text, start_pattern):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004465 r"""Retrieves all the text between matching open and close parentheses.
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004466
4467 Given a string of lines and a regular expression string, retrieve all the text
4468 following the expression and between opening punctuation symbols like
4469 (, [, or {, and the matching close-punctuation symbol. This properly nested
4470 occurrences of the punctuations, so for the text like
4471 printf(a(), b(c()));
4472 a call to _GetTextInside(text, r'printf\(') will return 'a(), b(c())'.
4473 start_pattern must match string having an open punctuation symbol at the end.
4474
4475 Args:
4476 text: The lines to extract text. Its comments and strings must be elided.
4477 It can be single line and can span multiple lines.
4478 start_pattern: The regexp string indicating where to start extracting
4479 the text.
4480 Returns:
4481 The extracted text.
4482 None if either the opening string or ending punctuation could not be found.
4483 """
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004484 # TODO(unknown): Audit cpplint.py to see what places could be profitably
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004485 # rewritten to use _GetTextInside (and use inferior regexp matching today).
4486
4487 # Give opening punctuations to get the matching close-punctuations.
4488 matching_punctuation = {'(': ')', '{': '}', '[': ']'}
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +00004489 closing_punctuation = set(matching_punctuation.values())
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004490
4491 # Find the position to start extracting text.
4492 match = re.search(start_pattern, text, re.M)
4493 if not match: # start_pattern not found in text.
4494 return None
4495 start_position = match.end(0)
4496
4497 assert start_position > 0, (
4498 'start_pattern must ends with an opening punctuation.')
4499 assert text[start_position - 1] in matching_punctuation, (
4500 'start_pattern must ends with an opening punctuation.')
4501 # Stack of closing punctuations we expect to have in text after position.
4502 punctuation_stack = [matching_punctuation[text[start_position - 1]]]
4503 position = start_position
4504 while punctuation_stack and position < len(text):
4505 if text[position] == punctuation_stack[-1]:
4506 punctuation_stack.pop()
4507 elif text[position] in closing_punctuation:
4508 # A closing punctuation without matching opening punctuations.
4509 return None
4510 elif text[position] in matching_punctuation:
4511 punctuation_stack.append(matching_punctuation[text[position]])
4512 position += 1
4513 if punctuation_stack:
4514 # Opening punctuations left without matching close-punctuations.
4515 return None
4516 # punctuations match.
4517 return text[start_position:position - 1]
4518
4519
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004520# Patterns for matching call-by-reference parameters.
4521#
4522# Supports nested templates up to 2 levels deep using this messy pattern:
4523# < (?: < (?: < [^<>]*
4524# >
4525# | [^<>] )*
4526# >
4527# | [^<>] )*
4528# >
4529_RE_PATTERN_IDENT = r'[_a-zA-Z]\w*' # =~ [[:alpha:]][[:alnum:]]*
4530_RE_PATTERN_TYPE = (
4531 r'(?:const\s+)?(?:typename\s+|class\s+|struct\s+|union\s+|enum\s+)?'
4532 r'(?:\w|'
4533 r'\s*<(?:<(?:<[^<>]*>|[^<>])*>|[^<>])*>|'
4534 r'::)+')
4535# A call-by-reference parameter ends with '& identifier'.
4536_RE_PATTERN_REF_PARAM = re.compile(
4537 r'(' + _RE_PATTERN_TYPE + r'(?:\s*(?:\bconst\b|[*]))*\s*'
4538 r'&\s*' + _RE_PATTERN_IDENT + r')\s*(?:=[^,()]+)?[,)]')
4539# A call-by-const-reference parameter either ends with 'const& identifier'
4540# or looks like 'const type& identifier' when 'type' is atomic.
4541_RE_PATTERN_CONST_REF_PARAM = (
4542 r'(?:.*\s*\bconst\s*&\s*' + _RE_PATTERN_IDENT +
4543 r'|const\s+' + _RE_PATTERN_TYPE + r'\s*&\s*' + _RE_PATTERN_IDENT + r')')
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004544# Stream types.
4545_RE_PATTERN_REF_STREAM_PARAM = (
4546 r'(?:.*stream\s*&\s*' + _RE_PATTERN_IDENT + r')')
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004547
4548
4549def CheckLanguage(filename, clean_lines, linenum, file_extension,
4550 include_state, nesting_state, error):
erg@google.com6317a9c2009-06-25 00:28:19 +00004551 """Checks rules from the 'C++ language rules' section of cppguide.html.
4552
4553 Some of these rules are hard to test (function overloading, using
4554 uint32 inappropriately), but we do the best we can.
4555
4556 Args:
4557 filename: The name of the current file.
4558 clean_lines: A CleansedLines instance containing the file.
4559 linenum: The number of the line to check.
4560 file_extension: The extension (without the dot) of the filename.
4561 include_state: An _IncludeState instance in which the headers are inserted.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004562 nesting_state: A NestingState instance which maintains information about
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004563 the current stack of nested blocks being parsed.
erg@google.com6317a9c2009-06-25 00:28:19 +00004564 error: The function to call with any errors found.
4565 """
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004566 # If the line is empty or consists of entirely a comment, no need to
4567 # check it.
4568 line = clean_lines.elided[linenum]
4569 if not line:
4570 return
4571
erg@google.com6317a9c2009-06-25 00:28:19 +00004572 match = _RE_PATTERN_INCLUDE.search(line)
4573 if match:
4574 CheckIncludeLine(filename, clean_lines, linenum, include_state, error)
4575 return
4576
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004577 # Reset include state across preprocessor directives. This is meant
4578 # to silence warnings for conditional includes.
avakulenko@google.com59146752014-08-11 20:20:55 +00004579 match = Match(r'^\s*#\s*(if|ifdef|ifndef|elif|else|endif)\b', line)
4580 if match:
4581 include_state.ResetSection(match.group(1))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004582
4583 # Make Windows paths like Unix.
4584 fullname = os.path.abspath(filename).replace('\\', '/')
skym@chromium.org3990c412016-02-05 20:55:12 +00004585
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004586 # Perform other checks now that we are sure that this is not an include line
4587 CheckCasts(filename, clean_lines, linenum, error)
4588 CheckGlobalStatic(filename, clean_lines, linenum, error)
4589 CheckPrintf(filename, clean_lines, linenum, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004590
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00004591 if file_extension == 'h':
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004592 # TODO(unknown): check that 1-arg constructors are explicit.
4593 # How to tell it's a constructor?
4594 # (handled in CheckForNonStandardConstructs for now)
avakulenko@google.com59146752014-08-11 20:20:55 +00004595 # TODO(unknown): check that classes declare or disable copy/assign
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004596 # (level 1 error)
4597 pass
4598
4599 # Check if people are using the verboten C basic types. The only exception
4600 # we regularly allow is "unsigned short port" for port.
4601 if Search(r'\bshort port\b', line):
4602 if not Search(r'\bunsigned short port\b', line):
4603 error(filename, linenum, 'runtime/int', 4,
4604 'Use "unsigned short" for ports, not "short"')
4605 else:
4606 match = Search(r'\b(short|long(?! +double)|long long)\b', line)
4607 if match:
4608 error(filename, linenum, 'runtime/int', 4,
4609 'Use int16/int64/etc, rather than the C type %s' % match.group(1))
4610
erg@google.com26970fa2009-11-17 18:07:32 +00004611 # Check if some verboten operator overloading is going on
4612 # TODO(unknown): catch out-of-line unary operator&:
4613 # class X {};
4614 # int operator&(const X& x) { return 42; } // unary operator&
4615 # The trick is it's hard to tell apart from binary operator&:
4616 # class Y { int operator&(const Y& x) { return 23; } }; // binary operator&
4617 if Search(r'\boperator\s*&\s*\(\s*\)', line):
4618 error(filename, linenum, 'runtime/operator', 4,
4619 'Unary operator& is dangerous. Do not use it.')
4620
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004621 # Check for suspicious usage of "if" like
4622 # } if (a == b) {
4623 if Search(r'\}\s*if\s*\(', line):
4624 error(filename, linenum, 'readability/braces', 4,
4625 'Did you mean "else if"? If not, start a new line for "if".')
4626
4627 # Check for potential format string bugs like printf(foo).
4628 # We constrain the pattern not to pick things like DocidForPrintf(foo).
4629 # Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str())
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004630 # TODO(unknown): Catch the following case. Need to change the calling
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004631 # convention of the whole function to process multiple line to handle it.
4632 # printf(
4633 # boy_this_is_a_really_long_variable_that_cannot_fit_on_the_prev_line);
4634 printf_args = _GetTextInside(line, r'(?i)\b(string)?printf\s*\(')
4635 if printf_args:
4636 match = Match(r'([\w.\->()]+)$', printf_args)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004637 if match and match.group(1) != '__VA_ARGS__':
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004638 function_name = re.search(r'\b((?:string)?printf)\s*\(',
4639 line, re.I).group(1)
4640 error(filename, linenum, 'runtime/printf', 4,
4641 'Potential format string bug. Do %s("%%s", %s) instead.'
4642 % (function_name, match.group(1)))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004643
4644 # Check for potential memset bugs like memset(buf, sizeof(buf), 0).
4645 match = Search(r'memset\s*\(([^,]*),\s*([^,]*),\s*0\s*\)', line)
4646 if match and not Match(r"^''|-?[0-9]+|0x[0-9A-Fa-f]$", match.group(2)):
4647 error(filename, linenum, 'runtime/memset', 4,
4648 'Did you mean "memset(%s, 0, %s)"?'
4649 % (match.group(1), match.group(2)))
4650
4651 if Search(r'\busing namespace\b', line):
4652 error(filename, linenum, 'build/namespaces', 5,
4653 'Do not use namespace using-directives. '
4654 'Use using-declarations instead.')
4655
4656 # Detect variable-length arrays.
4657 match = Match(r'\s*(.+::)?(\w+) [a-z]\w*\[(.+)];', line)
4658 if (match and match.group(2) != 'return' and match.group(2) != 'delete' and
4659 match.group(3).find(']') == -1):
4660 # Split the size using space and arithmetic operators as delimiters.
4661 # If any of the resulting tokens are not compile time constants then
4662 # report the error.
4663 tokens = re.split(r'\s|\+|\-|\*|\/|<<|>>]', match.group(3))
4664 is_const = True
4665 skip_next = False
4666 for tok in tokens:
4667 if skip_next:
4668 skip_next = False
4669 continue
4670
4671 if Search(r'sizeof\(.+\)', tok): continue
4672 if Search(r'arraysize\(\w+\)', tok): continue
Avi Drissman4157ba12019-01-09 14:18:07 +00004673 if Search(r'base::size\(.+\)', tok): continue
4674 if Search(r'std::size\(.+\)', tok): continue
4675 if Search(r'std::extent<.+>', tok): continue
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004676
4677 tok = tok.lstrip('(')
4678 tok = tok.rstrip(')')
4679 if not tok: continue
4680 if Match(r'\d+', tok): continue
4681 if Match(r'0[xX][0-9a-fA-F]+', tok): continue
4682 if Match(r'k[A-Z0-9]\w*', tok): continue
4683 if Match(r'(.+::)?k[A-Z0-9]\w*', tok): continue
4684 if Match(r'(.+::)?[A-Z][A-Z0-9_]*', tok): continue
4685 # A catch all for tricky sizeof cases, including 'sizeof expression',
4686 # 'sizeof(*type)', 'sizeof(const type)', 'sizeof(struct StructName)'
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004687 # requires skipping the next token because we split on ' ' and '*'.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004688 if tok.startswith('sizeof'):
4689 skip_next = True
4690 continue
4691 is_const = False
4692 break
4693 if not is_const:
4694 error(filename, linenum, 'runtime/arrays', 1,
4695 'Do not use variable-length arrays. Use an appropriately named '
4696 "('k' followed by CamelCase) compile-time constant for the size.")
4697
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004698 # Check for use of unnamed namespaces in header files. Registration
4699 # macros are typically OK, so we allow use of "namespace {" on lines
4700 # that end with backslashes.
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00004701 if (file_extension == 'h'
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004702 and Search(r'\bnamespace\s*{', line)
4703 and line[-1] != '\\'):
4704 error(filename, linenum, 'build/namespaces', 4,
4705 'Do not use unnamed namespaces in header files. See '
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00004706 'https://google.github.io/styleguide/cppguide.html#Namespaces'
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004707 ' for more information.')
4708
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004709
4710def CheckGlobalStatic(filename, clean_lines, linenum, error):
4711 """Check for unsafe global or static objects.
4712
4713 Args:
4714 filename: The name of the current file.
4715 clean_lines: A CleansedLines instance containing the file.
4716 linenum: The number of the line to check.
4717 error: The function to call with any errors found.
4718 """
4719 line = clean_lines.elided[linenum]
4720
avakulenko@google.com59146752014-08-11 20:20:55 +00004721 # Match two lines at a time to support multiline declarations
4722 if linenum + 1 < clean_lines.NumLines() and not Search(r'[;({]', line):
4723 line += clean_lines.elided[linenum + 1].strip()
4724
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004725 # Check for people declaring static/global STL strings at the top level.
4726 # This is dangerous because the C++ language does not guarantee that
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004727 # globals with constructors are initialized before the first access, and
4728 # also because globals can be destroyed when some threads are still running.
4729 # TODO(unknown): Generalize this to also find static unique_ptr instances.
4730 # TODO(unknown): File bugs for clang-tidy to find these.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004731 match = Match(
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004732 r'((?:|static +)(?:|const +))(?::*std::)?string( +const)? +'
4733 r'([a-zA-Z0-9_:]+)\b(.*)',
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004734 line)
avakulenko@google.com59146752014-08-11 20:20:55 +00004735
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004736 # Remove false positives:
4737 # - String pointers (as opposed to values).
4738 # string *pointer
4739 # const string *pointer
4740 # string const *pointer
4741 # string *const pointer
4742 #
4743 # - Functions and template specializations.
4744 # string Function<Type>(...
4745 # string Class<Type>::Method(...
4746 #
4747 # - Operators. These are matched separately because operator names
4748 # cross non-word boundaries, and trying to match both operators
4749 # and functions at the same time would decrease accuracy of
4750 # matching identifiers.
4751 # string Class::operator*()
4752 if (match and
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004753 not Search(r'\bstring\b(\s+const)?\s*[\*\&]\s*(const\s+)?\w', line) and
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004754 not Search(r'\boperator\W', line) and
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004755 not Match(r'\s*(<.*>)?(::[a-zA-Z0-9_]+)*\s*\(([^"]|$)', match.group(4))):
4756 if Search(r'\bconst\b', line):
4757 error(filename, linenum, 'runtime/string', 4,
4758 'For a static/global string constant, use a C style string '
4759 'instead: "%schar%s %s[]".' %
4760 (match.group(1), match.group(2) or '', match.group(3)))
4761 else:
4762 error(filename, linenum, 'runtime/string', 4,
4763 'Static/global string variables are not permitted.')
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004764
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004765 if (Search(r'\b([A-Za-z0-9_]*_)\(\1\)', line) or
4766 Search(r'\b([A-Za-z0-9_]*_)\(CHECK_NOTNULL\(\1\)\)', line)):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004767 error(filename, linenum, 'runtime/init', 4,
4768 'You seem to be initializing a member variable with itself.')
4769
4770
4771def CheckPrintf(filename, clean_lines, linenum, error):
4772 """Check for printf related issues.
4773
4774 Args:
4775 filename: The name of the current file.
4776 clean_lines: A CleansedLines instance containing the file.
4777 linenum: The number of the line to check.
4778 error: The function to call with any errors found.
4779 """
4780 line = clean_lines.elided[linenum]
4781
4782 # When snprintf is used, the second argument shouldn't be a literal.
4783 match = Search(r'snprintf\s*\(([^,]*),\s*([0-9]*)\s*,', line)
4784 if match and match.group(2) != '0':
4785 # If 2nd arg is zero, snprintf is used to calculate size.
4786 error(filename, linenum, 'runtime/printf', 3,
4787 'If you can, use sizeof(%s) instead of %s as the 2nd arg '
4788 'to snprintf.' % (match.group(1), match.group(2)))
4789
4790 # Check if some verboten C functions are being used.
avakulenko@google.com59146752014-08-11 20:20:55 +00004791 if Search(r'\bsprintf\s*\(', line):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004792 error(filename, linenum, 'runtime/printf', 5,
4793 'Never use sprintf. Use snprintf instead.')
avakulenko@google.com59146752014-08-11 20:20:55 +00004794 match = Search(r'\b(strcpy|strcat)\s*\(', line)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004795 if match:
4796 error(filename, linenum, 'runtime/printf', 4,
4797 'Almost always, snprintf is better than %s' % match.group(1))
4798
4799
4800def IsDerivedFunction(clean_lines, linenum):
4801 """Check if current line contains an inherited function.
4802
4803 Args:
4804 clean_lines: A CleansedLines instance containing the file.
4805 linenum: The number of the line to check.
4806 Returns:
4807 True if current line contains a function with "override"
4808 virt-specifier.
4809 """
avakulenko@google.com59146752014-08-11 20:20:55 +00004810 # Scan back a few lines for start of current function
Edward Lemur6d31ed52019-12-02 23:00:00 +00004811 for i in range(linenum, max(-1, linenum - 10), -1):
avakulenko@google.com59146752014-08-11 20:20:55 +00004812 match = Match(r'^([^()]*\w+)\(', clean_lines.elided[i])
4813 if match:
4814 # Look for "override" after the matching closing parenthesis
4815 line, _, closing_paren = CloseExpression(
4816 clean_lines, i, len(match.group(1)))
4817 return (closing_paren >= 0 and
4818 Search(r'\boverride\b', line[closing_paren:]))
4819 return False
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004820
4821
avakulenko@google.com255f2be2014-12-05 22:19:55 +00004822def IsOutOfLineMethodDefinition(clean_lines, linenum):
4823 """Check if current line contains an out-of-line method definition.
4824
4825 Args:
4826 clean_lines: A CleansedLines instance containing the file.
4827 linenum: The number of the line to check.
4828 Returns:
4829 True if current line contains an out-of-line method definition.
4830 """
4831 # Scan back a few lines for start of current function
Edward Lemur6d31ed52019-12-02 23:00:00 +00004832 for i in range(linenum, max(-1, linenum - 10), -1):
avakulenko@google.com255f2be2014-12-05 22:19:55 +00004833 if Match(r'^([^()]*\w+)\(', clean_lines.elided[i]):
4834 return Match(r'^[^()]*\w+::\w+\(', clean_lines.elided[i]) is not None
4835 return False
4836
4837
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004838def IsInitializerList(clean_lines, linenum):
4839 """Check if current line is inside constructor initializer list.
4840
4841 Args:
4842 clean_lines: A CleansedLines instance containing the file.
4843 linenum: The number of the line to check.
4844 Returns:
4845 True if current line appears to be inside constructor initializer
4846 list, False otherwise.
4847 """
Edward Lemur6d31ed52019-12-02 23:00:00 +00004848 for i in range(linenum, 1, -1):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004849 line = clean_lines.elided[i]
4850 if i == linenum:
4851 remove_function_body = Match(r'^(.*)\{\s*$', line)
4852 if remove_function_body:
4853 line = remove_function_body.group(1)
4854
4855 if Search(r'\s:\s*\w+[({]', line):
4856 # A lone colon tend to indicate the start of a constructor
4857 # initializer list. It could also be a ternary operator, which
4858 # also tend to appear in constructor initializer lists as
4859 # opposed to parameter lists.
4860 return True
4861 if Search(r'\}\s*,\s*$', line):
4862 # A closing brace followed by a comma is probably the end of a
4863 # brace-initialized member in constructor initializer list.
4864 return True
4865 if Search(r'[{};]\s*$', line):
4866 # Found one of the following:
4867 # - A closing brace or semicolon, probably the end of the previous
4868 # function.
4869 # - An opening brace, probably the start of current class or namespace.
4870 #
4871 # Current line is probably not inside an initializer list since
4872 # we saw one of those things without seeing the starting colon.
4873 return False
4874
4875 # Got to the beginning of the file without seeing the start of
4876 # constructor initializer list.
4877 return False
4878
4879
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004880def CheckForNonConstReference(filename, clean_lines, linenum,
4881 nesting_state, error):
4882 """Check for non-const references.
4883
4884 Separate from CheckLanguage since it scans backwards from current
4885 line, instead of scanning forward.
4886
4887 Args:
4888 filename: The name of the current file.
4889 clean_lines: A CleansedLines instance containing the file.
4890 linenum: The number of the line to check.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004891 nesting_state: A NestingState instance which maintains information about
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004892 the current stack of nested blocks being parsed.
4893 error: The function to call with any errors found.
4894 """
4895 # Do nothing if there is no '&' on current line.
4896 line = clean_lines.elided[linenum]
4897 if '&' not in line:
4898 return
4899
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004900 # If a function is inherited, current function doesn't have much of
4901 # a choice, so any non-const references should not be blamed on
4902 # derived function.
4903 if IsDerivedFunction(clean_lines, linenum):
4904 return
4905
avakulenko@google.com255f2be2014-12-05 22:19:55 +00004906 # Don't warn on out-of-line method definitions, as we would warn on the
4907 # in-line declaration, if it isn't marked with 'override'.
4908 if IsOutOfLineMethodDefinition(clean_lines, linenum):
4909 return
4910
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004911 # Long type names may be broken across multiple lines, usually in one
4912 # of these forms:
4913 # LongType
4914 # ::LongTypeContinued &identifier
4915 # LongType::
4916 # LongTypeContinued &identifier
4917 # LongType<
4918 # ...>::LongTypeContinued &identifier
4919 #
4920 # If we detected a type split across two lines, join the previous
4921 # line to current line so that we can match const references
4922 # accordingly.
4923 #
4924 # Note that this only scans back one line, since scanning back
4925 # arbitrary number of lines would be expensive. If you have a type
4926 # that spans more than 2 lines, please use a typedef.
4927 if linenum > 1:
4928 previous = None
4929 if Match(r'\s*::(?:[\w<>]|::)+\s*&\s*\S', line):
4930 # previous_line\n + ::current_line
4931 previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+[\w<>])\s*$',
4932 clean_lines.elided[linenum - 1])
4933 elif Match(r'\s*[a-zA-Z_]([\w<>]|::)+\s*&\s*\S', line):
4934 # previous_line::\n + current_line
4935 previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+::)\s*$',
4936 clean_lines.elided[linenum - 1])
4937 if previous:
4938 line = previous.group(1) + line.lstrip()
4939 else:
4940 # Check for templated parameter that is split across multiple lines
4941 endpos = line.rfind('>')
4942 if endpos > -1:
4943 (_, startline, startpos) = ReverseCloseExpression(
4944 clean_lines, linenum, endpos)
4945 if startpos > -1 and startline < linenum:
4946 # Found the matching < on an earlier line, collect all
4947 # pieces up to current line.
4948 line = ''
Edward Lemur6d31ed52019-12-02 23:00:00 +00004949 for i in range(startline, linenum + 1):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004950 line += clean_lines.elided[i].strip()
4951
4952 # Check for non-const references in function parameters. A single '&' may
4953 # found in the following places:
4954 # inside expression: binary & for bitwise AND
4955 # inside expression: unary & for taking the address of something
4956 # inside declarators: reference parameter
4957 # We will exclude the first two cases by checking that we are not inside a
4958 # function body, including one that was just introduced by a trailing '{'.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004959 # TODO(unknown): Doesn't account for 'catch(Exception& e)' [rare].
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004960 if (nesting_state.previous_stack_top and
4961 not (isinstance(nesting_state.previous_stack_top, _ClassInfo) or
4962 isinstance(nesting_state.previous_stack_top, _NamespaceInfo))):
4963 # Not at toplevel, not within a class, and not within a namespace
4964 return
4965
avakulenko@google.com59146752014-08-11 20:20:55 +00004966 # Avoid initializer lists. We only need to scan back from the
4967 # current line for something that starts with ':'.
4968 #
4969 # We don't need to check the current line, since the '&' would
4970 # appear inside the second set of parentheses on the current line as
4971 # opposed to the first set.
4972 if linenum > 0:
Edward Lemur6d31ed52019-12-02 23:00:00 +00004973 for i in range(linenum - 1, max(0, linenum - 10), -1):
avakulenko@google.com59146752014-08-11 20:20:55 +00004974 previous_line = clean_lines.elided[i]
4975 if not Search(r'[),]\s*$', previous_line):
4976 break
4977 if Match(r'^\s*:\s+\S', previous_line):
4978 return
4979
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004980 # Avoid preprocessors
4981 if Search(r'\\\s*$', line):
4982 return
4983
4984 # Avoid constructor initializer lists
4985 if IsInitializerList(clean_lines, linenum):
4986 return
4987
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004988 # We allow non-const references in a few standard places, like functions
4989 # called "swap()" or iostream operators like "<<" or ">>". Do not check
4990 # those function parameters.
4991 #
4992 # We also accept & in static_assert, which looks like a function but
4993 # it's actually a declaration expression.
Ayu Ishii09858612020-06-26 18:00:52 +00004994 allowlisted_functions = (r'(?:[sS]wap(?:<\w:+>)?|'
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004995 r'operator\s*[<>][<>]|'
4996 r'static_assert|COMPILE_ASSERT'
4997 r')\s*\(')
Ayu Ishii09858612020-06-26 18:00:52 +00004998 if Search(allowlisted_functions, line):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004999 return
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005000 elif not Search(r'\S+\([^)]*$', line):
Ayu Ishii09858612020-06-26 18:00:52 +00005001 # Don't see an allowlisted function on this line. Actually we
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005002 # didn't see any function name on this line, so this is likely a
5003 # multi-line parameter list. Try a bit harder to catch this case.
Edward Lemur6d31ed52019-12-02 23:00:00 +00005004 for i in range(2):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005005 if (linenum > i and
Ayu Ishii09858612020-06-26 18:00:52 +00005006 Search(allowlisted_functions, clean_lines.elided[linenum - i - 1])):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005007 return
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005008
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005009 decls = ReplaceAll(r'{[^}]*}', ' ', line) # exclude function body
5010 for parameter in re.findall(_RE_PATTERN_REF_PARAM, decls):
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005011 if (not Match(_RE_PATTERN_CONST_REF_PARAM, parameter) and
5012 not Match(_RE_PATTERN_REF_STREAM_PARAM, parameter)):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005013 error(filename, linenum, 'runtime/references', 2,
5014 'Is this a non-const reference? '
5015 'If so, make const or use a pointer: ' +
5016 ReplaceAll(' *<', '<', parameter))
5017
5018
5019def CheckCasts(filename, clean_lines, linenum, error):
5020 """Various cast related checks.
5021
5022 Args:
5023 filename: The name of the current file.
5024 clean_lines: A CleansedLines instance containing the file.
5025 linenum: The number of the line to check.
5026 error: The function to call with any errors found.
5027 """
5028 line = clean_lines.elided[linenum]
5029
5030 # Check to see if they're using an conversion function cast.
5031 # I just try to capture the most common basic types, though there are more.
5032 # Parameterless conversion functions, such as bool(), are allowed as they are
5033 # probably a member operator declaration or default constructor.
5034 match = Search(
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005035 r'(\bnew\s+(?:const\s+)?|\S<\s*(?:const\s+)?)?\b'
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005036 r'(int|float|double|bool|char|int32|uint32|int64|uint64)'
5037 r'(\([^)].*)', line)
5038 expecting_function = ExpectingFunctionArgs(clean_lines, linenum)
5039 if match and not expecting_function:
5040 matched_type = match.group(2)
5041
5042 # matched_new_or_template is used to silence two false positives:
5043 # - New operators
5044 # - Template arguments with function types
5045 #
5046 # For template arguments, we match on types immediately following
5047 # an opening bracket without any spaces. This is a fast way to
5048 # silence the common case where the function type is the first
5049 # template argument. False negative with less-than comparison is
5050 # avoided because those operators are usually followed by a space.
5051 #
5052 # function<double(double)> // bracket + no space = false positive
5053 # value < double(42) // bracket + space = true positive
5054 matched_new_or_template = match.group(1)
5055
avakulenko@google.com59146752014-08-11 20:20:55 +00005056 # Avoid arrays by looking for brackets that come after the closing
5057 # parenthesis.
5058 if Match(r'\([^()]+\)\s*\[', match.group(3)):
5059 return
5060
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005061 # Other things to ignore:
5062 # - Function pointers
5063 # - Casts to pointer types
5064 # - Placement new
5065 # - Alias declarations
5066 matched_funcptr = match.group(3)
5067 if (matched_new_or_template is None and
5068 not (matched_funcptr and
5069 (Match(r'\((?:[^() ]+::\s*\*\s*)?[^() ]+\)\s*\(',
5070 matched_funcptr) or
5071 matched_funcptr.startswith('(*)'))) and
5072 not Match(r'\s*using\s+\S+\s*=\s*' + matched_type, line) and
5073 not Search(r'new\(\S+\)\s*' + matched_type, line)):
5074 error(filename, linenum, 'readability/casting', 4,
5075 'Using deprecated casting style. '
5076 'Use static_cast<%s>(...) instead' %
5077 matched_type)
5078
5079 if not expecting_function:
avakulenko@google.com59146752014-08-11 20:20:55 +00005080 CheckCStyleCast(filename, clean_lines, linenum, 'static_cast',
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005081 r'\((int|float|double|bool|char|u?int(16|32|64))\)', error)
5082
5083 # This doesn't catch all cases. Consider (const char * const)"hello".
5084 #
5085 # (char *) "foo" should always be a const_cast (reinterpret_cast won't
5086 # compile).
avakulenko@google.com59146752014-08-11 20:20:55 +00005087 if CheckCStyleCast(filename, clean_lines, linenum, 'const_cast',
5088 r'\((char\s?\*+\s?)\)\s*"', error):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005089 pass
5090 else:
5091 # Check pointer casts for other than string constants
avakulenko@google.com59146752014-08-11 20:20:55 +00005092 CheckCStyleCast(filename, clean_lines, linenum, 'reinterpret_cast',
5093 r'\((\w+\s?\*+\s?)\)', error)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005094
5095 # In addition, we look for people taking the address of a cast. This
5096 # is dangerous -- casts can assign to temporaries, so the pointer doesn't
5097 # point where you think.
avakulenko@google.com59146752014-08-11 20:20:55 +00005098 #
5099 # Some non-identifier character is required before the '&' for the
5100 # expression to be recognized as a cast. These are casts:
5101 # expression = &static_cast<int*>(temporary());
5102 # function(&(int*)(temporary()));
5103 #
5104 # This is not a cast:
5105 # reference_type&(int* function_param);
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005106 match = Search(
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005107 r'(?:[^\w]&\(([^)*][^)]*)\)[\w(])|'
avakulenko@google.com59146752014-08-11 20:20:55 +00005108 r'(?:[^\w]&(static|dynamic|down|reinterpret)_cast\b)', line)
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005109 if match:
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005110 # Try a better error message when the & is bound to something
5111 # dereferenced by the casted pointer, as opposed to the casted
5112 # pointer itself.
5113 parenthesis_error = False
5114 match = Match(r'^(.*&(?:static|dynamic|down|reinterpret)_cast\b)<', line)
5115 if match:
5116 _, y1, x1 = CloseExpression(clean_lines, linenum, len(match.group(1)))
5117 if x1 >= 0 and clean_lines.elided[y1][x1] == '(':
5118 _, y2, x2 = CloseExpression(clean_lines, y1, x1)
5119 if x2 >= 0:
5120 extended_line = clean_lines.elided[y2][x2:]
5121 if y2 < clean_lines.NumLines() - 1:
5122 extended_line += clean_lines.elided[y2 + 1]
5123 if Match(r'\s*(?:->|\[)', extended_line):
5124 parenthesis_error = True
5125
5126 if parenthesis_error:
5127 error(filename, linenum, 'readability/casting', 4,
5128 ('Are you taking an address of something dereferenced '
5129 'from a cast? Wrapping the dereferenced expression in '
5130 'parentheses will make the binding more obvious'))
5131 else:
5132 error(filename, linenum, 'runtime/casting', 4,
5133 ('Are you taking an address of a cast? '
5134 'This is dangerous: could be a temp var. '
5135 'Take the address before doing the cast, rather than after'))
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005136
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005137
avakulenko@google.com59146752014-08-11 20:20:55 +00005138def CheckCStyleCast(filename, clean_lines, linenum, cast_type, pattern, error):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005139 """Checks for a C-style cast by looking for the pattern.
5140
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005141 Args:
5142 filename: The name of the current file.
avakulenko@google.com59146752014-08-11 20:20:55 +00005143 clean_lines: A CleansedLines instance containing the file.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005144 linenum: The number of the line to check.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005145 cast_type: The string for the C++ cast to recommend. This is either
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005146 reinterpret_cast, static_cast, or const_cast, depending.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005147 pattern: The regular expression used to find C-style casts.
5148 error: The function to call with any errors found.
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005149
5150 Returns:
5151 True if an error was emitted.
5152 False otherwise.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005153 """
avakulenko@google.com59146752014-08-11 20:20:55 +00005154 line = clean_lines.elided[linenum]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005155 match = Search(pattern, line)
5156 if not match:
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005157 return False
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005158
avakulenko@google.com59146752014-08-11 20:20:55 +00005159 # Exclude lines with keywords that tend to look like casts
5160 context = line[0:match.start(1) - 1]
5161 if Match(r'.*\b(?:sizeof|alignof|alignas|[_A-Z][_A-Z0-9]*)\s*$', context):
5162 return False
5163
5164 # Try expanding current context to see if we one level of
5165 # parentheses inside a macro.
5166 if linenum > 0:
Edward Lemur6d31ed52019-12-02 23:00:00 +00005167 for i in range(linenum - 1, max(0, linenum - 5), -1):
avakulenko@google.com59146752014-08-11 20:20:55 +00005168 context = clean_lines.elided[i] + context
5169 if Match(r'.*\b[_A-Z][_A-Z0-9]*\s*\((?:\([^()]*\)|[^()])*$', context):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005170 return False
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005171
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005172 # operator++(int) and operator--(int)
avakulenko@google.com59146752014-08-11 20:20:55 +00005173 if context.endswith(' operator++') or context.endswith(' operator--'):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005174 return False
5175
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005176 # A single unnamed argument for a function tends to look like old style cast.
5177 # If we see those, don't issue warnings for deprecated casts.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005178 remainder = line[match.end(0):]
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005179 if Match(r'^\s*(?:;|const\b|throw\b|final\b|override\b|[=>{),]|->)',
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005180 remainder):
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005181 return False
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005182
5183 # At this point, all that should be left is actual casts.
5184 error(filename, linenum, 'readability/casting', 4,
5185 'Using C-style cast. Use %s<%s>(...) instead' %
5186 (cast_type, match.group(1)))
5187
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005188 return True
5189
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005190
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005191def ExpectingFunctionArgs(clean_lines, linenum):
5192 """Checks whether where function type arguments are expected.
5193
5194 Args:
5195 clean_lines: A CleansedLines instance containing the file.
5196 linenum: The number of the line to check.
5197
5198 Returns:
5199 True if the line at 'linenum' is inside something that expects arguments
5200 of function types.
5201 """
5202 line = clean_lines.elided[linenum]
5203 return (Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line) or
5204 (linenum >= 2 and
5205 (Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\((?:\S+,)?\s*$',
5206 clean_lines.elided[linenum - 1]) or
5207 Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\(\s*$',
5208 clean_lines.elided[linenum - 2]) or
5209 Search(r'\bstd::m?function\s*\<\s*$',
5210 clean_lines.elided[linenum - 1]))))
5211
5212
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005213_HEADERS_CONTAINING_TEMPLATES = (
5214 ('<deque>', ('deque',)),
5215 ('<functional>', ('unary_function', 'binary_function',
5216 'plus', 'minus', 'multiplies', 'divides', 'modulus',
5217 'negate',
5218 'equal_to', 'not_equal_to', 'greater', 'less',
5219 'greater_equal', 'less_equal',
5220 'logical_and', 'logical_or', 'logical_not',
5221 'unary_negate', 'not1', 'binary_negate', 'not2',
5222 'bind1st', 'bind2nd',
5223 'pointer_to_unary_function',
5224 'pointer_to_binary_function',
5225 'ptr_fun',
5226 'mem_fun_t', 'mem_fun', 'mem_fun1_t', 'mem_fun1_ref_t',
5227 'mem_fun_ref_t',
5228 'const_mem_fun_t', 'const_mem_fun1_t',
5229 'const_mem_fun_ref_t', 'const_mem_fun1_ref_t',
5230 'mem_fun_ref',
5231 )),
5232 ('<limits>', ('numeric_limits',)),
5233 ('<list>', ('list',)),
5234 ('<map>', ('map', 'multimap',)),
lhchavez2d1b6da2016-07-13 10:40:01 -07005235 ('<memory>', ('allocator', 'make_shared', 'make_unique', 'shared_ptr',
5236 'unique_ptr', 'weak_ptr')),
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005237 ('<queue>', ('queue', 'priority_queue',)),
5238 ('<set>', ('set', 'multiset',)),
5239 ('<stack>', ('stack',)),
5240 ('<string>', ('char_traits', 'basic_string',)),
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005241 ('<tuple>', ('tuple',)),
lhchavez2d1b6da2016-07-13 10:40:01 -07005242 ('<unordered_map>', ('unordered_map', 'unordered_multimap')),
5243 ('<unordered_set>', ('unordered_set', 'unordered_multiset')),
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005244 ('<utility>', ('pair',)),
5245 ('<vector>', ('vector',)),
5246
5247 # gcc extensions.
5248 # Note: std::hash is their hash, ::hash is our hash
5249 ('<hash_map>', ('hash_map', 'hash_multimap',)),
5250 ('<hash_set>', ('hash_set', 'hash_multiset',)),
5251 ('<slist>', ('slist',)),
5252 )
5253
skym@chromium.org3990c412016-02-05 20:55:12 +00005254_HEADERS_MAYBE_TEMPLATES = (
5255 ('<algorithm>', ('copy', 'max', 'min', 'min_element', 'sort',
5256 'transform',
5257 )),
lhchavez2d1b6da2016-07-13 10:40:01 -07005258 ('<utility>', ('forward', 'make_pair', 'move', 'swap')),
skym@chromium.org3990c412016-02-05 20:55:12 +00005259 )
5260
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005261_RE_PATTERN_STRING = re.compile(r'\bstring\b')
5262
skym@chromium.org3990c412016-02-05 20:55:12 +00005263_re_pattern_headers_maybe_templates = []
5264for _header, _templates in _HEADERS_MAYBE_TEMPLATES:
5265 for _template in _templates:
5266 # Match max<type>(..., ...), max(..., ...), but not foo->max, foo.max or
5267 # type::max().
5268 _re_pattern_headers_maybe_templates.append(
5269 (re.compile(r'[^>.]\b' + _template + r'(<.*?>)?\([^\)]'),
5270 _template,
5271 _header))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005272
skym@chromium.org3990c412016-02-05 20:55:12 +00005273# Other scripts may reach in and modify this pattern.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005274_re_pattern_templates = []
5275for _header, _templates in _HEADERS_CONTAINING_TEMPLATES:
5276 for _template in _templates:
5277 _re_pattern_templates.append(
5278 (re.compile(r'(\<|\b)' + _template + r'\s*\<'),
5279 _template + '<>',
5280 _header))
5281
5282
erg@google.com6317a9c2009-06-25 00:28:19 +00005283def FilesBelongToSameModule(filename_cc, filename_h):
5284 """Check if these two filenames belong to the same module.
5285
5286 The concept of a 'module' here is a as follows:
5287 foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the
5288 same 'module' if they are in the same directory.
5289 some/path/public/xyzzy and some/path/internal/xyzzy are also considered
5290 to belong to the same module here.
5291
5292 If the filename_cc contains a longer path than the filename_h, for example,
5293 '/absolute/path/to/base/sysinfo.cc', and this file would include
5294 'base/sysinfo.h', this function also produces the prefix needed to open the
5295 header. This is used by the caller of this function to more robustly open the
5296 header file. We don't have access to the real include paths in this context,
5297 so we need this guesswork here.
5298
5299 Known bugs: tools/base/bar.cc and base/bar.h belong to the same module
5300 according to this implementation. Because of this, this function gives
5301 some false positives. This should be sufficiently rare in practice.
5302
5303 Args:
5304 filename_cc: is the path for the .cc file
5305 filename_h: is the path for the header path
5306
5307 Returns:
5308 Tuple with a bool and a string:
5309 bool: True if filename_cc and filename_h belong to the same module.
5310 string: the additional prefix needed to open the header file.
5311 """
5312
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005313 fileinfo = FileInfo(filename_cc)
5314 if not fileinfo.IsSource():
erg@google.com6317a9c2009-06-25 00:28:19 +00005315 return (False, '')
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005316 filename_cc = filename_cc[:-len(fileinfo.Extension())]
5317 matched_test_suffix = Search(_TEST_FILE_SUFFIX, fileinfo.BaseName())
5318 if matched_test_suffix:
5319 filename_cc = filename_cc[:-len(matched_test_suffix.group(1))]
erg@google.com6317a9c2009-06-25 00:28:19 +00005320 filename_cc = filename_cc.replace('/public/', '/')
5321 filename_cc = filename_cc.replace('/internal/', '/')
5322
5323 if not filename_h.endswith('.h'):
5324 return (False, '')
5325 filename_h = filename_h[:-len('.h')]
5326 if filename_h.endswith('-inl'):
5327 filename_h = filename_h[:-len('-inl')]
5328 filename_h = filename_h.replace('/public/', '/')
5329 filename_h = filename_h.replace('/internal/', '/')
5330
5331 files_belong_to_same_module = filename_cc.endswith(filename_h)
5332 common_path = ''
5333 if files_belong_to_same_module:
5334 common_path = filename_cc[:-len(filename_h)]
5335 return files_belong_to_same_module, common_path
5336
5337
avakulenko@google.com59146752014-08-11 20:20:55 +00005338def UpdateIncludeState(filename, include_dict, io=codecs):
5339 """Fill up the include_dict with new includes found from the file.
erg@google.com6317a9c2009-06-25 00:28:19 +00005340
5341 Args:
5342 filename: the name of the header to read.
avakulenko@google.com59146752014-08-11 20:20:55 +00005343 include_dict: a dictionary in which the headers are inserted.
erg@google.com6317a9c2009-06-25 00:28:19 +00005344 io: The io factory to use to read the file. Provided for testability.
5345
5346 Returns:
avakulenko@google.com59146752014-08-11 20:20:55 +00005347 True if a header was successfully added. False otherwise.
erg@google.com6317a9c2009-06-25 00:28:19 +00005348 """
5349 headerfile = None
5350 try:
5351 headerfile = io.open(filename, 'r', 'utf8', 'replace')
5352 except IOError:
5353 return False
5354 linenum = 0
5355 for line in headerfile:
5356 linenum += 1
5357 clean_line = CleanseComments(line)
5358 match = _RE_PATTERN_INCLUDE.search(clean_line)
5359 if match:
5360 include = match.group(2)
avakulenko@google.com59146752014-08-11 20:20:55 +00005361 include_dict.setdefault(include, linenum)
erg@google.com6317a9c2009-06-25 00:28:19 +00005362 return True
5363
5364
5365def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error,
5366 io=codecs):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005367 """Reports for missing stl includes.
5368
5369 This function will output warnings to make sure you are including the headers
5370 necessary for the stl containers and functions that you use. We only give one
5371 reason to include a header. For example, if you use both equal_to<> and
5372 less<> in a .h file, only one (the latter in the file) of these will be
5373 reported as a reason to include the <functional>.
5374
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005375 Args:
5376 filename: The name of the current file.
5377 clean_lines: A CleansedLines instance containing the file.
5378 include_state: An _IncludeState instance.
5379 error: The function to call with any errors found.
erg@google.com6317a9c2009-06-25 00:28:19 +00005380 io: The IO factory to use to read the header file. Provided for unittest
5381 injection.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005382 """
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005383 required = {} # A map of header name to linenumber and the template entity.
5384 # Example of required: { '<functional>': (1219, 'less<>') }
5385
Edward Lemur6d31ed52019-12-02 23:00:00 +00005386 for linenum in range(clean_lines.NumLines()):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005387 line = clean_lines.elided[linenum]
5388 if not line or line[0] == '#':
5389 continue
5390
5391 # String is special -- it is a non-templatized type in STL.
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005392 matched = _RE_PATTERN_STRING.search(line)
5393 if matched:
erg@google.com35589e62010-11-17 18:58:16 +00005394 # Don't warn about strings in non-STL namespaces:
5395 # (We check only the first match per line; good enough.)
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005396 prefix = line[:matched.start()]
erg@google.com35589e62010-11-17 18:58:16 +00005397 if prefix.endswith('std::') or not prefix.endswith('::'):
5398 required['<string>'] = (linenum, 'string')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005399
skym@chromium.org3990c412016-02-05 20:55:12 +00005400 for pattern, template, header in _re_pattern_headers_maybe_templates:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005401 if pattern.search(line):
5402 required[header] = (linenum, template)
5403
5404 # The following function is just a speed up, no semantics are changed.
5405 if not '<' in line: # Reduces the cpu time usage by skipping lines.
5406 continue
5407
5408 for pattern, template, header in _re_pattern_templates:
lhchavez9b2173c2016-07-13 10:20:07 -07005409 matched = pattern.search(line)
5410 if matched:
5411 # Don't warn about IWYU in non-STL namespaces:
5412 # (We check only the first match per line; good enough.)
5413 prefix = line[:matched.start()]
5414 if prefix.endswith('std::') or not prefix.endswith('::'):
5415 required[header] = (linenum, template)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005416
erg@google.com6317a9c2009-06-25 00:28:19 +00005417 # The policy is that if you #include something in foo.h you don't need to
5418 # include it again in foo.cc. Here, we will look at possible includes.
avakulenko@google.com59146752014-08-11 20:20:55 +00005419 # Let's flatten the include_state include_list and copy it into a dictionary.
5420 include_dict = dict([item for sublist in include_state.include_list
5421 for item in sublist])
erg@google.com6317a9c2009-06-25 00:28:19 +00005422
avakulenko@google.com59146752014-08-11 20:20:55 +00005423 # Did we find the header for this file (if any) and successfully load it?
erg@google.com6317a9c2009-06-25 00:28:19 +00005424 header_found = False
5425
5426 # Use the absolute path so that matching works properly.
erg@chromium.org8f927562012-01-30 19:51:28 +00005427 abs_filename = FileInfo(filename).FullName()
erg@google.com6317a9c2009-06-25 00:28:19 +00005428
5429 # For Emacs's flymake.
5430 # If cpplint is invoked from Emacs's flymake, a temporary file is generated
5431 # by flymake and that file name might end with '_flymake.cc'. In that case,
5432 # restore original file name here so that the corresponding header file can be
5433 # found.
5434 # e.g. If the file name is 'foo_flymake.cc', we should search for 'foo.h'
5435 # instead of 'foo_flymake.h'
erg@google.com35589e62010-11-17 18:58:16 +00005436 abs_filename = re.sub(r'_flymake\.cc$', '.cc', abs_filename)
erg@google.com6317a9c2009-06-25 00:28:19 +00005437
avakulenko@google.com59146752014-08-11 20:20:55 +00005438 # include_dict is modified during iteration, so we iterate over a copy of
erg@google.com6317a9c2009-06-25 00:28:19 +00005439 # the keys.
Sarthak Kukreti60378202019-12-17 20:46:58 +00005440 header_keys = list(include_dict.keys())
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005441 for header in header_keys:
erg@google.com6317a9c2009-06-25 00:28:19 +00005442 (same_module, common_path) = FilesBelongToSameModule(abs_filename, header)
5443 fullpath = common_path + header
avakulenko@google.com59146752014-08-11 20:20:55 +00005444 if same_module and UpdateIncludeState(fullpath, include_dict, io):
erg@google.com6317a9c2009-06-25 00:28:19 +00005445 header_found = True
5446
5447 # If we can't find the header file for a .cc, assume it's because we don't
5448 # know where to look. In that case we'll give up as we're not sure they
5449 # didn't include it in the .h file.
5450 # TODO(unknown): Do a better job of finding .h files so we are confident that
5451 # not having the .h file means there isn't one.
5452 if filename.endswith('.cc') and not header_found:
5453 return
5454
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005455 # All the lines have been processed, report the errors found.
5456 for required_header_unstripped in required:
5457 template = required[required_header_unstripped][1]
avakulenko@google.com59146752014-08-11 20:20:55 +00005458 if required_header_unstripped.strip('<>"') not in include_dict:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005459 error(filename, required[required_header_unstripped][0],
5460 'build/include_what_you_use', 4,
5461 'Add #include ' + required_header_unstripped + ' for ' + template)
5462
5463
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005464_RE_PATTERN_EXPLICIT_MAKEPAIR = re.compile(r'\bmake_pair\s*<')
5465
5466
5467def CheckMakePairUsesDeduction(filename, clean_lines, linenum, error):
5468 """Check that make_pair's template arguments are deduced.
5469
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005470 G++ 4.6 in C++11 mode fails badly if make_pair's template arguments are
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005471 specified explicitly, and such use isn't intended in any case.
5472
5473 Args:
5474 filename: The name of the current file.
5475 clean_lines: A CleansedLines instance containing the file.
5476 linenum: The number of the line to check.
5477 error: The function to call with any errors found.
5478 """
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005479 line = clean_lines.elided[linenum]
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005480 match = _RE_PATTERN_EXPLICIT_MAKEPAIR.search(line)
5481 if match:
5482 error(filename, linenum, 'build/explicit_make_pair',
5483 4, # 4 = high confidence
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005484 'For C++11-compatibility, omit template arguments from make_pair'
5485 ' OR use pair directly OR if appropriate, construct a pair directly')
avakulenko@google.com59146752014-08-11 20:20:55 +00005486
5487
avakulenko@google.com59146752014-08-11 20:20:55 +00005488def CheckRedundantVirtual(filename, clean_lines, linenum, error):
5489 """Check if line contains a redundant "virtual" function-specifier.
5490
5491 Args:
5492 filename: The name of the current file.
5493 clean_lines: A CleansedLines instance containing the file.
5494 linenum: The number of the line to check.
5495 error: The function to call with any errors found.
5496 """
5497 # Look for "virtual" on current line.
5498 line = clean_lines.elided[linenum]
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005499 virtual = Match(r'^(.*)(\bvirtual\b)(.*)$', line)
avakulenko@google.com59146752014-08-11 20:20:55 +00005500 if not virtual: return
5501
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005502 # Ignore "virtual" keywords that are near access-specifiers. These
5503 # are only used in class base-specifier and do not apply to member
5504 # functions.
5505 if (Search(r'\b(public|protected|private)\s+$', virtual.group(1)) or
5506 Match(r'^\s+(public|protected|private)\b', virtual.group(3))):
5507 return
5508
5509 # Ignore the "virtual" keyword from virtual base classes. Usually
5510 # there is a column on the same line in these cases (virtual base
5511 # classes are rare in google3 because multiple inheritance is rare).
5512 if Match(r'^.*[^:]:[^:].*$', line): return
5513
avakulenko@google.com59146752014-08-11 20:20:55 +00005514 # Look for the next opening parenthesis. This is the start of the
5515 # parameter list (possibly on the next line shortly after virtual).
5516 # TODO(unknown): doesn't work if there are virtual functions with
5517 # decltype() or other things that use parentheses, but csearch suggests
5518 # that this is rare.
5519 end_col = -1
5520 end_line = -1
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005521 start_col = len(virtual.group(2))
Edward Lemur6d31ed52019-12-02 23:00:00 +00005522 for start_line in range(linenum, min(linenum + 3, clean_lines.NumLines())):
avakulenko@google.com59146752014-08-11 20:20:55 +00005523 line = clean_lines.elided[start_line][start_col:]
5524 parameter_list = Match(r'^([^(]*)\(', line)
5525 if parameter_list:
5526 # Match parentheses to find the end of the parameter list
5527 (_, end_line, end_col) = CloseExpression(
5528 clean_lines, start_line, start_col + len(parameter_list.group(1)))
5529 break
5530 start_col = 0
5531
5532 if end_col < 0:
5533 return # Couldn't find end of parameter list, give up
5534
5535 # Look for "override" or "final" after the parameter list
5536 # (possibly on the next few lines).
Edward Lemur6d31ed52019-12-02 23:00:00 +00005537 for i in range(end_line, min(end_line + 3, clean_lines.NumLines())):
avakulenko@google.com59146752014-08-11 20:20:55 +00005538 line = clean_lines.elided[i][end_col:]
5539 match = Search(r'\b(override|final)\b', line)
5540 if match:
5541 error(filename, linenum, 'readability/inheritance', 4,
5542 ('"virtual" is redundant since function is '
5543 'already declared as "%s"' % match.group(1)))
5544
5545 # Set end_col to check whole lines after we are done with the
5546 # first line.
5547 end_col = 0
5548 if Search(r'[^\w]\s*$', line):
5549 break
5550
5551
5552def CheckRedundantOverrideOrFinal(filename, clean_lines, linenum, error):
5553 """Check if line contains a redundant "override" or "final" virt-specifier.
5554
5555 Args:
5556 filename: The name of the current file.
5557 clean_lines: A CleansedLines instance containing the file.
5558 linenum: The number of the line to check.
5559 error: The function to call with any errors found.
5560 """
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005561 # Look for closing parenthesis nearby. We need one to confirm where
5562 # the declarator ends and where the virt-specifier starts to avoid
5563 # false positives.
avakulenko@google.com59146752014-08-11 20:20:55 +00005564 line = clean_lines.elided[linenum]
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005565 declarator_end = line.rfind(')')
5566 if declarator_end >= 0:
5567 fragment = line[declarator_end:]
5568 else:
5569 if linenum > 1 and clean_lines.elided[linenum - 1].rfind(')') >= 0:
5570 fragment = line
5571 else:
5572 return
5573
5574 # Check that at most one of "override" or "final" is present, not both
5575 if Search(r'\boverride\b', fragment) and Search(r'\bfinal\b', fragment):
avakulenko@google.com59146752014-08-11 20:20:55 +00005576 error(filename, linenum, 'readability/inheritance', 4,
5577 ('"override" is redundant since function is '
5578 'already declared as "final"'))
5579
5580
5581
5582
5583# Returns true if we are at a new block, and it is directly
5584# inside of a namespace.
5585def IsBlockInNameSpace(nesting_state, is_forward_declaration):
5586 """Checks that the new block is directly in a namespace.
5587
5588 Args:
5589 nesting_state: The _NestingState object that contains info about our state.
5590 is_forward_declaration: If the class is a forward declared class.
5591 Returns:
5592 Whether or not the new block is directly in a namespace.
5593 """
5594 if is_forward_declaration:
5595 if len(nesting_state.stack) >= 1 and (
5596 isinstance(nesting_state.stack[-1], _NamespaceInfo)):
5597 return True
5598 else:
5599 return False
5600
5601 return (len(nesting_state.stack) > 1 and
5602 nesting_state.stack[-1].check_namespace_indentation and
5603 isinstance(nesting_state.stack[-2], _NamespaceInfo))
5604
5605
5606def ShouldCheckNamespaceIndentation(nesting_state, is_namespace_indent_item,
5607 raw_lines_no_comments, linenum):
5608 """This method determines if we should apply our namespace indentation check.
5609
5610 Args:
5611 nesting_state: The current nesting state.
5612 is_namespace_indent_item: If we just put a new class on the stack, True.
5613 If the top of the stack is not a class, or we did not recently
5614 add the class, False.
5615 raw_lines_no_comments: The lines without the comments.
5616 linenum: The current line number we are processing.
5617
5618 Returns:
5619 True if we should apply our namespace indentation check. Currently, it
5620 only works for classes and namespaces inside of a namespace.
5621 """
5622
5623 is_forward_declaration = IsForwardClassDeclaration(raw_lines_no_comments,
5624 linenum)
5625
5626 if not (is_namespace_indent_item or is_forward_declaration):
5627 return False
5628
5629 # If we are in a macro, we do not want to check the namespace indentation.
5630 if IsMacroDefinition(raw_lines_no_comments, linenum):
5631 return False
5632
5633 return IsBlockInNameSpace(nesting_state, is_forward_declaration)
5634
5635
5636# Call this method if the line is directly inside of a namespace.
5637# If the line above is blank (excluding comments) or the start of
5638# an inner namespace, it cannot be indented.
5639def CheckItemIndentationInNamespace(filename, raw_lines_no_comments, linenum,
5640 error):
5641 line = raw_lines_no_comments[linenum]
5642 if Match(r'^\s+', line):
5643 error(filename, linenum, 'runtime/indentation_namespace', 4,
5644 'Do not indent within a namespace')
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005645
5646
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005647def ProcessLine(filename, file_extension, clean_lines, line,
5648 include_state, function_state, nesting_state, error,
5649 extra_check_functions=[]):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005650 """Processes a single line in the file.
5651
5652 Args:
5653 filename: Filename of the file that is being processed.
5654 file_extension: The extension (dot not included) of the file.
5655 clean_lines: An array of strings, each representing a line of the file,
5656 with comments stripped.
5657 line: Number of line being processed.
5658 include_state: An _IncludeState instance in which the headers are inserted.
5659 function_state: A _FunctionState instance which counts function lines, etc.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005660 nesting_state: A NestingState instance which maintains information about
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005661 the current stack of nested blocks being parsed.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005662 error: A callable to which errors are reported, which takes 4 arguments:
5663 filename, line number, error level, and message
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005664 extra_check_functions: An array of additional check functions that will be
5665 run on each source line. Each function takes 4
5666 arguments: filename, clean_lines, line, error
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005667 """
5668 raw_lines = clean_lines.raw_lines
erg@google.com35589e62010-11-17 18:58:16 +00005669 ParseNolintSuppressions(filename, raw_lines[line], line, error)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005670 nesting_state.Update(filename, clean_lines, line, error)
avakulenko@google.com59146752014-08-11 20:20:55 +00005671 CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line,
5672 error)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005673 if nesting_state.InAsmBlock(): return
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005674 CheckForFunctionLengths(filename, clean_lines, line, function_state, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005675 CheckForMultilineCommentsAndStrings(filename, clean_lines, line, error)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005676 CheckStyle(filename, clean_lines, line, file_extension, nesting_state, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005677 CheckLanguage(filename, clean_lines, line, file_extension, include_state,
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005678 nesting_state, error)
5679 CheckForNonConstReference(filename, clean_lines, line, nesting_state, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005680 CheckForNonStandardConstructs(filename, clean_lines, line,
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005681 nesting_state, error)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005682 CheckVlogArguments(filename, clean_lines, line, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005683 CheckPosixThreading(filename, clean_lines, line, error)
erg@google.com6317a9c2009-06-25 00:28:19 +00005684 CheckInvalidIncrement(filename, clean_lines, line, error)
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005685 CheckMakePairUsesDeduction(filename, clean_lines, line, error)
avakulenko@google.com59146752014-08-11 20:20:55 +00005686 CheckRedundantVirtual(filename, clean_lines, line, error)
5687 CheckRedundantOverrideOrFinal(filename, clean_lines, line, error)
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005688 for check_fn in extra_check_functions:
5689 check_fn(filename, clean_lines, line, error)
avakulenko@google.com17449932014-07-28 22:13:33 +00005690
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005691def FlagCxx11Features(filename, clean_lines, linenum, error):
5692 """Flag those c++11 features that we only allow in certain places.
5693
5694 Args:
5695 filename: The name of the current file.
5696 clean_lines: A CleansedLines instance containing the file.
5697 linenum: The number of the line to check.
5698 error: The function to call with any errors found.
5699 """
5700 line = clean_lines.elided[linenum]
5701
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005702 include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line)
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005703
5704 # Flag unapproved C++ TR1 headers.
5705 if include and include.group(1).startswith('tr1/'):
5706 error(filename, linenum, 'build/c++tr1', 5,
5707 ('C++ TR1 headers such as <%s> are unapproved.') % include.group(1))
5708
5709 # Flag unapproved C++11 headers.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005710 if include and include.group(1) in ('cfenv',
5711 'condition_variable',
5712 'fenv.h',
5713 'future',
5714 'mutex',
5715 'thread',
5716 'chrono',
5717 'ratio',
5718 'regex',
5719 'system_error',
5720 ):
5721 error(filename, linenum, 'build/c++11', 5,
5722 ('<%s> is an unapproved C++11 header.') % include.group(1))
5723
5724 # The only place where we need to worry about C++11 keywords and library
5725 # features in preprocessor directives is in macro definitions.
5726 if Match(r'\s*#', line) and not Match(r'\s*#\s*define\b', line): return
5727
5728 # These are classes and free functions. The classes are always
5729 # mentioned as std::*, but we only catch the free functions if
5730 # they're not found by ADL. They're alphabetical by header.
5731 for top_name in (
5732 # type_traits
5733 'alignment_of',
5734 'aligned_union',
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005735 ):
5736 if Search(r'\bstd::%s\b' % top_name, line):
5737 error(filename, linenum, 'build/c++11', 5,
5738 ('std::%s is an unapproved C++11 class or function. Send c-style '
5739 'an example of where it would make your code more readable, and '
5740 'they may let you use it.') % top_name)
5741
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005742
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005743def FlagCxx14Features(filename, clean_lines, linenum, error):
5744 """Flag those C++14 features that we restrict.
5745
5746 Args:
5747 filename: The name of the current file.
5748 clean_lines: A CleansedLines instance containing the file.
5749 linenum: The number of the line to check.
5750 error: The function to call with any errors found.
5751 """
5752 line = clean_lines.elided[linenum]
5753
5754 include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line)
5755
5756 # Flag unapproved C++14 headers.
5757 if include and include.group(1) in ('scoped_allocator', 'shared_mutex'):
5758 error(filename, linenum, 'build/c++14', 5,
5759 ('<%s> is an unapproved C++14 header.') % include.group(1))
5760
5761
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005762def ProcessFileData(filename, file_extension, lines, error,
5763 extra_check_functions=[]):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005764 """Performs lint checks and reports any errors to the given error function.
5765
5766 Args:
5767 filename: Filename of the file that is being processed.
5768 file_extension: The extension (dot not included) of the file.
5769 lines: An array of strings, each representing a line of the file, with the
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005770 last element being empty if the file is terminated with a newline.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005771 error: A callable to which errors are reported, which takes 4 arguments:
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005772 filename, line number, error level, and message
5773 extra_check_functions: An array of additional check functions that will be
5774 run on each source line. Each function takes 4
5775 arguments: filename, clean_lines, line, error
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005776 """
5777 lines = (['// marker so line numbers and indices both start at 1'] + lines +
5778 ['// marker so line numbers end in a known way'])
5779
5780 include_state = _IncludeState()
5781 function_state = _FunctionState()
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005782 nesting_state = NestingState()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005783
erg@google.com35589e62010-11-17 18:58:16 +00005784 ResetNolintSuppressions()
5785
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005786 CheckForCopyright(filename, lines, error)
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005787 ProcessGlobalSuppresions(lines)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005788 RemoveMultiLineComments(filename, lines, error)
5789 clean_lines = CleansedLines(lines)
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005790
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00005791 if file_extension == 'h':
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005792 CheckForHeaderGuard(filename, clean_lines, error)
5793
Edward Lemur6d31ed52019-12-02 23:00:00 +00005794 for line in range(clean_lines.NumLines()):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005795 ProcessLine(filename, file_extension, clean_lines, line,
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005796 include_state, function_state, nesting_state, error,
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005797 extra_check_functions)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005798 FlagCxx11Features(filename, clean_lines, line, error)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005799 nesting_state.CheckCompletedBlocks(filename, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005800
5801 CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error)
skym@chromium.org3990c412016-02-05 20:55:12 +00005802
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005803 # Check that the .cc file has included its header if it exists.
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005804 if _IsSourceExtension(file_extension):
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005805 CheckHeaderFileIncluded(filename, include_state, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005806
5807 # We check here rather than inside ProcessLine so that we see raw
5808 # lines rather than "cleaned" lines.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005809 CheckForBadCharacters(filename, lines, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005810
5811 CheckForNewlineAtEOF(filename, lines, error)
5812
avakulenko@google.com17449932014-07-28 22:13:33 +00005813def ProcessConfigOverrides(filename):
5814 """ Loads the configuration files and processes the config overrides.
5815
5816 Args:
5817 filename: The name of the file being processed by the linter.
5818
5819 Returns:
5820 False if the current |filename| should not be processed further.
5821 """
5822
5823 abs_filename = os.path.abspath(filename)
5824 cfg_filters = []
5825 keep_looking = True
5826 while keep_looking:
5827 abs_path, base_name = os.path.split(abs_filename)
5828 if not base_name:
5829 break # Reached the root directory.
5830
5831 cfg_file = os.path.join(abs_path, "CPPLINT.cfg")
5832 abs_filename = abs_path
5833 if not os.path.isfile(cfg_file):
5834 continue
5835
5836 try:
5837 with open(cfg_file) as file_handle:
5838 for line in file_handle:
5839 line, _, _ = line.partition('#') # Remove comments.
5840 if not line.strip():
5841 continue
5842
5843 name, _, val = line.partition('=')
5844 name = name.strip()
5845 val = val.strip()
5846 if name == 'set noparent':
5847 keep_looking = False
5848 elif name == 'filter':
5849 cfg_filters.append(val)
5850 elif name == 'exclude_files':
5851 # When matching exclude_files pattern, use the base_name of
5852 # the current file name or the directory name we are processing.
5853 # For example, if we are checking for lint errors in /foo/bar/baz.cc
5854 # and we found the .cfg file at /foo/CPPLINT.cfg, then the config
5855 # file's "exclude_files" filter is meant to be checked against "bar"
5856 # and not "baz" nor "bar/baz.cc".
5857 if base_name:
5858 pattern = re.compile(val)
5859 if pattern.match(base_name):
5860 sys.stderr.write('Ignoring "%s": file excluded by "%s". '
5861 'File path component "%s" matches '
5862 'pattern "%s"\n' %
5863 (filename, cfg_file, base_name, val))
5864 return False
avakulenko@google.com68a4fa62014-08-25 16:26:18 +00005865 elif name == 'linelength':
5866 global _line_length
5867 try:
5868 _line_length = int(val)
5869 except ValueError:
5870 sys.stderr.write('Line length must be numeric.')
avakulenko@google.com17449932014-07-28 22:13:33 +00005871 else:
5872 sys.stderr.write(
5873 'Invalid configuration option (%s) in file %s\n' %
5874 (name, cfg_file))
5875
5876 except IOError:
5877 sys.stderr.write(
5878 "Skipping config file '%s': Can't open for reading\n" % cfg_file)
5879 keep_looking = False
5880
5881 # Apply all the accumulated filters in reverse order (top-level directory
5882 # config options having the least priority).
5883 for filter in reversed(cfg_filters):
5884 _AddFilters(filter)
5885
5886 return True
5887
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005888
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005889def ProcessFile(filename, vlevel, extra_check_functions=[]):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005890 """Does google-lint on a single file.
5891
5892 Args:
5893 filename: The name of the file to parse.
5894
5895 vlevel: The level of errors to report. Every error of confidence
5896 >= verbose_level will be reported. 0 is a good default.
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005897
5898 extra_check_functions: An array of additional check functions that will be
5899 run on each source line. Each function takes 4
5900 arguments: filename, clean_lines, line, error
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005901 """
5902
5903 _SetVerboseLevel(vlevel)
avakulenko@google.com17449932014-07-28 22:13:33 +00005904 _BackupFilters()
5905
5906 if not ProcessConfigOverrides(filename):
5907 _RestoreFilters()
5908 return
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005909
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005910 lf_lines = []
5911 crlf_lines = []
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005912 try:
5913 # Support the UNIX convention of using "-" for stdin. Note that
5914 # we are not opening the file with universal newline support
5915 # (which codecs doesn't support anyway), so the resulting lines do
5916 # contain trailing '\r' characters if we are reading a file that
5917 # has CRLF endings.
5918 # If after the split a trailing '\r' is present, it is removed
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005919 # below.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005920 if filename == '-':
5921 lines = codecs.StreamReaderWriter(sys.stdin,
5922 codecs.getreader('utf8'),
5923 codecs.getwriter('utf8'),
5924 'replace').read().split('\n')
5925 else:
5926 lines = codecs.open(filename, 'r', 'utf8', 'replace').read().split('\n')
5927
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005928 # Remove trailing '\r'.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005929 # The -1 accounts for the extra trailing blank line we get from split()
5930 for linenum in range(len(lines) - 1):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005931 if lines[linenum].endswith('\r'):
5932 lines[linenum] = lines[linenum].rstrip('\r')
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005933 crlf_lines.append(linenum + 1)
5934 else:
5935 lf_lines.append(linenum + 1)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005936
5937 except IOError:
5938 sys.stderr.write(
5939 "Skipping input '%s': Can't open for reading\n" % filename)
avakulenko@google.com17449932014-07-28 22:13:33 +00005940 _RestoreFilters()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005941 return
5942
5943 # Note, if no dot is found, this will give the entire filename as the ext.
5944 file_extension = filename[filename.rfind('.') + 1:]
5945
5946 # When reading from stdin, the extension is unknown, so no cpplint tests
5947 # should rely on the extension.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005948 if filename != '-' and file_extension not in _valid_extensions:
5949 sys.stderr.write('Ignoring %s; not a valid file name '
5950 '(%s)\n' % (filename, ', '.join(_valid_extensions)))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005951 else:
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005952 ProcessFileData(filename, file_extension, lines, Error,
5953 extra_check_functions)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005954
5955 # If end-of-line sequences are a mix of LF and CR-LF, issue
5956 # warnings on the lines with CR.
5957 #
5958 # Don't issue any warnings if all lines are uniformly LF or CR-LF,
5959 # since critique can handle these just fine, and the style guide
5960 # doesn't dictate a particular end of line sequence.
5961 #
5962 # We can't depend on os.linesep to determine what the desired
5963 # end-of-line sequence should be, since that will return the
5964 # server-side end-of-line sequence.
5965 if lf_lines and crlf_lines:
5966 # Warn on every line with CR. An alternative approach might be to
5967 # check whether the file is mostly CRLF or just LF, and warn on the
5968 # minority, we bias toward LF here since most tools prefer LF.
5969 for linenum in crlf_lines:
5970 Error(filename, linenum, 'whitespace/newline', 1,
5971 'Unexpected \\r (^M) found; better to use only \\n')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005972
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00005973 sys.stderr.write('Done processing %s\n' % filename)
avakulenko@google.com17449932014-07-28 22:13:33 +00005974 _RestoreFilters()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005975
5976
5977def PrintUsage(message):
5978 """Prints a brief usage string and exits, optionally with an error message.
5979
5980 Args:
5981 message: The optional error message.
5982 """
5983 sys.stderr.write(_USAGE)
5984 if message:
5985 sys.exit('\nFATAL ERROR: ' + message)
5986 else:
5987 sys.exit(1)
5988
5989
5990def PrintCategories():
5991 """Prints a list of all the error-categories used by error messages.
5992
5993 These are the categories used to filter messages via --filter.
5994 """
erg@google.com35589e62010-11-17 18:58:16 +00005995 sys.stderr.write(''.join(' %s\n' % cat for cat in _ERROR_CATEGORIES))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005996 sys.exit(0)
5997
5998
5999def ParseArguments(args):
6000 """Parses the command line arguments.
6001
6002 This may set the output format and verbosity level as side-effects.
6003
6004 Args:
6005 args: The command line arguments:
6006
6007 Returns:
6008 The list of filenames to lint.
6009 """
6010 try:
6011 (opts, filenames) = getopt.getopt(args, '', ['help', 'output=', 'verbose=',
Jordan Bayles91a32c52019-02-22 21:28:17 +00006012 'headers=', # We understand but ignore headers.
erg@google.com26970fa2009-11-17 18:07:32 +00006013 'counting=',
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00006014 'filter=',
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00006015 'root=',
6016 'linelength=',
sdefresne263e9282016-07-19 02:14:22 -07006017 'extensions=',
Jordan Bayles91a32c52019-02-22 21:28:17 +00006018 'project_root=',
6019 'repository='])
6020 except getopt.GetoptError as e:
6021 PrintUsage('Invalid arguments: {}'.format(e))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006022
6023 verbosity = _VerboseLevel()
6024 output_format = _OutputFormat()
6025 filters = ''
erg@google.com26970fa2009-11-17 18:07:32 +00006026 counting_style = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006027
6028 for (opt, val) in opts:
6029 if opt == '--help':
6030 PrintUsage(None)
6031 elif opt == '--output':
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00006032 if val not in ('emacs', 'vs7', 'eclipse'):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00006033 PrintUsage('The only allowed output formats are emacs, vs7 and eclipse.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006034 output_format = val
6035 elif opt == '--verbose':
6036 verbosity = int(val)
6037 elif opt == '--filter':
6038 filters = val
erg@google.com6317a9c2009-06-25 00:28:19 +00006039 if not filters:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006040 PrintCategories()
erg@google.com26970fa2009-11-17 18:07:32 +00006041 elif opt == '--counting':
6042 if val not in ('total', 'toplevel', 'detailed'):
6043 PrintUsage('Valid counting options are total, toplevel, and detailed')
6044 counting_style = val
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00006045 elif opt == '--root':
6046 global _root
6047 _root = val
Jordan Bayles91a32c52019-02-22 21:28:17 +00006048 elif opt == '--project_root' or opt == "--repository":
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00006049 global _project_root
6050 _project_root = val
6051 if not os.path.isabs(_project_root):
6052 PrintUsage('Project root must be an absolute path.')
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00006053 elif opt == '--linelength':
6054 global _line_length
6055 try:
6056 _line_length = int(val)
6057 except ValueError:
6058 PrintUsage('Line length must be digits.')
6059 elif opt == '--extensions':
6060 global _valid_extensions
6061 try:
6062 _valid_extensions = set(val.split(','))
6063 except ValueError:
qyearsley12fa6ff2016-08-24 09:18:40 -07006064 PrintUsage('Extensions must be comma separated list.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006065
6066 if not filenames:
6067 PrintUsage('No files were specified.')
6068
6069 _SetOutputFormat(output_format)
6070 _SetVerboseLevel(verbosity)
6071 _SetFilters(filters)
erg@google.com26970fa2009-11-17 18:07:32 +00006072 _SetCountingStyle(counting_style)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006073
6074 return filenames
6075
6076
6077def main():
6078 filenames = ParseArguments(sys.argv[1:])
6079
6080 # Change stderr to write with replacement characters so we don't die
6081 # if we try to print something containing non-ASCII characters.
Edward Lemur6d31ed52019-12-02 23:00:00 +00006082 # We use sys.stderr.buffer in Python 3, since StreamReaderWriter writes bytes
6083 # to the specified stream.
6084 sys.stderr = codecs.StreamReaderWriter(
6085 getattr(sys.stderr, 'buffer', sys.stderr),
6086 codecs.getreader('utf8'), codecs.getwriter('utf8'), 'replace')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006087
erg@google.com26970fa2009-11-17 18:07:32 +00006088 _cpplint_state.ResetErrorCounts()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006089 for filename in filenames:
6090 ProcessFile(filename, _cpplint_state.verbose_level)
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00006091 _cpplint_state.PrintErrorCounts()
erg@google.com26970fa2009-11-17 18:07:32 +00006092
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006093 sys.exit(_cpplint_state.error_count > 0)
6094
6095
6096if __name__ == '__main__':
6097 main()