]> git.lizzy.rs Git - rust.git/blob - util/update_lints.py
Merge pull request #3129 from mipli/3091-numeric-typo
[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         clippy_lints[cat].append((os.path.splitext(os.path.basename(fn))[0],
50                                   match.group('name').lower(),
51                                   "allow",
52                                   desc.replace('\\"', '"')))
53
54
55 def gen_group(lints):
56     """Write lint group (list of all lints in the form module::NAME)."""
57     for (module, name, _, _) in sorted(lints):
58         yield '        %s::%s,\n' % (module, name.upper())
59
60
61 def gen_mods(lints):
62     """Declare modules"""
63
64     for module in sorted(set(lint[0] for lint in lints)):
65         yield 'pub mod %s;\n' % module
66
67
68 def gen_deprecated(lints):
69     """Declare deprecated lints"""
70
71     for lint in lints:
72         yield '    store.register_removed(\n'
73         yield '        "%s",\n' % lint[1]
74         yield '        "%s",\n' % lint[2]
75         yield '    );\n'
76
77
78 def replace_region(fn, region_start, region_end, callback,
79                    replace_start=True, write_back=True):
80     """Replace a region in a file delimited by two lines matching regexes.
81
82     A callback is called to write the new region.  If `replace_start` is true,
83     the start delimiter line is replaced as well.  The end delimiter line is
84     never replaced.
85     """
86     # read current content
87     with open(fn) as fp:
88         lines = list(fp)
89
90     found = False
91
92     # replace old region with new region
93     new_lines = []
94     in_old_region = False
95     for line in lines:
96         if in_old_region:
97             if re.search(region_end, line):
98                 in_old_region = False
99                 new_lines.extend(callback())
100                 new_lines.append(line)
101         elif re.search(region_start, line):
102             if not replace_start:
103                 new_lines.append(line)
104             # old region starts here
105             in_old_region = True
106             found = True
107         else:
108             new_lines.append(line)
109
110     if not found:
111         print("regex " + region_start + " not found")
112
113     # write back to file
114     if write_back:
115         with open(fn, 'w') as fp:
116             fp.writelines(new_lines)
117
118     # if something changed, return true
119     return lines != new_lines
120
121
122 def main(print_only=False, check=False):
123     deprecated_lints = []
124     clippy_lints = {
125         "correctness": [],
126         "style": [],
127         "complexity": [],
128         "perf": [],
129         "restriction": [],
130         "pedantic": [],
131         "cargo": [],
132         "nursery": [],
133     }
134
135     # check directory
136     if not os.path.isfile('clippy_lints/src/lib.rs'):
137         print('Error: call this script from clippy checkout directory!')
138         return
139
140     # collect all lints from source files
141     for fn in os.listdir('clippy_lints/src'):
142         if fn.endswith('.rs'):
143             collect(deprecated_lints, clippy_lints,
144                     os.path.join('clippy_lints', 'src', fn))
145
146     # determine version
147     with open('Cargo.toml') as fp:
148         for line in fp:
149             if line.startswith('version ='):
150                 clippy_version = line.split()[2].strip('"')
151                 break
152         else:
153             print('Error: version not found in Cargo.toml!')
154             return
155
156     all_lints = []
157     clippy_lint_groups = [
158         "correctness",
159         "style",
160         "complexity",
161         "perf",
162     ]
163     clippy_lint_list = []
164     for x in clippy_lint_groups:
165         clippy_lint_list += clippy_lints[x]
166     for _, value in clippy_lints.iteritems():
167         all_lints += value
168
169     if print_only:
170         call(["./util/dev", "update_lints", "--print-only"])
171         return
172
173     # update the lint counter in README.md
174     changed = replace_region(
175         'README.md',
176         r'^\[There are \d+ lints included in this crate!\]\(https://rust-lang-nursery.github.io/rust-clippy/master/index.html\)$', "",
177         lambda: ['[There are %d lints included in this crate!](https://rust-lang-nursery.github.io/rust-clippy/master/index.html)\n' %
178                  (len(all_lints))],
179         write_back=not check)
180
181     # update the links in the CHANGELOG
182     changed |= replace_region(
183         'CHANGELOG.md',
184         "<!-- begin autogenerated links to lint list -->",
185         "<!-- end autogenerated links to lint list -->",
186         lambda: ["[`{0}`]: {1}#{0}\n".format(l[1], docs_link) for l in
187                  sorted(all_lints + deprecated_lints,
188                         key=lambda l: l[1])],
189         replace_start=False, write_back=not check)
190
191     # update version of clippy_lints in Cargo.toml
192     changed |= replace_region(
193         'Cargo.toml', r'# begin automatic update', '# end automatic update',
194         lambda: ['clippy_lints = { version = "%s", path = "clippy_lints" }\n' %
195                  clippy_version],
196         replace_start=False, write_back=not check)
197
198     # update version of clippy_lints in Cargo.toml
199     changed |= replace_region(
200         'clippy_lints/Cargo.toml', r'# begin automatic update', '# end automatic update',
201         lambda: ['version = "%s"\n' % clippy_version],
202         replace_start=False, write_back=not check)
203
204     # update the `pub mod` list
205     changed |= replace_region(
206         'clippy_lints/src/lib.rs', r'begin lints modules', r'end lints modules',
207         lambda: gen_mods(all_lints),
208         replace_start=False, write_back=not check)
209
210     # same for "clippy::*" lint collections
211     changed |= replace_region(
212         'clippy_lints/src/lib.rs', r'reg.register_lint_group\("clippy::all"', r'\]\);',
213         lambda: gen_group(clippy_lint_list),
214         replace_start=False, write_back=not check)
215
216     for key, value in clippy_lints.iteritems():
217         # same for "clippy::*" lint collections
218         changed |= replace_region(
219             'clippy_lints/src/lib.rs', r'reg.register_lint_group\("clippy::' + key + r'"', r'\]\);',
220             lambda: gen_group(value),
221             replace_start=False, write_back=not check)
222
223     # same for "deprecated" lint collection
224     changed |= replace_region(
225         'clippy_lints/src/lib.rs', r'let mut store', r'end deprecated lints',
226         lambda: gen_deprecated(deprecated_lints),
227         replace_start=False,
228         write_back=not check)
229
230     if check and changed:
231         print('Please run util/update_lints.py to regenerate lints lists.')
232         return 1
233
234
235 if __name__ == '__main__':
236     sys.exit(main(print_only='-n' in sys.argv, check='-c' in sys.argv))