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::core::DocContext;
15use crate::html::markdown::{ErrorCodes, find_testable_code};
16use crate::passes::Pass;
17use crate::passes::check_doc_test_visibility::{Tests, should_have_doc_example};
18use crate::visit::DocVisitor;
19
20pub(crate) const CALCULATE_DOC_COVERAGE: Pass = Pass {
21 name: "calculate-doc-coverage",
22 run: Some(calculate_doc_coverage),
23 description: "counts the number of items with and without documentation",
24};
25
26fn calculate_doc_coverage(krate: clean::Crate, ctx: &mut DocContext<'_>) -> clean::Crate {
27 let mut calc = CoverageCalculator { items: Default::default(), ctx };
28 calc.visit_crate(&krate);
29
30 calc.print_results();
31
32 krate
33}
34
35#[derive(Default, Copy, Clone, Serialize, Debug)]
36struct ItemCount {
37 total: u64,
38 with_docs: u64,
39 total_examples: u64,
40 with_examples: u64,
41}
42
43impl ItemCount {
44 fn count_item(
45 &mut self,
46 has_docs: bool,
47 has_doc_example: bool,
48 should_have_doc_examples: bool,
49 should_have_docs: bool,
50 ) {
51 if has_docs || should_have_docs {
52 self.total += 1;
53 }
54
55 if has_docs {
56 self.with_docs += 1;
57 }
58 if should_have_doc_examples || has_doc_example {
59 self.total_examples += 1;
60 }
61 if has_doc_example {
62 self.with_examples += 1;
63 }
64 }
65
66 fn percentage(&self) -> Option<f64> {
67 if self.total > 0 {
68 Some((self.with_docs as f64 * 100.0) / self.total as f64)
69 } else {
70 None
71 }
72 }
73
74 fn examples_percentage(&self) -> Option<f64> {
75 if self.total_examples > 0 {
76 Some((self.with_examples as f64 * 100.0) / self.total_examples as f64)
77 } else {
78 None
79 }
80 }
81}
82
83impl ops::Sub for ItemCount {
84 type Output = Self;
85
86 fn sub(self, rhs: Self) -> Self {
87 ItemCount {
88 total: self.total - rhs.total,
89 with_docs: self.with_docs - rhs.with_docs,
90 total_examples: self.total_examples - rhs.total_examples,
91 with_examples: self.with_examples - rhs.with_examples,
92 }
93 }
94}
95
96impl ops::AddAssign for ItemCount {
97 fn add_assign(&mut self, rhs: Self) {
98 self.total += rhs.total;
99 self.with_docs += rhs.with_docs;
100 self.total_examples += rhs.total_examples;
101 self.with_examples += rhs.with_examples;
102 }
103}
104
105struct CoverageCalculator<'a, 'b> {
106 items: BTreeMap<FileName, ItemCount>,
107 ctx: &'a mut DocContext<'b>,
108}
109
110fn limit_filename_len(filename: String) -> String {
111 let nb_chars = filename.chars().count();
112 if nb_chars > 35 {
113 "...".to_string()
114 + &filename[filename.char_indices().nth(nb_chars - 32).map(|x| x.0).unwrap_or(0)..]
115 } else {
116 filename
117 }
118}
119
120impl CoverageCalculator<'_, '_> {
121 fn to_json(&self) -> String {
122 serde_json::to_string(
123 &self
124 .items
125 .iter()
126 .map(|(k, v)| (k.display(RemapPathScopeComponents::COVERAGE).to_string(), v))
127 .collect::<BTreeMap<String, &ItemCount>>(),
128 )
129 .expect("failed to convert JSON data to string")
130 }
131
132 fn print_results(&self) {
133 let output_format = self.ctx.output_format;
134 if output_format.is_json() {
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}