1 //! Tidy check to enforce various stylistic guidelines on the Rust codebase.
3 //! Example checks are:
5 //! * No lines over 100 characters.
6 //! * No files with over 3000 lines.
8 //! * No trailing whitespace.
9 //! * No CR characters.
10 //! * No `TODO` or `XXX` directives.
11 //! * No unexplained ` ```ignore ` or ` ```rust,ignore ` doc tests.
13 //! A number of these checks can be opted-out of with various directives of the form:
14 //! `// ignore-tidy-CHECK-NAME`.
18 const ERROR_CODE_COLS
: usize = 80;
19 const COLS
: usize = 100;
21 const LINES
: usize = 3000;
23 const UNEXPLAINED_IGNORE_DOCTEST_INFO
: &str = r
#"unexplained "```ignore" doctest; try one:
25 * make the test actually pass, by adding necessary imports and declarations, or
26 * use "```text", if the code is not Rust code, or
27 * use "```compile_fail,Ennnn", if the code is expected to fail at compile time, or
28 * use "```should_panic", if the code is expected to fail at run time, or
29 * use "```no_run", if the code should type-check but not necessary linkable/runnable, or
30 * explain it like "```ignore (cannot-test-this-because-xxxx)", if the annotation cannot be avoided.
34 const LLVM_UNREACHABLE_INFO
: &str = r
"\
35 C++ code used llvm_unreachable, which triggers undefined behavior
36 when executed when assertions are disabled.
37 Use llvm::report_fatal_error for increased robustness.";
39 /// Parser states for `line_is_url`.
40 #[derive(Clone, Copy, PartialEq)]
41 #[allow(non_camel_case_types)]
44 EXP_LINK_LABEL_OR_URL
,
49 /// Returns `true` if `line` appears to be a line comment containing an URL,
50 /// possibly with a Markdown link label in front, and nothing else.
51 /// The Markdown link label, if present, may not contain whitespace.
52 /// Lines of this form are allowed to be overlength, because Markdown
53 /// offers no way to split a line in the middle of a URL, and the lengths
54 /// of URLs to external references are beyond our control.
55 fn line_is_url(columns
: usize, line
: &str) -> bool
{
56 // more basic check for error_codes.rs, to avoid complexity in implementing two state machines
57 if columns
== ERROR_CODE_COLS
{
58 return line
.starts_with("[") &&
59 line
.contains("]:") && line
.contains("http");
62 use self::LIUState
::*;
63 let mut state
: LIUState
= EXP_COMMENT_START
;
64 let is_url
= |w
: &str| w
.starts_with("http://") || w
.starts_with("https://");
66 for tok
in line
.split_whitespace() {
68 (EXP_COMMENT_START
, "//") |
69 (EXP_COMMENT_START
, "///") |
70 (EXP_COMMENT_START
, "//!") => state
= EXP_LINK_LABEL_OR_URL
,
72 (EXP_LINK_LABEL_OR_URL
, w
)
73 if w
.len() >= 4 && w
.starts_with('
['
) && w
.ends_with("]:")
76 (EXP_LINK_LABEL_OR_URL
, w
)
81 if is_url(w
) || w
.starts_with("../")
85 if w
.len() > columns
&& is_url(w
)
95 /// Returns `true` if `line` is allowed to be longer than the normal limit.
96 /// Currently there is only one exception, for long URLs, but more
97 /// may be added in the future.
98 fn long_line_is_ok(max_columns
: usize, line
: &str) -> bool
{
99 if line_is_url(max_columns
, line
) {
107 /// By default, tidy always warns against style issues.
110 /// `Ignore(false)` means that an `ignore-tidy-*` directive
111 /// has been provided, but is unnecessary. `Ignore(true)`
112 /// means that it is necessary (i.e. a warning would be
113 /// produced if `ignore-tidy-*` was not present).
117 fn contains_ignore_directive(can_contain
: bool
, contents
: &str, check
: &str) -> Directive
{
119 return Directive
::Deny
;
121 // Update `can_contain` when changing this
122 if contents
.contains(&format
!("// ignore-tidy-{}", check
)) ||
123 contents
.contains(&format
!("# ignore-tidy-{}", check
)) {
124 Directive
::Ignore(false)
130 macro_rules
! suppressible_tidy_err
{
131 ($err
:ident
, $skip
:ident
, $msg
:expr
) => {
132 if let Directive
::Deny
= $skip
{
135 $skip
= Directive
::Ignore(true);
140 pub fn check(path
: &Path
, bad
: &mut bool
) {
141 super::walk(path
, &mut super::filter_dirs
, &mut |entry
, contents
| {
142 let file
= entry
.path();
143 let filename
= file
.file_name().unwrap().to_string_lossy();
144 let extensions
= [".rs", ".py", ".js", ".sh", ".c", ".cpp", ".h", ".md"];
145 if extensions
.iter().all(|e
| !filename
.ends_with(e
)) ||
146 filename
.starts_with(".#") {
150 if filename
.ends_with(".md") &&
155 .to_string_lossy() != "error_codes" {
156 // We don't want to check all ".md" files (almost of of them aren't compliant
157 // currently), just the long error code explanation ones.
161 if contents
.is_empty() {
162 tidy_error
!(bad
, "{}: empty file", file
.display());
165 let max_columns
= if filename
== "error_codes.rs" || filename
.ends_with(".md") {
171 let can_contain
= contents
.contains("// ignore-tidy-") ||
172 contents
.contains("# ignore-tidy-");
173 let mut skip_cr
= contains_ignore_directive(can_contain
, &contents
, "cr");
174 let mut skip_undocumented_unsafe
=
175 contains_ignore_directive(can_contain
, &contents
, "undocumented-unsafe");
176 let mut skip_tab
= contains_ignore_directive(can_contain
, &contents
, "tab");
177 let mut skip_line_length
= contains_ignore_directive(can_contain
, &contents
, "linelength");
178 let mut skip_file_length
= contains_ignore_directive(can_contain
, &contents
, "filelength");
179 let mut skip_end_whitespace
=
180 contains_ignore_directive(can_contain
, &contents
, "end-whitespace");
181 let mut skip_trailing_newlines
=
182 contains_ignore_directive(can_contain
, &contents
, "trailing-newlines");
183 let mut skip_copyright
= contains_ignore_directive(can_contain
, &contents
, "copyright");
184 let mut leading_new_lines
= false;
185 let mut trailing_new_lines
= 0;
187 let mut last_safety_comment
= false;
188 for (i
, line
) in contents
.split('
\n'
).enumerate() {
189 let mut err
= |msg
: &str| {
190 tidy_error
!(bad
, "{}:{}: {}", file
.display(), i
+ 1, msg
);
192 if line
.chars().count() > max_columns
&&
193 !long_line_is_ok(max_columns
, line
) {
194 suppressible_tidy_err
!(
197 &format
!("line longer than {} chars", max_columns
)
200 if line
.contains('
\t'
) {
201 suppressible_tidy_err
!(err
, skip_tab
, "tab character");
203 if line
.ends_with(' '
) || line
.ends_with('
\t'
) {
204 suppressible_tidy_err
!(err
, skip_end_whitespace
, "trailing whitespace");
206 if line
.contains('
\r'
) {
207 suppressible_tidy_err
!(err
, skip_cr
, "CR character");
209 if filename
!= "style.rs" {
210 if line
.contains("TODO") {
211 err("TODO is deprecated; use FIXME")
213 if line
.contains("//") && line
.contains(" XXX") {
214 err("XXX is deprecated; use FIXME")
217 let is_test
= || file
.components().any(|c
| c
.as_os_str() == "tests");
218 // for now we just check libcore
219 if line
.contains("unsafe {") && !line
.trim().starts_with("//") && !last_safety_comment
{
220 if file
.components().any(|c
| c
.as_os_str() == "libcore") && !is_test() {
221 suppressible_tidy_err
!(err
, skip_undocumented_unsafe
, "undocumented unsafe");
224 if line
.contains("// SAFETY: ") || line
.contains("// Safety: ") {
225 last_safety_comment
= true;
226 } else if line
.trim().starts_with("//") || line
.trim().is_empty() {
227 // keep previous value
229 last_safety_comment
= false;
231 if (line
.starts_with("// Copyright") ||
232 line
.starts_with("# Copyright") ||
233 line
.starts_with("Copyright"))
234 && (line
.contains("Rust Developers") ||
235 line
.contains("Rust Project Developers")) {
236 suppressible_tidy_err
!(
239 "copyright notices attributed to the Rust Project Developers are deprecated"
242 if line
.ends_with("```ignore") || line
.ends_with("```rust,ignore") {
243 err(UNEXPLAINED_IGNORE_DOCTEST_INFO
);
245 if filename
.ends_with(".cpp") && line
.contains("llvm_unreachable") {
246 err(LLVM_UNREACHABLE_INFO
);
250 leading_new_lines
= true;
252 trailing_new_lines
+= 1;
254 trailing_new_lines
= 0;
258 if leading_new_lines
{
259 tidy_error
!(bad
, "{}: leading newline", file
.display());
261 let mut err
= |msg
: &str| {
262 tidy_error
!(bad
, "{}: {}", file
.display(), msg
);
264 match trailing_new_lines
{
265 0 => suppressible_tidy_err
!(err
, skip_trailing_newlines
, "missing trailing newline"),
267 n
=> suppressible_tidy_err
!(
269 skip_trailing_newlines
,
270 &format
!("too many trailing newlines ({})", n
)
277 "{}: too many lines ({}) (add `// \
278 ignore-tidy-filelength` to the file to suppress this error)",
283 suppressible_tidy_err
!(err
, skip_file_length
, "");
286 if let Directive
::Ignore(false) = skip_cr
{
287 tidy_error
!(bad
, "{}: ignoring CR characters unnecessarily", file
.display());
289 if let Directive
::Ignore(false) = skip_tab
{
290 tidy_error
!(bad
, "{}: ignoring tab characters unnecessarily", file
.display());
292 if let Directive
::Ignore(false) = skip_line_length
{
293 tidy_error
!(bad
, "{}: ignoring line length unnecessarily", file
.display());
295 if let Directive
::Ignore(false) = skip_file_length
{
296 tidy_error
!(bad
, "{}: ignoring file length unnecessarily", file
.display());
298 if let Directive
::Ignore(false) = skip_end_whitespace
{
299 tidy_error
!(bad
, "{}: ignoring trailing whitespace unnecessarily", file
.display());
301 if let Directive
::Ignore(false) = skip_trailing_newlines
{
302 tidy_error
!(bad
, "{}: ignoring trailing newlines unnecessarily", file
.display());
304 if let Directive
::Ignore(false) = skip_copyright
{
305 tidy_error
!(bad
, "{}: ignoring copyright unnecessarily", file
.display());