]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/doc.rs
Auto merge of #4591 - flip1995:rustup, r=flip1995
[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 declare_clippy_lint! {
38     /// **What it does:** Checks for the doc comments of publicly visible
39     /// unsafe functions and warns if there is no `# Safety` section.
40     ///
41     /// **Why is this bad?** Unsafe functions should document their safety
42     /// preconditions, so that users can be sure they are using them safely.
43     ///
44     /// **Known problems:** None.
45     ///
46     /// **Examples**:
47     /// ```rust
48     ///# type Universe = ();
49     /// /// This function should really be documented
50     /// pub unsafe fn start_apocalypse(u: &mut Universe) {
51     ///     unimplemented!();
52     /// }
53     /// ```
54     ///
55     /// At least write a line about safety:
56     ///
57     /// ```rust
58     ///# type Universe = ();
59     /// /// # Safety
60     /// ///
61     /// /// This function should not be called before the horsemen are ready.
62     /// pub unsafe fn start_apocalypse(u: &mut Universe) {
63     ///     unimplemented!();
64     /// }
65     /// ```
66     pub MISSING_SAFETY_DOC,
67     style,
68     "`pub unsafe fn` without `# Safety` docs"
69 }
70
71 #[allow(clippy::module_name_repetitions)]
72 #[derive(Clone)]
73 pub struct DocMarkdown {
74     valid_idents: FxHashSet<String>,
75 }
76
77 impl DocMarkdown {
78     pub fn new(valid_idents: FxHashSet<String>) -> Self {
79         Self { valid_idents }
80     }
81 }
82
83 impl_lint_pass!(DocMarkdown => [DOC_MARKDOWN, MISSING_SAFETY_DOC]);
84
85 impl EarlyLintPass for DocMarkdown {
86     fn check_crate(&mut self, cx: &EarlyContext<'_>, krate: &ast::Crate) {
87         check_attrs(cx, &self.valid_idents, &krate.attrs);
88     }
89
90     fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
91         if check_attrs(cx, &self.valid_idents, &item.attrs) {
92             return;
93         }
94         // no safety header
95         if let ast::ItemKind::Fn(_, ref header, ..) = item.kind {
96             if item.vis.node.is_pub() && header.unsafety == ast::Unsafety::Unsafe {
97                 span_lint(
98                     cx,
99                     MISSING_SAFETY_DOC,
100                     item.span,
101                     "unsafe function's docs miss `# Safety` section",
102                 );
103             }
104         }
105     }
106 }
107
108 /// Cleanup documentation decoration (`///` and such).
109 ///
110 /// We can't use `syntax::attr::AttributeMethods::with_desugared_doc` or
111 /// `syntax::parse::lexer::comments::strip_doc_comment_decoration` because we
112 /// need to keep track of
113 /// the spans but this function is inspired from the later.
114 #[allow(clippy::cast_possible_truncation)]
115 pub fn strip_doc_comment_decoration(comment: &str, span: Span) -> (String, Vec<(usize, Span)>) {
116     // one-line comments lose their prefix
117     const ONELINERS: &[&str] = &["///!", "///", "//!", "//"];
118     for prefix in ONELINERS {
119         if comment.starts_with(*prefix) {
120             let doc = &comment[prefix.len()..];
121             let mut doc = doc.to_owned();
122             doc.push('\n');
123             return (
124                 doc.to_owned(),
125                 vec![(doc.len(), span.with_lo(span.lo() + BytePos(prefix.len() as u32)))],
126             );
127         }
128     }
129
130     if comment.starts_with("/*") {
131         let doc = &comment[3..comment.len() - 2];
132         let mut sizes = vec![];
133         let mut contains_initial_stars = false;
134         for line in doc.lines() {
135             let offset = line.as_ptr() as usize - comment.as_ptr() as usize;
136             debug_assert_eq!(offset as u32 as usize, offset);
137             contains_initial_stars |= line.trim_start().starts_with('*');
138             // +1 for the newline
139             sizes.push((line.len() + 1, span.with_lo(span.lo() + BytePos(offset as u32))));
140         }
141         if !contains_initial_stars {
142             return (doc.to_string(), sizes);
143         }
144         // remove the initial '*'s if any
145         let mut no_stars = String::with_capacity(doc.len());
146         for line in doc.lines() {
147             let mut chars = line.chars();
148             while let Some(c) = chars.next() {
149                 if c.is_whitespace() {
150                     no_stars.push(c);
151                 } else {
152                     no_stars.push(if c == '*' { ' ' } else { c });
153                     break;
154                 }
155             }
156             no_stars.push_str(chars.as_str());
157             no_stars.push('\n');
158         }
159         return (no_stars, sizes);
160     }
161
162     panic!("not a doc-comment: {}", comment);
163 }
164
165 pub fn check_attrs<'a>(cx: &EarlyContext<'_>, valid_idents: &FxHashSet<String>, attrs: &'a [ast::Attribute]) -> bool {
166     let mut doc = String::new();
167     let mut spans = vec![];
168
169     for attr in attrs {
170         if attr.is_sugared_doc {
171             if let Some(ref current) = attr.value_str() {
172                 let current = current.to_string();
173                 let (current, current_spans) = strip_doc_comment_decoration(&current, attr.span);
174                 spans.extend_from_slice(&current_spans);
175                 doc.push_str(&current);
176             }
177         } else if attr.check_name(sym!(doc)) {
178             // ignore mix of sugared and non-sugared doc
179             return true; // don't trigger the safety check
180         }
181     }
182
183     let mut current = 0;
184     for &mut (ref mut offset, _) in &mut spans {
185         let offset_copy = *offset;
186         *offset = current;
187         current += offset_copy;
188     }
189
190     if doc.is_empty() {
191         return false;
192     }
193
194     let parser = pulldown_cmark::Parser::new(&doc).into_offset_iter();
195     // Iterate over all `Events` and combine consecutive events into one
196     let events = parser.coalesce(|previous, current| {
197         use pulldown_cmark::Event::*;
198
199         let previous_range = previous.1;
200         let current_range = current.1;
201
202         match (previous.0, current.0) {
203             (Text(previous), Text(current)) => {
204                 let mut previous = previous.to_string();
205                 previous.push_str(&current);
206                 Ok((Text(previous.into()), previous_range))
207             },
208             (previous, current) => Err(((previous, previous_range), (current, current_range))),
209         }
210     });
211     check_doc(cx, valid_idents, events, &spans)
212 }
213
214 fn check_doc<'a, Events: Iterator<Item = (pulldown_cmark::Event<'a>, Range<usize>)>>(
215     cx: &EarlyContext<'_>,
216     valid_idents: &FxHashSet<String>,
217     events: Events,
218     spans: &[(usize, Span)],
219 ) -> bool {
220     // true if a safety header was found
221     use pulldown_cmark::Event::*;
222     use pulldown_cmark::Tag::*;
223
224     let mut safety_header = false;
225     let mut in_code = false;
226     let mut in_link = None;
227     let mut in_heading = false;
228
229     for (event, range) in events {
230         match event {
231             Start(CodeBlock(_)) => in_code = true,
232             End(CodeBlock(_)) => in_code = false,
233             Start(Link(_, url, _)) => in_link = Some(url),
234             End(Link(..)) => in_link = None,
235             Start(Heading(_)) => in_heading = true,
236             End(Heading(_)) => in_heading = false,
237             Start(_tag) | End(_tag) => (), // We don't care about other tags
238             Html(_html) => (),             // HTML is weird, just ignore it
239             SoftBreak | HardBreak | TaskListMarker(_) | Code(_) | Rule => (),
240             FootnoteReference(text) | Text(text) => {
241                 if Some(&text) == in_link.as_ref() {
242                     // Probably a link of the form `<http://example.com>`
243                     // Which are represented as a link to "http://example.com" with
244                     // text "http://example.com" by pulldown-cmark
245                     continue;
246                 }
247                 safety_header |= in_heading && text.trim() == "Safety";
248                 if !in_code {
249                     let index = match spans.binary_search_by(|c| c.0.cmp(&range.start)) {
250                         Ok(o) => o,
251                         Err(e) => e - 1,
252                     };
253
254                     let (begin, span) = spans[index];
255
256                     // Adjust for the beginning of the current `Event`
257                     let span = span.with_lo(span.lo() + BytePos::from_usize(range.start - begin));
258
259                     check_text(cx, valid_idents, &text, span);
260                 }
261             },
262         }
263     }
264     safety_header
265 }
266
267 fn check_text(cx: &EarlyContext<'_>, valid_idents: &FxHashSet<String>, text: &str, span: Span) {
268     for word in text.split(|c: char| c.is_whitespace() || c == '\'') {
269         // Trim punctuation as in `some comment (see foo::bar).`
270         //                                                   ^^
271         // Or even as in `_foo bar_` which is emphasized.
272         let word = word.trim_matches(|c: char| !c.is_alphanumeric());
273
274         if valid_idents.contains(word) {
275             continue;
276         }
277
278         // Adjust for the current word
279         let offset = word.as_ptr() as usize - text.as_ptr() as usize;
280         let span = Span::new(
281             span.lo() + BytePos::from_usize(offset),
282             span.lo() + BytePos::from_usize(offset + word.len()),
283             span.ctxt(),
284         );
285
286         check_word(cx, word, span);
287     }
288 }
289
290 fn check_word(cx: &EarlyContext<'_>, word: &str, span: Span) {
291     /// Checks if a string is camel-case, i.e., contains at least two uppercase
292     /// letters (`Clippy` is ok) and one lower-case letter (`NASA` is ok).
293     /// Plurals are also excluded (`IDs` is ok).
294     fn is_camel_case(s: &str) -> bool {
295         if s.starts_with(|c: char| c.is_digit(10)) {
296             return false;
297         }
298
299         let s = if s.ends_with('s') { &s[..s.len() - 1] } else { s };
300
301         s.chars().all(char::is_alphanumeric)
302             && s.chars().filter(|&c| c.is_uppercase()).take(2).count() > 1
303             && s.chars().filter(|&c| c.is_lowercase()).take(1).count() > 0
304     }
305
306     fn has_underscore(s: &str) -> bool {
307         s != "_" && !s.contains("\\_") && s.contains('_')
308     }
309
310     fn has_hyphen(s: &str) -> bool {
311         s != "-" && s.contains('-')
312     }
313
314     if let Ok(url) = Url::parse(word) {
315         // try to get around the fact that `foo::bar` parses as a valid URL
316         if !url.cannot_be_a_base() {
317             span_lint(
318                 cx,
319                 DOC_MARKDOWN,
320                 span,
321                 "you should put bare URLs between `<`/`>` or make a proper Markdown link",
322             );
323
324             return;
325         }
326     }
327
328     // We assume that mixed-case words are not meant to be put inside bacticks. (Issue #2343)
329     if has_underscore(word) && has_hyphen(word) {
330         return;
331     }
332
333     if has_underscore(word) || word.contains("::") || is_camel_case(word) {
334         span_lint(
335             cx,
336             DOC_MARKDOWN,
337             span,
338             &format!("you should put `{}` between ticks in the documentation", word),
339         );
340     }
341 }