blob: 0e7f4a8ef060b4e6968fd9fb37b53d294f1980e3 [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
3303_RE_PATTERN_TODO = re.compile(r'^//(\s*)TODO(\(.+?\))?:?(\s|$)?')
3304
3305
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003306def CheckComment(line, filename, linenum, next_line_start, error):
3307 """Checks for common mistakes in comments.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003308
3309 Args:
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003310 line: The line in question.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003311 filename: The name of the current file.
3312 linenum: The number of the line to check.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003313 next_line_start: The first non-whitespace column of the next line.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003314 error: The function to call with any errors found.
3315 """
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003316 commentpos = line.find('//')
3317 if commentpos != -1:
3318 # Check if the // may be in quotes. If so, ignore it
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003319 if re.sub(r'\\.', '', line[0:commentpos]).count('"') % 2 == 0:
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003320 # Allow one space for new scopes, two spaces otherwise:
3321 if (not (Match(r'^.*{ *//', line) and next_line_start == commentpos) and
3322 ((commentpos >= 1 and
3323 line[commentpos-1] not in string.whitespace) or
3324 (commentpos >= 2 and
3325 line[commentpos-2] not in string.whitespace))):
3326 error(filename, linenum, 'whitespace/comments', 2,
3327 'At least two spaces is best between code and comments')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003328
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003329 # Checks for common mistakes in TODO comments.
3330 comment = line[commentpos:]
3331 match = _RE_PATTERN_TODO.match(comment)
3332 if match:
3333 # One whitespace is correct; zero whitespace is handled elsewhere.
3334 leading_whitespace = match.group(1)
3335 if len(leading_whitespace) > 1:
3336 error(filename, linenum, 'whitespace/todo', 2,
3337 'Too many spaces before TODO')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003338
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003339 username = match.group(2)
3340 if not username:
3341 error(filename, linenum, 'readability/todo', 2,
3342 'Missing username in TODO; it should look like '
3343 '"// TODO(my_username): Stuff."')
3344
3345 middle_whitespace = match.group(3)
3346 # Comparisons made explicit for correctness -- pylint: disable=g-explicit-bool-comparison
3347 if middle_whitespace != ' ' and middle_whitespace != '':
3348 error(filename, linenum, 'whitespace/todo', 2,
3349 'TODO(my_username) should be followed by a space')
3350
3351 # If the comment contains an alphanumeric character, there
avakulenko@google.com255f2be2014-12-05 22:19:55 +00003352 # should be a space somewhere between it and the // unless
3353 # it's a /// or //! Doxygen comment.
3354 if (Match(r'//[^ ]*\w', comment) and
3355 not Match(r'(///|//\!)(\s+|$)', comment)):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003356 error(filename, linenum, 'whitespace/comments', 4,
3357 'Should have a space between // and comment')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003358
avakulenko@google.com255f2be2014-12-05 22:19:55 +00003359
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003360def CheckSpacing(filename, clean_lines, linenum, nesting_state, error):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003361 """Checks for the correctness of various spacing issues in the code.
3362
3363 Things we check for: spaces around operators, spaces after
3364 if/for/while/switch, no spaces around parens in function calls, two
3365 spaces between code and comment, don't start a block with a blank
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003366 line, don't end a function with a blank line, don't add a blank line
3367 after public/protected/private, don't have too many blank lines in a row.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003368
3369 Args:
3370 filename: The name of the current file.
3371 clean_lines: A CleansedLines instance containing the file.
3372 linenum: The number of the line to check.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003373 nesting_state: A NestingState instance which maintains information about
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003374 the current stack of nested blocks being parsed.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003375 error: The function to call with any errors found.
3376 """
3377
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003378 # Don't use "elided" lines here, otherwise we can't check commented lines.
3379 # Don't want to use "raw" either, because we don't want to check inside C++11
3380 # raw strings,
3381 raw = clean_lines.lines_without_raw_strings
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003382 line = raw[linenum]
3383
3384 # Before nixing comments, check if the line is blank for no good
3385 # reason. This includes the first line after a block is opened, and
3386 # blank lines at the end of a function (ie, right before a line like '}'
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003387 #
3388 # Skip all the blank line checks if we are immediately inside a
3389 # namespace body. In other words, don't issue blank line warnings
3390 # for this block:
3391 # namespace {
3392 #
3393 # }
3394 #
3395 # A warning about missing end of namespace comments will be issued instead.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003396 #
3397 # Also skip blank line checks for 'extern "C"' blocks, which are formatted
3398 # like namespaces.
3399 if (IsBlankLine(line) and
3400 not nesting_state.InNamespaceBody() and
3401 not nesting_state.InExternC()):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003402 elided = clean_lines.elided
3403 prev_line = elided[linenum - 1]
3404 prevbrace = prev_line.rfind('{')
3405 # TODO(unknown): Don't complain if line before blank line, and line after,
3406 # both start with alnums and are indented the same amount.
3407 # This ignores whitespace at the start of a namespace block
3408 # because those are not usually indented.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003409 if prevbrace != -1 and prev_line[prevbrace:].find('}') == -1:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003410 # OK, we have a blank line at the start of a code block. Before we
3411 # complain, we check if it is an exception to the rule: The previous
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003412 # non-empty line has the parameters of a function header that are indented
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003413 # 4 spaces (because they did not fit in a 80 column line when placed on
3414 # the same line as the function name). We also check for the case where
3415 # the previous line is indented 6 spaces, which may happen when the
3416 # initializers of a constructor do not fit into a 80 column line.
3417 exception = False
3418 if Match(r' {6}\w', prev_line): # Initializer list?
3419 # We are looking for the opening column of initializer list, which
3420 # should be indented 4 spaces to cause 6 space indentation afterwards.
3421 search_position = linenum-2
3422 while (search_position >= 0
3423 and Match(r' {6}\w', elided[search_position])):
3424 search_position -= 1
3425 exception = (search_position >= 0
3426 and elided[search_position][:5] == ' :')
3427 else:
3428 # Search for the function arguments or an initializer list. We use a
3429 # simple heuristic here: If the line is indented 4 spaces; and we have a
3430 # closing paren, without the opening paren, followed by an opening brace
3431 # or colon (for initializer lists) we assume that it is the last line of
3432 # a function header. If we have a colon indented 4 spaces, it is an
3433 # initializer list.
3434 exception = (Match(r' {4}\w[^\(]*\)\s*(const\s*)?(\{\s*$|:)',
3435 prev_line)
3436 or Match(r' {4}:', prev_line))
3437
3438 if not exception:
3439 error(filename, linenum, 'whitespace/blank_line', 2,
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003440 'Redundant blank line at the start of a code block '
3441 'should be deleted.')
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003442 # Ignore blank lines at the end of a block in a long if-else
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003443 # chain, like this:
3444 # if (condition1) {
3445 # // Something followed by a blank line
3446 #
3447 # } else if (condition2) {
3448 # // Something else
3449 # }
3450 if linenum + 1 < clean_lines.NumLines():
3451 next_line = raw[linenum + 1]
3452 if (next_line
3453 and Match(r'\s*}', next_line)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003454 and next_line.find('} else ') == -1):
3455 error(filename, linenum, 'whitespace/blank_line', 3,
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003456 'Redundant blank line at the end of a code block '
3457 'should be deleted.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003458
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003459 matched = Match(r'\s*(public|protected|private):', prev_line)
3460 if matched:
3461 error(filename, linenum, 'whitespace/blank_line', 3,
3462 'Do not leave a blank line after "%s:"' % matched.group(1))
3463
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003464 # Next, check comments
3465 next_line_start = 0
3466 if linenum + 1 < clean_lines.NumLines():
3467 next_line = raw[linenum + 1]
3468 next_line_start = len(next_line) - len(next_line.lstrip())
3469 CheckComment(line, filename, linenum, next_line_start, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003470
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003471 # get rid of comments and strings
3472 line = clean_lines.elided[linenum]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003473
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003474 # You shouldn't have spaces before your brackets, except maybe after
Alex Lightac54b8d2022-01-20 13:02:48 +00003475 # 'delete []', 'return []() {};', 'auto [abc, ...] = ...;' or in the case of
3476 # c++ attributes like 'class [[clang::lto_visibility_public]] MyClass'.
Derek Morrisb8265f12020-04-16 18:40:27 +00003477 if (Search(r'\w\s+\[', line)
Alex Lightac54b8d2022-01-20 13:02:48 +00003478 and not Search(r'(?:auto&?|delete|return)\s+\[', line)
Derek Morrisb8265f12020-04-16 18:40:27 +00003479 and not Search(r'\s+\[\[', line)):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003480 error(filename, linenum, 'whitespace/braces', 5,
3481 'Extra space before [')
3482
3483 # In range-based for, we wanted spaces before and after the colon, but
3484 # not around "::" tokens that might appear.
3485 if (Search(r'for *\(.*[^:]:[^: ]', line) or
3486 Search(r'for *\(.*[^: ]:[^:]', line)):
3487 error(filename, linenum, 'whitespace/forcolon', 2,
3488 'Missing space around colon in range-based for loop')
3489
3490
3491def CheckOperatorSpacing(filename, clean_lines, linenum, error):
3492 """Checks for horizontal spacing around operators.
3493
3494 Args:
3495 filename: The name of the current file.
3496 clean_lines: A CleansedLines instance containing the file.
3497 linenum: The number of the line to check.
3498 error: The function to call with any errors found.
3499 """
3500 line = clean_lines.elided[linenum]
3501
3502 # Don't try to do spacing checks for operator methods. Do this by
3503 # replacing the troublesome characters with something else,
3504 # preserving column position for all other characters.
3505 #
3506 # The replacement is done repeatedly to avoid false positives from
3507 # operators that call operators.
3508 while True:
3509 match = Match(r'^(.*\boperator\b)(\S+)(\s*\(.*)$', line)
3510 if match:
3511 line = match.group(1) + ('_' * len(match.group(2))) + match.group(3)
3512 else:
3513 break
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003514
3515 # We allow no-spaces around = within an if: "if ( (a=Foo()) == 0 )".
3516 # Otherwise not. Note we only check for non-spaces on *both* sides;
3517 # sometimes people put non-spaces on one side when aligning ='s among
3518 # many lines (not that this is behavior that I approve of...)
avakulenko@google.com255f2be2014-12-05 22:19:55 +00003519 if ((Search(r'[\w.]=', line) or
3520 Search(r'=[\w.]', line))
3521 and not Search(r'\b(if|while|for) ', line)
3522 # Operators taken from [lex.operators] in C++11 standard.
3523 and not Search(r'(>=|<=|==|!=|&=|\^=|\|=|\+=|\*=|\/=|\%=)', line)
3524 and not Search(r'operator=', line)):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003525 error(filename, linenum, 'whitespace/operators', 4,
3526 'Missing spaces around =')
3527
3528 # It's ok not to have spaces around binary operators like + - * /, but if
3529 # there's too little whitespace, we get concerned. It's hard to tell,
3530 # though, so we punt on this one for now. TODO.
3531
3532 # You should always have whitespace around binary operators.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003533 #
3534 # Check <= and >= first to avoid false positives with < and >, then
3535 # check non-include lines for spacing around < and >.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003536 #
3537 # If the operator is followed by a comma, assume it's be used in a
3538 # macro context and don't do any checks. This avoids false
3539 # positives.
3540 #
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003541 # Note that && is not included here. This is because there are too
3542 # many false positives due to RValue references.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003543 match = Search(r'[^<>=!\s](==|!=|<=|>=|\|\|)[^<>=!\s,;\)]', line)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003544 if match:
3545 error(filename, linenum, 'whitespace/operators', 3,
3546 'Missing spaces around %s' % match.group(1))
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003547 elif not Match(r'#.*include', line):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003548 # Look for < that is not surrounded by spaces. This is only
3549 # triggered if both sides are missing spaces, even though
3550 # technically should should flag if at least one side is missing a
3551 # space. This is done to avoid some false positives with shifts.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003552 match = Match(r'^(.*[^\s<])<[^\s=<,]', line)
3553 if match:
3554 (_, _, end_pos) = CloseExpression(
3555 clean_lines, linenum, len(match.group(1)))
3556 if end_pos <= -1:
3557 error(filename, linenum, 'whitespace/operators', 3,
3558 'Missing spaces around <')
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003559
3560 # Look for > that is not surrounded by spaces. Similar to the
3561 # above, we only trigger if both sides are missing spaces to avoid
3562 # false positives with shifts.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003563 match = Match(r'^(.*[^-\s>])>[^\s=>,]', line)
3564 if match:
3565 (_, _, start_pos) = ReverseCloseExpression(
3566 clean_lines, linenum, len(match.group(1)))
3567 if start_pos <= -1:
3568 error(filename, linenum, 'whitespace/operators', 3,
3569 'Missing spaces around >')
3570
3571 # We allow no-spaces around << when used like this: 10<<20, but
3572 # not otherwise (particularly, not when used as streams)
avakulenko@google.com59146752014-08-11 20:20:55 +00003573 #
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003574 # We also allow operators following an opening parenthesis, since
3575 # those tend to be macros that deal with operators.
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003576 match = Search(r'(operator|[^\s(<])(?:L|UL|LL|ULL|l|ul|ll|ull)?<<([^\s,=<])', line)
avakulenko@google.com255f2be2014-12-05 22:19:55 +00003577 if (match and not (match.group(1).isdigit() and match.group(2).isdigit()) and
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003578 not (match.group(1) == 'operator' and match.group(2) == ';')):
3579 error(filename, linenum, 'whitespace/operators', 3,
3580 'Missing spaces around <<')
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003581
3582 # We allow no-spaces around >> for almost anything. This is because
3583 # C++11 allows ">>" to close nested templates, which accounts for
3584 # most cases when ">>" is not followed by a space.
3585 #
3586 # We still warn on ">>" followed by alpha character, because that is
3587 # likely due to ">>" being used for right shifts, e.g.:
3588 # value >> alpha
3589 #
3590 # When ">>" is used to close templates, the alphanumeric letter that
3591 # follows would be part of an identifier, and there should still be
3592 # a space separating the template type and the identifier.
3593 # type<type<type>> alpha
3594 match = Search(r'>>[a-zA-Z_]', line)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003595 if match:
3596 error(filename, linenum, 'whitespace/operators', 3,
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003597 'Missing spaces around >>')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003598
3599 # There shouldn't be space around unary operators
3600 match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line)
3601 if match:
3602 error(filename, linenum, 'whitespace/operators', 4,
3603 'Extra space for operator %s' % match.group(1))
3604
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003605
3606def CheckParenthesisSpacing(filename, clean_lines, linenum, error):
3607 """Checks for horizontal spacing around parentheses.
3608
3609 Args:
3610 filename: The name of the current file.
3611 clean_lines: A CleansedLines instance containing the file.
3612 linenum: The number of the line to check.
3613 error: The function to call with any errors found.
3614 """
3615 line = clean_lines.elided[linenum]
3616
3617 # No spaces after an if, while, switch, or for
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003618 match = Search(r' (if\(|for\(|while\(|switch\()', line)
3619 if match:
3620 error(filename, linenum, 'whitespace/parens', 5,
3621 'Missing space before ( in %s' % match.group(1))
3622
3623 # For if/for/while/switch, the left and right parens should be
3624 # consistent about how many spaces are inside the parens, and
3625 # there should either be zero or one spaces inside the parens.
3626 # We don't want: "if ( foo)" or "if ( foo )".
erg@google.com6317a9c2009-06-25 00:28:19 +00003627 # Exception: "for ( ; foo; bar)" and "for (foo; bar; )" are allowed.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003628 match = Search(r'\b(if|for|while|switch)\s*'
3629 r'\(([ ]*)(.).*[^ ]+([ ]*)\)\s*{\s*$',
3630 line)
3631 if match:
3632 if len(match.group(2)) != len(match.group(4)):
3633 if not (match.group(3) == ';' and
erg@google.com6317a9c2009-06-25 00:28:19 +00003634 len(match.group(2)) == 1 + len(match.group(4)) or
3635 not match.group(2) and Search(r'\bfor\s*\(.*; \)', line)):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003636 error(filename, linenum, 'whitespace/parens', 5,
3637 'Mismatching spaces inside () in %s' % match.group(1))
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003638 if len(match.group(2)) not in [0, 1]:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003639 error(filename, linenum, 'whitespace/parens', 5,
3640 'Should have zero or one spaces inside ( and ) in %s' %
3641 match.group(1))
3642
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003643
3644def CheckCommaSpacing(filename, clean_lines, linenum, error):
3645 """Checks for horizontal spacing near commas and semicolons.
3646
3647 Args:
3648 filename: The name of the current file.
3649 clean_lines: A CleansedLines instance containing the file.
3650 linenum: The number of the line to check.
3651 error: The function to call with any errors found.
3652 """
3653 raw = clean_lines.lines_without_raw_strings
3654 line = clean_lines.elided[linenum]
3655
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003656 # 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 +00003657 #
3658 # This does not apply when the non-space character following the
3659 # comma is another comma, since the only time when that happens is
3660 # for empty macro arguments.
3661 #
3662 # We run this check in two passes: first pass on elided lines to
3663 # verify that lines contain missing whitespaces, second pass on raw
3664 # lines to confirm that those missing whitespaces are not due to
3665 # elided comments.
avakulenko@google.com59146752014-08-11 20:20:55 +00003666 if (Search(r',[^,\s]', ReplaceAll(r'\boperator\s*,\s*\(', 'F(', line)) and
3667 Search(r',[^,\s]', raw[linenum])):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003668 error(filename, linenum, 'whitespace/comma', 3,
3669 'Missing space after ,')
3670
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003671 # You should always have a space after a semicolon
3672 # except for few corner cases
3673 # TODO(unknown): clarify if 'if (1) { return 1;}' is requires one more
3674 # space after ;
3675 if Search(r';[^\s};\\)/]', line):
3676 error(filename, linenum, 'whitespace/semicolon', 3,
3677 'Missing space after ;')
3678
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003679
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003680def _IsType(clean_lines, nesting_state, expr):
3681 """Check if expression looks like a type name, returns true if so.
3682
3683 Args:
3684 clean_lines: A CleansedLines instance containing the file.
3685 nesting_state: A NestingState instance which maintains information about
3686 the current stack of nested blocks being parsed.
3687 expr: The expression to check.
3688 Returns:
3689 True, if token looks like a type.
3690 """
3691 # Keep only the last token in the expression
3692 last_word = Match(r'^.*(\b\S+)$', expr)
3693 if last_word:
3694 token = last_word.group(1)
3695 else:
3696 token = expr
3697
3698 # Match native types and stdint types
3699 if _TYPES.match(token):
3700 return True
3701
3702 # Try a bit harder to match templated types. Walk up the nesting
3703 # stack until we find something that resembles a typename
3704 # declaration for what we are looking for.
3705 typename_pattern = (r'\b(?:typename|class|struct)\s+' + re.escape(token) +
3706 r'\b')
3707 block_index = len(nesting_state.stack) - 1
3708 while block_index >= 0:
3709 if isinstance(nesting_state.stack[block_index], _NamespaceInfo):
3710 return False
3711
3712 # Found where the opening brace is. We want to scan from this
3713 # line up to the beginning of the function, minus a few lines.
3714 # template <typename Type1, // stop scanning here
3715 # ...>
3716 # class C
3717 # : public ... { // start scanning here
3718 last_line = nesting_state.stack[block_index].starting_linenum
3719
3720 next_block_start = 0
3721 if block_index > 0:
3722 next_block_start = nesting_state.stack[block_index - 1].starting_linenum
3723 first_line = last_line
3724 while first_line >= next_block_start:
3725 if clean_lines.elided[first_line].find('template') >= 0:
3726 break
3727 first_line -= 1
3728 if first_line < next_block_start:
3729 # Didn't find any "template" keyword before reaching the next block,
3730 # there are probably no template things to check for this block
3731 block_index -= 1
3732 continue
3733
3734 # Look for typename in the specified range
Edward Lemur6d31ed52019-12-02 23:00:00 +00003735 for i in range(first_line, last_line + 1, 1):
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003736 if Search(typename_pattern, clean_lines.elided[i]):
3737 return True
3738 block_index -= 1
3739
3740 return False
3741
3742
3743def CheckBracesSpacing(filename, clean_lines, linenum, nesting_state, error):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003744 """Checks for horizontal spacing near commas.
3745
3746 Args:
3747 filename: The name of the current file.
3748 clean_lines: A CleansedLines instance containing the file.
3749 linenum: The number of the line to check.
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003750 nesting_state: A NestingState instance which maintains information about
3751 the current stack of nested blocks being parsed.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003752 error: The function to call with any errors found.
3753 """
3754 line = clean_lines.elided[linenum]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003755
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003756 # Except after an opening paren, or after another opening brace (in case of
3757 # an initializer list, for instance), you should have spaces before your
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003758 # braces when they are delimiting blocks, classes, namespaces etc.
3759 # And since you should never have braces at the beginning of a line,
3760 # this is an easy test. Except that braces used for initialization don't
3761 # follow the same rule; we often don't want spaces before those.
avakulenko@google.com255f2be2014-12-05 22:19:55 +00003762 match = Match(r'^(.*[^ ({>]){', line)
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003763
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003764 if match:
3765 # Try a bit harder to check for brace initialization. This
3766 # happens in one of the following forms:
3767 # Constructor() : initializer_list_{} { ... }
3768 # Constructor{}.MemberFunction()
3769 # Type variable{};
3770 # FunctionCall(type{}, ...);
3771 # LastArgument(..., type{});
3772 # LOG(INFO) << type{} << " ...";
3773 # map_of_type[{...}] = ...;
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003774 # ternary = expr ? new type{} : nullptr;
3775 # OuterTemplate<InnerTemplateConstructor<Type>{}>
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003776 #
3777 # We check for the character following the closing brace, and
3778 # silence the warning if it's one of those listed above, i.e.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003779 # "{.;,)<>]:".
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003780 #
3781 # To account for nested initializer list, we allow any number of
3782 # closing braces up to "{;,)<". We can't simply silence the
3783 # warning on first sight of closing brace, because that would
3784 # cause false negatives for things that are not initializer lists.
3785 # Silence this: But not this:
3786 # Outer{ if (...) {
3787 # Inner{...} if (...){ // Missing space before {
3788 # }; }
3789 #
3790 # There is a false negative with this approach if people inserted
3791 # spurious semicolons, e.g. "if (cond){};", but we will catch the
3792 # spurious semicolon with a separate check.
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003793 leading_text = match.group(1)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003794 (endline, endlinenum, endpos) = CloseExpression(
3795 clean_lines, linenum, len(match.group(1)))
3796 trailing_text = ''
3797 if endpos > -1:
3798 trailing_text = endline[endpos:]
Edward Lemur6d31ed52019-12-02 23:00:00 +00003799 for offset in range(endlinenum + 1,
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003800 min(endlinenum + 3, clean_lines.NumLines() - 1)):
3801 trailing_text += clean_lines.elided[offset]
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003802 # We also suppress warnings for `uint64_t{expression}` etc., as the style
3803 # guide recommends brace initialization for integral types to avoid
3804 # overflow/truncation.
3805 if (not Match(r'^[\s}]*[{.;,)<>\]:]', trailing_text)
3806 and not _IsType(clean_lines, nesting_state, leading_text)):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003807 error(filename, linenum, 'whitespace/braces', 5,
3808 'Missing space before {')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003809
3810 # Make sure '} else {' has spaces.
3811 if Search(r'}else', line):
3812 error(filename, linenum, 'whitespace/braces', 5,
3813 'Missing space before else')
3814
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003815 # You shouldn't have a space before a semicolon at the end of the line.
3816 # There's a special case for "for" since the style guide allows space before
3817 # the semicolon there.
3818 if Search(r':\s*;\s*$', line):
3819 error(filename, linenum, 'whitespace/semicolon', 5,
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003820 'Semicolon defining empty statement. Use {} instead.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003821 elif Search(r'^\s*;\s*$', line):
3822 error(filename, linenum, 'whitespace/semicolon', 5,
3823 'Line contains only semicolon. If this should be an empty statement, '
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003824 'use {} instead.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003825 elif (Search(r'\s+;\s*$', line) and
3826 not Search(r'\bfor\b', line)):
3827 error(filename, linenum, 'whitespace/semicolon', 5,
3828 'Extra space before last semicolon. If this should be an empty '
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003829 'statement, use {} instead.')
3830
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003831
3832def IsDecltype(clean_lines, linenum, column):
3833 """Check if the token ending on (linenum, column) is decltype().
3834
3835 Args:
3836 clean_lines: A CleansedLines instance containing the file.
3837 linenum: the number of the line to check.
3838 column: end column of the token to check.
3839 Returns:
3840 True if this token is decltype() expression, False otherwise.
3841 """
3842 (text, _, start_col) = ReverseCloseExpression(clean_lines, linenum, column)
3843 if start_col < 0:
3844 return False
3845 if Search(r'\bdecltype\s*$', text[0:start_col]):
3846 return True
3847 return False
3848
3849
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003850def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error):
3851 """Checks for additional blank line issues related to sections.
3852
3853 Currently the only thing checked here is blank line before protected/private.
3854
3855 Args:
3856 filename: The name of the current file.
3857 clean_lines: A CleansedLines instance containing the file.
3858 class_info: A _ClassInfo objects.
3859 linenum: The number of the line to check.
3860 error: The function to call with any errors found.
3861 """
3862 # Skip checks if the class is small, where small means 25 lines or less.
3863 # 25 lines seems like a good cutoff since that's the usual height of
3864 # terminals, and any class that can't fit in one screen can't really
3865 # be considered "small".
3866 #
3867 # Also skip checks if we are on the first line. This accounts for
3868 # classes that look like
3869 # class Foo { public: ... };
3870 #
3871 # If we didn't find the end of the class, last_line would be zero,
3872 # and the check will be skipped by the first condition.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003873 if (class_info.last_line - class_info.starting_linenum <= 24 or
3874 linenum <= class_info.starting_linenum):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003875 return
3876
3877 matched = Match(r'\s*(public|protected|private):', clean_lines.lines[linenum])
3878 if matched:
3879 # Issue warning if the line before public/protected/private was
3880 # not a blank line, but don't do this if the previous line contains
3881 # "class" or "struct". This can happen two ways:
3882 # - We are at the beginning of the class.
3883 # - We are forward-declaring an inner class that is semantically
3884 # private, but needed to be public for implementation reasons.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003885 # Also ignores cases where the previous line ends with a backslash as can be
3886 # common when defining classes in C macros.
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003887 prev_line = clean_lines.lines[linenum - 1]
3888 if (not IsBlankLine(prev_line) and
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003889 not Search(r'\b(class|struct)\b', prev_line) and
3890 not Search(r'\\$', prev_line)):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003891 # Try a bit harder to find the beginning of the class. This is to
3892 # account for multi-line base-specifier lists, e.g.:
3893 # class Derived
3894 # : public Base {
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00003895 end_class_head = class_info.starting_linenum
3896 for i in range(class_info.starting_linenum, linenum):
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00003897 if Search(r'\{\s*$', clean_lines.lines[i]):
3898 end_class_head = i
3899 break
3900 if end_class_head < linenum - 1:
3901 error(filename, linenum, 'whitespace/blank_line', 3,
3902 '"%s:" should be preceded by a blank line' % matched.group(1))
3903
3904
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003905def GetPreviousNonBlankLine(clean_lines, linenum):
3906 """Return the most recent non-blank line and its line number.
3907
3908 Args:
3909 clean_lines: A CleansedLines instance containing the file contents.
3910 linenum: The number of the line to check.
3911
3912 Returns:
3913 A tuple with two elements. The first element is the contents of the last
3914 non-blank line before the current line, or the empty string if this is the
3915 first non-blank line. The second is the line number of that line, or -1
3916 if this is the first non-blank line.
3917 """
3918
3919 prevlinenum = linenum - 1
3920 while prevlinenum >= 0:
3921 prevline = clean_lines.elided[prevlinenum]
3922 if not IsBlankLine(prevline): # if not a blank line...
3923 return (prevline, prevlinenum)
3924 prevlinenum -= 1
3925 return ('', -1)
3926
3927
3928def CheckBraces(filename, clean_lines, linenum, error):
3929 """Looks for misplaced braces (e.g. at the end of line).
3930
3931 Args:
3932 filename: The name of the current file.
3933 clean_lines: A CleansedLines instance containing the file.
3934 linenum: The number of the line to check.
3935 error: The function to call with any errors found.
3936 """
3937
3938 line = clean_lines.elided[linenum] # get rid of comments and strings
3939
3940 if Match(r'\s*{\s*$', line):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003941 # We allow an open brace to start a line in the case where someone is using
3942 # braces in a block to explicitly create a new scope, which is commonly used
3943 # to control the lifetime of stack-allocated variables. Braces are also
3944 # used for brace initializers inside function calls. We don't detect this
3945 # perfectly: we just don't complain if the last non-whitespace character on
3946 # the previous non-blank line is ',', ';', ':', '(', '{', or '}', or if the
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003947 # previous line starts a preprocessor block. We also allow a brace on the
3948 # following line if it is part of an array initialization and would not fit
3949 # within the 80 character limit of the preceding line.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003950 prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00003951 if (not Search(r'[,;:}{(]\s*$', prevline) and
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00003952 not Match(r'\s*#', prevline) and
3953 not (GetLineWidth(prevline) > _line_length - 2 and '[]' in prevline)):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003954 error(filename, linenum, 'whitespace/braces', 4,
3955 '{ should almost always be at the end of the previous line')
3956
3957 # An else clause should be on the same line as the preceding closing brace.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003958 if Match(r'\s*else\b\s*(?:if\b|\{|$)', line):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003959 prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
3960 if Match(r'\s*}\s*$', prevline):
3961 error(filename, linenum, 'whitespace/newline', 4,
3962 'An else should appear on the same line as the preceding }')
3963
3964 # If braces come on one side of an else, they should be on both.
3965 # However, we have to worry about "else if" that spans multiple lines!
Darius Maa7d7e42022-05-13 14:54:21 +00003966 if Search(r'else if\s*(?:constexpr\s*)?\(', line): # could be multi-line if
3967 brace_on_left = bool(Search(r'}\s*else if\s*(?:constexpr\s*)?\(', line))
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003968 # find the ( after the if
3969 pos = line.find('else if')
3970 pos = line.find('(', pos)
3971 if pos > 0:
3972 (endline, _, endpos) = CloseExpression(clean_lines, linenum, pos)
3973 brace_on_right = endline[endpos:].find('{') != -1
3974 if brace_on_left != brace_on_right: # must be brace after if
3975 error(filename, linenum, 'readability/braces', 5,
3976 'If an else has a brace on one side, it should have it on both')
3977 elif Search(r'}\s*else[^{]*$', line) or Match(r'[^}]*else\s*{', line):
3978 error(filename, linenum, 'readability/braces', 5,
3979 'If an else has a brace on one side, it should have it on both')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00003980
3981 # Likewise, an else should never have the else clause on the same line
3982 if Search(r'\belse [^\s{]', line) and not Search(r'\belse if\b', line):
3983 error(filename, linenum, 'whitespace/newline', 4,
3984 'Else clause should never be on same line as else (use 2 lines)')
3985
3986 # In the same way, a do/while should never be on one line
3987 if Match(r'\s*do [^\s{]', line):
3988 error(filename, linenum, 'whitespace/newline', 4,
3989 'do/while clauses should not be on a single line')
3990
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003991 # Check single-line if/else bodies. The style guide says 'curly braces are not
3992 # required for single-line statements'. We additionally allow multi-line,
3993 # single statements, but we reject anything with more than one semicolon in
3994 # it. This means that the first semicolon after the if should be at the end of
3995 # its line, and the line after that should have an indent level equal to or
3996 # lower than the if. We also check for ambiguous if/else nesting without
3997 # braces.
Darius Maa7d7e42022-05-13 14:54:21 +00003998 if_else_match = Search(r'\b(if\s*(?:constexpr\s*)?\(|else\b)', line)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00003999 if if_else_match and not Match(r'\s*#', line):
4000 if_indent = GetIndentLevel(line)
4001 endline, endlinenum, endpos = line, linenum, if_else_match.end()
Darius Maa7d7e42022-05-13 14:54:21 +00004002 if_match = Search(r'\bif\s*(?:constexpr\s*)?\(', line)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004003 if if_match:
4004 # This could be a multiline if condition, so find the end first.
4005 pos = if_match.end() - 1
4006 (endline, endlinenum, endpos) = CloseExpression(clean_lines, linenum, pos)
4007 # Check for an opening brace, either directly after the if or on the next
4008 # line. If found, this isn't a single-statement conditional.
4009 if (not Match(r'\s*{', endline[endpos:])
4010 and not (Match(r'\s*$', endline[endpos:])
4011 and endlinenum < (len(clean_lines.elided) - 1)
4012 and Match(r'\s*{', clean_lines.elided[endlinenum + 1]))):
4013 while (endlinenum < len(clean_lines.elided)
4014 and ';' not in clean_lines.elided[endlinenum][endpos:]):
4015 endlinenum += 1
4016 endpos = 0
4017 if endlinenum < len(clean_lines.elided):
4018 endline = clean_lines.elided[endlinenum]
4019 # We allow a mix of whitespace and closing braces (e.g. for one-liner
4020 # methods) and a single \ after the semicolon (for macros)
4021 endpos = endline.find(';')
4022 if not Match(r';[\s}]*(\\?)$', endline[endpos:]):
avakulenko@google.com59146752014-08-11 20:20:55 +00004023 # Semicolon isn't the last character, there's something trailing.
4024 # Output a warning if the semicolon is not contained inside
4025 # a lambda expression.
4026 if not Match(r'^[^{};]*\[[^\[\]]*\][^{}]*\{[^{}]*\}\s*\)*[;,]\s*$',
4027 endline):
4028 error(filename, linenum, 'readability/braces', 4,
4029 'If/else bodies with multiple statements require braces')
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004030 elif endlinenum < len(clean_lines.elided) - 1:
4031 # Make sure the next line is dedented
4032 next_line = clean_lines.elided[endlinenum + 1]
4033 next_indent = GetIndentLevel(next_line)
4034 # With ambiguous nested if statements, this will error out on the
4035 # if that *doesn't* match the else, regardless of whether it's the
4036 # inner one or outer one.
4037 if (if_match and Match(r'\s*else\b', next_line)
4038 and next_indent != if_indent):
4039 error(filename, linenum, 'readability/braces', 4,
4040 'Else clause should be indented at the same level as if. '
4041 'Ambiguous nested if/else chains require braces.')
4042 elif next_indent > if_indent:
4043 error(filename, linenum, 'readability/braces', 4,
4044 'If/else bodies with multiple statements require braces')
4045
4046
4047def CheckTrailingSemicolon(filename, clean_lines, linenum, error):
4048 """Looks for redundant trailing semicolon.
4049
4050 Args:
4051 filename: The name of the current file.
4052 clean_lines: A CleansedLines instance containing the file.
4053 linenum: The number of the line to check.
4054 error: The function to call with any errors found.
4055 """
4056
4057 line = clean_lines.elided[linenum]
4058
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004059 # Block bodies should not be followed by a semicolon. Due to C++11
Peter Kasting00741582023-02-16 20:09:51 +00004060 # brace initialization and C++20 concepts, there are more places
4061 # where semicolons are required than not. Places that are
4062 # recognized as true positives are listed below.
4063 #
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004064 # 1. Some flavor of block following closing parenthesis:
4065 # for (;;) {};
4066 # while (...) {};
4067 # switch (...) {};
4068 # Function(...) {};
4069 # if (...) {};
4070 # if (...) else if (...) {};
4071 #
4072 # 2. else block:
4073 # if (...) else {};
4074 #
4075 # 3. const member function:
4076 # Function(...) const {};
4077 #
4078 # 4. Block following some statement:
4079 # x = 42;
4080 # {};
4081 #
4082 # 5. Block at the beginning of a function:
4083 # Function(...) {
4084 # {};
4085 # }
4086 #
4087 # Note that naively checking for the preceding "{" will also match
4088 # braces inside multi-dimensional arrays, but this is fine since
4089 # that expression will not contain semicolons.
4090 #
4091 # 6. Block following another block:
4092 # while (true) {}
4093 # {};
4094 #
4095 # 7. End of namespaces:
4096 # namespace {};
4097 #
4098 # These semicolons seems far more common than other kinds of
4099 # redundant semicolons, possibly due to people converting classes
4100 # to namespaces. For now we do not warn for this case.
4101 #
4102 # Try matching case 1 first.
4103 match = Match(r'^(.*\)\s*)\{', line)
4104 if match:
4105 # Matched closing parenthesis (case 1). Check the token before the
4106 # matching opening parenthesis, and don't warn if it looks like a
4107 # macro. This avoids these false positives:
4108 # - macro that defines a base class
4109 # - multi-line macro that defines a base class
4110 # - macro that defines the whole class-head
4111 #
4112 # But we still issue warnings for macros that we know are safe to
4113 # warn, specifically:
4114 # - TEST, TEST_F, TEST_P, MATCHER, MATCHER_P
4115 # - TYPED_TEST
4116 # - INTERFACE_DEF
4117 # - EXCLUSIVE_LOCKS_REQUIRED, SHARED_LOCKS_REQUIRED, LOCKS_EXCLUDED:
4118 #
Ayu Ishii09858612020-06-26 18:00:52 +00004119 # We implement an allowlist of safe macros instead of a blocklist of
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004120 # unsafe macros, even though the latter appears less frequently in
Ayu Ishii09858612020-06-26 18:00:52 +00004121 # google code and would have been easier to implement. This is because
4122 # the downside for getting the allowlist wrong means some extra
4123 # semicolons, while the downside for getting the blocklist wrong
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004124 # would result in compile errors.
4125 #
avakulenko@google.com255f2be2014-12-05 22:19:55 +00004126 # In addition to macros, we also don't want to warn on
4127 # - Compound literals
4128 # - Lambdas
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004129 # - alignas specifier with anonymous structs
4130 # - decltype
Peter Kasting00741582023-02-16 20:09:51 +00004131 # - Type casts with parentheses, e.g.: var = (Type){value};
4132 # - Return type casts with parentheses, e.g.: return (Type){value};
4133 # - Function pointers with initializer list, e.g.: int (*f)(){};
4134 # - Requires expression, e.g. C = requires(){};
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004135 closing_brace_pos = match.group(1).rfind(')')
4136 opening_parenthesis = ReverseCloseExpression(
4137 clean_lines, linenum, closing_brace_pos)
4138 if opening_parenthesis[2] > -1:
4139 line_prefix = opening_parenthesis[0][0:opening_parenthesis[2]]
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004140 macro = Search(r'\b([A-Z_][A-Z0-9_]*)\s*$', line_prefix)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004141 func = Match(r'^(.*\])\s*$', line_prefix)
Peter Kasting00741582023-02-16 20:09:51 +00004142 if ((macro and macro.group(1) not in
4143 ('TEST', 'TEST_F', 'MATCHER', 'MATCHER_P', 'TYPED_TEST',
4144 'EXCLUSIVE_LOCKS_REQUIRED', 'SHARED_LOCKS_REQUIRED',
4145 'LOCKS_EXCLUDED', 'INTERFACE_DEF'))
4146 or (func and not Search(r'\boperator\s*\[\s*\]', func.group(1)))
4147 or Search(r'\b(?:struct|union)\s+alignas\s*$', line_prefix)
4148 or Search(r'\b(decltype|requires)$', line_prefix)
4149 or Search(r'(?:\s+=|\breturn)\s*$', line_prefix)
4150 or (Match(r'^\s*$', line_prefix) and Search(
4151 r'(?:\s+=|\breturn)\s*$', clean_lines.elided[linenum - 1]))
4152 or Search(r'\(\*\w+\)$', line_prefix)):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004153 match = None
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004154 if (match and
4155 opening_parenthesis[1] > 1 and
4156 Search(r'\]\s*$', clean_lines.elided[opening_parenthesis[1] - 1])):
4157 # Multi-line lambda-expression
4158 match = None
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004159
4160 else:
4161 # Try matching cases 2-3.
4162 match = Match(r'^(.*(?:else|\)\s*const)\s*)\{', line)
4163 if not match:
4164 # Try matching cases 4-6. These are always matched on separate lines.
4165 #
4166 # Note that we can't simply concatenate the previous line to the
4167 # current line and do a single match, otherwise we may output
4168 # duplicate warnings for the blank line case:
4169 # if (cond) {
4170 # // blank line
4171 # }
4172 prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
4173 if prevline and Search(r'[;{}]\s*$', prevline):
4174 match = Match(r'^(\s*)\{', line)
4175
4176 # Check matching closing brace
4177 if match:
4178 (endline, endlinenum, endpos) = CloseExpression(
4179 clean_lines, linenum, len(match.group(1)))
4180 if endpos > -1 and Match(r'^\s*;', endline[endpos:]):
4181 # Current {} pair is eligible for semicolon check, and we have found
4182 # the redundant semicolon, output warning here.
4183 #
4184 # Note: because we are scanning forward for opening braces, and
4185 # outputting warnings for the matching closing brace, if there are
4186 # nested blocks with trailing semicolons, we will get the error
4187 # messages in reversed order.
4188 error(filename, endlinenum, 'readability/braces', 4,
4189 "You don't need a ; after a }")
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004190
4191
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004192def CheckEmptyBlockBody(filename, clean_lines, linenum, error):
4193 """Look for empty loop/conditional body with only a single semicolon.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004194
4195 Args:
4196 filename: The name of the current file.
4197 clean_lines: A CleansedLines instance containing the file.
4198 linenum: The number of the line to check.
4199 error: The function to call with any errors found.
4200 """
4201
4202 # Search for loop keywords at the beginning of the line. Because only
4203 # whitespaces are allowed before the keywords, this will also ignore most
4204 # do-while-loops, since those lines should start with closing brace.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004205 #
4206 # We also check "if" blocks here, since an empty conditional block
4207 # is likely an error.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004208 line = clean_lines.elided[linenum]
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004209 matched = Match(r'\s*(for|while|if)\s*\(', line)
4210 if matched:
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004211 # Find the end of the conditional expression.
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004212 (end_line, end_linenum, end_pos) = CloseExpression(
4213 clean_lines, linenum, line.find('('))
4214
4215 # Output warning if what follows the condition expression is a semicolon.
4216 # No warning for all other cases, including whitespace or newline, since we
4217 # have a separate check for semicolons preceded by whitespace.
4218 if end_pos >= 0 and Match(r';', end_line[end_pos:]):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004219 if matched.group(1) == 'if':
4220 error(filename, end_linenum, 'whitespace/empty_conditional_body', 5,
4221 'Empty conditional bodies should use {}')
4222 else:
4223 error(filename, end_linenum, 'whitespace/empty_loop_body', 5,
4224 'Empty loop bodies should use {} or continue')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004225
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004226 # Check for if statements that have completely empty bodies (no comments)
4227 # and no else clauses.
4228 if end_pos >= 0 and matched.group(1) == 'if':
4229 # Find the position of the opening { for the if statement.
4230 # Return without logging an error if it has no brackets.
4231 opening_linenum = end_linenum
4232 opening_line_fragment = end_line[end_pos:]
4233 # Loop until EOF or find anything that's not whitespace or opening {.
4234 while not Search(r'^\s*\{', opening_line_fragment):
4235 if Search(r'^(?!\s*$)', opening_line_fragment):
4236 # Conditional has no brackets.
4237 return
4238 opening_linenum += 1
4239 if opening_linenum == len(clean_lines.elided):
4240 # Couldn't find conditional's opening { or any code before EOF.
4241 return
4242 opening_line_fragment = clean_lines.elided[opening_linenum]
4243 # Set opening_line (opening_line_fragment may not be entire opening line).
4244 opening_line = clean_lines.elided[opening_linenum]
4245
4246 # Find the position of the closing }.
4247 opening_pos = opening_line_fragment.find('{')
4248 if opening_linenum == end_linenum:
4249 # We need to make opening_pos relative to the start of the entire line.
4250 opening_pos += end_pos
4251 (closing_line, closing_linenum, closing_pos) = CloseExpression(
4252 clean_lines, opening_linenum, opening_pos)
4253 if closing_pos < 0:
4254 return
4255
4256 # Now construct the body of the conditional. This consists of the portion
4257 # of the opening line after the {, all lines until the closing line,
4258 # and the portion of the closing line before the }.
4259 if (clean_lines.raw_lines[opening_linenum] !=
4260 CleanseComments(clean_lines.raw_lines[opening_linenum])):
4261 # Opening line ends with a comment, so conditional isn't empty.
4262 return
4263 if closing_linenum > opening_linenum:
4264 # Opening line after the {. Ignore comments here since we checked above.
4265 body = list(opening_line[opening_pos+1:])
4266 # All lines until closing line, excluding closing line, with comments.
4267 body.extend(clean_lines.raw_lines[opening_linenum+1:closing_linenum])
4268 # Closing line before the }. Won't (and can't) have comments.
4269 body.append(clean_lines.elided[closing_linenum][:closing_pos-1])
4270 body = '\n'.join(body)
4271 else:
4272 # If statement has brackets and fits on a single line.
4273 body = opening_line[opening_pos+1:closing_pos-1]
4274
4275 # Check if the body is empty
4276 if not _EMPTY_CONDITIONAL_BODY_PATTERN.search(body):
4277 return
4278 # The body is empty. Now make sure there's not an else clause.
4279 current_linenum = closing_linenum
4280 current_line_fragment = closing_line[closing_pos:]
4281 # Loop until EOF or find anything that's not whitespace or else clause.
4282 while Search(r'^\s*$|^(?=\s*else)', current_line_fragment):
4283 if Search(r'^(?=\s*else)', current_line_fragment):
4284 # Found an else clause, so don't log an error.
4285 return
4286 current_linenum += 1
4287 if current_linenum == len(clean_lines.elided):
4288 break
4289 current_line_fragment = clean_lines.elided[current_linenum]
4290
4291 # The body is empty and there's no else clause until EOF or other code.
4292 error(filename, end_linenum, 'whitespace/empty_if_body', 4,
4293 ('If statement had no body and no else clause'))
4294
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004295
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004296def FindCheckMacro(line):
4297 """Find a replaceable CHECK-like macro.
4298
4299 Args:
4300 line: line to search on.
4301 Returns:
4302 (macro name, start position), or (None, -1) if no replaceable
4303 macro is found.
4304 """
4305 for macro in _CHECK_MACROS:
4306 i = line.find(macro)
4307 if i >= 0:
4308 # Find opening parenthesis. Do a regular expression match here
4309 # to make sure that we are matching the expected CHECK macro, as
4310 # opposed to some other macro that happens to contain the CHECK
4311 # substring.
4312 matched = Match(r'^(.*\b' + macro + r'\s*)\(', line)
4313 if not matched:
4314 continue
4315 return (macro, len(matched.group(1)))
4316 return (None, -1)
4317
4318
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004319def CheckCheck(filename, clean_lines, linenum, error):
4320 """Checks the use of CHECK and EXPECT macros.
4321
4322 Args:
4323 filename: The name of the current file.
4324 clean_lines: A CleansedLines instance containing the file.
4325 linenum: The number of the line to check.
4326 error: The function to call with any errors found.
4327 """
4328
4329 # Decide the set of replacement macros that should be suggested
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004330 lines = clean_lines.elided
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004331 (check_macro, start_pos) = FindCheckMacro(lines[linenum])
4332 if not check_macro:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004333 return
4334
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004335 # Find end of the boolean expression by matching parentheses
4336 (last_line, end_line, end_pos) = CloseExpression(
4337 clean_lines, linenum, start_pos)
4338 if end_pos < 0:
4339 return
avakulenko@google.com59146752014-08-11 20:20:55 +00004340
4341 # If the check macro is followed by something other than a
4342 # semicolon, assume users will log their own custom error messages
4343 # and don't suggest any replacements.
4344 if not Match(r'\s*;', last_line[end_pos:]):
4345 return
4346
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004347 if linenum == end_line:
4348 expression = lines[linenum][start_pos + 1:end_pos - 1]
4349 else:
4350 expression = lines[linenum][start_pos + 1:]
Edward Lemur6d31ed52019-12-02 23:00:00 +00004351 for i in range(linenum + 1, end_line):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004352 expression += lines[i]
4353 expression += last_line[0:end_pos - 1]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004354
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004355 # Parse expression so that we can take parentheses into account.
4356 # This avoids false positives for inputs like "CHECK((a < 4) == b)",
4357 # which is not replaceable by CHECK_LE.
4358 lhs = ''
4359 rhs = ''
4360 operator = None
4361 while expression:
4362 matched = Match(r'^\s*(<<|<<=|>>|>>=|->\*|->|&&|\|\||'
4363 r'==|!=|>=|>|<=|<|\()(.*)$', expression)
4364 if matched:
4365 token = matched.group(1)
4366 if token == '(':
4367 # Parenthesized operand
4368 expression = matched.group(2)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004369 (end, _) = FindEndOfExpressionInLine(expression, 0, ['('])
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004370 if end < 0:
4371 return # Unmatched parenthesis
4372 lhs += '(' + expression[0:end]
4373 expression = expression[end:]
4374 elif token in ('&&', '||'):
4375 # Logical and/or operators. This means the expression
4376 # contains more than one term, for example:
4377 # CHECK(42 < a && a < b);
4378 #
4379 # These are not replaceable with CHECK_LE, so bail out early.
4380 return
4381 elif token in ('<<', '<<=', '>>', '>>=', '->*', '->'):
4382 # Non-relational operator
4383 lhs += token
4384 expression = matched.group(2)
4385 else:
4386 # Relational operator
4387 operator = token
4388 rhs = matched.group(2)
4389 break
4390 else:
4391 # Unparenthesized operand. Instead of appending to lhs one character
4392 # at a time, we do another regular expression match to consume several
4393 # characters at once if possible. Trivial benchmark shows that this
4394 # is more efficient when the operands are longer than a single
4395 # character, which is generally the case.
4396 matched = Match(r'^([^-=!<>()&|]+)(.*)$', expression)
4397 if not matched:
4398 matched = Match(r'^(\s*\S)(.*)$', expression)
4399 if not matched:
4400 break
4401 lhs += matched.group(1)
4402 expression = matched.group(2)
4403
4404 # Only apply checks if we got all parts of the boolean expression
4405 if not (lhs and operator and rhs):
4406 return
4407
4408 # Check that rhs do not contain logical operators. We already know
4409 # that lhs is fine since the loop above parses out && and ||.
4410 if rhs.find('&&') > -1 or rhs.find('||') > -1:
4411 return
4412
4413 # At least one of the operands must be a constant literal. This is
4414 # to avoid suggesting replacements for unprintable things like
4415 # CHECK(variable != iterator)
4416 #
4417 # The following pattern matches decimal, hex integers, strings, and
4418 # characters (in that order).
4419 lhs = lhs.strip()
4420 rhs = rhs.strip()
4421 match_constant = r'^([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')$'
4422 if Match(match_constant, lhs) or Match(match_constant, rhs):
4423 # Note: since we know both lhs and rhs, we can provide a more
4424 # descriptive error message like:
4425 # Consider using CHECK_EQ(x, 42) instead of CHECK(x == 42)
4426 # Instead of:
4427 # Consider using CHECK_EQ instead of CHECK(a == b)
4428 #
4429 # We are still keeping the less descriptive message because if lhs
4430 # or rhs gets long, the error message might become unreadable.
4431 error(filename, linenum, 'readability/check', 2,
4432 'Consider using %s instead of %s(a %s b)' % (
4433 _CHECK_REPLACEMENT[check_macro][operator],
4434 check_macro, operator))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004435
4436
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004437def CheckAltTokens(filename, clean_lines, linenum, error):
4438 """Check alternative keywords being used in boolean expressions.
4439
4440 Args:
4441 filename: The name of the current file.
4442 clean_lines: A CleansedLines instance containing the file.
4443 linenum: The number of the line to check.
4444 error: The function to call with any errors found.
4445 """
4446 line = clean_lines.elided[linenum]
4447
4448 # Avoid preprocessor lines
4449 if Match(r'^\s*#', line):
4450 return
4451
4452 # Last ditch effort to avoid multi-line comments. This will not help
4453 # if the comment started before the current line or ended after the
4454 # current line, but it catches most of the false positives. At least,
4455 # it provides a way to workaround this warning for people who use
4456 # multi-line comments in preprocessor macros.
4457 #
4458 # TODO(unknown): remove this once cpplint has better support for
4459 # multi-line comments.
4460 if line.find('/*') >= 0 or line.find('*/') >= 0:
4461 return
4462
4463 for match in _ALT_TOKEN_REPLACEMENT_PATTERN.finditer(line):
4464 error(filename, linenum, 'readability/alt_tokens', 2,
4465 'Use operator %s instead of %s' % (
4466 _ALT_TOKEN_REPLACEMENT[match.group(1)], match.group(1)))
4467
4468
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004469def GetLineWidth(line):
4470 """Determines the width of the line in column positions.
4471
4472 Args:
4473 line: A string, which may be a Unicode string.
4474
4475 Returns:
4476 The width of the line in column positions, accounting for Unicode
4477 combining characters and wide characters.
4478 """
Edward Lemur6d31ed52019-12-02 23:00:00 +00004479 if sys.version_info == 2 and isinstance(line, unicode):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004480 width = 0
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004481 for uc in unicodedata.normalize('NFC', line):
4482 if unicodedata.east_asian_width(uc) in ('W', 'F'):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004483 width += 2
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004484 elif not unicodedata.combining(uc):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004485 width += 1
4486 return width
4487 else:
4488 return len(line)
4489
4490
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004491def CheckStyle(filename, clean_lines, linenum, file_extension, nesting_state,
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004492 error):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004493 """Checks rules from the 'C++ style rules' section of cppguide.html.
4494
4495 Most of these rules are hard to test (naming, comment style), but we
4496 do what we can. In particular we check for 2-space indents, line lengths,
4497 tab usage, spaces inside code, etc.
4498
4499 Args:
4500 filename: The name of the current file.
4501 clean_lines: A CleansedLines instance containing the file.
4502 linenum: The number of the line to check.
4503 file_extension: The extension (without the dot) of the filename.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004504 nesting_state: A NestingState instance which maintains information about
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004505 the current stack of nested blocks being parsed.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004506 error: The function to call with any errors found.
4507 """
4508
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004509 # Don't use "elided" lines here, otherwise we can't check commented lines.
4510 # Don't want to use "raw" either, because we don't want to check inside C++11
4511 # raw strings,
4512 raw_lines = clean_lines.lines_without_raw_strings
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004513 line = raw_lines[linenum]
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004514 prev = raw_lines[linenum - 1] if linenum > 0 else ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004515
4516 if line.find('\t') != -1:
4517 error(filename, linenum, 'whitespace/tab', 1,
4518 'Tab found; better to use spaces')
4519
4520 # One or three blank spaces at the beginning of the line is weird; it's
4521 # hard to reconcile that with 2-space indents.
4522 # NOTE: here are the conditions rob pike used for his tests. Mine aren't
4523 # as sophisticated, but it may be worth becoming so: RLENGTH==initial_spaces
4524 # if(RLENGTH > 20) complain = 0;
4525 # if(match($0, " +(error|private|public|protected):")) complain = 0;
4526 # if(match(prev, "&& *$")) complain = 0;
4527 # if(match(prev, "\\|\\| *$")) complain = 0;
4528 # if(match(prev, "[\",=><] *$")) complain = 0;
4529 # if(match($0, " <<")) complain = 0;
4530 # if(match(prev, " +for \\(")) complain = 0;
4531 # if(prevodd && match(prevprev, " +for \\(")) complain = 0;
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004532 scope_or_label_pattern = r'\s*\w+\s*:\s*\\?$'
4533 classinfo = nesting_state.InnermostClass()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004534 initial_spaces = 0
4535 cleansed_line = clean_lines.elided[linenum]
4536 while initial_spaces < len(line) and line[initial_spaces] == ' ':
4537 initial_spaces += 1
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004538 # There are certain situations we allow one space, notably for
4539 # section labels, and also lines containing multi-line raw strings.
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004540 # We also don't check for lines that look like continuation lines
4541 # (of lines ending in double quotes, commas, equals, or angle brackets)
4542 # because the rules for how to indent those are non-trivial.
4543 if (not Search(r'[",=><] *$', prev) and
4544 (initial_spaces == 1 or initial_spaces == 3) and
4545 not Match(scope_or_label_pattern, cleansed_line) and
4546 not (clean_lines.raw_lines[linenum] != line and
4547 Match(r'^\s*""', line))):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004548 error(filename, linenum, 'whitespace/indent', 3,
4549 'Weird number of spaces at line-start. '
4550 'Are you using a 2-space indent?')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004551
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004552 if line and line[-1].isspace():
4553 error(filename, linenum, 'whitespace/end_of_line', 4,
4554 'Line ends in whitespace. Consider deleting these extra spaces.')
4555
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004556 # Check if the line is a header guard.
4557 is_header_guard = False
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00004558 if file_extension == 'h':
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004559 cppvar = GetHeaderGuardCPPVariable(filename)
4560 if (line.startswith('#ifndef %s' % cppvar) or
4561 line.startswith('#define %s' % cppvar) or
4562 line.startswith('#endif // %s' % cppvar)):
4563 is_header_guard = True
4564 # #include lines and header guards can be long, since there's no clean way to
4565 # split them.
erg@google.com6317a9c2009-06-25 00:28:19 +00004566 #
4567 # URLs can be long too. It's possible to split these, but it makes them
4568 # harder to cut&paste.
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004569 #
4570 # The "$Id:...$" comment may also get very long without it being the
4571 # developers fault.
erg@google.com6317a9c2009-06-25 00:28:19 +00004572 if (not line.startswith('#include') and not is_header_guard and
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004573 not Match(r'^\s*//.*http(s?)://\S*$', line) and
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004574 not Match(r'^\s*//\s*[^\s]*$', line) and
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004575 not Match(r'^// \$Id:.*#[0-9]+ \$$', line)):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004576 line_width = GetLineWidth(line)
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004577 if line_width > _line_length:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004578 error(filename, linenum, 'whitespace/line_length', 2,
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004579 'Lines should be <= %i characters long' % _line_length)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004580
4581 if (cleansed_line.count(';') > 1 and
4582 # for loops are allowed two ;'s (and may run over two lines).
4583 cleansed_line.find('for') == -1 and
4584 (GetPreviousNonBlankLine(clean_lines, linenum)[0].find('for') == -1 or
4585 GetPreviousNonBlankLine(clean_lines, linenum)[0].find(';') != -1) and
4586 # It's ok to have many commands in a switch case that fits in 1 line
4587 not ((cleansed_line.find('case ') != -1 or
4588 cleansed_line.find('default:') != -1) and
4589 cleansed_line.find('break;') != -1)):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004590 error(filename, linenum, 'whitespace/newline', 0,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004591 'More than one command on the same line')
4592
4593 # Some more style checks
4594 CheckBraces(filename, clean_lines, linenum, error)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004595 CheckTrailingSemicolon(filename, clean_lines, linenum, error)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004596 CheckEmptyBlockBody(filename, clean_lines, linenum, error)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004597 CheckSpacing(filename, clean_lines, linenum, nesting_state, error)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004598 CheckOperatorSpacing(filename, clean_lines, linenum, error)
4599 CheckParenthesisSpacing(filename, clean_lines, linenum, error)
4600 CheckCommaSpacing(filename, clean_lines, linenum, error)
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004601 CheckBracesSpacing(filename, clean_lines, linenum, nesting_state, error)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004602 CheckSpacingForFunctionCall(filename, clean_lines, linenum, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004603 CheckCheck(filename, clean_lines, linenum, error)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004604 CheckAltTokens(filename, clean_lines, linenum, error)
4605 classinfo = nesting_state.InnermostClass()
4606 if classinfo:
4607 CheckSectionSpacing(filename, clean_lines, classinfo, linenum, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004608
4609
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004610_RE_PATTERN_INCLUDE = re.compile(r'^\s*#\s*include\s*([<"])([^>"]*)[>"].*$')
4611# Matches the first component of a filename delimited by -s and _s. That is:
4612# _RE_FIRST_COMPONENT.match('foo').group(0) == 'foo'
4613# _RE_FIRST_COMPONENT.match('foo.cc').group(0) == 'foo'
4614# _RE_FIRST_COMPONENT.match('foo-bar_baz.cc').group(0) == 'foo'
4615# _RE_FIRST_COMPONENT.match('foo_bar-baz.cc').group(0) == 'foo'
4616_RE_FIRST_COMPONENT = re.compile(r'^[^-_.]+')
4617
4618
4619def _DropCommonSuffixes(filename):
4620 """Drops common suffixes like _test.cc or -inl.h from filename.
4621
4622 For example:
4623 >>> _DropCommonSuffixes('foo/foo-inl.h')
4624 'foo/foo'
4625 >>> _DropCommonSuffixes('foo/bar/foo.cc')
4626 'foo/bar/foo'
4627 >>> _DropCommonSuffixes('foo/foo_internal.h')
4628 'foo/foo'
4629 >>> _DropCommonSuffixes('foo/foo_unusualinternal.h')
4630 'foo/foo_unusualinternal'
4631
4632 Args:
4633 filename: The input filename.
4634
4635 Returns:
4636 The filename with the common suffix removed.
4637 """
4638 for suffix in ('test.cc', 'regtest.cc', 'unittest.cc',
4639 'inl.h', 'impl.h', 'internal.h'):
4640 if (filename.endswith(suffix) and len(filename) > len(suffix) and
4641 filename[-len(suffix) - 1] in ('-', '_')):
4642 return filename[:-len(suffix) - 1]
4643 return os.path.splitext(filename)[0]
4644
4645
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004646def _ClassifyInclude(fileinfo, include, is_system):
4647 """Figures out what kind of header 'include' is.
4648
4649 Args:
4650 fileinfo: The current file cpplint is running over. A FileInfo instance.
4651 include: The path to a #included file.
4652 is_system: True if the #include used <> rather than "".
4653
4654 Returns:
4655 One of the _XXX_HEADER constants.
4656
4657 For example:
4658 >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'stdio.h', True)
4659 _C_SYS_HEADER
4660 >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'string', True)
4661 _CPP_SYS_HEADER
4662 >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', False)
4663 _LIKELY_MY_HEADER
4664 >>> _ClassifyInclude(FileInfo('foo/foo_unknown_extension.cc'),
4665 ... 'bar/foo_other_ext.h', False)
4666 _POSSIBLE_MY_HEADER
4667 >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/bar.h', False)
4668 _OTHER_HEADER
4669 """
4670 # This is a list of all standard c++ header files, except
4671 # those already checked for above.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004672 is_cpp_h = include in _CPP_HEADERS
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004673
4674 if is_system:
4675 if is_cpp_h:
4676 return _CPP_SYS_HEADER
4677 else:
4678 return _C_SYS_HEADER
4679
4680 # If the target file and the include we're checking share a
4681 # basename when we drop common extensions, and the include
4682 # lives in . , then it's likely to be owned by the target file.
4683 target_dir, target_base = (
4684 os.path.split(_DropCommonSuffixes(fileinfo.RepositoryName())))
4685 include_dir, include_base = os.path.split(_DropCommonSuffixes(include))
4686 if target_base == include_base and (
4687 include_dir == target_dir or
4688 include_dir == os.path.normpath(target_dir + '/../public')):
4689 return _LIKELY_MY_HEADER
4690
4691 # If the target and include share some initial basename
4692 # component, it's possible the target is implementing the
4693 # include, so it's allowed to be first, but we'll never
4694 # complain if it's not there.
4695 target_first_component = _RE_FIRST_COMPONENT.match(target_base)
4696 include_first_component = _RE_FIRST_COMPONENT.match(include_base)
4697 if (target_first_component and include_first_component and
4698 target_first_component.group(0) ==
4699 include_first_component.group(0)):
4700 return _POSSIBLE_MY_HEADER
4701
4702 return _OTHER_HEADER
4703
4704
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004705
erg@google.com6317a9c2009-06-25 00:28:19 +00004706def CheckIncludeLine(filename, clean_lines, linenum, include_state, error):
4707 """Check rules that are applicable to #include lines.
4708
4709 Strings on #include lines are NOT removed from elided line, to make
4710 certain tasks easier. However, to prevent false positives, checks
4711 applicable to #include lines in CheckLanguage must be put here.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004712
4713 Args:
4714 filename: The name of the current file.
4715 clean_lines: A CleansedLines instance containing the file.
4716 linenum: The number of the line to check.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004717 include_state: An _IncludeState instance in which the headers are inserted.
4718 error: The function to call with any errors found.
4719 """
4720 fileinfo = FileInfo(filename)
erg@google.com6317a9c2009-06-25 00:28:19 +00004721 line = clean_lines.lines[linenum]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004722
4723 # "include" should use the new style "foo/bar.h" instead of just "bar.h"
avakulenko@google.com59146752014-08-11 20:20:55 +00004724 # Only do this check if the included header follows google naming
4725 # conventions. If not, assume that it's a 3rd party API that
4726 # requires special include conventions.
4727 #
4728 # We also make an exception for Lua headers, which follow google
4729 # naming convention but not the include convention.
4730 match = Match(r'#include\s*"([^/]+\.h)"', line)
4731 if match and not _THIRD_PARTY_HEADERS_PATTERN.match(match.group(1)):
Fletcher Woodruff11b34152020-04-23 21:21:40 +00004732 error(filename, linenum, 'build/include_directory', 4,
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004733 'Include the directory when naming .h files')
4734
4735 # we shouldn't include a file more than once. actually, there are a
4736 # handful of instances where doing so is okay, but in general it's
4737 # not.
erg@google.com6317a9c2009-06-25 00:28:19 +00004738 match = _RE_PATTERN_INCLUDE.search(line)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004739 if match:
4740 include = match.group(2)
4741 is_system = (match.group(1) == '<')
avakulenko@google.com59146752014-08-11 20:20:55 +00004742 duplicate_line = include_state.FindHeader(include)
4743 if duplicate_line >= 0:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004744 error(filename, linenum, 'build/include', 4,
4745 '"%s" already included at %s:%s' %
avakulenko@google.com59146752014-08-11 20:20:55 +00004746 (include, filename, duplicate_line))
avakulenko@google.com255f2be2014-12-05 22:19:55 +00004747 elif (include.endswith('.cc') and
4748 os.path.dirname(fileinfo.RepositoryName()) != os.path.dirname(include)):
4749 error(filename, linenum, 'build/include', 4,
4750 'Do not include .cc files from other packages')
avakulenko@google.com59146752014-08-11 20:20:55 +00004751 elif not _THIRD_PARTY_HEADERS_PATTERN.match(include):
4752 include_state.include_list[-1].append((include, linenum))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004753
4754 # We want to ensure that headers appear in the right order:
4755 # 1) for foo.cc, foo.h (preferred location)
4756 # 2) c system files
4757 # 3) cpp system files
4758 # 4) for foo.cc, foo.h (deprecated location)
4759 # 5) other google headers
4760 #
4761 # We classify each include statement as one of those 5 types
4762 # using a number of techniques. The include_state object keeps
4763 # track of the highest type seen, and complains if we see a
4764 # lower type after that.
4765 error_message = include_state.CheckNextIncludeOrder(
4766 _ClassifyInclude(fileinfo, include, is_system))
4767 if error_message:
4768 error(filename, linenum, 'build/include_order', 4,
4769 '%s. Should be: %s.h, c system, c++ system, other.' %
4770 (error_message, fileinfo.BaseName()))
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004771 canonical_include = include_state.CanonicalizeAlphabeticalOrder(include)
4772 if not include_state.IsInAlphabeticalOrder(
4773 clean_lines, linenum, canonical_include):
erg@google.com26970fa2009-11-17 18:07:32 +00004774 error(filename, linenum, 'build/include_alpha', 4,
4775 'Include "%s" not in alphabetical order' % include)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004776 include_state.SetLastHeader(canonical_include)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004777
erg@google.com6317a9c2009-06-25 00:28:19 +00004778
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004779
4780def _GetTextInside(text, start_pattern):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004781 r"""Retrieves all the text between matching open and close parentheses.
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004782
4783 Given a string of lines and a regular expression string, retrieve all the text
4784 following the expression and between opening punctuation symbols like
4785 (, [, or {, and the matching close-punctuation symbol. This properly nested
4786 occurrences of the punctuations, so for the text like
4787 printf(a(), b(c()));
4788 a call to _GetTextInside(text, r'printf\(') will return 'a(), b(c())'.
4789 start_pattern must match string having an open punctuation symbol at the end.
4790
4791 Args:
4792 text: The lines to extract text. Its comments and strings must be elided.
4793 It can be single line and can span multiple lines.
4794 start_pattern: The regexp string indicating where to start extracting
4795 the text.
4796 Returns:
4797 The extracted text.
4798 None if either the opening string or ending punctuation could not be found.
4799 """
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004800 # TODO(unknown): Audit cpplint.py to see what places could be profitably
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004801 # rewritten to use _GetTextInside (and use inferior regexp matching today).
4802
4803 # Give opening punctuations to get the matching close-punctuations.
4804 matching_punctuation = {'(': ')', '{': '}', '[': ']'}
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +00004805 closing_punctuation = set(matching_punctuation.values())
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004806
4807 # Find the position to start extracting text.
4808 match = re.search(start_pattern, text, re.M)
4809 if not match: # start_pattern not found in text.
4810 return None
4811 start_position = match.end(0)
4812
4813 assert start_position > 0, (
4814 'start_pattern must ends with an opening punctuation.')
4815 assert text[start_position - 1] in matching_punctuation, (
4816 'start_pattern must ends with an opening punctuation.')
4817 # Stack of closing punctuations we expect to have in text after position.
4818 punctuation_stack = [matching_punctuation[text[start_position - 1]]]
4819 position = start_position
4820 while punctuation_stack and position < len(text):
4821 if text[position] == punctuation_stack[-1]:
4822 punctuation_stack.pop()
4823 elif text[position] in closing_punctuation:
4824 # A closing punctuation without matching opening punctuations.
4825 return None
4826 elif text[position] in matching_punctuation:
4827 punctuation_stack.append(matching_punctuation[text[position]])
4828 position += 1
4829 if punctuation_stack:
4830 # Opening punctuations left without matching close-punctuations.
4831 return None
4832 # punctuations match.
4833 return text[start_position:position - 1]
4834
4835
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004836# Patterns for matching call-by-reference parameters.
4837#
4838# Supports nested templates up to 2 levels deep using this messy pattern:
4839# < (?: < (?: < [^<>]*
4840# >
4841# | [^<>] )*
4842# >
4843# | [^<>] )*
4844# >
4845_RE_PATTERN_IDENT = r'[_a-zA-Z]\w*' # =~ [[:alpha:]][[:alnum:]]*
4846_RE_PATTERN_TYPE = (
4847 r'(?:const\s+)?(?:typename\s+|class\s+|struct\s+|union\s+|enum\s+)?'
4848 r'(?:\w|'
4849 r'\s*<(?:<(?:<[^<>]*>|[^<>])*>|[^<>])*>|'
4850 r'::)+')
4851# A call-by-reference parameter ends with '& identifier'.
4852_RE_PATTERN_REF_PARAM = re.compile(
4853 r'(' + _RE_PATTERN_TYPE + r'(?:\s*(?:\bconst\b|[*]))*\s*'
4854 r'&\s*' + _RE_PATTERN_IDENT + r')\s*(?:=[^,()]+)?[,)]')
4855# A call-by-const-reference parameter either ends with 'const& identifier'
4856# or looks like 'const type& identifier' when 'type' is atomic.
4857_RE_PATTERN_CONST_REF_PARAM = (
4858 r'(?:.*\s*\bconst\s*&\s*' + _RE_PATTERN_IDENT +
4859 r'|const\s+' + _RE_PATTERN_TYPE + r'\s*&\s*' + _RE_PATTERN_IDENT + r')')
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00004860# Stream types.
4861_RE_PATTERN_REF_STREAM_PARAM = (
4862 r'(?:.*stream\s*&\s*' + _RE_PATTERN_IDENT + r')')
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004863
4864
4865def CheckLanguage(filename, clean_lines, linenum, file_extension,
4866 include_state, nesting_state, error):
erg@google.com6317a9c2009-06-25 00:28:19 +00004867 """Checks rules from the 'C++ language rules' section of cppguide.html.
4868
4869 Some of these rules are hard to test (function overloading, using
4870 uint32 inappropriately), but we do the best we can.
4871
4872 Args:
4873 filename: The name of the current file.
4874 clean_lines: A CleansedLines instance containing the file.
4875 linenum: The number of the line to check.
4876 file_extension: The extension (without the dot) of the filename.
4877 include_state: An _IncludeState instance in which the headers are inserted.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004878 nesting_state: A NestingState instance which maintains information about
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004879 the current stack of nested blocks being parsed.
erg@google.com6317a9c2009-06-25 00:28:19 +00004880 error: The function to call with any errors found.
4881 """
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004882 # If the line is empty or consists of entirely a comment, no need to
4883 # check it.
4884 line = clean_lines.elided[linenum]
4885 if not line:
4886 return
4887
erg@google.com6317a9c2009-06-25 00:28:19 +00004888 match = _RE_PATTERN_INCLUDE.search(line)
4889 if match:
4890 CheckIncludeLine(filename, clean_lines, linenum, include_state, error)
4891 return
4892
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00004893 # Reset include state across preprocessor directives. This is meant
4894 # to silence warnings for conditional includes.
avakulenko@google.com59146752014-08-11 20:20:55 +00004895 match = Match(r'^\s*#\s*(if|ifdef|ifndef|elif|else|endif)\b', line)
4896 if match:
4897 include_state.ResetSection(match.group(1))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004898
4899 # Make Windows paths like Unix.
4900 fullname = os.path.abspath(filename).replace('\\', '/')
skym@chromium.org3990c412016-02-05 20:55:12 +00004901
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004902 # Perform other checks now that we are sure that this is not an include line
4903 CheckCasts(filename, clean_lines, linenum, error)
4904 CheckGlobalStatic(filename, clean_lines, linenum, error)
4905 CheckPrintf(filename, clean_lines, linenum, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004906
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00004907 if file_extension == 'h':
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004908 # TODO(unknown): check that 1-arg constructors are explicit.
4909 # How to tell it's a constructor?
4910 # (handled in CheckForNonStandardConstructs for now)
avakulenko@google.com59146752014-08-11 20:20:55 +00004911 # TODO(unknown): check that classes declare or disable copy/assign
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004912 # (level 1 error)
4913 pass
4914
4915 # Check if people are using the verboten C basic types. The only exception
4916 # we regularly allow is "unsigned short port" for port.
4917 if Search(r'\bshort port\b', line):
4918 if not Search(r'\bunsigned short port\b', line):
4919 error(filename, linenum, 'runtime/int', 4,
4920 'Use "unsigned short" for ports, not "short"')
4921 else:
4922 match = Search(r'\b(short|long(?! +double)|long long)\b', line)
4923 if match:
4924 error(filename, linenum, 'runtime/int', 4,
4925 'Use int16/int64/etc, rather than the C type %s' % match.group(1))
4926
erg@google.com26970fa2009-11-17 18:07:32 +00004927 # Check if some verboten operator overloading is going on
4928 # TODO(unknown): catch out-of-line unary operator&:
4929 # class X {};
4930 # int operator&(const X& x) { return 42; } // unary operator&
4931 # The trick is it's hard to tell apart from binary operator&:
4932 # class Y { int operator&(const Y& x) { return 23; } }; // binary operator&
4933 if Search(r'\boperator\s*&\s*\(\s*\)', line):
4934 error(filename, linenum, 'runtime/operator', 4,
4935 'Unary operator& is dangerous. Do not use it.')
4936
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004937 # Check for suspicious usage of "if" like
4938 # } if (a == b) {
Darius Maa7d7e42022-05-13 14:54:21 +00004939 if Search(r'\}\s*if\s*(?:constexpr\s*)?\(', line):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004940 error(filename, linenum, 'readability/braces', 4,
4941 'Did you mean "else if"? If not, start a new line for "if".')
4942
4943 # Check for potential format string bugs like printf(foo).
4944 # We constrain the pattern not to pick things like DocidForPrintf(foo).
4945 # Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str())
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00004946 # TODO(unknown): Catch the following case. Need to change the calling
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004947 # convention of the whole function to process multiple line to handle it.
4948 # printf(
4949 # boy_this_is_a_really_long_variable_that_cannot_fit_on_the_prev_line);
4950 printf_args = _GetTextInside(line, r'(?i)\b(string)?printf\s*\(')
4951 if printf_args:
4952 match = Match(r'([\w.\->()]+)$', printf_args)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00004953 if match and match.group(1) != '__VA_ARGS__':
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00004954 function_name = re.search(r'\b((?:string)?printf)\s*\(',
4955 line, re.I).group(1)
4956 error(filename, linenum, 'runtime/printf', 4,
4957 'Potential format string bug. Do %s("%%s", %s) instead.'
4958 % (function_name, match.group(1)))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004959
4960 # Check for potential memset bugs like memset(buf, sizeof(buf), 0).
4961 match = Search(r'memset\s*\(([^,]*),\s*([^,]*),\s*0\s*\)', line)
4962 if match and not Match(r"^''|-?[0-9]+|0x[0-9A-Fa-f]$", match.group(2)):
4963 error(filename, linenum, 'runtime/memset', 4,
4964 'Did you mean "memset(%s, 0, %s)"?'
4965 % (match.group(1), match.group(2)))
4966
4967 if Search(r'\busing namespace\b', line):
4968 error(filename, linenum, 'build/namespaces', 5,
4969 'Do not use namespace using-directives. '
4970 'Use using-declarations instead.')
4971
4972 # Detect variable-length arrays.
4973 match = Match(r'\s*(.+::)?(\w+) [a-z]\w*\[(.+)];', line)
4974 if (match and match.group(2) != 'return' and match.group(2) != 'delete' and
4975 match.group(3).find(']') == -1):
4976 # Split the size using space and arithmetic operators as delimiters.
4977 # If any of the resulting tokens are not compile time constants then
4978 # report the error.
4979 tokens = re.split(r'\s|\+|\-|\*|\/|<<|>>]', match.group(3))
4980 is_const = True
4981 skip_next = False
4982 for tok in tokens:
4983 if skip_next:
4984 skip_next = False
4985 continue
4986
4987 if Search(r'sizeof\(.+\)', tok): continue
4988 if Search(r'arraysize\(\w+\)', tok): continue
Avi Drissman4157ba12019-01-09 14:18:07 +00004989 if Search(r'base::size\(.+\)', tok): continue
4990 if Search(r'std::size\(.+\)', tok): continue
4991 if Search(r'std::extent<.+>', tok): continue
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00004992
4993 tok = tok.lstrip('(')
4994 tok = tok.rstrip(')')
4995 if not tok: continue
4996 if Match(r'\d+', tok): continue
4997 if Match(r'0[xX][0-9a-fA-F]+', tok): continue
4998 if Match(r'k[A-Z0-9]\w*', tok): continue
4999 if Match(r'(.+::)?k[A-Z0-9]\w*', tok): continue
5000 if Match(r'(.+::)?[A-Z][A-Z0-9_]*', tok): continue
5001 # A catch all for tricky sizeof cases, including 'sizeof expression',
5002 # 'sizeof(*type)', 'sizeof(const type)', 'sizeof(struct StructName)'
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005003 # requires skipping the next token because we split on ' ' and '*'.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005004 if tok.startswith('sizeof'):
5005 skip_next = True
5006 continue
5007 is_const = False
5008 break
5009 if not is_const:
5010 error(filename, linenum, 'runtime/arrays', 1,
5011 'Do not use variable-length arrays. Use an appropriately named '
5012 "('k' followed by CamelCase) compile-time constant for the size.")
5013
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005014 # Check for use of unnamed namespaces in header files. Registration
5015 # macros are typically OK, so we allow use of "namespace {" on lines
5016 # that end with backslashes.
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00005017 if (file_extension == 'h'
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005018 and Search(r'\bnamespace\s*{', line)
5019 and line[-1] != '\\'):
5020 error(filename, linenum, 'build/namespaces', 4,
5021 'Do not use unnamed namespaces in header files. See '
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00005022 'https://google.github.io/styleguide/cppguide.html#Namespaces'
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005023 ' for more information.')
5024
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005025
5026def CheckGlobalStatic(filename, clean_lines, linenum, error):
5027 """Check for unsafe global or static objects.
5028
5029 Args:
5030 filename: The name of the current file.
5031 clean_lines: A CleansedLines instance containing the file.
5032 linenum: The number of the line to check.
5033 error: The function to call with any errors found.
5034 """
5035 line = clean_lines.elided[linenum]
5036
avakulenko@google.com59146752014-08-11 20:20:55 +00005037 # Match two lines at a time to support multiline declarations
5038 if linenum + 1 < clean_lines.NumLines() and not Search(r'[;({]', line):
5039 line += clean_lines.elided[linenum + 1].strip()
5040
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005041 # Check for people declaring static/global STL strings at the top level.
5042 # This is dangerous because the C++ language does not guarantee that
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005043 # globals with constructors are initialized before the first access, and
5044 # also because globals can be destroyed when some threads are still running.
5045 # TODO(unknown): Generalize this to also find static unique_ptr instances.
5046 # TODO(unknown): File bugs for clang-tidy to find these.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005047 match = Match(
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005048 r'((?:|static +)(?:|const +))(?::*std::)?string( +const)? +'
5049 r'([a-zA-Z0-9_:]+)\b(.*)',
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005050 line)
avakulenko@google.com59146752014-08-11 20:20:55 +00005051
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005052 # Remove false positives:
5053 # - String pointers (as opposed to values).
5054 # string *pointer
5055 # const string *pointer
5056 # string const *pointer
5057 # string *const pointer
5058 #
5059 # - Functions and template specializations.
5060 # string Function<Type>(...
5061 # string Class<Type>::Method(...
5062 #
5063 # - Operators. These are matched separately because operator names
5064 # cross non-word boundaries, and trying to match both operators
5065 # and functions at the same time would decrease accuracy of
5066 # matching identifiers.
5067 # string Class::operator*()
5068 if (match and
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005069 not Search(r'\bstring\b(\s+const)?\s*[\*\&]\s*(const\s+)?\w', line) and
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005070 not Search(r'\boperator\W', line) and
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005071 not Match(r'\s*(<.*>)?(::[a-zA-Z0-9_]+)*\s*\(([^"]|$)', match.group(4))):
5072 if Search(r'\bconst\b', line):
5073 error(filename, linenum, 'runtime/string', 4,
5074 'For a static/global string constant, use a C style string '
5075 'instead: "%schar%s %s[]".' %
5076 (match.group(1), match.group(2) or '', match.group(3)))
5077 else:
5078 error(filename, linenum, 'runtime/string', 4,
5079 'Static/global string variables are not permitted.')
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005080
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005081 if (Search(r'\b([A-Za-z0-9_]*_)\(\1\)', line) or
5082 Search(r'\b([A-Za-z0-9_]*_)\(CHECK_NOTNULL\(\1\)\)', line)):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005083 error(filename, linenum, 'runtime/init', 4,
5084 'You seem to be initializing a member variable with itself.')
5085
5086
5087def CheckPrintf(filename, clean_lines, linenum, error):
5088 """Check for printf related issues.
5089
5090 Args:
5091 filename: The name of the current file.
5092 clean_lines: A CleansedLines instance containing the file.
5093 linenum: The number of the line to check.
5094 error: The function to call with any errors found.
5095 """
5096 line = clean_lines.elided[linenum]
5097
5098 # When snprintf is used, the second argument shouldn't be a literal.
5099 match = Search(r'snprintf\s*\(([^,]*),\s*([0-9]*)\s*,', line)
5100 if match and match.group(2) != '0':
5101 # If 2nd arg is zero, snprintf is used to calculate size.
5102 error(filename, linenum, 'runtime/printf', 3,
5103 'If you can, use sizeof(%s) instead of %s as the 2nd arg '
5104 'to snprintf.' % (match.group(1), match.group(2)))
5105
5106 # Check if some verboten C functions are being used.
avakulenko@google.com59146752014-08-11 20:20:55 +00005107 if Search(r'\bsprintf\s*\(', line):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005108 error(filename, linenum, 'runtime/printf', 5,
5109 'Never use sprintf. Use snprintf instead.')
avakulenko@google.com59146752014-08-11 20:20:55 +00005110 match = Search(r'\b(strcpy|strcat)\s*\(', line)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005111 if match:
5112 error(filename, linenum, 'runtime/printf', 4,
5113 'Almost always, snprintf is better than %s' % match.group(1))
5114
5115
5116def IsDerivedFunction(clean_lines, linenum):
5117 """Check if current line contains an inherited function.
5118
5119 Args:
5120 clean_lines: A CleansedLines instance containing the file.
5121 linenum: The number of the line to check.
5122 Returns:
5123 True if current line contains a function with "override"
5124 virt-specifier.
5125 """
avakulenko@google.com59146752014-08-11 20:20:55 +00005126 # Scan back a few lines for start of current function
Edward Lemur6d31ed52019-12-02 23:00:00 +00005127 for i in range(linenum, max(-1, linenum - 10), -1):
avakulenko@google.com59146752014-08-11 20:20:55 +00005128 match = Match(r'^([^()]*\w+)\(', clean_lines.elided[i])
5129 if match:
5130 # Look for "override" after the matching closing parenthesis
5131 line, _, closing_paren = CloseExpression(
5132 clean_lines, i, len(match.group(1)))
5133 return (closing_paren >= 0 and
5134 Search(r'\boverride\b', line[closing_paren:]))
5135 return False
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005136
5137
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005138def IsOutOfLineMethodDefinition(clean_lines, linenum):
5139 """Check if current line contains an out-of-line method definition.
5140
5141 Args:
5142 clean_lines: A CleansedLines instance containing the file.
5143 linenum: The number of the line to check.
5144 Returns:
5145 True if current line contains an out-of-line method definition.
5146 """
5147 # Scan back a few lines for start of current function
Edward Lemur6d31ed52019-12-02 23:00:00 +00005148 for i in range(linenum, max(-1, linenum - 10), -1):
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005149 if Match(r'^([^()]*\w+)\(', clean_lines.elided[i]):
5150 return Match(r'^[^()]*\w+::\w+\(', clean_lines.elided[i]) is not None
5151 return False
5152
5153
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005154def IsInitializerList(clean_lines, linenum):
5155 """Check if current line is inside constructor initializer list.
5156
5157 Args:
5158 clean_lines: A CleansedLines instance containing the file.
5159 linenum: The number of the line to check.
5160 Returns:
5161 True if current line appears to be inside constructor initializer
5162 list, False otherwise.
5163 """
Edward Lemur6d31ed52019-12-02 23:00:00 +00005164 for i in range(linenum, 1, -1):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005165 line = clean_lines.elided[i]
5166 if i == linenum:
5167 remove_function_body = Match(r'^(.*)\{\s*$', line)
5168 if remove_function_body:
5169 line = remove_function_body.group(1)
5170
5171 if Search(r'\s:\s*\w+[({]', line):
5172 # A lone colon tend to indicate the start of a constructor
5173 # initializer list. It could also be a ternary operator, which
5174 # also tend to appear in constructor initializer lists as
5175 # opposed to parameter lists.
5176 return True
5177 if Search(r'\}\s*,\s*$', line):
5178 # A closing brace followed by a comma is probably the end of a
5179 # brace-initialized member in constructor initializer list.
5180 return True
5181 if Search(r'[{};]\s*$', line):
5182 # Found one of the following:
5183 # - A closing brace or semicolon, probably the end of the previous
5184 # function.
5185 # - An opening brace, probably the start of current class or namespace.
5186 #
5187 # Current line is probably not inside an initializer list since
5188 # we saw one of those things without seeing the starting colon.
5189 return False
5190
5191 # Got to the beginning of the file without seeing the start of
5192 # constructor initializer list.
5193 return False
5194
5195
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005196def CheckForNonConstReference(filename, clean_lines, linenum,
5197 nesting_state, error):
5198 """Check for non-const references.
5199
5200 Separate from CheckLanguage since it scans backwards from current
5201 line, instead of scanning forward.
5202
5203 Args:
5204 filename: The name of the current file.
5205 clean_lines: A CleansedLines instance containing the file.
5206 linenum: The number of the line to check.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005207 nesting_state: A NestingState instance which maintains information about
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005208 the current stack of nested blocks being parsed.
5209 error: The function to call with any errors found.
5210 """
5211 # Do nothing if there is no '&' on current line.
5212 line = clean_lines.elided[linenum]
5213 if '&' not in line:
5214 return
5215
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005216 # If a function is inherited, current function doesn't have much of
5217 # a choice, so any non-const references should not be blamed on
5218 # derived function.
5219 if IsDerivedFunction(clean_lines, linenum):
5220 return
5221
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005222 # Don't warn on out-of-line method definitions, as we would warn on the
5223 # in-line declaration, if it isn't marked with 'override'.
5224 if IsOutOfLineMethodDefinition(clean_lines, linenum):
5225 return
5226
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005227 # Long type names may be broken across multiple lines, usually in one
5228 # of these forms:
5229 # LongType
5230 # ::LongTypeContinued &identifier
5231 # LongType::
5232 # LongTypeContinued &identifier
5233 # LongType<
5234 # ...>::LongTypeContinued &identifier
5235 #
5236 # If we detected a type split across two lines, join the previous
5237 # line to current line so that we can match const references
5238 # accordingly.
5239 #
5240 # Note that this only scans back one line, since scanning back
5241 # arbitrary number of lines would be expensive. If you have a type
5242 # that spans more than 2 lines, please use a typedef.
5243 if linenum > 1:
5244 previous = None
5245 if Match(r'\s*::(?:[\w<>]|::)+\s*&\s*\S', line):
5246 # previous_line\n + ::current_line
5247 previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+[\w<>])\s*$',
5248 clean_lines.elided[linenum - 1])
5249 elif Match(r'\s*[a-zA-Z_]([\w<>]|::)+\s*&\s*\S', line):
5250 # previous_line::\n + current_line
5251 previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+::)\s*$',
5252 clean_lines.elided[linenum - 1])
5253 if previous:
5254 line = previous.group(1) + line.lstrip()
5255 else:
5256 # Check for templated parameter that is split across multiple lines
5257 endpos = line.rfind('>')
5258 if endpos > -1:
5259 (_, startline, startpos) = ReverseCloseExpression(
5260 clean_lines, linenum, endpos)
5261 if startpos > -1 and startline < linenum:
5262 # Found the matching < on an earlier line, collect all
5263 # pieces up to current line.
5264 line = ''
Edward Lemur6d31ed52019-12-02 23:00:00 +00005265 for i in range(startline, linenum + 1):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005266 line += clean_lines.elided[i].strip()
5267
5268 # Check for non-const references in function parameters. A single '&' may
5269 # found in the following places:
5270 # inside expression: binary & for bitwise AND
5271 # inside expression: unary & for taking the address of something
5272 # inside declarators: reference parameter
5273 # We will exclude the first two cases by checking that we are not inside a
5274 # function body, including one that was just introduced by a trailing '{'.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005275 # TODO(unknown): Doesn't account for 'catch(Exception& e)' [rare].
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005276 if (nesting_state.previous_stack_top and
5277 not (isinstance(nesting_state.previous_stack_top, _ClassInfo) or
5278 isinstance(nesting_state.previous_stack_top, _NamespaceInfo))):
5279 # Not at toplevel, not within a class, and not within a namespace
5280 return
5281
avakulenko@google.com59146752014-08-11 20:20:55 +00005282 # Avoid initializer lists. We only need to scan back from the
5283 # current line for something that starts with ':'.
5284 #
5285 # We don't need to check the current line, since the '&' would
5286 # appear inside the second set of parentheses on the current line as
5287 # opposed to the first set.
5288 if linenum > 0:
Edward Lemur6d31ed52019-12-02 23:00:00 +00005289 for i in range(linenum - 1, max(0, linenum - 10), -1):
avakulenko@google.com59146752014-08-11 20:20:55 +00005290 previous_line = clean_lines.elided[i]
5291 if not Search(r'[),]\s*$', previous_line):
5292 break
5293 if Match(r'^\s*:\s+\S', previous_line):
5294 return
5295
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005296 # Avoid preprocessors
5297 if Search(r'\\\s*$', line):
5298 return
5299
5300 # Avoid constructor initializer lists
5301 if IsInitializerList(clean_lines, linenum):
5302 return
5303
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005304 # We allow non-const references in a few standard places, like functions
5305 # called "swap()" or iostream operators like "<<" or ">>". Do not check
5306 # those function parameters.
5307 #
5308 # We also accept & in static_assert, which looks like a function but
5309 # it's actually a declaration expression.
Ayu Ishii09858612020-06-26 18:00:52 +00005310 allowlisted_functions = (r'(?:[sS]wap(?:<\w:+>)?|'
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005311 r'operator\s*[<>][<>]|'
5312 r'static_assert|COMPILE_ASSERT'
5313 r')\s*\(')
Ayu Ishii09858612020-06-26 18:00:52 +00005314 if Search(allowlisted_functions, line):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005315 return
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005316 elif not Search(r'\S+\([^)]*$', line):
Ayu Ishii09858612020-06-26 18:00:52 +00005317 # Don't see an allowlisted function on this line. Actually we
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005318 # didn't see any function name on this line, so this is likely a
5319 # multi-line parameter list. Try a bit harder to catch this case.
Edward Lemur6d31ed52019-12-02 23:00:00 +00005320 for i in range(2):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005321 if (linenum > i and
Ayu Ishii09858612020-06-26 18:00:52 +00005322 Search(allowlisted_functions, clean_lines.elided[linenum - i - 1])):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005323 return
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005324
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005325 decls = ReplaceAll(r'{[^}]*}', ' ', line) # exclude function body
5326 for parameter in re.findall(_RE_PATTERN_REF_PARAM, decls):
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005327 if (not Match(_RE_PATTERN_CONST_REF_PARAM, parameter) and
5328 not Match(_RE_PATTERN_REF_STREAM_PARAM, parameter)):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005329 error(filename, linenum, 'runtime/references', 2,
5330 'Is this a non-const reference? '
5331 'If so, make const or use a pointer: ' +
5332 ReplaceAll(' *<', '<', parameter))
5333
5334
5335def CheckCasts(filename, clean_lines, linenum, error):
5336 """Various cast related checks.
5337
5338 Args:
5339 filename: The name of the current file.
5340 clean_lines: A CleansedLines instance containing the file.
5341 linenum: The number of the line to check.
5342 error: The function to call with any errors found.
5343 """
5344 line = clean_lines.elided[linenum]
5345
5346 # Check to see if they're using an conversion function cast.
5347 # I just try to capture the most common basic types, though there are more.
5348 # Parameterless conversion functions, such as bool(), are allowed as they are
5349 # probably a member operator declaration or default constructor.
5350 match = Search(
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005351 r'(\bnew\s+(?:const\s+)?|\S<\s*(?:const\s+)?)?\b'
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005352 r'(int|float|double|bool|char|int32|uint32|int64|uint64)'
5353 r'(\([^)].*)', line)
5354 expecting_function = ExpectingFunctionArgs(clean_lines, linenum)
5355 if match and not expecting_function:
5356 matched_type = match.group(2)
5357
5358 # matched_new_or_template is used to silence two false positives:
5359 # - New operators
5360 # - Template arguments with function types
5361 #
5362 # For template arguments, we match on types immediately following
5363 # an opening bracket without any spaces. This is a fast way to
5364 # silence the common case where the function type is the first
5365 # template argument. False negative with less-than comparison is
5366 # avoided because those operators are usually followed by a space.
5367 #
5368 # function<double(double)> // bracket + no space = false positive
5369 # value < double(42) // bracket + space = true positive
5370 matched_new_or_template = match.group(1)
5371
avakulenko@google.com59146752014-08-11 20:20:55 +00005372 # Avoid arrays by looking for brackets that come after the closing
5373 # parenthesis.
5374 if Match(r'\([^()]+\)\s*\[', match.group(3)):
5375 return
5376
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005377 # Other things to ignore:
5378 # - Function pointers
5379 # - Casts to pointer types
5380 # - Placement new
5381 # - Alias declarations
5382 matched_funcptr = match.group(3)
5383 if (matched_new_or_template is None and
5384 not (matched_funcptr and
5385 (Match(r'\((?:[^() ]+::\s*\*\s*)?[^() ]+\)\s*\(',
5386 matched_funcptr) or
5387 matched_funcptr.startswith('(*)'))) and
5388 not Match(r'\s*using\s+\S+\s*=\s*' + matched_type, line) and
5389 not Search(r'new\(\S+\)\s*' + matched_type, line)):
5390 error(filename, linenum, 'readability/casting', 4,
5391 'Using deprecated casting style. '
5392 'Use static_cast<%s>(...) instead' %
5393 matched_type)
5394
5395 if not expecting_function:
avakulenko@google.com59146752014-08-11 20:20:55 +00005396 CheckCStyleCast(filename, clean_lines, linenum, 'static_cast',
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005397 r'\((int|float|double|bool|char|u?int(16|32|64))\)', error)
5398
5399 # This doesn't catch all cases. Consider (const char * const)"hello".
5400 #
5401 # (char *) "foo" should always be a const_cast (reinterpret_cast won't
5402 # compile).
avakulenko@google.com59146752014-08-11 20:20:55 +00005403 if CheckCStyleCast(filename, clean_lines, linenum, 'const_cast',
5404 r'\((char\s?\*+\s?)\)\s*"', error):
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005405 pass
5406 else:
5407 # Check pointer casts for other than string constants
avakulenko@google.com59146752014-08-11 20:20:55 +00005408 CheckCStyleCast(filename, clean_lines, linenum, 'reinterpret_cast',
5409 r'\((\w+\s?\*+\s?)\)', error)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005410
5411 # In addition, we look for people taking the address of a cast. This
5412 # is dangerous -- casts can assign to temporaries, so the pointer doesn't
5413 # point where you think.
avakulenko@google.com59146752014-08-11 20:20:55 +00005414 #
5415 # Some non-identifier character is required before the '&' for the
5416 # expression to be recognized as a cast. These are casts:
5417 # expression = &static_cast<int*>(temporary());
5418 # function(&(int*)(temporary()));
5419 #
5420 # This is not a cast:
5421 # reference_type&(int* function_param);
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005422 match = Search(
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005423 r'(?:[^\w]&\(([^)*][^)]*)\)[\w(])|'
avakulenko@google.com59146752014-08-11 20:20:55 +00005424 r'(?:[^\w]&(static|dynamic|down|reinterpret)_cast\b)', line)
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005425 if match:
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005426 # Try a better error message when the & is bound to something
5427 # dereferenced by the casted pointer, as opposed to the casted
5428 # pointer itself.
5429 parenthesis_error = False
5430 match = Match(r'^(.*&(?:static|dynamic|down|reinterpret)_cast\b)<', line)
5431 if match:
5432 _, y1, x1 = CloseExpression(clean_lines, linenum, len(match.group(1)))
5433 if x1 >= 0 and clean_lines.elided[y1][x1] == '(':
5434 _, y2, x2 = CloseExpression(clean_lines, y1, x1)
5435 if x2 >= 0:
5436 extended_line = clean_lines.elided[y2][x2:]
5437 if y2 < clean_lines.NumLines() - 1:
5438 extended_line += clean_lines.elided[y2 + 1]
5439 if Match(r'\s*(?:->|\[)', extended_line):
5440 parenthesis_error = True
5441
5442 if parenthesis_error:
5443 error(filename, linenum, 'readability/casting', 4,
5444 ('Are you taking an address of something dereferenced '
5445 'from a cast? Wrapping the dereferenced expression in '
5446 'parentheses will make the binding more obvious'))
5447 else:
5448 error(filename, linenum, 'runtime/casting', 4,
5449 ('Are you taking an address of a cast? '
5450 'This is dangerous: could be a temp var. '
5451 'Take the address before doing the cast, rather than after'))
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005452
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005453
avakulenko@google.com59146752014-08-11 20:20:55 +00005454def CheckCStyleCast(filename, clean_lines, linenum, cast_type, pattern, error):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005455 """Checks for a C-style cast by looking for the pattern.
5456
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005457 Args:
5458 filename: The name of the current file.
avakulenko@google.com59146752014-08-11 20:20:55 +00005459 clean_lines: A CleansedLines instance containing the file.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005460 linenum: The number of the line to check.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005461 cast_type: The string for the C++ cast to recommend. This is either
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005462 reinterpret_cast, static_cast, or const_cast, depending.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005463 pattern: The regular expression used to find C-style casts.
5464 error: The function to call with any errors found.
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005465
5466 Returns:
5467 True if an error was emitted.
5468 False otherwise.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005469 """
avakulenko@google.com59146752014-08-11 20:20:55 +00005470 line = clean_lines.elided[linenum]
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005471 match = Search(pattern, line)
5472 if not match:
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005473 return False
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005474
avakulenko@google.com59146752014-08-11 20:20:55 +00005475 # Exclude lines with keywords that tend to look like casts
5476 context = line[0:match.start(1) - 1]
5477 if Match(r'.*\b(?:sizeof|alignof|alignas|[_A-Z][_A-Z0-9]*)\s*$', context):
5478 return False
5479
5480 # Try expanding current context to see if we one level of
5481 # parentheses inside a macro.
5482 if linenum > 0:
Edward Lemur6d31ed52019-12-02 23:00:00 +00005483 for i in range(linenum - 1, max(0, linenum - 5), -1):
avakulenko@google.com59146752014-08-11 20:20:55 +00005484 context = clean_lines.elided[i] + context
5485 if Match(r'.*\b[_A-Z][_A-Z0-9]*\s*\((?:\([^()]*\)|[^()])*$', context):
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005486 return False
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005487
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005488 # operator++(int) and operator--(int)
avakulenko@google.com59146752014-08-11 20:20:55 +00005489 if context.endswith(' operator++') or context.endswith(' operator--'):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005490 return False
5491
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005492 # A single unnamed argument for a function tends to look like old style cast.
5493 # If we see those, don't issue warnings for deprecated casts.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005494 remainder = line[match.end(0):]
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005495 if Match(r'^\s*(?:;|const\b|throw\b|final\b|override\b|[=>{),]|->)',
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005496 remainder):
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005497 return False
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005498
5499 # At this point, all that should be left is actual casts.
5500 error(filename, linenum, 'readability/casting', 4,
5501 'Using C-style cast. Use %s<%s>(...) instead' %
5502 (cast_type, match.group(1)))
5503
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005504 return True
5505
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005506
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005507def ExpectingFunctionArgs(clean_lines, linenum):
5508 """Checks whether where function type arguments are expected.
5509
5510 Args:
5511 clean_lines: A CleansedLines instance containing the file.
5512 linenum: The number of the line to check.
5513
5514 Returns:
5515 True if the line at 'linenum' is inside something that expects arguments
5516 of function types.
5517 """
5518 line = clean_lines.elided[linenum]
Peter Kasting00741582023-02-16 20:09:51 +00005519 return (Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line)
5520 or _TYPE_TRAITS_RE.search(line)
5521 or (linenum >= 2 and
5522 (Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\((?:\S+,)?\s*$',
5523 clean_lines.elided[linenum - 1])
5524 or Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\(\s*$',
5525 clean_lines.elided[linenum - 2])
5526 or Search(r'\b(::function|base::FunctionRef)\s*\<\s*$',
5527 clean_lines.elided[linenum - 1]))))
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005528
5529
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005530_HEADERS_CONTAINING_TEMPLATES = (
5531 ('<deque>', ('deque',)),
5532 ('<functional>', ('unary_function', 'binary_function',
5533 'plus', 'minus', 'multiplies', 'divides', 'modulus',
5534 'negate',
5535 'equal_to', 'not_equal_to', 'greater', 'less',
5536 'greater_equal', 'less_equal',
5537 'logical_and', 'logical_or', 'logical_not',
5538 'unary_negate', 'not1', 'binary_negate', 'not2',
5539 'bind1st', 'bind2nd',
5540 'pointer_to_unary_function',
5541 'pointer_to_binary_function',
5542 'ptr_fun',
5543 'mem_fun_t', 'mem_fun', 'mem_fun1_t', 'mem_fun1_ref_t',
5544 'mem_fun_ref_t',
5545 'const_mem_fun_t', 'const_mem_fun1_t',
5546 'const_mem_fun_ref_t', 'const_mem_fun1_ref_t',
5547 'mem_fun_ref',
5548 )),
5549 ('<limits>', ('numeric_limits',)),
5550 ('<list>', ('list',)),
5551 ('<map>', ('map', 'multimap',)),
lhchavez2d1b6da2016-07-13 10:40:01 -07005552 ('<memory>', ('allocator', 'make_shared', 'make_unique', 'shared_ptr',
5553 'unique_ptr', 'weak_ptr')),
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005554 ('<queue>', ('queue', 'priority_queue',)),
5555 ('<set>', ('set', 'multiset',)),
5556 ('<stack>', ('stack',)),
5557 ('<string>', ('char_traits', 'basic_string',)),
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005558 ('<tuple>', ('tuple',)),
lhchavez2d1b6da2016-07-13 10:40:01 -07005559 ('<unordered_map>', ('unordered_map', 'unordered_multimap')),
5560 ('<unordered_set>', ('unordered_set', 'unordered_multiset')),
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005561 ('<utility>', ('pair',)),
5562 ('<vector>', ('vector',)),
5563
5564 # gcc extensions.
5565 # Note: std::hash is their hash, ::hash is our hash
5566 ('<hash_map>', ('hash_map', 'hash_multimap',)),
5567 ('<hash_set>', ('hash_set', 'hash_multiset',)),
5568 ('<slist>', ('slist',)),
5569 )
5570
skym@chromium.org3990c412016-02-05 20:55:12 +00005571_HEADERS_MAYBE_TEMPLATES = (
5572 ('<algorithm>', ('copy', 'max', 'min', 'min_element', 'sort',
5573 'transform',
5574 )),
lhchavez2d1b6da2016-07-13 10:40:01 -07005575 ('<utility>', ('forward', 'make_pair', 'move', 'swap')),
skym@chromium.org3990c412016-02-05 20:55:12 +00005576 )
5577
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005578_RE_PATTERN_STRING = re.compile(r'\bstring\b')
5579
skym@chromium.org3990c412016-02-05 20:55:12 +00005580_re_pattern_headers_maybe_templates = []
5581for _header, _templates in _HEADERS_MAYBE_TEMPLATES:
5582 for _template in _templates:
Peter Kasting03b187d2022-11-04 18:33:43 +00005583 # Match max<type>(..., ...), max(..., ...), but not foo->max or foo.max.
skym@chromium.org3990c412016-02-05 20:55:12 +00005584 _re_pattern_headers_maybe_templates.append(
Peter Kastinge6f3d662022-11-07 22:57:33 +00005585 (re.compile(r'(?<![>.])\b' + _template + r'(<.*?>)?\([^\)]'), _template,
Peter Kasting03b187d2022-11-04 18:33:43 +00005586 _header))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005587
skym@chromium.org3990c412016-02-05 20:55:12 +00005588# Other scripts may reach in and modify this pattern.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005589_re_pattern_templates = []
5590for _header, _templates in _HEADERS_CONTAINING_TEMPLATES:
5591 for _template in _templates:
5592 _re_pattern_templates.append(
5593 (re.compile(r'(\<|\b)' + _template + r'\s*\<'),
5594 _template + '<>',
5595 _header))
5596
5597
erg@google.com6317a9c2009-06-25 00:28:19 +00005598def FilesBelongToSameModule(filename_cc, filename_h):
5599 """Check if these two filenames belong to the same module.
5600
5601 The concept of a 'module' here is a as follows:
5602 foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the
5603 same 'module' if they are in the same directory.
5604 some/path/public/xyzzy and some/path/internal/xyzzy are also considered
5605 to belong to the same module here.
5606
5607 If the filename_cc contains a longer path than the filename_h, for example,
5608 '/absolute/path/to/base/sysinfo.cc', and this file would include
5609 'base/sysinfo.h', this function also produces the prefix needed to open the
5610 header. This is used by the caller of this function to more robustly open the
5611 header file. We don't have access to the real include paths in this context,
5612 so we need this guesswork here.
5613
5614 Known bugs: tools/base/bar.cc and base/bar.h belong to the same module
5615 according to this implementation. Because of this, this function gives
5616 some false positives. This should be sufficiently rare in practice.
5617
5618 Args:
5619 filename_cc: is the path for the .cc file
5620 filename_h: is the path for the header path
5621
5622 Returns:
5623 Tuple with a bool and a string:
5624 bool: True if filename_cc and filename_h belong to the same module.
5625 string: the additional prefix needed to open the header file.
5626 """
5627
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005628 fileinfo = FileInfo(filename_cc)
5629 if not fileinfo.IsSource():
erg@google.com6317a9c2009-06-25 00:28:19 +00005630 return (False, '')
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00005631 filename_cc = filename_cc[:-len(fileinfo.Extension())]
5632 matched_test_suffix = Search(_TEST_FILE_SUFFIX, fileinfo.BaseName())
5633 if matched_test_suffix:
5634 filename_cc = filename_cc[:-len(matched_test_suffix.group(1))]
erg@google.com6317a9c2009-06-25 00:28:19 +00005635 filename_cc = filename_cc.replace('/public/', '/')
5636 filename_cc = filename_cc.replace('/internal/', '/')
5637
5638 if not filename_h.endswith('.h'):
5639 return (False, '')
5640 filename_h = filename_h[:-len('.h')]
5641 if filename_h.endswith('-inl'):
5642 filename_h = filename_h[:-len('-inl')]
5643 filename_h = filename_h.replace('/public/', '/')
5644 filename_h = filename_h.replace('/internal/', '/')
5645
5646 files_belong_to_same_module = filename_cc.endswith(filename_h)
5647 common_path = ''
5648 if files_belong_to_same_module:
5649 common_path = filename_cc[:-len(filename_h)]
5650 return files_belong_to_same_module, common_path
5651
5652
avakulenko@google.com59146752014-08-11 20:20:55 +00005653def UpdateIncludeState(filename, include_dict, io=codecs):
5654 """Fill up the include_dict with new includes found from the file.
erg@google.com6317a9c2009-06-25 00:28:19 +00005655
5656 Args:
5657 filename: the name of the header to read.
avakulenko@google.com59146752014-08-11 20:20:55 +00005658 include_dict: a dictionary in which the headers are inserted.
erg@google.com6317a9c2009-06-25 00:28:19 +00005659 io: The io factory to use to read the file. Provided for testability.
5660
5661 Returns:
avakulenko@google.com59146752014-08-11 20:20:55 +00005662 True if a header was successfully added. False otherwise.
erg@google.com6317a9c2009-06-25 00:28:19 +00005663 """
5664 headerfile = None
5665 try:
5666 headerfile = io.open(filename, 'r', 'utf8', 'replace')
5667 except IOError:
5668 return False
5669 linenum = 0
5670 for line in headerfile:
5671 linenum += 1
5672 clean_line = CleanseComments(line)
5673 match = _RE_PATTERN_INCLUDE.search(clean_line)
5674 if match:
5675 include = match.group(2)
avakulenko@google.com59146752014-08-11 20:20:55 +00005676 include_dict.setdefault(include, linenum)
erg@google.com6317a9c2009-06-25 00:28:19 +00005677 return True
5678
5679
Peter Kasting03b187d2022-11-04 18:33:43 +00005680def UpdateRequiredHeadersForLine(patterns, line, linenum, required):
5681 for pattern, template, header in patterns:
5682 matched = pattern.search(line)
5683 if matched:
5684 # Don't warn about IWYU in non-STL namespaces:
5685 # (We check only the first match per line; good enough.)
5686 prefix = line[:matched.start()]
5687 if prefix.endswith('std::') or not prefix.endswith('::'):
5688 required[header] = (linenum, template)
5689 return required
5690
5691
erg@google.com6317a9c2009-06-25 00:28:19 +00005692def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error,
5693 io=codecs):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005694 """Reports for missing stl includes.
5695
5696 This function will output warnings to make sure you are including the headers
5697 necessary for the stl containers and functions that you use. We only give one
5698 reason to include a header. For example, if you use both equal_to<> and
5699 less<> in a .h file, only one (the latter in the file) of these will be
5700 reported as a reason to include the <functional>.
5701
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005702 Args:
5703 filename: The name of the current file.
5704 clean_lines: A CleansedLines instance containing the file.
5705 include_state: An _IncludeState instance.
5706 error: The function to call with any errors found.
erg@google.com6317a9c2009-06-25 00:28:19 +00005707 io: The IO factory to use to read the header file. Provided for unittest
5708 injection.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005709 """
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +00005710 # A map of header name to linenumber and the template entity.
5711 # Example of required: { '<functional>': (1219, 'less<>') }
5712 required = {}
Edward Lemur6d31ed52019-12-02 23:00:00 +00005713 for linenum in range(clean_lines.NumLines()):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005714 line = clean_lines.elided[linenum]
5715 if not line or line[0] == '#':
5716 continue
5717
5718 # String is special -- it is a non-templatized type in STL.
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005719 matched = _RE_PATTERN_STRING.search(line)
5720 if matched:
erg@google.com35589e62010-11-17 18:58:16 +00005721 # Don't warn about strings in non-STL namespaces:
5722 # (We check only the first match per line; good enough.)
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005723 prefix = line[:matched.start()]
erg@google.com35589e62010-11-17 18:58:16 +00005724 if prefix.endswith('std::') or not prefix.endswith('::'):
5725 required['<string>'] = (linenum, 'string')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005726
Peter Kasting03b187d2022-11-04 18:33:43 +00005727 required = UpdateRequiredHeadersForLine(_re_pattern_headers_maybe_templates,
5728 line, linenum, required)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005729
5730 # The following function is just a speed up, no semantics are changed.
5731 if not '<' in line: # Reduces the cpu time usage by skipping lines.
5732 continue
5733
Peter Kasting03b187d2022-11-04 18:33:43 +00005734 required = UpdateRequiredHeadersForLine(_re_pattern_templates, line,
5735 linenum, required)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005736
erg@google.com6317a9c2009-06-25 00:28:19 +00005737 # The policy is that if you #include something in foo.h you don't need to
5738 # include it again in foo.cc. Here, we will look at possible includes.
avakulenko@google.com59146752014-08-11 20:20:55 +00005739 # Let's flatten the include_state include_list and copy it into a dictionary.
5740 include_dict = dict([item for sublist in include_state.include_list
5741 for item in sublist])
erg@google.com6317a9c2009-06-25 00:28:19 +00005742
avakulenko@google.com59146752014-08-11 20:20:55 +00005743 # Did we find the header for this file (if any) and successfully load it?
erg@google.com6317a9c2009-06-25 00:28:19 +00005744 header_found = False
5745
5746 # Use the absolute path so that matching works properly.
erg@chromium.org8f927562012-01-30 19:51:28 +00005747 abs_filename = FileInfo(filename).FullName()
erg@google.com6317a9c2009-06-25 00:28:19 +00005748
5749 # For Emacs's flymake.
5750 # If cpplint is invoked from Emacs's flymake, a temporary file is generated
5751 # by flymake and that file name might end with '_flymake.cc'. In that case,
5752 # restore original file name here so that the corresponding header file can be
5753 # found.
5754 # e.g. If the file name is 'foo_flymake.cc', we should search for 'foo.h'
5755 # instead of 'foo_flymake.h'
erg@google.com35589e62010-11-17 18:58:16 +00005756 abs_filename = re.sub(r'_flymake\.cc$', '.cc', abs_filename)
erg@google.com6317a9c2009-06-25 00:28:19 +00005757
avakulenko@google.com59146752014-08-11 20:20:55 +00005758 # include_dict is modified during iteration, so we iterate over a copy of
erg@google.com6317a9c2009-06-25 00:28:19 +00005759 # the keys.
Sarthak Kukreti60378202019-12-17 20:46:58 +00005760 header_keys = list(include_dict.keys())
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005761 for header in header_keys:
erg@google.com6317a9c2009-06-25 00:28:19 +00005762 (same_module, common_path) = FilesBelongToSameModule(abs_filename, header)
5763 fullpath = common_path + header
avakulenko@google.com59146752014-08-11 20:20:55 +00005764 if same_module and UpdateIncludeState(fullpath, include_dict, io):
erg@google.com6317a9c2009-06-25 00:28:19 +00005765 header_found = True
5766
5767 # If we can't find the header file for a .cc, assume it's because we don't
5768 # know where to look. In that case we'll give up as we're not sure they
5769 # didn't include it in the .h file.
5770 # TODO(unknown): Do a better job of finding .h files so we are confident that
5771 # not having the .h file means there isn't one.
5772 if filename.endswith('.cc') and not header_found:
5773 return
5774
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005775 # All the lines have been processed, report the errors found.
5776 for required_header_unstripped in required:
5777 template = required[required_header_unstripped][1]
avakulenko@google.com59146752014-08-11 20:20:55 +00005778 if required_header_unstripped.strip('<>"') not in include_dict:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005779 error(filename, required[required_header_unstripped][0],
5780 'build/include_what_you_use', 4,
5781 'Add #include ' + required_header_unstripped + ' for ' + template)
5782
5783
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005784_RE_PATTERN_EXPLICIT_MAKEPAIR = re.compile(r'\bmake_pair\s*<')
5785
5786
5787def CheckMakePairUsesDeduction(filename, clean_lines, linenum, error):
5788 """Check that make_pair's template arguments are deduced.
5789
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005790 G++ 4.6 in C++11 mode fails badly if make_pair's template arguments are
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005791 specified explicitly, and such use isn't intended in any case.
5792
5793 Args:
5794 filename: The name of the current file.
5795 clean_lines: A CleansedLines instance containing the file.
5796 linenum: The number of the line to check.
5797 error: The function to call with any errors found.
5798 """
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005799 line = clean_lines.elided[linenum]
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005800 match = _RE_PATTERN_EXPLICIT_MAKEPAIR.search(line)
5801 if match:
5802 error(filename, linenum, 'build/explicit_make_pair',
5803 4, # 4 = high confidence
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005804 'For C++11-compatibility, omit template arguments from make_pair'
5805 ' OR use pair directly OR if appropriate, construct a pair directly')
avakulenko@google.com59146752014-08-11 20:20:55 +00005806
5807
avakulenko@google.com59146752014-08-11 20:20:55 +00005808def CheckRedundantVirtual(filename, clean_lines, linenum, error):
5809 """Check if line contains a redundant "virtual" function-specifier.
5810
5811 Args:
5812 filename: The name of the current file.
5813 clean_lines: A CleansedLines instance containing the file.
5814 linenum: The number of the line to check.
5815 error: The function to call with any errors found.
5816 """
5817 # Look for "virtual" on current line.
5818 line = clean_lines.elided[linenum]
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005819 virtual = Match(r'^(.*)(\bvirtual\b)(.*)$', line)
avakulenko@google.com59146752014-08-11 20:20:55 +00005820 if not virtual: return
5821
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005822 # Ignore "virtual" keywords that are near access-specifiers. These
5823 # are only used in class base-specifier and do not apply to member
5824 # functions.
5825 if (Search(r'\b(public|protected|private)\s+$', virtual.group(1)) or
5826 Match(r'^\s+(public|protected|private)\b', virtual.group(3))):
5827 return
5828
5829 # Ignore the "virtual" keyword from virtual base classes. Usually
5830 # there is a column on the same line in these cases (virtual base
5831 # classes are rare in google3 because multiple inheritance is rare).
5832 if Match(r'^.*[^:]:[^:].*$', line): return
5833
avakulenko@google.com59146752014-08-11 20:20:55 +00005834 # Look for the next opening parenthesis. This is the start of the
5835 # parameter list (possibly on the next line shortly after virtual).
5836 # TODO(unknown): doesn't work if there are virtual functions with
5837 # decltype() or other things that use parentheses, but csearch suggests
5838 # that this is rare.
5839 end_col = -1
5840 end_line = -1
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005841 start_col = len(virtual.group(2))
Edward Lemur6d31ed52019-12-02 23:00:00 +00005842 for start_line in range(linenum, min(linenum + 3, clean_lines.NumLines())):
avakulenko@google.com59146752014-08-11 20:20:55 +00005843 line = clean_lines.elided[start_line][start_col:]
5844 parameter_list = Match(r'^([^(]*)\(', line)
5845 if parameter_list:
5846 # Match parentheses to find the end of the parameter list
5847 (_, end_line, end_col) = CloseExpression(
5848 clean_lines, start_line, start_col + len(parameter_list.group(1)))
5849 break
5850 start_col = 0
5851
5852 if end_col < 0:
5853 return # Couldn't find end of parameter list, give up
5854
5855 # Look for "override" or "final" after the parameter list
5856 # (possibly on the next few lines).
Edward Lemur6d31ed52019-12-02 23:00:00 +00005857 for i in range(end_line, min(end_line + 3, clean_lines.NumLines())):
avakulenko@google.com59146752014-08-11 20:20:55 +00005858 line = clean_lines.elided[i][end_col:]
5859 match = Search(r'\b(override|final)\b', line)
5860 if match:
5861 error(filename, linenum, 'readability/inheritance', 4,
5862 ('"virtual" is redundant since function is '
5863 'already declared as "%s"' % match.group(1)))
5864
5865 # Set end_col to check whole lines after we are done with the
5866 # first line.
5867 end_col = 0
5868 if Search(r'[^\w]\s*$', line):
5869 break
5870
5871
5872def CheckRedundantOverrideOrFinal(filename, clean_lines, linenum, error):
5873 """Check if line contains a redundant "override" or "final" virt-specifier.
5874
5875 Args:
5876 filename: The name of the current file.
5877 clean_lines: A CleansedLines instance containing the file.
5878 linenum: The number of the line to check.
5879 error: The function to call with any errors found.
5880 """
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005881 # Look for closing parenthesis nearby. We need one to confirm where
5882 # the declarator ends and where the virt-specifier starts to avoid
5883 # false positives.
avakulenko@google.com59146752014-08-11 20:20:55 +00005884 line = clean_lines.elided[linenum]
avakulenko@google.com255f2be2014-12-05 22:19:55 +00005885 declarator_end = line.rfind(')')
5886 if declarator_end >= 0:
5887 fragment = line[declarator_end:]
5888 else:
5889 if linenum > 1 and clean_lines.elided[linenum - 1].rfind(')') >= 0:
5890 fragment = line
5891 else:
5892 return
5893
5894 # Check that at most one of "override" or "final" is present, not both
5895 if Search(r'\boverride\b', fragment) and Search(r'\bfinal\b', fragment):
avakulenko@google.com59146752014-08-11 20:20:55 +00005896 error(filename, linenum, 'readability/inheritance', 4,
5897 ('"override" is redundant since function is '
5898 'already declared as "final"'))
5899
5900
5901
5902
5903# Returns true if we are at a new block, and it is directly
5904# inside of a namespace.
5905def IsBlockInNameSpace(nesting_state, is_forward_declaration):
5906 """Checks that the new block is directly in a namespace.
5907
5908 Args:
5909 nesting_state: The _NestingState object that contains info about our state.
5910 is_forward_declaration: If the class is a forward declared class.
5911 Returns:
5912 Whether or not the new block is directly in a namespace.
5913 """
5914 if is_forward_declaration:
5915 if len(nesting_state.stack) >= 1 and (
5916 isinstance(nesting_state.stack[-1], _NamespaceInfo)):
5917 return True
5918 else:
5919 return False
5920
5921 return (len(nesting_state.stack) > 1 and
5922 nesting_state.stack[-1].check_namespace_indentation and
5923 isinstance(nesting_state.stack[-2], _NamespaceInfo))
5924
5925
5926def ShouldCheckNamespaceIndentation(nesting_state, is_namespace_indent_item,
5927 raw_lines_no_comments, linenum):
5928 """This method determines if we should apply our namespace indentation check.
5929
5930 Args:
5931 nesting_state: The current nesting state.
5932 is_namespace_indent_item: If we just put a new class on the stack, True.
5933 If the top of the stack is not a class, or we did not recently
5934 add the class, False.
5935 raw_lines_no_comments: The lines without the comments.
5936 linenum: The current line number we are processing.
5937
5938 Returns:
5939 True if we should apply our namespace indentation check. Currently, it
5940 only works for classes and namespaces inside of a namespace.
5941 """
5942
5943 is_forward_declaration = IsForwardClassDeclaration(raw_lines_no_comments,
5944 linenum)
5945
5946 if not (is_namespace_indent_item or is_forward_declaration):
5947 return False
5948
5949 # If we are in a macro, we do not want to check the namespace indentation.
5950 if IsMacroDefinition(raw_lines_no_comments, linenum):
5951 return False
5952
5953 return IsBlockInNameSpace(nesting_state, is_forward_declaration)
5954
5955
5956# Call this method if the line is directly inside of a namespace.
5957# If the line above is blank (excluding comments) or the start of
5958# an inner namespace, it cannot be indented.
5959def CheckItemIndentationInNamespace(filename, raw_lines_no_comments, linenum,
5960 error):
5961 line = raw_lines_no_comments[linenum]
5962 if Match(r'^\s+', line):
5963 error(filename, linenum, 'runtime/indentation_namespace', 4,
5964 'Do not indent within a namespace')
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005965
5966
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005967def ProcessLine(filename, file_extension, clean_lines, line,
5968 include_state, function_state, nesting_state, error,
5969 extra_check_functions=[]):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005970 """Processes a single line in the file.
5971
5972 Args:
5973 filename: Filename of the file that is being processed.
5974 file_extension: The extension (dot not included) of the file.
5975 clean_lines: An array of strings, each representing a line of the file,
5976 with comments stripped.
5977 line: Number of line being processed.
5978 include_state: An _IncludeState instance in which the headers are inserted.
5979 function_state: A _FunctionState instance which counts function lines, etc.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005980 nesting_state: A NestingState instance which maintains information about
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005981 the current stack of nested blocks being parsed.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005982 error: A callable to which errors are reported, which takes 4 arguments:
5983 filename, line number, error level, and message
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00005984 extra_check_functions: An array of additional check functions that will be
5985 run on each source line. Each function takes 4
5986 arguments: filename, clean_lines, line, error
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005987 """
5988 raw_lines = clean_lines.raw_lines
erg@google.com35589e62010-11-17 18:58:16 +00005989 ParseNolintSuppressions(filename, raw_lines[line], line, error)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005990 nesting_state.Update(filename, clean_lines, line, error)
avakulenko@google.com59146752014-08-11 20:20:55 +00005991 CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line,
5992 error)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00005993 if nesting_state.InAsmBlock(): return
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005994 CheckForFunctionLengths(filename, clean_lines, line, function_state, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005995 CheckForMultilineCommentsAndStrings(filename, clean_lines, line, error)
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00005996 CheckStyle(filename, clean_lines, line, file_extension, nesting_state, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00005997 CheckLanguage(filename, clean_lines, line, file_extension, include_state,
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00005998 nesting_state, error)
5999 CheckForNonConstReference(filename, clean_lines, line, nesting_state, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006000 CheckForNonStandardConstructs(filename, clean_lines, line,
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00006001 nesting_state, error)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00006002 CheckVlogArguments(filename, clean_lines, line, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006003 CheckPosixThreading(filename, clean_lines, line, error)
erg@google.com6317a9c2009-06-25 00:28:19 +00006004 CheckInvalidIncrement(filename, clean_lines, line, error)
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00006005 CheckMakePairUsesDeduction(filename, clean_lines, line, error)
avakulenko@google.com59146752014-08-11 20:20:55 +00006006 CheckRedundantVirtual(filename, clean_lines, line, error)
6007 CheckRedundantOverrideOrFinal(filename, clean_lines, line, error)
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00006008 for check_fn in extra_check_functions:
6009 check_fn(filename, clean_lines, line, error)
avakulenko@google.com17449932014-07-28 22:13:33 +00006010
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00006011def FlagCxx11Features(filename, clean_lines, linenum, error):
6012 """Flag those c++11 features that we only allow in certain places.
6013
6014 Args:
6015 filename: The name of the current file.
6016 clean_lines: A CleansedLines instance containing the file.
6017 linenum: The number of the line to check.
6018 error: The function to call with any errors found.
6019 """
6020 line = clean_lines.elided[linenum]
6021
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00006022 include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line)
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00006023
6024 # Flag unapproved C++ TR1 headers.
6025 if include and include.group(1).startswith('tr1/'):
6026 error(filename, linenum, 'build/c++tr1', 5,
6027 ('C++ TR1 headers such as <%s> are unapproved.') % include.group(1))
6028
6029 # Flag unapproved C++11 headers.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00006030 if include and include.group(1) in ('cfenv',
6031 'condition_variable',
6032 'fenv.h',
6033 'future',
6034 'mutex',
6035 'thread',
6036 'chrono',
6037 'ratio',
6038 'regex',
6039 'system_error',
6040 ):
6041 error(filename, linenum, 'build/c++11', 5,
6042 ('<%s> is an unapproved C++11 header.') % include.group(1))
6043
6044 # The only place where we need to worry about C++11 keywords and library
6045 # features in preprocessor directives is in macro definitions.
6046 if Match(r'\s*#', line) and not Match(r'\s*#\s*define\b', line): return
6047
6048 # These are classes and free functions. The classes are always
6049 # mentioned as std::*, but we only catch the free functions if
6050 # they're not found by ADL. They're alphabetical by header.
6051 for top_name in (
6052 # type_traits
6053 'alignment_of',
6054 'aligned_union',
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00006055 ):
6056 if Search(r'\bstd::%s\b' % top_name, line):
6057 error(filename, linenum, 'build/c++11', 5,
6058 ('std::%s is an unapproved C++11 class or function. Send c-style '
6059 'an example of where it would make your code more readable, and '
6060 'they may let you use it.') % top_name)
6061
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006062
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00006063def FlagCxx14Features(filename, clean_lines, linenum, error):
6064 """Flag those C++14 features that we restrict.
6065
6066 Args:
6067 filename: The name of the current file.
6068 clean_lines: A CleansedLines instance containing the file.
6069 linenum: The number of the line to check.
6070 error: The function to call with any errors found.
6071 """
6072 line = clean_lines.elided[linenum]
6073
6074 include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line)
6075
6076 # Flag unapproved C++14 headers.
6077 if include and include.group(1) in ('scoped_allocator', 'shared_mutex'):
6078 error(filename, linenum, 'build/c++14', 5,
6079 ('<%s> is an unapproved C++14 header.') % include.group(1))
6080
6081
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00006082def ProcessFileData(filename, file_extension, lines, error,
6083 extra_check_functions=[]):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006084 """Performs lint checks and reports any errors to the given error function.
6085
6086 Args:
6087 filename: Filename of the file that is being processed.
6088 file_extension: The extension (dot not included) of the file.
6089 lines: An array of strings, each representing a line of the file, with the
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00006090 last element being empty if the file is terminated with a newline.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006091 error: A callable to which errors are reported, which takes 4 arguments:
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00006092 filename, line number, error level, and message
6093 extra_check_functions: An array of additional check functions that will be
6094 run on each source line. Each function takes 4
6095 arguments: filename, clean_lines, line, error
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006096 """
6097 lines = (['// marker so line numbers and indices both start at 1'] + lines +
6098 ['// marker so line numbers end in a known way'])
6099
6100 include_state = _IncludeState()
6101 function_state = _FunctionState()
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00006102 nesting_state = NestingState()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006103
erg@google.com35589e62010-11-17 18:58:16 +00006104 ResetNolintSuppressions()
6105
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006106 CheckForCopyright(filename, lines, error)
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00006107 ProcessGlobalSuppresions(lines)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006108 RemoveMultiLineComments(filename, lines, error)
6109 clean_lines = CleansedLines(lines)
avakulenko@google.com255f2be2014-12-05 22:19:55 +00006110
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00006111 if file_extension == 'h':
avakulenko@google.com255f2be2014-12-05 22:19:55 +00006112 CheckForHeaderGuard(filename, clean_lines, error)
6113
Edward Lemur6d31ed52019-12-02 23:00:00 +00006114 for line in range(clean_lines.NumLines()):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006115 ProcessLine(filename, file_extension, clean_lines, line,
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00006116 include_state, function_state, nesting_state, error,
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00006117 extra_check_functions)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00006118 FlagCxx11Features(filename, clean_lines, line, error)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00006119 nesting_state.CheckCompletedBlocks(filename, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006120
6121 CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error)
skym@chromium.org3990c412016-02-05 20:55:12 +00006122
avakulenko@google.com255f2be2014-12-05 22:19:55 +00006123 # Check that the .cc file has included its header if it exists.
avakulenko@chromium.org764ce712016-05-06 23:03:41 +00006124 if _IsSourceExtension(file_extension):
avakulenko@google.com255f2be2014-12-05 22:19:55 +00006125 CheckHeaderFileIncluded(filename, include_state, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006126
6127 # We check here rather than inside ProcessLine so that we see raw
6128 # lines rather than "cleaned" lines.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00006129 CheckForBadCharacters(filename, lines, error)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006130
6131 CheckForNewlineAtEOF(filename, lines, error)
6132
avakulenko@google.com17449932014-07-28 22:13:33 +00006133def ProcessConfigOverrides(filename):
6134 """ Loads the configuration files and processes the config overrides.
6135
6136 Args:
6137 filename: The name of the file being processed by the linter.
6138
6139 Returns:
6140 False if the current |filename| should not be processed further.
6141 """
6142
6143 abs_filename = os.path.abspath(filename)
6144 cfg_filters = []
6145 keep_looking = True
6146 while keep_looking:
6147 abs_path, base_name = os.path.split(abs_filename)
6148 if not base_name:
6149 break # Reached the root directory.
6150
6151 cfg_file = os.path.join(abs_path, "CPPLINT.cfg")
6152 abs_filename = abs_path
6153 if not os.path.isfile(cfg_file):
6154 continue
6155
6156 try:
6157 with open(cfg_file) as file_handle:
6158 for line in file_handle:
6159 line, _, _ = line.partition('#') # Remove comments.
6160 if not line.strip():
6161 continue
6162
6163 name, _, val = line.partition('=')
6164 name = name.strip()
6165 val = val.strip()
6166 if name == 'set noparent':
6167 keep_looking = False
6168 elif name == 'filter':
6169 cfg_filters.append(val)
6170 elif name == 'exclude_files':
6171 # When matching exclude_files pattern, use the base_name of
6172 # the current file name or the directory name we are processing.
6173 # For example, if we are checking for lint errors in /foo/bar/baz.cc
6174 # and we found the .cfg file at /foo/CPPLINT.cfg, then the config
6175 # file's "exclude_files" filter is meant to be checked against "bar"
6176 # and not "baz" nor "bar/baz.cc".
6177 if base_name:
6178 pattern = re.compile(val)
6179 if pattern.match(base_name):
6180 sys.stderr.write('Ignoring "%s": file excluded by "%s". '
6181 'File path component "%s" matches '
6182 'pattern "%s"\n' %
6183 (filename, cfg_file, base_name, val))
6184 return False
avakulenko@google.com68a4fa62014-08-25 16:26:18 +00006185 elif name == 'linelength':
6186 global _line_length
6187 try:
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +00006188 _line_length = int(val)
avakulenko@google.com68a4fa62014-08-25 16:26:18 +00006189 except ValueError:
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +00006190 sys.stderr.write('Line length must be numeric.')
avakulenko@google.com17449932014-07-28 22:13:33 +00006191 else:
6192 sys.stderr.write(
6193 'Invalid configuration option (%s) in file %s\n' %
6194 (name, cfg_file))
6195
6196 except IOError:
6197 sys.stderr.write(
6198 "Skipping config file '%s': Can't open for reading\n" % cfg_file)
6199 keep_looking = False
6200
6201 # Apply all the accumulated filters in reverse order (top-level directory
6202 # config options having the least priority).
6203 for filter in reversed(cfg_filters):
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +00006204 _AddFilters(filter)
avakulenko@google.com17449932014-07-28 22:13:33 +00006205
6206 return True
6207
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00006208
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00006209def ProcessFile(filename, vlevel, extra_check_functions=[]):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006210 """Does google-lint on a single file.
6211
6212 Args:
6213 filename: The name of the file to parse.
6214
6215 vlevel: The level of errors to report. Every error of confidence
6216 >= verbose_level will be reported. 0 is a good default.
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00006217
6218 extra_check_functions: An array of additional check functions that will be
6219 run on each source line. Each function takes 4
6220 arguments: filename, clean_lines, line, error
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006221 """
6222
6223 _SetVerboseLevel(vlevel)
avakulenko@google.com17449932014-07-28 22:13:33 +00006224 _BackupFilters()
6225
6226 if not ProcessConfigOverrides(filename):
6227 _RestoreFilters()
6228 return
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006229
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00006230 lf_lines = []
6231 crlf_lines = []
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006232 try:
6233 # Support the UNIX convention of using "-" for stdin. Note that
6234 # we are not opening the file with universal newline support
6235 # (which codecs doesn't support anyway), so the resulting lines do
6236 # contain trailing '\r' characters if we are reading a file that
6237 # has CRLF endings.
6238 # If after the split a trailing '\r' is present, it is removed
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00006239 # below.
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006240 if filename == '-':
6241 lines = codecs.StreamReaderWriter(sys.stdin,
6242 codecs.getreader('utf8'),
6243 codecs.getwriter('utf8'),
6244 'replace').read().split('\n')
6245 else:
6246 lines = codecs.open(filename, 'r', 'utf8', 'replace').read().split('\n')
6247
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006248 # Remove trailing '\r'.
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00006249 # The -1 accounts for the extra trailing blank line we get from split()
6250 for linenum in range(len(lines) - 1):
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006251 if lines[linenum].endswith('\r'):
6252 lines[linenum] = lines[linenum].rstrip('\r')
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00006253 crlf_lines.append(linenum + 1)
6254 else:
6255 lf_lines.append(linenum + 1)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006256
6257 except IOError:
6258 sys.stderr.write(
6259 "Skipping input '%s': Can't open for reading\n" % filename)
avakulenko@google.com17449932014-07-28 22:13:33 +00006260 _RestoreFilters()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006261 return
6262
6263 # Note, if no dot is found, this will give the entire filename as the ext.
6264 file_extension = filename[filename.rfind('.') + 1:]
6265
6266 # When reading from stdin, the extension is unknown, so no cpplint tests
6267 # should rely on the extension.
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00006268 if filename != '-' and file_extension not in _valid_extensions:
6269 sys.stderr.write('Ignoring %s; not a valid file name '
6270 '(%s)\n' % (filename, ', '.join(_valid_extensions)))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006271 else:
asvitkine@chromium.org8b8d8be2011-09-08 15:34:45 +00006272 ProcessFileData(filename, file_extension, lines, Error,
6273 extra_check_functions)
avakulenko@google.comd39bbb52014-06-04 22:55:20 +00006274
6275 # If end-of-line sequences are a mix of LF and CR-LF, issue
6276 # warnings on the lines with CR.
6277 #
6278 # Don't issue any warnings if all lines are uniformly LF or CR-LF,
6279 # since critique can handle these just fine, and the style guide
6280 # doesn't dictate a particular end of line sequence.
6281 #
6282 # We can't depend on os.linesep to determine what the desired
6283 # end-of-line sequence should be, since that will return the
6284 # server-side end-of-line sequence.
6285 if lf_lines and crlf_lines:
6286 # Warn on every line with CR. An alternative approach might be to
6287 # check whether the file is mostly CRLF or just LF, and warn on the
6288 # minority, we bias toward LF here since most tools prefer LF.
6289 for linenum in crlf_lines:
6290 Error(filename, linenum, 'whitespace/newline', 1,
6291 'Unexpected \\r (^M) found; better to use only \\n')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006292
avakulenko@google.com17449932014-07-28 22:13:33 +00006293 _RestoreFilters()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006294
6295
6296def PrintUsage(message):
6297 """Prints a brief usage string and exits, optionally with an error message.
6298
6299 Args:
6300 message: The optional error message.
6301 """
6302 sys.stderr.write(_USAGE)
6303 if message:
6304 sys.exit('\nFATAL ERROR: ' + message)
6305 else:
6306 sys.exit(1)
6307
6308
6309def PrintCategories():
6310 """Prints a list of all the error-categories used by error messages.
6311
6312 These are the categories used to filter messages via --filter.
6313 """
erg@google.com35589e62010-11-17 18:58:16 +00006314 sys.stderr.write(''.join(' %s\n' % cat for cat in _ERROR_CATEGORIES))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006315 sys.exit(0)
6316
6317
6318def ParseArguments(args):
6319 """Parses the command line arguments.
6320
6321 This may set the output format and verbosity level as side-effects.
6322
6323 Args:
6324 args: The command line arguments:
6325
6326 Returns:
6327 The list of filenames to lint.
6328 """
6329 try:
6330 (opts, filenames) = getopt.getopt(args, '', ['help', 'output=', 'verbose=',
Jordan Bayles91a32c52019-02-22 21:28:17 +00006331 'headers=', # We understand but ignore headers.
erg@google.com26970fa2009-11-17 18:07:32 +00006332 'counting=',
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00006333 'filter=',
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00006334 'root=',
6335 'linelength=',
sdefresne263e9282016-07-19 02:14:22 -07006336 'extensions=',
Jordan Bayles91a32c52019-02-22 21:28:17 +00006337 'project_root=',
6338 'repository='])
6339 except getopt.GetoptError as e:
6340 PrintUsage('Invalid arguments: {}'.format(e))
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006341
6342 verbosity = _VerboseLevel()
6343 output_format = _OutputFormat()
6344 filters = ''
erg@google.com26970fa2009-11-17 18:07:32 +00006345 counting_style = ''
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006346
6347 for (opt, val) in opts:
6348 if opt == '--help':
6349 PrintUsage(None)
6350 elif opt == '--output':
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00006351 if val not in ('emacs', 'vs7', 'eclipse'):
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00006352 PrintUsage('The only allowed output formats are emacs, vs7 and eclipse.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006353 output_format = val
6354 elif opt == '--verbose':
6355 verbosity = int(val)
6356 elif opt == '--filter':
6357 filters = val
erg@google.com6317a9c2009-06-25 00:28:19 +00006358 if not filters:
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006359 PrintCategories()
erg@google.com26970fa2009-11-17 18:07:32 +00006360 elif opt == '--counting':
6361 if val not in ('total', 'toplevel', 'detailed'):
6362 PrintUsage('Valid counting options are total, toplevel, and detailed')
6363 counting_style = val
mazda@chromium.org3fffcec2013-06-07 01:04:53 +00006364 elif opt == '--root':
6365 global _root
6366 _root = val
Jordan Bayles91a32c52019-02-22 21:28:17 +00006367 elif opt == '--project_root' or opt == "--repository":
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00006368 global _project_root
6369 _project_root = val
6370 if not os.path.isabs(_project_root):
6371 PrintUsage('Project root must be an absolute path.')
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00006372 elif opt == '--linelength':
6373 global _line_length
6374 try:
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +00006375 _line_length = int(val)
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00006376 except ValueError:
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +00006377 PrintUsage('Line length must be digits.')
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00006378 elif opt == '--extensions':
6379 global _valid_extensions
6380 try:
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +00006381 _valid_extensions = set(val.split(','))
raphael.kubo.da.costa@intel.com331fbc42014-05-09 08:48:20 +00006382 except ValueError:
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +00006383 PrintUsage('Extensions must be comma separated list.')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006384
6385 if not filenames:
6386 PrintUsage('No files were specified.')
6387
6388 _SetOutputFormat(output_format)
6389 _SetVerboseLevel(verbosity)
6390 _SetFilters(filters)
erg@google.com26970fa2009-11-17 18:07:32 +00006391 _SetCountingStyle(counting_style)
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006392
6393 return filenames
6394
6395
6396def main():
6397 filenames = ParseArguments(sys.argv[1:])
6398
6399 # Change stderr to write with replacement characters so we don't die
6400 # if we try to print something containing non-ASCII characters.
Edward Lemur6d31ed52019-12-02 23:00:00 +00006401 # We use sys.stderr.buffer in Python 3, since StreamReaderWriter writes bytes
6402 # to the specified stream.
6403 sys.stderr = codecs.StreamReaderWriter(
6404 getattr(sys.stderr, 'buffer', sys.stderr),
6405 codecs.getreader('utf8'), codecs.getwriter('utf8'), 'replace')
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006406
erg@google.com26970fa2009-11-17 18:07:32 +00006407 _cpplint_state.ResetErrorCounts()
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006408 for filename in filenames:
6409 ProcessFile(filename, _cpplint_state.verbose_level)
Sergiy Byelozyorov7999d922018-06-22 09:25:54 +00006410 _cpplint_state.PrintErrorCounts()
erg@google.com26970fa2009-11-17 18:07:32 +00006411
maruel@google.comfb2b8eb2009-04-23 21:03:42 +00006412 sys.exit(_cpplint_state.error_count > 0)
6413
6414
6415if __name__ == '__main__':
6416 main()