]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/doc.rs
Merge pull request #2589 from rust-lang-nursery/rangearg
[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 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 empasis 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 let Some(name) = attr.name() {
154             // ignore mix of sugared and non-sugared doc
155             if name == "doc" {
156                 return;
157             }
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: &[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: &[String], text: &str, span: Span) {
237     for word in text.split_whitespace() {
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.iter().any(|i| i == 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, ie. contains at least two uppercase
261     /// letter (`Clippy` is
262     /// ok) and one lower-case letter (`NASA` is ok). Plural are also excluded
263     /// (`IDs` is ok).
264     fn is_camel_case(s: &str) -> bool {
265         if s.starts_with(|c: char| c.is_digit(10)) {
266             return false;
267         }
268
269         let s = if s.ends_with('s') {
270             &s[..s.len() - 1]
271         } else {
272             s
273         };
274
275         s.chars().all(char::is_alphanumeric) && s.chars().filter(|&c| c.is_uppercase()).take(2).count() > 1
276             && s.chars().filter(|&c| c.is_lowercase()).take(1).count() > 0
277     }
278
279     fn has_underscore(s: &str) -> bool {
280         s != "_" && !s.contains("\\_") && 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     if has_underscore(word) || word.contains("::") || is_camel_case(word) {
298         span_lint(
299             cx,
300             DOC_MARKDOWN,
301             span,
302             &format!("you should put `{}` between ticks in the documentation", word),
303         );
304     }
305 }