@@ -9,6 +9,7 @@ use rustc_errors::{Applicability, DiagnosticBuilder, Level};
99use rustc_expand:: base:: * ;
1010use rustc_span:: symbol:: { sym, Ident , Symbol } ;
1111use rustc_span:: { ErrorGuaranteed , FileNameDisplayPreference , Span } ;
12+ use std:: assert_matches:: assert_matches;
1213use std:: iter;
1314use thin_vec:: { thin_vec, ThinVec } ;
1415
@@ -182,6 +183,16 @@ pub fn expand_test_or_bench(
182183 // creates $name: $expr
183184 let field = |name, expr| cx. field_imm ( sp, Ident :: from_str_and_span ( name, sp) , expr) ;
184185
186+ // Adds `#[coverage(off)]` to a closure, so it won't be instrumented in
187+ // `-Cinstrument-coverage` builds.
188+ // This requires `#[allow_internal_unstable(coverage_attribute)]` on the
189+ // corresponding macro declaration in `core::macros`.
190+ let coverage_off = |mut expr : P < ast:: Expr > | {
191+ assert_matches ! ( expr. kind, ast:: ExprKind :: Closure ( _) ) ;
192+ expr. attrs . push ( cx. attr_nested_word ( sym:: coverage, sym:: off, sp) ) ;
193+ expr
194+ } ;
195+
185196 let test_fn = if is_bench {
186197 // A simple ident for a lambda
187198 let b = Ident :: from_str_and_span ( "b" , attr_sp) ;
@@ -190,8 +201,9 @@ pub fn expand_test_or_bench(
190201 sp,
191202 cx. expr_path ( test_path ( "StaticBenchFn" ) ) ,
192203 thin_vec ! [
204+ // #[coverage(off)]
193205 // |b| self::test::assert_test_result(
194- cx. lambda1(
206+ coverage_off ( cx. lambda1(
195207 sp,
196208 cx. expr_call(
197209 sp,
@@ -206,16 +218,17 @@ pub fn expand_test_or_bench(
206218 ] ,
207219 ) ,
208220 b,
209- ) , // )
221+ ) ) , // )
210222 ] ,
211223 )
212224 } else {
213225 cx. expr_call (
214226 sp,
215227 cx. expr_path ( test_path ( "StaticTestFn" ) ) ,
216228 thin_vec ! [
229+ // #[coverage(off)]
217230 // || {
218- cx. lambda0(
231+ coverage_off ( cx. lambda0(
219232 sp,
220233 // test::assert_test_result(
221234 cx. expr_call(
@@ -230,7 +243,7 @@ pub fn expand_test_or_bench(
230243 ) , // )
231244 ] ,
232245 ) , // }
233- ) , // )
246+ ) ) , // )
234247 ] ,
235248 )
236249 } ;
0 commit comments