]> git.lizzy.rs Git - rust.git/blob - util/update_lints.py
Merge pull request #795 from mcarton/deprecated
[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 nl_escape_re = re.compile(r'\\\n\s*')
25
26 wiki_link = 'https://github.com/Manishearth/rust-clippy/wiki'
27
28
29 def collect(lints, deprecated_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     for match in declare_lint_re.finditer(code):
37         # remove \-newline escapes from description string
38         desc = nl_escape_re.sub('', match.group('desc'))
39         lints.append((os.path.splitext(os.path.basename(fn))[0],
40                       match.group('name').lower(),
41                       match.group('level').lower(),
42                       desc.replace('\\"', '"')))
43
44     for match in declare_deprecated_lint_re.finditer(code):
45         # remove \-newline escapes from description string
46         desc = nl_escape_re.sub('', match.group('desc'))
47         deprecated_lints.append((os.path.splitext(os.path.basename(fn))[0],
48                                 match.group('name').lower(),
49                                 desc.replace('\\"', '"')))
50
51
52 def gen_table(lints, link=None):
53     """Write lint table in Markdown format."""
54     if link:
55         lints = [(p, '[%s](%s#%s)' % (l, link, l), lvl, d)
56                  for (p, l, lvl, d) in lints]
57     # first and third column widths
58     w_name = max(len(l[1]) for l in lints)
59     w_desc = max(len(l[3]) for l in lints)
60     # header and underline
61     yield '%-*s | default | meaning\n' % (w_name, 'name')
62     yield '%s-|-%s-|-%s\n' % ('-' * w_name, '-' * 7, '-' * w_desc)
63     # one table row per lint
64     for (_, name, default, meaning) in sorted(lints, key=lambda l: l[1]):
65         yield '%-*s | %-7s | %s\n' % (w_name, name, default, meaning)
66
67
68 def gen_group(lints, levels=None):
69     """Write lint group (list of all lints in the form module::NAME)."""
70     if levels:
71         lints = [tup for tup in lints if tup[2] in levels]
72     for (module, name, _, _) in sorted(lints):
73         yield '        %s::%s,\n' % (module, name.upper())
74
75
76 def gen_mods(lints):
77     """Declare modules"""
78
79     for module in sorted(set(lint[0] for lint in lints)):
80         yield 'pub mod %s;\n' % module
81
82
83 def gen_deprecated(lints):
84     """Declare deprecated lints"""
85
86     for lint in lints:
87         yield '    store.register_removed("%s", "%s");\n' % (lint[1], lint[2])
88
89
90 def replace_region(fn, region_start, region_end, callback,
91                    replace_start=True, write_back=True):
92     """Replace a region in a file delimited by two lines matching regexes.
93
94     A callback is called to write the new region.  If `replace_start` is true,
95     the start delimiter line is replaced as well.  The end delimiter line is
96     never replaced.
97     """
98     # read current content
99     with open(fn) as fp:
100         lines = list(fp)
101
102     # replace old region with new region
103     new_lines = []
104     in_old_region = False
105     for line in lines:
106         if in_old_region:
107             if re.search(region_end, line):
108                 in_old_region = False
109                 new_lines.extend(callback())
110                 new_lines.append(line)
111         elif re.search(region_start, line):
112             if not replace_start:
113                 new_lines.append(line)
114             # old region starts here
115             in_old_region = True
116         else:
117             new_lines.append(line)
118
119     # write back to file
120     if write_back:
121         with open(fn, 'w') as fp:
122             fp.writelines(new_lines)
123
124     # if something changed, return true
125     return lines != new_lines
126
127
128 def main(print_only=False, check=False):
129     lints = []
130     deprecated_lints = []
131
132     # check directory
133     if not os.path.isfile('src/lib.rs'):
134         print('Error: call this script from clippy checkout directory!')
135         return
136
137     # collect all lints from source files
138     for root, dirs, files in os.walk('src'):
139         for fn in files:
140             if fn.endswith('.rs'):
141                 collect(lints, deprecated_lints, os.path.join(root, fn))
142
143     if print_only:
144         sys.stdout.writelines(gen_table(lints))
145         return
146
147     # replace table in README.md
148     changed = replace_region(
149         'README.md', r'^name +\|', '^$',
150         lambda: gen_table(lints, link=wiki_link),
151         write_back=not check)
152
153     changed |= replace_region(
154         'README.md',
155         r'^There are \d+ lints included in this crate:', "",
156         lambda: ['There are %d lints included in this crate:\n' % len(lints)],
157         write_back=not check)
158
159     # update the `pub mod` list
160     changed |= replace_region(
161         'src/lib.rs', r'begin lints modules', r'end lints modules',
162         lambda: gen_mods(lints),
163         replace_start=False, write_back=not check)
164
165     # same for "clippy" lint collection
166     changed |= replace_region(
167         'src/lib.rs', r'reg.register_lint_group\("clippy"', r'\]\);',
168         lambda: gen_group(lints, levels=('warn', 'deny')),
169         replace_start=False, write_back=not check)
170
171     # same for "deprecated" lint collection
172     changed |= replace_region(
173             'src/lib.rs', r'let mut store', r'end deprecated lints',
174             lambda: gen_deprecated(deprecated_lints),
175             replace_start=False,
176             write_back=not check)
177
178     # same for "clippy_pedantic" lint collection
179     changed |= replace_region(
180         'src/lib.rs', r'reg.register_lint_group\("clippy_pedantic"', r'\]\);',
181         lambda: gen_group(lints, levels=('allow',)),
182         replace_start=False, write_back=not check)
183
184     if check and changed:
185         print('Please run util/update_lints.py to regenerate lints lists.')
186         return 1
187
188
189 if __name__ == '__main__':
190     sys.exit(main(print_only='-n' in sys.argv, check='-c' in sys.argv))