]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_dev/src/new_lint.rs
Auto merge of #90580 - cjgillot:no-ee-upvar, r=Aaron1011
[rust.git] / src / tools / clippy / clippy_dev / src / new_lint.rs
1 use crate::clippy_project_root;
2 use indoc::indoc;
3 use std::fs::{self, OpenOptions};
4 use std::io::prelude::*;
5 use std::io::{self, ErrorKind};
6 use std::path::{Path, PathBuf};
7
8 struct LintData<'a> {
9     pass: &'a str,
10     name: &'a str,
11     category: &'a str,
12     project_root: PathBuf,
13 }
14
15 trait Context {
16     fn context<C: AsRef<str>>(self, text: C) -> Self;
17 }
18
19 impl<T> Context for io::Result<T> {
20     fn context<C: AsRef<str>>(self, text: C) -> Self {
21         match self {
22             Ok(t) => Ok(t),
23             Err(e) => {
24                 let message = format!("{}: {}", text.as_ref(), e);
25                 Err(io::Error::new(ErrorKind::Other, message))
26             },
27         }
28     }
29 }
30
31 /// Creates the files required to implement and test a new lint and runs `update_lints`.
32 ///
33 /// # Errors
34 ///
35 /// This function errors out if the files couldn't be created or written to.
36 pub fn create(pass: Option<&str>, lint_name: Option<&str>, category: Option<&str>, msrv: bool) -> io::Result<()> {
37     let lint = LintData {
38         pass: pass.expect("`pass` argument is validated by clap"),
39         name: lint_name.expect("`name` argument is validated by clap"),
40         category: category.expect("`category` argument is validated by clap"),
41         project_root: clippy_project_root(),
42     };
43
44     create_lint(&lint, msrv).context("Unable to create lint implementation")?;
45     create_test(&lint).context("Unable to create a test for the new lint")?;
46     add_lint(&lint, msrv).context("Unable to add lint to clippy_lints/src/lib.rs")
47 }
48
49 fn create_lint(lint: &LintData<'_>, enable_msrv: bool) -> io::Result<()> {
50     let lint_contents = get_lint_file_contents(lint, enable_msrv);
51
52     let lint_path = format!("clippy_lints/src/{}.rs", lint.name);
53     write_file(lint.project_root.join(&lint_path), lint_contents.as_bytes())
54 }
55
56 fn create_test(lint: &LintData<'_>) -> io::Result<()> {
57     fn create_project_layout<P: Into<PathBuf>>(lint_name: &str, location: P, case: &str, hint: &str) -> io::Result<()> {
58         let mut path = location.into().join(case);
59         fs::create_dir(&path)?;
60         write_file(path.join("Cargo.toml"), get_manifest_contents(lint_name, hint))?;
61
62         path.push("src");
63         fs::create_dir(&path)?;
64         let header = format!("// compile-flags: --crate-name={}", lint_name);
65         write_file(path.join("main.rs"), get_test_file_contents(lint_name, Some(&header)))?;
66
67         Ok(())
68     }
69
70     if lint.category == "cargo" {
71         let relative_test_dir = format!("tests/ui-cargo/{}", lint.name);
72         let test_dir = lint.project_root.join(relative_test_dir);
73         fs::create_dir(&test_dir)?;
74
75         create_project_layout(lint.name, &test_dir, "fail", "Content that triggers the lint goes here")?;
76         create_project_layout(lint.name, &test_dir, "pass", "This file should not trigger the lint")
77     } else {
78         let test_path = format!("tests/ui/{}.rs", lint.name);
79         let test_contents = get_test_file_contents(lint.name, None);
80         write_file(lint.project_root.join(test_path), test_contents)
81     }
82 }
83
84 fn add_lint(lint: &LintData<'_>, enable_msrv: bool) -> io::Result<()> {
85     let path = "clippy_lints/src/lib.rs";
86     let mut lib_rs = fs::read_to_string(path).context("reading")?;
87
88     let comment_start = lib_rs.find("// add lints here,").expect("Couldn't find comment");
89
90     let new_lint = if enable_msrv {
91         format!(
92             "store.register_{lint_pass}_pass(move || Box::new({module_name}::{camel_name}::new(msrv)));\n    ",
93             lint_pass = lint.pass,
94             module_name = lint.name,
95             camel_name = to_camel_case(lint.name),
96         )
97     } else {
98         format!(
99             "store.register_{lint_pass}_pass(|| Box::new({module_name}::{camel_name}));\n    ",
100             lint_pass = lint.pass,
101             module_name = lint.name,
102             camel_name = to_camel_case(lint.name),
103         )
104     };
105
106     lib_rs.insert_str(comment_start, &new_lint);
107
108     fs::write(path, lib_rs).context("writing")
109 }
110
111 fn write_file<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> io::Result<()> {
112     fn inner(path: &Path, contents: &[u8]) -> io::Result<()> {
113         OpenOptions::new()
114             .write(true)
115             .create_new(true)
116             .open(path)?
117             .write_all(contents)
118     }
119
120     inner(path.as_ref(), contents.as_ref()).context(format!("writing to file: {}", path.as_ref().display()))
121 }
122
123 fn to_camel_case(name: &str) -> String {
124     name.split('_')
125         .map(|s| {
126             if s.is_empty() {
127                 String::from("")
128             } else {
129                 [&s[0..1].to_uppercase(), &s[1..]].concat()
130             }
131         })
132         .collect()
133 }
134
135 fn get_test_file_contents(lint_name: &str, header_commands: Option<&str>) -> String {
136     let mut contents = format!(
137         indoc! {"
138             #![warn(clippy::{})]
139
140             fn main() {{
141                 // test code goes here
142             }}
143         "},
144         lint_name
145     );
146
147     if let Some(header) = header_commands {
148         contents = format!("{}\n{}", header, contents);
149     }
150
151     contents
152 }
153
154 fn get_manifest_contents(lint_name: &str, hint: &str) -> String {
155     format!(
156         indoc! {r#"
157             # {}
158
159             [package]
160             name = "{}"
161             version = "0.1.0"
162             publish = false
163
164             [workspace]
165         "#},
166         hint, lint_name
167     )
168 }
169
170 fn get_lint_file_contents(lint: &LintData<'_>, enable_msrv: bool) -> String {
171     let mut result = String::new();
172
173     let (pass_type, pass_lifetimes, pass_import, context_import) = match lint.pass {
174         "early" => ("EarlyLintPass", "", "use rustc_ast::ast::*;", "EarlyContext"),
175         "late" => ("LateLintPass", "<'_>", "use rustc_hir::*;", "LateContext"),
176         _ => {
177             unreachable!("`pass_type` should only ever be `early` or `late`!");
178         },
179     };
180
181     let lint_name = lint.name;
182     let category = lint.category;
183     let name_camel = to_camel_case(lint.name);
184     let name_upper = lint_name.to_uppercase();
185
186     result.push_str(&if enable_msrv {
187         format!(
188             indoc! {"
189                 use clippy_utils::msrvs;
190                 {pass_import}
191                 use rustc_lint::{{{context_import}, {pass_type}, LintContext}};
192                 use rustc_semver::RustcVersion;
193                 use rustc_session::{{declare_tool_lint, impl_lint_pass}};
194
195             "},
196             pass_type = pass_type,
197             pass_import = pass_import,
198             context_import = context_import,
199         )
200     } else {
201         format!(
202             indoc! {"
203                 {pass_import}
204                 use rustc_lint::{{{context_import}, {pass_type}}};
205                 use rustc_session::{{declare_lint_pass, declare_tool_lint}};
206
207             "},
208             pass_import = pass_import,
209             pass_type = pass_type,
210             context_import = context_import
211         )
212     });
213
214     result.push_str(&format!(
215         indoc! {"
216             declare_clippy_lint! {{
217                 /// ### What it does
218                 ///
219                 /// ### Why is this bad?
220                 ///
221                 /// ### Example
222                 /// ```rust
223                 /// // example code where clippy issues a warning
224                 /// ```
225                 /// Use instead:
226                 /// ```rust
227                 /// // example code which does not raise clippy warning
228                 /// ```
229                 pub {name_upper},
230                 {category},
231                 \"default lint description\"
232             }}
233         "},
234         name_upper = name_upper,
235         category = category,
236     ));
237
238     result.push_str(&if enable_msrv {
239         format!(
240             indoc! {"
241                 pub struct {name_camel} {{
242                     msrv: Option<RustcVersion>,
243                 }}
244
245                 impl {name_camel} {{
246                     #[must_use]
247                     pub fn new(msrv: Option<RustcVersion>) -> Self {{
248                         Self {{ msrv }}
249                     }}
250                 }}
251
252                 impl_lint_pass!({name_camel} => [{name_upper}]);
253
254                 impl {pass_type}{pass_lifetimes} for {name_camel} {{
255                     extract_msrv_attr!({context_import});
256                 }}
257
258                 // TODO: Add MSRV level to `clippy_utils/src/msrvs.rs` if needed.
259                 // TODO: Add MSRV test to `tests/ui/min_rust_version_attr.rs`.
260                 // TODO: Update msrv config comment in `clippy_lints/src/utils/conf.rs`
261             "},
262             pass_type = pass_type,
263             pass_lifetimes = pass_lifetimes,
264             name_upper = name_upper,
265             name_camel = name_camel,
266             context_import = context_import,
267         )
268     } else {
269         format!(
270             indoc! {"
271                 declare_lint_pass!({name_camel} => [{name_upper}]);
272
273                 impl {pass_type}{pass_lifetimes} for {name_camel} {{}}
274             "},
275             pass_type = pass_type,
276             pass_lifetimes = pass_lifetimes,
277             name_upper = name_upper,
278             name_camel = name_camel,
279         )
280     });
281
282     result
283 }
284
285 #[test]
286 fn test_camel_case() {
287     let s = "a_lint";
288     let s2 = to_camel_case(s);
289     assert_eq!(s2, "ALint");
290
291     let name = "a_really_long_new_lint";
292     let name2 = to_camel_case(name);
293     assert_eq!(name2, "AReallyLongNewLint");
294
295     let name3 = "lint__name";
296     let name4 = to_camel_case(name3);
297     assert_eq!(name4, "LintName");
298 }