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::*;
13 static ref DEC_CLIPPY_LINT_RE: Regex = Regex::new(
15 declare_clippy_lint!\s*[\{(]
17 \s+pub\s+(?P<name>[A-Z_][A-Z_0-9]*)\s*,\s*
18 (?P<cat>[a-z_]+)\s*,\s*
19 "(?P<desc>(?:[^"\\]+|\\(?s).(?-s))*)"\s*[})]
23 static ref DEC_DEPRECATED_LINT_RE: Regex = Regex::new(
25 declare_deprecated_lint!\s*[{(]\s*
27 \s+pub\s+(?P<name>[A-Z_][A-Z_0-9]*)\s*,\s*
28 "(?P<desc>(?:[^"\\]+|\\(?s).(?-s))*)"\s*[})]
32 static ref NL_ESCAPE_RE: Regex = Regex::new(r#"\\\n\s*"#).unwrap();
33 pub static ref DOCS_LINK: String = "https://rust-lang.github.io/rust-clippy/master/index.html".to_string();
36 /// Lint data parsed from the Clippy source code.
37 #[derive(Clone, PartialEq, Debug)]
42 pub deprecation: Option<String>,
48 pub fn new(name: &str, group: &str, desc: &str, deprecation: Option<&str>, module: &str) -> Self {
50 name: name.to_lowercase(),
51 group: group.to_string(),
52 desc: NL_ESCAPE_RE.replace(&desc.replace("\\\"", "\""), "").to_string(),
53 deprecation: deprecation.map(ToString::to_string),
54 module: module.to_string(),
58 /// Returns all non-deprecated lints and non-internal lints
59 pub fn usable_lints(lints: impl Iterator<Item = Self>) -> impl Iterator<Item = Self> {
60 lints.filter(|l| l.deprecation.is_none() && !l.is_internal())
63 /// Returns the lints in a `HashMap`, grouped by the different lint groups
65 pub fn by_lint_group(lints: &[Self]) -> HashMap<String, Vec<Self>> {
68 .map(|lint| (lint.group.to_string(), lint.clone()))
73 pub fn is_internal(&self) -> bool {
74 self.group.starts_with("internal")
78 /// Generates the Vec items for `register_lint_group` calls in `clippy_lints/src/lib.rs`.
80 pub fn gen_lint_group_list(lints: Vec<Lint>) -> Vec<String> {
84 if l.is_internal() || l.deprecation.is_some() {
87 Some(format!(" LintId::of(&{}::{}),", l.module, l.name.to_uppercase()))
91 .collect::<Vec<String>>()
94 /// Generates the `pub mod module_name` list in `clippy_lints/src/lib.rs`.
96 pub fn gen_modules_list(lints: Vec<Lint>) -> Vec<String> {
100 if l.is_internal() || l.deprecation.is_some() {
107 .map(|module| format!("pub mod {};", module))
109 .collect::<Vec<String>>()
112 /// Generates the list of lint links at the bottom of the README
114 pub fn gen_changelog_lint_list(lints: Vec<Lint>) -> Vec<String> {
115 let mut lint_list_sorted: Vec<Lint> = lints;
116 lint_list_sorted.sort_by_key(|l| l.name.clone());
123 Some(format!("[`{}`]: {}#{}", l.name, DOCS_LINK.clone(), l.name))
129 /// Generates the `register_removed` code in `./clippy_lints/src/lib.rs`.
131 pub fn gen_deprecated(lints: &[Lint]) -> Vec<String> {
135 l.clone().deprecation.map(|depr_text| {
137 " store.register_removed(".to_string(),
138 format!(" \"clippy::{}\",", l.name),
139 format!(" \"{}\",", depr_text),
145 .collect::<Vec<String>>()
149 pub fn gen_register_lint_list(lints: &[Lint]) -> Vec<String> {
150 let pre = " store.register_lints(&[".to_string();
151 let post = " ]);".to_string();
152 let mut inner = lints
155 if !l.is_internal() && l.deprecation.is_none() {
156 Some(format!(" &{}::{},", l.module, l.name.to_uppercase()))
162 .collect::<Vec<String>>();
163 inner.insert(0, pre);
168 /// Gathers all files in `src/clippy_lints` and gathers all lints inside
169 pub fn gather_all() -> impl Iterator<Item = Lint> {
170 lint_files().flat_map(|f| gather_from_file(&f))
173 fn gather_from_file(dir_entry: &walkdir::DirEntry) -> impl Iterator<Item = Lint> {
174 let mut file = fs::File::open(dir_entry.path()).unwrap();
175 let mut content = String::new();
176 file.read_to_string(&mut content).unwrap();
177 let mut filename = dir_entry.path().file_stem().unwrap().to_str().unwrap();
178 // If the lints are stored in mod.rs, we get the module name from
179 // the containing directory:
180 if filename == "mod" {
190 parse_contents(&content, filename)
193 fn parse_contents(content: &str, filename: &str) -> impl Iterator<Item = Lint> {
194 let lints = DEC_CLIPPY_LINT_RE
195 .captures_iter(content)
196 .map(|m| Lint::new(&m["name"], &m["cat"], &m["desc"], None, filename));
197 let deprecated = DEC_DEPRECATED_LINT_RE
198 .captures_iter(content)
199 .map(|m| Lint::new(&m["name"], "Deprecated", &m["desc"], Some(&m["desc"]), filename));
200 // Removing the `.collect::<Vec<Lint>>().into_iter()` causes some lifetime issues due to the map
201 lints.chain(deprecated).collect::<Vec<Lint>>().into_iter()
204 /// Collects all .rs files in the `clippy_lints/src` directory
205 fn lint_files() -> impl Iterator<Item = walkdir::DirEntry> {
206 // We use `WalkDir` instead of `fs::read_dir` here in order to recurse into subdirectories.
207 // Otherwise we would not collect all the lints, for example in `clippy_lints/src/methods/`.
208 WalkDir::new("../clippy_lints/src")
210 .filter_map(std::result::Result::ok)
211 .filter(|f| f.path().extension() == Some(OsStr::new("rs")))
214 /// Whether a file has had its text changed or not
215 #[derive(PartialEq, Debug)]
216 pub struct FileChange {
218 pub new_lines: String,
221 /// Replaces a region in a file delimited by two lines matching regexes.
223 /// `path` is the relative path to the file on which you want to perform the replacement.
225 /// See `replace_region_in_text` for documentation of the other options.
226 #[allow(clippy::expect_fun_call)]
227 pub fn replace_region_in_file<F>(
236 F: Fn() -> Vec<String>,
238 let mut f = fs::File::open(path).expect(&format!("File not found: {}", path));
239 let mut contents = String::new();
240 f.read_to_string(&mut contents)
241 .expect("Something went wrong reading the file");
242 let file_change = replace_region_in_text(&contents, start, end, replace_start, replacements);
245 let mut f = fs::File::create(path).expect(&format!("File not found: {}", path));
246 f.write_all(file_change.new_lines.as_bytes())
247 .expect("Unable to write file");
248 // Ensure we write the changes with a trailing newline so that
249 // the file has the proper line endings.
250 f.write_all(b"\n").expect("Unable to write file");
255 /// Replaces a region in a text delimited by two lines matching regexes.
257 /// * `text` is the input text on which you want to perform the replacement
258 /// * `start` is a `&str` that describes the delimiter line before the region you want to replace.
259 /// As the `&str` will be converted to a `Regex`, this can contain regex syntax, too.
260 /// * `end` is a `&str` that describes the delimiter line until where the replacement should happen.
261 /// As the `&str` will be converted to a `Regex`, this can contain regex syntax, too.
262 /// * If `replace_start` is true, the `start` delimiter line is replaced as well. The `end`
263 /// delimiter line is never replaced.
264 /// * `replacements` is a closure that has to return a `Vec<String>` which contains the new text.
266 /// If you want to perform the replacement on files instead of already parsed text,
267 /// use `replace_region_in_file`.
272 /// let the_text = "replace_start\nsome text\nthat will be replaced\nreplace_end";
273 /// let result = clippy_dev::replace_region_in_text(the_text, r#"replace_start"#, r#"replace_end"#, false, || {
274 /// vec!["a different".to_string(), "text".to_string()]
277 /// assert_eq!("replace_start\na different\ntext\nreplace_end", result);
279 pub fn replace_region_in_text<F>(text: &str, start: &str, end: &str, replace_start: bool, replacements: F) -> FileChange
281 F: Fn() -> Vec<String>,
283 let lines = text.lines();
284 let mut in_old_region = false;
285 let mut found = false;
286 let mut new_lines = vec![];
287 let start = Regex::new(start).unwrap();
288 let end = Regex::new(end).unwrap();
290 for line in lines.clone() {
292 if end.is_match(&line) {
293 in_old_region = false;
294 new_lines.extend(replacements());
295 new_lines.push(line.to_string());
297 } else if start.is_match(&line) {
299 new_lines.push(line.to_string());
301 in_old_region = true;
304 new_lines.push(line.to_string());
309 // This happens if the provided regex in `clippy_dev/src/main.rs` is not found in the
310 // given text or file. Most likely this is an error on the programmer's side and the Regex
312 eprintln!("error: regex `{:?}` not found. You may have to update it.", start);
316 changed: lines.ne(new_lines.clone()),
317 new_lines: new_lines.join("\n"),
322 fn test_parse_contents() {
323 let result: Vec<Lint> = parse_contents(
325 declare_clippy_lint! {
332 declare_clippy_lint!{
339 declare_deprecated_lint! {
340 pub SHOULD_ASSERT_EQ,
341 "`assert!()` will be more flexible with RFC 2011"
349 Lint::new("ptr_arg", "style", "really long text", None, "module_name"),
350 Lint::new("doc_markdown", "pedantic", "single line", None, "module_name"),
354 "`assert!()` will be more flexible with RFC 2011",
355 Some("`assert!()` will be more flexible with RFC 2011"),
359 assert_eq!(expected, result);
363 fn test_replace_region() {
364 let text = "\nabc\n123\n789\ndef\nghi";
365 let expected = FileChange {
367 new_lines: "\nabc\nhello world\ndef\nghi".to_string(),
369 let result = replace_region_in_text(text, r#"^\s*abc$"#, r#"^\s*def"#, false, || {
370 vec!["hello world".to_string()]
372 assert_eq!(expected, result);
376 fn test_replace_region_with_start() {
377 let text = "\nabc\n123\n789\ndef\nghi";
378 let expected = FileChange {
380 new_lines: "\nhello world\ndef\nghi".to_string(),
382 let result = replace_region_in_text(text, r#"^\s*abc$"#, r#"^\s*def"#, true, || {
383 vec!["hello world".to_string()]
385 assert_eq!(expected, result);
389 fn test_replace_region_no_changes() {
390 let text = "123\n456\n789";
391 let expected = FileChange {
393 new_lines: "123\n456\n789".to_string(),
395 let result = replace_region_in_text(text, r#"^\s*123$"#, r#"^\s*456"#, false, || vec![]);
396 assert_eq!(expected, result);
400 fn test_usable_lints() {
402 Lint::new("should_assert_eq", "Deprecated", "abc", Some("Reason"), "module_name"),
403 Lint::new("should_assert_eq2", "Not Deprecated", "abc", None, "module_name"),
404 Lint::new("should_assert_eq2", "internal", "abc", None, "module_name"),
405 Lint::new("should_assert_eq2", "internal_style", "abc", None, "module_name"),
407 let expected = vec![Lint::new(
414 assert_eq!(expected, Lint::usable_lints(lints.into_iter()).collect::<Vec<Lint>>());
418 fn test_by_lint_group() {
420 Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
421 Lint::new("should_assert_eq2", "group2", "abc", None, "module_name"),
422 Lint::new("incorrect_match", "group1", "abc", None, "module_name"),
424 let mut expected: HashMap<String, Vec<Lint>> = HashMap::new();
426 "group1".to_string(),
428 Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
429 Lint::new("incorrect_match", "group1", "abc", None, "module_name"),
433 "group2".to_string(),
434 vec![Lint::new("should_assert_eq2", "group2", "abc", None, "module_name")],
436 assert_eq!(expected, Lint::by_lint_group(&lints));
440 fn test_gen_changelog_lint_list() {
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_internal", "internal_style", "abc", None, "module_name"),
447 format!("[`should_assert_eq`]: {}#should_assert_eq", DOCS_LINK.to_string()),
448 format!("[`should_assert_eq2`]: {}#should_assert_eq2", DOCS_LINK.to_string()),
450 assert_eq!(expected, gen_changelog_lint_list(lints));
454 fn test_gen_deprecated() {
460 Some("has been superseded by should_assert_eq2"),
464 "another_deprecated",
467 Some("will be removed"),
470 Lint::new("should_assert_eq2", "group2", "abc", None, "module_name"),
472 let expected: Vec<String> = vec![
473 " store.register_removed(",
474 " \"clippy::should_assert_eq\",",
475 " \"has been superseded by should_assert_eq2\",",
477 " store.register_removed(",
478 " \"clippy::another_deprecated\",",
479 " \"will be removed\",",
485 assert_eq!(expected, gen_deprecated(&lints));
489 fn test_gen_modules_list() {
491 Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
492 Lint::new("should_assert_eq2", "group2", "abc", Some("abc"), "deprecated"),
493 Lint::new("incorrect_stuff", "group3", "abc", None, "another_module"),
494 Lint::new("incorrect_internal", "internal_style", "abc", None, "module_name"),
497 "pub mod another_module;".to_string(),
498 "pub mod module_name;".to_string(),
500 assert_eq!(expected, gen_modules_list(lints));
504 fn test_gen_lint_group_list() {
506 Lint::new("abc", "group1", "abc", None, "module_name"),
507 Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
508 Lint::new("should_assert_eq2", "group2", "abc", Some("abc"), "deprecated"),
509 Lint::new("incorrect_internal", "internal_style", "abc", None, "module_name"),
512 " LintId::of(&module_name::ABC),".to_string(),
513 " LintId::of(&module_name::SHOULD_ASSERT_EQ),".to_string(),
515 assert_eq!(expected, gen_lint_group_list(lints));