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