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