]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/passes/calculate_doc_coverage.rs
Auto merge of #91164 - Badel2:usefulness-stack-overflow, r=davidtwco
[rust.git] / src / librustdoc / passes / calculate_doc_coverage.rs
1 use crate::clean;
2 use crate::core::DocContext;
3 use crate::html::markdown::{find_testable_code, ErrorCodes};
4 use crate::passes::check_doc_test_visibility::{should_have_doc_example, Tests};
5 use crate::passes::Pass;
6 use crate::visit::DocVisitor;
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     calc.visit_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> DocVisitor for CoverageCalculator<'a, 'b> {
186     fn visit_item(&mut self, i: &clean::Item) {
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;
191         }
192
193         match *i.kind {
194             clean::StrippedItem(..) => {
195                 // don't count items in stripped modules
196                 return;
197             }
198             // docs on `use` and `extern crate` statements are not displayed, so they're not
199             // worth counting
200             clean::ImportItem(..) | clean::ExternCrateItem { .. } => {}
201             // Don't count trait impls, the missing-docs lint doesn't so we shouldn't either.
202             // Inherent impls *can* be documented, and those docs show up, but in most cases it
203             // doesn't make sense, as all methods on a type are in one single impl block
204             clean::ImplItem(_) => {}
205             _ => {
206                 let has_docs = !i.attrs.doc_strings.is_empty();
207                 let mut tests = Tests { found_tests: 0 };
208
209                 find_testable_code(
210                     &i.attrs.collapsed_doc_value().unwrap_or_default(),
211                     &mut tests,
212                     ErrorCodes::No,
213                     false,
214                     None,
215                 );
216
217                 let filename = i.span(self.ctx.tcx).filename(self.ctx.sess());
218                 let has_doc_example = tests.found_tests != 0;
219                 // The `expect_def_id()` should be okay because `local_def_id_to_hir_id`
220                 // would presumably panic if a fake `DefIndex` were passed.
221                 let hir_id = self
222                     .ctx
223                     .tcx
224                     .hir()
225                     .local_def_id_to_hir_id(i.def_id.expect_def_id().expect_local());
226                 let (level, source) = self.ctx.tcx.lint_level_at_node(MISSING_DOCS, hir_id);
227
228                 // In case we have:
229                 //
230                 // ```
231                 // enum Foo { Bar(u32) }
232                 // // or:
233                 // struct Bar(u32);
234                 // ```
235                 //
236                 // there is no need to require documentation on the fields of tuple variants and
237                 // tuple structs.
238                 let should_be_ignored = i
239                     .def_id
240                     .as_def_id()
241                     .and_then(|def_id| self.ctx.tcx.parent(def_id))
242                     .and_then(|def_id| self.ctx.tcx.hir().get_if_local(def_id))
243                     .map(|node| {
244                         matches!(
245                             node,
246                             hir::Node::Variant(hir::Variant {
247                                 data: hir::VariantData::Tuple(_, _),
248                                 ..
249                             }) | hir::Node::Item(hir::Item {
250                                 kind: hir::ItemKind::Struct(hir::VariantData::Tuple(_, _), _),
251                                 ..
252                             })
253                         )
254                     })
255                     .unwrap_or(false);
256
257                 // `missing_docs` is allow-by-default, so don't treat this as ignoring the item
258                 // unless the user had an explicit `allow`.
259                 //
260                 let should_have_docs = !should_be_ignored
261                     && (level != lint::Level::Allow || matches!(source, LintLevelSource::Default));
262
263                 debug!("counting {:?} {:?} in {:?}", i.type_(), i.name, filename);
264                 self.items.entry(filename).or_default().count_item(
265                     has_docs,
266                     has_doc_example,
267                     should_have_doc_example(self.ctx, &i),
268                     should_have_docs,
269                 );
270             }
271         }
272
273         self.visit_item_recur(i)
274     }
275 }