blob: 60b9c2bf2537f12d91c8c078dc3175618f2adff8 [file] [log] [blame]
Ryan Macnakfd032192022-03-21 20:45:12 +00001#!/usr/bin/env python3
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002#
erg@google.com26970fa2009-11-17 18:07:32 +00003# Copyright (c) 2009 Google Inc. All rights reserved.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004#
erg@google.com26970fa2009-11-17 18:07:32 +00005# Redistribution and use in source and binary forms, with or without
6# modification, are permitted provided that the following conditions are
7# met:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00008#
erg@google.com26970fa2009-11-17 18:07:32 +00009# * Redistributions of source code must retain the above copyright
10# notice, this list of conditions and the following disclaimer.
11# * Redistributions in binary form must reproduce the above
12# copyright notice, this list of conditions and the following disclaimer
13# in the documentation and/or other materials provided with the
14# distribution.
15# * Neither the name of Google Inc. nor the names of its
16# contributors may be used to endorse or promote products derived from
17# this software without specific prior written permission.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000018#
erg@google.com26970fa2009-11-17 18:07:32 +000019# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000030
agablef39c3332016-09-26 09:35:42 -070031# pylint: skip-file
32
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000033"""Does google-lint on c++ files.
34
35The goal of this script is to identify places in the code that *may*
36be in non-compliance with google style. It does not attempt to fix
37up these problems -- the point is to educate. It does also not
38attempt to find all problems, or to ensure that everything it does
39find is legitimately a problem.
40
41In particular, we can get very confused by /* and // inside strings!
42We do a small hack, which is to ignore //'s with "'s after them on the
43same line, but it is far from perfect (in either direction).
44"""
45
46import codecs
mazda@chromium.org3fffcec2013-06-07 01:04:53 +000047import copy
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000048import getopt
49import math # for log
50import os
51import re
52import sre_compile
53import string
54import sys
55import unicodedata
56
57
Edward Lemur6d31ed52019-12-02 23:00:00 +000058_USAGE = r"""
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000059Syntax: cpplint.py [--verbose=#] [--output=vs7] [--filter=-x,+y,...]
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +000060 [--counting=total|toplevel|detailed] [--root=subdir]
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +000061 [--linelength=digits]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000062 <file> [file] ...
63
64 The style guidelines this tries to follow are those in
Alexandr Ilinff294c32017-04-27 15:57:40 +020065 https://google.github.io/styleguide/cppguide.html
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000066
67 Every problem is given a confidence score from 1-5, with 5 meaning we are
68 certain of the problem, and 1 meaning it could be a legitimate construct.
69 This will miss some errors, and is not a substitute for a code review.
70
erg@google.com35589e62010-11-17 18:58:16 +000071 To suppress false-positive errors of a certain category, add a
72 'NOLINT(category)' comment to the line. NOLINT or NOLINT(*)
73 suppresses errors of all categories on that line.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000074
75 The files passed in will be linted; at least one file must be provided.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +000076 Default linted extensions are .cc, .cpp, .cu, .cuh and .h. Change the
77 extensions with the --extensions flag.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +000078
79 Flags:
80
81 output=vs7
82 By default, the output is formatted to ease emacs parsing. Visual Studio
83 compatible output (vs7) may also be used. Other formats are unsupported.
84
85 verbose=#
86 Specify a number 0-5 to restrict errors to certain verbosity levels.
87
88 filter=-x,+y,...
89 Specify a comma-separated list of category-filters to apply: only
90 error messages whose category names pass the filters will be printed.
91 (Category names are printed with the message and look like
92 "[whitespace/indent]".) Filters are evaluated left to right.
93 "-FOO" and "FOO" means "do not print categories that start with FOO".
94 "+FOO" means "do print categories that start with FOO".
95
96 Examples: --filter=-whitespace,+whitespace/braces
97 --filter=whitespace,runtime/printf,+runtime/printf_format
98 --filter=-,+build/include_what_you_use
99
100 To see a list of all the categories used in cpplint, pass no arg:
101 --filter=
erg@google.com26970fa2009-11-17 18:07:32 +0000102
103 counting=total|toplevel|detailed
104 The total number of errors found is always printed. If
105 'toplevel' is provided, then the count of errors in each of
106 the top-level categories like 'build' and 'whitespace' will
107 also be printed. If 'detailed' is provided, then a count
108 is provided for each category like 'build/class'.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +0000109
110 root=subdir
111 The root directory used for deriving header guard CPP variable.
112 By default, the header guard CPP variable is calculated as the relative
113 path to the directory that contains .git, .hg, or .svn. When this flag
114 is specified, the relative path is calculated from the specified
115 directory. If the specified directory does not exist, this flag is
116 ignored.
117
118 Examples:
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +0000119 Assuming that src/.git exists, the header guard CPP variables for
120 src/chrome/browser/ui/browser.h are:
mazda@chromium.org3fffcec2013-06-07 01:04:53 +0000121
122 No flag => CHROME_BROWSER_UI_BROWSER_H_
123 --root=chrome => BROWSER_UI_BROWSER_H_
124 --root=chrome/browser => UI_BROWSER_H_
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000125
126 linelength=digits
127 This is the allowed line length for the project. The default value is
128 80 characters.
129
130 Examples:
131 --linelength=120
132
133 extensions=extension,extension,...
134 The allowed file extensions that cpplint will check
135
136 Examples:
137 --extensions=hpp,cpp
avakulenko@google.com17449932014-07-28 22:13:33 +0000138
139 cpplint.py supports per-directory configurations specified in CPPLINT.cfg
140 files. CPPLINT.cfg file can contain a number of key=value pairs.
141 Currently the following options are supported:
142
143 set noparent
144 filter=+filter1,-filter2,...
145 exclude_files=regex
avakulenko@google.com68a4fa62014-08-25 16:26:18 +0000146 linelength=80
avakulenko@google.com17449932014-07-28 22:13:33 +0000147
148 "set noparent" option prevents cpplint from traversing directory tree
149 upwards looking for more .cfg files in parent directories. This option
150 is usually placed in the top-level project directory.
151
152 The "filter" option is similar in function to --filter flag. It specifies
153 message filters in addition to the |_DEFAULT_FILTERS| and those specified
154 through --filter command-line flag.
155
156 "exclude_files" allows to specify a regular expression to be matched against
157 a file name. If the expression matches, the file is skipped and not run
158 through liner.
159
avakulenko@google.com68a4fa62014-08-25 16:26:18 +0000160 "linelength" allows to specify the allowed line length for the project.
161
avakulenko@google.com17449932014-07-28 22:13:33 +0000162 CPPLINT.cfg has an effect on files in the same directory and all
163 sub-directories, unless overridden by a nested configuration file.
164
165 Example file:
166 filter=-build/include_order,+build/include_alpha
167 exclude_files=.*\.cc
168
169 The above example disables build/include_order warning and enables
170 build/include_alpha as well as excludes all .cc from being
171 processed by linter, in the current directory (where the .cfg
172 file is located) and all sub-directories.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000173"""
174
175# We categorize each error message we print. Here are the categories.
176# We want an explicit list so we can list them all in cpplint --filter=.
177# If you add a new error message with a new category, add it to the list
178# here! cpplint_unittest.py should tell you if you forget to do this.
erg@google.com35589e62010-11-17 18:58:16 +0000179_ERROR_CATEGORIES = [
avakulenko@google.com255f2be2014-12-05 22:19:55 +0000180 'build/class',
181 'build/c++11',
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000182 'build/c++14',
183 'build/c++tr1',
avakulenko@google.com255f2be2014-12-05 22:19:55 +0000184 'build/deprecated',
185 'build/endif_comment',
186 'build/explicit_make_pair',
187 'build/forward_decl',
188 'build/header_guard',
189 'build/include',
190 'build/include_alpha',
Fletcher Woodruff11b34152020-04-23 21:21:40 +0000191 'build/include_directory',
avakulenko@google.com255f2be2014-12-05 22:19:55 +0000192 'build/include_order',
193 'build/include_what_you_use',
194 'build/namespaces',
195 'build/printf_format',
196 'build/storage_class',
197 'legal/copyright',
198 'readability/alt_tokens',
199 'readability/braces',
200 'readability/casting',
201 'readability/check',
202 'readability/constructors',
203 'readability/fn_size',
avakulenko@google.com255f2be2014-12-05 22:19:55 +0000204 'readability/inheritance',
205 'readability/multiline_comment',
206 'readability/multiline_string',
207 'readability/namespace',
208 'readability/nolint',
209 'readability/nul',
210 'readability/strings',
211 'readability/todo',
212 'readability/utf8',
213 'runtime/arrays',
214 'runtime/casting',
215 'runtime/explicit',
216 'runtime/int',
217 'runtime/init',
218 'runtime/invalid_increment',
219 'runtime/member_string_references',
220 'runtime/memset',
221 'runtime/indentation_namespace',
222 'runtime/operator',
223 'runtime/printf',
224 'runtime/printf_format',
225 'runtime/references',
226 'runtime/string',
227 'runtime/threadsafe_fn',
228 'runtime/vlog',
229 'whitespace/blank_line',
230 'whitespace/braces',
231 'whitespace/comma',
232 'whitespace/comments',
233 'whitespace/empty_conditional_body',
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000234 'whitespace/empty_if_body',
avakulenko@google.com255f2be2014-12-05 22:19:55 +0000235 'whitespace/empty_loop_body',
236 'whitespace/end_of_line',
237 'whitespace/ending_newline',
238 'whitespace/forcolon',
239 'whitespace/indent',
240 'whitespace/line_length',
241 'whitespace/newline',
242 'whitespace/operators',
243 'whitespace/parens',
244 'whitespace/semicolon',
245 'whitespace/tab',
246 'whitespace/todo',
247 ]
248
249# These error categories are no longer enforced by cpplint, but for backwards-
250# compatibility they may still appear in NOLINT comments.
251_LEGACY_ERROR_CATEGORIES = [
252 'readability/streams',
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000253 'readability/function',
avakulenko@google.com255f2be2014-12-05 22:19:55 +0000254 ]
erg@google.com6317a9c2009-06-25 00:28:19 +0000255
avakulenko@google.comd39bbb52014-06-04 22:55:20 +0000256# The default state of the category filter. This is overridden by the --filter=
erg@google.com6317a9c2009-06-25 00:28:19 +0000257# flag. By default all errors are on, so only add here categories that should be
258# off by default (i.e., categories that must be enabled by the --filter= flags).
259# All entries here should start with a '-' or '+', as in the --filter= flag.
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +0000260_DEFAULT_FILTERS = ['-build/include_alpha']
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000261
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000262# The default list of categories suppressed for C (not C++) files.
263_DEFAULT_C_SUPPRESSED_CATEGORIES = [
264 'readability/casting',
265 ]
266
267# The default list of categories suppressed for Linux Kernel files.
268_DEFAULT_KERNEL_SUPPRESSED_CATEGORIES = [
269 'whitespace/tab',
270 ]
271
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000272# We used to check for high-bit characters, but after much discussion we
273# decided those were OK, as long as they were in UTF-8 and didn't represent
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +0000274# hard-coded international strings, which belong in a separate i18n file.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000275
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000276# C++ headers
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000277_CPP_HEADERS = frozenset([
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000278 # Legacy
279 'algobase.h',
280 'algo.h',
281 'alloc.h',
282 'builtinbuf.h',
283 'bvector.h',
284 'complex.h',
285 'defalloc.h',
286 'deque.h',
287 'editbuf.h',
288 'fstream.h',
289 'function.h',
290 'hash_map',
291 'hash_map.h',
292 'hash_set',
293 'hash_set.h',
294 'hashtable.h',
295 'heap.h',
296 'indstream.h',
297 'iomanip.h',
298 'iostream.h',
299 'istream.h',
300 'iterator.h',
301 'list.h',
302 'map.h',
303 'multimap.h',
304 'multiset.h',
305 'ostream.h',
306 'pair.h',
307 'parsestream.h',
308 'pfstream.h',
309 'procbuf.h',
310 'pthread_alloc',
311 'pthread_alloc.h',
312 'rope',
313 'rope.h',
314 'ropeimpl.h',
315 'set.h',
316 'slist',
317 'slist.h',
318 'stack.h',
319 'stdiostream.h',
320 'stl_alloc.h',
321 'stl_relops.h',
322 'streambuf.h',
323 'stream.h',
324 'strfile.h',
325 'strstream.h',
326 'tempbuf.h',
327 'tree.h',
328 'type_traits.h',
329 'vector.h',
330 # 17.6.1.2 C++ library headers
331 'algorithm',
dan sinclair9a3c4bc2022-06-17 22:58:24 +0000332 'any',
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000333 'array',
334 'atomic',
335 'bitset',
dan sinclair9a3c4bc2022-06-17 22:58:24 +0000336 'charconv',
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000337 'chrono',
338 'codecvt',
339 'complex',
340 'condition_variable',
341 'deque',
dan sinclair9a3c4bc2022-06-17 22:58:24 +0000342 'execution',
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000343 'exception',
dan sinclair9a3c4bc2022-06-17 22:58:24 +0000344 'filesystem',
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000345 'forward_list',
346 'fstream',
347 'functional',
348 'future',
349 'initializer_list',
350 'iomanip',
351 'ios',
352 'iosfwd',
353 'iostream',
354 'istream',
355 'iterator',
356 'limits',
357 'list',
358 'locale',
359 'map',
360 'memory',
dan sinclair9a3c4bc2022-06-17 22:58:24 +0000361 'memory_resource',
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000362 'mutex',
363 'new',
364 'numeric',
dan sinclair9a3c4bc2022-06-17 22:58:24 +0000365 'optional',
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000366 'ostream',
367 'queue',
368 'random',
369 'ratio',
370 'regex',
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000371 'scoped_allocator',
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000372 'set',
373 'sstream',
374 'stack',
375 'stdexcept',
376 'streambuf',
377 'string',
Jasper Chapman-Black9ab047e2019-11-07 15:51:54 +0000378 'string_view',
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000379 'strstream',
380 'system_error',
381 'thread',
382 'tuple',
383 'typeindex',
384 'typeinfo',
385 'type_traits',
386 'unordered_map',
387 'unordered_set',
388 'utility',
389 'valarray',
dan sinclair9a3c4bc2022-06-17 22:58:24 +0000390 'variant',
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000391 'vector',
392 # 17.6.1.2 C++ headers for C library facilities
393 'cassert',
394 'ccomplex',
395 'cctype',
396 'cerrno',
397 'cfenv',
398 'cfloat',
399 'cinttypes',
400 'ciso646',
401 'climits',
402 'clocale',
403 'cmath',
404 'csetjmp',
405 'csignal',
406 'cstdalign',
407 'cstdarg',
408 'cstdbool',
409 'cstddef',
410 'cstdint',
411 'cstdio',
412 'cstdlib',
413 'cstring',
414 'ctgmath',
415 'ctime',
416 'cuchar',
417 'cwchar',
418 'cwctype',
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000419 ])
420
Peter Kasting00741582023-02-16 20:09:51 +0000421# List of functions from <type_traits>. See [meta.type.synop]
422_TYPE_TRAITS = [
423 # 23.15.3, helper class
424 'integral_constant',
425 # 23.15.4.1, primary type categories
426 'is_void',
427 'is_null_pointer',
428 'is_integral',
429 'is_floating_point',
430 'is_array',
431 'is_pointer',
432 'is_lvalue_reference',
433 'is_rvalue_reference',
434 'is_member_object_pointer',
435 'is_member_function_pointer',
436 'is_enum',
437 'is_union',
438 'is_class',
439 'is_function',
440 # 23.15.4.2, composite type categories
441 'is_reference',
442 'is_arithmetic',
443 'is_fundamental',
444 'is_object',
445 'is_scalar',
446 'is_compound',
447 'is_member_pointer',
448 # 23.15.4.3, type properties
449 'is_const',
450 'is_volatile',
451 'is_trivial',
452 'is_trivially_copyable',
453 'is_standard_layout',
454 'is_pod',
455 'is_empty',
456 'is_polymorphic',
457 'is_abstract',
458 'is_final',
459 'is_aggregate',
460 'is_signed',
461 'is_unsigned',
462 'is_constructible',
463 'is_default_constructible',
464 'is_copy_constructible',
465 'is_move_constructible',
466 'is_assignable',
467 'is_copy_assignable',
468 'is_move_assignable',
469 'is_swappable_with',
470 'is_swappable',
471 'is_destructible',
472 'is_trivially_constructible',
473 'is_trivially_default_constructible',
474 'is_trivially_copy_constructible',
475 'is_trivially_move_constructible',
476 'is_trivially_assignable',
477 'is_trivially_copy_assignable',
478 'is_trivially_move_assignable',
479 'is_trivially_destructible',
480 'is_nothrow_constructible',
481 'is_nothrow_default_constructible',
482 'is_nothrow_copy_constructible',
483 'is_nothrow_move_constructible',
484 'is_nothrow_assignable',
485 'is_nothrow_copy_assignable',
486 'is_nothrow_move_assignable',
487 'is_nothrow_swappable_with',
488 'is_nothrow_swappable',
489 'is_nothrow_destructible',
490 'has_virtual_destructor',
491 'has_unique_object_representations',
492 # 23.15.5, type property queries
493 'alignment_of',
494 'rank',
495 'extent',
496 # 23.15.6, type relations
497 'is_same',
498 'is_base_of',
499 'is_convertible',
500 'is_invocable',
501 'is_invocable_r',
502 'is_nothrow_invocable',
503 'is_nothrow_invocable_r',
504 # 23.15.7.1, const-volatile modifications
505 'remove_const',
506 'remove_volatile',
507 'remove_cv',
508 'add_const',
509 'add_volatile',
510 'add_cv',
511 'remove_const_t',
512 'remove_volatile_t',
513 'remove_cv_t',
514 'add_const_t',
515 'add_volatile_t',
516 'add_cv_t',
517 # 23.15.7.2, reference modifications
518 'remove_reference',
519 'add_lvalue_reference',
520 'add_rvalue_reference',
521 'remove_reference_t',
522 'add_lvalue_reference_t',
523 'add_rvalue_reference_t',
524 # 23.15.7.3, sign modifications
525 'make_signed',
526 'make_unsigned',
527 'make_signed_t',
528 'make_unsigned_t',
529 # 23.15.7.4, array modifications
530 'remove_extent',
531 'remove_all_extents',
532 'remove_extent_t',
533 'remove_all_extents_t',
534 # 23.15.7.5, pointer modifications
535 'remove_pointer',
536 'add_pointer',
537 'remove_pointer_t',
538 'add_pointer_t',
539 # 23.15.7.6, other transformations
540 'aligned_storage',
541 'aligned_union',
542 'decay',
543 'enable_if',
544 'conditional',
545 'common_type',
546 'underlying_type',
547 'invoke_result',
548 'aligned_storage_t',
549 'aligned_union_t',
550 'decay_t',
551 'enable_if_t',
552 'conditional_t',
553 'common_type_t',
554 'underlying_type_t',
555 'invoke_result_t',
556 'void_t',
557 # 23.15.8, logical operator traits
558 'conjunction',
559 'disjunction',
560 'negation',
561 # 23.15.4.1, primary type categories
562 'is_void_v',
563 'is_null_pointer_v',
564 'is_integral_v',
565 'is_floating_point_v',
566 'is_array_v',
567 'is_pointer_v',
568 'is_lvalue_reference_v',
569 'is_rvalue_reference_v',
570 'is_member_object_pointer_v',
571 'is_member_function_pointer_v',
572 'is_enum_v',
573 'is_union_v',
574 'is_class_v',
575 'is_function_v',
576 # 23.15.4.2, composite type categories
577 'is_reference_v',
578 'is_arithmetic_v',
579 'is_fundamental_v',
580 'is_object_v',
581 'is_scalar_v',
582 'is_compound_v',
583 'is_member_pointer_v',
584 # 23.15.4.3, type properties
585 'is_const_v',
586 'is_volatile_v',
587 'is_trivial_v',
588 'is_trivially_copyable_v',
589 'is_standard_layout_v',
590 'is_pod_v',
591 'is_empty_v',
592 'is_polymorphic_v',
593 'is_abstract_v',
594 'is_final_v',
595 'is_aggregate_v',
596 'is_signed_v',
597 'is_unsigned_v',
598 'is_constructible_v',
599 'is_default_constructible_v',
600 'is_copy_constructible_v',
601 'is_move_constructible_v',
602 'is_assignable_v',
603 'is_copy_assignable_v',
604 'is_move_assignable_v',
605 'is_swappable_with_v',
606 'is_swappable_v',
607 'is_destructible_v',
608 'is_trivially_constructible_v',
609 'is_trivially_default_constructible_v',
610 'is_trivially_copy_constructible_v',
611 'is_trivially_move_constructible_v',
612 'is_trivially_assignable_v',
613 'is_trivially_copy_assignable_v',
614 'is_trivially_move_assignable_v',
615 'is_trivially_destructible_v',
616 'is_nothrow_constructible_v',
617 'is_nothrow_default_constructible_v',
618 'is_nothrow_copy_constructible_v',
619 'is_nothrow_move_constructible_v',
620 'is_nothrow_assignable_v',
621 'is_nothrow_copy_assignable_v',
622 'is_nothrow_move_assignable_v',
623 'is_nothrow_swappable_with_v',
624 'is_nothrow_swappable_v',
625 'is_nothrow_destructible_v',
626 'has_virtual_destructor_v',
627 'has_unique_object_representations_v',
628 # 23.15.5, type property queries
629 'alignment_of_v',
630 'rank_v',
631 'extent_v',
632 'is_same_v',
633 'is_base_of_v',
634 'is_convertible_v',
635 'is_invocable_v',
636 'is_invocable_r_v',
637 'is_nothrow_invocable_v',
638 'is_nothrow_invocable_r_v',
639 # 23.15.8, logical operator traits
640 'conjunction_v',
641 'disjunction_v',
642 'negation_v',
643]
644_TYPE_TRAITS_RE = re.compile(r'\b::(?:' + ('|'.join(_TYPE_TRAITS)) + ')<')
645
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000646# Type names
647_TYPES = re.compile(
648 r'^(?:'
649 # [dcl.type.simple]
650 r'(char(16_t|32_t)?)|wchar_t|'
651 r'bool|short|int|long|signed|unsigned|float|double|'
652 # [support.types]
653 r'(ptrdiff_t|size_t|max_align_t|nullptr_t)|'
654 # [cstdint.syn]
655 r'(u?int(_fast|_least)?(8|16|32|64)_t)|'
656 r'(u?int(max|ptr)_t)|'
657 r')$')
658
avakulenko@google.comd39bbb52014-06-04 22:55:20 +0000659
Fletcher Woodruff11b34152020-04-23 21:21:40 +0000660# These headers are excluded from [build/include], [build/include_directory],
661# and [build/include_order] checks:
avakulenko@google.com59146752014-08-11 20:20:55 +0000662# - Anything not following google file name conventions (containing an
663# uppercase character, such as Python.h or nsStringAPI.h, for example).
664# - Lua headers.
665_THIRD_PARTY_HEADERS_PATTERN = re.compile(
666 r'^(?:[^/]*[A-Z][^/]*\.h|lua\.h|lauxlib\.h|lualib\.h)$')
667
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000668# Pattern for matching FileInfo.BaseName() against test file name
669_TEST_FILE_SUFFIX = r'(_test|_unittest|_regtest)$'
670
671# Pattern that matches only complete whitespace, possibly across multiple lines.
672_EMPTY_CONDITIONAL_BODY_PATTERN = re.compile(r'^\s*$', re.DOTALL)
avakulenko@google.com59146752014-08-11 20:20:55 +0000673
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000674# Assertion macros. These are defined in base/logging.h and
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000675# testing/base/public/gunit.h.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000676_CHECK_MACROS = [
erg@google.com6317a9c2009-06-25 00:28:19 +0000677 'DCHECK', 'CHECK',
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000678 'EXPECT_TRUE', 'ASSERT_TRUE',
679 'EXPECT_FALSE', 'ASSERT_FALSE',
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000680 ]
681
erg@google.com6317a9c2009-06-25 00:28:19 +0000682# Replacement macros for CHECK/DCHECK/EXPECT_TRUE/EXPECT_FALSE
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000683_CHECK_REPLACEMENT = dict([(m, {}) for m in _CHECK_MACROS])
684
685for op, replacement in [('==', 'EQ'), ('!=', 'NE'),
686 ('>=', 'GE'), ('>', 'GT'),
687 ('<=', 'LE'), ('<', 'LT')]:
erg@google.com6317a9c2009-06-25 00:28:19 +0000688 _CHECK_REPLACEMENT['DCHECK'][op] = 'DCHECK_%s' % replacement
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000689 _CHECK_REPLACEMENT['CHECK'][op] = 'CHECK_%s' % replacement
690 _CHECK_REPLACEMENT['EXPECT_TRUE'][op] = 'EXPECT_%s' % replacement
691 _CHECK_REPLACEMENT['ASSERT_TRUE'][op] = 'ASSERT_%s' % replacement
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000692
693for op, inv_replacement in [('==', 'NE'), ('!=', 'EQ'),
694 ('>=', 'LT'), ('>', 'LE'),
695 ('<=', 'GT'), ('<', 'GE')]:
696 _CHECK_REPLACEMENT['EXPECT_FALSE'][op] = 'EXPECT_%s' % inv_replacement
697 _CHECK_REPLACEMENT['ASSERT_FALSE'][op] = 'ASSERT_%s' % inv_replacement
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000698
mazda@chromium.org3fffcec2013-06-07 01:04:53 +0000699# Alternative tokens and their replacements. For full list, see section 2.5
700# Alternative tokens [lex.digraph] in the C++ standard.
701#
702# Digraphs (such as '%:') are not included here since it's a mess to
703# match those on a word boundary.
704_ALT_TOKEN_REPLACEMENT = {
705 'and': '&&',
706 'bitor': '|',
707 'or': '||',
708 'xor': '^',
709 'compl': '~',
710 'bitand': '&',
711 'and_eq': '&=',
712 'or_eq': '|=',
713 'xor_eq': '^=',
714 'not': '!',
715 'not_eq': '!='
716 }
717
718# Compile regular expression that matches all the above keywords. The "[ =()]"
719# bit is meant to avoid matching these keywords outside of boolean expressions.
720#
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000721# False positives include C-style multi-line comments and multi-line strings
722# but those have always been troublesome for cpplint.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +0000723_ALT_TOKEN_REPLACEMENT_PATTERN = re.compile(
724 r'[ =()](' + ('|'.join(_ALT_TOKEN_REPLACEMENT.keys())) + r')(?=[ (]|$)')
725
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000726
727# These constants define types of headers for use with
728# _IncludeState.CheckNextIncludeOrder().
729_C_SYS_HEADER = 1
730_CPP_SYS_HEADER = 2
731_LIKELY_MY_HEADER = 3
732_POSSIBLE_MY_HEADER = 4
733_OTHER_HEADER = 5
734
mazda@chromium.org3fffcec2013-06-07 01:04:53 +0000735# These constants define the current inline assembly state
736_NO_ASM = 0 # Outside of inline assembly block
737_INSIDE_ASM = 1 # Inside inline assembly block
738_END_ASM = 2 # Last line of inline assembly block
739_BLOCK_ASM = 3 # The whole block is an inline assembly block
740
741# Match start of assembly blocks
742_MATCH_ASM = re.compile(r'^\s*(?:asm|_asm|__asm|__asm__)'
743 r'(?:\s+(volatile|__volatile__))?'
744 r'\s*[{(]')
745
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000746# Match strings that indicate we're working on a C (not C++) file.
747_SEARCH_C_FILE = re.compile(r'\b(?:LINT_C_FILE|'
748 r'vim?:\s*.*(\s*|:)filetype=c(\s*|:|$))')
749
750# Match string that indicates we're working on a Linux Kernel file.
751_SEARCH_KERNEL_FILE = re.compile(r'\b(?:LINT_KERNEL_FILE)')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000752
753_regexp_compile_cache = {}
754
erg@google.com35589e62010-11-17 18:58:16 +0000755# {str, set(int)}: a map from error categories to sets of linenumbers
756# on which those errors are expected and should be suppressed.
757_error_suppressions = {}
758
mazda@chromium.org3fffcec2013-06-07 01:04:53 +0000759# The root directory used for deriving header guard CPP variable.
760# This is set by --root flag.
761_root = None
David Sanders2f988472022-05-21 01:35:11 +0000762_root_debug = False
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +0000763
764# The project root directory. Used for deriving header guard CPP variable.
765# This is set by --project_root flag. Must be an absolute path.
766_project_root = None
sdefresne263e9282016-07-19 02:14:22 -0700767
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000768# The allowed line length of files.
769# This is set by --linelength flag.
770_line_length = 80
771
772# The allowed extensions for file names
773# This is set by --extensions flag.
774_valid_extensions = set(['cc', 'h', 'cpp', 'cu', 'cuh'])
775
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000776# {str, bool}: a map from error categories to booleans which indicate if the
777# category should be suppressed for every line.
778_global_error_suppressions = {}
779
780
erg@google.com35589e62010-11-17 18:58:16 +0000781def ParseNolintSuppressions(filename, raw_line, linenum, error):
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000782 """Updates the global list of line error-suppressions.
erg@google.com35589e62010-11-17 18:58:16 +0000783
784 Parses any NOLINT comments on the current line, updating the global
785 error_suppressions store. Reports an error if the NOLINT comment
786 was malformed.
787
788 Args:
789 filename: str, the name of the input file.
790 raw_line: str, the line of input text, with comments.
791 linenum: int, the number of the current line.
792 error: function, an error handler.
793 """
avakulenko@google.com59146752014-08-11 20:20:55 +0000794 matched = Search(r'\bNOLINT(NEXTLINE)?\b(\([^)]+\))?', raw_line)
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +0000795 if matched:
avakulenko@google.com59146752014-08-11 20:20:55 +0000796 if matched.group(1):
797 suppressed_line = linenum + 1
798 else:
799 suppressed_line = linenum
800 category = matched.group(2)
erg@google.com35589e62010-11-17 18:58:16 +0000801 if category in (None, '(*)'): # => "suppress all"
avakulenko@google.com59146752014-08-11 20:20:55 +0000802 _error_suppressions.setdefault(None, set()).add(suppressed_line)
erg@google.com35589e62010-11-17 18:58:16 +0000803 else:
804 if category.startswith('(') and category.endswith(')'):
805 category = category[1:-1]
806 if category in _ERROR_CATEGORIES:
avakulenko@google.com59146752014-08-11 20:20:55 +0000807 _error_suppressions.setdefault(category, set()).add(suppressed_line)
avakulenko@google.com255f2be2014-12-05 22:19:55 +0000808 elif category not in _LEGACY_ERROR_CATEGORIES:
erg@google.com35589e62010-11-17 18:58:16 +0000809 error(filename, linenum, 'readability/nolint', 5,
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +0000810 'Unknown NOLINT error category: %s' % category)
erg@google.com35589e62010-11-17 18:58:16 +0000811
812
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000813def ProcessGlobalSuppresions(lines):
814 """Updates the list of global error suppressions.
815
816 Parses any lint directives in the file that have global effect.
817
818 Args:
819 lines: An array of strings, each representing a line of the file, with the
820 last element being empty if the file is terminated with a newline.
821 """
822 for line in lines:
823 if _SEARCH_C_FILE.search(line):
824 for category in _DEFAULT_C_SUPPRESSED_CATEGORIES:
825 _global_error_suppressions[category] = True
826 if _SEARCH_KERNEL_FILE.search(line):
827 for category in _DEFAULT_KERNEL_SUPPRESSED_CATEGORIES:
828 _global_error_suppressions[category] = True
829
830
erg@google.com35589e62010-11-17 18:58:16 +0000831def ResetNolintSuppressions():
avakulenko@google.com59146752014-08-11 20:20:55 +0000832 """Resets the set of NOLINT suppressions to empty."""
erg@google.com35589e62010-11-17 18:58:16 +0000833 _error_suppressions.clear()
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000834 _global_error_suppressions.clear()
erg@google.com35589e62010-11-17 18:58:16 +0000835
836
837def IsErrorSuppressedByNolint(category, linenum):
838 """Returns true if the specified error category is suppressed on this line.
839
840 Consults the global error_suppressions map populated by
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000841 ParseNolintSuppressions/ProcessGlobalSuppresions/ResetNolintSuppressions.
erg@google.com35589e62010-11-17 18:58:16 +0000842
843 Args:
844 category: str, the category of the error.
845 linenum: int, the current line number.
846 Returns:
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000847 bool, True iff the error should be suppressed due to a NOLINT comment or
848 global suppression.
erg@google.com35589e62010-11-17 18:58:16 +0000849 """
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000850 return (_global_error_suppressions.get(category, False) or
851 linenum in _error_suppressions.get(category, set()) or
erg@google.com35589e62010-11-17 18:58:16 +0000852 linenum in _error_suppressions.get(None, set()))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000853
avakulenko@google.comd39bbb52014-06-04 22:55:20 +0000854
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000855def Match(pattern, s):
856 """Matches the string with the pattern, caching the compiled regexp."""
857 # The regexp compilation caching is inlined in both Match and Search for
858 # performance reasons; factoring it out into a separate function turns out
859 # to be noticeably expensive.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000860 if pattern not in _regexp_compile_cache:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000861 _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
862 return _regexp_compile_cache[pattern].match(s)
863
864
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000865def ReplaceAll(pattern, rep, s):
866 """Replaces instances of pattern in a string with a replacement.
867
868 The compiled regex is kept in a cache shared by Match and Search.
869
870 Args:
871 pattern: regex pattern
872 rep: replacement text
873 s: search string
874
875 Returns:
876 string with replacements made (or original string if no replacements)
877 """
878 if pattern not in _regexp_compile_cache:
879 _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
880 return _regexp_compile_cache[pattern].sub(rep, s)
881
882
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000883def Search(pattern, s):
884 """Searches the string for the pattern, caching the compiled regexp."""
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000885 if pattern not in _regexp_compile_cache:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000886 _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
887 return _regexp_compile_cache[pattern].search(s)
888
889
avakulenko@chromium.org764ce712016-05-06 23:03:41 +0000890def _IsSourceExtension(s):
891 """File extension (excluding dot) matches a source file extension."""
892 return s in ('c', 'cc', 'cpp', 'cxx')
893
894
avakulenko@google.com59146752014-08-11 20:20:55 +0000895class _IncludeState(object):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000896 """Tracks line numbers for includes, and the order in which includes appear.
897
avakulenko@google.com59146752014-08-11 20:20:55 +0000898 include_list contains list of lists of (header, line number) pairs.
899 It's a lists of lists rather than just one flat list to make it
900 easier to update across preprocessor boundaries.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000901
902 Call CheckNextIncludeOrder() once for each header in the file, passing
903 in the type constants defined above. Calls in an illegal order will
904 raise an _IncludeError with an appropriate error message.
905
906 """
907 # self._section will move monotonically through this set. If it ever
908 # needs to move backwards, CheckNextIncludeOrder will raise an error.
909 _INITIAL_SECTION = 0
910 _MY_H_SECTION = 1
911 _C_SECTION = 2
912 _CPP_SECTION = 3
913 _OTHER_H_SECTION = 4
914
915 _TYPE_NAMES = {
916 _C_SYS_HEADER: 'C system header',
917 _CPP_SYS_HEADER: 'C++ system header',
918 _LIKELY_MY_HEADER: 'header this file implements',
919 _POSSIBLE_MY_HEADER: 'header this file may implement',
920 _OTHER_HEADER: 'other header',
921 }
922 _SECTION_NAMES = {
923 _INITIAL_SECTION: "... nothing. (This can't be an error.)",
924 _MY_H_SECTION: 'a header this file implements',
925 _C_SECTION: 'C system header',
926 _CPP_SECTION: 'C++ system header',
927 _OTHER_H_SECTION: 'other header',
928 }
929
930 def __init__(self):
avakulenko@google.com59146752014-08-11 20:20:55 +0000931 self.include_list = [[]]
932 self.ResetSection('')
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000933
avakulenko@google.com59146752014-08-11 20:20:55 +0000934 def FindHeader(self, header):
935 """Check if a header has already been included.
936
937 Args:
938 header: header to check.
939 Returns:
940 Line number of previous occurrence, or -1 if the header has not
941 been seen before.
942 """
943 for section_list in self.include_list:
944 for f in section_list:
945 if f[0] == header:
946 return f[1]
947 return -1
948
949 def ResetSection(self, directive):
950 """Reset section checking for preprocessor directive.
951
952 Args:
953 directive: preprocessor directive (e.g. "if", "else").
954 """
erg@google.com26970fa2009-11-17 18:07:32 +0000955 # The name of the current section.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +0000956 self._section = self._INITIAL_SECTION
erg@google.com26970fa2009-11-17 18:07:32 +0000957 # The path of last found header.
958 self._last_header = ''
959
avakulenko@google.com59146752014-08-11 20:20:55 +0000960 # Update list of includes. Note that we never pop from the
961 # include list.
962 if directive in ('if', 'ifdef', 'ifndef'):
963 self.include_list.append([])
964 elif directive in ('else', 'elif'):
965 self.include_list[-1] = []
966
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000967 def SetLastHeader(self, header_path):
968 self._last_header = header_path
969
erg@google.com26970fa2009-11-17 18:07:32 +0000970 def CanonicalizeAlphabeticalOrder(self, header_path):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +0000971 """Returns a path canonicalized for alphabetical comparison.
erg@google.com26970fa2009-11-17 18:07:32 +0000972
973 - replaces "-" with "_" so they both cmp the same.
974 - removes '-inl' since we don't require them to be after the main header.
975 - lowercase everything, just in case.
976
977 Args:
978 header_path: Path to be canonicalized.
979
980 Returns:
981 Canonicalized path.
982 """
983 return header_path.replace('-inl.h', '.h').replace('-', '_').lower()
984
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000985 def IsInAlphabeticalOrder(self, clean_lines, linenum, header_path):
erg@google.com26970fa2009-11-17 18:07:32 +0000986 """Check if a header is in alphabetical order with the previous header.
987
988 Args:
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000989 clean_lines: A CleansedLines instance containing the file.
990 linenum: The number of the line to check.
991 header_path: Canonicalized header to be checked.
erg@google.com26970fa2009-11-17 18:07:32 +0000992
993 Returns:
994 Returns true if the header is in alphabetical order.
995 """
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +0000996 # If previous section is different from current section, _last_header will
997 # be reset to empty string, so it's always less than current header.
998 #
999 # If previous line was a blank line, assume that the headers are
1000 # intentionally sorted the way they are.
1001 if (self._last_header > header_path and
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001002 Match(r'^\s*#\s*include\b', clean_lines.elided[linenum - 1])):
erg@google.com26970fa2009-11-17 18:07:32 +00001003 return False
erg@google.com26970fa2009-11-17 18:07:32 +00001004 return True
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001005
1006 def CheckNextIncludeOrder(self, header_type):
1007 """Returns a non-empty error message if the next header is out of order.
1008
1009 This function also updates the internal state to be ready to check
1010 the next include.
1011
1012 Args:
1013 header_type: One of the _XXX_HEADER constants defined above.
1014
1015 Returns:
1016 The empty string if the header is in the right order, or an
1017 error message describing what's wrong.
1018
1019 """
1020 error_message = ('Found %s after %s' %
1021 (self._TYPE_NAMES[header_type],
1022 self._SECTION_NAMES[self._section]))
1023
erg@google.com26970fa2009-11-17 18:07:32 +00001024 last_section = self._section
1025
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001026 if header_type == _C_SYS_HEADER:
1027 if self._section <= self._C_SECTION:
1028 self._section = self._C_SECTION
1029 else:
erg@google.com26970fa2009-11-17 18:07:32 +00001030 self._last_header = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001031 return error_message
1032 elif header_type == _CPP_SYS_HEADER:
1033 if self._section <= self._CPP_SECTION:
1034 self._section = self._CPP_SECTION
1035 else:
erg@google.com26970fa2009-11-17 18:07:32 +00001036 self._last_header = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001037 return error_message
1038 elif header_type == _LIKELY_MY_HEADER:
1039 if self._section <= self._MY_H_SECTION:
1040 self._section = self._MY_H_SECTION
1041 else:
1042 self._section = self._OTHER_H_SECTION
1043 elif header_type == _POSSIBLE_MY_HEADER:
1044 if self._section <= self._MY_H_SECTION:
1045 self._section = self._MY_H_SECTION
1046 else:
1047 # This will always be the fallback because we're not sure
1048 # enough that the header is associated with this file.
1049 self._section = self._OTHER_H_SECTION
1050 else:
1051 assert header_type == _OTHER_HEADER
1052 self._section = self._OTHER_H_SECTION
1053
erg@google.com26970fa2009-11-17 18:07:32 +00001054 if last_section != self._section:
1055 self._last_header = ''
1056
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001057 return ''
1058
1059
1060class _CppLintState(object):
1061 """Maintains module-wide state.."""
1062
1063 def __init__(self):
1064 self.verbose_level = 1 # global setting.
1065 self.error_count = 0 # global count of reported errors
erg@google.com6317a9c2009-06-25 00:28:19 +00001066 # filters to apply when emitting error messages
1067 self.filters = _DEFAULT_FILTERS[:]
avakulenko@google.com17449932014-07-28 22:13:33 +00001068 # backup of filter list. Used to restore the state after each file.
1069 self._filters_backup = self.filters[:]
erg@google.com26970fa2009-11-17 18:07:32 +00001070 self.counting = 'total' # In what way are we counting errors?
1071 self.errors_by_category = {} # string to int dict storing error counts
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001072
1073 # output format:
1074 # "emacs" - format that emacs can parse (default)
1075 # "vs7" - format that Microsoft Visual Studio 7 can parse
1076 self.output_format = 'emacs'
1077
1078 def SetOutputFormat(self, output_format):
1079 """Sets the output format for errors."""
1080 self.output_format = output_format
1081
1082 def SetVerboseLevel(self, level):
1083 """Sets the module's verbosity, and returns the previous setting."""
1084 last_verbose_level = self.verbose_level
1085 self.verbose_level = level
1086 return last_verbose_level
1087
erg@google.com26970fa2009-11-17 18:07:32 +00001088 def SetCountingStyle(self, counting_style):
1089 """Sets the module's counting options."""
1090 self.counting = counting_style
1091
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001092 def SetFilters(self, filters):
1093 """Sets the error-message filters.
1094
1095 These filters are applied when deciding whether to emit a given
1096 error message.
1097
1098 Args:
1099 filters: A string of comma-separated filters (eg "+whitespace/indent").
1100 Each filter should start with + or -; else we die.
erg@google.com6317a9c2009-06-25 00:28:19 +00001101
1102 Raises:
1103 ValueError: The comma-separated filters did not all start with '+' or '-'.
1104 E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter"
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001105 """
erg@google.com6317a9c2009-06-25 00:28:19 +00001106 # Default filters always have less priority than the flag ones.
1107 self.filters = _DEFAULT_FILTERS[:]
avakulenko@google.com17449932014-07-28 22:13:33 +00001108 self.AddFilters(filters)
1109
1110 def AddFilters(self, filters):
1111 """ Adds more filters to the existing list of error-message filters. """
erg@google.com6317a9c2009-06-25 00:28:19 +00001112 for filt in filters.split(','):
1113 clean_filt = filt.strip()
1114 if clean_filt:
1115 self.filters.append(clean_filt)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001116 for filt in self.filters:
1117 if not (filt.startswith('+') or filt.startswith('-')):
1118 raise ValueError('Every filter in --filters must start with + or -'
1119 ' (%s does not)' % filt)
1120
avakulenko@google.com17449932014-07-28 22:13:33 +00001121 def BackupFilters(self):
1122 """ Saves the current filter list to backup storage."""
1123 self._filters_backup = self.filters[:]
1124
1125 def RestoreFilters(self):
1126 """ Restores filters previously backed up."""
1127 self.filters = self._filters_backup[:]
1128
erg@google.com26970fa2009-11-17 18:07:32 +00001129 def ResetErrorCounts(self):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001130 """Sets the module's error statistic back to zero."""
1131 self.error_count = 0
erg@google.com26970fa2009-11-17 18:07:32 +00001132 self.errors_by_category = {}
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001133
erg@google.com26970fa2009-11-17 18:07:32 +00001134 def IncrementErrorCount(self, category):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001135 """Bumps the module's error statistic."""
1136 self.error_count += 1
erg@google.com26970fa2009-11-17 18:07:32 +00001137 if self.counting in ('toplevel', 'detailed'):
1138 if self.counting != 'detailed':
1139 category = category.split('/')[0]
1140 if category not in self.errors_by_category:
1141 self.errors_by_category[category] = 0
1142 self.errors_by_category[category] += 1
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001143
erg@google.com26970fa2009-11-17 18:07:32 +00001144 def PrintErrorCounts(self):
1145 """Print a summary of errors by category, and the total."""
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +00001146 for category, count in self.errors_by_category.items():
erg@google.com26970fa2009-11-17 18:07:32 +00001147 sys.stderr.write('Category \'%s\' errors found: %d\n' %
1148 (category, count))
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00001149 sys.stderr.write('Total errors found: %d\n' % self.error_count)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001150
1151_cpplint_state = _CppLintState()
1152
1153
1154def _OutputFormat():
1155 """Gets the module's output format."""
1156 return _cpplint_state.output_format
1157
1158
1159def _SetOutputFormat(output_format):
1160 """Sets the module's output format."""
1161 _cpplint_state.SetOutputFormat(output_format)
1162
1163
1164def _VerboseLevel():
1165 """Returns the module's verbosity setting."""
1166 return _cpplint_state.verbose_level
1167
1168
1169def _SetVerboseLevel(level):
1170 """Sets the module's verbosity, and returns the previous setting."""
1171 return _cpplint_state.SetVerboseLevel(level)
1172
1173
erg@google.com26970fa2009-11-17 18:07:32 +00001174def _SetCountingStyle(level):
1175 """Sets the module's counting options."""
1176 _cpplint_state.SetCountingStyle(level)
1177
1178
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001179def _Filters():
1180 """Returns the module's list of output filters, as a list."""
1181 return _cpplint_state.filters
1182
1183
1184def _SetFilters(filters):
1185 """Sets the module's error-message filters.
1186
1187 These filters are applied when deciding whether to emit a given
1188 error message.
1189
1190 Args:
1191 filters: A string of comma-separated filters (eg "whitespace/indent").
1192 Each filter should start with + or -; else we die.
1193 """
1194 _cpplint_state.SetFilters(filters)
1195
avakulenko@google.com17449932014-07-28 22:13:33 +00001196def _AddFilters(filters):
1197 """Adds more filter overrides.
avakulenko@google.com59146752014-08-11 20:20:55 +00001198
avakulenko@google.com17449932014-07-28 22:13:33 +00001199 Unlike _SetFilters, this function does not reset the current list of filters
1200 available.
1201
1202 Args:
1203 filters: A string of comma-separated filters (eg "whitespace/indent").
1204 Each filter should start with + or -; else we die.
1205 """
1206 _cpplint_state.AddFilters(filters)
1207
1208def _BackupFilters():
1209 """ Saves the current filter list to backup storage."""
1210 _cpplint_state.BackupFilters()
1211
1212def _RestoreFilters():
1213 """ Restores filters previously backed up."""
1214 _cpplint_state.RestoreFilters()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001215
1216class _FunctionState(object):
1217 """Tracks current function name and the number of lines in its body."""
1218
1219 _NORMAL_TRIGGER = 250 # for --v=0, 500 for --v=1, etc.
1220 _TEST_TRIGGER = 400 # about 50% more than _NORMAL_TRIGGER.
1221
1222 def __init__(self):
1223 self.in_a_function = False
1224 self.lines_in_function = 0
1225 self.current_function = ''
1226
1227 def Begin(self, function_name):
1228 """Start analyzing function body.
1229
1230 Args:
1231 function_name: The name of the function being tracked.
1232 """
1233 self.in_a_function = True
1234 self.lines_in_function = 0
1235 self.current_function = function_name
1236
1237 def Count(self):
1238 """Count line in current function body."""
1239 if self.in_a_function:
1240 self.lines_in_function += 1
1241
1242 def Check(self, error, filename, linenum):
1243 """Report if too many lines in function body.
1244
1245 Args:
1246 error: The function to call with any errors found.
1247 filename: The name of the current file.
1248 linenum: The number of the line to check.
1249 """
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00001250 if not self.in_a_function:
1251 return
1252
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001253 if Match(r'T(EST|est)', self.current_function):
1254 base_trigger = self._TEST_TRIGGER
1255 else:
1256 base_trigger = self._NORMAL_TRIGGER
1257 trigger = base_trigger * 2**_VerboseLevel()
1258
1259 if self.lines_in_function > trigger:
1260 error_level = int(math.log(self.lines_in_function / base_trigger, 2))
1261 # 50 => 0, 100 => 1, 200 => 2, 400 => 3, 800 => 4, 1600 => 5, ...
1262 if error_level > 5:
1263 error_level = 5
1264 error(filename, linenum, 'readability/fn_size', error_level,
1265 'Small and focused functions are preferred:'
1266 ' %s has %d non-comment lines'
1267 ' (error triggered by exceeding %d lines).' % (
1268 self.current_function, self.lines_in_function, trigger))
1269
1270 def End(self):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00001271 """Stop analyzing function body."""
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001272 self.in_a_function = False
1273
1274
1275class _IncludeError(Exception):
1276 """Indicates a problem with the include order in a file."""
1277 pass
1278
1279
avakulenko@google.com59146752014-08-11 20:20:55 +00001280class FileInfo(object):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001281 """Provides utility functions for filenames.
1282
1283 FileInfo provides easy access to the components of a file's path
1284 relative to the project root.
1285 """
1286
1287 def __init__(self, filename):
1288 self._filename = filename
1289
1290 def FullName(self):
1291 """Make Windows paths like Unix."""
1292 return os.path.abspath(self._filename).replace('\\', '/')
1293
1294 def RepositoryName(self):
Edward Lemur6d31ed52019-12-02 23:00:00 +00001295 r"""FullName after removing the local path to the repository.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001296
1297 If we have a real absolute path name here we can try to do something smart:
1298 detecting the root of the checkout and truncating /path/to/checkout from
1299 the name so that we get header guards that don't include things like
1300 "C:\Documents and Settings\..." or "/home/username/..." in them and thus
1301 people on different computers who have checked the source out to different
1302 locations won't see bogus errors.
1303 """
1304 fullname = self.FullName()
1305
1306 if os.path.exists(fullname):
1307 project_dir = os.path.dirname(fullname)
1308
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00001309 if _project_root:
1310 prefix = os.path.commonprefix([_project_root, project_dir])
1311 return fullname[len(prefix) + 1:]
1312
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001313 if os.path.exists(os.path.join(project_dir, ".svn")):
1314 # If there's a .svn file in the current directory, we recursively look
1315 # up the directory tree for the top of the SVN checkout
1316 root_dir = project_dir
1317 one_up_dir = os.path.dirname(root_dir)
1318 while os.path.exists(os.path.join(one_up_dir, ".svn")):
1319 root_dir = os.path.dirname(root_dir)
1320 one_up_dir = os.path.dirname(one_up_dir)
1321
1322 prefix = os.path.commonprefix([root_dir, project_dir])
1323 return fullname[len(prefix) + 1:]
1324
erg@chromium.org7956a872011-11-30 01:44:03 +00001325 # Not SVN <= 1.6? Try to find a git, hg, or svn top level directory by
1326 # searching up from the current path.
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00001327 root_dir = os.path.dirname(fullname)
1328 while (root_dir != os.path.dirname(root_dir) and
1329 not os.path.exists(os.path.join(root_dir, ".git")) and
1330 not os.path.exists(os.path.join(root_dir, ".hg")) and
1331 not os.path.exists(os.path.join(root_dir, ".svn"))):
1332 root_dir = os.path.dirname(root_dir)
erg@google.com35589e62010-11-17 18:58:16 +00001333
1334 if (os.path.exists(os.path.join(root_dir, ".git")) or
erg@chromium.org7956a872011-11-30 01:44:03 +00001335 os.path.exists(os.path.join(root_dir, ".hg")) or
1336 os.path.exists(os.path.join(root_dir, ".svn"))):
erg@google.com35589e62010-11-17 18:58:16 +00001337 prefix = os.path.commonprefix([root_dir, project_dir])
1338 return fullname[len(prefix) + 1:]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001339
1340 # Don't know what to do; header guard warnings may be wrong...
1341 return fullname
1342
1343 def Split(self):
1344 """Splits the file into the directory, basename, and extension.
1345
1346 For 'chrome/browser/browser.cc', Split() would
1347 return ('chrome/browser', 'browser', '.cc')
1348
1349 Returns:
1350 A tuple of (directory, basename, extension).
1351 """
1352
1353 googlename = self.RepositoryName()
1354 project, rest = os.path.split(googlename)
1355 return (project,) + os.path.splitext(rest)
1356
1357 def BaseName(self):
1358 """File base name - text after the final slash, before the final period."""
1359 return self.Split()[1]
1360
1361 def Extension(self):
1362 """File extension - text following the final period."""
1363 return self.Split()[2]
1364
1365 def NoExtension(self):
1366 """File has no source file extension."""
1367 return '/'.join(self.Split()[0:2])
1368
1369 def IsSource(self):
1370 """File has a source file extension."""
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00001371 return _IsSourceExtension(self.Extension()[1:])
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001372
1373
erg@google.com35589e62010-11-17 18:58:16 +00001374def _ShouldPrintError(category, confidence, linenum):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00001375 """If confidence >= verbose, category passes filter and is not suppressed."""
erg@google.com35589e62010-11-17 18:58:16 +00001376
1377 # There are three ways we might decide not to print an error message:
1378 # a "NOLINT(category)" comment appears in the source,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001379 # the verbosity level isn't high enough, or the filters filter it out.
erg@google.com35589e62010-11-17 18:58:16 +00001380 if IsErrorSuppressedByNolint(category, linenum):
1381 return False
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001382
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001383 if confidence < _cpplint_state.verbose_level:
1384 return False
1385
1386 is_filtered = False
1387 for one_filter in _Filters():
1388 if one_filter.startswith('-'):
1389 if category.startswith(one_filter[1:]):
1390 is_filtered = True
1391 elif one_filter.startswith('+'):
1392 if category.startswith(one_filter[1:]):
1393 is_filtered = False
1394 else:
1395 assert False # should have been checked for in SetFilter.
1396 if is_filtered:
1397 return False
1398
1399 return True
1400
1401
1402def Error(filename, linenum, category, confidence, message):
1403 """Logs the fact we've found a lint error.
1404
1405 We log where the error was found, and also our confidence in the error,
1406 that is, how certain we are this is a legitimate style regression, and
1407 not a misidentification or a use that's sometimes justified.
1408
erg@google.com35589e62010-11-17 18:58:16 +00001409 False positives can be suppressed by the use of
1410 "cpplint(category)" comments on the offending line. These are
1411 parsed into _error_suppressions.
1412
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001413 Args:
1414 filename: The name of the file containing the error.
1415 linenum: The number of the line containing the error.
1416 category: A string used to describe the "category" this bug
1417 falls under: "whitespace", say, or "runtime". Categories
1418 may have a hierarchy separated by slashes: "whitespace/indent".
1419 confidence: A number from 1-5 representing a confidence score for
1420 the error, with 5 meaning that we are certain of the problem,
1421 and 1 meaning that it could be a legitimate construct.
1422 message: The error message.
1423 """
erg@google.com35589e62010-11-17 18:58:16 +00001424 if _ShouldPrintError(category, confidence, linenum):
erg@google.com26970fa2009-11-17 18:07:32 +00001425 _cpplint_state.IncrementErrorCount(category)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001426 if _cpplint_state.output_format == 'vs7':
Bruce Dawsonac964702022-05-27 17:08:46 +00001427 sys.stderr.write('%s(%s): (cpplint) %s [%s] [%d]\n' %
1428 (filename, linenum, message, category, confidence))
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001429 elif _cpplint_state.output_format == 'eclipse':
Bruce Dawsonac964702022-05-27 17:08:46 +00001430 sys.stderr.write('%s:%s: (cpplint) warning: %s [%s] [%d]\n' %
1431 (filename, linenum, message, category, confidence))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001432 else:
Bruce Dawsonac964702022-05-27 17:08:46 +00001433 sys.stderr.write('%s:%s: (cpplint) %s [%s] [%d]\n' %
1434 (filename, linenum, message, category, confidence))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001435
1436
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001437# Matches standard C++ escape sequences per 2.13.2.3 of the C++ standard.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001438_RE_PATTERN_CLEANSE_LINE_ESCAPES = re.compile(
1439 r'\\([abfnrtv?"\\\']|\d+|x[0-9a-fA-F]+)')
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001440# Match a single C style comment on the same line.
1441_RE_PATTERN_C_COMMENTS = r'/\*(?:[^*]|\*(?!/))*\*/'
1442# Matches multi-line C style comments.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001443# This RE is a little bit more complicated than one might expect, because we
1444# have to take care of space removals tools so we can handle comments inside
1445# statements better.
1446# The current rule is: We only clear spaces from both sides when we're at the
1447# end of the line. Otherwise, we try to remove spaces from the right side,
1448# if this doesn't work we try on left side but only if there's a non-character
1449# on the right.
1450_RE_PATTERN_CLEANSE_LINE_C_COMMENTS = re.compile(
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001451 r'(\s*' + _RE_PATTERN_C_COMMENTS + r'\s*$|' +
1452 _RE_PATTERN_C_COMMENTS + r'\s+|' +
1453 r'\s+' + _RE_PATTERN_C_COMMENTS + r'(?=\W)|' +
1454 _RE_PATTERN_C_COMMENTS + r')')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001455
1456
1457def IsCppString(line):
1458 """Does line terminate so, that the next symbol is in string constant.
1459
1460 This function does not consider single-line nor multi-line comments.
1461
1462 Args:
1463 line: is a partial line of code starting from the 0..n.
1464
1465 Returns:
1466 True, if next character appended to 'line' is inside a
1467 string constant.
1468 """
1469
1470 line = line.replace(r'\\', 'XX') # after this, \\" does not match to \"
1471 return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1
1472
1473
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001474def CleanseRawStrings(raw_lines):
1475 """Removes C++11 raw strings from lines.
1476
1477 Before:
1478 static const char kData[] = R"(
1479 multi-line string
1480 )";
1481
1482 After:
1483 static const char kData[] = ""
1484 (replaced by blank line)
1485 "";
1486
1487 Args:
1488 raw_lines: list of raw lines.
1489
1490 Returns:
1491 list of lines with C++11 raw strings replaced by empty strings.
1492 """
1493
1494 delimiter = None
1495 lines_without_raw_strings = []
1496 for line in raw_lines:
1497 if delimiter:
1498 # Inside a raw string, look for the end
1499 end = line.find(delimiter)
1500 if end >= 0:
1501 # Found the end of the string, match leading space for this
1502 # line and resume copying the original lines, and also insert
1503 # a "" on the last line.
1504 leading_space = Match(r'^(\s*)\S', line)
1505 line = leading_space.group(1) + '""' + line[end + len(delimiter):]
1506 delimiter = None
1507 else:
1508 # Haven't found the end yet, append a blank line.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001509 line = '""'
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001510
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001511 # Look for beginning of a raw string, and replace them with
1512 # empty strings. This is done in a loop to handle multiple raw
1513 # strings on the same line.
1514 while delimiter is None:
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001515 # Look for beginning of a raw string.
1516 # See 2.14.15 [lex.string] for syntax.
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00001517 #
1518 # Once we have matched a raw string, we check the prefix of the
1519 # line to make sure that the line is not part of a single line
1520 # comment. It's done this way because we remove raw strings
1521 # before removing comments as opposed to removing comments
1522 # before removing raw strings. This is because there are some
1523 # cpplint checks that requires the comments to be preserved, but
1524 # we don't want to check comments that are inside raw strings.
1525 matched = Match(r'^(.*?)\b(?:R|u8R|uR|UR|LR)"([^\s\\()]*)\((.*)$', line)
1526 if (matched and
1527 not Match(r'^([^\'"]|\'(\\.|[^\'])*\'|"(\\.|[^"])*")*//',
1528 matched.group(1))):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001529 delimiter = ')' + matched.group(2) + '"'
1530
1531 end = matched.group(3).find(delimiter)
1532 if end >= 0:
1533 # Raw string ended on same line
1534 line = (matched.group(1) + '""' +
1535 matched.group(3)[end + len(delimiter):])
1536 delimiter = None
1537 else:
1538 # Start of a multi-line raw string
1539 line = matched.group(1) + '""'
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001540 else:
1541 break
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001542
1543 lines_without_raw_strings.append(line)
1544
1545 # TODO(unknown): if delimiter is not None here, we might want to
1546 # emit a warning for unterminated string.
1547 return lines_without_raw_strings
1548
1549
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001550def FindNextMultiLineCommentStart(lines, lineix):
1551 """Find the beginning marker for a multiline comment."""
1552 while lineix < len(lines):
1553 if lines[lineix].strip().startswith('/*'):
1554 # Only return this marker if the comment goes beyond this line
1555 if lines[lineix].strip().find('*/', 2) < 0:
1556 return lineix
1557 lineix += 1
1558 return len(lines)
1559
1560
1561def FindNextMultiLineCommentEnd(lines, lineix):
1562 """We are inside a comment, find the end marker."""
1563 while lineix < len(lines):
1564 if lines[lineix].strip().endswith('*/'):
1565 return lineix
1566 lineix += 1
1567 return len(lines)
1568
1569
1570def RemoveMultiLineCommentsFromRange(lines, begin, end):
1571 """Clears a range of lines for multi-line comments."""
1572 # Having // dummy comments makes the lines non-empty, so we will not get
1573 # unnecessary blank line warnings later in the code.
1574 for i in range(begin, end):
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001575 lines[i] = '/**/'
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001576
1577
1578def RemoveMultiLineComments(filename, lines, error):
1579 """Removes multiline (c-style) comments from lines."""
1580 lineix = 0
1581 while lineix < len(lines):
1582 lineix_begin = FindNextMultiLineCommentStart(lines, lineix)
1583 if lineix_begin >= len(lines):
1584 return
1585 lineix_end = FindNextMultiLineCommentEnd(lines, lineix_begin)
1586 if lineix_end >= len(lines):
1587 error(filename, lineix_begin + 1, 'readability/multiline_comment', 5,
1588 'Could not find end of multi-line comment')
1589 return
1590 RemoveMultiLineCommentsFromRange(lines, lineix_begin, lineix_end + 1)
1591 lineix = lineix_end + 1
1592
1593
1594def CleanseComments(line):
1595 """Removes //-comments and single-line C-style /* */ comments.
1596
1597 Args:
1598 line: A line of C++ source.
1599
1600 Returns:
1601 The line with single-line comments removed.
1602 """
1603 commentpos = line.find('//')
1604 if commentpos != -1 and not IsCppString(line[:commentpos]):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00001605 line = line[:commentpos].rstrip()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001606 # get rid of /* ... */
1607 return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line)
1608
1609
erg@google.com6317a9c2009-06-25 00:28:19 +00001610class CleansedLines(object):
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001611 """Holds 4 copies of all lines with different preprocessing applied to them.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001612
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001613 1) elided member contains lines without strings and comments.
1614 2) lines member contains lines without comments.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001615 3) raw_lines member contains all the lines without processing.
avakulenko@google.com255f2be2014-12-05 22:19:55 +00001616 4) lines_without_raw_strings member is same as raw_lines, but with C++11 raw
1617 strings removed.
1618 All these members are of <type 'list'>, and of the same length.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001619 """
1620
1621 def __init__(self, lines):
1622 self.elided = []
1623 self.lines = []
1624 self.raw_lines = lines
1625 self.num_lines = len(lines)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001626 self.lines_without_raw_strings = CleanseRawStrings(lines)
1627 for linenum in range(len(self.lines_without_raw_strings)):
1628 self.lines.append(CleanseComments(
1629 self.lines_without_raw_strings[linenum]))
1630 elided = self._CollapseStrings(self.lines_without_raw_strings[linenum])
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001631 self.elided.append(CleanseComments(elided))
1632
1633 def NumLines(self):
1634 """Returns the number of lines represented."""
1635 return self.num_lines
1636
1637 @staticmethod
1638 def _CollapseStrings(elided):
1639 """Collapses strings and chars on a line to simple "" or '' blocks.
1640
1641 We nix strings first so we're not fooled by text like '"http://"'
1642
1643 Args:
1644 elided: The line being processed.
1645
1646 Returns:
1647 The line with collapsed strings.
1648 """
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001649 if _RE_PATTERN_INCLUDE.match(elided):
1650 return elided
1651
1652 # Remove escaped characters first to make quote/single quote collapsing
1653 # basic. Things that look like escaped characters shouldn't occur
1654 # outside of strings and chars.
1655 elided = _RE_PATTERN_CLEANSE_LINE_ESCAPES.sub('', elided)
1656
1657 # Replace quoted strings and digit separators. Both single quotes
1658 # and double quotes are processed in the same loop, otherwise
1659 # nested quotes wouldn't work.
1660 collapsed = ''
1661 while True:
1662 # Find the first quote character
1663 match = Match(r'^([^\'"]*)([\'"])(.*)$', elided)
1664 if not match:
1665 collapsed += elided
1666 break
1667 head, quote, tail = match.groups()
1668
1669 if quote == '"':
1670 # Collapse double quoted strings
1671 second_quote = tail.find('"')
1672 if second_quote >= 0:
1673 collapsed += head + '""'
1674 elided = tail[second_quote + 1:]
1675 else:
1676 # Unmatched double quote, don't bother processing the rest
1677 # of the line since this is probably a multiline string.
1678 collapsed += elided
1679 break
1680 else:
1681 # Found single quote, check nearby text to eliminate digit separators.
1682 #
1683 # There is no special handling for floating point here, because
1684 # the integer/fractional/exponent parts would all be parsed
1685 # correctly as long as there are digits on both sides of the
1686 # separator. So we are fine as long as we don't see something
1687 # like "0.'3" (gcc 4.9.0 will not allow this literal).
1688 if Search(r'\b(?:0[bBxX]?|[1-9])[0-9a-fA-F]*$', head):
1689 match_literal = Match(r'^((?:\'?[0-9a-zA-Z_])*)(.*)$', "'" + tail)
1690 collapsed += head + match_literal.group(1).replace("'", '')
1691 elided = match_literal.group(2)
1692 else:
1693 second_quote = tail.find('\'')
1694 if second_quote >= 0:
1695 collapsed += head + "''"
1696 elided = tail[second_quote + 1:]
1697 else:
1698 # Unmatched single quote
1699 collapsed += elided
1700 break
1701
1702 return collapsed
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001703
1704
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001705def FindEndOfExpressionInLine(line, startpos, stack):
1706 """Find the position just after the end of current parenthesized expression.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001707
1708 Args:
1709 line: a CleansedLines line.
1710 startpos: start searching at this position.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001711 stack: nesting stack at startpos.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001712
1713 Returns:
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001714 On finding matching end: (index just after matching end, None)
1715 On finding an unclosed expression: (-1, None)
1716 Otherwise: (-1, new stack at end of this line)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001717 """
Edward Lemur6d31ed52019-12-02 23:00:00 +00001718 for i in range(startpos, len(line)):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001719 char = line[i]
1720 if char in '([{':
1721 # Found start of parenthesized expression, push to expression stack
1722 stack.append(char)
1723 elif char == '<':
1724 # Found potential start of template argument list
1725 if i > 0 and line[i - 1] == '<':
1726 # Left shift operator
1727 if stack and stack[-1] == '<':
1728 stack.pop()
1729 if not stack:
1730 return (-1, None)
1731 elif i > 0 and Search(r'\boperator\s*$', line[0:i]):
1732 # operator<, don't add to stack
1733 continue
1734 else:
1735 # Tentative start of template argument list
1736 stack.append('<')
1737 elif char in ')]}':
1738 # Found end of parenthesized expression.
1739 #
1740 # If we are currently expecting a matching '>', the pending '<'
1741 # must have been an operator. Remove them from expression stack.
1742 while stack and stack[-1] == '<':
1743 stack.pop()
1744 if not stack:
1745 return (-1, None)
1746 if ((stack[-1] == '(' and char == ')') or
1747 (stack[-1] == '[' and char == ']') or
1748 (stack[-1] == '{' and char == '}')):
1749 stack.pop()
1750 if not stack:
1751 return (i + 1, None)
1752 else:
1753 # Mismatched parentheses
1754 return (-1, None)
1755 elif char == '>':
1756 # Found potential end of template argument list.
1757
1758 # Ignore "->" and operator functions
1759 if (i > 0 and
1760 (line[i - 1] == '-' or Search(r'\boperator\s*$', line[0:i - 1]))):
1761 continue
1762
1763 # Pop the stack if there is a matching '<'. Otherwise, ignore
1764 # this '>' since it must be an operator.
1765 if stack:
1766 if stack[-1] == '<':
1767 stack.pop()
1768 if not stack:
1769 return (i + 1, None)
1770 elif char == ';':
1771 # Found something that look like end of statements. If we are currently
1772 # expecting a '>', the matching '<' must have been an operator, since
1773 # template argument list should not contain statements.
1774 while stack and stack[-1] == '<':
1775 stack.pop()
1776 if not stack:
1777 return (-1, None)
1778
1779 # Did not find end of expression or unbalanced parentheses on this line
1780 return (-1, stack)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001781
1782
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001783def CloseExpression(clean_lines, linenum, pos):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001784 """If input points to ( or { or [ or <, finds the position that closes it.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001785
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001786 If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001787 linenum/pos that correspond to the closing of the expression.
1788
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001789 TODO(unknown): cpplint spends a fair bit of time matching parentheses.
1790 Ideally we would want to index all opening and closing parentheses once
1791 and have CloseExpression be just a simple lookup, but due to preprocessor
1792 tricks, this is not so easy.
1793
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001794 Args:
1795 clean_lines: A CleansedLines instance containing the file.
1796 linenum: The number of the line to check.
1797 pos: A position on the line.
1798
1799 Returns:
1800 A tuple (line, linenum, pos) pointer *past* the closing brace, or
1801 (line, len(lines), -1) if we never find a close. Note we ignore
1802 strings and comments when matching; and the line we return is the
1803 'cleansed' line at linenum.
1804 """
1805
1806 line = clean_lines.elided[linenum]
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001807 if (line[pos] not in '({[<') or Match(r'<[<=]', line[pos:]):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001808 return (line, clean_lines.NumLines(), -1)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001809
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001810 # Check first line
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001811 (end_pos, stack) = FindEndOfExpressionInLine(line, pos, [])
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001812 if end_pos > -1:
1813 return (line, linenum, end_pos)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001814
1815 # Continue scanning forward
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001816 while stack and linenum < clean_lines.NumLines() - 1:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001817 linenum += 1
1818 line = clean_lines.elided[linenum]
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001819 (end_pos, stack) = FindEndOfExpressionInLine(line, 0, stack)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001820 if end_pos > -1:
1821 return (line, linenum, end_pos)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001822
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001823 # Did not find end of expression before end of file, give up
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00001824 return (line, clean_lines.NumLines(), -1)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001825
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001826
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001827def FindStartOfExpressionInLine(line, endpos, stack):
1828 """Find position at the matching start of current expression.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001829
1830 This is almost the reverse of FindEndOfExpressionInLine, but note
1831 that the input position and returned position differs by 1.
1832
1833 Args:
1834 line: a CleansedLines line.
1835 endpos: start searching at this position.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001836 stack: nesting stack at endpos.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001837
1838 Returns:
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001839 On finding matching start: (index at matching start, None)
1840 On finding an unclosed expression: (-1, None)
1841 Otherwise: (-1, new stack at beginning of this line)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001842 """
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001843 i = endpos
1844 while i >= 0:
1845 char = line[i]
1846 if char in ')]}':
1847 # Found end of expression, push to expression stack
1848 stack.append(char)
1849 elif char == '>':
1850 # Found potential end of template argument list.
1851 #
1852 # Ignore it if it's a "->" or ">=" or "operator>"
1853 if (i > 0 and
1854 (line[i - 1] == '-' or
1855 Match(r'\s>=\s', line[i - 1:]) or
1856 Search(r'\boperator\s*$', line[0:i]))):
1857 i -= 1
1858 else:
1859 stack.append('>')
1860 elif char == '<':
1861 # Found potential start of template argument list
1862 if i > 0 and line[i - 1] == '<':
1863 # Left shift operator
1864 i -= 1
1865 else:
1866 # If there is a matching '>', we can pop the expression stack.
1867 # Otherwise, ignore this '<' since it must be an operator.
1868 if stack and stack[-1] == '>':
1869 stack.pop()
1870 if not stack:
1871 return (i, None)
1872 elif char in '([{':
1873 # Found start of expression.
1874 #
1875 # If there are any unmatched '>' on the stack, they must be
1876 # operators. Remove those.
1877 while stack and stack[-1] == '>':
1878 stack.pop()
1879 if not stack:
1880 return (-1, None)
1881 if ((char == '(' and stack[-1] == ')') or
1882 (char == '[' and stack[-1] == ']') or
1883 (char == '{' and stack[-1] == '}')):
1884 stack.pop()
1885 if not stack:
1886 return (i, None)
1887 else:
1888 # Mismatched parentheses
1889 return (-1, None)
1890 elif char == ';':
1891 # Found something that look like end of statements. If we are currently
1892 # expecting a '<', the matching '>' must have been an operator, since
1893 # template argument list should not contain statements.
1894 while stack and stack[-1] == '>':
1895 stack.pop()
1896 if not stack:
1897 return (-1, None)
1898
1899 i -= 1
1900
1901 return (-1, stack)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001902
1903
1904def ReverseCloseExpression(clean_lines, linenum, pos):
1905 """If input points to ) or } or ] or >, finds the position that opens it.
1906
1907 If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the
1908 linenum/pos that correspond to the opening of the expression.
1909
1910 Args:
1911 clean_lines: A CleansedLines instance containing the file.
1912 linenum: The number of the line to check.
1913 pos: A position on the line.
1914
1915 Returns:
1916 A tuple (line, linenum, pos) pointer *at* the opening brace, or
1917 (line, 0, -1) if we never find the matching opening brace. Note
1918 we ignore strings and comments when matching; and the line we
1919 return is the 'cleansed' line at linenum.
1920 """
1921 line = clean_lines.elided[linenum]
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001922 if line[pos] not in ')}]>':
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001923 return (line, 0, -1)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001924
1925 # Check last line
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001926 (start_pos, stack) = FindStartOfExpressionInLine(line, pos, [])
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001927 if start_pos > -1:
1928 return (line, linenum, start_pos)
1929
1930 # Continue scanning backward
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001931 while stack and linenum > 0:
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001932 linenum -= 1
1933 line = clean_lines.elided[linenum]
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001934 (start_pos, stack) = FindStartOfExpressionInLine(line, len(line) - 1, stack)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001935 if start_pos > -1:
1936 return (line, linenum, start_pos)
1937
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001938 # Did not find start of expression before beginning of file, give up
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00001939 return (line, 0, -1)
1940
1941
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001942def CheckForCopyright(filename, lines, error):
1943 """Logs an error if no Copyright message appears at the top of the file."""
1944
1945 # We'll say it should occur by line 10. Don't forget there's a
1946 # dummy line at the front.
Edward Lemur6d31ed52019-12-02 23:00:00 +00001947 for line in range(1, min(len(lines), 11)):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001948 if re.search(r'Copyright', lines[line], re.I): break
1949 else: # means no copyright line was found
1950 error(filename, 0, 'legal/copyright', 5,
1951 'No copyright message found. '
1952 'You should have a line: "Copyright [year] <Copyright Owner>"')
1953
1954
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00001955def GetIndentLevel(line):
1956 """Return the number of leading spaces in line.
1957
1958 Args:
1959 line: A string to check.
1960
1961 Returns:
1962 An integer count of leading spaces, possibly zero.
1963 """
1964 indent = Match(r'^( *)\S', line)
1965 if indent:
1966 return len(indent.group(1))
1967 else:
1968 return 0
1969
1970
David Sanders2f988472022-05-21 01:35:11 +00001971def PathSplitToList(path):
1972 """Returns the path split into a list by the separator.
1973
1974 Args:
1975 path: An absolute or relative path (e.g. '/a/b/c/' or '../a')
1976
1977 Returns:
1978 A list of path components (e.g. ['a', 'b', 'c]).
1979 """
1980 lst = []
1981 while True:
1982 (head, tail) = os.path.split(path)
1983 if head == path: # absolute paths end
1984 lst.append(head)
1985 break
1986 if tail == path: # relative paths end
1987 lst.append(tail)
1988 break
1989
1990 path = head
1991 lst.append(tail)
1992
1993 lst.reverse()
1994 return lst
1995
1996
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00001997def GetHeaderGuardCPPVariable(filename):
1998 """Returns the CPP variable that should be used as a header guard.
1999
2000 Args:
2001 filename: The name of a C++ header file.
2002
2003 Returns:
2004 The CPP variable that should be used as a header guard in the
2005 named file.
2006
2007 """
2008
erg@google.com35589e62010-11-17 18:58:16 +00002009 # Restores original filename in case that cpplint is invoked from Emacs's
2010 # flymake.
2011 filename = re.sub(r'_flymake\.h$', '.h', filename)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002012 filename = re.sub(r'/\.flymake/([^/]*)$', r'/\1', filename)
avakulenko@google.com255f2be2014-12-05 22:19:55 +00002013 # Replace 'c++' with 'cpp'.
2014 filename = filename.replace('C++', 'cpp').replace('c++', 'cpp')
skym@chromium.org3990c412016-02-05 20:55:12 +00002015
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002016 fileinfo = FileInfo(filename)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002017 file_path_from_root = fileinfo.RepositoryName()
David Sanders2f988472022-05-21 01:35:11 +00002018
2019 def FixupPathFromRoot():
2020 if _root_debug:
2021 sys.stderr.write("\n_root fixup, _root = '%s', repository name = '%s'\n"
2022 % (_root, fileinfo.RepositoryName()))
2023
2024 # Process the file path with the --root flag if it was set.
2025 if not _root:
2026 if _root_debug:
2027 sys.stderr.write("_root unspecified\n")
2028 return file_path_from_root
2029
2030 def StripListPrefix(lst, prefix):
2031 # f(['x', 'y'], ['w, z']) -> None (not a valid prefix)
2032 if lst[:len(prefix)] != prefix:
2033 return None
2034 # f(['a, 'b', 'c', 'd'], ['a', 'b']) -> ['c', 'd']
2035 return lst[(len(prefix)):]
2036
2037 # root behavior:
2038 # --root=subdir , lstrips subdir from the header guard
2039 maybe_path = StripListPrefix(PathSplitToList(file_path_from_root),
2040 PathSplitToList(_root))
2041
2042 if _root_debug:
2043 sys.stderr.write(("_root lstrip (maybe_path=%s, file_path_from_root=%s," +
2044 " _root=%s)\n") % (maybe_path, file_path_from_root, _root))
2045
2046 if maybe_path:
2047 return os.path.join(*maybe_path)
2048
2049 # --root=.. , will prepend the outer directory to the header guard
2050 full_path = fileinfo.FullName()
2051 # adapt slashes for windows
2052 root_abspath = os.path.abspath(_root).replace('\\', '/')
2053
2054 maybe_path = StripListPrefix(PathSplitToList(full_path),
2055 PathSplitToList(root_abspath))
2056
2057 if _root_debug:
2058 sys.stderr.write(("_root prepend (maybe_path=%s, full_path=%s, " +
2059 "root_abspath=%s)\n") % (maybe_path, full_path, root_abspath))
2060
2061 if maybe_path:
2062 return os.path.join(*maybe_path)
2063
2064 if _root_debug:
2065 sys.stderr.write("_root ignore, returning %s\n" % (file_path_from_root))
2066
2067 # --root=FAKE_DIR is ignored
2068 return file_path_from_root
2069
2070 file_path_from_root = FixupPathFromRoot()
avakulenko@google.com255f2be2014-12-05 22:19:55 +00002071 return re.sub(r'[^a-zA-Z0-9]', '_', file_path_from_root).upper() + '_'
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002072
2073
avakulenko@google.com255f2be2014-12-05 22:19:55 +00002074def CheckForHeaderGuard(filename, clean_lines, error):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002075 """Checks that the file contains a header guard.
2076
erg@google.com6317a9c2009-06-25 00:28:19 +00002077 Logs an error if no #ifndef header guard is present. For other
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002078 headers, checks that the full pathname is used.
2079
2080 Args:
2081 filename: The name of the C++ header file.
avakulenko@google.com255f2be2014-12-05 22:19:55 +00002082 clean_lines: A CleansedLines instance containing the file.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002083 error: The function to call with any errors found.
2084 """
2085
avakulenko@google.com59146752014-08-11 20:20:55 +00002086 # Don't check for header guards if there are error suppression
2087 # comments somewhere in this file.
2088 #
2089 # Because this is silencing a warning for a nonexistent line, we
2090 # only support the very specific NOLINT(build/header_guard) syntax,
2091 # and not the general NOLINT or NOLINT(*) syntax.
avakulenko@google.com255f2be2014-12-05 22:19:55 +00002092 raw_lines = clean_lines.lines_without_raw_strings
2093 for i in raw_lines:
avakulenko@google.com59146752014-08-11 20:20:55 +00002094 if Search(r'//\s*NOLINT\(build/header_guard\)', i):
2095 return
2096
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002097 cppvar = GetHeaderGuardCPPVariable(filename)
2098
avakulenko@google.com255f2be2014-12-05 22:19:55 +00002099 ifndef = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002100 ifndef_linenum = 0
avakulenko@google.com255f2be2014-12-05 22:19:55 +00002101 define = ''
2102 endif = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002103 endif_linenum = 0
avakulenko@google.com255f2be2014-12-05 22:19:55 +00002104 for linenum, line in enumerate(raw_lines):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002105 linesplit = line.split()
2106 if len(linesplit) >= 2:
2107 # find the first occurrence of #ifndef and #define, save arg
2108 if not ifndef and linesplit[0] == '#ifndef':
2109 # set ifndef to the header guard presented on the #ifndef line.
2110 ifndef = linesplit[1]
2111 ifndef_linenum = linenum
2112 if not define and linesplit[0] == '#define':
2113 define = linesplit[1]
2114 # find the last occurrence of #endif, save entire line
2115 if line.startswith('#endif'):
2116 endif = line
2117 endif_linenum = linenum
2118
avakulenko@google.com255f2be2014-12-05 22:19:55 +00002119 if not ifndef or not define or ifndef != define:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002120 error(filename, 0, 'build/header_guard', 5,
2121 'No #ifndef header guard found, suggested CPP variable is: %s' %
2122 cppvar)
2123 return
2124
2125 # The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__
2126 # for backward compatibility.
erg@google.com35589e62010-11-17 18:58:16 +00002127 if ifndef != cppvar:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002128 error_level = 0
2129 if ifndef != cppvar + '_':
2130 error_level = 5
2131
avakulenko@google.com255f2be2014-12-05 22:19:55 +00002132 ParseNolintSuppressions(filename, raw_lines[ifndef_linenum], ifndef_linenum,
erg@google.com35589e62010-11-17 18:58:16 +00002133 error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002134 error(filename, ifndef_linenum, 'build/header_guard', error_level,
2135 '#ifndef header guard has wrong style, please use: %s' % cppvar)
2136
avakulenko@google.com255f2be2014-12-05 22:19:55 +00002137 # Check for "//" comments on endif line.
2138 ParseNolintSuppressions(filename, raw_lines[endif_linenum], endif_linenum,
2139 error)
2140 match = Match(r'#endif\s*//\s*' + cppvar + r'(_)?\b', endif)
2141 if match:
2142 if match.group(1) == '_':
2143 # Issue low severity warning for deprecated double trailing underscore
2144 error(filename, endif_linenum, 'build/header_guard', 0,
2145 '#endif line should be "#endif // %s"' % cppvar)
erg@chromium.orgc452fea2012-01-26 21:10:45 +00002146 return
2147
avakulenko@google.com255f2be2014-12-05 22:19:55 +00002148 # Didn't find the corresponding "//" comment. If this file does not
2149 # contain any "//" comments at all, it could be that the compiler
2150 # only wants "/**/" comments, look for those instead.
2151 no_single_line_comments = True
Edward Lemur6d31ed52019-12-02 23:00:00 +00002152 for i in range(1, len(raw_lines) - 1):
avakulenko@google.com255f2be2014-12-05 22:19:55 +00002153 line = raw_lines[i]
2154 if Match(r'^(?:(?:\'(?:\.|[^\'])*\')|(?:"(?:\.|[^"])*")|[^\'"])*//', line):
2155 no_single_line_comments = False
2156 break
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002157
avakulenko@google.com255f2be2014-12-05 22:19:55 +00002158 if no_single_line_comments:
2159 match = Match(r'#endif\s*/\*\s*' + cppvar + r'(_)?\s*\*/', endif)
2160 if match:
2161 if match.group(1) == '_':
2162 # Low severity warning for double trailing underscore
2163 error(filename, endif_linenum, 'build/header_guard', 0,
2164 '#endif line should be "#endif /* %s */"' % cppvar)
2165 return
2166
2167 # Didn't find anything
2168 error(filename, endif_linenum, 'build/header_guard', 5,
2169 '#endif line should be "#endif // %s"' % cppvar)
2170
2171
2172def CheckHeaderFileIncluded(filename, include_state, error):
2173 """Logs an error if a .cc file does not include its header."""
2174
2175 # Do not check test files
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002176 fileinfo = FileInfo(filename)
2177 if Search(_TEST_FILE_SUFFIX, fileinfo.BaseName()):
avakulenko@google.com255f2be2014-12-05 22:19:55 +00002178 return
2179
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002180 headerfile = filename[0:len(filename) - len(fileinfo.Extension())] + '.h'
avakulenko@google.com255f2be2014-12-05 22:19:55 +00002181 if not os.path.exists(headerfile):
2182 return
2183 headername = FileInfo(headerfile).RepositoryName()
2184 first_include = 0
2185 for section_list in include_state.include_list:
2186 for f in section_list:
2187 if headername in f[0] or f[0] in headername:
2188 return
2189 if not first_include:
2190 first_include = f[1]
2191
2192 error(filename, first_include, 'build/include', 5,
2193 '%s should include its header file %s' % (fileinfo.RepositoryName(),
2194 headername))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002195
2196
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002197def CheckForBadCharacters(filename, lines, error):
2198 """Logs an error for each line containing bad characters.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002199
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002200 Two kinds of bad characters:
2201
2202 1. Unicode replacement characters: These indicate that either the file
2203 contained invalid UTF-8 (likely) or Unicode replacement characters (which
2204 it shouldn't). Note that it's possible for this to throw off line
2205 numbering if the invalid UTF-8 occurred adjacent to a newline.
2206
2207 2. NUL bytes. These are problematic for some tools.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002208
2209 Args:
2210 filename: The name of the current file.
2211 lines: An array of strings, each representing a line of the file.
2212 error: The function to call with any errors found.
2213 """
2214 for linenum, line in enumerate(lines):
2215 if u'\ufffd' in line:
2216 error(filename, linenum, 'readability/utf8', 5,
2217 'Line contains invalid UTF-8 (or Unicode replacement character).')
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002218 if '\0' in line:
2219 error(filename, linenum, 'readability/nul', 5, 'Line contains NUL byte.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002220
2221
2222def CheckForNewlineAtEOF(filename, lines, error):
2223 """Logs an error if there is no newline char at the end of the file.
2224
2225 Args:
2226 filename: The name of the current file.
2227 lines: An array of strings, each representing a line of the file.
2228 error: The function to call with any errors found.
2229 """
2230
2231 # The array lines() was created by adding two newlines to the
2232 # original file (go figure), then splitting on \n.
2233 # To verify that the file ends in \n, we just have to make sure the
2234 # last-but-two element of lines() exists and is empty.
2235 if len(lines) < 3 or lines[-2]:
2236 error(filename, len(lines) - 2, 'whitespace/ending_newline', 5,
2237 'Could not find a newline character at the end of the file.')
2238
2239
2240def CheckForMultilineCommentsAndStrings(filename, clean_lines, linenum, error):
2241 """Logs an error if we see /* ... */ or "..." that extend past one line.
2242
2243 /* ... */ comments are legit inside macros, for one line.
2244 Otherwise, we prefer // comments, so it's ok to warn about the
2245 other. Likewise, it's ok for strings to extend across multiple
2246 lines, as long as a line continuation character (backslash)
2247 terminates each line. Although not currently prohibited by the C++
2248 style guide, it's ugly and unnecessary. We don't do well with either
2249 in this lint program, so we warn about both.
2250
2251 Args:
2252 filename: The name of the current file.
2253 clean_lines: A CleansedLines instance containing the file.
2254 linenum: The number of the line to check.
2255 error: The function to call with any errors found.
2256 """
2257 line = clean_lines.elided[linenum]
2258
2259 # Remove all \\ (escaped backslashes) from the line. They are OK, and the
2260 # second (escaped) slash may trigger later \" detection erroneously.
2261 line = line.replace('\\\\', '')
2262
2263 if line.count('/*') > line.count('*/'):
2264 error(filename, linenum, 'readability/multiline_comment', 5,
2265 'Complex multi-line /*...*/-style comment found. '
2266 'Lint may give bogus warnings. '
2267 'Consider replacing these with //-style comments, '
2268 'with #if 0...#endif, '
2269 'or with more clearly structured multi-line comments.')
2270
2271 if (line.count('"') - line.count('\\"')) % 2:
2272 error(filename, linenum, 'readability/multiline_string', 5,
2273 'Multi-line string ("...") found. This lint script doesn\'t '
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002274 'do well with such strings, and may give bogus warnings. '
2275 'Use C++11 raw strings or concatenation instead.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002276
2277
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002278# (non-threadsafe name, thread-safe alternative, validation pattern)
2279#
2280# The validation pattern is used to eliminate false positives such as:
2281# _rand(); // false positive due to substring match.
2282# ->rand(); // some member function rand().
2283# ACMRandom rand(seed); // some variable named rand.
2284# ISAACRandom rand(); // another variable named rand.
2285#
2286# Basically we require the return value of these functions to be used
2287# in some expression context on the same line by matching on some
2288# operator before the function name. This eliminates constructors and
2289# member function calls.
2290_UNSAFE_FUNC_PREFIX = r'(?:[-+*/=%^&|(<]\s*|>\s+)'
2291_THREADING_LIST = (
2292 ('asctime(', 'asctime_r(', _UNSAFE_FUNC_PREFIX + r'asctime\([^)]+\)'),
2293 ('ctime(', 'ctime_r(', _UNSAFE_FUNC_PREFIX + r'ctime\([^)]+\)'),
2294 ('getgrgid(', 'getgrgid_r(', _UNSAFE_FUNC_PREFIX + r'getgrgid\([^)]+\)'),
2295 ('getgrnam(', 'getgrnam_r(', _UNSAFE_FUNC_PREFIX + r'getgrnam\([^)]+\)'),
2296 ('getlogin(', 'getlogin_r(', _UNSAFE_FUNC_PREFIX + r'getlogin\(\)'),
2297 ('getpwnam(', 'getpwnam_r(', _UNSAFE_FUNC_PREFIX + r'getpwnam\([^)]+\)'),
2298 ('getpwuid(', 'getpwuid_r(', _UNSAFE_FUNC_PREFIX + r'getpwuid\([^)]+\)'),
2299 ('gmtime(', 'gmtime_r(', _UNSAFE_FUNC_PREFIX + r'gmtime\([^)]+\)'),
2300 ('localtime(', 'localtime_r(', _UNSAFE_FUNC_PREFIX + r'localtime\([^)]+\)'),
2301 ('rand(', 'rand_r(', _UNSAFE_FUNC_PREFIX + r'rand\(\)'),
2302 ('strtok(', 'strtok_r(',
2303 _UNSAFE_FUNC_PREFIX + r'strtok\([^)]+\)'),
2304 ('ttyname(', 'ttyname_r(', _UNSAFE_FUNC_PREFIX + r'ttyname\([^)]+\)'),
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002305 )
2306
2307
2308def CheckPosixThreading(filename, clean_lines, linenum, error):
2309 """Checks for calls to thread-unsafe functions.
2310
2311 Much code has been originally written without consideration of
2312 multi-threading. Also, engineers are relying on their old experience;
2313 they have learned posix before threading extensions were added. These
2314 tests guide the engineers to use thread-safe functions (when using
2315 posix directly).
2316
2317 Args:
2318 filename: The name of the current file.
2319 clean_lines: A CleansedLines instance containing the file.
2320 linenum: The number of the line to check.
2321 error: The function to call with any errors found.
2322 """
2323 line = clean_lines.elided[linenum]
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002324 for single_thread_func, multithread_safe_func, pattern in _THREADING_LIST:
2325 # Additional pattern matching check to confirm that this is the
2326 # function we are looking for
2327 if Search(pattern, line):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002328 error(filename, linenum, 'runtime/threadsafe_fn', 2,
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002329 'Consider using ' + multithread_safe_func +
2330 '...) instead of ' + single_thread_func +
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002331 '...) for improved thread safety.')
2332
2333
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002334def CheckVlogArguments(filename, clean_lines, linenum, error):
2335 """Checks that VLOG() is only used for defining a logging level.
2336
2337 For example, VLOG(2) is correct. VLOG(INFO), VLOG(WARNING), VLOG(ERROR), and
2338 VLOG(FATAL) are not.
2339
2340 Args:
2341 filename: The name of the current file.
2342 clean_lines: A CleansedLines instance containing the file.
2343 linenum: The number of the line to check.
2344 error: The function to call with any errors found.
2345 """
2346 line = clean_lines.elided[linenum]
2347 if Search(r'\bVLOG\((INFO|ERROR|WARNING|DFATAL|FATAL)\)', line):
2348 error(filename, linenum, 'runtime/vlog', 5,
2349 'VLOG() should be used with numeric verbosity level. '
2350 'Use LOG() if you want symbolic severity levels.')
2351
erg@google.com26970fa2009-11-17 18:07:32 +00002352# Matches invalid increment: *count++, which moves pointer instead of
erg@google.com6317a9c2009-06-25 00:28:19 +00002353# incrementing a value.
erg@google.com26970fa2009-11-17 18:07:32 +00002354_RE_PATTERN_INVALID_INCREMENT = re.compile(
erg@google.com6317a9c2009-06-25 00:28:19 +00002355 r'^\s*\*\w+(\+\+|--);')
2356
2357
2358def CheckInvalidIncrement(filename, clean_lines, linenum, error):
erg@google.com26970fa2009-11-17 18:07:32 +00002359 """Checks for invalid increment *count++.
erg@google.com6317a9c2009-06-25 00:28:19 +00002360
2361 For example following function:
2362 void increment_counter(int* count) {
2363 *count++;
2364 }
2365 is invalid, because it effectively does count++, moving pointer, and should
2366 be replaced with ++*count, (*count)++ or *count += 1.
2367
2368 Args:
2369 filename: The name of the current file.
2370 clean_lines: A CleansedLines instance containing the file.
2371 linenum: The number of the line to check.
2372 error: The function to call with any errors found.
2373 """
2374 line = clean_lines.elided[linenum]
erg@google.com26970fa2009-11-17 18:07:32 +00002375 if _RE_PATTERN_INVALID_INCREMENT.match(line):
erg@google.com6317a9c2009-06-25 00:28:19 +00002376 error(filename, linenum, 'runtime/invalid_increment', 5,
2377 'Changing pointer instead of value (or unused value of operator*).')
2378
2379
avakulenko@google.com59146752014-08-11 20:20:55 +00002380def IsMacroDefinition(clean_lines, linenum):
2381 if Search(r'^#define', clean_lines[linenum]):
2382 return True
2383
2384 if linenum > 0 and Search(r'\\$', clean_lines[linenum - 1]):
2385 return True
2386
2387 return False
2388
2389
2390def IsForwardClassDeclaration(clean_lines, linenum):
2391 return Match(r'^\s*(\btemplate\b)*.*class\s+\w+;\s*$', clean_lines[linenum])
2392
2393
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002394class _BlockInfo(object):
2395 """Stores information about a generic block of code."""
2396
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002397 def __init__(self, linenum, seen_open_brace):
2398 self.starting_linenum = linenum
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002399 self.seen_open_brace = seen_open_brace
2400 self.open_parentheses = 0
2401 self.inline_asm = _NO_ASM
avakulenko@google.com59146752014-08-11 20:20:55 +00002402 self.check_namespace_indentation = False
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002403
2404 def CheckBegin(self, filename, clean_lines, linenum, error):
2405 """Run checks that applies to text up to the opening brace.
2406
2407 This is mostly for checking the text after the class identifier
2408 and the "{", usually where the base class is specified. For other
2409 blocks, there isn't much to check, so we always pass.
2410
2411 Args:
2412 filename: The name of the current file.
2413 clean_lines: A CleansedLines instance containing the file.
2414 linenum: The number of the line to check.
2415 error: The function to call with any errors found.
2416 """
2417 pass
2418
2419 def CheckEnd(self, filename, clean_lines, linenum, error):
2420 """Run checks that applies to text after the closing brace.
2421
2422 This is mostly used for checking end of namespace comments.
2423
2424 Args:
2425 filename: The name of the current file.
2426 clean_lines: A CleansedLines instance containing the file.
2427 linenum: The number of the line to check.
2428 error: The function to call with any errors found.
2429 """
2430 pass
2431
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002432 def IsBlockInfo(self):
2433 """Returns true if this block is a _BlockInfo.
2434
2435 This is convenient for verifying that an object is an instance of
2436 a _BlockInfo, but not an instance of any of the derived classes.
2437
2438 Returns:
2439 True for this class, False for derived classes.
2440 """
2441 return self.__class__ == _BlockInfo
2442
2443
2444class _ExternCInfo(_BlockInfo):
2445 """Stores information about an 'extern "C"' block."""
2446
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002447 def __init__(self, linenum):
2448 _BlockInfo.__init__(self, linenum, True)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002449
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002450
2451class _ClassInfo(_BlockInfo):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002452 """Stores information about a class."""
2453
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002454 def __init__(self, name, class_or_struct, clean_lines, linenum):
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002455 _BlockInfo.__init__(self, linenum, False)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002456 self.name = name
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002457 self.is_derived = False
avakulenko@google.com59146752014-08-11 20:20:55 +00002458 self.check_namespace_indentation = True
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002459 if class_or_struct == 'struct':
2460 self.access = 'public'
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002461 self.is_struct = True
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002462 else:
2463 self.access = 'private'
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002464 self.is_struct = False
2465
2466 # Remember initial indentation level for this class. Using raw_lines here
2467 # instead of elided to account for leading comments.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002468 self.class_indent = GetIndentLevel(clean_lines.raw_lines[linenum])
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002469
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00002470 # Try to find the end of the class. This will be confused by things like:
2471 # class A {
2472 # } *x = { ...
2473 #
2474 # But it's still good enough for CheckSectionSpacing.
2475 self.last_line = 0
2476 depth = 0
2477 for i in range(linenum, clean_lines.NumLines()):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002478 line = clean_lines.elided[i]
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00002479 depth += line.count('{') - line.count('}')
2480 if not depth:
2481 self.last_line = i
2482 break
2483
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002484 def CheckBegin(self, filename, clean_lines, linenum, error):
2485 # Look for a bare ':'
2486 if Search('(^|[^:]):($|[^:])', clean_lines.elided[linenum]):
2487 self.is_derived = True
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002488
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002489 def CheckEnd(self, filename, clean_lines, linenum, error):
avakulenko@google.com255f2be2014-12-05 22:19:55 +00002490 # If there is a DISALLOW macro, it should appear near the end of
2491 # the class.
2492 seen_last_thing_in_class = False
Edward Lemur6d31ed52019-12-02 23:00:00 +00002493 for i in range(linenum - 1, self.starting_linenum, -1):
avakulenko@google.com255f2be2014-12-05 22:19:55 +00002494 match = Search(
2495 r'\b(DISALLOW_COPY_AND_ASSIGN|DISALLOW_IMPLICIT_CONSTRUCTORS)\(' +
2496 self.name + r'\)',
2497 clean_lines.elided[i])
2498 if match:
2499 if seen_last_thing_in_class:
2500 error(filename, i, 'readability/constructors', 3,
2501 match.group(1) + ' should be the last thing in the class')
2502 break
2503
2504 if not Match(r'^\s*$', clean_lines.elided[i]):
2505 seen_last_thing_in_class = True
2506
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002507 # Check that closing brace is aligned with beginning of the class.
2508 # Only do this if the closing brace is indented by only whitespaces.
2509 # This means we will not check single-line class definitions.
2510 indent = Match(r'^( *)\}', clean_lines.elided[linenum])
2511 if indent and len(indent.group(1)) != self.class_indent:
2512 if self.is_struct:
2513 parent = 'struct ' + self.name
2514 else:
2515 parent = 'class ' + self.name
2516 error(filename, linenum, 'whitespace/indent', 3,
2517 'Closing brace should be aligned with beginning of %s' % parent)
2518
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002519
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002520class _NamespaceInfo(_BlockInfo):
2521 """Stores information about a namespace."""
2522
2523 def __init__(self, name, linenum):
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002524 _BlockInfo.__init__(self, linenum, False)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002525 self.name = name or ''
avakulenko@google.com59146752014-08-11 20:20:55 +00002526 self.check_namespace_indentation = True
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002527
2528 def CheckEnd(self, filename, clean_lines, linenum, error):
2529 """Check end of namespace comments."""
2530 line = clean_lines.raw_lines[linenum]
2531
2532 # Check how many lines is enclosed in this namespace. Don't issue
2533 # warning for missing namespace comments if there aren't enough
2534 # lines. However, do apply checks if there is already an end of
2535 # namespace comment and it's incorrect.
2536 #
2537 # TODO(unknown): We always want to check end of namespace comments
2538 # if a namespace is large, but sometimes we also want to apply the
2539 # check if a short namespace contained nontrivial things (something
2540 # other than forward declarations). There is currently no logic on
2541 # deciding what these nontrivial things are, so this check is
2542 # triggered by namespace size only, which works most of the time.
2543 if (linenum - self.starting_linenum < 10
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002544 and not Match(r'^\s*};*\s*(//|/\*).*\bnamespace\b', line)):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002545 return
2546
2547 # Look for matching comment at end of namespace.
2548 #
2549 # Note that we accept C style "/* */" comments for terminating
2550 # namespaces, so that code that terminate namespaces inside
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002551 # preprocessor macros can be cpplint clean.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002552 #
2553 # We also accept stuff like "// end of namespace <name>." with the
2554 # period at the end.
2555 #
2556 # Besides these, we don't accept anything else, otherwise we might
2557 # get false negatives when existing comment is a substring of the
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002558 # expected namespace.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002559 if self.name:
2560 # Named namespace
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002561 if not Match((r'^\s*};*\s*(//|/\*).*\bnamespace\s+' +
2562 re.escape(self.name) + r'[\*/\.\\\s]*$'),
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002563 line):
2564 error(filename, linenum, 'readability/namespace', 5,
2565 'Namespace should be terminated with "// namespace %s"' %
2566 self.name)
2567 else:
2568 # Anonymous namespace
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002569 if not Match(r'^\s*};*\s*(//|/\*).*\bnamespace[\*/\.\\\s]*$', line):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002570 # If "// namespace anonymous" or "// anonymous namespace (more text)",
2571 # mention "// anonymous namespace" as an acceptable form
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002572 if Match(r'^\s*}.*\b(namespace anonymous|anonymous namespace)\b', line):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002573 error(filename, linenum, 'readability/namespace', 5,
2574 'Anonymous namespace should be terminated with "// namespace"'
2575 ' or "// anonymous namespace"')
2576 else:
2577 error(filename, linenum, 'readability/namespace', 5,
2578 'Anonymous namespace should be terminated with "// namespace"')
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002579
2580
2581class _PreprocessorInfo(object):
2582 """Stores checkpoints of nesting stacks when #if/#else is seen."""
2583
2584 def __init__(self, stack_before_if):
2585 # The entire nesting stack before #if
2586 self.stack_before_if = stack_before_if
2587
2588 # The entire nesting stack up to #else
2589 self.stack_before_else = []
2590
2591 # Whether we have already seen #else or #elif
2592 self.seen_else = False
2593
2594
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002595class NestingState(object):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002596 """Holds states related to parsing braces."""
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002597
2598 def __init__(self):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002599 # Stack for tracking all braces. An object is pushed whenever we
2600 # see a "{", and popped when we see a "}". Only 3 types of
2601 # objects are possible:
2602 # - _ClassInfo: a class or struct.
2603 # - _NamespaceInfo: a namespace.
2604 # - _BlockInfo: some other type of block.
2605 self.stack = []
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002606
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002607 # Top of the previous stack before each Update().
2608 #
2609 # Because the nesting_stack is updated at the end of each line, we
2610 # had to do some convoluted checks to find out what is the current
2611 # scope at the beginning of the line. This check is simplified by
2612 # saving the previous top of nesting stack.
2613 #
2614 # We could save the full stack, but we only need the top. Copying
2615 # the full nesting stack would slow down cpplint by ~10%.
2616 self.previous_stack_top = []
2617
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002618 # Stack of _PreprocessorInfo objects.
2619 self.pp_stack = []
2620
2621 def SeenOpenBrace(self):
2622 """Check if we have seen the opening brace for the innermost block.
2623
2624 Returns:
2625 True if we have seen the opening brace, False if the innermost
2626 block is still expecting an opening brace.
2627 """
2628 return (not self.stack) or self.stack[-1].seen_open_brace
2629
2630 def InNamespaceBody(self):
2631 """Check if we are currently one level inside a namespace body.
2632
2633 Returns:
2634 True if top of the stack is a namespace block, False otherwise.
2635 """
2636 return self.stack and isinstance(self.stack[-1], _NamespaceInfo)
2637
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002638 def InExternC(self):
2639 """Check if we are currently one level inside an 'extern "C"' block.
2640
2641 Returns:
2642 True if top of the stack is an extern block, False otherwise.
2643 """
2644 return self.stack and isinstance(self.stack[-1], _ExternCInfo)
2645
2646 def InClassDeclaration(self):
2647 """Check if we are currently one level inside a class or struct declaration.
2648
2649 Returns:
2650 True if top of the stack is a class/struct, False otherwise.
2651 """
2652 return self.stack and isinstance(self.stack[-1], _ClassInfo)
2653
2654 def InAsmBlock(self):
2655 """Check if we are currently one level inside an inline ASM block.
2656
2657 Returns:
2658 True if the top of the stack is a block containing inline ASM.
2659 """
2660 return self.stack and self.stack[-1].inline_asm != _NO_ASM
2661
2662 def InTemplateArgumentList(self, clean_lines, linenum, pos):
2663 """Check if current position is inside template argument list.
2664
2665 Args:
2666 clean_lines: A CleansedLines instance containing the file.
2667 linenum: The number of the line to check.
2668 pos: position just after the suspected template argument.
2669 Returns:
2670 True if (linenum, pos) is inside template arguments.
2671 """
2672 while linenum < clean_lines.NumLines():
2673 # Find the earliest character that might indicate a template argument
2674 line = clean_lines.elided[linenum]
2675 match = Match(r'^[^{};=\[\]\.<>]*(.)', line[pos:])
2676 if not match:
2677 linenum += 1
2678 pos = 0
2679 continue
2680 token = match.group(1)
2681 pos += len(match.group(0))
2682
2683 # These things do not look like template argument list:
2684 # class Suspect {
2685 # class Suspect x; }
2686 if token in ('{', '}', ';'): return False
2687
2688 # These things look like template argument list:
2689 # template <class Suspect>
2690 # template <class Suspect = default_value>
2691 # template <class Suspect[]>
2692 # template <class Suspect...>
2693 if token in ('>', '=', '[', ']', '.'): return True
2694
2695 # Check if token is an unmatched '<'.
2696 # If not, move on to the next character.
2697 if token != '<':
2698 pos += 1
2699 if pos >= len(line):
2700 linenum += 1
2701 pos = 0
2702 continue
2703
2704 # We can't be sure if we just find a single '<', and need to
2705 # find the matching '>'.
2706 (_, end_line, end_pos) = CloseExpression(clean_lines, linenum, pos - 1)
2707 if end_pos < 0:
2708 # Not sure if template argument list or syntax error in file
2709 return False
2710 linenum = end_line
2711 pos = end_pos
2712 return False
2713
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002714 def UpdatePreprocessor(self, line):
2715 """Update preprocessor stack.
2716
2717 We need to handle preprocessors due to classes like this:
2718 #ifdef SWIG
2719 struct ResultDetailsPageElementExtensionPoint {
2720 #else
2721 struct ResultDetailsPageElementExtensionPoint : public Extension {
2722 #endif
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002723
2724 We make the following assumptions (good enough for most files):
2725 - Preprocessor condition evaluates to true from #if up to first
2726 #else/#elif/#endif.
2727
2728 - Preprocessor condition evaluates to false from #else/#elif up
2729 to #endif. We still perform lint checks on these lines, but
2730 these do not affect nesting stack.
2731
2732 Args:
2733 line: current line to check.
2734 """
2735 if Match(r'^\s*#\s*(if|ifdef|ifndef)\b', line):
2736 # Beginning of #if block, save the nesting stack here. The saved
2737 # stack will allow us to restore the parsing state in the #else case.
2738 self.pp_stack.append(_PreprocessorInfo(copy.deepcopy(self.stack)))
2739 elif Match(r'^\s*#\s*(else|elif)\b', line):
2740 # Beginning of #else block
2741 if self.pp_stack:
2742 if not self.pp_stack[-1].seen_else:
2743 # This is the first #else or #elif block. Remember the
2744 # whole nesting stack up to this point. This is what we
2745 # keep after the #endif.
2746 self.pp_stack[-1].seen_else = True
2747 self.pp_stack[-1].stack_before_else = copy.deepcopy(self.stack)
2748
2749 # Restore the stack to how it was before the #if
2750 self.stack = copy.deepcopy(self.pp_stack[-1].stack_before_if)
2751 else:
2752 # TODO(unknown): unexpected #else, issue warning?
2753 pass
2754 elif Match(r'^\s*#\s*endif\b', line):
2755 # End of #if or #else blocks.
2756 if self.pp_stack:
2757 # If we saw an #else, we will need to restore the nesting
2758 # stack to its former state before the #else, otherwise we
2759 # will just continue from where we left off.
2760 if self.pp_stack[-1].seen_else:
2761 # Here we can just use a shallow copy since we are the last
2762 # reference to it.
2763 self.stack = self.pp_stack[-1].stack_before_else
2764 # Drop the corresponding #if
2765 self.pp_stack.pop()
2766 else:
2767 # TODO(unknown): unexpected #endif, issue warning?
2768 pass
2769
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002770 # TODO(unknown): Update() is too long, but we will refactor later.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002771 def Update(self, filename, clean_lines, linenum, error):
2772 """Update nesting state with current line.
2773
2774 Args:
2775 filename: The name of the current file.
2776 clean_lines: A CleansedLines instance containing the file.
2777 linenum: The number of the line to check.
2778 error: The function to call with any errors found.
2779 """
2780 line = clean_lines.elided[linenum]
2781
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002782 # Remember top of the previous nesting stack.
2783 #
2784 # The stack is always pushed/popped and not modified in place, so
2785 # we can just do a shallow copy instead of copy.deepcopy. Using
2786 # deepcopy would slow down cpplint by ~28%.
2787 if self.stack:
2788 self.previous_stack_top = self.stack[-1]
2789 else:
2790 self.previous_stack_top = None
2791
2792 # Update pp_stack
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002793 self.UpdatePreprocessor(line)
2794
2795 # Count parentheses. This is to avoid adding struct arguments to
2796 # the nesting stack.
2797 if self.stack:
2798 inner_block = self.stack[-1]
2799 depth_change = line.count('(') - line.count(')')
2800 inner_block.open_parentheses += depth_change
2801
2802 # Also check if we are starting or ending an inline assembly block.
2803 if inner_block.inline_asm in (_NO_ASM, _END_ASM):
2804 if (depth_change != 0 and
2805 inner_block.open_parentheses == 1 and
2806 _MATCH_ASM.match(line)):
2807 # Enter assembly block
2808 inner_block.inline_asm = _INSIDE_ASM
2809 else:
2810 # Not entering assembly block. If previous line was _END_ASM,
2811 # we will now shift to _NO_ASM state.
2812 inner_block.inline_asm = _NO_ASM
2813 elif (inner_block.inline_asm == _INSIDE_ASM and
2814 inner_block.open_parentheses == 0):
2815 # Exit assembly block
2816 inner_block.inline_asm = _END_ASM
2817
2818 # Consume namespace declaration at the beginning of the line. Do
2819 # this in a loop so that we catch same line declarations like this:
2820 # namespace proto2 { namespace bridge { class MessageSet; } }
2821 while True:
2822 # Match start of namespace. The "\b\s*" below catches namespace
2823 # declarations even if it weren't followed by a whitespace, this
2824 # is so that we don't confuse our namespace checker. The
2825 # missing spaces will be flagged by CheckSpacing.
2826 namespace_decl_match = Match(r'^\s*namespace\b\s*([:\w]+)?(.*)$', line)
2827 if not namespace_decl_match:
2828 break
2829
2830 new_namespace = _NamespaceInfo(namespace_decl_match.group(1), linenum)
2831 self.stack.append(new_namespace)
2832
2833 line = namespace_decl_match.group(2)
2834 if line.find('{') != -1:
2835 new_namespace.seen_open_brace = True
2836 line = line[line.find('{') + 1:]
2837
2838 # Look for a class declaration in whatever is left of the line
2839 # after parsing namespaces. The regexp accounts for decorated classes
2840 # such as in:
2841 # class LOCKABLE API Object {
2842 # };
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002843 class_decl_match = Match(
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002844 r'^(\s*(?:template\s*<[\w\s<>,:]*>\s*)?'
Clemens Hammacher2cc6e252018-12-20 08:40:19 +00002845 r'(class|struct)\s+(?:[A-Z0-9_]+\s+)*(\w+(?:::\w+)*))'
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002846 r'(.*)$', line)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002847 if (class_decl_match and
2848 (not self.stack or self.stack[-1].open_parentheses == 0)):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002849 # We do not want to accept classes that are actually template arguments:
2850 # template <class Ignore1,
2851 # class Ignore2 = Default<Args>,
2852 # template <Args> class Ignore3>
2853 # void Function() {};
2854 #
2855 # To avoid template argument cases, we scan forward and look for
2856 # an unmatched '>'. If we see one, assume we are inside a
2857 # template argument list.
2858 end_declaration = len(class_decl_match.group(1))
2859 if not self.InTemplateArgumentList(clean_lines, linenum, end_declaration):
2860 self.stack.append(_ClassInfo(
2861 class_decl_match.group(3), class_decl_match.group(2),
2862 clean_lines, linenum))
2863 line = class_decl_match.group(4)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002864
2865 # If we have not yet seen the opening brace for the innermost block,
2866 # run checks here.
2867 if not self.SeenOpenBrace():
2868 self.stack[-1].CheckBegin(filename, clean_lines, linenum, error)
2869
2870 # Update access control if we are inside a class/struct
2871 if self.stack and isinstance(self.stack[-1], _ClassInfo):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002872 classinfo = self.stack[-1]
2873 access_match = Match(
2874 r'^(.*)\b(public|private|protected|signals)(\s+(?:slots\s*)?)?'
2875 r':(?:[^:]|$)',
2876 line)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002877 if access_match:
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002878 classinfo.access = access_match.group(2)
2879
2880 # Check that access keywords are indented +1 space. Skip this
2881 # check if the keywords are not preceded by whitespaces.
2882 indent = access_match.group(1)
2883 if (len(indent) != classinfo.class_indent + 1 and
2884 Match(r'^\s*$', indent)):
2885 if classinfo.is_struct:
2886 parent = 'struct ' + classinfo.name
2887 else:
2888 parent = 'class ' + classinfo.name
2889 slots = ''
2890 if access_match.group(3):
2891 slots = access_match.group(3)
2892 error(filename, linenum, 'whitespace/indent', 3,
2893 '%s%s: should be indented +1 space inside %s' % (
2894 access_match.group(2), slots, parent))
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002895
2896 # Consume braces or semicolons from what's left of the line
2897 while True:
2898 # Match first brace, semicolon, or closed parenthesis.
2899 matched = Match(r'^[^{;)}]*([{;)}])(.*)$', line)
2900 if not matched:
2901 break
2902
2903 token = matched.group(1)
2904 if token == '{':
2905 # If namespace or class hasn't seen a opening brace yet, mark
2906 # namespace/class head as complete. Push a new block onto the
2907 # stack otherwise.
2908 if not self.SeenOpenBrace():
2909 self.stack[-1].seen_open_brace = True
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002910 elif Match(r'^extern\s*"[^"]*"\s*\{', line):
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002911 self.stack.append(_ExternCInfo(linenum))
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002912 else:
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00002913 self.stack.append(_BlockInfo(linenum, True))
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002914 if _MATCH_ASM.match(line):
2915 self.stack[-1].inline_asm = _BLOCK_ASM
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002916
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002917 elif token == ';' or token == ')':
2918 # If we haven't seen an opening brace yet, but we already saw
2919 # a semicolon, this is probably a forward declaration. Pop
2920 # the stack for these.
2921 #
2922 # Similarly, if we haven't seen an opening brace yet, but we
2923 # already saw a closing parenthesis, then these are probably
2924 # function arguments with extra "class" or "struct" keywords.
2925 # Also pop these stack for these.
2926 if not self.SeenOpenBrace():
2927 self.stack.pop()
2928 else: # token == '}'
2929 # Perform end of block checks and pop the stack.
2930 if self.stack:
2931 self.stack[-1].CheckEnd(filename, clean_lines, linenum, error)
2932 self.stack.pop()
2933 line = matched.group(2)
2934
2935 def InnermostClass(self):
2936 """Get class info on the top of the stack.
2937
2938 Returns:
2939 A _ClassInfo object if we are inside a class, or None otherwise.
2940 """
2941 for i in range(len(self.stack), 0, -1):
2942 classinfo = self.stack[i - 1]
2943 if isinstance(classinfo, _ClassInfo):
2944 return classinfo
2945 return None
2946
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002947 def CheckCompletedBlocks(self, filename, error):
2948 """Checks that all classes and namespaces have been completely parsed.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002949
2950 Call this when all lines in a file have been processed.
2951 Args:
2952 filename: The name of the current file.
2953 error: The function to call with any errors found.
2954 """
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002955 # Note: This test can result in false positives if #ifdef constructs
2956 # get in the way of brace matching. See the testBuildClass test in
2957 # cpplint_unittest.py for an example of this.
2958 for obj in self.stack:
2959 if isinstance(obj, _ClassInfo):
2960 error(filename, obj.starting_linenum, 'build/class', 5,
2961 'Failed to find complete declaration of class %s' %
2962 obj.name)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002963 elif isinstance(obj, _NamespaceInfo):
2964 error(filename, obj.starting_linenum, 'build/namespaces', 5,
2965 'Failed to find complete declaration of namespace %s' %
2966 obj.name)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002967
2968
2969def CheckForNonStandardConstructs(filename, clean_lines, linenum,
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002970 nesting_state, error):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00002971 r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002972
2973 Complain about several constructs which gcc-2 accepts, but which are
2974 not standard C++. Warning about these in lint is one way to ease the
2975 transition to new compilers.
2976 - put storage class first (e.g. "static const" instead of "const static").
2977 - "%lld" instead of %qd" in printf-type functions.
2978 - "%1$d" is non-standard in printf-type functions.
2979 - "\%" is an undefined character escape sequence.
2980 - text after #endif is not allowed.
2981 - invalid inner-style forward declaration.
2982 - >? and <? operators, and their >?= and <?= cousins.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002983
erg@google.com26970fa2009-11-17 18:07:32 +00002984 Additionally, check for constructor/destructor style violations and reference
2985 members, as it is very convenient to do so while checking for
2986 gcc-2 compliance.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002987
2988 Args:
2989 filename: The name of the current file.
2990 clean_lines: A CleansedLines instance containing the file.
2991 linenum: The number of the line to check.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00002992 nesting_state: A NestingState instance which maintains information about
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00002993 the current stack of nested blocks being parsed.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00002994 error: A callable to which errors are reported, which takes 4 arguments:
2995 filename, line number, error level, and message
2996 """
2997
2998 # Remove comments from the line, but leave in strings for now.
2999 line = clean_lines.lines[linenum]
3000
3001 if Search(r'printf\s*\(.*".*%[-+ ]?\d*q', line):
3002 error(filename, linenum, 'runtime/printf_format', 3,
3003 '%q in format strings is deprecated. Use %ll instead.')
3004
3005 if Search(r'printf\s*\(.*".*%\d+\$', line):
3006 error(filename, linenum, 'runtime/printf_format', 2,
3007 '%N$ formats are unconventional. Try rewriting to avoid them.')
3008
3009 # Remove escaped backslashes before looking for undefined escapes.
3010 line = line.replace('\\\\', '')
3011
3012 if Search(r'("|\').*\\(%|\[|\(|{)', line):
3013 error(filename, linenum, 'build/printf_format', 3,
3014 '%, [, (, and { are undefined character escapes. Unescape them.')
3015
3016 # For the rest, work with both comments and strings removed.
3017 line = clean_lines.elided[linenum]
3018
3019 if Search(r'\b(const|volatile|void|char|short|int|long'
3020 r'|float|double|signed|unsigned'
3021 r'|schar|u?int8|u?int16|u?int32|u?int64)'
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003022 r'\s+(register|static|extern|typedef)\b',
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003023 line):
3024 error(filename, linenum, 'build/storage_class', 5,
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003025 'Storage-class specifier (static, extern, typedef, etc) should be '
3026 'at the beginning of the declaration.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003027
3028 if Match(r'\s*#\s*endif\s*[^/\s]+', line):
3029 error(filename, linenum, 'build/endif_comment', 5,
3030 'Uncommented text after #endif is non-standard. Use a comment.')
3031
3032 if Match(r'\s*class\s+(\w+\s*::\s*)+\w+\s*;', line):
3033 error(filename, linenum, 'build/forward_decl', 5,
3034 'Inner-style forward declarations are invalid. Remove this line.')
3035
3036 if Search(r'(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?',
3037 line):
3038 error(filename, linenum, 'build/deprecated', 3,
3039 '>? and <? (max and min) operators are non-standard and deprecated.')
3040
erg@google.com26970fa2009-11-17 18:07:32 +00003041 if Search(r'^\s*const\s*string\s*&\s*\w+\s*;', line):
3042 # TODO(unknown): Could it be expanded safely to arbitrary references,
3043 # without triggering too many false positives? The first
3044 # attempt triggered 5 warnings for mostly benign code in the regtest, hence
3045 # the restriction.
3046 # Here's the original regexp, for the reference:
3047 # type_name = r'\w+((\s*::\s*\w+)|(\s*<\s*\w+?\s*>))?'
3048 # r'\s*const\s*' + type_name + '\s*&\s*\w+\s*;'
3049 error(filename, linenum, 'runtime/member_string_references', 2,
3050 'const string& members are dangerous. It is much better to use '
3051 'alternatives, such as pointers or simple constants.')
3052
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003053 # Everything else in this function operates on class declarations.
3054 # Return early if the top of the nesting stack is not a class, or if
3055 # the class head is not completed yet.
3056 classinfo = nesting_state.InnermostClass()
3057 if not classinfo or not classinfo.seen_open_brace:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003058 return
3059
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003060 # The class may have been declared with namespace or classname qualifiers.
3061 # The constructor and destructor will not have those qualifiers.
3062 base_classname = classinfo.name.split('::')[-1]
3063
3064 # Look for single-argument constructors that aren't marked explicit.
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003065 # Technically a valid construct, but against style.
avakulenko@google.com59146752014-08-11 20:20:55 +00003066 explicit_constructor_match = Match(
danakjd7f56752017-02-22 11:45:06 -05003067 r'\s+(?:(?:inline|constexpr)\s+)*(explicit\s+)?'
3068 r'(?:(?:inline|constexpr)\s+)*%s\s*'
avakulenko@google.com59146752014-08-11 20:20:55 +00003069 r'\(((?:[^()]|\([^()]*\))*)\)'
3070 % re.escape(base_classname),
3071 line)
3072
3073 if explicit_constructor_match:
3074 is_marked_explicit = explicit_constructor_match.group(1)
3075
3076 if not explicit_constructor_match.group(2):
3077 constructor_args = []
3078 else:
3079 constructor_args = explicit_constructor_match.group(2).split(',')
3080
3081 # collapse arguments so that commas in template parameter lists and function
3082 # argument parameter lists don't split arguments in two
3083 i = 0
3084 while i < len(constructor_args):
3085 constructor_arg = constructor_args[i]
3086 while (constructor_arg.count('<') > constructor_arg.count('>') or
3087 constructor_arg.count('(') > constructor_arg.count(')')):
3088 constructor_arg += ',' + constructor_args[i + 1]
3089 del constructor_args[i + 1]
3090 constructor_args[i] = constructor_arg
3091 i += 1
3092
3093 defaulted_args = [arg for arg in constructor_args if '=' in arg]
3094 noarg_constructor = (not constructor_args or # empty arg list
3095 # 'void' arg specifier
3096 (len(constructor_args) == 1 and
3097 constructor_args[0].strip() == 'void'))
3098 onearg_constructor = ((len(constructor_args) == 1 and # exactly one arg
3099 not noarg_constructor) or
3100 # all but at most one arg defaulted
3101 (len(constructor_args) >= 1 and
3102 not noarg_constructor and
3103 len(defaulted_args) >= len(constructor_args) - 1))
3104 initializer_list_constructor = bool(
3105 onearg_constructor and
3106 Search(r'\bstd\s*::\s*initializer_list\b', constructor_args[0]))
3107 copy_constructor = bool(
3108 onearg_constructor and
3109 Match(r'(const\s+)?%s(\s*<[^>]*>)?(\s+const)?\s*(?:<\w+>\s*)?&'
3110 % re.escape(base_classname), constructor_args[0].strip()))
3111
3112 if (not is_marked_explicit and
3113 onearg_constructor and
3114 not initializer_list_constructor and
3115 not copy_constructor):
3116 if defaulted_args:
3117 error(filename, linenum, 'runtime/explicit', 5,
3118 'Constructors callable with one argument '
3119 'should be marked explicit.')
3120 else:
3121 error(filename, linenum, 'runtime/explicit', 5,
3122 'Single-parameter constructors should be marked explicit.')
3123 elif is_marked_explicit and not onearg_constructor:
3124 if noarg_constructor:
3125 error(filename, linenum, 'runtime/explicit', 5,
3126 'Zero-parameter constructors should not be marked explicit.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003127
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003128
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003129def CheckSpacingForFunctionCall(filename, clean_lines, linenum, error):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003130 """Checks for the correctness of various spacing around function calls.
3131
3132 Args:
3133 filename: The name of the current file.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003134 clean_lines: A CleansedLines instance containing the file.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003135 linenum: The number of the line to check.
3136 error: The function to call with any errors found.
3137 """
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003138 line = clean_lines.elided[linenum]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003139
3140 # Since function calls often occur inside if/for/while/switch
3141 # expressions - which have their own, more liberal conventions - we
3142 # first see if we should be looking inside such an expression for a
3143 # function call, to which we can apply more strict standards.
3144 fncall = line # if there's no control flow construct, look at whole line
Darius Maa7d7e42022-05-13 14:54:21 +00003145 for pattern in (r'\bif\s*(?:constexpr\s*)?\((.*)\)\s*{',
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003146 r'\bfor\s*\((.*)\)\s*{',
3147 r'\bwhile\s*\((.*)\)\s*[{;]',
3148 r'\bswitch\s*\((.*)\)\s*{'):
3149 match = Search(pattern, line)
3150 if match:
3151 fncall = match.group(1) # look inside the parens for function calls
3152 break
3153
3154 # Except in if/for/while/switch, there should never be space
3155 # immediately inside parens (eg "f( 3, 4 )"). We make an exception
3156 # for nested parens ( (a+b) + c ). Likewise, there should never be
3157 # a space before a ( when it's a function argument. I assume it's a
3158 # function argument when the char before the whitespace is legal in
3159 # a function name (alnum + _) and we're not starting a macro. Also ignore
3160 # pointers and references to arrays and functions coz they're too tricky:
3161 # we use a very simple way to recognize these:
3162 # " (something)(maybe-something)" or
3163 # " (something)(maybe-something," or
3164 # " (something)[something]"
3165 # Note that we assume the contents of [] to be short enough that
3166 # they'll never need to wrap.
3167 if ( # Ignore control structures.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003168 not Search(r'\b(if|for|while|switch|return|new|delete|catch|sizeof)\b',
3169 fncall) and
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003170 # Ignore pointers/references to functions.
3171 not Search(r' \([^)]+\)\([^)]*(\)|,$)', fncall) and
3172 # Ignore pointers/references to arrays.
3173 not Search(r' \([^)]+\)\[[^\]]+\]', fncall)):
erg@google.com6317a9c2009-06-25 00:28:19 +00003174 if Search(r'\w\s*\(\s(?!\s*\\$)', fncall): # a ( used for a fn call
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003175 error(filename, linenum, 'whitespace/parens', 4,
3176 'Extra space after ( in function call')
erg@google.com6317a9c2009-06-25 00:28:19 +00003177 elif Search(r'\(\s+(?!(\s*\\)|\()', fncall):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003178 error(filename, linenum, 'whitespace/parens', 2,
3179 'Extra space after (')
3180 if (Search(r'\w\s+\(', fncall) and
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003181 not Search(r'_{0,2}asm_{0,2}\s+_{0,2}volatile_{0,2}\s+\(', fncall) and
Bruce Dawson3e87cea2020-04-30 17:56:07 +00003182 not Search(r'#\s*define|typedef|__except|using\s+\w+\s*=', fncall) and
avakulenko@google.com255f2be2014-12-05 22:19:55 +00003183 not Search(r'\w\s+\((\w+::)*\*\w+\)\(', fncall) and
3184 not Search(r'\bcase\s+\(', fncall)):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003185 # TODO(unknown): Space after an operator function seem to be a common
3186 # error, silence those for now by restricting them to highest verbosity.
3187 if Search(r'\boperator_*\b', line):
3188 error(filename, linenum, 'whitespace/parens', 0,
3189 'Extra space before ( in function call')
3190 else:
3191 error(filename, linenum, 'whitespace/parens', 4,
3192 'Extra space before ( in function call')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003193 # If the ) is followed only by a newline or a { + newline, assume it's
3194 # part of a control statement (if/while/etc), and don't complain
3195 if Search(r'[^)]\s+\)\s*[^{\s]', fncall):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003196 # If the closing parenthesis is preceded by only whitespaces,
3197 # try to give a more descriptive error message.
3198 if Search(r'^\s+\)', fncall):
3199 error(filename, linenum, 'whitespace/parens', 2,
3200 'Closing ) should be moved to the previous line')
3201 else:
3202 error(filename, linenum, 'whitespace/parens', 2,
3203 'Extra space before )')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003204
3205
3206def IsBlankLine(line):
3207 """Returns true if the given line is blank.
3208
3209 We consider a line to be blank if the line is empty or consists of
3210 only white spaces.
3211
3212 Args:
3213 line: A line of a string.
3214
3215 Returns:
3216 True, if the given line is blank.
3217 """
3218 return not line or line.isspace()
3219
3220
avakulenko@google.com59146752014-08-11 20:20:55 +00003221def CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line,
3222 error):
3223 is_namespace_indent_item = (
3224 len(nesting_state.stack) > 1 and
3225 nesting_state.stack[-1].check_namespace_indentation and
3226 isinstance(nesting_state.previous_stack_top, _NamespaceInfo) and
3227 nesting_state.previous_stack_top == nesting_state.stack[-2])
3228
3229 if ShouldCheckNamespaceIndentation(nesting_state, is_namespace_indent_item,
3230 clean_lines.elided, line):
3231 CheckItemIndentationInNamespace(filename, clean_lines.elided,
3232 line, error)
3233
3234
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003235def CheckForFunctionLengths(filename, clean_lines, linenum,
3236 function_state, error):
3237 """Reports for long function bodies.
3238
3239 For an overview why this is done, see:
Alexandr Ilinff294c32017-04-27 15:57:40 +02003240 https://google.github.io/styleguide/cppguide.html#Write_Short_Functions
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003241
3242 Uses a simplistic algorithm assuming other style guidelines
3243 (especially spacing) are followed.
3244 Only checks unindented functions, so class members are unchecked.
3245 Trivial bodies are unchecked, so constructors with huge initializer lists
3246 may be missed.
3247 Blank/comment lines are not counted so as to avoid encouraging the removal
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003248 of vertical space and comments just to get through a lint check.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003249 NOLINT *on the last line of a function* disables this check.
3250
3251 Args:
3252 filename: The name of the current file.
3253 clean_lines: A CleansedLines instance containing the file.
3254 linenum: The number of the line to check.
3255 function_state: Current function name and lines in body so far.
3256 error: The function to call with any errors found.
3257 """
3258 lines = clean_lines.lines
3259 line = lines[linenum]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003260 joined_line = ''
3261
3262 starting_func = False
erg@google.com6317a9c2009-06-25 00:28:19 +00003263 regexp = r'(\w(\w|::|\*|\&|\s)*)\(' # decls * & space::name( ...
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003264 match_result = Match(regexp, line)
3265 if match_result:
3266 # If the name is all caps and underscores, figure it's a macro and
3267 # ignore it, unless it's TEST or TEST_F.
3268 function_name = match_result.group(1).split()[-1]
3269 if function_name == 'TEST' or function_name == 'TEST_F' or (
Quinten Yearsley48099572019-02-22 21:13:37 +00003270 not Match(r'[A-Z_0-9]+$', function_name)):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003271 starting_func = True
3272
3273 if starting_func:
3274 body_found = False
Edward Lemur6d31ed52019-12-02 23:00:00 +00003275 for start_linenum in range(linenum, clean_lines.NumLines()):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003276 start_line = lines[start_linenum]
3277 joined_line += ' ' + start_line.lstrip()
3278 if Search(r'(;|})', start_line): # Declarations and trivial functions
3279 body_found = True
3280 break # ... ignore
3281 elif Search(r'{', start_line):
3282 body_found = True
3283 function = Search(r'((\w|:)*)\(', line).group(1)
3284 if Match(r'TEST', function): # Handle TEST... macros
3285 parameter_regexp = Search(r'(\(.*\))', joined_line)
3286 if parameter_regexp: # Ignore bad syntax
3287 function += parameter_regexp.group(1)
3288 else:
3289 function += '()'
3290 function_state.Begin(function)
3291 break
3292 if not body_found:
erg@google.com6317a9c2009-06-25 00:28:19 +00003293 # No body for the function (or evidence of a non-function) was found.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003294 error(filename, linenum, 'readability/fn_size', 5,
3295 'Lint failed to find start of function body.')
3296 elif Match(r'^\}\s*$', line): # function end
erg@google.com35589e62010-11-17 18:58:16 +00003297 function_state.Check(error, filename, linenum)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003298 function_state.End()
3299 elif not Match(r'^\s*$', line):
3300 function_state.Count() # Count non-blank/non-comment lines.
3301
3302
Matthias Liedtke8eac0c62023-07-06 08:09:07 +00003303_RE_PATTERN_TODO = re.compile(
3304 r'^//(\s*)TODO(?:(\(.+?\)):?|:|)(\s|$|[A-Z]*[a-z])')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003305
3306
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003307def CheckComment(line, filename, linenum, next_line_start, error):
3308 """Checks for common mistakes in comments.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003309
3310 Args:
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003311 line: The line in question.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003312 filename: The name of the current file.
3313 linenum: The number of the line to check.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003314 next_line_start: The first non-whitespace column of the next line.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003315 error: The function to call with any errors found.
3316 """
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003317 commentpos = line.find('//')
3318 if commentpos != -1:
3319 # Check if the // may be in quotes. If so, ignore it
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003320 if re.sub(r'\\.', '', line[0:commentpos]).count('"') % 2 == 0:
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003321 # Allow one space for new scopes, two spaces otherwise:
3322 if (not (Match(r'^.*{ *//', line) and next_line_start == commentpos) and
3323 ((commentpos >= 1 and
3324 line[commentpos-1] not in string.whitespace) or
3325 (commentpos >= 2 and
3326 line[commentpos-2] not in string.whitespace))):
3327 error(filename, linenum, 'whitespace/comments', 2,
3328 'At least two spaces is best between code and comments')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003329
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003330 # Checks for common mistakes in TODO comments.
3331 comment = line[commentpos:]
3332 match = _RE_PATTERN_TODO.match(comment)
3333 if match:
3334 # One whitespace is correct; zero whitespace is handled elsewhere.
3335 leading_whitespace = match.group(1)
3336 if len(leading_whitespace) > 1:
3337 error(filename, linenum, 'whitespace/todo', 2,
3338 'Too many spaces before TODO')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003339
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003340 username = match.group(2)
3341 if not username:
3342 error(filename, linenum, 'readability/todo', 2,
3343 'Missing username in TODO; it should look like '
3344 '"// TODO(my_username): Stuff."')
3345
3346 middle_whitespace = match.group(3)
3347 # Comparisons made explicit for correctness -- pylint: disable=g-explicit-bool-comparison
3348 if middle_whitespace != ' ' and middle_whitespace != '':
3349 error(filename, linenum, 'whitespace/todo', 2,
3350 'TODO(my_username) should be followed by a space')
3351
3352 # If the comment contains an alphanumeric character, there
avakulenko@google.com255f2be2014-12-05 22:19:55 +00003353 # should be a space somewhere between it and the // unless
3354 # it's a /// or //! Doxygen comment.
3355 if (Match(r'//[^ ]*\w', comment) and
3356 not Match(r'(///|//\!)(\s+|$)', comment)):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003357 error(filename, linenum, 'whitespace/comments', 4,
3358 'Should have a space between // and comment')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003359
avakulenko@google.com255f2be2014-12-05 22:19:55 +00003360
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003361def CheckSpacing(filename, clean_lines, linenum, nesting_state, error):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003362 """Checks for the correctness of various spacing issues in the code.
3363
3364 Things we check for: spaces around operators, spaces after
3365 if/for/while/switch, no spaces around parens in function calls, two
3366 spaces between code and comment, don't start a block with a blank
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003367 line, don't end a function with a blank line, don't add a blank line
3368 after public/protected/private, don't have too many blank lines in a row.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003369
3370 Args:
3371 filename: The name of the current file.
3372 clean_lines: A CleansedLines instance containing the file.
3373 linenum: The number of the line to check.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003374 nesting_state: A NestingState instance which maintains information about
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003375 the current stack of nested blocks being parsed.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003376 error: The function to call with any errors found.
3377 """
3378
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003379 # Don't use "elided" lines here, otherwise we can't check commented lines.
3380 # Don't want to use "raw" either, because we don't want to check inside C++11
3381 # raw strings,
3382 raw = clean_lines.lines_without_raw_strings
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003383 line = raw[linenum]
3384
3385 # Before nixing comments, check if the line is blank for no good
3386 # reason. This includes the first line after a block is opened, and
3387 # blank lines at the end of a function (ie, right before a line like '}'
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003388 #
3389 # Skip all the blank line checks if we are immediately inside a
3390 # namespace body. In other words, don't issue blank line warnings
3391 # for this block:
3392 # namespace {
3393 #
3394 # }
3395 #
3396 # A warning about missing end of namespace comments will be issued instead.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003397 #
3398 # Also skip blank line checks for 'extern "C"' blocks, which are formatted
3399 # like namespaces.
3400 if (IsBlankLine(line) and
3401 not nesting_state.InNamespaceBody() and
3402 not nesting_state.InExternC()):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003403 elided = clean_lines.elided
3404 prev_line = elided[linenum - 1]
3405 prevbrace = prev_line.rfind('{')
3406 # TODO(unknown): Don't complain if line before blank line, and line after,
3407 # both start with alnums and are indented the same amount.
3408 # This ignores whitespace at the start of a namespace block
3409 # because those are not usually indented.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003410 if prevbrace != -1 and prev_line[prevbrace:].find('}') == -1:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003411 # OK, we have a blank line at the start of a code block. Before we
3412 # complain, we check if it is an exception to the rule: The previous
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003413 # non-empty line has the parameters of a function header that are indented
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003414 # 4 spaces (because they did not fit in a 80 column line when placed on
3415 # the same line as the function name). We also check for the case where
3416 # the previous line is indented 6 spaces, which may happen when the
3417 # initializers of a constructor do not fit into a 80 column line.
3418 exception = False
3419 if Match(r' {6}\w', prev_line): # Initializer list?
3420 # We are looking for the opening column of initializer list, which
3421 # should be indented 4 spaces to cause 6 space indentation afterwards.
3422 search_position = linenum-2
3423 while (search_position >= 0
3424 and Match(r' {6}\w', elided[search_position])):
3425 search_position -= 1
3426 exception = (search_position >= 0
3427 and elided[search_position][:5] == ' :')
3428 else:
3429 # Search for the function arguments or an initializer list. We use a
3430 # simple heuristic here: If the line is indented 4 spaces; and we have a
3431 # closing paren, without the opening paren, followed by an opening brace
3432 # or colon (for initializer lists) we assume that it is the last line of
3433 # a function header. If we have a colon indented 4 spaces, it is an
3434 # initializer list.
3435 exception = (Match(r' {4}\w[^\(]*\)\s*(const\s*)?(\{\s*$|:)',
3436 prev_line)
3437 or Match(r' {4}:', prev_line))
3438
3439 if not exception:
3440 error(filename, linenum, 'whitespace/blank_line', 2,
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003441 'Redundant blank line at the start of a code block '
3442 'should be deleted.')
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003443 # Ignore blank lines at the end of a block in a long if-else
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003444 # chain, like this:
3445 # if (condition1) {
3446 # // Something followed by a blank line
3447 #
3448 # } else if (condition2) {
3449 # // Something else
3450 # }
3451 if linenum + 1 < clean_lines.NumLines():
3452 next_line = raw[linenum + 1]
3453 if (next_line
3454 and Match(r'\s*}', next_line)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003455 and next_line.find('} else ') == -1):
3456 error(filename, linenum, 'whitespace/blank_line', 3,
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003457 'Redundant blank line at the end of a code block '
3458 'should be deleted.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003459
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003460 matched = Match(r'\s*(public|protected|private):', prev_line)
3461 if matched:
3462 error(filename, linenum, 'whitespace/blank_line', 3,
3463 'Do not leave a blank line after "%s:"' % matched.group(1))
3464
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003465 # Next, check comments
3466 next_line_start = 0
3467 if linenum + 1 < clean_lines.NumLines():
3468 next_line = raw[linenum + 1]
3469 next_line_start = len(next_line) - len(next_line.lstrip())
3470 CheckComment(line, filename, linenum, next_line_start, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003471
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003472 # get rid of comments and strings
3473 line = clean_lines.elided[linenum]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003474
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003475 # You shouldn't have spaces before your brackets, except maybe after
Alex Lightac54b8d2022-01-20 13:02:48 +00003476 # 'delete []', 'return []() {};', 'auto [abc, ...] = ...;' or in the case of
3477 # c++ attributes like 'class [[clang::lto_visibility_public]] MyClass'.
Derek Morrisb8265f12020-04-16 18:40:27 +00003478 if (Search(r'\w\s+\[', line)
Alex Lightac54b8d2022-01-20 13:02:48 +00003479 and not Search(r'(?:auto&?|delete|return)\s+\[', line)
Derek Morrisb8265f12020-04-16 18:40:27 +00003480 and not Search(r'\s+\[\[', line)):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003481 error(filename, linenum, 'whitespace/braces', 5,
3482 'Extra space before [')
3483
3484 # In range-based for, we wanted spaces before and after the colon, but
3485 # not around "::" tokens that might appear.
3486 if (Search(r'for *\(.*[^:]:[^: ]', line) or
3487 Search(r'for *\(.*[^: ]:[^:]', line)):
3488 error(filename, linenum, 'whitespace/forcolon', 2,
3489 'Missing space around colon in range-based for loop')
3490
3491
3492def CheckOperatorSpacing(filename, clean_lines, linenum, error):
3493 """Checks for horizontal spacing around operators.
3494
3495 Args:
3496 filename: The name of the current file.
3497 clean_lines: A CleansedLines instance containing the file.
3498 linenum: The number of the line to check.
3499 error: The function to call with any errors found.
3500 """
3501 line = clean_lines.elided[linenum]
3502
3503 # Don't try to do spacing checks for operator methods. Do this by
3504 # replacing the troublesome characters with something else,
3505 # preserving column position for all other characters.
3506 #
3507 # The replacement is done repeatedly to avoid false positives from
3508 # operators that call operators.
3509 while True:
3510 match = Match(r'^(.*\boperator\b)(\S+)(\s*\(.*)$', line)
3511 if match:
3512 line = match.group(1) + ('_' * len(match.group(2))) + match.group(3)
3513 else:
3514 break
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003515
3516 # We allow no-spaces around = within an if: "if ( (a=Foo()) == 0 )".
3517 # Otherwise not. Note we only check for non-spaces on *both* sides;
3518 # sometimes people put non-spaces on one side when aligning ='s among
3519 # many lines (not that this is behavior that I approve of...)
avakulenko@google.com255f2be2014-12-05 22:19:55 +00003520 if ((Search(r'[\w.]=', line) or
3521 Search(r'=[\w.]', line))
3522 and not Search(r'\b(if|while|for) ', line)
3523 # Operators taken from [lex.operators] in C++11 standard.
3524 and not Search(r'(>=|<=|==|!=|&=|\^=|\|=|\+=|\*=|\/=|\%=)', line)
3525 and not Search(r'operator=', line)):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003526 error(filename, linenum, 'whitespace/operators', 4,
3527 'Missing spaces around =')
3528
3529 # It's ok not to have spaces around binary operators like + - * /, but if
3530 # there's too little whitespace, we get concerned. It's hard to tell,
3531 # though, so we punt on this one for now. TODO.
3532
3533 # You should always have whitespace around binary operators.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003534 #
3535 # Check <= and >= first to avoid false positives with < and >, then
3536 # check non-include lines for spacing around < and >.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003537 #
3538 # If the operator is followed by a comma, assume it's be used in a
3539 # macro context and don't do any checks. This avoids false
3540 # positives.
3541 #
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003542 # Note that && is not included here. This is because there are too
3543 # many false positives due to RValue references.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003544 match = Search(r'[^<>=!\s](==|!=|<=|>=|\|\|)[^<>=!\s,;\)]', line)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003545 if match:
3546 error(filename, linenum, 'whitespace/operators', 3,
3547 'Missing spaces around %s' % match.group(1))
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003548 elif not Match(r'#.*include', line):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003549 # Look for < that is not surrounded by spaces. This is only
3550 # triggered if both sides are missing spaces, even though
3551 # technically should should flag if at least one side is missing a
3552 # space. This is done to avoid some false positives with shifts.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003553 match = Match(r'^(.*[^\s<])<[^\s=<,]', line)
3554 if match:
3555 (_, _, end_pos) = CloseExpression(
3556 clean_lines, linenum, len(match.group(1)))
3557 if end_pos <= -1:
3558 error(filename, linenum, 'whitespace/operators', 3,
3559 'Missing spaces around <')
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003560
3561 # Look for > that is not surrounded by spaces. Similar to the
3562 # above, we only trigger if both sides are missing spaces to avoid
3563 # false positives with shifts.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003564 match = Match(r'^(.*[^-\s>])>[^\s=>,]', line)
3565 if match:
3566 (_, _, start_pos) = ReverseCloseExpression(
3567 clean_lines, linenum, len(match.group(1)))
3568 if start_pos <= -1:
3569 error(filename, linenum, 'whitespace/operators', 3,
3570 'Missing spaces around >')
3571
3572 # We allow no-spaces around << when used like this: 10<<20, but
3573 # not otherwise (particularly, not when used as streams)
avakulenko@google.com59146752014-08-11 20:20:55 +00003574 #
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003575 # We also allow operators following an opening parenthesis, since
3576 # those tend to be macros that deal with operators.
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003577 match = Search(r'(operator|[^\s(<])(?:L|UL|LL|ULL|l|ul|ll|ull)?<<([^\s,=<])', line)
avakulenko@google.com255f2be2014-12-05 22:19:55 +00003578 if (match and not (match.group(1).isdigit() and match.group(2).isdigit()) and
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003579 not (match.group(1) == 'operator' and match.group(2) == ';')):
3580 error(filename, linenum, 'whitespace/operators', 3,
3581 'Missing spaces around <<')
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003582
3583 # We allow no-spaces around >> for almost anything. This is because
3584 # C++11 allows ">>" to close nested templates, which accounts for
3585 # most cases when ">>" is not followed by a space.
3586 #
3587 # We still warn on ">>" followed by alpha character, because that is
3588 # likely due to ">>" being used for right shifts, e.g.:
3589 # value >> alpha
3590 #
3591 # When ">>" is used to close templates, the alphanumeric letter that
3592 # follows would be part of an identifier, and there should still be
3593 # a space separating the template type and the identifier.
3594 # type<type<type>> alpha
3595 match = Search(r'>>[a-zA-Z_]', line)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003596 if match:
3597 error(filename, linenum, 'whitespace/operators', 3,
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003598 'Missing spaces around >>')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003599
3600 # There shouldn't be space around unary operators
3601 match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line)
3602 if match:
3603 error(filename, linenum, 'whitespace/operators', 4,
3604 'Extra space for operator %s' % match.group(1))
3605
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003606
3607def CheckParenthesisSpacing(filename, clean_lines, linenum, error):
3608 """Checks for horizontal spacing around parentheses.
3609
3610 Args:
3611 filename: The name of the current file.
3612 clean_lines: A CleansedLines instance containing the file.
3613 linenum: The number of the line to check.
3614 error: The function to call with any errors found.
3615 """
3616 line = clean_lines.elided[linenum]
3617
3618 # No spaces after an if, while, switch, or for
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003619 match = Search(r' (if\(|for\(|while\(|switch\()', line)
3620 if match:
3621 error(filename, linenum, 'whitespace/parens', 5,
3622 'Missing space before ( in %s' % match.group(1))
3623
3624 # For if/for/while/switch, the left and right parens should be
3625 # consistent about how many spaces are inside the parens, and
3626 # there should either be zero or one spaces inside the parens.
3627 # We don't want: "if ( foo)" or "if ( foo )".
erg@google.com6317a9c2009-06-25 00:28:19 +00003628 # Exception: "for ( ; foo; bar)" and "for (foo; bar; )" are allowed.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003629 match = Search(r'\b(if|for|while|switch)\s*'
3630 r'\(([ ]*)(.).*[^ ]+([ ]*)\)\s*{\s*$',
3631 line)
3632 if match:
3633 if len(match.group(2)) != len(match.group(4)):
3634 if not (match.group(3) == ';' and
erg@google.com6317a9c2009-06-25 00:28:19 +00003635 len(match.group(2)) == 1 + len(match.group(4)) or
3636 not match.group(2) and Search(r'\bfor\s*\(.*; \)', line)):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003637 error(filename, linenum, 'whitespace/parens', 5,
3638 'Mismatching spaces inside () in %s' % match.group(1))
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003639 if len(match.group(2)) not in [0, 1]:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003640 error(filename, linenum, 'whitespace/parens', 5,
3641 'Should have zero or one spaces inside ( and ) in %s' %
3642 match.group(1))
3643
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003644
3645def CheckCommaSpacing(filename, clean_lines, linenum, error):
3646 """Checks for horizontal spacing near commas and semicolons.
3647
3648 Args:
3649 filename: The name of the current file.
3650 clean_lines: A CleansedLines instance containing the file.
3651 linenum: The number of the line to check.
3652 error: The function to call with any errors found.
3653 """
3654 raw = clean_lines.lines_without_raw_strings
3655 line = clean_lines.elided[linenum]
3656
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003657 # 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 +00003658 #
3659 # This does not apply when the non-space character following the
3660 # comma is another comma, since the only time when that happens is
3661 # for empty macro arguments.
3662 #
3663 # We run this check in two passes: first pass on elided lines to
3664 # verify that lines contain missing whitespaces, second pass on raw
3665 # lines to confirm that those missing whitespaces are not due to
3666 # elided comments.
avakulenko@google.com59146752014-08-11 20:20:55 +00003667 if (Search(r',[^,\s]', ReplaceAll(r'\boperator\s*,\s*\(', 'F(', line)) and
3668 Search(r',[^,\s]', raw[linenum])):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003669 error(filename, linenum, 'whitespace/comma', 3,
3670 'Missing space after ,')
3671
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003672 # You should always have a space after a semicolon
3673 # except for few corner cases
3674 # TODO(unknown): clarify if 'if (1) { return 1;}' is requires one more
3675 # space after ;
3676 if Search(r';[^\s};\\)/]', line):
3677 error(filename, linenum, 'whitespace/semicolon', 3,
3678 'Missing space after ;')
3679
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003680
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003681def _IsType(clean_lines, nesting_state, expr):
3682 """Check if expression looks like a type name, returns true if so.
3683
3684 Args:
3685 clean_lines: A CleansedLines instance containing the file.
3686 nesting_state: A NestingState instance which maintains information about
3687 the current stack of nested blocks being parsed.
3688 expr: The expression to check.
3689 Returns:
3690 True, if token looks like a type.
3691 """
3692 # Keep only the last token in the expression
3693 last_word = Match(r'^.*(\b\S+)$', expr)
3694 if last_word:
3695 token = last_word.group(1)
3696 else:
3697 token = expr
3698
3699 # Match native types and stdint types
3700 if _TYPES.match(token):
3701 return True
3702
3703 # Try a bit harder to match templated types. Walk up the nesting
3704 # stack until we find something that resembles a typename
3705 # declaration for what we are looking for.
3706 typename_pattern = (r'\b(?:typename|class|struct)\s+' + re.escape(token) +
3707 r'\b')
3708 block_index = len(nesting_state.stack) - 1
3709 while block_index >= 0:
3710 if isinstance(nesting_state.stack[block_index], _NamespaceInfo):
3711 return False
3712
3713 # Found where the opening brace is. We want to scan from this
3714 # line up to the beginning of the function, minus a few lines.
3715 # template <typename Type1, // stop scanning here
3716 # ...>
3717 # class C
3718 # : public ... { // start scanning here
3719 last_line = nesting_state.stack[block_index].starting_linenum
3720
3721 next_block_start = 0
3722 if block_index > 0:
3723 next_block_start = nesting_state.stack[block_index - 1].starting_linenum
3724 first_line = last_line
3725 while first_line >= next_block_start:
3726 if clean_lines.elided[first_line].find('template') >= 0:
3727 break
3728 first_line -= 1
3729 if first_line < next_block_start:
3730 # Didn't find any "template" keyword before reaching the next block,
3731 # there are probably no template things to check for this block
3732 block_index -= 1
3733 continue
3734
3735 # Look for typename in the specified range
Edward Lemur6d31ed52019-12-02 23:00:00 +00003736 for i in range(first_line, last_line + 1, 1):
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003737 if Search(typename_pattern, clean_lines.elided[i]):
3738 return True
3739 block_index -= 1
3740
3741 return False
3742
3743
3744def CheckBracesSpacing(filename, clean_lines, linenum, nesting_state, error):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003745 """Checks for horizontal spacing near commas.
3746
3747 Args:
3748 filename: The name of the current file.
3749 clean_lines: A CleansedLines instance containing the file.
3750 linenum: The number of the line to check.
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003751 nesting_state: A NestingState instance which maintains information about
3752 the current stack of nested blocks being parsed.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003753 error: The function to call with any errors found.
3754 """
3755 line = clean_lines.elided[linenum]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003756
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003757 # Except after an opening paren, or after another opening brace (in case of
3758 # an initializer list, for instance), you should have spaces before your
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003759 # braces when they are delimiting blocks, classes, namespaces etc.
3760 # And since you should never have braces at the beginning of a line,
3761 # this is an easy test. Except that braces used for initialization don't
3762 # follow the same rule; we often don't want spaces before those.
avakulenko@google.com255f2be2014-12-05 22:19:55 +00003763 match = Match(r'^(.*[^ ({>]){', line)
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003764
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003765 if match:
3766 # Try a bit harder to check for brace initialization. This
3767 # happens in one of the following forms:
3768 # Constructor() : initializer_list_{} { ... }
3769 # Constructor{}.MemberFunction()
3770 # Type variable{};
3771 # FunctionCall(type{}, ...);
3772 # LastArgument(..., type{});
3773 # LOG(INFO) << type{} << " ...";
3774 # map_of_type[{...}] = ...;
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003775 # ternary = expr ? new type{} : nullptr;
3776 # OuterTemplate<InnerTemplateConstructor<Type>{}>
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003777 #
3778 # We check for the character following the closing brace, and
3779 # silence the warning if it's one of those listed above, i.e.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003780 # "{.;,)<>]:".
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003781 #
3782 # To account for nested initializer list, we allow any number of
3783 # closing braces up to "{;,)<". We can't simply silence the
3784 # warning on first sight of closing brace, because that would
3785 # cause false negatives for things that are not initializer lists.
3786 # Silence this: But not this:
3787 # Outer{ if (...) {
3788 # Inner{...} if (...){ // Missing space before {
3789 # }; }
3790 #
3791 # There is a false negative with this approach if people inserted
3792 # spurious semicolons, e.g. "if (cond){};", but we will catch the
3793 # spurious semicolon with a separate check.
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003794 leading_text = match.group(1)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003795 (endline, endlinenum, endpos) = CloseExpression(
3796 clean_lines, linenum, len(match.group(1)))
3797 trailing_text = ''
3798 if endpos > -1:
3799 trailing_text = endline[endpos:]
Edward Lemur6d31ed52019-12-02 23:00:00 +00003800 for offset in range(endlinenum + 1,
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003801 min(endlinenum + 3, clean_lines.NumLines() - 1)):
3802 trailing_text += clean_lines.elided[offset]
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003803 # We also suppress warnings for `uint64_t{expression}` etc., as the style
3804 # guide recommends brace initialization for integral types to avoid
3805 # overflow/truncation.
3806 if (not Match(r'^[\s}]*[{.;,)<>\]:]', trailing_text)
3807 and not _IsType(clean_lines, nesting_state, leading_text)):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003808 error(filename, linenum, 'whitespace/braces', 5,
3809 'Missing space before {')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003810
3811 # Make sure '} else {' has spaces.
3812 if Search(r'}else', line):
3813 error(filename, linenum, 'whitespace/braces', 5,
3814 'Missing space before else')
3815
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003816 # You shouldn't have a space before a semicolon at the end of the line.
3817 # There's a special case for "for" since the style guide allows space before
3818 # the semicolon there.
3819 if Search(r':\s*;\s*$', line):
3820 error(filename, linenum, 'whitespace/semicolon', 5,
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003821 'Semicolon defining empty statement. Use {} instead.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003822 elif Search(r'^\s*;\s*$', line):
3823 error(filename, linenum, 'whitespace/semicolon', 5,
3824 'Line contains only semicolon. If this should be an empty statement, '
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003825 'use {} instead.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003826 elif (Search(r'\s+;\s*$', line) and
3827 not Search(r'\bfor\b', line)):
3828 error(filename, linenum, 'whitespace/semicolon', 5,
3829 'Extra space before last semicolon. If this should be an empty '
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003830 'statement, use {} instead.')
3831
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003832
3833def IsDecltype(clean_lines, linenum, column):
3834 """Check if the token ending on (linenum, column) is decltype().
3835
3836 Args:
3837 clean_lines: A CleansedLines instance containing the file.
3838 linenum: the number of the line to check.
3839 column: end column of the token to check.
3840 Returns:
3841 True if this token is decltype() expression, False otherwise.
3842 """
3843 (text, _, start_col) = ReverseCloseExpression(clean_lines, linenum, column)
3844 if start_col < 0:
3845 return False
3846 if Search(r'\bdecltype\s*$', text[0:start_col]):
3847 return True
3848 return False
3849
3850
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003851def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error):
3852 """Checks for additional blank line issues related to sections.
3853
3854 Currently the only thing checked here is blank line before protected/private.
3855
3856 Args:
3857 filename: The name of the current file.
3858 clean_lines: A CleansedLines instance containing the file.
3859 class_info: A _ClassInfo objects.
3860 linenum: The number of the line to check.
3861 error: The function to call with any errors found.
3862 """
3863 # Skip checks if the class is small, where small means 25 lines or less.
3864 # 25 lines seems like a good cutoff since that's the usual height of
3865 # terminals, and any class that can't fit in one screen can't really
3866 # be considered "small".
3867 #
3868 # Also skip checks if we are on the first line. This accounts for
3869 # classes that look like
3870 # class Foo { public: ... };
3871 #
3872 # If we didn't find the end of the class, last_line would be zero,
3873 # and the check will be skipped by the first condition.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003874 if (class_info.last_line - class_info.starting_linenum <= 24 or
3875 linenum <= class_info.starting_linenum):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003876 return
3877
3878 matched = Match(r'\s*(public|protected|private):', clean_lines.lines[linenum])
3879 if matched:
3880 # Issue warning if the line before public/protected/private was
3881 # not a blank line, but don't do this if the previous line contains
3882 # "class" or "struct". This can happen two ways:
3883 # - We are at the beginning of the class.
3884 # - We are forward-declaring an inner class that is semantically
3885 # private, but needed to be public for implementation reasons.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003886 # Also ignores cases where the previous line ends with a backslash as can be
3887 # common when defining classes in C macros.
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003888 prev_line = clean_lines.lines[linenum - 1]
3889 if (not IsBlankLine(prev_line) and
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003890 not Search(r'\b(class|struct)\b', prev_line) and
3891 not Search(r'\\$', prev_line)):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003892 # Try a bit harder to find the beginning of the class. This is to
3893 # account for multi-line base-specifier lists, e.g.:
3894 # class Derived
3895 # : public Base {
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003896 end_class_head = class_info.starting_linenum
3897 for i in range(class_info.starting_linenum, linenum):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003898 if Search(r'\{\s*$', clean_lines.lines[i]):
3899 end_class_head = i
3900 break
3901 if end_class_head < linenum - 1:
3902 error(filename, linenum, 'whitespace/blank_line', 3,
3903 '"%s:" should be preceded by a blank line' % matched.group(1))
3904
3905
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003906def GetPreviousNonBlankLine(clean_lines, linenum):
3907 """Return the most recent non-blank line and its line number.
3908
3909 Args:
3910 clean_lines: A CleansedLines instance containing the file contents.
3911 linenum: The number of the line to check.
3912
3913 Returns:
3914 A tuple with two elements. The first element is the contents of the last
3915 non-blank line before the current line, or the empty string if this is the
3916 first non-blank line. The second is the line number of that line, or -1
3917 if this is the first non-blank line.
3918 """
3919
3920 prevlinenum = linenum - 1
3921 while prevlinenum >= 0:
3922 prevline = clean_lines.elided[prevlinenum]
3923 if not IsBlankLine(prevline): # if not a blank line...
3924 return (prevline, prevlinenum)
3925 prevlinenum -= 1
3926 return ('', -1)
3927
3928
3929def CheckBraces(filename, clean_lines, linenum, error):
3930 """Looks for misplaced braces (e.g. at the end of line).
3931
3932 Args:
3933 filename: The name of the current file.
3934 clean_lines: A CleansedLines instance containing the file.
3935 linenum: The number of the line to check.
3936 error: The function to call with any errors found.
3937 """
3938
3939 line = clean_lines.elided[linenum] # get rid of comments and strings
3940
3941 if Match(r'\s*{\s*$', line):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003942 # We allow an open brace to start a line in the case where someone is using
3943 # braces in a block to explicitly create a new scope, which is commonly used
3944 # to control the lifetime of stack-allocated variables. Braces are also
3945 # used for brace initializers inside function calls. We don't detect this
3946 # perfectly: we just don't complain if the last non-whitespace character on
3947 # the previous non-blank line is ',', ';', ':', '(', '{', or '}', or if the
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003948 # previous line starts a preprocessor block. We also allow a brace on the
3949 # following line if it is part of an array initialization and would not fit
3950 # within the 80 character limit of the preceding line.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003951 prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003952 if (not Search(r'[,;:}{(]\s*$', prevline) and
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003953 not Match(r'\s*#', prevline) and
3954 not (GetLineWidth(prevline) > _line_length - 2 and '[]' in prevline)):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003955 error(filename, linenum, 'whitespace/braces', 4,
3956 '{ should almost always be at the end of the previous line')
3957
3958 # An else clause should be on the same line as the preceding closing brace.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003959 if Match(r'\s*else\b\s*(?:if\b|\{|$)', line):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003960 prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
3961 if Match(r'\s*}\s*$', prevline):
3962 error(filename, linenum, 'whitespace/newline', 4,
3963 'An else should appear on the same line as the preceding }')
3964
3965 # If braces come on one side of an else, they should be on both.
3966 # However, we have to worry about "else if" that spans multiple lines!
Darius Maa7d7e42022-05-13 14:54:21 +00003967 if Search(r'else if\s*(?:constexpr\s*)?\(', line): # could be multi-line if
3968 brace_on_left = bool(Search(r'}\s*else if\s*(?:constexpr\s*)?\(', line))
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003969 # find the ( after the if
3970 pos = line.find('else if')
3971 pos = line.find('(', pos)
3972 if pos > 0:
3973 (endline, _, endpos) = CloseExpression(clean_lines, linenum, pos)
3974 brace_on_right = endline[endpos:].find('{') != -1
3975 if brace_on_left != brace_on_right: # must be brace after if
3976 error(filename, linenum, 'readability/braces', 5,
3977 'If an else has a brace on one side, it should have it on both')
3978 elif Search(r'}\s*else[^{]*$', line) or Match(r'[^}]*else\s*{', line):
3979 error(filename, linenum, 'readability/braces', 5,
3980 'If an else has a brace on one side, it should have it on both')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003981
3982 # Likewise, an else should never have the else clause on the same line
3983 if Search(r'\belse [^\s{]', line) and not Search(r'\belse if\b', line):
3984 error(filename, linenum, 'whitespace/newline', 4,
3985 'Else clause should never be on same line as else (use 2 lines)')
3986
3987 # In the same way, a do/while should never be on one line
3988 if Match(r'\s*do [^\s{]', line):
3989 error(filename, linenum, 'whitespace/newline', 4,
3990 'do/while clauses should not be on a single line')
3991
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003992 # Check single-line if/else bodies. The style guide says 'curly braces are not
3993 # required for single-line statements'. We additionally allow multi-line,
3994 # single statements, but we reject anything with more than one semicolon in
3995 # it. This means that the first semicolon after the if should be at the end of
3996 # its line, and the line after that should have an indent level equal to or
3997 # lower than the if. We also check for ambiguous if/else nesting without
3998 # braces.
Darius Maa7d7e42022-05-13 14:54:21 +00003999 if_else_match = Search(r'\b(if\s*(?:constexpr\s*)?\(|else\b)', line)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004000 if if_else_match and not Match(r'\s*#', line):
4001 if_indent = GetIndentLevel(line)
4002 endline, endlinenum, endpos = line, linenum, if_else_match.end()
Darius Maa7d7e42022-05-13 14:54:21 +00004003 if_match = Search(r'\bif\s*(?:constexpr\s*)?\(', line)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004004 if if_match:
4005 # This could be a multiline if condition, so find the end first.
4006 pos = if_match.end() - 1
4007 (endline, endlinenum, endpos) = CloseExpression(clean_lines, linenum, pos)
4008 # Check for an opening brace, either directly after the if or on the next
4009 # line. If found, this isn't a single-statement conditional.
4010 if (not Match(r'\s*{', endline[endpos:])
4011 and not (Match(r'\s*$', endline[endpos:])
4012 and endlinenum < (len(clean_lines.elided) - 1)
4013 and Match(r'\s*{', clean_lines.elided[endlinenum + 1]))):
4014 while (endlinenum < len(clean_lines.elided)
4015 and ';' not in clean_lines.elided[endlinenum][endpos:]):
4016 endlinenum += 1
4017 endpos = 0
4018 if endlinenum < len(clean_lines.elided):
4019 endline = clean_lines.elided[endlinenum]
4020 # We allow a mix of whitespace and closing braces (e.g. for one-liner
4021 # methods) and a single \ after the semicolon (for macros)
4022 endpos = endline.find(';')
4023 if not Match(r';[\s}]*(\\?)$', endline[endpos:]):
avakulenko@google.com59146752014-08-11 20:20:55 +00004024 # Semicolon isn't the last character, there's something trailing.
4025 # Output a warning if the semicolon is not contained inside
4026 # a lambda expression.
4027 if not Match(r'^[^{};]*\[[^\[\]]*\][^{}]*\{[^{}]*\}\s*\)*[;,]\s*$',
4028 endline):
4029 error(filename, linenum, 'readability/braces', 4,
4030 'If/else bodies with multiple statements require braces')
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004031 elif endlinenum < len(clean_lines.elided) - 1:
4032 # Make sure the next line is dedented
4033 next_line = clean_lines.elided[endlinenum + 1]
4034 next_indent = GetIndentLevel(next_line)
4035 # With ambiguous nested if statements, this will error out on the
4036 # if that *doesn't* match the else, regardless of whether it's the
4037 # inner one or outer one.
4038 if (if_match and Match(r'\s*else\b', next_line)
4039 and next_indent != if_indent):
4040 error(filename, linenum, 'readability/braces', 4,
4041 'Else clause should be indented at the same level as if. '
4042 'Ambiguous nested if/else chains require braces.')
4043 elif next_indent > if_indent:
4044 error(filename, linenum, 'readability/braces', 4,
4045 'If/else bodies with multiple statements require braces')
4046
4047
4048def CheckTrailingSemicolon(filename, clean_lines, linenum, error):
4049 """Looks for redundant trailing semicolon.
4050
4051 Args:
4052 filename: The name of the current file.
4053 clean_lines: A CleansedLines instance containing the file.
4054 linenum: The number of the line to check.
4055 error: The function to call with any errors found.
4056 """
4057
4058 line = clean_lines.elided[linenum]
4059
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004060 # Block bodies should not be followed by a semicolon. Due to C++11
Peter Kasting00741582023-02-16 20:09:51 +00004061 # brace initialization and C++20 concepts, there are more places
4062 # where semicolons are required than not. Places that are
4063 # recognized as true positives are listed below.
4064 #
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004065 # 1. Some flavor of block following closing parenthesis:
4066 # for (;;) {};
4067 # while (...) {};
4068 # switch (...) {};
4069 # Function(...) {};
4070 # if (...) {};
4071 # if (...) else if (...) {};
4072 #
4073 # 2. else block:
4074 # if (...) else {};
4075 #
4076 # 3. const member function:
4077 # Function(...) const {};
4078 #
4079 # 4. Block following some statement:
4080 # x = 42;
4081 # {};
4082 #
4083 # 5. Block at the beginning of a function:
4084 # Function(...) {
4085 # {};
4086 # }
4087 #
4088 # Note that naively checking for the preceding "{" will also match
4089 # braces inside multi-dimensional arrays, but this is fine since
4090 # that expression will not contain semicolons.
4091 #
4092 # 6. Block following another block:
4093 # while (true) {}
4094 # {};
4095 #
4096 # 7. End of namespaces:
4097 # namespace {};
4098 #
4099 # These semicolons seems far more common than other kinds of
4100 # redundant semicolons, possibly due to people converting classes
4101 # to namespaces. For now we do not warn for this case.
4102 #
4103 # Try matching case 1 first.
4104 match = Match(r'^(.*\)\s*)\{', line)
4105 if match:
4106 # Matched closing parenthesis (case 1). Check the token before the
4107 # matching opening parenthesis, and don't warn if it looks like a
4108 # macro. This avoids these false positives:
4109 # - macro that defines a base class
4110 # - multi-line macro that defines a base class
4111 # - macro that defines the whole class-head
4112 #
4113 # But we still issue warnings for macros that we know are safe to
4114 # warn, specifically:
4115 # - TEST, TEST_F, TEST_P, MATCHER, MATCHER_P
4116 # - TYPED_TEST
4117 # - INTERFACE_DEF
4118 # - EXCLUSIVE_LOCKS_REQUIRED, SHARED_LOCKS_REQUIRED, LOCKS_EXCLUDED:
4119 #
Ayu Ishii09858612020-06-26 18:00:52 +00004120 # We implement an allowlist of safe macros instead of a blocklist of
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004121 # unsafe macros, even though the latter appears less frequently in
Ayu Ishii09858612020-06-26 18:00:52 +00004122 # google code and would have been easier to implement. This is because
4123 # the downside for getting the allowlist wrong means some extra
4124 # semicolons, while the downside for getting the blocklist wrong
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004125 # would result in compile errors.
4126 #
avakulenko@google.com255f2be2014-12-05 22:19:55 +00004127 # In addition to macros, we also don't want to warn on
4128 # - Compound literals
4129 # - Lambdas
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004130 # - alignas specifier with anonymous structs
4131 # - decltype
Peter Kasting00741582023-02-16 20:09:51 +00004132 # - Type casts with parentheses, e.g.: var = (Type){value};
4133 # - Return type casts with parentheses, e.g.: return (Type){value};
4134 # - Function pointers with initializer list, e.g.: int (*f)(){};
4135 # - Requires expression, e.g. C = requires(){};
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004136 closing_brace_pos = match.group(1).rfind(')')
4137 opening_parenthesis = ReverseCloseExpression(
4138 clean_lines, linenum, closing_brace_pos)
4139 if opening_parenthesis[2] > -1:
4140 line_prefix = opening_parenthesis[0][0:opening_parenthesis[2]]
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004141 macro = Search(r'\b([A-Z_][A-Z0-9_]*)\s*$', line_prefix)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004142 func = Match(r'^(.*\])\s*$', line_prefix)
Peter Kasting00741582023-02-16 20:09:51 +00004143 if ((macro and macro.group(1) not in
4144 ('TEST', 'TEST_F', 'MATCHER', 'MATCHER_P', 'TYPED_TEST',
4145 'EXCLUSIVE_LOCKS_REQUIRED', 'SHARED_LOCKS_REQUIRED',
4146 'LOCKS_EXCLUDED', 'INTERFACE_DEF'))
4147 or (func and not Search(r'\boperator\s*\[\s*\]', func.group(1)))
4148 or Search(r'\b(?:struct|union)\s+alignas\s*$', line_prefix)
4149 or Search(r'\b(decltype|requires)$', line_prefix)
4150 or Search(r'(?:\s+=|\breturn)\s*$', line_prefix)
4151 or (Match(r'^\s*$', line_prefix) and Search(
4152 r'(?:\s+=|\breturn)\s*$', clean_lines.elided[linenum - 1]))
4153 or Search(r'\(\*\w+\)$', line_prefix)):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004154 match = None
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004155 if (match and
4156 opening_parenthesis[1] > 1 and
4157 Search(r'\]\s*$', clean_lines.elided[opening_parenthesis[1] - 1])):
4158 # Multi-line lambda-expression
4159 match = None
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004160
4161 else:
4162 # Try matching cases 2-3.
4163 match = Match(r'^(.*(?:else|\)\s*const)\s*)\{', line)
4164 if not match:
4165 # Try matching cases 4-6. These are always matched on separate lines.
4166 #
4167 # Note that we can't simply concatenate the previous line to the
4168 # current line and do a single match, otherwise we may output
4169 # duplicate warnings for the blank line case:
4170 # if (cond) {
4171 # // blank line
4172 # }
4173 prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
4174 if prevline and Search(r'[;{}]\s*$', prevline):
4175 match = Match(r'^(\s*)\{', line)
4176
4177 # Check matching closing brace
4178 if match:
4179 (endline, endlinenum, endpos) = CloseExpression(
4180 clean_lines, linenum, len(match.group(1)))
4181 if endpos > -1 and Match(r'^\s*;', endline[endpos:]):
4182 # Current {} pair is eligible for semicolon check, and we have found
4183 # the redundant semicolon, output warning here.
4184 #
4185 # Note: because we are scanning forward for opening braces, and
4186 # outputting warnings for the matching closing brace, if there are
4187 # nested blocks with trailing semicolons, we will get the error
4188 # messages in reversed order.
4189 error(filename, endlinenum, 'readability/braces', 4,
4190 "You don't need a ; after a }")
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004191
4192
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004193def CheckEmptyBlockBody(filename, clean_lines, linenum, error):
4194 """Look for empty loop/conditional body with only a single semicolon.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004195
4196 Args:
4197 filename: The name of the current file.
4198 clean_lines: A CleansedLines instance containing the file.
4199 linenum: The number of the line to check.
4200 error: The function to call with any errors found.
4201 """
4202
4203 # Search for loop keywords at the beginning of the line. Because only
4204 # whitespaces are allowed before the keywords, this will also ignore most
4205 # do-while-loops, since those lines should start with closing brace.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004206 #
4207 # We also check "if" blocks here, since an empty conditional block
4208 # is likely an error.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004209 line = clean_lines.elided[linenum]
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004210 matched = Match(r'\s*(for|while|if)\s*\(', line)
4211 if matched:
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004212 # Find the end of the conditional expression.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004213 (end_line, end_linenum, end_pos) = CloseExpression(
4214 clean_lines, linenum, line.find('('))
4215
4216 # Output warning if what follows the condition expression is a semicolon.
4217 # No warning for all other cases, including whitespace or newline, since we
4218 # have a separate check for semicolons preceded by whitespace.
4219 if end_pos >= 0 and Match(r';', end_line[end_pos:]):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004220 if matched.group(1) == 'if':
4221 error(filename, end_linenum, 'whitespace/empty_conditional_body', 5,
4222 'Empty conditional bodies should use {}')
4223 else:
4224 error(filename, end_linenum, 'whitespace/empty_loop_body', 5,
4225 'Empty loop bodies should use {} or continue')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004226
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004227 # Check for if statements that have completely empty bodies (no comments)
4228 # and no else clauses.
4229 if end_pos >= 0 and matched.group(1) == 'if':
4230 # Find the position of the opening { for the if statement.
4231 # Return without logging an error if it has no brackets.
4232 opening_linenum = end_linenum
4233 opening_line_fragment = end_line[end_pos:]
4234 # Loop until EOF or find anything that's not whitespace or opening {.
4235 while not Search(r'^\s*\{', opening_line_fragment):
4236 if Search(r'^(?!\s*$)', opening_line_fragment):
4237 # Conditional has no brackets.
4238 return
4239 opening_linenum += 1
4240 if opening_linenum == len(clean_lines.elided):
4241 # Couldn't find conditional's opening { or any code before EOF.
4242 return
4243 opening_line_fragment = clean_lines.elided[opening_linenum]
4244 # Set opening_line (opening_line_fragment may not be entire opening line).
4245 opening_line = clean_lines.elided[opening_linenum]
4246
4247 # Find the position of the closing }.
4248 opening_pos = opening_line_fragment.find('{')
4249 if opening_linenum == end_linenum:
4250 # We need to make opening_pos relative to the start of the entire line.
4251 opening_pos += end_pos
4252 (closing_line, closing_linenum, closing_pos) = CloseExpression(
4253 clean_lines, opening_linenum, opening_pos)
4254 if closing_pos < 0:
4255 return
4256
4257 # Now construct the body of the conditional. This consists of the portion
4258 # of the opening line after the {, all lines until the closing line,
4259 # and the portion of the closing line before the }.
4260 if (clean_lines.raw_lines[opening_linenum] !=
4261 CleanseComments(clean_lines.raw_lines[opening_linenum])):
4262 # Opening line ends with a comment, so conditional isn't empty.
4263 return
4264 if closing_linenum > opening_linenum:
4265 # Opening line after the {. Ignore comments here since we checked above.
4266 body = list(opening_line[opening_pos+1:])
4267 # All lines until closing line, excluding closing line, with comments.
4268 body.extend(clean_lines.raw_lines[opening_linenum+1:closing_linenum])
4269 # Closing line before the }. Won't (and can't) have comments.
4270 body.append(clean_lines.elided[closing_linenum][:closing_pos-1])
4271 body = '\n'.join(body)
4272 else:
4273 # If statement has brackets and fits on a single line.
4274 body = opening_line[opening_pos+1:closing_pos-1]
4275
4276 # Check if the body is empty
4277 if not _EMPTY_CONDITIONAL_BODY_PATTERN.search(body):
4278 return
4279 # The body is empty. Now make sure there's not an else clause.
4280 current_linenum = closing_linenum
4281 current_line_fragment = closing_line[closing_pos:]
4282 # Loop until EOF or find anything that's not whitespace or else clause.
4283 while Search(r'^\s*$|^(?=\s*else)', current_line_fragment):
4284 if Search(r'^(?=\s*else)', current_line_fragment):
4285 # Found an else clause, so don't log an error.
4286 return
4287 current_linenum += 1
4288 if current_linenum == len(clean_lines.elided):
4289 break
4290 current_line_fragment = clean_lines.elided[current_linenum]
4291
4292 # The body is empty and there's no else clause until EOF or other code.
4293 error(filename, end_linenum, 'whitespace/empty_if_body', 4,
4294 ('If statement had no body and no else clause'))
4295
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004296
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004297def FindCheckMacro(line):
4298 """Find a replaceable CHECK-like macro.
4299
4300 Args:
4301 line: line to search on.
4302 Returns:
4303 (macro name, start position), or (None, -1) if no replaceable
4304 macro is found.
4305 """
4306 for macro in _CHECK_MACROS:
4307 i = line.find(macro)
4308 if i >= 0:
4309 # Find opening parenthesis. Do a regular expression match here
4310 # to make sure that we are matching the expected CHECK macro, as
4311 # opposed to some other macro that happens to contain the CHECK
4312 # substring.
4313 matched = Match(r'^(.*\b' + macro + r'\s*)\(', line)
4314 if not matched:
4315 continue
4316 return (macro, len(matched.group(1)))
4317 return (None, -1)
4318
4319
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004320def CheckCheck(filename, clean_lines, linenum, error):
4321 """Checks the use of CHECK and EXPECT macros.
4322
4323 Args:
4324 filename: The name of the current file.
4325 clean_lines: A CleansedLines instance containing the file.
4326 linenum: The number of the line to check.
4327 error: The function to call with any errors found.
4328 """
4329
4330 # Decide the set of replacement macros that should be suggested
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004331 lines = clean_lines.elided
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004332 (check_macro, start_pos) = FindCheckMacro(lines[linenum])
4333 if not check_macro:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004334 return
4335
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004336 # Find end of the boolean expression by matching parentheses
4337 (last_line, end_line, end_pos) = CloseExpression(
4338 clean_lines, linenum, start_pos)
4339 if end_pos < 0:
4340 return
avakulenko@google.com59146752014-08-11 20:20:55 +00004341
4342 # If the check macro is followed by something other than a
4343 # semicolon, assume users will log their own custom error messages
4344 # and don't suggest any replacements.
4345 if not Match(r'\s*;', last_line[end_pos:]):
4346 return
4347
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004348 if linenum == end_line:
4349 expression = lines[linenum][start_pos + 1:end_pos - 1]
4350 else:
4351 expression = lines[linenum][start_pos + 1:]
Edward Lemur6d31ed52019-12-02 23:00:00 +00004352 for i in range(linenum + 1, end_line):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004353 expression += lines[i]
4354 expression += last_line[0:end_pos - 1]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004355
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004356 # Parse expression so that we can take parentheses into account.
4357 # This avoids false positives for inputs like "CHECK((a < 4) == b)",
4358 # which is not replaceable by CHECK_LE.
4359 lhs = ''
4360 rhs = ''
4361 operator = None
4362 while expression:
4363 matched = Match(r'^\s*(<<|<<=|>>|>>=|->\*|->|&&|\|\||'
4364 r'==|!=|>=|>|<=|<|\()(.*)$', expression)
4365 if matched:
4366 token = matched.group(1)
4367 if token == '(':
4368 # Parenthesized operand
4369 expression = matched.group(2)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004370 (end, _) = FindEndOfExpressionInLine(expression, 0, ['('])
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004371 if end < 0:
4372 return # Unmatched parenthesis
4373 lhs += '(' + expression[0:end]
4374 expression = expression[end:]
4375 elif token in ('&&', '||'):
4376 # Logical and/or operators. This means the expression
4377 # contains more than one term, for example:
4378 # CHECK(42 < a && a < b);
4379 #
4380 # These are not replaceable with CHECK_LE, so bail out early.
4381 return
4382 elif token in ('<<', '<<=', '>>', '>>=', '->*', '->'):
4383 # Non-relational operator
4384 lhs += token
4385 expression = matched.group(2)
4386 else:
4387 # Relational operator
4388 operator = token
4389 rhs = matched.group(2)
4390 break
4391 else:
4392 # Unparenthesized operand. Instead of appending to lhs one character
4393 # at a time, we do another regular expression match to consume several
4394 # characters at once if possible. Trivial benchmark shows that this
4395 # is more efficient when the operands are longer than a single
4396 # character, which is generally the case.
4397 matched = Match(r'^([^-=!<>()&|]+)(.*)$', expression)
4398 if not matched:
4399 matched = Match(r'^(\s*\S)(.*)$', expression)
4400 if not matched:
4401 break
4402 lhs += matched.group(1)
4403 expression = matched.group(2)
4404
4405 # Only apply checks if we got all parts of the boolean expression
4406 if not (lhs and operator and rhs):
4407 return
4408
4409 # Check that rhs do not contain logical operators. We already know
4410 # that lhs is fine since the loop above parses out && and ||.
4411 if rhs.find('&&') > -1 or rhs.find('||') > -1:
4412 return
4413
4414 # At least one of the operands must be a constant literal. This is
4415 # to avoid suggesting replacements for unprintable things like
4416 # CHECK(variable != iterator)
4417 #
4418 # The following pattern matches decimal, hex integers, strings, and
4419 # characters (in that order).
4420 lhs = lhs.strip()
4421 rhs = rhs.strip()
4422 match_constant = r'^([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')$'
4423 if Match(match_constant, lhs) or Match(match_constant, rhs):
4424 # Note: since we know both lhs and rhs, we can provide a more
4425 # descriptive error message like:
4426 # Consider using CHECK_EQ(x, 42) instead of CHECK(x == 42)
4427 # Instead of:
4428 # Consider using CHECK_EQ instead of CHECK(a == b)
4429 #
4430 # We are still keeping the less descriptive message because if lhs
4431 # or rhs gets long, the error message might become unreadable.
4432 error(filename, linenum, 'readability/check', 2,
4433 'Consider using %s instead of %s(a %s b)' % (
4434 _CHECK_REPLACEMENT[check_macro][operator],
4435 check_macro, operator))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004436
4437
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004438def CheckAltTokens(filename, clean_lines, linenum, error):
4439 """Check alternative keywords being used in boolean expressions.
4440
4441 Args:
4442 filename: The name of the current file.
4443 clean_lines: A CleansedLines instance containing the file.
4444 linenum: The number of the line to check.
4445 error: The function to call with any errors found.
4446 """
4447 line = clean_lines.elided[linenum]
4448
4449 # Avoid preprocessor lines
4450 if Match(r'^\s*#', line):
4451 return
4452
4453 # Last ditch effort to avoid multi-line comments. This will not help
4454 # if the comment started before the current line or ended after the
4455 # current line, but it catches most of the false positives. At least,
4456 # it provides a way to workaround this warning for people who use
4457 # multi-line comments in preprocessor macros.
4458 #
4459 # TODO(unknown): remove this once cpplint has better support for
4460 # multi-line comments.
4461 if line.find('/*') >= 0 or line.find('*/') >= 0:
4462 return
4463
4464 for match in _ALT_TOKEN_REPLACEMENT_PATTERN.finditer(line):
4465 error(filename, linenum, 'readability/alt_tokens', 2,
4466 'Use operator %s instead of %s' % (
4467 _ALT_TOKEN_REPLACEMENT[match.group(1)], match.group(1)))
4468
4469
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004470def GetLineWidth(line):
4471 """Determines the width of the line in column positions.
4472
4473 Args:
4474 line: A string, which may be a Unicode string.
4475
4476 Returns:
4477 The width of the line in column positions, accounting for Unicode
4478 combining characters and wide characters.
4479 """
Edward Lemur6d31ed52019-12-02 23:00:00 +00004480 if sys.version_info == 2 and isinstance(line, unicode):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004481 width = 0
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004482 for uc in unicodedata.normalize('NFC', line):
4483 if unicodedata.east_asian_width(uc) in ('W', 'F'):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004484 width += 2
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004485 elif not unicodedata.combining(uc):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004486 width += 1
4487 return width
4488 else:
4489 return len(line)
4490
4491
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004492def CheckStyle(filename, clean_lines, linenum, file_extension, nesting_state,
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004493 error):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004494 """Checks rules from the 'C++ style rules' section of cppguide.html.
4495
4496 Most of these rules are hard to test (naming, comment style), but we
4497 do what we can. In particular we check for 2-space indents, line lengths,
4498 tab usage, spaces inside code, etc.
4499
4500 Args:
4501 filename: The name of the current file.
4502 clean_lines: A CleansedLines instance containing the file.
4503 linenum: The number of the line to check.
4504 file_extension: The extension (without the dot) of the filename.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004505 nesting_state: A NestingState instance which maintains information about
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004506 the current stack of nested blocks being parsed.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004507 error: The function to call with any errors found.
4508 """
4509
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004510 # Don't use "elided" lines here, otherwise we can't check commented lines.
4511 # Don't want to use "raw" either, because we don't want to check inside C++11
4512 # raw strings,
4513 raw_lines = clean_lines.lines_without_raw_strings
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004514 line = raw_lines[linenum]
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004515 prev = raw_lines[linenum - 1] if linenum > 0 else ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004516
4517 if line.find('\t') != -1:
4518 error(filename, linenum, 'whitespace/tab', 1,
4519 'Tab found; better to use spaces')
4520
4521 # One or three blank spaces at the beginning of the line is weird; it's
4522 # hard to reconcile that with 2-space indents.
4523 # NOTE: here are the conditions rob pike used for his tests. Mine aren't
4524 # as sophisticated, but it may be worth becoming so: RLENGTH==initial_spaces
4525 # if(RLENGTH > 20) complain = 0;
4526 # if(match($0, " +(error|private|public|protected):")) complain = 0;
4527 # if(match(prev, "&& *$")) complain = 0;
4528 # if(match(prev, "\\|\\| *$")) complain = 0;
4529 # if(match(prev, "[\",=><] *$")) complain = 0;
4530 # if(match($0, " <<")) complain = 0;
4531 # if(match(prev, " +for \\(")) complain = 0;
4532 # if(prevodd && match(prevprev, " +for \\(")) complain = 0;
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004533 scope_or_label_pattern = r'\s*\w+\s*:\s*\\?$'
4534 classinfo = nesting_state.InnermostClass()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004535 initial_spaces = 0
4536 cleansed_line = clean_lines.elided[linenum]
4537 while initial_spaces < len(line) and line[initial_spaces] == ' ':
4538 initial_spaces += 1
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004539 # There are certain situations we allow one space, notably for
4540 # section labels, and also lines containing multi-line raw strings.
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004541 # We also don't check for lines that look like continuation lines
4542 # (of lines ending in double quotes, commas, equals, or angle brackets)
4543 # because the rules for how to indent those are non-trivial.
4544 if (not Search(r'[",=><] *$', prev) and
4545 (initial_spaces == 1 or initial_spaces == 3) and
4546 not Match(scope_or_label_pattern, cleansed_line) and
4547 not (clean_lines.raw_lines[linenum] != line and
4548 Match(r'^\s*""', line))):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004549 error(filename, linenum, 'whitespace/indent', 3,
4550 'Weird number of spaces at line-start. '
4551 'Are you using a 2-space indent?')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004552
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004553 if line and line[-1].isspace():
4554 error(filename, linenum, 'whitespace/end_of_line', 4,
4555 'Line ends in whitespace. Consider deleting these extra spaces.')
4556
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004557 # Check if the line is a header guard.
4558 is_header_guard = False
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00004559 if file_extension == 'h':
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004560 cppvar = GetHeaderGuardCPPVariable(filename)
4561 if (line.startswith('#ifndef %s' % cppvar) or
4562 line.startswith('#define %s' % cppvar) or
4563 line.startswith('#endif // %s' % cppvar)):
4564 is_header_guard = True
4565 # #include lines and header guards can be long, since there's no clean way to
4566 # split them.
erg@google.com6317a9c2009-06-25 00:28:19 +00004567 #
4568 # URLs can be long too. It's possible to split these, but it makes them
4569 # harder to cut&paste.
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004570 #
4571 # The "$Id:...$" comment may also get very long without it being the
4572 # developers fault.
erg@google.com6317a9c2009-06-25 00:28:19 +00004573 if (not line.startswith('#include') and not is_header_guard and
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004574 not Match(r'^\s*//.*http(s?)://\S*$', line) and
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004575 not Match(r'^\s*//\s*[^\s]*$', line) and
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004576 not Match(r'^// \$Id:.*#[0-9]+ \$$', line)):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004577 line_width = GetLineWidth(line)
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004578 if line_width > _line_length:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004579 error(filename, linenum, 'whitespace/line_length', 2,
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004580 'Lines should be <= %i characters long' % _line_length)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004581
4582 if (cleansed_line.count(';') > 1 and
4583 # for loops are allowed two ;'s (and may run over two lines).
4584 cleansed_line.find('for') == -1 and
4585 (GetPreviousNonBlankLine(clean_lines, linenum)[0].find('for') == -1 or
4586 GetPreviousNonBlankLine(clean_lines, linenum)[0].find(';') != -1) and
4587 # It's ok to have many commands in a switch case that fits in 1 line
4588 not ((cleansed_line.find('case ') != -1 or
4589 cleansed_line.find('default:') != -1) and
4590 cleansed_line.find('break;') != -1)):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004591 error(filename, linenum, 'whitespace/newline', 0,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004592 'More than one command on the same line')
4593
4594 # Some more style checks
4595 CheckBraces(filename, clean_lines, linenum, error)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004596 CheckTrailingSemicolon(filename, clean_lines, linenum, error)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004597 CheckEmptyBlockBody(filename, clean_lines, linenum, error)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004598 CheckSpacing(filename, clean_lines, linenum, nesting_state, error)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004599 CheckOperatorSpacing(filename, clean_lines, linenum, error)
4600 CheckParenthesisSpacing(filename, clean_lines, linenum, error)
4601 CheckCommaSpacing(filename, clean_lines, linenum, error)
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004602 CheckBracesSpacing(filename, clean_lines, linenum, nesting_state, error)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004603 CheckSpacingForFunctionCall(filename, clean_lines, linenum, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004604 CheckCheck(filename, clean_lines, linenum, error)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004605 CheckAltTokens(filename, clean_lines, linenum, error)
4606 classinfo = nesting_state.InnermostClass()
4607 if classinfo:
4608 CheckSectionSpacing(filename, clean_lines, classinfo, linenum, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004609
4610
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004611_RE_PATTERN_INCLUDE = re.compile(r'^\s*#\s*include\s*([<"])([^>"]*)[>"].*$')
4612# Matches the first component of a filename delimited by -s and _s. That is:
4613# _RE_FIRST_COMPONENT.match('foo').group(0) == 'foo'
4614# _RE_FIRST_COMPONENT.match('foo.cc').group(0) == 'foo'
4615# _RE_FIRST_COMPONENT.match('foo-bar_baz.cc').group(0) == 'foo'
4616# _RE_FIRST_COMPONENT.match('foo_bar-baz.cc').group(0) == 'foo'
4617_RE_FIRST_COMPONENT = re.compile(r'^[^-_.]+')
4618
4619
4620def _DropCommonSuffixes(filename):
4621 """Drops common suffixes like _test.cc or -inl.h from filename.
4622
4623 For example:
4624 >>> _DropCommonSuffixes('foo/foo-inl.h')
4625 'foo/foo'
4626 >>> _DropCommonSuffixes('foo/bar/foo.cc')
4627 'foo/bar/foo'
4628 >>> _DropCommonSuffixes('foo/foo_internal.h')
4629 'foo/foo'
4630 >>> _DropCommonSuffixes('foo/foo_unusualinternal.h')
4631 'foo/foo_unusualinternal'
4632
4633 Args:
4634 filename: The input filename.
4635
4636 Returns:
4637 The filename with the common suffix removed.
4638 """
4639 for suffix in ('test.cc', 'regtest.cc', 'unittest.cc',
4640 'inl.h', 'impl.h', 'internal.h'):
4641 if (filename.endswith(suffix) and len(filename) > len(suffix) and
4642 filename[-len(suffix) - 1] in ('-', '_')):
4643 return filename[:-len(suffix) - 1]
4644 return os.path.splitext(filename)[0]
4645
4646
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004647def _ClassifyInclude(fileinfo, include, is_system):
4648 """Figures out what kind of header 'include' is.
4649
4650 Args:
4651 fileinfo: The current file cpplint is running over. A FileInfo instance.
4652 include: The path to a #included file.
4653 is_system: True if the #include used <> rather than "".
4654
4655 Returns:
4656 One of the _XXX_HEADER constants.
4657
4658 For example:
4659 >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'stdio.h', True)
4660 _C_SYS_HEADER
4661 >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'string', True)
4662 _CPP_SYS_HEADER
4663 >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', False)
4664 _LIKELY_MY_HEADER
4665 >>> _ClassifyInclude(FileInfo('foo/foo_unknown_extension.cc'),
4666 ... 'bar/foo_other_ext.h', False)
4667 _POSSIBLE_MY_HEADER
4668 >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/bar.h', False)
4669 _OTHER_HEADER
4670 """
4671 # This is a list of all standard c++ header files, except
4672 # those already checked for above.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004673 is_cpp_h = include in _CPP_HEADERS
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004674
4675 if is_system:
4676 if is_cpp_h:
4677 return _CPP_SYS_HEADER
4678 else:
4679 return _C_SYS_HEADER
4680
4681 # If the target file and the include we're checking share a
4682 # basename when we drop common extensions, and the include
4683 # lives in . , then it's likely to be owned by the target file.
4684 target_dir, target_base = (
4685 os.path.split(_DropCommonSuffixes(fileinfo.RepositoryName())))
4686 include_dir, include_base = os.path.split(_DropCommonSuffixes(include))
4687 if target_base == include_base and (
4688 include_dir == target_dir or
4689 include_dir == os.path.normpath(target_dir + '/../public')):
4690 return _LIKELY_MY_HEADER
4691
4692 # If the target and include share some initial basename
4693 # component, it's possible the target is implementing the
4694 # include, so it's allowed to be first, but we'll never
4695 # complain if it's not there.
4696 target_first_component = _RE_FIRST_COMPONENT.match(target_base)
4697 include_first_component = _RE_FIRST_COMPONENT.match(include_base)
4698 if (target_first_component and include_first_component and
4699 target_first_component.group(0) ==
4700 include_first_component.group(0)):
4701 return _POSSIBLE_MY_HEADER
4702
4703 return _OTHER_HEADER
4704
4705
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004706
erg@google.com6317a9c2009-06-25 00:28:19 +00004707def CheckIncludeLine(filename, clean_lines, linenum, include_state, error):
4708 """Check rules that are applicable to #include lines.
4709
4710 Strings on #include lines are NOT removed from elided line, to make
4711 certain tasks easier. However, to prevent false positives, checks
4712 applicable to #include lines in CheckLanguage must be put here.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004713
4714 Args:
4715 filename: The name of the current file.
4716 clean_lines: A CleansedLines instance containing the file.
4717 linenum: The number of the line to check.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004718 include_state: An _IncludeState instance in which the headers are inserted.
4719 error: The function to call with any errors found.
4720 """
4721 fileinfo = FileInfo(filename)
erg@google.com6317a9c2009-06-25 00:28:19 +00004722 line = clean_lines.lines[linenum]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004723
4724 # "include" should use the new style "foo/bar.h" instead of just "bar.h"
avakulenko@google.com59146752014-08-11 20:20:55 +00004725 # Only do this check if the included header follows google naming
4726 # conventions. If not, assume that it's a 3rd party API that
4727 # requires special include conventions.
4728 #
4729 # We also make an exception for Lua headers, which follow google
4730 # naming convention but not the include convention.
4731 match = Match(r'#include\s*"([^/]+\.h)"', line)
4732 if match and not _THIRD_PARTY_HEADERS_PATTERN.match(match.group(1)):
Fletcher Woodruff11b34152020-04-23 21:21:40 +00004733 error(filename, linenum, 'build/include_directory', 4,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004734 'Include the directory when naming .h files')
4735
4736 # we shouldn't include a file more than once. actually, there are a
4737 # handful of instances where doing so is okay, but in general it's
4738 # not.
erg@google.com6317a9c2009-06-25 00:28:19 +00004739 match = _RE_PATTERN_INCLUDE.search(line)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004740 if match:
4741 include = match.group(2)
4742 is_system = (match.group(1) == '<')
avakulenko@google.com59146752014-08-11 20:20:55 +00004743 duplicate_line = include_state.FindHeader(include)
4744 if duplicate_line >= 0:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004745 error(filename, linenum, 'build/include', 4,
4746 '"%s" already included at %s:%s' %
avakulenko@google.com59146752014-08-11 20:20:55 +00004747 (include, filename, duplicate_line))
avakulenko@google.com255f2be2014-12-05 22:19:55 +00004748 elif (include.endswith('.cc') and
4749 os.path.dirname(fileinfo.RepositoryName()) != os.path.dirname(include)):
4750 error(filename, linenum, 'build/include', 4,
4751 'Do not include .cc files from other packages')
avakulenko@google.com59146752014-08-11 20:20:55 +00004752 elif not _THIRD_PARTY_HEADERS_PATTERN.match(include):
4753 include_state.include_list[-1].append((include, linenum))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004754
4755 # We want to ensure that headers appear in the right order:
4756 # 1) for foo.cc, foo.h (preferred location)
4757 # 2) c system files
4758 # 3) cpp system files
4759 # 4) for foo.cc, foo.h (deprecated location)
4760 # 5) other google headers
4761 #
4762 # We classify each include statement as one of those 5 types
4763 # using a number of techniques. The include_state object keeps
4764 # track of the highest type seen, and complains if we see a
4765 # lower type after that.
4766 error_message = include_state.CheckNextIncludeOrder(
4767 _ClassifyInclude(fileinfo, include, is_system))
4768 if error_message:
4769 error(filename, linenum, 'build/include_order', 4,
4770 '%s. Should be: %s.h, c system, c++ system, other.' %
4771 (error_message, fileinfo.BaseName()))
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004772 canonical_include = include_state.CanonicalizeAlphabeticalOrder(include)
4773 if not include_state.IsInAlphabeticalOrder(
4774 clean_lines, linenum, canonical_include):
erg@google.com26970fa2009-11-17 18:07:32 +00004775 error(filename, linenum, 'build/include_alpha', 4,
4776 'Include "%s" not in alphabetical order' % include)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004777 include_state.SetLastHeader(canonical_include)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004778
erg@google.com6317a9c2009-06-25 00:28:19 +00004779
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004780
4781def _GetTextInside(text, start_pattern):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004782 r"""Retrieves all the text between matching open and close parentheses.
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004783
4784 Given a string of lines and a regular expression string, retrieve all the text
4785 following the expression and between opening punctuation symbols like
4786 (, [, or {, and the matching close-punctuation symbol. This properly nested
4787 occurrences of the punctuations, so for the text like
4788 printf(a(), b(c()));
4789 a call to _GetTextInside(text, r'printf\(') will return 'a(), b(c())'.
4790 start_pattern must match string having an open punctuation symbol at the end.
4791
4792 Args:
4793 text: The lines to extract text. Its comments and strings must be elided.
4794 It can be single line and can span multiple lines.
4795 start_pattern: The regexp string indicating where to start extracting
4796 the text.
4797 Returns:
4798 The extracted text.
4799 None if either the opening string or ending punctuation could not be found.
4800 """
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004801 # TODO(unknown): Audit cpplint.py to see what places could be profitably
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004802 # rewritten to use _GetTextInside (and use inferior regexp matching today).
4803
4804 # Give opening punctuations to get the matching close-punctuations.
4805 matching_punctuation = {'(': ')', '{': '}', '[': ']'}
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +00004806 closing_punctuation = set(matching_punctuation.values())
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004807
4808 # Find the position to start extracting text.
4809 match = re.search(start_pattern, text, re.M)
4810 if not match: # start_pattern not found in text.
4811 return None
4812 start_position = match.end(0)
4813
4814 assert start_position > 0, (
4815 'start_pattern must ends with an opening punctuation.')
4816 assert text[start_position - 1] in matching_punctuation, (
4817 'start_pattern must ends with an opening punctuation.')
4818 # Stack of closing punctuations we expect to have in text after position.
4819 punctuation_stack = [matching_punctuation[text[start_position - 1]]]
4820 position = start_position
4821 while punctuation_stack and position < len(text):
4822 if text[position] == punctuation_stack[-1]:
4823 punctuation_stack.pop()
4824 elif text[position] in closing_punctuation:
4825 # A closing punctuation without matching opening punctuations.
4826 return None
4827 elif text[position] in matching_punctuation:
4828 punctuation_stack.append(matching_punctuation[text[position]])
4829 position += 1
4830 if punctuation_stack:
4831 # Opening punctuations left without matching close-punctuations.
4832 return None
4833 # punctuations match.
4834 return text[start_position:position - 1]
4835
4836
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004837# Patterns for matching call-by-reference parameters.
4838#
4839# Supports nested templates up to 2 levels deep using this messy pattern:
4840# < (?: < (?: < [^<>]*
4841# >
4842# | [^<>] )*
4843# >
4844# | [^<>] )*
4845# >
4846_RE_PATTERN_IDENT = r'[_a-zA-Z]\w*' # =~ [[:alpha:]][[:alnum:]]*
4847_RE_PATTERN_TYPE = (
4848 r'(?:const\s+)?(?:typename\s+|class\s+|struct\s+|union\s+|enum\s+)?'
4849 r'(?:\w|'
4850 r'\s*<(?:<(?:<[^<>]*>|[^<>])*>|[^<>])*>|'
4851 r'::)+')
4852# A call-by-reference parameter ends with '& identifier'.
4853_RE_PATTERN_REF_PARAM = re.compile(
4854 r'(' + _RE_PATTERN_TYPE + r'(?:\s*(?:\bconst\b|[*]))*\s*'
4855 r'&\s*' + _RE_PATTERN_IDENT + r')\s*(?:=[^,()]+)?[,)]')
4856# A call-by-const-reference parameter either ends with 'const& identifier'
4857# or looks like 'const type& identifier' when 'type' is atomic.
4858_RE_PATTERN_CONST_REF_PARAM = (
4859 r'(?:.*\s*\bconst\s*&\s*' + _RE_PATTERN_IDENT +
4860 r'|const\s+' + _RE_PATTERN_TYPE + r'\s*&\s*' + _RE_PATTERN_IDENT + r')')
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004861# Stream types.
4862_RE_PATTERN_REF_STREAM_PARAM = (
4863 r'(?:.*stream\s*&\s*' + _RE_PATTERN_IDENT + r')')
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004864
4865
4866def CheckLanguage(filename, clean_lines, linenum, file_extension,
4867 include_state, nesting_state, error):
erg@google.com6317a9c2009-06-25 00:28:19 +00004868 """Checks rules from the 'C++ language rules' section of cppguide.html.
4869
4870 Some of these rules are hard to test (function overloading, using
4871 uint32 inappropriately), but we do the best we can.
4872
4873 Args:
4874 filename: The name of the current file.
4875 clean_lines: A CleansedLines instance containing the file.
4876 linenum: The number of the line to check.
4877 file_extension: The extension (without the dot) of the filename.
4878 include_state: An _IncludeState instance in which the headers are inserted.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004879 nesting_state: A NestingState instance which maintains information about
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004880 the current stack of nested blocks being parsed.
erg@google.com6317a9c2009-06-25 00:28:19 +00004881 error: The function to call with any errors found.
4882 """
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004883 # If the line is empty or consists of entirely a comment, no need to
4884 # check it.
4885 line = clean_lines.elided[linenum]
4886 if not line:
4887 return
4888
erg@google.com6317a9c2009-06-25 00:28:19 +00004889 match = _RE_PATTERN_INCLUDE.search(line)
4890 if match:
4891 CheckIncludeLine(filename, clean_lines, linenum, include_state, error)
4892 return
4893
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004894 # Reset include state across preprocessor directives. This is meant
4895 # to silence warnings for conditional includes.
avakulenko@google.com59146752014-08-11 20:20:55 +00004896 match = Match(r'^\s*#\s*(if|ifdef|ifndef|elif|else|endif)\b', line)
4897 if match:
4898 include_state.ResetSection(match.group(1))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004899
4900 # Make Windows paths like Unix.
4901 fullname = os.path.abspath(filename).replace('\\', '/')
skym@chromium.org3990c412016-02-05 20:55:12 +00004902
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004903 # Perform other checks now that we are sure that this is not an include line
4904 CheckCasts(filename, clean_lines, linenum, error)
4905 CheckGlobalStatic(filename, clean_lines, linenum, error)
4906 CheckPrintf(filename, clean_lines, linenum, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004907
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00004908 if file_extension == 'h':
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004909 # TODO(unknown): check that 1-arg constructors are explicit.
4910 # How to tell it's a constructor?
4911 # (handled in CheckForNonStandardConstructs for now)
avakulenko@google.com59146752014-08-11 20:20:55 +00004912 # TODO(unknown): check that classes declare or disable copy/assign
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004913 # (level 1 error)
4914 pass
4915
4916 # Check if people are using the verboten C basic types. The only exception
4917 # we regularly allow is "unsigned short port" for port.
4918 if Search(r'\bshort port\b', line):
4919 if not Search(r'\bunsigned short port\b', line):
4920 error(filename, linenum, 'runtime/int', 4,
4921 'Use "unsigned short" for ports, not "short"')
4922 else:
4923 match = Search(r'\b(short|long(?! +double)|long long)\b', line)
4924 if match:
4925 error(filename, linenum, 'runtime/int', 4,
4926 'Use int16/int64/etc, rather than the C type %s' % match.group(1))
4927
erg@google.com26970fa2009-11-17 18:07:32 +00004928 # Check if some verboten operator overloading is going on
4929 # TODO(unknown): catch out-of-line unary operator&:
4930 # class X {};
4931 # int operator&(const X& x) { return 42; } // unary operator&
4932 # The trick is it's hard to tell apart from binary operator&:
4933 # class Y { int operator&(const Y& x) { return 23; } }; // binary operator&
4934 if Search(r'\boperator\s*&\s*\(\s*\)', line):
4935 error(filename, linenum, 'runtime/operator', 4,
4936 'Unary operator& is dangerous. Do not use it.')
4937
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004938 # Check for suspicious usage of "if" like
4939 # } if (a == b) {
Darius Maa7d7e42022-05-13 14:54:21 +00004940 if Search(r'\}\s*if\s*(?:constexpr\s*)?\(', line):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004941 error(filename, linenum, 'readability/braces', 4,
4942 'Did you mean "else if"? If not, start a new line for "if".')
4943
4944 # Check for potential format string bugs like printf(foo).
4945 # We constrain the pattern not to pick things like DocidForPrintf(foo).
4946 # Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str())
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004947 # TODO(unknown): Catch the following case. Need to change the calling
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004948 # convention of the whole function to process multiple line to handle it.
4949 # printf(
4950 # boy_this_is_a_really_long_variable_that_cannot_fit_on_the_prev_line);
4951 printf_args = _GetTextInside(line, r'(?i)\b(string)?printf\s*\(')
4952 if printf_args:
4953 match = Match(r'([\w.\->()]+)$', printf_args)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004954 if match and match.group(1) != '__VA_ARGS__':
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004955 function_name = re.search(r'\b((?:string)?printf)\s*\(',
4956 line, re.I).group(1)
4957 error(filename, linenum, 'runtime/printf', 4,
4958 'Potential format string bug. Do %s("%%s", %s) instead.'
4959 % (function_name, match.group(1)))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004960
4961 # Check for potential memset bugs like memset(buf, sizeof(buf), 0).
4962 match = Search(r'memset\s*\(([^,]*),\s*([^,]*),\s*0\s*\)', line)
4963 if match and not Match(r"^''|-?[0-9]+|0x[0-9A-Fa-f]$", match.group(2)):
4964 error(filename, linenum, 'runtime/memset', 4,
4965 'Did you mean "memset(%s, 0, %s)"?'
4966 % (match.group(1), match.group(2)))
4967
4968 if Search(r'\busing namespace\b', line):
4969 error(filename, linenum, 'build/namespaces', 5,
4970 'Do not use namespace using-directives. '
4971 'Use using-declarations instead.')
4972
4973 # Detect variable-length arrays.
4974 match = Match(r'\s*(.+::)?(\w+) [a-z]\w*\[(.+)];', line)
4975 if (match and match.group(2) != 'return' and match.group(2) != 'delete' and
4976 match.group(3).find(']') == -1):
4977 # Split the size using space and arithmetic operators as delimiters.
4978 # If any of the resulting tokens are not compile time constants then
4979 # report the error.
4980 tokens = re.split(r'\s|\+|\-|\*|\/|<<|>>]', match.group(3))
4981 is_const = True
4982 skip_next = False
4983 for tok in tokens:
4984 if skip_next:
4985 skip_next = False
4986 continue
4987
4988 if Search(r'sizeof\(.+\)', tok): continue
4989 if Search(r'arraysize\(\w+\)', tok): continue
Avi Drissman4157ba12019-01-09 14:18:07 +00004990 if Search(r'base::size\(.+\)', tok): continue
4991 if Search(r'std::size\(.+\)', tok): continue
4992 if Search(r'std::extent<.+>', tok): continue
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004993
4994 tok = tok.lstrip('(')
4995 tok = tok.rstrip(')')
4996 if not tok: continue
4997 if Match(r'\d+', tok): continue
4998 if Match(r'0[xX][0-9a-fA-F]+', tok): continue
4999 if Match(r'k[A-Z0-9]\w*', tok): continue
5000 if Match(r'(.+::)?k[A-Z0-9]\w*', tok): continue
5001 if Match(r'(.+::)?[A-Z][A-Z0-9_]*', tok): continue
5002 # A catch all for tricky sizeof cases, including 'sizeof expression',
5003 # 'sizeof(*type)', 'sizeof(const type)', 'sizeof(struct StructName)'
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005004 # requires skipping the next token because we split on ' ' and '*'.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005005 if tok.startswith('sizeof'):
5006 skip_next = True
5007 continue
5008 is_const = False
5009 break
5010 if not is_const:
5011 error(filename, linenum, 'runtime/arrays', 1,
5012 'Do not use variable-length arrays. Use an appropriately named '
5013 "('k' followed by CamelCase) compile-time constant for the size.")
5014
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005015 # Check for use of unnamed namespaces in header files. Registration
5016 # macros are typically OK, so we allow use of "namespace {" on lines
5017 # that end with backslashes.
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00005018 if (file_extension == 'h'
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005019 and Search(r'\bnamespace\s*{', line)
5020 and line[-1] != '\\'):
5021 error(filename, linenum, 'build/namespaces', 4,
5022 'Do not use unnamed namespaces in header files. See '
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00005023 'https://google.github.io/styleguide/cppguide.html#Namespaces'
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005024 ' for more information.')
5025
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005026
5027def CheckGlobalStatic(filename, clean_lines, linenum, error):
5028 """Check for unsafe global or static objects.
5029
5030 Args:
5031 filename: The name of the current file.
5032 clean_lines: A CleansedLines instance containing the file.
5033 linenum: The number of the line to check.
5034 error: The function to call with any errors found.
5035 """
5036 line = clean_lines.elided[linenum]
5037
avakulenko@google.com59146752014-08-11 20:20:55 +00005038 # Match two lines at a time to support multiline declarations
5039 if linenum + 1 < clean_lines.NumLines() and not Search(r'[;({]', line):
5040 line += clean_lines.elided[linenum + 1].strip()
5041
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005042 # Check for people declaring static/global STL strings at the top level.
5043 # This is dangerous because the C++ language does not guarantee that
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005044 # globals with constructors are initialized before the first access, and
5045 # also because globals can be destroyed when some threads are still running.
5046 # TODO(unknown): Generalize this to also find static unique_ptr instances.
5047 # TODO(unknown): File bugs for clang-tidy to find these.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005048 match = Match(
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005049 r'((?:|static +)(?:|const +))(?::*std::)?string( +const)? +'
5050 r'([a-zA-Z0-9_:]+)\b(.*)',
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005051 line)
avakulenko@google.com59146752014-08-11 20:20:55 +00005052
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005053 # Remove false positives:
5054 # - String pointers (as opposed to values).
5055 # string *pointer
5056 # const string *pointer
5057 # string const *pointer
5058 # string *const pointer
5059 #
5060 # - Functions and template specializations.
5061 # string Function<Type>(...
5062 # string Class<Type>::Method(...
5063 #
5064 # - Operators. These are matched separately because operator names
5065 # cross non-word boundaries, and trying to match both operators
5066 # and functions at the same time would decrease accuracy of
5067 # matching identifiers.
5068 # string Class::operator*()
5069 if (match and
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005070 not Search(r'\bstring\b(\s+const)?\s*[\*\&]\s*(const\s+)?\w', line) and
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005071 not Search(r'\boperator\W', line) and
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005072 not Match(r'\s*(<.*>)?(::[a-zA-Z0-9_]+)*\s*\(([^"]|$)', match.group(4))):
5073 if Search(r'\bconst\b', line):
5074 error(filename, linenum, 'runtime/string', 4,
5075 'For a static/global string constant, use a C style string '
5076 'instead: "%schar%s %s[]".' %
5077 (match.group(1), match.group(2) or '', match.group(3)))
5078 else:
5079 error(filename, linenum, 'runtime/string', 4,
5080 'Static/global string variables are not permitted.')
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005081
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005082 if (Search(r'\b([A-Za-z0-9_]*_)\(\1\)', line) or
5083 Search(r'\b([A-Za-z0-9_]*_)\(CHECK_NOTNULL\(\1\)\)', line)):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005084 error(filename, linenum, 'runtime/init', 4,
5085 'You seem to be initializing a member variable with itself.')
5086
5087
5088def CheckPrintf(filename, clean_lines, linenum, error):
5089 """Check for printf related issues.
5090
5091 Args:
5092 filename: The name of the current file.
5093 clean_lines: A CleansedLines instance containing the file.
5094 linenum: The number of the line to check.
5095 error: The function to call with any errors found.
5096 """
5097 line = clean_lines.elided[linenum]
5098
5099 # When snprintf is used, the second argument shouldn't be a literal.
5100 match = Search(r'snprintf\s*\(([^,]*),\s*([0-9]*)\s*,', line)
5101 if match and match.group(2) != '0':
5102 # If 2nd arg is zero, snprintf is used to calculate size.
5103 error(filename, linenum, 'runtime/printf', 3,
5104 'If you can, use sizeof(%s) instead of %s as the 2nd arg '
5105 'to snprintf.' % (match.group(1), match.group(2)))
5106
5107 # Check if some verboten C functions are being used.
avakulenko@google.com59146752014-08-11 20:20:55 +00005108 if Search(r'\bsprintf\s*\(', line):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005109 error(filename, linenum, 'runtime/printf', 5,
5110 'Never use sprintf. Use snprintf instead.')
avakulenko@google.com59146752014-08-11 20:20:55 +00005111 match = Search(r'\b(strcpy|strcat)\s*\(', line)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005112 if match:
5113 error(filename, linenum, 'runtime/printf', 4,
5114 'Almost always, snprintf is better than %s' % match.group(1))
5115
5116
5117def IsDerivedFunction(clean_lines, linenum):
5118 """Check if current line contains an inherited function.
5119
5120 Args:
5121 clean_lines: A CleansedLines instance containing the file.
5122 linenum: The number of the line to check.
5123 Returns:
5124 True if current line contains a function with "override"
5125 virt-specifier.
5126 """
avakulenko@google.com59146752014-08-11 20:20:55 +00005127 # Scan back a few lines for start of current function
Edward Lemur6d31ed52019-12-02 23:00:00 +00005128 for i in range(linenum, max(-1, linenum - 10), -1):
avakulenko@google.com59146752014-08-11 20:20:55 +00005129 match = Match(r'^([^()]*\w+)\(', clean_lines.elided[i])
5130 if match:
5131 # Look for "override" after the matching closing parenthesis
5132 line, _, closing_paren = CloseExpression(
5133 clean_lines, i, len(match.group(1)))
5134 return (closing_paren >= 0 and
5135 Search(r'\boverride\b', line[closing_paren:]))
5136 return False
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005137
5138
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005139def IsOutOfLineMethodDefinition(clean_lines, linenum):
5140 """Check if current line contains an out-of-line method definition.
5141
5142 Args:
5143 clean_lines: A CleansedLines instance containing the file.
5144 linenum: The number of the line to check.
5145 Returns:
5146 True if current line contains an out-of-line method definition.
5147 """
5148 # Scan back a few lines for start of current function
Edward Lemur6d31ed52019-12-02 23:00:00 +00005149 for i in range(linenum, max(-1, linenum - 10), -1):
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005150 if Match(r'^([^()]*\w+)\(', clean_lines.elided[i]):
5151 return Match(r'^[^()]*\w+::\w+\(', clean_lines.elided[i]) is not None
5152 return False
5153
5154
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005155def IsInitializerList(clean_lines, linenum):
5156 """Check if current line is inside constructor initializer list.
5157
5158 Args:
5159 clean_lines: A CleansedLines instance containing the file.
5160 linenum: The number of the line to check.
5161 Returns:
5162 True if current line appears to be inside constructor initializer
5163 list, False otherwise.
5164 """
Edward Lemur6d31ed52019-12-02 23:00:00 +00005165 for i in range(linenum, 1, -1):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005166 line = clean_lines.elided[i]
5167 if i == linenum:
5168 remove_function_body = Match(r'^(.*)\{\s*$', line)
5169 if remove_function_body:
5170 line = remove_function_body.group(1)
5171
5172 if Search(r'\s:\s*\w+[({]', line):
5173 # A lone colon tend to indicate the start of a constructor
5174 # initializer list. It could also be a ternary operator, which
5175 # also tend to appear in constructor initializer lists as
5176 # opposed to parameter lists.
5177 return True
5178 if Search(r'\}\s*,\s*$', line):
5179 # A closing brace followed by a comma is probably the end of a
5180 # brace-initialized member in constructor initializer list.
5181 return True
5182 if Search(r'[{};]\s*$', line):
5183 # Found one of the following:
5184 # - A closing brace or semicolon, probably the end of the previous
5185 # function.
5186 # - An opening brace, probably the start of current class or namespace.
5187 #
5188 # Current line is probably not inside an initializer list since
5189 # we saw one of those things without seeing the starting colon.
5190 return False
5191
5192 # Got to the beginning of the file without seeing the start of
5193 # constructor initializer list.
5194 return False
5195
5196
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005197def CheckForNonConstReference(filename, clean_lines, linenum,
5198 nesting_state, error):
5199 """Check for non-const references.
5200
5201 Separate from CheckLanguage since it scans backwards from current
5202 line, instead of scanning forward.
5203
5204 Args:
5205 filename: The name of the current file.
5206 clean_lines: A CleansedLines instance containing the file.
5207 linenum: The number of the line to check.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005208 nesting_state: A NestingState instance which maintains information about
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005209 the current stack of nested blocks being parsed.
5210 error: The function to call with any errors found.
5211 """
5212 # Do nothing if there is no '&' on current line.
5213 line = clean_lines.elided[linenum]
5214 if '&' not in line:
5215 return
5216
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005217 # If a function is inherited, current function doesn't have much of
5218 # a choice, so any non-const references should not be blamed on
5219 # derived function.
5220 if IsDerivedFunction(clean_lines, linenum):
5221 return
5222
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005223 # Don't warn on out-of-line method definitions, as we would warn on the
5224 # in-line declaration, if it isn't marked with 'override'.
5225 if IsOutOfLineMethodDefinition(clean_lines, linenum):
5226 return
5227
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005228 # Long type names may be broken across multiple lines, usually in one
5229 # of these forms:
5230 # LongType
5231 # ::LongTypeContinued &identifier
5232 # LongType::
5233 # LongTypeContinued &identifier
5234 # LongType<
5235 # ...>::LongTypeContinued &identifier
5236 #
5237 # If we detected a type split across two lines, join the previous
5238 # line to current line so that we can match const references
5239 # accordingly.
5240 #
5241 # Note that this only scans back one line, since scanning back
5242 # arbitrary number of lines would be expensive. If you have a type
5243 # that spans more than 2 lines, please use a typedef.
5244 if linenum > 1:
5245 previous = None
5246 if Match(r'\s*::(?:[\w<>]|::)+\s*&\s*\S', line):
5247 # previous_line\n + ::current_line
5248 previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+[\w<>])\s*$',
5249 clean_lines.elided[linenum - 1])
5250 elif Match(r'\s*[a-zA-Z_]([\w<>]|::)+\s*&\s*\S', line):
5251 # previous_line::\n + current_line
5252 previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+::)\s*$',
5253 clean_lines.elided[linenum - 1])
5254 if previous:
5255 line = previous.group(1) + line.lstrip()
5256 else:
5257 # Check for templated parameter that is split across multiple lines
5258 endpos = line.rfind('>')
5259 if endpos > -1:
5260 (_, startline, startpos) = ReverseCloseExpression(
5261 clean_lines, linenum, endpos)
5262 if startpos > -1 and startline < linenum:
5263 # Found the matching < on an earlier line, collect all
5264 # pieces up to current line.
5265 line = ''
Edward Lemur6d31ed52019-12-02 23:00:00 +00005266 for i in range(startline, linenum + 1):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005267 line += clean_lines.elided[i].strip()
5268
5269 # Check for non-const references in function parameters. A single '&' may
5270 # found in the following places:
5271 # inside expression: binary & for bitwise AND
5272 # inside expression: unary & for taking the address of something
5273 # inside declarators: reference parameter
5274 # We will exclude the first two cases by checking that we are not inside a
5275 # function body, including one that was just introduced by a trailing '{'.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005276 # TODO(unknown): Doesn't account for 'catch(Exception& e)' [rare].
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005277 if (nesting_state.previous_stack_top and
5278 not (isinstance(nesting_state.previous_stack_top, _ClassInfo) or
5279 isinstance(nesting_state.previous_stack_top, _NamespaceInfo))):
5280 # Not at toplevel, not within a class, and not within a namespace
5281 return
5282
avakulenko@google.com59146752014-08-11 20:20:55 +00005283 # Avoid initializer lists. We only need to scan back from the
5284 # current line for something that starts with ':'.
5285 #
5286 # We don't need to check the current line, since the '&' would
5287 # appear inside the second set of parentheses on the current line as
5288 # opposed to the first set.
5289 if linenum > 0:
Edward Lemur6d31ed52019-12-02 23:00:00 +00005290 for i in range(linenum - 1, max(0, linenum - 10), -1):
avakulenko@google.com59146752014-08-11 20:20:55 +00005291 previous_line = clean_lines.elided[i]
5292 if not Search(r'[),]\s*$', previous_line):
5293 break
5294 if Match(r'^\s*:\s+\S', previous_line):
5295 return
5296
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005297 # Avoid preprocessors
5298 if Search(r'\\\s*$', line):
5299 return
5300
5301 # Avoid constructor initializer lists
5302 if IsInitializerList(clean_lines, linenum):
5303 return
5304
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005305 # We allow non-const references in a few standard places, like functions
5306 # called "swap()" or iostream operators like "<<" or ">>". Do not check
5307 # those function parameters.
5308 #
5309 # We also accept & in static_assert, which looks like a function but
5310 # it's actually a declaration expression.
Ayu Ishii09858612020-06-26 18:00:52 +00005311 allowlisted_functions = (r'(?:[sS]wap(?:<\w:+>)?|'
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005312 r'operator\s*[<>][<>]|'
5313 r'static_assert|COMPILE_ASSERT'
5314 r')\s*\(')
Ayu Ishii09858612020-06-26 18:00:52 +00005315 if Search(allowlisted_functions, line):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005316 return
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005317 elif not Search(r'\S+\([^)]*$', line):
Ayu Ishii09858612020-06-26 18:00:52 +00005318 # Don't see an allowlisted function on this line. Actually we
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005319 # didn't see any function name on this line, so this is likely a
5320 # multi-line parameter list. Try a bit harder to catch this case.
Edward Lemur6d31ed52019-12-02 23:00:00 +00005321 for i in range(2):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005322 if (linenum > i and
Ayu Ishii09858612020-06-26 18:00:52 +00005323 Search(allowlisted_functions, clean_lines.elided[linenum - i - 1])):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005324 return
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005325
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005326 decls = ReplaceAll(r'{[^}]*}', ' ', line) # exclude function body
5327 for parameter in re.findall(_RE_PATTERN_REF_PARAM, decls):
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005328 if (not Match(_RE_PATTERN_CONST_REF_PARAM, parameter) and
5329 not Match(_RE_PATTERN_REF_STREAM_PARAM, parameter)):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005330 error(filename, linenum, 'runtime/references', 2,
5331 'Is this a non-const reference? '
5332 'If so, make const or use a pointer: ' +
5333 ReplaceAll(' *<', '<', parameter))
5334
5335
5336def CheckCasts(filename, clean_lines, linenum, error):
5337 """Various cast related checks.
5338
5339 Args:
5340 filename: The name of the current file.
5341 clean_lines: A CleansedLines instance containing the file.
5342 linenum: The number of the line to check.
5343 error: The function to call with any errors found.
5344 """
5345 line = clean_lines.elided[linenum]
5346
5347 # Check to see if they're using an conversion function cast.
5348 # I just try to capture the most common basic types, though there are more.
5349 # Parameterless conversion functions, such as bool(), are allowed as they are
5350 # probably a member operator declaration or default constructor.
5351 match = Search(
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005352 r'(\bnew\s+(?:const\s+)?|\S<\s*(?:const\s+)?)?\b'
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005353 r'(int|float|double|bool|char|int32|uint32|int64|uint64)'
5354 r'(\([^)].*)', line)
5355 expecting_function = ExpectingFunctionArgs(clean_lines, linenum)
5356 if match and not expecting_function:
5357 matched_type = match.group(2)
5358
5359 # matched_new_or_template is used to silence two false positives:
5360 # - New operators
5361 # - Template arguments with function types
5362 #
5363 # For template arguments, we match on types immediately following
5364 # an opening bracket without any spaces. This is a fast way to
5365 # silence the common case where the function type is the first
5366 # template argument. False negative with less-than comparison is
5367 # avoided because those operators are usually followed by a space.
5368 #
5369 # function<double(double)> // bracket + no space = false positive
5370 # value < double(42) // bracket + space = true positive
5371 matched_new_or_template = match.group(1)
5372
avakulenko@google.com59146752014-08-11 20:20:55 +00005373 # Avoid arrays by looking for brackets that come after the closing
5374 # parenthesis.
5375 if Match(r'\([^()]+\)\s*\[', match.group(3)):
5376 return
5377
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005378 # Other things to ignore:
5379 # - Function pointers
5380 # - Casts to pointer types
5381 # - Placement new
5382 # - Alias declarations
5383 matched_funcptr = match.group(3)
5384 if (matched_new_or_template is None and
5385 not (matched_funcptr and
5386 (Match(r'\((?:[^() ]+::\s*\*\s*)?[^() ]+\)\s*\(',
5387 matched_funcptr) or
5388 matched_funcptr.startswith('(*)'))) and
5389 not Match(r'\s*using\s+\S+\s*=\s*' + matched_type, line) and
5390 not Search(r'new\(\S+\)\s*' + matched_type, line)):
5391 error(filename, linenum, 'readability/casting', 4,
5392 'Using deprecated casting style. '
5393 'Use static_cast<%s>(...) instead' %
5394 matched_type)
5395
5396 if not expecting_function:
avakulenko@google.com59146752014-08-11 20:20:55 +00005397 CheckCStyleCast(filename, clean_lines, linenum, 'static_cast',
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005398 r'\((int|float|double|bool|char|u?int(16|32|64))\)', error)
5399
5400 # This doesn't catch all cases. Consider (const char * const)"hello".
5401 #
5402 # (char *) "foo" should always be a const_cast (reinterpret_cast won't
5403 # compile).
avakulenko@google.com59146752014-08-11 20:20:55 +00005404 if CheckCStyleCast(filename, clean_lines, linenum, 'const_cast',
5405 r'\((char\s?\*+\s?)\)\s*"', error):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005406 pass
5407 else:
5408 # Check pointer casts for other than string constants
avakulenko@google.com59146752014-08-11 20:20:55 +00005409 CheckCStyleCast(filename, clean_lines, linenum, 'reinterpret_cast',
5410 r'\((\w+\s?\*+\s?)\)', error)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005411
5412 # In addition, we look for people taking the address of a cast. This
5413 # is dangerous -- casts can assign to temporaries, so the pointer doesn't
5414 # point where you think.
avakulenko@google.com59146752014-08-11 20:20:55 +00005415 #
5416 # Some non-identifier character is required before the '&' for the
5417 # expression to be recognized as a cast. These are casts:
5418 # expression = &static_cast<int*>(temporary());
5419 # function(&(int*)(temporary()));
5420 #
5421 # This is not a cast:
5422 # reference_type&(int* function_param);
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005423 match = Search(
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005424 r'(?:[^\w]&\(([^)*][^)]*)\)[\w(])|'
avakulenko@google.com59146752014-08-11 20:20:55 +00005425 r'(?:[^\w]&(static|dynamic|down|reinterpret)_cast\b)', line)
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005426 if match:
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005427 # Try a better error message when the & is bound to something
5428 # dereferenced by the casted pointer, as opposed to the casted
5429 # pointer itself.
5430 parenthesis_error = False
5431 match = Match(r'^(.*&(?:static|dynamic|down|reinterpret)_cast\b)<', line)
5432 if match:
5433 _, y1, x1 = CloseExpression(clean_lines, linenum, len(match.group(1)))
5434 if x1 >= 0 and clean_lines.elided[y1][x1] == '(':
5435 _, y2, x2 = CloseExpression(clean_lines, y1, x1)
5436 if x2 >= 0:
5437 extended_line = clean_lines.elided[y2][x2:]
5438 if y2 < clean_lines.NumLines() - 1:
5439 extended_line += clean_lines.elided[y2 + 1]
5440 if Match(r'\s*(?:->|\[)', extended_line):
5441 parenthesis_error = True
5442
5443 if parenthesis_error:
5444 error(filename, linenum, 'readability/casting', 4,
5445 ('Are you taking an address of something dereferenced '
5446 'from a cast? Wrapping the dereferenced expression in '
5447 'parentheses will make the binding more obvious'))
5448 else:
5449 error(filename, linenum, 'runtime/casting', 4,
5450 ('Are you taking an address of a cast? '
5451 'This is dangerous: could be a temp var. '
5452 'Take the address before doing the cast, rather than after'))
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005453
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005454
avakulenko@google.com59146752014-08-11 20:20:55 +00005455def CheckCStyleCast(filename, clean_lines, linenum, cast_type, pattern, error):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005456 """Checks for a C-style cast by looking for the pattern.
5457
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005458 Args:
5459 filename: The name of the current file.
avakulenko@google.com59146752014-08-11 20:20:55 +00005460 clean_lines: A CleansedLines instance containing the file.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005461 linenum: The number of the line to check.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005462 cast_type: The string for the C++ cast to recommend. This is either
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005463 reinterpret_cast, static_cast, or const_cast, depending.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005464 pattern: The regular expression used to find C-style casts.
5465 error: The function to call with any errors found.
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005466
5467 Returns:
5468 True if an error was emitted.
5469 False otherwise.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005470 """
avakulenko@google.com59146752014-08-11 20:20:55 +00005471 line = clean_lines.elided[linenum]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005472 match = Search(pattern, line)
5473 if not match:
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005474 return False
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005475
avakulenko@google.com59146752014-08-11 20:20:55 +00005476 # Exclude lines with keywords that tend to look like casts
5477 context = line[0:match.start(1) - 1]
5478 if Match(r'.*\b(?:sizeof|alignof|alignas|[_A-Z][_A-Z0-9]*)\s*$', context):
5479 return False
5480
5481 # Try expanding current context to see if we one level of
5482 # parentheses inside a macro.
5483 if linenum > 0:
Edward Lemur6d31ed52019-12-02 23:00:00 +00005484 for i in range(linenum - 1, max(0, linenum - 5), -1):
avakulenko@google.com59146752014-08-11 20:20:55 +00005485 context = clean_lines.elided[i] + context
5486 if Match(r'.*\b[_A-Z][_A-Z0-9]*\s*\((?:\([^()]*\)|[^()])*$', context):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005487 return False
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005488
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005489 # operator++(int) and operator--(int)
avakulenko@google.com59146752014-08-11 20:20:55 +00005490 if context.endswith(' operator++') or context.endswith(' operator--'):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005491 return False
5492
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005493 # A single unnamed argument for a function tends to look like old style cast.
5494 # If we see those, don't issue warnings for deprecated casts.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005495 remainder = line[match.end(0):]
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005496 if Match(r'^\s*(?:;|const\b|throw\b|final\b|override\b|[=>{),]|->)',
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005497 remainder):
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005498 return False
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005499
5500 # At this point, all that should be left is actual casts.
5501 error(filename, linenum, 'readability/casting', 4,
5502 'Using C-style cast. Use %s<%s>(...) instead' %
5503 (cast_type, match.group(1)))
5504
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005505 return True
5506
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005507
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005508def ExpectingFunctionArgs(clean_lines, linenum):
5509 """Checks whether where function type arguments are expected.
5510
5511 Args:
5512 clean_lines: A CleansedLines instance containing the file.
5513 linenum: The number of the line to check.
5514
5515 Returns:
5516 True if the line at 'linenum' is inside something that expects arguments
5517 of function types.
5518 """
5519 line = clean_lines.elided[linenum]
Peter Kasting00741582023-02-16 20:09:51 +00005520 return (Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line)
5521 or _TYPE_TRAITS_RE.search(line)
5522 or (linenum >= 2 and
5523 (Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\((?:\S+,)?\s*$',
5524 clean_lines.elided[linenum - 1])
5525 or Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\(\s*$',
5526 clean_lines.elided[linenum - 2])
5527 or Search(r'\b(::function|base::FunctionRef)\s*\<\s*$',
5528 clean_lines.elided[linenum - 1]))))
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005529
5530
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005531_HEADERS_CONTAINING_TEMPLATES = (
5532 ('<deque>', ('deque',)),
5533 ('<functional>', ('unary_function', 'binary_function',
5534 'plus', 'minus', 'multiplies', 'divides', 'modulus',
5535 'negate',
5536 'equal_to', 'not_equal_to', 'greater', 'less',
5537 'greater_equal', 'less_equal',
5538 'logical_and', 'logical_or', 'logical_not',
5539 'unary_negate', 'not1', 'binary_negate', 'not2',
5540 'bind1st', 'bind2nd',
5541 'pointer_to_unary_function',
5542 'pointer_to_binary_function',
5543 'ptr_fun',
5544 'mem_fun_t', 'mem_fun', 'mem_fun1_t', 'mem_fun1_ref_t',
5545 'mem_fun_ref_t',
5546 'const_mem_fun_t', 'const_mem_fun1_t',
5547 'const_mem_fun_ref_t', 'const_mem_fun1_ref_t',
5548 'mem_fun_ref',
5549 )),
5550 ('<limits>', ('numeric_limits',)),
5551 ('<list>', ('list',)),
5552 ('<map>', ('map', 'multimap',)),
lhchavez2d1b6da2016-07-13 10:40:01 -07005553 ('<memory>', ('allocator', 'make_shared', 'make_unique', 'shared_ptr',
5554 'unique_ptr', 'weak_ptr')),
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005555 ('<queue>', ('queue', 'priority_queue',)),
5556 ('<set>', ('set', 'multiset',)),
5557 ('<stack>', ('stack',)),
5558 ('<string>', ('char_traits', 'basic_string',)),
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005559 ('<tuple>', ('tuple',)),
lhchavez2d1b6da2016-07-13 10:40:01 -07005560 ('<unordered_map>', ('unordered_map', 'unordered_multimap')),
5561 ('<unordered_set>', ('unordered_set', 'unordered_multiset')),
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005562 ('<utility>', ('pair',)),
5563 ('<vector>', ('vector',)),
5564
5565 # gcc extensions.
5566 # Note: std::hash is their hash, ::hash is our hash
5567 ('<hash_map>', ('hash_map', 'hash_multimap',)),
5568 ('<hash_set>', ('hash_set', 'hash_multiset',)),
5569 ('<slist>', ('slist',)),
5570 )
5571
skym@chromium.org3990c412016-02-05 20:55:12 +00005572_HEADERS_MAYBE_TEMPLATES = (
5573 ('<algorithm>', ('copy', 'max', 'min', 'min_element', 'sort',
5574 'transform',
5575 )),
lhchavez2d1b6da2016-07-13 10:40:01 -07005576 ('<utility>', ('forward', 'make_pair', 'move', 'swap')),
skym@chromium.org3990c412016-02-05 20:55:12 +00005577 )
5578
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005579_RE_PATTERN_STRING = re.compile(r'\bstring\b')
5580
skym@chromium.org3990c412016-02-05 20:55:12 +00005581_re_pattern_headers_maybe_templates = []
5582for _header, _templates in _HEADERS_MAYBE_TEMPLATES:
5583 for _template in _templates:
Peter Kasting03b187d2022-11-04 18:33:43 +00005584 # Match max<type>(..., ...), max(..., ...), but not foo->max or foo.max.
skym@chromium.org3990c412016-02-05 20:55:12 +00005585 _re_pattern_headers_maybe_templates.append(
Peter Kastinge6f3d662022-11-07 22:57:33 +00005586 (re.compile(r'(?<![>.])\b' + _template + r'(<.*?>)?\([^\)]'), _template,
Peter Kasting03b187d2022-11-04 18:33:43 +00005587 _header))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005588
skym@chromium.org3990c412016-02-05 20:55:12 +00005589# Other scripts may reach in and modify this pattern.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005590_re_pattern_templates = []
5591for _header, _templates in _HEADERS_CONTAINING_TEMPLATES:
5592 for _template in _templates:
5593 _re_pattern_templates.append(
5594 (re.compile(r'(\<|\b)' + _template + r'\s*\<'),
5595 _template + '<>',
5596 _header))
5597
5598
erg@google.com6317a9c2009-06-25 00:28:19 +00005599def FilesBelongToSameModule(filename_cc, filename_h):
5600 """Check if these two filenames belong to the same module.
5601
5602 The concept of a 'module' here is a as follows:
5603 foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the
5604 same 'module' if they are in the same directory.
5605 some/path/public/xyzzy and some/path/internal/xyzzy are also considered
5606 to belong to the same module here.
5607
5608 If the filename_cc contains a longer path than the filename_h, for example,
5609 '/absolute/path/to/base/sysinfo.cc', and this file would include
5610 'base/sysinfo.h', this function also produces the prefix needed to open the
5611 header. This is used by the caller of this function to more robustly open the
5612 header file. We don't have access to the real include paths in this context,
5613 so we need this guesswork here.
5614
5615 Known bugs: tools/base/bar.cc and base/bar.h belong to the same module
5616 according to this implementation. Because of this, this function gives
5617 some false positives. This should be sufficiently rare in practice.
5618
5619 Args:
5620 filename_cc: is the path for the .cc file
5621 filename_h: is the path for the header path
5622
5623 Returns:
5624 Tuple with a bool and a string:
5625 bool: True if filename_cc and filename_h belong to the same module.
5626 string: the additional prefix needed to open the header file.
5627 """
5628
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005629 fileinfo = FileInfo(filename_cc)
5630 if not fileinfo.IsSource():
erg@google.com6317a9c2009-06-25 00:28:19 +00005631 return (False, '')
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005632 filename_cc = filename_cc[:-len(fileinfo.Extension())]
5633 matched_test_suffix = Search(_TEST_FILE_SUFFIX, fileinfo.BaseName())
5634 if matched_test_suffix:
5635 filename_cc = filename_cc[:-len(matched_test_suffix.group(1))]
erg@google.com6317a9c2009-06-25 00:28:19 +00005636 filename_cc = filename_cc.replace('/public/', '/')
5637 filename_cc = filename_cc.replace('/internal/', '/')
5638
5639 if not filename_h.endswith('.h'):
5640 return (False, '')
5641 filename_h = filename_h[:-len('.h')]
5642 if filename_h.endswith('-inl'):
5643 filename_h = filename_h[:-len('-inl')]
5644 filename_h = filename_h.replace('/public/', '/')
5645 filename_h = filename_h.replace('/internal/', '/')
5646
5647 files_belong_to_same_module = filename_cc.endswith(filename_h)
5648 common_path = ''
5649 if files_belong_to_same_module:
5650 common_path = filename_cc[:-len(filename_h)]
5651 return files_belong_to_same_module, common_path
5652
5653
avakulenko@google.com59146752014-08-11 20:20:55 +00005654def UpdateIncludeState(filename, include_dict, io=codecs):
5655 """Fill up the include_dict with new includes found from the file.
erg@google.com6317a9c2009-06-25 00:28:19 +00005656
5657 Args:
5658 filename: the name of the header to read.
avakulenko@google.com59146752014-08-11 20:20:55 +00005659 include_dict: a dictionary in which the headers are inserted.
erg@google.com6317a9c2009-06-25 00:28:19 +00005660 io: The io factory to use to read the file. Provided for testability.
5661
5662 Returns:
avakulenko@google.com59146752014-08-11 20:20:55 +00005663 True if a header was successfully added. False otherwise.
erg@google.com6317a9c2009-06-25 00:28:19 +00005664 """
5665 headerfile = None
5666 try:
5667 headerfile = io.open(filename, 'r', 'utf8', 'replace')
5668 except IOError:
5669 return False
5670 linenum = 0
5671 for line in headerfile:
5672 linenum += 1
5673 clean_line = CleanseComments(line)
5674 match = _RE_PATTERN_INCLUDE.search(clean_line)
5675 if match:
5676 include = match.group(2)
avakulenko@google.com59146752014-08-11 20:20:55 +00005677 include_dict.setdefault(include, linenum)
erg@google.com6317a9c2009-06-25 00:28:19 +00005678 return True
5679
5680
Peter Kasting03b187d2022-11-04 18:33:43 +00005681def UpdateRequiredHeadersForLine(patterns, line, linenum, required):
5682 for pattern, template, header in patterns:
5683 matched = pattern.search(line)
5684 if matched:
5685 # Don't warn about IWYU in non-STL namespaces:
5686 # (We check only the first match per line; good enough.)
5687 prefix = line[:matched.start()]
5688 if prefix.endswith('std::') or not prefix.endswith('::'):
5689 required[header] = (linenum, template)
5690 return required
5691
5692
erg@google.com6317a9c2009-06-25 00:28:19 +00005693def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error,
5694 io=codecs):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005695 """Reports for missing stl includes.
5696
5697 This function will output warnings to make sure you are including the headers
5698 necessary for the stl containers and functions that you use. We only give one
5699 reason to include a header. For example, if you use both equal_to<> and
5700 less<> in a .h file, only one (the latter in the file) of these will be
5701 reported as a reason to include the <functional>.
5702
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005703 Args:
5704 filename: The name of the current file.
5705 clean_lines: A CleansedLines instance containing the file.
5706 include_state: An _IncludeState instance.
5707 error: The function to call with any errors found.
erg@google.com6317a9c2009-06-25 00:28:19 +00005708 io: The IO factory to use to read the header file. Provided for unittest
5709 injection.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005710 """
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +00005711 # A map of header name to linenumber and the template entity.
5712 # Example of required: { '<functional>': (1219, 'less<>') }
5713 required = {}
Edward Lemur6d31ed52019-12-02 23:00:00 +00005714 for linenum in range(clean_lines.NumLines()):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005715 line = clean_lines.elided[linenum]
5716 if not line or line[0] == '#':
5717 continue
5718
5719 # String is special -- it is a non-templatized type in STL.
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005720 matched = _RE_PATTERN_STRING.search(line)
5721 if matched:
erg@google.com35589e62010-11-17 18:58:16 +00005722 # Don't warn about strings in non-STL namespaces:
5723 # (We check only the first match per line; good enough.)
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005724 prefix = line[:matched.start()]
erg@google.com35589e62010-11-17 18:58:16 +00005725 if prefix.endswith('std::') or not prefix.endswith('::'):
5726 required['<string>'] = (linenum, 'string')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005727
Peter Kasting03b187d2022-11-04 18:33:43 +00005728 required = UpdateRequiredHeadersForLine(_re_pattern_headers_maybe_templates,
5729 line, linenum, required)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005730
5731 # The following function is just a speed up, no semantics are changed.
5732 if not '<' in line: # Reduces the cpu time usage by skipping lines.
5733 continue
5734
Peter Kasting03b187d2022-11-04 18:33:43 +00005735 required = UpdateRequiredHeadersForLine(_re_pattern_templates, line,
5736 linenum, required)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005737
erg@google.com6317a9c2009-06-25 00:28:19 +00005738 # The policy is that if you #include something in foo.h you don't need to
5739 # include it again in foo.cc. Here, we will look at possible includes.
avakulenko@google.com59146752014-08-11 20:20:55 +00005740 # Let's flatten the include_state include_list and copy it into a dictionary.
5741 include_dict = dict([item for sublist in include_state.include_list
5742 for item in sublist])
erg@google.com6317a9c2009-06-25 00:28:19 +00005743
avakulenko@google.com59146752014-08-11 20:20:55 +00005744 # Did we find the header for this file (if any) and successfully load it?
erg@google.com6317a9c2009-06-25 00:28:19 +00005745 header_found = False
5746
5747 # Use the absolute path so that matching works properly.
erg@chromium.org8f927562012-01-30 19:51:28 +00005748 abs_filename = FileInfo(filename).FullName()
erg@google.com6317a9c2009-06-25 00:28:19 +00005749
5750 # For Emacs's flymake.
5751 # If cpplint is invoked from Emacs's flymake, a temporary file is generated
5752 # by flymake and that file name might end with '_flymake.cc'. In that case,
5753 # restore original file name here so that the corresponding header file can be
5754 # found.
5755 # e.g. If the file name is 'foo_flymake.cc', we should search for 'foo.h'
5756 # instead of 'foo_flymake.h'
erg@google.com35589e62010-11-17 18:58:16 +00005757 abs_filename = re.sub(r'_flymake\.cc$', '.cc', abs_filename)
erg@google.com6317a9c2009-06-25 00:28:19 +00005758
avakulenko@google.com59146752014-08-11 20:20:55 +00005759 # include_dict is modified during iteration, so we iterate over a copy of
erg@google.com6317a9c2009-06-25 00:28:19 +00005760 # the keys.
Sarthak Kukreti60378202019-12-17 20:46:58 +00005761 header_keys = list(include_dict.keys())
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005762 for header in header_keys:
erg@google.com6317a9c2009-06-25 00:28:19 +00005763 (same_module, common_path) = FilesBelongToSameModule(abs_filename, header)
5764 fullpath = common_path + header
avakulenko@google.com59146752014-08-11 20:20:55 +00005765 if same_module and UpdateIncludeState(fullpath, include_dict, io):
erg@google.com6317a9c2009-06-25 00:28:19 +00005766 header_found = True
5767
5768 # If we can't find the header file for a .cc, assume it's because we don't
5769 # know where to look. In that case we'll give up as we're not sure they
5770 # didn't include it in the .h file.
5771 # TODO(unknown): Do a better job of finding .h files so we are confident that
5772 # not having the .h file means there isn't one.
5773 if filename.endswith('.cc') and not header_found:
5774 return
5775
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005776 # All the lines have been processed, report the errors found.
5777 for required_header_unstripped in required:
5778 template = required[required_header_unstripped][1]
avakulenko@google.com59146752014-08-11 20:20:55 +00005779 if required_header_unstripped.strip('<>"') not in include_dict:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005780 error(filename, required[required_header_unstripped][0],
5781 'build/include_what_you_use', 4,
5782 'Add #include ' + required_header_unstripped + ' for ' + template)
5783
5784
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005785_RE_PATTERN_EXPLICIT_MAKEPAIR = re.compile(r'\bmake_pair\s*<')
5786
5787
5788def CheckMakePairUsesDeduction(filename, clean_lines, linenum, error):
5789 """Check that make_pair's template arguments are deduced.
5790
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005791 G++ 4.6 in C++11 mode fails badly if make_pair's template arguments are
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005792 specified explicitly, and such use isn't intended in any case.
5793
5794 Args:
5795 filename: The name of the current file.
5796 clean_lines: A CleansedLines instance containing the file.
5797 linenum: The number of the line to check.
5798 error: The function to call with any errors found.
5799 """
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005800 line = clean_lines.elided[linenum]
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005801 match = _RE_PATTERN_EXPLICIT_MAKEPAIR.search(line)
5802 if match:
5803 error(filename, linenum, 'build/explicit_make_pair',
5804 4, # 4 = high confidence
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005805 'For C++11-compatibility, omit template arguments from make_pair'
5806 ' OR use pair directly OR if appropriate, construct a pair directly')
avakulenko@google.com59146752014-08-11 20:20:55 +00005807
5808
avakulenko@google.com59146752014-08-11 20:20:55 +00005809def CheckRedundantVirtual(filename, clean_lines, linenum, error):
5810 """Check if line contains a redundant "virtual" function-specifier.
5811
5812 Args:
5813 filename: The name of the current file.
5814 clean_lines: A CleansedLines instance containing the file.
5815 linenum: The number of the line to check.
5816 error: The function to call with any errors found.
5817 """
5818 # Look for "virtual" on current line.
5819 line = clean_lines.elided[linenum]
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005820 virtual = Match(r'^(.*)(\bvirtual\b)(.*)$', line)
avakulenko@google.com59146752014-08-11 20:20:55 +00005821 if not virtual: return
5822
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005823 # Ignore "virtual" keywords that are near access-specifiers. These
5824 # are only used in class base-specifier and do not apply to member
5825 # functions.
5826 if (Search(r'\b(public|protected|private)\s+$', virtual.group(1)) or
5827 Match(r'^\s+(public|protected|private)\b', virtual.group(3))):
5828 return
5829
5830 # Ignore the "virtual" keyword from virtual base classes. Usually
5831 # there is a column on the same line in these cases (virtual base
5832 # classes are rare in google3 because multiple inheritance is rare).
5833 if Match(r'^.*[^:]:[^:].*$', line): return
5834
avakulenko@google.com59146752014-08-11 20:20:55 +00005835 # Look for the next opening parenthesis. This is the start of the
5836 # parameter list (possibly on the next line shortly after virtual).
5837 # TODO(unknown): doesn't work if there are virtual functions with
5838 # decltype() or other things that use parentheses, but csearch suggests
5839 # that this is rare.
5840 end_col = -1
5841 end_line = -1
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005842 start_col = len(virtual.group(2))
Edward Lemur6d31ed52019-12-02 23:00:00 +00005843 for start_line in range(linenum, min(linenum + 3, clean_lines.NumLines())):
avakulenko@google.com59146752014-08-11 20:20:55 +00005844 line = clean_lines.elided[start_line][start_col:]
5845 parameter_list = Match(r'^([^(]*)\(', line)
5846 if parameter_list:
5847 # Match parentheses to find the end of the parameter list
5848 (_, end_line, end_col) = CloseExpression(
5849 clean_lines, start_line, start_col + len(parameter_list.group(1)))
5850 break
5851 start_col = 0
5852
5853 if end_col < 0:
5854 return # Couldn't find end of parameter list, give up
5855
5856 # Look for "override" or "final" after the parameter list
5857 # (possibly on the next few lines).
Edward Lemur6d31ed52019-12-02 23:00:00 +00005858 for i in range(end_line, min(end_line + 3, clean_lines.NumLines())):
avakulenko@google.com59146752014-08-11 20:20:55 +00005859 line = clean_lines.elided[i][end_col:]
5860 match = Search(r'\b(override|final)\b', line)
5861 if match:
5862 error(filename, linenum, 'readability/inheritance', 4,
5863 ('"virtual" is redundant since function is '
5864 'already declared as "%s"' % match.group(1)))
5865
5866 # Set end_col to check whole lines after we are done with the
5867 # first line.
5868 end_col = 0
5869 if Search(r'[^\w]\s*$', line):
5870 break
5871
5872
5873def CheckRedundantOverrideOrFinal(filename, clean_lines, linenum, error):
5874 """Check if line contains a redundant "override" or "final" virt-specifier.
5875
5876 Args:
5877 filename: The name of the current file.
5878 clean_lines: A CleansedLines instance containing the file.
5879 linenum: The number of the line to check.
5880 error: The function to call with any errors found.
5881 """
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005882 # Look for closing parenthesis nearby. We need one to confirm where
5883 # the declarator ends and where the virt-specifier starts to avoid
5884 # false positives.
avakulenko@google.com59146752014-08-11 20:20:55 +00005885 line = clean_lines.elided[linenum]
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005886 declarator_end = line.rfind(')')
5887 if declarator_end >= 0:
5888 fragment = line[declarator_end:]
5889 else:
5890 if linenum > 1 and clean_lines.elided[linenum - 1].rfind(')') >= 0:
5891 fragment = line
5892 else:
5893 return
5894
5895 # Check that at most one of "override" or "final" is present, not both
5896 if Search(r'\boverride\b', fragment) and Search(r'\bfinal\b', fragment):
avakulenko@google.com59146752014-08-11 20:20:55 +00005897 error(filename, linenum, 'readability/inheritance', 4,
5898 ('"override" is redundant since function is '
5899 'already declared as "final"'))
5900
5901
5902
5903
5904# Returns true if we are at a new block, and it is directly
5905# inside of a namespace.
5906def IsBlockInNameSpace(nesting_state, is_forward_declaration):
5907 """Checks that the new block is directly in a namespace.
5908
5909 Args:
5910 nesting_state: The _NestingState object that contains info about our state.
5911 is_forward_declaration: If the class is a forward declared class.
5912 Returns:
5913 Whether or not the new block is directly in a namespace.
5914 """
5915 if is_forward_declaration:
5916 if len(nesting_state.stack) >= 1 and (
5917 isinstance(nesting_state.stack[-1], _NamespaceInfo)):
5918 return True
5919 else:
5920 return False
5921
5922 return (len(nesting_state.stack) > 1 and
5923 nesting_state.stack[-1].check_namespace_indentation and
5924 isinstance(nesting_state.stack[-2], _NamespaceInfo))
5925
5926
5927def ShouldCheckNamespaceIndentation(nesting_state, is_namespace_indent_item,
5928 raw_lines_no_comments, linenum):
5929 """This method determines if we should apply our namespace indentation check.
5930
5931 Args:
5932 nesting_state: The current nesting state.
5933 is_namespace_indent_item: If we just put a new class on the stack, True.
5934 If the top of the stack is not a class, or we did not recently
5935 add the class, False.
5936 raw_lines_no_comments: The lines without the comments.
5937 linenum: The current line number we are processing.
5938
5939 Returns:
5940 True if we should apply our namespace indentation check. Currently, it
5941 only works for classes and namespaces inside of a namespace.
5942 """
5943
5944 is_forward_declaration = IsForwardClassDeclaration(raw_lines_no_comments,
5945 linenum)
5946
5947 if not (is_namespace_indent_item or is_forward_declaration):
5948 return False
5949
5950 # If we are in a macro, we do not want to check the namespace indentation.
5951 if IsMacroDefinition(raw_lines_no_comments, linenum):
5952 return False
5953
5954 return IsBlockInNameSpace(nesting_state, is_forward_declaration)
5955
5956
5957# Call this method if the line is directly inside of a namespace.
5958# If the line above is blank (excluding comments) or the start of
5959# an inner namespace, it cannot be indented.
5960def CheckItemIndentationInNamespace(filename, raw_lines_no_comments, linenum,
5961 error):
5962 line = raw_lines_no_comments[linenum]
5963 if Match(r'^\s+', line):
5964 error(filename, linenum, 'runtime/indentation_namespace', 4,
5965 'Do not indent within a namespace')
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005966
5967
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005968def ProcessLine(filename, file_extension, clean_lines, line,
5969 include_state, function_state, nesting_state, error,
5970 extra_check_functions=[]):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005971 """Processes a single line in the file.
5972
5973 Args:
5974 filename: Filename of the file that is being processed.
5975 file_extension: The extension (dot not included) of the file.
5976 clean_lines: An array of strings, each representing a line of the file,
5977 with comments stripped.
5978 line: Number of line being processed.
5979 include_state: An _IncludeState instance in which the headers are inserted.
5980 function_state: A _FunctionState instance which counts function lines, etc.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005981 nesting_state: A NestingState instance which maintains information about
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005982 the current stack of nested blocks being parsed.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005983 error: A callable to which errors are reported, which takes 4 arguments:
5984 filename, line number, error level, and message
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005985 extra_check_functions: An array of additional check functions that will be
5986 run on each source line. Each function takes 4
5987 arguments: filename, clean_lines, line, error
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005988 """
5989 raw_lines = clean_lines.raw_lines
erg@google.com35589e62010-11-17 18:58:16 +00005990 ParseNolintSuppressions(filename, raw_lines[line], line, error)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005991 nesting_state.Update(filename, clean_lines, line, error)
avakulenko@google.com59146752014-08-11 20:20:55 +00005992 CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line,
5993 error)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005994 if nesting_state.InAsmBlock(): return
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005995 CheckForFunctionLengths(filename, clean_lines, line, function_state, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005996 CheckForMultilineCommentsAndStrings(filename, clean_lines, line, error)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005997 CheckStyle(filename, clean_lines, line, file_extension, nesting_state, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005998 CheckLanguage(filename, clean_lines, line, file_extension, include_state,
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005999 nesting_state, error)
6000 CheckForNonConstReference(filename, clean_lines, line, nesting_state, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006001 CheckForNonStandardConstructs(filename, clean_lines, line,
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00006002 nesting_state, error)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00006003 CheckVlogArguments(filename, clean_lines, line, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006004 CheckPosixThreading(filename, clean_lines, line, error)
erg@google.com6317a9c2009-06-25 00:28:19 +00006005 CheckInvalidIncrement(filename, clean_lines, line, error)
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00006006 CheckMakePairUsesDeduction(filename, clean_lines, line, error)
avakulenko@google.com59146752014-08-11 20:20:55 +00006007 CheckRedundantVirtual(filename, clean_lines, line, error)
6008 CheckRedundantOverrideOrFinal(filename, clean_lines, line, error)
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00006009 for check_fn in extra_check_functions:
6010 check_fn(filename, clean_lines, line, error)
avakulenko@google.com17449932014-07-28 22:13:33 +00006011
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00006012def FlagCxx11Features(filename, clean_lines, linenum, error):
6013 """Flag those c++11 features that we only allow in certain places.
6014
6015 Args:
6016 filename: The name of the current file.
6017 clean_lines: A CleansedLines instance containing the file.
6018 linenum: The number of the line to check.
6019 error: The function to call with any errors found.
6020 """
6021 line = clean_lines.elided[linenum]
6022
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00006023 include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line)
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00006024
6025 # Flag unapproved C++ TR1 headers.
6026 if include and include.group(1).startswith('tr1/'):
6027 error(filename, linenum, 'build/c++tr1', 5,
6028 ('C++ TR1 headers such as <%s> are unapproved.') % include.group(1))
6029
6030 # Flag unapproved C++11 headers.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00006031 if include and include.group(1) in ('cfenv',
6032 'condition_variable',
6033 'fenv.h',
6034 'future',
6035 'mutex',
6036 'thread',
6037 'chrono',
6038 'ratio',
6039 'regex',
6040 'system_error',
6041 ):
6042 error(filename, linenum, 'build/c++11', 5,
6043 ('<%s> is an unapproved C++11 header.') % include.group(1))
6044
6045 # The only place where we need to worry about C++11 keywords and library
6046 # features in preprocessor directives is in macro definitions.
6047 if Match(r'\s*#', line) and not Match(r'\s*#\s*define\b', line): return
6048
6049 # These are classes and free functions. The classes are always
6050 # mentioned as std::*, but we only catch the free functions if
6051 # they're not found by ADL. They're alphabetical by header.
6052 for top_name in (
6053 # type_traits
6054 'alignment_of',
6055 'aligned_union',
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00006056 ):
6057 if Search(r'\bstd::%s\b' % top_name, line):
6058 error(filename, linenum, 'build/c++11', 5,
6059 ('std::%s is an unapproved C++11 class or function. Send c-style '
6060 'an example of where it would make your code more readable, and '
6061 'they may let you use it.') % top_name)
6062
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006063
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00006064def FlagCxx14Features(filename, clean_lines, linenum, error):
6065 """Flag those C++14 features that we restrict.
6066
6067 Args:
6068 filename: The name of the current file.
6069 clean_lines: A CleansedLines instance containing the file.
6070 linenum: The number of the line to check.
6071 error: The function to call with any errors found.
6072 """
6073 line = clean_lines.elided[linenum]
6074
6075 include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line)
6076
6077 # Flag unapproved C++14 headers.
6078 if include and include.group(1) in ('scoped_allocator', 'shared_mutex'):
6079 error(filename, linenum, 'build/c++14', 5,
6080 ('<%s> is an unapproved C++14 header.') % include.group(1))
6081
6082
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00006083def ProcessFileData(filename, file_extension, lines, error,
6084 extra_check_functions=[]):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006085 """Performs lint checks and reports any errors to the given error function.
6086
6087 Args:
6088 filename: Filename of the file that is being processed.
6089 file_extension: The extension (dot not included) of the file.
6090 lines: An array of strings, each representing a line of the file, with the
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00006091 last element being empty if the file is terminated with a newline.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006092 error: A callable to which errors are reported, which takes 4 arguments:
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00006093 filename, line number, error level, and message
6094 extra_check_functions: An array of additional check functions that will be
6095 run on each source line. Each function takes 4
6096 arguments: filename, clean_lines, line, error
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006097 """
6098 lines = (['// marker so line numbers and indices both start at 1'] + lines +
6099 ['// marker so line numbers end in a known way'])
6100
6101 include_state = _IncludeState()
6102 function_state = _FunctionState()
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00006103 nesting_state = NestingState()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006104
erg@google.com35589e62010-11-17 18:58:16 +00006105 ResetNolintSuppressions()
6106
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006107 CheckForCopyright(filename, lines, error)
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00006108 ProcessGlobalSuppresions(lines)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006109 RemoveMultiLineComments(filename, lines, error)
6110 clean_lines = CleansedLines(lines)
avakulenko@google.com255f2be2014-12-05 22:19:55 +00006111
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00006112 if file_extension == 'h':
avakulenko@google.com255f2be2014-12-05 22:19:55 +00006113 CheckForHeaderGuard(filename, clean_lines, error)
6114
Edward Lemur6d31ed52019-12-02 23:00:00 +00006115 for line in range(clean_lines.NumLines()):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006116 ProcessLine(filename, file_extension, clean_lines, line,
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00006117 include_state, function_state, nesting_state, error,
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00006118 extra_check_functions)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00006119 FlagCxx11Features(filename, clean_lines, line, error)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00006120 nesting_state.CheckCompletedBlocks(filename, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006121
6122 CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error)
skym@chromium.org3990c412016-02-05 20:55:12 +00006123
avakulenko@google.com255f2be2014-12-05 22:19:55 +00006124 # Check that the .cc file has included its header if it exists.
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00006125 if _IsSourceExtension(file_extension):
avakulenko@google.com255f2be2014-12-05 22:19:55 +00006126 CheckHeaderFileIncluded(filename, include_state, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006127
6128 # We check here rather than inside ProcessLine so that we see raw
6129 # lines rather than "cleaned" lines.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00006130 CheckForBadCharacters(filename, lines, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006131
6132 CheckForNewlineAtEOF(filename, lines, error)
6133
avakulenko@google.com17449932014-07-28 22:13:33 +00006134def ProcessConfigOverrides(filename):
6135 """ Loads the configuration files and processes the config overrides.
6136
6137 Args:
6138 filename: The name of the file being processed by the linter.
6139
6140 Returns:
6141 False if the current |filename| should not be processed further.
6142 """
6143
6144 abs_filename = os.path.abspath(filename)
6145 cfg_filters = []
6146 keep_looking = True
6147 while keep_looking:
6148 abs_path, base_name = os.path.split(abs_filename)
6149 if not base_name:
6150 break # Reached the root directory.
6151
6152 cfg_file = os.path.join(abs_path, "CPPLINT.cfg")
6153 abs_filename = abs_path
6154 if not os.path.isfile(cfg_file):
6155 continue
6156
6157 try:
6158 with open(cfg_file) as file_handle:
6159 for line in file_handle:
6160 line, _, _ = line.partition('#') # Remove comments.
6161 if not line.strip():
6162 continue
6163
6164 name, _, val = line.partition('=')
6165 name = name.strip()
6166 val = val.strip()
6167 if name == 'set noparent':
6168 keep_looking = False
6169 elif name == 'filter':
6170 cfg_filters.append(val)
6171 elif name == 'exclude_files':
6172 # When matching exclude_files pattern, use the base_name of
6173 # the current file name or the directory name we are processing.
6174 # For example, if we are checking for lint errors in /foo/bar/baz.cc
6175 # and we found the .cfg file at /foo/CPPLINT.cfg, then the config
6176 # file's "exclude_files" filter is meant to be checked against "bar"
6177 # and not "baz" nor "bar/baz.cc".
6178 if base_name:
6179 pattern = re.compile(val)
6180 if pattern.match(base_name):
6181 sys.stderr.write('Ignoring "%s": file excluded by "%s". '
6182 'File path component "%s" matches '
6183 'pattern "%s"\n' %
6184 (filename, cfg_file, base_name, val))
6185 return False
avakulenko@google.com68a4fa62014-08-25 16:26:18 +00006186 elif name == 'linelength':
6187 global _line_length
6188 try:
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +00006189 _line_length = int(val)
avakulenko@google.com68a4fa62014-08-25 16:26:18 +00006190 except ValueError:
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +00006191 sys.stderr.write('Line length must be numeric.')
avakulenko@google.com17449932014-07-28 22:13:33 +00006192 else:
6193 sys.stderr.write(
6194 'Invalid configuration option (%s) in file %s\n' %
6195 (name, cfg_file))
6196
6197 except IOError:
6198 sys.stderr.write(
6199 "Skipping config file '%s': Can't open for reading\n" % cfg_file)
6200 keep_looking = False
6201
6202 # Apply all the accumulated filters in reverse order (top-level directory
6203 # config options having the least priority).
6204 for filter in reversed(cfg_filters):
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +00006205 _AddFilters(filter)
avakulenko@google.com17449932014-07-28 22:13:33 +00006206
6207 return True
6208
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00006209
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00006210def ProcessFile(filename, vlevel, extra_check_functions=[]):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006211 """Does google-lint on a single file.
6212
6213 Args:
6214 filename: The name of the file to parse.
6215
6216 vlevel: The level of errors to report. Every error of confidence
6217 >= verbose_level will be reported. 0 is a good default.
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00006218
6219 extra_check_functions: An array of additional check functions that will be
6220 run on each source line. Each function takes 4
6221 arguments: filename, clean_lines, line, error
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006222 """
6223
6224 _SetVerboseLevel(vlevel)
avakulenko@google.com17449932014-07-28 22:13:33 +00006225 _BackupFilters()
6226
6227 if not ProcessConfigOverrides(filename):
6228 _RestoreFilters()
6229 return
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006230
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00006231 lf_lines = []
6232 crlf_lines = []
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006233 try:
6234 # Support the UNIX convention of using "-" for stdin. Note that
6235 # we are not opening the file with universal newline support
6236 # (which codecs doesn't support anyway), so the resulting lines do
6237 # contain trailing '\r' characters if we are reading a file that
6238 # has CRLF endings.
6239 # If after the split a trailing '\r' is present, it is removed
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00006240 # below.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006241 if filename == '-':
6242 lines = codecs.StreamReaderWriter(sys.stdin,
6243 codecs.getreader('utf8'),
6244 codecs.getwriter('utf8'),
6245 'replace').read().split('\n')
6246 else:
6247 lines = codecs.open(filename, 'r', 'utf8', 'replace').read().split('\n')
6248
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006249 # Remove trailing '\r'.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00006250 # The -1 accounts for the extra trailing blank line we get from split()
6251 for linenum in range(len(lines) - 1):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006252 if lines[linenum].endswith('\r'):
6253 lines[linenum] = lines[linenum].rstrip('\r')
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00006254 crlf_lines.append(linenum + 1)
6255 else:
6256 lf_lines.append(linenum + 1)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006257
6258 except IOError:
6259 sys.stderr.write(
6260 "Skipping input '%s': Can't open for reading\n" % filename)
avakulenko@google.com17449932014-07-28 22:13:33 +00006261 _RestoreFilters()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006262 return
6263
6264 # Note, if no dot is found, this will give the entire filename as the ext.
6265 file_extension = filename[filename.rfind('.') + 1:]
6266
6267 # When reading from stdin, the extension is unknown, so no cpplint tests
6268 # should rely on the extension.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00006269 if filename != '-' and file_extension not in _valid_extensions:
6270 sys.stderr.write('Ignoring %s; not a valid file name '
6271 '(%s)\n' % (filename, ', '.join(_valid_extensions)))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006272 else:
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00006273 ProcessFileData(filename, file_extension, lines, Error,
6274 extra_check_functions)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00006275
6276 # If end-of-line sequences are a mix of LF and CR-LF, issue
6277 # warnings on the lines with CR.
6278 #
6279 # Don't issue any warnings if all lines are uniformly LF or CR-LF,
6280 # since critique can handle these just fine, and the style guide
6281 # doesn't dictate a particular end of line sequence.
6282 #
6283 # We can't depend on os.linesep to determine what the desired
6284 # end-of-line sequence should be, since that will return the
6285 # server-side end-of-line sequence.
6286 if lf_lines and crlf_lines:
6287 # Warn on every line with CR. An alternative approach might be to
6288 # check whether the file is mostly CRLF or just LF, and warn on the
6289 # minority, we bias toward LF here since most tools prefer LF.
6290 for linenum in crlf_lines:
6291 Error(filename, linenum, 'whitespace/newline', 1,
6292 'Unexpected \\r (^M) found; better to use only \\n')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006293
avakulenko@google.com17449932014-07-28 22:13:33 +00006294 _RestoreFilters()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006295
6296
6297def PrintUsage(message):
6298 """Prints a brief usage string and exits, optionally with an error message.
6299
6300 Args:
6301 message: The optional error message.
6302 """
6303 sys.stderr.write(_USAGE)
6304 if message:
6305 sys.exit('\nFATAL ERROR: ' + message)
6306 else:
6307 sys.exit(1)
6308
6309
6310def PrintCategories():
6311 """Prints a list of all the error-categories used by error messages.
6312
6313 These are the categories used to filter messages via --filter.
6314 """
erg@google.com35589e62010-11-17 18:58:16 +00006315 sys.stderr.write(''.join(' %s\n' % cat for cat in _ERROR_CATEGORIES))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006316 sys.exit(0)
6317
6318
6319def ParseArguments(args):
6320 """Parses the command line arguments.
6321
6322 This may set the output format and verbosity level as side-effects.
6323
6324 Args:
6325 args: The command line arguments:
6326
6327 Returns:
6328 The list of filenames to lint.
6329 """
6330 try:
6331 (opts, filenames) = getopt.getopt(args, '', ['help', 'output=', 'verbose=',
Jordan Bayles91a32c52019-02-22 21:28:17 +00006332 'headers=', # We understand but ignore headers.
erg@google.com26970fa2009-11-17 18:07:32 +00006333 'counting=',
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00006334 'filter=',
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00006335 'root=',
6336 'linelength=',
sdefresne263e9282016-07-19 02:14:22 -07006337 'extensions=',
Jordan Bayles91a32c52019-02-22 21:28:17 +00006338 'project_root=',
6339 'repository='])
6340 except getopt.GetoptError as e:
6341 PrintUsage('Invalid arguments: {}'.format(e))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006342
6343 verbosity = _VerboseLevel()
6344 output_format = _OutputFormat()
6345 filters = ''
erg@google.com26970fa2009-11-17 18:07:32 +00006346 counting_style = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006347
6348 for (opt, val) in opts:
6349 if opt == '--help':
6350 PrintUsage(None)
6351 elif opt == '--output':
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00006352 if val not in ('emacs', 'vs7', 'eclipse'):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00006353 PrintUsage('The only allowed output formats are emacs, vs7 and eclipse.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006354 output_format = val
6355 elif opt == '--verbose':
6356 verbosity = int(val)
6357 elif opt == '--filter':
6358 filters = val
erg@google.com6317a9c2009-06-25 00:28:19 +00006359 if not filters:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006360 PrintCategories()
erg@google.com26970fa2009-11-17 18:07:32 +00006361 elif opt == '--counting':
6362 if val not in ('total', 'toplevel', 'detailed'):
6363 PrintUsage('Valid counting options are total, toplevel, and detailed')
6364 counting_style = val
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00006365 elif opt == '--root':
6366 global _root
6367 _root = val
Jordan Bayles91a32c52019-02-22 21:28:17 +00006368 elif opt == '--project_root' or opt == "--repository":
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00006369 global _project_root
6370 _project_root = val
6371 if not os.path.isabs(_project_root):
6372 PrintUsage('Project root must be an absolute path.')
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00006373 elif opt == '--linelength':
6374 global _line_length
6375 try:
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +00006376 _line_length = int(val)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00006377 except ValueError:
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +00006378 PrintUsage('Line length must be digits.')
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00006379 elif opt == '--extensions':
6380 global _valid_extensions
6381 try:
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +00006382 _valid_extensions = set(val.split(','))
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00006383 except ValueError:
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +00006384 PrintUsage('Extensions must be comma separated list.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006385
6386 if not filenames:
6387 PrintUsage('No files were specified.')
6388
6389 _SetOutputFormat(output_format)
6390 _SetVerboseLevel(verbosity)
6391 _SetFilters(filters)
erg@google.com26970fa2009-11-17 18:07:32 +00006392 _SetCountingStyle(counting_style)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006393
6394 return filenames
6395
6396
6397def main():
6398 filenames = ParseArguments(sys.argv[1:])
6399
6400 # Change stderr to write with replacement characters so we don't die
6401 # if we try to print something containing non-ASCII characters.
Edward Lemur6d31ed52019-12-02 23:00:00 +00006402 # We use sys.stderr.buffer in Python 3, since StreamReaderWriter writes bytes
6403 # to the specified stream.
6404 sys.stderr = codecs.StreamReaderWriter(
6405 getattr(sys.stderr, 'buffer', sys.stderr),
6406 codecs.getreader('utf8'), codecs.getwriter('utf8'), 'replace')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006407
erg@google.com26970fa2009-11-17 18:07:32 +00006408 _cpplint_state.ResetErrorCounts()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006409 for filename in filenames:
6410 ProcessFile(filename, _cpplint_state.verbose_level)
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00006411 _cpplint_state.PrintErrorCounts()
erg@google.com26970fa2009-11-17 18:07:32 +00006412
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006413 sys.exit(_cpplint_state.error_count > 0)
6414
6415
6416if __name__ == '__main__':
6417 main()