1#!/usr/bin/env python
2# pylint: skip-file
3#
4# Copyright (c) 2009 Google Inc. All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without
7# modification, are permitted provided that the following conditions are
8# met:
9#
10#    * Redistributions of source code must retain the above copyright
11# notice, this list of conditions and the following disclaimer.
12#    * Redistributions in binary form must reproduce the above
13# copyright notice, this list of conditions and the following disclaimer
14# in the documentation and/or other materials provided with the
15# distribution.
16#    * Neither the name of Google Inc. nor the names of its
17# contributors may be used to endorse or promote products derived from
18# this software without specific prior written permission.
19#
20# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
32"""Does google-lint on c++ files.
33
34The goal of this script is to identify places in the code that *may*
35be in non-compliance with google style.  It does not attempt to fix
36up these problems -- the point is to educate.  It does also not
37attempt to find all problems, or to ensure that everything it does
38find is legitimately a problem.
39
40In particular, we can get very confused by /* and // inside strings!
41We do a small hack, which is to ignore //'s with "'s after them on the
42same line, but it is far from perfect (in either direction).
43"""
44
45import codecs
46import copy
47import getopt
48import math  # for log
49import os
50import re
51import sre_compile
52import string
53import sys
54import unicodedata
55
56
57_USAGE = """
58Syntax: cpplint.py [--verbose=#] [--output=vs7] [--filter=-x,+y,...]
59                   [--counting=total|toplevel|detailed] [--root=subdir]
60                   [--linelength=digits] [--headers=x,y,...]
61                   [--quiet]
62        <file> [file] ...
63
64  The style guidelines this tries to follow are those in
65    https://google-styleguide.googlecode.com/svn/trunk/cppguide.xml
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
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.
74
75  The files passed in will be linted; at least one file must be provided.
76  Default linted extensions are .cc, .cpp, .cu, .cuh and .h.  Change the
77  extensions with the --extensions flag.
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    quiet
89      Don't print anything if no errors are found.
90
91    filter=-x,+y,...
92      Specify a comma-separated list of category-filters to apply: only
93      error messages whose category names pass the filters will be printed.
94      (Category names are printed with the message and look like
95      "[whitespace/indent]".)  Filters are evaluated left to right.
96      "-FOO" and "FOO" means "do not print categories that start with FOO".
97      "+FOO" means "do print categories that start with FOO".
98
99      Examples: --filter=-whitespace,+whitespace/braces
100                --filter=whitespace,runtime/printf,+runtime/printf_format
101                --filter=-,+build/include_what_you_use
102
103      To see a list of all the categories used in cpplint, pass no arg:
104         --filter=
105
106    counting=total|toplevel|detailed
107      The total number of errors found is always printed. If
108      'toplevel' is provided, then the count of errors in each of
109      the top-level categories like 'build' and 'whitespace' will
110      also be printed. If 'detailed' is provided, then a count
111      is provided for each category like 'build/class'.
112
113    root=subdir
114      The root directory used for deriving header guard CPP variable.
115      By default, the header guard CPP variable is calculated as the relative
116      path to the directory that contains .git, .hg, or .svn.  When this flag
117      is specified, the relative path is calculated from the specified
118      directory. If the specified directory does not exist, this flag is
119      ignored.
120
121      Examples:
122        Assuming that top/src/.git exists (and cwd=top/src), the header guard
123        CPP variables for top/src/chrome/browser/ui/browser.h are:
124
125        No flag => CHROME_BROWSER_UI_BROWSER_H_
126        --root=chrome => BROWSER_UI_BROWSER_H_
127        --root=chrome/browser => UI_BROWSER_H_
128        --root=.. => SRC_CHROME_BROWSER_UI_BROWSER_H_
129
130    linelength=digits
131      This is the allowed line length for the project. The default value is
132      80 characters.
133
134      Examples:
135        --linelength=120
136
137    extensions=extension,extension,...
138      The allowed file extensions that cpplint will check
139
140      Examples:
141        --extensions=hpp,cpp
142
143    headers=x,y,...
144      The header extensions that cpplint will treat as .h in checks. Values are
145      automatically added to --extensions list.
146
147      Examples:
148        --headers=hpp,hxx
149        --headers=hpp
150
151    cpplint.py supports per-directory configurations specified in CPPLINT.cfg
152    files. CPPLINT.cfg file can contain a number of key=value pairs.
153    Currently the following options are supported:
154
155      set noparent
156      filter=+filter1,-filter2,...
157      exclude_files=regex
158      linelength=80
159      root=subdir
160      headers=x,y,...
161
162    "set noparent" option prevents cpplint from traversing directory tree
163    upwards looking for more .cfg files in parent directories. This option
164    is usually placed in the top-level project directory.
165
166    The "filter" option is similar in function to --filter flag. It specifies
167    message filters in addition to the |_DEFAULT_FILTERS| and those specified
168    through --filter command-line flag.
169
170    "exclude_files" allows to specify a regular expression to be matched against
171    a file name. If the expression matches, the file is skipped and not run
172    through liner.
173
174    "linelength" allows to specify the allowed line length for the project.
175
176    The "root" option is similar in function to the --root flag (see example
177    above). Paths are relative to the directory of the CPPLINT.cfg.
178
179    The "headers" option is similar in function to the --headers flag
180    (see example above).
181
182    CPPLINT.cfg has an effect on files in the same directory and all
183    sub-directories, unless overridden by a nested configuration file.
184
185      Example file:
186        filter=-build/include_order,+build/include_alpha
187        exclude_files=.*\.cc
188
189    The above example disables build/include_order warning and enables
190    build/include_alpha as well as excludes all .cc from being
191    processed by linter, in the current directory (where the .cfg
192    file is located) and all sub-directories.
193"""
194
195# We categorize each error message we print.  Here are the categories.
196# We want an explicit list so we can list them all in cpplint --filter=.
197# If you add a new error message with a new category, add it to the list
198# here!  cpplint_unittest.py should tell you if you forget to do this.
199_ERROR_CATEGORIES = [
200    'build/class',
201    'build/c++11',
202    'build/c++14',
203    'build/c++tr1',
204    'build/deprecated',
205    'build/endif_comment',
206    'build/explicit_make_pair',
207    'build/forward_decl',
208    'build/header_guard',
209    'build/include',
210    'build/include_alpha',
211    'build/include_order',
212    'build/include_what_you_use',
213    'build/namespaces',
214    'build/printf_format',
215    'build/storage_class',
216    'legal/copyright',
217    'readability/alt_tokens',
218    'readability/braces',
219    'readability/casting',
220    'readability/check',
221    'readability/constructors',
222    'readability/fn_size',
223    'readability/inheritance',
224    'readability/multiline_comment',
225    'readability/multiline_string',
226    'readability/namespace',
227    'readability/nolint',
228    'readability/nul',
229    'readability/strings',
230    'readability/todo',
231    'readability/utf8',
232    'runtime/arrays',
233    'runtime/casting',
234    'runtime/explicit',
235    'runtime/int',
236    'runtime/init',
237    'runtime/invalid_increment',
238    'runtime/member_string_references',
239    'runtime/memset',
240    'runtime/indentation_namespace',
241    'runtime/operator',
242    'runtime/printf',
243    'runtime/printf_format',
244    'runtime/references',
245    'runtime/string',
246    'runtime/threadsafe_fn',
247    'runtime/vlog',
248    'whitespace/blank_line',
249    'whitespace/braces',
250    'whitespace/comma',
251    'whitespace/comments',
252    'whitespace/empty_conditional_body',
253    'whitespace/empty_if_body',
254    'whitespace/empty_loop_body',
255    'whitespace/end_of_line',
256    'whitespace/ending_newline',
257    'whitespace/forcolon',
258    'whitespace/indent',
259    'whitespace/line_length',
260    'whitespace/newline',
261    'whitespace/operators',
262    'whitespace/parens',
263    'whitespace/semicolon',
264    'whitespace/tab',
265    'whitespace/todo',
266    ]
267
268# These error categories are no longer enforced by cpplint, but for backwards-
269# compatibility they may still appear in NOLINT comments.
270_LEGACY_ERROR_CATEGORIES = [
271    'readability/streams',
272    'readability/function',
273    ]
274
275# The default state of the category filter. This is overridden by the --filter=
276# flag. By default all errors are on, so only add here categories that should be
277# off by default (i.e., categories that must be enabled by the --filter= flags).
278# All entries here should start with a '-' or '+', as in the --filter= flag.
279_DEFAULT_FILTERS = ['-build/include_alpha']
280
281# The default list of categories suppressed for C (not C++) files.
282_DEFAULT_C_SUPPRESSED_CATEGORIES = [
283    'readability/casting',
284    ]
285
286# The default list of categories suppressed for Linux Kernel files.
287_DEFAULT_KERNEL_SUPPRESSED_CATEGORIES = [
288    'whitespace/tab',
289    ]
290
291# We used to check for high-bit characters, but after much discussion we
292# decided those were OK, as long as they were in UTF-8 and didn't represent
293# hard-coded international strings, which belong in a separate i18n file.
294
295# C++ headers
296_CPP_HEADERS = frozenset([
297    # Legacy
298    'algobase.h',
299    'algo.h',
300    'alloc.h',
301    'builtinbuf.h',
302    'bvector.h',
303    'complex.h',
304    'defalloc.h',
305    'deque.h',
306    'editbuf.h',
307    'fstream.h',
308    'function.h',
309    'hash_map',
310    'hash_map.h',
311    'hash_set',
312    'hash_set.h',
313    'hashtable.h',
314    'heap.h',
315    'indstream.h',
316    'iomanip.h',
317    'iostream.h',
318    'istream.h',
319    'iterator.h',
320    'list.h',
321    'map.h',
322    'multimap.h',
323    'multiset.h',
324    'ostream.h',
325    'pair.h',
326    'parsestream.h',
327    'pfstream.h',
328    'procbuf.h',
329    'pthread_alloc',
330    'pthread_alloc.h',
331    'rope',
332    'rope.h',
333    'ropeimpl.h',
334    'set.h',
335    'slist',
336    'slist.h',
337    'stack.h',
338    'stdiostream.h',
339    'stl_alloc.h',
340    'stl_relops.h',
341    'streambuf.h',
342    'stream.h',
343    'strfile.h',
344    'strstream.h',
345    'tempbuf.h',
346    'tree.h',
347    'type_traits.h',
348    'vector.h',
349    # 17.6.1.2 C++ library headers
350    'algorithm',
351    'array',
352    'atomic',
353    'bitset',
354    'chrono',
355    'codecvt',
356    'complex',
357    'condition_variable',
358    'deque',
359    'exception',
360    'forward_list',
361    'fstream',
362    'functional',
363    'future',
364    'initializer_list',
365    'iomanip',
366    'ios',
367    'iosfwd',
368    'iostream',
369    'istream',
370    'iterator',
371    'limits',
372    'list',
373    'locale',
374    'map',
375    'memory',
376    'mutex',
377    'new',
378    'numeric',
379    'ostream',
380    'queue',
381    'random',
382    'ratio',
383    'regex',
384    'scoped_allocator',
385    'set',
386    'sstream',
387    'stack',
388    'stdexcept',
389    'streambuf',
390    'string',
391    'strstream',
392    'system_error',
393    'thread',
394    'tuple',
395    'typeindex',
396    'typeinfo',
397    'type_traits',
398    'unordered_map',
399    'unordered_set',
400    'utility',
401    'valarray',
402    'vector',
403    # 17.6.1.2 C++ headers for C library facilities
404    'cassert',
405    'ccomplex',
406    'cctype',
407    'cerrno',
408    'cfenv',
409    'cfloat',
410    'cinttypes',
411    'ciso646',
412    'climits',
413    'clocale',
414    'cmath',
415    'csetjmp',
416    'csignal',
417    'cstdalign',
418    'cstdarg',
419    'cstdbool',
420    'cstddef',
421    'cstdint',
422    'cstdio',
423    'cstdlib',
424    'cstring',
425    'ctgmath',
426    'ctime',
427    'cuchar',
428    'cwchar',
429    'cwctype',
430    ])
431
432# Type names
433_TYPES = re.compile(
434    r'^(?:'
435    # [dcl.type.simple]
436    r'(char(16_t|32_t)?)|wchar_t|'
437    r'bool|short|int|long|signed|unsigned|float|double|'
438    # [support.types]
439    r'(ptrdiff_t|size_t|max_align_t|nullptr_t)|'
440    # [cstdint.syn]
441    r'(u?int(_fast|_least)?(8|16|32|64)_t)|'
442    r'(u?int(max|ptr)_t)|'
443    r')$')
444
445
446# These headers are excluded from [build/include] and [build/include_order]
447# checks:
448# - Anything not following google file name conventions (containing an
449#   uppercase character, such as Python.h or nsStringAPI.h, for example).
450# - Lua headers.
451_THIRD_PARTY_HEADERS_PATTERN = re.compile(
452    r'^(?:[^/]*[A-Z][^/]*\.h|lua\.h|lauxlib\.h|lualib\.h)$')
453
454# Pattern for matching FileInfo.BaseName() against test file name
455_TEST_FILE_SUFFIX = r'(_test|_unittest|_regtest)$'
456
457# Pattern that matches only complete whitespace, possibly across multiple lines.
458_EMPTY_CONDITIONAL_BODY_PATTERN = re.compile(r'^\s*$', re.DOTALL)
459
460# Assertion macros.  These are defined in base/logging.h and
461# testing/base/public/gunit.h.
462_CHECK_MACROS = [
463    'DCHECK', 'CHECK',
464    'EXPECT_TRUE', 'ASSERT_TRUE',
465    'EXPECT_FALSE', 'ASSERT_FALSE',
466    ]
467
468# Replacement macros for CHECK/DCHECK/EXPECT_TRUE/EXPECT_FALSE
469_CHECK_REPLACEMENT = dict([(m, {}) for m in _CHECK_MACROS])
470
471for op, replacement in [('==', 'EQ'), ('!=', 'NE'),
472                        ('>=', 'GE'), ('>', 'GT'),
473                        ('<=', 'LE'), ('<', 'LT')]:
474  _CHECK_REPLACEMENT['DCHECK'][op] = 'DCHECK_%s' % replacement
475  _CHECK_REPLACEMENT['CHECK'][op] = 'CHECK_%s' % replacement
476  _CHECK_REPLACEMENT['EXPECT_TRUE'][op] = 'EXPECT_%s' % replacement
477  _CHECK_REPLACEMENT['ASSERT_TRUE'][op] = 'ASSERT_%s' % replacement
478
479for op, inv_replacement in [('==', 'NE'), ('!=', 'EQ'),
480                            ('>=', 'LT'), ('>', 'LE'),
481                            ('<=', 'GT'), ('<', 'GE')]:
482  _CHECK_REPLACEMENT['EXPECT_FALSE'][op] = 'EXPECT_%s' % inv_replacement
483  _CHECK_REPLACEMENT['ASSERT_FALSE'][op] = 'ASSERT_%s' % inv_replacement
484
485# Alternative tokens and their replacements.  For full list, see section 2.5
486# Alternative tokens [lex.digraph] in the C++ standard.
487#
488# Digraphs (such as '%:') are not included here since it's a mess to
489# match those on a word boundary.
490_ALT_TOKEN_REPLACEMENT = {
491    'and': '&&',
492    'bitor': '|',
493    'or': '||',
494    'xor': '^',
495    'compl': '~',
496    'bitand': '&',
497    'and_eq': '&=',
498    'or_eq': '|=',
499    'xor_eq': '^=',
500    'not': '!',
501    'not_eq': '!='
502    }
503
504# Compile regular expression that matches all the above keywords.  The "[ =()]"
505# bit is meant to avoid matching these keywords outside of boolean expressions.
506#
507# False positives include C-style multi-line comments and multi-line strings
508# but those have always been troublesome for cpplint.
509_ALT_TOKEN_REPLACEMENT_PATTERN = re.compile(
510    r'[ =()](' + ('|'.join(_ALT_TOKEN_REPLACEMENT.keys())) + r')(?=[ (]|$)')
511
512
513# These constants define types of headers for use with
514# _IncludeState.CheckNextIncludeOrder().
515_C_SYS_HEADER = 1
516_CPP_SYS_HEADER = 2
517_LIKELY_MY_HEADER = 3
518_POSSIBLE_MY_HEADER = 4
519_OTHER_HEADER = 5
520
521# These constants define the current inline assembly state
522_NO_ASM = 0       # Outside of inline assembly block
523_INSIDE_ASM = 1   # Inside inline assembly block
524_END_ASM = 2      # Last line of inline assembly block
525_BLOCK_ASM = 3    # The whole block is an inline assembly block
526
527# Match start of assembly blocks
528_MATCH_ASM = re.compile(r'^\s*(?:asm|_asm|__asm|__asm__)'
529                        r'(?:\s+(volatile|__volatile__))?'
530                        r'\s*[{(]')
531
532# Match strings that indicate we're working on a C (not C++) file.
533_SEARCH_C_FILE = re.compile(r'\b(?:LINT_C_FILE|'
534                            r'vim?:\s*.*(\s*|:)filetype=c(\s*|:|$))')
535
536# Match string that indicates we're working on a Linux Kernel file.
537_SEARCH_KERNEL_FILE = re.compile(r'\b(?:LINT_KERNEL_FILE)')
538
539_regexp_compile_cache = {}
540
541# {str, set(int)}: a map from error categories to sets of linenumbers
542# on which those errors are expected and should be suppressed.
543_error_suppressions = {}
544
545# The root directory used for deriving header guard CPP variable.
546# This is set by --root flag.
547_root = None
548_root_debug = False
549
550# The allowed line length of files.
551# This is set by --linelength flag.
552_line_length = 80
553
554# The allowed extensions for file names
555# This is set by --extensions flag.
556_valid_extensions = set(['cc', 'h', 'cpp', 'cu', 'cuh'])
557
558# Treat all headers starting with 'h' equally: .h, .hpp, .hxx etc.
559# This is set by --headers flag.
560_hpp_headers = set(['h'])
561
562# {str, bool}: a map from error categories to booleans which indicate if the
563# category should be suppressed for every line.
564_global_error_suppressions = {}
565
566def ProcessHppHeadersOption(val):
567  global _hpp_headers
568  try:
569    _hpp_headers = set(val.split(','))
570    # Automatically append to extensions list so it does not have to be set 2 times
571    _valid_extensions.update(_hpp_headers)
572  except ValueError:
573    PrintUsage('Header extensions must be comma seperated list.')
574
575def IsHeaderExtension(file_extension):
576  return file_extension in _hpp_headers
577
578def ParseNolintSuppressions(filename, raw_line, linenum, error):
579  """Updates the global list of line error-suppressions.
580
581  Parses any NOLINT comments on the current line, updating the global
582  error_suppressions store.  Reports an error if the NOLINT comment
583  was malformed.
584
585  Args:
586    filename: str, the name of the input file.
587    raw_line: str, the line of input text, with comments.
588    linenum: int, the number of the current line.
589    error: function, an error handler.
590  """
591  matched = Search(r'\bNOLINT(NEXTLINE)?\b(\([^)]+\))?', raw_line)
592  if matched:
593    if matched.group(1):
594      suppressed_line = linenum + 1
595    else:
596      suppressed_line = linenum
597    category = matched.group(2)
598    if category in (None, '(*)'):  # => "suppress all"
599      _error_suppressions.setdefault(None, set()).add(suppressed_line)
600    else:
601      if category.startswith('(') and category.endswith(')'):
602        category = category[1:-1]
603        if category in _ERROR_CATEGORIES:
604          _error_suppressions.setdefault(category, set()).add(suppressed_line)
605        elif category not in _LEGACY_ERROR_CATEGORIES:
606          error(filename, linenum, 'readability/nolint', 5,
607                'Unknown NOLINT error category: %s' % category)
608
609
610def ProcessGlobalSuppresions(lines):
611  """Updates the list of global error suppressions.
612
613  Parses any lint directives in the file that have global effect.
614
615  Args:
616    lines: An array of strings, each representing a line of the file, with the
617           last element being empty if the file is terminated with a newline.
618  """
619  for line in lines:
620    if _SEARCH_C_FILE.search(line):
621      for category in _DEFAULT_C_SUPPRESSED_CATEGORIES:
622        _global_error_suppressions[category] = True
623    if _SEARCH_KERNEL_FILE.search(line):
624      for category in _DEFAULT_KERNEL_SUPPRESSED_CATEGORIES:
625        _global_error_suppressions[category] = True
626
627
628def ResetNolintSuppressions():
629  """Resets the set of NOLINT suppressions to empty."""
630  _error_suppressions.clear()
631  _global_error_suppressions.clear()
632
633
634def IsErrorSuppressedByNolint(category, linenum):
635  """Returns true if the specified error category is suppressed on this line.
636
637  Consults the global error_suppressions map populated by
638  ParseNolintSuppressions/ProcessGlobalSuppresions/ResetNolintSuppressions.
639
640  Args:
641    category: str, the category of the error.
642    linenum: int, the current line number.
643  Returns:
644    bool, True iff the error should be suppressed due to a NOLINT comment or
645    global suppression.
646  """
647  return (_global_error_suppressions.get(category, False) or
648          linenum in _error_suppressions.get(category, set()) or
649          linenum in _error_suppressions.get(None, set()))
650
651
652def Match(pattern, s):
653  """Matches the string with the pattern, caching the compiled regexp."""
654  # The regexp compilation caching is inlined in both Match and Search for
655  # performance reasons; factoring it out into a separate function turns out
656  # to be noticeably expensive.
657  if pattern not in _regexp_compile_cache:
658    _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
659  return _regexp_compile_cache[pattern].match(s)
660
661
662def ReplaceAll(pattern, rep, s):
663  """Replaces instances of pattern in a string with a replacement.
664
665  The compiled regex is kept in a cache shared by Match and Search.
666
667  Args:
668    pattern: regex pattern
669    rep: replacement text
670    s: search string
671
672  Returns:
673    string with replacements made (or original string if no replacements)
674  """
675  if pattern not in _regexp_compile_cache:
676    _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
677  return _regexp_compile_cache[pattern].sub(rep, s)
678
679
680def Search(pattern, s):
681  """Searches the string for the pattern, caching the compiled regexp."""
682  if pattern not in _regexp_compile_cache:
683    _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
684  return _regexp_compile_cache[pattern].search(s)
685
686
687def _IsSourceExtension(s):
688  """File extension (excluding dot) matches a source file extension."""
689  return s in ('c', 'cc', 'cpp', 'cxx')
690
691
692class _IncludeState(object):
693  """Tracks line numbers for includes, and the order in which includes appear.
694
695  include_list contains list of lists of (header, line number) pairs.
696  It's a lists of lists rather than just one flat list to make it
697  easier to update across preprocessor boundaries.
698
699  Call CheckNextIncludeOrder() once for each header in the file, passing
700  in the type constants defined above. Calls in an illegal order will
701  raise an _IncludeError with an appropriate error message.
702
703  """
704  # self._section will move monotonically through this set. If it ever
705  # needs to move backwards, CheckNextIncludeOrder will raise an error.
706  _INITIAL_SECTION = 0
707  _MY_H_SECTION = 1
708  _C_SECTION = 2
709  _CPP_SECTION = 3
710  _OTHER_H_SECTION = 4
711
712  _TYPE_NAMES = {
713      _C_SYS_HEADER: 'C system header',
714      _CPP_SYS_HEADER: 'C++ system header',
715      _LIKELY_MY_HEADER: 'header this file implements',
716      _POSSIBLE_MY_HEADER: 'header this file may implement',
717      _OTHER_HEADER: 'other header',
718      }
719  _SECTION_NAMES = {
720      _INITIAL_SECTION: "... nothing. (This can't be an error.)",
721      _MY_H_SECTION: 'a header this file implements',
722      _C_SECTION: 'C system header',
723      _CPP_SECTION: 'C++ system header',
724      _OTHER_H_SECTION: 'other header',
725      }
726
727  def __init__(self):
728    self.include_list = [[]]
729    self.ResetSection('')
730
731  def FindHeader(self, header):
732    """Check if a header has already been included.
733
734    Args:
735      header: header to check.
736    Returns:
737      Line number of previous occurrence, or -1 if the header has not
738      been seen before.
739    """
740    for section_list in self.include_list:
741      for f in section_list:
742        if f[0] == header:
743          return f[1]
744    return -1
745
746  def ResetSection(self, directive):
747    """Reset section checking for preprocessor directive.
748
749    Args:
750      directive: preprocessor directive (e.g. "if", "else").
751    """
752    # The name of the current section.
753    self._section = self._INITIAL_SECTION
754    # The path of last found header.
755    self._last_header = ''
756
757    # Update list of includes.  Note that we never pop from the
758    # include list.
759    if directive in ('if', 'ifdef', 'ifndef'):
760      self.include_list.append([])
761    elif directive in ('else', 'elif'):
762      self.include_list[-1] = []
763
764  def SetLastHeader(self, header_path):
765    self._last_header = header_path
766
767  def CanonicalizeAlphabeticalOrder(self, header_path):
768    """Returns a path canonicalized for alphabetical comparison.
769
770    - replaces "-" with "_" so they both cmp the same.
771    - removes '-inl' since we don't require them to be after the main header.
772    - lowercase everything, just in case.
773
774    Args:
775      header_path: Path to be canonicalized.
776
777    Returns:
778      Canonicalized path.
779    """
780    return header_path.replace('-inl.h', '.h').replace('-', '_').lower()
781
782  def IsInAlphabeticalOrder(self, clean_lines, linenum, header_path):
783    """Check if a header is in alphabetical order with the previous header.
784
785    Args:
786      clean_lines: A CleansedLines instance containing the file.
787      linenum: The number of the line to check.
788      header_path: Canonicalized header to be checked.
789
790    Returns:
791      Returns true if the header is in alphabetical order.
792    """
793    # If previous section is different from current section, _last_header will
794    # be reset to empty string, so it's always less than current header.
795    #
796    # If previous line was a blank line, assume that the headers are
797    # intentionally sorted the way they are.
798    if (self._last_header > header_path and
799        Match(r'^\s*#\s*include\b', clean_lines.elided[linenum - 1])):
800      return False
801    return True
802
803  def CheckNextIncludeOrder(self, header_type):
804    """Returns a non-empty error message if the next header is out of order.
805
806    This function also updates the internal state to be ready to check
807    the next include.
808
809    Args:
810      header_type: One of the _XXX_HEADER constants defined above.
811
812    Returns:
813      The empty string if the header is in the right order, or an
814      error message describing what's wrong.
815
816    """
817    error_message = ('Found %s after %s' %
818                     (self._TYPE_NAMES[header_type],
819                      self._SECTION_NAMES[self._section]))
820
821    last_section = self._section
822
823    if header_type == _C_SYS_HEADER:
824      if self._section <= self._C_SECTION:
825        self._section = self._C_SECTION
826      else:
827        self._last_header = ''
828        return error_message
829    elif header_type == _CPP_SYS_HEADER:
830      if self._section <= self._CPP_SECTION:
831        self._section = self._CPP_SECTION
832      else:
833        self._last_header = ''
834        return error_message
835    elif header_type == _LIKELY_MY_HEADER:
836      if self._section <= self._MY_H_SECTION:
837        self._section = self._MY_H_SECTION
838      else:
839        self._section = self._OTHER_H_SECTION
840    elif header_type == _POSSIBLE_MY_HEADER:
841      if self._section <= self._MY_H_SECTION:
842        self._section = self._MY_H_SECTION
843      else:
844        # This will always be the fallback because we're not sure
845        # enough that the header is associated with this file.
846        self._section = self._OTHER_H_SECTION
847    else:
848      assert header_type == _OTHER_HEADER
849      self._section = self._OTHER_H_SECTION
850
851    if last_section != self._section:
852      self._last_header = ''
853
854    return ''
855
856
857class _CppLintState(object):
858  """Maintains module-wide state.."""
859
860  def __init__(self):
861    self.verbose_level = 1  # global setting.
862    self.error_count = 0    # global count of reported errors
863    # filters to apply when emitting error messages
864    self.filters = _DEFAULT_FILTERS[:]
865    # backup of filter list. Used to restore the state after each file.
866    self._filters_backup = self.filters[:]
867    self.counting = 'total'  # In what way are we counting errors?
868    self.errors_by_category = {}  # string to int dict storing error counts
869    self.quiet = False  # Suppress non-error messagess?
870
871    # output format:
872    # "emacs" - format that emacs can parse (default)
873    # "vs7" - format that Microsoft Visual Studio 7 can parse
874    self.output_format = 'emacs'
875
876  def SetOutputFormat(self, output_format):
877    """Sets the output format for errors."""
878    self.output_format = output_format
879
880  def SetQuiet(self, quiet):
881    """Sets the module's quiet settings, and returns the previous setting."""
882    last_quiet = self.quiet
883    self.quiet = quiet
884    return last_quiet
885
886  def SetVerboseLevel(self, level):
887    """Sets the module's verbosity, and returns the previous setting."""
888    last_verbose_level = self.verbose_level
889    self.verbose_level = level
890    return last_verbose_level
891
892  def SetCountingStyle(self, counting_style):
893    """Sets the module's counting options."""
894    self.counting = counting_style
895
896  def SetFilters(self, filters):
897    """Sets the error-message filters.
898
899    These filters are applied when deciding whether to emit a given
900    error message.
901
902    Args:
903      filters: A string of comma-separated filters (eg "+whitespace/indent").
904               Each filter should start with + or -; else we die.
905
906    Raises:
907      ValueError: The comma-separated filters did not all start with '+' or '-'.
908                  E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter"
909    """
910    # Default filters always have less priority than the flag ones.
911    self.filters = _DEFAULT_FILTERS[:]
912    self.AddFilters(filters)
913
914  def AddFilters(self, filters):
915    """ Adds more filters to the existing list of error-message filters. """
916    for filt in filters.split(','):
917      clean_filt = filt.strip()
918      if clean_filt:
919        self.filters.append(clean_filt)
920    for filt in self.filters:
921      if not (filt.startswith('+') or filt.startswith('-')):
922        raise ValueError('Every filter in --filters must start with + or -'
923                         ' (%s does not)' % filt)
924
925  def BackupFilters(self):
926    """ Saves the current filter list to backup storage."""
927    self._filters_backup = self.filters[:]
928
929  def RestoreFilters(self):
930    """ Restores filters previously backed up."""
931    self.filters = self._filters_backup[:]
932
933  def ResetErrorCounts(self):
934    """Sets the module's error statistic back to zero."""
935    self.error_count = 0
936    self.errors_by_category = {}
937
938  def IncrementErrorCount(self, category):
939    """Bumps the module's error statistic."""
940    self.error_count += 1
941    if self.counting in ('toplevel', 'detailed'):
942      if self.counting != 'detailed':
943        category = category.split('/')[0]
944      if category not in self.errors_by_category:
945        self.errors_by_category[category] = 0
946      self.errors_by_category[category] += 1
947
948  def PrintErrorCounts(self):
949    """Print a summary of errors by category, and the total."""
950    for category, count in self.errors_by_category.iteritems():
951      sys.stderr.write('Category \'%s\' errors found: %d\n' %
952                       (category, count))
953    sys.stdout.write('Total errors found: %d\n' % self.error_count)
954
955_cpplint_state = _CppLintState()
956
957
958def _OutputFormat():
959  """Gets the module's output format."""
960  return _cpplint_state.output_format
961
962
963def _SetOutputFormat(output_format):
964  """Sets the module's output format."""
965  _cpplint_state.SetOutputFormat(output_format)
966
967def _Quiet():
968  """Return's the module's quiet setting."""
969  return _cpplint_state.quiet
970
971def _SetQuiet(quiet):
972  """Set the module's quiet status, and return previous setting."""
973  return _cpplint_state.SetQuiet(quiet)
974
975
976def _VerboseLevel():
977  """Returns the module's verbosity setting."""
978  return _cpplint_state.verbose_level
979
980
981def _SetVerboseLevel(level):
982  """Sets the module's verbosity, and returns the previous setting."""
983  return _cpplint_state.SetVerboseLevel(level)
984
985
986def _SetCountingStyle(level):
987  """Sets the module's counting options."""
988  _cpplint_state.SetCountingStyle(level)
989
990
991def _Filters():
992  """Returns the module's list of output filters, as a list."""
993  return _cpplint_state.filters
994
995
996def _SetFilters(filters):
997  """Sets the module's error-message filters.
998
999  These filters are applied when deciding whether to emit a given
1000  error message.
1001
1002  Args:
1003    filters: A string of comma-separated filters (eg "whitespace/indent").
1004             Each filter should start with + or -; else we die.
1005  """
1006  _cpplint_state.SetFilters(filters)
1007
1008def _AddFilters(filters):
1009  """Adds more filter overrides.
1010
1011  Unlike _SetFilters, this function does not reset the current list of filters
1012  available.
1013
1014  Args:
1015    filters: A string of comma-separated filters (eg "whitespace/indent").
1016             Each filter should start with + or -; else we die.
1017  """
1018  _cpplint_state.AddFilters(filters)
1019
1020def _BackupFilters():
1021  """ Saves the current filter list to backup storage."""
1022  _cpplint_state.BackupFilters()
1023
1024def _RestoreFilters():
1025  """ Restores filters previously backed up."""
1026  _cpplint_state.RestoreFilters()
1027
1028class _FunctionState(object):
1029  """Tracks current function name and the number of lines in its body."""
1030
1031  _NORMAL_TRIGGER = 250  # for --v=0, 500 for --v=1, etc.
1032  _TEST_TRIGGER = 400    # about 50% more than _NORMAL_TRIGGER.
1033
1034  def __init__(self):
1035    self.in_a_function = False
1036    self.lines_in_function = 0
1037    self.current_function = ''
1038
1039  def Begin(self, function_name):
1040    """Start analyzing function body.
1041
1042    Args:
1043      function_name: The name of the function being tracked.
1044    """
1045    self.in_a_function = True
1046    self.lines_in_function = 0
1047    self.current_function = function_name
1048
1049  def Count(self):
1050    """Count line in current function body."""
1051    if self.in_a_function:
1052      self.lines_in_function += 1
1053
1054  def Check(self, error, filename, linenum):
1055    """Report if too many lines in function body.
1056
1057    Args:
1058      error: The function to call with any errors found.
1059      filename: The name of the current file.
1060      linenum: The number of the line to check.
1061    """
1062    if not self.in_a_function:
1063      return
1064
1065    if Match(r'T(EST|est)', self.current_function):
1066      base_trigger = self._TEST_TRIGGER
1067    else:
1068      base_trigger = self._NORMAL_TRIGGER
1069    trigger = base_trigger * 2**_VerboseLevel()
1070
1071    if self.lines_in_function > trigger:
1072      error_level = int(math.log(self.lines_in_function / base_trigger, 2))
1073      # 50 => 0, 100 => 1, 200 => 2, 400 => 3, 800 => 4, 1600 => 5, ...
1074      if error_level > 5:
1075        error_level = 5
1076      error(filename, linenum, 'readability/fn_size', error_level,
1077            'Small and focused functions are preferred:'
1078            ' %s has %d non-comment lines'
1079            ' (error triggered by exceeding %d lines).'  % (
1080                self.current_function, self.lines_in_function, trigger))
1081
1082  def End(self):
1083    """Stop analyzing function body."""
1084    self.in_a_function = False
1085
1086
1087class _IncludeError(Exception):
1088  """Indicates a problem with the include order in a file."""
1089  pass
1090
1091
1092class FileInfo(object):
1093  """Provides utility functions for filenames.
1094
1095  FileInfo provides easy access to the components of a file's path
1096  relative to the project root.
1097  """
1098
1099  def __init__(self, filename):
1100    self._filename = filename
1101
1102  def FullName(self):
1103    """Make Windows paths like Unix."""
1104    return os.path.abspath(self._filename).replace('\\', '/')
1105
1106  def RepositoryName(self):
1107    """FullName after removing the local path to the repository.
1108
1109    If we have a real absolute path name here we can try to do something smart:
1110    detecting the root of the checkout and truncating /path/to/checkout from
1111    the name so that we get header guards that don't include things like
1112    "C:\Documents and Settings\..." or "/home/username/..." in them and thus
1113    people on different computers who have checked the source out to different
1114    locations won't see bogus errors.
1115    """
1116    fullname = self.FullName()
1117
1118    if os.path.exists(fullname):
1119      project_dir = os.path.dirname(fullname)
1120
1121      if os.path.exists(os.path.join(project_dir, ".svn")):
1122        # If there's a .svn file in the current directory, we recursively look
1123        # up the directory tree for the top of the SVN checkout
1124        root_dir = project_dir
1125        one_up_dir = os.path.dirname(root_dir)
1126        while os.path.exists(os.path.join(one_up_dir, ".svn")):
1127          root_dir = os.path.dirname(root_dir)
1128          one_up_dir = os.path.dirname(one_up_dir)
1129
1130        prefix = os.path.commonprefix([root_dir, project_dir])
1131        return fullname[len(prefix) + 1:]
1132
1133      # Not SVN <= 1.6? Try to find a git, hg, or svn top level directory by
1134      # searching up from the current path.
1135      root_dir = current_dir = os.path.dirname(fullname)
1136      while current_dir != os.path.dirname(current_dir):
1137        if (os.path.exists(os.path.join(current_dir, ".git")) or
1138            os.path.exists(os.path.join(current_dir, ".hg")) or
1139            os.path.exists(os.path.join(current_dir, ".svn"))):
1140          root_dir = current_dir
1141        current_dir = os.path.dirname(current_dir)
1142
1143      if (os.path.exists(os.path.join(root_dir, ".git")) or
1144          os.path.exists(os.path.join(root_dir, ".hg")) or
1145          os.path.exists(os.path.join(root_dir, ".svn"))):
1146        prefix = os.path.commonprefix([root_dir, project_dir])
1147        return fullname[len(prefix) + 1:]
1148
1149    # Don't know what to do; header guard warnings may be wrong...
1150    return fullname
1151
1152  def Split(self):
1153    """Splits the file into the directory, basename, and extension.
1154
1155    For 'chrome/browser/browser.cc', Split() would
1156    return ('chrome/browser', 'browser', '.cc')
1157
1158    Returns:
1159      A tuple of (directory, basename, extension).
1160    """
1161
1162    googlename = self.RepositoryName()
1163    project, rest = os.path.split(googlename)
1164    return (project,) + os.path.splitext(rest)
1165
1166  def BaseName(self):
1167    """File base name - text after the final slash, before the final period."""
1168    return self.Split()[1]
1169
1170  def Extension(self):
1171    """File extension - text following the final period."""
1172    return self.Split()[2]
1173
1174  def NoExtension(self):
1175    """File has no source file extension."""
1176    return '/'.join(self.Split()[0:2])
1177
1178  def IsSource(self):
1179    """File has a source file extension."""
1180    return _IsSourceExtension(self.Extension()[1:])
1181
1182
1183def _ShouldPrintError(category, confidence, linenum):
1184  """If confidence >= verbose, category passes filter and is not suppressed."""
1185
1186  # There are three ways we might decide not to print an error message:
1187  # a "NOLINT(category)" comment appears in the source,
1188  # the verbosity level isn't high enough, or the filters filter it out.
1189  if IsErrorSuppressedByNolint(category, linenum):
1190    return False
1191
1192  if confidence < _cpplint_state.verbose_level:
1193    return False
1194
1195  is_filtered = False
1196  for one_filter in _Filters():
1197    if one_filter.startswith('-'):
1198      if category.startswith(one_filter[1:]):
1199        is_filtered = True
1200    elif one_filter.startswith('+'):
1201      if category.startswith(one_filter[1:]):
1202        is_filtered = False
1203    else:
1204      assert False  # should have been checked for in SetFilter.
1205  if is_filtered:
1206    return False
1207
1208  return True
1209
1210
1211def Error(filename, linenum, category, confidence, message):
1212  """Logs the fact we've found a lint error.
1213
1214  We log where the error was found, and also our confidence in the error,
1215  that is, how certain we are this is a legitimate style regression, and
1216  not a misidentification or a use that's sometimes justified.
1217
1218  False positives can be suppressed by the use of
1219  "cpplint(category)"  comments on the offending line.  These are
1220  parsed into _error_suppressions.
1221
1222  Args:
1223    filename: The name of the file containing the error.
1224    linenum: The number of the line containing the error.
1225    category: A string used to describe the "category" this bug
1226      falls under: "whitespace", say, or "runtime".  Categories
1227      may have a hierarchy separated by slashes: "whitespace/indent".
1228    confidence: A number from 1-5 representing a confidence score for
1229      the error, with 5 meaning that we are certain of the problem,
1230      and 1 meaning that it could be a legitimate construct.
1231    message: The error message.
1232  """
1233  if _ShouldPrintError(category, confidence, linenum):
1234    _cpplint_state.IncrementErrorCount(category)
1235    if _cpplint_state.output_format == 'vs7':
1236      sys.stderr.write('%s(%s): error cpplint: [%s] %s [%d]\n' % (
1237          filename, linenum, category, message, confidence))
1238    elif _cpplint_state.output_format == 'eclipse':
1239      sys.stderr.write('%s:%s: warning: %s  [%s] [%d]\n' % (
1240          filename, linenum, message, category, confidence))
1241    else:
1242      sys.stderr.write('%s:%s:  %s  [%s] [%d]\n' % (
1243          filename, linenum, message, category, confidence))
1244
1245
1246# Matches standard C++ escape sequences per 2.13.2.3 of the C++ standard.
1247_RE_PATTERN_CLEANSE_LINE_ESCAPES = re.compile(
1248    r'\\([abfnrtv?"\\\']|\d+|x[0-9a-fA-F]+)')
1249# Match a single C style comment on the same line.
1250_RE_PATTERN_C_COMMENTS = r'/\*(?:[^*]|\*(?!/))*\*/'
1251# Matches multi-line C style comments.
1252# This RE is a little bit more complicated than one might expect, because we
1253# have to take care of space removals tools so we can handle comments inside
1254# statements better.
1255# The current rule is: We only clear spaces from both sides when we're at the
1256# end of the line. Otherwise, we try to remove spaces from the right side,
1257# if this doesn't work we try on left side but only if there's a non-character
1258# on the right.
1259_RE_PATTERN_CLEANSE_LINE_C_COMMENTS = re.compile(
1260    r'(\s*' + _RE_PATTERN_C_COMMENTS + r'\s*$|' +
1261    _RE_PATTERN_C_COMMENTS + r'\s+|' +
1262    r'\s+' + _RE_PATTERN_C_COMMENTS + r'(?=\W)|' +
1263    _RE_PATTERN_C_COMMENTS + r')')
1264
1265
1266def IsCppString(line):
1267  """Does line terminate so, that the next symbol is in string constant.
1268
1269  This function does not consider single-line nor multi-line comments.
1270
1271  Args:
1272    line: is a partial line of code starting from the 0..n.
1273
1274  Returns:
1275    True, if next character appended to 'line' is inside a
1276    string constant.
1277  """
1278
1279  line = line.replace(r'\\', 'XX')  # after this, \\" does not match to \"
1280  return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1
1281
1282
1283def CleanseRawStrings(raw_lines):
1284  """Removes C++11 raw strings from lines.
1285
1286    Before:
1287      static const char kData[] = R"(
1288          multi-line string
1289          )";
1290
1291    After:
1292      static const char kData[] = ""
1293          (replaced by blank line)
1294          "";
1295
1296  Args:
1297    raw_lines: list of raw lines.
1298
1299  Returns:
1300    list of lines with C++11 raw strings replaced by empty strings.
1301  """
1302
1303  delimiter = None
1304  lines_without_raw_strings = []
1305  for line in raw_lines:
1306    if delimiter:
1307      # Inside a raw string, look for the end
1308      end = line.find(delimiter)
1309      if end >= 0:
1310        # Found the end of the string, match leading space for this
1311        # line and resume copying the original lines, and also insert
1312        # a "" on the last line.
1313        leading_space = Match(r'^(\s*)\S', line)
1314        line = leading_space.group(1) + '""' + line[end + len(delimiter):]
1315        delimiter = None
1316      else:
1317        # Haven't found the end yet, append a blank line.
1318        line = '""'
1319
1320    # Look for beginning of a raw string, and replace them with
1321    # empty strings.  This is done in a loop to handle multiple raw
1322    # strings on the same line.
1323    while delimiter is None:
1324      # Look for beginning of a raw string.
1325      # See 2.14.15 [lex.string] for syntax.
1326      #
1327      # Once we have matched a raw string, we check the prefix of the
1328      # line to make sure that the line is not part of a single line
1329      # comment.  It's done this way because we remove raw strings
1330      # before removing comments as opposed to removing comments
1331      # before removing raw strings.  This is because there are some
1332      # cpplint checks that requires the comments to be preserved, but
1333      # we don't want to check comments that are inside raw strings.
1334      matched = Match(r'^(.*?)\b(?:R|u8R|uR|UR|LR)"([^\s\\()]*)\((.*)$', line)
1335      if (matched and
1336          not Match(r'^([^\'"]|\'(\\.|[^\'])*\'|"(\\.|[^"])*")*//',
1337                    matched.group(1))):
1338        delimiter = ')' + matched.group(2) + '"'
1339
1340        end = matched.group(3).find(delimiter)
1341        if end >= 0:
1342          # Raw string ended on same line
1343          line = (matched.group(1) + '""' +
1344                  matched.group(3)[end + len(delimiter):])
1345          delimiter = None
1346        else:
1347          # Start of a multi-line raw string
1348          line = matched.group(1) + '""'
1349      else:
1350        break
1351
1352    lines_without_raw_strings.append(line)
1353
1354  # TODO(unknown): if delimiter is not None here, we might want to
1355  # emit a warning for unterminated string.
1356  return lines_without_raw_strings
1357
1358
1359def FindNextMultiLineCommentStart(lines, lineix):
1360  """Find the beginning marker for a multiline comment."""
1361  while lineix < len(lines):
1362    if lines[lineix].strip().startswith('/*'):
1363      # Only return this marker if the comment goes beyond this line
1364      if lines[lineix].strip().find('*/', 2) < 0:
1365        return lineix
1366    lineix += 1
1367  return len(lines)
1368
1369
1370def FindNextMultiLineCommentEnd(lines, lineix):
1371  """We are inside a comment, find the end marker."""
1372  while lineix < len(lines):
1373    if lines[lineix].strip().endswith('*/'):
1374      return lineix
1375    lineix += 1
1376  return len(lines)
1377
1378
1379def RemoveMultiLineCommentsFromRange(lines, begin, end):
1380  """Clears a range of lines for multi-line comments."""
1381  # Having // dummy comments makes the lines non-empty, so we will not get
1382  # unnecessary blank line warnings later in the code.
1383  for i in range(begin, end):
1384    lines[i] = '/**/'
1385
1386
1387def RemoveMultiLineComments(filename, lines, error):
1388  """Removes multiline (c-style) comments from lines."""
1389  lineix = 0
1390  while lineix < len(lines):
1391    lineix_begin = FindNextMultiLineCommentStart(lines, lineix)
1392    if lineix_begin >= len(lines):
1393      return
1394    lineix_end = FindNextMultiLineCommentEnd(lines, lineix_begin)
1395    if lineix_end >= len(lines):
1396      error(filename, lineix_begin + 1, 'readability/multiline_comment', 5,
1397            'Could not find end of multi-line comment')
1398      return
1399    RemoveMultiLineCommentsFromRange(lines, lineix_begin, lineix_end + 1)
1400    lineix = lineix_end + 1
1401
1402
1403def CleanseComments(line):
1404  """Removes //-comments and single-line C-style /* */ comments.
1405
1406  Args:
1407    line: A line of C++ source.
1408
1409  Returns:
1410    The line with single-line comments removed.
1411  """
1412  commentpos = line.find('//')
1413  if commentpos != -1 and not IsCppString(line[:commentpos]):
1414    line = line[:commentpos].rstrip()
1415  # get rid of /* ... */
1416  return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line)
1417
1418
1419class CleansedLines(object):
1420  """Holds 4 copies of all lines with different preprocessing applied to them.
1421
1422  1) elided member contains lines without strings and comments.
1423  2) lines member contains lines without comments.
1424  3) raw_lines member contains all the lines without processing.
1425  4) lines_without_raw_strings member is same as raw_lines, but with C++11 raw
1426     strings removed.
1427  All these members are of <type 'list'>, and of the same length.
1428  """
1429
1430  def __init__(self, lines):
1431    self.elided = []
1432    self.lines = []
1433    self.raw_lines = lines
1434    self.num_lines = len(lines)
1435    self.lines_without_raw_strings = CleanseRawStrings(lines)
1436    for linenum in range(len(self.lines_without_raw_strings)):
1437      self.lines.append(CleanseComments(
1438          self.lines_without_raw_strings[linenum]))
1439      elided = self._CollapseStrings(self.lines_without_raw_strings[linenum])
1440      self.elided.append(CleanseComments(elided))
1441
1442  def NumLines(self):
1443    """Returns the number of lines represented."""
1444    return self.num_lines
1445
1446  @staticmethod
1447  def _CollapseStrings(elided):
1448    """Collapses strings and chars on a line to simple "" or '' blocks.
1449
1450    We nix strings first so we're not fooled by text like '"http://"'
1451
1452    Args:
1453      elided: The line being processed.
1454
1455    Returns:
1456      The line with collapsed strings.
1457    """
1458    if _RE_PATTERN_INCLUDE.match(elided):
1459      return elided
1460
1461    # Remove escaped characters first to make quote/single quote collapsing
1462    # basic.  Things that look like escaped characters shouldn't occur
1463    # outside of strings and chars.
1464    elided = _RE_PATTERN_CLEANSE_LINE_ESCAPES.sub('', elided)
1465
1466    # Replace quoted strings and digit separators.  Both single quotes
1467    # and double quotes are processed in the same loop, otherwise
1468    # nested quotes wouldn't work.
1469    collapsed = ''
1470    while True:
1471      # Find the first quote character
1472      match = Match(r'^([^\'"]*)([\'"])(.*)$', elided)
1473      if not match:
1474        collapsed += elided
1475        break
1476      head, quote, tail = match.groups()
1477
1478      if quote == '"':
1479        # Collapse double quoted strings
1480        second_quote = tail.find('"')
1481        if second_quote >= 0:
1482          collapsed += head + '""'
1483          elided = tail[second_quote + 1:]
1484        else:
1485          # Unmatched double quote, don't bother processing the rest
1486          # of the line since this is probably a multiline string.
1487          collapsed += elided
1488          break
1489      else:
1490        # Found single quote, check nearby text to eliminate digit separators.
1491        #
1492        # There is no special handling for floating point here, because
1493        # the integer/fractional/exponent parts would all be parsed
1494        # correctly as long as there are digits on both sides of the
1495        # separator.  So we are fine as long as we don't see something
1496        # like "0.'3" (gcc 4.9.0 will not allow this literal).
1497        if Search(r'\b(?:0[bBxX]?|[1-9])[0-9a-fA-F]*$', head):
1498          match_literal = Match(r'^((?:\'?[0-9a-zA-Z_])*)(.*)$', "'" + tail)
1499          collapsed += head + match_literal.group(1).replace("'", '')
1500          elided = match_literal.group(2)
1501        else:
1502          second_quote = tail.find('\'')
1503          if second_quote >= 0:
1504            collapsed += head + "''"
1505            elided = tail[second_quote + 1:]
1506          else:
1507            # Unmatched single quote
1508            collapsed += elided
1509            break
1510
1511    return collapsed
1512
1513
1514def FindEndOfExpressionInLine(line, startpos, stack):
1515  """Find the position just after the end of current parenthesized expression.
1516
1517  Args:
1518    line: a CleansedLines line.
1519    startpos: start searching at this position.
1520    stack: nesting stack at startpos.
1521
1522  Returns:
1523    On finding matching end: (index just after matching end, None)
1524    On finding an unclosed expression: (-1, None)
1525    Otherwise: (-1, new stack at end of this line)
1526  """
1527  for i in xrange(startpos, len(line)):
1528    char = line[i]
1529    if char in '([{':
1530      # Found start of parenthesized expression, push to expression stack
1531      stack.append(char)
1532    elif char == '<':
1533      # Found potential start of template argument list
1534      if i > 0 and line[i - 1] == '<':
1535        # Left shift operator
1536        if stack and stack[-1] == '<':
1537          stack.pop()
1538          if not stack:
1539            return (-1, None)
1540      elif i > 0 and Search(r'\boperator\s*$', line[0:i]):
1541        # operator<, don't add to stack
1542        continue
1543      else:
1544        # Tentative start of template argument list
1545        stack.append('<')
1546    elif char in ')]}':
1547      # Found end of parenthesized expression.
1548      #
1549      # If we are currently expecting a matching '>', the pending '<'
1550      # must have been an operator.  Remove them from expression stack.
1551      while stack and stack[-1] == '<':
1552        stack.pop()
1553      if not stack:
1554        return (-1, None)
1555      if ((stack[-1] == '(' and char == ')') or
1556          (stack[-1] == '[' and char == ']') or
1557          (stack[-1] == '{' and char == '}')):
1558        stack.pop()
1559        if not stack:
1560          return (i + 1, None)
1561      else:
1562        # Mismatched parentheses
1563        return (-1, None)
1564    elif char == '>':
1565      # Found potential end of template argument list.
1566
1567      # Ignore "->" and operator functions
1568      if (i > 0 and
1569          (line[i - 1] == '-' or Search(r'\boperator\s*$', line[0:i - 1]))):
1570        continue
1571
1572      # Pop the stack if there is a matching '<'.  Otherwise, ignore
1573      # this '>' since it must be an operator.
1574      if stack:
1575        if stack[-1] == '<':
1576          stack.pop()
1577          if not stack:
1578            return (i + 1, None)
1579    elif char == ';':
1580      # Found something that look like end of statements.  If we are currently
1581      # expecting a '>', the matching '<' must have been an operator, since
1582      # template argument list should not contain statements.
1583      while stack and stack[-1] == '<':
1584        stack.pop()
1585      if not stack:
1586        return (-1, None)
1587
1588  # Did not find end of expression or unbalanced parentheses on this line
1589  return (-1, stack)
1590
1591
1592def CloseExpression(clean_lines, linenum, pos):
1593  """If input points to ( or { or [ or <, finds the position that closes it.
1594
1595  If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the
1596  linenum/pos that correspond to the closing of the expression.
1597
1598  TODO(unknown): cpplint spends a fair bit of time matching parentheses.
1599  Ideally we would want to index all opening and closing parentheses once
1600  and have CloseExpression be just a simple lookup, but due to preprocessor
1601  tricks, this is not so easy.
1602
1603  Args:
1604    clean_lines: A CleansedLines instance containing the file.
1605    linenum: The number of the line to check.
1606    pos: A position on the line.
1607
1608  Returns:
1609    A tuple (line, linenum, pos) pointer *past* the closing brace, or
1610    (line, len(lines), -1) if we never find a close.  Note we ignore
1611    strings and comments when matching; and the line we return is the
1612    'cleansed' line at linenum.
1613  """
1614
1615  line = clean_lines.elided[linenum]
1616  if (line[pos] not in '({[<') or Match(r'<[<=]', line[pos:]):
1617    return (line, clean_lines.NumLines(), -1)
1618
1619  # Check first line
1620  (end_pos, stack) = FindEndOfExpressionInLine(line, pos, [])
1621  if end_pos > -1:
1622    return (line, linenum, end_pos)
1623
1624  # Continue scanning forward
1625  while stack and linenum < clean_lines.NumLines() - 1:
1626    linenum += 1
1627    line = clean_lines.elided[linenum]
1628    (end_pos, stack) = FindEndOfExpressionInLine(line, 0, stack)
1629    if end_pos > -1:
1630      return (line, linenum, end_pos)
1631
1632  # Did not find end of expression before end of file, give up
1633  return (line, clean_lines.NumLines(), -1)
1634
1635
1636def FindStartOfExpressionInLine(line, endpos, stack):
1637  """Find position at the matching start of current expression.
1638
1639  This is almost the reverse of FindEndOfExpressionInLine, but note
1640  that the input position and returned position differs by 1.
1641
1642  Args:
1643    line: a CleansedLines line.
1644    endpos: start searching at this position.
1645    stack: nesting stack at endpos.
1646
1647  Returns:
1648    On finding matching start: (index at matching start, None)
1649    On finding an unclosed expression: (-1, None)
1650    Otherwise: (-1, new stack at beginning of this line)
1651  """
1652  i = endpos
1653  while i >= 0:
1654    char = line[i]
1655    if char in ')]}':
1656      # Found end of expression, push to expression stack
1657      stack.append(char)
1658    elif char == '>':
1659      # Found potential end of template argument list.
1660      #
1661      # Ignore it if it's a "->" or ">=" or "operator>"
1662      if (i > 0 and
1663          (line[i - 1] == '-' or
1664           Match(r'\s>=\s', line[i - 1:]) or
1665           Search(r'\boperator\s*$', line[0:i]))):
1666        i -= 1
1667      else:
1668        stack.append('>')
1669    elif char == '<':
1670      # Found potential start of template argument list
1671      if i > 0 and line[i - 1] == '<':
1672        # Left shift operator
1673        i -= 1
1674      else:
1675        # If there is a matching '>', we can pop the expression stack.
1676        # Otherwise, ignore this '<' since it must be an operator.
1677        if stack and stack[-1] == '>':
1678          stack.pop()
1679          if not stack:
1680            return (i, None)
1681    elif char in '([{':
1682      # Found start of expression.
1683      #
1684      # If there are any unmatched '>' on the stack, they must be
1685      # operators.  Remove those.
1686      while stack and stack[-1] == '>':
1687        stack.pop()
1688      if not stack:
1689        return (-1, None)
1690      if ((char == '(' and stack[-1] == ')') or
1691          (char == '[' and stack[-1] == ']') or
1692          (char == '{' and stack[-1] == '}')):
1693        stack.pop()
1694        if not stack:
1695          return (i, None)
1696      else:
1697        # Mismatched parentheses
1698        return (-1, None)
1699    elif char == ';':
1700      # Found something that look like end of statements.  If we are currently
1701      # expecting a '<', the matching '>' must have been an operator, since
1702      # template argument list should not contain statements.
1703      while stack and stack[-1] == '>':
1704        stack.pop()
1705      if not stack:
1706        return (-1, None)
1707
1708    i -= 1
1709
1710  return (-1, stack)
1711
1712
1713def ReverseCloseExpression(clean_lines, linenum, pos):
1714  """If input points to ) or } or ] or >, finds the position that opens it.
1715
1716  If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the
1717  linenum/pos that correspond to the opening of the expression.
1718
1719  Args:
1720    clean_lines: A CleansedLines instance containing the file.
1721    linenum: The number of the line to check.
1722    pos: A position on the line.
1723
1724  Returns:
1725    A tuple (line, linenum, pos) pointer *at* the opening brace, or
1726    (line, 0, -1) if we never find the matching opening brace.  Note
1727    we ignore strings and comments when matching; and the line we
1728    return is the 'cleansed' line at linenum.
1729  """
1730  line = clean_lines.elided[linenum]
1731  if line[pos] not in ')}]>':
1732    return (line, 0, -1)
1733
1734  # Check last line
1735  (start_pos, stack) = FindStartOfExpressionInLine(line, pos, [])
1736  if start_pos > -1:
1737    return (line, linenum, start_pos)
1738
1739  # Continue scanning backward
1740  while stack and linenum > 0:
1741    linenum -= 1
1742    line = clean_lines.elided[linenum]
1743    (start_pos, stack) = FindStartOfExpressionInLine(line, len(line) - 1, stack)
1744    if start_pos > -1:
1745      return (line, linenum, start_pos)
1746
1747  # Did not find start of expression before beginning of file, give up
1748  return (line, 0, -1)
1749
1750
1751def CheckForCopyright(filename, lines, error):
1752  """Logs an error if no Copyright message appears at the top of the file."""
1753
1754  # We'll say it should occur by line 10. Don't forget there's a
1755  # dummy line at the front.
1756  for line in xrange(1, min(len(lines), 11)):
1757    if re.search(r'Copyright', lines[line], re.I): break
1758  else:                       # means no copyright line was found
1759    error(filename, 0, 'legal/copyright', 5,
1760          'No copyright message found.  '
1761          'You should have a line: "Copyright [year] <Copyright Owner>"')
1762
1763
1764def GetIndentLevel(line):
1765  """Return the number of leading spaces in line.
1766
1767  Args:
1768    line: A string to check.
1769
1770  Returns:
1771    An integer count of leading spaces, possibly zero.
1772  """
1773  indent = Match(r'^( *)\S', line)
1774  if indent:
1775    return len(indent.group(1))
1776  else:
1777    return 0
1778
1779def PathSplitToList(path):
1780  """Returns the path split into a list by the separator.
1781
1782  Args:
1783    path: An absolute or relative path (e.g. '/a/b/c/' or '../a')
1784
1785  Returns:
1786    A list of path components (e.g. ['a', 'b', 'c]).
1787  """
1788  lst = []
1789  while True:
1790    (head, tail) = os.path.split(path)
1791    if head == path: # absolute paths end
1792      lst.append(head)
1793      break
1794    if tail == path: # relative paths end
1795      lst.append(tail)
1796      break
1797
1798    path = head
1799    lst.append(tail)
1800
1801  lst.reverse()
1802  return lst
1803
1804def GetHeaderGuardCPPVariable(filename):
1805  """Returns the CPP variable that should be used as a header guard.
1806
1807  Args:
1808    filename: The name of a C++ header file.
1809
1810  Returns:
1811    The CPP variable that should be used as a header guard in the
1812    named file.
1813
1814  """
1815
1816  # Restores original filename in case that cpplint is invoked from Emacs's
1817  # flymake.
1818  filename = re.sub(r'_flymake\.h$', '.h', filename)
1819  filename = re.sub(r'/\.flymake/([^/]*)$', r'/\1', filename)
1820  # Replace 'c++' with 'cpp'.
1821  filename = filename.replace('C++', 'cpp').replace('c++', 'cpp')
1822
1823  fileinfo = FileInfo(filename)
1824  file_path_from_root = fileinfo.RepositoryName()
1825
1826  def FixupPathFromRoot():
1827    if _root_debug:
1828      sys.stderr.write("\n_root fixup, _root = '%s', repository name = '%s'\n"
1829          %(_root, fileinfo.RepositoryName()))
1830
1831    # Process the file path with the --root flag if it was set.
1832    if not _root:
1833      if _root_debug:
1834        sys.stderr.write("_root unspecified\n")
1835      return file_path_from_root
1836
1837    def StripListPrefix(lst, prefix):
1838      # f(['x', 'y'], ['w, z']) -> None  (not a valid prefix)
1839      if lst[:len(prefix)] != prefix:
1840        return None
1841      # f(['a, 'b', 'c', 'd'], ['a', 'b']) -> ['c', 'd']
1842      return lst[(len(prefix)):]
1843
1844    # root behavior:
1845    #   --root=subdir , lstrips subdir from the header guard
1846    maybe_path = StripListPrefix(PathSplitToList(file_path_from_root),
1847                                 PathSplitToList(_root))
1848
1849    if _root_debug:
1850      sys.stderr.write("_root lstrip (maybe_path=%s, file_path_from_root=%s," +
1851          " _root=%s)\n" %(maybe_path, file_path_from_root, _root))
1852
1853    if maybe_path:
1854      return os.path.join(*maybe_path)
1855
1856    #   --root=.. , will prepend the outer directory to the header guard
1857    full_path = fileinfo.FullName()
1858    root_abspath = os.path.abspath(_root)
1859
1860    maybe_path = StripListPrefix(PathSplitToList(full_path),
1861                                 PathSplitToList(root_abspath))
1862
1863    if _root_debug:
1864      sys.stderr.write("_root prepend (maybe_path=%s, full_path=%s, " +
1865          "root_abspath=%s)\n" %(maybe_path, full_path, root_abspath))
1866
1867    if maybe_path:
1868      return os.path.join(*maybe_path)
1869
1870    if _root_debug:
1871      sys.stderr.write("_root ignore, returning %s\n" %(file_path_from_root))
1872
1873    #   --root=FAKE_DIR is ignored
1874    return file_path_from_root
1875
1876  file_path_from_root = FixupPathFromRoot()
1877  return re.sub(r'[^a-zA-Z0-9]', '_', file_path_from_root).upper() + '_'
1878
1879
1880def CheckForHeaderGuard(filename, clean_lines, error):
1881  """Checks that the file contains a header guard.
1882
1883  Logs an error if no #ifndef header guard is present.  For other
1884  headers, checks that the full pathname is used.
1885
1886  Args:
1887    filename: The name of the C++ header file.
1888    clean_lines: A CleansedLines instance containing the file.
1889    error: The function to call with any errors found.
1890  """
1891
1892  # Don't check for header guards if there are error suppression
1893  # comments somewhere in this file.
1894  #
1895  # Because this is silencing a warning for a nonexistent line, we
1896  # only support the very specific NOLINT(build/header_guard) syntax,
1897  # and not the general NOLINT or NOLINT(*) syntax.
1898  raw_lines = clean_lines.lines_without_raw_strings
1899  for i in raw_lines:
1900    if Search(r'//\s*NOLINT\(build/header_guard\)', i):
1901      return
1902
1903  cppvar = GetHeaderGuardCPPVariable(filename)
1904
1905  ifndef = ''
1906  ifndef_linenum = 0
1907  define = ''
1908  endif = ''
1909  endif_linenum = 0
1910  for linenum, line in enumerate(raw_lines):
1911    linesplit = line.split()
1912    if len(linesplit) >= 2:
1913      # find the first occurrence of #ifndef and #define, save arg
1914      if not ifndef and linesplit[0] == '#ifndef':
1915        # set ifndef to the header guard presented on the #ifndef line.
1916        ifndef = linesplit[1]
1917        ifndef_linenum = linenum
1918      if not define and linesplit[0] == '#define':
1919        define = linesplit[1]
1920    # find the last occurrence of #endif, save entire line
1921    if line.startswith('#endif'):
1922      endif = line
1923      endif_linenum = linenum
1924
1925  if not ifndef or not define or ifndef != define:
1926    error(filename, 0, 'build/header_guard', 5,
1927          'No #ifndef header guard found, suggested CPP variable is: %s' %
1928          cppvar)
1929    return
1930
1931  # The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__
1932  # for backward compatibility.
1933  if ifndef != cppvar:
1934    error_level = 0
1935    if ifndef != cppvar + '_':
1936      error_level = 5
1937
1938    ParseNolintSuppressions(filename, raw_lines[ifndef_linenum], ifndef_linenum,
1939                            error)
1940    error(filename, ifndef_linenum, 'build/header_guard', error_level,
1941          '#ifndef header guard has wrong style, please use: %s' % cppvar)
1942
1943  # Check for "//" comments on endif line.
1944  ParseNolintSuppressions(filename, raw_lines[endif_linenum], endif_linenum,
1945                          error)
1946  match = Match(r'#endif\s*//\s*' + cppvar + r'(_)?\b', endif)
1947  if match:
1948    if match.group(1) == '_':
1949      # Issue low severity warning for deprecated double trailing underscore
1950      error(filename, endif_linenum, 'build/header_guard', 0,
1951            '#endif line should be "#endif  // %s"' % cppvar)
1952    return
1953
1954  # Didn't find the corresponding "//" comment.  If this file does not
1955  # contain any "//" comments at all, it could be that the compiler
1956  # only wants "/**/" comments, look for those instead.
1957  no_single_line_comments = True
1958  for i in xrange(1, len(raw_lines) - 1):
1959    line = raw_lines[i]
1960    if Match(r'^(?:(?:\'(?:\.|[^\'])*\')|(?:"(?:\.|[^"])*")|[^\'"])*//', line):
1961      no_single_line_comments = False
1962      break
1963
1964  if no_single_line_comments:
1965    match = Match(r'#endif\s*/\*\s*' + cppvar + r'(_)?\s*\*/', endif)
1966    if match:
1967      if match.group(1) == '_':
1968        # Low severity warning for double trailing underscore
1969        error(filename, endif_linenum, 'build/header_guard', 0,
1970              '#endif line should be "#endif  /* %s */"' % cppvar)
1971      return
1972
1973  # Didn't find anything
1974  error(filename, endif_linenum, 'build/header_guard', 5,
1975        '#endif line should be "#endif  // %s"' % cppvar)
1976
1977
1978def CheckHeaderFileIncluded(filename, include_state, error):
1979  """Logs an error if a .cc file does not include its header."""
1980
1981  # Do not check test files
1982  fileinfo = FileInfo(filename)
1983  if Search(_TEST_FILE_SUFFIX, fileinfo.BaseName()):
1984    return
1985
1986  headerfile = filename[0:len(filename) - len(fileinfo.Extension())] + '.h'
1987  if not os.path.exists(headerfile):
1988    return
1989  headername = FileInfo(headerfile).RepositoryName()
1990  first_include = 0
1991  for section_list in include_state.include_list:
1992    for f in section_list:
1993      if headername in f[0] or f[0] in headername:
1994        return
1995      if not first_include:
1996        first_include = f[1]
1997
1998  error(filename, first_include, 'build/include', 5,
1999        '%s should include its header file %s' % (fileinfo.RepositoryName(),
2000                                                  headername))
2001
2002
2003def CheckForBadCharacters(filename, lines, error):
2004  """Logs an error for each line containing bad characters.
2005
2006  Two kinds of bad characters:
2007
2008  1. Unicode replacement characters: These indicate that either the file
2009  contained invalid UTF-8 (likely) or Unicode replacement characters (which
2010  it shouldn't).  Note that it's possible for this to throw off line
2011  numbering if the invalid UTF-8 occurred adjacent to a newline.
2012
2013  2. NUL bytes.  These are problematic for some tools.
2014
2015  Args:
2016    filename: The name of the current file.
2017    lines: An array of strings, each representing a line of the file.
2018    error: The function to call with any errors found.
2019  """
2020  for linenum, line in enumerate(lines):
2021    if u'\ufffd' in line:
2022      error(filename, linenum, 'readability/utf8', 5,
2023            'Line contains invalid UTF-8 (or Unicode replacement character).')
2024    if '\0' in line:
2025      error(filename, linenum, 'readability/nul', 5, 'Line contains NUL byte.')
2026
2027
2028def CheckForNewlineAtEOF(filename, lines, error):
2029  """Logs an error if there is no newline char at the end of the file.
2030
2031  Args:
2032    filename: The name of the current file.
2033    lines: An array of strings, each representing a line of the file.
2034    error: The function to call with any errors found.
2035  """
2036
2037  # The array lines() was created by adding two newlines to the
2038  # original file (go figure), then splitting on \n.
2039  # To verify that the file ends in \n, we just have to make sure the
2040  # last-but-two element of lines() exists and is empty.
2041  if len(lines) < 3 or lines[-2]:
2042    error(filename, len(lines) - 2, 'whitespace/ending_newline', 5,
2043          'Could not find a newline character at the end of the file.')
2044
2045
2046def CheckForMultilineCommentsAndStrings(filename, clean_lines, linenum, error):
2047  """Logs an error if we see /* ... */ or "..." that extend past one line.
2048
2049  /* ... */ comments are legit inside macros, for one line.
2050  Otherwise, we prefer // comments, so it's ok to warn about the
2051  other.  Likewise, it's ok for strings to extend across multiple
2052  lines, as long as a line continuation character (backslash)
2053  terminates each line. Although not currently prohibited by the C++
2054  style guide, it's ugly and unnecessary. We don't do well with either
2055  in this lint program, so we warn about both.
2056
2057  Args:
2058    filename: The name of the current file.
2059    clean_lines: A CleansedLines instance containing the file.
2060    linenum: The number of the line to check.
2061    error: The function to call with any errors found.
2062  """
2063  line = clean_lines.elided[linenum]
2064
2065  # Remove all \\ (escaped backslashes) from the line. They are OK, and the
2066  # second (escaped) slash may trigger later \" detection erroneously.
2067  line = line.replace('\\\\', '')
2068
2069  if line.count('/*') > line.count('*/'):
2070    error(filename, linenum, 'readability/multiline_comment', 5,
2071          'Complex multi-line /*...*/-style comment found. '
2072          'Lint may give bogus warnings.  '
2073          'Consider replacing these with //-style comments, '
2074          'with #if 0...#endif, '
2075          'or with more clearly structured multi-line comments.')
2076
2077  if (line.count('"') - line.count('\\"')) % 2:
2078    error(filename, linenum, 'readability/multiline_string', 5,
2079          'Multi-line string ("...") found.  This lint script doesn\'t '
2080          'do well with such strings, and may give bogus warnings.  '
2081          'Use C++11 raw strings or concatenation instead.')
2082
2083
2084# (non-threadsafe name, thread-safe alternative, validation pattern)
2085#
2086# The validation pattern is used to eliminate false positives such as:
2087#  _rand();               // false positive due to substring match.
2088#  ->rand();              // some member function rand().
2089#  ACMRandom rand(seed);  // some variable named rand.
2090#  ISAACRandom rand();    // another variable named rand.
2091#
2092# Basically we require the return value of these functions to be used
2093# in some expression context on the same line by matching on some
2094# operator before the function name.  This eliminates constructors and
2095# member function calls.
2096_UNSAFE_FUNC_PREFIX = r'(?:[-+*/=%^&|(<]\s*|>\s+)'
2097_THREADING_LIST = (
2098    ('asctime(', 'asctime_r(', _UNSAFE_FUNC_PREFIX + r'asctime\([^)]+\)'),
2099    ('ctime(', 'ctime_r(', _UNSAFE_FUNC_PREFIX + r'ctime\([^)]+\)'),
2100    ('getgrgid(', 'getgrgid_r(', _UNSAFE_FUNC_PREFIX + r'getgrgid\([^)]+\)'),
2101    ('getgrnam(', 'getgrnam_r(', _UNSAFE_FUNC_PREFIX + r'getgrnam\([^)]+\)'),
2102    ('getlogin(', 'getlogin_r(', _UNSAFE_FUNC_PREFIX + r'getlogin\(\)'),
2103    ('getpwnam(', 'getpwnam_r(', _UNSAFE_FUNC_PREFIX + r'getpwnam\([^)]+\)'),
2104    ('getpwuid(', 'getpwuid_r(', _UNSAFE_FUNC_PREFIX + r'getpwuid\([^)]+\)'),
2105    ('gmtime(', 'gmtime_r(', _UNSAFE_FUNC_PREFIX + r'gmtime\([^)]+\)'),
2106    ('localtime(', 'localtime_r(', _UNSAFE_FUNC_PREFIX + r'localtime\([^)]+\)'),
2107    ('rand(', 'rand_r(', _UNSAFE_FUNC_PREFIX + r'rand\(\)'),
2108    ('strtok(', 'strtok_r(',
2109     _UNSAFE_FUNC_PREFIX + r'strtok\([^)]+\)'),
2110    ('ttyname(', 'ttyname_r(', _UNSAFE_FUNC_PREFIX + r'ttyname\([^)]+\)'),
2111    )
2112
2113
2114def CheckPosixThreading(filename, clean_lines, linenum, error):
2115  """Checks for calls to thread-unsafe functions.
2116
2117  Much code has been originally written without consideration of
2118  multi-threading. Also, engineers are relying on their old experience;
2119  they have learned posix before threading extensions were added. These
2120  tests guide the engineers to use thread-safe functions (when using
2121  posix directly).
2122
2123  Args:
2124    filename: The name of the current file.
2125    clean_lines: A CleansedLines instance containing the file.
2126    linenum: The number of the line to check.
2127    error: The function to call with any errors found.
2128  """
2129  line = clean_lines.elided[linenum]
2130  for single_thread_func, multithread_safe_func, pattern in _THREADING_LIST:
2131    # Additional pattern matching check to confirm that this is the
2132    # function we are looking for
2133    if Search(pattern, line):
2134      error(filename, linenum, 'runtime/threadsafe_fn', 2,
2135            'Consider using ' + multithread_safe_func +
2136            '...) instead of ' + single_thread_func +
2137            '...) for improved thread safety.')
2138
2139
2140def CheckVlogArguments(filename, clean_lines, linenum, error):
2141  """Checks that VLOG() is only used for defining a logging level.
2142
2143  For example, VLOG(2) is correct. VLOG(INFO), VLOG(WARNING), VLOG(ERROR), and
2144  VLOG(FATAL) are not.
2145
2146  Args:
2147    filename: The name of the current file.
2148    clean_lines: A CleansedLines instance containing the file.
2149    linenum: The number of the line to check.
2150    error: The function to call with any errors found.
2151  """
2152  line = clean_lines.elided[linenum]
2153  if Search(r'\bVLOG\((INFO|ERROR|WARNING|DFATAL|FATAL)\)', line):
2154    error(filename, linenum, 'runtime/vlog', 5,
2155          'VLOG() should be used with numeric verbosity level.  '
2156          'Use LOG() if you want symbolic severity levels.')
2157
2158# Matches invalid increment: *count++, which moves pointer instead of
2159# incrementing a value.
2160_RE_PATTERN_INVALID_INCREMENT = re.compile(
2161    r'^\s*\*\w+(\+\+|--);')
2162
2163
2164def CheckInvalidIncrement(filename, clean_lines, linenum, error):
2165  """Checks for invalid increment *count++.
2166
2167  For example following function:
2168  void increment_counter(int* count) {
2169    *count++;
2170  }
2171  is invalid, because it effectively does count++, moving pointer, and should
2172  be replaced with ++*count, (*count)++ or *count += 1.
2173
2174  Args:
2175    filename: The name of the current file.
2176    clean_lines: A CleansedLines instance containing the file.
2177    linenum: The number of the line to check.
2178    error: The function to call with any errors found.
2179  """
2180  line = clean_lines.elided[linenum]
2181  if _RE_PATTERN_INVALID_INCREMENT.match(line):
2182    error(filename, linenum, 'runtime/invalid_increment', 5,
2183          'Changing pointer instead of value (or unused value of operator*).')
2184
2185
2186def IsMacroDefinition(clean_lines, linenum):
2187  if Search(r'^#define', clean_lines[linenum]):
2188    return True
2189
2190  if linenum > 0 and Search(r'\\$', clean_lines[linenum - 1]):
2191    return True
2192
2193  return False
2194
2195
2196def IsForwardClassDeclaration(clean_lines, linenum):
2197  return Match(r'^\s*(\btemplate\b)*.*class\s+\w+;\s*$', clean_lines[linenum])
2198
2199
2200class _BlockInfo(object):
2201  """Stores information about a generic block of code."""
2202
2203  def __init__(self, linenum, seen_open_brace):
2204    self.starting_linenum = linenum
2205    self.seen_open_brace = seen_open_brace
2206    self.open_parentheses = 0
2207    self.inline_asm = _NO_ASM
2208    self.check_namespace_indentation = False
2209
2210  def CheckBegin(self, filename, clean_lines, linenum, error):
2211    """Run checks that applies to text up to the opening brace.
2212
2213    This is mostly for checking the text after the class identifier
2214    and the "{", usually where the base class is specified.  For other
2215    blocks, there isn't much to check, so we always pass.
2216
2217    Args:
2218      filename: The name of the current file.
2219      clean_lines: A CleansedLines instance containing the file.
2220      linenum: The number of the line to check.
2221      error: The function to call with any errors found.
2222    """
2223    pass
2224
2225  def CheckEnd(self, filename, clean_lines, linenum, error):
2226    """Run checks that applies to text after the closing brace.
2227
2228    This is mostly used for checking end of namespace comments.
2229
2230    Args:
2231      filename: The name of the current file.
2232      clean_lines: A CleansedLines instance containing the file.
2233      linenum: The number of the line to check.
2234      error: The function to call with any errors found.
2235    """
2236    pass
2237
2238  def IsBlockInfo(self):
2239    """Returns true if this block is a _BlockInfo.
2240
2241    This is convenient for verifying that an object is an instance of
2242    a _BlockInfo, but not an instance of any of the derived classes.
2243
2244    Returns:
2245      True for this class, False for derived classes.
2246    """
2247    return self.__class__ == _BlockInfo
2248
2249
2250class _ExternCInfo(_BlockInfo):
2251  """Stores information about an 'extern "C"' block."""
2252
2253  def __init__(self, linenum):
2254    _BlockInfo.__init__(self, linenum, True)
2255
2256
2257class _ClassInfo(_BlockInfo):
2258  """Stores information about a class."""
2259
2260  def __init__(self, name, class_or_struct, clean_lines, linenum):
2261    _BlockInfo.__init__(self, linenum, False)
2262    self.name = name
2263    self.is_derived = False
2264    self.check_namespace_indentation = True
2265    if class_or_struct == 'struct':
2266      self.access = 'public'
2267      self.is_struct = True
2268    else:
2269      self.access = 'private'
2270      self.is_struct = False
2271
2272    # Remember initial indentation level for this class.  Using raw_lines here
2273    # instead of elided to account for leading comments.
2274    self.class_indent = GetIndentLevel(clean_lines.raw_lines[linenum])
2275
2276    # Try to find the end of the class.  This will be confused by things like:
2277    #   class A {
2278    #   } *x = { ...
2279    #
2280    # But it's still good enough for CheckSectionSpacing.
2281    self.last_line = 0
2282    depth = 0
2283    for i in range(linenum, clean_lines.NumLines()):
2284      line = clean_lines.elided[i]
2285      depth += line.count('{') - line.count('}')
2286      if not depth:
2287        self.last_line = i
2288        break
2289
2290  def CheckBegin(self, filename, clean_lines, linenum, error):
2291    # Look for a bare ':'
2292    if Search('(^|[^:]):($|[^:])', clean_lines.elided[linenum]):
2293      self.is_derived = True
2294
2295  def CheckEnd(self, filename, clean_lines, linenum, error):
2296    # If there is a DISALLOW macro, it should appear near the end of
2297    # the class.
2298    seen_last_thing_in_class = False
2299    for i in xrange(linenum - 1, self.starting_linenum, -1):
2300      match = Search(
2301          r'\b(DISALLOW_COPY_AND_ASSIGN|DISALLOW_IMPLICIT_CONSTRUCTORS)\(' +
2302          self.name + r'\)',
2303          clean_lines.elided[i])
2304      if match:
2305        if seen_last_thing_in_class:
2306          error(filename, i, 'readability/constructors', 3,
2307                match.group(1) + ' should be the last thing in the class')
2308        break
2309
2310      if not Match(r'^\s*$', clean_lines.elided[i]):
2311        seen_last_thing_in_class = True
2312
2313    # Check that closing brace is aligned with beginning of the class.
2314    # Only do this if the closing brace is indented by only whitespaces.
2315    # This means we will not check single-line class definitions.
2316    indent = Match(r'^( *)\}', clean_lines.elided[linenum])
2317    if indent and len(indent.group(1)) != self.class_indent:
2318      if self.is_struct:
2319        parent = 'struct ' + self.name
2320      else:
2321        parent = 'class ' + self.name
2322      error(filename, linenum, 'whitespace/indent', 3,
2323            'Closing brace should be aligned with beginning of %s' % parent)
2324
2325
2326class _NamespaceInfo(_BlockInfo):
2327  """Stores information about a namespace."""
2328
2329  def __init__(self, name, linenum):
2330    _BlockInfo.__init__(self, linenum, False)
2331    self.name = name or ''
2332    self.check_namespace_indentation = True
2333
2334  def CheckEnd(self, filename, clean_lines, linenum, error):
2335    """Check end of namespace comments."""
2336    line = clean_lines.raw_lines[linenum]
2337
2338    # Check how many lines is enclosed in this namespace.  Don't issue
2339    # warning for missing namespace comments if there aren't enough
2340    # lines.  However, do apply checks if there is already an end of
2341    # namespace comment and it's incorrect.
2342    #
2343    # TODO(unknown): We always want to check end of namespace comments
2344    # if a namespace is large, but sometimes we also want to apply the
2345    # check if a short namespace contained nontrivial things (something
2346    # other than forward declarations).  There is currently no logic on
2347    # deciding what these nontrivial things are, so this check is
2348    # triggered by namespace size only, which works most of the time.
2349    if (linenum - self.starting_linenum < 10
2350        and not Match(r'^\s*};*\s*(//|/\*).*\bnamespace\b', line)):
2351      return
2352
2353    # Look for matching comment at end of namespace.
2354    #
2355    # Note that we accept C style "/* */" comments for terminating
2356    # namespaces, so that code that terminate namespaces inside
2357    # preprocessor macros can be cpplint clean.
2358    #
2359    # We also accept stuff like "// end of namespace <name>." with the
2360    # period at the end.
2361    #
2362    # Besides these, we don't accept anything else, otherwise we might
2363    # get false negatives when existing comment is a substring of the
2364    # expected namespace.
2365    if self.name:
2366      # Named namespace
2367      if not Match((r'^\s*};*\s*(//|/\*).*\bnamespace\s+' +
2368                    re.escape(self.name) + r'[\*/\.\\\s]*$'),
2369                   line):
2370        error(filename, linenum, 'readability/namespace', 5,
2371              'Namespace should be terminated with "// namespace %s"' %
2372              self.name)
2373    else:
2374      # Anonymous namespace
2375      if not Match(r'^\s*};*\s*(//|/\*).*\bnamespace[\*/\.\\\s]*$', line):
2376        # If "// namespace anonymous" or "// anonymous namespace (more text)",
2377        # mention "// anonymous namespace" as an acceptable form
2378        if Match(r'^\s*}.*\b(namespace anonymous|anonymous namespace)\b', line):
2379          error(filename, linenum, 'readability/namespace', 5,
2380                'Anonymous namespace should be terminated with "// namespace"'
2381                ' or "// anonymous namespace"')
2382        else:
2383          error(filename, linenum, 'readability/namespace', 5,
2384                'Anonymous namespace should be terminated with "// namespace"')
2385
2386
2387class _PreprocessorInfo(object):
2388  """Stores checkpoints of nesting stacks when #if/#else is seen."""
2389
2390  def __init__(self, stack_before_if):
2391    # The entire nesting stack before #if
2392    self.stack_before_if = stack_before_if
2393
2394    # The entire nesting stack up to #else
2395    self.stack_before_else = []
2396
2397    # Whether we have already seen #else or #elif
2398    self.seen_else = False
2399
2400
2401class NestingState(object):
2402  """Holds states related to parsing braces."""
2403
2404  def __init__(self):
2405    # Stack for tracking all braces.  An object is pushed whenever we
2406    # see a "{", and popped when we see a "}".  Only 3 types of
2407    # objects are possible:
2408    # - _ClassInfo: a class or struct.
2409    # - _NamespaceInfo: a namespace.
2410    # - _BlockInfo: some other type of block.
2411    self.stack = []
2412
2413    # Top of the previous stack before each Update().
2414    #
2415    # Because the nesting_stack is updated at the end of each line, we
2416    # had to do some convoluted checks to find out what is the current
2417    # scope at the beginning of the line.  This check is simplified by
2418    # saving the previous top of nesting stack.
2419    #
2420    # We could save the full stack, but we only need the top.  Copying
2421    # the full nesting stack would slow down cpplint by ~10%.
2422    self.previous_stack_top = []
2423
2424    # Stack of _PreprocessorInfo objects.
2425    self.pp_stack = []
2426
2427  def SeenOpenBrace(self):
2428    """Check if we have seen the opening brace for the innermost block.
2429
2430    Returns:
2431      True if we have seen the opening brace, False if the innermost
2432      block is still expecting an opening brace.
2433    """
2434    return (not self.stack) or self.stack[-1].seen_open_brace
2435
2436  def InNamespaceBody(self):
2437    """Check if we are currently one level inside a namespace body.
2438
2439    Returns:
2440      True if top of the stack is a namespace block, False otherwise.
2441    """
2442    return self.stack and isinstance(self.stack[-1], _NamespaceInfo)
2443
2444  def InExternC(self):
2445    """Check if we are currently one level inside an 'extern "C"' block.
2446
2447    Returns:
2448      True if top of the stack is an extern block, False otherwise.
2449    """
2450    return self.stack and isinstance(self.stack[-1], _ExternCInfo)
2451
2452  def InClassDeclaration(self):
2453    """Check if we are currently one level inside a class or struct declaration.
2454
2455    Returns:
2456      True if top of the stack is a class/struct, False otherwise.
2457    """
2458    return self.stack and isinstance(self.stack[-1], _ClassInfo)
2459
2460  def InAsmBlock(self):
2461    """Check if we are currently one level inside an inline ASM block.
2462
2463    Returns:
2464      True if the top of the stack is a block containing inline ASM.
2465    """
2466    return self.stack and self.stack[-1].inline_asm != _NO_ASM
2467
2468  def InTemplateArgumentList(self, clean_lines, linenum, pos):
2469    """Check if current position is inside template argument list.
2470
2471    Args:
2472      clean_lines: A CleansedLines instance containing the file.
2473      linenum: The number of the line to check.
2474      pos: position just after the suspected template argument.
2475    Returns:
2476      True if (linenum, pos) is inside template arguments.
2477    """
2478    while linenum < clean_lines.NumLines():
2479      # Find the earliest character that might indicate a template argument
2480      line = clean_lines.elided[linenum]
2481      match = Match(r'^[^{};=\[\]\.<>]*(.)', line[pos:])
2482      if not match:
2483        linenum += 1
2484        pos = 0
2485        continue
2486      token = match.group(1)
2487      pos += len(match.group(0))
2488
2489      # These things do not look like template argument list:
2490      #   class Suspect {
2491      #   class Suspect x; }
2492      if token in ('{', '}', ';'): return False
2493
2494      # These things look like template argument list:
2495      #   template <class Suspect>
2496      #   template <class Suspect = default_value>
2497      #   template <class Suspect[]>
2498      #   template <class Suspect...>
2499      if token in ('>', '=', '[', ']', '.'): return True
2500
2501      # Check if token is an unmatched '<'.
2502      # If not, move on to the next character.
2503      if token != '<':
2504        pos += 1
2505        if pos >= len(line):
2506          linenum += 1
2507          pos = 0
2508        continue
2509
2510      # We can't be sure if we just find a single '<', and need to
2511      # find the matching '>'.
2512      (_, end_line, end_pos) = CloseExpression(clean_lines, linenum, pos - 1)
2513      if end_pos < 0:
2514        # Not sure if template argument list or syntax error in file
2515        return False
2516      linenum = end_line
2517      pos = end_pos
2518    return False
2519
2520  def UpdatePreprocessor(self, line):
2521    """Update preprocessor stack.
2522
2523    We need to handle preprocessors due to classes like this:
2524      #ifdef SWIG
2525      struct ResultDetailsPageElementExtensionPoint {
2526      #else
2527      struct ResultDetailsPageElementExtensionPoint : public Extension {
2528      #endif
2529
2530    We make the following assumptions (good enough for most files):
2531    - Preprocessor condition evaluates to true from #if up to first
2532      #else/#elif/#endif.
2533
2534    - Preprocessor condition evaluates to false from #else/#elif up
2535      to #endif.  We still perform lint checks on these lines, but
2536      these do not affect nesting stack.
2537
2538    Args:
2539      line: current line to check.
2540    """
2541    if Match(r'^\s*#\s*(if|ifdef|ifndef)\b', line):
2542      # Beginning of #if block, save the nesting stack here.  The saved
2543      # stack will allow us to restore the parsing state in the #else case.
2544      self.pp_stack.append(_PreprocessorInfo(copy.deepcopy(self.stack)))
2545    elif Match(r'^\s*#\s*(else|elif)\b', line):
2546      # Beginning of #else block
2547      if self.pp_stack:
2548        if not self.pp_stack[-1].seen_else:
2549          # This is the first #else or #elif block.  Remember the
2550          # whole nesting stack up to this point.  This is what we
2551          # keep after the #endif.
2552          self.pp_stack[-1].seen_else = True
2553          self.pp_stack[-1].stack_before_else = copy.deepcopy(self.stack)
2554
2555        # Restore the stack to how it was before the #if
2556        self.stack = copy.deepcopy(self.pp_stack[-1].stack_before_if)
2557      else:
2558        # TODO(unknown): unexpected #else, issue warning?
2559        pass
2560    elif Match(r'^\s*#\s*endif\b', line):
2561      # End of #if or #else blocks.
2562      if self.pp_stack:
2563        # If we saw an #else, we will need to restore the nesting
2564        # stack to its former state before the #else, otherwise we
2565        # will just continue from where we left off.
2566        if self.pp_stack[-1].seen_else:
2567          # Here we can just use a shallow copy since we are the last
2568          # reference to it.
2569          self.stack = self.pp_stack[-1].stack_before_else
2570        # Drop the corresponding #if
2571        self.pp_stack.pop()
2572      else:
2573        # TODO(unknown): unexpected #endif, issue warning?
2574        pass
2575
2576  # TODO(unknown): Update() is too long, but we will refactor later.
2577  def Update(self, filename, clean_lines, linenum, error):
2578    """Update nesting state with current line.
2579
2580    Args:
2581      filename: The name of the current file.
2582      clean_lines: A CleansedLines instance containing the file.
2583      linenum: The number of the line to check.
2584      error: The function to call with any errors found.
2585    """
2586    line = clean_lines.elided[linenum]
2587
2588    # Remember top of the previous nesting stack.
2589    #
2590    # The stack is always pushed/popped and not modified in place, so
2591    # we can just do a shallow copy instead of copy.deepcopy.  Using
2592    # deepcopy would slow down cpplint by ~28%.
2593    if self.stack:
2594      self.previous_stack_top = self.stack[-1]
2595    else:
2596      self.previous_stack_top = None
2597
2598    # Update pp_stack
2599    self.UpdatePreprocessor(line)
2600
2601    # Count parentheses.  This is to avoid adding struct arguments to
2602    # the nesting stack.
2603    if self.stack:
2604      inner_block = self.stack[-1]
2605      depth_change = line.count('(') - line.count(')')
2606      inner_block.open_parentheses += depth_change
2607
2608      # Also check if we are starting or ending an inline assembly block.
2609      if inner_block.inline_asm in (_NO_ASM, _END_ASM):
2610        if (depth_change != 0 and
2611            inner_block.open_parentheses == 1 and
2612            _MATCH_ASM.match(line)):
2613          # Enter assembly block
2614          inner_block.inline_asm = _INSIDE_ASM
2615        else:
2616          # Not entering assembly block.  If previous line was _END_ASM,
2617          # we will now shift to _NO_ASM state.
2618          inner_block.inline_asm = _NO_ASM
2619      elif (inner_block.inline_asm == _INSIDE_ASM and
2620            inner_block.open_parentheses == 0):
2621        # Exit assembly block
2622        inner_block.inline_asm = _END_ASM
2623
2624    # Consume namespace declaration at the beginning of the line.  Do
2625    # this in a loop so that we catch same line declarations like this:
2626    #   namespace proto2 { namespace bridge { class MessageSet; } }
2627    while True:
2628      # Match start of namespace.  The "\b\s*" below catches namespace
2629      # declarations even if it weren't followed by a whitespace, this
2630      # is so that we don't confuse our namespace checker.  The
2631      # missing spaces will be flagged by CheckSpacing.
2632      namespace_decl_match = Match(r'^\s*namespace\b\s*([:\w]+)?(.*)$', line)
2633      if not namespace_decl_match:
2634        break
2635
2636      new_namespace = _NamespaceInfo(namespace_decl_match.group(1), linenum)
2637      self.stack.append(new_namespace)
2638
2639      line = namespace_decl_match.group(2)
2640      if line.find('{') != -1:
2641        new_namespace.seen_open_brace = True
2642        line = line[line.find('{') + 1:]
2643
2644    # Look for a class declaration in whatever is left of the line
2645    # after parsing namespaces.  The regexp accounts for decorated classes
2646    # such as in:
2647    #   class LOCKABLE API Object {
2648    #   };
2649    class_decl_match = Match(
2650        r'^(\s*(?:template\s*<[\w\s<>,:]*>\s*)?'
2651        r'(class|struct)\s+(?:[A-Z_]+\s+)*(\w+(?:::\w+)*))'
2652        r'(.*)$', line)
2653    if (class_decl_match and
2654        (not self.stack or self.stack[-1].open_parentheses == 0)):
2655      # We do not want to accept classes that are actually template arguments:
2656      #   template <class Ignore1,
2657      #             class Ignore2 = Default<Args>,
2658      #             template <Args> class Ignore3>
2659      #   void Function() {};
2660      #
2661      # To avoid template argument cases, we scan forward and look for
2662      # an unmatched '>'.  If we see one, assume we are inside a
2663      # template argument list.
2664      end_declaration = len(class_decl_match.group(1))
2665      if not self.InTemplateArgumentList(clean_lines, linenum, end_declaration):
2666        self.stack.append(_ClassInfo(
2667            class_decl_match.group(3), class_decl_match.group(2),
2668            clean_lines, linenum))
2669        line = class_decl_match.group(4)
2670
2671    # If we have not yet seen the opening brace for the innermost block,
2672    # run checks here.
2673    if not self.SeenOpenBrace():
2674      self.stack[-1].CheckBegin(filename, clean_lines, linenum, error)
2675
2676    # Update access control if we are inside a class/struct
2677    if self.stack and isinstance(self.stack[-1], _ClassInfo):
2678      classinfo = self.stack[-1]
2679      access_match = Match(
2680          r'^(.*)\b(public|private|protected|signals)(\s+(?:slots\s*)?)?'
2681          r':(?:[^:]|$)',
2682          line)
2683      if access_match:
2684        classinfo.access = access_match.group(2)
2685
2686        # Check that access keywords are indented +1 space.  Skip this
2687        # check if the keywords are not preceded by whitespaces.
2688        indent = access_match.group(1)
2689        if (len(indent) != classinfo.class_indent + 1 and
2690            Match(r'^\s*$', indent)):
2691          if classinfo.is_struct:
2692            parent = 'struct ' + classinfo.name
2693          else:
2694            parent = 'class ' + classinfo.name
2695          slots = ''
2696          if access_match.group(3):
2697            slots = access_match.group(3)
2698          error(filename, linenum, 'whitespace/indent', 3,
2699                '%s%s: should be indented +1 space inside %s' % (
2700                    access_match.group(2), slots, parent))
2701
2702    # Consume braces or semicolons from what's left of the line
2703    while True:
2704      # Match first brace, semicolon, or closed parenthesis.
2705      matched = Match(r'^[^{;)}]*([{;)}])(.*)$', line)
2706      if not matched:
2707        break
2708
2709      token = matched.group(1)
2710      if token == '{':
2711        # If namespace or class hasn't seen a opening brace yet, mark
2712        # namespace/class head as complete.  Push a new block onto the
2713        # stack otherwise.
2714        if not self.SeenOpenBrace():
2715          self.stack[-1].seen_open_brace = True
2716        elif Match(r'^extern\s*"[^"]*"\s*\{', line):
2717          self.stack.append(_ExternCInfo(linenum))
2718        else:
2719          self.stack.append(_BlockInfo(linenum, True))
2720          if _MATCH_ASM.match(line):
2721            self.stack[-1].inline_asm = _BLOCK_ASM
2722
2723      elif token == ';' or token == ')':
2724        # If we haven't seen an opening brace yet, but we already saw
2725        # a semicolon, this is probably a forward declaration.  Pop
2726        # the stack for these.
2727        #
2728        # Similarly, if we haven't seen an opening brace yet, but we
2729        # already saw a closing parenthesis, then these are probably
2730        # function arguments with extra "class" or "struct" keywords.
2731        # Also pop these stack for these.
2732        if not self.SeenOpenBrace():
2733          self.stack.pop()
2734      else:  # token == '}'
2735        # Perform end of block checks and pop the stack.
2736        if self.stack:
2737          self.stack[-1].CheckEnd(filename, clean_lines, linenum, error)
2738          self.stack.pop()
2739      line = matched.group(2)
2740
2741  def InnermostClass(self):
2742    """Get class info on the top of the stack.
2743
2744    Returns:
2745      A _ClassInfo object if we are inside a class, or None otherwise.
2746    """
2747    for i in range(len(self.stack), 0, -1):
2748      classinfo = self.stack[i - 1]
2749      if isinstance(classinfo, _ClassInfo):
2750        return classinfo
2751    return None
2752
2753  def CheckCompletedBlocks(self, filename, error):
2754    """Checks that all classes and namespaces have been completely parsed.
2755
2756    Call this when all lines in a file have been processed.
2757    Args:
2758      filename: The name of the current file.
2759      error: The function to call with any errors found.
2760    """
2761    # Note: This test can result in false positives if #ifdef constructs
2762    # get in the way of brace matching. See the testBuildClass test in
2763    # cpplint_unittest.py for an example of this.
2764    for obj in self.stack:
2765      if isinstance(obj, _ClassInfo):
2766        error(filename, obj.starting_linenum, 'build/class', 5,
2767              'Failed to find complete declaration of class %s' %
2768              obj.name)
2769      elif isinstance(obj, _NamespaceInfo):
2770        error(filename, obj.starting_linenum, 'build/namespaces', 5,
2771              'Failed to find complete declaration of namespace %s' %
2772              obj.name)
2773
2774
2775def CheckForNonStandardConstructs(filename, clean_lines, linenum,
2776                                  nesting_state, error):
2777  r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
2778
2779  Complain about several constructs which gcc-2 accepts, but which are
2780  not standard C++.  Warning about these in lint is one way to ease the
2781  transition to new compilers.
2782  - put storage class first (e.g. "static const" instead of "const static").
2783  - "%lld" instead of %qd" in printf-type functions.
2784  - "%1$d" is non-standard in printf-type functions.
2785  - "\%" is an undefined character escape sequence.
2786  - text after #endif is not allowed.
2787  - invalid inner-style forward declaration.
2788  - >? and <? operators, and their >?= and <?= cousins.
2789
2790  Additionally, check for constructor/destructor style violations and reference
2791  members, as it is very convenient to do so while checking for
2792  gcc-2 compliance.
2793
2794  Args:
2795    filename: The name of the current file.
2796    clean_lines: A CleansedLines instance containing the file.
2797    linenum: The number of the line to check.
2798    nesting_state: A NestingState instance which maintains information about
2799                   the current stack of nested blocks being parsed.
2800    error: A callable to which errors are reported, which takes 4 arguments:
2801           filename, line number, error level, and message
2802  """
2803
2804  # Remove comments from the line, but leave in strings for now.
2805  line = clean_lines.lines[linenum]
2806
2807  if Search(r'printf\s*\(.*".*%[-+ ]?\d*q', line):
2808    error(filename, linenum, 'runtime/printf_format', 3,
2809          '%q in format strings is deprecated.  Use %ll instead.')
2810
2811  if Search(r'printf\s*\(.*".*%\d+\$', line):
2812    error(filename, linenum, 'runtime/printf_format', 2,
2813          '%N$ formats are unconventional.  Try rewriting to avoid them.')
2814
2815  # Remove escaped backslashes before looking for undefined escapes.
2816  line = line.replace('\\\\', '')
2817
2818  if Search(r'("|\').*\\(%|\[|\(|{)', line):
2819    error(filename, linenum, 'build/printf_format', 3,
2820          '%, [, (, and { are undefined character escapes.  Unescape them.')
2821
2822  # For the rest, work with both comments and strings removed.
2823  line = clean_lines.elided[linenum]
2824
2825  if Search(r'\b(const|volatile|void|char|short|int|long'
2826            r'|float|double|signed|unsigned'
2827            r'|schar|u?int8|u?int16|u?int32|u?int64)'
2828            r'\s+(register|static|extern|typedef)\b',
2829            line):
2830    error(filename, linenum, 'build/storage_class', 5,
2831          'Storage-class specifier (static, extern, typedef, etc) should be '
2832          'at the beginning of the declaration.')
2833
2834  if Match(r'\s*#\s*endif\s*[^/\s]+', line):
2835    error(filename, linenum, 'build/endif_comment', 5,
2836          'Uncommented text after #endif is non-standard.  Use a comment.')
2837
2838  if Match(r'\s*class\s+(\w+\s*::\s*)+\w+\s*;', line):
2839    error(filename, linenum, 'build/forward_decl', 5,
2840          'Inner-style forward declarations are invalid.  Remove this line.')
2841
2842  if Search(r'(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?',
2843            line):
2844    error(filename, linenum, 'build/deprecated', 3,
2845          '>? and <? (max and min) operators are non-standard and deprecated.')
2846
2847  if Search(r'^\s*const\s*string\s*&\s*\w+\s*;', line):
2848    # TODO(unknown): Could it be expanded safely to arbitrary references,
2849    # without triggering too many false positives? The first
2850    # attempt triggered 5 warnings for mostly benign code in the regtest, hence
2851    # the restriction.
2852    # Here's the original regexp, for the reference:
2853    # type_name = r'\w+((\s*::\s*\w+)|(\s*<\s*\w+?\s*>))?'
2854    # r'\s*const\s*' + type_name + '\s*&\s*\w+\s*;'
2855    error(filename, linenum, 'runtime/member_string_references', 2,
2856          'const string& members are dangerous. It is much better to use '
2857          'alternatives, such as pointers or simple constants.')
2858
2859  # Everything else in this function operates on class declarations.
2860  # Return early if the top of the nesting stack is not a class, or if
2861  # the class head is not completed yet.
2862  classinfo = nesting_state.InnermostClass()
2863  if not classinfo or not classinfo.seen_open_brace:
2864    return
2865
2866  # The class may have been declared with namespace or classname qualifiers.
2867  # The constructor and destructor will not have those qualifiers.
2868  base_classname = classinfo.name.split('::')[-1]
2869
2870  # Look for single-argument constructors that aren't marked explicit.
2871  # Technically a valid construct, but against style.
2872  explicit_constructor_match = Match(
2873      r'\s+(?:(?:inline|constexpr)\s+)*(explicit\s+)?'
2874      r'(?:(?:inline|constexpr)\s+)*%s\s*'
2875      r'\(((?:[^()]|\([^()]*\))*)\)'
2876      % re.escape(base_classname),
2877      line)
2878
2879  if explicit_constructor_match:
2880    is_marked_explicit = explicit_constructor_match.group(1)
2881
2882    if not explicit_constructor_match.group(2):
2883      constructor_args = []
2884    else:
2885      constructor_args = explicit_constructor_match.group(2).split(',')
2886
2887    # collapse arguments so that commas in template parameter lists and function
2888    # argument parameter lists don't split arguments in two
2889    i = 0
2890    while i < len(constructor_args):
2891      constructor_arg = constructor_args[i]
2892      while (constructor_arg.count('<') > constructor_arg.count('>') or
2893             constructor_arg.count('(') > constructor_arg.count(')')):
2894        constructor_arg += ',' + constructor_args[i + 1]
2895        del constructor_args[i + 1]
2896      constructor_args[i] = constructor_arg
2897      i += 1
2898
2899    defaulted_args = [arg for arg in constructor_args if '=' in arg]
2900    noarg_constructor = (not constructor_args or  # empty arg list
2901                         # 'void' arg specifier
2902                         (len(constructor_args) == 1 and
2903                          constructor_args[0].strip() == 'void'))
2904    onearg_constructor = ((len(constructor_args) == 1 and  # exactly one arg
2905                           not noarg_constructor) or
2906                          # all but at most one arg defaulted
2907                          (len(constructor_args) >= 1 and
2908                           not noarg_constructor and
2909                           len(defaulted_args) >= len(constructor_args) - 1))
2910    initializer_list_constructor = bool(
2911        onearg_constructor and
2912        Search(r'\bstd\s*::\s*initializer_list\b', constructor_args[0]))
2913    copy_constructor = bool(
2914        onearg_constructor and
2915        Match(r'(const\s+)?%s(\s*<[^>]*>)?(\s+const)?\s*(?:<\w+>\s*)?&'
2916              % re.escape(base_classname), constructor_args[0].strip()))
2917
2918    if (not is_marked_explicit and
2919        onearg_constructor and
2920        not initializer_list_constructor and
2921        not copy_constructor):
2922      if defaulted_args:
2923        error(filename, linenum, 'runtime/explicit', 5,
2924              'Constructors callable with one argument '
2925              'should be marked explicit.')
2926      else:
2927        error(filename, linenum, 'runtime/explicit', 5,
2928              'Single-parameter constructors should be marked explicit.')
2929    elif is_marked_explicit and not onearg_constructor:
2930      if noarg_constructor:
2931        error(filename, linenum, 'runtime/explicit', 5,
2932              'Zero-parameter constructors should not be marked explicit.')
2933
2934
2935def CheckSpacingForFunctionCall(filename, clean_lines, linenum, error):
2936  """Checks for the correctness of various spacing around function calls.
2937
2938  Args:
2939    filename: The name of the current file.
2940    clean_lines: A CleansedLines instance containing the file.
2941    linenum: The number of the line to check.
2942    error: The function to call with any errors found.
2943  """
2944  line = clean_lines.elided[linenum]
2945
2946  # Since function calls often occur inside if/for/while/switch
2947  # expressions - which have their own, more liberal conventions - we
2948  # first see if we should be looking inside such an expression for a
2949  # function call, to which we can apply more strict standards.
2950  fncall = line    # if there's no control flow construct, look at whole line
2951  for pattern in (r'\bif\s*\((.*)\)\s*{',
2952                  r'\bfor\s*\((.*)\)\s*{',
2953                  r'\bwhile\s*\((.*)\)\s*[{;]',
2954                  r'\bswitch\s*\((.*)\)\s*{'):
2955    match = Search(pattern, line)
2956    if match:
2957      fncall = match.group(1)    # look inside the parens for function calls
2958      break
2959
2960  # Except in if/for/while/switch, there should never be space
2961  # immediately inside parens (eg "f( 3, 4 )").  We make an exception
2962  # for nested parens ( (a+b) + c ).  Likewise, there should never be
2963  # a space before a ( when it's a function argument.  I assume it's a
2964  # function argument when the char before the whitespace is legal in
2965  # a function name (alnum + _) and we're not starting a macro. Also ignore
2966  # pointers and references to arrays and functions coz they're too tricky:
2967  # we use a very simple way to recognize these:
2968  # " (something)(maybe-something)" or
2969  # " (something)(maybe-something," or
2970  # " (something)[something]"
2971  # Note that we assume the contents of [] to be short enough that
2972  # they'll never need to wrap.
2973  if (  # Ignore control structures.
2974      not Search(r'\b(if|for|while|switch|return|new|delete|catch|sizeof)\b',
2975                 fncall) and
2976      # Ignore pointers/references to functions.
2977      not Search(r' \([^)]+\)\([^)]*(\)|,$)', fncall) and
2978      # Ignore pointers/references to arrays.
2979      not Search(r' \([^)]+\)\[[^\]]+\]', fncall)):
2980    if Search(r'\w\s*\(\s(?!\s*\\$)', fncall):      # a ( used for a fn call
2981      error(filename, linenum, 'whitespace/parens', 4,
2982            'Extra space after ( in function call')
2983    elif Search(r'\(\s+(?!(\s*\\)|\()', fncall):
2984      error(filename, linenum, 'whitespace/parens', 2,
2985            'Extra space after (')
2986    if (Search(r'\w\s+\(', fncall) and
2987        not Search(r'_{0,2}asm_{0,2}\s+_{0,2}volatile_{0,2}\s+\(', fncall) and
2988        not Search(r'#\s*define|typedef|using\s+\w+\s*=', fncall) and
2989        not Search(r'\w\s+\((\w+::)*\*\w+\)\(', fncall) and
2990        not Search(r'\bcase\s+\(', fncall)):
2991      # TODO(unknown): Space after an operator function seem to be a common
2992      # error, silence those for now by restricting them to highest verbosity.
2993      if Search(r'\boperator_*\b', line):
2994        error(filename, linenum, 'whitespace/parens', 0,
2995              'Extra space before ( in function call')
2996      else:
2997        error(filename, linenum, 'whitespace/parens', 4,
2998              'Extra space before ( in function call')
2999    # If the ) is followed only by a newline or a { + newline, assume it's
3000    # part of a control statement (if/while/etc), and don't complain
3001    if Search(r'[^)]\s+\)\s*[^{\s]', fncall):
3002      # If the closing parenthesis is preceded by only whitespaces,
3003      # try to give a more descriptive error message.
3004      if Search(r'^\s+\)', fncall):
3005        error(filename, linenum, 'whitespace/parens', 2,
3006              'Closing ) should be moved to the previous line')
3007      else:
3008        error(filename, linenum, 'whitespace/parens', 2,
3009              'Extra space before )')
3010
3011
3012def IsBlankLine(line):
3013  """Returns true if the given line is blank.
3014
3015  We consider a line to be blank if the line is empty or consists of
3016  only white spaces.
3017
3018  Args:
3019    line: A line of a string.
3020
3021  Returns:
3022    True, if the given line is blank.
3023  """
3024  return not line or line.isspace()
3025
3026
3027def CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line,
3028                                 error):
3029  is_namespace_indent_item = (
3030      len(nesting_state.stack) > 1 and
3031      nesting_state.stack[-1].check_namespace_indentation and
3032      isinstance(nesting_state.previous_stack_top, _NamespaceInfo) and
3033      nesting_state.previous_stack_top == nesting_state.stack[-2])
3034
3035  if ShouldCheckNamespaceIndentation(nesting_state, is_namespace_indent_item,
3036                                     clean_lines.elided, line):
3037    CheckItemIndentationInNamespace(filename, clean_lines.elided,
3038                                    line, error)
3039
3040
3041def CheckForFunctionLengths(filename, clean_lines, linenum,
3042                            function_state, error):
3043  """Reports for long function bodies.
3044
3045  For an overview why this is done, see:
3046  https://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions
3047
3048  Uses a simplistic algorithm assuming other style guidelines
3049  (especially spacing) are followed.
3050  Only checks unindented functions, so class members are unchecked.
3051  Trivial bodies are unchecked, so constructors with huge initializer lists
3052  may be missed.
3053  Blank/comment lines are not counted so as to avoid encouraging the removal
3054  of vertical space and comments just to get through a lint check.
3055  NOLINT *on the last line of a function* disables this check.
3056
3057  Args:
3058    filename: The name of the current file.
3059    clean_lines: A CleansedLines instance containing the file.
3060    linenum: The number of the line to check.
3061    function_state: Current function name and lines in body so far.
3062    error: The function to call with any errors found.
3063  """
3064  lines = clean_lines.lines
3065  line = lines[linenum]
3066  joined_line = ''
3067
3068  starting_func = False
3069  regexp = r'(\w(\w|::|\*|\&|\s)*)\('  # decls * & space::name( ...
3070  match_result = Match(regexp, line)
3071  if match_result:
3072    # If the name is all caps and underscores, figure it's a macro and
3073    # ignore it, unless it's TEST or TEST_F.
3074    function_name = match_result.group(1).split()[-1]
3075    if function_name == 'TEST' or function_name == 'TEST_F' or (
3076        not Match(r'[A-Z_]+$', function_name)):
3077      starting_func = True
3078
3079  if starting_func:
3080    body_found = False
3081    for start_linenum in xrange(linenum, clean_lines.NumLines()):
3082      start_line = lines[start_linenum]
3083      joined_line += ' ' + start_line.lstrip()
3084      if Search(r'(;|})', start_line):  # Declarations and trivial functions
3085        body_found = True
3086        break                              # ... ignore
3087      elif Search(r'{', start_line):
3088        body_found = True
3089        function = Search(r'((\w|:)*)\(', line).group(1)
3090        if Match(r'TEST', function):    # Handle TEST... macros
3091          parameter_regexp = Search(r'(\(.*\))', joined_line)
3092          if parameter_regexp:             # Ignore bad syntax
3093            function += parameter_regexp.group(1)
3094        else:
3095          function += '()'
3096        function_state.Begin(function)
3097        break
3098    if not body_found:
3099      # No body for the function (or evidence of a non-function) was found.
3100      error(filename, linenum, 'readability/fn_size', 5,
3101            'Lint failed to find start of function body.')
3102  elif Match(r'^\}\s*$', line):  # function end
3103    function_state.Check(error, filename, linenum)
3104    function_state.End()
3105  elif not Match(r'^\s*$', line):
3106    function_state.Count()  # Count non-blank/non-comment lines.
3107
3108
3109_RE_PATTERN_TODO = re.compile(r'^//(\s*)TODO(\(.+?\))?:?(\s|$)?')
3110
3111
3112def CheckComment(line, filename, linenum, next_line_start, error):
3113  """Checks for common mistakes in comments.
3114
3115  Args:
3116    line: The line in question.
3117    filename: The name of the current file.
3118    linenum: The number of the line to check.
3119    next_line_start: The first non-whitespace column of the next line.
3120    error: The function to call with any errors found.
3121  """
3122  commentpos = line.find('//')
3123  if commentpos != -1:
3124    # Check if the // may be in quotes.  If so, ignore it
3125    if re.sub(r'\\.', '', line[0:commentpos]).count('"') % 2 == 0:
3126      # Allow one space for new scopes, two spaces otherwise:
3127      if (not (Match(r'^.*{ *//', line) and next_line_start == commentpos) and
3128          ((commentpos >= 1 and
3129            line[commentpos-1] not in string.whitespace) or
3130           (commentpos >= 2 and
3131            line[commentpos-2] not in string.whitespace))):
3132        error(filename, linenum, 'whitespace/comments', 2,
3133              'At least two spaces is best between code and comments')
3134
3135      # Checks for common mistakes in TODO comments.
3136      comment = line[commentpos:]
3137      match = _RE_PATTERN_TODO.match(comment)
3138      if match:
3139        # One whitespace is correct; zero whitespace is handled elsewhere.
3140        leading_whitespace = match.group(1)
3141        if len(leading_whitespace) > 1:
3142          error(filename, linenum, 'whitespace/todo', 2,
3143                'Too many spaces before TODO')
3144
3145        username = match.group(2)
3146        if not username:
3147          error(filename, linenum, 'readability/todo', 2,
3148                'Missing username in TODO; it should look like '
3149                '"// TODO(my_username): Stuff."')
3150
3151        middle_whitespace = match.group(3)
3152        # Comparisons made explicit for correctness -- pylint: disable=g-explicit-bool-comparison
3153        if middle_whitespace != ' ' and middle_whitespace != '':
3154          error(filename, linenum, 'whitespace/todo', 2,
3155                'TODO(my_username) should be followed by a space')
3156
3157      # If the comment contains an alphanumeric character, there
3158      # should be a space somewhere between it and the // unless
3159      # it's a /// or //! Doxygen comment.
3160      if (Match(r'//[^ ]*\w', comment) and
3161          not Match(r'(///|//\!)(\s+|$)', comment)):
3162        error(filename, linenum, 'whitespace/comments', 4,
3163              'Should have a space between // and comment')
3164
3165
3166def CheckSpacing(filename, clean_lines, linenum, nesting_state, error):
3167  """Checks for the correctness of various spacing issues in the code.
3168
3169  Things we check for: spaces around operators, spaces after
3170  if/for/while/switch, no spaces around parens in function calls, two
3171  spaces between code and comment, don't start a block with a blank
3172  line, don't end a function with a blank line, don't add a blank line
3173  after public/protected/private, don't have too many blank lines in a row.
3174
3175  Args:
3176    filename: The name of the current file.
3177    clean_lines: A CleansedLines instance containing the file.
3178    linenum: The number of the line to check.
3179    nesting_state: A NestingState instance which maintains information about
3180                   the current stack of nested blocks being parsed.
3181    error: The function to call with any errors found.
3182  """
3183
3184  # Don't use "elided" lines here, otherwise we can't check commented lines.
3185  # Don't want to use "raw" either, because we don't want to check inside C++11
3186  # raw strings,
3187  raw = clean_lines.lines_without_raw_strings
3188  line = raw[linenum]
3189
3190  # Before nixing comments, check if the line is blank for no good
3191  # reason.  This includes the first line after a block is opened, and
3192  # blank lines at the end of a function (ie, right before a line like '}'
3193  #
3194  # Skip all the blank line checks if we are immediately inside a
3195  # namespace body.  In other words, don't issue blank line warnings
3196  # for this block:
3197  #   namespace {
3198  #
3199  #   }
3200  #
3201  # A warning about missing end of namespace comments will be issued instead.
3202  #
3203  # Also skip blank line checks for 'extern "C"' blocks, which are formatted
3204  # like namespaces.
3205  if (IsBlankLine(line) and
3206      not nesting_state.InNamespaceBody() and
3207      not nesting_state.InExternC()):
3208    elided = clean_lines.elided
3209    prev_line = elided[linenum - 1]
3210    prevbrace = prev_line.rfind('{')
3211    # TODO(unknown): Don't complain if line before blank line, and line after,
3212    #                both start with alnums and are indented the same amount.
3213    #                This ignores whitespace at the start of a namespace block
3214    #                because those are not usually indented.
3215    if prevbrace != -1 and prev_line[prevbrace:].find('}') == -1:
3216      # OK, we have a blank line at the start of a code block.  Before we
3217      # complain, we check if it is an exception to the rule: The previous
3218      # non-empty line has the parameters of a function header that are indented
3219      # 4 spaces (because they did not fit in a 80 column line when placed on
3220      # the same line as the function name).  We also check for the case where
3221      # the previous line is indented 6 spaces, which may happen when the
3222      # initializers of a constructor do not fit into a 80 column line.
3223      exception = False
3224      if Match(r' {6}\w', prev_line):  # Initializer list?
3225        # We are looking for the opening column of initializer list, which
3226        # should be indented 4 spaces to cause 6 space indentation afterwards.
3227        search_position = linenum-2
3228        while (search_position >= 0
3229               and Match(r' {6}\w', elided[search_position])):
3230          search_position -= 1
3231        exception = (search_position >= 0
3232                     and elided[search_position][:5] == '    :')
3233      else:
3234        # Search for the function arguments or an initializer list.  We use a
3235        # simple heuristic here: If the line is indented 4 spaces; and we have a
3236        # closing paren, without the opening paren, followed by an opening brace
3237        # or colon (for initializer lists) we assume that it is the last line of
3238        # a function header.  If we have a colon indented 4 spaces, it is an
3239        # initializer list.
3240        exception = (Match(r' {4}\w[^\(]*\)\s*(const\s*)?(\{\s*$|:)',
3241                           prev_line)
3242                     or Match(r' {4}:', prev_line))
3243
3244      if not exception:
3245        error(filename, linenum, 'whitespace/blank_line', 2,
3246              'Redundant blank line at the start of a code block '
3247              'should be deleted.')
3248    # Ignore blank lines at the end of a block in a long if-else
3249    # chain, like this:
3250    #   if (condition1) {
3251    #     // Something followed by a blank line
3252    #
3253    #   } else if (condition2) {
3254    #     // Something else
3255    #   }
3256    if linenum + 1 < clean_lines.NumLines():
3257      next_line = raw[linenum + 1]
3258      if (next_line
3259          and Match(r'\s*}', next_line)
3260          and next_line.find('} else ') == -1):
3261        error(filename, linenum, 'whitespace/blank_line', 3,
3262              'Redundant blank line at the end of a code block '
3263              'should be deleted.')
3264
3265    matched = Match(r'\s*(public|protected|private):', prev_line)
3266    if matched:
3267      error(filename, linenum, 'whitespace/blank_line', 3,
3268            'Do not leave a blank line after "%s:"' % matched.group(1))
3269
3270  # Next, check comments
3271  next_line_start = 0
3272  if linenum + 1 < clean_lines.NumLines():
3273    next_line = raw[linenum + 1]
3274    next_line_start = len(next_line) - len(next_line.lstrip())
3275  CheckComment(line, filename, linenum, next_line_start, error)
3276
3277  # get rid of comments and strings
3278  line = clean_lines.elided[linenum]
3279
3280  # You shouldn't have spaces before your brackets, except maybe after
3281  # 'delete []' or 'return []() {};'
3282  if Search(r'\w\s+\[', line) and not Search(r'(?:delete|return)\s+\[', line):
3283    error(filename, linenum, 'whitespace/braces', 5,
3284          'Extra space before [')
3285
3286  # In range-based for, we wanted spaces before and after the colon, but
3287  # not around "::" tokens that might appear.
3288  if (Search(r'for *\(.*[^:]:[^: ]', line) or
3289      Search(r'for *\(.*[^: ]:[^:]', line)):
3290    error(filename, linenum, 'whitespace/forcolon', 2,
3291          'Missing space around colon in range-based for loop')
3292
3293
3294def CheckOperatorSpacing(filename, clean_lines, linenum, error):
3295  """Checks for horizontal spacing around operators.
3296
3297  Args:
3298    filename: The name of the current file.
3299    clean_lines: A CleansedLines instance containing the file.
3300    linenum: The number of the line to check.
3301    error: The function to call with any errors found.
3302  """
3303  line = clean_lines.elided[linenum]
3304
3305  # Don't try to do spacing checks for operator methods.  Do this by
3306  # replacing the troublesome characters with something else,
3307  # preserving column position for all other characters.
3308  #
3309  # The replacement is done repeatedly to avoid false positives from
3310  # operators that call operators.
3311  while True:
3312    match = Match(r'^(.*\boperator\b)(\S+)(\s*\(.*)$', line)
3313    if match:
3314      line = match.group(1) + ('_' * len(match.group(2))) + match.group(3)
3315    else:
3316      break
3317
3318  # We allow no-spaces around = within an if: "if ( (a=Foo()) == 0 )".
3319  # Otherwise not.  Note we only check for non-spaces on *both* sides;
3320  # sometimes people put non-spaces on one side when aligning ='s among
3321  # many lines (not that this is behavior that I approve of...)
3322  if ((Search(r'[\w.]=', line) or
3323       Search(r'=[\w.]', line))
3324      and not Search(r'\b(if|while|for) ', line)
3325      # Operators taken from [lex.operators] in C++11 standard.
3326      and not Search(r'(>=|<=|==|!=|&=|\^=|\|=|\+=|\*=|\/=|\%=)', line)
3327      and not Search(r'operator=', line)):
3328    error(filename, linenum, 'whitespace/operators', 4,
3329          'Missing spaces around =')
3330
3331  # It's ok not to have spaces around binary operators like + - * /, but if
3332  # there's too little whitespace, we get concerned.  It's hard to tell,
3333  # though, so we punt on this one for now.  TODO.
3334
3335  # You should always have whitespace around binary operators.
3336  #
3337  # Check <= and >= first to avoid false positives with < and >, then
3338  # check non-include lines for spacing around < and >.
3339  #
3340  # If the operator is followed by a comma, assume it's be used in a
3341  # macro context and don't do any checks.  This avoids false
3342  # positives.
3343  #
3344  # Note that && is not included here.  This is because there are too
3345  # many false positives due to RValue references.
3346  match = Search(r'[^<>=!\s](==|!=|<=|>=|\|\|)[^<>=!\s,;\)]', line)
3347  if match:
3348    error(filename, linenum, 'whitespace/operators', 3,
3349          'Missing spaces around %s' % match.group(1))
3350  elif not Match(r'#.*include', line):
3351    # Look for < that is not surrounded by spaces.  This is only
3352    # triggered if both sides are missing spaces, even though
3353    # technically should should flag if at least one side is missing a
3354    # space.  This is done to avoid some false positives with shifts.
3355    match = Match(r'^(.*[^\s<])<[^\s=<,]', line)
3356    if match:
3357      (_, _, end_pos) = CloseExpression(
3358          clean_lines, linenum, len(match.group(1)))
3359      if end_pos <= -1:
3360        error(filename, linenum, 'whitespace/operators', 3,
3361              'Missing spaces around <')
3362
3363    # Look for > that is not surrounded by spaces.  Similar to the
3364    # above, we only trigger if both sides are missing spaces to avoid
3365    # false positives with shifts.
3366    match = Match(r'^(.*[^-\s>])>[^\s=>,]', line)
3367    if match:
3368      (_, _, start_pos) = ReverseCloseExpression(
3369          clean_lines, linenum, len(match.group(1)))
3370      if start_pos <= -1:
3371        error(filename, linenum, 'whitespace/operators', 3,
3372              'Missing spaces around >')
3373
3374  # We allow no-spaces around << when used like this: 10<<20, but
3375  # not otherwise (particularly, not when used as streams)
3376  #
3377  # We also allow operators following an opening parenthesis, since
3378  # those tend to be macros that deal with operators.
3379  match = Search(r'(operator|[^\s(<])(?:L|UL|LL|ULL|l|ul|ll|ull)?<<([^\s,=<])', line)
3380  if (match and not (match.group(1).isdigit() and match.group(2).isdigit()) and
3381      not (match.group(1) == 'operator' and match.group(2) == ';')):
3382    error(filename, linenum, 'whitespace/operators', 3,
3383          'Missing spaces around <<')
3384
3385  # We allow no-spaces around >> for almost anything.  This is because
3386  # C++11 allows ">>" to close nested templates, which accounts for
3387  # most cases when ">>" is not followed by a space.
3388  #
3389  # We still warn on ">>" followed by alpha character, because that is
3390  # likely due to ">>" being used for right shifts, e.g.:
3391  #   value >> alpha
3392  #
3393  # When ">>" is used to close templates, the alphanumeric letter that
3394  # follows would be part of an identifier, and there should still be
3395  # a space separating the template type and the identifier.
3396  #   type<type<type>> alpha
3397  match = Search(r'>>[a-zA-Z_]', line)
3398  if match:
3399    error(filename, linenum, 'whitespace/operators', 3,
3400          'Missing spaces around >>')
3401
3402  # There shouldn't be space around unary operators
3403  match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line)
3404  if match:
3405    error(filename, linenum, 'whitespace/operators', 4,
3406          'Extra space for operator %s' % match.group(1))
3407
3408
3409def CheckParenthesisSpacing(filename, clean_lines, linenum, error):
3410  """Checks for horizontal spacing around parentheses.
3411
3412  Args:
3413    filename: The name of the current file.
3414    clean_lines: A CleansedLines instance containing the file.
3415    linenum: The number of the line to check.
3416    error: The function to call with any errors found.
3417  """
3418  line = clean_lines.elided[linenum]
3419
3420  # No spaces after an if, while, switch, or for
3421  match = Search(r' (if\(|for\(|while\(|switch\()', line)
3422  if match:
3423    error(filename, linenum, 'whitespace/parens', 5,
3424          'Missing space before ( in %s' % match.group(1))
3425
3426  # For if/for/while/switch, the left and right parens should be
3427  # consistent about how many spaces are inside the parens, and
3428  # there should either be zero or one spaces inside the parens.
3429  # We don't want: "if ( foo)" or "if ( foo   )".
3430  # Exception: "for ( ; foo; bar)" and "for (foo; bar; )" are allowed.
3431  match = Search(r'\b(if|for|while|switch)\s*'
3432                 r'\(([ ]*)(.).*[^ ]+([ ]*)\)\s*{\s*$',
3433                 line)
3434  if match:
3435    if len(match.group(2)) != len(match.group(4)):
3436      if not (match.group(3) == ';' and
3437              len(match.group(2)) == 1 + len(match.group(4)) or
3438              not match.group(2) and Search(r'\bfor\s*\(.*; \)', line)):
3439        error(filename, linenum, 'whitespace/parens', 5,
3440              'Mismatching spaces inside () in %s' % match.group(1))
3441    if len(match.group(2)) not in [0, 1]:
3442      error(filename, linenum, 'whitespace/parens', 5,
3443            'Should have zero or one spaces inside ( and ) in %s' %
3444            match.group(1))
3445
3446
3447def CheckCommaSpacing(filename, clean_lines, linenum, error):
3448  """Checks for horizontal spacing near commas and semicolons.
3449
3450  Args:
3451    filename: The name of the current file.
3452    clean_lines: A CleansedLines instance containing the file.
3453    linenum: The number of the line to check.
3454    error: The function to call with any errors found.
3455  """
3456  raw = clean_lines.lines_without_raw_strings
3457  line = clean_lines.elided[linenum]
3458
3459  # You should always have a space after a comma (either as fn arg or operator)
3460  #
3461  # This does not apply when the non-space character following the
3462  # comma is another comma, since the only time when that happens is
3463  # for empty macro arguments.
3464  #
3465  # We run this check in two passes: first pass on elided lines to
3466  # verify that lines contain missing whitespaces, second pass on raw
3467  # lines to confirm that those missing whitespaces are not due to
3468  # elided comments.
3469  if (Search(r',[^,\s]', ReplaceAll(r'\boperator\s*,\s*\(', 'F(', line)) and
3470      Search(r',[^,\s]', raw[linenum])):
3471    error(filename, linenum, 'whitespace/comma', 3,
3472          'Missing space after ,')
3473
3474  # You should always have a space after a semicolon
3475  # except for few corner cases
3476  # TODO(unknown): clarify if 'if (1) { return 1;}' is requires one more
3477  # space after ;
3478  if Search(r';[^\s};\\)/]', line):
3479    error(filename, linenum, 'whitespace/semicolon', 3,
3480          'Missing space after ;')
3481
3482
3483def _IsType(clean_lines, nesting_state, expr):
3484  """Check if expression looks like a type name, returns true if so.
3485
3486  Args:
3487    clean_lines: A CleansedLines instance containing the file.
3488    nesting_state: A NestingState instance which maintains information about
3489                   the current stack of nested blocks being parsed.
3490    expr: The expression to check.
3491  Returns:
3492    True, if token looks like a type.
3493  """
3494  # Keep only the last token in the expression
3495  last_word = Match(r'^.*(\b\S+)$', expr)
3496  if last_word:
3497    token = last_word.group(1)
3498  else:
3499    token = expr
3500
3501  # Match native types and stdint types
3502  if _TYPES.match(token):
3503    return True
3504
3505  # Try a bit harder to match templated types.  Walk up the nesting
3506  # stack until we find something that resembles a typename
3507  # declaration for what we are looking for.
3508  typename_pattern = (r'\b(?:typename|class|struct)\s+' + re.escape(token) +
3509                      r'\b')
3510  block_index = len(nesting_state.stack) - 1
3511  while block_index >= 0:
3512    if isinstance(nesting_state.stack[block_index], _NamespaceInfo):
3513      return False
3514
3515    # Found where the opening brace is.  We want to scan from this
3516    # line up to the beginning of the function, minus a few lines.
3517    #   template <typename Type1,  // stop scanning here
3518    #             ...>
3519    #   class C
3520    #     : public ... {  // start scanning here
3521    last_line = nesting_state.stack[block_index].starting_linenum
3522
3523    next_block_start = 0
3524    if block_index > 0:
3525      next_block_start = nesting_state.stack[block_index - 1].starting_linenum
3526    first_line = last_line
3527    while first_line >= next_block_start:
3528      if clean_lines.elided[first_line].find('template') >= 0:
3529        break
3530      first_line -= 1
3531    if first_line < next_block_start:
3532      # Didn't find any "template" keyword before reaching the next block,
3533      # there are probably no template things to check for this block
3534      block_index -= 1
3535      continue
3536
3537    # Look for typename in the specified range
3538    for i in xrange(first_line, last_line + 1, 1):
3539      if Search(typename_pattern, clean_lines.elided[i]):
3540        return True
3541    block_index -= 1
3542
3543  return False
3544
3545
3546def CheckBracesSpacing(filename, clean_lines, linenum, nesting_state, error):
3547  """Checks for horizontal spacing near commas.
3548
3549  Args:
3550    filename: The name of the current file.
3551    clean_lines: A CleansedLines instance containing the file.
3552    linenum: The number of the line to check.
3553    nesting_state: A NestingState instance which maintains information about
3554                   the current stack of nested blocks being parsed.
3555    error: The function to call with any errors found.
3556  """
3557  line = clean_lines.elided[linenum]
3558
3559  # Except after an opening paren, or after another opening brace (in case of
3560  # an initializer list, for instance), you should have spaces before your
3561  # braces when they are delimiting blocks, classes, namespaces etc.
3562  # And since you should never have braces at the beginning of a line,
3563  # this is an easy test.  Except that braces used for initialization don't
3564  # follow the same rule; we often don't want spaces before those.
3565  match = Match(r'^(.*[^ ({>]){', line)
3566
3567  if match:
3568    # Try a bit harder to check for brace initialization.  This
3569    # happens in one of the following forms:
3570    #   Constructor() : initializer_list_{} { ... }
3571    #   Constructor{}.MemberFunction()
3572    #   Type variable{};
3573    #   FunctionCall(type{}, ...);
3574    #   LastArgument(..., type{});
3575    #   LOG(INFO) << type{} << " ...";
3576    #   map_of_type[{...}] = ...;
3577    #   ternary = expr ? new type{} : nullptr;
3578    #   OuterTemplate<InnerTemplateConstructor<Type>{}>
3579    #
3580    # We check for the character following the closing brace, and
3581    # silence the warning if it's one of those listed above, i.e.
3582    # "{.;,)<>]:".
3583    #
3584    # To account for nested initializer list, we allow any number of
3585    # closing braces up to "{;,)<".  We can't simply silence the
3586    # warning on first sight of closing brace, because that would
3587    # cause false negatives for things that are not initializer lists.
3588    #   Silence this:         But not this:
3589    #     Outer{                if (...) {
3590    #       Inner{...}            if (...){  // Missing space before {
3591    #     };                    }
3592    #
3593    # There is a false negative with this approach if people inserted
3594    # spurious semicolons, e.g. "if (cond){};", but we will catch the
3595    # spurious semicolon with a separate check.
3596    leading_text = match.group(1)
3597    (endline, endlinenum, endpos) = CloseExpression(
3598        clean_lines, linenum, len(match.group(1)))
3599    trailing_text = ''
3600    if endpos > -1:
3601      trailing_text = endline[endpos:]
3602    for offset in xrange(endlinenum + 1,
3603                         min(endlinenum + 3, clean_lines.NumLines() - 1)):
3604      trailing_text += clean_lines.elided[offset]
3605    # We also suppress warnings for `uint64_t{expression}` etc., as the style
3606    # guide recommends brace initialization for integral types to avoid
3607    # overflow/truncation.
3608    if (not Match(r'^[\s}]*[{.;,)<>\]:]', trailing_text)
3609        and not _IsType(clean_lines, nesting_state, leading_text)):
3610      error(filename, linenum, 'whitespace/braces', 5,
3611            'Missing space before {')
3612
3613  # Make sure '} else {' has spaces.
3614  if Search(r'}else', line):
3615    error(filename, linenum, 'whitespace/braces', 5,
3616          'Missing space before else')
3617
3618  # You shouldn't have a space before a semicolon at the end of the line.
3619  # There's a special case for "for" since the style guide allows space before
3620  # the semicolon there.
3621  if Search(r':\s*;\s*$', line):
3622    error(filename, linenum, 'whitespace/semicolon', 5,
3623          'Semicolon defining empty statement. Use {} instead.')
3624  elif Search(r'^\s*;\s*$', line):
3625    error(filename, linenum, 'whitespace/semicolon', 5,
3626          'Line contains only semicolon. If this should be an empty statement, '
3627          'use {} instead.')
3628  elif (Search(r'\s+;\s*$', line) and
3629        not Search(r'\bfor\b', line)):
3630    error(filename, linenum, 'whitespace/semicolon', 5,
3631          'Extra space before last semicolon. If this should be an empty '
3632          'statement, use {} instead.')
3633
3634
3635def IsDecltype(clean_lines, linenum, column):
3636  """Check if the token ending on (linenum, column) is decltype().
3637
3638  Args:
3639    clean_lines: A CleansedLines instance containing the file.
3640    linenum: the number of the line to check.
3641    column: end column of the token to check.
3642  Returns:
3643    True if this token is decltype() expression, False otherwise.
3644  """
3645  (text, _, start_col) = ReverseCloseExpression(clean_lines, linenum, column)
3646  if start_col < 0:
3647    return False
3648  if Search(r'\bdecltype\s*$', text[0:start_col]):
3649    return True
3650  return False
3651
3652
3653def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error):
3654  """Checks for additional blank line issues related to sections.
3655
3656  Currently the only thing checked here is blank line before protected/private.
3657
3658  Args:
3659    filename: The name of the current file.
3660    clean_lines: A CleansedLines instance containing the file.
3661    class_info: A _ClassInfo objects.
3662    linenum: The number of the line to check.
3663    error: The function to call with any errors found.
3664  """
3665  # Skip checks if the class is small, where small means 25 lines or less.
3666  # 25 lines seems like a good cutoff since that's the usual height of
3667  # terminals, and any class that can't fit in one screen can't really
3668  # be considered "small".
3669  #
3670  # Also skip checks if we are on the first line.  This accounts for
3671  # classes that look like
3672  #   class Foo { public: ... };
3673  #
3674  # If we didn't find the end of the class, last_line would be zero,
3675  # and the check will be skipped by the first condition.
3676  if (class_info.last_line - class_info.starting_linenum <= 24 or
3677      linenum <= class_info.starting_linenum):
3678    return
3679
3680  matched = Match(r'\s*(public|protected|private):', clean_lines.lines[linenum])
3681  if matched:
3682    # Issue warning if the line before public/protected/private was
3683    # not a blank line, but don't do this if the previous line contains
3684    # "class" or "struct".  This can happen two ways:
3685    #  - We are at the beginning of the class.
3686    #  - We are forward-declaring an inner class that is semantically
3687    #    private, but needed to be public for implementation reasons.
3688    # Also ignores cases where the previous line ends with a backslash as can be
3689    # common when defining classes in C macros.
3690    prev_line = clean_lines.lines[linenum - 1]
3691    if (not IsBlankLine(prev_line) and
3692        not Search(r'\b(class|struct)\b', prev_line) and
3693        not Search(r'\\$', prev_line)):
3694      # Try a bit harder to find the beginning of the class.  This is to
3695      # account for multi-line base-specifier lists, e.g.:
3696      #   class Derived
3697      #       : public Base {
3698      end_class_head = class_info.starting_linenum
3699      for i in range(class_info.starting_linenum, linenum):
3700        if Search(r'\{\s*$', clean_lines.lines[i]):
3701          end_class_head = i
3702          break
3703      if end_class_head < linenum - 1:
3704        error(filename, linenum, 'whitespace/blank_line', 3,
3705              '"%s:" should be preceded by a blank line' % matched.group(1))
3706
3707
3708def GetPreviousNonBlankLine(clean_lines, linenum):
3709  """Return the most recent non-blank line and its line number.
3710
3711  Args:
3712    clean_lines: A CleansedLines instance containing the file contents.
3713    linenum: The number of the line to check.
3714
3715  Returns:
3716    A tuple with two elements.  The first element is the contents of the last
3717    non-blank line before the current line, or the empty string if this is the
3718    first non-blank line.  The second is the line number of that line, or -1
3719    if this is the first non-blank line.
3720  """
3721
3722  prevlinenum = linenum - 1
3723  while prevlinenum >= 0:
3724    prevline = clean_lines.elided[prevlinenum]
3725    if not IsBlankLine(prevline):     # if not a blank line...
3726      return (prevline, prevlinenum)
3727    prevlinenum -= 1
3728  return ('', -1)
3729
3730
3731def CheckBraces(filename, clean_lines, linenum, error):
3732  """Looks for misplaced braces (e.g. at the end of line).
3733
3734  Args:
3735    filename: The name of the current file.
3736    clean_lines: A CleansedLines instance containing the file.
3737    linenum: The number of the line to check.
3738    error: The function to call with any errors found.
3739  """
3740
3741  line = clean_lines.elided[linenum]        # get rid of comments and strings
3742
3743  if Match(r'\s*{\s*$', line):
3744    # We allow an open brace to start a line in the case where someone is using
3745    # braces in a block to explicitly create a new scope, which is commonly used
3746    # to control the lifetime of stack-allocated variables.  Braces are also
3747    # used for brace initializers inside function calls.  We don't detect this
3748    # perfectly: we just don't complain if the last non-whitespace character on
3749    # the previous non-blank line is ',', ';', ':', '(', '{', or '}', or if the
3750    # previous line starts a preprocessor block. We also allow a brace on the
3751    # following line if it is part of an array initialization and would not fit
3752    # within the 80 character limit of the preceding line.
3753    prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
3754    if (not Search(r'[,;:}{(]\s*$', prevline) and
3755        not Match(r'\s*#', prevline) and
3756        not (GetLineWidth(prevline) > _line_length - 2 and '[]' in prevline)):
3757      error(filename, linenum, 'whitespace/braces', 4,
3758            '{ should almost always be at the end of the previous line')
3759
3760  # An else clause should be on the same line as the preceding closing brace.
3761  if Match(r'\s*else\b\s*(?:if\b|\{|$)', line):
3762    prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
3763    if Match(r'\s*}\s*$', prevline):
3764      error(filename, linenum, 'whitespace/newline', 4,
3765            'An else should appear on the same line as the preceding }')
3766
3767  # If braces come on one side of an else, they should be on both.
3768  # However, we have to worry about "else if" that spans multiple lines!
3769  if Search(r'else if\s*\(', line):       # could be multi-line if
3770    brace_on_left = bool(Search(r'}\s*else if\s*\(', line))
3771    # find the ( after the if
3772    pos = line.find('else if')
3773    pos = line.find('(', pos)
3774    if pos > 0:
3775      (endline, _, endpos) = CloseExpression(clean_lines, linenum, pos)
3776      brace_on_right = endline[endpos:].find('{') != -1
3777      if brace_on_left != brace_on_right:    # must be brace after if
3778        error(filename, linenum, 'readability/braces', 5,
3779              'If an else has a brace on one side, it should have it on both')
3780  elif Search(r'}\s*else[^{]*$', line) or Match(r'[^}]*else\s*{', line):
3781    error(filename, linenum, 'readability/braces', 5,
3782          'If an else has a brace on one side, it should have it on both')
3783
3784  # Likewise, an else should never have the else clause on the same line
3785  if Search(r'\belse [^\s{]', line) and not Search(r'\belse if\b', line):
3786    error(filename, linenum, 'whitespace/newline', 4,
3787          'Else clause should never be on same line as else (use 2 lines)')
3788
3789  # In the same way, a do/while should never be on one line
3790  if Match(r'\s*do [^\s{]', line):
3791    error(filename, linenum, 'whitespace/newline', 4,
3792          'do/while clauses should not be on a single line')
3793
3794  # Check single-line if/else bodies. The style guide says 'curly braces are not
3795  # required for single-line statements'. We additionally allow multi-line,
3796  # single statements, but we reject anything with more than one semicolon in
3797  # it. This means that the first semicolon after the if should be at the end of
3798  # its line, and the line after that should have an indent level equal to or
3799  # lower than the if. We also check for ambiguous if/else nesting without
3800  # braces.
3801  if_else_match = Search(r'\b(if\s*\(|else\b)', line)
3802  if if_else_match and not Match(r'\s*#', line):
3803    if_indent = GetIndentLevel(line)
3804    endline, endlinenum, endpos = line, linenum, if_else_match.end()
3805    if_match = Search(r'\bif\s*\(', line)
3806    if if_match:
3807      # This could be a multiline if condition, so find the end first.
3808      pos = if_match.end() - 1
3809      (endline, endlinenum, endpos) = CloseExpression(clean_lines, linenum, pos)
3810    # Check for an opening brace, either directly after the if or on the next
3811    # line. If found, this isn't a single-statement conditional.
3812    if (not Match(r'\s*{', endline[endpos:])
3813        and not (Match(r'\s*$', endline[endpos:])
3814                 and endlinenum < (len(clean_lines.elided) - 1)
3815                 and Match(r'\s*{', clean_lines.elided[endlinenum + 1]))):
3816      while (endlinenum < len(clean_lines.elided)
3817             and ';' not in clean_lines.elided[endlinenum][endpos:]):
3818        endlinenum += 1
3819        endpos = 0
3820      if endlinenum < len(clean_lines.elided):
3821        endline = clean_lines.elided[endlinenum]
3822        # We allow a mix of whitespace and closing braces (e.g. for one-liner
3823        # methods) and a single \ after the semicolon (for macros)
3824        endpos = endline.find(';')
3825        if not Match(r';[\s}]*(\\?)$', endline[endpos:]):
3826          # Semicolon isn't the last character, there's something trailing.
3827          # Output a warning if the semicolon is not contained inside
3828          # a lambda expression.
3829          if not Match(r'^[^{};]*\[[^\[\]]*\][^{}]*\{[^{}]*\}\s*\)*[;,]\s*$',
3830                       endline):
3831            error(filename, linenum, 'readability/braces', 4,
3832                  'If/else bodies with multiple statements require braces')
3833        elif endlinenum < len(clean_lines.elided) - 1:
3834          # Make sure the next line is dedented
3835          next_line = clean_lines.elided[endlinenum + 1]
3836          next_indent = GetIndentLevel(next_line)
3837          # With ambiguous nested if statements, this will error out on the
3838          # if that *doesn't* match the else, regardless of whether it's the
3839          # inner one or outer one.
3840          if (if_match and Match(r'\s*else\b', next_line)
3841              and next_indent != if_indent):
3842            error(filename, linenum, 'readability/braces', 4,
3843                  'Else clause should be indented at the same level as if. '
3844                  'Ambiguous nested if/else chains require braces.')
3845          elif next_indent > if_indent:
3846            error(filename, linenum, 'readability/braces', 4,
3847                  'If/else bodies with multiple statements require braces')
3848
3849
3850def CheckTrailingSemicolon(filename, clean_lines, linenum, error):
3851  """Looks for redundant trailing semicolon.
3852
3853  Args:
3854    filename: The name of the current file.
3855    clean_lines: A CleansedLines instance containing the file.
3856    linenum: The number of the line to check.
3857    error: The function to call with any errors found.
3858  """
3859
3860  line = clean_lines.elided[linenum]
3861
3862  # Block bodies should not be followed by a semicolon.  Due to C++11
3863  # brace initialization, there are more places where semicolons are
3864  # required than not, so we use a whitelist approach to check these
3865  # rather than a blacklist.  These are the places where "};" should
3866  # be replaced by just "}":
3867  # 1. Some flavor of block following closing parenthesis:
3868  #    for (;;) {};
3869  #    while (...) {};
3870  #    switch (...) {};
3871  #    Function(...) {};
3872  #    if (...) {};
3873  #    if (...) else if (...) {};
3874  #
3875  # 2. else block:
3876  #    if (...) else {};
3877  #
3878  # 3. const member function:
3879  #    Function(...) const {};
3880  #
3881  # 4. Block following some statement:
3882  #    x = 42;
3883  #    {};
3884  #
3885  # 5. Block at the beginning of a function:
3886  #    Function(...) {
3887  #      {};
3888  #    }
3889  #
3890  #    Note that naively checking for the preceding "{" will also match
3891  #    braces inside multi-dimensional arrays, but this is fine since
3892  #    that expression will not contain semicolons.
3893  #
3894  # 6. Block following another block:
3895  #    while (true) {}
3896  #    {};
3897  #
3898  # 7. End of namespaces:
3899  #    namespace {};
3900  #
3901  #    These semicolons seems far more common than other kinds of
3902  #    redundant semicolons, possibly due to people converting classes
3903  #    to namespaces.  For now we do not warn for this case.
3904  #
3905  # Try matching case 1 first.
3906  match = Match(r'^(.*\)\s*)\{', line)
3907  if match:
3908    # Matched closing parenthesis (case 1).  Check the token before the
3909    # matching opening parenthesis, and don't warn if it looks like a
3910    # macro.  This avoids these false positives:
3911    #  - macro that defines a base class
3912    #  - multi-line macro that defines a base class
3913    #  - macro that defines the whole class-head
3914    #
3915    # But we still issue warnings for macros that we know are safe to
3916    # warn, specifically:
3917    #  - TEST, TEST_F, TEST_P, MATCHER, MATCHER_P
3918    #  - TYPED_TEST
3919    #  - INTERFACE_DEF
3920    #  - EXCLUSIVE_LOCKS_REQUIRED, SHARED_LOCKS_REQUIRED, LOCKS_EXCLUDED:
3921    #
3922    # We implement a whitelist of safe macros instead of a blacklist of
3923    # unsafe macros, even though the latter appears less frequently in
3924    # google code and would have been easier to implement.  This is because
3925    # the downside for getting the whitelist wrong means some extra
3926    # semicolons, while the downside for getting the blacklist wrong
3927    # would result in compile errors.
3928    #
3929    # In addition to macros, we also don't want to warn on
3930    #  - Compound literals
3931    #  - Lambdas
3932    #  - alignas specifier with anonymous structs
3933    #  - decltype
3934    closing_brace_pos = match.group(1).rfind(')')
3935    opening_parenthesis = ReverseCloseExpression(
3936        clean_lines, linenum, closing_brace_pos)
3937    if opening_parenthesis[2] > -1:
3938      line_prefix = opening_parenthesis[0][0:opening_parenthesis[2]]
3939      macro = Search(r'\b([A-Z_][A-Z0-9_]*)\s*$', line_prefix)
3940      func = Match(r'^(.*\])\s*$', line_prefix)
3941      if ((macro and
3942           macro.group(1) not in (
3943               'TEST', 'TEST_F', 'MATCHER', 'MATCHER_P', 'TYPED_TEST',
3944               'EXCLUSIVE_LOCKS_REQUIRED', 'SHARED_LOCKS_REQUIRED',
3945               'LOCKS_EXCLUDED', 'INTERFACE_DEF')) or
3946          (func and not Search(r'\boperator\s*\[\s*\]', func.group(1))) or
3947          Search(r'\b(?:struct|union)\s+alignas\s*$', line_prefix) or
3948          Search(r'\bdecltype$', line_prefix) or
3949          Search(r'\s+=\s*$', line_prefix)):
3950        match = None
3951    if (match and
3952        opening_parenthesis[1] > 1 and
3953        Search(r'\]\s*$', clean_lines.elided[opening_parenthesis[1] - 1])):
3954      # Multi-line lambda-expression
3955      match = None
3956
3957  else:
3958    # Try matching cases 2-3.
3959    match = Match(r'^(.*(?:else|\)\s*const)\s*)\{', line)
3960    if not match:
3961      # Try matching cases 4-6.  These are always matched on separate lines.
3962      #
3963      # Note that we can't simply concatenate the previous line to the
3964      # current line and do a single match, otherwise we may output
3965      # duplicate warnings for the blank line case:
3966      #   if (cond) {
3967      #     // blank line
3968      #   }
3969      prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
3970      if prevline and Search(r'[;{}]\s*$', prevline):
3971        match = Match(r'^(\s*)\{', line)
3972
3973  # Check matching closing brace
3974  if match:
3975    (endline, endlinenum, endpos) = CloseExpression(
3976        clean_lines, linenum, len(match.group(1)))
3977    if endpos > -1 and Match(r'^\s*;', endline[endpos:]):
3978      # Current {} pair is eligible for semicolon check, and we have found
3979      # the redundant semicolon, output warning here.
3980      #
3981      # Note: because we are scanning forward for opening braces, and
3982      # outputting warnings for the matching closing brace, if there are
3983      # nested blocks with trailing semicolons, we will get the error
3984      # messages in reversed order.
3985
3986      # We need to check the line forward for NOLINT
3987      raw_lines = clean_lines.raw_lines
3988      ParseNolintSuppressions(filename, raw_lines[endlinenum-1], endlinenum-1,
3989                              error)
3990      ParseNolintSuppressions(filename, raw_lines[endlinenum], endlinenum,
3991                              error)
3992
3993      error(filename, endlinenum, 'readability/braces', 4,
3994            "You don't need a ; after a }")
3995
3996
3997def CheckEmptyBlockBody(filename, clean_lines, linenum, error):
3998  """Look for empty loop/conditional body with only a single semicolon.
3999
4000  Args:
4001    filename: The name of the current file.
4002    clean_lines: A CleansedLines instance containing the file.
4003    linenum: The number of the line to check.
4004    error: The function to call with any errors found.
4005  """
4006
4007  # Search for loop keywords at the beginning of the line.  Because only
4008  # whitespaces are allowed before the keywords, this will also ignore most
4009  # do-while-loops, since those lines should start with closing brace.
4010  #
4011  # We also check "if" blocks here, since an empty conditional block
4012  # is likely an error.
4013  line = clean_lines.elided[linenum]
4014  matched = Match(r'\s*(for|while|if)\s*\(', line)
4015  if matched:
4016    # Find the end of the conditional expression.
4017    (end_line, end_linenum, end_pos) = CloseExpression(
4018        clean_lines, linenum, line.find('('))
4019
4020    # Output warning if what follows the condition expression is a semicolon.
4021    # No warning for all other cases, including whitespace or newline, since we
4022    # have a separate check for semicolons preceded by whitespace.
4023    if end_pos >= 0 and Match(r';', end_line[end_pos:]):
4024      if matched.group(1) == 'if':
4025        error(filename, end_linenum, 'whitespace/empty_conditional_body', 5,
4026              'Empty conditional bodies should use {}')
4027      else:
4028        error(filename, end_linenum, 'whitespace/empty_loop_body', 5,
4029              'Empty loop bodies should use {} or continue')
4030
4031    # Check for if statements that have completely empty bodies (no comments)
4032    # and no else clauses.
4033    if end_pos >= 0 and matched.group(1) == 'if':
4034      # Find the position of the opening { for the if statement.
4035      # Return without logging an error if it has no brackets.
4036      opening_linenum = end_linenum
4037      opening_line_fragment = end_line[end_pos:]
4038      # Loop until EOF or find anything that's not whitespace or opening {.
4039      while not Search(r'^\s*\{', opening_line_fragment):
4040        if Search(r'^(?!\s*$)', opening_line_fragment):
4041          # Conditional has no brackets.
4042          return
4043        opening_linenum += 1
4044        if opening_linenum == len(clean_lines.elided):
4045          # Couldn't find conditional's opening { or any code before EOF.
4046          return
4047        opening_line_fragment = clean_lines.elided[opening_linenum]
4048      # Set opening_line (opening_line_fragment may not be entire opening line).
4049      opening_line = clean_lines.elided[opening_linenum]
4050
4051      # Find the position of the closing }.
4052      opening_pos = opening_line_fragment.find('{')
4053      if opening_linenum == end_linenum:
4054        # We need to make opening_pos relative to the start of the entire line.
4055        opening_pos += end_pos
4056      (closing_line, closing_linenum, closing_pos) = CloseExpression(
4057          clean_lines, opening_linenum, opening_pos)
4058      if closing_pos < 0:
4059        return
4060
4061      # Now construct the body of the conditional. This consists of the portion
4062      # of the opening line after the {, all lines until the closing line,
4063      # and the portion of the closing line before the }.
4064      if (clean_lines.raw_lines[opening_linenum] !=
4065          CleanseComments(clean_lines.raw_lines[opening_linenum])):
4066        # Opening line ends with a comment, so conditional isn't empty.
4067        return
4068      if closing_linenum > opening_linenum:
4069        # Opening line after the {. Ignore comments here since we checked above.
4070        body = list(opening_line[opening_pos+1:])
4071        # All lines until closing line, excluding closing line, with comments.
4072        body.extend(clean_lines.raw_lines[opening_linenum+1:closing_linenum])
4073        # Closing line before the }. Won't (and can't) have comments.
4074        body.append(clean_lines.elided[closing_linenum][:closing_pos-1])
4075        body = '\n'.join(body)
4076      else:
4077        # If statement has brackets and fits on a single line.
4078        body = opening_line[opening_pos+1:closing_pos-1]
4079
4080      # Check if the body is empty
4081      if not _EMPTY_CONDITIONAL_BODY_PATTERN.search(body):
4082        return
4083      # The body is empty. Now make sure there's not an else clause.
4084      current_linenum = closing_linenum
4085      current_line_fragment = closing_line[closing_pos:]
4086      # Loop until EOF or find anything that's not whitespace or else clause.
4087      while Search(r'^\s*$|^(?=\s*else)', current_line_fragment):
4088        if Search(r'^(?=\s*else)', current_line_fragment):
4089          # Found an else clause, so don't log an error.
4090          return
4091        current_linenum += 1
4092        if current_linenum == len(clean_lines.elided):
4093          break
4094        current_line_fragment = clean_lines.elided[current_linenum]
4095
4096      # The body is empty and there's no else clause until EOF or other code.
4097      error(filename, end_linenum, 'whitespace/empty_if_body', 4,
4098            ('If statement had no body and no else clause'))
4099
4100
4101def FindCheckMacro(line):
4102  """Find a replaceable CHECK-like macro.
4103
4104  Args:
4105    line: line to search on.
4106  Returns:
4107    (macro name, start position), or (None, -1) if no replaceable
4108    macro is found.
4109  """
4110  for macro in _CHECK_MACROS:
4111    i = line.find(macro)
4112    if i >= 0:
4113      # Find opening parenthesis.  Do a regular expression match here
4114      # to make sure that we are matching the expected CHECK macro, as
4115      # opposed to some other macro that happens to contain the CHECK
4116      # substring.
4117      matched = Match(r'^(.*\b' + macro + r'\s*)\(', line)
4118      if not matched:
4119        continue
4120      return (macro, len(matched.group(1)))
4121  return (None, -1)
4122
4123
4124def CheckCheck(filename, clean_lines, linenum, error):
4125  """Checks the use of CHECK and EXPECT macros.
4126
4127  Args:
4128    filename: The name of the current file.
4129    clean_lines: A CleansedLines instance containing the file.
4130    linenum: The number of the line to check.
4131    error: The function to call with any errors found.
4132  """
4133
4134  # Decide the set of replacement macros that should be suggested
4135  lines = clean_lines.elided
4136  (check_macro, start_pos) = FindCheckMacro(lines[linenum])
4137  if not check_macro:
4138    return
4139
4140  # Find end of the boolean expression by matching parentheses
4141  (last_line, end_line, end_pos) = CloseExpression(
4142      clean_lines, linenum, start_pos)
4143  if end_pos < 0:
4144    return
4145
4146  # If the check macro is followed by something other than a
4147  # semicolon, assume users will log their own custom error messages
4148  # and don't suggest any replacements.
4149  if not Match(r'\s*;', last_line[end_pos:]):
4150    return
4151
4152  if linenum == end_line:
4153    expression = lines[linenum][start_pos + 1:end_pos - 1]
4154  else:
4155    expression = lines[linenum][start_pos + 1:]
4156    for i in xrange(linenum + 1, end_line):
4157      expression += lines[i]
4158    expression += last_line[0:end_pos - 1]
4159
4160  # Parse expression so that we can take parentheses into account.
4161  # This avoids false positives for inputs like "CHECK((a < 4) == b)",
4162  # which is not replaceable by CHECK_LE.
4163  lhs = ''
4164  rhs = ''
4165  operator = None
4166  while expression:
4167    matched = Match(r'^\s*(<<|<<=|>>|>>=|->\*|->|&&|\|\||'
4168                    r'==|!=|>=|>|<=|<|\()(.*)$', expression)
4169    if matched:
4170      token = matched.group(1)
4171      if token == '(':
4172        # Parenthesized operand
4173        expression = matched.group(2)
4174        (end, _) = FindEndOfExpressionInLine(expression, 0, ['('])
4175        if end < 0:
4176          return  # Unmatched parenthesis
4177        lhs += '(' + expression[0:end]
4178        expression = expression[end:]
4179      elif token in ('&&', '||'):
4180        # Logical and/or operators.  This means the expression
4181        # contains more than one term, for example:
4182        #   CHECK(42 < a && a < b);
4183        #
4184        # These are not replaceable with CHECK_LE, so bail out early.
4185        return
4186      elif token in ('<<', '<<=', '>>', '>>=', '->*', '->'):
4187        # Non-relational operator
4188        lhs += token
4189        expression = matched.group(2)
4190      else:
4191        # Relational operator
4192        operator = token
4193        rhs = matched.group(2)
4194        break
4195    else:
4196      # Unparenthesized operand.  Instead of appending to lhs one character
4197      # at a time, we do another regular expression match to consume several
4198      # characters at once if possible.  Trivial benchmark shows that this
4199      # is more efficient when the operands are longer than a single
4200      # character, which is generally the case.
4201      matched = Match(r'^([^-=!<>()&|]+)(.*)$', expression)
4202      if not matched:
4203        matched = Match(r'^(\s*\S)(.*)$', expression)
4204        if not matched:
4205          break
4206      lhs += matched.group(1)
4207      expression = matched.group(2)
4208
4209  # Only apply checks if we got all parts of the boolean expression
4210  if not (lhs and operator and rhs):
4211    return
4212
4213  # Check that rhs do not contain logical operators.  We already know
4214  # that lhs is fine since the loop above parses out && and ||.
4215  if rhs.find('&&') > -1 or rhs.find('||') > -1:
4216    return
4217
4218  # At least one of the operands must be a constant literal.  This is
4219  # to avoid suggesting replacements for unprintable things like
4220  # CHECK(variable != iterator)
4221  #
4222  # The following pattern matches decimal, hex integers, strings, and
4223  # characters (in that order).
4224  lhs = lhs.strip()
4225  rhs = rhs.strip()
4226  match_constant = r'^([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')$'
4227  if Match(match_constant, lhs) or Match(match_constant, rhs):
4228    # Note: since we know both lhs and rhs, we can provide a more
4229    # descriptive error message like:
4230    #   Consider using CHECK_EQ(x, 42) instead of CHECK(x == 42)
4231    # Instead of:
4232    #   Consider using CHECK_EQ instead of CHECK(a == b)
4233    #
4234    # We are still keeping the less descriptive message because if lhs
4235    # or rhs gets long, the error message might become unreadable.
4236    error(filename, linenum, 'readability/check', 2,
4237          'Consider using %s instead of %s(a %s b)' % (
4238              _CHECK_REPLACEMENT[check_macro][operator],
4239              check_macro, operator))
4240
4241
4242def CheckAltTokens(filename, clean_lines, linenum, error):
4243  """Check alternative keywords being used in boolean expressions.
4244
4245  Args:
4246    filename: The name of the current file.
4247    clean_lines: A CleansedLines instance containing the file.
4248    linenum: The number of the line to check.
4249    error: The function to call with any errors found.
4250  """
4251  line = clean_lines.elided[linenum]
4252
4253  # Avoid preprocessor lines
4254  if Match(r'^\s*#', line):
4255    return
4256
4257  # Last ditch effort to avoid multi-line comments.  This will not help
4258  # if the comment started before the current line or ended after the
4259  # current line, but it catches most of the false positives.  At least,
4260  # it provides a way to workaround this warning for people who use
4261  # multi-line comments in preprocessor macros.
4262  #
4263  # TODO(unknown): remove this once cpplint has better support for
4264  # multi-line comments.
4265  if line.find('/*') >= 0 or line.find('*/') >= 0:
4266    return
4267
4268  for match in _ALT_TOKEN_REPLACEMENT_PATTERN.finditer(line):
4269    error(filename, linenum, 'readability/alt_tokens', 2,
4270          'Use operator %s instead of %s' % (
4271              _ALT_TOKEN_REPLACEMENT[match.group(1)], match.group(1)))
4272
4273
4274def GetLineWidth(line):
4275  """Determines the width of the line in column positions.
4276
4277  Args:
4278    line: A string, which may be a Unicode string.
4279
4280  Returns:
4281    The width of the line in column positions, accounting for Unicode
4282    combining characters and wide characters.
4283  """
4284  if isinstance(line, unicode):
4285    width = 0
4286    for uc in unicodedata.normalize('NFC', line):
4287      if unicodedata.east_asian_width(uc) in ('W', 'F'):
4288        width += 2
4289      elif not unicodedata.combining(uc):
4290        width += 1
4291    return width
4292  else:
4293    return len(line)
4294
4295
4296def CheckStyle(filename, clean_lines, linenum, file_extension, nesting_state,
4297               error):
4298  """Checks rules from the 'C++ style rules' section of cppguide.html.
4299
4300  Most of these rules are hard to test (naming, comment style), but we
4301  do what we can.  In particular we check for 2-space indents, line lengths,
4302  tab usage, spaces inside code, etc.
4303
4304  Args:
4305    filename: The name of the current file.
4306    clean_lines: A CleansedLines instance containing the file.
4307    linenum: The number of the line to check.
4308    file_extension: The extension (without the dot) of the filename.
4309    nesting_state: A NestingState instance which maintains information about
4310                   the current stack of nested blocks being parsed.
4311    error: The function to call with any errors found.
4312  """
4313
4314  # Don't use "elided" lines here, otherwise we can't check commented lines.
4315  # Don't want to use "raw" either, because we don't want to check inside C++11
4316  # raw strings,
4317  raw_lines = clean_lines.lines_without_raw_strings
4318  line = raw_lines[linenum]
4319  prev = raw_lines[linenum - 1] if linenum > 0 else ''
4320
4321  if line.find('\t') != -1:
4322    error(filename, linenum, 'whitespace/tab', 1,
4323          'Tab found; better to use spaces')
4324
4325  # One or three blank spaces at the beginning of the line is weird; it's
4326  # hard to reconcile that with 2-space indents.
4327  # NOTE: here are the conditions rob pike used for his tests.  Mine aren't
4328  # as sophisticated, but it may be worth becoming so:  RLENGTH==initial_spaces
4329  # if(RLENGTH > 20) complain = 0;
4330  # if(match($0, " +(error|private|public|protected):")) complain = 0;
4331  # if(match(prev, "&& *$")) complain = 0;
4332  # if(match(prev, "\\|\\| *$")) complain = 0;
4333  # if(match(prev, "[\",=><] *$")) complain = 0;
4334  # if(match($0, " <<")) complain = 0;
4335  # if(match(prev, " +for \\(")) complain = 0;
4336  # if(prevodd && match(prevprev, " +for \\(")) complain = 0;
4337  scope_or_label_pattern = r'\s*\w+\s*:\s*\\?$'
4338  classinfo = nesting_state.InnermostClass()
4339  initial_spaces = 0
4340  cleansed_line = clean_lines.elided[linenum]
4341  while initial_spaces < len(line) and line[initial_spaces] == ' ':
4342    initial_spaces += 1
4343  # There are certain situations we allow one space, notably for
4344  # section labels, and also lines containing multi-line raw strings.
4345  # We also don't check for lines that look like continuation lines
4346  # (of lines ending in double quotes, commas, equals, or angle brackets)
4347  # because the rules for how to indent those are non-trivial.
4348  if (not Search(r'[",=><] *$', prev) and
4349      (initial_spaces == 1 or initial_spaces == 3) and
4350      not Match(scope_or_label_pattern, cleansed_line) and
4351      not (clean_lines.raw_lines[linenum] != line and
4352           Match(r'^\s*""', line))):
4353    error(filename, linenum, 'whitespace/indent', 3,
4354          'Weird number of spaces at line-start.  '
4355          'Are you using a 2-space indent?')
4356
4357  if line and line[-1].isspace():
4358    error(filename, linenum, 'whitespace/end_of_line', 4,
4359          'Line ends in whitespace.  Consider deleting these extra spaces.')
4360
4361  # Check if the line is a header guard.
4362  is_header_guard = False
4363  if IsHeaderExtension(file_extension):
4364    cppvar = GetHeaderGuardCPPVariable(filename)
4365    if (line.startswith('#ifndef %s' % cppvar) or
4366        line.startswith('#define %s' % cppvar) or
4367        line.startswith('#endif  // %s' % cppvar)):
4368      is_header_guard = True
4369  # #include lines and header guards can be long, since there's no clean way to
4370  # split them.
4371  #
4372  # URLs can be long too.  It's possible to split these, but it makes them
4373  # harder to cut&paste.
4374  #
4375  # The "$Id:...$" comment may also get very long without it being the
4376  # developers fault.
4377  if (not line.startswith('#include') and not is_header_guard and
4378      not Match(r'^\s*//.*http(s?)://\S*$', line) and
4379      not Match(r'^\s*//\s*[^\s]*$', line) and
4380      not Match(r'^// \$Id:.*#[0-9]+ \$$', line)):
4381    line_width = GetLineWidth(line)
4382    if line_width > _line_length:
4383      error(filename, linenum, 'whitespace/line_length', 2,
4384            'Lines should be <= %i characters long' % _line_length)
4385
4386  if (cleansed_line.count(';') > 1 and
4387      # for loops are allowed two ;'s (and may run over two lines).
4388      cleansed_line.find('for') == -1 and
4389      (GetPreviousNonBlankLine(clean_lines, linenum)[0].find('for') == -1 or
4390       GetPreviousNonBlankLine(clean_lines, linenum)[0].find(';') != -1) and
4391      # It's ok to have many commands in a switch case that fits in 1 line
4392      not ((cleansed_line.find('case ') != -1 or
4393            cleansed_line.find('default:') != -1) and
4394           cleansed_line.find('break;') != -1)):
4395    error(filename, linenum, 'whitespace/newline', 0,
4396          'More than one command on the same line')
4397
4398  # Some more style checks
4399  CheckBraces(filename, clean_lines, linenum, error)
4400  CheckTrailingSemicolon(filename, clean_lines, linenum, error)
4401  CheckEmptyBlockBody(filename, clean_lines, linenum, error)
4402  CheckSpacing(filename, clean_lines, linenum, nesting_state, error)
4403  CheckOperatorSpacing(filename, clean_lines, linenum, error)
4404  CheckParenthesisSpacing(filename, clean_lines, linenum, error)
4405  CheckCommaSpacing(filename, clean_lines, linenum, error)
4406  CheckBracesSpacing(filename, clean_lines, linenum, nesting_state, error)
4407  CheckSpacingForFunctionCall(filename, clean_lines, linenum, error)
4408  CheckCheck(filename, clean_lines, linenum, error)
4409  CheckAltTokens(filename, clean_lines, linenum, error)
4410  classinfo = nesting_state.InnermostClass()
4411  if classinfo:
4412    CheckSectionSpacing(filename, clean_lines, classinfo, linenum, error)
4413
4414
4415_RE_PATTERN_INCLUDE = re.compile(r'^\s*#\s*include\s*([<"])([^>"]*)[>"].*$')
4416# Matches the first component of a filename delimited by -s and _s. That is:
4417#  _RE_FIRST_COMPONENT.match('foo').group(0) == 'foo'
4418#  _RE_FIRST_COMPONENT.match('foo.cc').group(0) == 'foo'
4419#  _RE_FIRST_COMPONENT.match('foo-bar_baz.cc').group(0) == 'foo'
4420#  _RE_FIRST_COMPONENT.match('foo_bar-baz.cc').group(0) == 'foo'
4421_RE_FIRST_COMPONENT = re.compile(r'^[^-_.]+')
4422
4423
4424def _DropCommonSuffixes(filename):
4425  """Drops common suffixes like _test.cc or -inl.h from filename.
4426
4427  For example:
4428    >>> _DropCommonSuffixes('foo/foo-inl.h')
4429    'foo/foo'
4430    >>> _DropCommonSuffixes('foo/bar/foo.cc')
4431    'foo/bar/foo'
4432    >>> _DropCommonSuffixes('foo/foo_internal.h')
4433    'foo/foo'
4434    >>> _DropCommonSuffixes('foo/foo_unusualinternal.h')
4435    'foo/foo_unusualinternal'
4436
4437  Args:
4438    filename: The input filename.
4439
4440  Returns:
4441    The filename with the common suffix removed.
4442  """
4443  for suffix in ('test.cc', 'regtest.cc', 'unittest.cc',
4444                 'inl.h', 'impl.h', 'internal.h'):
4445    if (filename.endswith(suffix) and len(filename) > len(suffix) and
4446        filename[-len(suffix) - 1] in ('-', '_')):
4447      return filename[:-len(suffix) - 1]
4448  return os.path.splitext(filename)[0]
4449
4450
4451def _ClassifyInclude(fileinfo, include, is_system):
4452  """Figures out what kind of header 'include' is.
4453
4454  Args:
4455    fileinfo: The current file cpplint is running over. A FileInfo instance.
4456    include: The path to a #included file.
4457    is_system: True if the #include used <> rather than "".
4458
4459  Returns:
4460    One of the _XXX_HEADER constants.
4461
4462  For example:
4463    >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'stdio.h', True)
4464    _C_SYS_HEADER
4465    >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'string', True)
4466    _CPP_SYS_HEADER
4467    >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', False)
4468    _LIKELY_MY_HEADER
4469    >>> _ClassifyInclude(FileInfo('foo/foo_unknown_extension.cc'),
4470    ...                  'bar/foo_other_ext.h', False)
4471    _POSSIBLE_MY_HEADER
4472    >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/bar.h', False)
4473    _OTHER_HEADER
4474  """
4475  # This is a list of all standard c++ header files, except
4476  # those already checked for above.
4477  is_cpp_h = include in _CPP_HEADERS
4478
4479  if is_system:
4480    if is_cpp_h:
4481      return _CPP_SYS_HEADER
4482    else:
4483      return _C_SYS_HEADER
4484
4485  # If the target file and the include we're checking share a
4486  # basename when we drop common extensions, and the include
4487  # lives in . , then it's likely to be owned by the target file.
4488  target_dir, target_base = (
4489      os.path.split(_DropCommonSuffixes(fileinfo.RepositoryName())))
4490  include_dir, include_base = os.path.split(_DropCommonSuffixes(include))
4491  if target_base == include_base and (
4492      include_dir == target_dir or
4493      include_dir == os.path.normpath(target_dir + '/../public')):
4494    return _LIKELY_MY_HEADER
4495
4496  # If the target and include share some initial basename
4497  # component, it's possible the target is implementing the
4498  # include, so it's allowed to be first, but we'll never
4499  # complain if it's not there.
4500  target_first_component = _RE_FIRST_COMPONENT.match(target_base)
4501  include_first_component = _RE_FIRST_COMPONENT.match(include_base)
4502  if (target_first_component and include_first_component and
4503      target_first_component.group(0) ==
4504      include_first_component.group(0)):
4505    return _POSSIBLE_MY_HEADER
4506
4507  return _OTHER_HEADER
4508
4509
4510
4511def CheckIncludeLine(filename, clean_lines, linenum, include_state, error):
4512  """Check rules that are applicable to #include lines.
4513
4514  Strings on #include lines are NOT removed from elided line, to make
4515  certain tasks easier. However, to prevent false positives, checks
4516  applicable to #include lines in CheckLanguage must be put here.
4517
4518  Args:
4519    filename: The name of the current file.
4520    clean_lines: A CleansedLines instance containing the file.
4521    linenum: The number of the line to check.
4522    include_state: An _IncludeState instance in which the headers are inserted.
4523    error: The function to call with any errors found.
4524  """
4525  fileinfo = FileInfo(filename)
4526  line = clean_lines.lines[linenum]
4527
4528  # "include" should use the new style "foo/bar.h" instead of just "bar.h"
4529  # Only do this check if the included header follows google naming
4530  # conventions.  If not, assume that it's a 3rd party API that
4531  # requires special include conventions.
4532  #
4533  # We also make an exception for Lua headers, which follow google
4534  # naming convention but not the include convention.
4535  match = Match(r'#include\s*"([^/]+\.h)"', line)
4536  if match and not _THIRD_PARTY_HEADERS_PATTERN.match(match.group(1)):
4537    error(filename, linenum, 'build/include', 4,
4538          'Include the directory when naming .h files')
4539
4540  # we shouldn't include a file more than once. actually, there are a
4541  # handful of instances where doing so is okay, but in general it's
4542  # not.
4543  match = _RE_PATTERN_INCLUDE.search(line)
4544  if match:
4545    include = match.group(2)
4546    is_system = (match.group(1) == '<')
4547    duplicate_line = include_state.FindHeader(include)
4548    if duplicate_line >= 0:
4549      error(filename, linenum, 'build/include', 4,
4550            '"%s" already included at %s:%s' %
4551            (include, filename, duplicate_line))
4552    elif (include.endswith('.cc') and
4553          os.path.dirname(fileinfo.RepositoryName()) != os.path.dirname(include)):
4554      error(filename, linenum, 'build/include', 4,
4555            'Do not include .cc files from other packages')
4556    elif not _THIRD_PARTY_HEADERS_PATTERN.match(include):
4557      include_state.include_list[-1].append((include, linenum))
4558
4559      # We want to ensure that headers appear in the right order:
4560      # 1) for foo.cc, foo.h  (preferred location)
4561      # 2) c system files
4562      # 3) cpp system files
4563      # 4) for foo.cc, foo.h  (deprecated location)
4564      # 5) other google headers
4565      #
4566      # We classify each include statement as one of those 5 types
4567      # using a number of techniques. The include_state object keeps
4568      # track of the highest type seen, and complains if we see a
4569      # lower type after that.
4570      error_message = include_state.CheckNextIncludeOrder(
4571          _ClassifyInclude(fileinfo, include, is_system))
4572      if error_message:
4573        error(filename, linenum, 'build/include_order', 4,
4574              '%s. Should be: %s.h, c system, c++ system, other.' %
4575              (error_message, fileinfo.BaseName()))
4576      canonical_include = include_state.CanonicalizeAlphabeticalOrder(include)
4577      if not include_state.IsInAlphabeticalOrder(
4578          clean_lines, linenum, canonical_include):
4579        error(filename, linenum, 'build/include_alpha', 4,
4580              'Include "%s" not in alphabetical order' % include)
4581      include_state.SetLastHeader(canonical_include)
4582
4583
4584
4585def _GetTextInside(text, start_pattern):
4586  r"""Retrieves all the text between matching open and close parentheses.
4587
4588  Given a string of lines and a regular expression string, retrieve all the text
4589  following the expression and between opening punctuation symbols like
4590  (, [, or {, and the matching close-punctuation symbol. This properly nested
4591  occurrences of the punctuations, so for the text like
4592    printf(a(), b(c()));
4593  a call to _GetTextInside(text, r'printf\(') will return 'a(), b(c())'.
4594  start_pattern must match string having an open punctuation symbol at the end.
4595
4596  Args:
4597    text: The lines to extract text. Its comments and strings must be elided.
4598           It can be single line and can span multiple lines.
4599    start_pattern: The regexp string indicating where to start extracting
4600                   the text.
4601  Returns:
4602    The extracted text.
4603    None if either the opening string or ending punctuation could not be found.
4604  """
4605  # TODO(unknown): Audit cpplint.py to see what places could be profitably
4606  # rewritten to use _GetTextInside (and use inferior regexp matching today).
4607
4608  # Give opening punctuations to get the matching close-punctuations.
4609  matching_punctuation = {'(': ')', '{': '}', '[': ']'}
4610  closing_punctuation = set(matching_punctuation.itervalues())
4611
4612  # Find the position to start extracting text.
4613  match = re.search(start_pattern, text, re.M)
4614  if not match:  # start_pattern not found in text.
4615    return None
4616  start_position = match.end(0)
4617
4618  assert start_position > 0, (
4619      'start_pattern must ends with an opening punctuation.')
4620  assert text[start_position - 1] in matching_punctuation, (
4621      'start_pattern must ends with an opening punctuation.')
4622  # Stack of closing punctuations we expect to have in text after position.
4623  punctuation_stack = [matching_punctuation[text[start_position - 1]]]
4624  position = start_position
4625  while punctuation_stack and position < len(text):
4626    if text[position] == punctuation_stack[-1]:
4627      punctuation_stack.pop()
4628    elif text[position] in closing_punctuation:
4629      # A closing punctuation without matching opening punctuations.
4630      return None
4631    elif text[position] in matching_punctuation:
4632      punctuation_stack.append(matching_punctuation[text[position]])
4633    position += 1
4634  if punctuation_stack:
4635    # Opening punctuations left without matching close-punctuations.
4636    return None
4637  # punctuations match.
4638  return text[start_position:position - 1]
4639
4640
4641# Patterns for matching call-by-reference parameters.
4642#
4643# Supports nested templates up to 2 levels deep using this messy pattern:
4644#   < (?: < (?: < [^<>]*
4645#               >
4646#           |   [^<>] )*
4647#         >
4648#     |   [^<>] )*
4649#   >
4650_RE_PATTERN_IDENT = r'[_a-zA-Z]\w*'  # =~ [[:alpha:]][[:alnum:]]*
4651_RE_PATTERN_TYPE = (
4652    r'(?:const\s+)?(?:typename\s+|class\s+|struct\s+|union\s+|enum\s+)?'
4653    r'(?:\w|'
4654    r'\s*<(?:<(?:<[^<>]*>|[^<>])*>|[^<>])*>|'
4655    r'::)+')
4656# A call-by-reference parameter ends with '& identifier'.
4657_RE_PATTERN_REF_PARAM = re.compile(
4658    r'(' + _RE_PATTERN_TYPE + r'(?:\s*(?:\bconst\b|[*]))*\s*'
4659    r'&\s*' + _RE_PATTERN_IDENT + r')\s*(?:=[^,()]+)?[,)]')
4660# A call-by-const-reference parameter either ends with 'const& identifier'
4661# or looks like 'const type& identifier' when 'type' is atomic.
4662_RE_PATTERN_CONST_REF_PARAM = (
4663    r'(?:.*\s*\bconst\s*&\s*' + _RE_PATTERN_IDENT +
4664    r'|const\s+' + _RE_PATTERN_TYPE + r'\s*&\s*' + _RE_PATTERN_IDENT + r')')
4665# Stream types.
4666_RE_PATTERN_REF_STREAM_PARAM = (
4667    r'(?:.*stream\s*&\s*' + _RE_PATTERN_IDENT + r')')
4668
4669
4670def CheckLanguage(filename, clean_lines, linenum, file_extension,
4671                  include_state, nesting_state, error):
4672  """Checks rules from the 'C++ language rules' section of cppguide.html.
4673
4674  Some of these rules are hard to test (function overloading, using
4675  uint32 inappropriately), but we do the best we can.
4676
4677  Args:
4678    filename: The name of the current file.
4679    clean_lines: A CleansedLines instance containing the file.
4680    linenum: The number of the line to check.
4681    file_extension: The extension (without the dot) of the filename.
4682    include_state: An _IncludeState instance in which the headers are inserted.
4683    nesting_state: A NestingState instance which maintains information about
4684                   the current stack of nested blocks being parsed.
4685    error: The function to call with any errors found.
4686  """
4687  # If the line is empty or consists of entirely a comment, no need to
4688  # check it.
4689  line = clean_lines.elided[linenum]
4690  if not line:
4691    return
4692
4693  match = _RE_PATTERN_INCLUDE.search(line)
4694  if match:
4695    CheckIncludeLine(filename, clean_lines, linenum, include_state, error)
4696    return
4697
4698  # Reset include state across preprocessor directives.  This is meant
4699  # to silence warnings for conditional includes.
4700  match = Match(r'^\s*#\s*(if|ifdef|ifndef|elif|else|endif)\b', line)
4701  if match:
4702    include_state.ResetSection(match.group(1))
4703
4704  # Make Windows paths like Unix.
4705  fullname = os.path.abspath(filename).replace('\\', '/')
4706
4707  # Perform other checks now that we are sure that this is not an include line
4708  CheckCasts(filename, clean_lines, linenum, error)
4709  CheckGlobalStatic(filename, clean_lines, linenum, error)
4710  CheckPrintf(filename, clean_lines, linenum, error)
4711
4712  if IsHeaderExtension(file_extension):
4713    # TODO(unknown): check that 1-arg constructors are explicit.
4714    #                How to tell it's a constructor?
4715    #                (handled in CheckForNonStandardConstructs for now)
4716    # TODO(unknown): check that classes declare or disable copy/assign
4717    #                (level 1 error)
4718    pass
4719
4720  # Check if people are using the verboten C basic types.  The only exception
4721  # we regularly allow is "unsigned short port" for port.
4722  if Search(r'\bshort port\b', line):
4723    if not Search(r'\bunsigned short port\b', line):
4724      error(filename, linenum, 'runtime/int', 4,
4725            'Use "unsigned short" for ports, not "short"')
4726  else:
4727    match = Search(r'\b(short|long(?! +double)|long long)\b', line)
4728    if match:
4729      error(filename, linenum, 'runtime/int', 4,
4730            'Use int16/int64/etc, rather than the C type %s' % match.group(1))
4731
4732  # Check if some verboten operator overloading is going on
4733  # TODO(unknown): catch out-of-line unary operator&:
4734  #   class X {};
4735  #   int operator&(const X& x) { return 42; }  // unary operator&
4736  # The trick is it's hard to tell apart from binary operator&:
4737  #   class Y { int operator&(const Y& x) { return 23; } }; // binary operator&
4738  if Search(r'\boperator\s*&\s*\(\s*\)', line):
4739    error(filename, linenum, 'runtime/operator', 4,
4740          'Unary operator& is dangerous.  Do not use it.')
4741
4742  # Check for suspicious usage of "if" like
4743  # } if (a == b) {
4744  if Search(r'\}\s*if\s*\(', line):
4745    error(filename, linenum, 'readability/braces', 4,
4746          'Did you mean "else if"? If not, start a new line for "if".')
4747
4748  # Check for potential format string bugs like printf(foo).
4749  # We constrain the pattern not to pick things like DocidForPrintf(foo).
4750  # Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str())
4751  # TODO(unknown): Catch the following case. Need to change the calling
4752  # convention of the whole function to process multiple line to handle it.
4753  #   printf(
4754  #       boy_this_is_a_really_long_variable_that_cannot_fit_on_the_prev_line);
4755  printf_args = _GetTextInside(line, r'(?i)\b(string)?printf\s*\(')
4756  if printf_args:
4757    match = Match(r'([\w.\->()]+)$', printf_args)
4758    if match and match.group(1) != '__VA_ARGS__':
4759      function_name = re.search(r'\b((?:string)?printf)\s*\(',
4760                                line, re.I).group(1)
4761      error(filename, linenum, 'runtime/printf', 4,
4762            'Potential format string bug. Do %s("%%s", %s) instead.'
4763            % (function_name, match.group(1)))
4764
4765  # Check for potential memset bugs like memset(buf, sizeof(buf), 0).
4766  match = Search(r'memset\s*\(([^,]*),\s*([^,]*),\s*0\s*\)', line)
4767  if match and not Match(r"^''|-?[0-9]+|0x[0-9A-Fa-f]$", match.group(2)):
4768    error(filename, linenum, 'runtime/memset', 4,
4769          'Did you mean "memset(%s, 0, %s)"?'
4770          % (match.group(1), match.group(2)))
4771
4772  if Search(r'\busing namespace\b', line):
4773    error(filename, linenum, 'build/namespaces', 5,
4774          'Do not use namespace using-directives.  '
4775          'Use using-declarations instead.')
4776
4777  # Detect variable-length arrays.
4778  match = Match(r'\s*(.+::)?(\w+) [a-z]\w*\[(.+)];', line)
4779  if (match and match.group(2) != 'return' and match.group(2) != 'delete' and
4780      match.group(3).find(']') == -1):
4781    # Split the size using space and arithmetic operators as delimiters.
4782    # If any of the resulting tokens are not compile time constants then
4783    # report the error.
4784    tokens = re.split(r'\s|\+|\-|\*|\/|<<|>>]', match.group(3))
4785    is_const = True
4786    skip_next = False
4787    for tok in tokens:
4788      if skip_next:
4789        skip_next = False
4790        continue
4791
4792      if Search(r'sizeof\(.+\)', tok): continue
4793      if Search(r'arraysize\(\w+\)', tok): continue
4794
4795      tok = tok.lstrip('(')
4796      tok = tok.rstrip(')')
4797      if not tok: continue
4798      if Match(r'\d+', tok): continue
4799      if Match(r'0[xX][0-9a-fA-F]+', tok): continue
4800      if Match(r'k[A-Z0-9]\w*', tok): continue
4801      if Match(r'(.+::)?k[A-Z0-9]\w*', tok): continue
4802      if Match(r'(.+::)?[A-Z][A-Z0-9_]*', tok): continue
4803      # A catch all for tricky sizeof cases, including 'sizeof expression',
4804      # 'sizeof(*type)', 'sizeof(const type)', 'sizeof(struct StructName)'
4805      # requires skipping the next token because we split on ' ' and '*'.
4806      if tok.startswith('sizeof'):
4807        skip_next = True
4808        continue
4809      is_const = False
4810      break
4811    if not is_const:
4812      error(filename, linenum, 'runtime/arrays', 1,
4813            'Do not use variable-length arrays.  Use an appropriately named '
4814            "('k' followed by CamelCase) compile-time constant for the size.")
4815
4816  # Check for use of unnamed namespaces in header files.  Registration
4817  # macros are typically OK, so we allow use of "namespace {" on lines
4818  # that end with backslashes.
4819  if (IsHeaderExtension(file_extension)
4820      and Search(r'\bnamespace\s*{', line)
4821      and line[-1] != '\\'):
4822    error(filename, linenum, 'build/namespaces', 4,
4823          'Do not use unnamed namespaces in header files.  See '
4824          'https://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces'
4825          ' for more information.')
4826
4827
4828def CheckGlobalStatic(filename, clean_lines, linenum, error):
4829  """Check for unsafe global or static objects.
4830
4831  Args:
4832    filename: The name of the current file.
4833    clean_lines: A CleansedLines instance containing the file.
4834    linenum: The number of the line to check.
4835    error: The function to call with any errors found.
4836  """
4837  line = clean_lines.elided[linenum]
4838
4839  # Match two lines at a time to support multiline declarations
4840  if linenum + 1 < clean_lines.NumLines() and not Search(r'[;({]', line):
4841    line += clean_lines.elided[linenum + 1].strip()
4842
4843  # Check for people declaring static/global STL strings at the top level.
4844  # This is dangerous because the C++ language does not guarantee that
4845  # globals with constructors are initialized before the first access, and
4846  # also because globals can be destroyed when some threads are still running.
4847  # TODO(unknown): Generalize this to also find static unique_ptr instances.
4848  # TODO(unknown): File bugs for clang-tidy to find these.
4849  match = Match(
4850      r'((?:|static +)(?:|const +))(?::*std::)?string( +const)? +'
4851      r'([a-zA-Z0-9_:]+)\b(.*)',
4852      line)
4853
4854  # Remove false positives:
4855  # - String pointers (as opposed to values).
4856  #    string *pointer
4857  #    const string *pointer
4858  #    string const *pointer
4859  #    string *const pointer
4860  #
4861  # - Functions and template specializations.
4862  #    string Function<Type>(...
4863  #    string Class<Type>::Method(...
4864  #
4865  # - Operators.  These are matched separately because operator names
4866  #   cross non-word boundaries, and trying to match both operators
4867  #   and functions at the same time would decrease accuracy of
4868  #   matching identifiers.
4869  #    string Class::operator*()
4870  if (match and
4871      not Search(r'\bstring\b(\s+const)?\s*[\*\&]\s*(const\s+)?\w', line) and
4872      not Search(r'\boperator\W', line) and
4873      not Match(r'\s*(<.*>)?(::[a-zA-Z0-9_]+)*\s*\(([^"]|$)', match.group(4))):
4874    if Search(r'\bconst\b', line):
4875      error(filename, linenum, 'runtime/string', 4,
4876            'For a static/global string constant, use a C style string '
4877            'instead: "%schar%s %s[]".' %
4878            (match.group(1), match.group(2) or '', match.group(3)))
4879    else:
4880      error(filename, linenum, 'runtime/string', 4,
4881            'Static/global string variables are not permitted.')
4882
4883  if (Search(r'\b([A-Za-z0-9_]*_)\(\1\)', line) or
4884      Search(r'\b([A-Za-z0-9_]*_)\(CHECK_NOTNULL\(\1\)\)', line)):
4885    error(filename, linenum, 'runtime/init', 4,
4886          'You seem to be initializing a member variable with itself.')
4887
4888
4889def CheckPrintf(filename, clean_lines, linenum, error):
4890  """Check for printf related issues.
4891
4892  Args:
4893    filename: The name of the current file.
4894    clean_lines: A CleansedLines instance containing the file.
4895    linenum: The number of the line to check.
4896    error: The function to call with any errors found.
4897  """
4898  line = clean_lines.elided[linenum]
4899
4900  # When snprintf is used, the second argument shouldn't be a literal.
4901  match = Search(r'snprintf\s*\(([^,]*),\s*([0-9]*)\s*,', line)
4902  if match and match.group(2) != '0':
4903    # If 2nd arg is zero, snprintf is used to calculate size.
4904    error(filename, linenum, 'runtime/printf', 3,
4905          'If you can, use sizeof(%s) instead of %s as the 2nd arg '
4906          'to snprintf.' % (match.group(1), match.group(2)))
4907
4908  # Check if some verboten C functions are being used.
4909  if Search(r'\bsprintf\s*\(', line):
4910    error(filename, linenum, 'runtime/printf', 5,
4911          'Never use sprintf. Use snprintf instead.')
4912  match = Search(r'\b(strcpy|strcat)\s*\(', line)
4913  if match:
4914    error(filename, linenum, 'runtime/printf', 4,
4915          'Almost always, snprintf is better than %s' % match.group(1))
4916
4917
4918def IsDerivedFunction(clean_lines, linenum):
4919  """Check if current line contains an inherited function.
4920
4921  Args:
4922    clean_lines: A CleansedLines instance containing the file.
4923    linenum: The number of the line to check.
4924  Returns:
4925    True if current line contains a function with "override"
4926    virt-specifier.
4927  """
4928  # Scan back a few lines for start of current function
4929  for i in xrange(linenum, max(-1, linenum - 10), -1):
4930    match = Match(r'^([^()]*\w+)\(', clean_lines.elided[i])
4931    if match:
4932      # Look for "override" after the matching closing parenthesis
4933      line, _, closing_paren = CloseExpression(
4934          clean_lines, i, len(match.group(1)))
4935      return (closing_paren >= 0 and
4936              Search(r'\boverride\b', line[closing_paren:]))
4937  return False
4938
4939
4940def IsOutOfLineMethodDefinition(clean_lines, linenum):
4941  """Check if current line contains an out-of-line method definition.
4942
4943  Args:
4944    clean_lines: A CleansedLines instance containing the file.
4945    linenum: The number of the line to check.
4946  Returns:
4947    True if current line contains an out-of-line method definition.
4948  """
4949  # Scan back a few lines for start of current function
4950  for i in xrange(linenum, max(-1, linenum - 10), -1):
4951    if Match(r'^([^()]*\w+)\(', clean_lines.elided[i]):
4952      return Match(r'^[^()]*\w+::\w+\(', clean_lines.elided[i]) is not None
4953  return False
4954
4955
4956def IsInitializerList(clean_lines, linenum):
4957  """Check if current line is inside constructor initializer list.
4958
4959  Args:
4960    clean_lines: A CleansedLines instance containing the file.
4961    linenum: The number of the line to check.
4962  Returns:
4963    True if current line appears to be inside constructor initializer
4964    list, False otherwise.
4965  """
4966  for i in xrange(linenum, 1, -1):
4967    line = clean_lines.elided[i]
4968    if i == linenum:
4969      remove_function_body = Match(r'^(.*)\{\s*$', line)
4970      if remove_function_body:
4971        line = remove_function_body.group(1)
4972
4973    if Search(r'\s:\s*\w+[({]', line):
4974      # A lone colon tend to indicate the start of a constructor
4975      # initializer list.  It could also be a ternary operator, which
4976      # also tend to appear in constructor initializer lists as
4977      # opposed to parameter lists.
4978      return True
4979    if Search(r'\}\s*,\s*$', line):
4980      # A closing brace followed by a comma is probably the end of a
4981      # brace-initialized member in constructor initializer list.
4982      return True
4983    if Search(r'[{};]\s*$', line):
4984      # Found one of the following:
4985      # - A closing brace or semicolon, probably the end of the previous
4986      #   function.
4987      # - An opening brace, probably the start of current class or namespace.
4988      #
4989      # Current line is probably not inside an initializer list since
4990      # we saw one of those things without seeing the starting colon.
4991      return False
4992
4993  # Got to the beginning of the file without seeing the start of
4994  # constructor initializer list.
4995  return False
4996
4997
4998def CheckForNonConstReference(filename, clean_lines, linenum,
4999                              nesting_state, error):
5000  """Check for non-const references.
5001
5002  Separate from CheckLanguage since it scans backwards from current
5003  line, instead of scanning forward.
5004
5005  Args:
5006    filename: The name of the current file.
5007    clean_lines: A CleansedLines instance containing the file.
5008    linenum: The number of the line to check.
5009    nesting_state: A NestingState instance which maintains information about
5010                   the current stack of nested blocks being parsed.
5011    error: The function to call with any errors found.
5012  """
5013  # Do nothing if there is no '&' on current line.
5014  line = clean_lines.elided[linenum]
5015  if '&' not in line:
5016    return
5017
5018  # If a function is inherited, current function doesn't have much of
5019  # a choice, so any non-const references should not be blamed on
5020  # derived function.
5021  if IsDerivedFunction(clean_lines, linenum):
5022    return
5023
5024  # Don't warn on out-of-line method definitions, as we would warn on the
5025  # in-line declaration, if it isn't marked with 'override'.
5026  if IsOutOfLineMethodDefinition(clean_lines, linenum):
5027    return
5028
5029  # Long type names may be broken across multiple lines, usually in one
5030  # of these forms:
5031  #   LongType
5032  #       ::LongTypeContinued &identifier
5033  #   LongType::
5034  #       LongTypeContinued &identifier
5035  #   LongType<
5036  #       ...>::LongTypeContinued &identifier
5037  #
5038  # If we detected a type split across two lines, join the previous
5039  # line to current line so that we can match const references
5040  # accordingly.
5041  #
5042  # Note that this only scans back one line, since scanning back
5043  # arbitrary number of lines would be expensive.  If you have a type
5044  # that spans more than 2 lines, please use a typedef.
5045  if linenum > 1:
5046    previous = None
5047    if Match(r'\s*::(?:[\w<>]|::)+\s*&\s*\S', line):
5048      # previous_line\n + ::current_line
5049      previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+[\w<>])\s*$',
5050                        clean_lines.elided[linenum - 1])
5051    elif Match(r'\s*[a-zA-Z_]([\w<>]|::)+\s*&\s*\S', line):
5052      # previous_line::\n + current_line
5053      previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+::)\s*$',
5054                        clean_lines.elided[linenum - 1])
5055    if previous:
5056      line = previous.group(1) + line.lstrip()
5057    else:
5058      # Check for templated parameter that is split across multiple lines
5059      endpos = line.rfind('>')
5060      if endpos > -1:
5061        (_, startline, startpos) = ReverseCloseExpression(
5062            clean_lines, linenum, endpos)
5063        if startpos > -1 and startline < linenum:
5064          # Found the matching < on an earlier line, collect all
5065          # pieces up to current line.
5066          line = ''
5067          for i in xrange(startline, linenum + 1):
5068            line += clean_lines.elided[i].strip()
5069
5070  # Check for non-const references in function parameters.  A single '&' may
5071  # found in the following places:
5072  #   inside expression: binary & for bitwise AND
5073  #   inside expression: unary & for taking the address of something
5074  #   inside declarators: reference parameter
5075  # We will exclude the first two cases by checking that we are not inside a
5076  # function body, including one that was just introduced by a trailing '{'.
5077  # TODO(unknown): Doesn't account for 'catch(Exception& e)' [rare].
5078  if (nesting_state.previous_stack_top and
5079      not (isinstance(nesting_state.previous_stack_top, _ClassInfo) or
5080           isinstance(nesting_state.previous_stack_top, _NamespaceInfo))):
5081    # Not at toplevel, not within a class, and not within a namespace
5082    return
5083
5084  # Avoid initializer lists.  We only need to scan back from the
5085  # current line for something that starts with ':'.
5086  #
5087  # We don't need to check the current line, since the '&' would
5088  # appear inside the second set of parentheses on the current line as
5089  # opposed to the first set.
5090  if linenum > 0:
5091    for i in xrange(linenum - 1, max(0, linenum - 10), -1):
5092      previous_line = clean_lines.elided[i]
5093      if not Search(r'[),]\s*$', previous_line):
5094        break
5095      if Match(r'^\s*:\s+\S', previous_line):
5096        return
5097
5098  # Avoid preprocessors
5099  if Search(r'\\\s*$', line):
5100    return
5101
5102  # Avoid constructor initializer lists
5103  if IsInitializerList(clean_lines, linenum):
5104    return
5105
5106  # We allow non-const references in a few standard places, like functions
5107  # called "swap()" or iostream operators like "<<" or ">>".  Do not check
5108  # those function parameters.
5109  #
5110  # We also accept & in static_assert, which looks like a function but
5111  # it's actually a declaration expression.
5112  whitelisted_functions = (r'(?:[sS]wap(?:<\w:+>)?|'
5113                           r'operator\s*[<>][<>]|'
5114                           r'static_assert|COMPILE_ASSERT'
5115                           r')\s*\(')
5116  if Search(whitelisted_functions, line):
5117    return
5118  elif not Search(r'\S+\([^)]*$', line):
5119    # Don't see a whitelisted function on this line.  Actually we
5120    # didn't see any function name on this line, so this is likely a
5121    # multi-line parameter list.  Try a bit harder to catch this case.
5122    for i in xrange(2):
5123      if (linenum > i and
5124          Search(whitelisted_functions, clean_lines.elided[linenum - i - 1])):
5125        return
5126
5127  decls = ReplaceAll(r'{[^}]*}', ' ', line)  # exclude function body
5128  for parameter in re.findall(_RE_PATTERN_REF_PARAM, decls):
5129    if (not Match(_RE_PATTERN_CONST_REF_PARAM, parameter) and
5130        not Match(_RE_PATTERN_REF_STREAM_PARAM, parameter)):
5131      error(filename, linenum, 'runtime/references', 2,
5132            'Is this a non-const reference? '
5133            'If so, make const or use a pointer: ' +
5134            ReplaceAll(' *<', '<', parameter))
5135
5136
5137def CheckCasts(filename, clean_lines, linenum, error):
5138  """Various cast related checks.
5139
5140  Args:
5141    filename: The name of the current file.
5142    clean_lines: A CleansedLines instance containing the file.
5143    linenum: The number of the line to check.
5144    error: The function to call with any errors found.
5145  """
5146  line = clean_lines.elided[linenum]
5147
5148  # Check to see if they're using an conversion function cast.
5149  # I just try to capture the most common basic types, though there are more.
5150  # Parameterless conversion functions, such as bool(), are allowed as they are
5151  # probably a member operator declaration or default constructor.
5152  match = Search(
5153      r'(\bnew\s+(?:const\s+)?|\S<\s*(?:const\s+)?)?\b'
5154      r'(int|float|double|bool|char|int32|uint32|int64|uint64)'
5155      r'(\([^)].*)', line)
5156  expecting_function = ExpectingFunctionArgs(clean_lines, linenum)
5157  if match and not expecting_function:
5158    matched_type = match.group(2)
5159
5160    # matched_new_or_template is used to silence two false positives:
5161    # - New operators
5162    # - Template arguments with function types
5163    #
5164    # For template arguments, we match on types immediately following
5165    # an opening bracket without any spaces.  This is a fast way to
5166    # silence the common case where the function type is the first
5167    # template argument.  False negative with less-than comparison is
5168    # avoided because those operators are usually followed by a space.
5169    #
5170    #   function<double(double)>   // bracket + no space = false positive
5171    #   value < double(42)         // bracket + space = true positive
5172    matched_new_or_template = match.group(1)
5173
5174    # Avoid arrays by looking for brackets that come after the closing
5175    # parenthesis.
5176    if Match(r'\([^()]+\)\s*\[', match.group(3)):
5177      return
5178
5179    # Other things to ignore:
5180    # - Function pointers
5181    # - Casts to pointer types
5182    # - Placement new
5183    # - Alias declarations
5184    matched_funcptr = match.group(3)
5185    if (matched_new_or_template is None and
5186        not (matched_funcptr and
5187             (Match(r'\((?:[^() ]+::\s*\*\s*)?[^() ]+\)\s*\(',
5188                    matched_funcptr) or
5189              matched_funcptr.startswith('(*)'))) and
5190        not Match(r'\s*using\s+\S+\s*=\s*' + matched_type, line) and
5191        not Search(r'new\(\S+\)\s*' + matched_type, line)):
5192      error(filename, linenum, 'readability/casting', 4,
5193            'Using deprecated casting style.  '
5194            'Use static_cast<%s>(...) instead' %
5195            matched_type)
5196
5197  if not expecting_function:
5198    CheckCStyleCast(filename, clean_lines, linenum, 'static_cast',
5199                    r'\((int|float|double|bool|char|u?int(16|32|64))\)', error)
5200
5201  # This doesn't catch all cases. Consider (const char * const)"hello".
5202  #
5203  # (char *) "foo" should always be a const_cast (reinterpret_cast won't
5204  # compile).
5205  if CheckCStyleCast(filename, clean_lines, linenum, 'const_cast',
5206                     r'\((char\s?\*+\s?)\)\s*"', error):
5207    pass
5208  else:
5209    # Check pointer casts for other than string constants
5210    CheckCStyleCast(filename, clean_lines, linenum, 'reinterpret_cast',
5211                    r'\((\w+\s?\*+\s?)\)', error)
5212
5213  # In addition, we look for people taking the address of a cast.  This
5214  # is dangerous -- casts can assign to temporaries, so the pointer doesn't
5215  # point where you think.
5216  #
5217  # Some non-identifier character is required before the '&' for the
5218  # expression to be recognized as a cast.  These are casts:
5219  #   expression = &static_cast<int*>(temporary());
5220  #   function(&(int*)(temporary()));
5221  #
5222  # This is not a cast:
5223  #   reference_type&(int* function_param);
5224  match = Search(
5225      r'(?:[^\w]&\(([^)*][^)]*)\)[\w(])|'
5226      r'(?:[^\w]&(static|dynamic|down|reinterpret)_cast\b)', line)
5227  if match:
5228    # Try a better error message when the & is bound to something
5229    # dereferenced by the casted pointer, as opposed to the casted
5230    # pointer itself.
5231    parenthesis_error = False
5232    match = Match(r'^(.*&(?:static|dynamic|down|reinterpret)_cast\b)<', line)
5233    if match:
5234      _, y1, x1 = CloseExpression(clean_lines, linenum, len(match.group(1)))
5235      if x1 >= 0 and clean_lines.elided[y1][x1] == '(':
5236        _, y2, x2 = CloseExpression(clean_lines, y1, x1)
5237        if x2 >= 0:
5238          extended_line = clean_lines.elided[y2][x2:]
5239          if y2 < clean_lines.NumLines() - 1:
5240            extended_line += clean_lines.elided[y2 + 1]
5241          if Match(r'\s*(?:->|\[)', extended_line):
5242            parenthesis_error = True
5243
5244    if parenthesis_error:
5245      error(filename, linenum, 'readability/casting', 4,
5246            ('Are you taking an address of something dereferenced '
5247             'from a cast?  Wrapping the dereferenced expression in '
5248             'parentheses will make the binding more obvious'))
5249    else:
5250      error(filename, linenum, 'runtime/casting', 4,
5251            ('Are you taking an address of a cast?  '
5252             'This is dangerous: could be a temp var.  '
5253             'Take the address before doing the cast, rather than after'))
5254
5255
5256def CheckCStyleCast(filename, clean_lines, linenum, cast_type, pattern, error):
5257  """Checks for a C-style cast by looking for the pattern.
5258
5259  Args:
5260    filename: The name of the current file.
5261    clean_lines: A CleansedLines instance containing the file.
5262    linenum: The number of the line to check.
5263    cast_type: The string for the C++ cast to recommend.  This is either
5264      reinterpret_cast, static_cast, or const_cast, depending.
5265    pattern: The regular expression used to find C-style casts.
5266    error: The function to call with any errors found.
5267
5268  Returns:
5269    True if an error was emitted.
5270    False otherwise.
5271  """
5272  line = clean_lines.elided[linenum]
5273  match = Search(pattern, line)
5274  if not match:
5275    return False
5276
5277  # Exclude lines with keywords that tend to look like casts
5278  context = line[0:match.start(1) - 1]
5279  if Match(r'.*\b(?:sizeof|alignof|alignas|[_A-Z][_A-Z0-9]*)\s*$', context):
5280    return False
5281
5282  # Try expanding current context to see if we one level of
5283  # parentheses inside a macro.
5284  if linenum > 0:
5285    for i in xrange(linenum - 1, max(0, linenum - 5), -1):
5286      context = clean_lines.elided[i] + context
5287  if Match(r'.*\b[_A-Z][_A-Z0-9]*\s*\((?:\([^()]*\)|[^()])*$', context):
5288    return False
5289
5290  # operator++(int) and operator--(int)
5291  if context.endswith(' operator++') or context.endswith(' operator--'):
5292    return False
5293
5294  # A single unnamed argument for a function tends to look like old style cast.
5295  # If we see those, don't issue warnings for deprecated casts.
5296  remainder = line[match.end(0):]
5297  if Match(r'^\s*(?:;|const\b|throw\b|final\b|override\b|[=>{),]|->)',
5298           remainder):
5299    return False
5300
5301  # At this point, all that should be left is actual casts.
5302  error(filename, linenum, 'readability/casting', 4,
5303        'Using C-style cast.  Use %s<%s>(...) instead' %
5304        (cast_type, match.group(1)))
5305
5306  return True
5307
5308
5309def ExpectingFunctionArgs(clean_lines, linenum):
5310  """Checks whether where function type arguments are expected.
5311
5312  Args:
5313    clean_lines: A CleansedLines instance containing the file.
5314    linenum: The number of the line to check.
5315
5316  Returns:
5317    True if the line at 'linenum' is inside something that expects arguments
5318    of function types.
5319  """
5320  line = clean_lines.elided[linenum]
5321  return (Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line) or
5322          (linenum >= 2 and
5323           (Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\((?:\S+,)?\s*$',
5324                  clean_lines.elided[linenum - 1]) or
5325            Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\(\s*$',
5326                  clean_lines.elided[linenum - 2]) or
5327            Search(r'\bstd::m?function\s*\<\s*$',
5328                   clean_lines.elided[linenum - 1]))))
5329
5330
5331_HEADERS_CONTAINING_TEMPLATES = (
5332    ('<deque>', ('deque',)),
5333    ('<functional>', ('unary_function', 'binary_function',
5334                      'plus', 'minus', 'multiplies', 'divides', 'modulus',
5335                      'negate',
5336                      'equal_to', 'not_equal_to', 'greater', 'less',
5337                      'greater_equal', 'less_equal',
5338                      'logical_and', 'logical_or', 'logical_not',
5339                      'unary_negate', 'not1', 'binary_negate', 'not2',
5340                      'bind1st', 'bind2nd',
5341                      'pointer_to_unary_function',
5342                      'pointer_to_binary_function',
5343                      'ptr_fun',
5344                      'mem_fun_t', 'mem_fun', 'mem_fun1_t', 'mem_fun1_ref_t',
5345                      'mem_fun_ref_t',
5346                      'const_mem_fun_t', 'const_mem_fun1_t',
5347                      'const_mem_fun_ref_t', 'const_mem_fun1_ref_t',
5348                      'mem_fun_ref',
5349                     )),
5350    ('<limits>', ('numeric_limits',)),
5351    ('<list>', ('list',)),
5352    ('<map>', ('map', 'multimap',)),
5353    ('<memory>', ('allocator', 'make_shared', 'make_unique', 'shared_ptr',
5354                  'unique_ptr', 'weak_ptr')),
5355    ('<queue>', ('queue', 'priority_queue',)),
5356    ('<set>', ('set', 'multiset',)),
5357    ('<stack>', ('stack',)),
5358    ('<string>', ('char_traits', 'basic_string',)),
5359    ('<tuple>', ('tuple',)),
5360    ('<unordered_map>', ('unordered_map', 'unordered_multimap')),
5361    ('<unordered_set>', ('unordered_set', 'unordered_multiset')),
5362    ('<utility>', ('pair',)),
5363    ('<vector>', ('vector',)),
5364
5365    # gcc extensions.
5366    # Note: std::hash is their hash, ::hash is our hash
5367    ('<hash_map>', ('hash_map', 'hash_multimap',)),
5368    ('<hash_set>', ('hash_set', 'hash_multiset',)),
5369    ('<slist>', ('slist',)),
5370    )
5371
5372_HEADERS_MAYBE_TEMPLATES = (
5373    ('<algorithm>', ('copy', 'max', 'min', 'min_element', 'sort',
5374                     'transform',
5375                    )),
5376    ('<utility>', ('forward', 'make_pair', 'move', 'swap')),
5377    )
5378
5379_RE_PATTERN_STRING = re.compile(r'\bstring\b')
5380
5381_re_pattern_headers_maybe_templates = []
5382for _header, _templates in _HEADERS_MAYBE_TEMPLATES:
5383  for _template in _templates:
5384    # Match max<type>(..., ...), max(..., ...), but not foo->max, foo.max or
5385    # type::max().
5386    _re_pattern_headers_maybe_templates.append(
5387        (re.compile(r'[^>.]\b' + _template + r'(<.*?>)?\([^\)]'),
5388            _template,
5389            _header))
5390
5391# Other scripts may reach in and modify this pattern.
5392_re_pattern_templates = []
5393for _header, _templates in _HEADERS_CONTAINING_TEMPLATES:
5394  for _template in _templates:
5395    _re_pattern_templates.append(
5396        (re.compile(r'(\<|\b)' + _template + r'\s*\<'),
5397         _template + '<>',
5398         _header))
5399
5400
5401def FilesBelongToSameModule(filename_cc, filename_h):
5402  """Check if these two filenames belong to the same module.
5403
5404  The concept of a 'module' here is a as follows:
5405  foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the
5406  same 'module' if they are in the same directory.
5407  some/path/public/xyzzy and some/path/internal/xyzzy are also considered
5408  to belong to the same module here.
5409
5410  If the filename_cc contains a longer path than the filename_h, for example,
5411  '/absolute/path/to/base/sysinfo.cc', and this file would include
5412  'base/sysinfo.h', this function also produces the prefix needed to open the
5413  header. This is used by the caller of this function to more robustly open the
5414  header file. We don't have access to the real include paths in this context,
5415  so we need this guesswork here.
5416
5417  Known bugs: tools/base/bar.cc and base/bar.h belong to the same module
5418  according to this implementation. Because of this, this function gives
5419  some false positives. This should be sufficiently rare in practice.
5420
5421  Args:
5422    filename_cc: is the path for the .cc file
5423    filename_h: is the path for the header path
5424
5425  Returns:
5426    Tuple with a bool and a string:
5427    bool: True if filename_cc and filename_h belong to the same module.
5428    string: the additional prefix needed to open the header file.
5429  """
5430
5431  fileinfo = FileInfo(filename_cc)
5432  if not fileinfo.IsSource():
5433    return (False, '')
5434  filename_cc = filename_cc[:-len(fileinfo.Extension())]
5435  matched_test_suffix = Search(_TEST_FILE_SUFFIX, fileinfo.BaseName())
5436  if matched_test_suffix:
5437    filename_cc = filename_cc[:-len(matched_test_suffix.group(1))]
5438  filename_cc = filename_cc.replace('/public/', '/')
5439  filename_cc = filename_cc.replace('/internal/', '/')
5440
5441  if not filename_h.endswith('.h'):
5442    return (False, '')
5443  filename_h = filename_h[:-len('.h')]
5444  if filename_h.endswith('-inl'):
5445    filename_h = filename_h[:-len('-inl')]
5446  filename_h = filename_h.replace('/public/', '/')
5447  filename_h = filename_h.replace('/internal/', '/')
5448
5449  files_belong_to_same_module = filename_cc.endswith(filename_h)
5450  common_path = ''
5451  if files_belong_to_same_module:
5452    common_path = filename_cc[:-len(filename_h)]
5453  return files_belong_to_same_module, common_path
5454
5455
5456def UpdateIncludeState(filename, include_dict, io=codecs):
5457  """Fill up the include_dict with new includes found from the file.
5458
5459  Args:
5460    filename: the name of the header to read.
5461    include_dict: a dictionary in which the headers are inserted.
5462    io: The io factory to use to read the file. Provided for testability.
5463
5464  Returns:
5465    True if a header was successfully added. False otherwise.
5466  """
5467  headerfile = None
5468  try:
5469    headerfile = io.open(filename, 'r', 'utf8', 'replace')
5470  except IOError:
5471    return False
5472  linenum = 0
5473  for line in headerfile:
5474    linenum += 1
5475    clean_line = CleanseComments(line)
5476    match = _RE_PATTERN_INCLUDE.search(clean_line)
5477    if match:
5478      include = match.group(2)
5479      include_dict.setdefault(include, linenum)
5480  return True
5481
5482
5483def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error,
5484                              io=codecs):
5485  """Reports for missing stl includes.
5486
5487  This function will output warnings to make sure you are including the headers
5488  necessary for the stl containers and functions that you use. We only give one
5489  reason to include a header. For example, if you use both equal_to<> and
5490  less<> in a .h file, only one (the latter in the file) of these will be
5491  reported as a reason to include the <functional>.
5492
5493  Args:
5494    filename: The name of the current file.
5495    clean_lines: A CleansedLines instance containing the file.
5496    include_state: An _IncludeState instance.
5497    error: The function to call with any errors found.
5498    io: The IO factory to use to read the header file. Provided for unittest
5499        injection.
5500  """
5501  required = {}  # A map of header name to linenumber and the template entity.
5502                 # Example of required: { '<functional>': (1219, 'less<>') }
5503
5504  for linenum in xrange(clean_lines.NumLines()):
5505    line = clean_lines.elided[linenum]
5506    if not line or line[0] == '#':
5507      continue
5508
5509    # String is special -- it is a non-templatized type in STL.
5510    matched = _RE_PATTERN_STRING.search(line)
5511    if matched:
5512      # Don't warn about strings in non-STL namespaces:
5513      # (We check only the first match per line; good enough.)
5514      prefix = line[:matched.start()]
5515      if prefix.endswith('std::') or not prefix.endswith('::'):
5516        required['<string>'] = (linenum, 'string')
5517
5518    for pattern, template, header in _re_pattern_headers_maybe_templates:
5519      if pattern.search(line):
5520        required[header] = (linenum, template)
5521
5522    # The following function is just a speed up, no semantics are changed.
5523    if not '<' in line:  # Reduces the cpu time usage by skipping lines.
5524      continue
5525
5526    for pattern, template, header in _re_pattern_templates:
5527      matched = pattern.search(line)
5528      if matched:
5529        # Don't warn about IWYU in non-STL namespaces:
5530        # (We check only the first match per line; good enough.)
5531        prefix = line[:matched.start()]
5532        if prefix.endswith('std::') or not prefix.endswith('::'):
5533          required[header] = (linenum, template)
5534
5535  # The policy is that if you #include something in foo.h you don't need to
5536  # include it again in foo.cc. Here, we will look at possible includes.
5537  # Let's flatten the include_state include_list and copy it into a dictionary.
5538  include_dict = dict([item for sublist in include_state.include_list
5539                       for item in sublist])
5540
5541  # Did we find the header for this file (if any) and successfully load it?
5542  header_found = False
5543
5544  # Use the absolute path so that matching works properly.
5545  abs_filename = FileInfo(filename).FullName()
5546
5547  # For Emacs's flymake.
5548  # If cpplint is invoked from Emacs's flymake, a temporary file is generated
5549  # by flymake and that file name might end with '_flymake.cc'. In that case,
5550  # restore original file name here so that the corresponding header file can be
5551  # found.
5552  # e.g. If the file name is 'foo_flymake.cc', we should search for 'foo.h'
5553  # instead of 'foo_flymake.h'
5554  abs_filename = re.sub(r'_flymake\.cc$', '.cc', abs_filename)
5555
5556  # include_dict is modified during iteration, so we iterate over a copy of
5557  # the keys.
5558  header_keys = include_dict.keys()
5559  for header in header_keys:
5560    (same_module, common_path) = FilesBelongToSameModule(abs_filename, header)
5561    fullpath = common_path + header
5562    if same_module and UpdateIncludeState(fullpath, include_dict, io):
5563      header_found = True
5564
5565  # If we can't find the header file for a .cc, assume it's because we don't
5566  # know where to look. In that case we'll give up as we're not sure they
5567  # didn't include it in the .h file.
5568  # TODO(unknown): Do a better job of finding .h files so we are confident that
5569  # not having the .h file means there isn't one.
5570  if filename.endswith('.cc') and not header_found:
5571    return
5572
5573  # All the lines have been processed, report the errors found.
5574  for required_header_unstripped in required:
5575    template = required[required_header_unstripped][1]
5576    if required_header_unstripped.strip('<>"') not in include_dict:
5577      error(filename, required[required_header_unstripped][0],
5578            'build/include_what_you_use', 4,
5579            'Add #include ' + required_header_unstripped + ' for ' + template)
5580
5581
5582_RE_PATTERN_EXPLICIT_MAKEPAIR = re.compile(r'\bmake_pair\s*<')
5583
5584
5585def CheckMakePairUsesDeduction(filename, clean_lines, linenum, error):
5586  """Check that make_pair's template arguments are deduced.
5587
5588  G++ 4.6 in C++11 mode fails badly if make_pair's template arguments are
5589  specified explicitly, and such use isn't intended in any case.
5590
5591  Args:
5592    filename: The name of the current file.
5593    clean_lines: A CleansedLines instance containing the file.
5594    linenum: The number of the line to check.
5595    error: The function to call with any errors found.
5596  """
5597  line = clean_lines.elided[linenum]
5598  match = _RE_PATTERN_EXPLICIT_MAKEPAIR.search(line)
5599  if match:
5600    error(filename, linenum, 'build/explicit_make_pair',
5601          4,  # 4 = high confidence
5602          'For C++11-compatibility, omit template arguments from make_pair'
5603          ' OR use pair directly OR if appropriate, construct a pair directly')
5604
5605
5606def CheckRedundantVirtual(filename, clean_lines, linenum, error):
5607  """Check if line contains a redundant "virtual" function-specifier.
5608
5609  Args:
5610    filename: The name of the current file.
5611    clean_lines: A CleansedLines instance containing the file.
5612    linenum: The number of the line to check.
5613    error: The function to call with any errors found.
5614  """
5615  # Look for "virtual" on current line.
5616  line = clean_lines.elided[linenum]
5617  virtual = Match(r'^(.*)(\bvirtual\b)(.*)$', line)
5618  if not virtual: return
5619
5620  # Ignore "virtual" keywords that are near access-specifiers.  These
5621  # are only used in class base-specifier and do not apply to member
5622  # functions.
5623  if (Search(r'\b(public|protected|private)\s+$', virtual.group(1)) or
5624      Match(r'^\s+(public|protected|private)\b', virtual.group(3))):
5625    return
5626
5627  # Ignore the "virtual" keyword from virtual base classes.  Usually
5628  # there is a column on the same line in these cases (virtual base
5629  # classes are rare in google3 because multiple inheritance is rare).
5630  if Match(r'^.*[^:]:[^:].*$', line): return
5631
5632  # Look for the next opening parenthesis.  This is the start of the
5633  # parameter list (possibly on the next line shortly after virtual).
5634  # TODO(unknown): doesn't work if there are virtual functions with
5635  # decltype() or other things that use parentheses, but csearch suggests
5636  # that this is rare.
5637  end_col = -1
5638  end_line = -1
5639  start_col = len(virtual.group(2))
5640  for start_line in xrange(linenum, min(linenum + 3, clean_lines.NumLines())):
5641    line = clean_lines.elided[start_line][start_col:]
5642    parameter_list = Match(r'^([^(]*)\(', line)
5643    if parameter_list:
5644      # Match parentheses to find the end of the parameter list
5645      (_, end_line, end_col) = CloseExpression(
5646          clean_lines, start_line, start_col + len(parameter_list.group(1)))
5647      break
5648    start_col = 0
5649
5650  if end_col < 0:
5651    return  # Couldn't find end of parameter list, give up
5652
5653  # Look for "override" or "final" after the parameter list
5654  # (possibly on the next few lines).
5655  for i in xrange(end_line, min(end_line + 3, clean_lines.NumLines())):
5656    line = clean_lines.elided[i][end_col:]
5657    match = Search(r'\b(override|final)\b', line)
5658    if match:
5659      error(filename, linenum, 'readability/inheritance', 4,
5660            ('"virtual" is redundant since function is '
5661             'already declared as "%s"' % match.group(1)))
5662
5663    # Set end_col to check whole lines after we are done with the
5664    # first line.
5665    end_col = 0
5666    if Search(r'[^\w]\s*$', line):
5667      break
5668
5669
5670def CheckRedundantOverrideOrFinal(filename, clean_lines, linenum, error):
5671  """Check if line contains a redundant "override" or "final" virt-specifier.
5672
5673  Args:
5674    filename: The name of the current file.
5675    clean_lines: A CleansedLines instance containing the file.
5676    linenum: The number of the line to check.
5677    error: The function to call with any errors found.
5678  """
5679  # Look for closing parenthesis nearby.  We need one to confirm where
5680  # the declarator ends and where the virt-specifier starts to avoid
5681  # false positives.
5682  line = clean_lines.elided[linenum]
5683  declarator_end = line.rfind(')')
5684  if declarator_end >= 0:
5685    fragment = line[declarator_end:]
5686  else:
5687    if linenum > 1 and clean_lines.elided[linenum - 1].rfind(')') >= 0:
5688      fragment = line
5689    else:
5690      return
5691
5692  # Check that at most one of "override" or "final" is present, not both
5693  if Search(r'\boverride\b', fragment) and Search(r'\bfinal\b', fragment):
5694    error(filename, linenum, 'readability/inheritance', 4,
5695          ('"override" is redundant since function is '
5696           'already declared as "final"'))
5697
5698
5699
5700
5701# Returns true if we are at a new block, and it is directly
5702# inside of a namespace.
5703def IsBlockInNameSpace(nesting_state, is_forward_declaration):
5704  """Checks that the new block is directly in a namespace.
5705
5706  Args:
5707    nesting_state: The _NestingState object that contains info about our state.
5708    is_forward_declaration: If the class is a forward declared class.
5709  Returns:
5710    Whether or not the new block is directly in a namespace.
5711  """
5712  if is_forward_declaration:
5713    if len(nesting_state.stack) >= 1 and (
5714        isinstance(nesting_state.stack[-1], _NamespaceInfo)):
5715      return True
5716    else:
5717      return False
5718
5719  return (len(nesting_state.stack) > 1 and
5720          nesting_state.stack[-1].check_namespace_indentation and
5721          isinstance(nesting_state.stack[-2], _NamespaceInfo))
5722
5723
5724def ShouldCheckNamespaceIndentation(nesting_state, is_namespace_indent_item,
5725                                    raw_lines_no_comments, linenum):
5726  """This method determines if we should apply our namespace indentation check.
5727
5728  Args:
5729    nesting_state: The current nesting state.
5730    is_namespace_indent_item: If we just put a new class on the stack, True.
5731      If the top of the stack is not a class, or we did not recently
5732      add the class, False.
5733    raw_lines_no_comments: The lines without the comments.
5734    linenum: The current line number we are processing.
5735
5736  Returns:
5737    True if we should apply our namespace indentation check. Currently, it
5738    only works for classes and namespaces inside of a namespace.
5739  """
5740
5741  is_forward_declaration = IsForwardClassDeclaration(raw_lines_no_comments,
5742                                                     linenum)
5743
5744  if not (is_namespace_indent_item or is_forward_declaration):
5745    return False
5746
5747  # If we are in a macro, we do not want to check the namespace indentation.
5748  if IsMacroDefinition(raw_lines_no_comments, linenum):
5749    return False
5750
5751  return IsBlockInNameSpace(nesting_state, is_forward_declaration)
5752
5753
5754# Call this method if the line is directly inside of a namespace.
5755# If the line above is blank (excluding comments) or the start of
5756# an inner namespace, it cannot be indented.
5757def CheckItemIndentationInNamespace(filename, raw_lines_no_comments, linenum,
5758                                    error):
5759  line = raw_lines_no_comments[linenum]
5760  if Match(r'^\s+', line):
5761    error(filename, linenum, 'runtime/indentation_namespace', 4,
5762          'Do not indent within a namespace')
5763
5764
5765def ProcessLine(filename, file_extension, clean_lines, line,
5766                include_state, function_state, nesting_state, error,
5767                extra_check_functions=[]):
5768  """Processes a single line in the file.
5769
5770  Args:
5771    filename: Filename of the file that is being processed.
5772    file_extension: The extension (dot not included) of the file.
5773    clean_lines: An array of strings, each representing a line of the file,
5774                 with comments stripped.
5775    line: Number of line being processed.
5776    include_state: An _IncludeState instance in which the headers are inserted.
5777    function_state: A _FunctionState instance which counts function lines, etc.
5778    nesting_state: A NestingState instance which maintains information about
5779                   the current stack of nested blocks being parsed.
5780    error: A callable to which errors are reported, which takes 4 arguments:
5781           filename, line number, error level, and message
5782    extra_check_functions: An array of additional check functions that will be
5783                           run on each source line. Each function takes 4
5784                           arguments: filename, clean_lines, line, error
5785  """
5786  raw_lines = clean_lines.raw_lines
5787  ParseNolintSuppressions(filename, raw_lines[line], line, error)
5788  nesting_state.Update(filename, clean_lines, line, error)
5789  CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line,
5790                               error)
5791  if nesting_state.InAsmBlock(): return
5792  CheckForFunctionLengths(filename, clean_lines, line, function_state, error)
5793  CheckForMultilineCommentsAndStrings(filename, clean_lines, line, error)
5794  CheckStyle(filename, clean_lines, line, file_extension, nesting_state, error)
5795  CheckLanguage(filename, clean_lines, line, file_extension, include_state,
5796                nesting_state, error)
5797  CheckForNonConstReference(filename, clean_lines, line, nesting_state, error)
5798  CheckForNonStandardConstructs(filename, clean_lines, line,
5799                                nesting_state, error)
5800  CheckVlogArguments(filename, clean_lines, line, error)
5801  CheckPosixThreading(filename, clean_lines, line, error)
5802  CheckInvalidIncrement(filename, clean_lines, line, error)
5803  CheckMakePairUsesDeduction(filename, clean_lines, line, error)
5804  CheckRedundantVirtual(filename, clean_lines, line, error)
5805  CheckRedundantOverrideOrFinal(filename, clean_lines, line, error)
5806  for check_fn in extra_check_functions:
5807    check_fn(filename, clean_lines, line, error)
5808
5809def FlagCxx11Features(filename, clean_lines, linenum, error):
5810  """Flag those c++11 features that we only allow in certain places.
5811
5812  Args:
5813    filename: The name of the current file.
5814    clean_lines: A CleansedLines instance containing the file.
5815    linenum: The number of the line to check.
5816    error: The function to call with any errors found.
5817  """
5818  line = clean_lines.elided[linenum]
5819
5820  include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line)
5821
5822  # Flag unapproved C++ TR1 headers.
5823  if include and include.group(1).startswith('tr1/'):
5824    error(filename, linenum, 'build/c++tr1', 5,
5825          ('C++ TR1 headers such as <%s> are unapproved.') % include.group(1))
5826
5827  # Flag unapproved C++11 headers.
5828  if include and include.group(1) in ('cfenv',
5829                                      'condition_variable',
5830                                      'fenv.h',
5831                                      'future',
5832                                      'mutex',
5833                                      'thread',
5834                                      'chrono',
5835                                      'ratio',
5836                                      'regex',
5837                                      'system_error',
5838                                     ):
5839    error(filename, linenum, 'build/c++11', 5,
5840          ('<%s> is an unapproved C++11 header.') % include.group(1))
5841
5842  # The only place where we need to worry about C++11 keywords and library
5843  # features in preprocessor directives is in macro definitions.
5844  if Match(r'\s*#', line) and not Match(r'\s*#\s*define\b', line): return
5845
5846  # These are classes and free functions.  The classes are always
5847  # mentioned as std::*, but we only catch the free functions if
5848  # they're not found by ADL.  They're alphabetical by header.
5849  for top_name in (
5850      # type_traits
5851      'alignment_of',
5852      'aligned_union',
5853      ):
5854    if Search(r'\bstd::%s\b' % top_name, line):
5855      error(filename, linenum, 'build/c++11', 5,
5856            ('std::%s is an unapproved C++11 class or function.  Send c-style '
5857             'an example of where it would make your code more readable, and '
5858             'they may let you use it.') % top_name)
5859
5860
5861def FlagCxx14Features(filename, clean_lines, linenum, error):
5862  """Flag those C++14 features that we restrict.
5863
5864  Args:
5865    filename: The name of the current file.
5866    clean_lines: A CleansedLines instance containing the file.
5867    linenum: The number of the line to check.
5868    error: The function to call with any errors found.
5869  """
5870  line = clean_lines.elided[linenum]
5871
5872  include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line)
5873
5874  # Flag unapproved C++14 headers.
5875  if include and include.group(1) in ('scoped_allocator', 'shared_mutex'):
5876    error(filename, linenum, 'build/c++14', 5,
5877          ('<%s> is an unapproved C++14 header.') % include.group(1))
5878
5879
5880def ProcessFileData(filename, file_extension, lines, error,
5881                    extra_check_functions=[]):
5882  """Performs lint checks and reports any errors to the given error function.
5883
5884  Args:
5885    filename: Filename of the file that is being processed.
5886    file_extension: The extension (dot not included) of the file.
5887    lines: An array of strings, each representing a line of the file, with the
5888           last element being empty if the file is terminated with a newline.
5889    error: A callable to which errors are reported, which takes 4 arguments:
5890           filename, line number, error level, and message
5891    extra_check_functions: An array of additional check functions that will be
5892                           run on each source line. Each function takes 4
5893                           arguments: filename, clean_lines, line, error
5894  """
5895  lines = (['// marker so line numbers and indices both start at 1'] + lines +
5896           ['// marker so line numbers end in a known way'])
5897
5898  include_state = _IncludeState()
5899  function_state = _FunctionState()
5900  nesting_state = NestingState()
5901
5902  ResetNolintSuppressions()
5903
5904  CheckForCopyright(filename, lines, error)
5905  ProcessGlobalSuppresions(lines)
5906  RemoveMultiLineComments(filename, lines, error)
5907  clean_lines = CleansedLines(lines)
5908
5909  if IsHeaderExtension(file_extension):
5910    CheckForHeaderGuard(filename, clean_lines, error)
5911
5912  for line in xrange(clean_lines.NumLines()):
5913    ProcessLine(filename, file_extension, clean_lines, line,
5914                include_state, function_state, nesting_state, error,
5915                extra_check_functions)
5916    FlagCxx11Features(filename, clean_lines, line, error)
5917  nesting_state.CheckCompletedBlocks(filename, error)
5918
5919  CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error)
5920
5921  # Check that the .cc file has included its header if it exists.
5922  if _IsSourceExtension(file_extension):
5923    CheckHeaderFileIncluded(filename, include_state, error)
5924
5925  # We check here rather than inside ProcessLine so that we see raw
5926  # lines rather than "cleaned" lines.
5927  CheckForBadCharacters(filename, lines, error)
5928
5929  CheckForNewlineAtEOF(filename, lines, error)
5930
5931def ProcessConfigOverrides(filename):
5932  """ Loads the configuration files and processes the config overrides.
5933
5934  Args:
5935    filename: The name of the file being processed by the linter.
5936
5937  Returns:
5938    False if the current |filename| should not be processed further.
5939  """
5940
5941  abs_filename = os.path.abspath(filename)
5942  cfg_filters = []
5943  keep_looking = True
5944  while keep_looking:
5945    abs_path, base_name = os.path.split(abs_filename)
5946    if not base_name:
5947      break  # Reached the root directory.
5948
5949    cfg_file = os.path.join(abs_path, "CPPLINT.cfg")
5950    abs_filename = abs_path
5951    if not os.path.isfile(cfg_file):
5952      continue
5953
5954    try:
5955      with open(cfg_file) as file_handle:
5956        for line in file_handle:
5957          line, _, _ = line.partition('#')  # Remove comments.
5958          if not line.strip():
5959            continue
5960
5961          name, _, val = line.partition('=')
5962          name = name.strip()
5963          val = val.strip()
5964          if name == 'set noparent':
5965            keep_looking = False
5966          elif name == 'filter':
5967            cfg_filters.append(val)
5968          elif name == 'exclude_files':
5969            # When matching exclude_files pattern, use the base_name of
5970            # the current file name or the directory name we are processing.
5971            # For example, if we are checking for lint errors in /foo/bar/baz.cc
5972            # and we found the .cfg file at /foo/CPPLINT.cfg, then the config
5973            # file's "exclude_files" filter is meant to be checked against "bar"
5974            # and not "baz" nor "bar/baz.cc".
5975            if base_name:
5976              pattern = re.compile(val)
5977              if pattern.match(base_name):
5978                if _cpplint_state.quiet:
5979                  # Suppress "Ignoring file" warning when using --quiet.
5980                  return False
5981                sys.stderr.write('Ignoring "%s": file excluded by "%s". '
5982                                 'File path component "%s" matches '
5983                                 'pattern "%s"\n' %
5984                                 (filename, cfg_file, base_name, val))
5985                return False
5986          elif name == 'linelength':
5987            global _line_length
5988            try:
5989                _line_length = int(val)
5990            except ValueError:
5991                sys.stderr.write('Line length must be numeric.')
5992          elif name == 'root':
5993            global _root
5994            # root directories are specified relative to CPPLINT.cfg dir.
5995            _root = os.path.join(os.path.dirname(cfg_file), val)
5996          elif name == 'headers':
5997            ProcessHppHeadersOption(val)
5998          else:
5999            sys.stderr.write(
6000                'Invalid configuration option (%s) in file %s\n' %
6001                (name, cfg_file))
6002
6003    except IOError:
6004      sys.stderr.write(
6005          "Skipping config file '%s': Can't open for reading\n" % cfg_file)
6006      keep_looking = False
6007
6008  # Apply all the accumulated filters in reverse order (top-level directory
6009  # config options having the least priority).
6010  for filter in reversed(cfg_filters):
6011     _AddFilters(filter)
6012
6013  return True
6014
6015
6016def ProcessFile(filename, vlevel, extra_check_functions=[]):
6017  """Does google-lint on a single file.
6018
6019  Args:
6020    filename: The name of the file to parse.
6021
6022    vlevel: The level of errors to report.  Every error of confidence
6023    >= verbose_level will be reported.  0 is a good default.
6024
6025    extra_check_functions: An array of additional check functions that will be
6026                           run on each source line. Each function takes 4
6027                           arguments: filename, clean_lines, line, error
6028  """
6029
6030  _SetVerboseLevel(vlevel)
6031  _BackupFilters()
6032  old_errors = _cpplint_state.error_count
6033
6034  if not ProcessConfigOverrides(filename):
6035    _RestoreFilters()
6036    return
6037
6038  lf_lines = []
6039  crlf_lines = []
6040  try:
6041    # Support the UNIX convention of using "-" for stdin.  Note that
6042    # we are not opening the file with universal newline support
6043    # (which codecs doesn't support anyway), so the resulting lines do
6044    # contain trailing '\r' characters if we are reading a file that
6045    # has CRLF endings.
6046    # If after the split a trailing '\r' is present, it is removed
6047    # below.
6048    if filename == '-':
6049      lines = codecs.StreamReaderWriter(sys.stdin,
6050                                        codecs.getreader('utf8'),
6051                                        codecs.getwriter('utf8'),
6052                                        'replace').read().split('\n')
6053    else:
6054      lines = codecs.open(filename, 'r', 'utf8', 'replace').read().split('\n')
6055
6056    # Remove trailing '\r'.
6057    # The -1 accounts for the extra trailing blank line we get from split()
6058    for linenum in range(len(lines) - 1):
6059      if lines[linenum].endswith('\r'):
6060        lines[linenum] = lines[linenum].rstrip('\r')
6061        crlf_lines.append(linenum + 1)
6062      else:
6063        lf_lines.append(linenum + 1)
6064
6065  except IOError:
6066    sys.stderr.write(
6067        "Skipping input '%s': Can't open for reading\n" % filename)
6068    _RestoreFilters()
6069    return
6070
6071  # Note, if no dot is found, this will give the entire filename as the ext.
6072  file_extension = filename[filename.rfind('.') + 1:]
6073
6074  # When reading from stdin, the extension is unknown, so no cpplint tests
6075  # should rely on the extension.
6076  if filename != '-' and file_extension not in _valid_extensions:
6077    sys.stderr.write('Ignoring %s; not a valid file name '
6078                     '(%s)\n' % (filename, ', '.join(_valid_extensions)))
6079  else:
6080    ProcessFileData(filename, file_extension, lines, Error,
6081                    extra_check_functions)
6082
6083    # If end-of-line sequences are a mix of LF and CR-LF, issue
6084    # warnings on the lines with CR.
6085    #
6086    # Don't issue any warnings if all lines are uniformly LF or CR-LF,
6087    # since critique can handle these just fine, and the style guide
6088    # doesn't dictate a particular end of line sequence.
6089    #
6090    # We can't depend on os.linesep to determine what the desired
6091    # end-of-line sequence should be, since that will return the
6092    # server-side end-of-line sequence.
6093    if lf_lines and crlf_lines:
6094      # Warn on every line with CR.  An alternative approach might be to
6095      # check whether the file is mostly CRLF or just LF, and warn on the
6096      # minority, we bias toward LF here since most tools prefer LF.
6097      for linenum in crlf_lines:
6098        Error(filename, linenum, 'whitespace/newline', 1,
6099              'Unexpected \\r (^M) found; better to use only \\n')
6100
6101  # Suppress printing anything if --quiet was passed unless the error
6102  # count has increased after processing this file.
6103  if not _cpplint_state.quiet or old_errors != _cpplint_state.error_count:
6104    sys.stdout.write('Done processing %s\n' % filename)
6105  _RestoreFilters()
6106
6107
6108def PrintUsage(message):
6109  """Prints a brief usage string and exits, optionally with an error message.
6110
6111  Args:
6112    message: The optional error message.
6113  """
6114  sys.stderr.write(_USAGE)
6115  if message:
6116    sys.exit('\nFATAL ERROR: ' + message)
6117  else:
6118    sys.exit(1)
6119
6120
6121def PrintCategories():
6122  """Prints a list of all the error-categories used by error messages.
6123
6124  These are the categories used to filter messages via --filter.
6125  """
6126  sys.stderr.write(''.join('  %s\n' % cat for cat in _ERROR_CATEGORIES))
6127  sys.exit(0)
6128
6129
6130def ParseArguments(args):
6131  """Parses the command line arguments.
6132
6133  This may set the output format and verbosity level as side-effects.
6134
6135  Args:
6136    args: The command line arguments:
6137
6138  Returns:
6139    The list of filenames to lint.
6140  """
6141  try:
6142    (opts, filenames) = getopt.getopt(args, '', ['help', 'output=', 'verbose=',
6143                                                 'counting=',
6144                                                 'filter=',
6145                                                 'root=',
6146                                                 'linelength=',
6147                                                 'extensions=',
6148                                                 'headers=',
6149                                                 'quiet'])
6150  except getopt.GetoptError:
6151    PrintUsage('Invalid arguments.')
6152
6153  verbosity = _VerboseLevel()
6154  output_format = _OutputFormat()
6155  filters = ''
6156  quiet = _Quiet()
6157  counting_style = ''
6158
6159  for (opt, val) in opts:
6160    if opt == '--help':
6161      PrintUsage(None)
6162    elif opt == '--output':
6163      if val not in ('emacs', 'vs7', 'eclipse'):
6164        PrintUsage('The only allowed output formats are emacs, vs7 and eclipse.')
6165      output_format = val
6166    elif opt == '--quiet':
6167      quiet = True
6168    elif opt == '--verbose':
6169      verbosity = int(val)
6170    elif opt == '--filter':
6171      filters = val
6172      if not filters:
6173        PrintCategories()
6174    elif opt == '--counting':
6175      if val not in ('total', 'toplevel', 'detailed'):
6176        PrintUsage('Valid counting options are total, toplevel, and detailed')
6177      counting_style = val
6178    elif opt == '--root':
6179      global _root
6180      _root = val
6181    elif opt == '--linelength':
6182      global _line_length
6183      try:
6184          _line_length = int(val)
6185      except ValueError:
6186          PrintUsage('Line length must be digits.')
6187    elif opt == '--extensions':
6188      global _valid_extensions
6189      try:
6190          _valid_extensions = set(val.split(','))
6191      except ValueError:
6192          PrintUsage('Extensions must be comma seperated list.')
6193    elif opt == '--headers':
6194      ProcessHppHeadersOption(val)
6195
6196  if not filenames:
6197    PrintUsage('No files were specified.')
6198
6199  _SetOutputFormat(output_format)
6200  _SetQuiet(quiet)
6201  _SetVerboseLevel(verbosity)
6202  _SetFilters(filters)
6203  _SetCountingStyle(counting_style)
6204
6205  return filenames
6206
6207
6208def main():
6209  filenames = ParseArguments(sys.argv[1:])
6210
6211  # Change stderr to write with replacement characters so we don't die
6212  # if we try to print something containing non-ASCII characters.
6213  sys.stderr = codecs.StreamReaderWriter(sys.stderr,
6214                                         codecs.getreader('utf8'),
6215                                         codecs.getwriter('utf8'),
6216                                         'replace')
6217
6218  _cpplint_state.ResetErrorCounts()
6219  for filename in filenames:
6220    ProcessFile(filename, _cpplint_state.verbose_level)
6221  # If --quiet is passed, suppress printing error count unless there are errors.
6222  if not _cpplint_state.quiet or _cpplint_state.error_count > 0:
6223    _cpplint_state.PrintErrorCounts()
6224
6225  sys.exit(_cpplint_state.error_count > 0)
6226
6227
6228if __name__ == '__main__':
6229  main()
6230