fixup! Upload upstream chromium 76.0.3809.146
[platform/framework/web/chromium-efl.git] / buildtools / checkdeps / cpp_checker.py
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.
4
5 """Checks C++ and Objective-C files for illegal includes."""
6
7 import codecs
8 import os
9 import re
10
11 import results
12 from rules import Rule, MessageRule
13
14
15 class CppChecker(object):
16
17   EXTENSIONS = [
18       '.h',
19       '.cc',
20       '.cpp',
21       '.m',
22       '.mm',
23   ]
24
25   # The maximum number of non-include lines we can see before giving up.
26   _MAX_UNINTERESTING_LINES = 50
27
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
31
32   # This regular expression will be used to extract filenames from include
33   # statements.
34   _EXTRACT_INCLUDE_PATH = re.compile(
35       '[ \t]*#[ \t]*(?:include|import)[ \t]+"(.*)"')
36
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
41
42   def CheckLine(self, rules, line, dependee_path, fail_on_temp_allow=False):
43     """Checks the given line with the given rule set.
44
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
49     if it does not.
50     """
51     found_item = self._EXTRACT_INCLUDE_PATH.match(line)
52     if not found_item:
53       return False, None  # Not a match
54
55     include_path = found_item.group(1)
56
57     if '\\' in include_path:
58       return True, results.DependencyViolation(
59           include_path,
60           MessageRule('Include paths may not include backslashes.'),
61           rules)
62
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.
66       if self._verbose:
67         print ' WARNING: include specified with no directory: ' + include_path
68       return True, None
69
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)
74
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)
79     return True, None
80
81   def CheckFile(self, rules, filepath):
82     if self._verbose:
83       print 'Checking: ' + filepath
84
85     dependee_status = results.DependeeStatus(filepath)
86     ret_val = ''  # We'll collect the error messages in here
87     last_include = 0
88     with codecs.open(filepath, encoding='utf-8') as f:
89       in_if0 = 0
90       for line_num, line in enumerate(f):
91         if line_num - last_include > self._MAX_UNINTERESTING_LINES:
92           break
93
94         line = line.strip()
95
96         # Check to see if we're at / inside an #if 0 block
97         if line.startswith('#if 0'):
98           in_if0 += 1
99           continue
100         if in_if0 > 0:
101           if line.startswith('#if'):
102             in_if0 += 1
103           elif line.startswith('#endif'):
104             in_if0 -= 1
105           continue
106
107         is_include, violation = self.CheckLine(rules, line, filepath)
108         if is_include:
109           last_include = line_num
110         if violation:
111           dependee_status.AddViolation(violation)
112
113     return dependee_status
114
115   @staticmethod
116   def IsCppFile(file_path):
117     """Returns True iff the given path ends in one of the extensions
118     handled by this checker.
119     """
120     return os.path.splitext(file_path)[1] in CppChecker.EXTENSIONS
121
122   def ShouldCheck(self, file_path):
123     """Check if the new #include file path should be presubmit checked.
124
125     Args:
126       file_path: file path to be checked
127
128     Return:
129       bool: True if the file should be checked; False otherwise.
130     """
131     return self.IsCppFile(file_path)