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::symbol::sym;
11 use rustc_span::FileName;
14 use std::collections::BTreeMap;
17 crate const CALCULATE_DOC_COVERAGE: Pass = Pass {
18 name: "calculate-doc-coverage",
19 run: calculate_doc_coverage,
20 description: "counts the number of items with and without documentation",
23 fn calculate_doc_coverage(krate: clean::Crate, ctx: &DocContext<'_>) -> clean::Crate {
24 let mut calc = CoverageCalculator::new(ctx);
25 let krate = calc.fold_crate(krate);
32 #[derive(Default, Copy, Clone, Serialize, Debug)]
44 has_doc_example: bool,
45 should_have_doc_examples: bool,
46 should_have_docs: bool,
48 if has_docs || should_have_docs {
55 if should_have_doc_examples || has_doc_example {
56 self.total_examples += 1;
59 self.with_examples += 1;
63 fn percentage(&self) -> Option<f64> {
65 Some((self.with_docs as f64 * 100.0) / self.total as f64)
71 fn examples_percentage(&self) -> Option<f64> {
72 if self.total_examples > 0 {
73 Some((self.with_examples as f64 * 100.0) / self.total_examples as f64)
80 impl ops::Sub for ItemCount {
83 fn sub(self, rhs: Self) -> Self {
85 total: self.total - rhs.total,
86 with_docs: self.with_docs - rhs.with_docs,
87 total_examples: self.total_examples - rhs.total_examples,
88 with_examples: self.with_examples - rhs.with_examples,
93 impl ops::AddAssign for ItemCount {
94 fn add_assign(&mut self, rhs: Self) {
95 self.total += rhs.total;
96 self.with_docs += rhs.with_docs;
97 self.total_examples += rhs.total_examples;
98 self.with_examples += rhs.with_examples;
102 struct CoverageCalculator<'a, 'b> {
103 items: BTreeMap<FileName, ItemCount>,
104 ctx: &'a DocContext<'b>,
107 fn limit_filename_len(filename: String) -> String {
108 let nb_chars = filename.chars().count();
111 + &filename[filename.char_indices().nth(nb_chars - 32).map(|x| x.0).unwrap_or(0)..]
117 impl<'a, 'b> CoverageCalculator<'a, 'b> {
118 fn new(ctx: &'a DocContext<'b>) -> CoverageCalculator<'a, 'b> {
119 CoverageCalculator { items: Default::default(), ctx }
122 fn to_json(&self) -> String {
123 serde_json::to_string(
127 .map(|(k, v)| (k.to_string(), v))
128 .collect::<BTreeMap<String, &ItemCount>>(),
130 .expect("failed to convert JSON data to string")
133 fn print_results(&self) {
134 let output_format = self.ctx.renderinfo.borrow().output_format;
135 if output_format.map(|o| o.is_json()).unwrap_or_else(|| false) {
136 println!("{}", self.to_json());
139 let mut total = ItemCount::default();
141 fn print_table_line() {
142 println!("+-{0:->35}-+-{0:->10}-+-{0:->10}-+-{0:->10}-+-{0:->10}-+", "");
145 fn print_table_record(
149 examples_percentage: f64,
152 "| {:<35} | {:>10} | {:>9.1}% | {:>10} | {:>9.1}% |",
153 name, count.with_docs, percentage, count.with_examples, examples_percentage,
159 "| {:<35} | {:>10} | {:>10} | {:>10} | {:>10} |",
160 "File", "Documented", "Percentage", "Examples", "Percentage",
164 for (file, &count) in &self.items {
165 if let Some(percentage) = count.percentage() {
167 &limit_filename_len(file.to_string()),
170 count.examples_percentage().unwrap_or(0.),
181 total.percentage().unwrap_or(0.0),
182 total.examples_percentage().unwrap_or(0.0),
188 impl<'a, 'b> fold::DocFolder for CoverageCalculator<'a, 'b> {
189 fn fold_item(&mut self, i: clean::Item) -> Option<clean::Item> {
191 _ if !i.def_id.is_local() => {
192 // non-local items are skipped because they can be out of the users control,
193 // especially in the case of trait impls, which rustdoc eagerly inlines
196 clean::StrippedItem(..) => {
197 // don't count items in stripped modules
200 clean::ImportItem(..) | clean::ExternCrateItem(..) => {
201 // docs on `use` and `extern crate` statements are not displayed, so they're not
205 clean::ImplItem(ref impl_)
209 .any(|item| item.has_name(sym::automatically_derived))
211 || impl_.blanket_impl.is_some() =>
213 // built-in derives get the `#[automatically_derived]` attribute, and
214 // synthetic/blanket impls are made up by rustdoc and can't be documented
215 // FIXME(misdreavus): need to also find items that came out of a derive macro
218 clean::ImplItem(ref impl_) => {
219 let filename = i.source.filename(self.ctx.sess());
220 if let Some(ref tr) = impl_.trait_ {
222 "impl {:#} for {:#} in {}",
223 tr.print(&self.ctx.cache),
224 impl_.for_.print(&self.ctx.cache),
228 // don't count trait impls, the missing-docs lint doesn't so we shouldn't
232 // inherent impls *can* be documented, and those docs show up, but in most
233 // cases it doesn't make sense, as all methods on a type are in one single
235 debug!("impl {:#} in {}", impl_.for_.print(&self.ctx.cache), filename);
239 let has_docs = !i.attrs.doc_strings.is_empty();
240 let mut tests = Tests { found_tests: 0 };
243 &i.attrs.collapsed_doc_value().unwrap_or_default(),
250 let filename = i.source.filename(self.ctx.sess());
251 let has_doc_example = tests.found_tests != 0;
252 let hir_id = self.ctx.tcx.hir().local_def_id_to_hir_id(i.def_id.expect_local());
253 let (level, source) = self.ctx.tcx.lint_level_at_node(MISSING_DOCS, hir_id);
254 // `missing_docs` is allow-by-default, so don't treat this as ignoring the item
255 // unless the user had an explicit `allow`
256 let should_have_docs =
257 level != lint::Level::Allow || matches!(source, LintLevelSource::Default);
258 debug!("counting {:?} {:?} in {}", i.type_(), i.name, filename);
259 self.items.entry(filename).or_default().count_item(
262 should_have_doc_example(self.ctx, &i),
268 Some(self.fold_item_recur(i))