1 use crate::clippy_project_root;
2 use indoc::{formatdoc, writedoc};
3 use std::fmt::Write as _;
4 use std::fs::{self, OpenOptions};
5 use std::io::prelude::*;
6 use std::io::{self, ErrorKind};
7 use std::path::{Path, PathBuf};
14 project_root: PathBuf,
18 fn context<C: AsRef<str>>(self, text: C) -> Self;
21 impl<T> Context for io::Result<T> {
22 fn context<C: AsRef<str>>(self, text: C) -> Self {
26 let message = format!("{}: {e}", text.as_ref());
27 Err(io::Error::new(ErrorKind::Other, message))
33 /// Creates the files required to implement and test a new lint and runs `update_lints`.
37 /// This function errors out if the files couldn't be created or written to.
39 pass: Option<&String>,
40 lint_name: Option<&String>,
41 category: Option<&str>,
45 if category == Some("cargo") && ty.is_none() {
46 // `cargo` is a special category, these lints should always be in `clippy_lints/src/cargo`
51 pass: pass.map_or("", String::as_str),
52 name: lint_name.expect("`name` argument is validated by clap"),
53 category: category.expect("`category` argument is validated by clap"),
55 project_root: clippy_project_root(),
58 create_lint(&lint, msrv).context("Unable to create lint implementation")?;
59 create_test(&lint).context("Unable to create a test for the new lint")?;
61 if lint.ty.is_none() {
62 add_lint(&lint, msrv).context("Unable to add lint to clippy_lints/src/lib.rs")?;
68 fn create_lint(lint: &LintData<'_>, enable_msrv: bool) -> io::Result<()> {
69 if let Some(ty) = lint.ty {
70 create_lint_for_ty(lint, enable_msrv, ty)
72 let lint_contents = get_lint_file_contents(lint, enable_msrv);
73 let lint_path = format!("clippy_lints/src/{}.rs", lint.name);
74 write_file(lint.project_root.join(&lint_path), lint_contents.as_bytes())?;
75 println!("Generated lint file: `{lint_path}`");
81 fn create_test(lint: &LintData<'_>) -> io::Result<()> {
82 fn create_project_layout<P: Into<PathBuf>>(lint_name: &str, location: P, case: &str, hint: &str) -> io::Result<()> {
83 let mut path = location.into().join(case);
84 fs::create_dir(&path)?;
85 write_file(path.join("Cargo.toml"), get_manifest_contents(lint_name, hint))?;
88 fs::create_dir(&path)?;
89 let header = format!("// compile-flags: --crate-name={lint_name}");
90 write_file(path.join("main.rs"), get_test_file_contents(lint_name, Some(&header)))?;
95 if lint.category == "cargo" {
96 let relative_test_dir = format!("tests/ui-cargo/{}", lint.name);
97 let test_dir = lint.project_root.join(&relative_test_dir);
98 fs::create_dir(&test_dir)?;
100 create_project_layout(lint.name, &test_dir, "fail", "Content that triggers the lint goes here")?;
101 create_project_layout(lint.name, &test_dir, "pass", "This file should not trigger the lint")?;
103 println!("Generated test directories: `{relative_test_dir}/pass`, `{relative_test_dir}/fail`");
105 let test_path = format!("tests/ui/{}.rs", lint.name);
106 let test_contents = get_test_file_contents(lint.name, None);
107 write_file(lint.project_root.join(&test_path), test_contents)?;
109 println!("Generated test file: `{test_path}`");
115 fn add_lint(lint: &LintData<'_>, enable_msrv: bool) -> io::Result<()> {
116 let path = "clippy_lints/src/lib.rs";
117 let mut lib_rs = fs::read_to_string(path).context("reading")?;
119 let comment_start = lib_rs.find("// add lints here,").expect("Couldn't find comment");
121 let new_lint = if enable_msrv {
123 "store.register_{lint_pass}_pass(move |{ctor_arg}| Box::new({module_name}::{camel_name}::new(msrv)));\n ",
124 lint_pass = lint.pass,
125 ctor_arg = if lint.pass == "late" { "_" } else { "" },
126 module_name = lint.name,
127 camel_name = to_camel_case(lint.name),
131 "store.register_{lint_pass}_pass(|{ctor_arg}| Box::new({module_name}::{camel_name}));\n ",
132 lint_pass = lint.pass,
133 ctor_arg = if lint.pass == "late" { "_" } else { "" },
134 module_name = lint.name,
135 camel_name = to_camel_case(lint.name),
139 lib_rs.insert_str(comment_start, &new_lint);
141 fs::write(path, lib_rs).context("writing")
144 fn write_file<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> io::Result<()> {
145 fn inner(path: &Path, contents: &[u8]) -> io::Result<()> {
153 inner(path.as_ref(), contents.as_ref()).context(format!("writing to file: {}", path.as_ref().display()))
156 fn to_camel_case(name: &str) -> String {
162 [&s[0..1].to_uppercase(), &s[1..]].concat()
168 pub(crate) fn get_stabilization_version() -> String {
169 fn parse_manifest(contents: &str) -> Option<String> {
170 let version = contents
172 .filter_map(|l| l.split_once('='))
173 .find_map(|(k, v)| (k.trim() == "version").then(|| v.trim()))?;
174 let Some(("0", version)) = version.get(1..version.len() - 1)?.split_once('.') else {
177 let (minor, patch) = version.split_once('.')?;
180 minor.parse::<u32>().ok()?,
181 patch.parse::<u32>().ok()?
184 let contents = fs::read_to_string("Cargo.toml").expect("Unable to read `Cargo.toml`");
185 parse_manifest(&contents).expect("Unable to find package version in `Cargo.toml`")
188 fn get_test_file_contents(lint_name: &str, header_commands: Option<&str>) -> String {
189 let mut contents = formatdoc!(
192 #![warn(clippy::{lint_name})]
195 // test code goes here
200 if let Some(header) = header_commands {
201 contents = format!("{header}\n{contents}");
207 fn get_manifest_contents(lint_name: &str, hint: &str) -> String {
222 fn get_lint_file_contents(lint: &LintData<'_>, enable_msrv: bool) -> String {
223 let mut result = String::new();
225 let (pass_type, pass_lifetimes, pass_import, context_import) = match lint.pass {
226 "early" => ("EarlyLintPass", "", "use rustc_ast::ast::*;", "EarlyContext"),
227 "late" => ("LateLintPass", "<'_>", "use rustc_hir::*;", "LateContext"),
229 unreachable!("`pass_type` should only ever be `early` or `late`!");
233 let lint_name = lint.name;
234 let category = lint.category;
235 let name_camel = to_camel_case(lint.name);
236 let name_upper = lint_name.to_uppercase();
238 result.push_str(&if enable_msrv {
241 use clippy_utils::msrvs;
243 use rustc_lint::{{{context_import}, {pass_type}, LintContext}};
244 use rustc_semver::RustcVersion;
245 use rustc_session::{{declare_tool_lint, impl_lint_pass}};
253 use rustc_lint::{{{context_import}, {pass_type}}};
254 use rustc_session::{{declare_lint_pass, declare_tool_lint}};
260 let _ = write!(result, "{}", get_lint_declaration(&name_upper, category));
262 result.push_str(&if enable_msrv {
265 pub struct {name_camel} {{
266 msrv: Option<RustcVersion>,
271 pub fn new(msrv: Option<RustcVersion>) -> Self {{
276 impl_lint_pass!({name_camel} => [{name_upper}]);
278 impl {pass_type}{pass_lifetimes} for {name_camel} {{
279 extract_msrv_attr!({context_import});
282 // TODO: Add MSRV level to `clippy_utils/src/msrvs.rs` if needed.
283 // TODO: Add MSRV test to `tests/ui/min_rust_version_attr.rs`.
284 // TODO: Update msrv config comment in `clippy_lints/src/utils/conf.rs`
290 declare_lint_pass!({name_camel} => [{name_upper}]);
292 impl {pass_type}{pass_lifetimes} for {name_camel} {{}}
300 fn get_lint_declaration(name_upper: &str, category: &str) -> String {
303 declare_clippy_lint! {{
306 /// ### Why is this bad?
310 /// // example code where clippy issues a warning
314 /// // example code which does not raise clippy warning
316 #[clippy::version = "{}"]
319 "default lint description"
322 get_stabilization_version(),
326 fn create_lint_for_ty(lint: &LintData<'_>, enable_msrv: bool, ty: &str) -> io::Result<()> {
328 "cargo" => assert_eq!(
329 lint.category, "cargo",
330 "Lints of type `cargo` must have the `cargo` category"
332 _ if lint.category == "cargo" => panic!("Lints of category `cargo` must have the `cargo` type"),
336 let ty_dir = lint.project_root.join(format!("clippy_lints/src/{ty}"));
338 ty_dir.exists() && ty_dir.is_dir(),
339 "Directory `{}` does not exist!",
343 let lint_file_path = ty_dir.join(format!("{}.rs", lint.name));
345 !lint_file_path.exists(),
346 "File `{}` already exists",
347 lint_file_path.display()
350 let mod_file_path = ty_dir.join("mod.rs");
351 let context_import = setup_mod_file(&mod_file_path, lint)?;
353 let name_upper = lint.name.to_uppercase();
354 let mut lint_file_contents = String::new();
360 use clippy_utils::{{meets_msrv, msrvs}};
361 use rustc_lint::{{{context_import}, LintContext}};
362 use rustc_semver::RustcVersion;
364 use super::{name_upper};
366 // TODO: Adjust the parameters as necessary
367 pub(super) fn check(cx: &{context_import}, msrv: Option<RustcVersion>) {{
368 if !meets_msrv(msrv, todo!("Add a new entry in `clippy_utils/src/msrvs`")) {{
374 context_import = context_import,
375 name_upper = name_upper,
381 use rustc_lint::{{{context_import}, LintContext}};
383 use super::{name_upper};
385 // TODO: Adjust the parameters as necessary
386 pub(super) fn check(cx: &{context_import}) {{
390 context_import = context_import,
391 name_upper = name_upper,
395 write_file(lint_file_path.as_path(), lint_file_contents)?;
396 println!("Generated lint file: `clippy_lints/src/{ty}/{}.rs`", lint.name);
398 "Be sure to add a call to `{}::check` in `clippy_lints/src/{ty}/mod.rs`!",
405 #[allow(clippy::too_many_lines)]
406 fn setup_mod_file(path: &Path, lint: &LintData<'_>) -> io::Result<&'static str> {
407 use super::update_lints::{match_tokens, LintDeclSearchResult};
408 use rustc_lexer::TokenKind;
410 let lint_name_upper = lint.name.to_uppercase();
412 let mut file_contents = fs::read_to_string(path)?;
414 !file_contents.contains(&lint_name_upper),
415 "Lint `{}` already defined in `{}`",
420 let mut offset = 0usize;
421 let mut last_decl_curly_offset = None;
422 let mut lint_context = None;
424 let mut iter = rustc_lexer::tokenize(&file_contents).map(|t| {
425 let range = offset..offset + t.len as usize;
428 LintDeclSearchResult {
430 content: &file_contents[range.clone()],
435 // Find both the last lint declaration (declare_clippy_lint!) and the lint pass impl
436 while let Some(LintDeclSearchResult { content, .. }) = iter.find(|result| result.token_kind == TokenKind::Ident) {
439 .filter(|t| !matches!(t.token_kind, TokenKind::Whitespace | TokenKind::LineComment { .. }));
442 "declare_clippy_lint" => {
444 match_tokens!(iter, Bang OpenBrace);
445 if let Some(LintDeclSearchResult { range, .. }) =
446 iter.find(|result| result.token_kind == TokenKind::CloseBrace)
448 last_decl_curly_offset = Some(range.end);
452 let mut token = iter.next();
455 Some(LintDeclSearchResult {
456 token_kind: TokenKind::Lt,
459 match_tokens!(iter, Lifetime { .. } Gt);
466 if let Some(LintDeclSearchResult {
467 token_kind: TokenKind::Ident,
472 // Get the appropriate lint context struct
473 lint_context = match content {
474 "LateLintPass" => Some("LateContext"),
475 "EarlyLintPass" => Some("EarlyContext"),
486 let last_decl_curly_offset =
487 last_decl_curly_offset.unwrap_or_else(|| panic!("No lint declarations found in `{}`", path.display()));
489 lint_context.unwrap_or_else(|| panic!("No lint pass implementation found in `{}`", path.display()));
491 // Add the lint declaration to `mod.rs`
492 file_contents.replace_range(
493 // Remove the trailing newline, which should always be present
494 last_decl_curly_offset..=last_decl_curly_offset,
495 &format!("\n\n{}", get_lint_declaration(&lint_name_upper, lint.category)),
498 // Add the lint to `impl_lint_pass`/`declare_lint_pass`
499 let impl_lint_pass_start = file_contents.find("impl_lint_pass!").unwrap_or_else(|| {
501 .find("declare_lint_pass!")
502 .unwrap_or_else(|| panic!("failed to find `impl_lint_pass`/`declare_lint_pass`"))
505 let mut arr_start = file_contents[impl_lint_pass_start..].find('[').unwrap_or_else(|| {
506 panic!("malformed `impl_lint_pass`/`declare_lint_pass`");
509 arr_start += impl_lint_pass_start;
511 let mut arr_end = file_contents[arr_start..]
513 .expect("failed to find `impl_lint_pass` terminator");
515 arr_end += arr_start;
517 let mut arr_content = file_contents[arr_start + 1..arr_end].to_string();
518 arr_content.retain(|c| !c.is_whitespace());
520 let mut new_arr_content = String::new();
521 for ident in arr_content
523 .chain(std::iter::once(&*lint_name_upper))
524 .filter(|s| !s.is_empty())
526 let _ = write!(new_arr_content, "\n {ident},");
528 new_arr_content.push('\n');
530 file_contents.replace_range(arr_start + 1..arr_end, &new_arr_content);
532 // Just add the mod declaration at the top, it'll be fixed by rustfmt
533 file_contents.insert_str(0, &format!("mod {};\n", &lint.name));
535 let mut file = OpenOptions::new()
539 .context(format!("trying to open: `{}`", path.display()))?;
540 file.write_all(file_contents.as_bytes())
541 .context(format!("writing to file: `{}`", path.display()))?;
547 fn test_camel_case() {
549 let s2 = to_camel_case(s);
550 assert_eq!(s2, "ALint");
552 let name = "a_really_long_new_lint";
553 let name2 = to_camel_case(name);
554 assert_eq!(name2, "AReallyLongNewLint");
556 let name3 = "lint__name";
557 let name4 = to_camel_case(name3);
558 assert_eq!(name4, "LintName");