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