From 6f6620b966ce9ea37d034fa9d184d60b84a9ce02 Mon Sep 17 00:00:00 2001 From: Eden Date: Sun, 7 Jun 2020 11:23:15 +0400 Subject: [PATCH 01/41] Rename "cyclone" to "apple-a7" per changes in upstream LLVM See: https://reviews.llvm.org/D70779 https://reviews.llvm.org/D70779#C1703593NL568 LLVM 10 merged into master at: https://github.com/rust-lang/rust/pull/67759 --- src/librustc_target/spec/aarch64_apple_ios.rs | 2 +- src/librustc_target/spec/aarch64_apple_tvos.rs | 2 +- src/librustc_target/spec/apple_sdk_base.rs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/librustc_target/spec/aarch64_apple_ios.rs b/src/librustc_target/spec/aarch64_apple_ios.rs index eac2c3e6aa40c..1447716ca8484 100644 --- a/src/librustc_target/spec/aarch64_apple_ios.rs +++ b/src/librustc_target/spec/aarch64_apple_ios.rs @@ -15,7 +15,7 @@ pub fn target() -> TargetResult { target_vendor: "apple".to_string(), linker_flavor: LinkerFlavor::Gcc, options: TargetOptions { - features: "+neon,+fp-armv8,+cyclone".to_string(), + features: "+neon,+fp-armv8,+apple-a7".to_string(), eliminate_frame_pointer: false, max_atomic_width: Some(128), abi_blacklist: super::arm_base::abi_blacklist(), diff --git a/src/librustc_target/spec/aarch64_apple_tvos.rs b/src/librustc_target/spec/aarch64_apple_tvos.rs index f1cd14ffd11a6..21f660ac8b839 100644 --- a/src/librustc_target/spec/aarch64_apple_tvos.rs +++ b/src/librustc_target/spec/aarch64_apple_tvos.rs @@ -15,7 +15,7 @@ pub fn target() -> TargetResult { target_vendor: "apple".to_string(), linker_flavor: LinkerFlavor::Gcc, options: TargetOptions { - features: "+neon,+fp-armv8,+cyclone".to_string(), + features: "+neon,+fp-armv8,+apple-a7".to_string(), eliminate_frame_pointer: false, max_atomic_width: Some(128), abi_blacklist: super::arm_base::abi_blacklist(), diff --git a/src/librustc_target/spec/apple_sdk_base.rs b/src/librustc_target/spec/apple_sdk_base.rs index c7cff17b1544c..b07c2aef1caca 100644 --- a/src/librustc_target/spec/apple_sdk_base.rs +++ b/src/librustc_target/spec/apple_sdk_base.rs @@ -122,7 +122,7 @@ fn target_cpu(arch: Arch) -> String { match arch { Armv7 => "cortex-a8", // iOS7 is supported on iPhone 4 and higher Armv7s => "cortex-a9", - Arm64 => "cyclone", + Arm64 => "apple-a7", I386 => "yonah", X86_64 => "core2", X86_64_macabi => "core2", From 95c4899e55e7aab68f06e67660257d73e6a46eda Mon Sep 17 00:00:00 2001 From: Alexis Bourget Date: Sun, 7 Jun 2020 23:36:07 +0200 Subject: [PATCH 02/41] Added an example where explicitly dropping a lock is necessary/a good idea. --- src/libstd/sync/mutex.rs | 61 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/src/libstd/sync/mutex.rs b/src/libstd/sync/mutex.rs index 797b22fdd1279..6077e1a402965 100644 --- a/src/libstd/sync/mutex.rs +++ b/src/libstd/sync/mutex.rs @@ -107,6 +107,67 @@ use crate::sys_common::poison::{self, LockResult, TryLockError, TryLockResult}; /// /// *guard += 1; /// ``` +/// +/// It is sometimes a good idea (or even necessary) to manually drop the mutex +/// to unlock it as soon as possible. If you need the resource until the end of +/// the scope, this is not needed. +/// +/// ``` +/// use std::sync::{Arc, Mutex}; +/// use std::thread; +/// +/// const N: usize = 3; +/// +/// // Some data to work with in multiple threads. +/// let data_mutex = Arc::new(Mutex::new([1, 2, 3, 4])); +/// // The result of all the work across all threads. +/// let res_mutex = Arc::new(Mutex::new(0)); +/// +/// // Threads other than the main thread. +/// let mut threads = Vec::with_capacity(N); +/// (0..N).for_each(|_| { +/// // Getting clones for the mutexes. +/// let data_mutex_clone = Arc::clone(&data_mutex); +/// let res_mutex_clone = Arc::clone(&res_mutex); +/// +/// threads.push(thread::spawn(move || { +/// let data = *data_mutex_clone.lock().unwrap(); +/// // This is the result of some important and long-ish work. +/// let result = data.iter().fold(0, |acc, x| acc + x * 2); +/// // We drop the `data` explicitely because it's not necessary anymore +/// // and the thread still has work to do. This allow other threads to +/// // start working on the data immediately, without waiting +/// // for the rest of the unrelated work to be done here. +/// std::mem::drop(data); +/// *res_mutex_clone.lock().unwrap() += result; +/// })); +/// }); +/// +/// let data = *data_mutex.lock().unwrap(); +/// // This is the result of some important and long-ish work. +/// let result = data.iter().fold(0, |acc, x| acc + x * 2); +/// // We drop the `data` explicitely because it's not necessary anymore +/// // and the thread still has work to do. This allow other threads to +/// // start working on the data immediately, without waiting +/// // for the rest of the unrelated work to be done here. +/// // +/// // It's even more important here because we `.join` the threads after that. +/// // If we had not dropped the lock, a thread could be waiting forever for +/// // it, causing a deadlock. +/// std::mem::drop(data); +/// // Here the lock is not assigned to a variable and so, even if the scope +/// // does not end after this line, the mutex is still released: +/// // there is no deadlock. +/// *res_mutex.lock().unwrap() += result; +/// +/// threads.into_iter().for_each(|thread| { +/// thread +/// .join() +/// .expect("The thread creating or execution failed !") +/// }); +/// +/// assert_eq!(*res_mutex.lock().unwrap(), 80); +/// ``` #[stable(feature = "rust1", since = "1.0.0")] #[cfg_attr(not(test), rustc_diagnostic_item = "mutex_type")] pub struct Mutex { From 9c8f881ccd050f06387612e4b8aa18111c51a63b Mon Sep 17 00:00:00 2001 From: Alexis Bourget Date: Sun, 7 Jun 2020 23:42:55 +0200 Subject: [PATCH 03/41] Improved the example to work with mutable data, providing a reason for the mutex holding it --- src/libstd/sync/mutex.rs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/libstd/sync/mutex.rs b/src/libstd/sync/mutex.rs index 6077e1a402965..633496154aefe 100644 --- a/src/libstd/sync/mutex.rs +++ b/src/libstd/sync/mutex.rs @@ -119,7 +119,7 @@ use crate::sys_common::poison::{self, LockResult, TryLockError, TryLockResult}; /// const N: usize = 3; /// /// // Some data to work with in multiple threads. -/// let data_mutex = Arc::new(Mutex::new([1, 2, 3, 4])); +/// let data_mutex = Arc::new(Mutex::new(vec![1, 2, 3, 4])); /// // The result of all the work across all threads. /// let res_mutex = Arc::new(Mutex::new(0)); /// @@ -131,9 +131,10 @@ use crate::sys_common::poison::{self, LockResult, TryLockError, TryLockResult}; /// let res_mutex_clone = Arc::clone(&res_mutex); /// /// threads.push(thread::spawn(move || { -/// let data = *data_mutex_clone.lock().unwrap(); +/// let mut data = data_mutex_clone.lock().unwrap(); /// // This is the result of some important and long-ish work. /// let result = data.iter().fold(0, |acc, x| acc + x * 2); +/// data.push(result); /// // We drop the `data` explicitely because it's not necessary anymore /// // and the thread still has work to do. This allow other threads to /// // start working on the data immediately, without waiting @@ -143,9 +144,10 @@ use crate::sys_common::poison::{self, LockResult, TryLockError, TryLockResult}; /// })); /// }); /// -/// let data = *data_mutex.lock().unwrap(); +/// let mut data = data_mutex.lock().unwrap(); /// // This is the result of some important and long-ish work. /// let result = data.iter().fold(0, |acc, x| acc + x * 2); +/// data.push(result); /// // We drop the `data` explicitely because it's not necessary anymore /// // and the thread still has work to do. This allow other threads to /// // start working on the data immediately, without waiting @@ -166,7 +168,7 @@ use crate::sys_common::poison::{self, LockResult, TryLockError, TryLockResult}; /// .expect("The thread creating or execution failed !") /// }); /// -/// assert_eq!(*res_mutex.lock().unwrap(), 80); +/// assert_eq!(*res_mutex.lock().unwrap(), 800); /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[cfg_attr(not(test), rustc_diagnostic_item = "mutex_type")] From fdef1a5915332a3f9012b41f4176cf2a16025257 Mon Sep 17 00:00:00 2001 From: Poliorcetics Date: Mon, 8 Jun 2020 16:29:47 +0200 Subject: [PATCH 04/41] Simply use drop instead of std::mem::drop Co-authored-by: LeSeulArtichaut --- src/libstd/sync/mutex.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/libstd/sync/mutex.rs b/src/libstd/sync/mutex.rs index 633496154aefe..c2c86fae654cf 100644 --- a/src/libstd/sync/mutex.rs +++ b/src/libstd/sync/mutex.rs @@ -139,7 +139,7 @@ use crate::sys_common::poison::{self, LockResult, TryLockError, TryLockResult}; /// // and the thread still has work to do. This allow other threads to /// // start working on the data immediately, without waiting /// // for the rest of the unrelated work to be done here. -/// std::mem::drop(data); +/// drop(data); /// *res_mutex_clone.lock().unwrap() += result; /// })); /// }); @@ -156,7 +156,7 @@ use crate::sys_common::poison::{self, LockResult, TryLockError, TryLockResult}; /// // It's even more important here because we `.join` the threads after that. /// // If we had not dropped the lock, a thread could be waiting forever for /// // it, causing a deadlock. -/// std::mem::drop(data); +/// drop(data); /// // Here the lock is not assigned to a variable and so, even if the scope /// // does not end after this line, the mutex is still released: /// // there is no deadlock. From 496818ccd79e9bc093552887c923168defb13c6c Mon Sep 17 00:00:00 2001 From: Alexis Bourget Date: Mon, 8 Jun 2020 18:31:45 +0200 Subject: [PATCH 05/41] Add methods to go from a nul-terminated Vec to a CString, checked and unchecked. Doc tests have been written and the documentation on the error type updated too. --- src/libstd/ffi/c_str.rs | 80 +++++++++++++++++++++++++++++++++++++++-- 1 file changed, 77 insertions(+), 3 deletions(-) diff --git a/src/libstd/ffi/c_str.rs b/src/libstd/ffi/c_str.rs index 4bac9a4917d8f..f3a935ccc1130 100644 --- a/src/libstd/ffi/c_str.rs +++ b/src/libstd/ffi/c_str.rs @@ -234,15 +234,18 @@ pub struct NulError(usize, Vec); /// An error indicating that a nul byte was not in the expected position. /// -/// The slice used to create a [`CStr`] must have one and only one nul -/// byte at the end of the slice. +/// The slice used to create a [`CStr`] or the vector used to create a +/// [`CString`] must have one and only one nul byte, positioned at the end. /// /// This error is created by the /// [`from_bytes_with_nul`][`CStr::from_bytes_with_nul`] method on -/// [`CStr`]. See its documentation for more. +/// [`CStr`] or the [`from_vec_with_nul`][`CString::from_vec_with_nul`] method +/// on [`CString`]. See their documentation for more. /// /// [`CStr`]: struct.CStr.html /// [`CStr::from_bytes_with_nul`]: struct.CStr.html#method.from_bytes_with_nul +/// [`CString`]: struct.CString.html +/// [`CString::from_vec_with_nul`]: struct.CString.html#method.from_vec_with_nul /// /// # Examples /// @@ -632,6 +635,77 @@ impl CString { let this = mem::ManuallyDrop::new(self); unsafe { ptr::read(&this.inner) } } + + /// Converts a `Vec` of `u8` to a `CString` without checking the invariants + /// on the given `Vec`. + /// + /// # Safety + /// + /// The given `Vec` **must** have one nul byte as its last element. + /// This means it cannot be empty nor have any other nul byte anywhere else. + /// + /// # Example + /// + /// ``` + /// use std::ffi::CString; + /// assert_eq!( + /// unsafe { CString::from_vec_with_nul_unchecked(b"abc\0".to_vec()) }, + /// unsafe { CString::from_vec_unchecked(b"abc".to_vec()) } + /// ); + /// ``` + #[stable(feature = "cstring_from_vec_with_nul", since = "1.46.0")] + pub unsafe fn from_vec_with_nul_unchecked(v: Vec) -> Self { + Self { inner: v.into_boxed_slice() } + } + + /// Attempts to converts a `Vec` of `u8` to a `CString`. + /// + /// Runtime checks are present to ensure there is only one nul byte in the + /// `Vec`, its last element. + /// + /// # Errors + /// + /// If a nul byte is present and not the last element or no nul bytes + /// is present, an error will be returned. + /// + /// # Examples + /// + /// A successful conversion will produce the same result as [`new`] when + /// called without the ending nul byte. + /// + /// ``` + /// use std::ffi::CString; + /// assert_eq!( + /// CString::from_vec_with_nul(b"abc\0".to_vec()) + /// .expect("CString::from_vec_with_nul failed"), + /// CString::new(b"abc".to_vec()) + /// ); + /// ``` + /// + /// A incorrectly formatted vector will produce an error. + /// + /// ``` + /// use std::ffi::{CString, FromBytesWithNulError}; + /// // Interior nul byte + /// let _: FromBytesWithNulError = CString::from_vec_with_nul(b"a\0bc".to_vec()).unwrap_err(); + /// // No nul byte + /// let _: FromBytesWithNulError = CString::from_vec_with_nul(b"abc".to_vec()).unwrap_err(); + /// ``` + /// + /// [`new`]: #method.new + #[stable(feature = "cstring_from_vec_with_nul", since = "1.46.0")] + pub fn from_vec_with_nul(v: Vec) -> Result { + let nul_pos = memchr::memchr(0, &v); + match nul_pos { + Some(nul_pos) if nul_pos + 1 == v.len() => { + // SAFETY: We know there is only one nul byte, at the end + // of the vec. + Ok(unsafe { Self::from_vec_with_nul_unchecked(v) }) + } + Some(nul_pos) => Err(FromBytesWithNulError::interior_nul(nul_pos)), + None => Err(FromBytesWithNulError::not_nul_terminated()), + } + } } // Turns this `CString` into an empty string to prevent From b03164e6679284b984437fe82092682cf7c984f8 Mon Sep 17 00:00:00 2001 From: Alexis Bourget Date: Tue, 9 Jun 2020 22:15:05 +0200 Subject: [PATCH 06/41] Move to unstable, linking the issue --- src/libstd/ffi/c_str.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/libstd/ffi/c_str.rs b/src/libstd/ffi/c_str.rs index f3a935ccc1130..6f7dc091897f4 100644 --- a/src/libstd/ffi/c_str.rs +++ b/src/libstd/ffi/c_str.rs @@ -653,7 +653,7 @@ impl CString { /// unsafe { CString::from_vec_unchecked(b"abc".to_vec()) } /// ); /// ``` - #[stable(feature = "cstring_from_vec_with_nul", since = "1.46.0")] + #[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")] pub unsafe fn from_vec_with_nul_unchecked(v: Vec) -> Self { Self { inner: v.into_boxed_slice() } } @@ -693,7 +693,7 @@ impl CString { /// ``` /// /// [`new`]: #method.new - #[stable(feature = "cstring_from_vec_with_nul", since = "1.46.0")] + #[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")] pub fn from_vec_with_nul(v: Vec) -> Result { let nul_pos = memchr::memchr(0, &v); match nul_pos { From 1312d30a6a837f72c3f36f5dc1c575a29890aa2c Mon Sep 17 00:00:00 2001 From: Alexis Bourget Date: Tue, 9 Jun 2020 22:40:30 +0200 Subject: [PATCH 07/41] Remove a lot of unecessary/duplicated comments --- src/libstd/sync/mutex.rs | 14 +++----------- 1 file changed, 3 insertions(+), 11 deletions(-) diff --git a/src/libstd/sync/mutex.rs b/src/libstd/sync/mutex.rs index c2c86fae654cf..b3ef521d6ecb0 100644 --- a/src/libstd/sync/mutex.rs +++ b/src/libstd/sync/mutex.rs @@ -118,15 +118,11 @@ use crate::sys_common::poison::{self, LockResult, TryLockError, TryLockResult}; /// /// const N: usize = 3; /// -/// // Some data to work with in multiple threads. /// let data_mutex = Arc::new(Mutex::new(vec![1, 2, 3, 4])); -/// // The result of all the work across all threads. /// let res_mutex = Arc::new(Mutex::new(0)); /// -/// // Threads other than the main thread. /// let mut threads = Vec::with_capacity(N); /// (0..N).for_each(|_| { -/// // Getting clones for the mutexes. /// let data_mutex_clone = Arc::clone(&data_mutex); /// let res_mutex_clone = Arc::clone(&res_mutex); /// @@ -135,10 +131,6 @@ use crate::sys_common::poison::{self, LockResult, TryLockError, TryLockResult}; /// // This is the result of some important and long-ish work. /// let result = data.iter().fold(0, |acc, x| acc + x * 2); /// data.push(result); -/// // We drop the `data` explicitely because it's not necessary anymore -/// // and the thread still has work to do. This allow other threads to -/// // start working on the data immediately, without waiting -/// // for the rest of the unrelated work to be done here. /// drop(data); /// *res_mutex_clone.lock().unwrap() += result; /// })); @@ -153,9 +145,9 @@ use crate::sys_common::poison::{self, LockResult, TryLockError, TryLockResult}; /// // start working on the data immediately, without waiting /// // for the rest of the unrelated work to be done here. /// // -/// // It's even more important here because we `.join` the threads after that. -/// // If we had not dropped the lock, a thread could be waiting forever for -/// // it, causing a deadlock. +/// // It's even more important here than in the threads because we `.join` the +/// // threads after that. If we had not dropped the lock, a thread could be +/// // waiting forever for it, causing a deadlock. /// drop(data); /// // Here the lock is not assigned to a variable and so, even if the scope /// // does not end after this line, the mutex is still released: From 88ea7e5234bff0c4fcf5859aa6d5dd8d0608b853 Mon Sep 17 00:00:00 2001 From: Matthew Jasper Date: Mon, 1 Jun 2020 18:58:18 +0100 Subject: [PATCH 08/41] Use min_specialization in the remaining rustc crates --- src/librustc_arena/lib.rs | 29 ++-- src/librustc_ast_lowering/lib.rs | 2 +- src/librustc_hir/arena.rs | 70 ++++----- .../infer/canonical/query_response.rs | 2 +- src/librustc_macros/src/query.rs | 4 +- src/librustc_metadata/lib.rs | 2 +- src/librustc_metadata/rmeta/decoder.rs | 17 ++- src/librustc_metadata/rmeta/encoder.rs | 35 +++-- src/librustc_middle/arena.rs | 76 +++++++--- src/librustc_middle/dep_graph/dep_node.rs | 27 +++- src/librustc_middle/lib.rs | 2 +- src/librustc_middle/mir/mod.rs | 37 ++++- src/librustc_middle/ty/codec.rs | 142 +++++++++++------- src/librustc_middle/ty/query/on_disk_cache.rs | 60 ++------ .../ty/query/profiling_support.rs | 41 +++-- src/librustc_middle/ty/query/values.rs | 20 ++- src/librustc_middle/ty/sty.rs | 2 - .../dep_graph/dep_node.rs | 9 +- src/librustc_query_system/lib.rs | 2 +- src/librustc_serialize/lib.rs | 2 +- src/librustc_serialize/serialize.rs | 36 ++--- src/librustc_trait_selection/infer.rs | 4 +- 22 files changed, 373 insertions(+), 248 deletions(-) diff --git a/src/librustc_arena/lib.rs b/src/librustc_arena/lib.rs index bbe80c26dcbf9..4ea5ec3c1de82 100644 --- a/src/librustc_arena/lib.rs +++ b/src/librustc_arena/lib.rs @@ -610,7 +610,7 @@ macro_rules! which_arena_for_type { #[macro_export] macro_rules! declare_arena { - ([], [$($a:tt $name:ident: $ty:ty,)*], $tcx:lifetime) => { + ([], [$($a:tt $name:ident: $ty:ty, $gen_ty:ty;)*], $tcx:lifetime) => { #[derive(Default)] pub struct Arena<$tcx> { pub dropless: $crate::DroplessArena, @@ -619,17 +619,17 @@ macro_rules! declare_arena { } #[marker] - pub trait ArenaAllocatable {} + pub trait ArenaAllocatable<'tcx> {} - impl ArenaAllocatable for T {} + impl<'tcx, T: Copy> ArenaAllocatable<'tcx> for T {} - unsafe trait ArenaField<'tcx>: Sized { + unsafe trait ArenaField<'tcx>: Sized + ArenaAllocatable<'tcx> { /// Returns a specific arena to allocate from. /// If `None` is returned, the `DropArena` will be used. fn arena<'a>(arena: &'a Arena<'tcx>) -> Option<&'a $crate::TypedArena>; } - unsafe impl<'tcx, T> ArenaField<'tcx> for T { + unsafe impl<'tcx, T: ArenaAllocatable<'tcx>> ArenaField<'tcx> for T { #[inline] default fn arena<'a>(_: &'a Arena<'tcx>) -> Option<&'a $crate::TypedArena> { panic!() @@ -638,18 +638,27 @@ macro_rules! declare_arena { $( #[allow(unused_lifetimes)] - impl<$tcx> ArenaAllocatable for $ty {} - unsafe impl<$tcx> ArenaField<$tcx> for $ty { + impl<$tcx> ArenaAllocatable<$tcx> for $ty {} + unsafe impl<$tcx, '_x, '_y, '_z, '_w> ArenaField<$tcx> for $gen_ty where Self: ArenaAllocatable<$tcx> { #[inline] fn arena<'a>(_arena: &'a Arena<$tcx>) -> Option<&'a $crate::TypedArena> { - $crate::which_arena_for_type!($a[&_arena.$name]) + // SAFETY: We only implement `ArenaAllocatable<$tcx>` for + // `$ty`, so `$ty` and Self are the same type + unsafe { + ::std::mem::transmute::< + Option<&'a $crate::TypedArena<$ty>>, + Option<&'a $crate::TypedArena>, + >( + $crate::which_arena_for_type!($a[&_arena.$name]) + ) + } } } )* impl<'tcx> Arena<'tcx> { #[inline] - pub fn alloc(&self, value: T) -> &mut T { + pub fn alloc>(&self, value: T) -> &mut T { if !::std::mem::needs_drop::() { return self.dropless.alloc(value); } @@ -667,7 +676,7 @@ macro_rules! declare_arena { self.dropless.alloc_slice(value) } - pub fn alloc_from_iter<'a, T: ArenaAllocatable>( + pub fn alloc_from_iter<'a, T: ArenaAllocatable<'tcx>>( &'a self, iter: impl ::std::iter::IntoIterator, ) -> &'a mut [T] { diff --git a/src/librustc_ast_lowering/lib.rs b/src/librustc_ast_lowering/lib.rs index 1f8c68f75e943..7b1535351262a 100644 --- a/src/librustc_ast_lowering/lib.rs +++ b/src/librustc_ast_lowering/lib.rs @@ -33,7 +33,7 @@ #![feature(array_value_iter)] #![feature(crate_visibility_modifier)] #![feature(marker_trait_attr)] -#![feature(specialization)] // FIXME: min_specialization does not work +#![feature(min_specialization)] #![feature(or_patterns)] #![recursion_limit = "256"] diff --git a/src/librustc_hir/arena.rs b/src/librustc_hir/arena.rs index 6ba396666070a..f439db715310c 100644 --- a/src/librustc_hir/arena.rs +++ b/src/librustc_hir/arena.rs @@ -12,41 +12,41 @@ macro_rules! arena_types { ($macro:path, $args:tt, $tcx:lifetime) => ( $macro!($args, [ // HIR types - [few] hir_krate: rustc_hir::Crate<$tcx>, - [] arm: rustc_hir::Arm<$tcx>, - [] asm_operand: rustc_hir::InlineAsmOperand<$tcx>, - [] asm_template: rustc_ast::ast::InlineAsmTemplatePiece, - [] attribute: rustc_ast::ast::Attribute, - [] block: rustc_hir::Block<$tcx>, - [] bare_fn_ty: rustc_hir::BareFnTy<$tcx>, - [few] global_asm: rustc_hir::GlobalAsm, - [] generic_arg: rustc_hir::GenericArg<$tcx>, - [] generic_args: rustc_hir::GenericArgs<$tcx>, - [] generic_bound: rustc_hir::GenericBound<$tcx>, - [] generic_param: rustc_hir::GenericParam<$tcx>, - [] expr: rustc_hir::Expr<$tcx>, - [] field: rustc_hir::Field<$tcx>, - [] field_pat: rustc_hir::FieldPat<$tcx>, - [] fn_decl: rustc_hir::FnDecl<$tcx>, - [] foreign_item: rustc_hir::ForeignItem<$tcx>, - [] impl_item_ref: rustc_hir::ImplItemRef<$tcx>, - [few] inline_asm: rustc_hir::InlineAsm<$tcx>, - [few] llvm_inline_asm: rustc_hir::LlvmInlineAsm<$tcx>, - [] local: rustc_hir::Local<$tcx>, - [few] macro_def: rustc_hir::MacroDef<$tcx>, - [] param: rustc_hir::Param<$tcx>, - [] pat: rustc_hir::Pat<$tcx>, - [] path: rustc_hir::Path<$tcx>, - [] path_segment: rustc_hir::PathSegment<$tcx>, - [] poly_trait_ref: rustc_hir::PolyTraitRef<$tcx>, - [] qpath: rustc_hir::QPath<$tcx>, - [] stmt: rustc_hir::Stmt<$tcx>, - [] struct_field: rustc_hir::StructField<$tcx>, - [] trait_item_ref: rustc_hir::TraitItemRef, - [] ty: rustc_hir::Ty<$tcx>, - [] type_binding: rustc_hir::TypeBinding<$tcx>, - [] variant: rustc_hir::Variant<$tcx>, - [] where_predicate: rustc_hir::WherePredicate<$tcx>, + [few] hir_krate: rustc_hir::Crate<$tcx>, rustc_hir::Crate<'_x>; + [] arm: rustc_hir::Arm<$tcx>, rustc_hir::Arm<'_x>; + [] asm_operand: rustc_hir::InlineAsmOperand<$tcx>, rustc_hir::InlineAsmOperand<'_x>; + [] asm_template: rustc_ast::ast::InlineAsmTemplatePiece, rustc_ast::ast::InlineAsmTemplatePiece; + [] attribute: rustc_ast::ast::Attribute, rustc_ast::ast::Attribute; + [] block: rustc_hir::Block<$tcx>, rustc_hir::Block<'_x>; + [] bare_fn_ty: rustc_hir::BareFnTy<$tcx>, rustc_hir::BareFnTy<'_x>; + [few] global_asm: rustc_hir::GlobalAsm, rustc_hir::GlobalAsm; + [] generic_arg: rustc_hir::GenericArg<$tcx>, rustc_hir::GenericArg<'_x>; + [] generic_args: rustc_hir::GenericArgs<$tcx>, rustc_hir::GenericArgs<'_x>; + [] generic_bound: rustc_hir::GenericBound<$tcx>, rustc_hir::GenericBound<'_x>; + [] generic_param: rustc_hir::GenericParam<$tcx>, rustc_hir::GenericParam<'_x>; + [] expr: rustc_hir::Expr<$tcx>, rustc_hir::Expr<'_x>; + [] field: rustc_hir::Field<$tcx>, rustc_hir::Field<'_x>; + [] field_pat: rustc_hir::FieldPat<$tcx>, rustc_hir::FieldPat<'_x>; + [] fn_decl: rustc_hir::FnDecl<$tcx>, rustc_hir::FnDecl<'_x>; + [] foreign_item: rustc_hir::ForeignItem<$tcx>, rustc_hir::ForeignItem<'_x>; + [] impl_item_ref: rustc_hir::ImplItemRef<$tcx>, rustc_hir::ImplItemRef<'_x>; + [few] inline_asm: rustc_hir::InlineAsm<$tcx>, rustc_hir::InlineAsm<'_x>; + [few] llvm_inline_asm: rustc_hir::LlvmInlineAsm<$tcx>, rustc_hir::LlvmInlineAsm<'_x>; + [] local: rustc_hir::Local<$tcx>, rustc_hir::Local<'_x>; + [few] macro_def: rustc_hir::MacroDef<$tcx>, rustc_hir::MacroDef<'_x>; + [] param: rustc_hir::Param<$tcx>, rustc_hir::Param<'_x>; + [] pat: rustc_hir::Pat<$tcx>, rustc_hir::Pat<'_x>; + [] path: rustc_hir::Path<$tcx>, rustc_hir::Path<'_x>; + [] path_segment: rustc_hir::PathSegment<$tcx>, rustc_hir::PathSegment<'_x>; + [] poly_trait_ref: rustc_hir::PolyTraitRef<$tcx>, rustc_hir::PolyTraitRef<'_x>; + [] qpath: rustc_hir::QPath<$tcx>, rustc_hir::QPath<'_x>; + [] stmt: rustc_hir::Stmt<$tcx>, rustc_hir::Stmt<'_x>; + [] struct_field: rustc_hir::StructField<$tcx>, rustc_hir::StructField<'_x>; + [] trait_item_ref: rustc_hir::TraitItemRef, rustc_hir::TraitItemRef; + [] ty: rustc_hir::Ty<$tcx>, rustc_hir::Ty<'_x>; + [] type_binding: rustc_hir::TypeBinding<$tcx>, rustc_hir::TypeBinding<'_x>; + [] variant: rustc_hir::Variant<$tcx>, rustc_hir::Variant<'_x>; + [] where_predicate: rustc_hir::WherePredicate<$tcx>, rustc_hir::WherePredicate<'_x>; ], $tcx); ) } diff --git a/src/librustc_infer/infer/canonical/query_response.rs b/src/librustc_infer/infer/canonical/query_response.rs index ab2393918c354..8af526e3ad31b 100644 --- a/src/librustc_infer/infer/canonical/query_response.rs +++ b/src/librustc_infer/infer/canonical/query_response.rs @@ -56,7 +56,7 @@ impl<'cx, 'tcx> InferCtxt<'cx, 'tcx> { ) -> Fallible> where T: Debug + TypeFoldable<'tcx>, - Canonical<'tcx, QueryResponse<'tcx, T>>: ArenaAllocatable, + Canonical<'tcx, QueryResponse<'tcx, T>>: ArenaAllocatable<'tcx>, { let query_response = self.make_query_response(inference_vars, answer, fulfill_cx)?; let canonical_result = self.canonicalize_response(&query_response); diff --git a/src/librustc_macros/src/query.rs b/src/librustc_macros/src/query.rs index 41a49a38a19cf..c17d5311e8fe6 100644 --- a/src/librustc_macros/src/query.rs +++ b/src/librustc_macros/src/query.rs @@ -433,7 +433,7 @@ pub fn rustc_queries(input: TokenStream) -> TokenStream { try_load_from_on_disk_cache_stream.extend(quote! { ::rustc_middle::dep_graph::DepKind::#name => { - if <#arg as DepNodeParams>>::CAN_RECONSTRUCT_QUERY_KEY { + if <#arg as DepNodeParams>>::can_reconstruct_query_key() { debug_assert!($tcx.dep_graph .node_color($dep_node) .map(|c| c.is_green()) @@ -490,7 +490,7 @@ pub fn rustc_queries(input: TokenStream) -> TokenStream { // Add a match arm to force the query given the dep node dep_node_force_stream.extend(quote! { ::rustc_middle::dep_graph::DepKind::#name => { - if <#arg as DepNodeParams>>::CAN_RECONSTRUCT_QUERY_KEY { + if <#arg as DepNodeParams>>::can_reconstruct_query_key() { if let Some(key) = <#arg as DepNodeParams>>::recover($tcx, $dep_node) { force_query::, _>( $tcx, diff --git a/src/librustc_metadata/lib.rs b/src/librustc_metadata/lib.rs index 2a2169880a54e..76e39a476c6d8 100644 --- a/src/librustc_metadata/lib.rs +++ b/src/librustc_metadata/lib.rs @@ -7,7 +7,7 @@ #![feature(nll)] #![feature(or_patterns)] #![feature(proc_macro_internals)] -#![feature(specialization)] // FIXME: min_specialization ICEs +#![feature(min_specialization)] #![feature(stmt_expr_attributes)] #![recursion_limit = "256"] diff --git a/src/librustc_metadata/rmeta/decoder.rs b/src/librustc_metadata/rmeta/decoder.rs index f5a9dceb78295..fdb5daa985529 100644 --- a/src/librustc_metadata/rmeta/decoder.rs +++ b/src/librustc_metadata/rmeta/decoder.rs @@ -30,7 +30,7 @@ use rustc_middle::mir::{self, interpret, Body, Promoted}; use rustc_middle::ty::codec::TyDecoder; use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_middle::util::common::record_time; -use rustc_serialize::{opaque, Decodable, Decoder, SpecializedDecoder}; +use rustc_serialize::{opaque, Decodable, Decoder, SpecializedDecoder, UseSpecializedDecodable}; use rustc_session::Session; use rustc_span::source_map::{respan, Spanned}; use rustc_span::symbol::{sym, Ident, Symbol}; @@ -218,7 +218,7 @@ impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a CrateMetadataRef<'a>, TyCtxt<'tcx>) { } } -impl<'a, 'tcx, T: Decodable> Lazy { +impl<'a, 'tcx, T: Decodable> Lazy { fn decode>(self, metadata: M) -> T { let mut dcx = metadata.decoder(self.position.get()); dcx.lazy_state = LazyState::NodeStart(self.position); @@ -226,7 +226,7 @@ impl<'a, 'tcx, T: Decodable> Lazy { } } -impl<'a: 'x, 'tcx: 'x, 'x, T: Decodable> Lazy<[T]> { +impl<'a: 'x, 'tcx: 'x, 'x, T: Decodable> Lazy<[T], usize> { fn decode>( self, metadata: M, @@ -321,20 +321,20 @@ impl<'a, 'tcx> TyDecoder<'tcx> for DecodeContext<'a, 'tcx> { } } -impl<'a, 'tcx, T> SpecializedDecoder> for DecodeContext<'a, 'tcx> { +impl<'a, 'tcx, T> SpecializedDecoder> for DecodeContext<'a, 'tcx> { fn specialized_decode(&mut self) -> Result, Self::Error> { self.read_lazy_with_meta(()) } } -impl<'a, 'tcx, T> SpecializedDecoder> for DecodeContext<'a, 'tcx> { +impl<'a, 'tcx, T> SpecializedDecoder> for DecodeContext<'a, 'tcx> { fn specialized_decode(&mut self) -> Result, Self::Error> { let len = self.read_usize()?; if len == 0 { Ok(Lazy::empty()) } else { self.read_lazy_with_meta(len) } } } -impl<'a, 'tcx, I: Idx, T> SpecializedDecoder>> for DecodeContext<'a, 'tcx> +impl<'a, 'tcx, I: Idx, T> SpecializedDecoder, usize>> for DecodeContext<'a, 'tcx> where Option: FixedSizeEncoding, { @@ -515,8 +515,9 @@ impl<'a, 'tcx> SpecializedDecoder for DecodeContext<'a, 'tcx> { } } -impl<'a, 'tcx, T: Decodable> SpecializedDecoder> - for DecodeContext<'a, 'tcx> +impl<'a, 'tcx, T> SpecializedDecoder> for DecodeContext<'a, 'tcx> +where + mir::ClearCrossCrate: UseSpecializedDecodable, { #[inline] fn specialized_decode(&mut self) -> Result, Self::Error> { diff --git a/src/librustc_metadata/rmeta/encoder.rs b/src/librustc_metadata/rmeta/encoder.rs index 64ccd46a744f5..1258e02bcd4bc 100644 --- a/src/librustc_metadata/rmeta/encoder.rs +++ b/src/librustc_metadata/rmeta/encoder.rs @@ -27,7 +27,7 @@ use rustc_middle::mir::{self, interpret}; use rustc_middle::traits::specialization_graph; use rustc_middle::ty::codec::{self as ty_codec, TyEncoder}; use rustc_middle::ty::{self, SymbolName, Ty, TyCtxt}; -use rustc_serialize::{opaque, Encodable, Encoder, SpecializedEncoder}; +use rustc_serialize::{opaque, Encodable, Encoder, SpecializedEncoder, UseSpecializedEncodable}; use rustc_session::config::CrateType; use rustc_span::source_map::Spanned; use rustc_span::symbol::{kw, sym, Ident, Symbol}; @@ -93,13 +93,13 @@ impl<'tcx> Encoder for EncodeContext<'tcx> { } } -impl<'tcx, T> SpecializedEncoder> for EncodeContext<'tcx> { +impl<'tcx, T> SpecializedEncoder> for EncodeContext<'tcx> { fn specialized_encode(&mut self, lazy: &Lazy) -> Result<(), Self::Error> { self.emit_lazy_distance(*lazy) } } -impl<'tcx, T> SpecializedEncoder> for EncodeContext<'tcx> { +impl<'tcx, T> SpecializedEncoder> for EncodeContext<'tcx> { fn specialized_encode(&mut self, lazy: &Lazy<[T]>) -> Result<(), Self::Error> { self.emit_usize(lazy.meta)?; if lazy.meta == 0 { @@ -109,7 +109,7 @@ impl<'tcx, T> SpecializedEncoder> for EncodeContext<'tcx> { } } -impl<'tcx, I: Idx, T> SpecializedEncoder>> for EncodeContext<'tcx> +impl<'tcx, I: Idx, T> SpecializedEncoder, usize>> for EncodeContext<'tcx> where Option: FixedSizeEncoding, { @@ -228,8 +228,13 @@ impl<'tcx> SpecializedEncoder for EncodeContext<'tcx> { } } -impl<'tcx> SpecializedEncoder> for EncodeContext<'tcx> { - fn specialized_encode(&mut self, ty: &Ty<'tcx>) -> Result<(), Self::Error> { +impl<'a, 'b, 'tcx> SpecializedEncoder<&'a ty::TyS<'b>> for EncodeContext<'tcx> +where + &'a ty::TyS<'b>: UseSpecializedEncodable, +{ + fn specialized_encode(&mut self, ty: &&'a ty::TyS<'b>) -> Result<(), Self::Error> { + debug_assert!(self.tcx.lift(ty).is_some()); + let ty = unsafe { std::mem::transmute::<&&'a ty::TyS<'b>, &&'tcx ty::TyS<'tcx>>(ty) }; ty_codec::encode_with_shorthand(self, ty, |ecx| &mut ecx.type_shorthands) } } @@ -251,12 +256,19 @@ impl<'tcx> SpecializedEncoder for EncodeContext<'tcx> { } } -impl<'tcx> SpecializedEncoder<&'tcx [(ty::Predicate<'tcx>, Span)]> for EncodeContext<'tcx> { +impl<'a, 'b, 'tcx> SpecializedEncoder<&'a [(ty::Predicate<'b>, Span)]> for EncodeContext<'tcx> { fn specialized_encode( &mut self, - predicates: &&'tcx [(ty::Predicate<'tcx>, Span)], + predicates: &&'a [(ty::Predicate<'b>, Span)], ) -> Result<(), Self::Error> { - ty_codec::encode_spanned_predicates(self, predicates, |ecx| &mut ecx.predicate_shorthands) + debug_assert!(self.tcx.lift(*predicates).is_some()); + let predicates = unsafe { + std::mem::transmute::< + &&'a [(ty::Predicate<'b>, Span)], + &&'tcx [(ty::Predicate<'tcx>, Span)], + >(predicates) + }; + ty_codec::encode_spanned_predicates(self, &predicates, |ecx| &mut ecx.predicate_shorthands) } } @@ -266,7 +278,10 @@ impl<'tcx> SpecializedEncoder for EncodeContext<'tcx> { } } -impl<'tcx, T: Encodable> SpecializedEncoder> for EncodeContext<'tcx> { +impl<'tcx, T> SpecializedEncoder> for EncodeContext<'tcx> +where + mir::ClearCrossCrate: UseSpecializedEncodable, +{ fn specialized_encode(&mut self, _: &mir::ClearCrossCrate) -> Result<(), Self::Error> { Ok(()) } diff --git a/src/librustc_middle/arena.rs b/src/librustc_middle/arena.rs index 75228350c6c45..f861d63aba0f3 100644 --- a/src/librustc_middle/arena.rs +++ b/src/librustc_middle/arena.rs @@ -11,79 +11,109 @@ macro_rules! arena_types { ($macro:path, $args:tt, $tcx:lifetime) => ( $macro!($args, [ - [] layouts: rustc_target::abi::Layout, + [] layouts: rustc_target::abi::Layout, rustc_target::abi::Layout; // AdtDef are interned and compared by address - [] adt_def: rustc_middle::ty::AdtDef, - [decode] tables: rustc_middle::ty::TypeckTables<$tcx>, - [] const_allocs: rustc_middle::mir::interpret::Allocation, + [] adt_def: rustc_middle::ty::AdtDef, rustc_middle::ty::AdtDef; + [decode] tables: rustc_middle::ty::TypeckTables<$tcx>, rustc_middle::ty::TypeckTables<'_x>; + [] const_allocs: rustc_middle::mir::interpret::Allocation, rustc_middle::mir::interpret::Allocation; // Required for the incremental on-disk cache - [few, decode] mir_keys: rustc_hir::def_id::DefIdSet, - [] region_scope_tree: rustc_middle::middle::region::ScopeTree, + [few, decode] mir_keys: rustc_hir::def_id::DefIdSet, rustc_hir::def_id::DefIdSet; + [] region_scope_tree: rustc_middle::middle::region::ScopeTree, rustc_middle::middle::region::ScopeTree; [] dropck_outlives: rustc_middle::infer::canonical::Canonical<'tcx, rustc_middle::infer::canonical::QueryResponse<'tcx, rustc_middle::traits::query::DropckOutlivesResult<'tcx> > >, + rustc_middle::infer::canonical::Canonical<'_x, + rustc_middle::infer::canonical::QueryResponse<'_y, + rustc_middle::traits::query::DropckOutlivesResult<'_z> + > + >; [] normalize_projection_ty: rustc_middle::infer::canonical::Canonical<'tcx, rustc_middle::infer::canonical::QueryResponse<'tcx, rustc_middle::traits::query::NormalizationResult<'tcx> > >, + rustc_middle::infer::canonical::Canonical<'_x, + rustc_middle::infer::canonical::QueryResponse<'_y, + rustc_middle::traits::query::NormalizationResult<'_z> + > + >; [] implied_outlives_bounds: rustc_middle::infer::canonical::Canonical<'tcx, rustc_middle::infer::canonical::QueryResponse<'tcx, Vec> > >, + rustc_middle::infer::canonical::Canonical<'_x, + rustc_middle::infer::canonical::QueryResponse<'_y, + Vec> + > + >; [] type_op_subtype: rustc_middle::infer::canonical::Canonical<'tcx, rustc_middle::infer::canonical::QueryResponse<'tcx, ()> >, + rustc_middle::infer::canonical::Canonical<'_x, + rustc_middle::infer::canonical::QueryResponse<'_y, ()> + >; [] type_op_normalize_poly_fn_sig: rustc_middle::infer::canonical::Canonical<'tcx, rustc_middle::infer::canonical::QueryResponse<'tcx, rustc_middle::ty::PolyFnSig<'tcx>> >, + rustc_middle::infer::canonical::Canonical<'_x, + rustc_middle::infer::canonical::QueryResponse<'_y, rustc_middle::ty::PolyFnSig<'_z>> + >; [] type_op_normalize_fn_sig: rustc_middle::infer::canonical::Canonical<'tcx, rustc_middle::infer::canonical::QueryResponse<'tcx, rustc_middle::ty::FnSig<'tcx>> >, + rustc_middle::infer::canonical::Canonical<'_x, + rustc_middle::infer::canonical::QueryResponse<'_y, rustc_middle::ty::FnSig<'_z>> + >; [] type_op_normalize_predicate: rustc_middle::infer::canonical::Canonical<'tcx, rustc_middle::infer::canonical::QueryResponse<'tcx, rustc_middle::ty::Predicate<'tcx>> >, + rustc_middle::infer::canonical::Canonical<'_x, + rustc_middle::infer::canonical::QueryResponse<'_y, rustc_middle::ty::Predicate<'_z>> + >; [] type_op_normalize_ty: rustc_middle::infer::canonical::Canonical<'tcx, rustc_middle::infer::canonical::QueryResponse<'tcx, rustc_middle::ty::Ty<'tcx>> >, - [few] all_traits: Vec, - [few] privacy_access_levels: rustc_middle::middle::privacy::AccessLevels, - [few] foreign_module: rustc_middle::middle::cstore::ForeignModule, - [few] foreign_modules: Vec, - [] upvars_mentioned: rustc_data_structures::fx::FxIndexMap, - [] object_safety_violations: rustc_middle::traits::ObjectSafetyViolation, - [] codegen_unit: rustc_middle::mir::mono::CodegenUnit<$tcx>, - [] attribute: rustc_ast::ast::Attribute, - [] name_set: rustc_data_structures::fx::FxHashSet, - [] hir_id_set: rustc_hir::HirIdSet, + rustc_middle::infer::canonical::Canonical<'_x, + rustc_middle::infer::canonical::QueryResponse<'_y, &'_z rustc_middle::ty::TyS<'_w>> + >; + [few] all_traits: Vec, Vec; + [few] privacy_access_levels: rustc_middle::middle::privacy::AccessLevels, rustc_middle::middle::privacy::AccessLevels; + [few] foreign_module: rustc_middle::middle::cstore::ForeignModule, rustc_middle::middle::cstore::ForeignModule; + [few] foreign_modules: Vec, Vec; + [] upvars_mentioned: rustc_data_structures::fx::FxIndexMap, rustc_data_structures::fx::FxIndexMap; + [] object_safety_violations: rustc_middle::traits::ObjectSafetyViolation, rustc_middle::traits::ObjectSafetyViolation; + [] codegen_unit: rustc_middle::mir::mono::CodegenUnit<$tcx>, rustc_middle::mir::mono::CodegenUnit<'_x>; + [] attribute: rustc_ast::ast::Attribute, rustc_ast::ast::Attribute; + [] name_set: rustc_data_structures::fx::FxHashSet, rustc_data_structures::fx::FxHashSet; + [] hir_id_set: rustc_hir::HirIdSet, rustc_hir::HirIdSet; // Interned types - [] tys: rustc_middle::ty::TyS<$tcx>, + [] tys: rustc_middle::ty::TyS<$tcx>, rustc_middle::ty::TyS<'_x>; // HIR query types - [few] indexed_hir: rustc_middle::hir::map::IndexedHir<$tcx>, - [few] hir_definitions: rustc_hir::definitions::Definitions, - [] hir_owner: rustc_middle::hir::Owner<$tcx>, - [] hir_owner_nodes: rustc_middle::hir::OwnerNodes<$tcx>, + [few] indexed_hir: rustc_middle::hir::map::IndexedHir<$tcx>, rustc_middle::hir::map::IndexedHir<'_x>; + [few] hir_definitions: rustc_hir::definitions::Definitions, rustc_hir::definitions::Definitions; + [] hir_owner: rustc_middle::hir::Owner<$tcx>, rustc_middle::hir::Owner<'_x>; + [] hir_owner_nodes: rustc_middle::hir::OwnerNodes<$tcx>, rustc_middle::hir::OwnerNodes<'_x>; // Note that this deliberately duplicates items in the `rustc_hir::arena`, // since we need to allocate this type on both the `rustc_hir` arena // (during lowering) and the `librustc_middle` arena (for decoding MIR) - [decode] asm_template: rustc_ast::ast::InlineAsmTemplatePiece, + [decode] asm_template: rustc_ast::ast::InlineAsmTemplatePiece, rustc_ast::ast::InlineAsmTemplatePiece; // This is used to decode the &'tcx [Span] for InlineAsm's line_spans. - [decode] span: rustc_span::Span, + [decode] span: rustc_span::Span, rustc_span::Span; ], $tcx); ) } diff --git a/src/librustc_middle/dep_graph/dep_node.rs b/src/librustc_middle/dep_graph/dep_node.rs index 2c0524fa99102..b14f17dee6060 100644 --- a/src/librustc_middle/dep_graph/dep_node.rs +++ b/src/librustc_middle/dep_graph/dep_node.rs @@ -128,7 +128,7 @@ macro_rules! define_dep_nodes { // tuple args $({ return <$tuple_arg_ty as DepNodeParams>> - ::CAN_RECONSTRUCT_QUERY_KEY; + ::can_reconstruct_query_key(); })* true @@ -304,7 +304,10 @@ rustc_dep_node_append!([define_dep_nodes!][ <'tcx> ]); impl<'tcx> DepNodeParams> for DefId { - const CAN_RECONSTRUCT_QUERY_KEY: bool = true; + #[inline] + fn can_reconstruct_query_key() -> bool { + true + } fn to_fingerprint(&self, tcx: TyCtxt<'tcx>) -> Fingerprint { tcx.def_path_hash(*self).0 @@ -320,7 +323,10 @@ impl<'tcx> DepNodeParams> for DefId { } impl<'tcx> DepNodeParams> for LocalDefId { - const CAN_RECONSTRUCT_QUERY_KEY: bool = true; + #[inline] + fn can_reconstruct_query_key() -> bool { + true + } fn to_fingerprint(&self, tcx: TyCtxt<'tcx>) -> Fingerprint { self.to_def_id().to_fingerprint(tcx) @@ -336,7 +342,10 @@ impl<'tcx> DepNodeParams> for LocalDefId { } impl<'tcx> DepNodeParams> for CrateNum { - const CAN_RECONSTRUCT_QUERY_KEY: bool = true; + #[inline] + fn can_reconstruct_query_key() -> bool { + true + } fn to_fingerprint(&self, tcx: TyCtxt<'tcx>) -> Fingerprint { let def_id = DefId { krate: *self, index: CRATE_DEF_INDEX }; @@ -353,7 +362,10 @@ impl<'tcx> DepNodeParams> for CrateNum { } impl<'tcx> DepNodeParams> for (DefId, DefId) { - const CAN_RECONSTRUCT_QUERY_KEY: bool = false; + #[inline] + fn can_reconstruct_query_key() -> bool { + false + } // We actually would not need to specialize the implementation of this // method but it's faster to combine the hashes than to instantiate a full @@ -375,7 +387,10 @@ impl<'tcx> DepNodeParams> for (DefId, DefId) { } impl<'tcx> DepNodeParams> for HirId { - const CAN_RECONSTRUCT_QUERY_KEY: bool = false; + #[inline] + fn can_reconstruct_query_key() -> bool { + false + } // We actually would not need to specialize the implementation of this // method but it's faster to combine the hashes than to instantiate a full diff --git a/src/librustc_middle/lib.rs b/src/librustc_middle/lib.rs index 7c433574d1843..62c92e988ba60 100644 --- a/src/librustc_middle/lib.rs +++ b/src/librustc_middle/lib.rs @@ -42,7 +42,7 @@ #![feature(option_expect_none)] #![feature(or_patterns)] #![feature(range_is_empty)] -#![feature(specialization)] // FIXME: min_specialization does not work +#![feature(min_specialization)] #![feature(track_caller)] #![feature(trusted_len)] #![feature(vec_remove_item)] diff --git a/src/librustc_middle/mir/mod.rs b/src/librustc_middle/mir/mod.rs index 98973f1b6fb7d..f159b82536fe2 100644 --- a/src/librustc_middle/mir/mod.rs +++ b/src/librustc_middle/mir/mod.rs @@ -457,8 +457,39 @@ impl ClearCrossCrate { } } -impl rustc_serialize::UseSpecializedEncodable for ClearCrossCrate {} -impl rustc_serialize::UseSpecializedDecodable for ClearCrossCrate {} +const TAG_CLEAR_CROSS_CRATE_CLEAR: u8 = 0; +const TAG_CLEAR_CROSS_CRATE_SET: u8 = 1; + +impl rustc_serialize::UseSpecializedEncodable for ClearCrossCrate { + #[inline] + fn default_encode(&self, e: &mut E) -> Result<(), E::Error> { + match *self { + ClearCrossCrate::Clear => TAG_CLEAR_CROSS_CRATE_CLEAR.encode(e), + ClearCrossCrate::Set(ref val) => { + TAG_CLEAR_CROSS_CRATE_SET.encode(e)?; + val.encode(e) + } + } + } +} +impl rustc_serialize::UseSpecializedDecodable for ClearCrossCrate { + #[inline] + fn default_decode(d: &mut D) -> Result, D::Error> + where + D: rustc_serialize::Decoder, + { + let discr = u8::decode(d)?; + + match discr { + TAG_CLEAR_CROSS_CRATE_CLEAR => Ok(ClearCrossCrate::Clear), + TAG_CLEAR_CROSS_CRATE_SET => { + let val = T::decode(d)?; + Ok(ClearCrossCrate::Set(val)) + } + _ => unreachable!(), + } + } +} /// Grouped information about the source code origin of a MIR entity. /// Intended to be inspected by diagnostics and debuginfo. @@ -1952,8 +1983,6 @@ impl ProjectionElem { /// and the index is a local. pub type PlaceElem<'tcx> = ProjectionElem>; -impl<'tcx> Copy for PlaceElem<'tcx> {} - // At least on 64 bit systems, `PlaceElem` should not be larger than two pointers. #[cfg(target_arch = "x86_64")] static_assert_size!(PlaceElem<'_>, 16); diff --git a/src/librustc_middle/ty/codec.rs b/src/librustc_middle/ty/codec.rs index 8bc69a9d12312..1a8e5c45dd2f7 100644 --- a/src/librustc_middle/ty/codec.rs +++ b/src/librustc_middle/ty/codec.rs @@ -97,7 +97,7 @@ where pub fn encode_spanned_predicates<'tcx, E, C>( encoder: &mut E, - predicates: &'tcx [(ty::Predicate<'tcx>, Span)], + predicates: &[(ty::Predicate<'tcx>, Span)], cache: C, ) -> Result<(), E::Error> where @@ -139,7 +139,7 @@ pub trait TyDecoder<'tcx>: Decoder { } #[inline] -pub fn decode_arena_allocable( +pub fn decode_arena_allocable<'tcx, D, T: ArenaAllocatable<'tcx> + Decodable>( decoder: &mut D, ) -> Result<&'tcx T, D::Error> where @@ -149,7 +149,7 @@ where } #[inline] -pub fn decode_arena_allocable_slice( +pub fn decode_arena_allocable_slice<'tcx, D, T: ArenaAllocatable<'tcx> + Decodable>( decoder: &mut D, ) -> Result<&'tcx [T], D::Error> where @@ -318,18 +318,38 @@ macro_rules! __impl_decoder_methods { macro_rules! impl_arena_allocatable_decoder { ([]$args:tt) => {}; ([decode $(, $attrs:ident)*] - [[$DecoderName:ident [$($typaram:tt),*]], [$name:ident: $ty:ty], $tcx:lifetime]) => { - impl<$($typaram),*> SpecializedDecoder<&$tcx $ty> for $DecoderName<$($typaram),*> { + [[$DecoderName:ident [$($typaram:tt),*]], [$name:ident: $ty:ty, $gen_ty:ty], $tcx:lifetime]) => { + // FIXME(#36588): These impls are horribly unsound as they allow + // the caller to pick any lifetime for `'tcx`, including `'static`. + #[allow(unused_lifetimes)] + impl<'_x, '_y, '_z, '_w, '_a, $($typaram),*> SpecializedDecoder<&'_a $gen_ty> + for $DecoderName<$($typaram),*> + where &'_a $gen_ty: UseSpecializedDecodable + { #[inline] - fn specialized_decode(&mut self) -> Result<&$tcx $ty, Self::Error> { - decode_arena_allocable(self) + fn specialized_decode(&mut self) -> Result<&'_a $gen_ty, Self::Error> { + unsafe { + std::mem::transmute::< + Result<&$tcx $ty, Self::Error>, + Result<&'_a $gen_ty, Self::Error>, + >(decode_arena_allocable(self)) + } } } - impl<$($typaram),*> SpecializedDecoder<&$tcx [$ty]> for $DecoderName<$($typaram),*> { + #[allow(unused_lifetimes)] + impl<'_x, '_y, '_z, '_w, '_a, $($typaram),*> SpecializedDecoder<&'_a [$gen_ty]> + for $DecoderName<$($typaram),*> + where &'_a [$gen_ty]: UseSpecializedDecodable + { #[inline] - fn specialized_decode(&mut self) -> Result<&$tcx [$ty], Self::Error> { - decode_arena_allocable_slice(self) + fn specialized_decode(&mut self) -> Result<&'_a [$gen_ty], Self::Error> { + unsafe { + std::mem::transmute::< + Result<&$tcx [$ty], Self::Error>, + Result<&'_a [$gen_ty], Self::Error>, + >(decode_arena_allocable_slice(self)) + } } } }; @@ -340,9 +360,9 @@ macro_rules! impl_arena_allocatable_decoder { #[macro_export] macro_rules! impl_arena_allocatable_decoders { - ($args:tt, [$($a:tt $name:ident: $ty:ty,)*], $tcx:lifetime) => { + ($args:tt, [$($a:tt $name:ident: $ty:ty, $gen_ty:ty;)*], $tcx:lifetime) => { $( - impl_arena_allocatable_decoder!($a [$args, [$name: $ty], $tcx]); + impl_arena_allocatable_decoder!($a [$args, [$name: $ty, $gen_ty], $tcx]); )* } } @@ -352,14 +372,15 @@ macro_rules! implement_ty_decoder { ($DecoderName:ident <$($typaram:tt),*>) => { mod __ty_decoder_impl { use std::borrow::Cow; + use std::mem::transmute; - use rustc_serialize::{Decoder, SpecializedDecoder}; + use rustc_serialize::{Decoder, SpecializedDecoder, UseSpecializedDecodable}; use $crate::infer::canonical::CanonicalVarInfos; use $crate::ty; use $crate::ty::codec::*; - use $crate::ty::subst::SubstsRef; - use rustc_hir::def_id::{CrateNum}; + use $crate::ty::subst::InternalSubsts; + use rustc_hir::def_id::CrateNum; use rustc_span::Span; @@ -398,8 +419,7 @@ macro_rules! implement_ty_decoder { } // FIXME(#36588): These impls are horribly unsound as they allow - // the caller to pick any lifetime for `'tcx`, including `'static`, - // by using the unspecialized proxies to them. + // the caller to pick any lifetime for `'tcx`, including `'static`. rustc_hir::arena_types!(impl_arena_allocatable_decoders, [$DecoderName [$($typaram),*]], 'tcx); arena_types!(impl_arena_allocatable_decoders, [$DecoderName [$($typaram),*]], 'tcx); @@ -411,90 +431,98 @@ macro_rules! implement_ty_decoder { } } - impl<$($typaram),*> SpecializedDecoder> - for $DecoderName<$($typaram),*> { - fn specialized_decode(&mut self) -> Result, Self::Error> { - decode_ty(self) + impl<'_x, '_y, $($typaram),*> SpecializedDecoder<&'_x ty::TyS<'_y>> + for $DecoderName<$($typaram),*> + where &'_x ty::TyS<'_y>: UseSpecializedDecodable + { + fn specialized_decode(&mut self) -> Result<&'_x ty::TyS<'_y>, Self::Error> { + unsafe { transmute::, Self::Error>, Result<&'_x ty::TyS<'_y>, Self::Error>>(decode_ty(self)) } } } - impl<$($typaram),*> SpecializedDecoder<&'tcx [(ty::Predicate<'tcx>, Span)]> - for $DecoderName<$($typaram),*> { + impl<'_x, '_y, $($typaram),*> SpecializedDecoder<&'_x [(ty::Predicate<'_y>, Span)]> + for $DecoderName<$($typaram),*> + where &'_x [(ty::Predicate<'_y>, Span)]: UseSpecializedDecodable { fn specialized_decode(&mut self) - -> Result<&'tcx [(ty::Predicate<'tcx>, Span)], Self::Error> { - decode_spanned_predicates(self) + -> Result<&'_x [(ty::Predicate<'_y>, Span)], Self::Error> + { + unsafe { transmute(decode_spanned_predicates(self)) } } } - impl<$($typaram),*> SpecializedDecoder> - for $DecoderName<$($typaram),*> { - fn specialized_decode(&mut self) -> Result, Self::Error> { - decode_substs(self) + impl<'_x, '_y, $($typaram),*> SpecializedDecoder<&'_x InternalSubsts<'_y>> + for $DecoderName<$($typaram),*> + where &'_x InternalSubsts<'_y>: UseSpecializedDecodable { + fn specialized_decode(&mut self) -> Result<&'_x InternalSubsts<'_y>, Self::Error> { + unsafe { transmute(decode_substs(self)) } } } - impl<$($typaram),*> SpecializedDecoder<$crate::mir::Place<'tcx>> + impl<'_x, $($typaram),*> SpecializedDecoder<$crate::mir::Place<'_x>> for $DecoderName<$($typaram),*> { fn specialized_decode( &mut self - ) -> Result<$crate::mir::Place<'tcx>, Self::Error> { - decode_place(self) + ) -> Result<$crate::mir::Place<'_x>, Self::Error> { + unsafe { transmute(decode_place(self)) } } } - impl<$($typaram),*> SpecializedDecoder> + impl<'_x, $($typaram),*> SpecializedDecoder> for $DecoderName<$($typaram),*> { - fn specialized_decode(&mut self) -> Result, Self::Error> { - decode_region(self) + fn specialized_decode(&mut self) -> Result, Self::Error> { + unsafe { transmute(decode_region(self)) } } } - impl<$($typaram),*> SpecializedDecoder<&'tcx ty::List>> - for $DecoderName<$($typaram),*> { + impl<'_x, '_y, '_z, $($typaram),*> SpecializedDecoder<&'_x ty::List<&'_y ty::TyS<'_z>>> + for $DecoderName<$($typaram),*> + where &'_x ty::List<&'_y ty::TyS<'_z>>: UseSpecializedDecodable { fn specialized_decode(&mut self) - -> Result<&'tcx ty::List>, Self::Error> { - decode_ty_slice(self) + -> Result<&'_x ty::List<&'_y ty::TyS<'_z>>, Self::Error> { + unsafe { transmute(decode_ty_slice(self)) } } } - impl<$($typaram),*> SpecializedDecoder<&'tcx ty::AdtDef> + impl<'_x, $($typaram),*> SpecializedDecoder<&'_x ty::AdtDef> for $DecoderName<$($typaram),*> { - fn specialized_decode(&mut self) -> Result<&'tcx ty::AdtDef, Self::Error> { - decode_adt_def(self) + fn specialized_decode(&mut self) -> Result<&'_x ty::AdtDef, Self::Error> { + unsafe { transmute(decode_adt_def(self)) } } } - impl<$($typaram),*> SpecializedDecoder<&'tcx ty::List>> - for $DecoderName<$($typaram),*> { + impl<'_x, '_y, $($typaram),*> SpecializedDecoder<&'_x ty::List>> + for $DecoderName<$($typaram),*> + where &'_x ty::List>: UseSpecializedDecodable { fn specialized_decode(&mut self) - -> Result<&'tcx ty::List>, Self::Error> { - decode_existential_predicate_slice(self) + -> Result<&'_x ty::List>, Self::Error> { + unsafe { transmute(decode_existential_predicate_slice(self)) } } } - impl<$($typaram),*> SpecializedDecoder> + impl<'_x, $($typaram),*> SpecializedDecoder> for $DecoderName<$($typaram),*> { fn specialized_decode(&mut self) - -> Result, Self::Error> { - decode_canonical_var_infos(self) + -> Result, Self::Error> { + unsafe { transmute(decode_canonical_var_infos(self)) } } } - impl<$($typaram),*> SpecializedDecoder<&'tcx $crate::ty::Const<'tcx>> - for $DecoderName<$($typaram),*> { - fn specialized_decode(&mut self) -> Result<&'tcx ty::Const<'tcx>, Self::Error> { - decode_const(self) + impl<'_x, '_y, $($typaram),*> SpecializedDecoder<&'_x $crate::ty::Const<'_y>> + for $DecoderName<$($typaram),*> + where &'_x $crate::ty::Const<'_y>: UseSpecializedDecodable { + fn specialized_decode(&mut self) -> Result<&'_x ty::Const<'_y>, Self::Error> { + unsafe { transmute(decode_const(self)) } } } - impl<$($typaram),*> SpecializedDecoder<&'tcx $crate::mir::interpret::Allocation> + impl<'_x, $($typaram),*> SpecializedDecoder<&'_x $crate::mir::interpret::Allocation> for $DecoderName<$($typaram),*> { fn specialized_decode( &mut self - ) -> Result<&'tcx $crate::mir::interpret::Allocation, Self::Error> { - decode_allocation(self) + ) -> Result<&'_x $crate::mir::interpret::Allocation, Self::Error> { + unsafe { transmute(decode_allocation(self)) } } } } - } + }; } diff --git a/src/librustc_middle/ty/query/on_disk_cache.rs b/src/librustc_middle/ty/query/on_disk_cache.rs index 4eae06742d9d3..5374dff422425 100644 --- a/src/librustc_middle/ty/query/on_disk_cache.rs +++ b/src/librustc_middle/ty/query/on_disk_cache.rs @@ -1,6 +1,6 @@ use crate::dep_graph::{DepNodeIndex, SerializedDepNodeIndex}; +use crate::mir::interpret; use crate::mir::interpret::{AllocDecodingSession, AllocDecodingState}; -use crate::mir::{self, interpret}; use crate::ty::codec::{self as ty_codec, TyDecoder, TyEncoder}; use crate::ty::context::TyCtxt; use crate::ty::{self, Ty}; @@ -26,9 +26,6 @@ use std::mem; const TAG_FILE_FOOTER: u128 = 0xC0FFEE_C0FFEE_C0FFEE_C0FFEE_C0FFEE; -const TAG_CLEAR_CROSS_CRATE_CLEAR: u8 = 0; -const TAG_CLEAR_CROSS_CRATE_SET: u8 = 1; - const TAG_NO_EXPN_DATA: u8 = 0; const TAG_EXPN_DATA_SHORTHAND: u8 = 1; const TAG_EXPN_DATA_INLINE: u8 = 2; @@ -667,24 +664,6 @@ impl<'a, 'tcx> SpecializedDecoder for CacheDecoder<'a, 'tcx> { } } -impl<'a, 'tcx, T: Decodable> SpecializedDecoder> - for CacheDecoder<'a, 'tcx> -{ - #[inline] - fn specialized_decode(&mut self) -> Result, Self::Error> { - let discr = u8::decode(self)?; - - match discr { - TAG_CLEAR_CROSS_CRATE_CLEAR => Ok(mir::ClearCrossCrate::Clear), - TAG_CLEAR_CROSS_CRATE_SET => { - let val = T::decode(self)?; - Ok(mir::ClearCrossCrate::Set(val)) - } - _ => unreachable!(), - } - } -} - //- ENCODING ------------------------------------------------------------------- /// An encoder that can write the incr. comp. cache. @@ -828,17 +807,20 @@ where } } -impl<'a, 'tcx, E> SpecializedEncoder> for CacheEncoder<'a, 'tcx, E> +impl<'a, 'b, 'c, 'tcx, E> SpecializedEncoder<&'b ty::TyS<'c>> for CacheEncoder<'a, 'tcx, E> where E: 'a + TyEncoder, + &'b ty::TyS<'c>: UseSpecializedEncodable, { #[inline] - fn specialized_encode(&mut self, ty: &Ty<'tcx>) -> Result<(), Self::Error> { + fn specialized_encode(&mut self, ty: &&'b ty::TyS<'c>) -> Result<(), Self::Error> { + debug_assert!(self.tcx.lift(ty).is_some()); + let ty = unsafe { std::mem::transmute::<&&'b ty::TyS<'c>, &&'tcx ty::TyS<'tcx>>(ty) }; ty_codec::encode_with_shorthand(self, ty, |encoder| &mut encoder.type_shorthands) } } -impl<'a, 'tcx, E> SpecializedEncoder<&'tcx [(ty::Predicate<'tcx>, Span)]> +impl<'a, 'b, 'c, 'tcx, E> SpecializedEncoder<&'b [(ty::Predicate<'c>, Span)]> for CacheEncoder<'a, 'tcx, E> where E: 'a + TyEncoder, @@ -846,8 +828,15 @@ where #[inline] fn specialized_encode( &mut self, - predicates: &&'tcx [(ty::Predicate<'tcx>, Span)], + predicates: &&'b [(ty::Predicate<'c>, Span)], ) -> Result<(), Self::Error> { + debug_assert!(self.tcx.lift(*predicates).is_some()); + let predicates = unsafe { + std::mem::transmute::< + &&'b [(ty::Predicate<'c>, Span)], + &&'tcx [(ty::Predicate<'tcx>, Span)], + >(predicates) + }; ty_codec::encode_spanned_predicates(self, predicates, |encoder| { &mut encoder.predicate_shorthands }) @@ -890,23 +879,6 @@ impl<'a, 'tcx> SpecializedEncoder for CacheEncoder<'a, 'tcx, opaque } } -impl<'a, 'tcx, E, T> SpecializedEncoder> for CacheEncoder<'a, 'tcx, E> -where - E: 'a + TyEncoder, - T: Encodable, -{ - #[inline] - fn specialized_encode(&mut self, val: &mir::ClearCrossCrate) -> Result<(), Self::Error> { - match *val { - mir::ClearCrossCrate::Clear => TAG_CLEAR_CROSS_CRATE_CLEAR.encode(self), - mir::ClearCrossCrate::Set(ref val) => { - TAG_CLEAR_CROSS_CRATE_SET.encode(self)?; - val.encode(self) - } - } - } -} - macro_rules! encoder_methods { ($($name:ident($ty:ty);)*) => { #[inline] @@ -995,7 +967,7 @@ fn encode_query_results<'a, 'tcx, Q, E>( query_result_index: &mut EncodedQueryResultIndex, ) -> Result<(), E::Error> where - Q: super::QueryDescription>, + Q: super::QueryDescription> + super::QueryAccessors>, Q::Value: Encodable, E: 'a + TyEncoder, { diff --git a/src/librustc_middle/ty/query/profiling_support.rs b/src/librustc_middle/ty/query/profiling_support.rs index e0d3e764dad83..3c44662441890 100644 --- a/src/librustc_middle/ty/query/profiling_support.rs +++ b/src/librustc_middle/ty/query/profiling_support.rs @@ -112,30 +112,53 @@ impl IntoSelfProfilingString for T { } } -impl IntoSelfProfilingString for DefId { +impl IntoSelfProfilingString for T { fn to_self_profile_string(&self, builder: &mut QueryKeyStringBuilder<'_, '_, '_>) -> StringId { + self.spec_to_self_profile_string(builder) + } +} + +#[rustc_specialization_trait] +pub trait SpecIntoSelfProfilingString: Debug { + fn spec_to_self_profile_string( + &self, + builder: &mut QueryKeyStringBuilder<'_, '_, '_>, + ) -> StringId; +} + +impl SpecIntoSelfProfilingString for DefId { + fn spec_to_self_profile_string( + &self, + builder: &mut QueryKeyStringBuilder<'_, '_, '_>, + ) -> StringId { builder.def_id_to_string_id(*self) } } -impl IntoSelfProfilingString for CrateNum { - fn to_self_profile_string(&self, builder: &mut QueryKeyStringBuilder<'_, '_, '_>) -> StringId { +impl SpecIntoSelfProfilingString for CrateNum { + fn spec_to_self_profile_string( + &self, + builder: &mut QueryKeyStringBuilder<'_, '_, '_>, + ) -> StringId { builder.def_id_to_string_id(DefId { krate: *self, index: CRATE_DEF_INDEX }) } } -impl IntoSelfProfilingString for DefIndex { - fn to_self_profile_string(&self, builder: &mut QueryKeyStringBuilder<'_, '_, '_>) -> StringId { +impl SpecIntoSelfProfilingString for DefIndex { + fn spec_to_self_profile_string( + &self, + builder: &mut QueryKeyStringBuilder<'_, '_, '_>, + ) -> StringId { builder.def_id_to_string_id(DefId { krate: LOCAL_CRATE, index: *self }) } } -impl IntoSelfProfilingString for (T0, T1) +impl SpecIntoSelfProfilingString for (T0, T1) where - T0: IntoSelfProfilingString + Debug, - T1: IntoSelfProfilingString + Debug, + T0: SpecIntoSelfProfilingString, + T1: SpecIntoSelfProfilingString, { - default fn to_self_profile_string( + fn spec_to_self_profile_string( &self, builder: &mut QueryKeyStringBuilder<'_, '_, '_>, ) -> StringId { diff --git a/src/librustc_middle/ty/query/values.rs b/src/librustc_middle/ty/query/values.rs index b01d15c29b2db..b1f76ff6a03bd 100644 --- a/src/librustc_middle/ty/query/values.rs +++ b/src/librustc_middle/ty/query/values.rs @@ -1,4 +1,4 @@ -use crate::ty::{self, AdtSizedConstraint, Ty, TyCtxt}; +use crate::ty::{self, AdtSizedConstraint, Ty, TyCtxt, TyS}; use rustc_span::symbol::Symbol; @@ -13,9 +13,11 @@ impl<'tcx, T> Value<'tcx> for T { } } -impl<'tcx> Value<'tcx> for Ty<'tcx> { - fn from_cycle_error(tcx: TyCtxt<'tcx>) -> Ty<'tcx> { - tcx.types.err +impl<'tcx> Value<'tcx> for &'_ TyS<'_> { + fn from_cycle_error(tcx: TyCtxt<'tcx>) -> Self { + // SAFETY: This is never called when `Self` is not `Ty<'tcx>`. + // FIXME: Represent the above fact in the trait system somehow. + unsafe { std::mem::transmute::, Ty<'_>>(tcx.types.err) } } } @@ -25,8 +27,14 @@ impl<'tcx> Value<'tcx> for ty::SymbolName { } } -impl<'tcx> Value<'tcx> for AdtSizedConstraint<'tcx> { +impl<'tcx> Value<'tcx> for AdtSizedConstraint<'_> { fn from_cycle_error(tcx: TyCtxt<'tcx>) -> Self { - AdtSizedConstraint(tcx.intern_type_list(&[tcx.types.err])) + // SAFETY: This is never called when `Self` is not `AdtSizedConstraint<'tcx>`. + // FIXME: Represent the above fact in the trait system somehow. + unsafe { + std::mem::transmute::, AdtSizedConstraint<'_>>( + AdtSizedConstraint(tcx.intern_type_list(&[tcx.types.err])), + ) + } } } diff --git a/src/librustc_middle/ty/sty.rs b/src/librustc_middle/ty/sty.rs index 5d4c2a54267c3..34333382a22a8 100644 --- a/src/librustc_middle/ty/sty.rs +++ b/src/librustc_middle/ty/sty.rs @@ -2404,8 +2404,6 @@ impl<'tcx> Const<'tcx> { } } -impl<'tcx> rustc_serialize::UseSpecializedDecodable for &'tcx Const<'tcx> {} - /// Represents a constant in Rust. #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, RustcEncodable, RustcDecodable, Hash)] #[derive(HashStable)] diff --git a/src/librustc_query_system/dep_graph/dep_node.rs b/src/librustc_query_system/dep_graph/dep_node.rs index d8875f8ac64a2..002b0f9c165dd 100644 --- a/src/librustc_query_system/dep_graph/dep_node.rs +++ b/src/librustc_query_system/dep_graph/dep_node.rs @@ -91,7 +91,7 @@ impl fmt::Debug for DepNode { } pub trait DepNodeParams: fmt::Debug + Sized { - const CAN_RECONSTRUCT_QUERY_KEY: bool; + fn can_reconstruct_query_key() -> bool; /// This method turns the parameters of a DepNodeConstructor into an opaque /// Fingerprint to be used in DepNode. @@ -108,7 +108,7 @@ pub trait DepNodeParams: fmt::Debug + Sized { /// This method tries to recover the query key from the given `DepNode`, /// something which is needed when forcing `DepNode`s during red-green /// evaluation. The query system will only call this method if - /// `CAN_RECONSTRUCT_QUERY_KEY` is `true`. + /// `can_reconstruct_query_key()` is `true`. /// It is always valid to return `None` here, in which case incremental /// compilation will treat the query as having changed instead of forcing it. fn recover(tcx: Ctxt, dep_node: &DepNode) -> Option; @@ -118,7 +118,10 @@ impl DepNodeParams for T where T: HashStable + fmt::Debug, { - default const CAN_RECONSTRUCT_QUERY_KEY: bool = false; + #[inline] + default fn can_reconstruct_query_key() -> bool { + false + } default fn to_fingerprint(&self, tcx: Ctxt) -> Fingerprint { let mut hcx = tcx.create_stable_hashing_context(); diff --git a/src/librustc_query_system/lib.rs b/src/librustc_query_system/lib.rs index 8e350d3ba267e..12450a4ccd3eb 100644 --- a/src/librustc_query_system/lib.rs +++ b/src/librustc_query_system/lib.rs @@ -4,7 +4,7 @@ #![feature(const_panic)] #![feature(core_intrinsics)] #![feature(hash_raw_entry)] -#![feature(specialization)] // FIXME: min_specialization rejects `default const` +#![feature(min_specialization)] #![feature(stmt_expr_attributes)] #![feature(vec_remove_item)] diff --git a/src/librustc_serialize/lib.rs b/src/librustc_serialize/lib.rs index 7261d631a6f31..3dc3e78382096 100644 --- a/src/librustc_serialize/lib.rs +++ b/src/librustc_serialize/lib.rs @@ -10,7 +10,7 @@ Core encoding and decoding interfaces. test(attr(allow(unused_variables), deny(warnings))) )] #![feature(box_syntax)] -#![feature(specialization)] // FIXME: min_specialization does not work +#![feature(min_specialization)] #![feature(never_type)] #![feature(nll)] #![feature(associated_type_bounds)] diff --git a/src/librustc_serialize/serialize.rs b/src/librustc_serialize/serialize.rs index e80d16bb0c7ab..29c5737ad895a 100644 --- a/src/librustc_serialize/serialize.rs +++ b/src/librustc_serialize/serialize.rs @@ -635,24 +635,6 @@ impl Decodable for PhantomData { } } -impl<'a, T: ?Sized + Encodable> Encodable for &'a T { - fn encode(&self, s: &mut S) -> Result<(), S::Error> { - (**self).encode(s) - } -} - -impl Encodable for Box { - fn encode(&self, s: &mut S) -> Result<(), S::Error> { - (**self).encode(s) - } -} - -impl Decodable for Box { - fn decode(d: &mut D) -> Result, D::Error> { - Ok(box Decodable::decode(d)?) - } -} - impl Decodable for Box<[T]> { fn decode(d: &mut D) -> Result, D::Error> { let v: Vec = Decodable::decode(d)?; @@ -1008,8 +990,20 @@ impl Decodable for T { // for this exact reason. // May be fixable in a simpler fashion via the // more complex lattice model for specialization. -impl<'a, T: ?Sized + Encodable> UseSpecializedEncodable for &'a T {} -impl UseSpecializedEncodable for Box {} -impl UseSpecializedDecodable for Box {} +impl<'a, T: ?Sized + Encodable> UseSpecializedEncodable for &'a T { + fn default_encode(&self, s: &mut S) -> Result<(), S::Error> { + (**self).encode(s) + } +} +impl UseSpecializedEncodable for Box { + fn default_encode(&self, s: &mut S) -> Result<(), S::Error> { + (**self).encode(s) + } +} +impl UseSpecializedDecodable for Box { + fn default_decode(d: &mut D) -> Result, D::Error> { + Ok(box Decodable::decode(d)?) + } +} impl<'a, T: Decodable> UseSpecializedDecodable for &'a T {} impl<'a, T: Decodable> UseSpecializedDecodable for &'a [T] {} diff --git a/src/librustc_trait_selection/infer.rs b/src/librustc_trait_selection/infer.rs index 66df4fe951162..f244785b49d2f 100644 --- a/src/librustc_trait_selection/infer.rs +++ b/src/librustc_trait_selection/infer.rs @@ -90,7 +90,7 @@ pub trait InferCtxtBuilderExt<'tcx> { where K: TypeFoldable<'tcx>, R: Debug + TypeFoldable<'tcx>, - Canonical<'tcx, QueryResponse<'tcx, R>>: ArenaAllocatable; + Canonical<'tcx, QueryResponse<'tcx, R>>: ArenaAllocatable<'tcx>; } impl<'tcx> InferCtxtBuilderExt<'tcx> for InferCtxtBuilder<'tcx> { @@ -118,7 +118,7 @@ impl<'tcx> InferCtxtBuilderExt<'tcx> for InferCtxtBuilder<'tcx> { where K: TypeFoldable<'tcx>, R: Debug + TypeFoldable<'tcx>, - Canonical<'tcx, QueryResponse<'tcx, R>>: ArenaAllocatable, + Canonical<'tcx, QueryResponse<'tcx, R>>: ArenaAllocatable<'tcx>, { self.enter_with_canonical( DUMMY_SP, From c29b3fa1484c625bd34cb4d94fc76f36c6233447 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Fri, 29 May 2020 09:24:59 -0700 Subject: [PATCH 09/41] On recursive ADT, provide indirection structured suggestion --- src/librustc_errors/diagnostic.rs | 23 +++++++ src/librustc_errors/diagnostic_builder.rs | 13 ++++ src/librustc_middle/ty/util.rs | 10 ++- .../traits/error_reporting/mod.rs | 66 +++++++++++++++---- src/librustc_typeck/check/mod.rs | 6 +- .../infinite-tag-type-recursion.stderr | 9 ++- src/test/ui/issues/issue-17431-1.stderr | 11 +++- src/test/ui/issues/issue-17431-2.stderr | 22 +++++-- src/test/ui/issues/issue-17431-3.stderr | 11 +++- src/test/ui/issues/issue-17431-4.stderr | 11 +++- src/test/ui/issues/issue-17431-5.stderr | 11 +++- src/test/ui/issues/issue-17431-6.stderr | 9 ++- src/test/ui/issues/issue-17431-7.stderr | 9 ++- src/test/ui/issues/issue-2718-a.stderr | 9 ++- src/test/ui/issues/issue-3008-1.stderr | 9 ++- src/test/ui/issues/issue-3008-2.stderr | 11 +++- src/test/ui/issues/issue-3008-3.stderr | 9 ++- src/test/ui/issues/issue-32326.stderr | 5 +- src/test/ui/issues/issue-3779.stderr | 11 +++- src/test/ui/issues/issue-57271.stderr | 18 ++++- src/test/ui/recursion/recursive-enum.stderr | 9 ++- src/test/ui/sized-cycle-note.stderr | 22 +++++-- src/test/ui/span/E0072.stderr | 11 +++- src/test/ui/span/multiline-span-E0072.stderr | 11 +++- src/test/ui/span/recursive-type-field.stderr | 23 ++++--- src/test/ui/type/type-recursive.stderr | 11 +++- .../ui/union/union-nonrepresentable.stderr | 11 +++- 27 files changed, 315 insertions(+), 66 deletions(-) diff --git a/src/librustc_errors/diagnostic.rs b/src/librustc_errors/diagnostic.rs index cff83c3d5cda2..acaa26c6ad2fc 100644 --- a/src/librustc_errors/diagnostic.rs +++ b/src/librustc_errors/diagnostic.rs @@ -296,6 +296,29 @@ impl Diagnostic { self } + pub fn multipart_suggestions( + &mut self, + msg: &str, + suggestions: Vec>, + applicability: Applicability, + ) -> &mut Self { + self.suggestions.push(CodeSuggestion { + substitutions: suggestions + .into_iter() + .map(|suggestion| Substitution { + parts: suggestion + .into_iter() + .map(|(span, snippet)| SubstitutionPart { snippet, span }) + .collect(), + }) + .collect(), + msg: msg.to_owned(), + style: SuggestionStyle::ShowCode, + applicability, + }); + self + } + /// Prints out a message with for a multipart suggestion without showing the suggested code. /// /// This is intended to be used for suggestions that are obvious in what the changes need to diff --git a/src/librustc_errors/diagnostic_builder.rs b/src/librustc_errors/diagnostic_builder.rs index 2dbd9f4e52fad..22bf8fe34aa15 100644 --- a/src/librustc_errors/diagnostic_builder.rs +++ b/src/librustc_errors/diagnostic_builder.rs @@ -260,6 +260,19 @@ impl<'a> DiagnosticBuilder<'a> { self } + pub fn multipart_suggestions( + &mut self, + msg: &str, + suggestions: Vec>, + applicability: Applicability, + ) -> &mut Self { + if !self.0.allow_suggestions { + return self; + } + self.0.diagnostic.multipart_suggestions(msg, suggestions, applicability); + self + } + pub fn tool_only_multipart_suggestion( &mut self, msg: &str, diff --git a/src/librustc_middle/ty/util.rs b/src/librustc_middle/ty/util.rs index c2b794ca4bdd9..5cdfa6f90128d 100644 --- a/src/librustc_middle/ty/util.rs +++ b/src/librustc_middle/ty/util.rs @@ -827,7 +827,15 @@ impl<'tcx> ty::TyS<'tcx> { // Find non representable fields with their spans fold_repr(def.all_fields().map(|field| { let ty = field.ty(tcx, substs); - let span = tcx.hir().span_if_local(field.did).unwrap_or(sp); + let span = match field + .did + .as_local() + .map(|id| tcx.hir().as_local_hir_id(id)) + .and_then(|id| tcx.hir().find(id)) + { + Some(hir::Node::Field(field)) => field.ty.span, + _ => sp, + }; match is_type_structurally_recursive( tcx, span, diff --git a/src/librustc_trait_selection/traits/error_reporting/mod.rs b/src/librustc_trait_selection/traits/error_reporting/mod.rs index 1b72a4bf84f19..3457f7b4580c5 100644 --- a/src/librustc_trait_selection/traits/error_reporting/mod.rs +++ b/src/librustc_trait_selection/traits/error_reporting/mod.rs @@ -1747,24 +1747,62 @@ impl<'a, 'tcx> InferCtxtPrivExt<'tcx> for InferCtxt<'a, 'tcx> { pub fn recursive_type_with_infinite_size_error( tcx: TyCtxt<'tcx>, type_def_id: DefId, -) -> DiagnosticBuilder<'tcx> { + spans: Vec, +) { assert!(type_def_id.is_local()); let span = tcx.hir().span_if_local(type_def_id).unwrap(); let span = tcx.sess.source_map().guess_head_span(span); - let mut err = struct_span_err!( - tcx.sess, - span, - E0072, - "recursive type `{}` has infinite size", - tcx.def_path_str(type_def_id) - ); + let path = tcx.def_path_str(type_def_id); + let mut err = + struct_span_err!(tcx.sess, span, E0072, "recursive type `{}` has infinite size", path); err.span_label(span, "recursive type has infinite size"); - err.help(&format!( - "insert indirection (e.g., a `Box`, `Rc`, or `&`) \ - at some point to make `{}` representable", - tcx.def_path_str(type_def_id) - )); - err + for &span in &spans { + err.span_label(span, "recursive without indirection"); + } + let short_msg = format!("insert some indirection to make `{}` representable", path); + let msg = format!( + "insert some indirection (e.g., a `Box`, `Rc`, or `&`) to make `{}` representable", + path, + ); + match &spans[..] { + [span] => { + err.multipart_suggestions( + &short_msg, + vec![ + vec![ + (span.shrink_to_lo(), "Box<".to_string()), + (span.shrink_to_hi(), ">".to_string()), + ], + vec![ + (span.shrink_to_lo(), "Rc<".to_string()), + (span.shrink_to_hi(), ">".to_string()), + ], + vec![(span.shrink_to_lo(), "&".to_string())], + ], + Applicability::HasPlaceholders, + ); + } + _ if spans.len() <= 4 => { + err.multipart_suggestion( + &msg, + spans + .iter() + .flat_map(|&span| { + vec![ + (span.shrink_to_lo(), "Box<".to_string()), + (span.shrink_to_hi(), ">".to_string()), + ] + .into_iter() + }) + .collect(), + Applicability::HasPlaceholders, + ); + } + _ => { + err.help(&msg); + } + } + err.emit(); } /// Summarizes information diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs index f2aeed4f1e465..1e8a149d7d9ec 100644 --- a/src/librustc_typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -2390,11 +2390,7 @@ fn check_representable(tcx: TyCtxt<'_>, sp: Span, item_def_id: LocalDefId) -> bo // caught by case 1. match rty.is_representable(tcx, sp) { Representability::SelfRecursive(spans) => { - let mut err = recursive_type_with_infinite_size_error(tcx, item_def_id.to_def_id()); - for span in spans { - err.span_label(span, "recursive without indirection"); - } - err.emit(); + recursive_type_with_infinite_size_error(tcx, item_def_id.to_def_id(), spans); return false; } Representability::Representable | Representability::ContainsRecursive => (), diff --git a/src/test/ui/infinite/infinite-tag-type-recursion.stderr b/src/test/ui/infinite/infinite-tag-type-recursion.stderr index 11f82b842ba6f..b6a4d8f4cf563 100644 --- a/src/test/ui/infinite/infinite-tag-type-recursion.stderr +++ b/src/test/ui/infinite/infinite-tag-type-recursion.stderr @@ -6,7 +6,14 @@ LL | enum MList { Cons(isize, MList), Nil } | | | recursive type has infinite size | - = help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to make `MList` representable +help: insert some indirection to make `MList` representable + | +LL | enum MList { Cons(isize, Box), Nil } + | ^^^^ ^ +LL | enum MList { Cons(isize, Rc), Nil } + | ^^^ ^ +LL | enum MList { Cons(isize, &MList), Nil } + | ^ error[E0391]: cycle detected when computing drop-check constraints for `MList` --> $DIR/infinite-tag-type-recursion.rs:1:1 diff --git a/src/test/ui/issues/issue-17431-1.stderr b/src/test/ui/issues/issue-17431-1.stderr index eb5a1366e8953..8d44154650e04 100644 --- a/src/test/ui/issues/issue-17431-1.stderr +++ b/src/test/ui/issues/issue-17431-1.stderr @@ -2,11 +2,18 @@ error[E0072]: recursive type `Foo` has infinite size --> $DIR/issue-17431-1.rs:1:1 | LL | struct Foo { foo: Option> } - | ^^^^^^^^^^ ------------------------ recursive without indirection + | ^^^^^^^^^^ ------------------- recursive without indirection | | | recursive type has infinite size | - = help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to make `Foo` representable +help: insert some indirection to make `Foo` representable + | +LL | struct Foo { foo: Box>> } + | ^^^^ ^ +LL | struct Foo { foo: Rc>> } + | ^^^ ^ +LL | struct Foo { foo: &Option> } + | ^ error: aborting due to previous error diff --git a/src/test/ui/issues/issue-17431-2.stderr b/src/test/ui/issues/issue-17431-2.stderr index 3a7b0e9ce7997..b06184e84da28 100644 --- a/src/test/ui/issues/issue-17431-2.stderr +++ b/src/test/ui/issues/issue-17431-2.stderr @@ -2,21 +2,35 @@ error[E0072]: recursive type `Baz` has infinite size --> $DIR/issue-17431-2.rs:1:1 | LL | struct Baz { q: Option } - | ^^^^^^^^^^ -------------- recursive without indirection + | ^^^^^^^^^^ ----------- recursive without indirection | | | recursive type has infinite size | - = help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to make `Baz` representable +help: insert some indirection to make `Baz` representable + | +LL | struct Baz { q: Box> } + | ^^^^ ^ +LL | struct Baz { q: Rc> } + | ^^^ ^ +LL | struct Baz { q: &Option } + | ^ error[E0072]: recursive type `Foo` has infinite size --> $DIR/issue-17431-2.rs:4:1 | LL | struct Foo { q: Option } - | ^^^^^^^^^^ -------------- recursive without indirection + | ^^^^^^^^^^ ----------- recursive without indirection | | | recursive type has infinite size | - = help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to make `Foo` representable +help: insert some indirection to make `Foo` representable + | +LL | struct Foo { q: Box> } + | ^^^^ ^ +LL | struct Foo { q: Rc> } + | ^^^ ^ +LL | struct Foo { q: &Option } + | ^ error: aborting due to 2 previous errors diff --git a/src/test/ui/issues/issue-17431-3.stderr b/src/test/ui/issues/issue-17431-3.stderr index 675a2e2714209..f32bd70fd6d94 100644 --- a/src/test/ui/issues/issue-17431-3.stderr +++ b/src/test/ui/issues/issue-17431-3.stderr @@ -2,11 +2,18 @@ error[E0072]: recursive type `Foo` has infinite size --> $DIR/issue-17431-3.rs:3:1 | LL | struct Foo { foo: Mutex> } - | ^^^^^^^^^^ ----------------------- recursive without indirection + | ^^^^^^^^^^ ------------------ recursive without indirection | | | recursive type has infinite size | - = help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to make `Foo` representable +help: insert some indirection to make `Foo` representable + | +LL | struct Foo { foo: Box>> } + | ^^^^ ^ +LL | struct Foo { foo: Rc>> } + | ^^^ ^ +LL | struct Foo { foo: &Mutex> } + | ^ error: aborting due to previous error diff --git a/src/test/ui/issues/issue-17431-4.stderr b/src/test/ui/issues/issue-17431-4.stderr index aff9071095ca0..372c5e975c844 100644 --- a/src/test/ui/issues/issue-17431-4.stderr +++ b/src/test/ui/issues/issue-17431-4.stderr @@ -2,11 +2,18 @@ error[E0072]: recursive type `Foo` has infinite size --> $DIR/issue-17431-4.rs:3:1 | LL | struct Foo { foo: Option>>, marker: marker::PhantomData } - | ^^^^^^^^^^^^^ --------------------------- recursive without indirection + | ^^^^^^^^^^^^^ ---------------------- recursive without indirection | | | recursive type has infinite size | - = help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to make `Foo` representable +help: insert some indirection to make `Foo` representable + | +LL | struct Foo { foo: Box>>>, marker: marker::PhantomData } + | ^^^^ ^ +LL | struct Foo { foo: Rc>>>, marker: marker::PhantomData } + | ^^^ ^ +LL | struct Foo { foo: &Option>>, marker: marker::PhantomData } + | ^ error: aborting due to previous error diff --git a/src/test/ui/issues/issue-17431-5.stderr b/src/test/ui/issues/issue-17431-5.stderr index 537f9f34f55ca..01b850ac33694 100644 --- a/src/test/ui/issues/issue-17431-5.stderr +++ b/src/test/ui/issues/issue-17431-5.stderr @@ -2,11 +2,18 @@ error[E0072]: recursive type `Bar` has infinite size --> $DIR/issue-17431-5.rs:5:1 | LL | struct Bar { x: Bar , marker: marker::PhantomData } - | ^^^^^^^^^^^^^ ----------- recursive without indirection + | ^^^^^^^^^^^^^ -------- recursive without indirection | | | recursive type has infinite size | - = help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to make `Bar` representable +help: insert some indirection to make `Bar` representable + | +LL | struct Bar { x: Box> , marker: marker::PhantomData } + | ^^^^ ^ +LL | struct Bar { x: Rc> , marker: marker::PhantomData } + | ^^^ ^ +LL | struct Bar { x: &Bar , marker: marker::PhantomData } + | ^ error: aborting due to previous error diff --git a/src/test/ui/issues/issue-17431-6.stderr b/src/test/ui/issues/issue-17431-6.stderr index cb2dab9501488..ce6c2db07fb6d 100644 --- a/src/test/ui/issues/issue-17431-6.stderr +++ b/src/test/ui/issues/issue-17431-6.stderr @@ -6,7 +6,14 @@ LL | enum Foo { X(Mutex>) } | | | recursive type has infinite size | - = help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to make `Foo` representable +help: insert some indirection to make `Foo` representable + | +LL | enum Foo { X(Box>>) } + | ^^^^ ^ +LL | enum Foo { X(Rc>>) } + | ^^^ ^ +LL | enum Foo { X(&Mutex>) } + | ^ error: aborting due to previous error diff --git a/src/test/ui/issues/issue-17431-7.stderr b/src/test/ui/issues/issue-17431-7.stderr index de70851da4b5f..4fb563ba502f2 100644 --- a/src/test/ui/issues/issue-17431-7.stderr +++ b/src/test/ui/issues/issue-17431-7.stderr @@ -6,7 +6,14 @@ LL | enum Foo { Voo(Option>) } | | | recursive type has infinite size | - = help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to make `Foo` representable +help: insert some indirection to make `Foo` representable + | +LL | enum Foo { Voo(Box>>) } + | ^^^^ ^ +LL | enum Foo { Voo(Rc>>) } + | ^^^ ^ +LL | enum Foo { Voo(&Option>) } + | ^ error: aborting due to previous error diff --git a/src/test/ui/issues/issue-2718-a.stderr b/src/test/ui/issues/issue-2718-a.stderr index 0f52c79192843..48b7a61e059ea 100644 --- a/src/test/ui/issues/issue-2718-a.stderr +++ b/src/test/ui/issues/issue-2718-a.stderr @@ -7,7 +7,14 @@ LL | pub struct Pong(SendPacket); | | recursive without indirection | recursive type has infinite size | - = help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to make `pingpong::Pong` representable +help: insert some indirection to make `pingpong::Pong` representable + | +LL | pub struct Pong(Box>); + | ^^^^ ^ +LL | pub struct Pong(Rc>); + | ^^^ ^ +LL | pub struct Pong(&SendPacket); + | ^ error: aborting due to previous error diff --git a/src/test/ui/issues/issue-3008-1.stderr b/src/test/ui/issues/issue-3008-1.stderr index f12274134ee05..d1173a4b3334c 100644 --- a/src/test/ui/issues/issue-3008-1.stderr +++ b/src/test/ui/issues/issue-3008-1.stderr @@ -7,7 +7,14 @@ LL | enum Bar { LL | BarSome(Bar) | --- recursive without indirection | - = help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to make `Bar` representable +help: insert some indirection to make `Bar` representable + | +LL | BarSome(Box) + | ^^^^ ^ +LL | BarSome(Rc) + | ^^^ ^ +LL | BarSome(&Bar) + | ^ error: aborting due to previous error diff --git a/src/test/ui/issues/issue-3008-2.stderr b/src/test/ui/issues/issue-3008-2.stderr index acc15f4b57c73..4fd60639b21a8 100644 --- a/src/test/ui/issues/issue-3008-2.stderr +++ b/src/test/ui/issues/issue-3008-2.stderr @@ -2,11 +2,18 @@ error[E0072]: recursive type `Bar` has infinite size --> $DIR/issue-3008-2.rs:2:1 | LL | struct Bar { x: Bar } - | ^^^^^^^^^^ ------ recursive without indirection + | ^^^^^^^^^^ --- recursive without indirection | | | recursive type has infinite size | - = help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to make `Bar` representable +help: insert some indirection to make `Bar` representable + | +LL | struct Bar { x: Box } + | ^^^^ ^ +LL | struct Bar { x: Rc } + | ^^^ ^ +LL | struct Bar { x: &Bar } + | ^ error: aborting due to previous error diff --git a/src/test/ui/issues/issue-3008-3.stderr b/src/test/ui/issues/issue-3008-3.stderr index d08a3d9708db3..e6efad9188300 100644 --- a/src/test/ui/issues/issue-3008-3.stderr +++ b/src/test/ui/issues/issue-3008-3.stderr @@ -6,7 +6,14 @@ LL | enum E2 { V2(E2, marker::PhantomData), } | | | recursive type has infinite size | - = help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to make `E2` representable +help: insert some indirection to make `E2` representable + | +LL | enum E2 { V2(Box>, marker::PhantomData), } + | ^^^^ ^ +LL | enum E2 { V2(Rc>, marker::PhantomData), } + | ^^^ ^ +LL | enum E2 { V2(&E2, marker::PhantomData), } + | ^ error: aborting due to previous error diff --git a/src/test/ui/issues/issue-32326.stderr b/src/test/ui/issues/issue-32326.stderr index 5967627e51a4b..0f3d3690b732e 100644 --- a/src/test/ui/issues/issue-32326.stderr +++ b/src/test/ui/issues/issue-32326.stderr @@ -8,7 +8,10 @@ LL | Plus(Expr, Expr), | | | recursive without indirection | - = help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to make `Expr` representable +help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to make `Expr` representable + | +LL | Plus(Box, Box), + | ^^^^ ^ ^^^^ ^ error: aborting due to previous error diff --git a/src/test/ui/issues/issue-3779.stderr b/src/test/ui/issues/issue-3779.stderr index ba1e842c610ba..9b50ddec12a44 100644 --- a/src/test/ui/issues/issue-3779.stderr +++ b/src/test/ui/issues/issue-3779.stderr @@ -5,9 +5,16 @@ LL | struct S { | ^^^^^^^^ recursive type has infinite size LL | LL | element: Option - | ------------------ recursive without indirection + | --------- recursive without indirection | - = help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to make `S` representable +help: insert some indirection to make `S` representable + | +LL | element: Box> + | ^^^^ ^ +LL | element: Rc> + | ^^^ ^ +LL | element: &Option + | ^ error: aborting due to previous error diff --git a/src/test/ui/issues/issue-57271.stderr b/src/test/ui/issues/issue-57271.stderr index 4f164624f7a53..a6fe83a9b5636 100644 --- a/src/test/ui/issues/issue-57271.stderr +++ b/src/test/ui/issues/issue-57271.stderr @@ -7,7 +7,14 @@ LL | Class(ClassTypeSignature), LL | Array(TypeSignature), | ------------- recursive without indirection | - = help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to make `ObjectType` representable +help: insert some indirection to make `ObjectType` representable + | +LL | Array(Box), + | ^^^^ ^ +LL | Array(Rc), + | ^^^ ^ +LL | Array(&TypeSignature), + | ^ error[E0072]: recursive type `TypeSignature` has infinite size --> $DIR/issue-57271.rs:19:1 @@ -18,7 +25,14 @@ LL | Base(BaseType), LL | Object(ObjectType), | ---------- recursive without indirection | - = help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to make `TypeSignature` representable +help: insert some indirection to make `TypeSignature` representable + | +LL | Object(Box), + | ^^^^ ^ +LL | Object(Rc), + | ^^^ ^ +LL | Object(&ObjectType), + | ^ error: aborting due to 2 previous errors diff --git a/src/test/ui/recursion/recursive-enum.stderr b/src/test/ui/recursion/recursive-enum.stderr index e4674b57a6d21..c68badd458bce 100644 --- a/src/test/ui/recursion/recursive-enum.stderr +++ b/src/test/ui/recursion/recursive-enum.stderr @@ -6,7 +6,14 @@ LL | enum List { Cons(T, List), Nil } | | | recursive type has infinite size | - = help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to make `List` representable +help: insert some indirection to make `List` representable + | +LL | enum List { Cons(T, Box>), Nil } + | ^^^^ ^ +LL | enum List { Cons(T, Rc>), Nil } + | ^^^ ^ +LL | enum List { Cons(T, &List), Nil } + | ^ error: aborting due to previous error diff --git a/src/test/ui/sized-cycle-note.stderr b/src/test/ui/sized-cycle-note.stderr index 95bdc34942645..99d8cfd0a05c9 100644 --- a/src/test/ui/sized-cycle-note.stderr +++ b/src/test/ui/sized-cycle-note.stderr @@ -2,21 +2,35 @@ error[E0072]: recursive type `Baz` has infinite size --> $DIR/sized-cycle-note.rs:9:1 | LL | struct Baz { q: Option } - | ^^^^^^^^^^ -------------- recursive without indirection + | ^^^^^^^^^^ ----------- recursive without indirection | | | recursive type has infinite size | - = help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to make `Baz` representable +help: insert some indirection to make `Baz` representable + | +LL | struct Baz { q: Box> } + | ^^^^ ^ +LL | struct Baz { q: Rc> } + | ^^^ ^ +LL | struct Baz { q: &Option } + | ^ error[E0072]: recursive type `Foo` has infinite size --> $DIR/sized-cycle-note.rs:11:1 | LL | struct Foo { q: Option } - | ^^^^^^^^^^ -------------- recursive without indirection + | ^^^^^^^^^^ ----------- recursive without indirection | | | recursive type has infinite size | - = help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to make `Foo` representable +help: insert some indirection to make `Foo` representable + | +LL | struct Foo { q: Box> } + | ^^^^ ^ +LL | struct Foo { q: Rc> } + | ^^^ ^ +LL | struct Foo { q: &Option } + | ^ error: aborting due to 2 previous errors diff --git a/src/test/ui/span/E0072.stderr b/src/test/ui/span/E0072.stderr index d4a5e7400d2a4..855e4facb7b8c 100644 --- a/src/test/ui/span/E0072.stderr +++ b/src/test/ui/span/E0072.stderr @@ -5,9 +5,16 @@ LL | struct ListNode { | ^^^^^^^^^^^^^^^ recursive type has infinite size LL | head: u8, LL | tail: Option, - | ---------------------- recursive without indirection + | ---------------- recursive without indirection | - = help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to make `ListNode` representable +help: insert some indirection to make `ListNode` representable + | +LL | tail: Box>, + | ^^^^ ^ +LL | tail: Rc>, + | ^^^ ^ +LL | tail: &Option, + | ^ error: aborting due to previous error diff --git a/src/test/ui/span/multiline-span-E0072.stderr b/src/test/ui/span/multiline-span-E0072.stderr index dd322fe833b49..260c2157e96b7 100644 --- a/src/test/ui/span/multiline-span-E0072.stderr +++ b/src/test/ui/span/multiline-span-E0072.stderr @@ -6,11 +6,18 @@ LL | | ListNode LL | | { LL | | head: u8, LL | | tail: Option, - | | ---------------------- recursive without indirection + | | ---------------- recursive without indirection LL | | } | |_^ recursive type has infinite size | - = help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to make `ListNode` representable +help: insert some indirection to make `ListNode` representable + | +LL | tail: Box>, + | ^^^^ ^ +LL | tail: Rc>, + | ^^^ ^ +LL | tail: &Option, + | ^ error: aborting due to previous error diff --git a/src/test/ui/span/recursive-type-field.stderr b/src/test/ui/span/recursive-type-field.stderr index d240872647e50..c1a3270d0a567 100644 --- a/src/test/ui/span/recursive-type-field.stderr +++ b/src/test/ui/span/recursive-type-field.stderr @@ -4,9 +4,16 @@ error[E0072]: recursive type `Foo` has infinite size LL | struct Foo<'a> { | ^^^^^^^^^^^^^^ recursive type has infinite size LL | bar: Bar<'a>, - | ------------ recursive without indirection + | ------- recursive without indirection | - = help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to make `Foo` representable +help: insert some indirection to make `Foo` representable + | +LL | bar: Box>, + | ^^^^ ^ +LL | bar: Rc>, + | ^^^ ^ +LL | bar: &Bar<'a>, + | ^ error[E0072]: recursive type `Bar` has infinite size --> $DIR/recursive-type-field.rs:8:1 @@ -14,18 +21,18 @@ error[E0072]: recursive type `Bar` has infinite size LL | struct Bar<'a> { | ^^^^^^^^^^^^^^ recursive type has infinite size LL | y: (Foo<'a>, Foo<'a>), - | --------------------- recursive without indirection + | ------------------ recursive without indirection LL | z: Option>, - | ------------------ recursive without indirection + | --------------- recursive without indirection ... LL | d: [Bar<'a>; 1], - | --------------- recursive without indirection + | ------------ recursive without indirection LL | e: Foo<'a>, - | ---------- recursive without indirection + | ------- recursive without indirection LL | x: Bar<'a>, - | ---------- recursive without indirection + | ------- recursive without indirection | - = help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to make `Bar` representable + = help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to make `Bar` representable error: aborting due to 2 previous errors diff --git a/src/test/ui/type/type-recursive.stderr b/src/test/ui/type/type-recursive.stderr index 72bf372e561d6..b98a6eac49e04 100644 --- a/src/test/ui/type/type-recursive.stderr +++ b/src/test/ui/type/type-recursive.stderr @@ -5,9 +5,16 @@ LL | struct T1 { | ^^^^^^^^^ recursive type has infinite size LL | foo: isize, LL | foolish: T1 - | ----------- recursive without indirection + | -- recursive without indirection | - = help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to make `T1` representable +help: insert some indirection to make `T1` representable + | +LL | foolish: Box + | ^^^^ ^ +LL | foolish: Rc + | ^^^ ^ +LL | foolish: &T1 + | ^ error: aborting due to previous error diff --git a/src/test/ui/union/union-nonrepresentable.stderr b/src/test/ui/union/union-nonrepresentable.stderr index 746c1033ea348..70863a549ad25 100644 --- a/src/test/ui/union/union-nonrepresentable.stderr +++ b/src/test/ui/union/union-nonrepresentable.stderr @@ -5,9 +5,16 @@ LL | union U { | ^^^^^^^ recursive type has infinite size LL | a: u8, LL | b: U, - | ---- recursive without indirection + | - recursive without indirection | - = help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to make `U` representable +help: insert some indirection to make `U` representable + | +LL | b: Box, + | ^^^^ ^ +LL | b: Rc, + | ^^^ ^ +LL | b: &U, + | ^ error: aborting due to previous error From 7cde07e5cc5cfc1665dd64e4c06482c2f10b693a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Sat, 30 May 2020 19:58:49 -0700 Subject: [PATCH 10/41] review comments: only suggest one substitution --- .../traits/error_reporting/mod.rs | 49 ++++++------------- .../infinite-tag-type-recursion.stderr | 6 +-- src/test/ui/issues/issue-17431-1.stderr | 6 +-- src/test/ui/issues/issue-17431-2.stderr | 12 +---- src/test/ui/issues/issue-17431-3.stderr | 6 +-- src/test/ui/issues/issue-17431-4.stderr | 6 +-- src/test/ui/issues/issue-17431-5.stderr | 6 +-- src/test/ui/issues/issue-17431-6.stderr | 6 +-- src/test/ui/issues/issue-17431-7.stderr | 6 +-- src/test/ui/issues/issue-2718-a.stderr | 6 +-- src/test/ui/issues/issue-3008-1.stderr | 6 +-- src/test/ui/issues/issue-3008-2.stderr | 6 +-- src/test/ui/issues/issue-3008-3.stderr | 6 +-- src/test/ui/issues/issue-3779.stderr | 6 +-- src/test/ui/issues/issue-57271.stderr | 12 +---- src/test/ui/recursion/recursive-enum.stderr | 6 +-- src/test/ui/sized-cycle-note.stderr | 12 +---- src/test/ui/span/E0072.stderr | 6 +-- src/test/ui/span/multiline-span-E0072.stderr | 6 +-- src/test/ui/span/recursive-type-field.stderr | 6 +-- src/test/ui/type/type-recursive.stderr | 6 +-- .../ui/union/union-nonrepresentable.stderr | 6 +-- 22 files changed, 38 insertions(+), 155 deletions(-) diff --git a/src/librustc_trait_selection/traits/error_reporting/mod.rs b/src/librustc_trait_selection/traits/error_reporting/mod.rs index 3457f7b4580c5..d31e04cffd55f 100644 --- a/src/librustc_trait_selection/traits/error_reporting/mod.rs +++ b/src/librustc_trait_selection/traits/error_reporting/mod.rs @@ -1759,48 +1759,27 @@ pub fn recursive_type_with_infinite_size_error( for &span in &spans { err.span_label(span, "recursive without indirection"); } - let short_msg = format!("insert some indirection to make `{}` representable", path); let msg = format!( "insert some indirection (e.g., a `Box`, `Rc`, or `&`) to make `{}` representable", path, ); - match &spans[..] { - [span] => { - err.multipart_suggestions( - &short_msg, - vec![ + if spans.len() <= 4 { + err.multipart_suggestion( + &msg, + spans + .iter() + .flat_map(|&span| { vec![ (span.shrink_to_lo(), "Box<".to_string()), (span.shrink_to_hi(), ">".to_string()), - ], - vec![ - (span.shrink_to_lo(), "Rc<".to_string()), - (span.shrink_to_hi(), ">".to_string()), - ], - vec![(span.shrink_to_lo(), "&".to_string())], - ], - Applicability::HasPlaceholders, - ); - } - _ if spans.len() <= 4 => { - err.multipart_suggestion( - &msg, - spans - .iter() - .flat_map(|&span| { - vec![ - (span.shrink_to_lo(), "Box<".to_string()), - (span.shrink_to_hi(), ">".to_string()), - ] - .into_iter() - }) - .collect(), - Applicability::HasPlaceholders, - ); - } - _ => { - err.help(&msg); - } + ] + .into_iter() + }) + .collect(), + Applicability::HasPlaceholders, + ); + } else { + err.help(&msg); } err.emit(); } diff --git a/src/test/ui/infinite/infinite-tag-type-recursion.stderr b/src/test/ui/infinite/infinite-tag-type-recursion.stderr index b6a4d8f4cf563..6d1df4fda2eb0 100644 --- a/src/test/ui/infinite/infinite-tag-type-recursion.stderr +++ b/src/test/ui/infinite/infinite-tag-type-recursion.stderr @@ -6,14 +6,10 @@ LL | enum MList { Cons(isize, MList), Nil } | | | recursive type has infinite size | -help: insert some indirection to make `MList` representable +help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to make `MList` representable | LL | enum MList { Cons(isize, Box), Nil } | ^^^^ ^ -LL | enum MList { Cons(isize, Rc), Nil } - | ^^^ ^ -LL | enum MList { Cons(isize, &MList), Nil } - | ^ error[E0391]: cycle detected when computing drop-check constraints for `MList` --> $DIR/infinite-tag-type-recursion.rs:1:1 diff --git a/src/test/ui/issues/issue-17431-1.stderr b/src/test/ui/issues/issue-17431-1.stderr index 8d44154650e04..58d087ca1998b 100644 --- a/src/test/ui/issues/issue-17431-1.stderr +++ b/src/test/ui/issues/issue-17431-1.stderr @@ -6,14 +6,10 @@ LL | struct Foo { foo: Option> } | | | recursive type has infinite size | -help: insert some indirection to make `Foo` representable +help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to make `Foo` representable | LL | struct Foo { foo: Box>> } | ^^^^ ^ -LL | struct Foo { foo: Rc>> } - | ^^^ ^ -LL | struct Foo { foo: &Option> } - | ^ error: aborting due to previous error diff --git a/src/test/ui/issues/issue-17431-2.stderr b/src/test/ui/issues/issue-17431-2.stderr index b06184e84da28..eba4bf6d1d5ea 100644 --- a/src/test/ui/issues/issue-17431-2.stderr +++ b/src/test/ui/issues/issue-17431-2.stderr @@ -6,14 +6,10 @@ LL | struct Baz { q: Option } | | | recursive type has infinite size | -help: insert some indirection to make `Baz` representable +help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to make `Baz` representable | LL | struct Baz { q: Box> } | ^^^^ ^ -LL | struct Baz { q: Rc> } - | ^^^ ^ -LL | struct Baz { q: &Option } - | ^ error[E0072]: recursive type `Foo` has infinite size --> $DIR/issue-17431-2.rs:4:1 @@ -23,14 +19,10 @@ LL | struct Foo { q: Option } | | | recursive type has infinite size | -help: insert some indirection to make `Foo` representable +help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to make `Foo` representable | LL | struct Foo { q: Box> } | ^^^^ ^ -LL | struct Foo { q: Rc> } - | ^^^ ^ -LL | struct Foo { q: &Option } - | ^ error: aborting due to 2 previous errors diff --git a/src/test/ui/issues/issue-17431-3.stderr b/src/test/ui/issues/issue-17431-3.stderr index f32bd70fd6d94..f6b15d0528ae8 100644 --- a/src/test/ui/issues/issue-17431-3.stderr +++ b/src/test/ui/issues/issue-17431-3.stderr @@ -6,14 +6,10 @@ LL | struct Foo { foo: Mutex> } | | | recursive type has infinite size | -help: insert some indirection to make `Foo` representable +help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to make `Foo` representable | LL | struct Foo { foo: Box>> } | ^^^^ ^ -LL | struct Foo { foo: Rc>> } - | ^^^ ^ -LL | struct Foo { foo: &Mutex> } - | ^ error: aborting due to previous error diff --git a/src/test/ui/issues/issue-17431-4.stderr b/src/test/ui/issues/issue-17431-4.stderr index 372c5e975c844..aa709e1ad5183 100644 --- a/src/test/ui/issues/issue-17431-4.stderr +++ b/src/test/ui/issues/issue-17431-4.stderr @@ -6,14 +6,10 @@ LL | struct Foo { foo: Option>>, marker: marker::PhantomData | | | recursive type has infinite size | -help: insert some indirection to make `Foo` representable +help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to make `Foo` representable | LL | struct Foo { foo: Box>>>, marker: marker::PhantomData } | ^^^^ ^ -LL | struct Foo { foo: Rc>>>, marker: marker::PhantomData } - | ^^^ ^ -LL | struct Foo { foo: &Option>>, marker: marker::PhantomData } - | ^ error: aborting due to previous error diff --git a/src/test/ui/issues/issue-17431-5.stderr b/src/test/ui/issues/issue-17431-5.stderr index 01b850ac33694..1558cffb036b3 100644 --- a/src/test/ui/issues/issue-17431-5.stderr +++ b/src/test/ui/issues/issue-17431-5.stderr @@ -6,14 +6,10 @@ LL | struct Bar { x: Bar , marker: marker::PhantomData } | | | recursive type has infinite size | -help: insert some indirection to make `Bar` representable +help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to make `Bar` representable | LL | struct Bar { x: Box> , marker: marker::PhantomData } | ^^^^ ^ -LL | struct Bar { x: Rc> , marker: marker::PhantomData } - | ^^^ ^ -LL | struct Bar { x: &Bar , marker: marker::PhantomData } - | ^ error: aborting due to previous error diff --git a/src/test/ui/issues/issue-17431-6.stderr b/src/test/ui/issues/issue-17431-6.stderr index ce6c2db07fb6d..f2aa2a79c8200 100644 --- a/src/test/ui/issues/issue-17431-6.stderr +++ b/src/test/ui/issues/issue-17431-6.stderr @@ -6,14 +6,10 @@ LL | enum Foo { X(Mutex>) } | | | recursive type has infinite size | -help: insert some indirection to make `Foo` representable +help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to make `Foo` representable | LL | enum Foo { X(Box>>) } | ^^^^ ^ -LL | enum Foo { X(Rc>>) } - | ^^^ ^ -LL | enum Foo { X(&Mutex>) } - | ^ error: aborting due to previous error diff --git a/src/test/ui/issues/issue-17431-7.stderr b/src/test/ui/issues/issue-17431-7.stderr index 4fb563ba502f2..684c3089e85ec 100644 --- a/src/test/ui/issues/issue-17431-7.stderr +++ b/src/test/ui/issues/issue-17431-7.stderr @@ -6,14 +6,10 @@ LL | enum Foo { Voo(Option>) } | | | recursive type has infinite size | -help: insert some indirection to make `Foo` representable +help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to make `Foo` representable | LL | enum Foo { Voo(Box>>) } | ^^^^ ^ -LL | enum Foo { Voo(Rc>>) } - | ^^^ ^ -LL | enum Foo { Voo(&Option>) } - | ^ error: aborting due to previous error diff --git a/src/test/ui/issues/issue-2718-a.stderr b/src/test/ui/issues/issue-2718-a.stderr index 48b7a61e059ea..d152ffde4e57d 100644 --- a/src/test/ui/issues/issue-2718-a.stderr +++ b/src/test/ui/issues/issue-2718-a.stderr @@ -7,14 +7,10 @@ LL | pub struct Pong(SendPacket); | | recursive without indirection | recursive type has infinite size | -help: insert some indirection to make `pingpong::Pong` representable +help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to make `pingpong::Pong` representable | LL | pub struct Pong(Box>); | ^^^^ ^ -LL | pub struct Pong(Rc>); - | ^^^ ^ -LL | pub struct Pong(&SendPacket); - | ^ error: aborting due to previous error diff --git a/src/test/ui/issues/issue-3008-1.stderr b/src/test/ui/issues/issue-3008-1.stderr index d1173a4b3334c..87ee36df21696 100644 --- a/src/test/ui/issues/issue-3008-1.stderr +++ b/src/test/ui/issues/issue-3008-1.stderr @@ -7,14 +7,10 @@ LL | enum Bar { LL | BarSome(Bar) | --- recursive without indirection | -help: insert some indirection to make `Bar` representable +help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to make `Bar` representable | LL | BarSome(Box) | ^^^^ ^ -LL | BarSome(Rc) - | ^^^ ^ -LL | BarSome(&Bar) - | ^ error: aborting due to previous error diff --git a/src/test/ui/issues/issue-3008-2.stderr b/src/test/ui/issues/issue-3008-2.stderr index 4fd60639b21a8..369a19d37e6f6 100644 --- a/src/test/ui/issues/issue-3008-2.stderr +++ b/src/test/ui/issues/issue-3008-2.stderr @@ -6,14 +6,10 @@ LL | struct Bar { x: Bar } | | | recursive type has infinite size | -help: insert some indirection to make `Bar` representable +help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to make `Bar` representable | LL | struct Bar { x: Box } | ^^^^ ^ -LL | struct Bar { x: Rc } - | ^^^ ^ -LL | struct Bar { x: &Bar } - | ^ error: aborting due to previous error diff --git a/src/test/ui/issues/issue-3008-3.stderr b/src/test/ui/issues/issue-3008-3.stderr index e6efad9188300..0b162eff94a7c 100644 --- a/src/test/ui/issues/issue-3008-3.stderr +++ b/src/test/ui/issues/issue-3008-3.stderr @@ -6,14 +6,10 @@ LL | enum E2 { V2(E2, marker::PhantomData), } | | | recursive type has infinite size | -help: insert some indirection to make `E2` representable +help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to make `E2` representable | LL | enum E2 { V2(Box>, marker::PhantomData), } | ^^^^ ^ -LL | enum E2 { V2(Rc>, marker::PhantomData), } - | ^^^ ^ -LL | enum E2 { V2(&E2, marker::PhantomData), } - | ^ error: aborting due to previous error diff --git a/src/test/ui/issues/issue-3779.stderr b/src/test/ui/issues/issue-3779.stderr index 9b50ddec12a44..7b17e91421660 100644 --- a/src/test/ui/issues/issue-3779.stderr +++ b/src/test/ui/issues/issue-3779.stderr @@ -7,14 +7,10 @@ LL | LL | element: Option | --------- recursive without indirection | -help: insert some indirection to make `S` representable +help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to make `S` representable | LL | element: Box> | ^^^^ ^ -LL | element: Rc> - | ^^^ ^ -LL | element: &Option - | ^ error: aborting due to previous error diff --git a/src/test/ui/issues/issue-57271.stderr b/src/test/ui/issues/issue-57271.stderr index a6fe83a9b5636..b7c799e163cee 100644 --- a/src/test/ui/issues/issue-57271.stderr +++ b/src/test/ui/issues/issue-57271.stderr @@ -7,14 +7,10 @@ LL | Class(ClassTypeSignature), LL | Array(TypeSignature), | ------------- recursive without indirection | -help: insert some indirection to make `ObjectType` representable +help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to make `ObjectType` representable | LL | Array(Box), | ^^^^ ^ -LL | Array(Rc), - | ^^^ ^ -LL | Array(&TypeSignature), - | ^ error[E0072]: recursive type `TypeSignature` has infinite size --> $DIR/issue-57271.rs:19:1 @@ -25,14 +21,10 @@ LL | Base(BaseType), LL | Object(ObjectType), | ---------- recursive without indirection | -help: insert some indirection to make `TypeSignature` representable +help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to make `TypeSignature` representable | LL | Object(Box), | ^^^^ ^ -LL | Object(Rc), - | ^^^ ^ -LL | Object(&ObjectType), - | ^ error: aborting due to 2 previous errors diff --git a/src/test/ui/recursion/recursive-enum.stderr b/src/test/ui/recursion/recursive-enum.stderr index c68badd458bce..ab4709d8e709e 100644 --- a/src/test/ui/recursion/recursive-enum.stderr +++ b/src/test/ui/recursion/recursive-enum.stderr @@ -6,14 +6,10 @@ LL | enum List { Cons(T, List), Nil } | | | recursive type has infinite size | -help: insert some indirection to make `List` representable +help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to make `List` representable | LL | enum List { Cons(T, Box>), Nil } | ^^^^ ^ -LL | enum List { Cons(T, Rc>), Nil } - | ^^^ ^ -LL | enum List { Cons(T, &List), Nil } - | ^ error: aborting due to previous error diff --git a/src/test/ui/sized-cycle-note.stderr b/src/test/ui/sized-cycle-note.stderr index 99d8cfd0a05c9..45062c2ea6c72 100644 --- a/src/test/ui/sized-cycle-note.stderr +++ b/src/test/ui/sized-cycle-note.stderr @@ -6,14 +6,10 @@ LL | struct Baz { q: Option } | | | recursive type has infinite size | -help: insert some indirection to make `Baz` representable +help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to make `Baz` representable | LL | struct Baz { q: Box> } | ^^^^ ^ -LL | struct Baz { q: Rc> } - | ^^^ ^ -LL | struct Baz { q: &Option } - | ^ error[E0072]: recursive type `Foo` has infinite size --> $DIR/sized-cycle-note.rs:11:1 @@ -23,14 +19,10 @@ LL | struct Foo { q: Option } | | | recursive type has infinite size | -help: insert some indirection to make `Foo` representable +help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to make `Foo` representable | LL | struct Foo { q: Box> } | ^^^^ ^ -LL | struct Foo { q: Rc> } - | ^^^ ^ -LL | struct Foo { q: &Option } - | ^ error: aborting due to 2 previous errors diff --git a/src/test/ui/span/E0072.stderr b/src/test/ui/span/E0072.stderr index 855e4facb7b8c..06493f05142e6 100644 --- a/src/test/ui/span/E0072.stderr +++ b/src/test/ui/span/E0072.stderr @@ -7,14 +7,10 @@ LL | head: u8, LL | tail: Option, | ---------------- recursive without indirection | -help: insert some indirection to make `ListNode` representable +help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to make `ListNode` representable | LL | tail: Box>, | ^^^^ ^ -LL | tail: Rc>, - | ^^^ ^ -LL | tail: &Option, - | ^ error: aborting due to previous error diff --git a/src/test/ui/span/multiline-span-E0072.stderr b/src/test/ui/span/multiline-span-E0072.stderr index 260c2157e96b7..55128347f7404 100644 --- a/src/test/ui/span/multiline-span-E0072.stderr +++ b/src/test/ui/span/multiline-span-E0072.stderr @@ -10,14 +10,10 @@ LL | | tail: Option, LL | | } | |_^ recursive type has infinite size | -help: insert some indirection to make `ListNode` representable +help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to make `ListNode` representable | LL | tail: Box>, | ^^^^ ^ -LL | tail: Rc>, - | ^^^ ^ -LL | tail: &Option, - | ^ error: aborting due to previous error diff --git a/src/test/ui/span/recursive-type-field.stderr b/src/test/ui/span/recursive-type-field.stderr index c1a3270d0a567..fb1d98b58dfbe 100644 --- a/src/test/ui/span/recursive-type-field.stderr +++ b/src/test/ui/span/recursive-type-field.stderr @@ -6,14 +6,10 @@ LL | struct Foo<'a> { LL | bar: Bar<'a>, | ------- recursive without indirection | -help: insert some indirection to make `Foo` representable +help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to make `Foo` representable | LL | bar: Box>, | ^^^^ ^ -LL | bar: Rc>, - | ^^^ ^ -LL | bar: &Bar<'a>, - | ^ error[E0072]: recursive type `Bar` has infinite size --> $DIR/recursive-type-field.rs:8:1 diff --git a/src/test/ui/type/type-recursive.stderr b/src/test/ui/type/type-recursive.stderr index b98a6eac49e04..d6d32cc5d6f39 100644 --- a/src/test/ui/type/type-recursive.stderr +++ b/src/test/ui/type/type-recursive.stderr @@ -7,14 +7,10 @@ LL | foo: isize, LL | foolish: T1 | -- recursive without indirection | -help: insert some indirection to make `T1` representable +help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to make `T1` representable | LL | foolish: Box | ^^^^ ^ -LL | foolish: Rc - | ^^^ ^ -LL | foolish: &T1 - | ^ error: aborting due to previous error diff --git a/src/test/ui/union/union-nonrepresentable.stderr b/src/test/ui/union/union-nonrepresentable.stderr index 70863a549ad25..c54d04de12c50 100644 --- a/src/test/ui/union/union-nonrepresentable.stderr +++ b/src/test/ui/union/union-nonrepresentable.stderr @@ -7,14 +7,10 @@ LL | a: u8, LL | b: U, | - recursive without indirection | -help: insert some indirection to make `U` representable +help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to make `U` representable | LL | b: Box, | ^^^^ ^ -LL | b: Rc, - | ^^^ ^ -LL | b: &U, - | ^ error: aborting due to previous error From 03552ec3fa4828329874a17d1b8966a0c03809d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Wed, 10 Jun 2020 14:54:27 -0700 Subject: [PATCH 11/41] fix rebase --- src/test/ui/issues/issue-72554.stderr | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/test/ui/issues/issue-72554.stderr b/src/test/ui/issues/issue-72554.stderr index 9db65f4a2ee8f..9de94c393a711 100644 --- a/src/test/ui/issues/issue-72554.stderr +++ b/src/test/ui/issues/issue-72554.stderr @@ -6,7 +6,10 @@ LL | pub enum ElemDerived { LL | A(ElemDerived) | ----------- recursive without indirection | - = help: insert indirection (e.g., a `Box`, `Rc`, or `&`) at some point to make `ElemDerived` representable +help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to make `ElemDerived` representable + | +LL | A(Box) + | ^^^^ ^ error: aborting due to previous error From 7f3bb398fa90d68c737dd7e00a3813e0620ba472 Mon Sep 17 00:00:00 2001 From: Alexis Bourget Date: Wed, 10 Jun 2020 23:13:45 +0200 Subject: [PATCH 12/41] Add a TryFrom> impl that mirror from_vec_with_nul --- src/libstd/ffi/c_str.rs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/libstd/ffi/c_str.rs b/src/libstd/ffi/c_str.rs index 6f7dc091897f4..3a3b51fd353b2 100644 --- a/src/libstd/ffi/c_str.rs +++ b/src/libstd/ffi/c_str.rs @@ -1,6 +1,7 @@ use crate::ascii; use crate::borrow::{Borrow, Cow}; use crate::cmp::Ordering; +use crate::convert::TryFrom; use crate::error::Error; use crate::fmt::{self, Write}; use crate::io; @@ -853,6 +854,19 @@ impl From> for CString { } } +#[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")] +impl TryFrom> for CString { + type Error = FromBytesWithNulError; + + /// See the document about [`from_vec_with_nul`] for more + /// informations about the behaviour of this method. + /// + /// [`from_vec_with_nul`]: struct.CString.html#method.from_vec_with_nul + fn try_from(value: Vec) -> Result { + Self::from_vec_with_nul(value) + } +} + #[stable(feature = "more_box_slice_clone", since = "1.29.0")] impl Clone for Box { #[inline] From 6b955268d71907d9049a399a0e0a33f6448e1221 Mon Sep 17 00:00:00 2001 From: Alexis Bourget Date: Thu, 11 Jun 2020 16:55:03 +0200 Subject: [PATCH 13/41] Fix the link in the TryFrom impl --- src/libstd/ffi/c_str.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libstd/ffi/c_str.rs b/src/libstd/ffi/c_str.rs index 3a3b51fd353b2..298f6c33457d8 100644 --- a/src/libstd/ffi/c_str.rs +++ b/src/libstd/ffi/c_str.rs @@ -861,7 +861,7 @@ impl TryFrom> for CString { /// See the document about [`from_vec_with_nul`] for more /// informations about the behaviour of this method. /// - /// [`from_vec_with_nul`]: struct.CString.html#method.from_vec_with_nul + /// [`from_vec_with_nul`]: CString::from_vec_with_nul fn try_from(value: Vec) -> Result { Self::from_vec_with_nul(value) } From 871513d02cf4d5c40689052aa7a1f3681fc3fdcc Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Mon, 1 Jun 2020 08:42:40 +0200 Subject: [PATCH 14/41] make miri memory TyCtxtAt a TyCtxt --- src/librustc_mir/interpret/eval_context.rs | 3 +-- src/librustc_mir/interpret/memory.rs | 20 ++++++++++---------- 2 files changed, 11 insertions(+), 12 deletions(-) diff --git a/src/librustc_mir/interpret/eval_context.rs b/src/librustc_mir/interpret/eval_context.rs index 6497e211de316..844f2ea07023b 100644 --- a/src/librustc_mir/interpret/eval_context.rs +++ b/src/librustc_mir/interpret/eval_context.rs @@ -301,7 +301,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { machine, tcx, param_env, - memory: Memory::new(tcx, memory_extra), + memory: Memory::new(*tcx, memory_extra), vtables: FxHashMap::default(), } } @@ -309,7 +309,6 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { #[inline(always)] pub fn set_span(&mut self, span: Span) { self.tcx.span = span; - self.memory.tcx.span = span; } #[inline(always)] diff --git a/src/librustc_mir/interpret/memory.rs b/src/librustc_mir/interpret/memory.rs index d7f64542aa78d..61dea4d43cea6 100644 --- a/src/librustc_mir/interpret/memory.rs +++ b/src/librustc_mir/interpret/memory.rs @@ -14,7 +14,7 @@ use std::ptr; use rustc_ast::ast::Mutability; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; -use rustc_middle::ty::{self, query::TyCtxtAt, Instance, ParamEnv}; +use rustc_middle::ty::{self, TyCtxt, Instance, ParamEnv}; use rustc_target::abi::{Align, HasDataLayout, Size, TargetDataLayout}; use super::{ @@ -115,7 +115,7 @@ pub struct Memory<'mir, 'tcx, M: Machine<'mir, 'tcx>> { pub extra: M::MemoryExtra, /// Lets us implement `HasDataLayout`, which is awfully convenient. - pub tcx: TyCtxtAt<'tcx>, + pub tcx: TyCtxt<'tcx>, } impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> HasDataLayout for Memory<'mir, 'tcx, M> { @@ -126,7 +126,7 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> HasDataLayout for Memory<'mir, 'tcx, M> } impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> { - pub fn new(tcx: TyCtxtAt<'tcx>, extra: M::MemoryExtra) -> Self { + pub fn new(tcx: TyCtxt<'tcx>, extra: M::MemoryExtra) -> Self { Memory { alloc_map: M::MemoryMap::default(), extra_fn_ptr_map: FxHashMap::default(), @@ -425,7 +425,7 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> { /// `M::tag_allocation`. fn get_global_alloc( memory_extra: &M::MemoryExtra, - tcx: TyCtxtAt<'tcx>, + tcx: TyCtxt<'tcx>, id: AllocId, is_write: bool, ) -> InterpResult<'tcx, Cow<'tcx, Allocation>> { @@ -455,7 +455,7 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> { throw_unsup!(ReadForeignStatic(def_id)) } trace!("get_global_alloc: Need to compute {:?}", def_id); - let instance = Instance::mono(tcx.tcx, def_id); + let instance = Instance::mono(tcx, def_id); let gid = GlobalId { instance, promoted: None }; // Use the raw query here to break validation cycles. Later uses of the static // will call the full query anyway. @@ -664,14 +664,14 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> { pub fn dump_allocs(&self, mut allocs: Vec) { // Cannot be a closure because it is generic in `Tag`, `Extra`. fn write_allocation_track_relocs<'tcx, Tag: Copy + fmt::Debug, Extra>( - tcx: TyCtxtAt<'tcx>, + tcx: TyCtxt<'tcx>, allocs_to_print: &mut VecDeque, alloc: &Allocation, ) { for &(_, target_id) in alloc.relocations().values() { allocs_to_print.push_back(target_id); } - pretty::write_allocation(tcx.tcx, alloc, &mut std::io::stderr()).unwrap(); + pretty::write_allocation(tcx, alloc, &mut std::io::stderr()).unwrap(); } allocs.sort(); @@ -820,7 +820,7 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> { return Ok(()); } }; - let tcx = self.tcx.tcx; + let tcx = self.tcx; self.get_raw_mut(ptr.alloc_id)?.write_bytes(&tcx, ptr, src) } @@ -846,7 +846,7 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> { return Ok(()); } }; - let tcx = self.tcx.tcx; + let tcx = self.tcx; let allocation = self.get_raw_mut(ptr.alloc_id)?; for idx in 0..len { @@ -888,7 +888,7 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> { let relocations = self.get_raw(src.alloc_id)?.prepare_relocation_copy(self, src, size, dest, length); - let tcx = self.tcx.tcx; + let tcx = self.tcx; // This checks relocation edges on the src. let src_bytes = From dc6ffaebd5b56793f86443a0a50c06f025321198 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Mon, 1 Jun 2020 10:15:17 +0200 Subject: [PATCH 15/41] make miri InterpCx TyCtxtAt a TyCtxt, and separately remember the root span of the evaluation --- src/librustc_middle/ty/util.rs | 1 + src/librustc_mir/const_eval/error.rs | 2 +- src/librustc_mir/const_eval/eval_queries.rs | 21 +++---- src/librustc_mir/interpret/cast.rs | 8 +-- src/librustc_mir/interpret/eval_context.rs | 60 ++++++++++++------- src/librustc_mir/interpret/intern.rs | 18 +++--- src/librustc_mir/interpret/intrinsics.rs | 4 +- .../interpret/intrinsics/caller_location.rs | 4 +- src/librustc_mir/interpret/memory.rs | 2 +- src/librustc_mir/interpret/operand.rs | 16 ++--- src/librustc_mir/interpret/place.rs | 39 ++++++------ src/librustc_mir/interpret/step.rs | 2 - src/librustc_mir/interpret/terminator.rs | 8 +-- src/librustc_mir/interpret/traits.rs | 32 +++++----- src/librustc_mir/transform/const_prop.rs | 15 ++--- 15 files changed, 123 insertions(+), 109 deletions(-) diff --git a/src/librustc_middle/ty/util.rs b/src/librustc_middle/ty/util.rs index c2b794ca4bdd9..29da7ff085065 100644 --- a/src/librustc_middle/ty/util.rs +++ b/src/librustc_middle/ty/util.rs @@ -705,6 +705,7 @@ impl<'tcx> ty::TyS<'tcx> { /// optimization as well as the rules around static values. Note /// that the `Freeze` trait is not exposed to end users and is /// effectively an implementation detail. + // FIXME: use `TyCtxtAt` instead of separate `Span`. pub fn is_freeze( &'tcx self, tcx: TyCtxt<'tcx>, diff --git a/src/librustc_mir/const_eval/error.rs b/src/librustc_mir/const_eval/error.rs index b165a69433db1..2aafafd8205d1 100644 --- a/src/librustc_mir/const_eval/error.rs +++ b/src/librustc_mir/const_eval/error.rs @@ -56,5 +56,5 @@ pub fn error_to_const_error<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>>( ) -> ConstEvalErr<'tcx> { error.print_backtrace(); let stacktrace = ecx.generate_stacktrace(); - ConstEvalErr { error: error.kind, stacktrace, span: ecx.tcx.span } + ConstEvalErr { error: error.kind, stacktrace, span: ecx.cur_span() } } diff --git a/src/librustc_mir/const_eval/eval_queries.rs b/src/librustc_mir/const_eval/eval_queries.rs index 2c0a40b4c543c..4101ea77c9080 100644 --- a/src/librustc_mir/const_eval/eval_queries.rs +++ b/src/librustc_mir/const_eval/eval_queries.rs @@ -27,7 +27,7 @@ fn eval_body_using_ecx<'mir, 'tcx>( body: &'mir mir::Body<'tcx>, ) -> InterpResult<'tcx, MPlaceTy<'tcx>> { debug!("eval_body_using_ecx: {:?}, {:?}", cid, ecx.param_env); - let tcx = ecx.tcx.tcx; + let tcx = ecx.tcx; let layout = ecx.layout_of(body.return_ty().subst(tcx, cid.instance.substs))?; assert!(!layout.is_unsized()); let ret = ecx.allocate(layout, MemoryKind::Stack); @@ -81,13 +81,14 @@ fn eval_body_using_ecx<'mir, 'tcx>( /// parameter. These bounds are passed to `mk_eval_cx` via the `ParamEnv` argument. pub(super) fn mk_eval_cx<'mir, 'tcx>( tcx: TyCtxt<'tcx>, - span: Span, + root_span: Span, param_env: ty::ParamEnv<'tcx>, can_access_statics: bool, ) -> CompileTimeEvalContext<'mir, 'tcx> { debug!("mk_eval_cx: {:?}", param_env); InterpCx::new( - tcx.at(span), + tcx, + root_span, param_env, CompileTimeInterpreter::new(tcx.sess.const_eval_limit()), MemoryExtra { can_access_statics }, @@ -163,7 +164,7 @@ pub(super) fn op_to_const<'tcx>( 0, ), }; - let len = b.to_machine_usize(&ecx.tcx.tcx).unwrap(); + let len = b.to_machine_usize(ecx).unwrap(); let start = start.try_into().unwrap(); let len: usize = len.try_into().unwrap(); ConstValue::Slice { data, start, end: start + len } @@ -213,7 +214,7 @@ fn validate_and_turn_into_const<'tcx>( val.map_err(|error| { let err = error_to_const_error(&ecx, error); - err.struct_error(ecx.tcx, "it is undefined behavior to use this value", |mut diag| { + err.struct_error(ecx.tcx_at(), "it is undefined behavior to use this value", |mut diag| { diag.note(note_on_undefined_behavior_error()); diag.emit(); }) @@ -299,9 +300,9 @@ pub fn const_eval_raw_provider<'tcx>( let is_static = tcx.is_static(def_id); - let span = tcx.def_span(cid.instance.def_id()); let mut ecx = InterpCx::new( - tcx.at(span), + tcx, + tcx.def_span(cid.instance.def_id()), key.param_env, CompileTimeInterpreter::new(tcx.sess.const_eval_limit()), MemoryExtra { can_access_statics: is_static }, @@ -316,7 +317,7 @@ pub fn const_eval_raw_provider<'tcx>( if is_static { // Ensure that if the above error was either `TooGeneric` or `Reported` // an error must be reported. - let v = err.report_as_error(ecx.tcx, "could not evaluate static initializer"); + let v = err.report_as_error(ecx.tcx_at(), "could not evaluate static initializer"); // If this is `Reveal:All`, then we need to make sure an error is reported but if // this is `Reveal::UserFacing`, then it's expected that we could get a @@ -372,13 +373,13 @@ pub fn const_eval_raw_provider<'tcx>( // anything else (array lengths, enum initializers, constant patterns) are // reported as hard errors } else { - err.report_as_error(ecx.tcx, "evaluation of constant value failed") + err.report_as_error(ecx.tcx_at(), "evaluation of constant value failed") } } } } else { // use of broken constant from other crate - err.report_as_error(ecx.tcx, "could not evaluate constant") + err.report_as_error(ecx.tcx_at(), "could not evaluate constant") } }) } diff --git a/src/librustc_mir/interpret/cast.rs b/src/librustc_mir/interpret/cast.rs index 0fd695586eb98..287b43ac50f96 100644 --- a/src/librustc_mir/interpret/cast.rs +++ b/src/librustc_mir/interpret/cast.rs @@ -56,7 +56,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { } let instance = ty::Instance::resolve_for_fn_ptr( - *self.tcx, + self.tcx, self.param_env, def_id, substs, @@ -91,7 +91,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { } let instance = ty::Instance::resolve_closure( - *self.tcx, + self.tcx, def_id, substs, ty::ClosureKind::FnOnce, @@ -140,7 +140,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // Handle cast from a univariant (ZST) enum. match src.layout.variants { Variants::Single { index } => { - if let Some(discr) = src.layout.ty.discriminant_for_variant(*self.tcx, index) { + if let Some(discr) = src.layout.ty.discriminant_for_variant(self.tcx, index) { assert!(src.layout.is_zst()); let discr_layout = self.layout_of(discr.ty)?; return Ok(self.cast_from_scalar(discr.val, discr_layout, cast_ty).into()); @@ -270,7 +270,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // u64 cast is from usize to u64, which is always good let val = Immediate::new_slice( ptr, - length.eval_usize(self.tcx.tcx, self.param_env), + length.eval_usize(self.tcx, self.param_env), self, ); self.write_immediate(val, dest) diff --git a/src/librustc_mir/interpret/eval_context.rs b/src/librustc_mir/interpret/eval_context.rs index 844f2ea07023b..1715b6fede962 100644 --- a/src/librustc_mir/interpret/eval_context.rs +++ b/src/librustc_mir/interpret/eval_context.rs @@ -33,7 +33,11 @@ pub struct InterpCx<'mir, 'tcx, M: Machine<'mir, 'tcx>> { pub machine: M, /// The results of the type checker, from rustc. - pub tcx: TyCtxtAt<'tcx>, + pub tcx: TyCtxt<'tcx>, + + /// The span of the "root" of the evaluation, i.e., the const + /// we are evaluating (if this is CTFE). + pub(super) root_span: Span, /// Bounds in scope for polymorphic evaluations. pub(crate) param_env: ty::ParamEnv<'tcx>, @@ -196,7 +200,7 @@ where { #[inline] fn tcx(&self) -> TyCtxt<'tcx> { - *self.tcx + self.tcx } } @@ -209,13 +213,13 @@ where } } -impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> LayoutOf for InterpCx<'mir, 'tcx, M> { +impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> LayoutOf for InterpCx<'mir, 'tcx, M> { type Ty = Ty<'tcx>; type TyAndLayout = InterpResult<'tcx, TyAndLayout<'tcx>>; #[inline] fn layout_of(&self, ty: Ty<'tcx>) -> Self::TyAndLayout { - self.tcx + self.tcx_at() .layout_of(self.param_env.and(ty)) .map_err(|layout| err_inval!(Layout(layout)).into()) } @@ -292,7 +296,8 @@ pub(super) fn from_known_layout<'tcx>( impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { pub fn new( - tcx: TyCtxtAt<'tcx>, + tcx: TyCtxt<'tcx>, + root_span: Span, param_env: ty::ParamEnv<'tcx>, machine: M, memory_extra: M::MemoryExtra, @@ -300,15 +305,26 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { InterpCx { machine, tcx, + root_span, param_env, - memory: Memory::new(*tcx, memory_extra), + memory: Memory::new(tcx, memory_extra), vtables: FxHashMap::default(), } } #[inline(always)] - pub fn set_span(&mut self, span: Span) { - self.tcx.span = span; + pub fn cur_span(&self) -> Span { + self + .stack() + .last() + .and_then(|f| f.current_source_info()) + .map(|si| si.span) + .unwrap_or(self.root_span) + } + + #[inline(always)] + pub fn tcx_at(&self) -> TyCtxtAt<'tcx> { + self.tcx.at(self.cur_span()) } #[inline(always)] @@ -386,12 +402,12 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { #[inline] pub fn type_is_sized(&self, ty: Ty<'tcx>) -> bool { - ty.is_sized(self.tcx, self.param_env) + ty.is_sized(self.tcx_at(), self.param_env) } #[inline] pub fn type_is_freeze(&self, ty: Ty<'tcx>) -> bool { - ty.is_freeze(*self.tcx, self.param_env, DUMMY_SP) + ty.is_freeze(self.tcx, self.param_env, self.cur_span()) } pub fn load_mir( @@ -402,20 +418,20 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // do not continue if typeck errors occurred (can only occur in local crate) let did = instance.def_id(); if let Some(did) = did.as_local() { - if self.tcx.has_typeck_tables(did) { - if let Some(error_reported) = self.tcx.typeck_tables_of(did).tainted_by_errors { + if self.tcx_at().has_typeck_tables(did) { + if let Some(error_reported) = self.tcx_at().typeck_tables_of(did).tainted_by_errors { throw_inval!(TypeckError(error_reported)) } } } trace!("load mir(instance={:?}, promoted={:?})", instance, promoted); if let Some(promoted) = promoted { - return Ok(&self.tcx.promoted_mir(did)[promoted]); + return Ok(&self.tcx_at().promoted_mir(did)[promoted]); } match instance { ty::InstanceDef::Item(def_id) => { - if self.tcx.is_mir_available(did) { - Ok(self.tcx.optimized_mir(did)) + if self.tcx_at().is_mir_available(did) { + Ok(self.tcx_at().optimized_mir(did)) } else { throw_unsup!(NoMirFor(def_id)) } @@ -456,7 +472,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { trace!("resolve: {:?}, {:#?}", def_id, substs); trace!("param_env: {:#?}", self.param_env); trace!("substs: {:#?}", substs); - match ty::Instance::resolve(*self.tcx, self.param_env, def_id, substs) { + match ty::Instance::resolve(self.tcx, self.param_env, def_id, substs) { Ok(Some(instance)) => Ok(instance), Ok(None) => throw_inval!(TooGeneric), @@ -475,7 +491,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // have to support that case (mostly by skipping all caching). match frame.locals.get(local).and_then(|state| state.layout.get()) { None => { - let layout = from_known_layout(self.tcx, layout, || { + let layout = from_known_layout(self.tcx_at(), layout, || { let local_ty = frame.body.local_decls[local].ty; let local_ty = self.subst_from_frame_and_normalize_erasing_regions(frame, local_ty); @@ -560,7 +576,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { let size = size.align_to(align); // Check if this brought us over the size limit. - if size.bytes() >= self.tcx.data_layout().obj_size_bound() { + if size.bytes() >= self.tcx.data_layout.obj_size_bound() { throw_ub!(InvalidMeta("total size is bigger than largest supported object")); } Ok(Some((size, align))) @@ -576,7 +592,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { let elem = layout.field(self, 0)?; // Make sure the slice is not too big. - let size = elem.size.checked_mul(len, &*self.tcx).ok_or_else(|| { + let size = elem.size.checked_mul(len, self).ok_or_else(|| { err_ub!(InvalidMeta("slice is bigger than largest supported object")) })?; Ok(Some((size, elem.align.abi))) @@ -627,7 +643,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { 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()) { + match self.tcx_at().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 @@ -842,7 +858,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { } else { self.param_env }; - let val = self.tcx.const_eval_global_id(param_env, gid, Some(self.tcx.span))?; + let val = self.tcx.const_eval_global_id(param_env, gid, Some(self.cur_span()))?; // Even though `ecx.const_eval` is called from `eval_const_to_op` we can never have a // recursion deeper than one level, because the `tcx.const_eval` above is guaranteed to not @@ -873,7 +889,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // FIXME: We can hit delay_span_bug if this is an invalid const, interning finds // that problem, but we never run validation to show an error. Can we ensure // this does not happen? - let val = self.tcx.const_eval_raw(param_env.and(gid))?; + let val = self.tcx_at().const_eval_raw(param_env.and(gid))?; self.raw_const_to_mplace(val) } diff --git a/src/librustc_mir/interpret/intern.rs b/src/librustc_mir/interpret/intern.rs index 02a7f24a1e351..284a1d5ea61ef 100644 --- a/src/librustc_mir/interpret/intern.rs +++ b/src/librustc_mir/interpret/intern.rs @@ -93,7 +93,7 @@ fn intern_shallow<'rt, 'mir, 'tcx, M: CompileTimeMachine<'mir, 'tcx>>( // in the value the dangling reference lies. // The `delay_span_bug` ensures that we don't forget such a check in validation. if tcx.get_global_alloc(alloc_id).is_none() { - tcx.sess.delay_span_bug(ecx.tcx.span, "tried to intern dangling pointer"); + tcx.sess.delay_span_bug(ecx.root_span, "tried to intern dangling pointer"); } // treat dangling pointers like other statics // just to stop trying to recurse into them @@ -111,7 +111,7 @@ fn intern_shallow<'rt, 'mir, 'tcx, M: CompileTimeMachine<'mir, 'tcx>>( if let InternMode::Static(mutability) = mode { // For this, we need to take into account `UnsafeCell`. When `ty` is `None`, we assume // no interior mutability. - let frozen = ty.map_or(true, |ty| ty.is_freeze(ecx.tcx.tcx, ecx.param_env, ecx.tcx.span)); + let frozen = ty.map_or(true, |ty| ty.is_freeze(ecx.tcx, ecx.param_env, ecx.root_span)); // For statics, allocation mutability is the combination of the place mutability and // the type mutability. // The entire allocation needs to be mutable if it contains an `UnsafeCell` anywhere. @@ -174,7 +174,7 @@ impl<'rt, 'mir, 'tcx: 'mir, M: CompileTimeMachine<'mir, 'tcx>> ValueVisitor<'mir // they caused. It also helps us to find cases where const-checking // failed to prevent an `UnsafeCell` (but as `ignore_interior_mut_in_const` // shows that part is not airtight). - mutable_memory_in_const(self.ecx.tcx, "`UnsafeCell`"); + mutable_memory_in_const(self.ecx.tcx_at(), "`UnsafeCell`"); } // We are crossing over an `UnsafeCell`, we can mutate again. This means that // References we encounter inside here are interned as pointing to mutable @@ -192,7 +192,7 @@ impl<'rt, 'mir, 'tcx: 'mir, M: CompileTimeMachine<'mir, 'tcx>> ValueVisitor<'mir fn visit_value(&mut self, mplace: MPlaceTy<'tcx>) -> InterpResult<'tcx> { // Handle Reference types, as these are the only relocations supported by const eval. // Raw pointers (and boxes) are handled by the `leftover_relocations` logic. - let tcx = self.ecx.tcx; + let tcx = self.ecx.tcx.at(self.ecx.root_span); let ty = mplace.layout.ty; if let ty::Ref(_, referenced_ty, ref_mutability) = ty.kind { let value = self.ecx.read_immediate(mplace.into())?; @@ -254,7 +254,7 @@ impl<'rt, 'mir, 'tcx: 'mir, M: CompileTimeMachine<'mir, 'tcx>> ValueVisitor<'mir if ref_mutability == Mutability::Mut { match referenced_ty.kind { ty::Array(_, n) - if n.eval_usize(tcx.tcx, self.ecx.param_env) == 0 => {} + if n.eval_usize(self.ecx.tcx, self.ecx.param_env) == 0 => {} ty::Slice(_) if mplace.meta.unwrap_meta().to_machine_usize(self.ecx)? == 0 => {} @@ -358,7 +358,7 @@ pub fn intern_const_alloc_recursive>( Ok(()) => {} Err(error) => { ecx.tcx.sess.delay_span_bug( - ecx.tcx.span, + ecx.root_span, "error during interning should later cause validation failure", ); // Some errors shouldn't come up because creating them causes @@ -407,7 +407,7 @@ pub fn intern_const_alloc_recursive>( // such as `const CONST_RAW: *const Vec = &Vec::new() as *const _;`. ecx.tcx .sess - .span_err(ecx.tcx.span, "untyped pointers are not allowed in constant"); + .span_err(ecx.root_span, "untyped pointers are not allowed in constant"); // For better errors later, mark the allocation as immutable. alloc.mutability = Mutability::Not; } @@ -422,11 +422,11 @@ pub fn intern_const_alloc_recursive>( } else if ecx.memory.dead_alloc_map.contains_key(&alloc_id) { // Codegen does not like dangling pointers, and generally `tcx` assumes that // all allocations referenced anywhere actually exist. So, make sure we error here. - ecx.tcx.sess.span_err(ecx.tcx.span, "encountered dangling pointer in final constant"); + ecx.tcx.sess.span_err(ecx.root_span, "encountered dangling pointer in final constant"); } else if ecx.tcx.get_global_alloc(alloc_id).is_none() { // We have hit an `AllocId` that is neither in local or global memory and isn't // marked as dangling by local memory. That should be impossible. - span_bug!(ecx.tcx.span, "encountered unknown alloc id {:?}", alloc_id); + span_bug!(ecx.root_span, "encountered unknown alloc id {:?}", alloc_id); } } } diff --git a/src/librustc_mir/interpret/intrinsics.rs b/src/librustc_mir/interpret/intrinsics.rs index 115a472cabe5e..c62fd316dc584 100644 --- a/src/librustc_mir/interpret/intrinsics.rs +++ b/src/librustc_mir/interpret/intrinsics.rs @@ -347,7 +347,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { let index = u64::from(self.read_scalar(args[1])?.to_u32()?); let elem = args[2]; let input = args[0]; - let (len, e_ty) = input.layout.ty.simd_size_and_type(self.tcx.tcx); + let (len, e_ty) = input.layout.ty.simd_size_and_type(self.tcx); assert!( index < len, "Index `{}` must be in bounds of vector type `{}`: `[0, {})`", @@ -374,7 +374,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { } sym::simd_extract => { let index = u64::from(self.read_scalar(args[1])?.to_u32()?); - let (len, e_ty) = args[0].layout.ty.simd_size_and_type(self.tcx.tcx); + let (len, e_ty) = args[0].layout.ty.simd_size_and_type(self.tcx); assert!( index < len, "index `{}` is out-of-bounds of vector type `{}` with length `{}`", diff --git a/src/librustc_mir/interpret/intrinsics/caller_location.rs b/src/librustc_mir/interpret/intrinsics/caller_location.rs index ddeed92f85124..193d38dc5523e 100644 --- a/src/librustc_mir/interpret/intrinsics/caller_location.rs +++ b/src/librustc_mir/interpret/intrinsics/caller_location.rs @@ -25,7 +25,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { "find_closest_untracked_caller_location: checking frame {:?}", frame.instance ); - !frame.instance.def.requires_caller_location(*self.tcx) + !frame.instance.def.requires_caller_location(self.tcx) }) // Assert that there is always such a frame. .unwrap(); @@ -58,7 +58,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { let loc_ty = self .tcx .type_of(self.tcx.require_lang_item(PanicLocationLangItem, None)) - .subst(*self.tcx, self.tcx.mk_substs([self.tcx.lifetimes.re_erased.into()].iter())); + .subst(self.tcx, self.tcx.mk_substs([self.tcx.lifetimes.re_erased.into()].iter())); let loc_layout = self.layout_of(loc_ty).unwrap(); let location = self.allocate(loc_layout, MemoryKind::CallerLocation); diff --git a/src/librustc_mir/interpret/memory.rs b/src/librustc_mir/interpret/memory.rs index 61dea4d43cea6..8af1a8ac608ac 100644 --- a/src/librustc_mir/interpret/memory.rs +++ b/src/librustc_mir/interpret/memory.rs @@ -14,7 +14,7 @@ use std::ptr; use rustc_ast::ast::Mutability; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; -use rustc_middle::ty::{self, TyCtxt, Instance, ParamEnv}; +use rustc_middle::ty::{self, Instance, ParamEnv, TyCtxt}; use rustc_target::abi::{Align, HasDataLayout, Size, TargetDataLayout}; use super::{ diff --git a/src/librustc_mir/interpret/operand.rs b/src/librustc_mir/interpret/operand.rs index db4473154c471..c9250098fedba 100644 --- a/src/librustc_mir/interpret/operand.rs +++ b/src/librustc_mir/interpret/operand.rs @@ -471,9 +471,9 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { trace!("eval_place_to_op: got {:?}", *op); // Sanity-check the type we ended up with. debug_assert!(mir_assign_valid_types( - *self.tcx, + self.tcx, self.layout_of(self.subst_from_current_frame_and_normalize_erasing_regions( - place.ty(&self.frame().body.local_decls, *self.tcx).ty + place.ty(&self.frame().body.local_decls, self.tcx).ty ))?, op.layout, )); @@ -554,7 +554,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // documentation). let val_val = M::adjust_global_const(self, val_val)?; // Other cases need layout. - let layout = from_known_layout(self.tcx, layout, || self.layout_of(val.ty))?; + let layout = from_known_layout(self.tcx_at(), layout, || self.layout_of(val.ty))?; let op = match val_val { ConstValue::ByRef { alloc, offset } => { let id = self.tcx.create_memory_alloc(alloc); @@ -589,7 +589,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { trace!("read_discriminant_value {:#?}", op.layout); // Get type and layout of the discriminant. - let discr_layout = self.layout_of(op.layout.ty.discriminant_ty(*self.tcx))?; + let discr_layout = self.layout_of(op.layout.ty.discriminant_ty(self.tcx))?; trace!("discriminant type: {:?}", discr_layout.ty); // We use "discriminant" to refer to the value associated with a particular enum variant. @@ -601,7 +601,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // rather confusing. let (tag_scalar_layout, tag_kind, tag_index) = match op.layout.variants { Variants::Single { index } => { - let discr = match op.layout.ty.discriminant_for_variant(*self.tcx, index) { + let discr = match op.layout.ty.discriminant_for_variant(self.tcx, index) { Some(discr) => { // This type actually has discriminants. assert_eq!(discr.ty, discr_layout.ty); @@ -630,7 +630,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // may be a pointer. This is `tag_val.layout`; we just use it for sanity checks. // Get layout for tag. - let tag_layout = self.layout_of(tag_scalar_layout.value.to_int_ty(*self.tcx))?; + let tag_layout = self.layout_of(tag_scalar_layout.value.to_int_ty(self.tcx))?; // Read tag and sanity-check `tag_layout`. let tag_val = self.read_immediate(self.operand_field(op, tag_index)?)?; @@ -651,12 +651,12 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // Convert discriminant to variant index, and catch invalid discriminants. let index = match op.layout.ty.kind { ty::Adt(adt, _) => { - adt.discriminants(self.tcx.tcx).find(|(_, var)| var.val == discr_bits) + adt.discriminants(self.tcx).find(|(_, var)| var.val == discr_bits) } ty::Generator(def_id, substs, _) => { let substs = substs.as_generator(); substs - .discriminants(def_id, self.tcx.tcx) + .discriminants(def_id, self.tcx) .find(|(_, var)| var.val == discr_bits) } _ => bug!("tagged layout for non-adt non-generator"), diff --git a/src/librustc_mir/interpret/place.rs b/src/librustc_mir/interpret/place.rs index 3f0800b12b549..0b4e92574a066 100644 --- a/src/librustc_mir/interpret/place.rs +++ b/src/librustc_mir/interpret/place.rs @@ -404,7 +404,7 @@ where // to get some code to work that probably ought to work. field_layout.align.abi } - None => bug!("Cannot compute offset for extern type field at non-0 offset"), + None => span_bug!(self.cur_span(), "cannot compute offset for extern type field at non-0 offset"), }; (base.meta, offset.align_to(align)) } else { @@ -440,7 +440,7 @@ where assert!(!field_layout.is_unsized()); base.offset(offset, MemPlaceMeta::None, field_layout, self) } - _ => bug!("`mplace_index` called on non-array type {:?}", base.layout.ty), + _ => span_bug!(self.cur_span(), "`mplace_index` called on non-array type {:?}", base.layout.ty), } } @@ -454,7 +454,7 @@ where let len = base.len(self)?; // also asserts that we have a type where this makes sense let stride = match base.layout.fields { FieldsShape::Array { stride, .. } => stride, - _ => bug!("mplace_array_fields: expected an array layout"), + _ => span_bug!(self.cur_span(), "mplace_array_fields: expected an array layout"), }; let layout = base.layout.field(self, 0)?; let dl = &self.tcx.data_layout; @@ -484,7 +484,7 @@ where // (that have count 0 in their layout). let from_offset = match base.layout.fields { FieldsShape::Array { stride, .. } => stride * from, // `Size` multiplication is checked - _ => bug!("Unexpected layout of index access: {:#?}", base.layout), + _ => span_bug!(self.cur_span(), "unexpected layout of index access: {:#?}", base.layout), }; // Compute meta and new layout @@ -497,7 +497,7 @@ where let len = Scalar::from_machine_usize(inner_len, self); (MemPlaceMeta::Meta(len), base.layout.ty) } - _ => bug!("cannot subslice non-array type: `{:?}`", base.layout.ty), + _ => span_bug!(self.cur_span(), "cannot subslice non-array type: `{:?}`", base.layout.ty), }; let layout = self.layout_of(ty)?; base.offset(from_offset, meta, layout, self) @@ -640,9 +640,9 @@ where self.dump_place(place_ty.place); // Sanity-check the type we ended up with. debug_assert!(mir_assign_valid_types( - *self.tcx, + self.tcx, self.layout_of(self.subst_from_current_frame_and_normalize_erasing_regions( - place.ty(&self.frame().body.local_decls, *self.tcx).ty + place.ty(&self.frame().body.local_decls, self.tcx).ty ))?, place_ty.layout, )); @@ -768,7 +768,7 @@ where None => return Ok(()), // zero-sized access }; - let tcx = &*self.tcx; + let tcx = self.tcx; // FIXME: We should check that there are dest.layout.size many bytes available in // memory. The code below is not sufficient, with enough padding it might not // cover all the bytes! @@ -777,11 +777,11 @@ where match dest.layout.abi { Abi::Scalar(_) => {} // fine _ => { - bug!("write_immediate_to_mplace: invalid Scalar layout: {:#?}", dest.layout) + span_bug!(self.cur_span(), "write_immediate_to_mplace: invalid Scalar layout: {:#?}", dest.layout) } } self.memory.get_raw_mut(ptr.alloc_id)?.write_scalar( - tcx, + &tcx, ptr, scalar, dest.layout.size, @@ -793,7 +793,8 @@ where // which `ptr.offset(b_offset)` cannot possibly fail to satisfy. let (a, b) = match dest.layout.abi { Abi::ScalarPair(ref a, ref b) => (&a.value, &b.value), - _ => bug!( + _ => span_bug!( + self.cur_span(), "write_immediate_to_mplace: invalid ScalarPair layout: {:#?}", dest.layout ), @@ -806,8 +807,8 @@ where // but that does not work: We could be a newtype around a pair, then the // fields do not match the `ScalarPair` components. - self.memory.get_raw_mut(ptr.alloc_id)?.write_scalar(tcx, ptr, a_val, a_size)?; - self.memory.get_raw_mut(b_ptr.alloc_id)?.write_scalar(tcx, b_ptr, b_val, b_size) + self.memory.get_raw_mut(ptr.alloc_id)?.write_scalar(&tcx, ptr, a_val, a_size)?; + self.memory.get_raw_mut(b_ptr.alloc_id)?.write_scalar(&tcx, b_ptr, b_val, b_size) } } } @@ -841,9 +842,9 @@ where ) -> InterpResult<'tcx> { // We do NOT compare the types for equality, because well-typed code can // actually "transmute" `&mut T` to `&T` in an assignment without a cast. - if !mir_assign_valid_types(self.tcx.tcx, src.layout, dest.layout) { + if !mir_assign_valid_types(self.tcx, src.layout, dest.layout) { span_bug!( - self.tcx.span, + self.cur_span(), "type mismatch when copying!\nsrc: {:?},\ndest: {:?}", src.layout.ty, dest.layout.ty, @@ -898,7 +899,7 @@ where src: OpTy<'tcx, M::PointerTag>, dest: PlaceTy<'tcx, M::PointerTag>, ) -> InterpResult<'tcx> { - if mir_assign_valid_types(self.tcx.tcx, src.layout, dest.layout) { + if mir_assign_valid_types(self.tcx, src.layout, dest.layout) { // Fast path: Just use normal `copy_op` return self.copy_op(src, dest); } @@ -910,7 +911,7 @@ where // on `typeck_tables().has_errors` at all const eval entry points. debug!("Size mismatch when transmuting!\nsrc: {:#?}\ndest: {:#?}", src, dest); self.tcx.sess.delay_span_bug( - self.tcx.span, + self.cur_span(), "size-changing transmute, should have been caught by transmute checking", ); throw_inval!(TransmuteSizeDiff(src.layout.ty, dest.layout.ty)); @@ -1056,7 +1057,7 @@ where // `TyAndLayout::for_variant()` call earlier already checks the variant is valid. let discr_val = - dest.layout.ty.discriminant_for_variant(*self.tcx, variant_index).unwrap().val; + dest.layout.ty.discriminant_for_variant(self.tcx, variant_index).unwrap().val; // raw discriminants for enums are isize or bigger during // their computation, but the in-memory tag is the smallest possible @@ -1085,7 +1086,7 @@ where .expect("overflow computing relative variant idx"); // We need to use machine arithmetic when taking into account `niche_start`: // discr_val = variant_index_relative + niche_start_val - let discr_layout = self.layout_of(discr_layout.value.to_int_ty(*self.tcx))?; + let discr_layout = self.layout_of(discr_layout.value.to_int_ty(self.tcx))?; let niche_start_val = ImmTy::from_uint(niche_start, discr_layout); let variant_index_relative_val = ImmTy::from_uint(variant_index_relative, discr_layout); diff --git a/src/librustc_mir/interpret/step.rs b/src/librustc_mir/interpret/step.rs index 02a709ab1a134..16c6396799e63 100644 --- a/src/librustc_mir/interpret/step.rs +++ b/src/librustc_mir/interpret/step.rs @@ -76,7 +76,6 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { fn statement(&mut self, stmt: &mir::Statement<'tcx>) -> InterpResult<'tcx> { info!("{:?}", stmt); - self.set_span(stmt.source_info.span); use rustc_middle::mir::StatementKind::*; @@ -279,7 +278,6 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { fn terminator(&mut self, terminator: &mir::Terminator<'tcx>) -> InterpResult<'tcx> { info!("{:?}", terminator.kind); - self.set_span(terminator.source_info.span); self.eval_terminator(terminator)?; if !self.stack().is_empty() { diff --git a/src/librustc_mir/interpret/terminator.rs b/src/librustc_mir/interpret/terminator.rs index cd7621ea9752b..9a4dd0a5204f9 100644 --- a/src/librustc_mir/interpret/terminator.rs +++ b/src/librustc_mir/interpret/terminator.rs @@ -69,7 +69,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { (fn_val, caller_abi) } ty::FnDef(def_id, substs) => { - let sig = func.layout.ty.fn_sig(*self.tcx); + let sig = func.layout.ty.fn_sig(self.tcx); (FnVal::Instance(self.resolve(def_id, substs)?), sig.abi()) } _ => span_bug!( @@ -96,7 +96,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { let ty = place.layout.ty; trace!("TerminatorKind::drop: {:?}, type {}", location, ty); - let instance = Instance::resolve_drop_in_place(*self.tcx, ty); + let instance = Instance::resolve_drop_in_place(self.tcx, ty); self.drop_in_place(place, instance, target, unwind)?; } @@ -227,9 +227,9 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // ABI check { let callee_abi = { - let instance_ty = instance.ty_env(*self.tcx, self.param_env); + let instance_ty = instance.ty_env(self.tcx, self.param_env); match instance_ty.kind { - ty::FnDef(..) => instance_ty.fn_sig(*self.tcx).abi(), + ty::FnDef(..) => instance_ty.fn_sig(self.tcx).abi(), ty::Closure(..) => Abi::RustCall, ty::Generator(..) => Abi::Rust, _ => bug!("unexpected callee ty: {:?}", instance_ty), diff --git a/src/librustc_mir/interpret/traits.rs b/src/librustc_mir/interpret/traits.rs index b9f9d37df7645..87493a8d383ec 100644 --- a/src/librustc_mir/interpret/traits.rs +++ b/src/librustc_mir/interpret/traits.rs @@ -2,7 +2,7 @@ use std::convert::TryFrom; use rustc_middle::mir::interpret::{InterpResult, Pointer, PointerArithmetic, Scalar}; use rustc_middle::ty::{self, Instance, Ty, TypeFoldable}; -use rustc_target::abi::{Align, HasDataLayout, LayoutOf, Size}; +use rustc_target::abi::{Align, LayoutOf, Size}; use super::{FnVal, InterpCx, Machine, MemoryKind}; @@ -36,10 +36,10 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { } let methods = if let Some(poly_trait_ref) = poly_trait_ref { - let trait_ref = poly_trait_ref.with_self_ty(*self.tcx, ty); + let trait_ref = poly_trait_ref.with_self_ty(self.tcx, ty); let trait_ref = self.tcx.erase_regions(&trait_ref); - self.tcx.vtable_methods(trait_ref) + self.tcx_at().vtable_methods(trait_ref) } else { &[] }; @@ -49,8 +49,9 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { let size = layout.size.bytes(); let align = layout.align.abi.bytes(); + let tcx = self.tcx; let ptr_size = self.pointer_size(); - let ptr_align = self.tcx.data_layout.pointer_align.abi; + let ptr_align = tcx.data_layout.pointer_align.abi; // ///////////////////////////////////////////////////////////////////////////////////////// // If you touch this code, be sure to also make the corresponding changes to // `get_vtable` in `rust_codegen_llvm/meth.rs`. @@ -60,33 +61,32 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { ptr_align, MemoryKind::Vtable, ); - let tcx = &*self.tcx; - let drop = Instance::resolve_drop_in_place(*tcx, ty); + let drop = Instance::resolve_drop_in_place(tcx, ty); let drop = self.memory.create_fn_alloc(FnVal::Instance(drop)); // No need to do any alignment checks on the memory accesses below, because we know the // allocation is correctly aligned as we created it above. Also we're only offsetting by // multiples of `ptr_align`, which means that it will stay aligned to `ptr_align`. let vtable_alloc = self.memory.get_raw_mut(vtable.alloc_id)?; - vtable_alloc.write_ptr_sized(tcx, vtable, drop.into())?; + vtable_alloc.write_ptr_sized(&tcx, vtable, drop.into())?; - let size_ptr = vtable.offset(ptr_size, tcx)?; - vtable_alloc.write_ptr_sized(tcx, size_ptr, Scalar::from_uint(size, ptr_size).into())?; - let align_ptr = vtable.offset(ptr_size * 2, tcx)?; - vtable_alloc.write_ptr_sized(tcx, align_ptr, Scalar::from_uint(align, ptr_size).into())?; + let size_ptr = vtable.offset(ptr_size, &tcx)?; + vtable_alloc.write_ptr_sized(&tcx, size_ptr, Scalar::from_uint(size, ptr_size).into())?; + let align_ptr = vtable.offset(ptr_size * 2, &tcx)?; + vtable_alloc.write_ptr_sized(&tcx, align_ptr, Scalar::from_uint(align, ptr_size).into())?; for (i, method) in methods.iter().enumerate() { if let Some((def_id, substs)) = *method { // resolve for vtable: insert shims where needed let instance = - ty::Instance::resolve_for_vtable(*tcx, self.param_env, def_id, substs) + ty::Instance::resolve_for_vtable(tcx, self.param_env, def_id, substs) .ok_or_else(|| err_inval!(TooGeneric))?; let fn_ptr = self.memory.create_fn_alloc(FnVal::Instance(instance)); // We cannot use `vtable_allic` as we are creating fn ptrs in this loop. - let method_ptr = vtable.offset(ptr_size * (3 + i as u64), tcx)?; + let method_ptr = vtable.offset(ptr_size * (3 + i as u64), &tcx)?; self.memory.get_raw_mut(vtable.alloc_id)?.write_ptr_sized( - tcx, + &tcx, method_ptr, fn_ptr.into(), )?; @@ -142,7 +142,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // to determine the type. let drop_instance = self.memory.get_fn(drop_fn)?.as_instance()?; trace!("Found drop fn: {:?}", drop_instance); - let fn_sig = drop_instance.ty_env(*self.tcx, self.param_env).fn_sig(*self.tcx); + let fn_sig = drop_instance.ty_env(self.tcx, self.param_env).fn_sig(self.tcx); let fn_sig = self.tcx.normalize_erasing_late_bound_regions(self.param_env, &fn_sig); // The drop function takes `*mut T` where `T` is the type being dropped, so get that. let args = fn_sig.inputs(); @@ -171,7 +171,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { alloc.read_ptr_sized(self, vtable.offset(pointer_size * 2, self)?)?.not_undef()?; let align = u64::try_from(self.force_bits(align, pointer_size)?).unwrap(); - if size >= self.tcx.data_layout().obj_size_bound() { + if size >= self.tcx.data_layout.obj_size_bound() { throw_ub_format!( "invalid vtable: \ size is bigger than largest supported object" diff --git a/src/librustc_mir/transform/const_prop.rs b/src/librustc_mir/transform/const_prop.rs index 0ff60cbd55d3c..133c05fc2f92b 100644 --- a/src/librustc_mir/transform/const_prop.rs +++ b/src/librustc_mir/transform/const_prop.rs @@ -313,7 +313,7 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> { let param_env = tcx.param_env(def_id).with_reveal_all(); let span = tcx.def_span(def_id); - let mut ecx = InterpCx::new(tcx.at(span), param_env, ConstPropMachine::new(), ()); + let mut ecx = InterpCx::new(tcx, span, param_env, ConstPropMachine::new(), ()); let can_const_prop = CanConstProp::check(body); let ret = ecx @@ -404,8 +404,7 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> { match self.ecx.eval_const_to_op(c.literal, None) { Ok(op) => Some(op), Err(error) => { - // Make sure errors point at the constant. - self.ecx.set_span(c.span); + let tcx = self.ecx.tcx.at(c.span); let err = error_to_const_error(&self.ecx, error); if let Some(lint_root) = self.lint_root(source_info) { let lint_only = match c.literal.val { @@ -419,16 +418,16 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> { // Out of backwards compatibility we cannot report hard errors in unused // generic functions using associated constants of the generic parameters. err.report_as_lint( - self.ecx.tcx, + tcx, "erroneous constant used", lint_root, Some(c.span), ); } else { - err.report_as_error(self.ecx.tcx, "erroneous constant used"); + err.report_as_error(tcx, "erroneous constant used"); } } else { - err.report_as_error(self.ecx.tcx, "erroneous constant used"); + err.report_as_error(tcx, "erroneous constant used"); } None } @@ -851,7 +850,6 @@ impl<'mir, 'tcx> MutVisitor<'tcx> for ConstPropagator<'mir, 'tcx> { fn visit_statement(&mut self, statement: &mut Statement<'tcx>, location: Location) { trace!("visit_statement: {:?}", statement); let source_info = statement.source_info; - self.ecx.set_span(source_info.span); self.source_info = Some(source_info); if let StatementKind::Assign(box (place, ref mut rval)) = statement.kind { let place_ty: Ty<'tcx> = place.ty(&self.local_decls, self.tcx).ty; @@ -864,7 +862,7 @@ impl<'mir, 'tcx> MutVisitor<'tcx> for ConstPropagator<'mir, 'tcx> { if let Some(value) = self.get_const(place) { if self.should_const_prop(value) { trace!("replacing {:?} with {:?}", rval, value); - self.replace_with_const(rval, value, statement.source_info); + self.replace_with_const(rval, value, source_info); if can_const_prop == ConstPropMode::FullConstProp || can_const_prop == ConstPropMode::OnlyInsideOwnBlock { @@ -927,7 +925,6 @@ impl<'mir, 'tcx> MutVisitor<'tcx> for ConstPropagator<'mir, 'tcx> { fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, location: Location) { let source_info = terminator.source_info; - self.ecx.set_span(source_info.span); self.source_info = Some(source_info); self.super_terminator(terminator, location); match &mut terminator.kind { From 0ac6fd0405c2f3defa9ad8ee3d4026469fbda018 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Mon, 1 Jun 2020 11:17:38 +0200 Subject: [PATCH 16/41] fix const_prop spans and re-bless tests --- src/librustc_mir/const_eval/error.rs | 5 ++-- src/librustc_mir/const_eval/eval_queries.rs | 4 +-- src/librustc_mir/interpret/cast.rs | 7 ++--- src/librustc_mir/interpret/eval_context.rs | 6 ++--- src/librustc_mir/interpret/place.rs | 27 ++++++++++++++----- src/librustc_mir/transform/const_prop.rs | 9 ++----- .../ui/consts/const-eval/infinite_loop.stderr | 4 +-- .../const_eval_limit_reached.stderr | 23 +++++++++------- .../recursive-zst-static.default.stderr | 4 +-- .../recursive-zst-static.unleash.stderr | 4 +-- .../consts/uninhabited-const-issue-61744.rs | 4 +-- .../uninhabited-const-issue-61744.stderr | 8 +++--- .../recursive-static-definition.stderr | 4 +-- .../ui/write-to-static-mut-in-static.stderr | 4 +-- 14 files changed, 61 insertions(+), 52 deletions(-) diff --git a/src/librustc_mir/const_eval/error.rs b/src/librustc_mir/const_eval/error.rs index 2aafafd8205d1..5deae94fe0c8e 100644 --- a/src/librustc_mir/const_eval/error.rs +++ b/src/librustc_mir/const_eval/error.rs @@ -2,7 +2,7 @@ use std::error::Error; use std::fmt; use rustc_middle::mir::AssertKind; -use rustc_span::Symbol; +use rustc_span::{Span, Symbol}; use super::InterpCx; use crate::interpret::{ConstEvalErr, InterpErrorInfo, Machine}; @@ -53,8 +53,9 @@ impl Error for ConstEvalErrKind {} pub fn error_to_const_error<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>>( ecx: &InterpCx<'mir, 'tcx, M>, error: InterpErrorInfo<'tcx>, + span: Option, ) -> ConstEvalErr<'tcx> { error.print_backtrace(); let stacktrace = ecx.generate_stacktrace(); - ConstEvalErr { error: error.kind, stacktrace, span: ecx.cur_span() } + ConstEvalErr { error: error.kind, stacktrace, span: span.unwrap_or_else(|| ecx.cur_span()) } } diff --git a/src/librustc_mir/const_eval/eval_queries.rs b/src/librustc_mir/const_eval/eval_queries.rs index 4101ea77c9080..28e77bb57cd0c 100644 --- a/src/librustc_mir/const_eval/eval_queries.rs +++ b/src/librustc_mir/const_eval/eval_queries.rs @@ -213,7 +213,7 @@ fn validate_and_turn_into_const<'tcx>( })(); val.map_err(|error| { - let err = error_to_const_error(&ecx, error); + let err = error_to_const_error(&ecx, error, None); err.struct_error(ecx.tcx_at(), "it is undefined behavior to use this value", |mut diag| { diag.note(note_on_undefined_behavior_error()); diag.emit(); @@ -312,7 +312,7 @@ pub fn const_eval_raw_provider<'tcx>( res.and_then(|body| eval_body_using_ecx(&mut ecx, cid, &body)) .map(|place| RawConst { alloc_id: place.ptr.assert_ptr().alloc_id, ty: place.layout.ty }) .map_err(|error| { - let err = error_to_const_error(&ecx, error); + let err = error_to_const_error(&ecx, error, None); // errors in statics are always emitted as fatal errors if is_static { // Ensure that if the above error was either `TooGeneric` or `Reported` diff --git a/src/librustc_mir/interpret/cast.rs b/src/librustc_mir/interpret/cast.rs index 287b43ac50f96..793a67d804cec 100644 --- a/src/librustc_mir/interpret/cast.rs +++ b/src/librustc_mir/interpret/cast.rs @@ -268,11 +268,8 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { (&ty::Array(_, length), &ty::Slice(_)) => { let ptr = self.read_immediate(src)?.to_scalar()?; // u64 cast is from usize to u64, which is always good - let val = Immediate::new_slice( - ptr, - length.eval_usize(self.tcx, self.param_env), - self, - ); + let val = + Immediate::new_slice(ptr, length.eval_usize(self.tcx, self.param_env), self); self.write_immediate(val, dest) } (&ty::Dynamic(..), &ty::Dynamic(..)) => { diff --git a/src/librustc_mir/interpret/eval_context.rs b/src/librustc_mir/interpret/eval_context.rs index 1715b6fede962..47e791854df48 100644 --- a/src/librustc_mir/interpret/eval_context.rs +++ b/src/librustc_mir/interpret/eval_context.rs @@ -314,8 +314,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { #[inline(always)] pub fn cur_span(&self) -> Span { - self - .stack() + self.stack() .last() .and_then(|f| f.current_source_info()) .map(|si| si.span) @@ -419,7 +418,8 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { let did = instance.def_id(); if let Some(did) = did.as_local() { if self.tcx_at().has_typeck_tables(did) { - if let Some(error_reported) = self.tcx_at().typeck_tables_of(did).tainted_by_errors { + if let Some(error_reported) = self.tcx_at().typeck_tables_of(did).tainted_by_errors + { throw_inval!(TypeckError(error_reported)) } } diff --git a/src/librustc_mir/interpret/place.rs b/src/librustc_mir/interpret/place.rs index 0b4e92574a066..2477100eb8ad8 100644 --- a/src/librustc_mir/interpret/place.rs +++ b/src/librustc_mir/interpret/place.rs @@ -404,7 +404,10 @@ where // to get some code to work that probably ought to work. field_layout.align.abi } - None => span_bug!(self.cur_span(), "cannot compute offset for extern type field at non-0 offset"), + None => span_bug!( + self.cur_span(), + "cannot compute offset for extern type field at non-0 offset" + ), }; (base.meta, offset.align_to(align)) } else { @@ -440,7 +443,11 @@ where assert!(!field_layout.is_unsized()); base.offset(offset, MemPlaceMeta::None, field_layout, self) } - _ => span_bug!(self.cur_span(), "`mplace_index` called on non-array type {:?}", base.layout.ty), + _ => span_bug!( + self.cur_span(), + "`mplace_index` called on non-array type {:?}", + base.layout.ty + ), } } @@ -484,7 +491,9 @@ where // (that have count 0 in their layout). let from_offset = match base.layout.fields { FieldsShape::Array { stride, .. } => stride * from, // `Size` multiplication is checked - _ => span_bug!(self.cur_span(), "unexpected layout of index access: {:#?}", base.layout), + _ => { + span_bug!(self.cur_span(), "unexpected layout of index access: {:#?}", base.layout) + } }; // Compute meta and new layout @@ -497,7 +506,9 @@ where let len = Scalar::from_machine_usize(inner_len, self); (MemPlaceMeta::Meta(len), base.layout.ty) } - _ => span_bug!(self.cur_span(), "cannot subslice non-array type: `{:?}`", base.layout.ty), + _ => { + span_bug!(self.cur_span(), "cannot subslice non-array type: `{:?}`", base.layout.ty) + } }; let layout = self.layout_of(ty)?; base.offset(from_offset, meta, layout, self) @@ -776,9 +787,11 @@ where Immediate::Scalar(scalar) => { match dest.layout.abi { Abi::Scalar(_) => {} // fine - _ => { - span_bug!(self.cur_span(), "write_immediate_to_mplace: invalid Scalar layout: {:#?}", dest.layout) - } + _ => span_bug!( + self.cur_span(), + "write_immediate_to_mplace: invalid Scalar layout: {:#?}", + dest.layout + ), } self.memory.get_raw_mut(ptr.alloc_id)?.write_scalar( &tcx, diff --git a/src/librustc_mir/transform/const_prop.rs b/src/librustc_mir/transform/const_prop.rs index 133c05fc2f92b..d50f052d405bc 100644 --- a/src/librustc_mir/transform/const_prop.rs +++ b/src/librustc_mir/transform/const_prop.rs @@ -405,7 +405,7 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> { Ok(op) => Some(op), Err(error) => { let tcx = self.ecx.tcx.at(c.span); - let err = error_to_const_error(&self.ecx, error); + let err = error_to_const_error(&self.ecx, error, Some(c.span)); if let Some(lint_root) = self.lint_root(source_info) { let lint_only = match c.literal.val { // Promoteds must lint and not error as the user didn't ask for them @@ -417,12 +417,7 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> { if lint_only { // Out of backwards compatibility we cannot report hard errors in unused // generic functions using associated constants of the generic parameters. - err.report_as_lint( - tcx, - "erroneous constant used", - lint_root, - Some(c.span), - ); + err.report_as_lint(tcx, "erroneous constant used", lint_root, Some(c.span)); } else { err.report_as_error(tcx, "erroneous constant used"); } diff --git a/src/test/ui/consts/const-eval/infinite_loop.stderr b/src/test/ui/consts/const-eval/infinite_loop.stderr index ebdb73c446791..3386e6e588e71 100644 --- a/src/test/ui/consts/const-eval/infinite_loop.stderr +++ b/src/test/ui/consts/const-eval/infinite_loop.stderr @@ -23,10 +23,10 @@ LL | n = if n % 2 == 0 { n/2 } else { 3*n + 1 }; = help: add `#![feature(const_if_match)]` to the crate attributes to enable error[E0080]: evaluation of constant value failed - --> $DIR/infinite_loop.rs:8:20 + --> $DIR/infinite_loop.rs:8:17 | LL | n = if n % 2 == 0 { n/2 } else { 3*n + 1 }; - | ^^^^^^^^^^ exceeded interpreter step limit (see `#[const_eval_limit]`) + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ exceeded interpreter step limit (see `#[const_eval_limit]`) error: aborting due to 3 previous errors diff --git a/src/test/ui/consts/const_limit/const_eval_limit_reached.stderr b/src/test/ui/consts/const_limit/const_eval_limit_reached.stderr index be522dd6d5d5a..8c2190b4e591f 100644 --- a/src/test/ui/consts/const_limit/const_eval_limit_reached.stderr +++ b/src/test/ui/consts/const_limit/const_eval_limit_reached.stderr @@ -1,15 +1,18 @@ error: any use of this value will cause an error - --> $DIR/const_eval_limit_reached.rs:8:11 + --> $DIR/const_eval_limit_reached.rs:8:5 | -LL | / const X: usize = { -LL | | let mut x = 0; -LL | | while x != 1000 { - | | ^^^^^^^^^ exceeded interpreter step limit (see `#[const_eval_limit]`) -LL | | -... | -LL | | x -LL | | }; - | |__- +LL | / const X: usize = { +LL | | let mut x = 0; +LL | | while x != 1000 { + | |_____^ +LL | || +LL | || x += 1; +LL | || } + | ||_____^ exceeded interpreter step limit (see `#[const_eval_limit]`) +LL | | +LL | | x +LL | | }; + | |__- | = note: `#[deny(const_err)]` on by default diff --git a/src/test/ui/consts/recursive-zst-static.default.stderr b/src/test/ui/consts/recursive-zst-static.default.stderr index d424b22f000bf..9042c6f6be191 100644 --- a/src/test/ui/consts/recursive-zst-static.default.stderr +++ b/src/test/ui/consts/recursive-zst-static.default.stderr @@ -1,8 +1,8 @@ error[E0391]: cycle detected when const-evaluating `FOO` - --> $DIR/recursive-zst-static.rs:10:18 + --> $DIR/recursive-zst-static.rs:10:1 | LL | static FOO: () = FOO; - | ^^^ + | ^^^^^^^^^^^^^^^^^^^^^ | note: ...which requires const-evaluating `FOO`... --> $DIR/recursive-zst-static.rs:10:1 diff --git a/src/test/ui/consts/recursive-zst-static.unleash.stderr b/src/test/ui/consts/recursive-zst-static.unleash.stderr index d424b22f000bf..9042c6f6be191 100644 --- a/src/test/ui/consts/recursive-zst-static.unleash.stderr +++ b/src/test/ui/consts/recursive-zst-static.unleash.stderr @@ -1,8 +1,8 @@ error[E0391]: cycle detected when const-evaluating `FOO` - --> $DIR/recursive-zst-static.rs:10:18 + --> $DIR/recursive-zst-static.rs:10:1 | LL | static FOO: () = FOO; - | ^^^ + | ^^^^^^^^^^^^^^^^^^^^^ | note: ...which requires const-evaluating `FOO`... --> $DIR/recursive-zst-static.rs:10:1 diff --git a/src/test/ui/consts/uninhabited-const-issue-61744.rs b/src/test/ui/consts/uninhabited-const-issue-61744.rs index 15436f9c1b2cf..55f42d84f9cb0 100644 --- a/src/test/ui/consts/uninhabited-const-issue-61744.rs +++ b/src/test/ui/consts/uninhabited-const-issue-61744.rs @@ -1,11 +1,11 @@ // build-fail pub const unsafe fn fake_type() -> T { - hint_unreachable() + hint_unreachable() //~ ERROR evaluation of constant value failed } pub const unsafe fn hint_unreachable() -> ! { - fake_type() //~ ERROR evaluation of constant value failed + fake_type() } trait Const { diff --git a/src/test/ui/consts/uninhabited-const-issue-61744.stderr b/src/test/ui/consts/uninhabited-const-issue-61744.stderr index ca232380897e3..fc908b2b2225f 100644 --- a/src/test/ui/consts/uninhabited-const-issue-61744.stderr +++ b/src/test/ui/consts/uninhabited-const-issue-61744.stderr @@ -1,9 +1,10 @@ error[E0080]: evaluation of constant value failed - --> $DIR/uninhabited-const-issue-61744.rs:8:5 + --> $DIR/uninhabited-const-issue-61744.rs:4:5 | LL | hint_unreachable() - | ------------------ + | ^^^^^^^^^^^^^^^^^^ | | + | reached the configured maximum number of stack frames | inside `fake_type::` at $DIR/uninhabited-const-issue-61744.rs:4:5 | inside `fake_type::` at $DIR/uninhabited-const-issue-61744.rs:4:5 | inside `fake_type::` at $DIR/uninhabited-const-issue-61744.rs:4:5 @@ -71,9 +72,8 @@ LL | hint_unreachable() | inside `fake_type::` at $DIR/uninhabited-const-issue-61744.rs:4:5 ... LL | fake_type() - | ^^^^^^^^^^^ + | ----------- | | - | reached the configured maximum number of stack frames | inside `hint_unreachable` at $DIR/uninhabited-const-issue-61744.rs:8:5 | inside `hint_unreachable` at $DIR/uninhabited-const-issue-61744.rs:8:5 | inside `hint_unreachable` at $DIR/uninhabited-const-issue-61744.rs:8:5 diff --git a/src/test/ui/recursion/recursive-static-definition.stderr b/src/test/ui/recursion/recursive-static-definition.stderr index b724c261a7c3c..093606e100cb3 100644 --- a/src/test/ui/recursion/recursive-static-definition.stderr +++ b/src/test/ui/recursion/recursive-static-definition.stderr @@ -1,8 +1,8 @@ error[E0391]: cycle detected when const-evaluating `FOO` - --> $DIR/recursive-static-definition.rs:1:23 + --> $DIR/recursive-static-definition.rs:1:1 | LL | pub static FOO: u32 = FOO; - | ^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ | note: ...which requires const-evaluating `FOO`... --> $DIR/recursive-static-definition.rs:1:1 diff --git a/src/test/ui/write-to-static-mut-in-static.stderr b/src/test/ui/write-to-static-mut-in-static.stderr index 6c2bd13d433ad..50dfce3448c34 100644 --- a/src/test/ui/write-to-static-mut-in-static.stderr +++ b/src/test/ui/write-to-static-mut-in-static.stderr @@ -5,10 +5,10 @@ LL | pub static mut B: () = unsafe { A = 1; }; | ^^^^^ modifying a static's initial value from another static's initializer error[E0391]: cycle detected when const-evaluating `C` - --> $DIR/write-to-static-mut-in-static.rs:5:34 + --> $DIR/write-to-static-mut-in-static.rs:5:1 | LL | pub static mut C: u32 = unsafe { C = 1; 0 }; - | ^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | note: ...which requires const-evaluating `C`... --> $DIR/write-to-static-mut-in-static.rs:5:1 From 32b01c78d0502c8a4cc36abbe8dc3c000436df98 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Thu, 11 Jun 2020 09:53:38 +0200 Subject: [PATCH 17/41] avoid computing cur_span all the time --- src/librustc_mir/const_eval/eval_queries.rs | 12 +++++++++--- src/librustc_mir/interpret/eval_context.rs | 8 +++++--- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/src/librustc_mir/const_eval/eval_queries.rs b/src/librustc_mir/const_eval/eval_queries.rs index 28e77bb57cd0c..310b09f71631e 100644 --- a/src/librustc_mir/const_eval/eval_queries.rs +++ b/src/librustc_mir/const_eval/eval_queries.rs @@ -317,7 +317,10 @@ pub fn const_eval_raw_provider<'tcx>( if is_static { // Ensure that if the above error was either `TooGeneric` or `Reported` // an error must be reported. - let v = err.report_as_error(ecx.tcx_at(), "could not evaluate static initializer"); + let v = err.report_as_error( + ecx.tcx.at(ecx.cur_span()), + "could not evaluate static initializer", + ); // If this is `Reveal:All`, then we need to make sure an error is reported but if // this is `Reveal::UserFacing`, then it's expected that we could get a @@ -373,13 +376,16 @@ pub fn const_eval_raw_provider<'tcx>( // anything else (array lengths, enum initializers, constant patterns) are // reported as hard errors } else { - err.report_as_error(ecx.tcx_at(), "evaluation of constant value failed") + err.report_as_error( + ecx.tcx.at(ecx.cur_span()), + "evaluation of constant value failed", + ) } } } } else { // use of broken constant from other crate - err.report_as_error(ecx.tcx_at(), "could not evaluate constant") + err.report_as_error(ecx.tcx.at(ecx.cur_span()), "could not evaluate constant") } }) } diff --git a/src/librustc_mir/interpret/eval_context.rs b/src/librustc_mir/interpret/eval_context.rs index 47e791854df48..866cdce7b77b6 100644 --- a/src/librustc_mir/interpret/eval_context.rs +++ b/src/librustc_mir/interpret/eval_context.rs @@ -323,7 +323,9 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { #[inline(always)] pub fn tcx_at(&self) -> TyCtxtAt<'tcx> { - self.tcx.at(self.cur_span()) + // Computing the current span has a non-trivial cost, and for cycle errors + // the "root span" is good enough. + self.tcx.at(self.root_span) } #[inline(always)] @@ -406,7 +408,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { #[inline] pub fn type_is_freeze(&self, ty: Ty<'tcx>) -> bool { - ty.is_freeze(self.tcx, self.param_env, self.cur_span()) + ty.is_freeze(self.tcx, self.param_env, self.root_span) } pub fn load_mir( @@ -889,7 +891,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // FIXME: We can hit delay_span_bug if this is an invalid const, interning finds // that problem, but we never run validation to show an error. Can we ensure // this does not happen? - let val = self.tcx_at().const_eval_raw(param_env.and(gid))?; + let val = self.tcx.at(self.cur_span()).const_eval_raw(param_env.and(gid))?; self.raw_const_to_mplace(val) } From c0aef6d816aa1f4a94e1057788e131ba82384d36 Mon Sep 17 00:00:00 2001 From: Eric Huss Date: Fri, 12 Jun 2020 14:17:42 -0700 Subject: [PATCH 18/41] Remove vestigial CI job msvc-aux. --- .github/workflows/ci.yml | 5 ----- src/bootstrap/builder.rs | 1 - src/bootstrap/mk/Makefile.in | 10 ++-------- src/bootstrap/test.rs | 7 ------- src/ci/azure-pipelines/auto.yml | 4 ---- src/ci/github-actions/ci.yml | 6 ------ 6 files changed, 2 insertions(+), 31 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c3c95226aebf6..72329a3572798 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -434,11 +434,6 @@ jobs: NO_DEBUG_ASSERTIONS: 1 NO_LLVM_ASSERTIONS: 1 os: windows-latest-xl - - name: x86_64-msvc-aux - env: - RUST_CHECK_TARGET: check-aux EXCLUDE_CARGO=1 - RUST_CONFIGURE_ARGS: "--build=x86_64-pc-windows-msvc" - os: windows-latest-xl - name: x86_64-msvc-cargo env: SCRIPT: python x.py test src/tools/cargotest src/tools/cargo diff --git a/src/bootstrap/builder.rs b/src/bootstrap/builder.rs index ffdd8485181f4..64e84da795a33 100644 --- a/src/bootstrap/builder.rs +++ b/src/bootstrap/builder.rs @@ -371,7 +371,6 @@ impl<'a> Builder<'a> { test::UiFullDeps, test::Rustdoc, test::Pretty, - test::RunPassValgrindPretty, test::Crate, test::CrateLibrustc, test::CrateRustdoc, diff --git a/src/bootstrap/mk/Makefile.in b/src/bootstrap/mk/Makefile.in index d8c97fc741478..12a1734e21c7e 100644 --- a/src/bootstrap/mk/Makefile.in +++ b/src/bootstrap/mk/Makefile.in @@ -6,12 +6,6 @@ Q := @ BOOTSTRAP_ARGS := endif -ifdef EXCLUDE_CARGO -AUX_ARGS := -else -AUX_ARGS := src/tools/cargo src/tools/cargotest -endif - BOOTSTRAP := $(CFG_PYTHON) $(CFG_SRC_DIR)src/bootstrap/bootstrap.py all: @@ -48,8 +42,8 @@ check: $(Q)$(BOOTSTRAP) test $(BOOTSTRAP_ARGS) check-aux: $(Q)$(BOOTSTRAP) test \ - src/test/run-pass-valgrind/pretty \ - $(AUX_ARGS) \ + src/tools/cargo \ + src/tools/cargotest \ $(BOOTSTRAP_ARGS) check-bootstrap: $(Q)$(CFG_PYTHON) $(CFG_SRC_DIR)src/bootstrap/bootstrap_test.py diff --git a/src/bootstrap/test.rs b/src/bootstrap/test.rs index 163132f563425..fb30ec0ffa49e 100644 --- a/src/bootstrap/test.rs +++ b/src/bootstrap/test.rs @@ -929,13 +929,6 @@ host_test!(UiFullDeps { path: "src/test/ui-fulldeps", mode: "ui", suite: "ui-ful host_test!(Rustdoc { path: "src/test/rustdoc", mode: "rustdoc", suite: "rustdoc" }); host_test!(Pretty { path: "src/test/pretty", mode: "pretty", suite: "pretty" }); -test!(RunPassValgrindPretty { - path: "src/test/run-pass-valgrind/pretty", - mode: "pretty", - suite: "run-pass-valgrind", - default: false, - host: true -}); default_test!(RunMake { path: "src/test/run-make", mode: "run-make", suite: "run-make" }); diff --git a/src/ci/azure-pipelines/auto.yml b/src/ci/azure-pipelines/auto.yml index f8fa7b727d179..3de27bc54c5c0 100644 --- a/src/ci/azure-pipelines/auto.yml +++ b/src/ci/azure-pipelines/auto.yml @@ -142,10 +142,6 @@ jobs: # FIXME(#59637) NO_DEBUG_ASSERTIONS: 1 NO_LLVM_ASSERTIONS: 1 - # MSVC aux tests - x86_64-msvc-aux: - RUST_CHECK_TARGET: check-aux EXCLUDE_CARGO=1 - INITIAL_RUST_CONFIGURE_ARGS: --build=x86_64-pc-windows-msvc x86_64-msvc-cargo: SCRIPT: python x.py test src/tools/cargotest src/tools/cargo INITIAL_RUST_CONFIGURE_ARGS: --build=x86_64-pc-windows-msvc --enable-lld diff --git a/src/ci/github-actions/ci.yml b/src/ci/github-actions/ci.yml index 92fec593a5410..3150ebd75a66e 100644 --- a/src/ci/github-actions/ci.yml +++ b/src/ci/github-actions/ci.yml @@ -496,12 +496,6 @@ jobs: NO_LLVM_ASSERTIONS: 1 <<: *job-windows-xl - - name: x86_64-msvc-aux - env: - RUST_CHECK_TARGET: check-aux EXCLUDE_CARGO=1 - RUST_CONFIGURE_ARGS: --build=x86_64-pc-windows-msvc - <<: *job-windows-xl - - name: x86_64-msvc-cargo env: SCRIPT: python x.py test src/tools/cargotest src/tools/cargo From 8b2092803e71180cd352f42041bf1725dc4ad1f6 Mon Sep 17 00:00:00 2001 From: Lzu Tao Date: Sat, 13 Jun 2020 01:27:14 +0000 Subject: [PATCH 19/41] Stabilize Option::zip --- src/libcore/lib.rs | 1 - src/libcore/option.rs | 8 +++++--- src/librustc_trait_selection/lib.rs | 1 - .../clippy_lints/src/checked_conversions.rs | 15 +++++---------- 4 files changed, 10 insertions(+), 15 deletions(-) diff --git a/src/libcore/lib.rs b/src/libcore/lib.rs index 7d21f9a9a66d0..fe05e914e6d44 100644 --- a/src/libcore/lib.rs +++ b/src/libcore/lib.rs @@ -145,7 +145,6 @@ #![feature(associated_type_bounds)] #![feature(const_type_id)] #![feature(const_caller_location)] -#![feature(option_zip)] #![feature(no_niche)] // rust-lang/rust#68303 #[prelude_import] diff --git a/src/libcore/option.rs b/src/libcore/option.rs index e8483875c97e5..5f0a12678ff43 100644 --- a/src/libcore/option.rs +++ b/src/libcore/option.rs @@ -926,7 +926,6 @@ impl Option { /// # Examples /// /// ``` - /// #![feature(option_zip)] /// let x = Some(1); /// let y = Some("hi"); /// let z = None::; @@ -934,9 +933,12 @@ impl Option { /// assert_eq!(x.zip(y), Some((1, "hi"))); /// assert_eq!(x.zip(z), None); /// ``` - #[unstable(feature = "option_zip", issue = "70086")] + #[stable(feature = "option_zip_option", since = "1.46.0")] pub fn zip(self, other: Option) -> Option<(T, U)> { - self.zip_with(other, |a, b| (a, b)) + match (self, other) { + (Some(a), Some(b)) => Some((a, b)), + _ => None, + } } /// Zips `self` and another `Option` with function `f`. diff --git a/src/librustc_trait_selection/lib.rs b/src/librustc_trait_selection/lib.rs index 044239b047a4e..ea886cd1f9e9b 100644 --- a/src/librustc_trait_selection/lib.rs +++ b/src/librustc_trait_selection/lib.rs @@ -16,7 +16,6 @@ #![feature(in_band_lifetimes)] #![feature(crate_visibility_modifier)] #![feature(or_patterns)] -#![feature(option_zip)] #![recursion_limit = "512"] // For rustdoc #[macro_use] diff --git a/src/tools/clippy/clippy_lints/src/checked_conversions.rs b/src/tools/clippy/clippy_lints/src/checked_conversions.rs index e845ef99c7cc0..88145015ba8bd 100644 --- a/src/tools/clippy/clippy_lints/src/checked_conversions.rs +++ b/src/tools/clippy/clippy_lints/src/checked_conversions.rs @@ -88,7 +88,7 @@ fn double_check<'a>(cx: &LateContext<'_, '_>, left: &'a Expr<'_>, right: &'a Exp let upper = check_upper_bound(l); let lower = check_lower_bound(r); - transpose(upper, lower).and_then(|(l, r)| l.combine(r, cx)) + upper.zip(lower).and_then(|(l, r)| l.combine(r, cx)) }; upper_lower(left, right).or_else(|| upper_lower(right, left)) @@ -131,7 +131,10 @@ impl<'a> Conversion<'a> { /// Checks if the to-type is the same (if there is a type constraint) fn has_compatible_to_type(&self, other: &Self) -> bool { - transpose(self.to_type.as_ref(), other.to_type.as_ref()).map_or(true, |(l, r)| l == r) + match (self.to_type, other.to_type) { + (Some(l), Some(r)) => l == r, + _ => true, + } } /// Try to construct a new conversion if the conversion type is valid @@ -322,14 +325,6 @@ fn int_ty_to_sym<'tcx>(path: &QPath<'_>) -> Option<&'tcx str> { } } -/// (Option, Option) -> Option<(T, U)> -fn transpose(lhs: Option, rhs: Option) -> Option<(T, U)> { - match (lhs, rhs) { - (Some(l), Some(r)) => Some((l, r)), - _ => None, - } -} - /// Will return the expressions as if they were expr1 <= expr2 fn normalize_le_ge<'a>(op: &BinOp, left: &'a Expr<'a>, right: &'a Expr<'a>) -> Option<(&'a Expr<'a>, &'a Expr<'a>)> { match op.node { From c45231ca555950cea450ba65f9d2d1962e3af6cd Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Fri, 12 Jun 2020 22:12:45 -0700 Subject: [PATCH 20/41] Revert heterogeneous SocketAddr PartialEq impls These lead to inference regressions (mostly in tests) in code that looks like: let socket = std::net::SocketAddrV4::new(std::net::Ipv4Addr::new(127, 0, 0, 1), 8080); assert_eq!(socket, "127.0.0.1:8080".parse().unwrap()); That compiles as of stable 1.44.0 but fails in beta with: error[E0284]: type annotations needed --> src/main.rs:3:41 | 3 | assert_eq!(socket, "127.0.0.1:8080".parse().unwrap()); | ^^^^^ cannot infer type for type parameter `F` declared on the associated function `parse` | = note: cannot satisfy `<_ as std::str::FromStr>::Err == _` help: consider specifying the type argument in the method call | 3 | assert_eq!(socket, "127.0.0.1:8080".parse::().unwrap()); | --- src/libstd/net/addr.rs | 40 ---------------------------------------- 1 file changed, 40 deletions(-) diff --git a/src/libstd/net/addr.rs b/src/libstd/net/addr.rs index b780340884e1f..7e3c3e8f3042e 100644 --- a/src/libstd/net/addr.rs +++ b/src/libstd/net/addr.rs @@ -694,42 +694,6 @@ impl PartialEq for SocketAddrV6 { && self.inner.sin6_scope_id == other.inner.sin6_scope_id } } -#[stable(feature = "socketaddr_ordering", since = "1.45.0")] -impl PartialEq for SocketAddr { - fn eq(&self, other: &SocketAddrV4) -> bool { - match self { - SocketAddr::V4(v4) => v4 == other, - SocketAddr::V6(_) => false, - } - } -} -#[stable(feature = "socketaddr_ordering", since = "1.45.0")] -impl PartialEq for SocketAddr { - fn eq(&self, other: &SocketAddrV6) -> bool { - match self { - SocketAddr::V4(_) => false, - SocketAddr::V6(v6) => v6 == other, - } - } -} -#[stable(feature = "socketaddr_ordering", since = "1.45.0")] -impl PartialEq for SocketAddrV4 { - fn eq(&self, other: &SocketAddr) -> bool { - match other { - SocketAddr::V4(v4) => self == v4, - SocketAddr::V6(_) => false, - } - } -} -#[stable(feature = "socketaddr_ordering", since = "1.45.0")] -impl PartialEq for SocketAddrV6 { - fn eq(&self, other: &SocketAddr) -> bool { - match other { - SocketAddr::V4(_) => false, - SocketAddr::V6(v6) => self == v6, - } - } -} #[stable(feature = "rust1", since = "1.0.0")] impl Eq for SocketAddrV4 {} #[stable(feature = "rust1", since = "1.0.0")] @@ -1242,12 +1206,8 @@ mod tests { // equality assert_eq!(v4_1, v4_1); assert_eq!(v6_1, v6_1); - assert_eq!(v4_1, SocketAddr::V4(v4_1)); - assert_eq!(v6_1, SocketAddr::V6(v6_1)); assert_eq!(SocketAddr::V4(v4_1), SocketAddr::V4(v4_1)); assert_eq!(SocketAddr::V6(v6_1), SocketAddr::V6(v6_1)); - assert!(v4_1 != SocketAddr::V6(v6_1)); - assert!(v6_1 != SocketAddr::V4(v4_1)); assert!(v4_1 != v4_2); assert!(v6_1 != v6_2); From 60496504ac635b3f805e8afed5eb6130b620f790 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Sat, 13 Jun 2020 13:47:37 +0200 Subject: [PATCH 21/41] avoid computing precise span for const_eval query --- src/librustc_mir/interpret/eval_context.rs | 2 +- src/test/ui/consts/const-size_of-cycle.stderr | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/librustc_mir/interpret/eval_context.rs b/src/librustc_mir/interpret/eval_context.rs index 866cdce7b77b6..4a0981a95a666 100644 --- a/src/librustc_mir/interpret/eval_context.rs +++ b/src/librustc_mir/interpret/eval_context.rs @@ -860,7 +860,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { } else { self.param_env }; - let val = self.tcx.const_eval_global_id(param_env, gid, Some(self.cur_span()))?; + let val = self.tcx.const_eval_global_id(param_env, gid, Some(self.root_span))?; // Even though `ecx.const_eval` is called from `eval_const_to_op` we can never have a // recursion deeper than one level, because the `tcx.const_eval` above is guaranteed to not diff --git a/src/test/ui/consts/const-size_of-cycle.stderr b/src/test/ui/consts/const-size_of-cycle.stderr index 5fd7fe4480e30..0aa30665f5907 100644 --- a/src/test/ui/consts/const-size_of-cycle.stderr +++ b/src/test/ui/consts/const-size_of-cycle.stderr @@ -17,8 +17,8 @@ LL | bytes: [u8; std::mem::size_of::()] note: ...which requires const-evaluating `std::mem::size_of`... --> $SRC_DIR/libcore/mem/mod.rs:LL:COL | -LL | intrinsics::size_of::() - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | pub const fn size_of() -> usize { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ note: ...which requires const-evaluating + checking `std::intrinsics::size_of`... --> $SRC_DIR/libcore/intrinsics.rs:LL:COL | From c6512fd4e959d1c19ee7b428a78696a53ab28bc6 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Sat, 13 Jun 2020 13:55:01 +0200 Subject: [PATCH 22/41] run const_eval_raw with root_span --- src/librustc_mir/interpret/eval_context.rs | 2 +- src/test/ui/infinite/infinite-recursion-const-fn.stderr | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/librustc_mir/interpret/eval_context.rs b/src/librustc_mir/interpret/eval_context.rs index 4a0981a95a666..5d344e9b372a0 100644 --- a/src/librustc_mir/interpret/eval_context.rs +++ b/src/librustc_mir/interpret/eval_context.rs @@ -891,7 +891,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // FIXME: We can hit delay_span_bug if this is an invalid const, interning finds // that problem, but we never run validation to show an error. Can we ensure // this does not happen? - let val = self.tcx.at(self.cur_span()).const_eval_raw(param_env.and(gid))?; + let val = self.tcx_at().const_eval_raw(param_env.and(gid))?; self.raw_const_to_mplace(val) } diff --git a/src/test/ui/infinite/infinite-recursion-const-fn.stderr b/src/test/ui/infinite/infinite-recursion-const-fn.stderr index 6bd5e035f5743..de0c579f63089 100644 --- a/src/test/ui/infinite/infinite-recursion-const-fn.stderr +++ b/src/test/ui/infinite/infinite-recursion-const-fn.stderr @@ -1,14 +1,14 @@ error[E0391]: cycle detected when const-evaluating `a` - --> $DIR/infinite-recursion-const-fn.rs:3:25 + --> $DIR/infinite-recursion-const-fn.rs:3:1 | LL | const fn a() -> usize { b() } - | ^^^ + | ^^^^^^^^^^^^^^^^^^^^^ | note: ...which requires const-evaluating `b`... - --> $DIR/infinite-recursion-const-fn.rs:4:25 + --> $DIR/infinite-recursion-const-fn.rs:4:1 | LL | const fn b() -> usize { a() } - | ^^^ + | ^^^^^^^^^^^^^^^^^^^^^ = note: ...which again requires const-evaluating `a`, completing the cycle note: cycle used when const-evaluating `ARR::{{constant}}#0` --> $DIR/infinite-recursion-const-fn.rs:5:18 From f747073fc1751afd2cfd4395283a4822b618f2da Mon Sep 17 00:00:00 2001 From: Poliorcetics Date: Sat, 13 Jun 2020 18:41:01 +0200 Subject: [PATCH 23/41] Apply suggestions from code review Co-authored-by: David Tolnay --- src/libstd/sync/mutex.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/libstd/sync/mutex.rs b/src/libstd/sync/mutex.rs index b3ef521d6ecb0..6625d4659dcac 100644 --- a/src/libstd/sync/mutex.rs +++ b/src/libstd/sync/mutex.rs @@ -108,8 +108,8 @@ use crate::sys_common::poison::{self, LockResult, TryLockError, TryLockResult}; /// *guard += 1; /// ``` /// -/// It is sometimes a good idea (or even necessary) to manually drop the mutex -/// to unlock it as soon as possible. If you need the resource until the end of +/// It is sometimes necessary to manually drop the mutex +/// guard to unlock it as soon as possible. If you need the resource until the end of /// the scope, this is not needed. /// /// ``` @@ -140,16 +140,16 @@ use crate::sys_common::poison::{self, LockResult, TryLockError, TryLockResult}; /// // This is the result of some important and long-ish work. /// let result = data.iter().fold(0, |acc, x| acc + x * 2); /// data.push(result); -/// // We drop the `data` explicitely because it's not necessary anymore +/// // We drop the `data` explicitly because it's not necessary anymore /// // and the thread still has work to do. This allow other threads to /// // start working on the data immediately, without waiting /// // for the rest of the unrelated work to be done here. /// // /// // It's even more important here than in the threads because we `.join` the -/// // threads after that. If we had not dropped the lock, a thread could be +/// // threads after that. If we had not dropped the mutex guard, a thread could be /// // waiting forever for it, causing a deadlock. /// drop(data); -/// // Here the lock is not assigned to a variable and so, even if the scope +/// // Here the mutex guard is not assigned to a variable and so, even if the scope /// // does not end after this line, the mutex is still released: /// // there is no deadlock. /// *res_mutex.lock().unwrap() += result; From 34b3ff06e101f60cb69268ee83c93c177b63c322 Mon Sep 17 00:00:00 2001 From: Poliorcetics Date: Sat, 13 Jun 2020 18:43:37 +0200 Subject: [PATCH 24/41] Clarify the scope-related explanation Based on the review made by dtolnay. --- src/libstd/sync/mutex.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/libstd/sync/mutex.rs b/src/libstd/sync/mutex.rs index 6625d4659dcac..37c8125b0984a 100644 --- a/src/libstd/sync/mutex.rs +++ b/src/libstd/sync/mutex.rs @@ -108,9 +108,8 @@ use crate::sys_common::poison::{self, LockResult, TryLockError, TryLockResult}; /// *guard += 1; /// ``` /// -/// It is sometimes necessary to manually drop the mutex -/// guard to unlock it as soon as possible. If you need the resource until the end of -/// the scope, this is not needed. +/// It is sometimes necessary to manually drop the mutex guard +/// to unlock it sooner than the end of the enclosing scope. /// /// ``` /// use std::sync::{Arc, Mutex}; From c010e711ca5ec02012afb83c0d99aec9d26a9eea Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Sat, 13 Jun 2020 10:11:02 -0700 Subject: [PATCH 25/41] Rewrap comments in Mutex example --- src/libstd/sync/mutex.rs | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/src/libstd/sync/mutex.rs b/src/libstd/sync/mutex.rs index 37c8125b0984a..8478457eabfc2 100644 --- a/src/libstd/sync/mutex.rs +++ b/src/libstd/sync/mutex.rs @@ -108,8 +108,8 @@ use crate::sys_common::poison::{self, LockResult, TryLockError, TryLockResult}; /// *guard += 1; /// ``` /// -/// It is sometimes necessary to manually drop the mutex guard -/// to unlock it sooner than the end of the enclosing scope. +/// It is sometimes necessary to manually drop the mutex guard to unlock it +/// sooner than the end of the enclosing scope. /// /// ``` /// use std::sync::{Arc, Mutex}; @@ -139,18 +139,18 @@ use crate::sys_common::poison::{self, LockResult, TryLockError, TryLockResult}; /// // This is the result of some important and long-ish work. /// let result = data.iter().fold(0, |acc, x| acc + x * 2); /// data.push(result); -/// // We drop the `data` explicitly because it's not necessary anymore -/// // and the thread still has work to do. This allow other threads to -/// // start working on the data immediately, without waiting -/// // for the rest of the unrelated work to be done here. +/// // We drop the `data` explicitly because it's not necessary anymore and the +/// // thread still has work to do. This allow other threads to start working on +/// // the data immediately, without waiting for the rest of the unrelated work +/// // to be done here. /// // /// // It's even more important here than in the threads because we `.join` the -/// // threads after that. If we had not dropped the mutex guard, a thread could be -/// // waiting forever for it, causing a deadlock. +/// // threads after that. If we had not dropped the mutex guard, a thread could +/// // be waiting forever for it, causing a deadlock. /// drop(data); -/// // Here the mutex guard is not assigned to a variable and so, even if the scope -/// // does not end after this line, the mutex is still released: -/// // there is no deadlock. +/// // Here the mutex guard is not assigned to a variable and so, even if the +/// // scope does not end after this line, the mutex is still released: there is +/// // no deadlock. /// *res_mutex.lock().unwrap() += result; /// /// threads.into_iter().for_each(|thread| { From 204c236ad5b632294d8794e729326be8053ab2aa Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Sat, 13 Jun 2020 10:21:11 -0700 Subject: [PATCH 26/41] Add test for comparing SocketAddr with inferred right-hand side --- src/libstd/net/addr.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/libstd/net/addr.rs b/src/libstd/net/addr.rs index 7e3c3e8f3042e..b8fa1a7f744d3 100644 --- a/src/libstd/net/addr.rs +++ b/src/libstd/net/addr.rs @@ -1228,5 +1228,10 @@ mod tests { assert!(v6_1 < v6_3); assert!(v4_3 > v4_1); assert!(v6_3 > v6_1); + + // compare with an inferred right-hand side + assert_eq!(v4_1, "224.120.45.1:23456".parse().unwrap()); + assert_eq!(v6_1, "[2001:db8:f00::1002]:23456".parse().unwrap()); + assert_eq!(SocketAddr::V4(v4_1), "224.120.45.1:23456".parse().unwrap()); } } From 71d41d9e9f020c9eb527a47e16e4041dfcdaef84 Mon Sep 17 00:00:00 2001 From: Stefan Lankes Date: Sat, 13 Jun 2020 20:51:00 +0200 Subject: [PATCH 27/41] add TcpListener support for HermitCore Add basic support of TcpListerner for HermitCore. In addition, revise TcpStream to support peer_addr. --- src/libstd/sys/hermit/net.rs | 157 +++++++++++++++++++++++++---------- 1 file changed, 111 insertions(+), 46 deletions(-) diff --git a/src/libstd/sys/hermit/net.rs b/src/libstd/sys/hermit/net.rs index 5b5379c8b0581..2fef8d381ca1a 100644 --- a/src/libstd/sys/hermit/net.rs +++ b/src/libstd/sys/hermit/net.rs @@ -1,10 +1,13 @@ use crate::convert::TryFrom; use crate::fmt; use crate::io::{self, ErrorKind, IoSlice, IoSliceMut}; -use crate::net::{Ipv4Addr, Ipv6Addr, Shutdown, SocketAddr}; +use crate::net::{IpAddr, Ipv4Addr, Ipv6Addr, Shutdown, SocketAddr}; use crate::str; +use crate::sync::Arc; use crate::sys::hermit::abi; +use crate::sys::hermit::abi::IpAddress::{Ipv4, Ipv6}; use crate::sys::{unsupported, Void}; +use crate::sys_common::AsInner; use crate::time::Duration; /// Checks whether the HermitCore's socket interface has been started already, and @@ -17,14 +20,37 @@ pub fn init() -> io::Result<()> { Ok(()) } -pub struct TcpStream(abi::Handle); +#[derive(Debug, Clone)] +pub struct Socket(abi::Handle); + +impl Socket { + fn new(handle: abi::Handle) -> Socket { + Socket(handle) + } +} + +impl AsInner for Socket { + fn as_inner(&self) -> &abi::Handle { + &self.0 + } +} + +impl Drop for Socket { + fn drop(&mut self) { + let _ = abi::tcpstream::close(self.0); + } +} + + +#[derive(Clone)] +pub struct TcpStream(Arc); impl TcpStream { pub fn connect(addr: io::Result<&SocketAddr>) -> io::Result { let addr = addr?; match abi::tcpstream::connect(addr.ip().to_string().as_bytes(), addr.port(), None) { - Ok(handle) => Ok(TcpStream(handle)), + Ok(handle) => Ok(TcpStream(Arc::new(Socket(handle)))), _ => { Err(io::Error::new(ErrorKind::Other, "Unable to initiate a connection on a socket")) } @@ -37,7 +63,7 @@ impl TcpStream { saddr.port(), Some(duration.as_millis() as u64), ) { - Ok(handle) => Ok(TcpStream(handle)), + Ok(handle) => Ok(TcpStream(Arc::new(Socket(handle)))), _ => { Err(io::Error::new(ErrorKind::Other, "Unable to initiate a connection on a socket")) } @@ -45,31 +71,34 @@ impl TcpStream { } pub fn set_read_timeout(&self, duration: Option) -> io::Result<()> { - abi::tcpstream::set_read_timeout(self.0, duration.map(|d| d.as_millis() as u64)) + abi::tcpstream::set_read_timeout(*self.0.as_inner(), duration.map(|d| d.as_millis() as u64)) .map_err(|_| io::Error::new(ErrorKind::Other, "Unable to set timeout value")) } pub fn set_write_timeout(&self, duration: Option) -> io::Result<()> { - abi::tcpstream::set_write_timeout(self.0, duration.map(|d| d.as_millis() as u64)) - .map_err(|_| io::Error::new(ErrorKind::Other, "Unable to set timeout value")) + abi::tcpstream::set_write_timeout( + *self.0.as_inner(), + duration.map(|d| d.as_millis() as u64), + ) + .map_err(|_| io::Error::new(ErrorKind::Other, "Unable to set timeout value")) } pub fn read_timeout(&self) -> io::Result> { - let duration = abi::tcpstream::get_read_timeout(self.0) + let duration = abi::tcpstream::get_read_timeout(*self.0.as_inner()) .map_err(|_| io::Error::new(ErrorKind::Other, "Unable to determine timeout value"))?; Ok(duration.map(|d| Duration::from_millis(d))) } pub fn write_timeout(&self) -> io::Result> { - let duration = abi::tcpstream::get_write_timeout(self.0) + let duration = abi::tcpstream::get_write_timeout(*self.0.as_inner()) .map_err(|_| io::Error::new(ErrorKind::Other, "Unable to determine timeout value"))?; Ok(duration.map(|d| Duration::from_millis(d))) } pub fn peek(&self, buf: &mut [u8]) -> io::Result { - abi::tcpstream::peek(self.0, buf) + abi::tcpstream::peek(*self.0.as_inner(), buf) .map_err(|_| io::Error::new(ErrorKind::Other, "set_nodelay failed")) } @@ -81,18 +110,11 @@ impl TcpStream { let mut size: usize = 0; for i in ioslice.iter_mut() { - let mut pos: usize = 0; - - while pos < i.len() { - let ret = abi::tcpstream::read(self.0, &mut i[pos..]) - .map_err(|_| io::Error::new(ErrorKind::Other, "Unable to read on socket"))?; - - if ret == 0 { - return Ok(size); - } else { - size += ret; - pos += ret; - } + let ret = abi::tcpstream::read(*self.0.as_inner(), &mut i[0..]) + .map_err(|_| io::Error::new(ErrorKind::Other, "Unable to read on socket"))?; + + if ret != 0 { + size += ret; } } @@ -112,7 +134,7 @@ impl TcpStream { let mut size: usize = 0; for i in ioslice.iter() { - size += abi::tcpstream::write(self.0, i) + size += abi::tcpstream::write(*self.0.as_inner(), i) .map_err(|_| io::Error::new(ErrorKind::Other, "Unable to write on socket"))?; } @@ -125,7 +147,32 @@ impl TcpStream { } pub fn peer_addr(&self) -> io::Result { - Err(io::Error::new(ErrorKind::Other, "peer_addr isn't supported")) + let (ipaddr, port) = abi::tcpstream::peer_addr(*self.0.as_inner()) + .map_err(|_| io::Error::new(ErrorKind::Other, "peer_addr failed"))?; + + let saddr = match ipaddr { + Ipv4(ref addr) => SocketAddr::new( + IpAddr::V4(Ipv4Addr::new(addr.0[0], addr.0[1], addr.0[2], addr.0[3])), + port, + ), + Ipv6(ref addr) => SocketAddr::new( + IpAddr::V6(Ipv6Addr::new( + ((addr.0[0] as u16) << 8) | addr.0[1] as u16, + ((addr.0[2] as u16) << 8) | addr.0[3] as u16, + ((addr.0[4] as u16) << 8) | addr.0[5] as u16, + ((addr.0[6] as u16) << 8) | addr.0[7] as u16, + ((addr.0[8] as u16) << 8) | addr.0[9] as u16, + ((addr.0[10] as u16) << 8) | addr.0[11] as u16, + ((addr.0[12] as u16) << 8) | addr.0[13] as u16, + ((addr.0[14] as u16) << 8) | addr.0[15] as u16)), + port, + ), + _ => { + return Err(io::Error::new(ErrorKind::Other, "peer_addr failed")); + }, + }; + + Ok(saddr) } pub fn socket_addr(&self) -> io::Result { @@ -133,34 +180,31 @@ impl TcpStream { } pub fn shutdown(&self, how: Shutdown) -> io::Result<()> { - abi::tcpstream::shutdown(self.0, how as i32) + abi::tcpstream::shutdown(*self.0.as_inner(), how as i32) .map_err(|_| io::Error::new(ErrorKind::Other, "unable to shutdown socket")) } pub fn duplicate(&self) -> io::Result { - let handle = abi::tcpstream::duplicate(self.0) - .map_err(|_| io::Error::new(ErrorKind::Other, "unable to duplicate stream"))?; - - Ok(TcpStream(handle)) + Ok(self.clone()) } pub fn set_nodelay(&self, mode: bool) -> io::Result<()> { - abi::tcpstream::set_nodelay(self.0, mode) + abi::tcpstream::set_nodelay(*self.0.as_inner(), mode) .map_err(|_| io::Error::new(ErrorKind::Other, "set_nodelay failed")) } pub fn nodelay(&self) -> io::Result { - abi::tcpstream::nodelay(self.0) + abi::tcpstream::nodelay(*self.0.as_inner()) .map_err(|_| io::Error::new(ErrorKind::Other, "nodelay failed")) } pub fn set_ttl(&self, tll: u32) -> io::Result<()> { - abi::tcpstream::set_tll(self.0, tll) + abi::tcpstream::set_tll(*self.0.as_inner(), tll) .map_err(|_| io::Error::new(ErrorKind::Other, "unable to set TTL")) } pub fn ttl(&self) -> io::Result { - abi::tcpstream::get_tll(self.0) + abi::tcpstream::get_tll(*self.0.as_inner()) .map_err(|_| io::Error::new(ErrorKind::Other, "unable to get TTL")) } @@ -169,40 +213,61 @@ impl TcpStream { } pub fn set_nonblocking(&self, mode: bool) -> io::Result<()> { - abi::tcpstream::set_nonblocking(self.0, mode) + abi::tcpstream::set_nonblocking(*self.0.as_inner(), mode) .map_err(|_| io::Error::new(ErrorKind::Other, "unable to set blocking mode")) } } -impl Drop for TcpStream { - fn drop(&mut self) { - let _ = abi::tcpstream::close(self.0); - } -} - impl fmt::Debug for TcpStream { fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result { Ok(()) } } -pub struct TcpListener(abi::Handle); +#[derive(Clone)] +pub struct TcpListener(SocketAddr); impl TcpListener { - pub fn bind(_: io::Result<&SocketAddr>) -> io::Result { - Err(io::Error::new(ErrorKind::Other, "not supported")) + pub fn bind(addr: io::Result<&SocketAddr>) -> io::Result { + let addr = addr?; + + Ok(TcpListener(*addr)) } pub fn socket_addr(&self) -> io::Result { - Err(io::Error::new(ErrorKind::Other, "not supported")) + Ok(self.0) } pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> { - Err(io::Error::new(ErrorKind::Other, "not supported")) + let (handle, ipaddr, port) = abi::tcplistener::accept(self.0.port()) + .map_err(|_| io::Error::new(ErrorKind::Other, "accept failed"))?; + let saddr = match ipaddr { + Ipv4(ref addr) => SocketAddr::new( + IpAddr::V4(Ipv4Addr::new(addr.0[0], addr.0[1], addr.0[2], addr.0[3])), + port, + ), + Ipv6(ref addr) => SocketAddr::new( + IpAddr::V6(Ipv6Addr::new( + ((addr.0[0] as u16) << 8) | addr.0[1] as u16, + ((addr.0[2] as u16) << 8) | addr.0[3] as u16, + ((addr.0[4] as u16) << 8) | addr.0[5] as u16, + ((addr.0[6] as u16) << 8) | addr.0[7] as u16, + ((addr.0[8] as u16) << 8) | addr.0[9] as u16, + ((addr.0[10] as u16) << 8) | addr.0[11] as u16, + ((addr.0[12] as u16) << 8) | addr.0[13] as u16, + ((addr.0[14] as u16) << 8) | addr.0[15] as u16)), + port, + ), + _ => { + return Err(io::Error::new(ErrorKind::Other, "accept failed")); + }, + }; + + Ok((TcpStream(Arc::new(Socket(handle))), saddr)) } pub fn duplicate(&self) -> io::Result { - Err(io::Error::new(ErrorKind::Other, "not supported")) + Ok(self.clone()) } pub fn set_ttl(&self, _: u32) -> io::Result<()> { From c99116afe37d5a1dde65ed8a2e107892be81b20a Mon Sep 17 00:00:00 2001 From: Stefan Lankes Date: Sun, 14 Jun 2020 00:38:31 +0200 Subject: [PATCH 28/41] remove unused function --- src/libstd/sys/hermit/net.rs | 6 ------ 1 file changed, 6 deletions(-) diff --git a/src/libstd/sys/hermit/net.rs b/src/libstd/sys/hermit/net.rs index 2fef8d381ca1a..70c010e6232f8 100644 --- a/src/libstd/sys/hermit/net.rs +++ b/src/libstd/sys/hermit/net.rs @@ -23,12 +23,6 @@ pub fn init() -> io::Result<()> { #[derive(Debug, Clone)] pub struct Socket(abi::Handle); -impl Socket { - fn new(handle: abi::Handle) -> Socket { - Socket(handle) - } -} - impl AsInner for Socket { fn as_inner(&self) -> &abi::Handle { &self.0 From fd86a847206dd2333c23c768b8c0564e15a05c1c Mon Sep 17 00:00:00 2001 From: Stefan Lankes Date: Sun, 14 Jun 2020 00:39:14 +0200 Subject: [PATCH 29/41] use latest interface to HermitCore --- Cargo.lock | 4 ++-- src/libstd/Cargo.toml | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index bbbcf797f7535..009767934d447 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1434,9 +1434,9 @@ dependencies = [ [[package]] name = "hermit-abi" -version = "0.1.13" +version = "0.1.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91780f809e750b0a89f5544be56617ff6b1227ee485bcb06ebe10cdf89bd3b71" +checksum = "b9586eedd4ce6b3c498bc3b4dd92fc9f11166aa908a914071953768066c67909" dependencies = [ "compiler_builtins", "libc", diff --git a/src/libstd/Cargo.toml b/src/libstd/Cargo.toml index 6af1cbb34b6c4..83029a8642097 100644 --- a/src/libstd/Cargo.toml +++ b/src/libstd/Cargo.toml @@ -41,7 +41,7 @@ dlmalloc = { version = "0.1", features = ['rustc-dep-of-std'] } fortanix-sgx-abi = { version = "0.3.2", features = ['rustc-dep-of-std'] } [target.'cfg(all(any(target_arch = "x86_64", target_arch = "aarch64"), target_os = "hermit"))'.dependencies] -hermit-abi = { version = "0.1.13", features = ['rustc-dep-of-std'] } +hermit-abi = { version = "0.1.14", features = ['rustc-dep-of-std'] } [target.wasm32-wasi.dependencies] wasi = { version = "0.9.0", features = ['rustc-dep-of-std'], default-features = false } From 2210abea71270867fe2c69782f282c654e106fac Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Sun, 14 Jun 2020 15:02:51 +0200 Subject: [PATCH 30/41] keep root_span and tcx together --- src/librustc_mir/const_eval/eval_queries.rs | 4 +- src/librustc_mir/interpret/cast.rs | 8 ++-- src/librustc_mir/interpret/eval_context.rs | 47 +++++++------------ src/librustc_mir/interpret/intern.rs | 19 ++++---- src/librustc_mir/interpret/intrinsics.rs | 4 +- .../interpret/intrinsics/caller_location.rs | 4 +- src/librustc_mir/interpret/operand.rs | 16 +++---- src/librustc_mir/interpret/place.rs | 14 +++--- src/librustc_mir/interpret/terminator.rs | 8 ++-- src/librustc_mir/interpret/traits.rs | 8 ++-- 10 files changed, 60 insertions(+), 72 deletions(-) diff --git a/src/librustc_mir/const_eval/eval_queries.rs b/src/librustc_mir/const_eval/eval_queries.rs index 310b09f71631e..d62300b3f5541 100644 --- a/src/librustc_mir/const_eval/eval_queries.rs +++ b/src/librustc_mir/const_eval/eval_queries.rs @@ -27,7 +27,7 @@ fn eval_body_using_ecx<'mir, 'tcx>( body: &'mir mir::Body<'tcx>, ) -> InterpResult<'tcx, MPlaceTy<'tcx>> { debug!("eval_body_using_ecx: {:?}, {:?}", cid, ecx.param_env); - let tcx = ecx.tcx; + let tcx = *ecx.tcx; let layout = ecx.layout_of(body.return_ty().subst(tcx, cid.instance.substs))?; assert!(!layout.is_unsized()); let ret = ecx.allocate(layout, MemoryKind::Stack); @@ -214,7 +214,7 @@ fn validate_and_turn_into_const<'tcx>( val.map_err(|error| { let err = error_to_const_error(&ecx, error, None); - err.struct_error(ecx.tcx_at(), "it is undefined behavior to use this value", |mut diag| { + err.struct_error(ecx.tcx, "it is undefined behavior to use this value", |mut diag| { diag.note(note_on_undefined_behavior_error()); diag.emit(); }) diff --git a/src/librustc_mir/interpret/cast.rs b/src/librustc_mir/interpret/cast.rs index 793a67d804cec..cfe856abe36dd 100644 --- a/src/librustc_mir/interpret/cast.rs +++ b/src/librustc_mir/interpret/cast.rs @@ -56,7 +56,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { } let instance = ty::Instance::resolve_for_fn_ptr( - self.tcx, + *self.tcx, self.param_env, def_id, substs, @@ -91,7 +91,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { } let instance = ty::Instance::resolve_closure( - self.tcx, + *self.tcx, def_id, substs, ty::ClosureKind::FnOnce, @@ -140,7 +140,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // Handle cast from a univariant (ZST) enum. match src.layout.variants { Variants::Single { index } => { - if let Some(discr) = src.layout.ty.discriminant_for_variant(self.tcx, index) { + if let Some(discr) = src.layout.ty.discriminant_for_variant(*self.tcx, index) { assert!(src.layout.is_zst()); let discr_layout = self.layout_of(discr.ty)?; return Ok(self.cast_from_scalar(discr.val, discr_layout, cast_ty).into()); @@ -269,7 +269,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { let ptr = self.read_immediate(src)?.to_scalar()?; // u64 cast is from usize to u64, which is always good let val = - Immediate::new_slice(ptr, length.eval_usize(self.tcx, self.param_env), self); + Immediate::new_slice(ptr, length.eval_usize(*self.tcx, self.param_env), self); self.write_immediate(val, dest) } (&ty::Dynamic(..), &ty::Dynamic(..)) => { diff --git a/src/librustc_mir/interpret/eval_context.rs b/src/librustc_mir/interpret/eval_context.rs index 5d344e9b372a0..519dfd5b54e34 100644 --- a/src/librustc_mir/interpret/eval_context.rs +++ b/src/librustc_mir/interpret/eval_context.rs @@ -33,11 +33,9 @@ pub struct InterpCx<'mir, 'tcx, M: Machine<'mir, 'tcx>> { pub machine: M, /// The results of the type checker, from rustc. - pub tcx: TyCtxt<'tcx>, - - /// The span of the "root" of the evaluation, i.e., the const + /// The span in this is the "root" of the evaluation, i.e., the const /// we are evaluating (if this is CTFE). - pub(super) root_span: Span, + pub tcx: TyCtxtAt<'tcx>, /// Bounds in scope for polymorphic evaluations. pub(crate) param_env: ty::ParamEnv<'tcx>, @@ -200,7 +198,7 @@ where { #[inline] fn tcx(&self) -> TyCtxt<'tcx> { - self.tcx + *self.tcx } } @@ -219,7 +217,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> LayoutOf for InterpCx<'mir, 'tcx, #[inline] fn layout_of(&self, ty: Ty<'tcx>) -> Self::TyAndLayout { - self.tcx_at() + self.tcx .layout_of(self.param_env.and(ty)) .map_err(|layout| err_inval!(Layout(layout)).into()) } @@ -304,8 +302,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { ) -> Self { InterpCx { machine, - tcx, - root_span, + tcx: tcx.at(root_span), param_env, memory: Memory::new(tcx, memory_extra), vtables: FxHashMap::default(), @@ -318,14 +315,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { .last() .and_then(|f| f.current_source_info()) .map(|si| si.span) - .unwrap_or(self.root_span) - } - - #[inline(always)] - pub fn tcx_at(&self) -> TyCtxtAt<'tcx> { - // Computing the current span has a non-trivial cost, and for cycle errors - // the "root span" is good enough. - self.tcx.at(self.root_span) + .unwrap_or(self.tcx.span) } #[inline(always)] @@ -403,12 +393,12 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { #[inline] pub fn type_is_sized(&self, ty: Ty<'tcx>) -> bool { - ty.is_sized(self.tcx_at(), self.param_env) + ty.is_sized(self.tcx, self.param_env) } #[inline] pub fn type_is_freeze(&self, ty: Ty<'tcx>) -> bool { - ty.is_freeze(self.tcx, self.param_env, self.root_span) + ty.is_freeze(*self.tcx, self.param_env, self.tcx.span) } pub fn load_mir( @@ -419,21 +409,20 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // do not continue if typeck errors occurred (can only occur in local crate) let did = instance.def_id(); if let Some(did) = did.as_local() { - if self.tcx_at().has_typeck_tables(did) { - if let Some(error_reported) = self.tcx_at().typeck_tables_of(did).tainted_by_errors - { + if self.tcx.has_typeck_tables(did) { + if let Some(error_reported) = self.tcx.typeck_tables_of(did).tainted_by_errors { throw_inval!(TypeckError(error_reported)) } } } trace!("load mir(instance={:?}, promoted={:?})", instance, promoted); if let Some(promoted) = promoted { - return Ok(&self.tcx_at().promoted_mir(did)[promoted]); + return Ok(&self.tcx.promoted_mir(did)[promoted]); } match instance { ty::InstanceDef::Item(def_id) => { - if self.tcx_at().is_mir_available(did) { - Ok(self.tcx_at().optimized_mir(did)) + if self.tcx.is_mir_available(did) { + Ok(self.tcx.optimized_mir(did)) } else { throw_unsup!(NoMirFor(def_id)) } @@ -474,7 +463,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { trace!("resolve: {:?}, {:#?}", def_id, substs); trace!("param_env: {:#?}", self.param_env); trace!("substs: {:#?}", substs); - match ty::Instance::resolve(self.tcx, self.param_env, def_id, substs) { + match ty::Instance::resolve(*self.tcx, self.param_env, def_id, substs) { Ok(Some(instance)) => Ok(instance), Ok(None) => throw_inval!(TooGeneric), @@ -493,7 +482,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // have to support that case (mostly by skipping all caching). match frame.locals.get(local).and_then(|state| state.layout.get()) { None => { - let layout = from_known_layout(self.tcx_at(), layout, || { + let layout = from_known_layout(self.tcx, layout, || { let local_ty = frame.body.local_decls[local].ty; let local_ty = self.subst_from_frame_and_normalize_erasing_regions(frame, local_ty); @@ -645,7 +634,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { 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_at().def_kind(instance.def_id()) { + 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 @@ -860,7 +849,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { } else { self.param_env }; - let val = self.tcx.const_eval_global_id(param_env, gid, Some(self.root_span))?; + let val = self.tcx.const_eval_global_id(param_env, gid, Some(self.tcx.span))?; // Even though `ecx.const_eval` is called from `eval_const_to_op` we can never have a // recursion deeper than one level, because the `tcx.const_eval` above is guaranteed to not @@ -891,7 +880,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // FIXME: We can hit delay_span_bug if this is an invalid const, interning finds // that problem, but we never run validation to show an error. Can we ensure // this does not happen? - let val = self.tcx_at().const_eval_raw(param_env.and(gid))?; + let val = self.tcx.const_eval_raw(param_env.and(gid))?; self.raw_const_to_mplace(val) } diff --git a/src/librustc_mir/interpret/intern.rs b/src/librustc_mir/interpret/intern.rs index 284a1d5ea61ef..3c724c79b4082 100644 --- a/src/librustc_mir/interpret/intern.rs +++ b/src/librustc_mir/interpret/intern.rs @@ -93,7 +93,7 @@ fn intern_shallow<'rt, 'mir, 'tcx, M: CompileTimeMachine<'mir, 'tcx>>( // in the value the dangling reference lies. // The `delay_span_bug` ensures that we don't forget such a check in validation. if tcx.get_global_alloc(alloc_id).is_none() { - tcx.sess.delay_span_bug(ecx.root_span, "tried to intern dangling pointer"); + tcx.sess.delay_span_bug(ecx.tcx.span, "tried to intern dangling pointer"); } // treat dangling pointers like other statics // just to stop trying to recurse into them @@ -111,7 +111,7 @@ fn intern_shallow<'rt, 'mir, 'tcx, M: CompileTimeMachine<'mir, 'tcx>>( if let InternMode::Static(mutability) = mode { // For this, we need to take into account `UnsafeCell`. When `ty` is `None`, we assume // no interior mutability. - let frozen = ty.map_or(true, |ty| ty.is_freeze(ecx.tcx, ecx.param_env, ecx.root_span)); + let frozen = ty.map_or(true, |ty| ty.is_freeze(*ecx.tcx, ecx.param_env, ecx.tcx.span)); // For statics, allocation mutability is the combination of the place mutability and // the type mutability. // The entire allocation needs to be mutable if it contains an `UnsafeCell` anywhere. @@ -174,7 +174,7 @@ impl<'rt, 'mir, 'tcx: 'mir, M: CompileTimeMachine<'mir, 'tcx>> ValueVisitor<'mir // they caused. It also helps us to find cases where const-checking // failed to prevent an `UnsafeCell` (but as `ignore_interior_mut_in_const` // shows that part is not airtight). - mutable_memory_in_const(self.ecx.tcx_at(), "`UnsafeCell`"); + mutable_memory_in_const(self.ecx.tcx, "`UnsafeCell`"); } // We are crossing over an `UnsafeCell`, we can mutate again. This means that // References we encounter inside here are interned as pointing to mutable @@ -192,7 +192,7 @@ impl<'rt, 'mir, 'tcx: 'mir, M: CompileTimeMachine<'mir, 'tcx>> ValueVisitor<'mir fn visit_value(&mut self, mplace: MPlaceTy<'tcx>) -> InterpResult<'tcx> { // Handle Reference types, as these are the only relocations supported by const eval. // Raw pointers (and boxes) are handled by the `leftover_relocations` logic. - let tcx = self.ecx.tcx.at(self.ecx.root_span); + let tcx = self.ecx.tcx; let ty = mplace.layout.ty; if let ty::Ref(_, referenced_ty, ref_mutability) = ty.kind { let value = self.ecx.read_immediate(mplace.into())?; @@ -253,8 +253,7 @@ impl<'rt, 'mir, 'tcx: 'mir, M: CompileTimeMachine<'mir, 'tcx>> ValueVisitor<'mir // caused (by somehow getting a mutable reference in a `const`). if ref_mutability == Mutability::Mut { match referenced_ty.kind { - ty::Array(_, n) - if n.eval_usize(self.ecx.tcx, self.ecx.param_env) == 0 => {} + ty::Array(_, n) if n.eval_usize(*tcx, self.ecx.param_env) == 0 => {} ty::Slice(_) if mplace.meta.unwrap_meta().to_machine_usize(self.ecx)? == 0 => {} @@ -358,7 +357,7 @@ pub fn intern_const_alloc_recursive>( Ok(()) => {} Err(error) => { ecx.tcx.sess.delay_span_bug( - ecx.root_span, + ecx.tcx.span, "error during interning should later cause validation failure", ); // Some errors shouldn't come up because creating them causes @@ -407,7 +406,7 @@ pub fn intern_const_alloc_recursive>( // such as `const CONST_RAW: *const Vec = &Vec::new() as *const _;`. ecx.tcx .sess - .span_err(ecx.root_span, "untyped pointers are not allowed in constant"); + .span_err(ecx.tcx.span, "untyped pointers are not allowed in constant"); // For better errors later, mark the allocation as immutable. alloc.mutability = Mutability::Not; } @@ -422,11 +421,11 @@ pub fn intern_const_alloc_recursive>( } else if ecx.memory.dead_alloc_map.contains_key(&alloc_id) { // Codegen does not like dangling pointers, and generally `tcx` assumes that // all allocations referenced anywhere actually exist. So, make sure we error here. - ecx.tcx.sess.span_err(ecx.root_span, "encountered dangling pointer in final constant"); + ecx.tcx.sess.span_err(ecx.tcx.span, "encountered dangling pointer in final constant"); } else if ecx.tcx.get_global_alloc(alloc_id).is_none() { // We have hit an `AllocId` that is neither in local or global memory and isn't // marked as dangling by local memory. That should be impossible. - span_bug!(ecx.root_span, "encountered unknown alloc id {:?}", alloc_id); + span_bug!(ecx.tcx.span, "encountered unknown alloc id {:?}", alloc_id); } } } diff --git a/src/librustc_mir/interpret/intrinsics.rs b/src/librustc_mir/interpret/intrinsics.rs index c62fd316dc584..47e5b8b4fcec4 100644 --- a/src/librustc_mir/interpret/intrinsics.rs +++ b/src/librustc_mir/interpret/intrinsics.rs @@ -347,7 +347,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { let index = u64::from(self.read_scalar(args[1])?.to_u32()?); let elem = args[2]; let input = args[0]; - let (len, e_ty) = input.layout.ty.simd_size_and_type(self.tcx); + let (len, e_ty) = input.layout.ty.simd_size_and_type(*self.tcx); assert!( index < len, "Index `{}` must be in bounds of vector type `{}`: `[0, {})`", @@ -374,7 +374,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { } sym::simd_extract => { let index = u64::from(self.read_scalar(args[1])?.to_u32()?); - let (len, e_ty) = args[0].layout.ty.simd_size_and_type(self.tcx); + let (len, e_ty) = args[0].layout.ty.simd_size_and_type(*self.tcx); assert!( index < len, "index `{}` is out-of-bounds of vector type `{}` with length `{}`", diff --git a/src/librustc_mir/interpret/intrinsics/caller_location.rs b/src/librustc_mir/interpret/intrinsics/caller_location.rs index 193d38dc5523e..ddeed92f85124 100644 --- a/src/librustc_mir/interpret/intrinsics/caller_location.rs +++ b/src/librustc_mir/interpret/intrinsics/caller_location.rs @@ -25,7 +25,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { "find_closest_untracked_caller_location: checking frame {:?}", frame.instance ); - !frame.instance.def.requires_caller_location(self.tcx) + !frame.instance.def.requires_caller_location(*self.tcx) }) // Assert that there is always such a frame. .unwrap(); @@ -58,7 +58,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { let loc_ty = self .tcx .type_of(self.tcx.require_lang_item(PanicLocationLangItem, None)) - .subst(self.tcx, self.tcx.mk_substs([self.tcx.lifetimes.re_erased.into()].iter())); + .subst(*self.tcx, self.tcx.mk_substs([self.tcx.lifetimes.re_erased.into()].iter())); let loc_layout = self.layout_of(loc_ty).unwrap(); let location = self.allocate(loc_layout, MemoryKind::CallerLocation); diff --git a/src/librustc_mir/interpret/operand.rs b/src/librustc_mir/interpret/operand.rs index c9250098fedba..38f5988d0eb3f 100644 --- a/src/librustc_mir/interpret/operand.rs +++ b/src/librustc_mir/interpret/operand.rs @@ -471,9 +471,9 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { trace!("eval_place_to_op: got {:?}", *op); // Sanity-check the type we ended up with. debug_assert!(mir_assign_valid_types( - self.tcx, + *self.tcx, self.layout_of(self.subst_from_current_frame_and_normalize_erasing_regions( - place.ty(&self.frame().body.local_decls, self.tcx).ty + place.ty(&self.frame().body.local_decls, *self.tcx).ty ))?, op.layout, )); @@ -554,7 +554,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // documentation). let val_val = M::adjust_global_const(self, val_val)?; // Other cases need layout. - let layout = from_known_layout(self.tcx_at(), layout, || self.layout_of(val.ty))?; + let layout = from_known_layout(self.tcx, layout, || self.layout_of(val.ty))?; let op = match val_val { ConstValue::ByRef { alloc, offset } => { let id = self.tcx.create_memory_alloc(alloc); @@ -589,7 +589,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { trace!("read_discriminant_value {:#?}", op.layout); // Get type and layout of the discriminant. - let discr_layout = self.layout_of(op.layout.ty.discriminant_ty(self.tcx))?; + let discr_layout = self.layout_of(op.layout.ty.discriminant_ty(*self.tcx))?; trace!("discriminant type: {:?}", discr_layout.ty); // We use "discriminant" to refer to the value associated with a particular enum variant. @@ -601,7 +601,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // rather confusing. let (tag_scalar_layout, tag_kind, tag_index) = match op.layout.variants { Variants::Single { index } => { - let discr = match op.layout.ty.discriminant_for_variant(self.tcx, index) { + let discr = match op.layout.ty.discriminant_for_variant(*self.tcx, index) { Some(discr) => { // This type actually has discriminants. assert_eq!(discr.ty, discr_layout.ty); @@ -630,7 +630,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // may be a pointer. This is `tag_val.layout`; we just use it for sanity checks. // Get layout for tag. - let tag_layout = self.layout_of(tag_scalar_layout.value.to_int_ty(self.tcx))?; + let tag_layout = self.layout_of(tag_scalar_layout.value.to_int_ty(*self.tcx))?; // Read tag and sanity-check `tag_layout`. let tag_val = self.read_immediate(self.operand_field(op, tag_index)?)?; @@ -651,12 +651,12 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // Convert discriminant to variant index, and catch invalid discriminants. let index = match op.layout.ty.kind { ty::Adt(adt, _) => { - adt.discriminants(self.tcx).find(|(_, var)| var.val == discr_bits) + adt.discriminants(*self.tcx).find(|(_, var)| var.val == discr_bits) } ty::Generator(def_id, substs, _) => { let substs = substs.as_generator(); substs - .discriminants(def_id, self.tcx) + .discriminants(def_id, *self.tcx) .find(|(_, var)| var.val == discr_bits) } _ => bug!("tagged layout for non-adt non-generator"), diff --git a/src/librustc_mir/interpret/place.rs b/src/librustc_mir/interpret/place.rs index 2477100eb8ad8..24b191e9b535a 100644 --- a/src/librustc_mir/interpret/place.rs +++ b/src/librustc_mir/interpret/place.rs @@ -651,9 +651,9 @@ where self.dump_place(place_ty.place); // Sanity-check the type we ended up with. debug_assert!(mir_assign_valid_types( - self.tcx, + *self.tcx, self.layout_of(self.subst_from_current_frame_and_normalize_erasing_regions( - place.ty(&self.frame().body.local_decls, self.tcx).ty + place.ty(&self.frame().body.local_decls, *self.tcx).ty ))?, place_ty.layout, )); @@ -779,7 +779,7 @@ where None => return Ok(()), // zero-sized access }; - let tcx = self.tcx; + let tcx = *self.tcx; // FIXME: We should check that there are dest.layout.size many bytes available in // memory. The code below is not sufficient, with enough padding it might not // cover all the bytes! @@ -855,7 +855,7 @@ where ) -> InterpResult<'tcx> { // We do NOT compare the types for equality, because well-typed code can // actually "transmute" `&mut T` to `&T` in an assignment without a cast. - if !mir_assign_valid_types(self.tcx, src.layout, dest.layout) { + if !mir_assign_valid_types(*self.tcx, src.layout, dest.layout) { span_bug!( self.cur_span(), "type mismatch when copying!\nsrc: {:?},\ndest: {:?}", @@ -912,7 +912,7 @@ where src: OpTy<'tcx, M::PointerTag>, dest: PlaceTy<'tcx, M::PointerTag>, ) -> InterpResult<'tcx> { - if mir_assign_valid_types(self.tcx, src.layout, dest.layout) { + if mir_assign_valid_types(*self.tcx, src.layout, dest.layout) { // Fast path: Just use normal `copy_op` return self.copy_op(src, dest); } @@ -1070,7 +1070,7 @@ where // `TyAndLayout::for_variant()` call earlier already checks the variant is valid. let discr_val = - dest.layout.ty.discriminant_for_variant(self.tcx, variant_index).unwrap().val; + dest.layout.ty.discriminant_for_variant(*self.tcx, variant_index).unwrap().val; // raw discriminants for enums are isize or bigger during // their computation, but the in-memory tag is the smallest possible @@ -1099,7 +1099,7 @@ where .expect("overflow computing relative variant idx"); // We need to use machine arithmetic when taking into account `niche_start`: // discr_val = variant_index_relative + niche_start_val - let discr_layout = self.layout_of(discr_layout.value.to_int_ty(self.tcx))?; + let discr_layout = self.layout_of(discr_layout.value.to_int_ty(*self.tcx))?; let niche_start_val = ImmTy::from_uint(niche_start, discr_layout); let variant_index_relative_val = ImmTy::from_uint(variant_index_relative, discr_layout); diff --git a/src/librustc_mir/interpret/terminator.rs b/src/librustc_mir/interpret/terminator.rs index 9a4dd0a5204f9..cd7621ea9752b 100644 --- a/src/librustc_mir/interpret/terminator.rs +++ b/src/librustc_mir/interpret/terminator.rs @@ -69,7 +69,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { (fn_val, caller_abi) } ty::FnDef(def_id, substs) => { - let sig = func.layout.ty.fn_sig(self.tcx); + let sig = func.layout.ty.fn_sig(*self.tcx); (FnVal::Instance(self.resolve(def_id, substs)?), sig.abi()) } _ => span_bug!( @@ -96,7 +96,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { let ty = place.layout.ty; trace!("TerminatorKind::drop: {:?}, type {}", location, ty); - let instance = Instance::resolve_drop_in_place(self.tcx, ty); + let instance = Instance::resolve_drop_in_place(*self.tcx, ty); self.drop_in_place(place, instance, target, unwind)?; } @@ -227,9 +227,9 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // ABI check { let callee_abi = { - let instance_ty = instance.ty_env(self.tcx, self.param_env); + let instance_ty = instance.ty_env(*self.tcx, self.param_env); match instance_ty.kind { - ty::FnDef(..) => instance_ty.fn_sig(self.tcx).abi(), + ty::FnDef(..) => instance_ty.fn_sig(*self.tcx).abi(), ty::Closure(..) => Abi::RustCall, ty::Generator(..) => Abi::Rust, _ => bug!("unexpected callee ty: {:?}", instance_ty), diff --git a/src/librustc_mir/interpret/traits.rs b/src/librustc_mir/interpret/traits.rs index 87493a8d383ec..a1d124bb7602e 100644 --- a/src/librustc_mir/interpret/traits.rs +++ b/src/librustc_mir/interpret/traits.rs @@ -36,10 +36,10 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { } let methods = if let Some(poly_trait_ref) = poly_trait_ref { - let trait_ref = poly_trait_ref.with_self_ty(self.tcx, ty); + let trait_ref = poly_trait_ref.with_self_ty(*self.tcx, ty); let trait_ref = self.tcx.erase_regions(&trait_ref); - self.tcx_at().vtable_methods(trait_ref) + self.tcx.vtable_methods(trait_ref) } else { &[] }; @@ -49,7 +49,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { let size = layout.size.bytes(); let align = layout.align.abi.bytes(); - let tcx = self.tcx; + let tcx = *self.tcx; let ptr_size = self.pointer_size(); let ptr_align = tcx.data_layout.pointer_align.abi; // ///////////////////////////////////////////////////////////////////////////////////////// @@ -142,7 +142,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // to determine the type. let drop_instance = self.memory.get_fn(drop_fn)?.as_instance()?; trace!("Found drop fn: {:?}", drop_instance); - let fn_sig = drop_instance.ty_env(self.tcx, self.param_env).fn_sig(self.tcx); + let fn_sig = drop_instance.ty_env(*self.tcx, self.param_env).fn_sig(*self.tcx); let fn_sig = self.tcx.normalize_erasing_late_bound_regions(self.param_env, &fn_sig); // The drop function takes `*mut T` where `T` is the type being dropped, so get that. let args = fn_sig.inputs(); From 5f4eb27a0dc5d17e4a74f1a2d71a8f5a30916e3a Mon Sep 17 00:00:00 2001 From: Alexis Bourget Date: Sun, 14 Jun 2020 19:21:44 +0200 Subject: [PATCH 31/41] Removing the TryFrom impl --- src/libstd/ffi/c_str.rs | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/src/libstd/ffi/c_str.rs b/src/libstd/ffi/c_str.rs index 298f6c33457d8..6f7dc091897f4 100644 --- a/src/libstd/ffi/c_str.rs +++ b/src/libstd/ffi/c_str.rs @@ -1,7 +1,6 @@ use crate::ascii; use crate::borrow::{Borrow, Cow}; use crate::cmp::Ordering; -use crate::convert::TryFrom; use crate::error::Error; use crate::fmt::{self, Write}; use crate::io; @@ -854,19 +853,6 @@ impl From> for CString { } } -#[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")] -impl TryFrom> for CString { - type Error = FromBytesWithNulError; - - /// See the document about [`from_vec_with_nul`] for more - /// informations about the behaviour of this method. - /// - /// [`from_vec_with_nul`]: CString::from_vec_with_nul - fn try_from(value: Vec) -> Result { - Self::from_vec_with_nul(value) - } -} - #[stable(feature = "more_box_slice_clone", since = "1.29.0")] impl Clone for Box { #[inline] From 685f06612dc8842b734181e380eae0f9b1a9483f Mon Sep 17 00:00:00 2001 From: Alexis Bourget Date: Sun, 14 Jun 2020 23:21:40 +0200 Subject: [PATCH 32/41] Add a new error type for the new method --- src/libstd/ffi/c_str.rs | 96 +++++++++++++++++++++++++++++++++++++++++ src/libstd/ffi/mod.rs | 2 + 2 files changed, 98 insertions(+) diff --git a/src/libstd/ffi/c_str.rs b/src/libstd/ffi/c_str.rs index 6f7dc091897f4..956100bca6a55 100644 --- a/src/libstd/ffi/c_str.rs +++ b/src/libstd/ffi/c_str.rs @@ -260,6 +260,32 @@ pub struct FromBytesWithNulError { kind: FromBytesWithNulErrorKind, } +/// An error indicating that a nul byte was not in the expected position. +/// +/// The vector used to create a [`CString`] must have one and only one nul byte, +/// positioned at the end. +/// +/// This error is created by the [`from_vec_with_nul`] method on [`CString`]. +/// See its documentation for more. +/// +/// [`CString`]: struct.CString.html +/// [`from_vec_with_nul`]: struct.CString.html#method.from_vec_with_nul +/// +/// # Examples +/// +/// ``` +/// #![feature(cstring_from_vec_with_nul)] +/// use std::ffi::{CString, FromVecWithNulError}; +/// +/// let _: FromVecWithNulError = CString::from_vec_with_nul(b"f\0oo".to_vec()).unwrap_err(); +/// ``` +#[derive(Clone, PartialEq, Eq, Debug)] +#[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")] +pub struct FromVecWithNulError { + error_kind: FromBytesWithNulErrorKind, + bytes: Vec, +} + #[derive(Clone, PartialEq, Eq, Debug)] enum FromBytesWithNulErrorKind { InteriorNul(usize), @@ -275,6 +301,59 @@ impl FromBytesWithNulError { } } +#[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")] +impl FromVecWithNulError { + /// Returns a slice of [`u8`]s bytes that were attempted to convert to a [`CString`]. + /// + /// # Examples + /// + /// Basic usage: + /// + /// ``` + /// #![feature(cstring_from_vec_with_nul)] + /// use std::ffi::CString; + /// + /// // Some invalid bytes in a vector + /// let bytes = b"f\0oo".to_vec(); + /// + /// let value = CString::from_vec_with_nul(bytes.clone()); + /// + /// assert_eq!(&bytes[..], value.unwrap_err().as_bytes()); + /// ``` + /// + /// [`CString`]: struct.CString.html + pub fn as_bytes(&self) -> &[u8] { + &self.bytes[..] + } + + /// Returns the bytes that were attempted to convert to a [`CString`]. + /// + /// This method is carefully constructed to avoid allocation. It will + /// consume the error, moving out the bytes, so that a copy of the bytes + /// does not need to be made. + /// + /// # Examples + /// + /// Basic usage: + /// + /// ``` + /// #![feature(cstring_from_vec_with_nul)] + /// use std::ffi::CString; + /// + /// // Some invalid bytes in a vector + /// let bytes = b"f\0oo".to_vec(); + /// + /// let value = CString::from_vec_with_nul(bytes.clone()); + /// + /// assert_eq!(bytes, value.unwrap_err().into_bytes()); + /// ``` + /// + /// [`CString`]: struct.CString.html + pub fn into_bytes(self) -> Vec { + self.bytes + } +} + /// An error indicating invalid UTF-8 when converting a [`CString`] into a [`String`]. /// /// `CString` is just a wrapper over a buffer of bytes with a nul @@ -1039,6 +1118,23 @@ impl fmt::Display for FromBytesWithNulError { } } +#[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")] +impl Error for FromVecWithNulError {} + +#[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")] +impl fmt::Display for FromVecWithNulError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self.error_kind { + FromBytesWithNulErrorKind::InteriorNul(pos) => { + write!(f, "data provided contains an interior nul byte at pos {}", pos) + } + FromBytesWithNulErrorKind::NotNulTerminated => { + write!(f, "data provided is not nul terminated") + } + } + } +} + impl IntoStringError { /// Consumes this error, returning original [`CString`] which generated the /// error. diff --git a/src/libstd/ffi/mod.rs b/src/libstd/ffi/mod.rs index 5aca7b7476a52..f442d7fde1a5e 100644 --- a/src/libstd/ffi/mod.rs +++ b/src/libstd/ffi/mod.rs @@ -157,6 +157,8 @@ #[stable(feature = "cstr_from_bytes", since = "1.10.0")] pub use self::c_str::FromBytesWithNulError; +#[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")] +pub use self::c_str::FromVecWithNulError; #[stable(feature = "rust1", since = "1.0.0")] pub use self::c_str::{CStr, CString, IntoStringError, NulError}; From 47cc5cca7e64a434fa15680b7dcc621ca6f1abbf Mon Sep 17 00:00:00 2001 From: Alexis Bourget Date: Sun, 14 Jun 2020 23:22:36 +0200 Subject: [PATCH 33/41] Update to use the new error type and correctly compile the doc tests --- src/libstd/ffi/c_str.rs | 37 +++++++++++++++++++++---------------- 1 file changed, 21 insertions(+), 16 deletions(-) diff --git a/src/libstd/ffi/c_str.rs b/src/libstd/ffi/c_str.rs index 956100bca6a55..3537a9f8656a2 100644 --- a/src/libstd/ffi/c_str.rs +++ b/src/libstd/ffi/c_str.rs @@ -234,18 +234,14 @@ pub struct NulError(usize, Vec); /// An error indicating that a nul byte was not in the expected position. /// -/// The slice used to create a [`CStr`] or the vector used to create a -/// [`CString`] must have one and only one nul byte, positioned at the end. +/// The slice used to create a [`CStr`] must have one and only one nul byte, +/// positioned at the end. /// -/// This error is created by the -/// [`from_bytes_with_nul`][`CStr::from_bytes_with_nul`] method on -/// [`CStr`] or the [`from_vec_with_nul`][`CString::from_vec_with_nul`] method -/// on [`CString`]. See their documentation for more. +/// This error is created by the [`from_bytes_with_nul`] method on [`CStr`]. +/// See its documentation for more. /// /// [`CStr`]: struct.CStr.html -/// [`CStr::from_bytes_with_nul`]: struct.CStr.html#method.from_bytes_with_nul -/// [`CString`]: struct.CString.html -/// [`CString::from_vec_with_nul`]: struct.CString.html#method.from_vec_with_nul +/// [`from_bytes_with_nul`]: struct.CStr.html#method.from_bytes_with_nul /// /// # Examples /// @@ -726,6 +722,7 @@ impl CString { /// # Example /// /// ``` + /// #![feature(cstring_from_vec_with_nul)] /// use std::ffi::CString; /// assert_eq!( /// unsafe { CString::from_vec_with_nul_unchecked(b"abc\0".to_vec()) }, @@ -753,27 +750,29 @@ impl CString { /// called without the ending nul byte. /// /// ``` + /// #![feature(cstring_from_vec_with_nul)] /// use std::ffi::CString; /// assert_eq!( /// CString::from_vec_with_nul(b"abc\0".to_vec()) /// .expect("CString::from_vec_with_nul failed"), - /// CString::new(b"abc".to_vec()) + /// CString::new(b"abc".to_vec()).expect("CString::new failed") /// ); /// ``` /// /// A incorrectly formatted vector will produce an error. /// /// ``` - /// use std::ffi::{CString, FromBytesWithNulError}; + /// #![feature(cstring_from_vec_with_nul)] + /// use std::ffi::{CString, FromVecWithNulError}; /// // Interior nul byte - /// let _: FromBytesWithNulError = CString::from_vec_with_nul(b"a\0bc".to_vec()).unwrap_err(); + /// let _: FromVecWithNulError = CString::from_vec_with_nul(b"a\0bc".to_vec()).unwrap_err(); /// // No nul byte - /// let _: FromBytesWithNulError = CString::from_vec_with_nul(b"abc".to_vec()).unwrap_err(); + /// let _: FromVecWithNulError = CString::from_vec_with_nul(b"abc".to_vec()).unwrap_err(); /// ``` /// /// [`new`]: #method.new #[unstable(feature = "cstring_from_vec_with_nul", issue = "73179")] - pub fn from_vec_with_nul(v: Vec) -> Result { + pub fn from_vec_with_nul(v: Vec) -> Result { let nul_pos = memchr::memchr(0, &v); match nul_pos { Some(nul_pos) if nul_pos + 1 == v.len() => { @@ -781,8 +780,14 @@ impl CString { // of the vec. Ok(unsafe { Self::from_vec_with_nul_unchecked(v) }) } - Some(nul_pos) => Err(FromBytesWithNulError::interior_nul(nul_pos)), - None => Err(FromBytesWithNulError::not_nul_terminated()), + Some(nul_pos) => Err(FromVecWithNulError { + error_kind: FromBytesWithNulErrorKind::InteriorNul(nul_pos), + bytes: v, + }), + None => Err(FromVecWithNulError { + error_kind: FromBytesWithNulErrorKind::NotNulTerminated, + bytes: v, + }), } } } From d221ffc68e543f4a38efcc2bd34f52145f89003b Mon Sep 17 00:00:00 2001 From: Stefan Lankes Date: Sun, 14 Jun 2020 23:43:54 +0200 Subject: [PATCH 34/41] simplify conversion to IpAddr::V6 --- src/libstd/sys/hermit/net.rs | 20 ++------------------ 1 file changed, 2 insertions(+), 18 deletions(-) diff --git a/src/libstd/sys/hermit/net.rs b/src/libstd/sys/hermit/net.rs index 70c010e6232f8..cba8d6aaca61c 100644 --- a/src/libstd/sys/hermit/net.rs +++ b/src/libstd/sys/hermit/net.rs @@ -150,15 +150,7 @@ impl TcpStream { port, ), Ipv6(ref addr) => SocketAddr::new( - IpAddr::V6(Ipv6Addr::new( - ((addr.0[0] as u16) << 8) | addr.0[1] as u16, - ((addr.0[2] as u16) << 8) | addr.0[3] as u16, - ((addr.0[4] as u16) << 8) | addr.0[5] as u16, - ((addr.0[6] as u16) << 8) | addr.0[7] as u16, - ((addr.0[8] as u16) << 8) | addr.0[9] as u16, - ((addr.0[10] as u16) << 8) | addr.0[11] as u16, - ((addr.0[12] as u16) << 8) | addr.0[13] as u16, - ((addr.0[14] as u16) << 8) | addr.0[15] as u16)), + IpAddr::V6(Ipv6Addr::new(addr.0)), port, ), _ => { @@ -241,15 +233,7 @@ impl TcpListener { port, ), Ipv6(ref addr) => SocketAddr::new( - IpAddr::V6(Ipv6Addr::new( - ((addr.0[0] as u16) << 8) | addr.0[1] as u16, - ((addr.0[2] as u16) << 8) | addr.0[3] as u16, - ((addr.0[4] as u16) << 8) | addr.0[5] as u16, - ((addr.0[6] as u16) << 8) | addr.0[7] as u16, - ((addr.0[8] as u16) << 8) | addr.0[9] as u16, - ((addr.0[10] as u16) << 8) | addr.0[11] as u16, - ((addr.0[12] as u16) << 8) | addr.0[13] as u16, - ((addr.0[14] as u16) << 8) | addr.0[15] as u16)), + IpAddr::V6(Ipv6Addr::new(addr.0)), port, ), _ => { From 9d596b50f15dfff47fa2272ee63cdc9aeb9307fa Mon Sep 17 00:00:00 2001 From: Stefan Lankes Date: Mon, 15 Jun 2020 07:28:53 +0200 Subject: [PATCH 35/41] changes to pass the format check --- src/libstd/sys/hermit/net.rs | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) diff --git a/src/libstd/sys/hermit/net.rs b/src/libstd/sys/hermit/net.rs index cba8d6aaca61c..ced554d8790a7 100644 --- a/src/libstd/sys/hermit/net.rs +++ b/src/libstd/sys/hermit/net.rs @@ -149,13 +149,10 @@ impl TcpStream { IpAddr::V4(Ipv4Addr::new(addr.0[0], addr.0[1], addr.0[2], addr.0[3])), port, ), - Ipv6(ref addr) => SocketAddr::new( - IpAddr::V6(Ipv6Addr::new(addr.0)), - port, - ), + Ipv6(ref addr) => SocketAddr::new(IpAddr::V6(Ipv6Addr::new(addr.0)), port), _ => { return Err(io::Error::new(ErrorKind::Other, "peer_addr failed")); - }, + } }; Ok(saddr) @@ -232,13 +229,10 @@ impl TcpListener { IpAddr::V4(Ipv4Addr::new(addr.0[0], addr.0[1], addr.0[2], addr.0[3])), port, ), - Ipv6(ref addr) => SocketAddr::new( - IpAddr::V6(Ipv6Addr::new(addr.0)), - port, - ), + Ipv6(ref addr) => SocketAddr::new(IpAddr::V6(Ipv6Addr::new(addr.0)), port), _ => { return Err(io::Error::new(ErrorKind::Other, "accept failed")); - }, + } }; Ok((TcpStream(Arc::new(Socket(handle))), saddr)) From 810ba395638f622b4e7f11c2f056382db4d2fa05 Mon Sep 17 00:00:00 2001 From: Stefan Lankes Date: Mon, 15 Jun 2020 08:07:56 +0200 Subject: [PATCH 36/41] remove obsolete line --- src/libstd/sys/hermit/net.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/libstd/sys/hermit/net.rs b/src/libstd/sys/hermit/net.rs index ced554d8790a7..fbb562fa51051 100644 --- a/src/libstd/sys/hermit/net.rs +++ b/src/libstd/sys/hermit/net.rs @@ -35,7 +35,6 @@ impl Drop for Socket { } } - #[derive(Clone)] pub struct TcpStream(Arc); From aa53a037a286a05c88e61ca008d90354cccb1512 Mon Sep 17 00:00:00 2001 From: Stefan Lankes Date: Mon, 15 Jun 2020 08:43:08 +0200 Subject: [PATCH 37/41] Revert "changes to pass the format check" This reverts commit 9d596b50f15dfff47fa2272ee63cdc9aeb9307fa. --- src/libstd/sys/hermit/net.rs | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/src/libstd/sys/hermit/net.rs b/src/libstd/sys/hermit/net.rs index fbb562fa51051..8f96f8622c661 100644 --- a/src/libstd/sys/hermit/net.rs +++ b/src/libstd/sys/hermit/net.rs @@ -148,10 +148,13 @@ impl TcpStream { IpAddr::V4(Ipv4Addr::new(addr.0[0], addr.0[1], addr.0[2], addr.0[3])), port, ), - Ipv6(ref addr) => SocketAddr::new(IpAddr::V6(Ipv6Addr::new(addr.0)), port), + Ipv6(ref addr) => SocketAddr::new( + IpAddr::V6(Ipv6Addr::new(addr.0)), + port, + ), _ => { return Err(io::Error::new(ErrorKind::Other, "peer_addr failed")); - } + }, }; Ok(saddr) @@ -228,10 +231,13 @@ impl TcpListener { IpAddr::V4(Ipv4Addr::new(addr.0[0], addr.0[1], addr.0[2], addr.0[3])), port, ), - Ipv6(ref addr) => SocketAddr::new(IpAddr::V6(Ipv6Addr::new(addr.0)), port), + Ipv6(ref addr) => SocketAddr::new( + IpAddr::V6(Ipv6Addr::new(addr.0)), + port, + ), _ => { return Err(io::Error::new(ErrorKind::Other, "accept failed")); - } + }, }; Ok((TcpStream(Arc::new(Socket(handle))), saddr)) From 9c9f21fb23ae59012e7aba162e1105d26fcd119b Mon Sep 17 00:00:00 2001 From: Stefan Lankes Date: Mon, 15 Jun 2020 08:43:44 +0200 Subject: [PATCH 38/41] Revert "simplify conversion to IpAddr::V6" This reverts commit d221ffc68e543f4a38efcc2bd34f52145f89003b. --- src/libstd/sys/hermit/net.rs | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/src/libstd/sys/hermit/net.rs b/src/libstd/sys/hermit/net.rs index 8f96f8622c661..a02f1131329ee 100644 --- a/src/libstd/sys/hermit/net.rs +++ b/src/libstd/sys/hermit/net.rs @@ -149,7 +149,15 @@ impl TcpStream { port, ), Ipv6(ref addr) => SocketAddr::new( - IpAddr::V6(Ipv6Addr::new(addr.0)), + IpAddr::V6(Ipv6Addr::new( + ((addr.0[0] as u16) << 8) | addr.0[1] as u16, + ((addr.0[2] as u16) << 8) | addr.0[3] as u16, + ((addr.0[4] as u16) << 8) | addr.0[5] as u16, + ((addr.0[6] as u16) << 8) | addr.0[7] as u16, + ((addr.0[8] as u16) << 8) | addr.0[9] as u16, + ((addr.0[10] as u16) << 8) | addr.0[11] as u16, + ((addr.0[12] as u16) << 8) | addr.0[13] as u16, + ((addr.0[14] as u16) << 8) | addr.0[15] as u16)), port, ), _ => { @@ -232,7 +240,15 @@ impl TcpListener { port, ), Ipv6(ref addr) => SocketAddr::new( - IpAddr::V6(Ipv6Addr::new(addr.0)), + IpAddr::V6(Ipv6Addr::new( + ((addr.0[0] as u16) << 8) | addr.0[1] as u16, + ((addr.0[2] as u16) << 8) | addr.0[3] as u16, + ((addr.0[4] as u16) << 8) | addr.0[5] as u16, + ((addr.0[6] as u16) << 8) | addr.0[7] as u16, + ((addr.0[8] as u16) << 8) | addr.0[9] as u16, + ((addr.0[10] as u16) << 8) | addr.0[11] as u16, + ((addr.0[12] as u16) << 8) | addr.0[13] as u16, + ((addr.0[14] as u16) << 8) | addr.0[15] as u16)), port, ), _ => { From 6c983a733550ff37cb603f409901f3b3d0eaa8c2 Mon Sep 17 00:00:00 2001 From: Stefan Lankes Date: Mon, 15 Jun 2020 08:53:58 +0200 Subject: [PATCH 39/41] use Ipv6Addr::from to build the IPv6 address --- src/libstd/sys/hermit/net.rs | 26 ++------------------------ 1 file changed, 2 insertions(+), 24 deletions(-) diff --git a/src/libstd/sys/hermit/net.rs b/src/libstd/sys/hermit/net.rs index a02f1131329ee..6410dec756d24 100644 --- a/src/libstd/sys/hermit/net.rs +++ b/src/libstd/sys/hermit/net.rs @@ -148,18 +148,7 @@ impl TcpStream { IpAddr::V4(Ipv4Addr::new(addr.0[0], addr.0[1], addr.0[2], addr.0[3])), port, ), - Ipv6(ref addr) => SocketAddr::new( - IpAddr::V6(Ipv6Addr::new( - ((addr.0[0] as u16) << 8) | addr.0[1] as u16, - ((addr.0[2] as u16) << 8) | addr.0[3] as u16, - ((addr.0[4] as u16) << 8) | addr.0[5] as u16, - ((addr.0[6] as u16) << 8) | addr.0[7] as u16, - ((addr.0[8] as u16) << 8) | addr.0[9] as u16, - ((addr.0[10] as u16) << 8) | addr.0[11] as u16, - ((addr.0[12] as u16) << 8) | addr.0[13] as u16, - ((addr.0[14] as u16) << 8) | addr.0[15] as u16)), - port, - ), + Ipv6(ref addr) => SocketAddr::new(IpAddr::V6(Ipv6Addr::from(addr.0)), port), _ => { return Err(io::Error::new(ErrorKind::Other, "peer_addr failed")); }, @@ -239,18 +228,7 @@ impl TcpListener { IpAddr::V4(Ipv4Addr::new(addr.0[0], addr.0[1], addr.0[2], addr.0[3])), port, ), - Ipv6(ref addr) => SocketAddr::new( - IpAddr::V6(Ipv6Addr::new( - ((addr.0[0] as u16) << 8) | addr.0[1] as u16, - ((addr.0[2] as u16) << 8) | addr.0[3] as u16, - ((addr.0[4] as u16) << 8) | addr.0[5] as u16, - ((addr.0[6] as u16) << 8) | addr.0[7] as u16, - ((addr.0[8] as u16) << 8) | addr.0[9] as u16, - ((addr.0[10] as u16) << 8) | addr.0[11] as u16, - ((addr.0[12] as u16) << 8) | addr.0[13] as u16, - ((addr.0[14] as u16) << 8) | addr.0[15] as u16)), - port, - ), + Ipv6(ref addr) => SocketAddr::new(IpAddr::V6(Ipv6Addr::from(addr.0)), port), _ => { return Err(io::Error::new(ErrorKind::Other, "accept failed")); }, From a8e3746e9160b8a433c95df7114e5760592a62e8 Mon Sep 17 00:00:00 2001 From: Stefan Lankes Date: Mon, 15 Jun 2020 09:29:32 +0200 Subject: [PATCH 40/41] add comment about the usage of Arc --- src/libstd/sys/hermit/net.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/libstd/sys/hermit/net.rs b/src/libstd/sys/hermit/net.rs index 6410dec756d24..9146dfc55f438 100644 --- a/src/libstd/sys/hermit/net.rs +++ b/src/libstd/sys/hermit/net.rs @@ -35,6 +35,9 @@ impl Drop for Socket { } } +// Arc is used to count the number of used sockets. +// Only if all sockets are released, the drop +// method will close the socket. #[derive(Clone)] pub struct TcpStream(Arc); From 76f1581a25a27029279bb5eac17971ba68df1dbe Mon Sep 17 00:00:00 2001 From: Stefan Lankes Date: Mon, 15 Jun 2020 10:05:14 +0200 Subject: [PATCH 41/41] remove obsolete , to pass the format check --- src/libstd/sys/hermit/net.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/libstd/sys/hermit/net.rs b/src/libstd/sys/hermit/net.rs index 9146dfc55f438..9e588c4265ac2 100644 --- a/src/libstd/sys/hermit/net.rs +++ b/src/libstd/sys/hermit/net.rs @@ -154,7 +154,7 @@ impl TcpStream { Ipv6(ref addr) => SocketAddr::new(IpAddr::V6(Ipv6Addr::from(addr.0)), port), _ => { return Err(io::Error::new(ErrorKind::Other, "peer_addr failed")); - }, + } }; Ok(saddr) @@ -234,7 +234,7 @@ impl TcpListener { Ipv6(ref addr) => SocketAddr::new(IpAddr::V6(Ipv6Addr::from(addr.0)), port), _ => { return Err(io::Error::new(ErrorKind::Other, "accept failed")); - }, + } }; Ok((TcpStream(Arc::new(Socket(handle))), saddr))