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};
18 pub mod stderr_length_check;
21 static DEC_CLIPPY_LINT_RE: SyncLazy<Regex> = SyncLazy::new(|| {
24 declare_clippy_lint!\s*[\{(]
26 \s+pub\s+(?P<name>[A-Z_][A-Z_0-9]*)\s*,\s*
27 (?P<cat>[a-z_]+)\s*,\s*
28 "(?P<desc>(?:[^"\\]+|\\(?s).(?-s))*)"\s*[})]
34 static DEC_DEPRECATED_LINT_RE: SyncLazy<Regex> = SyncLazy::new(|| {
37 declare_deprecated_lint!\s*[{(]\s*
39 \s+pub\s+(?P<name>[A-Z_][A-Z_0-9]*)\s*,\s*
40 "(?P<desc>(?:[^"\\]+|\\(?s).(?-s))*)"\s*[})]
45 static NL_ESCAPE_RE: SyncLazy<Regex> = SyncLazy::new(|| Regex::new(r#"\\\n\s*"#).unwrap());
47 pub static DOCS_LINK: &str = "https://rust-lang.github.io/rust-clippy/master/index.html";
49 /// Lint data parsed from the Clippy source code.
50 #[derive(Clone, PartialEq, Debug)]
55 pub deprecation: Option<String>,
61 pub fn new(name: &str, group: &str, desc: &str, deprecation: Option<&str>, module: &str) -> Self {
63 name: name.to_lowercase(),
64 group: group.to_string(),
65 desc: NL_ESCAPE_RE.replace(&desc.replace("\\\"", "\""), "").to_string(),
66 deprecation: deprecation.map(ToString::to_string),
67 module: module.to_string(),
71 /// Returns all non-deprecated lints and non-internal lints
73 pub fn usable_lints(lints: &[Self]) -> Vec<Self> {
76 .filter(|l| l.deprecation.is_none() && !l.group.starts_with("internal"))
81 /// Returns all internal lints (not `internal_warn` lints)
83 pub fn internal_lints(lints: &[Self]) -> Vec<Self> {
84 lints.iter().filter(|l| l.group == "internal").cloned().collect()
87 /// Returns all deprecated lints
89 pub fn deprecated_lints(lints: &[Self]) -> Vec<Self> {
90 lints.iter().filter(|l| l.deprecation.is_some()).cloned().collect()
93 /// Returns the lints in a `HashMap`, grouped by the different lint groups
95 pub fn by_lint_group(lints: impl Iterator<Item = Self>) -> HashMap<String, Vec<Self>> {
96 lints.map(|lint| (lint.group.to_string(), lint)).into_group_map()
100 /// Generates the Vec items for `register_lint_group` calls in `clippy_lints/src/lib.rs`.
102 pub fn gen_lint_group_list<'a>(lints: impl Iterator<Item = &'a Lint>) -> Vec<String> {
104 .map(|l| format!(" LintId::of(&{}::{}),", l.module, l.name.to_uppercase()))
106 .collect::<Vec<String>>()
109 /// Generates the `pub mod module_name` list in `clippy_lints/src/lib.rs`.
111 pub fn gen_modules_list<'a>(lints: impl Iterator<Item = &'a Lint>) -> Vec<String> {
115 .map(|module| format!("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<'a>(lints: impl Iterator<Item = &'a Lint>) -> Vec<String> {
124 .sorted_by_key(|l| &l.name)
125 .map(|l| format!("[`{}`]: {}#{}", l.name, DOCS_LINK, l.name))
129 /// Generates the `register_removed` code in `./clippy_lints/src/lib.rs`.
131 pub fn gen_deprecated<'a>(lints: impl Iterator<Item = &'a Lint>) -> Vec<String> {
138 " store.register_removed(".to_string(),
139 format!(" \"clippy::{}\",", l.name),
140 format!(" \"{}\",", depr_text),
144 .expect("only deprecated lints should be passed")
146 .collect::<Vec<String>>()
150 pub fn gen_register_lint_list<'a>(
151 internal_lints: impl Iterator<Item = &'a Lint>,
152 usable_lints: impl Iterator<Item = &'a Lint>,
154 let header = " store.register_lints(&[".to_string();
155 let footer = " ]);".to_string();
156 let internal_lints = internal_lints
157 .sorted_by_key(|l| format!(" &{}::{},", l.module, l.name.to_uppercase()))
160 " #[cfg(feature = \"internal-lints\")]\n &{}::{},",
162 l.name.to_uppercase()
165 let other_lints = usable_lints
166 .sorted_by_key(|l| format!(" &{}::{},", l.module, l.name.to_uppercase()))
167 .map(|l| format!(" &{}::{},", l.module, l.name.to_uppercase()))
169 let mut lint_list = vec![header];
170 lint_list.extend(internal_lints);
171 lint_list.extend(other_lints);
172 lint_list.push(footer);
176 /// Gathers all files in `src/clippy_lints` and gathers all lints inside
177 pub fn gather_all() -> impl Iterator<Item = Lint> {
178 lint_files().flat_map(|f| gather_from_file(&f))
181 fn gather_from_file(dir_entry: &walkdir::DirEntry) -> impl Iterator<Item = Lint> {
182 let content = fs::read_to_string(dir_entry.path()).unwrap();
183 let path = dir_entry.path();
184 let filename = path.file_stem().unwrap();
185 let path_buf = path.with_file_name(filename);
186 let mut rel_path = path_buf
187 .strip_prefix(clippy_project_root().join("clippy_lints/src"))
188 .expect("only files in `clippy_lints/src` should be looked at");
189 // If the lints are stored in mod.rs, we get the module name from
190 // the containing directory:
191 if filename == "mod" {
192 rel_path = rel_path.parent().unwrap();
195 let module = rel_path
197 .map(|c| c.as_os_str().to_str().unwrap())
201 parse_contents(&content, &module)
204 fn parse_contents(content: &str, module: &str) -> impl Iterator<Item = Lint> {
205 let lints = DEC_CLIPPY_LINT_RE
206 .captures_iter(content)
207 .map(|m| Lint::new(&m["name"], &m["cat"], &m["desc"], None, module));
208 let deprecated = DEC_DEPRECATED_LINT_RE
209 .captures_iter(content)
210 .map(|m| Lint::new(&m["name"], "Deprecated", &m["desc"], Some(&m["desc"]), module));
211 // Removing the `.collect::<Vec<Lint>>().into_iter()` causes some lifetime issues due to the map
212 lints.chain(deprecated).collect::<Vec<Lint>>().into_iter()
215 /// Collects all .rs files in the `clippy_lints/src` directory
216 fn lint_files() -> impl Iterator<Item = walkdir::DirEntry> {
217 // We use `WalkDir` instead of `fs::read_dir` here in order to recurse into subdirectories.
218 // Otherwise we would not collect all the lints, for example in `clippy_lints/src/methods/`.
219 let path = clippy_project_root().join("clippy_lints/src");
222 .filter_map(Result::ok)
223 .filter(|f| f.path().extension() == Some(OsStr::new("rs")))
226 /// Whether a file has had its text changed or not
227 #[derive(PartialEq, Debug)]
228 pub struct FileChange {
230 pub new_lines: String,
233 /// Replaces a region in a file delimited by two lines matching regexes.
235 /// `path` is the relative path to the file on which you want to perform the replacement.
237 /// See `replace_region_in_text` for documentation of the other options.
238 pub fn replace_region_in_file<F>(
247 F: FnOnce() -> Vec<String>,
249 let contents = fs::read_to_string(path).unwrap_or_else(|e| panic!("Cannot read from {}: {}", path.display(), e));
250 let file_change = replace_region_in_text(&contents, start, end, replace_start, replacements);
253 if let Err(e) = fs::write(path, file_change.new_lines.as_bytes()) {
254 panic!("Cannot write to {}: {}", path.display(), e);
260 /// Replaces a region in a text delimited by two lines matching regexes.
262 /// * `text` is the input text on which you want to perform the replacement
263 /// * `start` is a `&str` that describes the delimiter line before the region you want to replace.
264 /// As the `&str` will be converted to a `Regex`, this can contain regex syntax, too.
265 /// * `end` is a `&str` that describes the delimiter line until where the replacement should happen.
266 /// As the `&str` will be converted to a `Regex`, this can contain regex syntax, too.
267 /// * If `replace_start` is true, the `start` delimiter line is replaced as well. The `end`
268 /// delimiter line is never replaced.
269 /// * `replacements` is a closure that has to return a `Vec<String>` which contains the new text.
271 /// If you want to perform the replacement on files instead of already parsed text,
272 /// use `replace_region_in_file`.
277 /// let the_text = "replace_start\nsome text\nthat will be replaced\nreplace_end";
279 /// clippy_dev::replace_region_in_text(the_text, "replace_start", "replace_end", false, || {
280 /// vec!["a different".to_string(), "text".to_string()]
283 /// assert_eq!("replace_start\na different\ntext\nreplace_end", result);
285 pub fn replace_region_in_text<F>(text: &str, start: &str, end: &str, replace_start: bool, replacements: F) -> FileChange
287 F: FnOnce() -> Vec<String>,
289 let replace_it = replacements();
290 let mut in_old_region = false;
291 let mut found = false;
292 let mut new_lines = vec![];
293 let start = Regex::new(start).unwrap();
294 let end = Regex::new(end).unwrap();
296 for line in text.lines() {
298 if end.is_match(line) {
299 in_old_region = false;
300 new_lines.extend(replace_it.clone());
301 new_lines.push(line.to_string());
303 } else if start.is_match(line) {
305 new_lines.push(line.to_string());
307 in_old_region = true;
310 new_lines.push(line.to_string());
315 // This happens if the provided regex in `clippy_dev/src/main.rs` does not match in the
316 // given text or file. Most likely this is an error on the programmer's side and the Regex
318 eprintln!("error: regex \n{:?}\ndoesn't match. You may have to update it.", start);
319 std::process::exit(1);
322 let mut new_lines = new_lines.join("\n");
323 if text.ends_with('\n') {
324 new_lines.push('\n');
326 let changed = new_lines != text;
327 FileChange { changed, new_lines }
330 /// Returns the path to the Clippy project directory
332 pub fn clippy_project_root() -> PathBuf {
333 let current_dir = std::env::current_dir().unwrap();
334 for path in current_dir.ancestors() {
335 let result = std::fs::read_to_string(path.join("Cargo.toml"));
336 if let Err(err) = &result {
337 if err.kind() == std::io::ErrorKind::NotFound {
342 let content = result.unwrap();
343 if content.contains("[package]\nname = \"clippy\"") {
344 return path.to_path_buf();
347 panic!("error: Can't determine root of project. Please run inside a Clippy working dir.");
351 fn test_parse_contents() {
352 let result: Vec<Lint> = parse_contents(
354 declare_clippy_lint! {
361 declare_clippy_lint!{
368 declare_deprecated_lint! {
369 pub SHOULD_ASSERT_EQ,
370 "`assert!()` will be more flexible with RFC 2011"
378 Lint::new("ptr_arg", "style", "really long text", None, "module_name"),
379 Lint::new("doc_markdown", "pedantic", "single line", None, "module_name"),
383 "`assert!()` will be more flexible with RFC 2011",
384 Some("`assert!()` will be more flexible with RFC 2011"),
388 assert_eq!(expected, result);
392 fn test_replace_region() {
393 let text = "\nabc\n123\n789\ndef\nghi";
394 let expected = FileChange {
396 new_lines: "\nabc\nhello world\ndef\nghi".to_string(),
398 let result = replace_region_in_text(text, r#"^\s*abc$"#, r#"^\s*def"#, false, || {
399 vec!["hello world".to_string()]
401 assert_eq!(expected, result);
405 fn test_replace_region_with_start() {
406 let text = "\nabc\n123\n789\ndef\nghi";
407 let expected = FileChange {
409 new_lines: "\nhello world\ndef\nghi".to_string(),
411 let result = replace_region_in_text(text, r#"^\s*abc$"#, r#"^\s*def"#, true, || {
412 vec!["hello world".to_string()]
414 assert_eq!(expected, result);
418 fn test_replace_region_no_changes() {
419 let text = "123\n456\n789";
420 let expected = FileChange {
422 new_lines: "123\n456\n789".to_string(),
424 let result = replace_region_in_text(text, r#"^\s*123$"#, r#"^\s*456"#, false, Vec::new);
425 assert_eq!(expected, result);
429 fn test_usable_lints() {
431 Lint::new("should_assert_eq", "Deprecated", "abc", Some("Reason"), "module_name"),
432 Lint::new("should_assert_eq2", "Not Deprecated", "abc", None, "module_name"),
433 Lint::new("should_assert_eq2", "internal", "abc", None, "module_name"),
434 Lint::new("should_assert_eq2", "internal_style", "abc", None, "module_name"),
436 let expected = vec![Lint::new(
443 assert_eq!(expected, Lint::usable_lints(&lints));
447 fn test_by_lint_group() {
449 Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
450 Lint::new("should_assert_eq2", "group2", "abc", None, "module_name"),
451 Lint::new("incorrect_match", "group1", "abc", None, "module_name"),
453 let mut expected: HashMap<String, Vec<Lint>> = HashMap::new();
455 "group1".to_string(),
457 Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
458 Lint::new("incorrect_match", "group1", "abc", None, "module_name"),
462 "group2".to_string(),
463 vec![Lint::new("should_assert_eq2", "group2", "abc", None, "module_name")],
465 assert_eq!(expected, Lint::by_lint_group(lints.into_iter()));
469 fn test_gen_changelog_lint_list() {
471 Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
472 Lint::new("should_assert_eq2", "group2", "abc", None, "module_name"),
475 format!("[`should_assert_eq`]: {}#should_assert_eq", DOCS_LINK.to_string()),
476 format!("[`should_assert_eq2`]: {}#should_assert_eq2", DOCS_LINK.to_string()),
478 assert_eq!(expected, gen_changelog_lint_list(lints.iter()));
482 fn test_gen_deprecated() {
488 Some("has been superseded by should_assert_eq2"),
492 "another_deprecated",
495 Some("will be removed"),
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.iter()));
517 fn test_gen_deprecated_fail() {
518 let lints = vec![Lint::new("should_assert_eq2", "group2", "abc", None, "module_name")];
519 let _ = gen_deprecated(lints.iter());
523 fn test_gen_modules_list() {
525 Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
526 Lint::new("incorrect_stuff", "group3", "abc", None, "another_module"),
528 let expected = vec!["mod another_module;".to_string(), "mod module_name;".to_string()];
529 assert_eq!(expected, gen_modules_list(lints.iter()));
533 fn test_gen_lint_group_list() {
535 Lint::new("abc", "group1", "abc", None, "module_name"),
536 Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
537 Lint::new("internal", "internal_style", "abc", None, "module_name"),
540 " LintId::of(&module_name::ABC),".to_string(),
541 " LintId::of(&module_name::INTERNAL),".to_string(),
542 " LintId::of(&module_name::SHOULD_ASSERT_EQ),".to_string(),
544 assert_eq!(expected, gen_lint_group_list(lints.iter()));