diff --git a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs index 20a4402f6f699..760cefffee995 100644 --- a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs @@ -250,7 +250,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { // If we're in pattern, we do nothing in favor of the previous suggestion (#80913). // Same for if we're in a loop, see #101119. if is_loop_move & !in_pattern && !matches!(use_spans, UseSpans::ClosureUse { .. }) { - if let ty::Ref(_, _, hir::Mutability::Mut) = ty.kind() { + if let ty::Ref(_, _, ty::Mutability::Mut) = ty.kind() { // We have a `&mut` ref, we need to reborrow on each iteration (#62112). err.span_suggestion_verbose( span.shrink_to_lo(), diff --git a/compiler/rustc_borrowck/src/diagnostics/mod.rs b/compiler/rustc_borrowck/src/diagnostics/mod.rs index 8f5d5e67a7a9d..a4e31abb5dbe5 100644 --- a/compiler/rustc_borrowck/src/diagnostics/mod.rs +++ b/compiler/rustc_borrowck/src/diagnostics/mod.rs @@ -1068,7 +1068,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { // If the moved place was a `&mut` ref, then we can // suggest to reborrow it where it was moved, so it // will still be valid by the time we get to the usage. - if let ty::Ref(_, _, hir::Mutability::Mut) = + if let ty::Ref(_, _, ty::Mutability::Mut) = moved_place.ty(self.body, self.infcx.tcx).ty.kind() { // If we are in a loop this will be suggested later. @@ -1107,7 +1107,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { if let ty::Adt(def, args) = ty.kind() && Some(def.did()) == tcx.lang_items().pin_type() - && let ty::Ref(_, _, hir::Mutability::Mut) = args.type_at(0).kind() + && let ty::Ref(_, _, ty::Mutability::Mut) = args.type_at(0).kind() && let self_ty = self.infcx.instantiate_binder_with_fresh_vars( fn_call_span, LateBoundRegionConversionTime::FnCall, diff --git a/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs b/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs index e5ffc8a11142b..6f0c00b289a77 100644 --- a/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs @@ -70,7 +70,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { .place .place .deref_tys() - .any(|ty| matches!(ty.kind(), ty::Ref(.., hir::Mutability::Not))); + .any(|ty| matches!(ty.kind(), ty::Ref(.., Mutability::Not))); // If the place is immutable then: // @@ -918,7 +918,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { ); } } - AddrOf(BorrowKind::Ref, Mutability::Not, expr) => { + AddrOf(BorrowKind::Ref, hir::Mutability::Not, expr) => { // We have `for _ in &i`, suggest `for _ in &mut i`. err.span_suggestion_verbose( expr.span.shrink_to_lo(), @@ -1246,7 +1246,7 @@ pub fn mut_borrow_of_mutable_ref(local_decl: &LocalDecl<'_>, local_name: Option< LocalInfo::User(mir::BindingForm::Var(mir::VarBindingForm { binding_mode: ty::BindingMode::BindByValue(Mutability::Not), .. - })) => matches!(local_decl.ty.kind(), ty::Ref(_, _, hir::Mutability::Mut)), + })) => matches!(local_decl.ty.kind(), ty::Ref(_, _, Mutability::Mut)), LocalInfo::User(mir::BindingForm::ImplicitSelf(kind)) => { // Check if the user variable is a `&mut self` and we can therefore // suggest removing the `&mut`. @@ -1259,7 +1259,7 @@ pub fn mut_borrow_of_mutable_ref(local_decl: &LocalDecl<'_>, local_name: Option< // Otherwise, check if the name is the `self` keyword - in which case // we have an explicit self. Do the same thing in this case and check // for a `self: &mut Self` to suggest removing the `&mut`. - matches!(local_decl.ty.kind(), ty::Ref(_, _, hir::Mutability::Mut)) + matches!(local_decl.ty.kind(), ty::Ref(_, _, Mutability::Mut)) } _ => false, } @@ -1371,7 +1371,7 @@ fn suggest_ampmut<'tcx>( // otherwise, suggest that the user annotates the binding; we provide the // type of the local. let ty_mut = decl_ty.builtin_deref(true).unwrap(); - assert_eq!(ty_mut.mutbl, hir::Mutability::Not); + assert_eq!(ty_mut.mutbl, Mutability::Not); (false, span, format!("{}mut {}", if decl_ty.is_ref() { "&" } else { "*" }, ty_mut.ty)) } diff --git a/compiler/rustc_borrowck/src/diagnostics/region_errors.rs b/compiler/rustc_borrowck/src/diagnostics/region_errors.rs index 27072a60f65f0..1170985df9960 100644 --- a/compiler/rustc_borrowck/src/diagnostics/region_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/region_errors.rs @@ -488,14 +488,14 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { ty::VarianceDiagInfo::Invariant { ty, param_index } => { let (desc, note) = match ty.kind() { ty::RawPtr(ty_mut) => { - assert_eq!(ty_mut.mutbl, rustc_hir::Mutability::Mut); + assert_eq!(ty_mut.mutbl, ty::Mutability::Mut); ( format!("a mutable pointer to `{}`", ty_mut.ty), "mutable pointers are invariant over their type parameter".to_string(), ) } ty::Ref(_, inner_ty, mutbl) => { - assert_eq!(*mutbl, rustc_hir::Mutability::Mut); + assert_eq!(*mutbl, ty::Mutability::Mut); ( format!("a mutable reference to `{inner_ty}`"), "mutable references are invariant over their type parameter" diff --git a/compiler/rustc_borrowck/src/lib.rs b/compiler/rustc_borrowck/src/lib.rs index d274a3eea6ca9..5de46ee5e5237 100644 --- a/compiler/rustc_borrowck/src/lib.rs +++ b/compiler/rustc_borrowck/src/lib.rs @@ -1366,7 +1366,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { if proj == ProjectionElem::Deref { match place_ref.ty(this.body(), this.infcx.tcx).ty.kind() { // We aren't modifying a variable directly - ty::Ref(_, _, hir::Mutability::Mut) => return, + ty::Ref(_, _, Mutability::Mut) => return, _ => {} } @@ -2154,10 +2154,10 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { ty::Ref(_, _, mutbl) => { match mutbl { // Shared borrowed data is never mutable - hir::Mutability::Not => Err(place), + Mutability::Not => Err(place), // Mutably borrowed data is mutable, but only if we have a // unique path to the `&mut` - hir::Mutability::Mut => { + Mutability::Mut => { let mode = match self.is_upvar_field_projection(place) { Some(field) if self.upvars[field.index()].by_ref => { is_local_mutation_allowed @@ -2172,10 +2172,10 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { ty::RawPtr(tnm) => { match tnm.mutbl { // `*const` raw pointers are not mutable - hir::Mutability::Not => Err(place), + Mutability::Not => Err(place), // `*mut` raw pointers are always mutable, regardless of // context. The users have to check by themselves. - hir::Mutability::Mut => Ok(RootPlace { + Mutability::Mut => Ok(RootPlace { place_local: place.local, place_projection: place.projection, is_local_mutation_allowed, diff --git a/compiler/rustc_borrowck/src/place_ext.rs b/compiler/rustc_borrowck/src/place_ext.rs index 3d7e8c6ebf330..7863fd0024505 100644 --- a/compiler/rustc_borrowck/src/place_ext.rs +++ b/compiler/rustc_borrowck/src/place_ext.rs @@ -1,7 +1,6 @@ #![deny(rustc::untranslatable_diagnostic)] #![deny(rustc::diagnostic_outside_of_impl)] use crate::borrow_set::LocalsStateAtExit; -use rustc_hir as hir; use rustc_middle::mir::ProjectionElem; use rustc_middle::mir::{Body, Mutability, Place}; use rustc_middle::ty::{self, TyCtxt}; @@ -50,7 +49,7 @@ impl<'tcx> PlaceExt<'tcx> for Place<'tcx> { if elem == ProjectionElem::Deref { let ty = proj_base.ty(body, tcx).ty; match ty.kind() { - ty::Ref(_, _, hir::Mutability::Not) if i == 0 => { + ty::Ref(_, _, Mutability::Not) if i == 0 => { // For references to thread-local statics, we do need // to track the borrow. if body.local_decls[self.local].is_ref_to_thread_local() { @@ -58,7 +57,7 @@ impl<'tcx> PlaceExt<'tcx> for Place<'tcx> { } return true; } - ty::RawPtr(..) | ty::Ref(_, _, hir::Mutability::Not) => { + ty::RawPtr(..) | ty::Ref(_, _, Mutability::Not) => { // For both derefs of raw pointers and `&T` // references, the original path is `Copy` and // therefore not significant. In particular, diff --git a/compiler/rustc_borrowck/src/places_conflict.rs b/compiler/rustc_borrowck/src/places_conflict.rs index 539d0837659c8..158ea6e8f5723 100644 --- a/compiler/rustc_borrowck/src/places_conflict.rs +++ b/compiler/rustc_borrowck/src/places_conflict.rs @@ -55,7 +55,6 @@ use crate::ArtificialField; use crate::Overlap; use crate::{AccessDepth, Deep, Shallow}; -use rustc_hir as hir; use rustc_middle::mir::{ Body, BorrowKind, MutBorrowKind, Place, PlaceElem, PlaceRef, ProjectionElem, }; @@ -223,11 +222,11 @@ fn place_components_conflict<'tcx>( debug!("borrow_conflicts_with_place: shallow access behind ptr"); return false; } - (ProjectionElem::Deref, ty::Ref(_, _, hir::Mutability::Not), _) => { + (ProjectionElem::Deref, ty::Ref(_, _, ty::Mutability::Not), _) => { // Shouldn't be tracked bug!("Tracking borrow behind shared reference."); } - (ProjectionElem::Deref, ty::Ref(_, _, hir::Mutability::Mut), AccessDepth::Drop) => { + (ProjectionElem::Deref, ty::Ref(_, _, ty::Mutability::Mut), AccessDepth::Drop) => { // Values behind a mutable reference are not access either by dropping a // value, or by StorageDead debug!("borrow_conflicts_with_place: drop access behind ptr"); diff --git a/compiler/rustc_borrowck/src/prefixes.rs b/compiler/rustc_borrowck/src/prefixes.rs index e9c9709bd1f1a..16f5a26f90c59 100644 --- a/compiler/rustc_borrowck/src/prefixes.rs +++ b/compiler/rustc_borrowck/src/prefixes.rs @@ -11,7 +11,6 @@ use super::MirBorrowckCtxt; -use rustc_hir as hir; use rustc_middle::mir::{Body, PlaceRef, ProjectionElem}; use rustc_middle::ty::{self, TyCtxt}; @@ -125,14 +124,14 @@ impl<'cx, 'tcx> Iterator for Prefixes<'cx, 'tcx> { let ty = cursor_base.ty(self.body, self.tcx).ty; match ty.kind() { - ty::RawPtr(_) | ty::Ref(_ /*rgn*/, _ /*ty*/, hir::Mutability::Not) => { + ty::RawPtr(_) | ty::Ref(_ /*rgn*/, _ /*ty*/, ty::Mutability::Not) => { // don't continue traversing over derefs of raw pointers or shared // borrows. self.next = None; return Some(cursor); } - ty::Ref(_ /*rgn*/, _ /*ty*/, hir::Mutability::Mut) => { + ty::Ref(_ /*rgn*/, _ /*ty*/, ty::Mutability::Mut) => { self.next = Some(cursor_base); return Some(cursor); } diff --git a/compiler/rustc_borrowck/src/type_check/mod.rs b/compiler/rustc_borrowck/src/type_check/mod.rs index 1ec0e62d16a3b..d16f6d6cb0e6d 100644 --- a/compiler/rustc_borrowck/src/type_check/mod.rs +++ b/compiler/rustc_borrowck/src/type_check/mod.rs @@ -10,7 +10,6 @@ use either::Either; use rustc_data_structures::frozen::Frozen; use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; use rustc_errors::ErrorGuaranteed; -use rustc_hir as hir; use rustc_hir::def::DefKind; use rustc_hir::def_id::LocalDefId; use rustc_hir::lang_items::LangItem; @@ -2047,13 +2046,13 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { } CastKind::PointerCoercion(PointerCoercion::MutToConstPointer) => { - let ty::RawPtr(ty::TypeAndMut { ty: ty_from, mutbl: hir::Mutability::Mut }) = + let ty::RawPtr(ty::TypeAndMut { ty: ty_from, mutbl: Mutability::Mut }) = op.ty(body, tcx).kind() else { span_mirbug!(self, rvalue, "unexpected base type for cast {:?}", ty,); return; }; - let ty::RawPtr(ty::TypeAndMut { ty: ty_to, mutbl: hir::Mutability::Not }) = + let ty::RawPtr(ty::TypeAndMut { ty: ty_to, mutbl: Mutability::Not }) = ty.kind() else { span_mirbug!(self, rvalue, "unexpected target type for cast {:?}", ty,); @@ -2533,13 +2532,13 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { }); match mutbl { - hir::Mutability::Not => { + Mutability::Not => { // Immutable reference. We don't need the base // to be valid for the entire lifetime of // the borrow. break; } - hir::Mutability::Mut => { + Mutability::Mut => { // Mutable reference. We *do* need the base // to be valid, because after the base becomes // invalid, someone else can use our mutable deref. diff --git a/compiler/rustc_codegen_cranelift/src/abi/mod.rs b/compiler/rustc_codegen_cranelift/src/abi/mod.rs index c75ad852f82d0..bd146fd9660d8 100644 --- a/compiler/rustc_codegen_cranelift/src/abi/mod.rs +++ b/compiler/rustc_codegen_cranelift/src/abi/mod.rs @@ -673,7 +673,7 @@ pub(crate) fn codegen_drop<'tcx>( fx.layout_of(Ty::new_ref( fx.tcx, fx.tcx.lifetimes.re_erased, - TypeAndMut { ty, mutbl: crate::rustc_hir::Mutability::Mut }, + TypeAndMut { ty, mutbl: Mutability::Mut }, )), ); let arg_value = adjust_arg_for_abi(fx, arg_value, &fn_abi.args[0], true); diff --git a/compiler/rustc_codegen_cranelift/src/common.rs b/compiler/rustc_codegen_cranelift/src/common.rs index 8958369267e5d..dd0862339ed0a 100644 --- a/compiler/rustc_codegen_cranelift/src/common.rs +++ b/compiler/rustc_codegen_cranelift/src/common.rs @@ -98,7 +98,7 @@ fn clif_pair_type_from_ty<'tcx>( /// Is a pointer to this type a fat ptr? pub(crate) fn has_ptr_meta<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> bool { - let ptr_ty = Ty::new_ptr(tcx, TypeAndMut { ty, mutbl: rustc_hir::Mutability::Not }); + let ptr_ty = Ty::new_ptr(tcx, TypeAndMut { ty, mutbl: Mutability::Not }); match &tcx.layout_of(ParamEnv::reveal_all().and(ptr_ty)).unwrap().abi { Abi::Scalar(_) => false, Abi::ScalarPair(_, _) => true, diff --git a/compiler/rustc_codegen_cranelift/src/constant.rs b/compiler/rustc_codegen_cranelift/src/constant.rs index 1cb6fa0772314..02158c9851df6 100644 --- a/compiler/rustc_codegen_cranelift/src/constant.rs +++ b/compiler/rustc_codegen_cranelift/src/constant.rs @@ -216,7 +216,7 @@ pub(crate) fn data_id_for_alloc_id( cx: &mut ConstantCx, module: &mut dyn Module, alloc_id: AllocId, - mutability: rustc_hir::Mutability, + mutability: ty::Mutability, ) -> DataId { cx.todo.push(TodoItem::Alloc(alloc_id)); *cx.anon_allocs diff --git a/compiler/rustc_codegen_gcc/src/intrinsic/simd.rs b/compiler/rustc_codegen_gcc/src/intrinsic/simd.rs index 85d3e7234a0e6..acbbf89ba5257 100644 --- a/compiler/rustc_codegen_gcc/src/intrinsic/simd.rs +++ b/compiler/rustc_codegen_gcc/src/intrinsic/simd.rs @@ -740,7 +740,7 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( let (_, element_ty1) = arg_tys[1].simd_size_and_type(bx.tcx()); let (_, element_ty2) = arg_tys[2].simd_size_and_type(bx.tcx()); let (pointer_count, underlying_ty) = match element_ty1.kind() { - ty::RawPtr(p) if p.ty == in_elem && p.mutbl == hir::Mutability::Mut => { + ty::RawPtr(p) if p.ty == in_elem && p.mutbl == ty::Mutability::Mut => { (ptr_count(element_ty1), non_ptr(element_ty1)) } _ => { diff --git a/compiler/rustc_codegen_llvm/src/common.rs b/compiler/rustc_codegen_llvm/src/common.rs index 0b0816c27b6df..4cefb684550cd 100644 --- a/compiler/rustc_codegen_llvm/src/common.rs +++ b/compiler/rustc_codegen_llvm/src/common.rs @@ -6,13 +6,12 @@ use crate::llvm::{self, BasicBlock, Bool, ConstantInt, False, OperandBundleDef, use crate::type_::Type; use crate::value::Value; -use rustc_ast::Mutability; use rustc_codegen_ssa::traits::*; use rustc_data_structures::stable_hasher::{Hash128, HashStable, StableHasher}; use rustc_hir::def_id::DefId; use rustc_middle::bug; use rustc_middle::mir::interpret::{ConstAllocation, GlobalAlloc, Scalar}; -use rustc_middle::ty::TyCtxt; +use rustc_middle::ty::{Mutability, TyCtxt}; use rustc_session::cstore::{DllCallingConvention, DllImport, PeImportNameType}; use rustc_target::abi::{self, AddressSpace, HasDataLayout, Pointer}; use rustc_target::spec::Target; diff --git a/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs b/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs index 989df448a319e..2e041c37f7507 100644 --- a/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs +++ b/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs @@ -15,7 +15,7 @@ use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::stable_hasher::{Hash64, HashStable, StableHasher}; use rustc_hir::def_id::DefId; use rustc_hir::definitions::{DefPathData, DefPathDataName, DisambiguatedDefPathData}; -use rustc_hir::{AsyncGeneratorKind, GeneratorKind, Mutability}; +use rustc_hir::{AsyncGeneratorKind, GeneratorKind}; use rustc_middle::ty::layout::{IntegerExt, TyAndLayout}; use rustc_middle::ty::{self, ExistentialProjection, ParamEnv, Ty, TyCtxt}; use rustc_middle::ty::{GenericArgKind, GenericArgsRef}; @@ -140,14 +140,14 @@ fn push_debuginfo_type_name<'tcx>( ty::RawPtr(ty::TypeAndMut { ty: inner_type, mutbl }) => { if cpp_like_debuginfo { match mutbl { - Mutability::Not => output.push_str("ptr_const$<"), - Mutability::Mut => output.push_str("ptr_mut$<"), + ty::Mutability::Not => output.push_str("ptr_const$<"), + ty::Mutability::Mut => output.push_str("ptr_mut$<"), } } else { output.push('*'); match mutbl { - Mutability::Not => output.push_str("const "), - Mutability::Mut => output.push_str("mut "), + ty::Mutability::Not => output.push_str("const "), + ty::Mutability::Mut => output.push_str("mut "), } } @@ -160,8 +160,8 @@ fn push_debuginfo_type_name<'tcx>( ty::Ref(_, inner_type, mutbl) => { if cpp_like_debuginfo { match mutbl { - Mutability::Not => output.push_str("ref$<"), - Mutability::Mut => output.push_str("ref_mut$<"), + ty::Mutability::Not => output.push_str("ref$<"), + ty::Mutability::Mut => output.push_str("ref_mut$<"), } } else { output.push('&'); diff --git a/compiler/rustc_const_eval/src/const_eval/eval_queries.rs b/compiler/rustc_const_eval/src/const_eval/eval_queries.rs index 6b612c3483710..15c4b70f4b302 100644 --- a/compiler/rustc_const_eval/src/const_eval/eval_queries.rs +++ b/compiler/rustc_const_eval/src/const_eval/eval_queries.rs @@ -2,6 +2,7 @@ use std::mem; use either::{Left, Right}; +use rustc_hir as hir; use rustc_hir::def::DefKind; use rustc_middle::mir::interpret::{ErrorHandled, InterpErrorInfo}; use rustc_middle::mir::pretty::write_allocation_bytes; @@ -71,7 +72,8 @@ fn eval_body_using_ecx<'mir, 'tcx>( InternKind::Promoted } else { match tcx.static_mutability(cid.instance.def_id()) { - Some(m) => InternKind::Static(m), + Some(hir::Mutability::Mut) => InternKind::Static(ty::Mutability::Mut), + Some(hir::Mutability::Not) => InternKind::Static(ty::Mutability::Not), None => InternKind::Constant, } }; diff --git a/compiler/rustc_const_eval/src/const_eval/machine.rs b/compiler/rustc_const_eval/src/const_eval/machine.rs index 166d3d45e7930..c78b4903d2333 100644 --- a/compiler/rustc_const_eval/src/const_eval/machine.rs +++ b/compiler/rustc_const_eval/src/const_eval/machine.rs @@ -3,7 +3,7 @@ use rustc_hir::LangItem; use rustc_middle::mir; use rustc_middle::mir::interpret::PointerArithmetic; use rustc_middle::ty::layout::{FnAbiOf, TyAndLayout}; -use rustc_middle::ty::{self, TyCtxt}; +use rustc_middle::ty::{self, Mutability, TyCtxt}; use std::borrow::Borrow; use std::hash::Hash; use std::ops::ControlFlow; @@ -12,7 +12,6 @@ use rustc_data_structures::fx::FxIndexMap; use rustc_data_structures::fx::IndexEntry; use std::fmt; -use rustc_ast::Mutability; use rustc_hir::def_id::DefId; use rustc_middle::mir::AssertMessage; use rustc_span::symbol::{sym, Symbol}; diff --git a/compiler/rustc_const_eval/src/interpret/intern.rs b/compiler/rustc_const_eval/src/interpret/intern.rs index fd89e34204f0c..ea24048c776b3 100644 --- a/compiler/rustc_const_eval/src/interpret/intern.rs +++ b/compiler/rustc_const_eval/src/interpret/intern.rs @@ -17,11 +17,8 @@ use super::validity::RefTracking; use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; use rustc_errors::ErrorGuaranteed; -use rustc_hir as hir; use rustc_middle::mir::interpret::InterpResult; -use rustc_middle::ty::{self, layout::TyAndLayout, Ty}; - -use rustc_ast::Mutability; +use rustc_middle::ty::{self, layout::TyAndLayout, Mutability, Ty}; use super::{ AllocId, Allocation, InterpCx, MPlaceTy, Machine, MemoryKind, PlaceTy, Projectable, @@ -63,7 +60,7 @@ enum InternMode { /// A static and its current mutability. Below shared references inside a `static mut`, /// this is *immutable*, and below mutable references inside an `UnsafeCell`, this /// is *mutable*. - Static(hir::Mutability), + Static(Mutability), /// A `const`. Const, } @@ -312,7 +309,7 @@ impl<'rt, 'mir, 'tcx: 'mir, M: CompileTimeMachine<'mir, 'tcx, const_eval::Memory #[derive(Copy, Clone, Debug, PartialEq, Hash, Eq)] pub enum InternKind { /// The `mutability` of the static, ignoring the type which may have interior mutability. - Static(hir::Mutability), + Static(Mutability), /// A `const` item Constant, Promoted, diff --git a/compiler/rustc_const_eval/src/interpret/intrinsics/caller_location.rs b/compiler/rustc_const_eval/src/interpret/intrinsics/caller_location.rs index 948bec7464ad2..0f7a748a55774 100644 --- a/compiler/rustc_const_eval/src/interpret/intrinsics/caller_location.rs +++ b/compiler/rustc_const_eval/src/interpret/intrinsics/caller_location.rs @@ -1,7 +1,7 @@ -use rustc_ast::Mutability; use rustc_hir::lang_items::LangItem; use rustc_middle::mir::TerminatorKind; use rustc_middle::ty::layout::LayoutOf; +use rustc_middle::ty::Mutability; use rustc_span::{Span, Symbol}; use crate::interpret::{ diff --git a/compiler/rustc_const_eval/src/interpret/memory.rs b/compiler/rustc_const_eval/src/interpret/memory.rs index 5b31738e4e18e..d97650e28b9ec 100644 --- a/compiler/rustc_const_eval/src/interpret/memory.rs +++ b/compiler/rustc_const_eval/src/interpret/memory.rs @@ -12,10 +12,9 @@ use std::collections::VecDeque; use std::fmt; use std::ptr; -use rustc_ast::Mutability; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_middle::mir::display_allocation; -use rustc_middle::ty::{self, Instance, ParamEnv, Ty, TyCtxt}; +use rustc_middle::ty::{self, Instance, Mutability, ParamEnv, Ty, TyCtxt}; use rustc_target::abi::{Align, HasDataLayout, Size}; use crate::fluent_generated as fluent; diff --git a/compiler/rustc_const_eval/src/interpret/place.rs b/compiler/rustc_const_eval/src/interpret/place.rs index 09ffdec7de7d1..89581ca5add6c 100644 --- a/compiler/rustc_const_eval/src/interpret/place.rs +++ b/compiler/rustc_const_eval/src/interpret/place.rs @@ -6,12 +6,11 @@ use std::assert_matches::assert_matches; use either::{Either, Left, Right}; -use rustc_ast::Mutability; use rustc_index::IndexSlice; use rustc_middle::mir; use rustc_middle::ty; use rustc_middle::ty::layout::{LayoutOf, TyAndLayout}; -use rustc_middle::ty::Ty; +use rustc_middle::ty::{Mutability, Ty}; use rustc_target::abi::{Abi, Align, FieldIdx, HasDataLayout, Size, FIRST_VARIANT}; use super::{ diff --git a/compiler/rustc_const_eval/src/interpret/validity.rs b/compiler/rustc_const_eval/src/interpret/validity.rs index 082e5466fe2e7..8beb51f1ca275 100644 --- a/compiler/rustc_const_eval/src/interpret/validity.rs +++ b/compiler/rustc_const_eval/src/interpret/validity.rs @@ -9,7 +9,6 @@ use std::num::NonZeroUsize; use either::{Left, Right}; -use rustc_ast::Mutability; use rustc_data_structures::fx::FxHashSet; use rustc_hir as hir; use rustc_middle::mir::interpret::{ @@ -18,6 +17,7 @@ use rustc_middle::mir::interpret::{ }; use rustc_middle::ty; use rustc_middle::ty::layout::{LayoutOf, TyAndLayout}; +use rustc_middle::ty::Mutability; use rustc_span::symbol::{sym, Symbol}; use rustc_target::abi::{ Abi, FieldIdx, Scalar as ScalarAbi, Size, VariantIdx, Variants, WrappingRange, diff --git a/compiler/rustc_const_eval/src/transform/check_consts/check.rs b/compiler/rustc_const_eval/src/transform/check_consts/check.rs index 92e7922ad3b0c..77bce0462645b 100644 --- a/compiler/rustc_const_eval/src/transform/check_consts/check.rs +++ b/compiler/rustc_const_eval/src/transform/check_consts/check.rs @@ -198,7 +198,7 @@ impl<'ck, 'mir, 'tcx> TypeVisitor> for LocalReturnTyVisitor<'ck, 'm fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow { match t.kind() { ty::FnPtr(_) => ControlFlow::Continue(()), - ty::Ref(_, _, hir::Mutability::Mut) => { + ty::Ref(_, _, Mutability::Mut) => { self.checker.check_op(ops::ty::MutRef(self.kind)); t.super_visit_with(self) } diff --git a/compiler/rustc_hir_analysis/src/astconv/mod.rs b/compiler/rustc_hir_analysis/src/astconv/mod.rs index 2fcb45ef8aa12..c358765edf650 100644 --- a/compiler/rustc_hir_analysis/src/astconv/mod.rs +++ b/compiler/rustc_hir_analysis/src/astconv/mod.rs @@ -2475,14 +2475,31 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { let result_ty = match &ast_ty.kind { hir::TyKind::Slice(ty) => Ty::new_slice(tcx, self.ast_ty_to_ty(ty)), - hir::TyKind::Ptr(mt) => { - Ty::new_ptr(tcx, ty::TypeAndMut { ty: self.ast_ty_to_ty(mt.ty), mutbl: mt.mutbl }) - } + hir::TyKind::Ptr(mt) => Ty::new_ptr( + tcx, + ty::TypeAndMut { + ty: self.ast_ty_to_ty(mt.ty), + mutbl: match mt.mutbl { + hir::Mutability::Mut => ty::Mutability::Mut, + hir::Mutability::Not => ty::Mutability::Not, + }, + }, + ), hir::TyKind::Ref(region, mt) => { let r = self.ast_region_to_region(region, None); debug!(?r); let t = self.ast_ty_to_ty_inner(mt.ty, true, false); - Ty::new_ref(tcx, r, ty::TypeAndMut { ty: t, mutbl: mt.mutbl }) + Ty::new_ref( + tcx, + r, + ty::TypeAndMut { + ty: t, + mutbl: match mt.mutbl { + hir::Mutability::Mut => ty::Mutability::Mut, + hir::Mutability::Not => ty::Mutability::Not, + }, + }, + ) } hir::TyKind::Never => tcx.types.never, hir::TyKind::Tup(fields) => { diff --git a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs index a1470cc69c306..b718edd99ff23 100644 --- a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs +++ b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs @@ -1156,8 +1156,8 @@ fn report_trait_method_mismatch<'tcx>( let ty = trait_sig.inputs()[0]; let sugg = match ExplicitSelf::determine(ty, |ty| ty == impl_trait_ref.self_ty()) { ExplicitSelf::ByValue => "self".to_owned(), - ExplicitSelf::ByReference(_, hir::Mutability::Not) => "&self".to_owned(), - ExplicitSelf::ByReference(_, hir::Mutability::Mut) => "&mut self".to_owned(), + ExplicitSelf::ByReference(_, ty::Mutability::Not) => "&self".to_owned(), + ExplicitSelf::ByReference(_, ty::Mutability::Mut) => "&mut self".to_owned(), _ => format!("self: {ty}"), }; @@ -1375,8 +1375,8 @@ fn compare_self_type<'tcx>( let can_eq_self = |ty| infcx.can_eq(param_env, untransformed_self_ty, ty); match ExplicitSelf::determine(self_arg_ty, can_eq_self) { ExplicitSelf::ByValue => "self".to_owned(), - ExplicitSelf::ByReference(_, hir::Mutability::Not) => "&self".to_owned(), - ExplicitSelf::ByReference(_, hir::Mutability::Mut) => "&mut self".to_owned(), + ExplicitSelf::ByReference(_, ty::Mutability::Not) => "&self".to_owned(), + ExplicitSelf::ByReference(_, ty::Mutability::Mut) => "&mut self".to_owned(), _ => format!("self: {self_arg_ty}"), } }; diff --git a/compiler/rustc_hir_analysis/src/check/intrinsic.rs b/compiler/rustc_hir_analysis/src/check/intrinsic.rs index c61719c1fd293..ec5565f606f2a 100644 --- a/compiler/rustc_hir_analysis/src/check/intrinsic.rs +++ b/compiler/rustc_hir_analysis/src/check/intrinsic.rs @@ -206,7 +206,7 @@ pub fn check_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem<'_>) { | sym::prefetch_write_instruction => ( 1, vec![ - Ty::new_ptr(tcx, ty::TypeAndMut { ty: param(0), mutbl: hir::Mutability::Not }), + Ty::new_ptr(tcx, ty::TypeAndMut { ty: param(0), mutbl: ty::Mutability::Not }), tcx.types.i32, ], Ty::new_unit(tcx), @@ -220,10 +220,10 @@ pub fn check_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem<'_>) { sym::arith_offset => ( 1, vec![ - Ty::new_ptr(tcx, ty::TypeAndMut { ty: param(0), mutbl: hir::Mutability::Not }), + Ty::new_ptr(tcx, ty::TypeAndMut { ty: param(0), mutbl: ty::Mutability::Not }), tcx.types.isize, ], - Ty::new_ptr(tcx, ty::TypeAndMut { ty: param(0), mutbl: hir::Mutability::Not }), + Ty::new_ptr(tcx, ty::TypeAndMut { ty: param(0), mutbl: ty::Mutability::Not }), ), sym::option_payload_ptr => { let option_def_id = tcx.require_lang_item(hir::LangItem::Option, None); @@ -238,26 +238,26 @@ pub fn check_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem<'_>) { tcx.adt_def(option_def_id), tcx.mk_args_from_iter([ty::GenericArg::from(p0)].into_iter()), ), - mutbl: hir::Mutability::Not, + mutbl: ty::Mutability::Not, }, )], - Ty::new_ptr(tcx, ty::TypeAndMut { ty: p0, mutbl: hir::Mutability::Not }), + Ty::new_ptr(tcx, ty::TypeAndMut { ty: p0, mutbl: ty::Mutability::Not }), ) } sym::ptr_mask => ( 1, vec![ - Ty::new_ptr(tcx, ty::TypeAndMut { ty: param(0), mutbl: hir::Mutability::Not }), + Ty::new_ptr(tcx, ty::TypeAndMut { ty: param(0), mutbl: ty::Mutability::Not }), tcx.types.usize, ], - Ty::new_ptr(tcx, ty::TypeAndMut { ty: param(0), mutbl: hir::Mutability::Not }), + Ty::new_ptr(tcx, ty::TypeAndMut { ty: param(0), mutbl: ty::Mutability::Not }), ), sym::copy | sym::copy_nonoverlapping => ( 1, vec![ - Ty::new_ptr(tcx, ty::TypeAndMut { ty: param(0), mutbl: hir::Mutability::Not }), - Ty::new_ptr(tcx, ty::TypeAndMut { ty: param(0), mutbl: hir::Mutability::Mut }), + Ty::new_ptr(tcx, ty::TypeAndMut { ty: param(0), mutbl: ty::Mutability::Not }), + Ty::new_ptr(tcx, ty::TypeAndMut { ty: param(0), mutbl: ty::Mutability::Mut }), tcx.types.usize, ], Ty::new_unit(tcx), @@ -265,8 +265,8 @@ pub fn check_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem<'_>) { sym::volatile_copy_memory | sym::volatile_copy_nonoverlapping_memory => ( 1, vec![ - Ty::new_ptr(tcx, ty::TypeAndMut { ty: param(0), mutbl: hir::Mutability::Mut }), - Ty::new_ptr(tcx, ty::TypeAndMut { ty: param(0), mutbl: hir::Mutability::Not }), + Ty::new_ptr(tcx, ty::TypeAndMut { ty: param(0), mutbl: ty::Mutability::Mut }), + Ty::new_ptr(tcx, ty::TypeAndMut { ty: param(0), mutbl: ty::Mutability::Not }), tcx.types.usize, ], Ty::new_unit(tcx), @@ -278,7 +278,7 @@ pub fn check_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem<'_>) { sym::write_bytes | sym::volatile_set_memory => ( 1, vec![ - Ty::new_ptr(tcx, ty::TypeAndMut { ty: param(0), mutbl: hir::Mutability::Mut }), + Ty::new_ptr(tcx, ty::TypeAndMut { ty: param(0), mutbl: ty::Mutability::Mut }), tcx.types.u8, tcx.types.usize, ], @@ -441,12 +441,12 @@ pub fn check_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem<'_>) { ) } - sym::va_start | sym::va_end => match mk_va_list_ty(hir::Mutability::Mut) { + sym::va_start | sym::va_end => match mk_va_list_ty(ty::Mutability::Mut) { Some((va_list_ref_ty, _)) => (0, vec![va_list_ref_ty], Ty::new_unit(tcx)), None => bug!("`va_list` language item needed for C-variadic intrinsics"), }, - sym::va_copy => match mk_va_list_ty(hir::Mutability::Not) { + sym::va_copy => match mk_va_list_ty(ty::Mutability::Not) { Some((va_list_ref_ty, va_list_ty)) => { let va_list_ptr_ty = Ty::new_mut_ptr(tcx, va_list_ty); (0, vec![va_list_ptr_ty, va_list_ref_ty], Ty::new_unit(tcx)) @@ -454,7 +454,7 @@ pub fn check_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem<'_>) { None => bug!("`va_list` language item needed for C-variadic intrinsics"), }, - sym::va_arg => match mk_va_list_ty(hir::Mutability::Mut) { + sym::va_arg => match mk_va_list_ty(ty::Mutability::Mut) { Some((va_list_ref_ty, _)) => (1, vec![va_list_ref_ty], param(0)), None => bug!("`va_list` language item needed for C-variadic intrinsics"), }, diff --git a/compiler/rustc_hir_analysis/src/check/wfcheck.rs b/compiler/rustc_hir_analysis/src/check/wfcheck.rs index 34c28bce5d8bb..240d5ed9f52ad 100644 --- a/compiler/rustc_hir_analysis/src/check/wfcheck.rs +++ b/compiler/rustc_hir_analysis/src/check/wfcheck.rs @@ -901,7 +901,7 @@ fn check_param_wf(tcx: TyCtxt<'_>, param: &hir::GenericParam<'_>) { ty::Slice(ty) => ty_is_local(*ty), // `&` references use the inner type's `ConstParamTy`. // `&mut` are not supported. - ty::Ref(_, ty, ast::Mutability::Not) => ty_is_local(*ty), + ty::Ref(_, ty, ty::Mutability::Not) => ty_is_local(*ty), // Say that a tuple is local if any of its components are local. // This is not strictly correct, but it's likely that the user can fix the local component. ty::Tuple(tys) => tys.iter().any(|ty| ty_is_local(ty)), diff --git a/compiler/rustc_hir_analysis/src/variance/constraints.rs b/compiler/rustc_hir_analysis/src/variance/constraints.rs index 61d9c989e2fd9..f95676ff6ad61 100644 --- a/compiler/rustc_hir_analysis/src/variance/constraints.rs +++ b/compiler/rustc_hir_analysis/src/variance/constraints.rs @@ -447,12 +447,12 @@ impl<'a, 'tcx> ConstraintContext<'a, 'tcx> { variance: VarianceTermPtr<'a>, ) { match mt.mutbl { - hir::Mutability::Mut => { + ty::Mutability::Mut => { let invar = self.invariant(variance); self.add_constraints_from_ty(current, mt.ty, invar); } - hir::Mutability::Not => { + ty::Mutability::Not => { self.add_constraints_from_ty(current, mt.ty, variance); } } diff --git a/compiler/rustc_hir_typeck/src/coercion.rs b/compiler/rustc_hir_typeck/src/coercion.rs index 6c03bc3b57ac6..4ca515bd88b55 100644 --- a/compiler/rustc_hir_typeck/src/coercion.rs +++ b/compiler/rustc_hir_typeck/src/coercion.rs @@ -107,8 +107,8 @@ impl<'tcx> Visitor<'tcx> for CollectRetsVisitor<'tcx> { /// Coercing a mutable reference to an immutable works, while /// coercing `&T` to `&mut T` should be forbidden. fn coerce_mutbls<'tcx>( - from_mutbl: hir::Mutability, - to_mutbl: hir::Mutability, + from_mutbl: ty::Mutability, + to_mutbl: ty::Mutability, ) -> RelateResult<'tcx, ()> { if from_mutbl >= to_mutbl { Ok(()) } else { Err(TypeError::Mutability) } } @@ -325,7 +325,7 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { a: Ty<'tcx>, b: Ty<'tcx>, r_b: ty::Region<'tcx>, - mutbl_b: hir::Mutability, + mutbl_b: ty::Mutability, ) -> CoerceResult<'tcx> { debug!("coerce_borrowed_pointer(a={:?}, b={:?})", a, b); @@ -969,7 +969,7 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { &self, a: Ty<'tcx>, b: Ty<'tcx>, - mutbl_b: hir::Mutability, + mutbl_b: ty::Mutability, ) -> CoerceResult<'tcx> { debug!("coerce_unsafe_ptr(a={:?}, b={:?})", a, b); @@ -1262,7 +1262,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ] => { match *self.node_ty(expr.hir_id).kind() { ty::Ref(_, _, mt_orig) => { - let mutbl_adj: hir::Mutability = mutbl_adj.into(); + let mutbl_adj: ty::Mutability = mutbl_adj.into(); // Reborrow that we can safely ignore, because // the next adjustment can only be a Deref // which will be merged into it. diff --git a/compiler/rustc_hir_typeck/src/demand.rs b/compiler/rustc_hir_typeck/src/demand.rs index 65ec2f232aed7..8dbd3b6a76808 100644 --- a/compiler/rustc_hir_typeck/src/demand.rs +++ b/compiler/rustc_hir_typeck/src/demand.rs @@ -854,7 +854,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }); let mutability = match self.tcx.fn_sig(m.def_id).skip_binder().input(0).skip_binder().kind() { - ty::Ref(_, _, hir::Mutability::Mut) => "&mut ", + ty::Ref(_, _, ty::Mutability::Mut) => "&mut ", ty::Ref(_, _, _) => "&", _ => "", }; @@ -1518,10 +1518,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // bar(&x); // error, expected &mut // ``` let ref_ty = match mutability { - hir::Mutability::Mut => { + ty::Mutability::Mut => { Ty::new_mut_ref(self.tcx, self.tcx.lifetimes.re_static, checked_ty) } - hir::Mutability::Not => { + ty::Mutability::Not => { Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_static, checked_ty) } }; diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index 96df0346ac643..6c8cc851897c6 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -437,7 +437,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let ty = self.check_expr_with_expectation_and_needs(&oprnd, hint, Needs::maybe_mut_place(mutbl)); - let tm = ty::TypeAndMut { ty, mutbl }; + let tm = ty::TypeAndMut { + ty, + mutbl: match mutbl { + hir::Mutability::Mut => ty::Mutability::Mut, + hir::Mutability::Not => ty::Mutability::Not, + }, + }; match kind { _ if tm.ty.references_error() => Ty::new_misc_error(self.tcx), hir::BorrowKind::Raw => { diff --git a/compiler/rustc_hir_typeck/src/expr_use_visitor.rs b/compiler/rustc_hir_typeck/src/expr_use_visitor.rs index 8bc66ac5509be..c322ac902d716 100644 --- a/compiler/rustc_hir_typeck/src/expr_use_visitor.rs +++ b/compiler/rustc_hir_typeck/src/expr_use_visitor.rs @@ -271,7 +271,7 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { // &base // make sure that the thing we are pointing out stays valid // for the lifetime `scope_r` of the resulting ptr: - let bk = ty::BorrowKind::from_mutbl(m); + let bk = ty::BorrowKind::from_hir(m); self.borrow_expr(base, bk); } @@ -607,7 +607,7 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { // `x.deref()`. Since `deref()` is declared with `&self`, // this is an autoref of `x`. adjustment::Adjust::Deref(Some(ref deref)) => { - let bk = ty::BorrowKind::from_mutbl(deref.mutbl); + let bk = ty::BorrowKind::from_ty(deref.mutbl); self.delegate.borrow(&place_with_id, place_with_id.hir_id, bk); } @@ -639,14 +639,14 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { self.delegate.borrow( base_place, base_place.hir_id, - ty::BorrowKind::from_mutbl(m.into()), + ty::BorrowKind::from_ty(m.into()), ); } adjustment::AutoBorrow::RawPtr(m) => { debug!("walk_autoref: expr.hir_id={} base_place={:?}", expr.hir_id, base_place); - self.delegate.borrow(base_place, base_place.hir_id, ty::BorrowKind::from_mutbl(m)); + self.delegate.borrow(base_place, base_place.hir_id, ty::BorrowKind::from_ty(m)); } } } @@ -732,7 +732,7 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { // of the discriminant. match bm { ty::BindByReference(m) => { - let bk = ty::BorrowKind::from_mutbl(m); + let bk = ty::BorrowKind::from_ty(m); delegate.borrow(place, discr_place.hir_id, bk); } ty::BindByValue(..) => { diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs index 6e0e02b78149e..abc2a53a75b8b 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs @@ -1028,7 +1028,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { && inputs .get(0) .and_then(|self_ty| self_ty.ref_mutability()) - .is_some_and(rustc_ast::Mutability::is_mut) + .is_some_and(ty::Mutability::is_mut) }) }; diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs index 9f1800b45c33a..bcf2c6934097d 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs @@ -1292,8 +1292,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { arg: &hir::Expr<'tcx>, err: &mut rustc_errors::DiagnosticBuilder<'tcx, ErrorGuaranteed>, ) { - if let ty::RawPtr(ty::TypeAndMut { mutbl: hir::Mutability::Mut, .. }) = expected_ty.kind() - && let ty::RawPtr(ty::TypeAndMut { mutbl: hir::Mutability::Not, .. }) = + if let ty::RawPtr(ty::TypeAndMut { mutbl: ty::Mutability::Mut, .. }) = expected_ty.kind() + && let ty::RawPtr(ty::TypeAndMut { mutbl: ty::Mutability::Not, .. }) = provided_ty.kind() && let hir::ExprKind::Call(callee, _) = arg.kind && let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = callee.kind diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs index 14d6914134343..d4452277fa81e 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs @@ -419,7 +419,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if let Some((found_ty_inner, expected_ty_inner, error_tys)) = self.deconstruct_option_or_result(found, expected) - && let ty::Ref(_, peeled, hir::Mutability::Not) = *expected_ty_inner.kind() + && let ty::Ref(_, peeled, ty::Mutability::Not) = *expected_ty_inner.kind() { // Suggest removing any stray borrows (unless there's macro shenanigans involved). let inner_expr = expr.peel_borrows(); @@ -1092,7 +1092,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { expr_ty: Ty<'tcx>, expected_ty: Ty<'tcx>, ) -> bool { - if let ty::Ref(_, inner_ty, hir::Mutability::Not) = expr_ty.kind() + if let ty::Ref(_, inner_ty, ty::Mutability::Not) = expr_ty.kind() && let Some(clone_trait_def) = self.tcx.lang_items().clone_trait() && expected_ty == *inner_ty && self @@ -1416,8 +1416,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // We need to find a null pointer symbol to suggest let null_sym = match mutbl { - hir::Mutability::Not => sym::ptr_null, - hir::Mutability::Mut => sym::ptr_null_mut, + ty::Mutability::Not => sym::ptr_null, + ty::Mutability::Mut => sym::ptr_null_mut, }; let Some(null_did) = self.tcx.get_diagnostic_item(null_sym) else { return false; diff --git a/compiler/rustc_hir_typeck/src/method/confirm.rs b/compiler/rustc_hir_typeck/src/method/confirm.rs index 7c73f6a89cdb2..e9ce5dee9fbe6 100644 --- a/compiler/rustc_hir_typeck/src/method/confirm.rs +++ b/compiler/rustc_hir_typeck/src/method/confirm.rs @@ -223,7 +223,7 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { target = match target.kind() { &ty::RawPtr(ty::TypeAndMut { ty, mutbl }) => { assert!(mutbl.is_mut()); - Ty::new_ptr(self.tcx, ty::TypeAndMut { mutbl: hir::Mutability::Not, ty }) + Ty::new_ptr(self.tcx, ty::TypeAndMut { mutbl: ty::Mutability::Not, ty }) } other => panic!("Cannot adjust receiver type {other:?} to const ptr"), }; diff --git a/compiler/rustc_hir_typeck/src/method/probe.rs b/compiler/rustc_hir_typeck/src/method/probe.rs index 74f469cb39cbf..c5e8f2a87e279 100644 --- a/compiler/rustc_hir_typeck/src/method/probe.rs +++ b/compiler/rustc_hir_typeck/src/method/probe.rs @@ -176,7 +176,7 @@ pub enum AutorefOrPtrAdjustment { /// Receiver has type `T`, add `&` or `&mut` (it `T` is `mut`), and maybe also "unsize" it. /// Unsizing is used to convert a `[T; N]` to `[T]`, which only makes sense when autorefing. Autoref { - mutbl: hir::Mutability, + mutbl: ty::Mutability, /// Indicates that the source expression should be "unsized" to a target type. /// This is special-cased for just arrays unsizing to slices. @@ -1146,14 +1146,14 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { self.pick_autorefd_method( step, self_ty, - hir::Mutability::Not, + ty::Mutability::Not, unstable_candidates.as_deref_mut(), ) .or_else(|| { self.pick_autorefd_method( step, self_ty, - hir::Mutability::Mut, + ty::Mutability::Mut, unstable_candidates.as_deref_mut(), ) }) @@ -1206,7 +1206,7 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { &self, step: &CandidateStep<'tcx>, self_ty: Ty<'tcx>, - mutbl: hir::Mutability, + mutbl: ty::Mutability, unstable_candidates: Option<&mut Vec<(Candidate<'tcx>, Symbol)>>, ) -> Option> { let tcx = self.tcx; @@ -1239,11 +1239,11 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { return None; } - let &ty::RawPtr(ty::TypeAndMut { ty, mutbl: hir::Mutability::Mut }) = self_ty.kind() else { + let &ty::RawPtr(ty::TypeAndMut { ty, mutbl: ty::Mutability::Mut }) = self_ty.kind() else { return None; }; - let const_self_ty = ty::TypeAndMut { ty, mutbl: hir::Mutability::Not }; + let const_self_ty = ty::TypeAndMut { ty, mutbl: ty::Mutability::Not }; let const_ptr_ty = Ty::new_ptr(self.tcx, const_self_ty); self.pick_method(const_ptr_ty, unstable_candidates).map(|r| { r.map(|mut pick| { diff --git a/compiler/rustc_hir_typeck/src/method/suggest.rs b/compiler/rustc_hir_typeck/src/method/suggest.rs index 6b0dc73d49c68..2a86105b9553f 100644 --- a/compiler/rustc_hir_typeck/src/method/suggest.rs +++ b/compiler/rustc_hir_typeck/src/method/suggest.rs @@ -5,7 +5,6 @@ use crate::errors; use crate::errors::{CandidateTraitNote, NoAssociatedItem}; use crate::Expectation; use crate::FnCtxt; -use rustc_ast::ast::Mutability; use rustc_attr::parse_confusables; use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; use rustc_data_structures::unord::UnordSet; @@ -2075,8 +2074,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { )); } else if tcx.is_diagnostic_item(sym::RefCell, inner_id) { let (suggestion, borrow_kind, panic_if) = match mutable { - Some(Mutability::Not) => (".borrow()", "borrow", "a mutable borrow exists"), - Some(Mutability::Mut) => { + Some(ty::Mutability::Not) => { + (".borrow()", "borrow", "a mutable borrow exists") + } + Some(ty::Mutability::Mut) => { (".borrow_mut()", "mutably borrow", "any borrows exist") } None => return, @@ -2102,8 +2103,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ); } else if tcx.is_diagnostic_item(sym::RwLock, inner_id) { let (suggestion, borrow_kind) = match mutable { - Some(Mutability::Not) => (".read().unwrap()", "borrow"), - Some(Mutability::Mut) => (".write().unwrap()", "mutably borrow"), + Some(ty::Mutability::Not) => (".read().unwrap()", "borrow"), + Some(ty::Mutability::Mut) => (".write().unwrap()", "mutably borrow"), None => return, }; err.span_suggestion_verbose( diff --git a/compiler/rustc_hir_typeck/src/op.rs b/compiler/rustc_hir_typeck/src/op.rs index c46e641b10d24..2e5953bfb2d35 100644 --- a/compiler/rustc_hir_typeck/src/op.rs +++ b/compiler/rustc_hir_typeck/src/op.rs @@ -412,9 +412,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let suggest_different_borrow = |err: &mut DiagnosticBuilder<'_, _>, lhs_adjusted_ty, - lhs_new_mutbl: Option, + lhs_new_mutbl: Option, rhs_adjusted_ty, - rhs_new_mutbl: Option| { + rhs_new_mutbl: Option| { if self .lookup_op_method( lhs_adjusted_ty, @@ -442,7 +442,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ); } else { let mut suggest_new_borrow = - |new_mutbl: ast::Mutability, sp: Span| { + |new_mutbl: ty::Mutability, sp: Span| { // Can reborrow (&mut -> &) if new_mutbl.is_not() { err.span_suggestion_verbose( @@ -1073,7 +1073,7 @@ enum Op { /// Dereferences a single level of immutable referencing. fn deref_ty_if_possible(ty: Ty<'_>) -> Ty<'_> { match ty.kind() { - ty::Ref(_, ty, hir::Mutability::Not) => *ty, + ty::Ref(_, ty, ty::Mutability::Not) => *ty, _ => ty, } } diff --git a/compiler/rustc_hir_typeck/src/pat.rs b/compiler/rustc_hir_typeck/src/pat.rs index 110ec052b35d4..ba48e440042d6 100644 --- a/compiler/rustc_hir_typeck/src/pat.rs +++ b/compiler/rustc_hir_typeck/src/pat.rs @@ -121,7 +121,7 @@ impl<'tcx> FnCtxt<'_, 'tcx> { } } -const INITIAL_BM: BindingMode = BindingMode::BindByValue(hir::Mutability::Not); +const INITIAL_BM: BindingMode = BindingMode::BindByValue(ty::Mutability::Not); /// Mode for adjusting the expected type and binding mode. enum AdjustMode { @@ -200,7 +200,16 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.check_pat_tuple(pat.span, elements, ddpos, expected, pat_info) } PatKind::Box(inner) => self.check_pat_box(pat.span, inner, expected, pat_info), - PatKind::Ref(inner, mutbl) => self.check_pat_ref(pat, inner, mutbl, expected, pat_info), + PatKind::Ref(inner, mutbl) => self.check_pat_ref( + pat, + inner, + match mutbl { + hir::Mutability::Mut => ty::Mutability::Mut, + hir::Mutability::Not => ty::Mutability::Not, + }, + expected, + pat_info, + ), PatKind::Slice(before, slice, after) => { self.check_pat_slice(pat.span, before, slice, after, expected, pat_info) } @@ -362,10 +371,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // (depending on whether we observe `&` or `&mut`). ty::BindByValue(_) | // When `ref mut`, stay a `ref mut` (on `&mut`) or downgrade to `ref` (on `&`). - ty::BindByReference(hir::Mutability::Mut) => inner_mutability, + ty::BindByReference(ty::Mutability::Mut) => inner_mutability, // Once a `ref`, always a `ref`. // This is because a `& &mut` cannot mutate the underlying value. - ty::BindByReference(m @ hir::Mutability::Not) => m, + ty::BindByReference(m @ ty::Mutability::Not) => m, }); } @@ -1966,7 +1975,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { &self, pat: &'tcx Pat<'tcx>, inner: &'tcx Pat<'tcx>, - mutbl: hir::Mutability, + mutbl: ty::Mutability, expected: Ty<'tcx>, pat_info: PatInfo<'tcx, '_>, ) -> Ty<'tcx> { @@ -2017,7 +2026,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } /// Create a reference type with a fresh region variable. - fn new_ref_ty(&self, span: Span, mutbl: hir::Mutability, ty: Ty<'tcx>) -> Ty<'tcx> { + fn new_ref_ty(&self, span: Span, mutbl: ty::Mutability, ty: Ty<'tcx>) -> Ty<'tcx> { let region = self.next_region_var(infer::PatternRegion(span)); let mt = ty::TypeAndMut { ty, mutbl }; Ty::new_ref(self.tcx, region, mt) diff --git a/compiler/rustc_hir_typeck/src/place_op.rs b/compiler/rustc_hir_typeck/src/place_op.rs index 406434e09e68e..53daf173ad989 100644 --- a/compiler/rustc_hir_typeck/src/place_op.rs +++ b/compiler/rustc_hir_typeck/src/place_op.rs @@ -26,7 +26,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let ok = self.try_overloaded_deref(expr.span, oprnd_ty)?; let method = self.register_infer_ok_obligations(ok); - if let ty::Ref(region, _, hir::Mutability::Not) = method.sig.inputs()[0].kind() { + if let ty::Ref(region, _, ty::Mutability::Not) = method.sig.inputs()[0].kind() { self.apply_adjustments( oprnd_expr, vec![Adjustment { @@ -159,13 +159,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let method = self.register_infer_ok_obligations(result); let mut adjustments = self.adjust_steps(autoderef); - if let ty::Ref(region, _, hir::Mutability::Not) = method.sig.inputs()[0].kind() { + if let ty::Ref(region, _, ty::Mutability::Not) = method.sig.inputs()[0].kind() { adjustments.push(Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(*region, AutoBorrowMutability::Not)), target: Ty::new_ref( self.tcx, *region, - ty::TypeAndMut { mutbl: hir::Mutability::Not, ty: adjusted_ty }, + ty::TypeAndMut { mutbl: ty::Mutability::Not, ty: adjusted_ty }, ), }); } else { @@ -406,7 +406,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { debug!("convert_place_op_to_mutable: method={:?}", method); self.write_method_call(expr.hir_id, method); - let ty::Ref(region, _, hir::Mutability::Mut) = method.sig.inputs()[0].kind() else { + let ty::Ref(region, _, ty::Mutability::Mut) = method.sig.inputs()[0].kind() else { span_bug!(expr.span, "input to mutable place op is not a mut ref?"); }; diff --git a/compiler/rustc_hir_typeck/src/upvar.rs b/compiler/rustc_hir_typeck/src/upvar.rs index 4d64139036811..320877ecd8593 100644 --- a/compiler/rustc_hir_typeck/src/upvar.rs +++ b/compiler/rustc_hir_typeck/src/upvar.rs @@ -1582,7 +1582,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { &self, typeck_results: &'a TypeckResults<'tcx>, place: &Place<'tcx>, - ) -> hir::Mutability { + ) -> ty::Mutability { let var_hir_id = match place.base { PlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id, _ => unreachable!(), @@ -1592,7 +1592,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let mut is_mutbl = match bm { ty::BindByValue(mutability) => mutability, - ty::BindByReference(_) => hir::Mutability::Not, + ty::BindByReference(_) => ty::Mutability::Not, }; for pointer_ty in place.deref_tys() { @@ -1602,10 +1602,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Dereferencing a mut-ref allows us to mut the Place if we don't deref // an immut-ref after on top of this. - ty::Ref(.., hir::Mutability::Mut) => is_mutbl = hir::Mutability::Mut, + ty::Ref(.., ty::Mutability::Mut) => is_mutbl = ty::Mutability::Mut, // The place isn't mutable once we dereference an immutable reference. - ty::Ref(.., hir::Mutability::Not) => return hir::Mutability::Not, + ty::Ref(.., ty::Mutability::Not) => return ty::Mutability::Not, // Dereferencing a box doesn't change mutability ty::Adt(def, ..) if def.is_box() => {} @@ -2116,7 +2116,7 @@ fn truncate_place_to_len_and_update_capture_kind<'tcx>( curr_mode: &mut ty::UpvarCapture, len: usize, ) { - let is_mut_ref = |ty: Ty<'_>| matches!(ty.kind(), ty::Ref(.., hir::Mutability::Mut)); + let is_mut_ref = |ty: Ty<'_>| matches!(ty.kind(), ty::Ref(.., ty::Mutability::Mut)); // If the truncated part of the place contains `Deref` of a `&mut` then convert MutBorrow -> // UniqueImmBorrow @@ -2211,7 +2211,7 @@ fn truncate_capture_for_optimization( mut place: Place<'_>, mut curr_mode: ty::UpvarCapture, ) -> (Place<'_>, ty::UpvarCapture) { - let is_shared_ref = |ty: Ty<'_>| matches!(ty.kind(), ty::Ref(.., hir::Mutability::Not)); + let is_shared_ref = |ty: Ty<'_>| matches!(ty.kind(), ty::Ref(.., ty::Mutability::Not)); // Find the right-most deref (if any). All the projections that come after this // are fields or other "in-place pointer adjustments"; these refer therefore to diff --git a/compiler/rustc_infer/src/infer/error_reporting/mod.rs b/compiler/rustc_infer/src/infer/error_reporting/mod.rs index 496bb1766a71f..8336dce13a598 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/mod.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/mod.rs @@ -1189,7 +1189,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { fn push_ty_ref<'tcx>( region: ty::Region<'tcx>, ty: Ty<'tcx>, - mutbl: hir::Mutability, + mutbl: ty::Mutability, s: &mut DiagnosticStyledString, ) { let mut r = region.to_string(); diff --git a/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs b/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs index 5408b99235d42..24bcf5237f081 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs @@ -540,7 +540,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { [ .., Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(_, mut_)), target: _ }, - ] => hir::Mutability::from(*mut_).ref_prefix_str(), + ] => ty::Mutability::from(*mut_).ref_prefix_str(), _ => "", }; diff --git a/compiler/rustc_lint/src/reference_casting.rs b/compiler/rustc_lint/src/reference_casting.rs index d44691b5e9bac..059338a17de37 100644 --- a/compiler/rustc_lint/src/reference_casting.rs +++ b/compiler/rustc_lint/src/reference_casting.rs @@ -117,7 +117,7 @@ fn is_cast_from_const_to_mut<'tcx>( let end_ty = cx.typeck_results().node_type(orig_expr.hir_id); // Bail out early if the end type is **not** a mutable pointer. - if !matches!(end_ty.kind(), ty::RawPtr(TypeAndMut { ty: _, mutbl: Mutability::Mut })) { + if !matches!(end_ty.kind(), ty::RawPtr(TypeAndMut { ty: _, mutbl: ty::Mutability::Mut })) { return None; } @@ -154,7 +154,7 @@ fn is_cast_from_const_to_mut<'tcx>( } let start_ty = cx.typeck_results().node_type(e.hir_id); - if let ty::Ref(_, inner_ty, Mutability::Not) = start_ty.kind() { + if let ty::Ref(_, inner_ty, ty::Mutability::Not) = start_ty.kind() { // If an UnsafeCell method is involved we need to additionaly check the // inner type for the presence of the Freeze trait (ie does NOT contain // an UnsafeCell), since in that case we would incorrectly lint on valid casts. diff --git a/compiler/rustc_middle/src/mir/interpret/allocation.rs b/compiler/rustc_middle/src/mir/interpret/allocation.rs index aded3e495d922..88ca549b6ec0d 100644 --- a/compiler/rustc_middle/src/mir/interpret/allocation.rs +++ b/compiler/rustc_middle/src/mir/interpret/allocation.rs @@ -12,7 +12,6 @@ use std::ptr; use either::{Left, Right}; -use rustc_ast::Mutability; use rustc_data_structures::intern::Interned; use rustc_span::DUMMY_SP; use rustc_target::abi::{Align, HasDataLayout, Size}; @@ -80,7 +79,7 @@ pub struct Allocation> /// `true` if the allocation is mutable. /// Also used by codegen to determine if a static should be put into mutable memory, /// which happens for `static mut` and `static` with interior mutability. - pub mutability: Mutability, + pub mutability: ty::Mutability, /// Extra state for the machine. pub extra: Extra, } @@ -257,7 +256,7 @@ impl AllocRange { // The constructors are all without extra; the extra gets added by a machine hook later. impl Allocation { /// Creates an allocation from an existing `Bytes` value - this is needed for miri FFI support - pub fn from_raw_bytes(bytes: Bytes, align: Align, mutability: Mutability) -> Self { + pub fn from_raw_bytes(bytes: Bytes, align: Align, mutability: ty::Mutability) -> Self { let size = Size::from_bytes(bytes.len()); Self { bytes, @@ -273,7 +272,7 @@ impl Allocation { pub fn from_bytes<'a>( slice: impl Into>, align: Align, - mutability: Mutability, + mutability: ty::Mutability, ) -> Self { let bytes = Bytes::from_bytes(slice, align); let size = Size::from_bytes(bytes.len()); @@ -288,7 +287,7 @@ impl Allocation { } pub fn from_bytes_byte_aligned_immutable<'a>(slice: impl Into>) -> Self { - Allocation::from_bytes(slice, Align::ONE, Mutability::Not) + Allocation::from_bytes(slice, Align::ONE, ty::Mutability::Not) } fn uninit_inner(size: Size, align: Align, fail: impl FnOnce() -> R) -> Result { @@ -305,7 +304,7 @@ impl Allocation { provenance: ProvenanceMap::new(), init_mask: InitMask::new(size, false), align, - mutability: Mutability::Mut, + mutability: ty::Mutability::Mut, extra: (), }) } @@ -495,7 +494,7 @@ impl Allocation if range.size.bytes() == 0 { return; } - assert!(self.mutability == Mutability::Mut); + assert_eq!(self.mutability, ty::Mutability::Mut); self.init_mask.set_range(range, is_init); } @@ -579,7 +578,7 @@ impl Allocation range: AllocRange, val: Scalar, ) -> AllocResult { - assert!(self.mutability == Mutability::Mut); + assert_eq!(self.mutability, ty::Mutability::Mut); // `to_bits_or_ptr_internal` is the right method because we just want to store this data // as-is into memory. This also double-checks that `val.size()` matches `range.size`. diff --git a/compiler/rustc_middle/src/mir/mod.rs b/compiler/rustc_middle/src/mir/mod.rs index 3a5ff4dc91fde..ff16355be2a13 100644 --- a/compiler/rustc_middle/src/mir/mod.rs +++ b/compiler/rustc_middle/src/mir/mod.rs @@ -22,8 +22,8 @@ use rustc_hir::{self as hir, HirId}; use rustc_session::Session; use rustc_target::abi::{FieldIdx, VariantIdx}; +pub use crate::ty::Mutability; use polonius_engine::Atom; -pub use rustc_ast::Mutability; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::graph::dominators::Dominators; diff --git a/compiler/rustc_middle/src/mir/syntax.rs b/compiler/rustc_middle/src/mir/syntax.rs index 7a645fb5d62ba..ac0c79d538474 100644 --- a/compiler/rustc_middle/src/mir/syntax.rs +++ b/compiler/rustc_middle/src/mir/syntax.rs @@ -6,6 +6,7 @@ use super::{BasicBlock, Const, Local, UserTypeProjection}; use crate::mir::coverage::CoverageKind; +use crate::mir::Mutability; use crate::traits::Reveal; use crate::ty::adjustment::PointerCoercion; use crate::ty::GenericArgsRef; @@ -19,7 +20,6 @@ use rustc_hir::{self, GeneratorKind}; use rustc_index::IndexVec; use rustc_target::abi::{FieldIdx, VariantIdx}; -use rustc_ast::Mutability; use rustc_span::def_id::LocalDefId; use rustc_span::symbol::Symbol; use rustc_span::Span; diff --git a/compiler/rustc_middle/src/mir/tcx.rs b/compiler/rustc_middle/src/mir/tcx.rs index 44ae75e2de701..292b4b8a47dde 100644 --- a/compiler/rustc_middle/src/mir/tcx.rs +++ b/compiler/rustc_middle/src/mir/tcx.rs @@ -271,14 +271,14 @@ impl<'tcx> BinOp { } impl BorrowKind { - pub fn to_mutbl_lossy(self) -> hir::Mutability { + pub fn to_mutbl_lossy(self) -> Mutability { match self { - BorrowKind::Mut { .. } => hir::Mutability::Mut, - BorrowKind::Shared => hir::Mutability::Not, + BorrowKind::Mut { .. } => Mutability::Mut, + BorrowKind::Shared => Mutability::Not, // We have no type corresponding to a shallow borrow, so use // `&` as an approximation. - BorrowKind::Shallow => hir::Mutability::Not, + BorrowKind::Shallow => Mutability::Not, } } } diff --git a/compiler/rustc_middle/src/thir.rs b/compiler/rustc_middle/src/thir.rs index 67804998a3293..8e11f45ca3232 100644 --- a/compiler/rustc_middle/src/thir.rs +++ b/compiler/rustc_middle/src/thir.rs @@ -397,7 +397,7 @@ pub enum ExprKind<'tcx> { }, /// A `&raw [const|mut] $place_expr` raw borrow resulting in type `*[const|mut] T`. AddressOf { - mutability: hir::Mutability, + mutability: ty::Mutability, arg: ExprId, }, /// A `break` expression. diff --git a/compiler/rustc_middle/src/ty/adjustment.rs b/compiler/rustc_middle/src/ty/adjustment.rs index c3e8991c63a20..3567dd1ade0ba 100644 --- a/compiler/rustc_middle/src/ty/adjustment.rs +++ b/compiler/rustc_middle/src/ty/adjustment.rs @@ -113,7 +113,7 @@ pub enum Adjust<'tcx> { #[derive(TypeFoldable, TypeVisitable)] pub struct OverloadedDeref<'tcx> { pub region: ty::Region<'tcx>, - pub mutbl: hir::Mutability, + pub mutbl: ty::Mutability, /// The `Span` associated with the field access or method call /// that triggered this overloaded deref. pub span: Span, @@ -123,8 +123,8 @@ impl<'tcx> OverloadedDeref<'tcx> { /// Get the zst function item type for this method call. pub fn method_call(&self, tcx: TyCtxt<'tcx>, source: Ty<'tcx>) -> Ty<'tcx> { let trait_def_id = match self.mutbl { - hir::Mutability::Not => tcx.require_lang_item(LangItem::Deref, None), - hir::Mutability::Mut => tcx.require_lang_item(LangItem::DerefMut, None), + ty::Mutability::Not => tcx.require_lang_item(LangItem::Deref, None), + ty::Mutability::Mut => tcx.require_lang_item(LangItem::DerefMut, None), }; let method_def_id = tcx .associated_items(trait_def_id) @@ -164,19 +164,19 @@ impl AutoBorrowMutability { /// Creates an `AutoBorrowMutability` from a mutability and allowance of two phase borrows. /// /// Note that when `mutbl.is_not()`, `allow_two_phase_borrow` is ignored - pub fn new(mutbl: hir::Mutability, allow_two_phase_borrow: AllowTwoPhase) -> Self { + pub fn new(mutbl: ty::Mutability, allow_two_phase_borrow: AllowTwoPhase) -> Self { match mutbl { - hir::Mutability::Not => Self::Not, - hir::Mutability::Mut => Self::Mut { allow_two_phase_borrow }, + ty::Mutability::Not => Self::Not, + ty::Mutability::Mut => Self::Mut { allow_two_phase_borrow }, } } } -impl From for hir::Mutability { +impl From for ty::Mutability { fn from(m: AutoBorrowMutability) -> Self { match m { - AutoBorrowMutability::Mut { .. } => hir::Mutability::Mut, - AutoBorrowMutability::Not => hir::Mutability::Not, + AutoBorrowMutability::Mut { .. } => ty::Mutability::Mut, + AutoBorrowMutability::Not => ty::Mutability::Not, } } } @@ -188,7 +188,7 @@ pub enum AutoBorrow<'tcx> { Ref(ty::Region<'tcx>, AutoBorrowMutability), /// Converts from T to *T. - RawPtr(hir::Mutability), + RawPtr(ty::Mutability), } /// Information for `CoerceUnsized` impls, storing information we diff --git a/compiler/rustc_middle/src/ty/binding.rs b/compiler/rustc_middle/src/ty/binding.rs index af594bc5f24c8..0714e8814e51b 100644 --- a/compiler/rustc_middle/src/ty/binding.rs +++ b/compiler/rustc_middle/src/ty/binding.rs @@ -1,4 +1,5 @@ -use rustc_hir::{BindingAnnotation, ByRef, Mutability}; +use crate::ty::Mutability; +use rustc_hir::{self as hir, BindingAnnotation, ByRef}; #[derive(Clone, PartialEq, TyEncodable, TyDecodable, Debug, Copy, HashStable)] pub enum BindingMode { @@ -10,6 +11,11 @@ TrivialTypeTraversalImpls! { BindingMode } impl BindingMode { pub fn convert(BindingAnnotation(by_ref, mutbl): BindingAnnotation) -> BindingMode { + let mutbl = match mutbl { + hir::Mutability::Not => Mutability::Not, + hir::Mutability::Mut => Mutability::Mut, + }; + match by_ref { ByRef::No => BindingMode::BindByValue(mutbl), ByRef::Yes => BindingMode::BindByReference(mutbl), diff --git a/compiler/rustc_middle/src/ty/closure.rs b/compiler/rustc_middle/src/ty/closure.rs index 74bdd07a1c946..b3ed679c730e4 100644 --- a/compiler/rustc_middle/src/ty/closure.rs +++ b/compiler/rustc_middle/src/ty/closure.rs @@ -153,7 +153,7 @@ pub struct CapturedPlace<'tcx> { pub info: CaptureInfo, /// Represents if `place` can be mutated or not. - pub mutability: hir::Mutability, + pub mutability: ty::Mutability, /// Region of the resulting reference if the upvar is captured by ref. pub region: Option>, @@ -451,26 +451,33 @@ pub enum BorrowKind { } impl BorrowKind { - pub fn from_mutbl(m: hir::Mutability) -> BorrowKind { + pub fn from_hir(m: hir::Mutability) -> BorrowKind { match m { hir::Mutability::Mut => MutBorrow, hir::Mutability::Not => ImmBorrow, } } + pub fn from_ty(m: ty::Mutability) -> BorrowKind { + match m { + ty::Mutability::Mut => MutBorrow, + ty::Mutability::Not => ImmBorrow, + } + } + /// Returns a mutability `m` such that an `&m T` pointer could be used to obtain this borrow /// kind. Because borrow kinds are richer than mutabilities, we sometimes have to pick a /// mutability that is stronger than necessary so that it at least *would permit* the borrow in /// question. - pub fn to_mutbl_lossy(self) -> hir::Mutability { + pub fn to_mutbl_lossy(self) -> ty::Mutability { match self { - MutBorrow => hir::Mutability::Mut, - ImmBorrow => hir::Mutability::Not, + MutBorrow => ty::Mutability::Mut, + ImmBorrow => ty::Mutability::Not, // We have no type corresponding to a unique imm borrow, so // use `&mut`. It gives all the capabilities of a `&uniq` // and hence is a safe "over approximation". - UniqueImmBorrow => hir::Mutability::Mut, + UniqueImmBorrow => ty::Mutability::Mut, } } } diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index 05706e331f3a7..8c9e6f027b7e2 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -90,7 +90,6 @@ impl<'tcx> Interner for TyCtxt<'tcx> { type Region = Region<'tcx>; type Predicate = Predicate<'tcx>; type TypeAndMut = TypeAndMut<'tcx>; - type Mutability = hir::Mutability; type Movability = hir::Movability; type PolyFnSig = PolyFnSig<'tcx>; type ListBinderExistentialPredicate = &'tcx List>; @@ -121,13 +120,9 @@ impl<'tcx> Interner for TyCtxt<'tcx> { fn ty_and_mut_to_parts( TypeAndMut { ty, mutbl }: TypeAndMut<'tcx>, - ) -> (Self::Ty, Self::Mutability) { + ) -> (Self::Ty, ty::Mutability) { (ty, mutbl) } - - fn mutability_is_mut(mutbl: Self::Mutability) -> bool { - mutbl.is_mut() - } } type InternedSet<'tcx, T> = ShardedHashMap, ()>; diff --git a/compiler/rustc_middle/src/ty/error.rs b/compiler/rustc_middle/src/ty/error.rs index 0fe1284eed991..c9362fd0cdc99 100644 --- a/compiler/rustc_middle/src/ty/error.rs +++ b/compiler/rustc_middle/src/ty/error.rs @@ -287,8 +287,8 @@ impl<'tcx> Ty<'tcx> { ty::Slice(_) => "slice".into(), ty::RawPtr(_) => "raw pointer".into(), ty::Ref(.., mutbl) => match mutbl { - hir::Mutability::Mut => "mutable reference", - _ => "reference", + ty::Mutability::Mut => "mutable reference", + ty::Mutability::Not => "reference", } .into(), ty::FnDef(def_id, ..) => match tcx.def_kind(def_id) { diff --git a/compiler/rustc_middle/src/ty/layout.rs b/compiler/rustc_middle/src/ty/layout.rs index 5ef7ee5263641..00ffefdbace2e 100644 --- a/compiler/rustc_middle/src/ty/layout.rs +++ b/compiler/rustc_middle/src/ty/layout.rs @@ -7,7 +7,6 @@ use rustc_error_messages::DiagnosticMessage; use rustc_errors::{ DiagnosticArgValue, DiagnosticBuilder, Handler, IntoDiagnostic, IntoDiagnosticArg, }; -use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_index::IndexVec; use rustc_session::config::OptLevel; @@ -1004,10 +1003,10 @@ where // attributes in LLVM have compile-time cost even in unoptimized builds). let optimize = tcx.sess.opts.optimize != OptLevel::No; let kind = match mt { - hir::Mutability::Not => PointerKind::SharedRef { + ty::Mutability::Not => PointerKind::SharedRef { frozen: optimize && ty.is_freeze(tcx, cx.param_env()), }, - hir::Mutability::Mut => PointerKind::MutableRef { + ty::Mutability::Mut => PointerKind::MutableRef { unpin: optimize && ty.is_unpin(tcx, cx.param_env()), }, }; diff --git a/compiler/rustc_middle/src/ty/print/pretty.rs b/compiler/rustc_middle/src/ty/print/pretty.rs index d8010c714970d..516a7708a8734 100644 --- a/compiler/rustc_middle/src/ty/print/pretty.rs +++ b/compiler/rustc_middle/src/ty/print/pretty.rs @@ -645,8 +645,8 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { p!(write( "*{} ", match tm.mutbl { - hir::Mutability::Mut => "mut", - hir::Mutability::Not => "const", + ty::Mutability::Mut => "mut", + ty::Mutability::Not => "const", } )); p!(print(tm.ty)) diff --git a/compiler/rustc_middle/src/ty/relate.rs b/compiler/rustc_middle/src/ty/relate.rs index fdfdd6cc8d6d9..c8929ab146918 100644 --- a/compiler/rustc_middle/src/ty/relate.rs +++ b/compiler/rustc_middle/src/ty/relate.rs @@ -124,8 +124,8 @@ pub fn relate_type_and_mut<'tcx, R: TypeRelation<'tcx>>( } else { let mutbl = a.mutbl; let (variance, info) = match mutbl { - hir::Mutability::Not => (ty::Covariant, ty::VarianceDiagInfo::None), - hir::Mutability::Mut => { + ty::Mutability::Not => (ty::Covariant, ty::VarianceDiagInfo::None), + ty::Mutability::Mut => { (ty::Invariant, ty::VarianceDiagInfo::Invariant { ty: base_ty, param_index: 0 }) } }; diff --git a/compiler/rustc_middle/src/ty/structural_impls.rs b/compiler/rustc_middle/src/ty/structural_impls.rs index 2adbe9e030997..ecdd10d5544c8 100644 --- a/compiler/rustc_middle/src/ty/structural_impls.rs +++ b/compiler/rustc_middle/src/ty/structural_impls.rs @@ -458,6 +458,7 @@ TrivialLiftImpls! { bool, usize, u64, + ty::Mutability, } // For some things about which the type library does not know, or does not diff --git a/compiler/rustc_middle/src/ty/sty.rs b/compiler/rustc_middle/src/ty/sty.rs index fc207a2c350de..9a5714489820b 100644 --- a/compiler/rustc_middle/src/ty/sty.rs +++ b/compiler/rustc_middle/src/ty/sty.rs @@ -53,7 +53,7 @@ pub type ConstKind<'tcx> = IrConstKind>; #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)] pub struct TypeAndMut<'tcx> { pub ty: Ty<'tcx>, - pub mutbl: hir::Mutability, + pub mutbl: ty::Mutability, } #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, TyEncodable, TyDecodable, Copy)] @@ -2051,12 +2051,12 @@ impl<'tcx> Ty<'tcx> { #[inline] pub fn new_mut_ref(tcx: TyCtxt<'tcx>, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> { - Ty::new_ref(tcx, r, TypeAndMut { ty, mutbl: hir::Mutability::Mut }) + Ty::new_ref(tcx, r, TypeAndMut { ty, mutbl: ty::Mutability::Mut }) } #[inline] pub fn new_imm_ref(tcx: TyCtxt<'tcx>, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> { - Ty::new_ref(tcx, r, TypeAndMut { ty, mutbl: hir::Mutability::Not }) + Ty::new_ref(tcx, r, TypeAndMut { ty, mutbl: ty::Mutability::Not }) } #[inline] @@ -2066,12 +2066,12 @@ impl<'tcx> Ty<'tcx> { #[inline] pub fn new_mut_ptr(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> { - Ty::new_ptr(tcx, TypeAndMut { ty, mutbl: hir::Mutability::Mut }) + Ty::new_ptr(tcx, TypeAndMut { ty, mutbl: ty::Mutability::Mut }) } #[inline] pub fn new_imm_ptr(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> { - Ty::new_ptr(tcx, TypeAndMut { ty, mutbl: hir::Mutability::Not }) + Ty::new_ptr(tcx, TypeAndMut { ty, mutbl: ty::Mutability::Not }) } #[inline] @@ -2404,14 +2404,13 @@ impl<'tcx> Ty<'tcx> { pub fn is_mutable_ptr(self) -> bool { matches!( self.kind(), - RawPtr(TypeAndMut { mutbl: hir::Mutability::Mut, .. }) - | Ref(_, _, hir::Mutability::Mut) + RawPtr(TypeAndMut { mutbl: ty::Mutability::Mut, .. }) | Ref(_, _, ty::Mutability::Mut) ) } /// Get the mutability of the reference or `None` when not a reference #[inline] - pub fn ref_mutability(self) -> Option { + pub fn ref_mutability(self) -> Option { match self.kind() { Ref(_, _, mutability) => Some(*mutability), _ => None, @@ -2586,7 +2585,7 @@ impl<'tcx> Ty<'tcx> { pub fn builtin_deref(self, explicit: bool) -> Option> { match self.kind() { Adt(def, _) if def.is_box() => { - Some(TypeAndMut { ty: self.boxed_ty(), mutbl: hir::Mutability::Not }) + Some(TypeAndMut { ty: self.boxed_ty(), mutbl: ty::Mutability::Not }) } Ref(_, ty, mutbl) => Some(TypeAndMut { ty: *ty, mutbl: *mutbl }), RawPtr(mt) if explicit => Some(*mt), @@ -2894,11 +2893,11 @@ impl<'tcx> Ty<'tcx> { ty::FnPtr(..) => false, // Definitely absolutely not copy. - ty::Ref(_, _, hir::Mutability::Mut) => false, + ty::Ref(_, _, ty::Mutability::Mut) => false, // Thin pointers & thin shared references are pure-clone-copy, but for // anything with custom metadata it might be more complicated. - ty::Ref(_, _, hir::Mutability::Not) | ty::RawPtr(..) => false, + ty::Ref(_, _, ty::Mutability::Not) | ty::RawPtr(..) => false, ty::Generator(..) | ty::GeneratorWitness(..) => false, diff --git a/compiler/rustc_middle/src/ty/util.rs b/compiler/rustc_middle/src/ty/util.rs index 31b52677b2797..45f72d8dbae58 100644 --- a/compiler/rustc_middle/src/ty/util.rs +++ b/compiler/rustc_middle/src/ty/util.rs @@ -641,7 +641,7 @@ impl<'tcx> TyCtxt<'tcx> { /// Returns `true` if the node pointed to by `def_id` is a mutable `static` item. #[inline] pub fn is_mutable_static(self, def_id: DefId) -> bool { - self.static_mutability(def_id) == Some(hir::Mutability::Mut) + self.static_mutability(def_id).is_some_and(|mt| mt.is_mut()) } /// Returns `true` if the item pointed to by `def_id` is a thread local which needs a @@ -1222,8 +1222,8 @@ impl<'tcx> Ty<'tcx> { pub enum ExplicitSelf<'tcx> { ByValue, - ByReference(ty::Region<'tcx>, hir::Mutability), - ByRawPointer(hir::Mutability), + ByReference(ty::Region<'tcx>, ty::Mutability), + ByRawPointer(ty::Mutability), ByBox, Other, } diff --git a/compiler/rustc_middle/src/ty/vtable.rs b/compiler/rustc_middle/src/ty/vtable.rs index 62f41921d888a..90e94cf5a8627 100644 --- a/compiler/rustc_middle/src/ty/vtable.rs +++ b/compiler/rustc_middle/src/ty/vtable.rs @@ -2,7 +2,6 @@ use std::fmt; use crate::mir::interpret::{alloc_range, AllocId, Allocation, Pointer, Scalar}; use crate::ty::{self, Instance, PolyTraitRef, Ty, TyCtxt}; -use rustc_ast::Mutability; #[derive(Clone, Copy, PartialEq, HashStable)] pub enum VtblEntry<'tcx> { @@ -111,6 +110,6 @@ pub(super) fn vtable_allocation_provider<'tcx>( .expect("failed to build vtable representation"); } - vtable.mutability = Mutability::Not; + vtable.mutability = ty::Mutability::Not; tcx.reserve_and_set_memory_alloc(tcx.mk_const_alloc(vtable)) } diff --git a/compiler/rustc_mir_build/src/build/expr/into.rs b/compiler/rustc_mir_build/src/build/expr/into.rs index a4de42d45c995..495fa2b13d88f 100644 --- a/compiler/rustc_mir_build/src/build/expr/into.rs +++ b/compiler/rustc_mir_build/src/build/expr/into.rs @@ -5,10 +5,9 @@ use crate::build::{BlockAnd, BlockAndExtension, BlockFrame, Builder, NeedsTempor use rustc_ast::InlineAsmOptions; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::stack::ensure_sufficient_stack; -use rustc_hir as hir; use rustc_middle::mir::*; use rustc_middle::thir::*; -use rustc_middle::ty::CanonicalUserTypeAnnotation; +use rustc_middle::ty::{CanonicalUserTypeAnnotation, Mutability}; use std::iter; impl<'a, 'tcx> Builder<'a, 'tcx> { @@ -299,8 +298,8 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { ExprKind::AddressOf { mutability, arg } => { let arg = &this.thir[arg]; let place = match mutability { - hir::Mutability::Not => this.as_read_only_place(block, arg), - hir::Mutability::Mut => this.as_place(block, arg), + Mutability::Not => this.as_read_only_place(block, arg), + Mutability::Mut => this.as_place(block, arg), }; let address_of = Rvalue::AddressOf(mutability, unpack!(block = place)); this.cfg.push_assign(block, source_info, destination, address_of); diff --git a/compiler/rustc_mir_build/src/thir/cx/expr.rs b/compiler/rustc_mir_build/src/thir/cx/expr.rs index 0535ea24b82d6..0ad7a5f44871c 100644 --- a/compiler/rustc_mir_build/src/thir/cx/expr.rs +++ b/compiler/rustc_mir_build/src/thir/cx/expr.rs @@ -418,7 +418,13 @@ impl<'tcx> Cx<'tcx> { } hir::ExprKind::AddrOf(hir::BorrowKind::Raw, mutability, ref arg) => { - ExprKind::AddressOf { mutability, arg: self.mirror_expr(arg) } + ExprKind::AddressOf { + mutability: match mutability { + hir::Mutability::Not => ty::Mutability::Not, + hir::Mutability::Mut => ty::Mutability::Mut, + }, + arg: self.mirror_expr(arg), + } } hir::ExprKind::Block(ref blk, _) => ExprKind::Block { block: self.mirror_block(blk) }, @@ -1170,6 +1176,15 @@ impl ToBorrowKind for hir::Mutability { } } +impl ToBorrowKind for ty::Mutability { + fn to_borrow_kind(&self) -> BorrowKind { + match *self { + ty::Mutability::Mut => BorrowKind::Mut { kind: mir::MutBorrowKind::Default }, + ty::Mutability::Not => BorrowKind::Shared, + } + } +} + fn bin_op(op: hir::BinOpKind) -> BinOp { match op { hir::BinOpKind::Add => BinOp::Add, diff --git a/compiler/rustc_mir_build/src/thir/pattern/check_match.rs b/compiler/rustc_mir_build/src/thir/pattern/check_match.rs index 9d38087fdeb9d..f6265102b50b8 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/check_match.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/check_match.rs @@ -6,7 +6,6 @@ use super::usefulness::{ use crate::errors::*; use rustc_arena::TypedArena; -use rustc_ast::Mutability; use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_errors::{ @@ -580,7 +579,7 @@ fn check_for_bindings_named_same_as_variants( if let PatKind::Binding { name, mode: BindingMode::ByValue, - mutability: Mutability::Not, + mutability: ty::Mutability::Not, subpattern: None, ty, .. @@ -1036,15 +1035,15 @@ fn check_borrow_conflicts_in_at_patterns<'tcx>(cx: &MatchVisitor<'_, '_, 'tcx>, match mode { BindingMode::ByRef(mut_inner) => match (mut_outer, mut_inner.mutability()) { // Both sides are `ref`. - (Mutability::Not, Mutability::Not) => {} + (ty::Mutability::Not, ty::Mutability::Not) => {} // 2x `ref mut`. - (Mutability::Mut, Mutability::Mut) => { + (ty::Mutability::Mut, ty::Mutability::Mut) => { conflicts_mut_mut.push(Conflict::Mut { span, name }) } - (Mutability::Not, Mutability::Mut) => { + (ty::Mutability::Not, ty::Mutability::Mut) => { conflicts_mut_ref.push(Conflict::Mut { span, name }) } - (Mutability::Mut, Mutability::Not) => { + (ty::Mutability::Mut, ty::Mutability::Not) => { conflicts_mut_ref.push(Conflict::Ref { span, name }) } }, @@ -1060,8 +1059,8 @@ fn check_borrow_conflicts_in_at_patterns<'tcx>(cx: &MatchVisitor<'_, '_, 'tcx>, let report_move_conflict = !conflicts_move.is_empty(); let mut occurrences = match mut_outer { - Mutability::Mut => vec![Conflict::Mut { span: pat.span, name }], - Mutability::Not => vec![Conflict::Ref { span: pat.span, name }], + ty::Mutability::Mut => vec![Conflict::Mut { span: pat.span, name }], + ty::Mutability::Not => vec![Conflict::Ref { span: pat.span, name }], }; occurrences.extend(conflicts_mut_mut); occurrences.extend(conflicts_mut_ref); @@ -1074,10 +1073,10 @@ fn check_borrow_conflicts_in_at_patterns<'tcx>(cx: &MatchVisitor<'_, '_, 'tcx>, } else if report_mut_ref { // Report mutability conflicts for e.g. `ref x @ Some(ref mut y)` or the converse. match mut_outer { - Mutability::Mut => { + ty::Mutability::Mut => { sess.emit_err(AlreadyMutBorrowed { span: pat.span, occurrences }); } - Mutability::Not => { + ty::Mutability::Not => { sess.emit_err(AlreadyBorrowed { span: pat.span, occurrences }); } }; diff --git a/compiler/rustc_mir_build/src/thir/pattern/mod.rs b/compiler/rustc_mir_build/src/thir/pattern/mod.rs index 76ed6d2b6d73d..32cf59d2643cc 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/mod.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/mod.rs @@ -288,11 +288,11 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { .expect("missing binding mode"); let (mutability, mode) = match bm { ty::BindByValue(mutbl) => (mutbl, BindingMode::ByValue), - ty::BindByReference(hir::Mutability::Mut) => ( + ty::BindByReference(Mutability::Mut) => ( Mutability::Not, BindingMode::ByRef(BorrowKind::Mut { kind: mir::MutBorrowKind::Default }), ), - ty::BindByReference(hir::Mutability::Not) => { + ty::BindByReference(Mutability::Not) => { (Mutability::Not, BindingMode::ByRef(BorrowKind::Shared)) } }; diff --git a/compiler/rustc_mir_dataflow/src/elaborate_drops.rs b/compiler/rustc_mir_dataflow/src/elaborate_drops.rs index c9991e499b32a..fb5e49b95b10f 100644 --- a/compiler/rustc_mir_dataflow/src/elaborate_drops.rs +++ b/compiler/rustc_mir_dataflow/src/elaborate_drops.rs @@ -1,4 +1,3 @@ -use rustc_hir as hir; use rustc_hir::lang_items::LangItem; use rustc_index::Idx; use rustc_middle::mir::patch::MirPatch; @@ -634,7 +633,7 @@ where let ref_ty = Ty::new_ref( tcx, tcx.lifetimes.re_erased, - ty::TypeAndMut { ty, mutbl: hir::Mutability::Mut }, + ty::TypeAndMut { ty, mutbl: Mutability::Mut }, ); let ref_place = self.new_temp(ref_ty); let unit_temp = Place::from(self.new_temp(Ty::new_unit(tcx))); @@ -699,7 +698,7 @@ where let move_ = |place: Place<'tcx>| Operand::Move(place); let tcx = self.tcx(); - let ptr_ty = Ty::new_ptr(tcx, ty::TypeAndMut { ty: ety, mutbl: hir::Mutability::Mut }); + let ptr_ty = Ty::new_ptr(tcx, ty::TypeAndMut { ty: ety, mutbl: Mutability::Mut }); let ptr = Place::from(self.new_temp(ptr_ty)); let can_go = Place::from(self.new_temp(tcx.types.bool)); let one = self.constant_usize(1); diff --git a/compiler/rustc_mir_transform/src/generator.rs b/compiler/rustc_mir_transform/src/generator.rs index a6693519e54b2..e367ad97599a4 100644 --- a/compiler/rustc_mir_transform/src/generator.rs +++ b/compiler/rustc_mir_transform/src/generator.rs @@ -1082,7 +1082,7 @@ fn create_generator_drop_shim<'tcx>( // Change the generator argument from &mut to *mut body.local_decls[SELF_ARG] = LocalDecl::with_source_info( - Ty::new_ptr(tcx, ty::TypeAndMut { ty: gen_ty, mutbl: hir::Mutability::Mut }), + Ty::new_ptr(tcx, ty::TypeAndMut { ty: gen_ty, mutbl: Mutability::Mut }), source_info, ); diff --git a/compiler/rustc_mir_transform/src/instsimplify.rs b/compiler/rustc_mir_transform/src/instsimplify.rs index fbcd6e75ad4f1..1c74ad6b4d23a 100644 --- a/compiler/rustc_mir_transform/src/instsimplify.rs +++ b/compiler/rustc_mir_transform/src/instsimplify.rs @@ -2,7 +2,6 @@ use crate::simplify::simplify_duplicate_switch_targets; use crate::MirPass; -use rustc_hir::Mutability; use rustc_middle::mir::*; use rustc_middle::ty::layout::ValidityRequirement; use rustc_middle::ty::{self, GenericArgsRef, ParamEnv, Ty, TyCtxt}; diff --git a/compiler/rustc_mir_transform/src/nrvo.rs b/compiler/rustc_mir_transform/src/nrvo.rs index ff309bd10ec82..cb1ad816eef2f 100644 --- a/compiler/rustc_mir_transform/src/nrvo.rs +++ b/compiler/rustc_mir_transform/src/nrvo.rs @@ -1,9 +1,9 @@ //! See the docs for [`RenameReturnPlace`]. -use rustc_hir::Mutability; use rustc_index::bit_set::HybridBitSet; use rustc_middle::mir::visit::{MutVisitor, NonUseContext, PlaceContext, Visitor}; use rustc_middle::mir::{self, BasicBlock, Local, Location}; +use rustc_middle::ty::Mutability; use rustc_middle::ty::TyCtxt; use crate::MirPass; diff --git a/compiler/rustc_mir_transform/src/shim.rs b/compiler/rustc_mir_transform/src/shim.rs index e9895d97dfefa..abe9a9f51f906 100644 --- a/compiler/rustc_mir_transform/src/shim.rs +++ b/compiler/rustc_mir_transform/src/shim.rs @@ -508,7 +508,7 @@ impl<'tcx> CloneShimBuilder<'tcx> { Ty::new_ref( tcx, tcx.lifetimes.re_erased, - ty::TypeAndMut { ty, mutbl: hir::Mutability::Not }, + ty::TypeAndMut { ty, mutbl: Mutability::Not }, ), ); @@ -738,7 +738,7 @@ fn build_call_shim<'tcx>( Ty::new_ref( tcx, tcx.lifetimes.re_erased, - ty::TypeAndMut { ty: sig.inputs()[0], mutbl: hir::Mutability::Mut }, + ty::TypeAndMut { ty: sig.inputs()[0], mutbl: Mutability::Mut }, ), span, ) diff --git a/compiler/rustc_symbol_mangling/src/v0.rs b/compiler/rustc_symbol_mangling/src/v0.rs index 99c5d0164399b..3d382ac6681b3 100644 --- a/compiler/rustc_symbol_mangling/src/v0.rs +++ b/compiler/rustc_symbol_mangling/src/v0.rs @@ -387,8 +387,8 @@ impl<'tcx> Printer<'tcx> for &mut SymbolMangler<'tcx> { ty::Ref(r, ty, mutbl) => { self.push(match mutbl { - hir::Mutability::Not => "R", - hir::Mutability::Mut => "Q", + ty::Mutability::Not => "R", + ty::Mutability::Mut => "Q", }); if !r.is_erased() { self = r.print(self)?; @@ -398,8 +398,8 @@ impl<'tcx> Printer<'tcx> for &mut SymbolMangler<'tcx> { ty::RawPtr(mt) => { self.push(match mt.mutbl { - hir::Mutability::Not => "P", - hir::Mutability::Mut => "O", + ty::Mutability::Not => "P", + ty::Mutability::Mut => "O", }); self = mt.ty.print(self)?; } @@ -604,8 +604,8 @@ impl<'tcx> Printer<'tcx> for &mut SymbolMangler<'tcx> { // here and fully support unsized constants. ty::Ref(_, inner_ty, mutbl) => { self.push(match mutbl { - hir::Mutability::Not => "R", - hir::Mutability::Mut => "Q", + ty::Mutability::Not => "R", + ty::Mutability::Mut => "Q", }); match inner_ty.kind() { diff --git a/compiler/rustc_trait_selection/src/solve/assembly/structural_traits.rs b/compiler/rustc_trait_selection/src/solve/assembly/structural_traits.rs index 26c68acddffef..98322b94b3bf4 100644 --- a/compiler/rustc_trait_selection/src/solve/assembly/structural_traits.rs +++ b/compiler/rustc_trait_selection/src/solve/assembly/structural_traits.rs @@ -1,7 +1,7 @@ //! Code which is used by built-in goals that match "structurally", such a auto //! traits, `Copy`/`Clone`. use rustc_data_structures::fx::FxHashMap; -use rustc_hir::{def_id::DefId, Movability, Mutability}; +use rustc_hir::{def_id::DefId, Movability}; use rustc_infer::traits::query::NoSolution; use rustc_middle::traits::solve::Goal; use rustc_middle::ty::{ @@ -168,7 +168,7 @@ pub(in crate::solve) fn instantiate_constituent_tys_for_copy_clone_trait<'tcx>( | ty::Char | ty::RawPtr(..) | ty::Never - | ty::Ref(_, _, Mutability::Not) + | ty::Ref(_, _, ty::Mutability::Not) | ty::Array(..) => Err(NoSolution), ty::Dynamic(..) @@ -176,7 +176,7 @@ pub(in crate::solve) fn instantiate_constituent_tys_for_copy_clone_trait<'tcx>( | ty::Slice(_) | ty::Generator(_, _, Movability::Static) | ty::Foreign(..) - | ty::Ref(_, _, Mutability::Mut) + | ty::Ref(_, _, ty::Mutability::Mut) | ty::Adt(_, _) | ty::Alias(_, _) | ty::Param(_) diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/on_unimplemented.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/on_unimplemented.rs index 9c9b78f415238..79d3e878813be 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/on_unimplemented.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/on_unimplemented.rs @@ -291,7 +291,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { } // `&[{integral}]` - `FromIterator` needs that. - if let ty::Ref(_, ref_ty, rustc_ast::Mutability::Not) = self_ty.kind() + if let ty::Ref(_, ref_ty, ty::Mutability::Not) = self_ty.kind() && let ty::Slice(sty) = ref_ty.kind() && sty.is_integral() { diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs index 66529b67c17b3..48073ac4d8f30 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs @@ -1089,7 +1089,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { let Some(generics) = self.tcx.hir().get_generics(obligation.cause.body_id) else { return false; }; - let ty::Ref(_, inner_ty, hir::Mutability::Not) = ty.kind() else { return false }; + let ty::Ref(_, inner_ty, ty::Mutability::Not) = ty.kind() else { return false }; let ty::Param(param) = inner_ty.kind() else { return false }; let ObligationCauseCode::FunctionArgumentObligation { arg_hir_id, .. } = obligation.cause.code() @@ -1481,7 +1481,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { self_ty: Ty<'tcx>, target_ty: Ty<'tcx>, ) { - let ty::Ref(_, object_ty, hir::Mutability::Not) = target_ty.kind() else { + let ty::Ref(_, object_ty, ty::Mutability::Not) = target_ty.kind() else { return; }; let ty::Dynamic(predicates, _, ty::Dyn) = object_ty.kind() else { @@ -1729,8 +1729,8 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { if let ty::Ref(region, t_type, mutability) = *trait_pred.skip_binder().self_ty().kind() { let suggested_ty = match mutability { - hir::Mutability::Mut => Ty::new_imm_ref(self.tcx, region, t_type), - hir::Mutability::Not => Ty::new_mut_ref(self.tcx, region, t_type), + ty::Mutability::Mut => Ty::new_imm_ref(self.tcx, region, t_type), + ty::Mutability::Not => Ty::new_mut_ref(self.tcx, region, t_type), }; // Remapping bound vars here @@ -3600,14 +3600,14 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { && obligations.iter().all(|obligation| infcx.predicate_must_hold_modulo_regions(obligation)) && infcx.can_eq(param_env, deref_target, target_ty) { - let help = if let hir::Mutability::Mut = needs_mut + let help = if let ty::Mutability::Mut = needs_mut && let Some(deref_mut_did) = tcx.lang_items().deref_mut_trait() && infcx .type_implements_trait(deref_mut_did, iter::once(found_ty), param_env) .must_apply_modulo_regions() { Some(("call `Option::as_deref_mut()` first", ".as_deref_mut()")) - } else if let hir::Mutability::Not = needs_mut { + } else if let ty::Mutability::Not = needs_mut { Some(("call `Option::as_deref()` first", ".as_deref()")) } else { None @@ -4027,7 +4027,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) { let mut suggestions = vec![]; if snippet.starts_with('&') { - } else if let Some(hir::Mutability::Mut) = mutability { + } else if let Some(ty::Mutability::Mut) = mutability { suggestions.push((span.shrink_to_lo(), "&mut ".into())); } else { suggestions.push((span.shrink_to_lo(), "&".into())); @@ -4224,7 +4224,7 @@ fn hint_missing_borrow<'tcx>( let args = fn_decl.inputs.iter(); - fn get_deref_type_and_refs(mut ty: Ty<'_>) -> (Ty<'_>, Vec) { + fn get_deref_type_and_refs(mut ty: Ty<'_>) -> (Ty<'_>, Vec) { let mut refs = vec![]; while let ty::Ref(_, new_ty, mutbl) = ty.kind() { diff --git a/compiler/rustc_trait_selection/src/traits/misc.rs b/compiler/rustc_trait_selection/src/traits/misc.rs index ab07b10c65f58..0f1c4b495d426 100644 --- a/compiler/rustc_trait_selection/src/traits/misc.rs +++ b/compiler/rustc_trait_selection/src/traits/misc.rs @@ -53,7 +53,7 @@ pub fn type_allowed_to_implement_copy<'tcx>( | ty::Char | ty::RawPtr(..) | ty::Never - | ty::Ref(_, _, hir::Mutability::Not) + | ty::Ref(_, _, ty::Mutability::Not) | ty::Array(..) => return Ok(()), &ty::Adt(adt, args) => (adt, args), @@ -100,7 +100,7 @@ pub fn type_allowed_to_implement_const_param_ty<'tcx>( | ty::Str | ty::Array(..) | ty::Slice(_) - | ty::Ref(.., hir::Mutability::Not) + | ty::Ref(.., ty::Mutability::Not) | ty::Tuple(_) => return Ok(()), &ty::Adt(adt, args) => (adt, args), diff --git a/compiler/rustc_trait_selection/src/traits/select/confirmation.rs b/compiler/rustc_trait_selection/src/traits/select/confirmation.rs index 08ee9c73bf8aa..07313366ef9f7 100644 --- a/compiler/rustc_trait_selection/src/traits/select/confirmation.rs +++ b/compiler/rustc_trait_selection/src/traits/select/confirmation.rs @@ -6,7 +6,6 @@ //! //! [rustc dev guide]: //! https://rustc-dev-guide.rust-lang.org/traits/resolution.html#confirmation -use rustc_ast::Mutability; use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_hir::lang_items::LangItem; use rustc_infer::infer::LateBoundRegionConversionTime::HigherRankedType; @@ -310,8 +309,10 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { // For example, transmuting bool -> u8 is OK as long as you can't update that u8 // to be > 1, because you could later transmute the u8 back to a bool and get UB. match dst.mutability { - Mutability::Not => vec![make_obl(src.ty, dst.ty)], - Mutability::Mut => vec![make_obl(src.ty, dst.ty), make_obl(dst.ty, src.ty)], + ty::Mutability::Not => vec![make_obl(src.ty, dst.ty)], + ty::Mutability::Mut => { + vec![make_obl(src.ty, dst.ty), make_obl(dst.ty, src.ty)] + } } } } diff --git a/compiler/rustc_trait_selection/src/traits/select/mod.rs b/compiler/rustc_trait_selection/src/traits/select/mod.rs index 940ceca50d2d4..12f3b8f7db61d 100644 --- a/compiler/rustc_trait_selection/src/traits/select/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/select/mod.rs @@ -2171,7 +2171,7 @@ impl<'tcx> SelectionContext<'_, 'tcx> { | ty::Char | ty::RawPtr(..) | ty::Never - | ty::Ref(_, _, hir::Mutability::Not) + | ty::Ref(_, _, ty::Mutability::Not) | ty::Array(..) => { // Implementations provided in libcore None @@ -2182,7 +2182,7 @@ impl<'tcx> SelectionContext<'_, 'tcx> { | ty::Slice(..) | ty::Generator(_, _, hir::Movability::Static) | ty::Foreign(..) - | ty::Ref(_, _, hir::Mutability::Mut) => None, + | ty::Ref(_, _, ty::Mutability::Mut) => None, ty::Tuple(tys) => { // (*) binder moved here diff --git a/compiler/rustc_type_ir/src/lib.rs b/compiler/rustc_type_ir/src/lib.rs index 9f8d9f02ec24c..0b5ede108b12e 100644 --- a/compiler/rustc_type_ir/src/lib.rs +++ b/compiler/rustc_type_ir/src/lib.rs @@ -56,7 +56,6 @@ pub trait Interner: Sized { type Region: Clone + DebugWithInfcx + Hash + Ord; type Predicate; type TypeAndMut: Clone + Debug + Hash + Ord; - type Mutability: Clone + Debug + Hash + Ord; type Movability: Clone + Debug + Hash + Ord; type PolyFnSig: Clone + DebugWithInfcx + Hash + Ord; type ListBinderExistentialPredicate: Clone + DebugWithInfcx + Hash + Ord; @@ -85,8 +84,7 @@ pub trait Interner: Sized { type RegionVid: Clone + DebugWithInfcx + Hash + Ord; type PlaceholderRegion: Clone + Debug + Hash + Ord; - fn ty_and_mut_to_parts(ty_and_mut: Self::TypeAndMut) -> (Self::Ty, Self::Mutability); - fn mutability_is_mut(mutbl: Self::Mutability) -> bool; + fn ty_and_mut_to_parts(ty_and_mut: Self::TypeAndMut) -> (Self::Ty, Mutability); } /// Imagine you have a function `F: FnOnce(&[T]) -> R`, plus an iterator `iter` diff --git a/compiler/rustc_type_ir/src/structural_impls.rs b/compiler/rustc_type_ir/src/structural_impls.rs index 08af96ea15f0f..ab444e2c5cea7 100644 --- a/compiler/rustc_type_ir/src/structural_impls.rs +++ b/compiler/rustc_type_ir/src/structural_impls.rs @@ -28,6 +28,7 @@ TrivialTypeTraversalImpls! { u64, String, crate::DebruijnIndex, + crate::Mutability, } /////////////////////////////////////////////////////////////////////////// diff --git a/compiler/rustc_type_ir/src/sty.rs b/compiler/rustc_type_ir/src/sty.rs index 091b51440a6e1..ac5534e5576d1 100644 --- a/compiler/rustc_type_ir/src/sty.rs +++ b/compiler/rustc_type_ir/src/sty.rs @@ -33,6 +33,58 @@ pub enum DynKind { DynStar, } +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] +#[derive(Encodable, Decodable, HashStable_Generic)] +pub enum Mutability { + /// Immutable (`&T` and `*const T`) + Not, + /// Mutable (`&mut T` and `*mut T`) + Mut, +} + +impl Mutability { + pub fn invert(self) -> Self { + match self { + Mutability::Mut => Mutability::Not, + Mutability::Not => Mutability::Mut, + } + } + + /// Returns `""` (empty string) or `"mut "` depending on the mutability. + pub fn prefix_str(self) -> &'static str { + match self { + Mutability::Mut => "mut ", + Mutability::Not => "", + } + } + + /// Returns `"&"` or `"&mut "` depending on the mutability. + pub fn ref_prefix_str(self) -> &'static str { + match self { + Mutability::Not => "&", + Mutability::Mut => "&mut ", + } + } + + /// Returns `""` (empty string) or `"mutably "` depending on the mutability. + pub fn mutably_str(self) -> &'static str { + match self { + Mutability::Not => "", + Mutability::Mut => "mutably ", + } + } + + /// Return `true` if self is mutable + pub fn is_mut(self) -> bool { + matches!(self, Self::Mut) + } + + /// Return `true` if self is **not** mutable + pub fn is_not(self) -> bool { + matches!(self, Self::Not) + } +} + #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] #[derive(Encodable, Decodable, HashStable_Generic)] pub enum AliasKind { @@ -98,7 +150,7 @@ pub enum TyKind { /// A reference; a pointer with an associated lifetime. Written as /// `&'a mut T` or `&'a T`. - Ref(I::Region, I::Ty, I::Mutability), + Ref(I::Region, I::Ty, Mutability), /// The anonymous type of a function declaration/definition. Each /// function has a unique type. @@ -506,15 +558,15 @@ impl DebugWithInfcx for TyKind { Slice(t) => write!(f, "[{:?}]", &this.wrap(t)), RawPtr(p) => { let (ty, mutbl) = I::ty_and_mut_to_parts(p.clone()); - match I::mutability_is_mut(mutbl) { - true => write!(f, "*mut "), - false => write!(f, "*const "), + match mutbl { + Mutability::Mut => write!(f, "*mut "), + Mutability::Not => write!(f, "*const "), }?; write!(f, "{:?}", &this.wrap(ty)) } - Ref(r, t, m) => match I::mutability_is_mut(m.clone()) { - true => write!(f, "&{:?} mut {:?}", &this.wrap(r), &this.wrap(t)), - false => write!(f, "&{:?} {:?}", &this.wrap(r), &this.wrap(t)), + Ref(r, t, m) => match m { + Mutability::Mut => write!(f, "&{:?} mut {:?}", &this.wrap(r), &this.wrap(t)), + Mutability::Not => write!(f, "&{:?} {:?}", &this.wrap(r), &this.wrap(t)), }, FnDef(d, s) => f.debug_tuple_field2_finish("FnDef", d, &this.wrap(s)), FnPtr(s) => write!(f, "{:?}", &this.wrap(s)), @@ -573,7 +625,7 @@ where I::Const: Encodable, I::Region: Encodable, I::TypeAndMut: Encodable, - I::Mutability: Encodable, + Mutability: Encodable, I::Movability: Encodable, I::PolyFnSig: Encodable, I::ListBinderExistentialPredicate: Encodable, @@ -688,7 +740,7 @@ where I::Const: Decodable, I::Region: Decodable, I::TypeAndMut: Decodable, - I::Mutability: Decodable, + Mutability: Decodable, I::Movability: Decodable, I::PolyFnSig: Decodable, I::ListBinderExistentialPredicate: Decodable, @@ -756,7 +808,7 @@ where I::ListBinderExistentialPredicate: HashStable, I::Region: HashStable, I::Movability: HashStable, - I::Mutability: HashStable, + Mutability: HashStable, I::BinderListTy: HashStable, I::ListTy: HashStable, I::AliasTy: HashStable, diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index e08318e4f5427..04cf10f51ab6b 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -2062,12 +2062,19 @@ pub(crate) fn clean_middle_ty<'tcx>( let n = print_const(cx, n); Array(Box::new(clean_middle_ty(bound_ty.rebind(ty), cx, None, None)), n.into()) } - ty::RawPtr(mt) => { - RawPointer(mt.mutbl, Box::new(clean_middle_ty(bound_ty.rebind(mt.ty), cx, None, None))) - } + ty::RawPtr(mt) => RawPointer( + match mt.mutbl { + ty::Mutability::Mut => hir::Mutability::Mut, + ty::Mutability::Not => hir::Mutability::Not, + }, + Box::new(clean_middle_ty(bound_ty.rebind(mt.ty), cx, None, None)), + ), ty::Ref(r, ty, mutbl) => BorrowedRef { lifetime: clean_middle_region(r), - mutability: mutbl, + mutability: match mutbl { + ty::Mutability::Mut => hir::Mutability::Mut, + ty::Mutability::Not => hir::Mutability::Not, + }, type_: Box::new(clean_middle_ty( bound_ty.rebind(ty), cx, diff --git a/src/librustdoc/clean/types.rs b/src/librustdoc/clean/types.rs index 2a54266676d0c..829d116af63da 100644 --- a/src/librustdoc/clean/types.rs +++ b/src/librustdoc/clean/types.rs @@ -1836,8 +1836,8 @@ impl PrimitiveType { // or start with a more complex refactoring. Tuple => [SimplifiedType::Tuple(1), SimplifiedType::Tuple(2), SimplifiedType::Tuple(3)].into(), Unit => single(SimplifiedType::Tuple(0)), - RawPointer => [SimplifiedType::Ptr(Mutability::Not), SimplifiedType::Ptr(Mutability::Mut)].into_iter().collect(), - Reference => [SimplifiedType::Ref(Mutability::Not), SimplifiedType::Ref(Mutability::Mut)].into_iter().collect(), + RawPointer => [SimplifiedType::Ptr(ty::Mutability::Not), SimplifiedType::Ptr(ty::Mutability::Mut)].into_iter().collect(), + Reference => [SimplifiedType::Ref(ty::Mutability::Not), SimplifiedType::Ref(ty::Mutability::Mut)].into_iter().collect(), // FIXME: This will be wrong if we ever add inherent impls // for function pointers. Fn => single(SimplifiedType::Function(1)), diff --git a/src/tools/clippy/clippy_lints/src/borrow_deref_ref.rs b/src/tools/clippy/clippy_lints/src/borrow_deref_ref.rs index b3dbbb08f8ebf..004f6d24fa515 100644 --- a/src/tools/clippy/clippy_lints/src/borrow_deref_ref.rs +++ b/src/tools/clippy/clippy_lints/src/borrow_deref_ref.rs @@ -4,9 +4,8 @@ use clippy_utils::source::snippet_opt; use clippy_utils::ty::implements_trait; use clippy_utils::{get_parent_expr, is_from_proc_macro, is_lint_allowed}; use rustc_errors::Applicability; -use rustc_hir::{ExprKind, UnOp}; +use rustc_hir::{ExprKind, UnOp, Mutability}; use rustc_lint::{LateContext, LateLintPass}; -use rustc_middle::mir::Mutability; use rustc_middle::ty; use rustc_session::{declare_lint_pass, declare_tool_lint}; @@ -57,7 +56,7 @@ impl<'tcx> LateLintPass<'tcx> for BorrowDerefRef { if !deref_target.span.from_expansion(); if !matches!(deref_target.kind, ExprKind::Unary(UnOp::Deref, ..) ); let ref_ty = cx.typeck_results().expr_ty(deref_target); - if let ty::Ref(_, inner_ty, Mutability::Not) = ref_ty.kind(); + if let ty::Ref(_, inner_ty, ty::Mutability::Not) = ref_ty.kind(); if !is_from_proc_macro(cx, e); then{ diff --git a/src/tools/clippy/clippy_lints/src/casts/cast_slice_different_sizes.rs b/src/tools/clippy/clippy_lints/src/casts/cast_slice_different_sizes.rs index 4d9cc4cacc3e9..71ce996fe7cdc 100644 --- a/src/tools/clippy/clippy_lints/src/casts/cast_slice_different_sizes.rs +++ b/src/tools/clippy/clippy_lints/src/casts/cast_slice_different_sizes.rs @@ -2,11 +2,10 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::msrvs::{self, Msrv}; use clippy_utils::source; use if_chain::if_chain; -use rustc_ast::Mutability; use rustc_hir::{Expr, ExprKind, Node}; use rustc_lint::LateContext; use rustc_middle::ty::layout::LayoutOf; -use rustc_middle::ty::{self, Ty, TypeAndMut}; +use rustc_middle::ty::{self, Ty, TypeAndMut, Mutability}; use super::CAST_SLICE_DIFFERENT_SIZES; diff --git a/src/tools/clippy/clippy_lints/src/casts/ptr_as_ptr.rs b/src/tools/clippy/clippy_lints/src/casts/ptr_as_ptr.rs index 181dbcf6e9a86..cff556745b54a 100644 --- a/src/tools/clippy/clippy_lints/src/casts/ptr_as_ptr.rs +++ b/src/tools/clippy/clippy_lints/src/casts/ptr_as_ptr.rs @@ -3,9 +3,9 @@ use clippy_utils::msrvs::{self, Msrv}; use clippy_utils::source::snippet_with_applicability; use clippy_utils::sugg::Sugg; use rustc_errors::Applicability; -use rustc_hir::{Expr, ExprKind, Mutability, TyKind}; +use rustc_hir::{Expr, ExprKind, TyKind}; use rustc_lint::LateContext; -use rustc_middle::ty::{self, TypeAndMut}; +use rustc_middle::ty::{self, TypeAndMut, Mutability}; use super::PTR_AS_PTR; diff --git a/src/tools/clippy/clippy_lints/src/casts/ptr_cast_constness.rs b/src/tools/clippy/clippy_lints/src/casts/ptr_cast_constness.rs index ce1ab10910ccb..df18ca61e25df 100644 --- a/src/tools/clippy/clippy_lints/src/casts/ptr_cast_constness.rs +++ b/src/tools/clippy/clippy_lints/src/casts/ptr_cast_constness.rs @@ -3,9 +3,9 @@ use clippy_utils::msrvs::{Msrv, POINTER_CAST_CONSTNESS}; use clippy_utils::sugg::Sugg; use if_chain::if_chain; use rustc_errors::Applicability; -use rustc_hir::{Expr, Mutability}; +use rustc_hir::{Expr}; use rustc_lint::LateContext; -use rustc_middle::ty::{self, Ty, TypeAndMut}; +use rustc_middle::ty::{self, Ty, TypeAndMut, Mutability}; use super::PTR_CAST_CONSTNESS; diff --git a/src/tools/clippy/clippy_lints/src/dereference.rs b/src/tools/clippy/clippy_lints/src/dereference.rs index 5134cf66050c9..f060eec75bb59 100644 --- a/src/tools/clippy/clippy_lints/src/dereference.rs +++ b/src/tools/clippy/clippy_lints/src/dereference.rs @@ -598,7 +598,7 @@ impl<'tcx> LateLintPass<'tcx> for Dereferencing<'tcx> { if !pat.span.from_expansion(); if let ty::Ref(_, tam, _) = *cx.typeck_results().pat_ty(pat).kind(); // only lint immutable refs, because borrowed `&mut T` cannot be moved out - if let ty::Ref(_, _, Mutability::Not) = *tam.kind(); + if let ty::Ref(_, _, ty::Mutability::Not) = *tam.kind(); then { let mut app = Applicability::MachineApplicable; let snip = snippet_with_context(cx, name.span, pat.span.ctxt(), "..", &mut app).0; @@ -913,7 +913,7 @@ fn report<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, state: State, data }; let addr_of_str = if ty_changed_count < ref_count { // Check if a reborrow from &mut T -> &T is required. - if mutbl == Mutability::Not && matches!(ty.kind(), ty::Ref(_, _, Mutability::Mut)) { + if mutbl == Mutability::Not && matches!(ty.kind(), ty::Ref(_, _, ty::Mutability::Mut)) { "&*" } else { "" diff --git a/src/tools/clippy/clippy_lints/src/functions/must_use.rs b/src/tools/clippy/clippy_lints/src/functions/must_use.rs index 57df5683c9d39..90b815b7a3fa7 100644 --- a/src/tools/clippy/clippy_lints/src/functions/must_use.rs +++ b/src/tools/clippy/clippy_lints/src/functions/must_use.rs @@ -207,7 +207,7 @@ fn is_mutable_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, tys: &mut DefIdSet) ty::Tuple(args) => args.iter().any(|ty| is_mutable_ty(cx, ty, tys)), ty::Array(ty, _) | ty::Slice(ty) => is_mutable_ty(cx, ty, tys), ty::RawPtr(ty::TypeAndMut { ty, mutbl }) | ty::Ref(_, ty, mutbl) => { - mutbl == hir::Mutability::Mut || is_mutable_ty(cx, ty, tys) + mutbl == ty::Mutability::Mut || is_mutable_ty(cx, ty, tys) }, // calling something constitutes a side effect, so return true on all callables // also never calls need not be used, so return true for them, too diff --git a/src/tools/clippy/clippy_lints/src/iter_without_into_iter.rs b/src/tools/clippy/clippy_lints/src/iter_without_into_iter.rs index 43e1b92c9b9a7..5f13daabb496b 100644 --- a/src/tools/clippy/clippy_lints/src/iter_without_into_iter.rs +++ b/src/tools/clippy/clippy_lints/src/iter_without_into_iter.rs @@ -2,7 +2,6 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::get_parent_as_impl; use clippy_utils::source::snippet; use clippy_utils::ty::{implements_trait, make_normalized_projection}; -use rustc_ast::Mutability; use rustc_errors::Applicability; use rustc_hir::{FnRetTy, ImplItemKind, ImplicitSelfKind, ItemKind, TyKind}; use rustc_lint::{LateContext, LateLintPass}; @@ -124,8 +123,8 @@ impl LateLintPass<'_> for IterWithoutIntoIter { && trait_ref.trait_def_id().is_some_and(|did| cx.tcx.is_diagnostic_item(sym::IntoIterator, did)) && let &ty::Ref(_, ty, mtbl) = cx.tcx.type_of(item.owner_id).instantiate_identity().kind() && let expected_method_name = match mtbl { - Mutability::Mut => sym::iter_mut, - Mutability::Not => sym::iter, + ty::Mutability::Mut => sym::iter_mut, + ty::Mutability::Not => sym::iter, } && !type_has_inherent_method(cx, ty, expected_method_name) && let Some(iter_assoc_span) = imp.items.iter().find_map(|item| { diff --git a/src/tools/clippy/clippy_lints/src/len_zero.rs b/src/tools/clippy/clippy_lints/src/len_zero.rs index c06b35ca0dabf..ec56518ef017f 100644 --- a/src/tools/clippy/clippy_lints/src/len_zero.rs +++ b/src/tools/clippy/clippy_lints/src/len_zero.rs @@ -9,7 +9,7 @@ use rustc_hir::def::Res; use rustc_hir::def_id::{DefId, DefIdSet}; use rustc_hir::{ AssocItemKind, BinOpKind, Expr, ExprKind, FnRetTy, GenericArg, GenericBound, ImplItem, ImplItemKind, - ImplicitSelfKind, Item, ItemKind, LangItem, Mutability, Node, PatKind, PathSegment, PrimTy, QPath, TraitItemRef, + ImplicitSelfKind, Item, ItemKind, LangItem, Node, PatKind, PathSegment, PrimTy, QPath, TraitItemRef, TyKind, TypeBindingKind, }; use rustc_lint::{LateContext, LateLintPass}; @@ -406,8 +406,8 @@ fn check_is_empty_sig<'tcx>( [arg, res] if len_output.matches_is_empty_output(cx, *res) => { matches!( (arg.kind(), self_kind), - (ty::Ref(_, _, Mutability::Not), ImplicitSelfKind::ImmRef) - | (ty::Ref(_, _, Mutability::Mut), ImplicitSelfKind::MutRef) + (ty::Ref(_, _, ty::Mutability::Not), ImplicitSelfKind::ImmRef) + | (ty::Ref(_, _, ty::Mutability::Mut), ImplicitSelfKind::MutRef) ) || (!arg.is_ref() && matches!(self_kind, ImplicitSelfKind::Imm | ImplicitSelfKind::Mut)) }, _ => false, diff --git a/src/tools/clippy/clippy_lints/src/loops/explicit_iter_loop.rs b/src/tools/clippy/clippy_lints/src/loops/explicit_iter_loop.rs index 6ab256ef0010b..10fc65da9c810 100644 --- a/src/tools/clippy/clippy_lints/src/loops/explicit_iter_loop.rs +++ b/src/tools/clippy/clippy_lints/src/loops/explicit_iter_loop.rs @@ -7,7 +7,7 @@ use clippy_utils::ty::{ make_normalized_projection_with_regions, normalize_with_regions, }; use rustc_errors::Applicability; -use rustc_hir::{Expr, Mutability}; +use rustc_hir::Expr; use rustc_lint::LateContext; use rustc_middle::ty::adjustment::{Adjust, Adjustment, AutoBorrow, AutoBorrowMutability}; use rustc_middle::ty::{self, EarlyBinder, Ty, TypeAndMut}; @@ -61,10 +61,10 @@ enum AdjustKind { ReborrowMut, } impl AdjustKind { - fn borrow(mutbl: Mutability) -> Self { + fn borrow(mutbl: ty::Mutability) -> Self { match mutbl { - Mutability::Not => Self::Borrow, - Mutability::Mut => Self::BorrowMut, + ty::Mutability::Not => Self::Borrow, + ty::Mutability::Mut => Self::BorrowMut, } } @@ -75,10 +75,10 @@ impl AdjustKind { } } - fn reborrow(mutbl: Mutability) -> Self { + fn reborrow(mutbl: ty::Mutability) -> Self { match mutbl { - Mutability::Not => Self::Reborrow, - Mutability::Mut => Self::ReborrowMut, + ty::Mutability::Not => Self::Reborrow, + ty::Mutability::Mut => Self::ReborrowMut, } } @@ -150,7 +150,7 @@ fn is_ref_iterable<'tcx>( return Some((AdjustKind::None, self_ty)); } } else if enforce_iter_loop_reborrow - && let ty::Ref(region, ty, Mutability::Mut) = *self_ty.kind() + && let ty::Ref(region, ty, ty::Mutability::Mut) = *self_ty.kind() && let Some(mutbl) = mutbl { // Attempt to reborrow the mutable reference diff --git a/src/tools/clippy/clippy_lints/src/loops/for_kv_map.rs b/src/tools/clippy/clippy_lints/src/loops/for_kv_map.rs index ed620460dbe66..df3473049b1c2 100644 --- a/src/tools/clippy/clippy_lints/src/loops/for_kv_map.rs +++ b/src/tools/clippy/clippy_lints/src/loops/for_kv_map.rs @@ -4,7 +4,7 @@ use clippy_utils::source::snippet; use clippy_utils::sugg; use clippy_utils::ty::is_type_diagnostic_item; use clippy_utils::visitors::is_local_used; -use rustc_hir::{BorrowKind, Expr, ExprKind, Mutability, Pat, PatKind}; +use rustc_hir::{BorrowKind, Expr, ExprKind, Pat, PatKind}; use rustc_lint::LateContext; use rustc_middle::ty; use rustc_span::sym; @@ -19,14 +19,14 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, pat: &'tcx Pat<'_>, arg: &'tcx let (new_pat_span, kind, ty, mutbl) = match *cx.typeck_results().expr_ty(arg).kind() { ty::Ref(_, ty, mutbl) => match (&pat[0].kind, &pat[1].kind) { (key, _) if pat_is_wild(cx, key, body) => (pat[1].span, "value", ty, mutbl), - (_, value) if pat_is_wild(cx, value, body) => (pat[0].span, "key", ty, Mutability::Not), + (_, value) if pat_is_wild(cx, value, body) => (pat[0].span, "key", ty, ty::Mutability::Not), _ => return, }, _ => return, }; let mutbl = match mutbl { - Mutability::Not => "", - Mutability::Mut => "_mut", + ty::Mutability::Not => "", + ty::Mutability::Mut => "_mut", }; let arg = match arg.kind { ExprKind::AddrOf(BorrowKind::Ref, _, expr) => expr, diff --git a/src/tools/clippy/clippy_lints/src/loops/needless_range_loop.rs b/src/tools/clippy/clippy_lints/src/loops/needless_range_loop.rs index c4af46b8fd3a7..f0f65b4681a64 100644 --- a/src/tools/clippy/clippy_lints/src/loops/needless_range_loop.rs +++ b/src/tools/clippy/clippy_lints/src/loops/needless_range_loop.rs @@ -360,7 +360,7 @@ impl<'a, 'tcx> Visitor<'tcx> for VarVisitor<'a, 'tcx> { let ty = self.cx.typeck_results().expr_ty_adjusted(expr); self.prefer_mutable = false; if let ty::Ref(_, _, mutbl) = *ty.kind() { - if mutbl == Mutability::Mut { + if mutbl == ty::Mutability::Mut { self.prefer_mutable = true; } } @@ -375,7 +375,7 @@ impl<'a, 'tcx> Visitor<'tcx> for VarVisitor<'a, 'tcx> { ) { self.prefer_mutable = false; if let ty::Ref(_, _, mutbl) = *ty.kind() { - if mutbl == Mutability::Mut { + if mutbl == ty::Mutability::Mut { self.prefer_mutable = true; } } diff --git a/src/tools/clippy/clippy_lints/src/loops/utils.rs b/src/tools/clippy/clippy_lints/src/loops/utils.rs index 0a2bd89eb3cd3..1614071b763c2 100644 --- a/src/tools/clippy/clippy_lints/src/loops/utils.rs +++ b/src/tools/clippy/clippy_lints/src/loops/utils.rs @@ -331,8 +331,8 @@ pub(super) fn make_iterator_snippet(cx: &LateContext<'_>, arg: &Expr<'_>, applic match &arg_ty.kind() { ty::Ref(_, inner_ty, mutbl) if has_iter_method(cx, *inner_ty).is_some() => { let method_name = match mutbl { - Mutability::Mut => "iter_mut", - Mutability::Not => "iter", + ty::Mutability::Mut => "iter_mut", + ty::Mutability::Not => "iter", }; let caller = match &arg.kind { ExprKind::AddrOf(BorrowKind::Ref, _, arg_inner) => arg_inner, diff --git a/src/tools/clippy/clippy_lints/src/loops/while_let_on_iterator.rs b/src/tools/clippy/clippy_lints/src/loops/while_let_on_iterator.rs index 5153070cfe66b..05c70807c72f3 100644 --- a/src/tools/clippy/clippy_lints/src/loops/while_let_on_iterator.rs +++ b/src/tools/clippy/clippy_lints/src/loops/while_let_on_iterator.rs @@ -7,10 +7,11 @@ use if_chain::if_chain; use rustc_errors::Applicability; use rustc_hir::def::Res; use rustc_hir::intravisit::{walk_expr, Visitor}; -use rustc_hir::{Closure, Expr, ExprKind, HirId, LangItem, Local, Mutability, PatKind, UnOp}; +use rustc_hir::{Closure, Expr, ExprKind, HirId, LangItem, Local, PatKind, UnOp}; use rustc_lint::LateContext; use rustc_middle::hir::nested_filter::OnlyBodies; use rustc_middle::ty::adjustment::Adjust; +use rustc_middle::ty; use rustc_span::symbol::sym; use rustc_span::Symbol; @@ -48,7 +49,7 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { // If the iterator is a field or the iterator is accessed after the loop is complete it needs to be // borrowed mutably. TODO: If the struct can be partially moved from and the struct isn't used // afterwards a mutable borrow of a field isn't necessary. - let by_ref = if cx.typeck_results().expr_ty(iter_expr).ref_mutability() == Some(Mutability::Mut) + let by_ref = if cx.typeck_results().expr_ty(iter_expr).ref_mutability() == Some(ty::Mutability::Mut) || !iter_expr_struct.can_move || !iter_expr_struct.fields.is_empty() || needs_mutable_borrow(cx, &iter_expr_struct, loop_expr) diff --git a/src/tools/clippy/clippy_lints/src/manual_main_separator_str.rs b/src/tools/clippy/clippy_lints/src/manual_main_separator_str.rs index c292bbe4e9344..5861ff13754b0 100644 --- a/src/tools/clippy/clippy_lints/src/manual_main_separator_str.rs +++ b/src/tools/clippy/clippy_lints/src/manual_main_separator_str.rs @@ -3,7 +3,7 @@ use clippy_utils::msrvs::{self, Msrv}; use clippy_utils::{is_trait_method, match_def_path, paths, peel_hir_expr_refs}; use rustc_errors::Applicability; use rustc_hir::def::{DefKind, Res}; -use rustc_hir::{Expr, ExprKind, Mutability, QPath}; +use rustc_hir::{Expr, ExprKind, QPath}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty; use rustc_session::{declare_tool_lint, impl_lint_pass}; @@ -55,7 +55,7 @@ impl LateLintPass<'_> for ManualMainSeparatorStr { let ExprKind::Path(QPath::Resolved(None, path)) = receiver.kind && let Res::Def(DefKind::Const, receiver_def_id) = path.res && match_def_path(cx, receiver_def_id, &paths::PATH_MAIN_SEPARATOR) && - let ty::Ref(_, ty, Mutability::Not) = cx.typeck_results().expr_ty_adjusted(expr).kind() && + let ty::Ref(_, ty, ty::Mutability::Not) = cx.typeck_results().expr_ty_adjusted(expr).kind() && ty.is_str() { span_lint_and_sugg( diff --git a/src/tools/clippy/clippy_lints/src/matches/manual_utils.rs b/src/tools/clippy/clippy_lints/src/matches/manual_utils.rs index 781ee138c76f7..12e13f5623744 100644 --- a/src/tools/clippy/clippy_lints/src/matches/manual_utils.rs +++ b/src/tools/clippy/clippy_lints/src/matches/manual_utils.rs @@ -14,6 +14,7 @@ use rustc_hir::LangItem::{OptionNone, OptionSome}; use rustc_hir::{BindingAnnotation, Expr, ExprKind, HirId, Mutability, Pat, PatKind, Path, QPath}; use rustc_lint::LateContext; use rustc_span::{sym, SyntaxContext}; +use rustc_middle::ty; #[expect(clippy::too_many_arguments)] #[expect(clippy::too_many_lines)] @@ -101,11 +102,11 @@ where }); if let ExprKind::Path(QPath::Resolved(None, Path { res: Res::Local(l), .. })) = e.kind { match captures.get(l) { - Some(CaptureKind::Value | CaptureKind::Ref(Mutability::Mut)) => return None, - Some(CaptureKind::Ref(Mutability::Not)) if binding_ref_mutability == Mutability::Mut => { + Some(CaptureKind::Value | CaptureKind::Ref(ty::Mutability::Mut)) => return None, + Some(CaptureKind::Ref(ty::Mutability::Not)) if binding_ref_mutability == Mutability::Mut => { return None; }, - Some(CaptureKind::Ref(Mutability::Not)) | None => (), + Some(CaptureKind::Ref(ty::Mutability::Not)) | None => (), } } } diff --git a/src/tools/clippy/clippy_lints/src/methods/into_iter_on_ref.rs b/src/tools/clippy/clippy_lints/src/methods/into_iter_on_ref.rs index 8adf9e3705920..45940bf374e99 100644 --- a/src/tools/clippy/clippy_lints/src/methods/into_iter_on_ref.rs +++ b/src/tools/clippy/clippy_lints/src/methods/into_iter_on_ref.rs @@ -46,8 +46,8 @@ fn ty_has_iter_method(cx: &LateContext<'_>, self_ref_ty: Ty<'_>) -> Option<(Symb unreachable!() }; let method_name = match mutbl { - hir::Mutability::Not => "iter", - hir::Mutability::Mut => "iter_mut", + ty::Mutability::Not => "iter", + ty::Mutability::Mut => "iter_mut", }; (ty_name, method_name) }) diff --git a/src/tools/clippy/clippy_lints/src/methods/iter_overeager_cloned.rs b/src/tools/clippy/clippy_lints/src/methods/iter_overeager_cloned.rs index a49dd98db8713..169a2237df5b1 100644 --- a/src/tools/clippy/clippy_lints/src/methods/iter_overeager_cloned.rs +++ b/src/tools/clippy/clippy_lints/src/methods/iter_overeager_cloned.rs @@ -3,10 +3,10 @@ use clippy_utils::source::snippet_opt; use clippy_utils::ty::{implements_trait, is_copy}; use rustc_ast::BindingAnnotation; use rustc_errors::Applicability; -use rustc_hir::{Body, Expr, ExprKind, HirId, HirIdSet, PatKind}; +use rustc_hir::{Body, Expr, ExprKind, HirId, HirIdSet, PatKind, Mutability}; use rustc_hir_typeck::expr_use_visitor::{Delegate, ExprUseVisitor, PlaceBase, PlaceWithHirId}; use rustc_lint::LateContext; -use rustc_middle::mir::{FakeReadCause, Mutability}; +use rustc_middle::mir::FakeReadCause; use rustc_middle::ty::{self, BorrowKind}; use rustc_span::sym; diff --git a/src/tools/clippy/clippy_lints/src/methods/mod.rs b/src/tools/clippy/clippy_lints/src/methods/mod.rs index a935aea5075d7..071096c2c158a 100644 --- a/src/tools/clippy/clippy_lints/src/methods/mod.rs +++ b/src/tools/clippy/clippy_lints/src/methods/mod.rs @@ -4528,14 +4528,14 @@ impl SelfKind { } } - fn matches_ref<'a>(cx: &LateContext<'a>, mutability: hir::Mutability, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool { + fn matches_ref<'a>(cx: &LateContext<'a>, mutability: ty::Mutability, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool { if let ty::Ref(_, t, m) = *ty.kind() { return m == mutability && t == parent_ty; } let trait_sym = match mutability { - hir::Mutability::Not => sym::AsRef, - hir::Mutability::Mut => sym::AsMut, + ty::Mutability::Not => sym::AsRef, + ty::Mutability::Mut => sym::AsMut, }; let Some(trait_def_id) = cx.tcx.get_diagnostic_item(trait_sym) else { @@ -4546,14 +4546,14 @@ impl SelfKind { fn matches_none<'a>(cx: &LateContext<'a>, parent_ty: Ty<'a>, ty: Ty<'a>) -> bool { !matches_value(cx, parent_ty, ty) - && !matches_ref(cx, hir::Mutability::Not, parent_ty, ty) - && !matches_ref(cx, hir::Mutability::Mut, parent_ty, ty) + && !matches_ref(cx, ty::Mutability::Not, parent_ty, ty) + && !matches_ref(cx, ty::Mutability::Mut, parent_ty, ty) } match self { Self::Value => matches_value(cx, parent_ty, ty), - Self::Ref => matches_ref(cx, hir::Mutability::Not, parent_ty, ty) || ty == parent_ty && is_copy(cx, ty), - Self::RefMut => matches_ref(cx, hir::Mutability::Mut, parent_ty, ty), + Self::Ref => matches_ref(cx, ty::Mutability::Not, parent_ty, ty) || ty == parent_ty && is_copy(cx, ty), + Self::RefMut => matches_ref(cx, ty::Mutability::Mut, parent_ty, ty), Self::No => matches_none(cx, parent_ty, ty), } } diff --git a/src/tools/clippy/clippy_lints/src/methods/mut_mutex_lock.rs b/src/tools/clippy/clippy_lints/src/methods/mut_mutex_lock.rs index 2855e23bf5b6a..ce33a01b7c9b6 100644 --- a/src/tools/clippy/clippy_lints/src/methods/mut_mutex_lock.rs +++ b/src/tools/clippy/clippy_lints/src/methods/mut_mutex_lock.rs @@ -3,7 +3,7 @@ use clippy_utils::expr_custom_deref_adjustment; use clippy_utils::ty::is_type_diagnostic_item; use if_chain::if_chain; use rustc_errors::Applicability; -use rustc_hir::{Expr, Mutability}; +use rustc_hir::Expr; use rustc_lint::LateContext; use rustc_middle::ty; use rustc_span::{sym, Span}; @@ -12,8 +12,8 @@ use super::MUT_MUTEX_LOCK; pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, ex: &'tcx Expr<'tcx>, recv: &'tcx Expr<'tcx>, name_span: Span) { if_chain! { - if matches!(expr_custom_deref_adjustment(cx, recv), None | Some(Mutability::Mut)); - if let ty::Ref(_, _, Mutability::Mut) = cx.typeck_results().expr_ty(recv).kind(); + if matches!(expr_custom_deref_adjustment(cx, recv), None | Some(ty::Mutability::Mut)); + if let ty::Ref(_, _, ty::Mutability::Mut) = cx.typeck_results().expr_ty(recv).kind(); if let Some(method_id) = cx.typeck_results().type_dependent_def_id(ex.hir_id); if let Some(impl_id) = cx.tcx.impl_of_method(method_id); if is_type_diagnostic_item(cx, cx.tcx.type_of(impl_id).instantiate_identity(), sym::Mutex); diff --git a/src/tools/clippy/clippy_lints/src/methods/needless_collect.rs b/src/tools/clippy/clippy_lints/src/methods/needless_collect.rs index dbd965d650601..efe89465b53df 100644 --- a/src/tools/clippy/clippy_lints/src/methods/needless_collect.rs +++ b/src/tools/clippy/clippy_lints/src/methods/needless_collect.rs @@ -11,7 +11,7 @@ use rustc_data_structures::fx::FxHashMap; use rustc_errors::{Applicability, MultiSpan}; use rustc_hir::intravisit::{walk_block, walk_expr, Visitor}; use rustc_hir::{ - BindingAnnotation, Block, Expr, ExprKind, HirId, HirIdSet, Local, Mutability, Node, PatKind, Stmt, StmtKind, + BindingAnnotation, Block, Expr, ExprKind, HirId, HirIdSet, Local, Node, PatKind, Stmt, StmtKind, }; use rustc_lint::LateContext; use rustc_middle::hir::nested_filter; @@ -231,7 +231,7 @@ fn is_contains_sig(cx: &LateContext<'_>, call_id: HirId, iter_expr: &Expr<'_>) - && let sig = cx.tcx.fn_sig(id).instantiate_identity() && sig.skip_binder().output().is_bool() && let [_, search_ty] = *sig.skip_binder().inputs() - && let ty::Ref(_, search_ty, Mutability::Not) = *cx.tcx.erase_late_bound_regions(sig.rebind(search_ty)).kind() + && let ty::Ref(_, search_ty, ty::Mutability::Not) = *cx.tcx.erase_late_bound_regions(sig.rebind(search_ty)).kind() && let Some(iter_trait) = cx.tcx.get_diagnostic_item(sym::Iterator) && let Some(iter_item) = cx.tcx .associated_items(iter_trait) @@ -501,7 +501,7 @@ fn get_captured_ids(cx: &LateContext<'_>, ty: Ty<'_>) -> HirIdSet { .unwrap() .into_iter() .for_each(|(hir_id, capture_kind)| { - if matches!(capture_kind, CaptureKind::Ref(Mutability::Mut)) { + if matches!(capture_kind, CaptureKind::Ref(ty::Mutability::Mut)) { set.insert(hir_id); } }); diff --git a/src/tools/clippy/clippy_lints/src/methods/unnecessary_to_owned.rs b/src/tools/clippy/clippy_lints/src/methods/unnecessary_to_owned.rs index 50d6f3b7e55f5..3be9309fc1545 100644 --- a/src/tools/clippy/clippy_lints/src/methods/unnecessary_to_owned.rs +++ b/src/tools/clippy/clippy_lints/src/methods/unnecessary_to_owned.rs @@ -8,11 +8,10 @@ use clippy_utils::visitors::find_all_ret_expressions; use clippy_utils::{fn_def_id, get_parent_expr, is_diag_item_method, is_diag_trait_item, return_ty}; use rustc_errors::Applicability; use rustc_hir::def_id::DefId; -use rustc_hir::{BorrowKind, Expr, ExprKind, ItemKind, Node}; +use rustc_hir::{BorrowKind, Expr, ExprKind, ItemKind, Node, Mutability}; use rustc_hir_typeck::{FnCtxt, Inherited}; use rustc_infer::infer::TyCtxtInferExt; use rustc_lint::LateContext; -use rustc_middle::mir::Mutability; use rustc_middle::ty::adjustment::{Adjust, Adjustment, OverloadedDeref}; use rustc_middle::ty::{ self, ClauseKind, EarlyBinder, GenericArg, GenericArgKind, GenericArgsRef, ParamTy, ProjectionPredicate, @@ -278,7 +277,7 @@ fn check_other_call_arg<'tcx>( cx.tcx.lifetimes.re_erased, ty::TypeAndMut { ty: receiver_ty, - mutbl: Mutability::Not, + mutbl: ty::Mutability::Not, }, ))) } else { diff --git a/src/tools/clippy/clippy_lints/src/methods/utils.rs b/src/tools/clippy/clippy_lints/src/methods/utils.rs index 9f1f73e602185..0e41243039d60 100644 --- a/src/tools/clippy/clippy_lints/src/methods/utils.rs +++ b/src/tools/clippy/clippy_lints/src/methods/utils.rs @@ -145,7 +145,7 @@ impl<'cx, 'tcx> Visitor<'tcx> for CloneOrCopyVisitor<'cx, 'tcx> { if let Some(method_def_id) = self.cx.typeck_results().type_dependent_def_id(parent.hir_id); let method_ty = self.cx.tcx.type_of(method_def_id).instantiate_identity(); let self_ty = method_ty.fn_sig(self.cx.tcx).input(0).skip_binder(); - if matches!(self_ty.kind(), ty::Ref(_, _, Mutability::Not)); + if matches!(self_ty.kind(), ty::Ref(_, _, ty::Mutability::Not)); then { return; } diff --git a/src/tools/clippy/clippy_lints/src/mut_mut.rs b/src/tools/clippy/clippy_lints/src/mut_mut.rs index 64d8333a093b1..3f5a7165d4183 100644 --- a/src/tools/clippy/clippy_lints/src/mut_mut.rs +++ b/src/tools/clippy/clippy_lints/src/mut_mut.rs @@ -68,7 +68,7 @@ impl<'a, 'tcx> intravisit::Visitor<'tcx> for MutVisitor<'a, 'tcx> { expr.span, "generally you want to avoid `&mut &mut _` if possible", ); - } else if let ty::Ref(_, ty, hir::Mutability::Mut) = self.cx.typeck_results().expr_ty(e).kind() { + } else if let ty::Ref(_, ty, ty::Mutability::Mut) = self.cx.typeck_results().expr_ty(e).kind() { if ty.peel_refs().is_sized(self.cx.tcx, self.cx.param_env) { span_lint( self.cx, diff --git a/src/tools/clippy/clippy_lints/src/mut_reference.rs b/src/tools/clippy/clippy_lints/src/mut_reference.rs index 01b850cdb1139..c2cd828f4194c 100644 --- a/src/tools/clippy/clippy_lints/src/mut_reference.rs +++ b/src/tools/clippy/clippy_lints/src/mut_reference.rs @@ -83,9 +83,9 @@ fn check_arguments<'tcx>( let parameters = type_definition.fn_sig(cx.tcx).skip_binder().inputs(); for (argument, parameter) in iter::zip(arguments, parameters) { match parameter.kind() { - ty::Ref(_, _, Mutability::Not) + ty::Ref(_, _, ty::Mutability::Not) | ty::RawPtr(ty::TypeAndMut { - mutbl: Mutability::Not, .. + mutbl: ty::Mutability::Not, .. }) => { if let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Mut, _) = argument.kind { span_lint( diff --git a/src/tools/clippy/clippy_lints/src/mutable_debug_assertion.rs b/src/tools/clippy/clippy_lints/src/mutable_debug_assertion.rs index dea432fdbd505..fef0337c7c7a5 100644 --- a/src/tools/clippy/clippy_lints/src/mutable_debug_assertion.rs +++ b/src/tools/clippy/clippy_lints/src/mutable_debug_assertion.rs @@ -104,7 +104,7 @@ impl<'a, 'tcx> Visitor<'tcx> for MutArgVisitor<'a, 'tcx> { if let Some(adj) = self.cx.typeck_results().adjustments().get(expr.hir_id) { if adj .iter() - .any(|a| matches!(a.target.kind(), ty::Ref(_, _, Mutability::Mut))) + .any(|a| matches!(a.target.kind(), ty::Ref(_, _, ty::Mutability::Mut))) { self.found = true; return; diff --git a/src/tools/clippy/clippy_lints/src/needless_borrows_for_generic_args.rs b/src/tools/clippy/clippy_lints/src/needless_borrows_for_generic_args.rs index d55c77a92b158..da5396571b0b9 100644 --- a/src/tools/clippy/clippy_lints/src/needless_borrows_for_generic_args.rs +++ b/src/tools/clippy/clippy_lints/src/needless_borrows_for_generic_args.rs @@ -7,7 +7,7 @@ use clippy_utils::{expr_use_ctxt, peel_n_hir_expr_refs, DefinedTy, ExprUseNode}; use rustc_errors::Applicability; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::{DefId, LocalDefId}; -use rustc_hir::{Body, Expr, ExprKind, Mutability, Path, QPath}; +use rustc_hir::{Body, Expr, ExprKind, Path, QPath}; use rustc_index::bit_set::BitSet; use rustc_infer::infer::TyCtxtInferExt; use rustc_lint::{LateContext, LateLintPass}; @@ -227,7 +227,7 @@ fn needless_borrow_count<'tcx>( } // https://github.com/rust-lang/rust-clippy/pull/9136#pullrequestreview-1037379321 - if trait_with_ref_mut_self_method && !matches!(referent_ty.kind(), ty::Ref(_, _, Mutability::Mut)) { + if trait_with_ref_mut_self_method && !matches!(referent_ty.kind(), ty::Ref(_, _, ty::Mutability::Mut)) { return false; } @@ -284,7 +284,7 @@ fn has_ref_mut_self_method(cx: &LateContext<'_>, trait_def_id: DefId) -> bool { .instantiate_identity() .skip_binder() .inputs()[0]; - matches!(self_ty.kind(), ty::Ref(_, _, Mutability::Mut)) + matches!(self_ty.kind(), ty::Ref(_, _, ty::Mutability::Mut)) } else { false } diff --git a/src/tools/clippy/clippy_lints/src/needless_pass_by_ref_mut.rs b/src/tools/clippy/clippy_lints/src/needless_pass_by_ref_mut.rs index 212d6234bdb3c..66ede096dd29a 100644 --- a/src/tools/clippy/clippy_lints/src/needless_pass_by_ref_mut.rs +++ b/src/tools/clippy/clippy_lints/src/needless_pass_by_ref_mut.rs @@ -7,7 +7,7 @@ use rustc_data_structures::fx::{FxHashSet, FxIndexMap}; use rustc_errors::Applicability; use rustc_hir::intravisit::{walk_qpath, FnKind, Visitor}; use rustc_hir::{ - Body, Closure, Expr, ExprKind, FnDecl, HirId, HirIdMap, HirIdSet, Impl, ItemKind, Mutability, Node, PatKind, QPath, + Body, Closure, Expr, ExprKind, FnDecl, HirId, HirIdMap, HirIdSet, Impl, ItemKind, Node, PatKind, QPath, }; use rustc_hir_typeck::expr_use_visitor as euv; use rustc_infer::infer::{InferCtxt, TyCtxtInferExt}; @@ -79,7 +79,7 @@ fn should_skip<'tcx>( arg: &rustc_hir::Param<'_>, ) -> bool { // We check if this a `&mut`. `ref_mutability` returns `None` if it's not a reference. - if !matches!(ty.ref_mutability(), Some(Mutability::Mut)) { + if !matches!(ty.ref_mutability(), Some(ty::Mutability::Mut)) { return true; } @@ -324,7 +324,7 @@ impl<'tcx> euv::Delegate<'tcx> for MutablyUsedVariablesCtxt<'tcx> { self.add_alias(bind_id, *vid); } } else if !self.prev_move_to_closure.contains(vid) - && matches!(base_ty.ref_mutability(), Some(Mutability::Mut)) + && matches!(base_ty.ref_mutability(), Some(ty::Mutability::Mut)) { self.add_mutably_used_var(*vid); } @@ -352,7 +352,7 @@ impl<'tcx> euv::Delegate<'tcx> for MutablyUsedVariablesCtxt<'tcx> { // return `ImmBorrow`. So if there is "Unique" and it's a mutable reference, we add it // to the mutably used variables set. if borrow == ty::BorrowKind::MutBorrow - || (borrow == ty::BorrowKind::UniqueImmBorrow && base_ty.ref_mutability() == Some(Mutability::Mut)) + || (borrow == ty::BorrowKind::UniqueImmBorrow && base_ty.ref_mutability() == Some(ty::Mutability::Mut)) { self.add_mutably_used_var(*vid); } diff --git a/src/tools/clippy/clippy_lints/src/option_if_let_else.rs b/src/tools/clippy/clippy_lints/src/option_if_let_else.rs index a7a7f4fd8fa2c..aa62b50d82a88 100644 --- a/src/tools/clippy/clippy_lints/src/option_if_let_else.rs +++ b/src/tools/clippy/clippy_lints/src/option_if_let_else.rs @@ -10,6 +10,7 @@ use rustc_hir::def::Res; use rustc_hir::LangItem::{OptionNone, OptionSome, ResultErr, ResultOk}; use rustc_hir::{Arm, BindingAnnotation, Expr, ExprKind, MatchSource, Mutability, Pat, PatKind, Path, QPath, UnOp}; use rustc_lint::{LateContext, LateLintPass}; +use rustc_middle::ty; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::SyntaxContext; @@ -140,7 +141,7 @@ fn try_get_option_occurrence<'tcx>( ExprKind::AddrOf(_, Mutability::Not, _) => (true, false), ExprKind::AddrOf(_, Mutability::Mut, _) => (false, true), _ if let Some(mutb) = cx.typeck_results().expr_ty(expr).ref_mutability() => { - (mutb == Mutability::Not, mutb == Mutability::Mut) + (mutb == ty::Mutability::Not, mutb == ty::Mutability::Mut) } _ => (bind_annotation == BindingAnnotation::REF, bind_annotation == BindingAnnotation::REF_MUT), }; @@ -157,9 +158,9 @@ fn try_get_option_occurrence<'tcx>( match some_captures.get(local_id) .or_else(|| (method_sugg == "map_or_else").then_some(()).and_then(|()| none_captures.get(local_id))) { - Some(CaptureKind::Value | CaptureKind::Ref(Mutability::Mut)) => return None, - Some(CaptureKind::Ref(Mutability::Not)) if as_mut => return None, - Some(CaptureKind::Ref(Mutability::Not)) | None => (), + Some(CaptureKind::Value | CaptureKind::Ref(ty::Mutability::Mut)) => return None, + Some(CaptureKind::Ref(ty::Mutability::Not)) if as_mut => return None, + Some(CaptureKind::Ref(ty::Mutability::Not)) | None => (), } } } diff --git a/src/tools/clippy/clippy_lints/src/pass_by_ref_or_value.rs b/src/tools/clippy/clippy_lints/src/pass_by_ref_or_value.rs index 41513647f054e..dd3c2b93bc9a4 100644 --- a/src/tools/clippy/clippy_lints/src/pass_by_ref_or_value.rs +++ b/src/tools/clippy/clippy_lints/src/pass_by_ref_or_value.rs @@ -11,7 +11,7 @@ use rustc_data_structures::fx::FxHashSet; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_hir::intravisit::FnKind; -use rustc_hir::{BindingAnnotation, Body, FnDecl, Impl, ItemKind, MutTy, Mutability, Node, PatKind}; +use rustc_hir::{BindingAnnotation, Body, FnDecl, Impl, ItemKind, MutTy, Node, PatKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty::adjustment::{Adjust, PointerCoercion}; use rustc_middle::ty::layout::LayoutOf; @@ -166,7 +166,7 @@ impl<'tcx> PassByRefOrValue { } match *ty.skip_binder().kind() { - ty::Ref(lt, ty, Mutability::Not) => { + ty::Ref(lt, ty, ty::Mutability::Not) => { match lt.kind() { RegionKind::ReLateBound(index, region) if index.as_u32() == 0 && output_regions.contains(®ion) => diff --git a/src/tools/clippy/clippy_lints/src/pattern_type_mismatch.rs b/src/tools/clippy/clippy_lints/src/pattern_type_mismatch.rs index 9f98195d311fe..f57587f92a225 100644 --- a/src/tools/clippy/clippy_lints/src/pattern_type_mismatch.rs +++ b/src/tools/clippy/clippy_lints/src/pattern_type_mismatch.rs @@ -1,5 +1,5 @@ use clippy_utils::diagnostics::span_lint_and_help; -use rustc_hir::{intravisit, Body, Expr, ExprKind, FnDecl, Let, LocalSource, Mutability, Pat, PatKind, Stmt, StmtKind}; +use rustc_hir::{intravisit, Body, Expr, ExprKind, FnDecl, Let, LocalSource, Pat, PatKind, Stmt, StmtKind}; use rustc_lint::{LateContext, LateLintPass, LintContext}; use rustc_middle::lint::in_external_macro; use rustc_middle::ty; @@ -145,8 +145,8 @@ fn apply_lint(cx: &LateContext<'_>, pat: &Pat<'_>, deref_possible: DerefPossible _ => "", }, match mutability { - Mutability::Mut => "&mut _", - Mutability::Not => "&_", + ty::Mutability::Mut => "&mut _", + ty::Mutability::Not => "&_", }, ), ); @@ -162,7 +162,7 @@ enum Level { Lower, } -fn find_first_mismatch(cx: &LateContext<'_>, pat: &Pat<'_>) -> Option<(Span, Mutability, Level)> { +fn find_first_mismatch(cx: &LateContext<'_>, pat: &Pat<'_>) -> Option<(Span, ty::Mutability, Level)> { let mut result = None; pat.walk(|p| { if result.is_some() { diff --git a/src/tools/clippy/clippy_lints/src/ptr.rs b/src/tools/clippy/clippy_lints/src/ptr.rs index 310051efc5088..05871c4ba159b 100644 --- a/src/tools/clippy/clippy_lints/src/ptr.rs +++ b/src/tools/clippy/clippy_lints/src/ptr.rs @@ -12,7 +12,7 @@ use rustc_hir::hir_id::HirIdMap; use rustc_hir::intravisit::{walk_expr, Visitor}; use rustc_hir::{ self as hir, AnonConst, BinOpKind, BindingAnnotation, Body, Expr, ExprKind, FnRetTy, FnSig, GenericArg, - ImplItemKind, ItemKind, Lifetime, Mutability, Node, Param, PatKind, QPath, TraitFn, TraitItem, TraitItemKind, + ImplItemKind, ItemKind, Lifetime, Node, Param, PatKind, QPath, TraitFn, TraitItem, TraitItemKind, TyKind, Unsafety, }; use rustc_infer::infer::TyCtxtInferExt; @@ -174,7 +174,7 @@ impl<'tcx> LateLintPass<'tcx> for Ptr { sig.decl.inputs, &[], ) - .filter(|arg| arg.mutability() == Mutability::Not) + .filter(|arg| arg.mutability() == ty::Mutability::Not) { span_lint_hir_and_then(cx, PTR_ARG, arg.emission_id, arg.span, &arg.build_msg(), |diag| { diag.span_suggestion( @@ -231,7 +231,7 @@ impl<'tcx> LateLintPass<'tcx> for Ptr { let decl = sig.decl; let sig = cx.tcx.fn_sig(item_id).instantiate_identity().skip_binder(); let lint_args: Vec<_> = check_fn_args(cx, sig, decl.inputs, body.params) - .filter(|arg| !is_trait_item || arg.mutability() == Mutability::Not) + .filter(|arg| !is_trait_item || arg.mutability() == ty::Mutability::Not) .collect(); let results = check_ptr_arg_usage(cx, body, &lint_args); @@ -345,14 +345,14 @@ impl PtrArg<'_> { ) } - fn mutability(&self) -> Mutability { + fn mutability(&self) -> ty::Mutability { self.ref_prefix.mutability } } struct RefPrefix { lt: Lifetime, - mutability: Mutability, + mutability: ty::Mutability, } impl fmt::Display for RefPrefix { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { @@ -461,7 +461,7 @@ fn check_fn_args<'cx, 'tcx: 'cx>( [("clone", ".to_path_buf()"), ("as_path", "")].as_slice(), DerefTy::Path, ), - Some(sym::Cow) if mutability == Mutability::Not => { + Some(sym::Cow) if mutability == ty::Mutability::Not => { if let Some((lifetime, ty)) = name.args .and_then(|args| { if let [GenericArg::Lifetime(lifetime), ty] = args.args { @@ -543,7 +543,7 @@ fn check_fn_args<'cx, 'tcx: 'cx>( fn check_mut_from_ref<'tcx>(cx: &LateContext<'tcx>, sig: &FnSig<'_>, body: Option<&'tcx Body<'_>>) { if let FnRetTy::Return(ty) = sig.decl.output - && let Some((out, Mutability::Mut, _)) = get_ref_lm(ty) + && let Some((out, hir::Mutability::Mut, _)) = get_ref_lm(ty) { let out_region = cx.tcx.named_bound_var(out.hir_id); let args: Option> = sig @@ -552,7 +552,7 @@ fn check_mut_from_ref<'tcx>(cx: &LateContext<'tcx>, sig: &FnSig<'_>, body: Optio .iter() .filter_map(get_ref_lm) .filter(|&(lt, _, _)| cx.tcx.named_bound_var(lt.hir_id) == out_region) - .map(|(_, mutability, span)| (mutability == Mutability::Not).then_some(span)) + .map(|(_, mutability, span)| (mutability == hir::Mutability::Not).then_some(span)) .collect(); if let Some(args) = args && !args.is_empty() @@ -747,7 +747,7 @@ fn matches_preds<'tcx>( }) } -fn get_ref_lm<'tcx>(ty: &'tcx hir::Ty<'tcx>) -> Option<(&'tcx Lifetime, Mutability, Span)> { +fn get_ref_lm<'tcx>(ty: &'tcx hir::Ty<'tcx>) -> Option<(&'tcx Lifetime, hir::Mutability, Span)> { if let TyKind::Ref(lt, ref m) = ty.kind { Some((lt, m.mutbl, ty.span)) } else { diff --git a/src/tools/clippy/clippy_lints/src/transmute/transmute_ptr_to_ref.rs b/src/tools/clippy/clippy_lints/src/transmute/transmute_ptr_to_ref.rs index 6bdb9aa5a26d2..36835ac8d2db0 100644 --- a/src/tools/clippy/clippy_lints/src/transmute/transmute_ptr_to_ref.rs +++ b/src/tools/clippy/clippy_lints/src/transmute/transmute_ptr_to_ref.rs @@ -4,7 +4,7 @@ use clippy_utils::msrvs::{self, Msrv}; use clippy_utils::source::snippet_with_applicability; use clippy_utils::sugg; use rustc_errors::Applicability; -use rustc_hir::{self as hir, Expr, GenericArg, Mutability, Path, TyKind}; +use rustc_hir::{self as hir, Expr, GenericArg, Path, TyKind}; use rustc_lint::LateContext; use rustc_middle::ty::{self, Ty, TypeVisitableExt}; @@ -28,7 +28,7 @@ pub(super) fn check<'tcx>( &format!("transmute from a pointer type (`{from_ty}`) to a reference type (`{to_ty}`)"), |diag| { let arg = sugg::Sugg::hir(cx, arg, ".."); - let (deref, cast) = if *mutbl == Mutability::Mut { + let (deref, cast) = if *mutbl == ty::Mutability::Mut { ("&mut *", "*mut") } else { ("&*", "*const") diff --git a/src/tools/clippy/clippy_lints/src/transmute/transmute_ref_to_ref.rs b/src/tools/clippy/clippy_lints/src/transmute/transmute_ref_to_ref.rs index ea9ad99618abc..e6664df0b00ba 100644 --- a/src/tools/clippy/clippy_lints/src/transmute/transmute_ref_to_ref.rs +++ b/src/tools/clippy/clippy_lints/src/transmute/transmute_ref_to_ref.rs @@ -4,7 +4,7 @@ use clippy_utils::source::snippet; use clippy_utils::sugg; use if_chain::if_chain; use rustc_errors::Applicability; -use rustc_hir::{Expr, Mutability}; +use rustc_hir::Expr; use rustc_lint::LateContext; use rustc_middle::ty::{self, Ty}; @@ -27,7 +27,7 @@ pub(super) fn check<'tcx>( if let ty::Uint(ty::UintTy::U8) = slice_ty.kind(); if from_mutbl == to_mutbl; then { - let postfix = if *from_mutbl == Mutability::Mut { + let postfix = if *from_mutbl == ty::Mutability::Mut { "_mut" } else { "" @@ -66,7 +66,7 @@ pub(super) fn check<'tcx>( let sugg_paren = arg .as_ty(Ty::new_ptr(cx.tcx,ty_from_and_mut)) .as_ty(Ty::new_ptr(cx.tcx,ty_to_and_mut)); - let sugg = if *to_mutbl == Mutability::Mut { + let sugg = if *to_mutbl == ty::Mutability::Mut { sugg_paren.mut_addr_deref() } else { sugg_paren.addr_deref() diff --git a/src/tools/clippy/clippy_lints/src/vec_init_then_push.rs b/src/tools/clippy/clippy_lints/src/vec_init_then_push.rs index 3fa51216c7737..55fa86ba58226 100644 --- a/src/tools/clippy/clippy_lints/src/vec_init_then_push.rs +++ b/src/tools/clippy/clippy_lints/src/vec_init_then_push.rs @@ -11,6 +11,7 @@ use rustc_hir::{ }; use rustc_lint::{LateContext, LateLintPass, LintContext}; use rustc_middle::lint::in_external_macro; +use rustc_middle::ty; use rustc_session::{declare_tool_lint, impl_lint_pass}; use rustc_span::{Span, Symbol}; @@ -77,8 +78,8 @@ impl VecPushSearcher { return ControlFlow::Continue(()); }; let adjusted_ty = cx.typeck_results().expr_ty_adjusted(e); - let adjusted_mut = adjusted_ty.ref_mutability().unwrap_or(Mutability::Not); - needs_mut |= adjusted_mut == Mutability::Mut; + let adjusted_mut = adjusted_ty.ref_mutability().unwrap_or(ty::Mutability::Not); + needs_mut |= adjusted_mut == ty::Mutability::Mut; match parent.kind { ExprKind::AddrOf(_, Mutability::Mut, _) => { needs_mut = true; @@ -96,13 +97,13 @@ impl VecPushSearcher { } } needs_mut |= cx.typeck_results().expr_ty_adjusted(last_place).ref_mutability() - == Some(Mutability::Mut) + == Some(ty::Mutability::Mut) || get_parent_expr(cx, last_place) .map_or(false, |e| matches!(e.kind, ExprKind::AddrOf(_, Mutability::Mut, _))); }, ExprKind::MethodCall(_, recv, ..) if recv.hir_id == e.hir_id - && adjusted_mut == Mutability::Mut + && adjusted_mut == ty::Mutability::Mut && !adjusted_ty.peel_refs().is_slice() => { // No need to set `needs_mut` to true. The receiver will be either explicitly borrowed, or it will diff --git a/src/tools/clippy/clippy_utils/src/lib.rs b/src/tools/clippy/clippy_utils/src/lib.rs index c2c97259d38bf..f6e165230a5f4 100644 --- a/src/tools/clippy/clippy_utils/src/lib.rs +++ b/src/tools/clippy/clippy_utils/src/lib.rs @@ -90,7 +90,7 @@ use rustc_hir::LangItem::{OptionNone, OptionSome, ResultErr, ResultOk}; use rustc_hir::{ self as hir, def, Arm, ArrayLen, BindingAnnotation, Block, BlockCheckMode, Body, Closure, Destination, Expr, ExprField, ExprKind, FnDecl, FnRetTy, GenericArgs, HirId, Impl, ImplItem, ImplItemKind, ImplItemRef, Item, - ItemKind, LangItem, Local, MatchSource, Mutability, Node, OwnerId, Param, Pat, PatKind, Path, PathSegment, PrimTy, + ItemKind, LangItem, Local, MatchSource, Node, OwnerId, Param, Pat, PatKind, Path, PathSegment, PrimTy, QPath, Stmt, StmtKind, TraitItem, TraitItemKind, TraitItemRef, TraitRef, TyKind, UnOp, }; use rustc_lexer::{tokenize, TokenKind}; @@ -103,7 +103,7 @@ use rustc_middle::ty::fast_reject::SimplifiedType; use rustc_middle::ty::layout::IntegerExt; use rustc_middle::ty::{ self as rustc_ty, Binder, BorrowKind, ClosureKind, FloatTy, IntTy, ParamEnv, ParamEnvAnd, Ty, TyCtxt, TypeAndMut, - TypeVisitableExt, UintTy, UpvarCapture, + TypeVisitableExt, UintTy, UpvarCapture, Mutability, }; use rustc_span::hygiene::{ExpnKind, MacroKind}; use rustc_span::source_map::SourceMap; @@ -1041,7 +1041,10 @@ pub fn capture_local_usage(cx: &LateContext<'_>, e: &Expr<'_>) -> CaptureKind { match parent { Node::Expr(e) => match e.kind { - ExprKind::AddrOf(_, mutability, _) => return CaptureKind::Ref(mutability), + ExprKind::AddrOf(_, mutability, _) => return CaptureKind::Ref(match mutability { + hir::Mutability::Not => Mutability::Not, + hir::Mutability::Mut => Mutability::Mut, + }), ExprKind::Index(..) | ExprKind::Unary(UnOp::Deref, _) => capture = CaptureKind::Ref(Mutability::Not), ExprKind::Assign(lhs, ..) | ExprKind::AssignOp(_, lhs, _) if lhs.hir_id == child_id => { return CaptureKind::Ref(Mutability::Mut); diff --git a/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs b/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs index 55f9cb27ad4db..71ed51da2b9bb 100644 --- a/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs +++ b/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs @@ -58,7 +58,7 @@ fn check_ty<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, span: Span) -> McfResult { }; match ty.kind() { - ty::Ref(_, _, hir::Mutability::Mut) => { + ty::Ref(_, _, ty::Mutability::Mut) => { return Err((span, "mutable references in const fn are unstable".into())); }, ty::Alias(ty::Opaque, ..) => return Err((span, "`impl Trait` in const fn is unstable".into())), diff --git a/src/tools/clippy/clippy_utils/src/ty.rs b/src/tools/clippy/clippy_utils/src/ty.rs index 673b259523e18..d1bf872317df2 100644 --- a/src/tools/clippy/clippy_utils/src/ty.rs +++ b/src/tools/clippy/clippy_utils/src/ty.rs @@ -513,8 +513,8 @@ pub fn peel_mid_ty_refs(ty: Ty<'_>) -> (Ty<'_>, usize) { pub fn peel_mid_ty_refs_is_mutable(ty: Ty<'_>) -> (Ty<'_>, usize, Mutability) { fn f(ty: Ty<'_>, count: usize, mutability: Mutability) -> (Ty<'_>, usize, Mutability) { match ty.kind() { - ty::Ref(_, ty, Mutability::Mut) => f(*ty, count + 1, mutability), - ty::Ref(_, ty, Mutability::Not) => f(*ty, count + 1, Mutability::Not), + ty::Ref(_, ty, ty::Mutability::Mut) => f(*ty, count + 1, mutability), + ty::Ref(_, ty, ty::Mutability::Not) => f(*ty, count + 1, Mutability::Not), _ => (ty, count, mutability), } } @@ -1182,7 +1182,7 @@ pub fn make_normalized_projection<'tcx>( /// etc. pub fn is_interior_mut_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool { match *ty.kind() { - ty::Ref(_, inner_ty, mutbl) => mutbl == Mutability::Mut || is_interior_mut_ty(cx, inner_ty), + ty::Ref(_, inner_ty, mutbl) => mutbl == ty::Mutability::Mut || is_interior_mut_ty(cx, inner_ty), ty::Slice(inner_ty) => is_interior_mut_ty(cx, inner_ty), ty::Array(inner_ty, size) => { size.try_eval_target_usize(cx.tcx, cx.param_env) diff --git a/src/tools/miri/src/concurrency/data_race.rs b/src/tools/miri/src/concurrency/data_race.rs index f3a8f1c25d7b2..891e07382ee0f 100644 --- a/src/tools/miri/src/concurrency/data_race.rs +++ b/src/tools/miri/src/concurrency/data_race.rs @@ -46,10 +46,10 @@ use std::{ mem, }; -use rustc_ast::Mutability; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_index::{Idx, IndexVec}; use rustc_middle::mir; +use rustc_middle::ty::Mutability; use rustc_span::Span; use rustc_target::abi::{Align, Size}; diff --git a/src/tools/miri/src/machine.rs b/src/tools/miri/src/machine.rs index 7241c243d8ab1..1ac857b373396 100644 --- a/src/tools/miri/src/machine.rs +++ b/src/tools/miri/src/machine.rs @@ -11,10 +11,10 @@ use either::Either; use rand::rngs::StdRng; use rand::SeedableRng; -use rustc_ast::ast::Mutability; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; #[allow(unused)] use rustc_data_structures::static_assert_size; +use rustc_middle::ty::Mutability; use rustc_middle::{ mir, ty::{ diff --git a/src/tools/miri/src/shims/backtrace.rs b/src/tools/miri/src/shims/backtrace.rs index ee2edd462d19e..34af71d1be534 100644 --- a/src/tools/miri/src/shims/backtrace.rs +++ b/src/tools/miri/src/shims/backtrace.rs @@ -1,6 +1,6 @@ use crate::*; -use rustc_ast::ast::Mutability; use rustc_middle::ty::layout::LayoutOf as _; +use rustc_middle::ty::Mutability; use rustc_middle::ty::{self, Instance, Ty}; use rustc_span::{BytePos, Loc, Symbol}; use rustc_target::{abi::Size, spec::abi::Abi}; diff --git a/src/tools/miri/src/shims/panic.rs b/src/tools/miri/src/shims/panic.rs index 5c0f828e4e6bb..9664c464dbf5a 100644 --- a/src/tools/miri/src/shims/panic.rs +++ b/src/tools/miri/src/shims/panic.rs @@ -13,7 +13,7 @@ use log::trace; -use rustc_ast::Mutability; +use rustc_middle::ty::Mutability; use rustc_middle::{mir, ty}; use rustc_span::Symbol; use rustc_target::spec::abi::Abi;