1 # Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 # Use of this source code is governed by a BSD-style license that can be
3 # found in the LICENSE file.
5 """Checks C++ and Objective-C files for illegal includes."""
12 from rules import Rule, MessageRule
15 class CppChecker(object):
25 # The maximum number of non-include lines we can see before giving up.
26 _MAX_UNINTERESTING_LINES = 50
28 # The maximum line length, this is to be efficient in the case of very long
29 # lines (which can't be #includes).
30 _MAX_LINE_LENGTH = 128
32 # This regular expression will be used to extract filenames from include
34 _EXTRACT_INCLUDE_PATH = re.compile(
35 '[ \t]*#[ \t]*(?:include|import)[ \t]+"(.*)"')
37 def __init__(self, verbose, resolve_dotdot=False, root_dir=''):
38 self._verbose = verbose
39 self._resolve_dotdot = resolve_dotdot
40 self._root_dir = root_dir
42 def CheckLine(self, rules, line, dependee_path, fail_on_temp_allow=False):
43 """Checks the given line with the given rule set.
45 Returns a tuple (is_include, dependency_violation) where
46 is_include is True only if the line is an #include or #import
47 statement, and dependency_violation is an instance of
48 results.DependencyViolation if the line violates a rule, or None
51 found_item = self._EXTRACT_INCLUDE_PATH.match(line)
53 return False, None # Not a match
55 include_path = found_item.group(1)
57 if '\\' in include_path:
58 return True, results.DependencyViolation(
60 MessageRule('Include paths may not include backslashes.'),
63 if '/' not in include_path:
64 # Don't fail when no directory is specified. We may want to be more
65 # strict about this in the future.
67 print ' WARNING: include specified with no directory: ' + include_path
70 if self._resolve_dotdot and '../' in include_path:
71 dependee_dir = os.path.dirname(dependee_path)
72 include_path = os.path.join(dependee_dir, include_path)
73 include_path = os.path.relpath(include_path, self._root_dir)
75 rule = rules.RuleApplyingTo(include_path, dependee_path)
76 if (rule.allow == Rule.DISALLOW or
77 (fail_on_temp_allow and rule.allow == Rule.TEMP_ALLOW)):
78 return True, results.DependencyViolation(include_path, rule, rules)
81 def CheckFile(self, rules, filepath):
83 print 'Checking: ' + filepath
85 dependee_status = results.DependeeStatus(filepath)
86 ret_val = '' # We'll collect the error messages in here
88 with codecs.open(filepath, encoding='utf-8') as f:
90 for line_num, line in enumerate(f):
91 if line_num - last_include > self._MAX_UNINTERESTING_LINES:
96 # Check to see if we're at / inside an #if 0 block
97 if line.startswith('#if 0'):
101 if line.startswith('#if'):
103 elif line.startswith('#endif'):
107 is_include, violation = self.CheckLine(rules, line, filepath)
109 last_include = line_num
111 dependee_status.AddViolation(violation)
113 return dependee_status
116 def IsCppFile(file_path):
117 """Returns True iff the given path ends in one of the extensions
118 handled by this checker.
120 return os.path.splitext(file_path)[1] in CppChecker.EXTENSIONS
122 def ShouldCheck(self, file_path):
123 """Check if the new #include file path should be presubmit checked.
126 file_path: file path to be checked
129 bool: True if the file should be checked; False otherwise.
131 return self.IsCppFile(file_path)