Skip to content

Commit eefc2a0

Browse files
committed
Auto merge of rust-lang#10891 - Centri3:missing_const_for_fn, r=Jarcho
[`missing_const_for_fn`]: Ensure dropped locals are `~const Destruct` this will check every local for `TerminatorKind::Drop` to ensure they can be evaluated at compile time, not sure if this is the best way to do this but MIR is confusing and it works so... fixes rust-lang#10617 changelog: [`missing_const_for_fn`]: Ensure dropped locals are `~const Destruct`
2 parents 72332b2 + 9bc5a14 commit eefc2a0

File tree

5 files changed

+127
-23
lines changed

5 files changed

+127
-23
lines changed

clippy_utils/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
extern crate rustc_ast;
2121
extern crate rustc_ast_pretty;
2222
extern crate rustc_attr;
23+
extern crate rustc_const_eval;
2324
extern crate rustc_data_structures;
2425
// The `rustc_driver` crate seems to be required in order to use the `rust_ast` crate.
2526
#[allow(unused_extern_crates)]

clippy_utils/src/qualify_min_const_fn.rs

Lines changed: 63 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,17 +4,24 @@
44
// differ from the time of `rustc` even if the name stays the same.
55

66
use crate::msrvs::Msrv;
7+
use hir::LangItem;
8+
use rustc_const_eval::transform::check_consts::ConstCx;
79
use rustc_hir as hir;
810
use rustc_hir::def_id::DefId;
11+
use rustc_infer::infer::TyCtxtInferExt;
12+
use rustc_infer::traits::Obligation;
913
use rustc_middle::mir::{
1014
Body, CastKind, NonDivergingIntrinsic, NullOp, Operand, Place, ProjectionElem, Rvalue, Statement, StatementKind,
1115
Terminator, TerminatorKind,
1216
};
17+
use rustc_middle::traits::{ImplSource, ObligationCause};
1318
use rustc_middle::ty::subst::GenericArgKind;
1419
use rustc_middle::ty::{self, adjustment::PointerCast, Ty, TyCtxt};
20+
use rustc_middle::ty::{BoundConstness, TraitRef};
1521
use rustc_semver::RustcVersion;
1622
use rustc_span::symbol::sym;
1723
use rustc_span::Span;
24+
use rustc_trait_selection::traits::{ObligationCtxt, SelectionContext};
1825
use std::borrow::Cow;
1926

