diff --git a/src/libcore/ptr/mod.rs b/src/libcore/ptr/mod.rs index 4913cd73a2a9a..84f28488c74b6 100644 --- a/src/libcore/ptr/mod.rs +++ b/src/libcore/ptr/mod.rs @@ -76,12 +76,15 @@ use crate::intrinsics::{self, is_aligned_and_not_null, is_nonoverlapping}; use crate::mem::{self, MaybeUninit}; #[stable(feature = "rust1", since = "1.0.0")] +#[doc(inline)] pub use crate::intrinsics::copy_nonoverlapping; #[stable(feature = "rust1", since = "1.0.0")] +#[doc(inline)] pub use crate::intrinsics::copy; #[stable(feature = "rust1", since = "1.0.0")] +#[doc(inline)] pub use crate::intrinsics::write_bytes; mod non_null; diff --git a/src/librustc_error_codes/error_codes/E0308.md b/src/librustc_error_codes/error_codes/E0308.md index b2c8437049001..e2c40f03019c1 100644 --- a/src/librustc_error_codes/error_codes/E0308.md +++ b/src/librustc_error_codes/error_codes/E0308.md @@ -12,8 +12,7 @@ let x: i32 = "I am not a number!"; // type `i32` assigned to variable `x` ``` -This error occurs when the compiler was unable to infer the concrete type of a -variable. It can happen in several cases, the most common being a mismatch -between the type that the compiler inferred for a variable based on its -initializing expression, on the one hand, and the type the author explicitly -assigned to the variable, on the other hand. +This error occurs when the compiler is unable to infer the concrete type of a +variable. It can occur in several cases, the most common being a mismatch +between two types: the type the author explicitly assigned, and the type the +compiler inferred. diff --git a/src/librustc_error_codes/error_codes/E0567.md b/src/librustc_error_codes/error_codes/E0567.md index ec1ed03c126e1..05cf8fed03160 100644 --- a/src/librustc_error_codes/error_codes/E0567.md +++ b/src/librustc_error_codes/error_codes/E0567.md @@ -6,8 +6,7 @@ Erroneous code example: #![feature(optin_builtin_traits)] auto trait Generic {} // error! - -fn main() {} +# fn main() {} ``` Since an auto trait is implemented on all existing types, the @@ -20,6 +19,5 @@ To fix this issue, just remove the generics: #![feature(optin_builtin_traits)] auto trait Generic {} // ok! - -fn main() {} +# fn main() {} ``` diff --git a/src/librustc_middle/mir/interpret/allocation.rs b/src/librustc_middle/mir/interpret/allocation.rs index 8b9f09774853a..afc6a958296fc 100644 --- a/src/librustc_middle/mir/interpret/allocation.rs +++ b/src/librustc_middle/mir/interpret/allocation.rs @@ -13,8 +13,6 @@ use super::{ read_target_uint, write_target_uint, AllocId, InterpResult, Pointer, Scalar, ScalarMaybeUndef, }; -// NOTE: When adding new fields, make sure to adjust the `Snapshot` impl in -// `src/librustc_mir/interpret/snapshot.rs`. #[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)] #[derive(HashStable)] pub struct Allocation { diff --git a/src/librustc_middle/mir/interpret/error.rs b/src/librustc_middle/mir/interpret/error.rs index c56dc5196c6c2..2510dbcea0bdc 100644 --- a/src/librustc_middle/mir/interpret/error.rs +++ b/src/librustc_middle/mir/interpret/error.rs @@ -361,8 +361,6 @@ pub enum UndefinedBehaviorInfo { InvalidUndefBytes(Option), /// Working with a local that is not currently live. DeadLocal, - /// Trying to read from the return place of a function. - ReadFromReturnPlace, } impl fmt::Debug for UndefinedBehaviorInfo { @@ -424,7 +422,6 @@ impl fmt::Debug for UndefinedBehaviorInfo { "using uninitialized data, but this operation requires initialized memory" ), DeadLocal => write!(f, "accessing a dead local variable"), - ReadFromReturnPlace => write!(f, "reading from return place"), } } } diff --git a/src/librustc_middle/mir/interpret/value.rs b/src/librustc_middle/mir/interpret/value.rs index f3c1c87dad484..25fa3e5e8e0e3 100644 --- a/src/librustc_middle/mir/interpret/value.rs +++ b/src/librustc_middle/mir/interpret/value.rs @@ -188,11 +188,6 @@ impl<'tcx, Tag> Scalar { } } - #[inline] - pub fn null_ptr(cx: &impl HasDataLayout) -> Self { - Scalar::Raw { data: 0, size: cx.data_layout().pointer_size.bytes() as u8 } - } - #[inline] pub fn zst() -> Self { Scalar::Raw { data: 0, size: 0 } diff --git a/src/librustc_mir/borrow_check/type_check/mod.rs b/src/librustc_mir/borrow_check/type_check/mod.rs index 796efd2bab976..179641ec7c03a 100644 --- a/src/librustc_mir/borrow_check/type_check/mod.rs +++ b/src/librustc_mir/borrow_check/type_check/mod.rs @@ -42,7 +42,10 @@ use rustc_trait_selection::traits::{self, ObligationCause, PredicateObligations} use crate::dataflow::move_paths::MoveData; use crate::dataflow::MaybeInitializedPlaces; use crate::dataflow::ResultsCursor; -use crate::transform::promote_consts::should_suggest_const_in_array_repeat_expressions_attribute; +use crate::transform::{ + check_consts::ConstCx, + promote_consts::should_suggest_const_in_array_repeat_expressions_attribute, +}; use crate::borrow_check::{ borrow_set::BorrowSet, @@ -1984,14 +1987,17 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { let span = body.source_info(location).span; let ty = operand.ty(body, tcx); if !self.infcx.type_is_copy_modulo_regions(self.param_env, ty, span) { + let ccx = ConstCx::new_with_param_env( + tcx, + self.mir_def_id, + body, + self.param_env, + ); // To determine if `const_in_array_repeat_expressions` feature gate should // be mentioned, need to check if the rvalue is promotable. let should_suggest = should_suggest_const_in_array_repeat_expressions_attribute( - tcx, - self.mir_def_id, - body, - operand, + &ccx, operand, ); debug!("check_rvalue: should_suggest={:?}", should_suggest); diff --git a/src/librustc_mir/interpret/eval_context.rs b/src/librustc_mir/interpret/eval_context.rs index ae4ad49fe667f..0e06f5162f8ce 100644 --- a/src/librustc_mir/interpret/eval_context.rs +++ b/src/librustc_mir/interpret/eval_context.rs @@ -628,35 +628,30 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { let frame = M::init_frame_extra(self, pre_frame)?; self.stack_mut().push(frame); - // don't allocate at all for trivial constants - if body.local_decls.len() > 1 { - // Locals are initially uninitialized. - let dummy = LocalState { value: LocalValue::Uninitialized, layout: Cell::new(None) }; - let mut locals = IndexVec::from_elem(dummy, &body.local_decls); - // Return place is handled specially by the `eval_place` functions, and the - // entry in `locals` should never be used. Make it dead, to be sure. - locals[mir::RETURN_PLACE].value = LocalValue::Dead; - // Now mark those locals as dead that we do not want to initialize - match self.tcx.def_kind(instance.def_id()) { - // statics and constants don't have `Storage*` statements, no need to look for them - // - // FIXME: The above is likely untrue. See - // . Is it - // okay to ignore `StorageDead`/`StorageLive` annotations during CTFE? - Some(DefKind::Static | DefKind::Const | DefKind::AssocConst) => {} - _ => { - // Mark locals that use `Storage*` annotations as dead on function entry. - let always_live = AlwaysLiveLocals::new(self.body()); - for local in locals.indices() { - if !always_live.contains(local) { - locals[local].value = LocalValue::Dead; - } + // Locals are initially uninitialized. + let dummy = LocalState { value: LocalValue::Uninitialized, layout: Cell::new(None) }; + let mut locals = IndexVec::from_elem(dummy, &body.local_decls); + + // Now mark those locals as dead that we do not want to initialize + match self.tcx.def_kind(instance.def_id()) { + // statics and constants don't have `Storage*` statements, no need to look for them + // + // FIXME: The above is likely untrue. See + // . Is it + // okay to ignore `StorageDead`/`StorageLive` annotations during CTFE? + Some(DefKind::Static | DefKind::Const | DefKind::AssocConst) => {} + _ => { + // Mark locals that use `Storage*` annotations as dead on function entry. + let always_live = AlwaysLiveLocals::new(self.body()); + for local in locals.indices() { + if !always_live.contains(local) { + locals[local].value = LocalValue::Dead; } } } - // done - self.frame_mut().locals = locals; } + // done + self.frame_mut().locals = locals; M::after_stack_push(self)?; info!("ENTERING({}) {}", self.frame_idx(), self.frame().instance); @@ -734,6 +729,17 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { let frame = self.stack_mut().pop().expect("tried to pop a stack frame, but there were none"); + if !unwinding { + // Copy the return value to the caller's stack frame. + if let Some(return_place) = frame.return_place { + let op = self.access_local(&frame, mir::RETURN_PLACE, None)?; + self.copy_op_transmute(op, return_place)?; + self.dump_place(*return_place); + } else { + throw_ub!(Unreachable); + } + } + // Now where do we jump next? // Usually we want to clean up (deallocate locals), but in a few rare cases we don't. @@ -759,7 +765,6 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { self.deallocate_local(local.value)?; } - let return_place = frame.return_place; if M::after_stack_pop(self, frame, unwinding)? == StackPopJump::NoJump { // The hook already did everything. // We want to skip the `info!` below, hence early return. @@ -772,25 +777,6 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { self.unwind_to_block(unwind); } else { // Follow the normal return edge. - // Validate the return value. Do this after deallocating so that we catch dangling - // references. - if let Some(return_place) = return_place { - if M::enforce_validity(self) { - // Data got changed, better make sure it matches the type! - // It is still possible that the return place held invalid data while - // the function is running, but that's okay because nobody could have - // accessed that same data from the "outside" to observe any broken - // invariant -- that is, unless a function somehow has a ptr to - // its return place... but the way MIR is currently generated, the - // return place is always a local and then this cannot happen. - self.validate_operand(self.place_to_op(return_place)?)?; - } - } else { - // Uh, that shouldn't happen... the function did not intend to return - throw_ub!(Unreachable); - } - - // Jump to new block -- *after* validation so that the spans make more sense. if let Some(ret) = next_block { self.return_to_block(ret)?; } diff --git a/src/librustc_mir/interpret/operand.rs b/src/librustc_mir/interpret/operand.rs index 31e6fbdceee4a..8188106b5f187 100644 --- a/src/librustc_mir/interpret/operand.rs +++ b/src/librustc_mir/interpret/operand.rs @@ -419,7 +419,6 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { local: mir::Local, layout: Option>, ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { - assert_ne!(local, mir::RETURN_PLACE); let layout = self.layout_of_local(frame, local, layout)?; let op = if layout.is_zst() { // Do not read from ZST, they might not be initialized @@ -454,16 +453,11 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { place: mir::Place<'tcx>, layout: Option>, ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { - let base_op = match place.local { - mir::RETURN_PLACE => throw_ub!(ReadFromReturnPlace), - local => { - // Do not use the layout passed in as argument if the base we are looking at - // here is not the entire place. - let layout = if place.projection.is_empty() { layout } else { None }; - - self.access_local(self.frame(), local, layout)? - } - }; + // Do not use the layout passed in as argument if the base we are looking at + // here is not the entire place. + let layout = if place.projection.is_empty() { layout } else { None }; + + let base_op = self.access_local(self.frame(), place.local, layout)?; let op = place .projection diff --git a/src/librustc_mir/interpret/place.rs b/src/librustc_mir/interpret/place.rs index 348958ee6c59a..ba17a0b482afc 100644 --- a/src/librustc_mir/interpret/place.rs +++ b/src/librustc_mir/interpret/place.rs @@ -135,12 +135,6 @@ impl MemPlace { MemPlace { ptr, align, meta: MemPlaceMeta::None } } - /// Produces a Place that will error if attempted to be read from or written to - #[inline(always)] - fn null(cx: &impl HasDataLayout) -> Self { - Self::from_scalar_ptr(Scalar::null_ptr(cx), Align::from_bytes(1).unwrap()) - } - #[inline(always)] pub fn from_ptr(ptr: Pointer, align: Align) -> Self { Self::from_scalar_ptr(ptr.into(), align) @@ -260,12 +254,6 @@ impl<'tcx, Tag: ::std::fmt::Debug + Copy> OpTy<'tcx, Tag> { } impl Place { - /// Produces a Place that will error if attempted to be read from or written to - #[inline(always)] - fn null(cx: &impl HasDataLayout) -> Self { - Place::Ptr(MemPlace::null(cx)) - } - #[inline] pub fn assert_mem_place(self) -> MemPlace { match self { @@ -641,35 +629,10 @@ where &mut self, place: mir::Place<'tcx>, ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> { - let mut place_ty = match place.local { - mir::RETURN_PLACE => { - // `return_place` has the *caller* layout, but we want to use our - // `layout to verify our assumption. The caller will validate - // their layout on return. - PlaceTy { - place: match self.frame().return_place { - Some(p) => *p, - // Even if we don't have a return place, we sometimes need to - // create this place, but any attempt to read from / write to it - // (even a ZST read/write) needs to error, so let us make this - // a NULL place. - // - // FIXME: Ideally we'd make sure that the place projections also - // bail out. - None => Place::null(&*self), - }, - layout: self.layout_of( - self.subst_from_current_frame_and_normalize_erasing_regions( - self.frame().body.return_ty(), - ), - )?, - } - } - local => PlaceTy { - // This works even for dead/uninitialized locals; we check further when writing - place: Place::Local { frame: self.frame_idx(), local }, - layout: self.layout_of_local(self.frame(), local, None)?, - }, + let mut place_ty = PlaceTy { + // This works even for dead/uninitialized locals; we check further when writing + place: Place::Local { frame: self.frame_idx(), local: place.local }, + layout: self.layout_of_local(self.frame(), place.local, None)?, }; for elem in place.projection.iter() { diff --git a/src/librustc_mir/interpret/terminator.rs b/src/librustc_mir/interpret/terminator.rs index 7157225e5c9bb..777a4381cda72 100644 --- a/src/librustc_mir/interpret/terminator.rs +++ b/src/librustc_mir/interpret/terminator.rs @@ -19,7 +19,6 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { use rustc_middle::mir::TerminatorKind::*; match terminator.kind { Return => { - self.frame().return_place.map(|r| self.dump_place(*r)); self.pop_stack_frame(/* unwinding */ false)? } diff --git a/src/librustc_mir/transform/check_consts/mod.rs b/src/librustc_mir/transform/check_consts/mod.rs index 8aac5c791ecd2..a630c56ee977f 100644 --- a/src/librustc_mir/transform/check_consts/mod.rs +++ b/src/librustc_mir/transform/check_consts/mod.rs @@ -20,7 +20,7 @@ pub mod validation; /// Information about the item currently being const-checked, as well as a reference to the global /// context. -pub struct Item<'mir, 'tcx> { +pub struct ConstCx<'mir, 'tcx> { pub body: &'mir mir::Body<'tcx>, pub tcx: TyCtxt<'tcx>, pub def_id: DefId, @@ -28,12 +28,21 @@ pub struct Item<'mir, 'tcx> { pub const_kind: Option, } -impl Item<'mir, 'tcx> { +impl ConstCx<'mir, 'tcx> { pub fn new(tcx: TyCtxt<'tcx>, def_id: DefId, body: &'mir mir::Body<'tcx>) -> Self { let param_env = tcx.param_env(def_id); + Self::new_with_param_env(tcx, def_id, body, param_env) + } + + pub fn new_with_param_env( + tcx: TyCtxt<'tcx>, + def_id: DefId, + body: &'mir mir::Body<'tcx>, + param_env: ty::ParamEnv<'tcx>, + ) -> Self { let const_kind = ConstKind::for_item(tcx, def_id); - Item { body, tcx, def_id, param_env, const_kind } + ConstCx { body, tcx, def_id, param_env, const_kind } } /// Returns the kind of const context this `Item` represents (`const`, `static`, etc.). diff --git a/src/librustc_mir/transform/check_consts/ops.rs b/src/librustc_mir/transform/check_consts/ops.rs index c4b94b70938d3..60eb51f7ccabf 100644 --- a/src/librustc_mir/transform/check_consts/ops.rs +++ b/src/librustc_mir/transform/check_consts/ops.rs @@ -7,7 +7,7 @@ use rustc_session::parse::feature_err; use rustc_span::symbol::sym; use rustc_span::{Span, Symbol}; -use super::{ConstKind, Item}; +use super::{ConstCx, ConstKind}; /// An operation that is not *always* allowed in a const context. pub trait NonConstOp: std::fmt::Debug { @@ -27,19 +27,19 @@ pub trait NonConstOp: std::fmt::Debug { /// /// By default, it returns `true` if and only if this operation has a corresponding feature /// gate and that gate is enabled. - fn is_allowed_in_item(&self, item: &Item<'_, '_>) -> bool { - Self::feature_gate().map_or(false, |gate| item.tcx.features().enabled(gate)) + fn is_allowed_in_item(&self, ccx: &ConstCx<'_, '_>) -> bool { + Self::feature_gate().map_or(false, |gate| ccx.tcx.features().enabled(gate)) } - fn emit_error(&self, item: &Item<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { let mut err = struct_span_err!( - item.tcx.sess, + ccx.tcx.sess, span, E0019, "{} contains unimplemented expression type", - item.const_kind() + ccx.const_kind() ); - if item.tcx.sess.teach(&err.get_code().unwrap()) { + if ccx.tcx.sess.teach(&err.get_code().unwrap()) { err.note( "A function call isn't allowed in the const's initialization expression \ because the expression's value must be known at compile-time.", @@ -66,9 +66,9 @@ impl NonConstOp for Downcast { #[derive(Debug)] pub struct FnCallIndirect; impl NonConstOp for FnCallIndirect { - fn emit_error(&self, item: &Item<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { let mut err = - item.tcx.sess.struct_span_err(span, "function pointers are not allowed in const fn"); + ccx.tcx.sess.struct_span_err(span, "function pointers are not allowed in const fn"); err.emit(); } } @@ -77,14 +77,14 @@ impl NonConstOp for FnCallIndirect { #[derive(Debug)] pub struct FnCallNonConst(pub DefId); impl NonConstOp for FnCallNonConst { - fn emit_error(&self, item: &Item<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { let mut err = struct_span_err!( - item.tcx.sess, + ccx.tcx.sess, span, E0015, "calls in {}s are limited to constant functions, \ tuple structs and tuple variants", - item.const_kind(), + ccx.const_kind(), ); err.emit(); } @@ -96,12 +96,12 @@ impl NonConstOp for FnCallNonConst { #[derive(Debug)] pub struct FnCallUnstable(pub DefId, pub Symbol); impl NonConstOp for FnCallUnstable { - fn emit_error(&self, item: &Item<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { let FnCallUnstable(def_id, feature) = *self; - let mut err = item.tcx.sess.struct_span_err( + let mut err = ccx.tcx.sess.struct_span_err( span, - &format!("`{}` is not yet stable as a const fn", item.tcx.def_path_str(def_id)), + &format!("`{}` is not yet stable as a const fn", ccx.tcx.def_path_str(def_id)), ); if nightly_options::is_nightly_build() { err.help(&format!("add `#![feature({})]` to the crate attributes to enable", feature)); @@ -113,16 +113,16 @@ impl NonConstOp for FnCallUnstable { #[derive(Debug)] pub struct HeapAllocation; impl NonConstOp for HeapAllocation { - fn emit_error(&self, item: &Item<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { let mut err = struct_span_err!( - item.tcx.sess, + ccx.tcx.sess, span, E0010, "allocations are not allowed in {}s", - item.const_kind() + ccx.const_kind() ); - err.span_label(span, format!("allocation not allowed in {}s", item.const_kind())); - if item.tcx.sess.teach(&err.get_code().unwrap()) { + err.span_label(span, format!("allocation not allowed in {}s", ccx.const_kind())); + if ccx.tcx.sess.teach(&err.get_code().unwrap()) { err.note( "The value of statics and constants must be known at compile time, \ and they live for the entire lifetime of a program. Creating a boxed \ @@ -141,9 +141,9 @@ impl NonConstOp for IfOrMatch { Some(sym::const_if_match) } - fn emit_error(&self, item: &Item<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { // This should be caught by the HIR const-checker. - item.tcx.sess.delay_span_bug(span, "complex control flow is forbidden in a const context"); + ccx.tcx.sess.delay_span_bug(span, "complex control flow is forbidden in a const context"); } } @@ -154,14 +154,14 @@ impl NonConstOp for InlineAsm {} #[derive(Debug)] pub struct LiveDrop; impl NonConstOp for LiveDrop { - fn emit_error(&self, item: &Item<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { struct_span_err!( - item.tcx.sess, + ccx.tcx.sess, span, E0493, "destructors cannot be evaluated at compile-time" ) - .span_label(span, format!("{}s cannot evaluate destructors", item.const_kind())) + .span_label(span, format!("{}s cannot evaluate destructors", ccx.const_kind())) .emit(); } } @@ -173,18 +173,18 @@ impl NonConstOp for Loop { Some(sym::const_loop) } - fn emit_error(&self, item: &Item<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { // This should be caught by the HIR const-checker. - item.tcx.sess.delay_span_bug(span, "complex control flow is forbidden in a const context"); + ccx.tcx.sess.delay_span_bug(span, "complex control flow is forbidden in a const context"); } } #[derive(Debug)] pub struct CellBorrow; impl NonConstOp for CellBorrow { - fn emit_error(&self, item: &Item<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { struct_span_err!( - item.tcx.sess, + ccx.tcx.sess, span, E0492, "cannot borrow a constant which may contain \ @@ -201,19 +201,19 @@ impl NonConstOp for MutBorrow { Some(sym::const_mut_refs) } - fn emit_error(&self, item: &Item<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { let mut err = feature_err( - &item.tcx.sess.parse_sess, + &ccx.tcx.sess.parse_sess, sym::const_mut_refs, span, &format!( "references in {}s may only refer \ to immutable values", - item.const_kind() + ccx.const_kind() ), ); - err.span_label(span, format!("{}s require immutable values", item.const_kind())); - if item.tcx.sess.teach(&err.get_code().unwrap()) { + err.span_label(span, format!("{}s require immutable values", ccx.const_kind())); + if ccx.tcx.sess.teach(&err.get_code().unwrap()) { err.note( "References in statics and constants may only refer \ to immutable values.\n\n\ @@ -236,12 +236,12 @@ impl NonConstOp for MutAddressOf { Some(sym::const_mut_refs) } - fn emit_error(&self, item: &Item<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { feature_err( - &item.tcx.sess.parse_sess, + &ccx.tcx.sess.parse_sess, sym::const_mut_refs, span, - &format!("`&raw mut` is not allowed in {}s", item.const_kind()), + &format!("`&raw mut` is not allowed in {}s", ccx.const_kind()), ) .emit(); } @@ -262,12 +262,12 @@ impl NonConstOp for Panic { Some(sym::const_panic) } - fn emit_error(&self, item: &Item<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { feature_err( - &item.tcx.sess.parse_sess, + &ccx.tcx.sess.parse_sess, sym::const_panic, span, - &format!("panicking in {}s is unstable", item.const_kind()), + &format!("panicking in {}s is unstable", ccx.const_kind()), ) .emit(); } @@ -280,12 +280,12 @@ impl NonConstOp for RawPtrComparison { Some(sym::const_compare_raw_pointers) } - fn emit_error(&self, item: &Item<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { feature_err( - &item.tcx.sess.parse_sess, + &ccx.tcx.sess.parse_sess, sym::const_compare_raw_pointers, span, - &format!("comparing raw pointers inside {}", item.const_kind()), + &format!("comparing raw pointers inside {}", ccx.const_kind()), ) .emit(); } @@ -298,12 +298,12 @@ impl NonConstOp for RawPtrDeref { Some(sym::const_raw_ptr_deref) } - fn emit_error(&self, item: &Item<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { feature_err( - &item.tcx.sess.parse_sess, + &ccx.tcx.sess.parse_sess, sym::const_raw_ptr_deref, span, - &format!("dereferencing raw pointers in {}s is unstable", item.const_kind(),), + &format!("dereferencing raw pointers in {}s is unstable", ccx.const_kind(),), ) .emit(); } @@ -316,12 +316,12 @@ impl NonConstOp for RawPtrToIntCast { Some(sym::const_raw_ptr_to_usize_cast) } - fn emit_error(&self, item: &Item<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { feature_err( - &item.tcx.sess.parse_sess, + &ccx.tcx.sess.parse_sess, sym::const_raw_ptr_to_usize_cast, span, - &format!("casting pointers to integers in {}s is unstable", item.const_kind(),), + &format!("casting pointers to integers in {}s is unstable", ccx.const_kind(),), ) .emit(); } @@ -331,22 +331,22 @@ impl NonConstOp for RawPtrToIntCast { #[derive(Debug)] pub struct StaticAccess; impl NonConstOp for StaticAccess { - fn is_allowed_in_item(&self, item: &Item<'_, '_>) -> bool { - item.const_kind().is_static() + fn is_allowed_in_item(&self, ccx: &ConstCx<'_, '_>) -> bool { + ccx.const_kind().is_static() } - fn emit_error(&self, item: &Item<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { let mut err = struct_span_err!( - item.tcx.sess, + ccx.tcx.sess, span, E0013, "{}s cannot refer to statics", - item.const_kind() + ccx.const_kind() ); err.help( "consider extracting the value of the `static` to a `const`, and referring to that", ); - if item.tcx.sess.teach(&err.get_code().unwrap()) { + if ccx.tcx.sess.teach(&err.get_code().unwrap()) { err.note( "`static` and `const` variables can refer to other `const` variables. \ A `const` variable, however, cannot refer to a `static` variable.", @@ -363,9 +363,9 @@ pub struct ThreadLocalAccess; impl NonConstOp for ThreadLocalAccess { const IS_SUPPORTED_IN_MIRI: bool = false; - fn emit_error(&self, item: &Item<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { struct_span_err!( - item.tcx.sess, + ccx.tcx.sess, span, E0625, "thread-local statics cannot be \ @@ -378,19 +378,19 @@ impl NonConstOp for ThreadLocalAccess { #[derive(Debug)] pub struct UnionAccess; impl NonConstOp for UnionAccess { - fn is_allowed_in_item(&self, item: &Item<'_, '_>) -> bool { + fn is_allowed_in_item(&self, ccx: &ConstCx<'_, '_>) -> bool { // Union accesses are stable in all contexts except `const fn`. - item.const_kind() != ConstKind::ConstFn - || item.tcx.features().enabled(Self::feature_gate().unwrap()) + ccx.const_kind() != ConstKind::ConstFn + || ccx.tcx.features().enabled(Self::feature_gate().unwrap()) } fn feature_gate() -> Option { Some(sym::const_fn_union) } - fn emit_error(&self, item: &Item<'_, '_>, span: Span) { + fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) { feature_err( - &item.tcx.sess.parse_sess, + &ccx.tcx.sess.parse_sess, sym::const_fn_union, span, "unions in const fn are unstable", diff --git a/src/librustc_mir/transform/check_consts/qualifs.rs b/src/librustc_mir/transform/check_consts/qualifs.rs index 5f50e073e29a6..f82f06599b74a 100644 --- a/src/librustc_mir/transform/check_consts/qualifs.rs +++ b/src/librustc_mir/transform/check_consts/qualifs.rs @@ -6,7 +6,7 @@ use rustc_middle::mir::*; use rustc_middle::ty::{self, AdtDef, Ty}; use rustc_span::DUMMY_SP; -use super::Item as ConstCx; +use super::ConstCx; pub fn in_any_value_of_ty(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> ConstQualifs { ConstQualifs { diff --git a/src/librustc_mir/transform/check_consts/resolver.rs b/src/librustc_mir/transform/check_consts/resolver.rs index 6ae314b973ffe..a81d7a23be2fb 100644 --- a/src/librustc_mir/transform/check_consts/resolver.rs +++ b/src/librustc_mir/transform/check_consts/resolver.rs @@ -8,7 +8,7 @@ use rustc_middle::mir::{self, BasicBlock, Local, Location}; use std::marker::PhantomData; -use super::{qualifs, Item, Qualif}; +use super::{qualifs, ConstCx, Qualif}; use crate::dataflow; /// A `Visitor` that propagates qualifs between locals. This defines the transfer function of @@ -18,7 +18,7 @@ use crate::dataflow; /// the `MaybeMutBorrowedLocals` dataflow pass to see if a `Local` may have become qualified via /// an indirect assignment or function call. struct TransferFunction<'a, 'mir, 'tcx, Q> { - item: &'a Item<'mir, 'tcx>, + ccx: &'a ConstCx<'mir, 'tcx>, qualifs_per_local: &'a mut BitSet, _qualif: PhantomData, @@ -28,16 +28,16 @@ impl TransferFunction<'a, 'mir, 'tcx, Q> where Q: Qualif, { - fn new(item: &'a Item<'mir, 'tcx>, qualifs_per_local: &'a mut BitSet) -> Self { - TransferFunction { item, qualifs_per_local, _qualif: PhantomData } + fn new(ccx: &'a ConstCx<'mir, 'tcx>, qualifs_per_local: &'a mut BitSet) -> Self { + TransferFunction { ccx, qualifs_per_local, _qualif: PhantomData } } fn initialize_state(&mut self) { self.qualifs_per_local.clear(); - for arg in self.item.body.args_iter() { - let arg_ty = self.item.body.local_decls[arg].ty; - if Q::in_any_value_of_ty(self.item, arg_ty) { + for arg in self.ccx.body.args_iter() { + let arg_ty = self.ccx.body.local_decls[arg].ty; + if Q::in_any_value_of_ty(self.ccx, arg_ty) { self.qualifs_per_local.insert(arg); } } @@ -72,8 +72,8 @@ where ) { // We cannot reason about another function's internals, so use conservative type-based // qualification for the result of a function call. - let return_ty = return_place.ty(self.item.body, self.item.tcx).ty; - let qualif = Q::in_any_value_of_ty(self.item, return_ty); + let return_ty = return_place.ty(self.ccx.body, self.ccx.tcx).ty; + let qualif = Q::in_any_value_of_ty(self.ccx, return_ty); if !return_place.is_indirect() { self.assign_qualif_direct(&return_place, qualif); @@ -108,7 +108,7 @@ where location: Location, ) { let qualif = qualifs::in_rvalue::( - self.item, + self.ccx, &mut |l| self.qualifs_per_local.contains(l), rvalue, ); @@ -127,7 +127,7 @@ where if let mir::TerminatorKind::DropAndReplace { value, location: dest, .. } = kind { let qualif = qualifs::in_operand::( - self.item, + self.ccx, &mut |l| self.qualifs_per_local.contains(l), value, ); @@ -145,7 +145,7 @@ where /// The dataflow analysis used to propagate qualifs on arbitrary CFGs. pub(super) struct FlowSensitiveAnalysis<'a, 'mir, 'tcx, Q> { - item: &'a Item<'mir, 'tcx>, + ccx: &'a ConstCx<'mir, 'tcx>, _qualif: PhantomData, } @@ -153,15 +153,15 @@ impl<'a, 'mir, 'tcx, Q> FlowSensitiveAnalysis<'a, 'mir, 'tcx, Q> where Q: Qualif, { - pub(super) fn new(_: Q, item: &'a Item<'mir, 'tcx>) -> Self { - FlowSensitiveAnalysis { item, _qualif: PhantomData } + pub(super) fn new(_: Q, ccx: &'a ConstCx<'mir, 'tcx>) -> Self { + FlowSensitiveAnalysis { ccx, _qualif: PhantomData } } fn transfer_function( &self, state: &'a mut BitSet, ) -> TransferFunction<'a, 'mir, 'tcx, Q> { - TransferFunction::::new(self.item, state) + TransferFunction::::new(self.ccx, state) } } diff --git a/src/librustc_mir/transform/check_consts/validation.rs b/src/librustc_mir/transform/check_consts/validation.rs index ce0cdc2bac07b..45d8e1d08b721 100644 --- a/src/librustc_mir/transform/check_consts/validation.rs +++ b/src/librustc_mir/transform/check_consts/validation.rs @@ -20,7 +20,7 @@ use std::ops::Deref; use super::ops::{self, NonConstOp}; use super::qualifs::{self, HasMutInterior, NeedsDrop}; use super::resolver::FlowSensitiveAnalysis; -use super::{is_lang_panic_fn, ConstKind, Item, Qualif}; +use super::{is_lang_panic_fn, ConstCx, ConstKind, Qualif}; use crate::const_eval::{is_const_fn, is_unstable_const_fn}; use crate::dataflow::MaybeMutBorrowedLocals; use crate::dataflow::{self, Analysis}; @@ -37,15 +37,15 @@ struct QualifCursor<'a, 'mir, 'tcx, Q: Qualif> { } impl QualifCursor<'a, 'mir, 'tcx, Q> { - pub fn new(q: Q, item: &'a Item<'mir, 'tcx>) -> Self { - let cursor = FlowSensitiveAnalysis::new(q, item) - .into_engine(item.tcx, item.body, item.def_id) + pub fn new(q: Q, ccx: &'a ConstCx<'mir, 'tcx>) -> Self { + let cursor = FlowSensitiveAnalysis::new(q, ccx) + .into_engine(ccx.tcx, ccx.body, ccx.def_id) .iterate_to_fixpoint() - .into_results_cursor(item.body); + .into_results_cursor(ccx.body); - let mut in_any_value_of_ty = BitSet::new_empty(item.body.local_decls.len()); - for (local, decl) in item.body.local_decls.iter_enumerated() { - if Q::in_any_value_of_ty(item, decl.ty) { + let mut in_any_value_of_ty = BitSet::new_empty(ccx.body.local_decls.len()); + for (local, decl) in ccx.body.local_decls.iter_enumerated() { + if Q::in_any_value_of_ty(ccx, decl.ty) { in_any_value_of_ty.insert(local); } } @@ -91,12 +91,12 @@ impl Qualifs<'a, 'mir, 'tcx> { || self.indirectly_mutable(local, location) } - fn in_return_place(&mut self, item: &Item<'_, 'tcx>) -> ConstQualifs { + fn in_return_place(&mut self, ccx: &ConstCx<'_, 'tcx>) -> ConstQualifs { // Find the `Return` terminator if one exists. // // If no `Return` terminator exists, this MIR is divergent. Just return the conservative // qualifs for the return type. - let return_block = item + let return_block = ccx .body .basic_blocks() .iter_enumerated() @@ -107,11 +107,11 @@ impl Qualifs<'a, 'mir, 'tcx> { .map(|(bb, _)| bb); let return_block = match return_block { - None => return qualifs::in_any_value_of_ty(item, item.body.return_ty()), + None => return qualifs::in_any_value_of_ty(ccx, ccx.body.return_ty()), Some(bb) => bb, }; - let return_loc = item.body.terminator_loc(return_block); + let return_loc = ccx.body.terminator_loc(return_block); ConstQualifs { needs_drop: self.needs_drop(RETURN_PLACE, return_loc), @@ -121,7 +121,7 @@ impl Qualifs<'a, 'mir, 'tcx> { } pub struct Validator<'a, 'mir, 'tcx> { - item: &'a Item<'mir, 'tcx>, + ccx: &'a ConstCx<'mir, 'tcx>, qualifs: Qualifs<'a, 'mir, 'tcx>, /// The span of the current statement. @@ -129,19 +129,19 @@ pub struct Validator<'a, 'mir, 'tcx> { } impl Deref for Validator<'_, 'mir, 'tcx> { - type Target = Item<'mir, 'tcx>; + type Target = ConstCx<'mir, 'tcx>; fn deref(&self) -> &Self::Target { - &self.item + &self.ccx } } impl Validator<'a, 'mir, 'tcx> { - pub fn new(item: &'a Item<'mir, 'tcx>) -> Self { - let Item { tcx, body, def_id, param_env, .. } = *item; + pub fn new(ccx: &'a ConstCx<'mir, 'tcx>) -> Self { + let ConstCx { tcx, body, def_id, param_env, .. } = *ccx; - let needs_drop = QualifCursor::new(NeedsDrop, item); - let has_mut_interior = QualifCursor::new(HasMutInterior, item); + let needs_drop = QualifCursor::new(NeedsDrop, ccx); + let has_mut_interior = QualifCursor::new(HasMutInterior, ccx); // We can use `unsound_ignore_borrow_on_drop` here because custom drop impls are not // allowed in a const. @@ -156,11 +156,11 @@ impl Validator<'a, 'mir, 'tcx> { let qualifs = Qualifs { needs_drop, has_mut_interior, indirectly_mutable }; - Validator { span: item.body.span, item, qualifs } + Validator { span: ccx.body.span, ccx, qualifs } } pub fn check_body(&mut self) { - let Item { tcx, body, def_id, const_kind, .. } = *self.item; + let ConstCx { tcx, body, def_id, const_kind, .. } = *self.ccx; let use_min_const_fn_checks = (const_kind == Some(ConstKind::ConstFn) && crate::const_eval::is_min_const_fn(tcx, def_id)) @@ -175,7 +175,7 @@ impl Validator<'a, 'mir, 'tcx> { } } - check_short_circuiting_in_const_local(self.item); + check_short_circuiting_in_const_local(self.ccx); if body.is_cfg_cyclic() { // We can't provide a good span for the error here, but this should be caught by the @@ -196,7 +196,7 @@ impl Validator<'a, 'mir, 'tcx> { } pub fn qualifs_in_return_place(&mut self) -> ConstQualifs { - self.qualifs.in_return_place(self.item) + self.qualifs.in_return_place(self.ccx) } /// Emits an error at the given `span` if an expression cannot be evaluated in the current @@ -344,7 +344,7 @@ impl Visitor<'tcx> for Validator<'_, 'mir, 'tcx> { Rvalue::Ref(_, BorrowKind::Shared | BorrowKind::Shallow, ref place) | Rvalue::AddressOf(Mutability::Not, ref place) => { let borrowed_place_has_mut_interior = qualifs::in_place::( - &self.item, + &self.ccx, &mut |local| self.qualifs.has_mut_interior(local, location), place.as_ref(), ); @@ -608,8 +608,8 @@ fn error_min_const_fn_violation(tcx: TyCtxt<'_>, span: Span, msg: Cow<'_, str>) .emit(); } -fn check_short_circuiting_in_const_local(item: &Item<'_, 'tcx>) { - let body = item.body; +fn check_short_circuiting_in_const_local(ccx: &ConstCx<'_, 'tcx>) { + let body = ccx.body; if body.control_flow_destroyed.is_empty() { return; @@ -618,12 +618,12 @@ fn check_short_circuiting_in_const_local(item: &Item<'_, 'tcx>) { let mut locals = body.vars_iter(); if let Some(local) = locals.next() { let span = body.local_decls[local].source_info.span; - let mut error = item.tcx.sess.struct_span_err( + let mut error = ccx.tcx.sess.struct_span_err( span, &format!( "new features like let bindings are not permitted in {}s \ which also use short circuiting operators", - item.const_kind(), + ccx.const_kind(), ), ); for (span, kind) in body.control_flow_destroyed.iter() { diff --git a/src/librustc_mir/transform/const_prop.rs b/src/librustc_mir/transform/const_prop.rs index 271c746aa0fef..beabdf7f784f8 100644 --- a/src/librustc_mir/transform/const_prop.rs +++ b/src/librustc_mir/transform/const_prop.rs @@ -330,7 +330,6 @@ struct ConstPropagator<'mir, 'tcx> { // by accessing them through `ecx` instead. source_scopes: IndexVec, local_decls: IndexVec>, - ret: Option>, // Because we have `MutVisitor` we can't obtain the `SourceInfo` from a `Location`. So we store // the last known `SourceInfo` here and just keep revisiting it. source_info: Option, @@ -402,22 +401,19 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> { source_scopes: body.source_scopes.clone(), //FIXME(wesleywiser) we can't steal this because `Visitor::super_visit_body()` needs it local_decls: body.local_decls.clone(), - ret: ret.map(Into::into), source_info: None, } } fn get_const(&self, local: Local) -> Option> { - if local == RETURN_PLACE { - // Try to read the return place as an immediate so that if it is representable as a - // scalar, we can handle it as such, but otherwise, just return the value as is. - return match self.ret.map(|ret| self.ecx.try_read_immediate(ret)) { - Some(Ok(Ok(imm))) => Some(imm.into()), - _ => self.ret, - }; - } + let op = self.ecx.access_local(self.ecx.frame(), local, None).ok(); - self.ecx.access_local(self.ecx.frame(), local, None).ok() + // Try to read the local as an immediate so that if it is representable as a scalar, we can + // handle it as such, but otherwise, just return the value as is. + match op.map(|ret| self.ecx.try_read_immediate(ret)) { + Some(Ok(Ok(imm))) => Some(imm.into()), + _ => op, + } } fn remove_const(&mut self, local: Local) { diff --git a/src/librustc_mir/transform/mod.rs b/src/librustc_mir/transform/mod.rs index b7b67f36ae42f..a87955274a779 100644 --- a/src/librustc_mir/transform/mod.rs +++ b/src/librustc_mir/transform/mod.rs @@ -194,10 +194,10 @@ fn mir_const_qualif(tcx: TyCtxt<'_>, def_id: DefId) -> ConstQualifs { return Default::default(); } - let item = - check_consts::Item { body, tcx, def_id, const_kind, param_env: tcx.param_env(def_id) }; + let ccx = + check_consts::ConstCx { body, tcx, def_id, const_kind, param_env: tcx.param_env(def_id) }; - let mut validator = check_consts::validation::Validator::new(&item); + let mut validator = check_consts::validation::Validator::new(&ccx); validator.check_body(); // We return the qualifs in the return place for every MIR body, even though it is only used diff --git a/src/librustc_mir/transform/promote_consts.rs b/src/librustc_mir/transform/promote_consts.rs index 20576d82b1c7c..998af4ba39006 100644 --- a/src/librustc_mir/transform/promote_consts.rs +++ b/src/librustc_mir/transform/promote_consts.rs @@ -30,7 +30,7 @@ use std::cell::Cell; use std::{cmp, iter, mem}; use crate::const_eval::{is_const_fn, is_unstable_const_fn}; -use crate::transform::check_consts::{is_lang_panic_fn, qualifs, ConstKind, Item}; +use crate::transform::check_consts::{is_lang_panic_fn, qualifs, ConstCx, ConstKind}; use crate::transform::{MirPass, MirSource}; /// A `MirPass` for promotion. @@ -62,9 +62,10 @@ impl<'tcx> MirPass<'tcx> for PromoteTemps<'tcx> { let def_id = src.def_id(); let mut rpo = traversal::reverse_postorder(body); - let (temps, all_candidates) = collect_temps_and_candidates(tcx, body, &mut rpo); + let ccx = ConstCx::new(tcx, def_id, body); + let (temps, all_candidates) = collect_temps_and_candidates(&ccx, &mut rpo); - let promotable_candidates = validate_candidates(tcx, body, def_id, &temps, &all_candidates); + let promotable_candidates = validate_candidates(&ccx, &temps, &all_candidates); let promoted = promote_candidates(def_id, body, tcx, temps, promotable_candidates); self.promoted_fragments.set(promoted); @@ -139,8 +140,7 @@ fn args_required_const(tcx: TyCtxt<'_>, def_id: DefId) -> Option> { } struct Collector<'a, 'tcx> { - tcx: TyCtxt<'tcx>, - body: &'a Body<'tcx>, + ccx: &'a ConstCx<'a, 'tcx>, temps: IndexVec, candidates: Vec, span: Span, @@ -150,7 +150,7 @@ impl<'tcx> Visitor<'tcx> for Collector<'_, 'tcx> { fn visit_local(&mut self, &index: &Local, context: PlaceContext, location: Location) { debug!("visit_local: index={:?} context={:?} location={:?}", index, context, location); // We're only interested in temporaries and the return place - match self.body.local_kind(index) { + match self.ccx.body.local_kind(index) { LocalKind::Temp | LocalKind::ReturnPointer => {} LocalKind::Arg | LocalKind::Var => return, } @@ -203,7 +203,7 @@ impl<'tcx> Visitor<'tcx> for Collector<'_, 'tcx> { Rvalue::Ref(..) => { self.candidates.push(Candidate::Ref(location)); } - Rvalue::Repeat(..) if self.tcx.features().const_in_array_repeat_expressions => { + Rvalue::Repeat(..) if self.ccx.tcx.features().const_in_array_repeat_expressions => { // FIXME(#49147) only promote the element when it isn't `Copy` // (so that code that can copy it at runtime is unaffected). self.candidates.push(Candidate::Repeat(location)); @@ -216,10 +216,10 @@ impl<'tcx> Visitor<'tcx> for Collector<'_, 'tcx> { self.super_terminator_kind(kind, location); if let TerminatorKind::Call { ref func, .. } = *kind { - if let ty::FnDef(def_id, _) = func.ty(self.body, self.tcx).kind { - let fn_sig = self.tcx.fn_sig(def_id); + if let ty::FnDef(def_id, _) = func.ty(self.ccx.body, self.ccx.tcx).kind { + let fn_sig = self.ccx.tcx.fn_sig(def_id); if let Abi::RustIntrinsic | Abi::PlatformIntrinsic = fn_sig.abi() { - let name = self.tcx.item_name(def_id); + let name = self.ccx.tcx.item_name(def_id); // FIXME(eddyb) use `#[rustc_args_required_const(2)]` for shuffles. if name.as_str().starts_with("simd_shuffle") { self.candidates.push(Candidate::Argument { bb: location.block, index: 2 }); @@ -228,7 +228,7 @@ impl<'tcx> Visitor<'tcx> for Collector<'_, 'tcx> { } } - if let Some(constant_args) = args_required_const(self.tcx, def_id) { + if let Some(constant_args) = args_required_const(self.ccx.tcx, def_id) { for index in constant_args { self.candidates.push(Candidate::Argument { bb: location.block, index }); } @@ -243,16 +243,14 @@ impl<'tcx> Visitor<'tcx> for Collector<'_, 'tcx> { } pub fn collect_temps_and_candidates( - tcx: TyCtxt<'tcx>, - body: &Body<'tcx>, + ccx: &ConstCx<'mir, 'tcx>, rpo: &mut ReversePostorder<'_, 'tcx>, ) -> (IndexVec, Vec) { let mut collector = Collector { - tcx, - body, - temps: IndexVec::from_elem(TempState::Undefined, &body.local_decls), + temps: IndexVec::from_elem(TempState::Undefined, &ccx.body.local_decls), candidates: vec![], - span: body.span, + span: ccx.body.span, + ccx, }; for (bb, data) in rpo { collector.visit_basic_block_data(bb, data); @@ -264,7 +262,7 @@ pub fn collect_temps_and_candidates( /// /// This wraps an `Item`, and has access to all fields of that `Item` via `Deref` coercion. struct Validator<'a, 'tcx> { - item: Item<'a, 'tcx>, + ccx: &'a ConstCx<'a, 'tcx>, temps: &'a IndexVec, /// Explicit promotion happens e.g. for constant arguments declared via @@ -277,10 +275,10 @@ struct Validator<'a, 'tcx> { } impl std::ops::Deref for Validator<'a, 'tcx> { - type Target = Item<'a, 'tcx>; + type Target = ConstCx<'a, 'tcx>; fn deref(&self) -> &Self::Target { - &self.item + &self.ccx } } @@ -413,7 +411,7 @@ impl<'tcx> Validator<'_, 'tcx> { let statement = &self.body[loc.block].statements[loc.statement_index]; match &statement.kind { StatementKind::Assign(box (_, rhs)) => qualifs::in_rvalue::( - &self.item, + &self.ccx, &mut |l| self.qualif_local::(l), rhs, ), @@ -430,7 +428,7 @@ impl<'tcx> Validator<'_, 'tcx> { match &terminator.kind { TerminatorKind::Call { .. } => { let return_ty = self.body.local_decls[local].ty; - Q::in_any_value_of_ty(&self.item, return_ty) + Q::in_any_value_of_ty(&self.ccx, return_ty) } kind => { span_bug!(terminator.source_info.span, "{:?} not promotable", kind); @@ -717,13 +715,11 @@ impl<'tcx> Validator<'_, 'tcx> { // FIXME(eddyb) remove the differences for promotability in `static`, `const`, `const fn`. pub fn validate_candidates( - tcx: TyCtxt<'tcx>, - body: &Body<'tcx>, - def_id: DefId, + ccx: &ConstCx<'_, '_>, temps: &IndexVec, candidates: &[Candidate], ) -> Vec { - let mut validator = Validator { item: Item::new(tcx, def_id, body), temps, explicit: false }; + let mut validator = Validator { ccx, temps, explicit: false }; candidates .iter() @@ -735,11 +731,23 @@ pub fn validate_candidates( // and `#[rustc_args_required_const]` arguments here. let is_promotable = validator.validate_candidate(candidate).is_ok(); + + // If we use explicit validation, we carry the risk of turning a legitimate run-time + // operation into a failing compile-time operation. Make sure that does not happen + // by asserting that there is no possible run-time behavior here in case promotion + // fails. + if validator.explicit && !is_promotable { + ccx.tcx.sess.delay_span_bug( + ccx.body.span, + "Explicit promotion requested, but failed to promote", + ); + } + match candidate { Candidate::Argument { bb, index } if !is_promotable => { - let span = body[bb].terminator().source_info.span; + let span = ccx.body[bb].terminator().source_info.span; let msg = format!("argument {} is required to be a constant", index + 1); - tcx.sess.span_err(span, &msg); + ccx.tcx.sess.span_err(span, &msg); } _ => (), } @@ -1147,22 +1155,19 @@ pub fn promote_candidates<'tcx>( /// Feature attribute should be suggested if `operand` can be promoted and the feature is not /// enabled. crate fn should_suggest_const_in_array_repeat_expressions_attribute<'tcx>( - tcx: TyCtxt<'tcx>, - mir_def_id: DefId, - body: &Body<'tcx>, + ccx: &ConstCx<'_, 'tcx>, operand: &Operand<'tcx>, ) -> bool { - let mut rpo = traversal::reverse_postorder(&body); - let (temps, _) = collect_temps_and_candidates(tcx, &body, &mut rpo); - let validator = - Validator { item: Item::new(tcx, mir_def_id, body), temps: &temps, explicit: false }; + let mut rpo = traversal::reverse_postorder(&ccx.body); + let (temps, _) = collect_temps_and_candidates(&ccx, &mut rpo); + let validator = Validator { ccx, temps: &temps, explicit: false }; let should_promote = validator.validate_operand(operand).is_ok(); - let feature_flag = tcx.features().const_in_array_repeat_expressions; + let feature_flag = validator.ccx.tcx.features().const_in_array_repeat_expressions; debug!( - "should_suggest_const_in_array_repeat_expressions_flag: mir_def_id={:?} \ + "should_suggest_const_in_array_repeat_expressions_flag: def_id={:?} \ should_promote={:?} feature_flag={:?}", - mir_def_id, should_promote, feature_flag + validator.ccx.def_id, should_promote, feature_flag ); should_promote && !feature_flag } diff --git a/src/test/codegen/consts.rs b/src/test/codegen/consts.rs index e53e75b339bef..ed93af2f993d3 100644 --- a/src/test/codegen/consts.rs +++ b/src/test/codegen/consts.rs @@ -10,11 +10,11 @@ // CHECK: @STATIC = {{.*}}, align 4 // This checks the constants from inline_enum_const -// CHECK: @alloc5 = {{.*}}, align 2 +// CHECK: @alloc7 = {{.*}}, align 2 // This checks the constants from {low,high}_align_const, they share the same // constant, but the alignment differs, so the higher one should be used -// CHECK: [[LOW_HIGH:@[0-9]+]] = {{.*}} getelementptr inbounds (<{ [8 x i8] }>, <{ [8 x i8] }>* @alloc15, i32 0, i32 0, i32 0), {{.*}} +// CHECK: [[LOW_HIGH:@[0-9]+]] = {{.*}} getelementptr inbounds (<{ [8 x i8] }>, <{ [8 x i8] }>* @alloc19, i32 0, i32 0, i32 0), {{.*}} #[derive(Copy, Clone)] // repr(i16) is required for the {low,high}_align_const test diff --git a/src/test/incremental/hashes/enum_constructors.rs b/src/test/incremental/hashes/enum_constructors.rs index 99c50f7e17356..2c07cbcb2054b 100644 --- a/src/test/incremental/hashes/enum_constructors.rs +++ b/src/test/incremental/hashes/enum_constructors.rs @@ -274,14 +274,14 @@ pub enum Clike2 { // Change constructor path (C-like) -------------------------------------- #[cfg(cfail1)] pub fn change_constructor_path_c_like() { - let _ = Clike::B; + let _x = Clike::B; } #[cfg(not(cfail1))] #[rustc_clean(cfg="cfail2", except="hir_owner_nodes,optimized_mir,mir_built,typeck_tables_of")] #[rustc_clean(cfg="cfail3")] pub fn change_constructor_path_c_like() { - let _ = Clike2::B; + let _x = Clike2::B; } @@ -289,14 +289,14 @@ pub fn change_constructor_path_c_like() { // Change constructor variant (C-like) -------------------------------------- #[cfg(cfail1)] pub fn change_constructor_variant_c_like() { - let _ = Clike::A; + let _x = Clike::A; } #[cfg(not(cfail1))] #[rustc_clean(cfg="cfail2", except="hir_owner_nodes,optimized_mir,mir_built")] #[rustc_clean(cfg="cfail3")] pub fn change_constructor_variant_c_like() { - let _ = Clike::C; + let _x = Clike::C; } diff --git a/src/test/mir-opt/const_allocation2/32bit/rustc.main.ConstProp.after.mir b/src/test/mir-opt/const_allocation2/32bit/rustc.main.ConstProp.after.mir index 4105d673218a0..efd14ea140fe8 100644 --- a/src/test/mir-opt/const_allocation2/32bit/rustc.main.ConstProp.after.mir +++ b/src/test/mir-opt/const_allocation2/32bit/rustc.main.ConstProp.after.mir @@ -30,41 +30,41 @@ fn main() -> () { } alloc0 (static: FOO, size: 8, align: 4) { - ╾alloc24+0╼ 03 00 00 00 │ ╾──╼.... + ╾alloc25+0╼ 03 00 00 00 │ ╾──╼.... } -alloc24 (size: 48, align: 4) { - 0x00 │ 00 00 00 00 __ __ __ __ ╾alloc9+0─╼ 00 00 00 00 │ ....░░░░╾──╼.... - 0x10 │ 00 00 00 00 __ __ __ __ ╾alloc14+0╼ 02 00 00 00 │ ....░░░░╾──╼.... - 0x20 │ 01 00 00 00 2a 00 00 00 ╾alloc22+0╼ 03 00 00 00 │ ....*...╾──╼.... +alloc25 (size: 48, align: 4) { + 0x00 │ 00 00 00 00 __ __ __ __ ╾alloc10+0╼ 00 00 00 00 │ ....░░░░╾──╼.... + 0x10 │ 00 00 00 00 __ __ __ __ ╾alloc15+0╼ 02 00 00 00 │ ....░░░░╾──╼.... + 0x20 │ 01 00 00 00 2a 00 00 00 ╾alloc23+0╼ 03 00 00 00 │ ....*...╾──╼.... } -alloc9 (size: 0, align: 4) {} +alloc10 (size: 0, align: 4) {} -alloc14 (size: 8, align: 4) { - ╾alloc12+0╼ ╾alloc13+0╼ │ ╾──╼╾──╼ +alloc15 (size: 8, align: 4) { + ╾alloc13+0╼ ╾alloc14+0╼ │ ╾──╼╾──╼ } -alloc12 (size: 1, align: 1) { +alloc13 (size: 1, align: 1) { 05 │ . } -alloc13 (size: 1, align: 1) { +alloc14 (size: 1, align: 1) { 06 │ . } -alloc22 (size: 12, align: 4) { - ╾alloc18+3╼ ╾alloc19+0╼ ╾alloc21+2╼ │ ╾──╼╾──╼╾──╼ +alloc23 (size: 12, align: 4) { + ╾alloc19+3╼ ╾alloc20+0╼ ╾alloc22+2╼ │ ╾──╼╾──╼╾──╼ } -alloc18 (size: 4, align: 1) { +alloc19 (size: 4, align: 1) { 2a 45 15 6f │ *E.o } -alloc19 (size: 1, align: 1) { +alloc20 (size: 1, align: 1) { 2a │ * } -alloc21 (size: 4, align: 1) { +alloc22 (size: 4, align: 1) { 2a 45 15 6f │ *E.o } diff --git a/src/test/mir-opt/const_allocation2/64bit/rustc.main.ConstProp.after.mir b/src/test/mir-opt/const_allocation2/64bit/rustc.main.ConstProp.after.mir index e61f0a8b69fa7..3b649ee7a24bd 100644 --- a/src/test/mir-opt/const_allocation2/64bit/rustc.main.ConstProp.after.mir +++ b/src/test/mir-opt/const_allocation2/64bit/rustc.main.ConstProp.after.mir @@ -30,44 +30,44 @@ fn main() -> () { } alloc0 (static: FOO, size: 16, align: 8) { - ╾──────alloc24+0──────╼ 03 00 00 00 00 00 00 00 │ ╾──────╼........ + ╾──────alloc25+0──────╼ 03 00 00 00 00 00 00 00 │ ╾──────╼........ } -alloc24 (size: 72, align: 8) { - 0x00 │ 00 00 00 00 __ __ __ __ ╾──────alloc9+0───────╼ │ ....░░░░╾──────╼ +alloc25 (size: 72, align: 8) { + 0x00 │ 00 00 00 00 __ __ __ __ ╾──────alloc10+0──────╼ │ ....░░░░╾──────╼ 0x10 │ 00 00 00 00 00 00 00 00 00 00 00 00 __ __ __ __ │ ............░░░░ - 0x20 │ ╾──────alloc14+0──────╼ 02 00 00 00 00 00 00 00 │ ╾──────╼........ - 0x30 │ 01 00 00 00 2a 00 00 00 ╾──────alloc22+0──────╼ │ ....*...╾──────╼ + 0x20 │ ╾──────alloc15+0──────╼ 02 00 00 00 00 00 00 00 │ ╾──────╼........ + 0x30 │ 01 00 00 00 2a 00 00 00 ╾──────alloc23+0──────╼ │ ....*...╾──────╼ 0x40 │ 03 00 00 00 00 00 00 00 │ ........ } -alloc9 (size: 0, align: 8) {} +alloc10 (size: 0, align: 8) {} -alloc14 (size: 16, align: 8) { - ╾──────alloc12+0──────╼ ╾──────alloc13+0──────╼ │ ╾──────╼╾──────╼ +alloc15 (size: 16, align: 8) { + ╾──────alloc13+0──────╼ ╾──────alloc14+0──────╼ │ ╾──────╼╾──────╼ } -alloc12 (size: 1, align: 1) { +alloc13 (size: 1, align: 1) { 05 │ . } -alloc13 (size: 1, align: 1) { +alloc14 (size: 1, align: 1) { 06 │ . } -alloc22 (size: 24, align: 8) { - 0x00 │ ╾──────alloc18+3──────╼ ╾──────alloc19+0──────╼ │ ╾──────╼╾──────╼ - 0x10 │ ╾──────alloc21+2──────╼ │ ╾──────╼ +alloc23 (size: 24, align: 8) { + 0x00 │ ╾──────alloc19+3──────╼ ╾──────alloc20+0──────╼ │ ╾──────╼╾──────╼ + 0x10 │ ╾──────alloc22+2──────╼ │ ╾──────╼ } -alloc18 (size: 4, align: 1) { +alloc19 (size: 4, align: 1) { 2a 45 15 6f │ *E.o } -alloc19 (size: 1, align: 1) { +alloc20 (size: 1, align: 1) { 2a │ * } -alloc21 (size: 4, align: 1) { +alloc22 (size: 4, align: 1) { 2a 45 15 6f │ *E.o } diff --git a/src/test/ui/consts/const-eval/ub-nonnull.stderr b/src/test/ui/consts/const-eval/ub-nonnull.stderr index adad1b4f7fafe..b6c2572cb8dc3 100644 --- a/src/test/ui/consts/const-eval/ub-nonnull.stderr +++ b/src/test/ui/consts/const-eval/ub-nonnull.stderr @@ -13,7 +13,7 @@ LL | / const OUT_OF_BOUNDS_PTR: NonNull = { unsafe { LL | | let ptr: &[u8; 256] = mem::transmute(&0u8); // &0 gets promoted so it does not dangle LL | | // Use address-of-element for pointer arithmetic. This could wrap around to NULL! LL | | let out_of_bounds_ptr = &ptr[255]; - | | ^^^^^^^^^ Memory access failed: pointer must be in-bounds at offset 256, but is outside bounds of alloc8 which has size 1 + | | ^^^^^^^^^ Memory access failed: pointer must be in-bounds at offset 256, but is outside bounds of alloc11 which has size 1 LL | | mem::transmute(out_of_bounds_ptr) LL | | } }; | |____- diff --git a/src/test/ui/consts/miri_unleashed/mutable_const.stderr b/src/test/ui/consts/miri_unleashed/mutable_const.stderr index 8b847e4bf731f..54a9eda214660 100644 --- a/src/test/ui/consts/miri_unleashed/mutable_const.stderr +++ b/src/test/ui/consts/miri_unleashed/mutable_const.stderr @@ -11,7 +11,7 @@ LL | / const MUTATING_BEHIND_RAW: () = { LL | | // Test that `MUTABLE_BEHIND_RAW` is actually immutable, by doing this at const time. LL | | unsafe { LL | | *MUTABLE_BEHIND_RAW = 99 - | | ^^^^^^^^^^^^^^^^^^^^^^^^ writing to alloc1 which is read-only + | | ^^^^^^^^^^^^^^^^^^^^^^^^ writing to alloc2 which is read-only LL | | } LL | | }; | |__- diff --git a/src/test/ui/json-bom-plus-crlf-multifile.stderr b/src/test/ui/json-bom-plus-crlf-multifile.stderr index 99f91cc881617..8d3c316e467bd 100644 --- a/src/test/ui/json-bom-plus-crlf-multifile.stderr +++ b/src/test/ui/json-bom-plus-crlf-multifile.stderr @@ -12,11 +12,10 @@ let x: i32 = \"I am not a number!\"; // type `i32` assigned to variable `x` ``` -This error occurs when the compiler was unable to infer the concrete type of a -variable. It can happen in several cases, the most common being a mismatch -between the type that the compiler inferred for a variable based on its -initializing expression, on the one hand, and the type the author explicitly -assigned to the variable, on the other hand. +This error occurs when the compiler is unable to infer the concrete type of a +variable. It can occur in several cases, the most common being a mismatch +between two types: the type the author explicitly assigned, and the type the +compiler inferred. "},"level":"error","spans":[{"file_name":"$DIR/json-bom-plus-crlf-multifile-aux.rs","byte_start":621,"byte_end":622,"line_start":17,"line_end":17,"column_start":22,"column_end":23,"is_primary":true,"text":[{"text":" let s : String = 1; // Error in the middle of line.","highlight_start":22,"highlight_end":23}],"label":"expected struct `std::string::String`, found integer","suggested_replacement":null,"suggestion_applicability":null,"expansion":null},{"file_name":"$DIR/json-bom-plus-crlf-multifile-aux.rs","byte_start":612,"byte_end":618,"line_start":17,"line_end":17,"column_start":13,"column_end":19,"is_primary":false,"text":[{"text":" let s : String = 1; // Error in the middle of line.","highlight_start":13,"highlight_end":19}],"label":"expected due to this","suggested_replacement":null,"suggestion_applicability":null,"expansion":null}],"children":[{"message":"try using a conversion method","code":null,"level":"help","spans":[{"file_name":"$DIR/json-bom-plus-crlf-multifile-aux.rs","byte_start":621,"byte_end":622,"line_start":17,"line_end":17,"column_start":22,"column_end":23,"is_primary":true,"text":[{"text":" let s : String = 1; // Error in the middle of line.","highlight_start":22,"highlight_end":23}],"label":null,"suggested_replacement":"1.to_string()","suggestion_applicability":"MaybeIncorrect","expansion":null}],"children":[],"rendered":null}],"rendered":"$DIR/json-bom-plus-crlf-multifile-aux.rs:17:22: error[E0308]: mismatched types "} {"message":"mismatched types","code":{"code":"E0308","explanation":"Expected type did not match the received type. @@ -33,11 +32,10 @@ let x: i32 = \"I am not a number!\"; // type `i32` assigned to variable `x` ``` -This error occurs when the compiler was unable to infer the concrete type of a -variable. It can happen in several cases, the most common being a mismatch -between the type that the compiler inferred for a variable based on its -initializing expression, on the one hand, and the type the author explicitly -assigned to the variable, on the other hand. +This error occurs when the compiler is unable to infer the concrete type of a +variable. It can occur in several cases, the most common being a mismatch +between two types: the type the author explicitly assigned, and the type the +compiler inferred. "},"level":"error","spans":[{"file_name":"$DIR/json-bom-plus-crlf-multifile-aux.rs","byte_start":681,"byte_end":682,"line_start":19,"line_end":19,"column_start":22,"column_end":23,"is_primary":true,"text":[{"text":" let s : String = 1","highlight_start":22,"highlight_end":23}],"label":"expected struct `std::string::String`, found integer","suggested_replacement":null,"suggestion_applicability":null,"expansion":null},{"file_name":"$DIR/json-bom-plus-crlf-multifile-aux.rs","byte_start":672,"byte_end":678,"line_start":19,"line_end":19,"column_start":13,"column_end":19,"is_primary":false,"text":[{"text":" let s : String = 1","highlight_start":13,"highlight_end":19}],"label":"expected due to this","suggested_replacement":null,"suggestion_applicability":null,"expansion":null}],"children":[{"message":"try using a conversion method","code":null,"level":"help","spans":[{"file_name":"$DIR/json-bom-plus-crlf-multifile-aux.rs","byte_start":681,"byte_end":682,"line_start":19,"line_end":19,"column_start":22,"column_end":23,"is_primary":true,"text":[{"text":" let s : String = 1","highlight_start":22,"highlight_end":23}],"label":null,"suggested_replacement":"1.to_string()","suggestion_applicability":"MaybeIncorrect","expansion":null}],"children":[],"rendered":null}],"rendered":"$DIR/json-bom-plus-crlf-multifile-aux.rs:19:22: error[E0308]: mismatched types "} {"message":"mismatched types","code":{"code":"E0308","explanation":"Expected type did not match the received type. @@ -54,11 +52,10 @@ let x: i32 = \"I am not a number!\"; // type `i32` assigned to variable `x` ``` -This error occurs when the compiler was unable to infer the concrete type of a -variable. It can happen in several cases, the most common being a mismatch -between the type that the compiler inferred for a variable based on its -initializing expression, on the one hand, and the type the author explicitly -assigned to the variable, on the other hand. +This error occurs when the compiler is unable to infer the concrete type of a +variable. It can occur in several cases, the most common being a mismatch +between two types: the type the author explicitly assigned, and the type the +compiler inferred. "},"level":"error","spans":[{"file_name":"$DIR/json-bom-plus-crlf-multifile-aux.rs","byte_start":745,"byte_end":746,"line_start":23,"line_end":23,"column_start":1,"column_end":2,"is_primary":true,"text":[{"text":"1; // Error after the newline.","highlight_start":1,"highlight_end":2}],"label":"expected struct `std::string::String`, found integer","suggested_replacement":null,"suggestion_applicability":null,"expansion":null},{"file_name":"$DIR/json-bom-plus-crlf-multifile-aux.rs","byte_start":735,"byte_end":741,"line_start":22,"line_end":22,"column_start":13,"column_end":19,"is_primary":false,"text":[{"text":" let s : String =","highlight_start":13,"highlight_end":19}],"label":"expected due to this","suggested_replacement":null,"suggestion_applicability":null,"expansion":null}],"children":[{"message":"try using a conversion method","code":null,"level":"help","spans":[{"file_name":"$DIR/json-bom-plus-crlf-multifile-aux.rs","byte_start":745,"byte_end":746,"line_start":23,"line_end":23,"column_start":1,"column_end":2,"is_primary":true,"text":[{"text":"1; // Error after the newline.","highlight_start":1,"highlight_end":2}],"label":null,"suggested_replacement":"1.to_string()","suggestion_applicability":"MaybeIncorrect","expansion":null}],"children":[],"rendered":null}],"rendered":"$DIR/json-bom-plus-crlf-multifile-aux.rs:23:1: error[E0308]: mismatched types "} {"message":"mismatched types","code":{"code":"E0308","explanation":"Expected type did not match the received type. @@ -75,11 +72,10 @@ let x: i32 = \"I am not a number!\"; // type `i32` assigned to variable `x` ``` -This error occurs when the compiler was unable to infer the concrete type of a -variable. It can happen in several cases, the most common being a mismatch -between the type that the compiler inferred for a variable based on its -initializing expression, on the one hand, and the type the author explicitly -assigned to the variable, on the other hand. +This error occurs when the compiler is unable to infer the concrete type of a +variable. It can occur in several cases, the most common being a mismatch +between two types: the type the author explicitly assigned, and the type the +compiler inferred. "},"level":"error","spans":[{"file_name":"$DIR/json-bom-plus-crlf-multifile-aux.rs","byte_start":801,"byte_end":809,"line_start":25,"line_end":26,"column_start":22,"column_end":6,"is_primary":true,"text":[{"text":" let s : String = (","highlight_start":22,"highlight_end":23},{"text":" ); // Error spanning the newline.","highlight_start":1,"highlight_end":6}],"label":"expected struct `std::string::String`, found `()`","suggested_replacement":null,"suggestion_applicability":null,"expansion":null},{"file_name":"$DIR/json-bom-plus-crlf-multifile-aux.rs","byte_start":792,"byte_end":798,"line_start":25,"line_end":25,"column_start":13,"column_end":19,"is_primary":false,"text":[{"text":" let s : String = (","highlight_start":13,"highlight_end":19}],"label":"expected due to this","suggested_replacement":null,"suggestion_applicability":null,"expansion":null}],"children":[],"rendered":"$DIR/json-bom-plus-crlf-multifile-aux.rs:25:22: error[E0308]: mismatched types "} {"message":"aborting due to 4 previous errors","code":null,"level":"error","spans":[],"children":[],"rendered":"error: aborting due to 4 previous errors diff --git a/src/test/ui/json-bom-plus-crlf.stderr b/src/test/ui/json-bom-plus-crlf.stderr index 3e84f5ef54d2c..ed6b583f329d6 100644 --- a/src/test/ui/json-bom-plus-crlf.stderr +++ b/src/test/ui/json-bom-plus-crlf.stderr @@ -12,11 +12,10 @@ let x: i32 = \"I am not a number!\"; // type `i32` assigned to variable `x` ``` -This error occurs when the compiler was unable to infer the concrete type of a -variable. It can happen in several cases, the most common being a mismatch -between the type that the compiler inferred for a variable based on its -initializing expression, on the one hand, and the type the author explicitly -assigned to the variable, on the other hand. +This error occurs when the compiler is unable to infer the concrete type of a +variable. It can occur in several cases, the most common being a mismatch +between two types: the type the author explicitly assigned, and the type the +compiler inferred. "},"level":"error","spans":[{"file_name":"$DIR/json-bom-plus-crlf.rs","byte_start":606,"byte_end":607,"line_start":16,"line_end":16,"column_start":22,"column_end":23,"is_primary":true,"text":[{"text":" let s : String = 1; // Error in the middle of line.","highlight_start":22,"highlight_end":23}],"label":"expected struct `std::string::String`, found integer","suggested_replacement":null,"suggestion_applicability":null,"expansion":null},{"file_name":"$DIR/json-bom-plus-crlf.rs","byte_start":597,"byte_end":603,"line_start":16,"line_end":16,"column_start":13,"column_end":19,"is_primary":false,"text":[{"text":" let s : String = 1; // Error in the middle of line.","highlight_start":13,"highlight_end":19}],"label":"expected due to this","suggested_replacement":null,"suggestion_applicability":null,"expansion":null}],"children":[{"message":"try using a conversion method","code":null,"level":"help","spans":[{"file_name":"$DIR/json-bom-plus-crlf.rs","byte_start":606,"byte_end":607,"line_start":16,"line_end":16,"column_start":22,"column_end":23,"is_primary":true,"text":[{"text":" let s : String = 1; // Error in the middle of line.","highlight_start":22,"highlight_end":23}],"label":null,"suggested_replacement":"1.to_string()","suggestion_applicability":"MaybeIncorrect","expansion":null}],"children":[],"rendered":null}],"rendered":"$DIR/json-bom-plus-crlf.rs:16:22: error[E0308]: mismatched types "} {"message":"mismatched types","code":{"code":"E0308","explanation":"Expected type did not match the received type. @@ -33,11 +32,10 @@ let x: i32 = \"I am not a number!\"; // type `i32` assigned to variable `x` ``` -This error occurs when the compiler was unable to infer the concrete type of a -variable. It can happen in several cases, the most common being a mismatch -between the type that the compiler inferred for a variable based on its -initializing expression, on the one hand, and the type the author explicitly -assigned to the variable, on the other hand. +This error occurs when the compiler is unable to infer the concrete type of a +variable. It can occur in several cases, the most common being a mismatch +between two types: the type the author explicitly assigned, and the type the +compiler inferred. "},"level":"error","spans":[{"file_name":"$DIR/json-bom-plus-crlf.rs","byte_start":666,"byte_end":667,"line_start":18,"line_end":18,"column_start":22,"column_end":23,"is_primary":true,"text":[{"text":" let s : String = 1","highlight_start":22,"highlight_end":23}],"label":"expected struct `std::string::String`, found integer","suggested_replacement":null,"suggestion_applicability":null,"expansion":null},{"file_name":"$DIR/json-bom-plus-crlf.rs","byte_start":657,"byte_end":663,"line_start":18,"line_end":18,"column_start":13,"column_end":19,"is_primary":false,"text":[{"text":" let s : String = 1","highlight_start":13,"highlight_end":19}],"label":"expected due to this","suggested_replacement":null,"suggestion_applicability":null,"expansion":null}],"children":[{"message":"try using a conversion method","code":null,"level":"help","spans":[{"file_name":"$DIR/json-bom-plus-crlf.rs","byte_start":666,"byte_end":667,"line_start":18,"line_end":18,"column_start":22,"column_end":23,"is_primary":true,"text":[{"text":" let s : String = 1","highlight_start":22,"highlight_end":23}],"label":null,"suggested_replacement":"1.to_string()","suggestion_applicability":"MaybeIncorrect","expansion":null}],"children":[],"rendered":null}],"rendered":"$DIR/json-bom-plus-crlf.rs:18:22: error[E0308]: mismatched types "} {"message":"mismatched types","code":{"code":"E0308","explanation":"Expected type did not match the received type. @@ -54,11 +52,10 @@ let x: i32 = \"I am not a number!\"; // type `i32` assigned to variable `x` ``` -This error occurs when the compiler was unable to infer the concrete type of a -variable. It can happen in several cases, the most common being a mismatch -between the type that the compiler inferred for a variable based on its -initializing expression, on the one hand, and the type the author explicitly -assigned to the variable, on the other hand. +This error occurs when the compiler is unable to infer the concrete type of a +variable. It can occur in several cases, the most common being a mismatch +between two types: the type the author explicitly assigned, and the type the +compiler inferred. "},"level":"error","spans":[{"file_name":"$DIR/json-bom-plus-crlf.rs","byte_start":730,"byte_end":731,"line_start":22,"line_end":22,"column_start":1,"column_end":2,"is_primary":true,"text":[{"text":"1; // Error after the newline.","highlight_start":1,"highlight_end":2}],"label":"expected struct `std::string::String`, found integer","suggested_replacement":null,"suggestion_applicability":null,"expansion":null},{"file_name":"$DIR/json-bom-plus-crlf.rs","byte_start":720,"byte_end":726,"line_start":21,"line_end":21,"column_start":13,"column_end":19,"is_primary":false,"text":[{"text":" let s : String =","highlight_start":13,"highlight_end":19}],"label":"expected due to this","suggested_replacement":null,"suggestion_applicability":null,"expansion":null}],"children":[{"message":"try using a conversion method","code":null,"level":"help","spans":[{"file_name":"$DIR/json-bom-plus-crlf.rs","byte_start":730,"byte_end":731,"line_start":22,"line_end":22,"column_start":1,"column_end":2,"is_primary":true,"text":[{"text":"1; // Error after the newline.","highlight_start":1,"highlight_end":2}],"label":null,"suggested_replacement":"1.to_string()","suggestion_applicability":"MaybeIncorrect","expansion":null}],"children":[],"rendered":null}],"rendered":"$DIR/json-bom-plus-crlf.rs:22:1: error[E0308]: mismatched types "} {"message":"mismatched types","code":{"code":"E0308","explanation":"Expected type did not match the received type. @@ -75,11 +72,10 @@ let x: i32 = \"I am not a number!\"; // type `i32` assigned to variable `x` ``` -This error occurs when the compiler was unable to infer the concrete type of a -variable. It can happen in several cases, the most common being a mismatch -between the type that the compiler inferred for a variable based on its -initializing expression, on the one hand, and the type the author explicitly -assigned to the variable, on the other hand. +This error occurs when the compiler is unable to infer the concrete type of a +variable. It can occur in several cases, the most common being a mismatch +between two types: the type the author explicitly assigned, and the type the +compiler inferred. "},"level":"error","spans":[{"file_name":"$DIR/json-bom-plus-crlf.rs","byte_start":786,"byte_end":794,"line_start":24,"line_end":25,"column_start":22,"column_end":6,"is_primary":true,"text":[{"text":" let s : String = (","highlight_start":22,"highlight_end":23},{"text":" ); // Error spanning the newline.","highlight_start":1,"highlight_end":6}],"label":"expected struct `std::string::String`, found `()`","suggested_replacement":null,"suggestion_applicability":null,"expansion":null},{"file_name":"$DIR/json-bom-plus-crlf.rs","byte_start":777,"byte_end":783,"line_start":24,"line_end":24,"column_start":13,"column_end":19,"is_primary":false,"text":[{"text":" let s : String = (","highlight_start":13,"highlight_end":19}],"label":"expected due to this","suggested_replacement":null,"suggestion_applicability":null,"expansion":null}],"children":[],"rendered":"$DIR/json-bom-plus-crlf.rs:24:22: error[E0308]: mismatched types "} {"message":"aborting due to 4 previous errors","code":null,"level":"error","spans":[],"children":[],"rendered":"error: aborting due to 4 previous errors diff --git a/src/tools/compiletest/src/runtest.rs b/src/tools/compiletest/src/runtest.rs index 61a7d8ee5c948..1dd5adb2209ef 100644 --- a/src/tools/compiletest/src/runtest.rs +++ b/src/tools/compiletest/src/runtest.rs @@ -3338,6 +3338,10 @@ impl<'test> TestCx<'test> { } fn delete_file(&self, file: &PathBuf) { + if !file.exists() { + // Deleting a nonexistant file would error. + return; + } if let Err(e) = fs::remove_file(file) { self.fatal(&format!("failed to delete `{}`: {}", file.display(), e,)); } @@ -3400,7 +3404,7 @@ impl<'test> TestCx<'test> { let examined_content = self.load_expected_output_from_path(&examined_path).unwrap_or_else(|_| String::new()); - if examined_path.exists() && canon_content == &examined_content { + if canon_content == &examined_content { self.delete_file(&examined_path); } }