]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/doc.rs
Merge pull request #2006 from rust-lang-nursery/rustup
[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::{Span, BytePos};
6 use syntax_pos::Pos;
7 use utils::span_lint;
8
9 /// **What it does:** Checks for the presence of `_`, `::` or camel-case words
10 /// outside ticks in documentation.
11 ///
12 /// **Why is this bad?** *Rustdoc* supports markdown formatting, `_`, `::` and
13 /// camel-case probably indicates some code which should be included between
14 /// ticks. `_` can also be used for empasis in markdown, this lint tries to
15 /// consider that.
16 ///
17 /// **Known problems:** Lots of bad docs won’t be fixed, what the lint checks
18 /// for is limited, and there are still false positives.
19 ///
20 /// **Examples:**
21 /// ```rust
22 /// /// Do something with the foo_bar parameter. See also
23 /// that::other::module::foo.
24 /// // ^ `foo_bar` and `that::other::module::foo` should be ticked.
25 /// fn doit(foo_bar) { .. }
26 /// ```
27 declare_lint! {
28     pub DOC_MARKDOWN,
29     Warn,
30     "presence of `_`, `::` or camel-case outside backticks in documentation"
31 }
32
33 #[derive(Clone)]
34 pub struct Doc {
35     valid_idents: Vec<String>,
36 }
37
38 impl Doc {
39     pub fn new(valid_idents: Vec<String>) -> Self {
40         Self { valid_idents: valid_idents }
41     }
42 }
43
44 impl LintPass for Doc {
45     fn get_lints(&self) -> LintArray {
46         lint_array![DOC_MARKDOWN]
47     }
48 }
49
50 impl EarlyLintPass for Doc {
51     fn check_crate(&mut self, cx: &EarlyContext, krate: &ast::Crate) {
52         check_attrs(cx, &self.valid_idents, &krate.attrs);
53     }
54
55     fn check_item(&mut self, cx: &EarlyContext, item: &ast::Item) {
56         check_attrs(cx, &self.valid_idents, &item.attrs);
57     }
58 }
59
60 struct Parser<'a> {
61     parser: pulldown_cmark::Parser<'a>,
62 }
63
64 impl<'a> Parser<'a> {
65     fn new(parser: pulldown_cmark::Parser<'a>) -> Self {
66         Self { parser: parser }
67     }
68 }
69
70 impl<'a> Iterator for Parser<'a> {
71     type Item = (usize, pulldown_cmark::Event<'a>);
72
73     fn next(&mut self) -> Option<Self::Item> {
74         let offset = self.parser.get_offset();
75         self.parser.next().map(|event| (offset, event))
76     }
77 }
78
79 /// Cleanup documentation decoration (`///` and such).
80 ///
81 /// We can't use `syntax::attr::AttributeMethods::with_desugared_doc` or
82 /// `syntax::parse::lexer::comments::strip_doc_comment_decoration` because we
83 /// need to keep track of
84 /// the spans but this function is inspired from the later.
85 #[allow(cast_possible_truncation)]
86 pub fn strip_doc_comment_decoration(comment: &str, span: Span) -> (String, Vec<(usize, Span)>) {
87     // one-line comments lose their prefix
88     const ONELINERS: &'static [&'static str] = &["///!", "///", "//!", "//"];
89     for prefix in ONELINERS {
90         if comment.starts_with(*prefix) {
91             let doc = &comment[prefix.len()..];
92             let mut doc = doc.to_owned();
93             doc.push('\n');
94             return (
95                 doc.to_owned(),
96                 vec![
97                     (
98                         doc.len(),
99                         span.with_lo(span.lo() + BytePos(prefix.len() as u32)),
100                     ),
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((
116                 line.len() + 1,
117                 span.with_lo(span.lo() + BytePos(offset as u32)),
118             ));
119         }
120         if !contains_initial_stars {
121             return (doc.to_string(), sizes);
122         }
123         // remove the initial '*'s if any
124         let mut no_stars = String::with_capacity(doc.len());
125         for line in doc.lines() {
126             let mut chars = line.chars();
127             while let Some(c) = chars.next() {
128                 if c.is_whitespace() {
129                     no_stars.push(c);
130                 } else {
131                     no_stars.push(if c == '*' { ' ' } else { c });
132                     break;
133                 }
134             }
135             no_stars.push_str(chars.as_str());
136             no_stars.push('\n');
137         }
138         return (no_stars, sizes);
139     }
140
141     panic!("not a doc-comment: {}", comment);
142 }
143
144 pub fn check_attrs<'a>(cx: &EarlyContext, valid_idents: &[String], attrs: &'a [ast::Attribute]) {
145     let mut doc = String::new();
146     let mut spans = vec![];
147
148     for attr in attrs {
149         if attr.is_sugared_doc {
150             if let Some(ref current) = attr.value_str() {
151                 let current = current.to_string();
152                 let (current, current_spans) = strip_doc_comment_decoration(&current, attr.span);
153                 spans.extend_from_slice(&current_spans);
154                 doc.push_str(&current);
155             }
156         } else if let Some(name) = attr.name() {
157             // ignore mix of sugared and non-sugared doc
158             if name == "doc" {
159                 return;
160             }
161         }
162     }
163
164     let mut current = 0;
165     for &mut (ref mut offset, _) in &mut spans {
166         let offset_copy = *offset;
167         *offset = current;
168         current += offset_copy;
169     }
170
171     if !doc.is_empty() {
172         let parser = Parser::new(pulldown_cmark::Parser::new(&doc));
173         let parser = parser.coalesce(|x, y| {
174             use pulldown_cmark::Event::*;
175
176             let x_offset = x.0;
177             let y_offset = y.0;
178
179             match (x.1, y.1) {
180                 (Text(x), Text(y)) => {
181                     let mut x = x.into_owned();
182                     x.push_str(&y);
183                     Ok((x_offset, Text(x.into())))
184                 },
185                 (x, y) => Err(((x_offset, x), (y_offset, y))),
186             }
187         });
188         check_doc(cx, valid_idents, parser, &spans);
189     }
190 }
191
192 fn check_doc<'a, Events: Iterator<Item = (usize, pulldown_cmark::Event<'a>)>>(
193     cx: &EarlyContext,
194     valid_idents: &[String],
195     docs: Events,
196     spans: &[(usize, Span)],
197 ) {
198     use pulldown_cmark::Event::*;
199     use pulldown_cmark::Tag::*;
200
201     let mut in_code = false;
202
203     for (offset, event) in docs {
204         match event {
205             Start(CodeBlock(_)) |
206             Start(Code) => in_code = true,
207             End(CodeBlock(_)) |
208             End(Code) => in_code = false,
209             Start(_tag) | End(_tag) => (), // We don't care about other tags
210             Html(_html) |
211             InlineHtml(_html) => (), // HTML is weird, just ignore it
212             SoftBreak => (),
213             HardBreak => (),
214             FootnoteReference(text) |
215             Text(text) => {
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 begining 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 has_underscore(word) || word.contains("::") || is_camel_case(word) {
282         span_lint(
283             cx,
284             DOC_MARKDOWN,
285             span,
286             &format!("you should put `{}` between ticks in the documentation", word),
287         );
288     }
289 }