Skip to main content

rustdoc/passes/
check_doc_test_visibility.rs

1//! Looks for items missing (or incorrectly having) doctests.
2//!
3//! This pass is overloaded and runs two different lints.
4//!
5//! - MISSING_DOC_CODE_EXAMPLES: this lint is **UNSTABLE** and looks for public items missing doctests.
6//! - PRIVATE_DOC_TESTS: this lint is **STABLE** and looks for private items with doctests.
7
8use rustc_hir as hir;
9use rustc_macros::Diagnostic;
10use rustc_middle::lint::{LevelAndSource, LintLevelSource};
11use rustc_session::lint;
12use tracing::debug;
13
14use super::Pass;
15use crate::clean;
16use crate::clean::utils::inherits_doc_hidden;
17use crate::clean::*;
18use crate::core::DocContext;
19use crate::html::markdown::{ErrorCodes, Ignore, LangString, MdRelLine, find_testable_code};
20use crate::visit::DocVisitor;
21
22pub(crate) const CHECK_DOC_TEST_VISIBILITY: Pass = Pass {
23    name: "check_doc_test_visibility",
24    run: Some(check_doc_test_visibility),
25    description: "run various visibility-related lints on doctests",
26};
27
28struct DocTestVisibilityLinter<'a, 'tcx> {
29    cx: &'a mut DocContext<'tcx>,
30}
31
32pub(crate) fn check_doc_test_visibility(krate: Crate, cx: &mut DocContext<'_>) -> Crate {
33    let mut coll = DocTestVisibilityLinter { cx };
34    coll.visit_crate(&krate);
35    krate
36}
37
38impl DocVisitor<'_> for DocTestVisibilityLinter<'_, '_> {
39    fn visit_item(&mut self, item: &Item) {
40        look_for_tests(self.cx, &item.doc_value(), item);
41
42        self.visit_item_recur(item)
43    }
44}
45
46pub(crate) struct Tests {
47    pub(crate) found_tests: usize,
48}
49
50impl crate::doctest::DocTestVisitor for Tests {
51    fn visit_test(&mut self, _: String, config: LangString, _: MdRelLine) {
52        if config.rust && config.ignore == Ignore::None {
53            self.found_tests += 1;
54        }
55    }
56}
57
58pub(crate) fn should_have_doc_example(cx: &DocContext<'_>, item: &clean::Item) -> bool {
59    if !(cx.cache.effective_visibilities.is_directly_public(cx.tcx, item.item_id.expect_def_id())
60        || item.is_exported_macro())
61        || matches!(
62            item.kind,
63            clean::StructFieldItem(_)
64                | clean::VariantItem(_)
65                | clean::TypeAliasItem(_)
66                | clean::StaticItem(_)
67                | clean::ConstantItem(..)
68                | clean::ExternCrateItem { .. }
69                | clean::ImportItem(_)
70                | clean::PrimitiveItem(_)
71                | clean::KeywordItem
72                | clean::AttributeItem
73                | clean::ModuleItem(_)
74                | clean::TraitAliasItem(_)
75                | clean::ForeignFunctionItem(..)
76                | clean::ForeignStaticItem(..)
77                | clean::ForeignTypeItem
78                | clean::AssocTypeItem(..)
79                | clean::RequiredAssocConstItem(..)
80                | clean::ProvidedAssocConstItem(..)
81                | clean::ImplAssocConstItem(..)
82                | clean::RequiredAssocTypeItem(..)
83                | clean::ImplItem(_)
84                | clean::PlaceholderImplItem
85        )
86    {
87        return false;
88    }
89
90    // The `expect_def_id()` should be okay because `local_def_id_to_hir_id`
91    // would presumably panic if a fake `DefIndex` were passed.
92    let def_id = item.item_id.expect_def_id().expect_local();
93
94    // check if parent is trait impl
95    if let Some(parent_def_id) = cx.tcx.opt_local_parent(def_id)
96        && matches!(
97            cx.tcx.hir_node_by_def_id(parent_def_id),
98            hir::Node::Item(hir::Item {
99                kind: hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }),
100                ..
101            })
102        )
103    {
104        return false;
105    }
106
107    if (!cx.document_hidden()
108        && (cx.tcx.is_doc_hidden(def_id.to_def_id()) || inherits_doc_hidden(cx.tcx, def_id, None)))
109        || cx.tcx.def_span(def_id.to_def_id()).in_derive_expansion()
110    {
111        return false;
112    }
113    let LevelAndSource { level, src, .. } = cx.tcx.lint_level_at_node(
114        crate::lint::MISSING_DOC_CODE_EXAMPLES,
115        cx.tcx.local_def_id_to_hir_id(def_id),
116    );
117    level != lint::Level::Allow || matches!(src, LintLevelSource::Default)
118}
119
120pub(crate) fn look_for_tests(cx: &DocContext<'_>, dox: &str, item: &Item) {
121    #[derive(Diagnostic)]
122    #[diag("missing code example in this documentation")]
123    struct MissingCodeExample;
124
125    #[derive(Diagnostic)]
126    #[diag("documentation test in private item")]
127    struct DoctestInPrivateItem;
128
129    let Some(hir_id) = DocContext::as_local_hir_id(cx.tcx, item.item_id) else {
130        // If non-local, no need to check anything.
131        return;
132    };
133
134    let mut tests = Tests { found_tests: 0 };
135
136    find_testable_code(dox, &mut tests, ErrorCodes::No, None);
137
138    if tests.found_tests == 0 && cx.tcx.features().rustdoc_missing_doc_code_examples() {
139        if should_have_doc_example(cx, item) {
140            debug!("reporting error for {item:?} (hir_id={hir_id:?})");
141            let sp = item.attr_span(cx.tcx);
142            cx.tcx.emit_node_span_lint(
143                crate::lint::MISSING_DOC_CODE_EXAMPLES,
144                hir_id,
145                sp,
146                MissingCodeExample,
147            );
148        }
149    } else if tests.found_tests > 0
150        && !cx.cache.effective_visibilities.is_exported(cx.tcx, item.item_id.expect_def_id())
151    {
152        cx.tcx.emit_node_span_lint(
153            crate::lint::PRIVATE_DOC_TESTS,
154            hir_id,
155            item.attr_span(cx.tcx),
156            DoctestInPrivateItem,
157        );
158    }
159}