]> git.lizzy.rs Git - rust.git/blob - src/tools/tidy/src/style.rs
Rollup merge of #106175 - compiler-errors:bad-import-sugg, r=oli-obk
[rust.git] / src / tools / tidy / src / style.rs
1 //! Tidy check to enforce various stylistic guidelines on the Rust codebase.
2 //!
3 //! Example checks are:
4 //!
5 //! * No lines over 100 characters (in non-Rust files).
6 //! * No files with over 3000 lines (in non-Rust files).
7 //! * No tabs.
8 //! * No trailing whitespace.
9 //! * No CR characters.
10 //! * No `TODO` or `XXX` directives.
11 //! * No unexplained ` ```ignore ` or ` ```rust,ignore ` doc tests.
12 //!
13 //! Note that some of these rules are excluded from Rust files because we enforce rustfmt. It is
14 //! preferable to be formatted rather than tidy-clean.
15 //!
16 //! A number of these checks can be opted-out of with various directives of the form:
17 //! `// ignore-tidy-CHECK-NAME`.
18 // ignore-tidy-dbg
19
20 use crate::walk::{filter_dirs, walk};
21 use regex::{Regex, RegexSet};
22 use std::path::Path;
23
24 /// Error code markdown is restricted to 80 columns because they can be
25 /// displayed on the console with --example.
26 const ERROR_CODE_COLS: usize = 80;
27 const COLS: usize = 100;
28 const GOML_COLS: usize = 120;
29
30 const LINES: usize = 3000;
31
32 const UNEXPLAINED_IGNORE_DOCTEST_INFO: &str = r#"unexplained "```ignore" doctest; try one:
33
34 * make the test actually pass, by adding necessary imports and declarations, or
35 * use "```text", if the code is not Rust code, or
36 * use "```compile_fail,Ennnn", if the code is expected to fail at compile time, or
37 * use "```should_panic", if the code is expected to fail at run time, or
38 * use "```no_run", if the code should type-check but not necessary linkable/runnable, or
39 * explain it like "```ignore (cannot-test-this-because-xxxx)", if the annotation cannot be avoided.
40
41 "#;
42
43 const LLVM_UNREACHABLE_INFO: &str = r"\
44 C++ code used llvm_unreachable, which triggers undefined behavior
45 when executed when assertions are disabled.
46 Use llvm::report_fatal_error for increased robustness.";
47
48 const ANNOTATIONS_TO_IGNORE: &[&str] = &[
49     "// @!has",
50     "// @has",
51     "// @matches",
52     "// CHECK",
53     "// EMIT_MIR",
54     "// compile-flags",
55     "// error-pattern",
56     "// gdb",
57     "// lldb",
58     "// cdb",
59     "// normalize-stderr-test",
60 ];
61
62 // Intentionally written in decimal rather than hex
63 const PROBLEMATIC_CONSTS: &[u32] = &[
64     184594741, 2880289470, 2881141438, 2965027518, 2976579765, 3203381950, 3405691582, 3405697037,
65     3735927486, 3735932941, 4027431614, 4276992702,
66 ];
67
68 const INTERNAL_COMPILER_DOCS_LINE: &str = "#### This error code is internal to the compiler and will not be emitted with normal Rust code.";
69
70 /// Parser states for `line_is_url`.
71 #[derive(Clone, Copy, PartialEq)]
72 #[allow(non_camel_case_types)]
73 enum LIUState {
74     EXP_COMMENT_START,
75     EXP_LINK_LABEL_OR_URL,
76     EXP_URL,
77     EXP_END,
78 }
79
80 /// Returns `true` if `line` appears to be a line comment containing a URL,
81 /// possibly with a Markdown link label in front, and nothing else.
82 /// The Markdown link label, if present, may not contain whitespace.
83 /// Lines of this form are allowed to be overlength, because Markdown
84 /// offers no way to split a line in the middle of a URL, and the lengths
85 /// of URLs to external references are beyond our control.
86 fn line_is_url(is_error_code: bool, columns: usize, line: &str) -> bool {
87     // more basic check for markdown, to avoid complexity in implementing two state machines
88     if is_error_code {
89         return line.starts_with('[') && line.contains("]:") && line.contains("http");
90     }
91
92     use self::LIUState::*;
93     let mut state: LIUState = EXP_COMMENT_START;
94     let is_url = |w: &str| w.starts_with("http://") || w.starts_with("https://");
95
96     for tok in line.split_whitespace() {
97         match (state, tok) {
98             (EXP_COMMENT_START, "//") | (EXP_COMMENT_START, "///") | (EXP_COMMENT_START, "//!") => {
99                 state = EXP_LINK_LABEL_OR_URL
100             }
101
102             (EXP_LINK_LABEL_OR_URL, w)
103                 if w.len() >= 4 && w.starts_with('[') && w.ends_with("]:") =>
104             {
105                 state = EXP_URL
106             }
107
108             (EXP_LINK_LABEL_OR_URL, w) if is_url(w) => state = EXP_END,
109
110             (EXP_URL, w) if is_url(w) || w.starts_with("../") => state = EXP_END,
111
112             (_, w) if w.len() > columns && is_url(w) => state = EXP_END,
113
114             (_, _) => {}
115         }
116     }
117
118     state == EXP_END
119 }
120
121 /// Returns `true` if `line` can be ignored. This is the case when it contains
122 /// an annotation that is explicitly ignored.
123 fn should_ignore(line: &str) -> bool {
124     // Matches test annotations like `//~ ERROR text`.
125     // This mirrors the regex in src/tools/compiletest/src/runtest.rs, please
126     // update both if either are changed.
127     let re = Regex::new("\\s*//(\\[.*\\])?~.*").unwrap();
128     re.is_match(line) || ANNOTATIONS_TO_IGNORE.iter().any(|a| line.contains(a))
129 }
130
131 /// Returns `true` if `line` is allowed to be longer than the normal limit.
132 fn long_line_is_ok(extension: &str, is_error_code: bool, max_columns: usize, line: &str) -> bool {
133     match extension {
134         // fluent files are allowed to be any length
135         "ftl" => true,
136         // non-error code markdown is allowed to be any length
137         "md" if !is_error_code => true,
138         // HACK(Ezrashaw): there is no way to split a markdown header over multiple lines
139         "md" if line == INTERNAL_COMPILER_DOCS_LINE => true,
140         _ => line_is_url(is_error_code, max_columns, line) || should_ignore(line),
141     }
142 }
143
144 enum Directive {
145     /// By default, tidy always warns against style issues.
146     Deny,
147
148     /// `Ignore(false)` means that an `ignore-tidy-*` directive
149     /// has been provided, but is unnecessary. `Ignore(true)`
150     /// means that it is necessary (i.e. a warning would be
151     /// produced if `ignore-tidy-*` was not present).
152     Ignore(bool),
153 }
154
155 fn contains_ignore_directive(can_contain: bool, contents: &str, check: &str) -> Directive {
156     if !can_contain {
157         return Directive::Deny;
158     }
159     // Update `can_contain` when changing this
160     if contents.contains(&format!("// ignore-tidy-{check}"))
161         || contents.contains(&format!("# ignore-tidy-{check}"))
162         || contents.contains(&format!("/* ignore-tidy-{check} */"))
163     {
164         Directive::Ignore(false)
165     } else {
166         Directive::Deny
167     }
168 }
169
170 macro_rules! suppressible_tidy_err {
171     ($err:ident, $skip:ident, $msg:expr) => {
172         if let Directive::Deny = $skip {
173             $err($msg);
174         } else {
175             $skip = Directive::Ignore(true);
176         }
177     };
178 }
179
180 pub fn is_in(full_path: &Path, parent_folder_to_find: &str, folder_to_find: &str) -> bool {
181     if let Some(parent) = full_path.parent() {
182         if parent.file_name().map_or_else(
183             || false,
184             |f| {
185                 f.to_string_lossy() == folder_to_find
186                     && parent
187                         .parent()
188                         .and_then(|f| f.file_name())
189                         .map_or_else(|| false, |f| f == parent_folder_to_find)
190             },
191         ) {
192             true
193         } else {
194             is_in(parent, parent_folder_to_find, folder_to_find)
195         }
196     } else {
197         false
198     }
199 }
200
201 fn skip_markdown_path(path: &Path) -> bool {
202     // These aren't ready for tidy.
203     const SKIP_MD: &[&str] = &[
204         "src/doc/edition-guide",
205         "src/doc/embedded-book",
206         "src/doc/nomicon",
207         "src/doc/reference",
208         "src/doc/rust-by-example",
209         "src/doc/rustc-dev-guide",
210     ];
211     SKIP_MD.iter().any(|p| path.ends_with(p))
212 }
213
214 fn is_unexplained_ignore(extension: &str, line: &str) -> bool {
215     if !line.ends_with("```ignore") && !line.ends_with("```rust,ignore") {
216         return false;
217     }
218     if extension == "md" && line.trim().starts_with("//") {
219         // Markdown examples may include doc comments with ignore inside a
220         // code block.
221         return false;
222     }
223     true
224 }
225
226 pub fn check(path: &Path, bad: &mut bool) {
227     fn skip(path: &Path) -> bool {
228         filter_dirs(path) || skip_markdown_path(path)
229     }
230     let problematic_consts_strings: Vec<String> = (PROBLEMATIC_CONSTS.iter().map(u32::to_string))
231         .chain(PROBLEMATIC_CONSTS.iter().map(|v| format!("{:x}", v)))
232         .chain(PROBLEMATIC_CONSTS.iter().map(|v| format!("{:X}", v)))
233         .collect();
234     let problematic_regex = RegexSet::new(problematic_consts_strings.as_slice()).unwrap();
235     walk(path, &mut skip, &mut |entry, contents| {
236         let file = entry.path();
237         let filename = file.file_name().unwrap().to_string_lossy();
238         let extensions =
239             [".rs", ".py", ".js", ".sh", ".c", ".cpp", ".h", ".md", ".css", ".ftl", ".goml"];
240         if extensions.iter().all(|e| !filename.ends_with(e)) || filename.starts_with(".#") {
241             return;
242         }
243
244         let is_style_file = filename.ends_with(".css");
245         let under_rustfmt = filename.ends_with(".rs") &&
246             // This list should ideally be sourced from rustfmt.toml but we don't want to add a toml
247             // parser to tidy.
248             !file.ancestors().any(|a| {
249                 a.ends_with("src/test") ||
250                     a.ends_with("src/doc/book")
251             });
252
253         if is_style_file && !is_in(file, "src", "librustdoc") {
254             // We only check CSS files in rustdoc.
255             return;
256         }
257
258         if contents.is_empty() {
259             tidy_error!(bad, "{}: empty file", file.display());
260         }
261
262         let extension = file.extension().unwrap().to_string_lossy();
263         let is_error_code = extension == "md" && is_in(file, "src", "error_codes");
264         let is_goml_code = extension == "goml";
265
266         let max_columns = if is_error_code {
267             ERROR_CODE_COLS
268         } else if is_goml_code {
269             GOML_COLS
270         } else {
271             COLS
272         };
273
274         let can_contain = contents.contains("// ignore-tidy-")
275             || contents.contains("# ignore-tidy-")
276             || contents.contains("/* ignore-tidy-");
277         // Enable testing ICE's that require specific (untidy)
278         // file formats easily eg. `issue-1234-ignore-tidy.rs`
279         if filename.contains("ignore-tidy") {
280             return;
281         }
282         let mut skip_cr = contains_ignore_directive(can_contain, &contents, "cr");
283         let mut skip_undocumented_unsafe =
284             contains_ignore_directive(can_contain, &contents, "undocumented-unsafe");
285         let mut skip_tab = contains_ignore_directive(can_contain, &contents, "tab");
286         let mut skip_line_length = contains_ignore_directive(can_contain, &contents, "linelength");
287         let mut skip_file_length = contains_ignore_directive(can_contain, &contents, "filelength");
288         let mut skip_end_whitespace =
289             contains_ignore_directive(can_contain, &contents, "end-whitespace");
290         let mut skip_trailing_newlines =
291             contains_ignore_directive(can_contain, &contents, "trailing-newlines");
292         let mut skip_leading_newlines =
293             contains_ignore_directive(can_contain, &contents, "leading-newlines");
294         let mut skip_copyright = contains_ignore_directive(can_contain, &contents, "copyright");
295         let mut skip_dbg = contains_ignore_directive(can_contain, &contents, "dbg");
296         let mut leading_new_lines = false;
297         let mut trailing_new_lines = 0;
298         let mut lines = 0;
299         let mut last_safety_comment = false;
300         let is_test = file.components().any(|c| c.as_os_str() == "tests");
301         // scanning the whole file for multiple needles at once is more efficient than
302         // executing lines times needles separate searches.
303         let any_problematic_line = problematic_regex.is_match(contents);
304         for (i, line) in contents.split('\n').enumerate() {
305             if line.is_empty() {
306                 if i == 0 {
307                     leading_new_lines = true;
308                 }
309                 trailing_new_lines += 1;
310                 continue;
311             } else {
312                 trailing_new_lines = 0;
313             }
314
315             let trimmed = line.trim();
316
317             if !trimmed.starts_with("//") {
318                 lines += 1;
319             }
320
321             let mut err = |msg: &str| {
322                 tidy_error!(bad, "{}:{}: {}", file.display(), i + 1, msg);
323             };
324
325             if trimmed.contains("dbg!")
326                 && !trimmed.starts_with("//")
327                 && !file
328                     .ancestors()
329                     .any(|a| a.ends_with("src/test") || a.ends_with("library/alloc/tests"))
330                 && filename != "tests.rs"
331             {
332                 suppressible_tidy_err!(
333                     err,
334                     skip_dbg,
335                     "`dbg!` macro is intended as a debugging tool. It should not be in version control."
336                 )
337             }
338
339             if !under_rustfmt
340                 && line.chars().count() > max_columns
341                 && !long_line_is_ok(&extension, is_error_code, max_columns, line)
342             {
343                 suppressible_tidy_err!(
344                     err,
345                     skip_line_length,
346                     &format!("line longer than {max_columns} chars")
347                 );
348             }
349             if !is_style_file && line.contains('\t') {
350                 suppressible_tidy_err!(err, skip_tab, "tab character");
351             }
352             if line.ends_with(' ') || line.ends_with('\t') {
353                 suppressible_tidy_err!(err, skip_end_whitespace, "trailing whitespace");
354             }
355             if is_style_file && line.starts_with(' ') {
356                 err("CSS files use tabs for indent");
357             }
358             if line.contains('\r') {
359                 suppressible_tidy_err!(err, skip_cr, "CR character");
360             }
361             if filename != "style.rs" {
362                 if trimmed.contains("TODO") {
363                     err("TODO is deprecated; use FIXME")
364                 }
365                 if trimmed.contains("//") && trimmed.contains(" XXX") {
366                     err("XXX is deprecated; use FIXME")
367                 }
368                 if any_problematic_line {
369                     for s in problematic_consts_strings.iter() {
370                         if trimmed.contains(s) {
371                             err("Don't use magic numbers that spell things (consider 0x12345678)");
372                         }
373                     }
374                 }
375             }
376             // for now we just check libcore
377             if trimmed.contains("unsafe {") && !trimmed.starts_with("//") && !last_safety_comment {
378                 if file.components().any(|c| c.as_os_str() == "core") && !is_test {
379                     suppressible_tidy_err!(err, skip_undocumented_unsafe, "undocumented unsafe");
380                 }
381             }
382             if trimmed.contains("// SAFETY:") {
383                 last_safety_comment = true;
384             } else if trimmed.starts_with("//") || trimmed.is_empty() {
385                 // keep previous value
386             } else {
387                 last_safety_comment = false;
388             }
389             if (line.starts_with("// Copyright")
390                 || line.starts_with("# Copyright")
391                 || line.starts_with("Copyright"))
392                 && (trimmed.contains("Rust Developers")
393                     || trimmed.contains("Rust Project Developers"))
394             {
395                 suppressible_tidy_err!(
396                     err,
397                     skip_copyright,
398                     "copyright notices attributed to the Rust Project Developers are deprecated"
399                 );
400             }
401             if is_unexplained_ignore(&extension, line) {
402                 err(UNEXPLAINED_IGNORE_DOCTEST_INFO);
403             }
404             if filename.ends_with(".cpp") && line.contains("llvm_unreachable") {
405                 err(LLVM_UNREACHABLE_INFO);
406             }
407         }
408         if leading_new_lines {
409             let mut err = |_| {
410                 tidy_error!(bad, "{}: leading newline", file.display());
411             };
412             suppressible_tidy_err!(err, skip_leading_newlines, "mising leading newline");
413         }
414         let mut err = |msg: &str| {
415             tidy_error!(bad, "{}: {}", file.display(), msg);
416         };
417         match trailing_new_lines {
418             0 => suppressible_tidy_err!(err, skip_trailing_newlines, "missing trailing newline"),
419             1 => {}
420             n => suppressible_tidy_err!(
421                 err,
422                 skip_trailing_newlines,
423                 &format!("too many trailing newlines ({n})")
424             ),
425         };
426         if lines > LINES {
427             let mut err = |_| {
428                 tidy_error!(
429                     bad,
430                     "{}: too many lines ({}) (add `// \
431                      ignore-tidy-filelength` to the file to suppress this error)",
432                     file.display(),
433                     lines
434                 );
435             };
436             suppressible_tidy_err!(err, skip_file_length, "");
437         }
438
439         if let Directive::Ignore(false) = skip_cr {
440             tidy_error!(bad, "{}: ignoring CR characters unnecessarily", file.display());
441         }
442         if let Directive::Ignore(false) = skip_tab {
443             tidy_error!(bad, "{}: ignoring tab characters unnecessarily", file.display());
444         }
445         if let Directive::Ignore(false) = skip_end_whitespace {
446             tidy_error!(bad, "{}: ignoring trailing whitespace unnecessarily", file.display());
447         }
448         if let Directive::Ignore(false) = skip_trailing_newlines {
449             tidy_error!(bad, "{}: ignoring trailing newlines unnecessarily", file.display());
450         }
451         if let Directive::Ignore(false) = skip_leading_newlines {
452             tidy_error!(bad, "{}: ignoring leading newlines unnecessarily", file.display());
453         }
454         if let Directive::Ignore(false) = skip_copyright {
455             tidy_error!(bad, "{}: ignoring copyright unnecessarily", file.display());
456         }
457         // We deliberately do not warn about these being unnecessary,
458         // that would just lead to annoying churn.
459         let _unused = skip_line_length;
460         let _unused = skip_file_length;
461     })
462 }