1 //! Tidy check to enforce various stylistic guidelines on the Rust codebase.
3 //! Example checks are:
5 //! * No lines over 100 characters.
7 //! * No trailing whitespace.
8 //! * No CR characters.
9 //! * No `TODO` or `XXX` directives.
10 //! * No unexplained ` ```ignore ` or ` ```rust,ignore ` doc tests.
12 //! A number of these checks can be opted-out of with various directives of the form:
13 //! `// ignore-tidy-CHECK-NAME`.
16 use std::io::prelude::*;
19 const COLS: usize = 100;
21 const UNEXPLAINED_IGNORE_DOCTEST_INFO: &str = r#"unexplained "```ignore" doctest; try one:
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.
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.";
37 /// Parser states for `line_is_url`.
39 #[allow(non_camel_case_types)]
42 EXP_LINK_LABEL_OR_URL,
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;
57 for tok in line.split_whitespace() {
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,
63 (EXP_LINK_LABEL_OR_URL, w)
64 if w.len() >= 4 && w.starts_with('[') && w.ends_with("]:")
67 (EXP_LINK_LABEL_OR_URL, w)
68 if w.starts_with("http://") || w.starts_with("https://")
72 if w.starts_with("http://") || w.starts_with("https://") || w.starts_with("../")
75 (_, _) => return false,
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) {
94 /// By default, tidy always warns against style issues.
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).
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)
113 macro_rules! suppressible_tidy_err {
114 ($err:ident, $skip:ident, $msg:expr) => {
115 if let Directive::Deny = $skip {
118 $skip = Directive::Ignore(true);
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(".#") {
133 contents.truncate(0);
134 t!(t!(File::open(file), file).read_to_string(&mut contents));
136 if contents.is_empty() {
137 tidy_error!(bad, "{}: empty file", file.display());
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);
151 if line.chars().count() > COLS && !long_line_is_ok(line) {
152 suppressible_tidy_err!(
155 &format!("line longer than {} chars", COLS)
158 if line.contains('\t') {
159 suppressible_tidy_err!(err, skip_tab, "tab character");
161 if line.ends_with(' ') || line.ends_with('\t') {
162 suppressible_tidy_err!(err, skip_end_whitespace, "trailing whitespace");
164 if line.contains('\r') {
165 suppressible_tidy_err!(err, skip_cr, "CR character");
167 if filename != "style.rs" {
168 if line.contains("TODO") {
169 err("TODO is deprecated; use FIXME")
171 if line.contains("//") && line.contains(" XXX") {
172 err("XXX is deprecated; use FIXME")
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!(
183 "copyright notices attributed to the Rust Project Developers are deprecated"
186 if line.ends_with("```ignore") || line.ends_with("```rust,ignore") {
187 err(UNEXPLAINED_IGNORE_DOCTEST_INFO);
189 if filename.ends_with(".cpp") && line.contains("llvm_unreachable") {
190 err(LLVM_UNREACHABLE_INFO);
194 leading_new_lines = true;
196 trailing_new_lines += 1;
198 trailing_new_lines = 0;
201 if leading_new_lines {
202 tidy_error!(bad, "{}: leading newline", file.display());
204 match trailing_new_lines {
205 0 => tidy_error!(bad, "{}: missing trailing newline", file.display()),
207 n => tidy_error!(bad, "{}: too many trailing newlines ({})", file.display(), n),
210 if let Directive::Ignore(false) = skip_cr {
211 tidy_error!(bad, "{}: ignoring CR characters unnecessarily", file.display());
213 if let Directive::Ignore(false) = skip_tab {
214 tidy_error!(bad, "{}: ignoring tab characters unnecessarily", file.display());
216 if let Directive::Ignore(false) = skip_length {
217 tidy_error!(bad, "{}: ignoring line length unnecessarily", file.display());
219 if let Directive::Ignore(false) = skip_end_whitespace {
220 tidy_error!(bad, "{}: ignoring trailing whitespace unnecessarily", file.display());
222 if let Directive::Ignore(false) = skip_copyright {
223 tidy_error!(bad, "{}: ignoring copyright unnecessarily", file.display());