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