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