]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/passes/calculate_doc_coverage.rs
Auto merge of #81507 - weiznich:add_diesel_to_cargo_test, r=Mark-Simulacrum
[rust.git] / src / librustdoc / passes / calculate_doc_coverage.rs
1 use crate::clean;
2 use crate::core::DocContext;
3 use crate::fold::{self, DocFolder};
4 use crate::html::markdown::{find_testable_code, ErrorCodes};
5 use crate::passes::doc_test_lints::{should_have_doc_example, Tests};
6 use crate::passes::Pass;
7 use rustc_lint::builtin::MISSING_DOCS;
8 use rustc_middle::lint::LintLevelSource;
9 use rustc_session::lint;
10 use rustc_span::symbol::sym;
11 use rustc_span::FileName;
12 use serde::Serialize;
13
14 use std::collections::BTreeMap;
15 use std::ops;
16
17 crate const CALCULATE_DOC_COVERAGE: Pass = Pass {
18     name: "calculate-doc-coverage",
19     run: calculate_doc_coverage,
20     description: "counts the number of items with and without documentation",
21 };
22
23 fn calculate_doc_coverage(krate: clean::Crate, ctx: &mut DocContext<'_>) -> clean::Crate {
24     let mut calc = CoverageCalculator { items: Default::default(), ctx };
25     let krate = calc.fold_crate(krate);
26
27     calc.print_results();
28
29     krate
30 }
31
32 #[derive(Default, Copy, Clone, Serialize, Debug)]
33 struct ItemCount {
34     total: u64,
35     with_docs: u64,
36     total_examples: u64,
37     with_examples: u64,
38 }
39
40 impl ItemCount {
41     fn count_item(
42         &mut self,
43         has_docs: bool,
44         has_doc_example: bool,
45         should_have_doc_examples: bool,
46         should_have_docs: bool,
47     ) {
48         if has_docs || should_have_docs {
49             self.total += 1;
50         }
51
52         if has_docs {
53             self.with_docs += 1;
54         }
55         if should_have_doc_examples || has_doc_example {
56             self.total_examples += 1;
57         }
58         if has_doc_example {
59             self.with_examples += 1;
60         }
61     }
62
63     fn percentage(&self) -> Option<f64> {
64         if self.total > 0 {
65             Some((self.with_docs as f64 * 100.0) / self.total as f64)
66         } else {
67             None
68         }
69     }
70
71     fn examples_percentage(&self) -> Option<f64> {
72         if self.total_examples > 0 {
73             Some((self.with_examples as f64 * 100.0) / self.total_examples as f64)
74         } else {
75             None
76         }
77     }
78 }
79
80 impl ops::Sub for ItemCount {
81     type Output = Self;
82
83     fn sub(self, rhs: Self) -> Self {
84         ItemCount {
85             total: self.total - rhs.total,
86             with_docs: self.with_docs - rhs.with_docs,
87             total_examples: self.total_examples - rhs.total_examples,
88             with_examples: self.with_examples - rhs.with_examples,
89         }
90     }
91 }
92
93 impl ops::AddAssign for ItemCount {
94     fn add_assign(&mut self, rhs: Self) {
95         self.total += rhs.total;
96         self.with_docs += rhs.with_docs;
97         self.total_examples += rhs.total_examples;
98         self.with_examples += rhs.with_examples;
99     }
100 }
101
102 struct CoverageCalculator<'a, 'b> {
103     items: BTreeMap<FileName, ItemCount>,
104     ctx: &'a mut DocContext<'b>,
105 }
106
107 fn limit_filename_len(filename: String) -> String {
108     let nb_chars = filename.chars().count();
109     if nb_chars > 35 {
110         "...".to_string()
111             + &filename[filename.char_indices().nth(nb_chars - 32).map(|x| x.0).unwrap_or(0)..]
112     } else {
113         filename
114     }
115 }
116
117 impl<'a, 'b> CoverageCalculator<'a, 'b> {
118     fn to_json(&self) -> String {
119         serde_json::to_string(
120             &self
121                 .items
122                 .iter()
123                 .map(|(k, v)| (k.to_string(), v))
124                 .collect::<BTreeMap<String, &ItemCount>>(),
125         )
126         .expect("failed to convert JSON data to string")
127     }
128
129     fn print_results(&self) {
130         let output_format = self.ctx.output_format;
131         if output_format.is_json() {
132             println!("{}", self.to_json());
133             return;
134         }
135         let mut total = ItemCount::default();
136
137         fn print_table_line() {
138             println!("+-{0:->35}-+-{0:->10}-+-{0:->10}-+-{0:->10}-+-{0:->10}-+", "");
139         }
140
141         fn print_table_record(
142             name: &str,
143             count: ItemCount,
144             percentage: f64,
145             examples_percentage: f64,
146         ) {
147             println!(
148                 "| {:<35} | {:>10} | {:>9.1}% | {:>10} | {:>9.1}% |",
149                 name, count.with_docs, percentage, count.with_examples, examples_percentage,
150             );
151         }
152
153         print_table_line();
154         println!(
155             "| {:<35} | {:>10} | {:>10} | {:>10} | {:>10} |",
156             "File", "Documented", "Percentage", "Examples", "Percentage",
157         );
158         print_table_line();
159
160         for (file, &count) in &self.items {
161             if let Some(percentage) = count.percentage() {
162                 print_table_record(
163                     &limit_filename_len(file.to_string()),
164                     count,
165                     percentage,
166                     count.examples_percentage().unwrap_or(0.),
167                 );
168
169                 total += count;
170             }
171         }
172
173         print_table_line();
174         print_table_record(
175             "Total",
176             total,
177             total.percentage().unwrap_or(0.0),
178             total.examples_percentage().unwrap_or(0.0),
179         );
180         print_table_line();
181     }
182 }
183
184 impl<'a, 'b> fold::DocFolder for CoverageCalculator<'a, 'b> {
185     fn fold_item(&mut self, i: clean::Item) -> Option<clean::Item> {
186         match *i.kind {
187             _ if !i.def_id.is_local() => {
188                 // non-local items are skipped because they can be out of the users control,
189                 // especially in the case of trait impls, which rustdoc eagerly inlines
190                 return Some(i);
191             }
192             clean::StrippedItem(..) => {
193                 // don't count items in stripped modules
194                 return Some(i);
195             }
196             clean::ImportItem(..) | clean::ExternCrateItem { .. } => {
197                 // docs on `use` and `extern crate` statements are not displayed, so they're not
198                 // worth counting
199                 return Some(i);
200             }
201             clean::ImplItem(ref impl_)
202                 if i.attrs
203                     .other_attrs
204                     .iter()
205                     .any(|item| item.has_name(sym::automatically_derived))
206                     || impl_.synthetic
207                     || impl_.blanket_impl.is_some() =>
208             {
209                 // built-in derives get the `#[automatically_derived]` attribute, and
210                 // synthetic/blanket impls are made up by rustdoc and can't be documented
211                 // FIXME(misdreavus): need to also find items that came out of a derive macro
212                 return Some(i);
213             }
214             clean::ImplItem(ref impl_) => {
215                 let filename = i.span.filename(self.ctx.sess());
216                 if let Some(ref tr) = impl_.trait_ {
217                     debug!(
218                         "impl {:#} for {:#} in {}",
219                         tr.print(&self.ctx.cache, self.ctx.tcx),
220                         impl_.for_.print(&self.ctx.cache, self.ctx.tcx),
221                         filename,
222                     );
223
224                     // don't count trait impls, the missing-docs lint doesn't so we shouldn't
225                     // either
226                     return Some(i);
227                 } else {
228                     // inherent impls *can* be documented, and those docs show up, but in most
229                     // cases it doesn't make sense, as all methods on a type are in one single
230                     // impl block
231                     debug!(
232                         "impl {:#} in {}",
233                         impl_.for_.print(&self.ctx.cache, self.ctx.tcx),
234                         filename
235                     );
236                 }
237             }
238             _ => {
239                 let has_docs = !i.attrs.doc_strings.is_empty();
240                 let mut tests = Tests { found_tests: 0 };
241
242                 find_testable_code(
243                     &i.attrs.collapsed_doc_value().unwrap_or_default(),
244                     &mut tests,
245                     ErrorCodes::No,
246                     false,
247                     None,
248                 );
249
250                 let filename = i.span.filename(self.ctx.sess());
251                 let has_doc_example = tests.found_tests != 0;
252                 let hir_id = self.ctx.tcx.hir().local_def_id_to_hir_id(i.def_id.expect_local());
253                 let (level, source) = self.ctx.tcx.lint_level_at_node(MISSING_DOCS, hir_id);
254                 // `missing_docs` is allow-by-default, so don't treat this as ignoring the item
255                 // unless the user had an explicit `allow`
256                 let should_have_docs =
257                     level != lint::Level::Allow || matches!(source, LintLevelSource::Default);
258                 debug!("counting {:?} {:?} in {}", i.type_(), i.name, filename);
259                 self.items.entry(filename).or_default().count_item(
260                     has_docs,
261                     has_doc_example,
262                     should_have_doc_example(self.ctx, &i),
263                     should_have_docs,
264                 );
265             }
266         }
267
268         Some(self.fold_item_recur(i))
269     }
270 }