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