OLD | NEW |
1 #!/usr/bin/env python | 1 #!/usr/bin/env python |
2 # | 2 # |
3 # Copyright (c) 2009 Google Inc. All rights reserved. | 3 # Copyright (c) 2009 Google Inc. All rights reserved. |
4 # | 4 # |
5 # Redistribution and use in source and binary forms, with or without | 5 # Redistribution and use in source and binary forms, with or without |
6 # modification, are permitted provided that the following conditions are | 6 # modification, are permitted provided that the following conditions are |
7 # met: | 7 # met: |
8 # | 8 # |
9 # * Redistributions of source code must retain the above copyright | 9 # * Redistributions of source code must retain the above copyright |
10 # notice, this list of conditions and the following disclaimer. | 10 # notice, this list of conditions and the following disclaimer. |
(...skipping 35 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
46 # - Check accessors that return non-const pointer member vars are | 46 # - Check accessors that return non-const pointer member vars are |
47 # *not* declared const | 47 # *not* declared const |
48 # - Check for using public includes for testing | 48 # - Check for using public includes for testing |
49 # - Check for spaces between brackets in one-line inline method | 49 # - Check for spaces between brackets in one-line inline method |
50 # - Check for no assert() | 50 # - Check for no assert() |
51 # - Check for spaces surrounding operators | 51 # - Check for spaces surrounding operators |
52 # - Check for 0 in pointer context (should be NULL) | 52 # - Check for 0 in pointer context (should be NULL) |
53 # - Check for 0 in char context (should be '\0') | 53 # - Check for 0 in char context (should be '\0') |
54 # - Check for camel-case method name conventions for methods | 54 # - Check for camel-case method name conventions for methods |
55 # that are not simple inline getters and setters | 55 # that are not simple inline getters and setters |
56 # - Check that base classes have virtual destructors | |
57 # put " // namespace" after } that closes a namespace, with | |
58 # namespace's name after 'namespace' if it is named. | |
59 # - Do not indent namespace contents | 56 # - Do not indent namespace contents |
60 # - Avoid inlining non-trivial constructors in header files | 57 # - Avoid inlining non-trivial constructors in header files |
61 # include base/basictypes.h if DISALLOW_EVIL_CONSTRUCTORS is used | |
62 # - Check for old-school (void) cast for call-sites of functions | 58 # - Check for old-school (void) cast for call-sites of functions |
63 # ignored return value | 59 # ignored return value |
64 # - Check gUnit usage of anonymous namespace | 60 # - Check gUnit usage of anonymous namespace |
65 # - Check for class declaration order (typedefs, consts, enums, | 61 # - Check for class declaration order (typedefs, consts, enums, |
66 # ctor(s?), dtor, friend declarations, methods, member vars) | 62 # ctor(s?), dtor, friend declarations, methods, member vars) |
67 # | 63 # |
68 | 64 |
69 """Does google-lint on c++ files. | 65 """Does google-lint on c++ files. |
70 | 66 |
71 The goal of this script is to identify places in the code that *may* | 67 The goal of this script is to identify places in the code that *may* |
72 be in non-compliance with google style. It does not attempt to fix | 68 be in non-compliance with google style. It does not attempt to fix |
73 up these problems -- the point is to educate. It does also not | 69 up these problems -- the point is to educate. It does also not |
74 attempt to find all problems, or to ensure that everything it does | 70 attempt to find all problems, or to ensure that everything it does |
75 find is legitimately a problem. | 71 find is legitimately a problem. |
76 | 72 |
77 In particular, we can get very confused by /* and // inside strings! | 73 In particular, we can get very confused by /* and // inside strings! |
78 We do a small hack, which is to ignore //'s with "'s after them on the | 74 We do a small hack, which is to ignore //'s with "'s after them on the |
79 same line, but it is far from perfect (in either direction). | 75 same line, but it is far from perfect (in either direction). |
80 """ | 76 """ |
81 | 77 |
82 import codecs | 78 import codecs |
| 79 import copy |
83 import getopt | 80 import getopt |
84 import math # for log | 81 import math # for log |
85 import os | 82 import os |
86 import re | 83 import re |
87 import sre_compile | 84 import sre_compile |
88 import string | 85 import string |
89 import sys | 86 import sys |
90 import unicodedata | 87 import unicodedata |
91 | 88 |
92 | 89 |
(...skipping 39 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
132 | 129 |
133 To see a list of all the categories used in cpplint, pass no arg: | 130 To see a list of all the categories used in cpplint, pass no arg: |
134 --filter= | 131 --filter= |
135 | 132 |
136 counting=total|toplevel|detailed | 133 counting=total|toplevel|detailed |
137 The total number of errors found is always printed. If | 134 The total number of errors found is always printed. If |
138 'toplevel' is provided, then the count of errors in each of | 135 'toplevel' is provided, then the count of errors in each of |
139 the top-level categories like 'build' and 'whitespace' will | 136 the top-level categories like 'build' and 'whitespace' will |
140 also be printed. If 'detailed' is provided, then a count | 137 also be printed. If 'detailed' is provided, then a count |
141 is provided for each category like 'build/class'. | 138 is provided for each category like 'build/class'. |
| 139 |
| 140 root=subdir |
| 141 The root directory used for deriving header guard CPP variable. |
| 142 By default, the header guard CPP variable is calculated as the relative |
| 143 path to the directory that contains .git, .hg, or .svn. When this flag |
| 144 is specified, the relative path is calculated from the specified |
| 145 directory. If the specified directory does not exist, this flag is |
| 146 ignored. |
| 147 |
| 148 Examples: |
| 149 Assuing that src/.git exists, the header guard CPP variables for |
| 150 src/chrome/browser/ui/browser.h are: |
| 151 |
| 152 No flag => CHROME_BROWSER_UI_BROWSER_H_ |
| 153 --root=chrome => BROWSER_UI_BROWSER_H_ |
| 154 --root=chrome/browser => UI_BROWSER_H_ |
142 """ | 155 """ |
143 | 156 |
144 # We categorize each error message we print. Here are the categories. | 157 # We categorize each error message we print. Here are the categories. |
145 # We want an explicit list so we can list them all in cpplint --filter=. | 158 # We want an explicit list so we can list them all in cpplint --filter=. |
146 # If you add a new error message with a new category, add it to the list | 159 # If you add a new error message with a new category, add it to the list |
147 # here! cpplint_unittest.py should tell you if you forget to do this. | 160 # here! cpplint_unittest.py should tell you if you forget to do this. |
148 # \ used for clearer layout -- pylint: disable-msg=C6013 | 161 # \ used for clearer layout -- pylint: disable-msg=C6013 |
149 _ERROR_CATEGORIES = [ | 162 _ERROR_CATEGORIES = [ |
150 'build/class', | 163 'build/class', |
151 'build/deprecated', | 164 'build/deprecated', |
152 'build/endif_comment', | 165 'build/endif_comment', |
153 'build/explicit_make_pair', | 166 'build/explicit_make_pair', |
154 'build/forward_decl', | 167 'build/forward_decl', |
155 'build/header_guard', | 168 'build/header_guard', |
156 'build/include', | 169 'build/include', |
157 'build/include_alpha', | 170 'build/include_alpha', |
158 'build/include_order', | 171 'build/include_order', |
159 'build/include_what_you_use', | 172 'build/include_what_you_use', |
160 'build/namespaces', | 173 'build/namespaces', |
161 'build/printf_format', | 174 'build/printf_format', |
162 'build/storage_class', | 175 'build/storage_class', |
163 'legal/copyright', | 176 'legal/copyright', |
| 177 'readability/alt_tokens', |
164 'readability/braces', | 178 'readability/braces', |
165 'readability/casting', | 179 'readability/casting', |
166 'readability/check', | 180 'readability/check', |
167 'readability/constructors', | 181 'readability/constructors', |
168 'readability/fn_size', | 182 'readability/fn_size', |
169 'readability/function', | 183 'readability/function', |
170 'readability/multiline_comment', | 184 'readability/multiline_comment', |
171 'readability/multiline_string', | 185 'readability/multiline_string', |
| 186 'readability/namespace', |
172 'readability/nolint', | 187 'readability/nolint', |
173 'readability/streams', | 188 'readability/streams', |
174 'readability/todo', | 189 'readability/todo', |
175 'readability/utf8', | 190 'readability/utf8', |
176 'runtime/arrays', | 191 'runtime/arrays', |
177 'runtime/casting', | 192 'runtime/casting', |
178 'runtime/explicit', | 193 'runtime/explicit', |
179 'runtime/int', | 194 'runtime/int', |
180 'runtime/init', | 195 'runtime/init', |
181 'runtime/invalid_increment', | 196 'runtime/invalid_increment', |
182 'runtime/member_string_references', | 197 'runtime/member_string_references', |
183 'runtime/memset', | 198 'runtime/memset', |
184 'runtime/operator', | 199 'runtime/operator', |
185 'runtime/printf', | 200 'runtime/printf', |
186 'runtime/printf_format', | 201 'runtime/printf_format', |
187 'runtime/references', | 202 'runtime/references', |
188 'runtime/rtti', | 203 'runtime/rtti', |
189 'runtime/sizeof', | 204 'runtime/sizeof', |
190 'runtime/string', | 205 'runtime/string', |
191 'runtime/threadsafe_fn', | 206 'runtime/threadsafe_fn', |
192 'runtime/virtual', | |
193 'whitespace/blank_line', | 207 'whitespace/blank_line', |
194 'whitespace/braces', | 208 'whitespace/braces', |
195 'whitespace/comma', | 209 'whitespace/comma', |
196 'whitespace/comments', | 210 'whitespace/comments', |
| 211 'whitespace/empty_loop_body', |
197 'whitespace/end_of_line', | 212 'whitespace/end_of_line', |
198 'whitespace/ending_newline', | 213 'whitespace/ending_newline', |
| 214 'whitespace/forcolon', |
199 'whitespace/indent', | 215 'whitespace/indent', |
200 'whitespace/labels', | 216 'whitespace/labels', |
201 'whitespace/line_length', | 217 'whitespace/line_length', |
202 'whitespace/newline', | 218 'whitespace/newline', |
203 'whitespace/operators', | 219 'whitespace/operators', |
204 'whitespace/parens', | 220 'whitespace/parens', |
205 'whitespace/semicolon', | 221 'whitespace/semicolon', |
206 'whitespace/tab', | 222 'whitespace/tab', |
207 'whitespace/todo' | 223 'whitespace/todo' |
208 ] | 224 ] |
(...skipping 62 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
271 _CHECK_REPLACEMENT['ASSERT_TRUE_M'][op] = 'ASSERT_%s_M' % replacement | 287 _CHECK_REPLACEMENT['ASSERT_TRUE_M'][op] = 'ASSERT_%s_M' % replacement |
272 | 288 |
273 for op, inv_replacement in [('==', 'NE'), ('!=', 'EQ'), | 289 for op, inv_replacement in [('==', 'NE'), ('!=', 'EQ'), |
274 ('>=', 'LT'), ('>', 'LE'), | 290 ('>=', 'LT'), ('>', 'LE'), |
275 ('<=', 'GT'), ('<', 'GE')]: | 291 ('<=', 'GT'), ('<', 'GE')]: |
276 _CHECK_REPLACEMENT['EXPECT_FALSE'][op] = 'EXPECT_%s' % inv_replacement | 292 _CHECK_REPLACEMENT['EXPECT_FALSE'][op] = 'EXPECT_%s' % inv_replacement |
277 _CHECK_REPLACEMENT['ASSERT_FALSE'][op] = 'ASSERT_%s' % inv_replacement | 293 _CHECK_REPLACEMENT['ASSERT_FALSE'][op] = 'ASSERT_%s' % inv_replacement |
278 _CHECK_REPLACEMENT['EXPECT_FALSE_M'][op] = 'EXPECT_%s_M' % inv_replacement | 294 _CHECK_REPLACEMENT['EXPECT_FALSE_M'][op] = 'EXPECT_%s_M' % inv_replacement |
279 _CHECK_REPLACEMENT['ASSERT_FALSE_M'][op] = 'ASSERT_%s_M' % inv_replacement | 295 _CHECK_REPLACEMENT['ASSERT_FALSE_M'][op] = 'ASSERT_%s_M' % inv_replacement |
280 | 296 |
| 297 # Alternative tokens and their replacements. For full list, see section 2.5 |
| 298 # Alternative tokens [lex.digraph] in the C++ standard. |
| 299 # |
| 300 # Digraphs (such as '%:') are not included here since it's a mess to |
| 301 # match those on a word boundary. |
| 302 _ALT_TOKEN_REPLACEMENT = { |
| 303 'and': '&&', |
| 304 'bitor': '|', |
| 305 'or': '||', |
| 306 'xor': '^', |
| 307 'compl': '~', |
| 308 'bitand': '&', |
| 309 'and_eq': '&=', |
| 310 'or_eq': '|=', |
| 311 'xor_eq': '^=', |
| 312 'not': '!', |
| 313 'not_eq': '!=' |
| 314 } |
| 315 |
| 316 # Compile regular expression that matches all the above keywords. The "[ =()]" |
| 317 # bit is meant to avoid matching these keywords outside of boolean expressions. |
| 318 # |
| 319 # False positives include C-style multi-line comments (http://go/nsiut ) |
| 320 # and multi-line strings (http://go/beujw ), but those have always been |
| 321 # troublesome for cpplint. |
| 322 _ALT_TOKEN_REPLACEMENT_PATTERN = re.compile( |
| 323 r'[ =()](' + ('|'.join(_ALT_TOKEN_REPLACEMENT.keys())) + r')(?=[ (]|$)') |
| 324 |
281 | 325 |
282 # These constants define types of headers for use with | 326 # These constants define types of headers for use with |
283 # _IncludeState.CheckNextIncludeOrder(). | 327 # _IncludeState.CheckNextIncludeOrder(). |
284 _C_SYS_HEADER = 1 | 328 _C_SYS_HEADER = 1 |
285 _CPP_SYS_HEADER = 2 | 329 _CPP_SYS_HEADER = 2 |
286 _LIKELY_MY_HEADER = 3 | 330 _LIKELY_MY_HEADER = 3 |
287 _POSSIBLE_MY_HEADER = 4 | 331 _POSSIBLE_MY_HEADER = 4 |
288 _OTHER_HEADER = 5 | 332 _OTHER_HEADER = 5 |
289 | 333 |
| 334 # These constants define the current inline assembly state |
| 335 _NO_ASM = 0 # Outside of inline assembly block |
| 336 _INSIDE_ASM = 1 # Inside inline assembly block |
| 337 _END_ASM = 2 # Last line of inline assembly block |
| 338 _BLOCK_ASM = 3 # The whole block is an inline assembly block |
| 339 |
| 340 # Match start of assembly blocks |
| 341 _MATCH_ASM = re.compile(r'^\s*(?:asm|_asm|__asm|__asm__)' |
| 342 r'(?:\s+(volatile|__volatile__))?' |
| 343 r'\s*[{(]') |
| 344 |
290 | 345 |
291 _regexp_compile_cache = {} | 346 _regexp_compile_cache = {} |
292 | 347 |
293 # Finds occurrences of NOLINT or NOLINT(...). | 348 # Finds occurrences of NOLINT or NOLINT(...). |
294 _RE_SUPPRESSION = re.compile(r'\bNOLINT\b(\([^)]*\))?') | 349 _RE_SUPPRESSION = re.compile(r'\bNOLINT\b(\([^)]*\))?') |
295 | 350 |
296 # {str, set(int)}: a map from error categories to sets of linenumbers | 351 # {str, set(int)}: a map from error categories to sets of linenumbers |
297 # on which those errors are expected and should be suppressed. | 352 # on which those errors are expected and should be suppressed. |
298 _error_suppressions = {} | 353 _error_suppressions = {} |
299 | 354 |
| 355 # The root directory used for deriving header guard CPP variable. |
| 356 # This is set by --root flag. |
| 357 _root = None |
| 358 |
300 def ParseNolintSuppressions(filename, raw_line, linenum, error): | 359 def ParseNolintSuppressions(filename, raw_line, linenum, error): |
301 """Updates the global list of error-suppressions. | 360 """Updates the global list of error-suppressions. |
302 | 361 |
303 Parses any NOLINT comments on the current line, updating the global | 362 Parses any NOLINT comments on the current line, updating the global |
304 error_suppressions store. Reports an error if the NOLINT comment | 363 error_suppressions store. Reports an error if the NOLINT comment |
305 was malformed. | 364 was malformed. |
306 | 365 |
307 Args: | 366 Args: |
308 filename: str, the name of the input file. | 367 filename: str, the name of the input file. |
309 raw_line: str, the line of input text, with comments. | 368 raw_line: str, the line of input text, with comments. |
(...skipping 499 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
809 confidence: A number from 1-5 representing a confidence score for | 868 confidence: A number from 1-5 representing a confidence score for |
810 the error, with 5 meaning that we are certain of the problem, | 869 the error, with 5 meaning that we are certain of the problem, |
811 and 1 meaning that it could be a legitimate construct. | 870 and 1 meaning that it could be a legitimate construct. |
812 message: The error message. | 871 message: The error message. |
813 """ | 872 """ |
814 if _ShouldPrintError(category, confidence, linenum): | 873 if _ShouldPrintError(category, confidence, linenum): |
815 _cpplint_state.IncrementErrorCount(category) | 874 _cpplint_state.IncrementErrorCount(category) |
816 if _cpplint_state.output_format == 'vs7': | 875 if _cpplint_state.output_format == 'vs7': |
817 sys.stderr.write('%s(%s): %s [%s] [%d]\n' % ( | 876 sys.stderr.write('%s(%s): %s [%s] [%d]\n' % ( |
818 filename, linenum, message, category, confidence)) | 877 filename, linenum, message, category, confidence)) |
| 878 elif _cpplint_state.output_format == 'eclipse': |
| 879 sys.stderr.write('%s:%s: warning: %s [%s] [%d]\n' % ( |
| 880 filename, linenum, message, category, confidence)) |
819 else: | 881 else: |
820 sys.stderr.write('%s:%s: %s [%s] [%d]\n' % ( | 882 sys.stderr.write('%s:%s: %s [%s] [%d]\n' % ( |
821 filename, linenum, message, category, confidence)) | 883 filename, linenum, message, category, confidence)) |
822 | 884 |
823 | 885 |
824 # Matches standard C++ escape esequences per 2.13.2.3 of the C++ standard. | 886 # Matches standard C++ escape esequences per 2.13.2.3 of the C++ standard. |
825 _RE_PATTERN_CLEANSE_LINE_ESCAPES = re.compile( | 887 _RE_PATTERN_CLEANSE_LINE_ESCAPES = re.compile( |
826 r'\\([abfnrtv?"\\\']|\d+|x[0-9a-fA-F]+)') | 888 r'\\([abfnrtv?"\\\']|\d+|x[0-9a-fA-F]+)') |
827 # Matches strings. Escape codes should already be removed by ESCAPES. | 889 # Matches strings. Escape codes should already be removed by ESCAPES. |
828 _RE_PATTERN_CLEANSE_LINE_DOUBLE_QUOTES = re.compile(r'"[^"]*"') | 890 _RE_PATTERN_CLEANSE_LINE_DOUBLE_QUOTES = re.compile(r'"[^"]*"') |
(...skipping 89 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
918 line = line[:commentpos].rstrip() | 980 line = line[:commentpos].rstrip() |
919 # get rid of /* ... */ | 981 # get rid of /* ... */ |
920 return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line) | 982 return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line) |
921 | 983 |
922 | 984 |
923 class CleansedLines(object): | 985 class CleansedLines(object): |
924 """Holds 3 copies of all lines with different preprocessing applied to them. | 986 """Holds 3 copies of all lines with different preprocessing applied to them. |
925 | 987 |
926 1) elided member contains lines without strings and comments, | 988 1) elided member contains lines without strings and comments, |
927 2) lines member contains lines without comments, and | 989 2) lines member contains lines without comments, and |
928 3) raw member contains all the lines without processing. | 990 3) raw_lines member contains all the lines without processing. |
929 All these three members are of <type 'list'>, and of the same length. | 991 All these three members are of <type 'list'>, and of the same length. |
930 """ | 992 """ |
931 | 993 |
932 def __init__(self, lines): | 994 def __init__(self, lines): |
933 self.elided = [] | 995 self.elided = [] |
934 self.lines = [] | 996 self.lines = [] |
935 self.raw_lines = lines | 997 self.raw_lines = lines |
936 self.num_lines = len(lines) | 998 self.num_lines = len(lines) |
937 for linenum in range(len(lines)): | 999 for linenum in range(len(lines)): |
938 self.lines.append(CleanseComments(lines[linenum])) | 1000 self.lines.append(CleanseComments(lines[linenum])) |
(...skipping 19 matching lines...) Expand all Loading... |
958 if not _RE_PATTERN_INCLUDE.match(elided): | 1020 if not _RE_PATTERN_INCLUDE.match(elided): |
959 # Remove escaped characters first to make quote/single quote collapsing | 1021 # Remove escaped characters first to make quote/single quote collapsing |
960 # basic. Things that look like escaped characters shouldn't occur | 1022 # basic. Things that look like escaped characters shouldn't occur |
961 # outside of strings and chars. | 1023 # outside of strings and chars. |
962 elided = _RE_PATTERN_CLEANSE_LINE_ESCAPES.sub('', elided) | 1024 elided = _RE_PATTERN_CLEANSE_LINE_ESCAPES.sub('', elided) |
963 elided = _RE_PATTERN_CLEANSE_LINE_SINGLE_QUOTES.sub("''", elided) | 1025 elided = _RE_PATTERN_CLEANSE_LINE_SINGLE_QUOTES.sub("''", elided) |
964 elided = _RE_PATTERN_CLEANSE_LINE_DOUBLE_QUOTES.sub('""', elided) | 1026 elided = _RE_PATTERN_CLEANSE_LINE_DOUBLE_QUOTES.sub('""', elided) |
965 return elided | 1027 return elided |
966 | 1028 |
967 | 1029 |
| 1030 def FindEndOfExpressionInLine(line, startpos, depth, startchar, endchar): |
| 1031 """Find the position just after the matching endchar. |
| 1032 |
| 1033 Args: |
| 1034 line: a CleansedLines line. |
| 1035 startpos: start searching at this position. |
| 1036 depth: nesting level at startpos. |
| 1037 startchar: expression opening character. |
| 1038 endchar: expression closing character. |
| 1039 |
| 1040 Returns: |
| 1041 Index just after endchar. |
| 1042 """ |
| 1043 for i in xrange(startpos, len(line)): |
| 1044 if line[i] == startchar: |
| 1045 depth += 1 |
| 1046 elif line[i] == endchar: |
| 1047 depth -= 1 |
| 1048 if depth == 0: |
| 1049 return i + 1 |
| 1050 return -1 |
| 1051 |
| 1052 |
968 def CloseExpression(clean_lines, linenum, pos): | 1053 def CloseExpression(clean_lines, linenum, pos): |
969 """If input points to ( or { or [, finds the position that closes it. | 1054 """If input points to ( or { or [, finds the position that closes it. |
970 | 1055 |
971 If lines[linenum][pos] points to a '(' or '{' or '[', finds the | 1056 If lines[linenum][pos] points to a '(' or '{' or '[', finds the |
972 linenum/pos that correspond to the closing of the expression. | 1057 linenum/pos that correspond to the closing of the expression. |
973 | 1058 |
974 Args: | 1059 Args: |
975 clean_lines: A CleansedLines instance containing the file. | 1060 clean_lines: A CleansedLines instance containing the file. |
976 linenum: The number of the line to check. | 1061 linenum: The number of the line to check. |
977 pos: A position on the line. | 1062 pos: A position on the line. |
978 | 1063 |
979 Returns: | 1064 Returns: |
980 A tuple (line, linenum, pos) pointer *past* the closing brace, or | 1065 A tuple (line, linenum, pos) pointer *past* the closing brace, or |
981 (line, len(lines), -1) if we never find a close. Note we ignore | 1066 (line, len(lines), -1) if we never find a close. Note we ignore |
982 strings and comments when matching; and the line we return is the | 1067 strings and comments when matching; and the line we return is the |
983 'cleansed' line at linenum. | 1068 'cleansed' line at linenum. |
984 """ | 1069 """ |
985 | 1070 |
986 line = clean_lines.elided[linenum] | 1071 line = clean_lines.elided[linenum] |
987 startchar = line[pos] | 1072 startchar = line[pos] |
988 if startchar not in '({[': | 1073 if startchar not in '({[': |
989 return (line, clean_lines.NumLines(), -1) | 1074 return (line, clean_lines.NumLines(), -1) |
990 if startchar == '(': endchar = ')' | 1075 if startchar == '(': endchar = ')' |
991 if startchar == '[': endchar = ']' | 1076 if startchar == '[': endchar = ']' |
992 if startchar == '{': endchar = '}' | 1077 if startchar == '{': endchar = '}' |
993 | 1078 |
994 num_open = line.count(startchar) - line.count(endchar) | 1079 # Check first line |
995 while linenum < clean_lines.NumLines() and num_open > 0: | 1080 end_pos = FindEndOfExpressionInLine(line, pos, 0, startchar, endchar) |
| 1081 if end_pos > -1: |
| 1082 return (line, linenum, end_pos) |
| 1083 tail = line[pos:] |
| 1084 num_open = tail.count(startchar) - tail.count(endchar) |
| 1085 while linenum < clean_lines.NumLines() - 1: |
996 linenum += 1 | 1086 linenum += 1 |
997 line = clean_lines.elided[linenum] | 1087 line = clean_lines.elided[linenum] |
998 num_open += line.count(startchar) - line.count(endchar) | 1088 delta = line.count(startchar) - line.count(endchar) |
999 # OK, now find the endchar that actually got us back to even | 1089 if num_open + delta <= 0: |
1000 endpos = len(line) | 1090 return (line, linenum, |
1001 while num_open >= 0: | 1091 FindEndOfExpressionInLine(line, 0, num_open, startchar, endchar)) |
1002 endpos = line.rfind(')', 0, endpos) | 1092 num_open += delta |
1003 num_open -= 1 # chopped off another ) | |
1004 return (line, linenum, endpos + 1) | |
1005 | 1093 |
| 1094 # Did not find endchar before end of file, give up |
| 1095 return (line, clean_lines.NumLines(), -1) |
1006 | 1096 |
1007 def CheckForCopyright(filename, lines, error): | 1097 def CheckForCopyright(filename, lines, error): |
1008 """Logs an error if no Copyright message appears at the top of the file.""" | 1098 """Logs an error if no Copyright message appears at the top of the file.""" |
1009 | 1099 |
1010 # We'll say it should occur by line 10. Don't forget there's a | 1100 # We'll say it should occur by line 10. Don't forget there's a |
1011 # dummy line at the front. | 1101 # dummy line at the front. |
1012 for line in xrange(1, min(len(lines), 11)): | 1102 for line in xrange(1, min(len(lines), 11)): |
1013 if re.search(r'Copyright', lines[line], re.I): break | 1103 if re.search(r'Copyright', lines[line], re.I): break |
1014 else: # means no copyright line was found | 1104 else: # means no copyright line was found |
1015 error(filename, 0, 'legal/copyright', 5, | 1105 error(filename, 0, 'legal/copyright', 5, |
1016 'No copyright message found. ' | 1106 'No copyright message found. ' |
1017 'You should have a line: "Copyright [year] <Copyright Owner>"') | 1107 'You should have a line: "Copyright [year] <Copyright Owner>"') |
1018 | 1108 |
1019 | 1109 |
1020 def GetHeaderGuardCPPVariable(filename): | 1110 def GetHeaderGuardCPPVariable(filename): |
1021 """Returns the CPP variable that should be used as a header guard. | 1111 """Returns the CPP variable that should be used as a header guard. |
1022 | 1112 |
1023 Args: | 1113 Args: |
1024 filename: The name of a C++ header file. | 1114 filename: The name of a C++ header file. |
1025 | 1115 |
1026 Returns: | 1116 Returns: |
1027 The CPP variable that should be used as a header guard in the | 1117 The CPP variable that should be used as a header guard in the |
1028 named file. | 1118 named file. |
1029 | 1119 |
1030 """ | 1120 """ |
1031 | 1121 |
1032 # Restores original filename in case that cpplint is invoked from Emacs's | 1122 # Restores original filename in case that cpplint is invoked from Emacs's |
1033 # flymake. | 1123 # flymake. |
1034 filename = re.sub(r'_flymake\.h$', '.h', filename) | 1124 filename = re.sub(r'_flymake\.h$', '.h', filename) |
| 1125 filename = re.sub(r'/\.flymake/([^/]*)$', r'/\1', filename) |
1035 | 1126 |
1036 fileinfo = FileInfo(filename) | 1127 fileinfo = FileInfo(filename) |
1037 return re.sub(r'[-./\s]', '_', fileinfo.RepositoryName()).upper() + '_' | 1128 file_path_from_root = fileinfo.RepositoryName() |
| 1129 if _root: |
| 1130 file_path_from_root = re.sub('^' + _root + os.sep, '', file_path_from_root) |
| 1131 return re.sub(r'[-./\s]', '_', file_path_from_root).upper() + '_' |
1038 | 1132 |
1039 | 1133 |
1040 def CheckForHeaderGuard(filename, lines, error): | 1134 def CheckForHeaderGuard(filename, lines, error): |
1041 """Checks that the file contains a header guard. | 1135 """Checks that the file contains a header guard. |
1042 | 1136 |
1043 Logs an error if no #ifndef header guard is present. For other | 1137 Logs an error if no #ifndef header guard is present. For other |
1044 headers, checks that the full pathname is used. | 1138 headers, checks that the full pathname is used. |
1045 | 1139 |
1046 Args: | 1140 Args: |
1047 filename: The name of the C++ header file. | 1141 filename: The name of the C++ header file. |
(...skipping 204 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
1252 clean_lines: A CleansedLines instance containing the file. | 1346 clean_lines: A CleansedLines instance containing the file. |
1253 linenum: The number of the line to check. | 1347 linenum: The number of the line to check. |
1254 error: The function to call with any errors found. | 1348 error: The function to call with any errors found. |
1255 """ | 1349 """ |
1256 line = clean_lines.elided[linenum] | 1350 line = clean_lines.elided[linenum] |
1257 if _RE_PATTERN_INVALID_INCREMENT.match(line): | 1351 if _RE_PATTERN_INVALID_INCREMENT.match(line): |
1258 error(filename, linenum, 'runtime/invalid_increment', 5, | 1352 error(filename, linenum, 'runtime/invalid_increment', 5, |
1259 'Changing pointer instead of value (or unused value of operator*).') | 1353 'Changing pointer instead of value (or unused value of operator*).') |
1260 | 1354 |
1261 | 1355 |
1262 class _ClassInfo(object): | 1356 class _BlockInfo(object): |
| 1357 """Stores information about a generic block of code.""" |
| 1358 |
| 1359 def __init__(self, seen_open_brace): |
| 1360 self.seen_open_brace = seen_open_brace |
| 1361 self.open_parentheses = 0 |
| 1362 self.inline_asm = _NO_ASM |
| 1363 |
| 1364 def CheckBegin(self, filename, clean_lines, linenum, error): |
| 1365 """Run checks that applies to text up to the opening brace. |
| 1366 |
| 1367 This is mostly for checking the text after the class identifier |
| 1368 and the "{", usually where the base class is specified. For other |
| 1369 blocks, there isn't much to check, so we always pass. |
| 1370 |
| 1371 Args: |
| 1372 filename: The name of the current file. |
| 1373 clean_lines: A CleansedLines instance containing the file. |
| 1374 linenum: The number of the line to check. |
| 1375 error: The function to call with any errors found. |
| 1376 """ |
| 1377 pass |
| 1378 |
| 1379 def CheckEnd(self, filename, clean_lines, linenum, error): |
| 1380 """Run checks that applies to text after the closing brace. |
| 1381 |
| 1382 This is mostly used for checking end of namespace comments. |
| 1383 |
| 1384 Args: |
| 1385 filename: The name of the current file. |
| 1386 clean_lines: A CleansedLines instance containing the file. |
| 1387 linenum: The number of the line to check. |
| 1388 error: The function to call with any errors found. |
| 1389 """ |
| 1390 pass |
| 1391 |
| 1392 |
| 1393 class _ClassInfo(_BlockInfo): |
1263 """Stores information about a class.""" | 1394 """Stores information about a class.""" |
1264 | 1395 |
1265 def __init__(self, name, clean_lines, linenum): | 1396 def __init__(self, name, class_or_struct, clean_lines, linenum): |
| 1397 _BlockInfo.__init__(self, False) |
1266 self.name = name | 1398 self.name = name |
1267 self.linenum = linenum | 1399 self.starting_linenum = linenum |
1268 self.seen_open_brace = False | |
1269 self.is_derived = False | 1400 self.is_derived = False |
1270 self.virtual_method_linenumber = None | 1401 if class_or_struct == 'struct': |
1271 self.has_virtual_destructor = False | 1402 self.access = 'public' |
1272 self.brace_depth = 0 | 1403 else: |
| 1404 self.access = 'private' |
1273 | 1405 |
1274 # Try to find the end of the class. This will be confused by things like: | 1406 # Try to find the end of the class. This will be confused by things like: |
1275 # class A { | 1407 # class A { |
1276 # } *x = { ... | 1408 # } *x = { ... |
1277 # | 1409 # |
1278 # But it's still good enough for CheckSectionSpacing. | 1410 # But it's still good enough for CheckSectionSpacing. |
1279 self.last_line = 0 | 1411 self.last_line = 0 |
1280 depth = 0 | 1412 depth = 0 |
1281 for i in range(linenum, clean_lines.NumLines()): | 1413 for i in range(linenum, clean_lines.NumLines()): |
1282 line = clean_lines.lines[i] | 1414 line = clean_lines.elided[i] |
1283 depth += line.count('{') - line.count('}') | 1415 depth += line.count('{') - line.count('}') |
1284 if not depth: | 1416 if not depth: |
1285 self.last_line = i | 1417 self.last_line = i |
1286 break | 1418 break |
1287 | 1419 |
1288 | 1420 def CheckBegin(self, filename, clean_lines, linenum, error): |
1289 class _ClassState(object): | 1421 # Look for a bare ':' |
1290 """Holds the current state of the parse relating to class declarations. | 1422 if Search('(^|[^:]):($|[^:])', clean_lines.elided[linenum]): |
1291 | 1423 self.is_derived = True |
1292 It maintains a stack of _ClassInfos representing the parser's guess | 1424 |
1293 as to the current nesting of class declarations. The innermost class | 1425 |
1294 is at the top (back) of the stack. Typically, the stack will either | 1426 class _NamespaceInfo(_BlockInfo): |
1295 be empty or have exactly one entry. | 1427 """Stores information about a namespace.""" |
1296 """ | 1428 |
| 1429 def __init__(self, name, linenum): |
| 1430 _BlockInfo.__init__(self, False) |
| 1431 self.name = name or '' |
| 1432 self.starting_linenum = linenum |
| 1433 |
| 1434 def CheckEnd(self, filename, clean_lines, linenum, error): |
| 1435 """Check end of namespace comments.""" |
| 1436 line = clean_lines.raw_lines[linenum] |
| 1437 |
| 1438 # Check how many lines is enclosed in this namespace. Don't issue |
| 1439 # warning for missing namespace comments if there aren't enough |
| 1440 # lines. However, do apply checks if there is already an end of |
| 1441 # namespace comment and it's incorrect. |
| 1442 # |
| 1443 # TODO(unknown): We always want to check end of namespace comments |
| 1444 # if a namespace is large, but sometimes we also want to apply the |
| 1445 # check if a short namespace contained nontrivial things (something |
| 1446 # other than forward declarations). There is currently no logic on |
| 1447 # deciding what these nontrivial things are, so this check is |
| 1448 # triggered by namespace size only, which works most of the time. |
| 1449 if (linenum - self.starting_linenum < 10 |
| 1450 and not Match(r'};*\s*(//|/\*).*\bnamespace\b', line)): |
| 1451 return |
| 1452 |
| 1453 # Look for matching comment at end of namespace. |
| 1454 # |
| 1455 # Note that we accept C style "/* */" comments for terminating |
| 1456 # namespaces, so that code that terminate namespaces inside |
| 1457 # preprocessor macros can be cpplint clean. Example: http://go/nxpiz |
| 1458 # |
| 1459 # We also accept stuff like "// end of namespace <name>." with the |
| 1460 # period at the end. |
| 1461 # |
| 1462 # Besides these, we don't accept anything else, otherwise we might |
| 1463 # get false negatives when existing comment is a substring of the |
| 1464 # expected namespace. Example: http://go/ldkdc, http://cl/23548205 |
| 1465 if self.name: |
| 1466 # Named namespace |
| 1467 if not Match((r'};*\s*(//|/\*).*\bnamespace\s+' + re.escape(self.name) + |
| 1468 r'[\*/\.\\\s]*$'), |
| 1469 line): |
| 1470 error(filename, linenum, 'readability/namespace', 5, |
| 1471 'Namespace should be terminated with "// namespace %s"' % |
| 1472 self.name) |
| 1473 else: |
| 1474 # Anonymous namespace |
| 1475 if not Match(r'};*\s*(//|/\*).*\bnamespace[\*/\.\\\s]*$', line): |
| 1476 error(filename, linenum, 'readability/namespace', 5, |
| 1477 'Namespace should be terminated with "// namespace"') |
| 1478 |
| 1479 |
| 1480 class _PreprocessorInfo(object): |
| 1481 """Stores checkpoints of nesting stacks when #if/#else is seen.""" |
| 1482 |
| 1483 def __init__(self, stack_before_if): |
| 1484 # The entire nesting stack before #if |
| 1485 self.stack_before_if = stack_before_if |
| 1486 |
| 1487 # The entire nesting stack up to #else |
| 1488 self.stack_before_else = [] |
| 1489 |
| 1490 # Whether we have already seen #else or #elif |
| 1491 self.seen_else = False |
| 1492 |
| 1493 |
| 1494 class _NestingState(object): |
| 1495 """Holds states related to parsing braces.""" |
1297 | 1496 |
1298 def __init__(self): | 1497 def __init__(self): |
1299 self.classinfo_stack = [] | 1498 # Stack for tracking all braces. An object is pushed whenever we |
1300 | 1499 # see a "{", and popped when we see a "}". Only 3 types of |
1301 def CheckFinished(self, filename, error): | 1500 # objects are possible: |
| 1501 # - _ClassInfo: a class or struct. |
| 1502 # - _NamespaceInfo: a namespace. |
| 1503 # - _BlockInfo: some other type of block. |
| 1504 self.stack = [] |
| 1505 |
| 1506 # Stack of _PreprocessorInfo objects. |
| 1507 self.pp_stack = [] |
| 1508 |
| 1509 def SeenOpenBrace(self): |
| 1510 """Check if we have seen the opening brace for the innermost block. |
| 1511 |
| 1512 Returns: |
| 1513 True if we have seen the opening brace, False if the innermost |
| 1514 block is still expecting an opening brace. |
| 1515 """ |
| 1516 return (not self.stack) or self.stack[-1].seen_open_brace |
| 1517 |
| 1518 def InNamespaceBody(self): |
| 1519 """Check if we are currently one level inside a namespace body. |
| 1520 |
| 1521 Returns: |
| 1522 True if top of the stack is a namespace block, False otherwise. |
| 1523 """ |
| 1524 return self.stack and isinstance(self.stack[-1], _NamespaceInfo) |
| 1525 |
| 1526 def UpdatePreprocessor(self, line): |
| 1527 """Update preprocessor stack. |
| 1528 |
| 1529 We need to handle preprocessors due to classes like this: |
| 1530 #ifdef SWIG |
| 1531 struct ResultDetailsPageElementExtensionPoint { |
| 1532 #else |
| 1533 struct ResultDetailsPageElementExtensionPoint : public Extension { |
| 1534 #endif |
| 1535 (see http://go/qwddn for original example) |
| 1536 |
| 1537 We make the following assumptions (good enough for most files): |
| 1538 - Preprocessor condition evaluates to true from #if up to first |
| 1539 #else/#elif/#endif. |
| 1540 |
| 1541 - Preprocessor condition evaluates to false from #else/#elif up |
| 1542 to #endif. We still perform lint checks on these lines, but |
| 1543 these do not affect nesting stack. |
| 1544 |
| 1545 Args: |
| 1546 line: current line to check. |
| 1547 """ |
| 1548 if Match(r'^\s*#\s*(if|ifdef|ifndef)\b', line): |
| 1549 # Beginning of #if block, save the nesting stack here. The saved |
| 1550 # stack will allow us to restore the parsing state in the #else case. |
| 1551 self.pp_stack.append(_PreprocessorInfo(copy.deepcopy(self.stack))) |
| 1552 elif Match(r'^\s*#\s*(else|elif)\b', line): |
| 1553 # Beginning of #else block |
| 1554 if self.pp_stack: |
| 1555 if not self.pp_stack[-1].seen_else: |
| 1556 # This is the first #else or #elif block. Remember the |
| 1557 # whole nesting stack up to this point. This is what we |
| 1558 # keep after the #endif. |
| 1559 self.pp_stack[-1].seen_else = True |
| 1560 self.pp_stack[-1].stack_before_else = copy.deepcopy(self.stack) |
| 1561 |
| 1562 # Restore the stack to how it was before the #if |
| 1563 self.stack = copy.deepcopy(self.pp_stack[-1].stack_before_if) |
| 1564 else: |
| 1565 # TODO(unknown): unexpected #else, issue warning? |
| 1566 pass |
| 1567 elif Match(r'^\s*#\s*endif\b', line): |
| 1568 # End of #if or #else blocks. |
| 1569 if self.pp_stack: |
| 1570 # If we saw an #else, we will need to restore the nesting |
| 1571 # stack to its former state before the #else, otherwise we |
| 1572 # will just continue from where we left off. |
| 1573 if self.pp_stack[-1].seen_else: |
| 1574 # Here we can just use a shallow copy since we are the last |
| 1575 # reference to it. |
| 1576 self.stack = self.pp_stack[-1].stack_before_else |
| 1577 # Drop the corresponding #if |
| 1578 self.pp_stack.pop() |
| 1579 else: |
| 1580 # TODO(unknown): unexpected #endif, issue warning? |
| 1581 pass |
| 1582 |
| 1583 def Update(self, filename, clean_lines, linenum, error): |
| 1584 """Update nesting state with current line. |
| 1585 |
| 1586 Args: |
| 1587 filename: The name of the current file. |
| 1588 clean_lines: A CleansedLines instance containing the file. |
| 1589 linenum: The number of the line to check. |
| 1590 error: The function to call with any errors found. |
| 1591 """ |
| 1592 line = clean_lines.elided[linenum] |
| 1593 |
| 1594 # Update pp_stack first |
| 1595 self.UpdatePreprocessor(line) |
| 1596 |
| 1597 # Count parentheses. This is to avoid adding struct arguments to |
| 1598 # the nesting stack. |
| 1599 if self.stack: |
| 1600 inner_block = self.stack[-1] |
| 1601 depth_change = line.count('(') - line.count(')') |
| 1602 inner_block.open_parentheses += depth_change |
| 1603 |
| 1604 # Also check if we are starting or ending an inline assembly block. |
| 1605 if inner_block.inline_asm in (_NO_ASM, _END_ASM): |
| 1606 if (depth_change != 0 and |
| 1607 inner_block.open_parentheses == 1 and |
| 1608 _MATCH_ASM.match(line)): |
| 1609 # Enter assembly block |
| 1610 inner_block.inline_asm = _INSIDE_ASM |
| 1611 else: |
| 1612 # Not entering assembly block. If previous line was _END_ASM, |
| 1613 # we will now shift to _NO_ASM state. |
| 1614 inner_block.inline_asm = _NO_ASM |
| 1615 elif (inner_block.inline_asm == _INSIDE_ASM and |
| 1616 inner_block.open_parentheses == 0): |
| 1617 # Exit assembly block |
| 1618 inner_block.inline_asm = _END_ASM |
| 1619 |
| 1620 # Consume namespace declaration at the beginning of the line. Do |
| 1621 # this in a loop so that we catch same line declarations like this: |
| 1622 # namespace proto2 { namespace bridge { class MessageSet; } } |
| 1623 while True: |
| 1624 # Match start of namespace. The "\b\s*" below catches namespace |
| 1625 # declarations even if it weren't followed by a whitespace, this |
| 1626 # is so that we don't confuse our namespace checker. The |
| 1627 # missing spaces will be flagged by CheckSpacing. |
| 1628 namespace_decl_match = Match(r'^\s*namespace\b\s*([:\w]+)?(.*)$', line) |
| 1629 if not namespace_decl_match: |
| 1630 break |
| 1631 |
| 1632 new_namespace = _NamespaceInfo(namespace_decl_match.group(1), linenum) |
| 1633 self.stack.append(new_namespace) |
| 1634 |
| 1635 line = namespace_decl_match.group(2) |
| 1636 if line.find('{') != -1: |
| 1637 new_namespace.seen_open_brace = True |
| 1638 line = line[line.find('{') + 1:] |
| 1639 |
| 1640 # Look for a class declaration in whatever is left of the line |
| 1641 # after parsing namespaces. The regexp accounts for decorated classes |
| 1642 # such as in: |
| 1643 # class LOCKABLE API Object { |
| 1644 # }; |
| 1645 # |
| 1646 # Templates with class arguments may confuse the parser, for example: |
| 1647 # template <class T |
| 1648 # class Comparator = less<T>, |
| 1649 # class Vector = vector<T> > |
| 1650 # class HeapQueue { |
| 1651 # |
| 1652 # Because this parser has no nesting state about templates, by the |
| 1653 # time it saw "class Comparator", it may think that it's a new class. |
| 1654 # Nested templates have a similar problem: |
| 1655 # template < |
| 1656 # typename ExportedType, |
| 1657 # typename TupleType, |
| 1658 # template <typename, typename> class ImplTemplate> |
| 1659 # |
| 1660 # To avoid these cases, we ignore classes that are followed by '=' or '>' |
| 1661 class_decl_match = Match( |
| 1662 r'\s*(template\s*<[\w\s<>,:]*>\s*)?' |
| 1663 '(class|struct)\s+([A-Z_]+\s+)*(\w+(?:::\w+)*)' |
| 1664 '(([^=>]|<[^<>]*>)*)$', line) |
| 1665 if (class_decl_match and |
| 1666 (not self.stack or self.stack[-1].open_parentheses == 0)): |
| 1667 self.stack.append(_ClassInfo( |
| 1668 class_decl_match.group(4), class_decl_match.group(2), |
| 1669 clean_lines, linenum)) |
| 1670 line = class_decl_match.group(5) |
| 1671 |
| 1672 # If we have not yet seen the opening brace for the innermost block, |
| 1673 # run checks here. |
| 1674 if not self.SeenOpenBrace(): |
| 1675 self.stack[-1].CheckBegin(filename, clean_lines, linenum, error) |
| 1676 |
| 1677 # Update access control if we are inside a class/struct |
| 1678 if self.stack and isinstance(self.stack[-1], _ClassInfo): |
| 1679 access_match = Match(r'\s*(public|private|protected)\s*:', line) |
| 1680 if access_match: |
| 1681 self.stack[-1].access = access_match.group(1) |
| 1682 |
| 1683 # Consume braces or semicolons from what's left of the line |
| 1684 while True: |
| 1685 # Match first brace, semicolon, or closed parenthesis. |
| 1686 matched = Match(r'^[^{;)}]*([{;)}])(.*)$', line) |
| 1687 if not matched: |
| 1688 break |
| 1689 |
| 1690 token = matched.group(1) |
| 1691 if token == '{': |
| 1692 # If namespace or class hasn't seen a opening brace yet, mark |
| 1693 # namespace/class head as complete. Push a new block onto the |
| 1694 # stack otherwise. |
| 1695 if not self.SeenOpenBrace(): |
| 1696 self.stack[-1].seen_open_brace = True |
| 1697 else: |
| 1698 self.stack.append(_BlockInfo(True)) |
| 1699 if _MATCH_ASM.match(line): |
| 1700 self.stack[-1].inline_asm = _BLOCK_ASM |
| 1701 elif token == ';' or token == ')': |
| 1702 # If we haven't seen an opening brace yet, but we already saw |
| 1703 # a semicolon, this is probably a forward declaration. Pop |
| 1704 # the stack for these. |
| 1705 # |
| 1706 # Similarly, if we haven't seen an opening brace yet, but we |
| 1707 # already saw a closing parenthesis, then these are probably |
| 1708 # function arguments with extra "class" or "struct" keywords. |
| 1709 # Also pop these stack for these. |
| 1710 if not self.SeenOpenBrace(): |
| 1711 self.stack.pop() |
| 1712 else: # token == '}' |
| 1713 # Perform end of block checks and pop the stack. |
| 1714 if self.stack: |
| 1715 self.stack[-1].CheckEnd(filename, clean_lines, linenum, error) |
| 1716 self.stack.pop() |
| 1717 line = matched.group(2) |
| 1718 |
| 1719 def InnermostClass(self): |
| 1720 """Get class info on the top of the stack. |
| 1721 |
| 1722 Returns: |
| 1723 A _ClassInfo object if we are inside a class, or None otherwise. |
| 1724 """ |
| 1725 for i in range(len(self.stack), 0, -1): |
| 1726 classinfo = self.stack[i - 1] |
| 1727 if isinstance(classinfo, _ClassInfo): |
| 1728 return classinfo |
| 1729 return None |
| 1730 |
| 1731 def CheckClassFinished(self, filename, error): |
1302 """Checks that all classes have been completely parsed. | 1732 """Checks that all classes have been completely parsed. |
1303 | 1733 |
1304 Call this when all lines in a file have been processed. | 1734 Call this when all lines in a file have been processed. |
1305 Args: | 1735 Args: |
1306 filename: The name of the current file. | 1736 filename: The name of the current file. |
1307 error: The function to call with any errors found. | 1737 error: The function to call with any errors found. |
1308 """ | 1738 """ |
1309 if self.classinfo_stack: | 1739 # Note: This test can result in false positives if #ifdef constructs |
1310 # Note: This test can result in false positives if #ifdef constructs | 1740 # get in the way of brace matching. See the testBuildClass test in |
1311 # get in the way of brace matching. See the testBuildClass test in | 1741 # cpplint_unittest.py for an example of this. |
1312 # cpplint_unittest.py for an example of this. | 1742 for obj in self.stack: |
1313 error(filename, self.classinfo_stack[0].linenum, 'build/class', 5, | 1743 if isinstance(obj, _ClassInfo): |
1314 'Failed to find complete declaration of class %s' % | 1744 error(filename, obj.starting_linenum, 'build/class', 5, |
1315 self.classinfo_stack[0].name) | 1745 'Failed to find complete declaration of class %s' % |
| 1746 obj.name) |
1316 | 1747 |
1317 | 1748 |
1318 def CheckForNonStandardConstructs(filename, clean_lines, linenum, | 1749 def CheckForNonStandardConstructs(filename, clean_lines, linenum, |
1319 class_state, error): | 1750 nesting_state, error): |
1320 """Logs an error if we see certain non-ANSI constructs ignored by gcc-2. | 1751 """Logs an error if we see certain non-ANSI constructs ignored by gcc-2. |
1321 | 1752 |
1322 Complain about several constructs which gcc-2 accepts, but which are | 1753 Complain about several constructs which gcc-2 accepts, but which are |
1323 not standard C++. Warning about these in lint is one way to ease the | 1754 not standard C++. Warning about these in lint is one way to ease the |
1324 transition to new compilers. | 1755 transition to new compilers. |
1325 - put storage class first (e.g. "static const" instead of "const static"). | 1756 - put storage class first (e.g. "static const" instead of "const static"). |
1326 - "%lld" instead of %qd" in printf-type functions. | 1757 - "%lld" instead of %qd" in printf-type functions. |
1327 - "%1$d" is non-standard in printf-type functions. | 1758 - "%1$d" is non-standard in printf-type functions. |
1328 - "\%" is an undefined character escape sequence. | 1759 - "\%" is an undefined character escape sequence. |
1329 - text after #endif is not allowed. | 1760 - text after #endif is not allowed. |
1330 - invalid inner-style forward declaration. | 1761 - invalid inner-style forward declaration. |
1331 - >? and <? operators, and their >?= and <?= cousins. | 1762 - >? and <? operators, and their >?= and <?= cousins. |
1332 - classes with virtual methods need virtual destructors (compiler warning | |
1333 available, but not turned on yet.) | |
1334 | 1763 |
1335 Additionally, check for constructor/destructor style violations and reference | 1764 Additionally, check for constructor/destructor style violations and reference |
1336 members, as it is very convenient to do so while checking for | 1765 members, as it is very convenient to do so while checking for |
1337 gcc-2 compliance. | 1766 gcc-2 compliance. |
1338 | 1767 |
1339 Args: | 1768 Args: |
1340 filename: The name of the current file. | 1769 filename: The name of the current file. |
1341 clean_lines: A CleansedLines instance containing the file. | 1770 clean_lines: A CleansedLines instance containing the file. |
1342 linenum: The number of the line to check. | 1771 linenum: The number of the line to check. |
1343 class_state: A _ClassState instance which maintains information about | 1772 nesting_state: A _NestingState instance which maintains information about |
1344 the current stack of nested class declarations being parsed. | 1773 the current stack of nested blocks being parsed. |
1345 error: A callable to which errors are reported, which takes 4 arguments: | 1774 error: A callable to which errors are reported, which takes 4 arguments: |
1346 filename, line number, error level, and message | 1775 filename, line number, error level, and message |
1347 """ | 1776 """ |
1348 | 1777 |
1349 # Remove comments from the line, but leave in strings for now. | 1778 # Remove comments from the line, but leave in strings for now. |
1350 line = clean_lines.lines[linenum] | 1779 line = clean_lines.lines[linenum] |
1351 | 1780 |
1352 if Search(r'printf\s*\(.*".*%[-+ ]?\d*q', line): | 1781 if Search(r'printf\s*\(.*".*%[-+ ]?\d*q', line): |
1353 error(filename, linenum, 'runtime/printf_format', 3, | 1782 error(filename, linenum, 'runtime/printf_format', 3, |
1354 '%q in format strings is deprecated. Use %ll instead.') | 1783 '%q in format strings is deprecated. Use %ll instead.') |
1355 | 1784 |
1356 if Search(r'printf\s*\(.*".*%\d+\$', line): | 1785 if Search(r'printf\s*\(.*".*%\d+\$', line): |
1357 error(filename, linenum, 'runtime/printf_format', 2, | 1786 error(filename, linenum, 'runtime/printf_format', 2, |
1358 '%N$ formats are unconventional. Try rewriting to avoid them.') | 1787 '%N$ formats are unconventional. Try rewriting to avoid them.') |
1359 | 1788 |
1360 # Remove escaped backslashes before looking for undefined escapes. | 1789 # Remove escaped backslashes before looking for undefined escapes. |
1361 line = line.replace('\\\\', '') | 1790 line = line.replace('\\\\', '') |
1362 | 1791 |
1363 if Search(r'("|\').*\\(%|\[|\(|{)', line): | 1792 if Search(r'("|\').*\\(%|\[|\(|{)', line): |
1364 error(filename, linenum, 'build/printf_format', 3, | 1793 error(filename, linenum, 'build/printf_format', 3, |
1365 '%, [, (, and { are undefined character escapes. Unescape them.') | 1794 '%, [, (, and { are undefined character escapes. Unescape them.') |
1366 | 1795 |
1367 # For the rest, work with both comments and strings removed. | 1796 # For the rest, work with both comments and strings removed. |
1368 line = clean_lines.elided[linenum] | 1797 line = clean_lines.elided[linenum] |
1369 | 1798 |
1370 if Search(r'\b(const|volatile|void|char|short|int|long' | 1799 if Search(r'\b(const|volatile|void|char|short|int|long' |
1371 r'|float|double|signed|unsigned' | 1800 r'|float|double|signed|unsigned' |
1372 r'|schar|u?int8|u?int16|u?int32|u?int64)' | 1801 r'|schar|u?int8|u?int16|u?int32|u?int64)' |
1373 r'\s+(auto|register|static|extern|typedef)\b', | 1802 r'\s+(register|static|extern|typedef)\b', |
1374 line): | 1803 line): |
1375 error(filename, linenum, 'build/storage_class', 5, | 1804 error(filename, linenum, 'build/storage_class', 5, |
1376 'Storage class (static, extern, typedef, etc) should be first.') | 1805 'Storage class (static, extern, typedef, etc) should be first.') |
1377 | 1806 |
1378 if Match(r'\s*#\s*endif\s*[^/\s]+', line): | 1807 if Match(r'\s*#\s*endif\s*[^/\s]+', line): |
1379 error(filename, linenum, 'build/endif_comment', 5, | 1808 error(filename, linenum, 'build/endif_comment', 5, |
1380 'Uncommented text after #endif is non-standard. Use a comment.') | 1809 'Uncommented text after #endif is non-standard. Use a comment.') |
1381 | 1810 |
1382 if Match(r'\s*class\s+(\w+\s*::\s*)+\w+\s*;', line): | 1811 if Match(r'\s*class\s+(\w+\s*::\s*)+\w+\s*;', line): |
1383 error(filename, linenum, 'build/forward_decl', 5, | 1812 error(filename, linenum, 'build/forward_decl', 5, |
1384 'Inner-style forward declarations are invalid. Remove this line.') | 1813 'Inner-style forward declarations are invalid. Remove this line.') |
1385 | 1814 |
1386 if Search(r'(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?', | 1815 if Search(r'(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?', |
1387 line): | 1816 line): |
1388 error(filename, linenum, 'build/deprecated', 3, | 1817 error(filename, linenum, 'build/deprecated', 3, |
1389 '>? and <? (max and min) operators are non-standard and deprecated.') | 1818 '>? and <? (max and min) operators are non-standard and deprecated.') |
1390 | 1819 |
1391 if Search(r'^\s*const\s*string\s*&\s*\w+\s*;', line): | 1820 if Search(r'^\s*const\s*string\s*&\s*\w+\s*;', line): |
1392 # TODO(unknown): Could it be expanded safely to arbitrary references, | 1821 # TODO(unknown): Could it be expanded safely to arbitrary references, |
1393 # without triggering too many false positives? The first | 1822 # without triggering too many false positives? The first |
1394 # attempt triggered 5 warnings for mostly benign code in the regtest, hence | 1823 # attempt triggered 5 warnings for mostly benign code in the regtest, hence |
1395 # the restriction. | 1824 # the restriction. |
1396 # Here's the original regexp, for the reference: | 1825 # Here's the original regexp, for the reference: |
1397 # type_name = r'\w+((\s*::\s*\w+)|(\s*<\s*\w+?\s*>))?' | 1826 # type_name = r'\w+((\s*::\s*\w+)|(\s*<\s*\w+?\s*>))?' |
1398 # r'\s*const\s*' + type_name + '\s*&\s*\w+\s*;' | 1827 # r'\s*const\s*' + type_name + '\s*&\s*\w+\s*;' |
1399 error(filename, linenum, 'runtime/member_string_references', 2, | 1828 error(filename, linenum, 'runtime/member_string_references', 2, |
1400 'const string& members are dangerous. It is much better to use ' | 1829 'const string& members are dangerous. It is much better to use ' |
1401 'alternatives, such as pointers or simple constants.') | 1830 'alternatives, such as pointers or simple constants.') |
1402 | 1831 |
1403 # Track class entry and exit, and attempt to find cases within the | 1832 # Everything else in this function operates on class declarations. |
1404 # class declaration that don't meet the C++ style | 1833 # Return early if the top of the nesting stack is not a class, or if |
1405 # guidelines. Tracking is very dependent on the code matching Google | 1834 # the class head is not completed yet. |
1406 # style guidelines, but it seems to perform well enough in testing | 1835 classinfo = nesting_state.InnermostClass() |
1407 # to be a worthwhile addition to the checks. | 1836 if not classinfo or not classinfo.seen_open_brace: |
1408 classinfo_stack = class_state.classinfo_stack | |
1409 # Look for a class declaration. The regexp accounts for decorated classes | |
1410 # such as in: | |
1411 # class LOCKABLE API Object { | |
1412 # }; | |
1413 class_decl_match = Match( | |
1414 r'\s*(template\s*<[\w\s<>,:]*>\s*)?' | |
1415 '(class|struct)\s+([A-Z_]+\s+)*(\w+(::\w+)*)', line) | |
1416 if class_decl_match: | |
1417 classinfo_stack.append(_ClassInfo( | |
1418 class_decl_match.group(4), clean_lines, linenum)) | |
1419 | |
1420 # Everything else in this function uses the top of the stack if it's | |
1421 # not empty. | |
1422 if not classinfo_stack: | |
1423 return | 1837 return |
1424 | 1838 |
1425 classinfo = classinfo_stack[-1] | |
1426 | |
1427 # If the opening brace hasn't been seen look for it and also | |
1428 # parent class declarations. | |
1429 if not classinfo.seen_open_brace: | |
1430 # If the line has a ';' in it, assume it's a forward declaration or | |
1431 # a single-line class declaration, which we won't process. | |
1432 if line.find(';') != -1: | |
1433 classinfo_stack.pop() | |
1434 return | |
1435 classinfo.seen_open_brace = (line.find('{') != -1) | |
1436 # Look for a bare ':' | |
1437 if Search('(^|[^:]):($|[^:])', line): | |
1438 classinfo.is_derived = True | |
1439 if not classinfo.seen_open_brace: | |
1440 return # Everything else in this function is for after open brace | |
1441 | |
1442 # The class may have been declared with namespace or classname qualifiers. | 1839 # The class may have been declared with namespace or classname qualifiers. |
1443 # The constructor and destructor will not have those qualifiers. | 1840 # The constructor and destructor will not have those qualifiers. |
1444 base_classname = classinfo.name.split('::')[-1] | 1841 base_classname = classinfo.name.split('::')[-1] |
1445 | 1842 |
1446 # Look for single-argument constructors that aren't marked explicit. | 1843 # Look for single-argument constructors that aren't marked explicit. |
1447 # Technically a valid construct, but against style. | 1844 # Technically a valid construct, but against style. |
1448 args = Match(r'\s+(?:inline\s+)?%s\s*\(([^,()]+)\)' | 1845 args = Match(r'\s+(?:inline\s+)?%s\s*\(([^,()]+)\)' |
1449 % re.escape(base_classname), | 1846 % re.escape(base_classname), |
1450 line) | 1847 line) |
1451 if (args and | 1848 if (args and |
1452 args.group(1) != 'void' and | 1849 args.group(1) != 'void' and |
1453 not Match(r'(const\s+)?%s\s*(?:<\w+>\s*)?&' % re.escape(base_classname), | 1850 not Match(r'(const\s+)?%s\s*(?:<\w+>\s*)?&' % re.escape(base_classname), |
1454 args.group(1).strip())): | 1851 args.group(1).strip())): |
1455 error(filename, linenum, 'runtime/explicit', 5, | 1852 error(filename, linenum, 'runtime/explicit', 5, |
1456 'Single-argument constructors should be marked explicit.') | 1853 'Single-argument constructors should be marked explicit.') |
1457 | 1854 |
1458 # Look for methods declared virtual. | |
1459 if Search(r'\bvirtual\b', line): | |
1460 classinfo.virtual_method_linenumber = linenum | |
1461 # Only look for a destructor declaration on the same line. It would | |
1462 # be extremely unlikely for the destructor declaration to occupy | |
1463 # more than one line. | |
1464 if Search(r'~%s\s*\(' % base_classname, line): | |
1465 classinfo.has_virtual_destructor = True | |
1466 | |
1467 # Look for class end. | |
1468 brace_depth = classinfo.brace_depth | |
1469 brace_depth = brace_depth + line.count('{') - line.count('}') | |
1470 if brace_depth <= 0: | |
1471 classinfo = classinfo_stack.pop() | |
1472 # Try to detect missing virtual destructor declarations. | |
1473 # For now, only warn if a non-derived class with virtual methods lacks | |
1474 # a virtual destructor. This is to make it less likely that people will | |
1475 # declare derived virtual destructors without declaring the base | |
1476 # destructor virtual. | |
1477 if ((classinfo.virtual_method_linenumber is not None) and | |
1478 (not classinfo.has_virtual_destructor) and | |
1479 (not classinfo.is_derived)): # Only warn for base classes | |
1480 error(filename, classinfo.linenum, 'runtime/virtual', 4, | |
1481 'The class %s probably needs a virtual destructor due to ' | |
1482 'having virtual method(s), one declared at line %d.' | |
1483 % (classinfo.name, classinfo.virtual_method_linenumber)) | |
1484 else: | |
1485 classinfo.brace_depth = brace_depth | |
1486 | |
1487 | 1855 |
1488 def CheckSpacingForFunctionCall(filename, line, linenum, error): | 1856 def CheckSpacingForFunctionCall(filename, line, linenum, error): |
1489 """Checks for the correctness of various spacing around function calls. | 1857 """Checks for the correctness of various spacing around function calls. |
1490 | 1858 |
1491 Args: | 1859 Args: |
1492 filename: The name of the current file. | 1860 filename: The name of the current file. |
1493 line: The text of the line to check. | 1861 line: The text of the line to check. |
1494 linenum: The number of the line to check. | 1862 linenum: The number of the line to check. |
1495 error: The function to call with any errors found. | 1863 error: The function to call with any errors found. |
1496 """ | 1864 """ |
(...skipping 31 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
1528 not Search(r' \([^)]+\)\([^)]*(\)|,$)', fncall) and | 1896 not Search(r' \([^)]+\)\([^)]*(\)|,$)', fncall) and |
1529 # Ignore pointers/references to arrays. | 1897 # Ignore pointers/references to arrays. |
1530 not Search(r' \([^)]+\)\[[^\]]+\]', fncall)): | 1898 not Search(r' \([^)]+\)\[[^\]]+\]', fncall)): |
1531 if Search(r'\w\s*\(\s(?!\s*\\$)', fncall): # a ( used for a fn call | 1899 if Search(r'\w\s*\(\s(?!\s*\\$)', fncall): # a ( used for a fn call |
1532 error(filename, linenum, 'whitespace/parens', 4, | 1900 error(filename, linenum, 'whitespace/parens', 4, |
1533 'Extra space after ( in function call') | 1901 'Extra space after ( in function call') |
1534 elif Search(r'\(\s+(?!(\s*\\)|\()', fncall): | 1902 elif Search(r'\(\s+(?!(\s*\\)|\()', fncall): |
1535 error(filename, linenum, 'whitespace/parens', 2, | 1903 error(filename, linenum, 'whitespace/parens', 2, |
1536 'Extra space after (') | 1904 'Extra space after (') |
1537 if (Search(r'\w\s+\(', fncall) and | 1905 if (Search(r'\w\s+\(', fncall) and |
1538 not Search(r'#\s*define|typedef', fncall)): | 1906 not Search(r'#\s*define|typedef', fncall) and |
| 1907 not Search(r'\w\s+\((\w+::)?\*\w+\)\(', fncall)): |
1539 error(filename, linenum, 'whitespace/parens', 4, | 1908 error(filename, linenum, 'whitespace/parens', 4, |
1540 'Extra space before ( in function call') | 1909 'Extra space before ( in function call') |
1541 # If the ) is followed only by a newline or a { + newline, assume it's | 1910 # If the ) is followed only by a newline or a { + newline, assume it's |
1542 # part of a control statement (if/while/etc), and don't complain | 1911 # part of a control statement (if/while/etc), and don't complain |
1543 if Search(r'[^)]\s+\)\s*[^{\s]', fncall): | 1912 if Search(r'[^)]\s+\)\s*[^{\s]', fncall): |
1544 # If the closing parenthesis is preceded by only whitespaces, | 1913 # If the closing parenthesis is preceded by only whitespaces, |
1545 # try to give a more descriptive error message. | 1914 # try to give a more descriptive error message. |
1546 if Search(r'^\s+\)', fncall): | 1915 if Search(r'^\s+\)', fncall): |
1547 error(filename, linenum, 'whitespace/parens', 2, | 1916 error(filename, linenum, 'whitespace/parens', 2, |
1548 'Closing ) should be moved to the previous line') | 1917 'Closing ) should be moved to the previous line') |
(...skipping 112 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
1661 error(filename, linenum, 'readability/todo', 2, | 2030 error(filename, linenum, 'readability/todo', 2, |
1662 'Missing username in TODO; it should look like ' | 2031 'Missing username in TODO; it should look like ' |
1663 '"// TODO(my_username): Stuff."') | 2032 '"// TODO(my_username): Stuff."') |
1664 | 2033 |
1665 middle_whitespace = match.group(3) | 2034 middle_whitespace = match.group(3) |
1666 # Comparisons made explicit for correctness -- pylint: disable-msg=C6403 | 2035 # Comparisons made explicit for correctness -- pylint: disable-msg=C6403 |
1667 if middle_whitespace != ' ' and middle_whitespace != '': | 2036 if middle_whitespace != ' ' and middle_whitespace != '': |
1668 error(filename, linenum, 'whitespace/todo', 2, | 2037 error(filename, linenum, 'whitespace/todo', 2, |
1669 'TODO(my_username) should be followed by a space') | 2038 'TODO(my_username) should be followed by a space') |
1670 | 2039 |
| 2040 def CheckAccess(filename, clean_lines, linenum, nesting_state, error): |
| 2041 """Checks for improper use of DISALLOW* macros. |
1671 | 2042 |
1672 def CheckSpacing(filename, clean_lines, linenum, error): | 2043 Args: |
| 2044 filename: The name of the current file. |
| 2045 clean_lines: A CleansedLines instance containing the file. |
| 2046 linenum: The number of the line to check. |
| 2047 nesting_state: A _NestingState instance which maintains information about |
| 2048 the current stack of nested blocks being parsed. |
| 2049 error: The function to call with any errors found. |
| 2050 """ |
| 2051 line = clean_lines.elided[linenum] # get rid of comments and strings |
| 2052 |
| 2053 matched = Match((r'\s*(DISALLOW_COPY_AND_ASSIGN|' |
| 2054 r'DISALLOW_EVIL_CONSTRUCTORS|' |
| 2055 r'DISALLOW_IMPLICIT_CONSTRUCTORS)'), line) |
| 2056 if not matched: |
| 2057 return |
| 2058 if nesting_state.stack and isinstance(nesting_state.stack[-1], _ClassInfo): |
| 2059 if nesting_state.stack[-1].access != 'private': |
| 2060 error(filename, linenum, 'readability/constructors', 3, |
| 2061 '%s must be in the private: section' % matched.group(1)) |
| 2062 |
| 2063 else: |
| 2064 # Found DISALLOW* macro outside a class declaration, or perhaps it |
| 2065 # was used inside a function when it should have been part of the |
| 2066 # class declaration. We could issue a warning here, but it |
| 2067 # probably resulted in a compiler error already. |
| 2068 pass |
| 2069 |
| 2070 |
| 2071 def FindNextMatchingAngleBracket(clean_lines, linenum, init_suffix): |
| 2072 """Find the corresponding > to close a template. |
| 2073 |
| 2074 Args: |
| 2075 clean_lines: A CleansedLines instance containing the file. |
| 2076 linenum: Current line number. |
| 2077 init_suffix: Remainder of the current line after the initial <. |
| 2078 |
| 2079 Returns: |
| 2080 True if a matching bracket exists. |
| 2081 """ |
| 2082 line = init_suffix |
| 2083 nesting_stack = ['<'] |
| 2084 while True: |
| 2085 # Find the next operator that can tell us whether < is used as an |
| 2086 # opening bracket or as a less-than operator. We only want to |
| 2087 # warn on the latter case. |
| 2088 # |
| 2089 # We could also check all other operators and terminate the search |
| 2090 # early, e.g. if we got something like this "a<b+c", the "<" is |
| 2091 # most likely a less-than operator, but then we will get false |
| 2092 # positives for default arguments (e.g. http://go/prccd) and |
| 2093 # other template expressions (e.g. http://go/oxcjq). |
| 2094 match = Search(r'^[^<>(),;\[\]]*([<>(),;\[\]])(.*)$', line) |
| 2095 if match: |
| 2096 # Found an operator, update nesting stack |
| 2097 operator = match.group(1) |
| 2098 line = match.group(2) |
| 2099 |
| 2100 if nesting_stack[-1] == '<': |
| 2101 # Expecting closing angle bracket |
| 2102 if operator in ('<', '(', '['): |
| 2103 nesting_stack.append(operator) |
| 2104 elif operator == '>': |
| 2105 nesting_stack.pop() |
| 2106 if not nesting_stack: |
| 2107 # Found matching angle bracket |
| 2108 return True |
| 2109 elif operator == ',': |
| 2110 # Got a comma after a bracket, this is most likely a template |
| 2111 # argument. We have not seen a closing angle bracket yet, but |
| 2112 # it's probably a few lines later if we look for it, so just |
| 2113 # return early here. |
| 2114 return True |
| 2115 else: |
| 2116 # Got some other operator. |
| 2117 return False |
| 2118 |
| 2119 else: |
| 2120 # Expecting closing parenthesis or closing bracket |
| 2121 if operator in ('<', '(', '['): |
| 2122 nesting_stack.append(operator) |
| 2123 elif operator in (')', ']'): |
| 2124 # We don't bother checking for matching () or []. If we got |
| 2125 # something like (] or [), it would have been a syntax error. |
| 2126 nesting_stack.pop() |
| 2127 |
| 2128 else: |
| 2129 # Scan the next line |
| 2130 linenum += 1 |
| 2131 if linenum >= len(clean_lines.elided): |
| 2132 break |
| 2133 line = clean_lines.elided[linenum] |
| 2134 |
| 2135 # Exhausted all remaining lines and still no matching angle bracket. |
| 2136 # Most likely the input was incomplete, otherwise we should have |
| 2137 # seen a semicolon and returned early. |
| 2138 return True |
| 2139 |
| 2140 |
| 2141 def FindPreviousMatchingAngleBracket(clean_lines, linenum, init_prefix): |
| 2142 """Find the corresponding < that started a template. |
| 2143 |
| 2144 Args: |
| 2145 clean_lines: A CleansedLines instance containing the file. |
| 2146 linenum: Current line number. |
| 2147 init_prefix: Part of the current line before the initial >. |
| 2148 |
| 2149 Returns: |
| 2150 True if a matching bracket exists. |
| 2151 """ |
| 2152 line = init_prefix |
| 2153 nesting_stack = ['>'] |
| 2154 while True: |
| 2155 # Find the previous operator |
| 2156 match = Search(r'^(.*)([<>(),;\[\]])[^<>(),;\[\]]*$', line) |
| 2157 if match: |
| 2158 # Found an operator, update nesting stack |
| 2159 operator = match.group(2) |
| 2160 line = match.group(1) |
| 2161 |
| 2162 if nesting_stack[-1] == '>': |
| 2163 # Expecting opening angle bracket |
| 2164 if operator in ('>', ')', ']'): |
| 2165 nesting_stack.append(operator) |
| 2166 elif operator == '<': |
| 2167 nesting_stack.pop() |
| 2168 if not nesting_stack: |
| 2169 # Found matching angle bracket |
| 2170 return True |
| 2171 elif operator == ',': |
| 2172 # Got a comma before a bracket, this is most likely a |
| 2173 # template argument. The opening angle bracket is probably |
| 2174 # there if we look for it, so just return early here. |
| 2175 return True |
| 2176 else: |
| 2177 # Got some other operator. |
| 2178 return False |
| 2179 |
| 2180 else: |
| 2181 # Expecting opening parenthesis or opening bracket |
| 2182 if operator in ('>', ')', ']'): |
| 2183 nesting_stack.append(operator) |
| 2184 elif operator in ('(', '['): |
| 2185 nesting_stack.pop() |
| 2186 |
| 2187 else: |
| 2188 # Scan the previous line |
| 2189 linenum -= 1 |
| 2190 if linenum < 0: |
| 2191 break |
| 2192 line = clean_lines.elided[linenum] |
| 2193 |
| 2194 # Exhausted all earlier lines and still no matching angle bracket. |
| 2195 return False |
| 2196 |
| 2197 |
| 2198 def CheckSpacing(filename, clean_lines, linenum, nesting_state, error): |
1673 """Checks for the correctness of various spacing issues in the code. | 2199 """Checks for the correctness of various spacing issues in the code. |
1674 | 2200 |
1675 Things we check for: spaces around operators, spaces after | 2201 Things we check for: spaces around operators, spaces after |
1676 if/for/while/switch, no spaces around parens in function calls, two | 2202 if/for/while/switch, no spaces around parens in function calls, two |
1677 spaces between code and comment, don't start a block with a blank | 2203 spaces between code and comment, don't start a block with a blank |
1678 line, don't end a function with a blank line, don't add a blank line | 2204 line, don't end a function with a blank line, don't add a blank line |
1679 after public/protected/private, don't have too many blank lines in a row. | 2205 after public/protected/private, don't have too many blank lines in a row. |
1680 | 2206 |
1681 Args: | 2207 Args: |
1682 filename: The name of the current file. | 2208 filename: The name of the current file. |
1683 clean_lines: A CleansedLines instance containing the file. | 2209 clean_lines: A CleansedLines instance containing the file. |
1684 linenum: The number of the line to check. | 2210 linenum: The number of the line to check. |
| 2211 nesting_state: A _NestingState instance which maintains information about |
| 2212 the current stack of nested blocks being parsed. |
1685 error: The function to call with any errors found. | 2213 error: The function to call with any errors found. |
1686 """ | 2214 """ |
1687 | 2215 |
1688 raw = clean_lines.raw_lines | 2216 raw = clean_lines.raw_lines |
1689 line = raw[linenum] | 2217 line = raw[linenum] |
1690 | 2218 |
1691 # Before nixing comments, check if the line is blank for no good | 2219 # Before nixing comments, check if the line is blank for no good |
1692 # reason. This includes the first line after a block is opened, and | 2220 # reason. This includes the first line after a block is opened, and |
1693 # blank lines at the end of a function (ie, right before a line like '}' | 2221 # blank lines at the end of a function (ie, right before a line like '}' |
1694 if IsBlankLine(line): | 2222 # |
| 2223 # Skip all the blank line checks if we are immediately inside a |
| 2224 # namespace body. In other words, don't issue blank line warnings |
| 2225 # for this block: |
| 2226 # namespace { |
| 2227 # |
| 2228 # } |
| 2229 # |
| 2230 # A warning about missing end of namespace comments will be issued instead. |
| 2231 if IsBlankLine(line) and not nesting_state.InNamespaceBody(): |
1695 elided = clean_lines.elided | 2232 elided = clean_lines.elided |
1696 prev_line = elided[linenum - 1] | 2233 prev_line = elided[linenum - 1] |
1697 prevbrace = prev_line.rfind('{') | 2234 prevbrace = prev_line.rfind('{') |
1698 # TODO(unknown): Don't complain if line before blank line, and line after, | 2235 # TODO(unknown): Don't complain if line before blank line, and line after, |
1699 # both start with alnums and are indented the same amount. | 2236 # both start with alnums and are indented the same amount. |
1700 # This ignores whitespace at the start of a namespace block | 2237 # This ignores whitespace at the start of a namespace block |
1701 # because those are not usually indented. | 2238 # because those are not usually indented. |
1702 if (prevbrace != -1 and prev_line[prevbrace:].find('}') == -1 | 2239 if prevbrace != -1 and prev_line[prevbrace:].find('}') == -1: |
1703 and prev_line[:prevbrace].find('namespace') == -1): | |
1704 # OK, we have a blank line at the start of a code block. Before we | 2240 # OK, we have a blank line at the start of a code block. Before we |
1705 # complain, we check if it is an exception to the rule: The previous | 2241 # complain, we check if it is an exception to the rule: The previous |
1706 # non-empty line has the parameters of a function header that are indented | 2242 # non-empty line has the parameters of a function header that are indented |
1707 # 4 spaces (because they did not fit in a 80 column line when placed on | 2243 # 4 spaces (because they did not fit in a 80 column line when placed on |
1708 # the same line as the function name). We also check for the case where | 2244 # the same line as the function name). We also check for the case where |
1709 # the previous line is indented 6 spaces, which may happen when the | 2245 # the previous line is indented 6 spaces, which may happen when the |
1710 # initializers of a constructor do not fit into a 80 column line. | 2246 # initializers of a constructor do not fit into a 80 column line. |
1711 exception = False | 2247 exception = False |
1712 if Match(r' {6}\w', prev_line): # Initializer list? | 2248 if Match(r' {6}\w', prev_line): # Initializer list? |
1713 # We are looking for the opening column of initializer list, which | 2249 # We are looking for the opening column of initializer list, which |
(...skipping 11 matching lines...) Expand all Loading... |
1725 # or colon (for initializer lists) we assume that it is the last line of | 2261 # or colon (for initializer lists) we assume that it is the last line of |
1726 # a function header. If we have a colon indented 4 spaces, it is an | 2262 # a function header. If we have a colon indented 4 spaces, it is an |
1727 # initializer list. | 2263 # initializer list. |
1728 exception = (Match(r' {4}\w[^\(]*\)\s*(const\s*)?(\{\s*$|:)', | 2264 exception = (Match(r' {4}\w[^\(]*\)\s*(const\s*)?(\{\s*$|:)', |
1729 prev_line) | 2265 prev_line) |
1730 or Match(r' {4}:', prev_line)) | 2266 or Match(r' {4}:', prev_line)) |
1731 | 2267 |
1732 if not exception: | 2268 if not exception: |
1733 error(filename, linenum, 'whitespace/blank_line', 2, | 2269 error(filename, linenum, 'whitespace/blank_line', 2, |
1734 'Blank line at the start of a code block. Is this needed?') | 2270 'Blank line at the start of a code block. Is this needed?') |
1735 # This doesn't ignore whitespace at the end of a namespace block | 2271 # Ignore blank lines at the end of a block in a long if-else |
1736 # because that is too hard without pairing open/close braces; | |
1737 # however, a special exception is made for namespace closing | |
1738 # brackets which have a comment containing "namespace". | |
1739 # | |
1740 # Also, ignore blank lines at the end of a block in a long if-else | |
1741 # chain, like this: | 2272 # chain, like this: |
1742 # if (condition1) { | 2273 # if (condition1) { |
1743 # // Something followed by a blank line | 2274 # // Something followed by a blank line |
1744 # | 2275 # |
1745 # } else if (condition2) { | 2276 # } else if (condition2) { |
1746 # // Something else | 2277 # // Something else |
1747 # } | 2278 # } |
1748 if linenum + 1 < clean_lines.NumLines(): | 2279 if linenum + 1 < clean_lines.NumLines(): |
1749 next_line = raw[linenum + 1] | 2280 next_line = raw[linenum + 1] |
1750 if (next_line | 2281 if (next_line |
1751 and Match(r'\s*}', next_line) | 2282 and Match(r'\s*}', next_line) |
1752 and next_line.find('namespace') == -1 | |
1753 and next_line.find('} else ') == -1): | 2283 and next_line.find('} else ') == -1): |
1754 error(filename, linenum, 'whitespace/blank_line', 3, | 2284 error(filename, linenum, 'whitespace/blank_line', 3, |
1755 'Blank line at the end of a code block. Is this needed?') | 2285 'Blank line at the end of a code block. Is this needed?') |
1756 | 2286 |
1757 matched = Match(r'\s*(public|protected|private):', prev_line) | 2287 matched = Match(r'\s*(public|protected|private):', prev_line) |
1758 if matched: | 2288 if matched: |
1759 error(filename, linenum, 'whitespace/blank_line', 3, | 2289 error(filename, linenum, 'whitespace/blank_line', 3, |
1760 'Do not leave a blank line after "%s:"' % matched.group(1)) | 2290 'Do not leave a blank line after "%s:"' % matched.group(1)) |
1761 | 2291 |
1762 # Next, we complain if there's a comment too near the text | 2292 # Next, we complain if there's a comment too near the text |
(...skipping 40 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
1803 # many lines (not that this is behavior that I approve of...) | 2333 # many lines (not that this is behavior that I approve of...) |
1804 if Search(r'[\w.]=[\w.]', line) and not Search(r'\b(if|while) ', line): | 2334 if Search(r'[\w.]=[\w.]', line) and not Search(r'\b(if|while) ', line): |
1805 error(filename, linenum, 'whitespace/operators', 4, | 2335 error(filename, linenum, 'whitespace/operators', 4, |
1806 'Missing spaces around =') | 2336 'Missing spaces around =') |
1807 | 2337 |
1808 # It's ok not to have spaces around binary operators like + - * /, but if | 2338 # It's ok not to have spaces around binary operators like + - * /, but if |
1809 # there's too little whitespace, we get concerned. It's hard to tell, | 2339 # there's too little whitespace, we get concerned. It's hard to tell, |
1810 # though, so we punt on this one for now. TODO. | 2340 # though, so we punt on this one for now. TODO. |
1811 | 2341 |
1812 # You should always have whitespace around binary operators. | 2342 # You should always have whitespace around binary operators. |
1813 # Alas, we can't test < or > because they're legitimately used sans spaces | 2343 # |
1814 # (a->b, vector<int> a). The only time we can tell is a < with no >, and | 2344 # Check <= and >= first to avoid false positives with < and >, then |
1815 # only if it's not template params list spilling into the next line. | 2345 # check non-include lines for spacing around < and >. |
1816 match = Search(r'[^<>=!\s](==|!=|<=|>=)[^<>=!\s]', line) | 2346 match = Search(r'[^<>=!\s](==|!=|<=|>=)[^<>=!\s]', line) |
1817 if not match: | |
1818 # Note that while it seems that the '<[^<]*' term in the following | |
1819 # regexp could be simplified to '<.*', which would indeed match | |
1820 # the same class of strings, the [^<] means that searching for the | |
1821 # regexp takes linear rather than quadratic time. | |
1822 if not Search(r'<[^<]*,\s*$', line): # template params spill | |
1823 match = Search(r'[^<>=!\s](<)[^<>=!\s]([^>]|->)*$', line) | |
1824 if match: | 2347 if match: |
1825 error(filename, linenum, 'whitespace/operators', 3, | 2348 error(filename, linenum, 'whitespace/operators', 3, |
1826 'Missing spaces around %s' % match.group(1)) | 2349 'Missing spaces around %s' % match.group(1)) |
1827 # We allow no-spaces around << and >> when used like this: 10<<20, but | 2350 # We allow no-spaces around << when used like this: 10<<20, but |
1828 # not otherwise (particularly, not when used as streams) | 2351 # not otherwise (particularly, not when used as streams) |
1829 match = Search(r'[^0-9\s](<<|>>)[^0-9\s]', line) | 2352 match = Search(r'(\S)(?:L|UL|ULL|l|ul|ull)?<<(\S)', line) |
| 2353 if match and not (match.group(1).isdigit() and match.group(2).isdigit()): |
| 2354 error(filename, linenum, 'whitespace/operators', 3, |
| 2355 'Missing spaces around <<') |
| 2356 elif not Match(r'#.*include', line): |
| 2357 # Avoid false positives on -> |
| 2358 reduced_line = line.replace('->', '') |
| 2359 |
| 2360 # Look for < that is not surrounded by spaces. This is only |
| 2361 # triggered if both sides are missing spaces, even though |
| 2362 # technically should should flag if at least one side is missing a |
| 2363 # space. This is done to avoid some false positives with shifts. |
| 2364 match = Search(r'[^\s<]<([^\s=<].*)', reduced_line) |
| 2365 if (match and |
| 2366 not FindNextMatchingAngleBracket(clean_lines, linenum, match.group(1))): |
| 2367 error(filename, linenum, 'whitespace/operators', 3, |
| 2368 'Missing spaces around <') |
| 2369 |
| 2370 # Look for > that is not surrounded by spaces. Similar to the |
| 2371 # above, we only trigger if both sides are missing spaces to avoid |
| 2372 # false positives with shifts. |
| 2373 match = Search(r'^(.*[^\s>])>[^\s=>]', reduced_line) |
| 2374 if (match and |
| 2375 not FindPreviousMatchingAngleBracket(clean_lines, linenum, |
| 2376 match.group(1))): |
| 2377 error(filename, linenum, 'whitespace/operators', 3, |
| 2378 'Missing spaces around >') |
| 2379 |
| 2380 # We allow no-spaces around >> for almost anything. This is because |
| 2381 # C++11 allows ">>" to close nested templates, which accounts for |
| 2382 # most cases when ">>" is not followed by a space. |
| 2383 # |
| 2384 # We still warn on ">>" followed by alpha character, because that is |
| 2385 # likely due to ">>" being used for right shifts, e.g.: |
| 2386 # value >> alpha |
| 2387 # |
| 2388 # When ">>" is used to close templates, the alphanumeric letter that |
| 2389 # follows would be part of an identifier, and there should still be |
| 2390 # a space separating the template type and the identifier. |
| 2391 # type<type<type>> alpha |
| 2392 match = Search(r'>>[a-zA-Z_]', line) |
1830 if match: | 2393 if match: |
1831 error(filename, linenum, 'whitespace/operators', 3, | 2394 error(filename, linenum, 'whitespace/operators', 3, |
1832 'Missing spaces around %s' % match.group(1)) | 2395 'Missing spaces around >>') |
1833 | 2396 |
1834 # There shouldn't be space around unary operators | 2397 # There shouldn't be space around unary operators |
1835 match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line) | 2398 match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line) |
1836 if match: | 2399 if match: |
1837 error(filename, linenum, 'whitespace/operators', 4, | 2400 error(filename, linenum, 'whitespace/operators', 4, |
1838 'Extra space for operator %s' % match.group(1)) | 2401 'Extra space for operator %s' % match.group(1)) |
1839 | 2402 |
1840 # A pet peeve of mine: no spaces after an if, while, switch, or for | 2403 # A pet peeve of mine: no spaces after an if, while, switch, or for |
1841 match = Search(r' (if\(|for\(|while\(|switch\()', line) | 2404 match = Search(r' (if\(|for\(|while\(|switch\()', line) |
1842 if match: | 2405 if match: |
(...skipping 53 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
1896 # 'delete []' or 'new char * []'. | 2459 # 'delete []' or 'new char * []'. |
1897 if Search(r'\w\s+\[', line) and not Search(r'delete\s+\[', line): | 2460 if Search(r'\w\s+\[', line) and not Search(r'delete\s+\[', line): |
1898 error(filename, linenum, 'whitespace/braces', 5, | 2461 error(filename, linenum, 'whitespace/braces', 5, |
1899 'Extra space before [') | 2462 'Extra space before [') |
1900 | 2463 |
1901 # You shouldn't have a space before a semicolon at the end of the line. | 2464 # You shouldn't have a space before a semicolon at the end of the line. |
1902 # There's a special case for "for" since the style guide allows space before | 2465 # There's a special case for "for" since the style guide allows space before |
1903 # the semicolon there. | 2466 # the semicolon there. |
1904 if Search(r':\s*;\s*$', line): | 2467 if Search(r':\s*;\s*$', line): |
1905 error(filename, linenum, 'whitespace/semicolon', 5, | 2468 error(filename, linenum, 'whitespace/semicolon', 5, |
1906 'Semicolon defining empty statement. Use { } instead.') | 2469 'Semicolon defining empty statement. Use {} instead.') |
1907 elif Search(r'^\s*;\s*$', line): | 2470 elif Search(r'^\s*;\s*$', line): |
1908 error(filename, linenum, 'whitespace/semicolon', 5, | 2471 error(filename, linenum, 'whitespace/semicolon', 5, |
1909 'Line contains only semicolon. If this should be an empty statement, ' | 2472 'Line contains only semicolon. If this should be an empty statement, ' |
1910 'use { } instead.') | 2473 'use {} instead.') |
1911 elif (Search(r'\s+;\s*$', line) and | 2474 elif (Search(r'\s+;\s*$', line) and |
1912 not Search(r'\bfor\b', line)): | 2475 not Search(r'\bfor\b', line)): |
1913 error(filename, linenum, 'whitespace/semicolon', 5, | 2476 error(filename, linenum, 'whitespace/semicolon', 5, |
1914 'Extra space before last semicolon. If this should be an empty ' | 2477 'Extra space before last semicolon. If this should be an empty ' |
1915 'statement, use { } instead.') | 2478 'statement, use {} instead.') |
| 2479 |
| 2480 # In range-based for, we wanted spaces before and after the colon, but |
| 2481 # not around "::" tokens that might appear. |
| 2482 if (Search('for *\(.*[^:]:[^: ]', line) or |
| 2483 Search('for *\(.*[^: ]:[^:]', line)): |
| 2484 error(filename, linenum, 'whitespace/forcolon', 2, |
| 2485 'Missing space around colon in range-based for loop') |
1916 | 2486 |
1917 | 2487 |
1918 def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error): | 2488 def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error): |
1919 """Checks for additional blank line issues related to sections. | 2489 """Checks for additional blank line issues related to sections. |
1920 | 2490 |
1921 Currently the only thing checked here is blank line before protected/private. | 2491 Currently the only thing checked here is blank line before protected/private. |
1922 | 2492 |
1923 Args: | 2493 Args: |
1924 filename: The name of the current file. | 2494 filename: The name of the current file. |
1925 clean_lines: A CleansedLines instance containing the file. | 2495 clean_lines: A CleansedLines instance containing the file. |
1926 class_info: A _ClassInfo objects. | 2496 class_info: A _ClassInfo objects. |
1927 linenum: The number of the line to check. | 2497 linenum: The number of the line to check. |
1928 error: The function to call with any errors found. | 2498 error: The function to call with any errors found. |
1929 """ | 2499 """ |
1930 # Skip checks if the class is small, where small means 25 lines or less. | 2500 # Skip checks if the class is small, where small means 25 lines or less. |
1931 # 25 lines seems like a good cutoff since that's the usual height of | 2501 # 25 lines seems like a good cutoff since that's the usual height of |
1932 # terminals, and any class that can't fit in one screen can't really | 2502 # terminals, and any class that can't fit in one screen can't really |
1933 # be considered "small". | 2503 # be considered "small". |
1934 # | 2504 # |
1935 # Also skip checks if we are on the first line. This accounts for | 2505 # Also skip checks if we are on the first line. This accounts for |
1936 # classes that look like | 2506 # classes that look like |
1937 # class Foo { public: ... }; | 2507 # class Foo { public: ... }; |
1938 # | 2508 # |
1939 # If we didn't find the end of the class, last_line would be zero, | 2509 # If we didn't find the end of the class, last_line would be zero, |
1940 # and the check will be skipped by the first condition. | 2510 # and the check will be skipped by the first condition. |
1941 if (class_info.last_line - class_info.linenum <= 24 or | 2511 if (class_info.last_line - class_info.starting_linenum <= 24 or |
1942 linenum <= class_info.linenum): | 2512 linenum <= class_info.starting_linenum): |
1943 return | 2513 return |
1944 | 2514 |
1945 matched = Match(r'\s*(public|protected|private):', clean_lines.lines[linenum]) | 2515 matched = Match(r'\s*(public|protected|private):', clean_lines.lines[linenum]) |
1946 if matched: | 2516 if matched: |
1947 # Issue warning if the line before public/protected/private was | 2517 # Issue warning if the line before public/protected/private was |
1948 # not a blank line, but don't do this if the previous line contains | 2518 # not a blank line, but don't do this if the previous line contains |
1949 # "class" or "struct". This can happen two ways: | 2519 # "class" or "struct". This can happen two ways: |
1950 # - We are at the beginning of the class. | 2520 # - We are at the beginning of the class. |
1951 # - We are forward-declaring an inner class that is semantically | 2521 # - We are forward-declaring an inner class that is semantically |
1952 # private, but needed to be public for implementation reasons. | 2522 # private, but needed to be public for implementation reasons. |
| 2523 # Also ignores cases where the previous line ends with a backslash as can be |
| 2524 # common when defining classes in C macros. |
1953 prev_line = clean_lines.lines[linenum - 1] | 2525 prev_line = clean_lines.lines[linenum - 1] |
1954 if (not IsBlankLine(prev_line) and | 2526 if (not IsBlankLine(prev_line) and |
1955 not Search(r'\b(class|struct)\b', prev_line)): | 2527 not Search(r'\b(class|struct)\b', prev_line) and |
| 2528 not Search(r'\\$', prev_line)): |
1956 # Try a bit harder to find the beginning of the class. This is to | 2529 # Try a bit harder to find the beginning of the class. This is to |
1957 # account for multi-line base-specifier lists, e.g.: | 2530 # account for multi-line base-specifier lists, e.g.: |
1958 # class Derived | 2531 # class Derived |
1959 # : public Base { | 2532 # : public Base { |
1960 end_class_head = class_info.linenum | 2533 end_class_head = class_info.starting_linenum |
1961 for i in range(class_info.linenum, linenum): | 2534 for i in range(class_info.starting_linenum, linenum): |
1962 if Search(r'\{\s*$', clean_lines.lines[i]): | 2535 if Search(r'\{\s*$', clean_lines.lines[i]): |
1963 end_class_head = i | 2536 end_class_head = i |
1964 break | 2537 break |
1965 if end_class_head < linenum - 1: | 2538 if end_class_head < linenum - 1: |
1966 error(filename, linenum, 'whitespace/blank_line', 3, | 2539 error(filename, linenum, 'whitespace/blank_line', 3, |
1967 '"%s:" should be preceded by a blank line' % matched.group(1)) | 2540 '"%s:" should be preceded by a blank line' % matched.group(1)) |
1968 | 2541 |
1969 | 2542 |
1970 def GetPreviousNonBlankLine(clean_lines, linenum): | 2543 def GetPreviousNonBlankLine(clean_lines, linenum): |
1971 """Return the most recent non-blank line and its line number. | 2544 """Return the most recent non-blank line and its line number. |
(...skipping 29 matching lines...) Expand all Loading... |
2001 """ | 2574 """ |
2002 | 2575 |
2003 line = clean_lines.elided[linenum] # get rid of comments and strings | 2576 line = clean_lines.elided[linenum] # get rid of comments and strings |
2004 | 2577 |
2005 if Match(r'\s*{\s*$', line): | 2578 if Match(r'\s*{\s*$', line): |
2006 # We allow an open brace to start a line in the case where someone | 2579 # We allow an open brace to start a line in the case where someone |
2007 # is using braces in a block to explicitly create a new scope, | 2580 # is using braces in a block to explicitly create a new scope, |
2008 # which is commonly used to control the lifetime of | 2581 # which is commonly used to control the lifetime of |
2009 # stack-allocated variables. We don't detect this perfectly: we | 2582 # stack-allocated variables. We don't detect this perfectly: we |
2010 # just don't complain if the last non-whitespace character on the | 2583 # just don't complain if the last non-whitespace character on the |
2011 # previous non-blank line is ';', ':', '{', or '}'. | 2584 # previous non-blank line is ';', ':', '{', or '}', or if the previous |
| 2585 # line starts a preprocessor block. |
2012 prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] | 2586 prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] |
2013 if not Search(r'[;:}{]\s*$', prevline): | 2587 if (not Search(r'[;:}{]\s*$', prevline) and |
| 2588 not Match(r'\s*#', prevline)): |
2014 error(filename, linenum, 'whitespace/braces', 4, | 2589 error(filename, linenum, 'whitespace/braces', 4, |
2015 '{ should almost always be at the end of the previous line') | 2590 '{ should almost always be at the end of the previous line') |
2016 | 2591 |
2017 # An else clause should be on the same line as the preceding closing brace. | 2592 # An else clause should be on the same line as the preceding closing brace. |
2018 if Match(r'\s*else\s*', line): | 2593 if Match(r'\s*else\s*', line): |
2019 prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] | 2594 prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0] |
2020 if Match(r'\s*}\s*$', prevline): | 2595 if Match(r'\s*}\s*$', prevline): |
2021 error(filename, linenum, 'whitespace/newline', 4, | 2596 error(filename, linenum, 'whitespace/newline', 4, |
2022 'An else should appear on the same line as the preceding }') | 2597 'An else should appear on the same line as the preceding }') |
2023 | 2598 |
(...skipping 33 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
2057 line = prevline + line | 2632 line = prevline + line |
2058 else: | 2633 else: |
2059 break | 2634 break |
2060 if (Search(r'{.*}\s*;', line) and | 2635 if (Search(r'{.*}\s*;', line) and |
2061 line.count('{') == line.count('}') and | 2636 line.count('{') == line.count('}') and |
2062 not Search(r'struct|class|enum|\s*=\s*{', line)): | 2637 not Search(r'struct|class|enum|\s*=\s*{', line)): |
2063 error(filename, linenum, 'readability/braces', 4, | 2638 error(filename, linenum, 'readability/braces', 4, |
2064 "You don't need a ; after a }") | 2639 "You don't need a ; after a }") |
2065 | 2640 |
2066 | 2641 |
| 2642 def CheckEmptyLoopBody(filename, clean_lines, linenum, error): |
| 2643 """Loop for empty loop body with only a single semicolon. |
| 2644 |
| 2645 Args: |
| 2646 filename: The name of the current file. |
| 2647 clean_lines: A CleansedLines instance containing the file. |
| 2648 linenum: The number of the line to check. |
| 2649 error: The function to call with any errors found. |
| 2650 """ |
| 2651 |
| 2652 # Search for loop keywords at the beginning of the line. Because only |
| 2653 # whitespaces are allowed before the keywords, this will also ignore most |
| 2654 # do-while-loops, since those lines should start with closing brace. |
| 2655 line = clean_lines.elided[linenum] |
| 2656 if Match(r'\s*(for|while)\s*\(', line): |
| 2657 # Find the end of the conditional expression |
| 2658 (end_line, end_linenum, end_pos) = CloseExpression( |
| 2659 clean_lines, linenum, line.find('(')) |
| 2660 |
| 2661 # Output warning if what follows the condition expression is a semicolon. |
| 2662 # No warning for all other cases, including whitespace or newline, since we |
| 2663 # have a separate check for semicolons preceded by whitespace. |
| 2664 if end_pos >= 0 and Match(r';', end_line[end_pos:]): |
| 2665 error(filename, end_linenum, 'whitespace/empty_loop_body', 5, |
| 2666 'Empty loop bodies should use {} or continue') |
| 2667 |
| 2668 |
2067 def ReplaceableCheck(operator, macro, line): | 2669 def ReplaceableCheck(operator, macro, line): |
2068 """Determine whether a basic CHECK can be replaced with a more specific one. | 2670 """Determine whether a basic CHECK can be replaced with a more specific one. |
2069 | 2671 |
2070 For example suggest using CHECK_EQ instead of CHECK(a == b) and | 2672 For example suggest using CHECK_EQ instead of CHECK(a == b) and |
2071 similarly for CHECK_GE, CHECK_GT, CHECK_LE, CHECK_LT, CHECK_NE. | 2673 similarly for CHECK_GE, CHECK_GT, CHECK_LE, CHECK_LT, CHECK_NE. |
2072 | 2674 |
2073 Args: | 2675 Args: |
2074 operator: The C++ operator used in the CHECK. | 2676 operator: The C++ operator used in the CHECK. |
2075 macro: The CHECK or EXPECT macro being called. | 2677 macro: The CHECK or EXPECT macro being called. |
2076 line: The current source line. | 2678 line: The current source line. |
(...skipping 48 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
2125 # Encourage replacing plain CHECKs with CHECK_EQ/CHECK_NE/etc. | 2727 # Encourage replacing plain CHECKs with CHECK_EQ/CHECK_NE/etc. |
2126 for operator in ['==', '!=', '>=', '>', '<=', '<']: | 2728 for operator in ['==', '!=', '>=', '>', '<=', '<']: |
2127 if ReplaceableCheck(operator, current_macro, line): | 2729 if ReplaceableCheck(operator, current_macro, line): |
2128 error(filename, linenum, 'readability/check', 2, | 2730 error(filename, linenum, 'readability/check', 2, |
2129 'Consider using %s instead of %s(a %s b)' % ( | 2731 'Consider using %s instead of %s(a %s b)' % ( |
2130 _CHECK_REPLACEMENT[current_macro][operator], | 2732 _CHECK_REPLACEMENT[current_macro][operator], |
2131 current_macro, operator)) | 2733 current_macro, operator)) |
2132 break | 2734 break |
2133 | 2735 |
2134 | 2736 |
| 2737 def CheckAltTokens(filename, clean_lines, linenum, error): |
| 2738 """Check alternative keywords being used in boolean expressions. |
| 2739 |
| 2740 Args: |
| 2741 filename: The name of the current file. |
| 2742 clean_lines: A CleansedLines instance containing the file. |
| 2743 linenum: The number of the line to check. |
| 2744 error: The function to call with any errors found. |
| 2745 """ |
| 2746 line = clean_lines.elided[linenum] |
| 2747 |
| 2748 # Avoid preprocessor lines |
| 2749 if Match(r'^\s*#', line): |
| 2750 return |
| 2751 |
| 2752 # Last ditch effort to avoid multi-line comments. This will not help |
| 2753 # if the comment started before the current line or ended after the |
| 2754 # current line, but it catches most of the false positives. At least, |
| 2755 # it provides a way to workaround this warning for people who use |
| 2756 # multi-line comments in preprocessor macros. |
| 2757 # |
| 2758 # TODO(unknown): remove this once cpplint has better support for |
| 2759 # multi-line comments. |
| 2760 if line.find('/*') >= 0 or line.find('*/') >= 0: |
| 2761 return |
| 2762 |
| 2763 for match in _ALT_TOKEN_REPLACEMENT_PATTERN.finditer(line): |
| 2764 error(filename, linenum, 'readability/alt_tokens', 2, |
| 2765 'Use operator %s instead of %s' % ( |
| 2766 _ALT_TOKEN_REPLACEMENT[match.group(1)], match.group(1))) |
| 2767 |
| 2768 |
2135 def GetLineWidth(line): | 2769 def GetLineWidth(line): |
2136 """Determines the width of the line in column positions. | 2770 """Determines the width of the line in column positions. |
2137 | 2771 |
2138 Args: | 2772 Args: |
2139 line: A string, which may be a Unicode string. | 2773 line: A string, which may be a Unicode string. |
2140 | 2774 |
2141 Returns: | 2775 Returns: |
2142 The width of the line in column positions, accounting for Unicode | 2776 The width of the line in column positions, accounting for Unicode |
2143 combining characters and wide characters. | 2777 combining characters and wide characters. |
2144 """ | 2778 """ |
2145 if isinstance(line, unicode): | 2779 if isinstance(line, unicode): |
2146 width = 0 | 2780 width = 0 |
2147 for uc in unicodedata.normalize('NFC', line): | 2781 for uc in unicodedata.normalize('NFC', line): |
2148 if unicodedata.east_asian_width(uc) in ('W', 'F'): | 2782 if unicodedata.east_asian_width(uc) in ('W', 'F'): |
2149 width += 2 | 2783 width += 2 |
2150 elif not unicodedata.combining(uc): | 2784 elif not unicodedata.combining(uc): |
2151 width += 1 | 2785 width += 1 |
2152 return width | 2786 return width |
2153 else: | 2787 else: |
2154 return len(line) | 2788 return len(line) |
2155 | 2789 |
2156 | 2790 |
2157 def CheckStyle(filename, clean_lines, linenum, file_extension, class_state, | 2791 def CheckStyle(filename, clean_lines, linenum, file_extension, nesting_state, |
2158 error): | 2792 error): |
2159 """Checks rules from the 'C++ style rules' section of cppguide.html. | 2793 """Checks rules from the 'C++ style rules' section of cppguide.html. |
2160 | 2794 |
2161 Most of these rules are hard to test (naming, comment style), but we | 2795 Most of these rules are hard to test (naming, comment style), but we |
2162 do what we can. In particular we check for 2-space indents, line lengths, | 2796 do what we can. In particular we check for 2-space indents, line lengths, |
2163 tab usage, spaces inside code, etc. | 2797 tab usage, spaces inside code, etc. |
2164 | 2798 |
2165 Args: | 2799 Args: |
2166 filename: The name of the current file. | 2800 filename: The name of the current file. |
2167 clean_lines: A CleansedLines instance containing the file. | 2801 clean_lines: A CleansedLines instance containing the file. |
2168 linenum: The number of the line to check. | 2802 linenum: The number of the line to check. |
2169 file_extension: The extension (without the dot) of the filename. | 2803 file_extension: The extension (without the dot) of the filename. |
| 2804 nesting_state: A _NestingState instance which maintains information about |
| 2805 the current stack of nested blocks being parsed. |
2170 error: The function to call with any errors found. | 2806 error: The function to call with any errors found. |
2171 """ | 2807 """ |
2172 | 2808 |
2173 raw_lines = clean_lines.raw_lines | 2809 raw_lines = clean_lines.raw_lines |
2174 line = raw_lines[linenum] | 2810 line = raw_lines[linenum] |
2175 | 2811 |
2176 if line.find('\t') != -1: | 2812 if line.find('\t') != -1: |
2177 error(filename, linenum, 'whitespace/tab', 1, | 2813 error(filename, linenum, 'whitespace/tab', 1, |
2178 'Tab found; better to use spaces') | 2814 'Tab found; better to use spaces') |
2179 | 2815 |
(...skipping 61 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
2241 | 2877 |
2242 if (cleansed_line.count(';') > 1 and | 2878 if (cleansed_line.count(';') > 1 and |
2243 # for loops are allowed two ;'s (and may run over two lines). | 2879 # for loops are allowed two ;'s (and may run over two lines). |
2244 cleansed_line.find('for') == -1 and | 2880 cleansed_line.find('for') == -1 and |
2245 (GetPreviousNonBlankLine(clean_lines, linenum)[0].find('for') == -1 or | 2881 (GetPreviousNonBlankLine(clean_lines, linenum)[0].find('for') == -1 or |
2246 GetPreviousNonBlankLine(clean_lines, linenum)[0].find(';') != -1) and | 2882 GetPreviousNonBlankLine(clean_lines, linenum)[0].find(';') != -1) and |
2247 # It's ok to have many commands in a switch case that fits in 1 line | 2883 # It's ok to have many commands in a switch case that fits in 1 line |
2248 not ((cleansed_line.find('case ') != -1 or | 2884 not ((cleansed_line.find('case ') != -1 or |
2249 cleansed_line.find('default:') != -1) and | 2885 cleansed_line.find('default:') != -1) and |
2250 cleansed_line.find('break;') != -1)): | 2886 cleansed_line.find('break;') != -1)): |
2251 error(filename, linenum, 'whitespace/newline', 4, | 2887 error(filename, linenum, 'whitespace/newline', 0, |
2252 'More than one command on the same line') | 2888 'More than one command on the same line') |
2253 | 2889 |
2254 # Some more style checks | 2890 # Some more style checks |
2255 CheckBraces(filename, clean_lines, linenum, error) | 2891 CheckBraces(filename, clean_lines, linenum, error) |
2256 CheckSpacing(filename, clean_lines, linenum, error) | 2892 CheckEmptyLoopBody(filename, clean_lines, linenum, error) |
| 2893 CheckAccess(filename, clean_lines, linenum, nesting_state, error) |
| 2894 CheckSpacing(filename, clean_lines, linenum, nesting_state, error) |
2257 CheckCheck(filename, clean_lines, linenum, error) | 2895 CheckCheck(filename, clean_lines, linenum, error) |
2258 if class_state and class_state.classinfo_stack: | 2896 CheckAltTokens(filename, clean_lines, linenum, error) |
2259 CheckSectionSpacing(filename, clean_lines, | 2897 classinfo = nesting_state.InnermostClass() |
2260 class_state.classinfo_stack[-1], linenum, error) | 2898 if classinfo: |
| 2899 CheckSectionSpacing(filename, clean_lines, classinfo, linenum, error) |
2261 | 2900 |
2262 | 2901 |
2263 _RE_PATTERN_INCLUDE_NEW_STYLE = re.compile(r'#include +"[^/]+\.h"') | 2902 _RE_PATTERN_INCLUDE_NEW_STYLE = re.compile(r'#include +"[^/]+\.h"') |
2264 _RE_PATTERN_INCLUDE = re.compile(r'^\s*#\s*include\s*([<"])([^>"]*)[>"].*$') | 2903 _RE_PATTERN_INCLUDE = re.compile(r'^\s*#\s*include\s*([<"])([^>"]*)[>"].*$') |
2265 # Matches the first component of a filename delimited by -s and _s. That is: | 2904 # Matches the first component of a filename delimited by -s and _s. That is: |
2266 # _RE_FIRST_COMPONENT.match('foo').group(0) == 'foo' | 2905 # _RE_FIRST_COMPONENT.match('foo').group(0) == 'foo' |
2267 # _RE_FIRST_COMPONENT.match('foo.cc').group(0) == 'foo' | 2906 # _RE_FIRST_COMPONENT.match('foo.cc').group(0) == 'foo' |
2268 # _RE_FIRST_COMPONENT.match('foo-bar_baz.cc').group(0) == 'foo' | 2907 # _RE_FIRST_COMPONENT.match('foo-bar_baz.cc').group(0) == 'foo' |
2269 # _RE_FIRST_COMPONENT.match('foo_bar-baz.cc').group(0) == 'foo' | 2908 # _RE_FIRST_COMPONENT.match('foo_bar-baz.cc').group(0) == 'foo' |
2270 _RE_FIRST_COMPONENT = re.compile(r'^[^-_.]+') | 2909 _RE_FIRST_COMPONENT = re.compile(r'^[^-_.]+') |
(...skipping 276 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
2547 # version, we're willing for const to be before typename or after | 3186 # version, we're willing for const to be before typename or after |
2548 # Don't check the implementation on same line. | 3187 # Don't check the implementation on same line. |
2549 fnline = line.split('{', 1)[0] | 3188 fnline = line.split('{', 1)[0] |
2550 if (len(re.findall(r'\([^()]*\b(?:[\w:]|<[^()]*>)+(\s?&|&\s?)\w+', fnline)) > | 3189 if (len(re.findall(r'\([^()]*\b(?:[\w:]|<[^()]*>)+(\s?&|&\s?)\w+', fnline)) > |
2551 len(re.findall(r'\([^()]*\bconst\s+(?:typename\s+)?(?:struct\s+)?' | 3190 len(re.findall(r'\([^()]*\bconst\s+(?:typename\s+)?(?:struct\s+)?' |
2552 r'(?:[\w:]|<[^()]*>)+(\s?&|&\s?)\w+', fnline)) + | 3191 r'(?:[\w:]|<[^()]*>)+(\s?&|&\s?)\w+', fnline)) + |
2553 len(re.findall(r'\([^()]*\b(?:[\w:]|<[^()]*>)+\s+const(\s?&|&\s?)[\w]+', | 3192 len(re.findall(r'\([^()]*\b(?:[\w:]|<[^()]*>)+\s+const(\s?&|&\s?)[\w]+', |
2554 fnline))): | 3193 fnline))): |
2555 | 3194 |
2556 # We allow non-const references in a few standard places, like functions | 3195 # We allow non-const references in a few standard places, like functions |
2557 # called "swap()" or iostream operators like "<<" or ">>". | 3196 # called "swap()" or iostream operators like "<<" or ">>". We also filter |
| 3197 # out for loops, which lint otherwise mistakenly thinks are functions. |
2558 if not Search( | 3198 if not Search( |
2559 r'(swap|Swap|operator[<>][<>])\s*\(\s*(?:[\w:]|<.*>)+\s*&', | 3199 r'(for|swap|Swap|operator[<>][<>])\s*\(\s*' |
| 3200 r'(?:(?:typename\s*)?[\w:]|<.*>)+\s*&', |
2560 fnline): | 3201 fnline): |
2561 error(filename, linenum, 'runtime/references', 2, | 3202 error(filename, linenum, 'runtime/references', 2, |
2562 'Is this a non-const reference? ' | 3203 'Is this a non-const reference? ' |
2563 'If so, make const or use a pointer.') | 3204 'If so, make const or use a pointer.') |
2564 | 3205 |
2565 # Check to see if they're using an conversion function cast. | 3206 # Check to see if they're using an conversion function cast. |
2566 # I just try to capture the most common basic types, though there are more. | 3207 # I just try to capture the most common basic types, though there are more. |
2567 # Parameterless conversion functions, such as bool(), are allowed as they are | 3208 # Parameterless conversion functions, such as bool(), are allowed as they are |
2568 # probably a member operator declaration or default constructor. | 3209 # probably a member operator declaration or default constructor. |
2569 match = Search( | 3210 match = Search( |
2570 r'(\bnew\s+)?\b' # Grab 'new' operator, if it's there | 3211 r'(\bnew\s+)?\b' # Grab 'new' operator, if it's there |
2571 r'(int|float|double|bool|char|int32|uint32|int64|uint64)\([^)]', line) | 3212 r'(int|float|double|bool|char|int32|uint32|int64|uint64)\([^)]', line) |
2572 if match: | 3213 if match: |
2573 # gMock methods are defined using some variant of MOCK_METHODx(name, type) | 3214 # gMock methods are defined using some variant of MOCK_METHODx(name, type) |
2574 # where type may be float(), int(string), etc. Without context they are | 3215 # where type may be float(), int(string), etc. Without context they are |
2575 # virtually indistinguishable from int(x) casts. Likewise, gMock's | 3216 # virtually indistinguishable from int(x) casts. Likewise, gMock's |
2576 # MockCallback takes a template parameter of the form return_type(arg_type), | 3217 # MockCallback takes a template parameter of the form return_type(arg_type), |
2577 # which looks much like the cast we're trying to detect. | 3218 # which looks much like the cast we're trying to detect. |
2578 if (match.group(1) is None and # If new operator, then this isn't a cast | 3219 if (match.group(1) is None and # If new operator, then this isn't a cast |
2579 not (Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line) or | 3220 not (Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line) or |
2580 Match(r'^\s*MockCallback<.*>', line))): | 3221 Match(r'^\s*MockCallback<.*>', line))): |
2581 error(filename, linenum, 'readability/casting', 4, | 3222 # Try a bit harder to catch gmock lines: the only place where |
2582 'Using deprecated casting style. ' | 3223 # something looks like an old-style cast is where we declare the |
2583 'Use static_cast<%s>(...) instead' % | 3224 # return type of the mocked method, and the only time when we |
2584 match.group(2)) | 3225 # are missing context is if MOCK_METHOD was split across |
| 3226 # multiple lines (for example http://go/hrfhr ), so we only need |
| 3227 # to check the previous line for MOCK_METHOD. |
| 3228 if (linenum == 0 or |
| 3229 not Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(\S+,\s*$', |
| 3230 clean_lines.elided[linenum - 1])): |
| 3231 error(filename, linenum, 'readability/casting', 4, |
| 3232 'Using deprecated casting style. ' |
| 3233 'Use static_cast<%s>(...) instead' % |
| 3234 match.group(2)) |
2585 | 3235 |
2586 CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum], | 3236 CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum], |
2587 'static_cast', | 3237 'static_cast', |
2588 r'\((int|float|double|bool|char|u?int(16|32|64))\)', error) | 3238 r'\((int|float|double|bool|char|u?int(16|32|64))\)', error) |
2589 | 3239 |
2590 # This doesn't catch all cases. Consider (const char * const)"hello". | 3240 # This doesn't catch all cases. Consider (const char * const)"hello". |
2591 # | 3241 # |
2592 # (char *) "foo" should always be a const_cast (reinterpret_cast won't | 3242 # (char *) "foo" should always be a const_cast (reinterpret_cast won't |
2593 # compile). | 3243 # compile). |
2594 if CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum], | 3244 if CheckCStyleCast(filename, linenum, line, clean_lines.raw_lines[linenum], |
(...skipping 101 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
2696 # Check for potential format string bugs like printf(foo). | 3346 # Check for potential format string bugs like printf(foo). |
2697 # We constrain the pattern not to pick things like DocidForPrintf(foo). | 3347 # We constrain the pattern not to pick things like DocidForPrintf(foo). |
2698 # Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str()) | 3348 # Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str()) |
2699 # TODO(sugawarayu): Catch the following case. Need to change the calling | 3349 # TODO(sugawarayu): Catch the following case. Need to change the calling |
2700 # convention of the whole function to process multiple line to handle it. | 3350 # convention of the whole function to process multiple line to handle it. |
2701 # printf( | 3351 # printf( |
2702 # boy_this_is_a_really_long_variable_that_cannot_fit_on_the_prev_line); | 3352 # boy_this_is_a_really_long_variable_that_cannot_fit_on_the_prev_line); |
2703 printf_args = _GetTextInside(line, r'(?i)\b(string)?printf\s*\(') | 3353 printf_args = _GetTextInside(line, r'(?i)\b(string)?printf\s*\(') |
2704 if printf_args: | 3354 if printf_args: |
2705 match = Match(r'([\w.\->()]+)$', printf_args) | 3355 match = Match(r'([\w.\->()]+)$', printf_args) |
2706 if match: | 3356 if match and match.group(1) != '__VA_ARGS__': |
2707 function_name = re.search(r'\b((?:string)?printf)\s*\(', | 3357 function_name = re.search(r'\b((?:string)?printf)\s*\(', |
2708 line, re.I).group(1) | 3358 line, re.I).group(1) |
2709 error(filename, linenum, 'runtime/printf', 4, | 3359 error(filename, linenum, 'runtime/printf', 4, |
2710 'Potential format string bug. Do %s("%%s", %s) instead.' | 3360 'Potential format string bug. Do %s("%%s", %s) instead.' |
2711 % (function_name, match.group(1))) | 3361 % (function_name, match.group(1))) |
2712 | 3362 |
2713 # Check for potential memset bugs like memset(buf, sizeof(buf), 0). | 3363 # Check for potential memset bugs like memset(buf, sizeof(buf), 0). |
2714 match = Search(r'memset\s*\(([^,]*),\s*([^,]*),\s*0\s*\)', line) | 3364 match = Search(r'memset\s*\(([^,]*),\s*([^,]*),\s*0\s*\)', line) |
2715 if match and not Match(r"^''|-?[0-9]+|0x[0-9A-Fa-f]$", match.group(2)): | 3365 if match and not Match(r"^''|-?[0-9]+|0x[0-9A-Fa-f]$", match.group(2)): |
2716 error(filename, linenum, 'runtime/memset', 4, | 3366 error(filename, linenum, 'runtime/memset', 4, |
(...skipping 100 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
2817 if not match: | 3467 if not match: |
2818 return False | 3468 return False |
2819 | 3469 |
2820 # e.g., sizeof(int) | 3470 # e.g., sizeof(int) |
2821 sizeof_match = Match(r'.*sizeof\s*$', line[0:match.start(1) - 1]) | 3471 sizeof_match = Match(r'.*sizeof\s*$', line[0:match.start(1) - 1]) |
2822 if sizeof_match: | 3472 if sizeof_match: |
2823 error(filename, linenum, 'runtime/sizeof', 1, | 3473 error(filename, linenum, 'runtime/sizeof', 1, |
2824 'Using sizeof(type). Use sizeof(varname) instead if possible') | 3474 'Using sizeof(type). Use sizeof(varname) instead if possible') |
2825 return True | 3475 return True |
2826 | 3476 |
| 3477 # operator++(int) and operator--(int) |
| 3478 if (line[0:match.start(1) - 1].endswith(' operator++') or |
| 3479 line[0:match.start(1) - 1].endswith(' operator--')): |
| 3480 return False |
| 3481 |
2827 remainder = line[match.end(0):] | 3482 remainder = line[match.end(0):] |
2828 | 3483 |
2829 # The close paren is for function pointers as arguments to a function. | 3484 # The close paren is for function pointers as arguments to a function. |
2830 # eg, void foo(void (*bar)(int)); | 3485 # eg, void foo(void (*bar)(int)); |
2831 # The semicolon check is a more basic function check; also possibly a | 3486 # The semicolon check is a more basic function check; also possibly a |
2832 # function pointer typedef. | 3487 # function pointer typedef. |
2833 # eg, void foo(int); or void foo(int) const; | 3488 # eg, void foo(int); or void foo(int) const; |
2834 # The equals check is for function pointer assignment. | 3489 # The equals check is for function pointer assignment. |
2835 # eg, void *(*foo)(int) = ... | 3490 # eg, void *(*foo)(int) = ... |
2836 # The > is for MockCallback<...> ... | 3491 # The > is for MockCallback<...> ... |
(...skipping 268 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
3105 clean_lines: A CleansedLines instance containing the file. | 3760 clean_lines: A CleansedLines instance containing the file. |
3106 linenum: The number of the line to check. | 3761 linenum: The number of the line to check. |
3107 error: The function to call with any errors found. | 3762 error: The function to call with any errors found. |
3108 """ | 3763 """ |
3109 raw = clean_lines.raw_lines | 3764 raw = clean_lines.raw_lines |
3110 line = raw[linenum] | 3765 line = raw[linenum] |
3111 match = _RE_PATTERN_EXPLICIT_MAKEPAIR.search(line) | 3766 match = _RE_PATTERN_EXPLICIT_MAKEPAIR.search(line) |
3112 if match: | 3767 if match: |
3113 error(filename, linenum, 'build/explicit_make_pair', | 3768 error(filename, linenum, 'build/explicit_make_pair', |
3114 4, # 4 = high confidence | 3769 4, # 4 = high confidence |
3115 'Omit template arguments from make_pair OR use pair directly OR' | 3770 'For C++11-compatibility, omit template arguments from make_pair' |
3116 ' if appropriate, construct a pair directly') | 3771 ' OR use pair directly OR if appropriate, construct a pair directly') |
3117 | 3772 |
3118 | 3773 |
3119 def ProcessLine(filename, file_extension, | 3774 def ProcessLine(filename, file_extension, clean_lines, line, |
3120 clean_lines, line, include_state, function_state, | 3775 include_state, function_state, nesting_state, error, |
3121 class_state, error, extra_check_functions=[]): | 3776 extra_check_functions=[]): |
3122 """Processes a single line in the file. | 3777 """Processes a single line in the file. |
3123 | 3778 |
3124 Args: | 3779 Args: |
3125 filename: Filename of the file that is being processed. | 3780 filename: Filename of the file that is being processed. |
3126 file_extension: The extension (dot not included) of the file. | 3781 file_extension: The extension (dot not included) of the file. |
3127 clean_lines: An array of strings, each representing a line of the file, | 3782 clean_lines: An array of strings, each representing a line of the file, |
3128 with comments stripped. | 3783 with comments stripped. |
3129 line: Number of line being processed. | 3784 line: Number of line being processed. |
3130 include_state: An _IncludeState instance in which the headers are inserted. | 3785 include_state: An _IncludeState instance in which the headers are inserted. |
3131 function_state: A _FunctionState instance which counts function lines, etc. | 3786 function_state: A _FunctionState instance which counts function lines, etc. |
3132 class_state: A _ClassState instance which maintains information about | 3787 nesting_state: A _NestingState instance which maintains information about |
3133 the current stack of nested class declarations being parsed. | 3788 the current stack of nested blocks being parsed. |
3134 error: A callable to which errors are reported, which takes 4 arguments: | 3789 error: A callable to which errors are reported, which takes 4 arguments: |
3135 filename, line number, error level, and message | 3790 filename, line number, error level, and message |
3136 extra_check_functions: An array of additional check functions that will be | 3791 extra_check_functions: An array of additional check functions that will be |
3137 run on each source line. Each function takes 4 | 3792 run on each source line. Each function takes 4 |
3138 arguments: filename, clean_lines, line, error | 3793 arguments: filename, clean_lines, line, error |
3139 """ | 3794 """ |
3140 raw_lines = clean_lines.raw_lines | 3795 raw_lines = clean_lines.raw_lines |
3141 ParseNolintSuppressions(filename, raw_lines[line], line, error) | 3796 ParseNolintSuppressions(filename, raw_lines[line], line, error) |
| 3797 nesting_state.Update(filename, clean_lines, line, error) |
| 3798 if nesting_state.stack and nesting_state.stack[-1].inline_asm != _NO_ASM: |
| 3799 return |
3142 CheckForFunctionLengths(filename, clean_lines, line, function_state, error) | 3800 CheckForFunctionLengths(filename, clean_lines, line, function_state, error) |
3143 CheckForMultilineCommentsAndStrings(filename, clean_lines, line, error) | 3801 CheckForMultilineCommentsAndStrings(filename, clean_lines, line, error) |
3144 CheckStyle(filename, clean_lines, line, file_extension, class_state, error) | 3802 CheckStyle(filename, clean_lines, line, file_extension, nesting_state, error) |
3145 CheckLanguage(filename, clean_lines, line, file_extension, include_state, | 3803 CheckLanguage(filename, clean_lines, line, file_extension, include_state, |
3146 error) | 3804 error) |
3147 CheckForNonStandardConstructs(filename, clean_lines, line, | 3805 CheckForNonStandardConstructs(filename, clean_lines, line, |
3148 class_state, error) | 3806 nesting_state, error) |
3149 CheckPosixThreading(filename, clean_lines, line, error) | 3807 CheckPosixThreading(filename, clean_lines, line, error) |
3150 CheckInvalidIncrement(filename, clean_lines, line, error) | 3808 CheckInvalidIncrement(filename, clean_lines, line, error) |
3151 CheckMakePairUsesDeduction(filename, clean_lines, line, error) | 3809 CheckMakePairUsesDeduction(filename, clean_lines, line, error) |
3152 for check_fn in extra_check_functions: | 3810 for check_fn in extra_check_functions: |
3153 check_fn(filename, clean_lines, line, error) | 3811 check_fn(filename, clean_lines, line, error) |
3154 | 3812 |
3155 def ProcessFileData(filename, file_extension, lines, error, | 3813 def ProcessFileData(filename, file_extension, lines, error, |
3156 extra_check_functions=[]): | 3814 extra_check_functions=[]): |
3157 """Performs lint checks and reports any errors to the given error function. | 3815 """Performs lint checks and reports any errors to the given error function. |
3158 | 3816 |
3159 Args: | 3817 Args: |
3160 filename: Filename of the file that is being processed. | 3818 filename: Filename of the file that is being processed. |
3161 file_extension: The extension (dot not included) of the file. | 3819 file_extension: The extension (dot not included) of the file. |
3162 lines: An array of strings, each representing a line of the file, with the | 3820 lines: An array of strings, each representing a line of the file, with the |
3163 last element being empty if the file is terminated with a newline. | 3821 last element being empty if the file is terminated with a newline. |
3164 error: A callable to which errors are reported, which takes 4 arguments: | 3822 error: A callable to which errors are reported, which takes 4 arguments: |
3165 filename, line number, error level, and message | 3823 filename, line number, error level, and message |
3166 extra_check_functions: An array of additional check functions that will be | 3824 extra_check_functions: An array of additional check functions that will be |
3167 run on each source line. Each function takes 4 | 3825 run on each source line. Each function takes 4 |
3168 arguments: filename, clean_lines, line, error | 3826 arguments: filename, clean_lines, line, error |
3169 """ | 3827 """ |
3170 lines = (['// marker so line numbers and indices both start at 1'] + lines + | 3828 lines = (['// marker so line numbers and indices both start at 1'] + lines + |
3171 ['// marker so line numbers end in a known way']) | 3829 ['// marker so line numbers end in a known way']) |
3172 | 3830 |
3173 include_state = _IncludeState() | 3831 include_state = _IncludeState() |
3174 function_state = _FunctionState() | 3832 function_state = _FunctionState() |
3175 class_state = _ClassState() | 3833 nesting_state = _NestingState() |
3176 | 3834 |
3177 ResetNolintSuppressions() | 3835 ResetNolintSuppressions() |
3178 | 3836 |
3179 CheckForCopyright(filename, lines, error) | 3837 CheckForCopyright(filename, lines, error) |
3180 | 3838 |
3181 if file_extension == 'h': | 3839 if file_extension == 'h': |
3182 CheckForHeaderGuard(filename, lines, error) | 3840 CheckForHeaderGuard(filename, lines, error) |
3183 | 3841 |
3184 RemoveMultiLineComments(filename, lines, error) | 3842 RemoveMultiLineComments(filename, lines, error) |
3185 clean_lines = CleansedLines(lines) | 3843 clean_lines = CleansedLines(lines) |
3186 for line in xrange(clean_lines.NumLines()): | 3844 for line in xrange(clean_lines.NumLines()): |
3187 ProcessLine(filename, file_extension, clean_lines, line, | 3845 ProcessLine(filename, file_extension, clean_lines, line, |
3188 include_state, function_state, class_state, error, | 3846 include_state, function_state, nesting_state, error, |
3189 extra_check_functions) | 3847 extra_check_functions) |
3190 class_state.CheckFinished(filename, error) | 3848 nesting_state.CheckClassFinished(filename, error) |
3191 | 3849 |
3192 CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error) | 3850 CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error) |
3193 | 3851 |
3194 # We check here rather than inside ProcessLine so that we see raw | 3852 # We check here rather than inside ProcessLine so that we see raw |
3195 # lines rather than "cleaned" lines. | 3853 # lines rather than "cleaned" lines. |
3196 CheckForUnicodeReplacementCharacters(filename, lines, error) | 3854 CheckForUnicodeReplacementCharacters(filename, lines, error) |
3197 | 3855 |
3198 CheckForNewlineAtEOF(filename, lines, error) | 3856 CheckForNewlineAtEOF(filename, lines, error) |
3199 | 3857 |
3200 def ProcessFile(filename, vlevel, extra_check_functions=[]): | 3858 def ProcessFile(filename, vlevel, extra_check_functions=[]): |
(...skipping 93 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
3294 | 3952 |
3295 Args: | 3953 Args: |
3296 args: The command line arguments: | 3954 args: The command line arguments: |
3297 | 3955 |
3298 Returns: | 3956 Returns: |
3299 The list of filenames to lint. | 3957 The list of filenames to lint. |
3300 """ | 3958 """ |
3301 try: | 3959 try: |
3302 (opts, filenames) = getopt.getopt(args, '', ['help', 'output=', 'verbose=', | 3960 (opts, filenames) = getopt.getopt(args, '', ['help', 'output=', 'verbose=', |
3303 'counting=', | 3961 'counting=', |
3304 'filter=']) | 3962 'filter=', |
| 3963 'root=']) |
3305 except getopt.GetoptError: | 3964 except getopt.GetoptError: |
3306 PrintUsage('Invalid arguments.') | 3965 PrintUsage('Invalid arguments.') |
3307 | 3966 |
3308 verbosity = _VerboseLevel() | 3967 verbosity = _VerboseLevel() |
3309 output_format = _OutputFormat() | 3968 output_format = _OutputFormat() |
3310 filters = '' | 3969 filters = '' |
3311 counting_style = '' | 3970 counting_style = '' |
3312 | 3971 |
3313 for (opt, val) in opts: | 3972 for (opt, val) in opts: |
3314 if opt == '--help': | 3973 if opt == '--help': |
3315 PrintUsage(None) | 3974 PrintUsage(None) |
3316 elif opt == '--output': | 3975 elif opt == '--output': |
3317 if not val in ('emacs', 'vs7'): | 3976 if not val in ('emacs', 'vs7', 'eclipse'): |
3318 PrintUsage('The only allowed output formats are emacs and vs7.') | 3977 PrintUsage('The only allowed output formats are emacs, vs7 and eclipse.'
) |
3319 output_format = val | 3978 output_format = val |
3320 elif opt == '--verbose': | 3979 elif opt == '--verbose': |
3321 verbosity = int(val) | 3980 verbosity = int(val) |
3322 elif opt == '--filter': | 3981 elif opt == '--filter': |
3323 filters = val | 3982 filters = val |
3324 if not filters: | 3983 if not filters: |
3325 PrintCategories() | 3984 PrintCategories() |
3326 elif opt == '--counting': | 3985 elif opt == '--counting': |
3327 if val not in ('total', 'toplevel', 'detailed'): | 3986 if val not in ('total', 'toplevel', 'detailed'): |
3328 PrintUsage('Valid counting options are total, toplevel, and detailed') | 3987 PrintUsage('Valid counting options are total, toplevel, and detailed') |
3329 counting_style = val | 3988 counting_style = val |
| 3989 elif opt == '--root': |
| 3990 global _root |
| 3991 _root = val |
3330 | 3992 |
3331 if not filenames: | 3993 if not filenames: |
3332 PrintUsage('No files were specified.') | 3994 PrintUsage('No files were specified.') |
3333 | 3995 |
3334 _SetOutputFormat(output_format) | 3996 _SetOutputFormat(output_format) |
3335 _SetVerboseLevel(verbosity) | 3997 _SetVerboseLevel(verbosity) |
3336 _SetFilters(filters) | 3998 _SetFilters(filters) |
3337 _SetCountingStyle(counting_style) | 3999 _SetCountingStyle(counting_style) |
3338 | 4000 |
3339 return filenames | 4001 return filenames |
(...skipping 12 matching lines...) Expand all Loading... |
3352 _cpplint_state.ResetErrorCounts() | 4014 _cpplint_state.ResetErrorCounts() |
3353 for filename in filenames: | 4015 for filename in filenames: |
3354 ProcessFile(filename, _cpplint_state.verbose_level) | 4016 ProcessFile(filename, _cpplint_state.verbose_level) |
3355 _cpplint_state.PrintErrorCounts() | 4017 _cpplint_state.PrintErrorCounts() |
3356 | 4018 |
3357 sys.exit(_cpplint_state.error_count > 0) | 4019 sys.exit(_cpplint_state.error_count > 0) |
3358 | 4020 |
3359 | 4021 |
3360 if __name__ == '__main__': | 4022 if __name__ == '__main__': |
3361 main() | 4023 main() |
OLD | NEW |