]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/doc.rs
Auto merge of #5034 - ThibsG:MatchWildErrArmImprove5024, 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(_, _, _, _, ref trait_ref, ..) => {
163                 self.in_trait_impl = trait_ref.is_some();
164             },
165             _ => {},
166         }
167     }
168
169     fn check_item_post(&mut self, _cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item<'_>) {
170         if let hir::ItemKind::Impl(..) = item.kind {
171             self.in_trait_impl = false;
172         }
173     }
174
175     fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::TraitItem<'_>) {
176         let headers = check_attrs(cx, &self.valid_idents, &item.attrs);
177         if let hir::TraitItemKind::Method(ref sig, ..) = item.kind {
178             if !in_external_macro(cx.tcx.sess, item.span) {
179                 lint_for_missing_headers(cx, item.hir_id, item.span, sig, headers);
180             }
181         }
182     }
183
184     fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::ImplItem<'_>) {
185         let headers = check_attrs(cx, &self.valid_idents, &item.attrs);
186         if self.in_trait_impl || in_external_macro(cx.tcx.sess, item.span) {
187             return;
188         }
189         if let hir::ImplItemKind::Method(ref sig, ..) = item.kind {
190             lint_for_missing_headers(cx, item.hir_id, item.span, sig, headers);
191         }
192     }
193 }
194
195 fn lint_for_missing_headers<'a, 'tcx>(
196     cx: &LateContext<'a, 'tcx>,
197     hir_id: hir::HirId,
198     span: impl Into<MultiSpan> + Copy,
199     sig: &hir::FnSig<'_>,
200     headers: DocHeaders,
201 ) {
202     if !cx.access_levels.is_exported(hir_id) {
203         return; // Private functions do not require doc comments
204     }
205     if !headers.safety && sig.header.unsafety == hir::Unsafety::Unsafe {
206         span_lint(
207             cx,
208             MISSING_SAFETY_DOC,
209             span,
210             "unsafe function's docs miss `# Safety` section",
211         );
212     }
213     if !headers.errors && match_type(cx, return_ty(cx, hir_id), &paths::RESULT) {
214         span_lint(
215             cx,
216             MISSING_ERRORS_DOC,
217             span,
218             "docs for function returning `Result` missing `# Errors` section",
219         );
220     }
221 }
222
223 /// Cleanup documentation decoration (`///` and such).
224 ///
225 /// We can't use `syntax::attr::AttributeMethods::with_desugared_doc` or
226 /// `syntax::parse::lexer::comments::strip_doc_comment_decoration` because we
227 /// need to keep track of
228 /// the spans but this function is inspired from the later.
229 #[allow(clippy::cast_possible_truncation)]
230 #[must_use]
231 pub fn strip_doc_comment_decoration(comment: &str, span: Span) -> (String, Vec<(usize, Span)>) {
232     // one-line comments lose their prefix
233     const ONELINERS: &[&str] = &["///!", "///", "//!", "//"];
234     for prefix in ONELINERS {
235         if comment.starts_with(*prefix) {
236             let doc = &comment[prefix.len()..];
237             let mut doc = doc.to_owned();
238             doc.push('\n');
239             return (
240                 doc.to_owned(),
241                 vec![(doc.len(), span.with_lo(span.lo() + BytePos(prefix.len() as u32)))],
242             );
243         }
244     }
245
246     if comment.starts_with("/*") {
247         let doc = &comment[3..comment.len() - 2];
248         let mut sizes = vec![];
249         let mut contains_initial_stars = false;
250         for line in doc.lines() {
251             let offset = line.as_ptr() as usize - comment.as_ptr() as usize;
252             debug_assert_eq!(offset as u32 as usize, offset);
253             contains_initial_stars |= line.trim_start().starts_with('*');
254             // +1 for the newline
255             sizes.push((line.len() + 1, span.with_lo(span.lo() + BytePos(offset as u32))));
256         }
257         if !contains_initial_stars {
258             return (doc.to_string(), sizes);
259         }
260         // remove the initial '*'s if any
261         let mut no_stars = String::with_capacity(doc.len());
262         for line in doc.lines() {
263             let mut chars = line.chars();
264             while let Some(c) = chars.next() {
265                 if c.is_whitespace() {
266                     no_stars.push(c);
267                 } else {
268                     no_stars.push(if c == '*' { ' ' } else { c });
269                     break;
270                 }
271             }
272             no_stars.push_str(chars.as_str());
273             no_stars.push('\n');
274         }
275         return (no_stars, sizes);
276     }
277
278     panic!("not a doc-comment: {}", comment);
279 }
280
281 #[derive(Copy, Clone)]
282 struct DocHeaders {
283     safety: bool,
284     errors: bool,
285 }
286
287 fn check_attrs<'a>(cx: &LateContext<'_, '_>, valid_idents: &FxHashSet<String>, attrs: &'a [Attribute]) -> DocHeaders {
288     let mut doc = String::new();
289     let mut spans = vec![];
290
291     for attr in attrs {
292         if let AttrKind::DocComment(ref comment) = attr.kind {
293             let comment = comment.to_string();
294             let (comment, current_spans) = strip_doc_comment_decoration(&comment, attr.span);
295             spans.extend_from_slice(&current_spans);
296             doc.push_str(&comment);
297         } else if attr.check_name(sym!(doc)) {
298             // ignore mix of sugared and non-sugared doc
299             // don't trigger the safety or errors check
300             return DocHeaders {
301                 safety: true,
302                 errors: true,
303             };
304         }
305     }
306
307     let mut current = 0;
308     for &mut (ref mut offset, _) in &mut spans {
309         let offset_copy = *offset;
310         *offset = current;
311         current += offset_copy;
312     }
313
314     if doc.is_empty() {
315         return DocHeaders {
316             safety: false,
317             errors: false,
318         };
319     }
320
321     let parser = pulldown_cmark::Parser::new(&doc).into_offset_iter();
322     // Iterate over all `Events` and combine consecutive events into one
323     let events = parser.coalesce(|previous, current| {
324         use pulldown_cmark::Event::*;
325
326         let previous_range = previous.1;
327         let current_range = current.1;
328
329         match (previous.0, current.0) {
330             (Text(previous), Text(current)) => {
331                 let mut previous = previous.to_string();
332                 previous.push_str(&current);
333                 Ok((Text(previous.into()), previous_range))
334             },
335             (previous, current) => Err(((previous, previous_range), (current, current_range))),
336         }
337     });
338     check_doc(cx, valid_idents, events, &spans)
339 }
340
341 fn check_doc<'a, Events: Iterator<Item = (pulldown_cmark::Event<'a>, Range<usize>)>>(
342     cx: &LateContext<'_, '_>,
343     valid_idents: &FxHashSet<String>,
344     events: Events,
345     spans: &[(usize, Span)],
346 ) -> DocHeaders {
347     // true if a safety header was found
348     use pulldown_cmark::Event::*;
349     use pulldown_cmark::Tag::*;
350
351     let mut headers = DocHeaders {
352         safety: false,
353         errors: false,
354     };
355     let mut in_code = false;
356     let mut in_link = None;
357     let mut in_heading = false;
358
359     for (event, range) in events {
360         match event {
361             Start(CodeBlock(_)) => in_code = true,
362             End(CodeBlock(_)) => in_code = false,
363             Start(Link(_, url, _)) => in_link = Some(url),
364             End(Link(..)) => in_link = None,
365             Start(Heading(_)) => in_heading = true,
366             End(Heading(_)) => in_heading = false,
367             Start(_tag) | End(_tag) => (), // We don't care about other tags
368             Html(_html) => (),             // HTML is weird, just ignore it
369             SoftBreak | HardBreak | TaskListMarker(_) | Code(_) | Rule => (),
370             FootnoteReference(text) | Text(text) => {
371                 if Some(&text) == in_link.as_ref() {
372                     // Probably a link of the form `<http://example.com>`
373                     // Which are represented as a link to "http://example.com" with
374                     // text "http://example.com" by pulldown-cmark
375                     continue;
376                 }
377                 headers.safety |= in_heading && text.trim() == "Safety";
378                 headers.errors |= in_heading && text.trim() == "Errors";
379                 let index = match spans.binary_search_by(|c| c.0.cmp(&range.start)) {
380                     Ok(o) => o,
381                     Err(e) => e - 1,
382                 };
383                 let (begin, span) = spans[index];
384                 if in_code {
385                     check_code(cx, &text, span);
386                 } else {
387                     // Adjust for the beginning of the current `Event`
388                     let span = span.with_lo(span.lo() + BytePos::from_usize(range.start - begin));
389
390                     check_text(cx, valid_idents, &text, span);
391                 }
392             },
393         }
394     }
395     headers
396 }
397
398 static LEAVE_MAIN_PATTERNS: &[&str] = &["static", "fn main() {}", "extern crate"];
399
400 fn check_code(cx: &LateContext<'_, '_>, text: &str, span: Span) {
401     if text.contains("fn main() {") && !LEAVE_MAIN_PATTERNS.iter().any(|p| text.contains(p)) {
402         span_lint(cx, NEEDLESS_DOCTEST_MAIN, span, "needless `fn main` in doctest");
403     }
404 }
405
406 fn check_text(cx: &LateContext<'_, '_>, valid_idents: &FxHashSet<String>, text: &str, span: Span) {
407     for word in text.split(|c: char| c.is_whitespace() || c == '\'') {
408         // Trim punctuation as in `some comment (see foo::bar).`
409         //                                                   ^^
410         // Or even as in `_foo bar_` which is emphasized.
411         let word = word.trim_matches(|c: char| !c.is_alphanumeric());
412
413         if valid_idents.contains(word) {
414             continue;
415         }
416
417         // Adjust for the current word
418         let offset = word.as_ptr() as usize - text.as_ptr() as usize;
419         let span = Span::new(
420             span.lo() + BytePos::from_usize(offset),
421             span.lo() + BytePos::from_usize(offset + word.len()),
422             span.ctxt(),
423         );
424
425         check_word(cx, word, span);
426     }
427 }
428
429 fn check_word(cx: &LateContext<'_, '_>, word: &str, span: Span) {
430     /// Checks if a string is camel-case, i.e., contains at least two uppercase
431     /// letters (`Clippy` is ok) and one lower-case letter (`NASA` is ok).
432     /// Plurals are also excluded (`IDs` is ok).
433     fn is_camel_case(s: &str) -> bool {
434         if s.starts_with(|c: char| c.is_digit(10)) {
435             return false;
436         }
437
438         let s = if s.ends_with('s') { &s[..s.len() - 1] } else { s };
439
440         s.chars().all(char::is_alphanumeric)
441             && s.chars().filter(|&c| c.is_uppercase()).take(2).count() > 1
442             && s.chars().filter(|&c| c.is_lowercase()).take(1).count() > 0
443     }
444
445     fn has_underscore(s: &str) -> bool {
446         s != "_" && !s.contains("\\_") && s.contains('_')
447     }
448
449     fn has_hyphen(s: &str) -> bool {
450         s != "-" && s.contains('-')
451     }
452
453     if let Ok(url) = Url::parse(word) {
454         // try to get around the fact that `foo::bar` parses as a valid URL
455         if !url.cannot_be_a_base() {
456             span_lint(
457                 cx,
458                 DOC_MARKDOWN,
459                 span,
460                 "you should put bare URLs between `<`/`>` or make a proper Markdown link",
461             );
462
463             return;
464         }
465     }
466
467     // We assume that mixed-case words are not meant to be put inside bacticks. (Issue #2343)
468     if has_underscore(word) && has_hyphen(word) {
469         return;
470     }
471
472     if has_underscore(word) || word.contains("::") || is_camel_case(word) {
473         span_lint(
474             cx,
475             DOC_MARKDOWN,
476             span,
477             &format!("you should put `{}` between ticks in the documentation", word),
478         );
479     }
480 }