rustc_mir_transform/coverage/spans.rs
1use std::collections::VecDeque;
2
3use rustc_data_structures::fx::FxHashSet;
4use rustc_middle::mir;
5use rustc_span::{DesugaringKind, ExpnKind, MacroKind, Span};
6use tracing::{debug, debug_span, instrument};
7
8use crate::coverage::graph::{BasicCoverageBlock, CoverageGraph};
9use crate::coverage::spans::from_mir::{
10 ExtractedCovspans, Hole, SpanFromMir, extract_covspans_from_mir,
11};
12use crate::coverage::{ExtractedHirInfo, mappings};
13
14mod from_mir;
15
16pub(super) fn extract_refined_covspans(
17 mir_body: &mir::Body<'_>,
18 hir_info: &ExtractedHirInfo,
19 graph: &CoverageGraph,
20 code_mappings: &mut impl Extend<mappings::CodeMapping>,
21) {
22 let ExtractedCovspans { mut covspans } = extract_covspans_from_mir(mir_body, hir_info, graph);
23
24 // First, perform the passes that need macro information.
25 covspans.sort_by(|a, b| graph.cmp_in_dominator_order(a.bcb, b.bcb));
26 remove_unwanted_expansion_spans(&mut covspans);
27 split_visible_macro_spans(&mut covspans);
28
29 // We no longer need the extra information in `SpanFromMir`, so convert to `Covspan`.
30 let mut covspans = covspans.into_iter().map(SpanFromMir::into_covspan).collect::<Vec<_>>();
31
32 let compare_covspans = |a: &Covspan, b: &Covspan| {
33 compare_spans(a.span, b.span)
34 // After deduplication, we want to keep only the most-dominated BCB.
35 .then_with(|| graph.cmp_in_dominator_order(a.bcb, b.bcb).reverse())
36 };
37 covspans.sort_by(compare_covspans);
38
39 // Among covspans with the same span, keep only one,
40 // preferring the one with the most-dominated BCB.
41 // (Ideally we should try to preserve _all_ non-dominating BCBs, but that
42 // requires a lot more complexity in the span refiner, for little benefit.)
43 covspans.dedup_by(|b, a| a.span.source_equal(b.span));
44
45 // Sort the holes, and merge overlapping/adjacent holes.
46 let mut holes = hir_info.hole_spans.iter().map(|&span| Hole { span }).collect::<Vec<_>>();
47 holes.sort_by(|a, b| compare_spans(a.span, b.span));
48 holes.dedup_by(|b, a| a.merge_if_overlapping_or_adjacent(b));
49
50 // Split the covspans into separate buckets that don't overlap any holes.
51 let buckets = divide_spans_into_buckets(covspans, &holes);
52
53 for mut covspans in buckets {
54 // Make sure each individual bucket is internally sorted.
55 covspans.sort_by(compare_covspans);
56 let _span = debug_span!("processing bucket", ?covspans).entered();
57
58 let mut covspans = remove_unwanted_overlapping_spans(covspans);
59 debug!(?covspans, "after removing overlaps");
60
61 // Do one last merge pass, to simplify the output.
62 covspans.dedup_by(|b, a| a.merge_if_eligible(b));
63 debug!(?covspans, "after merge");
64
65 code_mappings.extend(covspans.into_iter().map(|Covspan { span, bcb }| {
66 // Each span produced by the refiner represents an ordinary code region.
67 mappings::CodeMapping { span, bcb }
68 }));
69 }
70}
71
72/// Macros that expand into branches (e.g. `assert!`, `trace!`) tend to generate
73/// multiple condition/consequent blocks that have the span of the whole macro
74/// invocation, which is unhelpful. Keeping only the first such span seems to
75/// give better mappings, so remove the others.
76///
77/// Similarly, `await` expands to a branch on the discriminant of `Poll`, which
78/// leads to incorrect coverage if the `Future` is immediately ready (#98712).
79///
80/// (The input spans should be sorted in BCB dominator order, so that the
81/// retained "first" span is likely to dominate the others.)
82fn remove_unwanted_expansion_spans(covspans: &mut Vec<SpanFromMir>) {
83 let mut deduplicated_spans = FxHashSet::default();
84
85 covspans.retain(|covspan| {
86 match covspan.expn_kind {
87 // Retain only the first await-related or macro-expanded covspan with this span.
88 Some(ExpnKind::Desugaring(DesugaringKind::Await)) => {
89 deduplicated_spans.insert(covspan.span)
90 }
91 Some(ExpnKind::Macro(MacroKind::Bang, _)) => deduplicated_spans.insert(covspan.span),
92 // Ignore (retain) other spans.
93 _ => true,
94 }
95 });
96}
97
98/// When a span corresponds to a macro invocation that is visible from the
99/// function body, split it into two parts. The first part covers just the
100/// macro name plus `!`, and the second part covers the rest of the macro
101/// invocation. This seems to give better results for code that uses macros.
102fn split_visible_macro_spans(covspans: &mut Vec<SpanFromMir>) {
103 let mut extra_spans = vec![];
104
105 covspans.retain(|covspan| {
106 let Some(ExpnKind::Macro(MacroKind::Bang, visible_macro)) = covspan.expn_kind else {
107 return true;
108 };
109
110 let split_len = visible_macro.as_str().len() as u32 + 1;
111 let (before, after) = covspan.span.split_at(split_len);
112 if !covspan.span.contains(before) || !covspan.span.contains(after) {
113 // Something is unexpectedly wrong with the split point.
114 // The debug assertion in `split_at` will have already caught this,
115 // but in release builds it's safer to do nothing and maybe get a
116 // bug report for unexpected coverage, rather than risk an ICE.
117 return true;
118 }
119
120 extra_spans.push(SpanFromMir::new(before, covspan.expn_kind.clone(), covspan.bcb));
121 extra_spans.push(SpanFromMir::new(after, covspan.expn_kind.clone(), covspan.bcb));
122 false // Discard the original covspan that we just split.
123 });
124
125 // The newly-split spans are added at the end, so any previous sorting
126 // is not preserved.
127 covspans.extend(extra_spans);
128}
129
130/// Uses the holes to divide the given covspans into buckets, such that:
131/// - No span in any hole overlaps a bucket (truncating the spans if necessary).
132/// - The spans in each bucket are strictly after all spans in previous buckets,
133/// and strictly before all spans in subsequent buckets.
134///
135/// The resulting buckets are sorted relative to each other, but might not be
136/// internally sorted.
137#[instrument(level = "debug")]
138fn divide_spans_into_buckets(input_covspans: Vec<Covspan>, holes: &[Hole]) -> Vec<Vec<Covspan>> {
139 debug_assert!(input_covspans.is_sorted_by(|a, b| compare_spans(a.span, b.span).is_le()));
140 debug_assert!(holes.is_sorted_by(|a, b| compare_spans(a.span, b.span).is_le()));
141
142 // Now we're ready to start carving holes out of the initial coverage spans,
143 // and grouping them in buckets separated by the holes.
144
145 let mut input_covspans = VecDeque::from(input_covspans);
146 let mut fragments = vec![];
147
148 // For each hole:
149 // - Identify the spans that are entirely or partly before the hole.
150 // - Put those spans in a corresponding bucket, truncated to the start of the hole.
151 // - If one of those spans also extends after the hole, put the rest of it
152 // in a "fragments" vector that is processed by the next hole.
153 let mut buckets = (0..holes.len()).map(|_| vec![]).collect::<Vec<_>>();
154 for (hole, bucket) in holes.iter().zip(&mut buckets) {
155 let fragments_from_prev = std::mem::take(&mut fragments);
156
157 // Only inspect spans that precede or overlap this hole,
158 // leaving the rest to be inspected by later holes.
159 // (This relies on the spans and holes both being sorted.)
160 let relevant_input_covspans =
161 drain_front_while(&mut input_covspans, |c| c.span.lo() < hole.span.hi());
162
163 for covspan in fragments_from_prev.into_iter().chain(relevant_input_covspans) {
164 let (before, after) = covspan.split_around_hole_span(hole.span);
165 bucket.extend(before);
166 fragments.extend(after);
167 }
168 }
169
170 // After finding the spans before each hole, any remaining fragments/spans
171 // form their own final bucket, after the final hole.
172 // (If there were no holes, this will just be all of the initial spans.)
173 fragments.extend(input_covspans);
174 buckets.push(fragments);
175
176 buckets
177}
178
179/// Similar to `.drain(..)`, but stops just before it would remove an item not
180/// satisfying the predicate.
181fn drain_front_while<'a, T>(
182 queue: &'a mut VecDeque<T>,
183 mut pred_fn: impl FnMut(&T) -> bool,
184) -> impl Iterator<Item = T> {
185 std::iter::from_fn(move || if pred_fn(queue.front()?) { queue.pop_front() } else { None })
186}
187
188/// Takes one of the buckets of (sorted) spans extracted from MIR, and "refines"
189/// those spans by removing spans that overlap in unwanted ways.
190#[instrument(level = "debug")]
191fn remove_unwanted_overlapping_spans(sorted_spans: Vec<Covspan>) -> Vec<Covspan> {
192 debug_assert!(sorted_spans.is_sorted_by(|a, b| compare_spans(a.span, b.span).is_le()));
193
194 // Holds spans that have been read from the input vector, but haven't yet
195 // been committed to the output vector.
196 let mut pending = vec![];
197 let mut refined = vec![];
198
199 for curr in sorted_spans {
200 pending.retain(|prev: &Covspan| {
201 if prev.span.hi() <= curr.span.lo() {
202 // There's no overlap between the previous/current covspans,
203 // so move the previous one into the refined list.
204 refined.push(prev.clone());
205 false
206 } else {
207 // Otherwise, retain the previous covspan only if it has the
208 // same BCB. This tends to discard long outer spans that enclose
209 // smaller inner spans with different control flow.
210 prev.bcb == curr.bcb
211 }
212 });
213 pending.push(curr);
214 }
215
216 // Drain the rest of the pending list into the refined list.
217 refined.extend(pending);
218 refined
219}
220
221#[derive(Clone, Debug)]
222struct Covspan {
223 span: Span,
224 bcb: BasicCoverageBlock,
225}
226
227impl Covspan {
228 /// Splits this covspan into 0-2 parts:
229 /// - The part that is strictly before the hole span, if any.
230 /// - The part that is strictly after the hole span, if any.
231 fn split_around_hole_span(&self, hole_span: Span) -> (Option<Self>, Option<Self>) {
232 let before = try {
233 let span = self.span.trim_end(hole_span)?;
234 Self { span, ..*self }
235 };
236 let after = try {
237 let span = self.span.trim_start(hole_span)?;
238 Self { span, ..*self }
239 };
240
241 (before, after)
242 }
243
244 /// If `self` and `other` can be merged (i.e. they have the same BCB),
245 /// mutates `self.span` to also include `other.span` and returns true.
246 ///
247 /// Note that compatible covspans can be merged even if their underlying
248 /// spans are not overlapping/adjacent; any space between them will also be
249 /// part of the merged covspan.
250 fn merge_if_eligible(&mut self, other: &Self) -> bool {
251 if self.bcb != other.bcb {
252 return false;
253 }
254
255 self.span = self.span.to(other.span);
256 true
257 }
258}
259
260/// Compares two spans in (lo ascending, hi descending) order.
261fn compare_spans(a: Span, b: Span) -> std::cmp::Ordering {
262 // First sort by span start.
263 Ord::cmp(&a.lo(), &b.lo())
264 // If span starts are the same, sort by span end in reverse order.
265 // This ensures that if spans A and B are adjacent in the list,
266 // and they overlap but are not equal, then either:
267 // - Span A extends further left, or
268 // - Both have the same start and span A extends further right
269 .then_with(|| Ord::cmp(&a.hi(), &b.hi()).reverse())
270}