]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_dev/src/update_lints.rs
59db51fbfac5149fec5158a137c91e94fa86bf4b
[rust.git] / src / tools / clippy / 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{..}(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('r')
401         .unwrap_or(s)
402         .trim_matches('#')
403         .strip_prefix('"')
404         .and_then(|s| s.strip_suffix('"'))
405         .unwrap_or_else(|| panic!("expected quoted string, found `{}`", s));
406     let mut res = String::with_capacity(s.len());
407     unescape::unescape_literal(s, unescape::Mode::Str, &mut |range, _| res.push_str(&s[range]));
408     res
409 }
410
411 /// Replaces a region in a file delimited by two lines matching regexes.
412 ///
413 /// `path` is the relative path to the file on which you want to perform the replacement.
414 ///
415 /// See `replace_region_in_text` for documentation of the other options.
416 ///
417 /// # Panics
418 ///
419 /// Panics if the path could not read or then written
420 fn replace_region_in_file(
421     update_mode: UpdateMode,
422     path: &Path,
423     start: &str,
424     end: &str,
425     write_replacement: impl FnMut(&mut String),
426 ) {
427     let contents = fs::read_to_string(path).unwrap_or_else(|e| panic!("Cannot read from `{}`: {}", path.display(), e));
428     let new_contents = match replace_region_in_text(&contents, start, end, write_replacement) {
429         Ok(x) => x,
430         Err(delim) => panic!("Couldn't find `{}` in file `{}`", delim, path.display()),
431     };
432
433     match update_mode {
434         UpdateMode::Check if contents != new_contents => exit_with_failure(),
435         UpdateMode::Check => (),
436         UpdateMode::Change => {
437             if let Err(e) = fs::write(path, new_contents.as_bytes()) {
438                 panic!("Cannot write to `{}`: {}", path.display(), e);
439             }
440         },
441     }
442 }
443
444 /// Replaces a region in a text delimited by two strings. Returns the new text if both delimiters
445 /// were found, or the missing delimiter if not.
446 fn replace_region_in_text<'a>(
447     text: &str,
448     start: &'a str,
449     end: &'a str,
450     mut write_replacement: impl FnMut(&mut String),
451 ) -> Result<String, &'a str> {
452     let (text_start, rest) = text.split_once(start).ok_or(start)?;
453     let (_, text_end) = rest.split_once(end).ok_or(end)?;
454
455     let mut res = String::with_capacity(text.len() + 4096);
456     res.push_str(text_start);
457     res.push_str(start);
458     write_replacement(&mut res);
459     res.push_str(end);
460     res.push_str(text_end);
461
462     Ok(res)
463 }
464
465 #[cfg(test)]
466 mod tests {
467     use super::*;
468
469     #[test]
470     fn test_parse_contents() {
471         static CONTENTS: &str = r#"
472             declare_clippy_lint! {
473                 #[clippy::version = "Hello Clippy!"]
474                 pub PTR_ARG,
475                 style,
476                 "really long \
477                 text"
478             }
479
480             declare_clippy_lint!{
481                 #[clippy::version = "Test version"]
482                 pub DOC_MARKDOWN,
483                 pedantic,
484                 "single line"
485             }
486         "#;
487         let mut result = Vec::new();
488         parse_contents(CONTENTS, "module_name", &mut result);
489
490         let expected = vec![
491             Lint::new("ptr_arg", "style", "\"really long text\"", "module_name"),
492             Lint::new("doc_markdown", "pedantic", "\"single line\"", "module_name"),
493         ];
494         assert_eq!(expected, result);
495     }
496
497     #[test]
498     fn test_parse_deprecated_contents() {
499         static DEPRECATED_CONTENTS: &str = r#"
500             /// some doc comment
501             declare_deprecated_lint! {
502                 #[clippy::version = "I'm a version"]
503                 pub SHOULD_ASSERT_EQ,
504                 "`assert!()` will be more flexible with RFC 2011"
505             }
506         "#;
507
508         let mut result = Vec::new();
509         parse_deprecated_contents(DEPRECATED_CONTENTS, &mut result);
510
511         let expected = vec![DeprecatedLint::new(
512             "should_assert_eq",
513             "\"`assert!()` will be more flexible with RFC 2011\"",
514         )];
515         assert_eq!(expected, result);
516     }
517
518     #[test]
519     fn test_usable_lints() {
520         let lints = vec![
521             Lint::new("should_assert_eq2", "Not Deprecated", "\"abc\"", "module_name"),
522             Lint::new("should_assert_eq2", "internal", "\"abc\"", "module_name"),
523             Lint::new("should_assert_eq2", "internal_style", "\"abc\"", "module_name"),
524         ];
525         let expected = vec![Lint::new(
526             "should_assert_eq2",
527             "Not Deprecated",
528             "\"abc\"",
529             "module_name",
530         )];
531         assert_eq!(expected, Lint::usable_lints(&lints));
532     }
533
534     #[test]
535     fn test_by_lint_group() {
536         let lints = vec![
537             Lint::new("should_assert_eq", "group1", "\"abc\"", "module_name"),
538             Lint::new("should_assert_eq2", "group2", "\"abc\"", "module_name"),
539             Lint::new("incorrect_match", "group1", "\"abc\"", "module_name"),
540         ];
541         let mut expected: HashMap<String, Vec<Lint>> = HashMap::new();
542         expected.insert(
543             "group1".to_string(),
544             vec![
545                 Lint::new("should_assert_eq", "group1", "\"abc\"", "module_name"),
546                 Lint::new("incorrect_match", "group1", "\"abc\"", "module_name"),
547             ],
548         );
549         expected.insert(
550             "group2".to_string(),
551             vec![Lint::new("should_assert_eq2", "group2", "\"abc\"", "module_name")],
552         );
553         assert_eq!(expected, Lint::by_lint_group(lints.into_iter()));
554     }
555
556     #[test]
557     fn test_gen_deprecated() {
558         let lints = vec![
559             DeprecatedLint::new("should_assert_eq", "\"has been superseded by should_assert_eq2\""),
560             DeprecatedLint::new("another_deprecated", "\"will be removed\""),
561         ];
562
563         let expected = GENERATED_FILE_COMMENT.to_string()
564             + &[
565                 "{",
566                 "    store.register_removed(",
567                 "        \"clippy::should_assert_eq\",",
568                 "        \"has been superseded by should_assert_eq2\",",
569                 "    );",
570                 "    store.register_removed(",
571                 "        \"clippy::another_deprecated\",",
572                 "        \"will be removed\",",
573                 "    );",
574                 "}",
575             ]
576             .join("\n")
577             + "\n";
578
579         assert_eq!(expected, gen_deprecated(&lints));
580     }
581
582     #[test]
583     fn test_gen_lint_group_list() {
584         let lints = vec![
585             Lint::new("abc", "group1", "\"abc\"", "module_name"),
586             Lint::new("should_assert_eq", "group1", "\"abc\"", "module_name"),
587             Lint::new("internal", "internal_style", "\"abc\"", "module_name"),
588         ];
589         let expected = GENERATED_FILE_COMMENT.to_string()
590             + &[
591                 "store.register_group(true, \"clippy::group1\", Some(\"clippy_group1\"), vec![",
592                 "    LintId::of(module_name::ABC),",
593                 "    LintId::of(module_name::INTERNAL),",
594                 "    LintId::of(module_name::SHOULD_ASSERT_EQ),",
595                 "])",
596             ]
597             .join("\n")
598             + "\n";
599
600         let result = gen_lint_group_list("group1", lints.iter());
601
602         assert_eq!(expected, result);
603     }
604 }