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