1 #![cfg_attr(feature = "deny-warnings", deny(warnings))]
3 use itertools::Itertools;
4 use lazy_static::lazy_static;
6 use std::collections::HashMap;
9 use std::io::prelude::*;
10 use std::path::{Path, PathBuf};
14 static ref DEC_CLIPPY_LINT_RE: Regex = Regex::new(
16 declare_clippy_lint!\s*[\{(]
18 \s+pub\s+(?P<name>[A-Z_][A-Z_0-9]*)\s*,\s*
19 (?P<cat>[a-z_]+)\s*,\s*
20 "(?P<desc>(?:[^"\\]+|\\(?s).(?-s))*)"\s*[})]
24 static ref DEC_DEPRECATED_LINT_RE: Regex = Regex::new(
26 declare_deprecated_lint!\s*[{(]\s*
28 \s+pub\s+(?P<name>[A-Z_][A-Z_0-9]*)\s*,\s*
29 "(?P<desc>(?:[^"\\]+|\\(?s).(?-s))*)"\s*[})]
33 static ref NL_ESCAPE_RE: Regex = Regex::new(r#"\\\n\s*"#).unwrap();
34 pub static ref DOCS_LINK: String = "https://rust-lang.github.io/rust-clippy/master/index.html".to_string();
37 /// Lint data parsed from the Clippy source code.
38 #[derive(Clone, PartialEq, Debug)]
43 pub deprecation: Option<String>,
49 pub fn new(name: &str, group: &str, desc: &str, deprecation: Option<&str>, module: &str) -> Self {
51 name: name.to_lowercase(),
52 group: group.to_string(),
53 desc: NL_ESCAPE_RE.replace(&desc.replace("\\\"", "\""), "").to_string(),
54 deprecation: deprecation.map(ToString::to_string),
55 module: module.to_string(),
59 /// Returns all non-deprecated lints and non-internal lints
60 pub fn usable_lints(lints: impl Iterator<Item = Self>) -> impl Iterator<Item = Self> {
61 lints.filter(|l| l.deprecation.is_none() && !l.is_internal())
64 /// Returns the lints in a `HashMap`, grouped by the different lint groups
66 pub fn by_lint_group(lints: &[Self]) -> HashMap<String, Vec<Self>> {
69 .map(|lint| (lint.group.to_string(), lint.clone()))
74 pub fn is_internal(&self) -> bool {
75 self.group.starts_with("internal")
79 /// Generates the Vec items for `register_lint_group` calls in `clippy_lints/src/lib.rs`.
81 pub fn gen_lint_group_list(lints: Vec<Lint>) -> Vec<String> {
85 if l.is_internal() || l.deprecation.is_some() {
88 Some(format!(" LintId::of(&{}::{}),", l.module, l.name.to_uppercase()))
92 .collect::<Vec<String>>()
95 /// Generates the `pub mod module_name` list in `clippy_lints/src/lib.rs`.
97 pub fn gen_modules_list(lints: Vec<Lint>) -> Vec<String> {
101 if l.is_internal() || l.deprecation.is_some() {
108 .map(|module| format!("pub mod {};", module))
110 .collect::<Vec<String>>()
113 /// Generates the list of lint links at the bottom of the README
115 pub fn gen_changelog_lint_list(lints: Vec<Lint>) -> Vec<String> {
116 let mut lint_list_sorted: Vec<Lint> = lints;
117 lint_list_sorted.sort_by_key(|l| l.name.clone());
124 Some(format!("[`{}`]: {}#{}", l.name, DOCS_LINK.clone(), l.name))
130 /// Generates the `register_removed` code in `./clippy_lints/src/lib.rs`.
132 pub fn gen_deprecated(lints: &[Lint]) -> Vec<String> {
136 l.clone().deprecation.map(|depr_text| {
138 " store.register_removed(".to_string(),
139 format!(" \"clippy::{}\",", l.name),
140 format!(" \"{}\",", depr_text),
146 .collect::<Vec<String>>()
150 pub fn gen_register_lint_list(lints: &[Lint]) -> Vec<String> {
151 let pre = " store.register_lints(&[".to_string();
152 let post = " ]);".to_string();
153 let mut inner = lints
156 if !l.is_internal() && l.deprecation.is_none() {
157 Some(format!(" &{}::{},", l.module, l.name.to_uppercase()))
163 .collect::<Vec<String>>();
164 inner.insert(0, pre);
169 /// Gathers all files in `src/clippy_lints` and gathers all lints inside
170 pub fn gather_all() -> impl Iterator<Item = Lint> {
171 lint_files().flat_map(|f| gather_from_file(&f))
174 fn gather_from_file(dir_entry: &walkdir::DirEntry) -> impl Iterator<Item = Lint> {
175 let mut file = fs::File::open(dir_entry.path()).unwrap();
176 let mut content = String::new();
177 file.read_to_string(&mut content).unwrap();
178 let mut filename = dir_entry.path().file_stem().unwrap().to_str().unwrap();
179 // If the lints are stored in mod.rs, we get the module name from
180 // the containing directory:
181 if filename == "mod" {
191 parse_contents(&content, filename)
194 fn parse_contents(content: &str, filename: &str) -> impl Iterator<Item = Lint> {
195 let lints = DEC_CLIPPY_LINT_RE
196 .captures_iter(content)
197 .map(|m| Lint::new(&m["name"], &m["cat"], &m["desc"], None, filename));
198 let deprecated = DEC_DEPRECATED_LINT_RE
199 .captures_iter(content)
200 .map(|m| Lint::new(&m["name"], "Deprecated", &m["desc"], Some(&m["desc"]), filename));
201 // Removing the `.collect::<Vec<Lint>>().into_iter()` causes some lifetime issues due to the map
202 lints.chain(deprecated).collect::<Vec<Lint>>().into_iter()
205 /// Collects all .rs files in the `clippy_lints/src` directory
206 fn lint_files() -> impl Iterator<Item = walkdir::DirEntry> {
207 // We use `WalkDir` instead of `fs::read_dir` here in order to recurse into subdirectories.
208 // Otherwise we would not collect all the lints, for example in `clippy_lints/src/methods/`.
209 let path = clippy_project_root().join("clippy_lints/src");
212 .filter_map(std::result::Result::ok)
213 .filter(|f| f.path().extension() == Some(OsStr::new("rs")))
216 /// Whether a file has had its text changed or not
217 #[derive(PartialEq, Debug)]
218 pub struct FileChange {
220 pub new_lines: String,
223 /// Replaces a region in a file delimited by two lines matching regexes.
225 /// `path` is the relative path to the file on which you want to perform the replacement.
227 /// See `replace_region_in_text` for documentation of the other options.
228 #[allow(clippy::expect_fun_call)]
229 pub fn replace_region_in_file<F>(
238 F: Fn() -> Vec<String>,
240 let path = clippy_project_root().join(path);
241 let mut f = fs::File::open(&path).expect(&format!("File not found: {}", path.to_string_lossy()));
242 let mut contents = String::new();
243 f.read_to_string(&mut contents)
244 .expect("Something went wrong reading the file");
245 let file_change = replace_region_in_text(&contents, start, end, replace_start, replacements);
248 let mut f = fs::File::create(&path).expect(&format!("File not found: {}", path.to_string_lossy()));
249 f.write_all(file_change.new_lines.as_bytes())
250 .expect("Unable to write file");
251 // Ensure we write the changes with a trailing newline so that
252 // the file has the proper line endings.
253 f.write_all(b"\n").expect("Unable to write file");
258 /// Replaces a region in a text delimited by two lines matching regexes.
260 /// * `text` is the input text on which you want to perform the replacement
261 /// * `start` is a `&str` that describes the delimiter line before the region you want to replace.
262 /// As the `&str` will be converted to a `Regex`, this can contain regex syntax, too.
263 /// * `end` is a `&str` that describes the delimiter line until where the replacement should happen.
264 /// As the `&str` will be converted to a `Regex`, this can contain regex syntax, too.
265 /// * If `replace_start` is true, the `start` delimiter line is replaced as well. The `end`
266 /// delimiter line is never replaced.
267 /// * `replacements` is a closure that has to return a `Vec<String>` which contains the new text.
269 /// If you want to perform the replacement on files instead of already parsed text,
270 /// use `replace_region_in_file`.
275 /// let the_text = "replace_start\nsome text\nthat will be replaced\nreplace_end";
276 /// let result = clippy_dev::replace_region_in_text(the_text, r#"replace_start"#, r#"replace_end"#, false, || {
277 /// vec!["a different".to_string(), "text".to_string()]
280 /// assert_eq!("replace_start\na different\ntext\nreplace_end", result);
282 pub fn replace_region_in_text<F>(text: &str, start: &str, end: &str, replace_start: bool, replacements: F) -> FileChange
284 F: Fn() -> Vec<String>,
286 let lines = text.lines();
287 let mut in_old_region = false;
288 let mut found = false;
289 let mut new_lines = vec![];
290 let start = Regex::new(start).unwrap();
291 let end = Regex::new(end).unwrap();
293 for line in lines.clone() {
295 if end.is_match(&line) {
296 in_old_region = false;
297 new_lines.extend(replacements());
298 new_lines.push(line.to_string());
300 } else if start.is_match(&line) {
302 new_lines.push(line.to_string());
304 in_old_region = true;
307 new_lines.push(line.to_string());
312 // This happens if the provided regex in `clippy_dev/src/main.rs` is not found in the
313 // given text or file. Most likely this is an error on the programmer's side and the Regex
315 eprintln!("error: regex `{:?}` not found. You may have to update it.", start);
319 changed: lines.ne(new_lines.clone()),
320 new_lines: new_lines.join("\n"),
324 /// Returns the path to the Clippy project directory
325 pub fn clippy_project_root() -> PathBuf {
326 let current_dir = std::env::current_dir().unwrap();
327 for path in current_dir.ancestors() {
328 let result = std::fs::read_to_string(path.join("Cargo.toml"));
329 if let Err(err) = &result {
330 if err.kind() == std::io::ErrorKind::NotFound {
335 let content = result.unwrap();
336 if content.contains("[package]\nname = \"clippy\"") {
337 return path.to_path_buf();
340 panic!("error: Can't determine root of project. Please run inside a Clippy working dir.");
344 fn test_parse_contents() {
345 let result: Vec<Lint> = parse_contents(
347 declare_clippy_lint! {
354 declare_clippy_lint!{
361 declare_deprecated_lint! {
362 pub SHOULD_ASSERT_EQ,
363 "`assert!()` will be more flexible with RFC 2011"
371 Lint::new("ptr_arg", "style", "really long text", None, "module_name"),
372 Lint::new("doc_markdown", "pedantic", "single line", None, "module_name"),
376 "`assert!()` will be more flexible with RFC 2011",
377 Some("`assert!()` will be more flexible with RFC 2011"),
381 assert_eq!(expected, result);
385 fn test_replace_region() {
386 let text = "\nabc\n123\n789\ndef\nghi";
387 let expected = FileChange {
389 new_lines: "\nabc\nhello world\ndef\nghi".to_string(),
391 let result = replace_region_in_text(text, r#"^\s*abc$"#, r#"^\s*def"#, false, || {
392 vec!["hello world".to_string()]
394 assert_eq!(expected, result);
398 fn test_replace_region_with_start() {
399 let text = "\nabc\n123\n789\ndef\nghi";
400 let expected = FileChange {
402 new_lines: "\nhello world\ndef\nghi".to_string(),
404 let result = replace_region_in_text(text, r#"^\s*abc$"#, r#"^\s*def"#, true, || {
405 vec!["hello world".to_string()]
407 assert_eq!(expected, result);
411 fn test_replace_region_no_changes() {
412 let text = "123\n456\n789";
413 let expected = FileChange {
415 new_lines: "123\n456\n789".to_string(),
417 let result = replace_region_in_text(text, r#"^\s*123$"#, r#"^\s*456"#, false, || vec![]);
418 assert_eq!(expected, result);
422 fn test_usable_lints() {
424 Lint::new("should_assert_eq", "Deprecated", "abc", Some("Reason"), "module_name"),
425 Lint::new("should_assert_eq2", "Not Deprecated", "abc", None, "module_name"),
426 Lint::new("should_assert_eq2", "internal", "abc", None, "module_name"),
427 Lint::new("should_assert_eq2", "internal_style", "abc", None, "module_name"),
429 let expected = vec![Lint::new(
436 assert_eq!(expected, Lint::usable_lints(lints.into_iter()).collect::<Vec<Lint>>());
440 fn test_by_lint_group() {
442 Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
443 Lint::new("should_assert_eq2", "group2", "abc", None, "module_name"),
444 Lint::new("incorrect_match", "group1", "abc", None, "module_name"),
446 let mut expected: HashMap<String, Vec<Lint>> = HashMap::new();
448 "group1".to_string(),
450 Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
451 Lint::new("incorrect_match", "group1", "abc", None, "module_name"),
455 "group2".to_string(),
456 vec![Lint::new("should_assert_eq2", "group2", "abc", None, "module_name")],
458 assert_eq!(expected, Lint::by_lint_group(&lints));
462 fn test_gen_changelog_lint_list() {
464 Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
465 Lint::new("should_assert_eq2", "group2", "abc", None, "module_name"),
466 Lint::new("incorrect_internal", "internal_style", "abc", None, "module_name"),
469 format!("[`should_assert_eq`]: {}#should_assert_eq", DOCS_LINK.to_string()),
470 format!("[`should_assert_eq2`]: {}#should_assert_eq2", DOCS_LINK.to_string()),
472 assert_eq!(expected, gen_changelog_lint_list(lints));
476 fn test_gen_deprecated() {
482 Some("has been superseded by should_assert_eq2"),
486 "another_deprecated",
489 Some("will be removed"),
492 Lint::new("should_assert_eq2", "group2", "abc", None, "module_name"),
494 let expected: Vec<String> = vec![
495 " store.register_removed(",
496 " \"clippy::should_assert_eq\",",
497 " \"has been superseded by should_assert_eq2\",",
499 " store.register_removed(",
500 " \"clippy::another_deprecated\",",
501 " \"will be removed\",",
507 assert_eq!(expected, gen_deprecated(&lints));
511 fn test_gen_modules_list() {
513 Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
514 Lint::new("should_assert_eq2", "group2", "abc", Some("abc"), "deprecated"),
515 Lint::new("incorrect_stuff", "group3", "abc", None, "another_module"),
516 Lint::new("incorrect_internal", "internal_style", "abc", None, "module_name"),
519 "pub mod another_module;".to_string(),
520 "pub mod module_name;".to_string(),
522 assert_eq!(expected, gen_modules_list(lints));
526 fn test_gen_lint_group_list() {
528 Lint::new("abc", "group1", "abc", None, "module_name"),
529 Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
530 Lint::new("should_assert_eq2", "group2", "abc", Some("abc"), "deprecated"),
531 Lint::new("incorrect_internal", "internal_style", "abc", None, "module_name"),
534 " LintId::of(&module_name::ABC),".to_string(),
535 " LintId::of(&module_name::SHOULD_ASSERT_EQ),".to_string(),
537 assert_eq!(expected, gen_lint_group_list(lints));