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::path::{Path, PathBuf};
14 pub mod stderr_length_check;
18 static ref DEC_CLIPPY_LINT_RE: Regex = Regex::new(
20 declare_clippy_lint!\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*[})]
28 static ref DEC_DEPRECATED_LINT_RE: Regex = Regex::new(
30 declare_deprecated_lint!\s*[{(]\s*
32 \s+pub\s+(?P<name>[A-Z_][A-Z_0-9]*)\s*,\s*
33 "(?P<desc>(?:[^"\\]+|\\(?s).(?-s))*)"\s*[})]
37 static ref NL_ESCAPE_RE: Regex = Regex::new(r#"\\\n\s*"#).unwrap();
40 pub static DOCS_LINK: &str = "https://rust-lang.github.io/rust-clippy/master/index.html";
42 /// Lint data parsed from the Clippy source code.
43 #[derive(Clone, PartialEq, Debug)]
48 pub deprecation: Option<String>,
54 pub fn new(name: &str, group: &str, desc: &str, deprecation: Option<&str>, module: &str) -> 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(),
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.is_internal())
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")
74 /// Returns the lints in a `HashMap`, grouped by the different lint groups
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()
81 pub fn is_internal(&self) -> bool {
82 self.group.starts_with("internal")
86 /// Generates the Vec items for `register_lint_group` calls in `clippy_lints/src/lib.rs`.
88 pub fn gen_lint_group_list(lints: &[Lint]) -> Vec<String> {
92 if l.deprecation.is_some() {
95 Some(format!(" LintId::of(&{}::{}),", l.module, l.name.to_uppercase()))
99 .collect::<Vec<String>>()
102 /// Generates the `pub mod module_name` list in `clippy_lints/src/lib.rs`.
104 pub fn gen_modules_list(lints: &[Lint]) -> Vec<String> {
108 if l.is_internal() || l.deprecation.is_some() {
111 Some(l.module.clone())
115 .map(|module| format!("pub mod {};", module))
117 .collect::<Vec<String>>()
120 /// Generates the list of lint links at the bottom of the README
122 pub fn gen_changelog_lint_list(lints: &[Lint]) -> Vec<String> {
125 .sorted_by_key(|l| l.name.clone())
130 Some(format!("[`{}`]: {}#{}", l.name, DOCS_LINK, l.name))
136 /// Generates the `register_removed` code in `./clippy_lints/src/lib.rs`.
138 pub fn gen_deprecated(lints: &[Lint]) -> Vec<String> {
142 l.clone().deprecation.map(|depr_text| {
144 " store.register_removed(".to_string(),
145 format!(" \"clippy::{}\",", l.name),
146 format!(" \"{}\",", depr_text),
152 .collect::<Vec<String>>()
156 pub fn gen_register_lint_list(lints: &[Lint]) -> Vec<String> {
157 let pre = " store.register_lints(&[".to_string();
158 let post = " ]);".to_string();
159 let mut inner = lints
162 if !l.is_internal() && l.deprecation.is_none() {
163 Some(format!(" &{}::{},", l.module, l.name.to_uppercase()))
169 .collect::<Vec<String>>();
170 inner.insert(0, pre);
175 /// Gathers all files in `src/clippy_lints` and gathers all lints inside
176 pub fn gather_all() -> impl Iterator<Item = Lint> {
177 lint_files().flat_map(|f| gather_from_file(&f))
180 fn gather_from_file(dir_entry: &walkdir::DirEntry) -> impl Iterator<Item = Lint> {
181 let content = fs::read_to_string(dir_entry.path()).unwrap();
182 let path = dir_entry.path();
183 let filename = path.file_stem().unwrap();
184 let path_buf = path.with_file_name(filename);
185 let mut rel_path = path_buf
186 .strip_prefix(clippy_project_root().join("clippy_lints/src"))
187 .expect("only files in `clippy_lints/src` should be looked at");
188 // If the lints are stored in mod.rs, we get the module name from
189 // the containing directory:
190 if filename == "mod" {
191 rel_path = rel_path.parent().unwrap();
194 let module = rel_path
196 .map(|c| c.as_os_str().to_str().unwrap())
200 parse_contents(&content, &module)
203 fn parse_contents(content: &str, module: &str) -> impl Iterator<Item = Lint> {
204 let lints = DEC_CLIPPY_LINT_RE
205 .captures_iter(content)
206 .map(|m| Lint::new(&m["name"], &m["cat"], &m["desc"], None, module));
207 let deprecated = DEC_DEPRECATED_LINT_RE
208 .captures_iter(content)
209 .map(|m| Lint::new(&m["name"], "Deprecated", &m["desc"], Some(&m["desc"]), module));
210 // Removing the `.collect::<Vec<Lint>>().into_iter()` causes some lifetime issues due to the map
211 lints.chain(deprecated).collect::<Vec<Lint>>().into_iter()
214 /// Collects all .rs files in the `clippy_lints/src` directory
215 fn lint_files() -> impl Iterator<Item = walkdir::DirEntry> {
216 // We use `WalkDir` instead of `fs::read_dir` here in order to recurse into subdirectories.
217 // Otherwise we would not collect all the lints, for example in `clippy_lints/src/methods/`.
218 let path = clippy_project_root().join("clippy_lints/src");
221 .filter_map(Result::ok)
222 .filter(|f| f.path().extension() == Some(OsStr::new("rs")))
225 /// Whether a file has had its text changed or not
226 #[derive(PartialEq, Debug)]
227 pub struct FileChange {
229 pub new_lines: String,
232 /// Replaces a region in a file delimited by two lines matching regexes.
234 /// `path` is the relative path to the file on which you want to perform the replacement.
236 /// See `replace_region_in_text` for documentation of the other options.
237 pub fn replace_region_in_file<F>(
246 F: FnOnce() -> Vec<String>,
248 let contents = fs::read_to_string(path).unwrap_or_else(|e| panic!("Cannot read from {}: {}", path.display(), e));
249 let file_change = replace_region_in_text(&contents, start, end, replace_start, replacements);
252 if let Err(e) = fs::write(path, file_change.new_lines.as_bytes()) {
253 panic!("Cannot write to {}: {}", path.display(), e);
259 /// Replaces a region in a text delimited by two lines matching regexes.
261 /// * `text` is the input text on which you want to perform the replacement
262 /// * `start` is a `&str` that describes the delimiter line before the region you want to replace.
263 /// As the `&str` will be converted to a `Regex`, this can contain regex syntax, too.
264 /// * `end` is a `&str` that describes the delimiter line until where the replacement should happen.
265 /// As the `&str` will be converted to a `Regex`, this can contain regex syntax, too.
266 /// * If `replace_start` is true, the `start` delimiter line is replaced as well. The `end`
267 /// delimiter line is never replaced.
268 /// * `replacements` is a closure that has to return a `Vec<String>` which contains the new text.
270 /// If you want to perform the replacement on files instead of already parsed text,
271 /// use `replace_region_in_file`.
276 /// let the_text = "replace_start\nsome text\nthat will be replaced\nreplace_end";
278 /// clippy_dev::replace_region_in_text(the_text, "replace_start", "replace_end", false, || {
279 /// vec!["a different".to_string(), "text".to_string()]
282 /// assert_eq!("replace_start\na different\ntext\nreplace_end", result);
284 pub fn replace_region_in_text<F>(text: &str, start: &str, end: &str, replace_start: bool, replacements: F) -> FileChange
286 F: FnOnce() -> Vec<String>,
288 let replace_it = replacements();
289 let mut in_old_region = false;
290 let mut found = false;
291 let mut new_lines = vec![];
292 let start = Regex::new(start).unwrap();
293 let end = Regex::new(end).unwrap();
295 for line in text.lines() {
297 if end.is_match(line) {
298 in_old_region = false;
299 new_lines.extend(replace_it.clone());
300 new_lines.push(line.to_string());
302 } else if start.is_match(line) {
304 new_lines.push(line.to_string());
306 in_old_region = true;
309 new_lines.push(line.to_string());
314 // This happens if the provided regex in `clippy_dev/src/main.rs` is not found in the
315 // given text or file. Most likely this is an error on the programmer's side and the Regex
317 eprintln!("error: regex `{:?}` not found. You may have to update it.", start);
320 let mut new_lines = new_lines.join("\n");
321 if text.ends_with('\n') {
322 new_lines.push('\n');
324 let changed = new_lines != text;
325 FileChange { changed, new_lines }
328 /// Returns the path to the Clippy project directory
330 pub fn clippy_project_root() -> PathBuf {
331 let current_dir = std::env::current_dir().unwrap();
332 for path in current_dir.ancestors() {
333 let result = std::fs::read_to_string(path.join("Cargo.toml"));
334 if let Err(err) = &result {
335 if err.kind() == std::io::ErrorKind::NotFound {
340 let content = result.unwrap();
341 if content.contains("[package]\nname = \"clippy\"") {
342 return path.to_path_buf();
345 panic!("error: Can't determine root of project. Please run inside a Clippy working dir.");
349 fn test_parse_contents() {
350 let result: Vec<Lint> = parse_contents(
352 declare_clippy_lint! {
359 declare_clippy_lint!{
366 declare_deprecated_lint! {
367 pub SHOULD_ASSERT_EQ,
368 "`assert!()` will be more flexible with RFC 2011"
376 Lint::new("ptr_arg", "style", "really long text", None, "module_name"),
377 Lint::new("doc_markdown", "pedantic", "single line", None, "module_name"),
381 "`assert!()` will be more flexible with RFC 2011",
382 Some("`assert!()` will be more flexible with RFC 2011"),
386 assert_eq!(expected, result);
390 fn test_replace_region() {
391 let text = "\nabc\n123\n789\ndef\nghi";
392 let expected = FileChange {
394 new_lines: "\nabc\nhello world\ndef\nghi".to_string(),
396 let result = replace_region_in_text(text, r#"^\s*abc$"#, r#"^\s*def"#, false, || {
397 vec!["hello world".to_string()]
399 assert_eq!(expected, result);
403 fn test_replace_region_with_start() {
404 let text = "\nabc\n123\n789\ndef\nghi";
405 let expected = FileChange {
407 new_lines: "\nhello world\ndef\nghi".to_string(),
409 let result = replace_region_in_text(text, r#"^\s*abc$"#, r#"^\s*def"#, true, || {
410 vec!["hello world".to_string()]
412 assert_eq!(expected, result);
416 fn test_replace_region_no_changes() {
417 let text = "123\n456\n789";
418 let expected = FileChange {
420 new_lines: "123\n456\n789".to_string(),
422 let result = replace_region_in_text(text, r#"^\s*123$"#, r#"^\s*456"#, false, || vec![]);
423 assert_eq!(expected, result);
427 fn test_usable_lints() {
429 Lint::new("should_assert_eq", "Deprecated", "abc", Some("Reason"), "module_name"),
430 Lint::new("should_assert_eq2", "Not Deprecated", "abc", None, "module_name"),
431 Lint::new("should_assert_eq2", "internal", "abc", None, "module_name"),
432 Lint::new("should_assert_eq2", "internal_style", "abc", None, "module_name"),
434 let expected = vec![Lint::new(
441 assert_eq!(expected, Lint::usable_lints(lints.into_iter()).collect::<Vec<Lint>>());
445 fn test_by_lint_group() {
447 Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
448 Lint::new("should_assert_eq2", "group2", "abc", None, "module_name"),
449 Lint::new("incorrect_match", "group1", "abc", None, "module_name"),
451 let mut expected: HashMap<String, Vec<Lint>> = HashMap::new();
453 "group1".to_string(),
455 Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
456 Lint::new("incorrect_match", "group1", "abc", None, "module_name"),
460 "group2".to_string(),
461 vec![Lint::new("should_assert_eq2", "group2", "abc", None, "module_name")],
463 assert_eq!(expected, Lint::by_lint_group(lints.into_iter()));
467 fn test_gen_changelog_lint_list() {
469 Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
470 Lint::new("should_assert_eq2", "group2", "abc", None, "module_name"),
471 Lint::new("incorrect_internal", "internal_style", "abc", None, "module_name"),
474 format!("[`should_assert_eq`]: {}#should_assert_eq", DOCS_LINK.to_string()),
475 format!("[`should_assert_eq2`]: {}#should_assert_eq2", DOCS_LINK.to_string()),
477 assert_eq!(expected, gen_changelog_lint_list(&lints));
481 fn test_gen_deprecated() {
487 Some("has been superseded by should_assert_eq2"),
491 "another_deprecated",
494 Some("will be removed"),
497 Lint::new("should_assert_eq2", "group2", "abc", None, "module_name"),
499 let expected: Vec<String> = vec![
500 " store.register_removed(",
501 " \"clippy::should_assert_eq\",",
502 " \"has been superseded by should_assert_eq2\",",
504 " store.register_removed(",
505 " \"clippy::another_deprecated\",",
506 " \"will be removed\",",
512 assert_eq!(expected, gen_deprecated(&lints));
516 fn test_gen_modules_list() {
518 Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
519 Lint::new("should_assert_eq2", "group2", "abc", Some("abc"), "deprecated"),
520 Lint::new("incorrect_stuff", "group3", "abc", None, "another_module"),
521 Lint::new("incorrect_internal", "internal_style", "abc", None, "module_name"),
524 "pub mod another_module;".to_string(),
525 "pub mod module_name;".to_string(),
527 assert_eq!(expected, gen_modules_list(&lints));
531 fn test_gen_lint_group_list() {
533 Lint::new("abc", "group1", "abc", None, "module_name"),
534 Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
535 Lint::new("should_assert_eq2", "group2", "abc", Some("abc"), "deprecated"),
536 Lint::new("internal", "internal_style", "abc", None, "module_name"),
539 " LintId::of(&module_name::ABC),".to_string(),
540 " LintId::of(&module_name::INTERNAL),".to_string(),
541 " LintId::of(&module_name::SHOULD_ASSERT_EQ),".to_string(),
543 assert_eq!(expected, gen_lint_group_list(&lints));