]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/doc.rs
8977ea437d141c3d78c5c3270172b31eaf044f38
[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                     (doc.len(), span.with_lo(span.lo() + BytePos(prefix.len() as u32))),
98                 ],
99             );
100         }
101     }
102
103     if comment.starts_with("/*") {
104         let doc = &comment[3..comment.len() - 2];
105         let mut sizes = vec![];
106         let mut contains_initial_stars = false;
107         for line in doc.lines() {
108             let offset = line.as_ptr() as usize - comment.as_ptr() as usize;
109             debug_assert_eq!(offset as u32 as usize, offset);
110             contains_initial_stars |= line.trim_left().starts_with('*');
111             // +1 for the newline
112             sizes.push((line.len() + 1, span.with_lo(span.lo() + BytePos(offset as u32))));
113         }
114         if !contains_initial_stars {
115             return (doc.to_string(), sizes);
116         }
117         // remove the initial '*'s if any
118         let mut no_stars = String::with_capacity(doc.len());
119         for line in doc.lines() {
120             let mut chars = line.chars();
121             while let Some(c) = chars.next() {
122                 if c.is_whitespace() {
123                     no_stars.push(c);
124                 } else {
125                     no_stars.push(if c == '*' { ' ' } else { c });
126                     break;
127                 }
128             }
129             no_stars.push_str(chars.as_str());
130             no_stars.push('\n');
131         }
132         return (no_stars, sizes);
133     }
134
135     panic!("not a doc-comment: {}", comment);
136 }
137
138 pub fn check_attrs<'a>(cx: &EarlyContext, valid_idents: &[String], attrs: &'a [ast::Attribute]) {
139     let mut doc = String::new();
140     let mut spans = vec![];
141
142     for attr in attrs {
143         if attr.is_sugared_doc {
144             if let Some(ref current) = attr.value_str() {
145                 let current = current.to_string();
146                 let (current, current_spans) = strip_doc_comment_decoration(&current, attr.span);
147                 spans.extend_from_slice(&current_spans);
148                 doc.push_str(&current);
149             }
150         } else if let Some(name) = attr.name() {
151             // ignore mix of sugared and non-sugared doc
152             if name == "doc" {
153                 return;
154             }
155         }
156     }
157
158     let mut current = 0;
159     for &mut (ref mut offset, _) in &mut spans {
160         let offset_copy = *offset;
161         *offset = current;
162         current += offset_copy;
163     }
164
165     if !doc.is_empty() {
166         let parser = Parser::new(pulldown_cmark::Parser::new(&doc));
167         let parser = parser.coalesce(|x, y| {
168             use pulldown_cmark::Event::*;
169
170             let x_offset = x.0;
171             let y_offset = y.0;
172
173             match (x.1, y.1) {
174                 (Text(x), Text(y)) => {
175                     let mut x = x.into_owned();
176                     x.push_str(&y);
177                     Ok((x_offset, Text(x.into())))
178                 },
179                 (x, y) => Err(((x_offset, x), (y_offset, y))),
180             }
181         });
182         check_doc(cx, valid_idents, parser, &spans);
183     }
184 }
185
186 fn check_doc<'a, Events: Iterator<Item = (usize, pulldown_cmark::Event<'a>)>>(
187     cx: &EarlyContext,
188     valid_idents: &[String],
189     docs: Events,
190     spans: &[(usize, Span)],
191 ) {
192     use pulldown_cmark::Event::*;
193     use pulldown_cmark::Tag::*;
194
195     let mut in_code = false;
196
197     for (offset, event) in docs {
198         match event {
199             Start(CodeBlock(_)) |
200             Start(Code) => in_code = true,
201             End(CodeBlock(_)) |
202             End(Code) => in_code = false,
203             Start(_tag) | End(_tag) => (), // We don't care about other tags
204             Html(_html) |
205             InlineHtml(_html) => (), // HTML is weird, just ignore it
206             SoftBreak => (),
207             HardBreak => (),
208             FootnoteReference(text) |
209             Text(text) => {
210                 if !in_code {
211                     let index = match spans.binary_search_by(|c| c.0.cmp(&offset)) {
212                         Ok(o) => o,
213                         Err(e) => e - 1,
214                     };
215
216                     let (begin, span) = spans[index];
217
218                     // Adjust for the begining of the current `Event`
219                     let span = span.with_lo(span.lo() + BytePos::from_usize(offset - begin));
220
221                     check_text(cx, valid_idents, &text, span);
222                 }
223             },
224         }
225     }
226 }
227
228 fn check_text(cx: &EarlyContext, valid_idents: &[String], text: &str, span: Span) {
229     for word in text.split_whitespace() {
230         // Trim punctuation as in `some comment (see foo::bar).`
231         //                                                   ^^
232         // Or even as in `_foo bar_` which is emphasized.
233         let word = word.trim_matches(|c: char| !c.is_alphanumeric());
234
235         if valid_idents.iter().any(|i| i == word) {
236             continue;
237         }
238
239         // Adjust for the current word
240         let offset = word.as_ptr() as usize - text.as_ptr() as usize;
241         let span = Span::new(
242             span.lo() + BytePos::from_usize(offset),
243             span.lo() + BytePos::from_usize(offset + word.len()),
244             span.ctxt(),
245         );
246
247         check_word(cx, word, span);
248     }
249 }
250
251 fn check_word(cx: &EarlyContext, word: &str, span: Span) {
252     /// Checks if a string is camel-case, ie. contains at least two uppercase
253     /// letter (`Clippy` is
254     /// ok) and one lower-case letter (`NASA` is ok). Plural are also excluded
255     /// (`IDs` is ok).
256     fn is_camel_case(s: &str) -> bool {
257         if s.starts_with(|c: char| c.is_digit(10)) {
258             return false;
259         }
260
261         let s = if s.ends_with('s') {
262             &s[..s.len() - 1]
263         } else {
264             s
265         };
266
267         s.chars().all(char::is_alphanumeric) && s.chars().filter(|&c| c.is_uppercase()).take(2).count() > 1 &&
268             s.chars().filter(|&c| c.is_lowercase()).take(1).count() > 0
269     }
270
271     fn has_underscore(s: &str) -> bool {
272         s != "_" && !s.contains("\\_") && s.contains('_')
273     }
274
275     if has_underscore(word) || word.contains("::") || is_camel_case(word) {
276         span_lint(
277             cx,
278             DOC_MARKDOWN,
279             span,
280             &format!("you should put `{}` between ticks in the documentation", word),
281         );
282     }
283 }