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
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)
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)
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)
30 nl_escape_re = re.compile(r'\\\n\s*')
32 wiki_link = 'https://github.com/Manishearth/rust-clippy/wiki'
35 def collect(lints, deprecated_lints, restriction_lints, fn):
36 """Collect all lints from a file.
38 Adds entries to the lints list as `(module, name, level, desc)`.
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('\\"', '"')))
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('\\"', '"')))
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(),
63 desc.replace('\\"', '"')))
66 def gen_table(lints, link=None):
67 """Write lint table in Markdown format."""
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 | meaning\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)
82 def gen_group(lints, levels=None):
83 """Write lint group (list of all lints in the form module::NAME)."""
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())
93 for module in sorted(set(lint[0] for lint in lints)):
94 yield 'pub mod %s;\n' % module
97 def gen_deprecated(lints):
98 """Declare deprecated lints"""
101 yield ' store.register_removed("%s", "%s");\n' % (lint[1], lint[2])
103 def replace_region(fn, region_start, region_end, callback,
104 replace_start=True, write_back=True):
105 """Replace a region in a file delimited by two lines matching regexes.
107 A callback is called to write the new region. If `replace_start` is true,
108 the start delimiter line is replaced as well. The end delimiter line is
111 # read current content
115 # replace old region with new region
117 in_old_region = False
120 if re.search(region_end, line):
121 in_old_region = False
122 new_lines.extend(callback())
123 new_lines.append(line)
124 elif re.search(region_start, line):
125 if not replace_start:
126 new_lines.append(line)
127 # old region starts here
130 new_lines.append(line)
134 with open(fn, 'w') as fp:
135 fp.writelines(new_lines)
137 # if something changed, return true
138 return lines != new_lines
141 def main(print_only=False, check=False):
143 deprecated_lints = []
144 restriction_lints = []
147 if not os.path.isfile('clippy_lints/src/lib.rs'):
148 print('Error: call this script from clippy checkout directory!')
151 # collect all lints from source files
152 for root, _, files in os.walk('clippy_lints/src'):
154 if fn.endswith('.rs'):
155 collect(lints, deprecated_lints, restriction_lints,
156 os.path.join(root, fn))
159 sys.stdout.writelines(gen_table(lints + restriction_lints))
162 # replace table in README.md
163 changed = replace_region(
164 'README.md', r'^name +\|', '^$',
165 lambda: gen_table(lints + restriction_lints, link=wiki_link),
166 write_back=not check)
168 changed |= replace_region(
170 r'^There are \d+ lints included in this crate:', "",
171 lambda: ['There are %d lints included in this crate:\n' % (len(lints)
172 + len(restriction_lints))],
173 write_back=not check)
175 # update the links in the CHANGELOG
176 changed |= replace_region(
178 "<!-- begin autogenerated links to wiki -->",
179 "<!-- end autogenerated links to wiki -->",
180 lambda: ["[`{0}`]: {1}#{0}\n".format(l[1], wiki_link) for l in
181 sorted(lints + restriction_lints + deprecated_lints,
182 key=lambda l: l[1])],
183 replace_start=False, write_back=not check)
185 # update the `pub mod` list
186 changed |= replace_region(
187 'clippy_lints/src/lib.rs', r'begin lints modules', r'end lints modules',
188 lambda: gen_mods(lints + restriction_lints),
189 replace_start=False, write_back=not check)
191 # same for "clippy" lint collection
192 changed |= replace_region(
193 'clippy_lints/src/lib.rs', r'reg.register_lint_group\("clippy"', r'\]\);',
194 lambda: gen_group(lints, levels=('warn', 'deny')),
195 replace_start=False, write_back=not check)
197 # same for "deprecated" lint collection
198 changed |= replace_region(
199 'clippy_lints/src/lib.rs', r'let mut store', r'end deprecated lints',
200 lambda: gen_deprecated(deprecated_lints),
202 write_back=not check)
204 # same for "clippy_pedantic" lint collection
205 changed |= replace_region(
206 'clippy_lints/src/lib.rs', r'reg.register_lint_group\("clippy_pedantic"', r'\]\);',
207 lambda: gen_group(lints, levels=('allow',)),
208 replace_start=False, write_back=not check)
210 # same for "clippy_restrictions" lint collection
211 changed |= replace_region(
212 'clippy_lints/src/lib.rs', r'reg.register_lint_group\("clippy_restrictions"',
213 r'\]\);', lambda: gen_group(restriction_lints),
214 replace_start=False, write_back=not check)
216 if check and changed:
217 print('Please run util/update_lints.py to regenerate lints lists.')
221 if __name__ == '__main__':
222 sys.exit(main(print_only='-n' in sys.argv, check='-c' in sys.argv))