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