Skip to main content

rustdoc/
calculate_doc_coverage.rs

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