1 #![cfg_attr(feature = "deny-warnings", deny(warnings))]
4 use itertools::Itertools;
6 use std::collections::HashMap;
9 use std::lazy::SyncLazy;
10 use std::path::{Path, PathBuf};
19 pub mod stderr_length_check;
22 static DEC_CLIPPY_LINT_RE: SyncLazy<Regex> = SyncLazy::new(|| {
25 declare_clippy_lint!\s*[\{(]
27 \s+pub\s+(?P<name>[A-Z_][A-Z_0-9]*)\s*,\s*
28 (?P<cat>[a-z_]+)\s*,\s*
29 "(?P<desc>(?:[^"\\]+|\\(?s).(?-s))*)"\s*[})]
35 static DEC_DEPRECATED_LINT_RE: SyncLazy<Regex> = SyncLazy::new(|| {
38 declare_deprecated_lint!\s*[{(]\s*
40 \s+pub\s+(?P<name>[A-Z_][A-Z_0-9]*)\s*,\s*
41 "(?P<desc>(?:[^"\\]+|\\(?s).(?-s))*)"\s*[})]
46 static NL_ESCAPE_RE: SyncLazy<Regex> = SyncLazy::new(|| Regex::new(r#"\\\n\s*"#).unwrap());
48 pub static DOCS_LINK: &str = "https://rust-lang.github.io/rust-clippy/master/index.html";
50 /// Lint data parsed from the Clippy source code.
51 #[derive(Clone, PartialEq, Debug)]
56 pub deprecation: Option<String>,
62 pub fn new(name: &str, group: &str, desc: &str, deprecation: Option<&str>, module: &str) -> Self {
64 name: name.to_lowercase(),
65 group: group.to_string(),
66 desc: NL_ESCAPE_RE.replace(&desc.replace("\\\"", "\""), "").to_string(),
67 deprecation: deprecation.map(ToString::to_string),
68 module: module.to_string(),
72 /// Returns all non-deprecated lints and non-internal lints
74 pub fn usable_lints(lints: &[Self]) -> Vec<Self> {
77 .filter(|l| l.deprecation.is_none() && !l.group.starts_with("internal"))
82 /// Returns all internal lints (not `internal_warn` lints)
84 pub fn internal_lints(lints: &[Self]) -> Vec<Self> {
85 lints.iter().filter(|l| l.group == "internal").cloned().collect()
88 /// Returns all deprecated lints
90 pub fn deprecated_lints(lints: &[Self]) -> Vec<Self> {
91 lints.iter().filter(|l| l.deprecation.is_some()).cloned().collect()
94 /// Returns the lints in a `HashMap`, grouped by the different lint groups
96 pub fn by_lint_group(lints: impl Iterator<Item = Self>) -> HashMap<String, Vec<Self>> {
97 lints.map(|lint| (lint.group.to_string(), lint)).into_group_map()
101 /// Generates the Vec items for `register_lint_group` calls in `clippy_lints/src/lib.rs`.
103 pub fn gen_lint_group_list<'a>(lints: impl Iterator<Item = &'a Lint>) -> Vec<String> {
105 .map(|l| format!(" LintId::of(&{}::{}),", l.module, l.name.to_uppercase()))
107 .collect::<Vec<String>>()
110 /// Generates the `pub mod module_name` list in `clippy_lints/src/lib.rs`.
112 pub fn gen_modules_list<'a>(lints: impl Iterator<Item = &'a Lint>) -> Vec<String> {
116 .map(|module| format!("mod {};", module))
118 .collect::<Vec<String>>()
121 /// Generates the list of lint links at the bottom of the README
123 pub fn gen_changelog_lint_list<'a>(lints: impl Iterator<Item = &'a Lint>) -> Vec<String> {
125 .sorted_by_key(|l| &l.name)
126 .map(|l| format!("[`{}`]: {}#{}", l.name, DOCS_LINK, l.name))
130 /// Generates the `register_removed` code in `./clippy_lints/src/lib.rs`.
132 pub fn gen_deprecated<'a>(lints: impl Iterator<Item = &'a Lint>) -> Vec<String> {
139 " store.register_removed(".to_string(),
140 format!(" \"clippy::{}\",", l.name),
141 format!(" \"{}\",", depr_text),
145 .expect("only deprecated lints should be passed")
147 .collect::<Vec<String>>()
151 pub fn gen_register_lint_list<'a>(
152 internal_lints: impl Iterator<Item = &'a Lint>,
153 usable_lints: impl Iterator<Item = &'a Lint>,
155 let header = " store.register_lints(&[".to_string();
156 let footer = " ]);".to_string();
157 let internal_lints = internal_lints
158 .sorted_by_key(|l| format!(" &{}::{},", l.module, l.name.to_uppercase()))
161 " #[cfg(feature = \"internal-lints\")]\n &{}::{},",
163 l.name.to_uppercase()
166 let other_lints = usable_lints
167 .sorted_by_key(|l| format!(" &{}::{},", l.module, l.name.to_uppercase()))
168 .map(|l| format!(" &{}::{},", l.module, l.name.to_uppercase()))
170 let mut lint_list = vec![header];
171 lint_list.extend(internal_lints);
172 lint_list.extend(other_lints);
173 lint_list.push(footer);
177 /// Gathers all files in `src/clippy_lints` and gathers all lints inside
178 pub fn gather_all() -> impl Iterator<Item = Lint> {
179 lint_files().flat_map(|f| gather_from_file(&f))
182 fn gather_from_file(dir_entry: &walkdir::DirEntry) -> impl Iterator<Item = Lint> {
183 let content = fs::read_to_string(dir_entry.path()).unwrap();
184 let path = dir_entry.path();
185 let filename = path.file_stem().unwrap();
186 let path_buf = path.with_file_name(filename);
187 let mut rel_path = path_buf
188 .strip_prefix(clippy_project_root().join("clippy_lints/src"))
189 .expect("only files in `clippy_lints/src` should be looked at");
190 // If the lints are stored in mod.rs, we get the module name from
191 // the containing directory:
192 if filename == "mod" {
193 rel_path = rel_path.parent().unwrap();
196 let module = rel_path
198 .map(|c| c.as_os_str().to_str().unwrap())
202 parse_contents(&content, &module)
205 fn parse_contents(content: &str, module: &str) -> impl Iterator<Item = Lint> {
206 let lints = DEC_CLIPPY_LINT_RE
207 .captures_iter(content)
208 .map(|m| Lint::new(&m["name"], &m["cat"], &m["desc"], None, module));
209 let deprecated = DEC_DEPRECATED_LINT_RE
210 .captures_iter(content)
211 .map(|m| Lint::new(&m["name"], "Deprecated", &m["desc"], Some(&m["desc"]), module));
212 // Removing the `.collect::<Vec<Lint>>().into_iter()` causes some lifetime issues due to the map
213 lints.chain(deprecated).collect::<Vec<Lint>>().into_iter()
216 /// Collects all .rs files in the `clippy_lints/src` directory
217 fn lint_files() -> impl Iterator<Item = walkdir::DirEntry> {
218 // We use `WalkDir` instead of `fs::read_dir` here in order to recurse into subdirectories.
219 // Otherwise we would not collect all the lints, for example in `clippy_lints/src/methods/`.
220 let path = clippy_project_root().join("clippy_lints/src");
223 .filter_map(Result::ok)
224 .filter(|f| f.path().extension() == Some(OsStr::new("rs")))
227 /// Whether a file has had its text changed or not
228 #[derive(PartialEq, Debug)]
229 pub struct FileChange {
231 pub new_lines: String,
234 /// Replaces a region in a file delimited by two lines matching regexes.
236 /// `path` is the relative path to the file on which you want to perform the replacement.
238 /// See `replace_region_in_text` for documentation of the other options.
242 /// Panics if the path could not read or then written
243 pub fn replace_region_in_file<F>(
252 F: FnOnce() -> Vec<String>,
254 let contents = fs::read_to_string(path).unwrap_or_else(|e| panic!("Cannot read from {}: {}", path.display(), e));
255 let file_change = replace_region_in_text(&contents, start, end, replace_start, replacements);
258 if let Err(e) = fs::write(path, file_change.new_lines.as_bytes()) {
259 panic!("Cannot write to {}: {}", path.display(), e);
265 /// Replaces a region in a text delimited by two lines matching regexes.
267 /// * `text` is the input text on which you want to perform the replacement
268 /// * `start` is a `&str` that describes the delimiter line before the region you want to replace.
269 /// As the `&str` will be converted to a `Regex`, this can contain regex syntax, too.
270 /// * `end` is a `&str` that describes the delimiter line until where the replacement should happen.
271 /// As the `&str` will be converted to a `Regex`, this can contain regex syntax, too.
272 /// * If `replace_start` is true, the `start` delimiter line is replaced as well. The `end`
273 /// delimiter line is never replaced.
274 /// * `replacements` is a closure that has to return a `Vec<String>` which contains the new text.
276 /// If you want to perform the replacement on files instead of already parsed text,
277 /// use `replace_region_in_file`.
282 /// let the_text = "replace_start\nsome text\nthat will be replaced\nreplace_end";
284 /// clippy_dev::replace_region_in_text(the_text, "replace_start", "replace_end", false, || {
285 /// vec!["a different".to_string(), "text".to_string()]
288 /// assert_eq!("replace_start\na different\ntext\nreplace_end", result);
293 /// Panics if start or end is not valid regex
294 pub fn replace_region_in_text<F>(text: &str, start: &str, end: &str, replace_start: bool, replacements: F) -> FileChange
296 F: FnOnce() -> Vec<String>,
298 let replace_it = replacements();
299 let mut in_old_region = false;
300 let mut found = false;
301 let mut new_lines = vec![];
302 let start = Regex::new(start).unwrap();
303 let end = Regex::new(end).unwrap();
305 for line in text.lines() {
307 if end.is_match(line) {
308 in_old_region = false;
309 new_lines.extend(replace_it.clone());
310 new_lines.push(line.to_string());
312 } else if start.is_match(line) {
314 new_lines.push(line.to_string());
316 in_old_region = true;
319 new_lines.push(line.to_string());
324 // This happens if the provided regex in `clippy_dev/src/main.rs` does not match in the
325 // given text or file. Most likely this is an error on the programmer's side and the Regex
327 eprintln!("error: regex \n{:?}\ndoesn't match. You may have to update it.", start);
328 std::process::exit(1);
331 let mut new_lines = new_lines.join("\n");
332 if text.ends_with('\n') {
333 new_lines.push('\n');
335 let changed = new_lines != text;
336 FileChange { changed, new_lines }
339 /// Returns the path to the Clippy project directory
343 /// Panics if the current directory could not be retrieved, there was an error reading any of the
344 /// Cargo.toml files or ancestor directory is the clippy root directory
346 pub fn clippy_project_root() -> PathBuf {
347 let current_dir = std::env::current_dir().unwrap();
348 for path in current_dir.ancestors() {
349 let result = std::fs::read_to_string(path.join("Cargo.toml"));
350 if let Err(err) = &result {
351 if err.kind() == std::io::ErrorKind::NotFound {
356 let content = result.unwrap();
357 if content.contains("[package]\nname = \"clippy\"") {
358 return path.to_path_buf();
361 panic!("error: Can't determine root of project. Please run inside a Clippy working dir.");
365 fn test_parse_contents() {
366 let result: Vec<Lint> = parse_contents(
368 declare_clippy_lint! {
375 declare_clippy_lint!{
382 declare_deprecated_lint! {
383 pub SHOULD_ASSERT_EQ,
384 "`assert!()` will be more flexible with RFC 2011"
392 Lint::new("ptr_arg", "style", "really long text", None, "module_name"),
393 Lint::new("doc_markdown", "pedantic", "single line", None, "module_name"),
397 "`assert!()` will be more flexible with RFC 2011",
398 Some("`assert!()` will be more flexible with RFC 2011"),
402 assert_eq!(expected, result);
406 fn test_replace_region() {
407 let text = "\nabc\n123\n789\ndef\nghi";
408 let expected = FileChange {
410 new_lines: "\nabc\nhello world\ndef\nghi".to_string(),
412 let result = replace_region_in_text(text, r#"^\s*abc$"#, r#"^\s*def"#, false, || {
413 vec!["hello world".to_string()]
415 assert_eq!(expected, result);
419 fn test_replace_region_with_start() {
420 let text = "\nabc\n123\n789\ndef\nghi";
421 let expected = FileChange {
423 new_lines: "\nhello world\ndef\nghi".to_string(),
425 let result = replace_region_in_text(text, r#"^\s*abc$"#, r#"^\s*def"#, true, || {
426 vec!["hello world".to_string()]
428 assert_eq!(expected, result);
432 fn test_replace_region_no_changes() {
433 let text = "123\n456\n789";
434 let expected = FileChange {
436 new_lines: "123\n456\n789".to_string(),
438 let result = replace_region_in_text(text, r#"^\s*123$"#, r#"^\s*456"#, false, Vec::new);
439 assert_eq!(expected, result);
443 fn test_usable_lints() {
445 Lint::new("should_assert_eq", "Deprecated", "abc", Some("Reason"), "module_name"),
446 Lint::new("should_assert_eq2", "Not Deprecated", "abc", None, "module_name"),
447 Lint::new("should_assert_eq2", "internal", "abc", None, "module_name"),
448 Lint::new("should_assert_eq2", "internal_style", "abc", None, "module_name"),
450 let expected = vec![Lint::new(
457 assert_eq!(expected, Lint::usable_lints(&lints));
461 fn test_by_lint_group() {
463 Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
464 Lint::new("should_assert_eq2", "group2", "abc", None, "module_name"),
465 Lint::new("incorrect_match", "group1", "abc", None, "module_name"),
467 let mut expected: HashMap<String, Vec<Lint>> = HashMap::new();
469 "group1".to_string(),
471 Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
472 Lint::new("incorrect_match", "group1", "abc", None, "module_name"),
476 "group2".to_string(),
477 vec![Lint::new("should_assert_eq2", "group2", "abc", None, "module_name")],
479 assert_eq!(expected, Lint::by_lint_group(lints.into_iter()));
483 fn test_gen_changelog_lint_list() {
485 Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
486 Lint::new("should_assert_eq2", "group2", "abc", None, "module_name"),
489 format!("[`should_assert_eq`]: {}#should_assert_eq", DOCS_LINK.to_string()),
490 format!("[`should_assert_eq2`]: {}#should_assert_eq2", DOCS_LINK.to_string()),
492 assert_eq!(expected, gen_changelog_lint_list(lints.iter()));
496 fn test_gen_deprecated() {
502 Some("has been superseded by should_assert_eq2"),
506 "another_deprecated",
509 Some("will be removed"),
513 let expected: Vec<String> = vec![
514 " store.register_removed(",
515 " \"clippy::should_assert_eq\",",
516 " \"has been superseded by should_assert_eq2\",",
518 " store.register_removed(",
519 " \"clippy::another_deprecated\",",
520 " \"will be removed\",",
526 assert_eq!(expected, gen_deprecated(lints.iter()));
531 fn test_gen_deprecated_fail() {
532 let lints = vec![Lint::new("should_assert_eq2", "group2", "abc", None, "module_name")];
533 let _ = gen_deprecated(lints.iter());
537 fn test_gen_modules_list() {
539 Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
540 Lint::new("incorrect_stuff", "group3", "abc", None, "another_module"),
542 let expected = vec!["mod another_module;".to_string(), "mod module_name;".to_string()];
543 assert_eq!(expected, gen_modules_list(lints.iter()));
547 fn test_gen_lint_group_list() {
549 Lint::new("abc", "group1", "abc", None, "module_name"),
550 Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
551 Lint::new("internal", "internal_style", "abc", None, "module_name"),
554 " LintId::of(&module_name::ABC),".to_string(),
555 " LintId::of(&module_name::INTERNAL),".to_string(),
556 " LintId::of(&module_name::SHOULD_ASSERT_EQ),".to_string(),
558 assert_eq!(expected, gen_lint_group_list(lints.iter()));