blob: b8c72dbe77ac7b089089997025fd377aa0fa70f6 [file] [log] [blame]
Ryan Macnakfd032192022-03-21 20:45:12 +00001#!/usr/bin/env python3
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',
dan sinclair9a3c4bc2022-06-17 22:58:24 +0000332 'any',
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000333 'array',
334 'atomic',
335 'bitset',
dan sinclair9a3c4bc2022-06-17 22:58:24 +0000336 'charconv',
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000337 'chrono',
338 'codecvt',
339 'complex',
340 'condition_variable',
341 'deque',
dan sinclair9a3c4bc2022-06-17 22:58:24 +0000342 'execution',
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000343 'exception',
dan sinclair9a3c4bc2022-06-17 22:58:24 +0000344 'filesystem',
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000345 'forward_list',
346 'fstream',
347 'functional',
348 'future',
349 'initializer_list',
350 'iomanip',
351 'ios',
352 'iosfwd',
353 'iostream',
354 'istream',
355 'iterator',
356 'limits',
357 'list',
358 'locale',
359 'map',
360 'memory',
dan sinclair9a3c4bc2022-06-17 22:58:24 +0000361 'memory_resource',
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000362 'mutex',
363 'new',
364 'numeric',
dan sinclair9a3c4bc2022-06-17 22:58:24 +0000365 'optional',
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000366 'ostream',
367 'queue',
368 'random',
369 'ratio',
370 'regex',
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000371 'scoped_allocator',
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000372 'set',
373 'sstream',
374 'stack',
375 'stdexcept',
376 'streambuf',
377 'string',
Jasper Chapman-Black9ab047e2019-11-07 15:51:54 +0000378 'string_view',
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000379 'strstream',
380 'system_error',
381 'thread',
382 'tuple',
383 'typeindex',
384 'typeinfo',
385 'type_traits',
386 'unordered_map',
387 'unordered_set',
388 'utility',
389 'valarray',
dan sinclair9a3c4bc2022-06-17 22:58:24 +0000390 'variant',
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000391 'vector',
392 # 17.6.1.2 C++ headers for C library facilities
393 'cassert',
394 'ccomplex',
395 'cctype',
396 'cerrno',
397 'cfenv',
398 'cfloat',
399 'cinttypes',
400 'ciso646',
401 'climits',
402 'clocale',
403 'cmath',
404 'csetjmp',
405 'csignal',
406 'cstdalign',
407 'cstdarg',
408 'cstdbool',
409 'cstddef',
410 'cstdint',
411 'cstdio',
412 'cstdlib',
413 'cstring',
414 'ctgmath',
415 'ctime',
416 'cuchar',
417 'cwchar',
418 'cwctype',
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000419 ])
420
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000421# Type names
422_TYPES = re.compile(
423 r'^(?:'
424 # [dcl.type.simple]
425 r'(char(16_t|32_t)?)|wchar_t|'
426 r'bool|short|int|long|signed|unsigned|float|double|'
427 # [support.types]
428 r'(ptrdiff_t|size_t|max_align_t|nullptr_t)|'
429 # [cstdint.syn]
430 r'(u?int(_fast|_least)?(8|16|32|64)_t)|'
431 r'(u?int(max|ptr)_t)|'
432 r')$')
433
avakulenko@google.comd39bbb52014-06-04 22:55:20 +0000434
Fletcher Woodruff11b34152020-04-23 21:21:40 +0000435# These headers are excluded from [build/include], [build/include_directory],
436# and [build/include_order] checks:
avakulenko@google.com59146752014-08-11 20:20:55 +0000437# - Anything not following google file name conventions (containing an
438# uppercase character, such as Python.h or nsStringAPI.h, for example).
439# - Lua headers.
440_THIRD_PARTY_HEADERS_PATTERN = re.compile(
441 r'^(?:[^/]*[A-Z][^/]*\.h|lua\.h|lauxlib\.h|lualib\.h)$')
442
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000443# Pattern for matching FileInfo.BaseName() against test file name
444_TEST_FILE_SUFFIX = r'(_test|_unittest|_regtest)$'
445
446# Pattern that matches only complete whitespace, possibly across multiple lines.
447_EMPTY_CONDITIONAL_BODY_PATTERN = re.compile(r'^\s*$', re.DOTALL)
avakulenko@google.com59146752014-08-11 20:20:55 +0000448
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000449# Assertion macros. These are defined in base/logging.h and
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000450# testing/base/public/gunit.h.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000451_CHECK_MACROS = [
erg@google.com6317a9c2009-06-25 00:28:19 +0000452 'DCHECK', 'CHECK',
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000453 'EXPECT_TRUE', 'ASSERT_TRUE',
454 'EXPECT_FALSE', 'ASSERT_FALSE',
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000455 ]
456
erg@google.com6317a9c2009-06-25 00:28:19 +0000457# Replacement macros for CHECK/DCHECK/EXPECT_TRUE/EXPECT_FALSE
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000458_CHECK_REPLACEMENT = dict([(m, {}) for m in _CHECK_MACROS])
459
460for op, replacement in [('==', 'EQ'), ('!=', 'NE'),
461 ('>=', 'GE'), ('>', 'GT'),
462 ('<=', 'LE'), ('<', 'LT')]:
erg@google.com6317a9c2009-06-25 00:28:19 +0000463 _CHECK_REPLACEMENT['DCHECK'][op] = 'DCHECK_%s' % replacement
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000464 _CHECK_REPLACEMENT['CHECK'][op] = 'CHECK_%s' % replacement
465 _CHECK_REPLACEMENT['EXPECT_TRUE'][op] = 'EXPECT_%s' % replacement
466 _CHECK_REPLACEMENT['ASSERT_TRUE'][op] = 'ASSERT_%s' % replacement
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000467
468for op, inv_replacement in [('==', 'NE'), ('!=', 'EQ'),
469 ('>=', 'LT'), ('>', 'LE'),
470 ('<=', 'GT'), ('<', 'GE')]:
471 _CHECK_REPLACEMENT['EXPECT_FALSE'][op] = 'EXPECT_%s' % inv_replacement
472 _CHECK_REPLACEMENT['ASSERT_FALSE'][op] = 'ASSERT_%s' % inv_replacement
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000473
mazda@chromium.org3fffcec2013-06-07 01:04:53 +0000474# Alternative tokens and their replacements. For full list, see section 2.5
475# Alternative tokens [lex.digraph] in the C++ standard.
476#
477# Digraphs (such as '%:') are not included here since it's a mess to
478# match those on a word boundary.
479_ALT_TOKEN_REPLACEMENT = {
480 'and': '&&',
481 'bitor': '|',
482 'or': '||',
483 'xor': '^',
484 'compl': '~',
485 'bitand': '&',
486 'and_eq': '&=',
487 'or_eq': '|=',
488 'xor_eq': '^=',
489 'not': '!',
490 'not_eq': '!='
491 }
492
493# Compile regular expression that matches all the above keywords. The "[ =()]"
494# bit is meant to avoid matching these keywords outside of boolean expressions.
495#
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000496# False positives include C-style multi-line comments and multi-line strings
497# but those have always been troublesome for cpplint.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +0000498_ALT_TOKEN_REPLACEMENT_PATTERN = re.compile(
499 r'[ =()](' + ('|'.join(_ALT_TOKEN_REPLACEMENT.keys())) + r')(?=[ (]|$)')
500
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000501
502# These constants define types of headers for use with
503# _IncludeState.CheckNextIncludeOrder().
504_C_SYS_HEADER = 1
505_CPP_SYS_HEADER = 2
506_LIKELY_MY_HEADER = 3
507_POSSIBLE_MY_HEADER = 4
508_OTHER_HEADER = 5
509
mazda@chromium.org3fffcec2013-06-07 01:04:53 +0000510# These constants define the current inline assembly state
511_NO_ASM = 0 # Outside of inline assembly block
512_INSIDE_ASM = 1 # Inside inline assembly block
513_END_ASM = 2 # Last line of inline assembly block
514_BLOCK_ASM = 3 # The whole block is an inline assembly block
515
516# Match start of assembly blocks
517_MATCH_ASM = re.compile(r'^\s*(?:asm|_asm|__asm|__asm__)'
518 r'(?:\s+(volatile|__volatile__))?'
519 r'\s*[{(]')
520
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000521# Match strings that indicate we're working on a C (not C++) file.
522_SEARCH_C_FILE = re.compile(r'\b(?:LINT_C_FILE|'
523 r'vim?:\s*.*(\s*|:)filetype=c(\s*|:|$))')
524
525# Match string that indicates we're working on a Linux Kernel file.
526_SEARCH_KERNEL_FILE = re.compile(r'\b(?:LINT_KERNEL_FILE)')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000527
528_regexp_compile_cache = {}
529
erg@google.com35589e62010-11-17 18:58:16 +0000530# {str, set(int)}: a map from error categories to sets of linenumbers
531# on which those errors are expected and should be suppressed.
532_error_suppressions = {}
533
mazda@chromium.org3fffcec2013-06-07 01:04:53 +0000534# The root directory used for deriving header guard CPP variable.
535# This is set by --root flag.
536_root = None
David Sanders2f988472022-05-21 01:35:11 +0000537_root_debug = False
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +0000538
539# The project root directory. Used for deriving header guard CPP variable.
540# This is set by --project_root flag. Must be an absolute path.
541_project_root = None
sdefresne263e9282016-07-19 02:14:22 -0700542
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000543# The allowed line length of files.
544# This is set by --linelength flag.
545_line_length = 80
546
547# The allowed extensions for file names
548# This is set by --extensions flag.
549_valid_extensions = set(['cc', 'h', 'cpp', 'cu', 'cuh'])
550
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000551# {str, bool}: a map from error categories to booleans which indicate if the
552# category should be suppressed for every line.
553_global_error_suppressions = {}
554
555
erg@google.com35589e62010-11-17 18:58:16 +0000556def ParseNolintSuppressions(filename, raw_line, linenum, error):
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000557 """Updates the global list of line error-suppressions.
erg@google.com35589e62010-11-17 18:58:16 +0000558
559 Parses any NOLINT comments on the current line, updating the global
560 error_suppressions store. Reports an error if the NOLINT comment
561 was malformed.
562
563 Args:
564 filename: str, the name of the input file.
565 raw_line: str, the line of input text, with comments.
566 linenum: int, the number of the current line.
567 error: function, an error handler.
568 """
avakulenko@google.com59146752014-08-11 20:20:55 +0000569 matched = Search(r'\bNOLINT(NEXTLINE)?\b(\([^)]+\))?', raw_line)
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +0000570 if matched:
avakulenko@google.com59146752014-08-11 20:20:55 +0000571 if matched.group(1):
572 suppressed_line = linenum + 1
573 else:
574 suppressed_line = linenum
575 category = matched.group(2)
erg@google.com35589e62010-11-17 18:58:16 +0000576 if category in (None, '(*)'): # => "suppress all"
avakulenko@google.com59146752014-08-11 20:20:55 +0000577 _error_suppressions.setdefault(None, set()).add(suppressed_line)
erg@google.com35589e62010-11-17 18:58:16 +0000578 else:
579 if category.startswith('(') and category.endswith(')'):
580 category = category[1:-1]
581 if category in _ERROR_CATEGORIES:
avakulenko@google.com59146752014-08-11 20:20:55 +0000582 _error_suppressions.setdefault(category, set()).add(suppressed_line)
avakulenko@google.com255f2be2014-12-05 22:19:55 +0000583 elif category not in _LEGACY_ERROR_CATEGORIES:
erg@google.com35589e62010-11-17 18:58:16 +0000584 error(filename, linenum, 'readability/nolint', 5,
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +0000585 'Unknown NOLINT error category: %s' % category)
erg@google.com35589e62010-11-17 18:58:16 +0000586
587
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000588def ProcessGlobalSuppresions(lines):
589 """Updates the list of global error suppressions.
590
591 Parses any lint directives in the file that have global effect.
592
593 Args:
594 lines: An array of strings, each representing a line of the file, with the
595 last element being empty if the file is terminated with a newline.
596 """
597 for line in lines:
598 if _SEARCH_C_FILE.search(line):
599 for category in _DEFAULT_C_SUPPRESSED_CATEGORIES:
600 _global_error_suppressions[category] = True
601 if _SEARCH_KERNEL_FILE.search(line):
602 for category in _DEFAULT_KERNEL_SUPPRESSED_CATEGORIES:
603 _global_error_suppressions[category] = True
604
605
erg@google.com35589e62010-11-17 18:58:16 +0000606def ResetNolintSuppressions():
avakulenko@google.com59146752014-08-11 20:20:55 +0000607 """Resets the set of NOLINT suppressions to empty."""
erg@google.com35589e62010-11-17 18:58:16 +0000608 _error_suppressions.clear()
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000609 _global_error_suppressions.clear()
erg@google.com35589e62010-11-17 18:58:16 +0000610
611
612def IsErrorSuppressedByNolint(category, linenum):
613 """Returns true if the specified error category is suppressed on this line.
614
615 Consults the global error_suppressions map populated by
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000616 ParseNolintSuppressions/ProcessGlobalSuppresions/ResetNolintSuppressions.
erg@google.com35589e62010-11-17 18:58:16 +0000617
618 Args:
619 category: str, the category of the error.
620 linenum: int, the current line number.
621 Returns:
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000622 bool, True iff the error should be suppressed due to a NOLINT comment or
623 global suppression.
erg@google.com35589e62010-11-17 18:58:16 +0000624 """
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000625 return (_global_error_suppressions.get(category, False) or
626 linenum in _error_suppressions.get(category, set()) or
erg@google.com35589e62010-11-17 18:58:16 +0000627 linenum in _error_suppressions.get(None, set()))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000628
avakulenko@google.comd39bbb52014-06-04 22:55:20 +0000629
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000630def Match(pattern, s):
631 """Matches the string with the pattern, caching the compiled regexp."""
632 # The regexp compilation caching is inlined in both Match and Search for
633 # performance reasons; factoring it out into a separate function turns out
634 # to be noticeably expensive.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000635 if pattern not in _regexp_compile_cache:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000636 _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
637 return _regexp_compile_cache[pattern].match(s)
638
639
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000640def ReplaceAll(pattern, rep, s):
641 """Replaces instances of pattern in a string with a replacement.
642
643 The compiled regex is kept in a cache shared by Match and Search.
644
645 Args:
646 pattern: regex pattern
647 rep: replacement text
648 s: search string
649
650 Returns:
651 string with replacements made (or original string if no replacements)
652 """
653 if pattern not in _regexp_compile_cache:
654 _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
655 return _regexp_compile_cache[pattern].sub(rep, s)
656
657
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000658def Search(pattern, s):
659 """Searches the string for the pattern, caching the compiled regexp."""
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000660 if pattern not in _regexp_compile_cache:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000661 _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
662 return _regexp_compile_cache[pattern].search(s)
663
664
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000665def _IsSourceExtension(s):
666 """File extension (excluding dot) matches a source file extension."""
667 return s in ('c', 'cc', 'cpp', 'cxx')
668
669
avakulenko@google.com59146752014-08-11 20:20:55 +0000670class _IncludeState(object):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000671 """Tracks line numbers for includes, and the order in which includes appear.
672
avakulenko@google.com59146752014-08-11 20:20:55 +0000673 include_list contains list of lists of (header, line number) pairs.
674 It's a lists of lists rather than just one flat list to make it
675 easier to update across preprocessor boundaries.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000676
677 Call CheckNextIncludeOrder() once for each header in the file, passing
678 in the type constants defined above. Calls in an illegal order will
679 raise an _IncludeError with an appropriate error message.
680
681 """
682 # self._section will move monotonically through this set. If it ever
683 # needs to move backwards, CheckNextIncludeOrder will raise an error.
684 _INITIAL_SECTION = 0
685 _MY_H_SECTION = 1
686 _C_SECTION = 2
687 _CPP_SECTION = 3
688 _OTHER_H_SECTION = 4
689
690 _TYPE_NAMES = {
691 _C_SYS_HEADER: 'C system header',
692 _CPP_SYS_HEADER: 'C++ system header',
693 _LIKELY_MY_HEADER: 'header this file implements',
694 _POSSIBLE_MY_HEADER: 'header this file may implement',
695 _OTHER_HEADER: 'other header',
696 }
697 _SECTION_NAMES = {
698 _INITIAL_SECTION: "... nothing. (This can't be an error.)",
699 _MY_H_SECTION: 'a header this file implements',
700 _C_SECTION: 'C system header',
701 _CPP_SECTION: 'C++ system header',
702 _OTHER_H_SECTION: 'other header',
703 }
704
705 def __init__(self):
avakulenko@google.com59146752014-08-11 20:20:55 +0000706 self.include_list = [[]]
707 self.ResetSection('')
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000708
avakulenko@google.com59146752014-08-11 20:20:55 +0000709 def FindHeader(self, header):
710 """Check if a header has already been included.
711
712 Args:
713 header: header to check.
714 Returns:
715 Line number of previous occurrence, or -1 if the header has not
716 been seen before.
717 """
718 for section_list in self.include_list:
719 for f in section_list:
720 if f[0] == header:
721 return f[1]
722 return -1
723
724 def ResetSection(self, directive):
725 """Reset section checking for preprocessor directive.
726
727 Args:
728 directive: preprocessor directive (e.g. "if", "else").
729 """
erg@google.com26970fa2009-11-17 18:07:32 +0000730 # The name of the current section.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000731 self._section = self._INITIAL_SECTION
erg@google.com26970fa2009-11-17 18:07:32 +0000732 # The path of last found header.
733 self._last_header = ''
734
avakulenko@google.com59146752014-08-11 20:20:55 +0000735 # Update list of includes. Note that we never pop from the
736 # include list.
737 if directive in ('if', 'ifdef', 'ifndef'):
738 self.include_list.append([])
739 elif directive in ('else', 'elif'):
740 self.include_list[-1] = []
741
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000742 def SetLastHeader(self, header_path):
743 self._last_header = header_path
744
erg@google.com26970fa2009-11-17 18:07:32 +0000745 def CanonicalizeAlphabeticalOrder(self, header_path):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +0000746 """Returns a path canonicalized for alphabetical comparison.
erg@google.com26970fa2009-11-17 18:07:32 +0000747
748 - replaces "-" with "_" so they both cmp the same.
749 - removes '-inl' since we don't require them to be after the main header.
750 - lowercase everything, just in case.
751
752 Args:
753 header_path: Path to be canonicalized.
754
755 Returns:
756 Canonicalized path.
757 """
758 return header_path.replace('-inl.h', '.h').replace('-', '_').lower()
759
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000760 def IsInAlphabeticalOrder(self, clean_lines, linenum, header_path):
erg@google.com26970fa2009-11-17 18:07:32 +0000761 """Check if a header is in alphabetical order with the previous header.
762
763 Args:
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000764 clean_lines: A CleansedLines instance containing the file.
765 linenum: The number of the line to check.
766 header_path: Canonicalized header to be checked.
erg@google.com26970fa2009-11-17 18:07:32 +0000767
768 Returns:
769 Returns true if the header is in alphabetical order.
770 """
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000771 # If previous section is different from current section, _last_header will
772 # be reset to empty string, so it's always less than current header.
773 #
774 # If previous line was a blank line, assume that the headers are
775 # intentionally sorted the way they are.
776 if (self._last_header > header_path and
avakulenko@google.com255f2be2014-12-05 22:19:55 +0000777 Match(r'^\s*#\s*include\b', clean_lines.elided[linenum - 1])):
erg@google.com26970fa2009-11-17 18:07:32 +0000778 return False
erg@google.com26970fa2009-11-17 18:07:32 +0000779 return True
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000780
781 def CheckNextIncludeOrder(self, header_type):
782 """Returns a non-empty error message if the next header is out of order.
783
784 This function also updates the internal state to be ready to check
785 the next include.
786
787 Args:
788 header_type: One of the _XXX_HEADER constants defined above.
789
790 Returns:
791 The empty string if the header is in the right order, or an
792 error message describing what's wrong.
793
794 """
795 error_message = ('Found %s after %s' %
796 (self._TYPE_NAMES[header_type],
797 self._SECTION_NAMES[self._section]))
798
erg@google.com26970fa2009-11-17 18:07:32 +0000799 last_section = self._section
800
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000801 if header_type == _C_SYS_HEADER:
802 if self._section <= self._C_SECTION:
803 self._section = self._C_SECTION
804 else:
erg@google.com26970fa2009-11-17 18:07:32 +0000805 self._last_header = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000806 return error_message
807 elif header_type == _CPP_SYS_HEADER:
808 if self._section <= self._CPP_SECTION:
809 self._section = self._CPP_SECTION
810 else:
erg@google.com26970fa2009-11-17 18:07:32 +0000811 self._last_header = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000812 return error_message
813 elif header_type == _LIKELY_MY_HEADER:
814 if self._section <= self._MY_H_SECTION:
815 self._section = self._MY_H_SECTION
816 else:
817 self._section = self._OTHER_H_SECTION
818 elif header_type == _POSSIBLE_MY_HEADER:
819 if self._section <= self._MY_H_SECTION:
820 self._section = self._MY_H_SECTION
821 else:
822 # This will always be the fallback because we're not sure
823 # enough that the header is associated with this file.
824 self._section = self._OTHER_H_SECTION
825 else:
826 assert header_type == _OTHER_HEADER
827 self._section = self._OTHER_H_SECTION
828
erg@google.com26970fa2009-11-17 18:07:32 +0000829 if last_section != self._section:
830 self._last_header = ''
831
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000832 return ''
833
834
835class _CppLintState(object):
836 """Maintains module-wide state.."""
837
838 def __init__(self):
839 self.verbose_level = 1 # global setting.
840 self.error_count = 0 # global count of reported errors
erg@google.com6317a9c2009-06-25 00:28:19 +0000841 # filters to apply when emitting error messages
842 self.filters = _DEFAULT_FILTERS[:]
avakulenko@google.com17449932014-07-28 22:13:33 +0000843 # backup of filter list. Used to restore the state after each file.
844 self._filters_backup = self.filters[:]
erg@google.com26970fa2009-11-17 18:07:32 +0000845 self.counting = 'total' # In what way are we counting errors?
846 self.errors_by_category = {} # string to int dict storing error counts
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000847
848 # output format:
849 # "emacs" - format that emacs can parse (default)
850 # "vs7" - format that Microsoft Visual Studio 7 can parse
851 self.output_format = 'emacs'
852
853 def SetOutputFormat(self, output_format):
854 """Sets the output format for errors."""
855 self.output_format = output_format
856
857 def SetVerboseLevel(self, level):
858 """Sets the module's verbosity, and returns the previous setting."""
859 last_verbose_level = self.verbose_level
860 self.verbose_level = level
861 return last_verbose_level
862
erg@google.com26970fa2009-11-17 18:07:32 +0000863 def SetCountingStyle(self, counting_style):
864 """Sets the module's counting options."""
865 self.counting = counting_style
866
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000867 def SetFilters(self, filters):
868 """Sets the error-message filters.
869
870 These filters are applied when deciding whether to emit a given
871 error message.
872
873 Args:
874 filters: A string of comma-separated filters (eg "+whitespace/indent").
875 Each filter should start with + or -; else we die.
erg@google.com6317a9c2009-06-25 00:28:19 +0000876
877 Raises:
878 ValueError: The comma-separated filters did not all start with '+' or '-'.
879 E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter"
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000880 """
erg@google.com6317a9c2009-06-25 00:28:19 +0000881 # Default filters always have less priority than the flag ones.
882 self.filters = _DEFAULT_FILTERS[:]
avakulenko@google.com17449932014-07-28 22:13:33 +0000883 self.AddFilters(filters)
884
885 def AddFilters(self, filters):
886 """ Adds more filters to the existing list of error-message filters. """
erg@google.com6317a9c2009-06-25 00:28:19 +0000887 for filt in filters.split(','):
888 clean_filt = filt.strip()
889 if clean_filt:
890 self.filters.append(clean_filt)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000891 for filt in self.filters:
892 if not (filt.startswith('+') or filt.startswith('-')):
893 raise ValueError('Every filter in --filters must start with + or -'
894 ' (%s does not)' % filt)
895
avakulenko@google.com17449932014-07-28 22:13:33 +0000896 def BackupFilters(self):
897 """ Saves the current filter list to backup storage."""
898 self._filters_backup = self.filters[:]
899
900 def RestoreFilters(self):
901 """ Restores filters previously backed up."""
902 self.filters = self._filters_backup[:]
903
erg@google.com26970fa2009-11-17 18:07:32 +0000904 def ResetErrorCounts(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000905 """Sets the module's error statistic back to zero."""
906 self.error_count = 0
erg@google.com26970fa2009-11-17 18:07:32 +0000907 self.errors_by_category = {}
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000908
erg@google.com26970fa2009-11-17 18:07:32 +0000909 def IncrementErrorCount(self, category):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000910 """Bumps the module's error statistic."""
911 self.error_count += 1
erg@google.com26970fa2009-11-17 18:07:32 +0000912 if self.counting in ('toplevel', 'detailed'):
913 if self.counting != 'detailed':
914 category = category.split('/')[0]
915 if category not in self.errors_by_category:
916 self.errors_by_category[category] = 0
917 self.errors_by_category[category] += 1
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000918
erg@google.com26970fa2009-11-17 18:07:32 +0000919 def PrintErrorCounts(self):
920 """Print a summary of errors by category, and the total."""
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000921 for category, count in self.errors_by_category.items():
erg@google.com26970fa2009-11-17 18:07:32 +0000922 sys.stderr.write('Category \'%s\' errors found: %d\n' %
923 (category, count))
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +0000924 sys.stderr.write('Total errors found: %d\n' % self.error_count)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000925
926_cpplint_state = _CppLintState()
927
928
929def _OutputFormat():
930 """Gets the module's output format."""
931 return _cpplint_state.output_format
932
933
934def _SetOutputFormat(output_format):
935 """Sets the module's output format."""
936 _cpplint_state.SetOutputFormat(output_format)
937
938
939def _VerboseLevel():
940 """Returns the module's verbosity setting."""
941 return _cpplint_state.verbose_level
942
943
944def _SetVerboseLevel(level):
945 """Sets the module's verbosity, and returns the previous setting."""
946 return _cpplint_state.SetVerboseLevel(level)
947
948
erg@google.com26970fa2009-11-17 18:07:32 +0000949def _SetCountingStyle(level):
950 """Sets the module's counting options."""
951 _cpplint_state.SetCountingStyle(level)
952
953
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000954def _Filters():
955 """Returns the module's list of output filters, as a list."""
956 return _cpplint_state.filters
957
958
959def _SetFilters(filters):
960 """Sets the module's error-message filters.
961
962 These filters are applied when deciding whether to emit a given
963 error message.
964
965 Args:
966 filters: A string of comma-separated filters (eg "whitespace/indent").
967 Each filter should start with + or -; else we die.
968 """
969 _cpplint_state.SetFilters(filters)
970
avakulenko@google.com17449932014-07-28 22:13:33 +0000971def _AddFilters(filters):
972 """Adds more filter overrides.
avakulenko@google.com59146752014-08-11 20:20:55 +0000973
avakulenko@google.com17449932014-07-28 22:13:33 +0000974 Unlike _SetFilters, this function does not reset the current list of filters
975 available.
976
977 Args:
978 filters: A string of comma-separated filters (eg "whitespace/indent").
979 Each filter should start with + or -; else we die.
980 """
981 _cpplint_state.AddFilters(filters)
982
983def _BackupFilters():
984 """ Saves the current filter list to backup storage."""
985 _cpplint_state.BackupFilters()
986
987def _RestoreFilters():
988 """ Restores filters previously backed up."""
989 _cpplint_state.RestoreFilters()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000990
991class _FunctionState(object):
992 """Tracks current function name and the number of lines in its body."""
993
994 _NORMAL_TRIGGER = 250 # for --v=0, 500 for --v=1, etc.
995 _TEST_TRIGGER = 400 # about 50% more than _NORMAL_TRIGGER.
996
997 def __init__(self):
998 self.in_a_function = False
999 self.lines_in_function = 0
1000 self.current_function = ''
1001
1002 def Begin(self, function_name):
1003 """Start analyzing function body.
1004
1005 Args:
1006 function_name: The name of the function being tracked.
1007 """
1008 self.in_a_function = True
1009 self.lines_in_function = 0
1010 self.current_function = function_name
1011
1012 def Count(self):
1013 """Count line in current function body."""
1014 if self.in_a_function:
1015 self.lines_in_function += 1
1016
1017 def Check(self, error, filename, linenum):
1018 """Report if too many lines in function body.
1019
1020 Args:
1021 error: The function to call with any errors found.
1022 filename: The name of the current file.
1023 linenum: The number of the line to check.
1024 """
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00001025 if not self.in_a_function:
1026 return
1027
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001028 if Match(r'T(EST|est)', self.current_function):
1029 base_trigger = self._TEST_TRIGGER
1030 else:
1031 base_trigger = self._NORMAL_TRIGGER
1032 trigger = base_trigger * 2**_VerboseLevel()
1033
1034 if self.lines_in_function > trigger:
1035 error_level = int(math.log(self.lines_in_function / base_trigger, 2))
1036 # 50 => 0, 100 => 1, 200 => 2, 400 => 3, 800 => 4, 1600 => 5, ...
1037 if error_level > 5:
1038 error_level = 5
1039 error(filename, linenum, 'readability/fn_size', error_level,
1040 'Small and focused functions are preferred:'
1041 ' %s has %d non-comment lines'
1042 ' (error triggered by exceeding %d lines).' % (
1043 self.current_function, self.lines_in_function, trigger))
1044
1045 def End(self):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00001046 """Stop analyzing function body."""
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001047 self.in_a_function = False
1048
1049
1050class _IncludeError(Exception):
1051 """Indicates a problem with the include order in a file."""
1052 pass
1053
1054
avakulenko@google.com59146752014-08-11 20:20:55 +00001055class FileInfo(object):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001056 """Provides utility functions for filenames.
1057
1058 FileInfo provides easy access to the components of a file's path
1059 relative to the project root.
1060 """
1061
1062 def __init__(self, filename):
1063 self._filename = filename
1064
1065 def FullName(self):
1066 """Make Windows paths like Unix."""
1067 return os.path.abspath(self._filename).replace('\\', '/')
1068
1069 def RepositoryName(self):
Edward Lemur6d31ed52019-12-02 23:00:00 +00001070 r"""FullName after removing the local path to the repository.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001071
1072 If we have a real absolute path name here we can try to do something smart:
1073 detecting the root of the checkout and truncating /path/to/checkout from
1074 the name so that we get header guards that don't include things like
1075 "C:\Documents and Settings\..." or "/home/username/..." in them and thus
1076 people on different computers who have checked the source out to different
1077 locations won't see bogus errors.
1078 """
1079 fullname = self.FullName()
1080
1081 if os.path.exists(fullname):
1082 project_dir = os.path.dirname(fullname)
1083
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00001084 if _project_root:
1085 prefix = os.path.commonprefix([_project_root, project_dir])
1086 return fullname[len(prefix) + 1:]
1087
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001088 if os.path.exists(os.path.join(project_dir, ".svn")):
1089 # If there's a .svn file in the current directory, we recursively look
1090 # up the directory tree for the top of the SVN checkout
1091 root_dir = project_dir
1092 one_up_dir = os.path.dirname(root_dir)
1093 while os.path.exists(os.path.join(one_up_dir, ".svn")):
1094 root_dir = os.path.dirname(root_dir)
1095 one_up_dir = os.path.dirname(one_up_dir)
1096
1097 prefix = os.path.commonprefix([root_dir, project_dir])
1098 return fullname[len(prefix) + 1:]
1099
erg@chromium.org7956a872011-11-30 01:44:03 +00001100 # Not SVN <= 1.6? Try to find a git, hg, or svn top level directory by
1101 # searching up from the current path.
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00001102 root_dir = os.path.dirname(fullname)
1103 while (root_dir != os.path.dirname(root_dir) and
1104 not os.path.exists(os.path.join(root_dir, ".git")) and
1105 not os.path.exists(os.path.join(root_dir, ".hg")) and
1106 not os.path.exists(os.path.join(root_dir, ".svn"))):
1107 root_dir = os.path.dirname(root_dir)
erg@google.com35589e62010-11-17 18:58:16 +00001108
1109 if (os.path.exists(os.path.join(root_dir, ".git")) or
erg@chromium.org7956a872011-11-30 01:44:03 +00001110 os.path.exists(os.path.join(root_dir, ".hg")) or
1111 os.path.exists(os.path.join(root_dir, ".svn"))):
erg@google.com35589e62010-11-17 18:58:16 +00001112 prefix = os.path.commonprefix([root_dir, project_dir])
1113 return fullname[len(prefix) + 1:]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001114
1115 # Don't know what to do; header guard warnings may be wrong...
1116 return fullname
1117
1118 def Split(self):
1119 """Splits the file into the directory, basename, and extension.
1120
1121 For 'chrome/browser/browser.cc', Split() would
1122 return ('chrome/browser', 'browser', '.cc')
1123
1124 Returns:
1125 A tuple of (directory, basename, extension).
1126 """
1127
1128 googlename = self.RepositoryName()
1129 project, rest = os.path.split(googlename)
1130 return (project,) + os.path.splitext(rest)
1131
1132 def BaseName(self):
1133 """File base name - text after the final slash, before the final period."""
1134 return self.Split()[1]
1135
1136 def Extension(self):
1137 """File extension - text following the final period."""
1138 return self.Split()[2]
1139
1140 def NoExtension(self):
1141 """File has no source file extension."""
1142 return '/'.join(self.Split()[0:2])
1143
1144 def IsSource(self):
1145 """File has a source file extension."""
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00001146 return _IsSourceExtension(self.Extension()[1:])
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001147
1148
erg@google.com35589e62010-11-17 18:58:16 +00001149def _ShouldPrintError(category, confidence, linenum):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00001150 """If confidence >= verbose, category passes filter and is not suppressed."""
erg@google.com35589e62010-11-17 18:58:16 +00001151
1152 # There are three ways we might decide not to print an error message:
1153 # a "NOLINT(category)" comment appears in the source,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001154 # the verbosity level isn't high enough, or the filters filter it out.
erg@google.com35589e62010-11-17 18:58:16 +00001155 if IsErrorSuppressedByNolint(category, linenum):
1156 return False
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001157
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001158 if confidence < _cpplint_state.verbose_level:
1159 return False
1160
1161 is_filtered = False
1162 for one_filter in _Filters():
1163 if one_filter.startswith('-'):
1164 if category.startswith(one_filter[1:]):
1165 is_filtered = True
1166 elif one_filter.startswith('+'):
1167 if category.startswith(one_filter[1:]):
1168 is_filtered = False
1169 else:
1170 assert False # should have been checked for in SetFilter.
1171 if is_filtered:
1172 return False
1173
1174 return True
1175
1176
1177def Error(filename, linenum, category, confidence, message):
1178 """Logs the fact we've found a lint error.
1179
1180 We log where the error was found, and also our confidence in the error,
1181 that is, how certain we are this is a legitimate style regression, and
1182 not a misidentification or a use that's sometimes justified.
1183
erg@google.com35589e62010-11-17 18:58:16 +00001184 False positives can be suppressed by the use of
1185 "cpplint(category)" comments on the offending line. These are
1186 parsed into _error_suppressions.
1187
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001188 Args:
1189 filename: The name of the file containing the error.
1190 linenum: The number of the line containing the error.
1191 category: A string used to describe the "category" this bug
1192 falls under: "whitespace", say, or "runtime". Categories
1193 may have a hierarchy separated by slashes: "whitespace/indent".
1194 confidence: A number from 1-5 representing a confidence score for
1195 the error, with 5 meaning that we are certain of the problem,
1196 and 1 meaning that it could be a legitimate construct.
1197 message: The error message.
1198 """
erg@google.com35589e62010-11-17 18:58:16 +00001199 if _ShouldPrintError(category, confidence, linenum):
erg@google.com26970fa2009-11-17 18:07:32 +00001200 _cpplint_state.IncrementErrorCount(category)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001201 if _cpplint_state.output_format == 'vs7':
Bruce Dawsonac964702022-05-27 17:08:46 +00001202 sys.stderr.write('%s(%s): (cpplint) %s [%s] [%d]\n' %
1203 (filename, linenum, message, category, confidence))
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001204 elif _cpplint_state.output_format == 'eclipse':
Bruce Dawsonac964702022-05-27 17:08:46 +00001205 sys.stderr.write('%s:%s: (cpplint) warning: %s [%s] [%d]\n' %
1206 (filename, linenum, message, category, confidence))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001207 else:
Bruce Dawsonac964702022-05-27 17:08:46 +00001208 sys.stderr.write('%s:%s: (cpplint) %s [%s] [%d]\n' %
1209 (filename, linenum, message, category, confidence))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001210
1211
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001212# Matches standard C++ escape sequences per 2.13.2.3 of the C++ standard.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001213_RE_PATTERN_CLEANSE_LINE_ESCAPES = re.compile(
1214 r'\\([abfnrtv?"\\\']|\d+|x[0-9a-fA-F]+)')
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001215# Match a single C style comment on the same line.
1216_RE_PATTERN_C_COMMENTS = r'/\*(?:[^*]|\*(?!/))*\*/'
1217# Matches multi-line C style comments.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001218# This RE is a little bit more complicated than one might expect, because we
1219# have to take care of space removals tools so we can handle comments inside
1220# statements better.
1221# The current rule is: We only clear spaces from both sides when we're at the
1222# end of the line. Otherwise, we try to remove spaces from the right side,
1223# if this doesn't work we try on left side but only if there's a non-character
1224# on the right.
1225_RE_PATTERN_CLEANSE_LINE_C_COMMENTS = re.compile(
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001226 r'(\s*' + _RE_PATTERN_C_COMMENTS + r'\s*$|' +
1227 _RE_PATTERN_C_COMMENTS + r'\s+|' +
1228 r'\s+' + _RE_PATTERN_C_COMMENTS + r'(?=\W)|' +
1229 _RE_PATTERN_C_COMMENTS + r')')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001230
1231
1232def IsCppString(line):
1233 """Does line terminate so, that the next symbol is in string constant.
1234
1235 This function does not consider single-line nor multi-line comments.
1236
1237 Args:
1238 line: is a partial line of code starting from the 0..n.
1239
1240 Returns:
1241 True, if next character appended to 'line' is inside a
1242 string constant.
1243 """
1244
1245 line = line.replace(r'\\', 'XX') # after this, \\" does not match to \"
1246 return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1
1247
1248
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001249def CleanseRawStrings(raw_lines):
1250 """Removes C++11 raw strings from lines.
1251
1252 Before:
1253 static const char kData[] = R"(
1254 multi-line string
1255 )";
1256
1257 After:
1258 static const char kData[] = ""
1259 (replaced by blank line)
1260 "";
1261
1262 Args:
1263 raw_lines: list of raw lines.
1264
1265 Returns:
1266 list of lines with C++11 raw strings replaced by empty strings.
1267 """
1268
1269 delimiter = None
1270 lines_without_raw_strings = []
1271 for line in raw_lines:
1272 if delimiter:
1273 # Inside a raw string, look for the end
1274 end = line.find(delimiter)
1275 if end >= 0:
1276 # Found the end of the string, match leading space for this
1277 # line and resume copying the original lines, and also insert
1278 # a "" on the last line.
1279 leading_space = Match(r'^(\s*)\S', line)
1280 line = leading_space.group(1) + '""' + line[end + len(delimiter):]
1281 delimiter = None
1282 else:
1283 # Haven't found the end yet, append a blank line.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001284 line = '""'
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001285
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001286 # Look for beginning of a raw string, and replace them with
1287 # empty strings. This is done in a loop to handle multiple raw
1288 # strings on the same line.
1289 while delimiter is None:
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001290 # Look for beginning of a raw string.
1291 # See 2.14.15 [lex.string] for syntax.
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00001292 #
1293 # Once we have matched a raw string, we check the prefix of the
1294 # line to make sure that the line is not part of a single line
1295 # comment. It's done this way because we remove raw strings
1296 # before removing comments as opposed to removing comments
1297 # before removing raw strings. This is because there are some
1298 # cpplint checks that requires the comments to be preserved, but
1299 # we don't want to check comments that are inside raw strings.
1300 matched = Match(r'^(.*?)\b(?:R|u8R|uR|UR|LR)"([^\s\\()]*)\((.*)$', line)
1301 if (matched and
1302 not Match(r'^([^\'"]|\'(\\.|[^\'])*\'|"(\\.|[^"])*")*//',
1303 matched.group(1))):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001304 delimiter = ')' + matched.group(2) + '"'
1305
1306 end = matched.group(3).find(delimiter)
1307 if end >= 0:
1308 # Raw string ended on same line
1309 line = (matched.group(1) + '""' +
1310 matched.group(3)[end + len(delimiter):])
1311 delimiter = None
1312 else:
1313 # Start of a multi-line raw string
1314 line = matched.group(1) + '""'
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001315 else:
1316 break
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001317
1318 lines_without_raw_strings.append(line)
1319
1320 # TODO(unknown): if delimiter is not None here, we might want to
1321 # emit a warning for unterminated string.
1322 return lines_without_raw_strings
1323
1324
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001325def FindNextMultiLineCommentStart(lines, lineix):
1326 """Find the beginning marker for a multiline comment."""
1327 while lineix < len(lines):
1328 if lines[lineix].strip().startswith('/*'):
1329 # Only return this marker if the comment goes beyond this line
1330 if lines[lineix].strip().find('*/', 2) < 0:
1331 return lineix
1332 lineix += 1
1333 return len(lines)
1334
1335
1336def FindNextMultiLineCommentEnd(lines, lineix):
1337 """We are inside a comment, find the end marker."""
1338 while lineix < len(lines):
1339 if lines[lineix].strip().endswith('*/'):
1340 return lineix
1341 lineix += 1
1342 return len(lines)
1343
1344
1345def RemoveMultiLineCommentsFromRange(lines, begin, end):
1346 """Clears a range of lines for multi-line comments."""
1347 # Having // dummy comments makes the lines non-empty, so we will not get
1348 # unnecessary blank line warnings later in the code.
1349 for i in range(begin, end):
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001350 lines[i] = '/**/'
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001351
1352
1353def RemoveMultiLineComments(filename, lines, error):
1354 """Removes multiline (c-style) comments from lines."""
1355 lineix = 0
1356 while lineix < len(lines):
1357 lineix_begin = FindNextMultiLineCommentStart(lines, lineix)
1358 if lineix_begin >= len(lines):
1359 return
1360 lineix_end = FindNextMultiLineCommentEnd(lines, lineix_begin)
1361 if lineix_end >= len(lines):
1362 error(filename, lineix_begin + 1, 'readability/multiline_comment', 5,
1363 'Could not find end of multi-line comment')
1364 return
1365 RemoveMultiLineCommentsFromRange(lines, lineix_begin, lineix_end + 1)
1366 lineix = lineix_end + 1
1367
1368
1369def CleanseComments(line):
1370 """Removes //-comments and single-line C-style /* */ comments.
1371
1372 Args:
1373 line: A line of C++ source.
1374
1375 Returns:
1376 The line with single-line comments removed.
1377 """
1378 commentpos = line.find('//')
1379 if commentpos != -1 and not IsCppString(line[:commentpos]):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00001380 line = line[:commentpos].rstrip()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001381 # get rid of /* ... */
1382 return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line)
1383
1384
erg@google.com6317a9c2009-06-25 00:28:19 +00001385class CleansedLines(object):
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001386 """Holds 4 copies of all lines with different preprocessing applied to them.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001387
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001388 1) elided member contains lines without strings and comments.
1389 2) lines member contains lines without comments.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001390 3) raw_lines member contains all the lines without processing.
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001391 4) lines_without_raw_strings member is same as raw_lines, but with C++11 raw
1392 strings removed.
1393 All these members are of <type 'list'>, and of the same length.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001394 """
1395
1396 def __init__(self, lines):
1397 self.elided = []
1398 self.lines = []
1399 self.raw_lines = lines
1400 self.num_lines = len(lines)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001401 self.lines_without_raw_strings = CleanseRawStrings(lines)
1402 for linenum in range(len(self.lines_without_raw_strings)):
1403 self.lines.append(CleanseComments(
1404 self.lines_without_raw_strings[linenum]))
1405 elided = self._CollapseStrings(self.lines_without_raw_strings[linenum])
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001406 self.elided.append(CleanseComments(elided))
1407
1408 def NumLines(self):
1409 """Returns the number of lines represented."""
1410 return self.num_lines
1411
1412 @staticmethod
1413 def _CollapseStrings(elided):
1414 """Collapses strings and chars on a line to simple "" or '' blocks.
1415
1416 We nix strings first so we're not fooled by text like '"http://"'
1417
1418 Args:
1419 elided: The line being processed.
1420
1421 Returns:
1422 The line with collapsed strings.
1423 """
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001424 if _RE_PATTERN_INCLUDE.match(elided):
1425 return elided
1426
1427 # Remove escaped characters first to make quote/single quote collapsing
1428 # basic. Things that look like escaped characters shouldn't occur
1429 # outside of strings and chars.
1430 elided = _RE_PATTERN_CLEANSE_LINE_ESCAPES.sub('', elided)
1431
1432 # Replace quoted strings and digit separators. Both single quotes
1433 # and double quotes are processed in the same loop, otherwise
1434 # nested quotes wouldn't work.
1435 collapsed = ''
1436 while True:
1437 # Find the first quote character
1438 match = Match(r'^([^\'"]*)([\'"])(.*)$', elided)
1439 if not match:
1440 collapsed += elided
1441 break
1442 head, quote, tail = match.groups()
1443
1444 if quote == '"':
1445 # Collapse double quoted strings
1446 second_quote = tail.find('"')
1447 if second_quote >= 0:
1448 collapsed += head + '""'
1449 elided = tail[second_quote + 1:]
1450 else:
1451 # Unmatched double quote, don't bother processing the rest
1452 # of the line since this is probably a multiline string.
1453 collapsed += elided
1454 break
1455 else:
1456 # Found single quote, check nearby text to eliminate digit separators.
1457 #
1458 # There is no special handling for floating point here, because
1459 # the integer/fractional/exponent parts would all be parsed
1460 # correctly as long as there are digits on both sides of the
1461 # separator. So we are fine as long as we don't see something
1462 # like "0.'3" (gcc 4.9.0 will not allow this literal).
1463 if Search(r'\b(?:0[bBxX]?|[1-9])[0-9a-fA-F]*$', head):
1464 match_literal = Match(r'^((?:\'?[0-9a-zA-Z_])*)(.*)$', "'" + tail)
1465 collapsed += head + match_literal.group(1).replace("'", '')
1466 elided = match_literal.group(2)
1467 else:
1468 second_quote = tail.find('\'')
1469 if second_quote >= 0:
1470 collapsed += head + "''"
1471 elided = tail[second_quote + 1:]
1472 else:
1473 # Unmatched single quote
1474 collapsed += elided
1475 break
1476
1477 return collapsed
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001478
1479
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001480def FindEndOfExpressionInLine(line, startpos, stack):
1481 """Find the position just after the end of current parenthesized expression.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001482
1483 Args:
1484 line: a CleansedLines line.
1485 startpos: start searching at this position.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001486 stack: nesting stack at startpos.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001487
1488 Returns:
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001489 On finding matching end: (index just after matching end, None)
1490 On finding an unclosed expression: (-1, None)
1491 Otherwise: (-1, new stack at end of this line)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001492 """
Edward Lemur6d31ed52019-12-02 23:00:00 +00001493 for i in range(startpos, len(line)):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001494 char = line[i]
1495 if char in '([{':
1496 # Found start of parenthesized expression, push to expression stack
1497 stack.append(char)
1498 elif char == '<':
1499 # Found potential start of template argument list
1500 if i > 0 and line[i - 1] == '<':
1501 # Left shift operator
1502 if stack and stack[-1] == '<':
1503 stack.pop()
1504 if not stack:
1505 return (-1, None)
1506 elif i > 0 and Search(r'\boperator\s*$', line[0:i]):
1507 # operator<, don't add to stack
1508 continue
1509 else:
1510 # Tentative start of template argument list
1511 stack.append('<')
1512 elif char in ')]}':
1513 # Found end of parenthesized expression.
1514 #
1515 # If we are currently expecting a matching '>', the pending '<'
1516 # must have been an operator. Remove them from expression stack.
1517 while stack and stack[-1] == '<':
1518 stack.pop()
1519 if not stack:
1520 return (-1, None)
1521 if ((stack[-1] == '(' and char == ')') or
1522 (stack[-1] == '[' and char == ']') or
1523 (stack[-1] == '{' and char == '}')):
1524 stack.pop()
1525 if not stack:
1526 return (i + 1, None)
1527 else:
1528 # Mismatched parentheses
1529 return (-1, None)
1530 elif char == '>':
1531 # Found potential end of template argument list.
1532
1533 # Ignore "->" and operator functions
1534 if (i > 0 and
1535 (line[i - 1] == '-' or Search(r'\boperator\s*$', line[0:i - 1]))):
1536 continue
1537
1538 # Pop the stack if there is a matching '<'. Otherwise, ignore
1539 # this '>' since it must be an operator.
1540 if stack:
1541 if stack[-1] == '<':
1542 stack.pop()
1543 if not stack:
1544 return (i + 1, None)
1545 elif char == ';':
1546 # Found something that look like end of statements. If we are currently
1547 # expecting a '>', the matching '<' must have been an operator, since
1548 # template argument list should not contain statements.
1549 while stack and stack[-1] == '<':
1550 stack.pop()
1551 if not stack:
1552 return (-1, None)
1553
1554 # Did not find end of expression or unbalanced parentheses on this line
1555 return (-1, stack)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001556
1557
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001558def CloseExpression(clean_lines, linenum, pos):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001559 """If input points to ( or { or [ or <, finds the position that closes it.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001560
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001561 If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001562 linenum/pos that correspond to the closing of the expression.
1563
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001564 TODO(unknown): cpplint spends a fair bit of time matching parentheses.
1565 Ideally we would want to index all opening and closing parentheses once
1566 and have CloseExpression be just a simple lookup, but due to preprocessor
1567 tricks, this is not so easy.
1568
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001569 Args:
1570 clean_lines: A CleansedLines instance containing the file.
1571 linenum: The number of the line to check.
1572 pos: A position on the line.
1573
1574 Returns:
1575 A tuple (line, linenum, pos) pointer *past* the closing brace, or
1576 (line, len(lines), -1) if we never find a close. Note we ignore
1577 strings and comments when matching; and the line we return is the
1578 'cleansed' line at linenum.
1579 """
1580
1581 line = clean_lines.elided[linenum]
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001582 if (line[pos] not in '({[<') or Match(r'<[<=]', line[pos:]):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001583 return (line, clean_lines.NumLines(), -1)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001584
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001585 # Check first line
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001586 (end_pos, stack) = FindEndOfExpressionInLine(line, pos, [])
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001587 if end_pos > -1:
1588 return (line, linenum, end_pos)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001589
1590 # Continue scanning forward
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001591 while stack and linenum < clean_lines.NumLines() - 1:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001592 linenum += 1
1593 line = clean_lines.elided[linenum]
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001594 (end_pos, stack) = FindEndOfExpressionInLine(line, 0, stack)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001595 if end_pos > -1:
1596 return (line, linenum, end_pos)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001597
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001598 # Did not find end of expression before end of file, give up
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001599 return (line, clean_lines.NumLines(), -1)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001600
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001601
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001602def FindStartOfExpressionInLine(line, endpos, stack):
1603 """Find position at the matching start of current expression.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001604
1605 This is almost the reverse of FindEndOfExpressionInLine, but note
1606 that the input position and returned position differs by 1.
1607
1608 Args:
1609 line: a CleansedLines line.
1610 endpos: start searching at this position.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001611 stack: nesting stack at endpos.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001612
1613 Returns:
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001614 On finding matching start: (index at matching start, None)
1615 On finding an unclosed expression: (-1, None)
1616 Otherwise: (-1, new stack at beginning of this line)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001617 """
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001618 i = endpos
1619 while i >= 0:
1620 char = line[i]
1621 if char in ')]}':
1622 # Found end of expression, push to expression stack
1623 stack.append(char)
1624 elif char == '>':
1625 # Found potential end of template argument list.
1626 #
1627 # Ignore it if it's a "->" or ">=" or "operator>"
1628 if (i > 0 and
1629 (line[i - 1] == '-' or
1630 Match(r'\s>=\s', line[i - 1:]) or
1631 Search(r'\boperator\s*$', line[0:i]))):
1632 i -= 1
1633 else:
1634 stack.append('>')
1635 elif char == '<':
1636 # Found potential start of template argument list
1637 if i > 0 and line[i - 1] == '<':
1638 # Left shift operator
1639 i -= 1
1640 else:
1641 # If there is a matching '>', we can pop the expression stack.
1642 # Otherwise, ignore this '<' since it must be an operator.
1643 if stack and stack[-1] == '>':
1644 stack.pop()
1645 if not stack:
1646 return (i, None)
1647 elif char in '([{':
1648 # Found start of expression.
1649 #
1650 # If there are any unmatched '>' on the stack, they must be
1651 # operators. Remove those.
1652 while stack and stack[-1] == '>':
1653 stack.pop()
1654 if not stack:
1655 return (-1, None)
1656 if ((char == '(' and stack[-1] == ')') or
1657 (char == '[' and stack[-1] == ']') or
1658 (char == '{' and stack[-1] == '}')):
1659 stack.pop()
1660 if not stack:
1661 return (i, None)
1662 else:
1663 # Mismatched parentheses
1664 return (-1, None)
1665 elif char == ';':
1666 # Found something that look like end of statements. If we are currently
1667 # expecting a '<', the matching '>' must have been an operator, since
1668 # template argument list should not contain statements.
1669 while stack and stack[-1] == '>':
1670 stack.pop()
1671 if not stack:
1672 return (-1, None)
1673
1674 i -= 1
1675
1676 return (-1, stack)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001677
1678
1679def ReverseCloseExpression(clean_lines, linenum, pos):
1680 """If input points to ) or } or ] or >, finds the position that opens it.
1681
1682 If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the
1683 linenum/pos that correspond to the opening of the expression.
1684
1685 Args:
1686 clean_lines: A CleansedLines instance containing the file.
1687 linenum: The number of the line to check.
1688 pos: A position on the line.
1689
1690 Returns:
1691 A tuple (line, linenum, pos) pointer *at* the opening brace, or
1692 (line, 0, -1) if we never find the matching opening brace. Note
1693 we ignore strings and comments when matching; and the line we
1694 return is the 'cleansed' line at linenum.
1695 """
1696 line = clean_lines.elided[linenum]
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001697 if line[pos] not in ')}]>':
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001698 return (line, 0, -1)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001699
1700 # Check last line
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001701 (start_pos, stack) = FindStartOfExpressionInLine(line, pos, [])
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001702 if start_pos > -1:
1703 return (line, linenum, start_pos)
1704
1705 # Continue scanning backward
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001706 while stack and linenum > 0:
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001707 linenum -= 1
1708 line = clean_lines.elided[linenum]
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001709 (start_pos, stack) = FindStartOfExpressionInLine(line, len(line) - 1, stack)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001710 if start_pos > -1:
1711 return (line, linenum, start_pos)
1712
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001713 # Did not find start of expression before beginning of file, give up
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001714 return (line, 0, -1)
1715
1716
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001717def CheckForCopyright(filename, lines, error):
1718 """Logs an error if no Copyright message appears at the top of the file."""
1719
1720 # We'll say it should occur by line 10. Don't forget there's a
1721 # dummy line at the front.
Edward Lemur6d31ed52019-12-02 23:00:00 +00001722 for line in range(1, min(len(lines), 11)):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001723 if re.search(r'Copyright', lines[line], re.I): break
1724 else: # means no copyright line was found
1725 error(filename, 0, 'legal/copyright', 5,
1726 'No copyright message found. '
1727 'You should have a line: "Copyright [year] <Copyright Owner>"')
1728
1729
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001730def GetIndentLevel(line):
1731 """Return the number of leading spaces in line.
1732
1733 Args:
1734 line: A string to check.
1735
1736 Returns:
1737 An integer count of leading spaces, possibly zero.
1738 """
1739 indent = Match(r'^( *)\S', line)
1740 if indent:
1741 return len(indent.group(1))
1742 else:
1743 return 0
1744
1745
David Sanders2f988472022-05-21 01:35:11 +00001746def PathSplitToList(path):
1747 """Returns the path split into a list by the separator.
1748
1749 Args:
1750 path: An absolute or relative path (e.g. '/a/b/c/' or '../a')
1751
1752 Returns:
1753 A list of path components (e.g. ['a', 'b', 'c]).
1754 """
1755 lst = []
1756 while True:
1757 (head, tail) = os.path.split(path)
1758 if head == path: # absolute paths end
1759 lst.append(head)
1760 break
1761 if tail == path: # relative paths end
1762 lst.append(tail)
1763 break
1764
1765 path = head
1766 lst.append(tail)
1767
1768 lst.reverse()
1769 return lst
1770
1771
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001772def GetHeaderGuardCPPVariable(filename):
1773 """Returns the CPP variable that should be used as a header guard.
1774
1775 Args:
1776 filename: The name of a C++ header file.
1777
1778 Returns:
1779 The CPP variable that should be used as a header guard in the
1780 named file.
1781
1782 """
1783
erg@google.com35589e62010-11-17 18:58:16 +00001784 # Restores original filename in case that cpplint is invoked from Emacs's
1785 # flymake.
1786 filename = re.sub(r'_flymake\.h$', '.h', filename)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001787 filename = re.sub(r'/\.flymake/([^/]*)$', r'/\1', filename)
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001788 # Replace 'c++' with 'cpp'.
1789 filename = filename.replace('C++', 'cpp').replace('c++', 'cpp')
skym@chromium.org3990c412016-02-05 20:55:12 +00001790
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001791 fileinfo = FileInfo(filename)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001792 file_path_from_root = fileinfo.RepositoryName()
David Sanders2f988472022-05-21 01:35:11 +00001793
1794 def FixupPathFromRoot():
1795 if _root_debug:
1796 sys.stderr.write("\n_root fixup, _root = '%s', repository name = '%s'\n"
1797 % (_root, fileinfo.RepositoryName()))
1798
1799 # Process the file path with the --root flag if it was set.
1800 if not _root:
1801 if _root_debug:
1802 sys.stderr.write("_root unspecified\n")
1803 return file_path_from_root
1804
1805 def StripListPrefix(lst, prefix):
1806 # f(['x', 'y'], ['w, z']) -> None (not a valid prefix)
1807 if lst[:len(prefix)] != prefix:
1808 return None
1809 # f(['a, 'b', 'c', 'd'], ['a', 'b']) -> ['c', 'd']
1810 return lst[(len(prefix)):]
1811
1812 # root behavior:
1813 # --root=subdir , lstrips subdir from the header guard
1814 maybe_path = StripListPrefix(PathSplitToList(file_path_from_root),
1815 PathSplitToList(_root))
1816
1817 if _root_debug:
1818 sys.stderr.write(("_root lstrip (maybe_path=%s, file_path_from_root=%s," +
1819 " _root=%s)\n") % (maybe_path, file_path_from_root, _root))
1820
1821 if maybe_path:
1822 return os.path.join(*maybe_path)
1823
1824 # --root=.. , will prepend the outer directory to the header guard
1825 full_path = fileinfo.FullName()
1826 # adapt slashes for windows
1827 root_abspath = os.path.abspath(_root).replace('\\', '/')
1828
1829 maybe_path = StripListPrefix(PathSplitToList(full_path),
1830 PathSplitToList(root_abspath))
1831
1832 if _root_debug:
1833 sys.stderr.write(("_root prepend (maybe_path=%s, full_path=%s, " +
1834 "root_abspath=%s)\n") % (maybe_path, full_path, root_abspath))
1835
1836 if maybe_path:
1837 return os.path.join(*maybe_path)
1838
1839 if _root_debug:
1840 sys.stderr.write("_root ignore, returning %s\n" % (file_path_from_root))
1841
1842 # --root=FAKE_DIR is ignored
1843 return file_path_from_root
1844
1845 file_path_from_root = FixupPathFromRoot()
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001846 return re.sub(r'[^a-zA-Z0-9]', '_', file_path_from_root).upper() + '_'
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001847
1848
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001849def CheckForHeaderGuard(filename, clean_lines, error):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001850 """Checks that the file contains a header guard.
1851
erg@google.com6317a9c2009-06-25 00:28:19 +00001852 Logs an error if no #ifndef header guard is present. For other
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001853 headers, checks that the full pathname is used.
1854
1855 Args:
1856 filename: The name of the C++ header file.
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001857 clean_lines: A CleansedLines instance containing the file.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001858 error: The function to call with any errors found.
1859 """
1860
avakulenko@google.com59146752014-08-11 20:20:55 +00001861 # Don't check for header guards if there are error suppression
1862 # comments somewhere in this file.
1863 #
1864 # Because this is silencing a warning for a nonexistent line, we
1865 # only support the very specific NOLINT(build/header_guard) syntax,
1866 # and not the general NOLINT or NOLINT(*) syntax.
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001867 raw_lines = clean_lines.lines_without_raw_strings
1868 for i in raw_lines:
avakulenko@google.com59146752014-08-11 20:20:55 +00001869 if Search(r'//\s*NOLINT\(build/header_guard\)', i):
1870 return
1871
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001872 cppvar = GetHeaderGuardCPPVariable(filename)
1873
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001874 ifndef = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001875 ifndef_linenum = 0
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001876 define = ''
1877 endif = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001878 endif_linenum = 0
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001879 for linenum, line in enumerate(raw_lines):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001880 linesplit = line.split()
1881 if len(linesplit) >= 2:
1882 # find the first occurrence of #ifndef and #define, save arg
1883 if not ifndef and linesplit[0] == '#ifndef':
1884 # set ifndef to the header guard presented on the #ifndef line.
1885 ifndef = linesplit[1]
1886 ifndef_linenum = linenum
1887 if not define and linesplit[0] == '#define':
1888 define = linesplit[1]
1889 # find the last occurrence of #endif, save entire line
1890 if line.startswith('#endif'):
1891 endif = line
1892 endif_linenum = linenum
1893
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001894 if not ifndef or not define or ifndef != define:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001895 error(filename, 0, 'build/header_guard', 5,
1896 'No #ifndef header guard found, suggested CPP variable is: %s' %
1897 cppvar)
1898 return
1899
1900 # The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__
1901 # for backward compatibility.
erg@google.com35589e62010-11-17 18:58:16 +00001902 if ifndef != cppvar:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001903 error_level = 0
1904 if ifndef != cppvar + '_':
1905 error_level = 5
1906
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001907 ParseNolintSuppressions(filename, raw_lines[ifndef_linenum], ifndef_linenum,
erg@google.com35589e62010-11-17 18:58:16 +00001908 error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001909 error(filename, ifndef_linenum, 'build/header_guard', error_level,
1910 '#ifndef header guard has wrong style, please use: %s' % cppvar)
1911
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001912 # Check for "//" comments on endif line.
1913 ParseNolintSuppressions(filename, raw_lines[endif_linenum], endif_linenum,
1914 error)
1915 match = Match(r'#endif\s*//\s*' + cppvar + r'(_)?\b', endif)
1916 if match:
1917 if match.group(1) == '_':
1918 # Issue low severity warning for deprecated double trailing underscore
1919 error(filename, endif_linenum, 'build/header_guard', 0,
1920 '#endif line should be "#endif // %s"' % cppvar)
erg@chromium.orgc452fea2012-01-26 21:10:45 +00001921 return
1922
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001923 # Didn't find the corresponding "//" comment. If this file does not
1924 # contain any "//" comments at all, it could be that the compiler
1925 # only wants "/**/" comments, look for those instead.
1926 no_single_line_comments = True
Edward Lemur6d31ed52019-12-02 23:00:00 +00001927 for i in range(1, len(raw_lines) - 1):
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001928 line = raw_lines[i]
1929 if Match(r'^(?:(?:\'(?:\.|[^\'])*\')|(?:"(?:\.|[^"])*")|[^\'"])*//', line):
1930 no_single_line_comments = False
1931 break
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001932
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001933 if no_single_line_comments:
1934 match = Match(r'#endif\s*/\*\s*' + cppvar + r'(_)?\s*\*/', endif)
1935 if match:
1936 if match.group(1) == '_':
1937 # Low severity warning for double trailing underscore
1938 error(filename, endif_linenum, 'build/header_guard', 0,
1939 '#endif line should be "#endif /* %s */"' % cppvar)
1940 return
1941
1942 # Didn't find anything
1943 error(filename, endif_linenum, 'build/header_guard', 5,
1944 '#endif line should be "#endif // %s"' % cppvar)
1945
1946
1947def CheckHeaderFileIncluded(filename, include_state, error):
1948 """Logs an error if a .cc file does not include its header."""
1949
1950 # Do not check test files
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00001951 fileinfo = FileInfo(filename)
1952 if Search(_TEST_FILE_SUFFIX, fileinfo.BaseName()):
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001953 return
1954
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00001955 headerfile = filename[0:len(filename) - len(fileinfo.Extension())] + '.h'
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001956 if not os.path.exists(headerfile):
1957 return
1958 headername = FileInfo(headerfile).RepositoryName()
1959 first_include = 0
1960 for section_list in include_state.include_list:
1961 for f in section_list:
1962 if headername in f[0] or f[0] in headername:
1963 return
1964 if not first_include:
1965 first_include = f[1]
1966
1967 error(filename, first_include, 'build/include', 5,
1968 '%s should include its header file %s' % (fileinfo.RepositoryName(),
1969 headername))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001970
1971
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001972def CheckForBadCharacters(filename, lines, error):
1973 """Logs an error for each line containing bad characters.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001974
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001975 Two kinds of bad characters:
1976
1977 1. Unicode replacement characters: These indicate that either the file
1978 contained invalid UTF-8 (likely) or Unicode replacement characters (which
1979 it shouldn't). Note that it's possible for this to throw off line
1980 numbering if the invalid UTF-8 occurred adjacent to a newline.
1981
1982 2. NUL bytes. These are problematic for some tools.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001983
1984 Args:
1985 filename: The name of the current file.
1986 lines: An array of strings, each representing a line of the file.
1987 error: The function to call with any errors found.
1988 """
1989 for linenum, line in enumerate(lines):
1990 if u'\ufffd' in line:
1991 error(filename, linenum, 'readability/utf8', 5,
1992 'Line contains invalid UTF-8 (or Unicode replacement character).')
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001993 if '\0' in line:
1994 error(filename, linenum, 'readability/nul', 5, 'Line contains NUL byte.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001995
1996
1997def CheckForNewlineAtEOF(filename, lines, error):
1998 """Logs an error if there is no newline char at the end of the file.
1999
2000 Args:
2001 filename: The name of the current file.
2002 lines: An array of strings, each representing a line of the file.
2003 error: The function to call with any errors found.
2004 """
2005
2006 # The array lines() was created by adding two newlines to the
2007 # original file (go figure), then splitting on \n.
2008 # To verify that the file ends in \n, we just have to make sure the
2009 # last-but-two element of lines() exists and is empty.
2010 if len(lines) < 3 or lines[-2]:
2011 error(filename, len(lines) - 2, 'whitespace/ending_newline', 5,
2012 'Could not find a newline character at the end of the file.')
2013
2014
2015def CheckForMultilineCommentsAndStrings(filename, clean_lines, linenum, error):
2016 """Logs an error if we see /* ... */ or "..." that extend past one line.
2017
2018 /* ... */ comments are legit inside macros, for one line.
2019 Otherwise, we prefer // comments, so it's ok to warn about the
2020 other. Likewise, it's ok for strings to extend across multiple
2021 lines, as long as a line continuation character (backslash)
2022 terminates each line. Although not currently prohibited by the C++
2023 style guide, it's ugly and unnecessary. We don't do well with either
2024 in this lint program, so we warn about both.
2025
2026 Args:
2027 filename: The name of the current file.
2028 clean_lines: A CleansedLines instance containing the file.
2029 linenum: The number of the line to check.
2030 error: The function to call with any errors found.
2031 """
2032 line = clean_lines.elided[linenum]
2033
2034 # Remove all \\ (escaped backslashes) from the line. They are OK, and the
2035 # second (escaped) slash may trigger later \" detection erroneously.
2036 line = line.replace('\\\\', '')
2037
2038 if line.count('/*') > line.count('*/'):
2039 error(filename, linenum, 'readability/multiline_comment', 5,
2040 'Complex multi-line /*...*/-style comment found. '
2041 'Lint may give bogus warnings. '
2042 'Consider replacing these with //-style comments, '
2043 'with #if 0...#endif, '
2044 'or with more clearly structured multi-line comments.')
2045
2046 if (line.count('"') - line.count('\\"')) % 2:
2047 error(filename, linenum, 'readability/multiline_string', 5,
2048 'Multi-line string ("...") found. This lint script doesn\'t '
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002049 'do well with such strings, and may give bogus warnings. '
2050 'Use C++11 raw strings or concatenation instead.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002051
2052
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002053# (non-threadsafe name, thread-safe alternative, validation pattern)
2054#
2055# The validation pattern is used to eliminate false positives such as:
2056# _rand(); // false positive due to substring match.
2057# ->rand(); // some member function rand().
2058# ACMRandom rand(seed); // some variable named rand.
2059# ISAACRandom rand(); // another variable named rand.
2060#
2061# Basically we require the return value of these functions to be used
2062# in some expression context on the same line by matching on some
2063# operator before the function name. This eliminates constructors and
2064# member function calls.
2065_UNSAFE_FUNC_PREFIX = r'(?:[-+*/=%^&|(<]\s*|>\s+)'
2066_THREADING_LIST = (
2067 ('asctime(', 'asctime_r(', _UNSAFE_FUNC_PREFIX + r'asctime\([^)]+\)'),
2068 ('ctime(', 'ctime_r(', _UNSAFE_FUNC_PREFIX + r'ctime\([^)]+\)'),
2069 ('getgrgid(', 'getgrgid_r(', _UNSAFE_FUNC_PREFIX + r'getgrgid\([^)]+\)'),
2070 ('getgrnam(', 'getgrnam_r(', _UNSAFE_FUNC_PREFIX + r'getgrnam\([^)]+\)'),
2071 ('getlogin(', 'getlogin_r(', _UNSAFE_FUNC_PREFIX + r'getlogin\(\)'),
2072 ('getpwnam(', 'getpwnam_r(', _UNSAFE_FUNC_PREFIX + r'getpwnam\([^)]+\)'),
2073 ('getpwuid(', 'getpwuid_r(', _UNSAFE_FUNC_PREFIX + r'getpwuid\([^)]+\)'),
2074 ('gmtime(', 'gmtime_r(', _UNSAFE_FUNC_PREFIX + r'gmtime\([^)]+\)'),
2075 ('localtime(', 'localtime_r(', _UNSAFE_FUNC_PREFIX + r'localtime\([^)]+\)'),
2076 ('rand(', 'rand_r(', _UNSAFE_FUNC_PREFIX + r'rand\(\)'),
2077 ('strtok(', 'strtok_r(',
2078 _UNSAFE_FUNC_PREFIX + r'strtok\([^)]+\)'),
2079 ('ttyname(', 'ttyname_r(', _UNSAFE_FUNC_PREFIX + r'ttyname\([^)]+\)'),
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002080 )
2081
2082
2083def CheckPosixThreading(filename, clean_lines, linenum, error):
2084 """Checks for calls to thread-unsafe functions.
2085
2086 Much code has been originally written without consideration of
2087 multi-threading. Also, engineers are relying on their old experience;
2088 they have learned posix before threading extensions were added. These
2089 tests guide the engineers to use thread-safe functions (when using
2090 posix directly).
2091
2092 Args:
2093 filename: The name of the current file.
2094 clean_lines: A CleansedLines instance containing the file.
2095 linenum: The number of the line to check.
2096 error: The function to call with any errors found.
2097 """
2098 line = clean_lines.elided[linenum]
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002099 for single_thread_func, multithread_safe_func, pattern in _THREADING_LIST:
2100 # Additional pattern matching check to confirm that this is the
2101 # function we are looking for
2102 if Search(pattern, line):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002103 error(filename, linenum, 'runtime/threadsafe_fn', 2,
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002104 'Consider using ' + multithread_safe_func +
2105 '...) instead of ' + single_thread_func +
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002106 '...) for improved thread safety.')
2107
2108
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002109def CheckVlogArguments(filename, clean_lines, linenum, error):
2110 """Checks that VLOG() is only used for defining a logging level.
2111
2112 For example, VLOG(2) is correct. VLOG(INFO), VLOG(WARNING), VLOG(ERROR), and
2113 VLOG(FATAL) are not.
2114
2115 Args:
2116 filename: The name of the current file.
2117 clean_lines: A CleansedLines instance containing the file.
2118 linenum: The number of the line to check.
2119 error: The function to call with any errors found.
2120 """
2121 line = clean_lines.elided[linenum]
2122 if Search(r'\bVLOG\((INFO|ERROR|WARNING|DFATAL|FATAL)\)', line):
2123 error(filename, linenum, 'runtime/vlog', 5,
2124 'VLOG() should be used with numeric verbosity level. '
2125 'Use LOG() if you want symbolic severity levels.')
2126
erg@google.com26970fa2009-11-17 18:07:32 +00002127# Matches invalid increment: *count++, which moves pointer instead of
erg@google.com6317a9c2009-06-25 00:28:19 +00002128# incrementing a value.
erg@google.com26970fa2009-11-17 18:07:32 +00002129_RE_PATTERN_INVALID_INCREMENT = re.compile(
erg@google.com6317a9c2009-06-25 00:28:19 +00002130 r'^\s*\*\w+(\+\+|--);')
2131
2132
2133def CheckInvalidIncrement(filename, clean_lines, linenum, error):
erg@google.com26970fa2009-11-17 18:07:32 +00002134 """Checks for invalid increment *count++.
erg@google.com6317a9c2009-06-25 00:28:19 +00002135
2136 For example following function:
2137 void increment_counter(int* count) {
2138 *count++;
2139 }
2140 is invalid, because it effectively does count++, moving pointer, and should
2141 be replaced with ++*count, (*count)++ or *count += 1.
2142
2143 Args:
2144 filename: The name of the current file.
2145 clean_lines: A CleansedLines instance containing the file.
2146 linenum: The number of the line to check.
2147 error: The function to call with any errors found.
2148 """
2149 line = clean_lines.elided[linenum]
erg@google.com26970fa2009-11-17 18:07:32 +00002150 if _RE_PATTERN_INVALID_INCREMENT.match(line):
erg@google.com6317a9c2009-06-25 00:28:19 +00002151 error(filename, linenum, 'runtime/invalid_increment', 5,
2152 'Changing pointer instead of value (or unused value of operator*).')
2153
2154
avakulenko@google.com59146752014-08-11 20:20:55 +00002155def IsMacroDefinition(clean_lines, linenum):
2156 if Search(r'^#define', clean_lines[linenum]):
2157 return True
2158
2159 if linenum > 0 and Search(r'\\$', clean_lines[linenum - 1]):
2160 return True
2161
2162 return False
2163
2164
2165def IsForwardClassDeclaration(clean_lines, linenum):
2166 return Match(r'^\s*(\btemplate\b)*.*class\s+\w+;\s*$', clean_lines[linenum])
2167
2168
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002169class _BlockInfo(object):
2170 """Stores information about a generic block of code."""
2171
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002172 def __init__(self, linenum, seen_open_brace):
2173 self.starting_linenum = linenum
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002174 self.seen_open_brace = seen_open_brace
2175 self.open_parentheses = 0
2176 self.inline_asm = _NO_ASM
avakulenko@google.com59146752014-08-11 20:20:55 +00002177 self.check_namespace_indentation = False
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002178
2179 def CheckBegin(self, filename, clean_lines, linenum, error):
2180 """Run checks that applies to text up to the opening brace.
2181
2182 This is mostly for checking the text after the class identifier
2183 and the "{", usually where the base class is specified. For other
2184 blocks, there isn't much to check, so we always pass.
2185
2186 Args:
2187 filename: The name of the current file.
2188 clean_lines: A CleansedLines instance containing the file.
2189 linenum: The number of the line to check.
2190 error: The function to call with any errors found.
2191 """
2192 pass
2193
2194 def CheckEnd(self, filename, clean_lines, linenum, error):
2195 """Run checks that applies to text after the closing brace.
2196
2197 This is mostly used for checking end of namespace comments.
2198
2199 Args:
2200 filename: The name of the current file.
2201 clean_lines: A CleansedLines instance containing the file.
2202 linenum: The number of the line to check.
2203 error: The function to call with any errors found.
2204 """
2205 pass
2206
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002207 def IsBlockInfo(self):
2208 """Returns true if this block is a _BlockInfo.
2209
2210 This is convenient for verifying that an object is an instance of
2211 a _BlockInfo, but not an instance of any of the derived classes.
2212
2213 Returns:
2214 True for this class, False for derived classes.
2215 """
2216 return self.__class__ == _BlockInfo
2217
2218
2219class _ExternCInfo(_BlockInfo):
2220 """Stores information about an 'extern "C"' block."""
2221
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002222 def __init__(self, linenum):
2223 _BlockInfo.__init__(self, linenum, True)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002224
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002225
2226class _ClassInfo(_BlockInfo):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002227 """Stores information about a class."""
2228
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002229 def __init__(self, name, class_or_struct, clean_lines, linenum):
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002230 _BlockInfo.__init__(self, linenum, False)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002231 self.name = name
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002232 self.is_derived = False
avakulenko@google.com59146752014-08-11 20:20:55 +00002233 self.check_namespace_indentation = True
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002234 if class_or_struct == 'struct':
2235 self.access = 'public'
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002236 self.is_struct = True
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002237 else:
2238 self.access = 'private'
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002239 self.is_struct = False
2240
2241 # Remember initial indentation level for this class. Using raw_lines here
2242 # instead of elided to account for leading comments.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002243 self.class_indent = GetIndentLevel(clean_lines.raw_lines[linenum])
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002244
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00002245 # Try to find the end of the class. This will be confused by things like:
2246 # class A {
2247 # } *x = { ...
2248 #
2249 # But it's still good enough for CheckSectionSpacing.
2250 self.last_line = 0
2251 depth = 0
2252 for i in range(linenum, clean_lines.NumLines()):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002253 line = clean_lines.elided[i]
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00002254 depth += line.count('{') - line.count('}')
2255 if not depth:
2256 self.last_line = i
2257 break
2258
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002259 def CheckBegin(self, filename, clean_lines, linenum, error):
2260 # Look for a bare ':'
2261 if Search('(^|[^:]):($|[^:])', clean_lines.elided[linenum]):
2262 self.is_derived = True
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002263
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002264 def CheckEnd(self, filename, clean_lines, linenum, error):
avakulenko@google.com255f2be2014-12-05 22:19:55 +00002265 # If there is a DISALLOW macro, it should appear near the end of
2266 # the class.
2267 seen_last_thing_in_class = False
Edward Lemur6d31ed52019-12-02 23:00:00 +00002268 for i in range(linenum - 1, self.starting_linenum, -1):
avakulenko@google.com255f2be2014-12-05 22:19:55 +00002269 match = Search(
2270 r'\b(DISALLOW_COPY_AND_ASSIGN|DISALLOW_IMPLICIT_CONSTRUCTORS)\(' +
2271 self.name + r'\)',
2272 clean_lines.elided[i])
2273 if match:
2274 if seen_last_thing_in_class:
2275 error(filename, i, 'readability/constructors', 3,
2276 match.group(1) + ' should be the last thing in the class')
2277 break
2278
2279 if not Match(r'^\s*$', clean_lines.elided[i]):
2280 seen_last_thing_in_class = True
2281
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002282 # Check that closing brace is aligned with beginning of the class.
2283 # Only do this if the closing brace is indented by only whitespaces.
2284 # This means we will not check single-line class definitions.
2285 indent = Match(r'^( *)\}', clean_lines.elided[linenum])
2286 if indent and len(indent.group(1)) != self.class_indent:
2287 if self.is_struct:
2288 parent = 'struct ' + self.name
2289 else:
2290 parent = 'class ' + self.name
2291 error(filename, linenum, 'whitespace/indent', 3,
2292 'Closing brace should be aligned with beginning of %s' % parent)
2293
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002294
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002295class _NamespaceInfo(_BlockInfo):
2296 """Stores information about a namespace."""
2297
2298 def __init__(self, name, linenum):
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002299 _BlockInfo.__init__(self, linenum, False)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002300 self.name = name or ''
avakulenko@google.com59146752014-08-11 20:20:55 +00002301 self.check_namespace_indentation = True
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002302
2303 def CheckEnd(self, filename, clean_lines, linenum, error):
2304 """Check end of namespace comments."""
2305 line = clean_lines.raw_lines[linenum]
2306
2307 # Check how many lines is enclosed in this namespace. Don't issue
2308 # warning for missing namespace comments if there aren't enough
2309 # lines. However, do apply checks if there is already an end of
2310 # namespace comment and it's incorrect.
2311 #
2312 # TODO(unknown): We always want to check end of namespace comments
2313 # if a namespace is large, but sometimes we also want to apply the
2314 # check if a short namespace contained nontrivial things (something
2315 # other than forward declarations). There is currently no logic on
2316 # deciding what these nontrivial things are, so this check is
2317 # triggered by namespace size only, which works most of the time.
2318 if (linenum - self.starting_linenum < 10
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002319 and not Match(r'^\s*};*\s*(//|/\*).*\bnamespace\b', line)):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002320 return
2321
2322 # Look for matching comment at end of namespace.
2323 #
2324 # Note that we accept C style "/* */" comments for terminating
2325 # namespaces, so that code that terminate namespaces inside
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002326 # preprocessor macros can be cpplint clean.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002327 #
2328 # We also accept stuff like "// end of namespace <name>." with the
2329 # period at the end.
2330 #
2331 # Besides these, we don't accept anything else, otherwise we might
2332 # get false negatives when existing comment is a substring of the
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002333 # expected namespace.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002334 if self.name:
2335 # Named namespace
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002336 if not Match((r'^\s*};*\s*(//|/\*).*\bnamespace\s+' +
2337 re.escape(self.name) + r'[\*/\.\\\s]*$'),
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002338 line):
2339 error(filename, linenum, 'readability/namespace', 5,
2340 'Namespace should be terminated with "// namespace %s"' %
2341 self.name)
2342 else:
2343 # Anonymous namespace
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002344 if not Match(r'^\s*};*\s*(//|/\*).*\bnamespace[\*/\.\\\s]*$', line):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002345 # If "// namespace anonymous" or "// anonymous namespace (more text)",
2346 # mention "// anonymous namespace" as an acceptable form
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002347 if Match(r'^\s*}.*\b(namespace anonymous|anonymous namespace)\b', line):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002348 error(filename, linenum, 'readability/namespace', 5,
2349 'Anonymous namespace should be terminated with "// namespace"'
2350 ' or "// anonymous namespace"')
2351 else:
2352 error(filename, linenum, 'readability/namespace', 5,
2353 'Anonymous namespace should be terminated with "// namespace"')
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002354
2355
2356class _PreprocessorInfo(object):
2357 """Stores checkpoints of nesting stacks when #if/#else is seen."""
2358
2359 def __init__(self, stack_before_if):
2360 # The entire nesting stack before #if
2361 self.stack_before_if = stack_before_if
2362
2363 # The entire nesting stack up to #else
2364 self.stack_before_else = []
2365
2366 # Whether we have already seen #else or #elif
2367 self.seen_else = False
2368
2369
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002370class NestingState(object):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002371 """Holds states related to parsing braces."""
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002372
2373 def __init__(self):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002374 # Stack for tracking all braces. An object is pushed whenever we
2375 # see a "{", and popped when we see a "}". Only 3 types of
2376 # objects are possible:
2377 # - _ClassInfo: a class or struct.
2378 # - _NamespaceInfo: a namespace.
2379 # - _BlockInfo: some other type of block.
2380 self.stack = []
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002381
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002382 # Top of the previous stack before each Update().
2383 #
2384 # Because the nesting_stack is updated at the end of each line, we
2385 # had to do some convoluted checks to find out what is the current
2386 # scope at the beginning of the line. This check is simplified by
2387 # saving the previous top of nesting stack.
2388 #
2389 # We could save the full stack, but we only need the top. Copying
2390 # the full nesting stack would slow down cpplint by ~10%.
2391 self.previous_stack_top = []
2392
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002393 # Stack of _PreprocessorInfo objects.
2394 self.pp_stack = []
2395
2396 def SeenOpenBrace(self):
2397 """Check if we have seen the opening brace for the innermost block.
2398
2399 Returns:
2400 True if we have seen the opening brace, False if the innermost
2401 block is still expecting an opening brace.
2402 """
2403 return (not self.stack) or self.stack[-1].seen_open_brace
2404
2405 def InNamespaceBody(self):
2406 """Check if we are currently one level inside a namespace body.
2407
2408 Returns:
2409 True if top of the stack is a namespace block, False otherwise.
2410 """
2411 return self.stack and isinstance(self.stack[-1], _NamespaceInfo)
2412
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002413 def InExternC(self):
2414 """Check if we are currently one level inside an 'extern "C"' block.
2415
2416 Returns:
2417 True if top of the stack is an extern block, False otherwise.
2418 """
2419 return self.stack and isinstance(self.stack[-1], _ExternCInfo)
2420
2421 def InClassDeclaration(self):
2422 """Check if we are currently one level inside a class or struct declaration.
2423
2424 Returns:
2425 True if top of the stack is a class/struct, False otherwise.
2426 """
2427 return self.stack and isinstance(self.stack[-1], _ClassInfo)
2428
2429 def InAsmBlock(self):
2430 """Check if we are currently one level inside an inline ASM block.
2431
2432 Returns:
2433 True if the top of the stack is a block containing inline ASM.
2434 """
2435 return self.stack and self.stack[-1].inline_asm != _NO_ASM
2436
2437 def InTemplateArgumentList(self, clean_lines, linenum, pos):
2438 """Check if current position is inside template argument list.
2439
2440 Args:
2441 clean_lines: A CleansedLines instance containing the file.
2442 linenum: The number of the line to check.
2443 pos: position just after the suspected template argument.
2444 Returns:
2445 True if (linenum, pos) is inside template arguments.
2446 """
2447 while linenum < clean_lines.NumLines():
2448 # Find the earliest character that might indicate a template argument
2449 line = clean_lines.elided[linenum]
2450 match = Match(r'^[^{};=\[\]\.<>]*(.)', line[pos:])
2451 if not match:
2452 linenum += 1
2453 pos = 0
2454 continue
2455 token = match.group(1)
2456 pos += len(match.group(0))
2457
2458 # These things do not look like template argument list:
2459 # class Suspect {
2460 # class Suspect x; }
2461 if token in ('{', '}', ';'): return False
2462
2463 # These things look like template argument list:
2464 # template <class Suspect>
2465 # template <class Suspect = default_value>
2466 # template <class Suspect[]>
2467 # template <class Suspect...>
2468 if token in ('>', '=', '[', ']', '.'): return True
2469
2470 # Check if token is an unmatched '<'.
2471 # If not, move on to the next character.
2472 if token != '<':
2473 pos += 1
2474 if pos >= len(line):
2475 linenum += 1
2476 pos = 0
2477 continue
2478
2479 # We can't be sure if we just find a single '<', and need to
2480 # find the matching '>'.
2481 (_, end_line, end_pos) = CloseExpression(clean_lines, linenum, pos - 1)
2482 if end_pos < 0:
2483 # Not sure if template argument list or syntax error in file
2484 return False
2485 linenum = end_line
2486 pos = end_pos
2487 return False
2488
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002489 def UpdatePreprocessor(self, line):
2490 """Update preprocessor stack.
2491
2492 We need to handle preprocessors due to classes like this:
2493 #ifdef SWIG
2494 struct ResultDetailsPageElementExtensionPoint {
2495 #else
2496 struct ResultDetailsPageElementExtensionPoint : public Extension {
2497 #endif
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002498
2499 We make the following assumptions (good enough for most files):
2500 - Preprocessor condition evaluates to true from #if up to first
2501 #else/#elif/#endif.
2502
2503 - Preprocessor condition evaluates to false from #else/#elif up
2504 to #endif. We still perform lint checks on these lines, but
2505 these do not affect nesting stack.
2506
2507 Args:
2508 line: current line to check.
2509 """
2510 if Match(r'^\s*#\s*(if|ifdef|ifndef)\b', line):
2511 # Beginning of #if block, save the nesting stack here. The saved
2512 # stack will allow us to restore the parsing state in the #else case.
2513 self.pp_stack.append(_PreprocessorInfo(copy.deepcopy(self.stack)))
2514 elif Match(r'^\s*#\s*(else|elif)\b', line):
2515 # Beginning of #else block
2516 if self.pp_stack:
2517 if not self.pp_stack[-1].seen_else:
2518 # This is the first #else or #elif block. Remember the
2519 # whole nesting stack up to this point. This is what we
2520 # keep after the #endif.
2521 self.pp_stack[-1].seen_else = True
2522 self.pp_stack[-1].stack_before_else = copy.deepcopy(self.stack)
2523
2524 # Restore the stack to how it was before the #if
2525 self.stack = copy.deepcopy(self.pp_stack[-1].stack_before_if)
2526 else:
2527 # TODO(unknown): unexpected #else, issue warning?
2528 pass
2529 elif Match(r'^\s*#\s*endif\b', line):
2530 # End of #if or #else blocks.
2531 if self.pp_stack:
2532 # If we saw an #else, we will need to restore the nesting
2533 # stack to its former state before the #else, otherwise we
2534 # will just continue from where we left off.
2535 if self.pp_stack[-1].seen_else:
2536 # Here we can just use a shallow copy since we are the last
2537 # reference to it.
2538 self.stack = self.pp_stack[-1].stack_before_else
2539 # Drop the corresponding #if
2540 self.pp_stack.pop()
2541 else:
2542 # TODO(unknown): unexpected #endif, issue warning?
2543 pass
2544
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002545 # TODO(unknown): Update() is too long, but we will refactor later.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002546 def Update(self, filename, clean_lines, linenum, error):
2547 """Update nesting state with current line.
2548
2549 Args:
2550 filename: The name of the current file.
2551 clean_lines: A CleansedLines instance containing the file.
2552 linenum: The number of the line to check.
2553 error: The function to call with any errors found.
2554 """
2555 line = clean_lines.elided[linenum]
2556
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002557 # Remember top of the previous nesting stack.
2558 #
2559 # The stack is always pushed/popped and not modified in place, so
2560 # we can just do a shallow copy instead of copy.deepcopy. Using
2561 # deepcopy would slow down cpplint by ~28%.
2562 if self.stack:
2563 self.previous_stack_top = self.stack[-1]
2564 else:
2565 self.previous_stack_top = None
2566
2567 # Update pp_stack
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002568 self.UpdatePreprocessor(line)
2569
2570 # Count parentheses. This is to avoid adding struct arguments to
2571 # the nesting stack.
2572 if self.stack:
2573 inner_block = self.stack[-1]
2574 depth_change = line.count('(') - line.count(')')
2575 inner_block.open_parentheses += depth_change
2576
2577 # Also check if we are starting or ending an inline assembly block.
2578 if inner_block.inline_asm in (_NO_ASM, _END_ASM):
2579 if (depth_change != 0 and
2580 inner_block.open_parentheses == 1 and
2581 _MATCH_ASM.match(line)):
2582 # Enter assembly block
2583 inner_block.inline_asm = _INSIDE_ASM
2584 else:
2585 # Not entering assembly block. If previous line was _END_ASM,
2586 # we will now shift to _NO_ASM state.
2587 inner_block.inline_asm = _NO_ASM
2588 elif (inner_block.inline_asm == _INSIDE_ASM and
2589 inner_block.open_parentheses == 0):
2590 # Exit assembly block
2591 inner_block.inline_asm = _END_ASM
2592
2593 # Consume namespace declaration at the beginning of the line. Do
2594 # this in a loop so that we catch same line declarations like this:
2595 # namespace proto2 { namespace bridge { class MessageSet; } }
2596 while True:
2597 # Match start of namespace. The "\b\s*" below catches namespace
2598 # declarations even if it weren't followed by a whitespace, this
2599 # is so that we don't confuse our namespace checker. The
2600 # missing spaces will be flagged by CheckSpacing.
2601 namespace_decl_match = Match(r'^\s*namespace\b\s*([:\w]+)?(.*)$', line)
2602 if not namespace_decl_match:
2603 break
2604
2605 new_namespace = _NamespaceInfo(namespace_decl_match.group(1), linenum)
2606 self.stack.append(new_namespace)
2607
2608 line = namespace_decl_match.group(2)
2609 if line.find('{') != -1:
2610 new_namespace.seen_open_brace = True
2611 line = line[line.find('{') + 1:]
2612
2613 # Look for a class declaration in whatever is left of the line
2614 # after parsing namespaces. The regexp accounts for decorated classes
2615 # such as in:
2616 # class LOCKABLE API Object {
2617 # };
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002618 class_decl_match = Match(
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002619 r'^(\s*(?:template\s*<[\w\s<>,:]*>\s*)?'
Clemens Hammacher2cc6e252018-12-20 08:40:19 +00002620 r'(class|struct)\s+(?:[A-Z0-9_]+\s+)*(\w+(?:::\w+)*))'
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002621 r'(.*)$', line)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002622 if (class_decl_match and
2623 (not self.stack or self.stack[-1].open_parentheses == 0)):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002624 # We do not want to accept classes that are actually template arguments:
2625 # template <class Ignore1,
2626 # class Ignore2 = Default<Args>,
2627 # template <Args> class Ignore3>
2628 # void Function() {};
2629 #
2630 # To avoid template argument cases, we scan forward and look for
2631 # an unmatched '>'. If we see one, assume we are inside a
2632 # template argument list.
2633 end_declaration = len(class_decl_match.group(1))
2634 if not self.InTemplateArgumentList(clean_lines, linenum, end_declaration):
2635 self.stack.append(_ClassInfo(
2636 class_decl_match.group(3), class_decl_match.group(2),
2637 clean_lines, linenum))
2638 line = class_decl_match.group(4)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002639
2640 # If we have not yet seen the opening brace for the innermost block,
2641 # run checks here.
2642 if not self.SeenOpenBrace():
2643 self.stack[-1].CheckBegin(filename, clean_lines, linenum, error)
2644
2645 # Update access control if we are inside a class/struct
2646 if self.stack and isinstance(self.stack[-1], _ClassInfo):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002647 classinfo = self.stack[-1]
2648 access_match = Match(
2649 r'^(.*)\b(public|private|protected|signals)(\s+(?:slots\s*)?)?'
2650 r':(?:[^:]|$)',
2651 line)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002652 if access_match:
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002653 classinfo.access = access_match.group(2)
2654
2655 # Check that access keywords are indented +1 space. Skip this
2656 # check if the keywords are not preceded by whitespaces.
2657 indent = access_match.group(1)
2658 if (len(indent) != classinfo.class_indent + 1 and
2659 Match(r'^\s*$', indent)):
2660 if classinfo.is_struct:
2661 parent = 'struct ' + classinfo.name
2662 else:
2663 parent = 'class ' + classinfo.name
2664 slots = ''
2665 if access_match.group(3):
2666 slots = access_match.group(3)
2667 error(filename, linenum, 'whitespace/indent', 3,
2668 '%s%s: should be indented +1 space inside %s' % (
2669 access_match.group(2), slots, parent))
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002670
2671 # Consume braces or semicolons from what's left of the line
2672 while True:
2673 # Match first brace, semicolon, or closed parenthesis.
2674 matched = Match(r'^[^{;)}]*([{;)}])(.*)$', line)
2675 if not matched:
2676 break
2677
2678 token = matched.group(1)
2679 if token == '{':
2680 # If namespace or class hasn't seen a opening brace yet, mark
2681 # namespace/class head as complete. Push a new block onto the
2682 # stack otherwise.
2683 if not self.SeenOpenBrace():
2684 self.stack[-1].seen_open_brace = True
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002685 elif Match(r'^extern\s*"[^"]*"\s*\{', line):
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002686 self.stack.append(_ExternCInfo(linenum))
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002687 else:
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002688 self.stack.append(_BlockInfo(linenum, True))
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002689 if _MATCH_ASM.match(line):
2690 self.stack[-1].inline_asm = _BLOCK_ASM
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002691
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002692 elif token == ';' or token == ')':
2693 # If we haven't seen an opening brace yet, but we already saw
2694 # a semicolon, this is probably a forward declaration. Pop
2695 # the stack for these.
2696 #
2697 # Similarly, if we haven't seen an opening brace yet, but we
2698 # already saw a closing parenthesis, then these are probably
2699 # function arguments with extra "class" or "struct" keywords.
2700 # Also pop these stack for these.
2701 if not self.SeenOpenBrace():
2702 self.stack.pop()
2703 else: # token == '}'
2704 # Perform end of block checks and pop the stack.
2705 if self.stack:
2706 self.stack[-1].CheckEnd(filename, clean_lines, linenum, error)
2707 self.stack.pop()
2708 line = matched.group(2)
2709
2710 def InnermostClass(self):
2711 """Get class info on the top of the stack.
2712
2713 Returns:
2714 A _ClassInfo object if we are inside a class, or None otherwise.
2715 """
2716 for i in range(len(self.stack), 0, -1):
2717 classinfo = self.stack[i - 1]
2718 if isinstance(classinfo, _ClassInfo):
2719 return classinfo
2720 return None
2721
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002722 def CheckCompletedBlocks(self, filename, error):
2723 """Checks that all classes and namespaces have been completely parsed.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002724
2725 Call this when all lines in a file have been processed.
2726 Args:
2727 filename: The name of the current file.
2728 error: The function to call with any errors found.
2729 """
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002730 # Note: This test can result in false positives if #ifdef constructs
2731 # get in the way of brace matching. See the testBuildClass test in
2732 # cpplint_unittest.py for an example of this.
2733 for obj in self.stack:
2734 if isinstance(obj, _ClassInfo):
2735 error(filename, obj.starting_linenum, 'build/class', 5,
2736 'Failed to find complete declaration of class %s' %
2737 obj.name)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002738 elif isinstance(obj, _NamespaceInfo):
2739 error(filename, obj.starting_linenum, 'build/namespaces', 5,
2740 'Failed to find complete declaration of namespace %s' %
2741 obj.name)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002742
2743
2744def CheckForNonStandardConstructs(filename, clean_lines, linenum,
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002745 nesting_state, error):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002746 r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002747
2748 Complain about several constructs which gcc-2 accepts, but which are
2749 not standard C++. Warning about these in lint is one way to ease the
2750 transition to new compilers.
2751 - put storage class first (e.g. "static const" instead of "const static").
2752 - "%lld" instead of %qd" in printf-type functions.
2753 - "%1$d" is non-standard in printf-type functions.
2754 - "\%" is an undefined character escape sequence.
2755 - text after #endif is not allowed.
2756 - invalid inner-style forward declaration.
2757 - >? and <? operators, and their >?= and <?= cousins.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002758
erg@google.com26970fa2009-11-17 18:07:32 +00002759 Additionally, check for constructor/destructor style violations and reference
2760 members, as it is very convenient to do so while checking for
2761 gcc-2 compliance.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002762
2763 Args:
2764 filename: The name of the current file.
2765 clean_lines: A CleansedLines instance containing the file.
2766 linenum: The number of the line to check.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002767 nesting_state: A NestingState instance which maintains information about
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002768 the current stack of nested blocks being parsed.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002769 error: A callable to which errors are reported, which takes 4 arguments:
2770 filename, line number, error level, and message
2771 """
2772
2773 # Remove comments from the line, but leave in strings for now.
2774 line = clean_lines.lines[linenum]
2775
2776 if Search(r'printf\s*\(.*".*%[-+ ]?\d*q', line):
2777 error(filename, linenum, 'runtime/printf_format', 3,
2778 '%q in format strings is deprecated. Use %ll instead.')
2779
2780 if Search(r'printf\s*\(.*".*%\d+\$', line):
2781 error(filename, linenum, 'runtime/printf_format', 2,
2782 '%N$ formats are unconventional. Try rewriting to avoid them.')
2783
2784 # Remove escaped backslashes before looking for undefined escapes.
2785 line = line.replace('\\\\', '')
2786
2787 if Search(r'("|\').*\\(%|\[|\(|{)', line):
2788 error(filename, linenum, 'build/printf_format', 3,
2789 '%, [, (, and { are undefined character escapes. Unescape them.')
2790
2791 # For the rest, work with both comments and strings removed.
2792 line = clean_lines.elided[linenum]
2793
2794 if Search(r'\b(const|volatile|void|char|short|int|long'
2795 r'|float|double|signed|unsigned'
2796 r'|schar|u?int8|u?int16|u?int32|u?int64)'
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002797 r'\s+(register|static|extern|typedef)\b',
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002798 line):
2799 error(filename, linenum, 'build/storage_class', 5,
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002800 'Storage-class specifier (static, extern, typedef, etc) should be '
2801 'at the beginning of the declaration.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002802
2803 if Match(r'\s*#\s*endif\s*[^/\s]+', line):
2804 error(filename, linenum, 'build/endif_comment', 5,
2805 'Uncommented text after #endif is non-standard. Use a comment.')
2806
2807 if Match(r'\s*class\s+(\w+\s*::\s*)+\w+\s*;', line):
2808 error(filename, linenum, 'build/forward_decl', 5,
2809 'Inner-style forward declarations are invalid. Remove this line.')
2810
2811 if Search(r'(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?',
2812 line):
2813 error(filename, linenum, 'build/deprecated', 3,
2814 '>? and <? (max and min) operators are non-standard and deprecated.')
2815
erg@google.com26970fa2009-11-17 18:07:32 +00002816 if Search(r'^\s*const\s*string\s*&\s*\w+\s*;', line):
2817 # TODO(unknown): Could it be expanded safely to arbitrary references,
2818 # without triggering too many false positives? The first
2819 # attempt triggered 5 warnings for mostly benign code in the regtest, hence
2820 # the restriction.
2821 # Here's the original regexp, for the reference:
2822 # type_name = r'\w+((\s*::\s*\w+)|(\s*<\s*\w+?\s*>))?'
2823 # r'\s*const\s*' + type_name + '\s*&\s*\w+\s*;'
2824 error(filename, linenum, 'runtime/member_string_references', 2,
2825 'const string& members are dangerous. It is much better to use '
2826 'alternatives, such as pointers or simple constants.')
2827
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002828 # Everything else in this function operates on class declarations.
2829 # Return early if the top of the nesting stack is not a class, or if
2830 # the class head is not completed yet.
2831 classinfo = nesting_state.InnermostClass()
2832 if not classinfo or not classinfo.seen_open_brace:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002833 return
2834
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002835 # The class may have been declared with namespace or classname qualifiers.
2836 # The constructor and destructor will not have those qualifiers.
2837 base_classname = classinfo.name.split('::')[-1]
2838
2839 # Look for single-argument constructors that aren't marked explicit.
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002840 # Technically a valid construct, but against style.
avakulenko@google.com59146752014-08-11 20:20:55 +00002841 explicit_constructor_match = Match(
danakjd7f56752017-02-22 11:45:06 -05002842 r'\s+(?:(?:inline|constexpr)\s+)*(explicit\s+)?'
2843 r'(?:(?:inline|constexpr)\s+)*%s\s*'
avakulenko@google.com59146752014-08-11 20:20:55 +00002844 r'\(((?:[^()]|\([^()]*\))*)\)'
2845 % re.escape(base_classname),
2846 line)
2847
2848 if explicit_constructor_match:
2849 is_marked_explicit = explicit_constructor_match.group(1)
2850
2851 if not explicit_constructor_match.group(2):
2852 constructor_args = []
2853 else:
2854 constructor_args = explicit_constructor_match.group(2).split(',')
2855
2856 # collapse arguments so that commas in template parameter lists and function
2857 # argument parameter lists don't split arguments in two
2858 i = 0
2859 while i < len(constructor_args):
2860 constructor_arg = constructor_args[i]
2861 while (constructor_arg.count('<') > constructor_arg.count('>') or
2862 constructor_arg.count('(') > constructor_arg.count(')')):
2863 constructor_arg += ',' + constructor_args[i + 1]
2864 del constructor_args[i + 1]
2865 constructor_args[i] = constructor_arg
2866 i += 1
2867
2868 defaulted_args = [arg for arg in constructor_args if '=' in arg]
2869 noarg_constructor = (not constructor_args or # empty arg list
2870 # 'void' arg specifier
2871 (len(constructor_args) == 1 and
2872 constructor_args[0].strip() == 'void'))
2873 onearg_constructor = ((len(constructor_args) == 1 and # exactly one arg
2874 not noarg_constructor) or
2875 # all but at most one arg defaulted
2876 (len(constructor_args) >= 1 and
2877 not noarg_constructor and
2878 len(defaulted_args) >= len(constructor_args) - 1))
2879 initializer_list_constructor = bool(
2880 onearg_constructor and
2881 Search(r'\bstd\s*::\s*initializer_list\b', constructor_args[0]))
2882 copy_constructor = bool(
2883 onearg_constructor and
2884 Match(r'(const\s+)?%s(\s*<[^>]*>)?(\s+const)?\s*(?:<\w+>\s*)?&'
2885 % re.escape(base_classname), constructor_args[0].strip()))
2886
2887 if (not is_marked_explicit and
2888 onearg_constructor and
2889 not initializer_list_constructor and
2890 not copy_constructor):
2891 if defaulted_args:
2892 error(filename, linenum, 'runtime/explicit', 5,
2893 'Constructors callable with one argument '
2894 'should be marked explicit.')
2895 else:
2896 error(filename, linenum, 'runtime/explicit', 5,
2897 'Single-parameter constructors should be marked explicit.')
2898 elif is_marked_explicit and not onearg_constructor:
2899 if noarg_constructor:
2900 error(filename, linenum, 'runtime/explicit', 5,
2901 'Zero-parameter constructors should not be marked explicit.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002902
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002903
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002904def CheckSpacingForFunctionCall(filename, clean_lines, linenum, error):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002905 """Checks for the correctness of various spacing around function calls.
2906
2907 Args:
2908 filename: The name of the current file.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002909 clean_lines: A CleansedLines instance containing the file.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002910 linenum: The number of the line to check.
2911 error: The function to call with any errors found.
2912 """
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002913 line = clean_lines.elided[linenum]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002914
2915 # Since function calls often occur inside if/for/while/switch
2916 # expressions - which have their own, more liberal conventions - we
2917 # first see if we should be looking inside such an expression for a
2918 # function call, to which we can apply more strict standards.
2919 fncall = line # if there's no control flow construct, look at whole line
Darius Maa7d7e42022-05-13 14:54:21 +00002920 for pattern in (r'\bif\s*(?:constexpr\s*)?\((.*)\)\s*{',
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002921 r'\bfor\s*\((.*)\)\s*{',
2922 r'\bwhile\s*\((.*)\)\s*[{;]',
2923 r'\bswitch\s*\((.*)\)\s*{'):
2924 match = Search(pattern, line)
2925 if match:
2926 fncall = match.group(1) # look inside the parens for function calls
2927 break
2928
2929 # Except in if/for/while/switch, there should never be space
2930 # immediately inside parens (eg "f( 3, 4 )"). We make an exception
2931 # for nested parens ( (a+b) + c ). Likewise, there should never be
2932 # a space before a ( when it's a function argument. I assume it's a
2933 # function argument when the char before the whitespace is legal in
2934 # a function name (alnum + _) and we're not starting a macro. Also ignore
2935 # pointers and references to arrays and functions coz they're too tricky:
2936 # we use a very simple way to recognize these:
2937 # " (something)(maybe-something)" or
2938 # " (something)(maybe-something," or
2939 # " (something)[something]"
2940 # Note that we assume the contents of [] to be short enough that
2941 # they'll never need to wrap.
2942 if ( # Ignore control structures.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002943 not Search(r'\b(if|for|while|switch|return|new|delete|catch|sizeof)\b',
2944 fncall) and
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002945 # Ignore pointers/references to functions.
2946 not Search(r' \([^)]+\)\([^)]*(\)|,$)', fncall) and
2947 # Ignore pointers/references to arrays.
2948 not Search(r' \([^)]+\)\[[^\]]+\]', fncall)):
erg@google.com6317a9c2009-06-25 00:28:19 +00002949 if Search(r'\w\s*\(\s(?!\s*\\$)', fncall): # a ( used for a fn call
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002950 error(filename, linenum, 'whitespace/parens', 4,
2951 'Extra space after ( in function call')
erg@google.com6317a9c2009-06-25 00:28:19 +00002952 elif Search(r'\(\s+(?!(\s*\\)|\()', fncall):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002953 error(filename, linenum, 'whitespace/parens', 2,
2954 'Extra space after (')
2955 if (Search(r'\w\s+\(', fncall) and
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002956 not Search(r'_{0,2}asm_{0,2}\s+_{0,2}volatile_{0,2}\s+\(', fncall) and
Bruce Dawson3e87cea2020-04-30 17:56:07 +00002957 not Search(r'#\s*define|typedef|__except|using\s+\w+\s*=', fncall) and
avakulenko@google.com255f2be2014-12-05 22:19:55 +00002958 not Search(r'\w\s+\((\w+::)*\*\w+\)\(', fncall) and
2959 not Search(r'\bcase\s+\(', fncall)):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002960 # TODO(unknown): Space after an operator function seem to be a common
2961 # error, silence those for now by restricting them to highest verbosity.
2962 if Search(r'\boperator_*\b', line):
2963 error(filename, linenum, 'whitespace/parens', 0,
2964 'Extra space before ( in function call')
2965 else:
2966 error(filename, linenum, 'whitespace/parens', 4,
2967 'Extra space before ( in function call')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002968 # If the ) is followed only by a newline or a { + newline, assume it's
2969 # part of a control statement (if/while/etc), and don't complain
2970 if Search(r'[^)]\s+\)\s*[^{\s]', fncall):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00002971 # If the closing parenthesis is preceded by only whitespaces,
2972 # try to give a more descriptive error message.
2973 if Search(r'^\s+\)', fncall):
2974 error(filename, linenum, 'whitespace/parens', 2,
2975 'Closing ) should be moved to the previous line')
2976 else:
2977 error(filename, linenum, 'whitespace/parens', 2,
2978 'Extra space before )')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002979
2980
2981def IsBlankLine(line):
2982 """Returns true if the given line is blank.
2983
2984 We consider a line to be blank if the line is empty or consists of
2985 only white spaces.
2986
2987 Args:
2988 line: A line of a string.
2989
2990 Returns:
2991 True, if the given line is blank.
2992 """
2993 return not line or line.isspace()
2994
2995
avakulenko@google.com59146752014-08-11 20:20:55 +00002996def CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line,
2997 error):
2998 is_namespace_indent_item = (
2999 len(nesting_state.stack) > 1 and
3000 nesting_state.stack[-1].check_namespace_indentation and
3001 isinstance(nesting_state.previous_stack_top, _NamespaceInfo) and
3002 nesting_state.previous_stack_top == nesting_state.stack[-2])
3003
3004 if ShouldCheckNamespaceIndentation(nesting_state, is_namespace_indent_item,
3005 clean_lines.elided, line):
3006 CheckItemIndentationInNamespace(filename, clean_lines.elided,
3007 line, error)
3008
3009
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003010def CheckForFunctionLengths(filename, clean_lines, linenum,
3011 function_state, error):
3012 """Reports for long function bodies.
3013
3014 For an overview why this is done, see:
Alexandr Ilinff294c32017-04-27 15:57:40 +02003015 https://google.github.io/styleguide/cppguide.html#Write_Short_Functions
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003016
3017 Uses a simplistic algorithm assuming other style guidelines
3018 (especially spacing) are followed.
3019 Only checks unindented functions, so class members are unchecked.
3020 Trivial bodies are unchecked, so constructors with huge initializer lists
3021 may be missed.
3022 Blank/comment lines are not counted so as to avoid encouraging the removal
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003023 of vertical space and comments just to get through a lint check.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003024 NOLINT *on the last line of a function* disables this check.
3025
3026 Args:
3027 filename: The name of the current file.
3028 clean_lines: A CleansedLines instance containing the file.
3029 linenum: The number of the line to check.
3030 function_state: Current function name and lines in body so far.
3031 error: The function to call with any errors found.
3032 """
3033 lines = clean_lines.lines
3034 line = lines[linenum]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003035 joined_line = ''
3036
3037 starting_func = False
erg@google.com6317a9c2009-06-25 00:28:19 +00003038 regexp = r'(\w(\w|::|\*|\&|\s)*)\(' # decls * & space::name( ...
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003039 match_result = Match(regexp, line)
3040 if match_result:
3041 # If the name is all caps and underscores, figure it's a macro and
3042 # ignore it, unless it's TEST or TEST_F.
3043 function_name = match_result.group(1).split()[-1]
3044 if function_name == 'TEST' or function_name == 'TEST_F' or (
Quinten Yearsley48099572019-02-22 21:13:37 +00003045 not Match(r'[A-Z_0-9]+$', function_name)):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003046 starting_func = True
3047
3048 if starting_func:
3049 body_found = False
Edward Lemur6d31ed52019-12-02 23:00:00 +00003050 for start_linenum in range(linenum, clean_lines.NumLines()):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003051 start_line = lines[start_linenum]
3052 joined_line += ' ' + start_line.lstrip()
3053 if Search(r'(;|})', start_line): # Declarations and trivial functions
3054 body_found = True
3055 break # ... ignore
3056 elif Search(r'{', start_line):
3057 body_found = True
3058 function = Search(r'((\w|:)*)\(', line).group(1)
3059 if Match(r'TEST', function): # Handle TEST... macros
3060 parameter_regexp = Search(r'(\(.*\))', joined_line)
3061 if parameter_regexp: # Ignore bad syntax
3062 function += parameter_regexp.group(1)
3063 else:
3064 function += '()'
3065 function_state.Begin(function)
3066 break
3067 if not body_found:
erg@google.com6317a9c2009-06-25 00:28:19 +00003068 # No body for the function (or evidence of a non-function) was found.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003069 error(filename, linenum, 'readability/fn_size', 5,
3070 'Lint failed to find start of function body.')
3071 elif Match(r'^\}\s*$', line): # function end
erg@google.com35589e62010-11-17 18:58:16 +00003072 function_state.Check(error, filename, linenum)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003073 function_state.End()
3074 elif not Match(r'^\s*$', line):
3075 function_state.Count() # Count non-blank/non-comment lines.
3076
3077
3078_RE_PATTERN_TODO = re.compile(r'^//(\s*)TODO(\(.+?\))?:?(\s|$)?')
3079
3080
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003081def CheckComment(line, filename, linenum, next_line_start, error):
3082 """Checks for common mistakes in comments.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003083
3084 Args:
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003085 line: The line in question.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003086 filename: The name of the current file.
3087 linenum: The number of the line to check.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003088 next_line_start: The first non-whitespace column of the next line.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003089 error: The function to call with any errors found.
3090 """
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003091 commentpos = line.find('//')
3092 if commentpos != -1:
3093 # Check if the // may be in quotes. If so, ignore it
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003094 if re.sub(r'\\.', '', line[0:commentpos]).count('"') % 2 == 0:
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003095 # Allow one space for new scopes, two spaces otherwise:
3096 if (not (Match(r'^.*{ *//', line) and next_line_start == commentpos) and
3097 ((commentpos >= 1 and
3098 line[commentpos-1] not in string.whitespace) or
3099 (commentpos >= 2 and
3100 line[commentpos-2] not in string.whitespace))):
3101 error(filename, linenum, 'whitespace/comments', 2,
3102 'At least two spaces is best between code and comments')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003103
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003104 # Checks for common mistakes in TODO comments.
3105 comment = line[commentpos:]
3106 match = _RE_PATTERN_TODO.match(comment)
3107 if match:
3108 # One whitespace is correct; zero whitespace is handled elsewhere.
3109 leading_whitespace = match.group(1)
3110 if len(leading_whitespace) > 1:
3111 error(filename, linenum, 'whitespace/todo', 2,
3112 'Too many spaces before TODO')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003113
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003114 username = match.group(2)
3115 if not username:
3116 error(filename, linenum, 'readability/todo', 2,
3117 'Missing username in TODO; it should look like '
3118 '"// TODO(my_username): Stuff."')
3119
3120 middle_whitespace = match.group(3)
3121 # Comparisons made explicit for correctness -- pylint: disable=g-explicit-bool-comparison
3122 if middle_whitespace != ' ' and middle_whitespace != '':
3123 error(filename, linenum, 'whitespace/todo', 2,
3124 'TODO(my_username) should be followed by a space')
3125
3126 # If the comment contains an alphanumeric character, there
avakulenko@google.com255f2be2014-12-05 22:19:55 +00003127 # should be a space somewhere between it and the // unless
3128 # it's a /// or //! Doxygen comment.
3129 if (Match(r'//[^ ]*\w', comment) and
3130 not Match(r'(///|//\!)(\s+|$)', comment)):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003131 error(filename, linenum, 'whitespace/comments', 4,
3132 'Should have a space between // and comment')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003133
avakulenko@google.com255f2be2014-12-05 22:19:55 +00003134
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003135def CheckSpacing(filename, clean_lines, linenum, nesting_state, error):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003136 """Checks for the correctness of various spacing issues in the code.
3137
3138 Things we check for: spaces around operators, spaces after
3139 if/for/while/switch, no spaces around parens in function calls, two
3140 spaces between code and comment, don't start a block with a blank
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003141 line, don't end a function with a blank line, don't add a blank line
3142 after public/protected/private, don't have too many blank lines in a row.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003143
3144 Args:
3145 filename: The name of the current file.
3146 clean_lines: A CleansedLines instance containing the file.
3147 linenum: The number of the line to check.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003148 nesting_state: A NestingState instance which maintains information about
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003149 the current stack of nested blocks being parsed.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003150 error: The function to call with any errors found.
3151 """
3152
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003153 # Don't use "elided" lines here, otherwise we can't check commented lines.
3154 # Don't want to use "raw" either, because we don't want to check inside C++11
3155 # raw strings,
3156 raw = clean_lines.lines_without_raw_strings
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003157 line = raw[linenum]
3158
3159 # Before nixing comments, check if the line is blank for no good
3160 # reason. This includes the first line after a block is opened, and
3161 # blank lines at the end of a function (ie, right before a line like '}'
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003162 #
3163 # Skip all the blank line checks if we are immediately inside a
3164 # namespace body. In other words, don't issue blank line warnings
3165 # for this block:
3166 # namespace {
3167 #
3168 # }
3169 #
3170 # A warning about missing end of namespace comments will be issued instead.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003171 #
3172 # Also skip blank line checks for 'extern "C"' blocks, which are formatted
3173 # like namespaces.
3174 if (IsBlankLine(line) and
3175 not nesting_state.InNamespaceBody() and
3176 not nesting_state.InExternC()):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003177 elided = clean_lines.elided
3178 prev_line = elided[linenum - 1]
3179 prevbrace = prev_line.rfind('{')
3180 # TODO(unknown): Don't complain if line before blank line, and line after,
3181 # both start with alnums and are indented the same amount.
3182 # This ignores whitespace at the start of a namespace block
3183 # because those are not usually indented.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003184 if prevbrace != -1 and prev_line[prevbrace:].find('}') == -1:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003185 # OK, we have a blank line at the start of a code block. Before we
3186 # complain, we check if it is an exception to the rule: The previous
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003187 # non-empty line has the parameters of a function header that are indented
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003188 # 4 spaces (because they did not fit in a 80 column line when placed on
3189 # the same line as the function name). We also check for the case where
3190 # the previous line is indented 6 spaces, which may happen when the
3191 # initializers of a constructor do not fit into a 80 column line.
3192 exception = False
3193 if Match(r' {6}\w', prev_line): # Initializer list?
3194 # We are looking for the opening column of initializer list, which
3195 # should be indented 4 spaces to cause 6 space indentation afterwards.
3196 search_position = linenum-2
3197 while (search_position >= 0
3198 and Match(r' {6}\w', elided[search_position])):
3199 search_position -= 1
3200 exception = (search_position >= 0
3201 and elided[search_position][:5] == ' :')
3202 else:
3203 # Search for the function arguments or an initializer list. We use a
3204 # simple heuristic here: If the line is indented 4 spaces; and we have a
3205 # closing paren, without the opening paren, followed by an opening brace
3206 # or colon (for initializer lists) we assume that it is the last line of
3207 # a function header. If we have a colon indented 4 spaces, it is an
3208 # initializer list.
3209 exception = (Match(r' {4}\w[^\(]*\)\s*(const\s*)?(\{\s*$|:)',
3210 prev_line)
3211 or Match(r' {4}:', prev_line))
3212
3213 if not exception:
3214 error(filename, linenum, 'whitespace/blank_line', 2,
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003215 'Redundant blank line at the start of a code block '
3216 'should be deleted.')
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003217 # Ignore blank lines at the end of a block in a long if-else
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003218 # chain, like this:
3219 # if (condition1) {
3220 # // Something followed by a blank line
3221 #
3222 # } else if (condition2) {
3223 # // Something else
3224 # }
3225 if linenum + 1 < clean_lines.NumLines():
3226 next_line = raw[linenum + 1]
3227 if (next_line
3228 and Match(r'\s*}', next_line)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003229 and next_line.find('} else ') == -1):
3230 error(filename, linenum, 'whitespace/blank_line', 3,
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003231 'Redundant blank line at the end of a code block '
3232 'should be deleted.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003233
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003234 matched = Match(r'\s*(public|protected|private):', prev_line)
3235 if matched:
3236 error(filename, linenum, 'whitespace/blank_line', 3,
3237 'Do not leave a blank line after "%s:"' % matched.group(1))
3238
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003239 # Next, check comments
3240 next_line_start = 0
3241 if linenum + 1 < clean_lines.NumLines():
3242 next_line = raw[linenum + 1]
3243 next_line_start = len(next_line) - len(next_line.lstrip())
3244 CheckComment(line, filename, linenum, next_line_start, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003245
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003246 # get rid of comments and strings
3247 line = clean_lines.elided[linenum]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003248
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003249 # You shouldn't have spaces before your brackets, except maybe after
Alex Lightac54b8d2022-01-20 13:02:48 +00003250 # 'delete []', 'return []() {};', 'auto [abc, ...] = ...;' or in the case of
3251 # c++ attributes like 'class [[clang::lto_visibility_public]] MyClass'.
Derek Morrisb8265f12020-04-16 18:40:27 +00003252 if (Search(r'\w\s+\[', line)
Alex Lightac54b8d2022-01-20 13:02:48 +00003253 and not Search(r'(?:auto&?|delete|return)\s+\[', line)
Derek Morrisb8265f12020-04-16 18:40:27 +00003254 and not Search(r'\s+\[\[', line)):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003255 error(filename, linenum, 'whitespace/braces', 5,
3256 'Extra space before [')
3257
3258 # In range-based for, we wanted spaces before and after the colon, but
3259 # not around "::" tokens that might appear.
3260 if (Search(r'for *\(.*[^:]:[^: ]', line) or
3261 Search(r'for *\(.*[^: ]:[^:]', line)):
3262 error(filename, linenum, 'whitespace/forcolon', 2,
3263 'Missing space around colon in range-based for loop')
3264
3265
3266def CheckOperatorSpacing(filename, clean_lines, linenum, error):
3267 """Checks for horizontal spacing around operators.
3268
3269 Args:
3270 filename: The name of the current file.
3271 clean_lines: A CleansedLines instance containing the file.
3272 linenum: The number of the line to check.
3273 error: The function to call with any errors found.
3274 """
3275 line = clean_lines.elided[linenum]
3276
3277 # Don't try to do spacing checks for operator methods. Do this by
3278 # replacing the troublesome characters with something else,
3279 # preserving column position for all other characters.
3280 #
3281 # The replacement is done repeatedly to avoid false positives from
3282 # operators that call operators.
3283 while True:
3284 match = Match(r'^(.*\boperator\b)(\S+)(\s*\(.*)$', line)
3285 if match:
3286 line = match.group(1) + ('_' * len(match.group(2))) + match.group(3)
3287 else:
3288 break
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003289
3290 # We allow no-spaces around = within an if: "if ( (a=Foo()) == 0 )".
3291 # Otherwise not. Note we only check for non-spaces on *both* sides;
3292 # sometimes people put non-spaces on one side when aligning ='s among
3293 # many lines (not that this is behavior that I approve of...)
avakulenko@google.com255f2be2014-12-05 22:19:55 +00003294 if ((Search(r'[\w.]=', line) or
3295 Search(r'=[\w.]', line))
3296 and not Search(r'\b(if|while|for) ', line)
3297 # Operators taken from [lex.operators] in C++11 standard.
3298 and not Search(r'(>=|<=|==|!=|&=|\^=|\|=|\+=|\*=|\/=|\%=)', line)
3299 and not Search(r'operator=', line)):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003300 error(filename, linenum, 'whitespace/operators', 4,
3301 'Missing spaces around =')
3302
3303 # It's ok not to have spaces around binary operators like + - * /, but if
3304 # there's too little whitespace, we get concerned. It's hard to tell,
3305 # though, so we punt on this one for now. TODO.
3306
3307 # You should always have whitespace around binary operators.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003308 #
3309 # Check <= and >= first to avoid false positives with < and >, then
3310 # check non-include lines for spacing around < and >.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003311 #
3312 # If the operator is followed by a comma, assume it's be used in a
3313 # macro context and don't do any checks. This avoids false
3314 # positives.
3315 #
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003316 # Note that && is not included here. This is because there are too
3317 # many false positives due to RValue references.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003318 match = Search(r'[^<>=!\s](==|!=|<=|>=|\|\|)[^<>=!\s,;\)]', line)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003319 if match:
3320 error(filename, linenum, 'whitespace/operators', 3,
3321 'Missing spaces around %s' % match.group(1))
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003322 elif not Match(r'#.*include', line):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003323 # Look for < that is not surrounded by spaces. This is only
3324 # triggered if both sides are missing spaces, even though
3325 # technically should should flag if at least one side is missing a
3326 # space. This is done to avoid some false positives with shifts.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003327 match = Match(r'^(.*[^\s<])<[^\s=<,]', line)
3328 if match:
3329 (_, _, end_pos) = CloseExpression(
3330 clean_lines, linenum, len(match.group(1)))
3331 if end_pos <= -1:
3332 error(filename, linenum, 'whitespace/operators', 3,
3333 'Missing spaces around <')
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003334
3335 # Look for > that is not surrounded by spaces. Similar to the
3336 # above, we only trigger if both sides are missing spaces to avoid
3337 # false positives with shifts.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003338 match = Match(r'^(.*[^-\s>])>[^\s=>,]', line)
3339 if match:
3340 (_, _, start_pos) = ReverseCloseExpression(
3341 clean_lines, linenum, len(match.group(1)))
3342 if start_pos <= -1:
3343 error(filename, linenum, 'whitespace/operators', 3,
3344 'Missing spaces around >')
3345
3346 # We allow no-spaces around << when used like this: 10<<20, but
3347 # not otherwise (particularly, not when used as streams)
avakulenko@google.com59146752014-08-11 20:20:55 +00003348 #
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003349 # We also allow operators following an opening parenthesis, since
3350 # those tend to be macros that deal with operators.
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003351 match = Search(r'(operator|[^\s(<])(?:L|UL|LL|ULL|l|ul|ll|ull)?<<([^\s,=<])', line)
avakulenko@google.com255f2be2014-12-05 22:19:55 +00003352 if (match and not (match.group(1).isdigit() and match.group(2).isdigit()) and
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003353 not (match.group(1) == 'operator' and match.group(2) == ';')):
3354 error(filename, linenum, 'whitespace/operators', 3,
3355 'Missing spaces around <<')
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003356
3357 # We allow no-spaces around >> for almost anything. This is because
3358 # C++11 allows ">>" to close nested templates, which accounts for
3359 # most cases when ">>" is not followed by a space.
3360 #
3361 # We still warn on ">>" followed by alpha character, because that is
3362 # likely due to ">>" being used for right shifts, e.g.:
3363 # value >> alpha
3364 #
3365 # When ">>" is used to close templates, the alphanumeric letter that
3366 # follows would be part of an identifier, and there should still be
3367 # a space separating the template type and the identifier.
3368 # type<type<type>> alpha
3369 match = Search(r'>>[a-zA-Z_]', line)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003370 if match:
3371 error(filename, linenum, 'whitespace/operators', 3,
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003372 'Missing spaces around >>')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003373
3374 # There shouldn't be space around unary operators
3375 match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line)
3376 if match:
3377 error(filename, linenum, 'whitespace/operators', 4,
3378 'Extra space for operator %s' % match.group(1))
3379
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003380
3381def CheckParenthesisSpacing(filename, clean_lines, linenum, error):
3382 """Checks for horizontal spacing around parentheses.
3383
3384 Args:
3385 filename: The name of the current file.
3386 clean_lines: A CleansedLines instance containing the file.
3387 linenum: The number of the line to check.
3388 error: The function to call with any errors found.
3389 """
3390 line = clean_lines.elided[linenum]
3391
3392 # No spaces after an if, while, switch, or for
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003393 match = Search(r' (if\(|for\(|while\(|switch\()', line)
3394 if match:
3395 error(filename, linenum, 'whitespace/parens', 5,
3396 'Missing space before ( in %s' % match.group(1))
3397
3398 # For if/for/while/switch, the left and right parens should be
3399 # consistent about how many spaces are inside the parens, and
3400 # there should either be zero or one spaces inside the parens.
3401 # We don't want: "if ( foo)" or "if ( foo )".
erg@google.com6317a9c2009-06-25 00:28:19 +00003402 # Exception: "for ( ; foo; bar)" and "for (foo; bar; )" are allowed.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003403 match = Search(r'\b(if|for|while|switch)\s*'
3404 r'\(([ ]*)(.).*[^ ]+([ ]*)\)\s*{\s*$',
3405 line)
3406 if match:
3407 if len(match.group(2)) != len(match.group(4)):
3408 if not (match.group(3) == ';' and
erg@google.com6317a9c2009-06-25 00:28:19 +00003409 len(match.group(2)) == 1 + len(match.group(4)) or
3410 not match.group(2) and Search(r'\bfor\s*\(.*; \)', line)):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003411 error(filename, linenum, 'whitespace/parens', 5,
3412 'Mismatching spaces inside () in %s' % match.group(1))
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003413 if len(match.group(2)) not in [0, 1]:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003414 error(filename, linenum, 'whitespace/parens', 5,
3415 'Should have zero or one spaces inside ( and ) in %s' %
3416 match.group(1))
3417
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003418
3419def CheckCommaSpacing(filename, clean_lines, linenum, error):
3420 """Checks for horizontal spacing near commas and semicolons.
3421
3422 Args:
3423 filename: The name of the current file.
3424 clean_lines: A CleansedLines instance containing the file.
3425 linenum: The number of the line to check.
3426 error: The function to call with any errors found.
3427 """
3428 raw = clean_lines.lines_without_raw_strings
3429 line = clean_lines.elided[linenum]
3430
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003431 # 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 +00003432 #
3433 # This does not apply when the non-space character following the
3434 # comma is another comma, since the only time when that happens is
3435 # for empty macro arguments.
3436 #
3437 # We run this check in two passes: first pass on elided lines to
3438 # verify that lines contain missing whitespaces, second pass on raw
3439 # lines to confirm that those missing whitespaces are not due to
3440 # elided comments.
avakulenko@google.com59146752014-08-11 20:20:55 +00003441 if (Search(r',[^,\s]', ReplaceAll(r'\boperator\s*,\s*\(', 'F(', line)) and
3442 Search(r',[^,\s]', raw[linenum])):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003443 error(filename, linenum, 'whitespace/comma', 3,
3444 'Missing space after ,')
3445
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003446 # You should always have a space after a semicolon
3447 # except for few corner cases
3448 # TODO(unknown): clarify if 'if (1) { return 1;}' is requires one more
3449 # space after ;
3450 if Search(r';[^\s};\\)/]', line):
3451 error(filename, linenum, 'whitespace/semicolon', 3,
3452 'Missing space after ;')
3453
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003454
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003455def _IsType(clean_lines, nesting_state, expr):
3456 """Check if expression looks like a type name, returns true if so.
3457
3458 Args:
3459 clean_lines: A CleansedLines instance containing the file.
3460 nesting_state: A NestingState instance which maintains information about
3461 the current stack of nested blocks being parsed.
3462 expr: The expression to check.
3463 Returns:
3464 True, if token looks like a type.
3465 """
3466 # Keep only the last token in the expression
3467 last_word = Match(r'^.*(\b\S+)$', expr)
3468 if last_word:
3469 token = last_word.group(1)
3470 else:
3471 token = expr
3472
3473 # Match native types and stdint types
3474 if _TYPES.match(token):
3475 return True
3476
3477 # Try a bit harder to match templated types. Walk up the nesting
3478 # stack until we find something that resembles a typename
3479 # declaration for what we are looking for.
3480 typename_pattern = (r'\b(?:typename|class|struct)\s+' + re.escape(token) +
3481 r'\b')
3482 block_index = len(nesting_state.stack) - 1
3483 while block_index >= 0:
3484 if isinstance(nesting_state.stack[block_index], _NamespaceInfo):
3485 return False
3486
3487 # Found where the opening brace is. We want to scan from this
3488 # line up to the beginning of the function, minus a few lines.
3489 # template <typename Type1, // stop scanning here
3490 # ...>
3491 # class C
3492 # : public ... { // start scanning here
3493 last_line = nesting_state.stack[block_index].starting_linenum
3494
3495 next_block_start = 0
3496 if block_index > 0:
3497 next_block_start = nesting_state.stack[block_index - 1].starting_linenum
3498 first_line = last_line
3499 while first_line >= next_block_start:
3500 if clean_lines.elided[first_line].find('template') >= 0:
3501 break
3502 first_line -= 1
3503 if first_line < next_block_start:
3504 # Didn't find any "template" keyword before reaching the next block,
3505 # there are probably no template things to check for this block
3506 block_index -= 1
3507 continue
3508
3509 # Look for typename in the specified range
Edward Lemur6d31ed52019-12-02 23:00:00 +00003510 for i in range(first_line, last_line + 1, 1):
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003511 if Search(typename_pattern, clean_lines.elided[i]):
3512 return True
3513 block_index -= 1
3514
3515 return False
3516
3517
3518def CheckBracesSpacing(filename, clean_lines, linenum, nesting_state, error):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003519 """Checks for horizontal spacing near commas.
3520
3521 Args:
3522 filename: The name of the current file.
3523 clean_lines: A CleansedLines instance containing the file.
3524 linenum: The number of the line to check.
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003525 nesting_state: A NestingState instance which maintains information about
3526 the current stack of nested blocks being parsed.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003527 error: The function to call with any errors found.
3528 """
3529 line = clean_lines.elided[linenum]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003530
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003531 # Except after an opening paren, or after another opening brace (in case of
3532 # an initializer list, for instance), you should have spaces before your
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003533 # braces when they are delimiting blocks, classes, namespaces etc.
3534 # And since you should never have braces at the beginning of a line,
3535 # this is an easy test. Except that braces used for initialization don't
3536 # follow the same rule; we often don't want spaces before those.
avakulenko@google.com255f2be2014-12-05 22:19:55 +00003537 match = Match(r'^(.*[^ ({>]){', line)
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003538
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003539 if match:
3540 # Try a bit harder to check for brace initialization. This
3541 # happens in one of the following forms:
3542 # Constructor() : initializer_list_{} { ... }
3543 # Constructor{}.MemberFunction()
3544 # Type variable{};
3545 # FunctionCall(type{}, ...);
3546 # LastArgument(..., type{});
3547 # LOG(INFO) << type{} << " ...";
3548 # map_of_type[{...}] = ...;
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003549 # ternary = expr ? new type{} : nullptr;
3550 # OuterTemplate<InnerTemplateConstructor<Type>{}>
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003551 #
3552 # We check for the character following the closing brace, and
3553 # silence the warning if it's one of those listed above, i.e.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003554 # "{.;,)<>]:".
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003555 #
3556 # To account for nested initializer list, we allow any number of
3557 # closing braces up to "{;,)<". We can't simply silence the
3558 # warning on first sight of closing brace, because that would
3559 # cause false negatives for things that are not initializer lists.
3560 # Silence this: But not this:
3561 # Outer{ if (...) {
3562 # Inner{...} if (...){ // Missing space before {
3563 # }; }
3564 #
3565 # There is a false negative with this approach if people inserted
3566 # spurious semicolons, e.g. "if (cond){};", but we will catch the
3567 # spurious semicolon with a separate check.
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003568 leading_text = match.group(1)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003569 (endline, endlinenum, endpos) = CloseExpression(
3570 clean_lines, linenum, len(match.group(1)))
3571 trailing_text = ''
3572 if endpos > -1:
3573 trailing_text = endline[endpos:]
Edward Lemur6d31ed52019-12-02 23:00:00 +00003574 for offset in range(endlinenum + 1,
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003575 min(endlinenum + 3, clean_lines.NumLines() - 1)):
3576 trailing_text += clean_lines.elided[offset]
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003577 # We also suppress warnings for `uint64_t{expression}` etc., as the style
3578 # guide recommends brace initialization for integral types to avoid
3579 # overflow/truncation.
3580 if (not Match(r'^[\s}]*[{.;,)<>\]:]', trailing_text)
3581 and not _IsType(clean_lines, nesting_state, leading_text)):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003582 error(filename, linenum, 'whitespace/braces', 5,
3583 'Missing space before {')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003584
3585 # Make sure '} else {' has spaces.
3586 if Search(r'}else', line):
3587 error(filename, linenum, 'whitespace/braces', 5,
3588 'Missing space before else')
3589
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003590 # You shouldn't have a space before a semicolon at the end of the line.
3591 # There's a special case for "for" since the style guide allows space before
3592 # the semicolon there.
3593 if Search(r':\s*;\s*$', line):
3594 error(filename, linenum, 'whitespace/semicolon', 5,
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003595 'Semicolon defining empty statement. Use {} instead.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003596 elif Search(r'^\s*;\s*$', line):
3597 error(filename, linenum, 'whitespace/semicolon', 5,
3598 'Line contains only semicolon. If this should be an empty statement, '
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003599 'use {} instead.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003600 elif (Search(r'\s+;\s*$', line) and
3601 not Search(r'\bfor\b', line)):
3602 error(filename, linenum, 'whitespace/semicolon', 5,
3603 'Extra space before last semicolon. If this should be an empty '
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003604 'statement, use {} instead.')
3605
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003606
3607def IsDecltype(clean_lines, linenum, column):
3608 """Check if the token ending on (linenum, column) is decltype().
3609
3610 Args:
3611 clean_lines: A CleansedLines instance containing the file.
3612 linenum: the number of the line to check.
3613 column: end column of the token to check.
3614 Returns:
3615 True if this token is decltype() expression, False otherwise.
3616 """
3617 (text, _, start_col) = ReverseCloseExpression(clean_lines, linenum, column)
3618 if start_col < 0:
3619 return False
3620 if Search(r'\bdecltype\s*$', text[0:start_col]):
3621 return True
3622 return False
3623
3624
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003625def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error):
3626 """Checks for additional blank line issues related to sections.
3627
3628 Currently the only thing checked here is blank line before protected/private.
3629
3630 Args:
3631 filename: The name of the current file.
3632 clean_lines: A CleansedLines instance containing the file.
3633 class_info: A _ClassInfo objects.
3634 linenum: The number of the line to check.
3635 error: The function to call with any errors found.
3636 """
3637 # Skip checks if the class is small, where small means 25 lines or less.
3638 # 25 lines seems like a good cutoff since that's the usual height of
3639 # terminals, and any class that can't fit in one screen can't really
3640 # be considered "small".
3641 #
3642 # Also skip checks if we are on the first line. This accounts for
3643 # classes that look like
3644 # class Foo { public: ... };
3645 #
3646 # If we didn't find the end of the class, last_line would be zero,
3647 # and the check will be skipped by the first condition.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003648 if (class_info.last_line - class_info.starting_linenum <= 24 or
3649 linenum <= class_info.starting_linenum):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003650 return
3651
3652 matched = Match(r'\s*(public|protected|private):', clean_lines.lines[linenum])
3653 if matched:
3654 # Issue warning if the line before public/protected/private was
3655 # not a blank line, but don't do this if the previous line contains
3656 # "class" or "struct". This can happen two ways:
3657 # - We are at the beginning of the class.
3658 # - We are forward-declaring an inner class that is semantically
3659 # private, but needed to be public for implementation reasons.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003660 # Also ignores cases where the previous line ends with a backslash as can be
3661 # common when defining classes in C macros.
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003662 prev_line = clean_lines.lines[linenum - 1]
3663 if (not IsBlankLine(prev_line) and
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003664 not Search(r'\b(class|struct)\b', prev_line) and
3665 not Search(r'\\$', prev_line)):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003666 # Try a bit harder to find the beginning of the class. This is to
3667 # account for multi-line base-specifier lists, e.g.:
3668 # class Derived
3669 # : public Base {
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003670 end_class_head = class_info.starting_linenum
3671 for i in range(class_info.starting_linenum, linenum):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003672 if Search(r'\{\s*$', clean_lines.lines[i]):
3673 end_class_head = i
3674 break
3675 if end_class_head < linenum - 1:
3676 error(filename, linenum, 'whitespace/blank_line', 3,
3677 '"%s:" should be preceded by a blank line' % matched.group(1))
3678
3679
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003680def GetPreviousNonBlankLine(clean_lines, linenum):
3681 """Return the most recent non-blank line and its line number.
3682
3683 Args:
3684 clean_lines: A CleansedLines instance containing the file contents.
3685 linenum: The number of the line to check.
3686
3687 Returns:
3688 A tuple with two elements. The first element is the contents of the last
3689 non-blank line before the current line, or the empty string if this is the
3690 first non-blank line. The second is the line number of that line, or -1
3691 if this is the first non-blank line.
3692 """
3693
3694 prevlinenum = linenum - 1
3695 while prevlinenum >= 0:
3696 prevline = clean_lines.elided[prevlinenum]
3697 if not IsBlankLine(prevline): # if not a blank line...
3698 return (prevline, prevlinenum)
3699 prevlinenum -= 1
3700 return ('', -1)
3701
3702
3703def CheckBraces(filename, clean_lines, linenum, error):
3704 """Looks for misplaced braces (e.g. at the end of line).
3705
3706 Args:
3707 filename: The name of the current file.
3708 clean_lines: A CleansedLines instance containing the file.
3709 linenum: The number of the line to check.
3710 error: The function to call with any errors found.
3711 """
3712
3713 line = clean_lines.elided[linenum] # get rid of comments and strings
3714
3715 if Match(r'\s*{\s*$', line):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003716 # We allow an open brace to start a line in the case where someone is using
3717 # braces in a block to explicitly create a new scope, which is commonly used
3718 # to control the lifetime of stack-allocated variables. Braces are also
3719 # used for brace initializers inside function calls. We don't detect this
3720 # perfectly: we just don't complain if the last non-whitespace character on
3721 # the previous non-blank line is ',', ';', ':', '(', '{', or '}', or if the
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003722 # previous line starts a preprocessor block. We also allow a brace on the
3723 # following line if it is part of an array initialization and would not fit
3724 # within the 80 character limit of the preceding line.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003725 prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003726 if (not Search(r'[,;:}{(]\s*$', prevline) and
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003727 not Match(r'\s*#', prevline) and
3728 not (GetLineWidth(prevline) > _line_length - 2 and '[]' in prevline)):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003729 error(filename, linenum, 'whitespace/braces', 4,
3730 '{ should almost always be at the end of the previous line')
3731
3732 # An else clause should be on the same line as the preceding closing brace.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003733 if Match(r'\s*else\b\s*(?:if\b|\{|$)', line):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003734 prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
3735 if Match(r'\s*}\s*$', prevline):
3736 error(filename, linenum, 'whitespace/newline', 4,
3737 'An else should appear on the same line as the preceding }')
3738
3739 # If braces come on one side of an else, they should be on both.
3740 # However, we have to worry about "else if" that spans multiple lines!
Darius Maa7d7e42022-05-13 14:54:21 +00003741 if Search(r'else if\s*(?:constexpr\s*)?\(', line): # could be multi-line if
3742 brace_on_left = bool(Search(r'}\s*else if\s*(?:constexpr\s*)?\(', line))
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003743 # find the ( after the if
3744 pos = line.find('else if')
3745 pos = line.find('(', pos)
3746 if pos > 0:
3747 (endline, _, endpos) = CloseExpression(clean_lines, linenum, pos)
3748 brace_on_right = endline[endpos:].find('{') != -1
3749 if brace_on_left != brace_on_right: # must be brace after if
3750 error(filename, linenum, 'readability/braces', 5,
3751 'If an else has a brace on one side, it should have it on both')
3752 elif Search(r'}\s*else[^{]*$', line) or Match(r'[^}]*else\s*{', line):
3753 error(filename, linenum, 'readability/braces', 5,
3754 'If an else has a brace on one side, it should have it on both')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003755
3756 # Likewise, an else should never have the else clause on the same line
3757 if Search(r'\belse [^\s{]', line) and not Search(r'\belse if\b', line):
3758 error(filename, linenum, 'whitespace/newline', 4,
3759 'Else clause should never be on same line as else (use 2 lines)')
3760
3761 # In the same way, a do/while should never be on one line
3762 if Match(r'\s*do [^\s{]', line):
3763 error(filename, linenum, 'whitespace/newline', 4,
3764 'do/while clauses should not be on a single line')
3765
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003766 # Check single-line if/else bodies. The style guide says 'curly braces are not
3767 # required for single-line statements'. We additionally allow multi-line,
3768 # single statements, but we reject anything with more than one semicolon in
3769 # it. This means that the first semicolon after the if should be at the end of
3770 # its line, and the line after that should have an indent level equal to or
3771 # lower than the if. We also check for ambiguous if/else nesting without
3772 # braces.
Darius Maa7d7e42022-05-13 14:54:21 +00003773 if_else_match = Search(r'\b(if\s*(?:constexpr\s*)?\(|else\b)', line)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003774 if if_else_match and not Match(r'\s*#', line):
3775 if_indent = GetIndentLevel(line)
3776 endline, endlinenum, endpos = line, linenum, if_else_match.end()
Darius Maa7d7e42022-05-13 14:54:21 +00003777 if_match = Search(r'\bif\s*(?:constexpr\s*)?\(', line)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003778 if if_match:
3779 # This could be a multiline if condition, so find the end first.
3780 pos = if_match.end() - 1
3781 (endline, endlinenum, endpos) = CloseExpression(clean_lines, linenum, pos)
3782 # Check for an opening brace, either directly after the if or on the next
3783 # line. If found, this isn't a single-statement conditional.
3784 if (not Match(r'\s*{', endline[endpos:])
3785 and not (Match(r'\s*$', endline[endpos:])
3786 and endlinenum < (len(clean_lines.elided) - 1)
3787 and Match(r'\s*{', clean_lines.elided[endlinenum + 1]))):
3788 while (endlinenum < len(clean_lines.elided)
3789 and ';' not in clean_lines.elided[endlinenum][endpos:]):
3790 endlinenum += 1
3791 endpos = 0
3792 if endlinenum < len(clean_lines.elided):
3793 endline = clean_lines.elided[endlinenum]
3794 # We allow a mix of whitespace and closing braces (e.g. for one-liner
3795 # methods) and a single \ after the semicolon (for macros)
3796 endpos = endline.find(';')
3797 if not Match(r';[\s}]*(\\?)$', endline[endpos:]):
avakulenko@google.com59146752014-08-11 20:20:55 +00003798 # Semicolon isn't the last character, there's something trailing.
3799 # Output a warning if the semicolon is not contained inside
3800 # a lambda expression.
3801 if not Match(r'^[^{};]*\[[^\[\]]*\][^{}]*\{[^{}]*\}\s*\)*[;,]\s*$',
3802 endline):
3803 error(filename, linenum, 'readability/braces', 4,
3804 'If/else bodies with multiple statements require braces')
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003805 elif endlinenum < len(clean_lines.elided) - 1:
3806 # Make sure the next line is dedented
3807 next_line = clean_lines.elided[endlinenum + 1]
3808 next_indent = GetIndentLevel(next_line)
3809 # With ambiguous nested if statements, this will error out on the
3810 # if that *doesn't* match the else, regardless of whether it's the
3811 # inner one or outer one.
3812 if (if_match and Match(r'\s*else\b', next_line)
3813 and next_indent != if_indent):
3814 error(filename, linenum, 'readability/braces', 4,
3815 'Else clause should be indented at the same level as if. '
3816 'Ambiguous nested if/else chains require braces.')
3817 elif next_indent > if_indent:
3818 error(filename, linenum, 'readability/braces', 4,
3819 'If/else bodies with multiple statements require braces')
3820
3821
3822def CheckTrailingSemicolon(filename, clean_lines, linenum, error):
3823 """Looks for redundant trailing semicolon.
3824
3825 Args:
3826 filename: The name of the current file.
3827 clean_lines: A CleansedLines instance containing the file.
3828 linenum: The number of the line to check.
3829 error: The function to call with any errors found.
3830 """
3831
3832 line = clean_lines.elided[linenum]
3833
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003834 # Block bodies should not be followed by a semicolon. Due to C++11
3835 # brace initialization, there are more places where semicolons are
Ayu Ishii09858612020-06-26 18:00:52 +00003836 # required than not, so we use an allowlist approach to check these
3837 # rather than a blocklist. These are the places where "};" should
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003838 # be replaced by just "}":
3839 # 1. Some flavor of block following closing parenthesis:
3840 # for (;;) {};
3841 # while (...) {};
3842 # switch (...) {};
3843 # Function(...) {};
3844 # if (...) {};
3845 # if (...) else if (...) {};
3846 #
3847 # 2. else block:
3848 # if (...) else {};
3849 #
3850 # 3. const member function:
3851 # Function(...) const {};
3852 #
3853 # 4. Block following some statement:
3854 # x = 42;
3855 # {};
3856 #
3857 # 5. Block at the beginning of a function:
3858 # Function(...) {
3859 # {};
3860 # }
3861 #
3862 # Note that naively checking for the preceding "{" will also match
3863 # braces inside multi-dimensional arrays, but this is fine since
3864 # that expression will not contain semicolons.
3865 #
3866 # 6. Block following another block:
3867 # while (true) {}
3868 # {};
3869 #
3870 # 7. End of namespaces:
3871 # namespace {};
3872 #
3873 # These semicolons seems far more common than other kinds of
3874 # redundant semicolons, possibly due to people converting classes
3875 # to namespaces. For now we do not warn for this case.
3876 #
3877 # Try matching case 1 first.
3878 match = Match(r'^(.*\)\s*)\{', line)
3879 if match:
3880 # Matched closing parenthesis (case 1). Check the token before the
3881 # matching opening parenthesis, and don't warn if it looks like a
3882 # macro. This avoids these false positives:
3883 # - macro that defines a base class
3884 # - multi-line macro that defines a base class
3885 # - macro that defines the whole class-head
3886 #
3887 # But we still issue warnings for macros that we know are safe to
3888 # warn, specifically:
3889 # - TEST, TEST_F, TEST_P, MATCHER, MATCHER_P
3890 # - TYPED_TEST
3891 # - INTERFACE_DEF
3892 # - EXCLUSIVE_LOCKS_REQUIRED, SHARED_LOCKS_REQUIRED, LOCKS_EXCLUDED:
3893 #
Ayu Ishii09858612020-06-26 18:00:52 +00003894 # We implement an allowlist of safe macros instead of a blocklist of
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003895 # unsafe macros, even though the latter appears less frequently in
Ayu Ishii09858612020-06-26 18:00:52 +00003896 # google code and would have been easier to implement. This is because
3897 # the downside for getting the allowlist wrong means some extra
3898 # semicolons, while the downside for getting the blocklist wrong
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003899 # would result in compile errors.
3900 #
avakulenko@google.com255f2be2014-12-05 22:19:55 +00003901 # In addition to macros, we also don't want to warn on
3902 # - Compound literals
3903 # - Lambdas
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003904 # - alignas specifier with anonymous structs
3905 # - decltype
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003906 closing_brace_pos = match.group(1).rfind(')')
3907 opening_parenthesis = ReverseCloseExpression(
3908 clean_lines, linenum, closing_brace_pos)
3909 if opening_parenthesis[2] > -1:
3910 line_prefix = opening_parenthesis[0][0:opening_parenthesis[2]]
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003911 macro = Search(r'\b([A-Z_][A-Z0-9_]*)\s*$', line_prefix)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003912 func = Match(r'^(.*\])\s*$', line_prefix)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003913 if ((macro and
3914 macro.group(1) not in (
3915 'TEST', 'TEST_F', 'MATCHER', 'MATCHER_P', 'TYPED_TEST',
3916 'EXCLUSIVE_LOCKS_REQUIRED', 'SHARED_LOCKS_REQUIRED',
3917 'LOCKS_EXCLUDED', 'INTERFACE_DEF')) or
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003918 (func and not Search(r'\boperator\s*\[\s*\]', func.group(1))) or
avakulenko@google.com255f2be2014-12-05 22:19:55 +00003919 Search(r'\b(?:struct|union)\s+alignas\s*$', line_prefix) or
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003920 Search(r'\bdecltype$', line_prefix) or
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003921 Search(r'\s+=\s*$', line_prefix)):
3922 match = None
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003923 if (match and
3924 opening_parenthesis[1] > 1 and
3925 Search(r'\]\s*$', clean_lines.elided[opening_parenthesis[1] - 1])):
3926 # Multi-line lambda-expression
3927 match = None
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003928
3929 else:
3930 # Try matching cases 2-3.
3931 match = Match(r'^(.*(?:else|\)\s*const)\s*)\{', line)
3932 if not match:
3933 # Try matching cases 4-6. These are always matched on separate lines.
3934 #
3935 # Note that we can't simply concatenate the previous line to the
3936 # current line and do a single match, otherwise we may output
3937 # duplicate warnings for the blank line case:
3938 # if (cond) {
3939 # // blank line
3940 # }
3941 prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
3942 if prevline and Search(r'[;{}]\s*$', prevline):
3943 match = Match(r'^(\s*)\{', line)
3944
3945 # Check matching closing brace
3946 if match:
3947 (endline, endlinenum, endpos) = CloseExpression(
3948 clean_lines, linenum, len(match.group(1)))
3949 if endpos > -1 and Match(r'^\s*;', endline[endpos:]):
3950 # Current {} pair is eligible for semicolon check, and we have found
3951 # the redundant semicolon, output warning here.
3952 #
3953 # Note: because we are scanning forward for opening braces, and
3954 # outputting warnings for the matching closing brace, if there are
3955 # nested blocks with trailing semicolons, we will get the error
3956 # messages in reversed order.
3957 error(filename, endlinenum, 'readability/braces', 4,
3958 "You don't need a ; after a }")
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003959
3960
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003961def CheckEmptyBlockBody(filename, clean_lines, linenum, error):
3962 """Look for empty loop/conditional body with only a single semicolon.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003963
3964 Args:
3965 filename: The name of the current file.
3966 clean_lines: A CleansedLines instance containing the file.
3967 linenum: The number of the line to check.
3968 error: The function to call with any errors found.
3969 """
3970
3971 # Search for loop keywords at the beginning of the line. Because only
3972 # whitespaces are allowed before the keywords, this will also ignore most
3973 # do-while-loops, since those lines should start with closing brace.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003974 #
3975 # We also check "if" blocks here, since an empty conditional block
3976 # is likely an error.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003977 line = clean_lines.elided[linenum]
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003978 matched = Match(r'\s*(for|while|if)\s*\(', line)
3979 if matched:
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003980 # Find the end of the conditional expression.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003981 (end_line, end_linenum, end_pos) = CloseExpression(
3982 clean_lines, linenum, line.find('('))
3983
3984 # Output warning if what follows the condition expression is a semicolon.
3985 # No warning for all other cases, including whitespace or newline, since we
3986 # have a separate check for semicolons preceded by whitespace.
3987 if end_pos >= 0 and Match(r';', end_line[end_pos:]):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003988 if matched.group(1) == 'if':
3989 error(filename, end_linenum, 'whitespace/empty_conditional_body', 5,
3990 'Empty conditional bodies should use {}')
3991 else:
3992 error(filename, end_linenum, 'whitespace/empty_loop_body', 5,
3993 'Empty loop bodies should use {} or continue')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003994
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003995 # Check for if statements that have completely empty bodies (no comments)
3996 # and no else clauses.
3997 if end_pos >= 0 and matched.group(1) == 'if':
3998 # Find the position of the opening { for the if statement.
3999 # Return without logging an error if it has no brackets.
4000 opening_linenum = end_linenum
4001 opening_line_fragment = end_line[end_pos:]
4002 # Loop until EOF or find anything that's not whitespace or opening {.
4003 while not Search(r'^\s*\{', opening_line_fragment):
4004 if Search(r'^(?!\s*$)', opening_line_fragment):
4005 # Conditional has no brackets.
4006 return
4007 opening_linenum += 1
4008 if opening_linenum == len(clean_lines.elided):
4009 # Couldn't find conditional's opening { or any code before EOF.
4010 return
4011 opening_line_fragment = clean_lines.elided[opening_linenum]
4012 # Set opening_line (opening_line_fragment may not be entire opening line).
4013 opening_line = clean_lines.elided[opening_linenum]
4014
4015 # Find the position of the closing }.
4016 opening_pos = opening_line_fragment.find('{')
4017 if opening_linenum == end_linenum:
4018 # We need to make opening_pos relative to the start of the entire line.
4019 opening_pos += end_pos
4020 (closing_line, closing_linenum, closing_pos) = CloseExpression(
4021 clean_lines, opening_linenum, opening_pos)
4022 if closing_pos < 0:
4023 return
4024
4025 # Now construct the body of the conditional. This consists of the portion
4026 # of the opening line after the {, all lines until the closing line,
4027 # and the portion of the closing line before the }.
4028 if (clean_lines.raw_lines[opening_linenum] !=
4029 CleanseComments(clean_lines.raw_lines[opening_linenum])):
4030 # Opening line ends with a comment, so conditional isn't empty.
4031 return
4032 if closing_linenum > opening_linenum:
4033 # Opening line after the {. Ignore comments here since we checked above.
4034 body = list(opening_line[opening_pos+1:])
4035 # All lines until closing line, excluding closing line, with comments.
4036 body.extend(clean_lines.raw_lines[opening_linenum+1:closing_linenum])
4037 # Closing line before the }. Won't (and can't) have comments.
4038 body.append(clean_lines.elided[closing_linenum][:closing_pos-1])
4039 body = '\n'.join(body)
4040 else:
4041 # If statement has brackets and fits on a single line.
4042 body = opening_line[opening_pos+1:closing_pos-1]
4043
4044 # Check if the body is empty
4045 if not _EMPTY_CONDITIONAL_BODY_PATTERN.search(body):
4046 return
4047 # The body is empty. Now make sure there's not an else clause.
4048 current_linenum = closing_linenum
4049 current_line_fragment = closing_line[closing_pos:]
4050 # Loop until EOF or find anything that's not whitespace or else clause.
4051 while Search(r'^\s*$|^(?=\s*else)', current_line_fragment):
4052 if Search(r'^(?=\s*else)', current_line_fragment):
4053 # Found an else clause, so don't log an error.
4054 return
4055 current_linenum += 1
4056 if current_linenum == len(clean_lines.elided):
4057 break
4058 current_line_fragment = clean_lines.elided[current_linenum]
4059
4060 # The body is empty and there's no else clause until EOF or other code.
4061 error(filename, end_linenum, 'whitespace/empty_if_body', 4,
4062 ('If statement had no body and no else clause'))
4063
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004064
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004065def FindCheckMacro(line):
4066 """Find a replaceable CHECK-like macro.
4067
4068 Args:
4069 line: line to search on.
4070 Returns:
4071 (macro name, start position), or (None, -1) if no replaceable
4072 macro is found.
4073 """
4074 for macro in _CHECK_MACROS:
4075 i = line.find(macro)
4076 if i >= 0:
4077 # Find opening parenthesis. Do a regular expression match here
4078 # to make sure that we are matching the expected CHECK macro, as
4079 # opposed to some other macro that happens to contain the CHECK
4080 # substring.
4081 matched = Match(r'^(.*\b' + macro + r'\s*)\(', line)
4082 if not matched:
4083 continue
4084 return (macro, len(matched.group(1)))
4085 return (None, -1)
4086
4087
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004088def CheckCheck(filename, clean_lines, linenum, error):
4089 """Checks the use of CHECK and EXPECT macros.
4090
4091 Args:
4092 filename: The name of the current file.
4093 clean_lines: A CleansedLines instance containing the file.
4094 linenum: The number of the line to check.
4095 error: The function to call with any errors found.
4096 """
4097
4098 # Decide the set of replacement macros that should be suggested
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004099 lines = clean_lines.elided
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004100 (check_macro, start_pos) = FindCheckMacro(lines[linenum])
4101 if not check_macro:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004102 return
4103
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004104 # Find end of the boolean expression by matching parentheses
4105 (last_line, end_line, end_pos) = CloseExpression(
4106 clean_lines, linenum, start_pos)
4107 if end_pos < 0:
4108 return
avakulenko@google.com59146752014-08-11 20:20:55 +00004109
4110 # If the check macro is followed by something other than a
4111 # semicolon, assume users will log their own custom error messages
4112 # and don't suggest any replacements.
4113 if not Match(r'\s*;', last_line[end_pos:]):
4114 return
4115
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004116 if linenum == end_line:
4117 expression = lines[linenum][start_pos + 1:end_pos - 1]
4118 else:
4119 expression = lines[linenum][start_pos + 1:]
Edward Lemur6d31ed52019-12-02 23:00:00 +00004120 for i in range(linenum + 1, end_line):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004121 expression += lines[i]
4122 expression += last_line[0:end_pos - 1]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004123
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004124 # Parse expression so that we can take parentheses into account.
4125 # This avoids false positives for inputs like "CHECK((a < 4) == b)",
4126 # which is not replaceable by CHECK_LE.
4127 lhs = ''
4128 rhs = ''
4129 operator = None
4130 while expression:
4131 matched = Match(r'^\s*(<<|<<=|>>|>>=|->\*|->|&&|\|\||'
4132 r'==|!=|>=|>|<=|<|\()(.*)$', expression)
4133 if matched:
4134 token = matched.group(1)
4135 if token == '(':
4136 # Parenthesized operand
4137 expression = matched.group(2)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004138 (end, _) = FindEndOfExpressionInLine(expression, 0, ['('])
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004139 if end < 0:
4140 return # Unmatched parenthesis
4141 lhs += '(' + expression[0:end]
4142 expression = expression[end:]
4143 elif token in ('&&', '||'):
4144 # Logical and/or operators. This means the expression
4145 # contains more than one term, for example:
4146 # CHECK(42 < a && a < b);
4147 #
4148 # These are not replaceable with CHECK_LE, so bail out early.
4149 return
4150 elif token in ('<<', '<<=', '>>', '>>=', '->*', '->'):
4151 # Non-relational operator
4152 lhs += token
4153 expression = matched.group(2)
4154 else:
4155 # Relational operator
4156 operator = token
4157 rhs = matched.group(2)
4158 break
4159 else:
4160 # Unparenthesized operand. Instead of appending to lhs one character
4161 # at a time, we do another regular expression match to consume several
4162 # characters at once if possible. Trivial benchmark shows that this
4163 # is more efficient when the operands are longer than a single
4164 # character, which is generally the case.
4165 matched = Match(r'^([^-=!<>()&|]+)(.*)$', expression)
4166 if not matched:
4167 matched = Match(r'^(\s*\S)(.*)$', expression)
4168 if not matched:
4169 break
4170 lhs += matched.group(1)
4171 expression = matched.group(2)
4172
4173 # Only apply checks if we got all parts of the boolean expression
4174 if not (lhs and operator and rhs):
4175 return
4176
4177 # Check that rhs do not contain logical operators. We already know
4178 # that lhs is fine since the loop above parses out && and ||.
4179 if rhs.find('&&') > -1 or rhs.find('||') > -1:
4180 return
4181
4182 # At least one of the operands must be a constant literal. This is
4183 # to avoid suggesting replacements for unprintable things like
4184 # CHECK(variable != iterator)
4185 #
4186 # The following pattern matches decimal, hex integers, strings, and
4187 # characters (in that order).
4188 lhs = lhs.strip()
4189 rhs = rhs.strip()
4190 match_constant = r'^([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')$'
4191 if Match(match_constant, lhs) or Match(match_constant, rhs):
4192 # Note: since we know both lhs and rhs, we can provide a more
4193 # descriptive error message like:
4194 # Consider using CHECK_EQ(x, 42) instead of CHECK(x == 42)
4195 # Instead of:
4196 # Consider using CHECK_EQ instead of CHECK(a == b)
4197 #
4198 # We are still keeping the less descriptive message because if lhs
4199 # or rhs gets long, the error message might become unreadable.
4200 error(filename, linenum, 'readability/check', 2,
4201 'Consider using %s instead of %s(a %s b)' % (
4202 _CHECK_REPLACEMENT[check_macro][operator],
4203 check_macro, operator))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004204
4205
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004206def CheckAltTokens(filename, clean_lines, linenum, error):
4207 """Check alternative keywords being used in boolean expressions.
4208
4209 Args:
4210 filename: The name of the current file.
4211 clean_lines: A CleansedLines instance containing the file.
4212 linenum: The number of the line to check.
4213 error: The function to call with any errors found.
4214 """
4215 line = clean_lines.elided[linenum]
4216
4217 # Avoid preprocessor lines
4218 if Match(r'^\s*#', line):
4219 return
4220
4221 # Last ditch effort to avoid multi-line comments. This will not help
4222 # if the comment started before the current line or ended after the
4223 # current line, but it catches most of the false positives. At least,
4224 # it provides a way to workaround this warning for people who use
4225 # multi-line comments in preprocessor macros.
4226 #
4227 # TODO(unknown): remove this once cpplint has better support for
4228 # multi-line comments.
4229 if line.find('/*') >= 0 or line.find('*/') >= 0:
4230 return
4231
4232 for match in _ALT_TOKEN_REPLACEMENT_PATTERN.finditer(line):
4233 error(filename, linenum, 'readability/alt_tokens', 2,
4234 'Use operator %s instead of %s' % (
4235 _ALT_TOKEN_REPLACEMENT[match.group(1)], match.group(1)))
4236
4237
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004238def GetLineWidth(line):
4239 """Determines the width of the line in column positions.
4240
4241 Args:
4242 line: A string, which may be a Unicode string.
4243
4244 Returns:
4245 The width of the line in column positions, accounting for Unicode
4246 combining characters and wide characters.
4247 """
Edward Lemur6d31ed52019-12-02 23:00:00 +00004248 if sys.version_info == 2 and isinstance(line, unicode):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004249 width = 0
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004250 for uc in unicodedata.normalize('NFC', line):
4251 if unicodedata.east_asian_width(uc) in ('W', 'F'):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004252 width += 2
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004253 elif not unicodedata.combining(uc):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004254 width += 1
4255 return width
4256 else:
4257 return len(line)
4258
4259
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004260def CheckStyle(filename, clean_lines, linenum, file_extension, nesting_state,
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004261 error):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004262 """Checks rules from the 'C++ style rules' section of cppguide.html.
4263
4264 Most of these rules are hard to test (naming, comment style), but we
4265 do what we can. In particular we check for 2-space indents, line lengths,
4266 tab usage, spaces inside code, etc.
4267
4268 Args:
4269 filename: The name of the current file.
4270 clean_lines: A CleansedLines instance containing the file.
4271 linenum: The number of the line to check.
4272 file_extension: The extension (without the dot) of the filename.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004273 nesting_state: A NestingState instance which maintains information about
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004274 the current stack of nested blocks being parsed.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004275 error: The function to call with any errors found.
4276 """
4277
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004278 # Don't use "elided" lines here, otherwise we can't check commented lines.
4279 # Don't want to use "raw" either, because we don't want to check inside C++11
4280 # raw strings,
4281 raw_lines = clean_lines.lines_without_raw_strings
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004282 line = raw_lines[linenum]
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004283 prev = raw_lines[linenum - 1] if linenum > 0 else ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004284
4285 if line.find('\t') != -1:
4286 error(filename, linenum, 'whitespace/tab', 1,
4287 'Tab found; better to use spaces')
4288
4289 # One or three blank spaces at the beginning of the line is weird; it's
4290 # hard to reconcile that with 2-space indents.
4291 # NOTE: here are the conditions rob pike used for his tests. Mine aren't
4292 # as sophisticated, but it may be worth becoming so: RLENGTH==initial_spaces
4293 # if(RLENGTH > 20) complain = 0;
4294 # if(match($0, " +(error|private|public|protected):")) complain = 0;
4295 # if(match(prev, "&& *$")) complain = 0;
4296 # if(match(prev, "\\|\\| *$")) complain = 0;
4297 # if(match(prev, "[\",=><] *$")) complain = 0;
4298 # if(match($0, " <<")) complain = 0;
4299 # if(match(prev, " +for \\(")) complain = 0;
4300 # if(prevodd && match(prevprev, " +for \\(")) complain = 0;
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004301 scope_or_label_pattern = r'\s*\w+\s*:\s*\\?$'
4302 classinfo = nesting_state.InnermostClass()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004303 initial_spaces = 0
4304 cleansed_line = clean_lines.elided[linenum]
4305 while initial_spaces < len(line) and line[initial_spaces] == ' ':
4306 initial_spaces += 1
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004307 # There are certain situations we allow one space, notably for
4308 # section labels, and also lines containing multi-line raw strings.
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004309 # We also don't check for lines that look like continuation lines
4310 # (of lines ending in double quotes, commas, equals, or angle brackets)
4311 # because the rules for how to indent those are non-trivial.
4312 if (not Search(r'[",=><] *$', prev) and
4313 (initial_spaces == 1 or initial_spaces == 3) and
4314 not Match(scope_or_label_pattern, cleansed_line) and
4315 not (clean_lines.raw_lines[linenum] != line and
4316 Match(r'^\s*""', line))):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004317 error(filename, linenum, 'whitespace/indent', 3,
4318 'Weird number of spaces at line-start. '
4319 'Are you using a 2-space indent?')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004320
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004321 if line and line[-1].isspace():
4322 error(filename, linenum, 'whitespace/end_of_line', 4,
4323 'Line ends in whitespace. Consider deleting these extra spaces.')
4324
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004325 # Check if the line is a header guard.
4326 is_header_guard = False
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00004327 if file_extension == 'h':
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004328 cppvar = GetHeaderGuardCPPVariable(filename)
4329 if (line.startswith('#ifndef %s' % cppvar) or
4330 line.startswith('#define %s' % cppvar) or
4331 line.startswith('#endif // %s' % cppvar)):
4332 is_header_guard = True
4333 # #include lines and header guards can be long, since there's no clean way to
4334 # split them.
erg@google.com6317a9c2009-06-25 00:28:19 +00004335 #
4336 # URLs can be long too. It's possible to split these, but it makes them
4337 # harder to cut&paste.
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004338 #
4339 # The "$Id:...$" comment may also get very long without it being the
4340 # developers fault.
erg@google.com6317a9c2009-06-25 00:28:19 +00004341 if (not line.startswith('#include') and not is_header_guard and
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004342 not Match(r'^\s*//.*http(s?)://\S*$', line) and
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004343 not Match(r'^\s*//\s*[^\s]*$', line) and
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004344 not Match(r'^// \$Id:.*#[0-9]+ \$$', line)):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004345 line_width = GetLineWidth(line)
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004346 if line_width > _line_length:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004347 error(filename, linenum, 'whitespace/line_length', 2,
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004348 'Lines should be <= %i characters long' % _line_length)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004349
4350 if (cleansed_line.count(';') > 1 and
4351 # for loops are allowed two ;'s (and may run over two lines).
4352 cleansed_line.find('for') == -1 and
4353 (GetPreviousNonBlankLine(clean_lines, linenum)[0].find('for') == -1 or
4354 GetPreviousNonBlankLine(clean_lines, linenum)[0].find(';') != -1) and
4355 # It's ok to have many commands in a switch case that fits in 1 line
4356 not ((cleansed_line.find('case ') != -1 or
4357 cleansed_line.find('default:') != -1) and
4358 cleansed_line.find('break;') != -1)):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004359 error(filename, linenum, 'whitespace/newline', 0,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004360 'More than one command on the same line')
4361
4362 # Some more style checks
4363 CheckBraces(filename, clean_lines, linenum, error)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004364 CheckTrailingSemicolon(filename, clean_lines, linenum, error)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004365 CheckEmptyBlockBody(filename, clean_lines, linenum, error)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004366 CheckSpacing(filename, clean_lines, linenum, nesting_state, error)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004367 CheckOperatorSpacing(filename, clean_lines, linenum, error)
4368 CheckParenthesisSpacing(filename, clean_lines, linenum, error)
4369 CheckCommaSpacing(filename, clean_lines, linenum, error)
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004370 CheckBracesSpacing(filename, clean_lines, linenum, nesting_state, error)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004371 CheckSpacingForFunctionCall(filename, clean_lines, linenum, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004372 CheckCheck(filename, clean_lines, linenum, error)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004373 CheckAltTokens(filename, clean_lines, linenum, error)
4374 classinfo = nesting_state.InnermostClass()
4375 if classinfo:
4376 CheckSectionSpacing(filename, clean_lines, classinfo, linenum, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004377
4378
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004379_RE_PATTERN_INCLUDE = re.compile(r'^\s*#\s*include\s*([<"])([^>"]*)[>"].*$')
4380# Matches the first component of a filename delimited by -s and _s. That is:
4381# _RE_FIRST_COMPONENT.match('foo').group(0) == 'foo'
4382# _RE_FIRST_COMPONENT.match('foo.cc').group(0) == 'foo'
4383# _RE_FIRST_COMPONENT.match('foo-bar_baz.cc').group(0) == 'foo'
4384# _RE_FIRST_COMPONENT.match('foo_bar-baz.cc').group(0) == 'foo'
4385_RE_FIRST_COMPONENT = re.compile(r'^[^-_.]+')
4386
4387
4388def _DropCommonSuffixes(filename):
4389 """Drops common suffixes like _test.cc or -inl.h from filename.
4390
4391 For example:
4392 >>> _DropCommonSuffixes('foo/foo-inl.h')
4393 'foo/foo'
4394 >>> _DropCommonSuffixes('foo/bar/foo.cc')
4395 'foo/bar/foo'
4396 >>> _DropCommonSuffixes('foo/foo_internal.h')
4397 'foo/foo'
4398 >>> _DropCommonSuffixes('foo/foo_unusualinternal.h')
4399 'foo/foo_unusualinternal'
4400
4401 Args:
4402 filename: The input filename.
4403
4404 Returns:
4405 The filename with the common suffix removed.
4406 """
4407 for suffix in ('test.cc', 'regtest.cc', 'unittest.cc',
4408 'inl.h', 'impl.h', 'internal.h'):
4409 if (filename.endswith(suffix) and len(filename) > len(suffix) and
4410 filename[-len(suffix) - 1] in ('-', '_')):
4411 return filename[:-len(suffix) - 1]
4412 return os.path.splitext(filename)[0]
4413
4414
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004415def _ClassifyInclude(fileinfo, include, is_system):
4416 """Figures out what kind of header 'include' is.
4417
4418 Args:
4419 fileinfo: The current file cpplint is running over. A FileInfo instance.
4420 include: The path to a #included file.
4421 is_system: True if the #include used <> rather than "".
4422
4423 Returns:
4424 One of the _XXX_HEADER constants.
4425
4426 For example:
4427 >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'stdio.h', True)
4428 _C_SYS_HEADER
4429 >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'string', True)
4430 _CPP_SYS_HEADER
4431 >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', False)
4432 _LIKELY_MY_HEADER
4433 >>> _ClassifyInclude(FileInfo('foo/foo_unknown_extension.cc'),
4434 ... 'bar/foo_other_ext.h', False)
4435 _POSSIBLE_MY_HEADER
4436 >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/bar.h', False)
4437 _OTHER_HEADER
4438 """
4439 # This is a list of all standard c++ header files, except
4440 # those already checked for above.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004441 is_cpp_h = include in _CPP_HEADERS
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004442
4443 if is_system:
4444 if is_cpp_h:
4445 return _CPP_SYS_HEADER
4446 else:
4447 return _C_SYS_HEADER
4448
4449 # If the target file and the include we're checking share a
4450 # basename when we drop common extensions, and the include
4451 # lives in . , then it's likely to be owned by the target file.
4452 target_dir, target_base = (
4453 os.path.split(_DropCommonSuffixes(fileinfo.RepositoryName())))
4454 include_dir, include_base = os.path.split(_DropCommonSuffixes(include))
4455 if target_base == include_base and (
4456 include_dir == target_dir or
4457 include_dir == os.path.normpath(target_dir + '/../public')):
4458 return _LIKELY_MY_HEADER
4459
4460 # If the target and include share some initial basename
4461 # component, it's possible the target is implementing the
4462 # include, so it's allowed to be first, but we'll never
4463 # complain if it's not there.
4464 target_first_component = _RE_FIRST_COMPONENT.match(target_base)
4465 include_first_component = _RE_FIRST_COMPONENT.match(include_base)
4466 if (target_first_component and include_first_component and
4467 target_first_component.group(0) ==
4468 include_first_component.group(0)):
4469 return _POSSIBLE_MY_HEADER
4470
4471 return _OTHER_HEADER
4472
4473
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004474
erg@google.com6317a9c2009-06-25 00:28:19 +00004475def CheckIncludeLine(filename, clean_lines, linenum, include_state, error):
4476 """Check rules that are applicable to #include lines.
4477
4478 Strings on #include lines are NOT removed from elided line, to make
4479 certain tasks easier. However, to prevent false positives, checks
4480 applicable to #include lines in CheckLanguage must be put here.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004481
4482 Args:
4483 filename: The name of the current file.
4484 clean_lines: A CleansedLines instance containing the file.
4485 linenum: The number of the line to check.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004486 include_state: An _IncludeState instance in which the headers are inserted.
4487 error: The function to call with any errors found.
4488 """
4489 fileinfo = FileInfo(filename)
erg@google.com6317a9c2009-06-25 00:28:19 +00004490 line = clean_lines.lines[linenum]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004491
4492 # "include" should use the new style "foo/bar.h" instead of just "bar.h"
avakulenko@google.com59146752014-08-11 20:20:55 +00004493 # Only do this check if the included header follows google naming
4494 # conventions. If not, assume that it's a 3rd party API that
4495 # requires special include conventions.
4496 #
4497 # We also make an exception for Lua headers, which follow google
4498 # naming convention but not the include convention.
4499 match = Match(r'#include\s*"([^/]+\.h)"', line)
4500 if match and not _THIRD_PARTY_HEADERS_PATTERN.match(match.group(1)):
Fletcher Woodruff11b34152020-04-23 21:21:40 +00004501 error(filename, linenum, 'build/include_directory', 4,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004502 'Include the directory when naming .h files')
4503
4504 # we shouldn't include a file more than once. actually, there are a
4505 # handful of instances where doing so is okay, but in general it's
4506 # not.
erg@google.com6317a9c2009-06-25 00:28:19 +00004507 match = _RE_PATTERN_INCLUDE.search(line)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004508 if match:
4509 include = match.group(2)
4510 is_system = (match.group(1) == '<')
avakulenko@google.com59146752014-08-11 20:20:55 +00004511 duplicate_line = include_state.FindHeader(include)
4512 if duplicate_line >= 0:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004513 error(filename, linenum, 'build/include', 4,
4514 '"%s" already included at %s:%s' %
avakulenko@google.com59146752014-08-11 20:20:55 +00004515 (include, filename, duplicate_line))
avakulenko@google.com255f2be2014-12-05 22:19:55 +00004516 elif (include.endswith('.cc') and
4517 os.path.dirname(fileinfo.RepositoryName()) != os.path.dirname(include)):
4518 error(filename, linenum, 'build/include', 4,
4519 'Do not include .cc files from other packages')
avakulenko@google.com59146752014-08-11 20:20:55 +00004520 elif not _THIRD_PARTY_HEADERS_PATTERN.match(include):
4521 include_state.include_list[-1].append((include, linenum))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004522
4523 # We want to ensure that headers appear in the right order:
4524 # 1) for foo.cc, foo.h (preferred location)
4525 # 2) c system files
4526 # 3) cpp system files
4527 # 4) for foo.cc, foo.h (deprecated location)
4528 # 5) other google headers
4529 #
4530 # We classify each include statement as one of those 5 types
4531 # using a number of techniques. The include_state object keeps
4532 # track of the highest type seen, and complains if we see a
4533 # lower type after that.
4534 error_message = include_state.CheckNextIncludeOrder(
4535 _ClassifyInclude(fileinfo, include, is_system))
4536 if error_message:
4537 error(filename, linenum, 'build/include_order', 4,
4538 '%s. Should be: %s.h, c system, c++ system, other.' %
4539 (error_message, fileinfo.BaseName()))
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004540 canonical_include = include_state.CanonicalizeAlphabeticalOrder(include)
4541 if not include_state.IsInAlphabeticalOrder(
4542 clean_lines, linenum, canonical_include):
erg@google.com26970fa2009-11-17 18:07:32 +00004543 error(filename, linenum, 'build/include_alpha', 4,
4544 'Include "%s" not in alphabetical order' % include)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004545 include_state.SetLastHeader(canonical_include)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004546
erg@google.com6317a9c2009-06-25 00:28:19 +00004547
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004548
4549def _GetTextInside(text, start_pattern):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004550 r"""Retrieves all the text between matching open and close parentheses.
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004551
4552 Given a string of lines and a regular expression string, retrieve all the text
4553 following the expression and between opening punctuation symbols like
4554 (, [, or {, and the matching close-punctuation symbol. This properly nested
4555 occurrences of the punctuations, so for the text like
4556 printf(a(), b(c()));
4557 a call to _GetTextInside(text, r'printf\(') will return 'a(), b(c())'.
4558 start_pattern must match string having an open punctuation symbol at the end.
4559
4560 Args:
4561 text: The lines to extract text. Its comments and strings must be elided.
4562 It can be single line and can span multiple lines.
4563 start_pattern: The regexp string indicating where to start extracting
4564 the text.
4565 Returns:
4566 The extracted text.
4567 None if either the opening string or ending punctuation could not be found.
4568 """
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004569 # TODO(unknown): Audit cpplint.py to see what places could be profitably
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004570 # rewritten to use _GetTextInside (and use inferior regexp matching today).
4571
4572 # Give opening punctuations to get the matching close-punctuations.
4573 matching_punctuation = {'(': ')', '{': '}', '[': ']'}
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +00004574 closing_punctuation = set(matching_punctuation.values())
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004575
4576 # Find the position to start extracting text.
4577 match = re.search(start_pattern, text, re.M)
4578 if not match: # start_pattern not found in text.
4579 return None
4580 start_position = match.end(0)
4581
4582 assert start_position > 0, (
4583 'start_pattern must ends with an opening punctuation.')
4584 assert text[start_position - 1] in matching_punctuation, (
4585 'start_pattern must ends with an opening punctuation.')
4586 # Stack of closing punctuations we expect to have in text after position.
4587 punctuation_stack = [matching_punctuation[text[start_position - 1]]]
4588 position = start_position
4589 while punctuation_stack and position < len(text):
4590 if text[position] == punctuation_stack[-1]:
4591 punctuation_stack.pop()
4592 elif text[position] in closing_punctuation:
4593 # A closing punctuation without matching opening punctuations.
4594 return None
4595 elif text[position] in matching_punctuation:
4596 punctuation_stack.append(matching_punctuation[text[position]])
4597 position += 1
4598 if punctuation_stack:
4599 # Opening punctuations left without matching close-punctuations.
4600 return None
4601 # punctuations match.
4602 return text[start_position:position - 1]
4603
4604
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004605# Patterns for matching call-by-reference parameters.
4606#
4607# Supports nested templates up to 2 levels deep using this messy pattern:
4608# < (?: < (?: < [^<>]*
4609# >
4610# | [^<>] )*
4611# >
4612# | [^<>] )*
4613# >
4614_RE_PATTERN_IDENT = r'[_a-zA-Z]\w*' # =~ [[:alpha:]][[:alnum:]]*
4615_RE_PATTERN_TYPE = (
4616 r'(?:const\s+)?(?:typename\s+|class\s+|struct\s+|union\s+|enum\s+)?'
4617 r'(?:\w|'
4618 r'\s*<(?:<(?:<[^<>]*>|[^<>])*>|[^<>])*>|'
4619 r'::)+')
4620# A call-by-reference parameter ends with '& identifier'.
4621_RE_PATTERN_REF_PARAM = re.compile(
4622 r'(' + _RE_PATTERN_TYPE + r'(?:\s*(?:\bconst\b|[*]))*\s*'
4623 r'&\s*' + _RE_PATTERN_IDENT + r')\s*(?:=[^,()]+)?[,)]')
4624# A call-by-const-reference parameter either ends with 'const& identifier'
4625# or looks like 'const type& identifier' when 'type' is atomic.
4626_RE_PATTERN_CONST_REF_PARAM = (
4627 r'(?:.*\s*\bconst\s*&\s*' + _RE_PATTERN_IDENT +
4628 r'|const\s+' + _RE_PATTERN_TYPE + r'\s*&\s*' + _RE_PATTERN_IDENT + r')')
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004629# Stream types.
4630_RE_PATTERN_REF_STREAM_PARAM = (
4631 r'(?:.*stream\s*&\s*' + _RE_PATTERN_IDENT + r')')
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004632
4633
4634def CheckLanguage(filename, clean_lines, linenum, file_extension,
4635 include_state, nesting_state, error):
erg@google.com6317a9c2009-06-25 00:28:19 +00004636 """Checks rules from the 'C++ language rules' section of cppguide.html.
4637
4638 Some of these rules are hard to test (function overloading, using
4639 uint32 inappropriately), but we do the best we can.
4640
4641 Args:
4642 filename: The name of the current file.
4643 clean_lines: A CleansedLines instance containing the file.
4644 linenum: The number of the line to check.
4645 file_extension: The extension (without the dot) of the filename.
4646 include_state: An _IncludeState instance in which the headers are inserted.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004647 nesting_state: A NestingState instance which maintains information about
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004648 the current stack of nested blocks being parsed.
erg@google.com6317a9c2009-06-25 00:28:19 +00004649 error: The function to call with any errors found.
4650 """
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004651 # If the line is empty or consists of entirely a comment, no need to
4652 # check it.
4653 line = clean_lines.elided[linenum]
4654 if not line:
4655 return
4656
erg@google.com6317a9c2009-06-25 00:28:19 +00004657 match = _RE_PATTERN_INCLUDE.search(line)
4658 if match:
4659 CheckIncludeLine(filename, clean_lines, linenum, include_state, error)
4660 return
4661
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004662 # Reset include state across preprocessor directives. This is meant
4663 # to silence warnings for conditional includes.
avakulenko@google.com59146752014-08-11 20:20:55 +00004664 match = Match(r'^\s*#\s*(if|ifdef|ifndef|elif|else|endif)\b', line)
4665 if match:
4666 include_state.ResetSection(match.group(1))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004667
4668 # Make Windows paths like Unix.
4669 fullname = os.path.abspath(filename).replace('\\', '/')
skym@chromium.org3990c412016-02-05 20:55:12 +00004670
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004671 # Perform other checks now that we are sure that this is not an include line
4672 CheckCasts(filename, clean_lines, linenum, error)
4673 CheckGlobalStatic(filename, clean_lines, linenum, error)
4674 CheckPrintf(filename, clean_lines, linenum, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004675
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00004676 if file_extension == 'h':
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004677 # TODO(unknown): check that 1-arg constructors are explicit.
4678 # How to tell it's a constructor?
4679 # (handled in CheckForNonStandardConstructs for now)
avakulenko@google.com59146752014-08-11 20:20:55 +00004680 # TODO(unknown): check that classes declare or disable copy/assign
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004681 # (level 1 error)
4682 pass
4683
4684 # Check if people are using the verboten C basic types. The only exception
4685 # we regularly allow is "unsigned short port" for port.
4686 if Search(r'\bshort port\b', line):
4687 if not Search(r'\bunsigned short port\b', line):
4688 error(filename, linenum, 'runtime/int', 4,
4689 'Use "unsigned short" for ports, not "short"')
4690 else:
4691 match = Search(r'\b(short|long(?! +double)|long long)\b', line)
4692 if match:
4693 error(filename, linenum, 'runtime/int', 4,
4694 'Use int16/int64/etc, rather than the C type %s' % match.group(1))
4695
erg@google.com26970fa2009-11-17 18:07:32 +00004696 # Check if some verboten operator overloading is going on
4697 # TODO(unknown): catch out-of-line unary operator&:
4698 # class X {};
4699 # int operator&(const X& x) { return 42; } // unary operator&
4700 # The trick is it's hard to tell apart from binary operator&:
4701 # class Y { int operator&(const Y& x) { return 23; } }; // binary operator&
4702 if Search(r'\boperator\s*&\s*\(\s*\)', line):
4703 error(filename, linenum, 'runtime/operator', 4,
4704 'Unary operator& is dangerous. Do not use it.')
4705
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004706 # Check for suspicious usage of "if" like
4707 # } if (a == b) {
Darius Maa7d7e42022-05-13 14:54:21 +00004708 if Search(r'\}\s*if\s*(?:constexpr\s*)?\(', line):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004709 error(filename, linenum, 'readability/braces', 4,
4710 'Did you mean "else if"? If not, start a new line for "if".')
4711
4712 # Check for potential format string bugs like printf(foo).
4713 # We constrain the pattern not to pick things like DocidForPrintf(foo).
4714 # Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str())
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004715 # TODO(unknown): Catch the following case. Need to change the calling
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004716 # convention of the whole function to process multiple line to handle it.
4717 # printf(
4718 # boy_this_is_a_really_long_variable_that_cannot_fit_on_the_prev_line);
4719 printf_args = _GetTextInside(line, r'(?i)\b(string)?printf\s*\(')
4720 if printf_args:
4721 match = Match(r'([\w.\->()]+)$', printf_args)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004722 if match and match.group(1) != '__VA_ARGS__':
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004723 function_name = re.search(r'\b((?:string)?printf)\s*\(',
4724 line, re.I).group(1)
4725 error(filename, linenum, 'runtime/printf', 4,
4726 'Potential format string bug. Do %s("%%s", %s) instead.'
4727 % (function_name, match.group(1)))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004728
4729 # Check for potential memset bugs like memset(buf, sizeof(buf), 0).
4730 match = Search(r'memset\s*\(([^,]*),\s*([^,]*),\s*0\s*\)', line)
4731 if match and not Match(r"^''|-?[0-9]+|0x[0-9A-Fa-f]$", match.group(2)):
4732 error(filename, linenum, 'runtime/memset', 4,
4733 'Did you mean "memset(%s, 0, %s)"?'
4734 % (match.group(1), match.group(2)))
4735
4736 if Search(r'\busing namespace\b', line):
4737 error(filename, linenum, 'build/namespaces', 5,
4738 'Do not use namespace using-directives. '
4739 'Use using-declarations instead.')
4740
4741 # Detect variable-length arrays.
4742 match = Match(r'\s*(.+::)?(\w+) [a-z]\w*\[(.+)];', line)
4743 if (match and match.group(2) != 'return' and match.group(2) != 'delete' and
4744 match.group(3).find(']') == -1):
4745 # Split the size using space and arithmetic operators as delimiters.
4746 # If any of the resulting tokens are not compile time constants then
4747 # report the error.
4748 tokens = re.split(r'\s|\+|\-|\*|\/|<<|>>]', match.group(3))
4749 is_const = True
4750 skip_next = False
4751 for tok in tokens:
4752 if skip_next:
4753 skip_next = False
4754 continue
4755
4756 if Search(r'sizeof\(.+\)', tok): continue
4757 if Search(r'arraysize\(\w+\)', tok): continue
Avi Drissman4157ba12019-01-09 14:18:07 +00004758 if Search(r'base::size\(.+\)', tok): continue
4759 if Search(r'std::size\(.+\)', tok): continue
4760 if Search(r'std::extent<.+>', tok): continue
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004761
4762 tok = tok.lstrip('(')
4763 tok = tok.rstrip(')')
4764 if not tok: continue
4765 if Match(r'\d+', tok): continue
4766 if Match(r'0[xX][0-9a-fA-F]+', tok): continue
4767 if Match(r'k[A-Z0-9]\w*', tok): continue
4768 if Match(r'(.+::)?k[A-Z0-9]\w*', tok): continue
4769 if Match(r'(.+::)?[A-Z][A-Z0-9_]*', tok): continue
4770 # A catch all for tricky sizeof cases, including 'sizeof expression',
4771 # 'sizeof(*type)', 'sizeof(const type)', 'sizeof(struct StructName)'
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004772 # requires skipping the next token because we split on ' ' and '*'.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004773 if tok.startswith('sizeof'):
4774 skip_next = True
4775 continue
4776 is_const = False
4777 break
4778 if not is_const:
4779 error(filename, linenum, 'runtime/arrays', 1,
4780 'Do not use variable-length arrays. Use an appropriately named '
4781 "('k' followed by CamelCase) compile-time constant for the size.")
4782
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004783 # Check for use of unnamed namespaces in header files. Registration
4784 # macros are typically OK, so we allow use of "namespace {" on lines
4785 # that end with backslashes.
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00004786 if (file_extension == 'h'
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004787 and Search(r'\bnamespace\s*{', line)
4788 and line[-1] != '\\'):
4789 error(filename, linenum, 'build/namespaces', 4,
4790 'Do not use unnamed namespaces in header files. See '
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00004791 'https://google.github.io/styleguide/cppguide.html#Namespaces'
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004792 ' for more information.')
4793
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004794
4795def CheckGlobalStatic(filename, clean_lines, linenum, error):
4796 """Check for unsafe global or static objects.
4797
4798 Args:
4799 filename: The name of the current file.
4800 clean_lines: A CleansedLines instance containing the file.
4801 linenum: The number of the line to check.
4802 error: The function to call with any errors found.
4803 """
4804 line = clean_lines.elided[linenum]
4805
avakulenko@google.com59146752014-08-11 20:20:55 +00004806 # Match two lines at a time to support multiline declarations
4807 if linenum + 1 < clean_lines.NumLines() and not Search(r'[;({]', line):
4808 line += clean_lines.elided[linenum + 1].strip()
4809
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004810 # Check for people declaring static/global STL strings at the top level.
4811 # This is dangerous because the C++ language does not guarantee that
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004812 # globals with constructors are initialized before the first access, and
4813 # also because globals can be destroyed when some threads are still running.
4814 # TODO(unknown): Generalize this to also find static unique_ptr instances.
4815 # TODO(unknown): File bugs for clang-tidy to find these.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004816 match = Match(
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004817 r'((?:|static +)(?:|const +))(?::*std::)?string( +const)? +'
4818 r'([a-zA-Z0-9_:]+)\b(.*)',
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004819 line)
avakulenko@google.com59146752014-08-11 20:20:55 +00004820
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004821 # Remove false positives:
4822 # - String pointers (as opposed to values).
4823 # string *pointer
4824 # const string *pointer
4825 # string const *pointer
4826 # string *const pointer
4827 #
4828 # - Functions and template specializations.
4829 # string Function<Type>(...
4830 # string Class<Type>::Method(...
4831 #
4832 # - Operators. These are matched separately because operator names
4833 # cross non-word boundaries, and trying to match both operators
4834 # and functions at the same time would decrease accuracy of
4835 # matching identifiers.
4836 # string Class::operator*()
4837 if (match and
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004838 not Search(r'\bstring\b(\s+const)?\s*[\*\&]\s*(const\s+)?\w', line) and
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004839 not Search(r'\boperator\W', line) and
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004840 not Match(r'\s*(<.*>)?(::[a-zA-Z0-9_]+)*\s*\(([^"]|$)', match.group(4))):
4841 if Search(r'\bconst\b', line):
4842 error(filename, linenum, 'runtime/string', 4,
4843 'For a static/global string constant, use a C style string '
4844 'instead: "%schar%s %s[]".' %
4845 (match.group(1), match.group(2) or '', match.group(3)))
4846 else:
4847 error(filename, linenum, 'runtime/string', 4,
4848 'Static/global string variables are not permitted.')
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004849
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004850 if (Search(r'\b([A-Za-z0-9_]*_)\(\1\)', line) or
4851 Search(r'\b([A-Za-z0-9_]*_)\(CHECK_NOTNULL\(\1\)\)', line)):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004852 error(filename, linenum, 'runtime/init', 4,
4853 'You seem to be initializing a member variable with itself.')
4854
4855
4856def CheckPrintf(filename, clean_lines, linenum, error):
4857 """Check for printf related issues.
4858
4859 Args:
4860 filename: The name of the current file.
4861 clean_lines: A CleansedLines instance containing the file.
4862 linenum: The number of the line to check.
4863 error: The function to call with any errors found.
4864 """
4865 line = clean_lines.elided[linenum]
4866
4867 # When snprintf is used, the second argument shouldn't be a literal.
4868 match = Search(r'snprintf\s*\(([^,]*),\s*([0-9]*)\s*,', line)
4869 if match and match.group(2) != '0':
4870 # If 2nd arg is zero, snprintf is used to calculate size.
4871 error(filename, linenum, 'runtime/printf', 3,
4872 'If you can, use sizeof(%s) instead of %s as the 2nd arg '
4873 'to snprintf.' % (match.group(1), match.group(2)))
4874
4875 # Check if some verboten C functions are being used.
avakulenko@google.com59146752014-08-11 20:20:55 +00004876 if Search(r'\bsprintf\s*\(', line):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004877 error(filename, linenum, 'runtime/printf', 5,
4878 'Never use sprintf. Use snprintf instead.')
avakulenko@google.com59146752014-08-11 20:20:55 +00004879 match = Search(r'\b(strcpy|strcat)\s*\(', line)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004880 if match:
4881 error(filename, linenum, 'runtime/printf', 4,
4882 'Almost always, snprintf is better than %s' % match.group(1))
4883
4884
4885def IsDerivedFunction(clean_lines, linenum):
4886 """Check if current line contains an inherited function.
4887
4888 Args:
4889 clean_lines: A CleansedLines instance containing the file.
4890 linenum: The number of the line to check.
4891 Returns:
4892 True if current line contains a function with "override"
4893 virt-specifier.
4894 """
avakulenko@google.com59146752014-08-11 20:20:55 +00004895 # Scan back a few lines for start of current function
Edward Lemur6d31ed52019-12-02 23:00:00 +00004896 for i in range(linenum, max(-1, linenum - 10), -1):
avakulenko@google.com59146752014-08-11 20:20:55 +00004897 match = Match(r'^([^()]*\w+)\(', clean_lines.elided[i])
4898 if match:
4899 # Look for "override" after the matching closing parenthesis
4900 line, _, closing_paren = CloseExpression(
4901 clean_lines, i, len(match.group(1)))
4902 return (closing_paren >= 0 and
4903 Search(r'\boverride\b', line[closing_paren:]))
4904 return False
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004905
4906
avakulenko@google.com255f2be2014-12-05 22:19:55 +00004907def IsOutOfLineMethodDefinition(clean_lines, linenum):
4908 """Check if current line contains an out-of-line method definition.
4909
4910 Args:
4911 clean_lines: A CleansedLines instance containing the file.
4912 linenum: The number of the line to check.
4913 Returns:
4914 True if current line contains an out-of-line method definition.
4915 """
4916 # Scan back a few lines for start of current function
Edward Lemur6d31ed52019-12-02 23:00:00 +00004917 for i in range(linenum, max(-1, linenum - 10), -1):
avakulenko@google.com255f2be2014-12-05 22:19:55 +00004918 if Match(r'^([^()]*\w+)\(', clean_lines.elided[i]):
4919 return Match(r'^[^()]*\w+::\w+\(', clean_lines.elided[i]) is not None
4920 return False
4921
4922
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004923def IsInitializerList(clean_lines, linenum):
4924 """Check if current line is inside constructor initializer list.
4925
4926 Args:
4927 clean_lines: A CleansedLines instance containing the file.
4928 linenum: The number of the line to check.
4929 Returns:
4930 True if current line appears to be inside constructor initializer
4931 list, False otherwise.
4932 """
Edward Lemur6d31ed52019-12-02 23:00:00 +00004933 for i in range(linenum, 1, -1):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004934 line = clean_lines.elided[i]
4935 if i == linenum:
4936 remove_function_body = Match(r'^(.*)\{\s*$', line)
4937 if remove_function_body:
4938 line = remove_function_body.group(1)
4939
4940 if Search(r'\s:\s*\w+[({]', line):
4941 # A lone colon tend to indicate the start of a constructor
4942 # initializer list. It could also be a ternary operator, which
4943 # also tend to appear in constructor initializer lists as
4944 # opposed to parameter lists.
4945 return True
4946 if Search(r'\}\s*,\s*$', line):
4947 # A closing brace followed by a comma is probably the end of a
4948 # brace-initialized member in constructor initializer list.
4949 return True
4950 if Search(r'[{};]\s*$', line):
4951 # Found one of the following:
4952 # - A closing brace or semicolon, probably the end of the previous
4953 # function.
4954 # - An opening brace, probably the start of current class or namespace.
4955 #
4956 # Current line is probably not inside an initializer list since
4957 # we saw one of those things without seeing the starting colon.
4958 return False
4959
4960 # Got to the beginning of the file without seeing the start of
4961 # constructor initializer list.
4962 return False
4963
4964
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004965def CheckForNonConstReference(filename, clean_lines, linenum,
4966 nesting_state, error):
4967 """Check for non-const references.
4968
4969 Separate from CheckLanguage since it scans backwards from current
4970 line, instead of scanning forward.
4971
4972 Args:
4973 filename: The name of the current file.
4974 clean_lines: A CleansedLines instance containing the file.
4975 linenum: The number of the line to check.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004976 nesting_state: A NestingState instance which maintains information about
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004977 the current stack of nested blocks being parsed.
4978 error: The function to call with any errors found.
4979 """
4980 # Do nothing if there is no '&' on current line.
4981 line = clean_lines.elided[linenum]
4982 if '&' not in line:
4983 return
4984
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004985 # If a function is inherited, current function doesn't have much of
4986 # a choice, so any non-const references should not be blamed on
4987 # derived function.
4988 if IsDerivedFunction(clean_lines, linenum):
4989 return
4990
avakulenko@google.com255f2be2014-12-05 22:19:55 +00004991 # Don't warn on out-of-line method definitions, as we would warn on the
4992 # in-line declaration, if it isn't marked with 'override'.
4993 if IsOutOfLineMethodDefinition(clean_lines, linenum):
4994 return
4995
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004996 # Long type names may be broken across multiple lines, usually in one
4997 # of these forms:
4998 # LongType
4999 # ::LongTypeContinued &identifier
5000 # LongType::
5001 # LongTypeContinued &identifier
5002 # LongType<
5003 # ...>::LongTypeContinued &identifier
5004 #
5005 # If we detected a type split across two lines, join the previous
5006 # line to current line so that we can match const references
5007 # accordingly.
5008 #
5009 # Note that this only scans back one line, since scanning back
5010 # arbitrary number of lines would be expensive. If you have a type
5011 # that spans more than 2 lines, please use a typedef.
5012 if linenum > 1:
5013 previous = None
5014 if Match(r'\s*::(?:[\w<>]|::)+\s*&\s*\S', line):
5015 # previous_line\n + ::current_line
5016 previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+[\w<>])\s*$',
5017 clean_lines.elided[linenum - 1])
5018 elif Match(r'\s*[a-zA-Z_]([\w<>]|::)+\s*&\s*\S', line):
5019 # previous_line::\n + current_line
5020 previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+::)\s*$',
5021 clean_lines.elided[linenum - 1])
5022 if previous:
5023 line = previous.group(1) + line.lstrip()
5024 else:
5025 # Check for templated parameter that is split across multiple lines
5026 endpos = line.rfind('>')
5027 if endpos > -1:
5028 (_, startline, startpos) = ReverseCloseExpression(
5029 clean_lines, linenum, endpos)
5030 if startpos > -1 and startline < linenum:
5031 # Found the matching < on an earlier line, collect all
5032 # pieces up to current line.
5033 line = ''
Edward Lemur6d31ed52019-12-02 23:00:00 +00005034 for i in range(startline, linenum + 1):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005035 line += clean_lines.elided[i].strip()
5036
5037 # Check for non-const references in function parameters. A single '&' may
5038 # found in the following places:
5039 # inside expression: binary & for bitwise AND
5040 # inside expression: unary & for taking the address of something
5041 # inside declarators: reference parameter
5042 # We will exclude the first two cases by checking that we are not inside a
5043 # function body, including one that was just introduced by a trailing '{'.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005044 # TODO(unknown): Doesn't account for 'catch(Exception& e)' [rare].
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005045 if (nesting_state.previous_stack_top and
5046 not (isinstance(nesting_state.previous_stack_top, _ClassInfo) or
5047 isinstance(nesting_state.previous_stack_top, _NamespaceInfo))):
5048 # Not at toplevel, not within a class, and not within a namespace
5049 return
5050
avakulenko@google.com59146752014-08-11 20:20:55 +00005051 # Avoid initializer lists. We only need to scan back from the
5052 # current line for something that starts with ':'.
5053 #
5054 # We don't need to check the current line, since the '&' would
5055 # appear inside the second set of parentheses on the current line as
5056 # opposed to the first set.
5057 if linenum > 0:
Edward Lemur6d31ed52019-12-02 23:00:00 +00005058 for i in range(linenum - 1, max(0, linenum - 10), -1):
avakulenko@google.com59146752014-08-11 20:20:55 +00005059 previous_line = clean_lines.elided[i]
5060 if not Search(r'[),]\s*$', previous_line):
5061 break
5062 if Match(r'^\s*:\s+\S', previous_line):
5063 return
5064
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005065 # Avoid preprocessors
5066 if Search(r'\\\s*$', line):
5067 return
5068
5069 # Avoid constructor initializer lists
5070 if IsInitializerList(clean_lines, linenum):
5071 return
5072
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005073 # We allow non-const references in a few standard places, like functions
5074 # called "swap()" or iostream operators like "<<" or ">>". Do not check
5075 # those function parameters.
5076 #
5077 # We also accept & in static_assert, which looks like a function but
5078 # it's actually a declaration expression.
Ayu Ishii09858612020-06-26 18:00:52 +00005079 allowlisted_functions = (r'(?:[sS]wap(?:<\w:+>)?|'
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005080 r'operator\s*[<>][<>]|'
5081 r'static_assert|COMPILE_ASSERT'
5082 r')\s*\(')
Ayu Ishii09858612020-06-26 18:00:52 +00005083 if Search(allowlisted_functions, line):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005084 return
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005085 elif not Search(r'\S+\([^)]*$', line):
Ayu Ishii09858612020-06-26 18:00:52 +00005086 # Don't see an allowlisted function on this line. Actually we
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005087 # didn't see any function name on this line, so this is likely a
5088 # multi-line parameter list. Try a bit harder to catch this case.
Edward Lemur6d31ed52019-12-02 23:00:00 +00005089 for i in range(2):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005090 if (linenum > i and
Ayu Ishii09858612020-06-26 18:00:52 +00005091 Search(allowlisted_functions, clean_lines.elided[linenum - i - 1])):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005092 return
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005093
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005094 decls = ReplaceAll(r'{[^}]*}', ' ', line) # exclude function body
5095 for parameter in re.findall(_RE_PATTERN_REF_PARAM, decls):
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005096 if (not Match(_RE_PATTERN_CONST_REF_PARAM, parameter) and
5097 not Match(_RE_PATTERN_REF_STREAM_PARAM, parameter)):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005098 error(filename, linenum, 'runtime/references', 2,
5099 'Is this a non-const reference? '
5100 'If so, make const or use a pointer: ' +
5101 ReplaceAll(' *<', '<', parameter))
5102
5103
5104def CheckCasts(filename, clean_lines, linenum, error):
5105 """Various cast related checks.
5106
5107 Args:
5108 filename: The name of the current file.
5109 clean_lines: A CleansedLines instance containing the file.
5110 linenum: The number of the line to check.
5111 error: The function to call with any errors found.
5112 """
5113 line = clean_lines.elided[linenum]
5114
5115 # Check to see if they're using an conversion function cast.
5116 # I just try to capture the most common basic types, though there are more.
5117 # Parameterless conversion functions, such as bool(), are allowed as they are
5118 # probably a member operator declaration or default constructor.
5119 match = Search(
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005120 r'(\bnew\s+(?:const\s+)?|\S<\s*(?:const\s+)?)?\b'
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005121 r'(int|float|double|bool|char|int32|uint32|int64|uint64)'
5122 r'(\([^)].*)', line)
5123 expecting_function = ExpectingFunctionArgs(clean_lines, linenum)
5124 if match and not expecting_function:
5125 matched_type = match.group(2)
5126
5127 # matched_new_or_template is used to silence two false positives:
5128 # - New operators
5129 # - Template arguments with function types
5130 #
5131 # For template arguments, we match on types immediately following
5132 # an opening bracket without any spaces. This is a fast way to
5133 # silence the common case where the function type is the first
5134 # template argument. False negative with less-than comparison is
5135 # avoided because those operators are usually followed by a space.
5136 #
5137 # function<double(double)> // bracket + no space = false positive
5138 # value < double(42) // bracket + space = true positive
5139 matched_new_or_template = match.group(1)
5140
avakulenko@google.com59146752014-08-11 20:20:55 +00005141 # Avoid arrays by looking for brackets that come after the closing
5142 # parenthesis.
5143 if Match(r'\([^()]+\)\s*\[', match.group(3)):
5144 return
5145
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005146 # Other things to ignore:
5147 # - Function pointers
5148 # - Casts to pointer types
5149 # - Placement new
5150 # - Alias declarations
5151 matched_funcptr = match.group(3)
5152 if (matched_new_or_template is None and
5153 not (matched_funcptr and
5154 (Match(r'\((?:[^() ]+::\s*\*\s*)?[^() ]+\)\s*\(',
5155 matched_funcptr) or
5156 matched_funcptr.startswith('(*)'))) and
5157 not Match(r'\s*using\s+\S+\s*=\s*' + matched_type, line) and
5158 not Search(r'new\(\S+\)\s*' + matched_type, line)):
5159 error(filename, linenum, 'readability/casting', 4,
5160 'Using deprecated casting style. '
5161 'Use static_cast<%s>(...) instead' %
5162 matched_type)
5163
5164 if not expecting_function:
avakulenko@google.com59146752014-08-11 20:20:55 +00005165 CheckCStyleCast(filename, clean_lines, linenum, 'static_cast',
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005166 r'\((int|float|double|bool|char|u?int(16|32|64))\)', error)
5167
5168 # This doesn't catch all cases. Consider (const char * const)"hello".
5169 #
5170 # (char *) "foo" should always be a const_cast (reinterpret_cast won't
5171 # compile).
avakulenko@google.com59146752014-08-11 20:20:55 +00005172 if CheckCStyleCast(filename, clean_lines, linenum, 'const_cast',
5173 r'\((char\s?\*+\s?)\)\s*"', error):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005174 pass
5175 else:
5176 # Check pointer casts for other than string constants
avakulenko@google.com59146752014-08-11 20:20:55 +00005177 CheckCStyleCast(filename, clean_lines, linenum, 'reinterpret_cast',
5178 r'\((\w+\s?\*+\s?)\)', error)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005179
5180 # In addition, we look for people taking the address of a cast. This
5181 # is dangerous -- casts can assign to temporaries, so the pointer doesn't
5182 # point where you think.
avakulenko@google.com59146752014-08-11 20:20:55 +00005183 #
5184 # Some non-identifier character is required before the '&' for the
5185 # expression to be recognized as a cast. These are casts:
5186 # expression = &static_cast<int*>(temporary());
5187 # function(&(int*)(temporary()));
5188 #
5189 # This is not a cast:
5190 # reference_type&(int* function_param);
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005191 match = Search(
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005192 r'(?:[^\w]&\(([^)*][^)]*)\)[\w(])|'
avakulenko@google.com59146752014-08-11 20:20:55 +00005193 r'(?:[^\w]&(static|dynamic|down|reinterpret)_cast\b)', line)
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005194 if match:
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005195 # Try a better error message when the & is bound to something
5196 # dereferenced by the casted pointer, as opposed to the casted
5197 # pointer itself.
5198 parenthesis_error = False
5199 match = Match(r'^(.*&(?:static|dynamic|down|reinterpret)_cast\b)<', line)
5200 if match:
5201 _, y1, x1 = CloseExpression(clean_lines, linenum, len(match.group(1)))
5202 if x1 >= 0 and clean_lines.elided[y1][x1] == '(':
5203 _, y2, x2 = CloseExpression(clean_lines, y1, x1)
5204 if x2 >= 0:
5205 extended_line = clean_lines.elided[y2][x2:]
5206 if y2 < clean_lines.NumLines() - 1:
5207 extended_line += clean_lines.elided[y2 + 1]
5208 if Match(r'\s*(?:->|\[)', extended_line):
5209 parenthesis_error = True
5210
5211 if parenthesis_error:
5212 error(filename, linenum, 'readability/casting', 4,
5213 ('Are you taking an address of something dereferenced '
5214 'from a cast? Wrapping the dereferenced expression in '
5215 'parentheses will make the binding more obvious'))
5216 else:
5217 error(filename, linenum, 'runtime/casting', 4,
5218 ('Are you taking an address of a cast? '
5219 'This is dangerous: could be a temp var. '
5220 'Take the address before doing the cast, rather than after'))
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005221
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005222
avakulenko@google.com59146752014-08-11 20:20:55 +00005223def CheckCStyleCast(filename, clean_lines, linenum, cast_type, pattern, error):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005224 """Checks for a C-style cast by looking for the pattern.
5225
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005226 Args:
5227 filename: The name of the current file.
avakulenko@google.com59146752014-08-11 20:20:55 +00005228 clean_lines: A CleansedLines instance containing the file.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005229 linenum: The number of the line to check.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005230 cast_type: The string for the C++ cast to recommend. This is either
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005231 reinterpret_cast, static_cast, or const_cast, depending.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005232 pattern: The regular expression used to find C-style casts.
5233 error: The function to call with any errors found.
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005234
5235 Returns:
5236 True if an error was emitted.
5237 False otherwise.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005238 """
avakulenko@google.com59146752014-08-11 20:20:55 +00005239 line = clean_lines.elided[linenum]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005240 match = Search(pattern, line)
5241 if not match:
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005242 return False
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005243
avakulenko@google.com59146752014-08-11 20:20:55 +00005244 # Exclude lines with keywords that tend to look like casts
5245 context = line[0:match.start(1) - 1]
5246 if Match(r'.*\b(?:sizeof|alignof|alignas|[_A-Z][_A-Z0-9]*)\s*$', context):
5247 return False
5248
5249 # Try expanding current context to see if we one level of
5250 # parentheses inside a macro.
5251 if linenum > 0:
Edward Lemur6d31ed52019-12-02 23:00:00 +00005252 for i in range(linenum - 1, max(0, linenum - 5), -1):
avakulenko@google.com59146752014-08-11 20:20:55 +00005253 context = clean_lines.elided[i] + context
5254 if Match(r'.*\b[_A-Z][_A-Z0-9]*\s*\((?:\([^()]*\)|[^()])*$', context):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005255 return False
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005256
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005257 # operator++(int) and operator--(int)
avakulenko@google.com59146752014-08-11 20:20:55 +00005258 if context.endswith(' operator++') or context.endswith(' operator--'):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005259 return False
5260
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005261 # A single unnamed argument for a function tends to look like old style cast.
5262 # If we see those, don't issue warnings for deprecated casts.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005263 remainder = line[match.end(0):]
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005264 if Match(r'^\s*(?:;|const\b|throw\b|final\b|override\b|[=>{),]|->)',
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005265 remainder):
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005266 return False
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005267
5268 # At this point, all that should be left is actual casts.
5269 error(filename, linenum, 'readability/casting', 4,
5270 'Using C-style cast. Use %s<%s>(...) instead' %
5271 (cast_type, match.group(1)))
5272
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005273 return True
5274
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005275
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005276def ExpectingFunctionArgs(clean_lines, linenum):
5277 """Checks whether where function type arguments are expected.
5278
5279 Args:
5280 clean_lines: A CleansedLines instance containing the file.
5281 linenum: The number of the line to check.
5282
5283 Returns:
5284 True if the line at 'linenum' is inside something that expects arguments
5285 of function types.
5286 """
5287 line = clean_lines.elided[linenum]
5288 return (Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line) or
5289 (linenum >= 2 and
5290 (Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\((?:\S+,)?\s*$',
5291 clean_lines.elided[linenum - 1]) or
5292 Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\(\s*$',
5293 clean_lines.elided[linenum - 2]) or
5294 Search(r'\bstd::m?function\s*\<\s*$',
5295 clean_lines.elided[linenum - 1]))))
5296
5297
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005298_HEADERS_CONTAINING_TEMPLATES = (
5299 ('<deque>', ('deque',)),
5300 ('<functional>', ('unary_function', 'binary_function',
5301 'plus', 'minus', 'multiplies', 'divides', 'modulus',
5302 'negate',
5303 'equal_to', 'not_equal_to', 'greater', 'less',
5304 'greater_equal', 'less_equal',
5305 'logical_and', 'logical_or', 'logical_not',
5306 'unary_negate', 'not1', 'binary_negate', 'not2',
5307 'bind1st', 'bind2nd',
5308 'pointer_to_unary_function',
5309 'pointer_to_binary_function',
5310 'ptr_fun',
5311 'mem_fun_t', 'mem_fun', 'mem_fun1_t', 'mem_fun1_ref_t',
5312 'mem_fun_ref_t',
5313 'const_mem_fun_t', 'const_mem_fun1_t',
5314 'const_mem_fun_ref_t', 'const_mem_fun1_ref_t',
5315 'mem_fun_ref',
5316 )),
5317 ('<limits>', ('numeric_limits',)),
5318 ('<list>', ('list',)),
5319 ('<map>', ('map', 'multimap',)),
lhchavez2d1b6da2016-07-13 10:40:01 -07005320 ('<memory>', ('allocator', 'make_shared', 'make_unique', 'shared_ptr',
5321 'unique_ptr', 'weak_ptr')),
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005322 ('<queue>', ('queue', 'priority_queue',)),
5323 ('<set>', ('set', 'multiset',)),
5324 ('<stack>', ('stack',)),
5325 ('<string>', ('char_traits', 'basic_string',)),
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005326 ('<tuple>', ('tuple',)),
lhchavez2d1b6da2016-07-13 10:40:01 -07005327 ('<unordered_map>', ('unordered_map', 'unordered_multimap')),
5328 ('<unordered_set>', ('unordered_set', 'unordered_multiset')),
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005329 ('<utility>', ('pair',)),
5330 ('<vector>', ('vector',)),
5331
5332 # gcc extensions.
5333 # Note: std::hash is their hash, ::hash is our hash
5334 ('<hash_map>', ('hash_map', 'hash_multimap',)),
5335 ('<hash_set>', ('hash_set', 'hash_multiset',)),
5336 ('<slist>', ('slist',)),
5337 )
5338
skym@chromium.org3990c412016-02-05 20:55:12 +00005339_HEADERS_MAYBE_TEMPLATES = (
5340 ('<algorithm>', ('copy', 'max', 'min', 'min_element', 'sort',
5341 'transform',
5342 )),
lhchavez2d1b6da2016-07-13 10:40:01 -07005343 ('<utility>', ('forward', 'make_pair', 'move', 'swap')),
skym@chromium.org3990c412016-02-05 20:55:12 +00005344 )
5345
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005346_RE_PATTERN_STRING = re.compile(r'\bstring\b')
5347
skym@chromium.org3990c412016-02-05 20:55:12 +00005348_re_pattern_headers_maybe_templates = []
5349for _header, _templates in _HEADERS_MAYBE_TEMPLATES:
5350 for _template in _templates:
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +00005351 # Match max<type>(..., ...), max(..., ...), but not foo->max, foo.max
5352 # or type::max().
skym@chromium.org3990c412016-02-05 20:55:12 +00005353 _re_pattern_headers_maybe_templates.append(
5354 (re.compile(r'[^>.]\b' + _template + r'(<.*?>)?\([^\)]'),
5355 _template,
5356 _header))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005357
skym@chromium.org3990c412016-02-05 20:55:12 +00005358# Other scripts may reach in and modify this pattern.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005359_re_pattern_templates = []
5360for _header, _templates in _HEADERS_CONTAINING_TEMPLATES:
5361 for _template in _templates:
5362 _re_pattern_templates.append(
5363 (re.compile(r'(\<|\b)' + _template + r'\s*\<'),
5364 _template + '<>',
5365 _header))
5366
5367
erg@google.com6317a9c2009-06-25 00:28:19 +00005368def FilesBelongToSameModule(filename_cc, filename_h):
5369 """Check if these two filenames belong to the same module.
5370
5371 The concept of a 'module' here is a as follows:
5372 foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the
5373 same 'module' if they are in the same directory.
5374 some/path/public/xyzzy and some/path/internal/xyzzy are also considered
5375 to belong to the same module here.
5376
5377 If the filename_cc contains a longer path than the filename_h, for example,
5378 '/absolute/path/to/base/sysinfo.cc', and this file would include
5379 'base/sysinfo.h', this function also produces the prefix needed to open the
5380 header. This is used by the caller of this function to more robustly open the
5381 header file. We don't have access to the real include paths in this context,
5382 so we need this guesswork here.
5383
5384 Known bugs: tools/base/bar.cc and base/bar.h belong to the same module
5385 according to this implementation. Because of this, this function gives
5386 some false positives. This should be sufficiently rare in practice.
5387
5388 Args:
5389 filename_cc: is the path for the .cc file
5390 filename_h: is the path for the header path
5391
5392 Returns:
5393 Tuple with a bool and a string:
5394 bool: True if filename_cc and filename_h belong to the same module.
5395 string: the additional prefix needed to open the header file.
5396 """
5397
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005398 fileinfo = FileInfo(filename_cc)
5399 if not fileinfo.IsSource():
erg@google.com6317a9c2009-06-25 00:28:19 +00005400 return (False, '')
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005401 filename_cc = filename_cc[:-len(fileinfo.Extension())]
5402 matched_test_suffix = Search(_TEST_FILE_SUFFIX, fileinfo.BaseName())
5403 if matched_test_suffix:
5404 filename_cc = filename_cc[:-len(matched_test_suffix.group(1))]
erg@google.com6317a9c2009-06-25 00:28:19 +00005405 filename_cc = filename_cc.replace('/public/', '/')
5406 filename_cc = filename_cc.replace('/internal/', '/')
5407
5408 if not filename_h.endswith('.h'):
5409 return (False, '')
5410 filename_h = filename_h[:-len('.h')]
5411 if filename_h.endswith('-inl'):
5412 filename_h = filename_h[:-len('-inl')]
5413 filename_h = filename_h.replace('/public/', '/')
5414 filename_h = filename_h.replace('/internal/', '/')
5415
5416 files_belong_to_same_module = filename_cc.endswith(filename_h)
5417 common_path = ''
5418 if files_belong_to_same_module:
5419 common_path = filename_cc[:-len(filename_h)]
5420 return files_belong_to_same_module, common_path
5421
5422
avakulenko@google.com59146752014-08-11 20:20:55 +00005423def UpdateIncludeState(filename, include_dict, io=codecs):
5424 """Fill up the include_dict with new includes found from the file.
erg@google.com6317a9c2009-06-25 00:28:19 +00005425
5426 Args:
5427 filename: the name of the header to read.
avakulenko@google.com59146752014-08-11 20:20:55 +00005428 include_dict: a dictionary in which the headers are inserted.
erg@google.com6317a9c2009-06-25 00:28:19 +00005429 io: The io factory to use to read the file. Provided for testability.
5430
5431 Returns:
avakulenko@google.com59146752014-08-11 20:20:55 +00005432 True if a header was successfully added. False otherwise.
erg@google.com6317a9c2009-06-25 00:28:19 +00005433 """
5434 headerfile = None
5435 try:
5436 headerfile = io.open(filename, 'r', 'utf8', 'replace')
5437 except IOError:
5438 return False
5439 linenum = 0
5440 for line in headerfile:
5441 linenum += 1
5442 clean_line = CleanseComments(line)
5443 match = _RE_PATTERN_INCLUDE.search(clean_line)
5444 if match:
5445 include = match.group(2)
avakulenko@google.com59146752014-08-11 20:20:55 +00005446 include_dict.setdefault(include, linenum)
erg@google.com6317a9c2009-06-25 00:28:19 +00005447 return True
5448
5449
5450def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error,
5451 io=codecs):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005452 """Reports for missing stl includes.
5453
5454 This function will output warnings to make sure you are including the headers
5455 necessary for the stl containers and functions that you use. We only give one
5456 reason to include a header. For example, if you use both equal_to<> and
5457 less<> in a .h file, only one (the latter in the file) of these will be
5458 reported as a reason to include the <functional>.
5459
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005460 Args:
5461 filename: The name of the current file.
5462 clean_lines: A CleansedLines instance containing the file.
5463 include_state: An _IncludeState instance.
5464 error: The function to call with any errors found.
erg@google.com6317a9c2009-06-25 00:28:19 +00005465 io: The IO factory to use to read the header file. Provided for unittest
5466 injection.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005467 """
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +00005468 # A map of header name to linenumber and the template entity.
5469 # Example of required: { '<functional>': (1219, 'less<>') }
5470 required = {}
Edward Lemur6d31ed52019-12-02 23:00:00 +00005471 for linenum in range(clean_lines.NumLines()):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005472 line = clean_lines.elided[linenum]
5473 if not line or line[0] == '#':
5474 continue
5475
5476 # String is special -- it is a non-templatized type in STL.
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005477 matched = _RE_PATTERN_STRING.search(line)
5478 if matched:
erg@google.com35589e62010-11-17 18:58:16 +00005479 # Don't warn about strings in non-STL namespaces:
5480 # (We check only the first match per line; good enough.)
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005481 prefix = line[:matched.start()]
erg@google.com35589e62010-11-17 18:58:16 +00005482 if prefix.endswith('std::') or not prefix.endswith('::'):
5483 required['<string>'] = (linenum, 'string')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005484
skym@chromium.org3990c412016-02-05 20:55:12 +00005485 for pattern, template, header in _re_pattern_headers_maybe_templates:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005486 if pattern.search(line):
5487 required[header] = (linenum, template)
5488
5489 # The following function is just a speed up, no semantics are changed.
5490 if not '<' in line: # Reduces the cpu time usage by skipping lines.
5491 continue
5492
5493 for pattern, template, header in _re_pattern_templates:
lhchavez9b2173c2016-07-13 10:20:07 -07005494 matched = pattern.search(line)
5495 if matched:
5496 # Don't warn about IWYU in non-STL namespaces:
5497 # (We check only the first match per line; good enough.)
5498 prefix = line[:matched.start()]
5499 if prefix.endswith('std::') or not prefix.endswith('::'):
5500 required[header] = (linenum, template)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005501
erg@google.com6317a9c2009-06-25 00:28:19 +00005502 # The policy is that if you #include something in foo.h you don't need to
5503 # include it again in foo.cc. Here, we will look at possible includes.
avakulenko@google.com59146752014-08-11 20:20:55 +00005504 # Let's flatten the include_state include_list and copy it into a dictionary.
5505 include_dict = dict([item for sublist in include_state.include_list
5506 for item in sublist])
erg@google.com6317a9c2009-06-25 00:28:19 +00005507
avakulenko@google.com59146752014-08-11 20:20:55 +00005508 # Did we find the header for this file (if any) and successfully load it?
erg@google.com6317a9c2009-06-25 00:28:19 +00005509 header_found = False
5510
5511 # Use the absolute path so that matching works properly.
erg@chromium.org8f927562012-01-30 19:51:28 +00005512 abs_filename = FileInfo(filename).FullName()
erg@google.com6317a9c2009-06-25 00:28:19 +00005513
5514 # For Emacs's flymake.
5515 # If cpplint is invoked from Emacs's flymake, a temporary file is generated
5516 # by flymake and that file name might end with '_flymake.cc'. In that case,
5517 # restore original file name here so that the corresponding header file can be
5518 # found.
5519 # e.g. If the file name is 'foo_flymake.cc', we should search for 'foo.h'
5520 # instead of 'foo_flymake.h'
erg@google.com35589e62010-11-17 18:58:16 +00005521 abs_filename = re.sub(r'_flymake\.cc$', '.cc', abs_filename)
erg@google.com6317a9c2009-06-25 00:28:19 +00005522
avakulenko@google.com59146752014-08-11 20:20:55 +00005523 # include_dict is modified during iteration, so we iterate over a copy of
erg@google.com6317a9c2009-06-25 00:28:19 +00005524 # the keys.
Sarthak Kukreti60378202019-12-17 20:46:58 +00005525 header_keys = list(include_dict.keys())
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005526 for header in header_keys:
erg@google.com6317a9c2009-06-25 00:28:19 +00005527 (same_module, common_path) = FilesBelongToSameModule(abs_filename, header)
5528 fullpath = common_path + header
avakulenko@google.com59146752014-08-11 20:20:55 +00005529 if same_module and UpdateIncludeState(fullpath, include_dict, io):
erg@google.com6317a9c2009-06-25 00:28:19 +00005530 header_found = True
5531
5532 # If we can't find the header file for a .cc, assume it's because we don't
5533 # know where to look. In that case we'll give up as we're not sure they
5534 # didn't include it in the .h file.
5535 # TODO(unknown): Do a better job of finding .h files so we are confident that
5536 # not having the .h file means there isn't one.
5537 if filename.endswith('.cc') and not header_found:
5538 return
5539
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005540 # All the lines have been processed, report the errors found.
5541 for required_header_unstripped in required:
5542 template = required[required_header_unstripped][1]
avakulenko@google.com59146752014-08-11 20:20:55 +00005543 if required_header_unstripped.strip('<>"') not in include_dict:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005544 error(filename, required[required_header_unstripped][0],
5545 'build/include_what_you_use', 4,
5546 'Add #include ' + required_header_unstripped + ' for ' + template)
5547
5548
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005549_RE_PATTERN_EXPLICIT_MAKEPAIR = re.compile(r'\bmake_pair\s*<')
5550
5551
5552def CheckMakePairUsesDeduction(filename, clean_lines, linenum, error):
5553 """Check that make_pair's template arguments are deduced.
5554
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005555 G++ 4.6 in C++11 mode fails badly if make_pair's template arguments are
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005556 specified explicitly, and such use isn't intended in any case.
5557
5558 Args:
5559 filename: The name of the current file.
5560 clean_lines: A CleansedLines instance containing the file.
5561 linenum: The number of the line to check.
5562 error: The function to call with any errors found.
5563 """
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005564 line = clean_lines.elided[linenum]
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005565 match = _RE_PATTERN_EXPLICIT_MAKEPAIR.search(line)
5566 if match:
5567 error(filename, linenum, 'build/explicit_make_pair',
5568 4, # 4 = high confidence
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005569 'For C++11-compatibility, omit template arguments from make_pair'
5570 ' OR use pair directly OR if appropriate, construct a pair directly')
avakulenko@google.com59146752014-08-11 20:20:55 +00005571
5572
avakulenko@google.com59146752014-08-11 20:20:55 +00005573def CheckRedundantVirtual(filename, clean_lines, linenum, error):
5574 """Check if line contains a redundant "virtual" function-specifier.
5575
5576 Args:
5577 filename: The name of the current file.
5578 clean_lines: A CleansedLines instance containing the file.
5579 linenum: The number of the line to check.
5580 error: The function to call with any errors found.
5581 """
5582 # Look for "virtual" on current line.
5583 line = clean_lines.elided[linenum]
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005584 virtual = Match(r'^(.*)(\bvirtual\b)(.*)$', line)
avakulenko@google.com59146752014-08-11 20:20:55 +00005585 if not virtual: return
5586
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005587 # Ignore "virtual" keywords that are near access-specifiers. These
5588 # are only used in class base-specifier and do not apply to member
5589 # functions.
5590 if (Search(r'\b(public|protected|private)\s+$', virtual.group(1)) or
5591 Match(r'^\s+(public|protected|private)\b', virtual.group(3))):
5592 return
5593
5594 # Ignore the "virtual" keyword from virtual base classes. Usually
5595 # there is a column on the same line in these cases (virtual base
5596 # classes are rare in google3 because multiple inheritance is rare).
5597 if Match(r'^.*[^:]:[^:].*$', line): return
5598
avakulenko@google.com59146752014-08-11 20:20:55 +00005599 # Look for the next opening parenthesis. This is the start of the
5600 # parameter list (possibly on the next line shortly after virtual).
5601 # TODO(unknown): doesn't work if there are virtual functions with
5602 # decltype() or other things that use parentheses, but csearch suggests
5603 # that this is rare.
5604 end_col = -1
5605 end_line = -1
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005606 start_col = len(virtual.group(2))
Edward Lemur6d31ed52019-12-02 23:00:00 +00005607 for start_line in range(linenum, min(linenum + 3, clean_lines.NumLines())):
avakulenko@google.com59146752014-08-11 20:20:55 +00005608 line = clean_lines.elided[start_line][start_col:]
5609 parameter_list = Match(r'^([^(]*)\(', line)
5610 if parameter_list:
5611 # Match parentheses to find the end of the parameter list
5612 (_, end_line, end_col) = CloseExpression(
5613 clean_lines, start_line, start_col + len(parameter_list.group(1)))
5614 break
5615 start_col = 0
5616
5617 if end_col < 0:
5618 return # Couldn't find end of parameter list, give up
5619
5620 # Look for "override" or "final" after the parameter list
5621 # (possibly on the next few lines).
Edward Lemur6d31ed52019-12-02 23:00:00 +00005622 for i in range(end_line, min(end_line + 3, clean_lines.NumLines())):
avakulenko@google.com59146752014-08-11 20:20:55 +00005623 line = clean_lines.elided[i][end_col:]
5624 match = Search(r'\b(override|final)\b', line)
5625 if match:
5626 error(filename, linenum, 'readability/inheritance', 4,
5627 ('"virtual" is redundant since function is '
5628 'already declared as "%s"' % match.group(1)))
5629
5630 # Set end_col to check whole lines after we are done with the
5631 # first line.
5632 end_col = 0
5633 if Search(r'[^\w]\s*$', line):
5634 break
5635
5636
5637def CheckRedundantOverrideOrFinal(filename, clean_lines, linenum, error):
5638 """Check if line contains a redundant "override" or "final" virt-specifier.
5639
5640 Args:
5641 filename: The name of the current file.
5642 clean_lines: A CleansedLines instance containing the file.
5643 linenum: The number of the line to check.
5644 error: The function to call with any errors found.
5645 """
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005646 # Look for closing parenthesis nearby. We need one to confirm where
5647 # the declarator ends and where the virt-specifier starts to avoid
5648 # false positives.
avakulenko@google.com59146752014-08-11 20:20:55 +00005649 line = clean_lines.elided[linenum]
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005650 declarator_end = line.rfind(')')
5651 if declarator_end >= 0:
5652 fragment = line[declarator_end:]
5653 else:
5654 if linenum > 1 and clean_lines.elided[linenum - 1].rfind(')') >= 0:
5655 fragment = line
5656 else:
5657 return
5658
5659 # Check that at most one of "override" or "final" is present, not both
5660 if Search(r'\boverride\b', fragment) and Search(r'\bfinal\b', fragment):
avakulenko@google.com59146752014-08-11 20:20:55 +00005661 error(filename, linenum, 'readability/inheritance', 4,
5662 ('"override" is redundant since function is '
5663 'already declared as "final"'))
5664
5665
5666
5667
5668# Returns true if we are at a new block, and it is directly
5669# inside of a namespace.
5670def IsBlockInNameSpace(nesting_state, is_forward_declaration):
5671 """Checks that the new block is directly in a namespace.
5672
5673 Args:
5674 nesting_state: The _NestingState object that contains info about our state.
5675 is_forward_declaration: If the class is a forward declared class.
5676 Returns:
5677 Whether or not the new block is directly in a namespace.
5678 """
5679 if is_forward_declaration:
5680 if len(nesting_state.stack) >= 1 and (
5681 isinstance(nesting_state.stack[-1], _NamespaceInfo)):
5682 return True
5683 else:
5684 return False
5685
5686 return (len(nesting_state.stack) > 1 and
5687 nesting_state.stack[-1].check_namespace_indentation and
5688 isinstance(nesting_state.stack[-2], _NamespaceInfo))
5689
5690
5691def ShouldCheckNamespaceIndentation(nesting_state, is_namespace_indent_item,
5692 raw_lines_no_comments, linenum):
5693 """This method determines if we should apply our namespace indentation check.
5694
5695 Args:
5696 nesting_state: The current nesting state.
5697 is_namespace_indent_item: If we just put a new class on the stack, True.
5698 If the top of the stack is not a class, or we did not recently
5699 add the class, False.
5700 raw_lines_no_comments: The lines without the comments.
5701 linenum: The current line number we are processing.
5702
5703 Returns:
5704 True if we should apply our namespace indentation check. Currently, it
5705 only works for classes and namespaces inside of a namespace.
5706 """
5707
5708 is_forward_declaration = IsForwardClassDeclaration(raw_lines_no_comments,
5709 linenum)
5710
5711 if not (is_namespace_indent_item or is_forward_declaration):
5712 return False
5713
5714 # If we are in a macro, we do not want to check the namespace indentation.
5715 if IsMacroDefinition(raw_lines_no_comments, linenum):
5716 return False
5717
5718 return IsBlockInNameSpace(nesting_state, is_forward_declaration)
5719
5720
5721# Call this method if the line is directly inside of a namespace.
5722# If the line above is blank (excluding comments) or the start of
5723# an inner namespace, it cannot be indented.
5724def CheckItemIndentationInNamespace(filename, raw_lines_no_comments, linenum,
5725 error):
5726 line = raw_lines_no_comments[linenum]
5727 if Match(r'^\s+', line):
5728 error(filename, linenum, 'runtime/indentation_namespace', 4,
5729 'Do not indent within a namespace')
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005730
5731
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005732def ProcessLine(filename, file_extension, clean_lines, line,
5733 include_state, function_state, nesting_state, error,
5734 extra_check_functions=[]):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005735 """Processes a single line in the file.
5736
5737 Args:
5738 filename: Filename of the file that is being processed.
5739 file_extension: The extension (dot not included) of the file.
5740 clean_lines: An array of strings, each representing a line of the file,
5741 with comments stripped.
5742 line: Number of line being processed.
5743 include_state: An _IncludeState instance in which the headers are inserted.
5744 function_state: A _FunctionState instance which counts function lines, etc.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005745 nesting_state: A NestingState instance which maintains information about
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005746 the current stack of nested blocks being parsed.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005747 error: A callable to which errors are reported, which takes 4 arguments:
5748 filename, line number, error level, and message
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005749 extra_check_functions: An array of additional check functions that will be
5750 run on each source line. Each function takes 4
5751 arguments: filename, clean_lines, line, error
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005752 """
5753 raw_lines = clean_lines.raw_lines
erg@google.com35589e62010-11-17 18:58:16 +00005754 ParseNolintSuppressions(filename, raw_lines[line], line, error)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005755 nesting_state.Update(filename, clean_lines, line, error)
avakulenko@google.com59146752014-08-11 20:20:55 +00005756 CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line,
5757 error)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005758 if nesting_state.InAsmBlock(): return
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005759 CheckForFunctionLengths(filename, clean_lines, line, function_state, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005760 CheckForMultilineCommentsAndStrings(filename, clean_lines, line, error)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005761 CheckStyle(filename, clean_lines, line, file_extension, nesting_state, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005762 CheckLanguage(filename, clean_lines, line, file_extension, include_state,
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005763 nesting_state, error)
5764 CheckForNonConstReference(filename, clean_lines, line, nesting_state, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005765 CheckForNonStandardConstructs(filename, clean_lines, line,
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005766 nesting_state, error)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005767 CheckVlogArguments(filename, clean_lines, line, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005768 CheckPosixThreading(filename, clean_lines, line, error)
erg@google.com6317a9c2009-06-25 00:28:19 +00005769 CheckInvalidIncrement(filename, clean_lines, line, error)
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005770 CheckMakePairUsesDeduction(filename, clean_lines, line, error)
avakulenko@google.com59146752014-08-11 20:20:55 +00005771 CheckRedundantVirtual(filename, clean_lines, line, error)
5772 CheckRedundantOverrideOrFinal(filename, clean_lines, line, error)
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005773 for check_fn in extra_check_functions:
5774 check_fn(filename, clean_lines, line, error)
avakulenko@google.com17449932014-07-28 22:13:33 +00005775
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005776def FlagCxx11Features(filename, clean_lines, linenum, error):
5777 """Flag those c++11 features that we only allow in certain places.
5778
5779 Args:
5780 filename: The name of the current file.
5781 clean_lines: A CleansedLines instance containing the file.
5782 linenum: The number of the line to check.
5783 error: The function to call with any errors found.
5784 """
5785 line = clean_lines.elided[linenum]
5786
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005787 include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line)
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005788
5789 # Flag unapproved C++ TR1 headers.
5790 if include and include.group(1).startswith('tr1/'):
5791 error(filename, linenum, 'build/c++tr1', 5,
5792 ('C++ TR1 headers such as <%s> are unapproved.') % include.group(1))
5793
5794 # Flag unapproved C++11 headers.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005795 if include and include.group(1) in ('cfenv',
5796 'condition_variable',
5797 'fenv.h',
5798 'future',
5799 'mutex',
5800 'thread',
5801 'chrono',
5802 'ratio',
5803 'regex',
5804 'system_error',
5805 ):
5806 error(filename, linenum, 'build/c++11', 5,
5807 ('<%s> is an unapproved C++11 header.') % include.group(1))
5808
5809 # The only place where we need to worry about C++11 keywords and library
5810 # features in preprocessor directives is in macro definitions.
5811 if Match(r'\s*#', line) and not Match(r'\s*#\s*define\b', line): return
5812
5813 # These are classes and free functions. The classes are always
5814 # mentioned as std::*, but we only catch the free functions if
5815 # they're not found by ADL. They're alphabetical by header.
5816 for top_name in (
5817 # type_traits
5818 'alignment_of',
5819 'aligned_union',
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005820 ):
5821 if Search(r'\bstd::%s\b' % top_name, line):
5822 error(filename, linenum, 'build/c++11', 5,
5823 ('std::%s is an unapproved C++11 class or function. Send c-style '
5824 'an example of where it would make your code more readable, and '
5825 'they may let you use it.') % top_name)
5826
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005827
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005828def FlagCxx14Features(filename, clean_lines, linenum, error):
5829 """Flag those C++14 features that we restrict.
5830
5831 Args:
5832 filename: The name of the current file.
5833 clean_lines: A CleansedLines instance containing the file.
5834 linenum: The number of the line to check.
5835 error: The function to call with any errors found.
5836 """
5837 line = clean_lines.elided[linenum]
5838
5839 include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line)
5840
5841 # Flag unapproved C++14 headers.
5842 if include and include.group(1) in ('scoped_allocator', 'shared_mutex'):
5843 error(filename, linenum, 'build/c++14', 5,
5844 ('<%s> is an unapproved C++14 header.') % include.group(1))
5845
5846
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005847def ProcessFileData(filename, file_extension, lines, error,
5848 extra_check_functions=[]):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005849 """Performs lint checks and reports any errors to the given error function.
5850
5851 Args:
5852 filename: Filename of the file that is being processed.
5853 file_extension: The extension (dot not included) of the file.
5854 lines: An array of strings, each representing a line of the file, with the
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005855 last element being empty if the file is terminated with a newline.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005856 error: A callable to which errors are reported, which takes 4 arguments:
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005857 filename, line number, error level, and message
5858 extra_check_functions: An array of additional check functions that will be
5859 run on each source line. Each function takes 4
5860 arguments: filename, clean_lines, line, error
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005861 """
5862 lines = (['// marker so line numbers and indices both start at 1'] + lines +
5863 ['// marker so line numbers end in a known way'])
5864
5865 include_state = _IncludeState()
5866 function_state = _FunctionState()
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005867 nesting_state = NestingState()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005868
erg@google.com35589e62010-11-17 18:58:16 +00005869 ResetNolintSuppressions()
5870
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005871 CheckForCopyright(filename, lines, error)
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005872 ProcessGlobalSuppresions(lines)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005873 RemoveMultiLineComments(filename, lines, error)
5874 clean_lines = CleansedLines(lines)
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005875
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00005876 if file_extension == 'h':
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005877 CheckForHeaderGuard(filename, clean_lines, error)
5878
Edward Lemur6d31ed52019-12-02 23:00:00 +00005879 for line in range(clean_lines.NumLines()):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005880 ProcessLine(filename, file_extension, clean_lines, line,
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005881 include_state, function_state, nesting_state, error,
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005882 extra_check_functions)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005883 FlagCxx11Features(filename, clean_lines, line, error)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005884 nesting_state.CheckCompletedBlocks(filename, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005885
5886 CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error)
skym@chromium.org3990c412016-02-05 20:55:12 +00005887
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005888 # Check that the .cc file has included its header if it exists.
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005889 if _IsSourceExtension(file_extension):
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005890 CheckHeaderFileIncluded(filename, include_state, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005891
5892 # We check here rather than inside ProcessLine so that we see raw
5893 # lines rather than "cleaned" lines.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005894 CheckForBadCharacters(filename, lines, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005895
5896 CheckForNewlineAtEOF(filename, lines, error)
5897
avakulenko@google.com17449932014-07-28 22:13:33 +00005898def ProcessConfigOverrides(filename):
5899 """ Loads the configuration files and processes the config overrides.
5900
5901 Args:
5902 filename: The name of the file being processed by the linter.
5903
5904 Returns:
5905 False if the current |filename| should not be processed further.
5906 """
5907
5908 abs_filename = os.path.abspath(filename)
5909 cfg_filters = []
5910 keep_looking = True
5911 while keep_looking:
5912 abs_path, base_name = os.path.split(abs_filename)
5913 if not base_name:
5914 break # Reached the root directory.
5915
5916 cfg_file = os.path.join(abs_path, "CPPLINT.cfg")
5917 abs_filename = abs_path
5918 if not os.path.isfile(cfg_file):
5919 continue
5920
5921 try:
5922 with open(cfg_file) as file_handle:
5923 for line in file_handle:
5924 line, _, _ = line.partition('#') # Remove comments.
5925 if not line.strip():
5926 continue
5927
5928 name, _, val = line.partition('=')
5929 name = name.strip()
5930 val = val.strip()
5931 if name == 'set noparent':
5932 keep_looking = False
5933 elif name == 'filter':
5934 cfg_filters.append(val)
5935 elif name == 'exclude_files':
5936 # When matching exclude_files pattern, use the base_name of
5937 # the current file name or the directory name we are processing.
5938 # For example, if we are checking for lint errors in /foo/bar/baz.cc
5939 # and we found the .cfg file at /foo/CPPLINT.cfg, then the config
5940 # file's "exclude_files" filter is meant to be checked against "bar"
5941 # and not "baz" nor "bar/baz.cc".
5942 if base_name:
5943 pattern = re.compile(val)
5944 if pattern.match(base_name):
5945 sys.stderr.write('Ignoring "%s": file excluded by "%s". '
5946 'File path component "%s" matches '
5947 'pattern "%s"\n' %
5948 (filename, cfg_file, base_name, val))
5949 return False
avakulenko@google.com68a4fa62014-08-25 16:26:18 +00005950 elif name == 'linelength':
5951 global _line_length
5952 try:
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +00005953 _line_length = int(val)
avakulenko@google.com68a4fa62014-08-25 16:26:18 +00005954 except ValueError:
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +00005955 sys.stderr.write('Line length must be numeric.')
avakulenko@google.com17449932014-07-28 22:13:33 +00005956 else:
5957 sys.stderr.write(
5958 'Invalid configuration option (%s) in file %s\n' %
5959 (name, cfg_file))
5960
5961 except IOError:
5962 sys.stderr.write(
5963 "Skipping config file '%s': Can't open for reading\n" % cfg_file)
5964 keep_looking = False
5965
5966 # Apply all the accumulated filters in reverse order (top-level directory
5967 # config options having the least priority).
5968 for filter in reversed(cfg_filters):
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +00005969 _AddFilters(filter)
avakulenko@google.com17449932014-07-28 22:13:33 +00005970
5971 return True
5972
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005973
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005974def ProcessFile(filename, vlevel, extra_check_functions=[]):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005975 """Does google-lint on a single file.
5976
5977 Args:
5978 filename: The name of the file to parse.
5979
5980 vlevel: The level of errors to report. Every error of confidence
5981 >= verbose_level will be reported. 0 is a good default.
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005982
5983 extra_check_functions: An array of additional check functions that will be
5984 run on each source line. Each function takes 4
5985 arguments: filename, clean_lines, line, error
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005986 """
5987
5988 _SetVerboseLevel(vlevel)
avakulenko@google.com17449932014-07-28 22:13:33 +00005989 _BackupFilters()
5990
5991 if not ProcessConfigOverrides(filename):
5992 _RestoreFilters()
5993 return
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005994
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005995 lf_lines = []
5996 crlf_lines = []
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005997 try:
5998 # Support the UNIX convention of using "-" for stdin. Note that
5999 # we are not opening the file with universal newline support
6000 # (which codecs doesn't support anyway), so the resulting lines do
6001 # contain trailing '\r' characters if we are reading a file that
6002 # has CRLF endings.
6003 # If after the split a trailing '\r' is present, it is removed
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00006004 # below.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006005 if filename == '-':
6006 lines = codecs.StreamReaderWriter(sys.stdin,
6007 codecs.getreader('utf8'),
6008 codecs.getwriter('utf8'),
6009 'replace').read().split('\n')
6010 else:
6011 lines = codecs.open(filename, 'r', 'utf8', 'replace').read().split('\n')
6012
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006013 # Remove trailing '\r'.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00006014 # The -1 accounts for the extra trailing blank line we get from split()
6015 for linenum in range(len(lines) - 1):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006016 if lines[linenum].endswith('\r'):
6017 lines[linenum] = lines[linenum].rstrip('\r')
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00006018 crlf_lines.append(linenum + 1)
6019 else:
6020 lf_lines.append(linenum + 1)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006021
6022 except IOError:
6023 sys.stderr.write(
6024 "Skipping input '%s': Can't open for reading\n" % filename)
avakulenko@google.com17449932014-07-28 22:13:33 +00006025 _RestoreFilters()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006026 return
6027
6028 # Note, if no dot is found, this will give the entire filename as the ext.
6029 file_extension = filename[filename.rfind('.') + 1:]
6030
6031 # When reading from stdin, the extension is unknown, so no cpplint tests
6032 # should rely on the extension.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00006033 if filename != '-' and file_extension not in _valid_extensions:
6034 sys.stderr.write('Ignoring %s; not a valid file name '
6035 '(%s)\n' % (filename, ', '.join(_valid_extensions)))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006036 else:
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00006037 ProcessFileData(filename, file_extension, lines, Error,
6038 extra_check_functions)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00006039
6040 # If end-of-line sequences are a mix of LF and CR-LF, issue
6041 # warnings on the lines with CR.
6042 #
6043 # Don't issue any warnings if all lines are uniformly LF or CR-LF,
6044 # since critique can handle these just fine, and the style guide
6045 # doesn't dictate a particular end of line sequence.
6046 #
6047 # We can't depend on os.linesep to determine what the desired
6048 # end-of-line sequence should be, since that will return the
6049 # server-side end-of-line sequence.
6050 if lf_lines and crlf_lines:
6051 # Warn on every line with CR. An alternative approach might be to
6052 # check whether the file is mostly CRLF or just LF, and warn on the
6053 # minority, we bias toward LF here since most tools prefer LF.
6054 for linenum in crlf_lines:
6055 Error(filename, linenum, 'whitespace/newline', 1,
6056 'Unexpected \\r (^M) found; better to use only \\n')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006057
avakulenko@google.com17449932014-07-28 22:13:33 +00006058 _RestoreFilters()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006059
6060
6061def PrintUsage(message):
6062 """Prints a brief usage string and exits, optionally with an error message.
6063
6064 Args:
6065 message: The optional error message.
6066 """
6067 sys.stderr.write(_USAGE)
6068 if message:
6069 sys.exit('\nFATAL ERROR: ' + message)
6070 else:
6071 sys.exit(1)
6072
6073
6074def PrintCategories():
6075 """Prints a list of all the error-categories used by error messages.
6076
6077 These are the categories used to filter messages via --filter.
6078 """
erg@google.com35589e62010-11-17 18:58:16 +00006079 sys.stderr.write(''.join(' %s\n' % cat for cat in _ERROR_CATEGORIES))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006080 sys.exit(0)
6081
6082
6083def ParseArguments(args):
6084 """Parses the command line arguments.
6085
6086 This may set the output format and verbosity level as side-effects.
6087
6088 Args:
6089 args: The command line arguments:
6090
6091 Returns:
6092 The list of filenames to lint.
6093 """
6094 try:
6095 (opts, filenames) = getopt.getopt(args, '', ['help', 'output=', 'verbose=',
Jordan Bayles91a32c52019-02-22 21:28:17 +00006096 'headers=', # We understand but ignore headers.
erg@google.com26970fa2009-11-17 18:07:32 +00006097 'counting=',
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00006098 'filter=',
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00006099 'root=',
6100 'linelength=',
sdefresne263e9282016-07-19 02:14:22 -07006101 'extensions=',
Jordan Bayles91a32c52019-02-22 21:28:17 +00006102 'project_root=',
6103 'repository='])
6104 except getopt.GetoptError as e:
6105 PrintUsage('Invalid arguments: {}'.format(e))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006106
6107 verbosity = _VerboseLevel()
6108 output_format = _OutputFormat()
6109 filters = ''
erg@google.com26970fa2009-11-17 18:07:32 +00006110 counting_style = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006111
6112 for (opt, val) in opts:
6113 if opt == '--help':
6114 PrintUsage(None)
6115 elif opt == '--output':
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00006116 if val not in ('emacs', 'vs7', 'eclipse'):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00006117 PrintUsage('The only allowed output formats are emacs, vs7 and eclipse.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006118 output_format = val
6119 elif opt == '--verbose':
6120 verbosity = int(val)
6121 elif opt == '--filter':
6122 filters = val
erg@google.com6317a9c2009-06-25 00:28:19 +00006123 if not filters:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006124 PrintCategories()
erg@google.com26970fa2009-11-17 18:07:32 +00006125 elif opt == '--counting':
6126 if val not in ('total', 'toplevel', 'detailed'):
6127 PrintUsage('Valid counting options are total, toplevel, and detailed')
6128 counting_style = val
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00006129 elif opt == '--root':
6130 global _root
6131 _root = val
Jordan Bayles91a32c52019-02-22 21:28:17 +00006132 elif opt == '--project_root' or opt == "--repository":
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00006133 global _project_root
6134 _project_root = val
6135 if not os.path.isabs(_project_root):
6136 PrintUsage('Project root must be an absolute path.')
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00006137 elif opt == '--linelength':
6138 global _line_length
6139 try:
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +00006140 _line_length = int(val)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00006141 except ValueError:
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +00006142 PrintUsage('Line length must be digits.')
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00006143 elif opt == '--extensions':
6144 global _valid_extensions
6145 try:
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +00006146 _valid_extensions = set(val.split(','))
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00006147 except ValueError:
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +00006148 PrintUsage('Extensions must be comma separated list.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006149
6150 if not filenames:
6151 PrintUsage('No files were specified.')
6152
6153 _SetOutputFormat(output_format)
6154 _SetVerboseLevel(verbosity)
6155 _SetFilters(filters)
erg@google.com26970fa2009-11-17 18:07:32 +00006156 _SetCountingStyle(counting_style)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006157
6158 return filenames
6159
6160
6161def main():
6162 filenames = ParseArguments(sys.argv[1:])
6163
6164 # Change stderr to write with replacement characters so we don't die
6165 # if we try to print something containing non-ASCII characters.
Edward Lemur6d31ed52019-12-02 23:00:00 +00006166 # We use sys.stderr.buffer in Python 3, since StreamReaderWriter writes bytes
6167 # to the specified stream.
6168 sys.stderr = codecs.StreamReaderWriter(
6169 getattr(sys.stderr, 'buffer', sys.stderr),
6170 codecs.getreader('utf8'), codecs.getwriter('utf8'), 'replace')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006171
erg@google.com26970fa2009-11-17 18:07:32 +00006172 _cpplint_state.ResetErrorCounts()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006173 for filename in filenames:
6174 ProcessFile(filename, _cpplint_state.verbose_level)
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00006175 _cpplint_state.PrintErrorCounts()
erg@google.com26970fa2009-11-17 18:07:32 +00006176
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006177 sys.exit(_cpplint_state.error_count > 0)
6178
6179
6180if __name__ == '__main__':
6181 main()