]> git.lizzy.rs Git - rust.git/blob - clippy_utils/src/qualify_min_const_fn.rs
add eq constraints on associated constants
[rust.git] / clippy_utils / src / qualify_min_const_fn.rs
1 // This code used to be a part of `rustc` but moved to Clippy as a result of
2 // https://github.com/rust-lang/rust/issues/76618. Because of that, it contains unused code and some
3 // of terminologies might not be relevant in the context of Clippy. Note that its behavior might
4 // differ from the time of `rustc` even if the name stays the same.
5
6 use rustc_hir as hir;
7 use rustc_hir::def_id::DefId;
8 use rustc_middle::mir::{
9     Body, CastKind, NullOp, Operand, Place, ProjectionElem, Rvalue, Statement, StatementKind, Terminator,
10     TerminatorKind,
11 };
12 use rustc_middle::ty::subst::GenericArgKind;
13 use rustc_middle::ty::{self, adjustment::PointerCast, Ty, TyCtxt};
14 use rustc_semver::RustcVersion;
15 use rustc_span::symbol::sym;
16 use rustc_span::Span;
17 use rustc_target::spec::abi::Abi::RustIntrinsic;
18 use std::borrow::Cow;
19
20 type McfResult = Result<(), (Span, Cow<'static, str>)>;
21
22 pub fn is_min_const_fn<'a, 'tcx>(tcx: TyCtxt<'tcx>, body: &'a Body<'tcx>, msrv: Option<&RustcVersion>) -> McfResult {
23     let def_id = body.source.def_id();
24     let mut current = def_id;
25     loop {
26         let predicates = tcx.predicates_of(current);
27         for (predicate, _) in predicates.predicates {
28             match predicate.kind().skip_binder() {
29                 ty::PredicateKind::RegionOutlives(_)
30                 | ty::PredicateKind::TypeOutlives(_)
31                 | ty::PredicateKind::WellFormed(_)
32                 | ty::PredicateKind::Projection(_)
33                 | ty::PredicateKind::ConstEvaluatable(..)
34                 | ty::PredicateKind::ConstEquate(..)
35                 | ty::PredicateKind::TypeWellFormedFromEnv(..) => continue,
36                 ty::PredicateKind::ObjectSafe(_) => panic!("object safe predicate on function: {:#?}", predicate),
37                 ty::PredicateKind::ClosureKind(..) => panic!("closure kind predicate on function: {:#?}", predicate),
38                 ty::PredicateKind::Subtype(_) => panic!("subtype predicate on function: {:#?}", predicate),
39                 ty::PredicateKind::Coerce(_) => panic!("coerce predicate on function: {:#?}", predicate),
40                 ty::PredicateKind::Trait(pred) => {
41                     if Some(pred.def_id()) == tcx.lang_items().sized_trait() {
42                         continue;
43                     }
44                     match pred.self_ty().kind() {
45                         ty::Param(ref p) => {
46                             let generics = tcx.generics_of(current);
47                             let def = generics.type_param(p, tcx);
48                             let span = tcx.def_span(def.def_id);
49                             return Err((
50                                 span,
51                                 "trait bounds other than `Sized` \
52                                  on const fn parameters are unstable"
53                                     .into(),
54                             ));
55                         },
56                         // other kinds of bounds are either tautologies
57                         // or cause errors in other passes
58                         _ => continue,
59                     }
60                 },
61             }
62         }
63         match predicates.parent {
64             Some(parent) => current = parent,
65             None => break,
66         }
67     }
68
69     for local in &body.local_decls {
70         check_ty(tcx, local.ty, local.source_info.span)?;
71     }
72     // impl trait is gone in MIR, so check the return type manually
73     check_ty(
74         tcx,
75         tcx.fn_sig(def_id).output().skip_binder(),
76         body.local_decls.iter().next().unwrap().source_info.span,
77     )?;
78
79     for bb in body.basic_blocks() {
80         check_terminator(tcx, body, bb.terminator(), msrv)?;
81         for stmt in &bb.statements {
82             check_statement(tcx, body, def_id, stmt)?;
83         }
84     }
85     Ok(())
86 }
87
88 fn check_ty<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, span: Span) -> McfResult {
89     for arg in ty.walk() {
90         let ty = match arg.unpack() {
91             GenericArgKind::Type(ty) => ty,
92
93             // No constraints on lifetimes or constants, except potentially
94             // constants' types, but `walk` will get to them as well.
95             GenericArgKind::Lifetime(_) | GenericArgKind::Const(_) => continue,
96         };
97
98         match ty.kind() {
99             ty::Ref(_, _, hir::Mutability::Mut) => {
100                 return Err((span, "mutable references in const fn are unstable".into()));
101             },
102             ty::Opaque(..) => return Err((span, "`impl Trait` in const fn is unstable".into())),
103             ty::FnPtr(..) => {
104                 return Err((span, "function pointers in const fn are unstable".into()));
105             },
106             ty::Dynamic(preds, _) => {
107                 for pred in preds.iter() {
108                     match pred.skip_binder() {
109                         ty::ExistentialPredicate::AutoTrait(_) | ty::ExistentialPredicate::Projection(_) => {
110                             return Err((
111                                 span,
112                                 "trait bounds other than `Sized` \
113                                  on const fn parameters are unstable"
114                                     .into(),
115                             ));
116                         },
117                         ty::ExistentialPredicate::Trait(trait_ref) => {
118                             if Some(trait_ref.def_id) != tcx.lang_items().sized_trait() {
119                                 return Err((
120                                     span,
121                                     "trait bounds other than `Sized` \
122                                      on const fn parameters are unstable"
123                                         .into(),
124                                 ));
125                             }
126                         },
127                     }
128                 }
129             },
130             _ => {},
131         }
132     }
133     Ok(())
134 }
135
136 fn check_rvalue<'tcx>(
137     tcx: TyCtxt<'tcx>,
138     body: &Body<'tcx>,
139     def_id: DefId,
140     rvalue: &Rvalue<'tcx>,
141     span: Span,
142 ) -> McfResult {
143     match rvalue {
144         Rvalue::ThreadLocalRef(_) => Err((span, "cannot access thread local storage in const fn".into())),
145         Rvalue::Repeat(operand, _) | Rvalue::Use(operand) => check_operand(tcx, operand, span, body),
146         Rvalue::Len(place) | Rvalue::Discriminant(place) | Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => {
147             check_place(tcx, *place, span, body)
148         },
149         Rvalue::Cast(CastKind::Misc, operand, cast_ty) => {
150             use rustc_middle::ty::cast::CastTy;
151             let cast_in = CastTy::from_ty(operand.ty(body, tcx)).expect("bad input type for cast");
152             let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
153             match (cast_in, cast_out) {
154                 (CastTy::Ptr(_) | CastTy::FnPtr, CastTy::Int(_)) => {
155                     Err((span, "casting pointers to ints is unstable in const fn".into()))
156                 },
157                 _ => check_operand(tcx, operand, span, body),
158             }
159         },
160         Rvalue::Cast(CastKind::Pointer(PointerCast::MutToConstPointer | PointerCast::ArrayToPointer), operand, _) => {
161             check_operand(tcx, operand, span, body)
162         },
163         Rvalue::Cast(
164             CastKind::Pointer(
165                 PointerCast::UnsafeFnPointer | PointerCast::ClosureFnPointer(_) | PointerCast::ReifyFnPointer,
166             ),
167             _,
168             _,
169         ) => Err((span, "function pointer casts are not allowed in const fn".into())),
170         Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), op, cast_ty) => {
171             let pointee_ty = if let Some(deref_ty) = cast_ty.builtin_deref(true) {
172                 deref_ty.ty
173             } else {
174                 // We cannot allow this for now.
175                 return Err((span, "unsizing casts are only allowed for references right now".into()));
176             };
177             let unsized_ty = tcx.struct_tail_erasing_lifetimes(pointee_ty, tcx.param_env(def_id));
178             if let ty::Slice(_) | ty::Str = unsized_ty.kind() {
179                 check_operand(tcx, op, span, body)?;
180                 // Casting/coercing things to slices is fine.
181                 Ok(())
182             } else {
183                 // We just can't allow trait objects until we have figured out trait method calls.
184                 Err((span, "unsizing casts are not allowed in const fn".into()))
185             }
186         },
187         // binops are fine on integers
188         Rvalue::BinaryOp(_, box (lhs, rhs)) | Rvalue::CheckedBinaryOp(_, box (lhs, rhs)) => {
189             check_operand(tcx, lhs, span, body)?;
190             check_operand(tcx, rhs, span, body)?;
191             let ty = lhs.ty(body, tcx);
192             if ty.is_integral() || ty.is_bool() || ty.is_char() {
193                 Ok(())
194             } else {
195                 Err((
196                     span,
197                     "only int, `bool` and `char` operations are stable in const fn".into(),
198                 ))
199             }
200         },
201         Rvalue::NullaryOp(NullOp::SizeOf | NullOp::AlignOf, _) | Rvalue::ShallowInitBox(_, _) => Ok(()),
202         Rvalue::UnaryOp(_, operand) => {
203             let ty = operand.ty(body, tcx);
204             if ty.is_integral() || ty.is_bool() {
205                 check_operand(tcx, operand, span, body)
206             } else {
207                 Err((span, "only int and `bool` operations are stable in const fn".into()))
208             }
209         },
210         Rvalue::Aggregate(_, operands) => {
211             for operand in operands {
212                 check_operand(tcx, operand, span, body)?;
213             }
214             Ok(())
215         },
216     }
217 }
218
219 fn check_statement<'tcx>(
220     tcx: TyCtxt<'tcx>,
221     body: &Body<'tcx>,
222     def_id: DefId,
223     statement: &Statement<'tcx>,
224 ) -> McfResult {
225     let span = statement.source_info.span;
226     match &statement.kind {
227         StatementKind::Assign(box (place, rval)) => {
228             check_place(tcx, *place, span, body)?;
229             check_rvalue(tcx, body, def_id, rval, span)
230         },
231
232         StatementKind::FakeRead(box (_, place)) => check_place(tcx, *place, span, body),
233         // just an assignment
234         StatementKind::SetDiscriminant { place, .. } => check_place(tcx, **place, span, body),
235
236         StatementKind::CopyNonOverlapping(box rustc_middle::mir::CopyNonOverlapping { dst, src, count }) => {
237             check_operand(tcx, dst, span, body)?;
238             check_operand(tcx, src, span, body)?;
239             check_operand(tcx, count, span, body)
240         },
241         // These are all NOPs
242         StatementKind::StorageLive(_)
243         | StatementKind::StorageDead(_)
244         | StatementKind::Retag { .. }
245         | StatementKind::AscribeUserType(..)
246         | StatementKind::Coverage(..)
247         | StatementKind::Nop => Ok(()),
248     }
249 }
250
251 fn check_operand<'tcx>(tcx: TyCtxt<'tcx>, operand: &Operand<'tcx>, span: Span, body: &Body<'tcx>) -> McfResult {
252     match operand {
253         Operand::Move(place) | Operand::Copy(place) => check_place(tcx, *place, span, body),
254         Operand::Constant(c) => match c.check_static_ptr(tcx) {
255             Some(_) => Err((span, "cannot access `static` items in const fn".into())),
256             None => Ok(()),
257         },
258     }
259 }
260
261 fn check_place<'tcx>(tcx: TyCtxt<'tcx>, place: Place<'tcx>, span: Span, body: &Body<'tcx>) -> McfResult {
262     let mut cursor = place.projection.as_ref();
263     while let [ref proj_base @ .., elem] = *cursor {
264         cursor = proj_base;
265         match elem {
266             ProjectionElem::Field(..) => {
267                 let base_ty = Place::ty_from(place.local, proj_base, body, tcx).ty;
268                 if let Some(def) = base_ty.ty_adt_def() {
269                     // No union field accesses in `const fn`
270                     if def.is_union() {
271                         return Err((span, "accessing union fields is unstable".into()));
272                     }
273                 }
274             },
275             ProjectionElem::ConstantIndex { .. }
276             | ProjectionElem::Downcast(..)
277             | ProjectionElem::Subslice { .. }
278             | ProjectionElem::Deref
279             | ProjectionElem::Index(_) => {},
280         }
281     }
282
283     Ok(())
284 }
285
286 fn check_terminator<'a, 'tcx>(
287     tcx: TyCtxt<'tcx>,
288     body: &'a Body<'tcx>,
289     terminator: &Terminator<'tcx>,
290     msrv: Option<&RustcVersion>,
291 ) -> McfResult {
292     let span = terminator.source_info.span;
293     match &terminator.kind {
294         TerminatorKind::FalseEdge { .. }
295         | TerminatorKind::FalseUnwind { .. }
296         | TerminatorKind::Goto { .. }
297         | TerminatorKind::Return
298         | TerminatorKind::Resume
299         | TerminatorKind::Unreachable => Ok(()),
300
301         TerminatorKind::Drop { place, .. } => check_place(tcx, *place, span, body),
302         TerminatorKind::DropAndReplace { place, value, .. } => {
303             check_place(tcx, *place, span, body)?;
304             check_operand(tcx, value, span, body)
305         },
306
307         TerminatorKind::SwitchInt {
308             discr,
309             switch_ty: _,
310             targets: _,
311         } => check_operand(tcx, discr, span, body),
312
313         TerminatorKind::Abort => Err((span, "abort is not stable in const fn".into())),
314         TerminatorKind::GeneratorDrop | TerminatorKind::Yield { .. } => {
315             Err((span, "const fn generators are unstable".into()))
316         },
317
318         TerminatorKind::Call {
319             func,
320             args,
321             from_hir_call: _,
322             destination: _,
323             cleanup: _,
324             fn_span: _,
325         } => {
326             let fn_ty = func.ty(body, tcx);
327             if let ty::FnDef(fn_def_id, _) = *fn_ty.kind() {
328                 if !is_const_fn(tcx, fn_def_id, msrv) {
329                     return Err((
330                         span,
331                         format!(
332                             "can only call other `const fn` within a `const fn`, \
333                              but `{:?}` is not stable as `const fn`",
334                             func,
335                         )
336                         .into(),
337                     ));
338                 }
339
340                 // HACK: This is to "unstabilize" the `transmute` intrinsic
341                 // within const fns. `transmute` is allowed in all other const contexts.
342                 // This won't really scale to more intrinsics or functions. Let's allow const
343                 // transmutes in const fn before we add more hacks to this.
344                 if tcx.fn_sig(fn_def_id).abi() == RustIntrinsic && tcx.item_name(fn_def_id) == sym::transmute {
345                     return Err((
346                         span,
347                         "can only call `transmute` from const items, not `const fn`".into(),
348                     ));
349                 }
350
351                 check_operand(tcx, func, span, body)?;
352
353                 for arg in args {
354                     check_operand(tcx, arg, span, body)?;
355                 }
356                 Ok(())
357             } else {
358                 Err((span, "can only call other const fns within const fn".into()))
359             }
360         },
361
362         TerminatorKind::Assert {
363             cond,
364             expected: _,
365             msg: _,
366             target: _,
367             cleanup: _,
368         } => check_operand(tcx, cond, span, body),
369
370         TerminatorKind::InlineAsm { .. } => Err((span, "cannot use inline assembly in const fn".into())),
371     }
372 }
373
374 fn is_const_fn(tcx: TyCtxt<'_>, def_id: DefId, msrv: Option<&RustcVersion>) -> bool {
375     tcx.is_const_fn(def_id)
376         && tcx.lookup_const_stability(def_id).map_or(true, |const_stab| {
377             if let rustc_attr::StabilityLevel::Stable { since } = const_stab.level {
378                 // Checking MSRV is manually necessary because `rustc` has no such concept. This entire
379                 // function could be removed if `rustc` provided a MSRV-aware version of `is_const_fn`.
380                 // as a part of an unimplemented MSRV check https://github.com/rust-lang/rust/issues/65262.
381                 crate::meets_msrv(
382                     msrv,
383                     &RustcVersion::parse(since.as_str())
384                         .expect("`rustc_attr::StabilityLevel::Stable::since` is ill-formatted"),
385                 )
386             } else {
387                 // Unstable const fn with the feature enabled.
388                 msrv.is_none()
389             }
390         })
391 }