]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/passes/calculate_doc_coverage.rs
remove unused return types such as empty Results or Options that would always be...
[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: &DocContext<'_>) -> clean::Crate {
24     let mut calc = CoverageCalculator::new(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 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 new(ctx: &'a DocContext<'b>) -> CoverageCalculator<'a, 'b> {
119         CoverageCalculator { items: Default::default(), ctx }
120     }
121
122     fn to_json(&self) -> String {
123         serde_json::to_string(
124             &self
125                 .items
126                 .iter()
127                 .map(|(k, v)| (k.to_string(), v))
128                 .collect::<BTreeMap<String, &ItemCount>>(),
129         )
130         .expect("failed to convert JSON data to string")
131     }
132
133     fn print_results(&self) {
134         let output_format = self.ctx.renderinfo.borrow().output_format;
135         if output_format.map(|o| o.is_json()).unwrap_or_else(|| false) {
136             println!("{}", self.to_json());
137             return;
138         }
139         let mut total = ItemCount::default();
140
141         fn print_table_line() {
142             println!("+-{0:->35}-+-{0:->10}-+-{0:->10}-+-{0:->10}-+-{0:->10}-+", "");
143         }
144
145         fn print_table_record(
146             name: &str,
147             count: ItemCount,
148             percentage: f64,
149             examples_percentage: f64,
150         ) {
151             println!(
152                 "| {:<35} | {:>10} | {:>9.1}% | {:>10} | {:>9.1}% |",
153                 name, count.with_docs, percentage, count.with_examples, examples_percentage,
154             );
155         }
156
157         print_table_line();
158         println!(
159             "| {:<35} | {:>10} | {:>10} | {:>10} | {:>10} |",
160             "File", "Documented", "Percentage", "Examples", "Percentage",
161         );
162         print_table_line();
163
164         for (file, &count) in &self.items {
165             if let Some(percentage) = count.percentage() {
166                 print_table_record(
167                     &limit_filename_len(file.to_string()),
168                     count,
169                     percentage,
170                     count.examples_percentage().unwrap_or(0.),
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<'a, 'b> fold::DocFolder for CoverageCalculator<'a, 'b> {
189     fn fold_item(&mut self, i: clean::Item) -> Option<clean::Item> {
190         match *i.kind {
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                 let filename = i.source.filename(self.ctx.sess());
220                 if let Some(ref tr) = impl_.trait_ {
221                     debug!("impl {:#} for {:#} in {}", tr.print(), impl_.for_.print(), filename,);
222
223                     // don't count trait impls, the missing-docs lint doesn't so we shouldn't
224                     // either
225                     return Some(i);
226                 } else {
227                     // inherent impls *can* be documented, and those docs show up, but in most
228                     // cases it doesn't make sense, as all methods on a type are in one single
229                     // impl block
230                     debug!("impl {:#} in {}", impl_.for_.print(), filename);
231                 }
232             }
233             _ => {
234                 let has_docs = !i.attrs.doc_strings.is_empty();
235                 let mut tests = Tests { found_tests: 0 };
236
237                 find_testable_code(
238                     &i.attrs
239                         .doc_strings
240                         .iter()
241                         .map(|d| d.doc.as_str())
242                         .collect::<Vec<_>>()
243                         .join("\n"),
244                     &mut tests,
245                     ErrorCodes::No,
246                     false,
247                     None,
248                 );
249
250                 let filename = i.source.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 }