]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/tabs_in_doc_comments.rs
Replace complex conditional with pattern matching
[rust.git] / clippy_lints / src / tabs_in_doc_comments.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use rustc_ast::ast;
3 use rustc_errors::Applicability;
4 use rustc_lint::{EarlyContext, EarlyLintPass};
5 use rustc_session::{declare_lint_pass, declare_tool_lint};
6 use rustc_span::source_map::{BytePos, Span};
7 use std::convert::TryFrom;
8
9 declare_clippy_lint! {
10     /// **What it does:** Checks doc comments for usage of tab characters.
11     ///
12     /// **Why is this bad?** The rust style-guide promotes spaces instead of tabs for indentation.
13     /// To keep a consistent view on the source, also doc comments should not have tabs.
14     /// Also, explaining ascii-diagrams containing tabs can get displayed incorrectly when the
15     /// display settings of the author and reader differ.
16     ///
17     /// **Known problems:** None.
18     ///
19     /// **Example:**
20     /// ```rust
21     /// ///
22     /// /// Struct to hold two strings:
23     /// ///     - first         one
24     /// ///     - second        one
25     /// pub struct DoubleString {
26     ///    ///
27     ///    ///  - First String:
28     ///    ///          - needs to be inside here
29     ///    first_string: String,
30     ///    ///
31     ///    ///  - Second String:
32     ///    ///          - needs to be inside here
33     ///    second_string: String,
34     ///}
35     /// ```
36     ///
37     /// Will be converted to:
38     /// ```rust
39     /// ///
40     /// /// Struct to hold two strings:
41     /// ///     - first        one
42     /// ///     - second    one
43     /// pub struct DoubleString {
44     ///    ///
45     ///    ///     - First String:
46     ///    ///         - needs to be inside here
47     ///    first_string: String,
48     ///    ///
49     ///    ///     - Second String:
50     ///    ///         - needs to be inside here
51     ///    second_string: String,
52     ///}
53     /// ```
54     pub TABS_IN_DOC_COMMENTS,
55     style,
56     "using tabs in doc comments is not recommended"
57 }
58
59 declare_lint_pass!(TabsInDocComments => [TABS_IN_DOC_COMMENTS]);
60
61 impl TabsInDocComments {
62     fn warn_if_tabs_in_doc(cx: &EarlyContext<'_>, attr: &ast::Attribute) {
63         if let ast::AttrKind::DocComment(_, comment) = attr.kind {
64             let comment = comment.as_str();
65
66             for (lo, hi) in get_chunks_of_tabs(&comment) {
67                 // +3 skips the opening delimiter
68                 let new_span = Span::new(
69                     attr.span.lo() + BytePos(3 + lo),
70                     attr.span.lo() + BytePos(3 + 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 char_indices: Vec<_> = the_str.char_indices().collect();
108
109     if let &[(_, '\t')] = &char_indices.as_slice() {
110         return vec![(0, 1)];
111     }
112
113     for entry in char_indices.windows(2) {
114         match entry {
115             [(_, '\t'), (_, '\t')] => {
116                 // either string starts with double tab, then we have to set it active,
117                 // otherwise is_active is true anyway
118                 is_active = true;
119             },
120             [(_, _), (index_b, '\t')] => {
121                 // as ['\t', '\t'] is excluded, this has to be a start of a tab group,
122                 // set indices accordingly
123                 is_active = true;
124                 current_start = *index_b as u32;
125             },
126             [(_, '\t'), (index_b, _)] => {
127                 // this now has to be an end of the group, hence we have to push a new tuple
128                 is_active = false;
129                 spans.push((current_start, *index_b as u32));
130             },
131             _ => {},
132         }
133     }
134
135     // only possible when tabs are at the end, insert last group
136     if is_active {
137         spans.push((
138             current_start,
139             u32::try_from(char_indices.last().unwrap().0 + 1).expect(line_length_way_to_long),
140         ));
141     }
142
143     spans
144 }
145
146 #[cfg(test)]
147 mod tests_for_get_chunks_of_tabs {
148     use super::get_chunks_of_tabs;
149
150     #[test]
151     fn test_unicode_han_string() {
152         let res = get_chunks_of_tabs(" 位\t");
153
154         assert_eq!(res, vec![(4, 5)]);
155     }
156
157     #[test]
158     fn test_empty_string() {
159         let res = get_chunks_of_tabs("");
160
161         assert_eq!(res, vec![]);
162     }
163
164     #[test]
165     fn test_simple() {
166         let res = get_chunks_of_tabs("sd\t\t\taa");
167
168         assert_eq!(res, vec![(2, 5)]);
169     }
170
171     #[test]
172     fn test_only_t() {
173         let res = get_chunks_of_tabs("\t\t");
174
175         assert_eq!(res, vec![(0, 2)]);
176     }
177
178     #[test]
179     fn test_only_one_t() {
180         let res = get_chunks_of_tabs("\t");
181
182         assert_eq!(res, vec![(0, 1)]);
183     }
184
185     #[test]
186     fn test_double() {
187         let res = get_chunks_of_tabs("sd\tasd\t\taa");
188
189         assert_eq!(res, vec![(2, 3), (6, 8)]);
190     }
191
192     #[test]
193     fn test_start() {
194         let res = get_chunks_of_tabs("\t\taa");
195
196         assert_eq!(res, vec![(0, 2)]);
197     }
198
199     #[test]
200     fn test_end() {
201         let res = get_chunks_of_tabs("aa\t\t");
202
203         assert_eq!(res, vec![(2, 4)]);
204     }
205
206     #[test]
207     fn test_start_single() {
208         let res = get_chunks_of_tabs("\taa");
209
210         assert_eq!(res, vec![(0, 1)]);
211     }
212
213     #[test]
214     fn test_end_single() {
215         let res = get_chunks_of_tabs("aa\t");
216
217         assert_eq!(res, vec![(2, 3)]);
218     }
219
220     #[test]
221     fn test_no_tabs() {
222         let res = get_chunks_of_tabs("dsfs");
223
224         assert_eq!(res, vec![]);
225     }
226 }