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