1 //! Calculates information used for the --show-coverage flag.
3 use crate::core::DocContext;
4 use crate::html::markdown::{find_testable_code, ErrorCodes};
5 use crate::passes::check_doc_test_visibility::{should_have_doc_example, Tests};
6 use crate::passes::Pass;
7 use crate::visit::DocVisitor;
9 use rustc_lint::builtin::MISSING_DOCS;
10 use rustc_middle::lint::LintLevelSource;
11 use rustc_middle::ty::DefIdTree;
12 use rustc_session::lint;
13 use rustc_span::FileName;
16 use std::collections::BTreeMap;
19 crate const CALCULATE_DOC_COVERAGE: Pass = Pass {
20 name: "calculate-doc-coverage",
21 run: calculate_doc_coverage,
22 description: "counts the number of items with and without documentation",
25 fn calculate_doc_coverage(krate: clean::Crate, ctx: &mut DocContext<'_>) -> clean::Crate {
26 let mut calc = CoverageCalculator { items: Default::default(), ctx };
27 calc.visit_crate(&krate);
34 #[derive(Default, Copy, Clone, Serialize, Debug)]
46 has_doc_example: bool,
47 should_have_doc_examples: bool,
48 should_have_docs: bool,
50 if has_docs || should_have_docs {
57 if should_have_doc_examples || has_doc_example {
58 self.total_examples += 1;
61 self.with_examples += 1;
65 fn percentage(&self) -> Option<f64> {
67 Some((self.with_docs as f64 * 100.0) / self.total as f64)
73 fn examples_percentage(&self) -> Option<f64> {
74 if self.total_examples > 0 {
75 Some((self.with_examples as f64 * 100.0) / self.total_examples as f64)
82 impl ops::Sub for ItemCount {
85 fn sub(self, rhs: Self) -> Self {
87 total: self.total - rhs.total,
88 with_docs: self.with_docs - rhs.with_docs,
89 total_examples: self.total_examples - rhs.total_examples,
90 with_examples: self.with_examples - rhs.with_examples,
95 impl ops::AddAssign for ItemCount {
96 fn add_assign(&mut self, rhs: Self) {
97 self.total += rhs.total;
98 self.with_docs += rhs.with_docs;
99 self.total_examples += rhs.total_examples;
100 self.with_examples += rhs.with_examples;
104 struct CoverageCalculator<'a, 'b> {
105 items: BTreeMap<FileName, ItemCount>,
106 ctx: &'a mut DocContext<'b>,
109 fn limit_filename_len(filename: String) -> String {
110 let nb_chars = filename.chars().count();
113 + &filename[filename.char_indices().nth(nb_chars - 32).map(|x| x.0).unwrap_or(0)..]
119 impl<'a, 'b> CoverageCalculator<'a, 'b> {
120 fn to_json(&self) -> String {
121 serde_json::to_string(
125 .map(|(k, v)| (k.prefer_local().to_string(), v))
126 .collect::<BTreeMap<String, &ItemCount>>(),
128 .expect("failed to convert JSON data to string")
131 fn print_results(&self) {
132 let output_format = self.ctx.output_format;
133 if output_format.is_json() {
134 println!("{}", self.to_json());
137 let mut total = ItemCount::default();
139 fn print_table_line() {
140 println!("+-{0:->35}-+-{0:->10}-+-{0:->10}-+-{0:->10}-+-{0:->10}-+", "");
143 fn print_table_record(
147 examples_percentage: f64,
150 "| {:<35} | {:>10} | {:>9.1}% | {:>10} | {:>9.1}% |",
151 name, count.with_docs, percentage, count.with_examples, examples_percentage,
157 "| {:<35} | {:>10} | {:>10} | {:>10} | {:>10} |",
158 "File", "Documented", "Percentage", "Examples", "Percentage",
162 for (file, &count) in &self.items {
163 if let Some(percentage) = count.percentage() {
165 &limit_filename_len(file.prefer_local().to_string_lossy().into()),
168 count.examples_percentage().unwrap_or(0.),
179 total.percentage().unwrap_or(0.0),
180 total.examples_percentage().unwrap_or(0.0),
186 impl<'a, 'b> DocVisitor for CoverageCalculator<'a, 'b> {
187 fn visit_item(&mut self, i: &clean::Item) {
188 if !i.def_id.is_local() {
189 // non-local items are skipped because they can be out of the users control,
190 // especially in the case of trait impls, which rustdoc eagerly inlines
195 clean::StrippedItem(..) => {
196 // don't count items in stripped modules
199 // docs on `use` and `extern crate` statements are not displayed, so they're not
201 clean::ImportItem(..) | clean::ExternCrateItem { .. } => {}
202 // Don't count trait impls, the missing-docs lint doesn't so we shouldn't either.
203 // Inherent impls *can* be documented, and those docs show up, but in most cases it
204 // doesn't make sense, as all methods on a type are in one single impl block
205 clean::ImplItem(_) => {}
207 let has_docs = !i.attrs.doc_strings.is_empty();
208 let mut tests = Tests { found_tests: 0 };
211 &i.attrs.collapsed_doc_value().unwrap_or_default(),
218 let filename = i.span(self.ctx.tcx).filename(self.ctx.sess());
219 let has_doc_example = tests.found_tests != 0;
220 // The `expect_def_id()` should be okay because `local_def_id_to_hir_id`
221 // would presumably panic if a fake `DefIndex` were passed.
226 .local_def_id_to_hir_id(i.def_id.expect_def_id().expect_local());
227 let (level, source) = self.ctx.tcx.lint_level_at_node(MISSING_DOCS, hir_id);
232 // enum Foo { Bar(u32) }
237 // there is no need to require documentation on the fields of tuple variants and
239 let should_be_ignored = i
242 .and_then(|def_id| self.ctx.tcx.parent(def_id))
243 .and_then(|def_id| self.ctx.tcx.hir().get_if_local(def_id))
247 hir::Node::Variant(hir::Variant {
248 data: hir::VariantData::Tuple(_, _),
250 }) | hir::Node::Item(hir::Item {
251 kind: hir::ItemKind::Struct(hir::VariantData::Tuple(_, _), _),
258 // `missing_docs` is allow-by-default, so don't treat this as ignoring the item
259 // unless the user had an explicit `allow`.
261 let should_have_docs = !should_be_ignored
262 && (level != lint::Level::Allow || matches!(source, LintLevelSource::Default));
264 debug!("counting {:?} {:?} in {:?}", i.type_(), i.name, filename);
265 self.items.entry(filename).or_default().count_item(
268 should_have_doc_example(self.ctx, &i),
274 self.visit_item_recur(i)