]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/passes/calculate_doc_coverage.rs
fmt
[rust.git] / src / librustdoc / passes / calculate_doc_coverage.rs
1 use crate::clean;
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;
10 use serde::Serialize;
11
12 use std::collections::BTreeMap;
13 use std::ops;
14
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",
19 };
20
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);
24
25     calc.print_results(ctx.renderinfo.borrow().output_format);
26
27     krate
28 }
29
30 #[derive(Default, Copy, Clone, Serialize)]
31 struct ItemCount {
32     total: u64,
33     with_docs: u64,
34     total_examples: u64,
35     with_examples: u64,
36 }
37
38 impl ItemCount {
39     fn count_item(
40         &mut self,
41         has_docs: bool,
42         has_doc_example: bool,
43         should_have_doc_examples: bool,
44     ) {
45         self.total += 1;
46
47         if has_docs {
48             self.with_docs += 1;
49         }
50         if should_have_doc_examples || has_doc_example {
51             self.total_examples += 1;
52         }
53         if has_doc_example {
54             self.with_examples += 1;
55         }
56     }
57
58     fn percentage(&self) -> Option<f64> {
59         if self.total > 0 {
60             Some((self.with_docs as f64 * 100.0) / self.total as f64)
61         } else {
62             None
63         }
64     }
65
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)
69         } else {
70             None
71         }
72     }
73 }
74
75 impl ops::Sub for ItemCount {
76     type Output = Self;
77
78     fn sub(self, rhs: Self) -> Self {
79         ItemCount {
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,
84         }
85     }
86 }
87
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;
94     }
95 }
96
97 struct CoverageCalculator {
98     items: BTreeMap<FileName, ItemCount>,
99 }
100
101 fn limit_filename_len(filename: String) -> String {
102     let nb_chars = filename.chars().count();
103     if nb_chars > 35 {
104         "...".to_string()
105             + &filename[filename.char_indices().nth(nb_chars - 32).map(|x| x.0).unwrap_or(0)..]
106     } else {
107         filename
108     }
109 }
110
111 impl CoverageCalculator {
112     fn new() -> CoverageCalculator {
113         CoverageCalculator { items: Default::default() }
114     }
115
116     fn to_json(&self) -> String {
117         serde_json::to_string(
118             &self
119                 .items
120                 .iter()
121                 .map(|(k, v)| (k.to_string(), v))
122                 .collect::<BTreeMap<String, &ItemCount>>(),
123         )
124         .expect("failed to convert JSON data to string")
125     }
126
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());
130             return;
131         }
132         let mut total = ItemCount::default();
133
134         fn print_table_line() {
135             println!("+-{0:->35}-+-{0:->10}-+-{0:->10}-+-{0:->10}-+-{0:->10}-+", "");
136         }
137
138         fn print_table_record(
139             name: &str,
140             count: ItemCount,
141             percentage: f64,
142             examples_percentage: f64,
143         ) {
144             println!(
145                 "| {:<35} | {:>10} | {:>9.1}% | {:>10} | {:>9.1}% |",
146                 name, count.with_docs, percentage, count.with_examples, examples_percentage,
147             );
148         }
149
150         print_table_line();
151         println!(
152             "| {:<35} | {:>10} | {:>10} | {:>10} | {:>10} |",
153             "File", "Documented", "Percentage", "Examples", "Percentage",
154         );
155         print_table_line();
156
157         for (file, &count) in &self.items {
158             if let (Some(percentage), Some(examples_percentage)) =
159                 (count.percentage(), count.examples_percentage())
160             {
161                 print_table_record(
162                     &limit_filename_len(file.to_string()),
163                     count,
164                     percentage,
165                     examples_percentage,
166                 );
167
168                 total += count;
169             }
170         }
171
172         print_table_line();
173         print_table_record(
174             "Total",
175             total,
176             total.percentage().unwrap_or(0.0),
177             total.examples_percentage().unwrap_or(0.0),
178         );
179         print_table_line();
180     }
181 }
182
183 impl fold::DocFolder for CoverageCalculator {
184     fn fold_item(&mut self, i: clean::Item) -> Option<clean::Item> {
185         match i.inner {
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
189                 return Some(i);
190             }
191             clean::StrippedItem(..) => {
192                 // don't count items in stripped modules
193                 return Some(i);
194             }
195             clean::ImportItem(..) | clean::ExternCrateItem(..) => {
196                 // docs on `use` and `extern crate` statements are not displayed, so they're not
197                 // worth counting
198                 return Some(i);
199             }
200             clean::ImplItem(ref impl_)
201                 if i.attrs
202                     .other_attrs
203                     .iter()
204                     .any(|item| item.has_name(sym::automatically_derived))
205                     || impl_.synthetic
206                     || impl_.blanket_impl.is_some() =>
207             {
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
211                 return Some(i);
212             }
213             clean::ImplItem(ref impl_) => {
214                 if let Some(ref tr) = impl_.trait_ {
215                     debug!(
216                         "impl {:#} for {:#} in {}",
217                         tr.print(),
218                         impl_.for_.print(),
219                         i.source.filename
220                     );
221
222                     // don't count trait impls, the missing-docs lint doesn't so we shouldn't
223                     // either
224                     return Some(i);
225                 } else {
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
228                     // impl block
229                     debug!("impl {:#} in {}", impl_.for_.print(), i.source.filename);
230                 }
231             }
232             _ => {
233                 let has_docs = !i.attrs.doc_strings.is_empty();
234                 let mut tests = Tests { found_tests: 0 };
235
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(_)
244                 );
245                 find_testable_code(
246                     &i.attrs.doc_strings.iter().map(|d| d.as_str()).collect::<Vec<_>>().join("\n"),
247                     &mut tests,
248                     ErrorCodes::No,
249                     false,
250                     None,
251                 );
252
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(
256                     has_docs,
257                     has_doc_example,
258                     should_have_doc_examples,
259                 );
260             }
261         }
262
263         self.fold_item_recur(i)
264     }
265 }