1 // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Tidy check to enforce various stylistic guidelines on the Rust codebase.
13 //! Example checks are:
15 //! * No lines over 100 characters
17 //! * No trailing whitespace
18 //! * No CR characters
19 //! * No `TODO` or `XXX` directives
20 //! * A valid license header is at the top
21 //! * No unexplained ` ```ignore ` or ` ```rust,ignore ` doc tests
23 //! A number of these checks can be opted-out of with various directives like
24 //! `// ignore-tidy-linelength`.
27 use std
::io
::prelude
::*;
30 const COLS
: usize = 100;
31 const LICENSE
: &'
static str = "\
32 Copyright <year> The Rust Project Developers. See the COPYRIGHT
33 file at the top-level directory of this distribution and at
34 http://rust-lang.org/COPYRIGHT.
36 Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
37 http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
38 <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
39 option. This file may not be copied, modified, or distributed
40 except according to those terms.";
42 const UNEXPLAINED_IGNORE_DOCTEST_INFO
: &str = r
#"unexplained "```ignore" doctest; try one:
44 * make the test actually pass, by adding necessary imports and declarations, or
45 * use "```text", if the code is not Rust code, or
46 * use "```compile_fail,Ennnn", if the code is expected to fail at compile time, or
47 * use "```should_panic", if the code is expected to fail at run time, or
48 * use "```no_run", if the code should type-check but not necessary linkable/runnable, or
49 * explain it like "```ignore (cannot-test-this-because-xxxx)", if the annotation cannot be avoided.
53 /// Parser states for line_is_url.
55 #[allow(non_camel_case_types)]
56 enum LIUState
{ EXP_COMMENT_START
,
57 EXP_LINK_LABEL_OR_URL
,
61 /// True if LINE appears to be a line comment containing an URL,
62 /// possibly with a Markdown link label in front, and nothing else.
63 /// The Markdown link label, if present, may not contain whitespace.
64 /// Lines of this form are allowed to be overlength, because Markdown
65 /// offers no way to split a line in the middle of a URL, and the lengths
66 /// of URLs to external references are beyond our control.
67 fn line_is_url(line
: &str) -> bool
{
68 use self::LIUState
::*;
69 let mut state
: LIUState
= EXP_COMMENT_START
;
71 for tok
in line
.split_whitespace() {
73 (EXP_COMMENT_START
, "//") => state
= EXP_LINK_LABEL_OR_URL
,
74 (EXP_COMMENT_START
, "///") => state
= EXP_LINK_LABEL_OR_URL
,
75 (EXP_COMMENT_START
, "//!") => state
= EXP_LINK_LABEL_OR_URL
,
77 (EXP_LINK_LABEL_OR_URL
, w
)
78 if w
.len() >= 4 && w
.starts_with("[") && w
.ends_with("]:")
81 (EXP_LINK_LABEL_OR_URL
, w
)
82 if w
.starts_with("http://") || w
.starts_with("https://")
86 if w
.starts_with("http://") || w
.starts_with("https://")
89 (_
, _
) => return false,
96 /// True if LINE is allowed to be longer than the normal limit.
97 /// Currently there is only one exception, for long URLs, but more
98 /// may be added in the future.
99 fn long_line_is_ok(line
: &str) -> bool
{
100 if line_is_url(line
) {
107 pub fn check(path
: &Path
, bad
: &mut bool
) {
108 let mut contents
= String
::new();
109 super::walk(path
, &mut super::filter_dirs
, &mut |file
| {
110 let filename
= file
.file_name().unwrap().to_string_lossy();
111 let extensions
= [".rs", ".py", ".js", ".sh", ".c", ".h"];
112 if extensions
.iter().all(|e
| !filename
.ends_with(e
)) ||
113 filename
.starts_with(".#") {
117 contents
.truncate(0);
118 t
!(t
!(File
::open(file
), file
).read_to_string(&mut contents
));
120 if contents
.is_empty() {
121 tidy_error
!(bad
, "{}: empty file", file
.display());
124 let skip_cr
= contents
.contains("ignore-tidy-cr");
125 let skip_tab
= contents
.contains("ignore-tidy-tab");
126 let skip_length
= contents
.contains("ignore-tidy-linelength");
127 let skip_end_whitespace
= contents
.contains("ignore-tidy-end-whitespace");
128 for (i
, line
) in contents
.split("\n").enumerate() {
129 let mut err
= |msg
: &str| {
130 tidy_error
!(bad
, "{}:{}: {}", file
.display(), i
+ 1, msg
);
132 if !skip_length
&& line
.chars().count() > COLS
133 && !long_line_is_ok(line
) {
134 err(&format
!("line longer than {} chars", COLS
));
136 if line
.contains("\t") && !skip_tab
{
137 err("tab character");
139 if !skip_end_whitespace
&& (line
.ends_with(" ") || line
.ends_with("\t")) {
140 err("trailing whitespace");
142 if line
.contains("\r") && !skip_cr
{
145 if filename
!= "style.rs" {
146 if line
.contains("TODO") {
147 err("TODO is deprecated; use FIXME")
149 if line
.contains("//") && line
.contains(" XXX") {
150 err("XXX is deprecated; use FIXME")
153 if line
.ends_with("```ignore") || line
.ends_with("```rust,ignore") {
154 err(UNEXPLAINED_IGNORE_DOCTEST_INFO
);
157 if !licenseck(file
, &contents
) {
158 tidy_error
!(bad
, "{}: incorrect license", file
.display());
163 fn licenseck(file
: &Path
, contents
: &str) -> bool
{
164 if contents
.contains("ignore-license") {
168 "libstd/sync/mpsc/mpsc_queue.rs",
169 "libstd/sync/mpsc/spsc_queue.rs",
171 if exceptions
.iter().any(|f
| file
.ends_with(f
)) {
175 // Skip the BOM if it's there
176 let bom
= "\u{feff}";
177 let contents
= if contents
.starts_with(bom
) {&contents[3..]}
else {contents}
;
179 // See if the license shows up in the first 100 lines
180 let lines
= contents
.lines().take(100).collect
::<Vec
<_
>>();
181 lines
.windows(LICENSE
.lines().count()).any(|window
| {
182 let offset
= if window
.iter().all(|w
| w
.starts_with("//")) {
184 } else if window
.iter().all(|w
| w
.starts_with('
#')) {
186 } else if window
.iter().all(|w
| w
.starts_with(" *")) {
191 window
.iter().map(|a
| a
[offset
..].trim())
192 .zip(LICENSE
.lines()).all(|(a
, b
)| {
193 a
== b
|| match b
.find("<year>") {
194 Some(i
) => a
.starts_with(&b
[..i
]) && a
.ends_with(&b
[i
+6..]),