blob: f7ad8d8b71be75282bc9d880bd85b80ded16a717 [file] [log] [blame]
erg@chromium.orgd528f8b2012-05-11 17:31:08 +00001#!/usr/bin/env python
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002#
erg@google.com26970fa2009-11-17 18:07:32 +00003# Copyright (c) 2009 Google Inc. All rights reserved.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004#
erg@google.com26970fa2009-11-17 18:07:32 +00005# Redistribution and use in source and binary forms, with or without
6# modification, are permitted provided that the following conditions are
7# met:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00008#
erg@google.com26970fa2009-11-17 18:07:32 +00009# * Redistributions of source code must retain the above copyright
10# notice, this list of conditions and the following disclaimer.
11# * Redistributions in binary form must reproduce the above
12# copyright notice, this list of conditions and the following disclaimer
13# in the documentation and/or other materials provided with the
14# distribution.
15# * Neither the name of Google Inc. nor the names of its
16# contributors may be used to endorse or promote products derived from
17# this software without specific prior written permission.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000018#
erg@google.com26970fa2009-11-17 18:07:32 +000019# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000030
agablef39c3332016-09-26 09:35:42 -070031# pylint: skip-file
32
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000033"""Does google-lint on c++ files.
34
35The goal of this script is to identify places in the code that *may*
36be in non-compliance with google style. It does not attempt to fix
37up these problems -- the point is to educate. It does also not
38attempt to find all problems, or to ensure that everything it does
39find is legitimately a problem.
40
41In particular, we can get very confused by /* and // inside strings!
42We do a small hack, which is to ignore //'s with "'s after them on the
43same line, but it is far from perfect (in either direction).
44"""
45
46import codecs
mazda@chromium.org3fffcec2013-06-07 01:04:53 +000047import copy
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000048import getopt
49import math # for log
50import os
51import re
52import sre_compile
53import string
54import sys
55import unicodedata
56
57
Edward Lemur6d31ed52019-12-02 23:00:00 +000058_USAGE = r"""
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000059Syntax: cpplint.py [--verbose=#] [--output=vs7] [--filter=-x,+y,...]
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +000060 [--counting=total|toplevel|detailed] [--root=subdir]
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +000061 [--linelength=digits]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000062 <file> [file] ...
63
64 The style guidelines this tries to follow are those in
Alexandr Ilinff294c32017-04-27 15:57:40 +020065 https://google.github.io/styleguide/cppguide.html
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000066
67 Every problem is given a confidence score from 1-5, with 5 meaning we are
68 certain of the problem, and 1 meaning it could be a legitimate construct.
69 This will miss some errors, and is not a substitute for a code review.
70
erg@google.com35589e62010-11-17 18:58:16 +000071 To suppress false-positive errors of a certain category, add a
72 'NOLINT(category)' comment to the line. NOLINT or NOLINT(*)
73 suppresses errors of all categories on that line.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000074
75 The files passed in will be linted; at least one file must be provided.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +000076 Default linted extensions are .cc, .cpp, .cu, .cuh and .h. Change the
77 extensions with the --extensions flag.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000078
79 Flags:
80
81 output=vs7
82 By default, the output is formatted to ease emacs parsing. Visual Studio
83 compatible output (vs7) may also be used. Other formats are unsupported.
84
85 verbose=#
86 Specify a number 0-5 to restrict errors to certain verbosity levels.
87
88 filter=-x,+y,...
89 Specify a comma-separated list of category-filters to apply: only
90 error messages whose category names pass the filters will be printed.
91 (Category names are printed with the message and look like
92 "[whitespace/indent]".) Filters are evaluated left to right.
93 "-FOO" and "FOO" means "do not print categories that start with FOO".
94 "+FOO" means "do print categories that start with FOO".
95
96 Examples: --filter=-whitespace,+whitespace/braces
97 --filter=whitespace,runtime/printf,+runtime/printf_format
98 --filter=-,+build/include_what_you_use
99
100 To see a list of all the categories used in cpplint, pass no arg:
101 --filter=
erg@google.com26970fa2009-11-17 18:07:32 +0000102
103 counting=total|toplevel|detailed
104 The total number of errors found is always printed. If
105 'toplevel' is provided, then the count of errors in each of
106 the top-level categories like 'build' and 'whitespace' will
107 also be printed. If 'detailed' is provided, then a count
108 is provided for each category like 'build/class'.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +0000109
110 root=subdir
111 The root directory used for deriving header guard CPP variable.
112 By default, the header guard CPP variable is calculated as the relative
113 path to the directory that contains .git, .hg, or .svn. When this flag
114 is specified, the relative path is calculated from the specified
115 directory. If the specified directory does not exist, this flag is
116 ignored.
117
118 Examples:
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +0000119 Assuming that src/.git exists, the header guard CPP variables for
120 src/chrome/browser/ui/browser.h are:
mazda@chromium.org3fffcec2013-06-07 01:04:53 +0000121
122 No flag => CHROME_BROWSER_UI_BROWSER_H_
123 --root=chrome => BROWSER_UI_BROWSER_H_
124 --root=chrome/browser => UI_BROWSER_H_
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000125
126 linelength=digits
127 This is the allowed line length for the project. The default value is
128 80 characters.
129
130 Examples:
131 --linelength=120
132
133 extensions=extension,extension,...
134 The allowed file extensions that cpplint will check
135
136 Examples:
137 --extensions=hpp,cpp
avakulenko@google.com17449932014-07-28 22:13:33 +0000138
139 cpplint.py supports per-directory configurations specified in CPPLINT.cfg
140 files. CPPLINT.cfg file can contain a number of key=value pairs.
141 Currently the following options are supported:
142
143 set noparent
144 filter=+filter1,-filter2,...
145 exclude_files=regex
avakulenko@google.com68a4fa62014-08-25 16:26:18 +0000146 linelength=80
avakulenko@google.com17449932014-07-28 22:13:33 +0000147
148 "set noparent" option prevents cpplint from traversing directory tree
149 upwards looking for more .cfg files in parent directories. This option
150 is usually placed in the top-level project directory.
151
152 The "filter" option is similar in function to --filter flag. It specifies
153 message filters in addition to the |_DEFAULT_FILTERS| and those specified
154 through --filter command-line flag.
155
156 "exclude_files" allows to specify a regular expression to be matched against
157 a file name. If the expression matches, the file is skipped and not run
158 through liner.
159
avakulenko@google.com68a4fa62014-08-25 16:26:18 +0000160 "linelength" allows to specify the allowed line length for the project.
161
avakulenko@google.com17449932014-07-28 22:13:33 +0000162 CPPLINT.cfg has an effect on files in the same directory and all
163 sub-directories, unless overridden by a nested configuration file.
164
165 Example file:
166 filter=-build/include_order,+build/include_alpha
167 exclude_files=.*\.cc
168
169 The above example disables build/include_order warning and enables
170 build/include_alpha as well as excludes all .cc from being
171 processed by linter, in the current directory (where the .cfg
172 file is located) and all sub-directories.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000173"""
174
175# We categorize each error message we print. Here are the categories.
176# We want an explicit list so we can list them all in cpplint --filter=.
177# If you add a new error message with a new category, add it to the list
178# here! cpplint_unittest.py should tell you if you forget to do this.
erg@google.com35589e62010-11-17 18:58:16 +0000179_ERROR_CATEGORIES = [
avakulenko@google.com255f2be2014-12-05 22:19:55 +0000180 'build/class',
181 'build/c++11',
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000182 'build/c++14',
183 'build/c++tr1',
avakulenko@google.com255f2be2014-12-05 22:19:55 +0000184 'build/deprecated',
185 'build/endif_comment',
186 'build/explicit_make_pair',
187 'build/forward_decl',
188 'build/header_guard',
189 'build/include',
190 'build/include_alpha',
191 'build/include_order',
192 'build/include_what_you_use',
193 'build/namespaces',
194 'build/printf_format',
195 'build/storage_class',
196 'legal/copyright',
197 'readability/alt_tokens',
198 'readability/braces',
199 'readability/casting',
200 'readability/check',
201 'readability/constructors',
202 'readability/fn_size',
avakulenko@google.com255f2be2014-12-05 22:19:55 +0000203 'readability/inheritance',
204 'readability/multiline_comment',
205 'readability/multiline_string',
206 'readability/namespace',
207 'readability/nolint',
208 'readability/nul',
209 'readability/strings',
210 'readability/todo',
211 'readability/utf8',
212 'runtime/arrays',
213 'runtime/casting',
214 'runtime/explicit',
215 'runtime/int',
216 'runtime/init',
217 'runtime/invalid_increment',
218 'runtime/member_string_references',
219 'runtime/memset',
220 'runtime/indentation_namespace',
221 'runtime/operator',
222 'runtime/printf',
223 'runtime/printf_format',
224 'runtime/references',
225 'runtime/string',
226 'runtime/threadsafe_fn',
227 'runtime/vlog',
228 'whitespace/blank_line',
229 'whitespace/braces',
230 'whitespace/comma',
231 'whitespace/comments',
232 'whitespace/empty_conditional_body',
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000233 'whitespace/empty_if_body',
avakulenko@google.com255f2be2014-12-05 22:19:55 +0000234 'whitespace/empty_loop_body',
235 'whitespace/end_of_line',
236 'whitespace/ending_newline',
237 'whitespace/forcolon',
238 'whitespace/indent',
239 'whitespace/line_length',
240 'whitespace/newline',
241 'whitespace/operators',
242 'whitespace/parens',
243 'whitespace/semicolon',
244 'whitespace/tab',
245 'whitespace/todo',
246 ]
247
248# These error categories are no longer enforced by cpplint, but for backwards-
249# compatibility they may still appear in NOLINT comments.
250_LEGACY_ERROR_CATEGORIES = [
251 'readability/streams',
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000252 'readability/function',
avakulenko@google.com255f2be2014-12-05 22:19:55 +0000253 ]
erg@google.com6317a9c2009-06-25 00:28:19 +0000254
avakulenko@google.comd39bbb52014-06-04 22:55:20 +0000255# The default state of the category filter. This is overridden by the --filter=
erg@google.com6317a9c2009-06-25 00:28:19 +0000256# flag. By default all errors are on, so only add here categories that should be
257# off by default (i.e., categories that must be enabled by the --filter= flags).
258# All entries here should start with a '-' or '+', as in the --filter= flag.
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +0000259_DEFAULT_FILTERS = ['-build/include_alpha']
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000260
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000261# The default list of categories suppressed for C (not C++) files.
262_DEFAULT_C_SUPPRESSED_CATEGORIES = [
263 'readability/casting',
264 ]
265
266# The default list of categories suppressed for Linux Kernel files.
267_DEFAULT_KERNEL_SUPPRESSED_CATEGORIES = [
268 'whitespace/tab',
269 ]
270
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000271# We used to check for high-bit characters, but after much discussion we
272# decided those were OK, as long as they were in UTF-8 and didn't represent
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +0000273# hard-coded international strings, which belong in a separate i18n file.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000274
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000275# C++ headers
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000276_CPP_HEADERS = frozenset([
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000277 # Legacy
278 'algobase.h',
279 'algo.h',
280 'alloc.h',
281 'builtinbuf.h',
282 'bvector.h',
283 'complex.h',
284 'defalloc.h',
285 'deque.h',
286 'editbuf.h',
287 'fstream.h',
288 'function.h',
289 'hash_map',
290 'hash_map.h',
291 'hash_set',
292 'hash_set.h',
293 'hashtable.h',
294 'heap.h',
295 'indstream.h',
296 'iomanip.h',
297 'iostream.h',
298 'istream.h',
299 'iterator.h',
300 'list.h',
301 'map.h',
302 'multimap.h',
303 'multiset.h',
304 'ostream.h',
305 'pair.h',
306 'parsestream.h',
307 'pfstream.h',
308 'procbuf.h',
309 'pthread_alloc',
310 'pthread_alloc.h',
311 'rope',
312 'rope.h',
313 'ropeimpl.h',
314 'set.h',
315 'slist',
316 'slist.h',
317 'stack.h',
318 'stdiostream.h',
319 'stl_alloc.h',
320 'stl_relops.h',
321 'streambuf.h',
322 'stream.h',
323 'strfile.h',
324 'strstream.h',
325 'tempbuf.h',
326 'tree.h',
327 'type_traits.h',
328 'vector.h',
329 # 17.6.1.2 C++ library headers
330 'algorithm',
331 'array',
332 'atomic',
333 'bitset',
334 'chrono',
335 'codecvt',
336 'complex',
337 'condition_variable',
338 'deque',
339 'exception',
340 'forward_list',
341 'fstream',
342 'functional',
343 'future',
344 'initializer_list',
345 'iomanip',
346 'ios',
347 'iosfwd',
348 'iostream',
349 'istream',
350 'iterator',
351 'limits',
352 'list',
353 'locale',
354 'map',
355 'memory',
356 'mutex',
357 'new',
358 'numeric',
359 'ostream',
360 'queue',
361 'random',
362 'ratio',
363 'regex',
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000364 'scoped_allocator',
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000365 'set',
366 'sstream',
367 'stack',
368 'stdexcept',
369 'streambuf',
370 'string',
Jasper Chapman-Black9ab047e2019-11-07 15:51:54 +0000371 'string_view',
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000372 'strstream',
373 'system_error',
374 'thread',
375 'tuple',
376 'typeindex',
377 'typeinfo',
378 'type_traits',
379 'unordered_map',
380 'unordered_set',
381 'utility',
382 'valarray',
383 'vector',
384 # 17.6.1.2 C++ headers for C library facilities
385 'cassert',
386 'ccomplex',
387 'cctype',
388 'cerrno',
389 'cfenv',
390 'cfloat',
391 'cinttypes',
392 'ciso646',
393 'climits',
394 'clocale',
395 'cmath',
396 'csetjmp',
397 'csignal',
398 'cstdalign',
399 'cstdarg',
400 'cstdbool',
401 'cstddef',
402 'cstdint',
403 'cstdio',
404 'cstdlib',
405 'cstring',
406 'ctgmath',
407 'ctime',
408 'cuchar',
409 'cwchar',
410 'cwctype',
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000411 ])
412
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000413# Type names
414_TYPES = re.compile(
415 r'^(?:'
416 # [dcl.type.simple]
417 r'(char(16_t|32_t)?)|wchar_t|'
418 r'bool|short|int|long|signed|unsigned|float|double|'
419 # [support.types]
420 r'(ptrdiff_t|size_t|max_align_t|nullptr_t)|'
421 # [cstdint.syn]
422 r'(u?int(_fast|_least)?(8|16|32|64)_t)|'
423 r'(u?int(max|ptr)_t)|'
424 r')$')
425
avakulenko@google.comd39bbb52014-06-04 22:55:20 +0000426
avakulenko@google.com59146752014-08-11 20:20:55 +0000427# These headers are excluded from [build/include] and [build/include_order]
428# checks:
429# - Anything not following google file name conventions (containing an
430# uppercase character, such as Python.h or nsStringAPI.h, for example).
431# - Lua headers.
432_THIRD_PARTY_HEADERS_PATTERN = re.compile(
433 r'^(?:[^/]*[A-Z][^/]*\.h|lua\.h|lauxlib\.h|lualib\.h)$')
434
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000435# Pattern for matching FileInfo.BaseName() against test file name
436_TEST_FILE_SUFFIX = r'(_test|_unittest|_regtest)$'
437
438# Pattern that matches only complete whitespace, possibly across multiple lines.
439_EMPTY_CONDITIONAL_BODY_PATTERN = re.compile(r'^\s*$', re.DOTALL)
avakulenko@google.com59146752014-08-11 20:20:55 +0000440
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000441# Assertion macros. These are defined in base/logging.h and
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000442# testing/base/public/gunit.h.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000443_CHECK_MACROS = [
erg@google.com6317a9c2009-06-25 00:28:19 +0000444 'DCHECK', 'CHECK',
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000445 'EXPECT_TRUE', 'ASSERT_TRUE',
446 'EXPECT_FALSE', 'ASSERT_FALSE',
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000447 ]
448
erg@google.com6317a9c2009-06-25 00:28:19 +0000449# Replacement macros for CHECK/DCHECK/EXPECT_TRUE/EXPECT_FALSE
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000450_CHECK_REPLACEMENT = dict([(m, {}) for m in _CHECK_MACROS])
451
452for op, replacement in [('==', 'EQ'), ('!=', 'NE'),
453 ('>=', 'GE'), ('>', 'GT'),
454 ('<=', 'LE'), ('<', 'LT')]:
erg@google.com6317a9c2009-06-25 00:28:19 +0000455 _CHECK_REPLACEMENT['DCHECK'][op] = 'DCHECK_%s' % replacement
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000456 _CHECK_REPLACEMENT['CHECK'][op] = 'CHECK_%s' % replacement
457 _CHECK_REPLACEMENT['EXPECT_TRUE'][op] = 'EXPECT_%s' % replacement
458 _CHECK_REPLACEMENT['ASSERT_TRUE'][op] = 'ASSERT_%s' % replacement
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000459
460for op, inv_replacement in [('==', 'NE'), ('!=', 'EQ'),
461 ('>=', 'LT'), ('>', 'LE'),
462 ('<=', 'GT'), ('<', 'GE')]:
463 _CHECK_REPLACEMENT['EXPECT_FALSE'][op] = 'EXPECT_%s' % inv_replacement
464 _CHECK_REPLACEMENT['ASSERT_FALSE'][op] = 'ASSERT_%s' % inv_replacement
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000465
mazda@chromium.org3fffcec2013-06-07 01:04:53 +0000466# Alternative tokens and their replacements. For full list, see section 2.5
467# Alternative tokens [lex.digraph] in the C++ standard.
468#
469# Digraphs (such as '%:') are not included here since it's a mess to
470# match those on a word boundary.
471_ALT_TOKEN_REPLACEMENT = {
472 'and': '&&',
473 'bitor': '|',
474 'or': '||',
475 'xor': '^',
476 'compl': '~',
477 'bitand': '&',
478 'and_eq': '&=',
479 'or_eq': '|=',
480 'xor_eq': '^=',
481 'not': '!',
482 'not_eq': '!='
483 }
484
485# Compile regular expression that matches all the above keywords. The "[ =()]"
486# bit is meant to avoid matching these keywords outside of boolean expressions.
487#
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000488# False positives include C-style multi-line comments and multi-line strings
489# but those have always been troublesome for cpplint.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +0000490_ALT_TOKEN_REPLACEMENT_PATTERN = re.compile(
491 r'[ =()](' + ('|'.join(_ALT_TOKEN_REPLACEMENT.keys())) + r')(?=[ (]|$)')
492
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000493
494# These constants define types of headers for use with
495# _IncludeState.CheckNextIncludeOrder().
496_C_SYS_HEADER = 1
497_CPP_SYS_HEADER = 2
498_LIKELY_MY_HEADER = 3
499_POSSIBLE_MY_HEADER = 4
500_OTHER_HEADER = 5
501
mazda@chromium.org3fffcec2013-06-07 01:04:53 +0000502# These constants define the current inline assembly state
503_NO_ASM = 0 # Outside of inline assembly block
504_INSIDE_ASM = 1 # Inside inline assembly block
505_END_ASM = 2 # Last line of inline assembly block
506_BLOCK_ASM = 3 # The whole block is an inline assembly block
507
508# Match start of assembly blocks
509_MATCH_ASM = re.compile(r'^\s*(?:asm|_asm|__asm|__asm__)'
510 r'(?:\s+(volatile|__volatile__))?'
511 r'\s*[{(]')
512
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000513# Match strings that indicate we're working on a C (not C++) file.
514_SEARCH_C_FILE = re.compile(r'\b(?:LINT_C_FILE|'
515 r'vim?:\s*.*(\s*|:)filetype=c(\s*|:|$))')
516
517# Match string that indicates we're working on a Linux Kernel file.
518_SEARCH_KERNEL_FILE = re.compile(r'\b(?:LINT_KERNEL_FILE)')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000519
520_regexp_compile_cache = {}
521
erg@google.com35589e62010-11-17 18:58:16 +0000522# {str, set(int)}: a map from error categories to sets of linenumbers
523# on which those errors are expected and should be suppressed.
524_error_suppressions = {}
525
mazda@chromium.org3fffcec2013-06-07 01:04:53 +0000526# The root directory used for deriving header guard CPP variable.
527# This is set by --root flag.
528_root = None
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +0000529
530# The project root directory. Used for deriving header guard CPP variable.
531# This is set by --project_root flag. Must be an absolute path.
532_project_root = None
sdefresne263e9282016-07-19 02:14:22 -0700533
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000534# The allowed line length of files.
535# This is set by --linelength flag.
536_line_length = 80
537
538# The allowed extensions for file names
539# This is set by --extensions flag.
540_valid_extensions = set(['cc', 'h', 'cpp', 'cu', 'cuh'])
541
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000542# {str, bool}: a map from error categories to booleans which indicate if the
543# category should be suppressed for every line.
544_global_error_suppressions = {}
545
546
erg@google.com35589e62010-11-17 18:58:16 +0000547def ParseNolintSuppressions(filename, raw_line, linenum, error):
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000548 """Updates the global list of line error-suppressions.
erg@google.com35589e62010-11-17 18:58:16 +0000549
550 Parses any NOLINT comments on the current line, updating the global
551 error_suppressions store. Reports an error if the NOLINT comment
552 was malformed.
553
554 Args:
555 filename: str, the name of the input file.
556 raw_line: str, the line of input text, with comments.
557 linenum: int, the number of the current line.
558 error: function, an error handler.
559 """
avakulenko@google.com59146752014-08-11 20:20:55 +0000560 matched = Search(r'\bNOLINT(NEXTLINE)?\b(\([^)]+\))?', raw_line)
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +0000561 if matched:
avakulenko@google.com59146752014-08-11 20:20:55 +0000562 if matched.group(1):
563 suppressed_line = linenum + 1
564 else:
565 suppressed_line = linenum
566 category = matched.group(2)
erg@google.com35589e62010-11-17 18:58:16 +0000567 if category in (None, '(*)'): # => "suppress all"
avakulenko@google.com59146752014-08-11 20:20:55 +0000568 _error_suppressions.setdefault(None, set()).add(suppressed_line)
erg@google.com35589e62010-11-17 18:58:16 +0000569 else:
570 if category.startswith('(') and category.endswith(')'):
571 category = category[1:-1]
572 if category in _ERROR_CATEGORIES:
avakulenko@google.com59146752014-08-11 20:20:55 +0000573 _error_suppressions.setdefault(category, set()).add(suppressed_line)
avakulenko@google.com255f2be2014-12-05 22:19:55 +0000574 elif category not in _LEGACY_ERROR_CATEGORIES:
erg@google.com35589e62010-11-17 18:58:16 +0000575 error(filename, linenum, 'readability/nolint', 5,
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +0000576 'Unknown NOLINT error category: %s' % category)
erg@google.com35589e62010-11-17 18:58:16 +0000577
578
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000579def ProcessGlobalSuppresions(lines):
580 """Updates the list of global error suppressions.
581
582 Parses any lint directives in the file that have global effect.
583
584 Args:
585 lines: An array of strings, each representing a line of the file, with the
586 last element being empty if the file is terminated with a newline.
587 """
588 for line in lines:
589 if _SEARCH_C_FILE.search(line):
590 for category in _DEFAULT_C_SUPPRESSED_CATEGORIES:
591 _global_error_suppressions[category] = True
592 if _SEARCH_KERNEL_FILE.search(line):
593 for category in _DEFAULT_KERNEL_SUPPRESSED_CATEGORIES:
594 _global_error_suppressions[category] = True
595
596
erg@google.com35589e62010-11-17 18:58:16 +0000597def ResetNolintSuppressions():
avakulenko@google.com59146752014-08-11 20:20:55 +0000598 """Resets the set of NOLINT suppressions to empty."""
erg@google.com35589e62010-11-17 18:58:16 +0000599 _error_suppressions.clear()
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000600 _global_error_suppressions.clear()
erg@google.com35589e62010-11-17 18:58:16 +0000601
602
603def IsErrorSuppressedByNolint(category, linenum):
604 """Returns true if the specified error category is suppressed on this line.
605
606 Consults the global error_suppressions map populated by
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000607 ParseNolintSuppressions/ProcessGlobalSuppresions/ResetNolintSuppressions.
erg@google.com35589e62010-11-17 18:58:16 +0000608
609 Args:
610 category: str, the category of the error.
611 linenum: int, the current line number.
612 Returns:
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000613 bool, True iff the error should be suppressed due to a NOLINT comment or
614 global suppression.
erg@google.com35589e62010-11-17 18:58:16 +0000615 """
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000616 return (_global_error_suppressions.get(category, False) or
617 linenum in _error_suppressions.get(category, set()) or
erg@google.com35589e62010-11-17 18:58:16 +0000618 linenum in _error_suppressions.get(None, set()))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000619
avakulenko@google.comd39bbb52014-06-04 22:55:20 +0000620
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000621def Match(pattern, s):
622 """Matches the string with the pattern, caching the compiled regexp."""
623 # The regexp compilation caching is inlined in both Match and Search for
624 # performance reasons; factoring it out into a separate function turns out
625 # to be noticeably expensive.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000626 if pattern not in _regexp_compile_cache:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000627 _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
628 return _regexp_compile_cache[pattern].match(s)
629
630
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000631def ReplaceAll(pattern, rep, s):
632 """Replaces instances of pattern in a string with a replacement.
633
634 The compiled regex is kept in a cache shared by Match and Search.
635
636 Args:
637 pattern: regex pattern
638 rep: replacement text
639 s: search string
640
641 Returns:
642 string with replacements made (or original string if no replacements)
643 """
644 if pattern not in _regexp_compile_cache:
645 _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
646 return _regexp_compile_cache[pattern].sub(rep, s)
647
648
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000649def Search(pattern, s):
650 """Searches the string for the pattern, caching the compiled regexp."""
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000651 if pattern not in _regexp_compile_cache:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000652 _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
653 return _regexp_compile_cache[pattern].search(s)
654
655
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000656def _IsSourceExtension(s):
657 """File extension (excluding dot) matches a source file extension."""
658 return s in ('c', 'cc', 'cpp', 'cxx')
659
660
avakulenko@google.com59146752014-08-11 20:20:55 +0000661class _IncludeState(object):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000662 """Tracks line numbers for includes, and the order in which includes appear.
663
avakulenko@google.com59146752014-08-11 20:20:55 +0000664 include_list contains list of lists of (header, line number) pairs.
665 It's a lists of lists rather than just one flat list to make it
666 easier to update across preprocessor boundaries.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000667
668 Call CheckNextIncludeOrder() once for each header in the file, passing
669 in the type constants defined above. Calls in an illegal order will
670 raise an _IncludeError with an appropriate error message.
671
672 """
673 # self._section will move monotonically through this set. If it ever
674 # needs to move backwards, CheckNextIncludeOrder will raise an error.
675 _INITIAL_SECTION = 0
676 _MY_H_SECTION = 1
677 _C_SECTION = 2
678 _CPP_SECTION = 3
679 _OTHER_H_SECTION = 4
680
681 _TYPE_NAMES = {
682 _C_SYS_HEADER: 'C system header',
683 _CPP_SYS_HEADER: 'C++ system header',
684 _LIKELY_MY_HEADER: 'header this file implements',
685 _POSSIBLE_MY_HEADER: 'header this file may implement',
686 _OTHER_HEADER: 'other header',
687 }
688 _SECTION_NAMES = {
689 _INITIAL_SECTION: "... nothing. (This can't be an error.)",
690 _MY_H_SECTION: 'a header this file implements',
691 _C_SECTION: 'C system header',
692 _CPP_SECTION: 'C++ system header',
693 _OTHER_H_SECTION: 'other header',
694 }
695
696 def __init__(self):
avakulenko@google.com59146752014-08-11 20:20:55 +0000697 self.include_list = [[]]
698 self.ResetSection('')
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000699
avakulenko@google.com59146752014-08-11 20:20:55 +0000700 def FindHeader(self, header):
701 """Check if a header has already been included.
702
703 Args:
704 header: header to check.
705 Returns:
706 Line number of previous occurrence, or -1 if the header has not
707 been seen before.
708 """
709 for section_list in self.include_list:
710 for f in section_list:
711 if f[0] == header:
712 return f[1]
713 return -1
714
715 def ResetSection(self, directive):
716 """Reset section checking for preprocessor directive.
717
718 Args:
719 directive: preprocessor directive (e.g. "if", "else").
720 """
erg@google.com26970fa2009-11-17 18:07:32 +0000721 # The name of the current section.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000722 self._section = self._INITIAL_SECTION
erg@google.com26970fa2009-11-17 18:07:32 +0000723 # The path of last found header.
724 self._last_header = ''
725
avakulenko@google.com59146752014-08-11 20:20:55 +0000726 # Update list of includes. Note that we never pop from the
727 # include list.
728 if directive in ('if', 'ifdef', 'ifndef'):
729 self.include_list.append([])
730 elif directive in ('else', 'elif'):
731 self.include_list[-1] = []
732
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000733 def SetLastHeader(self, header_path):
734 self._last_header = header_path
735
erg@google.com26970fa2009-11-17 18:07:32 +0000736 def CanonicalizeAlphabeticalOrder(self, header_path):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +0000737 """Returns a path canonicalized for alphabetical comparison.
erg@google.com26970fa2009-11-17 18:07:32 +0000738
739 - replaces "-" with "_" so they both cmp the same.
740 - removes '-inl' since we don't require them to be after the main header.
741 - lowercase everything, just in case.
742
743 Args:
744 header_path: Path to be canonicalized.
745
746 Returns:
747 Canonicalized path.
748 """
749 return header_path.replace('-inl.h', '.h').replace('-', '_').lower()
750
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000751 def IsInAlphabeticalOrder(self, clean_lines, linenum, header_path):
erg@google.com26970fa2009-11-17 18:07:32 +0000752 """Check if a header is in alphabetical order with the previous header.
753
754 Args:
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000755 clean_lines: A CleansedLines instance containing the file.
756 linenum: The number of the line to check.
757 header_path: Canonicalized header to be checked.
erg@google.com26970fa2009-11-17 18:07:32 +0000758
759 Returns:
760 Returns true if the header is in alphabetical order.
761 """
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000762 # If previous section is different from current section, _last_header will
763 # be reset to empty string, so it's always less than current header.
764 #
765 # If previous line was a blank line, assume that the headers are
766 # intentionally sorted the way they are.
767 if (self._last_header > header_path and
avakulenko@google.com255f2be2014-12-05 22:19:55 +0000768 Match(r'^\s*#\s*include\b', clean_lines.elided[linenum - 1])):
erg@google.com26970fa2009-11-17 18:07:32 +0000769 return False
erg@google.com26970fa2009-11-17 18:07:32 +0000770 return True
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000771
772 def CheckNextIncludeOrder(self, header_type):
773 """Returns a non-empty error message if the next header is out of order.
774
775 This function also updates the internal state to be ready to check
776 the next include.
777
778 Args:
779 header_type: One of the _XXX_HEADER constants defined above.
780
781 Returns:
782 The empty string if the header is in the right order, or an
783 error message describing what's wrong.
784
785 """
786 error_message = ('Found %s after %s' %
787 (self._TYPE_NAMES[header_type],
788 self._SECTION_NAMES[self._section]))
789
erg@google.com26970fa2009-11-17 18:07:32 +0000790 last_section = self._section
791
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000792 if header_type == _C_SYS_HEADER:
793 if self._section <= self._C_SECTION:
794 self._section = self._C_SECTION
795 else:
erg@google.com26970fa2009-11-17 18:07:32 +0000796 self._last_header = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000797 return error_message
798 elif header_type == _CPP_SYS_HEADER:
799 if self._section <= self._CPP_SECTION:
800 self._section = self._CPP_SECTION
801 else:
erg@google.com26970fa2009-11-17 18:07:32 +0000802 self._last_header = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000803 return error_message
804 elif header_type == _LIKELY_MY_HEADER:
805 if self._section <= self._MY_H_SECTION:
806 self._section = self._MY_H_SECTION
807 else:
808 self._section = self._OTHER_H_SECTION
809 elif header_type == _POSSIBLE_MY_HEADER:
810 if self._section <= self._MY_H_SECTION:
811 self._section = self._MY_H_SECTION
812 else:
813 # This will always be the fallback because we're not sure
814 # enough that the header is associated with this file.
815 self._section = self._OTHER_H_SECTION
816 else:
817 assert header_type == _OTHER_HEADER
818 self._section = self._OTHER_H_SECTION
819
erg@google.com26970fa2009-11-17 18:07:32 +0000820 if last_section != self._section:
821 self._last_header = ''
822
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000823 return ''
824
825
826class _CppLintState(object):
827 """Maintains module-wide state.."""
828
829 def __init__(self):
830 self.verbose_level = 1 # global setting.
831 self.error_count = 0 # global count of reported errors
erg@google.com6317a9c2009-06-25 00:28:19 +0000832 # filters to apply when emitting error messages
833 self.filters = _DEFAULT_FILTERS[:]
avakulenko@google.com17449932014-07-28 22:13:33 +0000834 # backup of filter list. Used to restore the state after each file.
835 self._filters_backup = self.filters[:]
erg@google.com26970fa2009-11-17 18:07:32 +0000836 self.counting = 'total' # In what way are we counting errors?
837 self.errors_by_category = {} # string to int dict storing error counts
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000838
839 # output format:
840 # "emacs" - format that emacs can parse (default)
841 # "vs7" - format that Microsoft Visual Studio 7 can parse
842 self.output_format = 'emacs'
843
844 def SetOutputFormat(self, output_format):
845 """Sets the output format for errors."""
846 self.output_format = output_format
847
848 def SetVerboseLevel(self, level):
849 """Sets the module's verbosity, and returns the previous setting."""
850 last_verbose_level = self.verbose_level
851 self.verbose_level = level
852 return last_verbose_level
853
erg@google.com26970fa2009-11-17 18:07:32 +0000854 def SetCountingStyle(self, counting_style):
855 """Sets the module's counting options."""
856 self.counting = counting_style
857
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000858 def SetFilters(self, filters):
859 """Sets the error-message filters.
860
861 These filters are applied when deciding whether to emit a given
862 error message.
863
864 Args:
865 filters: A string of comma-separated filters (eg "+whitespace/indent").
866 Each filter should start with + or -; else we die.
erg@google.com6317a9c2009-06-25 00:28:19 +0000867
868 Raises:
869 ValueError: The comma-separated filters did not all start with '+' or '-'.
870 E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter"
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000871 """
erg@google.com6317a9c2009-06-25 00:28:19 +0000872 # Default filters always have less priority than the flag ones.
873 self.filters = _DEFAULT_FILTERS[:]
avakulenko@google.com17449932014-07-28 22:13:33 +0000874 self.AddFilters(filters)
875
876 def AddFilters(self, filters):
877 """ Adds more filters to the existing list of error-message filters. """
erg@google.com6317a9c2009-06-25 00:28:19 +0000878 for filt in filters.split(','):
879 clean_filt = filt.strip()
880 if clean_filt:
881 self.filters.append(clean_filt)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000882 for filt in self.filters:
883 if not (filt.startswith('+') or filt.startswith('-')):
884 raise ValueError('Every filter in --filters must start with + or -'
885 ' (%s does not)' % filt)
886
avakulenko@google.com17449932014-07-28 22:13:33 +0000887 def BackupFilters(self):
888 """ Saves the current filter list to backup storage."""
889 self._filters_backup = self.filters[:]
890
891 def RestoreFilters(self):
892 """ Restores filters previously backed up."""
893 self.filters = self._filters_backup[:]
894
erg@google.com26970fa2009-11-17 18:07:32 +0000895 def ResetErrorCounts(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000896 """Sets the module's error statistic back to zero."""
897 self.error_count = 0
erg@google.com26970fa2009-11-17 18:07:32 +0000898 self.errors_by_category = {}
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000899
erg@google.com26970fa2009-11-17 18:07:32 +0000900 def IncrementErrorCount(self, category):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000901 """Bumps the module's error statistic."""
902 self.error_count += 1
erg@google.com26970fa2009-11-17 18:07:32 +0000903 if self.counting in ('toplevel', 'detailed'):
904 if self.counting != 'detailed':
905 category = category.split('/')[0]
906 if category not in self.errors_by_category:
907 self.errors_by_category[category] = 0
908 self.errors_by_category[category] += 1
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000909
erg@google.com26970fa2009-11-17 18:07:32 +0000910 def PrintErrorCounts(self):
911 """Print a summary of errors by category, and the total."""
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000912 for category, count in self.errors_by_category.items():
erg@google.com26970fa2009-11-17 18:07:32 +0000913 sys.stderr.write('Category \'%s\' errors found: %d\n' %
914 (category, count))
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +0000915 sys.stderr.write('Total errors found: %d\n' % self.error_count)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000916
917_cpplint_state = _CppLintState()
918
919
920def _OutputFormat():
921 """Gets the module's output format."""
922 return _cpplint_state.output_format
923
924
925def _SetOutputFormat(output_format):
926 """Sets the module's output format."""
927 _cpplint_state.SetOutputFormat(output_format)
928
929
930def _VerboseLevel():
931 """Returns the module's verbosity setting."""
932 return _cpplint_state.verbose_level
933
934
935def _SetVerboseLevel(level):
936 """Sets the module's verbosity, and returns the previous setting."""
937 return _cpplint_state.SetVerboseLevel(level)
938
939
erg@google.com26970fa2009-11-17 18:07:32 +0000940def _SetCountingStyle(level):
941 """Sets the module's counting options."""
942 _cpplint_state.SetCountingStyle(level)
943
944
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000945def _Filters():
946 """Returns the module's list of output filters, as a list."""
947 return _cpplint_state.filters
948
949
950def _SetFilters(filters):
951 """Sets the module's error-message filters.
952
953 These filters are applied when deciding whether to emit a given
954 error message.
955
956 Args:
957 filters: A string of comma-separated filters (eg "whitespace/indent").
958 Each filter should start with + or -; else we die.
959 """
960 _cpplint_state.SetFilters(filters)
961
avakulenko@google.com17449932014-07-28 22:13:33 +0000962def _AddFilters(filters):
963 """Adds more filter overrides.
avakulenko@google.com59146752014-08-11 20:20:55 +0000964
avakulenko@google.com17449932014-07-28 22:13:33 +0000965 Unlike _SetFilters, this function does not reset the current list of filters
966 available.
967
968 Args:
969 filters: A string of comma-separated filters (eg "whitespace/indent").
970 Each filter should start with + or -; else we die.
971 """
972 _cpplint_state.AddFilters(filters)
973
974def _BackupFilters():
975 """ Saves the current filter list to backup storage."""
976 _cpplint_state.BackupFilters()
977
978def _RestoreFilters():
979 """ Restores filters previously backed up."""
980 _cpplint_state.RestoreFilters()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000981
982class _FunctionState(object):
983 """Tracks current function name and the number of lines in its body."""
984
985 _NORMAL_TRIGGER = 250 # for --v=0, 500 for --v=1, etc.
986 _TEST_TRIGGER = 400 # about 50% more than _NORMAL_TRIGGER.
987
988 def __init__(self):
989 self.in_a_function = False
990 self.lines_in_function = 0
991 self.current_function = ''
992
993 def Begin(self, function_name):
994 """Start analyzing function body.
995
996 Args:
997 function_name: The name of the function being tracked.
998 """
999 self.in_a_function = True
1000 self.lines_in_function = 0
1001 self.current_function = function_name
1002
1003 def Count(self):
1004 """Count line in current function body."""
1005 if self.in_a_function:
1006 self.lines_in_function += 1
1007
1008 def Check(self, error, filename, linenum):
1009 """Report if too many lines in function body.
1010
1011 Args:
1012 error: The function to call with any errors found.
1013 filename: The name of the current file.
1014 linenum: The number of the line to check.
1015 """
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00001016 if not self.in_a_function:
1017 return
1018
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001019 if Match(r'T(EST|est)', self.current_function):
1020 base_trigger = self._TEST_TRIGGER
1021 else:
1022 base_trigger = self._NORMAL_TRIGGER
1023 trigger = base_trigger * 2**_VerboseLevel()
1024
1025 if self.lines_in_function > trigger:
1026 error_level = int(math.log(self.lines_in_function / base_trigger, 2))
1027 # 50 => 0, 100 => 1, 200 => 2, 400 => 3, 800 => 4, 1600 => 5, ...
1028 if error_level > 5:
1029 error_level = 5
1030 error(filename, linenum, 'readability/fn_size', error_level,
1031 'Small and focused functions are preferred:'
1032 ' %s has %d non-comment lines'
1033 ' (error triggered by exceeding %d lines).' % (
1034 self.current_function, self.lines_in_function, trigger))
1035
1036 def End(self):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00001037 """Stop analyzing function body."""
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001038 self.in_a_function = False
1039
1040
1041class _IncludeError(Exception):
1042 """Indicates a problem with the include order in a file."""
1043 pass
1044
1045
avakulenko@google.com59146752014-08-11 20:20:55 +00001046class FileInfo(object):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001047 """Provides utility functions for filenames.
1048
1049 FileInfo provides easy access to the components of a file's path
1050 relative to the project root.
1051 """
1052
1053 def __init__(self, filename):
1054 self._filename = filename
1055
1056 def FullName(self):
1057 """Make Windows paths like Unix."""
1058 return os.path.abspath(self._filename).replace('\\', '/')
1059
1060 def RepositoryName(self):
Edward Lemur6d31ed52019-12-02 23:00:00 +00001061 r"""FullName after removing the local path to the repository.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001062
1063 If we have a real absolute path name here we can try to do something smart:
1064 detecting the root of the checkout and truncating /path/to/checkout from
1065 the name so that we get header guards that don't include things like
1066 "C:\Documents and Settings\..." or "/home/username/..." in them and thus
1067 people on different computers who have checked the source out to different
1068 locations won't see bogus errors.
1069 """
1070 fullname = self.FullName()
1071
1072 if os.path.exists(fullname):
1073 project_dir = os.path.dirname(fullname)
1074
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00001075 if _project_root:
1076 prefix = os.path.commonprefix([_project_root, project_dir])
1077 return fullname[len(prefix) + 1:]
1078
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001079 if os.path.exists(os.path.join(project_dir, ".svn")):
1080 # If there's a .svn file in the current directory, we recursively look
1081 # up the directory tree for the top of the SVN checkout
1082 root_dir = project_dir
1083 one_up_dir = os.path.dirname(root_dir)
1084 while os.path.exists(os.path.join(one_up_dir, ".svn")):
1085 root_dir = os.path.dirname(root_dir)
1086 one_up_dir = os.path.dirname(one_up_dir)
1087
1088 prefix = os.path.commonprefix([root_dir, project_dir])
1089 return fullname[len(prefix) + 1:]
1090
erg@chromium.org7956a872011-11-30 01:44:03 +00001091 # Not SVN <= 1.6? Try to find a git, hg, or svn top level directory by
1092 # searching up from the current path.
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00001093 root_dir = os.path.dirname(fullname)
1094 while (root_dir != os.path.dirname(root_dir) and
1095 not os.path.exists(os.path.join(root_dir, ".git")) and
1096 not os.path.exists(os.path.join(root_dir, ".hg")) and
1097 not os.path.exists(os.path.join(root_dir, ".svn"))):
1098 root_dir = os.path.dirname(root_dir)
erg@google.com35589e62010-11-17 18:58:16 +00001099
1100 if (os.path.exists(os.path.join(root_dir, ".git")) or
erg@chromium.org7956a872011-11-30 01:44:03 +00001101 os.path.exists(os.path.join(root_dir, ".hg")) or
1102 os.path.exists(os.path.join(root_dir, ".svn"))):
erg@google.com35589e62010-11-17 18:58:16 +00001103 prefix = os.path.commonprefix([root_dir, project_dir])
1104 return fullname[len(prefix) + 1:]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001105
1106 # Don't know what to do; header guard warnings may be wrong...
1107 return fullname
1108
1109 def Split(self):
1110 """Splits the file into the directory, basename, and extension.
1111
1112 For 'chrome/browser/browser.cc', Split() would
1113 return ('chrome/browser', 'browser', '.cc')
1114
1115 Returns:
1116 A tuple of (directory, basename, extension).
1117 """
1118
1119 googlename = self.RepositoryName()
1120 project, rest = os.path.split(googlename)
1121 return (project,) + os.path.splitext(rest)
1122
1123 def BaseName(self):
1124 """File base name - text after the final slash, before the final period."""
1125 return self.Split()[1]
1126
1127 def Extension(self):
1128 """File extension - text following the final period."""
1129 return self.Split()[2]
1130
1131 def NoExtension(self):
1132 """File has no source file extension."""
1133 return '/'.join(self.Split()[0:2])
1134
1135 def IsSource(self):
1136 """File has a source file extension."""
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00001137 return _IsSourceExtension(self.Extension()[1:])
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001138
1139
erg@google.com35589e62010-11-17 18:58:16 +00001140def _ShouldPrintError(category, confidence, linenum):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00001141 """If confidence >= verbose, category passes filter and is not suppressed."""
erg@google.com35589e62010-11-17 18:58:16 +00001142
1143 # There are three ways we might decide not to print an error message:
1144 # a "NOLINT(category)" comment appears in the source,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001145 # the verbosity level isn't high enough, or the filters filter it out.
erg@google.com35589e62010-11-17 18:58:16 +00001146 if IsErrorSuppressedByNolint(category, linenum):
1147 return False
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001148
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001149 if confidence < _cpplint_state.verbose_level:
1150 return False
1151
1152 is_filtered = False
1153 for one_filter in _Filters():
1154 if one_filter.startswith('-'):
1155 if category.startswith(one_filter[1:]):
1156 is_filtered = True
1157 elif one_filter.startswith('+'):
1158 if category.startswith(one_filter[1:]):
1159 is_filtered = False
1160 else:
1161 assert False # should have been checked for in SetFilter.
1162 if is_filtered:
1163 return False
1164
1165 return True
1166
1167
1168def Error(filename, linenum, category, confidence, message):
1169 """Logs the fact we've found a lint error.
1170
1171 We log where the error was found, and also our confidence in the error,
1172 that is, how certain we are this is a legitimate style regression, and
1173 not a misidentification or a use that's sometimes justified.
1174
erg@google.com35589e62010-11-17 18:58:16 +00001175 False positives can be suppressed by the use of
1176 "cpplint(category)" comments on the offending line. These are
1177 parsed into _error_suppressions.
1178
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001179 Args:
1180 filename: The name of the file containing the error.
1181 linenum: The number of the line containing the error.
1182 category: A string used to describe the "category" this bug
1183 falls under: "whitespace", say, or "runtime". Categories
1184 may have a hierarchy separated by slashes: "whitespace/indent".
1185 confidence: A number from 1-5 representing a confidence score for
1186 the error, with 5 meaning that we are certain of the problem,
1187 and 1 meaning that it could be a legitimate construct.
1188 message: The error message.
1189 """
erg@google.com35589e62010-11-17 18:58:16 +00001190 if _ShouldPrintError(category, confidence, linenum):
erg@google.com26970fa2009-11-17 18:07:32 +00001191 _cpplint_state.IncrementErrorCount(category)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001192 if _cpplint_state.output_format == 'vs7':
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00001193 sys.stderr.write('%s(%s): %s [%s] [%d]\n' % (
1194 filename, linenum, message, category, confidence))
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001195 elif _cpplint_state.output_format == 'eclipse':
1196 sys.stderr.write('%s:%s: warning: %s [%s] [%d]\n' % (
1197 filename, linenum, message, category, confidence))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001198 else:
1199 sys.stderr.write('%s:%s: %s [%s] [%d]\n' % (
1200 filename, linenum, message, category, confidence))
1201
1202
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001203# Matches standard C++ escape sequences per 2.13.2.3 of the C++ standard.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001204_RE_PATTERN_CLEANSE_LINE_ESCAPES = re.compile(
1205 r'\\([abfnrtv?"\\\']|\d+|x[0-9a-fA-F]+)')
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001206# Match a single C style comment on the same line.
1207_RE_PATTERN_C_COMMENTS = r'/\*(?:[^*]|\*(?!/))*\*/'
1208# Matches multi-line C style comments.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001209# This RE is a little bit more complicated than one might expect, because we
1210# have to take care of space removals tools so we can handle comments inside
1211# statements better.
1212# The current rule is: We only clear spaces from both sides when we're at the
1213# end of the line. Otherwise, we try to remove spaces from the right side,
1214# if this doesn't work we try on left side but only if there's a non-character
1215# on the right.
1216_RE_PATTERN_CLEANSE_LINE_C_COMMENTS = re.compile(
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001217 r'(\s*' + _RE_PATTERN_C_COMMENTS + r'\s*$|' +
1218 _RE_PATTERN_C_COMMENTS + r'\s+|' +
1219 r'\s+' + _RE_PATTERN_C_COMMENTS + r'(?=\W)|' +
1220 _RE_PATTERN_C_COMMENTS + r')')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001221
1222
1223def IsCppString(line):
1224 """Does line terminate so, that the next symbol is in string constant.
1225
1226 This function does not consider single-line nor multi-line comments.
1227
1228 Args:
1229 line: is a partial line of code starting from the 0..n.
1230
1231 Returns:
1232 True, if next character appended to 'line' is inside a
1233 string constant.
1234 """
1235
1236 line = line.replace(r'\\', 'XX') # after this, \\" does not match to \"
1237 return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1
1238
1239
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001240def CleanseRawStrings(raw_lines):
1241 """Removes C++11 raw strings from lines.
1242
1243 Before:
1244 static const char kData[] = R"(
1245 multi-line string
1246 )";
1247
1248 After:
1249 static const char kData[] = ""
1250 (replaced by blank line)
1251 "";
1252
1253 Args:
1254 raw_lines: list of raw lines.
1255
1256 Returns:
1257 list of lines with C++11 raw strings replaced by empty strings.
1258 """
1259
1260 delimiter = None
1261 lines_without_raw_strings = []
1262 for line in raw_lines:
1263 if delimiter:
1264 # Inside a raw string, look for the end
1265 end = line.find(delimiter)
1266 if end >= 0:
1267 # Found the end of the string, match leading space for this
1268 # line and resume copying the original lines, and also insert
1269 # a "" on the last line.
1270 leading_space = Match(r'^(\s*)\S', line)
1271 line = leading_space.group(1) + '""' + line[end + len(delimiter):]
1272 delimiter = None
1273 else:
1274 # Haven't found the end yet, append a blank line.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001275 line = '""'
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001276
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001277 # Look for beginning of a raw string, and replace them with
1278 # empty strings. This is done in a loop to handle multiple raw
1279 # strings on the same line.
1280 while delimiter is None:
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001281 # Look for beginning of a raw string.
1282 # See 2.14.15 [lex.string] for syntax.
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00001283 #
1284 # Once we have matched a raw string, we check the prefix of the
1285 # line to make sure that the line is not part of a single line
1286 # comment. It's done this way because we remove raw strings
1287 # before removing comments as opposed to removing comments
1288 # before removing raw strings. This is because there are some
1289 # cpplint checks that requires the comments to be preserved, but
1290 # we don't want to check comments that are inside raw strings.
1291 matched = Match(r'^(.*?)\b(?:R|u8R|uR|UR|LR)"([^\s\\()]*)\((.*)$', line)
1292 if (matched and
1293 not Match(r'^([^\'"]|\'(\\.|[^\'])*\'|"(\\.|[^"])*")*//',
1294 matched.group(1))):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001295 delimiter = ')' + matched.group(2) + '"'
1296
1297 end = matched.group(3).find(delimiter)
1298 if end >= 0:
1299 # Raw string ended on same line
1300 line = (matched.group(1) + '""' +
1301 matched.group(3)[end + len(delimiter):])
1302 delimiter = None
1303 else:
1304 # Start of a multi-line raw string
1305 line = matched.group(1) + '""'
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001306 else:
1307 break
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001308
1309 lines_without_raw_strings.append(line)
1310
1311 # TODO(unknown): if delimiter is not None here, we might want to
1312 # emit a warning for unterminated string.
1313 return lines_without_raw_strings
1314
1315
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001316def FindNextMultiLineCommentStart(lines, lineix):
1317 """Find the beginning marker for a multiline comment."""
1318 while lineix < len(lines):
1319 if lines[lineix].strip().startswith('/*'):
1320 # Only return this marker if the comment goes beyond this line
1321 if lines[lineix].strip().find('*/', 2) < 0:
1322 return lineix
1323 lineix += 1
1324 return len(lines)
1325
1326
1327def FindNextMultiLineCommentEnd(lines, lineix):
1328 """We are inside a comment, find the end marker."""
1329 while lineix < len(lines):
1330 if lines[lineix].strip().endswith('*/'):
1331 return lineix
1332 lineix += 1
1333 return len(lines)
1334
1335
1336def RemoveMultiLineCommentsFromRange(lines, begin, end):
1337 """Clears a range of lines for multi-line comments."""
1338 # Having // dummy comments makes the lines non-empty, so we will not get
1339 # unnecessary blank line warnings later in the code.
1340 for i in range(begin, end):
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001341 lines[i] = '/**/'
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001342
1343
1344def RemoveMultiLineComments(filename, lines, error):
1345 """Removes multiline (c-style) comments from lines."""
1346 lineix = 0
1347 while lineix < len(lines):
1348 lineix_begin = FindNextMultiLineCommentStart(lines, lineix)
1349 if lineix_begin >= len(lines):
1350 return
1351 lineix_end = FindNextMultiLineCommentEnd(lines, lineix_begin)
1352 if lineix_end >= len(lines):
1353 error(filename, lineix_begin + 1, 'readability/multiline_comment', 5,
1354 'Could not find end of multi-line comment')
1355 return
1356 RemoveMultiLineCommentsFromRange(lines, lineix_begin, lineix_end + 1)
1357 lineix = lineix_end + 1
1358
1359
1360def CleanseComments(line):
1361 """Removes //-comments and single-line C-style /* */ comments.
1362
1363 Args:
1364 line: A line of C++ source.
1365
1366 Returns:
1367 The line with single-line comments removed.
1368 """
1369 commentpos = line.find('//')
1370 if commentpos != -1 and not IsCppString(line[:commentpos]):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00001371 line = line[:commentpos].rstrip()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001372 # get rid of /* ... */
1373 return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line)
1374
1375
erg@google.com6317a9c2009-06-25 00:28:19 +00001376class CleansedLines(object):
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001377 """Holds 4 copies of all lines with different preprocessing applied to them.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001378
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001379 1) elided member contains lines without strings and comments.
1380 2) lines member contains lines without comments.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001381 3) raw_lines member contains all the lines without processing.
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001382 4) lines_without_raw_strings member is same as raw_lines, but with C++11 raw
1383 strings removed.
1384 All these members are of <type 'list'>, and of the same length.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001385 """
1386
1387 def __init__(self, lines):
1388 self.elided = []
1389 self.lines = []
1390 self.raw_lines = lines
1391 self.num_lines = len(lines)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001392 self.lines_without_raw_strings = CleanseRawStrings(lines)
1393 for linenum in range(len(self.lines_without_raw_strings)):
1394 self.lines.append(CleanseComments(
1395 self.lines_without_raw_strings[linenum]))
1396 elided = self._CollapseStrings(self.lines_without_raw_strings[linenum])
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001397 self.elided.append(CleanseComments(elided))
1398
1399 def NumLines(self):
1400 """Returns the number of lines represented."""
1401 return self.num_lines
1402
1403 @staticmethod
1404 def _CollapseStrings(elided):
1405 """Collapses strings and chars on a line to simple "" or '' blocks.
1406
1407 We nix strings first so we're not fooled by text like '"http://"'
1408
1409 Args:
1410 elided: The line being processed.
1411
1412 Returns:
1413 The line with collapsed strings.
1414 """
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001415 if _RE_PATTERN_INCLUDE.match(elided):
1416 return elided
1417
1418 # Remove escaped characters first to make quote/single quote collapsing
1419 # basic. Things that look like escaped characters shouldn't occur
1420 # outside of strings and chars.
1421 elided = _RE_PATTERN_CLEANSE_LINE_ESCAPES.sub('', elided)
1422
1423 # Replace quoted strings and digit separators. Both single quotes
1424 # and double quotes are processed in the same loop, otherwise
1425 # nested quotes wouldn't work.
1426 collapsed = ''
1427 while True:
1428 # Find the first quote character
1429 match = Match(r'^([^\'"]*)([\'"])(.*)$', elided)
1430 if not match:
1431 collapsed += elided
1432 break
1433 head, quote, tail = match.groups()
1434
1435 if quote == '"':
1436 # Collapse double quoted strings
1437 second_quote = tail.find('"')
1438 if second_quote >= 0:
1439 collapsed += head + '""'
1440 elided = tail[second_quote + 1:]
1441 else:
1442 # Unmatched double quote, don't bother processing the rest
1443 # of the line since this is probably a multiline string.
1444 collapsed += elided
1445 break
1446 else:
1447 # Found single quote, check nearby text to eliminate digit separators.
1448 #
1449 # There is no special handling for floating point here, because
1450 # the integer/fractional/exponent parts would all be parsed
1451 # correctly as long as there are digits on both sides of the
1452 # separator. So we are fine as long as we don't see something
1453 # like "0.'3" (gcc 4.9.0 will not allow this literal).
1454 if Search(r'\b(?:0[bBxX]?|[1-9])[0-9a-fA-F]*$', head):
1455 match_literal = Match(r'^((?:\'?[0-9a-zA-Z_])*)(.*)$', "'" + tail)
1456 collapsed += head + match_literal.group(1).replace("'", '')
1457 elided = match_literal.group(2)
1458 else:
1459 second_quote = tail.find('\'')
1460 if second_quote >= 0:
1461 collapsed += head + "''"
1462 elided = tail[second_quote + 1:]
1463 else:
1464 # Unmatched single quote
1465 collapsed += elided
1466 break
1467
1468 return collapsed
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001469
1470
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001471def FindEndOfExpressionInLine(line, startpos, stack):
1472 """Find the position just after the end of current parenthesized expression.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001473
1474 Args:
1475 line: a CleansedLines line.
1476 startpos: start searching at this position.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001477 stack: nesting stack at startpos.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001478
1479 Returns:
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001480 On finding matching end: (index just after matching end, None)
1481 On finding an unclosed expression: (-1, None)
1482 Otherwise: (-1, new stack at end of this line)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001483 """
Edward Lemur6d31ed52019-12-02 23:00:00 +00001484 for i in range(startpos, len(line)):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001485 char = line[i]
1486 if char in '([{':
1487 # Found start of parenthesized expression, push to expression stack
1488 stack.append(char)
1489 elif char == '<':
1490 # Found potential start of template argument list
1491 if i > 0 and line[i - 1] == '<':
1492 # Left shift operator
1493 if stack and stack[-1] == '<':
1494 stack.pop()
1495 if not stack:
1496 return (-1, None)
1497 elif i > 0 and Search(r'\boperator\s*$', line[0:i]):
1498 # operator<, don't add to stack
1499 continue
1500 else:
1501 # Tentative start of template argument list
1502 stack.append('<')
1503 elif char in ')]}':
1504 # Found end of parenthesized expression.
1505 #
1506 # If we are currently expecting a matching '>', the pending '<'
1507 # must have been an operator. Remove them from expression stack.
1508 while stack and stack[-1] == '<':
1509 stack.pop()
1510 if not stack:
1511 return (-1, None)
1512 if ((stack[-1] == '(' and char == ')') or
1513 (stack[-1] == '[' and char == ']') or
1514 (stack[-1] == '{' and char == '}')):
1515 stack.pop()
1516 if not stack:
1517 return (i + 1, None)
1518 else:
1519 # Mismatched parentheses
1520 return (-1, None)
1521 elif char == '>':
1522 # Found potential end of template argument list.
1523
1524 # Ignore "->" and operator functions
1525 if (i > 0 and
1526 (line[i - 1] == '-' or Search(r'\boperator\s*$', line[0:i - 1]))):
1527 continue
1528
1529 # Pop the stack if there is a matching '<'. Otherwise, ignore
1530 # this '>' since it must be an operator.
1531 if stack:
1532 if stack[-1] == '<':
1533 stack.pop()
1534 if not stack:
1535 return (i + 1, None)
1536 elif char == ';':
1537 # Found something that look like end of statements. If we are currently
1538 # expecting a '>', the matching '<' must have been an operator, since
1539 # template argument list should not contain statements.
1540 while stack and stack[-1] == '<':
1541 stack.pop()
1542 if not stack:
1543 return (-1, None)
1544
1545 # Did not find end of expression or unbalanced parentheses on this line
1546 return (-1, stack)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001547
1548
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001549def CloseExpression(clean_lines, linenum, pos):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001550 """If input points to ( or { or [ or <, finds the position that closes it.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001551
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001552 If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001553 linenum/pos that correspond to the closing of the expression.
1554
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001555 TODO(unknown): cpplint spends a fair bit of time matching parentheses.
1556 Ideally we would want to index all opening and closing parentheses once
1557 and have CloseExpression be just a simple lookup, but due to preprocessor
1558 tricks, this is not so easy.
1559
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001560 Args:
1561 clean_lines: A CleansedLines instance containing the file.
1562 linenum: The number of the line to check.
1563 pos: A position on the line.
1564
1565 Returns:
1566 A tuple (line, linenum, pos) pointer *past* the closing brace, or
1567 (line, len(lines), -1) if we never find a close. Note we ignore
1568 strings and comments when matching; and the line we return is the
1569 'cleansed' line at linenum.
1570 """
1571
1572 line = clean_lines.elided[linenum]
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001573 if (line[pos] not in '({[<') or Match(r'<[<=]', line[pos:]):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001574 return (line, clean_lines.NumLines(), -1)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001575
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001576 # Check first line
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001577 (end_pos, stack) = FindEndOfExpressionInLine(line, pos, [])
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001578 if end_pos > -1:
1579 return (line, linenum, end_pos)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001580
1581 # Continue scanning forward
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001582 while stack and linenum < clean_lines.NumLines() - 1:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001583 linenum += 1
1584 line = clean_lines.elided[linenum]
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001585 (end_pos, stack) = FindEndOfExpressionInLine(line, 0, stack)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001586 if end_pos > -1:
1587 return (line, linenum, end_pos)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001588
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001589 # Did not find end of expression before end of file, give up
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001590 return (line, clean_lines.NumLines(), -1)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001591
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001592
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001593def FindStartOfExpressionInLine(line, endpos, stack):
1594 """Find position at the matching start of current expression.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001595
1596 This is almost the reverse of FindEndOfExpressionInLine, but note
1597 that the input position and returned position differs by 1.
1598
1599 Args:
1600 line: a CleansedLines line.
1601 endpos: start searching at this position.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001602 stack: nesting stack at endpos.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001603
1604 Returns:
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001605 On finding matching start: (index at matching start, None)
1606 On finding an unclosed expression: (-1, None)
1607 Otherwise: (-1, new stack at beginning of this line)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001608 """
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001609 i = endpos
1610 while i >= 0:
1611 char = line[i]
1612 if char in ')]}':
1613 # Found end of expression, push to expression stack
1614 stack.append(char)
1615 elif char == '>':
1616 # Found potential end of template argument list.
1617 #
1618 # Ignore it if it's a "->" or ">=" or "operator>"
1619 if (i > 0 and
1620 (line[i - 1] == '-' or
1621 Match(r'\s>=\s', line[i - 1:]) or
1622 Search(r'\boperator\s*$', line[0:i]))):
1623 i -= 1
1624 else:
1625 stack.append('>')
1626 elif char == '<':
1627 # Found potential start of template argument list
1628 if i > 0 and line[i - 1] == '<':
1629 # Left shift operator
1630 i -= 1
1631 else:
1632 # If there is a matching '>', we can pop the expression stack.
1633 # Otherwise, ignore this '<' since it must be an operator.
1634 if stack and stack[-1] == '>':
1635 stack.pop()
1636 if not stack:
1637 return (i, None)
1638 elif char in '([{':
1639 # Found start of expression.
1640 #
1641 # If there are any unmatched '>' on the stack, they must be
1642 # operators. Remove those.
1643 while stack and stack[-1] == '>':
1644 stack.pop()
1645 if not stack:
1646 return (-1, None)
1647 if ((char == '(' and stack[-1] == ')') or
1648 (char == '[' and stack[-1] == ']') or
1649 (char == '{' and stack[-1] == '}')):
1650 stack.pop()
1651 if not stack:
1652 return (i, None)
1653 else:
1654 # Mismatched parentheses
1655 return (-1, None)
1656 elif char == ';':
1657 # Found something that look like end of statements. If we are currently
1658 # expecting a '<', the matching '>' must have been an operator, since
1659 # template argument list should not contain statements.
1660 while stack and stack[-1] == '>':
1661 stack.pop()
1662 if not stack:
1663 return (-1, None)
1664
1665 i -= 1
1666
1667 return (-1, stack)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001668
1669
1670def ReverseCloseExpression(clean_lines, linenum, pos):
1671 """If input points to ) or } or ] or >, finds the position that opens it.
1672
1673 If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the
1674 linenum/pos that correspond to the opening of the expression.
1675
1676 Args:
1677 clean_lines: A CleansedLines instance containing the file.
1678 linenum: The number of the line to check.
1679 pos: A position on the line.
1680
1681 Returns:
1682 A tuple (line, linenum, pos) pointer *at* the opening brace, or
1683 (line, 0, -1) if we never find the matching opening brace. Note
1684 we ignore strings and comments when matching; and the line we
1685 return is the 'cleansed' line at linenum.
1686 """
1687 line = clean_lines.elided[linenum]
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001688 if line[pos] not in ')}]>':
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001689 return (line, 0, -1)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001690
1691 # Check last line
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001692 (start_pos, stack) = FindStartOfExpressionInLine(line, pos, [])
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001693 if start_pos > -1:
1694 return (line, linenum, start_pos)
1695
1696 # Continue scanning backward
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001697 while stack and linenum > 0:
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001698 linenum -= 1
1699 line = clean_lines.elided[linenum]
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001700 (start_pos, stack) = FindStartOfExpressionInLine(line, len(line) - 1, stack)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001701 if start_pos > -1:
1702 return (line, linenum, start_pos)
1703
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001704 # Did not find start of expression before beginning of file, give up
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001705 return (line, 0, -1)
1706
1707
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001708def CheckForCopyright(filename, lines, error):
1709 """Logs an error if no Copyright message appears at the top of the file."""
1710
1711 # We'll say it should occur by line 10. Don't forget there's a
1712 # dummy line at the front.
Edward Lemur6d31ed52019-12-02 23:00:00 +00001713 for line in range(1, min(len(lines), 11)):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001714 if re.search(r'Copyright', lines[line], re.I): break
1715 else: # means no copyright line was found
1716 error(filename, 0, 'legal/copyright', 5,
1717 'No copyright message found. '
1718 'You should have a line: "Copyright [year] <Copyright Owner>"')
1719
1720
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001721def GetIndentLevel(line):
1722 """Return the number of leading spaces in line.
1723
1724 Args:
1725 line: A string to check.
1726
1727 Returns:
1728 An integer count of leading spaces, possibly zero.
1729 """
1730 indent = Match(r'^( *)\S', line)
1731 if indent:
1732 return len(indent.group(1))
1733 else:
1734 return 0
1735
1736
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001737def GetHeaderGuardCPPVariable(filename):
1738 """Returns the CPP variable that should be used as a header guard.
1739
1740 Args:
1741 filename: The name of a C++ header file.
1742
1743 Returns:
1744 The CPP variable that should be used as a header guard in the
1745 named file.
1746
1747 """
1748
erg@google.com35589e62010-11-17 18:58:16 +00001749 # Restores original filename in case that cpplint is invoked from Emacs's
1750 # flymake.
1751 filename = re.sub(r'_flymake\.h$', '.h', filename)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001752 filename = re.sub(r'/\.flymake/([^/]*)$', r'/\1', filename)
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001753 # Replace 'c++' with 'cpp'.
1754 filename = filename.replace('C++', 'cpp').replace('c++', 'cpp')
skym@chromium.org3990c412016-02-05 20:55:12 +00001755
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001756 fileinfo = FileInfo(filename)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001757 file_path_from_root = fileinfo.RepositoryName()
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00001758 if _root:
1759 file_path_from_root = re.sub('^' + _root + os.sep, '', file_path_from_root)
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001760 return re.sub(r'[^a-zA-Z0-9]', '_', file_path_from_root).upper() + '_'
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001761
1762
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001763def CheckForHeaderGuard(filename, clean_lines, error):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001764 """Checks that the file contains a header guard.
1765
erg@google.com6317a9c2009-06-25 00:28:19 +00001766 Logs an error if no #ifndef header guard is present. For other
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001767 headers, checks that the full pathname is used.
1768
1769 Args:
1770 filename: The name of the C++ header file.
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001771 clean_lines: A CleansedLines instance containing the file.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001772 error: The function to call with any errors found.
1773 """
1774
avakulenko@google.com59146752014-08-11 20:20:55 +00001775 # Don't check for header guards if there are error suppression
1776 # comments somewhere in this file.
1777 #
1778 # Because this is silencing a warning for a nonexistent line, we
1779 # only support the very specific NOLINT(build/header_guard) syntax,
1780 # and not the general NOLINT or NOLINT(*) syntax.
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001781 raw_lines = clean_lines.lines_without_raw_strings
1782 for i in raw_lines:
avakulenko@google.com59146752014-08-11 20:20:55 +00001783 if Search(r'//\s*NOLINT\(build/header_guard\)', i):
1784 return
1785
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001786 cppvar = GetHeaderGuardCPPVariable(filename)
1787
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001788 ifndef = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001789 ifndef_linenum = 0
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001790 define = ''
1791 endif = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001792 endif_linenum = 0
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001793 for linenum, line in enumerate(raw_lines):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001794 linesplit = line.split()
1795 if len(linesplit) >= 2:
1796 # find the first occurrence of #ifndef and #define, save arg
1797 if not ifndef and linesplit[0] == '#ifndef':
1798 # set ifndef to the header guard presented on the #ifndef line.
1799 ifndef = linesplit[1]
1800 ifndef_linenum = linenum
1801 if not define and linesplit[0] == '#define':
1802 define = linesplit[1]
1803 # find the last occurrence of #endif, save entire line
1804 if line.startswith('#endif'):
1805 endif = line
1806 endif_linenum = linenum
1807
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001808 if not ifndef or not define or ifndef != define:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001809 error(filename, 0, 'build/header_guard', 5,
1810 'No #ifndef header guard found, suggested CPP variable is: %s' %
1811 cppvar)
1812 return
1813
1814 # The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__
1815 # for backward compatibility.
erg@google.com35589e62010-11-17 18:58:16 +00001816 if ifndef != cppvar:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001817 error_level = 0
1818 if ifndef != cppvar + '_':
1819 error_level = 5
1820
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001821 ParseNolintSuppressions(filename, raw_lines[ifndef_linenum], ifndef_linenum,
erg@google.com35589e62010-11-17 18:58:16 +00001822 error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001823 error(filename, ifndef_linenum, 'build/header_guard', error_level,
1824 '#ifndef header guard has wrong style, please use: %s' % cppvar)
1825
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001826 # Check for "//" comments on endif line.
1827 ParseNolintSuppressions(filename, raw_lines[endif_linenum], endif_linenum,
1828 error)
1829 match = Match(r'#endif\s*//\s*' + cppvar + r'(_)?\b', endif)
1830 if match:
1831 if match.group(1) == '_':
1832 # Issue low severity warning for deprecated double trailing underscore
1833 error(filename, endif_linenum, 'build/header_guard', 0,
1834 '#endif line should be "#endif // %s"' % cppvar)
erg@chromium.orgc452fea2012-01-26 21:10:45 +00001835 return
1836
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001837 # Didn't find the corresponding "//" comment. If this file does not
1838 # contain any "//" comments at all, it could be that the compiler
1839 # only wants "/**/" comments, look for those instead.
1840 no_single_line_comments = True
Edward Lemur6d31ed52019-12-02 23:00:00 +00001841 for i in range(1, len(raw_lines) - 1):
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001842 line = raw_lines[i]
1843 if Match(r'^(?:(?:\'(?:\.|[^\'])*\')|(?:"(?:\.|[^"])*")|[^\'"])*//', line):
1844 no_single_line_comments = False
1845 break
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001846
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001847 if no_single_line_comments:
1848 match = Match(r'#endif\s*/\*\s*' + cppvar + r'(_)?\s*\*/', endif)
1849 if match:
1850 if match.group(1) == '_':
1851 # Low severity warning for double trailing underscore
1852 error(filename, endif_linenum, 'build/header_guard', 0,
1853 '#endif line should be "#endif /* %s */"' % cppvar)
1854 return
1855
1856 # Didn't find anything
1857 error(filename, endif_linenum, 'build/header_guard', 5,
1858 '#endif line should be "#endif // %s"' % cppvar)
1859
1860
1861def CheckHeaderFileIncluded(filename, include_state, error):
1862 """Logs an error if a .cc file does not include its header."""
1863
1864 # Do not check test files
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00001865 fileinfo = FileInfo(filename)
1866 if Search(_TEST_FILE_SUFFIX, fileinfo.BaseName()):
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001867 return
1868
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00001869 headerfile = filename[0:len(filename) - len(fileinfo.Extension())] + '.h'
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001870 if not os.path.exists(headerfile):
1871 return
1872 headername = FileInfo(headerfile).RepositoryName()
1873 first_include = 0
1874 for section_list in include_state.include_list:
1875 for f in section_list:
1876 if headername in f[0] or f[0] in headername:
1877 return
1878 if not first_include:
1879 first_include = f[1]
1880
1881 error(filename, first_include, 'build/include', 5,
1882 '%s should include its header file %s' % (fileinfo.RepositoryName(),
1883 headername))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001884
1885
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001886def CheckForBadCharacters(filename, lines, error):
1887 """Logs an error for each line containing bad characters.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001888
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001889 Two kinds of bad characters:
1890
1891 1. Unicode replacement characters: These indicate that either the file
1892 contained invalid UTF-8 (likely) or Unicode replacement characters (which
1893 it shouldn't). Note that it's possible for this to throw off line
1894 numbering if the invalid UTF-8 occurred adjacent to a newline.
1895
1896 2. NUL bytes. These are problematic for some tools.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001897
1898 Args:
1899 filename: The name of the current file.
1900 lines: An array of strings, each representing a line of the file.
1901 error: The function to call with any errors found.
1902 """
1903 for linenum, line in enumerate(lines):
1904 if u'\ufffd' in line:
1905 error(filename, linenum, 'readability/utf8', 5,
1906 'Line contains invalid UTF-8 (or Unicode replacement character).')
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001907 if '\0' in line:
1908 error(filename, linenum, 'readability/nul', 5, 'Line contains NUL byte.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001909
1910
1911def CheckForNewlineAtEOF(filename, lines, error):
1912 """Logs an error if there is no newline char at the end of the file.
1913
1914 Args:
1915 filename: The name of the current file.
1916 lines: An array of strings, each representing a line of the file.
1917 error: The function to call with any errors found.
1918 """
1919
1920 # The array lines() was created by adding two newlines to the
1921 # original file (go figure), then splitting on \n.
1922 # To verify that the file ends in \n, we just have to make sure the
1923 # last-but-two element of lines() exists and is empty.
1924 if len(lines) < 3 or lines[-2]:
1925 error(filename, len(lines) - 2, 'whitespace/ending_newline', 5,
1926 'Could not find a newline character at the end of the file.')
1927
1928
1929def CheckForMultilineCommentsAndStrings(filename, clean_lines, linenum, error):
1930 """Logs an error if we see /* ... */ or "..." that extend past one line.
1931
1932 /* ... */ comments are legit inside macros, for one line.
1933 Otherwise, we prefer // comments, so it's ok to warn about the
1934 other. Likewise, it's ok for strings to extend across multiple
1935 lines, as long as a line continuation character (backslash)
1936 terminates each line. Although not currently prohibited by the C++
1937 style guide, it's ugly and unnecessary. We don't do well with either
1938 in this lint program, so we warn about both.
1939
1940 Args:
1941 filename: The name of the current file.
1942 clean_lines: A CleansedLines instance containing the file.
1943 linenum: The number of the line to check.
1944 error: The function to call with any errors found.
1945 """
1946 line = clean_lines.elided[linenum]
1947
1948 # Remove all \\ (escaped backslashes) from the line. They are OK, and the
1949 # second (escaped) slash may trigger later \" detection erroneously.
1950 line = line.replace('\\\\', '')
1951
1952 if line.count('/*') > line.count('*/'):
1953 error(filename, linenum, 'readability/multiline_comment', 5,
1954 'Complex multi-line /*...*/-style comment found. '
1955 'Lint may give bogus warnings. '
1956 'Consider replacing these with //-style comments, '
1957 'with #if 0...#endif, '
1958 'or with more clearly structured multi-line comments.')
1959
1960 if (line.count('"') - line.count('\\"')) % 2:
1961 error(filename, linenum, 'readability/multiline_string', 5,
1962 'Multi-line string ("...") found. This lint script doesn\'t '
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001963 'do well with such strings, and may give bogus warnings. '
1964 'Use C++11 raw strings or concatenation instead.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001965
1966
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001967# (non-threadsafe name, thread-safe alternative, validation pattern)
1968#
1969# The validation pattern is used to eliminate false positives such as:
1970# _rand(); // false positive due to substring match.
1971# ->rand(); // some member function rand().
1972# ACMRandom rand(seed); // some variable named rand.
1973# ISAACRandom rand(); // another variable named rand.
1974#
1975# Basically we require the return value of these functions to be used
1976# in some expression context on the same line by matching on some
1977# operator before the function name. This eliminates constructors and
1978# member function calls.
1979_UNSAFE_FUNC_PREFIX = r'(?:[-+*/=%^&|(<]\s*|>\s+)'
1980_THREADING_LIST = (
1981 ('asctime(', 'asctime_r(', _UNSAFE_FUNC_PREFIX + r'asctime\([^)]+\)'),
1982 ('ctime(', 'ctime_r(', _UNSAFE_FUNC_PREFIX + r'ctime\([^)]+\)'),
1983 ('getgrgid(', 'getgrgid_r(', _UNSAFE_FUNC_PREFIX + r'getgrgid\([^)]+\)'),
1984 ('getgrnam(', 'getgrnam_r(', _UNSAFE_FUNC_PREFIX + r'getgrnam\([^)]+\)'),
1985 ('getlogin(', 'getlogin_r(', _UNSAFE_FUNC_PREFIX + r'getlogin\(\)'),
1986 ('getpwnam(', 'getpwnam_r(', _UNSAFE_FUNC_PREFIX + r'getpwnam\([^)]+\)'),
1987 ('getpwuid(', 'getpwuid_r(', _UNSAFE_FUNC_PREFIX + r'getpwuid\([^)]+\)'),
1988 ('gmtime(', 'gmtime_r(', _UNSAFE_FUNC_PREFIX + r'gmtime\([^)]+\)'),
1989 ('localtime(', 'localtime_r(', _UNSAFE_FUNC_PREFIX + r'localtime\([^)]+\)'),
1990 ('rand(', 'rand_r(', _UNSAFE_FUNC_PREFIX + r'rand\(\)'),
1991 ('strtok(', 'strtok_r(',
1992 _UNSAFE_FUNC_PREFIX + r'strtok\([^)]+\)'),
1993 ('ttyname(', 'ttyname_r(', _UNSAFE_FUNC_PREFIX + r'ttyname\([^)]+\)'),
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001994 )
1995
1996
1997def CheckPosixThreading(filename, clean_lines, linenum, error):
1998 """Checks for calls to thread-unsafe functions.
1999
2000 Much code has been originally written without consideration of
2001 multi-threading. Also, engineers are relying on their old experience;
2002 they have learned posix before threading extensions were added. These
2003 tests guide the engineers to use thread-safe functions (when using
2004 posix directly).
2005
2006 Args:
2007 filename: The name of the current file.
2008 clean_lines: A CleansedLines instance containing the file.
2009 linenum: The number of the line to check.
2010 error: The function to call with any errors found.
2011 """
2012 line = clean_lines.elided[linenum]
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002013 for single_thread_func, multithread_safe_func, pattern in _THREADING_LIST:
2014 # Additional pattern matching check to confirm that this is the
2015 # function we are looking for
2016 if Search(pattern, line):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002017 error(filename, linenum, 'runtime/threadsafe_fn', 2,
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002018 'Consider using ' + multithread_safe_func +
2019 '...) instead of ' + single_thread_func +
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002020 '...) for improved thread safety.')
2021
2022
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002023def CheckVlogArguments(filename, clean_lines, linenum, error):
2024 """Checks that VLOG() is only used for defining a logging level.
2025
2026 For example, VLOG(2) is correct. VLOG(INFO), VLOG(WARNING), VLOG(ERROR), and
2027 VLOG(FATAL) are not.
2028
2029 Args:
2030 filename: The name of the current file.
2031 clean_lines: A CleansedLines instance containing the file.
2032 linenum: The number of the line to check.
2033 error: The function to call with any errors found.
2034 """
2035 line = clean_lines.elided[linenum]
2036 if Search(r'\bVLOG\((INFO|ERROR|WARNING|DFATAL|FATAL)\)', line):
2037 error(filename, linenum, 'runtime/vlog', 5,
2038 'VLOG() should be used with numeric verbosity level. '
2039 'Use LOG() if you want symbolic severity levels.')
2040
erg@google.com26970fa2009-11-17 18:07:32 +00002041# Matches invalid increment: *count++, which moves pointer instead of
erg@google.com6317a9c2009-06-25 00:28:19 +00002042# incrementing a value.
erg@google.com26970fa2009-11-17 18:07:32 +00002043_RE_PATTERN_INVALID_INCREMENT = re.compile(
erg@google.com6317a9c2009-06-25 00:28:19 +00002044 r'^\s*\*\w+(\+\+|--);')
2045
2046
2047def CheckInvalidIncrement(filename, clean_lines, linenum, error):
erg@google.com26970fa2009-11-17 18:07:32 +00002048 """Checks for invalid increment *count++.
erg@google.com6317a9c2009-06-25 00:28:19 +00002049
2050 For example following function:
2051 void increment_counter(int* count) {
2052 *count++;
2053 }
2054 is invalid, because it effectively does count++, moving pointer, and should
2055 be replaced with ++*count, (*count)++ or *count += 1.
2056
2057 Args:
2058 filename: The name of the current file.
2059 clean_lines: A CleansedLines instance containing the file.
2060 linenum: The number of the line to check.
2061 error: The function to call with any errors found.
2062 """
2063 line = clean_lines.elided[linenum]
erg@google.com26970fa2009-11-17 18:07:32 +00002064 if _RE_PATTERN_INVALID_INCREMENT.match(line):
erg@google.com6317a9c2009-06-25 00:28:19 +00002065 error(filename, linenum, 'runtime/invalid_increment', 5,
2066 'Changing pointer instead of value (or unused value of operator*).')
2067
2068
avakulenko@google.com59146752014-08-11 20:20:55 +00002069def IsMacroDefinition(clean_lines, linenum):
2070 if Search(r'^#define', clean_lines[linenum]):
2071 return True
2072
2073 if linenum > 0 and Search(r'\\$', clean_lines[linenum - 1]):
2074 return True
2075
2076 return False
2077
2078
2079def IsForwardClassDeclaration(clean_lines, linenum):
2080 return Match(r'^\s*(\btemplate\b)*.*class\s+\w+;\s*$', clean_lines[linenum])
2081
2082
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002083class _BlockInfo(object):
2084 """Stores information about a generic block of code."""
2085
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002086 def __init__(self, linenum, seen_open_brace):
2087 self.starting_linenum = linenum
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002088 self.seen_open_brace = seen_open_brace
2089 self.open_parentheses = 0
2090 self.inline_asm = _NO_ASM
avakulenko@google.com59146752014-08-11 20:20:55 +00002091 self.check_namespace_indentation = False
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002092
2093 def CheckBegin(self, filename, clean_lines, linenum, error):
2094 """Run checks that applies to text up to the opening brace.
2095
2096 This is mostly for checking the text after the class identifier
2097 and the "{", usually where the base class is specified. For other
2098 blocks, there isn't much to check, so we always pass.
2099
2100 Args:
2101 filename: The name of the current file.
2102 clean_lines: A CleansedLines instance containing the file.
2103 linenum: The number of the line to check.
2104 error: The function to call with any errors found.
2105 """
2106 pass
2107
2108 def CheckEnd(self, filename, clean_lines, linenum, error):
2109 """Run checks that applies to text after the closing brace.
2110
2111 This is mostly used for checking end of namespace comments.
2112
2113 Args:
2114 filename: The name of the current file.
2115 clean_lines: A CleansedLines instance containing the file.
2116 linenum: The number of the line to check.
2117 error: The function to call with any errors found.
2118 """
2119 pass
2120
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002121 def IsBlockInfo(self):
2122 """Returns true if this block is a _BlockInfo.
2123
2124 This is convenient for verifying that an object is an instance of
2125 a _BlockInfo, but not an instance of any of the derived classes.
2126
2127 Returns:
2128 True for this class, False for derived classes.
2129 """
2130 return self.__class__ == _BlockInfo
2131
2132
2133class _ExternCInfo(_BlockInfo):
2134 """Stores information about an 'extern "C"' block."""
2135
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002136 def __init__(self, linenum):
2137 _BlockInfo.__init__(self, linenum, True)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002138
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002139
2140class _ClassInfo(_BlockInfo):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002141 """Stores information about a class."""
2142
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002143 def __init__(self, name, class_or_struct, clean_lines, linenum):
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002144 _BlockInfo.__init__(self, linenum, False)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002145 self.name = name
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002146 self.is_derived = False
avakulenko@google.com59146752014-08-11 20:20:55 +00002147 self.check_namespace_indentation = True
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002148 if class_or_struct == 'struct':
2149 self.access = 'public'
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002150 self.is_struct = True
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002151 else:
2152 self.access = 'private'
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002153 self.is_struct = False
2154
2155 # Remember initial indentation level for this class. Using raw_lines here
2156 # instead of elided to account for leading comments.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002157 self.class_indent = GetIndentLevel(clean_lines.raw_lines[linenum])
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002158
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00002159 # Try to find the end of the class. This will be confused by things like:
2160 # class A {
2161 # } *x = { ...
2162 #
2163 # But it's still good enough for CheckSectionSpacing.
2164 self.last_line = 0
2165 depth = 0
2166 for i in range(linenum, clean_lines.NumLines()):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002167 line = clean_lines.elided[i]
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00002168 depth += line.count('{') - line.count('}')
2169 if not depth:
2170 self.last_line = i
2171 break
2172
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002173 def CheckBegin(self, filename, clean_lines, linenum, error):
2174 # Look for a bare ':'
2175 if Search('(^|[^:]):($|[^:])', clean_lines.elided[linenum]):
2176 self.is_derived = True
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002177
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002178 def CheckEnd(self, filename, clean_lines, linenum, error):
avakulenko@google.com255f2be2014-12-05 22:19:55 +00002179 # If there is a DISALLOW macro, it should appear near the end of
2180 # the class.
2181 seen_last_thing_in_class = False
Edward Lemur6d31ed52019-12-02 23:00:00 +00002182 for i in range(linenum - 1, self.starting_linenum, -1):
avakulenko@google.com255f2be2014-12-05 22:19:55 +00002183 match = Search(
2184 r'\b(DISALLOW_COPY_AND_ASSIGN|DISALLOW_IMPLICIT_CONSTRUCTORS)\(' +
2185 self.name + r'\)',
2186 clean_lines.elided[i])
2187 if match:
2188 if seen_last_thing_in_class:
2189 error(filename, i, 'readability/constructors', 3,
2190 match.group(1) + ' should be the last thing in the class')
2191 break
2192
2193 if not Match(r'^\s*$', clean_lines.elided[i]):
2194 seen_last_thing_in_class = True
2195
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002196 # Check that closing brace is aligned with beginning of the class.
2197 # Only do this if the closing brace is indented by only whitespaces.
2198 # This means we will not check single-line class definitions.
2199 indent = Match(r'^( *)\}', clean_lines.elided[linenum])
2200 if indent and len(indent.group(1)) != self.class_indent:
2201 if self.is_struct:
2202 parent = 'struct ' + self.name
2203 else:
2204 parent = 'class ' + self.name
2205 error(filename, linenum, 'whitespace/indent', 3,
2206 'Closing brace should be aligned with beginning of %s' % parent)
2207
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002208
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002209class _NamespaceInfo(_BlockInfo):
2210 """Stores information about a namespace."""
2211
2212 def __init__(self, name, linenum):
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002213 _BlockInfo.__init__(self, linenum, False)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002214 self.name = name or ''
avakulenko@google.com59146752014-08-11 20:20:55 +00002215 self.check_namespace_indentation = True
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002216
2217 def CheckEnd(self, filename, clean_lines, linenum, error):
2218 """Check end of namespace comments."""
2219 line = clean_lines.raw_lines[linenum]
2220
2221 # Check how many lines is enclosed in this namespace. Don't issue
2222 # warning for missing namespace comments if there aren't enough
2223 # lines. However, do apply checks if there is already an end of
2224 # namespace comment and it's incorrect.
2225 #
2226 # TODO(unknown): We always want to check end of namespace comments
2227 # if a namespace is large, but sometimes we also want to apply the
2228 # check if a short namespace contained nontrivial things (something
2229 # other than forward declarations). There is currently no logic on
2230 # deciding what these nontrivial things are, so this check is
2231 # triggered by namespace size only, which works most of the time.
2232 if (linenum - self.starting_linenum < 10
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002233 and not Match(r'^\s*};*\s*(//|/\*).*\bnamespace\b', line)):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002234 return
2235
2236 # Look for matching comment at end of namespace.
2237 #
2238 # Note that we accept C style "/* */" comments for terminating
2239 # namespaces, so that code that terminate namespaces inside
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002240 # preprocessor macros can be cpplint clean.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002241 #
2242 # We also accept stuff like "// end of namespace <name>." with the
2243 # period at the end.
2244 #
2245 # Besides these, we don't accept anything else, otherwise we might
2246 # get false negatives when existing comment is a substring of the
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002247 # expected namespace.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002248 if self.name:
2249 # Named namespace
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002250 if not Match((r'^\s*};*\s*(//|/\*).*\bnamespace\s+' +
2251 re.escape(self.name) + r'[\*/\.\\\s]*$'),
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002252 line):
2253 error(filename, linenum, 'readability/namespace', 5,
2254 'Namespace should be terminated with "// namespace %s"' %
2255 self.name)
2256 else:
2257 # Anonymous namespace
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002258 if not Match(r'^\s*};*\s*(//|/\*).*\bnamespace[\*/\.\\\s]*$', line):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002259 # If "// namespace anonymous" or "// anonymous namespace (more text)",
2260 # mention "// anonymous namespace" as an acceptable form
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002261 if Match(r'^\s*}.*\b(namespace anonymous|anonymous namespace)\b', line):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002262 error(filename, linenum, 'readability/namespace', 5,
2263 'Anonymous namespace should be terminated with "// namespace"'
2264 ' or "// anonymous namespace"')
2265 else:
2266 error(filename, linenum, 'readability/namespace', 5,
2267 'Anonymous namespace should be terminated with "// namespace"')
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002268
2269
2270class _PreprocessorInfo(object):
2271 """Stores checkpoints of nesting stacks when #if/#else is seen."""
2272
2273 def __init__(self, stack_before_if):
2274 # The entire nesting stack before #if
2275 self.stack_before_if = stack_before_if
2276
2277 # The entire nesting stack up to #else
2278 self.stack_before_else = []
2279
2280 # Whether we have already seen #else or #elif
2281 self.seen_else = False
2282
2283
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002284class NestingState(object):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002285 """Holds states related to parsing braces."""
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002286
2287 def __init__(self):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002288 # Stack for tracking all braces. An object is pushed whenever we
2289 # see a "{", and popped when we see a "}". Only 3 types of
2290 # objects are possible:
2291 # - _ClassInfo: a class or struct.
2292 # - _NamespaceInfo: a namespace.
2293 # - _BlockInfo: some other type of block.
2294 self.stack = []
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002295
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002296 # Top of the previous stack before each Update().
2297 #
2298 # Because the nesting_stack is updated at the end of each line, we
2299 # had to do some convoluted checks to find out what is the current
2300 # scope at the beginning of the line. This check is simplified by
2301 # saving the previous top of nesting stack.
2302 #
2303 # We could save the full stack, but we only need the top. Copying
2304 # the full nesting stack would slow down cpplint by ~10%.
2305 self.previous_stack_top = []
2306
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002307 # Stack of _PreprocessorInfo objects.
2308 self.pp_stack = []
2309
2310 def SeenOpenBrace(self):
2311 """Check if we have seen the opening brace for the innermost block.
2312
2313 Returns:
2314 True if we have seen the opening brace, False if the innermost
2315 block is still expecting an opening brace.
2316 """
2317 return (not self.stack) or self.stack[-1].seen_open_brace
2318
2319 def InNamespaceBody(self):
2320 """Check if we are currently one level inside a namespace body.
2321
2322 Returns:
2323 True if top of the stack is a namespace block, False otherwise.
2324 """
2325 return self.stack and isinstance(self.stack[-1], _NamespaceInfo)
2326
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002327 def InExternC(self):
2328 """Check if we are currently one level inside an 'extern "C"' block.
2329
2330 Returns:
2331 True if top of the stack is an extern block, False otherwise.
2332 """
2333 return self.stack and isinstance(self.stack[-1], _ExternCInfo)
2334
2335 def InClassDeclaration(self):
2336 """Check if we are currently one level inside a class or struct declaration.
2337
2338 Returns:
2339 True if top of the stack is a class/struct, False otherwise.
2340 """
2341 return self.stack and isinstance(self.stack[-1], _ClassInfo)
2342
2343 def InAsmBlock(self):
2344 """Check if we are currently one level inside an inline ASM block.
2345
2346 Returns:
2347 True if the top of the stack is a block containing inline ASM.
2348 """
2349 return self.stack and self.stack[-1].inline_asm != _NO_ASM
2350
2351 def InTemplateArgumentList(self, clean_lines, linenum, pos):
2352 """Check if current position is inside template argument list.
2353
2354 Args:
2355 clean_lines: A CleansedLines instance containing the file.
2356 linenum: The number of the line to check.
2357 pos: position just after the suspected template argument.
2358 Returns:
2359 True if (linenum, pos) is inside template arguments.
2360 """
2361 while linenum < clean_lines.NumLines():
2362 # Find the earliest character that might indicate a template argument
2363 line = clean_lines.elided[linenum]
2364 match = Match(r'^[^{};=\[\]\.<>]*(.)', line[pos:])
2365 if not match:
2366 linenum += 1
2367 pos = 0
2368 continue
2369 token = match.group(1)
2370 pos += len(match.group(0))
2371
2372 # These things do not look like template argument list:
2373 # class Suspect {
2374 # class Suspect x; }
2375 if token in ('{', '}', ';'): return False
2376
2377 # These things look like template argument list:
2378 # template <class Suspect>
2379 # template <class Suspect = default_value>
2380 # template <class Suspect[]>
2381 # template <class Suspect...>
2382 if token in ('>', '=', '[', ']', '.'): return True
2383
2384 # Check if token is an unmatched '<'.
2385 # If not, move on to the next character.
2386 if token != '<':
2387 pos += 1
2388 if pos >= len(line):
2389 linenum += 1
2390 pos = 0
2391 continue
2392
2393 # We can't be sure if we just find a single '<', and need to
2394 # find the matching '>'.
2395 (_, end_line, end_pos) = CloseExpression(clean_lines, linenum, pos - 1)
2396 if end_pos < 0:
2397 # Not sure if template argument list or syntax error in file
2398 return False
2399 linenum = end_line
2400 pos = end_pos
2401 return False
2402
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002403 def UpdatePreprocessor(self, line):
2404 """Update preprocessor stack.
2405
2406 We need to handle preprocessors due to classes like this:
2407 #ifdef SWIG
2408 struct ResultDetailsPageElementExtensionPoint {
2409 #else
2410 struct ResultDetailsPageElementExtensionPoint : public Extension {
2411 #endif
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002412
2413 We make the following assumptions (good enough for most files):
2414 - Preprocessor condition evaluates to true from #if up to first
2415 #else/#elif/#endif.
2416
2417 - Preprocessor condition evaluates to false from #else/#elif up
2418 to #endif. We still perform lint checks on these lines, but
2419 these do not affect nesting stack.
2420
2421 Args:
2422 line: current line to check.
2423 """
2424 if Match(r'^\s*#\s*(if|ifdef|ifndef)\b', line):
2425 # Beginning of #if block, save the nesting stack here. The saved
2426 # stack will allow us to restore the parsing state in the #else case.
2427 self.pp_stack.append(_PreprocessorInfo(copy.deepcopy(self.stack)))
2428 elif Match(r'^\s*#\s*(else|elif)\b', line):
2429 # Beginning of #else block
2430 if self.pp_stack:
2431 if not self.pp_stack[-1].seen_else:
2432 # This is the first #else or #elif block. Remember the
2433 # whole nesting stack up to this point. This is what we
2434 # keep after the #endif.
2435 self.pp_stack[-1].seen_else = True
2436 self.pp_stack[-1].stack_before_else = copy.deepcopy(self.stack)
2437
2438 # Restore the stack to how it was before the #if
2439 self.stack = copy.deepcopy(self.pp_stack[-1].stack_before_if)
2440 else:
2441 # TODO(unknown): unexpected #else, issue warning?
2442 pass
2443 elif Match(r'^\s*#\s*endif\b', line):
2444 # End of #if or #else blocks.
2445 if self.pp_stack:
2446 # If we saw an #else, we will need to restore the nesting
2447 # stack to its former state before the #else, otherwise we
2448 # will just continue from where we left off.
2449 if self.pp_stack[-1].seen_else:
2450 # Here we can just use a shallow copy since we are the last
2451 # reference to it.
2452 self.stack = self.pp_stack[-1].stack_before_else
2453 # Drop the corresponding #if
2454 self.pp_stack.pop()
2455 else:
2456 # TODO(unknown): unexpected #endif, issue warning?
2457 pass
2458
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002459 # TODO(unknown): Update() is too long, but we will refactor later.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002460 def Update(self, filename, clean_lines, linenum, error):
2461 """Update nesting state with current line.
2462
2463 Args:
2464 filename: The name of the current file.
2465 clean_lines: A CleansedLines instance containing the file.
2466 linenum: The number of the line to check.
2467 error: The function to call with any errors found.
2468 """
2469 line = clean_lines.elided[linenum]
2470
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002471 # Remember top of the previous nesting stack.
2472 #
2473 # The stack is always pushed/popped and not modified in place, so
2474 # we can just do a shallow copy instead of copy.deepcopy. Using
2475 # deepcopy would slow down cpplint by ~28%.
2476 if self.stack:
2477 self.previous_stack_top = self.stack[-1]
2478 else:
2479 self.previous_stack_top = None
2480
2481 # Update pp_stack
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002482 self.UpdatePreprocessor(line)
2483
2484 # Count parentheses. This is to avoid adding struct arguments to
2485 # the nesting stack.
2486 if self.stack:
2487 inner_block = self.stack[-1]
2488 depth_change = line.count('(') - line.count(')')
2489 inner_block.open_parentheses += depth_change
2490
2491 # Also check if we are starting or ending an inline assembly block.
2492 if inner_block.inline_asm in (_NO_ASM, _END_ASM):
2493 if (depth_change != 0 and
2494 inner_block.open_parentheses == 1 and
2495 _MATCH_ASM.match(line)):
2496 # Enter assembly block
2497 inner_block.inline_asm = _INSIDE_ASM
2498 else:
2499 # Not entering assembly block. If previous line was _END_ASM,
2500 # we will now shift to _NO_ASM state.
2501 inner_block.inline_asm = _NO_ASM
2502 elif (inner_block.inline_asm == _INSIDE_ASM and
2503 inner_block.open_parentheses == 0):
2504 # Exit assembly block
2505 inner_block.inline_asm = _END_ASM
2506
2507 # Consume namespace declaration at the beginning of the line. Do
2508 # this in a loop so that we catch same line declarations like this:
2509 # namespace proto2 { namespace bridge { class MessageSet; } }
2510 while True:
2511 # Match start of namespace. The "\b\s*" below catches namespace
2512 # declarations even if it weren't followed by a whitespace, this
2513 # is so that we don't confuse our namespace checker. The
2514 # missing spaces will be flagged by CheckSpacing.
2515 namespace_decl_match = Match(r'^\s*namespace\b\s*([:\w]+)?(.*)$', line)
2516 if not namespace_decl_match:
2517 break
2518
2519 new_namespace = _NamespaceInfo(namespace_decl_match.group(1), linenum)
2520 self.stack.append(new_namespace)
2521
2522 line = namespace_decl_match.group(2)
2523 if line.find('{') != -1:
2524 new_namespace.seen_open_brace = True
2525 line = line[line.find('{') + 1:]
2526
2527 # Look for a class declaration in whatever is left of the line
2528 # after parsing namespaces. The regexp accounts for decorated classes
2529 # such as in:
2530 # class LOCKABLE API Object {
2531 # };
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002532 class_decl_match = Match(
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002533 r'^(\s*(?:template\s*<[\w\s<>,:]*>\s*)?'
Clemens Hammacher2cc6e252018-12-20 08:40:19 +00002534 r'(class|struct)\s+(?:[A-Z0-9_]+\s+)*(\w+(?:::\w+)*))'
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002535 r'(.*)$', line)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002536 if (class_decl_match and
2537 (not self.stack or self.stack[-1].open_parentheses == 0)):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002538 # We do not want to accept classes that are actually template arguments:
2539 # template <class Ignore1,
2540 # class Ignore2 = Default<Args>,
2541 # template <Args> class Ignore3>
2542 # void Function() {};
2543 #
2544 # To avoid template argument cases, we scan forward and look for
2545 # an unmatched '>'. If we see one, assume we are inside a
2546 # template argument list.
2547 end_declaration = len(class_decl_match.group(1))
2548 if not self.InTemplateArgumentList(clean_lines, linenum, end_declaration):
2549 self.stack.append(_ClassInfo(
2550 class_decl_match.group(3), class_decl_match.group(2),
2551 clean_lines, linenum))
2552 line = class_decl_match.group(4)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002553
2554 # If we have not yet seen the opening brace for the innermost block,
2555 # run checks here.
2556 if not self.SeenOpenBrace():
2557 self.stack[-1].CheckBegin(filename, clean_lines, linenum, error)
2558
2559 # Update access control if we are inside a class/struct
2560 if self.stack and isinstance(self.stack[-1], _ClassInfo):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002561 classinfo = self.stack[-1]
2562 access_match = Match(
2563 r'^(.*)\b(public|private|protected|signals)(\s+(?:slots\s*)?)?'
2564 r':(?:[^:]|$)',
2565 line)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002566 if access_match:
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002567 classinfo.access = access_match.group(2)
2568
2569 # Check that access keywords are indented +1 space. Skip this
2570 # check if the keywords are not preceded by whitespaces.
2571 indent = access_match.group(1)
2572 if (len(indent) != classinfo.class_indent + 1 and
2573 Match(r'^\s*$', indent)):
2574 if classinfo.is_struct:
2575 parent = 'struct ' + classinfo.name
2576 else:
2577 parent = 'class ' + classinfo.name
2578 slots = ''
2579 if access_match.group(3):
2580 slots = access_match.group(3)
2581 error(filename, linenum, 'whitespace/indent', 3,
2582 '%s%s: should be indented +1 space inside %s' % (
2583 access_match.group(2), slots, parent))
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002584
2585 # Consume braces or semicolons from what's left of the line
2586 while True:
2587 # Match first brace, semicolon, or closed parenthesis.
2588 matched = Match(r'^[^{;)}]*([{;)}])(.*)$', line)
2589 if not matched:
2590 break
2591
2592 token = matched.group(1)
2593 if token == '{':
2594 # If namespace or class hasn't seen a opening brace yet, mark
2595 # namespace/class head as complete. Push a new block onto the
2596 # stack otherwise.
2597 if not self.SeenOpenBrace():
2598 self.stack[-1].seen_open_brace = True
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002599 elif Match(r'^extern\s*"[^"]*"\s*\{', line):
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002600 self.stack.append(_ExternCInfo(linenum))
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002601 else:
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002602 self.stack.append(_BlockInfo(linenum, True))
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002603 if _MATCH_ASM.match(line):
2604 self.stack[-1].inline_asm = _BLOCK_ASM
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002605
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002606 elif token == ';' or token == ')':
2607 # If we haven't seen an opening brace yet, but we already saw
2608 # a semicolon, this is probably a forward declaration. Pop
2609 # the stack for these.
2610 #
2611 # Similarly, if we haven't seen an opening brace yet, but we
2612 # already saw a closing parenthesis, then these are probably
2613 # function arguments with extra "class" or "struct" keywords.
2614 # Also pop these stack for these.
2615 if not self.SeenOpenBrace():
2616 self.stack.pop()
2617 else: # token == '}'
2618 # Perform end of block checks and pop the stack.
2619 if self.stack:
2620 self.stack[-1].CheckEnd(filename, clean_lines, linenum, error)
2621 self.stack.pop()
2622 line = matched.group(2)
2623
2624 def InnermostClass(self):
2625 """Get class info on the top of the stack.
2626
2627 Returns:
2628 A _ClassInfo object if we are inside a class, or None otherwise.
2629 """
2630 for i in range(len(self.stack), 0, -1):
2631 classinfo = self.stack[i - 1]
2632 if isinstance(classinfo, _ClassInfo):
2633 return classinfo
2634 return None
2635
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002636 def CheckCompletedBlocks(self, filename, error):
2637 """Checks that all classes and namespaces have been completely parsed.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002638
2639 Call this when all lines in a file have been processed.
2640 Args:
2641 filename: The name of the current file.
2642 error: The function to call with any errors found.
2643 """
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002644 # Note: This test can result in false positives if #ifdef constructs
2645 # get in the way of brace matching. See the testBuildClass test in
2646 # cpplint_unittest.py for an example of this.
2647 for obj in self.stack:
2648 if isinstance(obj, _ClassInfo):
2649 error(filename, obj.starting_linenum, 'build/class', 5,
2650 'Failed to find complete declaration of class %s' %
2651 obj.name)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002652 elif isinstance(obj, _NamespaceInfo):
2653 error(filename, obj.starting_linenum, 'build/namespaces', 5,
2654 'Failed to find complete declaration of namespace %s' %
2655 obj.name)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002656
2657
2658def CheckForNonStandardConstructs(filename, clean_lines, linenum,
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002659 nesting_state, error):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002660 r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002661
2662 Complain about several constructs which gcc-2 accepts, but which are
2663 not standard C++. Warning about these in lint is one way to ease the
2664 transition to new compilers.
2665 - put storage class first (e.g. "static const" instead of "const static").
2666 - "%lld" instead of %qd" in printf-type functions.
2667 - "%1$d" is non-standard in printf-type functions.
2668 - "\%" is an undefined character escape sequence.
2669 - text after #endif is not allowed.
2670 - invalid inner-style forward declaration.
2671 - >? and <? operators, and their >?= and <?= cousins.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002672
erg@google.com26970fa2009-11-17 18:07:32 +00002673 Additionally, check for constructor/destructor style violations and reference
2674 members, as it is very convenient to do so while checking for
2675 gcc-2 compliance.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002676
2677 Args:
2678 filename: The name of the current file.
2679 clean_lines: A CleansedLines instance containing the file.
2680 linenum: The number of the line to check.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002681 nesting_state: A NestingState instance which maintains information about
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002682 the current stack of nested blocks being parsed.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002683 error: A callable to which errors are reported, which takes 4 arguments:
2684 filename, line number, error level, and message
2685 """
2686
2687 # Remove comments from the line, but leave in strings for now.
2688 line = clean_lines.lines[linenum]
2689
2690 if Search(r'printf\s*\(.*".*%[-+ ]?\d*q', line):
2691 error(filename, linenum, 'runtime/printf_format', 3,
2692 '%q in format strings is deprecated. Use %ll instead.')
2693
2694 if Search(r'printf\s*\(.*".*%\d+\$', line):
2695 error(filename, linenum, 'runtime/printf_format', 2,
2696 '%N$ formats are unconventional. Try rewriting to avoid them.')
2697
2698 # Remove escaped backslashes before looking for undefined escapes.
2699 line = line.replace('\\\\', '')
2700
2701 if Search(r'("|\').*\\(%|\[|\(|{)', line):
2702 error(filename, linenum, 'build/printf_format', 3,
2703 '%, [, (, and { are undefined character escapes. Unescape them.')
2704
2705 # For the rest, work with both comments and strings removed.
2706 line = clean_lines.elided[linenum]
2707
2708 if Search(r'\b(const|volatile|void|char|short|int|long'
2709 r'|float|double|signed|unsigned'
2710 r'|schar|u?int8|u?int16|u?int32|u?int64)'
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002711 r'\s+(register|static|extern|typedef)\b',
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002712 line):
2713 error(filename, linenum, 'build/storage_class', 5,
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002714 'Storage-class specifier (static, extern, typedef, etc) should be '
2715 'at the beginning of the declaration.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002716
2717 if Match(r'\s*#\s*endif\s*[^/\s]+', line):
2718 error(filename, linenum, 'build/endif_comment', 5,
2719 'Uncommented text after #endif is non-standard. Use a comment.')
2720
2721 if Match(r'\s*class\s+(\w+\s*::\s*)+\w+\s*;', line):
2722 error(filename, linenum, 'build/forward_decl', 5,
2723 'Inner-style forward declarations are invalid. Remove this line.')
2724
2725 if Search(r'(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?',
2726 line):
2727 error(filename, linenum, 'build/deprecated', 3,
2728 '>? and <? (max and min) operators are non-standard and deprecated.')
2729
erg@google.com26970fa2009-11-17 18:07:32 +00002730 if Search(r'^\s*const\s*string\s*&\s*\w+\s*;', line):
2731 # TODO(unknown): Could it be expanded safely to arbitrary references,
2732 # without triggering too many false positives? The first
2733 # attempt triggered 5 warnings for mostly benign code in the regtest, hence
2734 # the restriction.
2735 # Here's the original regexp, for the reference:
2736 # type_name = r'\w+((\s*::\s*\w+)|(\s*<\s*\w+?\s*>))?'
2737 # r'\s*const\s*' + type_name + '\s*&\s*\w+\s*;'
2738 error(filename, linenum, 'runtime/member_string_references', 2,
2739 'const string& members are dangerous. It is much better to use '
2740 'alternatives, such as pointers or simple constants.')
2741
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002742 # Everything else in this function operates on class declarations.
2743 # Return early if the top of the nesting stack is not a class, or if
2744 # the class head is not completed yet.
2745 classinfo = nesting_state.InnermostClass()
2746 if not classinfo or not classinfo.seen_open_brace:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002747 return
2748
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002749 # The class may have been declared with namespace or classname qualifiers.
2750 # The constructor and destructor will not have those qualifiers.
2751 base_classname = classinfo.name.split('::')[-1]
2752
2753 # Look for single-argument constructors that aren't marked explicit.
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002754 # Technically a valid construct, but against style.
avakulenko@google.com59146752014-08-11 20:20:55 +00002755 explicit_constructor_match = Match(
danakjd7f56752017-02-22 11:45:06 -05002756 r'\s+(?:(?:inline|constexpr)\s+)*(explicit\s+)?'
2757 r'(?:(?:inline|constexpr)\s+)*%s\s*'
avakulenko@google.com59146752014-08-11 20:20:55 +00002758 r'\(((?:[^()]|\([^()]*\))*)\)'
2759 % re.escape(base_classname),
2760 line)
2761
2762 if explicit_constructor_match:
2763 is_marked_explicit = explicit_constructor_match.group(1)
2764
2765 if not explicit_constructor_match.group(2):
2766 constructor_args = []
2767 else:
2768 constructor_args = explicit_constructor_match.group(2).split(',')
2769
2770 # collapse arguments so that commas in template parameter lists and function
2771 # argument parameter lists don't split arguments in two
2772 i = 0
2773 while i < len(constructor_args):
2774 constructor_arg = constructor_args[i]
2775 while (constructor_arg.count('<') > constructor_arg.count('>') or
2776 constructor_arg.count('(') > constructor_arg.count(')')):
2777 constructor_arg += ',' + constructor_args[i + 1]
2778 del constructor_args[i + 1]
2779 constructor_args[i] = constructor_arg
2780 i += 1
2781
2782 defaulted_args = [arg for arg in constructor_args if '=' in arg]
2783 noarg_constructor = (not constructor_args or # empty arg list
2784 # 'void' arg specifier
2785 (len(constructor_args) == 1 and
2786 constructor_args[0].strip() == 'void'))
2787 onearg_constructor = ((len(constructor_args) == 1 and # exactly one arg
2788 not noarg_constructor) or
2789 # all but at most one arg defaulted
2790 (len(constructor_args) >= 1 and
2791 not noarg_constructor and
2792 len(defaulted_args) >= len(constructor_args) - 1))
2793 initializer_list_constructor = bool(
2794 onearg_constructor and
2795 Search(r'\bstd\s*::\s*initializer_list\b', constructor_args[0]))
2796 copy_constructor = bool(
2797 onearg_constructor and
2798 Match(r'(const\s+)?%s(\s*<[^>]*>)?(\s+const)?\s*(?:<\w+>\s*)?&'
2799 % re.escape(base_classname), constructor_args[0].strip()))
2800
2801 if (not is_marked_explicit and
2802 onearg_constructor and
2803 not initializer_list_constructor and
2804 not copy_constructor):
2805 if defaulted_args:
2806 error(filename, linenum, 'runtime/explicit', 5,
2807 'Constructors callable with one argument '
2808 'should be marked explicit.')
2809 else:
2810 error(filename, linenum, 'runtime/explicit', 5,
2811 'Single-parameter constructors should be marked explicit.')
2812 elif is_marked_explicit and not onearg_constructor:
2813 if noarg_constructor:
2814 error(filename, linenum, 'runtime/explicit', 5,
2815 'Zero-parameter constructors should not be marked explicit.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002816
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002817
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002818def CheckSpacingForFunctionCall(filename, clean_lines, linenum, error):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002819 """Checks for the correctness of various spacing around function calls.
2820
2821 Args:
2822 filename: The name of the current file.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002823 clean_lines: A CleansedLines instance containing the file.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002824 linenum: The number of the line to check.
2825 error: The function to call with any errors found.
2826 """
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002827 line = clean_lines.elided[linenum]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002828
2829 # Since function calls often occur inside if/for/while/switch
2830 # expressions - which have their own, more liberal conventions - we
2831 # first see if we should be looking inside such an expression for a
2832 # function call, to which we can apply more strict standards.
2833 fncall = line # if there's no control flow construct, look at whole line
2834 for pattern in (r'\bif\s*\((.*)\)\s*{',
2835 r'\bfor\s*\((.*)\)\s*{',
2836 r'\bwhile\s*\((.*)\)\s*[{;]',
2837 r'\bswitch\s*\((.*)\)\s*{'):
2838 match = Search(pattern, line)
2839 if match:
2840 fncall = match.group(1) # look inside the parens for function calls
2841 break
2842
2843 # Except in if/for/while/switch, there should never be space
2844 # immediately inside parens (eg "f( 3, 4 )"). We make an exception
2845 # for nested parens ( (a+b) + c ). Likewise, there should never be
2846 # a space before a ( when it's a function argument. I assume it's a
2847 # function argument when the char before the whitespace is legal in
2848 # a function name (alnum + _) and we're not starting a macro. Also ignore
2849 # pointers and references to arrays and functions coz they're too tricky:
2850 # we use a very simple way to recognize these:
2851 # " (something)(maybe-something)" or
2852 # " (something)(maybe-something," or
2853 # " (something)[something]"
2854 # Note that we assume the contents of [] to be short enough that
2855 # they'll never need to wrap.
2856 if ( # Ignore control structures.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002857 not Search(r'\b(if|for|while|switch|return|new|delete|catch|sizeof)\b',
2858 fncall) and
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002859 # Ignore pointers/references to functions.
2860 not Search(r' \([^)]+\)\([^)]*(\)|,$)', fncall) and
2861 # Ignore pointers/references to arrays.
2862 not Search(r' \([^)]+\)\[[^\]]+\]', fncall)):
erg@google.com6317a9c2009-06-25 00:28:19 +00002863 if Search(r'\w\s*\(\s(?!\s*\\$)', fncall): # a ( used for a fn call
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002864 error(filename, linenum, 'whitespace/parens', 4,
2865 'Extra space after ( in function call')
erg@google.com6317a9c2009-06-25 00:28:19 +00002866 elif Search(r'\(\s+(?!(\s*\\)|\()', fncall):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002867 error(filename, linenum, 'whitespace/parens', 2,
2868 'Extra space after (')
2869 if (Search(r'\w\s+\(', fncall) and
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002870 not Search(r'_{0,2}asm_{0,2}\s+_{0,2}volatile_{0,2}\s+\(', fncall) and
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002871 not Search(r'#\s*define|typedef|using\s+\w+\s*=', fncall) and
avakulenko@google.com255f2be2014-12-05 22:19:55 +00002872 not Search(r'\w\s+\((\w+::)*\*\w+\)\(', fncall) and
2873 not Search(r'\bcase\s+\(', fncall)):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002874 # TODO(unknown): Space after an operator function seem to be a common
2875 # error, silence those for now by restricting them to highest verbosity.
2876 if Search(r'\boperator_*\b', line):
2877 error(filename, linenum, 'whitespace/parens', 0,
2878 'Extra space before ( in function call')
2879 else:
2880 error(filename, linenum, 'whitespace/parens', 4,
2881 'Extra space before ( in function call')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002882 # If the ) is followed only by a newline or a { + newline, assume it's
2883 # part of a control statement (if/while/etc), and don't complain
2884 if Search(r'[^)]\s+\)\s*[^{\s]', fncall):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00002885 # If the closing parenthesis is preceded by only whitespaces,
2886 # try to give a more descriptive error message.
2887 if Search(r'^\s+\)', fncall):
2888 error(filename, linenum, 'whitespace/parens', 2,
2889 'Closing ) should be moved to the previous line')
2890 else:
2891 error(filename, linenum, 'whitespace/parens', 2,
2892 'Extra space before )')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002893
2894
2895def IsBlankLine(line):
2896 """Returns true if the given line is blank.
2897
2898 We consider a line to be blank if the line is empty or consists of
2899 only white spaces.
2900
2901 Args:
2902 line: A line of a string.
2903
2904 Returns:
2905 True, if the given line is blank.
2906 """
2907 return not line or line.isspace()
2908
2909
avakulenko@google.com59146752014-08-11 20:20:55 +00002910def CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line,
2911 error):
2912 is_namespace_indent_item = (
2913 len(nesting_state.stack) > 1 and
2914 nesting_state.stack[-1].check_namespace_indentation and
2915 isinstance(nesting_state.previous_stack_top, _NamespaceInfo) and
2916 nesting_state.previous_stack_top == nesting_state.stack[-2])
2917
2918 if ShouldCheckNamespaceIndentation(nesting_state, is_namespace_indent_item,
2919 clean_lines.elided, line):
2920 CheckItemIndentationInNamespace(filename, clean_lines.elided,
2921 line, error)
2922
2923
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002924def CheckForFunctionLengths(filename, clean_lines, linenum,
2925 function_state, error):
2926 """Reports for long function bodies.
2927
2928 For an overview why this is done, see:
Alexandr Ilinff294c32017-04-27 15:57:40 +02002929 https://google.github.io/styleguide/cppguide.html#Write_Short_Functions
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002930
2931 Uses a simplistic algorithm assuming other style guidelines
2932 (especially spacing) are followed.
2933 Only checks unindented functions, so class members are unchecked.
2934 Trivial bodies are unchecked, so constructors with huge initializer lists
2935 may be missed.
2936 Blank/comment lines are not counted so as to avoid encouraging the removal
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00002937 of vertical space and comments just to get through a lint check.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002938 NOLINT *on the last line of a function* disables this check.
2939
2940 Args:
2941 filename: The name of the current file.
2942 clean_lines: A CleansedLines instance containing the file.
2943 linenum: The number of the line to check.
2944 function_state: Current function name and lines in body so far.
2945 error: The function to call with any errors found.
2946 """
2947 lines = clean_lines.lines
2948 line = lines[linenum]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002949 joined_line = ''
2950
2951 starting_func = False
erg@google.com6317a9c2009-06-25 00:28:19 +00002952 regexp = r'(\w(\w|::|\*|\&|\s)*)\(' # decls * & space::name( ...
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002953 match_result = Match(regexp, line)
2954 if match_result:
2955 # If the name is all caps and underscores, figure it's a macro and
2956 # ignore it, unless it's TEST or TEST_F.
2957 function_name = match_result.group(1).split()[-1]
2958 if function_name == 'TEST' or function_name == 'TEST_F' or (
Quinten Yearsley48099572019-02-22 21:13:37 +00002959 not Match(r'[A-Z_0-9]+$', function_name)):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002960 starting_func = True
2961
2962 if starting_func:
2963 body_found = False
Edward Lemur6d31ed52019-12-02 23:00:00 +00002964 for start_linenum in range(linenum, clean_lines.NumLines()):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002965 start_line = lines[start_linenum]
2966 joined_line += ' ' + start_line.lstrip()
2967 if Search(r'(;|})', start_line): # Declarations and trivial functions
2968 body_found = True
2969 break # ... ignore
2970 elif Search(r'{', start_line):
2971 body_found = True
2972 function = Search(r'((\w|:)*)\(', line).group(1)
2973 if Match(r'TEST', function): # Handle TEST... macros
2974 parameter_regexp = Search(r'(\(.*\))', joined_line)
2975 if parameter_regexp: # Ignore bad syntax
2976 function += parameter_regexp.group(1)
2977 else:
2978 function += '()'
2979 function_state.Begin(function)
2980 break
2981 if not body_found:
erg@google.com6317a9c2009-06-25 00:28:19 +00002982 # No body for the function (or evidence of a non-function) was found.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002983 error(filename, linenum, 'readability/fn_size', 5,
2984 'Lint failed to find start of function body.')
2985 elif Match(r'^\}\s*$', line): # function end
erg@google.com35589e62010-11-17 18:58:16 +00002986 function_state.Check(error, filename, linenum)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002987 function_state.End()
2988 elif not Match(r'^\s*$', line):
2989 function_state.Count() # Count non-blank/non-comment lines.
2990
2991
2992_RE_PATTERN_TODO = re.compile(r'^//(\s*)TODO(\(.+?\))?:?(\s|$)?')
2993
2994
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002995def CheckComment(line, filename, linenum, next_line_start, error):
2996 """Checks for common mistakes in comments.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002997
2998 Args:
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002999 line: The line in question.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003000 filename: The name of the current file.
3001 linenum: The number of the line to check.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003002 next_line_start: The first non-whitespace column of the next line.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003003 error: The function to call with any errors found.
3004 """
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003005 commentpos = line.find('//')
3006 if commentpos != -1:
3007 # Check if the // may be in quotes. If so, ignore it
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003008 if re.sub(r'\\.', '', line[0:commentpos]).count('"') % 2 == 0:
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003009 # Allow one space for new scopes, two spaces otherwise:
3010 if (not (Match(r'^.*{ *//', line) and next_line_start == commentpos) and
3011 ((commentpos >= 1 and
3012 line[commentpos-1] not in string.whitespace) or
3013 (commentpos >= 2 and
3014 line[commentpos-2] not in string.whitespace))):
3015 error(filename, linenum, 'whitespace/comments', 2,
3016 'At least two spaces is best between code and comments')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003017
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003018 # Checks for common mistakes in TODO comments.
3019 comment = line[commentpos:]
3020 match = _RE_PATTERN_TODO.match(comment)
3021 if match:
3022 # One whitespace is correct; zero whitespace is handled elsewhere.
3023 leading_whitespace = match.group(1)
3024 if len(leading_whitespace) > 1:
3025 error(filename, linenum, 'whitespace/todo', 2,
3026 'Too many spaces before TODO')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003027
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003028 username = match.group(2)
3029 if not username:
3030 error(filename, linenum, 'readability/todo', 2,
3031 'Missing username in TODO; it should look like '
3032 '"// TODO(my_username): Stuff."')
3033
3034 middle_whitespace = match.group(3)
3035 # Comparisons made explicit for correctness -- pylint: disable=g-explicit-bool-comparison
3036 if middle_whitespace != ' ' and middle_whitespace != '':
3037 error(filename, linenum, 'whitespace/todo', 2,
3038 'TODO(my_username) should be followed by a space')
3039
3040 # If the comment contains an alphanumeric character, there
avakulenko@google.com255f2be2014-12-05 22:19:55 +00003041 # should be a space somewhere between it and the // unless
3042 # it's a /// or //! Doxygen comment.
3043 if (Match(r'//[^ ]*\w', comment) and
3044 not Match(r'(///|//\!)(\s+|$)', comment)):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003045 error(filename, linenum, 'whitespace/comments', 4,
3046 'Should have a space between // and comment')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003047
avakulenko@google.com255f2be2014-12-05 22:19:55 +00003048
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003049def CheckSpacing(filename, clean_lines, linenum, nesting_state, error):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003050 """Checks for the correctness of various spacing issues in the code.
3051
3052 Things we check for: spaces around operators, spaces after
3053 if/for/while/switch, no spaces around parens in function calls, two
3054 spaces between code and comment, don't start a block with a blank
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003055 line, don't end a function with a blank line, don't add a blank line
3056 after public/protected/private, don't have too many blank lines in a row.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003057
3058 Args:
3059 filename: The name of the current file.
3060 clean_lines: A CleansedLines instance containing the file.
3061 linenum: The number of the line to check.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003062 nesting_state: A NestingState instance which maintains information about
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003063 the current stack of nested blocks being parsed.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003064 error: The function to call with any errors found.
3065 """
3066
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003067 # Don't use "elided" lines here, otherwise we can't check commented lines.
3068 # Don't want to use "raw" either, because we don't want to check inside C++11
3069 # raw strings,
3070 raw = clean_lines.lines_without_raw_strings
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003071 line = raw[linenum]
3072
3073 # Before nixing comments, check if the line is blank for no good
3074 # reason. This includes the first line after a block is opened, and
3075 # blank lines at the end of a function (ie, right before a line like '}'
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003076 #
3077 # Skip all the blank line checks if we are immediately inside a
3078 # namespace body. In other words, don't issue blank line warnings
3079 # for this block:
3080 # namespace {
3081 #
3082 # }
3083 #
3084 # A warning about missing end of namespace comments will be issued instead.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003085 #
3086 # Also skip blank line checks for 'extern "C"' blocks, which are formatted
3087 # like namespaces.
3088 if (IsBlankLine(line) and
3089 not nesting_state.InNamespaceBody() and
3090 not nesting_state.InExternC()):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003091 elided = clean_lines.elided
3092 prev_line = elided[linenum - 1]
3093 prevbrace = prev_line.rfind('{')
3094 # TODO(unknown): Don't complain if line before blank line, and line after,
3095 # both start with alnums and are indented the same amount.
3096 # This ignores whitespace at the start of a namespace block
3097 # because those are not usually indented.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003098 if prevbrace != -1 and prev_line[prevbrace:].find('}') == -1:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003099 # OK, we have a blank line at the start of a code block. Before we
3100 # complain, we check if it is an exception to the rule: The previous
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003101 # non-empty line has the parameters of a function header that are indented
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003102 # 4 spaces (because they did not fit in a 80 column line when placed on
3103 # the same line as the function name). We also check for the case where
3104 # the previous line is indented 6 spaces, which may happen when the
3105 # initializers of a constructor do not fit into a 80 column line.
3106 exception = False
3107 if Match(r' {6}\w', prev_line): # Initializer list?
3108 # We are looking for the opening column of initializer list, which
3109 # should be indented 4 spaces to cause 6 space indentation afterwards.
3110 search_position = linenum-2
3111 while (search_position >= 0
3112 and Match(r' {6}\w', elided[search_position])):
3113 search_position -= 1
3114 exception = (search_position >= 0
3115 and elided[search_position][:5] == ' :')
3116 else:
3117 # Search for the function arguments or an initializer list. We use a
3118 # simple heuristic here: If the line is indented 4 spaces; and we have a
3119 # closing paren, without the opening paren, followed by an opening brace
3120 # or colon (for initializer lists) we assume that it is the last line of
3121 # a function header. If we have a colon indented 4 spaces, it is an
3122 # initializer list.
3123 exception = (Match(r' {4}\w[^\(]*\)\s*(const\s*)?(\{\s*$|:)',
3124 prev_line)
3125 or Match(r' {4}:', prev_line))
3126
3127 if not exception:
3128 error(filename, linenum, 'whitespace/blank_line', 2,
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003129 'Redundant blank line at the start of a code block '
3130 'should be deleted.')
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003131 # Ignore blank lines at the end of a block in a long if-else
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003132 # chain, like this:
3133 # if (condition1) {
3134 # // Something followed by a blank line
3135 #
3136 # } else if (condition2) {
3137 # // Something else
3138 # }
3139 if linenum + 1 < clean_lines.NumLines():
3140 next_line = raw[linenum + 1]
3141 if (next_line
3142 and Match(r'\s*}', next_line)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003143 and next_line.find('} else ') == -1):
3144 error(filename, linenum, 'whitespace/blank_line', 3,
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003145 'Redundant blank line at the end of a code block '
3146 'should be deleted.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003147
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003148 matched = Match(r'\s*(public|protected|private):', prev_line)
3149 if matched:
3150 error(filename, linenum, 'whitespace/blank_line', 3,
3151 'Do not leave a blank line after "%s:"' % matched.group(1))
3152
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003153 # Next, check comments
3154 next_line_start = 0
3155 if linenum + 1 < clean_lines.NumLines():
3156 next_line = raw[linenum + 1]
3157 next_line_start = len(next_line) - len(next_line.lstrip())
3158 CheckComment(line, filename, linenum, next_line_start, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003159
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003160 # get rid of comments and strings
3161 line = clean_lines.elided[linenum]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003162
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003163 # You shouldn't have spaces before your brackets, except maybe after
Derek Morrisb8265f12020-04-16 18:40:27 +00003164 # 'delete []' or 'return []() {};', or in the case of c++ attributes
3165 # like 'class [[clang::lto_visibility_public]] MyClass'.
3166 if (Search(r'\w\s+\[', line)
3167 and not Search(r'(?:delete|return)\s+\[', line)
3168 and not Search(r'\s+\[\[', line)):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003169 error(filename, linenum, 'whitespace/braces', 5,
3170 'Extra space before [')
3171
3172 # In range-based for, we wanted spaces before and after the colon, but
3173 # not around "::" tokens that might appear.
3174 if (Search(r'for *\(.*[^:]:[^: ]', line) or
3175 Search(r'for *\(.*[^: ]:[^:]', line)):
3176 error(filename, linenum, 'whitespace/forcolon', 2,
3177 'Missing space around colon in range-based for loop')
3178
3179
3180def CheckOperatorSpacing(filename, clean_lines, linenum, error):
3181 """Checks for horizontal spacing around operators.
3182
3183 Args:
3184 filename: The name of the current file.
3185 clean_lines: A CleansedLines instance containing the file.
3186 linenum: The number of the line to check.
3187 error: The function to call with any errors found.
3188 """
3189 line = clean_lines.elided[linenum]
3190
3191 # Don't try to do spacing checks for operator methods. Do this by
3192 # replacing the troublesome characters with something else,
3193 # preserving column position for all other characters.
3194 #
3195 # The replacement is done repeatedly to avoid false positives from
3196 # operators that call operators.
3197 while True:
3198 match = Match(r'^(.*\boperator\b)(\S+)(\s*\(.*)$', line)
3199 if match:
3200 line = match.group(1) + ('_' * len(match.group(2))) + match.group(3)
3201 else:
3202 break
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003203
3204 # We allow no-spaces around = within an if: "if ( (a=Foo()) == 0 )".
3205 # Otherwise not. Note we only check for non-spaces on *both* sides;
3206 # sometimes people put non-spaces on one side when aligning ='s among
3207 # many lines (not that this is behavior that I approve of...)
avakulenko@google.com255f2be2014-12-05 22:19:55 +00003208 if ((Search(r'[\w.]=', line) or
3209 Search(r'=[\w.]', line))
3210 and not Search(r'\b(if|while|for) ', line)
3211 # Operators taken from [lex.operators] in C++11 standard.
3212 and not Search(r'(>=|<=|==|!=|&=|\^=|\|=|\+=|\*=|\/=|\%=)', line)
3213 and not Search(r'operator=', line)):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003214 error(filename, linenum, 'whitespace/operators', 4,
3215 'Missing spaces around =')
3216
3217 # It's ok not to have spaces around binary operators like + - * /, but if
3218 # there's too little whitespace, we get concerned. It's hard to tell,
3219 # though, so we punt on this one for now. TODO.
3220
3221 # You should always have whitespace around binary operators.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003222 #
3223 # Check <= and >= first to avoid false positives with < and >, then
3224 # check non-include lines for spacing around < and >.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003225 #
3226 # If the operator is followed by a comma, assume it's be used in a
3227 # macro context and don't do any checks. This avoids false
3228 # positives.
3229 #
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003230 # Note that && is not included here. This is because there are too
3231 # many false positives due to RValue references.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003232 match = Search(r'[^<>=!\s](==|!=|<=|>=|\|\|)[^<>=!\s,;\)]', line)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003233 if match:
3234 error(filename, linenum, 'whitespace/operators', 3,
3235 'Missing spaces around %s' % match.group(1))
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003236 elif not Match(r'#.*include', line):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003237 # Look for < that is not surrounded by spaces. This is only
3238 # triggered if both sides are missing spaces, even though
3239 # technically should should flag if at least one side is missing a
3240 # space. This is done to avoid some false positives with shifts.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003241 match = Match(r'^(.*[^\s<])<[^\s=<,]', line)
3242 if match:
3243 (_, _, end_pos) = CloseExpression(
3244 clean_lines, linenum, len(match.group(1)))
3245 if end_pos <= -1:
3246 error(filename, linenum, 'whitespace/operators', 3,
3247 'Missing spaces around <')
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003248
3249 # Look for > that is not surrounded by spaces. Similar to the
3250 # above, we only trigger if both sides are missing spaces to avoid
3251 # false positives with shifts.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003252 match = Match(r'^(.*[^-\s>])>[^\s=>,]', line)
3253 if match:
3254 (_, _, start_pos) = ReverseCloseExpression(
3255 clean_lines, linenum, len(match.group(1)))
3256 if start_pos <= -1:
3257 error(filename, linenum, 'whitespace/operators', 3,
3258 'Missing spaces around >')
3259
3260 # We allow no-spaces around << when used like this: 10<<20, but
3261 # not otherwise (particularly, not when used as streams)
avakulenko@google.com59146752014-08-11 20:20:55 +00003262 #
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003263 # We also allow operators following an opening parenthesis, since
3264 # those tend to be macros that deal with operators.
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003265 match = Search(r'(operator|[^\s(<])(?:L|UL|LL|ULL|l|ul|ll|ull)?<<([^\s,=<])', line)
avakulenko@google.com255f2be2014-12-05 22:19:55 +00003266 if (match and not (match.group(1).isdigit() and match.group(2).isdigit()) and
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003267 not (match.group(1) == 'operator' and match.group(2) == ';')):
3268 error(filename, linenum, 'whitespace/operators', 3,
3269 'Missing spaces around <<')
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003270
3271 # We allow no-spaces around >> for almost anything. This is because
3272 # C++11 allows ">>" to close nested templates, which accounts for
3273 # most cases when ">>" is not followed by a space.
3274 #
3275 # We still warn on ">>" followed by alpha character, because that is
3276 # likely due to ">>" being used for right shifts, e.g.:
3277 # value >> alpha
3278 #
3279 # When ">>" is used to close templates, the alphanumeric letter that
3280 # follows would be part of an identifier, and there should still be
3281 # a space separating the template type and the identifier.
3282 # type<type<type>> alpha
3283 match = Search(r'>>[a-zA-Z_]', line)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003284 if match:
3285 error(filename, linenum, 'whitespace/operators', 3,
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003286 'Missing spaces around >>')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003287
3288 # There shouldn't be space around unary operators
3289 match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line)
3290 if match:
3291 error(filename, linenum, 'whitespace/operators', 4,
3292 'Extra space for operator %s' % match.group(1))
3293
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003294
3295def CheckParenthesisSpacing(filename, clean_lines, linenum, error):
3296 """Checks for horizontal spacing around parentheses.
3297
3298 Args:
3299 filename: The name of the current file.
3300 clean_lines: A CleansedLines instance containing the file.
3301 linenum: The number of the line to check.
3302 error: The function to call with any errors found.
3303 """
3304 line = clean_lines.elided[linenum]
3305
3306 # No spaces after an if, while, switch, or for
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003307 match = Search(r' (if\(|for\(|while\(|switch\()', line)
3308 if match:
3309 error(filename, linenum, 'whitespace/parens', 5,
3310 'Missing space before ( in %s' % match.group(1))
3311
3312 # For if/for/while/switch, the left and right parens should be
3313 # consistent about how many spaces are inside the parens, and
3314 # there should either be zero or one spaces inside the parens.
3315 # We don't want: "if ( foo)" or "if ( foo )".
erg@google.com6317a9c2009-06-25 00:28:19 +00003316 # Exception: "for ( ; foo; bar)" and "for (foo; bar; )" are allowed.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003317 match = Search(r'\b(if|for|while|switch)\s*'
3318 r'\(([ ]*)(.).*[^ ]+([ ]*)\)\s*{\s*$',
3319 line)
3320 if match:
3321 if len(match.group(2)) != len(match.group(4)):
3322 if not (match.group(3) == ';' and
erg@google.com6317a9c2009-06-25 00:28:19 +00003323 len(match.group(2)) == 1 + len(match.group(4)) or
3324 not match.group(2) and Search(r'\bfor\s*\(.*; \)', line)):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003325 error(filename, linenum, 'whitespace/parens', 5,
3326 'Mismatching spaces inside () in %s' % match.group(1))
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003327 if len(match.group(2)) not in [0, 1]:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003328 error(filename, linenum, 'whitespace/parens', 5,
3329 'Should have zero or one spaces inside ( and ) in %s' %
3330 match.group(1))
3331
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003332
3333def CheckCommaSpacing(filename, clean_lines, linenum, error):
3334 """Checks for horizontal spacing near commas and semicolons.
3335
3336 Args:
3337 filename: The name of the current file.
3338 clean_lines: A CleansedLines instance containing the file.
3339 linenum: The number of the line to check.
3340 error: The function to call with any errors found.
3341 """
3342 raw = clean_lines.lines_without_raw_strings
3343 line = clean_lines.elided[linenum]
3344
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003345 # 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 +00003346 #
3347 # This does not apply when the non-space character following the
3348 # comma is another comma, since the only time when that happens is
3349 # for empty macro arguments.
3350 #
3351 # We run this check in two passes: first pass on elided lines to
3352 # verify that lines contain missing whitespaces, second pass on raw
3353 # lines to confirm that those missing whitespaces are not due to
3354 # elided comments.
avakulenko@google.com59146752014-08-11 20:20:55 +00003355 if (Search(r',[^,\s]', ReplaceAll(r'\boperator\s*,\s*\(', 'F(', line)) and
3356 Search(r',[^,\s]', raw[linenum])):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003357 error(filename, linenum, 'whitespace/comma', 3,
3358 'Missing space after ,')
3359
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003360 # You should always have a space after a semicolon
3361 # except for few corner cases
3362 # TODO(unknown): clarify if 'if (1) { return 1;}' is requires one more
3363 # space after ;
3364 if Search(r';[^\s};\\)/]', line):
3365 error(filename, linenum, 'whitespace/semicolon', 3,
3366 'Missing space after ;')
3367
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003368
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003369def _IsType(clean_lines, nesting_state, expr):
3370 """Check if expression looks like a type name, returns true if so.
3371
3372 Args:
3373 clean_lines: A CleansedLines instance containing the file.
3374 nesting_state: A NestingState instance which maintains information about
3375 the current stack of nested blocks being parsed.
3376 expr: The expression to check.
3377 Returns:
3378 True, if token looks like a type.
3379 """
3380 # Keep only the last token in the expression
3381 last_word = Match(r'^.*(\b\S+)$', expr)
3382 if last_word:
3383 token = last_word.group(1)
3384 else:
3385 token = expr
3386
3387 # Match native types and stdint types
3388 if _TYPES.match(token):
3389 return True
3390
3391 # Try a bit harder to match templated types. Walk up the nesting
3392 # stack until we find something that resembles a typename
3393 # declaration for what we are looking for.
3394 typename_pattern = (r'\b(?:typename|class|struct)\s+' + re.escape(token) +
3395 r'\b')
3396 block_index = len(nesting_state.stack) - 1
3397 while block_index >= 0:
3398 if isinstance(nesting_state.stack[block_index], _NamespaceInfo):
3399 return False
3400
3401 # Found where the opening brace is. We want to scan from this
3402 # line up to the beginning of the function, minus a few lines.
3403 # template <typename Type1, // stop scanning here
3404 # ...>
3405 # class C
3406 # : public ... { // start scanning here
3407 last_line = nesting_state.stack[block_index].starting_linenum
3408
3409 next_block_start = 0
3410 if block_index > 0:
3411 next_block_start = nesting_state.stack[block_index - 1].starting_linenum
3412 first_line = last_line
3413 while first_line >= next_block_start:
3414 if clean_lines.elided[first_line].find('template') >= 0:
3415 break
3416 first_line -= 1
3417 if first_line < next_block_start:
3418 # Didn't find any "template" keyword before reaching the next block,
3419 # there are probably no template things to check for this block
3420 block_index -= 1
3421 continue
3422
3423 # Look for typename in the specified range
Edward Lemur6d31ed52019-12-02 23:00:00 +00003424 for i in range(first_line, last_line + 1, 1):
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003425 if Search(typename_pattern, clean_lines.elided[i]):
3426 return True
3427 block_index -= 1
3428
3429 return False
3430
3431
3432def CheckBracesSpacing(filename, clean_lines, linenum, nesting_state, error):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003433 """Checks for horizontal spacing near commas.
3434
3435 Args:
3436 filename: The name of the current file.
3437 clean_lines: A CleansedLines instance containing the file.
3438 linenum: The number of the line to check.
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003439 nesting_state: A NestingState instance which maintains information about
3440 the current stack of nested blocks being parsed.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003441 error: The function to call with any errors found.
3442 """
3443 line = clean_lines.elided[linenum]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003444
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003445 # Except after an opening paren, or after another opening brace (in case of
3446 # an initializer list, for instance), you should have spaces before your
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003447 # braces when they are delimiting blocks, classes, namespaces etc.
3448 # And since you should never have braces at the beginning of a line,
3449 # this is an easy test. Except that braces used for initialization don't
3450 # follow the same rule; we often don't want spaces before those.
avakulenko@google.com255f2be2014-12-05 22:19:55 +00003451 match = Match(r'^(.*[^ ({>]){', line)
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003452
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003453 if match:
3454 # Try a bit harder to check for brace initialization. This
3455 # happens in one of the following forms:
3456 # Constructor() : initializer_list_{} { ... }
3457 # Constructor{}.MemberFunction()
3458 # Type variable{};
3459 # FunctionCall(type{}, ...);
3460 # LastArgument(..., type{});
3461 # LOG(INFO) << type{} << " ...";
3462 # map_of_type[{...}] = ...;
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003463 # ternary = expr ? new type{} : nullptr;
3464 # OuterTemplate<InnerTemplateConstructor<Type>{}>
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003465 #
3466 # We check for the character following the closing brace, and
3467 # silence the warning if it's one of those listed above, i.e.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003468 # "{.;,)<>]:".
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003469 #
3470 # To account for nested initializer list, we allow any number of
3471 # closing braces up to "{;,)<". We can't simply silence the
3472 # warning on first sight of closing brace, because that would
3473 # cause false negatives for things that are not initializer lists.
3474 # Silence this: But not this:
3475 # Outer{ if (...) {
3476 # Inner{...} if (...){ // Missing space before {
3477 # }; }
3478 #
3479 # There is a false negative with this approach if people inserted
3480 # spurious semicolons, e.g. "if (cond){};", but we will catch the
3481 # spurious semicolon with a separate check.
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003482 leading_text = match.group(1)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003483 (endline, endlinenum, endpos) = CloseExpression(
3484 clean_lines, linenum, len(match.group(1)))
3485 trailing_text = ''
3486 if endpos > -1:
3487 trailing_text = endline[endpos:]
Edward Lemur6d31ed52019-12-02 23:00:00 +00003488 for offset in range(endlinenum + 1,
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003489 min(endlinenum + 3, clean_lines.NumLines() - 1)):
3490 trailing_text += clean_lines.elided[offset]
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003491 # We also suppress warnings for `uint64_t{expression}` etc., as the style
3492 # guide recommends brace initialization for integral types to avoid
3493 # overflow/truncation.
3494 if (not Match(r'^[\s}]*[{.;,)<>\]:]', trailing_text)
3495 and not _IsType(clean_lines, nesting_state, leading_text)):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003496 error(filename, linenum, 'whitespace/braces', 5,
3497 'Missing space before {')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003498
3499 # Make sure '} else {' has spaces.
3500 if Search(r'}else', line):
3501 error(filename, linenum, 'whitespace/braces', 5,
3502 'Missing space before else')
3503
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003504 # You shouldn't have a space before a semicolon at the end of the line.
3505 # There's a special case for "for" since the style guide allows space before
3506 # the semicolon there.
3507 if Search(r':\s*;\s*$', line):
3508 error(filename, linenum, 'whitespace/semicolon', 5,
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003509 'Semicolon defining empty statement. Use {} instead.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003510 elif Search(r'^\s*;\s*$', line):
3511 error(filename, linenum, 'whitespace/semicolon', 5,
3512 'Line contains only semicolon. If this should be an empty statement, '
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003513 'use {} instead.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003514 elif (Search(r'\s+;\s*$', line) and
3515 not Search(r'\bfor\b', line)):
3516 error(filename, linenum, 'whitespace/semicolon', 5,
3517 'Extra space before last semicolon. If this should be an empty '
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003518 'statement, use {} instead.')
3519
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003520
3521def IsDecltype(clean_lines, linenum, column):
3522 """Check if the token ending on (linenum, column) is decltype().
3523
3524 Args:
3525 clean_lines: A CleansedLines instance containing the file.
3526 linenum: the number of the line to check.
3527 column: end column of the token to check.
3528 Returns:
3529 True if this token is decltype() expression, False otherwise.
3530 """
3531 (text, _, start_col) = ReverseCloseExpression(clean_lines, linenum, column)
3532 if start_col < 0:
3533 return False
3534 if Search(r'\bdecltype\s*$', text[0:start_col]):
3535 return True
3536 return False
3537
3538
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003539def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error):
3540 """Checks for additional blank line issues related to sections.
3541
3542 Currently the only thing checked here is blank line before protected/private.
3543
3544 Args:
3545 filename: The name of the current file.
3546 clean_lines: A CleansedLines instance containing the file.
3547 class_info: A _ClassInfo objects.
3548 linenum: The number of the line to check.
3549 error: The function to call with any errors found.
3550 """
3551 # Skip checks if the class is small, where small means 25 lines or less.
3552 # 25 lines seems like a good cutoff since that's the usual height of
3553 # terminals, and any class that can't fit in one screen can't really
3554 # be considered "small".
3555 #
3556 # Also skip checks if we are on the first line. This accounts for
3557 # classes that look like
3558 # class Foo { public: ... };
3559 #
3560 # If we didn't find the end of the class, last_line would be zero,
3561 # and the check will be skipped by the first condition.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003562 if (class_info.last_line - class_info.starting_linenum <= 24 or
3563 linenum <= class_info.starting_linenum):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003564 return
3565
3566 matched = Match(r'\s*(public|protected|private):', clean_lines.lines[linenum])
3567 if matched:
3568 # Issue warning if the line before public/protected/private was
3569 # not a blank line, but don't do this if the previous line contains
3570 # "class" or "struct". This can happen two ways:
3571 # - We are at the beginning of the class.
3572 # - We are forward-declaring an inner class that is semantically
3573 # private, but needed to be public for implementation reasons.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003574 # Also ignores cases where the previous line ends with a backslash as can be
3575 # common when defining classes in C macros.
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003576 prev_line = clean_lines.lines[linenum - 1]
3577 if (not IsBlankLine(prev_line) and
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003578 not Search(r'\b(class|struct)\b', prev_line) and
3579 not Search(r'\\$', prev_line)):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003580 # Try a bit harder to find the beginning of the class. This is to
3581 # account for multi-line base-specifier lists, e.g.:
3582 # class Derived
3583 # : public Base {
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003584 end_class_head = class_info.starting_linenum
3585 for i in range(class_info.starting_linenum, linenum):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003586 if Search(r'\{\s*$', clean_lines.lines[i]):
3587 end_class_head = i
3588 break
3589 if end_class_head < linenum - 1:
3590 error(filename, linenum, 'whitespace/blank_line', 3,
3591 '"%s:" should be preceded by a blank line' % matched.group(1))
3592
3593
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003594def GetPreviousNonBlankLine(clean_lines, linenum):
3595 """Return the most recent non-blank line and its line number.
3596
3597 Args:
3598 clean_lines: A CleansedLines instance containing the file contents.
3599 linenum: The number of the line to check.
3600
3601 Returns:
3602 A tuple with two elements. The first element is the contents of the last
3603 non-blank line before the current line, or the empty string if this is the
3604 first non-blank line. The second is the line number of that line, or -1
3605 if this is the first non-blank line.
3606 """
3607
3608 prevlinenum = linenum - 1
3609 while prevlinenum >= 0:
3610 prevline = clean_lines.elided[prevlinenum]
3611 if not IsBlankLine(prevline): # if not a blank line...
3612 return (prevline, prevlinenum)
3613 prevlinenum -= 1
3614 return ('', -1)
3615
3616
3617def CheckBraces(filename, clean_lines, linenum, error):
3618 """Looks for misplaced braces (e.g. at the end of line).
3619
3620 Args:
3621 filename: The name of the current file.
3622 clean_lines: A CleansedLines instance containing the file.
3623 linenum: The number of the line to check.
3624 error: The function to call with any errors found.
3625 """
3626
3627 line = clean_lines.elided[linenum] # get rid of comments and strings
3628
3629 if Match(r'\s*{\s*$', line):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003630 # We allow an open brace to start a line in the case where someone is using
3631 # braces in a block to explicitly create a new scope, which is commonly used
3632 # to control the lifetime of stack-allocated variables. Braces are also
3633 # used for brace initializers inside function calls. We don't detect this
3634 # perfectly: we just don't complain if the last non-whitespace character on
3635 # the previous non-blank line is ',', ';', ':', '(', '{', or '}', or if the
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003636 # previous line starts a preprocessor block. We also allow a brace on the
3637 # following line if it is part of an array initialization and would not fit
3638 # within the 80 character limit of the preceding line.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003639 prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003640 if (not Search(r'[,;:}{(]\s*$', prevline) and
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003641 not Match(r'\s*#', prevline) and
3642 not (GetLineWidth(prevline) > _line_length - 2 and '[]' in prevline)):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003643 error(filename, linenum, 'whitespace/braces', 4,
3644 '{ should almost always be at the end of the previous line')
3645
3646 # An else clause should be on the same line as the preceding closing brace.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003647 if Match(r'\s*else\b\s*(?:if\b|\{|$)', line):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003648 prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
3649 if Match(r'\s*}\s*$', prevline):
3650 error(filename, linenum, 'whitespace/newline', 4,
3651 'An else should appear on the same line as the preceding }')
3652
3653 # If braces come on one side of an else, they should be on both.
3654 # However, we have to worry about "else if" that spans multiple lines!
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003655 if Search(r'else if\s*\(', line): # could be multi-line if
3656 brace_on_left = bool(Search(r'}\s*else if\s*\(', line))
3657 # find the ( after the if
3658 pos = line.find('else if')
3659 pos = line.find('(', pos)
3660 if pos > 0:
3661 (endline, _, endpos) = CloseExpression(clean_lines, linenum, pos)
3662 brace_on_right = endline[endpos:].find('{') != -1
3663 if brace_on_left != brace_on_right: # must be brace after if
3664 error(filename, linenum, 'readability/braces', 5,
3665 'If an else has a brace on one side, it should have it on both')
3666 elif Search(r'}\s*else[^{]*$', line) or Match(r'[^}]*else\s*{', line):
3667 error(filename, linenum, 'readability/braces', 5,
3668 'If an else has a brace on one side, it should have it on both')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003669
3670 # Likewise, an else should never have the else clause on the same line
3671 if Search(r'\belse [^\s{]', line) and not Search(r'\belse if\b', line):
3672 error(filename, linenum, 'whitespace/newline', 4,
3673 'Else clause should never be on same line as else (use 2 lines)')
3674
3675 # In the same way, a do/while should never be on one line
3676 if Match(r'\s*do [^\s{]', line):
3677 error(filename, linenum, 'whitespace/newline', 4,
3678 'do/while clauses should not be on a single line')
3679
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003680 # Check single-line if/else bodies. The style guide says 'curly braces are not
3681 # required for single-line statements'. We additionally allow multi-line,
3682 # single statements, but we reject anything with more than one semicolon in
3683 # it. This means that the first semicolon after the if should be at the end of
3684 # its line, and the line after that should have an indent level equal to or
3685 # lower than the if. We also check for ambiguous if/else nesting without
3686 # braces.
3687 if_else_match = Search(r'\b(if\s*\(|else\b)', line)
3688 if if_else_match and not Match(r'\s*#', line):
3689 if_indent = GetIndentLevel(line)
3690 endline, endlinenum, endpos = line, linenum, if_else_match.end()
3691 if_match = Search(r'\bif\s*\(', line)
3692 if if_match:
3693 # This could be a multiline if condition, so find the end first.
3694 pos = if_match.end() - 1
3695 (endline, endlinenum, endpos) = CloseExpression(clean_lines, linenum, pos)
3696 # Check for an opening brace, either directly after the if or on the next
3697 # line. If found, this isn't a single-statement conditional.
3698 if (not Match(r'\s*{', endline[endpos:])
3699 and not (Match(r'\s*$', endline[endpos:])
3700 and endlinenum < (len(clean_lines.elided) - 1)
3701 and Match(r'\s*{', clean_lines.elided[endlinenum + 1]))):
3702 while (endlinenum < len(clean_lines.elided)
3703 and ';' not in clean_lines.elided[endlinenum][endpos:]):
3704 endlinenum += 1
3705 endpos = 0
3706 if endlinenum < len(clean_lines.elided):
3707 endline = clean_lines.elided[endlinenum]
3708 # We allow a mix of whitespace and closing braces (e.g. for one-liner
3709 # methods) and a single \ after the semicolon (for macros)
3710 endpos = endline.find(';')
3711 if not Match(r';[\s}]*(\\?)$', endline[endpos:]):
avakulenko@google.com59146752014-08-11 20:20:55 +00003712 # Semicolon isn't the last character, there's something trailing.
3713 # Output a warning if the semicolon is not contained inside
3714 # a lambda expression.
3715 if not Match(r'^[^{};]*\[[^\[\]]*\][^{}]*\{[^{}]*\}\s*\)*[;,]\s*$',
3716 endline):
3717 error(filename, linenum, 'readability/braces', 4,
3718 'If/else bodies with multiple statements require braces')
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003719 elif endlinenum < len(clean_lines.elided) - 1:
3720 # Make sure the next line is dedented
3721 next_line = clean_lines.elided[endlinenum + 1]
3722 next_indent = GetIndentLevel(next_line)
3723 # With ambiguous nested if statements, this will error out on the
3724 # if that *doesn't* match the else, regardless of whether it's the
3725 # inner one or outer one.
3726 if (if_match and Match(r'\s*else\b', next_line)
3727 and next_indent != if_indent):
3728 error(filename, linenum, 'readability/braces', 4,
3729 'Else clause should be indented at the same level as if. '
3730 'Ambiguous nested if/else chains require braces.')
3731 elif next_indent > if_indent:
3732 error(filename, linenum, 'readability/braces', 4,
3733 'If/else bodies with multiple statements require braces')
3734
3735
3736def CheckTrailingSemicolon(filename, clean_lines, linenum, error):
3737 """Looks for redundant trailing semicolon.
3738
3739 Args:
3740 filename: The name of the current file.
3741 clean_lines: A CleansedLines instance containing the file.
3742 linenum: The number of the line to check.
3743 error: The function to call with any errors found.
3744 """
3745
3746 line = clean_lines.elided[linenum]
3747
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003748 # Block bodies should not be followed by a semicolon. Due to C++11
3749 # brace initialization, there are more places where semicolons are
3750 # required than not, so we use a whitelist approach to check these
3751 # rather than a blacklist. These are the places where "};" should
3752 # be replaced by just "}":
3753 # 1. Some flavor of block following closing parenthesis:
3754 # for (;;) {};
3755 # while (...) {};
3756 # switch (...) {};
3757 # Function(...) {};
3758 # if (...) {};
3759 # if (...) else if (...) {};
3760 #
3761 # 2. else block:
3762 # if (...) else {};
3763 #
3764 # 3. const member function:
3765 # Function(...) const {};
3766 #
3767 # 4. Block following some statement:
3768 # x = 42;
3769 # {};
3770 #
3771 # 5. Block at the beginning of a function:
3772 # Function(...) {
3773 # {};
3774 # }
3775 #
3776 # Note that naively checking for the preceding "{" will also match
3777 # braces inside multi-dimensional arrays, but this is fine since
3778 # that expression will not contain semicolons.
3779 #
3780 # 6. Block following another block:
3781 # while (true) {}
3782 # {};
3783 #
3784 # 7. End of namespaces:
3785 # namespace {};
3786 #
3787 # These semicolons seems far more common than other kinds of
3788 # redundant semicolons, possibly due to people converting classes
3789 # to namespaces. For now we do not warn for this case.
3790 #
3791 # Try matching case 1 first.
3792 match = Match(r'^(.*\)\s*)\{', line)
3793 if match:
3794 # Matched closing parenthesis (case 1). Check the token before the
3795 # matching opening parenthesis, and don't warn if it looks like a
3796 # macro. This avoids these false positives:
3797 # - macro that defines a base class
3798 # - multi-line macro that defines a base class
3799 # - macro that defines the whole class-head
3800 #
3801 # But we still issue warnings for macros that we know are safe to
3802 # warn, specifically:
3803 # - TEST, TEST_F, TEST_P, MATCHER, MATCHER_P
3804 # - TYPED_TEST
3805 # - INTERFACE_DEF
3806 # - EXCLUSIVE_LOCKS_REQUIRED, SHARED_LOCKS_REQUIRED, LOCKS_EXCLUDED:
3807 #
3808 # We implement a whitelist of safe macros instead of a blacklist of
3809 # unsafe macros, even though the latter appears less frequently in
3810 # google code and would have been easier to implement. This is because
3811 # the downside for getting the whitelist wrong means some extra
3812 # semicolons, while the downside for getting the blacklist wrong
3813 # would result in compile errors.
3814 #
avakulenko@google.com255f2be2014-12-05 22:19:55 +00003815 # In addition to macros, we also don't want to warn on
3816 # - Compound literals
3817 # - Lambdas
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003818 # - alignas specifier with anonymous structs
3819 # - decltype
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003820 closing_brace_pos = match.group(1).rfind(')')
3821 opening_parenthesis = ReverseCloseExpression(
3822 clean_lines, linenum, closing_brace_pos)
3823 if opening_parenthesis[2] > -1:
3824 line_prefix = opening_parenthesis[0][0:opening_parenthesis[2]]
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003825 macro = Search(r'\b([A-Z_][A-Z0-9_]*)\s*$', line_prefix)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003826 func = Match(r'^(.*\])\s*$', line_prefix)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003827 if ((macro and
3828 macro.group(1) not in (
3829 'TEST', 'TEST_F', 'MATCHER', 'MATCHER_P', 'TYPED_TEST',
3830 'EXCLUSIVE_LOCKS_REQUIRED', 'SHARED_LOCKS_REQUIRED',
3831 'LOCKS_EXCLUDED', 'INTERFACE_DEF')) or
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003832 (func and not Search(r'\boperator\s*\[\s*\]', func.group(1))) or
avakulenko@google.com255f2be2014-12-05 22:19:55 +00003833 Search(r'\b(?:struct|union)\s+alignas\s*$', line_prefix) or
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003834 Search(r'\bdecltype$', line_prefix) or
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003835 Search(r'\s+=\s*$', line_prefix)):
3836 match = None
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003837 if (match and
3838 opening_parenthesis[1] > 1 and
3839 Search(r'\]\s*$', clean_lines.elided[opening_parenthesis[1] - 1])):
3840 # Multi-line lambda-expression
3841 match = None
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003842
3843 else:
3844 # Try matching cases 2-3.
3845 match = Match(r'^(.*(?:else|\)\s*const)\s*)\{', line)
3846 if not match:
3847 # Try matching cases 4-6. These are always matched on separate lines.
3848 #
3849 # Note that we can't simply concatenate the previous line to the
3850 # current line and do a single match, otherwise we may output
3851 # duplicate warnings for the blank line case:
3852 # if (cond) {
3853 # // blank line
3854 # }
3855 prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
3856 if prevline and Search(r'[;{}]\s*$', prevline):
3857 match = Match(r'^(\s*)\{', line)
3858
3859 # Check matching closing brace
3860 if match:
3861 (endline, endlinenum, endpos) = CloseExpression(
3862 clean_lines, linenum, len(match.group(1)))
3863 if endpos > -1 and Match(r'^\s*;', endline[endpos:]):
3864 # Current {} pair is eligible for semicolon check, and we have found
3865 # the redundant semicolon, output warning here.
3866 #
3867 # Note: because we are scanning forward for opening braces, and
3868 # outputting warnings for the matching closing brace, if there are
3869 # nested blocks with trailing semicolons, we will get the error
3870 # messages in reversed order.
3871 error(filename, endlinenum, 'readability/braces', 4,
3872 "You don't need a ; after a }")
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003873
3874
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003875def CheckEmptyBlockBody(filename, clean_lines, linenum, error):
3876 """Look for empty loop/conditional body with only a single semicolon.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003877
3878 Args:
3879 filename: The name of the current file.
3880 clean_lines: A CleansedLines instance containing the file.
3881 linenum: The number of the line to check.
3882 error: The function to call with any errors found.
3883 """
3884
3885 # Search for loop keywords at the beginning of the line. Because only
3886 # whitespaces are allowed before the keywords, this will also ignore most
3887 # do-while-loops, since those lines should start with closing brace.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003888 #
3889 # We also check "if" blocks here, since an empty conditional block
3890 # is likely an error.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003891 line = clean_lines.elided[linenum]
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003892 matched = Match(r'\s*(for|while|if)\s*\(', line)
3893 if matched:
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003894 # Find the end of the conditional expression.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003895 (end_line, end_linenum, end_pos) = CloseExpression(
3896 clean_lines, linenum, line.find('('))
3897
3898 # Output warning if what follows the condition expression is a semicolon.
3899 # No warning for all other cases, including whitespace or newline, since we
3900 # have a separate check for semicolons preceded by whitespace.
3901 if end_pos >= 0 and Match(r';', end_line[end_pos:]):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003902 if matched.group(1) == 'if':
3903 error(filename, end_linenum, 'whitespace/empty_conditional_body', 5,
3904 'Empty conditional bodies should use {}')
3905 else:
3906 error(filename, end_linenum, 'whitespace/empty_loop_body', 5,
3907 'Empty loop bodies should use {} or continue')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003908
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003909 # Check for if statements that have completely empty bodies (no comments)
3910 # and no else clauses.
3911 if end_pos >= 0 and matched.group(1) == 'if':
3912 # Find the position of the opening { for the if statement.
3913 # Return without logging an error if it has no brackets.
3914 opening_linenum = end_linenum
3915 opening_line_fragment = end_line[end_pos:]
3916 # Loop until EOF or find anything that's not whitespace or opening {.
3917 while not Search(r'^\s*\{', opening_line_fragment):
3918 if Search(r'^(?!\s*$)', opening_line_fragment):
3919 # Conditional has no brackets.
3920 return
3921 opening_linenum += 1
3922 if opening_linenum == len(clean_lines.elided):
3923 # Couldn't find conditional's opening { or any code before EOF.
3924 return
3925 opening_line_fragment = clean_lines.elided[opening_linenum]
3926 # Set opening_line (opening_line_fragment may not be entire opening line).
3927 opening_line = clean_lines.elided[opening_linenum]
3928
3929 # Find the position of the closing }.
3930 opening_pos = opening_line_fragment.find('{')
3931 if opening_linenum == end_linenum:
3932 # We need to make opening_pos relative to the start of the entire line.
3933 opening_pos += end_pos
3934 (closing_line, closing_linenum, closing_pos) = CloseExpression(
3935 clean_lines, opening_linenum, opening_pos)
3936 if closing_pos < 0:
3937 return
3938
3939 # Now construct the body of the conditional. This consists of the portion
3940 # of the opening line after the {, all lines until the closing line,
3941 # and the portion of the closing line before the }.
3942 if (clean_lines.raw_lines[opening_linenum] !=
3943 CleanseComments(clean_lines.raw_lines[opening_linenum])):
3944 # Opening line ends with a comment, so conditional isn't empty.
3945 return
3946 if closing_linenum > opening_linenum:
3947 # Opening line after the {. Ignore comments here since we checked above.
3948 body = list(opening_line[opening_pos+1:])
3949 # All lines until closing line, excluding closing line, with comments.
3950 body.extend(clean_lines.raw_lines[opening_linenum+1:closing_linenum])
3951 # Closing line before the }. Won't (and can't) have comments.
3952 body.append(clean_lines.elided[closing_linenum][:closing_pos-1])
3953 body = '\n'.join(body)
3954 else:
3955 # If statement has brackets and fits on a single line.
3956 body = opening_line[opening_pos+1:closing_pos-1]
3957
3958 # Check if the body is empty
3959 if not _EMPTY_CONDITIONAL_BODY_PATTERN.search(body):
3960 return
3961 # The body is empty. Now make sure there's not an else clause.
3962 current_linenum = closing_linenum
3963 current_line_fragment = closing_line[closing_pos:]
3964 # Loop until EOF or find anything that's not whitespace or else clause.
3965 while Search(r'^\s*$|^(?=\s*else)', current_line_fragment):
3966 if Search(r'^(?=\s*else)', current_line_fragment):
3967 # Found an else clause, so don't log an error.
3968 return
3969 current_linenum += 1
3970 if current_linenum == len(clean_lines.elided):
3971 break
3972 current_line_fragment = clean_lines.elided[current_linenum]
3973
3974 # The body is empty and there's no else clause until EOF or other code.
3975 error(filename, end_linenum, 'whitespace/empty_if_body', 4,
3976 ('If statement had no body and no else clause'))
3977
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003978
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003979def FindCheckMacro(line):
3980 """Find a replaceable CHECK-like macro.
3981
3982 Args:
3983 line: line to search on.
3984 Returns:
3985 (macro name, start position), or (None, -1) if no replaceable
3986 macro is found.
3987 """
3988 for macro in _CHECK_MACROS:
3989 i = line.find(macro)
3990 if i >= 0:
3991 # Find opening parenthesis. Do a regular expression match here
3992 # to make sure that we are matching the expected CHECK macro, as
3993 # opposed to some other macro that happens to contain the CHECK
3994 # substring.
3995 matched = Match(r'^(.*\b' + macro + r'\s*)\(', line)
3996 if not matched:
3997 continue
3998 return (macro, len(matched.group(1)))
3999 return (None, -1)
4000
4001
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004002def CheckCheck(filename, clean_lines, linenum, error):
4003 """Checks the use of CHECK and EXPECT macros.
4004
4005 Args:
4006 filename: The name of the current file.
4007 clean_lines: A CleansedLines instance containing the file.
4008 linenum: The number of the line to check.
4009 error: The function to call with any errors found.
4010 """
4011
4012 # Decide the set of replacement macros that should be suggested
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004013 lines = clean_lines.elided
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004014 (check_macro, start_pos) = FindCheckMacro(lines[linenum])
4015 if not check_macro:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004016 return
4017
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004018 # Find end of the boolean expression by matching parentheses
4019 (last_line, end_line, end_pos) = CloseExpression(
4020 clean_lines, linenum, start_pos)
4021 if end_pos < 0:
4022 return
avakulenko@google.com59146752014-08-11 20:20:55 +00004023
4024 # If the check macro is followed by something other than a
4025 # semicolon, assume users will log their own custom error messages
4026 # and don't suggest any replacements.
4027 if not Match(r'\s*;', last_line[end_pos:]):
4028 return
4029
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004030 if linenum == end_line:
4031 expression = lines[linenum][start_pos + 1:end_pos - 1]
4032 else:
4033 expression = lines[linenum][start_pos + 1:]
Edward Lemur6d31ed52019-12-02 23:00:00 +00004034 for i in range(linenum + 1, end_line):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004035 expression += lines[i]
4036 expression += last_line[0:end_pos - 1]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004037
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004038 # Parse expression so that we can take parentheses into account.
4039 # This avoids false positives for inputs like "CHECK((a < 4) == b)",
4040 # which is not replaceable by CHECK_LE.
4041 lhs = ''
4042 rhs = ''
4043 operator = None
4044 while expression:
4045 matched = Match(r'^\s*(<<|<<=|>>|>>=|->\*|->|&&|\|\||'
4046 r'==|!=|>=|>|<=|<|\()(.*)$', expression)
4047 if matched:
4048 token = matched.group(1)
4049 if token == '(':
4050 # Parenthesized operand
4051 expression = matched.group(2)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004052 (end, _) = FindEndOfExpressionInLine(expression, 0, ['('])
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004053 if end < 0:
4054 return # Unmatched parenthesis
4055 lhs += '(' + expression[0:end]
4056 expression = expression[end:]
4057 elif token in ('&&', '||'):
4058 # Logical and/or operators. This means the expression
4059 # contains more than one term, for example:
4060 # CHECK(42 < a && a < b);
4061 #
4062 # These are not replaceable with CHECK_LE, so bail out early.
4063 return
4064 elif token in ('<<', '<<=', '>>', '>>=', '->*', '->'):
4065 # Non-relational operator
4066 lhs += token
4067 expression = matched.group(2)
4068 else:
4069 # Relational operator
4070 operator = token
4071 rhs = matched.group(2)
4072 break
4073 else:
4074 # Unparenthesized operand. Instead of appending to lhs one character
4075 # at a time, we do another regular expression match to consume several
4076 # characters at once if possible. Trivial benchmark shows that this
4077 # is more efficient when the operands are longer than a single
4078 # character, which is generally the case.
4079 matched = Match(r'^([^-=!<>()&|]+)(.*)$', expression)
4080 if not matched:
4081 matched = Match(r'^(\s*\S)(.*)$', expression)
4082 if not matched:
4083 break
4084 lhs += matched.group(1)
4085 expression = matched.group(2)
4086
4087 # Only apply checks if we got all parts of the boolean expression
4088 if not (lhs and operator and rhs):
4089 return
4090
4091 # Check that rhs do not contain logical operators. We already know
4092 # that lhs is fine since the loop above parses out && and ||.
4093 if rhs.find('&&') > -1 or rhs.find('||') > -1:
4094 return
4095
4096 # At least one of the operands must be a constant literal. This is
4097 # to avoid suggesting replacements for unprintable things like
4098 # CHECK(variable != iterator)
4099 #
4100 # The following pattern matches decimal, hex integers, strings, and
4101 # characters (in that order).
4102 lhs = lhs.strip()
4103 rhs = rhs.strip()
4104 match_constant = r'^([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')$'
4105 if Match(match_constant, lhs) or Match(match_constant, rhs):
4106 # Note: since we know both lhs and rhs, we can provide a more
4107 # descriptive error message like:
4108 # Consider using CHECK_EQ(x, 42) instead of CHECK(x == 42)
4109 # Instead of:
4110 # Consider using CHECK_EQ instead of CHECK(a == b)
4111 #
4112 # We are still keeping the less descriptive message because if lhs
4113 # or rhs gets long, the error message might become unreadable.
4114 error(filename, linenum, 'readability/check', 2,
4115 'Consider using %s instead of %s(a %s b)' % (
4116 _CHECK_REPLACEMENT[check_macro][operator],
4117 check_macro, operator))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004118
4119
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004120def CheckAltTokens(filename, clean_lines, linenum, error):
4121 """Check alternative keywords being used in boolean expressions.
4122
4123 Args:
4124 filename: The name of the current file.
4125 clean_lines: A CleansedLines instance containing the file.
4126 linenum: The number of the line to check.
4127 error: The function to call with any errors found.
4128 """
4129 line = clean_lines.elided[linenum]
4130
4131 # Avoid preprocessor lines
4132 if Match(r'^\s*#', line):
4133 return
4134
4135 # Last ditch effort to avoid multi-line comments. This will not help
4136 # if the comment started before the current line or ended after the
4137 # current line, but it catches most of the false positives. At least,
4138 # it provides a way to workaround this warning for people who use
4139 # multi-line comments in preprocessor macros.
4140 #
4141 # TODO(unknown): remove this once cpplint has better support for
4142 # multi-line comments.
4143 if line.find('/*') >= 0 or line.find('*/') >= 0:
4144 return
4145
4146 for match in _ALT_TOKEN_REPLACEMENT_PATTERN.finditer(line):
4147 error(filename, linenum, 'readability/alt_tokens', 2,
4148 'Use operator %s instead of %s' % (
4149 _ALT_TOKEN_REPLACEMENT[match.group(1)], match.group(1)))
4150
4151
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004152def GetLineWidth(line):
4153 """Determines the width of the line in column positions.
4154
4155 Args:
4156 line: A string, which may be a Unicode string.
4157
4158 Returns:
4159 The width of the line in column positions, accounting for Unicode
4160 combining characters and wide characters.
4161 """
Edward Lemur6d31ed52019-12-02 23:00:00 +00004162 if sys.version_info == 2 and isinstance(line, unicode):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004163 width = 0
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004164 for uc in unicodedata.normalize('NFC', line):
4165 if unicodedata.east_asian_width(uc) in ('W', 'F'):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004166 width += 2
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004167 elif not unicodedata.combining(uc):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004168 width += 1
4169 return width
4170 else:
4171 return len(line)
4172
4173
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004174def CheckStyle(filename, clean_lines, linenum, file_extension, nesting_state,
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004175 error):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004176 """Checks rules from the 'C++ style rules' section of cppguide.html.
4177
4178 Most of these rules are hard to test (naming, comment style), but we
4179 do what we can. In particular we check for 2-space indents, line lengths,
4180 tab usage, spaces inside code, etc.
4181
4182 Args:
4183 filename: The name of the current file.
4184 clean_lines: A CleansedLines instance containing the file.
4185 linenum: The number of the line to check.
4186 file_extension: The extension (without the dot) of the filename.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004187 nesting_state: A NestingState instance which maintains information about
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004188 the current stack of nested blocks being parsed.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004189 error: The function to call with any errors found.
4190 """
4191
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004192 # Don't use "elided" lines here, otherwise we can't check commented lines.
4193 # Don't want to use "raw" either, because we don't want to check inside C++11
4194 # raw strings,
4195 raw_lines = clean_lines.lines_without_raw_strings
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004196 line = raw_lines[linenum]
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004197 prev = raw_lines[linenum - 1] if linenum > 0 else ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004198
4199 if line.find('\t') != -1:
4200 error(filename, linenum, 'whitespace/tab', 1,
4201 'Tab found; better to use spaces')
4202
4203 # One or three blank spaces at the beginning of the line is weird; it's
4204 # hard to reconcile that with 2-space indents.
4205 # NOTE: here are the conditions rob pike used for his tests. Mine aren't
4206 # as sophisticated, but it may be worth becoming so: RLENGTH==initial_spaces
4207 # if(RLENGTH > 20) complain = 0;
4208 # if(match($0, " +(error|private|public|protected):")) complain = 0;
4209 # if(match(prev, "&& *$")) complain = 0;
4210 # if(match(prev, "\\|\\| *$")) complain = 0;
4211 # if(match(prev, "[\",=><] *$")) complain = 0;
4212 # if(match($0, " <<")) complain = 0;
4213 # if(match(prev, " +for \\(")) complain = 0;
4214 # if(prevodd && match(prevprev, " +for \\(")) complain = 0;
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004215 scope_or_label_pattern = r'\s*\w+\s*:\s*\\?$'
4216 classinfo = nesting_state.InnermostClass()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004217 initial_spaces = 0
4218 cleansed_line = clean_lines.elided[linenum]
4219 while initial_spaces < len(line) and line[initial_spaces] == ' ':
4220 initial_spaces += 1
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004221 # There are certain situations we allow one space, notably for
4222 # section labels, and also lines containing multi-line raw strings.
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004223 # We also don't check for lines that look like continuation lines
4224 # (of lines ending in double quotes, commas, equals, or angle brackets)
4225 # because the rules for how to indent those are non-trivial.
4226 if (not Search(r'[",=><] *$', prev) and
4227 (initial_spaces == 1 or initial_spaces == 3) and
4228 not Match(scope_or_label_pattern, cleansed_line) and
4229 not (clean_lines.raw_lines[linenum] != line and
4230 Match(r'^\s*""', line))):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004231 error(filename, linenum, 'whitespace/indent', 3,
4232 'Weird number of spaces at line-start. '
4233 'Are you using a 2-space indent?')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004234
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004235 if line and line[-1].isspace():
4236 error(filename, linenum, 'whitespace/end_of_line', 4,
4237 'Line ends in whitespace. Consider deleting these extra spaces.')
4238
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004239 # Check if the line is a header guard.
4240 is_header_guard = False
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00004241 if file_extension == 'h':
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004242 cppvar = GetHeaderGuardCPPVariable(filename)
4243 if (line.startswith('#ifndef %s' % cppvar) or
4244 line.startswith('#define %s' % cppvar) or
4245 line.startswith('#endif // %s' % cppvar)):
4246 is_header_guard = True
4247 # #include lines and header guards can be long, since there's no clean way to
4248 # split them.
erg@google.com6317a9c2009-06-25 00:28:19 +00004249 #
4250 # URLs can be long too. It's possible to split these, but it makes them
4251 # harder to cut&paste.
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004252 #
4253 # The "$Id:...$" comment may also get very long without it being the
4254 # developers fault.
erg@google.com6317a9c2009-06-25 00:28:19 +00004255 if (not line.startswith('#include') and not is_header_guard and
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004256 not Match(r'^\s*//.*http(s?)://\S*$', line) and
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004257 not Match(r'^\s*//\s*[^\s]*$', line) and
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004258 not Match(r'^// \$Id:.*#[0-9]+ \$$', line)):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004259 line_width = GetLineWidth(line)
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004260 if line_width > _line_length:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004261 error(filename, linenum, 'whitespace/line_length', 2,
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004262 'Lines should be <= %i characters long' % _line_length)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004263
4264 if (cleansed_line.count(';') > 1 and
4265 # for loops are allowed two ;'s (and may run over two lines).
4266 cleansed_line.find('for') == -1 and
4267 (GetPreviousNonBlankLine(clean_lines, linenum)[0].find('for') == -1 or
4268 GetPreviousNonBlankLine(clean_lines, linenum)[0].find(';') != -1) and
4269 # It's ok to have many commands in a switch case that fits in 1 line
4270 not ((cleansed_line.find('case ') != -1 or
4271 cleansed_line.find('default:') != -1) and
4272 cleansed_line.find('break;') != -1)):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004273 error(filename, linenum, 'whitespace/newline', 0,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004274 'More than one command on the same line')
4275
4276 # Some more style checks
4277 CheckBraces(filename, clean_lines, linenum, error)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004278 CheckTrailingSemicolon(filename, clean_lines, linenum, error)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004279 CheckEmptyBlockBody(filename, clean_lines, linenum, error)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004280 CheckSpacing(filename, clean_lines, linenum, nesting_state, error)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004281 CheckOperatorSpacing(filename, clean_lines, linenum, error)
4282 CheckParenthesisSpacing(filename, clean_lines, linenum, error)
4283 CheckCommaSpacing(filename, clean_lines, linenum, error)
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004284 CheckBracesSpacing(filename, clean_lines, linenum, nesting_state, error)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004285 CheckSpacingForFunctionCall(filename, clean_lines, linenum, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004286 CheckCheck(filename, clean_lines, linenum, error)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004287 CheckAltTokens(filename, clean_lines, linenum, error)
4288 classinfo = nesting_state.InnermostClass()
4289 if classinfo:
4290 CheckSectionSpacing(filename, clean_lines, classinfo, linenum, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004291
4292
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004293_RE_PATTERN_INCLUDE = re.compile(r'^\s*#\s*include\s*([<"])([^>"]*)[>"].*$')
4294# Matches the first component of a filename delimited by -s and _s. That is:
4295# _RE_FIRST_COMPONENT.match('foo').group(0) == 'foo'
4296# _RE_FIRST_COMPONENT.match('foo.cc').group(0) == 'foo'
4297# _RE_FIRST_COMPONENT.match('foo-bar_baz.cc').group(0) == 'foo'
4298# _RE_FIRST_COMPONENT.match('foo_bar-baz.cc').group(0) == 'foo'
4299_RE_FIRST_COMPONENT = re.compile(r'^[^-_.]+')
4300
4301
4302def _DropCommonSuffixes(filename):
4303 """Drops common suffixes like _test.cc or -inl.h from filename.
4304
4305 For example:
4306 >>> _DropCommonSuffixes('foo/foo-inl.h')
4307 'foo/foo'
4308 >>> _DropCommonSuffixes('foo/bar/foo.cc')
4309 'foo/bar/foo'
4310 >>> _DropCommonSuffixes('foo/foo_internal.h')
4311 'foo/foo'
4312 >>> _DropCommonSuffixes('foo/foo_unusualinternal.h')
4313 'foo/foo_unusualinternal'
4314
4315 Args:
4316 filename: The input filename.
4317
4318 Returns:
4319 The filename with the common suffix removed.
4320 """
4321 for suffix in ('test.cc', 'regtest.cc', 'unittest.cc',
4322 'inl.h', 'impl.h', 'internal.h'):
4323 if (filename.endswith(suffix) and len(filename) > len(suffix) and
4324 filename[-len(suffix) - 1] in ('-', '_')):
4325 return filename[:-len(suffix) - 1]
4326 return os.path.splitext(filename)[0]
4327
4328
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004329def _ClassifyInclude(fileinfo, include, is_system):
4330 """Figures out what kind of header 'include' is.
4331
4332 Args:
4333 fileinfo: The current file cpplint is running over. A FileInfo instance.
4334 include: The path to a #included file.
4335 is_system: True if the #include used <> rather than "".
4336
4337 Returns:
4338 One of the _XXX_HEADER constants.
4339
4340 For example:
4341 >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'stdio.h', True)
4342 _C_SYS_HEADER
4343 >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'string', True)
4344 _CPP_SYS_HEADER
4345 >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', False)
4346 _LIKELY_MY_HEADER
4347 >>> _ClassifyInclude(FileInfo('foo/foo_unknown_extension.cc'),
4348 ... 'bar/foo_other_ext.h', False)
4349 _POSSIBLE_MY_HEADER
4350 >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/bar.h', False)
4351 _OTHER_HEADER
4352 """
4353 # This is a list of all standard c++ header files, except
4354 # those already checked for above.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004355 is_cpp_h = include in _CPP_HEADERS
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004356
4357 if is_system:
4358 if is_cpp_h:
4359 return _CPP_SYS_HEADER
4360 else:
4361 return _C_SYS_HEADER
4362
4363 # If the target file and the include we're checking share a
4364 # basename when we drop common extensions, and the include
4365 # lives in . , then it's likely to be owned by the target file.
4366 target_dir, target_base = (
4367 os.path.split(_DropCommonSuffixes(fileinfo.RepositoryName())))
4368 include_dir, include_base = os.path.split(_DropCommonSuffixes(include))
4369 if target_base == include_base and (
4370 include_dir == target_dir or
4371 include_dir == os.path.normpath(target_dir + '/../public')):
4372 return _LIKELY_MY_HEADER
4373
4374 # If the target and include share some initial basename
4375 # component, it's possible the target is implementing the
4376 # include, so it's allowed to be first, but we'll never
4377 # complain if it's not there.
4378 target_first_component = _RE_FIRST_COMPONENT.match(target_base)
4379 include_first_component = _RE_FIRST_COMPONENT.match(include_base)
4380 if (target_first_component and include_first_component and
4381 target_first_component.group(0) ==
4382 include_first_component.group(0)):
4383 return _POSSIBLE_MY_HEADER
4384
4385 return _OTHER_HEADER
4386
4387
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004388
erg@google.com6317a9c2009-06-25 00:28:19 +00004389def CheckIncludeLine(filename, clean_lines, linenum, include_state, error):
4390 """Check rules that are applicable to #include lines.
4391
4392 Strings on #include lines are NOT removed from elided line, to make
4393 certain tasks easier. However, to prevent false positives, checks
4394 applicable to #include lines in CheckLanguage must be put here.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004395
4396 Args:
4397 filename: The name of the current file.
4398 clean_lines: A CleansedLines instance containing the file.
4399 linenum: The number of the line to check.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004400 include_state: An _IncludeState instance in which the headers are inserted.
4401 error: The function to call with any errors found.
4402 """
4403 fileinfo = FileInfo(filename)
erg@google.com6317a9c2009-06-25 00:28:19 +00004404 line = clean_lines.lines[linenum]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004405
4406 # "include" should use the new style "foo/bar.h" instead of just "bar.h"
avakulenko@google.com59146752014-08-11 20:20:55 +00004407 # Only do this check if the included header follows google naming
4408 # conventions. If not, assume that it's a 3rd party API that
4409 # requires special include conventions.
4410 #
4411 # We also make an exception for Lua headers, which follow google
4412 # naming convention but not the include convention.
4413 match = Match(r'#include\s*"([^/]+\.h)"', line)
4414 if match and not _THIRD_PARTY_HEADERS_PATTERN.match(match.group(1)):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004415 error(filename, linenum, 'build/include', 4,
4416 'Include the directory when naming .h files')
4417
4418 # we shouldn't include a file more than once. actually, there are a
4419 # handful of instances where doing so is okay, but in general it's
4420 # not.
erg@google.com6317a9c2009-06-25 00:28:19 +00004421 match = _RE_PATTERN_INCLUDE.search(line)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004422 if match:
4423 include = match.group(2)
4424 is_system = (match.group(1) == '<')
avakulenko@google.com59146752014-08-11 20:20:55 +00004425 duplicate_line = include_state.FindHeader(include)
4426 if duplicate_line >= 0:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004427 error(filename, linenum, 'build/include', 4,
4428 '"%s" already included at %s:%s' %
avakulenko@google.com59146752014-08-11 20:20:55 +00004429 (include, filename, duplicate_line))
avakulenko@google.com255f2be2014-12-05 22:19:55 +00004430 elif (include.endswith('.cc') and
4431 os.path.dirname(fileinfo.RepositoryName()) != os.path.dirname(include)):
4432 error(filename, linenum, 'build/include', 4,
4433 'Do not include .cc files from other packages')
avakulenko@google.com59146752014-08-11 20:20:55 +00004434 elif not _THIRD_PARTY_HEADERS_PATTERN.match(include):
4435 include_state.include_list[-1].append((include, linenum))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004436
4437 # We want to ensure that headers appear in the right order:
4438 # 1) for foo.cc, foo.h (preferred location)
4439 # 2) c system files
4440 # 3) cpp system files
4441 # 4) for foo.cc, foo.h (deprecated location)
4442 # 5) other google headers
4443 #
4444 # We classify each include statement as one of those 5 types
4445 # using a number of techniques. The include_state object keeps
4446 # track of the highest type seen, and complains if we see a
4447 # lower type after that.
4448 error_message = include_state.CheckNextIncludeOrder(
4449 _ClassifyInclude(fileinfo, include, is_system))
4450 if error_message:
4451 error(filename, linenum, 'build/include_order', 4,
4452 '%s. Should be: %s.h, c system, c++ system, other.' %
4453 (error_message, fileinfo.BaseName()))
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004454 canonical_include = include_state.CanonicalizeAlphabeticalOrder(include)
4455 if not include_state.IsInAlphabeticalOrder(
4456 clean_lines, linenum, canonical_include):
erg@google.com26970fa2009-11-17 18:07:32 +00004457 error(filename, linenum, 'build/include_alpha', 4,
4458 'Include "%s" not in alphabetical order' % include)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004459 include_state.SetLastHeader(canonical_include)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004460
erg@google.com6317a9c2009-06-25 00:28:19 +00004461
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004462
4463def _GetTextInside(text, start_pattern):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004464 r"""Retrieves all the text between matching open and close parentheses.
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004465
4466 Given a string of lines and a regular expression string, retrieve all the text
4467 following the expression and between opening punctuation symbols like
4468 (, [, or {, and the matching close-punctuation symbol. This properly nested
4469 occurrences of the punctuations, so for the text like
4470 printf(a(), b(c()));
4471 a call to _GetTextInside(text, r'printf\(') will return 'a(), b(c())'.
4472 start_pattern must match string having an open punctuation symbol at the end.
4473
4474 Args:
4475 text: The lines to extract text. Its comments and strings must be elided.
4476 It can be single line and can span multiple lines.
4477 start_pattern: The regexp string indicating where to start extracting
4478 the text.
4479 Returns:
4480 The extracted text.
4481 None if either the opening string or ending punctuation could not be found.
4482 """
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004483 # TODO(unknown): Audit cpplint.py to see what places could be profitably
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004484 # rewritten to use _GetTextInside (and use inferior regexp matching today).
4485
4486 # Give opening punctuations to get the matching close-punctuations.
4487 matching_punctuation = {'(': ')', '{': '}', '[': ']'}
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +00004488 closing_punctuation = set(matching_punctuation.values())
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004489
4490 # Find the position to start extracting text.
4491 match = re.search(start_pattern, text, re.M)
4492 if not match: # start_pattern not found in text.
4493 return None
4494 start_position = match.end(0)
4495
4496 assert start_position > 0, (
4497 'start_pattern must ends with an opening punctuation.')
4498 assert text[start_position - 1] in matching_punctuation, (
4499 'start_pattern must ends with an opening punctuation.')
4500 # Stack of closing punctuations we expect to have in text after position.
4501 punctuation_stack = [matching_punctuation[text[start_position - 1]]]
4502 position = start_position
4503 while punctuation_stack and position < len(text):
4504 if text[position] == punctuation_stack[-1]:
4505 punctuation_stack.pop()
4506 elif text[position] in closing_punctuation:
4507 # A closing punctuation without matching opening punctuations.
4508 return None
4509 elif text[position] in matching_punctuation:
4510 punctuation_stack.append(matching_punctuation[text[position]])
4511 position += 1
4512 if punctuation_stack:
4513 # Opening punctuations left without matching close-punctuations.
4514 return None
4515 # punctuations match.
4516 return text[start_position:position - 1]
4517
4518
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004519# Patterns for matching call-by-reference parameters.
4520#
4521# Supports nested templates up to 2 levels deep using this messy pattern:
4522# < (?: < (?: < [^<>]*
4523# >
4524# | [^<>] )*
4525# >
4526# | [^<>] )*
4527# >
4528_RE_PATTERN_IDENT = r'[_a-zA-Z]\w*' # =~ [[:alpha:]][[:alnum:]]*
4529_RE_PATTERN_TYPE = (
4530 r'(?:const\s+)?(?:typename\s+|class\s+|struct\s+|union\s+|enum\s+)?'
4531 r'(?:\w|'
4532 r'\s*<(?:<(?:<[^<>]*>|[^<>])*>|[^<>])*>|'
4533 r'::)+')
4534# A call-by-reference parameter ends with '& identifier'.
4535_RE_PATTERN_REF_PARAM = re.compile(
4536 r'(' + _RE_PATTERN_TYPE + r'(?:\s*(?:\bconst\b|[*]))*\s*'
4537 r'&\s*' + _RE_PATTERN_IDENT + r')\s*(?:=[^,()]+)?[,)]')
4538# A call-by-const-reference parameter either ends with 'const& identifier'
4539# or looks like 'const type& identifier' when 'type' is atomic.
4540_RE_PATTERN_CONST_REF_PARAM = (
4541 r'(?:.*\s*\bconst\s*&\s*' + _RE_PATTERN_IDENT +
4542 r'|const\s+' + _RE_PATTERN_TYPE + r'\s*&\s*' + _RE_PATTERN_IDENT + r')')
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004543# Stream types.
4544_RE_PATTERN_REF_STREAM_PARAM = (
4545 r'(?:.*stream\s*&\s*' + _RE_PATTERN_IDENT + r')')
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004546
4547
4548def CheckLanguage(filename, clean_lines, linenum, file_extension,
4549 include_state, nesting_state, error):
erg@google.com6317a9c2009-06-25 00:28:19 +00004550 """Checks rules from the 'C++ language rules' section of cppguide.html.
4551
4552 Some of these rules are hard to test (function overloading, using
4553 uint32 inappropriately), but we do the best we can.
4554
4555 Args:
4556 filename: The name of the current file.
4557 clean_lines: A CleansedLines instance containing the file.
4558 linenum: The number of the line to check.
4559 file_extension: The extension (without the dot) of the filename.
4560 include_state: An _IncludeState instance in which the headers are inserted.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004561 nesting_state: A NestingState instance which maintains information about
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004562 the current stack of nested blocks being parsed.
erg@google.com6317a9c2009-06-25 00:28:19 +00004563 error: The function to call with any errors found.
4564 """
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004565 # If the line is empty or consists of entirely a comment, no need to
4566 # check it.
4567 line = clean_lines.elided[linenum]
4568 if not line:
4569 return
4570
erg@google.com6317a9c2009-06-25 00:28:19 +00004571 match = _RE_PATTERN_INCLUDE.search(line)
4572 if match:
4573 CheckIncludeLine(filename, clean_lines, linenum, include_state, error)
4574 return
4575
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004576 # Reset include state across preprocessor directives. This is meant
4577 # to silence warnings for conditional includes.
avakulenko@google.com59146752014-08-11 20:20:55 +00004578 match = Match(r'^\s*#\s*(if|ifdef|ifndef|elif|else|endif)\b', line)
4579 if match:
4580 include_state.ResetSection(match.group(1))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004581
4582 # Make Windows paths like Unix.
4583 fullname = os.path.abspath(filename).replace('\\', '/')
skym@chromium.org3990c412016-02-05 20:55:12 +00004584
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004585 # Perform other checks now that we are sure that this is not an include line
4586 CheckCasts(filename, clean_lines, linenum, error)
4587 CheckGlobalStatic(filename, clean_lines, linenum, error)
4588 CheckPrintf(filename, clean_lines, linenum, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004589
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00004590 if file_extension == 'h':
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004591 # TODO(unknown): check that 1-arg constructors are explicit.
4592 # How to tell it's a constructor?
4593 # (handled in CheckForNonStandardConstructs for now)
avakulenko@google.com59146752014-08-11 20:20:55 +00004594 # TODO(unknown): check that classes declare or disable copy/assign
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004595 # (level 1 error)
4596 pass
4597
4598 # Check if people are using the verboten C basic types. The only exception
4599 # we regularly allow is "unsigned short port" for port.
4600 if Search(r'\bshort port\b', line):
4601 if not Search(r'\bunsigned short port\b', line):
4602 error(filename, linenum, 'runtime/int', 4,
4603 'Use "unsigned short" for ports, not "short"')
4604 else:
4605 match = Search(r'\b(short|long(?! +double)|long long)\b', line)
4606 if match:
4607 error(filename, linenum, 'runtime/int', 4,
4608 'Use int16/int64/etc, rather than the C type %s' % match.group(1))
4609
erg@google.com26970fa2009-11-17 18:07:32 +00004610 # Check if some verboten operator overloading is going on
4611 # TODO(unknown): catch out-of-line unary operator&:
4612 # class X {};
4613 # int operator&(const X& x) { return 42; } // unary operator&
4614 # The trick is it's hard to tell apart from binary operator&:
4615 # class Y { int operator&(const Y& x) { return 23; } }; // binary operator&
4616 if Search(r'\boperator\s*&\s*\(\s*\)', line):
4617 error(filename, linenum, 'runtime/operator', 4,
4618 'Unary operator& is dangerous. Do not use it.')
4619
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004620 # Check for suspicious usage of "if" like
4621 # } if (a == b) {
4622 if Search(r'\}\s*if\s*\(', line):
4623 error(filename, linenum, 'readability/braces', 4,
4624 'Did you mean "else if"? If not, start a new line for "if".')
4625
4626 # Check for potential format string bugs like printf(foo).
4627 # We constrain the pattern not to pick things like DocidForPrintf(foo).
4628 # Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str())
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004629 # TODO(unknown): Catch the following case. Need to change the calling
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004630 # convention of the whole function to process multiple line to handle it.
4631 # printf(
4632 # boy_this_is_a_really_long_variable_that_cannot_fit_on_the_prev_line);
4633 printf_args = _GetTextInside(line, r'(?i)\b(string)?printf\s*\(')
4634 if printf_args:
4635 match = Match(r'([\w.\->()]+)$', printf_args)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004636 if match and match.group(1) != '__VA_ARGS__':
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004637 function_name = re.search(r'\b((?:string)?printf)\s*\(',
4638 line, re.I).group(1)
4639 error(filename, linenum, 'runtime/printf', 4,
4640 'Potential format string bug. Do %s("%%s", %s) instead.'
4641 % (function_name, match.group(1)))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004642
4643 # Check for potential memset bugs like memset(buf, sizeof(buf), 0).
4644 match = Search(r'memset\s*\(([^,]*),\s*([^,]*),\s*0\s*\)', line)
4645 if match and not Match(r"^''|-?[0-9]+|0x[0-9A-Fa-f]$", match.group(2)):
4646 error(filename, linenum, 'runtime/memset', 4,
4647 'Did you mean "memset(%s, 0, %s)"?'
4648 % (match.group(1), match.group(2)))
4649
4650 if Search(r'\busing namespace\b', line):
4651 error(filename, linenum, 'build/namespaces', 5,
4652 'Do not use namespace using-directives. '
4653 'Use using-declarations instead.')
4654
4655 # Detect variable-length arrays.
4656 match = Match(r'\s*(.+::)?(\w+) [a-z]\w*\[(.+)];', line)
4657 if (match and match.group(2) != 'return' and match.group(2) != 'delete' and
4658 match.group(3).find(']') == -1):
4659 # Split the size using space and arithmetic operators as delimiters.
4660 # If any of the resulting tokens are not compile time constants then
4661 # report the error.
4662 tokens = re.split(r'\s|\+|\-|\*|\/|<<|>>]', match.group(3))
4663 is_const = True
4664 skip_next = False
4665 for tok in tokens:
4666 if skip_next:
4667 skip_next = False
4668 continue
4669
4670 if Search(r'sizeof\(.+\)', tok): continue
4671 if Search(r'arraysize\(\w+\)', tok): continue
Avi Drissman4157ba12019-01-09 14:18:07 +00004672 if Search(r'base::size\(.+\)', tok): continue
4673 if Search(r'std::size\(.+\)', tok): continue
4674 if Search(r'std::extent<.+>', tok): continue
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004675
4676 tok = tok.lstrip('(')
4677 tok = tok.rstrip(')')
4678 if not tok: continue
4679 if Match(r'\d+', tok): continue
4680 if Match(r'0[xX][0-9a-fA-F]+', tok): continue
4681 if Match(r'k[A-Z0-9]\w*', tok): continue
4682 if Match(r'(.+::)?k[A-Z0-9]\w*', tok): continue
4683 if Match(r'(.+::)?[A-Z][A-Z0-9_]*', tok): continue
4684 # A catch all for tricky sizeof cases, including 'sizeof expression',
4685 # 'sizeof(*type)', 'sizeof(const type)', 'sizeof(struct StructName)'
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004686 # requires skipping the next token because we split on ' ' and '*'.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004687 if tok.startswith('sizeof'):
4688 skip_next = True
4689 continue
4690 is_const = False
4691 break
4692 if not is_const:
4693 error(filename, linenum, 'runtime/arrays', 1,
4694 'Do not use variable-length arrays. Use an appropriately named '
4695 "('k' followed by CamelCase) compile-time constant for the size.")
4696
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004697 # Check for use of unnamed namespaces in header files. Registration
4698 # macros are typically OK, so we allow use of "namespace {" on lines
4699 # that end with backslashes.
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00004700 if (file_extension == 'h'
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004701 and Search(r'\bnamespace\s*{', line)
4702 and line[-1] != '\\'):
4703 error(filename, linenum, 'build/namespaces', 4,
4704 'Do not use unnamed namespaces in header files. See '
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00004705 'https://google.github.io/styleguide/cppguide.html#Namespaces'
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004706 ' for more information.')
4707
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004708
4709def CheckGlobalStatic(filename, clean_lines, linenum, error):
4710 """Check for unsafe global or static objects.
4711
4712 Args:
4713 filename: The name of the current file.
4714 clean_lines: A CleansedLines instance containing the file.
4715 linenum: The number of the line to check.
4716 error: The function to call with any errors found.
4717 """
4718 line = clean_lines.elided[linenum]
4719
avakulenko@google.com59146752014-08-11 20:20:55 +00004720 # Match two lines at a time to support multiline declarations
4721 if linenum + 1 < clean_lines.NumLines() and not Search(r'[;({]', line):
4722 line += clean_lines.elided[linenum + 1].strip()
4723
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004724 # Check for people declaring static/global STL strings at the top level.
4725 # This is dangerous because the C++ language does not guarantee that
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004726 # globals with constructors are initialized before the first access, and
4727 # also because globals can be destroyed when some threads are still running.
4728 # TODO(unknown): Generalize this to also find static unique_ptr instances.
4729 # TODO(unknown): File bugs for clang-tidy to find these.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004730 match = Match(
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004731 r'((?:|static +)(?:|const +))(?::*std::)?string( +const)? +'
4732 r'([a-zA-Z0-9_:]+)\b(.*)',
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004733 line)
avakulenko@google.com59146752014-08-11 20:20:55 +00004734
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004735 # Remove false positives:
4736 # - String pointers (as opposed to values).
4737 # string *pointer
4738 # const string *pointer
4739 # string const *pointer
4740 # string *const pointer
4741 #
4742 # - Functions and template specializations.
4743 # string Function<Type>(...
4744 # string Class<Type>::Method(...
4745 #
4746 # - Operators. These are matched separately because operator names
4747 # cross non-word boundaries, and trying to match both operators
4748 # and functions at the same time would decrease accuracy of
4749 # matching identifiers.
4750 # string Class::operator*()
4751 if (match and
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004752 not Search(r'\bstring\b(\s+const)?\s*[\*\&]\s*(const\s+)?\w', line) and
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004753 not Search(r'\boperator\W', line) and
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004754 not Match(r'\s*(<.*>)?(::[a-zA-Z0-9_]+)*\s*\(([^"]|$)', match.group(4))):
4755 if Search(r'\bconst\b', line):
4756 error(filename, linenum, 'runtime/string', 4,
4757 'For a static/global string constant, use a C style string '
4758 'instead: "%schar%s %s[]".' %
4759 (match.group(1), match.group(2) or '', match.group(3)))
4760 else:
4761 error(filename, linenum, 'runtime/string', 4,
4762 'Static/global string variables are not permitted.')
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004763
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004764 if (Search(r'\b([A-Za-z0-9_]*_)\(\1\)', line) or
4765 Search(r'\b([A-Za-z0-9_]*_)\(CHECK_NOTNULL\(\1\)\)', line)):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004766 error(filename, linenum, 'runtime/init', 4,
4767 'You seem to be initializing a member variable with itself.')
4768
4769
4770def CheckPrintf(filename, clean_lines, linenum, error):
4771 """Check for printf related issues.
4772
4773 Args:
4774 filename: The name of the current file.
4775 clean_lines: A CleansedLines instance containing the file.
4776 linenum: The number of the line to check.
4777 error: The function to call with any errors found.
4778 """
4779 line = clean_lines.elided[linenum]
4780
4781 # When snprintf is used, the second argument shouldn't be a literal.
4782 match = Search(r'snprintf\s*\(([^,]*),\s*([0-9]*)\s*,', line)
4783 if match and match.group(2) != '0':
4784 # If 2nd arg is zero, snprintf is used to calculate size.
4785 error(filename, linenum, 'runtime/printf', 3,
4786 'If you can, use sizeof(%s) instead of %s as the 2nd arg '
4787 'to snprintf.' % (match.group(1), match.group(2)))
4788
4789 # Check if some verboten C functions are being used.
avakulenko@google.com59146752014-08-11 20:20:55 +00004790 if Search(r'\bsprintf\s*\(', line):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004791 error(filename, linenum, 'runtime/printf', 5,
4792 'Never use sprintf. Use snprintf instead.')
avakulenko@google.com59146752014-08-11 20:20:55 +00004793 match = Search(r'\b(strcpy|strcat)\s*\(', line)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004794 if match:
4795 error(filename, linenum, 'runtime/printf', 4,
4796 'Almost always, snprintf is better than %s' % match.group(1))
4797
4798
4799def IsDerivedFunction(clean_lines, linenum):
4800 """Check if current line contains an inherited function.
4801
4802 Args:
4803 clean_lines: A CleansedLines instance containing the file.
4804 linenum: The number of the line to check.
4805 Returns:
4806 True if current line contains a function with "override"
4807 virt-specifier.
4808 """
avakulenko@google.com59146752014-08-11 20:20:55 +00004809 # Scan back a few lines for start of current function
Edward Lemur6d31ed52019-12-02 23:00:00 +00004810 for i in range(linenum, max(-1, linenum - 10), -1):
avakulenko@google.com59146752014-08-11 20:20:55 +00004811 match = Match(r'^([^()]*\w+)\(', clean_lines.elided[i])
4812 if match:
4813 # Look for "override" after the matching closing parenthesis
4814 line, _, closing_paren = CloseExpression(
4815 clean_lines, i, len(match.group(1)))
4816 return (closing_paren >= 0 and
4817 Search(r'\boverride\b', line[closing_paren:]))
4818 return False
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004819
4820
avakulenko@google.com255f2be2014-12-05 22:19:55 +00004821def IsOutOfLineMethodDefinition(clean_lines, linenum):
4822 """Check if current line contains an out-of-line method definition.
4823
4824 Args:
4825 clean_lines: A CleansedLines instance containing the file.
4826 linenum: The number of the line to check.
4827 Returns:
4828 True if current line contains an out-of-line method definition.
4829 """
4830 # Scan back a few lines for start of current function
Edward Lemur6d31ed52019-12-02 23:00:00 +00004831 for i in range(linenum, max(-1, linenum - 10), -1):
avakulenko@google.com255f2be2014-12-05 22:19:55 +00004832 if Match(r'^([^()]*\w+)\(', clean_lines.elided[i]):
4833 return Match(r'^[^()]*\w+::\w+\(', clean_lines.elided[i]) is not None
4834 return False
4835
4836
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004837def IsInitializerList(clean_lines, linenum):
4838 """Check if current line is inside constructor initializer list.
4839
4840 Args:
4841 clean_lines: A CleansedLines instance containing the file.
4842 linenum: The number of the line to check.
4843 Returns:
4844 True if current line appears to be inside constructor initializer
4845 list, False otherwise.
4846 """
Edward Lemur6d31ed52019-12-02 23:00:00 +00004847 for i in range(linenum, 1, -1):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004848 line = clean_lines.elided[i]
4849 if i == linenum:
4850 remove_function_body = Match(r'^(.*)\{\s*$', line)
4851 if remove_function_body:
4852 line = remove_function_body.group(1)
4853
4854 if Search(r'\s:\s*\w+[({]', line):
4855 # A lone colon tend to indicate the start of a constructor
4856 # initializer list. It could also be a ternary operator, which
4857 # also tend to appear in constructor initializer lists as
4858 # opposed to parameter lists.
4859 return True
4860 if Search(r'\}\s*,\s*$', line):
4861 # A closing brace followed by a comma is probably the end of a
4862 # brace-initialized member in constructor initializer list.
4863 return True
4864 if Search(r'[{};]\s*$', line):
4865 # Found one of the following:
4866 # - A closing brace or semicolon, probably the end of the previous
4867 # function.
4868 # - An opening brace, probably the start of current class or namespace.
4869 #
4870 # Current line is probably not inside an initializer list since
4871 # we saw one of those things without seeing the starting colon.
4872 return False
4873
4874 # Got to the beginning of the file without seeing the start of
4875 # constructor initializer list.
4876 return False
4877
4878
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004879def CheckForNonConstReference(filename, clean_lines, linenum,
4880 nesting_state, error):
4881 """Check for non-const references.
4882
4883 Separate from CheckLanguage since it scans backwards from current
4884 line, instead of scanning forward.
4885
4886 Args:
4887 filename: The name of the current file.
4888 clean_lines: A CleansedLines instance containing the file.
4889 linenum: The number of the line to check.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004890 nesting_state: A NestingState instance which maintains information about
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004891 the current stack of nested blocks being parsed.
4892 error: The function to call with any errors found.
4893 """
4894 # Do nothing if there is no '&' on current line.
4895 line = clean_lines.elided[linenum]
4896 if '&' not in line:
4897 return
4898
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004899 # If a function is inherited, current function doesn't have much of
4900 # a choice, so any non-const references should not be blamed on
4901 # derived function.
4902 if IsDerivedFunction(clean_lines, linenum):
4903 return
4904
avakulenko@google.com255f2be2014-12-05 22:19:55 +00004905 # Don't warn on out-of-line method definitions, as we would warn on the
4906 # in-line declaration, if it isn't marked with 'override'.
4907 if IsOutOfLineMethodDefinition(clean_lines, linenum):
4908 return
4909
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004910 # Long type names may be broken across multiple lines, usually in one
4911 # of these forms:
4912 # LongType
4913 # ::LongTypeContinued &identifier
4914 # LongType::
4915 # LongTypeContinued &identifier
4916 # LongType<
4917 # ...>::LongTypeContinued &identifier
4918 #
4919 # If we detected a type split across two lines, join the previous
4920 # line to current line so that we can match const references
4921 # accordingly.
4922 #
4923 # Note that this only scans back one line, since scanning back
4924 # arbitrary number of lines would be expensive. If you have a type
4925 # that spans more than 2 lines, please use a typedef.
4926 if linenum > 1:
4927 previous = None
4928 if Match(r'\s*::(?:[\w<>]|::)+\s*&\s*\S', line):
4929 # previous_line\n + ::current_line
4930 previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+[\w<>])\s*$',
4931 clean_lines.elided[linenum - 1])
4932 elif Match(r'\s*[a-zA-Z_]([\w<>]|::)+\s*&\s*\S', line):
4933 # previous_line::\n + current_line
4934 previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+::)\s*$',
4935 clean_lines.elided[linenum - 1])
4936 if previous:
4937 line = previous.group(1) + line.lstrip()
4938 else:
4939 # Check for templated parameter that is split across multiple lines
4940 endpos = line.rfind('>')
4941 if endpos > -1:
4942 (_, startline, startpos) = ReverseCloseExpression(
4943 clean_lines, linenum, endpos)
4944 if startpos > -1 and startline < linenum:
4945 # Found the matching < on an earlier line, collect all
4946 # pieces up to current line.
4947 line = ''
Edward Lemur6d31ed52019-12-02 23:00:00 +00004948 for i in range(startline, linenum + 1):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004949 line += clean_lines.elided[i].strip()
4950
4951 # Check for non-const references in function parameters. A single '&' may
4952 # found in the following places:
4953 # inside expression: binary & for bitwise AND
4954 # inside expression: unary & for taking the address of something
4955 # inside declarators: reference parameter
4956 # We will exclude the first two cases by checking that we are not inside a
4957 # function body, including one that was just introduced by a trailing '{'.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004958 # TODO(unknown): Doesn't account for 'catch(Exception& e)' [rare].
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004959 if (nesting_state.previous_stack_top and
4960 not (isinstance(nesting_state.previous_stack_top, _ClassInfo) or
4961 isinstance(nesting_state.previous_stack_top, _NamespaceInfo))):
4962 # Not at toplevel, not within a class, and not within a namespace
4963 return
4964
avakulenko@google.com59146752014-08-11 20:20:55 +00004965 # Avoid initializer lists. We only need to scan back from the
4966 # current line for something that starts with ':'.
4967 #
4968 # We don't need to check the current line, since the '&' would
4969 # appear inside the second set of parentheses on the current line as
4970 # opposed to the first set.
4971 if linenum > 0:
Edward Lemur6d31ed52019-12-02 23:00:00 +00004972 for i in range(linenum - 1, max(0, linenum - 10), -1):
avakulenko@google.com59146752014-08-11 20:20:55 +00004973 previous_line = clean_lines.elided[i]
4974 if not Search(r'[),]\s*$', previous_line):
4975 break
4976 if Match(r'^\s*:\s+\S', previous_line):
4977 return
4978
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004979 # Avoid preprocessors
4980 if Search(r'\\\s*$', line):
4981 return
4982
4983 # Avoid constructor initializer lists
4984 if IsInitializerList(clean_lines, linenum):
4985 return
4986
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004987 # We allow non-const references in a few standard places, like functions
4988 # called "swap()" or iostream operators like "<<" or ">>". Do not check
4989 # those function parameters.
4990 #
4991 # We also accept & in static_assert, which looks like a function but
4992 # it's actually a declaration expression.
4993 whitelisted_functions = (r'(?:[sS]wap(?:<\w:+>)?|'
4994 r'operator\s*[<>][<>]|'
4995 r'static_assert|COMPILE_ASSERT'
4996 r')\s*\(')
4997 if Search(whitelisted_functions, line):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004998 return
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004999 elif not Search(r'\S+\([^)]*$', line):
5000 # Don't see a whitelisted function on this line. Actually we
5001 # didn't see any function name on this line, so this is likely a
5002 # multi-line parameter list. Try a bit harder to catch this case.
Edward Lemur6d31ed52019-12-02 23:00:00 +00005003 for i in range(2):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005004 if (linenum > i and
5005 Search(whitelisted_functions, clean_lines.elided[linenum - i - 1])):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005006 return
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005007
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005008 decls = ReplaceAll(r'{[^}]*}', ' ', line) # exclude function body
5009 for parameter in re.findall(_RE_PATTERN_REF_PARAM, decls):
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005010 if (not Match(_RE_PATTERN_CONST_REF_PARAM, parameter) and
5011 not Match(_RE_PATTERN_REF_STREAM_PARAM, parameter)):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005012 error(filename, linenum, 'runtime/references', 2,
5013 'Is this a non-const reference? '
5014 'If so, make const or use a pointer: ' +
5015 ReplaceAll(' *<', '<', parameter))
5016
5017
5018def CheckCasts(filename, clean_lines, linenum, error):
5019 """Various cast related checks.
5020
5021 Args:
5022 filename: The name of the current file.
5023 clean_lines: A CleansedLines instance containing the file.
5024 linenum: The number of the line to check.
5025 error: The function to call with any errors found.
5026 """
5027 line = clean_lines.elided[linenum]
5028
5029 # Check to see if they're using an conversion function cast.
5030 # I just try to capture the most common basic types, though there are more.
5031 # Parameterless conversion functions, such as bool(), are allowed as they are
5032 # probably a member operator declaration or default constructor.
5033 match = Search(
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005034 r'(\bnew\s+(?:const\s+)?|\S<\s*(?:const\s+)?)?\b'
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005035 r'(int|float|double|bool|char|int32|uint32|int64|uint64)'
5036 r'(\([^)].*)', line)
5037 expecting_function = ExpectingFunctionArgs(clean_lines, linenum)
5038 if match and not expecting_function:
5039 matched_type = match.group(2)
5040
5041 # matched_new_or_template is used to silence two false positives:
5042 # - New operators
5043 # - Template arguments with function types
5044 #
5045 # For template arguments, we match on types immediately following
5046 # an opening bracket without any spaces. This is a fast way to
5047 # silence the common case where the function type is the first
5048 # template argument. False negative with less-than comparison is
5049 # avoided because those operators are usually followed by a space.
5050 #
5051 # function<double(double)> // bracket + no space = false positive
5052 # value < double(42) // bracket + space = true positive
5053 matched_new_or_template = match.group(1)
5054
avakulenko@google.com59146752014-08-11 20:20:55 +00005055 # Avoid arrays by looking for brackets that come after the closing
5056 # parenthesis.
5057 if Match(r'\([^()]+\)\s*\[', match.group(3)):
5058 return
5059
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005060 # Other things to ignore:
5061 # - Function pointers
5062 # - Casts to pointer types
5063 # - Placement new
5064 # - Alias declarations
5065 matched_funcptr = match.group(3)
5066 if (matched_new_or_template is None and
5067 not (matched_funcptr and
5068 (Match(r'\((?:[^() ]+::\s*\*\s*)?[^() ]+\)\s*\(',
5069 matched_funcptr) or
5070 matched_funcptr.startswith('(*)'))) and
5071 not Match(r'\s*using\s+\S+\s*=\s*' + matched_type, line) and
5072 not Search(r'new\(\S+\)\s*' + matched_type, line)):
5073 error(filename, linenum, 'readability/casting', 4,
5074 'Using deprecated casting style. '
5075 'Use static_cast<%s>(...) instead' %
5076 matched_type)
5077
5078 if not expecting_function:
avakulenko@google.com59146752014-08-11 20:20:55 +00005079 CheckCStyleCast(filename, clean_lines, linenum, 'static_cast',
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005080 r'\((int|float|double|bool|char|u?int(16|32|64))\)', error)
5081
5082 # This doesn't catch all cases. Consider (const char * const)"hello".
5083 #
5084 # (char *) "foo" should always be a const_cast (reinterpret_cast won't
5085 # compile).
avakulenko@google.com59146752014-08-11 20:20:55 +00005086 if CheckCStyleCast(filename, clean_lines, linenum, 'const_cast',
5087 r'\((char\s?\*+\s?)\)\s*"', error):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005088 pass
5089 else:
5090 # Check pointer casts for other than string constants
avakulenko@google.com59146752014-08-11 20:20:55 +00005091 CheckCStyleCast(filename, clean_lines, linenum, 'reinterpret_cast',
5092 r'\((\w+\s?\*+\s?)\)', error)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005093
5094 # In addition, we look for people taking the address of a cast. This
5095 # is dangerous -- casts can assign to temporaries, so the pointer doesn't
5096 # point where you think.
avakulenko@google.com59146752014-08-11 20:20:55 +00005097 #
5098 # Some non-identifier character is required before the '&' for the
5099 # expression to be recognized as a cast. These are casts:
5100 # expression = &static_cast<int*>(temporary());
5101 # function(&(int*)(temporary()));
5102 #
5103 # This is not a cast:
5104 # reference_type&(int* function_param);
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005105 match = Search(
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005106 r'(?:[^\w]&\(([^)*][^)]*)\)[\w(])|'
avakulenko@google.com59146752014-08-11 20:20:55 +00005107 r'(?:[^\w]&(static|dynamic|down|reinterpret)_cast\b)', line)
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005108 if match:
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005109 # Try a better error message when the & is bound to something
5110 # dereferenced by the casted pointer, as opposed to the casted
5111 # pointer itself.
5112 parenthesis_error = False
5113 match = Match(r'^(.*&(?:static|dynamic|down|reinterpret)_cast\b)<', line)
5114 if match:
5115 _, y1, x1 = CloseExpression(clean_lines, linenum, len(match.group(1)))
5116 if x1 >= 0 and clean_lines.elided[y1][x1] == '(':
5117 _, y2, x2 = CloseExpression(clean_lines, y1, x1)
5118 if x2 >= 0:
5119 extended_line = clean_lines.elided[y2][x2:]
5120 if y2 < clean_lines.NumLines() - 1:
5121 extended_line += clean_lines.elided[y2 + 1]
5122 if Match(r'\s*(?:->|\[)', extended_line):
5123 parenthesis_error = True
5124
5125 if parenthesis_error:
5126 error(filename, linenum, 'readability/casting', 4,
5127 ('Are you taking an address of something dereferenced '
5128 'from a cast? Wrapping the dereferenced expression in '
5129 'parentheses will make the binding more obvious'))
5130 else:
5131 error(filename, linenum, 'runtime/casting', 4,
5132 ('Are you taking an address of a cast? '
5133 'This is dangerous: could be a temp var. '
5134 'Take the address before doing the cast, rather than after'))
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005135
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005136
avakulenko@google.com59146752014-08-11 20:20:55 +00005137def CheckCStyleCast(filename, clean_lines, linenum, cast_type, pattern, error):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005138 """Checks for a C-style cast by looking for the pattern.
5139
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005140 Args:
5141 filename: The name of the current file.
avakulenko@google.com59146752014-08-11 20:20:55 +00005142 clean_lines: A CleansedLines instance containing the file.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005143 linenum: The number of the line to check.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005144 cast_type: The string for the C++ cast to recommend. This is either
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005145 reinterpret_cast, static_cast, or const_cast, depending.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005146 pattern: The regular expression used to find C-style casts.
5147 error: The function to call with any errors found.
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005148
5149 Returns:
5150 True if an error was emitted.
5151 False otherwise.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005152 """
avakulenko@google.com59146752014-08-11 20:20:55 +00005153 line = clean_lines.elided[linenum]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005154 match = Search(pattern, line)
5155 if not match:
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005156 return False
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005157
avakulenko@google.com59146752014-08-11 20:20:55 +00005158 # Exclude lines with keywords that tend to look like casts
5159 context = line[0:match.start(1) - 1]
5160 if Match(r'.*\b(?:sizeof|alignof|alignas|[_A-Z][_A-Z0-9]*)\s*$', context):
5161 return False
5162
5163 # Try expanding current context to see if we one level of
5164 # parentheses inside a macro.
5165 if linenum > 0:
Edward Lemur6d31ed52019-12-02 23:00:00 +00005166 for i in range(linenum - 1, max(0, linenum - 5), -1):
avakulenko@google.com59146752014-08-11 20:20:55 +00005167 context = clean_lines.elided[i] + context
5168 if Match(r'.*\b[_A-Z][_A-Z0-9]*\s*\((?:\([^()]*\)|[^()])*$', context):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005169 return False
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005170
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005171 # operator++(int) and operator--(int)
avakulenko@google.com59146752014-08-11 20:20:55 +00005172 if context.endswith(' operator++') or context.endswith(' operator--'):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005173 return False
5174
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005175 # A single unnamed argument for a function tends to look like old style cast.
5176 # If we see those, don't issue warnings for deprecated casts.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005177 remainder = line[match.end(0):]
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005178 if Match(r'^\s*(?:;|const\b|throw\b|final\b|override\b|[=>{),]|->)',
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005179 remainder):
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005180 return False
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005181
5182 # At this point, all that should be left is actual casts.
5183 error(filename, linenum, 'readability/casting', 4,
5184 'Using C-style cast. Use %s<%s>(...) instead' %
5185 (cast_type, match.group(1)))
5186
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005187 return True
5188
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005189
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005190def ExpectingFunctionArgs(clean_lines, linenum):
5191 """Checks whether where function type arguments are expected.
5192
5193 Args:
5194 clean_lines: A CleansedLines instance containing the file.
5195 linenum: The number of the line to check.
5196
5197 Returns:
5198 True if the line at 'linenum' is inside something that expects arguments
5199 of function types.
5200 """
5201 line = clean_lines.elided[linenum]
5202 return (Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line) or
5203 (linenum >= 2 and
5204 (Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\((?:\S+,)?\s*$',
5205 clean_lines.elided[linenum - 1]) or
5206 Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\(\s*$',
5207 clean_lines.elided[linenum - 2]) or
5208 Search(r'\bstd::m?function\s*\<\s*$',
5209 clean_lines.elided[linenum - 1]))))
5210
5211
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005212_HEADERS_CONTAINING_TEMPLATES = (
5213 ('<deque>', ('deque',)),
5214 ('<functional>', ('unary_function', 'binary_function',
5215 'plus', 'minus', 'multiplies', 'divides', 'modulus',
5216 'negate',
5217 'equal_to', 'not_equal_to', 'greater', 'less',
5218 'greater_equal', 'less_equal',
5219 'logical_and', 'logical_or', 'logical_not',
5220 'unary_negate', 'not1', 'binary_negate', 'not2',
5221 'bind1st', 'bind2nd',
5222 'pointer_to_unary_function',
5223 'pointer_to_binary_function',
5224 'ptr_fun',
5225 'mem_fun_t', 'mem_fun', 'mem_fun1_t', 'mem_fun1_ref_t',
5226 'mem_fun_ref_t',
5227 'const_mem_fun_t', 'const_mem_fun1_t',
5228 'const_mem_fun_ref_t', 'const_mem_fun1_ref_t',
5229 'mem_fun_ref',
5230 )),
5231 ('<limits>', ('numeric_limits',)),
5232 ('<list>', ('list',)),
5233 ('<map>', ('map', 'multimap',)),
lhchavez2d1b6da2016-07-13 10:40:01 -07005234 ('<memory>', ('allocator', 'make_shared', 'make_unique', 'shared_ptr',
5235 'unique_ptr', 'weak_ptr')),
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005236 ('<queue>', ('queue', 'priority_queue',)),
5237 ('<set>', ('set', 'multiset',)),
5238 ('<stack>', ('stack',)),
5239 ('<string>', ('char_traits', 'basic_string',)),
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005240 ('<tuple>', ('tuple',)),
lhchavez2d1b6da2016-07-13 10:40:01 -07005241 ('<unordered_map>', ('unordered_map', 'unordered_multimap')),
5242 ('<unordered_set>', ('unordered_set', 'unordered_multiset')),
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005243 ('<utility>', ('pair',)),
5244 ('<vector>', ('vector',)),
5245
5246 # gcc extensions.
5247 # Note: std::hash is their hash, ::hash is our hash
5248 ('<hash_map>', ('hash_map', 'hash_multimap',)),
5249 ('<hash_set>', ('hash_set', 'hash_multiset',)),
5250 ('<slist>', ('slist',)),
5251 )
5252
skym@chromium.org3990c412016-02-05 20:55:12 +00005253_HEADERS_MAYBE_TEMPLATES = (
5254 ('<algorithm>', ('copy', 'max', 'min', 'min_element', 'sort',
5255 'transform',
5256 )),
lhchavez2d1b6da2016-07-13 10:40:01 -07005257 ('<utility>', ('forward', 'make_pair', 'move', 'swap')),
skym@chromium.org3990c412016-02-05 20:55:12 +00005258 )
5259
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005260_RE_PATTERN_STRING = re.compile(r'\bstring\b')
5261
skym@chromium.org3990c412016-02-05 20:55:12 +00005262_re_pattern_headers_maybe_templates = []
5263for _header, _templates in _HEADERS_MAYBE_TEMPLATES:
5264 for _template in _templates:
5265 # Match max<type>(..., ...), max(..., ...), but not foo->max, foo.max or
5266 # type::max().
5267 _re_pattern_headers_maybe_templates.append(
5268 (re.compile(r'[^>.]\b' + _template + r'(<.*?>)?\([^\)]'),
5269 _template,
5270 _header))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005271
skym@chromium.org3990c412016-02-05 20:55:12 +00005272# Other scripts may reach in and modify this pattern.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005273_re_pattern_templates = []
5274for _header, _templates in _HEADERS_CONTAINING_TEMPLATES:
5275 for _template in _templates:
5276 _re_pattern_templates.append(
5277 (re.compile(r'(\<|\b)' + _template + r'\s*\<'),
5278 _template + '<>',
5279 _header))
5280
5281
erg@google.com6317a9c2009-06-25 00:28:19 +00005282def FilesBelongToSameModule(filename_cc, filename_h):
5283 """Check if these two filenames belong to the same module.
5284
5285 The concept of a 'module' here is a as follows:
5286 foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the
5287 same 'module' if they are in the same directory.
5288 some/path/public/xyzzy and some/path/internal/xyzzy are also considered
5289 to belong to the same module here.
5290
5291 If the filename_cc contains a longer path than the filename_h, for example,
5292 '/absolute/path/to/base/sysinfo.cc', and this file would include
5293 'base/sysinfo.h', this function also produces the prefix needed to open the
5294 header. This is used by the caller of this function to more robustly open the
5295 header file. We don't have access to the real include paths in this context,
5296 so we need this guesswork here.
5297
5298 Known bugs: tools/base/bar.cc and base/bar.h belong to the same module
5299 according to this implementation. Because of this, this function gives
5300 some false positives. This should be sufficiently rare in practice.
5301
5302 Args:
5303 filename_cc: is the path for the .cc file
5304 filename_h: is the path for the header path
5305
5306 Returns:
5307 Tuple with a bool and a string:
5308 bool: True if filename_cc and filename_h belong to the same module.
5309 string: the additional prefix needed to open the header file.
5310 """
5311
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005312 fileinfo = FileInfo(filename_cc)
5313 if not fileinfo.IsSource():
erg@google.com6317a9c2009-06-25 00:28:19 +00005314 return (False, '')
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005315 filename_cc = filename_cc[:-len(fileinfo.Extension())]
5316 matched_test_suffix = Search(_TEST_FILE_SUFFIX, fileinfo.BaseName())
5317 if matched_test_suffix:
5318 filename_cc = filename_cc[:-len(matched_test_suffix.group(1))]
erg@google.com6317a9c2009-06-25 00:28:19 +00005319 filename_cc = filename_cc.replace('/public/', '/')
5320 filename_cc = filename_cc.replace('/internal/', '/')
5321
5322 if not filename_h.endswith('.h'):
5323 return (False, '')
5324 filename_h = filename_h[:-len('.h')]
5325 if filename_h.endswith('-inl'):
5326 filename_h = filename_h[:-len('-inl')]
5327 filename_h = filename_h.replace('/public/', '/')
5328 filename_h = filename_h.replace('/internal/', '/')
5329
5330 files_belong_to_same_module = filename_cc.endswith(filename_h)
5331 common_path = ''
5332 if files_belong_to_same_module:
5333 common_path = filename_cc[:-len(filename_h)]
5334 return files_belong_to_same_module, common_path
5335
5336
avakulenko@google.com59146752014-08-11 20:20:55 +00005337def UpdateIncludeState(filename, include_dict, io=codecs):
5338 """Fill up the include_dict with new includes found from the file.
erg@google.com6317a9c2009-06-25 00:28:19 +00005339
5340 Args:
5341 filename: the name of the header to read.
avakulenko@google.com59146752014-08-11 20:20:55 +00005342 include_dict: a dictionary in which the headers are inserted.
erg@google.com6317a9c2009-06-25 00:28:19 +00005343 io: The io factory to use to read the file. Provided for testability.
5344
5345 Returns:
avakulenko@google.com59146752014-08-11 20:20:55 +00005346 True if a header was successfully added. False otherwise.
erg@google.com6317a9c2009-06-25 00:28:19 +00005347 """
5348 headerfile = None
5349 try:
5350 headerfile = io.open(filename, 'r', 'utf8', 'replace')
5351 except IOError:
5352 return False
5353 linenum = 0
5354 for line in headerfile:
5355 linenum += 1
5356 clean_line = CleanseComments(line)
5357 match = _RE_PATTERN_INCLUDE.search(clean_line)
5358 if match:
5359 include = match.group(2)
avakulenko@google.com59146752014-08-11 20:20:55 +00005360 include_dict.setdefault(include, linenum)
erg@google.com6317a9c2009-06-25 00:28:19 +00005361 return True
5362
5363
5364def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error,
5365 io=codecs):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005366 """Reports for missing stl includes.
5367
5368 This function will output warnings to make sure you are including the headers
5369 necessary for the stl containers and functions that you use. We only give one
5370 reason to include a header. For example, if you use both equal_to<> and
5371 less<> in a .h file, only one (the latter in the file) of these will be
5372 reported as a reason to include the <functional>.
5373
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005374 Args:
5375 filename: The name of the current file.
5376 clean_lines: A CleansedLines instance containing the file.
5377 include_state: An _IncludeState instance.
5378 error: The function to call with any errors found.
erg@google.com6317a9c2009-06-25 00:28:19 +00005379 io: The IO factory to use to read the header file. Provided for unittest
5380 injection.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005381 """
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005382 required = {} # A map of header name to linenumber and the template entity.
5383 # Example of required: { '<functional>': (1219, 'less<>') }
5384
Edward Lemur6d31ed52019-12-02 23:00:00 +00005385 for linenum in range(clean_lines.NumLines()):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005386 line = clean_lines.elided[linenum]
5387 if not line or line[0] == '#':
5388 continue
5389
5390 # String is special -- it is a non-templatized type in STL.
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005391 matched = _RE_PATTERN_STRING.search(line)
5392 if matched:
erg@google.com35589e62010-11-17 18:58:16 +00005393 # Don't warn about strings in non-STL namespaces:
5394 # (We check only the first match per line; good enough.)
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005395 prefix = line[:matched.start()]
erg@google.com35589e62010-11-17 18:58:16 +00005396 if prefix.endswith('std::') or not prefix.endswith('::'):
5397 required['<string>'] = (linenum, 'string')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005398
skym@chromium.org3990c412016-02-05 20:55:12 +00005399 for pattern, template, header in _re_pattern_headers_maybe_templates:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005400 if pattern.search(line):
5401 required[header] = (linenum, template)
5402
5403 # The following function is just a speed up, no semantics are changed.
5404 if not '<' in line: # Reduces the cpu time usage by skipping lines.
5405 continue
5406
5407 for pattern, template, header in _re_pattern_templates:
lhchavez9b2173c2016-07-13 10:20:07 -07005408 matched = pattern.search(line)
5409 if matched:
5410 # Don't warn about IWYU in non-STL namespaces:
5411 # (We check only the first match per line; good enough.)
5412 prefix = line[:matched.start()]
5413 if prefix.endswith('std::') or not prefix.endswith('::'):
5414 required[header] = (linenum, template)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005415
erg@google.com6317a9c2009-06-25 00:28:19 +00005416 # The policy is that if you #include something in foo.h you don't need to
5417 # include it again in foo.cc. Here, we will look at possible includes.
avakulenko@google.com59146752014-08-11 20:20:55 +00005418 # Let's flatten the include_state include_list and copy it into a dictionary.
5419 include_dict = dict([item for sublist in include_state.include_list
5420 for item in sublist])
erg@google.com6317a9c2009-06-25 00:28:19 +00005421
avakulenko@google.com59146752014-08-11 20:20:55 +00005422 # Did we find the header for this file (if any) and successfully load it?
erg@google.com6317a9c2009-06-25 00:28:19 +00005423 header_found = False
5424
5425 # Use the absolute path so that matching works properly.
erg@chromium.org8f927562012-01-30 19:51:28 +00005426 abs_filename = FileInfo(filename).FullName()
erg@google.com6317a9c2009-06-25 00:28:19 +00005427
5428 # For Emacs's flymake.
5429 # If cpplint is invoked from Emacs's flymake, a temporary file is generated
5430 # by flymake and that file name might end with '_flymake.cc'. In that case,
5431 # restore original file name here so that the corresponding header file can be
5432 # found.
5433 # e.g. If the file name is 'foo_flymake.cc', we should search for 'foo.h'
5434 # instead of 'foo_flymake.h'
erg@google.com35589e62010-11-17 18:58:16 +00005435 abs_filename = re.sub(r'_flymake\.cc$', '.cc', abs_filename)
erg@google.com6317a9c2009-06-25 00:28:19 +00005436
avakulenko@google.com59146752014-08-11 20:20:55 +00005437 # include_dict is modified during iteration, so we iterate over a copy of
erg@google.com6317a9c2009-06-25 00:28:19 +00005438 # the keys.
Sarthak Kukreti60378202019-12-17 20:46:58 +00005439 header_keys = list(include_dict.keys())
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005440 for header in header_keys:
erg@google.com6317a9c2009-06-25 00:28:19 +00005441 (same_module, common_path) = FilesBelongToSameModule(abs_filename, header)
5442 fullpath = common_path + header
avakulenko@google.com59146752014-08-11 20:20:55 +00005443 if same_module and UpdateIncludeState(fullpath, include_dict, io):
erg@google.com6317a9c2009-06-25 00:28:19 +00005444 header_found = True
5445
5446 # If we can't find the header file for a .cc, assume it's because we don't
5447 # know where to look. In that case we'll give up as we're not sure they
5448 # didn't include it in the .h file.
5449 # TODO(unknown): Do a better job of finding .h files so we are confident that
5450 # not having the .h file means there isn't one.
5451 if filename.endswith('.cc') and not header_found:
5452 return
5453
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005454 # All the lines have been processed, report the errors found.
5455 for required_header_unstripped in required:
5456 template = required[required_header_unstripped][1]
avakulenko@google.com59146752014-08-11 20:20:55 +00005457 if required_header_unstripped.strip('<>"') not in include_dict:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005458 error(filename, required[required_header_unstripped][0],
5459 'build/include_what_you_use', 4,
5460 'Add #include ' + required_header_unstripped + ' for ' + template)
5461
5462
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005463_RE_PATTERN_EXPLICIT_MAKEPAIR = re.compile(r'\bmake_pair\s*<')
5464
5465
5466def CheckMakePairUsesDeduction(filename, clean_lines, linenum, error):
5467 """Check that make_pair's template arguments are deduced.
5468
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005469 G++ 4.6 in C++11 mode fails badly if make_pair's template arguments are
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005470 specified explicitly, and such use isn't intended in any case.
5471
5472 Args:
5473 filename: The name of the current file.
5474 clean_lines: A CleansedLines instance containing the file.
5475 linenum: The number of the line to check.
5476 error: The function to call with any errors found.
5477 """
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005478 line = clean_lines.elided[linenum]
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005479 match = _RE_PATTERN_EXPLICIT_MAKEPAIR.search(line)
5480 if match:
5481 error(filename, linenum, 'build/explicit_make_pair',
5482 4, # 4 = high confidence
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005483 'For C++11-compatibility, omit template arguments from make_pair'
5484 ' OR use pair directly OR if appropriate, construct a pair directly')
avakulenko@google.com59146752014-08-11 20:20:55 +00005485
5486
avakulenko@google.com59146752014-08-11 20:20:55 +00005487def CheckRedundantVirtual(filename, clean_lines, linenum, error):
5488 """Check if line contains a redundant "virtual" function-specifier.
5489
5490 Args:
5491 filename: The name of the current file.
5492 clean_lines: A CleansedLines instance containing the file.
5493 linenum: The number of the line to check.
5494 error: The function to call with any errors found.
5495 """
5496 # Look for "virtual" on current line.
5497 line = clean_lines.elided[linenum]
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005498 virtual = Match(r'^(.*)(\bvirtual\b)(.*)$', line)
avakulenko@google.com59146752014-08-11 20:20:55 +00005499 if not virtual: return
5500
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005501 # Ignore "virtual" keywords that are near access-specifiers. These
5502 # are only used in class base-specifier and do not apply to member
5503 # functions.
5504 if (Search(r'\b(public|protected|private)\s+$', virtual.group(1)) or
5505 Match(r'^\s+(public|protected|private)\b', virtual.group(3))):
5506 return
5507
5508 # Ignore the "virtual" keyword from virtual base classes. Usually
5509 # there is a column on the same line in these cases (virtual base
5510 # classes are rare in google3 because multiple inheritance is rare).
5511 if Match(r'^.*[^:]:[^:].*$', line): return
5512
avakulenko@google.com59146752014-08-11 20:20:55 +00005513 # Look for the next opening parenthesis. This is the start of the
5514 # parameter list (possibly on the next line shortly after virtual).
5515 # TODO(unknown): doesn't work if there are virtual functions with
5516 # decltype() or other things that use parentheses, but csearch suggests
5517 # that this is rare.
5518 end_col = -1
5519 end_line = -1
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005520 start_col = len(virtual.group(2))
Edward Lemur6d31ed52019-12-02 23:00:00 +00005521 for start_line in range(linenum, min(linenum + 3, clean_lines.NumLines())):
avakulenko@google.com59146752014-08-11 20:20:55 +00005522 line = clean_lines.elided[start_line][start_col:]
5523 parameter_list = Match(r'^([^(]*)\(', line)
5524 if parameter_list:
5525 # Match parentheses to find the end of the parameter list
5526 (_, end_line, end_col) = CloseExpression(
5527 clean_lines, start_line, start_col + len(parameter_list.group(1)))
5528 break
5529 start_col = 0
5530
5531 if end_col < 0:
5532 return # Couldn't find end of parameter list, give up
5533
5534 # Look for "override" or "final" after the parameter list
5535 # (possibly on the next few lines).
Edward Lemur6d31ed52019-12-02 23:00:00 +00005536 for i in range(end_line, min(end_line + 3, clean_lines.NumLines())):
avakulenko@google.com59146752014-08-11 20:20:55 +00005537 line = clean_lines.elided[i][end_col:]
5538 match = Search(r'\b(override|final)\b', line)
5539 if match:
5540 error(filename, linenum, 'readability/inheritance', 4,
5541 ('"virtual" is redundant since function is '
5542 'already declared as "%s"' % match.group(1)))
5543
5544 # Set end_col to check whole lines after we are done with the
5545 # first line.
5546 end_col = 0
5547 if Search(r'[^\w]\s*$', line):
5548 break
5549
5550
5551def CheckRedundantOverrideOrFinal(filename, clean_lines, linenum, error):
5552 """Check if line contains a redundant "override" or "final" virt-specifier.
5553
5554 Args:
5555 filename: The name of the current file.
5556 clean_lines: A CleansedLines instance containing the file.
5557 linenum: The number of the line to check.
5558 error: The function to call with any errors found.
5559 """
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005560 # Look for closing parenthesis nearby. We need one to confirm where
5561 # the declarator ends and where the virt-specifier starts to avoid
5562 # false positives.
avakulenko@google.com59146752014-08-11 20:20:55 +00005563 line = clean_lines.elided[linenum]
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005564 declarator_end = line.rfind(')')
5565 if declarator_end >= 0:
5566 fragment = line[declarator_end:]
5567 else:
5568 if linenum > 1 and clean_lines.elided[linenum - 1].rfind(')') >= 0:
5569 fragment = line
5570 else:
5571 return
5572
5573 # Check that at most one of "override" or "final" is present, not both
5574 if Search(r'\boverride\b', fragment) and Search(r'\bfinal\b', fragment):
avakulenko@google.com59146752014-08-11 20:20:55 +00005575 error(filename, linenum, 'readability/inheritance', 4,
5576 ('"override" is redundant since function is '
5577 'already declared as "final"'))
5578
5579
5580
5581
5582# Returns true if we are at a new block, and it is directly
5583# inside of a namespace.
5584def IsBlockInNameSpace(nesting_state, is_forward_declaration):
5585 """Checks that the new block is directly in a namespace.
5586
5587 Args:
5588 nesting_state: The _NestingState object that contains info about our state.
5589 is_forward_declaration: If the class is a forward declared class.
5590 Returns:
5591 Whether or not the new block is directly in a namespace.
5592 """
5593 if is_forward_declaration:
5594 if len(nesting_state.stack) >= 1 and (
5595 isinstance(nesting_state.stack[-1], _NamespaceInfo)):
5596 return True
5597 else:
5598 return False
5599
5600 return (len(nesting_state.stack) > 1 and
5601 nesting_state.stack[-1].check_namespace_indentation and
5602 isinstance(nesting_state.stack[-2], _NamespaceInfo))
5603
5604
5605def ShouldCheckNamespaceIndentation(nesting_state, is_namespace_indent_item,
5606 raw_lines_no_comments, linenum):
5607 """This method determines if we should apply our namespace indentation check.
5608
5609 Args:
5610 nesting_state: The current nesting state.
5611 is_namespace_indent_item: If we just put a new class on the stack, True.
5612 If the top of the stack is not a class, or we did not recently
5613 add the class, False.
5614 raw_lines_no_comments: The lines without the comments.
5615 linenum: The current line number we are processing.
5616
5617 Returns:
5618 True if we should apply our namespace indentation check. Currently, it
5619 only works for classes and namespaces inside of a namespace.
5620 """
5621
5622 is_forward_declaration = IsForwardClassDeclaration(raw_lines_no_comments,
5623 linenum)
5624
5625 if not (is_namespace_indent_item or is_forward_declaration):
5626 return False
5627
5628 # If we are in a macro, we do not want to check the namespace indentation.
5629 if IsMacroDefinition(raw_lines_no_comments, linenum):
5630 return False
5631
5632 return IsBlockInNameSpace(nesting_state, is_forward_declaration)
5633
5634
5635# Call this method if the line is directly inside of a namespace.
5636# If the line above is blank (excluding comments) or the start of
5637# an inner namespace, it cannot be indented.
5638def CheckItemIndentationInNamespace(filename, raw_lines_no_comments, linenum,
5639 error):
5640 line = raw_lines_no_comments[linenum]
5641 if Match(r'^\s+', line):
5642 error(filename, linenum, 'runtime/indentation_namespace', 4,
5643 'Do not indent within a namespace')
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005644
5645
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005646def ProcessLine(filename, file_extension, clean_lines, line,
5647 include_state, function_state, nesting_state, error,
5648 extra_check_functions=[]):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005649 """Processes a single line in the file.
5650
5651 Args:
5652 filename: Filename of the file that is being processed.
5653 file_extension: The extension (dot not included) of the file.
5654 clean_lines: An array of strings, each representing a line of the file,
5655 with comments stripped.
5656 line: Number of line being processed.
5657 include_state: An _IncludeState instance in which the headers are inserted.
5658 function_state: A _FunctionState instance which counts function lines, etc.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005659 nesting_state: A NestingState instance which maintains information about
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005660 the current stack of nested blocks being parsed.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005661 error: A callable to which errors are reported, which takes 4 arguments:
5662 filename, line number, error level, and message
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005663 extra_check_functions: An array of additional check functions that will be
5664 run on each source line. Each function takes 4
5665 arguments: filename, clean_lines, line, error
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005666 """
5667 raw_lines = clean_lines.raw_lines
erg@google.com35589e62010-11-17 18:58:16 +00005668 ParseNolintSuppressions(filename, raw_lines[line], line, error)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005669 nesting_state.Update(filename, clean_lines, line, error)
avakulenko@google.com59146752014-08-11 20:20:55 +00005670 CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line,
5671 error)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005672 if nesting_state.InAsmBlock(): return
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005673 CheckForFunctionLengths(filename, clean_lines, line, function_state, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005674 CheckForMultilineCommentsAndStrings(filename, clean_lines, line, error)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005675 CheckStyle(filename, clean_lines, line, file_extension, nesting_state, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005676 CheckLanguage(filename, clean_lines, line, file_extension, include_state,
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005677 nesting_state, error)
5678 CheckForNonConstReference(filename, clean_lines, line, nesting_state, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005679 CheckForNonStandardConstructs(filename, clean_lines, line,
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005680 nesting_state, error)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005681 CheckVlogArguments(filename, clean_lines, line, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005682 CheckPosixThreading(filename, clean_lines, line, error)
erg@google.com6317a9c2009-06-25 00:28:19 +00005683 CheckInvalidIncrement(filename, clean_lines, line, error)
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005684 CheckMakePairUsesDeduction(filename, clean_lines, line, error)
avakulenko@google.com59146752014-08-11 20:20:55 +00005685 CheckRedundantVirtual(filename, clean_lines, line, error)
5686 CheckRedundantOverrideOrFinal(filename, clean_lines, line, error)
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005687 for check_fn in extra_check_functions:
5688 check_fn(filename, clean_lines, line, error)
avakulenko@google.com17449932014-07-28 22:13:33 +00005689
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005690def FlagCxx11Features(filename, clean_lines, linenum, error):
5691 """Flag those c++11 features that we only allow in certain places.
5692
5693 Args:
5694 filename: The name of the current file.
5695 clean_lines: A CleansedLines instance containing the file.
5696 linenum: The number of the line to check.
5697 error: The function to call with any errors found.
5698 """
5699 line = clean_lines.elided[linenum]
5700
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005701 include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line)
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005702
5703 # Flag unapproved C++ TR1 headers.
5704 if include and include.group(1).startswith('tr1/'):
5705 error(filename, linenum, 'build/c++tr1', 5,
5706 ('C++ TR1 headers such as <%s> are unapproved.') % include.group(1))
5707
5708 # Flag unapproved C++11 headers.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005709 if include and include.group(1) in ('cfenv',
5710 'condition_variable',
5711 'fenv.h',
5712 'future',
5713 'mutex',
5714 'thread',
5715 'chrono',
5716 'ratio',
5717 'regex',
5718 'system_error',
5719 ):
5720 error(filename, linenum, 'build/c++11', 5,
5721 ('<%s> is an unapproved C++11 header.') % include.group(1))
5722
5723 # The only place where we need to worry about C++11 keywords and library
5724 # features in preprocessor directives is in macro definitions.
5725 if Match(r'\s*#', line) and not Match(r'\s*#\s*define\b', line): return
5726
5727 # These are classes and free functions. The classes are always
5728 # mentioned as std::*, but we only catch the free functions if
5729 # they're not found by ADL. They're alphabetical by header.
5730 for top_name in (
5731 # type_traits
5732 'alignment_of',
5733 'aligned_union',
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005734 ):
5735 if Search(r'\bstd::%s\b' % top_name, line):
5736 error(filename, linenum, 'build/c++11', 5,
5737 ('std::%s is an unapproved C++11 class or function. Send c-style '
5738 'an example of where it would make your code more readable, and '
5739 'they may let you use it.') % top_name)
5740
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005741
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005742def FlagCxx14Features(filename, clean_lines, linenum, error):
5743 """Flag those C++14 features that we restrict.
5744
5745 Args:
5746 filename: The name of the current file.
5747 clean_lines: A CleansedLines instance containing the file.
5748 linenum: The number of the line to check.
5749 error: The function to call with any errors found.
5750 """
5751 line = clean_lines.elided[linenum]
5752
5753 include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line)
5754
5755 # Flag unapproved C++14 headers.
5756 if include and include.group(1) in ('scoped_allocator', 'shared_mutex'):
5757 error(filename, linenum, 'build/c++14', 5,
5758 ('<%s> is an unapproved C++14 header.') % include.group(1))
5759
5760
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005761def ProcessFileData(filename, file_extension, lines, error,
5762 extra_check_functions=[]):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005763 """Performs lint checks and reports any errors to the given error function.
5764
5765 Args:
5766 filename: Filename of the file that is being processed.
5767 file_extension: The extension (dot not included) of the file.
5768 lines: An array of strings, each representing a line of the file, with the
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005769 last element being empty if the file is terminated with a newline.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005770 error: A callable to which errors are reported, which takes 4 arguments:
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005771 filename, line number, error level, and message
5772 extra_check_functions: An array of additional check functions that will be
5773 run on each source line. Each function takes 4
5774 arguments: filename, clean_lines, line, error
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005775 """
5776 lines = (['// marker so line numbers and indices both start at 1'] + lines +
5777 ['// marker so line numbers end in a known way'])
5778
5779 include_state = _IncludeState()
5780 function_state = _FunctionState()
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005781 nesting_state = NestingState()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005782
erg@google.com35589e62010-11-17 18:58:16 +00005783 ResetNolintSuppressions()
5784
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005785 CheckForCopyright(filename, lines, error)
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005786 ProcessGlobalSuppresions(lines)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005787 RemoveMultiLineComments(filename, lines, error)
5788 clean_lines = CleansedLines(lines)
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005789
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00005790 if file_extension == 'h':
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005791 CheckForHeaderGuard(filename, clean_lines, error)
5792
Edward Lemur6d31ed52019-12-02 23:00:00 +00005793 for line in range(clean_lines.NumLines()):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005794 ProcessLine(filename, file_extension, clean_lines, line,
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005795 include_state, function_state, nesting_state, error,
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005796 extra_check_functions)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005797 FlagCxx11Features(filename, clean_lines, line, error)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005798 nesting_state.CheckCompletedBlocks(filename, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005799
5800 CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error)
skym@chromium.org3990c412016-02-05 20:55:12 +00005801
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005802 # Check that the .cc file has included its header if it exists.
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005803 if _IsSourceExtension(file_extension):
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005804 CheckHeaderFileIncluded(filename, include_state, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005805
5806 # We check here rather than inside ProcessLine so that we see raw
5807 # lines rather than "cleaned" lines.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005808 CheckForBadCharacters(filename, lines, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005809
5810 CheckForNewlineAtEOF(filename, lines, error)
5811
avakulenko@google.com17449932014-07-28 22:13:33 +00005812def ProcessConfigOverrides(filename):
5813 """ Loads the configuration files and processes the config overrides.
5814
5815 Args:
5816 filename: The name of the file being processed by the linter.
5817
5818 Returns:
5819 False if the current |filename| should not be processed further.
5820 """
5821
5822 abs_filename = os.path.abspath(filename)
5823 cfg_filters = []
5824 keep_looking = True
5825 while keep_looking:
5826 abs_path, base_name = os.path.split(abs_filename)
5827 if not base_name:
5828 break # Reached the root directory.
5829
5830 cfg_file = os.path.join(abs_path, "CPPLINT.cfg")
5831 abs_filename = abs_path
5832 if not os.path.isfile(cfg_file):
5833 continue
5834
5835 try:
5836 with open(cfg_file) as file_handle:
5837 for line in file_handle:
5838 line, _, _ = line.partition('#') # Remove comments.
5839 if not line.strip():
5840 continue
5841
5842 name, _, val = line.partition('=')
5843 name = name.strip()
5844 val = val.strip()
5845 if name == 'set noparent':
5846 keep_looking = False
5847 elif name == 'filter':
5848 cfg_filters.append(val)
5849 elif name == 'exclude_files':
5850 # When matching exclude_files pattern, use the base_name of
5851 # the current file name or the directory name we are processing.
5852 # For example, if we are checking for lint errors in /foo/bar/baz.cc
5853 # and we found the .cfg file at /foo/CPPLINT.cfg, then the config
5854 # file's "exclude_files" filter is meant to be checked against "bar"
5855 # and not "baz" nor "bar/baz.cc".
5856 if base_name:
5857 pattern = re.compile(val)
5858 if pattern.match(base_name):
5859 sys.stderr.write('Ignoring "%s": file excluded by "%s". '
5860 'File path component "%s" matches '
5861 'pattern "%s"\n' %
5862 (filename, cfg_file, base_name, val))
5863 return False
avakulenko@google.com68a4fa62014-08-25 16:26:18 +00005864 elif name == 'linelength':
5865 global _line_length
5866 try:
5867 _line_length = int(val)
5868 except ValueError:
5869 sys.stderr.write('Line length must be numeric.')
avakulenko@google.com17449932014-07-28 22:13:33 +00005870 else:
5871 sys.stderr.write(
5872 'Invalid configuration option (%s) in file %s\n' %
5873 (name, cfg_file))
5874
5875 except IOError:
5876 sys.stderr.write(
5877 "Skipping config file '%s': Can't open for reading\n" % cfg_file)
5878 keep_looking = False
5879
5880 # Apply all the accumulated filters in reverse order (top-level directory
5881 # config options having the least priority).
5882 for filter in reversed(cfg_filters):
5883 _AddFilters(filter)
5884
5885 return True
5886
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005887
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005888def ProcessFile(filename, vlevel, extra_check_functions=[]):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005889 """Does google-lint on a single file.
5890
5891 Args:
5892 filename: The name of the file to parse.
5893
5894 vlevel: The level of errors to report. Every error of confidence
5895 >= verbose_level will be reported. 0 is a good default.
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005896
5897 extra_check_functions: An array of additional check functions that will be
5898 run on each source line. Each function takes 4
5899 arguments: filename, clean_lines, line, error
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005900 """
5901
5902 _SetVerboseLevel(vlevel)
avakulenko@google.com17449932014-07-28 22:13:33 +00005903 _BackupFilters()
5904
5905 if not ProcessConfigOverrides(filename):
5906 _RestoreFilters()
5907 return
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005908
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005909 lf_lines = []
5910 crlf_lines = []
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005911 try:
5912 # Support the UNIX convention of using "-" for stdin. Note that
5913 # we are not opening the file with universal newline support
5914 # (which codecs doesn't support anyway), so the resulting lines do
5915 # contain trailing '\r' characters if we are reading a file that
5916 # has CRLF endings.
5917 # If after the split a trailing '\r' is present, it is removed
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005918 # below.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005919 if filename == '-':
5920 lines = codecs.StreamReaderWriter(sys.stdin,
5921 codecs.getreader('utf8'),
5922 codecs.getwriter('utf8'),
5923 'replace').read().split('\n')
5924 else:
5925 lines = codecs.open(filename, 'r', 'utf8', 'replace').read().split('\n')
5926
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005927 # Remove trailing '\r'.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005928 # The -1 accounts for the extra trailing blank line we get from split()
5929 for linenum in range(len(lines) - 1):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005930 if lines[linenum].endswith('\r'):
5931 lines[linenum] = lines[linenum].rstrip('\r')
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005932 crlf_lines.append(linenum + 1)
5933 else:
5934 lf_lines.append(linenum + 1)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005935
5936 except IOError:
5937 sys.stderr.write(
5938 "Skipping input '%s': Can't open for reading\n" % filename)
avakulenko@google.com17449932014-07-28 22:13:33 +00005939 _RestoreFilters()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005940 return
5941
5942 # Note, if no dot is found, this will give the entire filename as the ext.
5943 file_extension = filename[filename.rfind('.') + 1:]
5944
5945 # When reading from stdin, the extension is unknown, so no cpplint tests
5946 # should rely on the extension.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005947 if filename != '-' and file_extension not in _valid_extensions:
5948 sys.stderr.write('Ignoring %s; not a valid file name '
5949 '(%s)\n' % (filename, ', '.join(_valid_extensions)))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005950 else:
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005951 ProcessFileData(filename, file_extension, lines, Error,
5952 extra_check_functions)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005953
5954 # If end-of-line sequences are a mix of LF and CR-LF, issue
5955 # warnings on the lines with CR.
5956 #
5957 # Don't issue any warnings if all lines are uniformly LF or CR-LF,
5958 # since critique can handle these just fine, and the style guide
5959 # doesn't dictate a particular end of line sequence.
5960 #
5961 # We can't depend on os.linesep to determine what the desired
5962 # end-of-line sequence should be, since that will return the
5963 # server-side end-of-line sequence.
5964 if lf_lines and crlf_lines:
5965 # Warn on every line with CR. An alternative approach might be to
5966 # check whether the file is mostly CRLF or just LF, and warn on the
5967 # minority, we bias toward LF here since most tools prefer LF.
5968 for linenum in crlf_lines:
5969 Error(filename, linenum, 'whitespace/newline', 1,
5970 'Unexpected \\r (^M) found; better to use only \\n')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005971
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00005972 sys.stderr.write('Done processing %s\n' % filename)
avakulenko@google.com17449932014-07-28 22:13:33 +00005973 _RestoreFilters()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005974
5975
5976def PrintUsage(message):
5977 """Prints a brief usage string and exits, optionally with an error message.
5978
5979 Args:
5980 message: The optional error message.
5981 """
5982 sys.stderr.write(_USAGE)
5983 if message:
5984 sys.exit('\nFATAL ERROR: ' + message)
5985 else:
5986 sys.exit(1)
5987
5988
5989def PrintCategories():
5990 """Prints a list of all the error-categories used by error messages.
5991
5992 These are the categories used to filter messages via --filter.
5993 """
erg@google.com35589e62010-11-17 18:58:16 +00005994 sys.stderr.write(''.join(' %s\n' % cat for cat in _ERROR_CATEGORIES))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005995 sys.exit(0)
5996
5997
5998def ParseArguments(args):
5999 """Parses the command line arguments.
6000
6001 This may set the output format and verbosity level as side-effects.
6002
6003 Args:
6004 args: The command line arguments:
6005
6006 Returns:
6007 The list of filenames to lint.
6008 """
6009 try:
6010 (opts, filenames) = getopt.getopt(args, '', ['help', 'output=', 'verbose=',
Jordan Bayles91a32c52019-02-22 21:28:17 +00006011 'headers=', # We understand but ignore headers.
erg@google.com26970fa2009-11-17 18:07:32 +00006012 'counting=',
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00006013 'filter=',
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00006014 'root=',
6015 'linelength=',
sdefresne263e9282016-07-19 02:14:22 -07006016 'extensions=',
Jordan Bayles91a32c52019-02-22 21:28:17 +00006017 'project_root=',
6018 'repository='])
6019 except getopt.GetoptError as e:
6020 PrintUsage('Invalid arguments: {}'.format(e))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006021
6022 verbosity = _VerboseLevel()
6023 output_format = _OutputFormat()
6024 filters = ''
erg@google.com26970fa2009-11-17 18:07:32 +00006025 counting_style = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006026
6027 for (opt, val) in opts:
6028 if opt == '--help':
6029 PrintUsage(None)
6030 elif opt == '--output':
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00006031 if val not in ('emacs', 'vs7', 'eclipse'):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00006032 PrintUsage('The only allowed output formats are emacs, vs7 and eclipse.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006033 output_format = val
6034 elif opt == '--verbose':
6035 verbosity = int(val)
6036 elif opt == '--filter':
6037 filters = val
erg@google.com6317a9c2009-06-25 00:28:19 +00006038 if not filters:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006039 PrintCategories()
erg@google.com26970fa2009-11-17 18:07:32 +00006040 elif opt == '--counting':
6041 if val not in ('total', 'toplevel', 'detailed'):
6042 PrintUsage('Valid counting options are total, toplevel, and detailed')
6043 counting_style = val
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00006044 elif opt == '--root':
6045 global _root
6046 _root = val
Jordan Bayles91a32c52019-02-22 21:28:17 +00006047 elif opt == '--project_root' or opt == "--repository":
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00006048 global _project_root
6049 _project_root = val
6050 if not os.path.isabs(_project_root):
6051 PrintUsage('Project root must be an absolute path.')
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00006052 elif opt == '--linelength':
6053 global _line_length
6054 try:
6055 _line_length = int(val)
6056 except ValueError:
6057 PrintUsage('Line length must be digits.')
6058 elif opt == '--extensions':
6059 global _valid_extensions
6060 try:
6061 _valid_extensions = set(val.split(','))
6062 except ValueError:
qyearsley12fa6ff2016-08-24 09:18:40 -07006063 PrintUsage('Extensions must be comma separated list.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006064
6065 if not filenames:
6066 PrintUsage('No files were specified.')
6067
6068 _SetOutputFormat(output_format)
6069 _SetVerboseLevel(verbosity)
6070 _SetFilters(filters)
erg@google.com26970fa2009-11-17 18:07:32 +00006071 _SetCountingStyle(counting_style)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006072
6073 return filenames
6074
6075
6076def main():
6077 filenames = ParseArguments(sys.argv[1:])
6078
6079 # Change stderr to write with replacement characters so we don't die
6080 # if we try to print something containing non-ASCII characters.
Edward Lemur6d31ed52019-12-02 23:00:00 +00006081 # We use sys.stderr.buffer in Python 3, since StreamReaderWriter writes bytes
6082 # to the specified stream.
6083 sys.stderr = codecs.StreamReaderWriter(
6084 getattr(sys.stderr, 'buffer', sys.stderr),
6085 codecs.getreader('utf8'), codecs.getwriter('utf8'), 'replace')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006086
erg@google.com26970fa2009-11-17 18:07:32 +00006087 _cpplint_state.ResetErrorCounts()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006088 for filename in filenames:
6089 ProcessFile(filename, _cpplint_state.verbose_level)
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00006090 _cpplint_state.PrintErrorCounts()
erg@google.com26970fa2009-11-17 18:07:32 +00006091
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006092 sys.exit(_cpplint_state.error_count > 0)
6093
6094
6095if __name__ == '__main__':
6096 main()