2027
type McfResult = Result<(), (Span, Cow<'static, str>)>;
@@ -256,7 +263,19 @@ fn check_statement<'tcx>(
256263

257264
fn check_operand<'tcx>(tcx: TyCtxt<'tcx>, operand: &Operand<'tcx>, span: Span, body: &Body<'tcx>) -> McfResult {
258265
match operand {
259-
Operand::Move(place) | Operand::Copy(place) => check_place(tcx, *place, span, body),
266+
Operand::Move(place) => {
267+
if !place.projection.as_ref().is_empty()
268+
&& !is_ty_const_destruct(tcx, place.ty(&body.local_decls, tcx).ty, body)
269+
{
270+
return Err((
271+
span,
272+
"cannot drop locals with a non constant destructor in const fn".into(),
273+
));
274+
}
275+
276+
check_place(tcx, *place, span, body)
277+
},
278+
Operand::Copy(place) => check_place(tcx, *place, span, body),
260279
Operand::Constant(c) => match c.check_static_ptr(tcx) {
261280
Some(_) => Err((span, "cannot access `static` items in const fn".into())),
262281
None => Ok(()),
@@ -266,6 +285,7 @@ fn check_operand<'tcx>(tcx: TyCtxt<'tcx>, operand: &Operand<'tcx>, span: Span, b
266285

267286
fn check_place<'tcx>(tcx: TyCtxt<'tcx>, place: Place<'tcx>, span: Span, body: &Body<'tcx>) -> McfResult {
268287
let mut cursor = place.projection.as_ref();
288+
269289
while let [ref proj_base @ .., elem] = *cursor {
270290
cursor = proj_base;
271291
match elem {
@@ -305,15 +325,19 @@ fn check_terminator<'tcx>(
305325
| TerminatorKind::Resume
306326
| TerminatorKind::Terminate
307327
| TerminatorKind::Unreachable => Ok(()),
308-
309-
TerminatorKind::Drop { place, .. } => check_place(tcx, *place, span, body),
310-
328+
TerminatorKind::Drop { place, .. } => {
329+
if !is_ty_const_destruct(tcx, place.ty(&body.local_decls, tcx).ty, body) {
330+
return Err((
331+
span,
332+
"cannot drop locals with a non constant destructor in const fn".into(),
333+
));
334+
}
335+
Ok(())
336+
},
311337
TerminatorKind::SwitchInt { discr, targets: _ } => check_operand(tcx, discr, span, body),
312-
313338
TerminatorKind::GeneratorDrop | TerminatorKind::Yield { .. } => {
314339
Err((span, "const fn generators are unstable".into()))
315340
},
316-
317341
TerminatorKind::Call {
318342
func,
319343
args,
@@ -357,15 +381,13 @@ fn check_terminator<'tcx>(
357381
Err((span, "can only call other const fns within const fn".into()))
358382
}
359383
},
360-
361384
TerminatorKind::Assert {
362385
cond,
363386
expected: _,
364387
msg: _,
365388
target: _,
366389
unwind: _,
367390
} => check_operand(tcx, cond, span, body),
368-
369391
TerminatorKind::InlineAsm { .. } => Err((span, "cannot use inline assembly in const fn".into())),
370392
}
371393
}
@@ -379,8 +401,7 @@ fn is_const_fn(tcx: TyCtxt<'_>, def_id: DefId, msrv: &Msrv) -> bool {
379401
// as a part of an unimplemented MSRV check https://github.com/rust-lang/rust/issues/65262.
380402

381403
// HACK(nilstrieb): CURRENT_RUSTC_VERSION can return versions like 1.66.0-dev. `rustc-semver`
382-
// doesn't accept the `-dev` version number so we have to strip it
383-
// off.
404+
// doesn't accept the `-dev` version number so we have to strip it off.
384405
let short_version = since
385406
.as_str()
386407
.split('-')
@@ -398,3 +419,35 @@ fn is_const_fn(tcx: TyCtxt<'_>, def_id: DefId, msrv: &Msrv) -> bool {
398419
}
399420
})
400421
}
422+
423+
#[expect(clippy::similar_names)] // bit too pedantic
424+
fn is_ty_const_destruct<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, body: &Body<'tcx>) -> bool {
425+
// Avoid selecting for simple cases, such as builtin types.
426+
if ty::util::is_trivially_const_drop(ty) {
427+
return true;
428+
}
429+
430+
let obligation = Obligation::new(
431+
tcx,
432+
ObligationCause::dummy_with_span(body.span),
433+
ConstCx::new(tcx, body).param_env.with_const(),
434+
TraitRef::from_lang_item(tcx, LangItem::Destruct, body.span, [ty]).with_constness(BoundConstness::ConstIfConst),
435+
);
436+
437+
let infcx = tcx.infer_ctxt().build();
438+
let mut selcx = SelectionContext::new(&infcx);
439+
let Some(impl_src) = selcx.select(&obligation).ok().flatten() else {
440+
return false;
441+
};
442+
443+
if !matches!(
444+
impl_src,
445+
ImplSource::ConstDestruct(_) | ImplSource::Param(_, ty::BoundConstness::ConstIfConst)
446+
) {
447+
return false;
448+
}
449+
450+
let ocx = ObligationCtxt::new(&infcx);
451+
ocx.register_obligations(impl_src.nested_obligations());
452+
ocx.select_all_or_error().is_empty()
453+
}

tests/ui/missing_const_for_fn/cant_be_const.rs

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ extern crate proc_macros;
1313

1414
use proc_macros::with_span;
1515

16-
struct Game;
16+
struct Game; // You just lost.
1717

