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