xref: /aosp_15_r20/external/compiler-rt/lib/sanitizer_common/scripts/cpplint.py (revision 7c3d14c8b49c529e04be81a3ce6f5cc23712e4c6)
1*7c3d14c8STreehugger Robot#!/usr/bin/env python
2*7c3d14c8STreehugger Robot#
3*7c3d14c8STreehugger Robot# Copyright (c) 2009 Google Inc. All rights reserved.
4*7c3d14c8STreehugger Robot#
5*7c3d14c8STreehugger Robot# Redistribution and use in source and binary forms, with or without
6*7c3d14c8STreehugger Robot# modification, are permitted provided that the following conditions are
7*7c3d14c8STreehugger Robot# met:
8*7c3d14c8STreehugger Robot#
9*7c3d14c8STreehugger Robot#    * Redistributions of source code must retain the above copyright
10*7c3d14c8STreehugger Robot# notice, this list of conditions and the following disclaimer.
11*7c3d14c8STreehugger Robot#    * Redistributions in binary form must reproduce the above
12*7c3d14c8STreehugger Robot# copyright notice, this list of conditions and the following disclaimer
13*7c3d14c8STreehugger Robot# in the documentation and/or other materials provided with the
14*7c3d14c8STreehugger Robot# distribution.
15*7c3d14c8STreehugger Robot#    * Neither the name of Google Inc. nor the names of its
16*7c3d14c8STreehugger Robot# contributors may be used to endorse or promote products derived from
17*7c3d14c8STreehugger Robot# this software without specific prior written permission.
18*7c3d14c8STreehugger Robot#
19*7c3d14c8STreehugger Robot# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20*7c3d14c8STreehugger Robot# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21*7c3d14c8STreehugger Robot# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22*7c3d14c8STreehugger Robot# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23*7c3d14c8STreehugger Robot# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24*7c3d14c8STreehugger Robot# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25*7c3d14c8STreehugger Robot# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26*7c3d14c8STreehugger Robot# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27*7c3d14c8STreehugger Robot# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28*7c3d14c8STreehugger Robot# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29*7c3d14c8STreehugger Robot# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30*7c3d14c8STreehugger Robot
31*7c3d14c8STreehugger Robot# Here are some issues that I've had people identify in my code during reviews,
32*7c3d14c8STreehugger Robot# that I think are possible to flag automatically in a lint tool.  If these were
33*7c3d14c8STreehugger Robot# caught by lint, it would save time both for myself and that of my reviewers.
34*7c3d14c8STreehugger Robot# Most likely, some of these are beyond the scope of the current lint framework,
35*7c3d14c8STreehugger Robot# but I think it is valuable to retain these wish-list items even if they cannot
36*7c3d14c8STreehugger Robot# be immediately implemented.
37*7c3d14c8STreehugger Robot#
38*7c3d14c8STreehugger Robot#  Suggestions
39*7c3d14c8STreehugger Robot#  -----------
40*7c3d14c8STreehugger Robot#  - Check for no 'explicit' for multi-arg ctor
41*7c3d14c8STreehugger Robot#  - Check for boolean assign RHS in parens
42*7c3d14c8STreehugger Robot#  - Check for ctor initializer-list colon position and spacing
43*7c3d14c8STreehugger Robot#  - Check that if there's a ctor, there should be a dtor
44*7c3d14c8STreehugger Robot#  - Check accessors that return non-pointer member variables are
45*7c3d14c8STreehugger Robot#    declared const
46*7c3d14c8STreehugger Robot#  - Check accessors that return non-const pointer member vars are
47*7c3d14c8STreehugger Robot#    *not* declared const
48*7c3d14c8STreehugger Robot#  - Check for using public includes for testing
49*7c3d14c8STreehugger Robot#  - Check for spaces between brackets in one-line inline method
50*7c3d14c8STreehugger Robot#  - Check for no assert()
51*7c3d14c8STreehugger Robot#  - Check for spaces surrounding operators
52*7c3d14c8STreehugger Robot#  - Check for 0 in pointer context (should be NULL)
53*7c3d14c8STreehugger Robot#  - Check for 0 in char context (should be '\0')
54*7c3d14c8STreehugger Robot#  - Check for camel-case method name conventions for methods
55*7c3d14c8STreehugger Robot#    that are not simple inline getters and setters
56*7c3d14c8STreehugger Robot#  - Do not indent namespace contents
57*7c3d14c8STreehugger Robot#  - Avoid inlining non-trivial constructors in header files
58*7c3d14c8STreehugger Robot#  - Check for old-school (void) cast for call-sites of functions
59*7c3d14c8STreehugger Robot#    ignored return value
60*7c3d14c8STreehugger Robot#  - Check gUnit usage of anonymous namespace
61*7c3d14c8STreehugger Robot#  - Check for class declaration order (typedefs, consts, enums,
62*7c3d14c8STreehugger Robot#    ctor(s?), dtor, friend declarations, methods, member vars)
63*7c3d14c8STreehugger Robot#
64*7c3d14c8STreehugger Robot
65*7c3d14c8STreehugger Robot"""Does google-lint on c++ files.
66*7c3d14c8STreehugger Robot
67*7c3d14c8STreehugger RobotThe goal of this script is to identify places in the code that *may*
68*7c3d14c8STreehugger Robotbe in non-compliance with google style.  It does not attempt to fix
69*7c3d14c8STreehugger Robotup these problems -- the point is to educate.  It does also not
70*7c3d14c8STreehugger Robotattempt to find all problems, or to ensure that everything it does
71*7c3d14c8STreehugger Robotfind is legitimately a problem.
72*7c3d14c8STreehugger Robot
73*7c3d14c8STreehugger RobotIn particular, we can get very confused by /* and // inside strings!
74*7c3d14c8STreehugger RobotWe do a small hack, which is to ignore //'s with "'s after them on the
75*7c3d14c8STreehugger Robotsame line, but it is far from perfect (in either direction).
76*7c3d14c8STreehugger Robot"""
77*7c3d14c8STreehugger Robot
78*7c3d14c8STreehugger Robotimport codecs
79*7c3d14c8STreehugger Robotimport copy
80*7c3d14c8STreehugger Robotimport getopt
81*7c3d14c8STreehugger Robotimport math  # for log
82*7c3d14c8STreehugger Robotimport os
83*7c3d14c8STreehugger Robotimport re
84*7c3d14c8STreehugger Robotimport sre_compile
85*7c3d14c8STreehugger Robotimport string
86*7c3d14c8STreehugger Robotimport sys
87*7c3d14c8STreehugger Robotimport unicodedata
88*7c3d14c8STreehugger Robot
89*7c3d14c8STreehugger Robot
90*7c3d14c8STreehugger Robot_USAGE = """
91*7c3d14c8STreehugger RobotSyntax: cpplint.py [--verbose=#] [--output=vs7] [--filter=-x,+y,...]
92*7c3d14c8STreehugger Robot                   [--counting=total|toplevel|detailed]
93*7c3d14c8STreehugger Robot        <file> [file] ...
94*7c3d14c8STreehugger Robot
95*7c3d14c8STreehugger Robot  The style guidelines this tries to follow are those in
96*7c3d14c8STreehugger Robot    http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml
97*7c3d14c8STreehugger Robot
98*7c3d14c8STreehugger Robot  Every problem is given a confidence score from 1-5, with 5 meaning we are
99*7c3d14c8STreehugger Robot  certain of the problem, and 1 meaning it could be a legitimate construct.
100*7c3d14c8STreehugger Robot  This will miss some errors, and is not a substitute for a code review.
101*7c3d14c8STreehugger Robot
102*7c3d14c8STreehugger Robot  To suppress false-positive errors of a certain category, add a
103*7c3d14c8STreehugger Robot  'NOLINT(category)' comment to the line.  NOLINT or NOLINT(*)
104*7c3d14c8STreehugger Robot  suppresses errors of all categories on that line.
105*7c3d14c8STreehugger Robot
106*7c3d14c8STreehugger Robot  The files passed in will be linted; at least one file must be provided.
107*7c3d14c8STreehugger Robot  Linted extensions are .cc, .cpp, and .h.  Other file types will be ignored.
108*7c3d14c8STreehugger Robot
109*7c3d14c8STreehugger Robot  Flags:
110*7c3d14c8STreehugger Robot
111*7c3d14c8STreehugger Robot    output=vs7
112*7c3d14c8STreehugger Robot      By default, the output is formatted to ease emacs parsing.  Visual Studio
113*7c3d14c8STreehugger Robot      compatible output (vs7) may also be used.  Other formats are unsupported.
114*7c3d14c8STreehugger Robot
115*7c3d14c8STreehugger Robot    verbose=#
116*7c3d14c8STreehugger Robot      Specify a number 0-5 to restrict errors to certain verbosity levels.
117*7c3d14c8STreehugger Robot
118*7c3d14c8STreehugger Robot    filter=-x,+y,...
119*7c3d14c8STreehugger Robot      Specify a comma-separated list of category-filters to apply: only
120*7c3d14c8STreehugger Robot      error messages whose category names pass the filters will be printed.
121*7c3d14c8STreehugger Robot      (Category names are printed with the message and look like
122*7c3d14c8STreehugger Robot      "[whitespace/indent]".)  Filters are evaluated left to right.
123*7c3d14c8STreehugger Robot      "-FOO" and "FOO" means "do not print categories that start with FOO".
124*7c3d14c8STreehugger Robot      "+FOO" means "do print categories that start with FOO".
125*7c3d14c8STreehugger Robot
126*7c3d14c8STreehugger Robot      Examples: --filter=-whitespace,+whitespace/braces
127*7c3d14c8STreehugger Robot                --filter=whitespace,runtime/printf,+runtime/printf_format
128*7c3d14c8STreehugger Robot                --filter=-,+build/include_what_you_use
129*7c3d14c8STreehugger Robot
130*7c3d14c8STreehugger Robot      To see a list of all the categories used in cpplint, pass no arg:
131*7c3d14c8STreehugger Robot         --filter=
132*7c3d14c8STreehugger Robot
133*7c3d14c8STreehugger Robot    counting=total|toplevel|detailed
134*7c3d14c8STreehugger Robot      The total number of errors found is always printed. If
135*7c3d14c8STreehugger Robot      'toplevel' is provided, then the count of errors in each of
136*7c3d14c8STreehugger Robot      the top-level categories like 'build' and 'whitespace' will
137*7c3d14c8STreehugger Robot      also be printed. If 'detailed' is provided, then a count
138*7c3d14c8STreehugger Robot      is provided for each category like 'build/class'.
139*7c3d14c8STreehugger Robot
140*7c3d14c8STreehugger Robot    root=subdir
141*7c3d14c8STreehugger Robot      The root directory used for deriving header guard CPP variable.
142*7c3d14c8STreehugger Robot      By default, the header guard CPP variable is calculated as the relative
143*7c3d14c8STreehugger Robot      path to the directory that contains .git, .hg, or .svn.  When this flag
144*7c3d14c8STreehugger Robot      is specified, the relative path is calculated from the specified
145*7c3d14c8STreehugger Robot      directory. If the specified directory does not exist, this flag is
146*7c3d14c8STreehugger Robot      ignored.
147*7c3d14c8STreehugger Robot
148*7c3d14c8STreehugger Robot      Examples:
149*7c3d14c8STreehugger Robot        Assuing that src/.git exists, the header guard CPP variables for
150*7c3d14c8STreehugger Robot        src/chrome/browser/ui/browser.h are:
151*7c3d14c8STreehugger Robot
152*7c3d14c8STreehugger Robot        No flag => CHROME_BROWSER_UI_BROWSER_H_
153*7c3d14c8STreehugger Robot        --root=chrome => BROWSER_UI_BROWSER_H_
154*7c3d14c8STreehugger Robot        --root=chrome/browser => UI_BROWSER_H_
155*7c3d14c8STreehugger Robot"""
156*7c3d14c8STreehugger Robot
157*7c3d14c8STreehugger Robot# We categorize each error message we print.  Here are the categories.
158*7c3d14c8STreehugger Robot# We want an explicit list so we can list them all in cpplint --filter=.
159*7c3d14c8STreehugger Robot# If you add a new error message with a new category, add it to the list
160*7c3d14c8STreehugger Robot# here!  cpplint_unittest.py should tell you if you forget to do this.
161*7c3d14c8STreehugger Robot# \ used for clearer layout -- pylint: disable-msg=C6013
162*7c3d14c8STreehugger Robot_ERROR_CATEGORIES = [
163*7c3d14c8STreehugger Robot  'build/class',
164*7c3d14c8STreehugger Robot  'build/deprecated',
165*7c3d14c8STreehugger Robot  'build/endif_comment',
166*7c3d14c8STreehugger Robot  'build/explicit_make_pair',
167*7c3d14c8STreehugger Robot  'build/forward_decl',
168*7c3d14c8STreehugger Robot  'build/header_guard',
169*7c3d14c8STreehugger Robot  'build/include',
170*7c3d14c8STreehugger Robot  'build/include_alpha',
171*7c3d14c8STreehugger Robot  'build/include_order',
172*7c3d14c8STreehugger Robot  'build/include_what_you_use',
173*7c3d14c8STreehugger Robot  'build/namespaces',
174*7c3d14c8STreehugger Robot  'build/printf_format',
175*7c3d14c8STreehugger Robot  'build/storage_class',
176*7c3d14c8STreehugger Robot  'legal/copyright',
177*7c3d14c8STreehugger Robot  'readability/alt_tokens',
178*7c3d14c8STreehugger Robot  'readability/braces',
179*7c3d14c8STreehugger Robot  'readability/casting',
180*7c3d14c8STreehugger Robot  'readability/check',
181*7c3d14c8STreehugger Robot  'readability/constructors',
182*7c3d14c8STreehugger Robot  'readability/fn_size',
183*7c3d14c8STreehugger Robot  'readability/function',
184*7c3d14c8STreehugger Robot  'readability/multiline_comment',
185*7c3d14c8STreehugger Robot  'readability/multiline_string',
186*7c3d14c8STreehugger Robot  'readability/namespace',
187*7c3d14c8STreehugger Robot  'readability/nolint',
188*7c3d14c8STreehugger Robot  'readability/streams',
189*7c3d14c8STreehugger Robot  'readability/todo',
190*7c3d14c8STreehugger Robot  'readability/utf8',
191*7c3d14c8STreehugger Robot  'runtime/arrays',
192*7c3d14c8STreehugger Robot  'runtime/casting',
193*7c3d14c8STreehugger Robot  'runtime/explicit',
194*7c3d14c8STreehugger Robot  'runtime/int',
195*7c3d14c8STreehugger Robot  'runtime/init',
196*7c3d14c8STreehugger Robot  'runtime/invalid_increment',
197*7c3d14c8STreehugger Robot  'runtime/member_string_references',
198*7c3d14c8STreehugger Robot  'runtime/memset',
199*7c3d14c8STreehugger Robot  'runtime/operator',
200*7c3d14c8STreehugger Robot  'runtime/printf',
201*7c3d14c8STreehugger Robot  'runtime/printf_format',
202*7c3d14c8STreehugger Robot  'runtime/references',
203*7c3d14c8STreehugger Robot  'runtime/rtti',
204*7c3d14c8STreehugger Robot  'runtime/sizeof',
205*7c3d14c8STreehugger Robot  'runtime/string',
206*7c3d14c8STreehugger Robot  'runtime/threadsafe_fn',
207*7c3d14c8STreehugger Robot  'whitespace/blank_line',
208*7c3d14c8STreehugger Robot  'whitespace/braces',
209*7c3d14c8STreehugger Robot  'whitespace/comma',
210*7c3d14c8STreehugger Robot  'whitespace/comments',
211*7c3d14c8STreehugger Robot  'whitespace/empty_loop_body',
212*7c3d14c8STreehugger Robot  'whitespace/end_of_line',
213*7c3d14c8STreehugger Robot  'whitespace/ending_newline',
214*7c3d14c8STreehugger Robot  'whitespace/forcolon',
215*7c3d14c8STreehugger Robot  'whitespace/indent',
216*7c3d14c8STreehugger Robot  'whitespace/labels',
217*7c3d14c8STreehugger Robot  'whitespace/line_length',
218*7c3d14c8STreehugger Robot  'whitespace/newline',
219*7c3d14c8STreehugger Robot  'whitespace/operators',
220*7c3d14c8STreehugger Robot  'whitespace/parens',
221*7c3d14c8STreehugger Robot  'whitespace/semicolon',
222*7c3d14c8STreehugger Robot  'whitespace/tab',
223*7c3d14c8STreehugger Robot  'whitespace/todo'
224*7c3d14c8STreehugger Robot  ]
225*7c3d14c8STreehugger Robot
226*7c3d14c8STreehugger Robot# The default state of the category filter. This is overrided by the --filter=
227*7c3d14c8STreehugger Robot# flag. By default all errors are on, so only add here categories that should be
228*7c3d14c8STreehugger Robot# off by default (i.e., categories that must be enabled by the --filter= flags).
229*7c3d14c8STreehugger Robot# All entries here should start with a '-' or '+', as in the --filter= flag.
230*7c3d14c8STreehugger Robot_DEFAULT_FILTERS = ['-build/include_alpha']
231*7c3d14c8STreehugger Robot
232*7c3d14c8STreehugger Robot# We used to check for high-bit characters, but after much discussion we
233*7c3d14c8STreehugger Robot# decided those were OK, as long as they were in UTF-8 and didn't represent
234*7c3d14c8STreehugger Robot# hard-coded international strings, which belong in a separate i18n file.
235*7c3d14c8STreehugger Robot
236*7c3d14c8STreehugger Robot# Headers that we consider STL headers.
237*7c3d14c8STreehugger Robot_STL_HEADERS = frozenset([
238*7c3d14c8STreehugger Robot    'algobase.h', 'algorithm', 'alloc.h', 'bitset', 'deque', 'exception',
239*7c3d14c8STreehugger Robot    'function.h', 'functional', 'hash_map', 'hash_map.h', 'hash_set',
240*7c3d14c8STreehugger Robot    'hash_set.h', 'iterator', 'list', 'list.h', 'map', 'memory', 'new',
241*7c3d14c8STreehugger Robot    'pair.h', 'pthread_alloc', 'queue', 'set', 'set.h', 'sstream', 'stack',
242*7c3d14c8STreehugger Robot    'stl_alloc.h', 'stl_relops.h', 'type_traits.h',
243*7c3d14c8STreehugger Robot    'utility', 'vector', 'vector.h',
244*7c3d14c8STreehugger Robot    ])
245*7c3d14c8STreehugger Robot
246*7c3d14c8STreehugger Robot
247*7c3d14c8STreehugger Robot# Non-STL C++ system headers.
248*7c3d14c8STreehugger Robot_CPP_HEADERS = frozenset([
249*7c3d14c8STreehugger Robot    'algo.h', 'builtinbuf.h', 'bvector.h', 'cassert', 'cctype',
250*7c3d14c8STreehugger Robot    'cerrno', 'cfloat', 'ciso646', 'climits', 'clocale', 'cmath',
251*7c3d14c8STreehugger Robot    'complex', 'complex.h', 'csetjmp', 'csignal', 'cstdarg', 'cstddef',
252*7c3d14c8STreehugger Robot    'cstdio', 'cstdlib', 'cstring', 'ctime', 'cwchar', 'cwctype',
253*7c3d14c8STreehugger Robot    'defalloc.h', 'deque.h', 'editbuf.h', 'exception', 'fstream',
254*7c3d14c8STreehugger Robot    'fstream.h', 'hashtable.h', 'heap.h', 'indstream.h', 'iomanip',
255*7c3d14c8STreehugger Robot    'iomanip.h', 'ios', 'iosfwd', 'iostream', 'iostream.h', 'istream',
256*7c3d14c8STreehugger Robot    'istream.h', 'iterator.h', 'limits', 'map.h', 'multimap.h', 'multiset.h',
257*7c3d14c8STreehugger Robot    'numeric', 'ostream', 'ostream.h', 'parsestream.h', 'pfstream.h',
258*7c3d14c8STreehugger Robot    'PlotFile.h', 'procbuf.h', 'pthread_alloc.h', 'rope', 'rope.h',
259*7c3d14c8STreehugger Robot    'ropeimpl.h', 'SFile.h', 'slist', 'slist.h', 'stack.h', 'stdexcept',
260*7c3d14c8STreehugger Robot    'stdiostream.h', 'streambuf', 'streambuf.h', 'stream.h', 'strfile.h',
261*7c3d14c8STreehugger Robot    'string', 'strstream', 'strstream.h', 'tempbuf.h', 'tree.h', 'typeinfo',
262*7c3d14c8STreehugger Robot    'valarray',
263*7c3d14c8STreehugger Robot    ])
264*7c3d14c8STreehugger Robot
265*7c3d14c8STreehugger Robot
266*7c3d14c8STreehugger Robot# Assertion macros.  These are defined in base/logging.h and
267*7c3d14c8STreehugger Robot# testing/base/gunit.h.  Note that the _M versions need to come first
268*7c3d14c8STreehugger Robot# for substring matching to work.
269*7c3d14c8STreehugger Robot_CHECK_MACROS = [
270*7c3d14c8STreehugger Robot    'DCHECK', 'CHECK',
271*7c3d14c8STreehugger Robot    'EXPECT_TRUE_M', 'EXPECT_TRUE',
272*7c3d14c8STreehugger Robot    'ASSERT_TRUE_M', 'ASSERT_TRUE',
273*7c3d14c8STreehugger Robot    'EXPECT_FALSE_M', 'EXPECT_FALSE',
274*7c3d14c8STreehugger Robot    'ASSERT_FALSE_M', 'ASSERT_FALSE',
275*7c3d14c8STreehugger Robot    ]
276*7c3d14c8STreehugger Robot
277*7c3d14c8STreehugger Robot# Replacement macros for CHECK/DCHECK/EXPECT_TRUE/EXPECT_FALSE
278*7c3d14c8STreehugger Robot_CHECK_REPLACEMENT = dict([(m, {}) for m in _CHECK_MACROS])
279*7c3d14c8STreehugger Robot
280*7c3d14c8STreehugger Robotfor op, replacement in [('==', 'EQ'), ('!=', 'NE'),
281*7c3d14c8STreehugger Robot                        ('>=', 'GE'), ('>', 'GT'),
282*7c3d14c8STreehugger Robot                        ('<=', 'LE'), ('<', 'LT')]:
283*7c3d14c8STreehugger Robot  _CHECK_REPLACEMENT['DCHECK'][op] = 'DCHECK_%s' % replacement
284*7c3d14c8STreehugger Robot  _CHECK_REPLACEMENT['CHECK'][op] = 'CHECK_%s' % replacement
285*7c3d14c8STreehugger Robot  _CHECK_REPLACEMENT['EXPECT_TRUE'][op] = 'EXPECT_%s' % replacement
286*7c3d14c8STreehugger Robot  _CHECK_REPLACEMENT['ASSERT_TRUE'][op] = 'ASSERT_%s' % replacement
287*7c3d14c8STreehugger Robot  _CHECK_REPLACEMENT['EXPECT_TRUE_M'][op] = 'EXPECT_%s_M' % replacement
288*7c3d14c8STreehugger Robot  _CHECK_REPLACEMENT['ASSERT_TRUE_M'][op] = 'ASSERT_%s_M' % replacement
289*7c3d14c8STreehugger Robot
290*7c3d14c8STreehugger Robotfor op, inv_replacement in [('==', 'NE'), ('!=', 'EQ'),
291*7c3d14c8STreehugger Robot                            ('>=', 'LT'), ('>', 'LE'),
292*7c3d14c8STreehugger Robot                            ('<=', 'GT'), ('<', 'GE')]:
293*7c3d14c8STreehugger Robot  _CHECK_REPLACEMENT['EXPECT_FALSE'][op] = 'EXPECT_%s' % inv_replacement
294*7c3d14c8STreehugger Robot  _CHECK_REPLACEMENT['ASSERT_FALSE'][op] = 'ASSERT_%s' % inv_replacement
295*7c3d14c8STreehugger Robot  _CHECK_REPLACEMENT['EXPECT_FALSE_M'][op] = 'EXPECT_%s_M' % inv_replacement
296*7c3d14c8STreehugger Robot  _CHECK_REPLACEMENT['ASSERT_FALSE_M'][op] = 'ASSERT_%s_M' % inv_replacement
297*7c3d14c8STreehugger Robot
298*7c3d14c8STreehugger Robot# Alternative tokens and their replacements.  For full list, see section 2.5
299*7c3d14c8STreehugger Robot# Alternative tokens [lex.digraph] in the C++ standard.
300*7c3d14c8STreehugger Robot#
301*7c3d14c8STreehugger Robot# Digraphs (such as '%:') are not included here since it's a mess to
302*7c3d14c8STreehugger Robot# match those on a word boundary.
303*7c3d14c8STreehugger Robot_ALT_TOKEN_REPLACEMENT = {
304*7c3d14c8STreehugger Robot    'and': '&&',
305*7c3d14c8STreehugger Robot    'bitor': '|',
306*7c3d14c8STreehugger Robot    'or': '||',
307*7c3d14c8STreehugger Robot    'xor': '^',
308*7c3d14c8STreehugger Robot    'compl': '~',
309*7c3d14c8STreehugger Robot    'bitand': '&',
310*7c3d14c8STreehugger Robot    'and_eq': '&=',
311*7c3d14c8STreehugger Robot    'or_eq': '|=',
312*7c3d14c8STreehugger Robot    'xor_eq': '^=',
313*7c3d14c8STreehugger Robot    'not': '!',
314*7c3d14c8STreehugger Robot    'not_eq': '!='
315*7c3d14c8STreehugger Robot    }
316*7c3d14c8STreehugger Robot
317*7c3d14c8STreehugger Robot# Compile regular expression that matches all the above keywords.  The "[ =()]"
318*7c3d14c8STreehugger Robot# bit is meant to avoid matching these keywords outside of boolean expressions.
319*7c3d14c8STreehugger Robot#
320*7c3d14c8STreehugger Robot# False positives include C-style multi-line comments (http://go/nsiut )
321*7c3d14c8STreehugger Robot# and multi-line strings (http://go/beujw ), but those have always been
322*7c3d14c8STreehugger Robot# troublesome for cpplint.
323*7c3d14c8STreehugger Robot_ALT_TOKEN_REPLACEMENT_PATTERN = re.compile(
324*7c3d14c8STreehugger Robot    r'[ =()](' + ('|'.join(_ALT_TOKEN_REPLACEMENT.keys())) + r')(?=[ (]|$)')
325*7c3d14c8STreehugger Robot
326*7c3d14c8STreehugger Robot
327*7c3d14c8STreehugger Robot# These constants define types of headers for use with
328*7c3d14c8STreehugger Robot# _IncludeState.CheckNextIncludeOrder().
329*7c3d14c8STreehugger Robot_C_SYS_HEADER = 1
330*7c3d14c8STreehugger Robot_CPP_SYS_HEADER = 2
331*7c3d14c8STreehugger Robot_LIKELY_MY_HEADER = 3
332*7c3d14c8STreehugger Robot_POSSIBLE_MY_HEADER = 4
333*7c3d14c8STreehugger Robot_OTHER_HEADER = 5
334*7c3d14c8STreehugger Robot
335*7c3d14c8STreehugger Robot# These constants define the current inline assembly state
336*7c3d14c8STreehugger Robot_NO_ASM = 0       # Outside of inline assembly block
337*7c3d14c8STreehugger Robot_INSIDE_ASM = 1   # Inside inline assembly block
338*7c3d14c8STreehugger Robot_END_ASM = 2      # Last line of inline assembly block
339*7c3d14c8STreehugger Robot_BLOCK_ASM = 3    # The whole block is an inline assembly block
340*7c3d14c8STreehugger Robot
341*7c3d14c8STreehugger Robot# Match start of assembly blocks
342*7c3d14c8STreehugger Robot_MATCH_ASM = re.compile(r'^\s*(?:asm|_asm|__asm|__asm__)'
343*7c3d14c8STreehugger Robot                        r'(?:\s+(volatile|__volatile__))?'
344*7c3d14c8STreehugger Robot                        r'\s*[{(]')
345*7c3d14c8STreehugger Robot
346*7c3d14c8STreehugger Robot
347*7c3d14c8STreehugger Robot_regexp_compile_cache = {}
348*7c3d14c8STreehugger Robot
349*7c3d14c8STreehugger Robot# Finds occurrences of NOLINT or NOLINT(...).
350*7c3d14c8STreehugger Robot_RE_SUPPRESSION = re.compile(r'\bNOLINT\b(\([^)]*\))?')
351*7c3d14c8STreehugger Robot
352*7c3d14c8STreehugger Robot# {str, set(int)}: a map from error categories to sets of linenumbers
353*7c3d14c8STreehugger Robot# on which those errors are expected and should be suppressed.
354*7c3d14c8STreehugger Robot_error_suppressions = {}
355*7c3d14c8STreehugger Robot
356*7c3d14c8STreehugger Robot# The root directory used for deriving header guard CPP variable.
357*7c3d14c8STreehugger Robot# This is set by --root flag.
358*7c3d14c8STreehugger Robot_root = None
359*7c3d14c8STreehugger Robot
360*7c3d14c8STreehugger Robotdef ParseNolintSuppressions(filename, raw_line, linenum, error):
361*7c3d14c8STreehugger Robot  """Updates the global list of error-suppressions.
362*7c3d14c8STreehugger Robot
363*7c3d14c8STreehugger Robot  Parses any NOLINT comments on the current line, updating the global
364*7c3d14c8STreehugger Robot  error_suppressions store.  Reports an error if the NOLINT comment
365*7c3d14c8STreehugger Robot  was malformed.
366*7c3d14c8STreehugger Robot
367*7c3d14c8STreehugger Robot  Args:
368*7c3d14c8STreehugger Robot    filename: str, the name of the input file.
369*7c3d14c8STreehugger Robot    raw_line: str, the line of input text, with comments.
370*7c3d14c8STreehugger Robot    linenum: int, the number of the current line.
371*7c3d14c8STreehugger Robot    error: function, an error handler.
372*7c3d14c8STreehugger Robot  """
373*7c3d14c8STreehugger Robot  # FIXME(adonovan): "NOLINT(" is misparsed as NOLINT(*).
374*7c3d14c8STreehugger Robot  matched = _RE_SUPPRESSION.search(raw_line)
375*7c3d14c8STreehugger Robot  if matched:
376*7c3d14c8STreehugger Robot    category = matched.group(1)
377*7c3d14c8STreehugger Robot    if category in (None, '(*)'):  # => "suppress all"
378*7c3d14c8STreehugger Robot      _error_suppressions.setdefault(None, set()).add(linenum)
379*7c3d14c8STreehugger Robot    else:
380*7c3d14c8STreehugger Robot      if category.startswith('(') and category.endswith(')'):
381*7c3d14c8STreehugger Robot        category = category[1:-1]
382*7c3d14c8STreehugger Robot        if category in _ERROR_CATEGORIES:
383*7c3d14c8STreehugger Robot          _error_suppressions.setdefault(category, set()).add(linenum)
384*7c3d14c8STreehugger Robot        else:
385*7c3d14c8STreehugger Robot          error(filename, linenum, 'readability/nolint', 5,
386*7c3d14c8STreehugger Robot                'Unknown NOLINT error category: %s' % category)
387*7c3d14c8STreehugger Robot
388*7c3d14c8STreehugger Robot
389*7c3d14c8STreehugger Robotdef ResetNolintSuppressions():
390*7c3d14c8STreehugger Robot  "Resets the set of NOLINT suppressions to empty."
391*7c3d14c8STreehugger Robot  _error_suppressions.clear()
392*7c3d14c8STreehugger Robot
393*7c3d14c8STreehugger Robot
394*7c3d14c8STreehugger Robotdef IsErrorSuppressedByNolint(category, linenum):
395*7c3d14c8STreehugger Robot  """Returns true if the specified error category is suppressed on this line.
396*7c3d14c8STreehugger Robot
397*7c3d14c8STreehugger Robot  Consults the global error_suppressions map populated by
398*7c3d14c8STreehugger Robot  ParseNolintSuppressions/ResetNolintSuppressions.
399*7c3d14c8STreehugger Robot
400*7c3d14c8STreehugger Robot  Args:
401*7c3d14c8STreehugger Robot    category: str, the category of the error.
402*7c3d14c8STreehugger Robot    linenum: int, the current line number.
403*7c3d14c8STreehugger Robot  Returns:
404*7c3d14c8STreehugger Robot    bool, True iff the error should be suppressed due to a NOLINT comment.
405*7c3d14c8STreehugger Robot  """
406*7c3d14c8STreehugger Robot  return (linenum in _error_suppressions.get(category, set()) or
407*7c3d14c8STreehugger Robot          linenum in _error_suppressions.get(None, set()))
408*7c3d14c8STreehugger Robot
409*7c3d14c8STreehugger Robotdef Match(pattern, s):
410*7c3d14c8STreehugger Robot  """Matches the string with the pattern, caching the compiled regexp."""
411*7c3d14c8STreehugger Robot  # The regexp compilation caching is inlined in both Match and Search for
412*7c3d14c8STreehugger Robot  # performance reasons; factoring it out into a separate function turns out
413*7c3d14c8STreehugger Robot  # to be noticeably expensive.
414*7c3d14c8STreehugger Robot  if not pattern in _regexp_compile_cache:
415*7c3d14c8STreehugger Robot    _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
416*7c3d14c8STreehugger Robot  return _regexp_compile_cache[pattern].match(s)
417*7c3d14c8STreehugger Robot
418*7c3d14c8STreehugger Robot
419*7c3d14c8STreehugger Robotdef Search(pattern, s):
420*7c3d14c8STreehugger Robot  """Searches the string for the pattern, caching the compiled regexp."""
421*7c3d14c8STreehugger Robot  if not pattern in _regexp_compile_cache:
422*7c3d14c8STreehugger Robot    _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
423*7c3d14c8STreehugger Robot  return _regexp_compile_cache[pattern].search(s)
424*7c3d14c8STreehugger Robot
425*7c3d14c8STreehugger Robot
426*7c3d14c8STreehugger Robotclass _IncludeState(dict):
427*7c3d14c8STreehugger Robot  """Tracks line numbers for includes, and the order in which includes appear.
428*7c3d14c8STreehugger Robot
429*7c3d14c8STreehugger Robot  As a dict, an _IncludeState object serves as a mapping between include
430*7c3d14c8STreehugger Robot  filename and line number on which that file was included.
431*7c3d14c8STreehugger Robot
432*7c3d14c8STreehugger Robot  Call CheckNextIncludeOrder() once for each header in the file, passing
433*7c3d14c8STreehugger Robot  in the type constants defined above. Calls in an illegal order will
434*7c3d14c8STreehugger Robot  raise an _IncludeError with an appropriate error message.
435*7c3d14c8STreehugger Robot
436*7c3d14c8STreehugger Robot  """
437*7c3d14c8STreehugger Robot  # self._section will move monotonically through this set. If it ever
438*7c3d14c8STreehugger Robot  # needs to move backwards, CheckNextIncludeOrder will raise an error.
439*7c3d14c8STreehugger Robot  _INITIAL_SECTION = 0
440*7c3d14c8STreehugger Robot  _MY_H_SECTION = 1
441*7c3d14c8STreehugger Robot  _C_SECTION = 2
442*7c3d14c8STreehugger Robot  _CPP_SECTION = 3
443*7c3d14c8STreehugger Robot  _OTHER_H_SECTION = 4
444*7c3d14c8STreehugger Robot
445*7c3d14c8STreehugger Robot  _TYPE_NAMES = {
446*7c3d14c8STreehugger Robot      _C_SYS_HEADER: 'C system header',
447*7c3d14c8STreehugger Robot      _CPP_SYS_HEADER: 'C++ system header',
448*7c3d14c8STreehugger Robot      _LIKELY_MY_HEADER: 'header this file implements',
449*7c3d14c8STreehugger Robot      _POSSIBLE_MY_HEADER: 'header this file may implement',
450*7c3d14c8STreehugger Robot      _OTHER_HEADER: 'other header',
451*7c3d14c8STreehugger Robot      }
452*7c3d14c8STreehugger Robot  _SECTION_NAMES = {
453*7c3d14c8STreehugger Robot      _INITIAL_SECTION: "... nothing. (This can't be an error.)",
454*7c3d14c8STreehugger Robot      _MY_H_SECTION: 'a header this file implements',
455*7c3d14c8STreehugger Robot      _C_SECTION: 'C system header',
456*7c3d14c8STreehugger Robot      _CPP_SECTION: 'C++ system header',
457*7c3d14c8STreehugger Robot      _OTHER_H_SECTION: 'other header',
458*7c3d14c8STreehugger Robot      }
459*7c3d14c8STreehugger Robot
460*7c3d14c8STreehugger Robot  def __init__(self):
461*7c3d14c8STreehugger Robot    dict.__init__(self)
462*7c3d14c8STreehugger Robot    # The name of the current section.
463*7c3d14c8STreehugger Robot    self._section = self._INITIAL_SECTION
464*7c3d14c8STreehugger Robot    # The path of last found header.
465*7c3d14c8STreehugger Robot    self._last_header = ''
466*7c3d14c8STreehugger Robot
467*7c3d14c8STreehugger Robot  def CanonicalizeAlphabeticalOrder(self, header_path):
468*7c3d14c8STreehugger Robot    """Returns a path canonicalized for alphabetical comparison.
469*7c3d14c8STreehugger Robot
470*7c3d14c8STreehugger Robot    - replaces "-" with "_" so they both cmp the same.
471*7c3d14c8STreehugger Robot    - removes '-inl' since we don't require them to be after the main header.
472*7c3d14c8STreehugger Robot    - lowercase everything, just in case.
473*7c3d14c8STreehugger Robot
474*7c3d14c8STreehugger Robot    Args:
475*7c3d14c8STreehugger Robot      header_path: Path to be canonicalized.
476*7c3d14c8STreehugger Robot
477*7c3d14c8STreehugger Robot    Returns:
478*7c3d14c8STreehugger Robot      Canonicalized path.
479*7c3d14c8STreehugger Robot    """
480*7c3d14c8STreehugger Robot    return header_path.replace('-inl.h', '.h').replace('-', '_').lower()
481*7c3d14c8STreehugger Robot
482*7c3d14c8STreehugger Robot  def IsInAlphabeticalOrder(self, header_path):
483*7c3d14c8STreehugger Robot    """Check if a header is in alphabetical order with the previous header.
484*7c3d14c8STreehugger Robot
485*7c3d14c8STreehugger Robot    Args:
486*7c3d14c8STreehugger Robot      header_path: Header to be checked.
487*7c3d14c8STreehugger Robot
488*7c3d14c8STreehugger Robot    Returns:
489*7c3d14c8STreehugger Robot      Returns true if the header is in alphabetical order.
490*7c3d14c8STreehugger Robot    """
491*7c3d14c8STreehugger Robot    canonical_header = self.CanonicalizeAlphabeticalOrder(header_path)
492*7c3d14c8STreehugger Robot    if self._last_header > canonical_header:
493*7c3d14c8STreehugger Robot      return False
494*7c3d14c8STreehugger Robot    self._last_header = canonical_header
495*7c3d14c8STreehugger Robot    return True
496*7c3d14c8STreehugger Robot
497*7c3d14c8STreehugger Robot  def CheckNextIncludeOrder(self, header_type):
498*7c3d14c8STreehugger Robot    """Returns a non-empty error message if the next header is out of order.
499*7c3d14c8STreehugger Robot
500*7c3d14c8STreehugger Robot    This function also updates the internal state to be ready to check
501*7c3d14c8STreehugger Robot    the next include.
502*7c3d14c8STreehugger Robot
503*7c3d14c8STreehugger Robot    Args:
504*7c3d14c8STreehugger Robot      header_type: One of the _XXX_HEADER constants defined above.
505*7c3d14c8STreehugger Robot
506*7c3d14c8STreehugger Robot    Returns:
507*7c3d14c8STreehugger Robot      The empty string if the header is in the right order, or an
508*7c3d14c8STreehugger Robot      error message describing what's wrong.
509*7c3d14c8STreehugger Robot
510*7c3d14c8STreehugger Robot    """
511*7c3d14c8STreehugger Robot    error_message = ('Found %s after %s' %
512*7c3d14c8STreehugger Robot                     (self._TYPE_NAMES[header_type],
513*7c3d14c8STreehugger Robot                      self._SECTION_NAMES[self._section]))
514*7c3d14c8STreehugger Robot
515*7c3d14c8STreehugger Robot    last_section = self._section
516*7c3d14c8STreehugger Robot
517*7c3d14c8STreehugger Robot    if header_type == _C_SYS_HEADER:
518*7c3d14c8STreehugger Robot      if self._section <= self._C_SECTION:
519*7c3d14c8STreehugger Robot        self._section = self._C_SECTION
520*7c3d14c8STreehugger Robot      else:
521*7c3d14c8STreehugger Robot        self._last_header = ''
522*7c3d14c8STreehugger Robot        return error_message
523*7c3d14c8STreehugger Robot    elif header_type == _CPP_SYS_HEADER:
524*7c3d14c8STreehugger Robot      if self._section <= self._CPP_SECTION:
525*7c3d14c8STreehugger Robot        self._section = self._CPP_SECTION
526*7c3d14c8STreehugger Robot      else:
527*7c3d14c8STreehugger Robot        self._last_header = ''
528*7c3d14c8STreehugger Robot        return error_message
529*7c3d14c8STreehugger Robot    elif header_type == _LIKELY_MY_HEADER:
530*7c3d14c8STreehugger Robot      if self._section <= self._MY_H_SECTION:
531*7c3d14c8STreehugger Robot        self._section = self._MY_H_SECTION
532*7c3d14c8STreehugger Robot      else:
533*7c3d14c8STreehugger Robot        self._section = self._OTHER_H_SECTION
534*7c3d14c8STreehugger Robot    elif header_type == _POSSIBLE_MY_HEADER:
535*7c3d14c8STreehugger Robot      if self._section <= self._MY_H_SECTION:
536*7c3d14c8STreehugger Robot        self._section = self._MY_H_SECTION
537*7c3d14c8STreehugger Robot      else:
538*7c3d14c8STreehugger Robot        # This will always be the fallback because we're not sure
539*7c3d14c8STreehugger Robot        # enough that the header is associated with this file.
540*7c3d14c8STreehugger Robot        self._section = self._OTHER_H_SECTION
541*7c3d14c8STreehugger Robot    else:
542*7c3d14c8STreehugger Robot      assert header_type == _OTHER_HEADER
543*7c3d14c8STreehugger Robot      self._section = self._OTHER_H_SECTION
544*7c3d14c8STreehugger Robot
545*7c3d14c8STreehugger Robot    if last_section != self._section:
546*7c3d14c8STreehugger Robot      self._last_header = ''
547*7c3d14c8STreehugger Robot
548*7c3d14c8STreehugger Robot    return ''
549*7c3d14c8STreehugger Robot
550*7c3d14c8STreehugger Robot
551*7c3d14c8STreehugger Robotclass _CppLintState(object):
552*7c3d14c8STreehugger Robot  """Maintains module-wide state.."""
553*7c3d14c8STreehugger Robot
554*7c3d14c8STreehugger Robot  def __init__(self):
555*7c3d14c8STreehugger Robot    self.verbose_level = 1  # global setting.
556*7c3d14c8STreehugger Robot    self.error_count = 0    # global count of reported errors
557*7c3d14c8STreehugger Robot    # filters to apply when emitting error messages
558*7c3d14c8STreehugger Robot    self.filters = _DEFAULT_FILTERS[:]
559*7c3d14c8STreehugger Robot    self.counting = 'total'  # In what way are we counting errors?
560*7c3d14c8STreehugger Robot    self.errors_by_category = {}  # string to int dict storing error counts
561*7c3d14c8STreehugger Robot
562*7c3d14c8STreehugger Robot    # output format:
563*7c3d14c8STreehugger Robot    # "emacs" - format that emacs can parse (default)
564*7c3d14c8STreehugger Robot    # "vs7" - format that Microsoft Visual Studio 7 can parse
565*7c3d14c8STreehugger Robot    self.output_format = 'emacs'
566*7c3d14c8STreehugger Robot
567*7c3d14c8STreehugger Robot  def SetOutputFormat(self, output_format):
568*7c3d14c8STreehugger Robot    """Sets the output format for errors."""
569*7c3d14c8STreehugger Robot    self.output_format = output_format
570*7c3d14c8STreehugger Robot
571*7c3d14c8STreehugger Robot  def SetVerboseLevel(self, level):
572*7c3d14c8STreehugger Robot    """Sets the module's verbosity, and returns the previous setting."""
573*7c3d14c8STreehugger Robot    last_verbose_level = self.verbose_level
574*7c3d14c8STreehugger Robot    self.verbose_level = level
575*7c3d14c8STreehugger Robot    return last_verbose_level
576*7c3d14c8STreehugger Robot
577*7c3d14c8STreehugger Robot  def SetCountingStyle(self, counting_style):
578*7c3d14c8STreehugger Robot    """Sets the module's counting options."""
579*7c3d14c8STreehugger Robot    self.counting = counting_style
580*7c3d14c8STreehugger Robot
581*7c3d14c8STreehugger Robot  def SetFilters(self, filters):
582*7c3d14c8STreehugger Robot    """Sets the error-message filters.
583*7c3d14c8STreehugger Robot
584*7c3d14c8STreehugger Robot    These filters are applied when deciding whether to emit a given
585*7c3d14c8STreehugger Robot    error message.
586*7c3d14c8STreehugger Robot
587*7c3d14c8STreehugger Robot    Args:
588*7c3d14c8STreehugger Robot      filters: A string of comma-separated filters (eg "+whitespace/indent").
589*7c3d14c8STreehugger Robot               Each filter should start with + or -; else we die.
590*7c3d14c8STreehugger Robot
591*7c3d14c8STreehugger Robot    Raises:
592*7c3d14c8STreehugger Robot      ValueError: The comma-separated filters did not all start with '+' or '-'.
593*7c3d14c8STreehugger Robot                  E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter"
594*7c3d14c8STreehugger Robot    """
595*7c3d14c8STreehugger Robot    # Default filters always have less priority than the flag ones.
596*7c3d14c8STreehugger Robot    self.filters = _DEFAULT_FILTERS[:]
597*7c3d14c8STreehugger Robot    for filt in filters.split(','):
598*7c3d14c8STreehugger Robot      clean_filt = filt.strip()
599*7c3d14c8STreehugger Robot      if clean_filt:
600*7c3d14c8STreehugger Robot        self.filters.append(clean_filt)
601*7c3d14c8STreehugger Robot    for filt in self.filters:
602*7c3d14c8STreehugger Robot      if not (filt.startswith('+') or filt.startswith('-')):
603*7c3d14c8STreehugger Robot        raise ValueError('Every filter in --filters must start with + or -'
604*7c3d14c8STreehugger Robot                         ' (%s does not)' % filt)
605*7c3d14c8STreehugger Robot
606*7c3d14c8STreehugger Robot  def ResetErrorCounts(self):
607*7c3d14c8STreehugger Robot    """Sets the module's error statistic back to zero."""
608*7c3d14c8STreehugger Robot    self.error_count = 0
609*7c3d14c8STreehugger Robot    self.errors_by_category = {}
610*7c3d14c8STreehugger Robot
611*7c3d14c8STreehugger Robot  def IncrementErrorCount(self, category):
612*7c3d14c8STreehugger Robot    """Bumps the module's error statistic."""
613*7c3d14c8STreehugger Robot    self.error_count += 1
614*7c3d14c8STreehugger Robot    if self.counting in ('toplevel', 'detailed'):
615*7c3d14c8STreehugger Robot      if self.counting != 'detailed':
616*7c3d14c8STreehugger Robot        category = category.split('/')[0]
617*7c3d14c8STreehugger Robot      if category not in self.errors_by_category:
618*7c3d14c8STreehugger Robot        self.errors_by_category[category] = 0
619*7c3d14c8STreehugger Robot      self.errors_by_category[category] += 1
620*7c3d14c8STreehugger Robot
621*7c3d14c8STreehugger Robot  def PrintErrorCounts(self):
622*7c3d14c8STreehugger Robot    """Print a summary of errors by category, and the total."""
623*7c3d14c8STreehugger Robot    for category, count in self.errors_by_category.iteritems():
624*7c3d14c8STreehugger Robot      sys.stderr.write('Category \'%s\' errors found: %d\n' %
625*7c3d14c8STreehugger Robot                       (category, count))
626*7c3d14c8STreehugger Robot    sys.stderr.write('Total errors found: %d\n' % self.error_count)
627*7c3d14c8STreehugger Robot
628*7c3d14c8STreehugger Robot_cpplint_state = _CppLintState()
629*7c3d14c8STreehugger Robot
630*7c3d14c8STreehugger Robot
631*7c3d14c8STreehugger Robotdef _OutputFormat():
632*7c3d14c8STreehugger Robot  """Gets the module's output format."""
633*7c3d14c8STreehugger Robot  return _cpplint_state.output_format
634*7c3d14c8STreehugger Robot
635*7c3d14c8STreehugger Robot
636*7c3d14c8STreehugger Robotdef _SetOutputFormat(output_format):
637*7c3d14c8STreehugger Robot  """Sets the module's output format."""
638*7c3d14c8STreehugger Robot  _cpplint_state.SetOutputFormat(output_format)
639*7c3d14c8STreehugger Robot
640*7c3d14c8STreehugger Robot
641*7c3d14c8STreehugger Robotdef _VerboseLevel():
642*7c3d14c8STreehugger Robot  """Returns the module's verbosity setting."""
643*7c3d14c8STreehugger Robot  return _cpplint_state.verbose_level
644*7c3d14c8STreehugger Robot
645*7c3d14c8STreehugger Robot
646*7c3d14c8STreehugger Robotdef _SetVerboseLevel(level):
647*7c3d14c8STreehugger Robot  """Sets the module's verbosity, and returns the previous setting."""
648*7c3d14c8STreehugger Robot  return _cpplint_state.SetVerboseLevel(level)
649*7c3d14c8STreehugger Robot
650*7c3d14c8STreehugger Robot
651*7c3d14c8STreehugger Robotdef _SetCountingStyle(level):
652*7c3d14c8STreehugger Robot  """Sets the module's counting options."""
653*7c3d14c8STreehugger Robot  _cpplint_state.SetCountingStyle(level)
654*7c3d14c8STreehugger Robot
655*7c3d14c8STreehugger Robot
656*7c3d14c8STreehugger Robotdef _Filters():
657*7c3d14c8STreehugger Robot  """Returns the module's list of output filters, as a list."""
658*7c3d14c8STreehugger Robot  return _cpplint_state.filters
659*7c3d14c8STreehugger Robot
660*7c3d14c8STreehugger Robot
661*7c3d14c8STreehugger Robotdef _SetFilters(filters):
662*7c3d14c8STreehugger Robot  """Sets the module's error-message filters.
663*7c3d14c8STreehugger Robot
664*7c3d14c8STreehugger Robot  These filters are applied when deciding whether to emit a given
665*7c3d14c8STreehugger Robot  error message.
666*7c3d14c8STreehugger Robot
667*7c3d14c8STreehugger Robot  Args:
668*7c3d14c8STreehugger Robot    filters: A string of comma-separated filters (eg "whitespace/indent").
669*7c3d14c8STreehugger Robot             Each filter should start with + or -; else we die.
670*7c3d14c8STreehugger Robot  """
671*7c3d14c8STreehugger Robot  _cpplint_state.SetFilters(filters)
672*7c3d14c8STreehugger Robot
673*7c3d14c8STreehugger Robot
674*7c3d14c8STreehugger Robotclass _FunctionState(object):
675*7c3d14c8STreehugger Robot  """Tracks current function name and the number of lines in its body."""
676*7c3d14c8STreehugger Robot
677*7c3d14c8STreehugger Robot  _NORMAL_TRIGGER = 250  # for --v=0, 500 for --v=1, etc.
678*7c3d14c8STreehugger Robot  _TEST_TRIGGER = 400    # about 50% more than _NORMAL_TRIGGER.
679*7c3d14c8STreehugger Robot
680*7c3d14c8STreehugger Robot  def __init__(self):
681*7c3d14c8STreehugger Robot    self.in_a_function = False
682*7c3d14c8STreehugger Robot    self.lines_in_function = 0
683*7c3d14c8STreehugger Robot    self.current_function = ''
684*7c3d14c8STreehugger Robot
685*7c3d14c8STreehugger Robot  def Begin(self, function_name):
686*7c3d14c8STreehugger Robot    """Start analyzing function body.
687*7c3d14c8STreehugger Robot
688*7c3d14c8STreehugger Robot    Args:
689*7c3d14c8STreehugger Robot      function_name: The name of the function being tracked.
690*7c3d14c8STreehugger Robot    """
691*7c3d14c8STreehugger Robot    self.in_a_function = True
692*7c3d14c8STreehugger Robot    self.lines_in_function = 0
693*7c3d14c8STreehugger Robot    self.current_function = function_name
694*7c3d14c8STreehugger Robot
695*7c3d14c8STreehugger Robot  def Count(self):
696*7c3d14c8STreehugger Robot    """Count line in current function body."""
697*7c3d14c8STreehugger Robot    if self.in_a_function:
698*7c3d14c8STreehugger Robot      self.lines_in_function += 1
699*7c3d14c8STreehugger Robot
700*7c3d14c8STreehugger Robot  def Check(self, error, filename, linenum):
701*7c3d14c8STreehugger Robot    """Report if too many lines in function body.
702*7c3d14c8STreehugger Robot
703*7c3d14c8STreehugger Robot    Args:
704*7c3d14c8STreehugger Robot      error: The function to call with any errors found.
705*7c3d14c8STreehugger Robot      filename: The name of the current file.
706*7c3d14c8STreehugger Robot      linenum: The number of the line to check.
707*7c3d14c8STreehugger Robot    """
708*7c3d14c8STreehugger Robot    if Match(r'T(EST|est)', self.current_function):
709*7c3d14c8STreehugger Robot      base_trigger = self._TEST_TRIGGER
710*7c3d14c8STreehugger Robot    else:
711*7c3d14c8STreehugger Robot      base_trigger = self._NORMAL_TRIGGER
712*7c3d14c8STreehugger Robot    trigger = base_trigger * 2**_VerboseLevel()
713*7c3d14c8STreehugger Robot
714*7c3d14c8STreehugger Robot    if self.lines_in_function > trigger:
715*7c3d14c8STreehugger Robot      error_level = int(math.log(self.lines_in_function / base_trigger, 2))
716*7c3d14c8STreehugger Robot      # 50 => 0, 100 => 1, 200 => 2, 400 => 3, 800 => 4, 1600 => 5, ...
717*7c3d14c8STreehugger Robot      if error_level > 5:
718*7c3d14c8STreehugger Robot        error_level = 5
719*7c3d14c8STreehugger Robot      error(filename, linenum, 'readability/fn_size', error_level,
720*7c3d14c8STreehugger Robot            'Small and focused functions are preferred:'
721*7c3d14c8STreehugger Robot            ' %s has %d non-comment lines'
722*7c3d14c8STreehugger Robot            ' (error triggered by exceeding %d lines).'  % (
723*7c3d14c8STreehugger Robot                self.current_function, self.lines_in_function, trigger))
724*7c3d14c8STreehugger Robot
725*7c3d14c8STreehugger Robot  def End(self):
726*7c3d14c8STreehugger Robot    """Stop analyzing function body."""
727*7c3d14c8STreehugger Robot    self.in_a_function = False
728*7c3d14c8STreehugger Robot
729*7c3d14c8STreehugger Robot
730*7c3d14c8STreehugger Robotclass _IncludeError(Exception):
731*7c3d14c8STreehugger Robot  """Indicates a problem with the include order in a file."""
732*7c3d14c8STreehugger Robot  pass
733*7c3d14c8STreehugger Robot
734*7c3d14c8STreehugger Robot
735*7c3d14c8STreehugger Robotclass FileInfo:
736*7c3d14c8STreehugger Robot  """Provides utility functions for filenames.
737*7c3d14c8STreehugger Robot
738*7c3d14c8STreehugger Robot  FileInfo provides easy access to the components of a file's path
739*7c3d14c8STreehugger Robot  relative to the project root.
740*7c3d14c8STreehugger Robot  """
741*7c3d14c8STreehugger Robot
742*7c3d14c8STreehugger Robot  def __init__(self, filename):
743*7c3d14c8STreehugger Robot    self._filename = filename
744*7c3d14c8STreehugger Robot
745*7c3d14c8STreehugger Robot  def FullName(self):
746*7c3d14c8STreehugger Robot    """Make Windows paths like Unix."""
747*7c3d14c8STreehugger Robot    return os.path.abspath(self._filename).replace('\\', '/')
748*7c3d14c8STreehugger Robot
749*7c3d14c8STreehugger Robot  def RepositoryName(self):
750*7c3d14c8STreehugger Robot    """FullName after removing the local path to the repository.
751*7c3d14c8STreehugger Robot
752*7c3d14c8STreehugger Robot    If we have a real absolute path name here we can try to do something smart:
753*7c3d14c8STreehugger Robot    detecting the root of the checkout and truncating /path/to/checkout from
754*7c3d14c8STreehugger Robot    the name so that we get header guards that don't include things like
755*7c3d14c8STreehugger Robot    "C:\Documents and Settings\..." or "/home/username/..." in them and thus
756*7c3d14c8STreehugger Robot    people on different computers who have checked the source out to different
757*7c3d14c8STreehugger Robot    locations won't see bogus errors.
758*7c3d14c8STreehugger Robot    """
759*7c3d14c8STreehugger Robot    fullname = self.FullName()
760*7c3d14c8STreehugger Robot
761*7c3d14c8STreehugger Robot    if os.path.exists(fullname):
762*7c3d14c8STreehugger Robot      project_dir = os.path.dirname(fullname)
763*7c3d14c8STreehugger Robot
764*7c3d14c8STreehugger Robot      if os.path.exists(os.path.join(project_dir, ".svn")):
765*7c3d14c8STreehugger Robot        # If there's a .svn file in the current directory, we recursively look
766*7c3d14c8STreehugger Robot        # up the directory tree for the top of the SVN checkout
767*7c3d14c8STreehugger Robot        root_dir = project_dir
768*7c3d14c8STreehugger Robot        one_up_dir = os.path.dirname(root_dir)
769*7c3d14c8STreehugger Robot        while os.path.exists(os.path.join(one_up_dir, ".svn")):
770*7c3d14c8STreehugger Robot          root_dir = os.path.dirname(root_dir)
771*7c3d14c8STreehugger Robot          one_up_dir = os.path.dirname(one_up_dir)
772*7c3d14c8STreehugger Robot
773*7c3d14c8STreehugger Robot        prefix = os.path.commonprefix([root_dir, project_dir])
774*7c3d14c8STreehugger Robot        return fullname[len(prefix) + 1:]
775*7c3d14c8STreehugger Robot
776*7c3d14c8STreehugger Robot      # Not SVN <= 1.6? Try to find a git, hg, or svn top level directory by
777*7c3d14c8STreehugger Robot      # searching up from the current path.
778*7c3d14c8STreehugger Robot      root_dir = os.path.dirname(fullname)
779*7c3d14c8STreehugger Robot      while (root_dir != os.path.dirname(root_dir) and
780*7c3d14c8STreehugger Robot             not os.path.exists(os.path.join(root_dir, ".git")) and
781*7c3d14c8STreehugger Robot             not os.path.exists(os.path.join(root_dir, ".hg")) and
782*7c3d14c8STreehugger Robot             not os.path.exists(os.path.join(root_dir, ".svn"))):
783*7c3d14c8STreehugger Robot        root_dir = os.path.dirname(root_dir)
784*7c3d14c8STreehugger Robot
785*7c3d14c8STreehugger Robot      if (os.path.exists(os.path.join(root_dir, ".git")) or
786*7c3d14c8STreehugger Robot          os.path.exists(os.path.join(root_dir, ".hg")) or
787*7c3d14c8STreehugger Robot          os.path.exists(os.path.join(root_dir, ".svn"))):
788*7c3d14c8STreehugger Robot        prefix = os.path.commonprefix([root_dir, project_dir])
789*7c3d14c8STreehugger Robot        return fullname[len(prefix) + 1:]
790*7c3d14c8STreehugger Robot
791*7c3d14c8STreehugger Robot    # Don't know what to do; header guard warnings may be wrong...
792*7c3d14c8STreehugger Robot    return fullname
793*7c3d14c8STreehugger Robot
794*7c3d14c8STreehugger Robot  def Split(self):
795*7c3d14c8STreehugger Robot    """Splits the file into the directory, basename, and extension.
796*7c3d14c8STreehugger Robot
797*7c3d14c8STreehugger Robot    For 'chrome/browser/browser.cc', Split() would
798*7c3d14c8STreehugger Robot    return ('chrome/browser', 'browser', '.cc')
799*7c3d14c8STreehugger Robot
800*7c3d14c8STreehugger Robot    Returns:
801*7c3d14c8STreehugger Robot      A tuple of (directory, basename, extension).
802*7c3d14c8STreehugger Robot    """
803*7c3d14c8STreehugger Robot
804*7c3d14c8STreehugger Robot    googlename = self.RepositoryName()
805*7c3d14c8STreehugger Robot    project, rest = os.path.split(googlename)
806*7c3d14c8STreehugger Robot    return (project,) + os.path.splitext(rest)
807*7c3d14c8STreehugger Robot
808*7c3d14c8STreehugger Robot  def BaseName(self):
809*7c3d14c8STreehugger Robot    """File base name - text after the final slash, before the final period."""
810*7c3d14c8STreehugger Robot    return self.Split()[1]
811*7c3d14c8STreehugger Robot
812*7c3d14c8STreehugger Robot  def Extension(self):
813*7c3d14c8STreehugger Robot    """File extension - text following the final period."""
814*7c3d14c8STreehugger Robot    return self.Split()[2]
815*7c3d14c8STreehugger Robot
816*7c3d14c8STreehugger Robot  def NoExtension(self):
817*7c3d14c8STreehugger Robot    """File has no source file extension."""
818*7c3d14c8STreehugger Robot    return '/'.join(self.Split()[0:2])
819*7c3d14c8STreehugger Robot
820*7c3d14c8STreehugger Robot  def IsSource(self):
821*7c3d14c8STreehugger Robot    """File has a source file extension."""
822*7c3d14c8STreehugger Robot    return self.Extension()[1:] in ('c', 'cc', 'cpp', 'cxx')
823*7c3d14c8STreehugger Robot
824*7c3d14c8STreehugger Robot
825*7c3d14c8STreehugger Robotdef _ShouldPrintError(category, confidence, linenum):
826*7c3d14c8STreehugger Robot  """If confidence >= verbose, category passes filter and is not suppressed."""
827*7c3d14c8STreehugger Robot
828*7c3d14c8STreehugger Robot  # There are three ways we might decide not to print an error message:
829*7c3d14c8STreehugger Robot  # a "NOLINT(category)" comment appears in the source,
830*7c3d14c8STreehugger Robot  # the verbosity level isn't high enough, or the filters filter it out.
831*7c3d14c8STreehugger Robot  if IsErrorSuppressedByNolint(category, linenum):
832*7c3d14c8STreehugger Robot    return False
833*7c3d14c8STreehugger Robot  if confidence < _cpplint_state.verbose_level:
834*7c3d14c8STreehugger Robot    return False
835*7c3d14c8STreehugger Robot
836*7c3d14c8STreehugger Robot  is_filtered = False
837*7c3d14c8STreehugger Robot  for one_filter in _Filters():
838*7c3d14c8STreehugger Robot    if one_filter.startswith('-'):
839*7c3d14c8STreehugger Robot      if category.startswith(one_filter[1:]):
840*7c3d14c8STreehugger Robot        is_filtered = True
841*7c3d14c8STreehugger Robot    elif one_filter.startswith('+'):
842*7c3d14c8STreehugger Robot      if category.startswith(one_filter[1:]):
843*7c3d14c8STreehugger Robot        is_filtered = False
844*7c3d14c8STreehugger Robot    else:
845*7c3d14c8STreehugger Robot      assert False  # should have been checked for in SetFilter.
846*7c3d14c8STreehugger Robot  if is_filtered:
847*7c3d14c8STreehugger Robot    return False
848*7c3d14c8STreehugger Robot
849*7c3d14c8STreehugger Robot  return True
850*7c3d14c8STreehugger Robot
851*7c3d14c8STreehugger Robot
852*7c3d14c8STreehugger Robotdef Error(filename, linenum, category, confidence, message):
853*7c3d14c8STreehugger Robot  """Logs the fact we've found a lint error.
854*7c3d14c8STreehugger Robot
855*7c3d14c8STreehugger Robot  We log where the error was found, and also our confidence in the error,
856*7c3d14c8STreehugger Robot  that is, how certain we are this is a legitimate style regression, and
857*7c3d14c8STreehugger Robot  not a misidentification or a use that's sometimes justified.
858*7c3d14c8STreehugger Robot
859*7c3d14c8STreehugger Robot  False positives can be suppressed by the use of
860*7c3d14c8STreehugger Robot  "cpplint(category)"  comments on the offending line.  These are
861*7c3d14c8STreehugger Robot  parsed into _error_suppressions.
862*7c3d14c8STreehugger Robot
863*7c3d14c8STreehugger Robot  Args:
864*7c3d14c8STreehugger Robot    filename: The name of the file containing the error.
865*7c3d14c8STreehugger Robot    linenum: The number of the line containing the error.
866*7c3d14c8STreehugger Robot    category: A string used to describe the "category" this bug
867*7c3d14c8STreehugger Robot      falls under: "whitespace", say, or "runtime".  Categories
868*7c3d14c8STreehugger Robot      may have a hierarchy separated by slashes: "whitespace/indent".
869*7c3d14c8STreehugger Robot    confidence: A number from 1-5 representing a confidence score for
870*7c3d14c8STreehugger Robot      the error, with 5 meaning that we are certain of the problem,
871*7c3d14c8STreehugger Robot      and 1 meaning that it could be a legitimate construct.
872*7c3d14c8STreehugger Robot    message: The error message.
873*7c3d14c8STreehugger Robot  """
874*7c3d14c8STreehugger Robot  if _ShouldPrintError(category, confidence, linenum):
875*7c3d14c8STreehugger Robot    _cpplint_state.IncrementErrorCount(category)
876*7c3d14c8STreehugger Robot    if _cpplint_state.output_format == 'vs7':
877*7c3d14c8STreehugger Robot      sys.stderr.write('%s(%s):  %s  [%s] [%d]\n' % (
878*7c3d14c8STreehugger Robot          filename, linenum, message, category, confidence))
879*7c3d14c8STreehugger Robot    elif _cpplint_state.output_format == 'eclipse':
880*7c3d14c8STreehugger Robot      sys.stderr.write('%s:%s: warning: %s  [%s] [%d]\n' % (
881*7c3d14c8STreehugger Robot          filename, linenum, message, category, confidence))
882*7c3d14c8STreehugger Robot    else:
883*7c3d14c8STreehugger Robot      sys.stderr.write('%s:%s:  %s  [%s] [%d]\n' % (
884*7c3d14c8STreehugger Robot          filename, linenum, message, category, confidence))
885*7c3d14c8STreehugger Robot
886*7c3d14c8STreehugger Robot
887*7c3d14c8STreehugger Robot# Matches standard C++ escape esequences per 2.13.2.3 of the C++ standard.
888*7c3d14c8STreehugger Robot_RE_PATTERN_CLEANSE_LINE_ESCAPES = re.compile(
889*7c3d14c8STreehugger Robot    r'\\([abfnrtv?"\\\']|\d+|x[0-9a-fA-F]+)')
890*7c3d14c8STreehugger Robot# Matches strings.  Escape codes should already be removed by ESCAPES.
891*7c3d14c8STreehugger Robot_RE_PATTERN_CLEANSE_LINE_DOUBLE_QUOTES = re.compile(r'"[^"]*"')
892*7c3d14c8STreehugger Robot# Matches characters.  Escape codes should already be removed by ESCAPES.
893*7c3d14c8STreehugger Robot_RE_PATTERN_CLEANSE_LINE_SINGLE_QUOTES = re.compile(r"'.'")
894*7c3d14c8STreehugger Robot# Matches multi-line C++ comments.
895*7c3d14c8STreehugger Robot# This RE is a little bit more complicated than one might expect, because we
896*7c3d14c8STreehugger Robot# have to take care of space removals tools so we can handle comments inside
897*7c3d14c8STreehugger Robot# statements better.
898*7c3d14c8STreehugger Robot# The current rule is: We only clear spaces from both sides when we're at the
899*7c3d14c8STreehugger Robot# end of the line. Otherwise, we try to remove spaces from the right side,
900*7c3d14c8STreehugger Robot# if this doesn't work we try on left side but only if there's a non-character
901*7c3d14c8STreehugger Robot# on the right.
902*7c3d14c8STreehugger Robot_RE_PATTERN_CLEANSE_LINE_C_COMMENTS = re.compile(
903*7c3d14c8STreehugger Robot    r"""(\s*/\*.*\*/\s*$|
904*7c3d14c8STreehugger Robot            /\*.*\*/\s+|
905*7c3d14c8STreehugger Robot         \s+/\*.*\*/(?=\W)|
906*7c3d14c8STreehugger Robot            /\*.*\*/)""", re.VERBOSE)
907*7c3d14c8STreehugger Robot
908*7c3d14c8STreehugger Robot
909*7c3d14c8STreehugger Robotdef IsCppString(line):
910*7c3d14c8STreehugger Robot  """Does line terminate so, that the next symbol is in string constant.
911*7c3d14c8STreehugger Robot
912*7c3d14c8STreehugger Robot  This function does not consider single-line nor multi-line comments.
913*7c3d14c8STreehugger Robot
914*7c3d14c8STreehugger Robot  Args:
915*7c3d14c8STreehugger Robot    line: is a partial line of code starting from the 0..n.
916*7c3d14c8STreehugger Robot
917*7c3d14c8STreehugger Robot  Returns:
918*7c3d14c8STreehugger Robot    True, if next character appended to 'line' is inside a
919*7c3d14c8STreehugger Robot    string constant.
920*7c3d14c8STreehugger Robot  """
921*7c3d14c8STreehugger Robot
922*7c3d14c8STreehugger Robot  line = line.replace(r'\\', 'XX')  # after this, \\" does not match to \"
923*7c3d14c8STreehugger Robot  return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1
924*7c3d14c8STreehugger Robot
925*7c3d14c8STreehugger Robot
926*7c3d14c8STreehugger Robotdef FindNextMultiLineCommentStart(lines, lineix):
927*7c3d14c8STreehugger Robot  """Find the beginning marker for a multiline comment."""
928*7c3d14c8STreehugger Robot  while lineix < len(lines):
929*7c3d14c8STreehugger Robot    if lines[lineix].strip().startswith('/*'):
930*7c3d14c8STreehugger Robot      # Only return this marker if the comment goes beyond this line
931*7c3d14c8STreehugger Robot      if lines[lineix].strip().find('*/', 2) < 0:
932*7c3d14c8STreehugger Robot        return lineix
933*7c3d14c8STreehugger Robot    lineix += 1
934*7c3d14c8STreehugger Robot  return len(lines)
935*7c3d14c8STreehugger Robot
936*7c3d14c8STreehugger Robot
937*7c3d14c8STreehugger Robotdef FindNextMultiLineCommentEnd(lines, lineix):
938*7c3d14c8STreehugger Robot  """We are inside a comment, find the end marker."""
939*7c3d14c8STreehugger Robot  while lineix < len(lines):
940*7c3d14c8STreehugger Robot    if lines[lineix].strip().endswith('*/'):
941*7c3d14c8STreehugger Robot      return lineix
942*7c3d14c8STreehugger Robot    lineix += 1
943*7c3d14c8STreehugger Robot  return len(lines)
944*7c3d14c8STreehugger Robot
945*7c3d14c8STreehugger Robot
946*7c3d14c8STreehugger Robotdef RemoveMultiLineCommentsFromRange(lines, begin, end):
947*7c3d14c8STreehugger Robot  """Clears a range of lines for multi-line comments."""
948*7c3d14c8STreehugger Robot  # Having // dummy comments makes the lines non-empty, so we will not get
949*7c3d14c8STreehugger Robot  # unnecessary blank line warnings later in the code.
950*7c3d14c8STreehugger Robot  for i in range(begin, end):
951*7c3d14c8STreehugger Robot    lines[i] = '// dummy'
952*7c3d14c8STreehugger Robot
953*7c3d14c8STreehugger Robot
954*7c3d14c8STreehugger Robotdef RemoveMultiLineComments(filename, lines, error):
955*7c3d14c8STreehugger Robot  """Removes multiline (c-style) comments from lines."""
956*7c3d14c8STreehugger Robot  lineix = 0
957*7c3d14c8STreehugger Robot  while lineix < len(lines):
958*7c3d14c8STreehugger Robot    lineix_begin = FindNextMultiLineCommentStart(lines, lineix)
959*7c3d14c8STreehugger Robot    if lineix_begin >= len(lines):
960*7c3d14c8STreehugger Robot      return
961*7c3d14c8STreehugger Robot    lineix_end = FindNextMultiLineCommentEnd(lines, lineix_begin)
962*7c3d14c8STreehugger Robot    if lineix_end >= len(lines):
963*7c3d14c8STreehugger Robot      error(filename, lineix_begin + 1, 'readability/multiline_comment', 5,
964*7c3d14c8STreehugger Robot            'Could not find end of multi-line comment')
965*7c3d14c8STreehugger Robot      return
966*7c3d14c8STreehugger Robot    RemoveMultiLineCommentsFromRange(lines, lineix_begin, lineix_end + 1)
967*7c3d14c8STreehugger Robot    lineix = lineix_end + 1
968*7c3d14c8STreehugger Robot
969*7c3d14c8STreehugger Robot
970*7c3d14c8STreehugger Robotdef CleanseComments(line):
971*7c3d14c8STreehugger Robot  """Removes //-comments and single-line C-style /* */ comments.
972*7c3d14c8STreehugger Robot
973*7c3d14c8STreehugger Robot  Args:
974*7c3d14c8STreehugger Robot    line: A line of C++ source.
975*7c3d14c8STreehugger Robot
976*7c3d14c8STreehugger Robot  Returns:
977*7c3d14c8STreehugger Robot    The line with single-line comments removed.
978*7c3d14c8STreehugger Robot  """
979*7c3d14c8STreehugger Robot  commentpos = line.find('//')
980*7c3d14c8STreehugger Robot  if commentpos != -1 and not IsCppString(line[:commentpos]):
981*7c3d14c8STreehugger Robot    line = line[:commentpos].rstrip()
982*7c3d14c8STreehugger Robot  # get rid of /* ... */
983*7c3d14c8STreehugger Robot  return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line)
984*7c3d14c8STreehugger Robot
985*7c3d14c8STreehugger Robot
986*7c3d14c8STreehugger Robotclass CleansedLines(object):
987*7c3d14c8STreehugger Robot  """Holds 3 copies of all lines with different preprocessing applied to them.
988*7c3d14c8STreehugger Robot
989*7c3d14c8STreehugger Robot  1) elided member contains lines without strings and comments,
990*7c3d14c8STreehugger Robot  2) lines member contains lines without comments, and
991*7c3d14c8STreehugger Robot  3) raw_lines member contains all the lines without processing.
992*7c3d14c8STreehugger Robot  All these three members are of <type 'list'>, and of the same length.
993*7c3d14c8STreehugger Robot  """
994*7c3d14c8STreehugger Robot
995*7c3d14c8STreehugger Robot  def __init__(self, lines):
996*7c3d14c8STreehugger Robot    self.elided = []
997*7c3d14c8STreehugger Robot    self.lines = []
998*7c3d14c8STreehugger Robot    self.raw_lines = lines
999*7c3d14c8STreehugger Robot    self.num_lines = len(lines)
1000*7c3d14c8STreehugger Robot    for linenum in range(len(lines)):
1001*7c3d14c8STreehugger Robot      self.lines.append(CleanseComments(lines[linenum]))
1002*7c3d14c8STreehugger Robot      elided = self._CollapseStrings(lines[linenum])
1003*7c3d14c8STreehugger Robot      self.elided.append(CleanseComments(elided))
1004*7c3d14c8STreehugger Robot
1005*7c3d14c8STreehugger Robot  def NumLines(self):
1006*7c3d14c8STreehugger Robot    """Returns the number of lines represented."""
1007*7c3d14c8STreehugger Robot    return self.num_lines
1008*7c3d14c8STreehugger Robot
1009*7c3d14c8STreehugger Robot  @staticmethod
1010*7c3d14c8STreehugger Robot  def _CollapseStrings(elided):
1011*7c3d14c8STreehugger Robot    """Collapses strings and chars on a line to simple "" or '' blocks.
1012*7c3d14c8STreehugger Robot
1013*7c3d14c8STreehugger Robot    We nix strings first so we're not fooled by text like '"http://"'
1014*7c3d14c8STreehugger Robot
1015*7c3d14c8STreehugger Robot    Args:
1016*7c3d14c8STreehugger Robot      elided: The line being processed.
1017*7c3d14c8STreehugger Robot
1018*7c3d14c8STreehugger Robot    Returns:
1019*7c3d14c8STreehugger Robot      The line with collapsed strings.
1020*7c3d14c8STreehugger Robot    """
1021*7c3d14c8STreehugger Robot    if not _RE_PATTERN_INCLUDE.match(elided):
1022*7c3d14c8STreehugger Robot      # Remove escaped characters first to make quote/single quote collapsing
1023*7c3d14c8STreehugger Robot      # basic.  Things that look like escaped characters shouldn't occur
1024*7c3d14c8STreehugger Robot      # outside of strings and chars.
1025*7c3d14c8STreehugger Robot      elided = _RE_PATTERN_CLEANSE_LINE_ESCAPES.sub('', elided)
1026*7c3d14c8STreehugger Robot      elided = _RE_PATTERN_CLEANSE_LINE_SINGLE_QUOTES.sub("''", elided)
1027*7c3d14c8STreehugger Robot      elided = _RE_PATTERN_CLEANSE_LINE_DOUBLE_QUOTES.sub('""', elided)
1028*7c3d14c8STreehugger Robot    return elided
1029*7c3d14c8STreehugger Robot
1030*7c3d14c8STreehugger Robot
1031*7c3d14c8STreehugger Robotdef FindEndOfExpressionInLine(line, startpos, depth, startchar, endchar):
1032*7c3d14c8STreehugger Robot  """Find the position just after the matching endchar.
1033*7c3d14c8STreehugger Robot
1034*7c3d14c8STreehugger Robot  Args:
1035*7c3d14c8STreehugger Robot    line: a CleansedLines line.
1036*7c3d14c8STreehugger Robot    startpos: start searching at this position.
1037*7c3d14c8STreehugger Robot    depth: nesting level at startpos.
1038*7c3d14c8STreehugger Robot    startchar: expression opening character.
1039*7c3d14c8STreehugger Robot    endchar: expression closing character.
1040*7c3d14c8STreehugger Robot
1041*7c3d14c8STreehugger Robot  Returns:
1042*7c3d14c8STreehugger Robot    Index just after endchar.
1043*7c3d14c8STreehugger Robot  """
1044*7c3d14c8STreehugger Robot  for i in xrange(startpos, len(line)):
1045*7c3d14c8STreehugger Robot    if line[i] == startchar:
1046*7c3d14c8STreehugger Robot      depth += 1
1047*7c3d14c8STreehugger Robot    elif line[i] == endchar:
1048*7c3d14c8STreehugger Robot      depth -= 1
1049*7c3d14c8STreehugger Robot      if depth == 0:
1050*7c3d14c8STreehugger Robot        return i + 1
1051*7c3d14c8STreehugger Robot  return -1
1052*7c3d14c8STreehugger Robot
1053*7c3d14c8STreehugger Robot
1054*7c3d14c8STreehugger Robotdef CloseExpression(clean_lines, linenum, pos):
1055*7c3d14c8STreehugger Robot  """If input points to ( or { or [, finds the position that closes it.
1056*7c3d14c8STreehugger Robot
1057*7c3d14c8STreehugger Robot  If lines[linenum][pos] points to a '(' or '{' or '[', finds the
1058*7c3d14c8STreehugger Robot  linenum/pos that correspond to the closing of the expression.
1059*7c3d14c8STreehugger Robot
1060*7c3d14c8STreehugger Robot  Args:
1061*7c3d14c8STreehugger Robot    clean_lines: A CleansedLines instance containing the file.
1062*7c3d14c8STreehugger Robot    linenum: The number of the line to check.
1063*7c3d14c8STreehugger Robot    pos: A position on the line.
1064*7c3d14c8STreehugger Robot
1065*7c3d14c8STreehugger Robot  Returns:
1066*7c3d14c8STreehugger Robot    A tuple (line, linenum, pos) pointer *past* the closing brace, or
1067*7c3d14c8STreehugger Robot    (line, len(lines), -1) if we never find a close.  Note we ignore
1068*7c3d14c8STreehugger Robot    strings and comments when matching; and the line we return is the
1069*7c3d14c8STreehugger Robot    'cleansed' line at linenum.
1070*7c3d14c8STreehugger Robot  """
1071*7c3d14c8STreehugger Robot
1072*7c3d14c8STreehugger Robot  line = clean_lines.elided[linenum]
1073*7c3d14c8STreehugger Robot  startchar = line[pos]
1074*7c3d14c8STreehugger Robot  if startchar not in '({[':
1075*7c3d14c8STreehugger Robot    return (line, clean_lines.NumLines(), -1)
1076*7c3d14c8STreehugger Robot  if startchar == '(': endchar = ')'
1077*7c3d14c8STreehugger Robot  if startchar == '[': endchar = ']'
1078*7c3d14c8STreehugger Robot  if startchar == '{': endchar = '}'
1079*7c3d14c8STreehugger Robot
1080*7c3d14c8STreehugger Robot  # Check first line
1081*7c3d14c8STreehugger Robot  end_pos = FindEndOfExpressionInLine(line, pos, 0, startchar, endchar)
1082*7c3d14c8STreehugger Robot  if end_pos > -1:
1083*7c3d14c8STreehugger Robot    return (line, linenum, end_pos)
1084*7c3d14c8STreehugger Robot  tail = line[pos:]
1085*7c3d14c8STreehugger Robot  num_open = tail.count(startchar) - tail.count(endchar)
1086*7c3d14c8STreehugger Robot  while linenum < clean_lines.NumLines() - 1:
1087*7c3d14c8STreehugger Robot    linenum += 1
1088*7c3d14c8STreehugger Robot    line = clean_lines.elided[linenum]
1089*7c3d14c8STreehugger Robot    delta = line.count(startchar) - line.count(endchar)
1090*7c3d14c8STreehugger Robot    if num_open + delta <= 0:
1091*7c3d14c8STreehugger Robot      return (line, linenum,
1092*7c3d14c8STreehugger Robot              FindEndOfExpressionInLine(line, 0, num_open, startchar, endchar))
1093*7c3d14c8STreehugger Robot    num_open += delta
1094*7c3d14c8STreehugger Robot
1095*7c3d14c8STreehugger Robot  # Did not find endchar before end of file, give up
1096*7c3d14c8STreehugger Robot  return (line, clean_lines.NumLines(), -1)
1097*7c3d14c8STreehugger Robot
1098*7c3d14c8STreehugger Robotdef CheckForCopyright(filename, lines, error):
1099*7c3d14c8STreehugger Robot  """Logs an error if no Copyright message appears at the top of the file."""
1100*7c3d14c8STreehugger Robot
1101*7c3d14c8STreehugger Robot  # We'll say it should occur by line 10. Don't forget there's a
1102*7c3d14c8STreehugger Robot  # dummy line at the front.
1103*7c3d14c8STreehugger Robot  for line in xrange(1, min(len(lines), 11)):
1104*7c3d14c8STreehugger Robot    if re.search(r'Copyright', lines[line], re.I): break
1105*7c3d14c8STreehugger Robot  else:                       # means no copyright line was found
1106*7c3d14c8STreehugger Robot    error(filename, 0, 'legal/copyright', 5,
1107*7c3d14c8STreehugger Robot          'No copyright message found.  '
1108*7c3d14c8STreehugger Robot          'You should have a line: "Copyright [year] <Copyright Owner>"')
1109*7c3d14c8STreehugger Robot
1110*7c3d14c8STreehugger Robot
1111*7c3d14c8STreehugger Robotdef GetHeaderGuardCPPVariable(filename):
1112*7c3d14c8STreehugger Robot  """Returns the CPP variable that should be used as a header guard.
1113*7c3d14c8STreehugger Robot
1114*7c3d14c8STreehugger Robot  Args:
1115*7c3d14c8STreehugger Robot    filename: The name of a C++ header file.
1116*7c3d14c8STreehugger Robot
1117*7c3d14c8STreehugger Robot  Returns:
1118*7c3d14c8STreehugger Robot    The CPP variable that should be used as a header guard in the
1119*7c3d14c8STreehugger Robot    named file.
1120*7c3d14c8STreehugger Robot
1121*7c3d14c8STreehugger Robot  """
1122*7c3d14c8STreehugger Robot
1123*7c3d14c8STreehugger Robot  # Restores original filename in case that cpplint is invoked from Emacs's
1124*7c3d14c8STreehugger Robot  # flymake.
1125*7c3d14c8STreehugger Robot  filename = re.sub(r'_flymake\.h$', '.h', filename)
1126*7c3d14c8STreehugger Robot  filename = re.sub(r'/\.flymake/([^/]*)$', r'/\1', filename)
1127*7c3d14c8STreehugger Robot
1128*7c3d14c8STreehugger Robot  fileinfo = FileInfo(filename)
1129*7c3d14c8STreehugger Robot  file_path_from_root = fileinfo.RepositoryName()
1130*7c3d14c8STreehugger Robot  if _root:
1131*7c3d14c8STreehugger Robot    file_path_from_root = re.sub('^' + _root + os.sep, '', file_path_from_root)
1132*7c3d14c8STreehugger Robot  return re.sub(r'[-./\s]', '_', file_path_from_root).upper() + '_'
1133*7c3d14c8STreehugger Robot
1134*7c3d14c8STreehugger Robot
1135*7c3d14c8STreehugger Robotdef CheckForHeaderGuard(filename, lines, error):
1136*7c3d14c8STreehugger Robot  """Checks that the file contains a header guard.
1137*7c3d14c8STreehugger Robot
1138*7c3d14c8STreehugger Robot  Logs an error if no #ifndef header guard is present.  For other
1139*7c3d14c8STreehugger Robot  headers, checks that the full pathname is used.
1140*7c3d14c8STreehugger Robot
1141*7c3d14c8STreehugger Robot  Args:
1142*7c3d14c8STreehugger Robot    filename: The name of the C++ header file.
1143*7c3d14c8STreehugger Robot    lines: An array of strings, each representing a line of the file.
1144*7c3d14c8STreehugger Robot    error: The function to call with any errors found.
1145*7c3d14c8STreehugger Robot  """
1146*7c3d14c8STreehugger Robot
1147*7c3d14c8STreehugger Robot  cppvar = GetHeaderGuardCPPVariable(filename)
1148*7c3d14c8STreehugger Robot
1149*7c3d14c8STreehugger Robot  ifndef = None
1150*7c3d14c8STreehugger Robot  ifndef_linenum = 0
1151*7c3d14c8STreehugger Robot  define = None
1152*7c3d14c8STreehugger Robot  endif = None
1153*7c3d14c8STreehugger Robot  endif_linenum = 0
1154*7c3d14c8STreehugger Robot  for linenum, line in enumerate(lines):
1155*7c3d14c8STreehugger Robot    linesplit = line.split()
1156*7c3d14c8STreehugger Robot    if len(linesplit) >= 2:
1157*7c3d14c8STreehugger Robot      # find the first occurrence of #ifndef and #define, save arg
1158*7c3d14c8STreehugger Robot      if not ifndef and linesplit[0] == '#ifndef':
1159*7c3d14c8STreehugger Robot        # set ifndef to the header guard presented on the #ifndef line.
1160*7c3d14c8STreehugger Robot        ifndef = linesplit[1]
1161*7c3d14c8STreehugger Robot        ifndef_linenum = linenum
1162*7c3d14c8STreehugger Robot      if not define and linesplit[0] == '#define':
1163*7c3d14c8STreehugger Robot        define = linesplit[1]
1164*7c3d14c8STreehugger Robot    # find the last occurrence of #endif, save entire line
1165*7c3d14c8STreehugger Robot    if line.startswith('#endif'):
1166*7c3d14c8STreehugger Robot      endif = line
1167*7c3d14c8STreehugger Robot      endif_linenum = linenum
1168*7c3d14c8STreehugger Robot
1169*7c3d14c8STreehugger Robot  if not ifndef:
1170*7c3d14c8STreehugger Robot    error(filename, 0, 'build/header_guard', 5,
1171*7c3d14c8STreehugger Robot          'No #ifndef header guard found, suggested CPP variable is: %s' %
1172*7c3d14c8STreehugger Robot          cppvar)
1173*7c3d14c8STreehugger Robot    return
1174*7c3d14c8STreehugger Robot
1175*7c3d14c8STreehugger Robot  if not define:
1176*7c3d14c8STreehugger Robot    error(filename, 0, 'build/header_guard', 5,
1177*7c3d14c8STreehugger Robot          'No #define header guard found, suggested CPP variable is: %s' %
1178*7c3d14c8STreehugger Robot          cppvar)
1179*7c3d14c8STreehugger Robot    return
1180*7c3d14c8STreehugger Robot
1181*7c3d14c8STreehugger Robot  # The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__
1182*7c3d14c8STreehugger Robot  # for backward compatibility.
1183*7c3d14c8STreehugger Robot  if ifndef != cppvar:
1184*7c3d14c8STreehugger Robot    error_level = 0
1185*7c3d14c8STreehugger Robot    if ifndef != cppvar + '_':
1186*7c3d14c8STreehugger Robot      error_level = 5
1187*7c3d14c8STreehugger Robot
1188*7c3d14c8STreehugger Robot    ParseNolintSuppressions(filename, lines[ifndef_linenum], ifndef_linenum,
1189*7c3d14c8STreehugger Robot                            error)
1190*7c3d14c8STreehugger Robot    error(filename, ifndef_linenum, 'build/header_guard', error_level,
1191*7c3d14c8STreehugger Robot          '#ifndef header guard has wrong style, please use: %s' % cppvar)
1192*7c3d14c8STreehugger Robot
1193*7c3d14c8STreehugger Robot  if define != ifndef:
1194*7c3d14c8STreehugger Robot    error(filename, 0, 'build/header_guard', 5,
1195*7c3d14c8STreehugger Robot          '#ifndef and #define don\'t match, suggested CPP variable is: %s' %
1196*7c3d14c8STreehugger Robot          cppvar)
1197*7c3d14c8STreehugger Robot    return
1198*7c3d14c8STreehugger Robot
1199*7c3d14c8STreehugger Robot  if endif != ('#endif  // %s' % cppvar):
1200*7c3d14c8STreehugger Robot    error_level = 0
1201*7c3d14c8STreehugger Robot    if endif != ('#endif  // %s' % (cppvar + '_')):
1202*7c3d14c8STreehugger Robot      error_level = 5
1203*7c3d14c8STreehugger Robot
1204*7c3d14c8STreehugger Robot    ParseNolintSuppressions(filename, lines[endif_linenum], endif_linenum,
1205*7c3d14c8STreehugger Robot                            error)
1206*7c3d14c8STreehugger Robot    error(filename, endif_linenum, 'build/header_guard', error_level,
1207*7c3d14c8STreehugger Robot          '#endif line should be "#endif  // %s"' % cppvar)
1208*7c3d14c8STreehugger Robot
1209*7c3d14c8STreehugger Robot
1210*7c3d14c8STreehugger Robotdef CheckForUnicodeReplacementCharacters(filename, lines, error):
1211*7c3d14c8STreehugger Robot  """Logs an error for each line containing Unicode replacement characters.
1212*7c3d14c8STreehugger Robot
1213*7c3d14c8STreehugger Robot  These indicate that either the file contained invalid UTF-8 (likely)
1214*7c3d14c8STreehugger Robot  or Unicode replacement characters (which it shouldn't).  Note that
1215*7c3d14c8STreehugger Robot  it's possible for this to throw off line numbering if the invalid
1216*7c3d14c8STreehugger Robot  UTF-8 occurred adjacent to a newline.
1217*7c3d14c8STreehugger Robot
1218*7c3d14c8STreehugger Robot  Args:
1219*7c3d14c8STreehugger Robot    filename: The name of the current file.
1220*7c3d14c8STreehugger Robot    lines: An array of strings, each representing a line of the file.
1221*7c3d14c8STreehugger Robot    error: The function to call with any errors found.
1222*7c3d14c8STreehugger Robot  """
1223*7c3d14c8STreehugger Robot  for linenum, line in enumerate(lines):
1224*7c3d14c8STreehugger Robot    if u'\ufffd' in line:
1225*7c3d14c8STreehugger Robot      error(filename, linenum, 'readability/utf8', 5,
1226*7c3d14c8STreehugger Robot            'Line contains invalid UTF-8 (or Unicode replacement character).')
1227*7c3d14c8STreehugger Robot
1228*7c3d14c8STreehugger Robot
1229*7c3d14c8STreehugger Robotdef CheckForNewlineAtEOF(filename, lines, error):
1230*7c3d14c8STreehugger Robot  """Logs an error if there is no newline char at the end of the file.
1231*7c3d14c8STreehugger Robot
1232*7c3d14c8STreehugger Robot  Args:
1233*7c3d14c8STreehugger Robot    filename: The name of the current file.
1234*7c3d14c8STreehugger Robot    lines: An array of strings, each representing a line of the file.
1235*7c3d14c8STreehugger Robot    error: The function to call with any errors found.
1236*7c3d14c8STreehugger Robot  """
1237*7c3d14c8STreehugger Robot
1238*7c3d14c8STreehugger Robot  # The array lines() was created by adding two newlines to the
1239*7c3d14c8STreehugger Robot  # original file (go figure), then splitting on \n.
1240*7c3d14c8STreehugger Robot  # To verify that the file ends in \n, we just have to make sure the
1241*7c3d14c8STreehugger Robot  # last-but-two element of lines() exists and is empty.
1242*7c3d14c8STreehugger Robot  if len(lines) < 3 or lines[-2]:
1243*7c3d14c8STreehugger Robot    error(filename, len(lines) - 2, 'whitespace/ending_newline', 5,
1244*7c3d14c8STreehugger Robot          'Could not find a newline character at the end of the file.')
1245*7c3d14c8STreehugger Robot
1246*7c3d14c8STreehugger Robot
1247*7c3d14c8STreehugger Robotdef CheckForMultilineCommentsAndStrings(filename, clean_lines, linenum, error):
1248*7c3d14c8STreehugger Robot  """Logs an error if we see /* ... */ or "..." that extend past one line.
1249*7c3d14c8STreehugger Robot
1250*7c3d14c8STreehugger Robot  /* ... */ comments are legit inside macros, for one line.
1251*7c3d14c8STreehugger Robot  Otherwise, we prefer // comments, so it's ok to warn about the
1252*7c3d14c8STreehugger Robot  other.  Likewise, it's ok for strings to extend across multiple
1253*7c3d14c8STreehugger Robot  lines, as long as a line continuation character (backslash)
1254*7c3d14c8STreehugger Robot  terminates each line. Although not currently prohibited by the C++
1255*7c3d14c8STreehugger Robot  style guide, it's ugly and unnecessary. We don't do well with either
1256*7c3d14c8STreehugger Robot  in this lint program, so we warn about both.
1257*7c3d14c8STreehugger Robot
1258*7c3d14c8STreehugger Robot  Args:
1259*7c3d14c8STreehugger Robot    filename: The name of the current file.
1260*7c3d14c8STreehugger Robot    clean_lines: A CleansedLines instance containing the file.
1261*7c3d14c8STreehugger Robot    linenum: The number of the line to check.
1262*7c3d14c8STreehugger Robot    error: The function to call with any errors found.
1263*7c3d14c8STreehugger Robot  """
1264*7c3d14c8STreehugger Robot  line = clean_lines.elided[linenum]
1265*7c3d14c8STreehugger Robot
1266*7c3d14c8STreehugger Robot  # Remove all \\ (escaped backslashes) from the line. They are OK, and the
1267*7c3d14c8STreehugger Robot  # second (escaped) slash may trigger later \" detection erroneously.
1268*7c3d14c8STreehugger Robot  line = line.replace('\\\\', '')
1269*7c3d14c8STreehugger Robot
1270*7c3d14c8STreehugger Robot  if line.count('/*') > line.count('*/'):
1271*7c3d14c8STreehugger Robot    error(filename, linenum, 'readability/multiline_comment', 5,
1272*7c3d14c8STreehugger Robot          'Complex multi-line /*...*/-style comment found. '
1273*7c3d14c8STreehugger Robot          'Lint may give bogus warnings.  '
1274*7c3d14c8STreehugger Robot          'Consider replacing these with //-style comments, '
1275*7c3d14c8STreehugger Robot          'with #if 0...#endif, '
1276*7c3d14c8STreehugger Robot          'or with more clearly structured multi-line comments.')
1277*7c3d14c8STreehugger Robot
1278*7c3d14c8STreehugger Robot  if (line.count('"') - line.count('\\"')) % 2:
1279*7c3d14c8STreehugger Robot    error(filename, linenum, 'readability/multiline_string', 5,
1280*7c3d14c8STreehugger Robot          'Multi-line string ("...") found.  This lint script doesn\'t '
1281*7c3d14c8STreehugger Robot          'do well with such strings, and may give bogus warnings.  They\'re '
1282*7c3d14c8STreehugger Robot          'ugly and unnecessary, and you should use concatenation instead".')
1283*7c3d14c8STreehugger Robot
1284*7c3d14c8STreehugger Robot
1285*7c3d14c8STreehugger Robotthreading_list = (
1286*7c3d14c8STreehugger Robot    ('asctime(', 'asctime_r('),
1287*7c3d14c8STreehugger Robot    ('ctime(', 'ctime_r('),
1288*7c3d14c8STreehugger Robot    ('getgrgid(', 'getgrgid_r('),
1289*7c3d14c8STreehugger Robot    ('getgrnam(', 'getgrnam_r('),
1290*7c3d14c8STreehugger Robot    ('getlogin(', 'getlogin_r('),
1291*7c3d14c8STreehugger Robot    ('getpwnam(', 'getpwnam_r('),
1292*7c3d14c8STreehugger Robot    ('getpwuid(', 'getpwuid_r('),
1293*7c3d14c8STreehugger Robot    ('gmtime(', 'gmtime_r('),
1294*7c3d14c8STreehugger Robot    ('localtime(', 'localtime_r('),
1295*7c3d14c8STreehugger Robot    ('rand(', 'rand_r('),
1296*7c3d14c8STreehugger Robot    ('readdir(', 'readdir_r('),
1297*7c3d14c8STreehugger Robot    ('strtok(', 'strtok_r('),
1298*7c3d14c8STreehugger Robot    ('ttyname(', 'ttyname_r('),
1299*7c3d14c8STreehugger Robot    )
1300*7c3d14c8STreehugger Robot
1301*7c3d14c8STreehugger Robot
1302*7c3d14c8STreehugger Robotdef CheckPosixThreading(filename, clean_lines, linenum, error):
1303*7c3d14c8STreehugger Robot  """Checks for calls to thread-unsafe functions.
1304*7c3d14c8STreehugger Robot
1305*7c3d14c8STreehugger Robot  Much code has been originally written without consideration of
1306*7c3d14c8STreehugger Robot  multi-threading. Also, engineers are relying on their old experience;
1307*7c3d14c8STreehugger Robot  they have learned posix before threading extensions were added. These
1308*7c3d14c8STreehugger Robot  tests guide the engineers to use thread-safe functions (when using
1309*7c3d14c8STreehugger Robot  posix directly).
1310*7c3d14c8STreehugger Robot
1311*7c3d14c8STreehugger Robot  Args:
1312*7c3d14c8STreehugger Robot    filename: The name of the current file.
1313*7c3d14c8STreehugger Robot    clean_lines: A CleansedLines instance containing the file.
1314*7c3d14c8STreehugger Robot    linenum: The number of the line to check.
1315*7c3d14c8STreehugger Robot    error: The function to call with any errors found.
1316*7c3d14c8STreehugger Robot  """
1317*7c3d14c8STreehugger Robot  line = clean_lines.elided[linenum]
1318*7c3d14c8STreehugger Robot  for single_thread_function, multithread_safe_function in threading_list:
1319*7c3d14c8STreehugger Robot    ix = line.find(single_thread_function)
1320*7c3d14c8STreehugger Robot    # Comparisons made explicit for clarity -- pylint: disable-msg=C6403
1321*7c3d14c8STreehugger Robot    if ix >= 0 and (ix == 0 or (not line[ix - 1].isalnum() and
1322*7c3d14c8STreehugger Robot                                line[ix - 1] not in ('_', '.', '>'))):
1323*7c3d14c8STreehugger Robot      error(filename, linenum, 'runtime/threadsafe_fn', 2,
1324*7c3d14c8STreehugger Robot            'Consider using ' + multithread_safe_function +
1325*7c3d14c8STreehugger Robot            '...) instead of ' + single_thread_function +
1326*7c3d14c8STreehugger Robot            '...) for improved thread safety.')
1327*7c3d14c8STreehugger Robot
1328*7c3d14c8STreehugger Robot
1329*7c3d14c8STreehugger Robot# Matches invalid increment: *count++, which moves pointer instead of
1330*7c3d14c8STreehugger Robot# incrementing a value.
1331*7c3d14c8STreehugger Robot_RE_PATTERN_INVALID_INCREMENT = re.compile(
1332*7c3d14c8STreehugger Robot    r'^\s*\*\w+(\+\+|--);')
1333*7c3d14c8STreehugger Robot
1334*7c3d14c8STreehugger Robot
1335*7c3d14c8STreehugger Robotdef CheckInvalidIncrement(filename, clean_lines, linenum, error):
1336*7c3d14c8STreehugger Robot  """Checks for invalid increment *count++.
1337*7c3d14c8STreehugger Robot
1338*7c3d14c8STreehugger Robot  For example following function:
1339*7c3d14c8STreehugger Robot  void increment_counter(int* count) {
1340*7c3d14c8STreehugger Robot    *count++;
1341*7c3d14c8STreehugger Robot  }
1342*7c3d14c8STreehugger Robot  is invalid, because it effectively does count++, moving pointer, and should
1343*7c3d14c8STreehugger Robot  be replaced with ++*count, (*count)++ or *count += 1.
1344*7c3d14c8STreehugger Robot
1345*7c3d14c8STreehugger Robot  Args:
1346*7c3d14c8STreehugger Robot    filename: The name of the current file.
1347*7c3d14c8STreehugger Robot    clean_lines: A CleansedLines instance containing the file.
1348*7c3d14c8STreehugger Robot    linenum: The number of the line to check.
1349*7c3d14c8STreehugger Robot    error: The function to call with any errors found.
1350*7c3d14c8STreehugger Robot  """
1351*7c3d14c8STreehugger Robot  line = clean_lines.elided[linenum]
1352*7c3d14c8STreehugger Robot  if _RE_PATTERN_INVALID_INCREMENT.match(line):
1353*7c3d14c8STreehugger Robot    error(filename, linenum, 'runtime/invalid_increment', 5,
1354*7c3d14c8STreehugger Robot          'Changing pointer instead of value (or unused value of operator*).')
1355*7c3d14c8STreehugger Robot
1356*7c3d14c8STreehugger Robot
1357*7c3d14c8STreehugger Robotclass _BlockInfo(object):
1358*7c3d14c8STreehugger Robot  """Stores information about a generic block of code."""
1359*7c3d14c8STreehugger Robot
1360*7c3d14c8STreehugger Robot  def __init__(self, seen_open_brace):
1361*7c3d14c8STreehugger Robot    self.seen_open_brace = seen_open_brace
1362*7c3d14c8STreehugger Robot    self.open_parentheses = 0
1363*7c3d14c8STreehugger Robot    self.inline_asm = _NO_ASM
1364*7c3d14c8STreehugger Robot
1365*7c3d14c8STreehugger Robot  def CheckBegin(self, filename, clean_lines, linenum, error):
1366*7c3d14c8STreehugger Robot    """Run checks that applies to text up to the opening brace.
1367*7c3d14c8STreehugger Robot
1368*7c3d14c8STreehugger Robot    This is mostly for checking the text after the class identifier
1369*7c3d14c8STreehugger Robot    and the "{", usually where the base class is specified.  For other
1370*7c3d14c8STreehugger Robot    blocks, there isn't much to check, so we always pass.
1371*7c3d14c8STreehugger Robot
1372*7c3d14c8STreehugger Robot    Args:
1373*7c3d14c8STreehugger Robot      filename: The name of the current file.
1374*7c3d14c8STreehugger Robot      clean_lines: A CleansedLines instance containing the file.
1375*7c3d14c8STreehugger Robot      linenum: The number of the line to check.
1376*7c3d14c8STreehugger Robot      error: The function to call with any errors found.
1377*7c3d14c8STreehugger Robot    """
1378*7c3d14c8STreehugger Robot    pass
1379*7c3d14c8STreehugger Robot
1380*7c3d14c8STreehugger Robot  def CheckEnd(self, filename, clean_lines, linenum, error):
1381*7c3d14c8STreehugger Robot    """Run checks that applies to text after the closing brace.
1382*7c3d14c8STreehugger Robot
1383*7c3d14c8STreehugger Robot    This is mostly used for checking end of namespace comments.
1384*7c3d14c8STreehugger Robot
1385*7c3d14c8STreehugger Robot    Args:
1386*7c3d14c8STreehugger Robot      filename: The name of the current file.
1387*7c3d14c8STreehugger Robot      clean_lines: A CleansedLines instance containing the file.
1388*7c3d14c8STreehugger Robot      linenum: The number of the line to check.
1389*7c3d14c8STreehugger Robot      error: The function to call with any errors found.
1390*7c3d14c8STreehugger Robot    """
1391*7c3d14c8STreehugger Robot    pass
1392*7c3d14c8STreehugger Robot
1393*7c3d14c8STreehugger Robot
1394*7c3d14c8STreehugger Robotclass _ClassInfo(_BlockInfo):
1395*7c3d14c8STreehugger Robot  """Stores information about a class."""
1396*7c3d14c8STreehugger Robot
1397*7c3d14c8STreehugger Robot  def __init__(self, name, class_or_struct, clean_lines, linenum):
1398*7c3d14c8STreehugger Robot    _BlockInfo.__init__(self, False)
1399*7c3d14c8STreehugger Robot    self.name = name
1400*7c3d14c8STreehugger Robot    self.starting_linenum = linenum
1401*7c3d14c8STreehugger Robot    self.is_derived = False
1402*7c3d14c8STreehugger Robot    if class_or_struct == 'struct':
1403*7c3d14c8STreehugger Robot      self.access = 'public'
1404*7c3d14c8STreehugger Robot    else:
1405*7c3d14c8STreehugger Robot      self.access = 'private'
1406*7c3d14c8STreehugger Robot
1407*7c3d14c8STreehugger Robot    # Try to find the end of the class.  This will be confused by things like:
1408*7c3d14c8STreehugger Robot    #   class A {
1409*7c3d14c8STreehugger Robot    #   } *x = { ...
1410*7c3d14c8STreehugger Robot    #
1411*7c3d14c8STreehugger Robot    # But it's still good enough for CheckSectionSpacing.
1412*7c3d14c8STreehugger Robot    self.last_line = 0
1413*7c3d14c8STreehugger Robot    depth = 0
1414*7c3d14c8STreehugger Robot    for i in range(linenum, clean_lines.NumLines()):
1415*7c3d14c8STreehugger Robot      line = clean_lines.elided[i]
1416*7c3d14c8STreehugger Robot      depth += line.count('{') - line.count('}')
1417*7c3d14c8STreehugger Robot      if not depth:
1418*7c3d14c8STreehugger Robot        self.last_line = i
1419*7c3d14c8STreehugger Robot        break
1420*7c3d14c8STreehugger Robot
1421*7c3d14c8STreehugger Robot  def CheckBegin(self, filename, clean_lines, linenum, error):
1422*7c3d14c8STreehugger Robot    # Look for a bare ':'
1423*7c3d14c8STreehugger Robot    if Search('(^|[^:]):($|[^:])', clean_lines.elided[linenum]):
1424*7c3d14c8STreehugger Robot      self.is_derived = True
1425*7c3d14c8STreehugger Robot
1426*7c3d14c8STreehugger Robot
1427*7c3d14c8STreehugger Robotclass _NamespaceInfo(_BlockInfo):
1428*7c3d14c8STreehugger Robot  """Stores information about a namespace."""
1429*7c3d14c8STreehugger Robot
1430*7c3d14c8STreehugger Robot  def __init__(self, name, linenum):
1431*7c3d14c8STreehugger Robot    _BlockInfo.__init__(self, False)
1432*7c3d14c8STreehugger Robot    self.name = name or ''
1433*7c3d14c8STreehugger Robot    self.starting_linenum = linenum
1434*7c3d14c8STreehugger Robot
1435*7c3d14c8STreehugger Robot  def CheckEnd(self, filename, clean_lines, linenum, error):
1436*7c3d14c8STreehugger Robot    """Check end of namespace comments."""
1437*7c3d14c8STreehugger Robot    line = clean_lines.raw_lines[linenum]
1438*7c3d14c8STreehugger Robot
1439*7c3d14c8STreehugger Robot    # Check how many lines is enclosed in this namespace.  Don't issue
1440*7c3d14c8STreehugger Robot    # warning for missing namespace comments if there aren't enough
1441*7c3d14c8STreehugger Robot    # lines.  However, do apply checks if there is already an end of
1442*7c3d14c8STreehugger Robot    # namespace comment and it's incorrect.
1443*7c3d14c8STreehugger Robot    #
1444*7c3d14c8STreehugger Robot    # TODO(unknown): We always want to check end of namespace comments
1445*7c3d14c8STreehugger Robot    # if a namespace is large, but sometimes we also want to apply the
1446*7c3d14c8STreehugger Robot    # check if a short namespace contained nontrivial things (something
1447*7c3d14c8STreehugger Robot    # other than forward declarations).  There is currently no logic on
1448*7c3d14c8STreehugger Robot    # deciding what these nontrivial things are, so this check is
1449*7c3d14c8STreehugger Robot    # triggered by namespace size only, which works most of the time.
1450*7c3d14c8STreehugger Robot    if (linenum - self.starting_linenum < 10
1451*7c3d14c8STreehugger Robot        and not Match(r'};*\s*(//|/\*).*\bnamespace\b', line)):
1452*7c3d14c8STreehugger Robot      return
1453*7c3d14c8STreehugger Robot
1454*7c3d14c8STreehugger Robot    # Look for matching comment at end of namespace.
1455*7c3d14c8STreehugger Robot    #
1456*7c3d14c8STreehugger Robot    # Note that we accept C style "/* */" comments for terminating
1457*7c3d14c8STreehugger Robot    # namespaces, so that code that terminate namespaces inside
1458*7c3d14c8STreehugger Robot    # preprocessor macros can be cpplint clean.  Example: http://go/nxpiz
1459*7c3d14c8STreehugger Robot    #
1460*7c3d14c8STreehugger Robot    # We also accept stuff like "// end of namespace <name>." with the
1461*7c3d14c8STreehugger Robot    # period at the end.
1462*7c3d14c8STreehugger Robot    #
1463*7c3d14c8STreehugger Robot    # Besides these, we don't accept anything else, otherwise we might
1464*7c3d14c8STreehugger Robot    # get false negatives when existing comment is a substring of the
1465*7c3d14c8STreehugger Robot    # expected namespace.  Example: http://go/ldkdc, http://cl/23548205
1466*7c3d14c8STreehugger Robot    if self.name:
1467*7c3d14c8STreehugger Robot      # Named namespace
1468*7c3d14c8STreehugger Robot      if not Match((r'};*\s*(//|/\*).*\bnamespace\s+' + re.escape(self.name) +
1469*7c3d14c8STreehugger Robot                    r'[\*/\.\\\s]*$'),
1470*7c3d14c8STreehugger Robot                   line):
1471*7c3d14c8STreehugger Robot        error(filename, linenum, 'readability/namespace', 5,
1472*7c3d14c8STreehugger Robot              'Namespace should be terminated with "// namespace %s"' %
1473*7c3d14c8STreehugger Robot              self.name)
1474*7c3d14c8STreehugger Robot    else:
1475*7c3d14c8STreehugger Robot      # Anonymous namespace
1476*7c3d14c8STreehugger Robot      if not Match(r'};*\s*(//|/\*).*\bnamespace[\*/\.\\\s]*$', line):
1477*7c3d14c8STreehugger Robot        error(filename, linenum, 'readability/namespace', 5,
1478*7c3d14c8STreehugger Robot              'Namespace should be terminated with "// namespace"')
1479*7c3d14c8STreehugger Robot
1480*7c3d14c8STreehugger Robot
1481*7c3d14c8STreehugger Robotclass _PreprocessorInfo(object):
1482*7c3d14c8STreehugger Robot  """Stores checkpoints of nesting stacks when #if/#else is seen."""
1483*7c3d14c8STreehugger Robot
1484*7c3d14c8STreehugger Robot  def __init__(self, stack_before_if):
1485*7c3d14c8STreehugger Robot    # The entire nesting stack before #if
1486*7c3d14c8STreehugger Robot    self.stack_before_if = stack_before_if
1487*7c3d14c8STreehugger Robot
1488*7c3d14c8STreehugger Robot    # The entire nesting stack up to #else
1489*7c3d14c8STreehugger Robot    self.stack_before_else = []
1490*7c3d14c8STreehugger Robot
1491*7c3d14c8STreehugger Robot    # Whether we have already seen #else or #elif
1492*7c3d14c8STreehugger Robot    self.seen_else = False
1493*7c3d14c8STreehugger Robot
1494*7c3d14c8STreehugger Robot
1495*7c3d14c8STreehugger Robotclass _NestingState(object):
1496*7c3d14c8STreehugger Robot  """Holds states related to parsing braces."""
1497*7c3d14c8STreehugger Robot
1498*7c3d14c8STreehugger Robot  def __init__(self):
1499*7c3d14c8STreehugger Robot    # Stack for tracking all braces.  An object is pushed whenever we
1500*7c3d14c8STreehugger Robot    # see a "{", and popped when we see a "}".  Only 3 types of
1501*7c3d14c8STreehugger Robot    # objects are possible:
1502*7c3d14c8STreehugger Robot    # - _ClassInfo: a class or struct.
1503*7c3d14c8STreehugger Robot    # - _NamespaceInfo: a namespace.
1504*7c3d14c8STreehugger Robot    # - _BlockInfo: some other type of block.
1505*7c3d14c8STreehugger Robot    self.stack = []
1506*7c3d14c8STreehugger Robot
1507*7c3d14c8STreehugger Robot    # Stack of _PreprocessorInfo objects.
1508*7c3d14c8STreehugger Robot    self.pp_stack = []
1509*7c3d14c8STreehugger Robot
1510*7c3d14c8STreehugger Robot  def SeenOpenBrace(self):
1511*7c3d14c8STreehugger Robot    """Check if we have seen the opening brace for the innermost block.
1512*7c3d14c8STreehugger Robot
1513*7c3d14c8STreehugger Robot    Returns:
1514*7c3d14c8STreehugger Robot      True if we have seen the opening brace, False if the innermost
1515*7c3d14c8STreehugger Robot      block is still expecting an opening brace.
1516*7c3d14c8STreehugger Robot    """
1517*7c3d14c8STreehugger Robot    return (not self.stack) or self.stack[-1].seen_open_brace
1518*7c3d14c8STreehugger Robot
1519*7c3d14c8STreehugger Robot  def InNamespaceBody(self):
1520*7c3d14c8STreehugger Robot    """Check if we are currently one level inside a namespace body.
1521*7c3d14c8STreehugger Robot
1522*7c3d14c8STreehugger Robot    Returns:
1523*7c3d14c8STreehugger Robot      True if top of the stack is a namespace block, False otherwise.
1524*7c3d14c8STreehugger Robot    """
1525*7c3d14c8STreehugger Robot    return self.stack and isinstance(self.stack[-1], _NamespaceInfo)
1526*7c3d14c8STreehugger Robot
1527*7c3d14c8STreehugger Robot  def UpdatePreprocessor(self, line):
1528*7c3d14c8STreehugger Robot    """Update preprocessor stack.
1529*7c3d14c8STreehugger Robot
1530*7c3d14c8STreehugger Robot    We need to handle preprocessors due to classes like this:
1531*7c3d14c8STreehugger Robot      #ifdef SWIG
1532*7c3d14c8STreehugger Robot      struct ResultDetailsPageElementExtensionPoint {
1533*7c3d14c8STreehugger Robot      #else
1534*7c3d14c8STreehugger Robot      struct ResultDetailsPageElementExtensionPoint : public Extension {
1535*7c3d14c8STreehugger Robot      #endif
1536*7c3d14c8STreehugger Robot    (see http://go/qwddn for original example)
1537*7c3d14c8STreehugger Robot
1538*7c3d14c8STreehugger Robot    We make the following assumptions (good enough for most files):
1539*7c3d14c8STreehugger Robot    - Preprocessor condition evaluates to true from #if up to first
1540*7c3d14c8STreehugger Robot      #else/#elif/#endif.
1541*7c3d14c8STreehugger Robot
1542*7c3d14c8STreehugger Robot    - Preprocessor condition evaluates to false from #else/#elif up
1543*7c3d14c8STreehugger Robot      to #endif.  We still perform lint checks on these lines, but
1544*7c3d14c8STreehugger Robot      these do not affect nesting stack.
1545*7c3d14c8STreehugger Robot
1546*7c3d14c8STreehugger Robot    Args:
1547*7c3d14c8STreehugger Robot      line: current line to check.
1548*7c3d14c8STreehugger Robot    """
1549*7c3d14c8STreehugger Robot    if Match(r'^\s*#\s*(if|ifdef|ifndef)\b', line):
1550*7c3d14c8STreehugger Robot      # Beginning of #if block, save the nesting stack here.  The saved
1551*7c3d14c8STreehugger Robot      # stack will allow us to restore the parsing state in the #else case.
1552*7c3d14c8STreehugger Robot      self.pp_stack.append(_PreprocessorInfo(copy.deepcopy(self.stack)))
1553*7c3d14c8STreehugger Robot    elif Match(r'^\s*#\s*(else|elif)\b', line):
1554*7c3d14c8STreehugger Robot      # Beginning of #else block
1555*7c3d14c8STreehugger Robot      if self.pp_stack:
1556*7c3d14c8STreehugger Robot        if not self.pp_stack[-1].seen_else:
1557*7c3d14c8STreehugger Robot          # This is the first #else or #elif block.  Remember the
1558*7c3d14c8STreehugger Robot          # whole nesting stack up to this point.  This is what we
1559*7c3d14c8STreehugger Robot          # keep after the #endif.
1560*7c3d14c8STreehugger Robot          self.pp_stack[-1].seen_else = True
1561*7c3d14c8STreehugger Robot          self.pp_stack[-1].stack_before_else = copy.deepcopy(self.stack)
1562*7c3d14c8STreehugger Robot
1563*7c3d14c8STreehugger Robot        # Restore the stack to how it was before the #if
1564*7c3d14c8STreehugger Robot        self.stack = copy.deepcopy(self.pp_stack[-1].stack_before_if)
1565*7c3d14c8STreehugger Robot      else:
1566*7c3d14c8STreehugger Robot        # TODO(unknown): unexpected #else, issue warning?
1567*7c3d14c8STreehugger Robot        pass
1568*7c3d14c8STreehugger Robot    elif Match(r'^\s*#\s*endif\b', line):
1569*7c3d14c8STreehugger Robot      # End of #if or #else blocks.
1570*7c3d14c8STreehugger Robot      if self.pp_stack:
1571*7c3d14c8STreehugger Robot        # If we saw an #else, we will need to restore the nesting
1572*7c3d14c8STreehugger Robot        # stack to its former state before the #else, otherwise we
1573*7c3d14c8STreehugger Robot        # will just continue from where we left off.
1574*7c3d14c8STreehugger Robot        if self.pp_stack[-1].seen_else:
1575*7c3d14c8STreehugger Robot          # Here we can just use a shallow copy since we are the last
1576*7c3d14c8STreehugger Robot          # reference to it.
1577*7c3d14c8STreehugger Robot          self.stack = self.pp_stack[-1].stack_before_else
1578*7c3d14c8STreehugger Robot        # Drop the corresponding #if
1579*7c3d14c8STreehugger Robot        self.pp_stack.pop()
1580*7c3d14c8STreehugger Robot      else:
1581*7c3d14c8STreehugger Robot        # TODO(unknown): unexpected #endif, issue warning?
1582*7c3d14c8STreehugger Robot        pass
1583*7c3d14c8STreehugger Robot
1584*7c3d14c8STreehugger Robot  def Update(self, filename, clean_lines, linenum, error):
1585*7c3d14c8STreehugger Robot    """Update nesting state with current line.
1586*7c3d14c8STreehugger Robot
1587*7c3d14c8STreehugger Robot    Args:
1588*7c3d14c8STreehugger Robot      filename: The name of the current file.
1589*7c3d14c8STreehugger Robot      clean_lines: A CleansedLines instance containing the file.
1590*7c3d14c8STreehugger Robot      linenum: The number of the line to check.
1591*7c3d14c8STreehugger Robot      error: The function to call with any errors found.
1592*7c3d14c8STreehugger Robot    """
1593*7c3d14c8STreehugger Robot    line = clean_lines.elided[linenum]
1594*7c3d14c8STreehugger Robot
1595*7c3d14c8STreehugger Robot    # Update pp_stack first
1596*7c3d14c8STreehugger Robot    self.UpdatePreprocessor(line)
1597*7c3d14c8STreehugger Robot
1598*7c3d14c8STreehugger Robot    # Count parentheses.  This is to avoid adding struct arguments to
1599*7c3d14c8STreehugger Robot    # the nesting stack.
1600*7c3d14c8STreehugger Robot    if self.stack:
1601*7c3d14c8STreehugger Robot      inner_block = self.stack[-1]
1602*7c3d14c8STreehugger Robot      depth_change = line.count('(') - line.count(')')
1603*7c3d14c8STreehugger Robot      inner_block.open_parentheses += depth_change
1604*7c3d14c8STreehugger Robot
1605*7c3d14c8STreehugger Robot      # Also check if we are starting or ending an inline assembly block.
1606*7c3d14c8STreehugger Robot      if inner_block.inline_asm in (_NO_ASM, _END_ASM):
1607*7c3d14c8STreehugger Robot        if (depth_change != 0 and
1608*7c3d14c8STreehugger Robot            inner_block.open_parentheses == 1 and
1609*7c3d14c8STreehugger Robot            _MATCH_ASM.match(line)):
1610*7c3d14c8STreehugger Robot          # Enter assembly block
1611*7c3d14c8STreehugger Robot          inner_block.inline_asm = _INSIDE_ASM
1612*7c3d14c8STreehugger Robot        else:
1613*7c3d14c8STreehugger Robot          # Not entering assembly block.  If previous line was _END_ASM,
1614*7c3d14c8STreehugger Robot          # we will now shift to _NO_ASM state.
1615*7c3d14c8STreehugger Robot          inner_block.inline_asm = _NO_ASM
1616*7c3d14c8STreehugger Robot      elif (inner_block.inline_asm == _INSIDE_ASM and
1617*7c3d14c8STreehugger Robot            inner_block.open_parentheses == 0):
1618*7c3d14c8STreehugger Robot        # Exit assembly block
1619*7c3d14c8STreehugger Robot        inner_block.inline_asm = _END_ASM
1620*7c3d14c8STreehugger Robot
1621*7c3d14c8STreehugger Robot    # Consume namespace declaration at the beginning of the line.  Do
1622*7c3d14c8STreehugger Robot    # this in a loop so that we catch same line declarations like this:
1623*7c3d14c8STreehugger Robot    #   namespace proto2 { namespace bridge { class MessageSet; } }
1624*7c3d14c8STreehugger Robot    while True:
1625*7c3d14c8STreehugger Robot      # Match start of namespace.  The "\b\s*" below catches namespace
1626*7c3d14c8STreehugger Robot      # declarations even if it weren't followed by a whitespace, this
1627*7c3d14c8STreehugger Robot      # is so that we don't confuse our namespace checker.  The
1628*7c3d14c8STreehugger Robot      # missing spaces will be flagged by CheckSpacing.
1629*7c3d14c8STreehugger Robot      namespace_decl_match = Match(r'^\s*namespace\b\s*([:\w]+)?(.*)$', line)
1630*7c3d14c8STreehugger Robot      if not namespace_decl_match:
1631*7c3d14c8STreehugger Robot        break
1632*7c3d14c8STreehugger Robot
1633*7c3d14c8STreehugger Robot      new_namespace = _NamespaceInfo(namespace_decl_match.group(1), linenum)
1634*7c3d14c8STreehugger Robot      self.stack.append(new_namespace)
1635*7c3d14c8STreehugger Robot
1636*7c3d14c8STreehugger Robot      line = namespace_decl_match.group(2)
1637*7c3d14c8STreehugger Robot      if line.find('{') != -1:
1638*7c3d14c8STreehugger Robot        new_namespace.seen_open_brace = True
1639*7c3d14c8STreehugger Robot        line = line[line.find('{') + 1:]
1640*7c3d14c8STreehugger Robot
1641*7c3d14c8STreehugger Robot    # Look for a class declaration in whatever is left of the line
1642*7c3d14c8STreehugger Robot    # after parsing namespaces.  The regexp accounts for decorated classes
1643*7c3d14c8STreehugger Robot    # such as in:
1644*7c3d14c8STreehugger Robot    #   class LOCKABLE API Object {
1645*7c3d14c8STreehugger Robot    #   };
1646*7c3d14c8STreehugger Robot    #
1647*7c3d14c8STreehugger Robot    # Templates with class arguments may confuse the parser, for example:
1648*7c3d14c8STreehugger Robot    #   template <class T
1649*7c3d14c8STreehugger Robot    #             class Comparator = less<T>,
1650*7c3d14c8STreehugger Robot    #             class Vector = vector<T> >
1651*7c3d14c8STreehugger Robot    #   class HeapQueue {
1652*7c3d14c8STreehugger Robot    #
1653*7c3d14c8STreehugger Robot    # Because this parser has no nesting state about templates, by the
1654*7c3d14c8STreehugger Robot    # time it saw "class Comparator", it may think that it's a new class.
1655*7c3d14c8STreehugger Robot    # Nested templates have a similar problem:
1656*7c3d14c8STreehugger Robot    #   template <
1657*7c3d14c8STreehugger Robot    #       typename ExportedType,
1658*7c3d14c8STreehugger Robot    #       typename TupleType,
1659*7c3d14c8STreehugger Robot    #       template <typename, typename> class ImplTemplate>
1660*7c3d14c8STreehugger Robot    #
1661*7c3d14c8STreehugger Robot    # To avoid these cases, we ignore classes that are followed by '=' or '>'
1662*7c3d14c8STreehugger Robot    class_decl_match = Match(
1663*7c3d14c8STreehugger Robot        r'\s*(template\s*<[\w\s<>,:]*>\s*)?'
1664*7c3d14c8STreehugger Robot        '(class|struct)\s+([A-Z_]+\s+)*(\w+(?:::\w+)*)'
1665*7c3d14c8STreehugger Robot        '(([^=>]|<[^<>]*>)*)$', line)
1666*7c3d14c8STreehugger Robot    if (class_decl_match and
1667*7c3d14c8STreehugger Robot        (not self.stack or self.stack[-1].open_parentheses == 0)):
1668*7c3d14c8STreehugger Robot      self.stack.append(_ClassInfo(
1669*7c3d14c8STreehugger Robot          class_decl_match.group(4), class_decl_match.group(2),
1670*7c3d14c8STreehugger Robot          clean_lines, linenum))
1671*7c3d14c8STreehugger Robot      line = class_decl_match.group(5)
1672*7c3d14c8STreehugger Robot
1673*7c3d14c8STreehugger Robot    # If we have not yet seen the opening brace for the innermost block,
1674*7c3d14c8STreehugger Robot    # run checks here.
1675*7c3d14c8STreehugger Robot    if not self.SeenOpenBrace():
1676*7c3d14c8STreehugger Robot      self.stack[-1].CheckBegin(filename, clean_lines, linenum, error)
1677*7c3d14c8STreehugger Robot
1678*7c3d14c8STreehugger Robot    # Update access control if we are inside a class/struct
1679*7c3d14c8STreehugger Robot    if self.stack and isinstance(self.stack[-1], _ClassInfo):
1680*7c3d14c8STreehugger Robot      access_match = Match(r'\s*(public|private|protected)\s*:', line)
1681*7c3d14c8STreehugger Robot      if access_match:
1682*7c3d14c8STreehugger Robot        self.stack[-1].access = access_match.group(1)
1683*7c3d14c8STreehugger Robot
1684*7c3d14c8STreehugger Robot    # Consume braces or semicolons from what's left of the line
1685*7c3d14c8STreehugger Robot    while True:
1686*7c3d14c8STreehugger Robot      # Match first brace, semicolon, or closed parenthesis.
1687*7c3d14c8STreehugger Robot      matched = Match(r'^[^{;)}]*([{;)}])(.*)$', line)
1688*7c3d14c8STreehugger Robot      if not matched:
1689*7c3d14c8STreehugger Robot        break
1690*7c3d14c8STreehugger Robot
1691*7c3d14c8STreehugger Robot      token = matched.group(1)
1692*7c3d14c8STreehugger Robot      if token == '{':
1693*7c3d14c8STreehugger Robot        # If namespace or class hasn't seen a opening brace yet, mark
1694*7c3d14c8STreehugger Robot        # namespace/class head as complete.  Push a new block onto the
1695*7c3d14c8STreehugger Robot        # stack otherwise.
1696*7c3d14c8STreehugger Robot        if not self.SeenOpenBrace():
1697*7c3d14c8STreehugger Robot          self.stack[-1].seen_open_brace = True
1698*7c3d14c8STreehugger Robot        else:
1699*7c3d14c8STreehugger Robot          self.stack.append(_BlockInfo(True))
1700*7c3d14c8STreehugger Robot          if _MATCH_ASM.match(line):
1701*7c3d14c8STreehugger Robot            self.stack[-1].inline_asm = _BLOCK_ASM
1702*7c3d14c8STreehugger Robot      elif token == ';' or token == ')':
1703*7c3d14c8STreehugger Robot        # If we haven't seen an opening brace yet, but we already saw
1704*7c3d14c8STreehugger Robot        # a semicolon, this is probably a forward declaration.  Pop
1705*7c3d14c8STreehugger Robot        # the stack for these.
1706*7c3d14c8STreehugger Robot        #
1707*7c3d14c8STreehugger Robot        # Similarly, if we haven't seen an opening brace yet, but we
1708*7c3d14c8STreehugger Robot        # already saw a closing parenthesis, then these are probably
1709*7c3d14c8STreehugger Robot        # function arguments with extra "class" or "struct" keywords.
1710*7c3d14c8STreehugger Robot        # Also pop these stack for these.
1711*7c3d14c8STreehugger Robot        if not self.SeenOpenBrace():
1712*7c3d14c8STreehugger Robot          self.stack.pop()
1713*7c3d14c8STreehugger Robot      else:  # token == '}'
1714*7c3d14c8STreehugger Robot        # Perform end of block checks and pop the stack.
1715*7c3d14c8STreehugger Robot        if self.stack:
1716*7c3d14c8STreehugger Robot          self.stack[-1].CheckEnd(filename, clean_lines, linenum, error)
1717*7c3d14c8STreehugger Robot          self.stack.pop()
1718*7c3d14c8STreehugger Robot      line = matched.group(2)
1719*7c3d14c8STreehugger Robot
1720*7c3d14c8STreehugger Robot  def InnermostClass(self):
1721*7c3d14c8STreehugger Robot    """Get class info on the top of the stack.
1722*7c3d14c8STreehugger Robot
1723*7c3d14c8STreehugger Robot    Returns:
1724*7c3d14c8STreehugger Robot      A _ClassInfo object if we are inside a class, or None otherwise.
1725*7c3d14c8STreehugger Robot    """
1726*7c3d14c8STreehugger Robot    for i in range(len(self.stack), 0, -1):
1727*7c3d14c8STreehugger Robot      classinfo = self.stack[i - 1]
1728*7c3d14c8STreehugger Robot      if isinstance(classinfo, _ClassInfo):
1729*7c3d14c8STreehugger Robot        return classinfo
1730*7c3d14c8STreehugger Robot    return None
1731*7c3d14c8STreehugger Robot
1732*7c3d14c8STreehugger Robot  def CheckClassFinished(self, filename, error):
1733*7c3d14c8STreehugger Robot    """Checks that all classes have been completely parsed.
1734*7c3d14c8STreehugger Robot
1735*7c3d14c8STreehugger Robot    Call this when all lines in a file have been processed.
1736*7c3d14c8STreehugger Robot    Args:
1737*7c3d14c8STreehugger Robot      filename: The name of the current file.
1738*7c3d14c8STreehugger Robot      error: The function to call with any errors found.
1739*7c3d14c8STreehugger Robot    """
1740*7c3d14c8STreehugger Robot    # Note: This test can result in false positives if #ifdef constructs
1741*7c3d14c8STreehugger Robot    # get in the way of brace matching. See the testBuildClass test in
1742*7c3d14c8STreehugger Robot    # cpplint_unittest.py for an example of this.
1743*7c3d14c8STreehugger Robot    for obj in self.stack:
1744*7c3d14c8STreehugger Robot      if isinstance(obj, _ClassInfo):
1745*7c3d14c8STreehugger Robot        error(filename, obj.starting_linenum, 'build/class', 5,
1746*7c3d14c8STreehugger Robot              'Failed to find complete declaration of class %s' %
1747*7c3d14c8STreehugger Robot              obj.name)
1748*7c3d14c8STreehugger Robot
1749*7c3d14c8STreehugger Robot
1750*7c3d14c8STreehugger Robotdef CheckForNonStandardConstructs(filename, clean_lines, linenum,
1751*7c3d14c8STreehugger Robot                                  nesting_state, error):
1752*7c3d14c8STreehugger Robot  """Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
1753*7c3d14c8STreehugger Robot
1754*7c3d14c8STreehugger Robot  Complain about several constructs which gcc-2 accepts, but which are
1755*7c3d14c8STreehugger Robot  not standard C++.  Warning about these in lint is one way to ease the
1756*7c3d14c8STreehugger Robot  transition to new compilers.
1757*7c3d14c8STreehugger Robot  - put storage class first (e.g. "static const" instead of "const static").
1758*7c3d14c8STreehugger Robot  - "%lld" instead of %qd" in printf-type functions.
1759*7c3d14c8STreehugger Robot  - "%1$d" is non-standard in printf-type functions.
1760*7c3d14c8STreehugger Robot  - "\%" is an undefined character escape sequence.
1761*7c3d14c8STreehugger Robot  - text after #endif is not allowed.
1762*7c3d14c8STreehugger Robot  - invalid inner-style forward declaration.
1763*7c3d14c8STreehugger Robot  - >? and <? operators, and their >?= and <?= cousins.
1764*7c3d14c8STreehugger Robot
1765*7c3d14c8STreehugger Robot  Additionally, check for constructor/destructor style violations and reference
1766*7c3d14c8STreehugger Robot  members, as it is very convenient to do so while checking for
1767*7c3d14c8STreehugger Robot  gcc-2 compliance.
1768*7c3d14c8STreehugger Robot
1769*7c3d14c8STreehugger Robot  Args:
1770*7c3d14c8STreehugger Robot    filename: The name of the current file.
1771*7c3d14c8STreehugger Robot    clean_lines: A CleansedLines instance containing the file.
1772*7c3d14c8STreehugger Robot    linenum: The number of the line to check.
1773*7c3d14c8STreehugger Robot    nesting_state: A _NestingState instance which maintains information about
1774*7c3d14c8STreehugger Robot                   the current stack of nested blocks being parsed.
1775*7c3d14c8STreehugger Robot    error: A callable to which errors are reported, which takes 4 arguments:
1776*7c3d14c8STreehugger Robot           filename, line number, error level, and message
1777*7c3d14c8STreehugger Robot  """
1778*7c3d14c8STreehugger Robot
1779*7c3d14c8STreehugger Robot  # Remove comments from the line, but leave in strings for now.
1780*7c3d14c8STreehugger Robot  line = clean_lines.lines[linenum]
1781*7c3d14c8STreehugger Robot
1782*7c3d14c8STreehugger Robot  if Search(r'printf\s*\(.*".*%[-+ ]?\d*q', line):
1783*7c3d14c8STreehugger Robot    error(filename, linenum, 'runtime/printf_format', 3,
1784*7c3d14c8STreehugger Robot          '%q in format strings is deprecated.  Use %ll instead.')
1785*7c3d14c8STreehugger Robot
1786*7c3d14c8STreehugger Robot  if Search(r'printf\s*\(.*".*%\d+\$', line):
1787*7c3d14c8STreehugger Robot    error(filename, linenum, 'runtime/printf_format', 2,
1788*7c3d14c8STreehugger Robot          '%N$ formats are unconventional.  Try rewriting to avoid them.')
1789*7c3d14c8STreehugger Robot
1790*7c3d14c8STreehugger Robot  # Remove escaped backslashes before looking for undefined escapes.
1791*7c3d14c8STreehugger Robot  line = line.replace('\\\\', '')
1792*7c3d14c8STreehugger Robot
1793*7c3d14c8STreehugger Robot  if Search(r'("|\').*\\(%|\[|\(|{)', line):
1794*7c3d14c8STreehugger Robot    error(filename, linenum, 'build/printf_format', 3,
1795*7c3d14c8STreehugger Robot          '%, [, (, and { are undefined character escapes.  Unescape them.')
1796*7c3d14c8STreehugger Robot
1797*7c3d14c8STreehugger Robot  # For the rest, work with both comments and strings removed.
1798*7c3d14c8STreehugger Robot  line = clean_lines.elided[linenum]
1799*7c3d14c8STreehugger Robot
1800*7c3d14c8STreehugger Robot  if Search(r'\b(const|volatile|void|char|short|int|long'
1801*7c3d14c8STreehugger Robot            r'|float|double|signed|unsigned'
1802*7c3d14c8STreehugger Robot            r'|schar|u?int8|u?int16|u?int32|u?int64)'
1803*7c3d14c8STreehugger Robot            r'\s+(register|static|extern|typedef)\b',
1804*7c3d14c8STreehugger Robot            line):
1805*7c3d14c8STreehugger Robot    error(filename, linenum, 'build/storage_class', 5,
1806*7c3d14c8STreehugger Robot          'Storage class (static, extern, typedef, etc) should be first.')
1807*7c3d14c8STreehugger Robot
1808*7c3d14c8STreehugger Robot  if Match(r'\s*#\s*endif\s*[^/\s]+', line):
1809*7c3d14c8STreehugger Robot    error(filename, linenum, 'build/endif_comment', 5,
1810*7c3d14c8STreehugger Robot          'Uncommented text after #endif is non-standard.  Use a comment.')
1811*7c3d14c8STreehugger Robot
1812*7c3d14c8STreehugger Robot  if Match(r'\s*class\s+(\w+\s*::\s*)+\w+\s*;', line):
1813*7c3d14c8STreehugger Robot    error(filename, linenum, 'build/forward_decl', 5,
1814*7c3d14c8STreehugger Robot          'Inner-style forward declarations are invalid.  Remove this line.')
1815*7c3d14c8STreehugger Robot
1816*7c3d14c8STreehugger Robot  if Search(r'(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?',
1817*7c3d14c8STreehugger Robot            line):
1818*7c3d14c8STreehugger Robot    error(filename, linenum, 'build/deprecated', 3,
1819*7c3d14c8STreehugger Robot          '>? and <? (max and min) operators are non-standard and deprecated.')
1820*7c3d14c8STreehugger Robot
1821*7c3d14c8STreehugger Robot  if Search(r'^\s*const\s*string\s*&\s*\w+\s*;', line):
1822*7c3d14c8STreehugger Robot    # TODO(unknown): Could it be expanded safely to arbitrary references,
1823*7c3d14c8STreehugger Robot    # without triggering too many false positives? The first
1824*7c3d14c8STreehugger Robot    # attempt triggered 5 warnings for mostly benign code in the regtest, hence
1825*7c3d14c8STreehugger Robot    # the restriction.
1826*7c3d14c8STreehugger Robot    # Here's the original regexp, for the reference:
1827*7c3d14c8STreehugger Robot    # type_name = r'\w+((\s*::\s*\w+)|(\s*<\s*\w+?\s*>))?'
1828*7c3d14c8STreehugger Robot    # r'\s*const\s*' + type_name + '\s*&\s*\w+\s*;'
1829*7c3d14c8STreehugger Robot    error(filename, linenum, 'runtime/member_string_references', 2,
1830*7c3d14c8STreehugger Robot          'const string& members are dangerous. It is much better to use '
1831*7c3d14c8STreehugger Robot          'alternatives, such as pointers or simple constants.')
1832*7c3d14c8STreehugger Robot
1833*7c3d14c8STreehugger Robot  # Everything else in this function operates on class declarations.
1834*7c3d14c8STreehugger Robot  # Return early if the top of the nesting stack is not a class, or if
1835*7c3d14c8STreehugger Robot  # the class head is not completed yet.
1836*7c3d14c8STreehugger Robot  classinfo = nesting_state.InnermostClass()
1837*7c3d14c8STreehugger Robot  if not classinfo or not classinfo.seen_open_brace:
1838*7c3d14c8STreehugger Robot    return
1839*7c3d14c8STreehugger Robot
1840*7c3d14c8STreehugger Robot  # The class may have been declared with namespace or classname qualifiers.
1841*7c3d14c8STreehugger Robot  # The constructor and destructor will not have those qualifiers.
1842*7c3d14c8STreehugger Robot  base_classname = classinfo.name.split('::')[-1]
1843*7c3d14c8STreehugger Robot
1844*7c3d14c8STreehugger Robot  # Look for single-argument constructors that aren't marked explicit.
1845*7c3d14c8STreehugger Robot  # Technically a valid construct, but against style.
1846*7c3d14c8STreehugger Robot  args = Match(r'\s+(?:inline\s+)?%s\s*\(([^,()]+)\)'
1847*7c3d14c8STreehugger Robot               % re.escape(base_classname),
1848*7c3d14c8STreehugger Robot               line)
1849*7c3d14c8STreehugger Robot  if (args and
1850*7c3d14c8STreehugger Robot      args.group(1) != 'void' and
1851*7c3d14c8STreehugger Robot      not Match(r'(const\s+)?%s\s*(?:<\w+>\s*)?&' % re.escape(base_classname),
1852*7c3d14c8STreehugger Robot                args.group(1).strip())):
1853*7c3d14c8STreehugger Robot    error(filename, linenum, 'runtime/explicit', 5,
1854*7c3d14c8STreehugger Robot          'Single-argument constructors should be marked explicit.')
1855*7c3d14c8STreehugger Robot
1856*7c3d14c8STreehugger Robot
1857*7c3d14c8STreehugger Robotdef CheckSpacingForFunctionCall(filename, line, linenum, error):
1858*7c3d14c8STreehugger Robot  """Checks for the correctness of various spacing around function calls.
1859*7c3d14c8STreehugger Robot
1860*7c3d14c8STreehugger Robot  Args:
1861*7c3d14c8STreehugger Robot    filename: The name of the current file.
1862*7c3d14c8STreehugger Robot    line: The text of the line to check.
1863*7c3d14c8STreehugger Robot    linenum: The number of the line to check.
1864*7c3d14c8STreehugger Robot    error: The function to call with any errors found.
1865*7c3d14c8STreehugger Robot  """
1866*7c3d14c8STreehugger Robot
1867*7c3d14c8STreehugger Robot  # Since function calls often occur inside if/for/while/switch
1868*7c3d14c8STreehugger Robot  # expressions - which have their own, more liberal conventions - we
1869*7c3d14c8STreehugger Robot  # first see if we should be looking inside such an expression for a
1870*7c3d14c8STreehugger Robot  # function call, to which we can apply more strict standards.
1871*7c3d14c8STreehugger Robot  fncall = line    # if there's no control flow construct, look at whole line
1872*7c3d14c8STreehugger Robot  for pattern in (r'\bif\s*\((.*)\)\s*{',
1873*7c3d14c8STreehugger Robot                  r'\bfor\s*\((.*)\)\s*{',
1874*7c3d14c8STreehugger Robot                  r'\bwhile\s*\((.*)\)\s*[{;]',
1875*7c3d14c8STreehugger Robot                  r'\bswitch\s*\((.*)\)\s*{'):
1876*7c3d14c8STreehugger Robot    match = Search(pattern, line)
1877*7c3d14c8STreehugger Robot    if match:
1878*7c3d14c8STreehugger Robot      fncall = match.group(1)    # look inside the parens for function calls
1879*7c3d14c8STreehugger Robot      break
1880*7c3d14c8STreehugger Robot
1881*7c3d14c8STreehugger Robot  # Except in if/for/while/switch, there should never be space
1882*7c3d14c8STreehugger Robot  # immediately inside parens (eg "f( 3, 4 )").  We make an exception
1883*7c3d14c8STreehugger Robot  # for nested parens ( (a+b) + c ).  Likewise, there should never be
1884*7c3d14c8STreehugger Robot  # a space before a ( when it's a function argument.  I assume it's a
1885*7c3d14c8STreehugger Robot  # function argument when the char before the whitespace is legal in
1886*7c3d14c8STreehugger Robot  # a function name (alnum + _) and we're not starting a macro. Also ignore
1887*7c3d14c8STreehugger Robot  # pointers and references to arrays and functions coz they're too tricky:
1888*7c3d14c8STreehugger Robot  # we use a very simple way to recognize these:
1889*7c3d14c8STreehugger Robot  # " (something)(maybe-something)" or
1890*7c3d14c8STreehugger Robot  # " (something)(maybe-something," or
1891*7c3d14c8STreehugger Robot  # " (something)[something]"
1892*7c3d14c8STreehugger Robot  # Note that we assume the contents of [] to be short enough that
1893*7c3d14c8STreehugger Robot  # they'll never need to wrap.
1894*7c3d14c8STreehugger Robot  if (  # Ignore control structures.
1895*7c3d14c8STreehugger Robot      not Search(r'\b(if|for|while|switch|return|delete)\b', fncall) and
1896*7c3d14c8STreehugger Robot      # Ignore pointers/references to functions.
1897*7c3d14c8STreehugger Robot      not Search(r' \([^)]+\)\([^)]*(\)|,$)', fncall) and
1898*7c3d14c8STreehugger Robot      # Ignore pointers/references to arrays.
1899*7c3d14c8STreehugger Robot      not Search(r' \([^)]+\)\[[^\]]+\]', fncall)):
1900*7c3d14c8STreehugger Robot    if Search(r'\w\s*\(\s(?!\s*\\$)', fncall):      # a ( used for a fn call
1901*7c3d14c8STreehugger Robot      error(filename, linenum, 'whitespace/parens', 4,
1902*7c3d14c8STreehugger Robot            'Extra space after ( in function call')
1903*7c3d14c8STreehugger Robot    elif Search(r'\(\s+(?!(\s*\\)|\()', fncall):
1904*7c3d14c8STreehugger Robot      error(filename, linenum, 'whitespace/parens', 2,
1905*7c3d14c8STreehugger Robot            'Extra space after (')
1906*7c3d14c8STreehugger Robot    if (Search(r'\w\s+\(', fncall) and
1907*7c3d14c8STreehugger Robot        not Search(r'#\s*define|typedef', fncall) and
1908*7c3d14c8STreehugger Robot        not Search(r'\w\s+\((\w+::)?\*\w+\)\(', fncall)):
1909*7c3d14c8STreehugger Robot      error(filename, linenum, 'whitespace/parens', 4,
1910*7c3d14c8STreehugger Robot            'Extra space before ( in function call')
1911*7c3d14c8STreehugger Robot    # If the ) is followed only by a newline or a { + newline, assume it's
1912*7c3d14c8STreehugger Robot    # part of a control statement (if/while/etc), and don't complain
1913*7c3d14c8STreehugger Robot    if Search(r'[^)]\s+\)\s*[^{\s]', fncall):
1914*7c3d14c8STreehugger Robot      # If the closing parenthesis is preceded by only whitespaces,
1915*7c3d14c8STreehugger Robot      # try to give a more descriptive error message.
1916*7c3d14c8STreehugger Robot      if Search(r'^\s+\)', fncall):
1917*7c3d14c8STreehugger Robot        error(filename, linenum, 'whitespace/parens', 2,
1918*7c3d14c8STreehugger Robot              'Closing ) should be moved to the previous line')
1919*7c3d14c8STreehugger Robot      else:
1920*7c3d14c8STreehugger Robot        error(filename, linenum, 'whitespace/parens', 2,
1921*7c3d14c8STreehugger Robot              'Extra space before )')
1922*7c3d14c8STreehugger Robot
1923*7c3d14c8STreehugger Robot
1924*7c3d14c8STreehugger Robotdef IsBlankLine(line):
1925*7c3d14c8STreehugger Robot  """Returns true if the given line is blank.
1926*7c3d14c8STreehugger Robot
1927*7c3d14c8STreehugger Robot  We consider a line to be blank if the line is empty or consists of
1928*7c3d14c8STreehugger Robot  only white spaces.
1929*7c3d14c8STreehugger Robot
1930*7c3d14c8STreehugger Robot  Args:
1931*7c3d14c8STreehugger Robot    line: A line of a string.
1932*7c3d14c8STreehugger Robot
1933*7c3d14c8STreehugger Robot  Returns:
1934*7c3d14c8STreehugger Robot    True, if the given line is blank.
1935*7c3d14c8STreehugger Robot  """
1936*7c3d14c8STreehugger Robot  return not line or line.isspace()
1937*7c3d14c8STreehugger Robot
1938*7c3d14c8STreehugger Robot
1939*7c3d14c8STreehugger Robotdef CheckForFunctionLengths(filename, clean_lines, linenum,
1940*7c3d14c8STreehugger Robot                            function_state, error):
1941*7c3d14c8STreehugger Robot  """Reports for long function bodies.
1942*7c3d14c8STreehugger Robot
1943*7c3d14c8STreehugger Robot  For an overview why this is done, see:
1944*7c3d14c8STreehugger Robot  http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions
1945*7c3d14c8STreehugger Robot
1946*7c3d14c8STreehugger Robot  Uses a simplistic algorithm assuming other style guidelines
1947*7c3d14c8STreehugger Robot  (especially spacing) are followed.
1948*7c3d14c8STreehugger Robot  Only checks unindented functions, so class members are unchecked.
1949*7c3d14c8STreehugger Robot  Trivial bodies are unchecked, so constructors with huge initializer lists
1950*7c3d14c8STreehugger Robot  may be missed.
1951*7c3d14c8STreehugger Robot  Blank/comment lines are not counted so as to avoid encouraging the removal
1952*7c3d14c8STreehugger Robot  of vertical space and comments just to get through a lint check.
1953*7c3d14c8STreehugger Robot  NOLINT *on the last line of a function* disables this check.
1954*7c3d14c8STreehugger Robot
1955*7c3d14c8STreehugger Robot  Args:
1956*7c3d14c8STreehugger Robot    filename: The name of the current file.
1957*7c3d14c8STreehugger Robot    clean_lines: A CleansedLines instance containing the file.
1958*7c3d14c8STreehugger Robot    linenum: The number of the line to check.
1959*7c3d14c8STreehugger Robot    function_state: Current function name and lines in body so far.
1960*7c3d14c8STreehugger Robot    error: The function to call with any errors found.
1961*7c3d14c8STreehugger Robot  """
1962*7c3d14c8STreehugger Robot  lines = clean_lines.lines
1963*7c3d14c8STreehugger Robot  line = lines[linenum]
1964*7c3d14c8STreehugger Robot  raw = clean_lines.raw_lines
1965*7c3d14c8STreehugger Robot  raw_line = raw[linenum]
1966*7c3d14c8STreehugger Robot  joined_line = ''
1967*7c3d14c8STreehugger Robot
1968*7c3d14c8STreehugger Robot  starting_func = False
1969*7c3d14c8STreehugger Robot  regexp = r'(\w(\w|::|\*|\&|\s)*)\('  # decls * & space::name( ...
1970*7c3d14c8STreehugger Robot  match_result = Match(regexp, line)
1971*7c3d14c8STreehugger Robot  if match_result:
1972*7c3d14c8STreehugger Robot    # If the name is all caps and underscores, figure it's a macro and
1973*7c3d14c8STreehugger Robot    # ignore it, unless it's TEST or TEST_F.
1974*7c3d14c8STreehugger Robot    function_name = match_result.group(1).split()[-1]
1975*7c3d14c8STreehugger Robot    if function_name == 'TEST' or function_name == 'TEST_F' or (
1976*7c3d14c8STreehugger Robot        not Match(r'[A-Z_]+$', function_name)):
1977*7c3d14c8STreehugger Robot      starting_func = True
1978*7c3d14c8STreehugger Robot
1979*7c3d14c8STreehugger Robot  if starting_func:
1980*7c3d14c8STreehugger Robot    body_found = False
1981*7c3d14c8STreehugger Robot    for start_linenum in xrange(linenum, clean_lines.NumLines()):
1982*7c3d14c8STreehugger Robot      start_line = lines[start_linenum]
1983*7c3d14c8STreehugger Robot      joined_line += ' ' + start_line.lstrip()
1984*7c3d14c8STreehugger Robot      if Search(r'(;|})', start_line):  # Declarations and trivial functions
1985*7c3d14c8STreehugger Robot        body_found = True
1986*7c3d14c8STreehugger Robot        break                              # ... ignore
1987*7c3d14c8STreehugger Robot      elif Search(r'{', start_line):
1988*7c3d14c8STreehugger Robot        body_found = True
1989*7c3d14c8STreehugger Robot        function = Search(r'((\w|:)*)\(', line).group(1)
1990*7c3d14c8STreehugger Robot        if Match(r'TEST', function):    # Handle TEST... macros
1991*7c3d14c8STreehugger Robot          parameter_regexp = Search(r'(\(.*\))', joined_line)
1992*7c3d14c8STreehugger Robot          if parameter_regexp:             # Ignore bad syntax
1993*7c3d14c8STreehugger Robot            function += parameter_regexp.group(1)
1994*7c3d14c8STreehugger Robot        else:
1995*7c3d14c8STreehugger Robot          function += '()'
1996*7c3d14c8STreehugger Robot        function_state.Begin(function)
1997*7c3d14c8STreehugger Robot        break
1998*7c3d14c8STreehugger Robot    if not body_found:
1999*7c3d14c8STreehugger Robot      # No body for the function (or evidence of a non-function) was found.
2000*7c3d14c8STreehugger Robot      error(filename, linenum, 'readability/fn_size', 5,
2001*7c3d14c8STreehugger Robot            'Lint failed to find start of function body.')
2002*7c3d14c8STreehugger Robot  elif Match(r'^\}\s*$', line):  # function end
2003*7c3d14c8STreehugger Robot    function_state.Check(error, filename, linenum)
2004*7c3d14c8STreehugger Robot    function_state.End()
2005*7c3d14c8STreehugger Robot  elif not Match(r'^\s*$', line):
2006*7c3d14c8STreehugger Robot    function_state.Count()  # Count non-blank/non-comment lines.
2007*7c3d14c8STreehugger Robot
2008*7c3d14c8STreehugger Robot
2009*7c3d14c8STreehugger Robot_RE_PATTERN_TODO = re.compile(r'^//(\s*)TODO(\(.+?\))?:?(\s|$)?')
2010*7c3d14c8STreehugger Robot
2011*7c3d14c8STreehugger Robot
2012*7c3d14c8STreehugger Robotdef CheckComment(comment, filename, linenum, error):
2013*7c3d14c8STreehugger Robot  """Checks for common mistakes in TODO comments.
2014*7c3d14c8STreehugger Robot
2015*7c3d14c8STreehugger Robot  Args:
2016*7c3d14c8STreehugger Robot    comment: The text of the comment from the line in question.
2017*7c3d14c8STreehugger Robot    filename: The name of the current file.
2018*7c3d14c8STreehugger Robot    linenum: The number of the line to check.
2019*7c3d14c8STreehugger Robot    error: The function to call with any errors found.
2020*7c3d14c8STreehugger Robot  """
2021*7c3d14c8STreehugger Robot  match = _RE_PATTERN_TODO.match(comment)
2022*7c3d14c8STreehugger Robot  if match:
2023*7c3d14c8STreehugger Robot    # One whitespace is correct; zero whitespace is handled elsewhere.
2024*7c3d14c8STreehugger Robot    leading_whitespace = match.group(1)
2025*7c3d14c8STreehugger Robot    if len(leading_whitespace) > 1:
2026*7c3d14c8STreehugger Robot      error(filename, linenum, 'whitespace/todo', 2,
2027*7c3d14c8STreehugger Robot            'Too many spaces before TODO')
2028*7c3d14c8STreehugger Robot
2029*7c3d14c8STreehugger Robot    username = match.group(2)
2030*7c3d14c8STreehugger Robot    if not username:
2031*7c3d14c8STreehugger Robot      error(filename, linenum, 'readability/todo', 2,
2032*7c3d14c8STreehugger Robot            'Missing username in TODO; it should look like '
2033*7c3d14c8STreehugger Robot            '"// TODO(my_username): Stuff."')
2034*7c3d14c8STreehugger Robot
2035*7c3d14c8STreehugger Robot    middle_whitespace = match.group(3)
2036*7c3d14c8STreehugger Robot    # Comparisons made explicit for correctness -- pylint: disable-msg=C6403
2037*7c3d14c8STreehugger Robot    if middle_whitespace != ' ' and middle_whitespace != '':
2038*7c3d14c8STreehugger Robot      error(filename, linenum, 'whitespace/todo', 2,
2039*7c3d14c8STreehugger Robot            'TODO(my_username) should be followed by a space')
2040*7c3d14c8STreehugger Robot
2041*7c3d14c8STreehugger Robotdef CheckAccess(filename, clean_lines, linenum, nesting_state, error):
2042*7c3d14c8STreehugger Robot  """Checks for improper use of DISALLOW* macros.
2043*7c3d14c8STreehugger Robot
2044*7c3d14c8STreehugger Robot  Args:
2045*7c3d14c8STreehugger Robot    filename: The name of the current file.
2046*7c3d14c8STreehugger Robot    clean_lines: A CleansedLines instance containing the file.
2047*7c3d14c8STreehugger Robot    linenum: The number of the line to check.
2048*7c3d14c8STreehugger Robot    nesting_state: A _NestingState instance which maintains information about
2049*7c3d14c8STreehugger Robot                   the current stack of nested blocks being parsed.
2050*7c3d14c8STreehugger Robot    error: The function to call with any errors found.
2051*7c3d14c8STreehugger Robot  """
2052*7c3d14c8STreehugger Robot  line = clean_lines.elided[linenum]  # get rid of comments and strings
2053*7c3d14c8STreehugger Robot
2054*7c3d14c8STreehugger Robot  matched = Match((r'\s*(DISALLOW_COPY_AND_ASSIGN|'
2055*7c3d14c8STreehugger Robot                   r'DISALLOW_EVIL_CONSTRUCTORS|'
2056*7c3d14c8STreehugger Robot                   r'DISALLOW_IMPLICIT_CONSTRUCTORS)'), line)
2057*7c3d14c8STreehugger Robot  if not matched:
2058*7c3d14c8STreehugger Robot    return
2059*7c3d14c8STreehugger Robot  if nesting_state.stack and isinstance(nesting_state.stack[-1], _ClassInfo):
2060*7c3d14c8STreehugger Robot    if nesting_state.stack[-1].access != 'private':
2061*7c3d14c8STreehugger Robot      error(filename, linenum, 'readability/constructors', 3,
2062*7c3d14c8STreehugger Robot            '%s must be in the private: section' % matched.group(1))
2063*7c3d14c8STreehugger Robot
2064*7c3d14c8STreehugger Robot  else:
2065*7c3d14c8STreehugger Robot    # Found DISALLOW* macro outside a class declaration, or perhaps it
2066*7c3d14c8STreehugger Robot    # was used inside a function when it should have been part of the
2067*7c3d14c8STreehugger Robot    # class declaration.  We could issue a warning here, but it
2068*7c3d14c8STreehugger Robot    # probably resulted in a compiler error already.
2069*7c3d14c8STreehugger Robot    pass
2070*7c3d14c8STreehugger Robot
2071*7c3d14c8STreehugger Robot
2072*7c3d14c8STreehugger Robotdef FindNextMatchingAngleBracket(clean_lines, linenum, init_suffix):
2073*7c3d14c8STreehugger Robot  """Find the corresponding > to close a template.
2074*7c3d14c8STreehugger Robot
2075*7c3d14c8STreehugger Robot  Args:
2076*7c3d14c8STreehugger Robot    clean_lines: A CleansedLines instance containing the file.
2077*7c3d14c8STreehugger Robot    linenum: Current line number.
2078*7c3d14c8STreehugger Robot    init_suffix: Remainder of the current line after the initial <.
2079*7c3d14c8STreehugger Robot
2080*7c3d14c8STreehugger Robot  Returns:
2081*7c3d14c8STreehugger Robot    True if a matching bracket exists.
2082*7c3d14c8STreehugger Robot  """
2083*7c3d14c8STreehugger Robot  line = init_suffix
2084*7c3d14c8STreehugger Robot  nesting_stack = ['<']
2085*7c3d14c8STreehugger Robot  while True:
2086*7c3d14c8STreehugger Robot    # Find the next operator that can tell us whether < is used as an
2087*7c3d14c8STreehugger Robot    # opening bracket or as a less-than operator.  We only want to
2088*7c3d14c8STreehugger Robot    # warn on the latter case.
2089*7c3d14c8STreehugger Robot    #
2090*7c3d14c8STreehugger Robot    # We could also check all other operators and terminate the search
2091*7c3d14c8STreehugger Robot    # early, e.g. if we got something like this "a<b+c", the "<" is
2092*7c3d14c8STreehugger Robot    # most likely a less-than operator, but then we will get false
2093*7c3d14c8STreehugger Robot    # positives for default arguments (e.g. http://go/prccd) and
2094*7c3d14c8STreehugger Robot    # other template expressions (e.g. http://go/oxcjq).
2095*7c3d14c8STreehugger Robot    match = Search(r'^[^<>(),;\[\]]*([<>(),;\[\]])(.*)$', line)
2096*7c3d14c8STreehugger Robot    if match:
2097*7c3d14c8STreehugger Robot      # Found an operator, update nesting stack
2098*7c3d14c8STreehugger Robot      operator = match.group(1)
2099*7c3d14c8STreehugger Robot      line = match.group(2)
2100*7c3d14c8STreehugger Robot
2101*7c3d14c8STreehugger Robot      if nesting_stack[-1] == '<':
2102*7c3d14c8STreehugger Robot        # Expecting closing angle bracket
2103*7c3d14c8STreehugger Robot        if operator in ('<', '(', '['):
2104*7c3d14c8STreehugger Robot          nesting_stack.append(operator)
2105*7c3d14c8STreehugger Robot        elif operator == '>':
2106*7c3d14c8STreehugger Robot          nesting_stack.pop()
2107*7c3d14c8STreehugger Robot          if not nesting_stack:
2108*7c3d14c8STreehugger Robot            # Found matching angle bracket
2109*7c3d14c8STreehugger Robot            return True
2110*7c3d14c8STreehugger Robot        elif operator == ',':
2111*7c3d14c8STreehugger Robot          # Got a comma after a bracket, this is most likely a template
2112*7c3d14c8STreehugger Robot          # argument.  We have not seen a closing angle bracket yet, but
2113*7c3d14c8STreehugger Robot          # it's probably a few lines later if we look for it, so just
2114*7c3d14c8STreehugger Robot          # return early here.
2115*7c3d14c8STreehugger Robot          return True
2116*7c3d14c8STreehugger Robot        else:
2117*7c3d14c8STreehugger Robot          # Got some other operator.
2118*7c3d14c8STreehugger Robot          return False
2119*7c3d14c8STreehugger Robot
2120*7c3d14c8STreehugger Robot      else:
2121*7c3d14c8STreehugger Robot        # Expecting closing parenthesis or closing bracket
2122*7c3d14c8STreehugger Robot        if operator in ('<', '(', '['):
2123*7c3d14c8STreehugger Robot          nesting_stack.append(operator)
2124*7c3d14c8STreehugger Robot        elif operator in (')', ']'):
2125*7c3d14c8STreehugger Robot          # We don't bother checking for matching () or [].  If we got
2126*7c3d14c8STreehugger Robot          # something like (] or [), it would have been a syntax error.
2127*7c3d14c8STreehugger Robot          nesting_stack.pop()
2128*7c3d14c8STreehugger Robot
2129*7c3d14c8STreehugger Robot    else:
2130*7c3d14c8STreehugger Robot      # Scan the next line
2131*7c3d14c8STreehugger Robot      linenum += 1
2132*7c3d14c8STreehugger Robot      if linenum >= len(clean_lines.elided):
2133*7c3d14c8STreehugger Robot        break
2134*7c3d14c8STreehugger Robot      line = clean_lines.elided[linenum]
2135*7c3d14c8STreehugger Robot
2136*7c3d14c8STreehugger Robot  # Exhausted all remaining lines and still no matching angle bracket.
2137*7c3d14c8STreehugger Robot  # Most likely the input was incomplete, otherwise we should have
2138*7c3d14c8STreehugger Robot  # seen a semicolon and returned early.
2139*7c3d14c8STreehugger Robot  return True
2140*7c3d14c8STreehugger Robot
2141*7c3d14c8STreehugger Robot
2142*7c3d14c8STreehugger Robotdef FindPreviousMatchingAngleBracket(clean_lines, linenum, init_prefix):
2143*7c3d14c8STreehugger Robot  """Find the corresponding < that started a template.
2144*7c3d14c8STreehugger Robot
2145*7c3d14c8STreehugger Robot  Args:
2146*7c3d14c8STreehugger Robot    clean_lines: A CleansedLines instance containing the file.
2147*7c3d14c8STreehugger Robot    linenum: Current line number.
2148*7c3d14c8STreehugger Robot    init_prefix: Part of the current line before the initial >.
2149*7c3d14c8STreehugger Robot
2150*7c3d14c8STreehugger Robot  Returns:
2151*7c3d14c8STreehugger Robot    True if a matching bracket exists.
2152*7c3d14c8STreehugger Robot  """
2153*7c3d14c8STreehugger Robot  line = init_prefix
2154*7c3d14c8STreehugger Robot  nesting_stack = ['>']
2155*7c3d14c8STreehugger Robot  while True:
2156*7c3d14c8STreehugger Robot    # Find the previous operator
2157*7c3d14c8STreehugger Robot    match = Search(r'^(.*)([<>(),;\[\]])[^<>(),;\[\]]*$', line)
2158*7c3d14c8STreehugger Robot    if match:
2159*7c3d14c8STreehugger Robot      # Found an operator, update nesting stack
2160*7c3d14c8STreehugger Robot      operator = match.group(2)
2161*7c3d14c8STreehugger Robot      line = match.group(1)
2162*7c3d14c8STreehugger Robot
2163*7c3d14c8STreehugger Robot      if nesting_stack[-1] == '>':
2164*7c3d14c8STreehugger Robot        # Expecting opening angle bracket
2165*7c3d14c8STreehugger Robot        if operator in ('>', ')', ']'):
2166*7c3d14c8STreehugger Robot          nesting_stack.append(operator)
2167*7c3d14c8STreehugger Robot        elif operator == '<':
2168*7c3d14c8STreehugger Robot          nesting_stack.pop()
2169*7c3d14c8STreehugger Robot          if not nesting_stack:
2170*7c3d14c8STreehugger Robot            # Found matching angle bracket
2171*7c3d14c8STreehugger Robot            return True
2172*7c3d14c8STreehugger Robot        elif operator == ',':
2173*7c3d14c8STreehugger Robot          # Got a comma before a bracket, this is most likely a
2174*7c3d14c8STreehugger Robot          # template argument.  The opening angle bracket is probably
2175*7c3d14c8STreehugger Robot          # there if we look for it, so just return early here.
2176*7c3d14c8STreehugger Robot          return True
2177*7c3d14c8STreehugger Robot        else:
2178*7c3d14c8STreehugger Robot          # Got some other operator.
2179*7c3d14c8STreehugger Robot          return False
2180*7c3d14c8STreehugger Robot
2181*7c3d14c8STreehugger Robot      else:
2182*7c3d14c8STreehugger Robot        # Expecting opening parenthesis or opening bracket
2183*7c3d14c8STreehugger Robot        if operator in ('>', ')', ']'):
2184*7c3d14c8STreehugger Robot          nesting_stack.append(operator)
2185*7c3d14c8STreehugger Robot        elif operator in ('(', '['):
2186*7c3d14c8STreehugger Robot          nesting_stack.pop()
2187*7c3d14c8STreehugger Robot
2188*7c3d14c8STreehugger Robot    else:
2189*7c3d14c8STreehugger Robot      # Scan the previous line
2190*7c3d14c8STreehugger Robot      linenum -= 1
2191*7c3d14c8STreehugger Robot      if linenum < 0:
2192*7c3d14c8STreehugger Robot        break
2193*7c3d14c8STreehugger Robot      line = clean_lines.elided[linenum]
2194*7c3d14c8STreehugger Robot
2195*7c3d14c8STreehugger Robot  # Exhausted all earlier lines and still no matching angle bracket.
2196*7c3d14c8STreehugger Robot  return False
2197*7c3d14c8STreehugger Robot
2198*7c3d14c8STreehugger Robot
2199*7c3d14c8STreehugger Robotdef CheckSpacing(filename, clean_lines, linenum, nesting_state, error):
2200*7c3d14c8STreehugger Robot  """Checks for the correctness of various spacing issues in the code.
2201*7c3d14c8STreehugger Robot
2202*7c3d14c8STreehugger Robot  Things we check for: spaces around operators, spaces after
2203*7c3d14c8STreehugger Robot  if/for/while/switch, no spaces around parens in function calls, two
2204*7c3d14c8STreehugger Robot  spaces between code and comment, don't start a block with a blank
2205*7c3d14c8STreehugger Robot  line, don't end a function with a blank line, don't add a blank line
2206*7c3d14c8STreehugger Robot  after public/protected/private, don't have too many blank lines in a row.
2207*7c3d14c8STreehugger Robot
2208*7c3d14c8STreehugger Robot  Args:
2209*7c3d14c8STreehugger Robot    filename: The name of the current file.
2210*7c3d14c8STreehugger Robot    clean_lines: A CleansedLines instance containing the file.
2211*7c3d14c8STreehugger Robot    linenum: The number of the line to check.
2212*7c3d14c8STreehugger Robot    nesting_state: A _NestingState instance which maintains information about
2213*7c3d14c8STreehugger Robot                   the current stack of nested blocks being parsed.
2214*7c3d14c8STreehugger Robot    error: The function to call with any errors found.
2215*7c3d14c8STreehugger Robot  """
2216*7c3d14c8STreehugger Robot
2217*7c3d14c8STreehugger Robot  raw = clean_lines.raw_lines
2218*7c3d14c8STreehugger Robot  line = raw[linenum]
2219*7c3d14c8STreehugger Robot
2220*7c3d14c8STreehugger Robot  # Before nixing comments, check if the line is blank for no good
2221*7c3d14c8STreehugger Robot  # reason.  This includes the first line after a block is opened, and
2222*7c3d14c8STreehugger Robot  # blank lines at the end of a function (ie, right before a line like '}'
2223*7c3d14c8STreehugger Robot  #
2224*7c3d14c8STreehugger Robot  # Skip all the blank line checks if we are immediately inside a
2225*7c3d14c8STreehugger Robot  # namespace body.  In other words, don't issue blank line warnings
2226*7c3d14c8STreehugger Robot  # for this block:
2227*7c3d14c8STreehugger Robot  #   namespace {
2228*7c3d14c8STreehugger Robot  #
2229*7c3d14c8STreehugger Robot  #   }
2230*7c3d14c8STreehugger Robot  #
2231*7c3d14c8STreehugger Robot  # A warning about missing end of namespace comments will be issued instead.
2232*7c3d14c8STreehugger Robot  if IsBlankLine(line) and not nesting_state.InNamespaceBody():
2233*7c3d14c8STreehugger Robot    elided = clean_lines.elided
2234*7c3d14c8STreehugger Robot    prev_line = elided[linenum - 1]
2235*7c3d14c8STreehugger Robot    prevbrace = prev_line.rfind('{')
2236*7c3d14c8STreehugger Robot    # TODO(unknown): Don't complain if line before blank line, and line after,
2237*7c3d14c8STreehugger Robot    #                both start with alnums and are indented the same amount.
2238*7c3d14c8STreehugger Robot    #                This ignores whitespace at the start of a namespace block
2239*7c3d14c8STreehugger Robot    #                because those are not usually indented.
2240*7c3d14c8STreehugger Robot    if prevbrace != -1 and prev_line[prevbrace:].find('}') == -1:
2241*7c3d14c8STreehugger Robot      # OK, we have a blank line at the start of a code block.  Before we
2242*7c3d14c8STreehugger Robot      # complain, we check if it is an exception to the rule: The previous
2243*7c3d14c8STreehugger Robot      # non-empty line has the parameters of a function header that are indented
2244*7c3d14c8STreehugger Robot      # 4 spaces (because they did not fit in a 80 column line when placed on
2245*7c3d14c8STreehugger Robot      # the same line as the function name).  We also check for the case where
2246*7c3d14c8STreehugger Robot      # the previous line is indented 6 spaces, which may happen when the
2247*7c3d14c8STreehugger Robot      # initializers of a constructor do not fit into a 80 column line.
2248*7c3d14c8STreehugger Robot      exception = False
2249*7c3d14c8STreehugger Robot      if Match(r' {6}\w', prev_line):  # Initializer list?
2250*7c3d14c8STreehugger Robot        # We are looking for the opening column of initializer list, which
2251*7c3d14c8STreehugger Robot        # should be indented 4 spaces to cause 6 space indentation afterwards.
2252*7c3d14c8STreehugger Robot        search_position = linenum-2
2253*7c3d14c8STreehugger Robot        while (search_position >= 0
2254*7c3d14c8STreehugger Robot               and Match(r' {6}\w', elided[search_position])):
2255*7c3d14c8STreehugger Robot          search_position -= 1
2256*7c3d14c8STreehugger Robot        exception = (search_position >= 0
2257*7c3d14c8STreehugger Robot                     and elided[search_position][:5] == '    :')
2258*7c3d14c8STreehugger Robot      else:
2259*7c3d14c8STreehugger Robot        # Search for the function arguments or an initializer list.  We use a
2260*7c3d14c8STreehugger Robot        # simple heuristic here: If the line is indented 4 spaces; and we have a
2261*7c3d14c8STreehugger Robot        # closing paren, without the opening paren, followed by an opening brace
2262*7c3d14c8STreehugger Robot        # or colon (for initializer lists) we assume that it is the last line of
2263*7c3d14c8STreehugger Robot        # a function header.  If we have a colon indented 4 spaces, it is an
2264*7c3d14c8STreehugger Robot        # initializer list.
2265*7c3d14c8STreehugger Robot        exception = (Match(r' {4}\w[^\(]*\)\s*(const\s*)?(\{\s*$|:)',
2266*7c3d14c8STreehugger Robot                           prev_line)
2267*7c3d14c8STreehugger Robot                     or Match(r' {4}:', prev_line))
2268*7c3d14c8STreehugger Robot
2269*7c3d14c8STreehugger Robot      if not exception:
2270*7c3d14c8STreehugger Robot        error(filename, linenum, 'whitespace/blank_line', 2,
2271*7c3d14c8STreehugger Robot              'Blank line at the start of a code block.  Is this needed?')
2272*7c3d14c8STreehugger Robot    # Ignore blank lines at the end of a block in a long if-else
2273*7c3d14c8STreehugger Robot    # chain, like this:
2274*7c3d14c8STreehugger Robot    #   if (condition1) {
2275*7c3d14c8STreehugger Robot    #     // Something followed by a blank line
2276*7c3d14c8STreehugger Robot    #
2277*7c3d14c8STreehugger Robot    #   } else if (condition2) {
2278*7c3d14c8STreehugger Robot    #     // Something else
2279*7c3d14c8STreehugger Robot    #   }
2280*7c3d14c8STreehugger Robot    if linenum + 1 < clean_lines.NumLines():
2281*7c3d14c8STreehugger Robot      next_line = raw[linenum + 1]
2282*7c3d14c8STreehugger Robot      if (next_line
2283*7c3d14c8STreehugger Robot          and Match(r'\s*}', next_line)
2284*7c3d14c8STreehugger Robot          and next_line.find('} else ') == -1):
2285*7c3d14c8STreehugger Robot        error(filename, linenum, 'whitespace/blank_line', 3,
2286*7c3d14c8STreehugger Robot              'Blank line at the end of a code block.  Is this needed?')
2287*7c3d14c8STreehugger Robot
2288*7c3d14c8STreehugger Robot    matched = Match(r'\s*(public|protected|private):', prev_line)
2289*7c3d14c8STreehugger Robot    if matched:
2290*7c3d14c8STreehugger Robot      error(filename, linenum, 'whitespace/blank_line', 3,
2291*7c3d14c8STreehugger Robot            'Do not leave a blank line after "%s:"' % matched.group(1))
2292*7c3d14c8STreehugger Robot
2293*7c3d14c8STreehugger Robot  # Next, we complain if there's a comment too near the text
2294*7c3d14c8STreehugger Robot  commentpos = line.find('//')
2295*7c3d14c8STreehugger Robot  if commentpos != -1:
2296*7c3d14c8STreehugger Robot    # Check if the // may be in quotes.  If so, ignore it
2297*7c3d14c8STreehugger Robot    # Comparisons made explicit for clarity -- pylint: disable-msg=C6403
2298*7c3d14c8STreehugger Robot    if (line.count('"', 0, commentpos) -
2299*7c3d14c8STreehugger Robot        line.count('\\"', 0, commentpos)) % 2 == 0:   # not in quotes
2300*7c3d14c8STreehugger Robot      # Allow one space for new scopes, two spaces otherwise:
2301*7c3d14c8STreehugger Robot      if (not Match(r'^\s*{ //', line) and
2302*7c3d14c8STreehugger Robot          ((commentpos >= 1 and
2303*7c3d14c8STreehugger Robot            line[commentpos-1] not in string.whitespace) or
2304*7c3d14c8STreehugger Robot           (commentpos >= 2 and
2305*7c3d14c8STreehugger Robot            line[commentpos-2] not in string.whitespace))):
2306*7c3d14c8STreehugger Robot        error(filename, linenum, 'whitespace/comments', 2,
2307*7c3d14c8STreehugger Robot              'At least two spaces is best between code and comments')
2308*7c3d14c8STreehugger Robot      # There should always be a space between the // and the comment
2309*7c3d14c8STreehugger Robot      commentend = commentpos + 2
2310*7c3d14c8STreehugger Robot      if commentend < len(line) and not line[commentend] == ' ':
2311*7c3d14c8STreehugger Robot        # but some lines are exceptions -- e.g. if they're big
2312*7c3d14c8STreehugger Robot        # comment delimiters like:
2313*7c3d14c8STreehugger Robot        # //----------------------------------------------------------
2314*7c3d14c8STreehugger Robot        # or are an empty C++ style Doxygen comment, like:
2315*7c3d14c8STreehugger Robot        # ///
2316*7c3d14c8STreehugger Robot        # or they begin with multiple slashes followed by a space:
2317*7c3d14c8STreehugger Robot        # //////// Header comment
2318*7c3d14c8STreehugger Robot        match = (Search(r'[=/-]{4,}\s*$', line[commentend:]) or
2319*7c3d14c8STreehugger Robot                 Search(r'^/$', line[commentend:]) or
2320*7c3d14c8STreehugger Robot                 Search(r'^/+ ', line[commentend:]))
2321*7c3d14c8STreehugger Robot        if not match:
2322*7c3d14c8STreehugger Robot          error(filename, linenum, 'whitespace/comments', 4,
2323*7c3d14c8STreehugger Robot                'Should have a space between // and comment')
2324*7c3d14c8STreehugger Robot      CheckComment(line[commentpos:], filename, linenum, error)
2325*7c3d14c8STreehugger Robot
2326*7c3d14c8STreehugger Robot  line = clean_lines.elided[linenum]  # get rid of comments and strings
2327*7c3d14c8STreehugger Robot
2328*7c3d14c8STreehugger Robot  # Don't try to do spacing checks for operator methods
2329*7c3d14c8STreehugger Robot  line = re.sub(r'operator(==|!=|<|<<|<=|>=|>>|>)\(', 'operator\(', line)
2330*7c3d14c8STreehugger Robot
2331*7c3d14c8STreehugger Robot  # We allow no-spaces around = within an if: "if ( (a=Foo()) == 0 )".
2332*7c3d14c8STreehugger Robot  # Otherwise not.  Note we only check for non-spaces on *both* sides;
2333*7c3d14c8STreehugger Robot  # sometimes people put non-spaces on one side when aligning ='s among
2334*7c3d14c8STreehugger Robot  # many lines (not that this is behavior that I approve of...)
2335*7c3d14c8STreehugger Robot  if Search(r'[\w.]=[\w.]', line) and not Search(r'\b(if|while) ', line):
2336*7c3d14c8STreehugger Robot    error(filename, linenum, 'whitespace/operators', 4,
2337*7c3d14c8STreehugger Robot          'Missing spaces around =')
2338*7c3d14c8STreehugger Robot
2339*7c3d14c8STreehugger Robot  # It's ok not to have spaces around binary operators like + - * /, but if
2340*7c3d14c8STreehugger Robot  # there's too little whitespace, we get concerned.  It's hard to tell,
2341*7c3d14c8STreehugger Robot  # though, so we punt on this one for now.  TODO.
2342*7c3d14c8STreehugger Robot
2343*7c3d14c8STreehugger Robot  # You should always have whitespace around binary operators.
2344*7c3d14c8STreehugger Robot  #
2345*7c3d14c8STreehugger Robot  # Check <= and >= first to avoid false positives with < and >, then
2346*7c3d14c8STreehugger Robot  # check non-include lines for spacing around < and >.
2347*7c3d14c8STreehugger Robot  match = Search(r'[^<>=!\s](==|!=|<=|>=)[^<>=!\s]', line)
2348*7c3d14c8STreehugger Robot  if match:
2349*7c3d14c8STreehugger Robot    error(filename, linenum, 'whitespace/operators', 3,
2350*7c3d14c8STreehugger Robot          'Missing spaces around %s' % match.group(1))
2351*7c3d14c8STreehugger Robot  # We allow no-spaces around << when used like this: 10<<20, but
2352*7c3d14c8STreehugger Robot  # not otherwise (particularly, not when used as streams)
2353*7c3d14c8STreehugger Robot  match = Search(r'(\S)(?:L|UL|ULL|l|ul|ull)?<<(\S)', line)
2354*7c3d14c8STreehugger Robot  if match and not (match.group(1).isdigit() and match.group(2).isdigit()):
2355*7c3d14c8STreehugger Robot    error(filename, linenum, 'whitespace/operators', 3,
2356*7c3d14c8STreehugger Robot          'Missing spaces around <<')
2357*7c3d14c8STreehugger Robot  elif not Match(r'#.*include', line):
2358*7c3d14c8STreehugger Robot    # Avoid false positives on ->
2359*7c3d14c8STreehugger Robot    reduced_line = line.replace('->', '')
2360*7c3d14c8STreehugger Robot
2361*7c3d14c8STreehugger Robot    # Look for < that is not surrounded by spaces.  This is only
2362*7c3d14c8STreehugger Robot    # triggered if both sides are missing spaces, even though
2363*7c3d14c8STreehugger Robot    # technically should should flag if at least one side is missing a
2364*7c3d14c8STreehugger Robot    # space.  This is done to avoid some false positives with shifts.
2365*7c3d14c8STreehugger Robot    match = Search(r'[^\s<]<([^\s=<].*)', reduced_line)
2366*7c3d14c8STreehugger Robot    if (match and
2367*7c3d14c8STreehugger Robot        not FindNextMatchingAngleBracket(clean_lines, linenum, match.group(1))):
2368*7c3d14c8STreehugger Robot      error(filename, linenum, 'whitespace/operators', 3,
2369*7c3d14c8STreehugger Robot            'Missing spaces around <')
2370*7c3d14c8STreehugger Robot
2371*7c3d14c8STreehugger Robot    # Look for > that is not surrounded by spaces.  Similar to the
2372*7c3d14c8STreehugger Robot    # above, we only trigger if both sides are missing spaces to avoid
2373*7c3d14c8STreehugger Robot    # false positives with shifts.
2374*7c3d14c8STreehugger Robot    match = Search(r'^(.*[^\s>])>[^\s=>]', reduced_line)
2375*7c3d14c8STreehugger Robot    if (match and
2376*7c3d14c8STreehugger Robot        not FindPreviousMatchingAngleBracket(clean_lines, linenum,
2377*7c3d14c8STreehugger Robot                                             match.group(1))):
2378*7c3d14c8STreehugger Robot      error(filename, linenum, 'whitespace/operators', 3,
2379*7c3d14c8STreehugger Robot            'Missing spaces around >')
2380*7c3d14c8STreehugger Robot
2381*7c3d14c8STreehugger Robot  # We allow no-spaces around >> for almost anything.  This is because
2382*7c3d14c8STreehugger Robot  # C++11 allows ">>" to close nested templates, which accounts for
2383*7c3d14c8STreehugger Robot  # most cases when ">>" is not followed by a space.
2384*7c3d14c8STreehugger Robot  #
2385*7c3d14c8STreehugger Robot  # We still warn on ">>" followed by alpha character, because that is
2386*7c3d14c8STreehugger Robot  # likely due to ">>" being used for right shifts, e.g.:
2387*7c3d14c8STreehugger Robot  #   value >> alpha
2388*7c3d14c8STreehugger Robot  #
2389*7c3d14c8STreehugger Robot  # When ">>" is used to close templates, the alphanumeric letter that
2390*7c3d14c8STreehugger Robot  # follows would be part of an identifier, and there should still be
2391*7c3d14c8STreehugger Robot  # a space separating the template type and the identifier.
2392*7c3d14c8STreehugger Robot  #   type<type<type>> alpha
2393*7c3d14c8STreehugger Robot  match = Search(r'>>[a-zA-Z_]', line)
2394*7c3d14c8STreehugger Robot  if match:
2395*7c3d14c8STreehugger Robot    error(filename, linenum, 'whitespace/operators', 3,
2396*7c3d14c8STreehugger Robot          'Missing spaces around >>')
2397*7c3d14c8STreehugger Robot
2398*7c3d14c8STreehugger Robot  # There shouldn't be space around unary operators
2399*7c3d14c8STreehugger Robot  match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line)
2400*7c3d14c8STreehugger Robot  if match:
2401*7c3d14c8STreehugger Robot    error(filename, linenum, 'whitespace/operators', 4,
2402*7c3d14c8STreehugger Robot          'Extra space for operator %s' % match.group(1))
2403*7c3d14c8STreehugger Robot
2404*7c3d14c8STreehugger Robot  # A pet peeve of mine: no spaces after an if, while, switch, or for
2405*7c3d14c8STreehugger Robot  match = Search(r' (if\(|for\(|while\(|switch\()', line)
2406*7c3d14c8STreehugger Robot  if match:
2407*7c3d14c8STreehugger Robot    error(filename, linenum, 'whitespace/parens', 5,
2408*7c3d14c8STreehugger Robot          'Missing space before ( in %s' % match.group(1))
2409*7c3d14c8STreehugger Robot
2410*7c3d14c8STreehugger Robot  # For if/for/while/switch, the left and right parens should be
2411*7c3d14c8STreehugger Robot  # consistent about how many spaces are inside the parens, and
2412*7c3d14c8STreehugger Robot  # there should either be zero or one spaces inside the parens.
2413*7c3d14c8STreehugger Robot  # We don't want: "if ( foo)" or "if ( foo   )".
2414*7c3d14c8STreehugger Robot  # Exception: "for ( ; foo; bar)" and "for (foo; bar; )" are allowed.
2415*7c3d14c8STreehugger Robot  match = Search(r'\b(if|for|while|switch)\s*'
2416*7c3d14c8STreehugger Robot                 r'\(([ ]*)(.).*[^ ]+([ ]*)\)\s*{\s*$',
2417*7c3d14c8STreehugger Robot                 line)
2418*7c3d14c8STreehugger Robot  if match:
2419*7c3d14c8STreehugger Robot    if len(match.group(2)) != len(match.group(4)):
2420*7c3d14c8STreehugger Robot      if not (match.group(3) == ';' and
2421*7c3d14c8STreehugger Robot              len(match.group(2)) == 1 + len(match.group(4)) or
2422*7c3d14c8STreehugger Robot              not match.group(2) and Search(r'\bfor\s*\(.*; \)', line)):
2423*7c3d14c8STreehugger Robot        error(filename, linenum, 'whitespace/parens', 5,
2424*7c3d14c8STreehugger Robot              'Mismatching spaces inside () in %s' % match.group(1))
2425*7c3d14c8STreehugger Robot    if not len(match.group(2)) in [0, 1]:
2426*7c3d14c8STreehugger Robot      error(filename, linenum, 'whitespace/parens', 5,
2427*7c3d14c8STreehugger Robot            'Should have zero or one spaces inside ( and ) in %s' %
2428*7c3d14c8STreehugger Robot            match.group(1))
2429*7c3d14c8STreehugger Robot
2430*7c3d14c8STreehugger Robot  # You should always have a space after a comma (either as fn arg or operator)
2431*7c3d14c8STreehugger Robot  if Search(r',[^\s]', line):
2432*7c3d14c8STreehugger Robot    error(filename, linenum, 'whitespace/comma', 3,
2433*7c3d14c8STreehugger Robot          'Missing space after ,')
2434*7c3d14c8STreehugger Robot
2435*7c3d14c8STreehugger Robot  # You should always have a space after a semicolon
2436*7c3d14c8STreehugger Robot  # except for few corner cases
2437*7c3d14c8STreehugger Robot  # TODO(unknown): clarify if 'if (1) { return 1;}' is requires one more
2438*7c3d14c8STreehugger Robot  # space after ;
2439*7c3d14c8STreehugger Robot  if Search(r';[^\s};\\)/]', line):
2440*7c3d14c8STreehugger Robot    error(filename, linenum, 'whitespace/semicolon', 3,
2441*7c3d14c8STreehugger Robot          'Missing space after ;')
2442*7c3d14c8STreehugger Robot
2443*7c3d14c8STreehugger Robot  # Next we will look for issues with function calls.
2444*7c3d14c8STreehugger Robot  CheckSpacingForFunctionCall(filename, line, linenum, error)
2445*7c3d14c8STreehugger Robot
2446*7c3d14c8STreehugger Robot  # Except after an opening paren, or after another opening brace (in case of
2447*7c3d14c8STreehugger Robot  # an initializer list, for instance), you should have spaces before your
2448*7c3d14c8STreehugger Robot  # braces. And since you should never have braces at the beginning of a line,
2449*7c3d14c8STreehugger Robot  # this is an easy test.
2450*7c3d14c8STreehugger Robot  if Search(r'[^ ({]{', line):
2451*7c3d14c8STreehugger Robot    error(filename, linenum, 'whitespace/braces', 5,
2452*7c3d14c8STreehugger Robot          'Missing space before {')
2453*7c3d14c8STreehugger Robot
2454*7c3d14c8STreehugger Robot  # Make sure '} else {' has spaces.
2455*7c3d14c8STreehugger Robot  if Search(r'}else', line):
2456*7c3d14c8STreehugger Robot    error(filename, linenum, 'whitespace/braces', 5,
2457*7c3d14c8STreehugger Robot          'Missing space before else')
2458*7c3d14c8STreehugger Robot
2459*7c3d14c8STreehugger Robot  # You shouldn't have spaces before your brackets, except maybe after
2460*7c3d14c8STreehugger Robot  # 'delete []' or 'new char * []'.
2461*7c3d14c8STreehugger Robot  if Search(r'\w\s+\[', line) and not Search(r'delete\s+\[', line):
2462*7c3d14c8STreehugger Robot    error(filename, linenum, 'whitespace/braces', 5,
2463*7c3d14c8STreehugger Robot          'Extra space before [')
2464*7c3d14c8STreehugger Robot
2465*7c3d14c8STreehugger Robot  # You shouldn't have a space before a semicolon at the end of the line.
2466*7c3d14c8STreehugger Robot  # There's a special case for "for" since the style guide allows space before
2467*7c3d14c8STreehugger Robot  # the semicolon there.
2468*7c3d14c8STreehugger Robot  if Search(r':\s*;\s*$', line):
2469*7c3d14c8STreehugger Robot    error(filename, linenum, 'whitespace/semicolon', 5,
2470*7c3d14c8STreehugger Robot          'Semicolon defining empty statement. Use {} instead.')
2471*7c3d14c8STreehugger Robot  elif Search(r'^\s*;\s*$', line):
2472*7c3d14c8STreehugger Robot    error(filename, linenum, 'whitespace/semicolon', 5,
2473*7c3d14c8STreehugger Robot          'Line contains only semicolon. If this should be an empty statement, '
2474*7c3d14c8STreehugger Robot          'use {} instead.')
2475*7c3d14c8STreehugger Robot  elif (Search(r'\s+;\s*$', line) and
2476*7c3d14c8STreehugger Robot        not Search(r'\bfor\b', line)):
2477*7c3d14c8STreehugger Robot    error(filename, linenum, 'whitespace/semicolon', 5,
2478*7c3d14c8STreehugger Robot          'Extra space before last semicolon. If this should be an empty '
2479*7c3d14c8STreehugger Robot          'statement, use {} instead.')
2480*7c3d14c8STreehugger Robot
2481*7c3d14c8STreehugger Robot  # In range-based for, we wanted spaces before and after the colon, but
2482*7c3d14c8STreehugger Robot  # not around "::" tokens that might appear.
2483*7c3d14c8STreehugger Robot  if (Search('for *\(.*[^:]:[^: ]', line) or
2484*7c3d14c8STreehugger Robot      Search('for *\(.*[^: ]:[^:]', line)):
2485*7c3d14c8STreehugger Robot    error(filename, linenum, 'whitespace/forcolon', 2,
2486*7c3d14c8STreehugger Robot          'Missing space around colon in range-based for loop')
2487*7c3d14c8STreehugger Robot
2488*7c3d14c8STreehugger Robot
2489*7c3d14c8STreehugger Robotdef CheckSectionSpacing(filename, clean_lines, class_info, linenum, error):
2490*7c3d14c8STreehugger Robot  """Checks for additional blank line issues related to sections.
2491*7c3d14c8STreehugger Robot
2492*7c3d14c8STreehugger Robot  Currently the only thing checked here is blank line before protected/private.
2493*7c3d14c8STreehugger Robot
2494*7c3d14c8STreehugger Robot  Args:
2495*7c3d14c8STreehugger Robot    filename: The name of the current file.
2496*7c3d14c8STreehugger Robot    clean_lines: A CleansedLines instance containing the file.
2497*7c3d14c8STreehugger Robot    class_info: A _ClassInfo objects.
2498*7c3d14c8STreehugger Robot    linenum: The number of the line to check.
2499*7c3d14c8STreehugger Robot    error: The function to call with any errors found.
2500*7c3d14c8STreehugger Robot  """
2501*7c3d14c8STreehugger Robot  # Skip checks if the class is small, where small means 25 lines or less.
2502*7c3d14c8STreehugger Robot  # 25 lines seems like a good cutoff since that's the usual height of
2503*7c3d14c8STreehugger Robot  # terminals, and any class that can't fit in one screen can't really
2504*7c3d14c8STreehugger Robot  # be considered "small".
2505*7c3d14c8STreehugger Robot  #
2506*7c3d14c8STreehugger Robot  # Also skip checks if we are on the first line.  This accounts for
2507*7c3d14c8STreehugger Robot  # classes that look like
2508*7c3d14c8STreehugger Robot  #   class Foo { public: ... };
2509*7c3d14c8STreehugger Robot  #
2510*7c3d14c8STreehugger Robot  # If we didn't find the end of the class, last_line would be zero,
2511*7c3d14c8STreehugger Robot  # and the check will be skipped by the first condition.
2512*7c3d14c8STreehugger Robot  if (class_info.last_line - class_info.starting_linenum <= 24 or
2513*7c3d14c8STreehugger Robot      linenum <= class_info.starting_linenum):
2514*7c3d14c8STreehugger Robot    return
2515*7c3d14c8STreehugger Robot
2516*7c3d14c8STreehugger Robot  matched = Match(r'\s*(public|protected|private):', clean_lines.lines[linenum])
2517*7c3d14c8STreehugger Robot  if matched:
2518*7c3d14c8STreehugger Robot    # Issue warning if the line before public/protected/private was
2519*7c3d14c8STreehugger Robot    # not a blank line, but don't do this if the previous line contains
2520*7c3d14c8STreehugger Robot    # "class" or "struct".  This can happen two ways:
2521*7c3d14c8STreehugger Robot    #  - We are at the beginning of the class.
2522*7c3d14c8STreehugger Robot    #  - We are forward-declaring an inner class that is semantically
2523*7c3d14c8STreehugger Robot    #    private, but needed to be public for implementation reasons.
2524*7c3d14c8STreehugger Robot    # Also ignores cases where the previous line ends with a backslash as can be
2525*7c3d14c8STreehugger Robot    # common when defining classes in C macros.
2526*7c3d14c8STreehugger Robot    prev_line = clean_lines.lines[linenum - 1]
2527*7c3d14c8STreehugger Robot    if (not IsBlankLine(prev_line) and
2528*7c3d14c8STreehugger Robot        not Search(r'\b(class|struct)\b', prev_line) and
2529*7c3d14c8STreehugger Robot        not Search(r'\\$', prev_line)):
2530*7c3d14c8STreehugger Robot      # Try a bit harder to find the beginning of the class.  This is to
2531*7c3d14c8STreehugger Robot      # account for multi-line base-specifier lists, e.g.:
2532*7c3d14c8STreehugger Robot      #   class Derived
2533*7c3d14c8STreehugger Robot      #       : public Base {
2534*7c3d14c8STreehugger Robot      end_class_head = class_info.starting_linenum
2535*7c3d14c8STreehugger Robot      for i in range(class_info.starting_linenum, linenum):
2536*7c3d14c8STreehugger Robot        if Search(r'\{\s*$', clean_lines.lines[i]):
2537*7c3d14c8STreehugger Robot          end_class_head = i
2538*7c3d14c8STreehugger Robot          break
2539*7c3d14c8STreehugger Robot      if end_class_head < linenum - 1:
2540*7c3d14c8STreehugger Robot        error(filename, linenum, 'whitespace/blank_line', 3,
2541*7c3d14c8STreehugger Robot              '"%s:" should be preceded by a blank line' % matched.group(1))
2542*7c3d14c8STreehugger Robot
2543*7c3d14c8STreehugger Robot
2544*7c3d14c8STreehugger Robotdef GetPreviousNonBlankLine(clean_lines, linenum):
2545*7c3d14c8STreehugger Robot  """Return the most recent non-blank line and its line number.
2546*7c3d14c8STreehugger Robot
2547*7c3d14c8STreehugger Robot  Args:
2548*7c3d14c8STreehugger Robot    clean_lines: A CleansedLines instance containing the file contents.
2549*7c3d14c8STreehugger Robot    linenum: The number of the line to check.
2550*7c3d14c8STreehugger Robot
2551*7c3d14c8STreehugger Robot  Returns:
2552*7c3d14c8STreehugger Robot    A tuple with two elements.  The first element is the contents of the last
2553*7c3d14c8STreehugger Robot    non-blank line before the current line, or the empty string if this is the
2554*7c3d14c8STreehugger Robot    first non-blank line.  The second is the line number of that line, or -1
2555*7c3d14c8STreehugger Robot    if this is the first non-blank line.
2556*7c3d14c8STreehugger Robot  """
2557*7c3d14c8STreehugger Robot
2558*7c3d14c8STreehugger Robot  prevlinenum = linenum - 1
2559*7c3d14c8STreehugger Robot  while prevlinenum >= 0:
2560*7c3d14c8STreehugger Robot    prevline = clean_lines.elided[prevlinenum]
2561*7c3d14c8STreehugger Robot    if not IsBlankLine(prevline):     # if not a blank line...
2562*7c3d14c8STreehugger Robot      return (prevline, prevlinenum)
2563*7c3d14c8STreehugger Robot    prevlinenum -= 1
2564*7c3d14c8STreehugger Robot  return ('', -1)
2565*7c3d14c8STreehugger Robot
2566*7c3d14c8STreehugger Robot
2567*7c3d14c8STreehugger Robotdef CheckBraces(filename, clean_lines, linenum, error):
2568*7c3d14c8STreehugger Robot  """Looks for misplaced braces (e.g. at the end of line).
2569*7c3d14c8STreehugger Robot
2570*7c3d14c8STreehugger Robot  Args:
2571*7c3d14c8STreehugger Robot    filename: The name of the current file.
2572*7c3d14c8STreehugger Robot    clean_lines: A CleansedLines instance containing the file.
2573*7c3d14c8STreehugger Robot    linenum: The number of the line to check.
2574*7c3d14c8STreehugger Robot    error: The function to call with any errors found.
2575*7c3d14c8STreehugger Robot  """
2576*7c3d14c8STreehugger Robot
2577*7c3d14c8STreehugger Robot  line = clean_lines.elided[linenum]        # get rid of comments and strings
2578*7c3d14c8STreehugger Robot
2579*7c3d14c8STreehugger Robot  if Match(r'\s*{\s*$', line):
2580*7c3d14c8STreehugger Robot    # We allow an open brace to start a line in the case where someone
2581*7c3d14c8STreehugger Robot    # is using braces in a block to explicitly create a new scope,
2582*7c3d14c8STreehugger Robot    # which is commonly used to control the lifetime of
2583*7c3d14c8STreehugger Robot    # stack-allocated variables.  We don't detect this perfectly: we
2584*7c3d14c8STreehugger Robot    # just don't complain if the last non-whitespace character on the
2585*7c3d14c8STreehugger Robot    # previous non-blank line is ';', ':', '{', or '}', or if the previous
2586*7c3d14c8STreehugger Robot    # line starts a preprocessor block.
2587*7c3d14c8STreehugger Robot    prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
2588*7c3d14c8STreehugger Robot    if (not Search(r'[;:}{]\s*$', prevline) and
2589*7c3d14c8STreehugger Robot        not Match(r'\s*#', prevline)):
2590*7c3d14c8STreehugger Robot      error(filename, linenum, 'whitespace/braces', 4,
2591*7c3d14c8STreehugger Robot            '{ should almost always be at the end of the previous line')
2592*7c3d14c8STreehugger Robot
2593*7c3d14c8STreehugger Robot  # An else clause should be on the same line as the preceding closing brace.
2594*7c3d14c8STreehugger Robot  if Match(r'\s*else\s*', line):
2595*7c3d14c8STreehugger Robot    prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
2596*7c3d14c8STreehugger Robot    if Match(r'\s*}\s*$', prevline):
2597*7c3d14c8STreehugger Robot      error(filename, linenum, 'whitespace/newline', 4,
2598*7c3d14c8STreehugger Robot            'An else should appear on the same line as the preceding }')
2599*7c3d14c8STreehugger Robot
2600*7c3d14c8STreehugger Robot  # If braces come on one side of an else, they should be on both.
2601*7c3d14c8STreehugger Robot  # However, we have to worry about "else if" that spans multiple lines!
2602*7c3d14c8STreehugger Robot  if Search(r'}\s*else[^{]*$', line) or Match(r'[^}]*else\s*{', line):
2603*7c3d14c8STreehugger Robot    if Search(r'}\s*else if([^{]*)$', line):       # could be multi-line if
2604*7c3d14c8STreehugger Robot      # find the ( after the if
2605*7c3d14c8STreehugger Robot      pos = line.find('else if')
2606*7c3d14c8STreehugger Robot      pos = line.find('(', pos)
2607*7c3d14c8STreehugger Robot      if pos > 0:
2608*7c3d14c8STreehugger Robot        (endline, _, endpos) = CloseExpression(clean_lines, linenum, pos)
2609*7c3d14c8STreehugger Robot        if endline[endpos:].find('{') == -1:    # must be brace after if
2610*7c3d14c8STreehugger Robot          error(filename, linenum, 'readability/braces', 5,
2611*7c3d14c8STreehugger Robot                'If an else has a brace on one side, it should have it on both')
2612*7c3d14c8STreehugger Robot    else:            # common case: else not followed by a multi-line if
2613*7c3d14c8STreehugger Robot      error(filename, linenum, 'readability/braces', 5,
2614*7c3d14c8STreehugger Robot            'If an else has a brace on one side, it should have it on both')
2615*7c3d14c8STreehugger Robot
2616*7c3d14c8STreehugger Robot  # Likewise, an else should never have the else clause on the same line
2617*7c3d14c8STreehugger Robot  if Search(r'\belse [^\s{]', line) and not Search(r'\belse if\b', line):
2618*7c3d14c8STreehugger Robot    error(filename, linenum, 'whitespace/newline', 4,
2619*7c3d14c8STreehugger Robot          'Else clause should never be on same line as else (use 2 lines)')
2620*7c3d14c8STreehugger Robot
2621*7c3d14c8STreehugger Robot  # In the same way, a do/while should never be on one line
2622*7c3d14c8STreehugger Robot  if Match(r'\s*do [^\s{]', line):
2623*7c3d14c8STreehugger Robot    error(filename, linenum, 'whitespace/newline', 4,
2624*7c3d14c8STreehugger Robot          'do/while clauses should not be on a single line')
2625*7c3d14c8STreehugger Robot
2626*7c3d14c8STreehugger Robot  # Braces shouldn't be followed by a ; unless they're defining a struct
2627*7c3d14c8STreehugger Robot  # or initializing an array.
2628*7c3d14c8STreehugger Robot  # We can't tell in general, but we can for some common cases.
2629*7c3d14c8STreehugger Robot  prevlinenum = linenum
2630*7c3d14c8STreehugger Robot  while True:
2631*7c3d14c8STreehugger Robot    (prevline, prevlinenum) = GetPreviousNonBlankLine(clean_lines, prevlinenum)
2632*7c3d14c8STreehugger Robot    if Match(r'\s+{.*}\s*;', line) and not prevline.count(';'):
2633*7c3d14c8STreehugger Robot      line = prevline + line
2634*7c3d14c8STreehugger Robot    else:
2635*7c3d14c8STreehugger Robot      break
2636*7c3d14c8STreehugger Robot  if (Search(r'{.*}\s*;', line) and
2637*7c3d14c8STreehugger Robot      line.count('{') == line.count('}') and
2638*7c3d14c8STreehugger Robot      not Search(r'struct|class|enum|\s*=\s*{', line)):
2639*7c3d14c8STreehugger Robot    error(filename, linenum, 'readability/braces', 4,
2640*7c3d14c8STreehugger Robot          "You don't need a ; after a }")
2641*7c3d14c8STreehugger Robot
2642*7c3d14c8STreehugger Robot
2643*7c3d14c8STreehugger Robotdef CheckEmptyLoopBody(filename, clean_lines, linenum, error):
2644*7c3d14c8STreehugger Robot  """Loop for empty loop body with only a single semicolon.
2645*7c3d14c8STreehugger Robot
2646*7c3d14c8STreehugger Robot  Args:
2647*7c3d14c8STreehugger Robot    filename: The name of the current file.
2648*7c3d14c8STreehugger Robot    clean_lines: A CleansedLines instance containing the file.
2649*7c3d14c8STreehugger Robot    linenum: The number of the line to check.
2650*7c3d14c8STreehugger Robot    error: The function to call with any errors found.
2651*7c3d14c8STreehugger Robot  """
2652*7c3d14c8STreehugger Robot
2653*7c3d14c8STreehugger Robot  # Search for loop keywords at the beginning of the line.  Because only
2654*7c3d14c8STreehugger Robot  # whitespaces are allowed before the keywords, this will also ignore most
2655*7c3d14c8STreehugger Robot  # do-while-loops, since those lines should start with closing brace.
2656*7c3d14c8STreehugger Robot  line = clean_lines.elided[linenum]
2657*7c3d14c8STreehugger Robot  if Match(r'\s*(for|while)\s*\(', line):
2658*7c3d14c8STreehugger Robot    # Find the end of the conditional expression
2659*7c3d14c8STreehugger Robot    (end_line, end_linenum, end_pos) = CloseExpression(
2660*7c3d14c8STreehugger Robot        clean_lines, linenum, line.find('('))
2661*7c3d14c8STreehugger Robot
2662*7c3d14c8STreehugger Robot    # Output warning if what follows the condition expression is a semicolon.
2663*7c3d14c8STreehugger Robot    # No warning for all other cases, including whitespace or newline, since we
2664*7c3d14c8STreehugger Robot    # have a separate check for semicolons preceded by whitespace.
2665*7c3d14c8STreehugger Robot    if end_pos >= 0 and Match(r';', end_line[end_pos:]):
2666*7c3d14c8STreehugger Robot      error(filename, end_linenum, 'whitespace/empty_loop_body', 5,
2667*7c3d14c8STreehugger Robot            'Empty loop bodies should use {} or continue')
2668*7c3d14c8STreehugger Robot
2669*7c3d14c8STreehugger Robot
2670*7c3d14c8STreehugger Robotdef ReplaceableCheck(operator, macro, line):
2671*7c3d14c8STreehugger Robot  """Determine whether a basic CHECK can be replaced with a more specific one.
2672*7c3d14c8STreehugger Robot
2673*7c3d14c8STreehugger Robot  For example suggest using CHECK_EQ instead of CHECK(a == b) and
2674*7c3d14c8STreehugger Robot  similarly for CHECK_GE, CHECK_GT, CHECK_LE, CHECK_LT, CHECK_NE.
2675*7c3d14c8STreehugger Robot
2676*7c3d14c8STreehugger Robot  Args:
2677*7c3d14c8STreehugger Robot    operator: The C++ operator used in the CHECK.
2678*7c3d14c8STreehugger Robot    macro: The CHECK or EXPECT macro being called.
2679*7c3d14c8STreehugger Robot    line: The current source line.
2680*7c3d14c8STreehugger Robot
2681*7c3d14c8STreehugger Robot  Returns:
2682*7c3d14c8STreehugger Robot    True if the CHECK can be replaced with a more specific one.
2683*7c3d14c8STreehugger Robot  """
2684*7c3d14c8STreehugger Robot
2685*7c3d14c8STreehugger Robot  # This matches decimal and hex integers, strings, and chars (in that order).
2686*7c3d14c8STreehugger Robot  match_constant = r'([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')'
2687*7c3d14c8STreehugger Robot
2688*7c3d14c8STreehugger Robot  # Expression to match two sides of the operator with something that
2689*7c3d14c8STreehugger Robot  # looks like a literal, since CHECK(x == iterator) won't compile.
2690*7c3d14c8STreehugger Robot  # This means we can't catch all the cases where a more specific
2691*7c3d14c8STreehugger Robot  # CHECK is possible, but it's less annoying than dealing with
2692*7c3d14c8STreehugger Robot  # extraneous warnings.
2693*7c3d14c8STreehugger Robot  match_this = (r'\s*' + macro + r'\((\s*' +
2694*7c3d14c8STreehugger Robot                match_constant + r'\s*' + operator + r'[^<>].*|'
2695*7c3d14c8STreehugger Robot                r'.*[^<>]' + operator + r'\s*' + match_constant +
2696*7c3d14c8STreehugger Robot                r'\s*\))')
2697*7c3d14c8STreehugger Robot
2698*7c3d14c8STreehugger Robot  # Don't complain about CHECK(x == NULL) or similar because
2699*7c3d14c8STreehugger Robot  # CHECK_EQ(x, NULL) won't compile (requires a cast).
2700*7c3d14c8STreehugger Robot  # Also, don't complain about more complex boolean expressions
2701*7c3d14c8STreehugger Robot  # involving && or || such as CHECK(a == b || c == d).
2702*7c3d14c8STreehugger Robot  return Match(match_this, line) and not Search(r'NULL|&&|\|\|', line)
2703*7c3d14c8STreehugger Robot
2704*7c3d14c8STreehugger Robot
2705*7c3d14c8STreehugger Robotdef CheckCheck(filename, clean_lines, linenum, error):
2706*7c3d14c8STreehugger Robot  """Checks the use of CHECK and EXPECT macros.
2707*7c3d14c8STreehugger Robot
2708*7c3d14c8STreehugger Robot  Args:
2709*7c3d14c8STreehugger Robot    filename: The name of the current file.
2710*7c3d14c8STreehugger Robot    clean_lines: A CleansedLines instance containing the file.
2711*7c3d14c8STreehugger Robot    linenum: The number of the line to check.
2712*7c3d14c8STreehugger Robot    error: The function to call with any errors found.
2713*7c3d14c8STreehugger Robot  """
2714*7c3d14c8STreehugger Robot
2715*7c3d14c8STreehugger Robot  # Decide the set of replacement macros that should be suggested
2716*7c3d14c8STreehugger Robot  raw_lines = clean_lines.raw_lines
2717*7c3d14c8STreehugger Robot  current_macro = ''
2718*7c3d14c8STreehugger Robot  for macro in _CHECK_MACROS:
2719*7c3d14c8STreehugger Robot    if raw_lines[linenum].find(macro) >= 0:
2720*7c3d14c8STreehugger Robot      current_macro = macro
2721*7c3d14c8STreehugger Robot      break
2722*7c3d14c8STreehugger Robot  if not current_macro:
2723*7c3d14c8STreehugger Robot    # Don't waste time here if line doesn't contain 'CHECK' or 'EXPECT'
2724*7c3d14c8STreehugger Robot    return
2725*7c3d14c8STreehugger Robot
2726*7c3d14c8STreehugger Robot  line = clean_lines.elided[linenum]        # get rid of comments and strings
2727*7c3d14c8STreehugger Robot
2728*7c3d14c8STreehugger Robot  # Encourage replacing plain CHECKs with CHECK_EQ/CHECK_NE/etc.
2729*7c3d14c8STreehugger Robot  for operator in ['==', '!=', '>=', '>', '<=', '<']:
2730*7c3d14c8STreehugger Robot    if ReplaceableCheck(operator, current_macro, line):
2731*7c3d14c8STreehugger Robot      error(filename, linenum, 'readability/check', 2,
2732*7c3d14c8STreehugger Robot            'Consider using %s instead of %s(a %s b)' % (
2733*7c3d14c8STreehugger Robot                _CHECK_REPLACEMENT[current_macro][operator],
2734*7c3d14c8STreehugger Robot                current_macro, operator))
2735*7c3d14c8STreehugger Robot      break
2736*7c3d14c8STreehugger Robot
2737*7c3d14c8STreehugger Robot
2738*7c3d14c8STreehugger Robotdef CheckAltTokens(filename, clean_lines, linenum, error):
2739*7c3d14c8STreehugger Robot  """Check alternative keywords being used in boolean expressions.
2740*7c3d14c8STreehugger Robot
2741*7c3d14c8STreehugger Robot  Args:
2742*7c3d14c8STreehugger Robot    filename: The name of the current file.
2743*7c3d14c8STreehugger Robot    clean_lines: A CleansedLines instance containing the file.
2744*7c3d14c8STreehugger Robot    linenum: The number of the line to check.
2745*7c3d14c8STreehugger Robot    error: The function to call with any errors found.
2746*7c3d14c8STreehugger Robot  """
2747*7c3d14c8STreehugger Robot  line = clean_lines.elided[linenum]
2748*7c3d14c8STreehugger Robot
2749*7c3d14c8STreehugger Robot  # Avoid preprocessor lines
2750*7c3d14c8STreehugger Robot  if Match(r'^\s*#', line):
2751*7c3d14c8STreehugger Robot    return
2752*7c3d14c8STreehugger Robot
2753*7c3d14c8STreehugger Robot  # Last ditch effort to avoid multi-line comments.  This will not help
2754*7c3d14c8STreehugger Robot  # if the comment started before the current line or ended after the
2755*7c3d14c8STreehugger Robot  # current line, but it catches most of the false positives.  At least,
2756*7c3d14c8STreehugger Robot  # it provides a way to workaround this warning for people who use
2757*7c3d14c8STreehugger Robot  # multi-line comments in preprocessor macros.
2758*7c3d14c8STreehugger Robot  #
2759*7c3d14c8STreehugger Robot  # TODO(unknown): remove this once cpplint has better support for
2760*7c3d14c8STreehugger Robot  # multi-line comments.
2761*7c3d14c8STreehugger Robot  if line.find('/*') >= 0 or line.find('*/') >= 0:
2762*7c3d14c8STreehugger Robot    return
2763*7c3d14c8STreehugger Robot
2764*7c3d14c8STreehugger Robot  for match in _ALT_TOKEN_REPLACEMENT_PATTERN.finditer(line):
2765*7c3d14c8STreehugger Robot    error(filename, linenum, 'readability/alt_tokens', 2,
2766*7c3d14c8STreehugger Robot          'Use operator %s instead of %s' % (
2767*7c3d14c8STreehugger Robot              _ALT_TOKEN_REPLACEMENT[match.group(1)], match.group(1)))
2768*7c3d14c8STreehugger Robot
2769*7c3d14c8STreehugger Robot
2770*7c3d14c8STreehugger Robotdef GetLineWidth(line):
2771*7c3d14c8STreehugger Robot  """Determines the width of the line in column positions.
2772*7c3d14c8STreehugger Robot
2773*7c3d14c8STreehugger Robot  Args:
2774*7c3d14c8STreehugger Robot    line: A string, which may be a Unicode string.
2775*7c3d14c8STreehugger Robot
2776*7c3d14c8STreehugger Robot  Returns:
2777*7c3d14c8STreehugger Robot    The width of the line in column positions, accounting for Unicode
2778*7c3d14c8STreehugger Robot    combining characters and wide characters.
2779*7c3d14c8STreehugger Robot  """
2780*7c3d14c8STreehugger Robot  if isinstance(line, unicode):
2781*7c3d14c8STreehugger Robot    width = 0
2782*7c3d14c8STreehugger Robot    for uc in unicodedata.normalize('NFC', line):
2783*7c3d14c8STreehugger Robot      if unicodedata.east_asian_width(uc) in ('W', 'F'):
2784*7c3d14c8STreehugger Robot        width += 2
2785*7c3d14c8STreehugger Robot      elif not unicodedata.combining(uc):
2786*7c3d14c8STreehugger Robot        width += 1
2787*7c3d14c8STreehugger Robot    return width
2788*7c3d14c8STreehugger Robot  else:
2789*7c3d14c8STreehugger Robot    return len(line)
2790*7c3d14c8STreehugger Robot
2791*7c3d14c8STreehugger Robot
2792*7c3d14c8STreehugger Robotdef CheckStyle(filename, clean_lines, linenum, file_extension, nesting_state,
2793*7c3d14c8STreehugger Robot               error):
2794*7c3d14c8STreehugger Robot  """Checks rules from the 'C++ style rules' section of cppguide.html.
2795*7c3d14c8STreehugger Robot
2796*7c3d14c8STreehugger Robot  Most of these rules are hard to test (naming, comment style), but we
2797*7c3d14c8STreehugger Robot  do what we can.  In particular we check for 2-space indents, line lengths,
2798*7c3d14c8STreehugger Robot  tab usage, spaces inside code, etc.
2799*7c3d14c8STreehugger Robot
2800*7c3d14c8STreehugger Robot  Args:
2801*7c3d14c8STreehugger Robot    filename: The name of the current file.
2802*7c3d14c8STreehugger Robot    clean_lines: A CleansedLines instance containing the file.
2803*7c3d14c8STreehugger Robot    linenum: The number of the line to check.
2804*7c3d14c8STreehugger Robot    file_extension: The extension (without the dot) of the filename.
2805*7c3d14c8STreehugger Robot    nesting_state: A _NestingState instance which maintains information about
2806*7c3d14c8STreehugger Robot                   the current stack of nested blocks being parsed.
2807*7c3d14c8STreehugger Robot    error: The function to call with any errors found.
2808*7c3d14c8STreehugger Robot  """
2809*7c3d14c8STreehugger Robot
2810*7c3d14c8STreehugger Robot  raw_lines = clean_lines.raw_lines
2811*7c3d14c8STreehugger Robot  line = raw_lines[linenum]
2812*7c3d14c8STreehugger Robot
2813*7c3d14c8STreehugger Robot  if line.find('\t') != -1:
2814*7c3d14c8STreehugger Robot    error(filename, linenum, 'whitespace/tab', 1,
2815*7c3d14c8STreehugger Robot          'Tab found; better to use spaces')
2816*7c3d14c8STreehugger Robot
2817*7c3d14c8STreehugger Robot  # One or three blank spaces at the beginning of the line is weird; it's
2818*7c3d14c8STreehugger Robot  # hard to reconcile that with 2-space indents.
2819*7c3d14c8STreehugger Robot  # NOTE: here are the conditions rob pike used for his tests.  Mine aren't
2820*7c3d14c8STreehugger Robot  # as sophisticated, but it may be worth becoming so:  RLENGTH==initial_spaces
2821*7c3d14c8STreehugger Robot  # if(RLENGTH > 20) complain = 0;
2822*7c3d14c8STreehugger Robot  # if(match($0, " +(error|private|public|protected):")) complain = 0;
2823*7c3d14c8STreehugger Robot  # if(match(prev, "&& *$")) complain = 0;
2824*7c3d14c8STreehugger Robot  # if(match(prev, "\\|\\| *$")) complain = 0;
2825*7c3d14c8STreehugger Robot  # if(match(prev, "[\",=><] *$")) complain = 0;
2826*7c3d14c8STreehugger Robot  # if(match($0, " <<")) complain = 0;
2827*7c3d14c8STreehugger Robot  # if(match(prev, " +for \\(")) complain = 0;
2828*7c3d14c8STreehugger Robot  # if(prevodd && match(prevprev, " +for \\(")) complain = 0;
2829*7c3d14c8STreehugger Robot  initial_spaces = 0
2830*7c3d14c8STreehugger Robot  cleansed_line = clean_lines.elided[linenum]
2831*7c3d14c8STreehugger Robot  while initial_spaces < len(line) and line[initial_spaces] == ' ':
2832*7c3d14c8STreehugger Robot    initial_spaces += 1
2833*7c3d14c8STreehugger Robot  if line and line[-1].isspace():
2834*7c3d14c8STreehugger Robot    error(filename, linenum, 'whitespace/end_of_line', 4,
2835*7c3d14c8STreehugger Robot          'Line ends in whitespace.  Consider deleting these extra spaces.')
2836*7c3d14c8STreehugger Robot  # There are certain situations we allow one space, notably for labels
2837*7c3d14c8STreehugger Robot  elif ((initial_spaces == 1 or initial_spaces == 3) and
2838*7c3d14c8STreehugger Robot        not Match(r'\s*\w+\s*:\s*$', cleansed_line)):
2839*7c3d14c8STreehugger Robot    error(filename, linenum, 'whitespace/indent', 3,
2840*7c3d14c8STreehugger Robot          'Weird number of spaces at line-start.  '
2841*7c3d14c8STreehugger Robot          'Are you using a 2-space indent?')
2842*7c3d14c8STreehugger Robot  # Labels should always be indented at least one space.
2843*7c3d14c8STreehugger Robot  elif not initial_spaces and line[:2] != '//' and Search(r'[^:]:\s*$',
2844*7c3d14c8STreehugger Robot                                                          line):
2845*7c3d14c8STreehugger Robot    error(filename, linenum, 'whitespace/labels', 4,
2846*7c3d14c8STreehugger Robot          'Labels should always be indented at least one space.  '
2847*7c3d14c8STreehugger Robot          'If this is a member-initializer list in a constructor or '
2848*7c3d14c8STreehugger Robot          'the base class list in a class definition, the colon should '
2849*7c3d14c8STreehugger Robot          'be on the following line.')
2850*7c3d14c8STreehugger Robot
2851*7c3d14c8STreehugger Robot
2852*7c3d14c8STreehugger Robot  # Check if the line is a header guard.
2853*7c3d14c8STreehugger Robot  is_header_guard = False
2854*7c3d14c8STreehugger Robot  if file_extension == 'h':
2855*7c3d14c8STreehugger Robot    cppvar = GetHeaderGuardCPPVariable(filename)
2856*7c3d14c8STreehugger Robot    if (line.startswith('#ifndef %s' % cppvar) or
2857*7c3d14c8STreehugger Robot        line.startswith('#define %s' % cppvar) or
2858*7c3d14c8STreehugger Robot        line.startswith('#endif  // %s' % cppvar)):
2859*7c3d14c8STreehugger Robot      is_header_guard = True
2860*7c3d14c8STreehugger Robot  # #include lines and header guards can be long, since there's no clean way to
2861*7c3d14c8STreehugger Robot  # split them.
2862*7c3d14c8STreehugger Robot  #
2863*7c3d14c8STreehugger Robot  # URLs can be long too.  It's possible to split these, but it makes them
2864*7c3d14c8STreehugger Robot  # harder to cut&paste.
2865*7c3d14c8STreehugger Robot  #
2866*7c3d14c8STreehugger Robot  # The "$Id:...$" comment may also get very long without it being the
2867*7c3d14c8STreehugger Robot  # developers fault.
2868*7c3d14c8STreehugger Robot  if (not line.startswith('#include') and not is_header_guard and
2869*7c3d14c8STreehugger Robot      not Match(r'^\s*//.*http(s?)://\S*$', line) and
2870*7c3d14c8STreehugger Robot      not Match(r'^// \$Id:.*#[0-9]+ \$$', line)):
2871*7c3d14c8STreehugger Robot    line_width = GetLineWidth(line)
2872*7c3d14c8STreehugger Robot    if line_width > 100:
2873*7c3d14c8STreehugger Robot      error(filename, linenum, 'whitespace/line_length', 4,
2874*7c3d14c8STreehugger Robot            'Lines should very rarely be longer than 100 characters')
2875*7c3d14c8STreehugger Robot    elif line_width > 80:
2876*7c3d14c8STreehugger Robot      error(filename, linenum, 'whitespace/line_length', 2,
2877*7c3d14c8STreehugger Robot            'Lines should be <= 80 characters long')
2878*7c3d14c8STreehugger Robot
2879*7c3d14c8STreehugger Robot  if (cleansed_line.count(';') > 1 and
2880*7c3d14c8STreehugger Robot      # for loops are allowed two ;'s (and may run over two lines).
2881*7c3d14c8STreehugger Robot      cleansed_line.find('for') == -1 and
2882*7c3d14c8STreehugger Robot      (GetPreviousNonBlankLine(clean_lines, linenum)[0].find('for') == -1 or
2883*7c3d14c8STreehugger Robot       GetPreviousNonBlankLine(clean_lines, linenum)[0].find(';') != -1) and
2884*7c3d14c8STreehugger Robot      # It's ok to have many commands in a switch case that fits in 1 line
2885*7c3d14c8STreehugger Robot      not ((cleansed_line.find('case ') != -1 or
2886*7c3d14c8STreehugger Robot            cleansed_line.find('default:') != -1) and
2887*7c3d14c8STreehugger Robot           cleansed_line.find('break;') != -1)):
2888*7c3d14c8STreehugger Robot    error(filename, linenum, 'whitespace/newline', 0,
2889*7c3d14c8STreehugger Robot          'More than one command on the same line')
2890*7c3d14c8STreehugger Robot
2891*7c3d14c8STreehugger Robot  # Some more style checks
2892*7c3d14c8STreehugger Robot  CheckBraces(filename, clean_lines, linenum, error)
2893*7c3d14c8STreehugger Robot  CheckEmptyLoopBody(filename, clean_lines, linenum, error)
2894*7c3d14c8STreehugger Robot  CheckAccess(filename, clean_lines, linenum, nesting_state, error)
2895*7c3d14c8STreehugger Robot  CheckSpacing(filename, clean_lines, linenum, nesting_state, error)
2896*7c3d14c8STreehugger Robot  CheckCheck(filename, clean_lines, linenum, error)
2897*7c3d14c8STreehugger Robot  CheckAltTokens(filename, clean_lines, linenum, error)
2898*7c3d14c8STreehugger Robot  classinfo = nesting_state.InnermostClass()
2899*7c3d14c8STreehugger Robot  if classinfo:
2900*7c3d14c8STreehugger Robot    CheckSectionSpacing(filename, clean_lines, classinfo, linenum, error)
2901*7c3d14c8STreehugger Robot
2902*7c3d14c8STreehugger Robot
2903*7c3d14c8STreehugger Robot_RE_PATTERN_INCLUDE_NEW_STYLE = re.compile(r'#include +"[^/]+\.h"')
2904*7c3d14c8STreehugger Robot_RE_PATTERN_INCLUDE = re.compile(r'^\s*#\s*include\s*([<"])([^>"]*)[>"].*$')
2905*7c3d14c8STreehugger Robot# Matches the first component of a filename delimited by -s and _s. That is:
2906*7c3d14c8STreehugger Robot#  _RE_FIRST_COMPONENT.match('foo').group(0) == 'foo'
2907*7c3d14c8STreehugger Robot#  _RE_FIRST_COMPONENT.match('foo.cc').group(0) == 'foo'
2908*7c3d14c8STreehugger Robot#  _RE_FIRST_COMPONENT.match('foo-bar_baz.cc').group(0) == 'foo'
2909*7c3d14c8STreehugger Robot#  _RE_FIRST_COMPONENT.match('foo_bar-baz.cc').group(0) == 'foo'
2910*7c3d14c8STreehugger Robot_RE_FIRST_COMPONENT = re.compile(r'^[^-_.]+')
2911*7c3d14c8STreehugger Robot
2912*7c3d14c8STreehugger Robot
2913*7c3d14c8STreehugger Robotdef _DropCommonSuffixes(filename):
2914*7c3d14c8STreehugger Robot  """Drops common suffixes like _test.cc or -inl.h from filename.
2915*7c3d14c8STreehugger Robot
2916*7c3d14c8STreehugger Robot  For example:
2917*7c3d14c8STreehugger Robot    >>> _DropCommonSuffixes('foo/foo-inl.h')
2918*7c3d14c8STreehugger Robot    'foo/foo'
2919*7c3d14c8STreehugger Robot    >>> _DropCommonSuffixes('foo/bar/foo.cc')
2920*7c3d14c8STreehugger Robot    'foo/bar/foo'
2921*7c3d14c8STreehugger Robot    >>> _DropCommonSuffixes('foo/foo_internal.h')
2922*7c3d14c8STreehugger Robot    'foo/foo'
2923*7c3d14c8STreehugger Robot    >>> _DropCommonSuffixes('foo/foo_unusualinternal.h')
2924*7c3d14c8STreehugger Robot    'foo/foo_unusualinternal'
2925*7c3d14c8STreehugger Robot
2926*7c3d14c8STreehugger Robot  Args:
2927*7c3d14c8STreehugger Robot    filename: The input filename.
2928*7c3d14c8STreehugger Robot
2929*7c3d14c8STreehugger Robot  Returns:
2930*7c3d14c8STreehugger Robot    The filename with the common suffix removed.
2931*7c3d14c8STreehugger Robot  """
2932*7c3d14c8STreehugger Robot  for suffix in ('test.cc', 'regtest.cc', 'unittest.cc',
2933*7c3d14c8STreehugger Robot                 'inl.h', 'impl.h', 'internal.h'):
2934*7c3d14c8STreehugger Robot    if (filename.endswith(suffix) and len(filename) > len(suffix) and
2935*7c3d14c8STreehugger Robot        filename[-len(suffix) - 1] in ('-', '_')):
2936*7c3d14c8STreehugger Robot      return filename[:-len(suffix) - 1]
2937*7c3d14c8STreehugger Robot  return os.path.splitext(filename)[0]
2938*7c3d14c8STreehugger Robot
2939*7c3d14c8STreehugger Robot
2940*7c3d14c8STreehugger Robotdef _IsTestFilename(filename):
2941*7c3d14c8STreehugger Robot  """Determines if the given filename has a suffix that identifies it as a test.
2942*7c3d14c8STreehugger Robot
2943*7c3d14c8STreehugger Robot  Args:
2944*7c3d14c8STreehugger Robot    filename: The input filename.
2945*7c3d14c8STreehugger Robot
2946*7c3d14c8STreehugger Robot  Returns:
2947*7c3d14c8STreehugger Robot    True if 'filename' looks like a test, False otherwise.
2948*7c3d14c8STreehugger Robot  """
2949*7c3d14c8STreehugger Robot  if (filename.endswith('_test.cc') or
2950*7c3d14c8STreehugger Robot      filename.endswith('_unittest.cc') or
2951*7c3d14c8STreehugger Robot      filename.endswith('_regtest.cc')):
2952*7c3d14c8STreehugger Robot    return True
2953*7c3d14c8STreehugger Robot  else:
2954*7c3d14c8STreehugger Robot    return False
2955*7c3d14c8STreehugger Robot
2956*7c3d14c8STreehugger Robot
2957*7c3d14c8STreehugger Robotdef _ClassifyInclude(fileinfo, include, is_system):
2958*7c3d14c8STreehugger Robot  """Figures out what kind of header 'include' is.
2959*7c3d14c8STreehugger Robot
2960*7c3d14c8STreehugger Robot  Args:
2961*7c3d14c8STreehugger Robot    fileinfo: The current file cpplint is running over. A FileInfo instance.
2962*7c3d14c8STreehugger Robot    include: The path to a #included file.
2963*7c3d14c8STreehugger Robot    is_system: True if the #include used <> rather than "".
2964*7c3d14c8STreehugger Robot
2965*7c3d14c8STreehugger Robot  Returns:
2966*7c3d14c8STreehugger Robot    One of the _XXX_HEADER constants.
2967*7c3d14c8STreehugger Robot
2968*7c3d14c8STreehugger Robot  For example:
2969*7c3d14c8STreehugger Robot    >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'stdio.h', True)
2970*7c3d14c8STreehugger Robot    _C_SYS_HEADER
2971*7c3d14c8STreehugger Robot    >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'string', True)
2972*7c3d14c8STreehugger Robot    _CPP_SYS_HEADER
2973*7c3d14c8STreehugger Robot    >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', False)
2974*7c3d14c8STreehugger Robot    _LIKELY_MY_HEADER
2975*7c3d14c8STreehugger Robot    >>> _ClassifyInclude(FileInfo('foo/foo_unknown_extension.cc'),
2976*7c3d14c8STreehugger Robot    ...                  'bar/foo_other_ext.h', False)
2977*7c3d14c8STreehugger Robot    _POSSIBLE_MY_HEADER
2978*7c3d14c8STreehugger Robot    >>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/bar.h', False)
2979*7c3d14c8STreehugger Robot    _OTHER_HEADER
2980*7c3d14c8STreehugger Robot  """
2981*7c3d14c8STreehugger Robot  # This is a list of all standard c++ header files, except
2982*7c3d14c8STreehugger Robot  # those already checked for above.
2983*7c3d14c8STreehugger Robot  is_stl_h = include in _STL_HEADERS
2984*7c3d14c8STreehugger Robot  is_cpp_h = is_stl_h or include in _CPP_HEADERS
2985*7c3d14c8STreehugger Robot
2986*7c3d14c8STreehugger Robot  if is_system:
2987*7c3d14c8STreehugger Robot    if is_cpp_h:
2988*7c3d14c8STreehugger Robot      return _CPP_SYS_HEADER
2989*7c3d14c8STreehugger Robot    else:
2990*7c3d14c8STreehugger Robot      return _C_SYS_HEADER
2991*7c3d14c8STreehugger Robot
2992*7c3d14c8STreehugger Robot  # If the target file and the include we're checking share a
2993*7c3d14c8STreehugger Robot  # basename when we drop common extensions, and the include
2994*7c3d14c8STreehugger Robot  # lives in . , then it's likely to be owned by the target file.
2995*7c3d14c8STreehugger Robot  target_dir, target_base = (
2996*7c3d14c8STreehugger Robot      os.path.split(_DropCommonSuffixes(fileinfo.RepositoryName())))
2997*7c3d14c8STreehugger Robot  include_dir, include_base = os.path.split(_DropCommonSuffixes(include))
2998*7c3d14c8STreehugger Robot  if target_base == include_base and (
2999*7c3d14c8STreehugger Robot      include_dir == target_dir or
3000*7c3d14c8STreehugger Robot      include_dir == os.path.normpath(target_dir + '/../public')):
3001*7c3d14c8STreehugger Robot    return _LIKELY_MY_HEADER
3002*7c3d14c8STreehugger Robot
3003*7c3d14c8STreehugger Robot  # If the target and include share some initial basename
3004*7c3d14c8STreehugger Robot  # component, it's possible the target is implementing the
3005*7c3d14c8STreehugger Robot  # include, so it's allowed to be first, but we'll never
3006*7c3d14c8STreehugger Robot  # complain if it's not there.
3007*7c3d14c8STreehugger Robot  target_first_component = _RE_FIRST_COMPONENT.match(target_base)
3008*7c3d14c8STreehugger Robot  include_first_component = _RE_FIRST_COMPONENT.match(include_base)
3009*7c3d14c8STreehugger Robot  if (target_first_component and include_first_component and
3010*7c3d14c8STreehugger Robot      target_first_component.group(0) ==
3011*7c3d14c8STreehugger Robot      include_first_component.group(0)):
3012*7c3d14c8STreehugger Robot    return _POSSIBLE_MY_HEADER
3013*7c3d14c8STreehugger Robot
3014*7c3d14c8STreehugger Robot  return _OTHER_HEADER
3015*7c3d14c8STreehugger Robot
3016*7c3d14c8STreehugger Robot
3017*7c3d14c8STreehugger Robot
3018*7c3d14c8STreehugger Robotdef CheckIncludeLine(filename, clean_lines, linenum, include_state, error):
3019*7c3d14c8STreehugger Robot  """Check rules that are applicable to #include lines.
3020*7c3d14c8STreehugger Robot
3021*7c3d14c8STreehugger Robot  Strings on #include lines are NOT removed from elided line, to make
3022*7c3d14c8STreehugger Robot  certain tasks easier. However, to prevent false positives, checks
3023*7c3d14c8STreehugger Robot  applicable to #include lines in CheckLanguage must be put here.
3024*7c3d14c8STreehugger Robot
3025*7c3d14c8STreehugger Robot  Args:
3026*7c3d14c8STreehugger Robot    filename: The name of the current file.
3027*7c3d14c8STreehugger Robot    clean_lines: A CleansedLines instance containing the file.
3028*7c3d14c8STreehugger Robot    linenum: The number of the line to check.
3029*7c3d14c8STreehugger Robot    include_state: An _IncludeState instance in which the headers are inserted.
3030*7c3d14c8STreehugger Robot    error: The function to call with any errors found.
3031*7c3d14c8STreehugger Robot  """
3032*7c3d14c8STreehugger Robot  fileinfo = FileInfo(filename)
3033*7c3d14c8STreehugger Robot
3034*7c3d14c8STreehugger Robot  line = clean_lines.lines[linenum]
3035*7c3d14c8STreehugger Robot
3036*7c3d14c8STreehugger Robot  # "include" should use the new style "foo/bar.h" instead of just "bar.h"
3037*7c3d14c8STreehugger Robot  if _RE_PATTERN_INCLUDE_NEW_STYLE.search(line):
3038*7c3d14c8STreehugger Robot    error(filename, linenum, 'build/include', 4,
3039*7c3d14c8STreehugger Robot          'Include the directory when naming .h files')
3040*7c3d14c8STreehugger Robot
3041*7c3d14c8STreehugger Robot  # we shouldn't include a file more than once. actually, there are a
3042*7c3d14c8STreehugger Robot  # handful of instances where doing so is okay, but in general it's
3043*7c3d14c8STreehugger Robot  # not.
3044*7c3d14c8STreehugger Robot  match = _RE_PATTERN_INCLUDE.search(line)
3045*7c3d14c8STreehugger Robot  if match:
3046*7c3d14c8STreehugger Robot    include = match.group(2)
3047*7c3d14c8STreehugger Robot    is_system = (match.group(1) == '<')
3048*7c3d14c8STreehugger Robot    if include in include_state:
3049*7c3d14c8STreehugger Robot      error(filename, linenum, 'build/include', 4,
3050*7c3d14c8STreehugger Robot            '"%s" already included at %s:%s' %
3051*7c3d14c8STreehugger Robot            (include, filename, include_state[include]))
3052*7c3d14c8STreehugger Robot    else:
3053*7c3d14c8STreehugger Robot      include_state[include] = linenum
3054*7c3d14c8STreehugger Robot
3055*7c3d14c8STreehugger Robot      # We want to ensure that headers appear in the right order:
3056*7c3d14c8STreehugger Robot      # 1) for foo.cc, foo.h  (preferred location)
3057*7c3d14c8STreehugger Robot      # 2) c system files
3058*7c3d14c8STreehugger Robot      # 3) cpp system files
3059*7c3d14c8STreehugger Robot      # 4) for foo.cc, foo.h  (deprecated location)
3060*7c3d14c8STreehugger Robot      # 5) other google headers
3061*7c3d14c8STreehugger Robot      #
3062*7c3d14c8STreehugger Robot      # We classify each include statement as one of those 5 types
3063*7c3d14c8STreehugger Robot      # using a number of techniques. The include_state object keeps
3064*7c3d14c8STreehugger Robot      # track of the highest type seen, and complains if we see a
3065*7c3d14c8STreehugger Robot      # lower type after that.
3066*7c3d14c8STreehugger Robot      error_message = include_state.CheckNextIncludeOrder(
3067*7c3d14c8STreehugger Robot          _ClassifyInclude(fileinfo, include, is_system))
3068*7c3d14c8STreehugger Robot      if error_message:
3069*7c3d14c8STreehugger Robot        error(filename, linenum, 'build/include_order', 4,
3070*7c3d14c8STreehugger Robot              '%s. Should be: %s.h, c system, c++ system, other.' %
3071*7c3d14c8STreehugger Robot              (error_message, fileinfo.BaseName()))
3072*7c3d14c8STreehugger Robot      if not include_state.IsInAlphabeticalOrder(include):
3073*7c3d14c8STreehugger Robot        error(filename, linenum, 'build/include_alpha', 4,
3074*7c3d14c8STreehugger Robot              'Include "%s" not in alphabetical order' % include)
3075*7c3d14c8STreehugger Robot
3076*7c3d14c8STreehugger Robot  # Look for any of the stream classes that are part of standard C++.
3077*7c3d14c8STreehugger Robot  match = _RE_PATTERN_INCLUDE.match(line)
3078*7c3d14c8STreehugger Robot  if match:
3079*7c3d14c8STreehugger Robot    include = match.group(2)
3080*7c3d14c8STreehugger Robot    if Match(r'(f|ind|io|i|o|parse|pf|stdio|str|)?stream$', include):
3081*7c3d14c8STreehugger Robot      # Many unit tests use cout, so we exempt them.
3082*7c3d14c8STreehugger Robot      if not _IsTestFilename(filename):
3083*7c3d14c8STreehugger Robot        error(filename, linenum, 'readability/streams', 3,
3084*7c3d14c8STreehugger Robot              'Streams are highly discouraged.')
3085*7c3d14c8STreehugger Robot
3086*7c3d14c8STreehugger Robot
3087*7c3d14c8STreehugger Robotdef _GetTextInside(text, start_pattern):
3088*7c3d14c8STreehugger Robot  """Retrieves all the text between matching open and close parentheses.
3089*7c3d14c8STreehugger Robot
3090*7c3d14c8STreehugger Robot  Given a string of lines and a regular expression string, retrieve all the text
3091*7c3d14c8STreehugger Robot  following the expression and between opening punctuation symbols like
3092*7c3d14c8STreehugger Robot  (, [, or {, and the matching close-punctuation symbol. This properly nested
3093*7c3d14c8STreehugger Robot  occurrences of the punctuations, so for the text like
3094*7c3d14c8STreehugger Robot    printf(a(), b(c()));
3095*7c3d14c8STreehugger Robot  a call to _GetTextInside(text, r'printf\(') will return 'a(), b(c())'.
3096*7c3d14c8STreehugger Robot  start_pattern must match string having an open punctuation symbol at the end.
3097*7c3d14c8STreehugger Robot
3098*7c3d14c8STreehugger Robot  Args:
3099*7c3d14c8STreehugger Robot    text: The lines to extract text. Its comments and strings must be elided.
3100*7c3d14c8STreehugger Robot           It can be single line and can span multiple lines.
3101*7c3d14c8STreehugger Robot    start_pattern: The regexp string indicating where to start extracting
3102*7c3d14c8STreehugger Robot                   the text.
3103*7c3d14c8STreehugger Robot  Returns:
3104*7c3d14c8STreehugger Robot    The extracted text.
3105*7c3d14c8STreehugger Robot    None if either the opening string or ending punctuation could not be found.
3106*7c3d14c8STreehugger Robot  """
3107*7c3d14c8STreehugger Robot  # TODO(sugawarayu): Audit cpplint.py to see what places could be profitably
3108*7c3d14c8STreehugger Robot  # rewritten to use _GetTextInside (and use inferior regexp matching today).
3109*7c3d14c8STreehugger Robot
3110*7c3d14c8STreehugger Robot  # Give opening punctuations to get the matching close-punctuations.
3111*7c3d14c8STreehugger Robot  matching_punctuation = {'(': ')', '{': '}', '[': ']'}
3112*7c3d14c8STreehugger Robot  closing_punctuation = set(matching_punctuation.itervalues())
3113*7c3d14c8STreehugger Robot
3114*7c3d14c8STreehugger Robot  # Find the position to start extracting text.
3115*7c3d14c8STreehugger Robot  match = re.search(start_pattern, text, re.M)
3116*7c3d14c8STreehugger Robot  if not match:  # start_pattern not found in text.
3117*7c3d14c8STreehugger Robot    return None
3118*7c3d14c8STreehugger Robot  start_position = match.end(0)
3119*7c3d14c8STreehugger Robot
3120*7c3d14c8STreehugger Robot  assert start_position > 0, (
3121*7c3d14c8STreehugger Robot      'start_pattern must ends with an opening punctuation.')
3122*7c3d14c8STreehugger Robot  assert text[start_position - 1] in matching_punctuation, (
3123*7c3d14c8STreehugger Robot      'start_pattern must ends with an opening punctuation.')
3124*7c3d14c8STreehugger Robot  # Stack of closing punctuations we expect to have in text after position.
3125*7c3d14c8STreehugger Robot  punctuation_stack = [matching_punctuation[text[start_position - 1]]]
3126*7c3d14c8STreehugger Robot  position = start_position
3127*7c3d14c8STreehugger Robot  while punctuation_stack and position < len(text):
3128*7c3d14c8STreehugger Robot    if text[position] == punctuation_stack[-1]:
3129*7c3d14c8STreehugger Robot      punctuation_stack.pop()
3130*7c3d14c8STreehugger Robot    elif text[position] in closing_punctuation:
3131*7c3d14c8STreehugger Robot      # A closing punctuation without matching opening punctuations.
3132*7c3d14c8STreehugger Robot      return None
3133*7c3d14c8STreehugger Robot    elif text[position] in matching_punctuation:
3134*7c3d14c8STreehugger Robot      punctuation_stack.append(matching_punctuation[text[position]])
3135*7c3d14c8STreehugger Robot    position += 1
3136*7c3d14c8STreehugger Robot  if punctuation_stack:
3137*7c3d14c8STreehugger Robot    # Opening punctuations left without matching close-punctuations.
3138*7c3d14c8STreehugger Robot    return None
3139*7c3d14c8STreehugger Robot  # punctuations match.
3140*7c3d14c8STreehugger Robot  return text[start_position:position - 1]
3141*7c3d14c8STreehugger Robot
3142*7c3d14c8STreehugger Robot
3143*7c3d14c8STreehugger Robotdef CheckLanguage(filename, clean_lines, linenum, file_extension, include_state,
3144*7c3d14c8STreehugger Robot                  error):
3145*7c3d14c8STreehugger Robot  """Checks rules from the 'C++ language rules' section of cppguide.html.
3146*7c3d14c8STreehugger Robot
3147*7c3d14c8STreehugger Robot  Some of these rules are hard to test (function overloading, using
3148*7c3d14c8STreehugger Robot  uint32 inappropriately), but we do the best we can.
3149*7c3d14c8STreehugger Robot
3150*7c3d14c8STreehugger Robot  Args:
3151*7c3d14c8STreehugger Robot    filename: The name of the current file.
3152*7c3d14c8STreehugger Robot    clean_lines: A CleansedLines instance containing the file.
3153*7c3d14c8STreehugger Robot    linenum: The number of the line to check.
3154*7c3d14c8STreehugger Robot    file_extension: The extension (without the dot) of the filename.
3155*7c3d14c8STreehugger Robot    include_state: An _IncludeState instance in which the headers are inserted.
3156*7c3d14c8STreehugger Robot    error: The function to call with any errors found.
3157*7c3d14c8STreehugger Robot  """
3158*7c3d14c8STreehugger Robot  # If the line is empty or consists of entirely a comment, no need to
3159*7c3d14c8STreehugger Robot  # check it.
3160*7c3d14c8STreehugger Robot  line = clean_lines.elided[linenum]
3161*7c3d14c8STreehugger Robot  if not line:
3162*7c3d14c8STreehugger Robot    return
3163*7c3d14c8STreehugger Robot
3164*7c3d14c8STreehugger Robot  match = _RE_PATTERN_INCLUDE.search(line)
3165*7c3d14c8STreehugger Robot  if match:
3166*7c3d14c8STreehugger Robot    CheckIncludeLine(filename, clean_lines, linenum, include_state, error)
3167*7c3d14c8STreehugger Robot    return
3168*7c3d14c8STreehugger Robot
3169*7c3d14c8STreehugger Robot  # Create an extended_line, which is the concatenation of the current and
3170*7c3d14c8STreehugger Robot  # next lines, for more effective checking of code that may span more than one
3171*7c3d14c8STreehugger Robot  # line.
3172*7c3d14c8STreehugger Robot  if linenum + 1 < clean_lines.NumLines():
3173*7c3d14c8STreehugger Robot    extended_line = line + clean_lines.elided[linenum + 1]
3174*7c3d14c8STreehugger Robot  else:
3175*7c3d14c8STreehugger Robot    extended_line = line
3176*7c3d14c8STreehugger Robot
3177*7c3d14c8STreehugger Robot  # Make Windows paths like Unix.
3178*7c3d14c8STreehugger Robot  fullname = os.path.abspath(filename).replace('\\', '/')
3179*7c3d14c8STreehugger Robot
3180*7c3d14c8STreehugger Robot  # TODO(unknown): figure out if they're using default arguments in fn proto.
3181*7c3d14c8STreehugger Robot
3182*7c3d14c8STreehugger Robot  # Check for non-const references in functions.  This is tricky because &
3183*7c3d14c8STreehugger Robot  # is also used to take the address of something.  We allow <> for templates,
3184*7c3d14c8STreehugger Robot  # (ignoring whatever is between the braces) and : for classes.
3185*7c3d14c8STreehugger Robot  # These are complicated re's.  They try to capture the following:
3186*7c3d14c8STreehugger Robot  # paren (for fn-prototype start), typename, &, varname.  For the const
3187*7c3d14c8STreehugger Robot  # version, we're willing for const to be before typename or after
3188*7c3d14c8STreehugger Robot  # Don't check the implementation on same line.
3189*7c3d14c8STreehugger Robot  fnline = line.split('{', 1)[0]
3190*7c3d14c8STreehugger Robot  if (len(re.findall(r'\([^()]*\b(?:[\w:]|<[^()]*>)+(\s?&|&\s?)\w+', fnline)) >
3191*7c3d14c8STreehugger Robot      len(re.findall(r'\([^()]*\bconst\s+(?:typename\s+)?(?:struct\s+)?'
3192*7c3d14c8STreehugger Robot                     r'(?:[\w:]|<[^()]*>)+(\s?&|&\s?)\w+', fnline)) +
3193*7c3d14c8STreehugger Robot      len(re.findall(r'\([^()]*\b(?:[\w:]|<[^()]*>)+\s+const(\s?&|&\s?)[\w]+',
3194*7c3d14c8STreehugger Robot                     fnline))):
3195*7c3d14c8STreehugger Robot
3196*7c3d14c8STreehugger Robot    # We allow non-const references in a few standard places, like functions
3197*7c3d14c8STreehugger Robot    # called "swap()" or iostream operators like "<<" or ">>". We also filter
3198*7c3d14c8STreehugger Robot    # out for loops, which lint otherwise mistakenly thinks are functions.
3199*7c3d14c8STreehugger Robot    if not Search(
3200*7c3d14c8STreehugger Robot        r'(for|swap|Swap|operator[<>][<>])\s*\(\s*'
3201*7c3d14c8STreehugger Robot        r'(?:(?:typename\s*)?[\w:]|<.*>)+\s*&',
3202*7c3d14c8STreehugger Robot        fnline):
3203*7c3d14c8STreehugger Robot      error(filename, linenum, 'runtime/references', 2,
3204*7c3d14c8STreehugger Robot            'Is this a non-const reference? '
3205*7c3d14c8STreehugger Robot            'If so, make const or use a pointer.')
3206*7c3d14c8STreehugger Robot
3207*7c3d14c8STreehugger Robot  # Check to see if they're using an conversion function cast.
3208*7c3d14c8STreehugger Robot  # I just try to capture the most common basic types, though there are more.
3209*7c3d14c8STreehugger Robot  # Parameterless conversion functions, such as bool(), are allowed as they are
3210*7c3d14c8STreehugger Robot  # probably a member operator declaration or default constructor.
3211*7c3d14c8STreehugger Robot  match = Search(
3212*7c3d14c8STreehugger Robot      r'(\bnew\s+)?\b'  # Grab 'new' operator, if it's there
3213*7c3d14c8STreehugger Robot      r'(int|float|double|bool|char|int32|uint32|int64|uint64)\([^)]', line)
3214*7c3d14c8STreehugger Robot  if match:
3215*7c3d14c8STreehugger Robot    # gMock methods are defined using some variant of MOCK_METHODx(name, type)
3216*7c3d14c8STreehugger Robot    # where type may be float(), int(string), etc.  Without context they are
3217*7c3d14c8STreehugger Robot    # virtually indistinguishable from int(x) casts. Likewise, gMock's
3218*7c3d14c8STreehugger Robot    # MockCallback takes a template parameter of the form return_type(arg_type),
3219*7c3d14c8STreehugger Robot    # which looks much like the cast we're trying to detect.
3220*7c3d14c8STreehugger Robot    if (match.group(1) is None and  # If new operator, then this isn't a cast
3221*7c3d14c8STreehugger Robot        not (Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line) or
3222*7c3d14c8STreehugger Robot             Match(r'^\s*MockCallback<.*>', line))):
3223*7c3d14c8STreehugger Robot      # Try a bit harder to catch gmock lines: the only place where
3224*7c3d14c8STreehugger Robot      # something looks like an old-style cast is where we declare the
3225*7c3d14c8STreehugger Robot      # return type of the mocked method, and the only time when we
3226*7c3d14c8STreehugger Robot      # are missing context is if MOCK_METHOD was split across
3227*7c3d14c8STreehugger Robot      # multiple lines (for example http://go/hrfhr ), so we only need
3228*7c3d14c8STreehugger Robot      # to check the previous line for MOCK_METHOD.
3229*7c3d14c8STreehugger Robot      if (linenum == 0 or
3230*7c3d14c8STreehugger Robot          not Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(\S+,\s*$',
3231*7c3d14c8STreehugger Robot                    clean_lines.elided[linenum - 1])):
3232*7c3d14c8STreehugger Robot        error(filename, linenum, 'readability/casting', 4,
3233*7c3d14c8STreehugger Robot              'Using deprecated casting style.  '
3234*7c3d14c8STreehugger Robot              'Use static_cast<%s>(...) instead' %
3235*7c3d14c8STreehugger Robot              match.group(2))
3236*7c3d14c8STreehugger Robot
3237*7c3d14c8STreehugger Robot  CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum],
3238*7c3d14c8STreehugger Robot                  'static_cast',
3239*7c3d14c8STreehugger Robot                  r'\((int|float|double|bool|char|u?int(16|32|64))\)', error)
3240*7c3d14c8STreehugger Robot
3241*7c3d14c8STreehugger Robot  # This doesn't catch all cases. Consider (const char * const)"hello".
3242*7c3d14c8STreehugger Robot  #
3243*7c3d14c8STreehugger Robot  # (char *) "foo" should always be a const_cast (reinterpret_cast won't
3244*7c3d14c8STreehugger Robot  # compile).
3245*7c3d14c8STreehugger Robot  if CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum],
3246*7c3d14c8STreehugger Robot                     'const_cast', r'\((char\s?\*+\s?)\)\s*"', error):
3247*7c3d14c8STreehugger Robot    pass
3248*7c3d14c8STreehugger Robot  else:
3249*7c3d14c8STreehugger Robot    # Check pointer casts for other than string constants
3250*7c3d14c8STreehugger Robot    CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum],
3251*7c3d14c8STreehugger Robot                    'reinterpret_cast', r'\((\w+\s?\*+\s?)\)', error)
3252*7c3d14c8STreehugger Robot
3253*7c3d14c8STreehugger Robot  # In addition, we look for people taking the address of a cast.  This
3254*7c3d14c8STreehugger Robot  # is dangerous -- casts can assign to temporaries, so the pointer doesn't
3255*7c3d14c8STreehugger Robot  # point where you think.
3256*7c3d14c8STreehugger Robot  if Search(
3257*7c3d14c8STreehugger Robot      r'(&\([^)]+\)[\w(])|(&(static|dynamic|reinterpret)_cast\b)', line):
3258*7c3d14c8STreehugger Robot    error(filename, linenum, 'runtime/casting', 4,
3259*7c3d14c8STreehugger Robot          ('Are you taking an address of a cast?  '
3260*7c3d14c8STreehugger Robot           'This is dangerous: could be a temp var.  '
3261*7c3d14c8STreehugger Robot           'Take the address before doing the cast, rather than after'))
3262*7c3d14c8STreehugger Robot
3263*7c3d14c8STreehugger Robot  # Check for people declaring static/global STL strings at the top level.
3264*7c3d14c8STreehugger Robot  # This is dangerous because the C++ language does not guarantee that
3265*7c3d14c8STreehugger Robot  # globals with constructors are initialized before the first access.
3266*7c3d14c8STreehugger Robot  match = Match(
3267*7c3d14c8STreehugger Robot      r'((?:|static +)(?:|const +))string +([a-zA-Z0-9_:]+)\b(.*)',
3268*7c3d14c8STreehugger Robot      line)
3269*7c3d14c8STreehugger Robot  # Make sure it's not a function.
3270*7c3d14c8STreehugger Robot  # Function template specialization looks like: "string foo<Type>(...".
3271*7c3d14c8STreehugger Robot  # Class template definitions look like: "string Foo<Type>::Method(...".
3272*7c3d14c8STreehugger Robot  if match and not Match(r'\s*(<.*>)?(::[a-zA-Z0-9_]+)?\s*\(([^"]|$)',
3273*7c3d14c8STreehugger Robot                         match.group(3)):
3274*7c3d14c8STreehugger Robot    error(filename, linenum, 'runtime/string', 4,
3275*7c3d14c8STreehugger Robot          'For a static/global string constant, use a C style string instead: '
3276*7c3d14c8STreehugger Robot          '"%schar %s[]".' %
3277*7c3d14c8STreehugger Robot          (match.group(1), match.group(2)))
3278*7c3d14c8STreehugger Robot
3279*7c3d14c8STreehugger Robot  # Check that we're not using RTTI outside of testing code.
3280*7c3d14c8STreehugger Robot  if Search(r'\bdynamic_cast<', line) and not _IsTestFilename(filename):
3281*7c3d14c8STreehugger Robot    error(filename, linenum, 'runtime/rtti', 5,
3282*7c3d14c8STreehugger Robot          'Do not use dynamic_cast<>.  If you need to cast within a class '
3283*7c3d14c8STreehugger Robot          "hierarchy, use static_cast<> to upcast.  Google doesn't support "
3284*7c3d14c8STreehugger Robot          'RTTI.')
3285*7c3d14c8STreehugger Robot
3286*7c3d14c8STreehugger Robot  if Search(r'\b([A-Za-z0-9_]*_)\(\1\)', line):
3287*7c3d14c8STreehugger Robot    error(filename, linenum, 'runtime/init', 4,
3288*7c3d14c8STreehugger Robot          'You seem to be initializing a member variable with itself.')
3289*7c3d14c8STreehugger Robot
3290*7c3d14c8STreehugger Robot  if file_extension == 'h':
3291*7c3d14c8STreehugger Robot    # TODO(unknown): check that 1-arg constructors are explicit.
3292*7c3d14c8STreehugger Robot    #                How to tell it's a constructor?
3293*7c3d14c8STreehugger Robot    #                (handled in CheckForNonStandardConstructs for now)
3294*7c3d14c8STreehugger Robot    # TODO(unknown): check that classes have DISALLOW_EVIL_CONSTRUCTORS
3295*7c3d14c8STreehugger Robot    #                (level 1 error)
3296*7c3d14c8STreehugger Robot    pass
3297*7c3d14c8STreehugger Robot
3298*7c3d14c8STreehugger Robot  # Check if people are using the verboten C basic types.  The only exception
3299*7c3d14c8STreehugger Robot  # we regularly allow is "unsigned short port" for port.
3300*7c3d14c8STreehugger Robot  if Search(r'\bshort port\b', line):
3301*7c3d14c8STreehugger Robot    if not Search(r'\bunsigned short port\b', line):
3302*7c3d14c8STreehugger Robot      error(filename, linenum, 'runtime/int', 4,
3303*7c3d14c8STreehugger Robot            'Use "unsigned short" for ports, not "short"')
3304*7c3d14c8STreehugger Robot  else:
3305*7c3d14c8STreehugger Robot    match = Search(r'\b(short|long(?! +double)|long long)\b', line)
3306*7c3d14c8STreehugger Robot    if match:
3307*7c3d14c8STreehugger Robot      error(filename, linenum, 'runtime/int', 4,
3308*7c3d14c8STreehugger Robot            'Use int16/int64/etc, rather than the C type %s' % match.group(1))
3309*7c3d14c8STreehugger Robot
3310*7c3d14c8STreehugger Robot  # When snprintf is used, the second argument shouldn't be a literal.
3311*7c3d14c8STreehugger Robot  match = Search(r'snprintf\s*\(([^,]*),\s*([0-9]*)\s*,', line)
3312*7c3d14c8STreehugger Robot  if match and match.group(2) != '0':
3313*7c3d14c8STreehugger Robot    # If 2nd arg is zero, snprintf is used to calculate size.
3314*7c3d14c8STreehugger Robot    error(filename, linenum, 'runtime/printf', 3,
3315*7c3d14c8STreehugger Robot          'If you can, use sizeof(%s) instead of %s as the 2nd arg '
3316*7c3d14c8STreehugger Robot          'to snprintf.' % (match.group(1), match.group(2)))
3317*7c3d14c8STreehugger Robot
3318*7c3d14c8STreehugger Robot  # Check if some verboten C functions are being used.
3319*7c3d14c8STreehugger Robot  if Search(r'\bsprintf\b', line):
3320*7c3d14c8STreehugger Robot    error(filename, linenum, 'runtime/printf', 5,
3321*7c3d14c8STreehugger Robot          'Never use sprintf.  Use snprintf instead.')
3322*7c3d14c8STreehugger Robot  match = Search(r'\b(strcpy|strcat)\b', line)
3323*7c3d14c8STreehugger Robot  if match:
3324*7c3d14c8STreehugger Robot    error(filename, linenum, 'runtime/printf', 4,
3325*7c3d14c8STreehugger Robot          'Almost always, snprintf is better than %s' % match.group(1))
3326*7c3d14c8STreehugger Robot
3327*7c3d14c8STreehugger Robot  if Search(r'\bsscanf\b', line):
3328*7c3d14c8STreehugger Robot    error(filename, linenum, 'runtime/printf', 1,
3329*7c3d14c8STreehugger Robot          'sscanf can be ok, but is slow and can overflow buffers.')
3330*7c3d14c8STreehugger Robot
3331*7c3d14c8STreehugger Robot  # Check if some verboten operator overloading is going on
3332*7c3d14c8STreehugger Robot  # TODO(unknown): catch out-of-line unary operator&:
3333*7c3d14c8STreehugger Robot  #   class X {};
3334*7c3d14c8STreehugger Robot  #   int operator&(const X& x) { return 42; }  // unary operator&
3335*7c3d14c8STreehugger Robot  # The trick is it's hard to tell apart from binary operator&:
3336*7c3d14c8STreehugger Robot  #   class Y { int operator&(const Y& x) { return 23; } }; // binary operator&
3337*7c3d14c8STreehugger Robot  if Search(r'\boperator\s*&\s*\(\s*\)', line):
3338*7c3d14c8STreehugger Robot    error(filename, linenum, 'runtime/operator', 4,
3339*7c3d14c8STreehugger Robot          'Unary operator& is dangerous.  Do not use it.')
3340*7c3d14c8STreehugger Robot
3341*7c3d14c8STreehugger Robot  # Check for suspicious usage of "if" like
3342*7c3d14c8STreehugger Robot  # } if (a == b) {
3343*7c3d14c8STreehugger Robot  if Search(r'\}\s*if\s*\(', line):
3344*7c3d14c8STreehugger Robot    error(filename, linenum, 'readability/braces', 4,
3345*7c3d14c8STreehugger Robot          'Did you mean "else if"? If not, start a new line for "if".')
3346*7c3d14c8STreehugger Robot
3347*7c3d14c8STreehugger Robot  # Check for potential format string bugs like printf(foo).
3348*7c3d14c8STreehugger Robot  # We constrain the pattern not to pick things like DocidForPrintf(foo).
3349*7c3d14c8STreehugger Robot  # Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str())
3350*7c3d14c8STreehugger Robot  # TODO(sugawarayu): Catch the following case. Need to change the calling
3351*7c3d14c8STreehugger Robot  # convention of the whole function to process multiple line to handle it.
3352*7c3d14c8STreehugger Robot  #   printf(
3353*7c3d14c8STreehugger Robot  #       boy_this_is_a_really_long_variable_that_cannot_fit_on_the_prev_line);
3354*7c3d14c8STreehugger Robot  printf_args = _GetTextInside(line, r'(?i)\b(string)?printf\s*\(')
3355*7c3d14c8STreehugger Robot  if printf_args:
3356*7c3d14c8STreehugger Robot    match = Match(r'([\w.\->()]+)$', printf_args)
3357*7c3d14c8STreehugger Robot    if match and match.group(1) != '__VA_ARGS__':
3358*7c3d14c8STreehugger Robot      function_name = re.search(r'\b((?:string)?printf)\s*\(',
3359*7c3d14c8STreehugger Robot                                line, re.I).group(1)
3360*7c3d14c8STreehugger Robot      error(filename, linenum, 'runtime/printf', 4,
3361*7c3d14c8STreehugger Robot            'Potential format string bug. Do %s("%%s", %s) instead.'
3362*7c3d14c8STreehugger Robot            % (function_name, match.group(1)))
3363*7c3d14c8STreehugger Robot
3364*7c3d14c8STreehugger Robot  # Check for potential memset bugs like memset(buf, sizeof(buf), 0).
3365*7c3d14c8STreehugger Robot  match = Search(r'memset\s*\(([^,]*),\s*([^,]*),\s*0\s*\)', line)
3366*7c3d14c8STreehugger Robot  if match and not Match(r"^''|-?[0-9]+|0x[0-9A-Fa-f]$", match.group(2)):
3367*7c3d14c8STreehugger Robot    error(filename, linenum, 'runtime/memset', 4,
3368*7c3d14c8STreehugger Robot          'Did you mean "memset(%s, 0, %s)"?'
3369*7c3d14c8STreehugger Robot          % (match.group(1), match.group(2)))
3370*7c3d14c8STreehugger Robot
3371*7c3d14c8STreehugger Robot  if Search(r'\busing namespace\b', line):
3372*7c3d14c8STreehugger Robot    error(filename, linenum, 'build/namespaces', 5,
3373*7c3d14c8STreehugger Robot          'Do not use namespace using-directives.  '
3374*7c3d14c8STreehugger Robot          'Use using-declarations instead.')
3375*7c3d14c8STreehugger Robot
3376*7c3d14c8STreehugger Robot  # Detect variable-length arrays.
3377*7c3d14c8STreehugger Robot  match = Match(r'\s*(.+::)?(\w+) [a-z]\w*\[(.+)];', line)
3378*7c3d14c8STreehugger Robot  if (match and match.group(2) != 'return' and match.group(2) != 'delete' and
3379*7c3d14c8STreehugger Robot      match.group(3).find(']') == -1):
3380*7c3d14c8STreehugger Robot    # Split the size using space and arithmetic operators as delimiters.
3381*7c3d14c8STreehugger Robot    # If any of the resulting tokens are not compile time constants then
3382*7c3d14c8STreehugger Robot    # report the error.
3383*7c3d14c8STreehugger Robot    tokens = re.split(r'\s|\+|\-|\*|\/|<<|>>]', match.group(3))
3384*7c3d14c8STreehugger Robot    is_const = True
3385*7c3d14c8STreehugger Robot    skip_next = False
3386*7c3d14c8STreehugger Robot    for tok in tokens:
3387*7c3d14c8STreehugger Robot      if skip_next:
3388*7c3d14c8STreehugger Robot        skip_next = False
3389*7c3d14c8STreehugger Robot        continue
3390*7c3d14c8STreehugger Robot
3391*7c3d14c8STreehugger Robot      if Search(r'sizeof\(.+\)', tok): continue
3392*7c3d14c8STreehugger Robot      if Search(r'arraysize\(\w+\)', tok): continue
3393*7c3d14c8STreehugger Robot
3394*7c3d14c8STreehugger Robot      tok = tok.lstrip('(')
3395*7c3d14c8STreehugger Robot      tok = tok.rstrip(')')
3396*7c3d14c8STreehugger Robot      if not tok: continue
3397*7c3d14c8STreehugger Robot      if Match(r'\d+', tok): continue
3398*7c3d14c8STreehugger Robot      if Match(r'0[xX][0-9a-fA-F]+', tok): continue
3399*7c3d14c8STreehugger Robot      if Match(r'k[A-Z0-9]\w*', tok): continue
3400*7c3d14c8STreehugger Robot      if Match(r'(.+::)?k[A-Z0-9]\w*', tok): continue
3401*7c3d14c8STreehugger Robot      if Match(r'(.+::)?[A-Z][A-Z0-9_]*', tok): continue
3402*7c3d14c8STreehugger Robot      # A catch all for tricky sizeof cases, including 'sizeof expression',
3403*7c3d14c8STreehugger Robot      # 'sizeof(*type)', 'sizeof(const type)', 'sizeof(struct StructName)'
3404*7c3d14c8STreehugger Robot      # requires skipping the next token because we split on ' ' and '*'.
3405*7c3d14c8STreehugger Robot      if tok.startswith('sizeof'):
3406*7c3d14c8STreehugger Robot        skip_next = True
3407*7c3d14c8STreehugger Robot        continue
3408*7c3d14c8STreehugger Robot      is_const = False
3409*7c3d14c8STreehugger Robot      break
3410*7c3d14c8STreehugger Robot    if not is_const:
3411*7c3d14c8STreehugger Robot      error(filename, linenum, 'runtime/arrays', 1,
3412*7c3d14c8STreehugger Robot            'Do not use variable-length arrays.  Use an appropriately named '
3413*7c3d14c8STreehugger Robot            "('k' followed by CamelCase) compile-time constant for the size.")
3414*7c3d14c8STreehugger Robot
3415*7c3d14c8STreehugger Robot  # If DISALLOW_EVIL_CONSTRUCTORS, DISALLOW_COPY_AND_ASSIGN, or
3416*7c3d14c8STreehugger Robot  # DISALLOW_IMPLICIT_CONSTRUCTORS is present, then it should be the last thing
3417*7c3d14c8STreehugger Robot  # in the class declaration.
3418*7c3d14c8STreehugger Robot  match = Match(
3419*7c3d14c8STreehugger Robot      (r'\s*'
3420*7c3d14c8STreehugger Robot       r'(DISALLOW_(EVIL_CONSTRUCTORS|COPY_AND_ASSIGN|IMPLICIT_CONSTRUCTORS))'
3421*7c3d14c8STreehugger Robot       r'\(.*\);$'),
3422*7c3d14c8STreehugger Robot      line)
3423*7c3d14c8STreehugger Robot  if match and linenum + 1 < clean_lines.NumLines():
3424*7c3d14c8STreehugger Robot    next_line = clean_lines.elided[linenum + 1]
3425*7c3d14c8STreehugger Robot    # We allow some, but not all, declarations of variables to be present
3426*7c3d14c8STreehugger Robot    # in the statement that defines the class.  The [\w\*,\s]* fragment of
3427*7c3d14c8STreehugger Robot    # the regular expression below allows users to declare instances of
3428*7c3d14c8STreehugger Robot    # the class or pointers to instances, but not less common types such
3429*7c3d14c8STreehugger Robot    # as function pointers or arrays.  It's a tradeoff between allowing
3430*7c3d14c8STreehugger Robot    # reasonable code and avoiding trying to parse more C++ using regexps.
3431*7c3d14c8STreehugger Robot    if not Search(r'^\s*}[\w\*,\s]*;', next_line):
3432*7c3d14c8STreehugger Robot      error(filename, linenum, 'readability/constructors', 3,
3433*7c3d14c8STreehugger Robot            match.group(1) + ' should be the last thing in the class')
3434*7c3d14c8STreehugger Robot
3435*7c3d14c8STreehugger Robot  # Check for use of unnamed namespaces in header files.  Registration
3436*7c3d14c8STreehugger Robot  # macros are typically OK, so we allow use of "namespace {" on lines
3437*7c3d14c8STreehugger Robot  # that end with backslashes.
3438*7c3d14c8STreehugger Robot  if (file_extension == 'h'
3439*7c3d14c8STreehugger Robot      and Search(r'\bnamespace\s*{', line)
3440*7c3d14c8STreehugger Robot      and line[-1] != '\\'):
3441*7c3d14c8STreehugger Robot    error(filename, linenum, 'build/namespaces', 4,
3442*7c3d14c8STreehugger Robot          'Do not use unnamed namespaces in header files.  See '
3443*7c3d14c8STreehugger Robot          'http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces'
3444*7c3d14c8STreehugger Robot          ' for more information.')
3445*7c3d14c8STreehugger Robot
3446*7c3d14c8STreehugger Robot
3447*7c3d14c8STreehugger Robotdef CheckCStyleCast(filename, linenum, line, raw_line, cast_type, pattern,
3448*7c3d14c8STreehugger Robot                    error):
3449*7c3d14c8STreehugger Robot  """Checks for a C-style cast by looking for the pattern.
3450*7c3d14c8STreehugger Robot
3451*7c3d14c8STreehugger Robot  This also handles sizeof(type) warnings, due to similarity of content.
3452*7c3d14c8STreehugger Robot
3453*7c3d14c8STreehugger Robot  Args:
3454*7c3d14c8STreehugger Robot    filename: The name of the current file.
3455*7c3d14c8STreehugger Robot    linenum: The number of the line to check.
3456*7c3d14c8STreehugger Robot    line: The line of code to check.
3457*7c3d14c8STreehugger Robot    raw_line: The raw line of code to check, with comments.
3458*7c3d14c8STreehugger Robot    cast_type: The string for the C++ cast to recommend.  This is either
3459*7c3d14c8STreehugger Robot      reinterpret_cast, static_cast, or const_cast, depending.
3460*7c3d14c8STreehugger Robot    pattern: The regular expression used to find C-style casts.
3461*7c3d14c8STreehugger Robot    error: The function to call with any errors found.
3462*7c3d14c8STreehugger Robot
3463*7c3d14c8STreehugger Robot  Returns:
3464*7c3d14c8STreehugger Robot    True if an error was emitted.
3465*7c3d14c8STreehugger Robot    False otherwise.
3466*7c3d14c8STreehugger Robot  """
3467*7c3d14c8STreehugger Robot  match = Search(pattern, line)
3468*7c3d14c8STreehugger Robot  if not match:
3469*7c3d14c8STreehugger Robot    return False
3470*7c3d14c8STreehugger Robot
3471*7c3d14c8STreehugger Robot  # e.g., sizeof(int)
3472*7c3d14c8STreehugger Robot  sizeof_match = Match(r'.*sizeof\s*$', line[0:match.start(1) - 1])
3473*7c3d14c8STreehugger Robot  if sizeof_match:
3474*7c3d14c8STreehugger Robot    error(filename, linenum, 'runtime/sizeof', 1,
3475*7c3d14c8STreehugger Robot          'Using sizeof(type).  Use sizeof(varname) instead if possible')
3476*7c3d14c8STreehugger Robot    return True
3477*7c3d14c8STreehugger Robot
3478*7c3d14c8STreehugger Robot  # operator++(int) and operator--(int)
3479*7c3d14c8STreehugger Robot  if (line[0:match.start(1) - 1].endswith(' operator++') or
3480*7c3d14c8STreehugger Robot      line[0:match.start(1) - 1].endswith(' operator--')):
3481*7c3d14c8STreehugger Robot    return False
3482*7c3d14c8STreehugger Robot
3483*7c3d14c8STreehugger Robot  remainder = line[match.end(0):]
3484*7c3d14c8STreehugger Robot
3485*7c3d14c8STreehugger Robot  # The close paren is for function pointers as arguments to a function.
3486*7c3d14c8STreehugger Robot  # eg, void foo(void (*bar)(int));
3487*7c3d14c8STreehugger Robot  # The semicolon check is a more basic function check; also possibly a
3488*7c3d14c8STreehugger Robot  # function pointer typedef.
3489*7c3d14c8STreehugger Robot  # eg, void foo(int); or void foo(int) const;
3490*7c3d14c8STreehugger Robot  # The equals check is for function pointer assignment.
3491*7c3d14c8STreehugger Robot  # eg, void *(*foo)(int) = ...
3492*7c3d14c8STreehugger Robot  # The > is for MockCallback<...> ...
3493*7c3d14c8STreehugger Robot  #
3494*7c3d14c8STreehugger Robot  # Right now, this will only catch cases where there's a single argument, and
3495*7c3d14c8STreehugger Robot  # it's unnamed.  It should probably be expanded to check for multiple
3496*7c3d14c8STreehugger Robot  # arguments with some unnamed.
3497*7c3d14c8STreehugger Robot  function_match = Match(r'\s*(\)|=|(const)?\s*(;|\{|throw\(\)|>))', remainder)
3498*7c3d14c8STreehugger Robot  if function_match:
3499*7c3d14c8STreehugger Robot    if (not function_match.group(3) or
3500*7c3d14c8STreehugger Robot        function_match.group(3) == ';' or
3501*7c3d14c8STreehugger Robot        ('MockCallback<' not in raw_line and
3502*7c3d14c8STreehugger Robot         '/*' not in raw_line)):
3503*7c3d14c8STreehugger Robot      error(filename, linenum, 'readability/function', 3,
3504*7c3d14c8STreehugger Robot            'All parameters should be named in a function')
3505*7c3d14c8STreehugger Robot    return True
3506*7c3d14c8STreehugger Robot
3507*7c3d14c8STreehugger Robot  # At this point, all that should be left is actual casts.
3508*7c3d14c8STreehugger Robot  error(filename, linenum, 'readability/casting', 4,
3509*7c3d14c8STreehugger Robot        'Using C-style cast.  Use %s<%s>(...) instead' %
3510*7c3d14c8STreehugger Robot        (cast_type, match.group(1)))
3511*7c3d14c8STreehugger Robot
3512*7c3d14c8STreehugger Robot  return True
3513*7c3d14c8STreehugger Robot
3514*7c3d14c8STreehugger Robot
3515*7c3d14c8STreehugger Robot_HEADERS_CONTAINING_TEMPLATES = (
3516*7c3d14c8STreehugger Robot    ('<deque>', ('deque',)),
3517*7c3d14c8STreehugger Robot    ('<functional>', ('unary_function', 'binary_function',
3518*7c3d14c8STreehugger Robot                      'plus', 'minus', 'multiplies', 'divides', 'modulus',
3519*7c3d14c8STreehugger Robot                      'negate',
3520*7c3d14c8STreehugger Robot                      'equal_to', 'not_equal_to', 'greater', 'less',
3521*7c3d14c8STreehugger Robot                      'greater_equal', 'less_equal',
3522*7c3d14c8STreehugger Robot                      'logical_and', 'logical_or', 'logical_not',
3523*7c3d14c8STreehugger Robot                      'unary_negate', 'not1', 'binary_negate', 'not2',
3524*7c3d14c8STreehugger Robot                      'bind1st', 'bind2nd',
3525*7c3d14c8STreehugger Robot                      'pointer_to_unary_function',
3526*7c3d14c8STreehugger Robot                      'pointer_to_binary_function',
3527*7c3d14c8STreehugger Robot                      'ptr_fun',
3528*7c3d14c8STreehugger Robot                      'mem_fun_t', 'mem_fun', 'mem_fun1_t', 'mem_fun1_ref_t',
3529*7c3d14c8STreehugger Robot                      'mem_fun_ref_t',
3530*7c3d14c8STreehugger Robot                      'const_mem_fun_t', 'const_mem_fun1_t',
3531*7c3d14c8STreehugger Robot                      'const_mem_fun_ref_t', 'const_mem_fun1_ref_t',
3532*7c3d14c8STreehugger Robot                      'mem_fun_ref',
3533*7c3d14c8STreehugger Robot                     )),
3534*7c3d14c8STreehugger Robot    ('<limits>', ('numeric_limits',)),
3535*7c3d14c8STreehugger Robot    ('<list>', ('list',)),
3536*7c3d14c8STreehugger Robot    ('<map>', ('map', 'multimap',)),
3537*7c3d14c8STreehugger Robot    ('<memory>', ('allocator',)),
3538*7c3d14c8STreehugger Robot    ('<queue>', ('queue', 'priority_queue',)),
3539*7c3d14c8STreehugger Robot    ('<set>', ('set', 'multiset',)),
3540*7c3d14c8STreehugger Robot    ('<stack>', ('stack',)),
3541*7c3d14c8STreehugger Robot    ('<string>', ('char_traits', 'basic_string',)),
3542*7c3d14c8STreehugger Robot    ('<utility>', ('pair',)),
3543*7c3d14c8STreehugger Robot    ('<vector>', ('vector',)),
3544*7c3d14c8STreehugger Robot
3545*7c3d14c8STreehugger Robot    # gcc extensions.
3546*7c3d14c8STreehugger Robot    # Note: std::hash is their hash, ::hash is our hash
3547*7c3d14c8STreehugger Robot    ('<hash_map>', ('hash_map', 'hash_multimap',)),
3548*7c3d14c8STreehugger Robot    ('<hash_set>', ('hash_set', 'hash_multiset',)),
3549*7c3d14c8STreehugger Robot    ('<slist>', ('slist',)),
3550*7c3d14c8STreehugger Robot    )
3551*7c3d14c8STreehugger Robot
3552*7c3d14c8STreehugger Robot_RE_PATTERN_STRING = re.compile(r'\bstring\b')
3553*7c3d14c8STreehugger Robot
3554*7c3d14c8STreehugger Robot_re_pattern_algorithm_header = []
3555*7c3d14c8STreehugger Robotfor _template in ('copy', 'max', 'min', 'min_element', 'sort', 'swap',
3556*7c3d14c8STreehugger Robot                  'transform'):
3557*7c3d14c8STreehugger Robot  # Match max<type>(..., ...), max(..., ...), but not foo->max, foo.max or
3558*7c3d14c8STreehugger Robot  # type::max().
3559*7c3d14c8STreehugger Robot  _re_pattern_algorithm_header.append(
3560*7c3d14c8STreehugger Robot      (re.compile(r'[^>.]\b' + _template + r'(<.*?>)?\([^\)]'),
3561*7c3d14c8STreehugger Robot       _template,
3562*7c3d14c8STreehugger Robot       '<algorithm>'))
3563*7c3d14c8STreehugger Robot
3564*7c3d14c8STreehugger Robot_re_pattern_templates = []
3565*7c3d14c8STreehugger Robotfor _header, _templates in _HEADERS_CONTAINING_TEMPLATES:
3566*7c3d14c8STreehugger Robot  for _template in _templates:
3567*7c3d14c8STreehugger Robot    _re_pattern_templates.append(
3568*7c3d14c8STreehugger Robot        (re.compile(r'(\<|\b)' + _template + r'\s*\<'),
3569*7c3d14c8STreehugger Robot         _template + '<>',
3570*7c3d14c8STreehugger Robot         _header))
3571*7c3d14c8STreehugger Robot
3572*7c3d14c8STreehugger Robot
3573*7c3d14c8STreehugger Robotdef FilesBelongToSameModule(filename_cc, filename_h):
3574*7c3d14c8STreehugger Robot  """Check if these two filenames belong to the same module.
3575*7c3d14c8STreehugger Robot
3576*7c3d14c8STreehugger Robot  The concept of a 'module' here is a as follows:
3577*7c3d14c8STreehugger Robot  foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the
3578*7c3d14c8STreehugger Robot  same 'module' if they are in the same directory.
3579*7c3d14c8STreehugger Robot  some/path/public/xyzzy and some/path/internal/xyzzy are also considered
3580*7c3d14c8STreehugger Robot  to belong to the same module here.
3581*7c3d14c8STreehugger Robot
3582*7c3d14c8STreehugger Robot  If the filename_cc contains a longer path than the filename_h, for example,
3583*7c3d14c8STreehugger Robot  '/absolute/path/to/base/sysinfo.cc', and this file would include
3584*7c3d14c8STreehugger Robot  'base/sysinfo.h', this function also produces the prefix needed to open the
3585*7c3d14c8STreehugger Robot  header. This is used by the caller of this function to more robustly open the
3586*7c3d14c8STreehugger Robot  header file. We don't have access to the real include paths in this context,
3587*7c3d14c8STreehugger Robot  so we need this guesswork here.
3588*7c3d14c8STreehugger Robot
3589*7c3d14c8STreehugger Robot  Known bugs: tools/base/bar.cc and base/bar.h belong to the same module
3590*7c3d14c8STreehugger Robot  according to this implementation. Because of this, this function gives
3591*7c3d14c8STreehugger Robot  some false positives. This should be sufficiently rare in practice.
3592*7c3d14c8STreehugger Robot
3593*7c3d14c8STreehugger Robot  Args:
3594*7c3d14c8STreehugger Robot    filename_cc: is the path for the .cc file
3595*7c3d14c8STreehugger Robot    filename_h: is the path for the header path
3596*7c3d14c8STreehugger Robot
3597*7c3d14c8STreehugger Robot  Returns:
3598*7c3d14c8STreehugger Robot    Tuple with a bool and a string:
3599*7c3d14c8STreehugger Robot    bool: True if filename_cc and filename_h belong to the same module.
3600*7c3d14c8STreehugger Robot    string: the additional prefix needed to open the header file.
3601*7c3d14c8STreehugger Robot  """
3602*7c3d14c8STreehugger Robot
3603*7c3d14c8STreehugger Robot  if not filename_cc.endswith('.cc'):
3604*7c3d14c8STreehugger Robot    return (False, '')
3605*7c3d14c8STreehugger Robot  filename_cc = filename_cc[:-len('.cc')]
3606*7c3d14c8STreehugger Robot  if filename_cc.endswith('_unittest'):
3607*7c3d14c8STreehugger Robot    filename_cc = filename_cc[:-len('_unittest')]
3608*7c3d14c8STreehugger Robot  elif filename_cc.endswith('_test'):
3609*7c3d14c8STreehugger Robot    filename_cc = filename_cc[:-len('_test')]
3610*7c3d14c8STreehugger Robot  filename_cc = filename_cc.replace('/public/', '/')
3611*7c3d14c8STreehugger Robot  filename_cc = filename_cc.replace('/internal/', '/')
3612*7c3d14c8STreehugger Robot
3613*7c3d14c8STreehugger Robot  if not filename_h.endswith('.h'):
3614*7c3d14c8STreehugger Robot    return (False, '')
3615*7c3d14c8STreehugger Robot  filename_h = filename_h[:-len('.h')]
3616*7c3d14c8STreehugger Robot  if filename_h.endswith('-inl'):
3617*7c3d14c8STreehugger Robot    filename_h = filename_h[:-len('-inl')]
3618*7c3d14c8STreehugger Robot  filename_h = filename_h.replace('/public/', '/')
3619*7c3d14c8STreehugger Robot  filename_h = filename_h.replace('/internal/', '/')
3620*7c3d14c8STreehugger Robot
3621*7c3d14c8STreehugger Robot  files_belong_to_same_module = filename_cc.endswith(filename_h)
3622*7c3d14c8STreehugger Robot  common_path = ''
3623*7c3d14c8STreehugger Robot  if files_belong_to_same_module:
3624*7c3d14c8STreehugger Robot    common_path = filename_cc[:-len(filename_h)]
3625*7c3d14c8STreehugger Robot  return files_belong_to_same_module, common_path
3626*7c3d14c8STreehugger Robot
3627*7c3d14c8STreehugger Robot
3628*7c3d14c8STreehugger Robotdef UpdateIncludeState(filename, include_state, io=codecs):
3629*7c3d14c8STreehugger Robot  """Fill up the include_state with new includes found from the file.
3630*7c3d14c8STreehugger Robot
3631*7c3d14c8STreehugger Robot  Args:
3632*7c3d14c8STreehugger Robot    filename: the name of the header to read.
3633*7c3d14c8STreehugger Robot    include_state: an _IncludeState instance in which the headers are inserted.
3634*7c3d14c8STreehugger Robot    io: The io factory to use to read the file. Provided for testability.
3635*7c3d14c8STreehugger Robot
3636*7c3d14c8STreehugger Robot  Returns:
3637*7c3d14c8STreehugger Robot    True if a header was successfully added. False otherwise.
3638*7c3d14c8STreehugger Robot  """
3639*7c3d14c8STreehugger Robot  headerfile = None
3640*7c3d14c8STreehugger Robot  try:
3641*7c3d14c8STreehugger Robot    headerfile = io.open(filename, 'r', 'utf8', 'replace')
3642*7c3d14c8STreehugger Robot  except IOError:
3643*7c3d14c8STreehugger Robot    return False
3644*7c3d14c8STreehugger Robot  linenum = 0
3645*7c3d14c8STreehugger Robot  for line in headerfile:
3646*7c3d14c8STreehugger Robot    linenum += 1
3647*7c3d14c8STreehugger Robot    clean_line = CleanseComments(line)
3648*7c3d14c8STreehugger Robot    match = _RE_PATTERN_INCLUDE.search(clean_line)
3649*7c3d14c8STreehugger Robot    if match:
3650*7c3d14c8STreehugger Robot      include = match.group(2)
3651*7c3d14c8STreehugger Robot      # The value formatting is cute, but not really used right now.
3652*7c3d14c8STreehugger Robot      # What matters here is that the key is in include_state.
3653*7c3d14c8STreehugger Robot      include_state.setdefault(include, '%s:%d' % (filename, linenum))
3654*7c3d14c8STreehugger Robot  return True
3655*7c3d14c8STreehugger Robot
3656*7c3d14c8STreehugger Robot
3657*7c3d14c8STreehugger Robotdef CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error,
3658*7c3d14c8STreehugger Robot                              io=codecs):
3659*7c3d14c8STreehugger Robot  """Reports for missing stl includes.
3660*7c3d14c8STreehugger Robot
3661*7c3d14c8STreehugger Robot  This function will output warnings to make sure you are including the headers
3662*7c3d14c8STreehugger Robot  necessary for the stl containers and functions that you use. We only give one
3663*7c3d14c8STreehugger Robot  reason to include a header. For example, if you use both equal_to<> and
3664*7c3d14c8STreehugger Robot  less<> in a .h file, only one (the latter in the file) of these will be
3665*7c3d14c8STreehugger Robot  reported as a reason to include the <functional>.
3666*7c3d14c8STreehugger Robot
3667*7c3d14c8STreehugger Robot  Args:
3668*7c3d14c8STreehugger Robot    filename: The name of the current file.
3669*7c3d14c8STreehugger Robot    clean_lines: A CleansedLines instance containing the file.
3670*7c3d14c8STreehugger Robot    include_state: An _IncludeState instance.
3671*7c3d14c8STreehugger Robot    error: The function to call with any errors found.
3672*7c3d14c8STreehugger Robot    io: The IO factory to use to read the header file. Provided for unittest
3673*7c3d14c8STreehugger Robot        injection.
3674*7c3d14c8STreehugger Robot  """
3675*7c3d14c8STreehugger Robot  required = {}  # A map of header name to linenumber and the template entity.
3676*7c3d14c8STreehugger Robot                 # Example of required: { '<functional>': (1219, 'less<>') }
3677*7c3d14c8STreehugger Robot
3678*7c3d14c8STreehugger Robot  for linenum in xrange(clean_lines.NumLines()):
3679*7c3d14c8STreehugger Robot    line = clean_lines.elided[linenum]
3680*7c3d14c8STreehugger Robot    if not line or line[0] == '#':
3681*7c3d14c8STreehugger Robot      continue
3682*7c3d14c8STreehugger Robot
3683*7c3d14c8STreehugger Robot    # String is special -- it is a non-templatized type in STL.
3684*7c3d14c8STreehugger Robot    matched = _RE_PATTERN_STRING.search(line)
3685*7c3d14c8STreehugger Robot    if matched:
3686*7c3d14c8STreehugger Robot      # Don't warn about strings in non-STL namespaces:
3687*7c3d14c8STreehugger Robot      # (We check only the first match per line; good enough.)
3688*7c3d14c8STreehugger Robot      prefix = line[:matched.start()]
3689*7c3d14c8STreehugger Robot      if prefix.endswith('std::') or not prefix.endswith('::'):
3690*7c3d14c8STreehugger Robot        required['<string>'] = (linenum, 'string')
3691*7c3d14c8STreehugger Robot
3692*7c3d14c8STreehugger Robot    for pattern, template, header in _re_pattern_algorithm_header:
3693*7c3d14c8STreehugger Robot      if pattern.search(line):
3694*7c3d14c8STreehugger Robot        required[header] = (linenum, template)
3695*7c3d14c8STreehugger Robot
3696*7c3d14c8STreehugger Robot    # The following function is just a speed up, no semantics are changed.
3697*7c3d14c8STreehugger Robot    if not '<' in line:  # Reduces the cpu time usage by skipping lines.
3698*7c3d14c8STreehugger Robot      continue
3699*7c3d14c8STreehugger Robot
3700*7c3d14c8STreehugger Robot    for pattern, template, header in _re_pattern_templates:
3701*7c3d14c8STreehugger Robot      if pattern.search(line):
3702*7c3d14c8STreehugger Robot        required[header] = (linenum, template)
3703*7c3d14c8STreehugger Robot
3704*7c3d14c8STreehugger Robot  # The policy is that if you #include something in foo.h you don't need to
3705*7c3d14c8STreehugger Robot  # include it again in foo.cc. Here, we will look at possible includes.
3706*7c3d14c8STreehugger Robot  # Let's copy the include_state so it is only messed up within this function.
3707*7c3d14c8STreehugger Robot  include_state = include_state.copy()
3708*7c3d14c8STreehugger Robot
3709*7c3d14c8STreehugger Robot  # Did we find the header for this file (if any) and successfully load it?
3710*7c3d14c8STreehugger Robot  header_found = False
3711*7c3d14c8STreehugger Robot
3712*7c3d14c8STreehugger Robot  # Use the absolute path so that matching works properly.
3713*7c3d14c8STreehugger Robot  abs_filename = FileInfo(filename).FullName()
3714*7c3d14c8STreehugger Robot
3715*7c3d14c8STreehugger Robot  # For Emacs's flymake.
3716*7c3d14c8STreehugger Robot  # If cpplint is invoked from Emacs's flymake, a temporary file is generated
3717*7c3d14c8STreehugger Robot  # by flymake and that file name might end with '_flymake.cc'. In that case,
3718*7c3d14c8STreehugger Robot  # restore original file name here so that the corresponding header file can be
3719*7c3d14c8STreehugger Robot  # found.
3720*7c3d14c8STreehugger Robot  # e.g. If the file name is 'foo_flymake.cc', we should search for 'foo.h'
3721*7c3d14c8STreehugger Robot  # instead of 'foo_flymake.h'
3722*7c3d14c8STreehugger Robot  abs_filename = re.sub(r'_flymake\.cc$', '.cc', abs_filename)
3723*7c3d14c8STreehugger Robot
3724*7c3d14c8STreehugger Robot  # include_state is modified during iteration, so we iterate over a copy of
3725*7c3d14c8STreehugger Robot  # the keys.
3726*7c3d14c8STreehugger Robot  header_keys = include_state.keys()
3727*7c3d14c8STreehugger Robot  for header in header_keys:
3728*7c3d14c8STreehugger Robot    (same_module, common_path) = FilesBelongToSameModule(abs_filename, header)
3729*7c3d14c8STreehugger Robot    fullpath = common_path + header
3730*7c3d14c8STreehugger Robot    if same_module and UpdateIncludeState(fullpath, include_state, io):
3731*7c3d14c8STreehugger Robot      header_found = True
3732*7c3d14c8STreehugger Robot
3733*7c3d14c8STreehugger Robot  # If we can't find the header file for a .cc, assume it's because we don't
3734*7c3d14c8STreehugger Robot  # know where to look. In that case we'll give up as we're not sure they
3735*7c3d14c8STreehugger Robot  # didn't include it in the .h file.
3736*7c3d14c8STreehugger Robot  # TODO(unknown): Do a better job of finding .h files so we are confident that
3737*7c3d14c8STreehugger Robot  # not having the .h file means there isn't one.
3738*7c3d14c8STreehugger Robot  if filename.endswith('.cc') and not header_found:
3739*7c3d14c8STreehugger Robot    return
3740*7c3d14c8STreehugger Robot
3741*7c3d14c8STreehugger Robot  # All the lines have been processed, report the errors found.
3742*7c3d14c8STreehugger Robot  for required_header_unstripped in required:
3743*7c3d14c8STreehugger Robot    template = required[required_header_unstripped][1]
3744*7c3d14c8STreehugger Robot    if required_header_unstripped.strip('<>"') not in include_state:
3745*7c3d14c8STreehugger Robot      error(filename, required[required_header_unstripped][0],
3746*7c3d14c8STreehugger Robot            'build/include_what_you_use', 4,
3747*7c3d14c8STreehugger Robot            'Add #include ' + required_header_unstripped + ' for ' + template)
3748*7c3d14c8STreehugger Robot
3749*7c3d14c8STreehugger Robot
3750*7c3d14c8STreehugger Robot_RE_PATTERN_EXPLICIT_MAKEPAIR = re.compile(r'\bmake_pair\s*<')
3751*7c3d14c8STreehugger Robot
3752*7c3d14c8STreehugger Robot
3753*7c3d14c8STreehugger Robotdef CheckMakePairUsesDeduction(filename, clean_lines, linenum, error):
3754*7c3d14c8STreehugger Robot  """Check that make_pair's template arguments are deduced.
3755*7c3d14c8STreehugger Robot
3756*7c3d14c8STreehugger Robot  G++ 4.6 in C++0x mode fails badly if make_pair's template arguments are
3757*7c3d14c8STreehugger Robot  specified explicitly, and such use isn't intended in any case.
3758*7c3d14c8STreehugger Robot
3759*7c3d14c8STreehugger Robot  Args:
3760*7c3d14c8STreehugger Robot    filename: The name of the current file.
3761*7c3d14c8STreehugger Robot    clean_lines: A CleansedLines instance containing the file.
3762*7c3d14c8STreehugger Robot    linenum: The number of the line to check.
3763*7c3d14c8STreehugger Robot    error: The function to call with any errors found.
3764*7c3d14c8STreehugger Robot  """
3765*7c3d14c8STreehugger Robot  raw = clean_lines.raw_lines
3766*7c3d14c8STreehugger Robot  line = raw[linenum]
3767*7c3d14c8STreehugger Robot  match = _RE_PATTERN_EXPLICIT_MAKEPAIR.search(line)
3768*7c3d14c8STreehugger Robot  if match:
3769*7c3d14c8STreehugger Robot    error(filename, linenum, 'build/explicit_make_pair',
3770*7c3d14c8STreehugger Robot          4,  # 4 = high confidence
3771*7c3d14c8STreehugger Robot          'For C++11-compatibility, omit template arguments from make_pair'
3772*7c3d14c8STreehugger Robot          ' OR use pair directly OR if appropriate, construct a pair directly')
3773*7c3d14c8STreehugger Robot
3774*7c3d14c8STreehugger Robot
3775*7c3d14c8STreehugger Robotdef ProcessLine(filename, file_extension, clean_lines, line,
3776*7c3d14c8STreehugger Robot                include_state, function_state, nesting_state, error,
3777*7c3d14c8STreehugger Robot                extra_check_functions=[]):
3778*7c3d14c8STreehugger Robot  """Processes a single line in the file.
3779*7c3d14c8STreehugger Robot
3780*7c3d14c8STreehugger Robot  Args:
3781*7c3d14c8STreehugger Robot    filename: Filename of the file that is being processed.
3782*7c3d14c8STreehugger Robot    file_extension: The extension (dot not included) of the file.
3783*7c3d14c8STreehugger Robot    clean_lines: An array of strings, each representing a line of the file,
3784*7c3d14c8STreehugger Robot                 with comments stripped.
3785*7c3d14c8STreehugger Robot    line: Number of line being processed.
3786*7c3d14c8STreehugger Robot    include_state: An _IncludeState instance in which the headers are inserted.
3787*7c3d14c8STreehugger Robot    function_state: A _FunctionState instance which counts function lines, etc.
3788*7c3d14c8STreehugger Robot    nesting_state: A _NestingState instance which maintains information about
3789*7c3d14c8STreehugger Robot                   the current stack of nested blocks being parsed.
3790*7c3d14c8STreehugger Robot    error: A callable to which errors are reported, which takes 4 arguments:
3791*7c3d14c8STreehugger Robot           filename, line number, error level, and message
3792*7c3d14c8STreehugger Robot    extra_check_functions: An array of additional check functions that will be
3793*7c3d14c8STreehugger Robot                           run on each source line. Each function takes 4
3794*7c3d14c8STreehugger Robot                           arguments: filename, clean_lines, line, error
3795*7c3d14c8STreehugger Robot  """
3796*7c3d14c8STreehugger Robot  raw_lines = clean_lines.raw_lines
3797*7c3d14c8STreehugger Robot  ParseNolintSuppressions(filename, raw_lines[line], line, error)
3798*7c3d14c8STreehugger Robot  nesting_state.Update(filename, clean_lines, line, error)
3799*7c3d14c8STreehugger Robot  if nesting_state.stack and nesting_state.stack[-1].inline_asm != _NO_ASM:
3800*7c3d14c8STreehugger Robot    return
3801*7c3d14c8STreehugger Robot  CheckForFunctionLengths(filename, clean_lines, line, function_state, error)
3802*7c3d14c8STreehugger Robot  CheckForMultilineCommentsAndStrings(filename, clean_lines, line, error)
3803*7c3d14c8STreehugger Robot  CheckStyle(filename, clean_lines, line, file_extension, nesting_state, error)
3804*7c3d14c8STreehugger Robot  CheckLanguage(filename, clean_lines, line, file_extension, include_state,
3805*7c3d14c8STreehugger Robot                error)
3806*7c3d14c8STreehugger Robot  CheckForNonStandardConstructs(filename, clean_lines, line,
3807*7c3d14c8STreehugger Robot                                nesting_state, error)
3808*7c3d14c8STreehugger Robot  CheckPosixThreading(filename, clean_lines, line, error)
3809*7c3d14c8STreehugger Robot  CheckInvalidIncrement(filename, clean_lines, line, error)
3810*7c3d14c8STreehugger Robot  CheckMakePairUsesDeduction(filename, clean_lines, line, error)
3811*7c3d14c8STreehugger Robot  for check_fn in extra_check_functions:
3812*7c3d14c8STreehugger Robot    check_fn(filename, clean_lines, line, error)
3813*7c3d14c8STreehugger Robot
3814*7c3d14c8STreehugger Robotdef ProcessFileData(filename, file_extension, lines, error,
3815*7c3d14c8STreehugger Robot                    extra_check_functions=[]):
3816*7c3d14c8STreehugger Robot  """Performs lint checks and reports any errors to the given error function.
3817*7c3d14c8STreehugger Robot
3818*7c3d14c8STreehugger Robot  Args:
3819*7c3d14c8STreehugger Robot    filename: Filename of the file that is being processed.
3820*7c3d14c8STreehugger Robot    file_extension: The extension (dot not included) of the file.
3821*7c3d14c8STreehugger Robot    lines: An array of strings, each representing a line of the file, with the
3822*7c3d14c8STreehugger Robot           last element being empty if the file is terminated with a newline.
3823*7c3d14c8STreehugger Robot    error: A callable to which errors are reported, which takes 4 arguments:
3824*7c3d14c8STreehugger Robot           filename, line number, error level, and message
3825*7c3d14c8STreehugger Robot    extra_check_functions: An array of additional check functions that will be
3826*7c3d14c8STreehugger Robot                           run on each source line. Each function takes 4
3827*7c3d14c8STreehugger Robot                           arguments: filename, clean_lines, line, error
3828*7c3d14c8STreehugger Robot  """
3829*7c3d14c8STreehugger Robot  lines = (['// marker so line numbers and indices both start at 1'] + lines +
3830*7c3d14c8STreehugger Robot           ['// marker so line numbers end in a known way'])
3831*7c3d14c8STreehugger Robot
3832*7c3d14c8STreehugger Robot  include_state = _IncludeState()
3833*7c3d14c8STreehugger Robot  function_state = _FunctionState()
3834*7c3d14c8STreehugger Robot  nesting_state = _NestingState()
3835*7c3d14c8STreehugger Robot
3836*7c3d14c8STreehugger Robot  ResetNolintSuppressions()
3837*7c3d14c8STreehugger Robot
3838*7c3d14c8STreehugger Robot  CheckForCopyright(filename, lines, error)
3839*7c3d14c8STreehugger Robot
3840*7c3d14c8STreehugger Robot  if file_extension == 'h':
3841*7c3d14c8STreehugger Robot    CheckForHeaderGuard(filename, lines, error)
3842*7c3d14c8STreehugger Robot
3843*7c3d14c8STreehugger Robot  RemoveMultiLineComments(filename, lines, error)
3844*7c3d14c8STreehugger Robot  clean_lines = CleansedLines(lines)
3845*7c3d14c8STreehugger Robot  for line in xrange(clean_lines.NumLines()):
3846*7c3d14c8STreehugger Robot    ProcessLine(filename, file_extension, clean_lines, line,
3847*7c3d14c8STreehugger Robot                include_state, function_state, nesting_state, error,
3848*7c3d14c8STreehugger Robot                extra_check_functions)
3849*7c3d14c8STreehugger Robot  nesting_state.CheckClassFinished(filename, error)
3850*7c3d14c8STreehugger Robot
3851*7c3d14c8STreehugger Robot  CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error)
3852*7c3d14c8STreehugger Robot
3853*7c3d14c8STreehugger Robot  # We check here rather than inside ProcessLine so that we see raw
3854*7c3d14c8STreehugger Robot  # lines rather than "cleaned" lines.
3855*7c3d14c8STreehugger Robot  CheckForUnicodeReplacementCharacters(filename, lines, error)
3856*7c3d14c8STreehugger Robot
3857*7c3d14c8STreehugger Robot  CheckForNewlineAtEOF(filename, lines, error)
3858*7c3d14c8STreehugger Robot
3859*7c3d14c8STreehugger Robotdef ProcessFile(filename, vlevel, extra_check_functions=[]):
3860*7c3d14c8STreehugger Robot  """Does google-lint on a single file.
3861*7c3d14c8STreehugger Robot
3862*7c3d14c8STreehugger Robot  Args:
3863*7c3d14c8STreehugger Robot    filename: The name of the file to parse.
3864*7c3d14c8STreehugger Robot
3865*7c3d14c8STreehugger Robot    vlevel: The level of errors to report.  Every error of confidence
3866*7c3d14c8STreehugger Robot    >= verbose_level will be reported.  0 is a good default.
3867*7c3d14c8STreehugger Robot
3868*7c3d14c8STreehugger Robot    extra_check_functions: An array of additional check functions that will be
3869*7c3d14c8STreehugger Robot                           run on each source line. Each function takes 4
3870*7c3d14c8STreehugger Robot                           arguments: filename, clean_lines, line, error
3871*7c3d14c8STreehugger Robot  """
3872*7c3d14c8STreehugger Robot
3873*7c3d14c8STreehugger Robot  _SetVerboseLevel(vlevel)
3874*7c3d14c8STreehugger Robot
3875*7c3d14c8STreehugger Robot  try:
3876*7c3d14c8STreehugger Robot    # Support the UNIX convention of using "-" for stdin.  Note that
3877*7c3d14c8STreehugger Robot    # we are not opening the file with universal newline support
3878*7c3d14c8STreehugger Robot    # (which codecs doesn't support anyway), so the resulting lines do
3879*7c3d14c8STreehugger Robot    # contain trailing '\r' characters if we are reading a file that
3880*7c3d14c8STreehugger Robot    # has CRLF endings.
3881*7c3d14c8STreehugger Robot    # If after the split a trailing '\r' is present, it is removed
3882*7c3d14c8STreehugger Robot    # below. If it is not expected to be present (i.e. os.linesep !=
3883*7c3d14c8STreehugger Robot    # '\r\n' as in Windows), a warning is issued below if this file
3884*7c3d14c8STreehugger Robot    # is processed.
3885*7c3d14c8STreehugger Robot
3886*7c3d14c8STreehugger Robot    if filename == '-':
3887*7c3d14c8STreehugger Robot      lines = codecs.StreamReaderWriter(sys.stdin,
3888*7c3d14c8STreehugger Robot                                        codecs.getreader('utf8'),
3889*7c3d14c8STreehugger Robot                                        codecs.getwriter('utf8'),
3890*7c3d14c8STreehugger Robot                                        'replace').read().split('\n')
3891*7c3d14c8STreehugger Robot    else:
3892*7c3d14c8STreehugger Robot      lines = codecs.open(filename, 'r', 'utf8', 'replace').read().split('\n')
3893*7c3d14c8STreehugger Robot
3894*7c3d14c8STreehugger Robot    carriage_return_found = False
3895*7c3d14c8STreehugger Robot    # Remove trailing '\r'.
3896*7c3d14c8STreehugger Robot    for linenum in range(len(lines)):
3897*7c3d14c8STreehugger Robot      if lines[linenum].endswith('\r'):
3898*7c3d14c8STreehugger Robot        lines[linenum] = lines[linenum].rstrip('\r')
3899*7c3d14c8STreehugger Robot        carriage_return_found = True
3900*7c3d14c8STreehugger Robot
3901*7c3d14c8STreehugger Robot  except IOError:
3902*7c3d14c8STreehugger Robot    sys.stderr.write(
3903*7c3d14c8STreehugger Robot        "Skipping input '%s': Can't open for reading\n" % filename)
3904*7c3d14c8STreehugger Robot    return
3905*7c3d14c8STreehugger Robot
3906*7c3d14c8STreehugger Robot  # Note, if no dot is found, this will give the entire filename as the ext.
3907*7c3d14c8STreehugger Robot  file_extension = filename[filename.rfind('.') + 1:]
3908*7c3d14c8STreehugger Robot
3909*7c3d14c8STreehugger Robot  # When reading from stdin, the extension is unknown, so no cpplint tests
3910*7c3d14c8STreehugger Robot  # should rely on the extension.
3911*7c3d14c8STreehugger Robot  if (filename != '-' and file_extension != 'cc' and file_extension != 'h'
3912*7c3d14c8STreehugger Robot      and file_extension != 'cpp'):
3913*7c3d14c8STreehugger Robot    sys.stderr.write('Ignoring %s; not a .cc or .h file\n' % filename)
3914*7c3d14c8STreehugger Robot  else:
3915*7c3d14c8STreehugger Robot    ProcessFileData(filename, file_extension, lines, Error,
3916*7c3d14c8STreehugger Robot                    extra_check_functions)
3917*7c3d14c8STreehugger Robot    if carriage_return_found and os.linesep != '\r\n':
3918*7c3d14c8STreehugger Robot      # Use 0 for linenum since outputting only one error for potentially
3919*7c3d14c8STreehugger Robot      # several lines.
3920*7c3d14c8STreehugger Robot      Error(filename, 0, 'whitespace/newline', 1,
3921*7c3d14c8STreehugger Robot            'One or more unexpected \\r (^M) found;'
3922*7c3d14c8STreehugger Robot            'better to use only a \\n')
3923*7c3d14c8STreehugger Robot
3924*7c3d14c8STreehugger Robot  sys.stderr.write('Done processing %s\n' % filename)
3925*7c3d14c8STreehugger Robot
3926*7c3d14c8STreehugger Robot
3927*7c3d14c8STreehugger Robotdef PrintUsage(message):
3928*7c3d14c8STreehugger Robot  """Prints a brief usage string and exits, optionally with an error message.
3929*7c3d14c8STreehugger Robot
3930*7c3d14c8STreehugger Robot  Args:
3931*7c3d14c8STreehugger Robot    message: The optional error message.
3932*7c3d14c8STreehugger Robot  """
3933*7c3d14c8STreehugger Robot  sys.stderr.write(_USAGE)
3934*7c3d14c8STreehugger Robot  if message:
3935*7c3d14c8STreehugger Robot    sys.exit('\nFATAL ERROR: ' + message)
3936*7c3d14c8STreehugger Robot  else:
3937*7c3d14c8STreehugger Robot    sys.exit(1)
3938*7c3d14c8STreehugger Robot
3939*7c3d14c8STreehugger Robot
3940*7c3d14c8STreehugger Robotdef PrintCategories():
3941*7c3d14c8STreehugger Robot  """Prints a list of all the error-categories used by error messages.
3942*7c3d14c8STreehugger Robot
3943*7c3d14c8STreehugger Robot  These are the categories used to filter messages via --filter.
3944*7c3d14c8STreehugger Robot  """
3945*7c3d14c8STreehugger Robot  sys.stderr.write(''.join('  %s\n' % cat for cat in _ERROR_CATEGORIES))
3946*7c3d14c8STreehugger Robot  sys.exit(0)
3947*7c3d14c8STreehugger Robot
3948*7c3d14c8STreehugger Robot
3949*7c3d14c8STreehugger Robotdef ParseArguments(args):
3950*7c3d14c8STreehugger Robot  """Parses the command line arguments.
3951*7c3d14c8STreehugger Robot
3952*7c3d14c8STreehugger Robot  This may set the output format and verbosity level as side-effects.
3953*7c3d14c8STreehugger Robot
3954*7c3d14c8STreehugger Robot  Args:
3955*7c3d14c8STreehugger Robot    args: The command line arguments:
3956*7c3d14c8STreehugger Robot
3957*7c3d14c8STreehugger Robot  Returns:
3958*7c3d14c8STreehugger Robot    The list of filenames to lint.
3959*7c3d14c8STreehugger Robot  """
3960*7c3d14c8STreehugger Robot  try:
3961*7c3d14c8STreehugger Robot    (opts, filenames) = getopt.getopt(args, '', ['help', 'output=', 'verbose=',
3962*7c3d14c8STreehugger Robot                                                 'counting=',
3963*7c3d14c8STreehugger Robot                                                 'filter=',
3964*7c3d14c8STreehugger Robot                                                 'root='])
3965*7c3d14c8STreehugger Robot  except getopt.GetoptError:
3966*7c3d14c8STreehugger Robot    PrintUsage('Invalid arguments.')
3967*7c3d14c8STreehugger Robot
3968*7c3d14c8STreehugger Robot  verbosity = _VerboseLevel()
3969*7c3d14c8STreehugger Robot  output_format = _OutputFormat()
3970*7c3d14c8STreehugger Robot  filters = ''
3971*7c3d14c8STreehugger Robot  counting_style = ''
3972*7c3d14c8STreehugger Robot
3973*7c3d14c8STreehugger Robot  for (opt, val) in opts:
3974*7c3d14c8STreehugger Robot    if opt == '--help':
3975*7c3d14c8STreehugger Robot      PrintUsage(None)
3976*7c3d14c8STreehugger Robot    elif opt == '--output':
3977*7c3d14c8STreehugger Robot      if not val in ('emacs', 'vs7', 'eclipse'):
3978*7c3d14c8STreehugger Robot        PrintUsage('The only allowed output formats are emacs, vs7 and eclipse.')
3979*7c3d14c8STreehugger Robot      output_format = val
3980*7c3d14c8STreehugger Robot    elif opt == '--verbose':
3981*7c3d14c8STreehugger Robot      verbosity = int(val)
3982*7c3d14c8STreehugger Robot    elif opt == '--filter':
3983*7c3d14c8STreehugger Robot      filters = val
3984*7c3d14c8STreehugger Robot      if not filters:
3985*7c3d14c8STreehugger Robot        PrintCategories()
3986*7c3d14c8STreehugger Robot    elif opt == '--counting':
3987*7c3d14c8STreehugger Robot      if val not in ('total', 'toplevel', 'detailed'):
3988*7c3d14c8STreehugger Robot        PrintUsage('Valid counting options are total, toplevel, and detailed')
3989*7c3d14c8STreehugger Robot      counting_style = val
3990*7c3d14c8STreehugger Robot    elif opt == '--root':
3991*7c3d14c8STreehugger Robot      global _root
3992*7c3d14c8STreehugger Robot      _root = val
3993*7c3d14c8STreehugger Robot
3994*7c3d14c8STreehugger Robot  if not filenames:
3995*7c3d14c8STreehugger Robot    PrintUsage('No files were specified.')
3996*7c3d14c8STreehugger Robot
3997*7c3d14c8STreehugger Robot  _SetOutputFormat(output_format)
3998*7c3d14c8STreehugger Robot  _SetVerboseLevel(verbosity)
3999*7c3d14c8STreehugger Robot  _SetFilters(filters)
4000*7c3d14c8STreehugger Robot  _SetCountingStyle(counting_style)
4001*7c3d14c8STreehugger Robot
4002*7c3d14c8STreehugger Robot  return filenames
4003*7c3d14c8STreehugger Robot
4004*7c3d14c8STreehugger Robot
4005*7c3d14c8STreehugger Robotdef main():
4006*7c3d14c8STreehugger Robot  filenames = ParseArguments(sys.argv[1:])
4007*7c3d14c8STreehugger Robot
4008*7c3d14c8STreehugger Robot  # Change stderr to write with replacement characters so we don't die
4009*7c3d14c8STreehugger Robot  # if we try to print something containing non-ASCII characters.
4010*7c3d14c8STreehugger Robot  sys.stderr = codecs.StreamReaderWriter(sys.stderr,
4011*7c3d14c8STreehugger Robot                                         codecs.getreader('utf8'),
4012*7c3d14c8STreehugger Robot                                         codecs.getwriter('utf8'),
4013*7c3d14c8STreehugger Robot                                         'replace')
4014*7c3d14c8STreehugger Robot
4015*7c3d14c8STreehugger Robot  _cpplint_state.ResetErrorCounts()
4016*7c3d14c8STreehugger Robot  for filename in filenames:
4017*7c3d14c8STreehugger Robot    ProcessFile(filename, _cpplint_state.verbose_level)
4018*7c3d14c8STreehugger Robot  _cpplint_state.PrintErrorCounts()
4019*7c3d14c8STreehugger Robot
4020*7c3d14c8STreehugger Robot  sys.exit(_cpplint_state.error_count > 0)
4021*7c3d14c8STreehugger Robot
4022*7c3d14c8STreehugger Robot
4023*7c3d14c8STreehugger Robotif __name__ == '__main__':
4024*7c3d14c8STreehugger Robot  main()
4025