2 use crate::config::OutputFormat;
3 use crate::core::DocContext;
4 use crate::fold::{self, DocFolder};
5 use crate::html::markdown::{find_testable_code, ErrorCodes};
6 use crate::passes::doc_test_lints::Tests;
7 use crate::passes::Pass;
8 use rustc_span::symbol::sym;
9 use rustc_span::FileName;
12 use std::collections::BTreeMap;
15 pub const CALCULATE_DOC_COVERAGE: Pass = Pass {
16 name: "calculate-doc-coverage",
17 run: calculate_doc_coverage,
18 description: "counts the number of items with and without documentation",
21 fn calculate_doc_coverage(krate: clean::Crate, ctx: &DocContext<'_>) -> clean::Crate {
22 let mut calc = CoverageCalculator::new();
23 let krate = calc.fold_crate(krate);
25 calc.print_results(ctx.renderinfo.borrow().output_format);
30 #[derive(Default, Copy, Clone, Serialize)]
42 has_doc_example: bool,
43 should_have_doc_examples: bool,
50 if should_have_doc_examples || has_doc_example {
51 self.total_examples += 1;
54 self.with_examples += 1;
58 fn percentage(&self) -> Option<f64> {
60 Some((self.with_docs as f64 * 100.0) / self.total as f64)
66 fn examples_percentage(&self) -> Option<f64> {
67 if self.total_examples > 0 {
68 Some((self.with_examples as f64 * 100.0) / self.total_examples as f64)
75 impl ops::Sub for ItemCount {
78 fn sub(self, rhs: Self) -> Self {
80 total: self.total - rhs.total,
81 with_docs: self.with_docs - rhs.with_docs,
82 total_examples: self.total_examples - rhs.total_examples,
83 with_examples: self.with_examples - rhs.with_examples,
88 impl ops::AddAssign for ItemCount {
89 fn add_assign(&mut self, rhs: Self) {
90 self.total += rhs.total;
91 self.with_docs += rhs.with_docs;
92 self.total_examples += rhs.total_examples;
93 self.with_examples += rhs.with_examples;
97 struct CoverageCalculator {
98 items: BTreeMap<FileName, ItemCount>,
101 fn limit_filename_len(filename: String) -> String {
102 let nb_chars = filename.chars().count();
105 + &filename[filename.char_indices().nth(nb_chars - 32).map(|x| x.0).unwrap_or(0)..]
111 impl CoverageCalculator {
112 fn new() -> CoverageCalculator {
113 CoverageCalculator { items: Default::default() }
116 fn to_json(&self) -> String {
117 serde_json::to_string(
121 .map(|(k, v)| (k.to_string(), v))
122 .collect::<BTreeMap<String, &ItemCount>>(),
124 .expect("failed to convert JSON data to string")
127 fn print_results(&self, output_format: Option<OutputFormat>) {
128 if output_format.map(|o| o.is_json()).unwrap_or_else(|| false) {
129 println!("{}", self.to_json());
132 let mut total = ItemCount::default();
134 fn print_table_line() {
135 println!("+-{0:->35}-+-{0:->10}-+-{0:->10}-+-{0:->10}-+-{0:->10}-+", "");
138 fn print_table_record(
142 examples_percentage: f64,
145 "| {:<35} | {:>10} | {:>9.1}% | {:>10} | {:>9.1}% |",
146 name, count.with_docs, percentage, count.with_examples, examples_percentage,
152 "| {:<35} | {:>10} | {:>10} | {:>10} | {:>10} |",
153 "File", "Documented", "Percentage", "Examples", "Percentage",
157 for (file, &count) in &self.items {
158 if let (Some(percentage), Some(examples_percentage)) =
159 (count.percentage(), count.examples_percentage())
162 &limit_filename_len(file.to_string()),
176 total.percentage().unwrap_or(0.0),
177 total.examples_percentage().unwrap_or(0.0),
183 impl fold::DocFolder for CoverageCalculator {
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 clean::ImportItem(..) | clean::ExternCrateItem(..) => {
196 // docs on `use` and `extern crate` statements are not displayed, so they're not
200 clean::ImplItem(ref impl_)
204 .any(|item| item.has_name(sym::automatically_derived))
206 || impl_.blanket_impl.is_some() =>
208 // built-in derives get the `#[automatically_derived]` attribute, and
209 // synthetic/blanket impls are made up by rustdoc and can't be documented
210 // FIXME(misdreavus): need to also find items that came out of a derive macro
213 clean::ImplItem(ref impl_) => {
214 if let Some(ref tr) = impl_.trait_ {
216 "impl {:#} for {:#} in {}",
222 // don't count trait impls, the missing-docs lint doesn't so we shouldn't
226 // inherent impls *can* be documented, and those docs show up, but in most
227 // cases it doesn't make sense, as all methods on a type are in one single
229 debug!("impl {:#} in {}", impl_.for_.print(), i.source.filename);
233 let has_docs = !i.attrs.doc_strings.is_empty();
234 let mut tests = Tests { found_tests: 0 };
236 let should_have_doc_examples = !matches!(i.inner,
237 clean::StructFieldItem(_)
238 | clean::VariantItem(_)
239 | clean::AssocConstItem(_, _)
240 | clean::AssocTypeItem(_, _)
241 | clean::TypedefItem(_, _)
242 | clean::StaticItem(_)
243 | clean::ConstantItem(_)
246 &i.attrs.doc_strings.iter().map(|d| d.as_str()).collect::<Vec<_>>().join("\n"),
253 let has_doc_example = tests.found_tests != 0;
254 debug!("counting {:?} {:?} in {}", i.type_(), i.name, i.source.filename);
255 self.items.entry(i.source.filename.clone()).or_default().count_item(
258 should_have_doc_examples,
263 self.fold_item_recur(i)