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