2 use crate::core::DocContext;
3 use crate::fold::{self, DocFolder};
4 use crate::html::markdown::{find_testable_code, ErrorCodes};
5 use crate::passes::doc_test_lints::{should_have_doc_example, Tests};
6 use crate::passes::Pass;
7 use rustc_lint::builtin::MISSING_DOCS;
8 use rustc_middle::lint::LintLevelSource;
9 use rustc_session::lint;
10 use rustc_span::FileName;
13 use std::collections::BTreeMap;
16 crate const CALCULATE_DOC_COVERAGE: Pass = Pass {
17 name: "calculate-doc-coverage",
18 run: calculate_doc_coverage,
19 description: "counts the number of items with and without documentation",
22 fn calculate_doc_coverage(krate: clean::Crate, ctx: &mut DocContext<'_>) -> clean::Crate {
23 let mut calc = CoverageCalculator { items: Default::default(), ctx };
24 let krate = calc.fold_crate(krate);
31 #[derive(Default, Copy, Clone, Serialize, Debug)]
43 has_doc_example: bool,
44 should_have_doc_examples: bool,
45 should_have_docs: bool,
47 if has_docs || should_have_docs {
54 if should_have_doc_examples || has_doc_example {
55 self.total_examples += 1;
58 self.with_examples += 1;
62 fn percentage(&self) -> Option<f64> {
64 Some((self.with_docs as f64 * 100.0) / self.total as f64)
70 fn examples_percentage(&self) -> Option<f64> {
71 if self.total_examples > 0 {
72 Some((self.with_examples as f64 * 100.0) / self.total_examples as f64)
79 impl ops::Sub for ItemCount {
82 fn sub(self, rhs: Self) -> Self {
84 total: self.total - rhs.total,
85 with_docs: self.with_docs - rhs.with_docs,
86 total_examples: self.total_examples - rhs.total_examples,
87 with_examples: self.with_examples - rhs.with_examples,
92 impl ops::AddAssign for ItemCount {
93 fn add_assign(&mut self, rhs: Self) {
94 self.total += rhs.total;
95 self.with_docs += rhs.with_docs;
96 self.total_examples += rhs.total_examples;
97 self.with_examples += rhs.with_examples;
101 struct CoverageCalculator<'a, 'b> {
102 items: BTreeMap<FileName, ItemCount>,
103 ctx: &'a mut DocContext<'b>,
106 fn limit_filename_len(filename: String) -> String {
107 let nb_chars = filename.chars().count();
110 + &filename[filename.char_indices().nth(nb_chars - 32).map(|x| x.0).unwrap_or(0)..]
116 impl<'a, 'b> CoverageCalculator<'a, 'b> {
117 fn to_json(&self) -> String {
118 serde_json::to_string(
122 .map(|(k, v)| (k.to_string(), v))
123 .collect::<BTreeMap<String, &ItemCount>>(),
125 .expect("failed to convert JSON data to string")
128 fn print_results(&self) {
129 let output_format = self.ctx.output_format;
130 if output_format.is_json() {
131 println!("{}", self.to_json());
134 let mut total = ItemCount::default();
136 fn print_table_line() {
137 println!("+-{0:->35}-+-{0:->10}-+-{0:->10}-+-{0:->10}-+-{0:->10}-+", "");
140 fn print_table_record(
144 examples_percentage: f64,
147 "| {:<35} | {:>10} | {:>9.1}% | {:>10} | {:>9.1}% |",
148 name, count.with_docs, percentage, count.with_examples, examples_percentage,
154 "| {:<35} | {:>10} | {:>10} | {:>10} | {:>10} |",
155 "File", "Documented", "Percentage", "Examples", "Percentage",
159 for (file, &count) in &self.items {
160 if let Some(percentage) = count.percentage() {
162 &limit_filename_len(file.to_string()),
165 count.examples_percentage().unwrap_or(0.),
176 total.percentage().unwrap_or(0.0),
177 total.examples_percentage().unwrap_or(0.0),
183 impl<'a, 'b> fold::DocFolder for CoverageCalculator<'a, 'b> {
184 fn fold_item(&mut self, i: clean::Item) -> Option<clean::Item> {
186 _ if !i.def_id.is_local() => {
187 // non-local items are skipped because they can be out of the users control,
188 // especially in the case of trait impls, which rustdoc eagerly inlines
191 clean::StrippedItem(..) => {
192 // don't count items in stripped modules
195 // docs on `use` and `extern crate` statements are not displayed, so they're not
197 clean::ImportItem(..) | clean::ExternCrateItem { .. } => {}
198 // Don't count trait impls, the missing-docs lint doesn't so we shouldn't either.
199 // Inherent impls *can* be documented, and those docs show up, but in most cases it
200 // doesn't make sense, as all methods on a type are in one single impl block
201 clean::ImplItem(_) => {}
203 let has_docs = !i.attrs.doc_strings.is_empty();
204 let mut tests = Tests { found_tests: 0 };
207 &i.attrs.collapsed_doc_value().unwrap_or_default(),
214 let filename = i.span.filename(self.ctx.sess());
215 let has_doc_example = tests.found_tests != 0;
216 let hir_id = self.ctx.tcx.hir().local_def_id_to_hir_id(i.def_id.expect_local());
217 let (level, source) = self.ctx.tcx.lint_level_at_node(MISSING_DOCS, hir_id);
218 // `missing_docs` is allow-by-default, so don't treat this as ignoring the item
219 // unless the user had an explicit `allow`
220 let should_have_docs =
221 level != lint::Level::Allow || matches!(source, LintLevelSource::Default);
222 debug!("counting {:?} {:?} in {}", i.type_(), i.name, filename);
223 self.items.entry(filename).or_default().count_item(
226 should_have_doc_example(self.ctx, &i),
232 Some(self.fold_item_recur(i))