1 //! Tidy check to enforce various stylistic guidelines on the Rust codebase.
3 //! Example checks are:
5 //! * No lines over 100 characters (in non-Rust files).
6 //! * No files with over 3000 lines (in non-Rust files).
8 //! * No trailing whitespace.
9 //! * No CR characters.
10 //! * No `TODO` or `XXX` directives.
11 //! * No unexplained ` ```ignore ` or ` ```rust,ignore ` doc tests.
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.
16 //! A number of these checks can be opted-out of with various directives of the form:
17 //! `// ignore-tidy-CHECK-NAME`.
22 /// Error code markdown is restricted to 80 columns because they can be
23 /// displayed on the console with --example.
24 const ERROR_CODE_COLS
: usize = 80;
25 const COLS
: usize = 100;
27 const LINES
: usize = 3000;
29 const UNEXPLAINED_IGNORE_DOCTEST_INFO
: &str = r
#"unexplained "```ignore" doctest; try one:
31 * make the test actually pass, by adding necessary imports and declarations, or
32 * use "```text", if the code is not Rust code, or
33 * use "```compile_fail,Ennnn", if the code is expected to fail at compile time, or
34 * use "```should_panic", if the code is expected to fail at run time, or
35 * use "```no_run", if the code should type-check but not necessary linkable/runnable, or
36 * explain it like "```ignore (cannot-test-this-because-xxxx)", if the annotation cannot be avoided.
40 const LLVM_UNREACHABLE_INFO
: &str = r
"\
41 C++ code used llvm_unreachable, which triggers undefined behavior
42 when executed when assertions are disabled.
43 Use llvm::report_fatal_error for increased robustness.";
45 const ANNOTATIONS_TO_IGNORE
: &[&str] = &[
56 "// normalize-stderr-test",
59 /// Parser states for `line_is_url`.
60 #[derive(Clone, Copy, PartialEq)]
61 #[allow(non_camel_case_types)]
64 EXP_LINK_LABEL_OR_URL
,
69 /// Returns `true` if `line` appears to be a line comment containing a URL,
70 /// possibly with a Markdown link label in front, and nothing else.
71 /// The Markdown link label, if present, may not contain whitespace.
72 /// Lines of this form are allowed to be overlength, because Markdown
73 /// offers no way to split a line in the middle of a URL, and the lengths
74 /// of URLs to external references are beyond our control.
75 fn line_is_url(is_error_code
: bool
, columns
: usize, line
: &str) -> bool
{
76 // more basic check for markdown, to avoid complexity in implementing two state machines
78 return line
.starts_with('
['
) && line
.contains("]:") && line
.contains("http");
81 use self::LIUState
::*;
82 let mut state
: LIUState
= EXP_COMMENT_START
;
83 let is_url
= |w
: &str| w
.starts_with("http://") || w
.starts_with("https://");
85 for tok
in line
.split_whitespace() {
87 (EXP_COMMENT_START
, "//") | (EXP_COMMENT_START
, "///") | (EXP_COMMENT_START
, "//!") => {
88 state
= EXP_LINK_LABEL_OR_URL
91 (EXP_LINK_LABEL_OR_URL
, w
)
92 if w
.len() >= 4 && w
.starts_with('
['
) && w
.ends_with("]:") =>
97 (EXP_LINK_LABEL_OR_URL
, w
) if is_url(w
) => state
= EXP_END
,
99 (EXP_URL
, w
) if is_url(w
) || w
.starts_with("../") => state
= EXP_END
,
101 (_
, w
) if w
.len() > columns
&& is_url(w
) => state
= EXP_END
,
110 /// Returns `true` if `line` can be ignored. This is the case when it contains
111 /// an annotation that is explicitly ignored.
112 fn should_ignore(line
: &str) -> bool
{
113 // Matches test annotations like `//~ ERROR text`.
114 // This mirrors the regex in src/tools/compiletest/src/runtest.rs, please
115 // update both if either are changed.
116 let re
= Regex
::new("\\s*//(\\[.*\\])?~.*").unwrap();
117 re
.is_match(line
) || ANNOTATIONS_TO_IGNORE
.iter().any(|a
| line
.contains(a
))
120 /// Returns `true` if `line` is allowed to be longer than the normal limit.
121 fn long_line_is_ok(extension
: &str, is_error_code
: bool
, max_columns
: usize, line
: &str) -> bool
{
122 if extension
!= "md" || is_error_code
{
123 if line_is_url(is_error_code
, max_columns
, line
) || should_ignore(line
) {
126 } else if extension
== "md" {
127 // non-error code markdown is allowed to be any length
135 /// By default, tidy always warns against style issues.
138 /// `Ignore(false)` means that an `ignore-tidy-*` directive
139 /// has been provided, but is unnecessary. `Ignore(true)`
140 /// means that it is necessary (i.e. a warning would be
141 /// produced if `ignore-tidy-*` was not present).
145 fn contains_ignore_directive(can_contain
: bool
, contents
: &str, check
: &str) -> Directive
{
147 return Directive
::Deny
;
149 // Update `can_contain` when changing this
150 if contents
.contains(&format
!("// ignore-tidy-{}", check
))
151 || contents
.contains(&format
!("# ignore-tidy-{}", check
))
152 || contents
.contains(&format
!("/* ignore-tidy-{} */", check
))
154 Directive
::Ignore(false)
160 macro_rules
! suppressible_tidy_err
{
161 ($err
:ident
, $skip
:ident
, $msg
:expr
) => {
162 if let Directive
::Deny
= $skip
{
165 $skip
= Directive
::Ignore(true);
170 pub fn is_in(full_path
: &Path
, parent_folder_to_find
: &str, folder_to_find
: &str) -> bool
{
171 if let Some(parent
) = full_path
.parent() {
172 if parent
.file_name().map_or_else(
175 f
.to_string_lossy() == folder_to_find
178 .and_then(|f
| f
.file_name())
179 .map_or_else(|| false, |f
| f
== parent_folder_to_find
)
184 is_in(parent
, parent_folder_to_find
, folder_to_find
)
191 fn skip_markdown_path(path
: &Path
) -> bool
{
192 // These aren't ready for tidy.
193 const SKIP_MD
: &[&str] = &[
194 "src/doc/edition-guide",
195 "src/doc/embedded-book",
198 "src/doc/rust-by-example",
199 "src/doc/rustc-dev-guide",
201 SKIP_MD
.iter().any(|p
| path
.ends_with(p
))
204 fn is_unexplained_ignore(extension
: &str, line
: &str) -> bool
{
205 if !line
.ends_with("```ignore") && !line
.ends_with("```rust,ignore") {
208 if extension
== "md" && line
.trim().starts_with("//") {
209 // Markdown examples may include doc comments with ignore inside a
216 pub fn check(path
: &Path
, bad
: &mut bool
) {
217 fn skip(path
: &Path
) -> bool
{
218 super::filter_dirs(path
) || skip_markdown_path(path
)
220 super::walk(path
, &mut skip
, &mut |entry
, contents
| {
221 let file
= entry
.path();
222 let filename
= file
.file_name().unwrap().to_string_lossy();
223 let extensions
= [".rs", ".py", ".js", ".sh", ".c", ".cpp", ".h", ".md", ".css"];
224 if extensions
.iter().all(|e
| !filename
.ends_with(e
)) || filename
.starts_with(".#") {
228 let is_style_file
= filename
.ends_with(".css");
229 let under_rustfmt
= filename
.ends_with(".rs") &&
230 // This list should ideally be sourced from rustfmt.toml but we don't want to add a toml
232 !file
.ancestors().any(|a
| {
233 a
.ends_with("src/test") ||
234 a
.ends_with("src/doc/book")
237 if is_style_file
&& !is_in(file
, "src", "librustdoc") {
238 // We only check CSS files in rustdoc.
242 if contents
.is_empty() {
243 tidy_error
!(bad
, "{}: empty file", file
.display());
246 let extension
= file
.extension().unwrap().to_string_lossy();
247 let is_error_code
= extension
== "md" && is_in(file
, "src", "error_codes");
249 let max_columns
= if is_error_code { ERROR_CODE_COLS }
else { COLS }
;
251 let can_contain
= contents
.contains("// ignore-tidy-")
252 || contents
.contains("# ignore-tidy-")
253 || contents
.contains("/* ignore-tidy-");
254 // Enable testing ICE's that require specific (untidy)
255 // file formats easily eg. `issue-1234-ignore-tidy.rs`
256 if filename
.contains("ignore-tidy") {
259 let mut skip_cr
= contains_ignore_directive(can_contain
, &contents
, "cr");
260 let mut skip_undocumented_unsafe
=
261 contains_ignore_directive(can_contain
, &contents
, "undocumented-unsafe");
262 let mut skip_tab
= contains_ignore_directive(can_contain
, &contents
, "tab");
263 let mut skip_line_length
= contains_ignore_directive(can_contain
, &contents
, "linelength");
264 let mut skip_file_length
= contains_ignore_directive(can_contain
, &contents
, "filelength");
265 let mut skip_end_whitespace
=
266 contains_ignore_directive(can_contain
, &contents
, "end-whitespace");
267 let mut skip_trailing_newlines
=
268 contains_ignore_directive(can_contain
, &contents
, "trailing-newlines");
269 let mut skip_copyright
= contains_ignore_directive(can_contain
, &contents
, "copyright");
270 let mut leading_new_lines
= false;
271 let mut trailing_new_lines
= 0;
273 let mut last_safety_comment
= false;
274 for (i
, line
) in contents
.split('
\n'
).enumerate() {
275 let mut err
= |msg
: &str| {
276 tidy_error
!(bad
, "{}:{}: {}", file
.display(), i
+ 1, msg
);
279 && line
.chars().count() > max_columns
280 && !long_line_is_ok(&extension
, is_error_code
, max_columns
, line
)
282 suppressible_tidy_err
!(
285 &format
!("line longer than {} chars", max_columns
)
288 if !is_style_file
&& line
.contains('
\t'
) {
289 suppressible_tidy_err
!(err
, skip_tab
, "tab character");
291 if line
.ends_with(' '
) || line
.ends_with('
\t'
) {
292 suppressible_tidy_err
!(err
, skip_end_whitespace
, "trailing whitespace");
294 if is_style_file
&& line
.starts_with(' '
) {
295 err("CSS files use tabs for indent");
297 if line
.contains('
\r'
) {
298 suppressible_tidy_err
!(err
, skip_cr
, "CR character");
300 if filename
!= "style.rs" {
301 if line
.contains("TODO") {
302 err("TODO is deprecated; use FIXME")
304 if line
.contains("//") && line
.contains(" XXX") {
305 err("XXX is deprecated; use FIXME")
308 let is_test
= || file
.components().any(|c
| c
.as_os_str() == "tests");
309 // for now we just check libcore
310 if line
.contains("unsafe {") && !line
.trim().starts_with("//") && !last_safety_comment
{
311 if file
.components().any(|c
| c
.as_os_str() == "core") && !is_test() {
312 suppressible_tidy_err
!(err
, skip_undocumented_unsafe
, "undocumented unsafe");
315 if line
.contains("// SAFETY:") {
316 last_safety_comment
= true;
317 } else if line
.trim().starts_with("//") || line
.trim().is_empty() {
318 // keep previous value
320 last_safety_comment
= false;
322 if (line
.starts_with("// Copyright")
323 || line
.starts_with("# Copyright")
324 || line
.starts_with("Copyright"))
325 && (line
.contains("Rust Developers") || line
.contains("Rust Project Developers"))
327 suppressible_tidy_err
!(
330 "copyright notices attributed to the Rust Project Developers are deprecated"
333 if is_unexplained_ignore(&extension
, line
) {
334 err(UNEXPLAINED_IGNORE_DOCTEST_INFO
);
336 if filename
.ends_with(".cpp") && line
.contains("llvm_unreachable") {
337 err(LLVM_UNREACHABLE_INFO
);
341 leading_new_lines
= true;
343 trailing_new_lines
+= 1;
345 trailing_new_lines
= 0;
348 if !line
.trim().starts_with("//") {
352 if leading_new_lines
{
353 tidy_error
!(bad
, "{}: leading newline", file
.display());
355 let mut err
= |msg
: &str| {
356 tidy_error
!(bad
, "{}: {}", file
.display(), msg
);
358 match trailing_new_lines
{
359 0 => suppressible_tidy_err
!(err
, skip_trailing_newlines
, "missing trailing newline"),
361 n
=> suppressible_tidy_err
!(
363 skip_trailing_newlines
,
364 &format
!("too many trailing newlines ({})", n
)
371 "{}: too many lines ({}) (add `// \
372 ignore-tidy-filelength` to the file to suppress this error)",
377 suppressible_tidy_err
!(err
, skip_file_length
, "");
380 if let Directive
::Ignore(false) = skip_cr
{
381 tidy_error
!(bad
, "{}: ignoring CR characters unnecessarily", file
.display());
383 if let Directive
::Ignore(false) = skip_tab
{
384 tidy_error
!(bad
, "{}: ignoring tab characters unnecessarily", file
.display());
386 if let Directive
::Ignore(false) = skip_line_length
{
387 tidy_error
!(bad
, "{}: ignoring line length unnecessarily", file
.display());
389 if let Directive
::Ignore(false) = skip_file_length
{
390 tidy_error
!(bad
, "{}: ignoring file length unnecessarily", file
.display());
392 if let Directive
::Ignore(false) = skip_end_whitespace
{
393 tidy_error
!(bad
, "{}: ignoring trailing whitespace unnecessarily", file
.display());
395 if let Directive
::Ignore(false) = skip_trailing_newlines
{
396 tidy_error
!(bad
, "{}: ignoring trailing newlines unnecessarily", file
.display());
398 if let Directive
::Ignore(false) = skip_copyright
{
399 tidy_error
!(bad
, "{}: ignoring copyright unnecessarily", file
.display());