]> git.lizzy.rs Git - rust.git/blob - clippy_dev/src/update_lints.rs
4e48b670457e8a436875bd195c9fc0fbdbe8d96b
[rust.git] / clippy_dev / src / update_lints.rs
1 use core::fmt::Write;
2 use itertools::Itertools;
3 use rustc_lexer::{tokenize, unescape, LiteralKind, TokenKind};
4 use std::collections::HashMap;
5 use std::ffi::OsStr;
6 use std::fs;
7 use std::path::Path;
8 use walkdir::WalkDir;
9
10 use crate::clippy_project_root;
11
12 const GENERATED_FILE_COMMENT: &str = "// This file was generated by `cargo dev update_lints`.\n\
13      // Use that command to update this file and do not edit by hand.\n\
14      // Manual edits will be overwritten.\n\n";
15
16 const DOCS_LINK: &str = "https://rust-lang.github.io/rust-clippy/master/index.html";
17
18 #[derive(Clone, Copy, PartialEq)]
19 pub enum UpdateMode {
20     Check,
21     Change,
22 }
23
24 /// Runs the `update_lints` command.
25 ///
26 /// This updates various generated values from the lint source code.
27 ///
28 /// `update_mode` indicates if the files should be updated or if updates should be checked for.
29 ///
30 /// # Panics
31 ///
32 /// Panics if a file path could not read from or then written to
33 #[allow(clippy::too_many_lines)]
34 pub fn run(update_mode: UpdateMode) {
35     let (lints, deprecated_lints) = gather_all();
36
37     let internal_lints = Lint::internal_lints(&lints);
38     let usable_lints = Lint::usable_lints(&lints);
39     let mut sorted_usable_lints = usable_lints.clone();
40     sorted_usable_lints.sort_by_key(|lint| lint.name.clone());
41
42     replace_region_in_file(
43         update_mode,
44         Path::new("README.md"),
45         "[There are over ",
46         " lints included in this crate!]",
47         |res| {
48             write!(res, "{}", round_to_fifty(usable_lints.len())).unwrap();
49         },
50     );
51
52     replace_region_in_file(
53         update_mode,
54         Path::new("CHANGELOG.md"),
55         "<!-- begin autogenerated links to lint list -->\n",
56         "<!-- end autogenerated links to lint list -->",
57         |res| {
58             for lint in usable_lints
59                 .iter()
60                 .map(|l| &l.name)
61                 .chain(deprecated_lints.iter().map(|l| &l.name))
62                 .sorted()
63             {
64                 writeln!(res, "[`{}`]: {}#{}", lint, DOCS_LINK, lint).unwrap();
65             }
66         },
67     );
68
69     // This has to be in lib.rs, otherwise rustfmt doesn't work
70     replace_region_in_file(
71         update_mode,
72         Path::new("clippy_lints/src/lib.rs"),
73         "// begin lints modules, do not remove this comment, it’s used in `update_lints`\n",
74         "// end lints modules, do not remove this comment, it’s used in `update_lints`",
75         |res| {
76             for lint_mod in usable_lints.iter().map(|l| &l.module).unique().sorted() {
77                 writeln!(res, "mod {};", lint_mod).unwrap();
78             }
79         },
80     );
81
82     process_file(
83         "clippy_lints/src/lib.register_lints.rs",
84         update_mode,
85         &gen_register_lint_list(internal_lints.iter(), usable_lints.iter()),
86     );
87     process_file(
88         "clippy_lints/src/lib.deprecated.rs",
89         update_mode,
90         &gen_deprecated(&deprecated_lints),
91     );
92
93     let all_group_lints = usable_lints.iter().filter(|l| {
94         matches!(
95             &*l.group,
96             "correctness" | "suspicious" | "style" | "complexity" | "perf"
97         )
98     });
99     let content = gen_lint_group_list("all", all_group_lints);
100     process_file("clippy_lints/src/lib.register_all.rs", update_mode, &content);
101
102     for (lint_group, lints) in Lint::by_lint_group(usable_lints.into_iter().chain(internal_lints)) {
103         let content = gen_lint_group_list(&lint_group, lints.iter());
104         process_file(
105             &format!("clippy_lints/src/lib.register_{}.rs", lint_group),
106             update_mode,
107             &content,
108         );
109     }
110 }
111
112 pub fn print_lints() {
113     let (lint_list, _) = gather_all();
114     let usable_lints = Lint::usable_lints(&lint_list);
115     let usable_lint_count = usable_lints.len();
116     let grouped_by_lint_group = Lint::by_lint_group(usable_lints.into_iter());
117
118     for (lint_group, mut lints) in grouped_by_lint_group {
119         println!("\n## {}", lint_group);
120
121         lints.sort_by_key(|l| l.name.clone());
122
123         for lint in lints {
124             println!("* [{}]({}#{}) ({})", lint.name, DOCS_LINK, lint.name, lint.desc);
125         }
126     }
127
128     println!("there are {} lints", usable_lint_count);
129 }
130
131 fn round_to_fifty(count: usize) -> usize {
132     count / 50 * 50
133 }
134
135 fn process_file(path: impl AsRef<Path>, update_mode: UpdateMode, content: &str) {
136     if update_mode == UpdateMode::Check {
137         let old_content =
138             fs::read_to_string(&path).unwrap_or_else(|e| panic!("Cannot read from {}: {}", path.as_ref().display(), e));
139         if content != old_content {
140             exit_with_failure();
141         }
142     } else {
143         fs::write(&path, content.as_bytes())
144             .unwrap_or_else(|e| panic!("Cannot write to {}: {}", path.as_ref().display(), e));
145     }
146 }
147
148 fn exit_with_failure() {
149     println!(
150         "Not all lints defined properly. \
151                  Please run `cargo dev update_lints` to make sure all lints are defined properly."
152     );
153     std::process::exit(1);
154 }
155
156 /// Lint data parsed from the Clippy source code.
157 #[derive(Clone, PartialEq, Debug)]
158 struct Lint {
159     name: String,
160     group: String,
161     desc: String,
162     module: String,
163 }
164
165 impl Lint {
166     #[must_use]
167     fn new(name: &str, group: &str, desc: &str, module: &str) -> Self {
168         Self {
169             name: name.to_lowercase(),
170             group: group.into(),
171             desc: remove_line_splices(desc),
172             module: module.into(),
173         }
174     }
175
176     /// Returns all non-deprecated lints and non-internal lints
177     #[must_use]
178     fn usable_lints(lints: &[Self]) -> Vec<Self> {
179         lints
180             .iter()
181             .filter(|l| !l.group.starts_with("internal"))
182             .cloned()
183             .collect()
184     }
185
186     /// Returns all internal lints (not `internal_warn` lints)
187     #[must_use]
188     fn internal_lints(lints: &[Self]) -> Vec<Self> {
189         lints.iter().filter(|l| l.group == "internal").cloned().collect()
190     }
191
192     /// Returns the lints in a `HashMap`, grouped by the different lint groups
193     #[must_use]
194     fn by_lint_group(lints: impl Iterator<Item = Self>) -> HashMap<String, Vec<Self>> {
195         lints.map(|lint| (lint.group.to_string(), lint)).into_group_map()
196     }
197 }
198
199 #[derive(Clone, PartialEq, Debug)]
200 struct DeprecatedLint {
201     name: String,
202     reason: String,
203 }
204 impl DeprecatedLint {
205     fn new(name: &str, reason: &str) -> Self {
206         Self {
207             name: name.to_lowercase(),
208             reason: remove_line_splices(reason),
209         }
210     }
211 }
212
213 /// Generates the code for registering a group
214 fn gen_lint_group_list<'a>(group_name: &str, lints: impl Iterator<Item = &'a Lint>) -> String {
215     let mut details: Vec<_> = lints.map(|l| (&l.module, l.name.to_uppercase())).collect();
216     details.sort_unstable();
217
218     let mut output = GENERATED_FILE_COMMENT.to_string();
219
220     output.push_str(&format!(
221         "store.register_group(true, \"clippy::{0}\", Some(\"clippy_{0}\"), vec![\n",
222         group_name
223     ));
224     for (module, name) in details {
225         output.push_str(&format!("    LintId::of({}::{}),\n", module, name));
226     }
227     output.push_str("])\n");
228
229     output
230 }
231
232 /// Generates the `register_removed` code
233 #[must_use]
234 fn gen_deprecated(lints: &[DeprecatedLint]) -> String {
235     let mut output = GENERATED_FILE_COMMENT.to_string();
236     output.push_str("{\n");
237     for lint in lints {
238         output.push_str(&format!(
239             concat!(
240                 "    store.register_removed(\n",
241                 "        \"clippy::{}\",\n",
242                 "        \"{}\",\n",
243                 "    );\n"
244             ),
245             lint.name, lint.reason,
246         ));
247     }
248     output.push_str("}\n");
249
250     output
251 }
252
253 /// Generates the code for registering lints
254 #[must_use]
255 fn gen_register_lint_list<'a>(
256     internal_lints: impl Iterator<Item = &'a Lint>,
257     usable_lints: impl Iterator<Item = &'a Lint>,
258 ) -> String {
259     let mut details: Vec<_> = internal_lints
260         .map(|l| (false, &l.module, l.name.to_uppercase()))
261         .chain(usable_lints.map(|l| (true, &l.module, l.name.to_uppercase())))
262         .collect();
263     details.sort_unstable();
264
265     let mut output = GENERATED_FILE_COMMENT.to_string();
266     output.push_str("store.register_lints(&[\n");
267
268     for (is_public, module_name, lint_name) in details {
269         if !is_public {
270             output.push_str("    #[cfg(feature = \"internal\")]\n");
271         }
272         output.push_str(&format!("    {}::{},\n", module_name, lint_name));
273     }
274     output.push_str("])\n");
275
276     output
277 }
278
279 /// Gathers all lints defined in `clippy_lints/src`
280 fn gather_all() -> (Vec<Lint>, Vec<DeprecatedLint>) {
281     let mut lints = Vec::with_capacity(1000);
282     let mut deprecated_lints = Vec::with_capacity(50);
283     let root_path = clippy_project_root().join("clippy_lints/src");
284
285     for (rel_path, file) in WalkDir::new(&root_path)
286         .into_iter()
287         .map(Result::unwrap)
288         .filter(|f| f.path().extension() == Some(OsStr::new("rs")))
289         .map(|f| (f.path().strip_prefix(&root_path).unwrap().to_path_buf(), f))
290     {
291         let path = file.path();
292         let contents =
293             fs::read_to_string(path).unwrap_or_else(|e| panic!("Cannot read from `{}`: {}", path.display(), e));
294         let module = rel_path
295             .components()
296             .map(|c| c.as_os_str().to_str().unwrap())
297             .collect::<Vec<_>>()
298             .join("::");
299
300         // If the lints are stored in mod.rs, we get the module name from
301         // the containing directory:
302         let module = if let Some(module) = module.strip_suffix("::mod.rs") {
303             module
304         } else {
305             module.strip_suffix(".rs").unwrap_or(&module)
306         };
307
308         if module == "deprecated_lints" {
309             parse_deprecated_contents(&contents, &mut deprecated_lints);
310         } else {
311             parse_contents(&contents, module, &mut lints);
312         }
313     }
314     (lints, deprecated_lints)
315 }
316
317 macro_rules! match_tokens {
318     ($iter:ident, $($token:ident $({$($fields:tt)*})? $(($capture:ident))?)*) => {
319          {
320             $($(let $capture =)? if let Some((TokenKind::$token $({$($fields)*})?, _x)) = $iter.next() {
321                 _x
322             } else {
323                 continue;
324             };)*
325             #[allow(clippy::unused_unit)]
326             { ($($($capture,)?)*) }
327         }
328     }
329 }
330
331 /// Parse a source file looking for `declare_clippy_lint` macro invocations.
332 fn parse_contents(contents: &str, module: &str, lints: &mut Vec<Lint>) {
333     let mut offset = 0usize;
334     let mut iter = tokenize(contents).map(|t| {
335         let range = offset..offset + t.len;
336         offset = range.end;
337         (t.kind, &contents[range])
338     });
339
340     while iter.any(|(kind, s)| kind == TokenKind::Ident && s == "declare_clippy_lint") {
341         let mut iter = iter
342             .by_ref()
343             .filter(|&(kind, _)| !matches!(kind, TokenKind::Whitespace | TokenKind::LineComment { .. }));
344         // matches `!{`
345         match_tokens!(iter, Bang OpenBrace);
346         match iter.next() {
347             // #[clippy::version = "version"] pub
348             Some((TokenKind::Pound, _)) => {
349                 match_tokens!(iter, OpenBracket Ident Colon Colon Ident Eq Literal{..} CloseBracket Ident);
350             },
351             // pub
352             Some((TokenKind::Ident, _)) => (),
353             _ => continue,
354         }
355         let (name, group, desc) = match_tokens!(
356             iter,
357             // LINT_NAME
358             Ident(name) Comma
359             // group,
360             Ident(group) Comma
361             // "description" }
362             Literal{kind: LiteralKind::Str{..}, ..}(desc) CloseBrace
363         );
364         lints.push(Lint::new(name, group, desc, module));
365     }
366 }
367
368 /// Parse a source file looking for `declare_deprecated_lint` macro invocations.
369 fn parse_deprecated_contents(contents: &str, lints: &mut Vec<DeprecatedLint>) {
370     let mut offset = 0usize;
371     let mut iter = tokenize(contents).map(|t| {
372         let range = offset..offset + t.len;
373         offset = range.end;
374         (t.kind, &contents[range])
375     });
376     while iter.any(|(kind, s)| kind == TokenKind::Ident && s == "declare_deprecated_lint") {
377         let mut iter = iter
378             .by_ref()
379             .filter(|&(kind, _)| !matches!(kind, TokenKind::Whitespace | TokenKind::LineComment { .. }));
380         let (name, reason) = match_tokens!(
381             iter,
382             // !{
383             Bang OpenBrace
384             // #[clippy::version = "version"]
385             Pound OpenBracket Ident Colon Colon Ident Eq Literal{..} CloseBracket
386             // pub LINT_NAME,
387             Ident Ident(name) Comma
388             // "description"
389             Literal{kind: LiteralKind::Str{..},..}(reason)
390             // }
391             CloseBrace
392         );
393         lints.push(DeprecatedLint::new(name, reason));
394     }
395 }
396
397 /// Removes the line splices and surrounding quotes from a string literal
398 fn remove_line_splices(s: &str) -> String {
399     let s = s
400         .strip_prefix('"')
401         .and_then(|s| s.strip_suffix('"'))
402         .unwrap_or_else(|| panic!("expected quoted string, found `{}`", s));
403     let mut res = String::with_capacity(s.len());
404     unescape::unescape_literal(s, unescape::Mode::Str, &mut |range, _| res.push_str(&s[range]));
405     res
406 }
407
408 /// Replaces a region in a file delimited by two lines matching regexes.
409 ///
410 /// `path` is the relative path to the file on which you want to perform the replacement.
411 ///
412 /// See `replace_region_in_text` for documentation of the other options.
413 ///
414 /// # Panics
415 ///
416 /// Panics if the path could not read or then written
417 fn replace_region_in_file(
418     update_mode: UpdateMode,
419     path: &Path,
420     start: &str,
421     end: &str,
422     write_replacement: impl FnMut(&mut String),
423 ) {
424     let contents = fs::read_to_string(path).unwrap_or_else(|e| panic!("Cannot read from `{}`: {}", path.display(), e));
425     let new_contents = match replace_region_in_text(&contents, start, end, write_replacement) {
426         Ok(x) => x,
427         Err(delim) => panic!("Couldn't find `{}` in file `{}`", delim, path.display()),
428     };
429
430     match update_mode {
431         UpdateMode::Check if contents != new_contents => exit_with_failure(),
432         UpdateMode::Check => (),
433         UpdateMode::Change => {
434             if let Err(e) = fs::write(path, new_contents.as_bytes()) {
435                 panic!("Cannot write to `{}`: {}", path.display(), e);
436             }
437         },
438     }
439 }
440
441 /// Replaces a region in a text delimited by two strings. Returns the new text if both delimiters
442 /// were found, or the missing delimiter if not.
443 fn replace_region_in_text<'a>(
444     text: &str,
445     start: &'a str,
446     end: &'a str,
447     mut write_replacement: impl FnMut(&mut String),
448 ) -> Result<String, &'a str> {
449     let (text_start, rest) = text.split_once(start).ok_or(start)?;
450     let (_, text_end) = rest.split_once(end).ok_or(end)?;
451
452     let mut res = String::with_capacity(text.len() + 4096);
453     res.push_str(text_start);
454     res.push_str(start);
455     write_replacement(&mut res);
456     res.push_str(end);
457     res.push_str(text_end);
458
459     Ok(res)
460 }
461
462 #[cfg(test)]
463 mod tests {
464     use super::*;
465
466     #[test]
467     fn test_parse_contents() {
468         static CONTENTS: &str = r#"
469             declare_clippy_lint! {
470                 #[clippy::version = "Hello Clippy!"]
471                 pub PTR_ARG,
472                 style,
473                 "really long \
474                 text"
475             }
476
477             declare_clippy_lint!{
478                 #[clippy::version = "Test version"]
479                 pub DOC_MARKDOWN,
480                 pedantic,
481                 "single line"
482             }
483         "#;
484         let mut result = Vec::new();
485         parse_contents(CONTENTS, "module_name", &mut result);
486
487         let expected = vec![
488             Lint::new("ptr_arg", "style", "\"really long text\"", "module_name"),
489             Lint::new("doc_markdown", "pedantic", "\"single line\"", "module_name"),
490         ];
491         assert_eq!(expected, result);
492     }
493
494     #[test]
495     fn test_parse_deprecated_contents() {
496         static DEPRECATED_CONTENTS: &str = r#"
497             /// some doc comment
498             declare_deprecated_lint! {
499                 #[clippy::version = "I'm a version"]
500                 pub SHOULD_ASSERT_EQ,
501                 "`assert!()` will be more flexible with RFC 2011"
502             }
503         "#;
504
505         let mut result = Vec::new();
506         parse_deprecated_contents(DEPRECATED_CONTENTS, &mut result);
507
508         let expected = vec![DeprecatedLint::new(
509             "should_assert_eq",
510             "\"`assert!()` will be more flexible with RFC 2011\"",
511         )];
512         assert_eq!(expected, result);
513     }
514
515     #[test]
516     fn test_usable_lints() {
517         let lints = vec![
518             Lint::new("should_assert_eq2", "Not Deprecated", "\"abc\"", "module_name"),
519             Lint::new("should_assert_eq2", "internal", "\"abc\"", "module_name"),
520             Lint::new("should_assert_eq2", "internal_style", "\"abc\"", "module_name"),
521         ];
522         let expected = vec![Lint::new(
523             "should_assert_eq2",
524             "Not Deprecated",
525             "\"abc\"",
526             "module_name",
527         )];
528         assert_eq!(expected, Lint::usable_lints(&lints));
529     }
530
531     #[test]
532     fn test_by_lint_group() {
533         let lints = vec![
534             Lint::new("should_assert_eq", "group1", "\"abc\"", "module_name"),
535             Lint::new("should_assert_eq2", "group2", "\"abc\"", "module_name"),
536             Lint::new("incorrect_match", "group1", "\"abc\"", "module_name"),
537         ];
538         let mut expected: HashMap<String, Vec<Lint>> = HashMap::new();
539         expected.insert(
540             "group1".to_string(),
541             vec![
542                 Lint::new("should_assert_eq", "group1", "\"abc\"", "module_name"),
543                 Lint::new("incorrect_match", "group1", "\"abc\"", "module_name"),
544             ],
545         );
546         expected.insert(
547             "group2".to_string(),
548             vec![Lint::new("should_assert_eq2", "group2", "\"abc\"", "module_name")],
549         );
550         assert_eq!(expected, Lint::by_lint_group(lints.into_iter()));
551     }
552
553     #[test]
554     fn test_gen_deprecated() {
555         let lints = vec![
556             DeprecatedLint::new("should_assert_eq", "\"has been superseded by should_assert_eq2\""),
557             DeprecatedLint::new("another_deprecated", "\"will be removed\""),
558         ];
559
560         let expected = GENERATED_FILE_COMMENT.to_string()
561             + &[
562                 "{",
563                 "    store.register_removed(",
564                 "        \"clippy::should_assert_eq\",",
565                 "        \"has been superseded by should_assert_eq2\",",
566                 "    );",
567                 "    store.register_removed(",
568                 "        \"clippy::another_deprecated\",",
569                 "        \"will be removed\",",
570                 "    );",
571                 "}",
572             ]
573             .join("\n")
574             + "\n";
575
576         assert_eq!(expected, gen_deprecated(&lints));
577     }
578
579     #[test]
580     fn test_gen_lint_group_list() {
581         let lints = vec![
582             Lint::new("abc", "group1", "\"abc\"", "module_name"),
583             Lint::new("should_assert_eq", "group1", "\"abc\"", "module_name"),
584             Lint::new("internal", "internal_style", "\"abc\"", "module_name"),
585         ];
586         let expected = GENERATED_FILE_COMMENT.to_string()
587             + &[
588                 "store.register_group(true, \"clippy::group1\", Some(\"clippy_group1\"), vec![",
589                 "    LintId::of(module_name::ABC),",
590                 "    LintId::of(module_name::INTERNAL),",
591                 "    LintId::of(module_name::SHOULD_ASSERT_EQ),",
592                 "])",
593             ]
594             .join("\n")
595             + "\n";
596
597         let result = gen_lint_group_list("group1", lints.iter());
598
599         assert_eq!(expected, result);
600     }
601 }