]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/passes/calculate_doc_coverage.rs
Merge branch 'master' into feature/incorporate-tracing
[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::passes::Pass;
6
7 use rustc_span::symbol::sym;
8 use rustc_span::FileName;
9 use serde::Serialize;
10
11 use std::collections::BTreeMap;
12 use std::ops;
13
14 pub const CALCULATE_DOC_COVERAGE: Pass = Pass {
15     name: "calculate-doc-coverage",
16     run: calculate_doc_coverage,
17     description: "counts the number of items with and without documentation",
18 };
19
20 fn calculate_doc_coverage(krate: clean::Crate, ctx: &DocContext<'_>) -> clean::Crate {
21     let mut calc = CoverageCalculator::new();
22     let krate = calc.fold_crate(krate);
23
24     calc.print_results(ctx.renderinfo.borrow().output_format);
25
26     krate
27 }
28
29 #[derive(Default, Copy, Clone, Serialize)]
30 struct ItemCount {
31     total: u64,
32     with_docs: u64,
33 }
34
35 impl ItemCount {
36     fn count_item(&mut self, has_docs: bool) {
37         self.total += 1;
38
39         if has_docs {
40             self.with_docs += 1;
41         }
42     }
43
44     fn percentage(&self) -> Option<f64> {
45         if self.total > 0 {
46             Some((self.with_docs as f64 * 100.0) / self.total as f64)
47         } else {
48             None
49         }
50     }
51 }
52
53 impl ops::Sub for ItemCount {
54     type Output = Self;
55
56     fn sub(self, rhs: Self) -> Self {
57         ItemCount { total: self.total - rhs.total, with_docs: self.with_docs - rhs.with_docs }
58     }
59 }
60
61 impl ops::AddAssign for ItemCount {
62     fn add_assign(&mut self, rhs: Self) {
63         self.total += rhs.total;
64         self.with_docs += rhs.with_docs;
65     }
66 }
67
68 struct CoverageCalculator {
69     items: BTreeMap<FileName, ItemCount>,
70 }
71
72 fn limit_filename_len(filename: String) -> String {
73     let nb_chars = filename.chars().count();
74     if nb_chars > 35 {
75         "...".to_string()
76             + &filename[filename.char_indices().nth(nb_chars - 32).map(|x| x.0).unwrap_or(0)..]
77     } else {
78         filename
79     }
80 }
81
82 impl CoverageCalculator {
83     fn new() -> CoverageCalculator {
84         CoverageCalculator { items: Default::default() }
85     }
86
87     fn to_json(&self) -> String {
88         serde_json::to_string(
89             &self
90                 .items
91                 .iter()
92                 .map(|(k, v)| (k.to_string(), v))
93                 .collect::<BTreeMap<String, &ItemCount>>(),
94         )
95         .expect("failed to convert JSON data to string")
96     }
97
98     fn print_results(&self, output_format: Option<OutputFormat>) {
99         if output_format.map(|o| o.is_json()).unwrap_or_else(|| false) {
100             println!("{}", self.to_json());
101             return;
102         }
103         let mut total = ItemCount::default();
104
105         fn print_table_line() {
106             println!("+-{0:->35}-+-{0:->10}-+-{0:->10}-+-{0:->10}-+", "");
107         }
108
109         fn print_table_record(name: &str, count: ItemCount, percentage: f64) {
110             println!(
111                 "| {:<35} | {:>10} | {:>10} | {:>9.1}% |",
112                 name, count.with_docs, count.total, percentage
113             );
114         }
115
116         print_table_line();
117         println!(
118             "| {:<35} | {:>10} | {:>10} | {:>10} |",
119             "File", "Documented", "Total", "Percentage"
120         );
121         print_table_line();
122
123         for (file, &count) in &self.items {
124             if let Some(percentage) = count.percentage() {
125                 print_table_record(&limit_filename_len(file.to_string()), count, percentage);
126
127                 total += count;
128             }
129         }
130
131         print_table_line();
132         print_table_record("Total", total, total.percentage().unwrap_or(0.0));
133         print_table_line();
134     }
135 }
136
137 impl fold::DocFolder for CoverageCalculator {
138     fn fold_item(&mut self, i: clean::Item) -> Option<clean::Item> {
139         let has_docs = !i.attrs.doc_strings.is_empty();
140
141         match i.inner {
142             _ if !i.def_id.is_local() => {
143                 // non-local items are skipped because they can be out of the users control,
144                 // especially in the case of trait impls, which rustdoc eagerly inlines
145                 return Some(i);
146             }
147             clean::StrippedItem(..) => {
148                 // don't count items in stripped modules
149                 return Some(i);
150             }
151             clean::ImportItem(..) | clean::ExternCrateItem(..) => {
152                 // docs on `use` and `extern crate` statements are not displayed, so they're not
153                 // worth counting
154                 return Some(i);
155             }
156             clean::ImplItem(ref impl_)
157                 if i.attrs
158                     .other_attrs
159                     .iter()
160                     .any(|item| item.has_name(sym::automatically_derived))
161                     || impl_.synthetic
162                     || impl_.blanket_impl.is_some() =>
163             {
164                 // built-in derives get the `#[automatically_derived]` attribute, and
165                 // synthetic/blanket impls are made up by rustdoc and can't be documented
166                 // FIXME(misdreavus): need to also find items that came out of a derive macro
167                 return Some(i);
168             }
169             clean::ImplItem(ref impl_) => {
170                 if let Some(ref tr) = impl_.trait_ {
171                     debug!(
172                         "impl {:#} for {:#} in {}",
173                         tr.print(),
174                         impl_.for_.print(),
175                         i.source.filename
176                     );
177
178                     // don't count trait impls, the missing-docs lint doesn't so we shouldn't
179                     // either
180                     return Some(i);
181                 } else {
182                     // inherent impls *can* be documented, and those docs show up, but in most
183                     // cases it doesn't make sense, as all methods on a type are in one single
184                     // impl block
185                     debug!("impl {:#} in {}", impl_.for_.print(), i.source.filename);
186                 }
187             }
188             _ => {
189                 debug!("counting {:?} {:?} in {}", i.type_(), i.name, i.source.filename);
190                 self.items.entry(i.source.filename.clone()).or_default().count_item(has_docs);
191             }
192         }
193
194         self.fold_item_recur(i)
195     }
196 }