]> git.lizzy.rs Git - rust.git/blob - src/tools/tidy/src/style.rs
9ab88d6e9aeac8049dc68c1c39a7b4325319cf25
[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.
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 of the form:
13 //! `// ignore-tidy-CHECK-NAME`.
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 enum Directive {
94     /// By default, tidy always warns against style issues.
95     Deny,
96
97     /// `Ignore(false)` means that an `ignore-tidy-*` directive
98     /// has been provided, but is unnecessary. `Ignore(true)`
99     /// means that it is necessary (i.e. a warning would be
100     /// produced if `ignore-tidy-*` was not present).
101     Ignore(bool),
102 }
103
104 fn contains_ignore_directive(contents: &String, check: &str) -> Directive {
105     if contents.contains(&format!("// ignore-tidy-{}", check)) ||
106         contents.contains(&format!("# ignore-tidy-{}", check)) {
107         Directive::Ignore(false)
108     } else {
109         Directive::Deny
110     }
111 }
112
113 macro_rules! suppressible_tidy_err {
114     ($err:ident, $skip:ident, $msg:expr) => {
115         if let Directive::Deny = $skip {
116             $err($msg);
117         } else {
118             $skip = Directive::Ignore(true);
119         }
120     };
121 }
122
123 pub fn check(path: &Path, bad: &mut bool) {
124     let mut contents = String::new();
125     super::walk(path, &mut super::filter_dirs, &mut |file| {
126         let filename = file.file_name().unwrap().to_string_lossy();
127         let extensions = [".rs", ".py", ".js", ".sh", ".c", ".cpp", ".h"];
128         if extensions.iter().all(|e| !filename.ends_with(e)) ||
129            filename.starts_with(".#") {
130             return
131         }
132
133         contents.truncate(0);
134         t!(t!(File::open(file), file).read_to_string(&mut contents));
135
136         if contents.is_empty() {
137             tidy_error!(bad, "{}: empty file", file.display());
138         }
139
140         let mut skip_cr = contains_ignore_directive(&contents, "cr");
141         let mut skip_tab = contains_ignore_directive(&contents, "tab");
142         let mut skip_length = contains_ignore_directive(&contents, "linelength");
143         let mut skip_end_whitespace = contains_ignore_directive(&contents, "end-whitespace");
144         let mut skip_copyright = contains_ignore_directive(&contents, "copyright");
145         let mut leading_new_lines = false;
146         let mut trailing_new_lines = 0;
147         for (i, line) in contents.split('\n').enumerate() {
148             let mut err = |msg: &str| {
149                 tidy_error!(bad, "{}:{}: {}", file.display(), i + 1, msg);
150             };
151             if line.chars().count() > COLS && !long_line_is_ok(line) {
152                 suppressible_tidy_err!(
153                     err,
154                     skip_length,
155                     &format!("line longer than {} chars", COLS)
156                 );
157             }
158             if line.contains('\t') {
159                 suppressible_tidy_err!(err, skip_tab, "tab character");
160             }
161             if line.ends_with(' ') || line.ends_with('\t') {
162                 suppressible_tidy_err!(err, skip_end_whitespace, "trailing whitespace");
163             }
164             if line.contains('\r') {
165                 suppressible_tidy_err!(err, skip_cr, "CR character");
166             }
167             if filename != "style.rs" {
168                 if line.contains("TODO") {
169                     err("TODO is deprecated; use FIXME")
170                 }
171                 if line.contains("//") && line.contains(" XXX") {
172                     err("XXX is deprecated; use FIXME")
173                 }
174             }
175             if (line.starts_with("// Copyright") ||
176                 line.starts_with("# Copyright") ||
177                 line.starts_with("Copyright"))
178                 && (line.contains("Rust Developers") ||
179                     line.contains("Rust Project Developers")) {
180                 suppressible_tidy_err!(
181                     err,
182                     skip_copyright,
183                     "copyright notices attributed to the Rust Project Developers are deprecated"
184                 );
185             }
186             if line.ends_with("```ignore") || line.ends_with("```rust,ignore") {
187                 err(UNEXPLAINED_IGNORE_DOCTEST_INFO);
188             }
189             if filename.ends_with(".cpp") && line.contains("llvm_unreachable") {
190                 err(LLVM_UNREACHABLE_INFO);
191             }
192             if line.is_empty() {
193                 if i == 0 {
194                     leading_new_lines = true;
195                 }
196                 trailing_new_lines += 1;
197             } else {
198                 trailing_new_lines = 0;
199             }
200         }
201         if leading_new_lines {
202             tidy_error!(bad, "{}: leading newline", file.display());
203         }
204         match trailing_new_lines {
205             0 => tidy_error!(bad, "{}: missing trailing newline", file.display()),
206             1 => {}
207             n => tidy_error!(bad, "{}: too many trailing newlines ({})", file.display(), n),
208         };
209
210         if let Directive::Ignore(false) = skip_cr {
211             tidy_error!(bad, "{}: ignoring CR characters unnecessarily", file.display());
212         }
213         if let Directive::Ignore(false) = skip_tab {
214             tidy_error!(bad, "{}: ignoring tab characters unnecessarily", file.display());
215         }
216         if let Directive::Ignore(false) = skip_length {
217             tidy_error!(bad, "{}: ignoring line length unnecessarily", file.display());
218         }
219         if let Directive::Ignore(false) = skip_end_whitespace {
220             tidy_error!(bad, "{}: ignoring trailing whitespace unnecessarily", file.display());
221         }
222         if let Directive::Ignore(false) = skip_copyright {
223             tidy_error!(bad, "{}: ignoring copyright unnecessarily", file.display());
224         }
225     })
226 }