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