rustdoc/passes/
calculate_doc_coverage.rs

1//! Calculates information used for the --show-coverage flag.
2
3use std::collections::BTreeMap;
4use std::ops;
5
6use rustc_hir as hir;
7use rustc_lint::builtin::MISSING_DOCS;
8use rustc_middle::lint::{LevelAndSource, LintLevelSource};
9use rustc_session::lint;
10use rustc_span::{FileName, RemapPathScopeComponents};
11use serde::Serialize;
12use tracing::debug;
13
14use crate::clean;
15use crate::core::DocContext;
16use crate::html::markdown::{ErrorCodes, find_testable_code};
17use crate::passes::Pass;
18use crate::passes::check_doc_test_visibility::{Tests, should_have_doc_example};
19use crate::visit::DocVisitor;
20
21pub(crate) const CALCULATE_DOC_COVERAGE: Pass = Pass {
22    name: "calculate-doc-coverage",
23    run: Some(calculate_doc_coverage),
24    description: "counts the number of items with and without documentation",
25};
26
27fn calculate_doc_coverage(krate: clean::Crate, ctx: &mut DocContext<'_>) -> clean::Crate {
28    let mut calc = CoverageCalculator { items: Default::default(), ctx };
29    calc.visit_crate(&krate);
30
31    calc.print_results();
32
33    krate
34}
35
36#[derive(Default, Copy, Clone, Serialize, Debug)]
37struct ItemCount {
38    total: u64,
39    with_docs: u64,
40    total_examples: u64,
41    with_examples: u64,
42}
43
44impl ItemCount {
45    fn count_item(
46        &mut self,
47        has_docs: bool,
48        has_doc_example: bool,
49        should_have_doc_examples: bool,
50        should_have_docs: bool,
51    ) {
52        if has_docs || should_have_docs {
53            self.total += 1;
54        }
55
56        if has_docs {
57            self.with_docs += 1;
58        }
59        if should_have_doc_examples || has_doc_example {
60            self.total_examples += 1;
61        }
62        if has_doc_example {
63            self.with_examples += 1;
64        }
65    }
66
67    fn percentage(&self) -> Option<f64> {
68        if self.total > 0 {
69            Some((self.with_docs as f64 * 100.0) / self.total as f64)
70        } else {
71            None
72        }
73    }
74
75    fn examples_percentage(&self) -> Option<f64> {
76        if self.total_examples > 0 {
77            Some((self.with_examples as f64 * 100.0) / self.total_examples as f64)
78        } else {
79            None
80        }
81    }
82}
83
84impl ops::Sub for ItemCount {
85    type Output = Self;
86
87    fn sub(self, rhs: Self) -> Self {
88        ItemCount {
89            total: self.total - rhs.total,
90            with_docs: self.with_docs - rhs.with_docs,
91            total_examples: self.total_examples - rhs.total_examples,
92            with_examples: self.with_examples - rhs.with_examples,
93        }
94    }
95}
96
97impl ops::AddAssign for ItemCount {
98    fn add_assign(&mut self, rhs: Self) {
99        self.total += rhs.total;
100        self.with_docs += rhs.with_docs;
101        self.total_examples += rhs.total_examples;
102        self.with_examples += rhs.with_examples;
103    }
104}
105
106struct CoverageCalculator<'a, 'b> {
107    items: BTreeMap<FileName, ItemCount>,
108    ctx: &'a mut DocContext<'b>,
109}
110
111fn limit_filename_len(filename: String) -> String {
112    let nb_chars = filename.chars().count();
113    if nb_chars > 35 {
114        "...".to_string()
115            + &filename[filename.char_indices().nth(nb_chars - 32).map(|x| x.0).unwrap_or(0)..]
116    } else {
117        filename
118    }
119}
120
121impl CoverageCalculator<'_, '_> {
122    fn to_json(&self) -> String {
123        serde_json::to_string(
124            &self
125                .items
126                .iter()
127                .map(|(k, v)| (k.prefer_local_unconditionally().to_string(), v))
128                .collect::<BTreeMap<String, &ItemCount>>(),
129        )
130        .expect("failed to convert JSON data to string")
131    }
132
133    fn print_results(&self) {
134        let output_format = self.ctx.output_format;
135        // In this case we want to ensure that the `OutputFormat` is JSON and NOT the `DocContext`.
136        if output_format.is_json() {
137            println!("{}", self.to_json());
138            return;
139        }
140        let mut total = ItemCount::default();
141
142        fn print_table_line() {
143            println!("+-{0:->35}-+-{0:->10}-+-{0:->10}-+-{0:->10}-+-{0:->10}-+", "");
144        }
145
146        fn print_table_record(
147            name: &str,
148            count: ItemCount,
149            percentage: f64,
150            examples_percentage: f64,
151        ) {
152            println!(
153                "| {name:<35} | {with_docs:>10} | {percentage:>9.1}% | {with_examples:>10} | \
154                {examples_percentage:>9.1}% |",
155                with_docs = count.with_docs,
156                with_examples = count.with_examples,
157            );
158        }
159
160        print_table_line();
161        println!(
162            "| {:<35} | {:>10} | {:>10} | {:>10} | {:>10} |",
163            "File", "Documented", "Percentage", "Examples", "Percentage",
164        );
165        print_table_line();
166
167        for (file, &count) in &self.items {
168            if let Some(percentage) = count.percentage() {
169                print_table_record(
170                    &limit_filename_len(
171                        file.display(RemapPathScopeComponents::DIAGNOSTICS)
172                            .to_string_lossy()
173                            .into(),
174                    ),
175                    count,
176                    percentage,
177                    count.examples_percentage().unwrap_or(0.),
178                );
179
180                total += count;
181            }
182        }
183
184        print_table_line();
185        print_table_record(
186            "Total",
187            total,
188            total.percentage().unwrap_or(0.0),
189            total.examples_percentage().unwrap_or(0.0),
190        );
191        print_table_line();
192    }
193}
194
195impl DocVisitor<'_> for CoverageCalculator<'_, '_> {
196    fn visit_item(&mut self, i: &clean::Item) {
197        if !i.item_id.is_local() {
198            // non-local items are skipped because they can be out of the users control,
199            // especially in the case of trait impls, which rustdoc eagerly inlines
200            return;
201        }
202
203        match i.kind {
204            clean::StrippedItem(..) => {
205                // don't count items in stripped modules
206                return;
207            }
208            // docs on `use` and `extern crate` statements are not displayed, so they're not
209            // worth counting
210            clean::ImportItem(..) | clean::ExternCrateItem { .. } => {}
211            // Don't count trait impls, the missing-docs lint doesn't so we shouldn't either.
212            // Inherent impls *can* be documented, and those docs show up, but in most cases it
213            // doesn't make sense, as all methods on a type are in one single impl block
214            clean::ImplItem(_) => {}
215            _ => {
216                let has_docs = !i.attrs.doc_strings.is_empty();
217                let mut tests = Tests { found_tests: 0 };
218
219                find_testable_code(&i.doc_value(), &mut tests, ErrorCodes::No, None);
220
221                let has_doc_example = tests.found_tests != 0;
222                let hir_id = DocContext::as_local_hir_id(self.ctx.tcx, i.item_id).unwrap();
223                let LevelAndSource { level, src, .. } =
224                    self.ctx.tcx.lint_level_at_node(MISSING_DOCS, hir_id);
225
226                // In case we have:
227                //
228                // ```
229                // enum Foo { Bar(u32) }
230                // // or:
231                // struct Bar(u32);
232                // ```
233                //
234                // there is no need to require documentation on the fields of tuple variants and
235                // tuple structs.
236                let should_be_ignored = i
237                    .item_id
238                    .as_def_id()
239                    .and_then(|def_id| self.ctx.tcx.opt_parent(def_id))
240                    .and_then(|def_id| self.ctx.tcx.hir_get_if_local(def_id))
241                    .map(|node| {
242                        matches!(
243                            node,
244                            hir::Node::Variant(hir::Variant {
245                                data: hir::VariantData::Tuple(_, _, _),
246                                ..
247                            }) | hir::Node::Item(hir::Item {
248                                kind: hir::ItemKind::Struct(_, _, hir::VariantData::Tuple(_, _, _)),
249                                ..
250                            })
251                        )
252                    })
253                    .unwrap_or(false);
254
255                // `missing_docs` is allow-by-default, so don't treat this as ignoring the item
256                // unless the user had an explicit `allow`.
257                //
258                let should_have_docs = !should_be_ignored
259                    && (level != lint::Level::Allow || matches!(src, LintLevelSource::Default));
260
261                if let Some(span) = i.span(self.ctx.tcx) {
262                    let filename = span.filename(self.ctx.sess());
263                    debug!("counting {:?} {:?} in {filename:?}", i.type_(), i.name);
264                    self.items.entry(filename).or_default().count_item(
265                        has_docs,
266                        has_doc_example,
267                        should_have_doc_example(self.ctx, i),
268                        should_have_docs,
269                    );
270                }
271            }
272        }
273
274        self.visit_item_recur(i)
275    }
276}