Debian Codegraph @

tools/check_python_h_first.py

raw
1 #!/usr/bin/env python
2 """Check that Python.h is included before any stdlib headers.
3
4 May be a bit overzealous, but it should get the job done.
5 """
6 import argparse
7 import fnmatch
8 import os.path
9 import re
10 import subprocess
11 import sys
12
13 from get_submodule_paths import get_submodule_paths
14
15 HEADER_PATTERN = re.compile(
16 r'^\s*#\s*include\s*[<"]((?:\w+/)*\w+(?:\.h[hp+]{0,2})?)[>"]\s*$'
17 )
18
19 PYTHON_INCLUDING_HEADERS = [
20 "Python.h",
21 # This isn't all of Python.h, but it is the visibility macros
22 "pyconfig.h",
23 "numpy/npy_common.h",
24 "numpy/npy_math.h",
25 "numpy/arrayobject.h",
26 "numpy/ndarrayobject.h",
27 "numpy/ndarraytypes.h",
28 "numpy/random/distributions.h",
29 "npy_sort.h",
30 "npy_config.h",
31 "common.h",
32 "npy_cpu_features.h",
33 # Boost::Python
34 "boost/python.hpp",
35 ]
36 LEAF_HEADERS = [
37 "numpy/numpyconfig.h",
38 "numpy/npy_os.h",
39 "numpy/npy_cpu.h",
40 "numpy/utils.h",
41 ]
42
43 C_CPP_EXTENSIONS = (".c", ".h", ".cpp", ".hpp", ".cc", ".hh", ".cxx", ".hxx")
44 # check against list in diff_files
45
46 PARSER = argparse.ArgumentParser(description=__doc__)
47 PARSER.add_argument(
48 "files",
49 nargs="*",
50 help="Lint these files or directories; use **/*.c to lint all files\n"
51 "Expects relative paths",
52 )
53
54
55 def check_python_h_included_first(name_to_check: str) -> int:
56 """Check that the passed file includes Python.h first if it does at all.
57
58 Perhaps overzealous, but that should work around concerns with
59 recursion.
60
61 Parameters
62 ----------
63 name_to_check : str
64 The name of the file to check.
65
66 Returns
67 -------
68 int
69 The number of headers before Python.h
70 """
71 included_python = False
72 included_non_python_header = []
73 warned_python_construct = False
74 basename_to_check = os.path.basename(name_to_check)
75 in_comment = False
76 includes_headers = False
77 with open(name_to_check) as in_file:
78 for i, line in enumerate(in_file, 1):
79 # Very basic comment parsing
80 # Assumes /*...*/ comments are on their own lines
81 if "/*" in line:
82 if "*/" not in line:
83 in_comment = True
84 # else-branch could use regex to remove comment and continue
85 continue
86 if in_comment:
87 if "*/" in line:
88 in_comment = False
89 continue
90 line = line.split("//", 1)[0].strip()
91 match = HEADER_PATTERN.match(line)
92 if match:
93 includes_headers = True
94 this_header = match.group(1)
95 if this_header in PYTHON_INCLUDING_HEADERS:
96 if included_non_python_header and not included_python:
97 # Headers before python-including header
98 print(
99 f"Header before Python.h in file {name_to_check:s}\n"
100 f"Python.h on line {i:d}, other header(s) on line(s)"
101 f" {included_non_python_header}",
102 file=sys.stderr,
103 )
104 # else: # no headers before python-including header
105 included_python = True
106 PYTHON_INCLUDING_HEADERS.append(basename_to_check)
107 if os.path.dirname(name_to_check).endswith("include/numpy"):
108 PYTHON_INCLUDING_HEADERS.append(f"numpy/{basename_to_check:s}")
109 # We just found out where Python.h comes in this file
110 break
111 elif this_header in LEAF_HEADERS:
112 # This header is just defines, so it won't include
113 # the system headers that cause problems
114 continue
115 elif not included_python and (
116 "numpy/" in this_header
117 and this_header not in LEAF_HEADERS
118 or "python" in this_header.lower()
119 ):
120 print(
121 f"Python.h not included before python-including header "
122 f"in file {name_to_check:s}\n"
123 f"{this_header:s} on line {i:d}",
124 file=sys.stderr,
125 )
126 included_python = True
127 PYTHON_INCLUDING_HEADERS.append(basename_to_check)
128 elif not included_python and this_header not in LEAF_HEADERS:
129 included_non_python_header.append(i)
130 elif (
131 not included_python
132 and not warned_python_construct
133 and ".h" not in basename_to_check
134 ) and ("py::" in line or "PYBIND11_" in line):
135 print(
136 "Python-including header not used before python constructs "
137 f"in file {name_to_check:s}\nConstruct on line {i:d}",
138 file=sys.stderr,
139 )
140 warned_python_construct = True
141 if not includes_headers:
142 LEAF_HEADERS.append(basename_to_check)
143 return included_python and len(included_non_python_header)
144
145
146 def sort_order(path: str) -> tuple[int, str]:
147 if "include/numpy" in path:
148 # Want to process numpy/*.h first, to work out which of those
149 # include Python.h directly
150 priority = 0x00
151 elif "h" in os.path.splitext(path)[1].lower():
152 # Then other headers, which tend to include numpy/*.h
153 priority = 0x10
154 else:
155 # Source files after headers, to give the best chance of
156 # properly checking whether they include Python.h
157 priority = 0x20
158 if "common" in path:
159 priority -= 8
160 path_basename = os.path.basename(path)
161 if path_basename.startswith("npy_"):
162 priority -= 4
163 elif path_basename.startswith("npy"):
164 priority -= 3
165 elif path_basename.startswith("np"):
166 priority -= 2
167 if "config" in path_basename:
168 priority -= 1
169 return priority, path
170
171
172 def process_files(file_list: list[str]) -> int:
173 n_out_of_order = 0
174 submodule_paths = get_submodule_paths()
175 root_directory = os.path.dirname(os.path.dirname(__file__))
176 for name_to_check in sorted(file_list, key=sort_order):
177 name_to_check = os.path.join(root_directory, name_to_check)
178 if any(submodule_path in name_to_check for submodule_path in submodule_paths):
179 continue
180 if ".dispatch." in name_to_check:
181 continue
182 try:
183 n_out_of_order += check_python_h_included_first(name_to_check)
184 except UnicodeDecodeError:
185 print(f"File {name_to_check:s} not utf-8", sys.stdout)
186 return n_out_of_order
187
188
189 def find_c_cpp_files(root: str) -> list[str]:
190
191 result = []
192
193 for dirpath, dirnames, filenames in os.walk(root):
194 # I'm assuming other people have checked boost
195 for name in ("build", ".git", "boost"):
196 try:
197 dirnames.remove(name)
198 except ValueError:
199 pass
200 for name in fnmatch.filter(dirnames, "*.p"):
201 dirnames.remove(name)
202 result.extend(
203 [
204 os.path.join(dirpath, name)
205 for name in filenames
206 if os.path.splitext(name)[1].lower() in C_CPP_EXTENSIONS
207 ]
208 )
209 # Check the headers before the source files
210 result.sort(key=lambda path: "h" in os.path.splitext(path)[1], reverse=True)
211 return result
212
213
214 def diff_files(sha: str) -> list[str]:
215 """Find the diff since the given SHA.
216
217 Adapted from lint.py
218 """
219 res = subprocess.run(
220 [
221 "git",
222 "diff",
223 "--name-only",
224 "--diff-filter=ACMR",
225 "-z",
226 sha,
227 "--",
228 # Check against C_CPP_EXTENSIONS
229 "*.[chCH]",
230 "*.[ch]pp",
231 "*.[ch]xx",
232 "*.cc",
233 "*.hh",
234 ],
235 stdout=subprocess.PIPE,
236 encoding="utf-8",
237 )
238 res.check_returncode()
239 return [f for f in res.stdout.split("\0") if f]
240
241
242 if __name__ == "__main__":
243 args = PARSER.parse_args()
244
245 if len(args.files) == 0:
246 files = find_c_cpp_files("numpy")
247 else:
248 files = args.files
249 if len(files) == 1 and os.path.isdir(files[0]):
250 files = find_c_cpp_files(files[0])
251
252 # See which of the headers include Python.h and add them to the list
253 n_out_of_order = process_files(files)
254 sys.exit(n_out_of_order)