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