1use std::collections::BTreeMap;
4use std::ops;
5
6use rustc_hir as hir;
7use rustc_lint::builtin::MISSING_DOCS;
8use rustc_middle::lint::{LevelAndSource, LintLevelSource};
9use rustc_session::lint;
10use rustc_span::{FileName, RemapPathScopeComponents};
11use serde::Serialize;
12use tracing::debug;
13
14use crate::clean;
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.is_json() {
137 println!("{}", self.to_json());
138 return;
139 }
140 let mut total = ItemCount::default();
141
142 fn print_table_line() {
143 println!("+-{0:->35}-+-{0:->10}-+-{0:->10}-+-{0:->10}-+-{0:->10}-+", "");
144 }
145
146 fn print_table_record(
147 name: &str,
148 count: ItemCount,
149 percentage: f64,
150 examples_percentage: f64,
151 ) {
152 println!(
153 "| {name:<35} | {with_docs:>10} | {percentage:>9.1}% | {with_examples:>10} | \
154 {examples_percentage:>9.1}% |",
155 with_docs = count.with_docs,
156 with_examples = count.with_examples,
157 );
158 }
159
160 print_table_line();
161 println!(
162 "| {:<35} | {:>10} | {:>10} | {:>10} | {:>10} |",
163 "File", "Documented", "Percentage", "Examples", "Percentage",
164 );
165 print_table_line();
166
167 for (file, &count) in &self.items {
168 if let Some(percentage) = count.percentage() {
169 print_table_record(
170 &limit_filename_len(
171 file.display(RemapPathScopeComponents::COVERAGE).to_string(),
172 ),
173 count,
174 percentage,
175 count.examples_percentage().unwrap_or(0.),
176 );
177
178 total += count;
179 }
180 }
181
182 print_table_line();
183 print_table_record(
184 "Total",
185 total,
186 total.percentage().unwrap_or(0.0),
187 total.examples_percentage().unwrap_or(0.0),
188 );
189 print_table_line();
190 }
191}
192
193impl DocVisitor<'_> for CoverageCalculator<'_, '_> {
194 fn visit_item(&mut self, i: &clean::Item) {
195 if !i.item_id.is_local() {
196 return;
199 }
200
201 match i.kind {
202 clean::StrippedItem(..) => {
203 return;
205 }
206 clean::ImportItem(..) | clean::ExternCrateItem { .. } => {}
209 clean::ImplItem(_) => {}
213 _ => {
214 let has_docs = !i.attrs.doc_strings.is_empty();
215 let mut tests = Tests { found_tests: 0 };
216
217 find_testable_code(&i.doc_value(), &mut tests, ErrorCodes::No, None);
218
219 let has_doc_example = tests.found_tests != 0;
220 let hir_id = DocContext::as_local_hir_id(self.ctx.tcx, i.item_id).unwrap();
221 let LevelAndSource { level, src, .. } =
222 self.ctx.tcx.lint_level_at_node(MISSING_DOCS, hir_id);
223
224 let should_be_ignored = i
235 .item_id
236 .as_def_id()
237 .and_then(|def_id| self.ctx.tcx.opt_parent(def_id))
238 .and_then(|def_id| self.ctx.tcx.hir_get_if_local(def_id))
239 .map(|node| {
240 matches!(
241 node,
242 hir::Node::Variant(hir::Variant {
243 data: hir::VariantData::Tuple(_, _, _),
244 ..
245 }) | hir::Node::Item(hir::Item {
246 kind: hir::ItemKind::Struct(_, _, hir::VariantData::Tuple(_, _, _)),
247 ..
248 })
249 )
250 })
251 .unwrap_or(false);
252
253 let should_have_docs = !should_be_ignored
257 && (level != lint::Level::Allow || matches!(src, LintLevelSource::Default));
258
259 if let Some(span) = i.span(self.ctx.tcx) {
260 let filename = span.filename(self.ctx.sess());
261 debug!("counting {:?} {:?} in {filename:?}", i.type_(), i.name);
262 self.items.entry(filename).or_default().count_item(
263 has_docs,
264 has_doc_example,
265 should_have_doc_example(self.ctx, i),
266 should_have_docs,
267 );
268 }
269 }
270 }
271
272 self.visit_item_recur(i)
273 }
274}