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