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::LintLevelSource;
9use rustc_session::lint;
10use rustc_span::FileName;
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().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(file.prefer_local().to_string_lossy().into()),
171                    count,
172                    percentage,
173                    count.examples_percentage().unwrap_or(0.),
174                );
175
176                total += count;
177            }
178        }
179
180        print_table_line();
181        print_table_record(
182            "Total",
183            total,
184            total.percentage().unwrap_or(0.0),
185            total.examples_percentage().unwrap_or(0.0),
186        );
187        print_table_line();
188    }
189}
190
191impl DocVisitor<'_> for CoverageCalculator<'_, '_> {
192    fn visit_item(&mut self, i: &clean::Item) {
193        if !i.item_id.is_local() {
194            // non-local items are skipped because they can be out of the users control,
195            // especially in the case of trait impls, which rustdoc eagerly inlines
196            return;
197        }
198
199        match i.kind {
200            clean::StrippedItem(..) => {
201                // don't count items in stripped modules
202                return;
203            }
204            // docs on `use` and `extern crate` statements are not displayed, so they're not
205            // worth counting
206            clean::ImportItem(..) | clean::ExternCrateItem { .. } => {}
207            // Don't count trait impls, the missing-docs lint doesn't so we shouldn't either.
208            // Inherent impls *can* be documented, and those docs show up, but in most cases it
209            // doesn't make sense, as all methods on a type are in one single impl block
210            clean::ImplItem(_) => {}
211            _ => {
212                let has_docs = !i.attrs.doc_strings.is_empty();
213                let mut tests = Tests { found_tests: 0 };
214
215                find_testable_code(&i.doc_value(), &mut tests, ErrorCodes::No, false, None);
216
217                let has_doc_example = tests.found_tests != 0;
218                let hir_id = DocContext::as_local_hir_id(self.ctx.tcx, i.item_id).unwrap();
219                let (level, source) = self.ctx.tcx.lint_level_at_node(MISSING_DOCS, hir_id);
220
221                // In case we have:
222                //
223                // ```
224                // enum Foo { Bar(u32) }
225                // // or:
226                // struct Bar(u32);
227                // ```
228                //
229                // there is no need to require documentation on the fields of tuple variants and
230                // tuple structs.
231                let should_be_ignored = i
232                    .item_id
233                    .as_def_id()
234                    .and_then(|def_id| self.ctx.tcx.opt_parent(def_id))
235                    .and_then(|def_id| self.ctx.tcx.hir().get_if_local(def_id))
236                    .map(|node| {
237                        matches!(
238                            node,
239                            hir::Node::Variant(hir::Variant {
240                                data: hir::VariantData::Tuple(_, _, _),
241                                ..
242                            }) | hir::Node::Item(hir::Item {
243                                kind: hir::ItemKind::Struct(hir::VariantData::Tuple(_, _, _), _),
244                                ..
245                            })
246                        )
247                    })
248                    .unwrap_or(false);
249
250                // `missing_docs` is allow-by-default, so don't treat this as ignoring the item
251                // unless the user had an explicit `allow`.
252                //
253                let should_have_docs = !should_be_ignored
254                    && (level != lint::Level::Allow || matches!(source, LintLevelSource::Default));
255
256                if let Some(span) = i.span(self.ctx.tcx) {
257                    let filename = span.filename(self.ctx.sess());
258                    debug!("counting {:?} {:?} in {filename:?}", i.type_(), i.name);
259                    self.items.entry(filename).or_default().count_item(
260                        has_docs,
261                        has_doc_example,
262                        should_have_doc_example(self.ctx, i),
263                        should_have_docs,
264                    );
265                }
266            }
267        }
268
269        self.visit_item_recur(i)
270    }
271}