]> git.lizzy.rs Git - rust.git/blobdiff - clippy_lints/src/doc.rs
rustup https://github.com/rust-lang/rust/pull/67455
[rust.git] / clippy_lints / src / doc.rs
index bd959427403b712235f0db80387592d6ef9b3dfd..8f8d8ad96bbee14a9eb714cc0d05c23fd40efa9e 100644 (file)
@@ -1,12 +1,14 @@
-use crate::utils::span_lint;
+use crate::utils::{match_type, paths, return_ty, span_lint};
 use itertools::Itertools;
 use pulldown_cmark;
-use rustc::lint::{EarlyContext, EarlyLintPass, LintArray, LintPass};
-use rustc::{declare_tool_lint, impl_lint_pass};
+use rustc::hir;
+use rustc::impl_lint_pass;
+use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
 use rustc_data_structures::fx::FxHashSet;
+use rustc_session::declare_tool_lint;
 use std::ops::Range;
-use syntax::ast;
-use syntax::source_map::{BytePos, Span};
+use syntax::ast::{AttrKind, Attribute};
+use syntax::source_map::{BytePos, MultiSpan, Span};
 use syntax_pos::Pos;
 use url::Url;
 
@@ -43,7 +45,7 @@
     ///
     /// **Known problems:** None.
     ///
-    /// **Examples**:
+    /// **Examples:**
     /// ```rust
     ///# type Universe = ();
     /// /// This function should really be documented
     "`pub unsafe fn` without `# Safety` docs"
 }
 