1818
// This should not be linted because it's already const
1919
const fn already_const() -> i32 {
@@ -126,3 +126,34 @@ with_span! {
126126
span
127127
fn dont_check_in_proc_macro() {}
128128
}
129+
130+
// Do not lint `String` has `Vec<u8>`, which cannot be dropped in const contexts
131+
fn a(this: String) {}
132+
133+
enum A {
134+
F(String),
135+
N,
136+
}
137+
138+
// Same here.
139+
fn b(this: A) {}
140+
141+
// Minimized version of `a`.
142+
fn c(this: Vec<u16>) {}
143+
144+
struct F(A);
145+
146+
// Do not lint
147+
fn f(this: F) {}
148+
149+
// Do not lint
150+
fn g<T>(this: T) {}
151+
152+
struct Issue10617(String);
153+
154+
impl Issue10617 {
155+
// Do not lint
156+
pub fn name(self) -> String {
157+
self.0
158+
}
159+
}

tests/ui/missing_const_for_fn/could_be_const.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
#![warn(clippy::missing_const_for_fn)]
22
#![allow(incomplete_features, clippy::let_and_return)]
3+
#![feature(const_mut_refs)]
4+
#![feature(const_trait_impl)]
35

46
use std::mem::transmute;
57

@@ -87,3 +89,14 @@ fn msrv_1_46() -> i32 {
8789

8890
// Should not be const
8991
fn main() {}
92+
93+
struct D;
94+
95+
impl const Drop for D {
96+
fn drop(&mut self) {
97+
todo!();
98+
}
99+
}
100+
101+
// Lint this, since it can be dropped in const contexts
102+
fn d(this: D) {}
Lines changed: 18 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
error: this could be a `const fn`
2-
--> $DIR/could_be_const.rs:12:5
2+
--> $DIR/could_be_const.rs:14:5
33
|
44
LL | / pub fn new() -> Self {
55
LL | | Self { guess: 42 }
@@ -9,23 +9,23 @@ LL | | }
99
= note: `-D clippy::missing-const-for-fn` implied by `-D warnings`
1010

1111
error: this could be a `const fn`
12-
--> $DIR/could_be_const.rs:16:5
12+
--> $DIR/could_be_const.rs:18:5
1313
|
1414
LL | / fn const_generic_params<'a, T, const N: usize>(&self, b: &'a [T; N]) -> &'a [T; N] {
1515
LL | | b
1616
LL | | }
1717
| |_____^
1818

1919
error: this could be a `const fn`
20-
--> $DIR/could_be_const.rs:22:1
20+
--> $DIR/could_be_const.rs:24:1
2121
|
2222
LL | / fn one() -> i32 {
2323
LL | | 1
2424
LL | | }
2525
| |_^
2626

2727
error: this could be a `const fn`
28-
--> $DIR/could_be_const.rs:27:1
28+
--> $DIR/could_be_const.rs:29:1
2929
|
3030
LL | / fn two() -> i32 {
3131
LL | | let abc = 2;
@@ -34,60 +34,66 @@ LL | | }
3434
| |_^
3535

3636
error: this could be a `const fn`
37-
--> $DIR/could_be_const.rs:33:1
37+
--> $DIR/could_be_const.rs:35:1
3838
|
3939
LL | / fn string() -> String {
4040
LL | | String::new()
4141
LL | | }
4242
| |_^
4343

4444
error: this could be a `const fn`
45-
--> $DIR/could_be_const.rs:38:1
45+
--> $DIR/could_be_const.rs:40:1
4646
|
4747
LL | / unsafe fn four() -> i32 {
4848
LL | | 4
4949
LL | | }
5050
| |_^
5151

5252
error: this could be a `const fn`
53-
--> $DIR/could_be_const.rs:43:1
53+
--> $DIR/could_be_const.rs:45:1
5454
|
5555
LL | / fn generic<T>(t: T) -> T {
5656
LL | | t
5757
LL | | }
5858
| |_^
5959

6060
error: this could be a `const fn`
61-
--> $DIR/could_be_const.rs:51:1
61+
--> $DIR/could_be_const.rs:53:1
6262
|
6363
LL | / fn generic_arr<T: Copy>(t: [T; 1]) -> T {
6464
LL | | t[0]
6565
LL | | }
6666
| |_^
6767

6868
error: this could be a `const fn`
69-
--> $DIR/could_be_const.rs:64:9
69+
--> $DIR/could_be_const.rs:66:9
7070
|
7171
LL | / pub fn b(self, a: &A) -> B {
7272
LL | | B
7373
LL | | }
7474
| |_________^
7575

7676
error: this could be a `const fn`
77-
--> $DIR/could_be_const.rs:73:5
77+
--> $DIR/could_be_const.rs:75:5
7878
|
7979
LL | / fn const_fn_stabilized_before_msrv(byte: u8) {
8080
LL | | byte.is_ascii_digit();
8181
LL | | }
8282
| |_____^
8383

8484
error: this could be a `const fn`
85-
--> $DIR/could_be_const.rs:84:1
85+
--> $DIR/could_be_const.rs:86:1
8686
|
8787
LL | / fn msrv_1_46() -> i32 {
8888
LL | | 46
8989
LL | | }
9090
| |_^
9191

92-
error: aborting due to 11 previous errors
92+
error: this could be a `const fn`
93+
--> $DIR/could_be_const.rs:102:1
94+
|
95+
LL | fn d(this: D) {}
96+
| ^^^^^^^^^^^^^^^^
97+
98+
error: aborting due to 12 previous errors
9399

0 commit comments

Comments
 (0)