]> git.proxmox.com Git - rustc.git/blob - src/tools/tidy/src/style.rs
Update upstream source from tag 'upstream/1.34.2+dfsg1'
[rustc.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.
6 //! * No tabs.
7 //! * No trailing whitespace.
8 //! * No CR characters.
9 //! * No `TODO` or `XXX` directives.
10 //! * No unexplained ` ```ignore ` or ` ```rust,ignore ` doc tests.
11 //!
12 //! A number of these checks can be opted-out of with various directives like
13 //! `// ignore-tidy-linelength`.
14
15 use std::fs::File;
16 use std::io::prelude::*;
17 use std::path::Path;
18
19 const COLS: usize = 100;
20
21 const UNEXPLAINED_IGNORE_DOCTEST_INFO: &str = r#"unexplained "```ignore" doctest; try one:
22
23 * make the test actually pass, by adding necessary imports and declarations, or
24 * use "```text", if the code is not Rust code, or
25 * use "```compile_fail,Ennnn", if the code is expected to fail at compile time, or
26 * use "```should_panic", if the code is expected to fail at run time, or
27 * use "```no_run", if the code should type-check but not necessary linkable/runnable, or
28 * explain it like "```ignore (cannot-test-this-because-xxxx)", if the annotation cannot be avoided.
29
30 "#;
31
32 const LLVM_UNREACHABLE_INFO: &str = r"\
33 C++ code used llvm_unreachable, which triggers undefined behavior
34 when executed when assertions are disabled.
35 Use llvm::report_fatal_error for increased robustness.";
36
37 /// Parser states for `line_is_url`.
38 #[derive(PartialEq)]
39 #[allow(non_camel_case_types)]
40 enum LIUState {
41 EXP_COMMENT_START,
42 EXP_LINK_LABEL_OR_URL,
43 EXP_URL,
44 EXP_END,
45 }
46
47 /// Returns `true` if `line` appears to be a line comment containing an URL,
48 /// possibly with a Markdown link label in front, and nothing else.
49 /// The Markdown link label, if present, may not contain whitespace.
50 /// Lines of this form are allowed to be overlength, because Markdown
51 /// offers no way to split a line in the middle of a URL, and the lengths
52 /// of URLs to external references are beyond our control.
53 fn line_is_url(line: &str) -> bool {
54 use self::LIUState::*;
55 let mut state: LIUState = EXP_COMMENT_START;
56
57 for tok in line.split_whitespace() {
58 match (state, tok) {
59 (EXP_COMMENT_START, "//") => state = EXP_LINK_LABEL_OR_URL,
60 (EXP_COMMENT_START, "///") => state = EXP_LINK_LABEL_OR_URL,
61 (EXP_COMMENT_START, "//!") => state = EXP_LINK_LABEL_OR_URL,
62
63 (EXP_LINK_LABEL_OR_URL, w)
64 if w.len() >= 4 && w.starts_with('[') && w.ends_with("]:")
65 => state = EXP_URL,
66
67 (EXP_LINK_LABEL_OR_URL, w)
68 if w.starts_with("http://") || w.starts_with("https://")
69 => state = EXP_END,
70
71 (EXP_URL, w)
72 if w.starts_with("http://") || w.starts_with("https://") || w.starts_with("../")
73 => state = EXP_END,
74
75 (_, _) => return false,
76 }
77 }
78
79 state == EXP_END
80 }
81
82 /// Returns `true` if `line` is allowed to be longer than the normal limit.
83 /// Currently there is only one exception, for long URLs, but more
84 /// may be added in the future.
85 fn long_line_is_ok(line: &str) -> bool {
86 if line_is_url(line) {
87 return true;
88 }
89
90 false
91 }
92
93 pub fn check(path: &Path, bad: &mut bool) {
94 let mut contents = String::new();
95 super::walk(path, &mut super::filter_dirs, &mut |file| {
96 let filename = file.file_name().unwrap().to_string_lossy();
97 let extensions = [".rs", ".py", ".js", ".sh", ".c", ".cpp", ".h"];
98 if extensions.iter().all(|e| !filename.ends_with(e)) ||
99 filename.starts_with(".#") {
100 return
101 }
102
103 contents.truncate(0);
104 t!(t!(File::open(file), file).read_to_string(&mut contents));
105
106 if contents.is_empty() {
107 tidy_error!(bad, "{}: empty file", file.display());
108 }
109
110 let skip_cr = contents.contains("ignore-tidy-cr");
111 let skip_tab = contents.contains("ignore-tidy-tab");
112 let skip_length = contents.contains("ignore-tidy-linelength");
113 let skip_end_whitespace = contents.contains("ignore-tidy-end-whitespace");
114 let skip_copyright = contents.contains("ignore-tidy-copyright");
115 let mut trailing_new_lines = 0;
116 for (i, line) in contents.split('\n').enumerate() {
117 let mut err = |msg: &str| {
118 tidy_error!(bad, "{}:{}: {}", file.display(), i + 1, msg);
119 };
120 if !skip_length && line.chars().count() > COLS
121 && !long_line_is_ok(line) {
122 err(&format!("line longer than {} chars", COLS));
123 }
124 if !skip_tab && line.contains('\t') {
125 err("tab character");
126 }
127 if !skip_end_whitespace && (line.ends_with(' ') || line.ends_with('\t')) {
128 err("trailing whitespace");
129 }
130 if !skip_cr && line.contains('\r') {
131 err("CR character");
132 }
133 if filename != "style.rs" {
134 if line.contains("TODO") {
135 err("TODO is deprecated; use FIXME")
136 }
137 if line.contains("//") && line.contains(" XXX") {
138 err("XXX is deprecated; use FIXME")
139 }
140 }
141 if !skip_copyright && (line.starts_with("// Copyright") ||
142 line.starts_with("# Copyright") ||
143 line.starts_with("Copyright"))
144 && (line.contains("Rust Developers") ||
145 line.contains("Rust Project Developers")) {
146 err("copyright notices attributed to the Rust Project Developers are deprecated");
147 }
148 if line.ends_with("```ignore") || line.ends_with("```rust,ignore") {
149 err(UNEXPLAINED_IGNORE_DOCTEST_INFO);
150 }
151 if filename.ends_with(".cpp") && line.contains("llvm_unreachable") {
152 err(LLVM_UNREACHABLE_INFO);
153 }
154 if line.is_empty() {
155 trailing_new_lines += 1;
156 } else {
157 trailing_new_lines = 0;
158 }
159 }
160 match trailing_new_lines {
161 0 => tidy_error!(bad, "{}: missing trailing newline", file.display()),
162 1 | 2 => {}
163 n => tidy_error!(bad, "{}: too many trailing newlines ({})", file.display(), n),
164 };
165 })
166 }