+declare_clippy_lint! {
+    /// **What it does:** Checks the doc comments of publicly visible functions that
+    /// return a `Result` type and warns if there is no `# Errors` section.
+    ///
+    /// **Why is this bad?** Documenting the type of errors that can be returned from a
+    /// function can help callers write code to handle the errors appropriately.
+    ///
+    /// **Known problems:** None.
+    ///
+    /// **Examples:**
+    ///
+    /// Since the following function returns a `Result` it has an `# Errors` section in
+    /// its doc comment:
+    ///
+    /// ```rust
+    ///# use std::io;
+    /// /// # Errors
+    /// ///
+    /// /// Will return `Err` if `filename` does not exist or the user does not have
+    /// /// permission to read it.
+    /// pub fn read(filename: String) -> io::Result<String> {
+    ///     unimplemented!();
+    /// }
+    /// ```
+    pub MISSING_ERRORS_DOC,
+    pedantic,
+    "`pub fn` returns `Result` without `# Errors` in doc comment"
+}
+
 declare_clippy_lint! {
     /// **What it does:** Checks for `fn main() { .. }` in doctests
     ///
 #[derive(Clone)]
 pub struct DocMarkdown {
     valid_idents: FxHashSet<String>,
+    in_trait_impl: bool,
 }
 
 impl DocMarkdown {
     pub fn new(valid_idents: FxHashSet<String>) -> Self {
-        Self { valid_idents }
+        Self {
+            valid_idents,
+            in_trait_impl: false,
+        }
     }
 }
 
-impl_lint_pass!(DocMarkdown => [DOC_MARKDOWN, MISSING_SAFETY_DOC, NEEDLESS_DOCTEST_MAIN]);
+impl_lint_pass!(DocMarkdown => [DOC_MARKDOWN, MISSING_SAFETY_DOC, MISSING_ERRORS_DOC, NEEDLESS_DOCTEST_MAIN]);
 
-impl EarlyLintPass for DocMarkdown {
-    fn check_crate(&mut self, cx: &EarlyContext<'_>, krate: &ast::Crate) {
+impl<'a, 'tcx> LateLintPass<'a, 'tcx> for DocMarkdown {
+    fn check_crate(&mut self, cx: &LateContext<'a, 'tcx>, krate: &'tcx hir::Crate) {
         check_attrs(cx, &self.valid_idents, &krate.attrs);
     }
 
-    fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
-        if check_attrs(cx, &self.valid_idents, &item.attrs) {
+    fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item) {
+        let headers = check_attrs(cx, &self.valid_idents, &item.attrs);
+        match item.kind {
+            hir::ItemKind::Fn(ref sig, ..) => {
+                lint_for_missing_headers(cx, item.hir_id, item.span, sig, headers);
+            },
+            hir::ItemKind::Impl(_, _, _, _, ref trait_ref, ..) => {
+                self.in_trait_impl = trait_ref.is_some();
+            },
+            _ => {},
+        }
+    }
+
+    fn check_item_post(&mut self, _cx: &LateContext<'a, 'tcx>, item: &'tcx hir::Item) {
+        if let hir::ItemKind::Impl(..) = item.kind {
+            self.in_trait_impl = false;
+        }
+    }
+
+    fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::TraitItem) {
+        let headers = check_attrs(cx, &self.valid_idents, &item.attrs);
+        if let hir::TraitItemKind::Method(ref sig, ..) = item.kind {
+            lint_for_missing_headers(cx, item.hir_id, item.span, sig, headers);
+        }
+    }
+
+    fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx hir::ImplItem) {
+        let headers = check_attrs(cx, &self.valid_idents, &item.attrs);
+        if self.in_trait_impl {
             return;
         }
-        // no safety header
-        if let ast::ItemKind::Fn(_, ref header, ..) = item.kind {
-            if item.vis.node.is_pub() && header.unsafety == ast::Unsafety::Unsafe {
-                span_lint(
-                    cx,
-                    MISSING_SAFETY_DOC,
-                    item.span,
-                    "unsafe function's docs miss `# Safety` section",
-                );
-            }
+        if let hir::ImplItemKind::Method(ref sig, ..) = item.kind {
+            lint_for_missing_headers(cx, item.hir_id, item.span, sig, headers);
         }
     }
 }
 
+fn lint_for_missing_headers<'a, 'tcx>(
+    cx: &LateContext<'a, 'tcx>,
+    hir_id: hir::HirId,
+    span: impl Into<MultiSpan> + Copy,
+    sig: &hir::FnSig,
+    headers: DocHeaders,
+) {
+    if !cx.access_levels.is_exported(hir_id) {
+        return; // Private functions do not require doc comments
+    }
+    if !headers.safety && sig.header.unsafety == hir::Unsafety::Unsafe {
+        span_lint(
+            cx,
+            MISSING_SAFETY_DOC,
+            span,
+            "unsafe function's docs miss `# Safety` section",
+        );
+    }
+    if !headers.errors && match_type(cx, return_ty(cx, hir_id), &paths::RESULT) {
+        span_lint(
+            cx,
+            MISSING_ERRORS_DOC,
+            span,
+            "docs for function returning `Result` missing `# Errors` section",
+        );
+    }
+}
+
 /// Cleanup documentation decoration (`///` and such).
 ///
 /// We can't use `syntax::attr::AttributeMethods::with_desugared_doc` or
@@ -140,6 +222,7 @@ fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
 /// need to keep track of
 /// the spans but this function is inspired from the later.
 #[allow(clippy::cast_possible_truncation)]
+#[must_use]
 pub fn strip_doc_comment_decoration(comment: &str, span: Span) -> (String, Vec<(usize, Span)>) {
     // one-line comments lose their prefix
     const ONELINERS: &[&str] = &["///!", "///", "//!", "//"];
@@ -190,21 +273,29 @@ pub fn strip_doc_comment_decoration(comment: &str, span: Span) -> (String, Vec<(
     panic!("not a doc-comment: {}", comment);
 }
 
-pub fn check_attrs<'a>(cx: &EarlyContext<'_>, valid_idents: &FxHashSet<String>, attrs: &'a [ast::Attribute]) -> bool {
+#[derive(Copy, Clone)]
+struct DocHeaders {
+    safety: bool,
+    errors: bool,
+}
+
+fn check_attrs<'a>(cx: &LateContext<'_, '_>, valid_idents: &FxHashSet<String>, attrs: &'a [Attribute]) -> DocHeaders {
     let mut doc = String::new();
     let mut spans = vec![];
 
     for attr in attrs {
-        if attr.is_sugared_doc {
-            if let Some(ref current) = attr.value_str() {
-                let current = current.to_string();
-                let (current, current_spans) = strip_doc_comment_decoration(&current, attr.span);
-                spans.extend_from_slice(&current_spans);
-                doc.push_str(&current);
-            }
+        if let AttrKind::DocComment(ref comment) = attr.kind {
+            let comment = comment.to_string();
+            let (comment, current_spans) = strip_doc_comment_decoration(&comment, attr.span);
+            spans.extend_from_slice(&current_spans);
+            doc.push_str(&comment);
         } else if attr.check_name(sym!(doc)) {
             // ignore mix of sugared and non-sugared doc
-            return true; // don't trigger the safety check
+            // don't trigger the safety or errors check
+            return DocHeaders {
+                safety: true,
+                errors: true,
+            };
         }
     }
 
@@ -216,7 +307,10 @@ pub fn check_attrs<'a>(cx: &EarlyContext<'_>, valid_idents: &FxHashSet<String>,
     }
 
     if doc.is_empty() {
-        return false;
+        return DocHeaders {
+            safety: false,
+            errors: false,
+        };
     }
 
     let parser = pulldown_cmark::Parser::new(&doc).into_offset_iter();
@@ -240,16 +334,19 @@ pub fn check_attrs<'a>(cx: &EarlyContext<'_>, valid_idents: &FxHashSet<String>,
 }
 
 fn check_doc<'a, Events: Iterator<Item = (pulldown_cmark::Event<'a>, Range<usize>)>>(
-    cx: &EarlyContext<'_>,
+    cx: &LateContext<'_, '_>,
     valid_idents: &FxHashSet<String>,
     events: Events,
     spans: &[(usize, Span)],
-) -> bool {
+) -> DocHeaders {
     // true if a safety header was found
     use pulldown_cmark::Event::*;
     use pulldown_cmark::Tag::*;
 
-    let mut safety_header = false;
+    let mut headers = DocHeaders {
+        safety: false,
+        errors: false,
+    };
     let mut in_code = false;
     let mut in_link = None;
     let mut in_heading = false;
@@ -272,7 +369,8 @@ fn check_doc<'a, Events: Iterator<Item = (pulldown_cmark::Event<'a>, Range<usize
                     // text "http://example.com" by pulldown-cmark
                     continue;
                 }
-                safety_header |= in_heading && text.trim() == "Safety";
+                headers.safety |= in_heading && text.trim() == "Safety";
+                headers.errors |= in_heading && text.trim() == "Errors";
                 let index = match spans.binary_search_by(|c| c.0.cmp(&range.start)) {
                     Ok(o) => o,
                     Err(e) => e - 1,
@@ -283,21 +381,22 @@ fn check_doc<'a, Events: Iterator<Item = (pulldown_cmark::Event<'a>, Range<usize
                 } else {
                     // Adjust for the beginning of the current `Event`
                     let span = span.with_lo(span.lo() + BytePos::from_usize(range.start - begin));
+
                     check_text(cx, valid_idents, &text, span);
                 }
             },
         }
     }
