rustdoc/passes/
calculate_doc_coverage.rs1use std::collections::BTreeMap;
4use std::ops;
5
6use rustc_hir as hir;
7use rustc_lint::builtin::MISSING_DOCS;
8use rustc_middle::lint::LintLevelSource;
9use rustc_span::{FileName, RemapPathScopeComponents};
10use serde::Serialize;
11use tracing::debug;
12
13use crate::clean;
14use crate::config::OutputFormat;
15use crate::core::DocContext;
16use crate::html::markdown::{ErrorCodes, find_testable_code};
17use crate::passes::Pass;
18use crate::passes::check_doc_test_visibility::{Tests, should_have_doc_example};
19use crate::visit::DocVisitor;
20
21pub(crate) const CALCULATE_DOC_COVERAGE: Pass = Pass {
22 name: "calculate-doc-coverage",
23 run: Some(calculate_doc_coverage),
24 description: "counts the number of items with and without documentation",
25};
26
27fn calculate_doc_coverage(krate: clean::Crate, ctx: &mut DocContext<'_>) -> clean::Crate {
28 let mut calc = CoverageCalculator { items: Default::default(), ctx };
29 calc.visit_crate(&krate);
30
31 calc.print_results();
32
33 krate
34}
35
36#[derive(Default, Copy, Clone, Serialize, Debug)]
37struct ItemCount {
38 total: u64,
39 with_docs: u64,
40 total_examples: u64,
41 with_examples: u64,
42}
43
44impl ItemCount {
45 fn count_item(
46 &mut self,
47 has_docs: bool,
48 has_doc_example: bool,
49 should_have_doc_examples: bool,
50 should_have_docs: bool,
51 ) {
52 if has_docs || should_have_docs {
53 self.total += 1;
54 }
55
56 if has_docs {
57 self.with_docs += 1;
58 }
59 if should_have_doc_examples || has_doc_example {
60 self.total_examples += 1;
61 }
62 if has_doc_example {
63 self.with_examples += 1;
64 }
65 }
66
67 fn percentage(&self) -> Option<f64> {
68 if self.total > 0 {
69 Some((self.with_docs as f64 * 100.0) / self.total as f64)
70 } else {
71 None
72 }
73 }
74
75 fn examples_percentage(&self) -> Option<f64> {
76 if self.total_examples > 0 {
77 Some((self.with_examples as f64 * 100.0) / self.total_examples as f64)
78 } else {
79 None
80 }
81 }
82}
83
84impl ops::Sub for ItemCount {
85 type Output = Self;
86
87 fn sub(self, rhs: Self) -> Self {
88 ItemCount {
89 total: self.total - rhs.total,
90 with_docs: self.with_docs - rhs.with_docs,
91 total_examples: self.total_examples - rhs.total_examples,
92 with_examples: self.with_examples - rhs.with_examples,
93 }
94 }
95}
96
97impl ops::AddAssign for ItemCount {
98 fn add_assign(&mut self, rhs: Self) {
99 self.total += rhs.total;
100 self.with_docs += rhs.with_docs;
101 self.total_examples += rhs.total_examples;
102 self.with_examples += rhs.with_examples;
103 }
104}
105
106struct CoverageCalculator<'a, 'b> {
107 items: BTreeMap<FileName, ItemCount>,
108 ctx: &'a mut DocContext<'b>,
109}
110
111fn limit_filename_len(filename: String) -> String {
112 let nb_chars = filename.chars().count();
113 if nb_chars > 35 {
114 "...".to_string()
115 + &filename[filename.char_indices().nth(nb_chars - 32).map(|x| x.0).unwrap_or(0)..]
116 } else {
117 filename
118 }
119}
120
121impl CoverageCalculator<'_, '_> {
122 fn to_json(&self) -> String {
123 serde_json::to_string(
124 &self
125 .items
126 .iter()
127 .map(|(k, v)| (k.display(RemapPathScopeComponents::COVERAGE).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.output_format;
135 if output_format == OutputFormat::CoverageJson {
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 "| {name:<35} | {with_docs:>10} | {percentage:>9.1}% | {with_examples:>10} | \
153 {examples_percentage:>9.1}% |",
154 with_docs = count.with_docs,
155 with_examples = count.with_examples,
156 );
157 }
158
159 print_table_line();
160 println!(
161 "| {:<35} | {:>10} | {:>10} | {:>10} | {:>10} |",
162 "File", "Documented", "Percentage", "Examples", "Percentage",
163 );
164 print_table_line();
165
166 for (file, &count) in &self.items {
167 if let Some(percentage) = count.percentage() {
168 print_table_record(
169 &limit_filename_len(
170 file.display(RemapPathScopeComponents::COVERAGE).to_string(),
171 ),
172 count,
173 percentage,
174 count.examples_percentage().unwrap_or(0.),
175 );
176
177 total += count;
178 }
179 }
180
181 print_table_line();
182 print_table_record(
183 "Total",
184 total,
185 total.percentage().unwrap_or(0.0),
186 total.examples_percentage().unwrap_or(0.0),
187 );
188 print_table_line();
189 }
190}
191
192impl DocVisitor<'_> for CoverageCalculator<'_, '_> {
193 fn visit_item(&mut self, i: &clean::Item) {
194 if !i.item_id.is_local() {
195 return;
198 }
199
200 match i.kind {
201 clean::StrippedItem(..) => {
202 return;
204 }
205 clean::PlaceholderImplItem => {
206 return;
208 }
209 clean::ImportItem(..) | clean::ExternCrateItem { .. } => {}
212 clean::ImplItem(_) => {}
216 _ => {
217 let has_docs = !i.attrs.doc_strings.is_empty();
218 let mut tests = Tests { found_tests: 0 };
219
220 find_testable_code(&i.doc_value(), &mut tests, ErrorCodes::No, None);
221
222 let has_doc_example = tests.found_tests != 0;
223 let hir_id = DocContext::as_local_hir_id(self.ctx.tcx, i.item_id).unwrap();
224 let level_spec = self.ctx.tcx.lint_level_spec_at_node(MISSING_DOCS, hir_id);
225
226 let should_be_ignored = i
237 .item_id
238 .as_def_id()
239 .and_then(|def_id| self.ctx.tcx.opt_parent(def_id))
240 .and_then(|def_id| self.ctx.tcx.hir_get_if_local(def_id))
241 .map(|node| {
242 matches!(
243 node,
244 hir::Node::Variant(hir::Variant {
245 data: hir::VariantData::Tuple(_, _, _),
246 ..
247 }) | hir::Node::Item(hir::Item {
248 kind: hir::ItemKind::Struct(_, _, hir::VariantData::Tuple(_, _, _)),
249 ..
250 })
251 )
252 })
253 .unwrap_or(false);
254
255 let should_have_docs = !should_be_ignored
259 && (!level_spec.is_allow()
260 || matches!(level_spec.src, LintLevelSource::Default));
261
262 if let Some(span) = i.span(self.ctx.tcx) {
263 let filename = span.filename(self.ctx.sess());
264 debug!("counting {:?} {:?} in {filename:?}", i.type_(), i.name);
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
275 self.visit_item_recur(i)
276 }
277}