blob: 6cb84adf3f9c797571a1f0246a44a1de8878047c [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',
332 'array',
333 'atomic',
334 'bitset',
335 'chrono',
336 'codecvt',
337 'complex',
338 'condition_variable',
339 'deque',
340 'exception',
341 'forward_list',
342 'fstream',
343 'functional',
344 'future',
345 'initializer_list',
346 'iomanip',
347 'ios',
348 'iosfwd',
349 'iostream',
350 'istream',
351 'iterator',
352 'limits',
353 'list',
354 'locale',
355 'map',
356 'memory',
357 'mutex',
358 'new',
359 'numeric',
360 'ostream',
361 'queue',
362 'random',
363 'ratio',
364 'regex',
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000365 'scoped_allocator',
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000366 'set',
367 'sstream',
368 'stack',
369 'stdexcept',
370 'streambuf',
371 'string',
Jasper Chapman-Black9ab047e2019-11-07 15:51:54 +0000372 'string_view',
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000373 'strstream',
374 'system_error',
375 'thread',
376 'tuple',
377 'typeindex',
378 'typeinfo',
379 'type_traits',
380 'unordered_map',
381 'unordered_set',
382 'utility',
383 'valarray',
384 'vector',
385 # 17.6.1.2 C++ headers for C library facilities
386 'cassert',
387 'ccomplex',
388 'cctype',
389 'cerrno',
390 'cfenv',
391 'cfloat',
392 'cinttypes',
393 'ciso646',
394 'climits',
395 'clocale',
396 'cmath',
397 'csetjmp',
398 'csignal',
399 'cstdalign',
400 'cstdarg',
401 'cstdbool',
402 'cstddef',
403 'cstdint',
404 'cstdio',
405 'cstdlib',
406 'cstring',
407 'ctgmath',
408 'ctime',
409 'cuchar',
410 'cwchar',
411 'cwctype',
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000412 ])
413
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000414# Type names
415_TYPES = re.compile(
416 r'^(?:'
417 # [dcl.type.simple]
418 r'(char(16_t|32_t)?)|wchar_t|'
419 r'bool|short|int|long|signed|unsigned|float|double|'
420 # [support.types]
421 r'(ptrdiff_t|size_t|max_align_t|nullptr_t)|'
422 # [cstdint.syn]
423 r'(u?int(_fast|_least)?(8|16|32|64)_t)|'
424 r'(u?int(max|ptr)_t)|'
425 r')$')
426
avakulenko@google.comd39bbb52014-06-04 22:55:20 +0000427
Fletcher Woodruff11b34152020-04-23 21:21:40 +0000428# These headers are excluded from [build/include], [build/include_directory],
429# and [build/include_order] checks:
avakulenko@google.com59146752014-08-11 20:20:55 +0000430# - Anything not following google file name conventions (containing an
431# uppercase character, such as Python.h or nsStringAPI.h, for example).
432# - Lua headers.
433_THIRD_PARTY_HEADERS_PATTERN = re.compile(
434 r'^(?:[^/]*[A-Z][^/]*\.h|lua\.h|lauxlib\.h|lualib\.h)$')
435
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000436# Pattern for matching FileInfo.BaseName() against test file name
437_TEST_FILE_SUFFIX = r'(_test|_unittest|_regtest)$'
438
439# Pattern that matches only complete whitespace, possibly across multiple lines.
440_EMPTY_CONDITIONAL_BODY_PATTERN = re.compile(r'^\s*$', re.DOTALL)
avakulenko@google.com59146752014-08-11 20:20:55 +0000441
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000442# Assertion macros. These are defined in base/logging.h and
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000443# testing/base/public/gunit.h.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000444_CHECK_MACROS = [
erg@google.com6317a9c2009-06-25 00:28:19 +0000445 'DCHECK', 'CHECK',
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000446 'EXPECT_TRUE', 'ASSERT_TRUE',
447 'EXPECT_FALSE', 'ASSERT_FALSE',
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000448 ]
449
erg@google.com6317a9c2009-06-25 00:28:19 +0000450# Replacement macros for CHECK/DCHECK/EXPECT_TRUE/EXPECT_FALSE
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000451_CHECK_REPLACEMENT = dict([(m, {}) for m in _CHECK_MACROS])
452
453for op, replacement in [('==', 'EQ'), ('!=', 'NE'),
454 ('>=', 'GE'), ('>', 'GT'),
455 ('<=', 'LE'), ('<', 'LT')]:
erg@google.com6317a9c2009-06-25 00:28:19 +0000456 _CHECK_REPLACEMENT['DCHECK'][op] = 'DCHECK_%s' % replacement
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000457 _CHECK_REPLACEMENT['CHECK'][op] = 'CHECK_%s' % replacement
458 _CHECK_REPLACEMENT['EXPECT_TRUE'][op] = 'EXPECT_%s' % replacement
459 _CHECK_REPLACEMENT['ASSERT_TRUE'][op] = 'ASSERT_%s' % replacement
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000460
461for op, inv_replacement in [('==', 'NE'), ('!=', 'EQ'),
462 ('>=', 'LT'), ('>', 'LE'),
463 ('<=', 'GT'), ('<', 'GE')]:
464 _CHECK_REPLACEMENT['EXPECT_FALSE'][op] = 'EXPECT_%s' % inv_replacement
465 _CHECK_REPLACEMENT['ASSERT_FALSE'][op] = 'ASSERT_%s' % inv_replacement
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000466
mazda@chromium.org3fffcec2013-06-07 01:04:53 +0000467# Alternative tokens and their replacements. For full list, see section 2.5
468# Alternative tokens [lex.digraph] in the C++ standard.
469#
470# Digraphs (such as '%:') are not included here since it's a mess to
471# match those on a word boundary.
472_ALT_TOKEN_REPLACEMENT = {
473 'and': '&&',
474 'bitor': '|',
475 'or': '||',
476 'xor': '^',
477 'compl': '~',
478 'bitand': '&',
479 'and_eq': '&=',
480 'or_eq': '|=',
481 'xor_eq': '^=',
482 'not': '!',
483 'not_eq': '!='
484 }
485
486# Compile regular expression that matches all the above keywords. The "[ =()]"
487# bit is meant to avoid matching these keywords outside of boolean expressions.
488#
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000489# False positives include C-style multi-line comments and multi-line strings
490# but those have always been troublesome for cpplint.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +0000491_ALT_TOKEN_REPLACEMENT_PATTERN = re.compile(
492 r'[ =()](' + ('|'.join(_ALT_TOKEN_REPLACEMENT.keys())) + r')(?=[ (]|$)')
493
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000494
495# These constants define types of headers for use with
496# _IncludeState.CheckNextIncludeOrder().
497_C_SYS_HEADER = 1
498_CPP_SYS_HEADER = 2
499_LIKELY_MY_HEADER = 3
500_POSSIBLE_MY_HEADER = 4
501_OTHER_HEADER = 5
502
mazda@chromium.org3fffcec2013-06-07 01:04:53 +0000503# These constants define the current inline assembly state
504_NO_ASM = 0 # Outside of inline assembly block
505_INSIDE_ASM = 1 # Inside inline assembly block
506_END_ASM = 2 # Last line of inline assembly block
507_BLOCK_ASM = 3 # The whole block is an inline assembly block
508
509# Match start of assembly blocks
510_MATCH_ASM = re.compile(r'^\s*(?:asm|_asm|__asm|__asm__)'
511 r'(?:\s+(volatile|__volatile__))?'
512 r'\s*[{(]')
513
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000514# Match strings that indicate we're working on a C (not C++) file.
515_SEARCH_C_FILE = re.compile(r'\b(?:LINT_C_FILE|'
516 r'vim?:\s*.*(\s*|:)filetype=c(\s*|:|$))')
517
518# Match string that indicates we're working on a Linux Kernel file.
519_SEARCH_KERNEL_FILE = re.compile(r'\b(?:LINT_KERNEL_FILE)')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000520
521_regexp_compile_cache = {}
522
erg@google.com35589e62010-11-17 18:58:16 +0000523# {str, set(int)}: a map from error categories to sets of linenumbers
524# on which those errors are expected and should be suppressed.
525_error_suppressions = {}
526
mazda@chromium.org3fffcec2013-06-07 01:04:53 +0000527# The root directory used for deriving header guard CPP variable.
528# This is set by --root flag.
529_root = None
David Sanders2f988472022-05-21 01:35:11 +0000530_root_debug = False
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +0000531
532# The project root directory. Used for deriving header guard CPP variable.
533# This is set by --project_root flag. Must be an absolute path.
534_project_root = None
sdefresne263e9282016-07-19 02:14:22 -0700535
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000536# The allowed line length of files.
537# This is set by --linelength flag.
538_line_length = 80
539
540# The allowed extensions for file names
541# This is set by --extensions flag.
542_valid_extensions = set(['cc', 'h', 'cpp', 'cu', 'cuh'])
543
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000544# {str, bool}: a map from error categories to booleans which indicate if the
545# category should be suppressed for every line.
546_global_error_suppressions = {}
547
548
erg@google.com35589e62010-11-17 18:58:16 +0000549def ParseNolintSuppressions(filename, raw_line, linenum, error):
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000550 """Updates the global list of line error-suppressions.
erg@google.com35589e62010-11-17 18:58:16 +0000551
552 Parses any NOLINT comments on the current line, updating the global
553 error_suppressions store. Reports an error if the NOLINT comment
554 was malformed.
555
556 Args:
557 filename: str, the name of the input file.
558 raw_line: str, the line of input text, with comments.
559 linenum: int, the number of the current line.
560 error: function, an error handler.
561 """
avakulenko@google.com59146752014-08-11 20:20:55 +0000562 matched = Search(r'\bNOLINT(NEXTLINE)?\b(\([^)]+\))?', raw_line)
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +0000563 if matched:
avakulenko@google.com59146752014-08-11 20:20:55 +0000564 if matched.group(1):
565 suppressed_line = linenum + 1
566 else:
567 suppressed_line = linenum
568 category = matched.group(2)
erg@google.com35589e62010-11-17 18:58:16 +0000569 if category in (None, '(*)'): # => "suppress all"
avakulenko@google.com59146752014-08-11 20:20:55 +0000570 _error_suppressions.setdefault(None, set()).add(suppressed_line)
erg@google.com35589e62010-11-17 18:58:16 +0000571 else:
572 if category.startswith('(') and category.endswith(')'):
573 category = category[1:-1]
574 if category in _ERROR_CATEGORIES:
avakulenko@google.com59146752014-08-11 20:20:55 +0000575 _error_suppressions.setdefault(category, set()).add(suppressed_line)
avakulenko@google.com255f2be2014-12-05 22:19:55 +0000576 elif category not in _LEGACY_ERROR_CATEGORIES:
erg@google.com35589e62010-11-17 18:58:16 +0000577 error(filename, linenum, 'readability/nolint', 5,
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +0000578 'Unknown NOLINT error category: %s' % category)
erg@google.com35589e62010-11-17 18:58:16 +0000579
580
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000581def ProcessGlobalSuppresions(lines):
582 """Updates the list of global error suppressions.
583
584 Parses any lint directives in the file that have global effect.
585
586 Args:
587 lines: An array of strings, each representing a line of the file, with the
588 last element being empty if the file is terminated with a newline.
589 """
590 for line in lines:
591 if _SEARCH_C_FILE.search(line):
592 for category in _DEFAULT_C_SUPPRESSED_CATEGORIES:
593 _global_error_suppressions[category] = True
594 if _SEARCH_KERNEL_FILE.search(line):
595 for category in _DEFAULT_KERNEL_SUPPRESSED_CATEGORIES:
596 _global_error_suppressions[category] = True
597
598
erg@google.com35589e62010-11-17 18:58:16 +0000599def ResetNolintSuppressions():
avakulenko@google.com59146752014-08-11 20:20:55 +0000600 """Resets the set of NOLINT suppressions to empty."""
erg@google.com35589e62010-11-17 18:58:16 +0000601 _error_suppressions.clear()
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000602 _global_error_suppressions.clear()
erg@google.com35589e62010-11-17 18:58:16 +0000603
604
605def IsErrorSuppressedByNolint(category, linenum):
606 """Returns true if the specified error category is suppressed on this line.
607
608 Consults the global error_suppressions map populated by
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000609 ParseNolintSuppressions/ProcessGlobalSuppresions/ResetNolintSuppressions.
erg@google.com35589e62010-11-17 18:58:16 +0000610
611 Args:
612 category: str, the category of the error.
613 linenum: int, the current line number.
614 Returns:
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000615 bool, True iff the error should be suppressed due to a NOLINT comment or
616 global suppression.
erg@google.com35589e62010-11-17 18:58:16 +0000617 """
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000618 return (_global_error_suppressions.get(category, False) or
619 linenum in _error_suppressions.get(category, set()) or
erg@google.com35589e62010-11-17 18:58:16 +0000620 linenum in _error_suppressions.get(None, set()))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000621
avakulenko@google.comd39bbb52014-06-04 22:55:20 +0000622
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000623def Match(pattern, s):
624 """Matches the string with the pattern, caching the compiled regexp."""
625 # The regexp compilation caching is inlined in both Match and Search for
626 # performance reasons; factoring it out into a separate function turns out
627 # to be noticeably expensive.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000628 if pattern not in _regexp_compile_cache:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000629 _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
630 return _regexp_compile_cache[pattern].match(s)
631
632
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000633def ReplaceAll(pattern, rep, s):
634 """Replaces instances of pattern in a string with a replacement.
635
636 The compiled regex is kept in a cache shared by Match and Search.
637
638 Args:
639 pattern: regex pattern
640 rep: replacement text
641 s: search string
642
643 Returns:
644 string with replacements made (or original string if no replacements)
645 """
646 if pattern not in _regexp_compile_cache:
647 _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
648 return _regexp_compile_cache[pattern].sub(rep, s)
649
650
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000651def Search(pattern, s):
652 """Searches the string for the pattern, caching the compiled regexp."""
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000653 if pattern not in _regexp_compile_cache:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000654 _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
655 return _regexp_compile_cache[pattern].search(s)
656
657
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000658def _IsSourceExtension(s):
659 """File extension (excluding dot) matches a source file extension."""
660 return s in ('c', 'cc', 'cpp', 'cxx')
661
662
avakulenko@google.com59146752014-08-11 20:20:55 +0000663class _IncludeState(object):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000664 """Tracks line numbers for includes, and the order in which includes appear.
665
avakulenko@google.com59146752014-08-11 20:20:55 +0000666 include_list contains list of lists of (header, line number) pairs.
667 It's a lists of lists rather than just one flat list to make it
668 easier to update across preprocessor boundaries.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000669
670 Call CheckNextIncludeOrder() once for each header in the file, passing
671 in the type constants defined above. Calls in an illegal order will
672 raise an _IncludeError with an appropriate error message.
673
674 """
675 # self._section will move monotonically through this set. If it ever
676 # needs to move backwards, CheckNextIncludeOrder will raise an error.
677 _INITIAL_SECTION = 0
678 _MY_H_SECTION = 1
679 _C_SECTION = 2
680 _CPP_SECTION = 3
681 _OTHER_H_SECTION = 4
682
683 _TYPE_NAMES = {
684 _C_SYS_HEADER: 'C system header',
685 _CPP_SYS_HEADER: 'C++ system header',
686 _LIKELY_MY_HEADER: 'header this file implements',
687 _POSSIBLE_MY_HEADER: 'header this file may implement',
688 _OTHER_HEADER: 'other header',
689 }
690 _SECTION_NAMES = {
691 _INITIAL_SECTION: "... nothing. (This can't be an error.)",
692 _MY_H_SECTION: 'a header this file implements',
693 _C_SECTION: 'C system header',
694 _CPP_SECTION: 'C++ system header',
695 _OTHER_H_SECTION: 'other header',
696 }
697
698 def __init__(self):
avakulenko@google.com59146752014-08-11 20:20:55 +0000699 self.include_list = [[]]
700 self.ResetSection('')
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000701
avakulenko@google.com59146752014-08-11 20:20:55 +0000702 def FindHeader(self, header):
703 """Check if a header has already been included.
704
705 Args:
706 header: header to check.
707 Returns:
708 Line number of previous occurrence, or -1 if the header has not
709 been seen before.
710 """
711 for section_list in self.include_list:
712 for f in section_list:
713 if f[0] == header:
714 return f[1]
715 return -1
716
717 def ResetSection(self, directive):
718 """Reset section checking for preprocessor directive.
719
720 Args:
721 directive: preprocessor directive (e.g. "if", "else").
722 """
erg@google.com26970fa2009-11-17 18:07:32 +0000723 # The name of the current section.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000724 self._section = self._INITIAL_SECTION
erg@google.com26970fa2009-11-17 18:07:32 +0000725 # The path of last found header.
726 self._last_header = ''
727
avakulenko@google.com59146752014-08-11 20:20:55 +0000728 # Update list of includes. Note that we never pop from the
729 # include list.
730 if directive in ('if', 'ifdef', 'ifndef'):
731 self.include_list.append([])
732 elif directive in ('else', 'elif'):
733 self.include_list[-1] = []
734
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000735 def SetLastHeader(self, header_path):
736 self._last_header = header_path
737
erg@google.com26970fa2009-11-17 18:07:32 +0000738 def CanonicalizeAlphabeticalOrder(self, header_path):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +0000739 """Returns a path canonicalized for alphabetical comparison.
erg@google.com26970fa2009-11-17 18:07:32 +0000740
741 - replaces "-" with "_" so they both cmp the same.
742 - removes '-inl' since we don't require them to be after the main header.
743 - lowercase everything, just in case.
744
745 Args:
746 header_path: Path to be canonicalized.
747
748 Returns:
749 Canonicalized path.
750 """
751 return header_path.replace('-inl.h', '.h').replace('-', '_').lower()
752
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000753 def IsInAlphabeticalOrder(self, clean_lines, linenum, header_path):
erg@google.com26970fa2009-11-17 18:07:32 +0000754 """Check if a header is in alphabetical order with the previous header.
755
756 Args:
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000757 clean_lines: A CleansedLines instance containing the file.
758 linenum: The number of the line to check.
759 header_path: Canonicalized header to be checked.
erg@google.com26970fa2009-11-17 18:07:32 +0000760
761 Returns:
762 Returns true if the header is in alphabetical order.
763 """
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000764 # If previous section is different from current section, _last_header will
765 # be reset to empty string, so it's always less than current header.
766 #
767 # If previous line was a blank line, assume that the headers are
768 # intentionally sorted the way they are.
769 if (self._last_header > header_path and
avakulenko@google.com255f2be2014-12-05 22:19:55 +0000770 Match(r'^\s*#\s*include\b', clean_lines.elided[linenum - 1])):
erg@google.com26970fa2009-11-17 18:07:32 +0000771 return False
erg@google.com26970fa2009-11-17 18:07:32 +0000772 return True
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000773
774 def CheckNextIncludeOrder(self, header_type):
775 """Returns a non-empty error message if the next header is out of order.
776
777 This function also updates the internal state to be ready to check
778 the next include.
779
780 Args:
781 header_type: One of the _XXX_HEADER constants defined above.
782
783 Returns:
784 The empty string if the header is in the right order, or an
785 error message describing what's wrong.
786
787 """
788 error_message = ('Found %s after %s' %
789 (self._TYPE_NAMES[header_type],
790 self._SECTION_NAMES[self._section]))
791
erg@google.com26970fa2009-11-17 18:07:32 +0000792 last_section = self._section
793
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000794 if header_type == _C_SYS_HEADER:
795 if self._section <= self._C_SECTION:
796 self._section = self._C_SECTION
797 else:
erg@google.com26970fa2009-11-17 18:07:32 +0000798 self._last_header = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000799 return error_message
800 elif header_type == _CPP_SYS_HEADER:
801 if self._section <= self._CPP_SECTION:
802 self._section = self._CPP_SECTION
803 else:
erg@google.com26970fa2009-11-17 18:07:32 +0000804 self._last_header = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000805 return error_message
806 elif header_type == _LIKELY_MY_HEADER:
807 if self._section <= self._MY_H_SECTION:
808 self._section = self._MY_H_SECTION
809 else:
810 self._section = self._OTHER_H_SECTION
811 elif header_type == _POSSIBLE_MY_HEADER:
812 if self._section <= self._MY_H_SECTION:
813 self._section = self._MY_H_SECTION
814 else:
815 # This will always be the fallback because we're not sure
816 # enough that the header is associated with this file.
817 self._section = self._OTHER_H_SECTION
818 else:
819 assert header_type == _OTHER_HEADER
820 self._section = self._OTHER_H_SECTION
821
erg@google.com26970fa2009-11-17 18:07:32 +0000822 if last_section != self._section:
823 self._last_header = ''
824
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000825 return ''
826
827
828class _CppLintState(object):
829 """Maintains module-wide state.."""
830
831 def __init__(self):
832 self.verbose_level = 1 # global setting.
833 self.error_count = 0 # global count of reported errors
erg@google.com6317a9c2009-06-25 00:28:19 +0000834 # filters to apply when emitting error messages
835 self.filters = _DEFAULT_FILTERS[:]
avakulenko@google.com17449932014-07-28 22:13:33 +0000836 # backup of filter list. Used to restore the state after each file.
837 self._filters_backup = self.filters[:]
erg@google.com26970fa2009-11-17 18:07:32 +0000838 self.counting = 'total' # In what way are we counting errors?
839 self.errors_by_category = {} # string to int dict storing error counts
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000840
841 # output format:
842 # "emacs" - format that emacs can parse (default)
843 # "vs7" - format that Microsoft Visual Studio 7 can parse
844 self.output_format = 'emacs'
845
846 def SetOutputFormat(self, output_format):
847 """Sets the output format for errors."""
848 self.output_format = output_format
849
850 def SetVerboseLevel(self, level):
851 """Sets the module's verbosity, and returns the previous setting."""
852 last_verbose_level = self.verbose_level
853 self.verbose_level = level
854 return last_verbose_level
855
erg@google.com26970fa2009-11-17 18:07:32 +0000856 def SetCountingStyle(self, counting_style):
857 """Sets the module's counting options."""
858 self.counting = counting_style
859
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000860 def SetFilters(self, filters):
861 """Sets the error-message filters.
862
863 These filters are applied when deciding whether to emit a given
864 error message.
865
866 Args:
867 filters: A string of comma-separated filters (eg "+whitespace/indent").
868 Each filter should start with + or -; else we die.
erg@google.com6317a9c2009-06-25 00:28:19 +0000869
870 Raises:
871 ValueError: The comma-separated filters did not all start with '+' or '-'.
872 E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter"
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000873 """
erg@google.com6317a9c2009-06-25 00:28:19 +0000874 # Default filters always have less priority than the flag ones.
875 self.filters = _DEFAULT_FILTERS[:]
avakulenko@google.com17449932014-07-28 22:13:33 +0000876 self.AddFilters(filters)
877
878 def AddFilters(self, filters):
879 """ Adds more filters to the existing list of error-message filters. """
erg@google.com6317a9c2009-06-25 00:28:19 +0000880 for filt in filters.split(','):
881 clean_filt = filt.strip()
882 if clean_filt:
883 self.filters.append(clean_filt)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000884 for filt in self.filters:
885 if not (filt.startswith('+') or filt.startswith('-')):
886 raise ValueError('Every filter in --filters must start with + or -'
887 ' (%s does not)' % filt)
888
avakulenko@google.com17449932014-07-28 22:13:33 +0000889 def BackupFilters(self):
890 """ Saves the current filter list to backup storage."""
891 self._filters_backup = self.filters[:]
892
893 def RestoreFilters(self):
894 """ Restores filters previously backed up."""
895 self.filters = self._filters_backup[:]
896
erg@google.com26970fa2009-11-17 18:07:32 +0000897 def ResetErrorCounts(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000898 """Sets the module's error statistic back to zero."""
899 self.error_count = 0
erg@google.com26970fa2009-11-17 18:07:32 +0000900 self.errors_by_category = {}
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000901
erg@google.com26970fa2009-11-17 18:07:32 +0000902 def IncrementErrorCount(self, category):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000903 """Bumps the module's error statistic."""
904 self.error_count += 1
erg@google.com26970fa2009-11-17 18:07:32 +0000905 if self.counting in ('toplevel', 'detailed'):
906 if self.counting != 'detailed':
907 category = category.split('/')[0]
908 if category not in self.errors_by_category:
909 self.errors_by_category[category] = 0
910 self.errors_by_category[category] += 1
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000911
erg@google.com26970fa2009-11-17 18:07:32 +0000912 def PrintErrorCounts(self):
913 """Print a summary of errors by category, and the total."""
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000914 for category, count in self.errors_by_category.items():
erg@google.com26970fa2009-11-17 18:07:32 +0000915 sys.stderr.write('Category \'%s\' errors found: %d\n' %
916 (category, count))
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +0000917 sys.stderr.write('Total errors found: %d\n' % self.error_count)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000918
919_cpplint_state = _CppLintState()
920
921
922def _OutputFormat():
923 """Gets the module's output format."""
924 return _cpplint_state.output_format
925
926
927def _SetOutputFormat(output_format):
928 """Sets the module's output format."""
929 _cpplint_state.SetOutputFormat(output_format)
930
931
932def _VerboseLevel():
933 """Returns the module's verbosity setting."""
934 return _cpplint_state.verbose_level
935
936
937def _SetVerboseLevel(level):
938 """Sets the module's verbosity, and returns the previous setting."""
939 return _cpplint_state.SetVerboseLevel(level)
940
941
erg@google.com26970fa2009-11-17 18:07:32 +0000942def _SetCountingStyle(level):
943 """Sets the module's counting options."""
944 _cpplint_state.SetCountingStyle(level)
945
946
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000947def _Filters():
948 """Returns the module's list of output filters, as a list."""
949 return _cpplint_state.filters
950
951
952def _SetFilters(filters):
953 """Sets the module's error-message filters.
954
955 These filters are applied when deciding whether to emit a given
956 error message.
957
958 Args:
959 filters: A string of comma-separated filters (eg "whitespace/indent").
960 Each filter should start with + or -; else we die.
961 """
962 _cpplint_state.SetFilters(filters)
963
avakulenko@google.com17449932014-07-28 22:13:33 +0000964def _AddFilters(filters):
965 """Adds more filter overrides.
avakulenko@google.com59146752014-08-11 20:20:55 +0000966
avakulenko@google.com17449932014-07-28 22:13:33 +0000967 Unlike _SetFilters, this function does not reset the current list of filters
968 available.
969
970 Args:
971 filters: A string of comma-separated filters (eg "whitespace/indent").
972 Each filter should start with + or -; else we die.
973 """
974 _cpplint_state.AddFilters(filters)
975
976def _BackupFilters():
977 """ Saves the current filter list to backup storage."""
978 _cpplint_state.BackupFilters()
979
980def _RestoreFilters():
981 """ Restores filters previously backed up."""
982 _cpplint_state.RestoreFilters()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000983
984class _FunctionState(object):
985 """Tracks current function name and the number of lines in its body."""
986
987 _NORMAL_TRIGGER = 250 # for --v=0, 500 for --v=1, etc.
988 _TEST_TRIGGER = 400 # about 50% more than _NORMAL_TRIGGER.
989
990 def __init__(self):
991 self.in_a_function = False
992 self.lines_in_function = 0
993 self.current_function = ''
994
995 def Begin(self, function_name):
996 """Start analyzing function body.
997
998 Args:
999 function_name: The name of the function being tracked.
1000 """
1001 self.in_a_function = True
1002 self.lines_in_function = 0
1003 self.current_function = function_name
1004
1005 def Count(self):
1006 """Count line in current function body."""
1007 if self.in_a_function:
1008 self.lines_in_function += 1
1009
1010 def Check(self, error, filename, linenum):
1011 """Report if too many lines in function body.
1012
1013 Args:
1014 error: The function to call with any errors found.
1015 filename: The name of the current file.
1016 linenum: The number of the line to check.
1017 """
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00001018 if not self.in_a_function:
1019 return
1020
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001021 if Match(r'T(EST|est)', self.current_function):
1022 base_trigger = self._TEST_TRIGGER
1023 else:
1024 base_trigger = self._NORMAL_TRIGGER
1025 trigger = base_trigger * 2**_VerboseLevel()
1026
1027 if self.lines_in_function > trigger:
1028 error_level = int(math.log(self.lines_in_function / base_trigger, 2))
1029 # 50 => 0, 100 => 1, 200 => 2, 400 => 3, 800 => 4, 1600 => 5, ...
1030 if error_level > 5:
1031 error_level = 5
1032 error(filename, linenum, 'readability/fn_size', error_level,
1033 'Small and focused functions are preferred:'
1034 ' %s has %d non-comment lines'
1035 ' (error triggered by exceeding %d lines).' % (
1036 self.current_function, self.lines_in_function, trigger))
1037
1038 def End(self):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00001039 """Stop analyzing function body."""
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001040 self.in_a_function = False
1041
1042
1043class _IncludeError(Exception):
1044 """Indicates a problem with the include order in a file."""
1045 pass
1046
1047
avakulenko@google.com59146752014-08-11 20:20:55 +00001048class FileInfo(object):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001049 """Provides utility functions for filenames.
1050
1051 FileInfo provides easy access to the components of a file's path
1052 relative to the project root.
1053 """
1054
1055 def __init__(self, filename):
1056 self._filename = filename
1057
1058 def FullName(self):
1059 """Make Windows paths like Unix."""
1060 return os.path.abspath(self._filename).replace('\\', '/')
1061
1062 def RepositoryName(self):
Edward Lemur6d31ed52019-12-02 23:00:00 +00001063 r"""FullName after removing the local path to the repository.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001064
1065 If we have a real absolute path name here we can try to do something smart:
1066 detecting the root of the checkout and truncating /path/to/checkout from
1067 the name so that we get header guards that don't include things like
1068 "C:\Documents and Settings\..." or "/home/username/..." in them and thus
1069 people on different computers who have checked the source out to different
1070 locations won't see bogus errors.
1071 """
1072 fullname = self.FullName()
1073
1074 if os.path.exists(fullname):
1075 project_dir = os.path.dirname(fullname)
1076
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00001077 if _project_root:
1078 prefix = os.path.commonprefix([_project_root, project_dir])
1079 return fullname[len(prefix) + 1:]
1080
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001081 if os.path.exists(os.path.join(project_dir, ".svn")):
1082 # If there's a .svn file in the current directory, we recursively look
1083 # up the directory tree for the top of the SVN checkout
1084 root_dir = project_dir
1085 one_up_dir = os.path.dirname(root_dir)
1086 while os.path.exists(os.path.join(one_up_dir, ".svn")):
1087 root_dir = os.path.dirname(root_dir)
1088 one_up_dir = os.path.dirname(one_up_dir)
1089
1090 prefix = os.path.commonprefix([root_dir, project_dir])
1091 return fullname[len(prefix) + 1:]
1092
erg@chromium.org7956a872011-11-30 01:44:03 +00001093 # Not SVN <= 1.6? Try to find a git, hg, or svn top level directory by
1094 # searching up from the current path.
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00001095 root_dir = os.path.dirname(fullname)
1096 while (root_dir != os.path.dirname(root_dir) and
1097 not os.path.exists(os.path.join(root_dir, ".git")) and
1098 not os.path.exists(os.path.join(root_dir, ".hg")) and
1099 not os.path.exists(os.path.join(root_dir, ".svn"))):
1100 root_dir = os.path.dirname(root_dir)
erg@google.com35589e62010-11-17 18:58:16 +00001101
1102 if (os.path.exists(os.path.join(root_dir, ".git")) or
erg@chromium.org7956a872011-11-30 01:44:03 +00001103 os.path.exists(os.path.join(root_dir, ".hg")) or
1104 os.path.exists(os.path.join(root_dir, ".svn"))):
erg@google.com35589e62010-11-17 18:58:16 +00001105 prefix = os.path.commonprefix([root_dir, project_dir])
1106 return fullname[len(prefix) + 1:]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001107
1108 # Don't know what to do; header guard warnings may be wrong...
1109 return fullname
1110
1111 def Split(self):
1112 """Splits the file into the directory, basename, and extension.
1113
1114 For 'chrome/browser/browser.cc', Split() would
1115 return ('chrome/browser', 'browser', '.cc')
1116
1117 Returns:
1118 A tuple of (directory, basename, extension).
1119 """
1120
1121 googlename = self.RepositoryName()
1122 project, rest = os.path.split(googlename)
1123 return (project,) + os.path.splitext(rest)
1124
1125 def BaseName(self):
1126 """File base name - text after the final slash, before the final period."""
1127 return self.Split()[1]
1128
1129 def Extension(self):
1130 """File extension - text following the final period."""
1131 return self.Split()[2]
1132
1133 def NoExtension(self):
1134 """File has no source file extension."""
1135 return '/'.join(self.Split()[0:2])
1136
1137 def IsSource(self):
1138 """File has a source file extension."""
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00001139 return _IsSourceExtension(self.Extension()[1:])
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001140
1141
erg@google.com35589e62010-11-17 18:58:16 +00001142def _ShouldPrintError(category, confidence, linenum):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00001143 """If confidence >= verbose, category passes filter and is not suppressed."""
erg@google.com35589e62010-11-17 18:58:16 +00001144
1145 # There are three ways we might decide not to print an error message:
1146 # a "NOLINT(category)" comment appears in the source,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001147 # the verbosity level isn't high enough, or the filters filter it out.
erg@google.com35589e62010-11-17 18:58:16 +00001148 if IsErrorSuppressedByNolint(category, linenum):
1149 return False
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001150
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001151 if confidence < _cpplint_state.verbose_level:
1152 return False
1153
1154 is_filtered = False
1155 for one_filter in _Filters():
1156 if one_filter.startswith('-'):
1157 if category.startswith(one_filter[1:]):
1158 is_filtered = True
1159 elif one_filter.startswith('+'):
1160 if category.startswith(one_filter[1:]):
1161 is_filtered = False
1162 else:
1163 assert False # should have been checked for in SetFilter.
1164 if is_filtered:
1165 return False
1166
1167 return True
1168
1169
1170def Error(filename, linenum, category, confidence, message):
1171 """Logs the fact we've found a lint error.
1172
1173 We log where the error was found, and also our confidence in the error,
1174 that is, how certain we are this is a legitimate style regression, and
1175 not a misidentification or a use that's sometimes justified.
1176
erg@google.com35589e62010-11-17 18:58:16 +00001177 False positives can be suppressed by the use of
1178 "cpplint(category)" comments on the offending line. These are
1179 parsed into _error_suppressions.
1180
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001181 Args:
1182 filename: The name of the file containing the error.
1183 linenum: The number of the line containing the error.
1184 category: A string used to describe the "category" this bug
1185 falls under: "whitespace", say, or "runtime". Categories
1186 may have a hierarchy separated by slashes: "whitespace/indent".
1187 confidence: A number from 1-5 representing a confidence score for
1188 the error, with 5 meaning that we are certain of the problem,
1189 and 1 meaning that it could be a legitimate construct.
1190 message: The error message.
1191 """
erg@google.com35589e62010-11-17 18:58:16 +00001192 if _ShouldPrintError(category, confidence, linenum):
erg@google.com26970fa2009-11-17 18:07:32 +00001193 _cpplint_state.IncrementErrorCount(category)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001194 if _cpplint_state.output_format == 'vs7':
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00001195 sys.stderr.write('%s(%s): %s [%s] [%d]\n' % (
1196 filename, linenum, message, category, confidence))
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001197 elif _cpplint_state.output_format == 'eclipse':
1198 sys.stderr.write('%s:%s: warning: %s [%s] [%d]\n' % (
1199 filename, linenum, message, category, confidence))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001200 else:
1201 sys.stderr.write('%s:%s: %s [%s] [%d]\n' % (
1202 filename, linenum, message, category, confidence))
1203
1204
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001205# Matches standard C++ escape sequences per 2.13.2.3 of the C++ standard.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001206_RE_PATTERN_CLEANSE_LINE_ESCAPES = re.compile(
1207 r'\\([abfnrtv?"\\\']|\d+|x[0-9a-fA-F]+)')
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001208# Match a single C style comment on the same line.
1209_RE_PATTERN_C_COMMENTS = r'/\*(?:[^*]|\*(?!/))*\*/'
1210# Matches multi-line C style comments.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001211# This RE is a little bit more complicated than one might expect, because we
1212# have to take care of space removals tools so we can handle comments inside
1213# statements better.
1214# The current rule is: We only clear spaces from both sides when we're at the
1215# end of the line. Otherwise, we try to remove spaces from the right side,
1216# if this doesn't work we try on left side but only if there's a non-character
1217# on the right.
1218_RE_PATTERN_CLEANSE_LINE_C_COMMENTS = re.compile(
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001219 r'(\s*' + _RE_PATTERN_C_COMMENTS + r'\s*$|' +
1220 _RE_PATTERN_C_COMMENTS + r'\s+|' +
1221 r'\s+' + _RE_PATTERN_C_COMMENTS + r'(?=\W)|' +
1222 _RE_PATTERN_C_COMMENTS + r')')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001223
1224
1225def IsCppString(line):
1226 """Does line terminate so, that the next symbol is in string constant.
1227
1228 This function does not consider single-line nor multi-line comments.
1229
1230 Args:
1231 line: is a partial line of code starting from the 0..n.
1232
1233 Returns:
1234 True, if next character appended to 'line' is inside a
1235 string constant.
1236 """
1237
1238 line = line.replace(r'\\', 'XX') # after this, \\" does not match to \"
1239 return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1
1240
1241
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001242def CleanseRawStrings(raw_lines):
1243 """Removes C++11 raw strings from lines.
1244
1245 Before:
1246 static const char kData[] = R"(
1247 multi-line string
1248 )";
1249
1250 After:
1251 static const char kData[] = ""
1252 (replaced by blank line)
1253 "";
1254
1255 Args:
1256 raw_lines: list of raw lines.
1257
1258 Returns:
1259 list of lines with C++11 raw strings replaced by empty strings.
1260 """
1261
1262 delimiter = None
1263 lines_without_raw_strings = []
1264 for line in raw_lines:
1265 if delimiter:
1266 # Inside a raw string, look for the end
1267 end = line.find(delimiter)
1268 if end >= 0:
1269 # Found the end of the string, match leading space for this
1270 # line and resume copying the original lines, and also insert
1271 # a "" on the last line.
1272 leading_space = Match(r'^(\s*)\S', line)
1273 line = leading_space.group(1) + '""' + line[end + len(delimiter):]
1274 delimiter = None
1275 else:
1276 # Haven't found the end yet, append a blank line.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001277 line = '""'
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001278
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001279 # Look for beginning of a raw string, and replace them with
1280 # empty strings. This is done in a loop to handle multiple raw
1281 # strings on the same line.
1282 while delimiter is None:
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001283 # Look for beginning of a raw string.
1284 # See 2.14.15 [lex.string] for syntax.
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00001285 #
1286 # Once we have matched a raw string, we check the prefix of the
1287 # line to make sure that the line is not part of a single line
1288 # comment. It's done this way because we remove raw strings
1289 # before removing comments as opposed to removing comments
1290 # before removing raw strings. This is because there are some
1291 # cpplint checks that requires the comments to be preserved, but
1292 # we don't want to check comments that are inside raw strings.
1293 matched = Match(r'^(.*?)\b(?:R|u8R|uR|UR|LR)"([^\s\\()]*)\((.*)$', line)
1294 if (matched and
1295 not Match(r'^([^\'"]|\'(\\.|[^\'])*\'|"(\\.|[^"])*")*//',
1296 matched.group(1))):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001297 delimiter = ')' + matched.group(2) + '"'
1298
1299 end = matched.group(3).find(delimiter)
1300 if end >= 0:
1301 # Raw string ended on same line
1302 line = (matched.group(1) + '""' +
1303 matched.group(3)[end + len(delimiter):])
1304 delimiter = None
1305 else:
1306 # Start of a multi-line raw string
1307 line = matched.group(1) + '""'
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001308 else:
1309 break
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001310
1311 lines_without_raw_strings.append(line)
1312
1313 # TODO(unknown): if delimiter is not None here, we might want to
1314 # emit a warning for unterminated string.
1315 return lines_without_raw_strings
1316
1317
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001318def FindNextMultiLineCommentStart(lines, lineix):
1319 """Find the beginning marker for a multiline comment."""
1320 while lineix < len(lines):
1321 if lines[lineix].strip().startswith('/*'):
1322 # Only return this marker if the comment goes beyond this line
1323 if lines[lineix].strip().find('*/', 2) < 0:
1324 return lineix
1325 lineix += 1
1326 return len(lines)
1327
1328
1329def FindNextMultiLineCommentEnd(lines, lineix):
1330 """We are inside a comment, find the end marker."""
1331 while lineix < len(lines):
1332 if lines[lineix].strip().endswith('*/'):
1333 return lineix
1334 lineix += 1
1335 return len(lines)
1336
1337
1338def RemoveMultiLineCommentsFromRange(lines, begin, end):
1339 """Clears a range of lines for multi-line comments."""
1340 # Having // dummy comments makes the lines non-empty, so we will not get
1341 # unnecessary blank line warnings later in the code.
1342 for i in range(begin, end):
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001343 lines[i] = '/**/'
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001344
1345
1346def RemoveMultiLineComments(filename, lines, error):
1347 """Removes multiline (c-style) comments from lines."""
1348 lineix = 0
1349 while lineix < len(lines):
1350 lineix_begin = FindNextMultiLineCommentStart(lines, lineix)
1351 if lineix_begin >= len(lines):
1352 return
1353 lineix_end = FindNextMultiLineCommentEnd(lines, lineix_begin)
1354 if lineix_end >= len(lines):
1355 error(filename, lineix_begin + 1, 'readability/multiline_comment', 5,
1356 'Could not find end of multi-line comment')
1357 return
1358 RemoveMultiLineCommentsFromRange(lines, lineix_begin, lineix_end + 1)
1359 lineix = lineix_end + 1
1360
1361
1362def CleanseComments(line):
1363 """Removes //-comments and single-line C-style /* */ comments.
1364
1365 Args:
1366 line: A line of C++ source.
1367
1368 Returns:
1369 The line with single-line comments removed.
1370 """
1371 commentpos = line.find('//')
1372 if commentpos != -1 and not IsCppString(line[:commentpos]):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00001373 line = line[:commentpos].rstrip()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001374 # get rid of /* ... */
1375 return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line)
1376
1377
erg@google.com6317a9c2009-06-25 00:28:19 +00001378class CleansedLines(object):
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001379 """Holds 4 copies of all lines with different preprocessing applied to them.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001380
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001381 1) elided member contains lines without strings and comments.
1382 2) lines member contains lines without comments.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001383 3) raw_lines member contains all the lines without processing.
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001384 4) lines_without_raw_strings member is same as raw_lines, but with C++11 raw
1385 strings removed.
1386 All these members are of <type 'list'>, and of the same length.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001387 """
1388
1389 def __init__(self, lines):
1390 self.elided = []
1391 self.lines = []
1392 self.raw_lines = lines
1393 self.num_lines = len(lines)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001394 self.lines_without_raw_strings = CleanseRawStrings(lines)
1395 for linenum in range(len(self.lines_without_raw_strings)):
1396 self.lines.append(CleanseComments(
1397 self.lines_without_raw_strings[linenum]))
1398 elided = self._CollapseStrings(self.lines_without_raw_strings[linenum])
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001399 self.elided.append(CleanseComments(elided))
1400
1401 def NumLines(self):
1402 """Returns the number of lines represented."""
1403 return self.num_lines
1404
1405 @staticmethod
1406 def _CollapseStrings(elided):
1407 """Collapses strings and chars on a line to simple "" or '' blocks.
1408
1409 We nix strings first so we're not fooled by text like '"http://"'
1410
1411 Args:
1412 elided: The line being processed.
1413
1414 Returns:
1415 The line with collapsed strings.
1416 """
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001417 if _RE_PATTERN_INCLUDE.match(elided):
1418 return elided
1419
1420 # Remove escaped characters first to make quote/single quote collapsing
1421 # basic. Things that look like escaped characters shouldn't occur
1422 # outside of strings and chars.
1423 elided = _RE_PATTERN_CLEANSE_LINE_ESCAPES.sub('', elided)
1424
1425 # Replace quoted strings and digit separators. Both single quotes
1426 # and double quotes are processed in the same loop, otherwise
1427 # nested quotes wouldn't work.
1428 collapsed = ''
1429 while True:
1430 # Find the first quote character
1431 match = Match(r'^([^\'"]*)([\'"])(.*)$', elided)
1432 if not match:
1433 collapsed += elided
1434 break
1435 head, quote, tail = match.groups()
1436
1437 if quote == '"':
1438 # Collapse double quoted strings
1439 second_quote = tail.find('"')
1440 if second_quote >= 0:
1441 collapsed += head + '""'
1442 elided = tail[second_quote + 1:]
1443 else:
1444 # Unmatched double quote, don't bother processing the rest
1445 # of the line since this is probably a multiline string.
1446 collapsed += elided
1447 break
1448 else:
1449 # Found single quote, check nearby text to eliminate digit separators.
1450 #
1451 # There is no special handling for floating point here, because
1452 # the integer/fractional/exponent parts would all be parsed
1453 # correctly as long as there are digits on both sides of the
1454 # separator. So we are fine as long as we don't see something
1455 # like "0.'3" (gcc 4.9.0 will not allow this literal).
1456 if Search(r'\b(?:0[bBxX]?|[1-9])[0-9a-fA-F]*$', head):
1457 match_literal = Match(r'^((?:\'?[0-9a-zA-Z_])*)(.*)$', "'" + tail)
1458 collapsed += head + match_literal.group(1).replace("'", '')
1459 elided = match_literal.group(2)
1460 else:
1461 second_quote = tail.find('\'')
1462 if second_quote >= 0:
1463 collapsed += head + "''"
1464 elided = tail[second_quote + 1:]
1465 else:
1466 # Unmatched single quote
1467 collapsed += elided
1468 break
1469
1470 return collapsed
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001471
1472
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001473def FindEndOfExpressionInLine(line, startpos, stack):
1474 """Find the position just after the end of current parenthesized expression.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001475
1476 Args:
1477 line: a CleansedLines line.
1478 startpos: start searching at this position.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001479 stack: nesting stack at startpos.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001480
1481 Returns:
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001482 On finding matching end: (index just after matching end, None)
1483 On finding an unclosed expression: (-1, None)
1484 Otherwise: (-1, new stack at end of this line)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001485 """
Edward Lemur6d31ed52019-12-02 23:00:00 +00001486 for i in range(startpos, len(line)):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001487 char = line[i]
1488 if char in '([{':
1489 # Found start of parenthesized expression, push to expression stack
1490 stack.append(char)
1491 elif char == '<':
1492 # Found potential start of template argument list
1493 if i > 0 and line[i - 1] == '<':
1494 # Left shift operator
1495 if stack and stack[-1] == '<':
1496 stack.pop()
1497 if not stack:
1498 return (-1, None)
1499 elif i > 0 and Search(r'\boperator\s*$', line[0:i]):
1500 # operator<, don't add to stack
1501 continue
1502 else:
1503 # Tentative start of template argument list
1504 stack.append('<')
1505 elif char in ')]}':
1506 # Found end of parenthesized expression.
1507 #
1508 # If we are currently expecting a matching '>', the pending '<'
1509 # must have been an operator. Remove them from expression stack.
1510 while stack and stack[-1] == '<':
1511 stack.pop()
1512 if not stack:
1513 return (-1, None)
1514 if ((stack[-1] == '(' and char == ')') or
1515 (stack[-1] == '[' and char == ']') or
1516 (stack[-1] == '{' and char == '}')):
1517 stack.pop()
1518 if not stack:
1519 return (i + 1, None)
1520 else:
1521 # Mismatched parentheses
1522 return (-1, None)
1523 elif char == '>':
1524 # Found potential end of template argument list.
1525
1526 # Ignore "->" and operator functions
1527 if (i > 0 and
1528 (line[i - 1] == '-' or Search(r'\boperator\s*$', line[0:i - 1]))):
1529 continue
1530
1531 # Pop the stack if there is a matching '<'. Otherwise, ignore
1532 # this '>' since it must be an operator.
1533 if stack:
1534 if stack[-1] == '<':
1535 stack.pop()
1536 if not stack:
1537 return (i + 1, None)
1538 elif char == ';':
1539 # Found something that look like end of statements. If we are currently
1540 # expecting a '>', the matching '<' must have been an operator, since
1541 # template argument list should not contain statements.
1542 while stack and stack[-1] == '<':
1543 stack.pop()
1544 if not stack:
1545 return (-1, None)
1546
1547 # Did not find end of expression or unbalanced parentheses on this line
1548 return (-1, stack)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001549
1550
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001551def CloseExpression(clean_lines, linenum, pos):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001552 """If input points to ( or { or [ or <, finds the position that closes it.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001553
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001554 If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001555 linenum/pos that correspond to the closing of the expression.
1556
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001557 TODO(unknown): cpplint spends a fair bit of time matching parentheses.
1558 Ideally we would want to index all opening and closing parentheses once
1559 and have CloseExpression be just a simple lookup, but due to preprocessor
1560 tricks, this is not so easy.
1561
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001562 Args:
1563 clean_lines: A CleansedLines instance containing the file.
1564 linenum: The number of the line to check.
1565 pos: A position on the line.
1566
1567 Returns:
1568 A tuple (line, linenum, pos) pointer *past* the closing brace, or
1569 (line, len(lines), -1) if we never find a close. Note we ignore
1570 strings and comments when matching; and the line we return is the
1571 'cleansed' line at linenum.
1572 """
1573
1574 line = clean_lines.elided[linenum]
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001575 if (line[pos] not in '({[<') or Match(r'<[<=]', line[pos:]):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001576 return (line, clean_lines.NumLines(), -1)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001577
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001578 # Check first line
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001579 (end_pos, stack) = FindEndOfExpressionInLine(line, pos, [])
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001580 if end_pos > -1:
1581 return (line, linenum, end_pos)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001582
1583 # Continue scanning forward
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001584 while stack and linenum < clean_lines.NumLines() - 1:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001585 linenum += 1
1586 line = clean_lines.elided[linenum]
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001587 (end_pos, stack) = FindEndOfExpressionInLine(line, 0, stack)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001588 if end_pos > -1:
1589 return (line, linenum, end_pos)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001590
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001591 # Did not find end of expression before end of file, give up
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001592 return (line, clean_lines.NumLines(), -1)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001593
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001594
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001595def FindStartOfExpressionInLine(line, endpos, stack):
1596 """Find position at the matching start of current expression.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001597
1598 This is almost the reverse of FindEndOfExpressionInLine, but note
1599 that the input position and returned position differs by 1.
1600
1601 Args:
1602 line: a CleansedLines line.
1603 endpos: start searching at this position.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001604 stack: nesting stack at endpos.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001605
1606 Returns:
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001607 On finding matching start: (index at matching start, None)
1608 On finding an unclosed expression: (-1, None)
1609 Otherwise: (-1, new stack at beginning of this line)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001610 """
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001611 i = endpos
1612 while i >= 0:
1613 char = line[i]
1614 if char in ')]}':
1615 # Found end of expression, push to expression stack
1616 stack.append(char)
1617 elif char == '>':
1618 # Found potential end of template argument list.
1619 #
1620 # Ignore it if it's a "->" or ">=" or "operator>"
1621 if (i > 0 and
1622 (line[i - 1] == '-' or
1623 Match(r'\s>=\s', line[i - 1:]) or
1624 Search(r'\boperator\s*$', line[0:i]))):
1625 i -= 1
1626 else:
1627 stack.append('>')
1628 elif char == '<':
1629 # Found potential start of template argument list
1630 if i > 0 and line[i - 1] == '<':
1631 # Left shift operator
1632 i -= 1
1633 else:
1634 # If there is a matching '>', we can pop the expression stack.
1635 # Otherwise, ignore this '<' since it must be an operator.
1636 if stack and stack[-1] == '>':
1637 stack.pop()
1638 if not stack:
1639 return (i, None)
1640 elif char in '([{':
1641 # Found start of expression.
1642 #
1643 # If there are any unmatched '>' on the stack, they must be
1644 # operators. Remove those.
1645 while stack and stack[-1] == '>':
1646 stack.pop()
1647 if not stack:
1648 return (-1, None)
1649 if ((char == '(' and stack[-1] == ')') or
1650 (char == '[' and stack[-1] == ']') or
1651 (char == '{' and stack[-1] == '}')):
1652 stack.pop()
1653 if not stack:
1654 return (i, None)
1655 else:
1656 # Mismatched parentheses
1657 return (-1, None)
1658 elif char == ';':
1659 # Found something that look like end of statements. If we are currently
1660 # expecting a '<', the matching '>' must have been an operator, since
1661 # template argument list should not contain statements.
1662 while stack and stack[-1] == '>':
1663 stack.pop()
1664 if not stack:
1665 return (-1, None)
1666
1667 i -= 1
1668
1669 return (-1, stack)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001670
1671
1672def ReverseCloseExpression(clean_lines, linenum, pos):
1673 """If input points to ) or } or ] or >, finds the position that opens it.
1674
1675 If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the
1676 linenum/pos that correspond to the opening of the expression.
1677
1678 Args:
1679 clean_lines: A CleansedLines instance containing the file.
1680 linenum: The number of the line to check.
1681 pos: A position on the line.
1682
1683 Returns:
1684 A tuple (line, linenum, pos) pointer *at* the opening brace, or
1685 (line, 0, -1) if we never find the matching opening brace. Note
1686 we ignore strings and comments when matching; and the line we
1687 return is the 'cleansed' line at linenum.
1688 """
1689 line = clean_lines.elided[linenum]
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001690 if line[pos] not in ')}]>':
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001691 return (line, 0, -1)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001692
1693 # Check last line
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001694 (start_pos, stack) = FindStartOfExpressionInLine(line, pos, [])
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001695 if start_pos > -1:
1696 return (line, linenum, start_pos)
1697
1698 # Continue scanning backward
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001699 while stack and linenum > 0:
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001700 linenum -= 1
1701 line = clean_lines.elided[linenum]
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001702 (start_pos, stack) = FindStartOfExpressionInLine(line, len(line) - 1, stack)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001703 if start_pos > -1:
1704 return (line, linenum, start_pos)
1705
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001706 # Did not find start of expression before beginning of file, give up
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001707 return (line, 0, -1)
1708
1709
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001710def CheckForCopyright(filename, lines, error):
1711 """Logs an error if no Copyright message appears at the top of the file."""
1712
1713 # We'll say it should occur by line 10. Don't forget there's a
1714 # dummy line at the front.
Edward Lemur6d31ed52019-12-02 23:00:00 +00001715 for line in range(1, min(len(lines), 11)):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001716 if re.search(r'Copyright', lines[line], re.I): break
1717 else: # means no copyright line was found
1718 error(filename, 0, 'legal/copyright', 5,
1719 'No copyright message found. '
1720 'You should have a line: "Copyright [year] <Copyright Owner>"')
1721
1722
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001723def GetIndentLevel(line):
1724 """Return the number of leading spaces in line.
1725
1726 Args:
1727 line: A string to check.
1728
1729 Returns:
1730 An integer count of leading spaces, possibly zero.
1731 """
1732 indent = Match(r'^( *)\S', line)
1733 if indent:
1734 return len(indent.group(1))
1735 else:
1736 return 0
1737
1738
David Sanders2f988472022-05-21 01:35:11 +00001739def PathSplitToList(path):
1740 """Returns the path split into a list by the separator.
1741
1742 Args:
1743 path: An absolute or relative path (e.g. '/a/b/c/' or '../a')
1744
1745 Returns:
1746 A list of path components (e.g. ['a', 'b', 'c]).
1747 """
1748 lst = []
1749 while True:
1750 (head, tail) = os.path.split(path)
1751 if head == path: # absolute paths end
1752 lst.append(head)
1753 break
1754 if tail == path: # relative paths end
1755 lst.append(tail)
1756 break
1757
1758 path = head
1759 lst.append(tail)
1760
1761 lst.reverse()
1762 return lst
1763
1764
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001765def GetHeaderGuardCPPVariable(filename):
1766 """Returns the CPP variable that should be used as a header guard.
1767
1768 Args:
1769 filename: The name of a C++ header file.
1770
1771 Returns:
1772 The CPP variable that should be used as a header guard in the
1773 named file.
1774
1775 """
1776
erg@google.com35589e62010-11-17 18:58:16 +00001777 # Restores original filename in case that cpplint is invoked from Emacs's
1778 # flymake.
1779 filename = re.sub(r'_flymake\.h$', '.h', filename)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001780 filename = re.sub(r'/\.flymake/([^/]*)$', r'/\1', filename)
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001781 # Replace 'c++' with 'cpp'.
1782 filename = filename.replace('C++', 'cpp').replace('c++', 'cpp')
skym@chromium.org3990c412016-02-05 20:55:12 +00001783
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001784 fileinfo = FileInfo(filename)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001785 file_path_from_root = fileinfo.RepositoryName()
David Sanders2f988472022-05-21 01:35:11 +00001786
1787 def FixupPathFromRoot():
1788 if _root_debug:
1789 sys.stderr.write("\n_root fixup, _root = '%s', repository name = '%s'\n"
1790 % (_root, fileinfo.RepositoryName()))
1791
1792 # Process the file path with the --root flag if it was set.
1793 if not _root:
1794 if _root_debug:
1795 sys.stderr.write("_root unspecified\n")
1796 return file_path_from_root
1797
1798 def StripListPrefix(lst, prefix):
1799 # f(['x', 'y'], ['w, z']) -> None (not a valid prefix)
1800 if lst[:len(prefix)] != prefix:
1801 return None
1802 # f(['a, 'b', 'c', 'd'], ['a', 'b']) -> ['c', 'd']
1803 return lst[(len(prefix)):]
1804
1805 # root behavior:
1806 # --root=subdir , lstrips subdir from the header guard
1807 maybe_path = StripListPrefix(PathSplitToList(file_path_from_root),
1808 PathSplitToList(_root))
1809
1810 if _root_debug:
1811 sys.stderr.write(("_root lstrip (maybe_path=%s, file_path_from_root=%s," +
1812 " _root=%s)\n") % (maybe_path, file_path_from_root, _root))
1813
1814 if maybe_path:
1815 return os.path.join(*maybe_path)
1816
1817 # --root=.. , will prepend the outer directory to the header guard
1818 full_path = fileinfo.FullName()
1819 # adapt slashes for windows
1820 root_abspath = os.path.abspath(_root).replace('\\', '/')
1821
1822 maybe_path = StripListPrefix(PathSplitToList(full_path),
1823 PathSplitToList(root_abspath))
1824
1825 if _root_debug:
1826 sys.stderr.write(("_root prepend (maybe_path=%s, full_path=%s, " +
1827 "root_abspath=%s)\n") % (maybe_path, full_path, root_abspath))
1828
1829 if maybe_path:
1830 return os.path.join(*maybe_path)
1831
1832 if _root_debug:
1833 sys.stderr.write("_root ignore, returning %s\n" % (file_path_from_root))
1834
1835 # --root=FAKE_DIR is ignored
1836 return file_path_from_root
1837
1838 file_path_from_root = FixupPathFromRoot()
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001839 return re.sub(r'[^a-zA-Z0-9]', '_', file_path_from_root).upper() + '_'
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001840
1841
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001842def CheckForHeaderGuard(filename, clean_lines, error):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001843 """Checks that the file contains a header guard.
1844
erg@google.com6317a9c2009-06-25 00:28:19 +00001845 Logs an error if no #ifndef header guard is present. For other
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001846 headers, checks that the full pathname is used.
1847
1848 Args:
1849 filename: The name of the C++ header file.
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001850 clean_lines: A CleansedLines instance containing the file.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001851 error: The function to call with any errors found.
1852 """
1853
avakulenko@google.com59146752014-08-11 20:20:55 +00001854 # Don't check for header guards if there are error suppression
1855 # comments somewhere in this file.
1856 #
1857 # Because this is silencing a warning for a nonexistent line, we
1858 # only support the very specific NOLINT(build/header_guard) syntax,
1859 # and not the general NOLINT or NOLINT(*) syntax.
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001860 raw_lines = clean_lines.lines_without_raw_strings
1861 for i in raw_lines:
avakulenko@google.com59146752014-08-11 20:20:55 +00001862 if Search(r'//\s*NOLINT\(build/header_guard\)', i):
1863 return
1864
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001865 cppvar = GetHeaderGuardCPPVariable(filename)
1866
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001867 ifndef = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001868 ifndef_linenum = 0
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001869 define = ''
1870 endif = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001871 endif_linenum = 0
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001872 for linenum, line in enumerate(raw_lines):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001873 linesplit = line.split()
1874 if len(linesplit) >= 2:
1875 # find the first occurrence of #ifndef and #define, save arg
1876 if not ifndef and linesplit[0] == '#ifndef':
1877 # set ifndef to the header guard presented on the #ifndef line.
1878 ifndef = linesplit[1]
1879 ifndef_linenum = linenum
1880 if not define and linesplit[0] == '#define':
1881 define = linesplit[1]
1882 # find the last occurrence of #endif, save entire line
1883 if line.startswith('#endif'):
1884 endif = line
1885 endif_linenum = linenum
1886
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001887 if not ifndef or not define or ifndef != define:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001888 error(filename, 0, 'build/header_guard', 5,
1889 'No #ifndef header guard found, suggested CPP variable is: %s' %
1890 cppvar)
1891 return
1892
1893 # The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__
1894 # for backward compatibility.
erg@google.com35589e62010-11-17 18:58:16 +00001895 if ifndef != cppvar:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001896 error_level = 0
1897 if ifndef != cppvar + '_':
1898 error_level = 5
1899
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001900 ParseNolintSuppressions(filename, raw_lines[ifndef_linenum], ifndef_linenum,
erg@google.com35589e62010-11-17 18:58:16 +00001901 error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001902 error(filename, ifndef_linenum, 'build/header_guard', error_level,
1903 '#ifndef header guard has wrong style, please use: %s' % cppvar)
1904
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001905 # Check for "//" comments on endif line.
1906 ParseNolintSuppressions(filename, raw_lines[endif_linenum], endif_linenum,
1907 error)
1908 match = Match(r'#endif\s*//\s*' + cppvar + r'(_)?\b', endif)
1909 if match:
1910 if match.group(1) == '_':
1911 # Issue low severity warning for deprecated double trailing underscore
1912 error(filename, endif_linenum, 'build/header_guard', 0,
1913 '#endif line should be "#endif // %s"' % cppvar)
erg@chromium.orgc452fea2012-01-26 21:10:45 +00001914 return
1915
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001916 # Didn't find the corresponding "//" comment. If this file does not
1917 # contain any "//" comments at all, it could be that the compiler
1918 # only wants "/**/" comments, look for those instead.
1919 no_single_line_comments = True
Edward Lemur6d31ed52019-12-02 23:00:00 +00001920 for i in range(1, len(raw_lines) - 1):
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001921 line = raw_lines[i]
1922 if Match(r'^(?:(?:\'(?:\.|[^\'])*\')|(?:"(?:\.|[^"])*")|[^\'"])*//', line):
1923 no_single_line_comments = False
1924 break
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001925
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001926 if no_single_line_comments:
1927 match = Match(r'#endif\s*/\*\s*' + cppvar + r'(_)?\s*\*/', endif)
1928 if match:
1929 if match.group(1) == '_':
1930 # Low severity warning for double trailing underscore
1931 error(filename, endif_linenum, 'build/header_guard', 0,
1932 '#endif line should be "#endif /* %s */"' % cppvar)
1933 return
1934
1935 # Didn't find anything
1936 error(filename, endif_linenum, 'build/header_guard', 5,
1937 '#endif line should be "#endif // %s"' % cppvar)
1938
1939
1940def CheckHeaderFileIncluded(filename, include_state, error):
1941 """Logs an error if a .cc file does not include its header."""
1942
1943 # Do not check test files
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00001944 fileinfo = FileInfo(filename)
1945 if Search(_TEST_FILE_SUFFIX, fileinfo.BaseName()):
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001946 return
1947
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00001948 headerfile = filename[0:len(filename) - len(fileinfo.Extension())] + '.h'
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001949 if not os.path.exists(headerfile):
1950 return
1951 headername = FileInfo(headerfile).RepositoryName()
1952 first_include = 0
1953 for section_list in include_state.include_list:
1954 for f in section_list:
1955 if headername in f[0] or f[0] in headername:
1956 return
1957 if not first_include:
1958 first_include = f[1]
1959
1960 error(filename, first_include, 'build/include', 5,
1961 '%s should include its header file %s' % (fileinfo.RepositoryName(),
1962 headername))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001963
1964
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001965def CheckForBadCharacters(filename, lines, error):
1966 """Logs an error for each line containing bad characters.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001967
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001968 Two kinds of bad characters:
1969
1970 1. Unicode replacement characters: These indicate that either the file
1971 contained invalid UTF-8 (likely) or Unicode replacement characters (which
1972 it shouldn't). Note that it's possible for this to throw off line
1973 numbering if the invalid UTF-8 occurred adjacent to a newline.
1974
1975 2. NUL bytes. These are problematic for some tools.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001976
1977 Args:
1978 filename: The name of the current file.
1979 lines: An array of strings, each representing a line of the file.
1980 error: The function to call with any errors found.
1981 """
1982 for linenum, line in enumerate(lines):
1983 if u'\ufffd' in line:
1984 error(filename, linenum, 'readability/utf8', 5,
1985 'Line contains invalid UTF-8 (or Unicode replacement character).')
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001986 if '\0' in line:
1987 error(filename, linenum, 'readability/nul', 5, 'Line contains NUL byte.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001988
1989
1990def CheckForNewlineAtEOF(filename, lines, error):
1991 """Logs an error if there is no newline char at the end of the file.
1992
1993 Args:
1994 filename: The name of the current file.
1995 lines: An array of strings, each representing a line of the file.
1996 error: The function to call with any errors found.
1997 """
1998
1999 # The array lines() was created by adding two newlines to the
2000 # original file (go figure), then splitting on \n.
2001 # To verify that the file ends in \n, we just have to make sure the
2002 # last-but-two element of lines() exists and is empty.
2003 if len(lines) < 3 or lines[-2]:
2004 error(filename, len(lines) - 2, 'whitespace/ending_newline', 5,
2005 'Could not find a newline character at the end of the file.')
2006
2007
2008def CheckForMultilineCommentsAndStrings(filename, clean_lines, linenum, error):
2009 """Logs an error if we see /* ... */ or "..." that extend past one line.
2010
2011 /* ... */ comments are legit inside macros, for one line.
2012 Otherwise, we prefer // comments, so it's ok to warn about the
2013 other. Likewise, it's ok for strings to extend across multiple
2014 lines, as long as a line continuation character (backslash)
2015 terminates each line. Although not currently prohibited by the C++
2016 style guide, it's ugly and unnecessary. We don't do well with either
2017 in this lint program, so we warn about both.
2018
2019 Args:
2020 filename: The name of the current file.
2021 clean_lines: A CleansedLines instance containing the file.
2022 linenum: The number of the line to check.
2023 error: The function to call with any errors found.
2024 """
2025 line = clean_lines.elided[linenum]
2026
2027 # Remove all \\ (escaped backslashes) from the line. They are OK, and the
2028 # second (escaped) slash may trigger later \" detection erroneously.
2029 line = line.replace('\\\\', '')
2030
2031 if line.count('/*') > line.count('*/'):
2032 error(filename, linenum, 'readability/multiline_comment', 5,
2033 'Complex multi-line /*...*/-style comment found. '
2034 'Lint may give bogus warnings. '
2035 'Consider replacing these with //-style comments, '
2036 'with #if 0...#endif, '
2037 'or with more clearly structured multi-line comments.')
2038
2039 if (line.count('"') - line.count('\\"')) % 2:
2040 error(filename, linenum, 'readability/multiline_string', 5,
2041 'Multi-line string ("...") found. This lint script doesn\'t '
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002042 'do well with such strings, and may give bogus warnings. '
2043 'Use C++11 raw strings or concatenation instead.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002044
2045
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002046# (non-threadsafe name, thread-safe alternative, validation pattern)
2047#
2048# The validation pattern is used to eliminate false positives such as:
2049# _rand(); // false positive due to substring match.
2050# ->rand(); // some member function rand().
2051# ACMRandom rand(seed); // some variable named rand.
2052# ISAACRandom rand(); // another variable named rand.
2053#
2054# Basically we require the return value of these functions to be used
2055# in some expression context on the same line by matching on some
2056# operator before the function name. This eliminates constructors and
2057# member function calls.
2058_UNSAFE_FUNC_PREFIX = r'(?:[-+*/=%^&|(<]\s*|>\s+)'
2059_THREADING_LIST = (
2060 ('asctime(', 'asctime_r(', _UNSAFE_FUNC_PREFIX + r'asctime\([^)]+\)'),
2061 ('ctime(', 'ctime_r(', _UNSAFE_FUNC_PREFIX + r'ctime\([^)]+\)'),
2062 ('getgrgid(', 'getgrgid_r(', _UNSAFE_FUNC_PREFIX + r'getgrgid\([^)]+\)'),
2063 ('getgrnam(', 'getgrnam_r(', _UNSAFE_FUNC_PREFIX + r'getgrnam\([^)]+\)'),
2064 ('getlogin(', 'getlogin_r(', _UNSAFE_FUNC_PREFIX + r'getlogin\(\)'),
2065 ('getpwnam(', 'getpwnam_r(', _UNSAFE_FUNC_PREFIX + r'getpwnam\([^)]+\)'),
2066 ('getpwuid(', 'getpwuid_r(', _UNSAFE_FUNC_PREFIX + r'getpwuid\([^)]+\)'),
2067 ('gmtime(', 'gmtime_r(', _UNSAFE_FUNC_PREFIX + r'gmtime\([^)]+\)'),
2068 ('localtime(', 'localtime_r(', _UNSAFE_FUNC_PREFIX + r'localtime\([^)]+\)'),
2069 ('rand(', 'rand_r(', _UNSAFE_FUNC_PREFIX + r'rand\(\)'),
2070 ('strtok(', 'strtok_r(',
2071 _UNSAFE_FUNC_PREFIX + r'strtok\([^)]+\)'),
2072 ('ttyname(', 'ttyname_r(', _UNSAFE_FUNC_PREFIX + r'ttyname\([^)]+\)'),
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002073 )
2074
2075
2076def CheckPosixThreading(filename, clean_lines, linenum, error):
2077 """Checks for calls to thread-unsafe functions.
2078
2079 Much code has been originally written without consideration of
2080 multi-threading. Also, engineers are relying on their old experience;
2081 they have learned posix before threading extensions were added. These
2082 tests guide the engineers to use thread-safe functions (when using
2083 posix directly).
2084
2085 Args:
2086 filename: The name of the current file.
2087 clean_lines: A CleansedLines instance containing the file.
2088 linenum: The number of the line to check.
2089 error: The function to call with any errors found.
2090 """
2091 line = clean_lines.elided[linenum]
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002092 for single_thread_func, multithread_safe_func, pattern in _THREADING_LIST:
2093 # Additional pattern matching check to confirm that this is the
2094 # function we are looking for
2095 if Search(pattern, line):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002096 error(filename, linenum, 'runtime/threadsafe_fn', 2,
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002097 'Consider using ' + multithread_safe_func +
2098 '...) instead of ' + single_thread_func +
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002099 '...) for improved thread safety.')
2100
2101
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002102def CheckVlogArguments(filename, clean_lines, linenum, error):
2103 """Checks that VLOG() is only used for defining a logging level.
2104
2105 For example, VLOG(2) is correct. VLOG(INFO), VLOG(WARNING), VLOG(ERROR), and
2106 VLOG(FATAL) are not.
2107
2108 Args:
2109 filename: The name of the current file.
2110 clean_lines: A CleansedLines instance containing the file.
2111 linenum: The number of the line to check.
2112 error: The function to call with any errors found.
2113 """
2114 line = clean_lines.elided[linenum]
2115 if Search(r'\bVLOG\((INFO|ERROR|WARNING|DFATAL|FATAL)\)', line):
2116 error(filename, linenum, 'runtime/vlog', 5,
2117 'VLOG() should be used with numeric verbosity level. '
2118 'Use LOG() if you want symbolic severity levels.')
2119
erg@google.com26970fa2009-11-17 18:07:32 +00002120# Matches invalid increment: *count++, which moves pointer instead of
erg@google.com6317a9c2009-06-25 00:28:19 +00002121# incrementing a value.
erg@google.com26970fa2009-11-17 18:07:32 +00002122_RE_PATTERN_INVALID_INCREMENT = re.compile(
erg@google.com6317a9c2009-06-25 00:28:19 +00002123 r'^\s*\*\w+(\+\+|--);')
2124
2125
2126def CheckInvalidIncrement(filename, clean_lines, linenum, error):
erg@google.com26970fa2009-11-17 18:07:32 +00002127 """Checks for invalid increment *count++.
erg@google.com6317a9c2009-06-25 00:28:19 +00002128
2129 For example following function:
2130 void increment_counter(int* count) {
2131 *count++;
2132 }
2133 is invalid, because it effectively does count++, moving pointer, and should
2134 be replaced with ++*count, (*count)++ or *count += 1.
2135
2136 Args:
2137 filename: The name of the current file.
2138 clean_lines: A CleansedLines instance containing the file.
2139 linenum: The number of the line to check.
2140 error: The function to call with any errors found.
2141 """
2142 line = clean_lines.elided[linenum]
erg@google.com26970fa2009-11-17 18:07:32 +00002143 if _RE_PATTERN_INVALID_INCREMENT.match(line):
erg@google.com6317a9c2009-06-25 00:28:19 +00002144 error(filename, linenum, 'runtime/invalid_increment', 5,
2145 'Changing pointer instead of value (or unused value of operator*).')
2146
2147
avakulenko@google.com59146752014-08-11 20:20:55 +00002148def IsMacroDefinition(clean_lines, linenum):
2149 if Search(r'^#define', clean_lines[linenum]):
2150 return True
2151
2152 if linenum > 0 and Search(r'\\$', clean_lines[linenum - 1]):
2153 return True
2154
2155 return False
2156
2157
2158def IsForwardClassDeclaration(clean_lines, linenum):
2159 return Match(r'^\s*(\btemplate\b)*.*class\s+\w+;\s*$', clean_lines[linenum])
2160
2161
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002162class _BlockInfo(object):
2163 """Stores information about a generic block of code."""
2164
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002165 def __init__(self, linenum, seen_open_brace):
2166 self.starting_linenum = linenum
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002167 self.seen_open_brace = seen_open_brace
2168 self.open_parentheses = 0
2169 self.inline_asm = _NO_ASM
avakulenko@google.com59146752014-08-11 20:20:55 +00002170 self.check_namespace_indentation = False
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002171
2172 def CheckBegin(self, filename, clean_lines, linenum, error):
2173 """Run checks that applies to text up to the opening brace.
2174
2175 This is mostly for checking the text after the class identifier
2176 and the "{", usually where the base class is specified. For other
2177 blocks, there isn't much to check, so we always pass.
2178
2179 Args:
2180 filename: The name of the current file.
2181 clean_lines: A CleansedLines instance containing the file.
2182 linenum: The number of the line to check.
2183 error: The function to call with any errors found.
2184 """
2185 pass
2186
2187 def CheckEnd(self, filename, clean_lines, linenum, error):
2188 """Run checks that applies to text after the closing brace.
2189
2190 This is mostly used for checking end of namespace comments.
2191
2192 Args:
2193 filename: The name of the current file.
2194 clean_lines: A CleansedLines instance containing the file.
2195 linenum: The number of the line to check.
2196 error: The function to call with any errors found.
2197 """
2198 pass
2199
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002200 def IsBlockInfo(self):
2201 """Returns true if this block is a _BlockInfo.
2202
2203 This is convenient for verifying that an object is an instance of
2204 a _BlockInfo, but not an instance of any of the derived classes.
2205
2206 Returns:
2207 True for this class, False for derived classes.
2208 """
2209 return self.__class__ == _BlockInfo
2210
2211
2212class _ExternCInfo(_BlockInfo):
2213 """Stores information about an 'extern "C"' block."""
2214
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002215 def __init__(self, linenum):
2216 _BlockInfo.__init__(self, linenum, True)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002217
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002218
2219class _ClassInfo(_BlockInfo):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002220 """Stores information about a class."""
2221
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002222 def __init__(self, name, class_or_struct, clean_lines, linenum):
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002223 _BlockInfo.__init__(self, linenum, False)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002224 self.name = name
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002225 self.is_derived = False
avakulenko@google.com59146752014-08-11 20:20:55 +00002226 self.check_namespace_indentation = True
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002227 if class_or_struct == 'struct':
2228 self.access = 'public'
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002229 self.is_struct = True
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002230 else:
2231 self.access = 'private'
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002232 self.is_struct = False
2233
2234 # Remember initial indentation level for this class. Using raw_lines here
2235 # instead of elided to account for leading comments.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002236 self.class_indent = GetIndentLevel(clean_lines.raw_lines[linenum])
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002237
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00002238 # Try to find the end of the class. This will be confused by things like:
2239 # class A {
2240 # } *x = { ...
2241 #
2242 # But it's still good enough for CheckSectionSpacing.
2243 self.last_line = 0
2244 depth = 0
2245 for i in range(linenum, clean_lines.NumLines()):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002246 line = clean_lines.elided[i]
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00002247 depth += line.count('{') - line.count('}')
2248 if not depth:
2249 self.last_line = i
2250 break
2251
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002252 def CheckBegin(self, filename, clean_lines, linenum, error):
2253 # Look for a bare ':'
2254 if Search('(^|[^:]):($|[^:])', clean_lines.elided[linenum]):
2255 self.is_derived = True
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002256
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002257 def CheckEnd(self, filename, clean_lines, linenum, error):
avakulenko@google.com255f2be2014-12-05 22:19:55 +00002258 # If there is a DISALLOW macro, it should appear near the end of
2259 # the class.
2260 seen_last_thing_in_class = False
Edward Lemur6d31ed52019-12-02 23:00:00 +00002261 for i in range(linenum - 1, self.starting_linenum, -1):
avakulenko@google.com255f2be2014-12-05 22:19:55 +00002262 match = Search(
2263 r'\b(DISALLOW_COPY_AND_ASSIGN|DISALLOW_IMPLICIT_CONSTRUCTORS)\(' +
2264 self.name + r'\)',
2265 clean_lines.elided[i])
2266 if match:
2267 if seen_last_thing_in_class:
2268 error(filename, i, 'readability/constructors', 3,
2269 match.group(1) + ' should be the last thing in the class')
2270 break
2271
2272 if not Match(r'^\s*$', clean_lines.elided[i]):
2273 seen_last_thing_in_class = True
2274
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002275 # Check that closing brace is aligned with beginning of the class.
2276 # Only do this if the closing brace is indented by only whitespaces.
2277 # This means we will not check single-line class definitions.
2278 indent = Match(r'^( *)\}', clean_lines.elided[linenum])
2279 if indent and len(indent.group(1)) != self.class_indent:
2280 if self.is_struct:
2281 parent = 'struct ' + self.name
2282 else:
2283 parent = 'class ' + self.name
2284 error(filename, linenum, 'whitespace/indent', 3,
2285 'Closing brace should be aligned with beginning of %s' % parent)
2286
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002287
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002288class _NamespaceInfo(_BlockInfo):
2289 """Stores information about a namespace."""
2290
2291 def __init__(self, name, linenum):
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002292 _BlockInfo.__init__(self, linenum, False)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002293 self.name = name or ''
avakulenko@google.com59146752014-08-11 20:20:55 +00002294 self.check_namespace_indentation = True
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002295
2296 def CheckEnd(self, filename, clean_lines, linenum, error):
2297 """Check end of namespace comments."""
2298 line = clean_lines.raw_lines[linenum]
2299
2300 # Check how many lines is enclosed in this namespace. Don't issue
2301 # warning for missing namespace comments if there aren't enough
2302 # lines. However, do apply checks if there is already an end of
2303 # namespace comment and it's incorrect.
2304 #
2305 # TODO(unknown): We always want to check end of namespace comments
2306 # if a namespace is large, but sometimes we also want to apply the
2307 # check if a short namespace contained nontrivial things (something
2308 # other than forward declarations). There is currently no logic on
2309 # deciding what these nontrivial things are, so this check is
2310 # triggered by namespace size only, which works most of the time.
2311 if (linenum - self.starting_linenum < 10
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002312 and not Match(r'^\s*};*\s*(//|/\*).*\bnamespace\b', line)):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002313 return
2314
2315 # Look for matching comment at end of namespace.
2316 #
2317 # Note that we accept C style "/* */" comments for terminating
2318 # namespaces, so that code that terminate namespaces inside
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002319 # preprocessor macros can be cpplint clean.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002320 #
2321 # We also accept stuff like "// end of namespace <name>." with the
2322 # period at the end.
2323 #
2324 # Besides these, we don't accept anything else, otherwise we might
2325 # get false negatives when existing comment is a substring of the
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002326 # expected namespace.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002327 if self.name:
2328 # Named namespace
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002329 if not Match((r'^\s*};*\s*(//|/\*).*\bnamespace\s+' +
2330 re.escape(self.name) + r'[\*/\.\\\s]*$'),
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002331 line):
2332 error(filename, linenum, 'readability/namespace', 5,
2333 'Namespace should be terminated with "// namespace %s"' %
2334 self.name)
2335 else:
2336 # Anonymous namespace
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002337 if not Match(r'^\s*};*\s*(//|/\*).*\bnamespace[\*/\.\\\s]*$', line):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002338 # If "// namespace anonymous" or "// anonymous namespace (more text)",
2339 # mention "// anonymous namespace" as an acceptable form
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002340 if Match(r'^\s*}.*\b(namespace anonymous|anonymous namespace)\b', line):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002341 error(filename, linenum, 'readability/namespace', 5,
2342 'Anonymous namespace should be terminated with "// namespace"'
2343 ' or "// anonymous namespace"')
2344 else:
2345 error(filename, linenum, 'readability/namespace', 5,
2346 'Anonymous namespace should be terminated with "// namespace"')
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002347
2348
2349class _PreprocessorInfo(object):
2350 """Stores checkpoints of nesting stacks when #if/#else is seen."""
2351
2352 def __init__(self, stack_before_if):
2353 # The entire nesting stack before #if
2354 self.stack_before_if = stack_before_if
2355
2356 # The entire nesting stack up to #else
2357 self.stack_before_else = []
2358
2359 # Whether we have already seen #else or #elif
2360 self.seen_else = False
2361
2362
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002363class NestingState(object):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002364 """Holds states related to parsing braces."""
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002365
2366 def __init__(self):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002367 # Stack for tracking all braces. An object is pushed whenever we
2368 # see a "{", and popped when we see a "}". Only 3 types of
2369 # objects are possible:
2370 # - _ClassInfo: a class or struct.
2371 # - _NamespaceInfo: a namespace.
2372 # - _BlockInfo: some other type of block.
2373 self.stack = []
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002374
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002375 # Top of the previous stack before each Update().
2376 #
2377 # Because the nesting_stack is updated at the end of each line, we
2378 # had to do some convoluted checks to find out what is the current
2379 # scope at the beginning of the line. This check is simplified by
2380 # saving the previous top of nesting stack.
2381 #
2382 # We could save the full stack, but we only need the top. Copying
2383 # the full nesting stack would slow down cpplint by ~10%.
2384 self.previous_stack_top = []
2385
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002386 # Stack of _PreprocessorInfo objects.
2387 self.pp_stack = []
2388
2389 def SeenOpenBrace(self):
2390 """Check if we have seen the opening brace for the innermost block.
2391
2392 Returns:
2393 True if we have seen the opening brace, False if the innermost
2394 block is still expecting an opening brace.
2395 """
2396 return (not self.stack) or self.stack[-1].seen_open_brace
2397
2398 def InNamespaceBody(self):
2399 """Check if we are currently one level inside a namespace body.
2400
2401 Returns:
2402 True if top of the stack is a namespace block, False otherwise.
2403 """
2404 return self.stack and isinstance(self.stack[-1], _NamespaceInfo)
2405
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002406 def InExternC(self):
2407 """Check if we are currently one level inside an 'extern "C"' block.
2408
2409 Returns:
2410 True if top of the stack is an extern block, False otherwise.
2411 """
2412 return self.stack and isinstance(self.stack[-1], _ExternCInfo)
2413
2414 def InClassDeclaration(self):
2415 """Check if we are currently one level inside a class or struct declaration.
2416
2417 Returns:
2418 True if top of the stack is a class/struct, False otherwise.
2419 """
2420 return self.stack and isinstance(self.stack[-1], _ClassInfo)
2421
2422 def InAsmBlock(self):
2423 """Check if we are currently one level inside an inline ASM block.
2424
2425 Returns:
2426 True if the top of the stack is a block containing inline ASM.
2427 """
2428 return self.stack and self.stack[-1].inline_asm != _NO_ASM
2429
2430 def InTemplateArgumentList(self, clean_lines, linenum, pos):
2431 """Check if current position is inside template argument list.
2432
2433 Args:
2434 clean_lines: A CleansedLines instance containing the file.
2435 linenum: The number of the line to check.
2436 pos: position just after the suspected template argument.
2437 Returns:
2438 True if (linenum, pos) is inside template arguments.
2439 """
2440 while linenum < clean_lines.NumLines():
2441 # Find the earliest character that might indicate a template argument
2442 line = clean_lines.elided[linenum]
2443 match = Match(r'^[^{};=\[\]\.<>]*(.)', line[pos:])
2444 if not match:
2445 linenum += 1
2446 pos = 0
2447 continue
2448 token = match.group(1)
2449 pos += len(match.group(0))
2450
2451 # These things do not look like template argument list:
2452 # class Suspect {
2453 # class Suspect x; }
2454 if token in ('{', '}', ';'): return False
2455
2456 # These things look like template argument list:
2457 # template <class Suspect>
2458 # template <class Suspect = default_value>
2459 # template <class Suspect[]>
2460 # template <class Suspect...>
2461 if token in ('>', '=', '[', ']', '.'): return True
2462
2463 # Check if token is an unmatched '<'.
2464 # If not, move on to the next character.
2465 if token != '<':
2466 pos += 1
2467 if pos >= len(line):
2468 linenum += 1
2469 pos = 0
2470 continue
2471
2472 # We can't be sure if we just find a single '<', and need to
2473 # find the matching '>'.
2474 (_, end_line, end_pos) = CloseExpression(clean_lines, linenum, pos - 1)
2475 if end_pos < 0:
2476 # Not sure if template argument list or syntax error in file
2477 return False
2478 linenum = end_line
2479 pos = end_pos
2480 return False
2481
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002482 def UpdatePreprocessor(self, line):
2483 """Update preprocessor stack.
2484
2485 We need to handle preprocessors due to classes like this:
2486 #ifdef SWIG
2487 struct ResultDetailsPageElementExtensionPoint {
2488 #else
2489 struct ResultDetailsPageElementExtensionPoint : public Extension {
2490 #endif
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002491
2492 We make the following assumptions (good enough for most files):
2493 - Preprocessor condition evaluates to true from #if up to first
2494 #else/#elif/#endif.
2495
2496 - Preprocessor condition evaluates to false from #else/#elif up
2497 to #endif. We still perform lint checks on these lines, but
2498 these do not affect nesting stack.
2499
2500 Args:
2501 line: current line to check.
2502 """
2503 if Match(r'^\s*#\s*(if|ifdef|ifndef)\b', line):
2504 # Beginning of #if block, save the nesting stack here. The saved
2505 # stack will allow us to restore the parsing state in the #else case.
2506 self.pp_stack.append(_PreprocessorInfo(copy.deepcopy(self.stack)))
2507 elif Match(r'^\s*#\s*(else|elif)\b', line):
2508 # Beginning of #else block
2509 if self.pp_stack:
2510 if not self.pp_stack[-1].seen_else:
2511 # This is the first #else or #elif block. Remember the
2512 # whole nesting stack up to this point. This is what we
2513 # keep after the #endif.
2514 self.pp_stack[-1].seen_else = True
2515 self.pp_stack[-1].stack_before_else = copy.deepcopy(self.stack)
2516
2517 # Restore the stack to how it was before the #if
2518 self.stack = copy.deepcopy(self.pp_stack[-1].stack_before_if)
2519 else:
2520 # TODO(unknown): unexpected #else, issue warning?
2521 pass
2522 elif Match(r'^\s*#\s*endif\b', line):
2523 # End of #if or #else blocks.
2524 if self.pp_stack:
2525 # If we saw an #else, we will need to restore the nesting
2526 # stack to its former state before the #else, otherwise we
2527 # will just continue from where we left off.
2528 if self.pp_stack[-1].seen_else:
2529 # Here we can just use a shallow copy since we are the last
2530 # reference to it.
2531 self.stack = self.pp_stack[-1].stack_before_else
2532 # Drop the corresponding #if
2533 self.pp_stack.pop()
2534 else:
2535 # TODO(unknown): unexpected #endif, issue warning?
2536 pass
2537
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002538 # TODO(unknown): Update() is too long, but we will refactor later.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002539 def Update(self, filename, clean_lines, linenum, error):
2540 """Update nesting state with current line.
2541
2542 Args:
2543 filename: The name of the current file.
2544 clean_lines: A CleansedLines instance containing the file.
2545 linenum: The number of the line to check.
2546 error: The function to call with any errors found.
2547 """
2548 line = clean_lines.elided[linenum]
2549
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002550 # Remember top of the previous nesting stack.
2551 #
2552 # The stack is always pushed/popped and not modified in place, so
2553 # we can just do a shallow copy instead of copy.deepcopy. Using
2554 # deepcopy would slow down cpplint by ~28%.
2555 if self.stack:
2556 self.previous_stack_top = self.stack[-1]
2557 else:
2558 self.previous_stack_top = None
2559
2560 # Update pp_stack
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002561 self.UpdatePreprocessor(line)
2562
2563 # Count parentheses. This is to avoid adding struct arguments to
2564 # the nesting stack.
2565 if self.stack:
2566 inner_block = self.stack[-1]
2567 depth_change = line.count('(') - line.count(')')
2568 inner_block.open_parentheses += depth_change
2569
2570 # Also check if we are starting or ending an inline assembly block.
2571 if inner_block.inline_asm in (_NO_ASM, _END_ASM):
2572 if (depth_change != 0 and
2573 inner_block.open_parentheses == 1 and
2574 _MATCH_ASM.match(line)):
2575 # Enter assembly block
2576 inner_block.inline_asm = _INSIDE_ASM
2577 else:
2578 # Not entering assembly block. If previous line was _END_ASM,
2579 # we will now shift to _NO_ASM state.
2580 inner_block.inline_asm = _NO_ASM
2581 elif (inner_block.inline_asm == _INSIDE_ASM and
2582 inner_block.open_parentheses == 0):
2583 # Exit assembly block
2584 inner_block.inline_asm = _END_ASM
2585
2586 # Consume namespace declaration at the beginning of the line. Do
2587 # this in a loop so that we catch same line declarations like this:
2588 # namespace proto2 { namespace bridge { class MessageSet; } }
2589 while True:
2590 # Match start of namespace. The "\b\s*" below catches namespace
2591 # declarations even if it weren't followed by a whitespace, this
2592 # is so that we don't confuse our namespace checker. The
2593 # missing spaces will be flagged by CheckSpacing.
2594 namespace_decl_match = Match(r'^\s*namespace\b\s*([:\w]+)?(.*)$', line)
2595 if not namespace_decl_match:
2596 break
2597
2598 new_namespace = _NamespaceInfo(namespace_decl_match.group(1), linenum)
2599 self.stack.append(new_namespace)
2600
2601 line = namespace_decl_match.group(2)
2602 if line.find('{') != -1:
2603 new_namespace.seen_open_brace = True
2604 line = line[line.find('{') + 1:]
2605
2606 # Look for a class declaration in whatever is left of the line
2607 # after parsing namespaces. The regexp accounts for decorated classes
2608 # such as in:
2609 # class LOCKABLE API Object {
2610 # };
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002611 class_decl_match = Match(
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002612 r'^(\s*(?:template\s*<[\w\s<>,:]*>\s*)?'
Clemens Hammacher2cc6e252018-12-20 08:40:19 +00002613 r'(class|struct)\s+(?:[A-Z0-9_]+\s+)*(\w+(?:::\w+)*))'
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002614 r'(.*)$', line)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002615 if (class_decl_match and
2616 (not self.stack or self.stack[-1].open_parentheses == 0)):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002617 # We do not want to accept classes that are actually template arguments:
2618 # template <class Ignore1,
2619 # class Ignore2 = Default<Args>,
2620 # template <Args> class Ignore3>
2621 # void Function() {};
2622 #
2623 # To avoid template argument cases, we scan forward and look for
2624 # an unmatched '>'. If we see one, assume we are inside a
2625 # template argument list.
2626 end_declaration = len(class_decl_match.group(1))
2627 if not self.InTemplateArgumentList(clean_lines, linenum, end_declaration):
2628 self.stack.append(_ClassInfo(
2629 class_decl_match.group(3), class_decl_match.group(2),
2630 clean_lines, linenum))
2631 line = class_decl_match.group(4)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002632
2633 # If we have not yet seen the opening brace for the innermost block,
2634 # run checks here.
2635 if not self.SeenOpenBrace():
2636 self.stack[-1].CheckBegin(filename, clean_lines, linenum, error)
2637
2638 # Update access control if we are inside a class/struct
2639 if self.stack and isinstance(self.stack[-1], _ClassInfo):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002640 classinfo = self.stack[-1]
2641 access_match = Match(
2642 r'^(.*)\b(public|private|protected|signals)(\s+(?:slots\s*)?)?'
2643 r':(?:[^:]|$)',
2644 line)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002645 if access_match:
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002646 classinfo.access = access_match.group(2)
2647
2648 # Check that access keywords are indented +1 space. Skip this
2649 # check if the keywords are not preceded by whitespaces.
2650 indent = access_match.group(1)
2651 if (len(indent) != classinfo.class_indent + 1 and
2652 Match(r'^\s*$', indent)):
2653 if classinfo.is_struct:
2654 parent = 'struct ' + classinfo.name
2655 else:
2656 parent = 'class ' + classinfo.name
2657 slots = ''
2658 if access_match.group(3):
2659 slots = access_match.group(3)
2660 error(filename, linenum, 'whitespace/indent', 3,
2661 '%s%s: should be indented +1 space inside %s' % (
2662 access_match.group(2), slots, parent))
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002663
2664 # Consume braces or semicolons from what's left of the line
2665 while True:
2666 # Match first brace, semicolon, or closed parenthesis.
2667 matched = Match(r'^[^{;)}]*([{;)}])(.*)$', line)
2668 if not matched:
2669 break
2670
2671 token = matched.group(1)
2672 if token == '{':
2673 # If namespace or class hasn't seen a opening brace yet, mark
2674 # namespace/class head as complete. Push a new block onto the
2675 # stack otherwise.
2676 if not self.SeenOpenBrace():
2677 self.stack[-1].seen_open_brace = True
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002678 elif Match(r'^extern\s*"[^"]*"\s*\{', line):
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002679 self.stack.append(_ExternCInfo(linenum))
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002680 else:
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002681 self.stack.append(_BlockInfo(linenum, True))
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002682 if _MATCH_ASM.match(line):
2683 self.stack[-1].inline_asm = _BLOCK_ASM
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002684
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002685 elif token == ';' or token == ')':
2686 # If we haven't seen an opening brace yet, but we already saw
2687 # a semicolon, this is probably a forward declaration. Pop
2688 # the stack for these.
2689 #
2690 # Similarly, if we haven't seen an opening brace yet, but we
2691 # already saw a closing parenthesis, then these are probably
2692 # function arguments with extra "class" or "struct" keywords.
2693 # Also pop these stack for these.
2694 if not self.SeenOpenBrace():
2695 self.stack.pop()
2696 else: # token == '}'
2697 # Perform end of block checks and pop the stack.
2698 if self.stack:
2699 self.stack[-1].CheckEnd(filename, clean_lines, linenum, error)
2700 self.stack.pop()
2701 line = matched.group(2)
2702
2703 def InnermostClass(self):
2704 """Get class info on the top of the stack.
2705
2706 Returns:
2707 A _ClassInfo object if we are inside a class, or None otherwise.
2708 """
2709 for i in range(len(self.stack), 0, -1):
2710 classinfo = self.stack[i - 1]
2711 if isinstance(classinfo, _ClassInfo):
2712 return classinfo
2713 return None
2714
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002715 def CheckCompletedBlocks(self, filename, error):
2716 """Checks that all classes and namespaces have been completely parsed.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002717
2718 Call this when all lines in a file have been processed.
2719 Args:
2720 filename: The name of the current file.
2721 error: The function to call with any errors found.
2722 """
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002723 # Note: This test can result in false positives if #ifdef constructs
2724 # get in the way of brace matching. See the testBuildClass test in
2725 # cpplint_unittest.py for an example of this.
2726 for obj in self.stack:
2727 if isinstance(obj, _ClassInfo):
2728 error(filename, obj.starting_linenum, 'build/class', 5,
2729 'Failed to find complete declaration of class %s' %
2730 obj.name)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002731 elif isinstance(obj, _NamespaceInfo):
2732 error(filename, obj.starting_linenum, 'build/namespaces', 5,
2733 'Failed to find complete declaration of namespace %s' %
2734 obj.name)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002735
2736
2737def CheckForNonStandardConstructs(filename, clean_lines, linenum,
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002738 nesting_state, error):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002739 r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002740
2741 Complain about several constructs which gcc-2 accepts, but which are
2742 not standard C++. Warning about these in lint is one way to ease the
2743 transition to new compilers.
2744 - put storage class first (e.g. "static const" instead of "const static").
2745 - "%lld" instead of %qd" in printf-type functions.
2746 - "%1$d" is non-standard in printf-type functions.
2747 - "\%" is an undefined character escape sequence.
2748 - text after #endif is not allowed.
2749 - invalid inner-style forward declaration.
2750 - >? and <? operators, and their >?= and <?= cousins.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002751
erg@google.com26970fa2009-11-17 18:07:32 +00002752 Additionally, check for constructor/destructor style violations and reference
2753 members, as it is very convenient to do so while checking for
2754 gcc-2 compliance.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002755
2756 Args:
2757 filename: The name of the current file.
2758 clean_lines: A CleansedLines instance containing the file.
2759 linenum: The number of the line to check.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002760 nesting_state: A NestingState instance which maintains information about
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002761 the current stack of nested blocks being parsed.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002762 error: A callable to which errors are reported, which takes 4 arguments:
2763 filename, line number, error level, and message
2764 """
2765
2766 # Remove comments from the line, but leave in strings for now.
2767 line = clean_lines.lines[linenum]
2768
2769 if Search(r'printf\s*\(.*".*%[-+ ]?\d*q', line):
2770 error(filename, linenum, 'runtime/printf_format', 3,
2771 '%q in format strings is deprecated. Use %ll instead.')
2772
2773 if Search(r'printf\s*\(.*".*%\d+\$', line):
2774 error(filename, linenum, 'runtime/printf_format', 2,
2775 '%N$ formats are unconventional. Try rewriting to avoid them.')
2776
2777 # Remove escaped backslashes before looking for undefined escapes.
2778 line = line.replace('\\\\', '')
2779
2780 if Search(r'("|\').*\\(%|\[|\(|{)', line):
2781 error(filename, linenum, 'build/printf_format', 3,
2782 '%, [, (, and { are undefined character escapes. Unescape them.')
2783
2784 # For the rest, work with both comments and strings removed.
2785 line = clean_lines.elided[linenum]
2786
2787 if Search(r'\b(const|volatile|void|char|short|int|long'
2788 r'|float|double|signed|unsigned'
2789 r'|schar|u?int8|u?int16|u?int32|u?int64)'
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002790 r'\s+(register|static|extern|typedef)\b',
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002791 line):
2792 error(filename, linenum, 'build/storage_class', 5,
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002793 'Storage-class specifier (static, extern, typedef, etc) should be '
2794 'at the beginning of the declaration.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002795
2796 if Match(r'\s*#\s*endif\s*[^/\s]+', line):
2797 error(filename, linenum, 'build/endif_comment', 5,
2798 'Uncommented text after #endif is non-standard. Use a comment.')
2799
2800 if Match(r'\s*class\s+(\w+\s*::\s*)+\w+\s*;', line):
2801 error(filename, linenum, 'build/forward_decl', 5,
2802 'Inner-style forward declarations are invalid. Remove this line.')
2803
2804 if Search(r'(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?',
2805 line):
2806 error(filename, linenum, 'build/deprecated', 3,
2807 '>? and <? (max and min) operators are non-standard and deprecated.')
2808
erg@google.com26970fa2009-11-17 18:07:32 +00002809 if Search(r'^\s*const\s*string\s*&\s*\w+\s*;', line):
2810 # TODO(unknown): Could it be expanded safely to arbitrary references,
2811 # without triggering too many false positives? The first
2812 # attempt triggered 5 warnings for mostly benign code in the regtest, hence
2813 # the restriction.
2814 # Here's the original regexp, for the reference:
2815 # type_name = r'\w+((\s*::\s*\w+)|(\s*<\s*\w+?\s*>))?'
2816 # r'\s*const\s*' + type_name + '\s*&\s*\w+\s*;'
2817 error(filename, linenum, 'runtime/member_string_references', 2,
2818 'const string& members are dangerous. It is much better to use '
2819 'alternatives, such as pointers or simple constants.')
2820
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002821 # Everything else in this function operates on class declarations.
2822 # Return early if the top of the nesting stack is not a class, or if
2823 # the class head is not completed yet.
2824 classinfo = nesting_state.InnermostClass()
2825 if not classinfo or not classinfo.seen_open_brace:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002826 return
2827
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002828 # The class may have been declared with namespace or classname qualifiers.
2829 # The constructor and destructor will not have those qualifiers.
2830 base_classname = classinfo.name.split('::')[-1]
2831
2832 # Look for single-argument constructors that aren't marked explicit.
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002833 # Technically a valid construct, but against style.
avakulenko@google.com59146752014-08-11 20:20:55 +00002834 explicit_constructor_match = Match(
danakjd7f56752017-02-22 11:45:06 -05002835 r'\s+(?:(?:inline|constexpr)\s+)*(explicit\s+)?'
2836 r'(?:(?:inline|constexpr)\s+)*%s\s*'
avakulenko@google.com59146752014-08-11 20:20:55 +00002837 r'\(((?:[^()]|\([^()]*\))*)\)'
2838 % re.escape(base_classname),
2839 line)
2840
2841 if explicit_constructor_match:
2842 is_marked_explicit = explicit_constructor_match.group(1)
2843
2844 if not explicit_constructor_match.group(2):
2845 constructor_args = []
2846 else:
2847 constructor_args = explicit_constructor_match.group(2).split(',')
2848
2849 # collapse arguments so that commas in template parameter lists and function
2850 # argument parameter lists don't split arguments in two
2851 i = 0
2852 while i < len(constructor_args):
2853 constructor_arg = constructor_args[i]
2854 while (constructor_arg.count('<') > constructor_arg.count('>') or
2855 constructor_arg.count('(') > constructor_arg.count(')')):
2856 constructor_arg += ',' + constructor_args[i + 1]
2857 del constructor_args[i + 1]
2858 constructor_args[i] = constructor_arg
2859 i += 1
2860
2861 defaulted_args = [arg for arg in constructor_args if '=' in arg]
2862 noarg_constructor = (not constructor_args or # empty arg list
2863 # 'void' arg specifier
2864 (len(constructor_args) == 1 and
2865 constructor_args[0].strip() == 'void'))
2866 onearg_constructor = ((len(constructor_args) == 1 and # exactly one arg
2867 not noarg_constructor) or
2868 # all but at most one arg defaulted
2869 (len(constructor_args) >= 1 and
2870 not noarg_constructor and
2871 len(defaulted_args) >= len(constructor_args) - 1))
2872 initializer_list_constructor = bool(
2873 onearg_constructor and
2874 Search(r'\bstd\s*::\s*initializer_list\b', constructor_args[0]))
2875 copy_constructor = bool(
2876 onearg_constructor and
2877 Match(r'(const\s+)?%s(\s*<[^>]*>)?(\s+const)?\s*(?:<\w+>\s*)?&'
2878 % re.escape(base_classname), constructor_args[0].strip()))
2879
2880 if (not is_marked_explicit and
2881 onearg_constructor and
2882 not initializer_list_constructor and
2883 not copy_constructor):
2884 if defaulted_args:
2885 error(filename, linenum, 'runtime/explicit', 5,
2886 'Constructors callable with one argument '
2887 'should be marked explicit.')
2888 else:
2889 error(filename, linenum, 'runtime/explicit', 5,
2890 'Single-parameter constructors should be marked explicit.')
2891 elif is_marked_explicit and not onearg_constructor:
2892 if noarg_constructor:
2893 error(filename, linenum, 'runtime/explicit', 5,
2894 'Zero-parameter constructors should not be marked explicit.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002895
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002896
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002897def CheckSpacingForFunctionCall(filename, clean_lines, linenum, error):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002898 """Checks for the correctness of various spacing around function calls.
2899
2900 Args:
2901 filename: The name of the current file.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002902 clean_lines: A CleansedLines instance containing the file.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002903 linenum: The number of the line to check.
2904 error: The function to call with any errors found.
2905 """
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002906 line = clean_lines.elided[linenum]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002907
2908 # Since function calls often occur inside if/for/while/switch
2909 # expressions - which have their own, more liberal conventions - we
2910 # first see if we should be looking inside such an expression for a
2911 # function call, to which we can apply more strict standards.
2912 fncall = line # if there's no control flow construct, look at whole line
Darius Maa7d7e42022-05-13 14:54:21 +00002913 for pattern in (r'\bif\s*(?:constexpr\s*)?\((.*)\)\s*{',
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002914 r'\bfor\s*\((.*)\)\s*{',
2915 r'\bwhile\s*\((.*)\)\s*[{;]',
2916 r'\bswitch\s*\((.*)\)\s*{'):
2917 match = Search(pattern, line)
2918 if match:
2919 fncall = match.group(1) # look inside the parens for function calls
2920 break
2921
2922 # Except in if/for/while/switch, there should never be space
2923 # immediately inside parens (eg "f( 3, 4 )"). We make an exception
2924 # for nested parens ( (a+b) + c ). Likewise, there should never be
2925 # a space before a ( when it's a function argument. I assume it's a
2926 # function argument when the char before the whitespace is legal in
2927 # a function name (alnum + _) and we're not starting a macro. Also ignore
2928 # pointers and references to arrays and functions coz they're too tricky:
2929 # we use a very simple way to recognize these:
2930 # " (something)(maybe-something)" or
2931 # " (something)(maybe-something," or
2932 # " (something)[something]"
2933 # Note that we assume the contents of [] to be short enough that
2934 # they'll never need to wrap.
2935 if ( # Ignore control structures.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002936 not Search(r'\b(if|for|while|switch|return|new|delete|catch|sizeof)\b',
2937 fncall) and
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002938 # Ignore pointers/references to functions.
2939 not Search(r' \([^)]+\)\([^)]*(\)|,$)', fncall) and
2940 # Ignore pointers/references to arrays.
2941 not Search(r' \([^)]+\)\[[^\]]+\]', fncall)):
erg@google.com6317a9c2009-06-25 00:28:19 +00002942 if Search(r'\w\s*\(\s(?!\s*\\$)', fncall): # a ( used for a fn call
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002943 error(filename, linenum, 'whitespace/parens', 4,
2944 'Extra space after ( in function call')
erg@google.com6317a9c2009-06-25 00:28:19 +00002945 elif Search(r'\(\s+(?!(\s*\\)|\()', fncall):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002946 error(filename, linenum, 'whitespace/parens', 2,
2947 'Extra space after (')
2948 if (Search(r'\w\s+\(', fncall) and
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002949 not Search(r'_{0,2}asm_{0,2}\s+_{0,2}volatile_{0,2}\s+\(', fncall) and
Bruce Dawson3e87cea2020-04-30 17:56:07 +00002950 not Search(r'#\s*define|typedef|__except|using\s+\w+\s*=', fncall) and
avakulenko@google.com255f2be2014-12-05 22:19:55 +00002951 not Search(r'\w\s+\((\w+::)*\*\w+\)\(', fncall) and
2952 not Search(r'\bcase\s+\(', fncall)):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002953 # TODO(unknown): Space after an operator function seem to be a common
2954 # error, silence those for now by restricting them to highest verbosity.
2955 if Search(r'\boperator_*\b', line):
2956 error(filename, linenum, 'whitespace/parens', 0,
2957 'Extra space before ( in function call')
2958 else:
2959 error(filename, linenum, 'whitespace/parens', 4,
2960 'Extra space before ( in function call')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002961 # If the ) is followed only by a newline or a { + newline, assume it's
2962 # part of a control statement (if/while/etc), and don't complain
2963 if Search(r'[^)]\s+\)\s*[^{\s]', fncall):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00002964 # If the closing parenthesis is preceded by only whitespaces,
2965 # try to give a more descriptive error message.
2966 if Search(r'^\s+\)', fncall):
2967 error(filename, linenum, 'whitespace/parens', 2,
2968 'Closing ) should be moved to the previous line')
2969 else:
2970 error(filename, linenum, 'whitespace/parens', 2,
2971 'Extra space before )')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002972
2973
2974def IsBlankLine(line):
2975 """Returns true if the given line is blank.
2976
2977 We consider a line to be blank if the line is empty or consists of
2978 only white spaces.
2979
2980 Args:
2981 line: A line of a string.
2982
2983 Returns:
2984 True, if the given line is blank.
2985 """
2986 return not line or line.isspace()
2987
2988
avakulenko@google.com59146752014-08-11 20:20:55 +00002989def CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line,
2990 error):
2991 is_namespace_indent_item = (
2992 len(nesting_state.stack) > 1 and
2993 nesting_state.stack[-1].check_namespace_indentation and
2994 isinstance(nesting_state.previous_stack_top, _NamespaceInfo) and
2995 nesting_state.previous_stack_top == nesting_state.stack[-2])
2996
2997 if ShouldCheckNamespaceIndentation(nesting_state, is_namespace_indent_item,
2998 clean_lines.elided, line):
2999 CheckItemIndentationInNamespace(filename, clean_lines.elided,
3000 line, error)
3001
3002
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003003def CheckForFunctionLengths(filename, clean_lines, linenum,
3004 function_state, error):
3005 """Reports for long function bodies.
3006
3007 For an overview why this is done, see:
Alexandr Ilinff294c32017-04-27 15:57:40 +02003008 https://google.github.io/styleguide/cppguide.html#Write_Short_Functions
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003009
3010 Uses a simplistic algorithm assuming other style guidelines
3011 (especially spacing) are followed.
3012 Only checks unindented functions, so class members are unchecked.
3013 Trivial bodies are unchecked, so constructors with huge initializer lists
3014 may be missed.
3015 Blank/comment lines are not counted so as to avoid encouraging the removal
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003016 of vertical space and comments just to get through a lint check.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003017 NOLINT *on the last line of a function* disables this check.
3018
3019 Args:
3020 filename: The name of the current file.
3021 clean_lines: A CleansedLines instance containing the file.
3022 linenum: The number of the line to check.
3023 function_state: Current function name and lines in body so far.
3024 error: The function to call with any errors found.
3025 """
3026 lines = clean_lines.lines
3027 line = lines[linenum]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003028 joined_line = ''
3029
3030 starting_func = False
erg@google.com6317a9c2009-06-25 00:28:19 +00003031 regexp = r'(\w(\w|::|\*|\&|\s)*)\(' # decls * & space::name( ...
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003032 match_result = Match(regexp, line)
3033 if match_result:
3034 # If the name is all caps and underscores, figure it's a macro and
3035 # ignore it, unless it's TEST or TEST_F.
3036 function_name = match_result.group(1).split()[-1]
3037 if function_name == 'TEST' or function_name == 'TEST_F' or (
Quinten Yearsley48099572019-02-22 21:13:37 +00003038 not Match(r'[A-Z_0-9]+$', function_name)):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003039 starting_func = True
3040
3041 if starting_func:
3042 body_found = False
Edward Lemur6d31ed52019-12-02 23:00:00 +00003043 for start_linenum in range(linenum, clean_lines.NumLines()):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003044 start_line = lines[start_linenum]
3045 joined_line += ' ' + start_line.lstrip()
3046 if Search(r'(;|})', start_line): # Declarations and trivial functions
3047 body_found = True
3048 break # ... ignore
3049 elif Search(r'{', start_line):
3050 body_found = True
3051 function = Search(r'((\w|:)*)\(', line).group(1)
3052 if Match(r'TEST', function): # Handle TEST... macros
3053 parameter_regexp = Search(r'(\(.*\))', joined_line)
3054 if parameter_regexp: # Ignore bad syntax
3055 function += parameter_regexp.group(1)
3056 else:
3057 function += '()'
3058 function_state.Begin(function)
3059 break
3060 if not body_found:
erg@google.com6317a9c2009-06-25 00:28:19 +00003061 # No body for the function (or evidence of a non-function) was found.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003062 error(filename, linenum, 'readability/fn_size', 5,
3063 'Lint failed to find start of function body.')
3064 elif Match(r'^\}\s*$', line): # function end
erg@google.com35589e62010-11-17 18:58:16 +00003065 function_state.Check(error, filename, linenum)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003066 function_state.End()
3067 elif not Match(r'^\s*$', line):
3068 function_state.Count() # Count non-blank/non-comment lines.
3069
3070
3071_RE_PATTERN_TODO = re.compile(r'^//(\s*)TODO(\(.+?\))?:?(\s|$)?')
3072
3073
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003074def CheckComment(line, filename, linenum, next_line_start, error):
3075 """Checks for common mistakes in comments.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003076
3077 Args:
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003078 line: The line in question.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003079 filename: The name of the current file.
3080 linenum: The number of the line to check.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003081 next_line_start: The first non-whitespace column of the next line.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003082 error: The function to call with any errors found.
3083 """
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003084 commentpos = line.find('//')
3085 if commentpos != -1:
3086 # Check if the // may be in quotes. If so, ignore it
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003087 if re.sub(r'\\.', '', line[0:commentpos]).count('"') % 2 == 0:
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003088 # Allow one space for new scopes, two spaces otherwise:
3089 if (not (Match(r'^.*{ *//', line) and next_line_start == commentpos) and
3090 ((commentpos >= 1 and
3091 line[commentpos-1] not in string.whitespace) or
3092 (commentpos >= 2 and
3093 line[commentpos-2] not in string.whitespace))):
3094 error(filename, linenum, 'whitespace/comments', 2,
3095 'At least two spaces is best between code and comments')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003096
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003097 # Checks for common mistakes in TODO comments.
3098 comment = line[commentpos:]
3099 match = _RE_PATTERN_TODO.match(comment)
3100 if match:
3101 # One whitespace is correct; zero whitespace is handled elsewhere.
3102 leading_whitespace = match.group(1)
3103 if len(leading_whitespace) > 1:
3104 error(filename, linenum, 'whitespace/todo', 2,
3105 'Too many spaces before TODO')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003106
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003107 username = match.group(2)
3108 if not username:
3109 error(filename, linenum, 'readability/todo', 2,
3110 'Missing username in TODO; it should look like '
3111 '"// TODO(my_username): Stuff."')
3112
3113 middle_whitespace = match.group(3)
3114 # Comparisons made explicit for correctness -- pylint: disable=g-explicit-bool-comparison
3115 if middle_whitespace != ' ' and middle_whitespace != '':
3116 error(filename, linenum, 'whitespace/todo', 2,
3117 'TODO(my_username) should be followed by a space')
3118
3119 # If the comment contains an alphanumeric character, there
avakulenko@google.com255f2be2014-12-05 22:19:55 +00003120 # should be a space somewhere between it and the // unless
3121 # it's a /// or //! Doxygen comment.
3122 if (Match(r'//[^ ]*\w', comment) and
3123 not Match(r'(///|//\!)(\s+|$)', comment)):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003124 error(filename, linenum, 'whitespace/comments', 4,
3125 'Should have a space between // and comment')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003126
avakulenko@google.com255f2be2014-12-05 22:19:55 +00003127
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003128def CheckSpacing(filename, clean_lines, linenum, nesting_state, error):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003129 """Checks for the correctness of various spacing issues in the code.
3130
3131 Things we check for: spaces around operators, spaces after
3132 if/for/while/switch, no spaces around parens in function calls, two
3133 spaces between code and comment, don't start a block with a blank
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003134 line, don't end a function with a blank line, don't add a blank line
3135 after public/protected/private, don't have too many blank lines in a row.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003136
3137 Args:
3138 filename: The name of the current file.
3139 clean_lines: A CleansedLines instance containing the file.
3140 linenum: The number of the line to check.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003141 nesting_state: A NestingState instance which maintains information about
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003142 the current stack of nested blocks being parsed.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003143 error: The function to call with any errors found.
3144 """
3145
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003146 # Don't use "elided" lines here, otherwise we can't check commented lines.
3147 # Don't want to use "raw" either, because we don't want to check inside C++11
3148 # raw strings,
3149 raw = clean_lines.lines_without_raw_strings
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003150 line = raw[linenum]
3151
3152 # Before nixing comments, check if the line is blank for no good
3153 # reason. This includes the first line after a block is opened, and
3154 # blank lines at the end of a function (ie, right before a line like '}'
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003155 #
3156 # Skip all the blank line checks if we are immediately inside a
3157 # namespace body. In other words, don't issue blank line warnings
3158 # for this block:
3159 # namespace {
3160 #
3161 # }
3162 #
3163 # A warning about missing end of namespace comments will be issued instead.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003164 #
3165 # Also skip blank line checks for 'extern "C"' blocks, which are formatted
3166 # like namespaces.
3167 if (IsBlankLine(line) and
3168 not nesting_state.InNamespaceBody() and
3169 not nesting_state.InExternC()):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003170 elided = clean_lines.elided
3171 prev_line = elided[linenum - 1]
3172 prevbrace = prev_line.rfind('{')
3173 # TODO(unknown): Don't complain if line before blank line, and line after,
3174 # both start with alnums and are indented the same amount.
3175 # This ignores whitespace at the start of a namespace block
3176 # because those are not usually indented.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003177 if prevbrace != -1 and prev_line[prevbrace:].find('}') == -1:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003178 # OK, we have a blank line at the start of a code block. Before we
3179 # complain, we check if it is an exception to the rule: The previous
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003180 # non-empty line has the parameters of a function header that are indented
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003181 # 4 spaces (because they did not fit in a 80 column line when placed on
3182 # the same line as the function name). We also check for the case where
3183 # the previous line is indented 6 spaces, which may happen when the
3184 # initializers of a constructor do not fit into a 80 column line.
3185 exception = False
3186 if Match(r' {6}\w', prev_line): # Initializer list?
3187 # We are looking for the opening column of initializer list, which
3188 # should be indented 4 spaces to cause 6 space indentation afterwards.
3189 search_position = linenum-2
3190 while (search_position >= 0
3191 and Match(r' {6}\w', elided[search_position])):
3192 search_position -= 1
3193 exception = (search_position >= 0
3194 and elided[search_position][:5] == ' :')
3195 else:
3196 # Search for the function arguments or an initializer list. We use a
3197 # simple heuristic here: If the line is indented 4 spaces; and we have a
3198 # closing paren, without the opening paren, followed by an opening brace
3199 # or colon (for initializer lists) we assume that it is the last line of
3200 # a function header. If we have a colon indented 4 spaces, it is an
3201 # initializer list.
3202 exception = (Match(r' {4}\w[^\(]*\)\s*(const\s*)?(\{\s*$|:)',
3203 prev_line)
3204 or Match(r' {4}:', prev_line))
3205
3206 if not exception:
3207 error(filename, linenum, 'whitespace/blank_line', 2,
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003208 'Redundant blank line at the start of a code block '
3209 'should be deleted.')
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003210 # Ignore blank lines at the end of a block in a long if-else
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003211 # chain, like this:
3212 # if (condition1) {
3213 # // Something followed by a blank line
3214 #
3215 # } else if (condition2) {
3216 # // Something else
3217 # }
3218 if linenum + 1 < clean_lines.NumLines():
3219 next_line = raw[linenum + 1]
3220 if (next_line
3221 and Match(r'\s*}', next_line)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003222 and next_line.find('} else ') == -1):
3223 error(filename, linenum, 'whitespace/blank_line', 3,
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003224 'Redundant blank line at the end of a code block '
3225 'should be deleted.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003226
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003227 matched = Match(r'\s*(public|protected|private):', prev_line)
3228 if matched:
3229 error(filename, linenum, 'whitespace/blank_line', 3,
3230 'Do not leave a blank line after "%s:"' % matched.group(1))
3231
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003232 # Next, check comments
3233 next_line_start = 0
3234 if linenum + 1 < clean_lines.NumLines():
3235 next_line = raw[linenum + 1]
3236 next_line_start = len(next_line) - len(next_line.lstrip())
3237 CheckComment(line, filename, linenum, next_line_start, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003238
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003239 # get rid of comments and strings
3240 line = clean_lines.elided[linenum]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003241
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003242 # You shouldn't have spaces before your brackets, except maybe after
Alex Lightac54b8d2022-01-20 13:02:48 +00003243 # 'delete []', 'return []() {};', 'auto [abc, ...] = ...;' or in the case of
3244 # c++ attributes like 'class [[clang::lto_visibility_public]] MyClass'.
Derek Morrisb8265f12020-04-16 18:40:27 +00003245 if (Search(r'\w\s+\[', line)
Alex Lightac54b8d2022-01-20 13:02:48 +00003246 and not Search(r'(?:auto&?|delete|return)\s+\[', line)
Derek Morrisb8265f12020-04-16 18:40:27 +00003247 and not Search(r'\s+\[\[', line)):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003248 error(filename, linenum, 'whitespace/braces', 5,
3249 'Extra space before [')
3250
3251 # In range-based for, we wanted spaces before and after the colon, but
3252 # not around "::" tokens that might appear.
3253 if (Search(r'for *\(.*[^:]:[^: ]', line) or
3254 Search(r'for *\(.*[^: ]:[^:]', line)):
3255 error(filename, linenum, 'whitespace/forcolon', 2,
3256 'Missing space around colon in range-based for loop')
3257
3258
3259def CheckOperatorSpacing(filename, clean_lines, linenum, error):
3260 """Checks for horizontal spacing around operators.
3261
3262 Args:
3263 filename: The name of the current file.
3264 clean_lines: A CleansedLines instance containing the file.
3265 linenum: The number of the line to check.
3266 error: The function to call with any errors found.
3267 """
3268 line = clean_lines.elided[linenum]
3269
3270 # Don't try to do spacing checks for operator methods. Do this by
3271 # replacing the troublesome characters with something else,
3272 # preserving column position for all other characters.
3273 #
3274 # The replacement is done repeatedly to avoid false positives from
3275 # operators that call operators.
3276 while True:
3277 match = Match(r'^(.*\boperator\b)(\S+)(\s*\(.*)$', line)
3278 if match:
3279 line = match.group(1) + ('_' * len(match.group(2))) + match.group(3)
3280 else:
3281 break
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003282
3283 # We allow no-spaces around = within an if: "if ( (a=Foo()) == 0 )".
3284 # Otherwise not. Note we only check for non-spaces on *both* sides;
3285 # sometimes people put non-spaces on one side when aligning ='s among
3286 # many lines (not that this is behavior that I approve of...)
avakulenko@google.com255f2be2014-12-05 22:19:55 +00003287 if ((Search(r'[\w.]=', line) or
3288 Search(r'=[\w.]', line))
3289 and not Search(r'\b(if|while|for) ', line)
3290 # Operators taken from [lex.operators] in C++11 standard.
3291 and not Search(r'(>=|<=|==|!=|&=|\^=|\|=|\+=|\*=|\/=|\%=)', line)
3292 and not Search(r'operator=', line)):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003293 error(filename, linenum, 'whitespace/operators', 4,
3294 'Missing spaces around =')
3295
3296 # It's ok not to have spaces around binary operators like + - * /, but if
3297 # there's too little whitespace, we get concerned. It's hard to tell,
3298 # though, so we punt on this one for now. TODO.
3299
3300 # You should always have whitespace around binary operators.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003301 #
3302 # Check <= and >= first to avoid false positives with < and >, then
3303 # check non-include lines for spacing around < and >.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003304 #
3305 # If the operator is followed by a comma, assume it's be used in a
3306 # macro context and don't do any checks. This avoids false
3307 # positives.
3308 #
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003309 # Note that && is not included here. This is because there are too
3310 # many false positives due to RValue references.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003311 match = Search(r'[^<>=!\s](==|!=|<=|>=|\|\|)[^<>=!\s,;\)]', line)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003312 if match:
3313 error(filename, linenum, 'whitespace/operators', 3,
3314 'Missing spaces around %s' % match.group(1))
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003315 elif not Match(r'#.*include', line):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003316 # Look for < that is not surrounded by spaces. This is only
3317 # triggered if both sides are missing spaces, even though
3318 # technically should should flag if at least one side is missing a
3319 # space. This is done to avoid some false positives with shifts.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003320 match = Match(r'^(.*[^\s<])<[^\s=<,]', line)
3321 if match:
3322 (_, _, end_pos) = CloseExpression(
3323 clean_lines, linenum, len(match.group(1)))
3324 if end_pos <= -1:
3325 error(filename, linenum, 'whitespace/operators', 3,
3326 'Missing spaces around <')
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003327
3328 # Look for > that is not surrounded by spaces. Similar to the
3329 # above, we only trigger if both sides are missing spaces to avoid
3330 # false positives with shifts.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003331 match = Match(r'^(.*[^-\s>])>[^\s=>,]', line)
3332 if match:
3333 (_, _, start_pos) = ReverseCloseExpression(
3334 clean_lines, linenum, len(match.group(1)))
3335 if start_pos <= -1:
3336 error(filename, linenum, 'whitespace/operators', 3,
3337 'Missing spaces around >')
3338
3339 # We allow no-spaces around << when used like this: 10<<20, but
3340 # not otherwise (particularly, not when used as streams)
avakulenko@google.com59146752014-08-11 20:20:55 +00003341 #
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003342 # We also allow operators following an opening parenthesis, since
3343 # those tend to be macros that deal with operators.
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003344 match = Search(r'(operator|[^\s(<])(?:L|UL|LL|ULL|l|ul|ll|ull)?<<([^\s,=<])', line)
avakulenko@google.com255f2be2014-12-05 22:19:55 +00003345 if (match and not (match.group(1).isdigit() and match.group(2).isdigit()) and
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003346 not (match.group(1) == 'operator' and match.group(2) == ';')):
3347 error(filename, linenum, 'whitespace/operators', 3,
3348 'Missing spaces around <<')
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003349
3350 # We allow no-spaces around >> for almost anything. This is because
3351 # C++11 allows ">>" to close nested templates, which accounts for
3352 # most cases when ">>" is not followed by a space.
3353 #
3354 # We still warn on ">>" followed by alpha character, because that is
3355 # likely due to ">>" being used for right shifts, e.g.:
3356 # value >> alpha
3357 #
3358 # When ">>" is used to close templates, the alphanumeric letter that
3359 # follows would be part of an identifier, and there should still be
3360 # a space separating the template type and the identifier.
3361 # type<type<type>> alpha
3362 match = Search(r'>>[a-zA-Z_]', line)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003363 if match:
3364 error(filename, linenum, 'whitespace/operators', 3,
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003365 'Missing spaces around >>')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003366
3367 # There shouldn't be space around unary operators
3368 match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line)
3369 if match:
3370 error(filename, linenum, 'whitespace/operators', 4,
3371 'Extra space for operator %s' % match.group(1))
3372
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003373
3374def CheckParenthesisSpacing(filename, clean_lines, linenum, error):
3375 """Checks for horizontal spacing around parentheses.
3376
3377 Args:
3378 filename: The name of the current file.
3379 clean_lines: A CleansedLines instance containing the file.
3380 linenum: The number of the line to check.
3381 error: The function to call with any errors found.
3382 """
3383 line = clean_lines.elided[linenum]
3384
3385 # No spaces after an if, while, switch, or for
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003386 match = Search(r' (if\(|for\(|while\(|switch\()', line)
3387 if match:
3388 error(filename, linenum, 'whitespace/parens', 5,
3389 'Missing space before ( in %s' % match.group(1))
3390
3391 # For if/for/while/switch, the left and right parens should be
3392 # consistent about how many spaces are inside the parens, and
3393 # there should either be zero or one spaces inside the parens.
3394 # We don't want: "if ( foo)" or "if ( foo )".
erg@google.com6317a9c2009-06-25 00:28:19 +00003395 # Exception: "for ( ; foo; bar)" and "for (foo; bar; )" are allowed.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003396 match = Search(r'\b(if|for|while|switch)\s*'
3397 r'\(([ ]*)(.).*[^ ]+([ ]*)\)\s*{\s*$',
3398 line)
3399 if match:
3400 if len(match.group(2)) != len(match.group(4)):
3401 if not (match.group(3) == ';' and
erg@google.com6317a9c2009-06-25 00:28:19 +00003402 len(match.group(2)) == 1 + len(match.group(4)) or
3403 not match.group(2) and Search(r'\bfor\s*\(.*; \)', line)):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003404 error(filename, linenum, 'whitespace/parens', 5,
3405 'Mismatching spaces inside () in %s' % match.group(1))
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003406 if len(match.group(2)) not in [0, 1]:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003407 error(filename, linenum, 'whitespace/parens', 5,
3408 'Should have zero or one spaces inside ( and ) in %s' %
3409 match.group(1))
3410
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003411
3412def CheckCommaSpacing(filename, clean_lines, linenum, error):
3413 """Checks for horizontal spacing near commas and semicolons.
3414
3415 Args:
3416 filename: The name of the current file.
3417 clean_lines: A CleansedLines instance containing the file.
3418 linenum: The number of the line to check.
3419 error: The function to call with any errors found.
3420 """
3421 raw = clean_lines.lines_without_raw_strings
3422 line = clean_lines.elided[linenum]
3423
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003424 # 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 +00003425 #
3426 # This does not apply when the non-space character following the
3427 # comma is another comma, since the only time when that happens is
3428 # for empty macro arguments.
3429 #
3430 # We run this check in two passes: first pass on elided lines to
3431 # verify that lines contain missing whitespaces, second pass on raw
3432 # lines to confirm that those missing whitespaces are not due to
3433 # elided comments.
avakulenko@google.com59146752014-08-11 20:20:55 +00003434 if (Search(r',[^,\s]', ReplaceAll(r'\boperator\s*,\s*\(', 'F(', line)) and
3435 Search(r',[^,\s]', raw[linenum])):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003436 error(filename, linenum, 'whitespace/comma', 3,
3437 'Missing space after ,')
3438
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003439 # You should always have a space after a semicolon
3440 # except for few corner cases
3441 # TODO(unknown): clarify if 'if (1) { return 1;}' is requires one more
3442 # space after ;
3443 if Search(r';[^\s};\\)/]', line):
3444 error(filename, linenum, 'whitespace/semicolon', 3,
3445 'Missing space after ;')
3446
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003447
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003448def _IsType(clean_lines, nesting_state, expr):
3449 """Check if expression looks like a type name, returns true if so.
3450
3451 Args:
3452 clean_lines: A CleansedLines instance containing the file.
3453 nesting_state: A NestingState instance which maintains information about
3454 the current stack of nested blocks being parsed.
3455 expr: The expression to check.
3456 Returns:
3457 True, if token looks like a type.
3458 """
3459 # Keep only the last token in the expression
3460 last_word = Match(r'^.*(\b\S+)$', expr)
3461 if last_word:
3462 token = last_word.group(1)
3463 else:
3464 token = expr
3465
3466 # Match native types and stdint types
3467 if _TYPES.match(token):
3468 return True
3469
3470 # Try a bit harder to match templated types. Walk up the nesting
3471 # stack until we find something that resembles a typename
3472 # declaration for what we are looking for.
3473 typename_pattern = (r'\b(?:typename|class|struct)\s+' + re.escape(token) +
3474 r'\b')
3475 block_index = len(nesting_state.stack) - 1
3476 while block_index >= 0:
3477 if isinstance(nesting_state.stack[block_index], _NamespaceInfo):
3478 return False
3479
3480 # Found where the opening brace is. We want to scan from this
3481 # line up to the beginning of the function, minus a few lines.
3482 # template <typename Type1, // stop scanning here
3483 # ...>
3484 # class C
3485 # : public ... { // start scanning here
3486 last_line = nesting_state.stack[block_index].starting_linenum
3487
3488 next_block_start = 0
3489 if block_index > 0:
3490 next_block_start = nesting_state.stack[block_index - 1].starting_linenum
3491 first_line = last_line
3492 while first_line >= next_block_start:
3493 if clean_lines.elided[first_line].find('template') >= 0:
3494 break
3495 first_line -= 1
3496 if first_line < next_block_start:
3497 # Didn't find any "template" keyword before reaching the next block,
3498 # there are probably no template things to check for this block
3499 block_index -= 1
3500 continue
3501
3502 # Look for typename in the specified range
Edward Lemur6d31ed52019-12-02 23:00:00 +00003503 for i in range(first_line, last_line + 1, 1):
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003504 if Search(typename_pattern, clean_lines.elided[i]):
3505 return True
3506 block_index -= 1
3507
3508 return False
3509
3510
3511def CheckBracesSpacing(filename, clean_lines, linenum, nesting_state, error):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003512 """Checks for horizontal spacing near commas.
3513
3514 Args:
3515 filename: The name of the current file.
3516 clean_lines: A CleansedLines instance containing the file.
3517 linenum: The number of the line to check.
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003518 nesting_state: A NestingState instance which maintains information about
3519 the current stack of nested blocks being parsed.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003520 error: The function to call with any errors found.
3521 """
3522 line = clean_lines.elided[linenum]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003523
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003524 # Except after an opening paren, or after another opening brace (in case of
3525 # an initializer list, for instance), you should have spaces before your
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003526 # braces when they are delimiting blocks, classes, namespaces etc.
3527 # And since you should never have braces at the beginning of a line,
3528 # this is an easy test. Except that braces used for initialization don't
3529 # follow the same rule; we often don't want spaces before those.
avakulenko@google.com255f2be2014-12-05 22:19:55 +00003530 match = Match(r'^(.*[^ ({>]){', line)
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003531
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003532 if match:
3533 # Try a bit harder to check for brace initialization. This
3534 # happens in one of the following forms:
3535 # Constructor() : initializer_list_{} { ... }
3536 # Constructor{}.MemberFunction()
3537 # Type variable{};
3538 # FunctionCall(type{}, ...);
3539 # LastArgument(..., type{});
3540 # LOG(INFO) << type{} << " ...";
3541 # map_of_type[{...}] = ...;
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003542 # ternary = expr ? new type{} : nullptr;
3543 # OuterTemplate<InnerTemplateConstructor<Type>{}>
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003544 #
3545 # We check for the character following the closing brace, and
3546 # silence the warning if it's one of those listed above, i.e.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003547 # "{.;,)<>]:".
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003548 #
3549 # To account for nested initializer list, we allow any number of
3550 # closing braces up to "{;,)<". We can't simply silence the
3551 # warning on first sight of closing brace, because that would
3552 # cause false negatives for things that are not initializer lists.
3553 # Silence this: But not this:
3554 # Outer{ if (...) {
3555 # Inner{...} if (...){ // Missing space before {
3556 # }; }
3557 #
3558 # There is a false negative with this approach if people inserted
3559 # spurious semicolons, e.g. "if (cond){};", but we will catch the
3560 # spurious semicolon with a separate check.
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003561 leading_text = match.group(1)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003562 (endline, endlinenum, endpos) = CloseExpression(
3563 clean_lines, linenum, len(match.group(1)))
3564 trailing_text = ''
3565 if endpos > -1:
3566 trailing_text = endline[endpos:]
Edward Lemur6d31ed52019-12-02 23:00:00 +00003567 for offset in range(endlinenum + 1,
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003568 min(endlinenum + 3, clean_lines.NumLines() - 1)):
3569 trailing_text += clean_lines.elided[offset]
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003570 # We also suppress warnings for `uint64_t{expression}` etc., as the style
3571 # guide recommends brace initialization for integral types to avoid
3572 # overflow/truncation.
3573 if (not Match(r'^[\s}]*[{.;,)<>\]:]', trailing_text)
3574 and not _IsType(clean_lines, nesting_state, leading_text)):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003575 error(filename, linenum, 'whitespace/braces', 5,
3576 'Missing space before {')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003577
3578 # Make sure '} else {' has spaces.
3579 if Search(r'}else', line):
3580 error(filename, linenum, 'whitespace/braces', 5,
3581 'Missing space before else')
3582
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003583 # You shouldn't have a space before a semicolon at the end of the line.
3584 # There's a special case for "for" since the style guide allows space before
3585 # the semicolon there.
3586 if Search(r':\s*;\s*$', line):
3587 error(filename, linenum, 'whitespace/semicolon', 5,
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003588 'Semicolon defining empty statement. Use {} instead.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003589 elif Search(r'^\s*;\s*$', line):
3590 error(filename, linenum, 'whitespace/semicolon', 5,
3591 'Line contains only semicolon. If this should be an empty statement, '
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003592 'use {} instead.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003593 elif (Search(r'\s+;\s*$', line) and
3594 not Search(r'\bfor\b', line)):
3595 error(filename, linenum, 'whitespace/semicolon', 5,
3596 'Extra space before last semicolon. If this should be an empty '
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003597 'statement, use {} instead.')
3598
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003599
3600def IsDecltype(clean_lines, linenum, column):
3601 """Check if the token ending on (linenum, column) is decltype().
3602
3603 Args:
3604 clean_lines: A CleansedLines instance containing the file.
3605 linenum: the number of the line to check.
3606 column: end column of the token to check.
3607 Returns:
3608 True if this token is decltype() expression, False otherwise.
3609 """
3610 (text, _, start_col) = ReverseCloseExpression(clean_lines, linenum, column)
3611 if start_col < 0:
3612 return False
3613 if Search(r'\bdecltype\s*$', text[0:start_col]):
3614 return True
3615 return False
3616
3617
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003618def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error):
3619 """Checks for additional blank line issues related to sections.
3620
3621 Currently the only thing checked here is blank line before protected/private.
3622
3623 Args:
3624 filename: The name of the current file.
3625 clean_lines: A CleansedLines instance containing the file.
3626 class_info: A _ClassInfo objects.
3627 linenum: The number of the line to check.
3628 error: The function to call with any errors found.
3629 """
3630 # Skip checks if the class is small, where small means 25 lines or less.
3631 # 25 lines seems like a good cutoff since that's the usual height of
3632 # terminals, and any class that can't fit in one screen can't really
3633 # be considered "small".
3634 #
3635 # Also skip checks if we are on the first line. This accounts for
3636 # classes that look like
3637 # class Foo { public: ... };
3638 #
3639 # If we didn't find the end of the class, last_line would be zero,
3640 # and the check will be skipped by the first condition.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003641 if (class_info.last_line - class_info.starting_linenum <= 24 or
3642 linenum <= class_info.starting_linenum):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003643 return
3644
3645 matched = Match(r'\s*(public|protected|private):', clean_lines.lines[linenum])
3646 if matched:
3647 # Issue warning if the line before public/protected/private was
3648 # not a blank line, but don't do this if the previous line contains
3649 # "class" or "struct". This can happen two ways:
3650 # - We are at the beginning of the class.
3651 # - We are forward-declaring an inner class that is semantically
3652 # private, but needed to be public for implementation reasons.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003653 # Also ignores cases where the previous line ends with a backslash as can be
3654 # common when defining classes in C macros.
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003655 prev_line = clean_lines.lines[linenum - 1]
3656 if (not IsBlankLine(prev_line) and
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003657 not Search(r'\b(class|struct)\b', prev_line) and
3658 not Search(r'\\$', prev_line)):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003659 # Try a bit harder to find the beginning of the class. This is to
3660 # account for multi-line base-specifier lists, e.g.:
3661 # class Derived
3662 # : public Base {
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003663 end_class_head = class_info.starting_linenum
3664 for i in range(class_info.starting_linenum, linenum):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003665 if Search(r'\{\s*$', clean_lines.lines[i]):
3666 end_class_head = i
3667 break
3668 if end_class_head < linenum - 1:
3669 error(filename, linenum, 'whitespace/blank_line', 3,
3670 '"%s:" should be preceded by a blank line' % matched.group(1))
3671
3672
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003673def GetPreviousNonBlankLine(clean_lines, linenum):
3674 """Return the most recent non-blank line and its line number.
3675
3676 Args:
3677 clean_lines: A CleansedLines instance containing the file contents.
3678 linenum: The number of the line to check.
3679
3680 Returns:
3681 A tuple with two elements. The first element is the contents of the last
3682 non-blank line before the current line, or the empty string if this is the
3683 first non-blank line. The second is the line number of that line, or -1
3684 if this is the first non-blank line.
3685 """
3686
3687 prevlinenum = linenum - 1
3688 while prevlinenum >= 0:
3689 prevline = clean_lines.elided[prevlinenum]
3690 if not IsBlankLine(prevline): # if not a blank line...
3691 return (prevline, prevlinenum)
3692 prevlinenum -= 1
3693 return ('', -1)
3694
3695
3696def CheckBraces(filename, clean_lines, linenum, error):
3697 """Looks for misplaced braces (e.g. at the end of line).
3698
3699 Args:
3700 filename: The name of the current file.
3701 clean_lines: A CleansedLines instance containing the file.
3702 linenum: The number of the line to check.
3703 error: The function to call with any errors found.
3704 """
3705
3706 line = clean_lines.elided[linenum] # get rid of comments and strings
3707
3708 if Match(r'\s*{\s*$', line):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003709 # We allow an open brace to start a line in the case where someone is using
3710 # braces in a block to explicitly create a new scope, which is commonly used
3711 # to control the lifetime of stack-allocated variables. Braces are also
3712 # used for brace initializers inside function calls. We don't detect this
3713 # perfectly: we just don't complain if the last non-whitespace character on
3714 # the previous non-blank line is ',', ';', ':', '(', '{', or '}', or if the
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003715 # previous line starts a preprocessor block. We also allow a brace on the
3716 # following line if it is part of an array initialization and would not fit
3717 # within the 80 character limit of the preceding line.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003718 prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003719 if (not Search(r'[,;:}{(]\s*$', prevline) and
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003720 not Match(r'\s*#', prevline) and
3721 not (GetLineWidth(prevline) > _line_length - 2 and '[]' in prevline)):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003722 error(filename, linenum, 'whitespace/braces', 4,
3723 '{ should almost always be at the end of the previous line')
3724
3725 # An else clause should be on the same line as the preceding closing brace.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003726 if Match(r'\s*else\b\s*(?:if\b|\{|$)', line):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003727 prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
3728 if Match(r'\s*}\s*$', prevline):
3729 error(filename, linenum, 'whitespace/newline', 4,
3730 'An else should appear on the same line as the preceding }')
3731
3732 # If braces come on one side of an else, they should be on both.
3733 # However, we have to worry about "else if" that spans multiple lines!
Darius Maa7d7e42022-05-13 14:54:21 +00003734 if Search(r'else if\s*(?:constexpr\s*)?\(', line): # could be multi-line if
3735 brace_on_left = bool(Search(r'}\s*else if\s*(?:constexpr\s*)?\(', line))
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003736 # find the ( after the if
3737 pos = line.find('else if')
3738 pos = line.find('(', pos)
3739 if pos > 0:
3740 (endline, _, endpos) = CloseExpression(clean_lines, linenum, pos)
3741 brace_on_right = endline[endpos:].find('{') != -1
3742 if brace_on_left != brace_on_right: # must be brace after if
3743 error(filename, linenum, 'readability/braces', 5,
3744 'If an else has a brace on one side, it should have it on both')
3745 elif Search(r'}\s*else[^{]*$', line) or Match(r'[^}]*else\s*{', line):
3746 error(filename, linenum, 'readability/braces', 5,
3747 'If an else has a brace on one side, it should have it on both')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003748
3749 # Likewise, an else should never have the else clause on the same line
3750 if Search(r'\belse [^\s{]', line) and not Search(r'\belse if\b', line):
3751 error(filename, linenum, 'whitespace/newline', 4,
3752 'Else clause should never be on same line as else (use 2 lines)')
3753
3754 # In the same way, a do/while should never be on one line
3755 if Match(r'\s*do [^\s{]', line):
3756 error(filename, linenum, 'whitespace/newline', 4,
3757 'do/while clauses should not be on a single line')
3758
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003759 # Check single-line if/else bodies. The style guide says 'curly braces are not
3760 # required for single-line statements'. We additionally allow multi-line,
3761 # single statements, but we reject anything with more than one semicolon in
3762 # it. This means that the first semicolon after the if should be at the end of
3763 # its line, and the line after that should have an indent level equal to or
3764 # lower than the if. We also check for ambiguous if/else nesting without
3765 # braces.
Darius Maa7d7e42022-05-13 14:54:21 +00003766 if_else_match = Search(r'\b(if\s*(?:constexpr\s*)?\(|else\b)', line)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003767 if if_else_match and not Match(r'\s*#', line):
3768 if_indent = GetIndentLevel(line)
3769 endline, endlinenum, endpos = line, linenum, if_else_match.end()
Darius Maa7d7e42022-05-13 14:54:21 +00003770 if_match = Search(r'\bif\s*(?:constexpr\s*)?\(', line)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003771 if if_match:
3772 # This could be a multiline if condition, so find the end first.
3773 pos = if_match.end() - 1
3774 (endline, endlinenum, endpos) = CloseExpression(clean_lines, linenum, pos)
3775 # Check for an opening brace, either directly after the if or on the next
3776 # line. If found, this isn't a single-statement conditional.
3777 if (not Match(r'\s*{', endline[endpos:])
3778 and not (Match(r'\s*$', endline[endpos:])
3779 and endlinenum < (len(clean_lines.elided) - 1)
3780 and Match(r'\s*{', clean_lines.elided[endlinenum + 1]))):
3781 while (endlinenum < len(clean_lines.elided)
3782 and ';' not in clean_lines.elided[endlinenum][endpos:]):
3783 endlinenum += 1
3784 endpos = 0
3785 if endlinenum < len(clean_lines.elided):
3786 endline = clean_lines.elided[endlinenum]
3787 # We allow a mix of whitespace and closing braces (e.g. for one-liner
3788 # methods) and a single \ after the semicolon (for macros)
3789 endpos = endline.find(';')
3790 if not Match(r';[\s}]*(\\?)$', endline[endpos:]):
avakulenko@google.com59146752014-08-11 20:20:55 +00003791 # Semicolon isn't the last character, there's something trailing.
3792 # Output a warning if the semicolon is not contained inside
3793 # a lambda expression.
3794 if not Match(r'^[^{};]*\[[^\[\]]*\][^{}]*\{[^{}]*\}\s*\)*[;,]\s*$',
3795 endline):
3796 error(filename, linenum, 'readability/braces', 4,
3797 'If/else bodies with multiple statements require braces')
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003798 elif endlinenum < len(clean_lines.elided) - 1:
3799 # Make sure the next line is dedented
3800 next_line = clean_lines.elided[endlinenum + 1]
3801 next_indent = GetIndentLevel(next_line)
3802 # With ambiguous nested if statements, this will error out on the
3803 # if that *doesn't* match the else, regardless of whether it's the
3804 # inner one or outer one.
3805 if (if_match and Match(r'\s*else\b', next_line)
3806 and next_indent != if_indent):
3807 error(filename, linenum, 'readability/braces', 4,
3808 'Else clause should be indented at the same level as if. '
3809 'Ambiguous nested if/else chains require braces.')
3810 elif next_indent > if_indent:
3811 error(filename, linenum, 'readability/braces', 4,
3812 'If/else bodies with multiple statements require braces')
3813
3814
3815def CheckTrailingSemicolon(filename, clean_lines, linenum, error):
3816 """Looks for redundant trailing semicolon.
3817
3818 Args:
3819 filename: The name of the current file.
3820 clean_lines: A CleansedLines instance containing the file.
3821 linenum: The number of the line to check.
3822 error: The function to call with any errors found.
3823 """
3824
3825 line = clean_lines.elided[linenum]
3826
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003827 # Block bodies should not be followed by a semicolon. Due to C++11
3828 # brace initialization, there are more places where semicolons are
Ayu Ishii09858612020-06-26 18:00:52 +00003829 # required than not, so we use an allowlist approach to check these
3830 # rather than a blocklist. These are the places where "};" should
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003831 # be replaced by just "}":
3832 # 1. Some flavor of block following closing parenthesis:
3833 # for (;;) {};
3834 # while (...) {};
3835 # switch (...) {};
3836 # Function(...) {};
3837 # if (...) {};
3838 # if (...) else if (...) {};
3839 #
3840 # 2. else block:
3841 # if (...) else {};
3842 #
3843 # 3. const member function:
3844 # Function(...) const {};
3845 #
3846 # 4. Block following some statement:
3847 # x = 42;
3848 # {};
3849 #
3850 # 5. Block at the beginning of a function:
3851 # Function(...) {
3852 # {};
3853 # }
3854 #
3855 # Note that naively checking for the preceding "{" will also match
3856 # braces inside multi-dimensional arrays, but this is fine since
3857 # that expression will not contain semicolons.
3858 #
3859 # 6. Block following another block:
3860 # while (true) {}
3861 # {};
3862 #
3863 # 7. End of namespaces:
3864 # namespace {};
3865 #
3866 # These semicolons seems far more common than other kinds of
3867 # redundant semicolons, possibly due to people converting classes
3868 # to namespaces. For now we do not warn for this case.
3869 #
3870 # Try matching case 1 first.
3871 match = Match(r'^(.*\)\s*)\{', line)
3872 if match:
3873 # Matched closing parenthesis (case 1). Check the token before the
3874 # matching opening parenthesis, and don't warn if it looks like a
3875 # macro. This avoids these false positives:
3876 # - macro that defines a base class
3877 # - multi-line macro that defines a base class
3878 # - macro that defines the whole class-head
3879 #
3880 # But we still issue warnings for macros that we know are safe to
3881 # warn, specifically:
3882 # - TEST, TEST_F, TEST_P, MATCHER, MATCHER_P
3883 # - TYPED_TEST
3884 # - INTERFACE_DEF
3885 # - EXCLUSIVE_LOCKS_REQUIRED, SHARED_LOCKS_REQUIRED, LOCKS_EXCLUDED:
3886 #
Ayu Ishii09858612020-06-26 18:00:52 +00003887 # We implement an allowlist of safe macros instead of a blocklist of
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003888 # unsafe macros, even though the latter appears less frequently in
Ayu Ishii09858612020-06-26 18:00:52 +00003889 # google code and would have been easier to implement. This is because
3890 # the downside for getting the allowlist wrong means some extra
3891 # semicolons, while the downside for getting the blocklist wrong
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003892 # would result in compile errors.
3893 #
avakulenko@google.com255f2be2014-12-05 22:19:55 +00003894 # In addition to macros, we also don't want to warn on
3895 # - Compound literals
3896 # - Lambdas
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003897 # - alignas specifier with anonymous structs
3898 # - decltype
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003899 closing_brace_pos = match.group(1).rfind(')')
3900 opening_parenthesis = ReverseCloseExpression(
3901 clean_lines, linenum, closing_brace_pos)
3902 if opening_parenthesis[2] > -1:
3903 line_prefix = opening_parenthesis[0][0:opening_parenthesis[2]]
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003904 macro = Search(r'\b([A-Z_][A-Z0-9_]*)\s*$', line_prefix)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003905 func = Match(r'^(.*\])\s*$', line_prefix)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003906 if ((macro and
3907 macro.group(1) not in (
3908 'TEST', 'TEST_F', 'MATCHER', 'MATCHER_P', 'TYPED_TEST',
3909 'EXCLUSIVE_LOCKS_REQUIRED', 'SHARED_LOCKS_REQUIRED',
3910 'LOCKS_EXCLUDED', 'INTERFACE_DEF')) or
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003911 (func and not Search(r'\boperator\s*\[\s*\]', func.group(1))) or
avakulenko@google.com255f2be2014-12-05 22:19:55 +00003912 Search(r'\b(?:struct|union)\s+alignas\s*$', line_prefix) or
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003913 Search(r'\bdecltype$', line_prefix) or
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003914 Search(r'\s+=\s*$', line_prefix)):
3915 match = None
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003916 if (match and
3917 opening_parenthesis[1] > 1 and
3918 Search(r'\]\s*$', clean_lines.elided[opening_parenthesis[1] - 1])):
3919 # Multi-line lambda-expression
3920 match = None
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003921
3922 else:
3923 # Try matching cases 2-3.
3924 match = Match(r'^(.*(?:else|\)\s*const)\s*)\{', line)
3925 if not match:
3926 # Try matching cases 4-6. These are always matched on separate lines.
3927 #
3928 # Note that we can't simply concatenate the previous line to the
3929 # current line and do a single match, otherwise we may output
3930 # duplicate warnings for the blank line case:
3931 # if (cond) {
3932 # // blank line
3933 # }
3934 prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
3935 if prevline and Search(r'[;{}]\s*$', prevline):
3936 match = Match(r'^(\s*)\{', line)
3937
3938 # Check matching closing brace
3939 if match:
3940 (endline, endlinenum, endpos) = CloseExpression(
3941 clean_lines, linenum, len(match.group(1)))
3942 if endpos > -1 and Match(r'^\s*;', endline[endpos:]):
3943 # Current {} pair is eligible for semicolon check, and we have found
3944 # the redundant semicolon, output warning here.
3945 #
3946 # Note: because we are scanning forward for opening braces, and
3947 # outputting warnings for the matching closing brace, if there are
3948 # nested blocks with trailing semicolons, we will get the error
3949 # messages in reversed order.
3950 error(filename, endlinenum, 'readability/braces', 4,
3951 "You don't need a ; after a }")
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003952
3953
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003954def CheckEmptyBlockBody(filename, clean_lines, linenum, error):
3955 """Look for empty loop/conditional body with only a single semicolon.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003956
3957 Args:
3958 filename: The name of the current file.
3959 clean_lines: A CleansedLines instance containing the file.
3960 linenum: The number of the line to check.
3961 error: The function to call with any errors found.
3962 """
3963
3964 # Search for loop keywords at the beginning of the line. Because only
3965 # whitespaces are allowed before the keywords, this will also ignore most
3966 # do-while-loops, since those lines should start with closing brace.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003967 #
3968 # We also check "if" blocks here, since an empty conditional block
3969 # is likely an error.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003970 line = clean_lines.elided[linenum]
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003971 matched = Match(r'\s*(for|while|if)\s*\(', line)
3972 if matched:
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003973 # Find the end of the conditional expression.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003974 (end_line, end_linenum, end_pos) = CloseExpression(
3975 clean_lines, linenum, line.find('('))
3976
3977 # Output warning if what follows the condition expression is a semicolon.
3978 # No warning for all other cases, including whitespace or newline, since we
3979 # have a separate check for semicolons preceded by whitespace.
3980 if end_pos >= 0 and Match(r';', end_line[end_pos:]):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003981 if matched.group(1) == 'if':
3982 error(filename, end_linenum, 'whitespace/empty_conditional_body', 5,
3983 'Empty conditional bodies should use {}')
3984 else:
3985 error(filename, end_linenum, 'whitespace/empty_loop_body', 5,
3986 'Empty loop bodies should use {} or continue')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003987
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003988 # Check for if statements that have completely empty bodies (no comments)
3989 # and no else clauses.
3990 if end_pos >= 0 and matched.group(1) == 'if':
3991 # Find the position of the opening { for the if statement.
3992 # Return without logging an error if it has no brackets.
3993 opening_linenum = end_linenum
3994 opening_line_fragment = end_line[end_pos:]
3995 # Loop until EOF or find anything that's not whitespace or opening {.
3996 while not Search(r'^\s*\{', opening_line_fragment):
3997 if Search(r'^(?!\s*$)', opening_line_fragment):
3998 # Conditional has no brackets.
3999 return
4000 opening_linenum += 1
4001 if opening_linenum == len(clean_lines.elided):
4002 # Couldn't find conditional's opening { or any code before EOF.
4003 return
4004 opening_line_fragment = clean_lines.elided[opening_linenum]
4005 # Set opening_line (opening_line_fragment may not be entire opening line).
4006 opening_line = clean_lines.elided[opening_linenum]
4007
4008 # Find the position of the closing }.
4009 opening_pos = opening_line_fragment.find('{')
4010 if opening_linenum == end_linenum:
4011 # We need to make opening_pos relative to the start of the entire line.
4012 opening_pos += end_pos
4013 (closing_line, closing_linenum, closing_pos) = CloseExpression(
4014 clean_lines, opening_linenum, opening_pos)
4015 if closing_pos < 0:
4016 return
4017
4018 # Now construct the body of the conditional. This consists of the portion
4019 # of the opening line after the {, all lines until the closing line,
4020 # and the portion of the closing line before the }.
4021 if (clean_lines.raw_lines[opening_linenum] !=
4022 CleanseComments(clean_lines.raw_lines[opening_linenum])):
4023 # Opening line ends with a comment, so conditional isn't empty.
4024 return
4025 if closing_linenum > opening_linenum:
4026 # Opening line after the {. Ignore comments here since we checked above.
4027 body = list(opening_line[opening_pos+1:])
4028 # All lines until closing line, excluding closing line, with comments.
4029 body.extend(clean_lines.raw_lines[opening_linenum+1:closing_linenum])
4030 # Closing line before the }. Won't (and can't) have comments.
4031 body.append(clean_lines.elided[closing_linenum][:closing_pos-1])
4032 body = '\n'.join(body)
4033 else:
4034 # If statement has brackets and fits on a single line.
4035 body = opening_line[opening_pos+1:closing_pos-1]
4036
4037 # Check if the body is empty
4038 if not _EMPTY_CONDITIONAL_BODY_PATTERN.search(body):
4039 return
4040 # The body is empty. Now make sure there's not an else clause.
4041 current_linenum = closing_linenum
4042 current_line_fragment = closing_line[closing_pos:]
4043 # Loop until EOF or find anything that's not whitespace or else clause.
4044 while Search(r'^\s*$|^(?=\s*else)', current_line_fragment):
4045 if Search(r'^(?=\s*else)', current_line_fragment):
4046 # Found an else clause, so don't log an error.
4047 return
4048 current_linenum += 1
4049 if current_linenum == len(clean_lines.elided):
4050 break
4051 current_line_fragment = clean_lines.elided[current_linenum]
4052
4053 # The body is empty and there's no else clause until EOF or other code.
4054 error(filename, end_linenum, 'whitespace/empty_if_body', 4,
4055 ('If statement had no body and no else clause'))
4056
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004057
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004058def FindCheckMacro(line):
4059 """Find a replaceable CHECK-like macro.
4060
4061 Args:
4062 line: line to search on.
4063 Returns:
4064 (macro name, start position), or (None, -1) if no replaceable
4065 macro is found.
4066 """
4067 for macro in _CHECK_MACROS:
4068 i = line.find(macro)
4069 if i >= 0:
4070 # Find opening parenthesis. Do a regular expression match here
4071 # to make sure that we are matching the expected CHECK macro, as
4072 # opposed to some other macro that happens to contain the CHECK
4073 # substring.
4074 matched = Match(r'^(.*\b' + macro + r'\s*)\(', line)
4075 if not matched:
4076 continue
4077 return (macro, len(matched.group(1)))
4078 return (None, -1)
4079
4080
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004081def CheckCheck(filename, clean_lines, linenum, error):
4082 """Checks the use of CHECK and EXPECT macros.
4083
4084 Args:
4085 filename: The name of the current file.
4086 clean_lines: A CleansedLines instance containing the file.
4087 linenum: The number of the line to check.
4088 error: The function to call with any errors found.
4089 """
4090
4091 # Decide the set of replacement macros that should be suggested
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004092 lines = clean_lines.elided
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004093 (check_macro, start_pos) = FindCheckMacro(lines[linenum])
4094 if not check_macro:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004095 return
4096
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004097 # Find end of the boolean expression by matching parentheses
4098 (last_line, end_line, end_pos) = CloseExpression(
4099 clean_lines, linenum, start_pos)
4100 if end_pos < 0:
4101 return
avakulenko@google.com59146752014-08-11 20:20:55 +00004102
4103 # If the check macro is followed by something other than a
4104 # semicolon, assume users will log their own custom error messages
4105 # and don't suggest any replacements.
4106 if not Match(r'\s*;', last_line[end_pos:]):
4107 return
4108
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004109 if linenum == end_line:
4110 expression = lines[linenum][start_pos + 1:end_pos - 1]
4111 else:
4112 expression = lines[linenum][start_pos + 1:]
Edward Lemur6d31ed52019-12-02 23:00:00 +00004113 for i in range(linenum + 1, end_line):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004114 expression += lines[i]
4115 expression += last_line[0:end_pos - 1]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004116
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004117 # Parse expression so that we can take parentheses into account.
4118 # This avoids false positives for inputs like "CHECK((a < 4) == b)",
4119 # which is not replaceable by CHECK_LE.
4120 lhs = ''
4121 rhs = ''
4122 operator = None
4123 while expression:
4124 matched = Match(r'^\s*(<<|<<=|>>|>>=|->\*|->|&&|\|\||'
4125 r'==|!=|>=|>|<=|<|\()(.*)$', expression)
4126 if matched:
4127 token = matched.group(1)
4128 if token == '(':
4129 # Parenthesized operand
4130 expression = matched.group(2)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004131 (end, _) = FindEndOfExpressionInLine(expression, 0, ['('])
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004132 if end < 0:
4133 return # Unmatched parenthesis
4134 lhs += '(' + expression[0:end]
4135 expression = expression[end:]
4136 elif token in ('&&', '||'):
4137 # Logical and/or operators. This means the expression
4138 # contains more than one term, for example:
4139 # CHECK(42 < a && a < b);
4140 #
4141 # These are not replaceable with CHECK_LE, so bail out early.
4142 return
4143 elif token in ('<<', '<<=', '>>', '>>=', '->*', '->'):
4144 # Non-relational operator
4145 lhs += token
4146 expression = matched.group(2)
4147 else:
4148 # Relational operator
4149 operator = token
4150 rhs = matched.group(2)
4151 break
4152 else:
4153 # Unparenthesized operand. Instead of appending to lhs one character
4154 # at a time, we do another regular expression match to consume several
4155 # characters at once if possible. Trivial benchmark shows that this
4156 # is more efficient when the operands are longer than a single
4157 # character, which is generally the case.
4158 matched = Match(r'^([^-=!<>()&|]+)(.*)$', expression)
4159 if not matched:
4160 matched = Match(r'^(\s*\S)(.*)$', expression)
4161 if not matched:
4162 break
4163 lhs += matched.group(1)
4164 expression = matched.group(2)
4165
4166 # Only apply checks if we got all parts of the boolean expression
4167 if not (lhs and operator and rhs):
4168 return
4169
4170 # Check that rhs do not contain logical operators. We already know
4171 # that lhs is fine since the loop above parses out && and ||.
4172 if rhs.find('&&') > -1 or rhs.find('||') > -1:
4173 return
4174
4175 # At least one of the operands must be a constant literal. This is
4176 # to avoid suggesting replacements for unprintable things like
4177 # CHECK(variable != iterator)
4178 #
4179 # The following pattern matches decimal, hex integers, strings, and
4180 # characters (in that order).
4181 lhs = lhs.strip()
4182 rhs = rhs.strip()
4183 match_constant = r'^([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')$'
4184 if Match(match_constant, lhs) or Match(match_constant, rhs):
4185 # Note: since we know both lhs and rhs, we can provide a more
4186 # descriptive error message like:
4187 # Consider using CHECK_EQ(x, 42) instead of CHECK(x == 42)
4188 # Instead of:
4189 # Consider using CHECK_EQ instead of CHECK(a == b)
4190 #
4191 # We are still keeping the less descriptive message because if lhs
4192 # or rhs gets long, the error message might become unreadable.
4193 error(filename, linenum, 'readability/check', 2,
4194 'Consider using %s instead of %s(a %s b)' % (
4195 _CHECK_REPLACEMENT[check_macro][operator],
4196 check_macro, operator))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004197
4198
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004199def CheckAltTokens(filename, clean_lines, linenum, error):
4200 """Check alternative keywords being used in boolean expressions.
4201
4202 Args:
4203 filename: The name of the current file.
4204 clean_lines: A CleansedLines instance containing the file.
4205 linenum: The number of the line to check.
4206 error: The function to call with any errors found.
4207 """
4208 line = clean_lines.elided[linenum]
4209
4210 # Avoid preprocessor lines
4211 if Match(r'^\s*#', line):
4212 return
4213
4214 # Last ditch effort to avoid multi-line comments. This will not help
4215 # if the comment started before the current line or ended after the
4216 # current line, but it catches most of the false positives. At least,
4217 # it provides a way to workaround this warning for people who use
4218 # multi-line comments in preprocessor macros.
4219 #
4220 # TODO(unknown): remove this once cpplint has better support for
4221 # multi-line comments.
4222 if line.find('/*') >= 0 or line.find('*/') >= 0:
4223 return
4224
4225 for match in _ALT_TOKEN_REPLACEMENT_PATTERN.finditer(line):
4226 error(filename, linenum, 'readability/alt_tokens', 2,
4227 'Use operator %s instead of %s' % (
4228 _ALT_TOKEN_REPLACEMENT[match.group(1)], match.group(1)))
4229
4230
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004231def GetLineWidth(line):
4232 """Determines the width of the line in column positions.
4233
4234 Args:
4235 line: A string, which may be a Unicode string.
4236
4237 Returns:
4238 The width of the line in column positions, accounting for Unicode
4239 combining characters and wide characters.
4240 """
Edward Lemur6d31ed52019-12-02 23:00:00 +00004241 if sys.version_info == 2 and isinstance(line, unicode):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004242 width = 0
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004243 for uc in unicodedata.normalize('NFC', line):
4244 if unicodedata.east_asian_width(uc) in ('W', 'F'):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004245 width += 2
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004246 elif not unicodedata.combining(uc):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004247 width += 1
4248 return width
4249 else:
4250 return len(line)
4251
4252
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004253def CheckStyle(filename, clean_lines, linenum, file_extension, nesting_state,
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004254 error):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004255 """Checks rules from the 'C++ style rules' section of cppguide.html.
4256
4257 Most of these rules are hard to test (naming, comment style), but we
4258 do what we can. In particular we check for 2-space indents, line lengths,
4259 tab usage, spaces inside code, etc.
4260
4261 Args:
4262 filename: The name of the current file.
4263 clean_lines: A CleansedLines instance containing the file.
4264 linenum: The number of the line to check.
4265 file_extension: The extension (without the dot) of the filename.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004266 nesting_state: A NestingState instance which maintains information about
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004267 the current stack of nested blocks being parsed.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004268 error: The function to call with any errors found.
4269 """
4270
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004271 # Don't use "elided" lines here, otherwise we can't check commented lines.
4272 # Don't want to use "raw" either, because we don't want to check inside C++11
4273 # raw strings,
4274 raw_lines = clean_lines.lines_without_raw_strings
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004275 line = raw_lines[linenum]
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004276 prev = raw_lines[linenum - 1] if linenum > 0 else ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004277
4278 if line.find('\t') != -1:
4279 error(filename, linenum, 'whitespace/tab', 1,
4280 'Tab found; better to use spaces')
4281
4282 # One or three blank spaces at the beginning of the line is weird; it's
4283 # hard to reconcile that with 2-space indents.
4284 # NOTE: here are the conditions rob pike used for his tests. Mine aren't
4285 # as sophisticated, but it may be worth becoming so: RLENGTH==initial_spaces
4286 # if(RLENGTH > 20) complain = 0;
4287 # if(match($0, " +(error|private|public|protected):")) complain = 0;
4288 # if(match(prev, "&& *$")) complain = 0;
4289 # if(match(prev, "\\|\\| *$")) complain = 0;
4290 # if(match(prev, "[\",=><] *$")) complain = 0;
4291 # if(match($0, " <<")) complain = 0;
4292 # if(match(prev, " +for \\(")) complain = 0;
4293 # if(prevodd && match(prevprev, " +for \\(")) complain = 0;
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004294 scope_or_label_pattern = r'\s*\w+\s*:\s*\\?$'
4295 classinfo = nesting_state.InnermostClass()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004296 initial_spaces = 0
4297 cleansed_line = clean_lines.elided[linenum]
4298 while initial_spaces < len(line) and line[initial_spaces] == ' ':
4299 initial_spaces += 1
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004300 # There are certain situations we allow one space, notably for
4301 # section labels, and also lines containing multi-line raw strings.
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004302 # We also don't check for lines that look like continuation lines
4303 # (of lines ending in double quotes, commas, equals, or angle brackets)
4304 # because the rules for how to indent those are non-trivial.
4305 if (not Search(r'[",=><] *$', prev) and
4306 (initial_spaces == 1 or initial_spaces == 3) and
4307 not Match(scope_or_label_pattern, cleansed_line) and
4308 not (clean_lines.raw_lines[linenum] != line and
4309 Match(r'^\s*""', line))):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004310 error(filename, linenum, 'whitespace/indent', 3,
4311 'Weird number of spaces at line-start. '
4312 'Are you using a 2-space indent?')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004313
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004314 if line and line[-1].isspace():
4315 error(filename, linenum, 'whitespace/end_of_line', 4,
4316 'Line ends in whitespace. Consider deleting these extra spaces.')
4317
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004318 # Check if the line is a header guard.
4319 is_header_guard = False
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00004320 if file_extension == 'h':
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004321 cppvar = GetHeaderGuardCPPVariable(filename)
4322 if (line.startswith('#ifndef %s' % cppvar) or
4323 line.startswith('#define %s' % cppvar) or
4324 line.startswith('#endif // %s' % cppvar)):
4325 is_header_guard = True
4326 # #include lines and header guards can be long, since there's no clean way to
4327 # split them.
erg@google.com6317a9c2009-06-25 00:28:19 +00004328 #
4329 # URLs can be long too. It's possible to split these, but it makes them
4330 # harder to cut&paste.
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004331 #
4332 # The "$Id:...$" comment may also get very long without it being the
4333 # developers fault.
erg@google.com6317a9c2009-06-25 00:28:19 +00004334 if (not line.startswith('#include') and not is_header_guard and
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004335 not Match(r'^\s*//.*http(s?)://\S*$', line) and
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004336 not Match(r'^\s*//\s*[^\s]*$', line) and
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004337 not Match(r'^// \$Id:.*#[0-9]+ \$$', line)):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004338 line_width = GetLineWidth(line)
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004339 if line_width > _line_length:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004340 error(filename, linenum, 'whitespace/line_length', 2,
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004341 'Lines should be <= %i characters long' % _line_length)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004342
4343 if (cleansed_line.count(';') > 1 and
4344 # for loops are allowed two ;'s (and may run over two lines).
4345 cleansed_line.find('for') == -1 and
4346 (GetPreviousNonBlankLine(clean_lines, linenum)[0].find('for') == -1 or
4347 GetPreviousNonBlankLine(clean_lines, linenum)[0].find(';') != -1) and
4348 # It's ok to have many commands in a switch case that fits in 1 line
4349 not ((cleansed_line.find('case ') != -1 or
4350 cleansed_line.find('default:') != -1) and
4351 cleansed_line.find('break;') != -1)):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004352 error(filename, linenum, 'whitespace/newline', 0,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004353 'More than one command on the same line')
4354
4355 # Some more style checks
4356 CheckBraces(filename, clean_lines, linenum, error)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004357 CheckTrailingSemicolon(filename, clean_lines, linenum, error)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004358 CheckEmptyBlockBody(filename, clean_lines, linenum, error)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004359 CheckSpacing(filename, clean_lines, linenum, nesting_state, error)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004360 CheckOperatorSpacing(filename, clean_lines, linenum, error)
4361 CheckParenthesisSpacing(filename, clean_lines, linenum, error)
4362 CheckCommaSpacing(filename, clean_lines, linenum, error)
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004363 CheckBracesSpacing(filename, clean_lines, linenum, nesting_state, error)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004364 CheckSpacingForFunctionCall(filename, clean_lines, linenum, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004365 CheckCheck(filename, clean_lines, linenum, error)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004366 CheckAltTokens(filename, clean_lines, linenum, error)
4367 classinfo = nesting_state.InnermostClass()
4368 if classinfo:
4369 CheckSectionSpacing(filename, clean_lines, classinfo, linenum, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004370
4371
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004372_RE_PATTERN_INCLUDE = re.compile(r'^\s*#\s*include\s*([<"])([^>"]*)[>"].*$')
4373# Matches the first component of a filename delimited by -s and _s. That is:
4374# _RE_FIRST_COMPONENT.match('foo').group(0) == 'foo'
4375# _RE_FIRST_COMPONENT.match('foo.cc').group(0) == 'foo'
4376# _RE_FIRST_COMPONENT.match('foo-bar_baz.cc').group(0) == 'foo'
4377# _RE_FIRST_COMPONENT.match('foo_bar-baz.cc').group(0) == 'foo'
4378_RE_FIRST_COMPONENT = re.compile(r'^[^-_.]+')
4379
4380
4381def _DropCommonSuffixes(filename):
4382 """Drops common suffixes like _test.cc or -inl.h from filename.
4383
4384 For example:
4385 >>> _DropCommonSuffixes('foo/foo-inl.h')
4386 'foo/foo'
4387 >>> _DropCommonSuffixes('foo/bar/foo.cc')
4388 'foo/bar/foo'
4389 >>> _DropCommonSuffixes('foo/foo_internal.h')
4390 'foo/foo'
4391 >>> _DropCommonSuffixes('foo/foo_unusualinternal.h')
4392 'foo/foo_unusualinternal'
4393
4394 Args:
4395 filename: The input filename.
4396
4397 Returns:
4398 The filename with the common suffix removed.
4399 """
4400 for suffix in ('test.cc', 'regtest.cc', 'unittest.cc',
4401 'inl.h', 'impl.h', 'internal.h'):
4402 if (filename.endswith(suffix) and len(filename) > len(suffix) and
4403 filename[-len(suffix) - 1] in ('-', '_')):
4404 return filename[:-len(suffix) - 1]
4405 return os.path.splitext(filename)[0]
4406
4407
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004408def _ClassifyInclude(fileinfo, include, is_system):
4409 """Figures out what kind of header 'include' is.
4410
4411 Args:
4412 fileinfo: The current file cpplint is running over. A FileInfo instance.
4413 include: The path to a #included file.
4414 is_system: True if the #include used <> rather than "".
4415
4416 Returns:
4417 One of the _XXX_HEADER constants.
4418
4419 For example:
4420 >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'stdio.h', True)
4421 _C_SYS_HEADER
4422 >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'string', True)
4423 _CPP_SYS_HEADER
4424 >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', False)
4425 _LIKELY_MY_HEADER
4426 >>> _ClassifyInclude(FileInfo('foo/foo_unknown_extension.cc'),
4427 ... 'bar/foo_other_ext.h', False)
4428 _POSSIBLE_MY_HEADER
4429 >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/bar.h', False)
4430 _OTHER_HEADER
4431 """
4432 # This is a list of all standard c++ header files, except
4433 # those already checked for above.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004434 is_cpp_h = include in _CPP_HEADERS
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004435
4436 if is_system:
4437 if is_cpp_h:
4438 return _CPP_SYS_HEADER
4439 else:
4440 return _C_SYS_HEADER
4441
4442 # If the target file and the include we're checking share a
4443 # basename when we drop common extensions, and the include
4444 # lives in . , then it's likely to be owned by the target file.
4445 target_dir, target_base = (
4446 os.path.split(_DropCommonSuffixes(fileinfo.RepositoryName())))
4447 include_dir, include_base = os.path.split(_DropCommonSuffixes(include))
4448 if target_base == include_base and (
4449 include_dir == target_dir or
4450 include_dir == os.path.normpath(target_dir + '/../public')):
4451 return _LIKELY_MY_HEADER
4452
4453 # If the target and include share some initial basename
4454 # component, it's possible the target is implementing the
4455 # include, so it's allowed to be first, but we'll never
4456 # complain if it's not there.
4457 target_first_component = _RE_FIRST_COMPONENT.match(target_base)
4458 include_first_component = _RE_FIRST_COMPONENT.match(include_base)
4459 if (target_first_component and include_first_component and
4460 target_first_component.group(0) ==
4461 include_first_component.group(0)):
4462 return _POSSIBLE_MY_HEADER
4463
4464 return _OTHER_HEADER
4465
4466
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004467
erg@google.com6317a9c2009-06-25 00:28:19 +00004468def CheckIncludeLine(filename, clean_lines, linenum, include_state, error):
4469 """Check rules that are applicable to #include lines.
4470
4471 Strings on #include lines are NOT removed from elided line, to make
4472 certain tasks easier. However, to prevent false positives, checks
4473 applicable to #include lines in CheckLanguage must be put here.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004474
4475 Args:
4476 filename: The name of the current file.
4477 clean_lines: A CleansedLines instance containing the file.
4478 linenum: The number of the line to check.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004479 include_state: An _IncludeState instance in which the headers are inserted.
4480 error: The function to call with any errors found.
4481 """
4482 fileinfo = FileInfo(filename)
erg@google.com6317a9c2009-06-25 00:28:19 +00004483 line = clean_lines.lines[linenum]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004484
4485 # "include" should use the new style "foo/bar.h" instead of just "bar.h"
avakulenko@google.com59146752014-08-11 20:20:55 +00004486 # Only do this check if the included header follows google naming
4487 # conventions. If not, assume that it's a 3rd party API that
4488 # requires special include conventions.
4489 #
4490 # We also make an exception for Lua headers, which follow google
4491 # naming convention but not the include convention.
4492 match = Match(r'#include\s*"([^/]+\.h)"', line)
4493 if match and not _THIRD_PARTY_HEADERS_PATTERN.match(match.group(1)):
Fletcher Woodruff11b34152020-04-23 21:21:40 +00004494 error(filename, linenum, 'build/include_directory', 4,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004495 'Include the directory when naming .h files')
4496
4497 # we shouldn't include a file more than once. actually, there are a
4498 # handful of instances where doing so is okay, but in general it's
4499 # not.
erg@google.com6317a9c2009-06-25 00:28:19 +00004500 match = _RE_PATTERN_INCLUDE.search(line)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004501 if match:
4502 include = match.group(2)
4503 is_system = (match.group(1) == '<')
avakulenko@google.com59146752014-08-11 20:20:55 +00004504 duplicate_line = include_state.FindHeader(include)
4505 if duplicate_line >= 0:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004506 error(filename, linenum, 'build/include', 4,
4507 '"%s" already included at %s:%s' %
avakulenko@google.com59146752014-08-11 20:20:55 +00004508 (include, filename, duplicate_line))
avakulenko@google.com255f2be2014-12-05 22:19:55 +00004509 elif (include.endswith('.cc') and
4510 os.path.dirname(fileinfo.RepositoryName()) != os.path.dirname(include)):
4511 error(filename, linenum, 'build/include', 4,
4512 'Do not include .cc files from other packages')
avakulenko@google.com59146752014-08-11 20:20:55 +00004513 elif not _THIRD_PARTY_HEADERS_PATTERN.match(include):
4514 include_state.include_list[-1].append((include, linenum))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004515
4516 # We want to ensure that headers appear in the right order:
4517 # 1) for foo.cc, foo.h (preferred location)
4518 # 2) c system files
4519 # 3) cpp system files
4520 # 4) for foo.cc, foo.h (deprecated location)
4521 # 5) other google headers
4522 #
4523 # We classify each include statement as one of those 5 types
4524 # using a number of techniques. The include_state object keeps
4525 # track of the highest type seen, and complains if we see a
4526 # lower type after that.
4527 error_message = include_state.CheckNextIncludeOrder(
4528 _ClassifyInclude(fileinfo, include, is_system))
4529 if error_message:
4530 error(filename, linenum, 'build/include_order', 4,
4531 '%s. Should be: %s.h, c system, c++ system, other.' %
4532 (error_message, fileinfo.BaseName()))
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004533 canonical_include = include_state.CanonicalizeAlphabeticalOrder(include)
4534 if not include_state.IsInAlphabeticalOrder(
4535 clean_lines, linenum, canonical_include):
erg@google.com26970fa2009-11-17 18:07:32 +00004536 error(filename, linenum, 'build/include_alpha', 4,
4537 'Include "%s" not in alphabetical order' % include)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004538 include_state.SetLastHeader(canonical_include)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004539
erg@google.com6317a9c2009-06-25 00:28:19 +00004540
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004541
4542def _GetTextInside(text, start_pattern):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004543 r"""Retrieves all the text between matching open and close parentheses.
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004544
4545 Given a string of lines and a regular expression string, retrieve all the text
4546 following the expression and between opening punctuation symbols like
4547 (, [, or {, and the matching close-punctuation symbol. This properly nested
4548 occurrences of the punctuations, so for the text like
4549 printf(a(), b(c()));
4550 a call to _GetTextInside(text, r'printf\(') will return 'a(), b(c())'.
4551 start_pattern must match string having an open punctuation symbol at the end.
4552
4553 Args:
4554 text: The lines to extract text. Its comments and strings must be elided.
4555 It can be single line and can span multiple lines.
4556 start_pattern: The regexp string indicating where to start extracting
4557 the text.
4558 Returns:
4559 The extracted text.
4560 None if either the opening string or ending punctuation could not be found.
4561 """
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004562 # TODO(unknown): Audit cpplint.py to see what places could be profitably
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004563 # rewritten to use _GetTextInside (and use inferior regexp matching today).
4564
4565 # Give opening punctuations to get the matching close-punctuations.
4566 matching_punctuation = {'(': ')', '{': '}', '[': ']'}
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +00004567 closing_punctuation = set(matching_punctuation.values())
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004568
4569 # Find the position to start extracting text.
4570 match = re.search(start_pattern, text, re.M)
4571 if not match: # start_pattern not found in text.
4572 return None
4573 start_position = match.end(0)
4574
4575 assert start_position > 0, (
4576 'start_pattern must ends with an opening punctuation.')
4577 assert text[start_position - 1] in matching_punctuation, (
4578 'start_pattern must ends with an opening punctuation.')
4579 # Stack of closing punctuations we expect to have in text after position.
4580 punctuation_stack = [matching_punctuation[text[start_position - 1]]]
4581 position = start_position
4582 while punctuation_stack and position < len(text):
4583 if text[position] == punctuation_stack[-1]:
4584 punctuation_stack.pop()
4585 elif text[position] in closing_punctuation:
4586 # A closing punctuation without matching opening punctuations.
4587 return None
4588 elif text[position] in matching_punctuation:
4589 punctuation_stack.append(matching_punctuation[text[position]])
4590 position += 1
4591 if punctuation_stack:
4592 # Opening punctuations left without matching close-punctuations.
4593 return None
4594 # punctuations match.
4595 return text[start_position:position - 1]
4596
4597
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004598# Patterns for matching call-by-reference parameters.
4599#
4600# Supports nested templates up to 2 levels deep using this messy pattern:
4601# < (?: < (?: < [^<>]*
4602# >
4603# | [^<>] )*
4604# >
4605# | [^<>] )*
4606# >
4607_RE_PATTERN_IDENT = r'[_a-zA-Z]\w*' # =~ [[:alpha:]][[:alnum:]]*
4608_RE_PATTERN_TYPE = (
4609 r'(?:const\s+)?(?:typename\s+|class\s+|struct\s+|union\s+|enum\s+)?'
4610 r'(?:\w|'
4611 r'\s*<(?:<(?:<[^<>]*>|[^<>])*>|[^<>])*>|'
4612 r'::)+')
4613# A call-by-reference parameter ends with '& identifier'.
4614_RE_PATTERN_REF_PARAM = re.compile(
4615 r'(' + _RE_PATTERN_TYPE + r'(?:\s*(?:\bconst\b|[*]))*\s*'
4616 r'&\s*' + _RE_PATTERN_IDENT + r')\s*(?:=[^,()]+)?[,)]')
4617# A call-by-const-reference parameter either ends with 'const& identifier'
4618# or looks like 'const type& identifier' when 'type' is atomic.
4619_RE_PATTERN_CONST_REF_PARAM = (
4620 r'(?:.*\s*\bconst\s*&\s*' + _RE_PATTERN_IDENT +
4621 r'|const\s+' + _RE_PATTERN_TYPE + r'\s*&\s*' + _RE_PATTERN_IDENT + r')')
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004622# Stream types.
4623_RE_PATTERN_REF_STREAM_PARAM = (
4624 r'(?:.*stream\s*&\s*' + _RE_PATTERN_IDENT + r')')
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004625
4626
4627def CheckLanguage(filename, clean_lines, linenum, file_extension,
4628 include_state, nesting_state, error):
erg@google.com6317a9c2009-06-25 00:28:19 +00004629 """Checks rules from the 'C++ language rules' section of cppguide.html.
4630
4631 Some of these rules are hard to test (function overloading, using
4632 uint32 inappropriately), but we do the best we can.
4633
4634 Args:
4635 filename: The name of the current file.
4636 clean_lines: A CleansedLines instance containing the file.
4637 linenum: The number of the line to check.
4638 file_extension: The extension (without the dot) of the filename.
4639 include_state: An _IncludeState instance in which the headers are inserted.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004640 nesting_state: A NestingState instance which maintains information about
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004641 the current stack of nested blocks being parsed.
erg@google.com6317a9c2009-06-25 00:28:19 +00004642 error: The function to call with any errors found.
4643 """
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004644 # If the line is empty or consists of entirely a comment, no need to
4645 # check it.
4646 line = clean_lines.elided[linenum]
4647 if not line:
4648 return
4649
erg@google.com6317a9c2009-06-25 00:28:19 +00004650 match = _RE_PATTERN_INCLUDE.search(line)
4651 if match:
4652 CheckIncludeLine(filename, clean_lines, linenum, include_state, error)
4653 return
4654
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004655 # Reset include state across preprocessor directives. This is meant
4656 # to silence warnings for conditional includes.
avakulenko@google.com59146752014-08-11 20:20:55 +00004657 match = Match(r'^\s*#\s*(if|ifdef|ifndef|elif|else|endif)\b', line)
4658 if match:
4659 include_state.ResetSection(match.group(1))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004660
4661 # Make Windows paths like Unix.
4662 fullname = os.path.abspath(filename).replace('\\', '/')
skym@chromium.org3990c412016-02-05 20:55:12 +00004663
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004664 # Perform other checks now that we are sure that this is not an include line
4665 CheckCasts(filename, clean_lines, linenum, error)
4666 CheckGlobalStatic(filename, clean_lines, linenum, error)
4667 CheckPrintf(filename, clean_lines, linenum, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004668
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00004669 if file_extension == 'h':
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004670 # TODO(unknown): check that 1-arg constructors are explicit.
4671 # How to tell it's a constructor?
4672 # (handled in CheckForNonStandardConstructs for now)
avakulenko@google.com59146752014-08-11 20:20:55 +00004673 # TODO(unknown): check that classes declare or disable copy/assign
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004674 # (level 1 error)
4675 pass
4676
4677 # Check if people are using the verboten C basic types. The only exception
4678 # we regularly allow is "unsigned short port" for port.
4679 if Search(r'\bshort port\b', line):
4680 if not Search(r'\bunsigned short port\b', line):
4681 error(filename, linenum, 'runtime/int', 4,
4682 'Use "unsigned short" for ports, not "short"')
4683 else:
4684 match = Search(r'\b(short|long(?! +double)|long long)\b', line)
4685 if match:
4686 error(filename, linenum, 'runtime/int', 4,
4687 'Use int16/int64/etc, rather than the C type %s' % match.group(1))
4688
erg@google.com26970fa2009-11-17 18:07:32 +00004689 # Check if some verboten operator overloading is going on
4690 # TODO(unknown): catch out-of-line unary operator&:
4691 # class X {};
4692 # int operator&(const X& x) { return 42; } // unary operator&
4693 # The trick is it's hard to tell apart from binary operator&:
4694 # class Y { int operator&(const Y& x) { return 23; } }; // binary operator&
4695 if Search(r'\boperator\s*&\s*\(\s*\)', line):
4696 error(filename, linenum, 'runtime/operator', 4,
4697 'Unary operator& is dangerous. Do not use it.')
4698
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004699 # Check for suspicious usage of "if" like
4700 # } if (a == b) {
Darius Maa7d7e42022-05-13 14:54:21 +00004701 if Search(r'\}\s*if\s*(?:constexpr\s*)?\(', line):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004702 error(filename, linenum, 'readability/braces', 4,
4703 'Did you mean "else if"? If not, start a new line for "if".')
4704
4705 # Check for potential format string bugs like printf(foo).
4706 # We constrain the pattern not to pick things like DocidForPrintf(foo).
4707 # Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str())
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004708 # TODO(unknown): Catch the following case. Need to change the calling
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004709 # convention of the whole function to process multiple line to handle it.
4710 # printf(
4711 # boy_this_is_a_really_long_variable_that_cannot_fit_on_the_prev_line);
4712 printf_args = _GetTextInside(line, r'(?i)\b(string)?printf\s*\(')
4713 if printf_args:
4714 match = Match(r'([\w.\->()]+)$', printf_args)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004715 if match and match.group(1) != '__VA_ARGS__':
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004716 function_name = re.search(r'\b((?:string)?printf)\s*\(',
4717 line, re.I).group(1)
4718 error(filename, linenum, 'runtime/printf', 4,
4719 'Potential format string bug. Do %s("%%s", %s) instead.'
4720 % (function_name, match.group(1)))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004721
4722 # Check for potential memset bugs like memset(buf, sizeof(buf), 0).
4723 match = Search(r'memset\s*\(([^,]*),\s*([^,]*),\s*0\s*\)', line)
4724 if match and not Match(r"^''|-?[0-9]+|0x[0-9A-Fa-f]$", match.group(2)):
4725 error(filename, linenum, 'runtime/memset', 4,
4726 'Did you mean "memset(%s, 0, %s)"?'
4727 % (match.group(1), match.group(2)))
4728
4729 if Search(r'\busing namespace\b', line):
4730 error(filename, linenum, 'build/namespaces', 5,
4731 'Do not use namespace using-directives. '
4732 'Use using-declarations instead.')
4733
4734 # Detect variable-length arrays.
4735 match = Match(r'\s*(.+::)?(\w+) [a-z]\w*\[(.+)];', line)
4736 if (match and match.group(2) != 'return' and match.group(2) != 'delete' and
4737 match.group(3).find(']') == -1):
4738 # Split the size using space and arithmetic operators as delimiters.
4739 # If any of the resulting tokens are not compile time constants then
4740 # report the error.
4741 tokens = re.split(r'\s|\+|\-|\*|\/|<<|>>]', match.group(3))
4742 is_const = True
4743 skip_next = False
4744 for tok in tokens:
4745 if skip_next:
4746 skip_next = False
4747 continue
4748
4749 if Search(r'sizeof\(.+\)', tok): continue
4750 if Search(r'arraysize\(\w+\)', tok): continue
Avi Drissman4157ba12019-01-09 14:18:07 +00004751 if Search(r'base::size\(.+\)', tok): continue
4752 if Search(r'std::size\(.+\)', tok): continue
4753 if Search(r'std::extent<.+>', tok): continue
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004754
4755 tok = tok.lstrip('(')
4756 tok = tok.rstrip(')')
4757 if not tok: continue
4758 if Match(r'\d+', tok): continue
4759 if Match(r'0[xX][0-9a-fA-F]+', tok): continue
4760 if Match(r'k[A-Z0-9]\w*', tok): continue
4761 if Match(r'(.+::)?k[A-Z0-9]\w*', tok): continue
4762 if Match(r'(.+::)?[A-Z][A-Z0-9_]*', tok): continue
4763 # A catch all for tricky sizeof cases, including 'sizeof expression',
4764 # 'sizeof(*type)', 'sizeof(const type)', 'sizeof(struct StructName)'
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004765 # requires skipping the next token because we split on ' ' and '*'.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004766 if tok.startswith('sizeof'):
4767 skip_next = True
4768 continue
4769 is_const = False
4770 break
4771 if not is_const:
4772 error(filename, linenum, 'runtime/arrays', 1,
4773 'Do not use variable-length arrays. Use an appropriately named '
4774 "('k' followed by CamelCase) compile-time constant for the size.")
4775
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004776 # Check for use of unnamed namespaces in header files. Registration
4777 # macros are typically OK, so we allow use of "namespace {" on lines
4778 # that end with backslashes.
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00004779 if (file_extension == 'h'
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004780 and Search(r'\bnamespace\s*{', line)
4781 and line[-1] != '\\'):
4782 error(filename, linenum, 'build/namespaces', 4,
4783 'Do not use unnamed namespaces in header files. See '
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00004784 'https://google.github.io/styleguide/cppguide.html#Namespaces'
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004785 ' for more information.')
4786
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004787
4788def CheckGlobalStatic(filename, clean_lines, linenum, error):
4789 """Check for unsafe global or static objects.
4790
4791 Args:
4792 filename: The name of the current file.
4793 clean_lines: A CleansedLines instance containing the file.
4794 linenum: The number of the line to check.
4795 error: The function to call with any errors found.
4796 """
4797 line = clean_lines.elided[linenum]
4798
avakulenko@google.com59146752014-08-11 20:20:55 +00004799 # Match two lines at a time to support multiline declarations
4800 if linenum + 1 < clean_lines.NumLines() and not Search(r'[;({]', line):
4801 line += clean_lines.elided[linenum + 1].strip()
4802
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004803 # Check for people declaring static/global STL strings at the top level.
4804 # This is dangerous because the C++ language does not guarantee that
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004805 # globals with constructors are initialized before the first access, and
4806 # also because globals can be destroyed when some threads are still running.
4807 # TODO(unknown): Generalize this to also find static unique_ptr instances.
4808 # TODO(unknown): File bugs for clang-tidy to find these.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004809 match = Match(
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004810 r'((?:|static +)(?:|const +))(?::*std::)?string( +const)? +'
4811 r'([a-zA-Z0-9_:]+)\b(.*)',
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004812 line)
avakulenko@google.com59146752014-08-11 20:20:55 +00004813
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004814 # Remove false positives:
4815 # - String pointers (as opposed to values).
4816 # string *pointer
4817 # const string *pointer
4818 # string const *pointer
4819 # string *const pointer
4820 #
4821 # - Functions and template specializations.
4822 # string Function<Type>(...
4823 # string Class<Type>::Method(...
4824 #
4825 # - Operators. These are matched separately because operator names
4826 # cross non-word boundaries, and trying to match both operators
4827 # and functions at the same time would decrease accuracy of
4828 # matching identifiers.
4829 # string Class::operator*()
4830 if (match and
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004831 not Search(r'\bstring\b(\s+const)?\s*[\*\&]\s*(const\s+)?\w', line) and
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004832 not Search(r'\boperator\W', line) and
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004833 not Match(r'\s*(<.*>)?(::[a-zA-Z0-9_]+)*\s*\(([^"]|$)', match.group(4))):
4834 if Search(r'\bconst\b', line):
4835 error(filename, linenum, 'runtime/string', 4,
4836 'For a static/global string constant, use a C style string '
4837 'instead: "%schar%s %s[]".' %
4838 (match.group(1), match.group(2) or '', match.group(3)))
4839 else:
4840 error(filename, linenum, 'runtime/string', 4,
4841 'Static/global string variables are not permitted.')
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004842
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004843 if (Search(r'\b([A-Za-z0-9_]*_)\(\1\)', line) or
4844 Search(r'\b([A-Za-z0-9_]*_)\(CHECK_NOTNULL\(\1\)\)', line)):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004845 error(filename, linenum, 'runtime/init', 4,
4846 'You seem to be initializing a member variable with itself.')
4847
4848
4849def CheckPrintf(filename, clean_lines, linenum, error):
4850 """Check for printf related issues.
4851
4852 Args:
4853 filename: The name of the current file.
4854 clean_lines: A CleansedLines instance containing the file.
4855 linenum: The number of the line to check.
4856 error: The function to call with any errors found.
4857 """
4858 line = clean_lines.elided[linenum]
4859
4860 # When snprintf is used, the second argument shouldn't be a literal.
4861 match = Search(r'snprintf\s*\(([^,]*),\s*([0-9]*)\s*,', line)
4862 if match and match.group(2) != '0':
4863 # If 2nd arg is zero, snprintf is used to calculate size.
4864 error(filename, linenum, 'runtime/printf', 3,
4865 'If you can, use sizeof(%s) instead of %s as the 2nd arg '
4866 'to snprintf.' % (match.group(1), match.group(2)))
4867
4868 # Check if some verboten C functions are being used.
avakulenko@google.com59146752014-08-11 20:20:55 +00004869 if Search(r'\bsprintf\s*\(', line):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004870 error(filename, linenum, 'runtime/printf', 5,
4871 'Never use sprintf. Use snprintf instead.')
avakulenko@google.com59146752014-08-11 20:20:55 +00004872 match = Search(r'\b(strcpy|strcat)\s*\(', line)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004873 if match:
4874 error(filename, linenum, 'runtime/printf', 4,
4875 'Almost always, snprintf is better than %s' % match.group(1))
4876
4877
4878def IsDerivedFunction(clean_lines, linenum):
4879 """Check if current line contains an inherited function.
4880
4881 Args:
4882 clean_lines: A CleansedLines instance containing the file.
4883 linenum: The number of the line to check.
4884 Returns:
4885 True if current line contains a function with "override"
4886 virt-specifier.
4887 """
avakulenko@google.com59146752014-08-11 20:20:55 +00004888 # Scan back a few lines for start of current function
Edward Lemur6d31ed52019-12-02 23:00:00 +00004889 for i in range(linenum, max(-1, linenum - 10), -1):
avakulenko@google.com59146752014-08-11 20:20:55 +00004890 match = Match(r'^([^()]*\w+)\(', clean_lines.elided[i])
4891 if match:
4892 # Look for "override" after the matching closing parenthesis
4893 line, _, closing_paren = CloseExpression(
4894 clean_lines, i, len(match.group(1)))
4895 return (closing_paren >= 0 and
4896 Search(r'\boverride\b', line[closing_paren:]))
4897 return False
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004898
4899
avakulenko@google.com255f2be2014-12-05 22:19:55 +00004900def IsOutOfLineMethodDefinition(clean_lines, linenum):
4901 """Check if current line contains an out-of-line method definition.
4902
4903 Args:
4904 clean_lines: A CleansedLines instance containing the file.
4905 linenum: The number of the line to check.
4906 Returns:
4907 True if current line contains an out-of-line method definition.
4908 """
4909 # Scan back a few lines for start of current function
Edward Lemur6d31ed52019-12-02 23:00:00 +00004910 for i in range(linenum, max(-1, linenum - 10), -1):
avakulenko@google.com255f2be2014-12-05 22:19:55 +00004911 if Match(r'^([^()]*\w+)\(', clean_lines.elided[i]):
4912 return Match(r'^[^()]*\w+::\w+\(', clean_lines.elided[i]) is not None
4913 return False
4914
4915
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004916def IsInitializerList(clean_lines, linenum):
4917 """Check if current line is inside constructor initializer list.
4918
4919 Args:
4920 clean_lines: A CleansedLines instance containing the file.
4921 linenum: The number of the line to check.
4922 Returns:
4923 True if current line appears to be inside constructor initializer
4924 list, False otherwise.
4925 """
Edward Lemur6d31ed52019-12-02 23:00:00 +00004926 for i in range(linenum, 1, -1):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004927 line = clean_lines.elided[i]
4928 if i == linenum:
4929 remove_function_body = Match(r'^(.*)\{\s*$', line)
4930 if remove_function_body:
4931 line = remove_function_body.group(1)
4932
4933 if Search(r'\s:\s*\w+[({]', line):
4934 # A lone colon tend to indicate the start of a constructor
4935 # initializer list. It could also be a ternary operator, which
4936 # also tend to appear in constructor initializer lists as
4937 # opposed to parameter lists.
4938 return True
4939 if Search(r'\}\s*,\s*$', line):
4940 # A closing brace followed by a comma is probably the end of a
4941 # brace-initialized member in constructor initializer list.
4942 return True
4943 if Search(r'[{};]\s*$', line):
4944 # Found one of the following:
4945 # - A closing brace or semicolon, probably the end of the previous
4946 # function.
4947 # - An opening brace, probably the start of current class or namespace.
4948 #
4949 # Current line is probably not inside an initializer list since
4950 # we saw one of those things without seeing the starting colon.
4951 return False
4952
4953 # Got to the beginning of the file without seeing the start of
4954 # constructor initializer list.
4955 return False
4956
4957
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004958def CheckForNonConstReference(filename, clean_lines, linenum,
4959 nesting_state, error):
4960 """Check for non-const references.
4961
4962 Separate from CheckLanguage since it scans backwards from current
4963 line, instead of scanning forward.
4964
4965 Args:
4966 filename: The name of the current file.
4967 clean_lines: A CleansedLines instance containing the file.
4968 linenum: The number of the line to check.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004969 nesting_state: A NestingState instance which maintains information about
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004970 the current stack of nested blocks being parsed.
4971 error: The function to call with any errors found.
4972 """
4973 # Do nothing if there is no '&' on current line.
4974 line = clean_lines.elided[linenum]
4975 if '&' not in line:
4976 return
4977
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004978 # If a function is inherited, current function doesn't have much of
4979 # a choice, so any non-const references should not be blamed on
4980 # derived function.
4981 if IsDerivedFunction(clean_lines, linenum):
4982 return
4983
avakulenko@google.com255f2be2014-12-05 22:19:55 +00004984 # Don't warn on out-of-line method definitions, as we would warn on the
4985 # in-line declaration, if it isn't marked with 'override'.
4986 if IsOutOfLineMethodDefinition(clean_lines, linenum):
4987 return
4988
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004989 # Long type names may be broken across multiple lines, usually in one
4990 # of these forms:
4991 # LongType
4992 # ::LongTypeContinued &identifier
4993 # LongType::
4994 # LongTypeContinued &identifier
4995 # LongType<
4996 # ...>::LongTypeContinued &identifier
4997 #
4998 # If we detected a type split across two lines, join the previous
4999 # line to current line so that we can match const references
5000 # accordingly.
5001 #
5002 # Note that this only scans back one line, since scanning back
5003 # arbitrary number of lines would be expensive. If you have a type
5004 # that spans more than 2 lines, please use a typedef.
5005 if linenum > 1:
5006 previous = None
5007 if Match(r'\s*::(?:[\w<>]|::)+\s*&\s*\S', line):
5008 # previous_line\n + ::current_line
5009 previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+[\w<>])\s*$',
5010 clean_lines.elided[linenum - 1])
5011 elif Match(r'\s*[a-zA-Z_]([\w<>]|::)+\s*&\s*\S', line):
5012 # previous_line::\n + current_line
5013 previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+::)\s*$',
5014 clean_lines.elided[linenum - 1])
5015 if previous:
5016 line = previous.group(1) + line.lstrip()
5017 else:
5018 # Check for templated parameter that is split across multiple lines
5019 endpos = line.rfind('>')
5020 if endpos > -1:
5021 (_, startline, startpos) = ReverseCloseExpression(
5022 clean_lines, linenum, endpos)
5023 if startpos > -1 and startline < linenum:
5024 # Found the matching < on an earlier line, collect all
5025 # pieces up to current line.
5026 line = ''
Edward Lemur6d31ed52019-12-02 23:00:00 +00005027 for i in range(startline, linenum + 1):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005028 line += clean_lines.elided[i].strip()
5029
5030 # Check for non-const references in function parameters. A single '&' may
5031 # found in the following places:
5032 # inside expression: binary & for bitwise AND
5033 # inside expression: unary & for taking the address of something
5034 # inside declarators: reference parameter
5035 # We will exclude the first two cases by checking that we are not inside a
5036 # function body, including one that was just introduced by a trailing '{'.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005037 # TODO(unknown): Doesn't account for 'catch(Exception& e)' [rare].
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005038 if (nesting_state.previous_stack_top and
5039 not (isinstance(nesting_state.previous_stack_top, _ClassInfo) or
5040 isinstance(nesting_state.previous_stack_top, _NamespaceInfo))):
5041 # Not at toplevel, not within a class, and not within a namespace
5042 return
5043
avakulenko@google.com59146752014-08-11 20:20:55 +00005044 # Avoid initializer lists. We only need to scan back from the
5045 # current line for something that starts with ':'.
5046 #
5047 # We don't need to check the current line, since the '&' would
5048 # appear inside the second set of parentheses on the current line as
5049 # opposed to the first set.
5050 if linenum > 0:
Edward Lemur6d31ed52019-12-02 23:00:00 +00005051 for i in range(linenum - 1, max(0, linenum - 10), -1):
avakulenko@google.com59146752014-08-11 20:20:55 +00005052 previous_line = clean_lines.elided[i]
5053 if not Search(r'[),]\s*$', previous_line):
5054 break
5055 if Match(r'^\s*:\s+\S', previous_line):
5056 return
5057
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005058 # Avoid preprocessors
5059 if Search(r'\\\s*$', line):
5060 return
5061
5062 # Avoid constructor initializer lists
5063 if IsInitializerList(clean_lines, linenum):
5064 return
5065
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005066 # We allow non-const references in a few standard places, like functions
5067 # called "swap()" or iostream operators like "<<" or ">>". Do not check
5068 # those function parameters.
5069 #
5070 # We also accept & in static_assert, which looks like a function but
5071 # it's actually a declaration expression.
Ayu Ishii09858612020-06-26 18:00:52 +00005072 allowlisted_functions = (r'(?:[sS]wap(?:<\w:+>)?|'
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005073 r'operator\s*[<>][<>]|'
5074 r'static_assert|COMPILE_ASSERT'
5075 r')\s*\(')
Ayu Ishii09858612020-06-26 18:00:52 +00005076 if Search(allowlisted_functions, line):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005077 return
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005078 elif not Search(r'\S+\([^)]*$', line):
Ayu Ishii09858612020-06-26 18:00:52 +00005079 # Don't see an allowlisted function on this line. Actually we
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005080 # didn't see any function name on this line, so this is likely a
5081 # multi-line parameter list. Try a bit harder to catch this case.
Edward Lemur6d31ed52019-12-02 23:00:00 +00005082 for i in range(2):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005083 if (linenum > i and
Ayu Ishii09858612020-06-26 18:00:52 +00005084 Search(allowlisted_functions, clean_lines.elided[linenum - i - 1])):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005085 return
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005086
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005087 decls = ReplaceAll(r'{[^}]*}', ' ', line) # exclude function body
5088 for parameter in re.findall(_RE_PATTERN_REF_PARAM, decls):
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005089 if (not Match(_RE_PATTERN_CONST_REF_PARAM, parameter) and
5090 not Match(_RE_PATTERN_REF_STREAM_PARAM, parameter)):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005091 error(filename, linenum, 'runtime/references', 2,
5092 'Is this a non-const reference? '
5093 'If so, make const or use a pointer: ' +
5094 ReplaceAll(' *<', '<', parameter))
5095
5096
5097def CheckCasts(filename, clean_lines, linenum, error):
5098 """Various cast related checks.
5099
5100 Args:
5101 filename: The name of the current file.
5102 clean_lines: A CleansedLines instance containing the file.
5103 linenum: The number of the line to check.
5104 error: The function to call with any errors found.
5105 """
5106 line = clean_lines.elided[linenum]
5107
5108 # Check to see if they're using an conversion function cast.
5109 # I just try to capture the most common basic types, though there are more.
5110 # Parameterless conversion functions, such as bool(), are allowed as they are
5111 # probably a member operator declaration or default constructor.
5112 match = Search(
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005113 r'(\bnew\s+(?:const\s+)?|\S<\s*(?:const\s+)?)?\b'
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005114 r'(int|float|double|bool|char|int32|uint32|int64|uint64)'
5115 r'(\([^)].*)', line)
5116 expecting_function = ExpectingFunctionArgs(clean_lines, linenum)
5117 if match and not expecting_function:
5118 matched_type = match.group(2)
5119
5120 # matched_new_or_template is used to silence two false positives:
5121 # - New operators
5122 # - Template arguments with function types
5123 #
5124 # For template arguments, we match on types immediately following
5125 # an opening bracket without any spaces. This is a fast way to
5126 # silence the common case where the function type is the first
5127 # template argument. False negative with less-than comparison is
5128 # avoided because those operators are usually followed by a space.
5129 #
5130 # function<double(double)> // bracket + no space = false positive
5131 # value < double(42) // bracket + space = true positive
5132 matched_new_or_template = match.group(1)
5133
avakulenko@google.com59146752014-08-11 20:20:55 +00005134 # Avoid arrays by looking for brackets that come after the closing
5135 # parenthesis.
5136 if Match(r'\([^()]+\)\s*\[', match.group(3)):
5137 return
5138
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005139 # Other things to ignore:
5140 # - Function pointers
5141 # - Casts to pointer types
5142 # - Placement new
5143 # - Alias declarations
5144 matched_funcptr = match.group(3)
5145 if (matched_new_or_template is None and
5146 not (matched_funcptr and
5147 (Match(r'\((?:[^() ]+::\s*\*\s*)?[^() ]+\)\s*\(',
5148 matched_funcptr) or
5149 matched_funcptr.startswith('(*)'))) and
5150 not Match(r'\s*using\s+\S+\s*=\s*' + matched_type, line) and
5151 not Search(r'new\(\S+\)\s*' + matched_type, line)):
5152 error(filename, linenum, 'readability/casting', 4,
5153 'Using deprecated casting style. '
5154 'Use static_cast<%s>(...) instead' %
5155 matched_type)
5156
5157 if not expecting_function:
avakulenko@google.com59146752014-08-11 20:20:55 +00005158 CheckCStyleCast(filename, clean_lines, linenum, 'static_cast',
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005159 r'\((int|float|double|bool|char|u?int(16|32|64))\)', error)
5160
5161 # This doesn't catch all cases. Consider (const char * const)"hello".
5162 #
5163 # (char *) "foo" should always be a const_cast (reinterpret_cast won't
5164 # compile).
avakulenko@google.com59146752014-08-11 20:20:55 +00005165 if CheckCStyleCast(filename, clean_lines, linenum, 'const_cast',
5166 r'\((char\s?\*+\s?)\)\s*"', error):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005167 pass
5168 else:
5169 # Check pointer casts for other than string constants
avakulenko@google.com59146752014-08-11 20:20:55 +00005170 CheckCStyleCast(filename, clean_lines, linenum, 'reinterpret_cast',
5171 r'\((\w+\s?\*+\s?)\)', error)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005172
5173 # In addition, we look for people taking the address of a cast. This
5174 # is dangerous -- casts can assign to temporaries, so the pointer doesn't
5175 # point where you think.
avakulenko@google.com59146752014-08-11 20:20:55 +00005176 #
5177 # Some non-identifier character is required before the '&' for the
5178 # expression to be recognized as a cast. These are casts:
5179 # expression = &static_cast<int*>(temporary());
5180 # function(&(int*)(temporary()));
5181 #
5182 # This is not a cast:
5183 # reference_type&(int* function_param);
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005184 match = Search(
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005185 r'(?:[^\w]&\(([^)*][^)]*)\)[\w(])|'
avakulenko@google.com59146752014-08-11 20:20:55 +00005186 r'(?:[^\w]&(static|dynamic|down|reinterpret)_cast\b)', line)
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005187 if match:
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005188 # Try a better error message when the & is bound to something
5189 # dereferenced by the casted pointer, as opposed to the casted
5190 # pointer itself.
5191 parenthesis_error = False
5192 match = Match(r'^(.*&(?:static|dynamic|down|reinterpret)_cast\b)<', line)
5193 if match:
5194 _, y1, x1 = CloseExpression(clean_lines, linenum, len(match.group(1)))
5195 if x1 >= 0 and clean_lines.elided[y1][x1] == '(':
5196 _, y2, x2 = CloseExpression(clean_lines, y1, x1)
5197 if x2 >= 0:
5198 extended_line = clean_lines.elided[y2][x2:]
5199 if y2 < clean_lines.NumLines() - 1:
5200 extended_line += clean_lines.elided[y2 + 1]
5201 if Match(r'\s*(?:->|\[)', extended_line):
5202 parenthesis_error = True
5203
5204 if parenthesis_error:
5205 error(filename, linenum, 'readability/casting', 4,
5206 ('Are you taking an address of something dereferenced '
5207 'from a cast? Wrapping the dereferenced expression in '
5208 'parentheses will make the binding more obvious'))
5209 else:
5210 error(filename, linenum, 'runtime/casting', 4,
5211 ('Are you taking an address of a cast? '
5212 'This is dangerous: could be a temp var. '
5213 'Take the address before doing the cast, rather than after'))
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005214
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005215
avakulenko@google.com59146752014-08-11 20:20:55 +00005216def CheckCStyleCast(filename, clean_lines, linenum, cast_type, pattern, error):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005217 """Checks for a C-style cast by looking for the pattern.
5218
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005219 Args:
5220 filename: The name of the current file.
avakulenko@google.com59146752014-08-11 20:20:55 +00005221 clean_lines: A CleansedLines instance containing the file.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005222 linenum: The number of the line to check.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005223 cast_type: The string for the C++ cast to recommend. This is either
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005224 reinterpret_cast, static_cast, or const_cast, depending.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005225 pattern: The regular expression used to find C-style casts.
5226 error: The function to call with any errors found.
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005227
5228 Returns:
5229 True if an error was emitted.
5230 False otherwise.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005231 """
avakulenko@google.com59146752014-08-11 20:20:55 +00005232 line = clean_lines.elided[linenum]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005233 match = Search(pattern, line)
5234 if not match:
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005235 return False
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005236
avakulenko@google.com59146752014-08-11 20:20:55 +00005237 # Exclude lines with keywords that tend to look like casts
5238 context = line[0:match.start(1) - 1]
5239 if Match(r'.*\b(?:sizeof|alignof|alignas|[_A-Z][_A-Z0-9]*)\s*$', context):
5240 return False
5241
5242 # Try expanding current context to see if we one level of
5243 # parentheses inside a macro.
5244 if linenum > 0:
Edward Lemur6d31ed52019-12-02 23:00:00 +00005245 for i in range(linenum - 1, max(0, linenum - 5), -1):
avakulenko@google.com59146752014-08-11 20:20:55 +00005246 context = clean_lines.elided[i] + context
5247 if Match(r'.*\b[_A-Z][_A-Z0-9]*\s*\((?:\([^()]*\)|[^()])*$', context):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005248 return False
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005249
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005250 # operator++(int) and operator--(int)
avakulenko@google.com59146752014-08-11 20:20:55 +00005251 if context.endswith(' operator++') or context.endswith(' operator--'):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005252 return False
5253
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005254 # A single unnamed argument for a function tends to look like old style cast.
5255 # If we see those, don't issue warnings for deprecated casts.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005256 remainder = line[match.end(0):]
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005257 if Match(r'^\s*(?:;|const\b|throw\b|final\b|override\b|[=>{),]|->)',
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005258 remainder):
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005259 return False
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005260
5261 # At this point, all that should be left is actual casts.
5262 error(filename, linenum, 'readability/casting', 4,
5263 'Using C-style cast. Use %s<%s>(...) instead' %
5264 (cast_type, match.group(1)))
5265
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005266 return True
5267
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005268
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005269def ExpectingFunctionArgs(clean_lines, linenum):
5270 """Checks whether where function type arguments are expected.
5271
5272 Args:
5273 clean_lines: A CleansedLines instance containing the file.
5274 linenum: The number of the line to check.
5275
5276 Returns:
5277 True if the line at 'linenum' is inside something that expects arguments
5278 of function types.
5279 """
5280 line = clean_lines.elided[linenum]
5281 return (Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line) or
5282 (linenum >= 2 and
5283 (Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\((?:\S+,)?\s*$',
5284 clean_lines.elided[linenum - 1]) or
5285 Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\(\s*$',
5286 clean_lines.elided[linenum - 2]) or
5287 Search(r'\bstd::m?function\s*\<\s*$',
5288 clean_lines.elided[linenum - 1]))))
5289
5290
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005291_HEADERS_CONTAINING_TEMPLATES = (
5292 ('<deque>', ('deque',)),
5293 ('<functional>', ('unary_function', 'binary_function',
5294 'plus', 'minus', 'multiplies', 'divides', 'modulus',
5295 'negate',
5296 'equal_to', 'not_equal_to', 'greater', 'less',
5297 'greater_equal', 'less_equal',
5298 'logical_and', 'logical_or', 'logical_not',
5299 'unary_negate', 'not1', 'binary_negate', 'not2',
5300 'bind1st', 'bind2nd',
5301 'pointer_to_unary_function',
5302 'pointer_to_binary_function',
5303 'ptr_fun',
5304 'mem_fun_t', 'mem_fun', 'mem_fun1_t', 'mem_fun1_ref_t',
5305 'mem_fun_ref_t',
5306 'const_mem_fun_t', 'const_mem_fun1_t',
5307 'const_mem_fun_ref_t', 'const_mem_fun1_ref_t',
5308 'mem_fun_ref',
5309 )),
5310 ('<limits>', ('numeric_limits',)),
5311 ('<list>', ('list',)),
5312 ('<map>', ('map', 'multimap',)),
lhchavez2d1b6da2016-07-13 10:40:01 -07005313 ('<memory>', ('allocator', 'make_shared', 'make_unique', 'shared_ptr',
5314 'unique_ptr', 'weak_ptr')),
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005315 ('<queue>', ('queue', 'priority_queue',)),
5316 ('<set>', ('set', 'multiset',)),
5317 ('<stack>', ('stack',)),
5318 ('<string>', ('char_traits', 'basic_string',)),
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005319 ('<tuple>', ('tuple',)),
lhchavez2d1b6da2016-07-13 10:40:01 -07005320 ('<unordered_map>', ('unordered_map', 'unordered_multimap')),
5321 ('<unordered_set>', ('unordered_set', 'unordered_multiset')),
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005322 ('<utility>', ('pair',)),
5323 ('<vector>', ('vector',)),
5324
5325 # gcc extensions.
5326 # Note: std::hash is their hash, ::hash is our hash
5327 ('<hash_map>', ('hash_map', 'hash_multimap',)),
5328 ('<hash_set>', ('hash_set', 'hash_multiset',)),
5329 ('<slist>', ('slist',)),
5330 )
5331
skym@chromium.org3990c412016-02-05 20:55:12 +00005332_HEADERS_MAYBE_TEMPLATES = (
5333 ('<algorithm>', ('copy', 'max', 'min', 'min_element', 'sort',
5334 'transform',
5335 )),
lhchavez2d1b6da2016-07-13 10:40:01 -07005336 ('<utility>', ('forward', 'make_pair', 'move', 'swap')),
skym@chromium.org3990c412016-02-05 20:55:12 +00005337 )
5338
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005339_RE_PATTERN_STRING = re.compile(r'\bstring\b')
5340
skym@chromium.org3990c412016-02-05 20:55:12 +00005341_re_pattern_headers_maybe_templates = []
5342for _header, _templates in _HEADERS_MAYBE_TEMPLATES:
5343 for _template in _templates:
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +00005344 # Match max<type>(..., ...), max(..., ...), but not foo->max, foo.max
5345 # or type::max().
skym@chromium.org3990c412016-02-05 20:55:12 +00005346 _re_pattern_headers_maybe_templates.append(
5347 (re.compile(r'[^>.]\b' + _template + r'(<.*?>)?\([^\)]'),
5348 _template,
5349 _header))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005350
skym@chromium.org3990c412016-02-05 20:55:12 +00005351# Other scripts may reach in and modify this pattern.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005352_re_pattern_templates = []
5353for _header, _templates in _HEADERS_CONTAINING_TEMPLATES:
5354 for _template in _templates:
5355 _re_pattern_templates.append(
5356 (re.compile(r'(\<|\b)' + _template + r'\s*\<'),
5357 _template + '<>',
5358 _header))
5359
5360
erg@google.com6317a9c2009-06-25 00:28:19 +00005361def FilesBelongToSameModule(filename_cc, filename_h):
5362 """Check if these two filenames belong to the same module.
5363
5364 The concept of a 'module' here is a as follows:
5365 foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the
5366 same 'module' if they are in the same directory.
5367 some/path/public/xyzzy and some/path/internal/xyzzy are also considered
5368 to belong to the same module here.
5369
5370 If the filename_cc contains a longer path than the filename_h, for example,
5371 '/absolute/path/to/base/sysinfo.cc', and this file would include
5372 'base/sysinfo.h', this function also produces the prefix needed to open the
5373 header. This is used by the caller of this function to more robustly open the
5374 header file. We don't have access to the real include paths in this context,
5375 so we need this guesswork here.
5376
5377 Known bugs: tools/base/bar.cc and base/bar.h belong to the same module
5378 according to this implementation. Because of this, this function gives
5379 some false positives. This should be sufficiently rare in practice.
5380
5381 Args:
5382 filename_cc: is the path for the .cc file
5383 filename_h: is the path for the header path
5384
5385 Returns:
5386 Tuple with a bool and a string:
5387 bool: True if filename_cc and filename_h belong to the same module.
5388 string: the additional prefix needed to open the header file.
5389 """
5390
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005391 fileinfo = FileInfo(filename_cc)
5392 if not fileinfo.IsSource():
erg@google.com6317a9c2009-06-25 00:28:19 +00005393 return (False, '')
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005394 filename_cc = filename_cc[:-len(fileinfo.Extension())]
5395 matched_test_suffix = Search(_TEST_FILE_SUFFIX, fileinfo.BaseName())
5396 if matched_test_suffix:
5397 filename_cc = filename_cc[:-len(matched_test_suffix.group(1))]
erg@google.com6317a9c2009-06-25 00:28:19 +00005398 filename_cc = filename_cc.replace('/public/', '/')
5399 filename_cc = filename_cc.replace('/internal/', '/')
5400
5401 if not filename_h.endswith('.h'):
5402 return (False, '')
5403 filename_h = filename_h[:-len('.h')]
5404 if filename_h.endswith('-inl'):
5405 filename_h = filename_h[:-len('-inl')]
5406 filename_h = filename_h.replace('/public/', '/')
5407 filename_h = filename_h.replace('/internal/', '/')
5408
5409 files_belong_to_same_module = filename_cc.endswith(filename_h)
5410 common_path = ''
5411 if files_belong_to_same_module:
5412 common_path = filename_cc[:-len(filename_h)]
5413 return files_belong_to_same_module, common_path
5414
5415
avakulenko@google.com59146752014-08-11 20:20:55 +00005416def UpdateIncludeState(filename, include_dict, io=codecs):
5417 """Fill up the include_dict with new includes found from the file.
erg@google.com6317a9c2009-06-25 00:28:19 +00005418
5419 Args:
5420 filename: the name of the header to read.
avakulenko@google.com59146752014-08-11 20:20:55 +00005421 include_dict: a dictionary in which the headers are inserted.
erg@google.com6317a9c2009-06-25 00:28:19 +00005422 io: The io factory to use to read the file. Provided for testability.
5423
5424 Returns:
avakulenko@google.com59146752014-08-11 20:20:55 +00005425 True if a header was successfully added. False otherwise.
erg@google.com6317a9c2009-06-25 00:28:19 +00005426 """
5427 headerfile = None
5428 try:
5429 headerfile = io.open(filename, 'r', 'utf8', 'replace')
5430 except IOError:
5431 return False
5432 linenum = 0
5433 for line in headerfile:
5434 linenum += 1
5435 clean_line = CleanseComments(line)
5436 match = _RE_PATTERN_INCLUDE.search(clean_line)
5437 if match:
5438 include = match.group(2)
avakulenko@google.com59146752014-08-11 20:20:55 +00005439 include_dict.setdefault(include, linenum)
erg@google.com6317a9c2009-06-25 00:28:19 +00005440 return True
5441
5442
5443def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error,
5444 io=codecs):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005445 """Reports for missing stl includes.
5446
5447 This function will output warnings to make sure you are including the headers
5448 necessary for the stl containers and functions that you use. We only give one
5449 reason to include a header. For example, if you use both equal_to<> and
5450 less<> in a .h file, only one (the latter in the file) of these will be
5451 reported as a reason to include the <functional>.
5452
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005453 Args:
5454 filename: The name of the current file.
5455 clean_lines: A CleansedLines instance containing the file.
5456 include_state: An _IncludeState instance.
5457 error: The function to call with any errors found.
erg@google.com6317a9c2009-06-25 00:28:19 +00005458 io: The IO factory to use to read the header file. Provided for unittest
5459 injection.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005460 """
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +00005461 # A map of header name to linenumber and the template entity.
5462 # Example of required: { '<functional>': (1219, 'less<>') }
5463 required = {}
Edward Lemur6d31ed52019-12-02 23:00:00 +00005464 for linenum in range(clean_lines.NumLines()):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005465 line = clean_lines.elided[linenum]
5466 if not line or line[0] == '#':
5467 continue
5468
5469 # String is special -- it is a non-templatized type in STL.
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005470 matched = _RE_PATTERN_STRING.search(line)
5471 if matched:
erg@google.com35589e62010-11-17 18:58:16 +00005472 # Don't warn about strings in non-STL namespaces:
5473 # (We check only the first match per line; good enough.)
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005474 prefix = line[:matched.start()]
erg@google.com35589e62010-11-17 18:58:16 +00005475 if prefix.endswith('std::') or not prefix.endswith('::'):
5476 required['<string>'] = (linenum, 'string')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005477
skym@chromium.org3990c412016-02-05 20:55:12 +00005478 for pattern, template, header in _re_pattern_headers_maybe_templates:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005479 if pattern.search(line):
5480 required[header] = (linenum, template)
5481
5482 # The following function is just a speed up, no semantics are changed.
5483 if not '<' in line: # Reduces the cpu time usage by skipping lines.
5484 continue
5485
5486 for pattern, template, header in _re_pattern_templates:
lhchavez9b2173c2016-07-13 10:20:07 -07005487 matched = pattern.search(line)
5488 if matched:
5489 # Don't warn about IWYU in non-STL namespaces:
5490 # (We check only the first match per line; good enough.)
5491 prefix = line[:matched.start()]
5492 if prefix.endswith('std::') or not prefix.endswith('::'):
5493 required[header] = (linenum, template)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005494
erg@google.com6317a9c2009-06-25 00:28:19 +00005495 # The policy is that if you #include something in foo.h you don't need to
5496 # include it again in foo.cc. Here, we will look at possible includes.
avakulenko@google.com59146752014-08-11 20:20:55 +00005497 # Let's flatten the include_state include_list and copy it into a dictionary.
5498 include_dict = dict([item for sublist in include_state.include_list
5499 for item in sublist])
erg@google.com6317a9c2009-06-25 00:28:19 +00005500
avakulenko@google.com59146752014-08-11 20:20:55 +00005501 # Did we find the header for this file (if any) and successfully load it?
erg@google.com6317a9c2009-06-25 00:28:19 +00005502 header_found = False
5503
5504 # Use the absolute path so that matching works properly.
erg@chromium.org8f927562012-01-30 19:51:28 +00005505 abs_filename = FileInfo(filename).FullName()
erg@google.com6317a9c2009-06-25 00:28:19 +00005506
5507 # For Emacs's flymake.
5508 # If cpplint is invoked from Emacs's flymake, a temporary file is generated
5509 # by flymake and that file name might end with '_flymake.cc'. In that case,
5510 # restore original file name here so that the corresponding header file can be
5511 # found.
5512 # e.g. If the file name is 'foo_flymake.cc', we should search for 'foo.h'
5513 # instead of 'foo_flymake.h'
erg@google.com35589e62010-11-17 18:58:16 +00005514 abs_filename = re.sub(r'_flymake\.cc$', '.cc', abs_filename)
erg@google.com6317a9c2009-06-25 00:28:19 +00005515
avakulenko@google.com59146752014-08-11 20:20:55 +00005516 # include_dict is modified during iteration, so we iterate over a copy of
erg@google.com6317a9c2009-06-25 00:28:19 +00005517 # the keys.
Sarthak Kukreti60378202019-12-17 20:46:58 +00005518 header_keys = list(include_dict.keys())
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005519 for header in header_keys:
erg@google.com6317a9c2009-06-25 00:28:19 +00005520 (same_module, common_path) = FilesBelongToSameModule(abs_filename, header)
5521 fullpath = common_path + header
avakulenko@google.com59146752014-08-11 20:20:55 +00005522 if same_module and UpdateIncludeState(fullpath, include_dict, io):
erg@google.com6317a9c2009-06-25 00:28:19 +00005523 header_found = True
5524
5525 # If we can't find the header file for a .cc, assume it's because we don't
5526 # know where to look. In that case we'll give up as we're not sure they
5527 # didn't include it in the .h file.
5528 # TODO(unknown): Do a better job of finding .h files so we are confident that
5529 # not having the .h file means there isn't one.
5530 if filename.endswith('.cc') and not header_found:
5531 return
5532
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005533 # All the lines have been processed, report the errors found.
5534 for required_header_unstripped in required:
5535 template = required[required_header_unstripped][1]
avakulenko@google.com59146752014-08-11 20:20:55 +00005536 if required_header_unstripped.strip('<>"') not in include_dict:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005537 error(filename, required[required_header_unstripped][0],
5538 'build/include_what_you_use', 4,
5539 'Add #include ' + required_header_unstripped + ' for ' + template)
5540
5541
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005542_RE_PATTERN_EXPLICIT_MAKEPAIR = re.compile(r'\bmake_pair\s*<')
5543
5544
5545def CheckMakePairUsesDeduction(filename, clean_lines, linenum, error):
5546 """Check that make_pair's template arguments are deduced.
5547
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005548 G++ 4.6 in C++11 mode fails badly if make_pair's template arguments are
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005549 specified explicitly, and such use isn't intended in any case.
5550
5551 Args:
5552 filename: The name of the current file.
5553 clean_lines: A CleansedLines instance containing the file.
5554 linenum: The number of the line to check.
5555 error: The function to call with any errors found.
5556 """
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005557 line = clean_lines.elided[linenum]
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005558 match = _RE_PATTERN_EXPLICIT_MAKEPAIR.search(line)
5559 if match:
5560 error(filename, linenum, 'build/explicit_make_pair',
5561 4, # 4 = high confidence
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005562 'For C++11-compatibility, omit template arguments from make_pair'
5563 ' OR use pair directly OR if appropriate, construct a pair directly')
avakulenko@google.com59146752014-08-11 20:20:55 +00005564
5565
avakulenko@google.com59146752014-08-11 20:20:55 +00005566def CheckRedundantVirtual(filename, clean_lines, linenum, error):
5567 """Check if line contains a redundant "virtual" function-specifier.
5568
5569 Args:
5570 filename: The name of the current file.
5571 clean_lines: A CleansedLines instance containing the file.
5572 linenum: The number of the line to check.
5573 error: The function to call with any errors found.
5574 """
5575 # Look for "virtual" on current line.
5576 line = clean_lines.elided[linenum]
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005577 virtual = Match(r'^(.*)(\bvirtual\b)(.*)$', line)
avakulenko@google.com59146752014-08-11 20:20:55 +00005578 if not virtual: return
5579
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005580 # Ignore "virtual" keywords that are near access-specifiers. These
5581 # are only used in class base-specifier and do not apply to member
5582 # functions.
5583 if (Search(r'\b(public|protected|private)\s+$', virtual.group(1)) or
5584 Match(r'^\s+(public|protected|private)\b', virtual.group(3))):
5585 return
5586
5587 # Ignore the "virtual" keyword from virtual base classes. Usually
5588 # there is a column on the same line in these cases (virtual base
5589 # classes are rare in google3 because multiple inheritance is rare).
5590 if Match(r'^.*[^:]:[^:].*$', line): return
5591
avakulenko@google.com59146752014-08-11 20:20:55 +00005592 # Look for the next opening parenthesis. This is the start of the
5593 # parameter list (possibly on the next line shortly after virtual).
5594 # TODO(unknown): doesn't work if there are virtual functions with
5595 # decltype() or other things that use parentheses, but csearch suggests
5596 # that this is rare.
5597 end_col = -1
5598 end_line = -1
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005599 start_col = len(virtual.group(2))
Edward Lemur6d31ed52019-12-02 23:00:00 +00005600 for start_line in range(linenum, min(linenum + 3, clean_lines.NumLines())):
avakulenko@google.com59146752014-08-11 20:20:55 +00005601 line = clean_lines.elided[start_line][start_col:]
5602 parameter_list = Match(r'^([^(]*)\(', line)
5603 if parameter_list:
5604 # Match parentheses to find the end of the parameter list
5605 (_, end_line, end_col) = CloseExpression(
5606 clean_lines, start_line, start_col + len(parameter_list.group(1)))
5607 break
5608 start_col = 0
5609
5610 if end_col < 0:
5611 return # Couldn't find end of parameter list, give up
5612
5613 # Look for "override" or "final" after the parameter list
5614 # (possibly on the next few lines).
Edward Lemur6d31ed52019-12-02 23:00:00 +00005615 for i in range(end_line, min(end_line + 3, clean_lines.NumLines())):
avakulenko@google.com59146752014-08-11 20:20:55 +00005616 line = clean_lines.elided[i][end_col:]
5617 match = Search(r'\b(override|final)\b', line)
5618 if match:
5619 error(filename, linenum, 'readability/inheritance', 4,
5620 ('"virtual" is redundant since function is '
5621 'already declared as "%s"' % match.group(1)))
5622
5623 # Set end_col to check whole lines after we are done with the
5624 # first line.
5625 end_col = 0
5626 if Search(r'[^\w]\s*$', line):
5627 break
5628
5629
5630def CheckRedundantOverrideOrFinal(filename, clean_lines, linenum, error):
5631 """Check if line contains a redundant "override" or "final" virt-specifier.
5632
5633 Args:
5634 filename: The name of the current file.
5635 clean_lines: A CleansedLines instance containing the file.
5636 linenum: The number of the line to check.
5637 error: The function to call with any errors found.
5638 """
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005639 # Look for closing parenthesis nearby. We need one to confirm where
5640 # the declarator ends and where the virt-specifier starts to avoid
5641 # false positives.
avakulenko@google.com59146752014-08-11 20:20:55 +00005642 line = clean_lines.elided[linenum]
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005643 declarator_end = line.rfind(')')
5644 if declarator_end >= 0:
5645 fragment = line[declarator_end:]
5646 else:
5647 if linenum > 1 and clean_lines.elided[linenum - 1].rfind(')') >= 0:
5648 fragment = line
5649 else:
5650 return
5651
5652 # Check that at most one of "override" or "final" is present, not both
5653 if Search(r'\boverride\b', fragment) and Search(r'\bfinal\b', fragment):
avakulenko@google.com59146752014-08-11 20:20:55 +00005654 error(filename, linenum, 'readability/inheritance', 4,
5655 ('"override" is redundant since function is '
5656 'already declared as "final"'))
5657
5658
5659
5660
5661# Returns true if we are at a new block, and it is directly
5662# inside of a namespace.
5663def IsBlockInNameSpace(nesting_state, is_forward_declaration):
5664 """Checks that the new block is directly in a namespace.
5665
5666 Args:
5667 nesting_state: The _NestingState object that contains info about our state.
5668 is_forward_declaration: If the class is a forward declared class.
5669 Returns:
5670 Whether or not the new block is directly in a namespace.
5671 """
5672 if is_forward_declaration:
5673 if len(nesting_state.stack) >= 1 and (
5674 isinstance(nesting_state.stack[-1], _NamespaceInfo)):
5675 return True
5676 else:
5677 return False
5678
5679 return (len(nesting_state.stack) > 1 and
5680 nesting_state.stack[-1].check_namespace_indentation and
5681 isinstance(nesting_state.stack[-2], _NamespaceInfo))
5682
5683
5684def ShouldCheckNamespaceIndentation(nesting_state, is_namespace_indent_item,
5685 raw_lines_no_comments, linenum):
5686 """This method determines if we should apply our namespace indentation check.
5687
5688 Args:
5689 nesting_state: The current nesting state.
5690 is_namespace_indent_item: If we just put a new class on the stack, True.
5691 If the top of the stack is not a class, or we did not recently
5692 add the class, False.
5693 raw_lines_no_comments: The lines without the comments.
5694 linenum: The current line number we are processing.
5695
5696 Returns:
5697 True if we should apply our namespace indentation check. Currently, it
5698 only works for classes and namespaces inside of a namespace.
5699 """
5700
5701 is_forward_declaration = IsForwardClassDeclaration(raw_lines_no_comments,
5702 linenum)
5703
5704 if not (is_namespace_indent_item or is_forward_declaration):
5705 return False
5706
5707 # If we are in a macro, we do not want to check the namespace indentation.
5708 if IsMacroDefinition(raw_lines_no_comments, linenum):
5709 return False
5710
5711 return IsBlockInNameSpace(nesting_state, is_forward_declaration)
5712
5713
5714# Call this method if the line is directly inside of a namespace.
5715# If the line above is blank (excluding comments) or the start of
5716# an inner namespace, it cannot be indented.
5717def CheckItemIndentationInNamespace(filename, raw_lines_no_comments, linenum,
5718 error):
5719 line = raw_lines_no_comments[linenum]
5720 if Match(r'^\s+', line):
5721 error(filename, linenum, 'runtime/indentation_namespace', 4,
5722 'Do not indent within a namespace')
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005723
5724
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005725def ProcessLine(filename, file_extension, clean_lines, line,
5726 include_state, function_state, nesting_state, error,
5727 extra_check_functions=[]):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005728 """Processes a single line in the file.
5729
5730 Args:
5731 filename: Filename of the file that is being processed.
5732 file_extension: The extension (dot not included) of the file.
5733 clean_lines: An array of strings, each representing a line of the file,
5734 with comments stripped.
5735 line: Number of line being processed.
5736 include_state: An _IncludeState instance in which the headers are inserted.
5737 function_state: A _FunctionState instance which counts function lines, etc.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005738 nesting_state: A NestingState instance which maintains information about
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005739 the current stack of nested blocks being parsed.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005740 error: A callable to which errors are reported, which takes 4 arguments:
5741 filename, line number, error level, and message
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005742 extra_check_functions: An array of additional check functions that will be
5743 run on each source line. Each function takes 4
5744 arguments: filename, clean_lines, line, error
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005745 """
5746 raw_lines = clean_lines.raw_lines
erg@google.com35589e62010-11-17 18:58:16 +00005747 ParseNolintSuppressions(filename, raw_lines[line], line, error)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005748 nesting_state.Update(filename, clean_lines, line, error)
avakulenko@google.com59146752014-08-11 20:20:55 +00005749 CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line,
5750 error)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005751 if nesting_state.InAsmBlock(): return
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005752 CheckForFunctionLengths(filename, clean_lines, line, function_state, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005753 CheckForMultilineCommentsAndStrings(filename, clean_lines, line, error)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005754 CheckStyle(filename, clean_lines, line, file_extension, nesting_state, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005755 CheckLanguage(filename, clean_lines, line, file_extension, include_state,
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005756 nesting_state, error)
5757 CheckForNonConstReference(filename, clean_lines, line, nesting_state, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005758 CheckForNonStandardConstructs(filename, clean_lines, line,
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005759 nesting_state, error)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005760 CheckVlogArguments(filename, clean_lines, line, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005761 CheckPosixThreading(filename, clean_lines, line, error)
erg@google.com6317a9c2009-06-25 00:28:19 +00005762 CheckInvalidIncrement(filename, clean_lines, line, error)
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005763 CheckMakePairUsesDeduction(filename, clean_lines, line, error)
avakulenko@google.com59146752014-08-11 20:20:55 +00005764 CheckRedundantVirtual(filename, clean_lines, line, error)
5765 CheckRedundantOverrideOrFinal(filename, clean_lines, line, error)
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005766 for check_fn in extra_check_functions:
5767 check_fn(filename, clean_lines, line, error)
avakulenko@google.com17449932014-07-28 22:13:33 +00005768
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005769def FlagCxx11Features(filename, clean_lines, linenum, error):
5770 """Flag those c++11 features that we only allow in certain places.
5771
5772 Args:
5773 filename: The name of the current file.
5774 clean_lines: A CleansedLines instance containing the file.
5775 linenum: The number of the line to check.
5776 error: The function to call with any errors found.
5777 """
5778 line = clean_lines.elided[linenum]
5779
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005780 include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line)
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005781
5782 # Flag unapproved C++ TR1 headers.
5783 if include and include.group(1).startswith('tr1/'):
5784 error(filename, linenum, 'build/c++tr1', 5,
5785 ('C++ TR1 headers such as <%s> are unapproved.') % include.group(1))
5786
5787 # Flag unapproved C++11 headers.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005788 if include and include.group(1) in ('cfenv',
5789 'condition_variable',
5790 'fenv.h',
5791 'future',
5792 'mutex',
5793 'thread',
5794 'chrono',
5795 'ratio',
5796 'regex',
5797 'system_error',
5798 ):
5799 error(filename, linenum, 'build/c++11', 5,
5800 ('<%s> is an unapproved C++11 header.') % include.group(1))
5801
5802 # The only place where we need to worry about C++11 keywords and library
5803 # features in preprocessor directives is in macro definitions.
5804 if Match(r'\s*#', line) and not Match(r'\s*#\s*define\b', line): return
5805
5806 # These are classes and free functions. The classes are always
5807 # mentioned as std::*, but we only catch the free functions if
5808 # they're not found by ADL. They're alphabetical by header.
5809 for top_name in (
5810 # type_traits
5811 'alignment_of',
5812 'aligned_union',
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005813 ):
5814 if Search(r'\bstd::%s\b' % top_name, line):
5815 error(filename, linenum, 'build/c++11', 5,
5816 ('std::%s is an unapproved C++11 class or function. Send c-style '
5817 'an example of where it would make your code more readable, and '
5818 'they may let you use it.') % top_name)
5819
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005820
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005821def FlagCxx14Features(filename, clean_lines, linenum, error):
5822 """Flag those C++14 features that we restrict.
5823
5824 Args:
5825 filename: The name of the current file.
5826 clean_lines: A CleansedLines instance containing the file.
5827 linenum: The number of the line to check.
5828 error: The function to call with any errors found.
5829 """
5830 line = clean_lines.elided[linenum]
5831
5832 include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line)
5833
5834 # Flag unapproved C++14 headers.
5835 if include and include.group(1) in ('scoped_allocator', 'shared_mutex'):
5836 error(filename, linenum, 'build/c++14', 5,
5837 ('<%s> is an unapproved C++14 header.') % include.group(1))
5838
5839
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005840def ProcessFileData(filename, file_extension, lines, error,
5841 extra_check_functions=[]):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005842 """Performs lint checks and reports any errors to the given error function.
5843
5844 Args:
5845 filename: Filename of the file that is being processed.
5846 file_extension: The extension (dot not included) of the file.
5847 lines: An array of strings, each representing a line of the file, with the
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005848 last element being empty if the file is terminated with a newline.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005849 error: A callable to which errors are reported, which takes 4 arguments:
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005850 filename, line number, error level, and message
5851 extra_check_functions: An array of additional check functions that will be
5852 run on each source line. Each function takes 4
5853 arguments: filename, clean_lines, line, error
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005854 """
5855 lines = (['// marker so line numbers and indices both start at 1'] + lines +
5856 ['// marker so line numbers end in a known way'])
5857
5858 include_state = _IncludeState()
5859 function_state = _FunctionState()
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005860 nesting_state = NestingState()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005861
erg@google.com35589e62010-11-17 18:58:16 +00005862 ResetNolintSuppressions()
5863
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005864 CheckForCopyright(filename, lines, error)
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005865 ProcessGlobalSuppresions(lines)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005866 RemoveMultiLineComments(filename, lines, error)
5867 clean_lines = CleansedLines(lines)
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005868
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00005869 if file_extension == 'h':
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005870 CheckForHeaderGuard(filename, clean_lines, error)
5871
Edward Lemur6d31ed52019-12-02 23:00:00 +00005872 for line in range(clean_lines.NumLines()):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005873 ProcessLine(filename, file_extension, clean_lines, line,
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005874 include_state, function_state, nesting_state, error,
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005875 extra_check_functions)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005876 FlagCxx11Features(filename, clean_lines, line, error)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005877 nesting_state.CheckCompletedBlocks(filename, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005878
5879 CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error)
skym@chromium.org3990c412016-02-05 20:55:12 +00005880
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005881 # Check that the .cc file has included its header if it exists.
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005882 if _IsSourceExtension(file_extension):
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005883 CheckHeaderFileIncluded(filename, include_state, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005884
5885 # We check here rather than inside ProcessLine so that we see raw
5886 # lines rather than "cleaned" lines.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005887 CheckForBadCharacters(filename, lines, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005888
5889 CheckForNewlineAtEOF(filename, lines, error)
5890
avakulenko@google.com17449932014-07-28 22:13:33 +00005891def ProcessConfigOverrides(filename):
5892 """ Loads the configuration files and processes the config overrides.
5893
5894 Args:
5895 filename: The name of the file being processed by the linter.
5896
5897 Returns:
5898 False if the current |filename| should not be processed further.
5899 """
5900
5901 abs_filename = os.path.abspath(filename)
5902 cfg_filters = []
5903 keep_looking = True
5904 while keep_looking:
5905 abs_path, base_name = os.path.split(abs_filename)
5906 if not base_name:
5907 break # Reached the root directory.
5908
5909 cfg_file = os.path.join(abs_path, "CPPLINT.cfg")
5910 abs_filename = abs_path
5911 if not os.path.isfile(cfg_file):
5912 continue
5913
5914 try:
5915 with open(cfg_file) as file_handle:
5916 for line in file_handle:
5917 line, _, _ = line.partition('#') # Remove comments.
5918 if not line.strip():
5919 continue
5920
5921 name, _, val = line.partition('=')
5922 name = name.strip()
5923 val = val.strip()
5924 if name == 'set noparent':
5925 keep_looking = False
5926 elif name == 'filter':
5927 cfg_filters.append(val)
5928 elif name == 'exclude_files':
5929 # When matching exclude_files pattern, use the base_name of
5930 # the current file name or the directory name we are processing.
5931 # For example, if we are checking for lint errors in /foo/bar/baz.cc
5932 # and we found the .cfg file at /foo/CPPLINT.cfg, then the config
5933 # file's "exclude_files" filter is meant to be checked against "bar"
5934 # and not "baz" nor "bar/baz.cc".
5935 if base_name:
5936 pattern = re.compile(val)
5937 if pattern.match(base_name):
5938 sys.stderr.write('Ignoring "%s": file excluded by "%s". '
5939 'File path component "%s" matches '
5940 'pattern "%s"\n' %
5941 (filename, cfg_file, base_name, val))
5942 return False
avakulenko@google.com68a4fa62014-08-25 16:26:18 +00005943 elif name == 'linelength':
5944 global _line_length
5945 try:
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +00005946 _line_length = int(val)
avakulenko@google.com68a4fa62014-08-25 16:26:18 +00005947 except ValueError:
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +00005948 sys.stderr.write('Line length must be numeric.')
avakulenko@google.com17449932014-07-28 22:13:33 +00005949 else:
5950 sys.stderr.write(
5951 'Invalid configuration option (%s) in file %s\n' %
5952 (name, cfg_file))
5953
5954 except IOError:
5955 sys.stderr.write(
5956 "Skipping config file '%s': Can't open for reading\n" % cfg_file)
5957 keep_looking = False
5958
5959 # Apply all the accumulated filters in reverse order (top-level directory
5960 # config options having the least priority).
5961 for filter in reversed(cfg_filters):
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +00005962 _AddFilters(filter)
avakulenko@google.com17449932014-07-28 22:13:33 +00005963
5964 return True
5965
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005966
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005967def ProcessFile(filename, vlevel, extra_check_functions=[]):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005968 """Does google-lint on a single file.
5969
5970 Args:
5971 filename: The name of the file to parse.
5972
5973 vlevel: The level of errors to report. Every error of confidence
5974 >= verbose_level will be reported. 0 is a good default.
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005975
5976 extra_check_functions: An array of additional check functions that will be
5977 run on each source line. Each function takes 4
5978 arguments: filename, clean_lines, line, error
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005979 """
5980
5981 _SetVerboseLevel(vlevel)
avakulenko@google.com17449932014-07-28 22:13:33 +00005982 _BackupFilters()
5983
5984 if not ProcessConfigOverrides(filename):
5985 _RestoreFilters()
5986 return
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005987
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005988 lf_lines = []
5989 crlf_lines = []
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005990 try:
5991 # Support the UNIX convention of using "-" for stdin. Note that
5992 # we are not opening the file with universal newline support
5993 # (which codecs doesn't support anyway), so the resulting lines do
5994 # contain trailing '\r' characters if we are reading a file that
5995 # has CRLF endings.
5996 # If after the split a trailing '\r' is present, it is removed
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005997 # below.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005998 if filename == '-':
5999 lines = codecs.StreamReaderWriter(sys.stdin,
6000 codecs.getreader('utf8'),
6001 codecs.getwriter('utf8'),
6002 'replace').read().split('\n')
6003 else:
6004 lines = codecs.open(filename, 'r', 'utf8', 'replace').read().split('\n')
6005
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006006 # Remove trailing '\r'.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00006007 # The -1 accounts for the extra trailing blank line we get from split()
6008 for linenum in range(len(lines) - 1):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006009 if lines[linenum].endswith('\r'):
6010 lines[linenum] = lines[linenum].rstrip('\r')
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00006011 crlf_lines.append(linenum + 1)
6012 else:
6013 lf_lines.append(linenum + 1)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006014
6015 except IOError:
6016 sys.stderr.write(
6017 "Skipping input '%s': Can't open for reading\n" % filename)
avakulenko@google.com17449932014-07-28 22:13:33 +00006018 _RestoreFilters()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006019 return
6020
6021 # Note, if no dot is found, this will give the entire filename as the ext.
6022 file_extension = filename[filename.rfind('.') + 1:]
6023
6024 # When reading from stdin, the extension is unknown, so no cpplint tests
6025 # should rely on the extension.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00006026 if filename != '-' and file_extension not in _valid_extensions:
6027 sys.stderr.write('Ignoring %s; not a valid file name '
6028 '(%s)\n' % (filename, ', '.join(_valid_extensions)))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006029 else:
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00006030 ProcessFileData(filename, file_extension, lines, Error,
6031 extra_check_functions)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00006032
6033 # If end-of-line sequences are a mix of LF and CR-LF, issue
6034 # warnings on the lines with CR.
6035 #
6036 # Don't issue any warnings if all lines are uniformly LF or CR-LF,
6037 # since critique can handle these just fine, and the style guide
6038 # doesn't dictate a particular end of line sequence.
6039 #
6040 # We can't depend on os.linesep to determine what the desired
6041 # end-of-line sequence should be, since that will return the
6042 # server-side end-of-line sequence.
6043 if lf_lines and crlf_lines:
6044 # Warn on every line with CR. An alternative approach might be to
6045 # check whether the file is mostly CRLF or just LF, and warn on the
6046 # minority, we bias toward LF here since most tools prefer LF.
6047 for linenum in crlf_lines:
6048 Error(filename, linenum, 'whitespace/newline', 1,
6049 'Unexpected \\r (^M) found; better to use only \\n')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006050
avakulenko@google.com17449932014-07-28 22:13:33 +00006051 _RestoreFilters()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006052
6053
6054def PrintUsage(message):
6055 """Prints a brief usage string and exits, optionally with an error message.
6056
6057 Args:
6058 message: The optional error message.
6059 """
6060 sys.stderr.write(_USAGE)
6061 if message:
6062 sys.exit('\nFATAL ERROR: ' + message)
6063 else:
6064 sys.exit(1)
6065
6066
6067def PrintCategories():
6068 """Prints a list of all the error-categories used by error messages.
6069
6070 These are the categories used to filter messages via --filter.
6071 """
erg@google.com35589e62010-11-17 18:58:16 +00006072 sys.stderr.write(''.join(' %s\n' % cat for cat in _ERROR_CATEGORIES))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006073 sys.exit(0)
6074
6075
6076def ParseArguments(args):
6077 """Parses the command line arguments.
6078
6079 This may set the output format and verbosity level as side-effects.
6080
6081 Args:
6082 args: The command line arguments:
6083
6084 Returns:
6085 The list of filenames to lint.
6086 """
6087 try:
6088 (opts, filenames) = getopt.getopt(args, '', ['help', 'output=', 'verbose=',
Jordan Bayles91a32c52019-02-22 21:28:17 +00006089 'headers=', # We understand but ignore headers.
erg@google.com26970fa2009-11-17 18:07:32 +00006090 'counting=',
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00006091 'filter=',
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00006092 'root=',
6093 'linelength=',
sdefresne263e9282016-07-19 02:14:22 -07006094 'extensions=',
Jordan Bayles91a32c52019-02-22 21:28:17 +00006095 'project_root=',
6096 'repository='])
6097 except getopt.GetoptError as e:
6098 PrintUsage('Invalid arguments: {}'.format(e))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006099
6100 verbosity = _VerboseLevel()
6101 output_format = _OutputFormat()
6102 filters = ''
erg@google.com26970fa2009-11-17 18:07:32 +00006103 counting_style = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006104
6105 for (opt, val) in opts:
6106 if opt == '--help':
6107 PrintUsage(None)
6108 elif opt == '--output':
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00006109 if val not in ('emacs', 'vs7', 'eclipse'):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00006110 PrintUsage('The only allowed output formats are emacs, vs7 and eclipse.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006111 output_format = val
6112 elif opt == '--verbose':
6113 verbosity = int(val)
6114 elif opt == '--filter':
6115 filters = val
erg@google.com6317a9c2009-06-25 00:28:19 +00006116 if not filters:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006117 PrintCategories()
erg@google.com26970fa2009-11-17 18:07:32 +00006118 elif opt == '--counting':
6119 if val not in ('total', 'toplevel', 'detailed'):
6120 PrintUsage('Valid counting options are total, toplevel, and detailed')
6121 counting_style = val
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00006122 elif opt == '--root':
6123 global _root
6124 _root = val
Jordan Bayles91a32c52019-02-22 21:28:17 +00006125 elif opt == '--project_root' or opt == "--repository":
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00006126 global _project_root
6127 _project_root = val
6128 if not os.path.isabs(_project_root):
6129 PrintUsage('Project root must be an absolute path.')
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00006130 elif opt == '--linelength':
6131 global _line_length
6132 try:
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +00006133 _line_length = int(val)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00006134 except ValueError:
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +00006135 PrintUsage('Line length must be digits.')
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00006136 elif opt == '--extensions':
6137 global _valid_extensions
6138 try:
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +00006139 _valid_extensions = set(val.split(','))
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00006140 except ValueError:
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +00006141 PrintUsage('Extensions must be comma separated list.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006142
6143 if not filenames:
6144 PrintUsage('No files were specified.')
6145
6146 _SetOutputFormat(output_format)
6147 _SetVerboseLevel(verbosity)
6148 _SetFilters(filters)
erg@google.com26970fa2009-11-17 18:07:32 +00006149 _SetCountingStyle(counting_style)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006150
6151 return filenames
6152
6153
6154def main():
6155 filenames = ParseArguments(sys.argv[1:])
6156
6157 # Change stderr to write with replacement characters so we don't die
6158 # if we try to print something containing non-ASCII characters.
Edward Lemur6d31ed52019-12-02 23:00:00 +00006159 # We use sys.stderr.buffer in Python 3, since StreamReaderWriter writes bytes
6160 # to the specified stream.
6161 sys.stderr = codecs.StreamReaderWriter(
6162 getattr(sys.stderr, 'buffer', sys.stderr),
6163 codecs.getreader('utf8'), codecs.getwriter('utf8'), 'replace')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006164
erg@google.com26970fa2009-11-17 18:07:32 +00006165 _cpplint_state.ResetErrorCounts()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006166 for filename in filenames:
6167 ProcessFile(filename, _cpplint_state.verbose_level)
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00006168 _cpplint_state.PrintErrorCounts()
erg@google.com26970fa2009-11-17 18:07:32 +00006169
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006170 sys.exit(_cpplint_state.error_count > 0)
6171
6172
6173if __name__ == '__main__':
6174 main()