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