2 use crate::core::DocContext;
3 use crate::html::markdown::{find_testable_code, ErrorCodes};
4 use crate::passes::check_doc_test_visibility::{should_have_doc_example, Tests};
5 use crate::passes::Pass;
6 use crate::visit::DocVisitor;
8 use rustc_lint::builtin::MISSING_DOCS;
9 use rustc_middle::lint::LintLevelSource;
10 use rustc_middle::ty::DefIdTree;
11 use rustc_session::lint;
12 use rustc_span::FileName;
15 use std::collections::BTreeMap;
18 crate const CALCULATE_DOC_COVERAGE: Pass = Pass {
19 name: "calculate-doc-coverage",
20 run: calculate_doc_coverage,
21 description: "counts the number of items with and without documentation",
24 fn calculate_doc_coverage(krate: clean::Crate, ctx: &mut DocContext<'_>) -> clean::Crate {
25 let mut calc = CoverageCalculator { items: Default::default(), ctx };
26 calc.visit_crate(&krate);
33 #[derive(Default, Copy, Clone, Serialize, Debug)]
45 has_doc_example: bool,
46 should_have_doc_examples: bool,
47 should_have_docs: bool,
49 if has_docs || should_have_docs {
56 if should_have_doc_examples || has_doc_example {
57 self.total_examples += 1;
60 self.with_examples += 1;
64 fn percentage(&self) -> Option<f64> {
66 Some((self.with_docs as f64 * 100.0) / self.total as f64)
72 fn examples_percentage(&self) -> Option<f64> {
73 if self.total_examples > 0 {
74 Some((self.with_examples as f64 * 100.0) / self.total_examples as f64)
81 impl ops::Sub for ItemCount {
84 fn sub(self, rhs: Self) -> Self {
86 total: self.total - rhs.total,
87 with_docs: self.with_docs - rhs.with_docs,
88 total_examples: self.total_examples - rhs.total_examples,
89 with_examples: self.with_examples - rhs.with_examples,
94 impl ops::AddAssign for ItemCount {
95 fn add_assign(&mut self, rhs: Self) {
96 self.total += rhs.total;
97 self.with_docs += rhs.with_docs;
98 self.total_examples += rhs.total_examples;
99 self.with_examples += rhs.with_examples;
103 struct CoverageCalculator<'a, 'b> {
104 items: BTreeMap<FileName, ItemCount>,
105 ctx: &'a mut DocContext<'b>,
108 fn limit_filename_len(filename: String) -> String {
109 let nb_chars = filename.chars().count();
112 + &filename[filename.char_indices().nth(nb_chars - 32).map(|x| x.0).unwrap_or(0)..]
118 impl<'a, 'b> CoverageCalculator<'a, 'b> {
119 fn to_json(&self) -> String {
120 serde_json::to_string(
124 .map(|(k, v)| (k.prefer_local().to_string(), v))
125 .collect::<BTreeMap<String, &ItemCount>>(),
127 .expect("failed to convert JSON data to string")
130 fn print_results(&self) {
131 let output_format = self.ctx.output_format;
132 if output_format.is_json() {
133 println!("{}", self.to_json());
136 let mut total = ItemCount::default();
138 fn print_table_line() {
139 println!("+-{0:->35}-+-{0:->10}-+-{0:->10}-+-{0:->10}-+-{0:->10}-+", "");
142 fn print_table_record(
146 examples_percentage: f64,
149 "| {:<35} | {:>10} | {:>9.1}% | {:>10} | {:>9.1}% |",
150 name, count.with_docs, percentage, count.with_examples, examples_percentage,
156 "| {:<35} | {:>10} | {:>10} | {:>10} | {:>10} |",
157 "File", "Documented", "Percentage", "Examples", "Percentage",
161 for (file, &count) in &self.items {
162 if let Some(percentage) = count.percentage() {
164 &limit_filename_len(file.prefer_local().to_string_lossy().into()),
167 count.examples_percentage().unwrap_or(0.),
178 total.percentage().unwrap_or(0.0),
179 total.examples_percentage().unwrap_or(0.0),
185 impl<'a, 'b> DocVisitor for CoverageCalculator<'a, 'b> {
186 fn visit_item(&mut self, i: &clean::Item) {
187 if !i.def_id.is_local() {
188 // non-local items are skipped because they can be out of the users control,
189 // especially in the case of trait impls, which rustdoc eagerly inlines
194 clean::StrippedItem(..) => {
195 // don't count items in stripped modules
198 // docs on `use` and `extern crate` statements are not displayed, so they're not
200 clean::ImportItem(..) | clean::ExternCrateItem { .. } => {}
201 // Don't count trait impls, the missing-docs lint doesn't so we shouldn't either.
202 // Inherent impls *can* be documented, and those docs show up, but in most cases it
203 // doesn't make sense, as all methods on a type are in one single impl block
204 clean::ImplItem(_) => {}
206 let has_docs = !i.attrs.doc_strings.is_empty();
207 let mut tests = Tests { found_tests: 0 };
210 &i.attrs.collapsed_doc_value().unwrap_or_default(),
217 let filename = i.span(self.ctx.tcx).filename(self.ctx.sess());
218 let has_doc_example = tests.found_tests != 0;
219 // The `expect_def_id()` should be okay because `local_def_id_to_hir_id`
220 // would presumably panic if a fake `DefIndex` were passed.
225 .local_def_id_to_hir_id(i.def_id.expect_def_id().expect_local());
226 let (level, source) = self.ctx.tcx.lint_level_at_node(MISSING_DOCS, hir_id);
231 // enum Foo { Bar(u32) }
236 // there is no need to require documentation on the fields of tuple variants and
238 let should_be_ignored = i
241 .and_then(|def_id| self.ctx.tcx.parent(def_id))
242 .and_then(|def_id| self.ctx.tcx.hir().get_if_local(def_id))
246 hir::Node::Variant(hir::Variant {
247 data: hir::VariantData::Tuple(_, _),
249 }) | hir::Node::Item(hir::Item {
250 kind: hir::ItemKind::Struct(hir::VariantData::Tuple(_, _), _),
257 // `missing_docs` is allow-by-default, so don't treat this as ignoring the item
258 // unless the user had an explicit `allow`.
260 let should_have_docs = !should_be_ignored
261 && (level != lint::Level::Allow || matches!(source, LintLevelSource::Default));
263 debug!("counting {:?} {:?} in {:?}", i.type_(), i.name, filename);
264 self.items.entry(filename).or_default().count_item(
267 should_have_doc_example(self.ctx, &i),
273 self.visit_item_recur(i)