blob: 3aa06b0e6cf2b8d990d5a7eff5dfe9fd0fa1c0b7 [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
3164 # 'delete []' or 'return []() {};'
3165 if Search(r'\w\s+\[', line) and not Search(r'(?:delete|return)\s+\[', line):
3166 error(filename, linenum, 'whitespace/braces', 5,
3167 'Extra space before [')
3168
3169 # In range-based for, we wanted spaces before and after the colon, but
3170 # not around "::" tokens that might appear.
3171 if (Search(r'for *\(.*[^:]:[^: ]', line) or
3172 Search(r'for *\(.*[^: ]:[^:]', line)):
3173 error(filename, linenum, 'whitespace/forcolon', 2,
3174 'Missing space around colon in range-based for loop')
3175
3176
3177def CheckOperatorSpacing(filename, clean_lines, linenum, error):
3178 """Checks for horizontal spacing around operators.
3179
3180 Args:
3181 filename: The name of the current file.
3182 clean_lines: A CleansedLines instance containing the file.
3183 linenum: The number of the line to check.
3184 error: The function to call with any errors found.
3185 """
3186 line = clean_lines.elided[linenum]
3187
3188 # Don't try to do spacing checks for operator methods. Do this by
3189 # replacing the troublesome characters with something else,
3190 # preserving column position for all other characters.
3191 #
3192 # The replacement is done repeatedly to avoid false positives from
3193 # operators that call operators.
3194 while True:
3195 match = Match(r'^(.*\boperator\b)(\S+)(\s*\(.*)$', line)
3196 if match:
3197 line = match.group(1) + ('_' * len(match.group(2))) + match.group(3)
3198 else:
3199 break
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003200
3201 # We allow no-spaces around = within an if: "if ( (a=Foo()) == 0 )".
3202 # Otherwise not. Note we only check for non-spaces on *both* sides;
3203 # sometimes people put non-spaces on one side when aligning ='s among
3204 # many lines (not that this is behavior that I approve of...)
avakulenko@google.com255f2be2014-12-05 22:19:55 +00003205 if ((Search(r'[\w.]=', line) or
3206 Search(r'=[\w.]', line))
3207 and not Search(r'\b(if|while|for) ', line)
3208 # Operators taken from [lex.operators] in C++11 standard.
3209 and not Search(r'(>=|<=|==|!=|&=|\^=|\|=|\+=|\*=|\/=|\%=)', line)
3210 and not Search(r'operator=', line)):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003211 error(filename, linenum, 'whitespace/operators', 4,
3212 'Missing spaces around =')
3213
3214 # It's ok not to have spaces around binary operators like + - * /, but if
3215 # there's too little whitespace, we get concerned. It's hard to tell,
3216 # though, so we punt on this one for now. TODO.
3217
3218 # You should always have whitespace around binary operators.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003219 #
3220 # Check <= and >= first to avoid false positives with < and >, then
3221 # check non-include lines for spacing around < and >.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003222 #
3223 # If the operator is followed by a comma, assume it's be used in a
3224 # macro context and don't do any checks. This avoids false
3225 # positives.
3226 #
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003227 # Note that && is not included here. This is because there are too
3228 # many false positives due to RValue references.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003229 match = Search(r'[^<>=!\s](==|!=|<=|>=|\|\|)[^<>=!\s,;\)]', line)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003230 if match:
3231 error(filename, linenum, 'whitespace/operators', 3,
3232 'Missing spaces around %s' % match.group(1))
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003233 elif not Match(r'#.*include', line):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003234 # Look for < that is not surrounded by spaces. This is only
3235 # triggered if both sides are missing spaces, even though
3236 # technically should should flag if at least one side is missing a
3237 # space. This is done to avoid some false positives with shifts.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003238 match = Match(r'^(.*[^\s<])<[^\s=<,]', line)
3239 if match:
3240 (_, _, end_pos) = CloseExpression(
3241 clean_lines, linenum, len(match.group(1)))
3242 if end_pos <= -1:
3243 error(filename, linenum, 'whitespace/operators', 3,
3244 'Missing spaces around <')
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003245
3246 # Look for > that is not surrounded by spaces. Similar to the
3247 # above, we only trigger if both sides are missing spaces to avoid
3248 # false positives with shifts.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003249 match = Match(r'^(.*[^-\s>])>[^\s=>,]', line)
3250 if match:
3251 (_, _, start_pos) = ReverseCloseExpression(
3252 clean_lines, linenum, len(match.group(1)))
3253 if start_pos <= -1:
3254 error(filename, linenum, 'whitespace/operators', 3,
3255 'Missing spaces around >')
3256
3257 # We allow no-spaces around << when used like this: 10<<20, but
3258 # not otherwise (particularly, not when used as streams)
avakulenko@google.com59146752014-08-11 20:20:55 +00003259 #
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003260 # We also allow operators following an opening parenthesis, since
3261 # those tend to be macros that deal with operators.
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003262 match = Search(r'(operator|[^\s(<])(?:L|UL|LL|ULL|l|ul|ll|ull)?<<([^\s,=<])', line)
avakulenko@google.com255f2be2014-12-05 22:19:55 +00003263 if (match and not (match.group(1).isdigit() and match.group(2).isdigit()) and
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003264 not (match.group(1) == 'operator' and match.group(2) == ';')):
3265 error(filename, linenum, 'whitespace/operators', 3,
3266 'Missing spaces around <<')
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003267
3268 # We allow no-spaces around >> for almost anything. This is because
3269 # C++11 allows ">>" to close nested templates, which accounts for
3270 # most cases when ">>" is not followed by a space.
3271 #
3272 # We still warn on ">>" followed by alpha character, because that is
3273 # likely due to ">>" being used for right shifts, e.g.:
3274 # value >> alpha
3275 #
3276 # When ">>" is used to close templates, the alphanumeric letter that
3277 # follows would be part of an identifier, and there should still be
3278 # a space separating the template type and the identifier.
3279 # type<type<type>> alpha
3280 match = Search(r'>>[a-zA-Z_]', line)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003281 if match:
3282 error(filename, linenum, 'whitespace/operators', 3,
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003283 'Missing spaces around >>')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003284
3285 # There shouldn't be space around unary operators
3286 match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line)
3287 if match:
3288 error(filename, linenum, 'whitespace/operators', 4,
3289 'Extra space for operator %s' % match.group(1))
3290
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003291
3292def CheckParenthesisSpacing(filename, clean_lines, linenum, error):
3293 """Checks for horizontal spacing around parentheses.
3294
3295 Args:
3296 filename: The name of the current file.
3297 clean_lines: A CleansedLines instance containing the file.
3298 linenum: The number of the line to check.
3299 error: The function to call with any errors found.
3300 """
3301 line = clean_lines.elided[linenum]
3302
3303 # No spaces after an if, while, switch, or for
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003304 match = Search(r' (if\(|for\(|while\(|switch\()', line)
3305 if match:
3306 error(filename, linenum, 'whitespace/parens', 5,
3307 'Missing space before ( in %s' % match.group(1))
3308
3309 # For if/for/while/switch, the left and right parens should be
3310 # consistent about how many spaces are inside the parens, and
3311 # there should either be zero or one spaces inside the parens.
3312 # We don't want: "if ( foo)" or "if ( foo )".
erg@google.com6317a9c2009-06-25 00:28:19 +00003313 # Exception: "for ( ; foo; bar)" and "for (foo; bar; )" are allowed.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003314 match = Search(r'\b(if|for|while|switch)\s*'
3315 r'\(([ ]*)(.).*[^ ]+([ ]*)\)\s*{\s*$',
3316 line)
3317 if match:
3318 if len(match.group(2)) != len(match.group(4)):
3319 if not (match.group(3) == ';' and
erg@google.com6317a9c2009-06-25 00:28:19 +00003320 len(match.group(2)) == 1 + len(match.group(4)) or
3321 not match.group(2) and Search(r'\bfor\s*\(.*; \)', line)):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003322 error(filename, linenum, 'whitespace/parens', 5,
3323 'Mismatching spaces inside () in %s' % match.group(1))
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003324 if len(match.group(2)) not in [0, 1]:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003325 error(filename, linenum, 'whitespace/parens', 5,
3326 'Should have zero or one spaces inside ( and ) in %s' %
3327 match.group(1))
3328
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003329
3330def CheckCommaSpacing(filename, clean_lines, linenum, error):
3331 """Checks for horizontal spacing near commas and semicolons.
3332
3333 Args:
3334 filename: The name of the current file.
3335 clean_lines: A CleansedLines instance containing the file.
3336 linenum: The number of the line to check.
3337 error: The function to call with any errors found.
3338 """
3339 raw = clean_lines.lines_without_raw_strings
3340 line = clean_lines.elided[linenum]
3341
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003342 # 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 +00003343 #
3344 # This does not apply when the non-space character following the
3345 # comma is another comma, since the only time when that happens is
3346 # for empty macro arguments.
3347 #
3348 # We run this check in two passes: first pass on elided lines to
3349 # verify that lines contain missing whitespaces, second pass on raw
3350 # lines to confirm that those missing whitespaces are not due to
3351 # elided comments.
avakulenko@google.com59146752014-08-11 20:20:55 +00003352 if (Search(r',[^,\s]', ReplaceAll(r'\boperator\s*,\s*\(', 'F(', line)) and
3353 Search(r',[^,\s]', raw[linenum])):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003354 error(filename, linenum, 'whitespace/comma', 3,
3355 'Missing space after ,')
3356
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003357 # You should always have a space after a semicolon
3358 # except for few corner cases
3359 # TODO(unknown): clarify if 'if (1) { return 1;}' is requires one more
3360 # space after ;
3361 if Search(r';[^\s};\\)/]', line):
3362 error(filename, linenum, 'whitespace/semicolon', 3,
3363 'Missing space after ;')
3364
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003365
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003366def _IsType(clean_lines, nesting_state, expr):
3367 """Check if expression looks like a type name, returns true if so.
3368
3369 Args:
3370 clean_lines: A CleansedLines instance containing the file.
3371 nesting_state: A NestingState instance which maintains information about
3372 the current stack of nested blocks being parsed.
3373 expr: The expression to check.
3374 Returns:
3375 True, if token looks like a type.
3376 """
3377 # Keep only the last token in the expression
3378 last_word = Match(r'^.*(\b\S+)$', expr)
3379 if last_word:
3380 token = last_word.group(1)
3381 else:
3382 token = expr
3383
3384 # Match native types and stdint types
3385 if _TYPES.match(token):
3386 return True
3387
3388 # Try a bit harder to match templated types. Walk up the nesting
3389 # stack until we find something that resembles a typename
3390 # declaration for what we are looking for.
3391 typename_pattern = (r'\b(?:typename|class|struct)\s+' + re.escape(token) +
3392 r'\b')
3393 block_index = len(nesting_state.stack) - 1
3394 while block_index >= 0:
3395 if isinstance(nesting_state.stack[block_index], _NamespaceInfo):
3396 return False
3397
3398 # Found where the opening brace is. We want to scan from this
3399 # line up to the beginning of the function, minus a few lines.
3400 # template <typename Type1, // stop scanning here
3401 # ...>
3402 # class C
3403 # : public ... { // start scanning here
3404 last_line = nesting_state.stack[block_index].starting_linenum
3405
3406 next_block_start = 0
3407 if block_index > 0:
3408 next_block_start = nesting_state.stack[block_index - 1].starting_linenum
3409 first_line = last_line
3410 while first_line >= next_block_start:
3411 if clean_lines.elided[first_line].find('template') >= 0:
3412 break
3413 first_line -= 1
3414 if first_line < next_block_start:
3415 # Didn't find any "template" keyword before reaching the next block,
3416 # there are probably no template things to check for this block
3417 block_index -= 1
3418 continue
3419
3420 # Look for typename in the specified range
Edward Lemur6d31ed52019-12-02 23:00:00 +00003421 for i in range(first_line, last_line + 1, 1):
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003422 if Search(typename_pattern, clean_lines.elided[i]):
3423 return True
3424 block_index -= 1
3425
3426 return False
3427
3428
3429def CheckBracesSpacing(filename, clean_lines, linenum, nesting_state, error):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003430 """Checks for horizontal spacing near commas.
3431
3432 Args:
3433 filename: The name of the current file.
3434 clean_lines: A CleansedLines instance containing the file.
3435 linenum: The number of the line to check.
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003436 nesting_state: A NestingState instance which maintains information about
3437 the current stack of nested blocks being parsed.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003438 error: The function to call with any errors found.
3439 """
3440 line = clean_lines.elided[linenum]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003441
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003442 # Except after an opening paren, or after another opening brace (in case of
3443 # an initializer list, for instance), you should have spaces before your
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003444 # braces when they are delimiting blocks, classes, namespaces etc.
3445 # And since you should never have braces at the beginning of a line,
3446 # this is an easy test. Except that braces used for initialization don't
3447 # follow the same rule; we often don't want spaces before those.
avakulenko@google.com255f2be2014-12-05 22:19:55 +00003448 match = Match(r'^(.*[^ ({>]){', line)
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003449
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003450 if match:
3451 # Try a bit harder to check for brace initialization. This
3452 # happens in one of the following forms:
3453 # Constructor() : initializer_list_{} { ... }
3454 # Constructor{}.MemberFunction()
3455 # Type variable{};
3456 # FunctionCall(type{}, ...);
3457 # LastArgument(..., type{});
3458 # LOG(INFO) << type{} << " ...";
3459 # map_of_type[{...}] = ...;
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003460 # ternary = expr ? new type{} : nullptr;
3461 # OuterTemplate<InnerTemplateConstructor<Type>{}>
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003462 #
3463 # We check for the character following the closing brace, and
3464 # silence the warning if it's one of those listed above, i.e.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003465 # "{.;,)<>]:".
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003466 #
3467 # To account for nested initializer list, we allow any number of
3468 # closing braces up to "{;,)<". We can't simply silence the
3469 # warning on first sight of closing brace, because that would
3470 # cause false negatives for things that are not initializer lists.
3471 # Silence this: But not this:
3472 # Outer{ if (...) {
3473 # Inner{...} if (...){ // Missing space before {
3474 # }; }
3475 #
3476 # There is a false negative with this approach if people inserted
3477 # spurious semicolons, e.g. "if (cond){};", but we will catch the
3478 # spurious semicolon with a separate check.
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003479 leading_text = match.group(1)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003480 (endline, endlinenum, endpos) = CloseExpression(
3481 clean_lines, linenum, len(match.group(1)))
3482 trailing_text = ''
3483 if endpos > -1:
3484 trailing_text = endline[endpos:]
Edward Lemur6d31ed52019-12-02 23:00:00 +00003485 for offset in range(endlinenum + 1,
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003486 min(endlinenum + 3, clean_lines.NumLines() - 1)):
3487 trailing_text += clean_lines.elided[offset]
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003488 # We also suppress warnings for `uint64_t{expression}` etc., as the style
3489 # guide recommends brace initialization for integral types to avoid
3490 # overflow/truncation.
3491 if (not Match(r'^[\s}]*[{.;,)<>\]:]', trailing_text)
3492 and not _IsType(clean_lines, nesting_state, leading_text)):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003493 error(filename, linenum, 'whitespace/braces', 5,
3494 'Missing space before {')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003495
3496 # Make sure '} else {' has spaces.
3497 if Search(r'}else', line):
3498 error(filename, linenum, 'whitespace/braces', 5,
3499 'Missing space before else')
3500
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003501 # You shouldn't have a space before a semicolon at the end of the line.
3502 # There's a special case for "for" since the style guide allows space before
3503 # the semicolon there.
3504 if Search(r':\s*;\s*$', line):
3505 error(filename, linenum, 'whitespace/semicolon', 5,
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003506 'Semicolon defining empty statement. Use {} instead.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003507 elif Search(r'^\s*;\s*$', line):
3508 error(filename, linenum, 'whitespace/semicolon', 5,
3509 'Line contains only semicolon. If this should be an empty statement, '
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003510 'use {} instead.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003511 elif (Search(r'\s+;\s*$', line) and
3512 not Search(r'\bfor\b', line)):
3513 error(filename, linenum, 'whitespace/semicolon', 5,
3514 'Extra space before last semicolon. If this should be an empty '
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003515 'statement, use {} instead.')
3516
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003517
3518def IsDecltype(clean_lines, linenum, column):
3519 """Check if the token ending on (linenum, column) is decltype().
3520
3521 Args:
3522 clean_lines: A CleansedLines instance containing the file.
3523 linenum: the number of the line to check.
3524 column: end column of the token to check.
3525 Returns:
3526 True if this token is decltype() expression, False otherwise.
3527 """
3528 (text, _, start_col) = ReverseCloseExpression(clean_lines, linenum, column)
3529 if start_col < 0:
3530 return False
3531 if Search(r'\bdecltype\s*$', text[0:start_col]):
3532 return True
3533 return False
3534
3535
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003536def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error):
3537 """Checks for additional blank line issues related to sections.
3538
3539 Currently the only thing checked here is blank line before protected/private.
3540
3541 Args:
3542 filename: The name of the current file.
3543 clean_lines: A CleansedLines instance containing the file.
3544 class_info: A _ClassInfo objects.
3545 linenum: The number of the line to check.
3546 error: The function to call with any errors found.
3547 """
3548 # Skip checks if the class is small, where small means 25 lines or less.
3549 # 25 lines seems like a good cutoff since that's the usual height of
3550 # terminals, and any class that can't fit in one screen can't really
3551 # be considered "small".
3552 #
3553 # Also skip checks if we are on the first line. This accounts for
3554 # classes that look like
3555 # class Foo { public: ... };
3556 #
3557 # If we didn't find the end of the class, last_line would be zero,
3558 # and the check will be skipped by the first condition.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003559 if (class_info.last_line - class_info.starting_linenum <= 24 or
3560 linenum <= class_info.starting_linenum):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003561 return
3562
3563 matched = Match(r'\s*(public|protected|private):', clean_lines.lines[linenum])
3564 if matched:
3565 # Issue warning if the line before public/protected/private was
3566 # not a blank line, but don't do this if the previous line contains
3567 # "class" or "struct". This can happen two ways:
3568 # - We are at the beginning of the class.
3569 # - We are forward-declaring an inner class that is semantically
3570 # private, but needed to be public for implementation reasons.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003571 # Also ignores cases where the previous line ends with a backslash as can be
3572 # common when defining classes in C macros.
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003573 prev_line = clean_lines.lines[linenum - 1]
3574 if (not IsBlankLine(prev_line) and
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003575 not Search(r'\b(class|struct)\b', prev_line) and
3576 not Search(r'\\$', prev_line)):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003577 # Try a bit harder to find the beginning of the class. This is to
3578 # account for multi-line base-specifier lists, e.g.:
3579 # class Derived
3580 # : public Base {
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003581 end_class_head = class_info.starting_linenum
3582 for i in range(class_info.starting_linenum, linenum):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003583 if Search(r'\{\s*$', clean_lines.lines[i]):
3584 end_class_head = i
3585 break
3586 if end_class_head < linenum - 1:
3587 error(filename, linenum, 'whitespace/blank_line', 3,
3588 '"%s:" should be preceded by a blank line' % matched.group(1))
3589
3590
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003591def GetPreviousNonBlankLine(clean_lines, linenum):
3592 """Return the most recent non-blank line and its line number.
3593
3594 Args:
3595 clean_lines: A CleansedLines instance containing the file contents.
3596 linenum: The number of the line to check.
3597
3598 Returns:
3599 A tuple with two elements. The first element is the contents of the last
3600 non-blank line before the current line, or the empty string if this is the
3601 first non-blank line. The second is the line number of that line, or -1
3602 if this is the first non-blank line.
3603 """
3604
3605 prevlinenum = linenum - 1
3606 while prevlinenum >= 0:
3607 prevline = clean_lines.elided[prevlinenum]
3608 if not IsBlankLine(prevline): # if not a blank line...
3609 return (prevline, prevlinenum)
3610 prevlinenum -= 1
3611 return ('', -1)
3612
3613
3614def CheckBraces(filename, clean_lines, linenum, error):
3615 """Looks for misplaced braces (e.g. at the end of line).
3616
3617 Args:
3618 filename: The name of the current file.
3619 clean_lines: A CleansedLines instance containing the file.
3620 linenum: The number of the line to check.
3621 error: The function to call with any errors found.
3622 """
3623
3624 line = clean_lines.elided[linenum] # get rid of comments and strings
3625
3626 if Match(r'\s*{\s*$', line):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003627 # We allow an open brace to start a line in the case where someone is using
3628 # braces in a block to explicitly create a new scope, which is commonly used
3629 # to control the lifetime of stack-allocated variables. Braces are also
3630 # used for brace initializers inside function calls. We don't detect this
3631 # perfectly: we just don't complain if the last non-whitespace character on
3632 # the previous non-blank line is ',', ';', ':', '(', '{', or '}', or if the
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003633 # previous line starts a preprocessor block. We also allow a brace on the
3634 # following line if it is part of an array initialization and would not fit
3635 # within the 80 character limit of the preceding line.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003636 prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003637 if (not Search(r'[,;:}{(]\s*$', prevline) and
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003638 not Match(r'\s*#', prevline) and
3639 not (GetLineWidth(prevline) > _line_length - 2 and '[]' in prevline)):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003640 error(filename, linenum, 'whitespace/braces', 4,
3641 '{ should almost always be at the end of the previous line')
3642
3643 # An else clause should be on the same line as the preceding closing brace.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003644 if Match(r'\s*else\b\s*(?:if\b|\{|$)', line):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003645 prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
3646 if Match(r'\s*}\s*$', prevline):
3647 error(filename, linenum, 'whitespace/newline', 4,
3648 'An else should appear on the same line as the preceding }')
3649
3650 # If braces come on one side of an else, they should be on both.
3651 # However, we have to worry about "else if" that spans multiple lines!
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003652 if Search(r'else if\s*\(', line): # could be multi-line if
3653 brace_on_left = bool(Search(r'}\s*else if\s*\(', line))
3654 # find the ( after the if
3655 pos = line.find('else if')
3656 pos = line.find('(', pos)
3657 if pos > 0:
3658 (endline, _, endpos) = CloseExpression(clean_lines, linenum, pos)
3659 brace_on_right = endline[endpos:].find('{') != -1
3660 if brace_on_left != brace_on_right: # must be brace after if
3661 error(filename, linenum, 'readability/braces', 5,
3662 'If an else has a brace on one side, it should have it on both')
3663 elif Search(r'}\s*else[^{]*$', line) or Match(r'[^}]*else\s*{', line):
3664 error(filename, linenum, 'readability/braces', 5,
3665 'If an else has a brace on one side, it should have it on both')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003666
3667 # Likewise, an else should never have the else clause on the same line
3668 if Search(r'\belse [^\s{]', line) and not Search(r'\belse if\b', line):
3669 error(filename, linenum, 'whitespace/newline', 4,
3670 'Else clause should never be on same line as else (use 2 lines)')
3671
3672 # In the same way, a do/while should never be on one line
3673 if Match(r'\s*do [^\s{]', line):
3674 error(filename, linenum, 'whitespace/newline', 4,
3675 'do/while clauses should not be on a single line')
3676
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003677 # Check single-line if/else bodies. The style guide says 'curly braces are not
3678 # required for single-line statements'. We additionally allow multi-line,
3679 # single statements, but we reject anything with more than one semicolon in
3680 # it. This means that the first semicolon after the if should be at the end of
3681 # its line, and the line after that should have an indent level equal to or
3682 # lower than the if. We also check for ambiguous if/else nesting without
3683 # braces.
3684 if_else_match = Search(r'\b(if\s*\(|else\b)', line)
3685 if if_else_match and not Match(r'\s*#', line):
3686 if_indent = GetIndentLevel(line)
3687 endline, endlinenum, endpos = line, linenum, if_else_match.end()
3688 if_match = Search(r'\bif\s*\(', line)
3689 if if_match:
3690 # This could be a multiline if condition, so find the end first.
3691 pos = if_match.end() - 1
3692 (endline, endlinenum, endpos) = CloseExpression(clean_lines, linenum, pos)
3693 # Check for an opening brace, either directly after the if or on the next
3694 # line. If found, this isn't a single-statement conditional.
3695 if (not Match(r'\s*{', endline[endpos:])
3696 and not (Match(r'\s*$', endline[endpos:])
3697 and endlinenum < (len(clean_lines.elided) - 1)
3698 and Match(r'\s*{', clean_lines.elided[endlinenum + 1]))):
3699 while (endlinenum < len(clean_lines.elided)
3700 and ';' not in clean_lines.elided[endlinenum][endpos:]):
3701 endlinenum += 1
3702 endpos = 0
3703 if endlinenum < len(clean_lines.elided):
3704 endline = clean_lines.elided[endlinenum]
3705 # We allow a mix of whitespace and closing braces (e.g. for one-liner
3706 # methods) and a single \ after the semicolon (for macros)
3707 endpos = endline.find(';')
3708 if not Match(r';[\s}]*(\\?)$', endline[endpos:]):
avakulenko@google.com59146752014-08-11 20:20:55 +00003709 # Semicolon isn't the last character, there's something trailing.
3710 # Output a warning if the semicolon is not contained inside
3711 # a lambda expression.
3712 if not Match(r'^[^{};]*\[[^\[\]]*\][^{}]*\{[^{}]*\}\s*\)*[;,]\s*$',
3713 endline):
3714 error(filename, linenum, 'readability/braces', 4,
3715 'If/else bodies with multiple statements require braces')
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003716 elif endlinenum < len(clean_lines.elided) - 1:
3717 # Make sure the next line is dedented
3718 next_line = clean_lines.elided[endlinenum + 1]
3719 next_indent = GetIndentLevel(next_line)
3720 # With ambiguous nested if statements, this will error out on the
3721 # if that *doesn't* match the else, regardless of whether it's the
3722 # inner one or outer one.
3723 if (if_match and Match(r'\s*else\b', next_line)
3724 and next_indent != if_indent):
3725 error(filename, linenum, 'readability/braces', 4,
3726 'Else clause should be indented at the same level as if. '
3727 'Ambiguous nested if/else chains require braces.')
3728 elif next_indent > if_indent:
3729 error(filename, linenum, 'readability/braces', 4,
3730 'If/else bodies with multiple statements require braces')
3731
3732
3733def CheckTrailingSemicolon(filename, clean_lines, linenum, error):
3734 """Looks for redundant trailing semicolon.
3735
3736 Args:
3737 filename: The name of the current file.
3738 clean_lines: A CleansedLines instance containing the file.
3739 linenum: The number of the line to check.
3740 error: The function to call with any errors found.
3741 """
3742
3743 line = clean_lines.elided[linenum]
3744
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003745 # Block bodies should not be followed by a semicolon. Due to C++11
3746 # brace initialization, there are more places where semicolons are
3747 # required than not, so we use a whitelist approach to check these
3748 # rather than a blacklist. These are the places where "};" should
3749 # be replaced by just "}":
3750 # 1. Some flavor of block following closing parenthesis:
3751 # for (;;) {};
3752 # while (...) {};
3753 # switch (...) {};
3754 # Function(...) {};
3755 # if (...) {};
3756 # if (...) else if (...) {};
3757 #
3758 # 2. else block:
3759 # if (...) else {};
3760 #
3761 # 3. const member function:
3762 # Function(...) const {};
3763 #
3764 # 4. Block following some statement:
3765 # x = 42;
3766 # {};
3767 #
3768 # 5. Block at the beginning of a function:
3769 # Function(...) {
3770 # {};
3771 # }
3772 #
3773 # Note that naively checking for the preceding "{" will also match
3774 # braces inside multi-dimensional arrays, but this is fine since
3775 # that expression will not contain semicolons.
3776 #
3777 # 6. Block following another block:
3778 # while (true) {}
3779 # {};
3780 #
3781 # 7. End of namespaces:
3782 # namespace {};
3783 #
3784 # These semicolons seems far more common than other kinds of
3785 # redundant semicolons, possibly due to people converting classes
3786 # to namespaces. For now we do not warn for this case.
3787 #
3788 # Try matching case 1 first.
3789 match = Match(r'^(.*\)\s*)\{', line)
3790 if match:
3791 # Matched closing parenthesis (case 1). Check the token before the
3792 # matching opening parenthesis, and don't warn if it looks like a
3793 # macro. This avoids these false positives:
3794 # - macro that defines a base class
3795 # - multi-line macro that defines a base class
3796 # - macro that defines the whole class-head
3797 #
3798 # But we still issue warnings for macros that we know are safe to
3799 # warn, specifically:
3800 # - TEST, TEST_F, TEST_P, MATCHER, MATCHER_P
3801 # - TYPED_TEST
3802 # - INTERFACE_DEF
3803 # - EXCLUSIVE_LOCKS_REQUIRED, SHARED_LOCKS_REQUIRED, LOCKS_EXCLUDED:
3804 #
3805 # We implement a whitelist of safe macros instead of a blacklist of
3806 # unsafe macros, even though the latter appears less frequently in
3807 # google code and would have been easier to implement. This is because
3808 # the downside for getting the whitelist wrong means some extra
3809 # semicolons, while the downside for getting the blacklist wrong
3810 # would result in compile errors.
3811 #
avakulenko@google.com255f2be2014-12-05 22:19:55 +00003812 # In addition to macros, we also don't want to warn on
3813 # - Compound literals
3814 # - Lambdas
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003815 # - alignas specifier with anonymous structs
3816 # - decltype
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003817 closing_brace_pos = match.group(1).rfind(')')
3818 opening_parenthesis = ReverseCloseExpression(
3819 clean_lines, linenum, closing_brace_pos)
3820 if opening_parenthesis[2] > -1:
3821 line_prefix = opening_parenthesis[0][0:opening_parenthesis[2]]
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003822 macro = Search(r'\b([A-Z_][A-Z0-9_]*)\s*$', line_prefix)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003823 func = Match(r'^(.*\])\s*$', line_prefix)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003824 if ((macro and
3825 macro.group(1) not in (
3826 'TEST', 'TEST_F', 'MATCHER', 'MATCHER_P', 'TYPED_TEST',
3827 'EXCLUSIVE_LOCKS_REQUIRED', 'SHARED_LOCKS_REQUIRED',
3828 'LOCKS_EXCLUDED', 'INTERFACE_DEF')) or
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003829 (func and not Search(r'\boperator\s*\[\s*\]', func.group(1))) or
avakulenko@google.com255f2be2014-12-05 22:19:55 +00003830 Search(r'\b(?:struct|union)\s+alignas\s*$', line_prefix) or
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003831 Search(r'\bdecltype$', line_prefix) or
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003832 Search(r'\s+=\s*$', line_prefix)):
3833 match = None
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003834 if (match and
3835 opening_parenthesis[1] > 1 and
3836 Search(r'\]\s*$', clean_lines.elided[opening_parenthesis[1] - 1])):
3837 # Multi-line lambda-expression
3838 match = None
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003839
3840 else:
3841 # Try matching cases 2-3.
3842 match = Match(r'^(.*(?:else|\)\s*const)\s*)\{', line)
3843 if not match:
3844 # Try matching cases 4-6. These are always matched on separate lines.
3845 #
3846 # Note that we can't simply concatenate the previous line to the
3847 # current line and do a single match, otherwise we may output
3848 # duplicate warnings for the blank line case:
3849 # if (cond) {
3850 # // blank line
3851 # }
3852 prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
3853 if prevline and Search(r'[;{}]\s*$', prevline):
3854 match = Match(r'^(\s*)\{', line)
3855
3856 # Check matching closing brace
3857 if match:
3858 (endline, endlinenum, endpos) = CloseExpression(
3859 clean_lines, linenum, len(match.group(1)))
3860 if endpos > -1 and Match(r'^\s*;', endline[endpos:]):
3861 # Current {} pair is eligible for semicolon check, and we have found
3862 # the redundant semicolon, output warning here.
3863 #
3864 # Note: because we are scanning forward for opening braces, and
3865 # outputting warnings for the matching closing brace, if there are
3866 # nested blocks with trailing semicolons, we will get the error
3867 # messages in reversed order.
3868 error(filename, endlinenum, 'readability/braces', 4,
3869 "You don't need a ; after a }")
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003870
3871
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003872def CheckEmptyBlockBody(filename, clean_lines, linenum, error):
3873 """Look for empty loop/conditional body with only a single semicolon.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003874
3875 Args:
3876 filename: The name of the current file.
3877 clean_lines: A CleansedLines instance containing the file.
3878 linenum: The number of the line to check.
3879 error: The function to call with any errors found.
3880 """
3881
3882 # Search for loop keywords at the beginning of the line. Because only
3883 # whitespaces are allowed before the keywords, this will also ignore most
3884 # do-while-loops, since those lines should start with closing brace.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003885 #
3886 # We also check "if" blocks here, since an empty conditional block
3887 # is likely an error.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003888 line = clean_lines.elided[linenum]
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003889 matched = Match(r'\s*(for|while|if)\s*\(', line)
3890 if matched:
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003891 # Find the end of the conditional expression.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003892 (end_line, end_linenum, end_pos) = CloseExpression(
3893 clean_lines, linenum, line.find('('))
3894
3895 # Output warning if what follows the condition expression is a semicolon.
3896 # No warning for all other cases, including whitespace or newline, since we
3897 # have a separate check for semicolons preceded by whitespace.
3898 if end_pos >= 0 and Match(r';', end_line[end_pos:]):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003899 if matched.group(1) == 'if':
3900 error(filename, end_linenum, 'whitespace/empty_conditional_body', 5,
3901 'Empty conditional bodies should use {}')
3902 else:
3903 error(filename, end_linenum, 'whitespace/empty_loop_body', 5,
3904 'Empty loop bodies should use {} or continue')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003905
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003906 # Check for if statements that have completely empty bodies (no comments)
3907 # and no else clauses.
3908 if end_pos >= 0 and matched.group(1) == 'if':
3909 # Find the position of the opening { for the if statement.
3910 # Return without logging an error if it has no brackets.
3911 opening_linenum = end_linenum
3912 opening_line_fragment = end_line[end_pos:]
3913 # Loop until EOF or find anything that's not whitespace or opening {.
3914 while not Search(r'^\s*\{', opening_line_fragment):
3915 if Search(r'^(?!\s*$)', opening_line_fragment):
3916 # Conditional has no brackets.
3917 return
3918 opening_linenum += 1
3919 if opening_linenum == len(clean_lines.elided):
3920 # Couldn't find conditional's opening { or any code before EOF.
3921 return
3922 opening_line_fragment = clean_lines.elided[opening_linenum]
3923 # Set opening_line (opening_line_fragment may not be entire opening line).
3924 opening_line = clean_lines.elided[opening_linenum]
3925
3926 # Find the position of the closing }.
3927 opening_pos = opening_line_fragment.find('{')
3928 if opening_linenum == end_linenum:
3929 # We need to make opening_pos relative to the start of the entire line.
3930 opening_pos += end_pos
3931 (closing_line, closing_linenum, closing_pos) = CloseExpression(
3932 clean_lines, opening_linenum, opening_pos)
3933 if closing_pos < 0:
3934 return
3935
3936 # Now construct the body of the conditional. This consists of the portion
3937 # of the opening line after the {, all lines until the closing line,
3938 # and the portion of the closing line before the }.
3939 if (clean_lines.raw_lines[opening_linenum] !=
3940 CleanseComments(clean_lines.raw_lines[opening_linenum])):
3941 # Opening line ends with a comment, so conditional isn't empty.
3942 return
3943 if closing_linenum > opening_linenum:
3944 # Opening line after the {. Ignore comments here since we checked above.
3945 body = list(opening_line[opening_pos+1:])
3946 # All lines until closing line, excluding closing line, with comments.
3947 body.extend(clean_lines.raw_lines[opening_linenum+1:closing_linenum])
3948 # Closing line before the }. Won't (and can't) have comments.
3949 body.append(clean_lines.elided[closing_linenum][:closing_pos-1])
3950 body = '\n'.join(body)
3951 else:
3952 # If statement has brackets and fits on a single line.
3953 body = opening_line[opening_pos+1:closing_pos-1]
3954
3955 # Check if the body is empty
3956 if not _EMPTY_CONDITIONAL_BODY_PATTERN.search(body):
3957 return
3958 # The body is empty. Now make sure there's not an else clause.
3959 current_linenum = closing_linenum
3960 current_line_fragment = closing_line[closing_pos:]
3961 # Loop until EOF or find anything that's not whitespace or else clause.
3962 while Search(r'^\s*$|^(?=\s*else)', current_line_fragment):
3963 if Search(r'^(?=\s*else)', current_line_fragment):
3964 # Found an else clause, so don't log an error.
3965 return
3966 current_linenum += 1
3967 if current_linenum == len(clean_lines.elided):
3968 break
3969 current_line_fragment = clean_lines.elided[current_linenum]
3970
3971 # The body is empty and there's no else clause until EOF or other code.
3972 error(filename, end_linenum, 'whitespace/empty_if_body', 4,
3973 ('If statement had no body and no else clause'))
3974
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003975
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003976def FindCheckMacro(line):
3977 """Find a replaceable CHECK-like macro.
3978
3979 Args:
3980 line: line to search on.
3981 Returns:
3982 (macro name, start position), or (None, -1) if no replaceable
3983 macro is found.
3984 """
3985 for macro in _CHECK_MACROS:
3986 i = line.find(macro)
3987 if i >= 0:
3988 # Find opening parenthesis. Do a regular expression match here
3989 # to make sure that we are matching the expected CHECK macro, as
3990 # opposed to some other macro that happens to contain the CHECK
3991 # substring.
3992 matched = Match(r'^(.*\b' + macro + r'\s*)\(', line)
3993 if not matched:
3994 continue
3995 return (macro, len(matched.group(1)))
3996 return (None, -1)
3997
3998
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003999def CheckCheck(filename, clean_lines, linenum, error):
4000 """Checks the use of CHECK and EXPECT macros.
4001
4002 Args:
4003 filename: The name of the current file.
4004 clean_lines: A CleansedLines instance containing the file.
4005 linenum: The number of the line to check.
4006 error: The function to call with any errors found.
4007 """
4008
4009 # Decide the set of replacement macros that should be suggested
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004010 lines = clean_lines.elided
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004011 (check_macro, start_pos) = FindCheckMacro(lines[linenum])
4012 if not check_macro:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004013 return
4014
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004015 # Find end of the boolean expression by matching parentheses
4016 (last_line, end_line, end_pos) = CloseExpression(
4017 clean_lines, linenum, start_pos)
4018 if end_pos < 0:
4019 return
avakulenko@google.com59146752014-08-11 20:20:55 +00004020
4021 # If the check macro is followed by something other than a
4022 # semicolon, assume users will log their own custom error messages
4023 # and don't suggest any replacements.
4024 if not Match(r'\s*;', last_line[end_pos:]):
4025 return
4026
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004027 if linenum == end_line:
4028 expression = lines[linenum][start_pos + 1:end_pos - 1]
4029 else:
4030 expression = lines[linenum][start_pos + 1:]
Edward Lemur6d31ed52019-12-02 23:00:00 +00004031 for i in range(linenum + 1, end_line):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004032 expression += lines[i]
4033 expression += last_line[0:end_pos - 1]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004034
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004035 # Parse expression so that we can take parentheses into account.
4036 # This avoids false positives for inputs like "CHECK((a < 4) == b)",
4037 # which is not replaceable by CHECK_LE.
4038 lhs = ''
4039 rhs = ''
4040 operator = None
4041 while expression:
4042 matched = Match(r'^\s*(<<|<<=|>>|>>=|->\*|->|&&|\|\||'
4043 r'==|!=|>=|>|<=|<|\()(.*)$', expression)
4044 if matched:
4045 token = matched.group(1)
4046 if token == '(':
4047 # Parenthesized operand
4048 expression = matched.group(2)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004049 (end, _) = FindEndOfExpressionInLine(expression, 0, ['('])
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004050 if end < 0:
4051 return # Unmatched parenthesis
4052 lhs += '(' + expression[0:end]
4053 expression = expression[end:]
4054 elif token in ('&&', '||'):
4055 # Logical and/or operators. This means the expression
4056 # contains more than one term, for example:
4057 # CHECK(42 < a && a < b);
4058 #
4059 # These are not replaceable with CHECK_LE, so bail out early.
4060 return
4061 elif token in ('<<', '<<=', '>>', '>>=', '->*', '->'):
4062 # Non-relational operator
4063 lhs += token
4064 expression = matched.group(2)
4065 else:
4066 # Relational operator
4067 operator = token
4068 rhs = matched.group(2)
4069 break
4070 else:
4071 # Unparenthesized operand. Instead of appending to lhs one character
4072 # at a time, we do another regular expression match to consume several
4073 # characters at once if possible. Trivial benchmark shows that this
4074 # is more efficient when the operands are longer than a single
4075 # character, which is generally the case.
4076 matched = Match(r'^([^-=!<>()&|]+)(.*)$', expression)
4077 if not matched:
4078 matched = Match(r'^(\s*\S)(.*)$', expression)
4079 if not matched:
4080 break
4081 lhs += matched.group(1)
4082 expression = matched.group(2)
4083
4084 # Only apply checks if we got all parts of the boolean expression
4085 if not (lhs and operator and rhs):
4086 return
4087
4088 # Check that rhs do not contain logical operators. We already know
4089 # that lhs is fine since the loop above parses out && and ||.
4090 if rhs.find('&&') > -1 or rhs.find('||') > -1:
4091 return
4092
4093 # At least one of the operands must be a constant literal. This is
4094 # to avoid suggesting replacements for unprintable things like
4095 # CHECK(variable != iterator)
4096 #
4097 # The following pattern matches decimal, hex integers, strings, and
4098 # characters (in that order).
4099 lhs = lhs.strip()
4100 rhs = rhs.strip()
4101 match_constant = r'^([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')$'
4102 if Match(match_constant, lhs) or Match(match_constant, rhs):
4103 # Note: since we know both lhs and rhs, we can provide a more
4104 # descriptive error message like:
4105 # Consider using CHECK_EQ(x, 42) instead of CHECK(x == 42)
4106 # Instead of:
4107 # Consider using CHECK_EQ instead of CHECK(a == b)
4108 #
4109 # We are still keeping the less descriptive message because if lhs
4110 # or rhs gets long, the error message might become unreadable.
4111 error(filename, linenum, 'readability/check', 2,
4112 'Consider using %s instead of %s(a %s b)' % (
4113 _CHECK_REPLACEMENT[check_macro][operator],
4114 check_macro, operator))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004115
4116
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004117def CheckAltTokens(filename, clean_lines, linenum, error):
4118 """Check alternative keywords being used in boolean expressions.
4119
4120 Args:
4121 filename: The name of the current file.
4122 clean_lines: A CleansedLines instance containing the file.
4123 linenum: The number of the line to check.
4124 error: The function to call with any errors found.
4125 """
4126 line = clean_lines.elided[linenum]
4127
4128 # Avoid preprocessor lines
4129 if Match(r'^\s*#', line):
4130 return
4131
4132 # Last ditch effort to avoid multi-line comments. This will not help
4133 # if the comment started before the current line or ended after the
4134 # current line, but it catches most of the false positives. At least,
4135 # it provides a way to workaround this warning for people who use
4136 # multi-line comments in preprocessor macros.
4137 #
4138 # TODO(unknown): remove this once cpplint has better support for
4139 # multi-line comments.
4140 if line.find('/*') >= 0 or line.find('*/') >= 0:
4141 return
4142
4143 for match in _ALT_TOKEN_REPLACEMENT_PATTERN.finditer(line):
4144 error(filename, linenum, 'readability/alt_tokens', 2,
4145 'Use operator %s instead of %s' % (
4146 _ALT_TOKEN_REPLACEMENT[match.group(1)], match.group(1)))
4147
4148
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004149def GetLineWidth(line):
4150 """Determines the width of the line in column positions.
4151
4152 Args:
4153 line: A string, which may be a Unicode string.
4154
4155 Returns:
4156 The width of the line in column positions, accounting for Unicode
4157 combining characters and wide characters.
4158 """
Edward Lemur6d31ed52019-12-02 23:00:00 +00004159 if sys.version_info == 2 and isinstance(line, unicode):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004160 width = 0
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004161 for uc in unicodedata.normalize('NFC', line):
4162 if unicodedata.east_asian_width(uc) in ('W', 'F'):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004163 width += 2
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004164 elif not unicodedata.combining(uc):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004165 width += 1
4166 return width
4167 else:
4168 return len(line)
4169
4170
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004171def CheckStyle(filename, clean_lines, linenum, file_extension, nesting_state,
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004172 error):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004173 """Checks rules from the 'C++ style rules' section of cppguide.html.
4174
4175 Most of these rules are hard to test (naming, comment style), but we
4176 do what we can. In particular we check for 2-space indents, line lengths,
4177 tab usage, spaces inside code, etc.
4178
4179 Args:
4180 filename: The name of the current file.
4181 clean_lines: A CleansedLines instance containing the file.
4182 linenum: The number of the line to check.
4183 file_extension: The extension (without the dot) of the filename.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004184 nesting_state: A NestingState instance which maintains information about
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004185 the current stack of nested blocks being parsed.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004186 error: The function to call with any errors found.
4187 """
4188
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004189 # Don't use "elided" lines here, otherwise we can't check commented lines.
4190 # Don't want to use "raw" either, because we don't want to check inside C++11
4191 # raw strings,
4192 raw_lines = clean_lines.lines_without_raw_strings
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004193 line = raw_lines[linenum]
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004194 prev = raw_lines[linenum - 1] if linenum > 0 else ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004195
4196 if line.find('\t') != -1:
4197 error(filename, linenum, 'whitespace/tab', 1,
4198 'Tab found; better to use spaces')
4199
4200 # One or three blank spaces at the beginning of the line is weird; it's
4201 # hard to reconcile that with 2-space indents.
4202 # NOTE: here are the conditions rob pike used for his tests. Mine aren't
4203 # as sophisticated, but it may be worth becoming so: RLENGTH==initial_spaces
4204 # if(RLENGTH > 20) complain = 0;
4205 # if(match($0, " +(error|private|public|protected):")) complain = 0;
4206 # if(match(prev, "&& *$")) complain = 0;
4207 # if(match(prev, "\\|\\| *$")) complain = 0;
4208 # if(match(prev, "[\",=><] *$")) complain = 0;
4209 # if(match($0, " <<")) complain = 0;
4210 # if(match(prev, " +for \\(")) complain = 0;
4211 # if(prevodd && match(prevprev, " +for \\(")) complain = 0;
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004212 scope_or_label_pattern = r'\s*\w+\s*:\s*\\?$'
4213 classinfo = nesting_state.InnermostClass()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004214 initial_spaces = 0
4215 cleansed_line = clean_lines.elided[linenum]
4216 while initial_spaces < len(line) and line[initial_spaces] == ' ':
4217 initial_spaces += 1
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004218 # There are certain situations we allow one space, notably for
4219 # section labels, and also lines containing multi-line raw strings.
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004220 # We also don't check for lines that look like continuation lines
4221 # (of lines ending in double quotes, commas, equals, or angle brackets)
4222 # because the rules for how to indent those are non-trivial.
4223 if (not Search(r'[",=><] *$', prev) and
4224 (initial_spaces == 1 or initial_spaces == 3) and
4225 not Match(scope_or_label_pattern, cleansed_line) and
4226 not (clean_lines.raw_lines[linenum] != line and
4227 Match(r'^\s*""', line))):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004228 error(filename, linenum, 'whitespace/indent', 3,
4229 'Weird number of spaces at line-start. '
4230 'Are you using a 2-space indent?')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004231
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004232 if line and line[-1].isspace():
4233 error(filename, linenum, 'whitespace/end_of_line', 4,
4234 'Line ends in whitespace. Consider deleting these extra spaces.')
4235
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004236 # Check if the line is a header guard.
4237 is_header_guard = False
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00004238 if file_extension == 'h':
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004239 cppvar = GetHeaderGuardCPPVariable(filename)
4240 if (line.startswith('#ifndef %s' % cppvar) or
4241 line.startswith('#define %s' % cppvar) or
4242 line.startswith('#endif // %s' % cppvar)):
4243 is_header_guard = True
4244 # #include lines and header guards can be long, since there's no clean way to
4245 # split them.
erg@google.com6317a9c2009-06-25 00:28:19 +00004246 #
4247 # URLs can be long too. It's possible to split these, but it makes them
4248 # harder to cut&paste.
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004249 #
4250 # The "$Id:...$" comment may also get very long without it being the
4251 # developers fault.
erg@google.com6317a9c2009-06-25 00:28:19 +00004252 if (not line.startswith('#include') and not is_header_guard and
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004253 not Match(r'^\s*//.*http(s?)://\S*$', line) and
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004254 not Match(r'^\s*//\s*[^\s]*$', line) and
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004255 not Match(r'^// \$Id:.*#[0-9]+ \$$', line)):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004256 line_width = GetLineWidth(line)
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004257 if line_width > _line_length:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004258 error(filename, linenum, 'whitespace/line_length', 2,
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004259 'Lines should be <= %i characters long' % _line_length)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004260
4261 if (cleansed_line.count(';') > 1 and
4262 # for loops are allowed two ;'s (and may run over two lines).
4263 cleansed_line.find('for') == -1 and
4264 (GetPreviousNonBlankLine(clean_lines, linenum)[0].find('for') == -1 or
4265 GetPreviousNonBlankLine(clean_lines, linenum)[0].find(';') != -1) and
4266 # It's ok to have many commands in a switch case that fits in 1 line
4267 not ((cleansed_line.find('case ') != -1 or
4268 cleansed_line.find('default:') != -1) and
4269 cleansed_line.find('break;') != -1)):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004270 error(filename, linenum, 'whitespace/newline', 0,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004271 'More than one command on the same line')
4272
4273 # Some more style checks
4274 CheckBraces(filename, clean_lines, linenum, error)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004275 CheckTrailingSemicolon(filename, clean_lines, linenum, error)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004276 CheckEmptyBlockBody(filename, clean_lines, linenum, error)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004277 CheckSpacing(filename, clean_lines, linenum, nesting_state, error)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004278 CheckOperatorSpacing(filename, clean_lines, linenum, error)
4279 CheckParenthesisSpacing(filename, clean_lines, linenum, error)
4280 CheckCommaSpacing(filename, clean_lines, linenum, error)
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004281 CheckBracesSpacing(filename, clean_lines, linenum, nesting_state, error)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004282 CheckSpacingForFunctionCall(filename, clean_lines, linenum, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004283 CheckCheck(filename, clean_lines, linenum, error)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004284 CheckAltTokens(filename, clean_lines, linenum, error)
4285 classinfo = nesting_state.InnermostClass()
4286 if classinfo:
4287 CheckSectionSpacing(filename, clean_lines, classinfo, linenum, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004288
4289
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004290_RE_PATTERN_INCLUDE = re.compile(r'^\s*#\s*include\s*([<"])([^>"]*)[>"].*$')
4291# Matches the first component of a filename delimited by -s and _s. That is:
4292# _RE_FIRST_COMPONENT.match('foo').group(0) == 'foo'
4293# _RE_FIRST_COMPONENT.match('foo.cc').group(0) == 'foo'
4294# _RE_FIRST_COMPONENT.match('foo-bar_baz.cc').group(0) == 'foo'
4295# _RE_FIRST_COMPONENT.match('foo_bar-baz.cc').group(0) == 'foo'
4296_RE_FIRST_COMPONENT = re.compile(r'^[^-_.]+')
4297
4298
4299def _DropCommonSuffixes(filename):
4300 """Drops common suffixes like _test.cc or -inl.h from filename.
4301
4302 For example:
4303 >>> _DropCommonSuffixes('foo/foo-inl.h')
4304 'foo/foo'
4305 >>> _DropCommonSuffixes('foo/bar/foo.cc')
4306 'foo/bar/foo'
4307 >>> _DropCommonSuffixes('foo/foo_internal.h')
4308 'foo/foo'
4309 >>> _DropCommonSuffixes('foo/foo_unusualinternal.h')
4310 'foo/foo_unusualinternal'
4311
4312 Args:
4313 filename: The input filename.
4314
4315 Returns:
4316 The filename with the common suffix removed.
4317 """
4318 for suffix in ('test.cc', 'regtest.cc', 'unittest.cc',
4319 'inl.h', 'impl.h', 'internal.h'):
4320 if (filename.endswith(suffix) and len(filename) > len(suffix) and
4321 filename[-len(suffix) - 1] in ('-', '_')):
4322 return filename[:-len(suffix) - 1]
4323 return os.path.splitext(filename)[0]
4324
4325
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004326def _ClassifyInclude(fileinfo, include, is_system):
4327 """Figures out what kind of header 'include' is.
4328
4329 Args:
4330 fileinfo: The current file cpplint is running over. A FileInfo instance.
4331 include: The path to a #included file.
4332 is_system: True if the #include used <> rather than "".
4333
4334 Returns:
4335 One of the _XXX_HEADER constants.
4336
4337 For example:
4338 >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'stdio.h', True)
4339 _C_SYS_HEADER
4340 >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'string', True)
4341 _CPP_SYS_HEADER
4342 >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', False)
4343 _LIKELY_MY_HEADER
4344 >>> _ClassifyInclude(FileInfo('foo/foo_unknown_extension.cc'),
4345 ... 'bar/foo_other_ext.h', False)
4346 _POSSIBLE_MY_HEADER
4347 >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/bar.h', False)
4348 _OTHER_HEADER
4349 """
4350 # This is a list of all standard c++ header files, except
4351 # those already checked for above.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004352 is_cpp_h = include in _CPP_HEADERS
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004353
4354 if is_system:
4355 if is_cpp_h:
4356 return _CPP_SYS_HEADER
4357 else:
4358 return _C_SYS_HEADER
4359
4360 # If the target file and the include we're checking share a
4361 # basename when we drop common extensions, and the include
4362 # lives in . , then it's likely to be owned by the target file.
4363 target_dir, target_base = (
4364 os.path.split(_DropCommonSuffixes(fileinfo.RepositoryName())))
4365 include_dir, include_base = os.path.split(_DropCommonSuffixes(include))
4366 if target_base == include_base and (
4367 include_dir == target_dir or
4368 include_dir == os.path.normpath(target_dir + '/../public')):
4369 return _LIKELY_MY_HEADER
4370
4371 # If the target and include share some initial basename
4372 # component, it's possible the target is implementing the
4373 # include, so it's allowed to be first, but we'll never
4374 # complain if it's not there.
4375 target_first_component = _RE_FIRST_COMPONENT.match(target_base)
4376 include_first_component = _RE_FIRST_COMPONENT.match(include_base)
4377 if (target_first_component and include_first_component and
4378 target_first_component.group(0) ==
4379 include_first_component.group(0)):
4380 return _POSSIBLE_MY_HEADER
4381
4382 return _OTHER_HEADER
4383
4384
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004385
erg@google.com6317a9c2009-06-25 00:28:19 +00004386def CheckIncludeLine(filename, clean_lines, linenum, include_state, error):
4387 """Check rules that are applicable to #include lines.
4388
4389 Strings on #include lines are NOT removed from elided line, to make
4390 certain tasks easier. However, to prevent false positives, checks
4391 applicable to #include lines in CheckLanguage must be put here.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004392
4393 Args:
4394 filename: The name of the current file.
4395 clean_lines: A CleansedLines instance containing the file.
4396 linenum: The number of the line to check.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004397 include_state: An _IncludeState instance in which the headers are inserted.
4398 error: The function to call with any errors found.
4399 """
4400 fileinfo = FileInfo(filename)
erg@google.com6317a9c2009-06-25 00:28:19 +00004401 line = clean_lines.lines[linenum]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004402
4403 # "include" should use the new style "foo/bar.h" instead of just "bar.h"
avakulenko@google.com59146752014-08-11 20:20:55 +00004404 # Only do this check if the included header follows google naming
4405 # conventions. If not, assume that it's a 3rd party API that
4406 # requires special include conventions.
4407 #
4408 # We also make an exception for Lua headers, which follow google
4409 # naming convention but not the include convention.
4410 match = Match(r'#include\s*"([^/]+\.h)"', line)
4411 if match and not _THIRD_PARTY_HEADERS_PATTERN.match(match.group(1)):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004412 error(filename, linenum, 'build/include', 4,
4413 'Include the directory when naming .h files')
4414
4415 # we shouldn't include a file more than once. actually, there are a
4416 # handful of instances where doing so is okay, but in general it's
4417 # not.
erg@google.com6317a9c2009-06-25 00:28:19 +00004418 match = _RE_PATTERN_INCLUDE.search(line)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004419 if match:
4420 include = match.group(2)
4421 is_system = (match.group(1) == '<')
avakulenko@google.com59146752014-08-11 20:20:55 +00004422 duplicate_line = include_state.FindHeader(include)
4423 if duplicate_line >= 0:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004424 error(filename, linenum, 'build/include', 4,
4425 '"%s" already included at %s:%s' %
avakulenko@google.com59146752014-08-11 20:20:55 +00004426 (include, filename, duplicate_line))
avakulenko@google.com255f2be2014-12-05 22:19:55 +00004427 elif (include.endswith('.cc') and
4428 os.path.dirname(fileinfo.RepositoryName()) != os.path.dirname(include)):
4429 error(filename, linenum, 'build/include', 4,
4430 'Do not include .cc files from other packages')
avakulenko@google.com59146752014-08-11 20:20:55 +00004431 elif not _THIRD_PARTY_HEADERS_PATTERN.match(include):
4432 include_state.include_list[-1].append((include, linenum))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004433
4434 # We want to ensure that headers appear in the right order:
4435 # 1) for foo.cc, foo.h (preferred location)
4436 # 2) c system files
4437 # 3) cpp system files
4438 # 4) for foo.cc, foo.h (deprecated location)
4439 # 5) other google headers
4440 #
4441 # We classify each include statement as one of those 5 types
4442 # using a number of techniques. The include_state object keeps
4443 # track of the highest type seen, and complains if we see a
4444 # lower type after that.
4445 error_message = include_state.CheckNextIncludeOrder(
4446 _ClassifyInclude(fileinfo, include, is_system))
4447 if error_message:
4448 error(filename, linenum, 'build/include_order', 4,
4449 '%s. Should be: %s.h, c system, c++ system, other.' %
4450 (error_message, fileinfo.BaseName()))
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004451 canonical_include = include_state.CanonicalizeAlphabeticalOrder(include)
4452 if not include_state.IsInAlphabeticalOrder(
4453 clean_lines, linenum, canonical_include):
erg@google.com26970fa2009-11-17 18:07:32 +00004454 error(filename, linenum, 'build/include_alpha', 4,
4455 'Include "%s" not in alphabetical order' % include)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004456 include_state.SetLastHeader(canonical_include)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004457
erg@google.com6317a9c2009-06-25 00:28:19 +00004458
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004459
4460def _GetTextInside(text, start_pattern):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004461 r"""Retrieves all the text between matching open and close parentheses.
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004462
4463 Given a string of lines and a regular expression string, retrieve all the text
4464 following the expression and between opening punctuation symbols like
4465 (, [, or {, and the matching close-punctuation symbol. This properly nested
4466 occurrences of the punctuations, so for the text like
4467 printf(a(), b(c()));
4468 a call to _GetTextInside(text, r'printf\(') will return 'a(), b(c())'.
4469 start_pattern must match string having an open punctuation symbol at the end.
4470
4471 Args:
4472 text: The lines to extract text. Its comments and strings must be elided.
4473 It can be single line and can span multiple lines.
4474 start_pattern: The regexp string indicating where to start extracting
4475 the text.
4476 Returns:
4477 The extracted text.
4478 None if either the opening string or ending punctuation could not be found.
4479 """
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004480 # TODO(unknown): Audit cpplint.py to see what places could be profitably
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004481 # rewritten to use _GetTextInside (and use inferior regexp matching today).
4482
4483 # Give opening punctuations to get the matching close-punctuations.
4484 matching_punctuation = {'(': ')', '{': '}', '[': ']'}
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +00004485 closing_punctuation = set(matching_punctuation.values())
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004486
4487 # Find the position to start extracting text.
4488 match = re.search(start_pattern, text, re.M)
4489 if not match: # start_pattern not found in text.
4490 return None
4491 start_position = match.end(0)
4492
4493 assert start_position > 0, (
4494 'start_pattern must ends with an opening punctuation.')
4495 assert text[start_position - 1] in matching_punctuation, (
4496 'start_pattern must ends with an opening punctuation.')
4497 # Stack of closing punctuations we expect to have in text after position.
4498 punctuation_stack = [matching_punctuation[text[start_position - 1]]]
4499 position = start_position
4500 while punctuation_stack and position < len(text):
4501 if text[position] == punctuation_stack[-1]:
4502 punctuation_stack.pop()
4503 elif text[position] in closing_punctuation:
4504 # A closing punctuation without matching opening punctuations.
4505 return None
4506 elif text[position] in matching_punctuation:
4507 punctuation_stack.append(matching_punctuation[text[position]])
4508 position += 1
4509 if punctuation_stack:
4510 # Opening punctuations left without matching close-punctuations.
4511 return None
4512 # punctuations match.
4513 return text[start_position:position - 1]
4514
4515
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004516# Patterns for matching call-by-reference parameters.
4517#
4518# Supports nested templates up to 2 levels deep using this messy pattern:
4519# < (?: < (?: < [^<>]*
4520# >
4521# | [^<>] )*
4522# >
4523# | [^<>] )*
4524# >
4525_RE_PATTERN_IDENT = r'[_a-zA-Z]\w*' # =~ [[:alpha:]][[:alnum:]]*
4526_RE_PATTERN_TYPE = (
4527 r'(?:const\s+)?(?:typename\s+|class\s+|struct\s+|union\s+|enum\s+)?'
4528 r'(?:\w|'
4529 r'\s*<(?:<(?:<[^<>]*>|[^<>])*>|[^<>])*>|'
4530 r'::)+')
4531# A call-by-reference parameter ends with '& identifier'.
4532_RE_PATTERN_REF_PARAM = re.compile(
4533 r'(' + _RE_PATTERN_TYPE + r'(?:\s*(?:\bconst\b|[*]))*\s*'
4534 r'&\s*' + _RE_PATTERN_IDENT + r')\s*(?:=[^,()]+)?[,)]')
4535# A call-by-const-reference parameter either ends with 'const& identifier'
4536# or looks like 'const type& identifier' when 'type' is atomic.
4537_RE_PATTERN_CONST_REF_PARAM = (
4538 r'(?:.*\s*\bconst\s*&\s*' + _RE_PATTERN_IDENT +
4539 r'|const\s+' + _RE_PATTERN_TYPE + r'\s*&\s*' + _RE_PATTERN_IDENT + r')')
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004540# Stream types.
4541_RE_PATTERN_REF_STREAM_PARAM = (
4542 r'(?:.*stream\s*&\s*' + _RE_PATTERN_IDENT + r')')
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004543
4544
4545def CheckLanguage(filename, clean_lines, linenum, file_extension,
4546 include_state, nesting_state, error):
erg@google.com6317a9c2009-06-25 00:28:19 +00004547 """Checks rules from the 'C++ language rules' section of cppguide.html.
4548
4549 Some of these rules are hard to test (function overloading, using
4550 uint32 inappropriately), but we do the best we can.
4551
4552 Args:
4553 filename: The name of the current file.
4554 clean_lines: A CleansedLines instance containing the file.
4555 linenum: The number of the line to check.
4556 file_extension: The extension (without the dot) of the filename.
4557 include_state: An _IncludeState instance in which the headers are inserted.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004558 nesting_state: A NestingState instance which maintains information about
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004559 the current stack of nested blocks being parsed.
erg@google.com6317a9c2009-06-25 00:28:19 +00004560 error: The function to call with any errors found.
4561 """
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004562 # If the line is empty or consists of entirely a comment, no need to
4563 # check it.
4564 line = clean_lines.elided[linenum]
4565 if not line:
4566 return
4567
erg@google.com6317a9c2009-06-25 00:28:19 +00004568 match = _RE_PATTERN_INCLUDE.search(line)
4569 if match:
4570 CheckIncludeLine(filename, clean_lines, linenum, include_state, error)
4571 return
4572
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004573 # Reset include state across preprocessor directives. This is meant
4574 # to silence warnings for conditional includes.
avakulenko@google.com59146752014-08-11 20:20:55 +00004575 match = Match(r'^\s*#\s*(if|ifdef|ifndef|elif|else|endif)\b', line)
4576 if match:
4577 include_state.ResetSection(match.group(1))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004578
4579 # Make Windows paths like Unix.
4580 fullname = os.path.abspath(filename).replace('\\', '/')
skym@chromium.org3990c412016-02-05 20:55:12 +00004581
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004582 # Perform other checks now that we are sure that this is not an include line
4583 CheckCasts(filename, clean_lines, linenum, error)
4584 CheckGlobalStatic(filename, clean_lines, linenum, error)
4585 CheckPrintf(filename, clean_lines, linenum, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004586
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00004587 if file_extension == 'h':
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004588 # TODO(unknown): check that 1-arg constructors are explicit.
4589 # How to tell it's a constructor?
4590 # (handled in CheckForNonStandardConstructs for now)
avakulenko@google.com59146752014-08-11 20:20:55 +00004591 # TODO(unknown): check that classes declare or disable copy/assign
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004592 # (level 1 error)
4593 pass
4594
4595 # Check if people are using the verboten C basic types. The only exception
4596 # we regularly allow is "unsigned short port" for port.
4597 if Search(r'\bshort port\b', line):
4598 if not Search(r'\bunsigned short port\b', line):
4599 error(filename, linenum, 'runtime/int', 4,
4600 'Use "unsigned short" for ports, not "short"')
4601 else:
4602 match = Search(r'\b(short|long(?! +double)|long long)\b', line)
4603 if match:
4604 error(filename, linenum, 'runtime/int', 4,
4605 'Use int16/int64/etc, rather than the C type %s' % match.group(1))
4606
erg@google.com26970fa2009-11-17 18:07:32 +00004607 # Check if some verboten operator overloading is going on
4608 # TODO(unknown): catch out-of-line unary operator&:
4609 # class X {};
4610 # int operator&(const X& x) { return 42; } // unary operator&
4611 # The trick is it's hard to tell apart from binary operator&:
4612 # class Y { int operator&(const Y& x) { return 23; } }; // binary operator&
4613 if Search(r'\boperator\s*&\s*\(\s*\)', line):
4614 error(filename, linenum, 'runtime/operator', 4,
4615 'Unary operator& is dangerous. Do not use it.')
4616
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004617 # Check for suspicious usage of "if" like
4618 # } if (a == b) {
4619 if Search(r'\}\s*if\s*\(', line):
4620 error(filename, linenum, 'readability/braces', 4,
4621 'Did you mean "else if"? If not, start a new line for "if".')
4622
4623 # Check for potential format string bugs like printf(foo).
4624 # We constrain the pattern not to pick things like DocidForPrintf(foo).
4625 # Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str())
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004626 # TODO(unknown): Catch the following case. Need to change the calling
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004627 # convention of the whole function to process multiple line to handle it.
4628 # printf(
4629 # boy_this_is_a_really_long_variable_that_cannot_fit_on_the_prev_line);
4630 printf_args = _GetTextInside(line, r'(?i)\b(string)?printf\s*\(')
4631 if printf_args:
4632 match = Match(r'([\w.\->()]+)$', printf_args)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004633 if match and match.group(1) != '__VA_ARGS__':
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004634 function_name = re.search(r'\b((?:string)?printf)\s*\(',
4635 line, re.I).group(1)
4636 error(filename, linenum, 'runtime/printf', 4,
4637 'Potential format string bug. Do %s("%%s", %s) instead.'
4638 % (function_name, match.group(1)))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004639
4640 # Check for potential memset bugs like memset(buf, sizeof(buf), 0).
4641 match = Search(r'memset\s*\(([^,]*),\s*([^,]*),\s*0\s*\)', line)
4642 if match and not Match(r"^''|-?[0-9]+|0x[0-9A-Fa-f]$", match.group(2)):
4643 error(filename, linenum, 'runtime/memset', 4,
4644 'Did you mean "memset(%s, 0, %s)"?'
4645 % (match.group(1), match.group(2)))
4646
4647 if Search(r'\busing namespace\b', line):
4648 error(filename, linenum, 'build/namespaces', 5,
4649 'Do not use namespace using-directives. '
4650 'Use using-declarations instead.')
4651
4652 # Detect variable-length arrays.
4653 match = Match(r'\s*(.+::)?(\w+) [a-z]\w*\[(.+)];', line)
4654 if (match and match.group(2) != 'return' and match.group(2) != 'delete' and
4655 match.group(3).find(']') == -1):
4656 # Split the size using space and arithmetic operators as delimiters.
4657 # If any of the resulting tokens are not compile time constants then
4658 # report the error.
4659 tokens = re.split(r'\s|\+|\-|\*|\/|<<|>>]', match.group(3))
4660 is_const = True
4661 skip_next = False
4662 for tok in tokens:
4663 if skip_next:
4664 skip_next = False
4665 continue
4666
4667 if Search(r'sizeof\(.+\)', tok): continue
4668 if Search(r'arraysize\(\w+\)', tok): continue
Avi Drissman4157ba12019-01-09 14:18:07 +00004669 if Search(r'base::size\(.+\)', tok): continue
4670 if Search(r'std::size\(.+\)', tok): continue
4671 if Search(r'std::extent<.+>', tok): continue
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004672
4673 tok = tok.lstrip('(')
4674 tok = tok.rstrip(')')
4675 if not tok: continue
4676 if Match(r'\d+', tok): continue
4677 if Match(r'0[xX][0-9a-fA-F]+', tok): continue
4678 if Match(r'k[A-Z0-9]\w*', tok): continue
4679 if Match(r'(.+::)?k[A-Z0-9]\w*', tok): continue
4680 if Match(r'(.+::)?[A-Z][A-Z0-9_]*', tok): continue
4681 # A catch all for tricky sizeof cases, including 'sizeof expression',
4682 # 'sizeof(*type)', 'sizeof(const type)', 'sizeof(struct StructName)'
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004683 # requires skipping the next token because we split on ' ' and '*'.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004684 if tok.startswith('sizeof'):
4685 skip_next = True
4686 continue
4687 is_const = False
4688 break
4689 if not is_const:
4690 error(filename, linenum, 'runtime/arrays', 1,
4691 'Do not use variable-length arrays. Use an appropriately named '
4692 "('k' followed by CamelCase) compile-time constant for the size.")
4693
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004694 # Check for use of unnamed namespaces in header files. Registration
4695 # macros are typically OK, so we allow use of "namespace {" on lines
4696 # that end with backslashes.
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00004697 if (file_extension == 'h'
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004698 and Search(r'\bnamespace\s*{', line)
4699 and line[-1] != '\\'):
4700 error(filename, linenum, 'build/namespaces', 4,
4701 'Do not use unnamed namespaces in header files. See '
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00004702 'https://google.github.io/styleguide/cppguide.html#Namespaces'
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004703 ' for more information.')
4704
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004705
4706def CheckGlobalStatic(filename, clean_lines, linenum, error):
4707 """Check for unsafe global or static objects.
4708
4709 Args:
4710 filename: The name of the current file.
4711 clean_lines: A CleansedLines instance containing the file.
4712 linenum: The number of the line to check.
4713 error: The function to call with any errors found.
4714 """
4715 line = clean_lines.elided[linenum]
4716
avakulenko@google.com59146752014-08-11 20:20:55 +00004717 # Match two lines at a time to support multiline declarations
4718 if linenum + 1 < clean_lines.NumLines() and not Search(r'[;({]', line):
4719 line += clean_lines.elided[linenum + 1].strip()
4720
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004721 # Check for people declaring static/global STL strings at the top level.
4722 # This is dangerous because the C++ language does not guarantee that
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004723 # globals with constructors are initialized before the first access, and
4724 # also because globals can be destroyed when some threads are still running.
4725 # TODO(unknown): Generalize this to also find static unique_ptr instances.
4726 # TODO(unknown): File bugs for clang-tidy to find these.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004727 match = Match(
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004728 r'((?:|static +)(?:|const +))(?::*std::)?string( +const)? +'
4729 r'([a-zA-Z0-9_:]+)\b(.*)',
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004730 line)
avakulenko@google.com59146752014-08-11 20:20:55 +00004731
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004732 # Remove false positives:
4733 # - String pointers (as opposed to values).
4734 # string *pointer
4735 # const string *pointer
4736 # string const *pointer
4737 # string *const pointer
4738 #
4739 # - Functions and template specializations.
4740 # string Function<Type>(...
4741 # string Class<Type>::Method(...
4742 #
4743 # - Operators. These are matched separately because operator names
4744 # cross non-word boundaries, and trying to match both operators
4745 # and functions at the same time would decrease accuracy of
4746 # matching identifiers.
4747 # string Class::operator*()
4748 if (match and
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004749 not Search(r'\bstring\b(\s+const)?\s*[\*\&]\s*(const\s+)?\w', line) and
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004750 not Search(r'\boperator\W', line) and
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004751 not Match(r'\s*(<.*>)?(::[a-zA-Z0-9_]+)*\s*\(([^"]|$)', match.group(4))):
4752 if Search(r'\bconst\b', line):
4753 error(filename, linenum, 'runtime/string', 4,
4754 'For a static/global string constant, use a C style string '
4755 'instead: "%schar%s %s[]".' %
4756 (match.group(1), match.group(2) or '', match.group(3)))
4757 else:
4758 error(filename, linenum, 'runtime/string', 4,
4759 'Static/global string variables are not permitted.')
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004760
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004761 if (Search(r'\b([A-Za-z0-9_]*_)\(\1\)', line) or
4762 Search(r'\b([A-Za-z0-9_]*_)\(CHECK_NOTNULL\(\1\)\)', line)):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004763 error(filename, linenum, 'runtime/init', 4,
4764 'You seem to be initializing a member variable with itself.')
4765
4766
4767def CheckPrintf(filename, clean_lines, linenum, error):
4768 """Check for printf related issues.
4769
4770 Args:
4771 filename: The name of the current file.
4772 clean_lines: A CleansedLines instance containing the file.
4773 linenum: The number of the line to check.
4774 error: The function to call with any errors found.
4775 """
4776 line = clean_lines.elided[linenum]
4777
4778 # When snprintf is used, the second argument shouldn't be a literal.
4779 match = Search(r'snprintf\s*\(([^,]*),\s*([0-9]*)\s*,', line)
4780 if match and match.group(2) != '0':
4781 # If 2nd arg is zero, snprintf is used to calculate size.
4782 error(filename, linenum, 'runtime/printf', 3,
4783 'If you can, use sizeof(%s) instead of %s as the 2nd arg '
4784 'to snprintf.' % (match.group(1), match.group(2)))
4785
4786 # Check if some verboten C functions are being used.
avakulenko@google.com59146752014-08-11 20:20:55 +00004787 if Search(r'\bsprintf\s*\(', line):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004788 error(filename, linenum, 'runtime/printf', 5,
4789 'Never use sprintf. Use snprintf instead.')
avakulenko@google.com59146752014-08-11 20:20:55 +00004790 match = Search(r'\b(strcpy|strcat)\s*\(', line)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004791 if match:
4792 error(filename, linenum, 'runtime/printf', 4,
4793 'Almost always, snprintf is better than %s' % match.group(1))
4794
4795
4796def IsDerivedFunction(clean_lines, linenum):
4797 """Check if current line contains an inherited function.
4798
4799 Args:
4800 clean_lines: A CleansedLines instance containing the file.
4801 linenum: The number of the line to check.
4802 Returns:
4803 True if current line contains a function with "override"
4804 virt-specifier.
4805 """
avakulenko@google.com59146752014-08-11 20:20:55 +00004806 # Scan back a few lines for start of current function
Edward Lemur6d31ed52019-12-02 23:00:00 +00004807 for i in range(linenum, max(-1, linenum - 10), -1):
avakulenko@google.com59146752014-08-11 20:20:55 +00004808 match = Match(r'^([^()]*\w+)\(', clean_lines.elided[i])
4809 if match:
4810 # Look for "override" after the matching closing parenthesis
4811 line, _, closing_paren = CloseExpression(
4812 clean_lines, i, len(match.group(1)))
4813 return (closing_paren >= 0 and
4814 Search(r'\boverride\b', line[closing_paren:]))
4815 return False
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004816
4817
avakulenko@google.com255f2be2014-12-05 22:19:55 +00004818def IsOutOfLineMethodDefinition(clean_lines, linenum):
4819 """Check if current line contains an out-of-line method definition.
4820
4821 Args:
4822 clean_lines: A CleansedLines instance containing the file.
4823 linenum: The number of the line to check.
4824 Returns:
4825 True if current line contains an out-of-line method definition.
4826 """
4827 # Scan back a few lines for start of current function
Edward Lemur6d31ed52019-12-02 23:00:00 +00004828 for i in range(linenum, max(-1, linenum - 10), -1):
avakulenko@google.com255f2be2014-12-05 22:19:55 +00004829 if Match(r'^([^()]*\w+)\(', clean_lines.elided[i]):
4830 return Match(r'^[^()]*\w+::\w+\(', clean_lines.elided[i]) is not None
4831 return False
4832
4833
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004834def IsInitializerList(clean_lines, linenum):
4835 """Check if current line is inside constructor initializer list.
4836
4837 Args:
4838 clean_lines: A CleansedLines instance containing the file.
4839 linenum: The number of the line to check.
4840 Returns:
4841 True if current line appears to be inside constructor initializer
4842 list, False otherwise.
4843 """
Edward Lemur6d31ed52019-12-02 23:00:00 +00004844 for i in range(linenum, 1, -1):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004845 line = clean_lines.elided[i]
4846 if i == linenum:
4847 remove_function_body = Match(r'^(.*)\{\s*$', line)
4848 if remove_function_body:
4849 line = remove_function_body.group(1)
4850
4851 if Search(r'\s:\s*\w+[({]', line):
4852 # A lone colon tend to indicate the start of a constructor
4853 # initializer list. It could also be a ternary operator, which
4854 # also tend to appear in constructor initializer lists as
4855 # opposed to parameter lists.
4856 return True
4857 if Search(r'\}\s*,\s*$', line):
4858 # A closing brace followed by a comma is probably the end of a
4859 # brace-initialized member in constructor initializer list.
4860 return True
4861 if Search(r'[{};]\s*$', line):
4862 # Found one of the following:
4863 # - A closing brace or semicolon, probably the end of the previous
4864 # function.
4865 # - An opening brace, probably the start of current class or namespace.
4866 #
4867 # Current line is probably not inside an initializer list since
4868 # we saw one of those things without seeing the starting colon.
4869 return False
4870
4871 # Got to the beginning of the file without seeing the start of
4872 # constructor initializer list.
4873 return False
4874
4875
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004876def CheckForNonConstReference(filename, clean_lines, linenum,
4877 nesting_state, error):
4878 """Check for non-const references.
4879
4880 Separate from CheckLanguage since it scans backwards from current
4881 line, instead of scanning forward.
4882
4883 Args:
4884 filename: The name of the current file.
4885 clean_lines: A CleansedLines instance containing the file.
4886 linenum: The number of the line to check.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004887 nesting_state: A NestingState instance which maintains information about
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004888 the current stack of nested blocks being parsed.
4889 error: The function to call with any errors found.
4890 """
4891 # Do nothing if there is no '&' on current line.
4892 line = clean_lines.elided[linenum]
4893 if '&' not in line:
4894 return
4895
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004896 # If a function is inherited, current function doesn't have much of
4897 # a choice, so any non-const references should not be blamed on
4898 # derived function.
4899 if IsDerivedFunction(clean_lines, linenum):
4900 return
4901
avakulenko@google.com255f2be2014-12-05 22:19:55 +00004902 # Don't warn on out-of-line method definitions, as we would warn on the
4903 # in-line declaration, if it isn't marked with 'override'.
4904 if IsOutOfLineMethodDefinition(clean_lines, linenum):
4905 return
4906
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004907 # Long type names may be broken across multiple lines, usually in one
4908 # of these forms:
4909 # LongType
4910 # ::LongTypeContinued &identifier
4911 # LongType::
4912 # LongTypeContinued &identifier
4913 # LongType<
4914 # ...>::LongTypeContinued &identifier
4915 #
4916 # If we detected a type split across two lines, join the previous
4917 # line to current line so that we can match const references
4918 # accordingly.
4919 #
4920 # Note that this only scans back one line, since scanning back
4921 # arbitrary number of lines would be expensive. If you have a type
4922 # that spans more than 2 lines, please use a typedef.
4923 if linenum > 1:
4924 previous = None
4925 if Match(r'\s*::(?:[\w<>]|::)+\s*&\s*\S', line):
4926 # previous_line\n + ::current_line
4927 previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+[\w<>])\s*$',
4928 clean_lines.elided[linenum - 1])
4929 elif Match(r'\s*[a-zA-Z_]([\w<>]|::)+\s*&\s*\S', line):
4930 # previous_line::\n + current_line
4931 previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+::)\s*$',
4932 clean_lines.elided[linenum - 1])
4933 if previous:
4934 line = previous.group(1) + line.lstrip()
4935 else:
4936 # Check for templated parameter that is split across multiple lines
4937 endpos = line.rfind('>')
4938 if endpos > -1:
4939 (_, startline, startpos) = ReverseCloseExpression(
4940 clean_lines, linenum, endpos)
4941 if startpos > -1 and startline < linenum:
4942 # Found the matching < on an earlier line, collect all
4943 # pieces up to current line.
4944 line = ''
Edward Lemur6d31ed52019-12-02 23:00:00 +00004945 for i in range(startline, linenum + 1):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004946 line += clean_lines.elided[i].strip()
4947
4948 # Check for non-const references in function parameters. A single '&' may
4949 # found in the following places:
4950 # inside expression: binary & for bitwise AND
4951 # inside expression: unary & for taking the address of something
4952 # inside declarators: reference parameter
4953 # We will exclude the first two cases by checking that we are not inside a
4954 # function body, including one that was just introduced by a trailing '{'.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004955 # TODO(unknown): Doesn't account for 'catch(Exception& e)' [rare].
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004956 if (nesting_state.previous_stack_top and
4957 not (isinstance(nesting_state.previous_stack_top, _ClassInfo) or
4958 isinstance(nesting_state.previous_stack_top, _NamespaceInfo))):
4959 # Not at toplevel, not within a class, and not within a namespace
4960 return
4961
avakulenko@google.com59146752014-08-11 20:20:55 +00004962 # Avoid initializer lists. We only need to scan back from the
4963 # current line for something that starts with ':'.
4964 #
4965 # We don't need to check the current line, since the '&' would
4966 # appear inside the second set of parentheses on the current line as
4967 # opposed to the first set.
4968 if linenum > 0:
Edward Lemur6d31ed52019-12-02 23:00:00 +00004969 for i in range(linenum - 1, max(0, linenum - 10), -1):
avakulenko@google.com59146752014-08-11 20:20:55 +00004970 previous_line = clean_lines.elided[i]
4971 if not Search(r'[),]\s*$', previous_line):
4972 break
4973 if Match(r'^\s*:\s+\S', previous_line):
4974 return
4975
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004976 # Avoid preprocessors
4977 if Search(r'\\\s*$', line):
4978 return
4979
4980 # Avoid constructor initializer lists
4981 if IsInitializerList(clean_lines, linenum):
4982 return
4983
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004984 # We allow non-const references in a few standard places, like functions
4985 # called "swap()" or iostream operators like "<<" or ">>". Do not check
4986 # those function parameters.
4987 #
4988 # We also accept & in static_assert, which looks like a function but
4989 # it's actually a declaration expression.
4990 whitelisted_functions = (r'(?:[sS]wap(?:<\w:+>)?|'
4991 r'operator\s*[<>][<>]|'
4992 r'static_assert|COMPILE_ASSERT'
4993 r')\s*\(')
4994 if Search(whitelisted_functions, line):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004995 return
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004996 elif not Search(r'\S+\([^)]*$', line):
4997 # Don't see a whitelisted function on this line. Actually we
4998 # didn't see any function name on this line, so this is likely a
4999 # multi-line parameter list. Try a bit harder to catch this case.
Edward Lemur6d31ed52019-12-02 23:00:00 +00005000 for i in range(2):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005001 if (linenum > i and
5002 Search(whitelisted_functions, clean_lines.elided[linenum - i - 1])):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005003 return
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005004
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005005 decls = ReplaceAll(r'{[^}]*}', ' ', line) # exclude function body
5006 for parameter in re.findall(_RE_PATTERN_REF_PARAM, decls):
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005007 if (not Match(_RE_PATTERN_CONST_REF_PARAM, parameter) and
5008 not Match(_RE_PATTERN_REF_STREAM_PARAM, parameter)):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005009 error(filename, linenum, 'runtime/references', 2,
5010 'Is this a non-const reference? '
5011 'If so, make const or use a pointer: ' +
5012 ReplaceAll(' *<', '<', parameter))
5013
5014
5015def CheckCasts(filename, clean_lines, linenum, error):
5016 """Various cast related checks.
5017
5018 Args:
5019 filename: The name of the current file.
5020 clean_lines: A CleansedLines instance containing the file.
5021 linenum: The number of the line to check.
5022 error: The function to call with any errors found.
5023 """
5024 line = clean_lines.elided[linenum]
5025
5026 # Check to see if they're using an conversion function cast.
5027 # I just try to capture the most common basic types, though there are more.
5028 # Parameterless conversion functions, such as bool(), are allowed as they are
5029 # probably a member operator declaration or default constructor.
5030 match = Search(
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005031 r'(\bnew\s+(?:const\s+)?|\S<\s*(?:const\s+)?)?\b'
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005032 r'(int|float|double|bool|char|int32|uint32|int64|uint64)'
5033 r'(\([^)].*)', line)
5034 expecting_function = ExpectingFunctionArgs(clean_lines, linenum)
5035 if match and not expecting_function:
5036 matched_type = match.group(2)
5037
5038 # matched_new_or_template is used to silence two false positives:
5039 # - New operators
5040 # - Template arguments with function types
5041 #
5042 # For template arguments, we match on types immediately following
5043 # an opening bracket without any spaces. This is a fast way to
5044 # silence the common case where the function type is the first
5045 # template argument. False negative with less-than comparison is
5046 # avoided because those operators are usually followed by a space.
5047 #
5048 # function<double(double)> // bracket + no space = false positive
5049 # value < double(42) // bracket + space = true positive
5050 matched_new_or_template = match.group(1)
5051
avakulenko@google.com59146752014-08-11 20:20:55 +00005052 # Avoid arrays by looking for brackets that come after the closing
5053 # parenthesis.
5054 if Match(r'\([^()]+\)\s*\[', match.group(3)):
5055 return
5056
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005057 # Other things to ignore:
5058 # - Function pointers
5059 # - Casts to pointer types
5060 # - Placement new
5061 # - Alias declarations
5062 matched_funcptr = match.group(3)
5063 if (matched_new_or_template is None and
5064 not (matched_funcptr and
5065 (Match(r'\((?:[^() ]+::\s*\*\s*)?[^() ]+\)\s*\(',
5066 matched_funcptr) or
5067 matched_funcptr.startswith('(*)'))) and
5068 not Match(r'\s*using\s+\S+\s*=\s*' + matched_type, line) and
5069 not Search(r'new\(\S+\)\s*' + matched_type, line)):
5070 error(filename, linenum, 'readability/casting', 4,
5071 'Using deprecated casting style. '
5072 'Use static_cast<%s>(...) instead' %
5073 matched_type)
5074
5075 if not expecting_function:
avakulenko@google.com59146752014-08-11 20:20:55 +00005076 CheckCStyleCast(filename, clean_lines, linenum, 'static_cast',
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005077 r'\((int|float|double|bool|char|u?int(16|32|64))\)', error)
5078
5079 # This doesn't catch all cases. Consider (const char * const)"hello".
5080 #
5081 # (char *) "foo" should always be a const_cast (reinterpret_cast won't
5082 # compile).
avakulenko@google.com59146752014-08-11 20:20:55 +00005083 if CheckCStyleCast(filename, clean_lines, linenum, 'const_cast',
5084 r'\((char\s?\*+\s?)\)\s*"', error):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005085 pass
5086 else:
5087 # Check pointer casts for other than string constants
avakulenko@google.com59146752014-08-11 20:20:55 +00005088 CheckCStyleCast(filename, clean_lines, linenum, 'reinterpret_cast',
5089 r'\((\w+\s?\*+\s?)\)', error)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005090
5091 # In addition, we look for people taking the address of a cast. This
5092 # is dangerous -- casts can assign to temporaries, so the pointer doesn't
5093 # point where you think.
avakulenko@google.com59146752014-08-11 20:20:55 +00005094 #
5095 # Some non-identifier character is required before the '&' for the
5096 # expression to be recognized as a cast. These are casts:
5097 # expression = &static_cast<int*>(temporary());
5098 # function(&(int*)(temporary()));
5099 #
5100 # This is not a cast:
5101 # reference_type&(int* function_param);
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005102 match = Search(
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005103 r'(?:[^\w]&\(([^)*][^)]*)\)[\w(])|'
avakulenko@google.com59146752014-08-11 20:20:55 +00005104 r'(?:[^\w]&(static|dynamic|down|reinterpret)_cast\b)', line)
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005105 if match:
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005106 # Try a better error message when the & is bound to something
5107 # dereferenced by the casted pointer, as opposed to the casted
5108 # pointer itself.
5109 parenthesis_error = False
5110 match = Match(r'^(.*&(?:static|dynamic|down|reinterpret)_cast\b)<', line)
5111 if match:
5112 _, y1, x1 = CloseExpression(clean_lines, linenum, len(match.group(1)))
5113 if x1 >= 0 and clean_lines.elided[y1][x1] == '(':
5114 _, y2, x2 = CloseExpression(clean_lines, y1, x1)
5115 if x2 >= 0:
5116 extended_line = clean_lines.elided[y2][x2:]
5117 if y2 < clean_lines.NumLines() - 1:
5118 extended_line += clean_lines.elided[y2 + 1]
5119 if Match(r'\s*(?:->|\[)', extended_line):
5120 parenthesis_error = True
5121
5122 if parenthesis_error:
5123 error(filename, linenum, 'readability/casting', 4,
5124 ('Are you taking an address of something dereferenced '
5125 'from a cast? Wrapping the dereferenced expression in '
5126 'parentheses will make the binding more obvious'))
5127 else:
5128 error(filename, linenum, 'runtime/casting', 4,
5129 ('Are you taking an address of a cast? '
5130 'This is dangerous: could be a temp var. '
5131 'Take the address before doing the cast, rather than after'))
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005132
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005133
avakulenko@google.com59146752014-08-11 20:20:55 +00005134def CheckCStyleCast(filename, clean_lines, linenum, cast_type, pattern, error):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005135 """Checks for a C-style cast by looking for the pattern.
5136
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005137 Args:
5138 filename: The name of the current file.
avakulenko@google.com59146752014-08-11 20:20:55 +00005139 clean_lines: A CleansedLines instance containing the file.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005140 linenum: The number of the line to check.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005141 cast_type: The string for the C++ cast to recommend. This is either
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005142 reinterpret_cast, static_cast, or const_cast, depending.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005143 pattern: The regular expression used to find C-style casts.
5144 error: The function to call with any errors found.
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005145
5146 Returns:
5147 True if an error was emitted.
5148 False otherwise.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005149 """
avakulenko@google.com59146752014-08-11 20:20:55 +00005150 line = clean_lines.elided[linenum]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005151 match = Search(pattern, line)
5152 if not match:
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005153 return False
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005154
avakulenko@google.com59146752014-08-11 20:20:55 +00005155 # Exclude lines with keywords that tend to look like casts
5156 context = line[0:match.start(1) - 1]
5157 if Match(r'.*\b(?:sizeof|alignof|alignas|[_A-Z][_A-Z0-9]*)\s*$', context):
5158 return False
5159
5160 # Try expanding current context to see if we one level of
5161 # parentheses inside a macro.
5162 if linenum > 0:
Edward Lemur6d31ed52019-12-02 23:00:00 +00005163 for i in range(linenum - 1, max(0, linenum - 5), -1):
avakulenko@google.com59146752014-08-11 20:20:55 +00005164 context = clean_lines.elided[i] + context
5165 if Match(r'.*\b[_A-Z][_A-Z0-9]*\s*\((?:\([^()]*\)|[^()])*$', context):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005166 return False
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005167
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005168 # operator++(int) and operator--(int)
avakulenko@google.com59146752014-08-11 20:20:55 +00005169 if context.endswith(' operator++') or context.endswith(' operator--'):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005170 return False
5171
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005172 # A single unnamed argument for a function tends to look like old style cast.
5173 # If we see those, don't issue warnings for deprecated casts.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005174 remainder = line[match.end(0):]
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005175 if Match(r'^\s*(?:;|const\b|throw\b|final\b|override\b|[=>{),]|->)',
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005176 remainder):
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005177 return False
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005178
5179 # At this point, all that should be left is actual casts.
5180 error(filename, linenum, 'readability/casting', 4,
5181 'Using C-style cast. Use %s<%s>(...) instead' %
5182 (cast_type, match.group(1)))
5183
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005184 return True
5185
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005186
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005187def ExpectingFunctionArgs(clean_lines, linenum):
5188 """Checks whether where function type arguments are expected.
5189
5190 Args:
5191 clean_lines: A CleansedLines instance containing the file.
5192 linenum: The number of the line to check.
5193
5194 Returns:
5195 True if the line at 'linenum' is inside something that expects arguments
5196 of function types.
5197 """
5198 line = clean_lines.elided[linenum]
5199 return (Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line) or
5200 (linenum >= 2 and
5201 (Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\((?:\S+,)?\s*$',
5202 clean_lines.elided[linenum - 1]) or
5203 Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\(\s*$',
5204 clean_lines.elided[linenum - 2]) or
5205 Search(r'\bstd::m?function\s*\<\s*$',
5206 clean_lines.elided[linenum - 1]))))
5207
5208
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005209_HEADERS_CONTAINING_TEMPLATES = (
5210 ('<deque>', ('deque',)),
5211 ('<functional>', ('unary_function', 'binary_function',
5212 'plus', 'minus', 'multiplies', 'divides', 'modulus',
5213 'negate',
5214 'equal_to', 'not_equal_to', 'greater', 'less',
5215 'greater_equal', 'less_equal',
5216 'logical_and', 'logical_or', 'logical_not',
5217 'unary_negate', 'not1', 'binary_negate', 'not2',
5218 'bind1st', 'bind2nd',
5219 'pointer_to_unary_function',
5220 'pointer_to_binary_function',
5221 'ptr_fun',
5222 'mem_fun_t', 'mem_fun', 'mem_fun1_t', 'mem_fun1_ref_t',
5223 'mem_fun_ref_t',
5224 'const_mem_fun_t', 'const_mem_fun1_t',
5225 'const_mem_fun_ref_t', 'const_mem_fun1_ref_t',
5226 'mem_fun_ref',
5227 )),
5228 ('<limits>', ('numeric_limits',)),
5229 ('<list>', ('list',)),
5230 ('<map>', ('map', 'multimap',)),
lhchavez2d1b6da2016-07-13 10:40:01 -07005231 ('<memory>', ('allocator', 'make_shared', 'make_unique', 'shared_ptr',
5232 'unique_ptr', 'weak_ptr')),
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005233 ('<queue>', ('queue', 'priority_queue',)),
5234 ('<set>', ('set', 'multiset',)),
5235 ('<stack>', ('stack',)),
5236 ('<string>', ('char_traits', 'basic_string',)),
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005237 ('<tuple>', ('tuple',)),
lhchavez2d1b6da2016-07-13 10:40:01 -07005238 ('<unordered_map>', ('unordered_map', 'unordered_multimap')),
5239 ('<unordered_set>', ('unordered_set', 'unordered_multiset')),
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005240 ('<utility>', ('pair',)),
5241 ('<vector>', ('vector',)),
5242
5243 # gcc extensions.
5244 # Note: std::hash is their hash, ::hash is our hash
5245 ('<hash_map>', ('hash_map', 'hash_multimap',)),
5246 ('<hash_set>', ('hash_set', 'hash_multiset',)),
5247 ('<slist>', ('slist',)),
5248 )
5249
skym@chromium.org3990c412016-02-05 20:55:12 +00005250_HEADERS_MAYBE_TEMPLATES = (
5251 ('<algorithm>', ('copy', 'max', 'min', 'min_element', 'sort',
5252 'transform',
5253 )),
lhchavez2d1b6da2016-07-13 10:40:01 -07005254 ('<utility>', ('forward', 'make_pair', 'move', 'swap')),
skym@chromium.org3990c412016-02-05 20:55:12 +00005255 )
5256
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005257_RE_PATTERN_STRING = re.compile(r'\bstring\b')
5258
skym@chromium.org3990c412016-02-05 20:55:12 +00005259_re_pattern_headers_maybe_templates = []
5260for _header, _templates in _HEADERS_MAYBE_TEMPLATES:
5261 for _template in _templates:
5262 # Match max<type>(..., ...), max(..., ...), but not foo->max, foo.max or
5263 # type::max().
5264 _re_pattern_headers_maybe_templates.append(
5265 (re.compile(r'[^>.]\b' + _template + r'(<.*?>)?\([^\)]'),
5266 _template,
5267 _header))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005268
skym@chromium.org3990c412016-02-05 20:55:12 +00005269# Other scripts may reach in and modify this pattern.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005270_re_pattern_templates = []
5271for _header, _templates in _HEADERS_CONTAINING_TEMPLATES:
5272 for _template in _templates:
5273 _re_pattern_templates.append(
5274 (re.compile(r'(\<|\b)' + _template + r'\s*\<'),
5275 _template + '<>',
5276 _header))
5277
5278
erg@google.com6317a9c2009-06-25 00:28:19 +00005279def FilesBelongToSameModule(filename_cc, filename_h):
5280 """Check if these two filenames belong to the same module.
5281
5282 The concept of a 'module' here is a as follows:
5283 foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the
5284 same 'module' if they are in the same directory.
5285 some/path/public/xyzzy and some/path/internal/xyzzy are also considered
5286 to belong to the same module here.
5287
5288 If the filename_cc contains a longer path than the filename_h, for example,
5289 '/absolute/path/to/base/sysinfo.cc', and this file would include
5290 'base/sysinfo.h', this function also produces the prefix needed to open the
5291 header. This is used by the caller of this function to more robustly open the
5292 header file. We don't have access to the real include paths in this context,
5293 so we need this guesswork here.
5294
5295 Known bugs: tools/base/bar.cc and base/bar.h belong to the same module
5296 according to this implementation. Because of this, this function gives
5297 some false positives. This should be sufficiently rare in practice.
5298
5299 Args:
5300 filename_cc: is the path for the .cc file
5301 filename_h: is the path for the header path
5302
5303 Returns:
5304 Tuple with a bool and a string:
5305 bool: True if filename_cc and filename_h belong to the same module.
5306 string: the additional prefix needed to open the header file.
5307 """
5308
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005309 fileinfo = FileInfo(filename_cc)
5310 if not fileinfo.IsSource():
erg@google.com6317a9c2009-06-25 00:28:19 +00005311 return (False, '')
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005312 filename_cc = filename_cc[:-len(fileinfo.Extension())]
5313 matched_test_suffix = Search(_TEST_FILE_SUFFIX, fileinfo.BaseName())
5314 if matched_test_suffix:
5315 filename_cc = filename_cc[:-len(matched_test_suffix.group(1))]
erg@google.com6317a9c2009-06-25 00:28:19 +00005316 filename_cc = filename_cc.replace('/public/', '/')
5317 filename_cc = filename_cc.replace('/internal/', '/')
5318
5319 if not filename_h.endswith('.h'):
5320 return (False, '')
5321 filename_h = filename_h[:-len('.h')]
5322 if filename_h.endswith('-inl'):
5323 filename_h = filename_h[:-len('-inl')]
5324 filename_h = filename_h.replace('/public/', '/')
5325 filename_h = filename_h.replace('/internal/', '/')
5326
5327 files_belong_to_same_module = filename_cc.endswith(filename_h)
5328 common_path = ''
5329 if files_belong_to_same_module:
5330 common_path = filename_cc[:-len(filename_h)]
5331 return files_belong_to_same_module, common_path
5332
5333
avakulenko@google.com59146752014-08-11 20:20:55 +00005334def UpdateIncludeState(filename, include_dict, io=codecs):
5335 """Fill up the include_dict with new includes found from the file.
erg@google.com6317a9c2009-06-25 00:28:19 +00005336
5337 Args:
5338 filename: the name of the header to read.
avakulenko@google.com59146752014-08-11 20:20:55 +00005339 include_dict: a dictionary in which the headers are inserted.
erg@google.com6317a9c2009-06-25 00:28:19 +00005340 io: The io factory to use to read the file. Provided for testability.
5341
5342 Returns:
avakulenko@google.com59146752014-08-11 20:20:55 +00005343 True if a header was successfully added. False otherwise.
erg@google.com6317a9c2009-06-25 00:28:19 +00005344 """
5345 headerfile = None
5346 try:
5347 headerfile = io.open(filename, 'r', 'utf8', 'replace')
5348 except IOError:
5349 return False
5350 linenum = 0
5351 for line in headerfile:
5352 linenum += 1
5353 clean_line = CleanseComments(line)
5354 match = _RE_PATTERN_INCLUDE.search(clean_line)
5355 if match:
5356 include = match.group(2)
avakulenko@google.com59146752014-08-11 20:20:55 +00005357 include_dict.setdefault(include, linenum)
erg@google.com6317a9c2009-06-25 00:28:19 +00005358 return True
5359
5360
5361def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error,
5362 io=codecs):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005363 """Reports for missing stl includes.
5364
5365 This function will output warnings to make sure you are including the headers
5366 necessary for the stl containers and functions that you use. We only give one
5367 reason to include a header. For example, if you use both equal_to<> and
5368 less<> in a .h file, only one (the latter in the file) of these will be
5369 reported as a reason to include the <functional>.
5370
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005371 Args:
5372 filename: The name of the current file.
5373 clean_lines: A CleansedLines instance containing the file.
5374 include_state: An _IncludeState instance.
5375 error: The function to call with any errors found.
erg@google.com6317a9c2009-06-25 00:28:19 +00005376 io: The IO factory to use to read the header file. Provided for unittest
5377 injection.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005378 """
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005379 required = {} # A map of header name to linenumber and the template entity.
5380 # Example of required: { '<functional>': (1219, 'less<>') }
5381
Edward Lemur6d31ed52019-12-02 23:00:00 +00005382 for linenum in range(clean_lines.NumLines()):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005383 line = clean_lines.elided[linenum]
5384 if not line or line[0] == '#':
5385 continue
5386
5387 # String is special -- it is a non-templatized type in STL.
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005388 matched = _RE_PATTERN_STRING.search(line)
5389 if matched:
erg@google.com35589e62010-11-17 18:58:16 +00005390 # Don't warn about strings in non-STL namespaces:
5391 # (We check only the first match per line; good enough.)
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005392 prefix = line[:matched.start()]
erg@google.com35589e62010-11-17 18:58:16 +00005393 if prefix.endswith('std::') or not prefix.endswith('::'):
5394 required['<string>'] = (linenum, 'string')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005395
skym@chromium.org3990c412016-02-05 20:55:12 +00005396 for pattern, template, header in _re_pattern_headers_maybe_templates:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005397 if pattern.search(line):
5398 required[header] = (linenum, template)
5399
5400 # The following function is just a speed up, no semantics are changed.
5401 if not '<' in line: # Reduces the cpu time usage by skipping lines.
5402 continue
5403
5404 for pattern, template, header in _re_pattern_templates:
lhchavez9b2173c2016-07-13 10:20:07 -07005405 matched = pattern.search(line)
5406 if matched:
5407 # Don't warn about IWYU in non-STL namespaces:
5408 # (We check only the first match per line; good enough.)
5409 prefix = line[:matched.start()]
5410 if prefix.endswith('std::') or not prefix.endswith('::'):
5411 required[header] = (linenum, template)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005412
erg@google.com6317a9c2009-06-25 00:28:19 +00005413 # The policy is that if you #include something in foo.h you don't need to
5414 # include it again in foo.cc. Here, we will look at possible includes.
avakulenko@google.com59146752014-08-11 20:20:55 +00005415 # Let's flatten the include_state include_list and copy it into a dictionary.
5416 include_dict = dict([item for sublist in include_state.include_list
5417 for item in sublist])
erg@google.com6317a9c2009-06-25 00:28:19 +00005418
avakulenko@google.com59146752014-08-11 20:20:55 +00005419 # Did we find the header for this file (if any) and successfully load it?
erg@google.com6317a9c2009-06-25 00:28:19 +00005420 header_found = False
5421
5422 # Use the absolute path so that matching works properly.
erg@chromium.org8f927562012-01-30 19:51:28 +00005423 abs_filename = FileInfo(filename).FullName()
erg@google.com6317a9c2009-06-25 00:28:19 +00005424
5425 # For Emacs's flymake.
5426 # If cpplint is invoked from Emacs's flymake, a temporary file is generated
5427 # by flymake and that file name might end with '_flymake.cc'. In that case,
5428 # restore original file name here so that the corresponding header file can be
5429 # found.
5430 # e.g. If the file name is 'foo_flymake.cc', we should search for 'foo.h'
5431 # instead of 'foo_flymake.h'
erg@google.com35589e62010-11-17 18:58:16 +00005432 abs_filename = re.sub(r'_flymake\.cc$', '.cc', abs_filename)
erg@google.com6317a9c2009-06-25 00:28:19 +00005433
avakulenko@google.com59146752014-08-11 20:20:55 +00005434 # include_dict is modified during iteration, so we iterate over a copy of
erg@google.com6317a9c2009-06-25 00:28:19 +00005435 # the keys.
Sarthak Kukreti60378202019-12-17 20:46:58 +00005436 header_keys = list(include_dict.keys())
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005437 for header in header_keys:
erg@google.com6317a9c2009-06-25 00:28:19 +00005438 (same_module, common_path) = FilesBelongToSameModule(abs_filename, header)
5439 fullpath = common_path + header
avakulenko@google.com59146752014-08-11 20:20:55 +00005440 if same_module and UpdateIncludeState(fullpath, include_dict, io):
erg@google.com6317a9c2009-06-25 00:28:19 +00005441 header_found = True
5442
5443 # If we can't find the header file for a .cc, assume it's because we don't
5444 # know where to look. In that case we'll give up as we're not sure they
5445 # didn't include it in the .h file.
5446 # TODO(unknown): Do a better job of finding .h files so we are confident that
5447 # not having the .h file means there isn't one.
5448 if filename.endswith('.cc') and not header_found:
5449 return
5450
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005451 # All the lines have been processed, report the errors found.
5452 for required_header_unstripped in required:
5453 template = required[required_header_unstripped][1]
avakulenko@google.com59146752014-08-11 20:20:55 +00005454 if required_header_unstripped.strip('<>"') not in include_dict:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005455 error(filename, required[required_header_unstripped][0],
5456 'build/include_what_you_use', 4,
5457 'Add #include ' + required_header_unstripped + ' for ' + template)
5458
5459
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005460_RE_PATTERN_EXPLICIT_MAKEPAIR = re.compile(r'\bmake_pair\s*<')
5461
5462
5463def CheckMakePairUsesDeduction(filename, clean_lines, linenum, error):
5464 """Check that make_pair's template arguments are deduced.
5465
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005466 G++ 4.6 in C++11 mode fails badly if make_pair's template arguments are
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005467 specified explicitly, and such use isn't intended in any case.
5468
5469 Args:
5470 filename: The name of the current file.
5471 clean_lines: A CleansedLines instance containing the file.
5472 linenum: The number of the line to check.
5473 error: The function to call with any errors found.
5474 """
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005475 line = clean_lines.elided[linenum]
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005476 match = _RE_PATTERN_EXPLICIT_MAKEPAIR.search(line)
5477 if match:
5478 error(filename, linenum, 'build/explicit_make_pair',
5479 4, # 4 = high confidence
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005480 'For C++11-compatibility, omit template arguments from make_pair'
5481 ' OR use pair directly OR if appropriate, construct a pair directly')
avakulenko@google.com59146752014-08-11 20:20:55 +00005482
5483
avakulenko@google.com59146752014-08-11 20:20:55 +00005484def CheckRedundantVirtual(filename, clean_lines, linenum, error):
5485 """Check if line contains a redundant "virtual" function-specifier.
5486
5487 Args:
5488 filename: The name of the current file.
5489 clean_lines: A CleansedLines instance containing the file.
5490 linenum: The number of the line to check.
5491 error: The function to call with any errors found.
5492 """
5493 # Look for "virtual" on current line.
5494 line = clean_lines.elided[linenum]
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005495 virtual = Match(r'^(.*)(\bvirtual\b)(.*)$', line)
avakulenko@google.com59146752014-08-11 20:20:55 +00005496 if not virtual: return
5497
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005498 # Ignore "virtual" keywords that are near access-specifiers. These
5499 # are only used in class base-specifier and do not apply to member
5500 # functions.
5501 if (Search(r'\b(public|protected|private)\s+$', virtual.group(1)) or
5502 Match(r'^\s+(public|protected|private)\b', virtual.group(3))):
5503 return
5504
5505 # Ignore the "virtual" keyword from virtual base classes. Usually
5506 # there is a column on the same line in these cases (virtual base
5507 # classes are rare in google3 because multiple inheritance is rare).
5508 if Match(r'^.*[^:]:[^:].*$', line): return
5509
avakulenko@google.com59146752014-08-11 20:20:55 +00005510 # Look for the next opening parenthesis. This is the start of the
5511 # parameter list (possibly on the next line shortly after virtual).
5512 # TODO(unknown): doesn't work if there are virtual functions with
5513 # decltype() or other things that use parentheses, but csearch suggests
5514 # that this is rare.
5515 end_col = -1
5516 end_line = -1
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005517 start_col = len(virtual.group(2))
Edward Lemur6d31ed52019-12-02 23:00:00 +00005518 for start_line in range(linenum, min(linenum + 3, clean_lines.NumLines())):
avakulenko@google.com59146752014-08-11 20:20:55 +00005519 line = clean_lines.elided[start_line][start_col:]
5520 parameter_list = Match(r'^([^(]*)\(', line)
5521 if parameter_list:
5522 # Match parentheses to find the end of the parameter list
5523 (_, end_line, end_col) = CloseExpression(
5524 clean_lines, start_line, start_col + len(parameter_list.group(1)))
5525 break
5526 start_col = 0
5527
5528 if end_col < 0:
5529 return # Couldn't find end of parameter list, give up
5530
5531 # Look for "override" or "final" after the parameter list
5532 # (possibly on the next few lines).
Edward Lemur6d31ed52019-12-02 23:00:00 +00005533 for i in range(end_line, min(end_line + 3, clean_lines.NumLines())):
avakulenko@google.com59146752014-08-11 20:20:55 +00005534 line = clean_lines.elided[i][end_col:]
5535 match = Search(r'\b(override|final)\b', line)
5536 if match:
5537 error(filename, linenum, 'readability/inheritance', 4,
5538 ('"virtual" is redundant since function is '
5539 'already declared as "%s"' % match.group(1)))
5540
5541 # Set end_col to check whole lines after we are done with the
5542 # first line.
5543 end_col = 0
5544 if Search(r'[^\w]\s*$', line):
5545 break
5546
5547
5548def CheckRedundantOverrideOrFinal(filename, clean_lines, linenum, error):
5549 """Check if line contains a redundant "override" or "final" virt-specifier.
5550
5551 Args:
5552 filename: The name of the current file.
5553 clean_lines: A CleansedLines instance containing the file.
5554 linenum: The number of the line to check.
5555 error: The function to call with any errors found.
5556 """
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005557 # Look for closing parenthesis nearby. We need one to confirm where
5558 # the declarator ends and where the virt-specifier starts to avoid
5559 # false positives.
avakulenko@google.com59146752014-08-11 20:20:55 +00005560 line = clean_lines.elided[linenum]
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005561 declarator_end = line.rfind(')')
5562 if declarator_end >= 0:
5563 fragment = line[declarator_end:]
5564 else:
5565 if linenum > 1 and clean_lines.elided[linenum - 1].rfind(')') >= 0:
5566 fragment = line
5567 else:
5568 return
5569
5570 # Check that at most one of "override" or "final" is present, not both
5571 if Search(r'\boverride\b', fragment) and Search(r'\bfinal\b', fragment):
avakulenko@google.com59146752014-08-11 20:20:55 +00005572 error(filename, linenum, 'readability/inheritance', 4,
5573 ('"override" is redundant since function is '
5574 'already declared as "final"'))
5575
5576
5577
5578
5579# Returns true if we are at a new block, and it is directly
5580# inside of a namespace.
5581def IsBlockInNameSpace(nesting_state, is_forward_declaration):
5582 """Checks that the new block is directly in a namespace.
5583
5584 Args:
5585 nesting_state: The _NestingState object that contains info about our state.
5586 is_forward_declaration: If the class is a forward declared class.
5587 Returns:
5588 Whether or not the new block is directly in a namespace.
5589 """
5590 if is_forward_declaration:
5591 if len(nesting_state.stack) >= 1 and (
5592 isinstance(nesting_state.stack[-1], _NamespaceInfo)):
5593 return True
5594 else:
5595 return False
5596
5597 return (len(nesting_state.stack) > 1 and
5598 nesting_state.stack[-1].check_namespace_indentation and
5599 isinstance(nesting_state.stack[-2], _NamespaceInfo))
5600
5601
5602def ShouldCheckNamespaceIndentation(nesting_state, is_namespace_indent_item,
5603 raw_lines_no_comments, linenum):
5604 """This method determines if we should apply our namespace indentation check.
5605
5606 Args:
5607 nesting_state: The current nesting state.
5608 is_namespace_indent_item: If we just put a new class on the stack, True.
5609 If the top of the stack is not a class, or we did not recently
5610 add the class, False.
5611 raw_lines_no_comments: The lines without the comments.
5612 linenum: The current line number we are processing.
5613
5614 Returns:
5615 True if we should apply our namespace indentation check. Currently, it
5616 only works for classes and namespaces inside of a namespace.
5617 """
5618
5619 is_forward_declaration = IsForwardClassDeclaration(raw_lines_no_comments,
5620 linenum)
5621
5622 if not (is_namespace_indent_item or is_forward_declaration):
5623 return False
5624
5625 # If we are in a macro, we do not want to check the namespace indentation.
5626 if IsMacroDefinition(raw_lines_no_comments, linenum):
5627 return False
5628
5629 return IsBlockInNameSpace(nesting_state, is_forward_declaration)
5630
5631
5632# Call this method if the line is directly inside of a namespace.
5633# If the line above is blank (excluding comments) or the start of
5634# an inner namespace, it cannot be indented.
5635def CheckItemIndentationInNamespace(filename, raw_lines_no_comments, linenum,
5636 error):
5637 line = raw_lines_no_comments[linenum]
5638 if Match(r'^\s+', line):
5639 error(filename, linenum, 'runtime/indentation_namespace', 4,
5640 'Do not indent within a namespace')
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005641
5642
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005643def ProcessLine(filename, file_extension, clean_lines, line,
5644 include_state, function_state, nesting_state, error,
5645 extra_check_functions=[]):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005646 """Processes a single line in the file.
5647
5648 Args:
5649 filename: Filename of the file that is being processed.
5650 file_extension: The extension (dot not included) of the file.
5651 clean_lines: An array of strings, each representing a line of the file,
5652 with comments stripped.
5653 line: Number of line being processed.
5654 include_state: An _IncludeState instance in which the headers are inserted.
5655 function_state: A _FunctionState instance which counts function lines, etc.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005656 nesting_state: A NestingState instance which maintains information about
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005657 the current stack of nested blocks being parsed.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005658 error: A callable to which errors are reported, which takes 4 arguments:
5659 filename, line number, error level, and message
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005660 extra_check_functions: An array of additional check functions that will be
5661 run on each source line. Each function takes 4
5662 arguments: filename, clean_lines, line, error
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005663 """
5664 raw_lines = clean_lines.raw_lines
erg@google.com35589e62010-11-17 18:58:16 +00005665 ParseNolintSuppressions(filename, raw_lines[line], line, error)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005666 nesting_state.Update(filename, clean_lines, line, error)
avakulenko@google.com59146752014-08-11 20:20:55 +00005667 CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line,
5668 error)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005669 if nesting_state.InAsmBlock(): return
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005670 CheckForFunctionLengths(filename, clean_lines, line, function_state, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005671 CheckForMultilineCommentsAndStrings(filename, clean_lines, line, error)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005672 CheckStyle(filename, clean_lines, line, file_extension, nesting_state, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005673 CheckLanguage(filename, clean_lines, line, file_extension, include_state,
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005674 nesting_state, error)
5675 CheckForNonConstReference(filename, clean_lines, line, nesting_state, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005676 CheckForNonStandardConstructs(filename, clean_lines, line,
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005677 nesting_state, error)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005678 CheckVlogArguments(filename, clean_lines, line, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005679 CheckPosixThreading(filename, clean_lines, line, error)
erg@google.com6317a9c2009-06-25 00:28:19 +00005680 CheckInvalidIncrement(filename, clean_lines, line, error)
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005681 CheckMakePairUsesDeduction(filename, clean_lines, line, error)
avakulenko@google.com59146752014-08-11 20:20:55 +00005682 CheckRedundantVirtual(filename, clean_lines, line, error)
5683 CheckRedundantOverrideOrFinal(filename, clean_lines, line, error)
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005684 for check_fn in extra_check_functions:
5685 check_fn(filename, clean_lines, line, error)
avakulenko@google.com17449932014-07-28 22:13:33 +00005686
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005687def FlagCxx11Features(filename, clean_lines, linenum, error):
5688 """Flag those c++11 features that we only allow in certain places.
5689
5690 Args:
5691 filename: The name of the current file.
5692 clean_lines: A CleansedLines instance containing the file.
5693 linenum: The number of the line to check.
5694 error: The function to call with any errors found.
5695 """
5696 line = clean_lines.elided[linenum]
5697
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005698 include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line)
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005699
5700 # Flag unapproved C++ TR1 headers.
5701 if include and include.group(1).startswith('tr1/'):
5702 error(filename, linenum, 'build/c++tr1', 5,
5703 ('C++ TR1 headers such as <%s> are unapproved.') % include.group(1))
5704
5705 # Flag unapproved C++11 headers.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005706 if include and include.group(1) in ('cfenv',
5707 'condition_variable',
5708 'fenv.h',
5709 'future',
5710 'mutex',
5711 'thread',
5712 'chrono',
5713 'ratio',
5714 'regex',
5715 'system_error',
5716 ):
5717 error(filename, linenum, 'build/c++11', 5,
5718 ('<%s> is an unapproved C++11 header.') % include.group(1))
5719
5720 # The only place where we need to worry about C++11 keywords and library
5721 # features in preprocessor directives is in macro definitions.
5722 if Match(r'\s*#', line) and not Match(r'\s*#\s*define\b', line): return
5723
5724 # These are classes and free functions. The classes are always
5725 # mentioned as std::*, but we only catch the free functions if
5726 # they're not found by ADL. They're alphabetical by header.
5727 for top_name in (
5728 # type_traits
5729 'alignment_of',
5730 'aligned_union',
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005731 ):
5732 if Search(r'\bstd::%s\b' % top_name, line):
5733 error(filename, linenum, 'build/c++11', 5,
5734 ('std::%s is an unapproved C++11 class or function. Send c-style '
5735 'an example of where it would make your code more readable, and '
5736 'they may let you use it.') % top_name)
5737
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005738
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005739def FlagCxx14Features(filename, clean_lines, linenum, error):
5740 """Flag those C++14 features that we restrict.
5741
5742 Args:
5743 filename: The name of the current file.
5744 clean_lines: A CleansedLines instance containing the file.
5745 linenum: The number of the line to check.
5746 error: The function to call with any errors found.
5747 """
5748 line = clean_lines.elided[linenum]
5749
5750 include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line)
5751
5752 # Flag unapproved C++14 headers.
5753 if include and include.group(1) in ('scoped_allocator', 'shared_mutex'):
5754 error(filename, linenum, 'build/c++14', 5,
5755 ('<%s> is an unapproved C++14 header.') % include.group(1))
5756
5757
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005758def ProcessFileData(filename, file_extension, lines, error,
5759 extra_check_functions=[]):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005760 """Performs lint checks and reports any errors to the given error function.
5761
5762 Args:
5763 filename: Filename of the file that is being processed.
5764 file_extension: The extension (dot not included) of the file.
5765 lines: An array of strings, each representing a line of the file, with the
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005766 last element being empty if the file is terminated with a newline.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005767 error: A callable to which errors are reported, which takes 4 arguments:
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005768 filename, line number, error level, and message
5769 extra_check_functions: An array of additional check functions that will be
5770 run on each source line. Each function takes 4
5771 arguments: filename, clean_lines, line, error
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005772 """
5773 lines = (['// marker so line numbers and indices both start at 1'] + lines +
5774 ['// marker so line numbers end in a known way'])
5775
5776 include_state = _IncludeState()
5777 function_state = _FunctionState()
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005778 nesting_state = NestingState()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005779
erg@google.com35589e62010-11-17 18:58:16 +00005780 ResetNolintSuppressions()
5781
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005782 CheckForCopyright(filename, lines, error)
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005783 ProcessGlobalSuppresions(lines)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005784 RemoveMultiLineComments(filename, lines, error)
5785 clean_lines = CleansedLines(lines)
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005786
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00005787 if file_extension == 'h':
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005788 CheckForHeaderGuard(filename, clean_lines, error)
5789
Edward Lemur6d31ed52019-12-02 23:00:00 +00005790 for line in range(clean_lines.NumLines()):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005791 ProcessLine(filename, file_extension, clean_lines, line,
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005792 include_state, function_state, nesting_state, error,
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005793 extra_check_functions)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005794 FlagCxx11Features(filename, clean_lines, line, error)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005795 nesting_state.CheckCompletedBlocks(filename, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005796
5797 CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error)
skym@chromium.org3990c412016-02-05 20:55:12 +00005798
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005799 # Check that the .cc file has included its header if it exists.
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005800 if _IsSourceExtension(file_extension):
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005801 CheckHeaderFileIncluded(filename, include_state, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005802
5803 # We check here rather than inside ProcessLine so that we see raw
5804 # lines rather than "cleaned" lines.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005805 CheckForBadCharacters(filename, lines, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005806
5807 CheckForNewlineAtEOF(filename, lines, error)
5808
avakulenko@google.com17449932014-07-28 22:13:33 +00005809def ProcessConfigOverrides(filename):
5810 """ Loads the configuration files and processes the config overrides.
5811
5812 Args:
5813 filename: The name of the file being processed by the linter.
5814
5815 Returns:
5816 False if the current |filename| should not be processed further.
5817 """
5818
5819 abs_filename = os.path.abspath(filename)
5820 cfg_filters = []
5821 keep_looking = True
5822 while keep_looking:
5823 abs_path, base_name = os.path.split(abs_filename)
5824 if not base_name:
5825 break # Reached the root directory.
5826
5827 cfg_file = os.path.join(abs_path, "CPPLINT.cfg")
5828 abs_filename = abs_path
5829 if not os.path.isfile(cfg_file):
5830 continue
5831
5832 try:
5833 with open(cfg_file) as file_handle:
5834 for line in file_handle:
5835 line, _, _ = line.partition('#') # Remove comments.
5836 if not line.strip():
5837 continue
5838
5839 name, _, val = line.partition('=')
5840 name = name.strip()
5841 val = val.strip()
5842 if name == 'set noparent':
5843 keep_looking = False
5844 elif name == 'filter':
5845 cfg_filters.append(val)
5846 elif name == 'exclude_files':
5847 # When matching exclude_files pattern, use the base_name of
5848 # the current file name or the directory name we are processing.
5849 # For example, if we are checking for lint errors in /foo/bar/baz.cc
5850 # and we found the .cfg file at /foo/CPPLINT.cfg, then the config
5851 # file's "exclude_files" filter is meant to be checked against "bar"
5852 # and not "baz" nor "bar/baz.cc".
5853 if base_name:
5854 pattern = re.compile(val)
5855 if pattern.match(base_name):
5856 sys.stderr.write('Ignoring "%s": file excluded by "%s". '
5857 'File path component "%s" matches '
5858 'pattern "%s"\n' %
5859 (filename, cfg_file, base_name, val))
5860 return False
avakulenko@google.com68a4fa62014-08-25 16:26:18 +00005861 elif name == 'linelength':
5862 global _line_length
5863 try:
5864 _line_length = int(val)
5865 except ValueError:
5866 sys.stderr.write('Line length must be numeric.')
avakulenko@google.com17449932014-07-28 22:13:33 +00005867 else:
5868 sys.stderr.write(
5869 'Invalid configuration option (%s) in file %s\n' %
5870 (name, cfg_file))
5871
5872 except IOError:
5873 sys.stderr.write(
5874 "Skipping config file '%s': Can't open for reading\n" % cfg_file)
5875 keep_looking = False
5876
5877 # Apply all the accumulated filters in reverse order (top-level directory
5878 # config options having the least priority).
5879 for filter in reversed(cfg_filters):
5880 _AddFilters(filter)
5881
5882 return True
5883
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005884
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005885def ProcessFile(filename, vlevel, extra_check_functions=[]):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005886 """Does google-lint on a single file.
5887
5888 Args:
5889 filename: The name of the file to parse.
5890
5891 vlevel: The level of errors to report. Every error of confidence
5892 >= verbose_level will be reported. 0 is a good default.
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005893
5894 extra_check_functions: An array of additional check functions that will be
5895 run on each source line. Each function takes 4
5896 arguments: filename, clean_lines, line, error
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005897 """
5898
5899 _SetVerboseLevel(vlevel)
avakulenko@google.com17449932014-07-28 22:13:33 +00005900 _BackupFilters()
5901
5902 if not ProcessConfigOverrides(filename):
5903 _RestoreFilters()
5904 return
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005905
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005906 lf_lines = []
5907 crlf_lines = []
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005908 try:
5909 # Support the UNIX convention of using "-" for stdin. Note that
5910 # we are not opening the file with universal newline support
5911 # (which codecs doesn't support anyway), so the resulting lines do
5912 # contain trailing '\r' characters if we are reading a file that
5913 # has CRLF endings.
5914 # If after the split a trailing '\r' is present, it is removed
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005915 # below.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005916 if filename == '-':
5917 lines = codecs.StreamReaderWriter(sys.stdin,
5918 codecs.getreader('utf8'),
5919 codecs.getwriter('utf8'),
5920 'replace').read().split('\n')
5921 else:
5922 lines = codecs.open(filename, 'r', 'utf8', 'replace').read().split('\n')
5923
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005924 # Remove trailing '\r'.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005925 # The -1 accounts for the extra trailing blank line we get from split()
5926 for linenum in range(len(lines) - 1):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005927 if lines[linenum].endswith('\r'):
5928 lines[linenum] = lines[linenum].rstrip('\r')
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005929 crlf_lines.append(linenum + 1)
5930 else:
5931 lf_lines.append(linenum + 1)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005932
5933 except IOError:
5934 sys.stderr.write(
5935 "Skipping input '%s': Can't open for reading\n" % filename)
avakulenko@google.com17449932014-07-28 22:13:33 +00005936 _RestoreFilters()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005937 return
5938
5939 # Note, if no dot is found, this will give the entire filename as the ext.
5940 file_extension = filename[filename.rfind('.') + 1:]
5941
5942 # When reading from stdin, the extension is unknown, so no cpplint tests
5943 # should rely on the extension.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005944 if filename != '-' and file_extension not in _valid_extensions:
5945 sys.stderr.write('Ignoring %s; not a valid file name '
5946 '(%s)\n' % (filename, ', '.join(_valid_extensions)))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005947 else:
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005948 ProcessFileData(filename, file_extension, lines, Error,
5949 extra_check_functions)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005950
5951 # If end-of-line sequences are a mix of LF and CR-LF, issue
5952 # warnings on the lines with CR.
5953 #
5954 # Don't issue any warnings if all lines are uniformly LF or CR-LF,
5955 # since critique can handle these just fine, and the style guide
5956 # doesn't dictate a particular end of line sequence.
5957 #
5958 # We can't depend on os.linesep to determine what the desired
5959 # end-of-line sequence should be, since that will return the
5960 # server-side end-of-line sequence.
5961 if lf_lines and crlf_lines:
5962 # Warn on every line with CR. An alternative approach might be to
5963 # check whether the file is mostly CRLF or just LF, and warn on the
5964 # minority, we bias toward LF here since most tools prefer LF.
5965 for linenum in crlf_lines:
5966 Error(filename, linenum, 'whitespace/newline', 1,
5967 'Unexpected \\r (^M) found; better to use only \\n')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005968
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00005969 sys.stderr.write('Done processing %s\n' % filename)
avakulenko@google.com17449932014-07-28 22:13:33 +00005970 _RestoreFilters()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005971
5972
5973def PrintUsage(message):
5974 """Prints a brief usage string and exits, optionally with an error message.
5975
5976 Args:
5977 message: The optional error message.
5978 """
5979 sys.stderr.write(_USAGE)
5980 if message:
5981 sys.exit('\nFATAL ERROR: ' + message)
5982 else:
5983 sys.exit(1)
5984
5985
5986def PrintCategories():
5987 """Prints a list of all the error-categories used by error messages.
5988
5989 These are the categories used to filter messages via --filter.
5990 """
erg@google.com35589e62010-11-17 18:58:16 +00005991 sys.stderr.write(''.join(' %s\n' % cat for cat in _ERROR_CATEGORIES))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005992 sys.exit(0)
5993
5994
5995def ParseArguments(args):
5996 """Parses the command line arguments.
5997
5998 This may set the output format and verbosity level as side-effects.
5999
6000 Args:
6001 args: The command line arguments:
6002
6003 Returns:
6004 The list of filenames to lint.
6005 """
6006 try:
6007 (opts, filenames) = getopt.getopt(args, '', ['help', 'output=', 'verbose=',
Jordan Bayles91a32c52019-02-22 21:28:17 +00006008 'headers=', # We understand but ignore headers.
erg@google.com26970fa2009-11-17 18:07:32 +00006009 'counting=',
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00006010 'filter=',
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00006011 'root=',
6012 'linelength=',
sdefresne263e9282016-07-19 02:14:22 -07006013 'extensions=',
Jordan Bayles91a32c52019-02-22 21:28:17 +00006014 'project_root=',
6015 'repository='])
6016 except getopt.GetoptError as e:
6017 PrintUsage('Invalid arguments: {}'.format(e))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006018
6019 verbosity = _VerboseLevel()
6020 output_format = _OutputFormat()
6021 filters = ''
erg@google.com26970fa2009-11-17 18:07:32 +00006022 counting_style = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006023
6024 for (opt, val) in opts:
6025 if opt == '--help':
6026 PrintUsage(None)
6027 elif opt == '--output':
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00006028 if val not in ('emacs', 'vs7', 'eclipse'):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00006029 PrintUsage('The only allowed output formats are emacs, vs7 and eclipse.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006030 output_format = val
6031 elif opt == '--verbose':
6032 verbosity = int(val)
6033 elif opt == '--filter':
6034 filters = val
erg@google.com6317a9c2009-06-25 00:28:19 +00006035 if not filters:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006036 PrintCategories()
erg@google.com26970fa2009-11-17 18:07:32 +00006037 elif opt == '--counting':
6038 if val not in ('total', 'toplevel', 'detailed'):
6039 PrintUsage('Valid counting options are total, toplevel, and detailed')
6040 counting_style = val
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00006041 elif opt == '--root':
6042 global _root
6043 _root = val
Jordan Bayles91a32c52019-02-22 21:28:17 +00006044 elif opt == '--project_root' or opt == "--repository":
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00006045 global _project_root
6046 _project_root = val
6047 if not os.path.isabs(_project_root):
6048 PrintUsage('Project root must be an absolute path.')
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00006049 elif opt == '--linelength':
6050 global _line_length
6051 try:
6052 _line_length = int(val)
6053 except ValueError:
6054 PrintUsage('Line length must be digits.')
6055 elif opt == '--extensions':
6056 global _valid_extensions
6057 try:
6058 _valid_extensions = set(val.split(','))
6059 except ValueError:
qyearsley12fa6ff2016-08-24 09:18:40 -07006060 PrintUsage('Extensions must be comma separated list.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006061
6062 if not filenames:
6063 PrintUsage('No files were specified.')
6064
6065 _SetOutputFormat(output_format)
6066 _SetVerboseLevel(verbosity)
6067 _SetFilters(filters)
erg@google.com26970fa2009-11-17 18:07:32 +00006068 _SetCountingStyle(counting_style)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006069
6070 return filenames
6071
6072
6073def main():
6074 filenames = ParseArguments(sys.argv[1:])
6075
6076 # Change stderr to write with replacement characters so we don't die
6077 # if we try to print something containing non-ASCII characters.
Edward Lemur6d31ed52019-12-02 23:00:00 +00006078 # We use sys.stderr.buffer in Python 3, since StreamReaderWriter writes bytes
6079 # to the specified stream.
6080 sys.stderr = codecs.StreamReaderWriter(
6081 getattr(sys.stderr, 'buffer', sys.stderr),
6082 codecs.getreader('utf8'), codecs.getwriter('utf8'), 'replace')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006083
erg@google.com26970fa2009-11-17 18:07:32 +00006084 _cpplint_state.ResetErrorCounts()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006085 for filename in filenames:
6086 ProcessFile(filename, _cpplint_state.verbose_level)
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00006087 _cpplint_state.PrintErrorCounts()
erg@google.com26970fa2009-11-17 18:07:32 +00006088
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006089 sys.exit(_cpplint_state.error_count > 0)
6090
6091
6092if __name__ == '__main__':
6093 main()