-    safety_header
+    headers
 }
 
-fn check_code(cx: &EarlyContext<'_>, text: &str, span: Span) {
-    if text.contains("fn main() {") {
+fn check_code(cx: &LateContext<'_, '_>, text: &str, span: Span) {
+    if text.contains("fn main() {") && !(text.contains("static") || text.contains("fn main() {}")) {
         span_lint(cx, NEEDLESS_DOCTEST_MAIN, span, "needless `fn main` in doctest");
     }
 }
 
-fn check_text(cx: &EarlyContext<'_>, valid_idents: &FxHashSet<String>, text: &str, span: Span) {
+fn check_text(cx: &LateContext<'_, '_>, valid_idents: &FxHashSet<String>, text: &str, span: Span) {
     for word in text.split(|c: char| c.is_whitespace() || c == '\'') {
         // Trim punctuation as in `some comment (see foo::bar).`
         //                                                   ^^
@@ -320,7 +419,7 @@ fn check_text(cx: &EarlyContext<'_>, valid_idents: &FxHashSet<String>, text: &st
     }
 }
 
-fn check_word(cx: &EarlyContext<'_>, word: &str, span: Span) {
+fn check_word(cx: &LateContext<'_, '_>, word: &str, span: Span) {
     /// Checks if a string is camel-case, i.e., contains at least two uppercase
     /// letters (`Clippy` is ok) and one lower-case letter (`NASA` is ok).
     /// Plurals are also excluded (`IDs` is ok).