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