]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/tabs_in_doc_comments.rs
rustup https://github.com/rust-lang/rust/pull/67455
[rust.git] / clippy_lints / src / tabs_in_doc_comments.rs
1 use crate::utils::span_lint_and_sugg;
2 use rustc::declare_lint_pass;
3 use rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass};
4 use rustc_errors::Applicability;
5 use rustc_session::declare_tool_lint;
6 use std::convert::TryFrom;
7 use syntax::ast;
8 use syntax::source_map::{BytePos, Span};
9
10 declare_clippy_lint! {
11     /// **What it does:** Checks doc comments for usage of tab characters.
12     ///
13     /// **Why is this bad?** The rust style-guide promotes spaces instead of tabs for indentation.
14     /// To keep a consistent view on the source, also doc comments should not have tabs.
15     /// Also, explaining ascii-diagrams containing tabs can get displayed incorrectly when the
16     /// display settings of the author and reader differ.
17     ///
18     /// **Known problems:** None.
19     ///
20     /// **Example:**
21     /// ```rust
22     /// ///
23     /// /// Struct to hold two strings:
24     /// ///     - first         one
25     /// ///     - second        one
26     /// pub struct DoubleString {
27     ///    ///
28     ///    ///  - First String:
29     ///    ///          - needs to be inside here
30     ///    first_string: String,
31     ///    ///
32     ///    ///  - Second String:
33     ///    ///          - needs to be inside here
34     ///    second_string: String,
35     ///}
36     /// ```
37     ///
38     /// Will be converted to:
39      /// ```rust
40     /// ///
41     /// /// Struct to hold two strings:
42     /// ///     - first        one
43     /// ///     - second    one
44     /// pub struct DoubleString {
45     ///    ///
46     ///    ///     - First String:
47     ///    ///         - needs to be inside here
48     ///    first_string: String,
49     ///    ///
50     ///    ///     - Second String:
51     ///    ///         - needs to be inside here
52     ///    second_string: String,
53     ///}
54     /// ```
55     pub TABS_IN_DOC_COMMENTS,
56     style,
57     "using tabs in doc comments is not recommended"
58 }
59
60 declare_lint_pass!(TabsInDocComments => [TABS_IN_DOC_COMMENTS]);
61
62 impl TabsInDocComments {
63     fn warn_if_tabs_in_doc(cx: &EarlyContext<'_>, attr: &ast::Attribute) {
64         if let ast::AttrKind::DocComment(comment) = attr.kind {
65             let comment = comment.as_str();
66
67             for (lo, hi) in get_chunks_of_tabs(&comment) {
68                 let new_span = Span::new(
69                     attr.span.lo() + BytePos(lo),
70                     attr.span.lo() + BytePos(hi),
71                     attr.span.ctxt(),
72                 );
73                 span_lint_and_sugg(
74                     cx,
75                     TABS_IN_DOC_COMMENTS,
76                     new_span,
77                     "using tabs in doc comments is not recommended",
78                     "consider using four spaces per tab",
79                     "    ".repeat((hi - lo) as usize),
80                     Applicability::MaybeIncorrect,
81                 );
82             }
83         }
84     }
85 }
86
87 impl EarlyLintPass for TabsInDocComments {
88     fn check_attribute(&mut self, cx: &EarlyContext<'_>, attribute: &ast::Attribute) {
89         Self::warn_if_tabs_in_doc(cx, &attribute);
90     }
91 }
92
93 ///
94 /// scans the string for groups of tabs and returns the start(inclusive) and end positions
95 /// (exclusive) of all groups
96 /// e.g. "sd\tasd\t\taa" will be converted to [(2, 3), (6, 8)] as
97 ///       012 3456 7 89
98 ///         ^-^  ^---^
99 fn get_chunks_of_tabs(the_str: &str) -> Vec<(u32, u32)> {
100     let line_length_way_to_long = "doc comment longer than 2^32 chars";
101     let mut spans: Vec<(u32, u32)> = vec![];
102     let mut current_start: u32 = 0;
103
104     // tracker to decide if the last group of tabs is not closed by a non-tab character
105     let mut is_active = false;
106
107     let chars_array: Vec<_> = the_str.chars().collect();
108
109     if chars_array == vec!['\t'] {
110         return vec![(0, 1)];
111     }
112
113     for (index, arr) in chars_array.windows(2).enumerate() {
114         let index = u32::try_from(index).expect(line_length_way_to_long);
115         match arr {
116             ['\t', '\t'] => {
117                 // either string starts with double tab, then we have to set it active,
118                 // otherwise is_active is true anyway
119                 is_active = true;
120             },
121             [_, '\t'] => {
122                 // as ['\t', '\t'] is excluded, this has to be a start of a tab group,
123                 // set indices accordingly
124                 is_active = true;
125                 current_start = index + 1;
126             },
127             ['\t', _] => {
128                 // this now has to be an end of the group, hence we have to push a new tuple
129                 is_active = false;
130                 spans.push((current_start, index + 1));
131             },
132             _ => {},
133         }
134     }
135
136     // only possible when tabs are at the end, insert last group
137     if is_active {
138         spans.push((
139             current_start,
140             u32::try_from(the_str.chars().count()).expect(line_length_way_to_long),
141         ));
142     }
143
144     spans
145 }
146
147 #[cfg(test)]
148 mod tests_for_get_chunks_of_tabs {
149     use super::get_chunks_of_tabs;
150
151     #[test]
152     fn test_empty_string() {
153         let res = get_chunks_of_tabs("");
154
155         assert_eq!(res, vec![]);
156     }
157
158     #[test]
159     fn test_simple() {
160         let res = get_chunks_of_tabs("sd\t\t\taa");
161
162         assert_eq!(res, vec![(2, 5)]);
163     }
164
165     #[test]
166     fn test_only_t() {
167         let res = get_chunks_of_tabs("\t\t");
168
169         assert_eq!(res, vec![(0, 2)]);
170     }
171
172     #[test]
173     fn test_only_one_t() {
174         let res = get_chunks_of_tabs("\t");
175
176         assert_eq!(res, vec![(0, 1)]);
177     }
178
179     #[test]
180     fn test_double() {
181         let res = get_chunks_of_tabs("sd\tasd\t\taa");
182
183         assert_eq!(res, vec![(2, 3), (6, 8)]);
184     }
185
186     #[test]
187     fn test_start() {
188         let res = get_chunks_of_tabs("\t\taa");
189
190         assert_eq!(res, vec![(0, 2)]);
191     }
192
193     #[test]
194     fn test_end() {
195         let res = get_chunks_of_tabs("aa\t\t");
196
197         assert_eq!(res, vec![(2, 4)]);
198     }
199
200     #[test]
201     fn test_start_single() {
202         let res = get_chunks_of_tabs("\taa");
203
204         assert_eq!(res, vec![(0, 1)]);
205     }
206
207     #[test]
208     fn test_end_single() {
209         let res = get_chunks_of_tabs("aa\t");
210
211         assert_eq!(res, vec![(2, 3)]);
212     }
213
214     #[test]
215     fn test_no_tabs() {
216         let res = get_chunks_of_tabs("dsfs");
217
218         assert_eq!(res, vec![]);
219     }
220 }