]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/doc.rs
Merge pull request #2821 from mati865/rust-2018-migration
[rust.git] / clippy_lints / src / doc.rs
1 use itertools::Itertools;
2 use pulldown_cmark;
3 use rustc::lint::*;
4 use syntax::ast;
5 use syntax::codemap::{BytePos, Span};
6 use syntax_pos::Pos;
7 use crate::utils::span_lint;
8 use url::Url;
9
10 /// **What it does:** Checks for the presence of `_`, `::` or camel-case words
11 /// outside ticks in documentation.
12 ///
13 /// **Why is this bad?** *Rustdoc* supports markdown formatting, `_`, `::` and
14 /// camel-case probably indicates some code which should be included between
15 /// ticks. `_` can also be used for emphasis in markdown, this lint tries to
16 /// consider that.
17 ///
18 /// **Known problems:** Lots of bad docs won’t be fixed, what the lint checks
19 /// for is limited, and there are still false positives.
20 ///
21 /// **Examples:**
22 /// ```rust
23 /// /// Do something with the foo_bar parameter. See also
24 /// /// that::other::module::foo.
25 /// // ^ `foo_bar` and `that::other::module::foo` should be ticked.
26 /// fn doit(foo_bar) { .. }
27 /// ```
28 declare_clippy_lint! {
29     pub DOC_MARKDOWN,
30     pedantic,
31     "presence of `_`, `::` or camel-case outside backticks in documentation"
32 }
33
34 #[derive(Clone)]
35 pub struct Doc {
36     valid_idents: Vec<String>,
37 }
38
39 impl Doc {
40     pub fn new(valid_idents: Vec<String>) -> Self {
41         Self {
42             valid_idents,
43         }
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(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![
100                     (doc.len(), span.with_lo(span.lo() + BytePos(prefix.len() as u32))),
101                 ],
102             );
103         }
104     }
105
106     if comment.starts_with("/*") {
107         let doc = &comment[3..comment.len() - 2];
108         let mut sizes = vec![];
109         let mut contains_initial_stars = false;
110         for line in doc.lines() {
111             let offset = line.as_ptr() as usize - comment.as_ptr() as usize;
112             debug_assert_eq!(offset as u32 as usize, offset);
113             contains_initial_stars |= line.trim_left().starts_with('*');
114             // +1 for the newline
115             sizes.push((line.len() + 1, span.with_lo(span.lo() + BytePos(offset as u32))));
116         }
117         if !contains_initial_stars {
118             return (doc.to_string(), sizes);
119         }
120         // remove the initial '*'s if any
121         let mut no_stars = String::with_capacity(doc.len());
122         for line in doc.lines() {
123             let mut chars = line.chars();
124             while let Some(c) = chars.next() {
125                 if c.is_whitespace() {
126                     no_stars.push(c);
127                 } else {
128                     no_stars.push(if c == '*' { ' ' } else { c });
129                     break;
130                 }
131             }
132             no_stars.push_str(chars.as_str());
133             no_stars.push('\n');
134         }
135         return (no_stars, sizes);
136     }
137
138     panic!("not a doc-comment: {}", comment);
139 }
140
141 pub fn check_attrs<'a>(cx: &EarlyContext, valid_idents: &[String], attrs: &'a [ast::Attribute]) {
142     let mut doc = String::new();
143     let mut spans = vec![];
144
145     for attr in attrs {
146         if attr.is_sugared_doc {
147             if let Some(ref current) = attr.value_str() {
148                 let current = current.to_string();
149                 let (current, current_spans) = strip_doc_comment_decoration(&current, attr.span);
150                 spans.extend_from_slice(&current_spans);
151                 doc.push_str(&current);
152             }
153         } else if attr.name() == "doc" {
154             // ignore mix of sugared and non-sugared doc
155             return;
156         }
157     }
158
159     let mut current = 0;
160     for &mut (ref mut offset, _) in &mut spans {
161         let offset_copy = *offset;
162         *offset = current;
163         current += offset_copy;
164     }
165
166     if !doc.is_empty() {
167         let parser = Parser::new(pulldown_cmark::Parser::new(&doc));
168         let parser = parser.coalesce(|x, y| {
169             use pulldown_cmark::Event::*;
170
171             let x_offset = x.0;
172             let y_offset = y.0;
173
174             match (x.1, y.1) {
175                 (Text(x), Text(y)) => {
176                     let mut x = x.into_owned();
177                     x.push_str(&y);
178                     Ok((x_offset, Text(x.into())))
179                 },
180                 (x, y) => Err(((x_offset, x), (y_offset, y))),
181             }
182         });
183         check_doc(cx, valid_idents, parser, &spans);
184     }
185 }
186
187 fn check_doc<'a, Events: Iterator<Item = (usize, pulldown_cmark::Event<'a>)>>(
188     cx: &EarlyContext,
189     valid_idents: &[String],
190     docs: Events,
191     spans: &[(usize, Span)],
192 ) {
193     use pulldown_cmark::Event::*;
194     use pulldown_cmark::Tag::*;
195
196     let mut in_code = false;
197     let mut in_link = None;
198
199     for (offset, event) in docs {
200         match event {
201             Start(CodeBlock(_)) | Start(Code) => in_code = true,
202             End(CodeBlock(_)) | End(Code) => in_code = false,
203             Start(Link(link, _)) => in_link = Some(link),
204             End(Link(_, _)) => in_link = None,
205             Start(_tag) | End(_tag) => (),         // We don't care about other tags
206             Html(_html) | InlineHtml(_html) => (), // HTML is weird, just ignore it
207             SoftBreak | HardBreak => (),
208             FootnoteReference(text) | Text(text) => {
209                 if Some(&text) == in_link.as_ref() {
210                     // Probably a link of the form `<http://example.com>`
211                     // Which are represented as a link to "http://example.com" with
212                     // text "http://example.com" by pulldown-cmark
213                     continue;
214                 }
215
216                 if !in_code {
217                     let index = match spans.binary_search_by(|c| c.0.cmp(&offset)) {
218                         Ok(o) => o,
219                         Err(e) => e - 1,
220                     };
221
222                     let (begin, span) = spans[index];
223
224                     // Adjust for the beginning of the current `Event`
225                     let span = span.with_lo(span.lo() + BytePos::from_usize(offset - begin));
226
227                     check_text(cx, valid_idents, &text, span);
228                 }
229             },
230         }
231     }
232 }
233
234 fn check_text(cx: &EarlyContext, valid_idents: &[String], text: &str, span: Span) {
235     for word in text.split_whitespace() {
236         // Trim punctuation as in `some comment (see foo::bar).`
237         //                                                   ^^
238         // Or even as in `_foo bar_` which is emphasized.
239         let word = word.trim_matches(|c: char| !c.is_alphanumeric());
240
241         if valid_idents.iter().any(|i| i == word) {
242             continue;
243         }
244
245         // Adjust for the current word
246         let offset = word.as_ptr() as usize - text.as_ptr() as usize;
247         let span = Span::new(
248             span.lo() + BytePos::from_usize(offset),
249             span.lo() + BytePos::from_usize(offset + word.len()),
250             span.ctxt(),
251         );
252
253         check_word(cx, word, span);
254     }
255 }
256
257 fn check_word(cx: &EarlyContext, word: &str, span: Span) {
258     /// Checks if a string is camel-case, ie. contains at least two uppercase
259     /// letter (`Clippy` is
260     /// ok) and one lower-case letter (`NASA` is ok). Plural are also excluded
261     /// (`IDs` is ok).
262     fn is_camel_case(s: &str) -> bool {
263         if s.starts_with(|c: char| c.is_digit(10)) {
264             return false;
265         }
266
267         let s = if s.ends_with('s') {
268             &s[..s.len() - 1]
269         } else {
270             s
271         };
272
273         s.chars().all(char::is_alphanumeric) && s.chars().filter(|&c| c.is_uppercase()).take(2).count() > 1
274             && s.chars().filter(|&c| c.is_lowercase()).take(1).count() > 0
275     }
276
277     fn has_underscore(s: &str) -> bool {
278         s != "_" && !s.contains("\\_") && s.contains('_')
279     }
280
281     if let Ok(url) = Url::parse(word) {
282         // try to get around the fact that `foo::bar` parses as a valid URL
283         if !url.cannot_be_a_base() {
284             span_lint(
285                 cx,
286                 DOC_MARKDOWN,
287                 span,
288                 "you should put bare URLs between `<`/`>` or make a proper Markdown link",
289             );
290
291             return;
292         }
293     }
294
295     if has_underscore(word) || word.contains("::") || is_camel_case(word) {
296         span_lint(
297             cx,
298             DOC_MARKDOWN,
299             span,
300             &format!("you should put `{}` between ticks in the documentation", word),
301         );
302     }
303 }