]> git.ipfire.org Git - thirdparty/gcc.git/blame - contrib/check_GNU_style_lib.py
x86: Define __APX_F__ for -mapxf
[thirdparty/gcc.git] / contrib / check_GNU_style_lib.py
CommitLineData
b7fc9ae0 1#!/usr/bin/env python3
81f86cb9 2
a945c346 3# Copyright (C) 2017-2024 Free Software Foundation, Inc.
b7fc9ae0
TV
4#
5# Checks some of the GNU style formatting rules in a set of patches.
6# The script is a rewritten of the same bash script and should eventually
7# replace the former script.
8#
9# This file is part of GCC.
10#
11# GCC is free software; you can redistribute it and/or modify it under
12# the terms of the GNU General Public License as published by the Free
13# Software Foundation; either version 3, or (at your option) any later
14# version.
15#
16# GCC is distributed in the hope that it will be useful, but WITHOUT ANY
17# WARRANTY; without even the implied warranty of MERCHANTABILITY or
18# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
19# for more details.
20#
21# You should have received a copy of the GNU General Public License
22# along with GCC; see the file COPYING3. If not see
29abd09a 23# <http://www.gnu.org/licenses/>.
b7fc9ae0
TV
24#
25# The script requires python packages, which can be installed via pip3
26# like this:
27# $ pip3 install unidiff termcolor
28
29import sys
30import re
31import unittest
32
76baf5ca
TV
33def import_pip3(*args):
34 missing=[]
35 for (module, names) in args:
36 try:
37 lib = __import__(module)
38 except ImportError:
39 missing.append(module)
40 continue
41 if not isinstance(names, list):
42 names=[names]
43 for name in names:
44 globals()[name]=getattr(lib, name)
45 if len(missing) > 0:
46 missing_and_sep = ' and '.join(missing)
47 missing_space_sep = ' '.join(missing)
48 print('%s %s missing (run: pip3 install %s)'
49 % (missing_and_sep,
50 ("module is" if len(missing) == 1 else "modules are"),
51 missing_space_sep))
52 exit(3)
b7fc9ae0 53
76baf5ca
TV
54import_pip3(('termcolor', 'colored'),
55 ('unidiff', 'PatchSet'))
b7fc9ae0
TV
56
57from itertools import *
58
59ws_char = '█'
60ts = 8
61
62def error_string(s):
63 return colored(s, 'red', attrs = ['bold'])
64
65class CheckError:
66 def __init__(self, filename, lineno, console_error, error_message,
67 column = -1):
68 self.filename = filename
69 self.lineno = lineno
70 self.console_error = console_error
71 self.error_message = error_message
72 self.column = column
73
74 def error_location(self):
75 return '%s:%d:%d:' % (self.filename, self.lineno,
76 self.column if self.column != -1 else -1)
77
78class LineLengthCheck:
79 def __init__(self):
80 self.limit = 80
81 self.expanded_tab = ' ' * ts
82
83 def check(self, filename, lineno, line):
84 line_expanded = line.replace('\t', self.expanded_tab)
85 if len(line_expanded) > self.limit:
86 return CheckError(filename, lineno,
87 line_expanded[:self.limit]
88 + error_string(line_expanded[self.limit:]),
89 'lines should not exceed 80 characters', self.limit)
90
91 return None
92
93class SpacesCheck:
94 def __init__(self):
95 self.expanded_tab = ' ' * ts
96
97 def check(self, filename, lineno, line):
98 i = line.find(self.expanded_tab)
99 if i != -1:
100 return CheckError(filename, lineno,
101 line.replace(self.expanded_tab, error_string(ws_char * ts)),
102 'blocks of 8 spaces should be replaced with tabs', i)
103
ca44d7f4
ML
104class SpacesAndTabsMixedCheck:
105 def __init__(self):
106 self.re = re.compile('\ \t')
107
108 def check(self, filename, lineno, line):
109 stripped = line.lstrip()
110 start = line[:len(line) - len(stripped)]
111 if self.re.search(line):
112 return CheckError(filename, lineno,
113 error_string(start.replace('\t', ws_char * ts)) + line[len(start):],
114 'a space should not precede a tab', 0)
115
b7fc9ae0
TV
116class TrailingWhitespaceCheck:
117 def __init__(self):
118 self.re = re.compile('(\s+)$')
119
120 def check(self, filename, lineno, line):
0a71c876 121 assert(len(line) == 0 or line[-1] != '\n')
b7fc9ae0
TV
122 m = self.re.search(line)
123 if m != None:
124 return CheckError(filename, lineno,
125 line[:m.start(1)] + error_string(ws_char * len(m.group(1)))
126 + line[m.end(1):],
127 'trailing whitespace', m.start(1))
128
129class SentenceSeparatorCheck:
130 def __init__(self):
131 self.re = re.compile('\w\.(\s|\s{3,})\w')
132
133 def check(self, filename, lineno, line):
134 m = self.re.search(line)
135 if m != None:
136 return CheckError(filename, lineno,
137 line[:m.start(1)] + error_string(ws_char * len(m.group(1)))
138 + line[m.end(1):],
139 'dot, space, space, new sentence', m.start(1))
140
141class SentenceEndOfCommentCheck:
142 def __init__(self):
143 self.re = re.compile('\w\.(\s{0,1}|\s{3,})\*/')
144
145 def check(self, filename, lineno, line):
146 m = self.re.search(line)
147 if m != None:
148 return CheckError(filename, lineno,
149 line[:m.start(1)] + error_string(ws_char * len(m.group(1)))
150 + line[m.end(1):],
151 'dot, space, space, end of comment', m.start(1))
152
153class SentenceDotEndCheck:
154 def __init__(self):
155 self.re = re.compile('\w(\s*\*/)')
156
157 def check(self, filename, lineno, line):
158 m = self.re.search(line)
159 if m != None:
160 return CheckError(filename, lineno,
161 line[:m.start(1)] + error_string(m.group(1)) + line[m.end(1):],
162 'dot, space, space, end of comment', m.start(1))
163
164class FunctionParenthesisCheck:
165 # TODO: filter out GTY stuff
166 def __init__(self):
167 self.re = re.compile('\w(\s{2,})?(\()')
168
169 def check(self, filename, lineno, line):
170 if '#define' in line:
171 return None
172
173 m = self.re.search(line)
174 if m != None:
175 return CheckError(filename, lineno,
176 line[:m.start(2)] + error_string(m.group(2)) + line[m.end(2):],
177 'there should be exactly one space between function name ' \
178 'and parenthesis', m.start(2))
179
180class SquareBracketCheck:
181 def __init__(self):
182 self.re = re.compile('\w\s+(\[)')
183
184 def check(self, filename, lineno, line):
895ec195
PN
185 if filename.endswith('.md'):
186 return None
187
b7fc9ae0
TV
188 m = self.re.search(line)
189 if m != None:
190 return CheckError(filename, lineno,
191 line[:m.start(1)] + error_string(m.group(1)) + line[m.end(1):],
192 'there should be no space before a left square bracket',
193 m.start(1))
194
195class ClosingParenthesisCheck:
196 def __init__(self):
197 self.re = re.compile('\S\s+(\))')
198
199 def check(self, filename, lineno, line):
200 m = self.re.search(line)
201 if m != None:
202 return CheckError(filename, lineno,
203 line[:m.start(1)] + error_string(m.group(1)) + line[m.end(1):],
204 'there should be no space before closing parenthesis',
205 m.start(1))
206
207class BracesOnSeparateLineCheck:
208 # This will give false positives for C99 compound literals.
209
210 def __init__(self):
211 self.re = re.compile('(\)|else)\s*({)')
212
213 def check(self, filename, lineno, line):
214 m = self.re.search(line)
215 if m != None:
216 return CheckError(filename, lineno,
217 line[:m.start(2)] + error_string(m.group(2)) + line[m.end(2):],
218 'braces should be on a separate line', m.start(2))
219
220class TrailinigOperatorCheck:
221 def __init__(self):
222 regex = '^\s.*(([^a-zA-Z_]\*)|([-%<=&|^?])|([^*]/)|([^:][+]))$'
223 self.re = re.compile(regex)
224
225 def check(self, filename, lineno, line):
226 m = self.re.search(line)
227 if m != None:
228 return CheckError(filename, lineno,
229 line[:m.start(1)] + error_string(m.group(1)) + line[m.end(1):],
230 'trailing operator', m.start(1))
231
232class LineLengthTest(unittest.TestCase):
233 def setUp(self):
234 self.check = LineLengthCheck()
235
236 def test_line_length_check_basic(self):
237 r = self.check.check('foo', 123, self.check.limit * 'a' + ' = 123;')
238 self.assertIsNotNone(r)
239 self.assertEqual('foo', r.filename)
240 self.assertEqual(80, r.column)
241 self.assertEqual(r.console_error,
242 self.check.limit * 'a' + error_string(' = 123;'))
243
0a71c876
TV
244class TrailingWhitespaceTest(unittest.TestCase):
245 def setUp(self):
246 self.check = TrailingWhitespaceCheck()
247
248 def test_trailing_whitespace_check_basic(self):
249 r = self.check.check('foo', 123, 'a = 123;')
250 self.assertIsNone(r)
251 r = self.check.check('foo', 123, 'a = 123; ')
252 self.assertIsNotNone(r)
253 r = self.check.check('foo', 123, 'a = 123;\t')
254 self.assertIsNotNone(r)
255
ca44d7f4
ML
256class SpacesAndTabsMixedTest(unittest.TestCase):
257 def setUp(self):
258 self.check = SpacesAndTabsMixedCheck()
259
260 def test_trailing_whitespace_check_basic(self):
261 r = self.check.check('foo', 123, ' \ta = 123;')
262 self.assertEqual('foo', r.filename)
263 self.assertEqual(0, r.column)
264 self.assertIsNotNone(r.console_error)
265 r = self.check.check('foo', 123, ' \t a = 123;')
266 self.assertIsNotNone(r.console_error)
267 r = self.check.check('foo', 123, '\t a = 123;')
268 self.assertIsNone(r)
269
b0451799 270def check_GNU_style_file(file, format):
b7fc9ae0
TV
271 checks = [LineLengthCheck(), SpacesCheck(), TrailingWhitespaceCheck(),
272 SentenceSeparatorCheck(), SentenceEndOfCommentCheck(),
273 SentenceDotEndCheck(), FunctionParenthesisCheck(),
274 SquareBracketCheck(), ClosingParenthesisCheck(),
ca44d7f4
ML
275 BracesOnSeparateLineCheck(), TrailinigOperatorCheck(),
276 SpacesAndTabsMixedCheck()]
b7fc9ae0
TV
277 errors = []
278
b0451799 279 patch = PatchSet(file)
b7fc9ae0
TV
280
281 for pfile in patch.added_files + patch.modified_files:
282 t = pfile.target_file.lstrip('b/')
283 # Skip testsuite files
68aa3c08 284 if 'testsuite' in t or t.endswith('.py'):
b7fc9ae0
TV
285 continue
286
287 for hunk in pfile:
288 delta = 0
289 for line in hunk:
290 if line.is_added and line.target_line_no != None:
291 for check in checks:
0a71c876
TV
292 line_chomp = line.value.replace('\n', '')
293 e = check.check(t, line.target_line_no, line_chomp)
b7fc9ae0
TV
294 if e != None:
295 errors.append(e)
296
297 if format == 'stdio':
298 fn = lambda x: x.error_message
299 i = 1
300 for (k, errors) in groupby(sorted(errors, key = fn), fn):
301 errors = list(errors)
302 print('=== ERROR type #%d: %s (%d error(s)) ==='
303 % (i, k, len(errors)))
304 i += 1
305 for e in errors:
306 print(e.error_location () + e.console_error)
307 print()
308
309 exit(0 if len(errors) == 0 else 1)
310 elif format == 'quickfix':
311 f = 'errors.err'
312 with open(f, 'w+') as qf:
313 for e in errors:
314 qf.write('%s%s\n' % (e.error_location(), e.error_message))
315 if len(errors) == 0:
316 exit(0)
317 else:
318 print('%d error(s) written to %s file.' % (len(errors), f))
319 exit(1)
320 else:
321 assert False
322
323if __name__ == '__main__':
324 unittest.main()