]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/passes/calculate_doc_coverage.rs
Update rustdoc coverage UI test
[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 {
51             self.total_examples += 1;
52             if has_doc_example {
53                 self.with_examples += 1;
54             }
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}-+-{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} | {:>10} | {:>9.1}% | {:>10} | {:>9.1}% |",
146                 name,
147                 count.with_docs,
148                 count.total,
149                 percentage,
150                 count.with_examples,
151                 examples_percentage,
152             );
153         }
154
155         print_table_line();
156         println!(
157             "| {:<35} | {:>10} | {:>10} | {:>10} | {:>10} | {:>10} |",
158             "File", "Documented", "Total", "Percentage", "Examples", "Percentage",
159         );
160         print_table_line();
161
162         for (file, &count) in &self.items {
163             if let (Some(percentage), Some(examples_percentage)) =
164                 (count.percentage(), count.examples_percentage())
165             {
166                 print_table_record(
167                     &limit_filename_len(file.to_string()),
168                     count,
169                     percentage,
170                     examples_percentage,
171                 );
172
173                 total += count;
174             }
175         }
176
177         print_table_line();
178         print_table_record(
179             "Total",
180             total,
181             total.percentage().unwrap_or(0.0),
182             total.examples_percentage().unwrap_or(0.0),
183         );
184         print_table_line();
185     }
186 }
187
188 impl fold::DocFolder for CoverageCalculator {
189     fn fold_item(&mut self, i: clean::Item) -> Option<clean::Item> {
190         match i.inner {
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
194                 return Some(i);
195             }
196             clean::StrippedItem(..) => {
197                 // don't count items in stripped modules
198                 return Some(i);
199             }
200             clean::ImportItem(..) | clean::ExternCrateItem(..) => {
201                 // docs on `use` and `extern crate` statements are not displayed, so they're not
202                 // worth counting
203                 return Some(i);
204             }
205             clean::ImplItem(ref impl_)
206                 if i.attrs
207                     .other_attrs
208                     .iter()
209                     .any(|item| item.has_name(sym::automatically_derived))
210                     || impl_.synthetic
211                     || impl_.blanket_impl.is_some() =>
212             {
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
216                 return Some(i);
217             }
218             clean::ImplItem(ref impl_) => {
219                 if let Some(ref tr) = impl_.trait_ {
220                     debug!(
221                         "impl {:#} for {:#} in {}",
222                         tr.print(),
223                         impl_.for_.print(),
224                         i.source.filename
225                     );
226
227                     // don't count trait impls, the missing-docs lint doesn't so we shouldn't
228                     // either
229                     return Some(i);
230                 } else {
231                     // inherent impls *can* be documented, and those docs show up, but in most
232                     // cases it doesn't make sense, as all methods on a type are in one single
233                     // impl block
234                     debug!("impl {:#} in {}", impl_.for_.print(), i.source.filename);
235                 }
236             }
237             _ => {
238                 let has_docs = !i.attrs.doc_strings.is_empty();
239                 let mut tests = Tests { found_tests: 0 };
240
241                 let should_have_doc_examples = !matches!(i.inner,
242                     clean::StructFieldItem(_)
243                     | clean::VariantItem(_)
244                     | clean::AssocConstItem(_, _)
245                     | clean::AssocTypeItem(_, _)
246                     | clean::TypedefItem(_, _)
247                     | clean::StaticItem(_)
248                     | clean::ConstantItem(_)
249                 );
250                 if should_have_doc_examples {
251                     find_testable_code(
252                         &i.attrs
253                             .doc_strings
254                             .iter()
255                             .map(|d| d.as_str())
256                             .collect::<Vec<_>>()
257                             .join("\n"),
258                         &mut tests,
259                         ErrorCodes::No,
260                         false,
261                         None,
262                     );
263                 }
264
265                 let has_doc_example = tests.found_tests != 0;
266                 debug!("counting {:?} {:?} in {}", i.type_(), i.name, i.source.filename);
267                 self.items.entry(i.source.filename.clone()).or_default().count_item(
268                     has_docs,
269                     has_doc_example,
270                     should_have_doc_examples,
271                 );
272             }
273         }
274
275         self.fold_item_recur(i)
276     }
277 }