cd4ad8e6f797e35b0da2de33a56b064ffd27c793
[WebKit-https.git] / Tools / Scripts / webkitpy / style / checkers / cpp_unittest.py
1 # -*- coding: utf-8; -*-
2 #
3 # Copyright (C) 2011 Google Inc. All rights reserved.
4 # Copyright (C) 2009 Torch Mobile Inc.
5 # Copyright (C) 2009, 2013 Apple Inc. All rights reserved.
6 # Copyright (C) 2010 Chris Jerdonek (cjerdonek@webkit.org)
7 #
8 # Redistribution and use in source and binary forms, with or without
9 # modification, are permitted provided that the following conditions are
10 # met:
11 #
12 #    * Redistributions of source code must retain the above copyright
13 # notice, this list of conditions and the following disclaimer.
14 #    * Redistributions in binary form must reproduce the above
15 # copyright notice, this list of conditions and the following disclaimer
16 # in the documentation and/or other materials provided with the
17 # distribution.
18 #    * Neither the name of Google Inc. nor the names of its
19 # contributors may be used to endorse or promote products derived from
20 # this software without specific prior written permission.
21 #
22 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
25 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
26 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
27 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
28 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
32 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33
34 """Unit test for cpp_style.py."""
35
36 # FIXME: Add a good test that tests UpdateIncludeState.
37
38 import codecs
39 import os
40 import random
41 import re
42 import unittest
43 import cpp as cpp_style
44 from cpp import CppChecker
45 from ..filter import FilterConfiguration
46
47
48 # This class works as an error collector and replaces cpp_style.Error
49 # function for the unit tests.  We also verify each category we see
50 # is in CppChecker.categories, to help keep that list up to date.
51 class ErrorCollector:
52     _all_style_categories = CppChecker.categories
53     # This is a list including all categories seen in any unit test.
54     _seen_style_categories = {}
55
56     def __init__(self, assert_fn, filter=None, lines_to_check=None):
57         """assert_fn: a function to call when we notice a problem.
58            filter: filters the errors that we are concerned about."""
59         self._assert_fn = assert_fn
60         self._errors = []
61         self._lines_to_check = lines_to_check
62         if not filter:
63             filter = FilterConfiguration()
64         self._filter = filter
65
66     def __call__(self, line_number, category, confidence, message):
67         self._assert_fn(category in self._all_style_categories,
68                         'Message "%s" has category "%s",'
69                         ' which is not in CppChecker.categories' % (message, category))
70
71         if self._lines_to_check and not line_number in self._lines_to_check:
72             return False
73
74         if self._filter.should_check(category, ""):
75             self._seen_style_categories[category] = 1
76             self._errors.append('%s  [%s] [%d]' % (message, category, confidence))
77         return True
78
79     def results(self):
80         if len(self._errors) < 2:
81             return ''.join(self._errors)  # Most tests expect to have a string.
82         else:
83             return self._errors  # Let's give a list if there is more than one.
84
85     def result_list(self):
86         return self._errors
87
88     def verify_all_categories_are_seen(self):
89         """Fails if there's a category in _all_style_categories - _seen_style_categories.
90
91         This should only be called after all tests are run, so
92         _seen_style_categories has had a chance to fully populate.  Since
93         this isn't called from within the normal unittest framework, we
94         can't use the normal unittest assert macros.  Instead we just exit
95         when we see an error.  Good thing this test is always run last!
96         """
97         for category in self._all_style_categories:
98             if category not in self._seen_style_categories:
99                 import sys
100                 sys.exit('FATAL ERROR: There are no tests for category "%s"' % category)
101
102
103 # This class is a lame mock of codecs. We do not verify filename, mode, or
104 # encoding, but for the current use case it is not needed.
105 class MockIo:
106     def __init__(self, mock_file):
107         self.mock_file = mock_file
108
109     def open(self, unused_filename, unused_mode, unused_encoding, _):  # NOLINT
110         # (lint doesn't like open as a method name)
111         return self.mock_file
112
113
114 class CppFunctionsTest(unittest.TestCase):
115
116     """Supports testing functions that do not need CppStyleTestBase."""
117
118     def test_convert_to_lower_with_underscores(self):
119         self.assertEqual(cpp_style._convert_to_lower_with_underscores('ABC'), 'abc')
120         self.assertEqual(cpp_style._convert_to_lower_with_underscores('aB'), 'a_b')
121         self.assertEqual(cpp_style._convert_to_lower_with_underscores('isAName'), 'is_a_name')
122         self.assertEqual(cpp_style._convert_to_lower_with_underscores('AnotherTest'), 'another_test')
123         self.assertEqual(cpp_style._convert_to_lower_with_underscores('PassRefPtr<MyClass>'), 'pass_ref_ptr<my_class>')
124         self.assertEqual(cpp_style._convert_to_lower_with_underscores('_ABC'), '_abc')
125
126     def test_create_acronym(self):
127         self.assertEqual(cpp_style._create_acronym('ABC'), 'ABC')
128         self.assertEqual(cpp_style._create_acronym('IsAName'), 'IAN')
129         self.assertEqual(cpp_style._create_acronym('PassRefPtr<MyClass>'), 'PRP<MC>')
130
131     def test_is_c_or_objective_c(self):
132         clean_lines = cpp_style.CleansedLines([''])
133         clean_objc_lines = cpp_style.CleansedLines(['#import "header.h"'])
134         self.assertTrue(cpp_style._FileState(clean_lines, 'c').is_c_or_objective_c())
135         self.assertTrue(cpp_style._FileState(clean_lines, 'm').is_c_or_objective_c())
136         self.assertFalse(cpp_style._FileState(clean_lines, 'cpp').is_c_or_objective_c())
137         self.assertFalse(cpp_style._FileState(clean_lines, 'cc').is_c_or_objective_c())
138         self.assertFalse(cpp_style._FileState(clean_lines, 'h').is_c_or_objective_c())
139         self.assertTrue(cpp_style._FileState(clean_objc_lines, 'h').is_c_or_objective_c())
140
141     def test_parameter(self):
142         # Test type.
143         parameter = cpp_style.Parameter('ExceptionCode', 13, 1)
144         self.assertEqual(parameter.type, 'ExceptionCode')
145         self.assertEqual(parameter.name, '')
146         self.assertEqual(parameter.row, 1)
147
148         # Test type and name.
149         parameter = cpp_style.Parameter('PassRefPtr<MyClass> parent', 19, 1)
150         self.assertEqual(parameter.type, 'PassRefPtr<MyClass>')
151         self.assertEqual(parameter.name, 'parent')
152         self.assertEqual(parameter.row, 1)
153
154         # Test type, no name, with default value.
155         parameter = cpp_style.Parameter('MyClass = 0', 7, 0)
156         self.assertEqual(parameter.type, 'MyClass')
157         self.assertEqual(parameter.name, '')
158         self.assertEqual(parameter.row, 0)
159
160         # Test type, name, and default value.
161         parameter = cpp_style.Parameter('MyClass a = 0', 7, 0)
162         self.assertEqual(parameter.type, 'MyClass')
163         self.assertEqual(parameter.name, 'a')
164         self.assertEqual(parameter.row, 0)
165
166     def test_single_line_view(self):
167         start_position = cpp_style.Position(row=1, column=1)
168         end_position = cpp_style.Position(row=3, column=1)
169         single_line_view = cpp_style.SingleLineView(['0', 'abcde', 'fgh', 'i'], start_position, end_position)
170         self.assertEqual(single_line_view.single_line, 'bcde fgh i')
171         self.assertEqual(single_line_view.convert_column_to_row(0), 1)
172         self.assertEqual(single_line_view.convert_column_to_row(4), 1)
173         self.assertEqual(single_line_view.convert_column_to_row(5), 2)
174         self.assertEqual(single_line_view.convert_column_to_row(8), 2)
175         self.assertEqual(single_line_view.convert_column_to_row(9), 3)
176         self.assertEqual(single_line_view.convert_column_to_row(100), 3)
177
178         start_position = cpp_style.Position(row=0, column=3)
179         end_position = cpp_style.Position(row=0, column=4)
180         single_line_view = cpp_style.SingleLineView(['abcdef'], start_position, end_position)
181         self.assertEqual(single_line_view.single_line, 'd')
182
183     def test_create_skeleton_parameters(self):
184         self.assertEqual(cpp_style.create_skeleton_parameters(''), '')
185         self.assertEqual(cpp_style.create_skeleton_parameters(' '), ' ')
186         self.assertEqual(cpp_style.create_skeleton_parameters('long'), 'long,')
187         self.assertEqual(cpp_style.create_skeleton_parameters('const unsigned long int'), '                    int,')
188         self.assertEqual(cpp_style.create_skeleton_parameters('long int*'), '     int ,')
189         self.assertEqual(cpp_style.create_skeleton_parameters('PassRefPtr<Foo> a'), 'PassRefPtr      a,')
190         self.assertEqual(cpp_style.create_skeleton_parameters(
191                 'ComplexTemplate<NestedTemplate1<MyClass1, MyClass2>, NestedTemplate1<MyClass1, MyClass2> > param, int second'),
192                           'ComplexTemplate                                                                            param, int second,')
193         self.assertEqual(cpp_style.create_skeleton_parameters('int = 0, Namespace::Type& a'), 'int    ,            Type  a,')
194         # Create skeleton parameters is a bit too aggressive with function variables, but
195         # it allows for parsing other parameters and declarations like this are rare.
196         self.assertEqual(cpp_style.create_skeleton_parameters('void (*fn)(int a, int b), Namespace::Type& a'),
197                           'void                    ,            Type  a,')
198
199         # This doesn't look like functions declarations but the simplifications help to eliminate false positives.
200         self.assertEqual(cpp_style.create_skeleton_parameters('b{d}'), 'b   ,')
201
202     def test_find_parameter_name_index(self):
203         self.assertEqual(cpp_style.find_parameter_name_index(' int a '), 5)
204         self.assertEqual(cpp_style.find_parameter_name_index(' PassRefPtr     '), 16)
205         self.assertEqual(cpp_style.find_parameter_name_index('double'), 6)
206
207     def test_parameter_list(self):
208         elided_lines = ['int blah(PassRefPtr<MyClass> paramName,',
209                         'const Other1Class& foo,',
210                         'const ComplexTemplate<Class1, NestedTemplate<P1, P2> >* const * param = new ComplexTemplate<Class1, NestedTemplate<P1, P2> >(34, 42),',
211                         'int* myCount = 0);']
212         start_position = cpp_style.Position(row=0, column=8)
213         end_position = cpp_style.Position(row=3, column=16)
214
215         expected_parameters = ({'type': 'PassRefPtr<MyClass>', 'name': 'paramName', 'row': 0},
216                                {'type': 'const Other1Class&', 'name': 'foo', 'row': 1},
217                                {'type': 'const ComplexTemplate<Class1, NestedTemplate<P1, P2> >* const *', 'name': 'param', 'row': 2},
218                                {'type': 'int*', 'name': 'myCount', 'row': 3})
219         index = 0
220         for parameter in cpp_style.parameter_list(elided_lines, start_position, end_position):
221             expected_parameter = expected_parameters[index]
222             self.assertEqual(parameter.type, expected_parameter['type'])
223             self.assertEqual(parameter.name, expected_parameter['name'])
224             self.assertEqual(parameter.row, expected_parameter['row'])
225             index += 1
226         self.assertEqual(index, len(expected_parameters))
227
228     def test_check_parameter_against_text(self):
229         error_collector = ErrorCollector(self.assertTrue)
230         parameter = cpp_style.Parameter('FooF ooF', 4, 1)
231         self.assertFalse(cpp_style._check_parameter_name_against_text(parameter, 'FooF', error_collector))
232         self.assertEqual(error_collector.results(),
233                           'The parameter name "ooF" adds no information, so it should be removed.  [readability/parameter_name] [5]')
234
235
236 class CppStyleTestBase(unittest.TestCase):
237     """Provides some useful helper functions for cpp_style tests.
238
239     Attributes:
240       min_confidence: An integer that is the current minimum confidence
241                       level for the tests.
242
243     """
244
245     # FIXME: Refactor the unit tests so the confidence level is passed
246     #        explicitly, just like it is in the real code.
247     min_confidence = 1
248
249     # Helper function to avoid needing to explicitly pass confidence
250     # in all the unit test calls to cpp_style.process_file_data().
251     def process_file_data(self, filename, file_extension, lines, error, unit_test_config={}):
252         checker = CppChecker(filename, file_extension, error, self.min_confidence, unit_test_config)
253         checker.check(lines)
254
255     def perform_lint(self, code, filename, basic_error_rules, unit_test_config={}, lines_to_check=None):
256         error_collector = ErrorCollector(self.assertTrue, FilterConfiguration(basic_error_rules), lines_to_check)
257         lines = code.split('\n')
258         extension = filename.split('.')[1]
259         self.process_file_data(filename, extension, lines, error_collector, unit_test_config)
260         return error_collector.results()
261
262     # Perform lint on single line of input and return the error message.
263     def perform_single_line_lint(self, code, filename):
264         basic_error_rules = ('-build/header_guard',
265                              '-legal/copyright',
266                              '-readability/fn_size',
267                              '-readability/parameter_name',
268                              '-readability/pass_ptr',
269                              '-whitespace/ending_newline')
270         return self.perform_lint(code, filename, basic_error_rules)
271
272     # Perform lint over multiple lines and return the error message.
273     def perform_multi_line_lint(self, code, file_extension):
274         basic_error_rules = ('-build/header_guard',
275                              '-legal/copyright',
276                              '-readability/parameter_name',
277                              '-whitespace/ending_newline')
278         return self.perform_lint(code, 'test.' + file_extension, basic_error_rules)
279
280     # Only keep some errors related to includes, namespaces and rtti.
281     def perform_language_rules_check(self, filename, code, lines_to_check=None):
282         basic_error_rules = ('-',
283                              '+build/include',
284                              '+build/include_order',
285                              '+build/namespaces',
286                              '+runtime/rtti')
287         return self.perform_lint(code, filename, basic_error_rules, lines_to_check=lines_to_check)
288
289     # Only keep function length errors.
290     def perform_function_lengths_check(self, code):
291         basic_error_rules = ('-', '+readability/fn_size')
292         return self.perform_lint(code, 'test.cpp', basic_error_rules)
293
294     # Only keep pass ptr errors.
295     def perform_pass_ptr_check(self, code):
296         basic_error_rules = ('-', '+readability/pass_ptr')
297         return self.perform_lint(code, 'test.cpp', basic_error_rules)
298
299     # Only keep leaky pattern errors.
300     def perform_leaky_pattern_check(self, code):
301         basic_error_rules = ('-', '+runtime/leaky_pattern')
302         return self.perform_lint(code, 'test.cpp', basic_error_rules)
303
304     # Only include what you use errors.
305     def perform_include_what_you_use(self, code, filename='foo.h', io=codecs):
306         basic_error_rules = ('-', '+build/include_what_you_use')
307         unit_test_config = {cpp_style.INCLUDE_IO_INJECTION_KEY: io}
308         return self.perform_lint(code, filename, basic_error_rules, unit_test_config)
309
310     # Only include header guard errors.
311     def perform_header_guard_check(self, code, filename='foo.h'):
312         basic_error_rules = ('-', '+build/header_guard')
313         return self.perform_lint(code, filename, basic_error_rules)
314
315     # Perform lint and compare the error message with "expected_message".
316     def assert_lint(self, code, expected_message, file_name='foo.cpp'):
317         self.assertEqual(expected_message, self.perform_single_line_lint(code, file_name))
318
319     def assert_lint_one_of_many_errors_re(self, code, expected_message_re, file_name='foo.cpp'):
320         messages = self.perform_single_line_lint(code, file_name)
321         for message in messages:
322             if re.search(expected_message_re, message):
323                 return
324
325         self.assertEqual(expected_message_re, messages)
326
327     def assert_multi_line_lint(self, code, expected_message, file_name='foo.h'):
328         file_extension = file_name[file_name.rfind('.') + 1:]
329         self.assertEqual(expected_message, self.perform_multi_line_lint(code, file_extension))
330
331     def assert_multi_line_lint_re(self, code, expected_message_re, file_name='foo.h'):
332         file_extension = file_name[file_name.rfind('.') + 1:]
333         message = self.perform_multi_line_lint(code, file_extension)
334         if not re.search(expected_message_re, message):
335             self.fail('Message was:\n' + message + 'Expected match to "' + expected_message_re + '"')
336
337     def assert_language_rules_check(self, file_name, code, expected_message, lines_to_check=None):
338         self.assertEqual(expected_message,
339                           self.perform_language_rules_check(file_name, code, lines_to_check))
340
341     def assert_include_what_you_use(self, code, expected_message):
342         self.assertEqual(expected_message,
343                           self.perform_include_what_you_use(code))
344
345     def assert_header_guard(self, code, expected_message):
346         self.assertEqual(expected_message,
347                           self.perform_header_guard_check(code))
348
349     def assert_blank_lines_check(self, lines, start_errors, end_errors):
350         error_collector = ErrorCollector(self.assertTrue)
351         self.process_file_data('foo.cpp', 'cpp', lines, error_collector)
352         self.assertEqual(
353             start_errors,
354             error_collector.results().count(
355                 'Blank line at the start of a code block.  Is this needed?'
356                 '  [whitespace/blank_line] [2]'))
357         self.assertEqual(
358             end_errors,
359             error_collector.results().count(
360                 'Blank line at the end of a code block.  Is this needed?'
361                 '  [whitespace/blank_line] [3]'))
362
363     def assert_positions_equal(self, position, tuple_position):
364         """Checks if the two positions are equal.
365
366         position: a cpp_style.Position object.
367         tuple_position: a tuple (row, column) to compare against."""
368         self.assertEqual(position, cpp_style.Position(tuple_position[0], tuple_position[1]),
369                           'position %s, tuple_position %s' % (position, tuple_position))
370
371
372 class FunctionDetectionTest(CppStyleTestBase):
373     def perform_function_detection(self, lines, function_information, detection_line=0):
374         clean_lines = cpp_style.CleansedLines(lines)
375         function_state = cpp_style._FunctionState(5)
376         error_collector = ErrorCollector(self.assertTrue)
377         cpp_style.detect_functions(clean_lines, detection_line, function_state, error_collector)
378         if not function_information:
379             self.assertEqual(function_state.in_a_function, False)
380             return
381         self.assertEqual(function_state.in_a_function, True)
382         self.assertEqual(function_state.current_function, function_information['name'] + '()')
383         self.assertEqual(function_state.modifiers_and_return_type(), function_information['modifiers_and_return_type'])
384         self.assertEqual(function_state.is_final, function_information['is_final'])
385         self.assertEqual(function_state.is_override, function_information['is_override'])
386         self.assertEqual(function_state.is_pure, function_information['is_pure'])
387         self.assertEqual(function_state.is_virtual(), function_information['is_virtual'])
388         self.assertEqual(function_state.is_declaration, function_information['is_declaration'])
389         self.assert_positions_equal(function_state.function_name_start_position, function_information['function_name_start_position'])
390         self.assert_positions_equal(function_state.parameter_start_position, function_information['parameter_start_position'])
391         self.assert_positions_equal(function_state.parameter_end_position, function_information['parameter_end_position'])
392         self.assert_positions_equal(function_state.body_start_position, function_information['body_start_position'])
393         self.assert_positions_equal(function_state.end_position, function_information['end_position'])
394         expected_parameters = function_information.get('parameter_list')
395         if expected_parameters:
396             actual_parameters = function_state.parameter_list()
397             self.assertEqual(len(actual_parameters), len(expected_parameters))
398             for index in range(len(expected_parameters)):
399                 actual_parameter = actual_parameters[index]
400                 expected_parameter = expected_parameters[index]
401                 self.assertEqual(actual_parameter.type, expected_parameter['type'])
402                 self.assertEqual(actual_parameter.name, expected_parameter['name'])
403                 self.assertEqual(actual_parameter.row, expected_parameter['row'])
404
405     def test_basic_function_detection(self):
406         self.perform_function_detection(
407             ['void theTestFunctionName(int) {',
408              '}'],
409             {'name': 'theTestFunctionName',
410              'modifiers_and_return_type': 'void',
411              'function_name_start_position': (0, 5),
412              'parameter_start_position': (0, 24),
413              'parameter_end_position': (0, 29),
414              'body_start_position': (0, 30),
415              'end_position': (1, 1),
416              'is_final': False,
417              'is_override': False,
418              'is_virtual': False,
419              'is_pure': False,
420              'is_declaration': False})
421
422     def test_function_declaration_detection(self):
423         self.perform_function_detection(
424             ['void aFunctionName(int);'],
425             {'name': 'aFunctionName',
426              'modifiers_and_return_type': 'void',
427              'function_name_start_position': (0, 5),
428              'parameter_start_position': (0, 18),
429              'parameter_end_position': (0, 23),
430              'body_start_position': (0, 23),
431              'end_position': (0, 24),
432              'is_final': False,
433              'is_override': False,
434              'is_virtual': False,
435              'is_pure': False,
436              'is_declaration': True})
437
438         self.perform_function_detection(
439             ['CheckedInt<T> operator /(const CheckedInt<T> &lhs, const CheckedInt<T> &rhs);'],
440             {'name': 'operator /',
441              'modifiers_and_return_type': 'CheckedInt<T>',
442              'function_name_start_position': (0, 14),
443              'parameter_start_position': (0, 24),
444              'parameter_end_position': (0, 76),
445              'body_start_position': (0, 76),
446              'end_position': (0, 77),
447              'is_final': False,
448              'is_override': False,
449              'is_virtual': False,
450              'is_pure': False,
451              'is_declaration': True})
452
453         self.perform_function_detection(
454             ['CheckedInt<T> operator -(const CheckedInt<T> &lhs, const CheckedInt<T> &rhs);'],
455             {'name': 'operator -',
456              'modifiers_and_return_type': 'CheckedInt<T>',
457              'function_name_start_position': (0, 14),
458              'parameter_start_position': (0, 24),
459              'parameter_end_position': (0, 76),
460              'body_start_position': (0, 76),
461              'end_position': (0, 77),
462              'is_final': False,
463              'is_override': False,
464              'is_virtual': False,
465              'is_pure': False,
466              'is_declaration': True})
467
468         self.perform_function_detection(
469             ['CheckedInt<T> operator !=(const CheckedInt<T> &lhs, const CheckedInt<T> &rhs);'],
470             {'name': 'operator !=',
471              'modifiers_and_return_type': 'CheckedInt<T>',
472              'function_name_start_position': (0, 14),
473              'parameter_start_position': (0, 25),
474              'parameter_end_position': (0, 77),
475              'body_start_position': (0, 77),
476              'end_position': (0, 78),
477              'is_final': False,
478              'is_override': False,
479              'is_virtual': False,
480              'is_pure': False,
481              'is_declaration': True})
482
483         self.perform_function_detection(
484             ['CheckedInt<T> operator +(const CheckedInt<T> &lhs, const CheckedInt<T> &rhs);'],
485             {'name': 'operator +',
486              'modifiers_and_return_type': 'CheckedInt<T>',
487              'function_name_start_position': (0, 14),
488              'parameter_start_position': (0, 24),
489              'parameter_end_position': (0, 76),
490              'body_start_position': (0, 76),
491              'end_position': (0, 77),
492              'is_final': False,
493              'is_override': False,
494              'is_virtual': False,
495              'is_pure': False,
496              'is_declaration': True})
497
498     def test_pure_function_detection(self):
499         self.perform_function_detection(
500             ['virtual void theTestFunctionName(int = 0);'],
501             {'name': 'theTestFunctionName',
502              'modifiers_and_return_type': 'virtual void',
503              'function_name_start_position': (0, 13),
504              'parameter_start_position': (0, 32),
505              'parameter_end_position': (0, 41),
506              'body_start_position': (0, 41),
507              'end_position': (0, 42),
508              'is_final': False,
509              'is_override': False,
510              'is_virtual': True,
511              'is_pure': False,
512              'is_declaration': True})
513
514         self.perform_function_detection(
515             ['virtual void theTestFunctionName(int) = 0;'],
516             {'name': 'theTestFunctionName',
517              'modifiers_and_return_type': 'virtual void',
518              'function_name_start_position': (0, 13),
519              'parameter_start_position': (0, 32),
520              'parameter_end_position': (0, 37),
521              'body_start_position': (0, 41),
522              'end_position': (0, 42),
523              'is_final': False,
524              'is_override': False,
525              'is_virtual': True,
526              'is_pure': True,
527              'is_declaration': True})
528
529         # Hopefully, no one writes code like this but it is a tricky case.
530         self.perform_function_detection(
531             ['virtual void theTestFunctionName(int)',
532              ' = ',
533              ' 0 ;'],
534             {'name': 'theTestFunctionName',
535              'modifiers_and_return_type': 'virtual void',
536              'function_name_start_position': (0, 13),
537              'parameter_start_position': (0, 32),
538              'parameter_end_position': (0, 37),
539              'body_start_position': (2, 3),
540              'end_position': (2, 4),
541              'is_final': False,
542              'is_override': False,
543              'is_virtual': True,
544              'is_pure': True,
545              'is_declaration': True})
546
547     def test_override_and_final_function_detection(self):
548         self.perform_function_detection(
549             ['void theTestFunctionName(int override, int final);'],
550             {'name': 'theTestFunctionName',
551              'modifiers_and_return_type': 'void',
552              'function_name_start_position': (0, 5),
553              'parameter_start_position': (0, 24),
554              'parameter_end_position': (0, 49),
555              'body_start_position': (0, 49),
556              'end_position': (0, 50),
557              'is_final': False,
558              'is_override': False,
559              'is_virtual': False,
560              'is_pure': False,
561              'is_declaration': True})
562
563         self.perform_function_detection(
564             ['void theTestFunctionName(int final) override;'],
565             {'name': 'theTestFunctionName',
566              'modifiers_and_return_type': 'void',
567              'function_name_start_position': (0, 5),
568              'parameter_start_position': (0, 24),
569              'parameter_end_position': (0, 35),
570              'body_start_position': (0, 44),
571              'end_position': (0, 45),
572              'is_final': False,
573              'is_override': True,
574              'is_virtual': False,
575              'is_pure': False,
576              'is_declaration': True})
577
578         self.perform_function_detection(
579             ['void theTestFunctionName(int final) const override',
580              '{',
581              '}'],
582             {'name': 'theTestFunctionName',
583              'modifiers_and_return_type': 'void',
584              'function_name_start_position': (0, 5),
585              'parameter_start_position': (0, 24),
586              'parameter_end_position': (0, 35),
587              'body_start_position': (1, 0),
588              'end_position': (2, 1),
589              'is_final': False,
590              'is_override': True,
591              'is_virtual': False,
592              'is_pure': False,
593              'is_declaration': False})
594
595         self.perform_function_detection(
596             ['virtual void theTestFunctionName(int override) final;'],
597             {'name': 'theTestFunctionName',
598              'modifiers_and_return_type': 'virtual void',
599              'function_name_start_position': (0, 13),
600              'parameter_start_position': (0, 32),
601              'parameter_end_position': (0, 46),
602              'body_start_position': (0, 52),
603              'end_position': (0, 53),
604              'is_final': True,
605              'is_override': False,
606              'is_virtual': True,
607              'is_pure': False,
608              'is_declaration': True})
609
610         self.perform_function_detection(
611             ['void theTestFunctionName()',
612              'override',
613              'final;'],
614             {'name': 'theTestFunctionName',
615              'modifiers_and_return_type': 'void',
616              'function_name_start_position': (0, 5),
617              'parameter_start_position': (0, 24),
618              'parameter_end_position': (0, 26),
619              'body_start_position': (2, 5),
620              'end_position': (2, 6),
621              'is_final': True,
622              'is_override': True,
623              'is_virtual': False,
624              'is_pure': False,
625              'is_declaration': True})
626
627     def test_ignore_macros(self):
628         self.perform_function_detection(['void aFunctionName(int); \\'], None)
629
630     def test_non_functions(self):
631         # This case exposed an error because the open brace was in quotes.
632         self.perform_function_detection(
633             ['asm(',
634              '    "stmdb sp!, {r1-r3}" "\n"',
635              ');'],
636             # This isn't a function but it looks like one to our simple
637             # algorithm and that is ok.
638             {'name': 'asm',
639              'modifiers_and_return_type': '',
640              'function_name_start_position': (0, 0),
641              'parameter_start_position': (0, 3),
642              'parameter_end_position': (2, 1),
643              'body_start_position': (2, 1),
644              'end_position': (2, 2),
645              'is_final': False,
646              'is_override': False,
647              'is_virtual': False,
648              'is_pure': False,
649              'is_declaration': True})
650
651         # Simple test case with something that is not a function.
652         self.perform_function_detection(['class Stuff;'], None)
653
654     def test_parameter_list(self):
655         # A function with no arguments.
656         function_state = self.perform_function_detection(
657             ['void functionName();'],
658             {'name': 'functionName',
659              'modifiers_and_return_type': 'void',
660              'function_name_start_position': (0, 5),
661              'parameter_start_position': (0, 17),
662              'parameter_end_position': (0, 19),
663              'body_start_position': (0, 19),
664              'end_position': (0, 20),
665              'is_final': False,
666              'is_override': False,
667              'is_virtual': False,
668              'is_pure': False,
669              'is_declaration': True,
670              'parameter_list': ()})
671
672         # A function with one argument.
673         function_state = self.perform_function_detection(
674             ['void functionName(int);'],
675             {'name': 'functionName',
676              'modifiers_and_return_type': 'void',
677              'function_name_start_position': (0, 5),
678              'parameter_start_position': (0, 17),
679              'parameter_end_position': (0, 22),
680              'body_start_position': (0, 22),
681              'end_position': (0, 23),
682              'is_final': False,
683              'is_override': False,
684              'is_virtual': False,
685              'is_pure': False,
686              'is_declaration': True,
687              'parameter_list':
688                  ({'type': 'int', 'name': '', 'row': 0},)})
689
690         # A function with unsigned and short arguments
691         function_state = self.perform_function_detection(
692             ['void functionName(unsigned a, short b, long c, long long short unsigned int);'],
693             {'name': 'functionName',
694              'modifiers_and_return_type': 'void',
695              'function_name_start_position': (0, 5),
696              'parameter_start_position': (0, 17),
697              'parameter_end_position': (0, 76),
698              'body_start_position': (0, 76),
699              'end_position': (0, 77),
700              'is_final': False,
701              'is_override': False,
702              'is_virtual': False,
703              'is_pure': False,
704              'is_declaration': True,
705              'parameter_list':
706                  ({'type': 'unsigned', 'name': 'a', 'row': 0},
707                   {'type': 'short', 'name': 'b', 'row': 0},
708                   {'type': 'long', 'name': 'c', 'row': 0},
709                   {'type': 'long long short unsigned int', 'name': '', 'row': 0})})
710
711         # Some parameter type with modifiers and no parameter names.
712         function_state = self.perform_function_detection(
713             ['virtual void determineARIADropEffects(Vector<String>*&, const unsigned long int*&, const MediaPlayer::Preload, Other<Other2, Other3<P1, P2> >, int);'],
714             {'name': 'determineARIADropEffects',
715              'modifiers_and_return_type': 'virtual void',
716              'parameter_start_position': (0, 37),
717              'function_name_start_position': (0, 13),
718              'parameter_end_position': (0, 147),
719              'body_start_position': (0, 147),
720              'end_position': (0, 148),
721              'is_final': False,
722              'is_override': False,
723              'is_virtual': True,
724              'is_pure': False,
725              'is_declaration': True,
726              'parameter_list':
727                  ({'type': 'Vector<String>*&', 'name': '', 'row': 0},
728                   {'type': 'const unsigned long int*&', 'name': '', 'row': 0},
729                   {'type': 'const MediaPlayer::Preload', 'name': '', 'row': 0},
730                   {'type': 'Other<Other2, Other3<P1, P2> >', 'name': '', 'row': 0},
731                   {'type': 'int', 'name': '', 'row': 0})})
732
733         # Try parsing a function with a very complex definition.
734         function_state = self.perform_function_detection(
735             ['#define MyMacro(a) a',
736              'virtual',
737              'AnotherTemplate<Class1, Class2> aFunctionName(PassRefPtr<MyClass> paramName,',
738              'const Other1Class& foo,',
739              'const ComplexTemplate<Class1, NestedTemplate<P1, P2> >* const * param = new ComplexTemplate<Class1, NestedTemplate<P1, P2> >(34, 42),',
740              'int* myCount = 0);'],
741             {'name': 'aFunctionName',
742              'modifiers_and_return_type': 'virtual AnotherTemplate<Class1, Class2>',
743              'function_name_start_position': (2, 32),
744              'parameter_start_position': (2, 45),
745              'parameter_end_position': (5, 17),
746              'body_start_position': (5, 17),
747              'end_position': (5, 18),
748              'is_final': False,
749              'is_override': False,
750              'is_virtual': True,
751              'is_pure': False,
752              'is_declaration': True,
753              'parameter_list':
754                  ({'type': 'PassRefPtr<MyClass>', 'name': 'paramName', 'row': 2},
755                   {'type': 'const Other1Class&', 'name': 'foo', 'row': 3},
756                   {'type': 'const ComplexTemplate<Class1, NestedTemplate<P1, P2> >* const *', 'name': 'param', 'row': 4},
757                   {'type': 'int*', 'name': 'myCount', 'row': 5})},
758             detection_line=2)
759
760
761 class Cpp11StyleTest(CppStyleTestBase):
762     def test_rvaule_reference_at_end_of_line(self):
763         self.assert_lint('T&&', '')
764
765     def test_rvaule_reference_in_parameter_pack(self):
766         self.assert_lint('void requestCompleted(Arguments&&... arguments)', '')
767
768
769 class CppStyleTest(CppStyleTestBase):
770
771     def test_asm_lines_ignored(self):
772         self.assert_lint(
773             '__asm mov [registration], eax',
774             '')
775
776     # Test get line width.
777     def test_get_line_width(self):
778         self.assertEqual(0, cpp_style.get_line_width(''))
779         self.assertEqual(10, cpp_style.get_line_width(u'x' * 10))
780         self.assertEqual(16, cpp_style.get_line_width(u'都|道|府|県|支庁'))
781
782     def test_find_next_multi_line_comment_start(self):
783         self.assertEqual(1, cpp_style.find_next_multi_line_comment_start([''], 0))
784
785         lines = ['a', 'b', '/* c']
786         self.assertEqual(2, cpp_style.find_next_multi_line_comment_start(lines, 0))
787
788         lines = ['char a[] = "/*";']  # not recognized as comment.
789         self.assertEqual(1, cpp_style.find_next_multi_line_comment_start(lines, 0))
790
791     def test_find_next_multi_line_comment_end(self):
792         self.assertEqual(1, cpp_style.find_next_multi_line_comment_end([''], 0))
793         lines = ['a', 'b', ' c */']
794         self.assertEqual(2, cpp_style.find_next_multi_line_comment_end(lines, 0))
795
796     def test_remove_multi_line_comments_from_range(self):
797         lines = ['a', '  /* comment ', ' * still comment', ' comment */   ', 'b']
798         cpp_style.remove_multi_line_comments_from_range(lines, 1, 4)
799         self.assertEqual(['a', '// dummy', '// dummy', '// dummy', 'b'], lines)
800
801     def test_position(self):
802         position = cpp_style.Position(3, 4)
803         self.assert_positions_equal(position, (3, 4))
804         self.assertEqual(position.row, 3)
805         self.assertTrue(position > cpp_style.Position(position.row - 1, position.column + 1))
806         self.assertTrue(position > cpp_style.Position(position.row, position.column - 1))
807         self.assertTrue(position < cpp_style.Position(position.row, position.column + 1))
808         self.assertTrue(position < cpp_style.Position(position.row + 1, position.column - 1))
809         self.assertEqual(position.__str__(), '(3, 4)')
810
811     def test_rfind_in_lines(self):
812         not_found_position = cpp_style.Position(10, 11)
813         start_position = cpp_style.Position(2, 2)
814         lines = ['ab', 'ace', 'test']
815         self.assertEqual(not_found_position, cpp_style._rfind_in_lines('st', lines, start_position, not_found_position))
816         self.assertTrue(cpp_style.Position(1, 1) == cpp_style._rfind_in_lines('a', lines, start_position, not_found_position))
817         self.assertEqual(cpp_style.Position(2, 2), cpp_style._rfind_in_lines('(te|a)', lines, start_position, not_found_position))
818
819     def test_close_expression(self):
820         self.assertEqual(cpp_style.Position(1, -1), cpp_style.close_expression([')('], cpp_style.Position(0, 1)))
821         self.assertEqual(cpp_style.Position(1, -1), cpp_style.close_expression([') ()'], cpp_style.Position(0, 1)))
822         self.assertEqual(cpp_style.Position(0, 4), cpp_style.close_expression([')[)]'], cpp_style.Position(0, 1)))
823         self.assertEqual(cpp_style.Position(0, 5), cpp_style.close_expression(['}{}{}'], cpp_style.Position(0, 3)))
824         self.assertEqual(cpp_style.Position(1, 1), cpp_style.close_expression(['}{}{', '}'], cpp_style.Position(0, 3)))
825         self.assertEqual(cpp_style.Position(2, -1), cpp_style.close_expression(['][][', ' '], cpp_style.Position(0, 3)))
826
827     def test_spaces_at_end_of_line(self):
828         self.assert_lint(
829             '// Hello there ',
830             'Line ends in whitespace.  Consider deleting these extra spaces.'
831             '  [whitespace/end_of_line] [4]')
832
833     # Test C-style cast cases.
834     def test_cstyle_cast(self):
835         self.assert_lint(
836             'int a = (int)1.0;',
837             'Using C-style cast.  Use static_cast<int>(...) instead'
838             '  [readability/casting] [4]')
839         self.assert_lint(
840             'int *a = (int *)DEFINED_VALUE;',
841             'Using C-style cast.  Use reinterpret_cast<int *>(...) instead'
842             '  [readability/casting] [4]', 'foo.c')
843         self.assert_lint(
844             'uint16 a = (uint16)1.0;',
845             'Using C-style cast.  Use static_cast<uint16>(...) instead'
846             '  [readability/casting] [4]')
847         self.assert_lint(
848             'int32 a = (int32)1.0;',
849             'Using C-style cast.  Use static_cast<int32>(...) instead'
850             '  [readability/casting] [4]')
851         self.assert_lint(
852             'uint64 a = (uint64)1.0;',
853             'Using C-style cast.  Use static_cast<uint64>(...) instead'
854             '  [readability/casting] [4]')
855
856     # Test taking address of casts (runtime/casting)
857     def test_runtime_casting(self):
858         self.assert_lint(
859             'int* x = &static_cast<int*>(foo);',
860             'Are you taking an address of a cast?  '
861             'This is dangerous: could be a temp var.  '
862             'Take the address before doing the cast, rather than after'
863             '  [runtime/casting] [4]')
864
865         self.assert_lint(
866             'int* x = &dynamic_cast<int *>(foo);',
867             ['Are you taking an address of a cast?  '
868              'This is dangerous: could be a temp var.  '
869              'Take the address before doing the cast, rather than after'
870              '  [runtime/casting] [4]',
871              'Do not use dynamic_cast<>.  If you need to cast within a class '
872              'hierarchy, use static_cast<> to upcast.  Google doesn\'t support '
873              'RTTI.  [runtime/rtti] [5]'])
874
875         self.assert_lint(
876             'int* x = &reinterpret_cast<int *>(foo);',
877             'Are you taking an address of a cast?  '
878             'This is dangerous: could be a temp var.  '
879             'Take the address before doing the cast, rather than after'
880             '  [runtime/casting] [4]')
881
882         # It's OK to cast an address.
883         self.assert_lint(
884             'int* x = reinterpret_cast<int *>(&foo);',
885             '')
886
887     def test_runtime_selfinit(self):
888         self.assert_multi_line_lint(
889             '''\
890             Foo::Foo(Bar raa, Bel laa)
891                 : raa_(raa_)
892                 , laa_(laa_) { }''',
893             ['You seem to be initializing a member variable with itself.'
894             '  [runtime/init] [4]',
895             'You seem to be initializing a member variable with itself.'
896             '  [runtime/init] [4]'])
897         self.assert_multi_line_lint(
898             '''\
899             Foo::Foo(Bar raa, Bel laa)
900                 : raa_(raa)
901                 , laa_(laa) { }''',
902             '')
903         self.assert_multi_line_lint(
904             '''\
905             Foo::Foo(Bar raa)
906                 : raa_(raa)
907                 , laa_(raa_)
908                 , llaa_(laa_) { }''',
909             '')
910
911     def test_runtime_rtti(self):
912         statement = 'int* x = dynamic_cast<int*>(&foo);'
913         error_message = (
914             'Do not use dynamic_cast<>.  If you need to cast within a class '
915             'hierarchy, use static_cast<> to upcast.  Google doesn\'t support '
916             'RTTI.  [runtime/rtti] [5]')
917         # dynamic_cast is disallowed in most files.
918         self.assert_language_rules_check('foo.cpp', statement, error_message)
919         self.assert_language_rules_check('foo.h', statement, error_message)
920
921     # Test for static_cast readability.
922     def test_static_cast_readability(self):
923         self.assert_lint(
924             'Text* x = static_cast<Text*>(foo);',
925             'Consider using toText helper function in WebCore/dom/Text.h '
926             'instead of static_cast<Text*>'
927             '  [readability/check] [4]')
928
929     # We cannot test this functionality because of difference of
930     # function definitions.  Anyway, we may never enable this.
931     #
932     # # Test for unnamed arguments in a method.
933     # def test_check_for_unnamed_params(self):
934     #   message = ('All parameters should be named in a function'
935     #              '  [readability/function] [3]')
936     #   self.assert_lint('virtual void A(int*) const;', message)
937     #   self.assert_lint('virtual void B(void (*fn)(int*));', message)
938     #   self.assert_lint('virtual void C(int*);', message)
939     #   self.assert_lint('void *(*f)(void *) = x;', message)
940     #   self.assert_lint('void Method(char*) {', message)
941     #   self.assert_lint('void Method(char*);', message)
942     #   self.assert_lint('void Method(char* /*x*/);', message)
943     #   self.assert_lint('typedef void (*Method)(int32);', message)
944     #   self.assert_lint('static void operator delete[](void*) throw();', message)
945     #
946     #   self.assert_lint('virtual void D(int* p);', '')
947     #   self.assert_lint('void operator delete(void* x) throw();', '')
948     #   self.assert_lint('void Method(char* x)\n{', '')
949     #   self.assert_lint('void Method(char* /*x*/)\n{', '')
950     #   self.assert_lint('void Method(char* x);', '')
951     #   self.assert_lint('typedef void (*Method)(int32 x);', '')
952     #   self.assert_lint('static void operator delete[](void* x) throw();', '')
953     #   self.assert_lint('static void operator delete[](void* /*x*/) throw();', '')
954     #
955     #   # This one should technically warn, but doesn't because the function
956     #   # pointer is confusing.
957     #   self.assert_lint('virtual void E(void (*fn)(int* p));', '')
958
959     # Test deprecated casts such as int(d)
960     def test_deprecated_cast(self):
961         self.assert_lint(
962             'int a = int(2.2);',
963             'Using deprecated casting style.  '
964             'Use static_cast<int>(...) instead'
965             '  [readability/casting] [4]')
966         # Checks for false positives...
967         self.assert_lint(
968             'int a = int(); // Constructor, o.k.',
969             '')
970         self.assert_multi_line_lint(
971             '''\
972             X::X()
973                 : a(int()) { } // default Constructor, o.k.''',
974             '')
975         self.assert_lint(
976             'operator bool(); // Conversion operator, o.k.',
977             '')
978
979     # The second parameter to a gMock method definition is a function signature
980     # that often looks like a bad cast but should not picked up by lint.
981     def test_mock_method(self):
982         self.assert_lint(
983             'MOCK_METHOD0(method, int());',
984             '')
985         self.assert_lint(
986             'MOCK_CONST_METHOD1(method, float(string));',
987             '')
988         self.assert_lint(
989             'MOCK_CONST_METHOD2_T(method, double(float, float));',
990             '')
991
992     # Test sizeof(type) cases.
993     def test_sizeof_type(self):
994         self.assert_lint(
995             'sizeof(int);',
996             'Using sizeof(type).  Use sizeof(varname) instead if possible'
997             '  [runtime/sizeof] [1]')
998         self.assert_lint(
999             'sizeof(int *);',
1000             'Using sizeof(type).  Use sizeof(varname) instead if possible'
1001             '  [runtime/sizeof] [1]')
1002
1003     # Test typedef cases.  There was a bug that cpp_style misidentified
1004     # typedef for pointer to function as C-style cast and produced
1005     # false-positive error messages.
1006     def test_typedef_for_pointer_to_function(self):
1007         self.assert_lint(
1008             'typedef void (*Func)(int x);',
1009             '')
1010         self.assert_lint(
1011             'typedef void (*Func)(int *x);',
1012             '')
1013         self.assert_lint(
1014             'typedef void Func(int x);',
1015             '')
1016         self.assert_lint(
1017             'typedef void Func(int *x);',
1018             '')
1019
1020     def test_include_what_you_use_no_implementation_files(self):
1021         code = 'std::vector<int> foo;'
1022         self.assertEqual('Add #include <vector> for vector<>'
1023                           '  [build/include_what_you_use] [4]',
1024                           self.perform_include_what_you_use(code, 'foo.h'))
1025         self.assertEqual('',
1026                           self.perform_include_what_you_use(code, 'foo.cpp'))
1027
1028     def test_include_what_you_use(self):
1029         self.assert_include_what_you_use(
1030             '''#include <vector>
1031                std::vector<int> foo;
1032             ''',
1033             '')
1034         self.assert_include_what_you_use(
1035             '''#include <map>
1036                std::pair<int,int> foo;
1037             ''',
1038             '')
1039         self.assert_include_what_you_use(
1040             '''#include <multimap>
1041                std::pair<int,int> foo;
1042             ''',
1043             '')
1044         self.assert_include_what_you_use(
1045             '''#include <hash_map>
1046                std::pair<int,int> foo;
1047             ''',
1048             '')
1049         self.assert_include_what_you_use(
1050             '''#include <utility>
1051                std::pair<int,int> foo;
1052             ''',
1053             '')
1054         self.assert_include_what_you_use(
1055             '''#include <vector>
1056                DECLARE_string(foobar);
1057             ''',
1058             '')
1059         self.assert_include_what_you_use(
1060             '''#include <vector>
1061                DEFINE_string(foobar, "", "");
1062             ''',
1063             '')
1064         self.assert_include_what_you_use(
1065             '''#include <vector>
1066                std::pair<int,int> foo;
1067             ''',
1068             'Add #include <utility> for pair<>'
1069             '  [build/include_what_you_use] [4]')
1070         self.assert_include_what_you_use(
1071             '''#include "base/foobar.h"
1072                std::vector<int> foo;
1073             ''',
1074             'Add #include <vector> for vector<>'
1075             '  [build/include_what_you_use] [4]')
1076         self.assert_include_what_you_use(
1077             '''#include <vector>
1078                std::set<int> foo;
1079             ''',
1080             'Add #include <set> for set<>'
1081             '  [build/include_what_you_use] [4]')
1082         self.assert_include_what_you_use(
1083             '''#include "base/foobar.h"
1084               hash_map<int, int> foobar;
1085             ''',
1086             'Add #include <hash_map> for hash_map<>'
1087             '  [build/include_what_you_use] [4]')
1088         self.assert_include_what_you_use(
1089             '''#include "base/foobar.h"
1090                bool foobar = std::less<int>(0,1);
1091             ''',
1092             'Add #include <functional> for less<>'
1093             '  [build/include_what_you_use] [4]')
1094         self.assert_include_what_you_use(
1095             '''#include "base/foobar.h"
1096                bool foobar = min<int>(0,1);
1097             ''',
1098             'Add #include <algorithm> for min  [build/include_what_you_use] [4]')
1099         self.assert_include_what_you_use(
1100             'void a(const string &foobar);',
1101             'Add #include <string> for string  [build/include_what_you_use] [4]')
1102         self.assert_include_what_you_use(
1103             '''#include "base/foobar.h"
1104                bool foobar = swap(0,1);
1105             ''',
1106             'Add #include <algorithm> for swap  [build/include_what_you_use] [4]')
1107         self.assert_include_what_you_use(
1108             '''#include "base/foobar.h"
1109                bool foobar = transform(a.begin(), a.end(), b.start(), Foo);
1110             ''',
1111             'Add #include <algorithm> for transform  '
1112             '[build/include_what_you_use] [4]')
1113         self.assert_include_what_you_use(
1114             '''#include "base/foobar.h"
1115                bool foobar = min_element(a.begin(), a.end());
1116             ''',
1117             'Add #include <algorithm> for min_element  '
1118             '[build/include_what_you_use] [4]')
1119         self.assert_include_what_you_use(
1120             '''foo->swap(0,1);
1121                foo.swap(0,1);
1122             ''',
1123             '')
1124         self.assert_include_what_you_use(
1125             '''#include <string>
1126                void a(const std::multimap<int,string> &foobar);
1127             ''',
1128             'Add #include <map> for multimap<>'
1129             '  [build/include_what_you_use] [4]')
1130         self.assert_include_what_you_use(
1131             '''#include <queue>
1132                void a(const std::priority_queue<int> &foobar);
1133             ''',
1134             '')
1135         self.assert_include_what_you_use(
1136              '''#include "base/basictypes.h"
1137                 #include "base/port.h"
1138                 #include <assert.h>
1139                 #include <string>
1140                 #include <vector>
1141                 vector<string> hajoa;''', '')
1142         self.assert_include_what_you_use(
1143             '''#include <string>
1144                int i = numeric_limits<int>::max()
1145             ''',
1146             'Add #include <limits> for numeric_limits<>'
1147             '  [build/include_what_you_use] [4]')
1148         self.assert_include_what_you_use(
1149             '''#include <limits>
1150                int i = numeric_limits<int>::max()
1151             ''',
1152             '')
1153
1154         # Test the UpdateIncludeState code path.
1155         mock_header_contents = ['#include "blah/foo.h"', '#include "blah/bar.h"']
1156         message = self.perform_include_what_you_use(
1157             '#include "config.h"\n'
1158             '#include "blah/a.h"\n',
1159             filename='blah/a.cpp',
1160             io=MockIo(mock_header_contents))
1161         self.assertEqual(message, '')
1162
1163         mock_header_contents = ['#include <set>']
1164         message = self.perform_include_what_you_use(
1165             '''#include "config.h"
1166                #include "blah/a.h"
1167
1168                std::set<int> foo;''',
1169             filename='blah/a.cpp',
1170             io=MockIo(mock_header_contents))
1171         self.assertEqual(message, '')
1172
1173         # If there's just a .cpp and the header can't be found then it's ok.
1174         message = self.perform_include_what_you_use(
1175             '''#include "config.h"
1176                #include "blah/a.h"
1177
1178                std::set<int> foo;''',
1179             filename='blah/a.cpp')
1180         self.assertEqual(message, '')
1181
1182         # Make sure we find the headers with relative paths.
1183         mock_header_contents = ['']
1184         message = self.perform_include_what_you_use(
1185             '''#include "config.h"
1186                #include "%s%sa.h"
1187
1188                std::set<int> foo;''' % (os.path.basename(os.getcwd()), os.path.sep),
1189             filename='a.cpp',
1190             io=MockIo(mock_header_contents))
1191         self.assertEqual(message, 'Add #include <set> for set<>  '
1192                                    '[build/include_what_you_use] [4]')
1193
1194     def test_files_belong_to_same_module(self):
1195         f = cpp_style.files_belong_to_same_module
1196         self.assertEqual((True, ''), f('a.cpp', 'a.h'))
1197         self.assertEqual((True, ''), f('base/google.cpp', 'base/google.h'))
1198         self.assertEqual((True, ''), f('base/google_test.cpp', 'base/google.h'))
1199         self.assertEqual((True, ''),
1200                           f('base/google_unittest.cpp', 'base/google.h'))
1201         self.assertEqual((True, ''),
1202                           f('base/internal/google_unittest.cpp',
1203                             'base/public/google.h'))
1204         self.assertEqual((True, 'xxx/yyy/'),
1205                           f('xxx/yyy/base/internal/google_unittest.cpp',
1206                             'base/public/google.h'))
1207         self.assertEqual((True, 'xxx/yyy/'),
1208                           f('xxx/yyy/base/google_unittest.cpp',
1209                             'base/public/google.h'))
1210         self.assertEqual((True, ''),
1211                           f('base/google_unittest.cpp', 'base/google-inl.h'))
1212         self.assertEqual((True, '/home/build/google3/'),
1213                           f('/home/build/google3/base/google.cpp', 'base/google.h'))
1214
1215         self.assertEqual((False, ''),
1216                           f('/home/build/google3/base/google.cpp', 'basu/google.h'))
1217         self.assertEqual((False, ''), f('a.cpp', 'b.h'))
1218
1219     def test_cleanse_line(self):
1220         self.assertEqual('int foo = 0;  ',
1221                           cpp_style.cleanse_comments('int foo = 0;  // danger!'))
1222         self.assertEqual('int o = 0;',
1223                           cpp_style.cleanse_comments('int /* foo */ o = 0;'))
1224         self.assertEqual('foo(int a, int b);',
1225                           cpp_style.cleanse_comments('foo(int a /* abc */, int b);'))
1226         self.assertEqual('f(a, b);',
1227                          cpp_style.cleanse_comments('f(a, /* name */ b);'))
1228         self.assertEqual('f(a, b);',
1229                          cpp_style.cleanse_comments('f(a /* name */, b);'))
1230         self.assertEqual('f(a, b);',
1231                          cpp_style.cleanse_comments('f(a, /* name */b);'))
1232
1233     def test_multi_line_comments(self):
1234         # missing explicit is bad
1235         self.assert_multi_line_lint(
1236             r'''int a = 0;
1237                 /* multi-liner
1238                 class Foo {
1239                 Foo(int f);  // should cause a lint warning in code
1240                 }
1241             */ ''',
1242         '')
1243         self.assert_multi_line_lint(
1244             '''\
1245             /* int a = 0; multi-liner
1246             static const int b = 0;''',
1247             ['Could not find end of multi-line comment'
1248              '  [readability/multiline_comment] [5]',
1249              'Complex multi-line /*...*/-style comment found. '
1250              'Lint may give bogus warnings.  Consider replacing these with '
1251              '//-style comments, with #if 0...#endif, or with more clearly '
1252              'structured multi-line comments.  [readability/multiline_comment] [5]'])
1253         self.assert_multi_line_lint(r'''    /* multi-line comment''',
1254                                     ['Could not find end of multi-line comment'
1255                                      '  [readability/multiline_comment] [5]',
1256                                      'Complex multi-line /*...*/-style comment found. '
1257                                      'Lint may give bogus warnings.  Consider replacing these with '
1258                                      '//-style comments, with #if 0...#endif, or with more clearly '
1259                                      'structured multi-line comments.  [readability/multiline_comment] [5]'])
1260         self.assert_multi_line_lint(r'''    // /* comment, but not multi-line''', '')
1261
1262     def test_multiline_strings(self):
1263         multiline_string_error_message = (
1264             'Multi-line string ("...") found.  This lint script doesn\'t '
1265             'do well with such strings, and may give bogus warnings.  They\'re '
1266             'ugly and unnecessary, and you should use concatenation instead".'
1267             '  [readability/multiline_string] [5]')
1268
1269         file_path = 'mydir/foo.cpp'
1270
1271         error_collector = ErrorCollector(self.assertTrue)
1272         self.process_file_data(file_path, 'cpp',
1273                                ['const char* str = "This is a\\',
1274                                 ' multiline string.";'],
1275                                error_collector)
1276         self.assertEqual(
1277             2,  # One per line.
1278             error_collector.result_list().count(multiline_string_error_message))
1279
1280     def test_platformh_comments(self):
1281         check_platformh_message = (
1282             'CPP comments are not allowed in Platform.h, '
1283             'please use C comments /* ... */  [build/cpp_comment] [5]')
1284
1285         platformh_file_path = 'Source/WTF/wtf/Platform.h'
1286
1287         # CPP comment are not allowed in Platform.h header file.
1288         error_collector = ErrorCollector(self.assertTrue)
1289         self.process_file_data(platformh_file_path, 'h',
1290                                ['// This is a cpp comment.'],
1291                                error_collector)
1292         self.assertEqual(
1293             1,
1294             error_collector.result_list().count(check_platformh_message))
1295
1296         # C comments are allowed in Platform.h
1297         error_collector = ErrorCollector(self.assertTrue)
1298         self.process_file_data(platformh_file_path, 'h',
1299                                ['/* This is a C comment.*/'],
1300                                error_collector)
1301         self.assertEqual(
1302             0,
1303             error_collector.result_list().count(check_platformh_message))
1304
1305         platformh_file_path = 'Source/WTF/wtf/platform.h'
1306
1307         # CPP comment are allowed in other header files.
1308         error_collector = ErrorCollector(self.assertTrue)
1309         self.process_file_data(platformh_file_path, 'h',
1310                                ['// This is a cpp comment.'
1311                                 '// The filepath is not'
1312                                 '// Source/WTF/wtf/Platform.h'],
1313                                error_collector)
1314         self.assertEqual(
1315             0,
1316             error_collector.result_list().count(check_platformh_message))
1317
1318     # Test non-explicit single-argument constructors
1319     def test_explicit_single_argument_constructors(self):
1320         # missing explicit is bad
1321         self.assert_multi_line_lint(
1322             '''\
1323             class Foo {
1324                 Foo(int f);
1325             };''',
1326             'Single-argument constructors should be marked explicit.'
1327             '  [runtime/explicit] [5]')
1328         # missing explicit is bad, even with whitespace
1329         self.assert_multi_line_lint(
1330             '''\
1331             class Foo {
1332                 Foo (int f);
1333             };''',
1334             ['Extra space before ( in function call  [whitespace/parens] [4]',
1335              'Single-argument constructors should be marked explicit.'
1336              '  [runtime/explicit] [5]'])
1337         # missing explicit, with distracting comment, is still bad
1338         self.assert_multi_line_lint(
1339             '''\
1340             class Foo {
1341                 Foo(int f); // simpler than Foo(blargh, blarg)
1342             };''',
1343             'Single-argument constructors should be marked explicit.'
1344             '  [runtime/explicit] [5]')
1345         # missing explicit, with qualified classname
1346         self.assert_multi_line_lint(
1347             '''\
1348             class Qualifier::AnotherOne::Foo {
1349                 Foo(int f);
1350             };''',
1351             'Single-argument constructors should be marked explicit.'
1352             '  [runtime/explicit] [5]')
1353         # structs are caught as well.
1354         self.assert_multi_line_lint(
1355             '''\
1356             struct Foo {
1357                 Foo(int f);
1358             };''',
1359             'Single-argument constructors should be marked explicit.'
1360             '  [runtime/explicit] [5]')
1361         # Templatized classes are caught as well.
1362         self.assert_multi_line_lint(
1363             '''\
1364             template<typename T> class Foo {
1365                 Foo(int f);
1366             };''',
1367             'Single-argument constructors should be marked explicit.'
1368             '  [runtime/explicit] [5]')
1369         # proper style is okay
1370         self.assert_multi_line_lint(
1371             '''\
1372             class Foo {
1373                 explicit Foo(int f);
1374             };''',
1375             '')
1376         # two argument constructor is okay
1377         self.assert_multi_line_lint(
1378             '''\
1379             class Foo {
1380                 Foo(int f, int b);
1381             };''',
1382             '')
1383         # two argument constructor, across two lines, is okay
1384         self.assert_multi_line_lint(
1385             '''\
1386             class Foo {
1387                 Foo(int f,
1388                     int b);
1389             };''',
1390             '')
1391         # non-constructor (but similar name), is okay
1392         self.assert_multi_line_lint(
1393             '''\
1394             class Foo {
1395                 aFoo(int f);
1396             };''',
1397             '')
1398         # constructor with void argument is okay
1399         self.assert_multi_line_lint(
1400             '''\
1401             class Foo {
1402                 Foo(void);
1403             };''',
1404             '')
1405         # single argument method is okay
1406         self.assert_multi_line_lint(
1407             '''\
1408             class Foo {
1409                 Bar(int b);
1410             };''',
1411             '')
1412         # comments should be ignored
1413         self.assert_multi_line_lint(
1414             '''\
1415             class Foo {
1416             // Foo(int f);
1417             };''',
1418             '')
1419         # single argument function following class definition is okay
1420         # (okay, it's not actually valid, but we don't want a false positive)
1421         self.assert_multi_line_lint(
1422             '''\
1423             class Foo {
1424                 Foo(int f, int b);
1425             };
1426             Foo(int f);''',
1427             '')
1428         # single argument function is okay
1429         self.assert_multi_line_lint(
1430             '''static Foo(int f);''',
1431             '')
1432         # single argument copy constructor is okay.
1433         self.assert_multi_line_lint(
1434             '''\
1435             class Foo {
1436                 Foo(const Foo&);
1437             };''',
1438             '')
1439         self.assert_multi_line_lint(
1440             '''\
1441             class Foo {
1442                 Foo(Foo&);
1443             };''',
1444             '')
1445
1446     def test_slash_star_comment_on_single_line(self):
1447         self.assert_multi_line_lint(
1448             '''/* static */ Foo(int f);''',
1449             '')
1450         self.assert_multi_line_lint(
1451             '''/*/ static */  Foo(int f);''',
1452             '')
1453         self.assert_multi_line_lint(
1454             '''/*/ static Foo(int f);''',
1455             'Could not find end of multi-line comment'
1456             '  [readability/multiline_comment] [5]')
1457         self.assert_multi_line_lint(
1458             '''    /*/ static Foo(int f);''',
1459             'Could not find end of multi-line comment'
1460             '  [readability/multiline_comment] [5]')
1461
1462     # Test suspicious usage of "if" like this:
1463     # if (a == b) {
1464     #   DoSomething();
1465     # } if (a == c) {   // Should be "else if".
1466     #   DoSomething();  // This gets called twice if a == b && a == c.
1467     # }
1468     def test_suspicious_usage_of_if(self):
1469         self.assert_lint(
1470             '    if (a == b) {',
1471             '')
1472         self.assert_lint(
1473             '    } if (a == b) {',
1474             'Did you mean "else if"? If not, start a new line for "if".'
1475             '  [readability/braces] [4]')
1476
1477     # Test suspicious usage of memset. Specifically, a 0
1478     # as the final argument is almost certainly an error.
1479     def test_suspicious_usage_of_memset(self):
1480         # Normal use is okay.
1481         self.assert_lint(
1482             '    memset(buf, 0, sizeof(buf))',
1483             '')
1484
1485         # A 0 as the final argument is almost certainly an error.
1486         self.assert_lint(
1487             '    memset(buf, sizeof(buf), 0)',
1488             'Did you mean "memset(buf, 0, sizeof(buf))"?'
1489             '  [runtime/memset] [4]')
1490         self.assert_lint(
1491             '    memset(buf, xsize * ysize, 0)',
1492             'Did you mean "memset(buf, 0, xsize * ysize)"?'
1493             '  [runtime/memset] [4]')
1494
1495         # There is legitimate test code that uses this form.
1496         # This is okay since the second argument is a literal.
1497         self.assert_lint(
1498             "    memset(buf, 'y', 0)",
1499             '')
1500         self.assert_lint(
1501             '    memset(buf, 4, 0)',
1502             '')
1503         self.assert_lint(
1504             '    memset(buf, -1, 0)',
1505             '')
1506         self.assert_lint(
1507             '    memset(buf, 0xF1, 0)',
1508             '')
1509         self.assert_lint(
1510             '    memset(buf, 0xcd, 0)',
1511             '')
1512
1513     def test_check_posix_threading(self):
1514         self.assert_lint('sctime_r()', '')
1515         self.assert_lint('strtok_r()', '')
1516         self.assert_lint('    strtok_r(foo, ba, r)', '')
1517         self.assert_lint('brand()', '')
1518         self.assert_lint('_rand()', '')
1519         self.assert_lint('.rand()', '')
1520         self.assert_lint('>rand()', '')
1521         self.assert_lint('rand()',
1522                          'Consider using rand_r(...) instead of rand(...)'
1523                          ' for improved thread safety.'
1524                          '  [runtime/threadsafe_fn] [2]')
1525         self.assert_lint('strtok()',
1526                          'Consider using strtok_r(...) '
1527                          'instead of strtok(...)'
1528                          ' for improved thread safety.'
1529                          '  [runtime/threadsafe_fn] [2]')
1530
1531     def test_debug_security_assertion(self):
1532         self.assert_lint(
1533             'ASSERT_WITH_SECURITY_IMPLICATION(value)',
1534             'Please replace ASSERT_WITH_SECURITY_IMPLICATION() with '
1535             'RELEASE_ASSERT_WITH_SECURITY_IMPLICATION().'
1536             '  [security/assertion] [5]')
1537         self.assert_lint(
1538             'RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(value)',
1539             '')
1540
1541     # Test for insecure string functions like strcpy()/strcat().
1542     def test_insecure_string_operations(self):
1543         self.assert_lint(
1544             'sprintf(destination, "%s", arg)',
1545             'Never use sprintf.  Use snprintf instead.'
1546             '  [security/printf] [5]')
1547         self.assert_lint(
1548             'strcat(destination, append)',
1549             'Almost always, snprintf is better than strcat.'
1550             '  [security/printf] [4]')
1551         self.assert_lint(
1552             'strcpy(destination, source)',
1553             'Almost always, snprintf is better than strcpy.'
1554             '  [security/printf] [4]')
1555         self.assert_lint('strstr(haystack, "needle")', '')
1556
1557     # Test potential format string bugs like printf(foo).
1558     def test_format_strings(self):
1559         self.assert_lint('printf("foo")', '')
1560         self.assert_lint('printf("foo: %s", foo)', '')
1561         self.assert_lint('DocidForPrintf(docid)', '')  # Should not trigger.
1562         self.assert_lint(
1563             'printf(foo)',
1564             'Potential format string bug. Do printf("%s", foo) instead.'
1565             '  [security/printf] [4]')
1566         self.assert_lint(
1567             'printf(foo.c_str())',
1568             'Potential format string bug. '
1569             'Do printf("%s", foo.c_str()) instead.'
1570             '  [security/printf] [4]')
1571         self.assert_lint(
1572             'printf(foo->c_str())',
1573             'Potential format string bug. '
1574             'Do printf("%s", foo->c_str()) instead.'
1575             '  [security/printf] [4]')
1576         self.assert_lint(
1577             'StringPrintf(foo)',
1578             'Potential format string bug. Do StringPrintf("%s", foo) instead.'
1579             ''
1580             '  [security/printf] [4]')
1581
1582     # Test for insecure temp file creation.
1583     def test_insecure_temp_file(self):
1584         self.assert_lint(
1585             'mktemp(template);',
1586             'Never use mktemp.  Use mkstemp or mkostemp instead.'
1587             '  [security/temp_file] [5]')
1588         self.assert_lint('mkstemp(template);', '')
1589         self.assert_lint('mkostemp(template);', '')
1590
1591     # Variable-length arrays are not permitted.
1592     def test_variable_length_array_detection(self):
1593         errmsg = ('Do not use variable-length arrays.  Use an appropriately named '
1594                   "('k' followed by CamelCase) compile-time constant for the size."
1595                   '  [runtime/arrays] [1]')
1596
1597         self.assert_lint('int a[any_old_variable];', errmsg)
1598         self.assert_lint('int doublesize[some_var * 2];', errmsg)
1599         self.assert_lint('int a[afunction()];', errmsg)
1600         self.assert_lint('int a[function(kMaxFooBars)];', errmsg)
1601         self.assert_lint('bool aList[items_->size()];', errmsg)
1602         self.assert_lint('namespace::Type buffer[len+1];', errmsg)
1603
1604         self.assert_lint('int a[64];', '')
1605         self.assert_lint('int a[0xFF];', '')
1606         self.assert_lint('int first[256], second[256];', '')
1607         self.assert_lint('int arrayName[kCompileTimeConstant];', '')
1608         self.assert_lint('char buf[somenamespace::kBufSize];', '')
1609         self.assert_lint('int arrayName[ALL_CAPS];', '')
1610         self.assert_lint('AClass array1[foo::bar::ALL_CAPS];', '')
1611         self.assert_lint('int a[kMaxStrLen + 1];', '')
1612         self.assert_lint('int a[sizeof(foo)];', '')
1613         self.assert_lint('int a[sizeof(*foo)];', '')
1614         self.assert_lint('int a[sizeof foo];', '')
1615         self.assert_lint('int a[sizeof(struct Foo)];', '')
1616         self.assert_lint('int a[128 - sizeof(const bar)];', '')
1617         self.assert_lint('int a[(sizeof(foo) * 4)];', '')
1618         self.assert_lint('int a[(arraysize(fixed_size_array)/2) << 1];', 'Missing spaces around /  [whitespace/operators] [3]')
1619         self.assert_lint('delete a[some_var];', '')
1620         self.assert_lint('return a[some_var];', '')
1621
1622     # Brace usage
1623     def test_braces(self):
1624         # Braces shouldn't be followed by a ; unless they're defining a struct
1625         # or initializing an array
1626         self.assert_lint('int a[3] = { 1, 2, 3 };', '')
1627         self.assert_lint(
1628             '''\
1629             const int foo[] =
1630                 {1, 2, 3 };''',
1631             '')
1632         # For single line, unmatched '}' with a ';' is ignored (not enough context)
1633         self.assert_multi_line_lint(
1634             '''\
1635             int a[3] = { 1,
1636                 2,
1637                 3 };''',
1638             '')
1639         self.assert_multi_line_lint(
1640             '''\
1641             int a[2][3] = { { 1, 2 },
1642                 { 3, 4 } };''',
1643             '')
1644         self.assert_multi_line_lint(
1645             '''\
1646             int a[2][3] =
1647                 { { 1, 2 },
1648                 { 3, 4 } };''',
1649             '')
1650
1651     # CHECK/EXPECT_TRUE/EXPECT_FALSE replacements
1652     def test_check_check(self):
1653         self.assert_lint('CHECK(x == 42)',
1654                          'Consider using CHECK_EQ instead of CHECK(a == b)'
1655                          '  [readability/check] [2]')
1656         self.assert_lint('CHECK(x != 42)',
1657                          'Consider using CHECK_NE instead of CHECK(a != b)'
1658                          '  [readability/check] [2]')
1659         self.assert_lint('CHECK(x >= 42)',
1660                          'Consider using CHECK_GE instead of CHECK(a >= b)'
1661                          '  [readability/check] [2]')
1662         self.assert_lint('CHECK(x > 42)',
1663                          'Consider using CHECK_GT instead of CHECK(a > b)'
1664                          '  [readability/check] [2]')
1665         self.assert_lint('CHECK(x <= 42)',
1666                          'Consider using CHECK_LE instead of CHECK(a <= b)'
1667                          '  [readability/check] [2]')
1668         self.assert_lint('CHECK(x < 42)',
1669                          'Consider using CHECK_LT instead of CHECK(a < b)'
1670                          '  [readability/check] [2]')
1671
1672         self.assert_lint('DCHECK(x == 42)',
1673                          'Consider using DCHECK_EQ instead of DCHECK(a == b)'
1674                          '  [readability/check] [2]')
1675         self.assert_lint('DCHECK(x != 42)',
1676                          'Consider using DCHECK_NE instead of DCHECK(a != b)'
1677                          '  [readability/check] [2]')
1678         self.assert_lint('DCHECK(x >= 42)',
1679                          'Consider using DCHECK_GE instead of DCHECK(a >= b)'
1680                          '  [readability/check] [2]')
1681         self.assert_lint('DCHECK(x > 42)',
1682                          'Consider using DCHECK_GT instead of DCHECK(a > b)'
1683                          '  [readability/check] [2]')
1684         self.assert_lint('DCHECK(x <= 42)',
1685                          'Consider using DCHECK_LE instead of DCHECK(a <= b)'
1686                          '  [readability/check] [2]')
1687         self.assert_lint('DCHECK(x < 42)',
1688                          'Consider using DCHECK_LT instead of DCHECK(a < b)'
1689                          '  [readability/check] [2]')
1690
1691         self.assert_lint(
1692             'EXPECT_TRUE("42" == x)',
1693             'Consider using EXPECT_EQ instead of EXPECT_TRUE(a == b)'
1694             '  [readability/check] [2]')
1695         self.assert_lint(
1696             'EXPECT_TRUE("42" != x)',
1697             'Consider using EXPECT_NE instead of EXPECT_TRUE(a != b)'
1698             '  [readability/check] [2]')
1699         self.assert_lint(
1700             'EXPECT_TRUE(+42 >= x)',
1701             'Consider using EXPECT_GE instead of EXPECT_TRUE(a >= b)'
1702             '  [readability/check] [2]')
1703         self.assert_lint(
1704             'EXPECT_TRUE_M(-42 > x)',
1705             'Consider using EXPECT_GT_M instead of EXPECT_TRUE_M(a > b)'
1706             '  [readability/check] [2]')
1707         self.assert_lint(
1708             'EXPECT_TRUE_M(42U <= x)',
1709             'Consider using EXPECT_LE_M instead of EXPECT_TRUE_M(a <= b)'
1710             '  [readability/check] [2]')
1711         self.assert_lint(
1712             'EXPECT_TRUE_M(42L < x)',
1713             'Consider using EXPECT_LT_M instead of EXPECT_TRUE_M(a < b)'
1714             '  [readability/check] [2]')
1715
1716         self.assert_lint(
1717             'EXPECT_FALSE(x == 42)',
1718             'Consider using EXPECT_NE instead of EXPECT_FALSE(a == b)'
1719             '  [readability/check] [2]')
1720         self.assert_lint(
1721             'EXPECT_FALSE(x != 42)',
1722             'Consider using EXPECT_EQ instead of EXPECT_FALSE(a != b)'
1723             '  [readability/check] [2]')
1724         self.assert_lint(
1725             'EXPECT_FALSE(x >= 42)',
1726             'Consider using EXPECT_LT instead of EXPECT_FALSE(a >= b)'
1727             '  [readability/check] [2]')
1728         self.assert_lint(
1729             'ASSERT_FALSE(x > 42)',
1730             'Consider using ASSERT_LE instead of ASSERT_FALSE(a > b)'
1731             '  [readability/check] [2]')
1732         self.assert_lint(
1733             'ASSERT_FALSE(x <= 42)',
1734             'Consider using ASSERT_GT instead of ASSERT_FALSE(a <= b)'
1735             '  [readability/check] [2]')
1736         self.assert_lint(
1737             'ASSERT_FALSE_M(x < 42)',
1738             'Consider using ASSERT_GE_M instead of ASSERT_FALSE_M(a < b)'
1739             '  [readability/check] [2]')
1740
1741         self.assert_lint('CHECK(some_iterator == obj.end())', '')
1742         self.assert_lint('EXPECT_TRUE(some_iterator == obj.end())', '')
1743         self.assert_lint('EXPECT_FALSE(some_iterator == obj.end())', '')
1744
1745         self.assert_lint('CHECK(CreateTestFile(dir, (1 << 20)));', '')
1746         self.assert_lint('CHECK(CreateTestFile(dir, (1 >> 20)));', '')
1747
1748         self.assert_lint('CHECK(x<42)',
1749                          ['Missing spaces around <'
1750                           '  [whitespace/operators] [3]',
1751                           'Consider using CHECK_LT instead of CHECK(a < b)'
1752                           '  [readability/check] [2]'])
1753         self.assert_lint('CHECK(x>42)',
1754                          'Consider using CHECK_GT instead of CHECK(a > b)'
1755                          '  [readability/check] [2]')
1756
1757         self.assert_lint(
1758             '    EXPECT_TRUE(42 < x) // Random comment.',
1759             'Consider using EXPECT_LT instead of EXPECT_TRUE(a < b)'
1760             '  [readability/check] [2]')
1761         self.assert_lint(
1762             'EXPECT_TRUE( 42 < x )',
1763             ['Extra space after ( in function call'
1764              '  [whitespace/parens] [4]',
1765              'Consider using EXPECT_LT instead of EXPECT_TRUE(a < b)'
1766              '  [readability/check] [2]'])
1767         self.assert_lint(
1768             'CHECK("foo" == "foo")',
1769             'Consider using CHECK_EQ instead of CHECK(a == b)'
1770             '  [readability/check] [2]')
1771
1772         self.assert_lint('CHECK_EQ("foo", "foo")', '')
1773
1774     def test_brace_at_begin_of_line(self):
1775         self.assert_lint('{',
1776                          'This { should be at the end of the previous line'
1777                          '  [whitespace/braces] [4]')
1778         self.assert_multi_line_lint(
1779             '#endif\n'
1780             '{\n'
1781             '}\n',
1782             '')
1783         self.assert_multi_line_lint(
1784             'if (condition) {',
1785             '')
1786         self.assert_multi_line_lint(
1787             '    MACRO1(macroArg) {',
1788             '')
1789         self.assert_multi_line_lint(
1790             'ACCESSOR_GETTER(MessageEventPorts) {',
1791             'Place brace on its own line for function definitions.  [whitespace/braces] [4]')
1792         self.assert_multi_line_lint(
1793             'int foo() {',
1794             'Place brace on its own line for function definitions.  [whitespace/braces] [4]')
1795         self.assert_multi_line_lint(
1796             'int foo() const {',
1797             'Place brace on its own line for function definitions.  [whitespace/braces] [4]')
1798         self.assert_multi_line_lint(
1799             'int foo() const override {',
1800             'Place brace on its own line for function definitions.  [whitespace/braces] [4]')
1801         self.assert_multi_line_lint(
1802             'int foo() override {',
1803             'Place brace on its own line for function definitions.  [whitespace/braces] [4]')
1804         self.assert_multi_line_lint(
1805             'int foo() const final {',
1806             'Place brace on its own line for function definitions.  [whitespace/braces] [4]')
1807         self.assert_multi_line_lint(
1808             'int foo() final {',
1809             'Place brace on its own line for function definitions.  [whitespace/braces] [4]')
1810         self.assert_multi_line_lint(
1811             'int foo() const\n'
1812             '{\n'
1813             '}\n',
1814             '')
1815         self.assert_multi_line_lint(
1816             'int foo() override\n'
1817             '{\n'
1818             '}\n',
1819             '')
1820         self.assert_multi_line_lint(
1821             'int foo() final\n'
1822             '{\n'
1823             '}\n',
1824             '')
1825         self.assert_multi_line_lint(
1826             '[]() {\n'
1827             '}\n',
1828             '')
1829         self.assert_multi_line_lint(
1830             'if (condition\n'
1831             '    && condition2\n'
1832             '    && condition3) {\n'
1833             '}\n',
1834             '')
1835         self.assert_multi_line_lint(
1836             'auto Foo:bar() -> Baz\n'
1837             '{\n'
1838             '}\n',
1839             '')
1840         self.assert_multi_line_lint(
1841             'int foo() const override\n'
1842             '{\n'
1843             '}\n',
1844             '')
1845         self.assert_multi_line_lint(
1846             'int foo() const final\n'
1847             '{\n'
1848             '}\n',
1849             '')
1850         self.assert_multi_line_lint(
1851             '    @try {\n'
1852             '    } @catch (NSException *exception) {\n'
1853             '    }\n',
1854             '')
1855         self.assert_multi_line_lint(
1856             '    @synchronized (self) {\n'
1857             '    }\n',
1858             '')
1859
1860     def test_mismatching_spaces_in_parens(self):
1861         self.assert_lint('if (foo ) {', 'Extra space before ) in if'
1862                          '  [whitespace/parens] [5]')
1863         self.assert_lint('switch ( foo) {', 'Extra space after ( in switch'
1864                          '  [whitespace/parens] [5]')
1865         self.assert_lint('for (foo; ba; bar ) {', 'Extra space before ) in for'
1866                          '  [whitespace/parens] [5]')
1867         self.assert_lint('for ((foo); (ba); (bar) ) {', 'Extra space before ) in for'
1868                          '  [whitespace/parens] [5]')
1869         self.assert_lint('for (; foo; bar) {', '')
1870         self.assert_lint('for (; (foo); (bar)) {', '')
1871         self.assert_lint('for ( ; foo; bar) {', '')
1872         self.assert_lint('for ( ; (foo); (bar)) {', '')
1873         self.assert_lint('for ( ; foo; bar ) {', 'Extra space before ) in for'
1874                          '  [whitespace/parens] [5]')
1875         self.assert_lint('for ( ; (foo); (bar) ) {', 'Extra space before ) in for'
1876                          '  [whitespace/parens] [5]')
1877         self.assert_lint('for (foo; bar; ) {', '')
1878         self.assert_lint('for ((foo); (bar); ) {', '')
1879         self.assert_lint('while (  foo) {', 'Extra space after ( in while'
1880                          '  [whitespace/parens] [5]')
1881
1882     def test_spacing_for_fncall(self):
1883         self.assert_lint('if (foo) {', '')
1884         self.assert_lint('for (foo;bar;baz) {', '')
1885         self.assert_lint('while (foo) {', '')
1886         self.assert_lint('switch (foo) {', '')
1887         self.assert_lint('new (RenderArena()) RenderInline(document())', '')
1888         self.assert_lint('foo( bar)', 'Extra space after ( in function call'
1889                          '  [whitespace/parens] [4]')
1890         self.assert_lint('foobar( \\', '')
1891         self.assert_lint('foobar(     \\', '')
1892         self.assert_lint('( a + b)', 'Extra space after ('
1893                          '  [whitespace/parens] [2]')
1894         self.assert_lint('((a+b))', '')
1895         self.assert_lint('foo (foo)', 'Extra space before ( in function call'
1896                          '  [whitespace/parens] [4]')
1897         self.assert_lint('@property (readonly) NSUInteger count;', '')
1898         self.assert_lint('#elif (foo(bar))', '')
1899         self.assert_lint('#elif (foo(bar) && foo(baz))', '')
1900         self.assert_lint('typedef foo (*foo)(foo)', '')
1901         self.assert_lint('typedef foo (*foo12bar_)(foo)', '')
1902         self.assert_lint('typedef foo (Foo::*bar)(foo)', '')
1903         self.assert_lint('foo (Foo::*bar)(',
1904                          'Extra space before ( in function call'
1905                          '  [whitespace/parens] [4]')
1906         self.assert_lint('typedef foo (Foo::*bar)(', '')
1907         self.assert_lint('(foo)(bar)', '')
1908         self.assert_lint('Foo (*foo)(bar)', '')
1909         self.assert_lint('Foo (*foo)(Bar bar,', '')
1910         self.assert_lint('char (*p)[sizeof(foo)] = &foo', '')
1911         self.assert_lint('char (&ref)[sizeof(foo)] = &foo', '')
1912         self.assert_lint('const char32 (*table[])[6];', '')
1913         self.assert_lint('@interface Foo (Category)', '')
1914         self.assert_lint('@interface Foo ()', '')
1915         self.assert_lint('@implementation Foo (Category)', '')
1916         self.assert_lint('@implementation Foo ()', '')
1917
1918     def test_spacing_before_braces(self):
1919         self.assert_lint('if (foo){', 'Missing space before {'
1920                          '  [whitespace/braces] [5]')
1921         self.assert_lint('for{', 'Missing space before {'
1922                          '  [whitespace/braces] [5]')
1923         self.assert_lint('for {', '')
1924         self.assert_lint('dispatch_async(dispatch_get_main_queue(), ^{', '')
1925         self.assert_lint('[outOfBandTracks.get() addObject:@{', '')
1926         self.assert_lint('EXPECT_DEBUG_DEATH({', '')
1927         self.assert_lint('LOCAL_LOG(R"({ "url": "%{public}s",)", url.string().utf8().data());', '')
1928
1929     def test_spacing_between_braces(self):
1930         self.assert_lint('    { }', '')
1931         self.assert_lint('    {}', 'Missing space inside { }.  [whitespace/braces] [5]')
1932         self.assert_lint('    {   }', 'Too many spaces inside { }.  [whitespace/braces] [5]')
1933
1934     def test_spacing_before_brackets(self):
1935         self.assert_lint('delete [] base;', '')
1936         # See SOFT_LINK_CLASS_FOR_HEADER() macro in SoftLinking.h.
1937         self.assert_lint('        return [get_##framework##_##className##Class() alloc]; \\', '')
1938         self.assert_lint('        m_taskFunction = [callee, method, arguments...] {', '')
1939         self.assert_lint('int main(int argc, char* agrv [])', 'Extra space before [.  [whitespace/brackets] [5]')
1940         self.assert_lint('    str [strLength] = \'\\0\';', 'Extra space before [.  [whitespace/brackets] [5]')
1941
1942     def test_cpp_lambda_functions(self):
1943         self.assert_lint('        [&] (Type argument) {', '')
1944         self.assert_lint('        [] {', '')
1945         self.assert_lint('        [ =] (Type argument) {', 'Extra space in capture list.  [whitespace/brackets] [4]')
1946         self.assert_lint('        [var, var_ref&] {', '')
1947         self.assert_lint('        [var , var_ref&] {', 'Extra space in capture list.  [whitespace/brackets] [4]')
1948         self.assert_lint('        [var,var_ref&] {', 'Missing space after ,  [whitespace/comma] [3]')
1949
1950     def test_objective_c_block(self):
1951         self.assert_lint('        ^(var, var_ref) {', '', 'foo.mm')
1952         self.assert_lint('        ^(var, var_ref) {', '', 'foo.m')
1953         self.assert_lint('        ^(var , var_ref) {', 'Extra space in block arguments.  [whitespace/brackets] [4]', 'foo.m')
1954         self.assert_lint('        ^(var,var_ref) {', 'Missing space after ,  [whitespace/comma] [3]', 'foo.m')
1955         self.assert_lint('        ^(var, var_ref) {', 'Place brace on its own line for function definitions.  [whitespace/braces] [4]', 'foo.cpp')
1956         self.assert_lint('        ^{', '', 'foo.m')
1957         self.assert_lint('        ^ {', 'Extra space between ^ and block definition.  [whitespace/brackets] [4]', 'foo.m')
1958         self.assert_lint('        ^   {', 'Extra space between ^ and block definition.  [whitespace/brackets] [4]', 'foo.m')
1959         self.assert_lint('        ^ (arg1, arg2) {', 'Extra space between ^ and block arguments.  [whitespace/brackets] [4]', 'foo.m')
1960         self.assert_lint('        ^(arg1, arg2){', 'Missing space before {  [whitespace/braces] [5]', 'foo.m')
1961
1962     def test_objective_c_block_as_argument(self):
1963         self.assert_lint('        withLambda:^(var, var_ref) {', '', 'foo.mm')
1964         self.assert_lint('        withLambda:^{', '', 'foo.m')
1965         self.assert_lint('        withLambda:^ {', 'Extra space between ^ and block definition.  [whitespace/brackets] [4]', 'foo.m')
1966
1967     def test_spacing_around_else(self):
1968         self.assert_lint('}else {', 'Missing space before else'
1969                          '  [whitespace/braces] [5]')
1970         self.assert_lint('} else{', 'Missing space before {'
1971                          '  [whitespace/braces] [5]')
1972         self.assert_lint('} else {', '')
1973         self.assert_lint('} else if', '')
1974
1975     def test_spacing_for_binary_ops(self):
1976         self.assert_lint('if (foo<=bar) {', 'Missing spaces around <='
1977                          '  [whitespace/operators] [3]')
1978         self.assert_lint('if (foo<bar) {', 'Missing spaces around <'
1979                          '  [whitespace/operators] [3]')
1980         self.assert_lint('if (foo<bar->baz) {', 'Missing spaces around <'
1981                          '  [whitespace/operators] [3]')
1982         self.assert_lint('if (foo<bar->bar) {', 'Missing spaces around <'
1983                          '  [whitespace/operators] [3]')
1984         self.assert_lint('typedef hash_map<Foo, Bar', 'Missing spaces around <'
1985                          '  [whitespace/operators] [3]')
1986         self.assert_lint('typedef hash_map<FoooooType, BaaaaarType,', '')
1987         self.assert_lint('a<Foo> t+=b;', 'Missing spaces around +='
1988                          '  [whitespace/operators] [3]')
1989         self.assert_lint('a<Foo> t-=b;', 'Missing spaces around -='
1990                          '  [whitespace/operators] [3]')
1991         self.assert_lint('a<Foo*> t*=b;', 'Missing spaces around *='
1992                          '  [whitespace/operators] [3]')
1993         self.assert_lint('a<Foo*> t/=b;', 'Missing spaces around /='
1994                          '  [whitespace/operators] [3]')
1995         self.assert_lint('a<Foo*> t|=b;', 'Missing spaces around |='
1996                          '  [whitespace/operators] [3]')
1997         self.assert_lint('a<Foo*> t&=b;', 'Missing spaces around &='
1998                          '  [whitespace/operators] [3]')
1999         self.assert_lint('a<Foo*> t<<=b;', 'Missing spaces around <<='
2000                          '  [whitespace/operators] [3]')
2001         self.assert_lint('a<Foo*> t>>=b;', 'Missing spaces around >>='
2002                          '  [whitespace/operators] [3]')
2003         self.assert_lint('a<Foo*> t>>=&b|c;', 'Missing spaces around >>='
2004                          '  [whitespace/operators] [3]')
2005         self.assert_lint('a<Foo*> t<<=*b/c;', 'Missing spaces around <<='
2006                          '  [whitespace/operators] [3]')
2007         self.assert_lint('a<Foo> t -= b;', '')
2008         self.assert_lint('a<Foo> t += b;', '')
2009         self.assert_lint('a<Foo*> t *= b;', '')
2010         self.assert_lint('a<Foo*> t /= b;', '')
2011         self.assert_lint('a<Foo*> t |= b;', '')
2012         self.assert_lint('a<Foo*> t &= b;', '')
2013         self.assert_lint('a<Foo*> t <<= b;', '')
2014         self.assert_lint('a<Foo*> t >>= b;', '')
2015         self.assert_lint('a<Foo*> t >>= &b|c;', 'Missing spaces around |'
2016                          '  [whitespace/operators] [3]')
2017         self.assert_lint('a<Foo*> t <<= *b/c;', 'Missing spaces around /'
2018                          '  [whitespace/operators] [3]')
2019         self.assert_lint('a<Foo*> t <<= b/c; //Test', [
2020                          'Should have a space between // and comment  '
2021                          '[whitespace/comments] [4]', 'Missing'
2022                          ' spaces around /  [whitespace/operators] [3]'])
2023         self.assert_lint('a<Foo*> t <<= b||c;  //Test', ['One space before end'
2024                          ' of line comments  [whitespace/comments] [5]',
2025                          'Should have a space between // and comment  '
2026                          '[whitespace/comments] [4]',
2027                          'Missing spaces around ||  [whitespace/operators] [3]'])
2028         self.assert_lint('a<Foo*> t <<= b||c; // Test', 'Missing spaces around'
2029                          ' ||  [whitespace/operators] [3]')
2030         self.assert_lint('a<Foo*> t <<= b||&c; // Test', 'Missing spaces around'
2031                          ' ||  [whitespace/operators] [3]')
2032         self.assert_lint('a<Foo*> t <<= b||*c; // Test', 'Missing spaces around'
2033                          ' ||  [whitespace/operators] [3]')
2034         self.assert_lint('a<Foo*> t <<= b && *c; // Test', '')
2035         self.assert_lint('a<Foo*> t <<= b && &c; // Test', '')
2036         self.assert_lint('a<Foo*> t <<= b || &c;  /*Test', 'Complex multi-line '
2037                          '/*...*/-style comment found. Lint may give bogus '
2038                          'warnings.  Consider replacing these with //-style'
2039                          ' comments, with #if 0...#endif, or with more clearly'
2040                          ' structured multi-line comments.  [readability/multiline_comment] [5]')
2041         self.assert_lint('a<Foo&> t <<= &b | &c;', '')
2042         self.assert_lint('a<Foo*> t <<= &b & &c; // Test', '')
2043         self.assert_lint('a<Foo*> t <<= *b / &c; // Test', '')
2044         self.assert_lint('if (a=b == 1)', 'Missing spaces around =  [whitespace/operators] [4]')
2045         self.assert_lint('if (a = b == 1)', '')
2046         self.assert_multi_line_lint('#include <sys/io.h>\n', '')
2047         self.assert_multi_line_lint('#import <foo/bar.h>\n', '')
2048         self.assert_multi_line_lint('#if __has_include(<ApplicationServices/ApplicationServicesPriv.h>)\n', '')
2049         self.assert_multi_line_lint('#elif __has_include(<ApplicationServices/ApplicationServicesPriv.h>)\n', '')
2050         self.assert_multi_line_lint('#endif // __has_include(<ApplicationServices/ApplicationServicesPriv.h>)\n', '')
2051         self.assert_lint('Foo&& a = bar();', '')
2052
2053     def test_operator_methods(self):
2054         self.assert_lint('String operator+(const String&, const String&);', '')
2055         self.assert_lint('String operator/(const String&, const String&);', '')
2056         self.assert_lint('bool operator==(const String&, const String&);', '')
2057         self.assert_lint('String& operator-=(const String&, const String&);', '')
2058         self.assert_lint('String& operator+=(const String&, const String&);', '')
2059         self.assert_lint('String& operator*=(const String&, const String&);', '')
2060         self.assert_lint('String& operator%=(const String&, const String&);', '')
2061         self.assert_lint('String& operator&=(const String&, const String&);', '')
2062         self.assert_lint('String& operator<<=(const String&, const String&);', '')
2063         self.assert_lint('String& operator>>=(const String&, const String&);', '')
2064         self.assert_lint('String& operator|=(const String&, const String&);', '')
2065         self.assert_lint('String& operator^=(const String&, const String&);', '')
2066
2067     def test_spacing_in_objective_c_properties(self):
2068         self.assert_lint('@property (readonly) BOOL pass;', '')
2069         self.assert_lint('@property (getter=isPassing) BOOL passing;', '')
2070         self.assert_lint('@property (nonatomic, readonly) NSString* title;', '')
2071         self.assert_lint('@property(readonly) BOOL fail;',
2072                          'Should have space between @property and attributes.  [whitespace/property] [4]')
2073         self.assert_lint('@property (getter = isFailing) BOOL failing;',
2074                          'Should not have spaces around = in property attributes.  [whitespace/property] [4]')
2075         self.assert_lint('@property (nonatomic,readonly) NSString* title;',
2076                          'Missing space after ,  [whitespace/comma] [3]')
2077
2078     def test_spacing_before_last_semicolon(self):
2079         self.assert_lint('call_function() ;',
2080                          'Extra space before last semicolon. If this should be an '
2081                          'empty statement, use { } instead.'
2082                          '  [whitespace/semicolon] [5]')
2083         self.assert_lint('while (true) ;',
2084                          'Extra space before last semicolon. If this should be an '
2085                          'empty statement, use { } instead.'
2086                          '  [whitespace/semicolon] [5]')
2087         self.assert_lint('default:;',
2088                          'Semicolon defining empty statement. Use { } instead.'
2089                          '  [whitespace/semicolon] [5]')
2090         self.assert_lint('        ;',
2091                          'Line contains only semicolon. If this should be an empty '
2092                          'statement, use { } instead.'
2093                          '  [whitespace/semicolon] [5]')
2094         self.assert_lint('for (int i = 0; ;', '')
2095
2096     # Static or global STL strings.
2097     def test_static_or_global_stlstrings(self):
2098         self.assert_lint('string foo;',
2099                          'For a static/global string constant, use a C style '
2100                          'string instead: "char foo[]".'
2101                          '  [runtime/string] [4]')
2102         self.assert_lint('string kFoo = "hello"; // English',
2103                          'For a static/global string constant, use a C style '
2104                          'string instead: "char kFoo[]".'
2105                          '  [runtime/string] [4]')
2106         self.assert_lint('static string foo;',
2107                          'For a static/global string constant, use a C style '
2108                          'string instead: "static char foo[]".'
2109                          '  [runtime/string] [4]')
2110         self.assert_lint('static const string foo;',
2111                          'For a static/global string constant, use a C style '
2112                          'string instead: "static const char foo[]".'
2113                          '  [runtime/string] [4]')
2114         self.assert_lint('string Foo::bar;',
2115                          'For a static/global string constant, use a C style '
2116                          'string instead: "char Foo::bar[]".'
2117                          '  [runtime/string] [4]')
2118         # Rare case.
2119         self.assert_lint('string foo("foobar");',
2120                          'For a static/global string constant, use a C style '
2121                          'string instead: "char foo[]".'
2122                          '  [runtime/string] [4]')
2123         # Should not catch local or member variables.
2124         self.assert_lint('    string foo', '')
2125         # Should not catch functions.
2126         self.assert_lint('string EmptyString() { return ""; }', '')
2127         self.assert_lint('string EmptyString () { return ""; }', '')
2128         self.assert_lint('string VeryLongNameFunctionSometimesEndsWith(\n'
2129                          '    VeryLongNameType veryLongNameVariable) { }', '')
2130         self.assert_lint('template<>\n'
2131                          'string FunctionTemplateSpecialization<SomeType>(\n'
2132                          '    int x) { return ""; }', '')
2133         self.assert_lint('template<>\n'
2134                          'string FunctionTemplateSpecialization<vector<A::B>* >(\n'
2135                          '    int x) { return ""; }', '')
2136
2137         # should not catch methods of template classes.
2138         self.assert_lint('string Class<Type>::Method() const\n'
2139                          '{\n'
2140                          '    return "";\n'
2141                          '}\n', '')
2142         self.assert_lint('string Class<Type>::Method(\n'
2143                          '    int arg) const\n'
2144                          '{\n'
2145                          '    return "";\n'
2146                          '}\n', '')
2147
2148     def test_no_spaces_in_function_calls(self):
2149         self.assert_lint('TellStory(1, 3);',
2150                          '')
2151         self.assert_lint('TellStory(1, 3 );',
2152                          'Extra space before )'
2153                          '  [whitespace/parens] [2]')
2154         self.assert_lint('TellStory(1 /* wolf */, 3 /* pigs */);',
2155                          '')
2156         self.assert_multi_line_lint('#endif\n    );',
2157                                     '')
2158
2159     def test_one_spaces_between_code_and_comments(self):
2160         self.assert_lint('} // namespace foo',
2161                          '')
2162         self.assert_lint('}// namespace foo',
2163                          'One space before end of line comments'
2164                          '  [whitespace/comments] [5]')
2165         self.assert_lint('printf("foo"); // Outside quotes.',
2166                          '')
2167         self.assert_lint('int i = 0; // Having one space is fine.', '')
2168         self.assert_lint('int i = 0;  // Having two spaces is bad.',
2169                          'One space before end of line comments'
2170                          '  [whitespace/comments] [5]')
2171         self.assert_lint('int i = 0;   // Having three spaces is bad.',
2172                          'One space before end of line comments'
2173                          '  [whitespace/comments] [5]')
2174         self.assert_lint('// Top level comment', '')
2175         self.assert_lint('    // Line starts with four spaces.', '')
2176         self.assert_lint('foo();\n'
2177                          '{ // A scope is opening.', '')
2178         self.assert_lint('    foo();\n'
2179                          '    { // An indented scope is opening.', '')
2180         self.assert_lint('if (foo) { // not a pure scope',
2181                          '')
2182         self.assert_lint('printf("// In quotes.")', '')
2183         self.assert_lint('printf("\\"%s // In quotes.")', '')
2184         self.assert_lint('printf("%s", "// In quotes.")', '')
2185
2186     def test_one_spaces_after_punctuation_in_comments(self):
2187         self.assert_lint('int a; // This is a sentence.',
2188                          '')
2189         self.assert_lint('int a; // This is a sentence.  ',
2190                          'Line ends in whitespace.  Consider deleting these extra spaces.  [whitespace/end_of_line] [4]')
2191         self.assert_lint('int a; // This is a sentence. This is a another sentence.',
2192                          '')
2193         self.assert_lint('int a; // This is a sentence.  This is a another sentence.',
2194                          'Should have only a single space after a punctuation in a comment.  [whitespace/comments] [5]')
2195         self.assert_lint('int a; // This is a sentence!  This is a another sentence.',
2196                          'Should have only a single space after a punctuation in a comment.  [whitespace/comments] [5]')
2197         self.assert_lint('int a; // Why did I write this?  This is a another sentence.',
2198                          'Should have only a single space after a punctuation in a comment.  [whitespace/comments] [5]')
2199         self.assert_lint('int a; // Elementary,  my dear.',
2200                          'Should have only a single space after a punctuation in a comment.  [whitespace/comments] [5]')
2201         self.assert_lint('int a; // The following should be clear:  Is it?',
2202                          'Should have only a single space after a punctuation in a comment.  [whitespace/comments] [5]')
2203         self.assert_lint('int a; // Look at the follow semicolon;  I hope this gives an error.',
2204                          'Should have only a single space after a punctuation in a comment.  [whitespace/comments] [5]')
2205
2206     def test_space_after_comment_marker(self):
2207         self.assert_lint('//', '')
2208         self.assert_lint('//x', 'Should have a space between // and comment'
2209                          '  [whitespace/comments] [4]')
2210         self.assert_lint('// x', '')
2211         self.assert_lint('//----', '')
2212         self.assert_lint('//====', '')
2213         self.assert_lint('//////', '')
2214         self.assert_lint('////// x', '')
2215         self.assert_lint('/// x', '')
2216         self.assert_lint('////x', 'Should have a space between // and comment'
2217                          '  [whitespace/comments] [4]')
2218
2219     def test_newline_at_eof(self):
2220         def do_test(self, data, is_missing_eof):
2221             error_collector = ErrorCollector(self.assertTrue)
2222             self.process_file_data('foo.cpp', 'cpp', data.split('\n'),
2223                                    error_collector)
2224             # The warning appears only once.
2225             self.assertEqual(
2226                 int(is_missing_eof),
2227                 error_collector.results().count(
2228                     'Could not find a newline character at the end of the file.'
2229                     '  [whitespace/ending_newline] [5]'))
2230
2231         do_test(self, '// Newline\n// at EOF\n', False)
2232         do_test(self, '// Newline2\n\n// at EOF\n', False)
2233         do_test(self, '// No newline\n// at EOF', True)
2234         do_test(self, '// No newline2\n\n// at EOF', True)
2235
2236     def test_extra_newlines_at_eof(self):
2237         def do_test(self, data, too_many_newlines):
2238             error_collector = ErrorCollector(self.assertTrue)
2239             self.process_file_data('foo.cpp', 'cpp', data.split('\n'),
2240                                    error_collector)
2241             # The warning appears only once.
2242             self.assertEqual(
2243                 int(too_many_newlines),
2244                 error_collector.results().count(
2245                     'There was more than one newline at the end of the file.'
2246                     '  [whitespace/ending_newline] [5]'))
2247
2248         do_test(self, '// No Newline\n// at EOF', False)
2249         do_test(self, '// No Newline2\n\n// at EOF', False)
2250         do_test(self, '// One Newline\n// at EOF\n', False)
2251         do_test(self, '// One Newline2\n\n// at EOF\n', False)
2252         do_test(self, '// Two Newlines\n// at EOF\n\n', True)
2253         do_test(self, '// Three Newlines\n// at EOF\n\n\n', True)
2254
2255     def test_invalid_utf8(self):
2256         def do_test(self, raw_bytes, has_invalid_utf8):
2257             error_collector = ErrorCollector(self.assertTrue)
2258             self.process_file_data('foo.cpp', 'cpp',
2259                                    unicode(raw_bytes, 'utf8', 'replace').split('\n'),
2260                                    error_collector)
2261             # The warning appears only once.
2262             self.assertEqual(
2263                 int(has_invalid_utf8),
2264                 error_collector.results().count(
2265                     'Line contains invalid UTF-8'
2266                     ' (or Unicode replacement character).'
2267                     '  [readability/utf8] [5]'))
2268
2269         do_test(self, 'Hello world\n', False)
2270         do_test(self, '\xe9\x8e\xbd\n', False)
2271         do_test(self, '\xe9x\x8e\xbd\n', True)
2272         # This is the encoding of the replacement character itself (which
2273         # you can see by evaluating codecs.getencoder('utf8')(u'\ufffd')).
2274         do_test(self, '\xef\xbf\xbd\n', True)
2275
2276     def test_is_blank_line(self):
2277         self.assertTrue(cpp_style.is_blank_line(''))
2278         self.assertTrue(cpp_style.is_blank_line(' '))
2279         self.assertTrue(cpp_style.is_blank_line(' \t\r\n'))
2280         self.assertTrue(not cpp_style.is_blank_line('int a;'))
2281         self.assertTrue(not cpp_style.is_blank_line('{'))
2282
2283     def test_blank_lines_check(self):
2284         self.assert_blank_lines_check(['{\n', '\n', '\n', '}\n'], 1, 1)
2285         self.assert_blank_lines_check(['  if (foo) {\n', '\n', '  }\n'], 1, 1)
2286         self.assert_blank_lines_check(
2287             ['\n', '// {\n', '\n', '\n', '// Comment\n', '{\n', '}\n'], 0, 0)
2288         self.assert_blank_lines_check(['\n', 'run("{");\n', '\n'], 0, 0)
2289         self.assert_blank_lines_check(['\n', '  if (foo) { return 0; }\n', '\n'], 0, 0)
2290
2291     def test_allow_blank_line_before_closing_namespace(self):
2292         error_collector = ErrorCollector(self.assertTrue)
2293         self.process_file_data('foo.cpp', 'cpp',
2294                                ['namespace {', '', '}  // namespace'],
2295                                error_collector)
2296         self.assertEqual(0, error_collector.results().count(
2297             'Blank line at the end of a code block.  Is this needed?'
2298             '  [whitespace/blank_line] [3]'))
2299
2300     def test_allow_blank_line_before_if_else_chain(self):
2301         error_collector = ErrorCollector(self.assertTrue)
2302         self.process_file_data('foo.cpp', 'cpp',
2303                                ['if (hoge) {',
2304                                 '',  # No warning
2305                                 '} else if (piyo) {',
2306                                 '',  # No warning
2307                                 '} else if (piyopiyo) {',
2308                                 '  hoge = true;',  # No warning
2309                                 '} else {',
2310                                 '',  # Warning on this line
2311                                 '}'],
2312                                error_collector)
2313         self.assertEqual(1, error_collector.results().count(
2314             'Blank line at the end of a code block.  Is this needed?'
2315             '  [whitespace/blank_line] [3]'))
2316
2317     def test_else_on_same_line_as_closing_braces(self):
2318         error_collector = ErrorCollector(self.assertTrue)
2319         self.process_file_data('foo.cpp', 'cpp',
2320                                ['if (hoge) {',
2321                                 '',
2322                                 '}',
2323                                 ' else {'  # Warning on this line
2324                                 '',
2325                                 '}'],
2326                                error_collector)
2327         self.assertEqual(1, error_collector.results().count(
2328             'An else should appear on the same line as the preceding }'
2329             '  [whitespace/newline] [4]'))
2330
2331     def test_else_clause_not_on_same_line_as_else(self):
2332         self.assert_lint('    else DoSomethingElse();',
2333                          'Else clause should never be on same line as else '
2334                          '(use 2 lines)  [whitespace/newline] [4]')
2335         self.assert_lint('    else ifDoSomethingElse();',
2336                          'Else clause should never be on same line as else '
2337                          '(use 2 lines)  [whitespace/newline] [4]')
2338         self.assert_lint('    else if (blah) {', '')
2339         self.assert_lint('    variable_ends_in_else = true;', '')
2340         self.assert_lint('    else \\', '')
2341
2342     def test_comma(self):
2343         self.assert_lint('a = f(1,2);',
2344                          'Missing space after ,  [whitespace/comma] [3]')
2345         self.assert_lint('int tmp=a,a=b,b=tmp;',
2346                          ['Missing spaces around =  [whitespace/operators] [4]',
2347                           'Missing space after ,  [whitespace/comma] [3]'])
2348         self.assert_lint('f(a, /* name */ b);', '')
2349         self.assert_lint('f(a, /* name */b);', '')
2350
2351     def test_declaration(self):
2352         self.assert_lint('int a;', '')
2353         self.assert_lint('int   a;', 'Extra space between int and a  [whitespace/declaration] [3]')
2354         self.assert_lint('int*  a;', 'Extra space between int* and a  [whitespace/declaration] [3]')
2355         self.assert_lint('else if { }', '')
2356         self.assert_lint('else   if { }', 'Extra space between else and if  [whitespace/declaration] [3]')
2357
2358     def test_pointer_reference_marker_location(self):
2359         self.assert_lint('int* b;', '', 'foo.cpp')
2360         self.assert_lint('int *b;',
2361                          'Declaration has space between type name and * in int *b  [whitespace/declaration] [3]',
2362                          'foo.cpp')
2363         self.assert_lint('int * b;',
2364                          'Declaration has space between type name and * in int * b  [whitespace/declaration] [3]',
2365                          'foo.cpp')
2366         self.assert_lint('return *b;', '', 'foo.cpp')
2367         self.assert_lint('return a * b;', '', 'foo.cpp')
2368         self.assert_lint('delete *b;', '', 'foo.cpp')
2369         self.assert_lint('int *b;', '', 'foo.c')
2370         self.assert_lint('int* b;',
2371                          'Declaration has space between * and variable name in int* b  [whitespace/declaration] [3]',
2372                          'foo.c')
2373         self.assert_lint('int& b;', '', 'foo.cpp')
2374         self.assert_lint('int &b;',
2375                          'Declaration has space between type name and & in int &b  [whitespace/declaration] [3]',
2376                          'foo.cpp')
2377         self.assert_lint('return &b;', '', 'foo.cpp')
2378         self.assert_lint('*foo = bar;', '', 'foo.cpp')
2379
2380     def test_indent(self):
2381         self.assert_lint('static int noindent;', '')
2382         self.assert_lint('    int fourSpaceIndent;', '')
2383         self.assert_lint(' int oneSpaceIndent;',
2384                          'Weird number of spaces at line-start.  '
2385                          'Are you using a 4-space indent?  [whitespace/indent] [3]')
2386         self.assert_lint('   int threeSpaceIndent;',
2387                          'Weird number of spaces at line-start.  '
2388                          'Are you using a 4-space indent?  [whitespace/indent] [3]')
2389         self.assert_lint(' char* oneSpaceIndent = "public:";',
2390                          'Weird number of spaces at line-start.  '
2391                          'Are you using a 4-space indent?  [whitespace/indent] [3]')
2392         self.assert_lint(' public:',
2393                          'Weird number of spaces at line-start.  '
2394                          'Are you using a 4-space indent?  [whitespace/indent] [3]')
2395         self.assert_lint('  public:',
2396                          'Weird number of spaces at line-start.  '
2397                          'Are you using a 4-space indent?  [whitespace/indent] [3]')
2398         self.assert_lint('   public:',
2399                          'Weird number of spaces at line-start.  '
2400                          'Are you using a 4-space indent?  [whitespace/indent] [3]')
2401         self.assert_multi_line_lint(
2402             'class Foo {\n'
2403             'public:\n'
2404             '    enum Bar {\n'
2405             '        Alpha,\n'
2406             '        Beta,\n'
2407             '#if ENABLED_BETZ\n'
2408             '        Charlie,\n'
2409             '#endif\n'
2410             '    };\n'
2411             '};',
2412             '')
2413
2414     def test_not_alabel(self):
2415         self.assert_lint('MyVeryLongNamespace::MyVeryLongClassName::', '')
2416
2417     def test_tab(self):
2418         self.assert_lint('\tint a;',
2419                          'Tab found; better to use spaces  [whitespace/tab] [1]')
2420         self.assert_lint('int a = 5;\t// set a to 5',
2421                          'Tab found; better to use spaces  [whitespace/tab] [1]')
2422
2423     def test_unnamed_namespaces_in_headers(self):
2424         self.assert_language_rules_check(
2425             'foo.h', 'namespace {',
2426             'Do not use unnamed namespaces in header files.  See'
2427             ' http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces'
2428             ' for more information.  [build/namespaces] [4]')
2429         # namespace registration macros are OK.
2430         self.assert_language_rules_check('foo.h', 'namespace {  \\', '')
2431         # named namespaces are OK.
2432         self.assert_language_rules_check('foo.h', 'namespace foo {', '')
2433         self.assert_language_rules_check('foo.h', 'namespace foonamespace {', '')
2434         self.assert_language_rules_check('foo.cpp', 'namespace {', '')
2435         self.assert_language_rules_check('foo.cpp', 'namespace foo {', '')
2436
2437     def test_build_class(self):
2438         # Test that the linter can parse to the end of class definitions,
2439         # and that it will report when it can't.
2440         # Use multi-line linter because it performs the ClassState check.
2441         self.assert_multi_line_lint(
2442             'class Foo {',
2443             'Failed to find complete declaration of class Foo'
2444             '  [build/class] [5]')
2445         # Don't warn on forward declarations of various types.
2446         self.assert_multi_line_lint(
2447             'class Foo;',
2448             '')
2449         self.assert_multi_line_lint(
2450             '''\
2451             struct Foo*
2452                 foo = NewFoo();''',
2453             '')
2454         # Here is an example where the linter gets confused, even though
2455         # the code doesn't violate the style guide.
2456         self.assert_multi_line_lint(
2457             'class Foo\n'
2458             '#ifdef DERIVE_FROM_GOO\n'
2459             '    : public Goo {\n'
2460             '#else\n'
2461             '    : public Hoo {\n'
2462             '#endif\n'
2463             '};',
2464             'Failed to find complete declaration of class Foo'
2465             '  [build/class] [5]')
2466
2467     def test_build_end_comment(self):
2468         # The crosstool compiler we currently use will fail to compile the
2469         # code in this test, so we might consider removing the lint check.
2470         self.assert_lint('#endif Not a comment',
2471                          'Uncommented text after #endif is non-standard.'
2472                          '  Use a comment.'
2473                          '  [build/endif_comment] [5]')
2474
2475     def test_build_forward_decl(self):
2476         # The crosstool compiler we currently use will fail to compile the
2477         # code in this test, so we might consider removing the lint check.
2478         self.assert_lint('class Foo::Goo;',
2479                          'Inner-style forward declarations are invalid.'
2480                          '  Remove this line.'
2481                          '  [build/forward_decl] [5]')
2482
2483     def test_build_header_guard(self):
2484         rules = ('-', '+build/header_guard')
2485
2486         # Old header guard.
2487         self.assert_header_guard('#ifndef Foo_h',
2488             'Use #pragma once instead of #ifndef for header guard.'
2489             '  [build/header_guard] [5]')
2490
2491         # No header guard. Okay, since this could be an ObjC header.
2492         self.assert_header_guard('', '')
2493
2494         # Valid header guard.
2495         self.assert_header_guard('#pragma once', '')
2496
2497     def test_build_printf_format(self):
2498         self.assert_lint(
2499             r'printf("\%%d", value);',
2500             '%, [, (, and { are undefined character escapes.  Unescape them.'
2501             '  [build/printf_format] [3]')
2502
2503         self.assert_lint(
2504             r'snprintf(buffer, sizeof(buffer), "\[%d", value);',
2505             '%, [, (, and { are undefined character escapes.  Unescape them.'
2506             '  [build/printf_format] [3]')
2507
2508         self.assert_lint(
2509             r'fprintf(file, "\(%d", value);',
2510             '%, [, (, and { are undefined character escapes.  Unescape them.'
2511             '  [build/printf_format] [3]')
2512
2513         self.assert_lint(
2514             r'vsnprintf(buffer, sizeof(buffer), "\\\{%d", ap);',
2515             '%, [, (, and { are undefined character escapes.  Unescape them.'
2516             '  [build/printf_format] [3]')
2517
2518         # Don't warn if double-slash precedes the symbol
2519         self.assert_lint(r'printf("\\%%%d", value);',
2520                          '')
2521
2522     def test_runtime_printf_format(self):
2523         self.assert_lint(
2524             r'fprintf(file, "%q", value);',
2525             '%q in format strings is deprecated.  Use %ll instead.'
2526             '  [runtime/printf_format] [3]')
2527
2528         self.assert_lint(
2529             r'aprintf(file, "The number is %12q", value);',
2530             '%q in format strings is deprecated.  Use %ll instead.'
2531             '  [runtime/printf_format] [3]')
2532
2533         self.assert_lint(
2534             r'printf(file, "The number is" "%-12q", value);',
2535             '%q in format strings is deprecated.  Use %ll instead.'
2536             '  [runtime/printf_format] [3]')
2537
2538         self.assert_lint(
2539             r'printf(file, "The number is" "%+12q", value);',
2540             '%q in format strings is deprecated.  Use %ll instead.'
2541             '  [runtime/printf_format] [3]')
2542
2543         self.assert_lint(
2544             r'printf(file, "The number is" "% 12q", value);',
2545             '%q in format strings is deprecated.  Use %ll instead.'
2546             '  [runtime/printf_format] [3]')
2547
2548         self.assert_lint(
2549             r'snprintf(file, "Never mix %d and %1$d parmaeters!", value);',
2550             '%N$ formats are unconventional.  Try rewriting to avoid them.'
2551             '  [runtime/printf_format] [2]')
2552
2553     def assert_lintLogCodeOnError(self, code, expected_message):
2554         # Special assert_lint which logs the input code on error.
2555         result = self.perform_single_line_lint(code, 'foo.cpp')
2556         if result != expected_message:
2557             self.fail('For code: "%s"\nGot: "%s"\nExpected: "%s"'
2558                       % (code, result, expected_message))
2559
2560     def test_build_storage_class(self):
2561         qualifiers = [None, 'const', 'volatile']
2562         signs = [None, 'signed', 'unsigned']
2563         types = ['void', 'char', 'int', 'float', 'double',
2564                  'schar', 'int8', 'uint8', 'int16', 'uint16',
2565                  'int32', 'uint32', 'int64', 'uint64']
2566         storage_classes = ['auto', 'extern', 'register', 'static', 'typedef']
2567
2568         build_storage_class_error_message = (
2569             'Storage class (static, extern, typedef, etc) should be first.'
2570             '  [build/storage_class] [5]')
2571
2572         # Some explicit cases. Legal in C++, deprecated in C99.
2573         self.assert_lint('const int static foo = 5;',
2574                          build_storage_class_error_message)
2575
2576         self.assert_lint('char static foo;',
2577                          build_storage_class_error_message)
2578
2579         self.assert_lint('double const static foo = 2.0;',
2580                          build_storage_class_error_message)
2581
2582         self.assert_lint('uint64 typedef unsignedLongLong;',
2583                          build_storage_class_error_message)
2584
2585         self.assert_lint('int register foo = 0;',
2586                          build_storage_class_error_message)
2587
2588         # Since there are a very large number of possibilities, randomly
2589         # construct declarations.
2590         # Make sure that the declaration is logged if there's an error.
2591         # Seed generator with an integer for absolute reproducibility.
2592         random.seed(25)
2593         for unused_i in range(10):
2594             # Build up random list of non-storage-class declaration specs.
2595             other_decl_specs = [random.choice(qualifiers), random.choice(signs),
2596                                 random.choice(types)]
2597             # remove None
2598             other_decl_specs = filter(lambda x: x is not None, other_decl_specs)
2599
2600             # shuffle
2601             random.shuffle(other_decl_specs)
2602
2603             # insert storage class after the first
2604             storage_class = random.choice(storage_classes)
2605             insertion_point = random.randint(1, len(other_decl_specs))
2606             decl_specs = (other_decl_specs[0:insertion_point]
2607                           + [storage_class]
2608                           + other_decl_specs[insertion_point:])
2609
2610             self.assert_lintLogCodeOnError(
2611                 ' '.join(decl_specs) + ';',
2612                 build_storage_class_error_message)
2613
2614             # but no error if storage class is first
2615             self.assert_lintLogCodeOnError(
2616                 storage_class + ' ' + ' '.join(other_decl_specs),
2617                 '')
2618
2619     def test_legal_copyright(self):
2620         legal_copyright_message = (
2621             'No copyright message found.  '
2622             'You should have a line: "Copyright [year] <Copyright Owner>"'
2623             '  [legal/copyright] [5]')
2624
2625         copyright_line = '// Copyright 2008 Google Inc. All Rights Reserved.'
2626
2627         file_path = 'mydir/googleclient/foo.cpp'
2628
2629         # There should be a copyright message in the first 10 lines
2630         error_collector = ErrorCollector(self.assertTrue)
2631         self.process_file_data(file_path, 'cpp', [], error_collector)
2632         self.assertEqual(
2633             1,
2634             error_collector.result_list().count(legal_copyright_message))
2635
2636         error_collector = ErrorCollector(self.assertTrue)
2637         self.process_file_data(
2638             file_path, 'cpp',
2639             ['' for unused_i in range(10)] + [copyright_line],
2640             error_collector)
2641         self.assertEqual(
2642             1,
2643             error_collector.result_list().count(legal_copyright_message))
2644
2645         # Test that warning isn't issued if Copyright line appears early enough.
2646         error_collector = ErrorCollector(self.assertTrue)
2647         self.process_file_data(file_path, 'cpp', [copyright_line], error_collector)
2648         for message in error_collector.result_list():
2649             if message.find('legal/copyright') != -1:
2650                 self.fail('Unexpected error: %s' % message)
2651
2652         error_collector = ErrorCollector(self.assertTrue)
2653         self.process_file_data(
2654             file_path, 'cpp',
2655             ['' for unused_i in range(9)] + [copyright_line],
2656             error_collector)
2657         for message in error_collector.result_list():
2658             if message.find('legal/copyright') != -1:
2659                 self.fail('Unexpected error: %s' % message)
2660
2661     def test_invalid_increment(self):
2662         self.assert_lint('*count++;',
2663                          'Changing pointer instead of value (or unused value of '
2664                          'operator*).  [runtime/invalid_increment] [5]')
2665
2666     # Enum bitfields are not allowed and should be declared as unsigned integral types.
2667     def test_enum_bitfields(self):
2668         errmsg = ('Please declare enum bitfields as unsigned integral types.  [runtime/enum_bitfields] [5]')
2669
2670         self.assert_lint('AnEnum a : 30;', errmsg)
2671         self.assert_lint('mutable AnEnum a : 14;', errmsg)
2672         self.assert_lint('const AnEnum a : 6;', errmsg)
2673         self.assert_lint('bool a : 1;', '')
2674
2675     # Integral bitfields must be declared with either signed or unsigned keyword.
2676     def test_plain_integral_bitfields(self):
2677         errmsg = ('Please declare integral type bitfields with either signed or unsigned.  [runtime/bitfields] [5]')
2678
2679         self.assert_lint('int a : 30;', errmsg)
2680         self.assert_lint('mutable short a : 14;', errmsg)
2681         self.assert_lint('const char a : 6;', errmsg)
2682         self.assert_lint('long int a : 30;', errmsg)
2683         self.assert_lint('int a = 1 ? 0 : 30;', '')
2684         self.assert_lint('bool a : 1;', '')
2685
2686
2687 class CleansedLinesTest(unittest.TestCase):
2688     def test_init(self):
2689         lines = ['Line 1',
2690                  'Line 2',
2691                  'Line 3 // Comment test',
2692                  'Line 4 "foo"']
2693
2694         clean_lines = cpp_style.CleansedLines(lines)
2695         self.assertEqual(lines, clean_lines.raw_lines)
2696         self.assertEqual(4, clean_lines.num_lines())
2697
2698         self.assertEqual(['Line 1',
2699                            'Line 2',
2700                            'Line 3 ',
2701                            'Line 4 "foo"'],
2702                           clean_lines.lines)
2703
2704         self.assertEqual(['Line 1',
2705                            'Line 2',
2706                            'Line 3 ',
2707                            'Line 4 ""'],
2708                           clean_lines.elided)
2709
2710     def test_init_empty(self):
2711         clean_lines = cpp_style.CleansedLines([])
2712         self.assertEqual([], clean_lines.raw_lines)
2713         self.assertEqual(0, clean_lines.num_lines())
2714
2715     def test_collapse_strings(self):
2716         collapse = cpp_style.CleansedLines.collapse_strings
2717         self.assertEqual('""', collapse('""'))             # ""     (empty)
2718         self.assertEqual('"""', collapse('"""'))           # """    (bad)
2719         self.assertEqual('""', collapse('"xyz"'))          # "xyz"  (string)
2720         self.assertEqual('""', collapse('"\\\""'))         # "\""   (string)
2721         self.assertEqual('""', collapse('"\'"'))           # "'"    (string)
2722         self.assertEqual('"\"', collapse('"\"'))           # "\"    (bad)
2723         self.assertEqual('""', collapse('"\\\\"'))         # "\\"   (string)
2724         self.assertEqual('"', collapse('"\\\\\\"'))        # "\\\"  (bad)
2725         self.assertEqual('""', collapse('"\\\\\\\\"'))     # "\\\\" (string)
2726
2727         self.assertEqual('\'\'', collapse('\'\''))         # ''     (empty)
2728         self.assertEqual('\'\'', collapse('\'a\''))        # 'a'    (char)
2729         self.assertEqual('\'\'', collapse('\'\\\'\''))     # '\''   (char)
2730         self.assertEqual('\'', collapse('\'\\\''))         # '\'    (bad)
2731         self.assertEqual('', collapse('\\012'))            # '\012' (char)
2732         self.assertEqual('', collapse('\\xfF0'))           # '\xfF0' (char)
2733         self.assertEqual('', collapse('\\n'))              # '\n' (char)
2734         self.assertEqual('\#', collapse('\\#'))            # '\#' (bad)
2735
2736         self.assertEqual('StringReplace(body, "", "");',
2737                           collapse('StringReplace(body, "\\\\", "\\\\\\\\");'))
2738         self.assertEqual('\'\' ""',
2739                           collapse('\'"\' "foo"'))
2740
2741
2742 class OrderOfIncludesTest(CppStyleTestBase):
2743     def setUp(self):
2744         self.include_state = cpp_style._IncludeState()
2745
2746         # Cheat os.path.abspath called in FileInfo class.
2747         self.os_path_abspath_orig = os.path.abspath
2748         self.os_path_isfile_orig = os.path.isfile
2749         os.path.abspath = lambda value: value
2750
2751     def tearDown(self):
2752         os.path.abspath = self.os_path_abspath_orig
2753         os.path.isfile = self.os_path_isfile_orig
2754
2755     def test_check_next_include_order__no_config(self):
2756         self.assertEqual('Header file should not contain WebCore config.h.',
2757                          self.include_state.check_next_include_order(cpp_style._CONFIG_HEADER, 'Foo.h', True, True))
2758
2759     def test_check_next_include_order__no_self(self):
2760         self.assertEqual('Header file should not contain itself.',
2761                          self.include_state.check_next_include_order(cpp_style._PRIMARY_HEADER, 'Foo.h', True, True))
2762         # Test actual code to make sure that header types are correctly assigned.
2763         self.assert_language_rules_check('Foo.h',
2764                                          '#include "Foo.h"\n',
2765                                          'Header file should not contain itself. Should be: alphabetically sorted.'
2766                                          '  [build/include_order] [4]')
2767         self.assert_language_rules_check('FooBar.h',
2768                                          '#include "Foo.h"\n',
2769                                          '')
2770
2771     def test_check_next_include_order__likely_then_config(self):
2772         self.assertEqual('Found header this file implements before WebCore config.h.',
2773                          self.include_state.check_next_include_order(cpp_style._PRIMARY_HEADER, 'Foo.cpp', False, True))
2774         self.assertEqual('Found WebCore config.h after a header this file implements.',
2775                          self.include_state.check_next_include_order(cpp_style._CONFIG_HEADER, 'Foo.cpp', False, True))
2776
2777     def test_check_next_include_order__other_then_config(self):
2778         self.assertEqual('Found other header before WebCore config.h.',
2779                          self.include_state.check_next_include_order(cpp_style._OTHER_HEADER, 'Foo.cpp', False, True))
2780         self.assertEqual('Found WebCore config.h after other header.',
2781                          self.include_state.check_next_include_order(cpp_style._CONFIG_HEADER, 'Foo.cpp', False, True))
2782
2783     def test_check_next_include_order__config_then_other_then_likely(self):
2784         self.assertEqual('', self.include_state.check_next_include_order(cpp_style._CONFIG_HEADER, 'Foo.cpp', False, True))
2785         self.assertEqual('Found other header before a header this file implements.',
2786                          self.include_state.check_next_include_order(cpp_style._OTHER_HEADER, 'Foo.cpp', False, True))
2787         self.assertEqual('Found header this file implements after other header.',
2788                          self.include_state.check_next_include_order(cpp_style._PRIMARY_HEADER, 'Foo.cpp', False, True))
2789
2790     def test_check_alphabetical_include_order(self):
2791         self.assert_language_rules_check('foo.h',
2792                                          '#include "a.h"\n'
2793                                          '#include "c.h"\n'
2794                                          '#include "b.h"\n',
2795                                          'Alphabetical sorting problem.  [build/include_order] [4]')
2796
2797         self.assert_language_rules_check('foo.h',
2798                                          '#include "a.h"\n'
2799                                          '#include "b.h"\n'
2800                                          '#include "c.h"\n',
2801                                          '')
2802
2803         self.assert_language_rules_check('foo.h',
2804                                          '#include <assert.h>\n'
2805                                          '#include "bar.h"\n',
2806                                          'Bad include order. Mixing system and custom headers.  [build/include_order] [4]')
2807
2808         self.assert_language_rules_check('foo.h',
2809                                          '#include "bar.h"\n'
2810                                          '#include <assert.h>\n',
2811                                          '')
2812
2813         self.assert_language_rules_check('foo.h',
2814                                          '#include "bar.h"\n'
2815                                          '#include "array.lut.h"\n',
2816                                          '')
2817
2818     def test_check_alphabetical_include_order_errors_reported_for_both_lines(self):
2819         # If one of the two lines of out of order headers are filtered, the error should be
2820         # reported on the other line.
2821         self.assert_language_rules_check('foo.h',
2822                                          '#include "a.h"\n'
2823                                          '#include "c.h"\n'
2824                                          '#include "b.h"\n',
2825                                          'Alphabetical sorting problem.  [build/include_order] [4]',
2826                                          lines_to_check=[2])
2827
2828         self.assert_language_rules_check('foo.h',
2829                                          '#include "a.h"\n'
2830                                          '#include "c.h"\n'
2831                                          '#include "b.h"\n',
2832                                          'Alphabetical sorting problem.  [build/include_order] [4]',
2833                                          lines_to_check=[3])
2834
2835         # If no lines are filtered, the error should be reported only once.
2836         self.assert_language_rules_check('foo.h',
2837                                          '#include "a.h"\n'
2838                                          '#include "c.h"\n'
2839                                          '#include "b.h"\n',
2840                                          'Alphabetical sorting problem.  [build/include_order] [4]')
2841
2842     def test_check_line_break_after_own_header(self):
2843         self.assert_language_rules_check('foo.cpp',
2844                                          '#include "config.h"\n'
2845                                          '#include "foo.h"\n'
2846                                          '#include "bar.h"\n',
2847                                          'You should add a blank line after implementation file\'s own header.  [build/include_order] [4]')
2848
2849         self.assert_language_rules_check('foo.cpp',
2850                                          '#include "config.h"\n'
2851                                          '#include "foo.h"\n'
2852                                          '\n'
2853                                          '#include "bar.h"\n',
2854                                          '')
2855
2856     def test_check_line_break_before_own_header(self):
2857         self.assert_language_rules_check('foo.cpp',
2858                                          '#include "config.h"\n'
2859                                          '\n'
2860                                          '#include "foo.h"\n'
2861                                          '\n'
2862                                          '#include "bar.h"\n',
2863                                          'You should not add a blank line before implementation file\'s own header.  [build/include_order] [4]')
2864
2865         self.assert_language_rules_check('foo.cpp',
2866                                          '#include "config.h"\n'
2867                                          '#include "foo.h"\n'
2868                                          '\n'
2869                                          '#include "bar.h"\n',
2870                                          '')
2871
2872     def test_check_preprocessor_in_include_section(self):
2873         self.assert_language_rules_check('foo.cpp',
2874                                          '#include "config.h"\n'
2875                                          '#include "foo.h"\n'
2876                                          '\n'
2877                                          '#ifdef BAZ\n'
2878                                          '#include "baz.h"\n'
2879                                          '#else\n'
2880                                          '#include "foobar.h"\n'
2881                                          '#endif"\n'
2882                                          '#include "bar.h"\n',  # No flag because previous is in preprocessor section.
2883                                          '')
2884
2885         self.assert_language_rules_check('foo.cpp',
2886                                          '#include "config.h"\n'
2887                                          '#include "foo.h"\n'
2888                                          '\n'
2889                                          '#ifdef BAZ\n'
2890                                          '#include "baz.h"\n'
2891                                          '#endif"\n'
2892                                          '#include "bar.h"\n'
2893                                          '#include "a.h"\n',  # Should still flag this.
2894                                          'Alphabetical sorting problem.  [build/include_order] [4]')
2895
2896         self.assert_language_rules_check('foo.cpp',
2897                                          '#include "config.h"\n'
2898                                          '#include "foo.h"\n'
2899                                          '\n'
2900                                          '#ifdef BAZ\n'
2901                                          '#include "baz.h"\n'
2902                                          '#include "bar.h"\n'  # Should still flag this.
2903                                          '#endif"\n',
2904                                          'Alphabetical sorting problem.  [build/include_order] [4]')
2905
2906         self.assert_language_rules_check('foo.cpp',
2907                                          '#include "config.h"\n'
2908                                          '#include "foo.h"\n'
2909                                          '\n'
2910                                          '#ifdef BAZ\n'
2911                                          '#include "baz.h"\n'
2912                                          '#endif"\n'
2913                                          '#ifdef FOOBAR\n'
2914                                          '#include "foobar.h"\n'
2915                                          '#endif"\n'
2916                                          '#include "bar.h"\n'
2917                                          '#include "a.h"\n',  # Should still flag this.
2918                                          'Alphabetical sorting problem.  [build/include_order] [4]')
2919
2920         # Check that after an already included error, the sorting rules still work.
2921         self.assert_language_rules_check('foo.cpp',
2922                                          '#include "config.h"\n'
2923                                          '#include "foo.h"\n'
2924                                          '\n'
2925                                          '#include "foo.h"\n'
2926                                          '#include "g.h"\n',
2927                                          '"foo.h" already included at foo.cpp:2  [build/include] [4]')
2928
2929     def test_primary_header(self):
2930         # File with non-existing primary header should not produce errors.
2931         self.assert_language_rules_check('foo.cpp',
2932                                          '#include "config.h"\n'
2933                                          '\n'
2934                                          '#include "bar.h"\n',
2935                                          '')
2936         # Pretend that header files exist.
2937         os.path.isfile = lambda filename: True
2938         # Missing include for existing primary header -> error.
2939         self.assert_language_rules_check('foo.cpp',
2940                                          '#include "config.h"\n'
2941                                          '\n'
2942                                          '#include "bar.h"\n',
2943                                          'Found other header before a header this file implements. '
2944                                          'Should be: config.h, primary header, blank line, and then '
2945                                          'alphabetically sorted.  [build/include_order] [4]')
2946         # *SoftLink.cpp files should not include their headers -> no error.
2947         self.assert_language_rules_check('FooSoftLink.cpp',
2948                                          '#include "config.h"\n'
2949                                          '\n'
2950                                          '#include <wtf/SoftLinking.h>\n',
2951                                          '')
2952         # Having include for existing primary header -> no error.
2953         self.assert_language_rules_check('foo.cpp',
2954                                          '#include "config.h"\n'
2955                                          '#include "foo.h"\n'
2956                                          '\n'
2957                                          '#include "bar.h"\n',
2958                                          '')
2959
2960         os.path.isfile = self.os_path_isfile_orig
2961
2962     def test_public_primary_header(self):
2963         # System header is not considered a primary header.
2964         self.assert_language_rules_check('foo.cpp',
2965                                          '#include "config.h"\n'
2966                                          '#include <other/foo.h>\n'
2967                                          '\n'
2968                                          '#include "a.h"\n',
2969                                          'Bad include order. Mixing system and custom headers.  [build/include_order] [4]')
2970
2971         # ...except that it starts with public/.
2972         self.assert_language_rules_check('foo.cpp',
2973                                          '#include "config.h"\n'
2974                                          '#include <public/foo.h>\n'
2975                                          '\n'
2976                                          '#include "a.h"\n',
2977                                          '')
2978
2979         # Even if it starts with public/ its base part must match with the source file name.
2980         self.assert_language_rules_check('foo.cpp',
2981                                          '#include "config.h"\n'
2982                                          '#include <public/foop.h>\n'
2983                                          '\n'
2984                                          '#include "a.h"\n',
2985                                          'Bad include order. Mixing system and custom headers.  [build/include_order] [4]')
2986
2987         # *SoftLink.h header should never be included in other header files.
2988         self.assert_language_rules_check('foo.h',
2989                                          '#include "Bar.h"\n'
2990                                          '\n'
2991                                          '#include "FrameworkSoftLink.h"\n',
2992                                          '*SoftLink.h header should never be included in a header.  [build/include_order] [4]')
2993
2994         # Complain about *SoftLink.h headers that are not last.
2995         self.assert_language_rules_check('Foo.cpp',
2996                                          '#include "config.h"\n'
2997                                          '#include "Foo.h"\n'
2998                                          '\n'
2999                                          '#include "ALocalHeader.h"\n'
3000                                          '#include "FrameworkSoftLink.h"\n'
3001                                          '#include <Framework/Bar.h>\n',
3002                                          '*SoftLink.h header should be included after all other headers.  [build/include_order] [4]')
3003
3004         self.assert_language_rules_check('Foo.cpp',
3005                                          '#include "config.h"\n'
3006                                          '#include "Foo.h"\n'
3007                                          '\n'
3008                                          '#include "ALocalHeader.h"\n'
3009                                          '#include <Framework/Bar.h>\n'
3010                                          '\n'
3011                                          '#include "FrameworkSoftLink.h"\n'
3012                                          '\n'
3013                                          '#if PLATFORM(FOO)\n'
3014                                          '#include "FooPlatform.h"\n'
3015                                          '#endif // PLATFORM(FOO)\n',
3016                                          '*SoftLink.h header should be included after all other headers.  [build/include_order] [4]')
3017
3018         # Don't complain about *SoftLink.h headers that are last.
3019         self.assert_language_rules_check('Foo.cpp',
3020                                          '#include "config.h"\n'
3021                                          '#include "Foo.h"\n'
3022                                          '\n'
3023                                          '#include "ALocalHeader.h"\n'
3024                                          '#include <Framework/Bar.h>\n'
3025                                          '\n'
3026                                          '#if PLATFORM(FOO)\n'
3027                                          '#include "FooPlatform.h"\n'
3028                                          '#endif // PLATFORM(FOO)\n'
3029                                          '\n'
3030                                          '#include "FrameworkSoftLink.h"\n',
3031                                          '')
3032
3033         self.assert_language_rules_check('Foo.cpp',
3034                                          '#include "config.h"\n'
3035                                          '#include "Foo.h"\n'
3036                                          '\n'
3037                                          '#include "ALocalHeader.h"\n'
3038                                          '#include <Framework/Bar.h>\n'
3039                                          '\n'
3040                                          '#if PLATFORM(FOO)\n'
3041                                          '#include "FooPlatform.h"\n'
3042                                          '#endif // PLATFORM(FOO)\n'
3043                                          '\n'
3044                                          '#include "FrameworkASoftLink.h"\n'
3045                                          '#include "FrameworkBSoftLink.h"\n',
3046                                          '')
3047
3048         self.assert_language_rules_check('Foo.cpp',
3049                                          '#include "config.h"\n'
3050                                          '#include <Framework/Bar.h>\n'
3051                                          '\n'
3052                                          '#include "FrameworkSoftLink.h"\n',
3053                                          '')
3054
3055     def test_check_wtf_includes(self):
3056         self.assert_language_rules_check('foo.cpp',
3057                                          '#include "config.h"\n'
3058                                          '#include "foo.h"\n'
3059                                          '\n'
3060                                          '#include <wtf/Assertions.h>\n',
3061                                          '')
3062         self.assert_language_rules_check('foo.cpp',
3063                                          '#include "config.h"\n'
3064                                          '#include "foo.h"\n'
3065                                          '\n'
3066                                          '#include "wtf/Assertions.h"\n',
3067                                          'wtf includes should be <wtf/file.h> instead of "wtf/file.h".'
3068                                          '  [build/include] [4]')
3069
3070     def test_classify_include(self):
3071         classify_include = cpp_style._classify_include
3072         include_state = cpp_style._IncludeState()
3073         self.assertEqual(cpp_style._CONFIG_HEADER,
3074                          classify_include('foo/foo.cpp',
3075                                           'config.h',
3076                                           False, include_state))
3077         self.assertEqual(cpp_style._PRIMARY_HEADER,
3078                          classify_include('foo/internal/foo.cpp',
3079                                           'foo/public/foo.h',
3080                                           False, include_state))
3081         self.assertEqual(cpp_style._PRIMARY_HEADER,
3082                          classify_include('foo/internal/foo.cpp',
3083                                           'foo/other/public/foo.h',
3084                                           False, include_state))
3085         self.assertEqual(cpp_style._OTHER_HEADER,
3086                          classify_include('foo/internal/foo.cpp',
3087                                           'foo/other/public/foop.h',
3088                                           False, include_state))
3089         self.assertEqual(cpp_style._OTHER_HEADER,
3090                          classify_include('foo/foo.cpp',
3091                                           'string',
3092                                           True, include_state))
3093         self.assertEqual(cpp_style._PRIMARY_HEADER,
3094                          classify_include('fooCustom.cpp',
3095                                           'foo.h',
3096                                           False, include_state))
3097         self.assertEqual(cpp_style._PRIMARY_HEADER,
3098                          classify_include('PrefixFooCustom.cpp',
3099                                           'Foo.h',
3100                                           False, include_state))
3101         # <public/foo.h> must be considered as primary even if is_system is True.
3102         self.assertEqual(cpp_style._PRIMARY_HEADER,
3103                          classify_include('foo/foo.cpp',
3104                                           'public/foo.h',
3105                                           True, include_state))
3106         self.assertEqual(cpp_style._OTHER_HEADER,
3107                          classify_include('foo.cpp',
3108                                           'foo.h',
3109                                           True, include_state))
3110         self.assertEqual(cpp_style._OTHER_HEADER,
3111                          classify_include('foo.cpp',
3112                                           'public/foop.h',
3113                                           True, include_state))
3114         self.assertEqual(cpp_style._SOFT_LINK_HEADER,
3115                          classify_include('foo.cpp',
3116                                           'BarSoftLink.h',
3117                                           False, include_state))
3118         # Tricky example where both includes might be classified as primary.
3119         self.assert_language_rules_check('ScrollbarThemeWince.cpp',
3120                                          '#include "config.h"\n'
3121                                          '#include "ScrollbarThemeWince.h"\n'
3122                                          '\n'
3123                                          '#include "Scrollbar.h"\n',
3124                                          '')
3125         self.assert_language_rules_check('ScrollbarThemeWince.cpp',
3126                                          '#include "config.h"\n'
3127                                          '#include "Scrollbar.h"\n'
3128                                          '\n'
3129                                          '#include "ScrollbarThemeWince.h"\n',
3130                                          'Found header this file implements after a header this file implements.'
3131                                          ' Should be: config.h, primary header, blank line, and then alphabetically sorted.'
3132                                          '  [build/include_order] [4]')
3133         self.assert_language_rules_check('ResourceHandleWin.cpp',
3134                                          '#include "config.h"\n'
3135                                          '#include "ResourceHandle.h"\n'
3136                                          '\n'
3137                                          '#include "ResourceHandleWin.h"\n',
3138                                          '')
3139
3140     def test_try_drop_common_suffixes(self):
3141         self.assertEqual('foo/foo', cpp_style._drop_common_suffixes('foo/foo-inl.h'))
3142         self.assertEqual('foo/bar/foo',
3143                          cpp_style._drop_common_suffixes('foo/bar/foo_inl.h'))
3144         self.assertEqual('foo/foo', cpp_style._drop_common_suffixes('foo/foo.cpp'))
3145         self.assertEqual('foo/foo_unusualinternal',
3146                          cpp_style._drop_common_suffixes('foo/foo_unusualinternal.h'))
3147         self.assertEqual('',
3148                          cpp_style._drop_common_suffixes('_test.cpp'))
3149         self.assertEqual('test',
3150                          cpp_style._drop_common_suffixes('test.cpp'))
3151
3152
3153 class CheckForFunctionLengthsTest(CppStyleTestBase):
3154     def setUp(self):
3155         # Reducing these thresholds for the tests speeds up tests significantly.
3156         self.old_normal_trigger = cpp_style._FunctionState._NORMAL_TRIGGER
3157         self.old_test_trigger = cpp_style._FunctionState._TEST_TRIGGER
3158
3159         cpp_style._FunctionState._NORMAL_TRIGGER = 10
3160         cpp_style._FunctionState._TEST_TRIGGER = 25
3161
3162     def tearDown(self):
3163         cpp_style._FunctionState._NORMAL_TRIGGER = self.old_normal_trigger
3164         cpp_style._FunctionState._TEST_TRIGGER = self.old_test_trigger
3165
3166     # FIXME: Eliminate the need for this function.
3167     def set_min_confidence(self, min_confidence):
3168         """Set new test confidence and return old test confidence."""
3169         old_min_confidence = self.min_confidence
3170         self.min_confidence = min_confidence
3171         return old_min_confidence
3172
3173     def assert_function_lengths_check(self, code, expected_message):
3174         """Check warnings for long function bodies are as expected.
3175
3176         Args:
3177           code: C++ source code expected to generate a warning message.
3178           expected_message: Message expected to be generated by the C++ code.
3179         """
3180         self.assertEqual(expected_message,
3181                           self.perform_function_lengths_check(code))
3182
3183     def trigger_lines(self, error_level):
3184         """Return number of lines needed to trigger a function length warning.
3185
3186         Args: