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