]> git.lizzy.rs Git - rust.git/blob - clippy_dev/src/lib.rs
Get rid of Lint::is_internal method
[rust.git] / clippy_dev / src / lib.rs
1 #![cfg_attr(feature = "deny-warnings", deny(warnings))]
2
3 use itertools::Itertools;
4 use lazy_static::lazy_static;
5 use regex::Regex;
6 use std::collections::HashMap;
7 use std::ffi::OsStr;
8 use std::fs;
9 use std::path::{Path, PathBuf};
10 use walkdir::WalkDir;
11
12 pub mod fmt;
13 pub mod new_lint;
14 pub mod stderr_length_check;
15 pub mod update_lints;
16
17 lazy_static! {
18     static ref DEC_CLIPPY_LINT_RE: Regex = Regex::new(
19         r#"(?x)
20         declare_clippy_lint!\s*[\{(]
21         (?:\s+///.*)*
22         \s+pub\s+(?P<name>[A-Z_][A-Z_0-9]*)\s*,\s*
23         (?P<cat>[a-z_]+)\s*,\s*
24         "(?P<desc>(?:[^"\\]+|\\(?s).(?-s))*)"\s*[})]
25     "#
26     )
27     .unwrap();
28     static ref DEC_DEPRECATED_LINT_RE: Regex = Regex::new(
29         r#"(?x)
30         declare_deprecated_lint!\s*[{(]\s*
31         (?:\s+///.*)*
32         \s+pub\s+(?P<name>[A-Z_][A-Z_0-9]*)\s*,\s*
33         "(?P<desc>(?:[^"\\]+|\\(?s).(?-s))*)"\s*[})]
34     "#
35     )
36     .unwrap();
37     static ref NL_ESCAPE_RE: Regex = Regex::new(r#"\\\n\s*"#).unwrap();
38 }
39
40 pub static DOCS_LINK: &str = "https://rust-lang.github.io/rust-clippy/master/index.html";
41
42 /// Lint data parsed from the Clippy source code.
43 #[derive(Clone, PartialEq, Debug)]
44 pub struct Lint {
45     pub name: String,
46     pub group: String,
47     pub desc: String,
48     pub deprecation: Option<String>,
49     pub module: String,
50 }
51
52 impl Lint {
53     #[must_use]
54     pub fn new(name: &str, group: &str, desc: &str, deprecation: Option<&str>, module: &str) -> Self {
55         Self {
56             name: name.to_lowercase(),
57             group: group.to_string(),
58             desc: NL_ESCAPE_RE.replace(&desc.replace("\\\"", "\""), "").to_string(),
59             deprecation: deprecation.map(ToString::to_string),
60             module: module.to_string(),
61         }
62     }
63
64     /// Returns all non-deprecated lints and non-internal lints
65     pub fn usable_lints(lints: impl Iterator<Item = Self>) -> impl Iterator<Item = Self> {
66         lints.filter(|l| l.deprecation.is_none() && !l.group.starts_with("internal"))
67     }
68
69     /// Returns all internal lints (not `internal_warn` lints)
70     pub fn internal_lints(lints: impl Iterator<Item = Self>) -> impl Iterator<Item = Self> {
71         lints.filter(|l| l.group == "internal")
72     }
73
74     /// Returns the lints in a `HashMap`, grouped by the different lint groups
75     #[must_use]
76     pub fn by_lint_group(lints: impl Iterator<Item = Self>) -> HashMap<String, Vec<Self>> {
77         lints.map(|lint| (lint.group.to_string(), lint)).into_group_map()
78     }
79 }
80
81 /// Generates the Vec items for `register_lint_group` calls in `clippy_lints/src/lib.rs`.
82 #[must_use]
83 pub fn gen_lint_group_list(lints: &[Lint]) -> Vec<String> {
84     lints
85         .into_iter()
86         .filter_map(|l| {
87             if l.deprecation.is_some() {
88                 None
89             } else {
90                 Some(format!("        LintId::of(&{}::{}),", l.module, l.name.to_uppercase()))
91             }
92         })
93         .sorted()
94         .collect::<Vec<String>>()
95 }
96
97 /// Generates the `pub mod module_name` list in `clippy_lints/src/lib.rs`.
98 #[must_use]
99 pub fn gen_modules_list(lints: &[Lint]) -> Vec<String> {
100     lints
101         .iter()
102         .map(|l| &l.module)
103         .unique()
104         .map(|module| format!("pub mod {};", module))
105         .sorted()
106         .collect::<Vec<String>>()
107 }
108
109 /// Generates the list of lint links at the bottom of the README
110 #[must_use]
111 pub fn gen_changelog_lint_list(lints: &[Lint]) -> Vec<String> {
112     lints
113         .iter()
114         .sorted_by_key(|l| l.name.clone())
115         .filter_map(|l| {
116             if l.group.starts_with("internal") {
117                 None
118             } else {
119                 Some(format!("[`{}`]: {}#{}", l.name, DOCS_LINK, l.name))
120             }
121         })
122         .collect()
123 }
124
125 /// Generates the `register_removed` code in `./clippy_lints/src/lib.rs`.
126 #[must_use]
127 pub fn gen_deprecated(lints: &[Lint]) -> Vec<String> {
128     lints
129         .iter()
130         .filter_map(|l| {
131             l.clone().deprecation.map(|depr_text| {
132                 vec![
133                     "    store.register_removed(".to_string(),
134                     format!("        \"clippy::{}\",", l.name),
135                     format!("        \"{}\",", depr_text),
136                     "    );".to_string(),
137                 ]
138             })
139         })
140         .flatten()
141         .collect::<Vec<String>>()
142 }
143
144 #[must_use]
145 pub fn gen_register_lint_list(lints: &[Lint]) -> Vec<String> {
146     let pre = "    store.register_lints(&[".to_string();
147     let post = "    ]);".to_string();
148     let mut inner = lints
149         .iter()
150         .map(|l| format!("        &{}::{},", l.module, l.name.to_uppercase()))
151         .sorted()
152         .collect::<Vec<String>>();
153     inner.insert(0, pre);
154     inner.push(post);
155     inner
156 }
157
158 /// Gathers all files in `src/clippy_lints` and gathers all lints inside
159 pub fn gather_all() -> impl Iterator<Item = Lint> {
160     lint_files().flat_map(|f| gather_from_file(&f))
161 }
162
163 fn gather_from_file(dir_entry: &walkdir::DirEntry) -> impl Iterator<Item = Lint> {
164     let content = fs::read_to_string(dir_entry.path()).unwrap();
165     let path = dir_entry.path();
166     let filename = path.file_stem().unwrap();
167     let path_buf = path.with_file_name(filename);
168     let mut rel_path = path_buf
169         .strip_prefix(clippy_project_root().join("clippy_lints/src"))
170         .expect("only files in `clippy_lints/src` should be looked at");
171     // If the lints are stored in mod.rs, we get the module name from
172     // the containing directory:
173     if filename == "mod" {
174         rel_path = rel_path.parent().unwrap();
175     }
176
177     let module = rel_path
178         .components()
179         .map(|c| c.as_os_str().to_str().unwrap())
180         .collect::<Vec<_>>()
181         .join("::");
182
183     parse_contents(&content, &module)
184 }
185
186 fn parse_contents(content: &str, module: &str) -> impl Iterator<Item = Lint> {
187     let lints = DEC_CLIPPY_LINT_RE
188         .captures_iter(content)
189         .map(|m| Lint::new(&m["name"], &m["cat"], &m["desc"], None, module));
190     let deprecated = DEC_DEPRECATED_LINT_RE
191         .captures_iter(content)
192         .map(|m| Lint::new(&m["name"], "Deprecated", &m["desc"], Some(&m["desc"]), module));
193     // Removing the `.collect::<Vec<Lint>>().into_iter()` causes some lifetime issues due to the map
194     lints.chain(deprecated).collect::<Vec<Lint>>().into_iter()
195 }
196
197 /// Collects all .rs files in the `clippy_lints/src` directory
198 fn lint_files() -> impl Iterator<Item = walkdir::DirEntry> {
199     // We use `WalkDir` instead of `fs::read_dir` here in order to recurse into subdirectories.
200     // Otherwise we would not collect all the lints, for example in `clippy_lints/src/methods/`.
201     let path = clippy_project_root().join("clippy_lints/src");
202     WalkDir::new(path)
203         .into_iter()
204         .filter_map(Result::ok)
205         .filter(|f| f.path().extension() == Some(OsStr::new("rs")))
206 }
207
208 /// Whether a file has had its text changed or not
209 #[derive(PartialEq, Debug)]
210 pub struct FileChange {
211     pub changed: bool,
212     pub new_lines: String,
213 }
214
215 /// Replaces a region in a file delimited by two lines matching regexes.
216 ///
217 /// `path` is the relative path to the file on which you want to perform the replacement.
218 ///
219 /// See `replace_region_in_text` for documentation of the other options.
220 pub fn replace_region_in_file<F>(
221     path: &Path,
222     start: &str,
223     end: &str,
224     replace_start: bool,
225     write_back: bool,
226     replacements: F,
227 ) -> FileChange
228 where
229     F: FnOnce() -> Vec<String>,
230 {
231     let contents = fs::read_to_string(path).unwrap_or_else(|e| panic!("Cannot read from {}: {}", path.display(), e));
232     let file_change = replace_region_in_text(&contents, start, end, replace_start, replacements);
233
234     if write_back {
235         if let Err(e) = fs::write(path, file_change.new_lines.as_bytes()) {
236             panic!("Cannot write to {}: {}", path.display(), e);
237         }
238     }
239     file_change
240 }
241
242 /// Replaces a region in a text delimited by two lines matching regexes.
243 ///
244 /// * `text` is the input text on which you want to perform the replacement
245 /// * `start` is a `&str` that describes the delimiter line before the region you want to replace.
246 ///   As the `&str` will be converted to a `Regex`, this can contain regex syntax, too.
247 /// * `end` is a `&str` that describes the delimiter line until where the replacement should happen.
248 ///   As the `&str` will be converted to a `Regex`, this can contain regex syntax, too.
249 /// * If `replace_start` is true, the `start` delimiter line is replaced as well. The `end`
250 ///   delimiter line is never replaced.
251 /// * `replacements` is a closure that has to return a `Vec<String>` which contains the new text.
252 ///
253 /// If you want to perform the replacement on files instead of already parsed text,
254 /// use `replace_region_in_file`.
255 ///
256 /// # Example
257 ///
258 /// ```
259 /// let the_text = "replace_start\nsome text\nthat will be replaced\nreplace_end";
260 /// let result =
261 ///     clippy_dev::replace_region_in_text(the_text, "replace_start", "replace_end", false, || {
262 ///         vec!["a different".to_string(), "text".to_string()]
263 ///     })
264 ///     .new_lines;
265 /// assert_eq!("replace_start\na different\ntext\nreplace_end", result);
266 /// ```
267 pub fn replace_region_in_text<F>(text: &str, start: &str, end: &str, replace_start: bool, replacements: F) -> FileChange
268 where
269     F: FnOnce() -> Vec<String>,
270 {
271     let replace_it = replacements();
272     let mut in_old_region = false;
273     let mut found = false;
274     let mut new_lines = vec![];
275     let start = Regex::new(start).unwrap();
276     let end = Regex::new(end).unwrap();
277
278     for line in text.lines() {
279         if in_old_region {
280             if end.is_match(line) {
281                 in_old_region = false;
282                 new_lines.extend(replace_it.clone());
283                 new_lines.push(line.to_string());
284             }
285         } else if start.is_match(line) {
286             if !replace_start {
287                 new_lines.push(line.to_string());
288             }
289             in_old_region = true;
290             found = true;
291         } else {
292             new_lines.push(line.to_string());
293         }
294     }
295
296     if !found {
297         // This happens if the provided regex in `clippy_dev/src/main.rs` is not found in the
298         // given text or file. Most likely this is an error on the programmer's side and the Regex
299         // is incorrect.
300         eprintln!("error: regex `{:?}` not found. You may have to update it.", start);
301     }
302
303     let mut new_lines = new_lines.join("\n");
304     if text.ends_with('\n') {
305         new_lines.push('\n');
306     }
307     let changed = new_lines != text;
308     FileChange { changed, new_lines }
309 }
310
311 /// Returns the path to the Clippy project directory
312 #[must_use]
313 pub fn clippy_project_root() -> PathBuf {
314     let current_dir = std::env::current_dir().unwrap();
315     for path in current_dir.ancestors() {
316         let result = std::fs::read_to_string(path.join("Cargo.toml"));
317         if let Err(err) = &result {
318             if err.kind() == std::io::ErrorKind::NotFound {
319                 continue;
320             }
321         }
322
323         let content = result.unwrap();
324         if content.contains("[package]\nname = \"clippy\"") {
325             return path.to_path_buf();
326         }
327     }
328     panic!("error: Can't determine root of project. Please run inside a Clippy working dir.");
329 }
330
331 #[test]
332 fn test_parse_contents() {
333     let result: Vec<Lint> = parse_contents(
334         r#"
335 declare_clippy_lint! {
336     pub PTR_ARG,
337     style,
338     "really long \
339      text"
340 }
341
342 declare_clippy_lint!{
343     pub DOC_MARKDOWN,
344     pedantic,
345     "single line"
346 }
347
348 /// some doc comment
349 declare_deprecated_lint! {
350     pub SHOULD_ASSERT_EQ,
351     "`assert!()` will be more flexible with RFC 2011"
352 }
353     "#,
354         "module_name",
355     )
356     .collect();
357
358     let expected = vec![
359         Lint::new("ptr_arg", "style", "really long text", None, "module_name"),
360         Lint::new("doc_markdown", "pedantic", "single line", None, "module_name"),
361         Lint::new(
362             "should_assert_eq",
363             "Deprecated",
364             "`assert!()` will be more flexible with RFC 2011",
365             Some("`assert!()` will be more flexible with RFC 2011"),
366             "module_name",
367         ),
368     ];
369     assert_eq!(expected, result);
370 }
371
372 #[test]
373 fn test_replace_region() {
374     let text = "\nabc\n123\n789\ndef\nghi";
375     let expected = FileChange {
376         changed: true,
377         new_lines: "\nabc\nhello world\ndef\nghi".to_string(),
378     };
379     let result = replace_region_in_text(text, r#"^\s*abc$"#, r#"^\s*def"#, false, || {
380         vec!["hello world".to_string()]
381     });
382     assert_eq!(expected, result);
383 }
384
385 #[test]
386 fn test_replace_region_with_start() {
387     let text = "\nabc\n123\n789\ndef\nghi";
388     let expected = FileChange {
389         changed: true,
390         new_lines: "\nhello world\ndef\nghi".to_string(),
391     };
392     let result = replace_region_in_text(text, r#"^\s*abc$"#, r#"^\s*def"#, true, || {
393         vec!["hello world".to_string()]
394     });
395     assert_eq!(expected, result);
396 }
397
398 #[test]
399 fn test_replace_region_no_changes() {
400     let text = "123\n456\n789";
401     let expected = FileChange {
402         changed: false,
403         new_lines: "123\n456\n789".to_string(),
404     };
405     let result = replace_region_in_text(text, r#"^\s*123$"#, r#"^\s*456"#, false, || vec![]);
406     assert_eq!(expected, result);
407 }
408
409 #[test]
410 fn test_usable_lints() {
411     let lints = vec![
412         Lint::new("should_assert_eq", "Deprecated", "abc", Some("Reason"), "module_name"),
413         Lint::new("should_assert_eq2", "Not Deprecated", "abc", None, "module_name"),
414         Lint::new("should_assert_eq2", "internal", "abc", None, "module_name"),
415         Lint::new("should_assert_eq2", "internal_style", "abc", None, "module_name"),
416     ];
417     let expected = vec![Lint::new(
418         "should_assert_eq2",
419         "Not Deprecated",
420         "abc",
421         None,
422         "module_name",
423     )];
424     assert_eq!(expected, Lint::usable_lints(lints.into_iter()).collect::<Vec<Lint>>());
425 }
426
427 #[test]
428 fn test_by_lint_group() {
429     let lints = vec![
430         Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
431         Lint::new("should_assert_eq2", "group2", "abc", None, "module_name"),
432         Lint::new("incorrect_match", "group1", "abc", None, "module_name"),
433     ];
434     let mut expected: HashMap<String, Vec<Lint>> = HashMap::new();
435     expected.insert(
436         "group1".to_string(),
437         vec![
438             Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
439             Lint::new("incorrect_match", "group1", "abc", None, "module_name"),
440         ],
441     );
442     expected.insert(
443         "group2".to_string(),
444         vec![Lint::new("should_assert_eq2", "group2", "abc", None, "module_name")],
445     );
446     assert_eq!(expected, Lint::by_lint_group(lints.into_iter()));
447 }
448
449 #[test]
450 fn test_gen_changelog_lint_list() {
451     let lints = vec![
452         Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
453         Lint::new("should_assert_eq2", "group2", "abc", None, "module_name"),
454         Lint::new("incorrect_internal", "internal_style", "abc", None, "module_name"),
455     ];
456     let expected = vec![
457         format!("[`should_assert_eq`]: {}#should_assert_eq", DOCS_LINK.to_string()),
458         format!("[`should_assert_eq2`]: {}#should_assert_eq2", DOCS_LINK.to_string()),
459     ];
460     assert_eq!(expected, gen_changelog_lint_list(&lints));
461 }
462
463 #[test]
464 fn test_gen_deprecated() {
465     let lints = vec![
466         Lint::new(
467             "should_assert_eq",
468             "group1",
469             "abc",
470             Some("has been superseded by should_assert_eq2"),
471             "module_name",
472         ),
473         Lint::new(
474             "another_deprecated",
475             "group2",
476             "abc",
477             Some("will be removed"),
478             "module_name",
479         ),
480         Lint::new("should_assert_eq2", "group2", "abc", None, "module_name"),
481     ];
482     let expected: Vec<String> = vec![
483         "    store.register_removed(",
484         "        \"clippy::should_assert_eq\",",
485         "        \"has been superseded by should_assert_eq2\",",
486         "    );",
487         "    store.register_removed(",
488         "        \"clippy::another_deprecated\",",
489         "        \"will be removed\",",
490         "    );",
491     ]
492     .into_iter()
493     .map(String::from)
494     .collect();
495     assert_eq!(expected, gen_deprecated(&lints));
496 }
497
498 #[test]
499 fn test_gen_modules_list() {
500     let lints = vec![
501         Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
502         Lint::new("should_assert_eq2", "group2", "abc", Some("abc"), "deprecated"),
503         Lint::new("incorrect_stuff", "group3", "abc", None, "another_module"),
504         Lint::new("incorrect_internal", "internal_style", "abc", None, "module_name"),
505     ];
506     let expected = vec![
507         "pub mod another_module;".to_string(),
508         "pub mod module_name;".to_string(),
509     ];
510     assert_eq!(expected, gen_modules_list(&lints));
511 }
512
513 #[test]
514 fn test_gen_lint_group_list() {
515     let lints = vec![
516         Lint::new("abc", "group1", "abc", None, "module_name"),
517         Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
518         Lint::new("should_assert_eq2", "group2", "abc", Some("abc"), "deprecated"),
519         Lint::new("internal", "internal_style", "abc", None, "module_name"),
520     ];
521     let expected = vec![
522         "        LintId::of(&module_name::ABC),".to_string(),
523         "        LintId::of(&module_name::INTERNAL),".to_string(),
524         "        LintId::of(&module_name::SHOULD_ASSERT_EQ),".to_string(),
525     ];
526     assert_eq!(expected, gen_lint_group_list(&lints));
527 }