Debian Codegraph @

cpplint.py

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 #!/usr/bin/env python
2 #
3 # Copyright (c) 2009 Google Inc. All rights reserved.
4 #
5 # Redistribution and use in source and binary forms, with or without
6 # modification, are permitted provided that the following conditions are
7 # met:
8 #
9 # * 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.
18 #
19 # 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.
30
31 """Does google-lint on c++ files.
32
33 The goal of this script is to identify places in the code that *may*
34 be in non-compliance with google style. It does not attempt to fix
35 up these problems -- the point is to educate. It does also not
36 attempt to find all problems, or to ensure that everything it does
37 find is legitimately a problem.
38
39 In particular, we can get very confused by /* and // inside strings!
40 We do a small hack, which is to ignore //'s with "'s after them on the
41 same line, but it is far from perfect (in either direction).
42 """
43
44 from __future__ import annotations # PEP 604 not in 3.9
45
46 import codecs
47 import collections
48 import copy
49 import getopt
50 import glob
51 import itertools
52 import math # for log
53 import os
54 import re
55 import string
56 import sys
57 import sysconfig
58 import unicodedata
59 import xml.etree.ElementTree
60
61 # if empty, use defaults
62 _valid_extensions: set[str] = set()
63
64 __VERSION__ = "2.0.2"
65
66 _USAGE = """
67 Syntax: cpplint.py [--verbose=#] [--output=emacs|eclipse|vs7|junit|sed|gsed]
68 [--filter=-x,+y,...]
69 [--counting=total|toplevel|detailed] [--root=subdir]
70 [--repository=path]
71 [--linelength=digits] [--headers=x,y,...]
72 [--recursive]
73 [--exclude=path]
74 [--extensions=hpp,cpp,...]
75 [--includeorder=default|standardcfirst]
76 [--config=filename]
77 [--quiet]
78 [--version]
79 <file> [file] ...
80
81 Style checker for C/C++ source files.
82 This is a fork of the Google style checker with minor extensions.
83
84 The style guidelines this tries to follow are those in
85 https://google.github.io/styleguide/cppguide.html
86
87 Every problem is given a confidence score from 1-5, with 5 meaning we are
88 certain of the problem, and 1 meaning it could be a legitimate construct.
89 This will miss some errors, and is not a substitute for a code review.
90
91 To suppress false-positive errors of certain categories, add a
92 'NOLINT(category[, category...])' comment to the line. NOLINT or NOLINT(*)
93 suppresses errors of all categories on that line. To suppress categories
94 on the next line use NOLINTNEXTLINE instead of NOLINT. To suppress errors in
95 a block of code 'NOLINTBEGIN(category[, category...])' comment to a line at
96 the start of the block and to end the block add a comment with 'NOLINTEND'.
97 NOLINT blocks are inclusive so any statements on the same line as a BEGIN
98 or END will have the error suppression applied.
99
100 The files passed in will be linted; at least one file must be provided.
101 Default linted extensions are %s.
102 Other file types will be ignored.
103 Change the extensions with the --extensions flag.
104
105 Flags:
106
107 output=emacs|eclipse|vs7|junit|sed|gsed
108 By default, the output is formatted to ease emacs parsing. Visual Studio
109 compatible output (vs7) may also be used. Further support exists for
110 eclipse (eclipse), and JUnit (junit). XML parsers such as those used
111 in Jenkins and Bamboo may also be used.
112 The sed format outputs sed commands that should fix some of the errors.
113 Note that this requires gnu sed. If that is installed as gsed on your
114 system (common e.g. on macOS with homebrew) you can use the gsed output
115 format. Sed commands are written to stdout, not stderr, so you should be
116 able to pipe output straight to a shell to run the fixes.
117
118 verbose=#
119 Specify a number 0-5 to restrict errors to certain verbosity levels.
120 Errors with lower verbosity levels have lower confidence and are more
121 likely to be false positives.
122
123 quiet
124 Don't print anything if no errors are found.
125
126 filter=-x,+y,...
127 Specify a comma-separated list of category-filters to apply: only
128 error messages whose category names pass the filters will be printed.
129 (Category names are printed with the message and look like
130 "[whitespace/indent]".) Filters are evaluated left to right.
131 "-FOO" means "do not print categories that start with FOO".
132 "+FOO" means "do print categories that start with FOO".
133
134 Examples: --filter=-whitespace,+whitespace/braces
135 --filter=-whitespace,-runtime/printf,+runtime/printf_format
136 --filter=-,+build/include_what_you_use
137
138 To see a list of all the categories used in cpplint, pass no arg:
139 --filter=
140
141 Filters can directly be limited to files and also line numbers. The
142 syntax is category:file:line , where line is optional. The filter limitation
143 works for both + and - and can be combined with ordinary filters:
144
145 Examples: --filter=-whitespace:foo.h,+whitespace/braces:foo.h
146 --filter=-whitespace,-runtime/printf:foo.h:14,+runtime/printf_format:foo.h
147 --filter=-,+build/include_what_you_use:foo.h:321
148
149 counting=total|toplevel|detailed
150 The total number of errors found is always printed. If
151 'toplevel' is provided, then the count of errors in each of
152 the top-level categories like 'build' and 'whitespace' will
153 also be printed. If 'detailed' is provided, then a count
154 is provided for each category like 'legal/copyright'.
155
156 repository=path
157 The top level directory of the repository, used to derive the header
158 guard CPP variable. By default, this is determined by searching for a
159 path that contains .git, .hg, or .svn. When this flag is specified, the
160 given path is used instead. This option allows the header guard CPP
161 variable to remain consistent even if members of a team have different
162 repository root directories (such as when checking out a subdirectory
163 with SVN). In addition, users of non-mainstream version control systems
164 can use this flag to ensure readable header guard CPP variables.
165
166 Examples:
167 Assuming that Alice checks out ProjectName and Bob checks out
168 ProjectName/trunk and trunk contains src/chrome/ui/browser.h, then
169 with no --repository flag, the header guard CPP variable will be:
170
171 Alice => TRUNK_SRC_CHROME_BROWSER_UI_BROWSER_H_
172 Bob => SRC_CHROME_BROWSER_UI_BROWSER_H_
173
174 If Alice uses the --repository=trunk flag and Bob omits the flag or
175 uses --repository=. then the header guard CPP variable will be:
176
177 Alice => SRC_CHROME_BROWSER_UI_BROWSER_H_
178 Bob => SRC_CHROME_BROWSER_UI_BROWSER_H_
179
180 root=subdir
181 The root directory used for deriving header guard CPP variable.
182 This directory is relative to the top level directory of the repository
183 which by default is determined by searching for a directory that contains
184 .git, .hg, or .svn but can also be controlled with the --repository flag.
185 If the specified directory does not exist, this flag is ignored.
186
187 Examples:
188 Assuming that src is the top level directory of the repository (and
189 cwd=top/src), the header guard CPP variables for
190 src/chrome/browser/ui/browser.h are:
191
192 No flag => CHROME_BROWSER_UI_BROWSER_H_
193 --root=chrome => BROWSER_UI_BROWSER_H_
194 --root=chrome/browser => UI_BROWSER_H_
195 --root=.. => SRC_CHROME_BROWSER_UI_BROWSER_H_
196
197 linelength=digits
198 This is the allowed line length for the project. The default value is
199 80 characters.
200
201 Examples:
202 --linelength=120
203
204 recursive
205 Search for files to lint recursively. Each directory given in the list
206 of files to be linted is replaced by all files that descend from that
207 directory. Files with extensions not in the valid extensions list are
208 excluded.
209
210 exclude=path
211 Exclude the given path from the list of files to be linted. Relative
212 paths are evaluated relative to the current directory and shell globbing
213 is performed. This flag can be provided multiple times to exclude
214 multiple files.
215
216 Examples:
217 --exclude=one.cc
218 --exclude=src/*.cc
219 --exclude=src/*.cc --exclude=test/*.cc
220
221 extensions=extension,extension,...
222 The allowed file extensions that cpplint will check
223
224 Examples:
225 --extensions=%s
226
227 includeorder=default|standardcfirst
228 For the build/include_order rule, the default is to blindly assume angle
229 bracket includes with file extension are c-system-headers (default),
230 even knowing this will have false classifications.
231 The default is established at google.
232 standardcfirst means to instead use an allow-list of known c headers and
233 treat all others as separate group of "other system headers". The C headers
234 included are those of the C-standard lib and closely related ones.
235
236 config=filename
237 Search for config files with the specified name instead of CPPLINT.cfg
238
239 headers=x,y,...
240 The header extensions that cpplint will treat as .h in checks. Values are
241 automatically added to --extensions list.
242 (by default, only files with extensions %s will be assumed to be headers)
243
244 Examples:
245 --headers=%s
246 --headers=hpp,hxx
247 --headers=hpp
248
249 cpplint.py supports per-directory configurations specified in CPPLINT.cfg
250 files. CPPLINT.cfg file can contain a number of key=value pairs.
251 Currently the following options are supported:
252
253 set noparent
254 filter=+filter1,-filter2,...
255 exclude_files=regex
256 linelength=80
257 root=subdir
258 headers=x,y,...
259
260 "set noparent" option prevents cpplint from traversing directory tree
261 upwards looking for more .cfg files in parent directories. This option
262 is usually placed in the top-level project directory.
263
264 The "filter" option is similar in function to --filter flag. It specifies
265 message filters in addition to the |_DEFAULT_FILTERS| and those specified
266 through --filter command-line flag.
267
268 "exclude_files" allows to specify a regular expression to be matched against
269 a file name. If the expression matches, the file is skipped and not run
270 through the linter.
271
272 "linelength" allows to specify the allowed line length for the project.
273
274 The "root" option is similar in function to the --root flag (see example
275 above). Paths are relative to the directory of the CPPLINT.cfg.
276
277 The "headers" option is similar in function to the --headers flag
278 (see example above).
279
280 CPPLINT.cfg has an effect on files in the same directory and all
281 sub-directories, unless overridden by a nested configuration file.
282
283 Example file:
284 filter=-build/include_order,+build/include_alpha
285 exclude_files=.*\\.cc
286
287 The above example disables build/include_order warning and enables
288 build/include_alpha as well as excludes all .cc from being
289 processed by linter, in the current directory (where the .cfg
290 file is located) and all sub-directories.
291 """
292
293 # We categorize each error message we print. Here are the categories.
294 # We want an explicit list so we can list them all in cpplint --filter=.
295 # If you add a new error message with a new category, add it to the list
296 # here! cpplint_unittest.py should tell you if you forget to do this.
297 _ERROR_CATEGORIES = [
298 "build/c++11",
299 "build/c++17",
300 "build/deprecated",
301 "build/endif_comment",
302 "build/explicit_make_pair",
303 "build/forward_decl",
304 "build/header_guard",
305 "build/include",
306 "build/include_subdir",
307 "build/include_alpha",
308 "build/include_order",
309 "build/include_what_you_use",
310 "build/namespaces_headers",
311 "build/namespaces_literals",
312 "build/namespaces",
313 "build/printf_format",
314 "build/storage_class",
315 "legal/copyright",
316 "readability/alt_tokens",
317 "readability/braces",
318 "readability/casting",
319 "readability/check",
320 "readability/constructors",
321 "readability/fn_size",
322 "readability/inheritance",
323 "readability/multiline_comment",
324 "readability/multiline_string",
325 "readability/namespace",
326 "readability/nolint",
327 "readability/nul",
328 "readability/todo",
329 "readability/utf8",
330 "runtime/arrays",
331 "runtime/casting",
332 "runtime/explicit",
333 "runtime/int",
334 "runtime/init",
335 "runtime/invalid_increment",
336 "runtime/member_string_references",
337 "runtime/memset",
338 "runtime/operator",
339 "runtime/printf",
340 "runtime/printf_format",
341 "runtime/references",
342 "runtime/string",
343 "runtime/threadsafe_fn",
344 "runtime/vlog",
345 "whitespace/blank_line",
346 "whitespace/braces",
347 "whitespace/comma",
348 "whitespace/comments",
349 "whitespace/empty_conditional_body",
350 "whitespace/empty_if_body",
351 "whitespace/empty_loop_body",
352 "whitespace/end_of_line",
353 "whitespace/ending_newline",
354 "whitespace/forcolon",
355 "whitespace/indent",
356 "whitespace/indent_namespace",
357 "whitespace/line_length",
358 "whitespace/newline",
359 "whitespace/operators",
360 "whitespace/parens",
361 "whitespace/semicolon",
362 "whitespace/tab",
363 "whitespace/todo",
364 ]
365
366 # keywords to use with --outputs which generate stdout for machine processing
367 _MACHINE_OUTPUTS = ["junit", "sed", "gsed"]
368
369 # These error categories are no longer enforced by cpplint, but for backwards-
370 # compatibility they may still appear in NOLINT comments.
371 _LEGACY_ERROR_CATEGORIES = [
372 "build/class",
373 "readability/streams",
374 "readability/function",
375 ]
376
377 # These prefixes for categories should be ignored since they relate to other
378 # tools which also use the NOLINT syntax, e.g. clang-tidy.
379 _OTHER_NOLINT_CATEGORY_PREFIXES = [
380 "clang-analyzer-",
381 "abseil-",
382 "altera-",
383 "android-",
384 "boost-",
385 "bugprone-",
386 "cert-",
387 "concurrency-",
388 "cppcoreguidelines-",
389 "darwin-",
390 "fuchsia-",
391 "google-",
392 "hicpp-",
393 "linuxkernel-",
394 "llvm-",
395 "llvmlibc-",
396 "misc-",
397 "modernize-",
398 "mpi-",
399 "objc-",
400 "openmp-",
401 "performance-",
402 "portability-",
403 "readability-",
404 "zircon-",
405 ]
406
407 # The default state of the category filter. This is overridden by the --filter=
408 # flag. By default all errors are on, so only add here categories that should be
409 # off by default (i.e., categories that must be enabled by the --filter= flags).
410 # All entries here should start with a '-' or '+', as in the --filter= flag.
411 _DEFAULT_FILTERS = [
412 "-build/include_alpha",
413 "-readability/fn_size",
414 "-runtime/references",
415 ]
416
417 # The default list of categories suppressed for C (not C++) files.
418 _DEFAULT_C_SUPPRESSED_CATEGORIES = [
419 "readability/casting",
420 ]
421
422 # The default list of categories suppressed for Linux Kernel files.
423 _DEFAULT_KERNEL_SUPPRESSED_CATEGORIES = [
424 "whitespace/tab",
425 ]
426
427 # We used to check for high-bit characters, but after much discussion we
428 # decided those were OK, as long as they were in UTF-8 and didn't represent
429 # hard-coded international strings, which belong in a separate i18n file.
430
431 # C++ headers
432 _CPP_HEADERS = frozenset(
433 [
434 # Legacy
435 "algobase.h",
436 "algo.h",
437 "alloc.h",
438 "builtinbuf.h",
439 "bvector.h",
440 # 'complex.h', collides with System C header "complex.h" since C11
441 "defalloc.h",
442 "deque.h",
443 "editbuf.h",
444 "fstream.h",
445 "function.h",
446 "hash_map",
447 "hash_map.h",
448 "hash_set",
449 "hash_set.h",
450 "hashtable.h",
451 "heap.h",
452 "indstream.h",
453 "iomanip.h",
454 "iostream.h",
455 "istream.h",
456 "iterator.h",
457 "list.h",
458 "map.h",
459 "multimap.h",
460 "multiset.h",
461 "ostream.h",
462 "pair.h",
463 "parsestream.h",
464 "pfstream.h",
465 "procbuf.h",
466 "pthread_alloc",
467 "pthread_alloc.h",
468 "rope",
469 "rope.h",
470 "ropeimpl.h",
471 "set.h",
472 "slist",
473 "slist.h",
474 "stack.h",
475 "stdiostream.h",
476 "stl_alloc.h",
477 "stl_relops.h",
478 "streambuf.h",
479 "stream.h",
480 "strfile.h",
481 "strstream.h",
482 "tempbuf.h",
483 "tree.h",
484 "type_traits.h",
485 "vector.h",
486 # C++ library headers
487 "algorithm",
488 "array",
489 "atomic",
490 "bitset",
491 "chrono",
492 "codecvt",
493 "complex",
494 "condition_variable",
495 "deque",
496 "exception",
497 "forward_list",
498 "fstream",
499 "functional",
500 "future",
501 "initializer_list",
502 "iomanip",
503 "ios",
504 "iosfwd",
505 "iostream",
506 "istream",
507 "iterator",
508 "limits",
509 "list",
510 "locale",
511 "map",
512 "memory",
513 "mutex",
514 "new",
515 "numeric",
516 "ostream",
517 "queue",
518 "random",
519 "ratio",
520 "regex",
521 "scoped_allocator",
522 "set",
523 "sstream",
524 "stack",
525 "stdexcept",
526 "streambuf",
527 "string",
528 "strstream",
529 "system_error",
530 "thread",
531 "tuple",
532 "typeindex",
533 "typeinfo",
534 "type_traits",
535 "unordered_map",
536 "unordered_set",
537 "utility",
538 "valarray",
539 "vector",
540 # C++14 headers
541 "shared_mutex",
542 # C++17 headers
543 "any",
544 "charconv",
545 "codecvt",
546 "execution",
547 "filesystem",
548 "memory_resource",
549 "optional",
550 "string_view",
551 "variant",
552 # C++20 headers
553 "barrier",
554 "bit",
555 "compare",
556 "concepts",
557 "coroutine",
558 "format",
559 "latch",
560 "numbers",
561 "ranges",
562 "semaphore",
563 "source_location",
564 "span",
565 "stop_token",
566 "syncstream",
567 "version",
568 # C++23 headers
569 "expected",
570 "flat_map",
571 "flat_set",
572 "generator",
573 "mdspan",
574 "print",
575 "spanstream",
576 "stacktrace",
577 "stdfloat",
578 # C++ headers for C library facilities
579 "cassert",
580 "ccomplex",
581 "cctype",
582 "cerrno",
583 "cfenv",
584 "cfloat",
585 "cinttypes",
586 "ciso646",
587 "climits",
588 "clocale",
589 "cmath",
590 "csetjmp",
591 "csignal",
592 "cstdalign",
593 "cstdarg",
594 "cstdbool",
595 "cstddef",
596 "cstdint",
597 "cstdio",
598 "cstdlib",
599 "cstring",
600 "ctgmath",
601 "ctime",
602 "cuchar",
603 "cwchar",
604 "cwctype",
605 ]
606 )
607
608 # C headers
609 _C_HEADERS = frozenset(
610 [
611 # System C headers
612 "assert.h",
613 "complex.h",
614 "ctype.h",
615 "errno.h",
616 "fenv.h",
617 "float.h",
618 "inttypes.h",
619 "iso646.h",
620 "limits.h",
621 "locale.h",
622 "math.h",
623 "setjmp.h",
624 "signal.h",
625 "stdalign.h",
626 "stdarg.h",
627 "stdatomic.h",
628 "stdbool.h",
629 "stddef.h",
630 "stdint.h",
631 "stdio.h",
632 "stdlib.h",
633 "stdnoreturn.h",
634 "string.h",
635 "tgmath.h",
636 "threads.h",
637 "time.h",
638 "uchar.h",
639 "wchar.h",
640 "wctype.h",
641 # C23 headers
642 "stdbit.h",
643 "stdckdint.h",
644 # additional POSIX C headers
645 "aio.h",
646 "arpa/inet.h",
647 "cpio.h",
648 "dirent.h",
649 "dlfcn.h",
650 "fcntl.h",
651 "fmtmsg.h",
652 "fnmatch.h",
653 "ftw.h",
654 "glob.h",
655 "grp.h",
656 "iconv.h",
657 "langinfo.h",
658 "libgen.h",
659 "monetary.h",
660 "mqueue.h",
661 "ndbm.h",
662 "net/if.h",
663 "netdb.h",
664 "netinet/in.h",
665 "netinet/tcp.h",
666 "nl_types.h",
667 "poll.h",
668 "pthread.h",
669 "pwd.h",
670 "regex.h",
671 "sched.h",
672 "search.h",
673 "semaphore.h",
674 "setjmp.h",
675 "signal.h",
676 "spawn.h",
677 "strings.h",
678 "stropts.h",
679 "syslog.h",
680 "tar.h",
681 "termios.h",
682 "trace.h",
683 "ulimit.h",
684 "unistd.h",
685 "utime.h",
686 "utmpx.h",
687 "wordexp.h",
688 # additional GNUlib headers
689 "a.out.h",
690 "aliases.h",
691 "alloca.h",
692 "ar.h",
693 "argp.h",
694 "argz.h",
695 "byteswap.h",
696 "crypt.h",
697 "endian.h",
698 "envz.h",
699 "err.h",
700 "error.h",
701 "execinfo.h",
702 "fpu_control.h",
703 "fstab.h",
704 "fts.h",
705 "getopt.h",
706 "gshadow.h",
707 "ieee754.h",
708 "ifaddrs.h",
709 "libintl.h",
710 "mcheck.h",
711 "mntent.h",
712 "obstack.h",
713 "paths.h",
714 "printf.h",
715 "pty.h",
716 "resolv.h",
717 "shadow.h",
718 "sysexits.h",
719 "ttyent.h",
720 # Additional linux glibc headers
721 "dlfcn.h",
722 "elf.h",
723 "features.h",
724 "gconv.h",
725 "gnu-versions.h",
726 "lastlog.h",
727 "libio.h",
728 "link.h",
729 "malloc.h",
730 "memory.h",
731 "netash/ash.h",
732 "netatalk/at.h",
733 "netax25/ax25.h",
734 "neteconet/ec.h",
735 "netipx/ipx.h",
736 "netiucv/iucv.h",
737 "netpacket/packet.h",
738 "netrom/netrom.h",
739 "netrose/rose.h",
740 "nfs/nfs.h",
741 "nl_types.h",
742 "nss.h",
743 "re_comp.h",
744 "regexp.h",
745 "sched.h",
746 "sgtty.h",
747 "stab.h",
748 "stdc-predef.h",
749 "stdio_ext.h",
750 "syscall.h",
751 "termio.h",
752 "thread_db.h",
753 "ucontext.h",
754 "ustat.h",
755 "utmp.h",
756 "values.h",
757 "wait.h",
758 "xlocale.h",
759 # Hardware specific headers
760 "arm_neon.h",
761 "emmintrin.h",
762 "xmmintin.h",
763 ]
764 )
765
766 # Folders of C libraries so commonly used in C++,
767 # that they have parity with standard C libraries.
768 C_STANDARD_HEADER_FOLDERS = frozenset(
769 [
770 # standard C library
771 "sys",
772 # glibc for linux
773 "arpa",
774 "asm-generic",
775 "bits",
776 "gnu",
777 "net",
778 "netinet",
779 "protocols",
780 "rpc",
781 "rpcsvc",
782 "scsi",
783 # linux kernel header
784 "drm",
785 "linux",
786 "misc",
787 "mtd",
788 "rdma",
789 "sound",
790 "video",
791 "xen",
792 ]
793 )
794
795 # Type names
796 _TYPES = re.compile(
797 r"^(?:"
798 # [dcl.type.simple]
799 r"(char(16_t|32_t)?)|wchar_t|"
800 r"bool|short|int|long|signed|unsigned|float|double|"
801 # [support.types]
802 r"(ptrdiff_t|size_t|max_align_t|nullptr_t)|"
803 # [cstdint.syn]
804 r"(u?int(_fast|_least)?(8|16|32|64)_t)|"
805 r"(u?int(max|ptr)_t)|"
806 r")$"
807 )
808
809
810 # These headers are excluded from [build/include] and [build/include_order]
811 # checks:
812 # - Anything not following google file name conventions (containing an
813 # uppercase character, such as Python.h or nsStringAPI.h, for example).
814 # - Lua headers.
815 _THIRD_PARTY_HEADERS_PATTERN = re.compile(r"^(?:[^/]*[A-Z][^/]*\.h|lua\.h|lauxlib\.h|lualib\.h)$")
816
817 # Pattern for matching FileInfo.BaseName() against test file name
818 _test_suffixes = ["_test", "_regtest", "_unittest"]
819 _TEST_FILE_SUFFIX = "(" + "|".join(_test_suffixes) + r")$"
820
821 # Pattern that matches only complete whitespace, possibly across multiple lines.
822 _EMPTY_CONDITIONAL_BODY_PATTERN = re.compile(r"^\s*$", re.DOTALL)
823
824 # Assertion macros. These are defined in base/logging.h and
825 # testing/base/public/gunit.h.
826 _CHECK_MACROS = [
827 "DCHECK",
828 "CHECK",
829 "EXPECT_TRUE",
830 "ASSERT_TRUE",
831 "EXPECT_FALSE",
832 "ASSERT_FALSE",
833 ]
834
835 # Replacement macros for CHECK/DCHECK/EXPECT_TRUE/EXPECT_FALSE
836 _CHECK_REPLACEMENT: dict[str, dict[str, str]] = {macro_var: {} for macro_var in _CHECK_MACROS}
837
838 for op, replacement in [
839 ("==", "EQ"),
840 ("!=", "NE"),
841 (">=", "GE"),
842 (">", "GT"),
843 ("<=", "LE"),
844 ("<", "LT"),
845 ]:
846 _CHECK_REPLACEMENT["DCHECK"][op] = f"DCHECK_{replacement}"
847 _CHECK_REPLACEMENT["CHECK"][op] = f"CHECK_{replacement}"
848 _CHECK_REPLACEMENT["EXPECT_TRUE"][op] = f"EXPECT_{replacement}"
849 _CHECK_REPLACEMENT["ASSERT_TRUE"][op] = f"ASSERT_{replacement}"
850
851 for op, inv_replacement in [
852 ("==", "NE"),
853 ("!=", "EQ"),
854 (">=", "LT"),
855 (">", "LE"),
856 ("<=", "GT"),
857 ("<", "GE"),
858 ]:
859 _CHECK_REPLACEMENT["EXPECT_FALSE"][op] = f"EXPECT_{inv_replacement}"
860 _CHECK_REPLACEMENT["ASSERT_FALSE"][op] = f"ASSERT_{inv_replacement}"
861
862 # Alternative tokens and their replacements. For full list, see section 2.5
863 # Alternative tokens [lex.digraph] in the C++ standard.
864 #
865 # Digraphs (such as '%:') are not included here since it's a mess to
866 # match those on a word boundary.
867 _ALT_TOKEN_REPLACEMENT = {
868 "and": "&&",
869 "bitor": "|",
870 "or": "||",
871 "xor": "^",
872 "compl": "~",
873 "bitand": "&",
874 "and_eq": "&=",
875 "or_eq": "|=",
876 "xor_eq": "^=",
877 "not": "!",
878 "not_eq": "!=",
879 }
880
881 # Compile regular expression that matches all the above keywords. The "[ =()]"
882 # bit is meant to avoid matching these keywords outside of boolean expressions.
883 #
884 # False positives include C-style multi-line comments and multi-line strings
885 # but those have always been troublesome for cpplint.
886 _ALT_TOKEN_REPLACEMENT_PATTERN = re.compile(
887 r"([ =()])(" + ("|".join(_ALT_TOKEN_REPLACEMENT.keys())) + r")([ (]|$)"
888 )
889
890
891 # These constants define types of headers for use with
892 # _IncludeState.CheckNextIncludeOrder().
893 _C_SYS_HEADER = 1
894 _CPP_SYS_HEADER = 2
895 _OTHER_SYS_HEADER = 3
896 _LIKELY_MY_HEADER = 4
897 _POSSIBLE_MY_HEADER = 5
898 _OTHER_HEADER = 6
899
900 # These constants define the current inline assembly state
901 _NO_ASM = 0 # Outside of inline assembly block
902 _INSIDE_ASM = 1 # Inside inline assembly block
903 _END_ASM = 2 # Last line of inline assembly block
904 _BLOCK_ASM = 3 # The whole block is an inline assembly block
905
906 # Match start of assembly blocks
907 _MATCH_ASM = re.compile(
908 r"^\s*(?:asm|_asm|__asm|__asm__)"
909 r"(?:\s+(volatile|__volatile__))?"
910 r"\s*[{(]"
911 )
912
913 # Match strings that indicate we're working on a C (not C++) file.
914 _SEARCH_C_FILE = re.compile(
915 r"\b(?:LINT_C_FILE|"
916 r"vim?:\s*.*(\s*|:)filetype=c(\s*|:|$))"
917 )
918
919 # Match string that indicates we're working on a Linux Kernel file.
920 _SEARCH_KERNEL_FILE = re.compile(r"\b(?:LINT_KERNEL_FILE)")
921
922 # Commands for sed to fix the problem
923 _SED_FIXUPS = {
924 "Remove spaces around =": r"s/ = /=/",
925 "Remove spaces around !=": r"s/ != /!=/",
926 "Remove space before ( in if (": r"s/if (/if(/",
927 "Remove space before ( in for (": r"s/for (/for(/",
928 "Remove space before ( in while (": r"s/while (/while(/",
929 "Remove space before ( in switch (": r"s/switch (/switch(/",
930 "Should have a space between // and comment": r"s/\/\//\/\/ /",
931 "Missing space before {": r"s/\([^ ]\){/\1 {/",
932 "Tab found, replace by spaces": r"s/\t/ /g",
933 "Line ends in whitespace. Consider deleting these extra spaces.": r"s/\s*$//",
934 "You don't need a ; after a }": r"s/};/}/",
935 "Missing space after ,": r"s/,\([^ ]\)/, \1/g",
936 }
937
938 # The root directory used for deriving header guard CPP variable.
939 # This is set by --root flag.
940 _root = None
941 _root_debug = False
942
943 # The top level repository directory. If set, _root is calculated relative to
944 # this directory instead of the directory containing version control artifacts.
945 # This is set by the --repository flag.
946 _repository = None
947
948 # Files to exclude from linting. This is set by the --exclude flag.
949 _excludes = None
950
951 # Whether to suppress all PrintInfo messages, UNRELATED to --quiet flag
952 _quiet = False
953
954 # The allowed line length of files.
955 # This is set by --linelength flag.
956 _line_length = 80
957
958 # This allows to use different include order rule than default
959 _include_order = "default"
960
961 # This allows different config files to be used
962 _config_filename = "CPPLINT.cfg"
963
964 # Treat all headers starting with 'h' equally: .h, .hpp, .hxx etc.
965 # This is set by --headers flag.
966 _hpp_headers: set[str] = set()
967
968
969 class ErrorSuppressions:
970 """Class to track all error suppressions for cpplint"""
971
972 class LineRange:
973 """Class to represent a range of line numbers for which an error is suppressed"""
974
975 def __init__(self, begin, end):
976 self.begin = begin
977 self.end = end
978
979 def __str__(self):
980 return f"[{self.begin}-{self.end}]"
981
982 def __contains__(self, obj):
983 return self.begin <= obj <= self.end
984
985 def ContainsRange(self, other):
986 return self.begin <= other.begin and self.end >= other.end
987
988 def __init__(self):
989 self._suppressions = collections.defaultdict(list)
990 self._open_block_suppression = None
991
992 def _AddSuppression(self, category, line_range):
993 suppressed = self._suppressions[category]
994 if not (suppressed and suppressed[-1].ContainsRange(line_range)):
995 suppressed.append(line_range)
996
997 def GetOpenBlockStart(self):
998 """:return: The start of the current open block or `-1` if there is not an open block"""
999 return self._open_block_suppression.begin if self._open_block_suppression else -1
1000
1001 def AddGlobalSuppression(self, category):
1002 """Add a suppression for `category` which is suppressed for the whole file"""
1003 self._AddSuppression(category, self.LineRange(0, math.inf))
1004
1005 def AddLineSuppression(self, category, linenum):
1006 """Add a suppression for `category` which is suppressed only on `linenum`"""
1007 self._AddSuppression(category, self.LineRange(linenum, linenum))
1008
1009 def StartBlockSuppression(self, category, linenum):
1010 """Start a suppression block for `category` on `linenum`. inclusive"""
1011 if self._open_block_suppression is None:
1012 self._open_block_suppression = self.LineRange(linenum, math.inf)
1013 self._AddSuppression(category, self._open_block_suppression)
1014
1015 def EndBlockSuppression(self, linenum):
1016 """End the current block suppression on `linenum`. inclusive"""
1017 if self._open_block_suppression:
1018 self._open_block_suppression.end = linenum
1019 self._open_block_suppression = None
1020
1021 def IsSuppressed(self, category, linenum):
1022 """:return: `True` if `category` is suppressed for `linenum`"""
1023 suppressed = self._suppressions[category] + self._suppressions[None]
1024 return any(linenum in lr for lr in suppressed)
1025
1026 def HasOpenBlock(self):
1027 """:return: `True` if a block suppression was started but not ended"""
1028 return self._open_block_suppression is not None
1029
1030 def Clear(self):
1031 """Clear all current error suppressions"""
1032 self._suppressions.clear()
1033 self._open_block_suppression = None
1034
1035
1036 # {str, set(int)}: a map from error categories to sets of linenumbers
1037 # on which those errors are expected and should be suppressed.
1038 _error_suppressions = ErrorSuppressions()
1039
1040
1041 def ProcessHppHeadersOption(val):
1042 global _hpp_headers
1043 try:
1044 _hpp_headers = {ext.strip() for ext in val.split(",")}
1045 except ValueError:
1046 PrintUsage("Header extensions must be comma separated list.")
1047
1048
1049 def ProcessIncludeOrderOption(val):
1050 if val is None or val == "default":
1051 pass
1052 elif val == "standardcfirst":
1053 global _include_order
1054 _include_order = val
1055 else:
1056 PrintUsage("Invalid includeorder value %s. Expected default|standardcfirst")
1057
1058
1059 def IsHeaderExtension(file_extension):
1060 return file_extension in GetHeaderExtensions()
1061
1062
1063 def GetHeaderExtensions():
1064 if _hpp_headers:
1065 return _hpp_headers
1066 if _valid_extensions:
1067 return {h for h in _valid_extensions if "h" in h}
1068 return {"h", "hh", "hpp", "hxx", "h++", "cuh"}
1069
1070
1071 # The allowed extensions for file names
1072 # This is set by --extensions flag
1073 def GetAllExtensions():
1074 return GetHeaderExtensions().union(_valid_extensions or {"c", "cc", "cpp", "cxx", "c++", "cu"})
1075
1076
1077 def ProcessExtensionsOption(val):
1078 global _valid_extensions
1079 try:
1080 extensions = [ext.strip() for ext in val.split(",")]
1081 _valid_extensions = set(extensions)
1082 except ValueError:
1083 PrintUsage(
1084 "Extensions should be a comma-separated list of values;"
1085 "for example: extensions=hpp,cpp\n"
1086 f'This could not be parsed: "{val}"'
1087 )
1088
1089
1090 def GetNonHeaderExtensions():
1091 return GetAllExtensions().difference(GetHeaderExtensions())
1092
1093
1094 def ParseNolintSuppressions(filename, raw_line, linenum, error):
1095 """Updates the global list of line error-suppressions.
1096
1097 Parses any NOLINT comments on the current line, updating the global
1098 error_suppressions store. Reports an error if the NOLINT comment
1099 was malformed.
1100
1101 Args:
1102 filename: str, the name of the input file.
1103 raw_line: str, the line of input text, with comments.
1104 linenum: int, the number of the current line.
1105 error: function, an error handler.
1106 """
1107 if matched := re.search(r"\bNOLINT(NEXTLINE|BEGIN|END)?\b(\([^)]+\))?", raw_line):
1108 no_lint_type = matched.group(1)
1109 if no_lint_type == "NEXTLINE":
1110
1111 def ProcessCategory(category):
1112 _error_suppressions.AddLineSuppression(category, linenum + 1)
1113 elif no_lint_type == "BEGIN":
1114 if _error_suppressions.HasOpenBlock():
1115 error(
1116 filename,
1117 linenum,
1118 "readability/nolint",
1119 5,
1120 (
1121 "NONLINT block already defined on line "
1122 f"{_error_suppressions.GetOpenBlockStart()}"
1123 ),
1124 )
1125
1126 def ProcessCategory(category):
1127 _error_suppressions.StartBlockSuppression(category, linenum)
1128 elif no_lint_type == "END":
1129 if not _error_suppressions.HasOpenBlock():
1130 error(filename, linenum, "readability/nolint", 5, "Not in a NOLINT block")
1131
1132 def ProcessCategory(category):
1133 if category is not None:
1134 error(
1135 filename,
1136 linenum,
1137 "readability/nolint",
1138 5,
1139 f"NOLINT categories not supported in block END: {category}",
1140 )
1141 _error_suppressions.EndBlockSuppression(linenum)
1142 else:
1143
1144 def ProcessCategory(category):
1145 _error_suppressions.AddLineSuppression(category, linenum)
1146
1147 categories = matched.group(2)
1148 if categories in (None, "(*)"): # => "suppress all"
1149 ProcessCategory(None)
1150 elif categories.startswith("(") and categories.endswith(")"):
1151 for category in {c.strip() for c in categories[1:-1].split(",")}:
1152 if category in _ERROR_CATEGORIES:
1153 ProcessCategory(category)
1154 elif any(c for c in _OTHER_NOLINT_CATEGORY_PREFIXES if category.startswith(c)):
1155 # Ignore any categories from other tools.
1156 pass
1157 elif category not in _LEGACY_ERROR_CATEGORIES:
1158 error(
1159 filename,
1160 linenum,
1161 "readability/nolint",
1162 5,
1163 f"Unknown NOLINT error category: {category}",
1164 )
1165
1166
1167 def ProcessGlobalSuppressions(filename: str, lines: list[str]) -> None:
1168 """Updates the list of global error suppressions.
1169
1170 Parses any lint directives in the file that have global effect.
1171
1172 Args:
1173 lines: An array of strings, each representing a line of the file, with the
1174 last element being empty if the file is terminated with a newline.
1175 filename: str, the name of the input file.
1176 """
1177 for line in lines:
1178 if _SEARCH_C_FILE.search(line) or filename.lower().endswith((".c", ".cu")):
1179 for category in _DEFAULT_C_SUPPRESSED_CATEGORIES:
1180 _error_suppressions.AddGlobalSuppression(category)
1181 if _SEARCH_KERNEL_FILE.search(line):
1182 for category in _DEFAULT_KERNEL_SUPPRESSED_CATEGORIES:
1183 _error_suppressions.AddGlobalSuppression(category)
1184
1185
1186 def ResetNolintSuppressions():
1187 """Resets the set of NOLINT suppressions to empty."""
1188 _error_suppressions.Clear()
1189
1190
1191 def IsErrorSuppressedByNolint(category, linenum):
1192 """Returns true if the specified error category is suppressed on this line.
1193
1194 Consults the global error_suppressions map populated by
1195 ParseNolintSuppressions/ProcessGlobalSuppressions/ResetNolintSuppressions.
1196
1197 Args:
1198 category: str, the category of the error.
1199 linenum: int, the current line number.
1200 Returns:
1201 bool, True iff the error should be suppressed due to a NOLINT comment,
1202 block suppression or global suppression.
1203 """
1204 return _error_suppressions.IsSuppressed(category, linenum)
1205
1206
1207 def _IsSourceExtension(s):
1208 """File extension (excluding dot) matches a source file extension."""
1209 return s in GetNonHeaderExtensions()
1210
1211
1212 class _IncludeState:
1213 """Tracks line numbers for includes, and the order in which includes appear.
1214
1215 include_list contains list of lists of (header, line number) pairs.
1216 It's a lists of lists rather than just one flat list to make it
1217 easier to update across preprocessor boundaries.
1218
1219 Call CheckNextIncludeOrder() once for each header in the file, passing
1220 in the type constants defined above. Calls in an illegal order will
1221 raise an _IncludeError with an appropriate error message.
1222
1223 """
1224
1225 # self._section will move monotonically through this set. If it ever
1226 # needs to move backwards, CheckNextIncludeOrder will raise an error.
1227 _INITIAL_SECTION = 0
1228 _MY_H_SECTION = 1
1229 _C_SECTION = 2
1230 _CPP_SECTION = 3
1231 _OTHER_SYS_SECTION = 4
1232 _OTHER_H_SECTION = 5
1233
1234 _TYPE_NAMES = {
1235 _C_SYS_HEADER: "C system header",
1236 _CPP_SYS_HEADER: "C++ system header",
1237 _OTHER_SYS_HEADER: "other system header",
1238 _LIKELY_MY_HEADER: "header this file implements",
1239 _POSSIBLE_MY_HEADER: "header this file may implement",
1240 _OTHER_HEADER: "other header",
1241 }
1242 _SECTION_NAMES = {
1243 _INITIAL_SECTION: "... nothing. (This can't be an error.)",
1244 _MY_H_SECTION: "a header this file implements",
1245 _C_SECTION: "C system header",
1246 _CPP_SECTION: "C++ system header",
1247 _OTHER_SYS_SECTION: "other system header",
1248 _OTHER_H_SECTION: "other header",
1249 }
1250
1251 def __init__(self):
1252 self.include_list = [[]]
1253 self._section = None
1254 self._last_header = None
1255 self.ResetSection("")
1256
1257 def FindHeader(self, header):
1258 """Check if a header has already been included.
1259
1260 Args:
1261 header: header to check.
1262 Returns:
1263 Line number of previous occurrence, or -1 if the header has not
1264 been seen before.
1265 """
1266 for section_list in self.include_list:
1267 for f in section_list:
1268 if f[0] == header:
1269 return f[1]
1270 return -1
1271
1272 def ResetSection(self, directive):
1273 """Reset section checking for preprocessor directive.
1274
1275 Args:
1276 directive: preprocessor directive (e.g. "if", "else").
1277 """
1278 # The name of the current section.
1279 self._section = self._INITIAL_SECTION
1280 # The path of last found header.
1281 self._last_header = ""
1282
1283 # Update list of includes. Note that we never pop from the
1284 # include list.
1285 if directive in ("if", "ifdef", "ifndef"):
1286 self.include_list.append([])
1287 elif directive in ("else", "elif"):
1288 self.include_list[-1] = []
1289
1290 def SetLastHeader(self, header_path):
1291 self._last_header = header_path
1292
1293 def CanonicalizeAlphabeticalOrder(self, header_path):
1294 """Returns a path canonicalized for alphabetical comparison.
1295
1296 - replaces "-" with "_" so they both cmp the same.
1297 - removes '-inl' since we don't require them to be after the main header.
1298 - lowercase everything, just in case.
1299
1300 Args:
1301 header_path: Path to be canonicalized.
1302
1303 Returns:
1304 Canonicalized path.
1305 """
1306 return header_path.replace("-inl.h", ".h").replace("-", "_").lower()
1307
1308 def IsInAlphabeticalOrder(self, clean_lines, linenum, header_path):
1309 """Check if a header is in alphabetical order with the previous header.
1310
1311 Args:
1312 clean_lines: A CleansedLines instance containing the file.
1313 linenum: The number of the line to check.
1314 header_path: Canonicalized header to be checked.
1315
1316 Returns:
1317 Returns true if the header is in alphabetical order.
1318 """
1319 # If previous section is different from current section, _last_header will
1320 # be reset to empty string, so it's always less than current header.
1321 #
1322 # If previous line was a blank line, assume that the headers are
1323 # intentionally sorted the way they are.
1324 return not (
1325 self._last_header > header_path
1326 and re.match(r"^\s*#\s*include\b", clean_lines.elided[linenum - 1])
1327 )
1328
1329 def CheckNextIncludeOrder(self, header_type):
1330 """Returns a non-empty error message if the next header is out of order.
1331
1332 This function also updates the internal state to be ready to check
1333 the next include.
1334
1335 Args:
1336 header_type: One of the _XXX_HEADER constants defined above.
1337
1338 Returns:
1339 The empty string if the header is in the right order, or an
1340 error message describing what's wrong.
1341
1342 """
1343 error_message = (
1344 f"Found {self._TYPE_NAMES[header_type]} after {self._SECTION_NAMES[self._section]}"
1345 )
1346
1347 last_section = self._section
1348
1349 if header_type == _C_SYS_HEADER:
1350 if self._section <= self._C_SECTION:
1351 self._section = self._C_SECTION
1352 else:
1353 self._last_header = ""
1354 return error_message
1355 elif header_type == _CPP_SYS_HEADER:
1356 if self._section <= self._CPP_SECTION:
1357 self._section = self._CPP_SECTION
1358 else:
1359 self._last_header = ""
1360 return error_message
1361 elif header_type == _OTHER_SYS_HEADER:
1362 if self._section <= self._OTHER_SYS_SECTION:
1363 self._section = self._OTHER_SYS_SECTION
1364 else:
1365 self._last_header = ""
1366 return error_message
1367 elif header_type == _LIKELY_MY_HEADER:
1368 if self._section <= self._MY_H_SECTION:
1369 self._section = self._MY_H_SECTION
1370 else:
1371 self._section = self._OTHER_H_SECTION
1372 elif header_type == _POSSIBLE_MY_HEADER:
1373 if self._section <= self._MY_H_SECTION:
1374 self._section = self._MY_H_SECTION
1375 else:
1376 # This will always be the fallback because we're not sure
1377 # enough that the header is associated with this file.
1378 self._section = self._OTHER_H_SECTION
1379 else:
1380 assert header_type == _OTHER_HEADER
1381 self._section = self._OTHER_H_SECTION
1382
1383 if last_section != self._section:
1384 self._last_header = ""
1385
1386 return ""
1387
1388
1389 class _CppLintState:
1390 """Maintains module-wide state.."""
1391
1392 def __init__(self):
1393 self.verbose_level = 1 # global setting.
1394 self.error_count = 0 # global count of reported errors
1395 # filters to apply when emitting error messages
1396 self.filters = _DEFAULT_FILTERS[:]
1397 # backup of filter list. Used to restore the state after each file.
1398 self._filters_backup = self.filters[:]
1399 self.counting = "total" # In what way are we counting errors?
1400 self.errors_by_category = {} # string to int dict storing error counts
1401 self.quiet = False # Suppress non-error messages?
1402
1403 # output format:
1404 # "emacs" - format that emacs can parse (default)
1405 # "eclipse" - format that eclipse can parse
1406 # "vs7" - format that Microsoft Visual Studio 7 can parse
1407 # "junit" - format that Jenkins, Bamboo, etc can parse
1408 # "sed" - returns a gnu sed command to fix the problem
1409 # "gsed" - like sed, but names the command gsed, e.g. for macOS homebrew users
1410 self.output_format = "emacs"
1411
1412 # For JUnit output, save errors and failures until the end so that they
1413 # can be written into the XML
1414 self._junit_errors = []
1415 self._junit_failures = []
1416
1417 def SetOutputFormat(self, output_format):
1418 """Sets the output format for errors."""
1419 self.output_format = output_format
1420
1421 def SetQuiet(self, quiet):
1422 """Sets the module's quiet settings, and returns the previous setting."""
1423 last_quiet = self.quiet
1424 self.quiet = quiet
1425 return last_quiet
1426
1427 def SetVerboseLevel(self, level):
1428 """Sets the module's verbosity, and returns the previous setting."""
1429 last_verbose_level = self.verbose_level
1430 self.verbose_level = level
1431 return last_verbose_level
1432
1433 def SetCountingStyle(self, counting_style):
1434 """Sets the module's counting options."""
1435 self.counting = counting_style
1436
1437 def SetFilters(self, filters):
1438 """Sets the error-message filters.
1439
1440 These filters are applied when deciding whether to emit a given
1441 error message.
1442
1443 Args:
1444 filters: A string of comma-separated filters (eg "+whitespace/indent").
1445 Each filter should start with + or -; else we die.
1446
1447 Raises:
1448 ValueError: The comma-separated filters did not all start with '+' or '-'.
1449 E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter"
1450 """
1451 # Default filters always have less priority than the flag ones.
1452 self.filters = _DEFAULT_FILTERS[:]
1453 self.AddFilters(filters)
1454
1455 def AddFilters(self, filters):
1456 """Adds more filters to the existing list of error-message filters."""
1457 for filt in filters.split(","):
1458 clean_filt = filt.strip()
1459 if clean_filt:
1460 self.filters.append(clean_filt)
1461 for filt in self.filters:
1462 if not filt.startswith(("+", "-")):
1463 msg = f"Every filter in --filters must start with + or - ({filt} does not)"
1464 raise ValueError(msg)
1465
1466 def BackupFilters(self):
1467 """Saves the current filter list to backup storage."""
1468 self._filters_backup = self.filters[:]
1469
1470 def RestoreFilters(self):
1471 """Restores filters previously backed up."""
1472 self.filters = self._filters_backup[:]
1473
1474 def ResetErrorCounts(self):
1475 """Sets the module's error statistic back to zero."""
1476 self.error_count = 0
1477 self.errors_by_category = {}
1478
1479 def IncrementErrorCount(self, category):
1480 """Bumps the module's error statistic."""
1481 self.error_count += 1
1482 if self.counting in ("toplevel", "detailed"):
1483 if self.counting != "detailed":
1484 category = category.split("/")[0]
1485 if category not in self.errors_by_category:
1486 self.errors_by_category[category] = 0
1487 self.errors_by_category[category] += 1
1488
1489 def PrintErrorCounts(self):
1490 """Print a summary of errors by category, and the total."""
1491 for category, count in sorted(dict.items(self.errors_by_category)):
1492 self.PrintInfo(f"Category '{category}' errors found: {count}\n")
1493 if self.error_count > 0:
1494 self.PrintInfo(f"Total errors found: {self.error_count}\n")
1495
1496 def PrintInfo(self, message):
1497 # _quiet does not represent --quiet flag.
1498 # Hide infos from stdout to keep stdout pure for machine consumption
1499 if not _quiet and self.output_format not in _MACHINE_OUTPUTS:
1500 sys.stdout.write(message)
1501
1502 def PrintError(self, message):
1503 if self.output_format == "junit":
1504 self._junit_errors.append(message)
1505 else:
1506 sys.stderr.write(message)
1507
1508 def AddJUnitFailure(self, filename, linenum, message, category, confidence):
1509 self._junit_failures.append((filename, linenum, message, category, confidence))
1510
1511 def FormatJUnitXML(self):
1512 num_errors = len(self._junit_errors)
1513 num_failures = len(self._junit_failures)
1514
1515 testsuite = xml.etree.ElementTree.Element("testsuite")
1516 testsuite.attrib["errors"] = str(num_errors)
1517 testsuite.attrib["failures"] = str(num_failures)
1518 testsuite.attrib["name"] = "cpplint"
1519
1520 if num_errors == 0 and num_failures == 0:
1521 testsuite.attrib["tests"] = str(1)
1522 xml.etree.ElementTree.SubElement(testsuite, "testcase", name="passed")
1523
1524 else:
1525 testsuite.attrib["tests"] = str(num_errors + num_failures)
1526 if num_errors > 0:
1527 testcase = xml.etree.ElementTree.SubElement(testsuite, "testcase")
1528 testcase.attrib["name"] = "errors"
1529 error = xml.etree.ElementTree.SubElement(testcase, "error")
1530 error.text = "\n".join(self._junit_errors)
1531 if num_failures > 0:
1532 # Group failures by file
1533 failed_file_order = []
1534 failures_by_file = {}
1535 for failure in self._junit_failures:
1536 failed_file = failure[0]
1537 if failed_file not in failed_file_order:
1538 failed_file_order.append(failed_file)
1539 failures_by_file[failed_file] = []
1540 failures_by_file[failed_file].append(failure)
1541 # Create a testcase for each file
1542 for failed_file in failed_file_order:
1543 failures = failures_by_file[failed_file]
1544 testcase = xml.etree.ElementTree.SubElement(testsuite, "testcase")
1545 testcase.attrib["name"] = failed_file
1546 failure = xml.etree.ElementTree.SubElement(testcase, "failure")
1547 template = "{0}: {1} [{2}] [{3}]"
1548 texts = [template.format(f[1], f[2], f[3], f[4]) for f in failures]
1549 failure.text = "\n".join(texts)
1550
1551 xml_decl = '<?xml version="1.0" encoding="UTF-8" ?>\n'
1552 return xml_decl + xml.etree.ElementTree.tostring(testsuite, "utf-8").decode("utf-8")
1553
1554
1555 _cpplint_state = _CppLintState()
1556
1557
1558 def _OutputFormat():
1559 """Gets the module's output format."""
1560 return _cpplint_state.output_format
1561
1562
1563 def _SetOutputFormat(output_format):
1564 """Sets the module's output format."""
1565 _cpplint_state.SetOutputFormat(output_format)
1566
1567
1568 def _Quiet():
1569 """Return's the module's quiet setting."""
1570 return _cpplint_state.quiet
1571
1572
1573 def _SetQuiet(quiet):
1574 """Set the module's quiet status, and return previous setting."""
1575 return _cpplint_state.SetQuiet(quiet)
1576
1577
1578 def _VerboseLevel():
1579 """Returns the module's verbosity setting."""
1580 return _cpplint_state.verbose_level
1581
1582
1583 def _SetVerboseLevel(level):
1584 """Sets the module's verbosity, and returns the previous setting."""
1585 return _cpplint_state.SetVerboseLevel(level)
1586
1587
1588 def _SetCountingStyle(level):
1589 """Sets the module's counting options."""
1590 _cpplint_state.SetCountingStyle(level)
1591
1592
1593 def _Filters():
1594 """Returns the module's list of output filters, as a list."""
1595 return _cpplint_state.filters
1596
1597
1598 def _SetFilters(filters):
1599 """Sets the module's error-message filters.
1600
1601 These filters are applied when deciding whether to emit a given
1602 error message.
1603
1604 Args:
1605 filters: A string of comma-separated filters (eg "whitespace/indent").
1606 Each filter should start with + or -; else we die.
1607 """
1608 _cpplint_state.SetFilters(filters)
1609
1610
1611 def _AddFilters(filters):
1612 """Adds more filter overrides.
1613
1614 Unlike _SetFilters, this function does not reset the current list of filters
1615 available.
1616
1617 Args:
1618 filters: A string of comma-separated filters (eg "whitespace/indent").
1619 Each filter should start with + or -; else we die.
1620 """
1621 _cpplint_state.AddFilters(filters)
1622
1623
1624 def _BackupFilters():
1625 """Saves the current filter list to backup storage."""
1626 _cpplint_state.BackupFilters()
1627
1628
1629 def _RestoreFilters():
1630 """Restores filters previously backed up."""
1631 _cpplint_state.RestoreFilters()
1632
1633
1634 class _FunctionState:
1635 """Tracks current function name and the number of lines in its body."""
1636
1637 _NORMAL_TRIGGER = 250 # for --v=0, 500 for --v=1, etc.
1638 _TEST_TRIGGER = 400 # about 50% more than _NORMAL_TRIGGER.
1639
1640 def __init__(self):
1641 self.in_a_function = False
1642 self.lines_in_function = 0
1643 self.current_function = ""
1644
1645 def Begin(self, function_name):
1646 """Start analyzing function body.
1647
1648 Args:
1649 function_name: The name of the function being tracked.
1650 """
1651 self.in_a_function = True
1652 self.lines_in_function = 0
1653 self.current_function = function_name
1654
1655 def Count(self):
1656 """Count line in current function body."""
1657 if self.in_a_function:
1658 self.lines_in_function += 1
1659
1660 def Check(self, error, filename, linenum):
1661 """Report if too many lines in function body.
1662
1663 Args:
1664 error: The function to call with any errors found.
1665 filename: The name of the current file.
1666 linenum: The number of the line to check.
1667 """
1668 if not self.in_a_function:
1669 return
1670
1671 if re.match(r"T(EST|est)", self.current_function):
1672 base_trigger = self._TEST_TRIGGER
1673 else:
1674 base_trigger = self._NORMAL_TRIGGER
1675 trigger = base_trigger * 2 ** _VerboseLevel()
1676
1677 if self.lines_in_function > trigger:
1678 error_level = int(math.log2(self.lines_in_function / base_trigger))
1679 # 50 => 0, 100 => 1, 200 => 2, 400 => 3, 800 => 4, 1600 => 5, ...
1680 error_level = min(error_level, 5)
1681 error(
1682 filename,
1683 linenum,
1684 "readability/fn_size",
1685 error_level,
1686 "Small and focused functions are preferred:"
1687 f" {self.current_function} has {self.lines_in_function} non-comment lines"
1688 f" (error triggered by exceeding {trigger} lines).",
1689 )
1690
1691 def End(self):
1692 """Stop analyzing function body."""
1693 self.in_a_function = False
1694
1695
1696 class _IncludeError(Exception):
1697 """Indicates a problem with the include order in a file."""
1698
1699 pass
1700
1701
1702 class FileInfo:
1703 """Provides utility functions for filenames.
1704
1705 FileInfo provides easy access to the components of a file's path
1706 relative to the project root.
1707 """
1708
1709 def __init__(self, filename):
1710 self._filename = filename
1711
1712 def FullName(self):
1713 """Make Windows paths like Unix."""
1714 return os.path.abspath(self._filename).replace("\\", "/")
1715
1716 def RepositoryName(self):
1717 r"""FullName after removing the local path to the repository.
1718
1719 If we have a real absolute path name here we can try to do something smart:
1720 detecting the root of the checkout and truncating /path/to/checkout from
1721 the name so that we get header guards that don't include things like
1722 "C:\\Documents and Settings\\..." or "/home/username/..." in them and thus
1723 people on different computers who have checked the source out to different
1724 locations won't see bogus errors.
1725 """
1726 fullname = self.FullName()
1727
1728 if os.path.exists(fullname):
1729 project_dir = os.path.dirname(fullname)
1730
1731 # If the user specified a repository path, it exists, and the file is
1732 # contained in it, use the specified repository path
1733 if _repository:
1734 repo = FileInfo(_repository).FullName()
1735 root_dir = project_dir
1736 while os.path.exists(root_dir):
1737 # allow case insensitive compare on Windows
1738 if os.path.normcase(root_dir) == os.path.normcase(repo):
1739 return os.path.relpath(fullname, root_dir).replace("\\", "/")
1740 one_up_dir = os.path.dirname(root_dir)
1741 if one_up_dir == root_dir:
1742 break
1743 root_dir = one_up_dir
1744
1745 if os.path.exists(os.path.join(project_dir, ".svn")):
1746 # If there's a .svn file in the current directory, we recursively look
1747 # up the directory tree for the top of the SVN checkout
1748 root_dir = project_dir
1749 one_up_dir = os.path.dirname(root_dir)
1750 while os.path.exists(os.path.join(one_up_dir, ".svn")):
1751 root_dir = os.path.dirname(root_dir)
1752 one_up_dir = os.path.dirname(one_up_dir)
1753
1754 prefix = os.path.commonprefix([root_dir, project_dir])
1755 return fullname[len(prefix) + 1 :]
1756
1757 # Not SVN <= 1.6? Try to find a git, hg, or svn top level directory by
1758 # searching up from the current path.
1759 root_dir = current_dir = os.path.dirname(fullname)
1760 while current_dir != os.path.dirname(current_dir):
1761 if (
1762 os.path.exists(os.path.join(current_dir, ".git"))
1763 or os.path.exists(os.path.join(current_dir, ".hg"))
1764 or os.path.exists(os.path.join(current_dir, ".svn"))
1765 ):
1766 root_dir = current_dir
1767 break
1768 current_dir = os.path.dirname(current_dir)
1769
1770 if (
1771 os.path.exists(os.path.join(root_dir, ".git"))
1772 or os.path.exists(os.path.join(root_dir, ".hg"))
1773 or os.path.exists(os.path.join(root_dir, ".svn"))
1774 ):
1775 prefix = os.path.commonprefix([root_dir, project_dir])
1776 return fullname[len(prefix) + 1 :]
1777
1778 # Don't know what to do; header guard warnings may be wrong...
1779 return fullname
1780
1781 def Split(self):
1782 """Splits the file into the directory, basename, and extension.
1783
1784 For 'chrome/browser/browser.cc', Split() would
1785 return ('chrome/browser', 'browser', '.cc')
1786
1787 Returns:
1788 A tuple of (directory, basename, extension).
1789 """
1790
1791 googlename = self.RepositoryName()
1792 project, rest = os.path.split(googlename)
1793 return (project,) + os.path.splitext(rest)
1794
1795 def BaseName(self):
1796 """File base name - text after the final slash, before the final period."""
1797 return self.Split()[1]
1798
1799 def Extension(self):
1800 """File extension - text following the final period, includes that period."""
1801 return self.Split()[2]
1802
1803 def NoExtension(self):
1804 """File has no source file extension."""
1805 return "/".join(self.Split()[0:2])
1806
1807 def IsSource(self):
1808 """File has a source file extension."""
1809 return _IsSourceExtension(self.Extension()[1:])
1810
1811
1812 def _ShouldPrintError(category, confidence, filename, linenum):
1813 """If confidence >= verbose, category passes filter and is not suppressed."""
1814
1815 # There are three ways we might decide not to print an error message:
1816 # a "NOLINT(category)" comment appears in the source,
1817 # the verbosity level isn't high enough, or the filters filter it out.
1818 if IsErrorSuppressedByNolint(category, linenum):
1819 return False
1820
1821 if confidence < _cpplint_state.verbose_level:
1822 return False
1823
1824 is_filtered = False
1825 for one_filter in _Filters():
1826 filter_cat, filter_file, filter_line = _ParseFilterSelector(one_filter[1:])
1827 category_match = category.startswith(filter_cat)
1828 file_match = filter_file in ("", filename)
1829 line_match = filter_line in (linenum, -1)
1830
1831 if one_filter.startswith("-"):
1832 if category_match and file_match and line_match:
1833 is_filtered = True
1834 elif one_filter.startswith("+"):
1835 if category_match and file_match and line_match:
1836 is_filtered = False
1837 else:
1838 # should have been checked for in SetFilter.
1839 msg = f"Invalid filter: {one_filter}"
1840 raise ValueError(msg)
1841 return not is_filtered
1842
1843
1844 def Error(filename, linenum, category, confidence, message):
1845 """Logs the fact we've found a lint error.
1846
1847 We log where the error was found, and also our confidence in the error,
1848 that is, how certain we are this is a legitimate style regression, and
1849 not a misidentification or a use that's sometimes justified.
1850
1851 False positives can be suppressed by the use of "NOLINT(category)"
1852 comments, NOLINTNEXTLINE or in blocks started by NOLINTBEGIN. These
1853 are parsed into _error_suppressions.
1854
1855 Args:
1856 filename: The name of the file containing the error.
1857 linenum: The number of the line containing the error.
1858 category: A string used to describe the "category" this bug
1859 falls under: "whitespace", say, or "runtime". Categories
1860 may have a hierarchy separated by slashes: "whitespace/indent".
1861 confidence: A number from 1-5 representing a confidence score for
1862 the error, with 5 meaning that we are certain of the problem,
1863 and 1 meaning that it could be a legitimate construct.
1864 message: The error message.
1865 """
1866 if _ShouldPrintError(category, confidence, filename, linenum):
1867 _cpplint_state.IncrementErrorCount(category)
1868 if _cpplint_state.output_format == "vs7":
1869 _cpplint_state.PrintError(
1870 f"{filename}({linenum}): error cpplint: [{category}] {message} [{confidence}]\n"
1871 )
1872 elif _cpplint_state.output_format == "eclipse":
1873 sys.stderr.write(
1874 f"{filename}:{linenum}: warning: {message} [{category}] [{confidence}]\n"
1875 )
1876 elif _cpplint_state.output_format == "junit":
1877 _cpplint_state.AddJUnitFailure(filename, linenum, message, category, confidence)
1878 elif _cpplint_state.output_format in ["sed", "gsed"]:
1879 if message in _SED_FIXUPS:
1880 sys.stdout.write(
1881 f"{_cpplint_state.output_format} -i"
1882 f" '{linenum}{_SED_FIXUPS[message]}' {filename}"
1883 f" # {message} [{category}] [{confidence}]\n"
1884 )
1885 else:
1886 sys.stderr.write(
1887 f'# {filename}:{linenum}: "{message}" [{category}] [{confidence}]\n'
1888 )
1889 else:
1890 final_message = f"{filename}:{linenum}: {message} [{category}] [{confidence}]\n"
1891 sys.stderr.write(final_message)
1892
1893
1894 # Matches standard C++ escape sequences per 2.13.2.3 of the C++ standard.
1895 _RE_PATTERN_CLEANSE_LINE_ESCAPES = re.compile(r'\\([abfnrtv?"\\\']|\d+|x[0-9a-fA-F]+)')
1896 # Match a single C style comment on the same line.
1897 _RE_PATTERN_C_COMMENTS = r"/\*(?:[^*]|\*(?!/))*\*/"
1898 # Matches multi-line C style comments.
1899 # This RE is a little bit more complicated than one might expect, because we
1900 # have to take care of space removals tools so we can handle comments inside
1901 # statements better.
1902 # The current rule is: We only clear spaces from both sides when we're at the
1903 # end of the line. Otherwise, we try to remove spaces from the right side,
1904 # if this doesn't work we try on left side but only if there's a non-character
1905 # on the right.
1906 _RE_PATTERN_CLEANSE_LINE_C_COMMENTS = re.compile(
1907 r"(\s*"
1908 + _RE_PATTERN_C_COMMENTS
1909 + r"\s*$|"
1910 + _RE_PATTERN_C_COMMENTS
1911 + r"\s+|"
1912 + r"\s+"
1913 + _RE_PATTERN_C_COMMENTS
1914 + r"(?=\W)|"
1915 + _RE_PATTERN_C_COMMENTS
1916 + r")"
1917 )
1918
1919
1920 def IsCppString(line):
1921 """Does line terminate so, that the next symbol is in string constant.
1922
1923 This function does not consider single-line nor multi-line comments.
1924
1925 Args:
1926 line: is a partial line of code starting from the 0..n.
1927
1928 Returns:
1929 True, if next character appended to 'line' is inside a
1930 string constant.
1931 """
1932
1933 line = line.replace(r"\\", "XX") # after this, \\" does not match to \"
1934 return ((line.count('"') - line.count(r"\"") - line.count("'\"'")) & 1) == 1
1935
1936
1937 def CleanseRawStrings(raw_lines):
1938 """Removes C++11 raw strings from lines.
1939
1940 Before:
1941 static const char kData[] = R"(
1942 multi-line string
1943 )";
1944
1945 After:
1946 static const char kData[] = ""
1947 (replaced by blank line)
1948 "";
1949
1950 Args:
1951 raw_lines: list of raw lines.
1952
1953 Returns:
1954 list of lines with C++11 raw strings replaced by empty strings.
1955 """
1956
1957 delimiter = None
1958 lines_without_raw_strings = []
1959 for line in raw_lines:
1960 if delimiter:
1961 # Inside a raw string, look for the end
1962 end = line.find(delimiter)
1963 if end >= 0:
1964 # Found the end of the string, match leading space for this
1965 # line and resume copying the original lines, and also insert
1966 # a "" on the last line.
1967 leading_space = re.match(r"^(\s*)\S", line)
1968 line = leading_space.group(1) + '""' + line[end + len(delimiter) :]
1969 delimiter = None
1970 else:
1971 # Haven't found the end yet, append a blank line.
1972 line = '""'
1973
1974 # Look for beginning of a raw string, and replace them with
1975 # empty strings. This is done in a loop to handle multiple raw
1976 # strings on the same line.
1977 while delimiter is None:
1978 # Look for beginning of a raw string.
1979 # See 2.14.15 [lex.string] for syntax.
1980 #
1981 # Once we have matched a raw string, we check the prefix of the
1982 # line to make sure that the line is not part of a single line
1983 # comment. It's done this way because we remove raw strings
1984 # before removing comments as opposed to removing comments
1985 # before removing raw strings. This is because there are some
1986 # cpplint checks that requires the comments to be preserved, but
1987 # we don't want to check comments that are inside raw strings.
1988 matched = re.match(r'^(.*?)\b(?:R|u8R|uR|UR|LR)"([^\s\\()]*)\((.*)$', line)
1989 if matched and not re.match(
1990 r'^([^\'"]|\'(\\.|[^\'])*\'|"(\\.|[^"])*")*//', matched.group(1)
1991 ):
1992 delimiter = ")" + matched.group(2) + '"'
1993
1994 end = matched.group(3).find(delimiter)
1995 if end >= 0:
1996 # Raw string ended on same line
1997 line = matched.group(1) + '""' + matched.group(3)[end + len(delimiter) :]
1998 delimiter = None
1999 else:
2000 # Start of a multi-line raw string
2001 line = matched.group(1) + '""'
2002 else:
2003 break
2004
2005 lines_without_raw_strings.append(line)
2006
2007 # TODO(google): if delimiter is not None here, we might want to
2008 # emit a warning for unterminated string.
2009 return lines_without_raw_strings
2010
2011
2012 def FindNextMultiLineCommentStart(lines, lineix):
2013 """Find the beginning marker for a multiline comment."""
2014 while lineix < len(lines):
2015 if lines[lineix].strip().startswith("/*"):
2016 # Only return this marker if the comment goes beyond this line
2017 if lines[lineix].strip().find("*/", 2) < 0:
2018 return lineix
2019 lineix += 1
2020 return len(lines)
2021
2022
2023 def FindNextMultiLineCommentEnd(lines, lineix):
2024 """We are inside a comment, find the end marker."""
2025 while lineix < len(lines):
2026 if lines[lineix].strip().endswith("*/"):
2027 return lineix
2028 lineix += 1
2029 return len(lines)
2030
2031
2032 def RemoveMultiLineCommentsFromRange(lines, begin, end):
2033 """Clears a range of lines for multi-line comments."""
2034 # Having // <empty> comments makes the lines non-empty, so we will not get
2035 # unnecessary blank line warnings later in the code.
2036 for i in range(begin, end):
2037 lines[i] = "/**/"
2038
2039
2040 def RemoveMultiLineComments(filename, lines, error):
2041 """Removes multiline (c-style) comments from lines."""
2042 lineix = 0
2043 while lineix < len(lines):
2044 lineix_begin = FindNextMultiLineCommentStart(lines, lineix)
2045 if lineix_begin >= len(lines):
2046 return
2047 lineix_end = FindNextMultiLineCommentEnd(lines, lineix_begin)
2048 if lineix_end >= len(lines):
2049 error(
2050 filename,
2051 lineix_begin + 1,
2052 "readability/multiline_comment",
2053 5,
2054 "Could not find end of multi-line comment",
2055 )
2056 return
2057 RemoveMultiLineCommentsFromRange(lines, lineix_begin, lineix_end + 1)
2058 lineix = lineix_end + 1
2059
2060
2061 def CleanseComments(line):
2062 """Removes //-comments and single-line C-style /* */ comments.
2063
2064 Args:
2065 line: A line of C++ source.
2066
2067 Returns:
2068 The line with single-line comments removed.
2069 """
2070 commentpos = line.find("//")
2071 if commentpos != -1 and not IsCppString(line[:commentpos]):
2072 line = line[:commentpos].rstrip()
2073 # get rid of /* ... */
2074 return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub("", line)
2075
2076
2077 def ReplaceAlternateTokens(line):
2078 """Replace any alternate token by its original counterpart.
2079
2080 In order to comply with the google rule stating that unary operators should
2081 never be followed by a space, an exception is made for the 'not' and 'compl'
2082 alternate tokens. For these, any trailing space is removed during the
2083 conversion.
2084
2085 Args:
2086 line: The line being processed.
2087
2088 Returns:
2089 The line with alternate tokens replaced.
2090 """
2091 for match in _ALT_TOKEN_REPLACEMENT_PATTERN.finditer(line):
2092 token = _ALT_TOKEN_REPLACEMENT[match.group(2)]
2093 tail = "" if match.group(2) in ["not", "compl"] and match.group(3) == " " else r"\3"
2094 line = re.sub(match.re, rf"\1{token}{tail}", line, count=1)
2095 return line
2096
2097
2098 class CleansedLines:
2099 """Holds 4 copies of all lines with different preprocessing applied to them.
2100
2101 1) elided member contains lines without strings and comments.
2102 2) lines member contains lines without comments.
2103 3) raw_lines member contains all the lines without processing.
2104 4) lines_without_raw_strings member is same as raw_lines, but with C++11 raw
2105 strings removed.
2106 All these members are of <type 'list'>, and of the same length.
2107 """
2108
2109 def __init__(self, lines):
2110 if "-readability/alt_tokens" in _cpplint_state.filters:
2111 for i, line in enumerate(lines):
2112 lines[i] = ReplaceAlternateTokens(line)
2113 self.elided = []
2114 self.lines = []
2115 self.raw_lines = lines
2116 self.num_lines = len(lines)
2117 self.lines_without_raw_strings = CleanseRawStrings(lines)
2118 for line in self.lines_without_raw_strings:
2119 self.lines.append(CleanseComments(line))
2120 elided = self._CollapseStrings(line)
2121 self.elided.append(CleanseComments(elided))
2122
2123 def NumLines(self):
2124 """Returns the number of lines represented."""
2125 return self.num_lines
2126
2127 @staticmethod
2128 def _CollapseStrings(elided):
2129 """Collapses strings and chars on a line to simple "" or '' blocks.
2130
2131 We nix strings first so we're not fooled by text like '"http://"'
2132
2133 Args:
2134 elided: The line being processed.
2135
2136 Returns:
2137 The line with collapsed strings.
2138 """
2139 if _RE_PATTERN_INCLUDE.match(elided):
2140 return elided
2141
2142 # Remove escaped characters first to make quote/single quote collapsing
2143 # basic. Things that look like escaped characters shouldn't occur
2144 # outside of strings and chars.
2145 elided = _RE_PATTERN_CLEANSE_LINE_ESCAPES.sub("", elided)
2146
2147 # Replace quoted strings and digit separators. Both single quotes
2148 # and double quotes are processed in the same loop, otherwise
2149 # nested quotes wouldn't work.
2150 collapsed = ""
2151 while True:
2152 # Find the first quote character
2153 match = re.match(r'^([^\'"]*)([\'"])(.*)$', elided)
2154 if not match:
2155 collapsed += elided
2156 break
2157 head, quote, tail = match.groups()
2158
2159 if quote == '"':
2160 # Collapse double quoted strings
2161 second_quote = tail.find('"')
2162 if second_quote >= 0:
2163 collapsed += head + '""'
2164 elided = tail[second_quote + 1 :]
2165 else:
2166 # Unmatched double quote, don't bother processing the rest
2167 # of the line since this is probably a multiline string.
2168 collapsed += elided
2169 break
2170 else:
2171 # Found single quote, check nearby text to eliminate digit separators.
2172 #
2173 # There is no special handling for floating point here, because
2174 # the integer/fractional/exponent parts would all be parsed
2175 # correctly as long as there are digits on both sides of the
2176 # separator. So we are fine as long as we don't see something
2177 # like "0.'3" (gcc 4.9.0 will not allow this literal).
2178 if re.search(r"\b(?:0[bBxX]?|[1-9])[0-9a-fA-F]*$", head):
2179 match_literal = re.match(r"^((?:\'?[0-9a-zA-Z_])*)(.*)$", "'" + tail)
2180 collapsed += head + match_literal.group(1).replace("'", "")
2181 elided = match_literal.group(2)
2182 else:
2183 second_quote = tail.find("'")
2184 if second_quote >= 0:
2185 collapsed += head + "''"
2186 elided = tail[second_quote + 1 :]
2187 else:
2188 # Unmatched single quote
2189 collapsed += elided
2190 break
2191
2192 return collapsed
2193
2194
2195 def FindEndOfExpressionInLine(line, startpos, stack):
2196 """Find the position just after the end of current parenthesized expression.
2197
2198 Args:
2199 line: a CleansedLines line.
2200 startpos: start searching at this position.
2201 stack: nesting stack at startpos.
2202
2203 Returns:
2204 On finding matching end: (index just after matching end, None)
2205 On finding an unclosed expression: (-1, None)
2206 Otherwise: (-1, new stack at end of this line)
2207 """
2208 for i in range(startpos, len(line)):
2209 char = line[i]
2210 if char in "([{":
2211 # Found start of parenthesized expression, push to expression stack
2212 stack.append(char)
2213 elif char == "<":
2214 # Found potential start of template argument list
2215 if i > 0 and line[i - 1] == "<":
2216 # Left shift operator
2217 if stack and stack[-1] == "<":
2218 stack.pop()
2219 if not stack:
2220 return (-1, None)
2221 elif i > 0 and re.search(r"\boperator\s*$", line[0:i]):
2222 # operator<, don't add to stack
2223 continue
2224 else:
2225 # Tentative start of template argument list
2226 stack.append("<")
2227 elif char in ")]}":
2228 # Found end of parenthesized expression.
2229 #
2230 # If we are currently expecting a matching '>', the pending '<'
2231 # must have been an operator. Remove them from expression stack.
2232 while stack and stack[-1] == "<":
2233 stack.pop()
2234 if not stack:
2235 return (-1, None)
2236 if (
2237 (stack[-1] == "(" and char == ")")
2238 or (stack[-1] == "[" and char == "]")
2239 or (stack[-1] == "{" and char == "}")
2240 ):
2241 stack.pop()
2242 if not stack:
2243 return (i + 1, None)
2244 else:
2245 # Mismatched parentheses
2246 return (-1, None)
2247 elif char == ">":
2248 # Found potential end of template argument list.
2249
2250 # Ignore "->" and operator functions
2251 if i > 0 and (line[i - 1] == "-" or re.search(r"\boperator\s*$", line[0 : i - 1])):
2252 continue
2253
2254 # Pop the stack if there is a matching '<'. Otherwise, ignore
2255 # this '>' since it must be an operator.
2256 if stack and stack[-1] == "<":
2257 stack.pop()
2258 if not stack:
2259 return (i + 1, None)
2260 elif char == ";":
2261 # Found something that look like end of statements. If we are currently
2262 # expecting a '>', the matching '<' must have been an operator, since
2263 # template argument list should not contain statements.
2264 while stack and stack[-1] == "<":
2265 stack.pop()
2266 if not stack:
2267 return (-1, None)
2268
2269 # Did not find end of expression or unbalanced parentheses on this line
2270 return (-1, stack)
2271
2272
2273 def CloseExpression(clean_lines, linenum, pos):
2274 """If input points to ( or { or [ or <, finds the position that closes it.
2275
2276 If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the
2277 linenum/pos that correspond to the closing of the expression.
2278
2279 TODO(google): cpplint spends a fair bit of time matching parentheses.
2280 Ideally we would want to index all opening and closing parentheses once
2281 and have CloseExpression be just a simple lookup, but due to preprocessor
2282 tricks, this is not so easy.
2283
2284 Args:
2285 clean_lines: A CleansedLines instance containing the file.
2286 linenum: The number of the line to check.
2287 pos: A position on the line.
2288
2289 Returns:
2290 A tuple (line, linenum, pos) pointer *past* the closing brace, or
2291 (line, len(lines), -1) if we never find a close. Note we ignore
2292 strings and comments when matching; and the line we return is the
2293 'cleansed' line at linenum.
2294 """
2295
2296 line = clean_lines.elided[linenum]
2297 if (line[pos] not in "({[<") or re.match(r"<[<=]", line[pos:]):
2298 return (line, clean_lines.NumLines(), -1)
2299
2300 # Check first line
2301 (end_pos, stack) = FindEndOfExpressionInLine(line, pos, [])
2302 if end_pos > -1:
2303 return (line, linenum, end_pos)
2304
2305 # Continue scanning forward
2306 while stack and linenum < clean_lines.NumLines() - 1:
2307 linenum += 1
2308 line = clean_lines.elided[linenum]
2309 (end_pos, stack) = FindEndOfExpressionInLine(line, 0, stack)
2310 if end_pos > -1:
2311 return (line, linenum, end_pos)
2312
2313 # Did not find end of expression before end of file, give up
2314 return (line, clean_lines.NumLines(), -1)
2315
2316
2317 def FindStartOfExpressionInLine(line, endpos, stack):
2318 """Find position at the matching start of current expression.
2319
2320 This is almost the reverse of FindEndOfExpressionInLine, but note
2321 that the input position and returned position differs by 1.
2322
2323 Args:
2324 line: a CleansedLines line.
2325 endpos: start searching at this position.
2326 stack: nesting stack at endpos.
2327
2328 Returns:
2329 On finding matching start: (index at matching start, None)
2330 On finding an unclosed expression: (-1, None)
2331 Otherwise: (-1, new stack at beginning of this line)
2332 """
2333 i = endpos
2334 while i >= 0:
2335 char = line[i]
2336 if char in ")]}":
2337 # Found end of expression, push to expression stack
2338 stack.append(char)
2339 elif char == ">":
2340 # Found potential end of template argument list.
2341 #
2342 # Ignore it if it's a "->" or ">=" or "operator>"
2343 if i > 0 and (
2344 line[i - 1] == "-"
2345 or re.match(r"\s>=\s", line[i - 1 :])
2346 or re.search(r"\boperator\s*$", line[0:i])
2347 ):
2348 i -= 1
2349 else:
2350 stack.append(">")
2351 elif char == "<":
2352 # Found potential start of template argument list
2353 if i > 0 and line[i - 1] == "<":
2354 # Left shift operator
2355 i -= 1
2356 else:
2357 # If there is a matching '>', we can pop the expression stack.
2358 # Otherwise, ignore this '<' since it must be an operator.
2359 if stack and stack[-1] == ">":
2360 stack.pop()
2361 if not stack:
2362 return (i, None)
2363 elif char in "([{":
2364 # Found start of expression.
2365 #
2366 # If there are any unmatched '>' on the stack, they must be
2367 # operators. Remove those.
2368 while stack and stack[-1] == ">":
2369 stack.pop()
2370 if not stack:
2371 return (-1, None)
2372 if (
2373 (char == "(" and stack[-1] == ")")
2374 or (char == "[" and stack[-1] == "]")
2375 or (char == "{" and stack[-1] == "}")
2376 ):
2377 stack.pop()
2378 if not stack:
2379 return (i, None)
2380 else:
2381 # Mismatched parentheses
2382 return (-1, None)
2383 elif char == ";":
2384 # Found something that look like end of statements. If we are currently
2385 # expecting a '<', the matching '>' must have been an operator, since
2386 # template argument list should not contain statements.
2387 while stack and stack[-1] == ">":
2388 stack.pop()
2389 if not stack:
2390 return (-1, None)
2391
2392 i -= 1
2393
2394 return (-1, stack)
2395
2396
2397 def ReverseCloseExpression(clean_lines, linenum, pos):
2398 """If input points to ) or } or ] or >, finds the position that opens it.
2399
2400 If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the
2401 linenum/pos that correspond to the opening of the expression.
2402
2403 Args:
2404 clean_lines: A CleansedLines instance containing the file.
2405 linenum: The number of the line to check.
2406 pos: A position on the line.
2407
2408 Returns:
2409 A tuple (line, linenum, pos) pointer *at* the opening brace, or
2410 (line, 0, -1) if we never find the matching opening brace. Note
2411 we ignore strings and comments when matching; and the line we
2412 return is the 'cleansed' line at linenum.
2413 """
2414 line = clean_lines.elided[linenum]
2415 if line[pos] not in ")}]>":
2416 return (line, 0, -1)
2417
2418 # Check last line
2419 (start_pos, stack) = FindStartOfExpressionInLine(line, pos, [])
2420 if start_pos > -1:
2421 return (line, linenum, start_pos)
2422
2423 # Continue scanning backward
2424 while stack and linenum > 0:
2425 linenum -= 1
2426 line = clean_lines.elided[linenum]
2427 (start_pos, stack) = FindStartOfExpressionInLine(line, len(line) - 1, stack)
2428 if start_pos > -1:
2429 return (line, linenum, start_pos)
2430
2431 # Did not find start of expression before beginning of file, give up
2432 return (line, 0, -1)
2433
2434
2435 def CheckForCopyright(filename, lines, error):
2436 """Logs an error if no Copyright message appears at the top of the file."""
2437
2438 # We'll say it should occur by line 10. Don't forget there's a
2439 # placeholder line at the front.
2440 for line in range(1, min(len(lines), 11)):
2441 if re.search(r"Copyright", lines[line], re.IGNORECASE):
2442 break
2443 else: # means no copyright line was found
2444 error(
2445 filename,
2446 0,
2447 "legal/copyright",
2448 5,
2449 "No copyright message found. "
2450 'You should have a line: "Copyright [year] <Copyright Owner>"',
2451 )
2452
2453
2454 def GetIndentLevel(line):
2455 """Return the number of leading spaces in line.
2456
2457 Args:
2458 line: A string to check.
2459
2460 Returns:
2461 An integer count of leading spaces, possibly zero.
2462 """
2463 if indent := re.match(r"^( *)\S", line):
2464 return len(indent.group(1))
2465 return 0
2466
2467
2468 def PathSplitToList(path):
2469 """Returns the path split into a list by the separator.
2470
2471 Args:
2472 path: An absolute or relative path (e.g. '/a/b/c/' or '../a')
2473
2474 Returns:
2475 A list of path components (e.g. ['a', 'b', 'c]).
2476 """
2477 lst = []
2478 while True:
2479 (head, tail) = os.path.split(path)
2480 if head == path: # absolute paths end
2481 lst.append(head)
2482 break
2483 if tail == path: # relative paths end
2484 lst.append(tail)
2485 break
2486
2487 path = head
2488 lst.append(tail)
2489
2490 lst.reverse()
2491 return lst
2492
2493
2494 def GetHeaderGuardCPPVariable(filename):
2495 """Returns the CPP variable that should be used as a header guard.
2496
2497 Args:
2498 filename: The name of a C++ header file.
2499
2500 Returns:
2501 The CPP variable that should be used as a header guard in the
2502 named file.
2503
2504 """
2505
2506 # Restores original filename in case that cpplint is invoked from Emacs's
2507 # flymake.
2508 filename = re.sub(r"_flymake\.h$", ".h", filename)
2509 filename = re.sub(r"/\.flymake/([^/]*)$", r"/\1", filename)
2510 # Replace 'c++' with 'cpp'.
2511 filename = filename.replace("C++", "cpp").replace("c++", "cpp")
2512
2513 fileinfo = FileInfo(filename)
2514 file_path_from_root = fileinfo.RepositoryName()
2515
2516 def FixupPathFromRoot():
2517 if _root_debug:
2518 sys.stderr.write(
2519 f"\n_root fixup, _root = '{_root}',"
2520 f" repository name = '{fileinfo.RepositoryName()}'\n"
2521 )
2522
2523 # Process the file path with the --root flag if it was set.
2524 if not _root:
2525 if _root_debug:
2526 sys.stderr.write("_root unspecified\n")
2527 return file_path_from_root
2528
2529 def StripListPrefix(lst, prefix):
2530 # f(['x', 'y'], ['w, z']) -> None (not a valid prefix)
2531 if lst[: len(prefix)] != prefix:
2532 return None
2533 # f(['a, 'b', 'c', 'd'], ['a', 'b']) -> ['c', 'd']
2534 return lst[(len(prefix)) :]
2535
2536 # root behavior:
2537 # --root=subdir , lstrips subdir from the header guard
2538 maybe_path = StripListPrefix(PathSplitToList(file_path_from_root), PathSplitToList(_root))
2539
2540 if _root_debug:
2541 sys.stderr.write(
2542 ("_root lstrip (maybe_path=%s, file_path_from_root=%s," + " _root=%s)\n")
2543 % (maybe_path, file_path_from_root, _root)
2544 )
2545
2546 if maybe_path:
2547 return os.path.join(*maybe_path)
2548
2549 # --root=.. , will prepend the outer directory to the header guard
2550 full_path = fileinfo.FullName()
2551 # adapt slashes for windows
2552 root_abspath = os.path.abspath(_root).replace("\\", "/")
2553
2554 maybe_path = StripListPrefix(PathSplitToList(full_path), PathSplitToList(root_abspath))
2555
2556 if _root_debug:
2557 sys.stderr.write(
2558 ("_root prepend (maybe_path=%s, full_path=%s, " + "root_abspath=%s)\n")
2559 % (maybe_path, full_path, root_abspath)
2560 )
2561
2562 if maybe_path:
2563 return os.path.join(*maybe_path)
2564
2565 if _root_debug:
2566 sys.stderr.write(f"_root ignore, returning {file_path_from_root}\n")
2567
2568 # --root=FAKE_DIR is ignored
2569 return file_path_from_root
2570
2571 file_path_from_root = FixupPathFromRoot()
2572 return re.sub(r"[^a-zA-Z0-9]", "_", file_path_from_root).upper() + "_"
2573
2574
2575 def CheckForHeaderGuard(filename, clean_lines, error, cppvar):
2576 """Checks that the file contains a header guard.
2577
2578 Logs an error if no #ifndef header guard is present. For other
2579 headers, checks that the full pathname is used.
2580
2581 Args:
2582 filename: The name of the C++ header file.
2583 clean_lines: A CleansedLines instance containing the file.
2584 error: The function to call with any errors found.
2585 """
2586
2587 # Don't check for header guards if there are error suppression
2588 # comments somewhere in this file.
2589 #
2590 # Because this is silencing a warning for a nonexistent line, we
2591 # only support the very specific NOLINT(build/header_guard) syntax,
2592 # and not the general NOLINT or NOLINT(*) syntax.
2593 raw_lines = clean_lines.lines_without_raw_strings
2594 for i in raw_lines:
2595 if re.search(r"//\s*NOLINT\(build/header_guard\)", i):
2596 return
2597
2598 # Allow pragma once instead of header guards
2599 for i in raw_lines:
2600 if re.search(r"^\s*#pragma\s+once", i):
2601 return
2602
2603 ifndef = ""
2604 ifndef_linenum = 0
2605 define = ""
2606 endif = ""
2607 endif_linenum = 0
2608 for linenum, line in enumerate(raw_lines):
2609 linesplit = line.split()
2610 if len(linesplit) >= 2:
2611 # find the first occurrence of #ifndef and #define, save arg
2612 if not ifndef and linesplit[0] == "#ifndef":
2613 # set ifndef to the header guard presented on the #ifndef line.
2614 ifndef = linesplit[1]
2615 ifndef_linenum = linenum
2616 if not define and linesplit[0] == "#define":
2617 define = linesplit[1]
2618 # find the last occurrence of #endif, save entire line
2619 if line.startswith("#endif"):
2620 endif = line
2621 endif_linenum = linenum
2622
2623 if not ifndef or not define or ifndef != define:
2624 error(
2625 filename,
2626 0,
2627 "build/header_guard",
2628 5,
2629 f"No #ifndef header guard found, suggested CPP variable is: {cppvar}",
2630 )
2631 return
2632
2633 # The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__
2634 # for backward compatibility.
2635 if ifndef != cppvar:
2636 error_level = 0
2637 if ifndef != cppvar + "_":
2638 error_level = 5
2639
2640 ParseNolintSuppressions(filename, raw_lines[ifndef_linenum], ifndef_linenum, error)
2641 error(
2642 filename,
2643 ifndef_linenum,
2644 "build/header_guard",
2645 error_level,
2646 f"#ifndef header guard has wrong style, please use: {cppvar}",
2647 )
2648
2649 # Check for "//" comments on endif line.
2650 ParseNolintSuppressions(filename, raw_lines[endif_linenum], endif_linenum, error)
2651 match = re.match(r"#endif\s*//\s*" + cppvar + r"(_)?\b", endif)
2652 if match:
2653 if match.group(1) == "_":
2654 # Issue low severity warning for deprecated double trailing underscore
2655 error(
2656 filename,
2657 endif_linenum,
2658 "build/header_guard",
2659 0,
2660 f'#endif line should be "#endif // {cppvar}"',
2661 )
2662 return
2663
2664 # Didn't find the corresponding "//" comment. If this file does not
2665 # contain any "//" comments at all, it could be that the compiler
2666 # only wants "/**/" comments, look for those instead.
2667 no_single_line_comments = True
2668 for i in range(1, len(raw_lines) - 1):
2669 line = raw_lines[i]
2670 if re.match(r'^(?:(?:\'(?:\.|[^\'])*\')|(?:"(?:\.|[^"])*")|[^\'"])*//', line):
2671 no_single_line_comments = False
2672 break
2673
2674 if no_single_line_comments:
2675 match = re.match(r"#endif\s*/\*\s*" + cppvar + r"(_)?\s*\*/", endif)
2676 if match:
2677 if match.group(1) == "_":
2678 # Low severity warning for double trailing underscore
2679 error(
2680 filename,
2681 endif_linenum,
2682 "build/header_guard",
2683 0,
2684 f'#endif line should be "#endif /* {cppvar} */"',
2685 )
2686 return
2687
2688 # Didn't find anything
2689 error(
2690 filename,
2691 endif_linenum,
2692 "build/header_guard",
2693 5,
2694 f'#endif line should be "#endif // {cppvar}"',
2695 )
2696
2697
2698 def CheckHeaderFileIncluded(filename, include_state, error):
2699 """Logs an error if a source file does not include its header."""
2700
2701 # Do not check test files
2702 fileinfo = FileInfo(filename)
2703 if re.search(_TEST_FILE_SUFFIX, fileinfo.BaseName()):
2704 return
2705
2706 first_include = message = None
2707 basefilename = filename[0 : len(filename) - len(fileinfo.Extension())]
2708 for ext in GetHeaderExtensions():
2709 headerfile = basefilename + "." + ext
2710 if not os.path.exists(headerfile):
2711 continue
2712 headername = FileInfo(headerfile).RepositoryName()
2713 include_uses_unix_dir_aliases = False
2714 for section_list in include_state.include_list:
2715 for f in section_list:
2716 include_text = f[0]
2717 if "./" in include_text:
2718 include_uses_unix_dir_aliases = True
2719 if headername in include_text or include_text in headername:
2720 return
2721 if not first_include:
2722 first_include = f[1]
2723
2724 message = f"{fileinfo.RepositoryName()} should include its header file {headername}"
2725 if include_uses_unix_dir_aliases:
2726 message += ". Relative paths like . and .. are not allowed."
2727
2728 if message:
2729 error(filename, first_include, "build/include", 5, message)
2730
2731
2732 def CheckForBadCharacters(filename, lines, error):
2733 """Logs an error for each line containing bad characters.
2734
2735 Two kinds of bad characters:
2736
2737 1. Unicode replacement characters: These indicate that either the file
2738 contained invalid UTF-8 (likely) or Unicode replacement characters (which
2739 it shouldn't). Note that it's possible for this to throw off line
2740 numbering if the invalid UTF-8 occurred adjacent to a newline.
2741
2742 2. NUL bytes. These are problematic for some tools.
2743
2744 Args:
2745 filename: The name of the current file.
2746 lines: An array of strings, each representing a line of the file.
2747 error: The function to call with any errors found.
2748 """
2749 for linenum, line in enumerate(lines):
2750 if "\ufffd" in line:
2751 error(
2752 filename,
2753 linenum,
2754 "readability/utf8",
2755 5,
2756 "Line contains invalid UTF-8 (or Unicode replacement character).",
2757 )
2758 if "\0" in line:
2759 error(filename, linenum, "readability/nul", 5, "Line contains NUL byte.")
2760
2761
2762 def CheckForNewlineAtEOF(filename, lines, error):
2763 """Logs an error if there is no newline char at the end of the file.
2764
2765 Args:
2766 filename: The name of the current file.
2767 lines: An array of strings, each representing a line of the file.
2768 error: The function to call with any errors found.
2769 """
2770
2771 # The array lines() was created by adding two newlines to the
2772 # original file (go figure), then splitting on \n.
2773 # To verify that the file ends in \n, we just have to make sure the
2774 # last-but-two element of lines() exists and is empty.
2775 if len(lines) < 3 or lines[-2]:
2776 error(
2777 filename,
2778 len(lines) - 2,
2779 "whitespace/ending_newline",
2780 5,
2781 "Could not find a newline character at the end of the file.",
2782 )
2783
2784
2785 def CheckForMultilineCommentsAndStrings(filename, clean_lines, linenum, error):
2786 """Logs an error if we see /* ... */ or "..." that extend past one line.
2787
2788 /* ... */ comments are legit inside macros, for one line.
2789 Otherwise, we prefer // comments, so it's ok to warn about the
2790 other. Likewise, it's ok for strings to extend across multiple
2791 lines, as long as a line continuation character (backslash)
2792 terminates each line. Although not currently prohibited by the C++
2793 style guide, it's ugly and unnecessary. We don't do well with either
2794 in this lint program, so we warn about both.
2795
2796 Args:
2797 filename: The name of the current file.
2798 clean_lines: A CleansedLines instance containing the file.
2799 linenum: The number of the line to check.
2800 error: The function to call with any errors found.
2801 """
2802 line = clean_lines.elided[linenum]
2803
2804 # Remove all \\ (escaped backslashes) from the line. They are OK, and the
2805 # second (escaped) slash may trigger later \" detection erroneously.
2806 line = line.replace("\\\\", "")
2807
2808 if line.count("/*") > line.count("*/"):
2809 error(
2810 filename,
2811 linenum,
2812 "readability/multiline_comment",
2813 5,
2814 "Complex multi-line /*...*/-style comment found. "
2815 "Lint may give bogus warnings. "
2816 "Consider replacing these with //-style comments, "
2817 "with #if 0...#endif, "
2818 "or with more clearly structured multi-line comments.",
2819 )
2820
2821 if (line.count('"') - line.count('\\"')) % 2:
2822 error(
2823 filename,
2824 linenum,
2825 "readability/multiline_string",
2826 5,
2827 'Multi-line string ("...") found. This lint script doesn\'t '
2828 "do well with such strings, and may give bogus warnings. "
2829 "Use C++11 raw strings or concatenation instead.",
2830 )
2831
2832
2833 # (non-threadsafe name, thread-safe alternative, validation pattern)
2834 #
2835 # The validation pattern is used to eliminate false positives such as:
2836 # _rand(); // false positive due to substring match.
2837 # ->rand(); // some member function rand().
2838 # ACMRandom rand(seed); // some variable named rand.
2839 # ISAACRandom rand(); // another variable named rand.
2840 #
2841 # Basically we require the return value of these functions to be used
2842 # in some expression context on the same line by matching on some
2843 # operator before the function name. This eliminates constructors and
2844 # member function calls.
2845 _UNSAFE_FUNC_PREFIX = r"(?:[-+*/=%^&|(<]\s*|>\s+)"
2846 _THREADING_LIST = (
2847 ("asctime(", "asctime_r(", _UNSAFE_FUNC_PREFIX + r"asctime\([^)]+\)"),
2848 ("ctime(", "ctime_r(", _UNSAFE_FUNC_PREFIX + r"ctime\([^)]+\)"),
2849 ("getgrgid(", "getgrgid_r(", _UNSAFE_FUNC_PREFIX + r"getgrgid\([^)]+\)"),
2850 ("getgrnam(", "getgrnam_r(", _UNSAFE_FUNC_PREFIX + r"getgrnam\([^)]+\)"),
2851 ("getlogin(", "getlogin_r(", _UNSAFE_FUNC_PREFIX + r"getlogin\(\)"),
2852 ("getpwnam(", "getpwnam_r(", _UNSAFE_FUNC_PREFIX + r"getpwnam\([^)]+\)"),
2853 ("getpwuid(", "getpwuid_r(", _UNSAFE_FUNC_PREFIX + r"getpwuid\([^)]+\)"),
2854 ("gmtime(", "gmtime_r(", _UNSAFE_FUNC_PREFIX + r"gmtime\([^)]+\)"),
2855 ("localtime(", "localtime_r(", _UNSAFE_FUNC_PREFIX + r"localtime\([^)]+\)"),
2856 ("rand(", "rand_r(", _UNSAFE_FUNC_PREFIX + r"rand\(\)"),
2857 ("strtok(", "strtok_r(", _UNSAFE_FUNC_PREFIX + r"strtok\([^)]+\)"),
2858 ("ttyname(", "ttyname_r(", _UNSAFE_FUNC_PREFIX + r"ttyname\([^)]+\)"),
2859 )
2860
2861
2862 def CheckPosixThreading(filename, clean_lines, linenum, error):
2863 """Checks for calls to thread-unsafe functions.
2864
2865 Much code has been originally written without consideration of
2866 multi-threading. Also, engineers are relying on their old experience;
2867 they have learned posix before threading extensions were added. These
2868 tests guide the engineers to use thread-safe functions (when using
2869 posix directly).
2870
2871 Args:
2872 filename: The name of the current file.
2873 clean_lines: A CleansedLines instance containing the file.
2874 linenum: The number of the line to check.
2875 error: The function to call with any errors found.
2876 """
2877 line = clean_lines.elided[linenum]
2878 for single_thread_func, multithread_safe_func, pattern in _THREADING_LIST:
2879 # Additional pattern matching check to confirm that this is the
2880 # function we are looking for
2881 if re.search(pattern, line):
2882 error(
2883 filename,
2884 linenum,
2885 "runtime/threadsafe_fn",
2886 2,
2887 "Consider using "
2888 + multithread_safe_func
2889 + "...) instead of "
2890 + single_thread_func
2891 + "...) for improved thread safety.",
2892 )
2893
2894
2895 def CheckVlogArguments(filename, clean_lines, linenum, error):
2896 """Checks that VLOG() is only used for defining a logging level.
2897
2898 For example, VLOG(2) is correct. VLOG(INFO), VLOG(WARNING), VLOG(ERROR), and
2899 VLOG(FATAL) are not.
2900
2901 Args:
2902 filename: The name of the current file.
2903 clean_lines: A CleansedLines instance containing the file.
2904 linenum: The number of the line to check.
2905 error: The function to call with any errors found.
2906 """
2907 line = clean_lines.elided[linenum]
2908 if re.search(r"\bVLOG\((INFO|ERROR|WARNING|DFATAL|FATAL)\)", line):
2909 error(
2910 filename,
2911 linenum,
2912 "runtime/vlog",
2913 5,
2914 "VLOG() should be used with numeric verbosity level. "
2915 "Use LOG() if you want symbolic severity levels.",
2916 )
2917
2918
2919 # Matches invalid increment: *count++, which moves pointer instead of
2920 # incrementing a value.
2921 _RE_PATTERN_INVALID_INCREMENT = re.compile(r"^\s*\*\w+(\+\+|--);")
2922
2923
2924 def CheckInvalidIncrement(filename, clean_lines, linenum, error):
2925 """Checks for invalid increment *count++.
2926
2927 For example following function:
2928 void increment_counter(int* count) {
2929 *count++;
2930 }
2931 is invalid, because it effectively does count++, moving pointer, and should
2932 be replaced with ++*count, (*count)++ or *count += 1.
2933
2934 Args:
2935 filename: The name of the current file.
2936 clean_lines: A CleansedLines instance containing the file.
2937 linenum: The number of the line to check.
2938 error: The function to call with any errors found.
2939 """
2940 line = clean_lines.elided[linenum]
2941 if _RE_PATTERN_INVALID_INCREMENT.match(line):
2942 error(
2943 filename,
2944 linenum,
2945 "runtime/invalid_increment",
2946 5,
2947 "Changing pointer instead of value (or unused value of operator*).",
2948 )
2949
2950
2951 def IsMacroDefinition(clean_lines, linenum):
2952 if re.search(r"^#define", clean_lines[linenum]):
2953 return True
2954
2955 return bool(linenum > 0 and re.search(r"\\$", clean_lines[linenum - 1]))
2956
2957
2958 def IsForwardClassDeclaration(clean_lines, linenum):
2959 return re.match(r"^\s*(\btemplate\b)*.*class\s+\w+;\s*$", clean_lines[linenum])
2960
2961
2962 class _BlockInfo:
2963 """Stores information about a generic block of code."""
2964
2965 def __init__(self, linenum, seen_open_brace):
2966 self.starting_linenum = linenum
2967 self.seen_open_brace = seen_open_brace
2968 self.open_parentheses = 0
2969 self.inline_asm = _NO_ASM
2970 self.check_namespace_indentation = False
2971
2972 def CheckBegin(self, filename, clean_lines, linenum, error):
2973 """Run checks that applies to text up to the opening brace.
2974
2975 This is mostly for checking the text after the class identifier
2976 and the "{", usually where the base class is specified. For other
2977 blocks, there isn't much to check, so we always pass.
2978
2979 Args:
2980 filename: The name of the current file.
2981 clean_lines: A CleansedLines instance containing the file.
2982 linenum: The number of the line to check.
2983 error: The function to call with any errors found.
2984 """
2985 pass
2986
2987 def CheckEnd(self, filename, clean_lines, linenum, error):
2988 """Run checks that applies to text after the closing brace.
2989
2990 This is mostly used for checking end of namespace comments.
2991
2992 Args:
2993 filename: The name of the current file.
2994 clean_lines: A CleansedLines instance containing the file.
2995 linenum: The number of the line to check.
2996 error: The function to call with any errors found.
2997 """
2998 pass
2999
3000 def IsBlockInfo(self):
3001 """Returns true if this block is a _BlockInfo.
3002
3003 This is convenient for verifying that an object is an instance of
3004 a _BlockInfo, but not an instance of any of the derived classes.
3005
3006 Returns:
3007 True for this class, False for derived classes.
3008 """
3009 return self.__class__ == _BlockInfo
3010
3011
3012 class _ExternCInfo(_BlockInfo):
3013 """Stores information about an 'extern "C"' block."""
3014
3015 def __init__(self, linenum):
3016 _BlockInfo.__init__(self, linenum, True)
3017
3018
3019 class _ClassInfo(_BlockInfo):
3020 """Stores information about a class."""
3021
3022 def __init__(self, name, class_or_struct, clean_lines, linenum):
3023 _BlockInfo.__init__(self, linenum, False)
3024 self.name = name
3025 self.is_derived = False
3026 self.check_namespace_indentation = True
3027 if class_or_struct == "struct":
3028 self.access = "public"
3029 self.is_struct = True
3030 else:
3031 self.access = "private"
3032 self.is_struct = False
3033
3034 # Remember initial indentation level for this class. Using raw_lines here
3035 # instead of elided to account for leading comments.
3036 self.class_indent = GetIndentLevel(clean_lines.raw_lines[linenum])
3037
3038 # Try to find the end of the class. This will be confused by things like:
3039 # class A {
3040 # } *x = { ...
3041 #
3042 # But it's still good enough for CheckSectionSpacing.
3043 self.last_line = 0
3044 depth = 0
3045 for i in range(linenum, clean_lines.NumLines()):
3046 line = clean_lines.elided[i]
3047 depth += line.count("{") - line.count("}")
3048 if not depth:
3049 self.last_line = i
3050 break
3051
3052 def CheckBegin(self, filename, clean_lines, linenum, error):
3053 # Look for a bare ':'
3054 if re.search("(^|[^:]):($|[^:])", clean_lines.elided[linenum]):
3055 self.is_derived = True
3056
3057 def CheckEnd(self, filename, clean_lines, linenum, error):
3058 # If there is a DISALLOW macro, it should appear near the end of
3059 # the class.
3060 seen_last_thing_in_class = False
3061 for i in range(linenum - 1, self.starting_linenum, -1):
3062 match = re.search(
3063 r"\b(DISALLOW_COPY_AND_ASSIGN|DISALLOW_IMPLICIT_CONSTRUCTORS)\("
3064 + self.name
3065 + r"\)",
3066 clean_lines.elided[i],
3067 )
3068 if match:
3069 if seen_last_thing_in_class:
3070 error(
3071 filename,
3072 i,
3073 "readability/constructors",
3074 3,
3075 match.group(1) + " should be the last thing in the class",
3076 )
3077 break
3078
3079 if not re.match(r"^\s*$", clean_lines.elided[i]):
3080 seen_last_thing_in_class = True
3081
3082 # Check that closing brace is aligned with beginning of the class.
3083 # Only do this if the closing brace is indented by only whitespaces.
3084 # This means we will not check single-line class definitions.
3085 indent = re.match(r"^( *)\}", clean_lines.elided[linenum])
3086 if indent and len(indent.group(1)) != self.class_indent:
3087 if self.is_struct:
3088 parent = "struct " + self.name
3089 else:
3090 parent = "class " + self.name
3091 error(
3092 filename,
3093 linenum,
3094 "whitespace/indent",
3095 3,
3096 f"Closing brace should be aligned with beginning of {parent}",
3097 )
3098
3099
3100 class _ConstructorInfo(_BlockInfo):
3101 """Stores information about a constructor.
3102 For detecting member initializer lists."""
3103
3104 def __init__(self, linenum: int):
3105 _BlockInfo.__init__(self, linenum, seen_open_brace=False)
3106
3107
3108 class _NamespaceInfo(_BlockInfo):
3109 """Stores information about a namespace."""
3110
3111 def __init__(self, name, linenum):
3112 _BlockInfo.__init__(self, linenum, False)
3113 self.name = name or ""
3114 self.check_namespace_indentation = True
3115
3116 def CheckEnd(self, filename, clean_lines, linenum, error):
3117 """Check end of namespace comments."""
3118 line = clean_lines.raw_lines[linenum]
3119
3120 # Check how many lines is enclosed in this namespace. Don't issue
3121 # warning for missing namespace comments if there aren't enough
3122 # lines. However, do apply checks if there is already an end of
3123 # namespace comment and it's incorrect.
3124 #
3125 # TODO(google): We always want to check end of namespace comments
3126 # if a namespace is large, but sometimes we also want to apply the
3127 # check if a short namespace contained nontrivial things (something
3128 # other than forward declarations). There is currently no logic on
3129 # deciding what these nontrivial things are, so this check is
3130 # triggered by namespace size only, which works most of the time.
3131 if linenum - self.starting_linenum < 10 and not re.match(
3132 r"^\s*};*\s*(//|/\*).*\bnamespace\b", line
3133 ):
3134 return
3135
3136 # Look for matching comment at end of namespace.
3137 #
3138 # Note that we accept C style "/* */" comments for terminating
3139 # namespaces, so that code that terminate namespaces inside
3140 # preprocessor macros can be cpplint clean.
3141 #
3142 # We also accept stuff like "// end of namespace <name>." with the
3143 # period at the end.
3144 #
3145 # Besides these, we don't accept anything else, otherwise we might
3146 # get false negatives when existing comment is a substring of the
3147 # expected namespace.
3148 if self.name:
3149 # Named namespace
3150 if not re.match(
3151 (r"^\s*};*\s*(//|/\*).*\bnamespace\s+" + re.escape(self.name) + r"[\*/\.\\\s]*$"),
3152 line,
3153 ):
3154 error(
3155 filename,
3156 linenum,
3157 "readability/namespace",
3158 5,
3159 f'Namespace should be terminated with "// namespace {self.name}"',
3160 )
3161 else:
3162 # Anonymous namespace
3163 if not re.match(r"^\s*};*\s*(//|/\*).*\bnamespace[\*/\.\\\s]*$", line):
3164 # If "// namespace anonymous" or "// anonymous namespace (more text)",
3165 # mention "// anonymous namespace" as an acceptable form
3166 if re.match(r"^\s*}.*\b(namespace anonymous|anonymous namespace)\b", line):
3167 error(
3168 filename,
3169 linenum,
3170 "readability/namespace",
3171 5,
3172 'Anonymous namespace should be terminated with "// namespace"'
3173 ' or "// anonymous namespace"',
3174 )
3175 else:
3176 error(
3177 filename,
3178 linenum,
3179 "readability/namespace",
3180 5,
3181 'Anonymous namespace should be terminated with "// namespace"',
3182 )
3183
3184
3185 class _WrappedInfo(_BlockInfo):
3186 """Stores information about parentheses, initializer lists, etc.
3187 Not exactly a block but we do need the same signature.
3188 Needed to avoid namespace indentation false positives,
3189 though parentheses tracking would slow us down a lot
3190 and is effectively already done by open_parentheses."""
3191
3192 pass
3193
3194
3195 class _MemInitListInfo(_WrappedInfo):
3196 """Stores information about member initializer lists."""
3197
3198 pass
3199
3200
3201 class _PreprocessorInfo:
3202 """Stores checkpoints of nesting stacks when #if/#else is seen."""
3203
3204 def __init__(self, stack_before_if):
3205 # The entire nesting stack before #if
3206 self.stack_before_if = stack_before_if
3207
3208 # The entire nesting stack up to #else
3209 self.stack_before_else = []
3210
3211 # Whether we have already seen #else or #elif
3212 self.seen_else = False
3213
3214
3215 class NestingState:
3216 """Holds states related to parsing braces."""
3217
3218 def __init__(self):
3219 # Stack for tracking all braces. An object is pushed whenever we
3220 # see a "{", and popped when we see a "}". Only 3 types of
3221 # objects are possible:
3222 # - _ClassInfo: a class or struct.
3223 # - _NamespaceInfo: a namespace.
3224 # - _BlockInfo: some other type of block.
3225 self.stack: list[_BlockInfo] = []
3226
3227 # Top of the previous stack before each Update().
3228 #
3229 # Because the nesting_stack is updated at the end of each line, we
3230 # had to do some convoluted checks to find out what is the current
3231 # scope at the beginning of the line. This check is simplified by
3232 # saving the previous top of nesting stack.
3233 #
3234 # We could save the full stack, but we only need the top. Copying
3235 # the full nesting stack would slow down cpplint by ~10%.
3236 self.previous_stack_top: _BlockInfo | None = None
3237
3238 # The number of open parentheses in the previous stack top before the last update.
3239 # Used to prevent false indentation detection when e.g. a function parameter is indented.
3240 # We can't use previous_stack_top, a shallow copy whose open_parentheses value is updated.
3241 self.previous_open_parentheses = 0
3242
3243 # The last stack item we popped.
3244 self.popped_top: _BlockInfo | None = None
3245
3246 # Stack of _PreprocessorInfo objects.
3247 self.pp_stack = []
3248
3249 def SeenOpenBrace(self):
3250 """Check if we have seen the opening brace for the innermost block.
3251
3252 Returns:
3253 True if we have seen the opening brace, False if the innermost
3254 block is still expecting an opening brace.
3255 """
3256 return (not self.stack) or self.stack[-1].seen_open_brace
3257
3258 def InNamespaceBody(self):
3259 """Check if we are currently one level inside a namespace body.
3260
3261 Returns:
3262 True if top of the stack is a namespace block, False otherwise.
3263 """
3264 return self.stack and isinstance(self.stack[-1], _NamespaceInfo)
3265
3266 def InExternC(self):
3267 """Check if we are currently one level inside an 'extern "C"' block.
3268
3269 Returns:
3270 True if top of the stack is an extern block, False otherwise.
3271 """
3272 return self.stack and isinstance(self.stack[-1], _ExternCInfo)
3273
3274 def InClassDeclaration(self):
3275 """Check if we are currently one level inside a class or struct declaration.
3276
3277 Returns:
3278 True if top of the stack is a class/struct, False otherwise.
3279 """
3280 return self.stack and isinstance(self.stack[-1], _ClassInfo)
3281
3282 def InAsmBlock(self):
3283 """Check if we are currently one level inside an inline ASM block.
3284
3285 Returns:
3286 True if the top of the stack is a block containing inline ASM.
3287 """
3288 return self.stack and self.stack[-1].inline_asm != _NO_ASM
3289
3290 def InTemplateArgumentList(self, clean_lines, linenum, pos):
3291 """Check if current position is inside template argument list.
3292
3293 Args:
3294 clean_lines: A CleansedLines instance containing the file.
3295 linenum: The number of the line to check.
3296 pos: position just after the suspected template argument.
3297 Returns:
3298 True if (linenum, pos) is inside template arguments.
3299 """
3300 while linenum < clean_lines.NumLines():
3301 # Find the earliest character that might indicate a template argument
3302 line = clean_lines.elided[linenum]
3303 match = re.match(r"^[^{};=\[\]\.<>]*(.)", line[pos:])
3304 if not match:
3305 linenum += 1
3306 pos = 0
3307 continue
3308 token = match.group(1)
3309 pos += len(match.group(0))
3310
3311 # These things do not look like template argument list:
3312 # class Suspect {
3313 # class Suspect x; }
3314 if token in ("{", "}", ";"):
3315 return False
3316
3317 # These things look like template argument list:
3318 # template <class Suspect>
3319 # template <class Suspect = default_value>
3320 # template <class Suspect[]>
3321 # template <class Suspect...>
3322 if token in (">", "=", "[", "]", "."):
3323 return True
3324
3325 # Check if token is an unmatched '<'.
3326 # If not, move on to the next character.
3327 if token != "<":
3328 pos += 1
3329 if pos >= len(line):
3330 linenum += 1
3331 pos = 0
3332 continue
3333
3334 # We can't be sure if we just find a single '<', and need to
3335 # find the matching '>'.
3336 (_, end_line, end_pos) = CloseExpression(clean_lines, linenum, pos - 1)
3337 if end_pos < 0:
3338 # Not sure if template argument list or syntax error in file
3339 return False
3340 linenum = end_line
3341 pos = end_pos
3342 return False
3343
3344 def UpdatePreprocessor(self, line):
3345 """Update preprocessor stack.
3346
3347 We need to handle preprocessors due to classes like this:
3348 #ifdef SWIG
3349 struct ResultDetailsPageElementExtensionPoint {
3350 #else
3351 struct ResultDetailsPageElementExtensionPoint : public Extension {
3352 #endif
3353
3354 We make the following assumptions (good enough for most files):
3355 - Preprocessor condition evaluates to true from #if up to first
3356 #else/#elif/#endif.
3357
3358 - Preprocessor condition evaluates to false from #else/#elif up
3359 to #endif. We still perform lint checks on these lines, but
3360 these do not affect nesting stack.
3361
3362 Args:
3363 line: current line to check.
3364 """
3365 if re.match(r"^\s*#\s*(if|ifdef|ifndef)\b", line):
3366 # Beginning of #if block, save the nesting stack here. The saved
3367 # stack will allow us to restore the parsing state in the #else case.
3368 self.pp_stack.append(_PreprocessorInfo(copy.deepcopy(self.stack)))
3369 elif re.match(r"^\s*#\s*(else|elif)\b", line):
3370 # Beginning of #else block
3371 if self.pp_stack:
3372 if not self.pp_stack[-1].seen_else:
3373 # This is the first #else or #elif block. Remember the
3374 # whole nesting stack up to this point. This is what we
3375 # keep after the #endif.
3376 self.pp_stack[-1].seen_else = True
3377 self.pp_stack[-1].stack_before_else = copy.deepcopy(self.stack)
3378
3379 # Restore the stack to how it was before the #if
3380 self.stack = copy.deepcopy(self.pp_stack[-1].stack_before_if)
3381 else:
3382 # TODO(google): unexpected #else, issue warning?
3383 pass
3384 elif re.match(r"^\s*#\s*endif\b", line):
3385 # End of #if or #else blocks.
3386 if self.pp_stack:
3387 # If we saw an #else, we will need to restore the nesting
3388 # stack to its former state before the #else, otherwise we
3389 # will just continue from where we left off.
3390 if self.pp_stack[-1].seen_else:
3391 # Here we can just use a shallow copy since we are the last
3392 # reference to it.
3393 self.stack = self.pp_stack[-1].stack_before_else
3394 # Drop the corresponding #if
3395 self.pp_stack.pop()
3396 else:
3397 # TODO(google): unexpected #endif, issue warning?
3398 pass
3399
3400 def _Pop(self):
3401 """Pop the innermost state (top of the stack) and remember the popped item."""
3402 self.popped_top = self.stack.pop()
3403
3404 def _CountOpenParentheses(self, line: str):
3405 # Count parentheses. This is to avoid adding struct arguments to
3406 # the nesting stack.
3407 if self.stack:
3408 inner_block = self.stack[-1]
3409 depth_change = line.count("(") - line.count(")")
3410 inner_block.open_parentheses += depth_change
3411
3412 # Also check if we are starting or ending an inline assembly block.
3413 if inner_block.inline_asm in (_NO_ASM, _END_ASM):
3414 if (
3415 depth_change != 0
3416 and inner_block.open_parentheses == 1
3417 and _MATCH_ASM.match(line)
3418 ):
3419 # Enter assembly block
3420 inner_block.inline_asm = _INSIDE_ASM
3421 else:
3422 # Not entering assembly block. If previous line was _END_ASM,
3423 # we will now shift to _NO_ASM state.
3424 inner_block.inline_asm = _NO_ASM
3425 elif inner_block.inline_asm == _INSIDE_ASM and inner_block.open_parentheses == 0:
3426 # Exit assembly block
3427 inner_block.inline_asm = _END_ASM
3428
3429 def _UpdateNamesapce(self, line: str, linenum: int) -> str | None:
3430 """
3431 Match start of namespace, append to stack, and consume line
3432 Args:
3433 line: Line to check and consume
3434 linenum: Line number of the line to check
3435
3436 Returns:
3437 The consumed line if namespace matched; None otherwise
3438 """
3439 # Match start of namespace. The "\b\s*" below catches namespace
3440 # declarations even if it weren't followed by a whitespace, this
3441 # is so that we don't confuse our namespace checker. The
3442 # missing spaces will be flagged by CheckSpacing.
3443 namespace_decl_match = re.match(r"^\s*namespace\b\s*([:\w]+)?(.*)$", line)
3444 if not namespace_decl_match:
3445 return None
3446
3447 new_namespace = _NamespaceInfo(namespace_decl_match.group(1), linenum)
3448 self.stack.append(new_namespace)
3449
3450 line = namespace_decl_match.group(2)
3451 if line.find("{") != -1:
3452 new_namespace.seen_open_brace = True
3453 line = line[line.find("{") + 1 :]
3454 return line
3455
3456 def _UpdateConstructor(self, line: str, linenum: int, class_name: str | None = None):
3457 """
3458 Check if the given line is a constructor.
3459 Args:
3460 line: Line to check.
3461 class_name: If line checked is inside of a class block, a str of the class's name;
3462 otherwise, None.
3463 """
3464 if not class_name:
3465 if not re.match(r"\s*(\w*)\s*::\s*\1\s*\(", line):
3466 return
3467 elif not re.match(rf"\s*{re.escape(class_name)}\s*\(", line):
3468 return
3469
3470 self.stack.append(_ConstructorInfo(linenum))
3471
3472 # TODO(google): Update() is too long, but we will refactor later.
3473 def Update(self, filename: str, clean_lines: CleansedLines, linenum: int, error):
3474 """Update nesting state with current line.
3475
3476 Args:
3477 filename: The name of the current file.
3478 clean_lines: A CleansedLines instance containing the file.
3479 linenum: The number of the line to check.
3480 error: The function to call with any errors found.
3481 """
3482 line = clean_lines.elided[linenum]
3483
3484 # Remember top of the previous nesting stack.
3485 #
3486 # The stack is always pushed/popped and not modified in place, so
3487 # we can just do a shallow copy instead of copy.deepcopy. Using
3488 # deepcopy would slow down cpplint by ~28%.
3489 if self.stack:
3490 self.previous_stack_top = self.stack[-1]
3491 self.previous_open_parentheses = self.stack[-1].open_parentheses
3492 else:
3493 self.previous_stack_top = None
3494
3495 # Update pp_stack
3496 self.UpdatePreprocessor(line)
3497
3498 self._CountOpenParentheses(line)
3499
3500 # Consume namespace declaration at the beginning of the line. Do
3501 # this in a loop so that we catch same line declarations like this:
3502 # namespace proto2 { namespace bridge { class MessageSet; } }
3503 while (new_line := self._UpdateNamesapce(line, linenum)) is not None: # could be empty str
3504 line = new_line
3505
3506 # Look for a class declaration in whatever is left of the line
3507 # after parsing namespaces. The regexp accounts for decorated classes
3508 # such as in:
3509 # class LOCKABLE API Object {
3510 # };
3511 class_decl_match = re.match(
3512 r"^(\s*(?:template\s*<[\w\s<>,:=]*>\s*)?"
3513 r"(class|struct)\s+(?:[a-zA-Z0-9_]+\s+)*(\w+(?:::\w+)*))"
3514 r"(.*)$",
3515 line,
3516 )
3517 if class_decl_match and (not self.stack or self.stack[-1].open_parentheses == 0):
3518 # We do not want to accept classes that are actually template arguments:
3519 # template <class Ignore1,
3520 # class Ignore2 = Default<Args>,
3521 # template <Args> class Ignore3>
3522 # void Function() {};
3523 #
3524 # To avoid template argument cases, we scan forward and look for
3525 # an unmatched '>'. If we see one, assume we are inside a
3526 # template argument list.
3527 end_declaration = len(class_decl_match.group(1))
3528 if not self.InTemplateArgumentList(clean_lines, linenum, end_declaration):
3529 self.stack.append(
3530 _ClassInfo(
3531 class_decl_match.group(3), class_decl_match.group(2), clean_lines, linenum
3532 )
3533 )
3534 line = class_decl_match.group(4)
3535
3536 # If we have not yet seen the opening brace for the innermost block,
3537 # run checks here.
3538 if not self.SeenOpenBrace():
3539 self.stack[-1].CheckBegin(filename, clean_lines, linenum, error)
3540
3541 # Update access control if we are directly inside a class/struct
3542 if self.stack and isinstance(self.stack[-1], _ClassInfo):
3543 if self.stack[-1].seen_open_brace:
3544 classinfo: _ClassInfo = self.stack[-1]
3545 # Update access control
3546 if access_match := re.match(
3547 r"^(.*)\b(public|private|protected|signals)(\s+(?:slots\s*)?)?"
3548 r":([^:].*|$)",
3549 line,
3550 ):
3551 classinfo.access = access_match.group(2)
3552
3553 # Check that access keywords are indented +1 space. Skip this
3554 # check if the keywords are not preceded by whitespaces.
3555 indent = access_match.group(1)
3556 if len(indent) != classinfo.class_indent + 1 and re.match(r"^\s*$", indent):
3557 if classinfo.is_struct:
3558 parent = "struct " + classinfo.name
3559 else:
3560 parent = "class " + classinfo.name
3561 slots = ""
3562 if access_match.group(3):
3563 slots = access_match.group(3)
3564 error(
3565 filename,
3566 linenum,
3567 "whitespace/indent",
3568 3,
3569 f"{access_match.group(2)}{slots}:"
3570 f" should be indented +1 space inside {parent}",
3571 )
3572
3573 line = access_match.group(4)
3574 else:
3575 self._UpdateConstructor(line, linenum, class_name=classinfo.name)
3576 else: # Not in class
3577 self._UpdateConstructor(line, linenum)
3578
3579 # If brace not open and we just finished a parenthetical definition,
3580 # check if we're in a member initializer list following a constructor.
3581 if (
3582 self.stack
3583 and (
3584 isinstance(self.stack[-1], _ConstructorInfo)
3585 or isinstance(self.previous_stack_top, _ConstructorInfo)
3586 )
3587 and not self.stack[-1].seen_open_brace
3588 and re.search(r"[^:]:[^:]", line)
3589 ):
3590 self.stack.append(_MemInitListInfo(linenum, seen_open_brace=False))
3591
3592 # Consume braces or semicolons from what's left of the line
3593 while True:
3594 # Match first brace, semicolon, or closed parenthesis.
3595 matched = re.match(r"^[^{;)}]*([{;)}])(.*)$", line)
3596 if not matched:
3597 break
3598
3599 token = matched.group(1)
3600 if token == "{":
3601 # If namespace or class hasn't seen an opening brace yet, mark
3602 # namespace/class head as complete. Push a new block onto the
3603 # stack otherwise.
3604 if not self.SeenOpenBrace():
3605 # End of initializer list wrap if present
3606 if isinstance(self.stack[-1], _MemInitListInfo):
3607 self._Pop()
3608 self.stack[-1].seen_open_brace = True
3609 elif re.match(r'^extern\s*"[^"]*"\s*\{', line):
3610 self.stack.append(_ExternCInfo(linenum))
3611 else:
3612 self.stack.append(_BlockInfo(linenum, True))
3613 if _MATCH_ASM.match(line):
3614 self.stack[-1].inline_asm = _BLOCK_ASM
3615 elif token == ";":
3616 # If we haven't seen an opening brace yet, but we already saw
3617 # a semicolon, this is probably a forward declaration. Pop
3618 # the stack for these.
3619 if not self.SeenOpenBrace():
3620 self._Pop()
3621 elif token == ")":
3622 # Similarly, if we haven't seen an opening brace yet, but we
3623 # already saw a closing parenthesis, then these are probably
3624 # function arguments with extra "class" or "struct" keywords.
3625 # Also pop these stack for these.
3626 if (
3627 self.stack
3628 and not self.stack[-1].seen_open_brace
3629 and isinstance(self.stack[-1], _ClassInfo)
3630 ):
3631 self._Pop()
3632 else: # token == '}'
3633 # Perform end of block checks and pop the stack.
3634 if self.stack:
3635 self.stack[-1].CheckEnd(filename, clean_lines, linenum, error)
3636 self._Pop()
3637 line = matched.group(2)
3638
3639 def InnermostClass(self):
3640 """Get class info on the top of the stack.
3641
3642 Returns:
3643 A _ClassInfo object if we are inside a class, or None otherwise.
3644 """
3645 for i in range(len(self.stack), 0, -1):
3646 classinfo = self.stack[i - 1]
3647 if isinstance(classinfo, _ClassInfo):
3648 return classinfo
3649 return None
3650
3651
3652 def CheckForNonStandardConstructs(filename, clean_lines, linenum, nesting_state, error):
3653 r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
3654
3655 Complain about several constructs which gcc-2 accepts, but which are
3656 not standard C++. Warning about these in lint is one way to ease the
3657 transition to new compilers.
3658 - put storage class first (e.g. "static const" instead of "const static").
3659 - "%lld" instead of %qd" in printf-type functions.
3660 - "%1$d" is non-standard in printf-type functions.
3661 - "\%" is an undefined character escape sequence.
3662 - text after #endif is not allowed.
3663 - invalid inner-style forward declaration.
3664 - >? and <? operators, and their >?= and <?= cousins.
3665
3666 Additionally, check for constructor/destructor style violations and reference
3667 members, as it is very convenient to do so while checking for
3668 gcc-2 compliance.
3669
3670 Args:
3671 filename: The name of the current file.
3672 clean_lines: A CleansedLines instance containing the file.
3673 linenum: The number of the line to check.
3674 nesting_state: A NestingState instance which maintains information about
3675 the current stack of nested blocks being parsed.
3676 error: A callable to which errors are reported, which takes 4 arguments:
3677 filename, line number, error level, and message
3678 """
3679
3680 # Remove comments from the line, but leave in strings for now.
3681 line = clean_lines.lines[linenum]
3682
3683 if re.search(r'printf\s*\(.*".*%[-+ ]?\d*q', line):
3684 error(
3685 filename,
3686 linenum,
3687 "runtime/printf_format",
3688 3,
3689 "%q in format strings is deprecated. Use %ll instead.",
3690 )
3691
3692 if re.search(r'printf\s*\(.*".*%\d+\$', line):
3693 error(
3694 filename,
3695 linenum,
3696 "runtime/printf_format",
3697 2,
3698 "%N$ formats are unconventional. Try rewriting to avoid them.",
3699 )
3700
3701 # Remove escaped backslashes before looking for undefined escapes.
3702 line = line.replace("\\\\", "")
3703
3704 if re.search(r'("|\').*\\(%|\[|\(|{)', line):
3705 error(
3706 filename,
3707 linenum,
3708 "build/printf_format",
3709 3,
3710 "%, [, (, and { are undefined character escapes. Unescape them.",
3711 )
3712
3713 # For the rest, work with both comments and strings removed.
3714 line = clean_lines.elided[linenum]
3715
3716 if re.search(
3717 r"\b(const|volatile|void|char|short|int|long"
3718 r"|float|double|signed|unsigned"
3719 r"|schar|u?int8_t|u?int16_t|u?int32_t|u?int64_t)"
3720 r"\s+(register|static|extern|typedef)\b",
3721 line,
3722 ):
3723 error(
3724 filename,
3725 linenum,
3726 "build/storage_class",
3727 5,
3728 "Storage-class specifier (static, extern, typedef, etc) should be "
3729 "at the beginning of the declaration.",
3730 )
3731
3732 if re.match(r"\s*#\s*endif\s*[^/\s]+", line):
3733 error(
3734 filename,
3735 linenum,
3736 "build/endif_comment",
3737 5,
3738 "Uncommented text after #endif is non-standard. Use a comment.",
3739 )
3740
3741 if re.match(r"\s*class\s+(\w+\s*::\s*)+\w+\s*;", line):
3742 error(
3743 filename,
3744 linenum,
3745 "build/forward_decl",
3746 5,
3747 "Inner-style forward declarations are invalid. Remove this line.",
3748 )
3749
3750 if re.search(r"(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?", line):
3751 error(
3752 filename,
3753 linenum,
3754 "build/deprecated",
3755 3,
3756 ">? and <? (max and min) operators are non-standard and deprecated.",
3757 )
3758
3759 if re.search(r"^\s*const\s*string\s*&\s*\w+\s*;", line):
3760 # TODO(google): Could it be expanded safely to arbitrary references,
3761 # without triggering too many false positives? The first
3762 # attempt triggered 5 warnings for mostly benign code in the regtest, hence
3763 # the restriction.
3764 # Here's the original regexp, for the reference:
3765 # type_name = r'\w+((\s*::\s*\w+)|(\s*<\s*\w+?\s*>))?'
3766 # r'\s*const\s*' + type_name + '\s*&\s*\w+\s*;'
3767 error(
3768 filename,
3769 linenum,
3770 "runtime/member_string_references",
3771 2,
3772 "const string& members are dangerous. It is much better to use "
3773 "alternatives, such as pointers or simple constants.",
3774 )
3775
3776 # Everything else in this function operates on class declarations.
3777 # Return early if the top of the nesting stack is not a class, or if
3778 # the class head is not completed yet.
3779 classinfo = nesting_state.InnermostClass()
3780 if not classinfo or not classinfo.seen_open_brace:
3781 return
3782
3783 # The class may have been declared with namespace or classname qualifiers.
3784 # The constructor and destructor will not have those qualifiers.
3785 base_classname = classinfo.name.split("::")[-1]
3786
3787 # Look for single-argument constructors that aren't marked explicit.
3788 # Technically a valid construct, but against style.
3789 explicit_constructor_match = re.match(
3790 r"\s+(?:(?:inline|constexpr)\s+)*(explicit\s+)?"
3791 rf"(?:(?:inline|constexpr)\s+)*{re.escape(base_classname)}\s*"
3792 r"\(((?:[^()]|\([^()]*\))*)\)",
3793 line,
3794 )
3795
3796 if explicit_constructor_match:
3797 is_marked_explicit = explicit_constructor_match.group(1)
3798
3799 if not explicit_constructor_match.group(2):
3800 constructor_args = []
3801 else:
3802 constructor_args = explicit_constructor_match.group(2).split(",")
3803
3804 # collapse arguments so that commas in template parameter lists and function
3805 # argument parameter lists don't split arguments in two
3806 i = 0
3807 while i < len(constructor_args):
3808 constructor_arg = constructor_args[i]
3809 while constructor_arg.count("<") > constructor_arg.count(">") or constructor_arg.count(
3810 "("
3811 ) > constructor_arg.count(")"):
3812 constructor_arg += "," + constructor_args[i + 1]
3813 del constructor_args[i + 1]
3814 constructor_args[i] = constructor_arg
3815 i += 1
3816
3817 variadic_args = [arg for arg in constructor_args if "&&..." in arg]
3818 defaulted_args = [arg for arg in constructor_args if "=" in arg]
3819 noarg_constructor = (
3820 not constructor_args # empty arg list
3821 or
3822 # 'void' arg specifier
3823 (len(constructor_args) == 1 and constructor_args[0].strip() == "void")
3824 )
3825 onearg_constructor = (
3826 (
3827 len(constructor_args) == 1 # exactly one arg
3828 and not noarg_constructor
3829 )
3830 or
3831 # all but at most one arg defaulted
3832 (
3833 len(constructor_args) >= 1
3834 and not noarg_constructor
3835 and len(defaulted_args) >= len(constructor_args) - 1
3836 )
3837 or
3838 # variadic arguments with zero or one argument
3839 (len(constructor_args) <= 2 and len(variadic_args) >= 1)
3840 )
3841 initializer_list_constructor = bool(
3842 onearg_constructor
3843 and re.search(r"\bstd\s*::\s*initializer_list\b", constructor_args[0])
3844 )
3845 copy_constructor = bool(
3846 onearg_constructor
3847 and re.match(
3848 r"((const\s+(volatile\s+)?)?|(volatile\s+(const\s+)?))?"
3849 rf"{re.escape(base_classname)}(\s*<[^>]*>)?(\s+const)?\s*(?:<\w+>\s*)?&",
3850 constructor_args[0].strip(),
3851 )
3852 )
3853
3854 if (
3855 not is_marked_explicit
3856 and onearg_constructor
3857 and not initializer_list_constructor
3858 and not copy_constructor
3859 ):
3860 if defaulted_args or variadic_args:
3861 error(
3862 filename,
3863 linenum,
3864 "runtime/explicit",
3865 4,
3866 "Constructors callable with one argument should be marked explicit.",
3867 )
3868 else:
3869 error(
3870 filename,
3871 linenum,
3872 "runtime/explicit",
3873 4,
3874 "Single-parameter constructors should be marked explicit.",
3875 )
3876
3877
3878 def CheckSpacingForFunctionCall(filename, clean_lines, linenum, error):
3879 """Checks for the correctness of various spacing around function calls.
3880
3881 Args:
3882 filename: The name of the current file.
3883 clean_lines: A CleansedLines instance containing the file.
3884 linenum: The number of the line to check.
3885 error: The function to call with any errors found.
3886 """
3887 line = clean_lines.elided[linenum]
3888
3889 # Since function calls often occur inside if/for/while/switch
3890 # expressions - which have their own, more liberal conventions - we
3891 # first see if we should be looking inside such an expression for a
3892 # function call, to which we can apply more strict standards.
3893 fncall = line # if there's no control flow construct, look at whole line
3894 for pattern in (
3895 r"\bif\s*\((.*)\)\s*{",
3896 r"\bfor\s*\((.*)\)\s*{",
3897 r"\bwhile\s*\((.*)\)\s*[{;]",
3898 r"\bswitch\s*\((.*)\)\s*{",
3899 ):
3900 match = re.search(pattern, line)
3901 if match:
3902 fncall = match.group(1) # look inside the parens for function calls
3903 break
3904
3905 # Except in if/for/while/switch, there should never be space
3906 # immediately inside parens (eg "f( 3, 4 )"). We make an exception
3907 # for nested parens ( (a+b) + c ). Likewise, there should never be
3908 # a space before a ( when it's a function argument. I assume it's a
3909 # function argument when the char before the whitespace is legal in
3910 # a function name (alnum + _) and we're not starting a macro. Also ignore
3911 # pointers and references to arrays and functions coz they're too tricky:
3912 # we use a very simple way to recognize these:
3913 # " (something)(maybe-something)" or
3914 # " (something)(maybe-something," or
3915 # " (something)[something]"
3916 # Note that we assume the contents of [] to be short enough that
3917 # they'll never need to wrap.
3918 if ( # Ignore control structures.
3919 not re.search(r"\b(if|elif|for|while|switch|return|new|delete|catch|sizeof)\b", fncall)
3920 and
3921 # Ignore pointers/references to functions.
3922 not re.search(r" \([^)]+\)\([^)]*(\)|,$)", fncall)
3923 and
3924 # Ignore pointers/references to arrays.
3925 not re.search(r" \([^)]+\)\[[^\]]+\]", fncall)
3926 ):
3927 if re.search(r"\w\s*\(\s(?!\s*\\$)", fncall): # a ( used for a fn call
3928 error(filename, linenum, "whitespace/parens", 4, "Extra space after ( in function call")
3929 elif re.search(r"\(\s+(?!(\s*\\)|\()", fncall):
3930 error(filename, linenum, "whitespace/parens", 2, "Extra space after (")
3931 if (
3932 re.search(r"\w\s+\(", fncall)
3933 and not re.search(r"_{0,2}asm_{0,2}\s+_{0,2}volatile_{0,2}\s+\(", fncall)
3934 and not re.search(r"#\s*define|typedef|using\s+\w+\s*=", fncall)
3935 and not re.search(r"\w\s+\((\w+::)*\*\w+\)\(", fncall)
3936 and not re.search(r"\bcase\s+\(", fncall)
3937 ):
3938 # TODO(google): Space after an operator function seem to be a common
3939 # error, silence those for now by restricting them to highest verbosity.
3940 if re.search(r"\boperator_*\b", line):
3941 error(
3942 filename,
3943 linenum,
3944 "whitespace/parens",
3945 0,
3946 "Extra space before ( in function call",
3947 )
3948 else:
3949 error(
3950 filename,
3951 linenum,
3952 "whitespace/parens",
3953 4,
3954 "Extra space before ( in function call",
3955 )
3956 # If the ) is followed only by a newline or a { + newline, assume it's
3957 # part of a control statement (if/while/etc), and don't complain
3958 if re.search(r"[^)]\s+\)\s*[^{\s]", fncall):
3959 # If the closing parenthesis is preceded by only whitespaces,
3960 # try to give a more descriptive error message.
3961 if re.search(r"^\s+\)", fncall):
3962 error(
3963 filename,
3964 linenum,
3965 "whitespace/parens",
3966 2,
3967 "Closing ) should be moved to the previous line",
3968 )
3969 else:
3970 error(filename, linenum, "whitespace/parens", 2, "Extra space before )")
3971
3972
3973 def IsBlankLine(line):
3974 """Returns true if the given line is blank.
3975
3976 We consider a line to be blank if the line is empty or consists of
3977 only white spaces.
3978
3979 Args:
3980 line: A line of a string.
3981
3982 Returns:
3983 True, if the given line is blank.
3984 """
3985 return not line or line.isspace()
3986
3987
3988 def CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line, error):
3989 is_namespace_indent_item = len(nesting_state.stack) >= 1 and (
3990 isinstance(nesting_state.stack[-1], _NamespaceInfo)
3991 or (isinstance(nesting_state.previous_stack_top, _NamespaceInfo))
3992 )
3993
3994 if ShouldCheckNamespaceIndentation(
3995 nesting_state, is_namespace_indent_item, clean_lines.elided, line
3996 ):
3997 CheckItemIndentationInNamespace(filename, clean_lines.elided, line, error)
3998
3999
4000 def CheckForFunctionLengths(filename, clean_lines, linenum, function_state, error):
4001 """Reports for long function bodies.
4002
4003 For an overview why this is done, see:
4004 https://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions
4005
4006 Uses a simplistic algorithm assuming other style guidelines
4007 (especially spacing) are followed.
4008 Only checks unindented functions, so class members are unchecked.
4009 Trivial bodies are unchecked, so constructors with huge initializer lists
4010 may be missed.
4011 Blank/comment lines are not counted so as to avoid encouraging the removal
4012 of vertical space and comments just to get through a lint check.
4013 NOLINT *on the last line of a function* disables this check.
4014
4015 Args:
4016 filename: The name of the current file.
4017 clean_lines: A CleansedLines instance containing the file.
4018 linenum: The number of the line to check.
4019 function_state: Current function name and lines in body so far.
4020 error: The function to call with any errors found.
4021 """
4022 lines = clean_lines.lines
4023 line = lines[linenum]
4024 joined_line = ""
4025
4026 starting_func = False
4027 regexp = r"(\w(\w|::|\*|\&|\s)*)\(" # decls * & space::name( ...
4028 if match_result := re.match(regexp, line):
4029 # If the name is all caps and underscores, figure it's a macro and
4030 # ignore it, unless it's TEST or TEST_F.
4031 function_name = match_result.group(1).split()[-1]
4032 if function_name in {"TEST", "TEST_F"} or not re.match(r"[A-Z_]+$", function_name):
4033 starting_func = True
4034
4035 if starting_func:
4036 body_found = False
4037 for start_linenum in range(linenum, clean_lines.NumLines()):
4038 start_line = lines[start_linenum]
4039 joined_line += " " + start_line.lstrip()
4040 if re.search(r"(;|})", start_line): # Declarations and trivial functions
4041 body_found = True
4042 break # ... ignore
4043 if re.search(r"{", start_line):
4044 body_found = True
4045 function = re.search(r"((\w|:)*)\(", line).group(1)
4046 if re.match(r"TEST", function): # Handle TEST... macros
4047 parameter_regexp = re.search(r"(\(.*\))", joined_line)
4048 if parameter_regexp: # Ignore bad syntax
4049 function += parameter_regexp.group(1)
4050 else:
4051 function += "()"
4052 function_state.Begin(function)
4053 break
4054 if not body_found:
4055 # No body for the function (or evidence of a non-function) was found.
4056 error(
4057 filename,
4058 linenum,
4059 "readability/fn_size",
4060 5,
4061 "Lint failed to find start of function body.",
4062 )
4063 elif re.match(r"^\}\s*$", line): # function end
4064 function_state.Check(error, filename, linenum)
4065 function_state.End()
4066 elif not re.match(r"^\s*$", line):
4067 function_state.Count() # Count non-blank/non-comment lines.
4068
4069
4070 _RE_PATTERN_TODO = re.compile(r"^//(\s*)TODO(\(.+?\))?:?(\s|$)?")
4071
4072
4073 def CheckComment(line, filename, linenum, next_line_start, error):
4074 """Checks for common mistakes in comments.
4075
4076 Args:
4077 line: The line in question.
4078 filename: The name of the current file.
4079 linenum: The number of the line to check.
4080 next_line_start: The first non-whitespace column of the next line.
4081 error: The function to call with any errors found.
4082 """
4083 commentpos = line.find("//")
4084 if commentpos != -1:
4085 # Check if the // may be in quotes. If so, ignore it
4086 if re.sub(r"\\.", "", line[0:commentpos]).count('"') % 2 == 0:
4087 # Allow one space for new scopes, two spaces otherwise:
4088 if not (re.match(r"^.*{ *//", line) and next_line_start == commentpos) and (
4089 (commentpos >= 1 and line[commentpos - 1] not in string.whitespace)
4090 or (commentpos >= 2 and line[commentpos - 2] not in string.whitespace)
4091 ):
4092 error(
4093 filename,
4094 linenum,
4095 "whitespace/comments",
4096 2,
4097 "At least two spaces is best between code and comments",
4098 )
4099
4100 # Checks for common mistakes in TODO comments.
4101 comment = line[commentpos:]
4102 match = _RE_PATTERN_TODO.match(comment)
4103 if match:
4104 # One whitespace is correct; zero whitespace is handled elsewhere.
4105 leading_whitespace = match.group(1)
4106 if len(leading_whitespace) > 1:
4107 error(filename, linenum, "whitespace/todo", 2, "Too many spaces before TODO")
4108
4109 username = match.group(2)
4110 if not username:
4111 error(
4112 filename,
4113 linenum,
4114 "readability/todo",
4115 2,
4116 "Missing username in TODO; it should look like "
4117 '"// TODO(my_username): Stuff."',
4118 )
4119
4120 middle_whitespace = match.group(3)
4121 # Comparisons made explicit for correctness
4122 # -- pylint: disable=g-explicit-bool-comparison
4123 if middle_whitespace not in {" ", ""}:
4124 error(
4125 filename,
4126 linenum,
4127 "whitespace/todo",
4128 2,
4129 "TODO(my_username) should be followed by a space",
4130 )
4131
4132 # If the comment contains an alphanumeric character, there
4133 # should be a space somewhere between it and the // unless
4134 # it's a /// or //! Doxygen comment.
4135 if re.match(r"//[^ ]*\w", comment) and not re.match(r"(///|//\!)(\s+|$)", comment):
4136 error(
4137 filename,
4138 linenum,
4139 "whitespace/comments",
4140 4,
4141 "Should have a space between // and comment",
4142 )
4143
4144
4145 def CheckSpacing(filename, clean_lines, linenum, nesting_state, error):
4146 """Checks for the correctness of various spacing issues in the code.
4147
4148 Things we check for: spaces around operators, spaces after
4149 if/for/while/switch, no spaces around parens in function calls, two
4150 spaces between code and comment, don't start a block with a blank
4151 line, don't end a function with a blank line, don't add a blank line
4152 after public/protected/private, don't have too many blank lines in a row.
4153
4154 Args:
4155 filename: The name of the current file.
4156 clean_lines: A CleansedLines instance containing the file.
4157 linenum: The number of the line to check.
4158 nesting_state: A NestingState instance which maintains information about
4159 the current stack of nested blocks being parsed.
4160 error: The function to call with any errors found.
4161 """
4162
4163 # Don't use "elided" lines here, otherwise we can't check commented lines.
4164 # Don't want to use "raw" either, because we don't want to check inside C++11
4165 # raw strings,
4166 raw = clean_lines.lines_without_raw_strings
4167 line = raw[linenum]
4168
4169 # Before nixing comments, check if the line is blank for no good
4170 # reason. This includes the first line after a block is opened, and
4171 # blank lines at the end of a function (ie, right before a line like '}'
4172 #
4173 # Skip all the blank line checks if we are immediately inside a
4174 # namespace body. In other words, don't issue blank line warnings
4175 # for this block:
4176 # namespace {
4177 #
4178 # }
4179 #
4180 # A warning about missing end of namespace comments will be issued instead.
4181 #
4182 # Also skip blank line checks for 'extern "C"' blocks, which are formatted
4183 # like namespaces.
4184 if IsBlankLine(line) and not nesting_state.InNamespaceBody() and not nesting_state.InExternC():
4185 elided = clean_lines.elided
4186 prev_line = elided[linenum - 1]
4187 prevbrace = prev_line.rfind("{")
4188 # TODO(google): Don't complain if line before blank line, and line after,
4189 # both start with alnums and are indented the same amount.
4190 # This ignores whitespace at the start of a namespace block
4191 # because those are not usually indented.
4192 if prevbrace != -1 and prev_line[prevbrace:].find("}") == -1:
4193 # OK, we have a blank line at the start of a code block. Before we
4194 # complain, we check if it is an exception to the rule: The previous
4195 # non-empty line has the parameters of a function header that are indented
4196 # 4 spaces (because they did not fit in a 80 column line when placed on
4197 # the same line as the function name). We also check for the case where
4198 # the previous line is indented 6 spaces, which may happen when the
4199 # initializers of a constructor do not fit into a 80 column line.
4200 exception = False
4201 if re.match(r" {6}\w", prev_line): # Initializer list?
4202 # We are looking for the opening column of initializer list, which
4203 # should be indented 4 spaces to cause 6 space indentation afterwards.
4204 search_position = linenum - 2
4205 while search_position >= 0 and re.match(r" {6}\w", elided[search_position]):
4206 search_position -= 1
4207 exception = search_position >= 0 and elided[search_position][:5] == " :"
4208 else:
4209 # Search for the function arguments or an initializer list. We use a
4210 # simple heuristic here: If the line is indented 4 spaces; and we have a
4211 # closing paren, without the opening paren, followed by an opening brace
4212 # or colon (for initializer lists) we assume that it is the last line of
4213 # a function header. If we have a colon indented 4 spaces, it is an
4214 # initializer list.
4215 exception = re.match(
4216 r" {4}\w[^\(]*\)\s*(const\s*)?(\{\s*$|:)", prev_line
4217 ) or re.match(r" {4}:", prev_line)
4218
4219 if not exception:
4220 error(
4221 filename,
4222 linenum,
4223 "whitespace/blank_line",
4224 2,
4225 "Redundant blank line at the start of a code block should be deleted.",
4226 )
4227 # Ignore blank lines at the end of a block in a long if-else
4228 # chain, like this:
4229 # if (condition1) {
4230 # // Something followed by a blank line
4231 #
4232 # } else if (condition2) {
4233 # // Something else
4234 # }
4235 if linenum + 1 < clean_lines.NumLines():
4236 next_line = raw[linenum + 1]
4237 if next_line and re.match(r"\s*}", next_line) and next_line.find("} else ") == -1:
4238 error(
4239 filename,
4240 linenum,
4241 "whitespace/blank_line",
4242 3,
4243 "Redundant blank line at the end of a code block should be deleted.",
4244 )
4245
4246 matched = re.match(r"\s*(public|protected|private):", prev_line)
4247 if matched:
4248 error(
4249 filename,
4250 linenum,
4251 "whitespace/blank_line",
4252 3,
4253 f'Do not leave a blank line after "{matched.group(1)}:"',
4254 )
4255
4256 # Next, check comments
4257 next_line_start = 0
4258 if linenum + 1 < clean_lines.NumLines():
4259 next_line = raw[linenum + 1]
4260 next_line_start = len(next_line) - len(next_line.lstrip())
4261 CheckComment(line, filename, linenum, next_line_start, error)
4262
4263 # get rid of comments and strings
4264 line = clean_lines.elided[linenum]
4265
4266 # You shouldn't have spaces before your brackets, except for C++11 attributes
4267 # or maybe after 'delete []', 'return []() {};', or 'auto [abc, ...] = ...;'.
4268 if re.search(r"\w\s+\[(?!\[)", line) and not re.search(r"(?:auto&?|delete|return)\s+\[", line):
4269 error(filename, linenum, "whitespace/braces", 5, "Extra space before [")
4270
4271 # In range-based for, we wanted spaces before and after the colon, but
4272 # not around "::" tokens that might appear.
4273 if re.search(r"for *\(.*[^:]:[^: ]", line) or re.search(r"for *\(.*[^: ]:[^:]", line):
4274 error(
4275 filename,
4276 linenum,
4277 "whitespace/forcolon",
4278 2,
4279 "Missing space around colon in range-based for loop",
4280 )
4281
4282
4283 def CheckOperatorSpacing(filename, clean_lines, linenum, error):
4284 """Checks for horizontal spacing around operators.
4285
4286 Args:
4287 filename: The name of the current file.
4288 clean_lines: A CleansedLines instance containing the file.
4289 linenum: The number of the line to check.
4290 error: The function to call with any errors found.
4291 """
4292 line = clean_lines.elided[linenum]
4293
4294 # Don't try to do spacing checks for operator methods. Do this by
4295 # replacing the troublesome characters with something else,
4296 # preserving column position for all other characters.
4297 #
4298 # The replacement is done repeatedly to avoid false positives from
4299 # operators that call operators.
4300 while True:
4301 match = re.match(r"^(.*\boperator\b)(\S+)(\s*\(.*)$", line)
4302 if match:
4303 line = match.group(1) + ("_" * len(match.group(2))) + match.group(3)
4304 else:
4305 break
4306
4307 # We allow no-spaces around = within an if: "if ( (a=Foo()) == 0 )".
4308 # Otherwise not. Note we only check for non-spaces on *both* sides;
4309 # sometimes people put non-spaces on one side when aligning ='s among
4310 # many lines (not that this is behavior that I approve of...)
4311 if (
4312 (re.search(r"[\w.]=", line) or re.search(r"=[\w.]", line))
4313 and not re.search(r"\b(if|while|for) ", line)
4314 # Operators taken from [lex.operators] in C++11 standard.
4315 and not re.search(r"(>=|<=|==|!=|&=|\^=|\|=|\+=|\*=|\/=|\%=)", line)
4316 and not re.search(r"operator=", line)
4317 ):
4318 error(filename, linenum, "whitespace/operators", 4, "Missing spaces around =")
4319
4320 # It's ok not to have spaces around binary operators like + - * /, but if
4321 # there's too little whitespace, we get concerned. It's hard to tell,
4322 # though, so we punt on this one for now. TODO(google).
4323
4324 # You should always have whitespace around binary operators.
4325 #
4326 # Check <= and >= first to avoid false positives with < and >, then
4327 # check non-include lines for spacing around < and >.
4328 #
4329 # If the operator is followed by a comma, assume it's be used in a
4330 # macro context and don't do any checks. This avoids false
4331 # positives.
4332 #
4333 # Note that && is not included here. This is because there are too
4334 # many false positives due to RValue references.
4335 match = re.search(r"[^<>=!\s](==|!=|<=|>=|\|\|)[^<>=!\s,;\)]", line)
4336 if match:
4337 # TODO(google): support alternate operators
4338 error(
4339 filename, linenum, "whitespace/operators", 3, f"Missing spaces around {match.group(1)}"
4340 )
4341 elif not re.match(r"#.*include", line):
4342 # Look for < that is not surrounded by spaces. This is only
4343 # triggered if both sides are missing spaces, even though
4344 # technically should should flag if at least one side is missing a
4345 # space. This is done to avoid some false positives with shifts.
4346 match = re.match(r"^(.*[^\s<])<[^\s=<,]", line)
4347 if match:
4348 (_, _, end_pos) = CloseExpression(clean_lines, linenum, len(match.group(1)))
4349 if end_pos <= -1:
4350 error(filename, linenum, "whitespace/operators", 3, "Missing spaces around <")
4351
4352 # Look for > that is not surrounded by spaces. Similar to the
4353 # above, we only trigger if both sides are missing spaces to avoid
4354 # false positives with shifts.
4355 match = re.match(r"^(.*[^-\s>])>[^\s=>,]", line)
4356 if match:
4357 (_, _, start_pos) = ReverseCloseExpression(clean_lines, linenum, len(match.group(1)))
4358 if start_pos <= -1:
4359 error(filename, linenum, "whitespace/operators", 3, "Missing spaces around >")
4360
4361 # We allow no-spaces around << when used like this: 10<<20, but
4362 # not otherwise (particularly, not when used as streams)
4363 #
4364 # We also allow operators following an opening parenthesis, since
4365 # those tend to be macros that deal with operators.
4366 match = re.search(r"(operator|[^\s(<])(?:L|UL|LL|ULL|l|ul|ll|ull)?<<([^\s,=<])", line)
4367 if (
4368 match
4369 and not (match.group(1).isdigit() and match.group(2).isdigit())
4370 and not (match.group(1) == "operator" and match.group(2) == ";")
4371 ):
4372 error(filename, linenum, "whitespace/operators", 3, "Missing spaces around <<")
4373
4374 # We allow no-spaces around >> for almost anything. This is because
4375 # C++11 allows ">>" to close nested templates, which accounts for
4376 # most cases when ">>" is not followed by a space.
4377 #
4378 # We still warn on ">>" followed by alpha character, because that is
4379 # likely due to ">>" being used for right shifts, e.g.:
4380 # value >> alpha
4381 #
4382 # When ">>" is used to close templates, the alphanumeric letter that
4383 # follows would be part of an identifier, and there should still be
4384 # a space separating the template type and the identifier.
4385 # type<type<type>> alpha
4386 match = re.search(r">>[a-zA-Z_]", line)
4387 if match:
4388 error(filename, linenum, "whitespace/operators", 3, "Missing spaces around >>")
4389
4390 # There shouldn't be space around unary operators
4391 match = re.search(r"(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])", line)
4392 if match:
4393 error(
4394 filename,
4395 linenum,
4396 "whitespace/operators",
4397 4,
4398 f"Extra space for operator {match.group(1)}",
4399 )
4400
4401
4402 def CheckParenthesisSpacing(filename, clean_lines, linenum, error):
4403 """Checks for horizontal spacing around parentheses.
4404
4405 Args:
4406 filename: The name of the current file.
4407 clean_lines: A CleansedLines instance containing the file.
4408 linenum: The number of the line to check.
4409 error: The function to call with any errors found.
4410 """
4411 line = clean_lines.elided[linenum]
4412
4413 # No spaces after an if, while, switch, or for
4414 match = re.search(r" (if\(|for\(|while\(|switch\()", line)
4415 if match:
4416 error(
4417 filename, linenum, "whitespace/parens", 5, f"Missing space before ( in {match.group(1)}"
4418 )
4419
4420 # For if/for/while/switch, the left and right parens should be
4421 # consistent about how many spaces are inside the parens, and
4422 # there should either be zero or one spaces inside the parens.
4423 # We don't want: "if ( foo)" or "if ( foo )".
4424 # Exception: "for ( ; foo; bar)" and "for (foo; bar; )" are allowed.
4425 match = re.search(
4426 r"\b(if|for|while|switch)\s*"
4427 r"\(([ ]*)(.).*[^ ]+([ ]*)\)\s*{\s*$",
4428 line,
4429 )
4430 if match:
4431 if len(match.group(2)) != len(match.group(4)) and not (
4432 match.group(3) == ";"
4433 and len(match.group(2)) == 1 + len(match.group(4))
4434 or not match.group(2)
4435 and re.search(r"\bfor\s*\(.*; \)", line)
4436 ):
4437 error(
4438 filename,
4439 linenum,
4440 "whitespace/parens",
4441 5,
4442 f"Mismatching spaces inside () in {match.group(1)}",
4443 )
4444 if len(match.group(2)) not in [0, 1]:
4445 error(
4446 filename,
4447 linenum,
4448 "whitespace/parens",
4449 5,
4450 f"Should have zero or one spaces inside ( and ) in {match.group(1)}",
4451 )
4452
4453
4454 def CheckCommaSpacing(filename, clean_lines, linenum, error):
4455 """Checks for horizontal spacing near commas and semicolons.
4456
4457 Args:
4458 filename: The name of the current file.
4459 clean_lines: A CleansedLines instance containing the file.
4460 linenum: The number of the line to check.
4461 error: The function to call with any errors found.
4462 """
4463 raw = clean_lines.lines_without_raw_strings
4464 line = clean_lines.elided[linenum]
4465
4466 # You should always have a space after a comma (either as fn arg or operator)
4467 #
4468 # This does not apply when the non-space character following the
4469 # comma is another comma, since the only time when that happens is
4470 # for empty macro arguments.
4471 #
4472 # We run this check in two passes: first pass on elided lines to
4473 # verify that lines contain missing whitespaces, second pass on raw
4474 # lines to confirm that those missing whitespaces are not due to
4475 # elided comments.
4476 match = re.search(
4477 r",[^,\s]", re.sub(r"\b__VA_OPT__\s*\(,\)", "", re.sub(r"\boperator\s*,\s*\(", "F(", line))
4478 )
4479 if match and re.search(r",[^,\s]", raw[linenum]):
4480 error(filename, linenum, "whitespace/comma", 3, "Missing space after ,")
4481
4482 # You should always have a space after a semicolon
4483 # except for few corner cases
4484 # TODO(google): clarify if 'if (1) { return 1;}' is requires one more
4485 # space after ;
4486 if re.search(r";[^\s};\\)/]", line):
4487 error(filename, linenum, "whitespace/semicolon", 3, "Missing space after ;")
4488
4489
4490 def _IsType(clean_lines, nesting_state, expr):
4491 """Check if expression looks like a type name, returns true if so.
4492
4493 Args:
4494 clean_lines: A CleansedLines instance containing the file.
4495 nesting_state: A NestingState instance which maintains information about
4496 the current stack of nested blocks being parsed.
4497 expr: The expression to check.
4498 Returns:
4499 True, if token looks like a type.
4500 """
4501 # Keep only the last token in the expression
4502 if last_word := re.match(r"^.*(\b\S+)$", expr):
4503 token = last_word.group(1)
4504 else:
4505 token = expr
4506
4507 # Match native types and stdint types
4508 if _TYPES.match(token):
4509 return True
4510
4511 # Try a bit harder to match templated types. Walk up the nesting
4512 # stack until we find something that resembles a typename
4513 # declaration for what we are looking for.
4514 typename_pattern = r"\b(?:typename|class|struct)\s+" + re.escape(token) + r"\b"
4515 block_index = len(nesting_state.stack) - 1
4516 while block_index >= 0:
4517 if isinstance(nesting_state.stack[block_index], _NamespaceInfo):
4518 return False
4519
4520 # Found where the opening brace is. We want to scan from this
4521 # line up to the beginning of the function, minus a few lines.
4522 # template <typename Type1, // stop scanning here
4523 # ...>
4524 # class C
4525 # : public ... { // start scanning here
4526 last_line = nesting_state.stack[block_index].starting_linenum
4527
4528 next_block_start = 0
4529 if block_index > 0:
4530 next_block_start = nesting_state.stack[block_index - 1].starting_linenum
4531 first_line = last_line
4532 while first_line >= next_block_start:
4533 if clean_lines.elided[first_line].find("template") >= 0:
4534 break
4535 first_line -= 1
4536 if first_line < next_block_start:
4537 # Didn't find any "template" keyword before reaching the next block,
4538 # there are probably no template things to check for this block
4539 block_index -= 1
4540 continue
4541
4542 # Look for typename in the specified range
4543 for i in range(first_line, last_line + 1, 1):
4544 if re.search(typename_pattern, clean_lines.elided[i]):
4545 return True
4546 block_index -= 1
4547
4548 return False
4549
4550
4551 def CheckBracesSpacing(filename, clean_lines, linenum, nesting_state, error):
4552 """Checks for horizontal spacing near commas.
4553
4554 Args:
4555 filename: The name of the current file.
4556 clean_lines: A CleansedLines instance containing the file.
4557 linenum: The number of the line to check.
4558 nesting_state: A NestingState instance which maintains information about
4559 the current stack of nested blocks being parsed.
4560 error: The function to call with any errors found.
4561 """
4562 line = clean_lines.elided[linenum]
4563
4564 # Except after an opening paren, or after another opening brace (in case of
4565 # an initializer list, for instance), you should have spaces before your
4566 # braces when they are delimiting blocks, classes, namespaces etc.
4567 # And since you should never have braces at the beginning of a line,
4568 # this is an easy test. Except that braces used for initialization don't
4569 # follow the same rule; we often don't want spaces before those.
4570
4571 if match := re.match(r"^(.*[^ ({>]){", line):
4572 # Try a bit harder to check for brace initialization. This
4573 # happens in one of the following forms:
4574 # Constructor() : initializer_list_{} { ... }
4575 # Constructor{}.MemberFunction()
4576 # Type variable{};
4577 # FunctionCall(type{}, ...);
4578 # LastArgument(..., type{});
4579 # LOG(INFO) << type{} << " ...";
4580 # map_of_type[{...}] = ...;
4581 # ternary = expr ? new type{} : nullptr;
4582 # OuterTemplate<InnerTemplateConstructor<Type>{}>
4583 #
4584 # We check for the character following the closing brace, and
4585 # silence the warning if it's one of those listed above, i.e.
4586 # "{.;,)<>]:".
4587 #
4588 # To account for nested initializer list, we allow any number of
4589 # closing braces up to "{;,)<". We can't simply silence the
4590 # warning on first sight of closing brace, because that would
4591 # cause false negatives for things that are not initializer lists.
4592 # Silence this: But not this:
4593 # Outer{ if (...) {
4594 # Inner{...} if (...){ // Missing space before {
4595 # }; }
4596 #
4597 # There is a false negative with this approach if people inserted
4598 # spurious semicolons, e.g. "if (cond){};", but we will catch the
4599 # spurious semicolon with a separate check.
4600 leading_text = match.group(1)
4601 (endline, endlinenum, endpos) = CloseExpression(clean_lines, linenum, len(match.group(1)))
4602 trailing_text = ""
4603 if endpos > -1:
4604 trailing_text = endline[endpos:]
4605 for offset in range(endlinenum + 1, min(endlinenum + 3, clean_lines.NumLines() - 1)):
4606 trailing_text += clean_lines.elided[offset]
4607 # We also suppress warnings for `uint64_t{expression}` etc., as the style
4608 # guide recommends brace initialization for integral types to avoid
4609 # overflow/truncation.
4610 if not re.match(r"^[\s}]*[{.;,)<>\]:]", trailing_text) and not _IsType(
4611 clean_lines, nesting_state, leading_text
4612 ):
4613 error(filename, linenum, "whitespace/braces", 5, "Missing space before {")
4614
4615 # Make sure '} else {' has spaces.
4616 if re.search(r"}else", line):
4617 error(filename, linenum, "whitespace/braces", 5, "Missing space before else")
4618
4619 # You shouldn't have a space before a semicolon at the end of the line.
4620 # There's a special case for "for" since the style guide allows space before
4621 # the semicolon there.
4622 if re.search(r":\s*;\s*$", line):
4623 error(
4624 filename,
4625 linenum,
4626 "whitespace/semicolon",
4627 5,
4628 "Semicolon defining empty statement. Use {} instead.",
4629 )
4630 elif re.search(r"^\s*;\s*$", line):
4631 error(
4632 filename,
4633 linenum,
4634 "whitespace/semicolon",
4635 5,
4636 "Line contains only semicolon. If this should be an empty statement, use {} instead.",
4637 )
4638 elif re.search(r"\s+;\s*$", line) and not re.search(r"\bfor\b", line):
4639 error(
4640 filename,
4641 linenum,
4642 "whitespace/semicolon",
4643 5,
4644 "Extra space before last semicolon. If this should be an empty "
4645 "statement, use {} instead.",
4646 )
4647
4648
4649 def IsDecltype(clean_lines, linenum, column):
4650 """Check if the token ending on (linenum, column) is decltype().
4651
4652 Args:
4653 clean_lines: A CleansedLines instance containing the file.
4654 linenum: the number of the line to check.
4655 column: end column of the token to check.
4656 Returns:
4657 True if this token is decltype() expression, False otherwise.
4658 """
4659 (text, _, start_col) = ReverseCloseExpression(clean_lines, linenum, column)
4660 if start_col < 0:
4661 return False
4662 return bool(re.search(r"\bdecltype\s*$", text[0:start_col]))
4663
4664
4665 def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error):
4666 """Checks for additional blank line issues related to sections.
4667
4668 Currently the only thing checked here is blank line before protected/private.
4669
4670 Args:
4671 filename: The name of the current file.
4672 clean_lines: A CleansedLines instance containing the file.
4673 class_info: A _ClassInfo objects.
4674 linenum: The number of the line to check.
4675 error: The function to call with any errors found.
4676 """
4677 # Skip checks if the class is small, where small means 25 lines or less.
4678 # 25 lines seems like a good cutoff since that's the usual height of
4679 # terminals, and any class that can't fit in one screen can't really
4680 # be considered "small".
4681 #
4682 # Also skip checks if we are on the first line. This accounts for
4683 # classes that look like
4684 # class Foo { public: ... };
4685 #
4686 # If we didn't find the end of the class, last_line would be zero,
4687 # and the check will be skipped by the first condition.
4688 if (
4689 class_info.last_line - class_info.starting_linenum <= 24
4690 or linenum <= class_info.starting_linenum
4691 ):
4692 return
4693
4694 matched = re.match(r"\s*(public|protected|private):", clean_lines.lines[linenum])
4695 if matched:
4696 # Issue warning if the line before public/protected/private was
4697 # not a blank line, but don't do this if the previous line contains
4698 # "class" or "struct". This can happen two ways:
4699 # - We are at the beginning of the class.
4700 # - We are forward-declaring an inner class that is semantically
4701 # private, but needed to be public for implementation reasons.
4702 # Also ignores cases where the previous line ends with a backslash as can be
4703 # common when defining classes in C macros.
4704 prev_line = clean_lines.lines[linenum - 1]
4705 if (
4706 not IsBlankLine(prev_line)
4707 and not re.search(r"\b(class|struct)\b", prev_line)
4708 and not re.search(r"\\$", prev_line)
4709 ):
4710 # Try a bit harder to find the beginning of the class. This is to
4711 # account for multi-line base-specifier lists, e.g.:
4712 # class Derived
4713 # : public Base {
4714 end_class_head = class_info.starting_linenum
4715 for i in range(class_info.starting_linenum, linenum):
4716 if re.search(r"\{\s*$", clean_lines.lines[i]):
4717 end_class_head = i
4718 break
4719 if end_class_head < linenum - 1:
4720 error(
4721 filename,
4722 linenum,
4723 "whitespace/blank_line",
4724 3,
4725 f'"{matched.group(1)}:" should be preceded by a blank line',
4726 )
4727
4728
4729 def GetPreviousNonBlankLine(clean_lines, linenum):
4730 """Return the most recent non-blank line and its line number.
4731
4732 Args:
4733 clean_lines: A CleansedLines instance containing the file contents.
4734 linenum: The number of the line to check.
4735
4736 Returns:
4737 A tuple with two elements. The first element is the contents of the last
4738 non-blank line before the current line, or the empty string if this is the
4739 first non-blank line. The second is the line number of that line, or -1
4740 if this is the first non-blank line.
4741 """
4742
4743 prevlinenum = linenum - 1
4744 while prevlinenum >= 0:
4745 prevline = clean_lines.elided[prevlinenum]
4746 if not IsBlankLine(prevline): # if not a blank line...
4747 return (prevline, prevlinenum)
4748 prevlinenum -= 1
4749 return ("", -1)
4750
4751
4752 def CheckBraces(filename, clean_lines, linenum, error):
4753 """Looks for misplaced braces (e.g. at the end of line).
4754
4755 Args:
4756 filename: The name of the current file.
4757 clean_lines: A CleansedLines instance containing the file.
4758 linenum: The number of the line to check.
4759 error: The function to call with any errors found.
4760 """
4761
4762 line = clean_lines.elided[linenum] # get rid of comments and strings
4763
4764 if re.match(r"\s*{\s*$", line):
4765 # We allow an open brace to start a line in the case where someone is using
4766 # braces in a block to explicitly create a new scope, which is commonly used
4767 # to control the lifetime of stack-allocated variables. Braces are also
4768 # used for brace initializers inside function calls. We don't detect this
4769 # perfectly: we just don't complain if the last non-whitespace character on
4770 # the previous non-blank line is ',', ';', ':', '(', '{', or '}', or if the
4771 # previous line starts a preprocessor block. We also allow a brace on the
4772 # following line if it is part of an array initialization and would not fit
4773 # within the 80 character limit of the preceding line.
4774 prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
4775 if (
4776 not re.search(r"[,;:}{(]\s*$", prevline)
4777 and not re.match(r"\s*#", prevline)
4778 and not (GetLineWidth(prevline) > _line_length - 2 and "[]" in prevline)
4779 ):
4780 error(
4781 filename,
4782 linenum,
4783 "whitespace/braces",
4784 4,
4785 "{ should almost always be at the end of the previous line",
4786 )
4787
4788 # An else clause should be on the same line as the preceding closing brace.
4789 if last_wrong := re.match(r"\s*else\b\s*(?:if\b|\{|$)", line):
4790 prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
4791 if re.match(r"\s*}\s*$", prevline):
4792 error(
4793 filename,
4794 linenum,
4795 "whitespace/newline",
4796 4,
4797 "An else should appear on the same line as the preceding }",
4798 )
4799 else:
4800 last_wrong = False
4801
4802 # If braces come on one side of an else, they should be on both.
4803 # However, we have to worry about "else if" that spans multiple lines!
4804 if re.search(r"else if\s*\(", line): # could be multi-line if
4805 brace_on_left = bool(re.search(r"}\s*else if\s*\(", line))
4806 # find the ( after the if
4807 pos = line.find("else if")
4808 pos = line.find("(", pos)
4809 if pos > 0:
4810 (endline, _, endpos) = CloseExpression(clean_lines, linenum, pos)
4811 brace_on_right = endline[endpos:].find("{") != -1
4812 if brace_on_left != brace_on_right: # must be brace after if
4813 error(
4814 filename,
4815 linenum,
4816 "readability/braces",
4817 5,
4818 "If an else has a brace on one side, it should have it on both",
4819 )
4820 # Prevent detection if statement has { and we detected an improper newline after }
4821 elif re.search(r"}\s*else[^{]*$", line) or (
4822 re.match(r"[^}]*else\s*{", line) and not last_wrong
4823 ):
4824 error(
4825 filename,
4826 linenum,
4827 "readability/braces",
4828 5,
4829 "If an else has a brace on one side, it should have it on both",
4830 )
4831
4832 # No control clauses with braces should have its contents on the same line
4833 # Exclude } which will be covered by empty-block detect
4834 # Exclude ; which may be used by while in a do-while
4835 if (
4836 keyword := re.search(
4837 r"\b(else if|if|while|for|switch)" # These have parens
4838 r"\s*\(.*\)\s*(?:\[\[(?:un)?likely\]\]\s*)?{\s*[^\s\\};]",
4839 line,
4840 )
4841 ) or (
4842 keyword := re.search(
4843 r"\b(else|do|try)" # These don't have parens
4844 r"\s*(?:\[\[(?:un)?likely\]\]\s*)?{\s*[^\s\\}]",
4845 line,
4846 )
4847 ):
4848 error(
4849 filename,
4850 linenum,
4851 "whitespace/newline",
4852 5,
4853 f"Controlled statements inside brackets of {keyword.group(1)} clause"
4854 " should be on a separate line",
4855 )
4856
4857 # TODO(aaronliu0130): Err on if...else and do...while statements without braces;
4858 # style guide has changed since the below comment was written
4859
4860 # Check single-line if/else bodies. The style guide says 'curly braces are not
4861 # required for single-line statements'. We additionally allow multi-line,
4862 # single statements, but we reject anything with more than one semicolon in
4863 # it. This means that the first semicolon after the if should be at the end of
4864 # its line, and the line after that should have an indent level equal to or
4865 # lower than the if. We also check for ambiguous if/else nesting without
4866 # braces.
4867 if_else_match = re.search(r"\b(if\s*(|constexpr)\s*\(|else\b)", line)
4868 if if_else_match and not re.match(r"\s*#", line):
4869 if_indent = GetIndentLevel(line)
4870 endline, endlinenum, endpos = line, linenum, if_else_match.end()
4871 if_match = re.search(r"\bif\s*(|constexpr)\s*\(", line)
4872 if if_match:
4873 # This could be a multiline if condition, so find the end first.
4874 pos = if_match.end() - 1
4875 (endline, endlinenum, endpos) = CloseExpression(clean_lines, linenum, pos)
4876 # Check for an opening brace, either directly after the if or on the next
4877 # line. If found, this isn't a single-statement conditional.
4878 if not re.match(r"\s*(?:\[\[(?:un)?likely\]\]\s*)?{", endline[endpos:]) and not (
4879 re.match(r"\s*$", endline[endpos:])
4880 and endlinenum < (len(clean_lines.elided) - 1)
4881 and re.match(r"\s*{", clean_lines.elided[endlinenum + 1])
4882 ):
4883 while (
4884 endlinenum < len(clean_lines.elided)
4885 and ";" not in clean_lines.elided[endlinenum][endpos:]
4886 ):
4887 endlinenum += 1
4888 endpos = 0
4889 if endlinenum < len(clean_lines.elided):
4890 endline = clean_lines.elided[endlinenum]
4891 # We allow a mix of whitespace and closing braces (e.g. for one-liner
4892 # methods) and a single \ after the semicolon (for macros)
4893 endpos = endline.find(";")
4894 if not re.match(r";[\s}]*(\\?)$", endline[endpos:]):
4895 # Semicolon isn't the last character, there's something trailing.
4896 # Output a warning if the semicolon is not contained inside
4897 # a lambda expression.
4898 if not re.match(r"^[^{};]*\[[^\[\]]*\][^{}]*\{[^{}]*\}\s*\)*[;,]\s*$", endline):
4899 error(
4900 filename,
4901 linenum,
4902 "readability/braces",
4903 4,
4904 "If/else bodies with multiple statements require braces",
4905 )
4906 elif endlinenum < len(clean_lines.elided) - 1:
4907 # Make sure the next line is dedented
4908 next_line = clean_lines.elided[endlinenum + 1]
4909 next_indent = GetIndentLevel(next_line)
4910 # With ambiguous nested if statements, this will error out on the
4911 # if that *doesn't* match the else, regardless of whether it's the
4912 # inner one or outer one.
4913 if if_match and re.match(r"\s*else\b", next_line) and next_indent != if_indent:
4914 error(
4915 filename,
4916 linenum,
4917 "readability/braces",
4918 4,
4919 "Else clause should be indented at the same level as if. "
4920 "Ambiguous nested if/else chains require braces.",
4921 )
4922 elif next_indent > if_indent:
4923 error(
4924 filename,
4925 linenum,
4926 "readability/braces",
4927 4,
4928 "If/else bodies with multiple statements require braces",
4929 )
4930
4931
4932 def CheckTrailingSemicolon(filename, clean_lines, linenum, error):
4933 """Looks for redundant trailing semicolon.
4934
4935 Args:
4936 filename: The name of the current file.
4937 clean_lines: A CleansedLines instance containing the file.
4938 linenum: The number of the line to check.
4939 error: The function to call with any errors found.
4940 """
4941
4942 line = clean_lines.elided[linenum]
4943
4944 # Block bodies should not be followed by a semicolon. Due to C++11
4945 # brace initialization, there are more places where semicolons are
4946 # required than not, so we explicitly list the allowed rules rather
4947 # than listing the disallowed ones. These are the places where "};"
4948 # should be replaced by just "}":
4949 # 1. Some flavor of block following closing parenthesis:
4950 # for (;;) {};
4951 # while (...) {};
4952 # switch (...) {};
4953 # Function(...) {};
4954 # if (...) {};
4955 # if (...) else if (...) {};
4956 #
4957 # 2. else block:
4958 # if (...) else {};
4959 #
4960 # 3. const member function:
4961 # Function(...) const {};
4962 #
4963 # 4. Block following some statement:
4964 # x = 42;
4965 # {};
4966 #
4967 # 5. Block at the beginning of a function:
4968 # Function(...) {
4969 # {};
4970 # }
4971 #
4972 # Note that naively checking for the preceding "{" will also match
4973 # braces inside multi-dimensional arrays, but this is fine since
4974 # that expression will not contain semicolons.
4975 #
4976 # 6. Block following another block:
4977 # while (true) {}
4978 # {};
4979 #
4980 # 7. End of namespaces:
4981 # namespace {};
4982 #
4983 # These semicolons seems far more common than other kinds of
4984 # redundant semicolons, possibly due to people converting classes
4985 # to namespaces. For now we do not warn for this case.
4986 #
4987 # Try matching case 1 first.
4988 match = re.match(r"^(.*\)\s*)\{", line)
4989 if match:
4990 # Matched closing parenthesis (case 1). Check the token before the
4991 # matching opening parenthesis, and don't warn if it looks like a
4992 # macro. This avoids these false positives:
4993 # - macro that defines a base class
4994 # - multi-line macro that defines a base class
4995 # - macro that defines the whole class-head
4996 #
4997 # But we still issue warnings for macros that we know are safe to
4998 # warn, specifically:
4999 # - TEST, TEST_F, TEST_P, MATCHER, MATCHER_P
5000 # - TYPED_TEST
5001 # - INTERFACE_DEF
5002 # - EXCLUSIVE_LOCKS_REQUIRED, SHARED_LOCKS_REQUIRED, LOCKS_EXCLUDED:
5003 #
5004 # We implement a list of safe macros instead of a list of
5005 # unsafe macros, even though the latter appears less frequently in
5006 # google code and would have been easier to implement. This is because
5007 # the downside for getting the allowed checks wrong means some extra
5008 # semicolons, while the downside for getting disallowed checks wrong
5009 # would result in compile errors.
5010 #
5011 # In addition to macros, we also don't want to warn on
5012 # - Compound literals
5013 # - Lambdas
5014 # - alignas specifier with anonymous structs
5015 # - decltype
5016 # - concepts (requires expression)
5017 closing_brace_pos = match.group(1).rfind(")")
5018 opening_parenthesis = ReverseCloseExpression(clean_lines, linenum, closing_brace_pos)
5019 if opening_parenthesis[2] > -1:
5020 line_prefix = opening_parenthesis[0][0 : opening_parenthesis[2]]
5021 macro = re.search(r"\b([A-Z_][A-Z0-9_]*)\s*$", line_prefix)
5022 func = re.match(r"^(.*\])\s*$", line_prefix)
5023 if (
5024 (
5025 macro
5026 and macro.group(1)
5027 not in (
5028 "TEST",
5029 "TEST_F",
5030 "MATCHER",
5031 "MATCHER_P",
5032 "TYPED_TEST",
5033 "EXCLUSIVE_LOCKS_REQUIRED",
5034 "SHARED_LOCKS_REQUIRED",
5035 "LOCKS_EXCLUDED",
5036 "INTERFACE_DEF",
5037 )
5038 )
5039 or (func and not re.search(r"\boperator\s*\[\s*\]", func.group(1)))
5040 or re.search(r"\b(?:struct|union)\s+alignas\s*$", line_prefix)
5041 or re.search(r"\bdecltype$", line_prefix)
5042 or re.search(r"\brequires.*$", line_prefix)
5043 or re.search(r"\s+=\s*$", line_prefix)
5044 ):
5045 match = None
5046 if (
5047 match
5048 and opening_parenthesis[1] > 1
5049 and re.search(r"\]\s*$", clean_lines.elided[opening_parenthesis[1] - 1])
5050 ):
5051 # Multi-line lambda-expression
5052 match = None
5053
5054 else:
5055 # Try matching cases 2-3.
5056 match = re.match(r"^(.*(?:else|\)\s*const)\s*)\{", line)
5057 if not match:
5058 # Try matching cases 4-6. These are always matched on separate lines.
5059 #
5060 # Note that we can't simply concatenate the previous line to the
5061 # current line and do a single match, otherwise we may output
5062 # duplicate warnings for the blank line case:
5063 # if (cond) {
5064 # // blank line
5065 # }
5066 prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
5067 if prevline and re.search(r"[;{}]\s*$", prevline):
5068 match = re.match(r"^(\s*)\{", line)
5069
5070 # Check matching closing brace
5071 if match:
5072 (endline, endlinenum, endpos) = CloseExpression(clean_lines, linenum, len(match.group(1)))
5073 if endpos > -1 and re.match(r"^\s*;", endline[endpos:]):
5074 # Current {} pair is eligible for semicolon check, and we have found
5075 # the redundant semicolon, output warning here.
5076 #
5077 # Note: because we are scanning forward for opening braces, and
5078 # outputting warnings for the matching closing brace, if there are
5079 # nested blocks with trailing semicolons, we will get the error
5080 # messages in reversed order.
5081
5082 # We need to check the line forward for NOLINT
5083 raw_lines = clean_lines.raw_lines
5084 ParseNolintSuppressions(filename, raw_lines[endlinenum - 1], endlinenum - 1, error)
5085 ParseNolintSuppressions(filename, raw_lines[endlinenum], endlinenum, error)
5086
5087 error(filename, endlinenum, "readability/braces", 4, "You don't need a ; after a }")
5088
5089
5090 def CheckEmptyBlockBody(filename, clean_lines, linenum, error):
5091 """Look for empty loop/conditional body with only a single semicolon.
5092
5093 Args:
5094 filename: The name of the current file.
5095 clean_lines: A CleansedLines instance containing the file.
5096 linenum: The number of the line to check.
5097 error: The function to call with any errors found.
5098 """
5099
5100 # Search for loop keywords at the beginning of the line. Because only
5101 # whitespaces are allowed before the keywords, this will also ignore most
5102 # do-while-loops, since those lines should start with closing brace.
5103 #
5104 # We also check "if" blocks here, since an empty conditional block
5105 # is likely an error.
5106 line = clean_lines.elided[linenum]
5107 if matched := re.match(r"\s*(for|while|if)\s*\(", line):
5108 # Find the end of the conditional expression.
5109 (end_line, end_linenum, end_pos) = CloseExpression(clean_lines, linenum, line.find("("))
5110
5111 # Output warning if what follows the condition expression is a semicolon.
5112 # No warning for all other cases, including whitespace or newline, since we
5113 # have a separate check for semicolons preceded by whitespace.
5114 if end_pos >= 0 and re.match(r";", end_line[end_pos:]):
5115 if matched.group(1) == "if":
5116 error(
5117 filename,
5118 end_linenum,
5119 "whitespace/empty_conditional_body",
5120 5,
5121 "Empty conditional bodies should use {}",
5122 )
5123 else:
5124 error(
5125 filename,
5126 end_linenum,
5127 "whitespace/empty_loop_body",
5128 5,
5129 "Empty loop bodies should use {} or continue",
5130 )
5131
5132 # Check for if statements that have completely empty bodies (no comments)
5133 # and no else clauses.
5134 if end_pos >= 0 and matched.group(1) == "if":
5135 # Find the position of the opening { for the if statement.
5136 # Return without logging an error if it has no brackets.
5137 opening_linenum = end_linenum
5138 opening_line_fragment = end_line[end_pos:]
5139 # Loop until EOF or find anything that's not whitespace or opening {.
5140 while not re.search(r"^\s*\{", opening_line_fragment):
5141 if re.search(r"^(?!\s*$)", opening_line_fragment):
5142 # Conditional has no brackets.
5143 return
5144 opening_linenum += 1
5145 if opening_linenum == len(clean_lines.elided):
5146 # Couldn't find conditional's opening { or any code before EOF.
5147 return
5148 opening_line_fragment = clean_lines.elided[opening_linenum]
5149 # Set opening_line (opening_line_fragment may not be entire opening line).
5150 opening_line = clean_lines.elided[opening_linenum]
5151
5152 # Find the position of the closing }.
5153 opening_pos = opening_line_fragment.find("{")
5154 if opening_linenum == end_linenum:
5155 # We need to make opening_pos relative to the start of the entire line.
5156 opening_pos += end_pos
5157 (closing_line, closing_linenum, closing_pos) = CloseExpression(
5158 clean_lines, opening_linenum, opening_pos
5159 )
5160 if closing_pos < 0:
5161 return
5162
5163 # Now construct the body of the conditional. This consists of the portion
5164 # of the opening line after the {, all lines until the closing line,
5165 # and the portion of the closing line before the }.
5166 if clean_lines.raw_lines[opening_linenum] != CleanseComments(
5167 clean_lines.raw_lines[opening_linenum]
5168 ):
5169 # Opening line ends with a comment, so conditional isn't empty.
5170 return
5171 if closing_linenum > opening_linenum:
5172 # Opening line after the {. Ignore comments here since we checked above.
5173 bodylist = list(opening_line[opening_pos + 1 :])
5174 # All lines until closing line, excluding closing line, with comments.
5175 bodylist.extend(clean_lines.raw_lines[opening_linenum + 1 : closing_linenum])
5176 # Closing line before the }. Won't (and can't) have comments.
5177 bodylist.append(clean_lines.elided[closing_linenum][: closing_pos - 1])
5178 body = "\n".join(bodylist)
5179 else:
5180 # If statement has brackets and fits on a single line.
5181 body = opening_line[opening_pos + 1 : closing_pos - 1]
5182
5183 # Check if the body is empty
5184 if not _EMPTY_CONDITIONAL_BODY_PATTERN.search(body):
5185 return
5186 # The body is empty. Now make sure there's not an else clause.
5187 current_linenum = closing_linenum
5188 current_line_fragment = closing_line[closing_pos:]
5189 # Loop until EOF or find anything that's not whitespace or else clause.
5190 while re.search(r"^\s*$|^(?=\s*else)", current_line_fragment):
5191 if re.search(r"^(?=\s*else)", current_line_fragment):
5192 # Found an else clause, so don't log an error.
5193 return
5194 current_linenum += 1
5195 if current_linenum == len(clean_lines.elided):
5196 break
5197 current_line_fragment = clean_lines.elided[current_linenum]
5198
5199 # The body is empty and there's no else clause until EOF or other code.
5200 error(
5201 filename,
5202 end_linenum,
5203 "whitespace/empty_if_body",
5204 4,
5205 ("If statement had no body and no else clause"),
5206 )
5207
5208
5209 def FindCheckMacro(line):
5210 """Find a replaceable CHECK-like macro.
5211
5212 Args:
5213 line: line to search on.
5214 Returns:
5215 (macro name, start position), or (None, -1) if no replaceable
5216 macro is found.
5217 """
5218 for macro in _CHECK_MACROS:
5219 i = line.find(macro)
5220 if i >= 0:
5221 # Find opening parenthesis. Do a regular expression match here
5222 # to make sure that we are matching the expected CHECK macro, as
5223 # opposed to some other macro that happens to contain the CHECK
5224 # substring.
5225 matched = re.match(r"^(.*\b" + macro + r"\s*)\(", line)
5226 if not matched:
5227 continue
5228 return (macro, len(matched.group(1)))
5229 return (None, -1)
5230
5231
5232 def CheckCheck(filename, clean_lines, linenum, error):
5233 """Checks the use of CHECK and EXPECT macros.
5234
5235 Args:
5236 filename: The name of the current file.
5237 clean_lines: A CleansedLines instance containing the file.
5238 linenum: The number of the line to check.
5239 error: The function to call with any errors found.
5240 """
5241
5242 # Decide the set of replacement macros that should be suggested
5243 lines = clean_lines.elided
5244 (check_macro, start_pos) = FindCheckMacro(lines[linenum])
5245 if not check_macro:
5246 return
5247
5248 # Find end of the boolean expression by matching parentheses
5249 (last_line, end_line, end_pos) = CloseExpression(clean_lines, linenum, start_pos)
5250 if end_pos < 0:
5251 return
5252
5253 # If the check macro is followed by something other than a
5254 # semicolon, assume users will log their own custom error messages
5255 # and don't suggest any replacements.
5256 if not re.match(r"\s*;", last_line[end_pos:]):
5257 return
5258
5259 if linenum == end_line:
5260 expression = lines[linenum][start_pos + 1 : end_pos - 1]
5261 else:
5262 expression = lines[linenum][start_pos + 1 :]
5263 for i in range(linenum + 1, end_line):
5264 expression += lines[i]
5265 expression += last_line[0 : end_pos - 1]
5266
5267 # Parse expression so that we can take parentheses into account.
5268 # This avoids false positives for inputs like "CHECK((a < 4) == b)",
5269 # which is not replaceable by CHECK_LE.
5270 lhs = ""
5271 rhs = ""
5272 operator = None
5273 while expression:
5274 matched = re.match(
5275 r"^\s*(<<|<<=|>>|>>=|->\*|->|&&|\|\||"
5276 r"==|!=|>=|>|<=|<|\()(.*)$",
5277 expression,
5278 )
5279 if matched:
5280 token = matched.group(1)
5281 if token == "(":
5282 # Parenthesized operand
5283 expression = matched.group(2)
5284 (end, _) = FindEndOfExpressionInLine(expression, 0, ["("])
5285 if end < 0:
5286 return # Unmatched parenthesis
5287 lhs += "(" + expression[0:end]
5288 expression = expression[end:]
5289 elif token in ("&&", "||"):
5290 # Logical and/or operators. This means the expression
5291 # contains more than one term, for example:
5292 # CHECK(42 < a && a < b);
5293 #
5294 # These are not replaceable with CHECK_LE, so bail out early.
5295 return
5296 elif token in ("<<", "<<=", ">>", ">>=", "->*", "->"):
5297 # Non-relational operator
5298 lhs += token
5299 expression = matched.group(2)
5300 else:
5301 # Relational operator
5302 operator = token
5303 rhs = matched.group(2)
5304 break
5305 else:
5306 # Unparenthesized operand. Instead of appending to lhs one character
5307 # at a time, we do another regular expression match to consume several
5308 # characters at once if possible. Trivial benchmark shows that this
5309 # is more efficient when the operands are longer than a single
5310 # character, which is generally the case.
5311 matched = re.match(r"^([^-=!<>()&|]+)(.*)$", expression)
5312 if not matched:
5313 matched = re.match(r"^(\s*\S)(.*)$", expression)
5314 if not matched:
5315 break
5316 lhs += matched.group(1)
5317 expression = matched.group(2)
5318
5319 # Only apply checks if we got all parts of the boolean expression
5320 if not (lhs and operator and rhs):
5321 return
5322
5323 # Check that rhs do not contain logical operators. We already know
5324 # that lhs is fine since the loop above parses out && and ||.
5325 if rhs.find("&&") > -1 or rhs.find("||") > -1:
5326 return
5327
5328 # At least one of the operands must be a constant literal. This is
5329 # to avoid suggesting replacements for unprintable things like
5330 # CHECK(variable != iterator)
5331 #
5332 # The following pattern matches decimal, hex integers, strings, and
5333 # characters (in that order).
5334 lhs = lhs.strip()
5335 rhs = rhs.strip()
5336 match_constant = r'^([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')$'
5337 if re.match(match_constant, lhs) or re.match(match_constant, rhs):
5338 # Note: since we know both lhs and rhs, we can provide a more
5339 # descriptive error message like:
5340 # Consider using CHECK_EQ(x, 42) instead of CHECK(x == 42)
5341 # Instead of:
5342 # Consider using CHECK_EQ instead of CHECK(a == b)
5343 #
5344 # We are still keeping the less descriptive message because if lhs
5345 # or rhs gets long, the error message might become unreadable.
5346 error(
5347 filename,
5348 linenum,
5349 "readability/check",
5350 2,
5351 f"Consider using {_CHECK_REPLACEMENT[check_macro][operator]}"
5352 f" instead of {check_macro}(a {operator} b)",
5353 )
5354
5355
5356 def CheckAltTokens(filename, clean_lines, linenum, error):
5357 """Check alternative keywords being used in boolean expressions.
5358
5359 Args:
5360 filename: The name of the current file.
5361 clean_lines: A CleansedLines instance containing the file.
5362 linenum: The number of the line to check.
5363 error: The function to call with any errors found.
5364 """
5365 line = clean_lines.elided[linenum]
5366
5367 # Avoid preprocessor lines
5368 if re.match(r"^\s*#", line):
5369 return
5370
5371 # Last ditch effort to avoid multi-line comments. This will not help
5372 # if the comment started before the current line or ended after the
5373 # current line, but it catches most of the false positives. At least,
5374 # it provides a way to workaround this warning for people who use
5375 # multi-line comments in preprocessor macros.
5376 #
5377 # TODO(google): remove this once cpplint has better support for
5378 # multi-line comments.
5379 if line.find("/*") >= 0 or line.find("*/") >= 0:
5380 return
5381
5382 for match in _ALT_TOKEN_REPLACEMENT_PATTERN.finditer(line):
5383 error(
5384 filename,
5385 linenum,
5386 "readability/alt_tokens",
5387 2,
5388 f"Use operator {_ALT_TOKEN_REPLACEMENT[match.group(2)]} instead of {match.group(2)}",
5389 )
5390
5391
5392 def GetLineWidth(line):
5393 """Determines the width of the line in column positions.
5394
5395 Args:
5396 line: A string, which may be a Unicode string.
5397
5398 Returns:
5399 The width of the line in column positions, accounting for Unicode
5400 combining characters and wide characters.
5401 """
5402 if isinstance(line, str):
5403 width = 0
5404 for uc in unicodedata.normalize("NFC", line):
5405 if unicodedata.east_asian_width(uc) in ("W", "F"):
5406 width += 2
5407 elif not unicodedata.combining(uc):
5408 # Issue 337
5409 # https://mail.python.org/pipermail/python-list/2012-August/628809.html
5410 if (sys.version_info.major, sys.version_info.minor) <= (3, 2):
5411 # https://github.com/python/cpython/blob/2.7/Include/unicodeobject.h#L81
5412 is_wide_build = sysconfig.get_config_var("Py_UNICODE_SIZE") >= 4
5413 # https://github.com/python/cpython/blob/2.7/Objects/unicodeobject.c#L564
5414 is_low_surrogate = 0xDC00 <= ord(uc) <= 0xDFFF
5415 if not is_wide_build and is_low_surrogate:
5416 width -= 1
5417
5418 width += 1
5419 return width
5420 return len(line)
5421
5422
5423 def CheckStyle(filename, clean_lines, linenum, file_extension, nesting_state, error, cppvar=None):
5424 """Checks rules from the 'C++ style rules' section of cppguide.html.
5425
5426 Most of these rules are hard to test (naming, comment style), but we
5427 do what we can. In particular we check for 2-space indents, line lengths,
5428 tab usage, spaces inside code, etc.
5429
5430 Args:
5431 filename: The name of the current file.
5432 clean_lines: A CleansedLines instance containing the file.
5433 linenum: The number of the line to check.
5434 file_extension: The extension (without the dot) of the filename.
5435 nesting_state: A NestingState instance which maintains information about
5436 the current stack of nested blocks being parsed.
5437 error: The function to call with any errors found.
5438 cppvar: The header guard variable returned by GetHeaderGuardCPPVar.
5439 """
5440
5441 # Don't use "elided" lines here, otherwise we can't check commented lines.
5442 # Don't want to use "raw" either, because we don't want to check inside C++11
5443 # raw strings,
5444 raw_lines = clean_lines.lines_without_raw_strings
5445 line = raw_lines[linenum]
5446 prev = raw_lines[linenum - 1] if linenum > 0 else ""
5447
5448 if line.find("\t") != -1:
5449 error(filename, linenum, "whitespace/tab", 1, "Tab found; better to use spaces")
5450
5451 # One or three blank spaces at the beginning of the line is weird; it's
5452 # hard to reconcile that with 2-space indents.
5453 # NOTE: here are the conditions rob pike used for his tests. Mine aren't
5454 # as sophisticated, but it may be worth becoming so: RLENGTH==initial_spaces
5455 # if(RLENGTH > 20) complain = 0;
5456 # if(match($0, " +(error|private|public|protected):")) complain = 0;
5457 # if(match(prev, "&& *$")) complain = 0;
5458 # if(match(prev, "\\|\\| *$")) complain = 0;
5459 # if(match(prev, "[\",=><] *$")) complain = 0;
5460 # if(match($0, " <<")) complain = 0;
5461 # if(match(prev, " +for \\(")) complain = 0;
5462 # if(prevodd && match(prevprev, " +for \\(")) complain = 0;
5463 scope_or_label_pattern = r"\s*(?:public|private|protected|signals)(?:\s+(?:slots\s*)?)?:\s*\\?$"
5464 classinfo = nesting_state.InnermostClass()
5465 initial_spaces = 0
5466 cleansed_line = clean_lines.elided[linenum]
5467 while initial_spaces < len(line) and line[initial_spaces] == " ":
5468 initial_spaces += 1
5469 # There are certain situations we allow one space, notably for
5470 # section labels, and also lines containing multi-line raw strings.
5471 # We also don't check for lines that look like continuation lines
5472 # (of lines ending in double quotes, commas, equals, or angle brackets)
5473 # because the rules for how to indent those are non-trivial.
5474 if (
5475 not re.search(r'[",=><] *$', prev)
5476 and (initial_spaces in {1, 3})
5477 and not re.match(scope_or_label_pattern, cleansed_line)
5478 and not (clean_lines.raw_lines[linenum] != line and re.match(r'^\s*""', line))
5479 ):
5480 error(
5481 filename,
5482 linenum,
5483 "whitespace/indent",
5484 3,
5485 "Weird number of spaces at line-start. Are you using a 2-space indent?",
5486 )
5487
5488 if line and line[-1].isspace():
5489 error(
5490 filename,
5491 linenum,
5492 "whitespace/end_of_line",
5493 4,
5494 "Line ends in whitespace. Consider deleting these extra spaces.",
5495 )
5496
5497 # Check if the line is a header guard.
5498 is_header_guard = IsHeaderExtension(file_extension) and line.startswith(
5499 (f"#ifndef {cppvar}", f"#define {cppvar}", f"#endif // {cppvar}")
5500 )
5501 # #include lines and header guards can be long, since there's no clean way to
5502 # split them.
5503 #
5504 # URLs can be long too. It's possible to split these, but it makes them
5505 # harder to cut&paste.
5506 #
5507 # The "$Id:...$" comment may also get very long without it being the
5508 # developers fault.
5509 #
5510 # Doxygen documentation copying can get pretty long when using an overloaded
5511 # function declaration
5512 if (
5513 not line.startswith("#include")
5514 and not is_header_guard
5515 and not re.match(r"^\s*//.*http(s?)://\S*$", line)
5516 and not re.match(r"^\s*//\s*[^\s]*$", line)
5517 and not re.match(r"^// \$Id:.*#[0-9]+ \$$", line)
5518 and not re.match(r"^\s*/// [@\\](copydoc|copydetails|copybrief) .*$", line)
5519 ):
5520 line_width = GetLineWidth(line)
5521 if line_width > _line_length:
5522 error(
5523 filename,
5524 linenum,
5525 "whitespace/line_length",
5526 2,
5527 f"Lines should be <= {_line_length} characters long",
5528 )
5529
5530 if (
5531 cleansed_line.count(";") > 1
5532 and
5533 # allow simple single line lambdas
5534 not re.match(r"^[^{};]*\[[^\[\]]*\][^{}]*\{[^{}\n\r]*\}", line)
5535 and
5536 # for loops are allowed two ;'s (and may run over two lines).
5537 cleansed_line.find("for") == -1
5538 and (
5539 GetPreviousNonBlankLine(clean_lines, linenum)[0].find("for") == -1
5540 or GetPreviousNonBlankLine(clean_lines, linenum)[0].find(";") != -1
5541 )
5542 and
5543 # It's ok to have many commands in a switch case that fits in 1 line
5544 not (
5545 (cleansed_line.find("case ") != -1 or cleansed_line.find("default:") != -1)
5546 and cleansed_line.find("break;") != -1
5547 )
5548 ):
5549 error(filename, linenum, "whitespace/newline", 0, "More than one command on the same line")
5550
5551 # Some more style checks
5552 CheckBraces(filename, clean_lines, linenum, error)
5553 CheckTrailingSemicolon(filename, clean_lines, linenum, error)
5554 CheckEmptyBlockBody(filename, clean_lines, linenum, error)
5555 CheckSpacing(filename, clean_lines, linenum, nesting_state, error)
5556 CheckOperatorSpacing(filename, clean_lines, linenum, error)
5557 CheckParenthesisSpacing(filename, clean_lines, linenum, error)
5558 CheckCommaSpacing(filename, clean_lines, linenum, error)
5559 CheckBracesSpacing(filename, clean_lines, linenum, nesting_state, error)
5560 CheckSpacingForFunctionCall(filename, clean_lines, linenum, error)
5561 CheckCheck(filename, clean_lines, linenum, error)
5562 CheckAltTokens(filename, clean_lines, linenum, error)
5563 classinfo = nesting_state.InnermostClass()
5564 if classinfo:
5565 CheckSectionSpacing(filename, clean_lines, classinfo, linenum, error)
5566
5567
5568 _RE_PATTERN_INCLUDE = re.compile(r'^\s*#\s*include\s*([<"])([^>"]*)[>"].*$')
5569 # Matches the first component of a filename delimited by -s and _s. That is:
5570 # _RE_FIRST_COMPONENT.match('foo').group(0) == 'foo'
5571 # _RE_FIRST_COMPONENT.match('foo.cc').group(0) == 'foo'
5572 # _RE_FIRST_COMPONENT.match('foo-bar_baz.cc').group(0) == 'foo'
5573 # _RE_FIRST_COMPONENT.match('foo_bar-baz.cc').group(0) == 'foo'
5574 _RE_FIRST_COMPONENT = re.compile(r"^[^-_.]+")
5575
5576
5577 def _DropCommonSuffixes(filename):
5578 """Drops common suffixes like _test.cc or -inl.h from filename.
5579
5580 For example:
5581 >>> _DropCommonSuffixes('foo/foo-inl.h')
5582 'foo/foo'
5583 >>> _DropCommonSuffixes('foo/bar/foo.cc')
5584 'foo/bar/foo'
5585 >>> _DropCommonSuffixes('foo/foo_internal.h')
5586 'foo/foo'
5587 >>> _DropCommonSuffixes('foo/foo_unusualinternal.h')
5588 'foo/foo_unusualinternal'
5589
5590 Args:
5591 filename: The input filename.
5592
5593 Returns:
5594 The filename with the common suffix removed.
5595 """
5596 for suffix in itertools.chain(
5597 (
5598 f"{test_suffix.lstrip('_')}.{ext}"
5599 for test_suffix, ext in itertools.product(_test_suffixes, GetNonHeaderExtensions())
5600 ),
5601 (
5602 f"{suffix}.{ext}"
5603 for suffix, ext in itertools.product(["inl", "imp", "internal"], GetHeaderExtensions())
5604 ),
5605 ):
5606 if (
5607 filename.endswith(suffix)
5608 and len(filename) > len(suffix)
5609 and filename[-len(suffix) - 1] in ("-", "_")
5610 ):
5611 return filename[: -len(suffix) - 1]
5612 return os.path.splitext(filename)[0]
5613
5614
5615 def _ClassifyInclude(fileinfo, include, used_angle_brackets, include_order="default"):
5616 """Figures out what kind of header 'include' is.
5617
5618 Args:
5619 fileinfo: The current file cpplint is running over. A FileInfo instance.
5620 include: The path to a #included file.
5621 used_angle_brackets: True if the #include used <> rather than "".
5622 include_order: "default" or other value allowed in program arguments
5623
5624 Returns:
5625 One of the _XXX_HEADER constants.
5626
5627 For example:
5628 >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'stdio.h', True)
5629 _C_SYS_HEADER
5630 >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'string', True)
5631 _CPP_SYS_HEADER
5632 >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', True, "standardcfirst")
5633 _OTHER_SYS_HEADER
5634 >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', False)
5635 _LIKELY_MY_HEADER
5636 >>> _ClassifyInclude(FileInfo('foo/foo_unknown_extension.cc'),
5637 ... 'bar/foo_other_ext.h', False)
5638 _POSSIBLE_MY_HEADER
5639 >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/bar.h', False)
5640 _OTHER_HEADER
5641 """
5642 # This is a list of all standard c++ header files, except
5643 # those already checked for above.
5644 is_cpp_header = include in _CPP_HEADERS
5645
5646 # Mark include as C header if in list or in a known folder for standard-ish C headers.
5647 is_std_c_header = (include_order == "default") or (
5648 include in _C_HEADERS
5649 # additional linux glibc header folders
5650 or re.search(rf"(?:{'|'.join(C_STANDARD_HEADER_FOLDERS)})\/.*\.h", include)
5651 )
5652
5653 # Headers with C++ extensions shouldn't be considered C system headers
5654 include_ext = os.path.splitext(include)[1]
5655 is_system = used_angle_brackets and include_ext not in [".hh", ".hpp", ".hxx", ".h++"]
5656
5657 if is_system:
5658 if is_cpp_header:
5659 return _CPP_SYS_HEADER
5660 if is_std_c_header:
5661 return _C_SYS_HEADER
5662 return _OTHER_SYS_HEADER
5663
5664 # If the target file and the include we're checking share a
5665 # basename when we drop common extensions, and the include
5666 # lives in . , then it's likely to be owned by the target file.
5667 target_dir, target_base = os.path.split(_DropCommonSuffixes(fileinfo.RepositoryName()))
5668 include_dir, include_base = os.path.split(_DropCommonSuffixes(include))
5669 target_dir_pub = os.path.normpath(target_dir + "/../public")
5670 target_dir_pub = target_dir_pub.replace("\\", "/")
5671 if target_base == include_base and (include_dir in (target_dir, target_dir_pub)):
5672 return _LIKELY_MY_HEADER
5673
5674 # If the target and include share some initial basename
5675 # component, it's possible the target is implementing the
5676 # include, so it's allowed to be first, but we'll never
5677 # complain if it's not there.
5678 target_first_component = _RE_FIRST_COMPONENT.match(target_base)
5679 include_first_component = _RE_FIRST_COMPONENT.match(include_base)
5680 if (
5681 target_first_component
5682 and include_first_component
5683 and target_first_component.group(0) == include_first_component.group(0)
5684 ):
5685 return _POSSIBLE_MY_HEADER
5686
5687 return _OTHER_HEADER
5688
5689
5690 def CheckIncludeLine(filename, clean_lines, linenum, include_state, error):
5691 """Check rules that are applicable to #include lines.
5692
5693 Strings on #include lines are NOT removed from elided line, to make
5694 certain tasks easier. However, to prevent false positives, checks
5695 applicable to #include lines in CheckLanguage must be put here.
5696
5697 Args:
5698 filename: The name of the current file.
5699 clean_lines: A CleansedLines instance containing the file.
5700 linenum: The number of the line to check.
5701 include_state: An _IncludeState instance in which the headers are inserted.
5702 error: The function to call with any errors found.
5703 """
5704 fileinfo = FileInfo(filename)
5705 line = clean_lines.lines[linenum]
5706
5707 # "include" should use the new style "foo/bar.h" instead of just "bar.h"
5708 # Only do this check if the included header follows google naming
5709 # conventions. If not, assume that it's a 3rd party API that
5710 # requires special include conventions.
5711 #
5712 # We also make an exception for Lua headers, which follow google
5713 # naming convention but not the include convention.
5714 match = re.match(r'#include\s*"([^/]+\.(.*))"', line)
5715 if (
5716 match
5717 and IsHeaderExtension(match.group(2))
5718 and not _THIRD_PARTY_HEADERS_PATTERN.match(match.group(1))
5719 ):
5720 error(
5721 filename,
5722 linenum,
5723 "build/include_subdir",
5724 4,
5725 "Include the directory when naming header files",
5726 )
5727
5728 # we shouldn't include a file more than once. actually, there are a
5729 # handful of instances where doing so is okay, but in general it's
5730 # not.
5731 match = _RE_PATTERN_INCLUDE.search(line)
5732 if match:
5733 include = match.group(2)
5734 used_angle_brackets = match.group(1) == "<"
5735 duplicate_line = include_state.FindHeader(include)
5736 if duplicate_line >= 0:
5737 error(
5738 filename,
5739 linenum,
5740 "build/include",
5741 4,
5742 f'"{include}" already included at {filename}:{duplicate_line}',
5743 )
5744 return
5745
5746 for extension in GetNonHeaderExtensions():
5747 if include.endswith("." + extension) and os.path.dirname(
5748 fileinfo.RepositoryName()
5749 ) != os.path.dirname(include):
5750 error(
5751 filename,
5752 linenum,
5753 "build/include",
5754 4,
5755 "Do not include ." + extension + " files from other packages",
5756 )
5757 return
5758
5759 # We DO want to include a 3rd party looking header if it matches the
5760 # filename. Otherwise we get an erroneous error "...should include its
5761 # header" error later.
5762 third_src_header = False
5763 for ext in GetHeaderExtensions():
5764 basefilename = filename[0 : len(filename) - len(fileinfo.Extension())]
5765 headerfile = basefilename + "." + ext
5766 headername = FileInfo(headerfile).RepositoryName()
5767 if headername in include or include in headername:
5768 third_src_header = True
5769 break
5770
5771 if third_src_header or not _THIRD_PARTY_HEADERS_PATTERN.match(include):
5772 include_state.include_list[-1].append((include, linenum))
5773
5774 # We want to ensure that headers appear in the right order:
5775 # 1) for foo.cc, foo.h (preferred location)
5776 # 2) c system files
5777 # 3) cpp system files
5778 # 4) for foo.cc, foo.h (deprecated location)
5779 # 5) other google headers
5780 #
5781 # We classify each include statement as one of those 5 types
5782 # using a number of techniques. The include_state object keeps
5783 # track of the highest type seen, and complains if we see a
5784 # lower type after that.
5785 error_message = include_state.CheckNextIncludeOrder(
5786 _ClassifyInclude(fileinfo, include, used_angle_brackets, _include_order)
5787 )
5788 if error_message:
5789 error(
5790 filename,
5791 linenum,
5792 "build/include_order",
5793 4,
5794 f"{error_message}. Should be: {fileinfo.BaseName()}.h, c system,"
5795 " c++ system, other.",
5796 )
5797 canonical_include = include_state.CanonicalizeAlphabeticalOrder(include)
5798 if not include_state.IsInAlphabeticalOrder(clean_lines, linenum, canonical_include):
5799 error(
5800 filename,
5801 linenum,
5802 "build/include_alpha",
5803 4,
5804 f'Include "{include}" not in alphabetical order',
5805 )
5806 include_state.SetLastHeader(canonical_include)
5807
5808
5809 def _GetTextInside(text, start_pattern):
5810 r"""Retrieves all the text between matching open and close parentheses.
5811
5812 Given a string of lines and a regular expression string, retrieve all the text
5813 following the expression and between opening punctuation symbols like
5814 (, [, or {, and the matching close-punctuation symbol. This properly nested
5815 occurrences of the punctuation, so for the text like
5816 printf(a(), b(c()));
5817 a call to _GetTextInside(text, r'printf\(') will return 'a(), b(c())'.
5818 start_pattern must match string having an open punctuation symbol at the end.
5819
5820 Args:
5821 text: The lines to extract text. Its comments and strings must be elided.
5822 It can be single line and can span multiple lines.
5823 start_pattern: The regexp string indicating where to start extracting
5824 the text.
5825 Returns:
5826 The extracted text.
5827 None if either the opening string or ending punctuation could not be found.
5828 """
5829 # TODO(google): Audit cpplint.py to see what places could be profitably
5830 # rewritten to use _GetTextInside (and use inferior regexp matching today).
5831
5832 # Give opening punctuation to get the matching close-punctuation.
5833 matching_punctuation = {"(": ")", "{": "}", "[": "]"}
5834 closing_punctuation = set(dict.values(matching_punctuation))
5835
5836 # Find the position to start extracting text.
5837 match = re.search(start_pattern, text, re.MULTILINE)
5838 if not match: # start_pattern not found in text.
5839 return None
5840 start_position = match.end(0)
5841
5842 assert start_position > 0, "start_pattern must ends with an opening punctuation."
5843 assert text[start_position - 1] in matching_punctuation, (
5844 "start_pattern must ends with an opening punctuation."
5845 )
5846 # Stack of closing punctuation we expect to have in text after position.
5847 punctuation_stack = [matching_punctuation[text[start_position - 1]]]
5848 position = start_position
5849 while punctuation_stack and position < len(text):
5850 if text[position] == punctuation_stack[-1]:
5851 punctuation_stack.pop()
5852 elif text[position] in closing_punctuation:
5853 # A closing punctuation without matching opening punctuation.
5854 return None
5855 elif text[position] in matching_punctuation:
5856 punctuation_stack.append(matching_punctuation[text[position]])
5857 position += 1
5858 if punctuation_stack:
5859 # Opening punctuation left without matching close-punctuation.
5860 return None
5861 # punctuation match.
5862 return text[start_position : position - 1]
5863
5864
5865 # Patterns for matching call-by-reference parameters.
5866 #
5867 # Supports nested templates up to 2 levels deep using this messy pattern:
5868 # < (?: < (?: < [^<>]*
5869 # >
5870 # | [^<>] )*
5871 # >
5872 # | [^<>] )*
5873 # >
5874 _RE_PATTERN_IDENT = r"[_a-zA-Z]\w*" # =~ [[:alpha:]][[:alnum:]]*
5875 _RE_PATTERN_TYPE = (
5876 r"(?:const\s+)?(?:typename\s+|class\s+|struct\s+|union\s+|enum\s+)?"
5877 r"(?:\w|"
5878 r"\s*<(?:<(?:<[^<>]*>|[^<>])*>|[^<>])*>|"
5879 r"::)+"
5880 )
5881 # A call-by-reference parameter ends with '& identifier'.
5882 _RE_PATTERN_REF_PARAM = re.compile(
5883 r"(" + _RE_PATTERN_TYPE + r"(?:\s*(?:\bconst\b|[*]))*\s*"
5884 r"&\s*" + _RE_PATTERN_IDENT + r")\s*(?:=[^,()]+)?[,)]"
5885 )
5886 # A call-by-const-reference parameter either ends with 'const& identifier'
5887 # or looks like 'const type& identifier' when 'type' is atomic.
5888 _RE_PATTERN_CONST_REF_PARAM = (
5889 r"(?:.*\s*\bconst\s*&\s*"
5890 + _RE_PATTERN_IDENT
5891 + r"|const\s+"
5892 + _RE_PATTERN_TYPE
5893 + r"\s*&\s*"
5894 + _RE_PATTERN_IDENT
5895 + r")"
5896 )
5897 # Stream types.
5898 _RE_PATTERN_REF_STREAM_PARAM = r"(?:.*stream\s*&\s*" + _RE_PATTERN_IDENT + r")"
5899
5900
5901 def CheckLanguage(
5902 filename, clean_lines, linenum, file_extension, include_state, nesting_state, error
5903 ):
5904 """Checks rules from the 'C++ language rules' section of cppguide.html.
5905
5906 Some of these rules are hard to test (function overloading, using
5907 uint32_t inappropriately), but we do the best we can.
5908
5909 Args:
5910 filename: The name of the current file.
5911 clean_lines: A CleansedLines instance containing the file.
5912 linenum: The number of the line to check.
5913 file_extension: The extension (without the dot) of the filename.
5914 include_state: An _IncludeState instance in which the headers are inserted.
5915 nesting_state: A NestingState instance which maintains information about
5916 the current stack of nested blocks being parsed.
5917 error: The function to call with any errors found.
5918 """
5919 # If the line is empty or consists of entirely a comment, no need to
5920 # check it.
5921 line = clean_lines.elided[linenum]
5922 if not line:
5923 return
5924
5925 match = _RE_PATTERN_INCLUDE.search(line)
5926 if match:
5927 CheckIncludeLine(filename, clean_lines, linenum, include_state, error)
5928 return
5929
5930 # Reset include state across preprocessor directives. This is meant
5931 # to silence warnings for conditional includes.
5932 match = re.match(r"^\s*#\s*(if|ifdef|ifndef|elif|else|endif)\b", line)
5933 if match:
5934 include_state.ResetSection(match.group(1))
5935
5936 # Perform other checks now that we are sure that this is not an include line
5937 CheckCasts(filename, clean_lines, linenum, error)
5938 CheckGlobalStatic(filename, clean_lines, linenum, error)
5939 CheckPrintf(filename, clean_lines, linenum, error)
5940
5941 if IsHeaderExtension(file_extension):
5942 # TODO(google): check that 1-arg constructors are explicit.
5943 # How to tell it's a constructor?
5944 # (handled in CheckForNonStandardConstructs for now)
5945 # TODO(google): check that classes declare or disable copy/assign
5946 # (level 1 error)
5947 pass
5948
5949 # Check if people are using the verboten C basic types. The only exception
5950 # we regularly allow is "unsigned short port" for port.
5951 if re.search(r"\bshort port\b", line):
5952 if not re.search(r"\bunsigned short port\b", line):
5953 error(
5954 filename, linenum, "runtime/int", 4, 'Use "unsigned short" for ports, not "short"'
5955 )
5956 else:
5957 match = re.search(r"\b(short|long(?! +double)|long long)\b", line)
5958 if match:
5959 error(
5960 filename,
5961 linenum,
5962 "runtime/int",
5963 4,
5964 f"Use int16_t/int64_t/etc, rather than the C type {match.group(1)}",
5965 )
5966
5967 # Check if some verboten operator overloading is going on
5968 # TODO(google): catch out-of-line unary operator&:
5969 # class X {};
5970 # int operator&(const X& x) { return 42; } // unary operator&
5971 # The trick is it's hard to tell apart from binary operator&:
5972 # class Y { int operator&(const Y& x) { return 23; } }; // binary operator&
5973 if re.search(r"\boperator\s*&\s*\(\s*\)", line):
5974 error(
5975 filename,
5976 linenum,
5977 "runtime/operator",
5978 4,
5979 "Unary operator& is dangerous. Do not use it.",
5980 )
5981
5982 # Check for suspicious usage of "if" like
5983 # } if (a == b) {
5984 if re.search(r"\}\s*if\s*\(", line):
5985 error(
5986 filename,
5987 linenum,
5988 "readability/braces",
5989 4,
5990 'Did you mean "else if"? If not, start a new line for "if".',
5991 )
5992
5993 # Check for potential format string bugs like printf(foo).
5994 # We constrain the pattern not to pick things like DocidForPrintf(foo).
5995 # Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str())
5996 # TODO(google): Catch the following case. Need to change the calling
5997 # convention of the whole function to process multiple line to handle it.
5998 # printf(
5999 # boy_this_is_a_really_long_variable_that_cannot_fit_on_the_prev_line);
6000 if printf_args := _GetTextInside(line, r"(?i)\b(string)?printf\s*\("):
6001 match = re.match(r"([\w.\->()]+)$", printf_args)
6002 if match and match.group(1) != "__VA_ARGS__":
6003 function_name = re.search(r"\b((?:string)?printf)\s*\(", line, re.IGNORECASE).group(1)
6004 error(
6005 filename,
6006 linenum,
6007 "runtime/printf",
6008 4,
6009 f'Potential format string bug. Do {function_name}("%s", {match.group(1)}) instead.',
6010 )
6011
6012 # Check for potential memset bugs like memset(buf, sizeof(buf), 0).
6013 match = re.search(r"memset\s*\(([^,]*),\s*([^,]*),\s*0\s*\)", line)
6014 if match and not re.match(r"^''|-?[0-9]+|0x[0-9A-Fa-f]$", match.group(2)):
6015 error(
6016 filename,
6017 linenum,
6018 "runtime/memset",
6019 4,
6020 f'Did you mean "memset({match.group(1)}, 0, {match.group(2)})"?',
6021 )
6022
6023 if re.search(r"\busing namespace\b", line):
6024 if re.search(r"\bliterals\b", line):
6025 error(
6026 filename,
6027 linenum,
6028 "build/namespaces_literals",
6029 5,
6030 "Do not use namespace using-directives. Use using-declarations instead.",
6031 )
6032 else:
6033 error(
6034 filename,
6035 linenum,
6036 "build/namespaces",
6037 5,
6038 "Do not use namespace using-directives. Use using-declarations instead.",
6039 )
6040
6041 # Detect variable-length arrays.
6042 match = re.match(r"\s*(.+::)?(\w+) [a-z]\w*\[(.+)];", line)
6043 if (
6044 match
6045 and match.group(2) != "return"
6046 and match.group(2) != "delete"
6047 and match.group(3).find("]") == -1
6048 ):
6049 # Split the size using space and arithmetic operators as delimiters.
6050 # If any of the resulting tokens are not compile time constants then
6051 # report the error.
6052 tokens = re.split(r"\s|\+|\-|\*|\/|<<|>>]", match.group(3))
6053 is_const = True
6054 skip_next = False
6055 for tok in tokens:
6056 if skip_next:
6057 skip_next = False
6058 continue
6059
6060 if re.search(r"sizeof\(.+\)", tok):
6061 continue
6062 if re.search(r"arraysize\(\w+\)", tok):
6063 continue
6064
6065 tok = tok.lstrip("(")
6066 tok = tok.rstrip(")")
6067 if not tok:
6068 continue
6069 if re.match(r"\d+", tok):
6070 continue
6071 if re.match(r"0[xX][0-9a-fA-F]+", tok):
6072 continue
6073 if re.match(r"k[A-Z0-9]\w*", tok):
6074 continue
6075 if re.match(r"(.+::)?k[A-Z0-9]\w*", tok):
6076 continue
6077 if re.match(r"(.+::)?[A-Z][A-Z0-9_]*", tok):
6078 continue
6079 # A catch all for tricky sizeof cases, including 'sizeof expression',
6080 # 'sizeof(*type)', 'sizeof(const type)', 'sizeof(struct StructName)'
6081 # requires skipping the next token because we split on ' ' and '*'.
6082 if tok.startswith("sizeof"):
6083 skip_next = True
6084 continue
6085 is_const = False
6086 break
6087 if not is_const:
6088 error(
6089 filename,
6090 linenum,
6091 "runtime/arrays",
6092 1,
6093 "Do not use variable-length arrays. Use an appropriately named "
6094 "('k' followed by CamelCase) compile-time constant for the size.",
6095 )
6096
6097 # Check for use of unnamed namespaces in header files. Registration
6098 # macros are typically OK, so we allow use of "namespace {" on lines
6099 # that end with backslashes.
6100 if (
6101 IsHeaderExtension(file_extension)
6102 and re.search(r"\bnamespace\s*{", line)
6103 and line[-1] != "\\"
6104 ):
6105 error(
6106 filename,
6107 linenum,
6108 "build/namespaces_headers",
6109 4,
6110 "Do not use unnamed namespaces in header files. See "
6111 "https://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces"
6112 " for more information.",
6113 )
6114
6115
6116 def CheckGlobalStatic(filename, clean_lines, linenum, error):
6117 """Check for unsafe global or static objects.
6118
6119 Args:
6120 filename: The name of the current file.
6121 clean_lines: A CleansedLines instance containing the file.
6122 linenum: The number of the line to check.
6123 error: The function to call with any errors found.
6124 """
6125 line = clean_lines.elided[linenum]
6126
6127 # Match two lines at a time to support multiline declarations
6128 if linenum + 1 < clean_lines.NumLines() and not re.search(r"[;({]", line):
6129 line += clean_lines.elided[linenum + 1].strip()
6130
6131 # Check for people declaring static/global STL strings at the top level.
6132 # This is dangerous because the C++ language does not guarantee that
6133 # globals with constructors are initialized before the first access, and
6134 # also because globals can be destroyed when some threads are still running.
6135 # TODO(google): Generalize this to also find static unique_ptr instances.
6136 # TODO(google): File bugs for clang-tidy to find these.
6137 match = re.match(
6138 r"((?:|static +)(?:|const +))(?::*std::)?string( +const)? +"
6139 r"([a-zA-Z0-9_:]+)\b(.*)",
6140 line,
6141 )
6142
6143 # Remove false positives:
6144 # - String pointers (as opposed to values).
6145 # string *pointer
6146 # const string *pointer
6147 # string const *pointer
6148 # string *const pointer
6149 #
6150 # - Functions and template specializations.
6151 # string Function<Type>(...
6152 # string Class<Type>::Method(...
6153 #
6154 # - Operators. These are matched separately because operator names
6155 # cross non-word boundaries, and trying to match both operators
6156 # and functions at the same time would decrease accuracy of
6157 # matching identifiers.
6158 # string Class::operator*()
6159 if (
6160 match
6161 and not re.search(r"\bstring\b(\s+const)?\s*[\*\&]\s*(const\s+)?\w", line)
6162 and not re.search(r"\boperator\W", line)
6163 and not re.match(r'\s*(<.*>)?(::[a-zA-Z0-9_]+)*\s*\(([^"]|$)', match.group(4))
6164 ):
6165 if re.search(r"\bconst\b", line):
6166 error(
6167 filename,
6168 linenum,
6169 "runtime/string",
6170 4,
6171 "For a static/global string constant, use a C style string instead:"
6172 f' "{match.group(1)}char{match.group(2) or ""} {match.group(3)}[]".',
6173 )
6174 else:
6175 error(
6176 filename,
6177 linenum,
6178 "runtime/string",
6179 4,
6180 "Static/global string variables are not permitted.",
6181 )
6182
6183 if re.search(r"\b([A-Za-z0-9_]*_)\(\1\)", line) or re.search(
6184 r"\b([A-Za-z0-9_]*_)\(CHECK_NOTNULL\(\1\)\)", line
6185 ):
6186 error(
6187 filename,
6188 linenum,
6189 "runtime/init",
6190 4,
6191 "You seem to be initializing a member variable with itself.",
6192 )
6193
6194
6195 def CheckPrintf(filename, clean_lines, linenum, error):
6196 """Check for printf related issues.
6197
6198 Args:
6199 filename: The name of the current file.
6200 clean_lines: A CleansedLines instance containing the file.
6201 linenum: The number of the line to check.
6202 error: The function to call with any errors found.
6203 """
6204 line = clean_lines.elided[linenum]
6205
6206 # When snprintf is used, the second argument shouldn't be a literal.
6207 match = re.search(r"snprintf\s*\(([^,]*),\s*([0-9]*)\s*,", line)
6208 if match and match.group(2) != "0":
6209 # If 2nd arg is zero, snprintf is used to calculate size.
6210 error(
6211 filename,
6212 linenum,
6213 "runtime/printf",
6214 3,
6215 "If you can, use"
6216 f" sizeof({match.group(1)}) instead of {match.group(2)}"
6217 " as the 2nd arg to snprintf.",
6218 )
6219
6220 # Check if some verboten C functions are being used.
6221 if re.search(r"\bsprintf\s*\(", line):
6222 error(filename, linenum, "runtime/printf", 5, "Never use sprintf. Use snprintf instead.")
6223 match = re.search(r"\b(strcpy|strcat)\s*\(", line)
6224 if match:
6225 error(
6226 filename,
6227 linenum,
6228 "runtime/printf",
6229 4,
6230 f"Almost always, snprintf is better than {match.group(1)}",
6231 )
6232
6233
6234 def IsDerivedFunction(clean_lines, linenum):
6235 """Check if current line contains an inherited function.
6236
6237 Args:
6238 clean_lines: A CleansedLines instance containing the file.
6239 linenum: The number of the line to check.
6240 Returns:
6241 True if current line contains a function with "override"
6242 virt-specifier.
6243 """
6244 # Scan back a few lines for start of current function
6245 for i in range(linenum, max(-1, linenum - 10), -1):
6246 match = re.match(r"^([^()]*\w+)\(", clean_lines.elided[i])
6247 if match:
6248 # Look for "override" after the matching closing parenthesis
6249 line, _, closing_paren = CloseExpression(clean_lines, i, len(match.group(1)))
6250 return closing_paren >= 0 and re.search(r"\boverride\b", line[closing_paren:])
6251 return False
6252
6253
6254 def IsOutOfLineMethodDefinition(clean_lines, linenum):
6255 """Check if current line contains an out-of-line method definition.
6256
6257 Args:
6258 clean_lines: A CleansedLines instance containing the file.
6259 linenum: The number of the line to check.
6260 Returns:
6261 True if current line contains an out-of-line method definition.
6262 """
6263 # Scan back a few lines for start of current function
6264 for i in range(linenum, max(-1, linenum - 10), -1):
6265 if re.match(r"^([^()]*\w+)\(", clean_lines.elided[i]):
6266 return re.match(r"^[^()]*\w+::\w+\(", clean_lines.elided[i]) is not None
6267 return False
6268
6269
6270 def IsInitializerList(clean_lines, linenum):
6271 """Check if current line is inside constructor initializer list.
6272
6273 Args:
6274 clean_lines: A CleansedLines instance containing the file.
6275 linenum: The number of the line to check.
6276 Returns:
6277 True if current line appears to be inside constructor initializer
6278 list, False otherwise.
6279 """
6280 for i in range(linenum, 1, -1):
6281 line = clean_lines.elided[i]
6282 if i == linenum:
6283 remove_function_body = re.match(r"^(.*)\{\s*$", line)
6284 if remove_function_body:
6285 line = remove_function_body.group(1)
6286
6287 if re.search(r"\s:\s*\w+[({]", line):
6288 # A lone colon tend to indicate the start of a constructor
6289 # initializer list. It could also be a ternary operator, which
6290 # also tend to appear in constructor initializer lists as
6291 # opposed to parameter lists.
6292 return True
6293 if re.search(r"\}\s*,\s*$", line):
6294 # A closing brace followed by a comma is probably the end of a
6295 # brace-initialized member in constructor initializer list.
6296 return True
6297 if re.search(r"[{};]\s*$", line):
6298 # Found one of the following:
6299 # - A closing brace or semicolon, probably the end of the previous
6300 # function.
6301 # - An opening brace, probably the start of current class or namespace.
6302 #
6303 # Current line is probably not inside an initializer list since
6304 # we saw one of those things without seeing the starting colon.
6305 return False
6306
6307 # Got to the beginning of the file without seeing the start of
6308 # constructor initializer list.
6309 return False
6310
6311
6312 def CheckForNonConstReference(filename, clean_lines, linenum, nesting_state, error):
6313 """Check for non-const references.
6314
6315 Separate from CheckLanguage since it scans backwards from current
6316 line, instead of scanning forward.
6317
6318 Args:
6319 filename: The name of the current file.
6320 clean_lines: A CleansedLines instance containing the file.
6321 linenum: The number of the line to check.
6322 nesting_state: A NestingState instance which maintains information about
6323 the current stack of nested blocks being parsed.
6324 error: The function to call with any errors found.
6325 """
6326 # Do nothing if there is no '&' on current line.
6327 line = clean_lines.elided[linenum]
6328 if "&" not in line:
6329 return
6330
6331 # If a function is inherited, current function doesn't have much of
6332 # a choice, so any non-const references should not be blamed on
6333 # derived function.
6334 if IsDerivedFunction(clean_lines, linenum):
6335 return
6336
6337 # Don't warn on out-of-line method definitions, as we would warn on the
6338 # in-line declaration, if it isn't marked with 'override'.
6339 if IsOutOfLineMethodDefinition(clean_lines, linenum):
6340 return
6341
6342 # Long type names may be broken across multiple lines, usually in one
6343 # of these forms:
6344 # LongType
6345 # ::LongTypeContinued &identifier
6346 # LongType::
6347 # LongTypeContinued &identifier
6348 # LongType<
6349 # ...>::LongTypeContinued &identifier
6350 #
6351 # If we detected a type split across two lines, join the previous
6352 # line to current line so that we can match const references
6353 # accordingly.
6354 #
6355 # Note that this only scans back one line, since scanning back
6356 # arbitrary number of lines would be expensive. If you have a type
6357 # that spans more than 2 lines, please use a typedef.
6358 if linenum > 1:
6359 previous = None
6360 if re.match(r"\s*::(?:[\w<>]|::)+\s*&\s*\S", line):
6361 # previous_line\n + ::current_line
6362 previous = re.search(
6363 r"\b((?:const\s*)?(?:[\w<>]|::)+[\w<>])\s*$", clean_lines.elided[linenum - 1]
6364 )
6365 elif re.match(r"\s*[a-zA-Z_]([\w<>]|::)+\s*&\s*\S", line):
6366 # previous_line::\n + current_line
6367 previous = re.search(
6368 r"\b((?:const\s*)?(?:[\w<>]|::)+::)\s*$", clean_lines.elided[linenum - 1]
6369 )
6370 if previous:
6371 line = previous.group(1) + line.lstrip()
6372 else:
6373 # Check for templated parameter that is split across multiple lines
6374 endpos = line.rfind(">")
6375 if endpos > -1:
6376 (_, startline, startpos) = ReverseCloseExpression(clean_lines, linenum, endpos)
6377 if startpos > -1 and startline < linenum:
6378 # Found the matching < on an earlier line, collect all
6379 # pieces up to current line.
6380 line = ""
6381 for i in range(startline, linenum + 1):
6382 line += clean_lines.elided[i].strip()
6383
6384 # Check for non-const references in function parameters. A single '&' may
6385 # found in the following places:
6386 # inside expression: binary & for bitwise AND
6387 # inside expression: unary & for taking the address of something
6388 # inside declarators: reference parameter
6389 # We will exclude the first two cases by checking that we are not inside a
6390 # function body, including one that was just introduced by a trailing '{'.
6391 # TODO(google): Doesn't account for 'catch(Exception& e)' [rare].
6392 if nesting_state.previous_stack_top and not (
6393 isinstance(nesting_state.previous_stack_top, (_ClassInfo, _NamespaceInfo))
6394 ):
6395 # Not at toplevel, not within a class, and not within a namespace
6396 return
6397
6398 # Avoid initializer lists. We only need to scan back from the
6399 # current line for something that starts with ':'.
6400 #
6401 # We don't need to check the current line, since the '&' would
6402 # appear inside the second set of parentheses on the current line as
6403 # opposed to the first set.
6404 if linenum > 0:
6405 for i in range(linenum - 1, max(0, linenum - 10), -1):
6406 previous_line = clean_lines.elided[i]
6407 if not re.search(r"[),]\s*$", previous_line):
6408 break
6409 if re.match(r"^\s*:\s+\S", previous_line):
6410 return
6411
6412 # Avoid preprocessors
6413 if re.search(r"\\\s*$", line):
6414 return
6415
6416 # Avoid constructor initializer lists
6417 if IsInitializerList(clean_lines, linenum):
6418 return
6419
6420 # We allow non-const references in a few standard places, like functions
6421 # called "swap()" or iostream operators like "<<" or ">>". Do not check
6422 # those function parameters.
6423 #
6424 # We also accept & in static_assert, which looks like a function but
6425 # it's actually a declaration expression.
6426 allowed_functions = (
6427 r"(?:[sS]wap(?:<\w:+>)?|"
6428 r"operator\s*[<>][<>]|"
6429 r"static_assert|COMPILE_ASSERT"
6430 r")\s*\("
6431 )
6432 if re.search(allowed_functions, line):
6433 return
6434 if not re.search(r"\S+\([^)]*$", line):
6435 # Don't see an allowed function on this line. Actually we
6436 # didn't see any function name on this line, so this is likely a
6437 # multi-line parameter list. Try a bit harder to catch this case.
6438 for i in range(2):
6439 if linenum > i and re.search(allowed_functions, clean_lines.elided[linenum - i - 1]):
6440 return
6441
6442 decls = re.sub(r"{[^}]*}", " ", line) # exclude function body
6443 for parameter in re.findall(_RE_PATTERN_REF_PARAM, decls):
6444 if not re.match(_RE_PATTERN_CONST_REF_PARAM, parameter) and not re.match(
6445 _RE_PATTERN_REF_STREAM_PARAM, parameter
6446 ):
6447 error(
6448 filename,
6449 linenum,
6450 "runtime/references",
6451 2,
6452 "Is this a non-const reference? "
6453 "If so, make const or use a pointer: " + re.sub(" *<", "<", parameter),
6454 )
6455
6456
6457 def CheckCasts(filename, clean_lines, linenum, error):
6458 """Various cast related checks.
6459
6460 Args:
6461 filename: The name of the current file.
6462 clean_lines: A CleansedLines instance containing the file.
6463 linenum: The number of the line to check.
6464 error: The function to call with any errors found.
6465 """
6466 line = clean_lines.elided[linenum]
6467
6468 # Check to see if they're using an conversion function cast.
6469 # I just try to capture the most common basic types, though there are more.
6470 # Parameterless conversion functions, such as bool(), are allowed as they are
6471 # probably a member operator declaration or default constructor.
6472 match = re.search(
6473 r"(\bnew\s+(?:const\s+)?|\S<\s*(?:const\s+)?)?\b"
6474 r"(int|float|double|bool|char|int16_t|uint16_t|int32_t|uint32_t|int64_t|uint64_t)"
6475 r"(\([^)].*)",
6476 line,
6477 )
6478 expecting_function = ExpectingFunctionArgs(clean_lines, linenum)
6479 if match and not expecting_function:
6480 matched_type = match.group(2)
6481
6482 # matched_new_or_template is used to silence two false positives:
6483 # - New operators
6484 # - Template arguments with function types
6485 #
6486 # For template arguments, we match on types immediately following
6487 # an opening bracket without any spaces. This is a fast way to
6488 # silence the common case where the function type is the first
6489 # template argument. False negative with less-than comparison is
6490 # avoided because those operators are usually followed by a space.
6491 #
6492 # function<double(double)> // bracket + no space = false positive
6493 # value < double(42) // bracket + space = true positive
6494 matched_new_or_template = match.group(1)
6495
6496 # Avoid arrays by looking for brackets that come after the closing
6497 # parenthesis.
6498 if re.match(r"\([^()]+\)\s*\[", match.group(3)):
6499 return
6500
6501 # Other things to ignore:
6502 # - Function pointers
6503 # - Casts to pointer types
6504 # - Placement new
6505 # - Alias declarations
6506 matched_funcptr = match.group(3)
6507 if (
6508 matched_new_or_template is None
6509 and not (
6510 matched_funcptr
6511 and (
6512 re.match(r"\((?:[^() ]+::\s*\*\s*)?[^() ]+\)\s*\(", matched_funcptr)
6513 or matched_funcptr.startswith("(*)")
6514 )
6515 )
6516 and not re.match(r"\s*using\s+\S+\s*=\s*" + matched_type, line)
6517 and not re.search(r"new\(\S+\)\s*" + matched_type, line)
6518 ):
6519 error(
6520 filename,
6521 linenum,
6522 "readability/casting",
6523 4,
6524 f"Using deprecated casting style. Use static_cast<{matched_type}>(...) instead",
6525 )
6526
6527 if not expecting_function:
6528 CheckCStyleCast(
6529 filename,
6530 clean_lines,
6531 linenum,
6532 "static_cast",
6533 r"\((int|float|double|bool|char|u?int(16|32|64)_t|size_t)\)",
6534 error,
6535 )
6536
6537 # This doesn't catch all cases. Consider (const char * const)"hello".
6538 #
6539 # (char *) "foo" should always be a const_cast (reinterpret_cast won't
6540 # compile).
6541 if CheckCStyleCast(
6542 filename, clean_lines, linenum, "const_cast", r'\((char\s?\*+\s?)\)\s*"', error
6543 ):
6544 pass
6545 else:
6546 # Check pointer casts for other than string constants
6547 CheckCStyleCast(
6548 filename, clean_lines, linenum, "reinterpret_cast", r"\((\w+\s?\*+\s?)\)", error
6549 )
6550
6551 # In addition, we look for people taking the address of a cast. This
6552 # is dangerous -- casts can assign to temporaries, so the pointer doesn't
6553 # point where you think.
6554 #
6555 # Some non-identifier character is required before the '&' for the
6556 # expression to be recognized as a cast. These are casts:
6557 # expression = &static_cast<int*>(temporary());
6558 # function(&(int*)(temporary()));
6559 #
6560 # This is not a cast:
6561 # reference_type&(int* function_param);
6562 match = re.search(
6563 r"(?:[^\w]&\(([^)*][^)]*)\)[\w(])|"
6564 r"(?:[^\w]&(static|dynamic|down|reinterpret)_cast\b)",
6565 line,
6566 )
6567 if match:
6568 # Try a better error message when the & is bound to something
6569 # dereferenced by the casted pointer, as opposed to the casted
6570 # pointer itself.
6571 parenthesis_error = False
6572 match = re.match(r"^(.*&(?:static|dynamic|down|reinterpret)_cast\b)<", line)
6573 if match:
6574 _, y1, x1 = CloseExpression(clean_lines, linenum, len(match.group(1)))
6575 if x1 >= 0 and clean_lines.elided[y1][x1] == "(":
6576 _, y2, x2 = CloseExpression(clean_lines, y1, x1)
6577 if x2 >= 0:
6578 extended_line = clean_lines.elided[y2][x2:]
6579 if y2 < clean_lines.NumLines() - 1:
6580 extended_line += clean_lines.elided[y2 + 1]
6581 if re.match(r"\s*(?:->|\[)", extended_line):
6582 parenthesis_error = True
6583
6584 if parenthesis_error:
6585 error(
6586 filename,
6587 linenum,
6588 "readability/casting",
6589 4,
6590 (
6591 "Are you taking an address of something dereferenced "
6592 "from a cast? Wrapping the dereferenced expression in "
6593 "parentheses will make the binding more obvious"
6594 ),
6595 )
6596 else:
6597 error(
6598 filename,
6599 linenum,
6600 "runtime/casting",
6601 4,
6602 (
6603 "Are you taking an address of a cast? "
6604 "This is dangerous: could be a temp var. "
6605 "Take the address before doing the cast, rather than after"
6606 ),
6607 )
6608
6609
6610 def CheckCStyleCast(filename, clean_lines, linenum, cast_type, pattern, error):
6611 """Checks for a C-style cast by looking for the pattern.
6612
6613 Args:
6614 filename: The name of the current file.
6615 clean_lines: A CleansedLines instance containing the file.
6616 linenum: The number of the line to check.
6617 cast_type: The string for the C++ cast to recommend. This is either
6618 reinterpret_cast, static_cast, or const_cast, depending.
6619 pattern: The regular expression used to find C-style casts.
6620 error: The function to call with any errors found.
6621
6622 Returns:
6623 True if an error was emitted.
6624 False otherwise.
6625 """
6626 line = clean_lines.elided[linenum]
6627 match = re.search(pattern, line)
6628 if not match:
6629 return False
6630
6631 # Exclude lines with keywords that tend to look like casts
6632 context = line[0 : match.start(1) - 1]
6633 if re.match(r".*\b(?:sizeof|alignof|alignas|[_A-Z][_A-Z0-9]*)\s*$", context):
6634 return False
6635
6636 # Try expanding current context to see if we one level of
6637 # parentheses inside a macro.
6638 if linenum > 0:
6639 for i in range(linenum - 1, max(0, linenum - 5), -1):
6640 context = clean_lines.elided[i] + context
6641 if re.match(r".*\b[_A-Z][_A-Z0-9]*\s*\((?:\([^()]*\)|[^()])*$", context):
6642 return False
6643
6644 # operator++(int) and operator--(int)
6645 if context.endswith((" operator++", " operator--", "::operator++", "::operator--")):
6646 return False
6647
6648 # A single unnamed argument for a function tends to look like old style cast.
6649 # If we see those, don't issue warnings for deprecated casts.
6650 remainder = line[match.end(0) :]
6651 if re.match(r"^\s*(?:;|const\b|throw\b|final\b|override\b|[=>{),]|->)", remainder):
6652 return False
6653
6654 # At this point, all that should be left is actual casts.
6655 error(
6656 filename,
6657 linenum,
6658 "readability/casting",
6659 4,
6660 f"Using C-style cast. Use {cast_type}<{match.group(1)}>(...) instead",
6661 )
6662
6663 return True
6664
6665
6666 def ExpectingFunctionArgs(clean_lines, linenum):
6667 """Checks whether where function type arguments are expected.
6668
6669 Args:
6670 clean_lines: A CleansedLines instance containing the file.
6671 linenum: The number of the line to check.
6672
6673 Returns:
6674 True if the line at 'linenum' is inside something that expects arguments
6675 of function types.
6676 """
6677 line = clean_lines.elided[linenum]
6678 return re.match(r"^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(", line) or (
6679 linenum >= 2
6680 and (
6681 re.match(
6682 r"^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\((?:\S+,)?\s*$",
6683 clean_lines.elided[linenum - 1],
6684 )
6685 or re.match(
6686 r"^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\(\s*$", clean_lines.elided[linenum - 2]
6687 )
6688 or re.search(r"\bstd::m?function\s*\<\s*$", clean_lines.elided[linenum - 1])
6689 )
6690 )
6691
6692
6693 _HEADERS_CONTAINING_TEMPLATES: tuple[tuple[str, tuple[str, ...]], ...] = (
6694 ("<deque>", ("deque",)),
6695 (
6696 "<functional>",
6697 (
6698 "unary_function",
6699 "binary_function",
6700 "plus",
6701 "minus",
6702 "multiplies",
6703 "divides",
6704 "modulus",
6705 "negate",
6706 "equal_to",
6707 "not_equal_to",
6708 "greater",
6709 "less",
6710 "greater_equal",
6711 "less_equal",
6712 "logical_and",
6713 "logical_or",
6714 "logical_not",
6715 "unary_negate",
6716 "not1",
6717 "binary_negate",
6718 "not2",
6719 "bind1st",
6720 "bind2nd",
6721 "pointer_to_unary_function",
6722 "pointer_to_binary_function",
6723 "ptr_fun",
6724 "mem_fun_t",
6725 "mem_fun",
6726 "mem_fun1_t",
6727 "mem_fun1_ref_t",
6728 "mem_fun_ref_t",
6729 "const_mem_fun_t",
6730 "const_mem_fun1_t",
6731 "const_mem_fun_ref_t",
6732 "const_mem_fun1_ref_t",
6733 "mem_fun_ref",
6734 ),
6735 ),
6736 ("<limits>", ("numeric_limits",)),
6737 ("<list>", ("list",)),
6738 ("<map>", ("multimap",)),
6739 (
6740 "<memory>",
6741 ("allocator", "make_shared", "make_unique", "shared_ptr", "unique_ptr", "weak_ptr"),
6742 ),
6743 (
6744 "<queue>",
6745 (
6746 "queue",
6747 "priority_queue",
6748 ),
6749 ),
6750 (
6751 "<set>",
6752 (
6753 "set",
6754 "multiset",
6755 ),
6756 ),
6757 ("<stack>", ("stack",)),
6758 (
6759 "<string>",
6760 (
6761 "char_traits",
6762 "basic_string",
6763 ),
6764 ),
6765 ("<tuple>", ("tuple",)),
6766 ("<unordered_map>", ("unordered_map", "unordered_multimap")),
6767 ("<unordered_set>", ("unordered_set", "unordered_multiset")),
6768 ("<utility>", ("pair",)),
6769 ("<vector>", ("vector",)),
6770 # gcc extensions.
6771 # Note: std::hash is their hash, ::hash is our hash
6772 (
6773 "<hash_map>",
6774 (
6775 "hash_map",
6776 "hash_multimap",
6777 ),
6778 ),
6779 (
6780 "<hash_set>",
6781 (
6782 "hash_set",
6783 "hash_multiset",
6784 ),
6785 ),
6786 ("<slist>", ("slist",)),
6787 )
6788
6789 _HEADERS_MAYBE_TEMPLATES: tuple[tuple[str, tuple[str, ...]], ...] = (
6790 (
6791 "<algorithm>",
6792 (
6793 "copy",
6794 "max",
6795 "min",
6796 "min_element",
6797 "sort",
6798 "transform",
6799 ),
6800 ),
6801 ("<utility>", ("forward", "make_pair", "move", "swap")),
6802 )
6803
6804 # Non templated types or global objects
6805 _HEADERS_TYPES_OR_OBJS: tuple[tuple[str, tuple[str, ...]], ...] = (
6806 # String and others are special -- it is a non-templatized type in STL.
6807 ("<string>", ("string",)),
6808 ("<iostream>", ("cin", "cout", "cerr", "clog", "wcin", "wcout", "wcerr", "wclog")),
6809 ("<cstdio>", ("FILE", "fpos_t")),
6810 )
6811
6812 # Non templated functions
6813 _HEADERS_FUNCTIONS: tuple[tuple[str, tuple[str, ...]], ...] = (
6814 (
6815 "<cstdio>",
6816 (
6817 "fopen",
6818 "freopen",
6819 "fclose",
6820 "fflush",
6821 "setbuf",
6822 "setvbuf",
6823 "fread",
6824 "fwrite",
6825 "fgetc",
6826 "getc",
6827 "fgets",
6828 "fputc",
6829 "putc",
6830 "fputs",
6831 "getchar",
6832 "gets",
6833 "putchar",
6834 "puts",
6835 "ungetc",
6836 "scanf",
6837 "fscanf",
6838 "sscanf",
6839 "vscanf",
6840 "vfscanf",
6841 "vsscanf",
6842 "printf",
6843 "fprintf",
6844 "sprintf",
6845 "snprintf",
6846 "vprintf",
6847 "vfprintf",
6848 "vsprintf",
6849 "vsnprintf",
6850 "ftell",
6851 "fgetpos",
6852 "fseek",
6853 "fsetpos",
6854 "clearerr",
6855 "feof",
6856 "ferror",
6857 "perror",
6858 "tmpfile",
6859 "tmpnam",
6860 ),
6861 ),
6862 )
6863
6864 _re_pattern_headers_maybe_templates: list[tuple[re.Pattern, str, str]] = []
6865 for _header, _templates in _HEADERS_MAYBE_TEMPLATES:
6866 # Match max<type>(..., ...), max(..., ...), but not foo->max, foo.max or
6867 # 'type::max()'.
6868 _re_pattern_headers_maybe_templates.extend(
6869 (re.compile(r"((\bstd::)|[^>.:])\b" + _template + r"(<.*?>)?\([^\)]"), _template, _header)
6870 for _template in _templates
6871 )
6872
6873 # Map is often overloaded. Only check, if it is fully qualified.
6874 # Match 'std::map<type>(...)', but not 'map<type>(...)''
6875 _re_pattern_headers_maybe_templates.append(
6876 (re.compile(r"(std\b::\bmap\s*\<)|(^(std\b::\b)map\b\(\s*\<)"), "map<>", "<map>")
6877 )
6878
6879 # Other scripts may reach in and modify this pattern.
6880 _re_pattern_templates: list[tuple[re.Pattern, str, str]] = []
6881 for _header, _templates in _HEADERS_CONTAINING_TEMPLATES:
6882 _re_pattern_templates.extend(
6883 (
6884 re.compile(r"((^|(^|\s|((^|\W)::))std::)|[^>.:]\b)" + _template + r"\s*\<"),
6885 _template + "<>",
6886 _header,
6887 )
6888 for _template in _templates
6889 )
6890
6891 _re_pattern_types_or_objs: list[tuple[re.Pattern, object | type, str]] = []
6892 for _header, _types_or_objs in _HEADERS_TYPES_OR_OBJS:
6893 _re_pattern_types_or_objs.extend(
6894 (re.compile(r"\b" + _type_or_obj + r"\b"), _type_or_obj, _header)
6895 for _type_or_obj in _types_or_objs
6896 )
6897
6898 _re_pattern_functions: list[tuple[re.Pattern, str, str]] = []
6899 for _header, _functions in _HEADERS_FUNCTIONS:
6900 # Match printf(..., ...), but not foo->printf, foo.printf or
6901 # 'type::printf()'.
6902 _re_pattern_functions.extend(
6903 (re.compile(r"([^>.]|^)\b" + _function + r"\([^\)]"), _function, _header)
6904 for _function in _functions
6905 )
6906
6907
6908 def FilesBelongToSameModule(filename_cc, filename_h):
6909 """Check if these two filenames belong to the same module.
6910
6911 The concept of a 'module' here is a as follows:
6912 foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the
6913 same 'module' if they are in the same directory.
6914 some/path/public/xyzzy and some/path/internal/xyzzy are also considered
6915 to belong to the same module here.
6916
6917 If the filename_cc contains a longer path than the filename_h, for example,
6918 '/absolute/path/to/base/sysinfo.cc', and this file would include
6919 'base/sysinfo.h', this function also produces the prefix needed to open the
6920 header. This is used by the caller of this function to more robustly open the
6921 header file. We don't have access to the real include paths in this context,
6922 so we need this guesswork here.
6923
6924 Known bugs: tools/base/bar.cc and base/bar.h belong to the same module
6925 according to this implementation. Because of this, this function gives
6926 some false positives. This should be sufficiently rare in practice.
6927
6928 Args:
6929 filename_cc: is the path for the source (e.g. .cc) file
6930 filename_h: is the path for the header path
6931
6932 Returns:
6933 Tuple with a bool and a string:
6934 bool: True if filename_cc and filename_h belong to the same module.
6935 string: the additional prefix needed to open the header file.
6936 """
6937 fileinfo_cc = FileInfo(filename_cc)
6938 if fileinfo_cc.Extension().lstrip(".") not in GetNonHeaderExtensions():
6939 return (False, "")
6940
6941 fileinfo_h = FileInfo(filename_h)
6942 if not IsHeaderExtension(fileinfo_h.Extension().lstrip(".")):
6943 return (False, "")
6944
6945 filename_cc = filename_cc[: -(len(fileinfo_cc.Extension()))]
6946 if matched_test_suffix := re.search(_TEST_FILE_SUFFIX, fileinfo_cc.BaseName()):
6947 filename_cc = filename_cc[: -len(matched_test_suffix.group(1))]
6948
6949 filename_cc = filename_cc.replace("/public/", "/")
6950 filename_cc = filename_cc.replace("/internal/", "/")
6951
6952 filename_h = filename_h[: -(len(fileinfo_h.Extension()))]
6953 filename_h = filename_h.removesuffix("-inl")
6954 filename_h = filename_h.replace("/public/", "/")
6955 filename_h = filename_h.replace("/internal/", "/")
6956
6957 files_belong_to_same_module = filename_cc.endswith(filename_h)
6958 common_path = ""
6959 if files_belong_to_same_module:
6960 common_path = filename_cc[: -len(filename_h)]
6961 return files_belong_to_same_module, common_path
6962
6963
6964 def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error, io=codecs):
6965 """Reports for missing stl includes.
6966
6967 This function will output warnings to make sure you are including the headers
6968 necessary for the stl containers and functions that you use. We only give one
6969 reason to include a header. For example, if you use both equal_to<> and
6970 less<> in a .h file, only one (the latter in the file) of these will be
6971 reported as a reason to include the <functional>.
6972
6973 Args:
6974 filename: The name of the current file.
6975 clean_lines: A CleansedLines instance containing the file.
6976 include_state: An _IncludeState instance.
6977 error: The function to call with any errors found.
6978 io: The IO factory to use to read the header file. Provided for unittest
6979 injection.
6980 """
6981 required = {} # A map of header name to linenumber and the template entity.
6982 # Example of required: { '<functional>': (1219, 'less<>') }
6983
6984 for linenum in range(clean_lines.NumLines()):
6985 line = clean_lines.elided[linenum]
6986 if not line or line[0] == "#":
6987 continue
6988
6989 _re_patterns = []
6990 _re_patterns.extend(_re_pattern_types_or_objs)
6991 _re_patterns.extend(_re_pattern_functions)
6992 for pattern, item, header in _re_patterns:
6993 matched = pattern.search(line)
6994 if matched:
6995 # Don't warn about strings in non-STL namespaces:
6996 # (We check only the first match per line; good enough.)
6997 prefix = line[: matched.start()]
6998 if prefix.endswith("std::") or not prefix.endswith("::"):
6999 required[header] = (linenum, item)
7000
7001 for pattern, template, header in _re_pattern_headers_maybe_templates:
7002 if pattern.search(line):
7003 required[header] = (linenum, template)
7004
7005 # The following function is just a speed up, no semantics are changed.
7006 if "<" not in line: # Reduces the cpu time usage by skipping lines.
7007 continue
7008
7009 for pattern, template, header in _re_pattern_templates:
7010 matched = pattern.search(line)
7011 if matched:
7012 # Don't warn about IWYU in non-STL namespaces:
7013 # (We check only the first match per line; good enough.)
7014 prefix = line[: matched.start()]
7015 if prefix.endswith("std::") or not prefix.endswith("::"):
7016 required[header] = (linenum, template)
7017
7018 # Let's flatten the include_state include_list and copy it into a dictionary.
7019 include_dict = dict([item for sublist in include_state.include_list for item in sublist])
7020
7021 # All the lines have been processed, report the errors found.
7022 for header in sorted(required, key=required.__getitem__):
7023 template = required[header][1]
7024 header_stripped = header.strip('<>"')
7025 if header_stripped not in include_dict and not (
7026 header_stripped[0] == "c" and (header_stripped[1:] + ".h") in include_dict
7027 ):
7028 error(
7029 filename,
7030 required[header][0],
7031 "build/include_what_you_use",
7032 4,
7033 "Add #include " + header + " for " + template,
7034 )
7035
7036
7037 _RE_PATTERN_EXPLICIT_MAKEPAIR = re.compile(r"\bmake_pair\s*<")
7038
7039
7040 def CheckMakePairUsesDeduction(filename, clean_lines, linenum, error):
7041 """Check that make_pair's template arguments are deduced.
7042
7043 G++ 4.6 in C++11 mode fails badly if make_pair's template arguments are
7044 specified explicitly, and such use isn't intended in any case.
7045
7046 Args:
7047 filename: The name of the current file.
7048 clean_lines: A CleansedLines instance containing the file.
7049 linenum: The number of the line to check.
7050 error: The function to call with any errors found.
7051 """
7052 line = clean_lines.elided[linenum]
7053 match = _RE_PATTERN_EXPLICIT_MAKEPAIR.search(line)
7054 if match:
7055 error(
7056 filename,
7057 linenum,
7058 "build/explicit_make_pair",
7059 4, # 4 = high confidence
7060 "For C++11-compatibility, omit template arguments from make_pair"
7061 " OR use pair directly OR if appropriate, construct a pair directly",
7062 )
7063
7064
7065 def CheckRedundantVirtual(filename, clean_lines, linenum, error):
7066 """Check if line contains a redundant "virtual" function-specifier.
7067
7068 Args:
7069 filename: The name of the current file.
7070 clean_lines: A CleansedLines instance containing the file.
7071 linenum: The number of the line to check.
7072 error: The function to call with any errors found.
7073 """
7074 # Look for "virtual" on current line.
7075 line = clean_lines.elided[linenum]
7076 virtual = re.match(r"^(.*)(\bvirtual\b)(.*)$", line)
7077 if not virtual:
7078 return
7079
7080 # Ignore "virtual" keywords that are near access-specifiers. These
7081 # are only used in class base-specifier and do not apply to member
7082 # functions.
7083 if re.search(r"\b(public|protected|private)\s+$", virtual.group(1)) or re.match(
7084 r"^\s+(public|protected|private)\b", virtual.group(3)
7085 ):
7086 return
7087
7088 # Ignore the "virtual" keyword from virtual base classes. Usually
7089 # there is a column on the same line in these cases (virtual base
7090 # classes are rare in google3 because multiple inheritance is rare).
7091 if re.match(r"^.*[^:]:[^:].*$", line):
7092 return
7093
7094 # Look for the next opening parenthesis. This is the start of the
7095 # parameter list (possibly on the next line shortly after virtual).
7096 # TODO(google): doesn't work if there are virtual functions with
7097 # decltype() or other things that use parentheses, but csearch suggests
7098 # that this is rare.
7099 end_col = -1
7100 end_line = -1
7101 start_col = len(virtual.group(2))
7102 for start_line in range(linenum, min(linenum + 3, clean_lines.NumLines())):
7103 line = clean_lines.elided[start_line][start_col:]
7104 parameter_list = re.match(r"^([^(]*)\(", line)
7105 if parameter_list:
7106 # Match parentheses to find the end of the parameter list
7107 (_, end_line, end_col) = CloseExpression(
7108 clean_lines, start_line, start_col + len(parameter_list.group(1))
7109 )
7110 break
7111 start_col = 0
7112
7113 if end_col < 0:
7114 return # Couldn't find end of parameter list, give up
7115
7116 # Look for "override" or "final" after the parameter list
7117 # (possibly on the next few lines).
7118 for i in range(end_line, min(end_line + 3, clean_lines.NumLines())):
7119 line = clean_lines.elided[i][end_col:]
7120 match = re.search(r"\b(override|final)\b", line)
7121 if match:
7122 error(
7123 filename,
7124 linenum,
7125 "readability/inheritance",
7126 4,
7127 (
7128 '"virtual" is redundant since function is '
7129 f'already declared as "{match.group(1)}"'
7130 ),
7131 )
7132
7133 # Set end_col to check whole lines after we are done with the
7134 # first line.
7135 end_col = 0
7136 if re.search(r"[^\w]\s*$", line):
7137 break
7138
7139
7140 def CheckRedundantOverrideOrFinal(filename, clean_lines, linenum, error):
7141 """Check if line contains a redundant "override" or "final" virt-specifier.
7142
7143 Args:
7144 filename: The name of the current file.
7145 clean_lines: A CleansedLines instance containing the file.
7146 linenum: The number of the line to check.
7147 error: The function to call with any errors found.
7148 """
7149 # Look for closing parenthesis nearby. We need one to confirm where
7150 # the declarator ends and where the virt-specifier starts to avoid
7151 # false positives.
7152 line = clean_lines.elided[linenum]
7153 if (declarator_end := line.rfind(")")) >= 0:
7154 fragment = line[declarator_end:]
7155 else:
7156 if linenum > 1 and clean_lines.elided[linenum - 1].rfind(")") >= 0:
7157 fragment = line
7158 else:
7159 return
7160
7161 # Check that at most one of "override" or "final" is present, not both
7162 if re.search(r"\boverride\b", fragment) and re.search(r"\bfinal\b", fragment):
7163 error(
7164 filename,
7165 linenum,
7166 "readability/inheritance",
7167 4,
7168 ('"override" is redundant since function is already declared as "final"'),
7169 )
7170
7171
7172 # Returns true if we are at a new block, and it is directly
7173 # inside of a namespace.
7174 def IsBlockInNameSpace(nesting_state: NestingState, is_forward_declaration: bool): # noqa: FBT001
7175 """Checks that the new block is directly in a namespace.
7176
7177 Args:
7178 nesting_state: The NestingState object that contains info about our state.
7179 is_forward_declaration: If the class is a forward declared class.
7180 Returns:
7181 Whether or not the new block is directly in a namespace.
7182 """
7183 if is_forward_declaration:
7184 return len(nesting_state.stack) >= 1 and (
7185 isinstance(nesting_state.stack[-1], _NamespaceInfo)
7186 )
7187
7188 if len(nesting_state.stack) >= 1:
7189 if isinstance(nesting_state.stack[-1], _NamespaceInfo):
7190 return True
7191 if (
7192 len(nesting_state.stack) > 1
7193 and isinstance(nesting_state.previous_stack_top, _NamespaceInfo)
7194 and (
7195 isinstance(nesting_state.stack[-2], _NamespaceInfo)
7196 or len(nesting_state.stack) > 2 # Accommodate for WrappedInfo
7197 and issubclass(type(nesting_state.stack[-1]), _WrappedInfo)
7198 and not nesting_state.stack[-2].seen_open_brace
7199 and isinstance(nesting_state.stack[-3], _NamespaceInfo)
7200 )
7201 ):
7202 return True
7203 return False
7204
7205
7206 def ShouldCheckNamespaceIndentation(
7207 nesting_state: NestingState, is_namespace_indent_item, raw_lines_no_comments, linenum
7208 ):
7209 """This method determines if we should apply our namespace indentation check.
7210
7211 Args:
7212 nesting_state: The current nesting state.
7213 is_namespace_indent_item: If we just put a new class on the stack, True.
7214 If the top of the stack is not a class, or we did not recently
7215 add the class, False.
7216 raw_lines_no_comments: The lines without the comments.
7217 linenum: The current line number we are processing.
7218
7219 Returns:
7220 True if we should apply our namespace indentation check. Currently, it
7221 only works for classes and namespaces inside of a namespace.
7222 """
7223
7224 # Required by all checks involving nesting_state
7225 if not nesting_state.stack:
7226 return False
7227
7228 is_forward_declaration = IsForwardClassDeclaration(raw_lines_no_comments, linenum)
7229
7230 if not (is_namespace_indent_item or is_forward_declaration):
7231 return False
7232
7233 # If we are in a macro, we do not want to check the namespace indentation.
7234 if IsMacroDefinition(raw_lines_no_comments, linenum):
7235 return False
7236
7237 # Skip if we are inside an open parenthesis block (e.g. function parameters).
7238 if nesting_state.previous_stack_top and nesting_state.previous_open_parentheses > 0:
7239 return False
7240
7241 # Skip if we are extra-indenting a member initializer list.
7242 if (
7243 isinstance(nesting_state.previous_stack_top, _ConstructorInfo) # F/N (A::A() : _a(0) {/{})
7244 and (
7245 isinstance(nesting_state.stack[-1], _MemInitListInfo)
7246 or isinstance(nesting_state.popped_top, _MemInitListInfo)
7247 )
7248 ) or ( # popping constructor after MemInitList on the same line (: _a(a) {})
7249 isinstance(nesting_state.previous_stack_top, _ConstructorInfo)
7250 and isinstance(nesting_state.popped_top, _ConstructorInfo)
7251 and re.search(r"[^:]:[^:]", raw_lines_no_comments[linenum])
7252 ):
7253 return False
7254
7255 return IsBlockInNameSpace(nesting_state, is_forward_declaration)
7256
7257
7258 # Call this method if the line is directly inside of a namespace.
7259 # If the line above is blank (excluding comments) or the start of
7260 # an inner namespace, it cannot be indented.
7261 def CheckItemIndentationInNamespace(filename, raw_lines_no_comments, linenum, error):
7262 line = raw_lines_no_comments[linenum]
7263 if re.match(r"^\s+", line):
7264 error(
7265 filename, linenum, "whitespace/indent_namespace", 4, "Do not indent within a namespace."
7266 )
7267
7268
7269 def ProcessLine(
7270 filename,
7271 file_extension,
7272 clean_lines,
7273 line,
7274 include_state,
7275 function_state,
7276 nesting_state,
7277 error,
7278 extra_check_functions=None,
7279 cppvar=None,
7280 ):
7281 """Processes a single line in the file.
7282
7283 Args:
7284 filename: Filename of the file that is being processed.
7285 file_extension: The extension (dot not included) of the file.
7286 clean_lines: An array of strings, each representing a line of the file,
7287 with comments stripped.
7288 line: Number of line being processed.
7289 include_state: An _IncludeState instance in which the headers are inserted.
7290 function_state: A _FunctionState instance which counts function lines, etc.
7291 nesting_state: A NestingState instance which maintains information about
7292 the current stack of nested blocks being parsed.
7293 error: A callable to which errors are reported, which takes 4 arguments:
7294 filename, line number, error level, and message
7295 extra_check_functions: An array of additional check functions that will be
7296 run on each source line. Each function takes 4
7297 arguments: filename, clean_lines, line, error
7298 cppvar: The header guard variable returned by GetHeaderGuardCPPVar.
7299 """
7300 raw_lines = clean_lines.raw_lines
7301 ParseNolintSuppressions(filename, raw_lines[line], line, error)
7302 nesting_state.Update(filename, clean_lines, line, error)
7303 CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line, error)
7304 if nesting_state.InAsmBlock():
7305 return
7306 CheckForFunctionLengths(filename, clean_lines, line, function_state, error)
7307 CheckForMultilineCommentsAndStrings(filename, clean_lines, line, error)
7308 CheckStyle(filename, clean_lines, line, file_extension, nesting_state, error, cppvar)
7309 CheckLanguage(filename, clean_lines, line, file_extension, include_state, nesting_state, error)
7310 CheckForNonConstReference(filename, clean_lines, line, nesting_state, error)
7311 CheckForNonStandardConstructs(filename, clean_lines, line, nesting_state, error)
7312 CheckVlogArguments(filename, clean_lines, line, error)
7313 CheckPosixThreading(filename, clean_lines, line, error)
7314 CheckInvalidIncrement(filename, clean_lines, line, error)
7315 CheckMakePairUsesDeduction(filename, clean_lines, line, error)
7316 CheckRedundantVirtual(filename, clean_lines, line, error)
7317 CheckRedundantOverrideOrFinal(filename, clean_lines, line, error)
7318 if extra_check_functions:
7319 for check_fn in extra_check_functions:
7320 check_fn(filename, clean_lines, line, error)
7321
7322
7323 def FlagCxxHeaders(filename, clean_lines, linenum, error):
7324 """Flag C++ headers that the styleguide restricts.
7325
7326 Args:
7327 filename: The name of the current file.
7328 clean_lines: A CleansedLines instance containing the file.
7329 linenum: The number of the line to check.
7330 error: The function to call with any errors found.
7331 """
7332 line = clean_lines.elided[linenum]
7333
7334 include = re.match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line)
7335
7336 # Flag unapproved C++11 headers.
7337 if include and include.group(1) in (
7338 "cfenv",
7339 "fenv.h",
7340 "ratio",
7341 ):
7342 error(
7343 filename,
7344 linenum,
7345 "build/c++11",
7346 5,
7347 f"<{include.group(1)}> is an unapproved C++11 header.",
7348 )
7349
7350 # filesystem is the only unapproved C++17 header
7351 if include and include.group(1) == "filesystem":
7352 error(filename, linenum, "build/c++17", 5, "<filesystem> is an unapproved C++17 header.")
7353
7354
7355 def ProcessFileData(filename, file_extension, lines, error, extra_check_functions=None):
7356 """Performs lint checks and reports any errors to the given error function.
7357
7358 Args:
7359 filename: Filename of the file that is being processed.
7360 file_extension: The extension (dot not included) of the file.
7361 lines: An array of strings, each representing a line of the file, with the
7362 last element being empty if the file is terminated with a newline.
7363 error: A callable to which errors are reported, which takes 4 arguments:
7364 filename, line number, error level, and message
7365 extra_check_functions: An array of additional check functions that will be
7366 run on each source line. Each function takes 4
7367 arguments: filename, clean_lines, line, error
7368 """
7369 lines = (
7370 ["// marker so line numbers and indices both start at 1"]
7371 + lines
7372 + ["// marker so line numbers end in a known way"]
7373 )
7374
7375 include_state = _IncludeState()
7376 function_state = _FunctionState()
7377 nesting_state = NestingState()
7378
7379 ResetNolintSuppressions()
7380
7381 CheckForCopyright(filename, lines, error)
7382 ProcessGlobalSuppressions(filename, lines)
7383 RemoveMultiLineComments(filename, lines, error)
7384 clean_lines = CleansedLines(lines)
7385
7386 cppvar = None
7387 if IsHeaderExtension(file_extension):
7388 cppvar = GetHeaderGuardCPPVariable(filename)
7389 CheckForHeaderGuard(filename, clean_lines, error, cppvar)
7390
7391 for line in range(clean_lines.NumLines()):
7392 ProcessLine(
7393 filename,
7394 file_extension,
7395 clean_lines,
7396 line,
7397 include_state,
7398 function_state,
7399 nesting_state,
7400 error,
7401 extra_check_functions,
7402 cppvar,
7403 )
7404 FlagCxxHeaders(filename, clean_lines, line, error)
7405 if _error_suppressions.HasOpenBlock():
7406 error(
7407 filename,
7408 _error_suppressions.GetOpenBlockStart(),
7409 "readability/nolint",
7410 5,
7411 "NONLINT block never ended",
7412 )
7413
7414 CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error)
7415
7416 # Check that the .cc file has included its header if it exists.
7417 if _IsSourceExtension(file_extension):
7418 CheckHeaderFileIncluded(filename, include_state, error)
7419
7420 # We check here rather than inside ProcessLine so that we see raw
7421 # lines rather than "cleaned" lines.
7422 CheckForBadCharacters(filename, lines, error)
7423
7424 CheckForNewlineAtEOF(filename, lines, error)
7425
7426
7427 def ProcessConfigOverrides(filename):
7428 """Loads the configuration files and processes the config overrides.
7429
7430 Args:
7431 filename: The name of the file being processed by the linter.
7432
7433 Returns:
7434 False if the current |filename| should not be processed further.
7435 """
7436
7437 abs_filename = os.path.abspath(filename)
7438 cfg_filters = []
7439 keep_looking = True
7440 while keep_looking:
7441 abs_path, base_name = os.path.split(abs_filename)
7442 if not base_name:
7443 break # Reached the root directory.
7444
7445 cfg_file = os.path.join(abs_path, _config_filename)
7446 abs_filename = abs_path
7447 if not os.path.isfile(cfg_file):
7448 continue
7449
7450 try:
•7451 with open(cfg_file, encoding="utf8", errors="replace") as file_handle:
7452 for line in file_handle:
7453 line, _, _ = line.partition("#") # Remove comments.
7454 if not line.strip():
7455 continue
7456
7457 name, _, val = line.partition("=")
7458 name = name.strip()
7459 val = val.strip()
7460 if name == "set noparent":
7461 keep_looking = False
7462 elif name == "filter":
7463 cfg_filters.append(val)
7464 elif name == "exclude_files":
7465 # When matching exclude_files pattern, use the base_name of
7466 # the current file name or the directory name we are processing.
7467 # For example, if we are checking for lint errors in /foo/bar/baz.cc
7468 # and we found the .cfg file at /foo/CPPLINT.cfg, then the config
7469 # file's "exclude_files" filter is meant to be checked against "bar"
7470 # and not "baz" nor "bar/baz.cc".
7471 if base_name:
7472 pattern = re.compile(val)
7473 if pattern.match(base_name):
7474 if _cpplint_state.quiet:
7475 # Suppress "Ignoring file" warning when using --quiet.
7476 return False
7477 _cpplint_state.PrintInfo(
7478 f'Ignoring "{filename}": file excluded by "{cfg_file}". '
7479 'File path component "%s" matches '
7480 'pattern "%s"\n' % (base_name, val)
7481 )
7482 return False
7483 elif name == "linelength":
7484 global _line_length
7485 try:
7486 _line_length = int(val)
7487 except ValueError:
7488 _cpplint_state.PrintError("Line length must be numeric.")
7489 elif name == "extensions":
7490 ProcessExtensionsOption(val)
7491 elif name == "root":
7492 global _root
7493 # root directories are specified relative to CPPLINT.cfg dir.
7494 _root = os.path.join(os.path.dirname(cfg_file), val)
7495 elif name == "headers":
7496 ProcessHppHeadersOption(val)
7497 elif name == "includeorder":
7498 ProcessIncludeOrderOption(val)
7499 else:
7500 _cpplint_state.PrintError(
7501 f"Invalid configuration option ({name}) in file {cfg_file}\n"
7502 )
7503
7504 except OSError:
7505 _cpplint_state.PrintError(
7506 f"Skipping config file '{cfg_file}': Can't open for reading\n"
7507 )
7508 keep_looking = False
7509
7510 # Apply all the accumulated filters in reverse order (top-level directory
7511 # config options having the least priority).
7512 for cfg_filter in reversed(cfg_filters):
7513 _AddFilters(cfg_filter)
7514
7515 return True
7516
7517
7518 def ProcessFile(filename, vlevel, extra_check_functions=None):
7519 """Does google-lint on a single file.
7520
7521 Args:
7522 filename: The name of the file to parse.
7523
7524 vlevel: The level of errors to report. Every error of confidence
7525 >= verbose_level will be reported. 0 is a good default.
7526
7527 extra_check_functions: An array of additional check functions that will be
7528 run on each source line. Each function takes 4
7529 arguments: filename, clean_lines, line, error
7530 """
7531
7532 _SetVerboseLevel(vlevel)
7533 _BackupFilters()
7534 old_errors = _cpplint_state.error_count
7535
7536 if not ProcessConfigOverrides(filename):
7537 _RestoreFilters()
7538 return
7539
7540 lf_lines = []
7541 crlf_lines = []
7542 try:
7543 # Support the UNIX convention of using "-" for stdin. Note that
•7544 # we are not opening the file with universal newline support,
7545 # so the resulting lines do # contain trailing '\r' characters
7546 # if we are reading a file that # has CRLF endings.
7547 # If after the split a trailing '\r' is present, it is removed
7548 # below.
7549 if filename == "-":
7550 lines = sys.stdin.read().split("\n")
7551 else:
•7552 with open(filename, encoding="utf8", errors="replace") as target_file:
7553 lines = target_file.read().split("\n")
7554
7555 # Remove trailing '\r'.
7556 # The -1 accounts for the extra trailing blank line we get from split()
7557 for linenum in range(len(lines) - 1):
7558 if lines[linenum].endswith("\r"):
7559 lines[linenum] = lines[linenum].rstrip("\r")
7560 crlf_lines.append(linenum + 1)
7561 else:
7562 lf_lines.append(linenum + 1)
7563
7564 except OSError:
7565 # TODO(aaronliu0130): Maybe make this have an exit code of 2 after all is done
7566 _cpplint_state.PrintError(f"Skipping input '{filename}': Can't open for reading\n")
7567 _RestoreFilters()
7568 return
7569
7570 # Note, if no dot is found, this will give the entire filename as the ext.
7571 file_extension = filename[filename.rfind(".") + 1 :]
7572
7573 # When reading from stdin, the extension is unknown, so no cpplint tests
7574 # should rely on the extension.
7575 if filename != "-" and file_extension not in GetAllExtensions():
7576 _cpplint_state.PrintError(
7577 f"Ignoring {filename}; not a valid file name ({(', '.join(GetAllExtensions()))})\n"
7578 )
7579 else:
7580 ProcessFileData(filename, file_extension, lines, Error, extra_check_functions)
7581
7582 # If end-of-line sequences are a mix of LF and CR-LF, issue
7583 # warnings on the lines with CR.
7584 #
7585 # Don't issue any warnings if all lines are uniformly LF or CR-LF,
7586 # since critique can handle these just fine, and the style guide
7587 # doesn't dictate a particular end of line sequence.
7588 #
7589 # We can't depend on os.linesep to determine what the desired
7590 # end-of-line sequence should be, since that will return the
7591 # server-side end-of-line sequence.
7592 if lf_lines and crlf_lines:
7593 # Warn on every line with CR. An alternative approach might be to
7594 # check whether the file is mostly CRLF or just LF, and warn on the
7595 # minority, we bias toward LF here since most tools prefer LF.
7596 for linenum in crlf_lines:
7597 Error(
7598 filename,
7599 linenum,
7600 "whitespace/newline",
7601 1,
7602 "Unexpected \\r (^M) found; better to use only \\n",
7603 )
7604
7605 # Suppress printing anything if --quiet was passed unless the error
7606 # count has increased after processing this file.
7607 if not _cpplint_state.quiet or old_errors != _cpplint_state.error_count:
7608 _cpplint_state.PrintInfo(f"Done processing {filename}\n")
7609 _RestoreFilters()
7610
7611
7612 def PrintUsage(message):
7613 """Prints a brief usage string and exits, optionally with an error message.
7614
7615 Args:
7616 message: The optional error message.
7617 """
7618 sys.stderr.write(
7619 _USAGE
7620 % (
7621 sorted(GetAllExtensions()),
7622 ",".join(sorted(GetAllExtensions())),
7623 sorted(GetHeaderExtensions()),
7624 ",".join(sorted(GetHeaderExtensions())),
7625 )
7626 )
7627
7628 if message:
7629 sys.exit("\nFATAL ERROR: " + message)
7630 else:
7631 sys.exit(0)
7632
7633
7634 def PrintVersion():
7635 sys.stdout.write("Cpplint fork (https://github.com/cpplint/cpplint)\n")
7636 sys.stdout.write("cpplint " + __VERSION__ + "\n")
7637 sys.stdout.write("Python " + sys.version + "\n")
7638 sys.exit(0)
7639
7640
7641 def PrintCategories():
7642 """Prints a list of all the error-categories used by error messages.
7643
7644 These are the categories used to filter messages via --filter.
7645 """
7646 sys.stderr.write("".join(f" {cat}\n" for cat in _ERROR_CATEGORIES))
7647 sys.exit(0)
7648
7649
7650 def ParseArguments(args):
7651 """Parses the command line arguments.
7652
7653 This may set the output format and verbosity level as side-effects.
7654
7655 Args:
7656 args: The command line arguments:
7657
7658 Returns:
7659 The list of filenames to lint.
7660 """
7661 try:
7662 (opts, filenames) = getopt.getopt(
7663 args,
7664 "",
7665 [
7666 "help",
7667 "output=",
7668 "verbose=",
7669 "v=",
7670 "version",
7671 "counting=",
7672 "filter=",
7673 "root=",
7674 "repository=",
7675 "linelength=",
7676 "extensions=",
7677 "exclude=",
7678 "recursive",
7679 "headers=",
7680 "includeorder=",
7681 "config=",
7682 "quiet",
7683 ],
7684 )
7685 except getopt.GetoptError:
7686 PrintUsage("Invalid arguments.")
7687
7688 verbosity = _VerboseLevel()
7689 output_format = _OutputFormat()
7690 filters = ""
7691 quiet = _Quiet()
7692 counting_style = ""
7693 recursive = False
7694
7695 for opt, val in opts:
7696 if opt == "--help":
7697 PrintUsage(None)
7698 if opt == "--version":
7699 PrintVersion()
7700 elif opt == "--output":
7701 if val not in ("emacs", "vs7", "eclipse", "junit", "sed", "gsed"):
7702 PrintUsage(
7703 "The only allowed output formats are emacs, vs7, eclipse sed, gsed and junit."
7704 )
7705 output_format = val
7706 elif opt == "--quiet":
7707 quiet = True
7708 elif opt in {"--verbose", "--v"}:
7709 verbosity = int(val)
7710 elif opt == "--filter":
7711 filters = val
7712 if not filters:
7713 PrintCategories()
7714 elif opt == "--counting":
7715 if val not in ("total", "toplevel", "detailed"):
7716 PrintUsage("Valid counting options are total, toplevel, and detailed")
7717 counting_style = val
7718 elif opt == "--root":
7719 global _root
7720 _root = val
7721 elif opt == "--repository":
7722 global _repository
7723 _repository = val
7724 elif opt == "--linelength":
7725 global _line_length
7726 try:
7727 _line_length = int(val)
7728 except ValueError:
7729 PrintUsage("Line length must be digits.")
7730 elif opt == "--exclude":
7731 global _excludes
7732 if not _excludes:
7733 _excludes = set()
7734 _excludes.update(glob.glob(val))
7735 elif opt == "--extensions":
7736 ProcessExtensionsOption(val)
7737 elif opt == "--headers":
7738 ProcessHppHeadersOption(val)
7739 elif opt == "--recursive":
7740 recursive = True
7741 elif opt == "--includeorder":
7742 ProcessIncludeOrderOption(val)
7743 elif opt == "--config":
7744 global _config_filename
7745 _config_filename = val
7746 if os.path.basename(_config_filename) != _config_filename:
7747 PrintUsage("Config file name must not include directory components.")
7748
7749 if not filenames:
7750 PrintUsage("No files were specified.")
7751
7752 if recursive:
7753 filenames = _ExpandDirectories(filenames)
7754
7755 if _excludes:
7756 filenames = _FilterExcludedFiles(filenames)
7757
7758 _SetOutputFormat(output_format)
7759 _SetQuiet(quiet)
7760 _SetVerboseLevel(verbosity)
7761 _SetFilters(filters)
7762 _SetCountingStyle(counting_style)
7763
7764 filenames.sort()
7765 return filenames
7766
7767
7768 def _ParseFilterSelector(parameter):
7769 """Parses the given command line parameter for file- and line-specific
7770 exclusions.
7771 readability/casting:file.cpp
7772 readability/casting:file.cpp:43
7773
7774 Args:
7775 parameter: The parameter value of --filter
7776
7777 Returns:
7778 [category, filename, line].
7779 Category is always given.
7780 Filename is either a filename or empty if all files are meant.
7781 Line is either a line in filename or -1 if all lines are meant.
7782 """
7783 colon_pos = parameter.find(":")
7784 if colon_pos == -1:
7785 return parameter, "", -1
7786 category = parameter[:colon_pos]
7787 second_colon_pos = parameter.find(":", colon_pos + 1)
7788 if second_colon_pos == -1:
7789 return category, parameter[colon_pos + 1 :], -1
7790 return (
7791 category,
7792 parameter[colon_pos + 1 : second_colon_pos],
7793 int(parameter[second_colon_pos + 1 :]),
7794 )
7795
7796
7797 def _ExpandDirectories(filenames):
7798 """Searches a list of filenames and replaces directories in the list with
7799 all files descending from those directories. Files with extensions not in
7800 the valid extensions list are excluded.
7801
7802 Args:
7803 filenames: A list of files or directories
7804
7805 Returns:
7806 A list of all files that are members of filenames or descended from a
7807 directory in filenames
7808 """
7809 expanded = set()
7810 for filename in filenames:
7811 if not os.path.isdir(filename):
7812 expanded.add(filename)
7813 continue
7814
7815 for root, _, files in os.walk(filename):
7816 for loopfile in files:
7817 fullname = os.path.join(root, loopfile)
7818 fullname = fullname.removeprefix("." + os.path.sep)
7819 expanded.add(fullname)
7820
7821 return [
7822 filename for filename in expanded if os.path.splitext(filename)[1][1:] in GetAllExtensions()
7823 ]
7824
7825
7826 def _FilterExcludedFiles(fnames):
7827 """Filters out files listed in the --exclude command line switch. File paths
7828 in the switch are evaluated relative to the current working directory
7829 """
7830 exclude_paths = [os.path.abspath(f) for f in _excludes]
7831 # because globbing does not work recursively, exclude all subpath of all excluded entries
7832 return [
7833 f
7834 for f in fnames
7835 if not any(e for e in exclude_paths if _IsParentOrSame(e, os.path.abspath(f)))
7836 ]
7837
7838
7839 def _IsParentOrSame(parent, child):
7840 """Return true if child is subdirectory of parent.
7841 Assumes both paths are absolute and don't contain symlinks.
7842 """
7843 parent = os.path.normpath(parent)
7844 child = os.path.normpath(child)
7845 if parent == child:
7846 return True
7847
7848 prefix = os.path.commonprefix([parent, child])
7849 if prefix != parent:
7850 return False
7851 # Note: os.path.commonprefix operates on character basis, so
7852 # take extra care of situations like '/foo/ba' and '/foo/bar/baz'
7853 child_suffix = child[len(prefix) :]
7854 child_suffix = child_suffix.lstrip(os.sep)
7855 return child == os.path.join(prefix, child_suffix)
7856
7857
7858 def main():
7859 filenames = ParseArguments(sys.argv[1:])
7860 backup_err = sys.stderr
7861 try:
7862 # Change stderr to write with replacement characters so we don't die
7863 # if we try to print something containing non-ASCII characters.
7864 sys.stderr = codecs.StreamReader(sys.stderr, "replace")
7865
7866 _cpplint_state.ResetErrorCounts()
7867 for filename in filenames:
7868 ProcessFile(filename, _cpplint_state.verbose_level)
7869 # If --quiet is passed, suppress printing error count unless there are errors.
7870 if not _cpplint_state.quiet or _cpplint_state.error_count > 0:
7871 _cpplint_state.PrintErrorCounts()
7872
7873 if _cpplint_state.output_format == "junit":
7874 sys.stderr.write(_cpplint_state.FormatJUnitXML())
7875
7876 finally:
7877 sys.stderr = backup_err
7878
7879 sys.exit(_cpplint_state.error_count > 0)
7880
7881
7882 if __name__ == "__main__":
7883 main()