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