]> git.proxmox.com Git - rustc.git/blob - src/tools/tidy/src/style.rs
Merge branch 'debian/experimental' into debian/sid
[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 (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
19 use std::path::Path;
20
21 const ERROR_CODE_COLS: usize = 80;
22 const COLS: usize = 100;
23
24 const LINES: usize = 3000;
25
26 const UNEXPLAINED_IGNORE_DOCTEST_INFO: &str = r#"unexplained "```ignore" doctest; try one:
27
28 * make the test actually pass, by adding necessary imports and declarations, or
29 * use "```text", if the code is not Rust code, or
30 * use "```compile_fail,Ennnn", if the code is expected to fail at compile time, or
31 * use "```should_panic", if the code is expected to fail at run time, or
32 * use "```no_run", if the code should type-check but not necessary linkable/runnable, or
33 * explain it like "```ignore (cannot-test-this-because-xxxx)", if the annotation cannot be avoided.
34
35 "#;
36
37 const LLVM_UNREACHABLE_INFO: &str = r"\
38 C++ code used llvm_unreachable, which triggers undefined behavior
39 when executed when assertions are disabled.
40 Use llvm::report_fatal_error for increased robustness.";
41
42 /// Parser states for `line_is_url`.
43 #[derive(Clone, Copy, PartialEq)]
44 #[allow(non_camel_case_types)]
45 enum LIUState {
46 EXP_COMMENT_START,
47 EXP_LINK_LABEL_OR_URL,
48 EXP_URL,
49 EXP_END,
50 }
51
52 /// Returns `true` if `line` appears to be a line comment containing an URL,
53 /// possibly with a Markdown link label in front, and nothing else.
54 /// The Markdown link label, if present, may not contain whitespace.
55 /// Lines of this form are allowed to be overlength, because Markdown
56 /// offers no way to split a line in the middle of a URL, and the lengths
57 /// of URLs to external references are beyond our control.
58 fn line_is_url(columns: usize, line: &str) -> bool {
59 // more basic check for error_codes.rs, to avoid complexity in implementing two state machines
60 if columns == ERROR_CODE_COLS {
61 return line.starts_with('[') && line.contains("]:") && line.contains("http");
62 }
63
64 use self::LIUState::*;
65 let mut state: LIUState = EXP_COMMENT_START;
66 let is_url = |w: &str| w.starts_with("http://") || w.starts_with("https://");
67
68 for tok in line.split_whitespace() {
69 match (state, tok) {
70 (EXP_COMMENT_START, "//") | (EXP_COMMENT_START, "///") | (EXP_COMMENT_START, "//!") => {
71 state = EXP_LINK_LABEL_OR_URL
72 }
73
74 (EXP_LINK_LABEL_OR_URL, w)
75 if w.len() >= 4 && w.starts_with('[') && w.ends_with("]:") =>
76 {
77 state = EXP_URL
78 }
79
80 (EXP_LINK_LABEL_OR_URL, w) if is_url(w) => state = EXP_END,
81
82 (EXP_URL, w) if is_url(w) || w.starts_with("../") => state = EXP_END,
83
84 (_, w) if w.len() > columns && is_url(w) => state = EXP_END,
85
86 (_, _) => {}
87 }
88 }
89
90 state == EXP_END
91 }
92
93 /// Returns `true` if `line` is allowed to be longer than the normal limit.
94 /// Currently there is only one exception, for long URLs, but more
95 /// may be added in the future.
96 fn long_line_is_ok(max_columns: usize, line: &str) -> bool {
97 if line_is_url(max_columns, line) {
98 return true;
99 }
100
101 false
102 }
103
104 enum Directive {
105 /// By default, tidy always warns against style issues.
106 Deny,
107
108 /// `Ignore(false)` means that an `ignore-tidy-*` directive
109 /// has been provided, but is unnecessary. `Ignore(true)`
110 /// means that it is necessary (i.e. a warning would be
111 /// produced if `ignore-tidy-*` was not present).
112 Ignore(bool),
113 }
114
115 fn contains_ignore_directive(can_contain: bool, contents: &str, check: &str) -> Directive {
116 if !can_contain {
117 return Directive::Deny;
118 }
119 // Update `can_contain` when changing this
120 if contents.contains(&format!("// ignore-tidy-{}", check))
121 || contents.contains(&format!("# ignore-tidy-{}", check))
122 {
123 Directive::Ignore(false)
124 } else {
125 Directive::Deny
126 }
127 }
128
129 macro_rules! suppressible_tidy_err {
130 ($err:ident, $skip:ident, $msg:expr) => {
131 if let Directive::Deny = $skip {
132 $err($msg);
133 } else {
134 $skip = Directive::Ignore(true);
135 }
136 };
137 }
138
139 pub fn check(path: &Path, bad: &mut bool) {
140 super::walk(path, &mut super::filter_dirs, &mut |entry, contents| {
141 let file = entry.path();
142 let filename = file.file_name().unwrap().to_string_lossy();
143 let extensions = [".rs", ".py", ".js", ".sh", ".c", ".cpp", ".h", ".md"];
144 if extensions.iter().all(|e| !filename.ends_with(e)) || filename.starts_with(".#") {
145 return;
146 }
147
148 let under_rustfmt = filename.ends_with(".rs") &&
149 // This list should ideally be sourced from rustfmt.toml but we don't want to add a toml
150 // parser to tidy.
151 !file.ancestors().any(|a| {
152 a.ends_with("src/test") ||
153 a.ends_with("src/libstd/sys/cloudabi") ||
154 a.ends_with("src/doc/book")
155 });
156
157 if filename.ends_with(".md")
158 && file.parent().unwrap().file_name().unwrap().to_string_lossy() != "error_codes"
159 {
160 // We don't want to check all ".md" files (almost of of them aren't compliant
161 // currently), just the long error code explanation ones.
162 return;
163 }
164
165 if contents.is_empty() {
166 tidy_error!(bad, "{}: empty file", file.display());
167 }
168
169 let max_columns = if filename == "error_codes.rs" || filename.ends_with(".md") {
170 ERROR_CODE_COLS
171 } else {
172 COLS
173 };
174
175 let can_contain =
176 contents.contains("// ignore-tidy-") || contents.contains("# ignore-tidy-");
177 // Enable testing ICE's that require specific (untidy)
178 // file formats easily eg. `issue-1234-ignore-tidy.rs`
179 if filename.contains("ignore-tidy") {
180 return;
181 }
182 let mut skip_cr = contains_ignore_directive(can_contain, &contents, "cr");
183 let mut skip_undocumented_unsafe =
184 contains_ignore_directive(can_contain, &contents, "undocumented-unsafe");
185 let mut skip_tab = contains_ignore_directive(can_contain, &contents, "tab");
186 let mut skip_line_length = contains_ignore_directive(can_contain, &contents, "linelength");
187 let mut skip_file_length = contains_ignore_directive(can_contain, &contents, "filelength");
188 let mut skip_end_whitespace =
189 contains_ignore_directive(can_contain, &contents, "end-whitespace");
190 let mut skip_trailing_newlines =
191 contains_ignore_directive(can_contain, &contents, "trailing-newlines");
192 let mut skip_copyright = contains_ignore_directive(can_contain, &contents, "copyright");
193 let mut leading_new_lines = false;
194 let mut trailing_new_lines = 0;
195 let mut lines = 0;
196 let mut last_safety_comment = false;
197 for (i, line) in contents.split('\n').enumerate() {
198 let mut err = |msg: &str| {
199 tidy_error!(bad, "{}:{}: {}", file.display(), i + 1, msg);
200 };
201 if !under_rustfmt
202 && line.chars().count() > max_columns
203 && !long_line_is_ok(max_columns, line)
204 {
205 suppressible_tidy_err!(
206 err,
207 skip_line_length,
208 &format!("line longer than {} chars", max_columns)
209 );
210 }
211 if line.contains('\t') {
212 suppressible_tidy_err!(err, skip_tab, "tab character");
213 }
214 if line.ends_with(' ') || line.ends_with('\t') {
215 suppressible_tidy_err!(err, skip_end_whitespace, "trailing whitespace");
216 }
217 if line.contains('\r') {
218 suppressible_tidy_err!(err, skip_cr, "CR character");
219 }
220 if filename != "style.rs" {
221 if line.contains("TODO") {
222 err("TODO is deprecated; use FIXME")
223 }
224 if line.contains("//") && line.contains(" XXX") {
225 err("XXX is deprecated; use FIXME")
226 }
227 }
228 let is_test = || file.components().any(|c| c.as_os_str() == "tests");
229 // for now we just check libcore
230 if line.contains("unsafe {") && !line.trim().starts_with("//") && !last_safety_comment {
231 if file.components().any(|c| c.as_os_str() == "libcore") && !is_test() {
232 suppressible_tidy_err!(err, skip_undocumented_unsafe, "undocumented unsafe");
233 }
234 }
235 if line.contains("// SAFETY: ") || line.contains("// Safety: ") {
236 last_safety_comment = true;
237 } else if line.trim().starts_with("//") || line.trim().is_empty() {
238 // keep previous value
239 } else {
240 last_safety_comment = false;
241 }
242 if (line.starts_with("// Copyright")
243 || line.starts_with("# Copyright")
244 || line.starts_with("Copyright"))
245 && (line.contains("Rust Developers") || line.contains("Rust Project Developers"))
246 {
247 suppressible_tidy_err!(
248 err,
249 skip_copyright,
250 "copyright notices attributed to the Rust Project Developers are deprecated"
251 );
252 }
253 if line.ends_with("```ignore") || line.ends_with("```rust,ignore") {
254 err(UNEXPLAINED_IGNORE_DOCTEST_INFO);
255 }
256 if filename.ends_with(".cpp") && line.contains("llvm_unreachable") {
257 err(LLVM_UNREACHABLE_INFO);
258 }
259 if line.is_empty() {
260 if i == 0 {
261 leading_new_lines = true;
262 }
263 trailing_new_lines += 1;
264 } else {
265 trailing_new_lines = 0;
266 }
267 lines = i;
268 }
269 if leading_new_lines {
270 tidy_error!(bad, "{}: leading newline", file.display());
271 }
272 let mut err = |msg: &str| {
273 tidy_error!(bad, "{}: {}", file.display(), msg);
274 };
275 match trailing_new_lines {
276 0 => suppressible_tidy_err!(err, skip_trailing_newlines, "missing trailing newline"),
277 1 => {}
278 n => suppressible_tidy_err!(
279 err,
280 skip_trailing_newlines,
281 &format!("too many trailing newlines ({})", n)
282 ),
283 };
284 if lines > LINES {
285 let mut err = |_| {
286 tidy_error!(
287 bad,
288 "{}: too many lines ({}) (add `// \
289 ignore-tidy-filelength` to the file to suppress this error)",
290 file.display(),
291 lines
292 );
293 };
294 suppressible_tidy_err!(err, skip_file_length, "");
295 }
296
297 if let Directive::Ignore(false) = skip_cr {
298 tidy_error!(bad, "{}: ignoring CR characters unnecessarily", file.display());
299 }
300 if let Directive::Ignore(false) = skip_tab {
301 tidy_error!(bad, "{}: ignoring tab characters unnecessarily", file.display());
302 }
303 if let Directive::Ignore(false) = skip_line_length {
304 tidy_error!(bad, "{}: ignoring line length unnecessarily", file.display());
305 }
306 if let Directive::Ignore(false) = skip_file_length {
307 tidy_error!(bad, "{}: ignoring file length unnecessarily", file.display());
308 }
309 if let Directive::Ignore(false) = skip_end_whitespace {
310 tidy_error!(bad, "{}: ignoring trailing whitespace unnecessarily", file.display());
311 }
312 if let Directive::Ignore(false) = skip_trailing_newlines {
313 tidy_error!(bad, "{}: ignoring trailing newlines unnecessarily", file.display());
314 }
315 if let Directive::Ignore(false) = skip_copyright {
316 tidy_error!(bad, "{}: ignoring copyright unnecessarily", file.display());
317 }
318 })
319 }