[email protected] | d528f8b | 2012-05-11 17:31:08 | [diff] [blame] | 1 | #!/usr/bin/env python |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2 | # |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 3 | # Copyright (c) 2009 Google Inc. All rights reserved. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 4 | # |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 5 | # Redistribution and use in source and binary forms, with or without |
| 6 | # modification, are permitted provided that the following conditions are |
| 7 | # met: |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 8 | # |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 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. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 18 | # |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 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. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 30 | |
agable | f39c333 | 2016-09-26 16:35:42 | [diff] [blame] | 31 | # pylint: skip-file |
| 32 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 33 | """Does google-lint on c++ files. |
| 34 | |
| 35 | The goal of this script is to identify places in the code that *may* |
| 36 | be in non-compliance with google style. It does not attempt to fix |
| 37 | up these problems -- the point is to educate. It does also not |
| 38 | attempt to find all problems, or to ensure that everything it does |
| 39 | find is legitimately a problem. |
| 40 | |
| 41 | In particular, we can get very confused by /* and // inside strings! |
| 42 | We do a small hack, which is to ignore //'s with "'s after them on the |
| 43 | same line, but it is far from perfect (in either direction). |
| 44 | """ |
| 45 | |
| 46 | import codecs |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 47 | import copy |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 48 | import getopt |
| 49 | import math # for log |
| 50 | import os |
| 51 | import re |
| 52 | import sre_compile |
| 53 | import string |
| 54 | import sys |
| 55 | import unicodedata |
| 56 | |
| 57 | |
| 58 | _USAGE = """ |
| 59 | Syntax: cpplint.py [--verbose=#] [--output=vs7] [--filter=-x,+y,...] |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 60 | [--counting=total|toplevel|detailed] [--root=subdir] |
| 61 | [--linelength=digits] |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 62 | <file> [file] ... |
| 63 | |
| 64 | The style guidelines this tries to follow are those in |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 65 | https://google-styleguide.googlecode.com/svn/trunk/cppguide.xml |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 66 | |
| 67 | Every problem is given a confidence score from 1-5, with 5 meaning we are |
| 68 | certain of the problem, and 1 meaning it could be a legitimate construct. |
| 69 | This will miss some errors, and is not a substitute for a code review. |
| 70 | |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 71 | To suppress false-positive errors of a certain category, add a |
| 72 | 'NOLINT(category)' comment to the line. NOLINT or NOLINT(*) |
| 73 | suppresses errors of all categories on that line. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 74 | |
| 75 | The files passed in will be linted; at least one file must be provided. |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 76 | Default linted extensions are .cc, .cpp, .cu, .cuh and .h. Change the |
| 77 | extensions with the --extensions flag. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 78 | |
| 79 | Flags: |
| 80 | |
| 81 | output=vs7 |
| 82 | By default, the output is formatted to ease emacs parsing. Visual Studio |
| 83 | compatible output (vs7) may also be used. Other formats are unsupported. |
| 84 | |
| 85 | verbose=# |
| 86 | Specify a number 0-5 to restrict errors to certain verbosity levels. |
| 87 | |
| 88 | filter=-x,+y,... |
| 89 | Specify a comma-separated list of category-filters to apply: only |
| 90 | error messages whose category names pass the filters will be printed. |
| 91 | (Category names are printed with the message and look like |
| 92 | "[whitespace/indent]".) Filters are evaluated left to right. |
| 93 | "-FOO" and "FOO" means "do not print categories that start with FOO". |
| 94 | "+FOO" means "do print categories that start with FOO". |
| 95 | |
| 96 | Examples: --filter=-whitespace,+whitespace/braces |
| 97 | --filter=whitespace,runtime/printf,+runtime/printf_format |
| 98 | --filter=-,+build/include_what_you_use |
| 99 | |
| 100 | To see a list of all the categories used in cpplint, pass no arg: |
| 101 | --filter= |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 102 | |
| 103 | counting=total|toplevel|detailed |
| 104 | The total number of errors found is always printed. If |
| 105 | 'toplevel' is provided, then the count of errors in each of |
| 106 | the top-level categories like 'build' and 'whitespace' will |
| 107 | also be printed. If 'detailed' is provided, then a count |
| 108 | is provided for each category like 'build/class'. |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 109 | |
| 110 | root=subdir |
| 111 | The root directory used for deriving header guard CPP variable. |
| 112 | By default, the header guard CPP variable is calculated as the relative |
| 113 | path to the directory that contains .git, .hg, or .svn. When this flag |
| 114 | is specified, the relative path is calculated from the specified |
| 115 | directory. If the specified directory does not exist, this flag is |
| 116 | ignored. |
| 117 | |
| 118 | Examples: |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 119 | Assuming that src/.git exists, the header guard CPP variables for |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 120 | src/chrome/browser/ui/browser.h are: |
| 121 | |
| 122 | No flag => CHROME_BROWSER_UI_BROWSER_H_ |
| 123 | --root=chrome => BROWSER_UI_BROWSER_H_ |
| 124 | --root=chrome/browser => UI_BROWSER_H_ |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 125 | |
| 126 | linelength=digits |
| 127 | This is the allowed line length for the project. The default value is |
| 128 | 80 characters. |
| 129 | |
| 130 | Examples: |
| 131 | --linelength=120 |
| 132 | |
| 133 | extensions=extension,extension,... |
| 134 | The allowed file extensions that cpplint will check |
| 135 | |
| 136 | Examples: |
| 137 | --extensions=hpp,cpp |
[email protected] | 1744993 | 2014-07-28 22:13:33 | [diff] [blame] | 138 | |
| 139 | cpplint.py supports per-directory configurations specified in CPPLINT.cfg |
| 140 | files. CPPLINT.cfg file can contain a number of key=value pairs. |
| 141 | Currently the following options are supported: |
| 142 | |
| 143 | set noparent |
| 144 | filter=+filter1,-filter2,... |
| 145 | exclude_files=regex |
[email protected] | 68a4fa6 | 2014-08-25 16:26:18 | [diff] [blame] | 146 | linelength=80 |
[email protected] | 1744993 | 2014-07-28 22:13:33 | [diff] [blame] | 147 | |
| 148 | "set noparent" option prevents cpplint from traversing directory tree |
| 149 | upwards looking for more .cfg files in parent directories. This option |
| 150 | is usually placed in the top-level project directory. |
| 151 | |
| 152 | The "filter" option is similar in function to --filter flag. It specifies |
| 153 | message filters in addition to the |_DEFAULT_FILTERS| and those specified |
| 154 | through --filter command-line flag. |
| 155 | |
| 156 | "exclude_files" allows to specify a regular expression to be matched against |
| 157 | a file name. If the expression matches, the file is skipped and not run |
| 158 | through liner. |
| 159 | |
[email protected] | 68a4fa6 | 2014-08-25 16:26:18 | [diff] [blame] | 160 | "linelength" allows to specify the allowed line length for the project. |
| 161 | |
[email protected] | 1744993 | 2014-07-28 22:13:33 | [diff] [blame] | 162 | CPPLINT.cfg has an effect on files in the same directory and all |
| 163 | sub-directories, unless overridden by a nested configuration file. |
| 164 | |
| 165 | Example file: |
| 166 | filter=-build/include_order,+build/include_alpha |
| 167 | exclude_files=.*\.cc |
| 168 | |
| 169 | The above example disables build/include_order warning and enables |
| 170 | build/include_alpha as well as excludes all .cc from being |
| 171 | processed by linter, in the current directory (where the .cfg |
| 172 | file is located) and all sub-directories. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 173 | """ |
| 174 | |
| 175 | # We categorize each error message we print. Here are the categories. |
| 176 | # We want an explicit list so we can list them all in cpplint --filter=. |
| 177 | # If you add a new error message with a new category, add it to the list |
| 178 | # here! cpplint_unittest.py should tell you if you forget to do this. |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 179 | _ERROR_CATEGORIES = [ |
[email protected] | 255f2be | 2014-12-05 22:19:55 | [diff] [blame] | 180 | 'build/class', |
| 181 | 'build/c++11', |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 182 | 'build/c++14', |
| 183 | 'build/c++tr1', |
[email protected] | 255f2be | 2014-12-05 22:19:55 | [diff] [blame] | 184 | 'build/deprecated', |
| 185 | 'build/endif_comment', |
| 186 | 'build/explicit_make_pair', |
| 187 | 'build/forward_decl', |
| 188 | 'build/header_guard', |
| 189 | 'build/include', |
| 190 | 'build/include_alpha', |
| 191 | 'build/include_order', |
| 192 | 'build/include_what_you_use', |
| 193 | 'build/namespaces', |
| 194 | 'build/printf_format', |
| 195 | 'build/storage_class', |
| 196 | 'legal/copyright', |
| 197 | 'readability/alt_tokens', |
| 198 | 'readability/braces', |
| 199 | 'readability/casting', |
| 200 | 'readability/check', |
| 201 | 'readability/constructors', |
| 202 | 'readability/fn_size', |
[email protected] | 255f2be | 2014-12-05 22:19:55 | [diff] [blame] | 203 | 'readability/inheritance', |
| 204 | 'readability/multiline_comment', |
| 205 | 'readability/multiline_string', |
| 206 | 'readability/namespace', |
| 207 | 'readability/nolint', |
| 208 | 'readability/nul', |
| 209 | 'readability/strings', |
| 210 | 'readability/todo', |
| 211 | 'readability/utf8', |
| 212 | 'runtime/arrays', |
| 213 | 'runtime/casting', |
| 214 | 'runtime/explicit', |
| 215 | 'runtime/int', |
| 216 | 'runtime/init', |
| 217 | 'runtime/invalid_increment', |
| 218 | 'runtime/member_string_references', |
| 219 | 'runtime/memset', |
| 220 | 'runtime/indentation_namespace', |
| 221 | 'runtime/operator', |
| 222 | 'runtime/printf', |
| 223 | 'runtime/printf_format', |
| 224 | 'runtime/references', |
| 225 | 'runtime/string', |
| 226 | 'runtime/threadsafe_fn', |
| 227 | 'runtime/vlog', |
| 228 | 'whitespace/blank_line', |
| 229 | 'whitespace/braces', |
| 230 | 'whitespace/comma', |
| 231 | 'whitespace/comments', |
| 232 | 'whitespace/empty_conditional_body', |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 233 | 'whitespace/empty_if_body', |
[email protected] | 255f2be | 2014-12-05 22:19:55 | [diff] [blame] | 234 | 'whitespace/empty_loop_body', |
| 235 | 'whitespace/end_of_line', |
| 236 | 'whitespace/ending_newline', |
| 237 | 'whitespace/forcolon', |
| 238 | 'whitespace/indent', |
| 239 | 'whitespace/line_length', |
| 240 | 'whitespace/newline', |
| 241 | 'whitespace/operators', |
| 242 | 'whitespace/parens', |
| 243 | 'whitespace/semicolon', |
| 244 | 'whitespace/tab', |
| 245 | 'whitespace/todo', |
| 246 | ] |
| 247 | |
| 248 | # These error categories are no longer enforced by cpplint, but for backwards- |
| 249 | # compatibility they may still appear in NOLINT comments. |
| 250 | _LEGACY_ERROR_CATEGORIES = [ |
| 251 | 'readability/streams', |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 252 | 'readability/function', |
[email protected] | 255f2be | 2014-12-05 22:19:55 | [diff] [blame] | 253 | ] |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 254 | |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 255 | # The default state of the category filter. This is overridden by the --filter= |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 256 | # flag. By default all errors are on, so only add here categories that should be |
| 257 | # off by default (i.e., categories that must be enabled by the --filter= flags). |
| 258 | # All entries here should start with a '-' or '+', as in the --filter= flag. |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 259 | _DEFAULT_FILTERS = ['-build/include_alpha'] |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 260 | |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 261 | # The default list of categories suppressed for C (not C++) files. |
| 262 | _DEFAULT_C_SUPPRESSED_CATEGORIES = [ |
| 263 | 'readability/casting', |
| 264 | ] |
| 265 | |
| 266 | # The default list of categories suppressed for Linux Kernel files. |
| 267 | _DEFAULT_KERNEL_SUPPRESSED_CATEGORIES = [ |
| 268 | 'whitespace/tab', |
| 269 | ] |
| 270 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 271 | # We used to check for high-bit characters, but after much discussion we |
| 272 | # decided those were OK, as long as they were in UTF-8 and didn't represent |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 273 | # hard-coded international strings, which belong in a separate i18n file. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 274 | |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 275 | # C++ headers |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 276 | _CPP_HEADERS = frozenset([ |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 277 | # Legacy |
| 278 | 'algobase.h', |
| 279 | 'algo.h', |
| 280 | 'alloc.h', |
| 281 | 'builtinbuf.h', |
| 282 | 'bvector.h', |
| 283 | 'complex.h', |
| 284 | 'defalloc.h', |
| 285 | 'deque.h', |
| 286 | 'editbuf.h', |
| 287 | 'fstream.h', |
| 288 | 'function.h', |
| 289 | 'hash_map', |
| 290 | 'hash_map.h', |
| 291 | 'hash_set', |
| 292 | 'hash_set.h', |
| 293 | 'hashtable.h', |
| 294 | 'heap.h', |
| 295 | 'indstream.h', |
| 296 | 'iomanip.h', |
| 297 | 'iostream.h', |
| 298 | 'istream.h', |
| 299 | 'iterator.h', |
| 300 | 'list.h', |
| 301 | 'map.h', |
| 302 | 'multimap.h', |
| 303 | 'multiset.h', |
| 304 | 'ostream.h', |
| 305 | 'pair.h', |
| 306 | 'parsestream.h', |
| 307 | 'pfstream.h', |
| 308 | 'procbuf.h', |
| 309 | 'pthread_alloc', |
| 310 | 'pthread_alloc.h', |
| 311 | 'rope', |
| 312 | 'rope.h', |
| 313 | 'ropeimpl.h', |
| 314 | 'set.h', |
| 315 | 'slist', |
| 316 | 'slist.h', |
| 317 | 'stack.h', |
| 318 | 'stdiostream.h', |
| 319 | 'stl_alloc.h', |
| 320 | 'stl_relops.h', |
| 321 | 'streambuf.h', |
| 322 | 'stream.h', |
| 323 | 'strfile.h', |
| 324 | 'strstream.h', |
| 325 | 'tempbuf.h', |
| 326 | 'tree.h', |
| 327 | 'type_traits.h', |
| 328 | 'vector.h', |
| 329 | # 17.6.1.2 C++ library headers |
| 330 | 'algorithm', |
| 331 | 'array', |
| 332 | 'atomic', |
| 333 | 'bitset', |
| 334 | 'chrono', |
| 335 | 'codecvt', |
| 336 | 'complex', |
| 337 | 'condition_variable', |
| 338 | 'deque', |
| 339 | 'exception', |
| 340 | 'forward_list', |
| 341 | 'fstream', |
| 342 | 'functional', |
| 343 | 'future', |
| 344 | 'initializer_list', |
| 345 | 'iomanip', |
| 346 | 'ios', |
| 347 | 'iosfwd', |
| 348 | 'iostream', |
| 349 | 'istream', |
| 350 | 'iterator', |
| 351 | 'limits', |
| 352 | 'list', |
| 353 | 'locale', |
| 354 | 'map', |
| 355 | 'memory', |
| 356 | 'mutex', |
| 357 | 'new', |
| 358 | 'numeric', |
| 359 | 'ostream', |
| 360 | 'queue', |
| 361 | 'random', |
| 362 | 'ratio', |
| 363 | 'regex', |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 364 | 'scoped_allocator', |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 365 | 'set', |
| 366 | 'sstream', |
| 367 | 'stack', |
| 368 | 'stdexcept', |
| 369 | 'streambuf', |
| 370 | 'string', |
| 371 | 'strstream', |
| 372 | 'system_error', |
| 373 | 'thread', |
| 374 | 'tuple', |
| 375 | 'typeindex', |
| 376 | 'typeinfo', |
| 377 | 'type_traits', |
| 378 | 'unordered_map', |
| 379 | 'unordered_set', |
| 380 | 'utility', |
| 381 | 'valarray', |
| 382 | 'vector', |
| 383 | # 17.6.1.2 C++ headers for C library facilities |
| 384 | 'cassert', |
| 385 | 'ccomplex', |
| 386 | 'cctype', |
| 387 | 'cerrno', |
| 388 | 'cfenv', |
| 389 | 'cfloat', |
| 390 | 'cinttypes', |
| 391 | 'ciso646', |
| 392 | 'climits', |
| 393 | 'clocale', |
| 394 | 'cmath', |
| 395 | 'csetjmp', |
| 396 | 'csignal', |
| 397 | 'cstdalign', |
| 398 | 'cstdarg', |
| 399 | 'cstdbool', |
| 400 | 'cstddef', |
| 401 | 'cstdint', |
| 402 | 'cstdio', |
| 403 | 'cstdlib', |
| 404 | 'cstring', |
| 405 | 'ctgmath', |
| 406 | 'ctime', |
| 407 | 'cuchar', |
| 408 | 'cwchar', |
| 409 | 'cwctype', |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 410 | ]) |
| 411 | |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 412 | # Type names |
| 413 | _TYPES = re.compile( |
| 414 | r'^(?:' |
| 415 | # [dcl.type.simple] |
| 416 | r'(char(16_t|32_t)?)|wchar_t|' |
| 417 | r'bool|short|int|long|signed|unsigned|float|double|' |
| 418 | # [support.types] |
| 419 | r'(ptrdiff_t|size_t|max_align_t|nullptr_t)|' |
| 420 | # [cstdint.syn] |
| 421 | r'(u?int(_fast|_least)?(8|16|32|64)_t)|' |
| 422 | r'(u?int(max|ptr)_t)|' |
| 423 | r')$') |
| 424 | |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 425 | |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 426 | # These headers are excluded from [build/include] and [build/include_order] |
| 427 | # checks: |
| 428 | # - Anything not following google file name conventions (containing an |
| 429 | # uppercase character, such as Python.h or nsStringAPI.h, for example). |
| 430 | # - Lua headers. |
| 431 | _THIRD_PARTY_HEADERS_PATTERN = re.compile( |
| 432 | r'^(?:[^/]*[A-Z][^/]*\.h|lua\.h|lauxlib\.h|lualib\.h)$') |
| 433 | |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 434 | # Pattern for matching FileInfo.BaseName() against test file name |
| 435 | _TEST_FILE_SUFFIX = r'(_test|_unittest|_regtest)$' |
| 436 | |
| 437 | # Pattern that matches only complete whitespace, possibly across multiple lines. |
| 438 | _EMPTY_CONDITIONAL_BODY_PATTERN = re.compile(r'^\s*$', re.DOTALL) |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 439 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 440 | # Assertion macros. These are defined in base/logging.h and |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 441 | # testing/base/public/gunit.h. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 442 | _CHECK_MACROS = [ |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 443 | 'DCHECK', 'CHECK', |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 444 | 'EXPECT_TRUE', 'ASSERT_TRUE', |
| 445 | 'EXPECT_FALSE', 'ASSERT_FALSE', |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 446 | ] |
| 447 | |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 448 | # Replacement macros for CHECK/DCHECK/EXPECT_TRUE/EXPECT_FALSE |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 449 | _CHECK_REPLACEMENT = dict([(m, {}) for m in _CHECK_MACROS]) |
| 450 | |
| 451 | for op, replacement in [('==', 'EQ'), ('!=', 'NE'), |
| 452 | ('>=', 'GE'), ('>', 'GT'), |
| 453 | ('<=', 'LE'), ('<', 'LT')]: |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 454 | _CHECK_REPLACEMENT['DCHECK'][op] = 'DCHECK_%s' % replacement |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 455 | _CHECK_REPLACEMENT['CHECK'][op] = 'CHECK_%s' % replacement |
| 456 | _CHECK_REPLACEMENT['EXPECT_TRUE'][op] = 'EXPECT_%s' % replacement |
| 457 | _CHECK_REPLACEMENT['ASSERT_TRUE'][op] = 'ASSERT_%s' % replacement |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 458 | |
| 459 | for op, inv_replacement in [('==', 'NE'), ('!=', 'EQ'), |
| 460 | ('>=', 'LT'), ('>', 'LE'), |
| 461 | ('<=', 'GT'), ('<', 'GE')]: |
| 462 | _CHECK_REPLACEMENT['EXPECT_FALSE'][op] = 'EXPECT_%s' % inv_replacement |
| 463 | _CHECK_REPLACEMENT['ASSERT_FALSE'][op] = 'ASSERT_%s' % inv_replacement |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 464 | |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 465 | # Alternative tokens and their replacements. For full list, see section 2.5 |
| 466 | # Alternative tokens [lex.digraph] in the C++ standard. |
| 467 | # |
| 468 | # Digraphs (such as '%:') are not included here since it's a mess to |
| 469 | # match those on a word boundary. |
| 470 | _ALT_TOKEN_REPLACEMENT = { |
| 471 | 'and': '&&', |
| 472 | 'bitor': '|', |
| 473 | 'or': '||', |
| 474 | 'xor': '^', |
| 475 | 'compl': '~', |
| 476 | 'bitand': '&', |
| 477 | 'and_eq': '&=', |
| 478 | 'or_eq': '|=', |
| 479 | 'xor_eq': '^=', |
| 480 | 'not': '!', |
| 481 | 'not_eq': '!=' |
| 482 | } |
| 483 | |
| 484 | # Compile regular expression that matches all the above keywords. The "[ =()]" |
| 485 | # bit is meant to avoid matching these keywords outside of boolean expressions. |
| 486 | # |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 487 | # False positives include C-style multi-line comments and multi-line strings |
| 488 | # but those have always been troublesome for cpplint. |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 489 | _ALT_TOKEN_REPLACEMENT_PATTERN = re.compile( |
| 490 | r'[ =()](' + ('|'.join(_ALT_TOKEN_REPLACEMENT.keys())) + r')(?=[ (]|$)') |
| 491 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 492 | |
| 493 | # These constants define types of headers for use with |
| 494 | # _IncludeState.CheckNextIncludeOrder(). |
| 495 | _C_SYS_HEADER = 1 |
| 496 | _CPP_SYS_HEADER = 2 |
| 497 | _LIKELY_MY_HEADER = 3 |
| 498 | _POSSIBLE_MY_HEADER = 4 |
| 499 | _OTHER_HEADER = 5 |
| 500 | |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 501 | # These constants define the current inline assembly state |
| 502 | _NO_ASM = 0 # Outside of inline assembly block |
| 503 | _INSIDE_ASM = 1 # Inside inline assembly block |
| 504 | _END_ASM = 2 # Last line of inline assembly block |
| 505 | _BLOCK_ASM = 3 # The whole block is an inline assembly block |
| 506 | |
| 507 | # Match start of assembly blocks |
| 508 | _MATCH_ASM = re.compile(r'^\s*(?:asm|_asm|__asm|__asm__)' |
| 509 | r'(?:\s+(volatile|__volatile__))?' |
| 510 | r'\s*[{(]') |
| 511 | |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 512 | # Match strings that indicate we're working on a C (not C++) file. |
| 513 | _SEARCH_C_FILE = re.compile(r'\b(?:LINT_C_FILE|' |
| 514 | r'vim?:\s*.*(\s*|:)filetype=c(\s*|:|$))') |
| 515 | |
| 516 | # Match string that indicates we're working on a Linux Kernel file. |
| 517 | _SEARCH_KERNEL_FILE = re.compile(r'\b(?:LINT_KERNEL_FILE)') |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 518 | |
| 519 | _regexp_compile_cache = {} |
| 520 | |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 521 | # {str, set(int)}: a map from error categories to sets of linenumbers |
| 522 | # on which those errors are expected and should be suppressed. |
| 523 | _error_suppressions = {} |
| 524 | |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 525 | # The root directory used for deriving header guard CPP variable. |
| 526 | # This is set by --root flag. |
| 527 | _root = None |
| 528 | |
sdefresne | 263e928 | 2016-07-19 09:14:22 | [diff] [blame] | 529 | # The project root directory. Used for deriving header guard CPP variable. |
| 530 | # This is set by --project_root flag. Must be an absolute path. |
| 531 | _project_root = None |
| 532 | |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 533 | # The allowed line length of files. |
| 534 | # This is set by --linelength flag. |
| 535 | _line_length = 80 |
| 536 | |
| 537 | # The allowed extensions for file names |
| 538 | # This is set by --extensions flag. |
| 539 | _valid_extensions = set(['cc', 'h', 'cpp', 'cu', 'cuh']) |
| 540 | |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 541 | # {str, bool}: a map from error categories to booleans which indicate if the |
| 542 | # category should be suppressed for every line. |
| 543 | _global_error_suppressions = {} |
| 544 | |
| 545 | |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 546 | def ParseNolintSuppressions(filename, raw_line, linenum, error): |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 547 | """Updates the global list of line error-suppressions. |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 548 | |
| 549 | Parses any NOLINT comments on the current line, updating the global |
| 550 | error_suppressions store. Reports an error if the NOLINT comment |
| 551 | was malformed. |
| 552 | |
| 553 | Args: |
| 554 | filename: str, the name of the input file. |
| 555 | raw_line: str, the line of input text, with comments. |
| 556 | linenum: int, the number of the current line. |
| 557 | error: function, an error handler. |
| 558 | """ |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 559 | matched = Search(r'\bNOLINT(NEXTLINE)?\b(\([^)]+\))?', raw_line) |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 560 | if matched: |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 561 | if matched.group(1): |
| 562 | suppressed_line = linenum + 1 |
| 563 | else: |
| 564 | suppressed_line = linenum |
| 565 | category = matched.group(2) |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 566 | if category in (None, '(*)'): # => "suppress all" |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 567 | _error_suppressions.setdefault(None, set()).add(suppressed_line) |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 568 | else: |
| 569 | if category.startswith('(') and category.endswith(')'): |
| 570 | category = category[1:-1] |
| 571 | if category in _ERROR_CATEGORIES: |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 572 | _error_suppressions.setdefault(category, set()).add(suppressed_line) |
[email protected] | 255f2be | 2014-12-05 22:19:55 | [diff] [blame] | 573 | elif category not in _LEGACY_ERROR_CATEGORIES: |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 574 | error(filename, linenum, 'readability/nolint', 5, |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 575 | 'Unknown NOLINT error category: %s' % category) |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 576 | |
| 577 | |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 578 | def ProcessGlobalSuppresions(lines): |
| 579 | """Updates the list of global error suppressions. |
| 580 | |
| 581 | Parses any lint directives in the file that have global effect. |
| 582 | |
| 583 | Args: |
| 584 | lines: An array of strings, each representing a line of the file, with the |
| 585 | last element being empty if the file is terminated with a newline. |
| 586 | """ |
| 587 | for line in lines: |
| 588 | if _SEARCH_C_FILE.search(line): |
| 589 | for category in _DEFAULT_C_SUPPRESSED_CATEGORIES: |
| 590 | _global_error_suppressions[category] = True |
| 591 | if _SEARCH_KERNEL_FILE.search(line): |
| 592 | for category in _DEFAULT_KERNEL_SUPPRESSED_CATEGORIES: |
| 593 | _global_error_suppressions[category] = True |
| 594 | |
| 595 | |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 596 | def ResetNolintSuppressions(): |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 597 | """Resets the set of NOLINT suppressions to empty.""" |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 598 | _error_suppressions.clear() |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 599 | _global_error_suppressions.clear() |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 600 | |
| 601 | |
| 602 | def IsErrorSuppressedByNolint(category, linenum): |
| 603 | """Returns true if the specified error category is suppressed on this line. |
| 604 | |
| 605 | Consults the global error_suppressions map populated by |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 606 | ParseNolintSuppressions/ProcessGlobalSuppresions/ResetNolintSuppressions. |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 607 | |
| 608 | Args: |
| 609 | category: str, the category of the error. |
| 610 | linenum: int, the current line number. |
| 611 | Returns: |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 612 | bool, True iff the error should be suppressed due to a NOLINT comment or |
| 613 | global suppression. |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 614 | """ |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 615 | return (_global_error_suppressions.get(category, False) or |
| 616 | linenum in _error_suppressions.get(category, set()) or |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 617 | linenum in _error_suppressions.get(None, set())) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 618 | |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 619 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 620 | def Match(pattern, s): |
| 621 | """Matches the string with the pattern, caching the compiled regexp.""" |
| 622 | # The regexp compilation caching is inlined in both Match and Search for |
| 623 | # performance reasons; factoring it out into a separate function turns out |
| 624 | # to be noticeably expensive. |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 625 | if pattern not in _regexp_compile_cache: |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 626 | _regexp_compile_cache[pattern] = sre_compile.compile(pattern) |
| 627 | return _regexp_compile_cache[pattern].match(s) |
| 628 | |
| 629 | |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 630 | def ReplaceAll(pattern, rep, s): |
| 631 | """Replaces instances of pattern in a string with a replacement. |
| 632 | |
| 633 | The compiled regex is kept in a cache shared by Match and Search. |
| 634 | |
| 635 | Args: |
| 636 | pattern: regex pattern |
| 637 | rep: replacement text |
| 638 | s: search string |
| 639 | |
| 640 | Returns: |
| 641 | string with replacements made (or original string if no replacements) |
| 642 | """ |
| 643 | if pattern not in _regexp_compile_cache: |
| 644 | _regexp_compile_cache[pattern] = sre_compile.compile(pattern) |
| 645 | return _regexp_compile_cache[pattern].sub(rep, s) |
| 646 | |
| 647 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 648 | def Search(pattern, s): |
| 649 | """Searches the string for the pattern, caching the compiled regexp.""" |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 650 | if pattern not in _regexp_compile_cache: |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 651 | _regexp_compile_cache[pattern] = sre_compile.compile(pattern) |
| 652 | return _regexp_compile_cache[pattern].search(s) |
| 653 | |
| 654 | |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 655 | def _IsSourceExtension(s): |
| 656 | """File extension (excluding dot) matches a source file extension.""" |
| 657 | return s in ('c', 'cc', 'cpp', 'cxx') |
| 658 | |
| 659 | |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 660 | class _IncludeState(object): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 661 | """Tracks line numbers for includes, and the order in which includes appear. |
| 662 | |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 663 | include_list contains list of lists of (header, line number) pairs. |
| 664 | It's a lists of lists rather than just one flat list to make it |
| 665 | easier to update across preprocessor boundaries. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 666 | |
| 667 | Call CheckNextIncludeOrder() once for each header in the file, passing |
| 668 | in the type constants defined above. Calls in an illegal order will |
| 669 | raise an _IncludeError with an appropriate error message. |
| 670 | |
| 671 | """ |
| 672 | # self._section will move monotonically through this set. If it ever |
| 673 | # needs to move backwards, CheckNextIncludeOrder will raise an error. |
| 674 | _INITIAL_SECTION = 0 |
| 675 | _MY_H_SECTION = 1 |
| 676 | _C_SECTION = 2 |
| 677 | _CPP_SECTION = 3 |
| 678 | _OTHER_H_SECTION = 4 |
| 679 | |
| 680 | _TYPE_NAMES = { |
| 681 | _C_SYS_HEADER: 'C system header', |
| 682 | _CPP_SYS_HEADER: 'C++ system header', |
| 683 | _LIKELY_MY_HEADER: 'header this file implements', |
| 684 | _POSSIBLE_MY_HEADER: 'header this file may implement', |
| 685 | _OTHER_HEADER: 'other header', |
| 686 | } |
| 687 | _SECTION_NAMES = { |
| 688 | _INITIAL_SECTION: "... nothing. (This can't be an error.)", |
| 689 | _MY_H_SECTION: 'a header this file implements', |
| 690 | _C_SECTION: 'C system header', |
| 691 | _CPP_SECTION: 'C++ system header', |
| 692 | _OTHER_H_SECTION: 'other header', |
| 693 | } |
| 694 | |
| 695 | def __init__(self): |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 696 | self.include_list = [[]] |
| 697 | self.ResetSection('') |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 698 | |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 699 | def FindHeader(self, header): |
| 700 | """Check if a header has already been included. |
| 701 | |
| 702 | Args: |
| 703 | header: header to check. |
| 704 | Returns: |
| 705 | Line number of previous occurrence, or -1 if the header has not |
| 706 | been seen before. |
| 707 | """ |
| 708 | for section_list in self.include_list: |
| 709 | for f in section_list: |
| 710 | if f[0] == header: |
| 711 | return f[1] |
| 712 | return -1 |
| 713 | |
| 714 | def ResetSection(self, directive): |
| 715 | """Reset section checking for preprocessor directive. |
| 716 | |
| 717 | Args: |
| 718 | directive: preprocessor directive (e.g. "if", "else"). |
| 719 | """ |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 720 | # The name of the current section. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 721 | self._section = self._INITIAL_SECTION |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 722 | # The path of last found header. |
| 723 | self._last_header = '' |
| 724 | |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 725 | # Update list of includes. Note that we never pop from the |
| 726 | # include list. |
| 727 | if directive in ('if', 'ifdef', 'ifndef'): |
| 728 | self.include_list.append([]) |
| 729 | elif directive in ('else', 'elif'): |
| 730 | self.include_list[-1] = [] |
| 731 | |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 732 | def SetLastHeader(self, header_path): |
| 733 | self._last_header = header_path |
| 734 | |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 735 | def CanonicalizeAlphabeticalOrder(self, header_path): |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 736 | """Returns a path canonicalized for alphabetical comparison. |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 737 | |
| 738 | - replaces "-" with "_" so they both cmp the same. |
| 739 | - removes '-inl' since we don't require them to be after the main header. |
| 740 | - lowercase everything, just in case. |
| 741 | |
| 742 | Args: |
| 743 | header_path: Path to be canonicalized. |
| 744 | |
| 745 | Returns: |
| 746 | Canonicalized path. |
| 747 | """ |
| 748 | return header_path.replace('-inl.h', '.h').replace('-', '_').lower() |
| 749 | |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 750 | def IsInAlphabeticalOrder(self, clean_lines, linenum, header_path): |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 751 | """Check if a header is in alphabetical order with the previous header. |
| 752 | |
| 753 | Args: |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 754 | clean_lines: A CleansedLines instance containing the file. |
| 755 | linenum: The number of the line to check. |
| 756 | header_path: Canonicalized header to be checked. |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 757 | |
| 758 | Returns: |
| 759 | Returns true if the header is in alphabetical order. |
| 760 | """ |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 761 | # If previous section is different from current section, _last_header will |
| 762 | # be reset to empty string, so it's always less than current header. |
| 763 | # |
| 764 | # If previous line was a blank line, assume that the headers are |
| 765 | # intentionally sorted the way they are. |
| 766 | if (self._last_header > header_path and |
[email protected] | 255f2be | 2014-12-05 22:19:55 | [diff] [blame] | 767 | Match(r'^\s*#\s*include\b', clean_lines.elided[linenum - 1])): |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 768 | return False |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 769 | return True |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 770 | |
| 771 | def CheckNextIncludeOrder(self, header_type): |
| 772 | """Returns a non-empty error message if the next header is out of order. |
| 773 | |
| 774 | This function also updates the internal state to be ready to check |
| 775 | the next include. |
| 776 | |
| 777 | Args: |
| 778 | header_type: One of the _XXX_HEADER constants defined above. |
| 779 | |
| 780 | Returns: |
| 781 | The empty string if the header is in the right order, or an |
| 782 | error message describing what's wrong. |
| 783 | |
| 784 | """ |
| 785 | error_message = ('Found %s after %s' % |
| 786 | (self._TYPE_NAMES[header_type], |
| 787 | self._SECTION_NAMES[self._section])) |
| 788 | |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 789 | last_section = self._section |
| 790 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 791 | if header_type == _C_SYS_HEADER: |
| 792 | if self._section <= self._C_SECTION: |
| 793 | self._section = self._C_SECTION |
| 794 | else: |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 795 | self._last_header = '' |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 796 | return error_message |
| 797 | elif header_type == _CPP_SYS_HEADER: |
| 798 | if self._section <= self._CPP_SECTION: |
| 799 | self._section = self._CPP_SECTION |
| 800 | else: |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 801 | self._last_header = '' |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 802 | return error_message |
| 803 | elif header_type == _LIKELY_MY_HEADER: |
| 804 | if self._section <= self._MY_H_SECTION: |
| 805 | self._section = self._MY_H_SECTION |
| 806 | else: |
| 807 | self._section = self._OTHER_H_SECTION |
| 808 | elif header_type == _POSSIBLE_MY_HEADER: |
| 809 | if self._section <= self._MY_H_SECTION: |
| 810 | self._section = self._MY_H_SECTION |
| 811 | else: |
| 812 | # This will always be the fallback because we're not sure |
| 813 | # enough that the header is associated with this file. |
| 814 | self._section = self._OTHER_H_SECTION |
| 815 | else: |
| 816 | assert header_type == _OTHER_HEADER |
| 817 | self._section = self._OTHER_H_SECTION |
| 818 | |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 819 | if last_section != self._section: |
| 820 | self._last_header = '' |
| 821 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 822 | return '' |
| 823 | |
| 824 | |
| 825 | class _CppLintState(object): |
| 826 | """Maintains module-wide state..""" |
| 827 | |
| 828 | def __init__(self): |
| 829 | self.verbose_level = 1 # global setting. |
| 830 | self.error_count = 0 # global count of reported errors |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 831 | # filters to apply when emitting error messages |
| 832 | self.filters = _DEFAULT_FILTERS[:] |
[email protected] | 1744993 | 2014-07-28 22:13:33 | [diff] [blame] | 833 | # backup of filter list. Used to restore the state after each file. |
| 834 | self._filters_backup = self.filters[:] |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 835 | self.counting = 'total' # In what way are we counting errors? |
| 836 | self.errors_by_category = {} # string to int dict storing error counts |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 837 | |
| 838 | # output format: |
| 839 | # "emacs" - format that emacs can parse (default) |
| 840 | # "vs7" - format that Microsoft Visual Studio 7 can parse |
| 841 | self.output_format = 'emacs' |
| 842 | |
| 843 | def SetOutputFormat(self, output_format): |
| 844 | """Sets the output format for errors.""" |
| 845 | self.output_format = output_format |
| 846 | |
| 847 | def SetVerboseLevel(self, level): |
| 848 | """Sets the module's verbosity, and returns the previous setting.""" |
| 849 | last_verbose_level = self.verbose_level |
| 850 | self.verbose_level = level |
| 851 | return last_verbose_level |
| 852 | |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 853 | def SetCountingStyle(self, counting_style): |
| 854 | """Sets the module's counting options.""" |
| 855 | self.counting = counting_style |
| 856 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 857 | def SetFilters(self, filters): |
| 858 | """Sets the error-message filters. |
| 859 | |
| 860 | These filters are applied when deciding whether to emit a given |
| 861 | error message. |
| 862 | |
| 863 | Args: |
| 864 | filters: A string of comma-separated filters (eg "+whitespace/indent"). |
| 865 | Each filter should start with + or -; else we die. |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 866 | |
| 867 | Raises: |
| 868 | ValueError: The comma-separated filters did not all start with '+' or '-'. |
| 869 | E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter" |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 870 | """ |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 871 | # Default filters always have less priority than the flag ones. |
| 872 | self.filters = _DEFAULT_FILTERS[:] |
[email protected] | 1744993 | 2014-07-28 22:13:33 | [diff] [blame] | 873 | self.AddFilters(filters) |
| 874 | |
| 875 | def AddFilters(self, filters): |
| 876 | """ Adds more filters to the existing list of error-message filters. """ |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 877 | for filt in filters.split(','): |
| 878 | clean_filt = filt.strip() |
| 879 | if clean_filt: |
| 880 | self.filters.append(clean_filt) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 881 | for filt in self.filters: |
| 882 | if not (filt.startswith('+') or filt.startswith('-')): |
| 883 | raise ValueError('Every filter in --filters must start with + or -' |
| 884 | ' (%s does not)' % filt) |
| 885 | |
[email protected] | 1744993 | 2014-07-28 22:13:33 | [diff] [blame] | 886 | def BackupFilters(self): |
| 887 | """ Saves the current filter list to backup storage.""" |
| 888 | self._filters_backup = self.filters[:] |
| 889 | |
| 890 | def RestoreFilters(self): |
| 891 | """ Restores filters previously backed up.""" |
| 892 | self.filters = self._filters_backup[:] |
| 893 | |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 894 | def ResetErrorCounts(self): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 895 | """Sets the module's error statistic back to zero.""" |
| 896 | self.error_count = 0 |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 897 | self.errors_by_category = {} |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 898 | |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 899 | def IncrementErrorCount(self, category): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 900 | """Bumps the module's error statistic.""" |
| 901 | self.error_count += 1 |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 902 | if self.counting in ('toplevel', 'detailed'): |
| 903 | if self.counting != 'detailed': |
| 904 | category = category.split('/')[0] |
| 905 | if category not in self.errors_by_category: |
| 906 | self.errors_by_category[category] = 0 |
| 907 | self.errors_by_category[category] += 1 |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 908 | |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 909 | def PrintErrorCounts(self): |
| 910 | """Print a summary of errors by category, and the total.""" |
| 911 | for category, count in self.errors_by_category.iteritems(): |
| 912 | sys.stderr.write('Category \'%s\' errors found: %d\n' % |
| 913 | (category, count)) |
| 914 | sys.stderr.write('Total errors found: %d\n' % self.error_count) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 915 | |
| 916 | _cpplint_state = _CppLintState() |
| 917 | |
| 918 | |
| 919 | def _OutputFormat(): |
| 920 | """Gets the module's output format.""" |
| 921 | return _cpplint_state.output_format |
| 922 | |
| 923 | |
| 924 | def _SetOutputFormat(output_format): |
| 925 | """Sets the module's output format.""" |
| 926 | _cpplint_state.SetOutputFormat(output_format) |
| 927 | |
| 928 | |
| 929 | def _VerboseLevel(): |
| 930 | """Returns the module's verbosity setting.""" |
| 931 | return _cpplint_state.verbose_level |
| 932 | |
| 933 | |
| 934 | def _SetVerboseLevel(level): |
| 935 | """Sets the module's verbosity, and returns the previous setting.""" |
| 936 | return _cpplint_state.SetVerboseLevel(level) |
| 937 | |
| 938 | |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 939 | def _SetCountingStyle(level): |
| 940 | """Sets the module's counting options.""" |
| 941 | _cpplint_state.SetCountingStyle(level) |
| 942 | |
| 943 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 944 | def _Filters(): |
| 945 | """Returns the module's list of output filters, as a list.""" |
| 946 | return _cpplint_state.filters |
| 947 | |
| 948 | |
| 949 | def _SetFilters(filters): |
| 950 | """Sets the module's error-message filters. |
| 951 | |
| 952 | These filters are applied when deciding whether to emit a given |
| 953 | error message. |
| 954 | |
| 955 | Args: |
| 956 | filters: A string of comma-separated filters (eg "whitespace/indent"). |
| 957 | Each filter should start with + or -; else we die. |
| 958 | """ |
| 959 | _cpplint_state.SetFilters(filters) |
| 960 | |
[email protected] | 1744993 | 2014-07-28 22:13:33 | [diff] [blame] | 961 | def _AddFilters(filters): |
| 962 | """Adds more filter overrides. |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 963 | |
[email protected] | 1744993 | 2014-07-28 22:13:33 | [diff] [blame] | 964 | Unlike _SetFilters, this function does not reset the current list of filters |
| 965 | available. |
| 966 | |
| 967 | Args: |
| 968 | filters: A string of comma-separated filters (eg "whitespace/indent"). |
| 969 | Each filter should start with + or -; else we die. |
| 970 | """ |
| 971 | _cpplint_state.AddFilters(filters) |
| 972 | |
| 973 | def _BackupFilters(): |
| 974 | """ Saves the current filter list to backup storage.""" |
| 975 | _cpplint_state.BackupFilters() |
| 976 | |
| 977 | def _RestoreFilters(): |
| 978 | """ Restores filters previously backed up.""" |
| 979 | _cpplint_state.RestoreFilters() |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 980 | |
| 981 | class _FunctionState(object): |
| 982 | """Tracks current function name and the number of lines in its body.""" |
| 983 | |
| 984 | _NORMAL_TRIGGER = 250 # for --v=0, 500 for --v=1, etc. |
| 985 | _TEST_TRIGGER = 400 # about 50% more than _NORMAL_TRIGGER. |
| 986 | |
| 987 | def __init__(self): |
| 988 | self.in_a_function = False |
| 989 | self.lines_in_function = 0 |
| 990 | self.current_function = '' |
| 991 | |
| 992 | def Begin(self, function_name): |
| 993 | """Start analyzing function body. |
| 994 | |
| 995 | Args: |
| 996 | function_name: The name of the function being tracked. |
| 997 | """ |
| 998 | self.in_a_function = True |
| 999 | self.lines_in_function = 0 |
| 1000 | self.current_function = function_name |
| 1001 | |
| 1002 | def Count(self): |
| 1003 | """Count line in current function body.""" |
| 1004 | if self.in_a_function: |
| 1005 | self.lines_in_function += 1 |
| 1006 | |
| 1007 | def Check(self, error, filename, linenum): |
| 1008 | """Report if too many lines in function body. |
| 1009 | |
| 1010 | Args: |
| 1011 | error: The function to call with any errors found. |
| 1012 | filename: The name of the current file. |
| 1013 | linenum: The number of the line to check. |
| 1014 | """ |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 1015 | if not self.in_a_function: |
| 1016 | return |
| 1017 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1018 | if Match(r'T(EST|est)', self.current_function): |
| 1019 | base_trigger = self._TEST_TRIGGER |
| 1020 | else: |
| 1021 | base_trigger = self._NORMAL_TRIGGER |
| 1022 | trigger = base_trigger * 2**_VerboseLevel() |
| 1023 | |
| 1024 | if self.lines_in_function > trigger: |
| 1025 | error_level = int(math.log(self.lines_in_function / base_trigger, 2)) |
| 1026 | # 50 => 0, 100 => 1, 200 => 2, 400 => 3, 800 => 4, 1600 => 5, ... |
| 1027 | if error_level > 5: |
| 1028 | error_level = 5 |
| 1029 | error(filename, linenum, 'readability/fn_size', error_level, |
| 1030 | 'Small and focused functions are preferred:' |
| 1031 | ' %s has %d non-comment lines' |
| 1032 | ' (error triggered by exceeding %d lines).' % ( |
| 1033 | self.current_function, self.lines_in_function, trigger)) |
| 1034 | |
| 1035 | def End(self): |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 1036 | """Stop analyzing function body.""" |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1037 | self.in_a_function = False |
| 1038 | |
| 1039 | |
| 1040 | class _IncludeError(Exception): |
| 1041 | """Indicates a problem with the include order in a file.""" |
| 1042 | pass |
| 1043 | |
| 1044 | |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 1045 | class FileInfo(object): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1046 | """Provides utility functions for filenames. |
| 1047 | |
| 1048 | FileInfo provides easy access to the components of a file's path |
| 1049 | relative to the project root. |
| 1050 | """ |
| 1051 | |
| 1052 | def __init__(self, filename): |
| 1053 | self._filename = filename |
| 1054 | |
| 1055 | def FullName(self): |
| 1056 | """Make Windows paths like Unix.""" |
| 1057 | return os.path.abspath(self._filename).replace('\\', '/') |
| 1058 | |
| 1059 | def RepositoryName(self): |
| 1060 | """FullName after removing the local path to the repository. |
| 1061 | |
| 1062 | If we have a real absolute path name here we can try to do something smart: |
| 1063 | detecting the root of the checkout and truncating /path/to/checkout from |
| 1064 | the name so that we get header guards that don't include things like |
| 1065 | "C:\Documents and Settings\..." or "/home/username/..." in them and thus |
| 1066 | people on different computers who have checked the source out to different |
| 1067 | locations won't see bogus errors. |
| 1068 | """ |
| 1069 | fullname = self.FullName() |
| 1070 | |
| 1071 | if os.path.exists(fullname): |
| 1072 | project_dir = os.path.dirname(fullname) |
| 1073 | |
sdefresne | 263e928 | 2016-07-19 09:14:22 | [diff] [blame] | 1074 | if _project_root: |
| 1075 | prefix = os.path.commonprefix([_project_root, project_dir]) |
| 1076 | return fullname[len(prefix) + 1:] |
| 1077 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1078 | if os.path.exists(os.path.join(project_dir, ".svn")): |
| 1079 | # If there's a .svn file in the current directory, we recursively look |
| 1080 | # up the directory tree for the top of the SVN checkout |
| 1081 | root_dir = project_dir |
| 1082 | one_up_dir = os.path.dirname(root_dir) |
| 1083 | while os.path.exists(os.path.join(one_up_dir, ".svn")): |
| 1084 | root_dir = os.path.dirname(root_dir) |
| 1085 | one_up_dir = os.path.dirname(one_up_dir) |
| 1086 | |
| 1087 | prefix = os.path.commonprefix([root_dir, project_dir]) |
| 1088 | return fullname[len(prefix) + 1:] |
| 1089 | |
[email protected] | 7956a87 | 2011-11-30 01:44:03 | [diff] [blame] | 1090 | # Not SVN <= 1.6? Try to find a git, hg, or svn top level directory by |
| 1091 | # searching up from the current path. |
[email protected] | 95a5ad8 | 2016-04-22 19:29:18 | [diff] [blame] | 1092 | root_dir = os.path.dirname(fullname) |
| 1093 | while (root_dir != os.path.dirname(root_dir) and |
| 1094 | not os.path.exists(os.path.join(root_dir, ".git")) and |
| 1095 | not os.path.exists(os.path.join(root_dir, ".hg")) and |
| 1096 | not os.path.exists(os.path.join(root_dir, ".svn"))): |
| 1097 | root_dir = os.path.dirname(root_dir) |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 1098 | |
| 1099 | if (os.path.exists(os.path.join(root_dir, ".git")) or |
[email protected] | 7956a87 | 2011-11-30 01:44:03 | [diff] [blame] | 1100 | os.path.exists(os.path.join(root_dir, ".hg")) or |
| 1101 | os.path.exists(os.path.join(root_dir, ".svn"))): |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 1102 | prefix = os.path.commonprefix([root_dir, project_dir]) |
| 1103 | return fullname[len(prefix) + 1:] |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1104 | |
| 1105 | # Don't know what to do; header guard warnings may be wrong... |
| 1106 | return fullname |
| 1107 | |
| 1108 | def Split(self): |
| 1109 | """Splits the file into the directory, basename, and extension. |
| 1110 | |
| 1111 | For 'chrome/browser/browser.cc', Split() would |
| 1112 | return ('chrome/browser', 'browser', '.cc') |
| 1113 | |
| 1114 | Returns: |
| 1115 | A tuple of (directory, basename, extension). |
| 1116 | """ |
| 1117 | |
| 1118 | googlename = self.RepositoryName() |
| 1119 | project, rest = os.path.split(googlename) |
| 1120 | return (project,) + os.path.splitext(rest) |
| 1121 | |
| 1122 | def BaseName(self): |
| 1123 | """File base name - text after the final slash, before the final period.""" |
| 1124 | return self.Split()[1] |
| 1125 | |
| 1126 | def Extension(self): |
| 1127 | """File extension - text following the final period.""" |
| 1128 | return self.Split()[2] |
| 1129 | |
| 1130 | def NoExtension(self): |
| 1131 | """File has no source file extension.""" |
| 1132 | return '/'.join(self.Split()[0:2]) |
| 1133 | |
| 1134 | def IsSource(self): |
| 1135 | """File has a source file extension.""" |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 1136 | return _IsSourceExtension(self.Extension()[1:]) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1137 | |
| 1138 | |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 1139 | def _ShouldPrintError(category, confidence, linenum): |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 1140 | """If confidence >= verbose, category passes filter and is not suppressed.""" |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 1141 | |
| 1142 | # There are three ways we might decide not to print an error message: |
| 1143 | # a "NOLINT(category)" comment appears in the source, |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1144 | # the verbosity level isn't high enough, or the filters filter it out. |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 1145 | if IsErrorSuppressedByNolint(category, linenum): |
| 1146 | return False |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 1147 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1148 | if confidence < _cpplint_state.verbose_level: |
| 1149 | return False |
| 1150 | |
| 1151 | is_filtered = False |
| 1152 | for one_filter in _Filters(): |
| 1153 | if one_filter.startswith('-'): |
| 1154 | if category.startswith(one_filter[1:]): |
| 1155 | is_filtered = True |
| 1156 | elif one_filter.startswith('+'): |
| 1157 | if category.startswith(one_filter[1:]): |
| 1158 | is_filtered = False |
| 1159 | else: |
| 1160 | assert False # should have been checked for in SetFilter. |
| 1161 | if is_filtered: |
| 1162 | return False |
| 1163 | |
| 1164 | return True |
| 1165 | |
| 1166 | |
| 1167 | def Error(filename, linenum, category, confidence, message): |
| 1168 | """Logs the fact we've found a lint error. |
| 1169 | |
| 1170 | We log where the error was found, and also our confidence in the error, |
| 1171 | that is, how certain we are this is a legitimate style regression, and |
| 1172 | not a misidentification or a use that's sometimes justified. |
| 1173 | |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 1174 | False positives can be suppressed by the use of |
| 1175 | "cpplint(category)" comments on the offending line. These are |
| 1176 | parsed into _error_suppressions. |
| 1177 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1178 | Args: |
| 1179 | filename: The name of the file containing the error. |
| 1180 | linenum: The number of the line containing the error. |
| 1181 | category: A string used to describe the "category" this bug |
| 1182 | falls under: "whitespace", say, or "runtime". Categories |
| 1183 | may have a hierarchy separated by slashes: "whitespace/indent". |
| 1184 | confidence: A number from 1-5 representing a confidence score for |
| 1185 | the error, with 5 meaning that we are certain of the problem, |
| 1186 | and 1 meaning that it could be a legitimate construct. |
| 1187 | message: The error message. |
| 1188 | """ |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 1189 | if _ShouldPrintError(category, confidence, linenum): |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 1190 | _cpplint_state.IncrementErrorCount(category) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1191 | if _cpplint_state.output_format == 'vs7': |
| 1192 | sys.stderr.write('%s(%s): %s [%s] [%d]\n' % ( |
| 1193 | filename, linenum, message, category, confidence)) |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 1194 | elif _cpplint_state.output_format == 'eclipse': |
| 1195 | sys.stderr.write('%s:%s: warning: %s [%s] [%d]\n' % ( |
| 1196 | filename, linenum, message, category, confidence)) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1197 | else: |
| 1198 | sys.stderr.write('%s:%s: %s [%s] [%d]\n' % ( |
| 1199 | filename, linenum, message, category, confidence)) |
| 1200 | |
| 1201 | |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 1202 | # Matches standard C++ escape sequences per 2.13.2.3 of the C++ standard. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1203 | _RE_PATTERN_CLEANSE_LINE_ESCAPES = re.compile( |
| 1204 | r'\\([abfnrtv?"\\\']|\d+|x[0-9a-fA-F]+)') |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 1205 | # Match a single C style comment on the same line. |
| 1206 | _RE_PATTERN_C_COMMENTS = r'/\*(?:[^*]|\*(?!/))*\*/' |
| 1207 | # Matches multi-line C style comments. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1208 | # This RE is a little bit more complicated than one might expect, because we |
| 1209 | # have to take care of space removals tools so we can handle comments inside |
| 1210 | # statements better. |
| 1211 | # The current rule is: We only clear spaces from both sides when we're at the |
| 1212 | # end of the line. Otherwise, we try to remove spaces from the right side, |
| 1213 | # if this doesn't work we try on left side but only if there's a non-character |
| 1214 | # on the right. |
| 1215 | _RE_PATTERN_CLEANSE_LINE_C_COMMENTS = re.compile( |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 1216 | r'(\s*' + _RE_PATTERN_C_COMMENTS + r'\s*$|' + |
| 1217 | _RE_PATTERN_C_COMMENTS + r'\s+|' + |
| 1218 | r'\s+' + _RE_PATTERN_C_COMMENTS + r'(?=\W)|' + |
| 1219 | _RE_PATTERN_C_COMMENTS + r')') |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1220 | |
| 1221 | |
| 1222 | def IsCppString(line): |
| 1223 | """Does line terminate so, that the next symbol is in string constant. |
| 1224 | |
| 1225 | This function does not consider single-line nor multi-line comments. |
| 1226 | |
| 1227 | Args: |
| 1228 | line: is a partial line of code starting from the 0..n. |
| 1229 | |
| 1230 | Returns: |
| 1231 | True, if next character appended to 'line' is inside a |
| 1232 | string constant. |
| 1233 | """ |
| 1234 | |
| 1235 | line = line.replace(r'\\', 'XX') # after this, \\" does not match to \" |
| 1236 | return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1 |
| 1237 | |
| 1238 | |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 1239 | def CleanseRawStrings(raw_lines): |
| 1240 | """Removes C++11 raw strings from lines. |
| 1241 | |
| 1242 | Before: |
| 1243 | static const char kData[] = R"( |
| 1244 | multi-line string |
| 1245 | )"; |
| 1246 | |
| 1247 | After: |
| 1248 | static const char kData[] = "" |
| 1249 | (replaced by blank line) |
| 1250 | ""; |
| 1251 | |
| 1252 | Args: |
| 1253 | raw_lines: list of raw lines. |
| 1254 | |
| 1255 | Returns: |
| 1256 | list of lines with C++11 raw strings replaced by empty strings. |
| 1257 | """ |
| 1258 | |
| 1259 | delimiter = None |
| 1260 | lines_without_raw_strings = [] |
| 1261 | for line in raw_lines: |
| 1262 | if delimiter: |
| 1263 | # Inside a raw string, look for the end |
| 1264 | end = line.find(delimiter) |
| 1265 | if end >= 0: |
| 1266 | # Found the end of the string, match leading space for this |
| 1267 | # line and resume copying the original lines, and also insert |
| 1268 | # a "" on the last line. |
| 1269 | leading_space = Match(r'^(\s*)\S', line) |
| 1270 | line = leading_space.group(1) + '""' + line[end + len(delimiter):] |
| 1271 | delimiter = None |
| 1272 | else: |
| 1273 | # Haven't found the end yet, append a blank line. |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 1274 | line = '""' |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 1275 | |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 1276 | # Look for beginning of a raw string, and replace them with |
| 1277 | # empty strings. This is done in a loop to handle multiple raw |
| 1278 | # strings on the same line. |
| 1279 | while delimiter is None: |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 1280 | # Look for beginning of a raw string. |
| 1281 | # See 2.14.15 [lex.string] for syntax. |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 1282 | # |
| 1283 | # Once we have matched a raw string, we check the prefix of the |
| 1284 | # line to make sure that the line is not part of a single line |
| 1285 | # comment. It's done this way because we remove raw strings |
| 1286 | # before removing comments as opposed to removing comments |
| 1287 | # before removing raw strings. This is because there are some |
| 1288 | # cpplint checks that requires the comments to be preserved, but |
| 1289 | # we don't want to check comments that are inside raw strings. |
| 1290 | matched = Match(r'^(.*?)\b(?:R|u8R|uR|UR|LR)"([^\s\\()]*)\((.*)$', line) |
| 1291 | if (matched and |
| 1292 | not Match(r'^([^\'"]|\'(\\.|[^\'])*\'|"(\\.|[^"])*")*//', |
| 1293 | matched.group(1))): |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 1294 | delimiter = ')' + matched.group(2) + '"' |
| 1295 | |
| 1296 | end = matched.group(3).find(delimiter) |
| 1297 | if end >= 0: |
| 1298 | # Raw string ended on same line |
| 1299 | line = (matched.group(1) + '""' + |
| 1300 | matched.group(3)[end + len(delimiter):]) |
| 1301 | delimiter = None |
| 1302 | else: |
| 1303 | # Start of a multi-line raw string |
| 1304 | line = matched.group(1) + '""' |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 1305 | else: |
| 1306 | break |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 1307 | |
| 1308 | lines_without_raw_strings.append(line) |
| 1309 | |
| 1310 | # TODO(unknown): if delimiter is not None here, we might want to |
| 1311 | # emit a warning for unterminated string. |
| 1312 | return lines_without_raw_strings |
| 1313 | |
| 1314 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1315 | def FindNextMultiLineCommentStart(lines, lineix): |
| 1316 | """Find the beginning marker for a multiline comment.""" |
| 1317 | while lineix < len(lines): |
| 1318 | if lines[lineix].strip().startswith('/*'): |
| 1319 | # Only return this marker if the comment goes beyond this line |
| 1320 | if lines[lineix].strip().find('*/', 2) < 0: |
| 1321 | return lineix |
| 1322 | lineix += 1 |
| 1323 | return len(lines) |
| 1324 | |
| 1325 | |
| 1326 | def FindNextMultiLineCommentEnd(lines, lineix): |
| 1327 | """We are inside a comment, find the end marker.""" |
| 1328 | while lineix < len(lines): |
| 1329 | if lines[lineix].strip().endswith('*/'): |
| 1330 | return lineix |
| 1331 | lineix += 1 |
| 1332 | return len(lines) |
| 1333 | |
| 1334 | |
| 1335 | def RemoveMultiLineCommentsFromRange(lines, begin, end): |
| 1336 | """Clears a range of lines for multi-line comments.""" |
| 1337 | # Having // dummy comments makes the lines non-empty, so we will not get |
| 1338 | # unnecessary blank line warnings later in the code. |
| 1339 | for i in range(begin, end): |
[email protected] | 255f2be | 2014-12-05 22:19:55 | [diff] [blame] | 1340 | lines[i] = '/**/' |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1341 | |
| 1342 | |
| 1343 | def RemoveMultiLineComments(filename, lines, error): |
| 1344 | """Removes multiline (c-style) comments from lines.""" |
| 1345 | lineix = 0 |
| 1346 | while lineix < len(lines): |
| 1347 | lineix_begin = FindNextMultiLineCommentStart(lines, lineix) |
| 1348 | if lineix_begin >= len(lines): |
| 1349 | return |
| 1350 | lineix_end = FindNextMultiLineCommentEnd(lines, lineix_begin) |
| 1351 | if lineix_end >= len(lines): |
| 1352 | error(filename, lineix_begin + 1, 'readability/multiline_comment', 5, |
| 1353 | 'Could not find end of multi-line comment') |
| 1354 | return |
| 1355 | RemoveMultiLineCommentsFromRange(lines, lineix_begin, lineix_end + 1) |
| 1356 | lineix = lineix_end + 1 |
| 1357 | |
| 1358 | |
| 1359 | def CleanseComments(line): |
| 1360 | """Removes //-comments and single-line C-style /* */ comments. |
| 1361 | |
| 1362 | Args: |
| 1363 | line: A line of C++ source. |
| 1364 | |
| 1365 | Returns: |
| 1366 | The line with single-line comments removed. |
| 1367 | """ |
| 1368 | commentpos = line.find('//') |
| 1369 | if commentpos != -1 and not IsCppString(line[:commentpos]): |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 1370 | line = line[:commentpos].rstrip() |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1371 | # get rid of /* ... */ |
| 1372 | return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line) |
| 1373 | |
| 1374 | |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 1375 | class CleansedLines(object): |
[email protected] | 255f2be | 2014-12-05 22:19:55 | [diff] [blame] | 1376 | """Holds 4 copies of all lines with different preprocessing applied to them. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1377 | |
[email protected] | 255f2be | 2014-12-05 22:19:55 | [diff] [blame] | 1378 | 1) elided member contains lines without strings and comments. |
| 1379 | 2) lines member contains lines without comments. |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 1380 | 3) raw_lines member contains all the lines without processing. |
[email protected] | 255f2be | 2014-12-05 22:19:55 | [diff] [blame] | 1381 | 4) lines_without_raw_strings member is same as raw_lines, but with C++11 raw |
| 1382 | strings removed. |
| 1383 | All these members are of <type 'list'>, and of the same length. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1384 | """ |
| 1385 | |
| 1386 | def __init__(self, lines): |
| 1387 | self.elided = [] |
| 1388 | self.lines = [] |
| 1389 | self.raw_lines = lines |
| 1390 | self.num_lines = len(lines) |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 1391 | self.lines_without_raw_strings = CleanseRawStrings(lines) |
| 1392 | for linenum in range(len(self.lines_without_raw_strings)): |
| 1393 | self.lines.append(CleanseComments( |
| 1394 | self.lines_without_raw_strings[linenum])) |
| 1395 | elided = self._CollapseStrings(self.lines_without_raw_strings[linenum]) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1396 | self.elided.append(CleanseComments(elided)) |
| 1397 | |
| 1398 | def NumLines(self): |
| 1399 | """Returns the number of lines represented.""" |
| 1400 | return self.num_lines |
| 1401 | |
| 1402 | @staticmethod |
| 1403 | def _CollapseStrings(elided): |
| 1404 | """Collapses strings and chars on a line to simple "" or '' blocks. |
| 1405 | |
| 1406 | We nix strings first so we're not fooled by text like '"http://"' |
| 1407 | |
| 1408 | Args: |
| 1409 | elided: The line being processed. |
| 1410 | |
| 1411 | Returns: |
| 1412 | The line with collapsed strings. |
| 1413 | """ |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 1414 | if _RE_PATTERN_INCLUDE.match(elided): |
| 1415 | return elided |
| 1416 | |
| 1417 | # Remove escaped characters first to make quote/single quote collapsing |
| 1418 | # basic. Things that look like escaped characters shouldn't occur |
| 1419 | # outside of strings and chars. |
| 1420 | elided = _RE_PATTERN_CLEANSE_LINE_ESCAPES.sub('', elided) |
| 1421 | |
| 1422 | # Replace quoted strings and digit separators. Both single quotes |
| 1423 | # and double quotes are processed in the same loop, otherwise |
| 1424 | # nested quotes wouldn't work. |
| 1425 | collapsed = '' |
| 1426 | while True: |
| 1427 | # Find the first quote character |
| 1428 | match = Match(r'^([^\'"]*)([\'"])(.*)$', elided) |
| 1429 | if not match: |
| 1430 | collapsed += elided |
| 1431 | break |
| 1432 | head, quote, tail = match.groups() |
| 1433 | |
| 1434 | if quote == '"': |
| 1435 | # Collapse double quoted strings |
| 1436 | second_quote = tail.find('"') |
| 1437 | if second_quote >= 0: |
| 1438 | collapsed += head + '""' |
| 1439 | elided = tail[second_quote + 1:] |
| 1440 | else: |
| 1441 | # Unmatched double quote, don't bother processing the rest |
| 1442 | # of the line since this is probably a multiline string. |
| 1443 | collapsed += elided |
| 1444 | break |
| 1445 | else: |
| 1446 | # Found single quote, check nearby text to eliminate digit separators. |
| 1447 | # |
| 1448 | # There is no special handling for floating point here, because |
| 1449 | # the integer/fractional/exponent parts would all be parsed |
| 1450 | # correctly as long as there are digits on both sides of the |
| 1451 | # separator. So we are fine as long as we don't see something |
| 1452 | # like "0.'3" (gcc 4.9.0 will not allow this literal). |
| 1453 | if Search(r'\b(?:0[bBxX]?|[1-9])[0-9a-fA-F]*$', head): |
| 1454 | match_literal = Match(r'^((?:\'?[0-9a-zA-Z_])*)(.*)$', "'" + tail) |
| 1455 | collapsed += head + match_literal.group(1).replace("'", '') |
| 1456 | elided = match_literal.group(2) |
| 1457 | else: |
| 1458 | second_quote = tail.find('\'') |
| 1459 | if second_quote >= 0: |
| 1460 | collapsed += head + "''" |
| 1461 | elided = tail[second_quote + 1:] |
| 1462 | else: |
| 1463 | # Unmatched single quote |
| 1464 | collapsed += elided |
| 1465 | break |
| 1466 | |
| 1467 | return collapsed |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1468 | |
| 1469 | |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 1470 | def FindEndOfExpressionInLine(line, startpos, stack): |
| 1471 | """Find the position just after the end of current parenthesized expression. |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 1472 | |
| 1473 | Args: |
| 1474 | line: a CleansedLines line. |
| 1475 | startpos: start searching at this position. |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 1476 | stack: nesting stack at startpos. |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 1477 | |
| 1478 | Returns: |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 1479 | On finding matching end: (index just after matching end, None) |
| 1480 | On finding an unclosed expression: (-1, None) |
| 1481 | Otherwise: (-1, new stack at end of this line) |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 1482 | """ |
| 1483 | for i in xrange(startpos, len(line)): |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 1484 | char = line[i] |
| 1485 | if char in '([{': |
| 1486 | # Found start of parenthesized expression, push to expression stack |
| 1487 | stack.append(char) |
| 1488 | elif char == '<': |
| 1489 | # Found potential start of template argument list |
| 1490 | if i > 0 and line[i - 1] == '<': |
| 1491 | # Left shift operator |
| 1492 | if stack and stack[-1] == '<': |
| 1493 | stack.pop() |
| 1494 | if not stack: |
| 1495 | return (-1, None) |
| 1496 | elif i > 0 and Search(r'\boperator\s*$', line[0:i]): |
| 1497 | # operator<, don't add to stack |
| 1498 | continue |
| 1499 | else: |
| 1500 | # Tentative start of template argument list |
| 1501 | stack.append('<') |
| 1502 | elif char in ')]}': |
| 1503 | # Found end of parenthesized expression. |
| 1504 | # |
| 1505 | # If we are currently expecting a matching '>', the pending '<' |
| 1506 | # must have been an operator. Remove them from expression stack. |
| 1507 | while stack and stack[-1] == '<': |
| 1508 | stack.pop() |
| 1509 | if not stack: |
| 1510 | return (-1, None) |
| 1511 | if ((stack[-1] == '(' and char == ')') or |
| 1512 | (stack[-1] == '[' and char == ']') or |
| 1513 | (stack[-1] == '{' and char == '}')): |
| 1514 | stack.pop() |
| 1515 | if not stack: |
| 1516 | return (i + 1, None) |
| 1517 | else: |
| 1518 | # Mismatched parentheses |
| 1519 | return (-1, None) |
| 1520 | elif char == '>': |
| 1521 | # Found potential end of template argument list. |
| 1522 | |
| 1523 | # Ignore "->" and operator functions |
| 1524 | if (i > 0 and |
| 1525 | (line[i - 1] == '-' or Search(r'\boperator\s*$', line[0:i - 1]))): |
| 1526 | continue |
| 1527 | |
| 1528 | # Pop the stack if there is a matching '<'. Otherwise, ignore |
| 1529 | # this '>' since it must be an operator. |
| 1530 | if stack: |
| 1531 | if stack[-1] == '<': |
| 1532 | stack.pop() |
| 1533 | if not stack: |
| 1534 | return (i + 1, None) |
| 1535 | elif char == ';': |
| 1536 | # Found something that look like end of statements. If we are currently |
| 1537 | # expecting a '>', the matching '<' must have been an operator, since |
| 1538 | # template argument list should not contain statements. |
| 1539 | while stack and stack[-1] == '<': |
| 1540 | stack.pop() |
| 1541 | if not stack: |
| 1542 | return (-1, None) |
| 1543 | |
| 1544 | # Did not find end of expression or unbalanced parentheses on this line |
| 1545 | return (-1, stack) |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 1546 | |
| 1547 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1548 | def CloseExpression(clean_lines, linenum, pos): |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 1549 | """If input points to ( or { or [ or <, finds the position that closes it. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1550 | |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 1551 | If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1552 | linenum/pos that correspond to the closing of the expression. |
| 1553 | |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 1554 | TODO(unknown): cpplint spends a fair bit of time matching parentheses. |
| 1555 | Ideally we would want to index all opening and closing parentheses once |
| 1556 | and have CloseExpression be just a simple lookup, but due to preprocessor |
| 1557 | tricks, this is not so easy. |
| 1558 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1559 | Args: |
| 1560 | clean_lines: A CleansedLines instance containing the file. |
| 1561 | linenum: The number of the line to check. |
| 1562 | pos: A position on the line. |
| 1563 | |
| 1564 | Returns: |
| 1565 | A tuple (line, linenum, pos) pointer *past* the closing brace, or |
| 1566 | (line, len(lines), -1) if we never find a close. Note we ignore |
| 1567 | strings and comments when matching; and the line we return is the |
| 1568 | 'cleansed' line at linenum. |
| 1569 | """ |
| 1570 | |
| 1571 | line = clean_lines.elided[linenum] |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 1572 | if (line[pos] not in '({[<') or Match(r'<[<=]', line[pos:]): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1573 | return (line, clean_lines.NumLines(), -1) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1574 | |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 1575 | # Check first line |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 1576 | (end_pos, stack) = FindEndOfExpressionInLine(line, pos, []) |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 1577 | if end_pos > -1: |
| 1578 | return (line, linenum, end_pos) |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 1579 | |
| 1580 | # Continue scanning forward |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 1581 | while stack and linenum < clean_lines.NumLines() - 1: |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1582 | linenum += 1 |
| 1583 | line = clean_lines.elided[linenum] |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 1584 | (end_pos, stack) = FindEndOfExpressionInLine(line, 0, stack) |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 1585 | if end_pos > -1: |
| 1586 | return (line, linenum, end_pos) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1587 | |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 1588 | # Did not find end of expression before end of file, give up |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 1589 | return (line, clean_lines.NumLines(), -1) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1590 | |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 1591 | |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 1592 | def FindStartOfExpressionInLine(line, endpos, stack): |
| 1593 | """Find position at the matching start of current expression. |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 1594 | |
| 1595 | This is almost the reverse of FindEndOfExpressionInLine, but note |
| 1596 | that the input position and returned position differs by 1. |
| 1597 | |
| 1598 | Args: |
| 1599 | line: a CleansedLines line. |
| 1600 | endpos: start searching at this position. |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 1601 | stack: nesting stack at endpos. |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 1602 | |
| 1603 | Returns: |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 1604 | On finding matching start: (index at matching start, None) |
| 1605 | On finding an unclosed expression: (-1, None) |
| 1606 | Otherwise: (-1, new stack at beginning of this line) |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 1607 | """ |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 1608 | i = endpos |
| 1609 | while i >= 0: |
| 1610 | char = line[i] |
| 1611 | if char in ')]}': |
| 1612 | # Found end of expression, push to expression stack |
| 1613 | stack.append(char) |
| 1614 | elif char == '>': |
| 1615 | # Found potential end of template argument list. |
| 1616 | # |
| 1617 | # Ignore it if it's a "->" or ">=" or "operator>" |
| 1618 | if (i > 0 and |
| 1619 | (line[i - 1] == '-' or |
| 1620 | Match(r'\s>=\s', line[i - 1:]) or |
| 1621 | Search(r'\boperator\s*$', line[0:i]))): |
| 1622 | i -= 1 |
| 1623 | else: |
| 1624 | stack.append('>') |
| 1625 | elif char == '<': |
| 1626 | # Found potential start of template argument list |
| 1627 | if i > 0 and line[i - 1] == '<': |
| 1628 | # Left shift operator |
| 1629 | i -= 1 |
| 1630 | else: |
| 1631 | # If there is a matching '>', we can pop the expression stack. |
| 1632 | # Otherwise, ignore this '<' since it must be an operator. |
| 1633 | if stack and stack[-1] == '>': |
| 1634 | stack.pop() |
| 1635 | if not stack: |
| 1636 | return (i, None) |
| 1637 | elif char in '([{': |
| 1638 | # Found start of expression. |
| 1639 | # |
| 1640 | # If there are any unmatched '>' on the stack, they must be |
| 1641 | # operators. Remove those. |
| 1642 | while stack and stack[-1] == '>': |
| 1643 | stack.pop() |
| 1644 | if not stack: |
| 1645 | return (-1, None) |
| 1646 | if ((char == '(' and stack[-1] == ')') or |
| 1647 | (char == '[' and stack[-1] == ']') or |
| 1648 | (char == '{' and stack[-1] == '}')): |
| 1649 | stack.pop() |
| 1650 | if not stack: |
| 1651 | return (i, None) |
| 1652 | else: |
| 1653 | # Mismatched parentheses |
| 1654 | return (-1, None) |
| 1655 | elif char == ';': |
| 1656 | # Found something that look like end of statements. If we are currently |
| 1657 | # expecting a '<', the matching '>' must have been an operator, since |
| 1658 | # template argument list should not contain statements. |
| 1659 | while stack and stack[-1] == '>': |
| 1660 | stack.pop() |
| 1661 | if not stack: |
| 1662 | return (-1, None) |
| 1663 | |
| 1664 | i -= 1 |
| 1665 | |
| 1666 | return (-1, stack) |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 1667 | |
| 1668 | |
| 1669 | def ReverseCloseExpression(clean_lines, linenum, pos): |
| 1670 | """If input points to ) or } or ] or >, finds the position that opens it. |
| 1671 | |
| 1672 | If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the |
| 1673 | linenum/pos that correspond to the opening of the expression. |
| 1674 | |
| 1675 | Args: |
| 1676 | clean_lines: A CleansedLines instance containing the file. |
| 1677 | linenum: The number of the line to check. |
| 1678 | pos: A position on the line. |
| 1679 | |
| 1680 | Returns: |
| 1681 | A tuple (line, linenum, pos) pointer *at* the opening brace, or |
| 1682 | (line, 0, -1) if we never find the matching opening brace. Note |
| 1683 | we ignore strings and comments when matching; and the line we |
| 1684 | return is the 'cleansed' line at linenum. |
| 1685 | """ |
| 1686 | line = clean_lines.elided[linenum] |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 1687 | if line[pos] not in ')}]>': |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 1688 | return (line, 0, -1) |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 1689 | |
| 1690 | # Check last line |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 1691 | (start_pos, stack) = FindStartOfExpressionInLine(line, pos, []) |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 1692 | if start_pos > -1: |
| 1693 | return (line, linenum, start_pos) |
| 1694 | |
| 1695 | # Continue scanning backward |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 1696 | while stack and linenum > 0: |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 1697 | linenum -= 1 |
| 1698 | line = clean_lines.elided[linenum] |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 1699 | (start_pos, stack) = FindStartOfExpressionInLine(line, len(line) - 1, stack) |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 1700 | if start_pos > -1: |
| 1701 | return (line, linenum, start_pos) |
| 1702 | |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 1703 | # Did not find start of expression before beginning of file, give up |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 1704 | return (line, 0, -1) |
| 1705 | |
| 1706 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1707 | def CheckForCopyright(filename, lines, error): |
| 1708 | """Logs an error if no Copyright message appears at the top of the file.""" |
| 1709 | |
| 1710 | # We'll say it should occur by line 10. Don't forget there's a |
| 1711 | # dummy line at the front. |
| 1712 | for line in xrange(1, min(len(lines), 11)): |
| 1713 | if re.search(r'Copyright', lines[line], re.I): break |
| 1714 | else: # means no copyright line was found |
| 1715 | error(filename, 0, 'legal/copyright', 5, |
| 1716 | 'No copyright message found. ' |
| 1717 | 'You should have a line: "Copyright [year] <Copyright Owner>"') |
| 1718 | |
| 1719 | |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 1720 | def GetIndentLevel(line): |
| 1721 | """Return the number of leading spaces in line. |
| 1722 | |
| 1723 | Args: |
| 1724 | line: A string to check. |
| 1725 | |
| 1726 | Returns: |
| 1727 | An integer count of leading spaces, possibly zero. |
| 1728 | """ |
| 1729 | indent = Match(r'^( *)\S', line) |
| 1730 | if indent: |
| 1731 | return len(indent.group(1)) |
| 1732 | else: |
| 1733 | return 0 |
| 1734 | |
| 1735 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1736 | def GetHeaderGuardCPPVariable(filename): |
| 1737 | """Returns the CPP variable that should be used as a header guard. |
| 1738 | |
| 1739 | Args: |
| 1740 | filename: The name of a C++ header file. |
| 1741 | |
| 1742 | Returns: |
| 1743 | The CPP variable that should be used as a header guard in the |
| 1744 | named file. |
| 1745 | |
| 1746 | """ |
| 1747 | |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 1748 | # Restores original filename in case that cpplint is invoked from Emacs's |
| 1749 | # flymake. |
| 1750 | filename = re.sub(r'_flymake\.h$', '.h', filename) |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 1751 | filename = re.sub(r'/\.flymake/([^/]*)$', r'/\1', filename) |
[email protected] | 255f2be | 2014-12-05 22:19:55 | [diff] [blame] | 1752 | # Replace 'c++' with 'cpp'. |
| 1753 | filename = filename.replace('C++', 'cpp').replace('c++', 'cpp') |
[email protected] | 3990c41 | 2016-02-05 20:55:12 | [diff] [blame] | 1754 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1755 | fileinfo = FileInfo(filename) |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 1756 | file_path_from_root = fileinfo.RepositoryName() |
| 1757 | if _root: |
| 1758 | file_path_from_root = re.sub('^' + _root + os.sep, '', file_path_from_root) |
[email protected] | 255f2be | 2014-12-05 22:19:55 | [diff] [blame] | 1759 | return re.sub(r'[^a-zA-Z0-9]', '_', file_path_from_root).upper() + '_' |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1760 | |
| 1761 | |
[email protected] | 255f2be | 2014-12-05 22:19:55 | [diff] [blame] | 1762 | def CheckForHeaderGuard(filename, clean_lines, error): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1763 | """Checks that the file contains a header guard. |
| 1764 | |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 1765 | Logs an error if no #ifndef header guard is present. For other |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1766 | headers, checks that the full pathname is used. |
| 1767 | |
| 1768 | Args: |
| 1769 | filename: The name of the C++ header file. |
[email protected] | 255f2be | 2014-12-05 22:19:55 | [diff] [blame] | 1770 | clean_lines: A CleansedLines instance containing the file. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1771 | error: The function to call with any errors found. |
| 1772 | """ |
| 1773 | |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 1774 | # Don't check for header guards if there are error suppression |
| 1775 | # comments somewhere in this file. |
| 1776 | # |
| 1777 | # Because this is silencing a warning for a nonexistent line, we |
| 1778 | # only support the very specific NOLINT(build/header_guard) syntax, |
| 1779 | # and not the general NOLINT or NOLINT(*) syntax. |
[email protected] | 255f2be | 2014-12-05 22:19:55 | [diff] [blame] | 1780 | raw_lines = clean_lines.lines_without_raw_strings |
| 1781 | for i in raw_lines: |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 1782 | if Search(r'//\s*NOLINT\(build/header_guard\)', i): |
| 1783 | return |
| 1784 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1785 | cppvar = GetHeaderGuardCPPVariable(filename) |
| 1786 | |
[email protected] | 255f2be | 2014-12-05 22:19:55 | [diff] [blame] | 1787 | ifndef = '' |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1788 | ifndef_linenum = 0 |
[email protected] | 255f2be | 2014-12-05 22:19:55 | [diff] [blame] | 1789 | define = '' |
| 1790 | endif = '' |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1791 | endif_linenum = 0 |
[email protected] | 255f2be | 2014-12-05 22:19:55 | [diff] [blame] | 1792 | for linenum, line in enumerate(raw_lines): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1793 | linesplit = line.split() |
| 1794 | if len(linesplit) >= 2: |
| 1795 | # find the first occurrence of #ifndef and #define, save arg |
| 1796 | if not ifndef and linesplit[0] == '#ifndef': |
| 1797 | # set ifndef to the header guard presented on the #ifndef line. |
| 1798 | ifndef = linesplit[1] |
| 1799 | ifndef_linenum = linenum |
| 1800 | if not define and linesplit[0] == '#define': |
| 1801 | define = linesplit[1] |
| 1802 | # find the last occurrence of #endif, save entire line |
| 1803 | if line.startswith('#endif'): |
| 1804 | endif = line |
| 1805 | endif_linenum = linenum |
| 1806 | |
[email protected] | 255f2be | 2014-12-05 22:19:55 | [diff] [blame] | 1807 | if not ifndef or not define or ifndef != define: |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1808 | error(filename, 0, 'build/header_guard', 5, |
| 1809 | 'No #ifndef header guard found, suggested CPP variable is: %s' % |
| 1810 | cppvar) |
| 1811 | return |
| 1812 | |
| 1813 | # The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__ |
| 1814 | # for backward compatibility. |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 1815 | if ifndef != cppvar: |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1816 | error_level = 0 |
| 1817 | if ifndef != cppvar + '_': |
| 1818 | error_level = 5 |
| 1819 | |
[email protected] | 255f2be | 2014-12-05 22:19:55 | [diff] [blame] | 1820 | ParseNolintSuppressions(filename, raw_lines[ifndef_linenum], ifndef_linenum, |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 1821 | error) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1822 | error(filename, ifndef_linenum, 'build/header_guard', error_level, |
| 1823 | '#ifndef header guard has wrong style, please use: %s' % cppvar) |
| 1824 | |
[email protected] | 255f2be | 2014-12-05 22:19:55 | [diff] [blame] | 1825 | # Check for "//" comments on endif line. |
| 1826 | ParseNolintSuppressions(filename, raw_lines[endif_linenum], endif_linenum, |
| 1827 | error) |
| 1828 | match = Match(r'#endif\s*//\s*' + cppvar + r'(_)?\b', endif) |
| 1829 | if match: |
| 1830 | if match.group(1) == '_': |
| 1831 | # Issue low severity warning for deprecated double trailing underscore |
| 1832 | error(filename, endif_linenum, 'build/header_guard', 0, |
| 1833 | '#endif line should be "#endif // %s"' % cppvar) |
[email protected] | c452fea | 2012-01-26 21:10:45 | [diff] [blame] | 1834 | return |
| 1835 | |
[email protected] | 255f2be | 2014-12-05 22:19:55 | [diff] [blame] | 1836 | # Didn't find the corresponding "//" comment. If this file does not |
| 1837 | # contain any "//" comments at all, it could be that the compiler |
| 1838 | # only wants "/**/" comments, look for those instead. |
| 1839 | no_single_line_comments = True |
| 1840 | for i in xrange(1, len(raw_lines) - 1): |
| 1841 | line = raw_lines[i] |
| 1842 | if Match(r'^(?:(?:\'(?:\.|[^\'])*\')|(?:"(?:\.|[^"])*")|[^\'"])*//', line): |
| 1843 | no_single_line_comments = False |
| 1844 | break |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1845 | |
[email protected] | 255f2be | 2014-12-05 22:19:55 | [diff] [blame] | 1846 | if no_single_line_comments: |
| 1847 | match = Match(r'#endif\s*/\*\s*' + cppvar + r'(_)?\s*\*/', endif) |
| 1848 | if match: |
| 1849 | if match.group(1) == '_': |
| 1850 | # Low severity warning for double trailing underscore |
| 1851 | error(filename, endif_linenum, 'build/header_guard', 0, |
| 1852 | '#endif line should be "#endif /* %s */"' % cppvar) |
| 1853 | return |
| 1854 | |
| 1855 | # Didn't find anything |
| 1856 | error(filename, endif_linenum, 'build/header_guard', 5, |
| 1857 | '#endif line should be "#endif // %s"' % cppvar) |
| 1858 | |
| 1859 | |
| 1860 | def CheckHeaderFileIncluded(filename, include_state, error): |
| 1861 | """Logs an error if a .cc file does not include its header.""" |
| 1862 | |
| 1863 | # Do not check test files |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 1864 | fileinfo = FileInfo(filename) |
| 1865 | if Search(_TEST_FILE_SUFFIX, fileinfo.BaseName()): |
[email protected] | 255f2be | 2014-12-05 22:19:55 | [diff] [blame] | 1866 | return |
| 1867 | |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 1868 | headerfile = filename[0:len(filename) - len(fileinfo.Extension())] + '.h' |
[email protected] | 255f2be | 2014-12-05 22:19:55 | [diff] [blame] | 1869 | if not os.path.exists(headerfile): |
| 1870 | return |
| 1871 | headername = FileInfo(headerfile).RepositoryName() |
| 1872 | first_include = 0 |
| 1873 | for section_list in include_state.include_list: |
| 1874 | for f in section_list: |
| 1875 | if headername in f[0] or f[0] in headername: |
| 1876 | return |
| 1877 | if not first_include: |
| 1878 | first_include = f[1] |
| 1879 | |
| 1880 | error(filename, first_include, 'build/include', 5, |
| 1881 | '%s should include its header file %s' % (fileinfo.RepositoryName(), |
| 1882 | headername)) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1883 | |
| 1884 | |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 1885 | def CheckForBadCharacters(filename, lines, error): |
| 1886 | """Logs an error for each line containing bad characters. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1887 | |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 1888 | Two kinds of bad characters: |
| 1889 | |
| 1890 | 1. Unicode replacement characters: These indicate that either the file |
| 1891 | contained invalid UTF-8 (likely) or Unicode replacement characters (which |
| 1892 | it shouldn't). Note that it's possible for this to throw off line |
| 1893 | numbering if the invalid UTF-8 occurred adjacent to a newline. |
| 1894 | |
| 1895 | 2. NUL bytes. These are problematic for some tools. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1896 | |
| 1897 | Args: |
| 1898 | filename: The name of the current file. |
| 1899 | lines: An array of strings, each representing a line of the file. |
| 1900 | error: The function to call with any errors found. |
| 1901 | """ |
| 1902 | for linenum, line in enumerate(lines): |
| 1903 | if u'\ufffd' in line: |
| 1904 | error(filename, linenum, 'readability/utf8', 5, |
| 1905 | 'Line contains invalid UTF-8 (or Unicode replacement character).') |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 1906 | if '\0' in line: |
| 1907 | error(filename, linenum, 'readability/nul', 5, 'Line contains NUL byte.') |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1908 | |
| 1909 | |
| 1910 | def CheckForNewlineAtEOF(filename, lines, error): |
| 1911 | """Logs an error if there is no newline char at the end of the file. |
| 1912 | |
| 1913 | Args: |
| 1914 | filename: The name of the current file. |
| 1915 | lines: An array of strings, each representing a line of the file. |
| 1916 | error: The function to call with any errors found. |
| 1917 | """ |
| 1918 | |
| 1919 | # The array lines() was created by adding two newlines to the |
| 1920 | # original file (go figure), then splitting on \n. |
| 1921 | # To verify that the file ends in \n, we just have to make sure the |
| 1922 | # last-but-two element of lines() exists and is empty. |
| 1923 | if len(lines) < 3 or lines[-2]: |
| 1924 | error(filename, len(lines) - 2, 'whitespace/ending_newline', 5, |
| 1925 | 'Could not find a newline character at the end of the file.') |
| 1926 | |
| 1927 | |
| 1928 | def CheckForMultilineCommentsAndStrings(filename, clean_lines, linenum, error): |
| 1929 | """Logs an error if we see /* ... */ or "..." that extend past one line. |
| 1930 | |
| 1931 | /* ... */ comments are legit inside macros, for one line. |
| 1932 | Otherwise, we prefer // comments, so it's ok to warn about the |
| 1933 | other. Likewise, it's ok for strings to extend across multiple |
| 1934 | lines, as long as a line continuation character (backslash) |
| 1935 | terminates each line. Although not currently prohibited by the C++ |
| 1936 | style guide, it's ugly and unnecessary. We don't do well with either |
| 1937 | in this lint program, so we warn about both. |
| 1938 | |
| 1939 | Args: |
| 1940 | filename: The name of the current file. |
| 1941 | clean_lines: A CleansedLines instance containing the file. |
| 1942 | linenum: The number of the line to check. |
| 1943 | error: The function to call with any errors found. |
| 1944 | """ |
| 1945 | line = clean_lines.elided[linenum] |
| 1946 | |
| 1947 | # Remove all \\ (escaped backslashes) from the line. They are OK, and the |
| 1948 | # second (escaped) slash may trigger later \" detection erroneously. |
| 1949 | line = line.replace('\\\\', '') |
| 1950 | |
| 1951 | if line.count('/*') > line.count('*/'): |
| 1952 | error(filename, linenum, 'readability/multiline_comment', 5, |
| 1953 | 'Complex multi-line /*...*/-style comment found. ' |
| 1954 | 'Lint may give bogus warnings. ' |
| 1955 | 'Consider replacing these with //-style comments, ' |
| 1956 | 'with #if 0...#endif, ' |
| 1957 | 'or with more clearly structured multi-line comments.') |
| 1958 | |
| 1959 | if (line.count('"') - line.count('\\"')) % 2: |
| 1960 | error(filename, linenum, 'readability/multiline_string', 5, |
| 1961 | 'Multi-line string ("...") found. This lint script doesn\'t ' |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 1962 | 'do well with such strings, and may give bogus warnings. ' |
| 1963 | 'Use C++11 raw strings or concatenation instead.') |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1964 | |
| 1965 | |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 1966 | # (non-threadsafe name, thread-safe alternative, validation pattern) |
| 1967 | # |
| 1968 | # The validation pattern is used to eliminate false positives such as: |
| 1969 | # _rand(); // false positive due to substring match. |
| 1970 | # ->rand(); // some member function rand(). |
| 1971 | # ACMRandom rand(seed); // some variable named rand. |
| 1972 | # ISAACRandom rand(); // another variable named rand. |
| 1973 | # |
| 1974 | # Basically we require the return value of these functions to be used |
| 1975 | # in some expression context on the same line by matching on some |
| 1976 | # operator before the function name. This eliminates constructors and |
| 1977 | # member function calls. |
| 1978 | _UNSAFE_FUNC_PREFIX = r'(?:[-+*/=%^&|(<]\s*|>\s+)' |
| 1979 | _THREADING_LIST = ( |
| 1980 | ('asctime(', 'asctime_r(', _UNSAFE_FUNC_PREFIX + r'asctime\([^)]+\)'), |
| 1981 | ('ctime(', 'ctime_r(', _UNSAFE_FUNC_PREFIX + r'ctime\([^)]+\)'), |
| 1982 | ('getgrgid(', 'getgrgid_r(', _UNSAFE_FUNC_PREFIX + r'getgrgid\([^)]+\)'), |
| 1983 | ('getgrnam(', 'getgrnam_r(', _UNSAFE_FUNC_PREFIX + r'getgrnam\([^)]+\)'), |
| 1984 | ('getlogin(', 'getlogin_r(', _UNSAFE_FUNC_PREFIX + r'getlogin\(\)'), |
| 1985 | ('getpwnam(', 'getpwnam_r(', _UNSAFE_FUNC_PREFIX + r'getpwnam\([^)]+\)'), |
| 1986 | ('getpwuid(', 'getpwuid_r(', _UNSAFE_FUNC_PREFIX + r'getpwuid\([^)]+\)'), |
| 1987 | ('gmtime(', 'gmtime_r(', _UNSAFE_FUNC_PREFIX + r'gmtime\([^)]+\)'), |
| 1988 | ('localtime(', 'localtime_r(', _UNSAFE_FUNC_PREFIX + r'localtime\([^)]+\)'), |
| 1989 | ('rand(', 'rand_r(', _UNSAFE_FUNC_PREFIX + r'rand\(\)'), |
| 1990 | ('strtok(', 'strtok_r(', |
| 1991 | _UNSAFE_FUNC_PREFIX + r'strtok\([^)]+\)'), |
| 1992 | ('ttyname(', 'ttyname_r(', _UNSAFE_FUNC_PREFIX + r'ttyname\([^)]+\)'), |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 1993 | ) |
| 1994 | |
| 1995 | |
| 1996 | def CheckPosixThreading(filename, clean_lines, linenum, error): |
| 1997 | """Checks for calls to thread-unsafe functions. |
| 1998 | |
| 1999 | Much code has been originally written without consideration of |
| 2000 | multi-threading. Also, engineers are relying on their old experience; |
| 2001 | they have learned posix before threading extensions were added. These |
| 2002 | tests guide the engineers to use thread-safe functions (when using |
| 2003 | posix directly). |
| 2004 | |
| 2005 | Args: |
| 2006 | filename: The name of the current file. |
| 2007 | clean_lines: A CleansedLines instance containing the file. |
| 2008 | linenum: The number of the line to check. |
| 2009 | error: The function to call with any errors found. |
| 2010 | """ |
| 2011 | line = clean_lines.elided[linenum] |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 2012 | for single_thread_func, multithread_safe_func, pattern in _THREADING_LIST: |
| 2013 | # Additional pattern matching check to confirm that this is the |
| 2014 | # function we are looking for |
| 2015 | if Search(pattern, line): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2016 | error(filename, linenum, 'runtime/threadsafe_fn', 2, |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 2017 | 'Consider using ' + multithread_safe_func + |
| 2018 | '...) instead of ' + single_thread_func + |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2019 | '...) for improved thread safety.') |
| 2020 | |
| 2021 | |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 2022 | def CheckVlogArguments(filename, clean_lines, linenum, error): |
| 2023 | """Checks that VLOG() is only used for defining a logging level. |
| 2024 | |
| 2025 | For example, VLOG(2) is correct. VLOG(INFO), VLOG(WARNING), VLOG(ERROR), and |
| 2026 | VLOG(FATAL) are not. |
| 2027 | |
| 2028 | Args: |
| 2029 | filename: The name of the current file. |
| 2030 | clean_lines: A CleansedLines instance containing the file. |
| 2031 | linenum: The number of the line to check. |
| 2032 | error: The function to call with any errors found. |
| 2033 | """ |
| 2034 | line = clean_lines.elided[linenum] |
| 2035 | if Search(r'\bVLOG\((INFO|ERROR|WARNING|DFATAL|FATAL)\)', line): |
| 2036 | error(filename, linenum, 'runtime/vlog', 5, |
| 2037 | 'VLOG() should be used with numeric verbosity level. ' |
| 2038 | 'Use LOG() if you want symbolic severity levels.') |
| 2039 | |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 2040 | # Matches invalid increment: *count++, which moves pointer instead of |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 2041 | # incrementing a value. |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 2042 | _RE_PATTERN_INVALID_INCREMENT = re.compile( |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 2043 | r'^\s*\*\w+(\+\+|--);') |
| 2044 | |
| 2045 | |
| 2046 | def CheckInvalidIncrement(filename, clean_lines, linenum, error): |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 2047 | """Checks for invalid increment *count++. |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 2048 | |
| 2049 | For example following function: |
| 2050 | void increment_counter(int* count) { |
| 2051 | *count++; |
| 2052 | } |
| 2053 | is invalid, because it effectively does count++, moving pointer, and should |
| 2054 | be replaced with ++*count, (*count)++ or *count += 1. |
| 2055 | |
| 2056 | Args: |
| 2057 | filename: The name of the current file. |
| 2058 | clean_lines: A CleansedLines instance containing the file. |
| 2059 | linenum: The number of the line to check. |
| 2060 | error: The function to call with any errors found. |
| 2061 | """ |
| 2062 | line = clean_lines.elided[linenum] |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 2063 | if _RE_PATTERN_INVALID_INCREMENT.match(line): |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 2064 | error(filename, linenum, 'runtime/invalid_increment', 5, |
| 2065 | 'Changing pointer instead of value (or unused value of operator*).') |
| 2066 | |
| 2067 | |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 2068 | def IsMacroDefinition(clean_lines, linenum): |
| 2069 | if Search(r'^#define', clean_lines[linenum]): |
| 2070 | return True |
| 2071 | |
| 2072 | if linenum > 0 and Search(r'\\$', clean_lines[linenum - 1]): |
| 2073 | return True |
| 2074 | |
| 2075 | return False |
| 2076 | |
| 2077 | |
| 2078 | def IsForwardClassDeclaration(clean_lines, linenum): |
| 2079 | return Match(r'^\s*(\btemplate\b)*.*class\s+\w+;\s*$', clean_lines[linenum]) |
| 2080 | |
| 2081 | |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2082 | class _BlockInfo(object): |
| 2083 | """Stores information about a generic block of code.""" |
| 2084 | |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 2085 | def __init__(self, linenum, seen_open_brace): |
| 2086 | self.starting_linenum = linenum |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2087 | self.seen_open_brace = seen_open_brace |
| 2088 | self.open_parentheses = 0 |
| 2089 | self.inline_asm = _NO_ASM |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 2090 | self.check_namespace_indentation = False |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2091 | |
| 2092 | def CheckBegin(self, filename, clean_lines, linenum, error): |
| 2093 | """Run checks that applies to text up to the opening brace. |
| 2094 | |
| 2095 | This is mostly for checking the text after the class identifier |
| 2096 | and the "{", usually where the base class is specified. For other |
| 2097 | blocks, there isn't much to check, so we always pass. |
| 2098 | |
| 2099 | Args: |
| 2100 | filename: The name of the current file. |
| 2101 | clean_lines: A CleansedLines instance containing the file. |
| 2102 | linenum: The number of the line to check. |
| 2103 | error: The function to call with any errors found. |
| 2104 | """ |
| 2105 | pass |
| 2106 | |
| 2107 | def CheckEnd(self, filename, clean_lines, linenum, error): |
| 2108 | """Run checks that applies to text after the closing brace. |
| 2109 | |
| 2110 | This is mostly used for checking end of namespace comments. |
| 2111 | |
| 2112 | Args: |
| 2113 | filename: The name of the current file. |
| 2114 | clean_lines: A CleansedLines instance containing the file. |
| 2115 | linenum: The number of the line to check. |
| 2116 | error: The function to call with any errors found. |
| 2117 | """ |
| 2118 | pass |
| 2119 | |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 2120 | def IsBlockInfo(self): |
| 2121 | """Returns true if this block is a _BlockInfo. |
| 2122 | |
| 2123 | This is convenient for verifying that an object is an instance of |
| 2124 | a _BlockInfo, but not an instance of any of the derived classes. |
| 2125 | |
| 2126 | Returns: |
| 2127 | True for this class, False for derived classes. |
| 2128 | """ |
| 2129 | return self.__class__ == _BlockInfo |
| 2130 | |
| 2131 | |
| 2132 | class _ExternCInfo(_BlockInfo): |
| 2133 | """Stores information about an 'extern "C"' block.""" |
| 2134 | |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 2135 | def __init__(self, linenum): |
| 2136 | _BlockInfo.__init__(self, linenum, True) |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 2137 | |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2138 | |
| 2139 | class _ClassInfo(_BlockInfo): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2140 | """Stores information about a class.""" |
| 2141 | |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2142 | def __init__(self, name, class_or_struct, clean_lines, linenum): |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 2143 | _BlockInfo.__init__(self, linenum, False) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2144 | self.name = name |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2145 | self.is_derived = False |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 2146 | self.check_namespace_indentation = True |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2147 | if class_or_struct == 'struct': |
| 2148 | self.access = 'public' |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 2149 | self.is_struct = True |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2150 | else: |
| 2151 | self.access = 'private' |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 2152 | self.is_struct = False |
| 2153 | |
| 2154 | # Remember initial indentation level for this class. Using raw_lines here |
| 2155 | # instead of elided to account for leading comments. |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 2156 | self.class_indent = GetIndentLevel(clean_lines.raw_lines[linenum]) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2157 | |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 2158 | # Try to find the end of the class. This will be confused by things like: |
| 2159 | # class A { |
| 2160 | # } *x = { ... |
| 2161 | # |
| 2162 | # But it's still good enough for CheckSectionSpacing. |
| 2163 | self.last_line = 0 |
| 2164 | depth = 0 |
| 2165 | for i in range(linenum, clean_lines.NumLines()): |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2166 | line = clean_lines.elided[i] |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 2167 | depth += line.count('{') - line.count('}') |
| 2168 | if not depth: |
| 2169 | self.last_line = i |
| 2170 | break |
| 2171 | |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2172 | def CheckBegin(self, filename, clean_lines, linenum, error): |
| 2173 | # Look for a bare ':' |
| 2174 | if Search('(^|[^:]):($|[^:])', clean_lines.elided[linenum]): |
| 2175 | self.is_derived = True |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2176 | |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 2177 | def CheckEnd(self, filename, clean_lines, linenum, error): |
[email protected] | 255f2be | 2014-12-05 22:19:55 | [diff] [blame] | 2178 | # If there is a DISALLOW macro, it should appear near the end of |
| 2179 | # the class. |
| 2180 | seen_last_thing_in_class = False |
| 2181 | for i in xrange(linenum - 1, self.starting_linenum, -1): |
| 2182 | match = Search( |
| 2183 | r'\b(DISALLOW_COPY_AND_ASSIGN|DISALLOW_IMPLICIT_CONSTRUCTORS)\(' + |
| 2184 | self.name + r'\)', |
| 2185 | clean_lines.elided[i]) |
| 2186 | if match: |
| 2187 | if seen_last_thing_in_class: |
| 2188 | error(filename, i, 'readability/constructors', 3, |
| 2189 | match.group(1) + ' should be the last thing in the class') |
| 2190 | break |
| 2191 | |
| 2192 | if not Match(r'^\s*$', clean_lines.elided[i]): |
| 2193 | seen_last_thing_in_class = True |
| 2194 | |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 2195 | # Check that closing brace is aligned with beginning of the class. |
| 2196 | # Only do this if the closing brace is indented by only whitespaces. |
| 2197 | # This means we will not check single-line class definitions. |
| 2198 | indent = Match(r'^( *)\}', clean_lines.elided[linenum]) |
| 2199 | if indent and len(indent.group(1)) != self.class_indent: |
| 2200 | if self.is_struct: |
| 2201 | parent = 'struct ' + self.name |
| 2202 | else: |
| 2203 | parent = 'class ' + self.name |
| 2204 | error(filename, linenum, 'whitespace/indent', 3, |
| 2205 | 'Closing brace should be aligned with beginning of %s' % parent) |
| 2206 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2207 | |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2208 | class _NamespaceInfo(_BlockInfo): |
| 2209 | """Stores information about a namespace.""" |
| 2210 | |
| 2211 | def __init__(self, name, linenum): |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 2212 | _BlockInfo.__init__(self, linenum, False) |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2213 | self.name = name or '' |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 2214 | self.check_namespace_indentation = True |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2215 | |
| 2216 | def CheckEnd(self, filename, clean_lines, linenum, error): |
| 2217 | """Check end of namespace comments.""" |
| 2218 | line = clean_lines.raw_lines[linenum] |
| 2219 | |
| 2220 | # Check how many lines is enclosed in this namespace. Don't issue |
| 2221 | # warning for missing namespace comments if there aren't enough |
| 2222 | # lines. However, do apply checks if there is already an end of |
| 2223 | # namespace comment and it's incorrect. |
| 2224 | # |
| 2225 | # TODO(unknown): We always want to check end of namespace comments |
| 2226 | # if a namespace is large, but sometimes we also want to apply the |
| 2227 | # check if a short namespace contained nontrivial things (something |
| 2228 | # other than forward declarations). There is currently no logic on |
| 2229 | # deciding what these nontrivial things are, so this check is |
| 2230 | # triggered by namespace size only, which works most of the time. |
| 2231 | if (linenum - self.starting_linenum < 10 |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 2232 | and not Match(r'^\s*};*\s*(//|/\*).*\bnamespace\b', line)): |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2233 | return |
| 2234 | |
| 2235 | # Look for matching comment at end of namespace. |
| 2236 | # |
| 2237 | # Note that we accept C style "/* */" comments for terminating |
| 2238 | # namespaces, so that code that terminate namespaces inside |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 2239 | # preprocessor macros can be cpplint clean. |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2240 | # |
| 2241 | # We also accept stuff like "// end of namespace <name>." with the |
| 2242 | # period at the end. |
| 2243 | # |
| 2244 | # Besides these, we don't accept anything else, otherwise we might |
| 2245 | # get false negatives when existing comment is a substring of the |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 2246 | # expected namespace. |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2247 | if self.name: |
| 2248 | # Named namespace |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 2249 | if not Match((r'^\s*};*\s*(//|/\*).*\bnamespace\s+' + |
| 2250 | re.escape(self.name) + r'[\*/\.\\\s]*$'), |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2251 | line): |
| 2252 | error(filename, linenum, 'readability/namespace', 5, |
| 2253 | 'Namespace should be terminated with "// namespace %s"' % |
| 2254 | self.name) |
| 2255 | else: |
| 2256 | # Anonymous namespace |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 2257 | if not Match(r'^\s*};*\s*(//|/\*).*\bnamespace[\*/\.\\\s]*$', line): |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 2258 | # If "// namespace anonymous" or "// anonymous namespace (more text)", |
| 2259 | # mention "// anonymous namespace" as an acceptable form |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 2260 | if Match(r'^\s*}.*\b(namespace anonymous|anonymous namespace)\b', line): |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 2261 | error(filename, linenum, 'readability/namespace', 5, |
| 2262 | 'Anonymous namespace should be terminated with "// namespace"' |
| 2263 | ' or "// anonymous namespace"') |
| 2264 | else: |
| 2265 | error(filename, linenum, 'readability/namespace', 5, |
| 2266 | 'Anonymous namespace should be terminated with "// namespace"') |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2267 | |
| 2268 | |
| 2269 | class _PreprocessorInfo(object): |
| 2270 | """Stores checkpoints of nesting stacks when #if/#else is seen.""" |
| 2271 | |
| 2272 | def __init__(self, stack_before_if): |
| 2273 | # The entire nesting stack before #if |
| 2274 | self.stack_before_if = stack_before_if |
| 2275 | |
| 2276 | # The entire nesting stack up to #else |
| 2277 | self.stack_before_else = [] |
| 2278 | |
| 2279 | # Whether we have already seen #else or #elif |
| 2280 | self.seen_else = False |
| 2281 | |
| 2282 | |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 2283 | class NestingState(object): |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2284 | """Holds states related to parsing braces.""" |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2285 | |
| 2286 | def __init__(self): |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2287 | # Stack for tracking all braces. An object is pushed whenever we |
| 2288 | # see a "{", and popped when we see a "}". Only 3 types of |
| 2289 | # objects are possible: |
| 2290 | # - _ClassInfo: a class or struct. |
| 2291 | # - _NamespaceInfo: a namespace. |
| 2292 | # - _BlockInfo: some other type of block. |
| 2293 | self.stack = [] |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2294 | |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 2295 | # Top of the previous stack before each Update(). |
| 2296 | # |
| 2297 | # Because the nesting_stack is updated at the end of each line, we |
| 2298 | # had to do some convoluted checks to find out what is the current |
| 2299 | # scope at the beginning of the line. This check is simplified by |
| 2300 | # saving the previous top of nesting stack. |
| 2301 | # |
| 2302 | # We could save the full stack, but we only need the top. Copying |
| 2303 | # the full nesting stack would slow down cpplint by ~10%. |
| 2304 | self.previous_stack_top = [] |
| 2305 | |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2306 | # Stack of _PreprocessorInfo objects. |
| 2307 | self.pp_stack = [] |
| 2308 | |
| 2309 | def SeenOpenBrace(self): |
| 2310 | """Check if we have seen the opening brace for the innermost block. |
| 2311 | |
| 2312 | Returns: |
| 2313 | True if we have seen the opening brace, False if the innermost |
| 2314 | block is still expecting an opening brace. |
| 2315 | """ |
| 2316 | return (not self.stack) or self.stack[-1].seen_open_brace |
| 2317 | |
| 2318 | def InNamespaceBody(self): |
| 2319 | """Check if we are currently one level inside a namespace body. |
| 2320 | |
| 2321 | Returns: |
| 2322 | True if top of the stack is a namespace block, False otherwise. |
| 2323 | """ |
| 2324 | return self.stack and isinstance(self.stack[-1], _NamespaceInfo) |
| 2325 | |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 2326 | def InExternC(self): |
| 2327 | """Check if we are currently one level inside an 'extern "C"' block. |
| 2328 | |
| 2329 | Returns: |
| 2330 | True if top of the stack is an extern block, False otherwise. |
| 2331 | """ |
| 2332 | return self.stack and isinstance(self.stack[-1], _ExternCInfo) |
| 2333 | |
| 2334 | def InClassDeclaration(self): |
| 2335 | """Check if we are currently one level inside a class or struct declaration. |
| 2336 | |
| 2337 | Returns: |
| 2338 | True if top of the stack is a class/struct, False otherwise. |
| 2339 | """ |
| 2340 | return self.stack and isinstance(self.stack[-1], _ClassInfo) |
| 2341 | |
| 2342 | def InAsmBlock(self): |
| 2343 | """Check if we are currently one level inside an inline ASM block. |
| 2344 | |
| 2345 | Returns: |
| 2346 | True if the top of the stack is a block containing inline ASM. |
| 2347 | """ |
| 2348 | return self.stack and self.stack[-1].inline_asm != _NO_ASM |
| 2349 | |
| 2350 | def InTemplateArgumentList(self, clean_lines, linenum, pos): |
| 2351 | """Check if current position is inside template argument list. |
| 2352 | |
| 2353 | Args: |
| 2354 | clean_lines: A CleansedLines instance containing the file. |
| 2355 | linenum: The number of the line to check. |
| 2356 | pos: position just after the suspected template argument. |
| 2357 | Returns: |
| 2358 | True if (linenum, pos) is inside template arguments. |
| 2359 | """ |
| 2360 | while linenum < clean_lines.NumLines(): |
| 2361 | # Find the earliest character that might indicate a template argument |
| 2362 | line = clean_lines.elided[linenum] |
| 2363 | match = Match(r'^[^{};=\[\]\.<>]*(.)', line[pos:]) |
| 2364 | if not match: |
| 2365 | linenum += 1 |
| 2366 | pos = 0 |
| 2367 | continue |
| 2368 | token = match.group(1) |
| 2369 | pos += len(match.group(0)) |
| 2370 | |
| 2371 | # These things do not look like template argument list: |
| 2372 | # class Suspect { |
| 2373 | # class Suspect x; } |
| 2374 | if token in ('{', '}', ';'): return False |
| 2375 | |
| 2376 | # These things look like template argument list: |
| 2377 | # template <class Suspect> |
| 2378 | # template <class Suspect = default_value> |
| 2379 | # template <class Suspect[]> |
| 2380 | # template <class Suspect...> |
| 2381 | if token in ('>', '=', '[', ']', '.'): return True |
| 2382 | |
| 2383 | # Check if token is an unmatched '<'. |
| 2384 | # If not, move on to the next character. |
| 2385 | if token != '<': |
| 2386 | pos += 1 |
| 2387 | if pos >= len(line): |
| 2388 | linenum += 1 |
| 2389 | pos = 0 |
| 2390 | continue |
| 2391 | |
| 2392 | # We can't be sure if we just find a single '<', and need to |
| 2393 | # find the matching '>'. |
| 2394 | (_, end_line, end_pos) = CloseExpression(clean_lines, linenum, pos - 1) |
| 2395 | if end_pos < 0: |
| 2396 | # Not sure if template argument list or syntax error in file |
| 2397 | return False |
| 2398 | linenum = end_line |
| 2399 | pos = end_pos |
| 2400 | return False |
| 2401 | |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2402 | def UpdatePreprocessor(self, line): |
| 2403 | """Update preprocessor stack. |
| 2404 | |
| 2405 | We need to handle preprocessors due to classes like this: |
| 2406 | #ifdef SWIG |
| 2407 | struct ResultDetailsPageElementExtensionPoint { |
| 2408 | #else |
| 2409 | struct ResultDetailsPageElementExtensionPoint : public Extension { |
| 2410 | #endif |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2411 | |
| 2412 | We make the following assumptions (good enough for most files): |
| 2413 | - Preprocessor condition evaluates to true from #if up to first |
| 2414 | #else/#elif/#endif. |
| 2415 | |
| 2416 | - Preprocessor condition evaluates to false from #else/#elif up |
| 2417 | to #endif. We still perform lint checks on these lines, but |
| 2418 | these do not affect nesting stack. |
| 2419 | |
| 2420 | Args: |
| 2421 | line: current line to check. |
| 2422 | """ |
| 2423 | if Match(r'^\s*#\s*(if|ifdef|ifndef)\b', line): |
| 2424 | # Beginning of #if block, save the nesting stack here. The saved |
| 2425 | # stack will allow us to restore the parsing state in the #else case. |
| 2426 | self.pp_stack.append(_PreprocessorInfo(copy.deepcopy(self.stack))) |
| 2427 | elif Match(r'^\s*#\s*(else|elif)\b', line): |
| 2428 | # Beginning of #else block |
| 2429 | if self.pp_stack: |
| 2430 | if not self.pp_stack[-1].seen_else: |
| 2431 | # This is the first #else or #elif block. Remember the |
| 2432 | # whole nesting stack up to this point. This is what we |
| 2433 | # keep after the #endif. |
| 2434 | self.pp_stack[-1].seen_else = True |
| 2435 | self.pp_stack[-1].stack_before_else = copy.deepcopy(self.stack) |
| 2436 | |
| 2437 | # Restore the stack to how it was before the #if |
| 2438 | self.stack = copy.deepcopy(self.pp_stack[-1].stack_before_if) |
| 2439 | else: |
| 2440 | # TODO(unknown): unexpected #else, issue warning? |
| 2441 | pass |
| 2442 | elif Match(r'^\s*#\s*endif\b', line): |
| 2443 | # End of #if or #else blocks. |
| 2444 | if self.pp_stack: |
| 2445 | # If we saw an #else, we will need to restore the nesting |
| 2446 | # stack to its former state before the #else, otherwise we |
| 2447 | # will just continue from where we left off. |
| 2448 | if self.pp_stack[-1].seen_else: |
| 2449 | # Here we can just use a shallow copy since we are the last |
| 2450 | # reference to it. |
| 2451 | self.stack = self.pp_stack[-1].stack_before_else |
| 2452 | # Drop the corresponding #if |
| 2453 | self.pp_stack.pop() |
| 2454 | else: |
| 2455 | # TODO(unknown): unexpected #endif, issue warning? |
| 2456 | pass |
| 2457 | |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 2458 | # TODO(unknown): Update() is too long, but we will refactor later. |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2459 | def Update(self, filename, clean_lines, linenum, error): |
| 2460 | """Update nesting state with current line. |
| 2461 | |
| 2462 | Args: |
| 2463 | filename: The name of the current file. |
| 2464 | clean_lines: A CleansedLines instance containing the file. |
| 2465 | linenum: The number of the line to check. |
| 2466 | error: The function to call with any errors found. |
| 2467 | """ |
| 2468 | line = clean_lines.elided[linenum] |
| 2469 | |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 2470 | # Remember top of the previous nesting stack. |
| 2471 | # |
| 2472 | # The stack is always pushed/popped and not modified in place, so |
| 2473 | # we can just do a shallow copy instead of copy.deepcopy. Using |
| 2474 | # deepcopy would slow down cpplint by ~28%. |
| 2475 | if self.stack: |
| 2476 | self.previous_stack_top = self.stack[-1] |
| 2477 | else: |
| 2478 | self.previous_stack_top = None |
| 2479 | |
| 2480 | # Update pp_stack |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2481 | self.UpdatePreprocessor(line) |
| 2482 | |
| 2483 | # Count parentheses. This is to avoid adding struct arguments to |
| 2484 | # the nesting stack. |
| 2485 | if self.stack: |
| 2486 | inner_block = self.stack[-1] |
| 2487 | depth_change = line.count('(') - line.count(')') |
| 2488 | inner_block.open_parentheses += depth_change |
| 2489 | |
| 2490 | # Also check if we are starting or ending an inline assembly block. |
| 2491 | if inner_block.inline_asm in (_NO_ASM, _END_ASM): |
| 2492 | if (depth_change != 0 and |
| 2493 | inner_block.open_parentheses == 1 and |
| 2494 | _MATCH_ASM.match(line)): |
| 2495 | # Enter assembly block |
| 2496 | inner_block.inline_asm = _INSIDE_ASM |
| 2497 | else: |
| 2498 | # Not entering assembly block. If previous line was _END_ASM, |
| 2499 | # we will now shift to _NO_ASM state. |
| 2500 | inner_block.inline_asm = _NO_ASM |
| 2501 | elif (inner_block.inline_asm == _INSIDE_ASM and |
| 2502 | inner_block.open_parentheses == 0): |
| 2503 | # Exit assembly block |
| 2504 | inner_block.inline_asm = _END_ASM |
| 2505 | |
| 2506 | # Consume namespace declaration at the beginning of the line. Do |
| 2507 | # this in a loop so that we catch same line declarations like this: |
| 2508 | # namespace proto2 { namespace bridge { class MessageSet; } } |
| 2509 | while True: |
| 2510 | # Match start of namespace. The "\b\s*" below catches namespace |
| 2511 | # declarations even if it weren't followed by a whitespace, this |
| 2512 | # is so that we don't confuse our namespace checker. The |
| 2513 | # missing spaces will be flagged by CheckSpacing. |
| 2514 | namespace_decl_match = Match(r'^\s*namespace\b\s*([:\w]+)?(.*)$', line) |
| 2515 | if not namespace_decl_match: |
| 2516 | break |
| 2517 | |
| 2518 | new_namespace = _NamespaceInfo(namespace_decl_match.group(1), linenum) |
| 2519 | self.stack.append(new_namespace) |
| 2520 | |
| 2521 | line = namespace_decl_match.group(2) |
| 2522 | if line.find('{') != -1: |
| 2523 | new_namespace.seen_open_brace = True |
| 2524 | line = line[line.find('{') + 1:] |
| 2525 | |
| 2526 | # Look for a class declaration in whatever is left of the line |
| 2527 | # after parsing namespaces. The regexp accounts for decorated classes |
| 2528 | # such as in: |
| 2529 | # class LOCKABLE API Object { |
| 2530 | # }; |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2531 | class_decl_match = Match( |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 2532 | r'^(\s*(?:template\s*<[\w\s<>,:]*>\s*)?' |
| 2533 | r'(class|struct)\s+(?:[A-Z_]+\s+)*(\w+(?:::\w+)*))' |
| 2534 | r'(.*)$', line) |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2535 | if (class_decl_match and |
| 2536 | (not self.stack or self.stack[-1].open_parentheses == 0)): |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 2537 | # We do not want to accept classes that are actually template arguments: |
| 2538 | # template <class Ignore1, |
| 2539 | # class Ignore2 = Default<Args>, |
| 2540 | # template <Args> class Ignore3> |
| 2541 | # void Function() {}; |
| 2542 | # |
| 2543 | # To avoid template argument cases, we scan forward and look for |
| 2544 | # an unmatched '>'. If we see one, assume we are inside a |
| 2545 | # template argument list. |
| 2546 | end_declaration = len(class_decl_match.group(1)) |
| 2547 | if not self.InTemplateArgumentList(clean_lines, linenum, end_declaration): |
| 2548 | self.stack.append(_ClassInfo( |
| 2549 | class_decl_match.group(3), class_decl_match.group(2), |
| 2550 | clean_lines, linenum)) |
| 2551 | line = class_decl_match.group(4) |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2552 | |
| 2553 | # If we have not yet seen the opening brace for the innermost block, |
| 2554 | # run checks here. |
| 2555 | if not self.SeenOpenBrace(): |
| 2556 | self.stack[-1].CheckBegin(filename, clean_lines, linenum, error) |
| 2557 | |
| 2558 | # Update access control if we are inside a class/struct |
| 2559 | if self.stack and isinstance(self.stack[-1], _ClassInfo): |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 2560 | classinfo = self.stack[-1] |
| 2561 | access_match = Match( |
| 2562 | r'^(.*)\b(public|private|protected|signals)(\s+(?:slots\s*)?)?' |
| 2563 | r':(?:[^:]|$)', |
| 2564 | line) |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2565 | if access_match: |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 2566 | classinfo.access = access_match.group(2) |
| 2567 | |
| 2568 | # Check that access keywords are indented +1 space. Skip this |
| 2569 | # check if the keywords are not preceded by whitespaces. |
| 2570 | indent = access_match.group(1) |
| 2571 | if (len(indent) != classinfo.class_indent + 1 and |
| 2572 | Match(r'^\s*$', indent)): |
| 2573 | if classinfo.is_struct: |
| 2574 | parent = 'struct ' + classinfo.name |
| 2575 | else: |
| 2576 | parent = 'class ' + classinfo.name |
| 2577 | slots = '' |
| 2578 | if access_match.group(3): |
| 2579 | slots = access_match.group(3) |
| 2580 | error(filename, linenum, 'whitespace/indent', 3, |
| 2581 | '%s%s: should be indented +1 space inside %s' % ( |
| 2582 | access_match.group(2), slots, parent)) |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2583 | |
| 2584 | # Consume braces or semicolons from what's left of the line |
| 2585 | while True: |
| 2586 | # Match first brace, semicolon, or closed parenthesis. |
| 2587 | matched = Match(r'^[^{;)}]*([{;)}])(.*)$', line) |
| 2588 | if not matched: |
| 2589 | break |
| 2590 | |
| 2591 | token = matched.group(1) |
| 2592 | if token == '{': |
| 2593 | # If namespace or class hasn't seen a opening brace yet, mark |
| 2594 | # namespace/class head as complete. Push a new block onto the |
| 2595 | # stack otherwise. |
| 2596 | if not self.SeenOpenBrace(): |
| 2597 | self.stack[-1].seen_open_brace = True |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 2598 | elif Match(r'^extern\s*"[^"]*"\s*\{', line): |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 2599 | self.stack.append(_ExternCInfo(linenum)) |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2600 | else: |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 2601 | self.stack.append(_BlockInfo(linenum, True)) |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2602 | if _MATCH_ASM.match(line): |
| 2603 | self.stack[-1].inline_asm = _BLOCK_ASM |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 2604 | |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2605 | elif token == ';' or token == ')': |
| 2606 | # If we haven't seen an opening brace yet, but we already saw |
| 2607 | # a semicolon, this is probably a forward declaration. Pop |
| 2608 | # the stack for these. |
| 2609 | # |
| 2610 | # Similarly, if we haven't seen an opening brace yet, but we |
| 2611 | # already saw a closing parenthesis, then these are probably |
| 2612 | # function arguments with extra "class" or "struct" keywords. |
| 2613 | # Also pop these stack for these. |
| 2614 | if not self.SeenOpenBrace(): |
| 2615 | self.stack.pop() |
| 2616 | else: # token == '}' |
| 2617 | # Perform end of block checks and pop the stack. |
| 2618 | if self.stack: |
| 2619 | self.stack[-1].CheckEnd(filename, clean_lines, linenum, error) |
| 2620 | self.stack.pop() |
| 2621 | line = matched.group(2) |
| 2622 | |
| 2623 | def InnermostClass(self): |
| 2624 | """Get class info on the top of the stack. |
| 2625 | |
| 2626 | Returns: |
| 2627 | A _ClassInfo object if we are inside a class, or None otherwise. |
| 2628 | """ |
| 2629 | for i in range(len(self.stack), 0, -1): |
| 2630 | classinfo = self.stack[i - 1] |
| 2631 | if isinstance(classinfo, _ClassInfo): |
| 2632 | return classinfo |
| 2633 | return None |
| 2634 | |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 2635 | def CheckCompletedBlocks(self, filename, error): |
| 2636 | """Checks that all classes and namespaces have been completely parsed. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2637 | |
| 2638 | Call this when all lines in a file have been processed. |
| 2639 | Args: |
| 2640 | filename: The name of the current file. |
| 2641 | error: The function to call with any errors found. |
| 2642 | """ |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2643 | # Note: This test can result in false positives if #ifdef constructs |
| 2644 | # get in the way of brace matching. See the testBuildClass test in |
| 2645 | # cpplint_unittest.py for an example of this. |
| 2646 | for obj in self.stack: |
| 2647 | if isinstance(obj, _ClassInfo): |
| 2648 | error(filename, obj.starting_linenum, 'build/class', 5, |
| 2649 | 'Failed to find complete declaration of class %s' % |
| 2650 | obj.name) |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 2651 | elif isinstance(obj, _NamespaceInfo): |
| 2652 | error(filename, obj.starting_linenum, 'build/namespaces', 5, |
| 2653 | 'Failed to find complete declaration of namespace %s' % |
| 2654 | obj.name) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2655 | |
| 2656 | |
| 2657 | def CheckForNonStandardConstructs(filename, clean_lines, linenum, |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2658 | nesting_state, error): |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 2659 | r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2660 | |
| 2661 | Complain about several constructs which gcc-2 accepts, but which are |
| 2662 | not standard C++. Warning about these in lint is one way to ease the |
| 2663 | transition to new compilers. |
| 2664 | - put storage class first (e.g. "static const" instead of "const static"). |
| 2665 | - "%lld" instead of %qd" in printf-type functions. |
| 2666 | - "%1$d" is non-standard in printf-type functions. |
| 2667 | - "\%" is an undefined character escape sequence. |
| 2668 | - text after #endif is not allowed. |
| 2669 | - invalid inner-style forward declaration. |
| 2670 | - >? and <? operators, and their >?= and <?= cousins. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2671 | |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 2672 | Additionally, check for constructor/destructor style violations and reference |
| 2673 | members, as it is very convenient to do so while checking for |
| 2674 | gcc-2 compliance. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2675 | |
| 2676 | Args: |
| 2677 | filename: The name of the current file. |
| 2678 | clean_lines: A CleansedLines instance containing the file. |
| 2679 | linenum: The number of the line to check. |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 2680 | nesting_state: A NestingState instance which maintains information about |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2681 | the current stack of nested blocks being parsed. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2682 | error: A callable to which errors are reported, which takes 4 arguments: |
| 2683 | filename, line number, error level, and message |
| 2684 | """ |
| 2685 | |
| 2686 | # Remove comments from the line, but leave in strings for now. |
| 2687 | line = clean_lines.lines[linenum] |
| 2688 | |
| 2689 | if Search(r'printf\s*\(.*".*%[-+ ]?\d*q', line): |
| 2690 | error(filename, linenum, 'runtime/printf_format', 3, |
| 2691 | '%q in format strings is deprecated. Use %ll instead.') |
| 2692 | |
| 2693 | if Search(r'printf\s*\(.*".*%\d+\$', line): |
| 2694 | error(filename, linenum, 'runtime/printf_format', 2, |
| 2695 | '%N$ formats are unconventional. Try rewriting to avoid them.') |
| 2696 | |
| 2697 | # Remove escaped backslashes before looking for undefined escapes. |
| 2698 | line = line.replace('\\\\', '') |
| 2699 | |
| 2700 | if Search(r'("|\').*\\(%|\[|\(|{)', line): |
| 2701 | error(filename, linenum, 'build/printf_format', 3, |
| 2702 | '%, [, (, and { are undefined character escapes. Unescape them.') |
| 2703 | |
| 2704 | # For the rest, work with both comments and strings removed. |
| 2705 | line = clean_lines.elided[linenum] |
| 2706 | |
| 2707 | if Search(r'\b(const|volatile|void|char|short|int|long' |
| 2708 | r'|float|double|signed|unsigned' |
| 2709 | r'|schar|u?int8|u?int16|u?int32|u?int64)' |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2710 | r'\s+(register|static|extern|typedef)\b', |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2711 | line): |
| 2712 | error(filename, linenum, 'build/storage_class', 5, |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 2713 | 'Storage-class specifier (static, extern, typedef, etc) should be ' |
| 2714 | 'at the beginning of the declaration.') |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2715 | |
| 2716 | if Match(r'\s*#\s*endif\s*[^/\s]+', line): |
| 2717 | error(filename, linenum, 'build/endif_comment', 5, |
| 2718 | 'Uncommented text after #endif is non-standard. Use a comment.') |
| 2719 | |
| 2720 | if Match(r'\s*class\s+(\w+\s*::\s*)+\w+\s*;', line): |
| 2721 | error(filename, linenum, 'build/forward_decl', 5, |
| 2722 | 'Inner-style forward declarations are invalid. Remove this line.') |
| 2723 | |
| 2724 | if Search(r'(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?', |
| 2725 | line): |
| 2726 | error(filename, linenum, 'build/deprecated', 3, |
| 2727 | '>? and <? (max and min) operators are non-standard and deprecated.') |
| 2728 | |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 2729 | if Search(r'^\s*const\s*string\s*&\s*\w+\s*;', line): |
| 2730 | # TODO(unknown): Could it be expanded safely to arbitrary references, |
| 2731 | # without triggering too many false positives? The first |
| 2732 | # attempt triggered 5 warnings for mostly benign code in the regtest, hence |
| 2733 | # the restriction. |
| 2734 | # Here's the original regexp, for the reference: |
| 2735 | # type_name = r'\w+((\s*::\s*\w+)|(\s*<\s*\w+?\s*>))?' |
| 2736 | # r'\s*const\s*' + type_name + '\s*&\s*\w+\s*;' |
| 2737 | error(filename, linenum, 'runtime/member_string_references', 2, |
| 2738 | 'const string& members are dangerous. It is much better to use ' |
| 2739 | 'alternatives, such as pointers or simple constants.') |
| 2740 | |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 2741 | # Everything else in this function operates on class declarations. |
| 2742 | # Return early if the top of the nesting stack is not a class, or if |
| 2743 | # the class head is not completed yet. |
| 2744 | classinfo = nesting_state.InnermostClass() |
| 2745 | if not classinfo or not classinfo.seen_open_brace: |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2746 | return |
| 2747 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2748 | # The class may have been declared with namespace or classname qualifiers. |
| 2749 | # The constructor and destructor will not have those qualifiers. |
| 2750 | base_classname = classinfo.name.split('::')[-1] |
| 2751 | |
| 2752 | # Look for single-argument constructors that aren't marked explicit. |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 2753 | # Technically a valid construct, but against style. |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 2754 | explicit_constructor_match = Match( |
danakj | d7f5675 | 2017-02-22 16:45:06 | [diff] [blame] | 2755 | r'\s+(?:(?:inline|constexpr)\s+)*(explicit\s+)?' |
| 2756 | r'(?:(?:inline|constexpr)\s+)*%s\s*' |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 2757 | r'\(((?:[^()]|\([^()]*\))*)\)' |
| 2758 | % re.escape(base_classname), |
| 2759 | line) |
| 2760 | |
| 2761 | if explicit_constructor_match: |
| 2762 | is_marked_explicit = explicit_constructor_match.group(1) |
| 2763 | |
| 2764 | if not explicit_constructor_match.group(2): |
| 2765 | constructor_args = [] |
| 2766 | else: |
| 2767 | constructor_args = explicit_constructor_match.group(2).split(',') |
| 2768 | |
| 2769 | # collapse arguments so that commas in template parameter lists and function |
| 2770 | # argument parameter lists don't split arguments in two |
| 2771 | i = 0 |
| 2772 | while i < len(constructor_args): |
| 2773 | constructor_arg = constructor_args[i] |
| 2774 | while (constructor_arg.count('<') > constructor_arg.count('>') or |
| 2775 | constructor_arg.count('(') > constructor_arg.count(')')): |
| 2776 | constructor_arg += ',' + constructor_args[i + 1] |
| 2777 | del constructor_args[i + 1] |
| 2778 | constructor_args[i] = constructor_arg |
| 2779 | i += 1 |
| 2780 | |
| 2781 | defaulted_args = [arg for arg in constructor_args if '=' in arg] |
| 2782 | noarg_constructor = (not constructor_args or # empty arg list |
| 2783 | # 'void' arg specifier |
| 2784 | (len(constructor_args) == 1 and |
| 2785 | constructor_args[0].strip() == 'void')) |
| 2786 | onearg_constructor = ((len(constructor_args) == 1 and # exactly one arg |
| 2787 | not noarg_constructor) or |
| 2788 | # all but at most one arg defaulted |
| 2789 | (len(constructor_args) >= 1 and |
| 2790 | not noarg_constructor and |
| 2791 | len(defaulted_args) >= len(constructor_args) - 1)) |
| 2792 | initializer_list_constructor = bool( |
| 2793 | onearg_constructor and |
| 2794 | Search(r'\bstd\s*::\s*initializer_list\b', constructor_args[0])) |
| 2795 | copy_constructor = bool( |
| 2796 | onearg_constructor and |
| 2797 | Match(r'(const\s+)?%s(\s*<[^>]*>)?(\s+const)?\s*(?:<\w+>\s*)?&' |
| 2798 | % re.escape(base_classname), constructor_args[0].strip())) |
| 2799 | |
| 2800 | if (not is_marked_explicit and |
| 2801 | onearg_constructor and |
| 2802 | not initializer_list_constructor and |
| 2803 | not copy_constructor): |
| 2804 | if defaulted_args: |
| 2805 | error(filename, linenum, 'runtime/explicit', 5, |
| 2806 | 'Constructors callable with one argument ' |
| 2807 | 'should be marked explicit.') |
| 2808 | else: |
| 2809 | error(filename, linenum, 'runtime/explicit', 5, |
| 2810 | 'Single-parameter constructors should be marked explicit.') |
| 2811 | elif is_marked_explicit and not onearg_constructor: |
| 2812 | if noarg_constructor: |
| 2813 | error(filename, linenum, 'runtime/explicit', 5, |
| 2814 | 'Zero-parameter constructors should not be marked explicit.') |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2815 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2816 | |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 2817 | def CheckSpacingForFunctionCall(filename, clean_lines, linenum, error): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2818 | """Checks for the correctness of various spacing around function calls. |
| 2819 | |
| 2820 | Args: |
| 2821 | filename: The name of the current file. |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 2822 | clean_lines: A CleansedLines instance containing the file. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2823 | linenum: The number of the line to check. |
| 2824 | error: The function to call with any errors found. |
| 2825 | """ |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 2826 | line = clean_lines.elided[linenum] |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2827 | |
| 2828 | # Since function calls often occur inside if/for/while/switch |
| 2829 | # expressions - which have their own, more liberal conventions - we |
| 2830 | # first see if we should be looking inside such an expression for a |
| 2831 | # function call, to which we can apply more strict standards. |
| 2832 | fncall = line # if there's no control flow construct, look at whole line |
| 2833 | for pattern in (r'\bif\s*\((.*)\)\s*{', |
| 2834 | r'\bfor\s*\((.*)\)\s*{', |
| 2835 | r'\bwhile\s*\((.*)\)\s*[{;]', |
| 2836 | r'\bswitch\s*\((.*)\)\s*{'): |
| 2837 | match = Search(pattern, line) |
| 2838 | if match: |
| 2839 | fncall = match.group(1) # look inside the parens for function calls |
| 2840 | break |
| 2841 | |
| 2842 | # Except in if/for/while/switch, there should never be space |
| 2843 | # immediately inside parens (eg "f( 3, 4 )"). We make an exception |
| 2844 | # for nested parens ( (a+b) + c ). Likewise, there should never be |
| 2845 | # a space before a ( when it's a function argument. I assume it's a |
| 2846 | # function argument when the char before the whitespace is legal in |
| 2847 | # a function name (alnum + _) and we're not starting a macro. Also ignore |
| 2848 | # pointers and references to arrays and functions coz they're too tricky: |
| 2849 | # we use a very simple way to recognize these: |
| 2850 | # " (something)(maybe-something)" or |
| 2851 | # " (something)(maybe-something," or |
| 2852 | # " (something)[something]" |
| 2853 | # Note that we assume the contents of [] to be short enough that |
| 2854 | # they'll never need to wrap. |
| 2855 | if ( # Ignore control structures. |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 2856 | not Search(r'\b(if|for|while|switch|return|new|delete|catch|sizeof)\b', |
| 2857 | fncall) and |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2858 | # Ignore pointers/references to functions. |
| 2859 | not Search(r' \([^)]+\)\([^)]*(\)|,$)', fncall) and |
| 2860 | # Ignore pointers/references to arrays. |
| 2861 | not Search(r' \([^)]+\)\[[^\]]+\]', fncall)): |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 2862 | if Search(r'\w\s*\(\s(?!\s*\\$)', fncall): # a ( used for a fn call |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2863 | error(filename, linenum, 'whitespace/parens', 4, |
| 2864 | 'Extra space after ( in function call') |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 2865 | elif Search(r'\(\s+(?!(\s*\\)|\()', fncall): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2866 | error(filename, linenum, 'whitespace/parens', 2, |
| 2867 | 'Extra space after (') |
| 2868 | if (Search(r'\w\s+\(', fncall) and |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 2869 | not Search(r'_{0,2}asm_{0,2}\s+_{0,2}volatile_{0,2}\s+\(', fncall) and |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 2870 | not Search(r'#\s*define|typedef|using\s+\w+\s*=', fncall) and |
[email protected] | 255f2be | 2014-12-05 22:19:55 | [diff] [blame] | 2871 | not Search(r'\w\s+\((\w+::)*\*\w+\)\(', fncall) and |
| 2872 | not Search(r'\bcase\s+\(', fncall)): |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 2873 | # TODO(unknown): Space after an operator function seem to be a common |
| 2874 | # error, silence those for now by restricting them to highest verbosity. |
| 2875 | if Search(r'\boperator_*\b', line): |
| 2876 | error(filename, linenum, 'whitespace/parens', 0, |
| 2877 | 'Extra space before ( in function call') |
| 2878 | else: |
| 2879 | error(filename, linenum, 'whitespace/parens', 4, |
| 2880 | 'Extra space before ( in function call') |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2881 | # If the ) is followed only by a newline or a { + newline, assume it's |
| 2882 | # part of a control statement (if/while/etc), and don't complain |
| 2883 | if Search(r'[^)]\s+\)\s*[^{\s]', fncall): |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 2884 | # If the closing parenthesis is preceded by only whitespaces, |
| 2885 | # try to give a more descriptive error message. |
| 2886 | if Search(r'^\s+\)', fncall): |
| 2887 | error(filename, linenum, 'whitespace/parens', 2, |
| 2888 | 'Closing ) should be moved to the previous line') |
| 2889 | else: |
| 2890 | error(filename, linenum, 'whitespace/parens', 2, |
| 2891 | 'Extra space before )') |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2892 | |
| 2893 | |
| 2894 | def IsBlankLine(line): |
| 2895 | """Returns true if the given line is blank. |
| 2896 | |
| 2897 | We consider a line to be blank if the line is empty or consists of |
| 2898 | only white spaces. |
| 2899 | |
| 2900 | Args: |
| 2901 | line: A line of a string. |
| 2902 | |
| 2903 | Returns: |
| 2904 | True, if the given line is blank. |
| 2905 | """ |
| 2906 | return not line or line.isspace() |
| 2907 | |
| 2908 | |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 2909 | def CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line, |
| 2910 | error): |
| 2911 | is_namespace_indent_item = ( |
| 2912 | len(nesting_state.stack) > 1 and |
| 2913 | nesting_state.stack[-1].check_namespace_indentation and |
| 2914 | isinstance(nesting_state.previous_stack_top, _NamespaceInfo) and |
| 2915 | nesting_state.previous_stack_top == nesting_state.stack[-2]) |
| 2916 | |
| 2917 | if ShouldCheckNamespaceIndentation(nesting_state, is_namespace_indent_item, |
| 2918 | clean_lines.elided, line): |
| 2919 | CheckItemIndentationInNamespace(filename, clean_lines.elided, |
| 2920 | line, error) |
| 2921 | |
| 2922 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2923 | def CheckForFunctionLengths(filename, clean_lines, linenum, |
| 2924 | function_state, error): |
| 2925 | """Reports for long function bodies. |
| 2926 | |
| 2927 | For an overview why this is done, see: |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 2928 | https://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2929 | |
| 2930 | Uses a simplistic algorithm assuming other style guidelines |
| 2931 | (especially spacing) are followed. |
| 2932 | Only checks unindented functions, so class members are unchecked. |
| 2933 | Trivial bodies are unchecked, so constructors with huge initializer lists |
| 2934 | may be missed. |
| 2935 | Blank/comment lines are not counted so as to avoid encouraging the removal |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 2936 | of vertical space and comments just to get through a lint check. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2937 | NOLINT *on the last line of a function* disables this check. |
| 2938 | |
| 2939 | Args: |
| 2940 | filename: The name of the current file. |
| 2941 | clean_lines: A CleansedLines instance containing the file. |
| 2942 | linenum: The number of the line to check. |
| 2943 | function_state: Current function name and lines in body so far. |
| 2944 | error: The function to call with any errors found. |
| 2945 | """ |
| 2946 | lines = clean_lines.lines |
| 2947 | line = lines[linenum] |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2948 | joined_line = '' |
| 2949 | |
| 2950 | starting_func = False |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 2951 | regexp = r'(\w(\w|::|\*|\&|\s)*)\(' # decls * & space::name( ... |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2952 | match_result = Match(regexp, line) |
| 2953 | if match_result: |
| 2954 | # If the name is all caps and underscores, figure it's a macro and |
| 2955 | # ignore it, unless it's TEST or TEST_F. |
| 2956 | function_name = match_result.group(1).split()[-1] |
| 2957 | if function_name == 'TEST' or function_name == 'TEST_F' or ( |
| 2958 | not Match(r'[A-Z_]+$', function_name)): |
| 2959 | starting_func = True |
| 2960 | |
| 2961 | if starting_func: |
| 2962 | body_found = False |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 2963 | for start_linenum in xrange(linenum, clean_lines.NumLines()): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2964 | start_line = lines[start_linenum] |
| 2965 | joined_line += ' ' + start_line.lstrip() |
| 2966 | if Search(r'(;|})', start_line): # Declarations and trivial functions |
| 2967 | body_found = True |
| 2968 | break # ... ignore |
| 2969 | elif Search(r'{', start_line): |
| 2970 | body_found = True |
| 2971 | function = Search(r'((\w|:)*)\(', line).group(1) |
| 2972 | if Match(r'TEST', function): # Handle TEST... macros |
| 2973 | parameter_regexp = Search(r'(\(.*\))', joined_line) |
| 2974 | if parameter_regexp: # Ignore bad syntax |
| 2975 | function += parameter_regexp.group(1) |
| 2976 | else: |
| 2977 | function += '()' |
| 2978 | function_state.Begin(function) |
| 2979 | break |
| 2980 | if not body_found: |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 2981 | # No body for the function (or evidence of a non-function) was found. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2982 | error(filename, linenum, 'readability/fn_size', 5, |
| 2983 | 'Lint failed to find start of function body.') |
| 2984 | elif Match(r'^\}\s*$', line): # function end |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 2985 | function_state.Check(error, filename, linenum) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2986 | function_state.End() |
| 2987 | elif not Match(r'^\s*$', line): |
| 2988 | function_state.Count() # Count non-blank/non-comment lines. |
| 2989 | |
| 2990 | |
| 2991 | _RE_PATTERN_TODO = re.compile(r'^//(\s*)TODO(\(.+?\))?:?(\s|$)?') |
| 2992 | |
| 2993 | |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 2994 | def CheckComment(line, filename, linenum, next_line_start, error): |
| 2995 | """Checks for common mistakes in comments. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2996 | |
| 2997 | Args: |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 2998 | line: The line in question. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 2999 | filename: The name of the current file. |
| 3000 | linenum: The number of the line to check. |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 3001 | next_line_start: The first non-whitespace column of the next line. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3002 | error: The function to call with any errors found. |
| 3003 | """ |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 3004 | commentpos = line.find('//') |
| 3005 | if commentpos != -1: |
| 3006 | # Check if the // may be in quotes. If so, ignore it |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 3007 | if re.sub(r'\\.', '', line[0:commentpos]).count('"') % 2 == 0: |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 3008 | # Allow one space for new scopes, two spaces otherwise: |
| 3009 | if (not (Match(r'^.*{ *//', line) and next_line_start == commentpos) and |
| 3010 | ((commentpos >= 1 and |
| 3011 | line[commentpos-1] not in string.whitespace) or |
| 3012 | (commentpos >= 2 and |
| 3013 | line[commentpos-2] not in string.whitespace))): |
| 3014 | error(filename, linenum, 'whitespace/comments', 2, |
| 3015 | 'At least two spaces is best between code and comments') |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3016 | |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 3017 | # Checks for common mistakes in TODO comments. |
| 3018 | comment = line[commentpos:] |
| 3019 | match = _RE_PATTERN_TODO.match(comment) |
| 3020 | if match: |
| 3021 | # One whitespace is correct; zero whitespace is handled elsewhere. |
| 3022 | leading_whitespace = match.group(1) |
| 3023 | if len(leading_whitespace) > 1: |
| 3024 | error(filename, linenum, 'whitespace/todo', 2, |
| 3025 | 'Too many spaces before TODO') |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3026 | |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 3027 | username = match.group(2) |
| 3028 | if not username: |
| 3029 | error(filename, linenum, 'readability/todo', 2, |
| 3030 | 'Missing username in TODO; it should look like ' |
| 3031 | '"// TODO(my_username): Stuff."') |
| 3032 | |
| 3033 | middle_whitespace = match.group(3) |
| 3034 | # Comparisons made explicit for correctness -- pylint: disable=g-explicit-bool-comparison |
| 3035 | if middle_whitespace != ' ' and middle_whitespace != '': |
| 3036 | error(filename, linenum, 'whitespace/todo', 2, |
| 3037 | 'TODO(my_username) should be followed by a space') |
| 3038 | |
| 3039 | # If the comment contains an alphanumeric character, there |
[email protected] | 255f2be | 2014-12-05 22:19:55 | [diff] [blame] | 3040 | # should be a space somewhere between it and the // unless |
| 3041 | # it's a /// or //! Doxygen comment. |
| 3042 | if (Match(r'//[^ ]*\w', comment) and |
| 3043 | not Match(r'(///|//\!)(\s+|$)', comment)): |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 3044 | error(filename, linenum, 'whitespace/comments', 4, |
| 3045 | 'Should have a space between // and comment') |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3046 | |
[email protected] | 255f2be | 2014-12-05 22:19:55 | [diff] [blame] | 3047 | |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 3048 | def CheckAccess(filename, clean_lines, linenum, nesting_state, error): |
| 3049 | """Checks for improper use of DISALLOW* macros. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3050 | |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 3051 | Args: |
| 3052 | filename: The name of the current file. |
| 3053 | clean_lines: A CleansedLines instance containing the file. |
| 3054 | linenum: The number of the line to check. |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 3055 | nesting_state: A NestingState instance which maintains information about |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 3056 | the current stack of nested blocks being parsed. |
| 3057 | error: The function to call with any errors found. |
| 3058 | """ |
| 3059 | line = clean_lines.elided[linenum] # get rid of comments and strings |
| 3060 | |
| 3061 | matched = Match((r'\s*(DISALLOW_COPY_AND_ASSIGN|' |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 3062 | r'DISALLOW_IMPLICIT_CONSTRUCTORS)'), line) |
| 3063 | if not matched: |
| 3064 | return |
| 3065 | if nesting_state.stack and isinstance(nesting_state.stack[-1], _ClassInfo): |
| 3066 | if nesting_state.stack[-1].access != 'private': |
| 3067 | error(filename, linenum, 'readability/constructors', 3, |
| 3068 | '%s must be in the private: section' % matched.group(1)) |
| 3069 | |
| 3070 | else: |
| 3071 | # Found DISALLOW* macro outside a class declaration, or perhaps it |
| 3072 | # was used inside a function when it should have been part of the |
| 3073 | # class declaration. We could issue a warning here, but it |
| 3074 | # probably resulted in a compiler error already. |
| 3075 | pass |
| 3076 | |
| 3077 | |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 3078 | def CheckSpacing(filename, clean_lines, linenum, nesting_state, error): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3079 | """Checks for the correctness of various spacing issues in the code. |
| 3080 | |
| 3081 | Things we check for: spaces around operators, spaces after |
| 3082 | if/for/while/switch, no spaces around parens in function calls, two |
| 3083 | spaces between code and comment, don't start a block with a blank |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 3084 | line, don't end a function with a blank line, don't add a blank line |
| 3085 | after public/protected/private, don't have too many blank lines in a row. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3086 | |
| 3087 | Args: |
| 3088 | filename: The name of the current file. |
| 3089 | clean_lines: A CleansedLines instance containing the file. |
| 3090 | linenum: The number of the line to check. |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 3091 | nesting_state: A NestingState instance which maintains information about |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 3092 | the current stack of nested blocks being parsed. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3093 | error: The function to call with any errors found. |
| 3094 | """ |
| 3095 | |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 3096 | # Don't use "elided" lines here, otherwise we can't check commented lines. |
| 3097 | # Don't want to use "raw" either, because we don't want to check inside C++11 |
| 3098 | # raw strings, |
| 3099 | raw = clean_lines.lines_without_raw_strings |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3100 | line = raw[linenum] |
| 3101 | |
| 3102 | # Before nixing comments, check if the line is blank for no good |
| 3103 | # reason. This includes the first line after a block is opened, and |
| 3104 | # blank lines at the end of a function (ie, right before a line like '}' |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 3105 | # |
| 3106 | # Skip all the blank line checks if we are immediately inside a |
| 3107 | # namespace body. In other words, don't issue blank line warnings |
| 3108 | # for this block: |
| 3109 | # namespace { |
| 3110 | # |
| 3111 | # } |
| 3112 | # |
| 3113 | # A warning about missing end of namespace comments will be issued instead. |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 3114 | # |
| 3115 | # Also skip blank line checks for 'extern "C"' blocks, which are formatted |
| 3116 | # like namespaces. |
| 3117 | if (IsBlankLine(line) and |
| 3118 | not nesting_state.InNamespaceBody() and |
| 3119 | not nesting_state.InExternC()): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3120 | elided = clean_lines.elided |
| 3121 | prev_line = elided[linenum - 1] |
| 3122 | prevbrace = prev_line.rfind('{') |
| 3123 | # TODO(unknown): Don't complain if line before blank line, and line after, |
| 3124 | # both start with alnums and are indented the same amount. |
| 3125 | # This ignores whitespace at the start of a namespace block |
| 3126 | # because those are not usually indented. |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 3127 | if prevbrace != -1 and prev_line[prevbrace:].find('}') == -1: |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3128 | # OK, we have a blank line at the start of a code block. Before we |
| 3129 | # complain, we check if it is an exception to the rule: The previous |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 3130 | # non-empty line has the parameters of a function header that are indented |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3131 | # 4 spaces (because they did not fit in a 80 column line when placed on |
| 3132 | # the same line as the function name). We also check for the case where |
| 3133 | # the previous line is indented 6 spaces, which may happen when the |
| 3134 | # initializers of a constructor do not fit into a 80 column line. |
| 3135 | exception = False |
| 3136 | if Match(r' {6}\w', prev_line): # Initializer list? |
| 3137 | # We are looking for the opening column of initializer list, which |
| 3138 | # should be indented 4 spaces to cause 6 space indentation afterwards. |
| 3139 | search_position = linenum-2 |
| 3140 | while (search_position >= 0 |
| 3141 | and Match(r' {6}\w', elided[search_position])): |
| 3142 | search_position -= 1 |
| 3143 | exception = (search_position >= 0 |
| 3144 | and elided[search_position][:5] == ' :') |
| 3145 | else: |
| 3146 | # Search for the function arguments or an initializer list. We use a |
| 3147 | # simple heuristic here: If the line is indented 4 spaces; and we have a |
| 3148 | # closing paren, without the opening paren, followed by an opening brace |
| 3149 | # or colon (for initializer lists) we assume that it is the last line of |
| 3150 | # a function header. If we have a colon indented 4 spaces, it is an |
| 3151 | # initializer list. |
| 3152 | exception = (Match(r' {4}\w[^\(]*\)\s*(const\s*)?(\{\s*$|:)', |
| 3153 | prev_line) |
| 3154 | or Match(r' {4}:', prev_line)) |
| 3155 | |
| 3156 | if not exception: |
| 3157 | error(filename, linenum, 'whitespace/blank_line', 2, |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 3158 | 'Redundant blank line at the start of a code block ' |
| 3159 | 'should be deleted.') |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 3160 | # Ignore blank lines at the end of a block in a long if-else |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3161 | # chain, like this: |
| 3162 | # if (condition1) { |
| 3163 | # // Something followed by a blank line |
| 3164 | # |
| 3165 | # } else if (condition2) { |
| 3166 | # // Something else |
| 3167 | # } |
| 3168 | if linenum + 1 < clean_lines.NumLines(): |
| 3169 | next_line = raw[linenum + 1] |
| 3170 | if (next_line |
| 3171 | and Match(r'\s*}', next_line) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3172 | and next_line.find('} else ') == -1): |
| 3173 | error(filename, linenum, 'whitespace/blank_line', 3, |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 3174 | 'Redundant blank line at the end of a code block ' |
| 3175 | 'should be deleted.') |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3176 | |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 3177 | matched = Match(r'\s*(public|protected|private):', prev_line) |
| 3178 | if matched: |
| 3179 | error(filename, linenum, 'whitespace/blank_line', 3, |
| 3180 | 'Do not leave a blank line after "%s:"' % matched.group(1)) |
| 3181 | |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 3182 | # Next, check comments |
| 3183 | next_line_start = 0 |
| 3184 | if linenum + 1 < clean_lines.NumLines(): |
| 3185 | next_line = raw[linenum + 1] |
| 3186 | next_line_start = len(next_line) - len(next_line.lstrip()) |
| 3187 | CheckComment(line, filename, linenum, next_line_start, error) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3188 | |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 3189 | # get rid of comments and strings |
| 3190 | line = clean_lines.elided[linenum] |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3191 | |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 3192 | # You shouldn't have spaces before your brackets, except maybe after |
| 3193 | # 'delete []' or 'return []() {};' |
| 3194 | if Search(r'\w\s+\[', line) and not Search(r'(?:delete|return)\s+\[', line): |
| 3195 | error(filename, linenum, 'whitespace/braces', 5, |
| 3196 | 'Extra space before [') |
| 3197 | |
| 3198 | # In range-based for, we wanted spaces before and after the colon, but |
| 3199 | # not around "::" tokens that might appear. |
| 3200 | if (Search(r'for *\(.*[^:]:[^: ]', line) or |
| 3201 | Search(r'for *\(.*[^: ]:[^:]', line)): |
| 3202 | error(filename, linenum, 'whitespace/forcolon', 2, |
| 3203 | 'Missing space around colon in range-based for loop') |
| 3204 | |
| 3205 | |
| 3206 | def CheckOperatorSpacing(filename, clean_lines, linenum, error): |
| 3207 | """Checks for horizontal spacing around operators. |
| 3208 | |
| 3209 | Args: |
| 3210 | filename: The name of the current file. |
| 3211 | clean_lines: A CleansedLines instance containing the file. |
| 3212 | linenum: The number of the line to check. |
| 3213 | error: The function to call with any errors found. |
| 3214 | """ |
| 3215 | line = clean_lines.elided[linenum] |
| 3216 | |
| 3217 | # Don't try to do spacing checks for operator methods. Do this by |
| 3218 | # replacing the troublesome characters with something else, |
| 3219 | # preserving column position for all other characters. |
| 3220 | # |
| 3221 | # The replacement is done repeatedly to avoid false positives from |
| 3222 | # operators that call operators. |
| 3223 | while True: |
| 3224 | match = Match(r'^(.*\boperator\b)(\S+)(\s*\(.*)$', line) |
| 3225 | if match: |
| 3226 | line = match.group(1) + ('_' * len(match.group(2))) + match.group(3) |
| 3227 | else: |
| 3228 | break |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3229 | |
| 3230 | # We allow no-spaces around = within an if: "if ( (a=Foo()) == 0 )". |
| 3231 | # Otherwise not. Note we only check for non-spaces on *both* sides; |
| 3232 | # sometimes people put non-spaces on one side when aligning ='s among |
| 3233 | # many lines (not that this is behavior that I approve of...) |
[email protected] | 255f2be | 2014-12-05 22:19:55 | [diff] [blame] | 3234 | if ((Search(r'[\w.]=', line) or |
| 3235 | Search(r'=[\w.]', line)) |
| 3236 | and not Search(r'\b(if|while|for) ', line) |
| 3237 | # Operators taken from [lex.operators] in C++11 standard. |
| 3238 | and not Search(r'(>=|<=|==|!=|&=|\^=|\|=|\+=|\*=|\/=|\%=)', line) |
| 3239 | and not Search(r'operator=', line)): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3240 | error(filename, linenum, 'whitespace/operators', 4, |
| 3241 | 'Missing spaces around =') |
| 3242 | |
| 3243 | # It's ok not to have spaces around binary operators like + - * /, but if |
| 3244 | # there's too little whitespace, we get concerned. It's hard to tell, |
| 3245 | # though, so we punt on this one for now. TODO. |
| 3246 | |
| 3247 | # You should always have whitespace around binary operators. |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 3248 | # |
| 3249 | # Check <= and >= first to avoid false positives with < and >, then |
| 3250 | # check non-include lines for spacing around < and >. |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 3251 | # |
| 3252 | # If the operator is followed by a comma, assume it's be used in a |
| 3253 | # macro context and don't do any checks. This avoids false |
| 3254 | # positives. |
| 3255 | # |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 3256 | # Note that && is not included here. This is because there are too |
| 3257 | # many false positives due to RValue references. |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 3258 | match = Search(r'[^<>=!\s](==|!=|<=|>=|\|\|)[^<>=!\s,;\)]', line) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3259 | if match: |
| 3260 | error(filename, linenum, 'whitespace/operators', 3, |
| 3261 | 'Missing spaces around %s' % match.group(1)) |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 3262 | elif not Match(r'#.*include', line): |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 3263 | # Look for < that is not surrounded by spaces. This is only |
| 3264 | # triggered if both sides are missing spaces, even though |
| 3265 | # technically should should flag if at least one side is missing a |
| 3266 | # space. This is done to avoid some false positives with shifts. |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 3267 | match = Match(r'^(.*[^\s<])<[^\s=<,]', line) |
| 3268 | if match: |
| 3269 | (_, _, end_pos) = CloseExpression( |
| 3270 | clean_lines, linenum, len(match.group(1))) |
| 3271 | if end_pos <= -1: |
| 3272 | error(filename, linenum, 'whitespace/operators', 3, |
| 3273 | 'Missing spaces around <') |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 3274 | |
| 3275 | # Look for > that is not surrounded by spaces. Similar to the |
| 3276 | # above, we only trigger if both sides are missing spaces to avoid |
| 3277 | # false positives with shifts. |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 3278 | match = Match(r'^(.*[^-\s>])>[^\s=>,]', line) |
| 3279 | if match: |
| 3280 | (_, _, start_pos) = ReverseCloseExpression( |
| 3281 | clean_lines, linenum, len(match.group(1))) |
| 3282 | if start_pos <= -1: |
| 3283 | error(filename, linenum, 'whitespace/operators', 3, |
| 3284 | 'Missing spaces around >') |
| 3285 | |
| 3286 | # We allow no-spaces around << when used like this: 10<<20, but |
| 3287 | # not otherwise (particularly, not when used as streams) |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 3288 | # |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 3289 | # We also allow operators following an opening parenthesis, since |
| 3290 | # those tend to be macros that deal with operators. |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 3291 | match = Search(r'(operator|[^\s(<])(?:L|UL|LL|ULL|l|ul|ll|ull)?<<([^\s,=<])', line) |
[email protected] | 255f2be | 2014-12-05 22:19:55 | [diff] [blame] | 3292 | if (match and not (match.group(1).isdigit() and match.group(2).isdigit()) and |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 3293 | not (match.group(1) == 'operator' and match.group(2) == ';')): |
| 3294 | error(filename, linenum, 'whitespace/operators', 3, |
| 3295 | 'Missing spaces around <<') |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 3296 | |
| 3297 | # We allow no-spaces around >> for almost anything. This is because |
| 3298 | # C++11 allows ">>" to close nested templates, which accounts for |
| 3299 | # most cases when ">>" is not followed by a space. |
| 3300 | # |
| 3301 | # We still warn on ">>" followed by alpha character, because that is |
| 3302 | # likely due to ">>" being used for right shifts, e.g.: |
| 3303 | # value >> alpha |
| 3304 | # |
| 3305 | # When ">>" is used to close templates, the alphanumeric letter that |
| 3306 | # follows would be part of an identifier, and there should still be |
| 3307 | # a space separating the template type and the identifier. |
| 3308 | # type<type<type>> alpha |
| 3309 | match = Search(r'>>[a-zA-Z_]', line) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3310 | if match: |
| 3311 | error(filename, linenum, 'whitespace/operators', 3, |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 3312 | 'Missing spaces around >>') |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3313 | |
| 3314 | # There shouldn't be space around unary operators |
| 3315 | match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line) |
| 3316 | if match: |
| 3317 | error(filename, linenum, 'whitespace/operators', 4, |
| 3318 | 'Extra space for operator %s' % match.group(1)) |
| 3319 | |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 3320 | |
| 3321 | def CheckParenthesisSpacing(filename, clean_lines, linenum, error): |
| 3322 | """Checks for horizontal spacing around parentheses. |
| 3323 | |
| 3324 | Args: |
| 3325 | filename: The name of the current file. |
| 3326 | clean_lines: A CleansedLines instance containing the file. |
| 3327 | linenum: The number of the line to check. |
| 3328 | error: The function to call with any errors found. |
| 3329 | """ |
| 3330 | line = clean_lines.elided[linenum] |
| 3331 | |
| 3332 | # No spaces after an if, while, switch, or for |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3333 | match = Search(r' (if\(|for\(|while\(|switch\()', line) |
| 3334 | if match: |
| 3335 | error(filename, linenum, 'whitespace/parens', 5, |
| 3336 | 'Missing space before ( in %s' % match.group(1)) |
| 3337 | |
| 3338 | # For if/for/while/switch, the left and right parens should be |
| 3339 | # consistent about how many spaces are inside the parens, and |
| 3340 | # there should either be zero or one spaces inside the parens. |
| 3341 | # We don't want: "if ( foo)" or "if ( foo )". |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 3342 | # Exception: "for ( ; foo; bar)" and "for (foo; bar; )" are allowed. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3343 | match = Search(r'\b(if|for|while|switch)\s*' |
| 3344 | r'\(([ ]*)(.).*[^ ]+([ ]*)\)\s*{\s*$', |
| 3345 | line) |
| 3346 | if match: |
| 3347 | if len(match.group(2)) != len(match.group(4)): |
| 3348 | if not (match.group(3) == ';' and |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 3349 | len(match.group(2)) == 1 + len(match.group(4)) or |
| 3350 | not match.group(2) and Search(r'\bfor\s*\(.*; \)', line)): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3351 | error(filename, linenum, 'whitespace/parens', 5, |
| 3352 | 'Mismatching spaces inside () in %s' % match.group(1)) |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 3353 | if len(match.group(2)) not in [0, 1]: |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3354 | error(filename, linenum, 'whitespace/parens', 5, |
| 3355 | 'Should have zero or one spaces inside ( and ) in %s' % |
| 3356 | match.group(1)) |
| 3357 | |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 3358 | |
| 3359 | def CheckCommaSpacing(filename, clean_lines, linenum, error): |
| 3360 | """Checks for horizontal spacing near commas and semicolons. |
| 3361 | |
| 3362 | Args: |
| 3363 | filename: The name of the current file. |
| 3364 | clean_lines: A CleansedLines instance containing the file. |
| 3365 | linenum: The number of the line to check. |
| 3366 | error: The function to call with any errors found. |
| 3367 | """ |
| 3368 | raw = clean_lines.lines_without_raw_strings |
| 3369 | line = clean_lines.elided[linenum] |
| 3370 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3371 | # You should always have a space after a comma (either as fn arg or operator) |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 3372 | # |
| 3373 | # This does not apply when the non-space character following the |
| 3374 | # comma is another comma, since the only time when that happens is |
| 3375 | # for empty macro arguments. |
| 3376 | # |
| 3377 | # We run this check in two passes: first pass on elided lines to |
| 3378 | # verify that lines contain missing whitespaces, second pass on raw |
| 3379 | # lines to confirm that those missing whitespaces are not due to |
| 3380 | # elided comments. |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 3381 | if (Search(r',[^,\s]', ReplaceAll(r'\boperator\s*,\s*\(', 'F(', line)) and |
| 3382 | Search(r',[^,\s]', raw[linenum])): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3383 | error(filename, linenum, 'whitespace/comma', 3, |
| 3384 | 'Missing space after ,') |
| 3385 | |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 3386 | # You should always have a space after a semicolon |
| 3387 | # except for few corner cases |
| 3388 | # TODO(unknown): clarify if 'if (1) { return 1;}' is requires one more |
| 3389 | # space after ; |
| 3390 | if Search(r';[^\s};\\)/]', line): |
| 3391 | error(filename, linenum, 'whitespace/semicolon', 3, |
| 3392 | 'Missing space after ;') |
| 3393 | |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 3394 | |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 3395 | def _IsType(clean_lines, nesting_state, expr): |
| 3396 | """Check if expression looks like a type name, returns true if so. |
| 3397 | |
| 3398 | Args: |
| 3399 | clean_lines: A CleansedLines instance containing the file. |
| 3400 | nesting_state: A NestingState instance which maintains information about |
| 3401 | the current stack of nested blocks being parsed. |
| 3402 | expr: The expression to check. |
| 3403 | Returns: |
| 3404 | True, if token looks like a type. |
| 3405 | """ |
| 3406 | # Keep only the last token in the expression |
| 3407 | last_word = Match(r'^.*(\b\S+)$', expr) |
| 3408 | if last_word: |
| 3409 | token = last_word.group(1) |
| 3410 | else: |
| 3411 | token = expr |
| 3412 | |
| 3413 | # Match native types and stdint types |
| 3414 | if _TYPES.match(token): |
| 3415 | return True |
| 3416 | |
| 3417 | # Try a bit harder to match templated types. Walk up the nesting |
| 3418 | # stack until we find something that resembles a typename |
| 3419 | # declaration for what we are looking for. |
| 3420 | typename_pattern = (r'\b(?:typename|class|struct)\s+' + re.escape(token) + |
| 3421 | r'\b') |
| 3422 | block_index = len(nesting_state.stack) - 1 |
| 3423 | while block_index >= 0: |
| 3424 | if isinstance(nesting_state.stack[block_index], _NamespaceInfo): |
| 3425 | return False |
| 3426 | |
| 3427 | # Found where the opening brace is. We want to scan from this |
| 3428 | # line up to the beginning of the function, minus a few lines. |
| 3429 | # template <typename Type1, // stop scanning here |
| 3430 | # ...> |
| 3431 | # class C |
| 3432 | # : public ... { // start scanning here |
| 3433 | last_line = nesting_state.stack[block_index].starting_linenum |
| 3434 | |
| 3435 | next_block_start = 0 |
| 3436 | if block_index > 0: |
| 3437 | next_block_start = nesting_state.stack[block_index - 1].starting_linenum |
| 3438 | first_line = last_line |
| 3439 | while first_line >= next_block_start: |
| 3440 | if clean_lines.elided[first_line].find('template') >= 0: |
| 3441 | break |
| 3442 | first_line -= 1 |
| 3443 | if first_line < next_block_start: |
| 3444 | # Didn't find any "template" keyword before reaching the next block, |
| 3445 | # there are probably no template things to check for this block |
| 3446 | block_index -= 1 |
| 3447 | continue |
| 3448 | |
| 3449 | # Look for typename in the specified range |
| 3450 | for i in xrange(first_line, last_line + 1, 1): |
| 3451 | if Search(typename_pattern, clean_lines.elided[i]): |
| 3452 | return True |
| 3453 | block_index -= 1 |
| 3454 | |
| 3455 | return False |
| 3456 | |
| 3457 | |
| 3458 | def CheckBracesSpacing(filename, clean_lines, linenum, nesting_state, error): |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 3459 | """Checks for horizontal spacing near commas. |
| 3460 | |
| 3461 | Args: |
| 3462 | filename: The name of the current file. |
| 3463 | clean_lines: A CleansedLines instance containing the file. |
| 3464 | linenum: The number of the line to check. |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 3465 | nesting_state: A NestingState instance which maintains information about |
| 3466 | the current stack of nested blocks being parsed. |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 3467 | error: The function to call with any errors found. |
| 3468 | """ |
| 3469 | line = clean_lines.elided[linenum] |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3470 | |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 3471 | # Except after an opening paren, or after another opening brace (in case of |
| 3472 | # an initializer list, for instance), you should have spaces before your |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 3473 | # braces when they are delimiting blocks, classes, namespaces etc. |
| 3474 | # And since you should never have braces at the beginning of a line, |
| 3475 | # this is an easy test. Except that braces used for initialization don't |
| 3476 | # follow the same rule; we often don't want spaces before those. |
[email protected] | 255f2be | 2014-12-05 22:19:55 | [diff] [blame] | 3477 | match = Match(r'^(.*[^ ({>]){', line) |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 3478 | |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 3479 | if match: |
| 3480 | # Try a bit harder to check for brace initialization. This |
| 3481 | # happens in one of the following forms: |
| 3482 | # Constructor() : initializer_list_{} { ... } |
| 3483 | # Constructor{}.MemberFunction() |
| 3484 | # Type variable{}; |
| 3485 | # FunctionCall(type{}, ...); |
| 3486 | # LastArgument(..., type{}); |
| 3487 | # LOG(INFO) << type{} << " ..."; |
| 3488 | # map_of_type[{...}] = ...; |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 3489 | # ternary = expr ? new type{} : nullptr; |
| 3490 | # OuterTemplate<InnerTemplateConstructor<Type>{}> |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 3491 | # |
| 3492 | # We check for the character following the closing brace, and |
| 3493 | # silence the warning if it's one of those listed above, i.e. |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 3494 | # "{.;,)<>]:". |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 3495 | # |
| 3496 | # To account for nested initializer list, we allow any number of |
| 3497 | # closing braces up to "{;,)<". We can't simply silence the |
| 3498 | # warning on first sight of closing brace, because that would |
| 3499 | # cause false negatives for things that are not initializer lists. |
| 3500 | # Silence this: But not this: |
| 3501 | # Outer{ if (...) { |
| 3502 | # Inner{...} if (...){ // Missing space before { |
| 3503 | # }; } |
| 3504 | # |
| 3505 | # There is a false negative with this approach if people inserted |
| 3506 | # spurious semicolons, e.g. "if (cond){};", but we will catch the |
| 3507 | # spurious semicolon with a separate check. |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 3508 | leading_text = match.group(1) |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 3509 | (endline, endlinenum, endpos) = CloseExpression( |
| 3510 | clean_lines, linenum, len(match.group(1))) |
| 3511 | trailing_text = '' |
| 3512 | if endpos > -1: |
| 3513 | trailing_text = endline[endpos:] |
| 3514 | for offset in xrange(endlinenum + 1, |
| 3515 | min(endlinenum + 3, clean_lines.NumLines() - 1)): |
| 3516 | trailing_text += clean_lines.elided[offset] |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 3517 | # We also suppress warnings for `uint64_t{expression}` etc., as the style |
| 3518 | # guide recommends brace initialization for integral types to avoid |
| 3519 | # overflow/truncation. |
| 3520 | if (not Match(r'^[\s}]*[{.;,)<>\]:]', trailing_text) |
| 3521 | and not _IsType(clean_lines, nesting_state, leading_text)): |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 3522 | error(filename, linenum, 'whitespace/braces', 5, |
| 3523 | 'Missing space before {') |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3524 | |
| 3525 | # Make sure '} else {' has spaces. |
| 3526 | if Search(r'}else', line): |
| 3527 | error(filename, linenum, 'whitespace/braces', 5, |
| 3528 | 'Missing space before else') |
| 3529 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3530 | # You shouldn't have a space before a semicolon at the end of the line. |
| 3531 | # There's a special case for "for" since the style guide allows space before |
| 3532 | # the semicolon there. |
| 3533 | if Search(r':\s*;\s*$', line): |
| 3534 | error(filename, linenum, 'whitespace/semicolon', 5, |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 3535 | 'Semicolon defining empty statement. Use {} instead.') |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3536 | elif Search(r'^\s*;\s*$', line): |
| 3537 | error(filename, linenum, 'whitespace/semicolon', 5, |
| 3538 | 'Line contains only semicolon. If this should be an empty statement, ' |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 3539 | 'use {} instead.') |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3540 | elif (Search(r'\s+;\s*$', line) and |
| 3541 | not Search(r'\bfor\b', line)): |
| 3542 | error(filename, linenum, 'whitespace/semicolon', 5, |
| 3543 | 'Extra space before last semicolon. If this should be an empty ' |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 3544 | 'statement, use {} instead.') |
| 3545 | |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 3546 | |
| 3547 | def IsDecltype(clean_lines, linenum, column): |
| 3548 | """Check if the token ending on (linenum, column) is decltype(). |
| 3549 | |
| 3550 | Args: |
| 3551 | clean_lines: A CleansedLines instance containing the file. |
| 3552 | linenum: the number of the line to check. |
| 3553 | column: end column of the token to check. |
| 3554 | Returns: |
| 3555 | True if this token is decltype() expression, False otherwise. |
| 3556 | """ |
| 3557 | (text, _, start_col) = ReverseCloseExpression(clean_lines, linenum, column) |
| 3558 | if start_col < 0: |
| 3559 | return False |
| 3560 | if Search(r'\bdecltype\s*$', text[0:start_col]): |
| 3561 | return True |
| 3562 | return False |
| 3563 | |
| 3564 | |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 3565 | def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error): |
| 3566 | """Checks for additional blank line issues related to sections. |
| 3567 | |
| 3568 | Currently the only thing checked here is blank line before protected/private. |
| 3569 | |
| 3570 | Args: |
| 3571 | filename: The name of the current file. |
| 3572 | clean_lines: A CleansedLines instance containing the file. |
| 3573 | class_info: A _ClassInfo objects. |
| 3574 | linenum: The number of the line to check. |
| 3575 | error: The function to call with any errors found. |
| 3576 | """ |
| 3577 | # Skip checks if the class is small, where small means 25 lines or less. |
| 3578 | # 25 lines seems like a good cutoff since that's the usual height of |
| 3579 | # terminals, and any class that can't fit in one screen can't really |
| 3580 | # be considered "small". |
| 3581 | # |
| 3582 | # Also skip checks if we are on the first line. This accounts for |
| 3583 | # classes that look like |
| 3584 | # class Foo { public: ... }; |
| 3585 | # |
| 3586 | # If we didn't find the end of the class, last_line would be zero, |
| 3587 | # and the check will be skipped by the first condition. |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 3588 | if (class_info.last_line - class_info.starting_linenum <= 24 or |
| 3589 | linenum <= class_info.starting_linenum): |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 3590 | return |
| 3591 | |
| 3592 | matched = Match(r'\s*(public|protected|private):', clean_lines.lines[linenum]) |
| 3593 | if matched: |
| 3594 | # Issue warning if the line before public/protected/private was |
| 3595 | # not a blank line, but don't do this if the previous line contains |
| 3596 | # "class" or "struct". This can happen two ways: |
| 3597 | # - We are at the beginning of the class. |
| 3598 | # - We are forward-declaring an inner class that is semantically |
| 3599 | # private, but needed to be public for implementation reasons. |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 3600 | # Also ignores cases where the previous line ends with a backslash as can be |
| 3601 | # common when defining classes in C macros. |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 3602 | prev_line = clean_lines.lines[linenum - 1] |
| 3603 | if (not IsBlankLine(prev_line) and |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 3604 | not Search(r'\b(class|struct)\b', prev_line) and |
| 3605 | not Search(r'\\$', prev_line)): |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 3606 | # Try a bit harder to find the beginning of the class. This is to |
| 3607 | # account for multi-line base-specifier lists, e.g.: |
| 3608 | # class Derived |
| 3609 | # : public Base { |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 3610 | end_class_head = class_info.starting_linenum |
| 3611 | for i in range(class_info.starting_linenum, linenum): |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 3612 | if Search(r'\{\s*$', clean_lines.lines[i]): |
| 3613 | end_class_head = i |
| 3614 | break |
| 3615 | if end_class_head < linenum - 1: |
| 3616 | error(filename, linenum, 'whitespace/blank_line', 3, |
| 3617 | '"%s:" should be preceded by a blank line' % matched.group(1)) |
| 3618 | |
| 3619 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3620 | def GetPreviousNonBlankLine(clean_lines, linenum): |
| 3621 | """Return the most recent non-blank line and its line number. |
| 3622 | |
| 3623 | Args: |
| 3624 | clean_lines: A CleansedLines instance containing the file contents. |
| 3625 | linenum: The number of the line to check. |
| 3626 | |
| 3627 | Returns: |
| 3628 | A tuple with two elements. The first element is the contents of the last |
| 3629 | non-blank line before the current line, or the empty string if this is the |
| 3630 | first non-blank line. The second is the line number of that line, or -1 |
| 3631 | if this is the first non-blank line. |
| 3632 | """ |
| 3633 | |
| 3634 | prevlinenum = linenum - 1 |
| 3635 | while prevlinenum >= 0: |
| 3636 | prevline = clean_lines.elided[prevlinenum] |
| 3637 | if not IsBlankLine(prevline): # if not a blank line... |
| 3638 | return (prevline, prevlinenum) |
| 3639 | prevlinenum -= 1 |
| 3640 | return ('', -1) |
| 3641 | |
| 3642 | |
| 3643 | def CheckBraces(filename, clean_lines, linenum, error): |
| 3644 | """Looks for misplaced braces (e.g. at the end of line). |
| 3645 | |
| 3646 | Args: |
| 3647 | filename: The name of the current file. |
| 3648 | clean_lines: A CleansedLines instance containing the file. |
| 3649 | linenum: The number of the line to check. |
| 3650 | error: The function to call with any errors found. |
| 3651 | """ |
| 3652 | |
| 3653 | line = clean_lines.elided[linenum] # get rid of comments and strings |
| 3654 | |
| 3655 | if Match(r'\s*{\s*$', line): |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 3656 | # We allow an open brace to start a line in the case where someone is using |
| 3657 | # braces in a block to explicitly create a new scope, which is commonly used |
| 3658 | # to control the lifetime of stack-allocated variables. Braces are also |
| 3659 | # used for brace initializers inside function calls. We don't detect this |
| 3660 | # perfectly: we just don't complain if the last non-whitespace character on |
| 3661 | # the previous non-blank line is ',', ';', ':', '(', '{', or '}', or if the |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 3662 | # previous line starts a preprocessor block. We also allow a brace on the |
| 3663 | # following line if it is part of an array initialization and would not fit |
| 3664 | # within the 80 character limit of the preceding line. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3665 | prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 3666 | if (not Search(r'[,;:}{(]\s*$', prevline) and |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 3667 | not Match(r'\s*#', prevline) and |
| 3668 | not (GetLineWidth(prevline) > _line_length - 2 and '[]' in prevline)): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3669 | error(filename, linenum, 'whitespace/braces', 4, |
| 3670 | '{ should almost always be at the end of the previous line') |
| 3671 | |
| 3672 | # An else clause should be on the same line as the preceding closing brace. |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 3673 | if Match(r'\s*else\b\s*(?:if\b|\{|$)', line): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3674 | prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] |
| 3675 | if Match(r'\s*}\s*$', prevline): |
| 3676 | error(filename, linenum, 'whitespace/newline', 4, |
| 3677 | 'An else should appear on the same line as the preceding }') |
| 3678 | |
| 3679 | # If braces come on one side of an else, they should be on both. |
| 3680 | # However, we have to worry about "else if" that spans multiple lines! |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 3681 | if Search(r'else if\s*\(', line): # could be multi-line if |
| 3682 | brace_on_left = bool(Search(r'}\s*else if\s*\(', line)) |
| 3683 | # find the ( after the if |
| 3684 | pos = line.find('else if') |
| 3685 | pos = line.find('(', pos) |
| 3686 | if pos > 0: |
| 3687 | (endline, _, endpos) = CloseExpression(clean_lines, linenum, pos) |
| 3688 | brace_on_right = endline[endpos:].find('{') != -1 |
| 3689 | if brace_on_left != brace_on_right: # must be brace after if |
| 3690 | error(filename, linenum, 'readability/braces', 5, |
| 3691 | 'If an else has a brace on one side, it should have it on both') |
| 3692 | elif Search(r'}\s*else[^{]*$', line) or Match(r'[^}]*else\s*{', line): |
| 3693 | error(filename, linenum, 'readability/braces', 5, |
| 3694 | 'If an else has a brace on one side, it should have it on both') |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3695 | |
| 3696 | # Likewise, an else should never have the else clause on the same line |
| 3697 | if Search(r'\belse [^\s{]', line) and not Search(r'\belse if\b', line): |
| 3698 | error(filename, linenum, 'whitespace/newline', 4, |
| 3699 | 'Else clause should never be on same line as else (use 2 lines)') |
| 3700 | |
| 3701 | # In the same way, a do/while should never be on one line |
| 3702 | if Match(r'\s*do [^\s{]', line): |
| 3703 | error(filename, linenum, 'whitespace/newline', 4, |
| 3704 | 'do/while clauses should not be on a single line') |
| 3705 | |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 3706 | # Check single-line if/else bodies. The style guide says 'curly braces are not |
| 3707 | # required for single-line statements'. We additionally allow multi-line, |
| 3708 | # single statements, but we reject anything with more than one semicolon in |
| 3709 | # it. This means that the first semicolon after the if should be at the end of |
| 3710 | # its line, and the line after that should have an indent level equal to or |
| 3711 | # lower than the if. We also check for ambiguous if/else nesting without |
| 3712 | # braces. |
| 3713 | if_else_match = Search(r'\b(if\s*\(|else\b)', line) |
| 3714 | if if_else_match and not Match(r'\s*#', line): |
| 3715 | if_indent = GetIndentLevel(line) |
| 3716 | endline, endlinenum, endpos = line, linenum, if_else_match.end() |
| 3717 | if_match = Search(r'\bif\s*\(', line) |
| 3718 | if if_match: |
| 3719 | # This could be a multiline if condition, so find the end first. |
| 3720 | pos = if_match.end() - 1 |
| 3721 | (endline, endlinenum, endpos) = CloseExpression(clean_lines, linenum, pos) |
| 3722 | # Check for an opening brace, either directly after the if or on the next |
| 3723 | # line. If found, this isn't a single-statement conditional. |
| 3724 | if (not Match(r'\s*{', endline[endpos:]) |
| 3725 | and not (Match(r'\s*$', endline[endpos:]) |
| 3726 | and endlinenum < (len(clean_lines.elided) - 1) |
| 3727 | and Match(r'\s*{', clean_lines.elided[endlinenum + 1]))): |
| 3728 | while (endlinenum < len(clean_lines.elided) |
| 3729 | and ';' not in clean_lines.elided[endlinenum][endpos:]): |
| 3730 | endlinenum += 1 |
| 3731 | endpos = 0 |
| 3732 | if endlinenum < len(clean_lines.elided): |
| 3733 | endline = clean_lines.elided[endlinenum] |
| 3734 | # We allow a mix of whitespace and closing braces (e.g. for one-liner |
| 3735 | # methods) and a single \ after the semicolon (for macros) |
| 3736 | endpos = endline.find(';') |
| 3737 | if not Match(r';[\s}]*(\\?)$', endline[endpos:]): |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 3738 | # Semicolon isn't the last character, there's something trailing. |
| 3739 | # Output a warning if the semicolon is not contained inside |
| 3740 | # a lambda expression. |
| 3741 | if not Match(r'^[^{};]*\[[^\[\]]*\][^{}]*\{[^{}]*\}\s*\)*[;,]\s*$', |
| 3742 | endline): |
| 3743 | error(filename, linenum, 'readability/braces', 4, |
| 3744 | 'If/else bodies with multiple statements require braces') |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 3745 | elif endlinenum < len(clean_lines.elided) - 1: |
| 3746 | # Make sure the next line is dedented |
| 3747 | next_line = clean_lines.elided[endlinenum + 1] |
| 3748 | next_indent = GetIndentLevel(next_line) |
| 3749 | # With ambiguous nested if statements, this will error out on the |
| 3750 | # if that *doesn't* match the else, regardless of whether it's the |
| 3751 | # inner one or outer one. |
| 3752 | if (if_match and Match(r'\s*else\b', next_line) |
| 3753 | and next_indent != if_indent): |
| 3754 | error(filename, linenum, 'readability/braces', 4, |
| 3755 | 'Else clause should be indented at the same level as if. ' |
| 3756 | 'Ambiguous nested if/else chains require braces.') |
| 3757 | elif next_indent > if_indent: |
| 3758 | error(filename, linenum, 'readability/braces', 4, |
| 3759 | 'If/else bodies with multiple statements require braces') |
| 3760 | |
| 3761 | |
| 3762 | def CheckTrailingSemicolon(filename, clean_lines, linenum, error): |
| 3763 | """Looks for redundant trailing semicolon. |
| 3764 | |
| 3765 | Args: |
| 3766 | filename: The name of the current file. |
| 3767 | clean_lines: A CleansedLines instance containing the file. |
| 3768 | linenum: The number of the line to check. |
| 3769 | error: The function to call with any errors found. |
| 3770 | """ |
| 3771 | |
| 3772 | line = clean_lines.elided[linenum] |
| 3773 | |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 3774 | # Block bodies should not be followed by a semicolon. Due to C++11 |
| 3775 | # brace initialization, there are more places where semicolons are |
| 3776 | # required than not, so we use a whitelist approach to check these |
| 3777 | # rather than a blacklist. These are the places where "};" should |
| 3778 | # be replaced by just "}": |
| 3779 | # 1. Some flavor of block following closing parenthesis: |
| 3780 | # for (;;) {}; |
| 3781 | # while (...) {}; |
| 3782 | # switch (...) {}; |
| 3783 | # Function(...) {}; |
| 3784 | # if (...) {}; |
| 3785 | # if (...) else if (...) {}; |
| 3786 | # |
| 3787 | # 2. else block: |
| 3788 | # if (...) else {}; |
| 3789 | # |
| 3790 | # 3. const member function: |
| 3791 | # Function(...) const {}; |
| 3792 | # |
| 3793 | # 4. Block following some statement: |
| 3794 | # x = 42; |
| 3795 | # {}; |
| 3796 | # |
| 3797 | # 5. Block at the beginning of a function: |
| 3798 | # Function(...) { |
| 3799 | # {}; |
| 3800 | # } |
| 3801 | # |
| 3802 | # Note that naively checking for the preceding "{" will also match |
| 3803 | # braces inside multi-dimensional arrays, but this is fine since |
| 3804 | # that expression will not contain semicolons. |
| 3805 | # |
| 3806 | # 6. Block following another block: |
| 3807 | # while (true) {} |
| 3808 | # {}; |
| 3809 | # |
| 3810 | # 7. End of namespaces: |
| 3811 | # namespace {}; |
| 3812 | # |
| 3813 | # These semicolons seems far more common than other kinds of |
| 3814 | # redundant semicolons, possibly due to people converting classes |
| 3815 | # to namespaces. For now we do not warn for this case. |
| 3816 | # |
| 3817 | # Try matching case 1 first. |
| 3818 | match = Match(r'^(.*\)\s*)\{', line) |
| 3819 | if match: |
| 3820 | # Matched closing parenthesis (case 1). Check the token before the |
| 3821 | # matching opening parenthesis, and don't warn if it looks like a |
| 3822 | # macro. This avoids these false positives: |
| 3823 | # - macro that defines a base class |
| 3824 | # - multi-line macro that defines a base class |
| 3825 | # - macro that defines the whole class-head |
| 3826 | # |
| 3827 | # But we still issue warnings for macros that we know are safe to |
| 3828 | # warn, specifically: |
| 3829 | # - TEST, TEST_F, TEST_P, MATCHER, MATCHER_P |
| 3830 | # - TYPED_TEST |
| 3831 | # - INTERFACE_DEF |
| 3832 | # - EXCLUSIVE_LOCKS_REQUIRED, SHARED_LOCKS_REQUIRED, LOCKS_EXCLUDED: |
| 3833 | # |
| 3834 | # We implement a whitelist of safe macros instead of a blacklist of |
| 3835 | # unsafe macros, even though the latter appears less frequently in |
| 3836 | # google code and would have been easier to implement. This is because |
| 3837 | # the downside for getting the whitelist wrong means some extra |
| 3838 | # semicolons, while the downside for getting the blacklist wrong |
| 3839 | # would result in compile errors. |
| 3840 | # |
[email protected] | 255f2be | 2014-12-05 22:19:55 | [diff] [blame] | 3841 | # In addition to macros, we also don't want to warn on |
| 3842 | # - Compound literals |
| 3843 | # - Lambdas |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 3844 | # - alignas specifier with anonymous structs |
| 3845 | # - decltype |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 3846 | closing_brace_pos = match.group(1).rfind(')') |
| 3847 | opening_parenthesis = ReverseCloseExpression( |
| 3848 | clean_lines, linenum, closing_brace_pos) |
| 3849 | if opening_parenthesis[2] > -1: |
| 3850 | line_prefix = opening_parenthesis[0][0:opening_parenthesis[2]] |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 3851 | macro = Search(r'\b([A-Z_][A-Z0-9_]*)\s*$', line_prefix) |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 3852 | func = Match(r'^(.*\])\s*$', line_prefix) |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 3853 | if ((macro and |
| 3854 | macro.group(1) not in ( |
| 3855 | 'TEST', 'TEST_F', 'MATCHER', 'MATCHER_P', 'TYPED_TEST', |
| 3856 | 'EXCLUSIVE_LOCKS_REQUIRED', 'SHARED_LOCKS_REQUIRED', |
| 3857 | 'LOCKS_EXCLUDED', 'INTERFACE_DEF')) or |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 3858 | (func and not Search(r'\boperator\s*\[\s*\]', func.group(1))) or |
[email protected] | 255f2be | 2014-12-05 22:19:55 | [diff] [blame] | 3859 | Search(r'\b(?:struct|union)\s+alignas\s*$', line_prefix) or |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 3860 | Search(r'\bdecltype$', line_prefix) or |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 3861 | Search(r'\s+=\s*$', line_prefix)): |
| 3862 | match = None |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 3863 | if (match and |
| 3864 | opening_parenthesis[1] > 1 and |
| 3865 | Search(r'\]\s*$', clean_lines.elided[opening_parenthesis[1] - 1])): |
| 3866 | # Multi-line lambda-expression |
| 3867 | match = None |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 3868 | |
| 3869 | else: |
| 3870 | # Try matching cases 2-3. |
| 3871 | match = Match(r'^(.*(?:else|\)\s*const)\s*)\{', line) |
| 3872 | if not match: |
| 3873 | # Try matching cases 4-6. These are always matched on separate lines. |
| 3874 | # |
| 3875 | # Note that we can't simply concatenate the previous line to the |
| 3876 | # current line and do a single match, otherwise we may output |
| 3877 | # duplicate warnings for the blank line case: |
| 3878 | # if (cond) { |
| 3879 | # // blank line |
| 3880 | # } |
| 3881 | prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] |
| 3882 | if prevline and Search(r'[;{}]\s*$', prevline): |
| 3883 | match = Match(r'^(\s*)\{', line) |
| 3884 | |
| 3885 | # Check matching closing brace |
| 3886 | if match: |
| 3887 | (endline, endlinenum, endpos) = CloseExpression( |
| 3888 | clean_lines, linenum, len(match.group(1))) |
| 3889 | if endpos > -1 and Match(r'^\s*;', endline[endpos:]): |
| 3890 | # Current {} pair is eligible for semicolon check, and we have found |
| 3891 | # the redundant semicolon, output warning here. |
| 3892 | # |
| 3893 | # Note: because we are scanning forward for opening braces, and |
| 3894 | # outputting warnings for the matching closing brace, if there are |
| 3895 | # nested blocks with trailing semicolons, we will get the error |
| 3896 | # messages in reversed order. |
| 3897 | error(filename, endlinenum, 'readability/braces', 4, |
| 3898 | "You don't need a ; after a }") |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3899 | |
| 3900 | |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 3901 | def CheckEmptyBlockBody(filename, clean_lines, linenum, error): |
| 3902 | """Look for empty loop/conditional body with only a single semicolon. |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 3903 | |
| 3904 | Args: |
| 3905 | filename: The name of the current file. |
| 3906 | clean_lines: A CleansedLines instance containing the file. |
| 3907 | linenum: The number of the line to check. |
| 3908 | error: The function to call with any errors found. |
| 3909 | """ |
| 3910 | |
| 3911 | # Search for loop keywords at the beginning of the line. Because only |
| 3912 | # whitespaces are allowed before the keywords, this will also ignore most |
| 3913 | # do-while-loops, since those lines should start with closing brace. |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 3914 | # |
| 3915 | # We also check "if" blocks here, since an empty conditional block |
| 3916 | # is likely an error. |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 3917 | line = clean_lines.elided[linenum] |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 3918 | matched = Match(r'\s*(for|while|if)\s*\(', line) |
| 3919 | if matched: |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 3920 | # Find the end of the conditional expression. |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 3921 | (end_line, end_linenum, end_pos) = CloseExpression( |
| 3922 | clean_lines, linenum, line.find('(')) |
| 3923 | |
| 3924 | # Output warning if what follows the condition expression is a semicolon. |
| 3925 | # No warning for all other cases, including whitespace or newline, since we |
| 3926 | # have a separate check for semicolons preceded by whitespace. |
| 3927 | if end_pos >= 0 and Match(r';', end_line[end_pos:]): |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 3928 | if matched.group(1) == 'if': |
| 3929 | error(filename, end_linenum, 'whitespace/empty_conditional_body', 5, |
| 3930 | 'Empty conditional bodies should use {}') |
| 3931 | else: |
| 3932 | error(filename, end_linenum, 'whitespace/empty_loop_body', 5, |
| 3933 | 'Empty loop bodies should use {} or continue') |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 3934 | |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 3935 | # Check for if statements that have completely empty bodies (no comments) |
| 3936 | # and no else clauses. |
| 3937 | if end_pos >= 0 and matched.group(1) == 'if': |
| 3938 | # Find the position of the opening { for the if statement. |
| 3939 | # Return without logging an error if it has no brackets. |
| 3940 | opening_linenum = end_linenum |
| 3941 | opening_line_fragment = end_line[end_pos:] |
| 3942 | # Loop until EOF or find anything that's not whitespace or opening {. |
| 3943 | while not Search(r'^\s*\{', opening_line_fragment): |
| 3944 | if Search(r'^(?!\s*$)', opening_line_fragment): |
| 3945 | # Conditional has no brackets. |
| 3946 | return |
| 3947 | opening_linenum += 1 |
| 3948 | if opening_linenum == len(clean_lines.elided): |
| 3949 | # Couldn't find conditional's opening { or any code before EOF. |
| 3950 | return |
| 3951 | opening_line_fragment = clean_lines.elided[opening_linenum] |
| 3952 | # Set opening_line (opening_line_fragment may not be entire opening line). |
| 3953 | opening_line = clean_lines.elided[opening_linenum] |
| 3954 | |
| 3955 | # Find the position of the closing }. |
| 3956 | opening_pos = opening_line_fragment.find('{') |
| 3957 | if opening_linenum == end_linenum: |
| 3958 | # We need to make opening_pos relative to the start of the entire line. |
| 3959 | opening_pos += end_pos |
| 3960 | (closing_line, closing_linenum, closing_pos) = CloseExpression( |
| 3961 | clean_lines, opening_linenum, opening_pos) |
| 3962 | if closing_pos < 0: |
| 3963 | return |
| 3964 | |
| 3965 | # Now construct the body of the conditional. This consists of the portion |
| 3966 | # of the opening line after the {, all lines until the closing line, |
| 3967 | # and the portion of the closing line before the }. |
| 3968 | if (clean_lines.raw_lines[opening_linenum] != |
| 3969 | CleanseComments(clean_lines.raw_lines[opening_linenum])): |
| 3970 | # Opening line ends with a comment, so conditional isn't empty. |
| 3971 | return |
| 3972 | if closing_linenum > opening_linenum: |
| 3973 | # Opening line after the {. Ignore comments here since we checked above. |
| 3974 | body = list(opening_line[opening_pos+1:]) |
| 3975 | # All lines until closing line, excluding closing line, with comments. |
| 3976 | body.extend(clean_lines.raw_lines[opening_linenum+1:closing_linenum]) |
| 3977 | # Closing line before the }. Won't (and can't) have comments. |
| 3978 | body.append(clean_lines.elided[closing_linenum][:closing_pos-1]) |
| 3979 | body = '\n'.join(body) |
| 3980 | else: |
| 3981 | # If statement has brackets and fits on a single line. |
| 3982 | body = opening_line[opening_pos+1:closing_pos-1] |
| 3983 | |
| 3984 | # Check if the body is empty |
| 3985 | if not _EMPTY_CONDITIONAL_BODY_PATTERN.search(body): |
| 3986 | return |
| 3987 | # The body is empty. Now make sure there's not an else clause. |
| 3988 | current_linenum = closing_linenum |
| 3989 | current_line_fragment = closing_line[closing_pos:] |
| 3990 | # Loop until EOF or find anything that's not whitespace or else clause. |
| 3991 | while Search(r'^\s*$|^(?=\s*else)', current_line_fragment): |
| 3992 | if Search(r'^(?=\s*else)', current_line_fragment): |
| 3993 | # Found an else clause, so don't log an error. |
| 3994 | return |
| 3995 | current_linenum += 1 |
| 3996 | if current_linenum == len(clean_lines.elided): |
| 3997 | break |
| 3998 | current_line_fragment = clean_lines.elided[current_linenum] |
| 3999 | |
| 4000 | # The body is empty and there's no else clause until EOF or other code. |
| 4001 | error(filename, end_linenum, 'whitespace/empty_if_body', 4, |
| 4002 | ('If statement had no body and no else clause')) |
| 4003 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 4004 | |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 4005 | def FindCheckMacro(line): |
| 4006 | """Find a replaceable CHECK-like macro. |
| 4007 | |
| 4008 | Args: |
| 4009 | line: line to search on. |
| 4010 | Returns: |
| 4011 | (macro name, start position), or (None, -1) if no replaceable |
| 4012 | macro is found. |
| 4013 | """ |
| 4014 | for macro in _CHECK_MACROS: |
| 4015 | i = line.find(macro) |
| 4016 | if i >= 0: |
| 4017 | # Find opening parenthesis. Do a regular expression match here |
| 4018 | # to make sure that we are matching the expected CHECK macro, as |
| 4019 | # opposed to some other macro that happens to contain the CHECK |
| 4020 | # substring. |
| 4021 | matched = Match(r'^(.*\b' + macro + r'\s*)\(', line) |
| 4022 | if not matched: |
| 4023 | continue |
| 4024 | return (macro, len(matched.group(1))) |
| 4025 | return (None, -1) |
| 4026 | |
| 4027 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 4028 | def CheckCheck(filename, clean_lines, linenum, error): |
| 4029 | """Checks the use of CHECK and EXPECT macros. |
| 4030 | |
| 4031 | Args: |
| 4032 | filename: The name of the current file. |
| 4033 | clean_lines: A CleansedLines instance containing the file. |
| 4034 | linenum: The number of the line to check. |
| 4035 | error: The function to call with any errors found. |
| 4036 | """ |
| 4037 | |
| 4038 | # Decide the set of replacement macros that should be suggested |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 4039 | lines = clean_lines.elided |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 4040 | (check_macro, start_pos) = FindCheckMacro(lines[linenum]) |
| 4041 | if not check_macro: |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 4042 | return |
| 4043 | |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 4044 | # Find end of the boolean expression by matching parentheses |
| 4045 | (last_line, end_line, end_pos) = CloseExpression( |
| 4046 | clean_lines, linenum, start_pos) |
| 4047 | if end_pos < 0: |
| 4048 | return |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 4049 | |
| 4050 | # If the check macro is followed by something other than a |
| 4051 | # semicolon, assume users will log their own custom error messages |
| 4052 | # and don't suggest any replacements. |
| 4053 | if not Match(r'\s*;', last_line[end_pos:]): |
| 4054 | return |
| 4055 | |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 4056 | if linenum == end_line: |
| 4057 | expression = lines[linenum][start_pos + 1:end_pos - 1] |
| 4058 | else: |
| 4059 | expression = lines[linenum][start_pos + 1:] |
| 4060 | for i in xrange(linenum + 1, end_line): |
| 4061 | expression += lines[i] |
| 4062 | expression += last_line[0:end_pos - 1] |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 4063 | |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 4064 | # Parse expression so that we can take parentheses into account. |
| 4065 | # This avoids false positives for inputs like "CHECK((a < 4) == b)", |
| 4066 | # which is not replaceable by CHECK_LE. |
| 4067 | lhs = '' |
| 4068 | rhs = '' |
| 4069 | operator = None |
| 4070 | while expression: |
| 4071 | matched = Match(r'^\s*(<<|<<=|>>|>>=|->\*|->|&&|\|\||' |
| 4072 | r'==|!=|>=|>|<=|<|\()(.*)$', expression) |
| 4073 | if matched: |
| 4074 | token = matched.group(1) |
| 4075 | if token == '(': |
| 4076 | # Parenthesized operand |
| 4077 | expression = matched.group(2) |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 4078 | (end, _) = FindEndOfExpressionInLine(expression, 0, ['(']) |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 4079 | if end < 0: |
| 4080 | return # Unmatched parenthesis |
| 4081 | lhs += '(' + expression[0:end] |
| 4082 | expression = expression[end:] |
| 4083 | elif token in ('&&', '||'): |
| 4084 | # Logical and/or operators. This means the expression |
| 4085 | # contains more than one term, for example: |
| 4086 | # CHECK(42 < a && a < b); |
| 4087 | # |
| 4088 | # These are not replaceable with CHECK_LE, so bail out early. |
| 4089 | return |
| 4090 | elif token in ('<<', '<<=', '>>', '>>=', '->*', '->'): |
| 4091 | # Non-relational operator |
| 4092 | lhs += token |
| 4093 | expression = matched.group(2) |
| 4094 | else: |
| 4095 | # Relational operator |
| 4096 | operator = token |
| 4097 | rhs = matched.group(2) |
| 4098 | break |
| 4099 | else: |
| 4100 | # Unparenthesized operand. Instead of appending to lhs one character |
| 4101 | # at a time, we do another regular expression match to consume several |
| 4102 | # characters at once if possible. Trivial benchmark shows that this |
| 4103 | # is more efficient when the operands are longer than a single |
| 4104 | # character, which is generally the case. |
| 4105 | matched = Match(r'^([^-=!<>()&|]+)(.*)$', expression) |
| 4106 | if not matched: |
| 4107 | matched = Match(r'^(\s*\S)(.*)$', expression) |
| 4108 | if not matched: |
| 4109 | break |
| 4110 | lhs += matched.group(1) |
| 4111 | expression = matched.group(2) |
| 4112 | |
| 4113 | # Only apply checks if we got all parts of the boolean expression |
| 4114 | if not (lhs and operator and rhs): |
| 4115 | return |
| 4116 | |
| 4117 | # Check that rhs do not contain logical operators. We already know |
| 4118 | # that lhs is fine since the loop above parses out && and ||. |
| 4119 | if rhs.find('&&') > -1 or rhs.find('||') > -1: |
| 4120 | return |
| 4121 | |
| 4122 | # At least one of the operands must be a constant literal. This is |
| 4123 | # to avoid suggesting replacements for unprintable things like |
| 4124 | # CHECK(variable != iterator) |
| 4125 | # |
| 4126 | # The following pattern matches decimal, hex integers, strings, and |
| 4127 | # characters (in that order). |
| 4128 | lhs = lhs.strip() |
| 4129 | rhs = rhs.strip() |
| 4130 | match_constant = r'^([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')$' |
| 4131 | if Match(match_constant, lhs) or Match(match_constant, rhs): |
| 4132 | # Note: since we know both lhs and rhs, we can provide a more |
| 4133 | # descriptive error message like: |
| 4134 | # Consider using CHECK_EQ(x, 42) instead of CHECK(x == 42) |
| 4135 | # Instead of: |
| 4136 | # Consider using CHECK_EQ instead of CHECK(a == b) |
| 4137 | # |
| 4138 | # We are still keeping the less descriptive message because if lhs |
| 4139 | # or rhs gets long, the error message might become unreadable. |
| 4140 | error(filename, linenum, 'readability/check', 2, |
| 4141 | 'Consider using %s instead of %s(a %s b)' % ( |
| 4142 | _CHECK_REPLACEMENT[check_macro][operator], |
| 4143 | check_macro, operator)) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 4144 | |
| 4145 | |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 4146 | def CheckAltTokens(filename, clean_lines, linenum, error): |
| 4147 | """Check alternative keywords being used in boolean expressions. |
| 4148 | |
| 4149 | Args: |
| 4150 | filename: The name of the current file. |
| 4151 | clean_lines: A CleansedLines instance containing the file. |
| 4152 | linenum: The number of the line to check. |
| 4153 | error: The function to call with any errors found. |
| 4154 | """ |
| 4155 | line = clean_lines.elided[linenum] |
| 4156 | |
| 4157 | # Avoid preprocessor lines |
| 4158 | if Match(r'^\s*#', line): |
| 4159 | return |
| 4160 | |
| 4161 | # Last ditch effort to avoid multi-line comments. This will not help |
| 4162 | # if the comment started before the current line or ended after the |
| 4163 | # current line, but it catches most of the false positives. At least, |
| 4164 | # it provides a way to workaround this warning for people who use |
| 4165 | # multi-line comments in preprocessor macros. |
| 4166 | # |
| 4167 | # TODO(unknown): remove this once cpplint has better support for |
| 4168 | # multi-line comments. |
| 4169 | if line.find('/*') >= 0 or line.find('*/') >= 0: |
| 4170 | return |
| 4171 | |
| 4172 | for match in _ALT_TOKEN_REPLACEMENT_PATTERN.finditer(line): |
| 4173 | error(filename, linenum, 'readability/alt_tokens', 2, |
| 4174 | 'Use operator %s instead of %s' % ( |
| 4175 | _ALT_TOKEN_REPLACEMENT[match.group(1)], match.group(1))) |
| 4176 | |
| 4177 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 4178 | def GetLineWidth(line): |
| 4179 | """Determines the width of the line in column positions. |
| 4180 | |
| 4181 | Args: |
| 4182 | line: A string, which may be a Unicode string. |
| 4183 | |
| 4184 | Returns: |
| 4185 | The width of the line in column positions, accounting for Unicode |
| 4186 | combining characters and wide characters. |
| 4187 | """ |
| 4188 | if isinstance(line, unicode): |
| 4189 | width = 0 |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 4190 | for uc in unicodedata.normalize('NFC', line): |
| 4191 | if unicodedata.east_asian_width(uc) in ('W', 'F'): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 4192 | width += 2 |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 4193 | elif not unicodedata.combining(uc): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 4194 | width += 1 |
| 4195 | return width |
| 4196 | else: |
| 4197 | return len(line) |
| 4198 | |
| 4199 | |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 4200 | def CheckStyle(filename, clean_lines, linenum, file_extension, nesting_state, |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 4201 | error): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 4202 | """Checks rules from the 'C++ style rules' section of cppguide.html. |
| 4203 | |
| 4204 | Most of these rules are hard to test (naming, comment style), but we |
| 4205 | do what we can. In particular we check for 2-space indents, line lengths, |
| 4206 | tab usage, spaces inside code, etc. |
| 4207 | |
| 4208 | Args: |
| 4209 | filename: The name of the current file. |
| 4210 | clean_lines: A CleansedLines instance containing the file. |
| 4211 | linenum: The number of the line to check. |
| 4212 | file_extension: The extension (without the dot) of the filename. |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 4213 | nesting_state: A NestingState instance which maintains information about |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 4214 | the current stack of nested blocks being parsed. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 4215 | error: The function to call with any errors found. |
| 4216 | """ |
| 4217 | |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 4218 | # Don't use "elided" lines here, otherwise we can't check commented lines. |
| 4219 | # Don't want to use "raw" either, because we don't want to check inside C++11 |
| 4220 | # raw strings, |
| 4221 | raw_lines = clean_lines.lines_without_raw_strings |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 4222 | line = raw_lines[linenum] |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 4223 | prev = raw_lines[linenum - 1] if linenum > 0 else '' |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 4224 | |
| 4225 | if line.find('\t') != -1: |
| 4226 | error(filename, linenum, 'whitespace/tab', 1, |
| 4227 | 'Tab found; better to use spaces') |
| 4228 | |
| 4229 | # One or three blank spaces at the beginning of the line is weird; it's |
| 4230 | # hard to reconcile that with 2-space indents. |
| 4231 | # NOTE: here are the conditions rob pike used for his tests. Mine aren't |
| 4232 | # as sophisticated, but it may be worth becoming so: RLENGTH==initial_spaces |
| 4233 | # if(RLENGTH > 20) complain = 0; |
| 4234 | # if(match($0, " +(error|private|public|protected):")) complain = 0; |
| 4235 | # if(match(prev, "&& *$")) complain = 0; |
| 4236 | # if(match(prev, "\\|\\| *$")) complain = 0; |
| 4237 | # if(match(prev, "[\",=><] *$")) complain = 0; |
| 4238 | # if(match($0, " <<")) complain = 0; |
| 4239 | # if(match(prev, " +for \\(")) complain = 0; |
| 4240 | # if(prevodd && match(prevprev, " +for \\(")) complain = 0; |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 4241 | scope_or_label_pattern = r'\s*\w+\s*:\s*\\?$' |
| 4242 | classinfo = nesting_state.InnermostClass() |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 4243 | initial_spaces = 0 |
| 4244 | cleansed_line = clean_lines.elided[linenum] |
| 4245 | while initial_spaces < len(line) and line[initial_spaces] == ' ': |
| 4246 | initial_spaces += 1 |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 4247 | # There are certain situations we allow one space, notably for |
| 4248 | # section labels, and also lines containing multi-line raw strings. |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 4249 | # We also don't check for lines that look like continuation lines |
| 4250 | # (of lines ending in double quotes, commas, equals, or angle brackets) |
| 4251 | # because the rules for how to indent those are non-trivial. |
| 4252 | if (not Search(r'[",=><] *$', prev) and |
| 4253 | (initial_spaces == 1 or initial_spaces == 3) and |
| 4254 | not Match(scope_or_label_pattern, cleansed_line) and |
| 4255 | not (clean_lines.raw_lines[linenum] != line and |
| 4256 | Match(r'^\s*""', line))): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 4257 | error(filename, linenum, 'whitespace/indent', 3, |
| 4258 | 'Weird number of spaces at line-start. ' |
| 4259 | 'Are you using a 2-space indent?') |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 4260 | |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 4261 | if line and line[-1].isspace(): |
| 4262 | error(filename, linenum, 'whitespace/end_of_line', 4, |
| 4263 | 'Line ends in whitespace. Consider deleting these extra spaces.') |
| 4264 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 4265 | # Check if the line is a header guard. |
| 4266 | is_header_guard = False |
| 4267 | if file_extension == 'h': |
| 4268 | cppvar = GetHeaderGuardCPPVariable(filename) |
| 4269 | if (line.startswith('#ifndef %s' % cppvar) or |
| 4270 | line.startswith('#define %s' % cppvar) or |
| 4271 | line.startswith('#endif // %s' % cppvar)): |
| 4272 | is_header_guard = True |
| 4273 | # #include lines and header guards can be long, since there's no clean way to |
| 4274 | # split them. |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 4275 | # |
| 4276 | # URLs can be long too. It's possible to split these, but it makes them |
| 4277 | # harder to cut&paste. |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 4278 | # |
| 4279 | # The "$Id:...$" comment may also get very long without it being the |
| 4280 | # developers fault. |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 4281 | if (not line.startswith('#include') and not is_header_guard and |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 4282 | not Match(r'^\s*//.*http(s?)://\S*$', line) and |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 4283 | not Match(r'^\s*//\s*[^\s]*$', line) and |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 4284 | not Match(r'^// \$Id:.*#[0-9]+ \$$', line)): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 4285 | line_width = GetLineWidth(line) |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 4286 | if line_width > _line_length: |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 4287 | error(filename, linenum, 'whitespace/line_length', 2, |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 4288 | 'Lines should be <= %i characters long' % _line_length) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 4289 | |
| 4290 | if (cleansed_line.count(';') > 1 and |
| 4291 | # for loops are allowed two ;'s (and may run over two lines). |
| 4292 | cleansed_line.find('for') == -1 and |
| 4293 | (GetPreviousNonBlankLine(clean_lines, linenum)[0].find('for') == -1 or |
| 4294 | GetPreviousNonBlankLine(clean_lines, linenum)[0].find(';') != -1) and |
| 4295 | # It's ok to have many commands in a switch case that fits in 1 line |
| 4296 | not ((cleansed_line.find('case ') != -1 or |
| 4297 | cleansed_line.find('default:') != -1) and |
| 4298 | cleansed_line.find('break;') != -1)): |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 4299 | error(filename, linenum, 'whitespace/newline', 0, |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 4300 | 'More than one command on the same line') |
| 4301 | |
| 4302 | # Some more style checks |
| 4303 | CheckBraces(filename, clean_lines, linenum, error) |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 4304 | CheckTrailingSemicolon(filename, clean_lines, linenum, error) |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 4305 | CheckEmptyBlockBody(filename, clean_lines, linenum, error) |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 4306 | CheckAccess(filename, clean_lines, linenum, nesting_state, error) |
| 4307 | CheckSpacing(filename, clean_lines, linenum, nesting_state, error) |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 4308 | CheckOperatorSpacing(filename, clean_lines, linenum, error) |
| 4309 | CheckParenthesisSpacing(filename, clean_lines, linenum, error) |
| 4310 | CheckCommaSpacing(filename, clean_lines, linenum, error) |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 4311 | CheckBracesSpacing(filename, clean_lines, linenum, nesting_state, error) |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 4312 | CheckSpacingForFunctionCall(filename, clean_lines, linenum, error) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 4313 | CheckCheck(filename, clean_lines, linenum, error) |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 4314 | CheckAltTokens(filename, clean_lines, linenum, error) |
| 4315 | classinfo = nesting_state.InnermostClass() |
| 4316 | if classinfo: |
| 4317 | CheckSectionSpacing(filename, clean_lines, classinfo, linenum, error) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 4318 | |
| 4319 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 4320 | _RE_PATTERN_INCLUDE = re.compile(r'^\s*#\s*include\s*([<"])([^>"]*)[>"].*$') |
| 4321 | # Matches the first component of a filename delimited by -s and _s. That is: |
| 4322 | # _RE_FIRST_COMPONENT.match('foo').group(0) == 'foo' |
| 4323 | # _RE_FIRST_COMPONENT.match('foo.cc').group(0) == 'foo' |
| 4324 | # _RE_FIRST_COMPONENT.match('foo-bar_baz.cc').group(0) == 'foo' |
| 4325 | # _RE_FIRST_COMPONENT.match('foo_bar-baz.cc').group(0) == 'foo' |
| 4326 | _RE_FIRST_COMPONENT = re.compile(r'^[^-_.]+') |
| 4327 | |
| 4328 | |
| 4329 | def _DropCommonSuffixes(filename): |
| 4330 | """Drops common suffixes like _test.cc or -inl.h from filename. |
| 4331 | |
| 4332 | For example: |
| 4333 | >>> _DropCommonSuffixes('foo/foo-inl.h') |
| 4334 | 'foo/foo' |
| 4335 | >>> _DropCommonSuffixes('foo/bar/foo.cc') |
| 4336 | 'foo/bar/foo' |
| 4337 | >>> _DropCommonSuffixes('foo/foo_internal.h') |
| 4338 | 'foo/foo' |
| 4339 | >>> _DropCommonSuffixes('foo/foo_unusualinternal.h') |
| 4340 | 'foo/foo_unusualinternal' |
| 4341 | |
| 4342 | Args: |
| 4343 | filename: The input filename. |
| 4344 | |
| 4345 | Returns: |
| 4346 | The filename with the common suffix removed. |
| 4347 | """ |
| 4348 | for suffix in ('test.cc', 'regtest.cc', 'unittest.cc', |
| 4349 | 'inl.h', 'impl.h', 'internal.h'): |
| 4350 | if (filename.endswith(suffix) and len(filename) > len(suffix) and |
| 4351 | filename[-len(suffix) - 1] in ('-', '_')): |
| 4352 | return filename[:-len(suffix) - 1] |
| 4353 | return os.path.splitext(filename)[0] |
| 4354 | |
| 4355 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 4356 | def _ClassifyInclude(fileinfo, include, is_system): |
| 4357 | """Figures out what kind of header 'include' is. |
| 4358 | |
| 4359 | Args: |
| 4360 | fileinfo: The current file cpplint is running over. A FileInfo instance. |
| 4361 | include: The path to a #included file. |
| 4362 | is_system: True if the #include used <> rather than "". |
| 4363 | |
| 4364 | Returns: |
| 4365 | One of the _XXX_HEADER constants. |
| 4366 | |
| 4367 | For example: |
| 4368 | >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'stdio.h', True) |
| 4369 | _C_SYS_HEADER |
| 4370 | >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'string', True) |
| 4371 | _CPP_SYS_HEADER |
| 4372 | >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', False) |
| 4373 | _LIKELY_MY_HEADER |
| 4374 | >>> _ClassifyInclude(FileInfo('foo/foo_unknown_extension.cc'), |
| 4375 | ... 'bar/foo_other_ext.h', False) |
| 4376 | _POSSIBLE_MY_HEADER |
| 4377 | >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/bar.h', False) |
| 4378 | _OTHER_HEADER |
| 4379 | """ |
| 4380 | # This is a list of all standard c++ header files, except |
| 4381 | # those already checked for above. |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 4382 | is_cpp_h = include in _CPP_HEADERS |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 4383 | |
| 4384 | if is_system: |
| 4385 | if is_cpp_h: |
| 4386 | return _CPP_SYS_HEADER |
| 4387 | else: |
| 4388 | return _C_SYS_HEADER |
| 4389 | |
| 4390 | # If the target file and the include we're checking share a |
| 4391 | # basename when we drop common extensions, and the include |
| 4392 | # lives in . , then it's likely to be owned by the target file. |
| 4393 | target_dir, target_base = ( |
| 4394 | os.path.split(_DropCommonSuffixes(fileinfo.RepositoryName()))) |
| 4395 | include_dir, include_base = os.path.split(_DropCommonSuffixes(include)) |
| 4396 | if target_base == include_base and ( |
| 4397 | include_dir == target_dir or |
| 4398 | include_dir == os.path.normpath(target_dir + '/../public')): |
| 4399 | return _LIKELY_MY_HEADER |
| 4400 | |
| 4401 | # If the target and include share some initial basename |
| 4402 | # component, it's possible the target is implementing the |
| 4403 | # include, so it's allowed to be first, but we'll never |
| 4404 | # complain if it's not there. |
| 4405 | target_first_component = _RE_FIRST_COMPONENT.match(target_base) |
| 4406 | include_first_component = _RE_FIRST_COMPONENT.match(include_base) |
| 4407 | if (target_first_component and include_first_component and |
| 4408 | target_first_component.group(0) == |
| 4409 | include_first_component.group(0)): |
| 4410 | return _POSSIBLE_MY_HEADER |
| 4411 | |
| 4412 | return _OTHER_HEADER |
| 4413 | |
| 4414 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 4415 | |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 4416 | def CheckIncludeLine(filename, clean_lines, linenum, include_state, error): |
| 4417 | """Check rules that are applicable to #include lines. |
| 4418 | |
| 4419 | Strings on #include lines are NOT removed from elided line, to make |
| 4420 | certain tasks easier. However, to prevent false positives, checks |
| 4421 | applicable to #include lines in CheckLanguage must be put here. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 4422 | |
| 4423 | Args: |
| 4424 | filename: The name of the current file. |
| 4425 | clean_lines: A CleansedLines instance containing the file. |
| 4426 | linenum: The number of the line to check. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 4427 | include_state: An _IncludeState instance in which the headers are inserted. |
| 4428 | error: The function to call with any errors found. |
| 4429 | """ |
| 4430 | fileinfo = FileInfo(filename) |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 4431 | line = clean_lines.lines[linenum] |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 4432 | |
| 4433 | # "include" should use the new style "foo/bar.h" instead of just "bar.h" |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 4434 | # Only do this check if the included header follows google naming |
| 4435 | # conventions. If not, assume that it's a 3rd party API that |
| 4436 | # requires special include conventions. |
| 4437 | # |
| 4438 | # We also make an exception for Lua headers, which follow google |
| 4439 | # naming convention but not the include convention. |
| 4440 | match = Match(r'#include\s*"([^/]+\.h)"', line) |
| 4441 | if match and not _THIRD_PARTY_HEADERS_PATTERN.match(match.group(1)): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 4442 | error(filename, linenum, 'build/include', 4, |
| 4443 | 'Include the directory when naming .h files') |
| 4444 | |
| 4445 | # we shouldn't include a file more than once. actually, there are a |
| 4446 | # handful of instances where doing so is okay, but in general it's |
| 4447 | # not. |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 4448 | match = _RE_PATTERN_INCLUDE.search(line) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 4449 | if match: |
| 4450 | include = match.group(2) |
| 4451 | is_system = (match.group(1) == '<') |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 4452 | duplicate_line = include_state.FindHeader(include) |
| 4453 | if duplicate_line >= 0: |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 4454 | error(filename, linenum, 'build/include', 4, |
| 4455 | '"%s" already included at %s:%s' % |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 4456 | (include, filename, duplicate_line)) |
[email protected] | 255f2be | 2014-12-05 22:19:55 | [diff] [blame] | 4457 | elif (include.endswith('.cc') and |
| 4458 | os.path.dirname(fileinfo.RepositoryName()) != os.path.dirname(include)): |
| 4459 | error(filename, linenum, 'build/include', 4, |
| 4460 | 'Do not include .cc files from other packages') |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 4461 | elif not _THIRD_PARTY_HEADERS_PATTERN.match(include): |
| 4462 | include_state.include_list[-1].append((include, linenum)) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 4463 | |
| 4464 | # We want to ensure that headers appear in the right order: |
| 4465 | # 1) for foo.cc, foo.h (preferred location) |
| 4466 | # 2) c system files |
| 4467 | # 3) cpp system files |
| 4468 | # 4) for foo.cc, foo.h (deprecated location) |
| 4469 | # 5) other google headers |
| 4470 | # |
| 4471 | # We classify each include statement as one of those 5 types |
| 4472 | # using a number of techniques. The include_state object keeps |
| 4473 | # track of the highest type seen, and complains if we see a |
| 4474 | # lower type after that. |
| 4475 | error_message = include_state.CheckNextIncludeOrder( |
| 4476 | _ClassifyInclude(fileinfo, include, is_system)) |
| 4477 | if error_message: |
| 4478 | error(filename, linenum, 'build/include_order', 4, |
| 4479 | '%s. Should be: %s.h, c system, c++ system, other.' % |
| 4480 | (error_message, fileinfo.BaseName())) |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 4481 | canonical_include = include_state.CanonicalizeAlphabeticalOrder(include) |
| 4482 | if not include_state.IsInAlphabeticalOrder( |
| 4483 | clean_lines, linenum, canonical_include): |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 4484 | error(filename, linenum, 'build/include_alpha', 4, |
| 4485 | 'Include "%s" not in alphabetical order' % include) |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 4486 | include_state.SetLastHeader(canonical_include) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 4487 | |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 4488 | |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 4489 | |
| 4490 | def _GetTextInside(text, start_pattern): |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 4491 | r"""Retrieves all the text between matching open and close parentheses. |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 4492 | |
| 4493 | Given a string of lines and a regular expression string, retrieve all the text |
| 4494 | following the expression and between opening punctuation symbols like |
| 4495 | (, [, or {, and the matching close-punctuation symbol. This properly nested |
| 4496 | occurrences of the punctuations, so for the text like |
| 4497 | printf(a(), b(c())); |
| 4498 | a call to _GetTextInside(text, r'printf\(') will return 'a(), b(c())'. |
| 4499 | start_pattern must match string having an open punctuation symbol at the end. |
| 4500 | |
| 4501 | Args: |
| 4502 | text: The lines to extract text. Its comments and strings must be elided. |
| 4503 | It can be single line and can span multiple lines. |
| 4504 | start_pattern: The regexp string indicating where to start extracting |
| 4505 | the text. |
| 4506 | Returns: |
| 4507 | The extracted text. |
| 4508 | None if either the opening string or ending punctuation could not be found. |
| 4509 | """ |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 4510 | # TODO(unknown): Audit cpplint.py to see what places could be profitably |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 4511 | # rewritten to use _GetTextInside (and use inferior regexp matching today). |
| 4512 | |
| 4513 | # Give opening punctuations to get the matching close-punctuations. |
| 4514 | matching_punctuation = {'(': ')', '{': '}', '[': ']'} |
| 4515 | closing_punctuation = set(matching_punctuation.itervalues()) |
| 4516 | |
| 4517 | # Find the position to start extracting text. |
| 4518 | match = re.search(start_pattern, text, re.M) |
| 4519 | if not match: # start_pattern not found in text. |
| 4520 | return None |
| 4521 | start_position = match.end(0) |
| 4522 | |
| 4523 | assert start_position > 0, ( |
| 4524 | 'start_pattern must ends with an opening punctuation.') |
| 4525 | assert text[start_position - 1] in matching_punctuation, ( |
| 4526 | 'start_pattern must ends with an opening punctuation.') |
| 4527 | # Stack of closing punctuations we expect to have in text after position. |
| 4528 | punctuation_stack = [matching_punctuation[text[start_position - 1]]] |
| 4529 | position = start_position |
| 4530 | while punctuation_stack and position < len(text): |
| 4531 | if text[position] == punctuation_stack[-1]: |
| 4532 | punctuation_stack.pop() |
| 4533 | elif text[position] in closing_punctuation: |
| 4534 | # A closing punctuation without matching opening punctuations. |
| 4535 | return None |
| 4536 | elif text[position] in matching_punctuation: |
| 4537 | punctuation_stack.append(matching_punctuation[text[position]]) |
| 4538 | position += 1 |
| 4539 | if punctuation_stack: |
| 4540 | # Opening punctuations left without matching close-punctuations. |
| 4541 | return None |
| 4542 | # punctuations match. |
| 4543 | return text[start_position:position - 1] |
| 4544 | |
| 4545 | |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 4546 | # Patterns for matching call-by-reference parameters. |
| 4547 | # |
| 4548 | # Supports nested templates up to 2 levels deep using this messy pattern: |
| 4549 | # < (?: < (?: < [^<>]* |
| 4550 | # > |
| 4551 | # | [^<>] )* |
| 4552 | # > |
| 4553 | # | [^<>] )* |
| 4554 | # > |
| 4555 | _RE_PATTERN_IDENT = r'[_a-zA-Z]\w*' # =~ [[:alpha:]][[:alnum:]]* |
| 4556 | _RE_PATTERN_TYPE = ( |
| 4557 | r'(?:const\s+)?(?:typename\s+|class\s+|struct\s+|union\s+|enum\s+)?' |
| 4558 | r'(?:\w|' |
| 4559 | r'\s*<(?:<(?:<[^<>]*>|[^<>])*>|[^<>])*>|' |
| 4560 | r'::)+') |
| 4561 | # A call-by-reference parameter ends with '& identifier'. |
| 4562 | _RE_PATTERN_REF_PARAM = re.compile( |
| 4563 | r'(' + _RE_PATTERN_TYPE + r'(?:\s*(?:\bconst\b|[*]))*\s*' |
| 4564 | r'&\s*' + _RE_PATTERN_IDENT + r')\s*(?:=[^,()]+)?[,)]') |
| 4565 | # A call-by-const-reference parameter either ends with 'const& identifier' |
| 4566 | # or looks like 'const type& identifier' when 'type' is atomic. |
| 4567 | _RE_PATTERN_CONST_REF_PARAM = ( |
| 4568 | r'(?:.*\s*\bconst\s*&\s*' + _RE_PATTERN_IDENT + |
| 4569 | r'|const\s+' + _RE_PATTERN_TYPE + r'\s*&\s*' + _RE_PATTERN_IDENT + r')') |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 4570 | # Stream types. |
| 4571 | _RE_PATTERN_REF_STREAM_PARAM = ( |
| 4572 | r'(?:.*stream\s*&\s*' + _RE_PATTERN_IDENT + r')') |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 4573 | |
| 4574 | |
| 4575 | def CheckLanguage(filename, clean_lines, linenum, file_extension, |
| 4576 | include_state, nesting_state, error): |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 4577 | """Checks rules from the 'C++ language rules' section of cppguide.html. |
| 4578 | |
| 4579 | Some of these rules are hard to test (function overloading, using |
| 4580 | uint32 inappropriately), but we do the best we can. |
| 4581 | |
| 4582 | Args: |
| 4583 | filename: The name of the current file. |
| 4584 | clean_lines: A CleansedLines instance containing the file. |
| 4585 | linenum: The number of the line to check. |
| 4586 | file_extension: The extension (without the dot) of the filename. |
| 4587 | include_state: An _IncludeState instance in which the headers are inserted. |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 4588 | nesting_state: A NestingState instance which maintains information about |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 4589 | the current stack of nested blocks being parsed. |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 4590 | error: The function to call with any errors found. |
| 4591 | """ |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 4592 | # If the line is empty or consists of entirely a comment, no need to |
| 4593 | # check it. |
| 4594 | line = clean_lines.elided[linenum] |
| 4595 | if not line: |
| 4596 | return |
| 4597 | |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 4598 | match = _RE_PATTERN_INCLUDE.search(line) |
| 4599 | if match: |
| 4600 | CheckIncludeLine(filename, clean_lines, linenum, include_state, error) |
| 4601 | return |
| 4602 | |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 4603 | # Reset include state across preprocessor directives. This is meant |
| 4604 | # to silence warnings for conditional includes. |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 4605 | match = Match(r'^\s*#\s*(if|ifdef|ifndef|elif|else|endif)\b', line) |
| 4606 | if match: |
| 4607 | include_state.ResetSection(match.group(1)) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 4608 | |
| 4609 | # Make Windows paths like Unix. |
| 4610 | fullname = os.path.abspath(filename).replace('\\', '/') |
[email protected] | 3990c41 | 2016-02-05 20:55:12 | [diff] [blame] | 4611 | |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 4612 | # Perform other checks now that we are sure that this is not an include line |
| 4613 | CheckCasts(filename, clean_lines, linenum, error) |
| 4614 | CheckGlobalStatic(filename, clean_lines, linenum, error) |
| 4615 | CheckPrintf(filename, clean_lines, linenum, error) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 4616 | |
| 4617 | if file_extension == 'h': |
| 4618 | # TODO(unknown): check that 1-arg constructors are explicit. |
| 4619 | # How to tell it's a constructor? |
| 4620 | # (handled in CheckForNonStandardConstructs for now) |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 4621 | # TODO(unknown): check that classes declare or disable copy/assign |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 4622 | # (level 1 error) |
| 4623 | pass |
| 4624 | |
| 4625 | # Check if people are using the verboten C basic types. The only exception |
| 4626 | # we regularly allow is "unsigned short port" for port. |
| 4627 | if Search(r'\bshort port\b', line): |
| 4628 | if not Search(r'\bunsigned short port\b', line): |
| 4629 | error(filename, linenum, 'runtime/int', 4, |
| 4630 | 'Use "unsigned short" for ports, not "short"') |
| 4631 | else: |
| 4632 | match = Search(r'\b(short|long(?! +double)|long long)\b', line) |
| 4633 | if match: |
| 4634 | error(filename, linenum, 'runtime/int', 4, |
| 4635 | 'Use int16/int64/etc, rather than the C type %s' % match.group(1)) |
| 4636 | |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 4637 | # Check if some verboten operator overloading is going on |
| 4638 | # TODO(unknown): catch out-of-line unary operator&: |
| 4639 | # class X {}; |
| 4640 | # int operator&(const X& x) { return 42; } // unary operator& |
| 4641 | # The trick is it's hard to tell apart from binary operator&: |
| 4642 | # class Y { int operator&(const Y& x) { return 23; } }; // binary operator& |
| 4643 | if Search(r'\boperator\s*&\s*\(\s*\)', line): |
| 4644 | error(filename, linenum, 'runtime/operator', 4, |
| 4645 | 'Unary operator& is dangerous. Do not use it.') |
| 4646 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 4647 | # Check for suspicious usage of "if" like |
| 4648 | # } if (a == b) { |
| 4649 | if Search(r'\}\s*if\s*\(', line): |
| 4650 | error(filename, linenum, 'readability/braces', 4, |
| 4651 | 'Did you mean "else if"? If not, start a new line for "if".') |
| 4652 | |
| 4653 | # Check for potential format string bugs like printf(foo). |
| 4654 | # We constrain the pattern not to pick things like DocidForPrintf(foo). |
| 4655 | # Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str()) |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 4656 | # TODO(unknown): Catch the following case. Need to change the calling |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 4657 | # convention of the whole function to process multiple line to handle it. |
| 4658 | # printf( |
| 4659 | # boy_this_is_a_really_long_variable_that_cannot_fit_on_the_prev_line); |
| 4660 | printf_args = _GetTextInside(line, r'(?i)\b(string)?printf\s*\(') |
| 4661 | if printf_args: |
| 4662 | match = Match(r'([\w.\->()]+)$', printf_args) |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 4663 | if match and match.group(1) != '__VA_ARGS__': |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 4664 | function_name = re.search(r'\b((?:string)?printf)\s*\(', |
| 4665 | line, re.I).group(1) |
| 4666 | error(filename, linenum, 'runtime/printf', 4, |
| 4667 | 'Potential format string bug. Do %s("%%s", %s) instead.' |
| 4668 | % (function_name, match.group(1))) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 4669 | |
| 4670 | # Check for potential memset bugs like memset(buf, sizeof(buf), 0). |
| 4671 | match = Search(r'memset\s*\(([^,]*),\s*([^,]*),\s*0\s*\)', line) |
| 4672 | if match and not Match(r"^''|-?[0-9]+|0x[0-9A-Fa-f]$", match.group(2)): |
| 4673 | error(filename, linenum, 'runtime/memset', 4, |
| 4674 | 'Did you mean "memset(%s, 0, %s)"?' |
| 4675 | % (match.group(1), match.group(2))) |
| 4676 | |
| 4677 | if Search(r'\busing namespace\b', line): |
| 4678 | error(filename, linenum, 'build/namespaces', 5, |
| 4679 | 'Do not use namespace using-directives. ' |
| 4680 | 'Use using-declarations instead.') |
| 4681 | |
| 4682 | # Detect variable-length arrays. |
| 4683 | match = Match(r'\s*(.+::)?(\w+) [a-z]\w*\[(.+)];', line) |
| 4684 | if (match and match.group(2) != 'return' and match.group(2) != 'delete' and |
| 4685 | match.group(3).find(']') == -1): |
| 4686 | # Split the size using space and arithmetic operators as delimiters. |
| 4687 | # If any of the resulting tokens are not compile time constants then |
| 4688 | # report the error. |
| 4689 | tokens = re.split(r'\s|\+|\-|\*|\/|<<|>>]', match.group(3)) |
| 4690 | is_const = True |
| 4691 | skip_next = False |
| 4692 | for tok in tokens: |
| 4693 | if skip_next: |
| 4694 | skip_next = False |
| 4695 | continue |
| 4696 | |
| 4697 | if Search(r'sizeof\(.+\)', tok): continue |
| 4698 | if Search(r'arraysize\(\w+\)', tok): continue |
| 4699 | |
| 4700 | tok = tok.lstrip('(') |
| 4701 | tok = tok.rstrip(')') |
| 4702 | if not tok: continue |
| 4703 | if Match(r'\d+', tok): continue |
| 4704 | if Match(r'0[xX][0-9a-fA-F]+', tok): continue |
| 4705 | if Match(r'k[A-Z0-9]\w*', tok): continue |
| 4706 | if Match(r'(.+::)?k[A-Z0-9]\w*', tok): continue |
| 4707 | if Match(r'(.+::)?[A-Z][A-Z0-9_]*', tok): continue |
| 4708 | # A catch all for tricky sizeof cases, including 'sizeof expression', |
| 4709 | # 'sizeof(*type)', 'sizeof(const type)', 'sizeof(struct StructName)' |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 4710 | # requires skipping the next token because we split on ' ' and '*'. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 4711 | if tok.startswith('sizeof'): |
| 4712 | skip_next = True |
| 4713 | continue |
| 4714 | is_const = False |
| 4715 | break |
| 4716 | if not is_const: |
| 4717 | error(filename, linenum, 'runtime/arrays', 1, |
| 4718 | 'Do not use variable-length arrays. Use an appropriately named ' |
| 4719 | "('k' followed by CamelCase) compile-time constant for the size.") |
| 4720 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 4721 | # Check for use of unnamed namespaces in header files. Registration |
| 4722 | # macros are typically OK, so we allow use of "namespace {" on lines |
| 4723 | # that end with backslashes. |
| 4724 | if (file_extension == 'h' |
| 4725 | and Search(r'\bnamespace\s*{', line) |
| 4726 | and line[-1] != '\\'): |
| 4727 | error(filename, linenum, 'build/namespaces', 4, |
| 4728 | 'Do not use unnamed namespaces in header files. See ' |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 4729 | 'https://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces' |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 4730 | ' for more information.') |
| 4731 | |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 4732 | |
| 4733 | def CheckGlobalStatic(filename, clean_lines, linenum, error): |
| 4734 | """Check for unsafe global or static objects. |
| 4735 | |
| 4736 | Args: |
| 4737 | filename: The name of the current file. |
| 4738 | clean_lines: A CleansedLines instance containing the file. |
| 4739 | linenum: The number of the line to check. |
| 4740 | error: The function to call with any errors found. |
| 4741 | """ |
| 4742 | line = clean_lines.elided[linenum] |
| 4743 | |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 4744 | # Match two lines at a time to support multiline declarations |
| 4745 | if linenum + 1 < clean_lines.NumLines() and not Search(r'[;({]', line): |
| 4746 | line += clean_lines.elided[linenum + 1].strip() |
| 4747 | |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 4748 | # Check for people declaring static/global STL strings at the top level. |
| 4749 | # This is dangerous because the C++ language does not guarantee that |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 4750 | # globals with constructors are initialized before the first access, and |
| 4751 | # also because globals can be destroyed when some threads are still running. |
| 4752 | # TODO(unknown): Generalize this to also find static unique_ptr instances. |
| 4753 | # TODO(unknown): File bugs for clang-tidy to find these. |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 4754 | match = Match( |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 4755 | r'((?:|static +)(?:|const +))(?::*std::)?string( +const)? +' |
| 4756 | r'([a-zA-Z0-9_:]+)\b(.*)', |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 4757 | line) |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 4758 | |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 4759 | # Remove false positives: |
| 4760 | # - String pointers (as opposed to values). |
| 4761 | # string *pointer |
| 4762 | # const string *pointer |
| 4763 | # string const *pointer |
| 4764 | # string *const pointer |
| 4765 | # |
| 4766 | # - Functions and template specializations. |
| 4767 | # string Function<Type>(... |
| 4768 | # string Class<Type>::Method(... |
| 4769 | # |
| 4770 | # - Operators. These are matched separately because operator names |
| 4771 | # cross non-word boundaries, and trying to match both operators |
| 4772 | # and functions at the same time would decrease accuracy of |
| 4773 | # matching identifiers. |
| 4774 | # string Class::operator*() |
| 4775 | if (match and |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 4776 | not Search(r'\bstring\b(\s+const)?\s*[\*\&]\s*(const\s+)?\w', line) and |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 4777 | not Search(r'\boperator\W', line) and |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 4778 | not Match(r'\s*(<.*>)?(::[a-zA-Z0-9_]+)*\s*\(([^"]|$)', match.group(4))): |
| 4779 | if Search(r'\bconst\b', line): |
| 4780 | error(filename, linenum, 'runtime/string', 4, |
| 4781 | 'For a static/global string constant, use a C style string ' |
| 4782 | 'instead: "%schar%s %s[]".' % |
| 4783 | (match.group(1), match.group(2) or '', match.group(3))) |
| 4784 | else: |
| 4785 | error(filename, linenum, 'runtime/string', 4, |
| 4786 | 'Static/global string variables are not permitted.') |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 4787 | |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 4788 | if (Search(r'\b([A-Za-z0-9_]*_)\(\1\)', line) or |
| 4789 | Search(r'\b([A-Za-z0-9_]*_)\(CHECK_NOTNULL\(\1\)\)', line)): |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 4790 | error(filename, linenum, 'runtime/init', 4, |
| 4791 | 'You seem to be initializing a member variable with itself.') |
| 4792 | |
| 4793 | |
| 4794 | def CheckPrintf(filename, clean_lines, linenum, error): |
| 4795 | """Check for printf related issues. |
| 4796 | |
| 4797 | Args: |
| 4798 | filename: The name of the current file. |
| 4799 | clean_lines: A CleansedLines instance containing the file. |
| 4800 | linenum: The number of the line to check. |
| 4801 | error: The function to call with any errors found. |
| 4802 | """ |
| 4803 | line = clean_lines.elided[linenum] |
| 4804 | |
| 4805 | # When snprintf is used, the second argument shouldn't be a literal. |
| 4806 | match = Search(r'snprintf\s*\(([^,]*),\s*([0-9]*)\s*,', line) |
| 4807 | if match and match.group(2) != '0': |
| 4808 | # If 2nd arg is zero, snprintf is used to calculate size. |
| 4809 | error(filename, linenum, 'runtime/printf', 3, |
| 4810 | 'If you can, use sizeof(%s) instead of %s as the 2nd arg ' |
| 4811 | 'to snprintf.' % (match.group(1), match.group(2))) |
| 4812 | |
| 4813 | # Check if some verboten C functions are being used. |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 4814 | if Search(r'\bsprintf\s*\(', line): |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 4815 | error(filename, linenum, 'runtime/printf', 5, |
| 4816 | 'Never use sprintf. Use snprintf instead.') |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 4817 | match = Search(r'\b(strcpy|strcat)\s*\(', line) |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 4818 | if match: |
| 4819 | error(filename, linenum, 'runtime/printf', 4, |
| 4820 | 'Almost always, snprintf is better than %s' % match.group(1)) |
| 4821 | |
| 4822 | |
| 4823 | def IsDerivedFunction(clean_lines, linenum): |
| 4824 | """Check if current line contains an inherited function. |
| 4825 | |
| 4826 | Args: |
| 4827 | clean_lines: A CleansedLines instance containing the file. |
| 4828 | linenum: The number of the line to check. |
| 4829 | Returns: |
| 4830 | True if current line contains a function with "override" |
| 4831 | virt-specifier. |
| 4832 | """ |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 4833 | # Scan back a few lines for start of current function |
| 4834 | for i in xrange(linenum, max(-1, linenum - 10), -1): |
| 4835 | match = Match(r'^([^()]*\w+)\(', clean_lines.elided[i]) |
| 4836 | if match: |
| 4837 | # Look for "override" after the matching closing parenthesis |
| 4838 | line, _, closing_paren = CloseExpression( |
| 4839 | clean_lines, i, len(match.group(1))) |
| 4840 | return (closing_paren >= 0 and |
| 4841 | Search(r'\boverride\b', line[closing_paren:])) |
| 4842 | return False |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 4843 | |
| 4844 | |
[email protected] | 255f2be | 2014-12-05 22:19:55 | [diff] [blame] | 4845 | def IsOutOfLineMethodDefinition(clean_lines, linenum): |
| 4846 | """Check if current line contains an out-of-line method definition. |
| 4847 | |
| 4848 | Args: |
| 4849 | clean_lines: A CleansedLines instance containing the file. |
| 4850 | linenum: The number of the line to check. |
| 4851 | Returns: |
| 4852 | True if current line contains an out-of-line method definition. |
| 4853 | """ |
| 4854 | # Scan back a few lines for start of current function |
| 4855 | for i in xrange(linenum, max(-1, linenum - 10), -1): |
| 4856 | if Match(r'^([^()]*\w+)\(', clean_lines.elided[i]): |
| 4857 | return Match(r'^[^()]*\w+::\w+\(', clean_lines.elided[i]) is not None |
| 4858 | return False |
| 4859 | |
| 4860 | |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 4861 | def IsInitializerList(clean_lines, linenum): |
| 4862 | """Check if current line is inside constructor initializer list. |
| 4863 | |
| 4864 | Args: |
| 4865 | clean_lines: A CleansedLines instance containing the file. |
| 4866 | linenum: The number of the line to check. |
| 4867 | Returns: |
| 4868 | True if current line appears to be inside constructor initializer |
| 4869 | list, False otherwise. |
| 4870 | """ |
| 4871 | for i in xrange(linenum, 1, -1): |
| 4872 | line = clean_lines.elided[i] |
| 4873 | if i == linenum: |
| 4874 | remove_function_body = Match(r'^(.*)\{\s*$', line) |
| 4875 | if remove_function_body: |
| 4876 | line = remove_function_body.group(1) |
| 4877 | |
| 4878 | if Search(r'\s:\s*\w+[({]', line): |
| 4879 | # A lone colon tend to indicate the start of a constructor |
| 4880 | # initializer list. It could also be a ternary operator, which |
| 4881 | # also tend to appear in constructor initializer lists as |
| 4882 | # opposed to parameter lists. |
| 4883 | return True |
| 4884 | if Search(r'\}\s*,\s*$', line): |
| 4885 | # A closing brace followed by a comma is probably the end of a |
| 4886 | # brace-initialized member in constructor initializer list. |
| 4887 | return True |
| 4888 | if Search(r'[{};]\s*$', line): |
| 4889 | # Found one of the following: |
| 4890 | # - A closing brace or semicolon, probably the end of the previous |
| 4891 | # function. |
| 4892 | # - An opening brace, probably the start of current class or namespace. |
| 4893 | # |
| 4894 | # Current line is probably not inside an initializer list since |
| 4895 | # we saw one of those things without seeing the starting colon. |
| 4896 | return False |
| 4897 | |
| 4898 | # Got to the beginning of the file without seeing the start of |
| 4899 | # constructor initializer list. |
| 4900 | return False |
| 4901 | |
| 4902 | |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 4903 | def CheckForNonConstReference(filename, clean_lines, linenum, |
| 4904 | nesting_state, error): |
| 4905 | """Check for non-const references. |
| 4906 | |
| 4907 | Separate from CheckLanguage since it scans backwards from current |
| 4908 | line, instead of scanning forward. |
| 4909 | |
| 4910 | Args: |
| 4911 | filename: The name of the current file. |
| 4912 | clean_lines: A CleansedLines instance containing the file. |
| 4913 | linenum: The number of the line to check. |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 4914 | nesting_state: A NestingState instance which maintains information about |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 4915 | the current stack of nested blocks being parsed. |
| 4916 | error: The function to call with any errors found. |
| 4917 | """ |
| 4918 | # Do nothing if there is no '&' on current line. |
| 4919 | line = clean_lines.elided[linenum] |
| 4920 | if '&' not in line: |
| 4921 | return |
| 4922 | |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 4923 | # If a function is inherited, current function doesn't have much of |
| 4924 | # a choice, so any non-const references should not be blamed on |
| 4925 | # derived function. |
| 4926 | if IsDerivedFunction(clean_lines, linenum): |
| 4927 | return |
| 4928 | |
[email protected] | 255f2be | 2014-12-05 22:19:55 | [diff] [blame] | 4929 | # Don't warn on out-of-line method definitions, as we would warn on the |
| 4930 | # in-line declaration, if it isn't marked with 'override'. |
| 4931 | if IsOutOfLineMethodDefinition(clean_lines, linenum): |
| 4932 | return |
| 4933 | |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 4934 | # Long type names may be broken across multiple lines, usually in one |
| 4935 | # of these forms: |
| 4936 | # LongType |
| 4937 | # ::LongTypeContinued &identifier |
| 4938 | # LongType:: |
| 4939 | # LongTypeContinued &identifier |
| 4940 | # LongType< |
| 4941 | # ...>::LongTypeContinued &identifier |
| 4942 | # |
| 4943 | # If we detected a type split across two lines, join the previous |
| 4944 | # line to current line so that we can match const references |
| 4945 | # accordingly. |
| 4946 | # |
| 4947 | # Note that this only scans back one line, since scanning back |
| 4948 | # arbitrary number of lines would be expensive. If you have a type |
| 4949 | # that spans more than 2 lines, please use a typedef. |
| 4950 | if linenum > 1: |
| 4951 | previous = None |
| 4952 | if Match(r'\s*::(?:[\w<>]|::)+\s*&\s*\S', line): |
| 4953 | # previous_line\n + ::current_line |
| 4954 | previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+[\w<>])\s*$', |
| 4955 | clean_lines.elided[linenum - 1]) |
| 4956 | elif Match(r'\s*[a-zA-Z_]([\w<>]|::)+\s*&\s*\S', line): |
| 4957 | # previous_line::\n + current_line |
| 4958 | previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+::)\s*$', |
| 4959 | clean_lines.elided[linenum - 1]) |
| 4960 | if previous: |
| 4961 | line = previous.group(1) + line.lstrip() |
| 4962 | else: |
| 4963 | # Check for templated parameter that is split across multiple lines |
| 4964 | endpos = line.rfind('>') |
| 4965 | if endpos > -1: |
| 4966 | (_, startline, startpos) = ReverseCloseExpression( |
| 4967 | clean_lines, linenum, endpos) |
| 4968 | if startpos > -1 and startline < linenum: |
| 4969 | # Found the matching < on an earlier line, collect all |
| 4970 | # pieces up to current line. |
| 4971 | line = '' |
| 4972 | for i in xrange(startline, linenum + 1): |
| 4973 | line += clean_lines.elided[i].strip() |
| 4974 | |
| 4975 | # Check for non-const references in function parameters. A single '&' may |
| 4976 | # found in the following places: |
| 4977 | # inside expression: binary & for bitwise AND |
| 4978 | # inside expression: unary & for taking the address of something |
| 4979 | # inside declarators: reference parameter |
| 4980 | # We will exclude the first two cases by checking that we are not inside a |
| 4981 | # function body, including one that was just introduced by a trailing '{'. |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 4982 | # TODO(unknown): Doesn't account for 'catch(Exception& e)' [rare]. |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 4983 | if (nesting_state.previous_stack_top and |
| 4984 | not (isinstance(nesting_state.previous_stack_top, _ClassInfo) or |
| 4985 | isinstance(nesting_state.previous_stack_top, _NamespaceInfo))): |
| 4986 | # Not at toplevel, not within a class, and not within a namespace |
| 4987 | return |
| 4988 | |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 4989 | # Avoid initializer lists. We only need to scan back from the |
| 4990 | # current line for something that starts with ':'. |
| 4991 | # |
| 4992 | # We don't need to check the current line, since the '&' would |
| 4993 | # appear inside the second set of parentheses on the current line as |
| 4994 | # opposed to the first set. |
| 4995 | if linenum > 0: |
| 4996 | for i in xrange(linenum - 1, max(0, linenum - 10), -1): |
| 4997 | previous_line = clean_lines.elided[i] |
| 4998 | if not Search(r'[),]\s*$', previous_line): |
| 4999 | break |
| 5000 | if Match(r'^\s*:\s+\S', previous_line): |
| 5001 | return |
| 5002 | |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 5003 | # Avoid preprocessors |
| 5004 | if Search(r'\\\s*$', line): |
| 5005 | return |
| 5006 | |
| 5007 | # Avoid constructor initializer lists |
| 5008 | if IsInitializerList(clean_lines, linenum): |
| 5009 | return |
| 5010 | |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 5011 | # We allow non-const references in a few standard places, like functions |
| 5012 | # called "swap()" or iostream operators like "<<" or ">>". Do not check |
| 5013 | # those function parameters. |
| 5014 | # |
| 5015 | # We also accept & in static_assert, which looks like a function but |
| 5016 | # it's actually a declaration expression. |
| 5017 | whitelisted_functions = (r'(?:[sS]wap(?:<\w:+>)?|' |
| 5018 | r'operator\s*[<>][<>]|' |
| 5019 | r'static_assert|COMPILE_ASSERT' |
| 5020 | r')\s*\(') |
| 5021 | if Search(whitelisted_functions, line): |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 5022 | return |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 5023 | elif not Search(r'\S+\([^)]*$', line): |
| 5024 | # Don't see a whitelisted function on this line. Actually we |
| 5025 | # didn't see any function name on this line, so this is likely a |
| 5026 | # multi-line parameter list. Try a bit harder to catch this case. |
| 5027 | for i in xrange(2): |
| 5028 | if (linenum > i and |
| 5029 | Search(whitelisted_functions, clean_lines.elided[linenum - i - 1])): |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 5030 | return |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 5031 | |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 5032 | decls = ReplaceAll(r'{[^}]*}', ' ', line) # exclude function body |
| 5033 | for parameter in re.findall(_RE_PATTERN_REF_PARAM, decls): |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 5034 | if (not Match(_RE_PATTERN_CONST_REF_PARAM, parameter) and |
| 5035 | not Match(_RE_PATTERN_REF_STREAM_PARAM, parameter)): |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 5036 | error(filename, linenum, 'runtime/references', 2, |
| 5037 | 'Is this a non-const reference? ' |
| 5038 | 'If so, make const or use a pointer: ' + |
| 5039 | ReplaceAll(' *<', '<', parameter)) |
| 5040 | |
| 5041 | |
| 5042 | def CheckCasts(filename, clean_lines, linenum, error): |
| 5043 | """Various cast related checks. |
| 5044 | |
| 5045 | Args: |
| 5046 | filename: The name of the current file. |
| 5047 | clean_lines: A CleansedLines instance containing the file. |
| 5048 | linenum: The number of the line to check. |
| 5049 | error: The function to call with any errors found. |
| 5050 | """ |
| 5051 | line = clean_lines.elided[linenum] |
| 5052 | |
| 5053 | # Check to see if they're using an conversion function cast. |
| 5054 | # I just try to capture the most common basic types, though there are more. |
| 5055 | # Parameterless conversion functions, such as bool(), are allowed as they are |
| 5056 | # probably a member operator declaration or default constructor. |
| 5057 | match = Search( |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 5058 | r'(\bnew\s+(?:const\s+)?|\S<\s*(?:const\s+)?)?\b' |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 5059 | r'(int|float|double|bool|char|int32|uint32|int64|uint64)' |
| 5060 | r'(\([^)].*)', line) |
| 5061 | expecting_function = ExpectingFunctionArgs(clean_lines, linenum) |
| 5062 | if match and not expecting_function: |
| 5063 | matched_type = match.group(2) |
| 5064 | |
| 5065 | # matched_new_or_template is used to silence two false positives: |
| 5066 | # - New operators |
| 5067 | # - Template arguments with function types |
| 5068 | # |
| 5069 | # For template arguments, we match on types immediately following |
| 5070 | # an opening bracket without any spaces. This is a fast way to |
| 5071 | # silence the common case where the function type is the first |
| 5072 | # template argument. False negative with less-than comparison is |
| 5073 | # avoided because those operators are usually followed by a space. |
| 5074 | # |
| 5075 | # function<double(double)> // bracket + no space = false positive |
| 5076 | # value < double(42) // bracket + space = true positive |
| 5077 | matched_new_or_template = match.group(1) |
| 5078 | |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 5079 | # Avoid arrays by looking for brackets that come after the closing |
| 5080 | # parenthesis. |
| 5081 | if Match(r'\([^()]+\)\s*\[', match.group(3)): |
| 5082 | return |
| 5083 | |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 5084 | # Other things to ignore: |
| 5085 | # - Function pointers |
| 5086 | # - Casts to pointer types |
| 5087 | # - Placement new |
| 5088 | # - Alias declarations |
| 5089 | matched_funcptr = match.group(3) |
| 5090 | if (matched_new_or_template is None and |
| 5091 | not (matched_funcptr and |
| 5092 | (Match(r'\((?:[^() ]+::\s*\*\s*)?[^() ]+\)\s*\(', |
| 5093 | matched_funcptr) or |
| 5094 | matched_funcptr.startswith('(*)'))) and |
| 5095 | not Match(r'\s*using\s+\S+\s*=\s*' + matched_type, line) and |
| 5096 | not Search(r'new\(\S+\)\s*' + matched_type, line)): |
| 5097 | error(filename, linenum, 'readability/casting', 4, |
| 5098 | 'Using deprecated casting style. ' |
| 5099 | 'Use static_cast<%s>(...) instead' % |
| 5100 | matched_type) |
| 5101 | |
| 5102 | if not expecting_function: |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 5103 | CheckCStyleCast(filename, clean_lines, linenum, 'static_cast', |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 5104 | r'\((int|float|double|bool|char|u?int(16|32|64))\)', error) |
| 5105 | |
| 5106 | # This doesn't catch all cases. Consider (const char * const)"hello". |
| 5107 | # |
| 5108 | # (char *) "foo" should always be a const_cast (reinterpret_cast won't |
| 5109 | # compile). |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 5110 | if CheckCStyleCast(filename, clean_lines, linenum, 'const_cast', |
| 5111 | r'\((char\s?\*+\s?)\)\s*"', error): |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 5112 | pass |
| 5113 | else: |
| 5114 | # Check pointer casts for other than string constants |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 5115 | CheckCStyleCast(filename, clean_lines, linenum, 'reinterpret_cast', |
| 5116 | r'\((\w+\s?\*+\s?)\)', error) |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 5117 | |
| 5118 | # In addition, we look for people taking the address of a cast. This |
| 5119 | # is dangerous -- casts can assign to temporaries, so the pointer doesn't |
| 5120 | # point where you think. |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 5121 | # |
| 5122 | # Some non-identifier character is required before the '&' for the |
| 5123 | # expression to be recognized as a cast. These are casts: |
| 5124 | # expression = &static_cast<int*>(temporary()); |
| 5125 | # function(&(int*)(temporary())); |
| 5126 | # |
| 5127 | # This is not a cast: |
| 5128 | # reference_type&(int* function_param); |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 5129 | match = Search( |
[email protected] | 255f2be | 2014-12-05 22:19:55 | [diff] [blame] | 5130 | r'(?:[^\w]&\(([^)*][^)]*)\)[\w(])|' |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 5131 | r'(?:[^\w]&(static|dynamic|down|reinterpret)_cast\b)', line) |
[email protected] | 255f2be | 2014-12-05 22:19:55 | [diff] [blame] | 5132 | if match: |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 5133 | # Try a better error message when the & is bound to something |
| 5134 | # dereferenced by the casted pointer, as opposed to the casted |
| 5135 | # pointer itself. |
| 5136 | parenthesis_error = False |
| 5137 | match = Match(r'^(.*&(?:static|dynamic|down|reinterpret)_cast\b)<', line) |
| 5138 | if match: |
| 5139 | _, y1, x1 = CloseExpression(clean_lines, linenum, len(match.group(1))) |
| 5140 | if x1 >= 0 and clean_lines.elided[y1][x1] == '(': |
| 5141 | _, y2, x2 = CloseExpression(clean_lines, y1, x1) |
| 5142 | if x2 >= 0: |
| 5143 | extended_line = clean_lines.elided[y2][x2:] |
| 5144 | if y2 < clean_lines.NumLines() - 1: |
| 5145 | extended_line += clean_lines.elided[y2 + 1] |
| 5146 | if Match(r'\s*(?:->|\[)', extended_line): |
| 5147 | parenthesis_error = True |
| 5148 | |
| 5149 | if parenthesis_error: |
| 5150 | error(filename, linenum, 'readability/casting', 4, |
| 5151 | ('Are you taking an address of something dereferenced ' |
| 5152 | 'from a cast? Wrapping the dereferenced expression in ' |
| 5153 | 'parentheses will make the binding more obvious')) |
| 5154 | else: |
| 5155 | error(filename, linenum, 'runtime/casting', 4, |
| 5156 | ('Are you taking an address of a cast? ' |
| 5157 | 'This is dangerous: could be a temp var. ' |
| 5158 | 'Take the address before doing the cast, rather than after')) |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 5159 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5160 | |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 5161 | def CheckCStyleCast(filename, clean_lines, linenum, cast_type, pattern, error): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5162 | """Checks for a C-style cast by looking for the pattern. |
| 5163 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5164 | Args: |
| 5165 | filename: The name of the current file. |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 5166 | clean_lines: A CleansedLines instance containing the file. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5167 | linenum: The number of the line to check. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5168 | cast_type: The string for the C++ cast to recommend. This is either |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 5169 | reinterpret_cast, static_cast, or const_cast, depending. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5170 | pattern: The regular expression used to find C-style casts. |
| 5171 | error: The function to call with any errors found. |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 5172 | |
| 5173 | Returns: |
| 5174 | True if an error was emitted. |
| 5175 | False otherwise. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5176 | """ |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 5177 | line = clean_lines.elided[linenum] |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5178 | match = Search(pattern, line) |
| 5179 | if not match: |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 5180 | return False |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5181 | |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 5182 | # Exclude lines with keywords that tend to look like casts |
| 5183 | context = line[0:match.start(1) - 1] |
| 5184 | if Match(r'.*\b(?:sizeof|alignof|alignas|[_A-Z][_A-Z0-9]*)\s*$', context): |
| 5185 | return False |
| 5186 | |
| 5187 | # Try expanding current context to see if we one level of |
| 5188 | # parentheses inside a macro. |
| 5189 | if linenum > 0: |
| 5190 | for i in xrange(linenum - 1, max(0, linenum - 5), -1): |
| 5191 | context = clean_lines.elided[i] + context |
| 5192 | if Match(r'.*\b[_A-Z][_A-Z0-9]*\s*\((?:\([^()]*\)|[^()])*$', context): |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 5193 | return False |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5194 | |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 5195 | # operator++(int) and operator--(int) |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 5196 | if context.endswith(' operator++') or context.endswith(' operator--'): |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 5197 | return False |
| 5198 | |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 5199 | # A single unnamed argument for a function tends to look like old style cast. |
| 5200 | # If we see those, don't issue warnings for deprecated casts. |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 5201 | remainder = line[match.end(0):] |
[email protected] | 255f2be | 2014-12-05 22:19:55 | [diff] [blame] | 5202 | if Match(r'^\s*(?:;|const\b|throw\b|final\b|override\b|[=>{),]|->)', |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 5203 | remainder): |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 5204 | return False |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5205 | |
| 5206 | # At this point, all that should be left is actual casts. |
| 5207 | error(filename, linenum, 'readability/casting', 4, |
| 5208 | 'Using C-style cast. Use %s<%s>(...) instead' % |
| 5209 | (cast_type, match.group(1))) |
| 5210 | |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 5211 | return True |
| 5212 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5213 | |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 5214 | def ExpectingFunctionArgs(clean_lines, linenum): |
| 5215 | """Checks whether where function type arguments are expected. |
| 5216 | |
| 5217 | Args: |
| 5218 | clean_lines: A CleansedLines instance containing the file. |
| 5219 | linenum: The number of the line to check. |
| 5220 | |
| 5221 | Returns: |
| 5222 | True if the line at 'linenum' is inside something that expects arguments |
| 5223 | of function types. |
| 5224 | """ |
| 5225 | line = clean_lines.elided[linenum] |
| 5226 | return (Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line) or |
| 5227 | (linenum >= 2 and |
| 5228 | (Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\((?:\S+,)?\s*$', |
| 5229 | clean_lines.elided[linenum - 1]) or |
| 5230 | Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\(\s*$', |
| 5231 | clean_lines.elided[linenum - 2]) or |
| 5232 | Search(r'\bstd::m?function\s*\<\s*$', |
| 5233 | clean_lines.elided[linenum - 1])))) |
| 5234 | |
| 5235 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5236 | _HEADERS_CONTAINING_TEMPLATES = ( |
| 5237 | ('<deque>', ('deque',)), |
| 5238 | ('<functional>', ('unary_function', 'binary_function', |
| 5239 | 'plus', 'minus', 'multiplies', 'divides', 'modulus', |
| 5240 | 'negate', |
| 5241 | 'equal_to', 'not_equal_to', 'greater', 'less', |
| 5242 | 'greater_equal', 'less_equal', |
| 5243 | 'logical_and', 'logical_or', 'logical_not', |
| 5244 | 'unary_negate', 'not1', 'binary_negate', 'not2', |
| 5245 | 'bind1st', 'bind2nd', |
| 5246 | 'pointer_to_unary_function', |
| 5247 | 'pointer_to_binary_function', |
| 5248 | 'ptr_fun', |
| 5249 | 'mem_fun_t', 'mem_fun', 'mem_fun1_t', 'mem_fun1_ref_t', |
| 5250 | 'mem_fun_ref_t', |
| 5251 | 'const_mem_fun_t', 'const_mem_fun1_t', |
| 5252 | 'const_mem_fun_ref_t', 'const_mem_fun1_ref_t', |
| 5253 | 'mem_fun_ref', |
| 5254 | )), |
| 5255 | ('<limits>', ('numeric_limits',)), |
| 5256 | ('<list>', ('list',)), |
| 5257 | ('<map>', ('map', 'multimap',)), |
lhchavez | 2d1b6da | 2016-07-13 17:40:01 | [diff] [blame] | 5258 | ('<memory>', ('allocator', 'make_shared', 'make_unique', 'shared_ptr', |
| 5259 | 'unique_ptr', 'weak_ptr')), |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5260 | ('<queue>', ('queue', 'priority_queue',)), |
| 5261 | ('<set>', ('set', 'multiset',)), |
| 5262 | ('<stack>', ('stack',)), |
| 5263 | ('<string>', ('char_traits', 'basic_string',)), |
[email protected] | 255f2be | 2014-12-05 22:19:55 | [diff] [blame] | 5264 | ('<tuple>', ('tuple',)), |
lhchavez | 2d1b6da | 2016-07-13 17:40:01 | [diff] [blame] | 5265 | ('<unordered_map>', ('unordered_map', 'unordered_multimap')), |
| 5266 | ('<unordered_set>', ('unordered_set', 'unordered_multiset')), |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5267 | ('<utility>', ('pair',)), |
| 5268 | ('<vector>', ('vector',)), |
| 5269 | |
| 5270 | # gcc extensions. |
| 5271 | # Note: std::hash is their hash, ::hash is our hash |
| 5272 | ('<hash_map>', ('hash_map', 'hash_multimap',)), |
| 5273 | ('<hash_set>', ('hash_set', 'hash_multiset',)), |
| 5274 | ('<slist>', ('slist',)), |
| 5275 | ) |
| 5276 | |
[email protected] | 3990c41 | 2016-02-05 20:55:12 | [diff] [blame] | 5277 | _HEADERS_MAYBE_TEMPLATES = ( |
| 5278 | ('<algorithm>', ('copy', 'max', 'min', 'min_element', 'sort', |
| 5279 | 'transform', |
| 5280 | )), |
lhchavez | 2d1b6da | 2016-07-13 17:40:01 | [diff] [blame] | 5281 | ('<utility>', ('forward', 'make_pair', 'move', 'swap')), |
[email protected] | 3990c41 | 2016-02-05 20:55:12 | [diff] [blame] | 5282 | ) |
| 5283 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5284 | _RE_PATTERN_STRING = re.compile(r'\bstring\b') |
| 5285 | |
[email protected] | 3990c41 | 2016-02-05 20:55:12 | [diff] [blame] | 5286 | _re_pattern_headers_maybe_templates = [] |
| 5287 | for _header, _templates in _HEADERS_MAYBE_TEMPLATES: |
| 5288 | for _template in _templates: |
| 5289 | # Match max<type>(..., ...), max(..., ...), but not foo->max, foo.max or |
| 5290 | # type::max(). |
| 5291 | _re_pattern_headers_maybe_templates.append( |
| 5292 | (re.compile(r'[^>.]\b' + _template + r'(<.*?>)?\([^\)]'), |
| 5293 | _template, |
| 5294 | _header)) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5295 | |
[email protected] | 3990c41 | 2016-02-05 20:55:12 | [diff] [blame] | 5296 | # Other scripts may reach in and modify this pattern. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5297 | _re_pattern_templates = [] |
| 5298 | for _header, _templates in _HEADERS_CONTAINING_TEMPLATES: |
| 5299 | for _template in _templates: |
| 5300 | _re_pattern_templates.append( |
| 5301 | (re.compile(r'(\<|\b)' + _template + r'\s*\<'), |
| 5302 | _template + '<>', |
| 5303 | _header)) |
| 5304 | |
| 5305 | |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 5306 | def FilesBelongToSameModule(filename_cc, filename_h): |
| 5307 | """Check if these two filenames belong to the same module. |
| 5308 | |
| 5309 | The concept of a 'module' here is a as follows: |
| 5310 | foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the |
| 5311 | same 'module' if they are in the same directory. |
| 5312 | some/path/public/xyzzy and some/path/internal/xyzzy are also considered |
| 5313 | to belong to the same module here. |
| 5314 | |
| 5315 | If the filename_cc contains a longer path than the filename_h, for example, |
| 5316 | '/absolute/path/to/base/sysinfo.cc', and this file would include |
| 5317 | 'base/sysinfo.h', this function also produces the prefix needed to open the |
| 5318 | header. This is used by the caller of this function to more robustly open the |
| 5319 | header file. We don't have access to the real include paths in this context, |
| 5320 | so we need this guesswork here. |
| 5321 | |
| 5322 | Known bugs: tools/base/bar.cc and base/bar.h belong to the same module |
| 5323 | according to this implementation. Because of this, this function gives |
| 5324 | some false positives. This should be sufficiently rare in practice. |
| 5325 | |
| 5326 | Args: |
| 5327 | filename_cc: is the path for the .cc file |
| 5328 | filename_h: is the path for the header path |
| 5329 | |
| 5330 | Returns: |
| 5331 | Tuple with a bool and a string: |
| 5332 | bool: True if filename_cc and filename_h belong to the same module. |
| 5333 | string: the additional prefix needed to open the header file. |
| 5334 | """ |
| 5335 | |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 5336 | fileinfo = FileInfo(filename_cc) |
| 5337 | if not fileinfo.IsSource(): |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 5338 | return (False, '') |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 5339 | filename_cc = filename_cc[:-len(fileinfo.Extension())] |
| 5340 | matched_test_suffix = Search(_TEST_FILE_SUFFIX, fileinfo.BaseName()) |
| 5341 | if matched_test_suffix: |
| 5342 | filename_cc = filename_cc[:-len(matched_test_suffix.group(1))] |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 5343 | filename_cc = filename_cc.replace('/public/', '/') |
| 5344 | filename_cc = filename_cc.replace('/internal/', '/') |
| 5345 | |
| 5346 | if not filename_h.endswith('.h'): |
| 5347 | return (False, '') |
| 5348 | filename_h = filename_h[:-len('.h')] |
| 5349 | if filename_h.endswith('-inl'): |
| 5350 | filename_h = filename_h[:-len('-inl')] |
| 5351 | filename_h = filename_h.replace('/public/', '/') |
| 5352 | filename_h = filename_h.replace('/internal/', '/') |
| 5353 | |
| 5354 | files_belong_to_same_module = filename_cc.endswith(filename_h) |
| 5355 | common_path = '' |
| 5356 | if files_belong_to_same_module: |
| 5357 | common_path = filename_cc[:-len(filename_h)] |
| 5358 | return files_belong_to_same_module, common_path |
| 5359 | |
| 5360 | |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 5361 | def UpdateIncludeState(filename, include_dict, io=codecs): |
| 5362 | """Fill up the include_dict with new includes found from the file. |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 5363 | |
| 5364 | Args: |
| 5365 | filename: the name of the header to read. |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 5366 | include_dict: a dictionary in which the headers are inserted. |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 5367 | io: The io factory to use to read the file. Provided for testability. |
| 5368 | |
| 5369 | Returns: |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 5370 | True if a header was successfully added. False otherwise. |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 5371 | """ |
| 5372 | headerfile = None |
| 5373 | try: |
| 5374 | headerfile = io.open(filename, 'r', 'utf8', 'replace') |
| 5375 | except IOError: |
| 5376 | return False |
| 5377 | linenum = 0 |
| 5378 | for line in headerfile: |
| 5379 | linenum += 1 |
| 5380 | clean_line = CleanseComments(line) |
| 5381 | match = _RE_PATTERN_INCLUDE.search(clean_line) |
| 5382 | if match: |
| 5383 | include = match.group(2) |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 5384 | include_dict.setdefault(include, linenum) |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 5385 | return True |
| 5386 | |
| 5387 | |
| 5388 | def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error, |
| 5389 | io=codecs): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5390 | """Reports for missing stl includes. |
| 5391 | |
| 5392 | This function will output warnings to make sure you are including the headers |
| 5393 | necessary for the stl containers and functions that you use. We only give one |
| 5394 | reason to include a header. For example, if you use both equal_to<> and |
| 5395 | less<> in a .h file, only one (the latter in the file) of these will be |
| 5396 | reported as a reason to include the <functional>. |
| 5397 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5398 | Args: |
| 5399 | filename: The name of the current file. |
| 5400 | clean_lines: A CleansedLines instance containing the file. |
| 5401 | include_state: An _IncludeState instance. |
| 5402 | error: The function to call with any errors found. |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 5403 | io: The IO factory to use to read the header file. Provided for unittest |
| 5404 | injection. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5405 | """ |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5406 | required = {} # A map of header name to linenumber and the template entity. |
| 5407 | # Example of required: { '<functional>': (1219, 'less<>') } |
| 5408 | |
| 5409 | for linenum in xrange(clean_lines.NumLines()): |
| 5410 | line = clean_lines.elided[linenum] |
| 5411 | if not line or line[0] == '#': |
| 5412 | continue |
| 5413 | |
| 5414 | # String is special -- it is a non-templatized type in STL. |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 5415 | matched = _RE_PATTERN_STRING.search(line) |
| 5416 | if matched: |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 5417 | # Don't warn about strings in non-STL namespaces: |
| 5418 | # (We check only the first match per line; good enough.) |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 5419 | prefix = line[:matched.start()] |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 5420 | if prefix.endswith('std::') or not prefix.endswith('::'): |
| 5421 | required['<string>'] = (linenum, 'string') |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5422 | |
[email protected] | 3990c41 | 2016-02-05 20:55:12 | [diff] [blame] | 5423 | for pattern, template, header in _re_pattern_headers_maybe_templates: |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5424 | if pattern.search(line): |
| 5425 | required[header] = (linenum, template) |
| 5426 | |
| 5427 | # The following function is just a speed up, no semantics are changed. |
| 5428 | if not '<' in line: # Reduces the cpu time usage by skipping lines. |
| 5429 | continue |
| 5430 | |
| 5431 | for pattern, template, header in _re_pattern_templates: |
lhchavez | 9b2173c | 2016-07-13 17:20:07 | [diff] [blame] | 5432 | matched = pattern.search(line) |
| 5433 | if matched: |
| 5434 | # Don't warn about IWYU in non-STL namespaces: |
| 5435 | # (We check only the first match per line; good enough.) |
| 5436 | prefix = line[:matched.start()] |
| 5437 | if prefix.endswith('std::') or not prefix.endswith('::'): |
| 5438 | required[header] = (linenum, template) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5439 | |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 5440 | # The policy is that if you #include something in foo.h you don't need to |
| 5441 | # include it again in foo.cc. Here, we will look at possible includes. |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 5442 | # Let's flatten the include_state include_list and copy it into a dictionary. |
| 5443 | include_dict = dict([item for sublist in include_state.include_list |
| 5444 | for item in sublist]) |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 5445 | |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 5446 | # Did we find the header for this file (if any) and successfully load it? |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 5447 | header_found = False |
| 5448 | |
| 5449 | # Use the absolute path so that matching works properly. |
[email protected] | 8f92756 | 2012-01-30 19:51:28 | [diff] [blame] | 5450 | abs_filename = FileInfo(filename).FullName() |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 5451 | |
| 5452 | # For Emacs's flymake. |
| 5453 | # If cpplint is invoked from Emacs's flymake, a temporary file is generated |
| 5454 | # by flymake and that file name might end with '_flymake.cc'. In that case, |
| 5455 | # restore original file name here so that the corresponding header file can be |
| 5456 | # found. |
| 5457 | # e.g. If the file name is 'foo_flymake.cc', we should search for 'foo.h' |
| 5458 | # instead of 'foo_flymake.h' |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 5459 | abs_filename = re.sub(r'_flymake\.cc$', '.cc', abs_filename) |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 5460 | |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 5461 | # include_dict is modified during iteration, so we iterate over a copy of |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 5462 | # the keys. |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 5463 | header_keys = include_dict.keys() |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 5464 | for header in header_keys: |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 5465 | (same_module, common_path) = FilesBelongToSameModule(abs_filename, header) |
| 5466 | fullpath = common_path + header |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 5467 | if same_module and UpdateIncludeState(fullpath, include_dict, io): |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 5468 | header_found = True |
| 5469 | |
| 5470 | # If we can't find the header file for a .cc, assume it's because we don't |
| 5471 | # know where to look. In that case we'll give up as we're not sure they |
| 5472 | # didn't include it in the .h file. |
| 5473 | # TODO(unknown): Do a better job of finding .h files so we are confident that |
| 5474 | # not having the .h file means there isn't one. |
| 5475 | if filename.endswith('.cc') and not header_found: |
| 5476 | return |
| 5477 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5478 | # All the lines have been processed, report the errors found. |
| 5479 | for required_header_unstripped in required: |
| 5480 | template = required[required_header_unstripped][1] |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 5481 | if required_header_unstripped.strip('<>"') not in include_dict: |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5482 | error(filename, required[required_header_unstripped][0], |
| 5483 | 'build/include_what_you_use', 4, |
| 5484 | 'Add #include ' + required_header_unstripped + ' for ' + template) |
| 5485 | |
| 5486 | |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 5487 | _RE_PATTERN_EXPLICIT_MAKEPAIR = re.compile(r'\bmake_pair\s*<') |
| 5488 | |
| 5489 | |
| 5490 | def CheckMakePairUsesDeduction(filename, clean_lines, linenum, error): |
| 5491 | """Check that make_pair's template arguments are deduced. |
| 5492 | |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 5493 | G++ 4.6 in C++11 mode fails badly if make_pair's template arguments are |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 5494 | specified explicitly, and such use isn't intended in any case. |
| 5495 | |
| 5496 | Args: |
| 5497 | filename: The name of the current file. |
| 5498 | clean_lines: A CleansedLines instance containing the file. |
| 5499 | linenum: The number of the line to check. |
| 5500 | error: The function to call with any errors found. |
| 5501 | """ |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 5502 | line = clean_lines.elided[linenum] |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 5503 | match = _RE_PATTERN_EXPLICIT_MAKEPAIR.search(line) |
| 5504 | if match: |
| 5505 | error(filename, linenum, 'build/explicit_make_pair', |
| 5506 | 4, # 4 = high confidence |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 5507 | 'For C++11-compatibility, omit template arguments from make_pair' |
| 5508 | ' OR use pair directly OR if appropriate, construct a pair directly') |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 5509 | |
| 5510 | |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 5511 | def CheckRedundantVirtual(filename, clean_lines, linenum, error): |
| 5512 | """Check if line contains a redundant "virtual" function-specifier. |
| 5513 | |
| 5514 | Args: |
| 5515 | filename: The name of the current file. |
| 5516 | clean_lines: A CleansedLines instance containing the file. |
| 5517 | linenum: The number of the line to check. |
| 5518 | error: The function to call with any errors found. |
| 5519 | """ |
| 5520 | # Look for "virtual" on current line. |
| 5521 | line = clean_lines.elided[linenum] |
[email protected] | 255f2be | 2014-12-05 22:19:55 | [diff] [blame] | 5522 | virtual = Match(r'^(.*)(\bvirtual\b)(.*)$', line) |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 5523 | if not virtual: return |
| 5524 | |
[email protected] | 255f2be | 2014-12-05 22:19:55 | [diff] [blame] | 5525 | # Ignore "virtual" keywords that are near access-specifiers. These |
| 5526 | # are only used in class base-specifier and do not apply to member |
| 5527 | # functions. |
| 5528 | if (Search(r'\b(public|protected|private)\s+$', virtual.group(1)) or |
| 5529 | Match(r'^\s+(public|protected|private)\b', virtual.group(3))): |
| 5530 | return |
| 5531 | |
| 5532 | # Ignore the "virtual" keyword from virtual base classes. Usually |
| 5533 | # there is a column on the same line in these cases (virtual base |
| 5534 | # classes are rare in google3 because multiple inheritance is rare). |
| 5535 | if Match(r'^.*[^:]:[^:].*$', line): return |
| 5536 | |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 5537 | # Look for the next opening parenthesis. This is the start of the |
| 5538 | # parameter list (possibly on the next line shortly after virtual). |
| 5539 | # TODO(unknown): doesn't work if there are virtual functions with |
| 5540 | # decltype() or other things that use parentheses, but csearch suggests |
| 5541 | # that this is rare. |
| 5542 | end_col = -1 |
| 5543 | end_line = -1 |
[email protected] | 255f2be | 2014-12-05 22:19:55 | [diff] [blame] | 5544 | start_col = len(virtual.group(2)) |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 5545 | for start_line in xrange(linenum, min(linenum + 3, clean_lines.NumLines())): |
| 5546 | line = clean_lines.elided[start_line][start_col:] |
| 5547 | parameter_list = Match(r'^([^(]*)\(', line) |
| 5548 | if parameter_list: |
| 5549 | # Match parentheses to find the end of the parameter list |
| 5550 | (_, end_line, end_col) = CloseExpression( |
| 5551 | clean_lines, start_line, start_col + len(parameter_list.group(1))) |
| 5552 | break |
| 5553 | start_col = 0 |
| 5554 | |
| 5555 | if end_col < 0: |
| 5556 | return # Couldn't find end of parameter list, give up |
| 5557 | |
| 5558 | # Look for "override" or "final" after the parameter list |
| 5559 | # (possibly on the next few lines). |
| 5560 | for i in xrange(end_line, min(end_line + 3, clean_lines.NumLines())): |
| 5561 | line = clean_lines.elided[i][end_col:] |
| 5562 | match = Search(r'\b(override|final)\b', line) |
| 5563 | if match: |
| 5564 | error(filename, linenum, 'readability/inheritance', 4, |
| 5565 | ('"virtual" is redundant since function is ' |
| 5566 | 'already declared as "%s"' % match.group(1))) |
| 5567 | |
| 5568 | # Set end_col to check whole lines after we are done with the |
| 5569 | # first line. |
| 5570 | end_col = 0 |
| 5571 | if Search(r'[^\w]\s*$', line): |
| 5572 | break |
| 5573 | |
| 5574 | |
| 5575 | def CheckRedundantOverrideOrFinal(filename, clean_lines, linenum, error): |
| 5576 | """Check if line contains a redundant "override" or "final" virt-specifier. |
| 5577 | |
| 5578 | Args: |
| 5579 | filename: The name of the current file. |
| 5580 | clean_lines: A CleansedLines instance containing the file. |
| 5581 | linenum: The number of the line to check. |
| 5582 | error: The function to call with any errors found. |
| 5583 | """ |
[email protected] | 255f2be | 2014-12-05 22:19:55 | [diff] [blame] | 5584 | # Look for closing parenthesis nearby. We need one to confirm where |
| 5585 | # the declarator ends and where the virt-specifier starts to avoid |
| 5586 | # false positives. |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 5587 | line = clean_lines.elided[linenum] |
[email protected] | 255f2be | 2014-12-05 22:19:55 | [diff] [blame] | 5588 | declarator_end = line.rfind(')') |
| 5589 | if declarator_end >= 0: |
| 5590 | fragment = line[declarator_end:] |
| 5591 | else: |
| 5592 | if linenum > 1 and clean_lines.elided[linenum - 1].rfind(')') >= 0: |
| 5593 | fragment = line |
| 5594 | else: |
| 5595 | return |
| 5596 | |
| 5597 | # Check that at most one of "override" or "final" is present, not both |
| 5598 | if Search(r'\boverride\b', fragment) and Search(r'\bfinal\b', fragment): |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 5599 | error(filename, linenum, 'readability/inheritance', 4, |
| 5600 | ('"override" is redundant since function is ' |
| 5601 | 'already declared as "final"')) |
| 5602 | |
| 5603 | |
| 5604 | |
| 5605 | |
| 5606 | # Returns true if we are at a new block, and it is directly |
| 5607 | # inside of a namespace. |
| 5608 | def IsBlockInNameSpace(nesting_state, is_forward_declaration): |
| 5609 | """Checks that the new block is directly in a namespace. |
| 5610 | |
| 5611 | Args: |
| 5612 | nesting_state: The _NestingState object that contains info about our state. |
| 5613 | is_forward_declaration: If the class is a forward declared class. |
| 5614 | Returns: |
| 5615 | Whether or not the new block is directly in a namespace. |
| 5616 | """ |
| 5617 | if is_forward_declaration: |
| 5618 | if len(nesting_state.stack) >= 1 and ( |
| 5619 | isinstance(nesting_state.stack[-1], _NamespaceInfo)): |
| 5620 | return True |
| 5621 | else: |
| 5622 | return False |
| 5623 | |
| 5624 | return (len(nesting_state.stack) > 1 and |
| 5625 | nesting_state.stack[-1].check_namespace_indentation and |
| 5626 | isinstance(nesting_state.stack[-2], _NamespaceInfo)) |
| 5627 | |
| 5628 | |
| 5629 | def ShouldCheckNamespaceIndentation(nesting_state, is_namespace_indent_item, |
| 5630 | raw_lines_no_comments, linenum): |
| 5631 | """This method determines if we should apply our namespace indentation check. |
| 5632 | |
| 5633 | Args: |
| 5634 | nesting_state: The current nesting state. |
| 5635 | is_namespace_indent_item: If we just put a new class on the stack, True. |
| 5636 | If the top of the stack is not a class, or we did not recently |
| 5637 | add the class, False. |
| 5638 | raw_lines_no_comments: The lines without the comments. |
| 5639 | linenum: The current line number we are processing. |
| 5640 | |
| 5641 | Returns: |
| 5642 | True if we should apply our namespace indentation check. Currently, it |
| 5643 | only works for classes and namespaces inside of a namespace. |
| 5644 | """ |
| 5645 | |
| 5646 | is_forward_declaration = IsForwardClassDeclaration(raw_lines_no_comments, |
| 5647 | linenum) |
| 5648 | |
| 5649 | if not (is_namespace_indent_item or is_forward_declaration): |
| 5650 | return False |
| 5651 | |
| 5652 | # If we are in a macro, we do not want to check the namespace indentation. |
| 5653 | if IsMacroDefinition(raw_lines_no_comments, linenum): |
| 5654 | return False |
| 5655 | |
| 5656 | return IsBlockInNameSpace(nesting_state, is_forward_declaration) |
| 5657 | |
| 5658 | |
| 5659 | # Call this method if the line is directly inside of a namespace. |
| 5660 | # If the line above is blank (excluding comments) or the start of |
| 5661 | # an inner namespace, it cannot be indented. |
| 5662 | def CheckItemIndentationInNamespace(filename, raw_lines_no_comments, linenum, |
| 5663 | error): |
| 5664 | line = raw_lines_no_comments[linenum] |
| 5665 | if Match(r'^\s+', line): |
| 5666 | error(filename, linenum, 'runtime/indentation_namespace', 4, |
| 5667 | 'Do not indent within a namespace') |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 5668 | |
| 5669 | |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 5670 | def ProcessLine(filename, file_extension, clean_lines, line, |
| 5671 | include_state, function_state, nesting_state, error, |
| 5672 | extra_check_functions=[]): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5673 | """Processes a single line in the file. |
| 5674 | |
| 5675 | Args: |
| 5676 | filename: Filename of the file that is being processed. |
| 5677 | file_extension: The extension (dot not included) of the file. |
| 5678 | clean_lines: An array of strings, each representing a line of the file, |
| 5679 | with comments stripped. |
| 5680 | line: Number of line being processed. |
| 5681 | include_state: An _IncludeState instance in which the headers are inserted. |
| 5682 | function_state: A _FunctionState instance which counts function lines, etc. |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 5683 | nesting_state: A NestingState instance which maintains information about |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 5684 | the current stack of nested blocks being parsed. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5685 | error: A callable to which errors are reported, which takes 4 arguments: |
| 5686 | filename, line number, error level, and message |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 5687 | extra_check_functions: An array of additional check functions that will be |
| 5688 | run on each source line. Each function takes 4 |
| 5689 | arguments: filename, clean_lines, line, error |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5690 | """ |
| 5691 | raw_lines = clean_lines.raw_lines |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 5692 | ParseNolintSuppressions(filename, raw_lines[line], line, error) |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 5693 | nesting_state.Update(filename, clean_lines, line, error) |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 5694 | CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line, |
| 5695 | error) |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 5696 | if nesting_state.InAsmBlock(): return |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5697 | CheckForFunctionLengths(filename, clean_lines, line, function_state, error) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5698 | CheckForMultilineCommentsAndStrings(filename, clean_lines, line, error) |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 5699 | CheckStyle(filename, clean_lines, line, file_extension, nesting_state, error) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5700 | CheckLanguage(filename, clean_lines, line, file_extension, include_state, |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 5701 | nesting_state, error) |
| 5702 | CheckForNonConstReference(filename, clean_lines, line, nesting_state, error) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5703 | CheckForNonStandardConstructs(filename, clean_lines, line, |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 5704 | nesting_state, error) |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 5705 | CheckVlogArguments(filename, clean_lines, line, error) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5706 | CheckPosixThreading(filename, clean_lines, line, error) |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 5707 | CheckInvalidIncrement(filename, clean_lines, line, error) |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 5708 | CheckMakePairUsesDeduction(filename, clean_lines, line, error) |
[email protected] | 5914675 | 2014-08-11 20:20:55 | [diff] [blame] | 5709 | CheckRedundantVirtual(filename, clean_lines, line, error) |
| 5710 | CheckRedundantOverrideOrFinal(filename, clean_lines, line, error) |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 5711 | for check_fn in extra_check_functions: |
| 5712 | check_fn(filename, clean_lines, line, error) |
[email protected] | 1744993 | 2014-07-28 22:13:33 | [diff] [blame] | 5713 | |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 5714 | def FlagCxx11Features(filename, clean_lines, linenum, error): |
| 5715 | """Flag those c++11 features that we only allow in certain places. |
| 5716 | |
| 5717 | Args: |
| 5718 | filename: The name of the current file. |
| 5719 | clean_lines: A CleansedLines instance containing the file. |
| 5720 | linenum: The number of the line to check. |
| 5721 | error: The function to call with any errors found. |
| 5722 | """ |
| 5723 | line = clean_lines.elided[linenum] |
| 5724 | |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 5725 | include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line) |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 5726 | |
| 5727 | # Flag unapproved C++ TR1 headers. |
| 5728 | if include and include.group(1).startswith('tr1/'): |
| 5729 | error(filename, linenum, 'build/c++tr1', 5, |
| 5730 | ('C++ TR1 headers such as <%s> are unapproved.') % include.group(1)) |
| 5731 | |
| 5732 | # Flag unapproved C++11 headers. |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 5733 | if include and include.group(1) in ('cfenv', |
| 5734 | 'condition_variable', |
| 5735 | 'fenv.h', |
| 5736 | 'future', |
| 5737 | 'mutex', |
| 5738 | 'thread', |
| 5739 | 'chrono', |
| 5740 | 'ratio', |
| 5741 | 'regex', |
| 5742 | 'system_error', |
| 5743 | ): |
| 5744 | error(filename, linenum, 'build/c++11', 5, |
| 5745 | ('<%s> is an unapproved C++11 header.') % include.group(1)) |
| 5746 | |
| 5747 | # The only place where we need to worry about C++11 keywords and library |
| 5748 | # features in preprocessor directives is in macro definitions. |
| 5749 | if Match(r'\s*#', line) and not Match(r'\s*#\s*define\b', line): return |
| 5750 | |
| 5751 | # These are classes and free functions. The classes are always |
| 5752 | # mentioned as std::*, but we only catch the free functions if |
| 5753 | # they're not found by ADL. They're alphabetical by header. |
| 5754 | for top_name in ( |
| 5755 | # type_traits |
| 5756 | 'alignment_of', |
| 5757 | 'aligned_union', |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 5758 | ): |
| 5759 | if Search(r'\bstd::%s\b' % top_name, line): |
| 5760 | error(filename, linenum, 'build/c++11', 5, |
| 5761 | ('std::%s is an unapproved C++11 class or function. Send c-style ' |
| 5762 | 'an example of where it would make your code more readable, and ' |
| 5763 | 'they may let you use it.') % top_name) |
| 5764 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5765 | |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 5766 | def FlagCxx14Features(filename, clean_lines, linenum, error): |
| 5767 | """Flag those C++14 features that we restrict. |
| 5768 | |
| 5769 | Args: |
| 5770 | filename: The name of the current file. |
| 5771 | clean_lines: A CleansedLines instance containing the file. |
| 5772 | linenum: The number of the line to check. |
| 5773 | error: The function to call with any errors found. |
| 5774 | """ |
| 5775 | line = clean_lines.elided[linenum] |
| 5776 | |
| 5777 | include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line) |
| 5778 | |
| 5779 | # Flag unapproved C++14 headers. |
| 5780 | if include and include.group(1) in ('scoped_allocator', 'shared_mutex'): |
| 5781 | error(filename, linenum, 'build/c++14', 5, |
| 5782 | ('<%s> is an unapproved C++14 header.') % include.group(1)) |
| 5783 | |
| 5784 | |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 5785 | def ProcessFileData(filename, file_extension, lines, error, |
| 5786 | extra_check_functions=[]): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5787 | """Performs lint checks and reports any errors to the given error function. |
| 5788 | |
| 5789 | Args: |
| 5790 | filename: Filename of the file that is being processed. |
| 5791 | file_extension: The extension (dot not included) of the file. |
| 5792 | lines: An array of strings, each representing a line of the file, with the |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 5793 | last element being empty if the file is terminated with a newline. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5794 | error: A callable to which errors are reported, which takes 4 arguments: |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 5795 | filename, line number, error level, and message |
| 5796 | extra_check_functions: An array of additional check functions that will be |
| 5797 | run on each source line. Each function takes 4 |
| 5798 | arguments: filename, clean_lines, line, error |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5799 | """ |
| 5800 | lines = (['// marker so line numbers and indices both start at 1'] + lines + |
| 5801 | ['// marker so line numbers end in a known way']) |
| 5802 | |
| 5803 | include_state = _IncludeState() |
| 5804 | function_state = _FunctionState() |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 5805 | nesting_state = NestingState() |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5806 | |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 5807 | ResetNolintSuppressions() |
| 5808 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5809 | CheckForCopyright(filename, lines, error) |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 5810 | ProcessGlobalSuppresions(lines) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5811 | RemoveMultiLineComments(filename, lines, error) |
| 5812 | clean_lines = CleansedLines(lines) |
[email protected] | 255f2be | 2014-12-05 22:19:55 | [diff] [blame] | 5813 | |
| 5814 | if file_extension == 'h': |
| 5815 | CheckForHeaderGuard(filename, clean_lines, error) |
| 5816 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5817 | for line in xrange(clean_lines.NumLines()): |
| 5818 | ProcessLine(filename, file_extension, clean_lines, line, |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 5819 | include_state, function_state, nesting_state, error, |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 5820 | extra_check_functions) |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 5821 | FlagCxx11Features(filename, clean_lines, line, error) |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 5822 | nesting_state.CheckCompletedBlocks(filename, error) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5823 | |
| 5824 | CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error) |
[email protected] | 3990c41 | 2016-02-05 20:55:12 | [diff] [blame] | 5825 | |
[email protected] | 255f2be | 2014-12-05 22:19:55 | [diff] [blame] | 5826 | # Check that the .cc file has included its header if it exists. |
[email protected] | 764ce71 | 2016-05-06 23:03:41 | [diff] [blame] | 5827 | if _IsSourceExtension(file_extension): |
[email protected] | 255f2be | 2014-12-05 22:19:55 | [diff] [blame] | 5828 | CheckHeaderFileIncluded(filename, include_state, error) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5829 | |
| 5830 | # We check here rather than inside ProcessLine so that we see raw |
| 5831 | # lines rather than "cleaned" lines. |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 5832 | CheckForBadCharacters(filename, lines, error) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5833 | |
| 5834 | CheckForNewlineAtEOF(filename, lines, error) |
| 5835 | |
[email protected] | 1744993 | 2014-07-28 22:13:33 | [diff] [blame] | 5836 | def ProcessConfigOverrides(filename): |
| 5837 | """ Loads the configuration files and processes the config overrides. |
| 5838 | |
| 5839 | Args: |
| 5840 | filename: The name of the file being processed by the linter. |
| 5841 | |
| 5842 | Returns: |
| 5843 | False if the current |filename| should not be processed further. |
| 5844 | """ |
| 5845 | |
| 5846 | abs_filename = os.path.abspath(filename) |
| 5847 | cfg_filters = [] |
| 5848 | keep_looking = True |
| 5849 | while keep_looking: |
| 5850 | abs_path, base_name = os.path.split(abs_filename) |
| 5851 | if not base_name: |
| 5852 | break # Reached the root directory. |
| 5853 | |
| 5854 | cfg_file = os.path.join(abs_path, "CPPLINT.cfg") |
| 5855 | abs_filename = abs_path |
| 5856 | if not os.path.isfile(cfg_file): |
| 5857 | continue |
| 5858 | |
| 5859 | try: |
| 5860 | with open(cfg_file) as file_handle: |
| 5861 | for line in file_handle: |
| 5862 | line, _, _ = line.partition('#') # Remove comments. |
| 5863 | if not line.strip(): |
| 5864 | continue |
| 5865 | |
| 5866 | name, _, val = line.partition('=') |
| 5867 | name = name.strip() |
| 5868 | val = val.strip() |
| 5869 | if name == 'set noparent': |
| 5870 | keep_looking = False |
| 5871 | elif name == 'filter': |
| 5872 | cfg_filters.append(val) |
| 5873 | elif name == 'exclude_files': |
| 5874 | # When matching exclude_files pattern, use the base_name of |
| 5875 | # the current file name or the directory name we are processing. |
| 5876 | # For example, if we are checking for lint errors in /foo/bar/baz.cc |
| 5877 | # and we found the .cfg file at /foo/CPPLINT.cfg, then the config |
| 5878 | # file's "exclude_files" filter is meant to be checked against "bar" |
| 5879 | # and not "baz" nor "bar/baz.cc". |
| 5880 | if base_name: |
| 5881 | pattern = re.compile(val) |
| 5882 | if pattern.match(base_name): |
| 5883 | sys.stderr.write('Ignoring "%s": file excluded by "%s". ' |
| 5884 | 'File path component "%s" matches ' |
| 5885 | 'pattern "%s"\n' % |
| 5886 | (filename, cfg_file, base_name, val)) |
| 5887 | return False |
[email protected] | 68a4fa6 | 2014-08-25 16:26:18 | [diff] [blame] | 5888 | elif name == 'linelength': |
| 5889 | global _line_length |
| 5890 | try: |
| 5891 | _line_length = int(val) |
| 5892 | except ValueError: |
| 5893 | sys.stderr.write('Line length must be numeric.') |
[email protected] | 1744993 | 2014-07-28 22:13:33 | [diff] [blame] | 5894 | else: |
| 5895 | sys.stderr.write( |
| 5896 | 'Invalid configuration option (%s) in file %s\n' % |
| 5897 | (name, cfg_file)) |
| 5898 | |
| 5899 | except IOError: |
| 5900 | sys.stderr.write( |
| 5901 | "Skipping config file '%s': Can't open for reading\n" % cfg_file) |
| 5902 | keep_looking = False |
| 5903 | |
| 5904 | # Apply all the accumulated filters in reverse order (top-level directory |
| 5905 | # config options having the least priority). |
| 5906 | for filter in reversed(cfg_filters): |
| 5907 | _AddFilters(filter) |
| 5908 | |
| 5909 | return True |
| 5910 | |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 5911 | |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 5912 | def ProcessFile(filename, vlevel, extra_check_functions=[]): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5913 | """Does google-lint on a single file. |
| 5914 | |
| 5915 | Args: |
| 5916 | filename: The name of the file to parse. |
| 5917 | |
| 5918 | vlevel: The level of errors to report. Every error of confidence |
| 5919 | >= verbose_level will be reported. 0 is a good default. |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 5920 | |
| 5921 | extra_check_functions: An array of additional check functions that will be |
| 5922 | run on each source line. Each function takes 4 |
| 5923 | arguments: filename, clean_lines, line, error |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5924 | """ |
| 5925 | |
| 5926 | _SetVerboseLevel(vlevel) |
[email protected] | 1744993 | 2014-07-28 22:13:33 | [diff] [blame] | 5927 | _BackupFilters() |
| 5928 | |
| 5929 | if not ProcessConfigOverrides(filename): |
| 5930 | _RestoreFilters() |
| 5931 | return |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5932 | |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 5933 | lf_lines = [] |
| 5934 | crlf_lines = [] |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5935 | try: |
| 5936 | # Support the UNIX convention of using "-" for stdin. Note that |
| 5937 | # we are not opening the file with universal newline support |
| 5938 | # (which codecs doesn't support anyway), so the resulting lines do |
| 5939 | # contain trailing '\r' characters if we are reading a file that |
| 5940 | # has CRLF endings. |
| 5941 | # If after the split a trailing '\r' is present, it is removed |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 5942 | # below. |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5943 | if filename == '-': |
| 5944 | lines = codecs.StreamReaderWriter(sys.stdin, |
| 5945 | codecs.getreader('utf8'), |
| 5946 | codecs.getwriter('utf8'), |
| 5947 | 'replace').read().split('\n') |
| 5948 | else: |
| 5949 | lines = codecs.open(filename, 'r', 'utf8', 'replace').read().split('\n') |
| 5950 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5951 | # Remove trailing '\r'. |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 5952 | # The -1 accounts for the extra trailing blank line we get from split() |
| 5953 | for linenum in range(len(lines) - 1): |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5954 | if lines[linenum].endswith('\r'): |
| 5955 | lines[linenum] = lines[linenum].rstrip('\r') |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 5956 | crlf_lines.append(linenum + 1) |
| 5957 | else: |
| 5958 | lf_lines.append(linenum + 1) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5959 | |
| 5960 | except IOError: |
| 5961 | sys.stderr.write( |
| 5962 | "Skipping input '%s': Can't open for reading\n" % filename) |
[email protected] | 1744993 | 2014-07-28 22:13:33 | [diff] [blame] | 5963 | _RestoreFilters() |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5964 | return |
| 5965 | |
| 5966 | # Note, if no dot is found, this will give the entire filename as the ext. |
| 5967 | file_extension = filename[filename.rfind('.') + 1:] |
| 5968 | |
| 5969 | # When reading from stdin, the extension is unknown, so no cpplint tests |
| 5970 | # should rely on the extension. |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 5971 | if filename != '-' and file_extension not in _valid_extensions: |
| 5972 | sys.stderr.write('Ignoring %s; not a valid file name ' |
| 5973 | '(%s)\n' % (filename, ', '.join(_valid_extensions))) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5974 | else: |
[email protected] | 8b8d8be | 2011-09-08 15:34:45 | [diff] [blame] | 5975 | ProcessFileData(filename, file_extension, lines, Error, |
| 5976 | extra_check_functions) |
[email protected] | d39bbb5 | 2014-06-04 22:55:20 | [diff] [blame] | 5977 | |
| 5978 | # If end-of-line sequences are a mix of LF and CR-LF, issue |
| 5979 | # warnings on the lines with CR. |
| 5980 | # |
| 5981 | # Don't issue any warnings if all lines are uniformly LF or CR-LF, |
| 5982 | # since critique can handle these just fine, and the style guide |
| 5983 | # doesn't dictate a particular end of line sequence. |
| 5984 | # |
| 5985 | # We can't depend on os.linesep to determine what the desired |
| 5986 | # end-of-line sequence should be, since that will return the |
| 5987 | # server-side end-of-line sequence. |
| 5988 | if lf_lines and crlf_lines: |
| 5989 | # Warn on every line with CR. An alternative approach might be to |
| 5990 | # check whether the file is mostly CRLF or just LF, and warn on the |
| 5991 | # minority, we bias toward LF here since most tools prefer LF. |
| 5992 | for linenum in crlf_lines: |
| 5993 | Error(filename, linenum, 'whitespace/newline', 1, |
| 5994 | 'Unexpected \\r (^M) found; better to use only \\n') |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5995 | |
| 5996 | sys.stderr.write('Done processing %s\n' % filename) |
[email protected] | 1744993 | 2014-07-28 22:13:33 | [diff] [blame] | 5997 | _RestoreFilters() |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 5998 | |
| 5999 | |
| 6000 | def PrintUsage(message): |
| 6001 | """Prints a brief usage string and exits, optionally with an error message. |
| 6002 | |
| 6003 | Args: |
| 6004 | message: The optional error message. |
| 6005 | """ |
| 6006 | sys.stderr.write(_USAGE) |
| 6007 | if message: |
| 6008 | sys.exit('\nFATAL ERROR: ' + message) |
| 6009 | else: |
| 6010 | sys.exit(1) |
| 6011 | |
| 6012 | |
| 6013 | def PrintCategories(): |
| 6014 | """Prints a list of all the error-categories used by error messages. |
| 6015 | |
| 6016 | These are the categories used to filter messages via --filter. |
| 6017 | """ |
[email protected] | 35589e6 | 2010-11-17 18:58:16 | [diff] [blame] | 6018 | sys.stderr.write(''.join(' %s\n' % cat for cat in _ERROR_CATEGORIES)) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 6019 | sys.exit(0) |
| 6020 | |
| 6021 | |
| 6022 | def ParseArguments(args): |
| 6023 | """Parses the command line arguments. |
| 6024 | |
| 6025 | This may set the output format and verbosity level as side-effects. |
| 6026 | |
| 6027 | Args: |
| 6028 | args: The command line arguments: |
| 6029 | |
| 6030 | Returns: |
| 6031 | The list of filenames to lint. |
| 6032 | """ |
| 6033 | try: |
| 6034 | (opts, filenames) = getopt.getopt(args, '', ['help', 'output=', 'verbose=', |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 6035 | 'counting=', |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 6036 | 'filter=', |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 6037 | 'root=', |
| 6038 | 'linelength=', |
sdefresne | 263e928 | 2016-07-19 09:14:22 | [diff] [blame] | 6039 | 'extensions=', |
| 6040 | 'project_root=']) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 6041 | except getopt.GetoptError: |
| 6042 | PrintUsage('Invalid arguments.') |
| 6043 | |
| 6044 | verbosity = _VerboseLevel() |
| 6045 | output_format = _OutputFormat() |
| 6046 | filters = '' |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 6047 | counting_style = '' |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 6048 | |
| 6049 | for (opt, val) in opts: |
| 6050 | if opt == '--help': |
| 6051 | PrintUsage(None) |
| 6052 | elif opt == '--output': |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 6053 | if val not in ('emacs', 'vs7', 'eclipse'): |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 6054 | PrintUsage('The only allowed output formats are emacs, vs7 and eclipse.') |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 6055 | output_format = val |
| 6056 | elif opt == '--verbose': |
| 6057 | verbosity = int(val) |
| 6058 | elif opt == '--filter': |
| 6059 | filters = val |
[email protected] | 6317a9c | 2009-06-25 00:28:19 | [diff] [blame] | 6060 | if not filters: |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 6061 | PrintCategories() |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 6062 | elif opt == '--counting': |
| 6063 | if val not in ('total', 'toplevel', 'detailed'): |
| 6064 | PrintUsage('Valid counting options are total, toplevel, and detailed') |
| 6065 | counting_style = val |
[email protected] | 3fffcec | 2013-06-07 01:04:53 | [diff] [blame] | 6066 | elif opt == '--root': |
| 6067 | global _root |
| 6068 | _root = val |
sdefresne | 263e928 | 2016-07-19 09:14:22 | [diff] [blame] | 6069 | elif opt == '--project_root': |
| 6070 | global _project_root |
| 6071 | _project_root = val |
| 6072 | if not os.path.isabs(_project_root): |
| 6073 | PrintUsage('Project root must be an absolute path.') |
[email protected] | 331fbc4 | 2014-05-09 08:48:20 | [diff] [blame] | 6074 | elif opt == '--linelength': |
| 6075 | global _line_length |
| 6076 | try: |
| 6077 | _line_length = int(val) |
| 6078 | except ValueError: |
| 6079 | PrintUsage('Line length must be digits.') |
| 6080 | elif opt == '--extensions': |
| 6081 | global _valid_extensions |
| 6082 | try: |
| 6083 | _valid_extensions = set(val.split(',')) |
| 6084 | except ValueError: |
qyearsley | 12fa6ff | 2016-08-24 16:18:40 | [diff] [blame] | 6085 | PrintUsage('Extensions must be comma separated list.') |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 6086 | |
| 6087 | if not filenames: |
| 6088 | PrintUsage('No files were specified.') |
| 6089 | |
| 6090 | _SetOutputFormat(output_format) |
| 6091 | _SetVerboseLevel(verbosity) |
| 6092 | _SetFilters(filters) |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 6093 | _SetCountingStyle(counting_style) |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 6094 | |
| 6095 | return filenames |
| 6096 | |
| 6097 | |
| 6098 | def main(): |
| 6099 | filenames = ParseArguments(sys.argv[1:]) |
| 6100 | |
| 6101 | # Change stderr to write with replacement characters so we don't die |
| 6102 | # if we try to print something containing non-ASCII characters. |
| 6103 | sys.stderr = codecs.StreamReaderWriter(sys.stderr, |
| 6104 | codecs.getreader('utf8'), |
| 6105 | codecs.getwriter('utf8'), |
| 6106 | 'replace') |
| 6107 | |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 6108 | _cpplint_state.ResetErrorCounts() |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 6109 | for filename in filenames: |
| 6110 | ProcessFile(filename, _cpplint_state.verbose_level) |
[email protected] | 26970fa | 2009-11-17 18:07:32 | [diff] [blame] | 6111 | _cpplint_state.PrintErrorCounts() |
| 6112 | |
[email protected] | fb2b8eb | 2009-04-23 21:03:42 | [diff] [blame] | 6113 | sys.exit(_cpplint_state.error_count > 0) |
| 6114 | |
| 6115 | |
| 6116 | if __name__ == '__main__': |
| 6117 | main() |