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::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::ModuleItem(_)
71                | clean::TraitAliasItem(_)
72                | clean::ForeignFunctionItem(..)
73                | clean::ForeignStaticItem(..)
74                | clean::ForeignTypeItem
75                | clean::AssocTypeItem(..)
76                | clean::RequiredAssocConstItem(..)
77                | clean::ProvidedAssocConstItem(..)
78                | clean::ImplAssocConstItem(..)
79                | clean::RequiredAssocTypeItem(..)
80                // check for trait impl
81                | clean::ImplItem(box clean::Impl { trait_: Some(_), .. })
82        )
83    {
84        return false;
85    }
86
87    // The `expect_def_id()` should be okay because `local_def_id_to_hir_id`
88    // would presumably panic if a fake `DefIndex` were passed.
89    let def_id = item.item_id.expect_def_id().expect_local();
90
91    // check if parent is trait impl
92    if let Some(parent_def_id) = cx.tcx.opt_local_parent(def_id)
93        && matches!(
94            cx.tcx.hir_node_by_def_id(parent_def_id),
95            hir::Node::Item(hir::Item {
96                kind: hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }),
97                ..
98            })
99        )
100    {
101        return false;
102    }
103
104    if (!cx.render_options.document_hidden
105        && (cx.tcx.is_doc_hidden(def_id.to_def_id()) || inherits_doc_hidden(cx.tcx, def_id, None)))
106        || cx.tcx.def_span(def_id.to_def_id()).in_derive_expansion()
107    {
108        return false;
109    }
110    let (level, source) = cx.tcx.lint_level_at_node(
111        crate::lint::MISSING_DOC_CODE_EXAMPLES,
112        cx.tcx.local_def_id_to_hir_id(def_id),
113    );
114    level != lint::Level::Allow || matches!(source, LintLevelSource::Default)
115}
116
117pub(crate) fn look_for_tests(cx: &DocContext<'_>, dox: &str, item: &Item) {
118    let Some(hir_id) = DocContext::as_local_hir_id(cx.tcx, item.item_id) else {
119        // If non-local, no need to check anything.
120        return;
121    };
122
123    let mut tests = Tests { found_tests: 0 };
124
125    find_testable_code(dox, &mut tests, ErrorCodes::No, false, None);
126
127    if tests.found_tests == 0 && cx.tcx.features().rustdoc_missing_doc_code_examples() {
128        if should_have_doc_example(cx, item) {
129            debug!("reporting error for {item:?} (hir_id={hir_id:?})");
130            let sp = item.attr_span(cx.tcx);
131            cx.tcx.node_span_lint(crate::lint::MISSING_DOC_CODE_EXAMPLES, hir_id, sp, |lint| {
132                lint.primary_message("missing code example in this documentation");
133            });
134        }
135    } else if tests.found_tests > 0
136        && !cx.cache.effective_visibilities.is_exported(cx.tcx, item.item_id.expect_def_id())
137    {
138        cx.tcx.node_span_lint(
139            crate::lint::PRIVATE_DOC_TESTS,
140            hir_id,
141            item.attr_span(cx.tcx),
142            |lint| {
143                lint.primary_message("documentation test in private item");
144            },
145        );
146    }
147}