]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/doc.rs
Auto merge of #4809 - iankronquist:patch-1, r=flip1995
[rust.git] / clippy_lints / src / doc.rs
1 use crate::utils::{is_entrypoint_fn, match_type, paths, return_ty, span_lint};
2 use itertools::Itertools;
3 use rustc::lint::in_external_macro;
4 use rustc_data_structures::fx::FxHashSet;
5 use rustc_hir as hir;
6 use rustc_lint::{LateContext, LateLintPass};
7 use rustc_session::{declare_tool_lint, impl_lint_pass};
8 use rustc_span::source_map::{BytePos, MultiSpan, Span};
9 use rustc_span::Pos;
10 use std::ops::Range;
11 use syntax::ast::{AttrKind, Attribute};
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: usize) {}
32     /// ```
33     pub DOC_MARKDOWN,
34     pedantic,
35     "presence of `_`, `::` or camel-case outside backticks in documentation"
36 }
37
38 declare_clippy_lint! {
39     /// **What it does:** Checks for the doc comments of publicly visible
40     /// unsafe functions and warns if there is no `# Safety` section.
41     ///
42     /// **Why is this bad?** Unsafe functions should document their safety
43     /// preconditions, so that users can be sure they are using them safely.
44     ///
45     /// **Known problems:** None.
46     ///
47     /// **Examples:**
48     /// ```rust
49     ///# type Universe = ();
50     /// /// This function should really be documented
51     /// pub unsafe fn start_apocalypse(u: &mut Universe) {
52     ///     unimplemented!();
53     /// }
54     /// ```
55     ///
56     /// At least write a line about safety:
57     ///
58     /// ```rust
59     ///# type Universe = ();
60     /// /// # Safety
61     /// ///
62     /// /// This function should not be called before the horsemen are ready.
63     /// pub unsafe fn start_apocalypse(u: &mut Universe) {
64     ///     unimplemented!();
65     /// }
66     /// ```
67     pub MISSING_SAFETY_DOC,
68     style,
69     "`pub unsafe fn` without `# Safety` docs"
70 }
71
72 declare_clippy_lint! {
73     /// **What it does:** Checks the doc comments of publicly visible functions that
74     /// return a `Result` type and warns if there is no `# Errors` section.
75     ///
76     /// **Why is this bad?** Documenting the type of errors that can be returned from a
77     /// function can help callers write code to handle the errors appropriately.
78     ///
79     /// **Known problems:** None.
80     ///
81     /// **Examples:**
82     ///
83     /// Since the following function returns a `Result` it has an `# Errors` section in
84     /// its doc comment:
85     ///
86     /// ```rust
87     ///# use std::io;
88     /// /// # Errors
89     /// ///
90     /// /// Will return `Err` if `filename` does not exist or the user does not have
91     /// /// permission to read it.
92     /// pub fn read(filename: String) -> io::Result<String> {
93     ///     unimplemented!();
94     /// }
95     /// ```
96     pub MISSING_ERRORS_DOC,
97     pedantic,
98     "`pub fn` returns `Result` without `# Errors` in doc comment"
99 }
100
101 declare_clippy_lint! {
102     /// **What it does:** Checks for `fn main() { .. }` in doctests
103     ///
104     /// **Why is this bad?** The test can be shorter (and likely more readable)
105     /// if the `fn main()` is left implicit.
106     ///
107     /// **Known problems:** None.
108     ///
109     /// **Examples:**
110     /// ``````rust
111     /// /// An example of a doctest with a `main()` function
112     /// ///
113     /// /// # Examples
114     /// ///
115     /// /// ```
116     /// /// fn main() {
117     /// ///     // this needs not be in an `fn`
118     /// /// }
119     /// /// ```
120     /// fn needless_main() {
121     ///     unimplemented!();
122     /// }
123     /// ``````
124     pub NEEDLESS_DOCTEST_MAIN,
125     style,
126     "presence of `fn main() {` in code examples"
127 }
128
129 #[allow(clippy::module_name_repetitions)]
130 #[derive(Clone)]
131 pub struct DocMarkdown {
132     valid_idents: FxHashSet<String>,
133     in_trait_impl: bool,
134 }
135
136 impl DocMarkdown {
137     pub fn new(valid_idents: FxHashSet<String>) -> Self {
138         Self {
139             valid_idents,
140             in_trait_impl: false,
141         }
142     }
143 }
144
145 impl_lint_pass!(DocMarkdown => [DOC_MARKDOWN, MISSING_SAFETY_DOC, MISSING_ERRORS_DOC, NEEDLESS_DOCTEST_MAIN]);
146
147 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for DocMarkdown {
148     fn check_crate(&mut self, cx: &LateContext<'a, 'tcx>, krate: &'tcx hir::Crate<'_>) {
149         check_attrs(cx, &self.valid_idents, &krate.attrs);
150     }
151
152     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item<'_>) {
153         let headers = check_attrs(cx, &self.valid_idents, &item.attrs);
154         match item.kind {
155             hir::ItemKind::Fn(ref sig, ..) => {
156                 if !(is_entrypoint_fn(cx, cx.tcx.hir().local_def_id(item.hir_id))
157                     || in_external_macro(cx.tcx.sess, item.span))
158                 {
159                     lint_for_missing_headers(cx, item.hir_id, item.span, sig, headers);
160                 }
161             },
162             hir::ItemKind::Impl {
163                 of_trait: ref trait_ref,
164                 ..
165             } => {
166                 self.in_trait_impl = trait_ref.is_some();
167             },
168             _ => {},
169         }
170     }
171
172     fn check_item_post(&mut self, _cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item<'_>) {
173         if let hir::ItemKind::Impl { .. } = item.kind {
174             self.in_trait_impl = false;
175         }
176     }
177
178     fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::TraitItem<'_>) {
179         let headers = check_attrs(cx, &self.valid_idents, &item.attrs);
180         if let hir::TraitItemKind::Method(ref sig, ..) = item.kind {
181             if !in_external_macro(cx.tcx.sess, item.span) {
182                 lint_for_missing_headers(cx, item.hir_id, item.span, sig, headers);
183             }
184         }
185     }
186
187     fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::ImplItem<'_>) {
188         let headers = check_attrs(cx, &self.valid_idents, &item.attrs);
189         if self.in_trait_impl || in_external_macro(cx.tcx.sess, item.span) {
190             return;
191         }
192         if let hir::ImplItemKind::Method(ref sig, ..) = item.kind {
193             lint_for_missing_headers(cx, item.hir_id, item.span, sig, headers);
194         }
195     }
196 }
197
198 fn lint_for_missing_headers<'a, 'tcx>(
199     cx: &LateContext<'a, 'tcx>,
200     hir_id: hir::HirId,
201     span: impl Into<MultiSpan> + Copy,
202     sig: &hir::FnSig<'_>,
203     headers: DocHeaders,
204 ) {
205     if !cx.access_levels.is_exported(hir_id) {
206         return; // Private functions do not require doc comments
207     }
208     if !headers.safety && sig.header.unsafety == hir::Unsafety::Unsafe {
209         span_lint(
210             cx,
211             MISSING_SAFETY_DOC,
212             span,
213             "unsafe function's docs miss `# Safety` section",
214         );
215     }
216     if !headers.errors && match_type(cx, return_ty(cx, hir_id), &paths::RESULT) {
217         span_lint(
218             cx,
219             MISSING_ERRORS_DOC,
220             span,
221             "docs for function returning `Result` missing `# Errors` section",
222         );
223     }
224 }
225
226 /// Cleanup documentation decoration (`///` and such).
227 ///
228 /// We can't use `syntax::attr::AttributeMethods::with_desugared_doc` or
229 /// `syntax::parse::lexer::comments::strip_doc_comment_decoration` because we
230 /// need to keep track of
231 /// the spans but this function is inspired from the later.
232 #[allow(clippy::cast_possible_truncation)]
233 #[must_use]
234 pub fn strip_doc_comment_decoration(comment: &str, span: Span) -> (String, Vec<(usize, Span)>) {
235     // one-line comments lose their prefix
236     const ONELINERS: &[&str] = &["///!", "///", "//!", "//"];
237     for prefix in ONELINERS {
238         if comment.starts_with(*prefix) {
239             let doc = &comment[prefix.len()..];
240             let mut doc = doc.to_owned();
241             doc.push('\n');
242             return (
243                 doc.to_owned(),
244                 vec![(doc.len(), span.with_lo(span.lo() + BytePos(prefix.len() as u32)))],
245             );
246         }
247     }
248
249     if comment.starts_with("/*") {
250         let doc = &comment[3..comment.len() - 2];
251         let mut sizes = vec![];
252         let mut contains_initial_stars = false;
253         for line in doc.lines() {
254             let offset = line.as_ptr() as usize - comment.as_ptr() as usize;
255             debug_assert_eq!(offset as u32 as usize, offset);
256             contains_initial_stars |= line.trim_start().starts_with('*');
257             // +1 for the newline
258             sizes.push((line.len() + 1, span.with_lo(span.lo() + BytePos(offset as u32))));
259         }
260         if !contains_initial_stars {
261             return (doc.to_string(), sizes);
262         }
263         // remove the initial '*'s if any
264         let mut no_stars = String::with_capacity(doc.len());
265         for line in doc.lines() {
266             let mut chars = line.chars();
267             while let Some(c) = chars.next() {
268                 if c.is_whitespace() {
269                     no_stars.push(c);
270                 } else {
271                     no_stars.push(if c == '*' { ' ' } else { c });
272                     break;
273                 }
274             }
275             no_stars.push_str(chars.as_str());
276             no_stars.push('\n');
277         }
278         return (no_stars, sizes);
279     }
280
281     panic!("not a doc-comment: {}", comment);
282 }
283
284 #[derive(Copy, Clone)]
285 struct DocHeaders {
286     safety: bool,
287     errors: bool,
288 }
289
290 fn check_attrs<'a>(cx: &LateContext<'_, '_>, valid_idents: &FxHashSet<String>, attrs: &'a [Attribute]) -> DocHeaders {
291     let mut doc = String::new();
292     let mut spans = vec![];
293
294     for attr in attrs {
295         if let AttrKind::DocComment(ref comment) = attr.kind {
296             let comment = comment.to_string();
297             let (comment, current_spans) = strip_doc_comment_decoration(&comment, attr.span);
298             spans.extend_from_slice(&current_spans);
299             doc.push_str(&comment);
300         } else if attr.check_name(sym!(doc)) {
301             // ignore mix of sugared and non-sugared doc
302             // don't trigger the safety or errors check
303             return DocHeaders {
304                 safety: true,
305                 errors: true,
306             };
307         }
308     }
309
310     let mut current = 0;
311     for &mut (ref mut offset, _) in &mut spans {
312         let offset_copy = *offset;
313         *offset = current;
314         current += offset_copy;
315     }
316
317     if doc.is_empty() {
318         return DocHeaders {
319             safety: false,
320             errors: false,
321         };
322     }
323
324     let parser = pulldown_cmark::Parser::new(&doc).into_offset_iter();
325     // Iterate over all `Events` and combine consecutive events into one
326     let events = parser.coalesce(|previous, current| {
327         use pulldown_cmark::Event::*;
328
329         let previous_range = previous.1;
330         let current_range = current.1;
331
332         match (previous.0, current.0) {
333             (Text(previous), Text(current)) => {
334                 let mut previous = previous.to_string();
335                 previous.push_str(&current);
336                 Ok((Text(previous.into()), previous_range))
337             },
338             (previous, current) => Err(((previous, previous_range), (current, current_range))),
339         }
340     });
341     check_doc(cx, valid_idents, events, &spans)
342 }
343
344 fn check_doc<'a, Events: Iterator<Item = (pulldown_cmark::Event<'a>, Range<usize>)>>(
345     cx: &LateContext<'_, '_>,
346     valid_idents: &FxHashSet<String>,
347     events: Events,
348     spans: &[(usize, Span)],
349 ) -> DocHeaders {
350     // true if a safety header was found
351     use pulldown_cmark::Event::*;
352     use pulldown_cmark::Tag::*;
353
354     let mut headers = DocHeaders {
355         safety: false,
356         errors: false,
357     };
358     let mut in_code = false;
359     let mut in_link = None;
360     let mut in_heading = false;
361
362     for (event, range) in events {
363         match event {
364             Start(CodeBlock(_)) => in_code = true,
365             End(CodeBlock(_)) => in_code = false,
366             Start(Link(_, url, _)) => in_link = Some(url),
367             End(Link(..)) => in_link = None,
368             Start(Heading(_)) => in_heading = true,
369             End(Heading(_)) => in_heading = false,
370             Start(_tag) | End(_tag) => (), // We don't care about other tags
371             Html(_html) => (),             // HTML is weird, just ignore it
372             SoftBreak | HardBreak | TaskListMarker(_) | Code(_) | Rule => (),
373             FootnoteReference(text) | Text(text) => {
374                 if Some(&text) == in_link.as_ref() {
375                     // Probably a link of the form `<http://example.com>`
376                     // Which are represented as a link to "http://example.com" with
377                     // text "http://example.com" by pulldown-cmark
378                     continue;
379                 }
380                 headers.safety |= in_heading && text.trim() == "Safety";
381                 headers.errors |= in_heading && text.trim() == "Errors";
382                 let index = match spans.binary_search_by(|c| c.0.cmp(&range.start)) {
383                     Ok(o) => o,
384                     Err(e) => e - 1,
385                 };
386                 let (begin, span) = spans[index];
387                 if in_code {
388                     check_code(cx, &text, span);
389                 } else {
390                     // Adjust for the beginning of the current `Event`
391                     let span = span.with_lo(span.lo() + BytePos::from_usize(range.start - begin));
392
393                     check_text(cx, valid_idents, &text, span);
394                 }
395             },
396         }
397     }
398     headers
399 }
400
401 static LEAVE_MAIN_PATTERNS: &[&str] = &["static", "fn main() {}", "extern crate"];
402
403 fn check_code(cx: &LateContext<'_, '_>, text: &str, span: Span) {
404     if text.contains("fn main() {") && !LEAVE_MAIN_PATTERNS.iter().any(|p| text.contains(p)) {
405         span_lint(cx, NEEDLESS_DOCTEST_MAIN, span, "needless `fn main` in doctest");
406     }
407 }
408
409 fn check_text(cx: &LateContext<'_, '_>, valid_idents: &FxHashSet<String>, text: &str, span: Span) {
410     for word in text.split(|c: char| c.is_whitespace() || c == '\'') {
411         // Trim punctuation as in `some comment (see foo::bar).`
412         //                                                   ^^
413         // Or even as in `_foo bar_` which is emphasized.
414         let word = word.trim_matches(|c: char| !c.is_alphanumeric());
415
416         if valid_idents.contains(word) {
417             continue;
418         }
419
420         // Adjust for the current word
421         let offset = word.as_ptr() as usize - text.as_ptr() as usize;
422         let span = Span::new(
423             span.lo() + BytePos::from_usize(offset),
424             span.lo() + BytePos::from_usize(offset + word.len()),
425             span.ctxt(),
426         );
427
428         check_word(cx, word, span);
429     }
430 }
431
432 fn check_word(cx: &LateContext<'_, '_>, word: &str, span: Span) {
433     /// Checks if a string is camel-case, i.e., contains at least two uppercase
434     /// letters (`Clippy` is ok) and one lower-case letter (`NASA` is ok).
435     /// Plurals are also excluded (`IDs` is ok).
436     fn is_camel_case(s: &str) -> bool {
437         if s.starts_with(|c: char| c.is_digit(10)) {
438             return false;
439         }
440
441         let s = if s.ends_with('s') { &s[..s.len() - 1] } else { s };
442
443         s.chars().all(char::is_alphanumeric)
444             && s.chars().filter(|&c| c.is_uppercase()).take(2).count() > 1
445             && s.chars().filter(|&c| c.is_lowercase()).take(1).count() > 0
446     }
447
448     fn has_underscore(s: &str) -> bool {
449         s != "_" && !s.contains("\\_") && s.contains('_')
450     }
451
452     fn has_hyphen(s: &str) -> bool {
453         s != "-" && s.contains('-')
454     }
455
456     if let Ok(url) = Url::parse(word) {
457         // try to get around the fact that `foo::bar` parses as a valid URL
458         if !url.cannot_be_a_base() {
459             span_lint(
460                 cx,
461                 DOC_MARKDOWN,
462                 span,
463                 "you should put bare URLs between `<`/`>` or make a proper Markdown link",
464             );
465
466             return;
467         }
468     }
469
470     // We assume that mixed-case words are not meant to be put inside bacticks. (Issue #2343)
471     if has_underscore(word) && has_hyphen(word) {
472         return;
473     }
474
475     if has_underscore(word) || word.contains("::") || is_camel_case(word) {
476         span_lint(
477             cx,
478             DOC_MARKDOWN,
479             span,
480             &format!("you should put `{}` between ticks in the documentation", word),
481         );
482     }
483 }