]> git.lizzy.rs Git - rust.git/blob - util/update_lints.py
Merge #3353
[rust.git] / util / update_lints.py
1 #!/usr/bin/env python
2
3 # Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
4 # file at the top-level directory of this distribution and at
5 # http://rust-lang.org/COPYRIGHT.
6 #
7 # Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
8 # http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
9 # <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
10 # option. This file may not be copied, modified, or distributed
11 # except according to those terms.
12
13
14 # Generate a Markdown table of all lints, and put it in README.md.
15 # With -n option, only print the new table to stdout.
16 # With -c option, print a warning and set exit status to 1 if a file would be
17 # changed.
18
19 import os
20 import re
21 import sys
22 from subprocess import call
23
24 declare_deprecated_lint_re = re.compile(r'''
25     declare_deprecated_lint! \s* [{(] \s*
26     pub \s+ (?P<name>[A-Z_][A-Z_0-9]*) \s*,\s*
27     " (?P<desc>(?:[^"\\]+|\\.)*) " \s* [})]
28 ''', re.VERBOSE | re.DOTALL)
29
30 declare_clippy_lint_re = re.compile(r'''
31     declare_clippy_lint! \s* [{(] \s*
32     pub \s+ (?P<name>[A-Z_][A-Z_0-9]*) \s*,\s*
33     (?P<cat>[a-z_]+) \s*,\s*
34     " (?P<desc>(?:[^"\\]+|\\.)*) " \s* [})]
35 ''', re.VERBOSE | re.DOTALL)
36
37 nl_escape_re = re.compile(r'\\\n\s*')
38
39 docs_link = 'https://rust-lang-nursery.github.io/rust-clippy/master/index.html'
40
41
42 def collect(deprecated_lints, clippy_lints, fn):
43     """Collect all lints from a file.
44
45     Adds entries to the lints list as `(module, name, level, desc)`.
46     """
47     with open(fn) as fp:
48         code = fp.read()
49
50     for match in declare_deprecated_lint_re.finditer(code):
51         # remove \-newline escapes from description string
52         desc = nl_escape_re.sub('', match.group('desc'))
53         deprecated_lints.append((os.path.splitext(os.path.basename(fn))[0],
54                                 match.group('name').lower(),
55                                 desc.replace('\\"', '"')))
56
57     for match in declare_clippy_lint_re.finditer(code):
58         # remove \-newline escapes from description string
59         desc = nl_escape_re.sub('', match.group('desc'))
60         cat = match.group('cat')
61         if cat in ('internal', 'internal_warn'):
62             continue
63         module_name = os.path.splitext(os.path.basename(fn))[0]
64         if module_name == 'mod':
65             module_name = os.path.basename(os.path.dirname(fn))
66         clippy_lints[cat].append((module_name,
67                                   match.group('name').lower(),
68                                   "allow",
69                                   desc.replace('\\"', '"')))
70
71
72 def gen_group(lints):
73     """Write lint group (list of all lints in the form module::NAME)."""
74     for (module, name, _, _) in sorted(lints):
75         yield '        %s::%s,\n' % (module, name.upper())
76
77
78 def gen_mods(lints):
79     """Declare modules"""
80
81     for module in sorted(set(lint[0] for lint in lints)):
82         yield 'pub mod %s;\n' % module
83
84
85 def gen_deprecated(lints):
86     """Declare deprecated lints"""
87
88     for lint in lints:
89         yield '    store.register_removed(\n'
90         yield '        "%s",\n' % lint[1]
91         yield '        "%s",\n' % lint[2]
92         yield '    );\n'
93
94
95 def replace_region(fn, region_start, region_end, callback,
96                    replace_start=True, write_back=True):
97     """Replace a region in a file delimited by two lines matching regexes.
98
99     A callback is called to write the new region.  If `replace_start` is true,
100     the start delimiter line is replaced as well.  The end delimiter line is
101     never replaced.
102     """
103     # read current content
104     with open(fn) as fp:
105         lines = list(fp)
106
107     found = False
108
109     # replace old region with new region
110     new_lines = []
111     in_old_region = False
112     for line in lines:
113         if in_old_region:
114             if re.search(region_end, line):
115                 in_old_region = False
116                 new_lines.extend(callback())
117                 new_lines.append(line)
118         elif re.search(region_start, line):
119             if not replace_start:
120                 new_lines.append(line)
121             # old region starts here
122             in_old_region = True
123             found = True
124         else:
125             new_lines.append(line)
126
127     if not found:
128         print("regex " + region_start + " not found")
129
130     # write back to file
131     if write_back:
132         with open(fn, 'w') as fp:
133             fp.writelines(new_lines)
134
135     # if something changed, return true
136     return lines != new_lines
137
138
139 def main(print_only=False, check=False):
140     deprecated_lints = []
141     clippy_lints = {
142         "correctness": [],
143         "style": [],
144         "complexity": [],
145         "perf": [],
146         "restriction": [],
147         "pedantic": [],
148         "cargo": [],
149         "nursery": [],
150     }
151
152     # check directory
153     if not os.path.isfile('clippy_lints/src/lib.rs'):
154         print('Error: call this script from clippy checkout directory!')
155         return
156
157     # collect all lints from source files
158     for root, dirs, files in os.walk('clippy_lints/src'):
159         for fn in files:
160             if fn.endswith('.rs'):
161                 collect(deprecated_lints, clippy_lints,
162                         os.path.join(root, fn))
163
164     # determine version
165     with open('Cargo.toml') as fp:
166         for line in fp:
167             if line.startswith('version ='):
168                 clippy_version = line.split()[2].strip('"')
169                 break
170         else:
171             print('Error: version not found in Cargo.toml!')
172             return
173
174     all_lints = []
175     clippy_lint_groups = [
176         "correctness",
177         "style",
178         "complexity",
179         "perf",
180     ]
181     clippy_lint_list = []
182     for x in clippy_lint_groups:
183         clippy_lint_list += clippy_lints[x]
184     for _, value in clippy_lints.iteritems():
185         all_lints += value
186
187     if print_only:
188         call(["./util/dev", "update_lints", "--print-only"])
189         return
190
191     # update the lint counter in README.md
192     changed = replace_region(
193         'README.md',
194         r'^\[There are \d+ lints included in this crate!\]\(https://rust-lang-nursery.github.io/rust-clippy/master/index.html\)$', "",
195         lambda: ['[There are %d lints included in this crate!](https://rust-lang-nursery.github.io/rust-clippy/master/index.html)\n' %
196                  (len(all_lints))],
197         write_back=not check)
198
199     # update the links in the CHANGELOG
200     changed |= replace_region(
201         'CHANGELOG.md',
202         "<!-- begin autogenerated links to lint list -->",
203         "<!-- end autogenerated links to lint list -->",
204         lambda: ["[`{0}`]: {1}#{0}\n".format(l[1], docs_link) for l in
205                  sorted(all_lints + deprecated_lints,
206                         key=lambda l: l[1])],
207         replace_start=False, write_back=not check)
208
209     # update version of clippy_lints in Cargo.toml
210     changed |= replace_region(
211         'Cargo.toml', r'# begin automatic update', '# end automatic update',
212         lambda: ['clippy_lints = { version = "%s", path = "clippy_lints" }\n' %
213                  clippy_version],
214         replace_start=False, write_back=not check)
215
216     # update version of clippy_lints in Cargo.toml
217     changed |= replace_region(
218         'clippy_lints/Cargo.toml', r'# begin automatic update', '# end automatic update',
219         lambda: ['version = "%s"\n' % clippy_version],
220         replace_start=False, write_back=not check)
221
222     # update the `pub mod` list
223     changed |= replace_region(
224         'clippy_lints/src/lib.rs', r'begin lints modules', r'end lints modules',
225         lambda: gen_mods(all_lints),
226         replace_start=False, write_back=not check)
227
228     # same for "clippy::*" lint collections
229     changed |= replace_region(
230         'clippy_lints/src/lib.rs', r'reg.register_lint_group\("clippy::all"', r'\]\);',
231         lambda: gen_group(clippy_lint_list),
232         replace_start=False, write_back=not check)
233
234     for key, value in clippy_lints.iteritems():
235         # same for "clippy::*" lint collections
236         changed |= replace_region(
237             'clippy_lints/src/lib.rs', r'reg.register_lint_group\("clippy::' + key + r'"', r'\]\);',
238             lambda: gen_group(value),
239             replace_start=False, write_back=not check)
240
241     # same for "deprecated" lint collection
242     changed |= replace_region(
243         'clippy_lints/src/lib.rs', r'begin deprecated lints', r'end deprecated lints',
244         lambda: gen_deprecated(deprecated_lints),
245         replace_start=False,
246         write_back=not check)
247
248     if check and changed:
249         print('Please run util/update_lints.py to regenerate lints lists.')
250         return 1
251
252
253 if __name__ == '__main__':
254     sys.exit(main(print_only='-n' in sys.argv, check='-c' in sys.argv))