]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/doc.rs
Auto merge of #3946 - rchaser53:issue-3920, r=flip1995
[rust.git] / clippy_lints / src / doc.rs
1 use crate::utils::span_lint;
2 use itertools::Itertools;
3 use pulldown_cmark;
4 use rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass};
5 use rustc::{declare_tool_lint, lint_array};
6 use rustc_data_structures::fx::FxHashSet;
7 use syntax::ast;
8 use syntax::source_map::{BytePos, Span};
9 use syntax_pos::Pos;
10 use url::Url;
11
12 declare_clippy_lint! {
13     /// **What it does:** Checks for the presence of `_`, `::` or camel-case words
14     /// outside ticks in documentation.
15     ///
16     /// **Why is this bad?** *Rustdoc* supports markdown formatting, `_`, `::` and
17     /// camel-case probably indicates some code which should be included between
18     /// ticks. `_` can also be used for emphasis in markdown, this lint tries to
19     /// consider that.
20     ///
21     /// **Known problems:** Lots of bad docs won’t be fixed, what the lint checks
22     /// for is limited, and there are still false positives.
23     ///
24     /// **Examples:**
25     /// ```rust
26     /// /// Do something with the foo_bar parameter. See also
27     /// /// that::other::module::foo.
28     /// // ^ `foo_bar` and `that::other::module::foo` should be ticked.
29     /// fn doit(foo_bar) { .. }
30     /// ```
31     pub DOC_MARKDOWN,
32     pedantic,
33     "presence of `_`, `::` or camel-case outside backticks in documentation"
34 }
35
36 #[derive(Clone)]
37 pub struct Doc {
38     valid_idents: FxHashSet<String>,
39 }
40
41 impl Doc {
42     pub fn new(valid_idents: FxHashSet<String>) -> Self {
43         Self { valid_idents }
44     }
45 }
46
47 impl LintPass for Doc {
48     fn get_lints(&self) -> LintArray {
49         lint_array![DOC_MARKDOWN]
50     }
51
52     fn name(&self) -> &'static str {
53         "DocMarkdown"
54     }
55 }
56
57 impl EarlyLintPass for Doc {
58     fn check_crate(&mut self, cx: &EarlyContext<'_>, krate: &ast::Crate) {
59         check_attrs(cx, &self.valid_idents, &krate.attrs);
60     }
61
62     fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
63         check_attrs(cx, &self.valid_idents, &item.attrs);
64     }
65 }
66
67 struct Parser<'a> {
68     parser: pulldown_cmark::Parser<'a>,
69 }
70
71 impl<'a> Parser<'a> {
72     fn new(parser: pulldown_cmark::Parser<'a>) -> Self {
73         Self { parser }
74     }
75 }
76
77 impl<'a> Iterator for Parser<'a> {
78     type Item = (usize, pulldown_cmark::Event<'a>);
79
80     fn next(&mut self) -> Option<Self::Item> {
81         let offset = self.parser.get_offset();
82         self.parser.next().map(|event| (offset, event))
83     }
84 }
85
86 /// Cleanup documentation decoration (`///` and such).
87 ///
88 /// We can't use `syntax::attr::AttributeMethods::with_desugared_doc` or
89 /// `syntax::parse::lexer::comments::strip_doc_comment_decoration` because we
90 /// need to keep track of
91 /// the spans but this function is inspired from the later.
92 #[allow(clippy::cast_possible_truncation)]
93 pub fn strip_doc_comment_decoration(comment: &str, span: Span) -> (String, Vec<(usize, Span)>) {
94     // one-line comments lose their prefix
95     const ONELINERS: &[&str] = &["///!", "///", "//!", "//"];
96     for prefix in ONELINERS {
97         if comment.starts_with(*prefix) {
98             let doc = &comment[prefix.len()..];
99             let mut doc = doc.to_owned();
100             doc.push('\n');
101             return (
102                 doc.to_owned(),
103                 vec![(doc.len(), span.with_lo(span.lo() + BytePos(prefix.len() as u32)))],
104             );
105         }
106     }
107
108     if comment.starts_with("/*") {
109         let doc = &comment[3..comment.len() - 2];
110         let mut sizes = vec![];
111         let mut contains_initial_stars = false;
112         for line in doc.lines() {
113             let offset = line.as_ptr() as usize - comment.as_ptr() as usize;
114             debug_assert_eq!(offset as u32 as usize, offset);
115             contains_initial_stars |= line.trim_start().starts_with('*');
116             // +1 for the newline
117             sizes.push((line.len() + 1, span.with_lo(span.lo() + BytePos(offset as u32))));
118         }
119         if !contains_initial_stars {
120             return (doc.to_string(), sizes);
121         }
122         // remove the initial '*'s if any
123         let mut no_stars = String::with_capacity(doc.len());
124         for line in doc.lines() {
125             let mut chars = line.chars();
126             while let Some(c) = chars.next() {
127                 if c.is_whitespace() {
128                     no_stars.push(c);
129                 } else {
130                     no_stars.push(if c == '*' { ' ' } else { c });
131                     break;
132                 }
133             }
134             no_stars.push_str(chars.as_str());
135             no_stars.push('\n');
136         }
137         return (no_stars, sizes);
138     }
139
140     panic!("not a doc-comment: {}", comment);
141 }
142
143 pub fn check_attrs<'a>(cx: &EarlyContext<'_>, valid_idents: &FxHashSet<String>, attrs: &'a [ast::Attribute]) {
144     let mut doc = String::new();
145     let mut spans = vec![];
146
147     for attr in attrs {
148         if attr.is_sugared_doc {
149             if let Some(ref current) = attr.value_str() {
150                 let current = current.to_string();
151                 let (current, current_spans) = strip_doc_comment_decoration(&current, attr.span);
152                 spans.extend_from_slice(&current_spans);
153                 doc.push_str(&current);
154             }
155         } else if attr.check_name("doc") {
156             // ignore mix of sugared and non-sugared doc
157             return;
158         }
159     }
160
161     let mut current = 0;
162     for &mut (ref mut offset, _) in &mut spans {
163         let offset_copy = *offset;
164         *offset = current;
165         current += offset_copy;
166     }
167
168     if !doc.is_empty() {
169         let parser = Parser::new(pulldown_cmark::Parser::new(&doc));
170         let parser = parser.coalesce(|x, y| {
171             use pulldown_cmark::Event::*;
172
173             let x_offset = x.0;
174             let y_offset = y.0;
175
176             match (x.1, y.1) {
177                 (Text(x), Text(y)) => {
178                     let mut x = x.into_owned();
179                     x.push_str(&y);
180                     Ok((x_offset, Text(x.into())))
181                 },
182                 (x, y) => Err(((x_offset, x), (y_offset, y))),
183             }
184         });
185         check_doc(cx, valid_idents, parser, &spans);
186     }
187 }
188
189 fn check_doc<'a, Events: Iterator<Item = (usize, pulldown_cmark::Event<'a>)>>(
190     cx: &EarlyContext<'_>,
191     valid_idents: &FxHashSet<String>,
192     docs: Events,
193     spans: &[(usize, Span)],
194 ) {
195     use pulldown_cmark::Event::*;
196     use pulldown_cmark::Tag::*;
197
198     let mut in_code = false;
199     let mut in_link = None;
200
201     for (offset, event) in docs {
202         match event {
203             Start(CodeBlock(_)) | Start(Code) => in_code = true,
204             End(CodeBlock(_)) | End(Code) => in_code = false,
205             Start(Link(link, _)) => in_link = Some(link),
206             End(Link(_, _)) => in_link = None,
207             Start(_tag) | End(_tag) => (),         // We don't care about other tags
208             Html(_html) | InlineHtml(_html) => (), // HTML is weird, just ignore it
209             SoftBreak | HardBreak => (),
210             FootnoteReference(text) | Text(text) => {
211                 if Some(&text) == in_link.as_ref() {
212                     // Probably a link of the form `<http://example.com>`
213                     // Which are represented as a link to "http://example.com" with
214                     // text "http://example.com" by pulldown-cmark
215                     continue;
216                 }
217
218                 if !in_code {
219                     let index = match spans.binary_search_by(|c| c.0.cmp(&offset)) {
220                         Ok(o) => o,
221                         Err(e) => e - 1,
222                     };
223
224                     let (begin, span) = spans[index];
225
226                     // Adjust for the beginning of the current `Event`
227                     let span = span.with_lo(span.lo() + BytePos::from_usize(offset - begin));
228
229                     check_text(cx, valid_idents, &text, span);
230                 }
231             },
232         }
233     }
234 }
235
236 fn check_text(cx: &EarlyContext<'_>, valid_idents: &FxHashSet<String>, text: &str, span: Span) {
237     for word in text.split(|c: char| c.is_whitespace() || c == '\'') {
238         // Trim punctuation as in `some comment (see foo::bar).`
239         //                                                   ^^
240         // Or even as in `_foo bar_` which is emphasized.
241         let word = word.trim_matches(|c: char| !c.is_alphanumeric());
242
243         if valid_idents.contains(word) {
244             continue;
245         }
246
247         // Adjust for the current word
248         let offset = word.as_ptr() as usize - text.as_ptr() as usize;
249         let span = Span::new(
250             span.lo() + BytePos::from_usize(offset),
251             span.lo() + BytePos::from_usize(offset + word.len()),
252             span.ctxt(),
253         );
254
255         check_word(cx, word, span);
256     }
257 }
258
259 fn check_word(cx: &EarlyContext<'_>, word: &str, span: Span) {
260     /// Checks if a string is camel-case, i.e., contains at least two uppercase
261     /// letters (`Clippy` is ok) and one lower-case letter (`NASA` is ok).
262     /// Plurals are also excluded (`IDs` is ok).
263     fn is_camel_case(s: &str) -> bool {
264         if s.starts_with(|c: char| c.is_digit(10)) {
265             return false;
266         }
267
268         let s = if s.ends_with('s') { &s[..s.len() - 1] } else { s };
269
270         s.chars().all(char::is_alphanumeric)
271             && s.chars().filter(|&c| c.is_uppercase()).take(2).count() > 1
272             && s.chars().filter(|&c| c.is_lowercase()).take(1).count() > 0
273     }
274
275     fn has_underscore(s: &str) -> bool {
276         s != "_" && !s.contains("\\_") && s.contains('_')
277     }
278
279     fn has_hyphen(s: &str) -> bool {
280         s != "-" && s.contains('-')
281     }
282
283     if let Ok(url) = Url::parse(word) {
284         // try to get around the fact that `foo::bar` parses as a valid URL
285         if !url.cannot_be_a_base() {
286             span_lint(
287                 cx,
288                 DOC_MARKDOWN,
289                 span,
290                 "you should put bare URLs between `<`/`>` or make a proper Markdown link",
291             );
292
293             return;
294         }
295     }
296
297     // We assume that mixed-case words are not meant to be put inside bacticks. (Issue #2343)
298     if has_underscore(word) && has_hyphen(word) {
299         return;
300     }
301
302     if has_underscore(word) || word.contains("::") || is_camel_case(word) {
303         span_lint(
304             cx,
305             DOC_MARKDOWN,
306             span,
307             &format!("you should put `{}` between ticks in the documentation", word),
308         );
309     }
310 }