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::LintLevelSource;
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        || item.is_exported_macro())
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                | clean::ImplItem(_)
83                | clean::PlaceholderImplItem
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 level_spec = cx.tcx.lint_level_spec_at_node(
113        crate::lint::MISSING_DOC_CODE_EXAMPLES,
114        cx.tcx.local_def_id_to_hir_id(def_id),
115    );
116    !level_spec.is_allow() || matches!(level_spec.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}