2 #![cfg_attr(feature = "deny-warnings", deny(warnings))]
3 // warn on lints, that are included in `rust-lang/rust`s bootstrap
4 #![warn(rust_2018_idioms, unused_lifetimes)]
6 use itertools::Itertools;
8 use std::collections::HashMap;
11 use std::lazy::SyncLazy;
12 use std::path::{Path, PathBuf};
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>(group_name: &str, lints: impl Iterator<Item = &'a Lint>) -> Vec<String> {
104 let header = format!(
105 r#"store.register_group(true, "clippy::{0}", Some("clippy_{0}"), vec!["#,
108 let footer = "])".to_string();
110 let mut result = vec![header];
114 .map(|l| format!("LintId::of({}::{}),", l.module, l.name.to_uppercase()))
123 /// Generates the `pub mod module_name` list in `clippy_lints/src/lib.rs`.
125 pub fn gen_modules_list<'a>(lints: impl Iterator<Item = &'a Lint>) -> Vec<String> {
129 .map(|module| format!("mod {};", module))
131 .collect::<Vec<String>>()
134 /// Generates the list of lint links at the bottom of the README
136 pub fn gen_changelog_lint_list<'a>(lints: impl Iterator<Item = &'a Lint>) -> Vec<String> {
138 .sorted_by_key(|l| &l.name)
139 .map(|l| format!("[`{}`]: {}#{}", l.name, DOCS_LINK, l.name))
143 /// Generates the `register_removed` code in `./clippy_lints/src/lib.rs`.
145 pub fn gen_deprecated<'a>(lints: impl Iterator<Item = &'a Lint>) -> Vec<String> {
146 let mut result = vec!["{".to_string()];
147 result.extend(lints.flat_map(|l| {
152 " store.register_removed(".to_string(),
153 format!(" \"clippy::{}\",", l.name),
154 format!(" \"{}\",", depr_text),
158 .expect("only deprecated lints should be passed")
160 result.push("}".to_string());
165 pub fn gen_register_lint_list<'a>(
166 internal_lints: impl Iterator<Item = &'a Lint>,
167 usable_lints: impl Iterator<Item = &'a Lint>,
169 let header = " store.register_lints(&[".to_string();
170 let footer = " ])".to_string();
171 let internal_lints = internal_lints
172 .sorted_by_key(|l| format!(" {}::{},", l.module, l.name.to_uppercase()))
175 " #[cfg(feature = \"internal-lints\")]\n {}::{},",
177 l.name.to_uppercase()
180 let other_lints = usable_lints
181 .sorted_by_key(|l| format!(" {}::{},", l.module, l.name.to_uppercase()))
182 .map(|l| format!(" {}::{},", l.module, l.name.to_uppercase()))
184 let mut lint_list = vec![header];
185 lint_list.extend(internal_lints);
186 lint_list.extend(other_lints);
187 lint_list.push(footer);
191 /// Gathers all files in `src/clippy_lints` and gathers all lints inside
192 pub fn gather_all() -> impl Iterator<Item = Lint> {
193 lint_files().flat_map(|f| gather_from_file(&f))
196 fn gather_from_file(dir_entry: &walkdir::DirEntry) -> impl Iterator<Item = Lint> {
197 let content = fs::read_to_string(dir_entry.path()).unwrap();
198 let path = dir_entry.path();
199 let filename = path.file_stem().unwrap();
200 let path_buf = path.with_file_name(filename);
201 let mut rel_path = path_buf
202 .strip_prefix(clippy_project_root().join("clippy_lints/src"))
203 .expect("only files in `clippy_lints/src` should be looked at");
204 // If the lints are stored in mod.rs, we get the module name from
205 // the containing directory:
206 if filename == "mod" {
207 rel_path = rel_path.parent().unwrap();
210 let module = rel_path
212 .map(|c| c.as_os_str().to_str().unwrap())
216 parse_contents(&content, &module)
219 fn parse_contents(content: &str, module: &str) -> impl Iterator<Item = Lint> {
220 let lints = DEC_CLIPPY_LINT_RE
221 .captures_iter(content)
222 .map(|m| Lint::new(&m["name"], &m["cat"], &m["desc"], None, module));
223 let deprecated = DEC_DEPRECATED_LINT_RE
224 .captures_iter(content)
225 .map(|m| Lint::new(&m["name"], "Deprecated", &m["desc"], Some(&m["desc"]), module));
226 // Removing the `.collect::<Vec<Lint>>().into_iter()` causes some lifetime issues due to the map
227 lints.chain(deprecated).collect::<Vec<Lint>>().into_iter()
230 /// Collects all .rs files in the `clippy_lints/src` directory
231 fn lint_files() -> impl Iterator<Item = walkdir::DirEntry> {
232 // We use `WalkDir` instead of `fs::read_dir` here in order to recurse into subdirectories.
233 // Otherwise we would not collect all the lints, for example in `clippy_lints/src/methods/`.
234 let path = clippy_project_root().join("clippy_lints/src");
237 .filter_map(Result::ok)
238 .filter(|f| f.path().extension() == Some(OsStr::new("rs")))
241 /// Whether a file has had its text changed or not
242 #[derive(PartialEq, Debug)]
243 pub struct FileChange {
245 pub new_lines: String,
248 /// Replaces a region in a file delimited by two lines matching regexes.
250 /// `path` is the relative path to the file on which you want to perform the replacement.
252 /// See `replace_region_in_text` for documentation of the other options.
256 /// Panics if the path could not read or then written
257 pub fn replace_region_in_file<F>(
266 F: FnOnce() -> Vec<String>,
268 let contents = fs::read_to_string(path).unwrap_or_else(|e| panic!("Cannot read from {}: {}", path.display(), e));
269 let file_change = replace_region_in_text(&contents, start, end, replace_start, replacements);
272 if let Err(e) = fs::write(path, file_change.new_lines.as_bytes()) {
273 panic!("Cannot write to {}: {}", path.display(), e);
279 /// Replaces a region in a text delimited by two lines matching regexes.
281 /// * `text` is the input text on which you want to perform the replacement
282 /// * `start` is a `&str` that describes the delimiter line before the region you want to replace.
283 /// As the `&str` will be converted to a `Regex`, this can contain regex syntax, too.
284 /// * `end` is a `&str` that describes the delimiter line until where the replacement should happen.
285 /// As the `&str` will be converted to a `Regex`, this can contain regex syntax, too.
286 /// * If `replace_start` is true, the `start` delimiter line is replaced as well. The `end`
287 /// delimiter line is never replaced.
288 /// * `replacements` is a closure that has to return a `Vec<String>` which contains the new text.
290 /// If you want to perform the replacement on files instead of already parsed text,
291 /// use `replace_region_in_file`.
296 /// let the_text = "replace_start\nsome text\nthat will be replaced\nreplace_end";
298 /// clippy_dev::replace_region_in_text(the_text, "replace_start", "replace_end", false, || {
299 /// vec!["a different".to_string(), "text".to_string()]
302 /// assert_eq!("replace_start\na different\ntext\nreplace_end", result);
307 /// Panics if start or end is not valid regex
308 pub fn replace_region_in_text<F>(text: &str, start: &str, end: &str, replace_start: bool, replacements: F) -> FileChange
310 F: FnOnce() -> Vec<String>,
312 let replace_it = replacements();
313 let mut in_old_region = false;
314 let mut found = false;
315 let mut new_lines = vec![];
316 let start = Regex::new(start).unwrap();
317 let end = Regex::new(end).unwrap();
319 for line in text.lines() {
321 if end.is_match(line) {
322 in_old_region = false;
323 new_lines.extend(replace_it.clone());
324 new_lines.push(line.to_string());
326 } else if start.is_match(line) {
328 new_lines.push(line.to_string());
330 in_old_region = true;
333 new_lines.push(line.to_string());
338 // This happens if the provided regex in `clippy_dev/src/main.rs` does not match in the
339 // given text or file. Most likely this is an error on the programmer's side and the Regex
341 eprintln!("error: regex \n{:?}\ndoesn't match. You may have to update it.", start);
342 std::process::exit(1);
345 let mut new_lines = new_lines.join("\n");
346 if text.ends_with('\n') {
347 new_lines.push('\n');
349 let changed = new_lines != text;
350 FileChange { changed, new_lines }
353 /// Returns the path to the Clippy project directory
357 /// Panics if the current directory could not be retrieved, there was an error reading any of the
358 /// Cargo.toml files or ancestor directory is the clippy root directory
360 pub fn clippy_project_root() -> PathBuf {
361 let current_dir = std::env::current_dir().unwrap();
362 for path in current_dir.ancestors() {
363 let result = std::fs::read_to_string(path.join("Cargo.toml"));
364 if let Err(err) = &result {
365 if err.kind() == std::io::ErrorKind::NotFound {
370 let content = result.unwrap();
371 if content.contains("[package]\nname = \"clippy\"") {
372 return path.to_path_buf();
375 panic!("error: Can't determine root of project. Please run inside a Clippy working dir.");
379 fn test_parse_contents() {
380 let result: Vec<Lint> = parse_contents(
382 declare_clippy_lint! {
389 declare_clippy_lint!{
396 declare_deprecated_lint! {
397 pub SHOULD_ASSERT_EQ,
398 "`assert!()` will be more flexible with RFC 2011"
406 Lint::new("ptr_arg", "style", "really long text", None, "module_name"),
407 Lint::new("doc_markdown", "pedantic", "single line", None, "module_name"),
411 "`assert!()` will be more flexible with RFC 2011",
412 Some("`assert!()` will be more flexible with RFC 2011"),
416 assert_eq!(expected, result);
420 fn test_replace_region() {
421 let text = "\nabc\n123\n789\ndef\nghi";
422 let expected = FileChange {
424 new_lines: "\nabc\nhello world\ndef\nghi".to_string(),
426 let result = replace_region_in_text(text, r#"^\s*abc$"#, r#"^\s*def"#, false, || {
427 vec!["hello world".to_string()]
429 assert_eq!(expected, result);
433 fn test_replace_region_with_start() {
434 let text = "\nabc\n123\n789\ndef\nghi";
435 let expected = FileChange {
437 new_lines: "\nhello world\ndef\nghi".to_string(),
439 let result = replace_region_in_text(text, r#"^\s*abc$"#, r#"^\s*def"#, true, || {
440 vec!["hello world".to_string()]
442 assert_eq!(expected, result);
446 fn test_replace_region_no_changes() {
447 let text = "123\n456\n789";
448 let expected = FileChange {
450 new_lines: "123\n456\n789".to_string(),
452 let result = replace_region_in_text(text, r#"^\s*123$"#, r#"^\s*456"#, false, Vec::new);
453 assert_eq!(expected, result);
457 fn test_usable_lints() {
459 Lint::new("should_assert_eq", "Deprecated", "abc", Some("Reason"), "module_name"),
460 Lint::new("should_assert_eq2", "Not Deprecated", "abc", None, "module_name"),
461 Lint::new("should_assert_eq2", "internal", "abc", None, "module_name"),
462 Lint::new("should_assert_eq2", "internal_style", "abc", None, "module_name"),
464 let expected = vec![Lint::new(
471 assert_eq!(expected, Lint::usable_lints(&lints));
475 fn test_by_lint_group() {
477 Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
478 Lint::new("should_assert_eq2", "group2", "abc", None, "module_name"),
479 Lint::new("incorrect_match", "group1", "abc", None, "module_name"),
481 let mut expected: HashMap<String, Vec<Lint>> = HashMap::new();
483 "group1".to_string(),
485 Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
486 Lint::new("incorrect_match", "group1", "abc", None, "module_name"),
490 "group2".to_string(),
491 vec![Lint::new("should_assert_eq2", "group2", "abc", None, "module_name")],
493 assert_eq!(expected, Lint::by_lint_group(lints.into_iter()));
497 fn test_gen_changelog_lint_list() {
499 Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
500 Lint::new("should_assert_eq2", "group2", "abc", None, "module_name"),
503 format!("[`should_assert_eq`]: {}#should_assert_eq", DOCS_LINK.to_string()),
504 format!("[`should_assert_eq2`]: {}#should_assert_eq2", DOCS_LINK.to_string()),
506 assert_eq!(expected, gen_changelog_lint_list(lints.iter()));
510 fn test_gen_deprecated() {
516 Some("has been superseded by should_assert_eq2"),
520 "another_deprecated",
523 Some("will be removed"),
527 let expected: Vec<String> = vec![
529 " store.register_removed(",
530 " \"clippy::should_assert_eq\",",
531 " \"has been superseded by should_assert_eq2\",",
533 " store.register_removed(",
534 " \"clippy::another_deprecated\",",
535 " \"will be removed\",",
542 assert_eq!(expected, gen_deprecated(lints.iter()));
547 fn test_gen_deprecated_fail() {
548 let lints = vec![Lint::new("should_assert_eq2", "group2", "abc", None, "module_name")];
549 let _deprecated_lints = gen_deprecated(lints.iter());
553 fn test_gen_modules_list() {
555 Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
556 Lint::new("incorrect_stuff", "group3", "abc", None, "another_module"),
558 let expected = vec!["mod another_module;".to_string(), "mod module_name;".to_string()];
559 assert_eq!(expected, gen_modules_list(lints.iter()));
563 fn test_gen_lint_group_list() {
565 Lint::new("abc", "group1", "abc", None, "module_name"),
566 Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
567 Lint::new("internal", "internal_style", "abc", None, "module_name"),
570 "store.register_group(true, \"clippy::group1\", Some(\"clippy_group1\"), vec![",
571 "LintId::of(module_name::ABC),",
572 "LintId::of(module_name::INTERNAL),",
573 "LintId::of(module_name::SHOULD_ASSERT_EQ),",
576 assert_eq!(expected, gen_lint_group_list("group1", lints.iter()));