diff --git a/src/ci/docker/wasm32/Dockerfile b/src/ci/docker/wasm32/Dockerfile index 8232539edda77..92461305320ee 100644 --- a/src/ci/docker/wasm32/Dockerfile +++ b/src/ci/docker/wasm32/Dockerfile @@ -25,7 +25,18 @@ RUN ln `which python3` /usr/bin/python ENV PATH=$PATH:/emsdk-portable ENV PATH=$PATH:/emsdk-portable/upstream/emscripten/ -ENV PATH=$PATH:/emsdk-portable/node/12.9.1_64bit/bin/ + +# Rust's build system requires NodeJS to be in the path, but the directory in +# which emsdk stores it contains the version number. This caused breakages in +# the past when emsdk bumped the node version causing the path to point to a +# missing directory. +# +# To avoid the problem this symlinks the latest NodeJs version available to +# "latest", and adds that to the path. +RUN ln -s /emsdk-portable/node/$(ls /emsdk-portable/node | sort -V | tail -n 1) \ + /emsdk-portable/node/latest +ENV PATH=$PATH:/emsdk-portable/node/latest/bin/ + ENV BINARYEN_ROOT=/emsdk-portable/upstream/ ENV EMSDK=/emsdk-portable ENV EM_CONFIG=/emsdk-portable/.emscripten diff --git a/src/libcore/alloc/global.rs b/src/libcore/alloc/global.rs index 147fe696ac02f..c198797e650f6 100644 --- a/src/libcore/alloc/global.rs +++ b/src/libcore/alloc/global.rs @@ -127,9 +127,12 @@ pub unsafe trait GlobalAlloc { #[stable(feature = "global_alloc", since = "1.28.0")] unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { let size = layout.size(); - let ptr = self.alloc(layout); + // SAFETY: the safety contract for `alloc` must be upheld by the caller. + let ptr = unsafe { self.alloc(layout) }; if !ptr.is_null() { - ptr::write_bytes(ptr, 0, size); + // SAFETY: as allocation succeeded, the region from `ptr` + // of size `size` is guaranteed to be valid for writes. + unsafe { ptr::write_bytes(ptr, 0, size) }; } ptr } @@ -187,11 +190,18 @@ pub unsafe trait GlobalAlloc { /// [`handle_alloc_error`]: ../../alloc/alloc/fn.handle_alloc_error.html #[stable(feature = "global_alloc", since = "1.28.0")] unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { - let new_layout = Layout::from_size_align_unchecked(new_size, layout.align()); - let new_ptr = self.alloc(new_layout); + // SAFETY: the caller must ensure that the `new_size` does not overflow. + // `layout.align()` comes from a `Layout` and is thus guaranteed to be valid. + let new_layout = unsafe { Layout::from_size_align_unchecked(new_size, layout.align()) }; + // SAFETY: the caller must ensure that `new_layout` is greater than zero. + let new_ptr = unsafe { self.alloc(new_layout) }; if !new_ptr.is_null() { - ptr::copy_nonoverlapping(ptr, new_ptr, cmp::min(layout.size(), new_size)); - self.dealloc(ptr, layout); + // SAFETY: the previously allocated block cannot overlap the newly allocated block. + // The safety contract for `dealloc` must be upheld by the caller. + unsafe { + ptr::copy_nonoverlapping(ptr, new_ptr, cmp::min(layout.size(), new_size)); + self.dealloc(ptr, layout); + } } new_ptr } diff --git a/src/libcore/alloc/layout.rs b/src/libcore/alloc/layout.rs index a09c2387d0de2..ae7ae7044655b 100644 --- a/src/libcore/alloc/layout.rs +++ b/src/libcore/alloc/layout.rs @@ -90,7 +90,8 @@ impl Layout { #[rustc_const_stable(feature = "alloc_layout", since = "1.28.0")] #[inline] pub const unsafe fn from_size_align_unchecked(size: usize, align: usize) -> Self { - Layout { size_: size, align_: NonZeroUsize::new_unchecked(align) } + // SAFETY: the caller must ensure that `align` is greater than zero. + Layout { size_: size, align_: unsafe { NonZeroUsize::new_unchecked(align) } } } /// The minimum size in bytes for a memory block of this layout. diff --git a/src/libcore/alloc/mod.rs b/src/libcore/alloc/mod.rs index 1346fbd481003..be4e051b1ca42 100644 --- a/src/libcore/alloc/mod.rs +++ b/src/libcore/alloc/mod.rs @@ -54,7 +54,9 @@ impl AllocInit { #[inline] #[unstable(feature = "allocator_api", issue = "32838")] pub unsafe fn init(self, memory: MemoryBlock) { - self.init_offset(memory, 0) + // SAFETY: the safety contract for `init_offset` must be + // upheld by the caller. + unsafe { self.init_offset(memory, 0) } } /// Initialize the memory block like specified by `init` at the specified `offset`. @@ -78,7 +80,10 @@ impl AllocInit { match self { AllocInit::Uninitialized => (), AllocInit::Zeroed => { - memory.ptr.as_ptr().add(offset).write_bytes(0, memory.size - offset) + // SAFETY: the caller must guarantee that `offset` is smaller than or equal to `memory.size`, + // so the memory from `memory.ptr + offset` of length `memory.size - offset` + // is guaranteed to be contaned in `memory` and thus valid for writes. + unsafe { memory.ptr.as_ptr().add(offset).write_bytes(0, memory.size - offset) } } } } @@ -281,11 +286,23 @@ pub unsafe trait AllocRef { return Ok(MemoryBlock { ptr, size }); } - let new_layout = Layout::from_size_align_unchecked(new_size, layout.align()); + let new_layout = + // SAFETY: the caller must ensure that the `new_size` does not overflow. + // `layout.align()` comes from a `Layout` and is thus guaranteed to be valid for a Layout. + // The caller must ensure that `new_size` is greater than zero. + unsafe { Layout::from_size_align_unchecked(new_size, layout.align()) }; let new_memory = self.alloc(new_layout, init)?; - ptr::copy_nonoverlapping(ptr.as_ptr(), new_memory.ptr.as_ptr(), size); - self.dealloc(ptr, layout); - Ok(new_memory) + + // SAFETY: because `new_size` must be greater than or equal to `size`, both the old and new + // memory allocation are valid for reads and writes for `size` bytes. Also, because the old + // allocation wasn't yet deallocated, it cannot overlap `new_memory`. Thus, the call to + // `copy_nonoverlapping` is safe. + // The safety contract for `dealloc` must be upheld by the caller. + unsafe { + ptr::copy_nonoverlapping(ptr.as_ptr(), new_memory.ptr.as_ptr(), size); + self.dealloc(ptr, layout); + Ok(new_memory) + } } } } @@ -356,11 +373,23 @@ pub unsafe trait AllocRef { return Ok(MemoryBlock { ptr, size }); } - let new_layout = Layout::from_size_align_unchecked(new_size, layout.align()); + let new_layout = + // SAFETY: the caller must ensure that the `new_size` does not overflow. + // `layout.align()` comes from a `Layout` and is thus guaranteed to be valid for a Layout. + // The caller must ensure that `new_size` is greater than zero. + unsafe { Layout::from_size_align_unchecked(new_size, layout.align()) }; let new_memory = self.alloc(new_layout, AllocInit::Uninitialized)?; - ptr::copy_nonoverlapping(ptr.as_ptr(), new_memory.ptr.as_ptr(), new_size); - self.dealloc(ptr, layout); - Ok(new_memory) + + // SAFETY: because `new_size` must be lower than or equal to `size`, both the old and new + // memory allocation are valid for reads and writes for `new_size` bytes. Also, because the + // old allocation wasn't yet deallocated, it cannot overlap `new_memory`. Thus, the call to + // `copy_nonoverlapping` is safe. + // The safety contract for `dealloc` must be upheld by the caller. + unsafe { + ptr::copy_nonoverlapping(ptr.as_ptr(), new_memory.ptr.as_ptr(), new_size); + self.dealloc(ptr, layout); + Ok(new_memory) + } } } } @@ -386,7 +415,8 @@ where #[inline] unsafe fn dealloc(&mut self, ptr: NonNull, layout: Layout) { - (**self).dealloc(ptr, layout) + // SAFETY: the safety contract must be upheld by the caller + unsafe { (**self).dealloc(ptr, layout) } } #[inline] @@ -398,7 +428,8 @@ where placement: ReallocPlacement, init: AllocInit, ) -> Result { - (**self).grow(ptr, layout, new_size, placement, init) + // SAFETY: the safety contract must be upheld by the caller + unsafe { (**self).grow(ptr, layout, new_size, placement, init) } } #[inline] @@ -409,6 +440,7 @@ where new_size: usize, placement: ReallocPlacement, ) -> Result { - (**self).shrink(ptr, layout, new_size, placement) + // SAFETY: the safety contract must be upheld by the caller + unsafe { (**self).shrink(ptr, layout, new_size, placement) } } } diff --git a/src/libcore/cell.rs b/src/libcore/cell.rs index c4293ed7bcfe2..51d9695687f4a 100644 --- a/src/libcore/cell.rs +++ b/src/libcore/cell.rs @@ -1005,7 +1005,12 @@ impl RefCell { #[inline] pub unsafe fn try_borrow_unguarded(&self) -> Result<&T, BorrowError> { if !is_writing(self.borrow.get()) { - Ok(&*self.value.get()) + // SAFETY: We check that nobody is actively writing now, but it is + // the caller's responsibility to ensure that nobody writes until + // the returned reference is no longer in use. + // Also, `self.value.get()` refers to the value owned by `self` + // and is thus guaranteed to be valid for the lifetime of `self`. + Ok(unsafe { &*self.value.get() }) } else { Err(BorrowError { _private: () }) } diff --git a/src/libcore/char/convert.rs b/src/libcore/char/convert.rs index d7e39946148ed..c329eec76ac3d 100644 --- a/src/libcore/char/convert.rs +++ b/src/libcore/char/convert.rs @@ -99,7 +99,8 @@ pub fn from_u32(i: u32) -> Option { #[inline] #[stable(feature = "char_from_unchecked", since = "1.5.0")] pub unsafe fn from_u32_unchecked(i: u32) -> char { - if cfg!(debug_assertions) { char::from_u32(i).unwrap() } else { transmute(i) } + // SAFETY: the caller must guarantee that `i` is a valid char value. + if cfg!(debug_assertions) { char::from_u32(i).unwrap() } else { unsafe { transmute(i) } } } #[stable(feature = "char_convert", since = "1.13.0")] diff --git a/src/libcore/char/methods.rs b/src/libcore/char/methods.rs index dd2f01c679f73..72555d781ed38 100644 --- a/src/libcore/char/methods.rs +++ b/src/libcore/char/methods.rs @@ -183,7 +183,8 @@ impl char { #[unstable(feature = "assoc_char_funcs", reason = "recently added", issue = "71763")] #[inline] pub unsafe fn from_u32_unchecked(i: u32) -> char { - super::convert::from_u32_unchecked(i) + // SAFETY: the safety contract must be upheld by the caller. + unsafe { super::convert::from_u32_unchecked(i) } } /// Converts a digit in the given radix to a `char`. diff --git a/src/libcore/convert/num.rs b/src/libcore/convert/num.rs index 46ba0a279b7ff..336c0b26bc7d7 100644 --- a/src/libcore/convert/num.rs +++ b/src/libcore/convert/num.rs @@ -28,7 +28,8 @@ macro_rules! impl_float_to_int { #[doc(hidden)] #[inline] unsafe fn to_int_unchecked(self) -> $Int { - crate::intrinsics::float_to_int_unchecked(self) + // SAFETY: the safety contract must be upheld by the caller. + unsafe { crate::intrinsics::float_to_int_unchecked(self) } } } )+ diff --git a/src/libcore/ffi.rs b/src/libcore/ffi.rs index 7bc2866dc2e67..ca4632006509f 100644 --- a/src/libcore/ffi.rs +++ b/src/libcore/ffi.rs @@ -333,7 +333,8 @@ impl<'f> VaListImpl<'f> { /// Advance to the next arg. #[inline] pub unsafe fn arg(&mut self) -> T { - va_arg(self) + // SAFETY: the caller must uphold the safety contract for `va_arg`. + unsafe { va_arg(self) } } /// Copies the `va_list` at the current location. @@ -343,7 +344,10 @@ impl<'f> VaListImpl<'f> { { let mut ap = self.clone(); let ret = f(ap.as_va_list()); - va_end(&mut ap); + // SAFETY: the caller must uphold the safety contract for `va_end`. + unsafe { + va_end(&mut ap); + } ret } } diff --git a/src/libcore/future/mod.rs b/src/libcore/future/mod.rs index 9dbc23f5c04c5..2555d91ae8d9a 100644 --- a/src/libcore/future/mod.rs +++ b/src/libcore/future/mod.rs @@ -85,5 +85,7 @@ where #[unstable(feature = "gen_future", issue = "50547")] #[inline] pub unsafe fn get_context<'a, 'b>(cx: ResumeTy) -> &'a mut Context<'b> { - &mut *cx.0.as_ptr().cast() + // SAFETY: the caller must guarantee that `cx.0` is a valid pointer + // that fulfills all the requirements for a mutable reference. + unsafe { &mut *cx.0.as_ptr().cast() } } diff --git a/src/libcore/hash/sip.rs b/src/libcore/hash/sip.rs index ac058609f45ed..f2bbf646f3272 100644 --- a/src/libcore/hash/sip.rs +++ b/src/libcore/hash/sip.rs @@ -130,15 +130,19 @@ unsafe fn u8to64_le(buf: &[u8], start: usize, len: usize) -> u64 { let mut i = 0; // current byte index (from LSB) in the output u64 let mut out = 0; if i + 3 < len { - out = load_int_le!(buf, start + i, u32) as u64; + // SAFETY: `i` cannot be greater than `len`, and the caller must guarantee + // that the index start..start+len is in bounds. + out = unsafe { load_int_le!(buf, start + i, u32) } as u64; i += 4; } if i + 1 < len { - out |= (load_int_le!(buf, start + i, u16) as u64) << (i * 8); + // SAFETY: same as above. + out |= (unsafe { load_int_le!(buf, start + i, u16) } as u64) << (i * 8); i += 2 } if i < len { - out |= (*buf.get_unchecked(start + i) as u64) << (i * 8); + // SAFETY: same as above. + out |= (unsafe { *buf.get_unchecked(start + i) } as u64) << (i * 8); i += 1; } debug_assert_eq!(i, len); diff --git a/src/libcore/hint.rs b/src/libcore/hint.rs index 0d794de5fe84b..9ebcde79b633d 100644 --- a/src/libcore/hint.rs +++ b/src/libcore/hint.rs @@ -46,7 +46,9 @@ use crate::intrinsics; #[inline] #[stable(feature = "unreachable", since = "1.27.0")] pub unsafe fn unreachable_unchecked() -> ! { - intrinsics::unreachable() + // SAFETY: the safety contract for `intrinsics::unreachable` must + // be upheld by the caller. + unsafe { intrinsics::unreachable() } } /// Emits a machine instruction hinting to the processor that it is running in busy-wait diff --git a/src/libcore/intrinsics.rs b/src/libcore/intrinsics.rs index 57ffed19c0085..7206cbd198fca 100644 --- a/src/libcore/intrinsics.rs +++ b/src/libcore/intrinsics.rs @@ -2099,7 +2099,10 @@ pub unsafe fn copy_nonoverlapping(src: *const T, dst: *mut T, count: usize) { // Not panicking to keep codegen impact smaller. abort(); } - copy_nonoverlapping(src, dst, count) + + // SAFETY: the safety contract for `copy_nonoverlapping` must be + // upheld by the caller. + unsafe { copy_nonoverlapping(src, dst, count) } } /// Copies `count * size_of::()` bytes from `src` to `dst`. The source @@ -2165,7 +2168,9 @@ pub unsafe fn copy(src: *const T, dst: *mut T, count: usize) { // Not panicking to keep codegen impact smaller. abort(); } - copy(src, dst, count) + + // SAFETY: the safety contract for `copy` must be upheld by the caller. + unsafe { copy(src, dst, count) } } /// Sets `count * size_of::()` bytes of memory starting at `dst` to @@ -2248,5 +2253,7 @@ pub unsafe fn write_bytes(dst: *mut T, val: u8, count: usize) { } debug_assert!(is_aligned_and_not_null(dst), "attempt to write to unaligned or null pointer"); - write_bytes(dst, val, count) + + // SAFETY: the safety contract for `write_bytes` must be upheld by the caller. + unsafe { write_bytes(dst, val, count) } } diff --git a/src/libcore/iter/adapters/fuse.rs b/src/libcore/iter/adapters/fuse.rs index 502fc2e631502..d2e2fc04a2b76 100644 --- a/src/libcore/iter/adapters/fuse.rs +++ b/src/libcore/iter/adapters/fuse.rs @@ -178,9 +178,10 @@ where { unsafe fn get_unchecked(&mut self, i: usize) -> I::Item { match self.iter { - Some(ref mut iter) => iter.get_unchecked(i), + // SAFETY: the caller must uphold the contract for `TrustedRandomAccess::get_unchecked`. + Some(ref mut iter) => unsafe { iter.get_unchecked(i) }, // SAFETY: the caller asserts there is an item at `i`, so we're not exhausted. - None => intrinsics::unreachable(), + None => unsafe { intrinsics::unreachable() }, } } diff --git a/src/libcore/iter/adapters/mod.rs b/src/libcore/iter/adapters/mod.rs index 00529f0e2d54f..133643a0c7f03 100644 --- a/src/libcore/iter/adapters/mod.rs +++ b/src/libcore/iter/adapters/mod.rs @@ -272,7 +272,8 @@ where T: Copy, { unsafe fn get_unchecked(&mut self, i: usize) -> Self::Item { - *self.it.get_unchecked(i) + // SAFETY: the caller must uphold the contract for `TrustedRandomAccess::get_unchecked`. + unsafe { *self.it.get_unchecked(i) } } #[inline] @@ -402,7 +403,8 @@ where T: Clone, { default unsafe fn get_unchecked(&mut self, i: usize) -> Self::Item { - self.it.get_unchecked(i).clone() + // SAFETY: the caller must uphold the contract for `TrustedRandomAccess::get_unchecked`. + unsafe { self.it.get_unchecked(i) }.clone() } #[inline] @@ -418,7 +420,8 @@ where T: Copy, { unsafe fn get_unchecked(&mut self, i: usize) -> Self::Item { - *self.it.get_unchecked(i) + // SAFETY: the caller must uphold the contract for `TrustedRandomAccess::get_unchecked`. + unsafe { *self.it.get_unchecked(i) } } #[inline] @@ -930,7 +933,8 @@ where F: FnMut(I::Item) -> B, { unsafe fn get_unchecked(&mut self, i: usize) -> Self::Item { - (self.f)(self.iter.get_unchecked(i)) + // SAFETY: the caller must uphold the contract for `TrustedRandomAccess::get_unchecked`. + (self.f)(unsafe { self.iter.get_unchecked(i) }) } #[inline] fn may_have_side_effect() -> bool { @@ -1392,7 +1396,8 @@ where I: TrustedRandomAccess, { unsafe fn get_unchecked(&mut self, i: usize) -> (usize, I::Item) { - (self.count + i, self.iter.get_unchecked(i)) + // SAFETY: the caller must uphold the contract for `TrustedRandomAccess::get_unchecked`. + (self.count + i, unsafe { self.iter.get_unchecked(i) }) } fn may_have_side_effect() -> bool { diff --git a/src/libcore/iter/adapters/zip.rs b/src/libcore/iter/adapters/zip.rs index e83d36a580f06..985e6561665c7 100644 --- a/src/libcore/iter/adapters/zip.rs +++ b/src/libcore/iter/adapters/zip.rs @@ -271,7 +271,8 @@ where B: TrustedRandomAccess, { unsafe fn get_unchecked(&mut self, i: usize) -> (A::Item, B::Item) { - (self.a.get_unchecked(i), self.b.get_unchecked(i)) + // SAFETY: the caller must uphold the contract for `TrustedRandomAccess::get_unchecked`. + unsafe { (self.a.get_unchecked(i), self.b.get_unchecked(i)) } } fn may_have_side_effect() -> bool { diff --git a/src/libcore/iter/range.rs b/src/libcore/iter/range.rs index bd7e6cfa5a750..ee53b6a13f837 100644 --- a/src/libcore/iter/range.rs +++ b/src/libcore/iter/range.rs @@ -189,12 +189,14 @@ macro_rules! step_identical_methods { () => { #[inline] unsafe fn forward_unchecked(start: Self, n: usize) -> Self { - start.unchecked_add(n as Self) + // SAFETY: the caller has to guarantee that `start + n` doesn't overflow. + unsafe { start.unchecked_add(n as Self) } } #[inline] unsafe fn backward_unchecked(start: Self, n: usize) -> Self { - start.unchecked_sub(n as Self) + // SAFETY: the caller has to guarantee that `start - n` doesn't overflow. + unsafe { start.unchecked_sub(n as Self) } } #[inline] @@ -450,21 +452,33 @@ unsafe impl Step for char { #[inline] unsafe fn forward_unchecked(start: char, count: usize) -> char { let start = start as u32; - let mut res = Step::forward_unchecked(start, count); + // SAFETY: the caller must guarantee that this doesn't overflow + // the range of values for a char. + let mut res = unsafe { Step::forward_unchecked(start, count) }; if start < 0xD800 && 0xD800 <= res { - res = Step::forward_unchecked(res, 0x800); + // SAFETY: the caller must guarantee that this doesn't overflow + // the range of values for a char. + res = unsafe { Step::forward_unchecked(res, 0x800) }; } - char::from_u32_unchecked(res) + // SAFETY: because of the previous contract, this is guaranteed + // by the caller to be a valid char. + unsafe { char::from_u32_unchecked(res) } } #[inline] unsafe fn backward_unchecked(start: char, count: usize) -> char { let start = start as u32; - let mut res = Step::backward_unchecked(start, count); + // SAFETY: the caller must guarantee that this doesn't overflow + // the range of values for a char. + let mut res = unsafe { Step::backward_unchecked(start, count) }; if start >= 0xE000 && 0xE000 > res { - res = Step::backward_unchecked(res, 0x800); + // SAFETY: the caller must guarantee that this doesn't overflow + // the range of values for a char. + res = unsafe { Step::backward_unchecked(res, 0x800) }; } - char::from_u32_unchecked(res) + // SAFETY: because of the previous contract, this is guaranteed + // by the caller to be a valid char. + unsafe { char::from_u32_unchecked(res) } } } diff --git a/src/libcore/lib.rs b/src/libcore/lib.rs index 63ddd97eed3df..50c56434fa9a1 100644 --- a/src/libcore/lib.rs +++ b/src/libcore/lib.rs @@ -149,6 +149,8 @@ #![feature(const_type_id)] #![feature(const_caller_location)] #![feature(no_niche)] // rust-lang/rust#68303 +#![feature(unsafe_block_in_unsafe_fn)] +#![deny(unsafe_op_in_unsafe_fn)] #[prelude_import] #[allow(unused)] @@ -279,7 +281,13 @@ pub mod primitive; // set up in such a way that directly pulling it here works such that the // crate uses the this crate as its libcore. #[path = "../stdarch/crates/core_arch/src/mod.rs"] -#[allow(missing_docs, missing_debug_implementations, dead_code, unused_imports)] +#[allow( + missing_docs, + missing_debug_implementations, + dead_code, + unused_imports, + unsafe_op_in_unsafe_fn +)] // FIXME: This annotation should be moved into rust-lang/stdarch after clashing_extern_declarations is // merged. It currently cannot because bootstrap fails as the lint hasn't been defined yet. #[cfg_attr(not(bootstrap), allow(clashing_extern_declarations))] diff --git a/src/libcore/mem/manually_drop.rs b/src/libcore/mem/manually_drop.rs index 18767c482c77e..920f5e9c0bd28 100644 --- a/src/libcore/mem/manually_drop.rs +++ b/src/libcore/mem/manually_drop.rs @@ -122,7 +122,9 @@ impl ManuallyDrop { #[stable(feature = "manually_drop_take", since = "1.42.0")] #[inline] pub unsafe fn take(slot: &mut ManuallyDrop) -> T { - ptr::read(&slot.value) + // SAFETY: we are reading from a reference, which is guaranteed + // to be valid for reads. + unsafe { ptr::read(&slot.value) } } } @@ -152,7 +154,10 @@ impl ManuallyDrop { #[stable(feature = "manually_drop", since = "1.20.0")] #[inline] pub unsafe fn drop(slot: &mut ManuallyDrop) { - ptr::drop_in_place(&mut slot.value) + // SAFETY: we are dropping the value pointed to by a mutable reference + // which is guaranteed to be valid for writes. + // It is up to the caller to make sure that `slot` isn't dropped again. + unsafe { ptr::drop_in_place(&mut slot.value) } } } diff --git a/src/libcore/mem/maybe_uninit.rs b/src/libcore/mem/maybe_uninit.rs index 499016545e967..7732525a0fc28 100644 --- a/src/libcore/mem/maybe_uninit.rs +++ b/src/libcore/mem/maybe_uninit.rs @@ -494,8 +494,12 @@ impl MaybeUninit { #[inline(always)] #[rustc_diagnostic_item = "assume_init"] pub unsafe fn assume_init(self) -> T { - intrinsics::assert_inhabited::(); - ManuallyDrop::into_inner(self.value) + // SAFETY: the caller must guarantee that `self` is initialized. + // This also means that `self` must be a `value` variant. + unsafe { + intrinsics::assert_inhabited::(); + ManuallyDrop::into_inner(self.value) + } } /// Reads the value from the `MaybeUninit` container. The resulting `T` is subject @@ -558,8 +562,12 @@ impl MaybeUninit { #[unstable(feature = "maybe_uninit_extra", issue = "63567")] #[inline(always)] pub unsafe fn read(&self) -> T { - intrinsics::assert_inhabited::(); - self.as_ptr().read() + // SAFETY: the caller must guarantee that `self` is initialized. + // Reading from `self.as_ptr()` is safe since `self` should be initialized. + unsafe { + intrinsics::assert_inhabited::(); + self.as_ptr().read() + } } /// Gets a shared reference to the contained value. @@ -620,8 +628,12 @@ impl MaybeUninit { #[unstable(feature = "maybe_uninit_ref", issue = "63568")] #[inline(always)] pub unsafe fn get_ref(&self) -> &T { - intrinsics::assert_inhabited::(); - &*self.value + // SAFETY: the caller must guarantee that `self` is initialized. + // This also means that `self` must be a `value` variant. + unsafe { + intrinsics::assert_inhabited::(); + &*self.value + } } /// Gets a mutable (unique) reference to the contained value. @@ -738,8 +750,12 @@ impl MaybeUninit { #[unstable(feature = "maybe_uninit_ref", issue = "63568")] #[inline(always)] pub unsafe fn get_mut(&mut self) -> &mut T { - intrinsics::assert_inhabited::(); - &mut *self.value + // SAFETY: the caller must guarantee that `self` is initialized. + // This also means that `self` must be a `value` variant. + unsafe { + intrinsics::assert_inhabited::(); + &mut *self.value + } } /// Assuming all the elements are initialized, get a slice to them. @@ -752,7 +768,11 @@ impl MaybeUninit { #[unstable(feature = "maybe_uninit_slice_assume_init", issue = "none")] #[inline(always)] pub unsafe fn slice_get_ref(slice: &[Self]) -> &[T] { - &*(slice as *const [Self] as *const [T]) + // SAFETY: casting slice to a `*const [T]` is safe since the caller guarantees that + // `slice` is initialized, and`MaybeUninit` is guaranteed to have the same layout as `T`. + // The pointer obtained is valid since it refers to memory owned by `slice` which is a + // reference and thus guaranteed to be valid for reads. + unsafe { &*(slice as *const [Self] as *const [T]) } } /// Assuming all the elements are initialized, get a mutable slice to them. @@ -765,7 +785,9 @@ impl MaybeUninit { #[unstable(feature = "maybe_uninit_slice_assume_init", issue = "none")] #[inline(always)] pub unsafe fn slice_get_mut(slice: &mut [Self]) -> &mut [T] { - &mut *(slice as *mut [Self] as *mut [T]) + // SAFETY: similar to safety notes for `slice_get_ref`, but we have a + // mutable reference which is also guaranteed to be valid for writes. + unsafe { &mut *(slice as *mut [Self] as *mut [T]) } } /// Gets a pointer to the first element of the array. diff --git a/src/libcore/mem/mod.rs b/src/libcore/mem/mod.rs index 46e6ea7cd1866..272088815ece9 100644 --- a/src/libcore/mem/mod.rs +++ b/src/libcore/mem/mod.rs @@ -623,8 +623,11 @@ pub const fn needs_drop() -> bool { #[allow(deprecated)] #[rustc_diagnostic_item = "mem_zeroed"] pub unsafe fn zeroed() -> T { - intrinsics::assert_zero_valid::(); - MaybeUninit::zeroed().assume_init() + // SAFETY: the caller must guarantee that an all-zero value is valid for `T`. + unsafe { + intrinsics::assert_zero_valid::(); + MaybeUninit::zeroed().assume_init() + } } /// Bypasses Rust's normal memory-initialization checks by pretending to @@ -656,8 +659,11 @@ pub unsafe fn zeroed() -> T { #[allow(deprecated)] #[rustc_diagnostic_item = "mem_uninitialized"] pub unsafe fn uninitialized() -> T { - intrinsics::assert_uninit_valid::(); - MaybeUninit::uninit().assume_init() + // SAFETY: the caller must guarantee that an unitialized value is valid for `T`. + unsafe { + intrinsics::assert_uninit_valid::(); + MaybeUninit::uninit().assume_init() + } } /// Swaps the values at two mutable locations, without deinitializing either one. @@ -922,9 +928,14 @@ pub fn drop(_x: T) {} pub unsafe fn transmute_copy(src: &T) -> U { // If U has a higher alignment requirement, src may not be suitably aligned. if align_of::() > align_of::() { - ptr::read_unaligned(src as *const T as *const U) + // SAFETY: `src` is a reference which is guaranteed to be valid for reads. + // The caller must guarantee that the actual transmutation is safe. + unsafe { ptr::read_unaligned(src as *const T as *const U) } } else { - ptr::read(src as *const T as *const U) + // SAFETY: `src` is a reference which is guaranteed to be valid for reads. + // We just checked that `src as *const U` was properly aligned. + // The caller must guarantee that the actual transmutation is safe. + unsafe { ptr::read(src as *const T as *const U) } } } diff --git a/src/libcore/num/f32.rs b/src/libcore/num/f32.rs index 6313de31ce4d5..061d1ea6b1c46 100644 --- a/src/libcore/num/f32.rs +++ b/src/libcore/num/f32.rs @@ -629,7 +629,9 @@ impl f32 { where Self: FloatToInt, { - FloatToInt::::to_int_unchecked(self) + // SAFETY: the caller must uphold the safety contract for + // `FloatToInt::to_int_unchecked`. + unsafe { FloatToInt::::to_int_unchecked(self) } } /// Raw transmutation to `u32`. diff --git a/src/libcore/num/f64.rs b/src/libcore/num/f64.rs index d42e5392c5863..b0df4d64f6ee1 100644 --- a/src/libcore/num/f64.rs +++ b/src/libcore/num/f64.rs @@ -643,7 +643,9 @@ impl f64 { where Self: FloatToInt, { - FloatToInt::::to_int_unchecked(self) + // SAFETY: the caller must uphold the safety contract for + // `FloatToInt::to_int_unchecked`. + unsafe { FloatToInt::::to_int_unchecked(self) } } /// Raw transmutation to `u64`. diff --git a/src/libcore/num/mod.rs b/src/libcore/num/mod.rs index d36da90f2adc9..2ded2e9c086c8 100644 --- a/src/libcore/num/mod.rs +++ b/src/libcore/num/mod.rs @@ -74,7 +74,8 @@ assert_eq!(size_of::>(), size_of::<", s #[rustc_const_stable(feature = "nonzero", since = "1.34.0")] #[inline] pub const unsafe fn new_unchecked(n: $Int) -> Self { - Self(n) + // SAFETY: this is guaranteed to be safe by the caller. + unsafe { Self(n) } } /// Creates a non-zero if the given value is not zero. @@ -762,7 +763,9 @@ cannot occur. This results in undefined behavior when `self + rhs > ", stringify without modifying the original"] #[inline] pub unsafe fn unchecked_add(self, rhs: Self) -> Self { - intrinsics::unchecked_add(self, rhs) + // SAFETY: the caller must uphold the safety contract for + // `unchecked_add`. + unsafe { intrinsics::unchecked_add(self, rhs) } } } @@ -804,7 +807,9 @@ cannot occur. This results in undefined behavior when `self - rhs > ", stringify without modifying the original"] #[inline] pub unsafe fn unchecked_sub(self, rhs: Self) -> Self { - intrinsics::unchecked_sub(self, rhs) + // SAFETY: the caller must uphold the safety contract for + // `unchecked_sub`. + unsafe { intrinsics::unchecked_sub(self, rhs) } } } @@ -846,7 +851,9 @@ cannot occur. This results in undefined behavior when `self * rhs > ", stringify without modifying the original"] #[inline] pub unsafe fn unchecked_mul(self, rhs: Self) -> Self { - intrinsics::unchecked_mul(self, rhs) + // SAFETY: the caller must uphold the safety contract for + // `unchecked_mul`. + unsafe { intrinsics::unchecked_mul(self, rhs) } } } @@ -2998,7 +3005,9 @@ cannot occur. This results in undefined behavior when `self + rhs > ", stringify without modifying the original"] #[inline] pub unsafe fn unchecked_add(self, rhs: Self) -> Self { - intrinsics::unchecked_add(self, rhs) + // SAFETY: the caller must uphold the safety contract for + // `unchecked_add`. + unsafe { intrinsics::unchecked_add(self, rhs) } } } @@ -3038,7 +3047,9 @@ cannot occur. This results in undefined behavior when `self - rhs > ", stringify without modifying the original"] #[inline] pub unsafe fn unchecked_sub(self, rhs: Self) -> Self { - intrinsics::unchecked_sub(self, rhs) + // SAFETY: the caller must uphold the safety contract for + // `unchecked_sub`. + unsafe { intrinsics::unchecked_sub(self, rhs) } } } @@ -3078,7 +3089,9 @@ cannot occur. This results in undefined behavior when `self * rhs > ", stringify without modifying the original"] #[inline] pub unsafe fn unchecked_mul(self, rhs: Self) -> Self { - intrinsics::unchecked_mul(self, rhs) + // SAFETY: the caller must uphold the safety contract for + // `unchecked_mul`. + unsafe { intrinsics::unchecked_mul(self, rhs) } } } diff --git a/src/libcore/pin.rs b/src/libcore/pin.rs index 6f5bf7ad9da52..da299f026f8f1 100644 --- a/src/libcore/pin.rs +++ b/src/libcore/pin.rs @@ -679,7 +679,10 @@ impl<'a, T: ?Sized> Pin<&'a T> { { let pointer = &*self.pointer; let new_pointer = func(pointer); - Pin::new_unchecked(new_pointer) + + // SAFETY: the safety contract for `new_unchecked` must be + // upheld by the caller. + unsafe { Pin::new_unchecked(new_pointer) } } /// Gets a shared reference out of a pin. @@ -769,9 +772,13 @@ impl<'a, T: ?Sized> Pin<&'a mut T> { U: ?Sized, F: FnOnce(&mut T) -> &mut U, { - let pointer = Pin::get_unchecked_mut(self); + // SAFETY: the caller is responsible for not moving the + // value out of this reference. + let pointer = unsafe { Pin::get_unchecked_mut(self) }; let new_pointer = func(pointer); - Pin::new_unchecked(new_pointer) + // SAFETY: as the value of `this` is guaranteed to not have + // been moved out, this call to `new_unchecked` is safe. + unsafe { Pin::new_unchecked(new_pointer) } } } diff --git a/src/libcore/ptr/const_ptr.rs b/src/libcore/ptr/const_ptr.rs index 64a506a6377f2..d1d7a71523822 100644 --- a/src/libcore/ptr/const_ptr.rs +++ b/src/libcore/ptr/const_ptr.rs @@ -95,7 +95,9 @@ impl *const T { #[stable(feature = "ptr_as_ref", since = "1.9.0")] #[inline] pub unsafe fn as_ref<'a>(self) -> Option<&'a T> { - if self.is_null() { None } else { Some(&*self) } + // SAFETY: the caller must guarantee that `self` is valid + // for a reference if it isn't null. + if self.is_null() { None } else { unsafe { Some(&*self) } } } /// Calculates the offset from a pointer. @@ -157,7 +159,8 @@ impl *const T { where T: Sized, { - intrinsics::offset(self, count) + // SAFETY: the caller must uphold the safety contract for `offset`. + unsafe { intrinsics::offset(self, count) } } /// Calculates the offset from a pointer using wrapping arithmetic. @@ -292,7 +295,8 @@ impl *const T { { let pointee_size = mem::size_of::(); assert!(0 < pointee_size && pointee_size <= isize::MAX as usize); - intrinsics::ptr_offset_from(self, origin) + // SAFETY: the caller must uphold the safety contract for `ptr_offset_from`. + unsafe { intrinsics::ptr_offset_from(self, origin) } } /// Returns whether two pointers are guaranteed to be equal. @@ -471,7 +475,8 @@ impl *const T { where T: Sized, { - self.offset(count as isize) + // SAFETY: the caller must uphold the safety contract for `offset`. + unsafe { self.offset(count as isize) } } /// Calculates the offset from a pointer (convenience for @@ -534,7 +539,8 @@ impl *const T { where T: Sized, { - self.offset((count as isize).wrapping_neg()) + // SAFETY: the caller must uphold the safety contract for `offset`. + unsafe { self.offset((count as isize).wrapping_neg()) } } /// Calculates the offset from a pointer using wrapping arithmetic. @@ -663,7 +669,8 @@ impl *const T { where T: Sized, { - read(self) + // SAFETY: the caller must uphold the safety contract for `read`. + unsafe { read(self) } } /// Performs a volatile read of the value from `self` without moving it. This @@ -682,7 +689,8 @@ impl *const T { where T: Sized, { - read_volatile(self) + // SAFETY: the caller must uphold the safety contract for `read_volatile`. + unsafe { read_volatile(self) } } /// Reads the value from `self` without moving it. This leaves the @@ -699,7 +707,8 @@ impl *const T { where T: Sized, { - read_unaligned(self) + // SAFETY: the caller must uphold the safety contract for `read_unaligned`. + unsafe { read_unaligned(self) } } /// Copies `count * size_of` bytes from `self` to `dest`. The source @@ -716,7 +725,8 @@ impl *const T { where T: Sized, { - copy(self, dest, count) + // SAFETY: the caller must uphold the safety contract for `copy`. + unsafe { copy(self, dest, count) } } /// Copies `count * size_of` bytes from `self` to `dest`. The source @@ -733,7 +743,8 @@ impl *const T { where T: Sized, { - copy_nonoverlapping(self, dest, count) + // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`. + unsafe { copy_nonoverlapping(self, dest, count) } } /// Computes the offset that needs to be applied to the pointer in order to make it aligned to diff --git a/src/libcore/ptr/mod.rs b/src/libcore/ptr/mod.rs index ca2b0c85ec121..5f028f9ea76ca 100644 --- a/src/libcore/ptr/mod.rs +++ b/src/libcore/ptr/mod.rs @@ -184,7 +184,9 @@ mod mut_ptr; pub unsafe fn drop_in_place(to_drop: *mut T) { // Code here does not matter - this is replaced by the // real drop glue by the compiler. - drop_in_place(to_drop) + + // SAFETY: see comment above + unsafe { drop_in_place(to_drop) } } /// Creates a null raw pointer. @@ -374,9 +376,15 @@ pub unsafe fn swap(x: *mut T, y: *mut T) { let mut tmp = MaybeUninit::::uninit(); // Perform the swap - copy_nonoverlapping(x, tmp.as_mut_ptr(), 1); - copy(y, x, 1); // `x` and `y` may overlap - copy_nonoverlapping(tmp.as_ptr(), y, 1); + // SAFETY: the caller must guarantee that `x` and `y` are + // valid for writes and properly aligned. `tmp` cannot be + // overlapping either `x` or `y` because `tmp` was just allocated + // on the stack as a separate allocated object. + unsafe { + copy_nonoverlapping(x, tmp.as_mut_ptr(), 1); + copy(y, x, 1); // `x` and `y` may overlap + copy_nonoverlapping(tmp.as_ptr(), y, 1); + } } /// Swaps `count * size_of::()` bytes between the two regions of memory @@ -432,7 +440,9 @@ pub unsafe fn swap_nonoverlapping(x: *mut T, y: *mut T, count: usize) { let x = x as *mut u8; let y = y as *mut u8; let len = mem::size_of::() * count; - swap_nonoverlapping_bytes(x, y, len) + // SAFETY: the caller must guarantee that `x` and `y` are + // valid for writes and properly aligned. + unsafe { swap_nonoverlapping_bytes(x, y, len) } } #[inline] @@ -440,11 +450,16 @@ pub(crate) unsafe fn swap_nonoverlapping_one(x: *mut T, y: *mut T) { // For types smaller than the block optimization below, // just swap directly to avoid pessimizing codegen. if mem::size_of::() < 32 { - let z = read(x); - copy_nonoverlapping(y, x, 1); - write(y, z); + // SAFETY: the caller must guarantee that `x` and `y` are valid + // for writes, properly aligned, and non-overlapping. + unsafe { + let z = read(x); + copy_nonoverlapping(y, x, 1); + write(y, z); + } } else { - swap_nonoverlapping(x, y, 1); + // SAFETY: the caller must uphold the safety contract for `swap_nonoverlapping`. + unsafe { swap_nonoverlapping(x, y, 1) }; } } @@ -471,14 +486,23 @@ unsafe fn swap_nonoverlapping_bytes(x: *mut u8, y: *mut u8, len: usize) { // Declaring `t` here avoids aligning the stack when this loop is unused let mut t = mem::MaybeUninit::::uninit(); let t = t.as_mut_ptr() as *mut u8; - let x = x.add(i); - let y = y.add(i); - // Swap a block of bytes of x & y, using t as a temporary buffer - // This should be optimized into efficient SIMD operations where available - copy_nonoverlapping(x, t, block_size); - copy_nonoverlapping(y, x, block_size); - copy_nonoverlapping(t, y, block_size); + // SAFETY: As `i < len`, and as the caller must guarantee that `x` and `y` are valid + // for `len` bytes, `x + i` and `y + i` must be valid adresses, which fulfills the + // safety contract for `add`. + // + // Also, the caller must guarantee that `x` and `y` are valid for writes, properly aligned, + // and non-overlapping, which fulfills the safety contract for `copy_nonoverlapping`. + unsafe { + let x = x.add(i); + let y = y.add(i); + + // Swap a block of bytes of x & y, using t as a temporary buffer + // This should be optimized into efficient SIMD operations where available + copy_nonoverlapping(x, t, block_size); + copy_nonoverlapping(y, x, block_size); + copy_nonoverlapping(t, y, block_size); + } i += block_size; } @@ -488,12 +512,16 @@ unsafe fn swap_nonoverlapping_bytes(x: *mut u8, y: *mut u8, len: usize) { let rem = len - i; let t = t.as_mut_ptr() as *mut u8; - let x = x.add(i); - let y = y.add(i); - copy_nonoverlapping(x, t, rem); - copy_nonoverlapping(y, x, rem); - copy_nonoverlapping(t, y, rem); + // SAFETY: see previous safety comment. + unsafe { + let x = x.add(i); + let y = y.add(i); + + copy_nonoverlapping(x, t, rem); + copy_nonoverlapping(y, x, rem); + copy_nonoverlapping(t, y, rem); + } } } @@ -540,7 +568,13 @@ unsafe fn swap_nonoverlapping_bytes(x: *mut u8, y: *mut u8, len: usize) { #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub unsafe fn replace(dst: *mut T, mut src: T) -> T { - mem::swap(&mut *dst, &mut src); // cannot overlap + // SAFETY: the caller must guarantee that `dst` is valid to be + // cast to a mutable reference (valid for writes, aligned, initialized), + // and cannot overlap `src` since `dst` must point to a distinct + // allocated object. + unsafe { + mem::swap(&mut *dst, &mut src); // cannot overlap + } src } @@ -658,8 +692,16 @@ pub unsafe fn replace(dst: *mut T, mut src: T) -> T { pub unsafe fn read(src: *const T) -> T { // `copy_nonoverlapping` takes care of debug_assert. let mut tmp = MaybeUninit::::uninit(); - copy_nonoverlapping(src, tmp.as_mut_ptr(), 1); - tmp.assume_init() + // SAFETY: the caller must guarantee that `src` is valid for reads. + // `src` cannot overlap `tmp` because `tmp` was just allocated on + // the stack as a separate allocated object. + // + // Also, since we just wrote a valid value into `tmp`, it is guaranteed + // to be properly initialized. + unsafe { + copy_nonoverlapping(src, tmp.as_mut_ptr(), 1); + tmp.assume_init() + } } /// Reads the value from `src` without moving it. This leaves the @@ -752,8 +794,16 @@ pub unsafe fn read(src: *const T) -> T { pub unsafe fn read_unaligned(src: *const T) -> T { // `copy_nonoverlapping` takes care of debug_assert. let mut tmp = MaybeUninit::::uninit(); - copy_nonoverlapping(src as *const u8, tmp.as_mut_ptr() as *mut u8, mem::size_of::()); - tmp.assume_init() + // SAFETY: the caller must guarantee that `src` is valid for reads. + // `src` cannot overlap `tmp` because `tmp` was just allocated on + // the stack as a separate allocated object. + // + // Also, since we just wrote a valid value into `tmp`, it is guaranteed + // to be properly initialized. + unsafe { + copy_nonoverlapping(src as *const u8, tmp.as_mut_ptr() as *mut u8, mem::size_of::()); + tmp.assume_init() + } } /// Overwrites a memory location with the given value without reading or @@ -847,7 +897,8 @@ pub unsafe fn write(dst: *mut T, src: T) { // Not panicking to keep codegen impact smaller. abort(); } - intrinsics::move_val_init(&mut *dst, src) + // SAFETY: the caller must uphold the safety contract for `move_val_init`. + unsafe { intrinsics::move_val_init(&mut *dst, src) } } /// Overwrites a memory location with the given value without reading or @@ -939,8 +990,13 @@ pub unsafe fn write(dst: *mut T, src: T) { #[inline] #[stable(feature = "ptr_unaligned", since = "1.17.0")] pub unsafe fn write_unaligned(dst: *mut T, src: T) { - // `copy_nonoverlapping` takes care of debug_assert. - copy_nonoverlapping(&src as *const T as *const u8, dst as *mut u8, mem::size_of::()); + // SAFETY: the caller must guarantee that `dst` is valid for writes. + // `dst` cannot overlap `src` because the caller has mutable access + // to `dst` while `src` is owned by this function. + unsafe { + // `copy_nonoverlapping` takes care of debug_assert. + copy_nonoverlapping(&src as *const T as *const u8, dst as *mut u8, mem::size_of::()); + } mem::forget(src); } @@ -1015,7 +1071,8 @@ pub unsafe fn read_volatile(src: *const T) -> T { // Not panicking to keep codegen impact smaller. abort(); } - intrinsics::volatile_load(src) + // SAFETY: the caller must uphold the safety contract for `volatile_load`. + unsafe { intrinsics::volatile_load(src) } } /// Performs a volatile write of a memory location with the given value without @@ -1087,7 +1144,10 @@ pub unsafe fn write_volatile(dst: *mut T, src: T) { // Not panicking to keep codegen impact smaller. abort(); } - intrinsics::volatile_store(dst, src); + // SAFETY: the caller must uphold the safety contract for `volatile_store`. + unsafe { + intrinsics::volatile_store(dst, src); + } } /// Align pointer `p`. @@ -1173,8 +1233,8 @@ pub(crate) unsafe fn align_offset(p: *const T, a: usize) -> usize { } let smoda = stride & a_minus_one; - // a is power-of-two so cannot be 0. stride = 0 is handled above. - let gcdpow = intrinsics::cttz_nonzero(stride).min(intrinsics::cttz_nonzero(a)); + // SAFETY: a is power-of-two so cannot be 0. stride = 0 is handled above. + let gcdpow = unsafe { intrinsics::cttz_nonzero(stride).min(intrinsics::cttz_nonzero(a)) }; let gcd = 1usize << gcdpow; if p as usize & (gcd.wrapping_sub(1)) == 0 { diff --git a/src/libcore/ptr/mut_ptr.rs b/src/libcore/ptr/mut_ptr.rs index 6b5cd9fdb854d..7d4b6339b511f 100644 --- a/src/libcore/ptr/mut_ptr.rs +++ b/src/libcore/ptr/mut_ptr.rs @@ -89,7 +89,9 @@ impl *mut T { #[stable(feature = "ptr_as_ref", since = "1.9.0")] #[inline] pub unsafe fn as_ref<'a>(self) -> Option<&'a T> { - if self.is_null() { None } else { Some(&*self) } + // SAFETY: the caller must guarantee that `self` is valid for a + // reference if it isn't null. + if self.is_null() { None } else { unsafe { Some(&*self) } } } /// Calculates the offset from a pointer. @@ -151,7 +153,10 @@ impl *mut T { where T: Sized, { - intrinsics::offset(self, count) as *mut T + // SAFETY: the caller must uphold the safety contract for `offset`. + // The obtained pointer is valid for writes since the caller must + // guarantee that it points to the same allocated object as `self`. + unsafe { intrinsics::offset(self, count) as *mut T } } /// Calculates the offset from a pointer using wrapping arithmetic. @@ -270,7 +275,9 @@ impl *mut T { #[stable(feature = "ptr_as_ref", since = "1.9.0")] #[inline] pub unsafe fn as_mut<'a>(self) -> Option<&'a mut T> { - if self.is_null() { None } else { Some(&mut *self) } + // SAFETY: the caller must guarantee that `self` is be valid for + // a mutable reference if it isn't null. + if self.is_null() { None } else { unsafe { Some(&mut *self) } } } /// Returns whether two pointers are guaranteed to be equal. @@ -406,7 +413,8 @@ impl *mut T { where T: Sized, { - (self as *const T).offset_from(origin) + // SAFETY: the caller must uphold the safety contract for `offset_from`. + unsafe { (self as *const T).offset_from(origin) } } /// Calculates the distance between two pointers. The returned value is in @@ -518,7 +526,8 @@ impl *mut T { where T: Sized, { - self.offset(count as isize) + // SAFETY: the caller must uphold the safety contract for `offset`. + unsafe { self.offset(count as isize) } } /// Calculates the offset from a pointer (convenience for @@ -581,7 +590,8 @@ impl *mut T { where T: Sized, { - self.offset((count as isize).wrapping_neg()) + // SAFETY: the caller must uphold the safety contract for `offset`. + unsafe { self.offset((count as isize).wrapping_neg()) } } /// Calculates the offset from a pointer using wrapping arithmetic. @@ -710,7 +720,8 @@ impl *mut T { where T: Sized, { - read(self) + // SAFETY: the caller must uphold the safety contract for ``. + unsafe { read(self) } } /// Performs a volatile read of the value from `self` without moving it. This @@ -729,7 +740,8 @@ impl *mut T { where T: Sized, { - read_volatile(self) + // SAFETY: the caller must uphold the safety contract for `read_volatile`. + unsafe { read_volatile(self) } } /// Reads the value from `self` without moving it. This leaves the @@ -746,7 +758,8 @@ impl *mut T { where T: Sized, { - read_unaligned(self) + // SAFETY: the caller must uphold the safety contract for `read_unaligned`. + unsafe { read_unaligned(self) } } /// Copies `count * size_of` bytes from `self` to `dest`. The source @@ -763,7 +776,8 @@ impl *mut T { where T: Sized, { - copy(self, dest, count) + // SAFETY: the caller must uphold the safety contract for `copy`. + unsafe { copy(self, dest, count) } } /// Copies `count * size_of` bytes from `self` to `dest`. The source @@ -780,7 +794,8 @@ impl *mut T { where T: Sized, { - copy_nonoverlapping(self, dest, count) + // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`. + unsafe { copy_nonoverlapping(self, dest, count) } } /// Copies `count * size_of` bytes from `src` to `self`. The source @@ -797,7 +812,8 @@ impl *mut T { where T: Sized, { - copy(src, self, count) + // SAFETY: the caller must uphold the safety contract for `copy`. + unsafe { copy(src, self, count) } } /// Copies `count * size_of` bytes from `src` to `self`. The source @@ -814,7 +830,8 @@ impl *mut T { where T: Sized, { - copy_nonoverlapping(src, self, count) + // SAFETY: the caller must uphold the safety contract for `copy_nonoverlapping`. + unsafe { copy_nonoverlapping(src, self, count) } } /// Executes the destructor (if any) of the pointed-to value. @@ -825,7 +842,8 @@ impl *mut T { #[stable(feature = "pointer_methods", since = "1.26.0")] #[inline] pub unsafe fn drop_in_place(self) { - drop_in_place(self) + // SAFETY: the caller must uphold the safety contract for `drop_in_place`. + unsafe { drop_in_place(self) } } /// Overwrites a memory location with the given value without reading or @@ -840,7 +858,8 @@ impl *mut T { where T: Sized, { - write(self, val) + // SAFETY: the caller must uphold the safety contract for `write`. + unsafe { write(self, val) } } /// Invokes memset on the specified pointer, setting `count * size_of::()` @@ -855,7 +874,8 @@ impl *mut T { where T: Sized, { - write_bytes(self, val, count) + // SAFETY: the caller must uphold the safety contract for `write_bytes`. + unsafe { write_bytes(self, val, count) } } /// Performs a volatile write of a memory location with the given value without @@ -874,7 +894,8 @@ impl *mut T { where T: Sized, { - write_volatile(self, val) + // SAFETY: the caller must uphold the safety contract for `write_volatile`. + unsafe { write_volatile(self, val) } } /// Overwrites a memory location with the given value without reading or @@ -891,7 +912,8 @@ impl *mut T { where T: Sized, { - write_unaligned(self, val) + // SAFETY: the caller must uphold the safety contract for `write_unaligned`. + unsafe { write_unaligned(self, val) } } /// Replaces the value at `self` with `src`, returning the old @@ -906,7 +928,8 @@ impl *mut T { where T: Sized, { - replace(self, src) + // SAFETY: the caller must uphold the safety contract for `replace`. + unsafe { replace(self, src) } } /// Swaps the values at two mutable locations of the same type, without @@ -922,7 +945,8 @@ impl *mut T { where T: Sized, { - swap(self, with) + // SAFETY: the caller must uphold the safety contract for `swap`. + unsafe { swap(self, with) } } /// Computes the offset that needs to be applied to the pointer in order to make it aligned to diff --git a/src/libcore/ptr/non_null.rs b/src/libcore/ptr/non_null.rs index 870364a61dd47..c2d31bfb6a4ee 100644 --- a/src/libcore/ptr/non_null.rs +++ b/src/libcore/ptr/non_null.rs @@ -87,7 +87,8 @@ impl NonNull { #[rustc_const_stable(feature = "const_nonnull_new_unchecked", since = "1.32.0")] #[inline] pub const unsafe fn new_unchecked(ptr: *mut T) -> Self { - NonNull { pointer: ptr as _ } + // SAFETY: the caller must guarantee that `ptr` is non-null. + unsafe { NonNull { pointer: ptr as _ } } } /// Creates a new `NonNull` if `ptr` is non-null. @@ -118,7 +119,9 @@ impl NonNull { #[stable(feature = "nonnull", since = "1.25.0")] #[inline] pub unsafe fn as_ref(&self) -> &T { - &*self.as_ptr() + // SAFETY: the caller must guarantee that `self` meets all the + // requirements for a reference. + unsafe { &*self.as_ptr() } } /// Mutably dereferences the content. @@ -129,7 +132,9 @@ impl NonNull { #[stable(feature = "nonnull", since = "1.25.0")] #[inline] pub unsafe fn as_mut(&mut self) -> &mut T { - &mut *self.as_ptr() + // SAFETY: the caller must guarantee that `self` meets all the + // requirements for a mutable reference. + unsafe { &mut *self.as_ptr() } } /// Casts to a pointer of another type. diff --git a/src/libcore/ptr/unique.rs b/src/libcore/ptr/unique.rs index f58d35f06137d..78647eee3389a 100644 --- a/src/libcore/ptr/unique.rs +++ b/src/libcore/ptr/unique.rs @@ -87,7 +87,8 @@ impl Unique { /// `ptr` must be non-null. #[inline] pub const unsafe fn new_unchecked(ptr: *mut T) -> Self { - Unique { pointer: ptr as _, _marker: PhantomData } + // SAFETY: the caller must guarantee that `ptr` is non-null. + unsafe { Unique { pointer: ptr as _, _marker: PhantomData } } } /// Creates a new `Unique` if `ptr` is non-null. @@ -114,7 +115,9 @@ impl Unique { /// (unbound) lifetime is needed, use `&*my_ptr.as_ptr()`. #[inline] pub unsafe fn as_ref(&self) -> &T { - &*self.as_ptr() + // SAFETY: the caller must guarantee that `self` meets all the + // requirements for a reference. + unsafe { &*self.as_ptr() } } /// Mutably dereferences the content. @@ -124,7 +127,9 @@ impl Unique { /// (unbound) lifetime is needed, use `&mut *my_ptr.as_ptr()`. #[inline] pub unsafe fn as_mut(&mut self) -> &mut T { - &mut *self.as_ptr() + // SAFETY: the caller must guarantee that `self` meets all the + // requirements for a mutable reference. + unsafe { &mut *self.as_ptr() } } /// Casts to a pointer of another type. diff --git a/src/libcore/slice/mod.rs b/src/libcore/slice/mod.rs index 6a50cdbc1d9fb..71d63a7115dbe 100644 --- a/src/libcore/slice/mod.rs +++ b/src/libcore/slice/mod.rs @@ -310,7 +310,8 @@ impl [T] { where I: SliceIndex, { - index.get_unchecked(self) + // SAFETY: the caller must uphold the safety requirements for `get_unchecked`. + unsafe { index.get_unchecked(self) } } /// Returns a mutable reference to an element or subslice, without doing @@ -341,7 +342,8 @@ impl [T] { where I: SliceIndex, { - index.get_unchecked_mut(self) + // SAFETY: the caller must uphold the safety requirements for `get_unchecked_mut`. + unsafe { index.get_unchecked_mut(self) } } /// Returns a raw pointer to the slice's buffer. @@ -2519,18 +2521,21 @@ impl [T] { // First, find at what point do we split between the first and 2nd slice. Easy with // ptr.align_offset. let ptr = self.as_ptr(); - let offset = crate::ptr::align_offset(ptr, mem::align_of::()); + let offset = unsafe { crate::ptr::align_offset(ptr, mem::align_of::()) }; if offset > self.len() { (self, &[], &[]) } else { let (left, rest) = self.split_at(offset); - // now `rest` is definitely aligned, so `from_raw_parts_mut` below is okay let (us_len, ts_len) = rest.align_to_offsets::(); - ( - left, - from_raw_parts(rest.as_ptr() as *const U, us_len), - from_raw_parts(rest.as_ptr().add(rest.len() - ts_len), ts_len), - ) + // SAFETY: now `rest` is definitely aligned, so `from_raw_parts` below is okay, + // since the caller guarantees that we can transmute `T` to `U` safely. + unsafe { + ( + left, + from_raw_parts(rest.as_ptr() as *const U, us_len), + from_raw_parts(rest.as_ptr().add(rest.len() - ts_len), ts_len), + ) + } } } @@ -2575,21 +2580,23 @@ impl [T] { // First, find at what point do we split between the first and 2nd slice. Easy with // ptr.align_offset. let ptr = self.as_ptr(); - let offset = crate::ptr::align_offset(ptr, mem::align_of::()); + let offset = unsafe { crate::ptr::align_offset(ptr, mem::align_of::()) }; if offset > self.len() { (self, &mut [], &mut []) } else { let (left, rest) = self.split_at_mut(offset); - // now `rest` is definitely aligned, so `from_raw_parts_mut` below is okay let (us_len, ts_len) = rest.align_to_offsets::(); let rest_len = rest.len(); let mut_ptr = rest.as_mut_ptr(); // We can't use `rest` again after this, that would invalidate its alias `mut_ptr`! - ( - left, - from_raw_parts_mut(mut_ptr as *mut U, us_len), - from_raw_parts_mut(mut_ptr.add(rest_len - ts_len), ts_len), - ) + // SAFETY: see comments for `align_to`. + unsafe { + ( + left, + from_raw_parts_mut(mut_ptr as *mut U, us_len), + from_raw_parts_mut(mut_ptr.add(rest_len - ts_len), ts_len), + ) + } } } @@ -2914,12 +2921,18 @@ impl SliceIndex<[T]> for usize { #[inline] unsafe fn get_unchecked(self, slice: &[T]) -> &T { - &*slice.as_ptr().add(self) + // SAFETY: `slice` cannot be longer than `isize::MAX` and + // the caller guarantees that `self` is in bounds of `slice` + // so `self` cannot overflow an `isize`, so the call to `add` is safe. + // The obtained pointer comes from a reference which is guaranteed + // to be valid. + unsafe { &*slice.as_ptr().add(self) } } #[inline] unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut T { - &mut *slice.as_mut_ptr().add(self) + // SAFETY: see comments for `get_unchecked` above. + unsafe { &mut *slice.as_mut_ptr().add(self) } } #[inline] @@ -2959,12 +2972,18 @@ impl SliceIndex<[T]> for ops::Range { #[inline] unsafe fn get_unchecked(self, slice: &[T]) -> &[T] { - from_raw_parts(slice.as_ptr().add(self.start), self.end - self.start) + // SAFETY: `slice` cannot be longer than `isize::MAX` and + // the caller guarantees that `self` is in bounds of `slice` + // so `self` cannot overflow an `isize`, so the call to `add` is safe. + // Also, since the caller guarantees that `self` is in bounds of `slice`, + // `from_raw_parts` will give a subslice of `slice` which is always safe. + unsafe { from_raw_parts(slice.as_ptr().add(self.start), self.end - self.start) } } #[inline] unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] { - from_raw_parts_mut(slice.as_mut_ptr().add(self.start), self.end - self.start) + // SAFETY: see comments for `get_unchecked` above. + unsafe { from_raw_parts_mut(slice.as_mut_ptr().add(self.start), self.end - self.start) } } #[inline] @@ -3004,12 +3023,14 @@ impl SliceIndex<[T]> for ops::RangeTo { #[inline] unsafe fn get_unchecked(self, slice: &[T]) -> &[T] { - (0..self.end).get_unchecked(slice) + // SAFETY: the caller has to uphold the safety contract for `get_unchecked`. + unsafe { (0..self.end).get_unchecked(slice) } } #[inline] unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] { - (0..self.end).get_unchecked_mut(slice) + // SAFETY: the caller has to uphold the safety contract for `get_unchecked_mut`. + unsafe { (0..self.end).get_unchecked_mut(slice) } } #[inline] @@ -3039,12 +3060,14 @@ impl SliceIndex<[T]> for ops::RangeFrom { #[inline] unsafe fn get_unchecked(self, slice: &[T]) -> &[T] { - (self.start..slice.len()).get_unchecked(slice) + // SAFETY: the caller has to uphold the safety contract for `get_unchecked`. + unsafe { (self.start..slice.len()).get_unchecked(slice) } } #[inline] unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] { - (self.start..slice.len()).get_unchecked_mut(slice) + // SAFETY: the caller has to uphold the safety contract for `get_unchecked_mut`. + unsafe { (self.start..slice.len()).get_unchecked_mut(slice) } } #[inline] @@ -3113,12 +3136,14 @@ impl SliceIndex<[T]> for ops::RangeInclusive { #[inline] unsafe fn get_unchecked(self, slice: &[T]) -> &[T] { - (*self.start()..self.end() + 1).get_unchecked(slice) + // SAFETY: the caller has to uphold the safety contract for `get_unchecked`. + unsafe { (*self.start()..self.end() + 1).get_unchecked(slice) } } #[inline] unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] { - (*self.start()..self.end() + 1).get_unchecked_mut(slice) + // SAFETY: the caller has to uphold the safety contract for `get_unchecked_mut`. + unsafe { (*self.start()..self.end() + 1).get_unchecked_mut(slice) } } #[inline] @@ -3154,12 +3179,14 @@ impl SliceIndex<[T]> for ops::RangeToInclusive { #[inline] unsafe fn get_unchecked(self, slice: &[T]) -> &[T] { - (0..=self.end).get_unchecked(slice) + // SAFETY: the caller has to uphold the safety contract for `get_unchecked`. + unsafe { (0..=self.end).get_unchecked(slice) } } #[inline] unsafe fn get_unchecked_mut(self, slice: &mut [T]) -> &mut [T] { - (0..=self.end).get_unchecked_mut(slice) + // SAFETY: the caller has to uphold the safety contract for `get_unchecked_mut`. + unsafe { (0..=self.end).get_unchecked_mut(slice) } } #[inline] @@ -3308,7 +3335,9 @@ macro_rules! iterator { self.ptr.as_ptr() } else { let old = self.ptr.as_ptr(); - self.ptr = NonNull::new_unchecked(self.ptr.as_ptr().offset(offset)); + // SAFETY: the caller guarantees that `offset` doesn't exceed `self.len()`, + // so this new pointer is inside `self` and thus guaranteed to be non-null. + self.ptr = unsafe { NonNull::new_unchecked(self.ptr.as_ptr().offset(offset)) }; old } } @@ -3322,7 +3351,10 @@ macro_rules! iterator { zst_shrink!(self, offset); self.ptr.as_ptr() } else { - self.end = self.end.offset(-offset); + // SAFETY: the caller guarantees that `offset` doesn't exceed `self.len()`, + // which is guaranteed to not overflow an `isize`. Also, the resulting pointer + // is in bounds of `slice`, which fulfills the other requirements for `offset`. + self.end = unsafe { self.end.offset(-offset) }; self.end } } @@ -4640,7 +4672,11 @@ impl FusedIterator for Windows<'_, T> {} #[doc(hidden)] unsafe impl<'a, T> TrustedRandomAccess for Windows<'a, T> { unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] { - from_raw_parts(self.v.as_ptr().add(i), self.size) + // SAFETY: since the caller guarantees that `i` is in bounds, + // which means that `i` cannot overflow an `isize`, and the + // slice created by `from_raw_parts` is a subslice of `self.v` + // thus is guaranteed to be valid for the lifetime `'a` of `self.v`. + unsafe { from_raw_parts(self.v.as_ptr().add(i), self.size) } } fn may_have_side_effect() -> bool { false @@ -4784,7 +4820,14 @@ unsafe impl<'a, T> TrustedRandomAccess for Chunks<'a, T> { None => self.v.len(), Some(end) => cmp::min(end, self.v.len()), }; - from_raw_parts(self.v.as_ptr().add(start), end - start) + // SAFETY: the caller guarantees that `i` is in bounds, + // which means that `start` must be in bounds of the + // underlying `self.v` slice, and we made sure that `end` + // is also in bounds of `self.v`. Thus, `start` cannot overflow + // an `isize`, and the slice constructed by `from_raw_parts` + // is a subslice of `self.v` which is guaranteed to be valid + // for the lifetime `'a` of `self.v`. + unsafe { from_raw_parts(self.v.as_ptr().add(start), end - start) } } fn may_have_side_effect() -> bool { false @@ -4926,7 +4969,8 @@ unsafe impl<'a, T> TrustedRandomAccess for ChunksMut<'a, T> { None => self.v.len(), Some(end) => cmp::min(end, self.v.len()), }; - from_raw_parts_mut(self.v.as_mut_ptr().add(start), end - start) + // SAFETY: see comments for `Chunks::get_unchecked`. + unsafe { from_raw_parts_mut(self.v.as_mut_ptr().add(start), end - start) } } fn may_have_side_effect() -> bool { false @@ -5063,7 +5107,8 @@ impl FusedIterator for ChunksExact<'_, T> {} unsafe impl<'a, T> TrustedRandomAccess for ChunksExact<'a, T> { unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] { let start = i * self.chunk_size; - from_raw_parts(self.v.as_ptr().add(start), self.chunk_size) + // SAFETY: mostly identical to `Chunks::get_unchecked`. + unsafe { from_raw_parts(self.v.as_ptr().add(start), self.chunk_size) } } fn may_have_side_effect() -> bool { false @@ -5197,7 +5242,8 @@ impl FusedIterator for ChunksExactMut<'_, T> {} unsafe impl<'a, T> TrustedRandomAccess for ChunksExactMut<'a, T> { unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] { let start = i * self.chunk_size; - from_raw_parts_mut(self.v.as_mut_ptr().add(start), self.chunk_size) + // SAFETY: see comments for `ChunksExactMut::get_unchecked`. + unsafe { from_raw_parts_mut(self.v.as_mut_ptr().add(start), self.chunk_size) } } fn may_have_side_effect() -> bool { false @@ -5344,7 +5390,8 @@ unsafe impl<'a, T> TrustedRandomAccess for RChunks<'a, T> { None => 0, Some(start) => start, }; - from_raw_parts(self.v.as_ptr().add(start), end - start) + // SAFETY: mostly identical to `Chunks::get_unchecked`. + unsafe { from_raw_parts(self.v.as_ptr().add(start), end - start) } } fn may_have_side_effect() -> bool { false @@ -5489,7 +5536,8 @@ unsafe impl<'a, T> TrustedRandomAccess for RChunksMut<'a, T> { None => 0, Some(start) => start, }; - from_raw_parts_mut(self.v.as_mut_ptr().add(start), end - start) + // SAFETY: see comments for `RChunks::get_unchecked`. + unsafe { from_raw_parts_mut(self.v.as_mut_ptr().add(start), end - start) } } fn may_have_side_effect() -> bool { false @@ -5630,7 +5678,8 @@ unsafe impl<'a, T> TrustedRandomAccess for RChunksExact<'a, T> { unsafe fn get_unchecked(&mut self, i: usize) -> &'a [T] { let end = self.v.len() - i * self.chunk_size; let start = end - self.chunk_size; - from_raw_parts(self.v.as_ptr().add(start), self.chunk_size) + // SAFETY: mostmy identical to `Chunks::get_unchecked`. + unsafe { from_raw_parts(self.v.as_ptr().add(start), self.chunk_size) } } fn may_have_side_effect() -> bool { false @@ -5769,7 +5818,8 @@ unsafe impl<'a, T> TrustedRandomAccess for RChunksExactMut<'a, T> { unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut [T] { let end = self.v.len() - i * self.chunk_size; let start = end - self.chunk_size; - from_raw_parts_mut(self.v.as_mut_ptr().add(start), self.chunk_size) + // SAFETY: see comments for `RChunksExact::get_unchecked`. + unsafe { from_raw_parts_mut(self.v.as_mut_ptr().add(start), self.chunk_size) } } fn may_have_side_effect() -> bool { false @@ -5865,7 +5915,8 @@ pub unsafe fn from_raw_parts<'a, T>(data: *const T, len: usize) -> &'a [T] { mem::size_of::().saturating_mul(len) <= isize::MAX as usize, "attempt to create slice covering at least half the address space" ); - &*ptr::slice_from_raw_parts(data, len) + // SAFETY: the caller must uphold the safety contract for `from_raw_parts`. + unsafe { &*ptr::slice_from_raw_parts(data, len) } } /// Performs the same functionality as [`from_raw_parts`], except that a @@ -5905,7 +5956,8 @@ pub unsafe fn from_raw_parts_mut<'a, T>(data: *mut T, len: usize) -> &'a mut [T] mem::size_of::().saturating_mul(len) <= isize::MAX as usize, "attempt to create slice covering at least half the address space" ); - &mut *ptr::slice_from_raw_parts_mut(data, len) + // SAFETY: the caller must uphold the safety contract for `from_raw_parts_mut`. + unsafe { &mut *ptr::slice_from_raw_parts_mut(data, len) } } /// Converts a reference to T into a slice of length 1 (without copying). @@ -6181,7 +6233,11 @@ impl_marker_for!(BytewiseEquality, #[doc(hidden)] unsafe impl<'a, T> TrustedRandomAccess for Iter<'a, T> { unsafe fn get_unchecked(&mut self, i: usize) -> &'a T { - &*self.ptr.as_ptr().add(i) + // SAFETY: the caller must guarantee that `i` is in bounds + // of the underlying slice, so `i` cannot overflow an `isize`, + // and the returned references is guaranteed to refer to an element + // of the slice and thus guaranteed to be valid. + unsafe { &*self.ptr.as_ptr().add(i) } } fn may_have_side_effect() -> bool { false @@ -6191,7 +6247,8 @@ unsafe impl<'a, T> TrustedRandomAccess for Iter<'a, T> { #[doc(hidden)] unsafe impl<'a, T> TrustedRandomAccess for IterMut<'a, T> { unsafe fn get_unchecked(&mut self, i: usize) -> &'a mut T { - &mut *self.ptr.as_ptr().add(i) + // SAFETY: see comments for `Iter::get_unchecked`. + unsafe { &mut *self.ptr.as_ptr().add(i) } } fn may_have_side_effect() -> bool { false diff --git a/src/libcore/slice/rotate.rs b/src/libcore/slice/rotate.rs index f73e14f27e092..a89596b15ef94 100644 --- a/src/libcore/slice/rotate.rs +++ b/src/libcore/slice/rotate.rs @@ -1,3 +1,5 @@ +// ignore-tidy-undocumented-unsafe + use crate::cmp; use crate::mem::{self, MaybeUninit}; use crate::ptr; @@ -77,9 +79,9 @@ pub unsafe fn ptr_rotate(mut left: usize, mut mid: *mut T, mut right: usize) // the way until about `left + right == 32`, but the worst case performance breaks even // around 16. 24 was chosen as middle ground. If the size of `T` is larger than 4 // `usize`s, this algorithm also outperforms other algorithms. - let x = mid.sub(left); + let x = unsafe { mid.sub(left) }; // beginning of first round - let mut tmp: T = x.read(); + let mut tmp: T = unsafe { x.read() }; let mut i = right; // `gcd` can be found before hand by calculating `gcd(left + right, right)`, // but it is faster to do one loop which calculates the gcd as a side effect, then @@ -90,7 +92,7 @@ pub unsafe fn ptr_rotate(mut left: usize, mut mid: *mut T, mut right: usize) // the very end. This is possibly due to the fact that swapping or replacing temporaries // uses only one memory address in the loop instead of needing to manage two. loop { - tmp = x.add(i).replace(tmp); + tmp = unsafe { x.add(i).replace(tmp) }; // instead of incrementing `i` and then checking if it is outside the bounds, we // check if `i` will go outside the bounds on the next increment. This prevents // any wrapping of pointers or `usize`. @@ -98,7 +100,7 @@ pub unsafe fn ptr_rotate(mut left: usize, mut mid: *mut T, mut right: usize) i -= left; if i == 0 { // end of first round - x.write(tmp); + unsafe { x.write(tmp) }; break; } // this conditional must be here if `left + right >= 15` @@ -111,14 +113,14 @@ pub unsafe fn ptr_rotate(mut left: usize, mut mid: *mut T, mut right: usize) } // finish the chunk with more rounds for start in 1..gcd { - tmp = x.add(start).read(); + tmp = unsafe { x.add(start).read() }; i = start + right; loop { - tmp = x.add(i).replace(tmp); + tmp = unsafe { x.add(i).replace(tmp) }; if i >= left { i -= left; if i == start { - x.add(start).write(tmp); + unsafe { x.add(start).write(tmp) }; break; } } else { @@ -133,15 +135,19 @@ pub unsafe fn ptr_rotate(mut left: usize, mut mid: *mut T, mut right: usize) // The `[T; 0]` here is to ensure this is appropriately aligned for T let mut rawarray = MaybeUninit::<(BufType, [T; 0])>::uninit(); let buf = rawarray.as_mut_ptr() as *mut T; - let dim = mid.sub(left).add(right); + let dim = unsafe { mid.sub(left).add(right) }; if left <= right { - ptr::copy_nonoverlapping(mid.sub(left), buf, left); - ptr::copy(mid, mid.sub(left), right); - ptr::copy_nonoverlapping(buf, dim, left); + unsafe { + ptr::copy_nonoverlapping(mid.sub(left), buf, left); + ptr::copy(mid, mid.sub(left), right); + ptr::copy_nonoverlapping(buf, dim, left); + } } else { - ptr::copy_nonoverlapping(mid, buf, right); - ptr::copy(mid.sub(left), dim, left); - ptr::copy_nonoverlapping(buf, mid.sub(left), right); + unsafe { + ptr::copy_nonoverlapping(mid, buf, right); + ptr::copy(mid.sub(left), dim, left); + ptr::copy_nonoverlapping(buf, mid.sub(left), right); + } } return; } else if left >= right { @@ -150,8 +156,10 @@ pub unsafe fn ptr_rotate(mut left: usize, mut mid: *mut T, mut right: usize) // of this algorithm would be, and swapping using that last chunk instead of swapping // adjacent chunks like this algorithm is doing, but this way is still faster. loop { - ptr::swap_nonoverlapping(mid.sub(right), mid, right); - mid = mid.sub(right); + unsafe { + ptr::swap_nonoverlapping(mid.sub(right), mid, right); + mid = mid.sub(right); + } left -= right; if left < right { break; @@ -160,8 +168,10 @@ pub unsafe fn ptr_rotate(mut left: usize, mut mid: *mut T, mut right: usize) } else { // Algorithm 3, `left < right` loop { - ptr::swap_nonoverlapping(mid.sub(left), mid, left); - mid = mid.add(left); + unsafe { + ptr::swap_nonoverlapping(mid.sub(left), mid, left); + mid = mid.add(left); + } right -= left; if right < left { break; diff --git a/src/libcore/str/mod.rs b/src/libcore/str/mod.rs index 6c4b28499a60b..0014501d2c4d0 100644 --- a/src/libcore/str/mod.rs +++ b/src/libcore/str/mod.rs @@ -419,7 +419,11 @@ pub fn from_utf8_mut(v: &mut [u8]) -> Result<&mut str, Utf8Error> { #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub unsafe fn from_utf8_unchecked(v: &[u8]) -> &str { - &*(v as *const [u8] as *const str) + // SAFETY: the caller must guarantee that the bytes `v` + // are valid UTF-8, thus the cast to `*const str` is safe. + // Also, the pointer dereference is safe because that pointer + // comes from a reference which is guaranteed to be valid for reads. + unsafe { &*(v as *const [u8] as *const str) } } /// Converts a slice of bytes to a string slice without checking @@ -444,7 +448,11 @@ pub unsafe fn from_utf8_unchecked(v: &[u8]) -> &str { #[inline] #[stable(feature = "str_mut_extras", since = "1.20.0")] pub unsafe fn from_utf8_unchecked_mut(v: &mut [u8]) -> &mut str { - &mut *(v as *mut [u8] as *mut str) + // SAFETY: the caller must guarantee that the bytes `v` + // are valid UTF-8, thus the cast to `*mut str` is safe. + // Also, the pointer dereference is safe because that pointer + // comes from a reference which is guaranteed to be valid for writes. + unsafe { &mut *(v as *mut [u8] as *mut str) } } #[stable(feature = "rust1", since = "1.0.0")] @@ -867,7 +875,9 @@ unsafe impl TrustedLen for Bytes<'_> {} #[doc(hidden)] unsafe impl TrustedRandomAccess for Bytes<'_> { unsafe fn get_unchecked(&mut self, i: usize) -> u8 { - self.0.get_unchecked(i) + // SAFETY: the caller must uphold the safety contract + // for `TrustedRandomAccess::get_unchecked`. + unsafe { self.0.get_unchecked(i) } } fn may_have_side_effect() -> bool { false @@ -1904,15 +1914,27 @@ mod traits { } #[inline] unsafe fn get_unchecked(self, slice: &str) -> &Self::Output { - let ptr = slice.as_ptr().add(self.start); + // SAFETY: the caller guarantees that `self` is in bounds of `slice` + // which satisfies all the conditions for `add`. + let ptr = unsafe { slice.as_ptr().add(self.start) }; let len = self.end - self.start; - super::from_utf8_unchecked(slice::from_raw_parts(ptr, len)) + // SAFETY: as the caller guarantees that `self` is in bounds of `slice`, + // we can safely construct a subslice with `from_raw_parts` and use it + // since we return a shared thus immutable reference. + // The call to `from_utf8_unchecked` is safe since the data comes from + // a `str` which is guaranteed to be valid utf8, since the caller + // must guarantee that `self.start` and `self.end` are char boundaries. + unsafe { super::from_utf8_unchecked(slice::from_raw_parts(ptr, len)) } } #[inline] unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output { - let ptr = slice.as_mut_ptr().add(self.start); + // SAFETY: see comments for `get_unchecked`. + let ptr = unsafe { slice.as_mut_ptr().add(self.start) }; let len = self.end - self.start; - super::from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr, len)) + // SAFETY: mostly identical to the comments for `get_unchecked`, except that we + // can return a mutable reference since the caller passed a mutable reference + // and is thus guaranteed to have exclusive write access to `slice`. + unsafe { super::from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr, len)) } } #[inline] fn index(self, slice: &str) -> &Self::Output { @@ -1974,12 +1996,21 @@ mod traits { #[inline] unsafe fn get_unchecked(self, slice: &str) -> &Self::Output { let ptr = slice.as_ptr(); - super::from_utf8_unchecked(slice::from_raw_parts(ptr, self.end)) + // SAFETY: as the caller guarantees that `self` is in bounds of `slice`, + // we can safely construct a subslice with `from_raw_parts` and use it + // since we return a shared thus immutable reference. + // The call to `from_utf8_unchecked` is safe since the data comes from + // a `str` which is guaranteed to be valid utf8, since the caller + // must guarantee that `self.end` is a char boundary. + unsafe { super::from_utf8_unchecked(slice::from_raw_parts(ptr, self.end)) } } #[inline] unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output { let ptr = slice.as_mut_ptr(); - super::from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr, self.end)) + // SAFETY: mostly identical to `get_unchecked`, except that we can safely + // return a mutable reference since the caller passed a mutable reference + // and is thus guaranteed to have exclusive write access to `slice`. + unsafe { super::from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr, self.end)) } } #[inline] fn index(self, slice: &str) -> &Self::Output { @@ -2036,15 +2067,27 @@ mod traits { } #[inline] unsafe fn get_unchecked(self, slice: &str) -> &Self::Output { - let ptr = slice.as_ptr().add(self.start); + // SAFETY: the caller guarantees that `self` is in bounds of `slice` + // which satisfies all the conditions for `add`. + let ptr = unsafe { slice.as_ptr().add(self.start) }; let len = slice.len() - self.start; - super::from_utf8_unchecked(slice::from_raw_parts(ptr, len)) + // SAFETY: as the caller guarantees that `self` is in bounds of `slice`, + // we can safely construct a subslice with `from_raw_parts` and use it + // since we return a shared thus immutable reference. + // The call to `from_utf8_unchecked` is safe since the data comes from + // a `str` which is guaranteed to be valid utf8, since the caller + // must guarantee that `self.start` is a char boundary. + unsafe { super::from_utf8_unchecked(slice::from_raw_parts(ptr, len)) } } #[inline] unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output { - let ptr = slice.as_mut_ptr().add(self.start); + // SAFETY: identical to `get_unchecked`. + let ptr = unsafe { slice.as_mut_ptr().add(self.start) }; let len = slice.len() - self.start; - super::from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr, len)) + // SAFETY: mostly identical to `get_unchecked`, except that we can safely + // return a mutable reference since the caller passed a mutable reference + // and is thus guaranteed to have exclusive write access to `slice`. + unsafe { super::from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr, len)) } } #[inline] fn index(self, slice: &str) -> &Self::Output { @@ -2099,11 +2142,13 @@ mod traits { } #[inline] unsafe fn get_unchecked(self, slice: &str) -> &Self::Output { - (*self.start()..self.end() + 1).get_unchecked(slice) + // SAFETY: the caller must uphold the safety contract for `get_unchecked`. + unsafe { (*self.start()..self.end() + 1).get_unchecked(slice) } } #[inline] unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output { - (*self.start()..self.end() + 1).get_unchecked_mut(slice) + // SAFETY: the caller must uphold the safety contract for `get_unchecked_mut`. + unsafe { (*self.start()..self.end() + 1).get_unchecked_mut(slice) } } #[inline] fn index(self, slice: &str) -> &Self::Output { @@ -2148,11 +2193,13 @@ mod traits { } #[inline] unsafe fn get_unchecked(self, slice: &str) -> &Self::Output { - (..self.end + 1).get_unchecked(slice) + // SAFETY: the caller must uphold the safety contract for `get_unchecked`. + unsafe { (..self.end + 1).get_unchecked(slice) } } #[inline] unsafe fn get_unchecked_mut(self, slice: &mut str) -> &mut Self::Output { - (..self.end + 1).get_unchecked_mut(slice) + // SAFETY: the caller must uphold the safety contract for `get_unchecked_mut`. + unsafe { (..self.end + 1).get_unchecked_mut(slice) } } #[inline] fn index(self, slice: &str) -> &Self::Output { @@ -2373,7 +2420,11 @@ impl str { #[stable(feature = "str_mut_extras", since = "1.20.0")] #[inline(always)] pub unsafe fn as_bytes_mut(&mut self) -> &mut [u8] { - &mut *(self as *mut str as *mut [u8]) + // SAFETY: the cast from `&str` to `&[u8]` is safe since `str` + // has the same layout as `&[u8]` (only libstd can make this guarantee). + // The pointer dereference is safe since it comes from a mutable reference which + // is guaranteed to be valid for writes. + unsafe { &mut *(self as *mut str as *mut [u8]) } } /// Converts a string slice to a raw pointer. @@ -2509,7 +2560,8 @@ impl str { #[stable(feature = "str_checked_slicing", since = "1.20.0")] #[inline] pub unsafe fn get_unchecked>(&self, i: I) -> &I::Output { - i.get_unchecked(self) + // SAFETY: the caller must uphold the safety contract for `get_unchecked`. + unsafe { i.get_unchecked(self) } } /// Returns a mutable, unchecked subslice of `str`. @@ -2541,7 +2593,8 @@ impl str { #[stable(feature = "str_checked_slicing", since = "1.20.0")] #[inline] pub unsafe fn get_unchecked_mut>(&mut self, i: I) -> &mut I::Output { - i.get_unchecked_mut(self) + // SAFETY: the caller must uphold the safety contract for `get_unchecked_mut`. + unsafe { i.get_unchecked_mut(self) } } /// Creates a string slice from another string slice, bypassing safety @@ -2591,7 +2644,8 @@ impl str { #[rustc_deprecated(since = "1.29.0", reason = "use `get_unchecked(begin..end)` instead")] #[inline] pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str { - (begin..end).get_unchecked(self) + // SAFETY: the caller must uphold the safety contract for `get_unchecked`. + unsafe { (begin..end).get_unchecked(self) } } /// Creates a string slice from another string slice, bypassing safety @@ -2622,7 +2676,8 @@ impl str { #[rustc_deprecated(since = "1.29.0", reason = "use `get_unchecked_mut(begin..end)` instead")] #[inline] pub unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str { - (begin..end).get_unchecked_mut(self) + // SAFETY: the caller must uphold the safety contract for `get_unchecked_mut`. + unsafe { (begin..end).get_unchecked_mut(self) } } /// Divide one string slice into two at an index. diff --git a/src/libcore/sync/atomic.rs b/src/libcore/sync/atomic.rs index 1cd68f2881b7c..fcae6c86774f2 100644 --- a/src/libcore/sync/atomic.rs +++ b/src/libcore/sync/atomic.rs @@ -2335,35 +2335,44 @@ fn strongest_failure_ordering(order: Ordering) -> Ordering { #[inline] unsafe fn atomic_store(dst: *mut T, val: T, order: Ordering) { - match order { - Release => intrinsics::atomic_store_rel(dst, val), - Relaxed => intrinsics::atomic_store_relaxed(dst, val), - SeqCst => intrinsics::atomic_store(dst, val), - Acquire => panic!("there is no such thing as an acquire store"), - AcqRel => panic!("there is no such thing as an acquire/release store"), + // SAFETY: the caller must uphold the safety contract for `atomic_store`. + unsafe { + match order { + Release => intrinsics::atomic_store_rel(dst, val), + Relaxed => intrinsics::atomic_store_relaxed(dst, val), + SeqCst => intrinsics::atomic_store(dst, val), + Acquire => panic!("there is no such thing as an acquire store"), + AcqRel => panic!("there is no such thing as an acquire/release store"), + } } } #[inline] unsafe fn atomic_load(dst: *const T, order: Ordering) -> T { - match order { - Acquire => intrinsics::atomic_load_acq(dst), - Relaxed => intrinsics::atomic_load_relaxed(dst), - SeqCst => intrinsics::atomic_load(dst), - Release => panic!("there is no such thing as a release load"), - AcqRel => panic!("there is no such thing as an acquire/release load"), + // SAFETY: the caller must uphold the safety contract for `atomic_load`. + unsafe { + match order { + Acquire => intrinsics::atomic_load_acq(dst), + Relaxed => intrinsics::atomic_load_relaxed(dst), + SeqCst => intrinsics::atomic_load(dst), + Release => panic!("there is no such thing as a release load"), + AcqRel => panic!("there is no such thing as an acquire/release load"), + } } } #[inline] #[cfg(target_has_atomic = "8")] unsafe fn atomic_swap(dst: *mut T, val: T, order: Ordering) -> T { - match order { - Acquire => intrinsics::atomic_xchg_acq(dst, val), - Release => intrinsics::atomic_xchg_rel(dst, val), - AcqRel => intrinsics::atomic_xchg_acqrel(dst, val), - Relaxed => intrinsics::atomic_xchg_relaxed(dst, val), - SeqCst => intrinsics::atomic_xchg(dst, val), + // SAFETY: the caller must uphold the safety contract for `atomic_swap`. + unsafe { + match order { + Acquire => intrinsics::atomic_xchg_acq(dst, val), + Release => intrinsics::atomic_xchg_rel(dst, val), + AcqRel => intrinsics::atomic_xchg_acqrel(dst, val), + Relaxed => intrinsics::atomic_xchg_relaxed(dst, val), + SeqCst => intrinsics::atomic_xchg(dst, val), + } } } @@ -2371,12 +2380,15 @@ unsafe fn atomic_swap(dst: *mut T, val: T, order: Ordering) -> T { #[inline] #[cfg(target_has_atomic = "8")] unsafe fn atomic_add(dst: *mut T, val: T, order: Ordering) -> T { - match order { - Acquire => intrinsics::atomic_xadd_acq(dst, val), - Release => intrinsics::atomic_xadd_rel(dst, val), - AcqRel => intrinsics::atomic_xadd_acqrel(dst, val), - Relaxed => intrinsics::atomic_xadd_relaxed(dst, val), - SeqCst => intrinsics::atomic_xadd(dst, val), + // SAFETY: the caller must uphold the safety contract for `atomic_add`. + unsafe { + match order { + Acquire => intrinsics::atomic_xadd_acq(dst, val), + Release => intrinsics::atomic_xadd_rel(dst, val), + AcqRel => intrinsics::atomic_xadd_acqrel(dst, val), + Relaxed => intrinsics::atomic_xadd_relaxed(dst, val), + SeqCst => intrinsics::atomic_xadd(dst, val), + } } } @@ -2384,12 +2396,15 @@ unsafe fn atomic_add(dst: *mut T, val: T, order: Ordering) -> T { #[inline] #[cfg(target_has_atomic = "8")] unsafe fn atomic_sub(dst: *mut T, val: T, order: Ordering) -> T { - match order { - Acquire => intrinsics::atomic_xsub_acq(dst, val), - Release => intrinsics::atomic_xsub_rel(dst, val), - AcqRel => intrinsics::atomic_xsub_acqrel(dst, val), - Relaxed => intrinsics::atomic_xsub_relaxed(dst, val), - SeqCst => intrinsics::atomic_xsub(dst, val), + // SAFETY: the caller must uphold the safety contract for `atomic_sub`. + unsafe { + match order { + Acquire => intrinsics::atomic_xsub_acq(dst, val), + Release => intrinsics::atomic_xsub_rel(dst, val), + AcqRel => intrinsics::atomic_xsub_acqrel(dst, val), + Relaxed => intrinsics::atomic_xsub_relaxed(dst, val), + SeqCst => intrinsics::atomic_xsub(dst, val), + } } } @@ -2402,19 +2417,22 @@ unsafe fn atomic_compare_exchange( success: Ordering, failure: Ordering, ) -> Result { - let (val, ok) = match (success, failure) { - (Acquire, Acquire) => intrinsics::atomic_cxchg_acq(dst, old, new), - (Release, Relaxed) => intrinsics::atomic_cxchg_rel(dst, old, new), - (AcqRel, Acquire) => intrinsics::atomic_cxchg_acqrel(dst, old, new), - (Relaxed, Relaxed) => intrinsics::atomic_cxchg_relaxed(dst, old, new), - (SeqCst, SeqCst) => intrinsics::atomic_cxchg(dst, old, new), - (Acquire, Relaxed) => intrinsics::atomic_cxchg_acq_failrelaxed(dst, old, new), - (AcqRel, Relaxed) => intrinsics::atomic_cxchg_acqrel_failrelaxed(dst, old, new), - (SeqCst, Relaxed) => intrinsics::atomic_cxchg_failrelaxed(dst, old, new), - (SeqCst, Acquire) => intrinsics::atomic_cxchg_failacq(dst, old, new), - (_, AcqRel) => panic!("there is no such thing as an acquire/release failure ordering"), - (_, Release) => panic!("there is no such thing as a release failure ordering"), - _ => panic!("a failure ordering can't be stronger than a success ordering"), + // SAFETY: the caller must uphold the safety contract for `atomic_compare_exchange`. + let (val, ok) = unsafe { + match (success, failure) { + (Acquire, Acquire) => intrinsics::atomic_cxchg_acq(dst, old, new), + (Release, Relaxed) => intrinsics::atomic_cxchg_rel(dst, old, new), + (AcqRel, Acquire) => intrinsics::atomic_cxchg_acqrel(dst, old, new), + (Relaxed, Relaxed) => intrinsics::atomic_cxchg_relaxed(dst, old, new), + (SeqCst, SeqCst) => intrinsics::atomic_cxchg(dst, old, new), + (Acquire, Relaxed) => intrinsics::atomic_cxchg_acq_failrelaxed(dst, old, new), + (AcqRel, Relaxed) => intrinsics::atomic_cxchg_acqrel_failrelaxed(dst, old, new), + (SeqCst, Relaxed) => intrinsics::atomic_cxchg_failrelaxed(dst, old, new), + (SeqCst, Acquire) => intrinsics::atomic_cxchg_failacq(dst, old, new), + (_, AcqRel) => panic!("there is no such thing as an acquire/release failure ordering"), + (_, Release) => panic!("there is no such thing as a release failure ordering"), + _ => panic!("a failure ordering can't be stronger than a success ordering"), + } }; if ok { Ok(val) } else { Err(val) } } @@ -2428,19 +2446,22 @@ unsafe fn atomic_compare_exchange_weak( success: Ordering, failure: Ordering, ) -> Result { - let (val, ok) = match (success, failure) { - (Acquire, Acquire) => intrinsics::atomic_cxchgweak_acq(dst, old, new), - (Release, Relaxed) => intrinsics::atomic_cxchgweak_rel(dst, old, new), - (AcqRel, Acquire) => intrinsics::atomic_cxchgweak_acqrel(dst, old, new), - (Relaxed, Relaxed) => intrinsics::atomic_cxchgweak_relaxed(dst, old, new), - (SeqCst, SeqCst) => intrinsics::atomic_cxchgweak(dst, old, new), - (Acquire, Relaxed) => intrinsics::atomic_cxchgweak_acq_failrelaxed(dst, old, new), - (AcqRel, Relaxed) => intrinsics::atomic_cxchgweak_acqrel_failrelaxed(dst, old, new), - (SeqCst, Relaxed) => intrinsics::atomic_cxchgweak_failrelaxed(dst, old, new), - (SeqCst, Acquire) => intrinsics::atomic_cxchgweak_failacq(dst, old, new), - (_, AcqRel) => panic!("there is no such thing as an acquire/release failure ordering"), - (_, Release) => panic!("there is no such thing as a release failure ordering"), - _ => panic!("a failure ordering can't be stronger than a success ordering"), + // SAFETY: the caller must uphold the safety contract for `atomic_compare_exchange_weak`. + let (val, ok) = unsafe { + match (success, failure) { + (Acquire, Acquire) => intrinsics::atomic_cxchgweak_acq(dst, old, new), + (Release, Relaxed) => intrinsics::atomic_cxchgweak_rel(dst, old, new), + (AcqRel, Acquire) => intrinsics::atomic_cxchgweak_acqrel(dst, old, new), + (Relaxed, Relaxed) => intrinsics::atomic_cxchgweak_relaxed(dst, old, new), + (SeqCst, SeqCst) => intrinsics::atomic_cxchgweak(dst, old, new), + (Acquire, Relaxed) => intrinsics::atomic_cxchgweak_acq_failrelaxed(dst, old, new), + (AcqRel, Relaxed) => intrinsics::atomic_cxchgweak_acqrel_failrelaxed(dst, old, new), + (SeqCst, Relaxed) => intrinsics::atomic_cxchgweak_failrelaxed(dst, old, new), + (SeqCst, Acquire) => intrinsics::atomic_cxchgweak_failacq(dst, old, new), + (_, AcqRel) => panic!("there is no such thing as an acquire/release failure ordering"), + (_, Release) => panic!("there is no such thing as a release failure ordering"), + _ => panic!("a failure ordering can't be stronger than a success ordering"), + } }; if ok { Ok(val) } else { Err(val) } } @@ -2448,48 +2469,60 @@ unsafe fn atomic_compare_exchange_weak( #[inline] #[cfg(target_has_atomic = "8")] unsafe fn atomic_and(dst: *mut T, val: T, order: Ordering) -> T { - match order { - Acquire => intrinsics::atomic_and_acq(dst, val), - Release => intrinsics::atomic_and_rel(dst, val), - AcqRel => intrinsics::atomic_and_acqrel(dst, val), - Relaxed => intrinsics::atomic_and_relaxed(dst, val), - SeqCst => intrinsics::atomic_and(dst, val), + // SAFETY: the caller must uphold the safety contract for `atomic_and` + unsafe { + match order { + Acquire => intrinsics::atomic_and_acq(dst, val), + Release => intrinsics::atomic_and_rel(dst, val), + AcqRel => intrinsics::atomic_and_acqrel(dst, val), + Relaxed => intrinsics::atomic_and_relaxed(dst, val), + SeqCst => intrinsics::atomic_and(dst, val), + } } } #[inline] #[cfg(target_has_atomic = "8")] unsafe fn atomic_nand(dst: *mut T, val: T, order: Ordering) -> T { - match order { - Acquire => intrinsics::atomic_nand_acq(dst, val), - Release => intrinsics::atomic_nand_rel(dst, val), - AcqRel => intrinsics::atomic_nand_acqrel(dst, val), - Relaxed => intrinsics::atomic_nand_relaxed(dst, val), - SeqCst => intrinsics::atomic_nand(dst, val), + // SAFETY: the caller must uphold the safety contract for `atomic_nand` + unsafe { + match order { + Acquire => intrinsics::atomic_nand_acq(dst, val), + Release => intrinsics::atomic_nand_rel(dst, val), + AcqRel => intrinsics::atomic_nand_acqrel(dst, val), + Relaxed => intrinsics::atomic_nand_relaxed(dst, val), + SeqCst => intrinsics::atomic_nand(dst, val), + } } } #[inline] #[cfg(target_has_atomic = "8")] unsafe fn atomic_or(dst: *mut T, val: T, order: Ordering) -> T { - match order { - Acquire => intrinsics::atomic_or_acq(dst, val), - Release => intrinsics::atomic_or_rel(dst, val), - AcqRel => intrinsics::atomic_or_acqrel(dst, val), - Relaxed => intrinsics::atomic_or_relaxed(dst, val), - SeqCst => intrinsics::atomic_or(dst, val), + // SAFETY: the caller must uphold the safety contract for `atomic_or` + unsafe { + match order { + Acquire => intrinsics::atomic_or_acq(dst, val), + Release => intrinsics::atomic_or_rel(dst, val), + AcqRel => intrinsics::atomic_or_acqrel(dst, val), + Relaxed => intrinsics::atomic_or_relaxed(dst, val), + SeqCst => intrinsics::atomic_or(dst, val), + } } } #[inline] #[cfg(target_has_atomic = "8")] unsafe fn atomic_xor(dst: *mut T, val: T, order: Ordering) -> T { - match order { - Acquire => intrinsics::atomic_xor_acq(dst, val), - Release => intrinsics::atomic_xor_rel(dst, val), - AcqRel => intrinsics::atomic_xor_acqrel(dst, val), - Relaxed => intrinsics::atomic_xor_relaxed(dst, val), - SeqCst => intrinsics::atomic_xor(dst, val), + // SAFETY: the caller must uphold the safety contract for `atomic_xor` + unsafe { + match order { + Acquire => intrinsics::atomic_xor_acq(dst, val), + Release => intrinsics::atomic_xor_rel(dst, val), + AcqRel => intrinsics::atomic_xor_acqrel(dst, val), + Relaxed => intrinsics::atomic_xor_relaxed(dst, val), + SeqCst => intrinsics::atomic_xor(dst, val), + } } } @@ -2497,12 +2530,15 @@ unsafe fn atomic_xor(dst: *mut T, val: T, order: Ordering) -> T { #[inline] #[cfg(target_has_atomic = "8")] unsafe fn atomic_max(dst: *mut T, val: T, order: Ordering) -> T { - match order { - Acquire => intrinsics::atomic_max_acq(dst, val), - Release => intrinsics::atomic_max_rel(dst, val), - AcqRel => intrinsics::atomic_max_acqrel(dst, val), - Relaxed => intrinsics::atomic_max_relaxed(dst, val), - SeqCst => intrinsics::atomic_max(dst, val), + // SAFETY: the caller must uphold the safety contract for `atomic_max` + unsafe { + match order { + Acquire => intrinsics::atomic_max_acq(dst, val), + Release => intrinsics::atomic_max_rel(dst, val), + AcqRel => intrinsics::atomic_max_acqrel(dst, val), + Relaxed => intrinsics::atomic_max_relaxed(dst, val), + SeqCst => intrinsics::atomic_max(dst, val), + } } } @@ -2510,12 +2546,15 @@ unsafe fn atomic_max(dst: *mut T, val: T, order: Ordering) -> T { #[inline] #[cfg(target_has_atomic = "8")] unsafe fn atomic_min(dst: *mut T, val: T, order: Ordering) -> T { - match order { - Acquire => intrinsics::atomic_min_acq(dst, val), - Release => intrinsics::atomic_min_rel(dst, val), - AcqRel => intrinsics::atomic_min_acqrel(dst, val), - Relaxed => intrinsics::atomic_min_relaxed(dst, val), - SeqCst => intrinsics::atomic_min(dst, val), + // SAFETY: the caller must uphold the safety contract for `atomic_min` + unsafe { + match order { + Acquire => intrinsics::atomic_min_acq(dst, val), + Release => intrinsics::atomic_min_rel(dst, val), + AcqRel => intrinsics::atomic_min_acqrel(dst, val), + Relaxed => intrinsics::atomic_min_relaxed(dst, val), + SeqCst => intrinsics::atomic_min(dst, val), + } } } @@ -2523,12 +2562,15 @@ unsafe fn atomic_min(dst: *mut T, val: T, order: Ordering) -> T { #[inline] #[cfg(target_has_atomic = "8")] unsafe fn atomic_umax(dst: *mut T, val: T, order: Ordering) -> T { - match order { - Acquire => intrinsics::atomic_umax_acq(dst, val), - Release => intrinsics::atomic_umax_rel(dst, val), - AcqRel => intrinsics::atomic_umax_acqrel(dst, val), - Relaxed => intrinsics::atomic_umax_relaxed(dst, val), - SeqCst => intrinsics::atomic_umax(dst, val), + // SAFETY: the caller must uphold the safety contract for `atomic_umax` + unsafe { + match order { + Acquire => intrinsics::atomic_umax_acq(dst, val), + Release => intrinsics::atomic_umax_rel(dst, val), + AcqRel => intrinsics::atomic_umax_acqrel(dst, val), + Relaxed => intrinsics::atomic_umax_relaxed(dst, val), + SeqCst => intrinsics::atomic_umax(dst, val), + } } } @@ -2536,12 +2578,15 @@ unsafe fn atomic_umax(dst: *mut T, val: T, order: Ordering) -> T { #[inline] #[cfg(target_has_atomic = "8")] unsafe fn atomic_umin(dst: *mut T, val: T, order: Ordering) -> T { - match order { - Acquire => intrinsics::atomic_umin_acq(dst, val), - Release => intrinsics::atomic_umin_rel(dst, val), - AcqRel => intrinsics::atomic_umin_acqrel(dst, val), - Relaxed => intrinsics::atomic_umin_relaxed(dst, val), - SeqCst => intrinsics::atomic_umin(dst, val), + // SAFETY: the caller must uphold the safety contract for `atomic_umin` + unsafe { + match order { + Acquire => intrinsics::atomic_umin_acq(dst, val), + Release => intrinsics::atomic_umin_rel(dst, val), + AcqRel => intrinsics::atomic_umin_acqrel(dst, val), + Relaxed => intrinsics::atomic_umin_relaxed(dst, val), + SeqCst => intrinsics::atomic_umin(dst, val), + } } } diff --git a/src/libcore/tests/lib.rs b/src/libcore/tests/lib.rs index c60ce8ec837d5..68a5e20a66fdc 100644 --- a/src/libcore/tests/lib.rs +++ b/src/libcore/tests/lib.rs @@ -44,6 +44,8 @@ #![feature(option_unwrap_none)] #![feature(peekable_next_if)] #![feature(partition_point)] +#![feature(unsafe_block_in_unsafe_fn)] +#![deny(unsafe_op_in_unsafe_fn)] extern crate test; diff --git a/src/librustc_ast/attr/mod.rs b/src/librustc_ast/attr/mod.rs index 6c128f0176f66..76139209c9151 100644 --- a/src/librustc_ast/attr/mod.rs +++ b/src/librustc_ast/attr/mod.rs @@ -475,7 +475,7 @@ impl MetaItem { let span = span.with_hi(segments.last().unwrap().ident.span.hi()); Path { span, segments } } - Some(TokenTree::Token(Token { kind: token::Interpolated(nt, _), .. })) => match *nt { + Some(TokenTree::Token(Token { kind: token::Interpolated(nt), .. })) => match *nt { token::Nonterminal::NtMeta(ref item) => return item.meta(item.path.span), token::Nonterminal::NtPath(ref path) => path.clone(), _ => return None, @@ -560,6 +560,9 @@ impl MetaItemKind { tokens: &mut impl Iterator, ) -> Option { match tokens.next() { + Some(TokenTree::Delimited(_, token::NoDelim, inner_tokens)) => { + MetaItemKind::name_value_from_tokens(&mut inner_tokens.trees()) + } Some(TokenTree::Token(token)) => { Lit::from_token(&token).ok().map(MetaItemKind::NameValue) } @@ -619,13 +622,20 @@ impl NestedMetaItem { where I: Iterator, { - if let Some(TokenTree::Token(token)) = tokens.peek() { - if let Ok(lit) = Lit::from_token(token) { + match tokens.peek() { + Some(TokenTree::Token(token)) => { + if let Ok(lit) = Lit::from_token(token) { + tokens.next(); + return Some(NestedMetaItem::Literal(lit)); + } + } + Some(TokenTree::Delimited(_, token::NoDelim, inner_tokens)) => { + let inner_tokens = inner_tokens.clone(); tokens.next(); - return Some(NestedMetaItem::Literal(lit)); + return NestedMetaItem::from_tokens(&mut inner_tokens.into_trees().peekable()); } + _ => {} } - MetaItem::from_tokens(tokens).map(NestedMetaItem::MetaItem) } } diff --git a/src/librustc_ast/mut_visit.rs b/src/librustc_ast/mut_visit.rs index 3fd2815daa14f..54f81ef106fe1 100644 --- a/src/librustc_ast/mut_visit.rs +++ b/src/librustc_ast/mut_visit.rs @@ -656,7 +656,7 @@ pub fn noop_visit_token(t: &mut Token, vis: &mut T) { *span = ident.span; return; // Avoid visiting the span for the second time. } - token::Interpolated(nt, _) => { + token::Interpolated(nt) => { let mut nt = Lrc::make_mut(nt); vis.visit_interpolated(&mut nt); } diff --git a/src/librustc_ast/token.rs b/src/librustc_ast/token.rs index 89be3e6e212cc..173ea5e48d682 100644 --- a/src/librustc_ast/token.rs +++ b/src/librustc_ast/token.rs @@ -11,7 +11,7 @@ use crate::tokenstream::TokenTree; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; use rustc_data_structures::sync::Lrc; use rustc_macros::HashStable_Generic; -use rustc_span::symbol::kw; +use rustc_span::symbol::{kw, sym}; use rustc_span::symbol::{Ident, Symbol}; use rustc_span::{self, Span, DUMMY_SP}; use std::borrow::Cow; @@ -182,15 +182,6 @@ fn ident_can_begin_type(name: Symbol, span: Span, is_raw: bool) -> bool { .contains(&name) } -/// A hack used to pass AST fragments to attribute and derive macros -/// as a single nonterminal token instead of a token stream. -/// FIXME: It needs to be removed, but there are some compatibility issues (see #73345). -#[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)] -pub enum FlattenGroup { - Yes, - No, -} - #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable_Generic)] pub enum TokenKind { /* Expression-operator symbols. */ @@ -245,7 +236,7 @@ pub enum TokenKind { /// treat regular and interpolated lifetime identifiers in the same way. Lifetime(Symbol), - Interpolated(Lrc, FlattenGroup), + Interpolated(Lrc), // Can be expanded into several tokens. /// A doc comment. @@ -352,7 +343,7 @@ impl Token { /// if they keep spans or perform edition checks. pub fn uninterpolated_span(&self) -> Span { match &self.kind { - Interpolated(nt, _) => nt.span(), + Interpolated(nt) => nt.span(), _ => self.span, } } @@ -391,7 +382,7 @@ impl Token { ModSep | // global path Lifetime(..) | // labeled loop Pound => true, // expression attributes - Interpolated(ref nt, _) => match **nt { + Interpolated(ref nt) => match **nt { NtLiteral(..) | NtExpr(..) | NtBlock(..) | @@ -417,7 +408,7 @@ impl Token { Lifetime(..) | // lifetime bound in trait object Lt | BinOp(Shl) | // associated path ModSep => true, // global path - Interpolated(ref nt, _) => match **nt { + Interpolated(ref nt) => match **nt { NtTy(..) | NtPath(..) => true, _ => false, }, @@ -429,7 +420,7 @@ impl Token { pub fn can_begin_const_arg(&self) -> bool { match self.kind { OpenDelim(Brace) => true, - Interpolated(ref nt, _) => match **nt { + Interpolated(ref nt) => match **nt { NtExpr(..) | NtBlock(..) | NtLiteral(..) => true, _ => false, }, @@ -464,7 +455,7 @@ impl Token { match self.uninterpolate().kind { Literal(..) | BinOp(Minus) => true, Ident(name, false) if name.is_bool_lit() => true, - Interpolated(ref nt, _) => match &**nt { + Interpolated(ref nt) => match &**nt { NtLiteral(_) => true, NtExpr(e) => match &e.kind { ast::ExprKind::Lit(_) => true, @@ -485,7 +476,7 @@ impl Token { // otherwise returns the original token. pub fn uninterpolate(&self) -> Cow<'_, Token> { match &self.kind { - Interpolated(nt, _) => match **nt { + Interpolated(nt) => match **nt { NtIdent(ident, is_raw) => { Cow::Owned(Token::new(Ident(ident.name, is_raw), ident.span)) } @@ -532,7 +523,7 @@ impl Token { /// Returns `true` if the token is an interpolated path. fn is_path(&self) -> bool { - if let Interpolated(ref nt, _) = self.kind { + if let Interpolated(ref nt) = self.kind { if let NtPath(..) = **nt { return true; } @@ -544,7 +535,7 @@ impl Token { /// That is, is this a pre-parsed expression dropped into the token stream /// (which happens while parsing the result of macro expansion)? pub fn is_whole_expr(&self) -> bool { - if let Interpolated(ref nt, _) = self.kind { + if let Interpolated(ref nt) = self.kind { if let NtExpr(_) | NtLiteral(_) | NtPath(_) | NtIdent(..) | NtBlock(_) = **nt { return true; } @@ -555,7 +546,7 @@ impl Token { // Is the token an interpolated block (`$b:block`)? pub fn is_whole_block(&self) -> bool { - if let Interpolated(ref nt, _) = self.kind { + if let Interpolated(ref nt) = self.kind { if let NtBlock(..) = **nt { return true; } @@ -785,6 +776,26 @@ impl Nonterminal { NtTT(tt) => tt.span(), } } + + /// This nonterminal looks like some specific enums from + /// `proc-macro-hack` and `procedural-masquerade` crates. + /// We need to maintain some special pretty-printing behavior for them due to incorrect + /// asserts in old versions of those crates and their wide use in the ecosystem. + /// See issue #73345 for more details. + /// FIXME(#73933): Remove this eventually. + pub fn pretty_printing_compatibility_hack(&self) -> bool { + if let NtItem(item) = self { + let name = item.ident.name; + if name == sym::ProceduralMasqueradeDummyType || name == sym::ProcMacroHack { + if let ast::ItemKind::Enum(enum_def, _) = &item.kind { + if let [variant] = &*enum_def.variants { + return variant.ident.name == sym::Input; + } + } + } + } + false + } } impl PartialEq for Nonterminal { diff --git a/src/librustc_ast/util/literal.rs b/src/librustc_ast/util/literal.rs index ea59f867c59d2..4428d09902b92 100644 --- a/src/librustc_ast/util/literal.rs +++ b/src/librustc_ast/util/literal.rs @@ -205,7 +205,7 @@ impl Lit { token::Lit::new(token::Bool, name, None) } token::Literal(lit) => lit, - token::Interpolated(ref nt, _) => { + token::Interpolated(ref nt) => { if let token::NtExpr(expr) | token::NtLiteral(expr) = &**nt { if let ast::ExprKind::Lit(lit) = &expr.kind { return Ok(lit.clone()); diff --git a/src/librustc_ast_lowering/lib.rs b/src/librustc_ast_lowering/lib.rs index bc0980f041b94..b5d3beb4f8a9b 100644 --- a/src/librustc_ast_lowering/lib.rs +++ b/src/librustc_ast_lowering/lib.rs @@ -39,8 +39,8 @@ use rustc_ast::ast; use rustc_ast::ast::*; use rustc_ast::attr; use rustc_ast::node_id::NodeMap; -use rustc_ast::token::{self, Nonterminal, Token}; -use rustc_ast::tokenstream::{TokenStream, TokenTree}; +use rustc_ast::token::{self, DelimToken, Nonterminal, Token}; +use rustc_ast::tokenstream::{DelimSpan, TokenStream, TokenTree}; use rustc_ast::visit::{self, AssocCtxt, Visitor}; use rustc_ast::walk_list; use rustc_ast_pretty::pprust; @@ -1027,9 +1027,14 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { fn lower_token(&mut self, token: Token) -> TokenStream { match token.kind { - token::Interpolated(nt, _) => { + token::Interpolated(nt) => { let tts = (self.nt_to_tokenstream)(&nt, &self.sess.parse_sess, token.span); - self.lower_token_stream(tts) + TokenTree::Delimited( + DelimSpan::from_single(token.span), + DelimToken::NoDelim, + self.lower_token_stream(tts), + ) + .into() } _ => TokenTree::Token(token).into(), } diff --git a/src/librustc_ast_pretty/pprust.rs b/src/librustc_ast_pretty/pprust.rs index 86faa1f086ce2..2d803262f79e1 100644 --- a/src/librustc_ast_pretty/pprust.rs +++ b/src/librustc_ast_pretty/pprust.rs @@ -9,7 +9,7 @@ use rustc_ast::ast::{InlineAsmOptions, InlineAsmTemplatePiece}; use rustc_ast::attr; use rustc_ast::ptr::P; use rustc_ast::token::{self, BinOpToken, DelimToken, Nonterminal, Token, TokenKind}; -use rustc_ast::tokenstream::{self, TokenStream, TokenTree}; +use rustc_ast::tokenstream::{TokenStream, TokenTree}; use rustc_ast::util::parser::{self, AssocOp, Fixity}; use rustc_ast::util::{classify, comments}; use rustc_span::edition::Edition; @@ -148,9 +148,14 @@ pub fn to_string(f: impl FnOnce(&mut State<'_>)) -> String { printer.s.eof() } -// This makes comma-separated lists look slightly nicer, -// and also addresses a specific regression described in issue #63896. +// This makes printed token streams look slightly nicer, +// and also addresses some specific regressions described in #63896 and #73345. fn tt_prepend_space(tt: &TokenTree, prev: &TokenTree) -> bool { + if let TokenTree::Token(token) = prev { + if let token::DocComment(s) = token.kind { + return !s.as_str().starts_with("//"); + } + } match tt { TokenTree::Token(token) => match token.kind { token::Comma => false, @@ -163,7 +168,14 @@ fn tt_prepend_space(tt: &TokenTree, prev: &TokenTree) -> bool { }, _ => true, }, - _ => true, + TokenTree::Delimited(_, DelimToken::Bracket, _) => match prev { + TokenTree::Token(token) => match token.kind { + token::Pound => false, + _ => true, + }, + _ => true, + }, + TokenTree::Delimited(..) => true, } } @@ -245,7 +257,7 @@ fn token_kind_to_string_ext(tok: &TokenKind, convert_dollar_crate: Option) token::CloseDelim(token::Bracket) => "]".to_string(), token::OpenDelim(token::Brace) => "{".to_string(), token::CloseDelim(token::Brace) => "}".to_string(), - token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim) => " ".to_string(), + token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim) => "".to_string(), token::Pound => "#".to_string(), token::Dollar => "$".to_string(), token::Question => "?".to_string(), @@ -266,7 +278,7 @@ fn token_kind_to_string_ext(tok: &TokenKind, convert_dollar_crate: Option) token::Shebang(s) => format!("/* shebang: {}*/", s), token::Unknown(s) => s.to_string(), - token::Interpolated(ref nt, _) => nonterminal_to_string(nt), + token::Interpolated(ref nt) => nonterminal_to_string(nt), } } @@ -293,7 +305,7 @@ pub fn nonterminal_to_string(nt: &Nonterminal) -> String { token::NtIdent(e, is_raw) => IdentPrinter::for_ast_ident(e, is_raw).to_string(), token::NtLifetime(e) => e.to_string(), token::NtLiteral(ref e) => expr_to_string(e), - token::NtTT(ref tree) => tt_to_string(tree.clone()), + token::NtTT(ref tree) => tt_to_string(tree), token::NtVis(ref e) => vis_to_string(e), } } @@ -314,11 +326,11 @@ pub fn expr_to_string(e: &ast::Expr) -> String { to_string(|s| s.print_expr(e)) } -pub fn tt_to_string(tt: tokenstream::TokenTree) -> String { +pub fn tt_to_string(tt: &TokenTree) -> String { to_string(|s| s.print_tt(tt, false)) } -pub fn tts_to_string(tokens: TokenStream) -> String { +pub fn tts_to_string(tokens: &TokenStream) -> String { to_string(|s| s.print_tts(tokens, false)) } @@ -585,7 +597,7 @@ pub trait PrintState<'a>: std::ops::Deref + std::ops::Dere false, None, delim.to_token(), - tokens.clone(), + tokens, true, span, ), @@ -594,7 +606,7 @@ pub trait PrintState<'a>: std::ops::Deref + std::ops::Dere if let MacArgs::Eq(_, tokens) = &item.args { self.space(); self.word_space("="); - self.print_tts(tokens.clone(), true); + self.print_tts(tokens, true); } } } @@ -635,9 +647,9 @@ pub trait PrintState<'a>: std::ops::Deref + std::ops::Dere /// appropriate macro, transcribe back into the grammar we just parsed from, /// and then pretty-print the resulting AST nodes (so, e.g., we print /// expression arguments as expressions). It can be done! I think. - fn print_tt(&mut self, tt: tokenstream::TokenTree, convert_dollar_crate: bool) { + fn print_tt(&mut self, tt: &TokenTree, convert_dollar_crate: bool) { match tt { - TokenTree::Token(ref token) => { + TokenTree::Token(token) => { self.word(token_to_string_ext(&token, convert_dollar_crate)); if let token::DocComment(..) = token.kind { self.hardbreak() @@ -648,7 +660,7 @@ pub trait PrintState<'a>: std::ops::Deref + std::ops::Dere None, false, None, - delim, + *delim, tts, convert_dollar_crate, dspan.entire(), @@ -657,14 +669,14 @@ pub trait PrintState<'a>: std::ops::Deref + std::ops::Dere } } - fn print_tts(&mut self, tts: tokenstream::TokenStream, convert_dollar_crate: bool) { - let mut iter = tts.into_trees().peekable(); + fn print_tts(&mut self, tts: &TokenStream, convert_dollar_crate: bool) { + let mut iter = tts.trees().peekable(); while let Some(tt) = iter.next() { - let show_space = - if let Some(next) = iter.peek() { tt_prepend_space(next, &tt) } else { false }; - self.print_tt(tt, convert_dollar_crate); - if show_space { - self.space(); + self.print_tt(&tt, convert_dollar_crate); + if let Some(next) = iter.peek() { + if tt_prepend_space(next, &tt) { + self.space(); + } } } } @@ -675,7 +687,7 @@ pub trait PrintState<'a>: std::ops::Deref + std::ops::Dere has_bang: bool, ident: Option, delim: DelimToken, - tts: TokenStream, + tts: &TokenStream, convert_dollar_crate: bool, span: Span, ) { @@ -1253,7 +1265,7 @@ impl<'a> State<'a> { has_bang, Some(item.ident), macro_def.body.delim(), - macro_def.body.inner_tokens(), + ¯o_def.body.inner_tokens(), true, item.span, ); @@ -1577,7 +1589,7 @@ impl<'a> State<'a> { true, None, m.args.delim(), - m.args.inner_tokens(), + &m.args.inner_tokens(), true, m.span(), ); diff --git a/src/librustc_builtin_macros/log_syntax.rs b/src/librustc_builtin_macros/log_syntax.rs index ae3a889428ae4..ede34a7612589 100644 --- a/src/librustc_builtin_macros/log_syntax.rs +++ b/src/librustc_builtin_macros/log_syntax.rs @@ -7,7 +7,7 @@ pub fn expand_log_syntax<'cx>( sp: rustc_span::Span, tts: TokenStream, ) -> Box { - println!("{}", pprust::tts_to_string(tts)); + println!("{}", pprust::tts_to_string(&tts)); // any so that `log_syntax` can be invoked as an expression and item. base::DummyResult::any_valid(sp) diff --git a/src/librustc_builtin_macros/source_util.rs b/src/librustc_builtin_macros/source_util.rs index 1b164eae5a345..e46cf67e64d66 100644 --- a/src/librustc_builtin_macros/source_util.rs +++ b/src/librustc_builtin_macros/source_util.rs @@ -71,7 +71,7 @@ pub fn expand_stringify( tts: TokenStream, ) -> Box { let sp = cx.with_def_site_ctxt(sp); - let s = pprust::tts_to_string(tts); + let s = pprust::tts_to_string(&tts); base::MacEager::expr(cx.expr_str(sp, Symbol::intern(&s))) } diff --git a/src/librustc_driver/pretty.rs b/src/librustc_driver/pretty.rs index 0a21eb8de059c..d138d7896fe5a 100644 --- a/src/librustc_driver/pretty.rs +++ b/src/librustc_driver/pretty.rs @@ -80,8 +80,9 @@ where PpmTyped => { abort_on_err(tcx.analysis(LOCAL_CRATE), tcx.sess); - let empty_tables = ty::TypeckTables::empty(None); - let annotation = TypedAnnotation { tcx, tables: Cell::new(&empty_tables) }; + let empty_typeck_results = ty::TypeckResults::empty(None); + let annotation = + TypedAnnotation { tcx, typeck_results: Cell::new(&empty_typeck_results) }; tcx.dep_graph.with_ignore(|| f(&annotation, tcx.hir().krate())) } _ => panic!("Should use call_with_pp_support"), @@ -306,7 +307,7 @@ impl<'a> pprust::PpAnn for HygieneAnnotation<'a> { struct TypedAnnotation<'a, 'tcx> { tcx: TyCtxt<'tcx>, - tables: Cell<&'a ty::TypeckTables<'tcx>>, + typeck_results: Cell<&'a ty::TypeckResults<'tcx>>, } impl<'b, 'tcx> HirPrinterSupport<'tcx> for TypedAnnotation<'b, 'tcx> { @@ -329,13 +330,13 @@ impl<'b, 'tcx> HirPrinterSupport<'tcx> for TypedAnnotation<'b, 'tcx> { impl<'a, 'tcx> pprust_hir::PpAnn for TypedAnnotation<'a, 'tcx> { fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested) { - let old_tables = self.tables.get(); + let old_typeck_results = self.typeck_results.get(); if let pprust_hir::Nested::Body(id) = nested { - self.tables.set(self.tcx.body_tables(id)); + self.typeck_results.set(self.tcx.typeck_body(id)); } let pp_ann = &(&self.tcx.hir() as &dyn hir::intravisit::Map<'_>); pprust_hir::PpAnn::nested(pp_ann, state, nested); - self.tables.set(old_tables); + self.typeck_results.set(old_typeck_results); } fn pre(&self, s: &mut pprust_hir::State<'_>, node: pprust_hir::AnnNode<'_>) { if let pprust_hir::AnnNode::Expr(_) = node { @@ -347,7 +348,7 @@ impl<'a, 'tcx> pprust_hir::PpAnn for TypedAnnotation<'a, 'tcx> { s.s.space(); s.s.word("as"); s.s.space(); - s.s.word(self.tables.get().expr_ty(expr).to_string()); + s.s.word(self.typeck_results.get().expr_ty(expr).to_string()); s.pclose(); } } diff --git a/src/librustc_error_codes/error_codes/E0712.md b/src/librustc_error_codes/error_codes/E0712.md index 89f60084f0a60..7e09210e7874c 100644 --- a/src/librustc_error_codes/error_codes/E0712.md +++ b/src/librustc_error_codes/error_codes/E0712.md @@ -1,5 +1,5 @@ -This error occurs because a borrow of a thread-local variable was made inside a -function which outlived the lifetime of the function. +A borrow of a thread-local variable was made inside a function which outlived +the lifetime of the function. Erroneous code example: diff --git a/src/librustc_expand/base.rs b/src/librustc_expand/base.rs index 757eee8bb46e1..db9293bddeb7d 100644 --- a/src/librustc_expand/base.rs +++ b/src/librustc_expand/base.rs @@ -4,14 +4,14 @@ use crate::module::DirectoryOwnership; use rustc_ast::ast::{self, Attribute, NodeId, PatKind}; use rustc_ast::mut_visit::{self, MutVisitor}; use rustc_ast::ptr::P; -use rustc_ast::token::{self, FlattenGroup}; -use rustc_ast::tokenstream::{self, TokenStream, TokenTree}; +use rustc_ast::token; +use rustc_ast::tokenstream::{self, TokenStream}; use rustc_ast::visit::{AssocCtxt, Visitor}; use rustc_attr::{self as attr, Deprecation, HasAttrs, Stability}; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::sync::{self, Lrc}; use rustc_errors::{DiagnosticBuilder, ErrorReported}; -use rustc_parse::{self, parser, MACRO_ARGUMENTS}; +use rustc_parse::{self, nt_to_tokenstream, parser, MACRO_ARGUMENTS}; use rustc_session::{parse::ParseSess, Limit}; use rustc_span::def_id::DefId; use rustc_span::edition::Edition; @@ -120,10 +120,7 @@ impl Annotatable { } } - crate fn into_tokens(self) -> TokenStream { - // `Annotatable` can be converted into tokens directly, but we - // are packing it into a nonterminal as a piece of AST to make - // the produced token stream look nicer in pretty-printed form. + crate fn into_tokens(self, sess: &ParseSess) -> TokenStream { let nt = match self { Annotatable::Item(item) => token::NtItem(item), Annotatable::TraitItem(item) | Annotatable::ImplItem(item) => { @@ -142,7 +139,7 @@ impl Annotatable { | Annotatable::StructField(..) | Annotatable::Variant(..) => panic!("unexpected annotatable"), }; - TokenTree::token(token::Interpolated(Lrc::new(nt), FlattenGroup::Yes), DUMMY_SP).into() + nt_to_tokenstream(&nt, sess, DUMMY_SP) } pub fn expect_item(self) -> P { @@ -374,7 +371,7 @@ where impl MutVisitor for AvoidInterpolatedIdents { fn visit_tt(&mut self, tt: &mut tokenstream::TokenTree) { if let tokenstream::TokenTree::Token(token) = tt { - if let token::Interpolated(nt, _) = &token.kind { + if let token::Interpolated(nt) = &token.kind { if let token::NtIdent(ident, is_raw) = **nt { *tt = tokenstream::TokenTree::token( token::Ident(ident.name, is_raw), diff --git a/src/librustc_expand/expand.rs b/src/librustc_expand/expand.rs index 4e41bd4bbfa08..bd7a094c5e355 100644 --- a/src/librustc_expand/expand.rs +++ b/src/librustc_expand/expand.rs @@ -705,7 +705,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> { SyntaxExtensionKind::Attr(expander) => { self.gate_proc_macro_input(&item); self.gate_proc_macro_attr_item(span, &item); - let tokens = item.into_tokens(); + let tokens = item.into_tokens(self.cx.parse_sess); let attr_item = attr.unwrap_normal_item(); if let MacArgs::Eq(..) = attr_item.args { self.cx.span_err(span, "key-value macro attributes are not supported"); diff --git a/src/librustc_expand/mbe/macro_parser.rs b/src/librustc_expand/mbe/macro_parser.rs index c90a438c25ece..3c15a81c67f67 100644 --- a/src/librustc_expand/mbe/macro_parser.rs +++ b/src/librustc_expand/mbe/macro_parser.rs @@ -790,7 +790,7 @@ fn may_begin_with(token: &Token, name: Symbol) -> bool { }, sym::block => match token.kind { token::OpenDelim(token::Brace) => true, - token::Interpolated(ref nt, _) => match **nt { + token::Interpolated(ref nt) => match **nt { token::NtItem(_) | token::NtPat(_) | token::NtTy(_) @@ -804,7 +804,7 @@ fn may_begin_with(token: &Token, name: Symbol) -> bool { }, sym::path | sym::meta => match token.kind { token::ModSep | token::Ident(..) => true, - token::Interpolated(ref nt, _) => match **nt { + token::Interpolated(ref nt) => match **nt { token::NtPath(_) | token::NtMeta(_) => true, _ => may_be_ident(&nt), }, @@ -823,12 +823,12 @@ fn may_begin_with(token: &Token, name: Symbol) -> bool { token::ModSep | // path token::Lt | // path (UFCS constant) token::BinOp(token::Shl) => true, // path (double UFCS) - token::Interpolated(ref nt, _) => may_be_ident(nt), + token::Interpolated(ref nt) => may_be_ident(nt), _ => false, }, sym::lifetime => match token.kind { token::Lifetime(_) => true, - token::Interpolated(ref nt, _) => match **nt { + token::Interpolated(ref nt) => match **nt { token::NtLifetime(_) | token::NtTT(_) => true, _ => false, }, diff --git a/src/librustc_expand/mbe/macro_rules.rs b/src/librustc_expand/mbe/macro_rules.rs index 8cdb5b09c9e8b..36b323df69797 100644 --- a/src/librustc_expand/mbe/macro_rules.rs +++ b/src/librustc_expand/mbe/macro_rules.rs @@ -224,7 +224,7 @@ fn generic_extension<'cx>( let sess = cx.parse_sess; if cx.trace_macros() { - let msg = format!("expanding `{}! {{ {} }}`", name, pprust::tts_to_string(arg.clone())); + let msg = format!("expanding `{}! {{ {} }}`", name, pprust::tts_to_string(&arg)); trace_macros_note(&mut cx.expansions, sp, msg); } @@ -300,7 +300,7 @@ fn generic_extension<'cx>( } if cx.trace_macros() { - let msg = format!("to `{}`", pprust::tts_to_string(tts.clone())); + let msg = format!("to `{}`", pprust::tts_to_string(&tts)); trace_macros_note(&mut cx.expansions, sp, msg); } @@ -387,6 +387,7 @@ pub fn compile_declarative_macro( def: &ast::Item, edition: Edition, ) -> SyntaxExtension { + debug!("compile_declarative_macro: {:?}", def); let mk_syn_ext = |expander| { SyntaxExtension::new( sess, diff --git a/src/librustc_expand/mbe/quoted.rs b/src/librustc_expand/mbe/quoted.rs index de66c2ada40e6..09306f26ee0ad 100644 --- a/src/librustc_expand/mbe/quoted.rs +++ b/src/librustc_expand/mbe/quoted.rs @@ -90,7 +90,7 @@ pub(super) fn parse( /// # Parameters /// /// - `tree`: the tree we wish to convert. -/// - `trees`: an iterator over trees. We may need to read more tokens from it in order to finish +/// - `outer_trees`: an iterator over trees. We may need to read more tokens from it in order to finish /// converting `tree` /// - `expect_matchers`: same as for `parse` (see above). /// - `sess`: the parsing session. Any errors will be emitted to this session. @@ -98,7 +98,7 @@ pub(super) fn parse( /// unstable features or not. fn parse_tree( tree: tokenstream::TokenTree, - trees: &mut impl Iterator, + outer_trees: &mut impl Iterator, expect_matchers: bool, sess: &ParseSess, node_id: NodeId, @@ -106,56 +106,72 @@ fn parse_tree( // Depending on what `tree` is, we could be parsing different parts of a macro match tree { // `tree` is a `$` token. Look at the next token in `trees` - tokenstream::TokenTree::Token(Token { kind: token::Dollar, span }) => match trees.next() { - // `tree` is followed by a delimited set of token trees. This indicates the beginning - // of a repetition sequence in the macro (e.g. `$(pat)*`). - Some(tokenstream::TokenTree::Delimited(span, delim, tts)) => { - // Must have `(` not `{` or `[` - if delim != token::Paren { - let tok = pprust::token_kind_to_string(&token::OpenDelim(delim)); - let msg = format!("expected `(`, found `{}`", tok); - sess.span_diagnostic.span_err(span.entire(), &msg); - } - // Parse the contents of the sequence itself - let sequence = parse(tts, expect_matchers, sess, node_id); - // Get the Kleene operator and optional separator - let (separator, kleene) = parse_sep_and_kleene_op(trees, span.entire(), sess); - // Count the number of captured "names" (i.e., named metavars) - let name_captures = macro_parser::count_names(&sequence); - TokenTree::Sequence( - span, - Lrc::new(SequenceRepetition { - tts: sequence, - separator, - kleene, - num_captures: name_captures, - }), - ) + tokenstream::TokenTree::Token(Token { kind: token::Dollar, span }) => { + // FIXME: Handle `None`-delimited groups in a more systematic way + // during parsing. + let mut next = outer_trees.next(); + let mut trees: Box>; + if let Some(tokenstream::TokenTree::Delimited(_, token::NoDelim, tts)) = next { + trees = Box::new(tts.into_trees()); + next = trees.next(); + } else { + trees = Box::new(outer_trees); } - // `tree` is followed by an `ident`. This could be `$meta_var` or the `$crate` special - // metavariable that names the crate of the invocation. - Some(tokenstream::TokenTree::Token(token)) if token.is_ident() => { - let (ident, is_raw) = token.ident().unwrap(); - let span = ident.span.with_lo(span.lo()); - if ident.name == kw::Crate && !is_raw { - TokenTree::token(token::Ident(kw::DollarCrate, is_raw), span) - } else { - TokenTree::MetaVar(span, ident) + match next { + // `tree` is followed by a delimited set of token trees. This indicates the beginning + // of a repetition sequence in the macro (e.g. `$(pat)*`). + Some(tokenstream::TokenTree::Delimited(span, delim, tts)) => { + // Must have `(` not `{` or `[` + if delim != token::Paren { + let tok = pprust::token_kind_to_string(&token::OpenDelim(delim)); + let msg = format!("expected `(`, found `{}`", tok); + sess.span_diagnostic.span_err(span.entire(), &msg); + } + // Parse the contents of the sequence itself + let sequence = parse(tts, expect_matchers, sess, node_id); + // Get the Kleene operator and optional separator + let (separator, kleene) = + parse_sep_and_kleene_op(&mut trees, span.entire(), sess); + // Count the number of captured "names" (i.e., named metavars) + let name_captures = macro_parser::count_names(&sequence); + TokenTree::Sequence( + span, + Lrc::new(SequenceRepetition { + tts: sequence, + separator, + kleene, + num_captures: name_captures, + }), + ) } - } - // `tree` is followed by a random token. This is an error. - Some(tokenstream::TokenTree::Token(token)) => { - let msg = - format!("expected identifier, found `{}`", pprust::token_to_string(&token),); - sess.span_diagnostic.span_err(token.span, &msg); - TokenTree::MetaVar(token.span, Ident::invalid()) - } + // `tree` is followed by an `ident`. This could be `$meta_var` or the `$crate` special + // metavariable that names the crate of the invocation. + Some(tokenstream::TokenTree::Token(token)) if token.is_ident() => { + let (ident, is_raw) = token.ident().unwrap(); + let span = ident.span.with_lo(span.lo()); + if ident.name == kw::Crate && !is_raw { + TokenTree::token(token::Ident(kw::DollarCrate, is_raw), span) + } else { + TokenTree::MetaVar(span, ident) + } + } - // There are no more tokens. Just return the `$` we already have. - None => TokenTree::token(token::Dollar, span), - }, + // `tree` is followed by a random token. This is an error. + Some(tokenstream::TokenTree::Token(token)) => { + let msg = format!( + "expected identifier, found `{}`", + pprust::token_to_string(&token), + ); + sess.span_diagnostic.span_err(token.span, &msg); + TokenTree::MetaVar(token.span, Ident::invalid()) + } + + // There are no more tokens. Just return the `$` we already have. + None => TokenTree::token(token::Dollar, span), + } + } // `tree` is an arbitrary token. Keep it. tokenstream::TokenTree::Token(token) => TokenTree::Token(token), diff --git a/src/librustc_expand/mbe/transcribe.rs b/src/librustc_expand/mbe/transcribe.rs index 486f0a6420d6e..e2d3d5c4d644e 100644 --- a/src/librustc_expand/mbe/transcribe.rs +++ b/src/librustc_expand/mbe/transcribe.rs @@ -4,7 +4,7 @@ use crate::mbe::macro_parser::{MatchedNonterminal, MatchedSeq, NamedMatch}; use rustc_ast::ast::MacCall; use rustc_ast::mut_visit::{self, MutVisitor}; -use rustc_ast::token::{self, FlattenGroup, NtTT, Token}; +use rustc_ast::token::{self, NtTT, Token}; use rustc_ast::tokenstream::{DelimSpan, TokenStream, TokenTree, TreeAndJoint}; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::sync::Lrc; @@ -240,10 +240,7 @@ pub(super) fn transcribe<'a>( result.push(tt.clone().into()); } else { marker.visit_span(&mut sp); - let token = TokenTree::token( - token::Interpolated(nt.clone(), FlattenGroup::No), - sp, - ); + let token = TokenTree::token(token::Interpolated(nt.clone()), sp); result.push(token.into()); } } else { diff --git a/src/librustc_expand/proc_macro.rs b/src/librustc_expand/proc_macro.rs index 1e26c832a2621..54012d62a72a7 100644 --- a/src/librustc_expand/proc_macro.rs +++ b/src/librustc_expand/proc_macro.rs @@ -2,10 +2,11 @@ use crate::base::{self, *}; use crate::proc_macro_server; use rustc_ast::ast::{self, ItemKind, MetaItemKind, NestedMetaItem}; -use rustc_ast::token::{self, FlattenGroup}; -use rustc_ast::tokenstream::{self, TokenStream}; +use rustc_ast::token; +use rustc_ast::tokenstream::{TokenStream, TokenTree}; use rustc_data_structures::sync::Lrc; use rustc_errors::{Applicability, ErrorReported}; +use rustc_parse::nt_to_tokenstream; use rustc_span::symbol::sym; use rustc_span::{Span, DUMMY_SP}; @@ -102,8 +103,12 @@ impl MultiItemModifier for ProcMacroDerive { } } - let token = token::Interpolated(Lrc::new(token::NtItem(item)), FlattenGroup::Yes); - let input = tokenstream::TokenTree::token(token, DUMMY_SP).into(); + let item = token::NtItem(item); + let input = if item.pretty_printing_compatibility_hack() { + TokenTree::token(token::Interpolated(Lrc::new(item)), DUMMY_SP).into() + } else { + nt_to_tokenstream(&item, ecx.parse_sess, DUMMY_SP) + }; let server = proc_macro_server::Rustc::new(ecx); let stream = match self.client.run(&EXEC_STRATEGY, server, input) { diff --git a/src/librustc_expand/proc_macro_server.rs b/src/librustc_expand/proc_macro_server.rs index c88b5a37f718a..ce53b9c0b66c8 100644 --- a/src/librustc_expand/proc_macro_server.rs +++ b/src/librustc_expand/proc_macro_server.rs @@ -1,7 +1,7 @@ use crate::base::ExtCtxt; use rustc_ast::ast; -use rustc_ast::token::{self, FlattenGroup}; +use rustc_ast::token; use rustc_ast::tokenstream::{self, DelimSpan, IsJoint::*, TokenStream, TreeAndJoint}; use rustc_ast::util::comments; use rustc_ast_pretty::pprust; @@ -60,12 +60,7 @@ impl FromInternal<(TreeAndJoint, &'_ ParseSess, &'_ mut Vec)> let Token { kind, span } = match tree { tokenstream::TokenTree::Delimited(span, delim, tts) => { let delimiter = Delimiter::from_internal(delim); - return TokenTree::Group(Group { - delimiter, - stream: tts, - span, - flatten: FlattenGroup::No, - }); + return TokenTree::Group(Group { delimiter, stream: tts, span, flatten: false }); } tokenstream::TokenTree::Token(token) => token, }; @@ -172,7 +167,7 @@ impl FromInternal<(TreeAndJoint, &'_ ParseSess, &'_ mut Vec)> delimiter: Delimiter::Bracket, stream, span: DelimSpan::from_single(span), - flatten: FlattenGroup::No, + flatten: false, })); if style == ast::AttrStyle::Inner { stack.push(tt!(Punct::new('!', false))); @@ -180,13 +175,13 @@ impl FromInternal<(TreeAndJoint, &'_ ParseSess, &'_ mut Vec)> tt!(Punct::new('#', false)) } - Interpolated(nt, flatten) => { + Interpolated(nt) => { let stream = nt_to_tokenstream(&nt, sess, span); TokenTree::Group(Group { delimiter: Delimiter::None, stream, span: DelimSpan::from_single(span), - flatten, + flatten: nt.pretty_printing_compatibility_hack(), }) } @@ -293,7 +288,7 @@ pub struct Group { /// A hack used to pass AST fragments to attribute and derive macros /// as a single nonterminal token instead of a token stream. /// FIXME: It needs to be removed, but there are some compatibility issues (see #73345). - flatten: FlattenGroup, + flatten: bool, } #[derive(Copy, Clone, PartialEq, Eq, Hash)] @@ -413,7 +408,7 @@ impl server::TokenStream for Rustc<'_> { ) } fn to_string(&mut self, stream: &Self::TokenStream) -> String { - pprust::tts_to_string(stream.clone()) + pprust::tts_to_string(stream) } fn from_token_tree( &mut self, @@ -453,7 +448,7 @@ impl server::TokenStreamIter for Rustc<'_> { // Such token needs to be "unwrapped" and not represented as a delimited group. // FIXME: It needs to be removed, but there are some compatibility issues (see #73345). if let TokenTree::Group(ref group) = tree { - if matches!(group.flatten, FlattenGroup::Yes) { + if group.flatten { iter.cursor.append(group.stream.clone()); continue; } @@ -469,7 +464,7 @@ impl server::Group for Rustc<'_> { delimiter, stream, span: DelimSpan::from_single(server::Span::call_site(self)), - flatten: FlattenGroup::No, + flatten: false, } } fn delimiter(&mut self, group: &Self::Group) -> Delimiter { diff --git a/src/librustc_hir/hir.rs b/src/librustc_hir/hir.rs index f3dfec7ca7215..ab33cb2b1ad12 100644 --- a/src/librustc_hir/hir.rs +++ b/src/librustc_hir/hir.rs @@ -1571,7 +1571,7 @@ pub enum ExprKind<'hir> { /// To resolve the called method to a `DefId`, call [`type_dependent_def_id`] with /// the `hir_id` of the `MethodCall` node itself. /// - /// [`type_dependent_def_id`]: ../ty/struct.TypeckTables.html#method.type_dependent_def_id + /// [`type_dependent_def_id`]: ../ty/struct.TypeckResults.html#method.type_dependent_def_id MethodCall(&'hir PathSegment<'hir>, Span, &'hir [Expr<'hir>], Span), /// A tuple (e.g., `(a, b, c, d)`). Tup(&'hir [Expr<'hir>]), @@ -1659,7 +1659,7 @@ pub enum ExprKind<'hir> { /// /// To resolve the path to a `DefId`, call [`qpath_res`]. /// -/// [`qpath_res`]: ../rustc_middle/ty/struct.TypeckTables.html#method.qpath_res +/// [`qpath_res`]: ../rustc_middle/ty/struct.TypeckResults.html#method.qpath_res #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)] pub enum QPath<'hir> { /// Path to a definition, optionally "fully-qualified" with a `Self` diff --git a/src/librustc_incremental/persist/dirty_clean.rs b/src/librustc_incremental/persist/dirty_clean.rs index 2ee95174dffe6..4e7f2f61c2caf 100644 --- a/src/librustc_incremental/persist/dirty_clean.rs +++ b/src/librustc_incremental/persist/dirty_clean.rs @@ -3,9 +3,9 @@ //! we will compare the fingerprint from the current and from the previous //! compilation session as appropriate: //! -//! - `#[rustc_clean(cfg="rev2", except="typeck_tables_of")]` if we are +//! - `#[rustc_clean(cfg="rev2", except="typeck")]` if we are //! in `#[cfg(rev2)]`, then the fingerprints associated with -//! `DepNode::typeck_tables_of(X)` must be DIFFERENT (`X` is the `DefId` of the +//! `DepNode::typeck(X)` must be DIFFERENT (`X` is the `DefId` of the //! current node). //! - `#[rustc_clean(cfg="rev2")]` same as above, except that the //! fingerprints must be the SAME (along with all other fingerprints). @@ -48,7 +48,7 @@ const BASE_FN: &[&str] = &[ label_strs::type_of, // And a big part of compilation (that we eventually want to cache) is type inference // information: - label_strs::typeck_tables_of, + label_strs::typeck, ]; /// DepNodes for Hir, which is pretty much everything diff --git a/src/librustc_infer/infer/error_reporting/mod.rs b/src/librustc_infer/infer/error_reporting/mod.rs index 7fdcbd31df3c5..d0b9449e036fe 100644 --- a/src/librustc_infer/infer/error_reporting/mod.rs +++ b/src/librustc_infer/infer/error_reporting/mod.rs @@ -624,8 +624,9 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { let scrut_expr = self.tcx.hir().expect_expr(scrut_hir_id); let scrut_ty = if let hir::ExprKind::Call(_, args) = &scrut_expr.kind { let arg_expr = args.first().expect("try desugaring call w/out arg"); - self.in_progress_tables - .and_then(|tables| tables.borrow().expr_ty_opt(arg_expr)) + self.in_progress_typeck_results.and_then(|typeck_results| { + typeck_results.borrow().expr_ty_opt(arg_expr) + }) } else { bug!("try desugaring w/out call expr as scrutinee"); }; @@ -1683,8 +1684,10 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { let hir = &self.tcx.hir(); // Attempt to obtain the span of the parameter so we can // suggest adding an explicit lifetime bound to it. - let generics = - self.in_progress_tables.and_then(|table| table.borrow().hir_owner).map(|table_owner| { + let generics = self + .in_progress_typeck_results + .and_then(|table| table.borrow().hir_owner) + .map(|table_owner| { let hir_id = hir.as_local_hir_id(table_owner); let parent_id = hir.get_parent_item(hir_id); ( diff --git a/src/librustc_infer/infer/error_reporting/need_type_info.rs b/src/librustc_infer/infer/error_reporting/need_type_info.rs index 1687bcc155636..bf087dfacfa43 100644 --- a/src/librustc_infer/infer/error_reporting/need_type_info.rs +++ b/src/librustc_infer/infer/error_reporting/need_type_info.rs @@ -42,8 +42,10 @@ impl<'a, 'tcx> FindHirNodeVisitor<'a, 'tcx> { } fn node_ty_contains_target(&mut self, hir_id: HirId) -> Option> { - let ty_opt = - self.infcx.in_progress_tables.and_then(|tables| tables.borrow().node_type_opt(hir_id)); + let ty_opt = self + .infcx + .in_progress_typeck_results + .and_then(|typeck_results| typeck_results.borrow().node_type_opt(hir_id)); match ty_opt { Some(ty) => { let ty = self.infcx.resolve_vars_if_possible(&ty); @@ -123,8 +125,11 @@ impl<'a, 'tcx> Visitor<'tcx> for FindHirNodeVisitor<'a, 'tcx> { if let ExprKind::MethodCall(_, call_span, exprs, _) = expr.kind { if call_span == self.target_span && Some(self.target) - == self.infcx.in_progress_tables.and_then(|tables| { - tables.borrow().node_type_opt(exprs.first().unwrap().hir_id).map(Into::into) + == self.infcx.in_progress_typeck_results.and_then(|typeck_results| { + typeck_results + .borrow() + .node_type_opt(exprs.first().unwrap().hir_id) + .map(Into::into) }) { self.found_exact_method_call = Some(&expr); @@ -580,8 +585,8 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { e: &Expr<'_>, err: &mut DiagnosticBuilder<'_>, ) { - if let (Some(tables), None) = (self.in_progress_tables, &segment.args) { - let borrow = tables.borrow(); + if let (Some(typeck_results), None) = (self.in_progress_typeck_results, &segment.args) { + let borrow = typeck_results.borrow(); if let Some((DefKind::AssocFn, did)) = borrow.type_dependent_def(e.hir_id) { let generics = self.tcx.generics_of(did); if !generics.params.is_empty() { diff --git a/src/librustc_infer/infer/mod.rs b/src/librustc_infer/infer/mod.rs index 76ac61c067280..367b75d339433 100644 --- a/src/librustc_infer/infer/mod.rs +++ b/src/librustc_infer/infer/mod.rs @@ -283,11 +283,11 @@ impl<'tcx> InferCtxtInner<'tcx> { pub struct InferCtxt<'a, 'tcx> { pub tcx: TyCtxt<'tcx>, - /// During type-checking/inference of a body, `in_progress_tables` - /// contains a reference to the tables being built up, which are + /// During type-checking/inference of a body, `in_progress_typeck_results` + /// contains a reference to the typeck_results being built up, which are /// used for reading closure kinds/signatures as they are inferred, /// and for error reporting logic to read arbitrary node types. - pub in_progress_tables: Option<&'a RefCell>>, + pub in_progress_typeck_results: Option<&'a RefCell>>, pub inner: RefCell>, @@ -571,7 +571,7 @@ impl<'tcx> fmt::Display for FixupError<'tcx> { /// `F: for<'b, 'tcx> where 'tcx FnOnce(InferCtxt<'b, 'tcx>)`. pub struct InferCtxtBuilder<'tcx> { tcx: TyCtxt<'tcx>, - fresh_tables: Option>>, + fresh_typeck_results: Option>>, } pub trait TyCtxtInferExt<'tcx> { @@ -580,15 +580,15 @@ pub trait TyCtxtInferExt<'tcx> { impl TyCtxtInferExt<'tcx> for TyCtxt<'tcx> { fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> { - InferCtxtBuilder { tcx: self, fresh_tables: None } + InferCtxtBuilder { tcx: self, fresh_typeck_results: None } } } impl<'tcx> InferCtxtBuilder<'tcx> { /// Used only by `rustc_typeck` during body type-checking/inference, - /// will initialize `in_progress_tables` with fresh `TypeckTables`. - pub fn with_fresh_in_progress_tables(mut self, table_owner: LocalDefId) -> Self { - self.fresh_tables = Some(RefCell::new(ty::TypeckTables::empty(Some(table_owner)))); + /// will initialize `in_progress_typeck_results` with fresh `TypeckResults`. + pub fn with_fresh_in_progress_typeck_results(mut self, hir_owner: LocalDefId) -> Self { + self.fresh_typeck_results = Some(RefCell::new(ty::TypeckResults::empty(Some(hir_owner)))); self } @@ -616,11 +616,11 @@ impl<'tcx> InferCtxtBuilder<'tcx> { } pub fn enter(&mut self, f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>) -> R) -> R { - let InferCtxtBuilder { tcx, ref fresh_tables } = *self; - let in_progress_tables = fresh_tables.as_ref(); + let InferCtxtBuilder { tcx, ref fresh_typeck_results } = *self; + let in_progress_typeck_results = fresh_typeck_results.as_ref(); f(InferCtxt { tcx, - in_progress_tables, + in_progress_typeck_results, inner: RefCell::new(InferCtxtInner::new()), lexical_region_resolutions: RefCell::new(None), selection_cache: Default::default(), @@ -667,7 +667,7 @@ pub struct CombinedSnapshot<'a, 'tcx> { region_constraints_snapshot: RegionSnapshot, universe: ty::UniverseIndex, was_in_snapshot: bool, - _in_progress_tables: Option>>, + _in_progress_typeck_results: Option>>, } impl<'a, 'tcx> InferCtxt<'a, 'tcx> { @@ -789,9 +789,11 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { region_constraints_snapshot: inner.unwrap_region_constraints().start_snapshot(), universe: self.universe(), was_in_snapshot: in_snapshot, - // Borrow tables "in progress" (i.e., during typeck) + // Borrow typeck_results "in progress" (i.e., during typeck) // to ban writes from within a snapshot to them. - _in_progress_tables: self.in_progress_tables.map(|tables| tables.borrow()), + _in_progress_typeck_results: self + .in_progress_typeck_results + .map(|typeck_results| typeck_results.borrow()), } } @@ -802,7 +804,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { region_constraints_snapshot, universe, was_in_snapshot, - _in_progress_tables, + _in_progress_typeck_results, } = snapshot; self.in_snapshot.set(was_in_snapshot); @@ -820,7 +822,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { region_constraints_snapshot: _, universe: _, was_in_snapshot, - _in_progress_tables, + _in_progress_typeck_results, } = snapshot; self.in_snapshot.set(was_in_snapshot); diff --git a/src/librustc_interface/tests.rs b/src/librustc_interface/tests.rs index d861b444c8816..e35dbbc0c2f24 100644 --- a/src/librustc_interface/tests.rs +++ b/src/librustc_interface/tests.rs @@ -500,7 +500,6 @@ fn test_debugging_options_tracking_hash() { untracked!(print_link_args, true); untracked!(print_llvm_passes, true); untracked!(print_mono_items, Some(String::from("abc"))); - untracked!(print_region_graph, true); untracked!(print_type_sizes, true); untracked!(query_dep_graph, true); untracked!(query_stats, true); diff --git a/src/librustc_lexer/src/lib.rs b/src/librustc_lexer/src/lib.rs index 77b3d26463dfe..2f4b1bbd3ba0f 100644 --- a/src/librustc_lexer/src/lib.rs +++ b/src/librustc_lexer/src/lib.rs @@ -51,8 +51,9 @@ pub enum TokenKind { // Multi-char tokens: /// "// comment" LineComment, - /// "/* block comment */" - /// Block comments can be recursive, so the sequence like "/* /* */" + /// `/* block comment */` + /// + /// Block comments can be recursive, so the sequence like `/* /* */` /// will not be considered terminated and will result in a parsing error. BlockComment { terminated: bool }, /// Any whitespace characters sequence. diff --git a/src/librustc_lint/array_into_iter.rs b/src/librustc_lint/array_into_iter.rs index 82ac60be17c82..f7c8811fcb5b8 100644 --- a/src/librustc_lint/array_into_iter.rs +++ b/src/librustc_lint/array_into_iter.rs @@ -31,7 +31,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ArrayIntoIter { // Check if the method call actually calls the libcore // `IntoIterator::into_iter`. - let def_id = cx.tables().type_dependent_def_id(expr.hir_id).unwrap(); + let def_id = cx.typeck_results().type_dependent_def_id(expr.hir_id).unwrap(); match cx.tcx.trait_of_item(def_id) { Some(trait_id) if cx.tcx.is_diagnostic_item(sym::IntoIterator, trait_id) => {} _ => return, @@ -45,7 +45,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ArrayIntoIter { // `Box` is the only thing that values can be moved out of via // method call. `Box::new([1]).into_iter()` should trigger this // lint. - let mut recv_ty = cx.tables().expr_ty(receiver_arg); + let mut recv_ty = cx.typeck_results().expr_ty(receiver_arg); let mut num_box_derefs = 0; while recv_ty.is_box() { num_box_derefs += 1; @@ -60,13 +60,13 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ArrayIntoIter { // Make sure that there is an autoref coercion at the expected // position. The first `num_box_derefs` adjustments are the derefs // of the box. - match cx.tables().expr_adjustments(receiver_arg).get(num_box_derefs) { + match cx.typeck_results().expr_adjustments(receiver_arg).get(num_box_derefs) { Some(Adjustment { kind: Adjust::Borrow(_), .. }) => {} _ => return, } // Emit lint diagnostic. - let target = match cx.tables().expr_ty_adjusted(receiver_arg).kind { + let target = match cx.typeck_results().expr_ty_adjusted(receiver_arg).kind { ty::Ref(_, ty::TyS { kind: ty::Array(..), .. }, _) => "[T; N]", ty::Ref(_, ty::TyS { kind: ty::Slice(..), .. }, _) => "[T]", diff --git a/src/librustc_lint/builtin.rs b/src/librustc_lint/builtin.rs index d55cbbe19c279..f75d47231559f 100644 --- a/src/librustc_lint/builtin.rs +++ b/src/librustc_lint/builtin.rs @@ -144,7 +144,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BoxPointers { } fn check_expr(&mut self, cx: &LateContext<'_, '_>, e: &hir::Expr<'_>) { - let ty = cx.tables().node_type(e.hir_id); + let ty = cx.typeck_results().node_type(e.hir_id); self.check_heap_type(cx, e.span, ty); } } @@ -161,11 +161,11 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonShorthandFieldPatterns { fn check_pat(&mut self, cx: &LateContext<'_, '_>, pat: &hir::Pat<'_>) { if let PatKind::Struct(ref qpath, field_pats, _) = pat.kind { let variant = cx - .tables() + .typeck_results() .pat_ty(pat) .ty_adt_def() .expect("struct pattern type is not an ADT") - .variant_of_res(cx.tables().qpath_res(qpath, pat.hir_id)); + .variant_of_res(cx.typeck_results().qpath_res(qpath, pat.hir_id)); for fieldpat in field_pats { if fieldpat.is_shorthand { continue; @@ -178,7 +178,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonShorthandFieldPatterns { } if let PatKind::Binding(binding_annot, _, ident, None) = fieldpat.pat.kind { if cx.tcx.find_field_index(ident, &variant) - == Some(cx.tcx.field_index(fieldpat.hir_id, cx.tables())) + == Some(cx.tcx.field_index(fieldpat.hir_id, cx.typeck_results())) { cx.struct_span_lint(NON_SHORTHAND_FIELD_PATTERNS, fieldpat.span, |lint| { let mut err = lint @@ -901,7 +901,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MutableTransmutes { expr: &hir::Expr<'_>, ) -> Option<(Ty<'tcx>, Ty<'tcx>)> { let def = if let hir::ExprKind::Path(ref qpath) = expr.kind { - cx.tables().qpath_res(qpath, expr.hir_id) + cx.typeck_results().qpath_res(qpath, expr.hir_id) } else { return None; }; @@ -909,7 +909,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MutableTransmutes { if !def_id_is_transmute(cx, did) { return None; } - let sig = cx.tables().node_type(expr.hir_id).fn_sig(cx.tcx); + let sig = cx.typeck_results().node_type(expr.hir_id).fn_sig(cx.tcx); let from = sig.inputs().skip_binder()[0]; let to = sig.output().skip_binder(); return Some((from, to)); @@ -1891,7 +1891,8 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidValue { if let hir::ExprKind::Call(ref path_expr, ref args) = expr.kind { // Find calls to `mem::{uninitialized,zeroed}` methods. if let hir::ExprKind::Path(ref qpath) = path_expr.kind { - let def_id = cx.tables().qpath_res(qpath, path_expr.hir_id).opt_def_id()?; + let def_id = + cx.typeck_results().qpath_res(qpath, path_expr.hir_id).opt_def_id()?; if cx.tcx.is_diagnostic_item(sym::mem_zeroed, def_id) { return Some(InitKind::Zeroed); @@ -1905,14 +1906,16 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidValue { } } else if let hir::ExprKind::MethodCall(_, _, ref args, _) = expr.kind { // Find problematic calls to `MaybeUninit::assume_init`. - let def_id = cx.tables().type_dependent_def_id(expr.hir_id)?; + let def_id = cx.typeck_results().type_dependent_def_id(expr.hir_id)?; if cx.tcx.is_diagnostic_item(sym::assume_init, def_id) { // This is a call to *some* method named `assume_init`. // See if the `self` parameter is one of the dangerous constructors. if let hir::ExprKind::Call(ref path_expr, _) = args[0].kind { if let hir::ExprKind::Path(ref qpath) = path_expr.kind { - let def_id = - cx.tables().qpath_res(qpath, path_expr.hir_id).opt_def_id()?; + let def_id = cx + .typeck_results() + .qpath_res(qpath, path_expr.hir_id) + .opt_def_id()?; if cx.tcx.is_diagnostic_item(sym::maybe_uninit_zeroed, def_id) { return Some(InitKind::Zeroed); @@ -2025,7 +2028,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidValue { // This conjures an instance of a type out of nothing, // using zeroed or uninitialized memory. // We are extremely conservative with what we warn about. - let conjured_ty = cx.tables().expr_ty(expr); + let conjured_ty = cx.typeck_results().expr_ty(expr); if let Some((msg, span)) = ty_find_init_error(cx.tcx, conjured_ty, init) { cx.struct_span_lint(INVALID_VALUE, expr.span, |lint| { let mut err = lint.build(&format!( diff --git a/src/librustc_lint/context.rs b/src/librustc_lint/context.rs index 0b4ae131af0fc..0a4b23bfd4181 100644 --- a/src/librustc_lint/context.rs +++ b/src/librustc_lint/context.rs @@ -427,14 +427,14 @@ pub struct LateContext<'a, 'tcx> { /// Current body, or `None` if outside a body. pub enclosing_body: Option, - /// Type-checking side-tables for the current body. Access using the - /// `tables` method, which handles querying the tables on demand. + /// Type-checking side-typeck_results for the current body. Access using the + /// `typeck_results` method, which handles querying the typeck_results on demand. // FIXME(eddyb) move all the code accessing internal fields like this, // to this module, to avoid exposing it to lint logic. - pub(super) cached_typeck_tables: Cell>>, + pub(super) cached_typeck_results: Cell>>, - // HACK(eddyb) replace this with having `Option` around `&TypeckTables`. - pub(super) empty_typeck_tables: &'a ty::TypeckTables<'tcx>, + // HACK(eddyb) replace this with having `Option` around `&TypeckResults`. + pub(super) empty_typeck_results: &'a ty::TypeckResults<'tcx>, /// Parameter environment for the item we are in. pub param_env: ty::ParamEnv<'tcx>, @@ -676,19 +676,19 @@ impl LintContext for EarlyContext<'_> { } impl<'a, 'tcx> LateContext<'a, 'tcx> { - /// Gets the type-checking side-tables for the current body, - /// or empty `TypeckTables` if outside a body. - // FIXME(eddyb) return `Option<&'tcx ty::TypeckTables<'tcx>>`, + /// Gets the type-checking side-typeck_results for the current body, + /// or empty `TypeckResults` if outside a body. + // FIXME(eddyb) return `Option<&'tcx ty::TypeckResults<'tcx>>`, // where `None` indicates we're outside a body. - pub fn tables(&self) -> &'a ty::TypeckTables<'tcx> { + pub fn typeck_results(&self) -> &'a ty::TypeckResults<'tcx> { if let Some(body) = self.enclosing_body { - self.cached_typeck_tables.get().unwrap_or_else(|| { - let tables = self.tcx.body_tables(body); - self.cached_typeck_tables.set(Some(tables)); - tables + self.cached_typeck_results.get().unwrap_or_else(|| { + let typeck_results = self.tcx.typeck_body(body); + self.cached_typeck_results.set(Some(typeck_results)); + typeck_results }) } else { - self.empty_typeck_tables + self.empty_typeck_results } } diff --git a/src/librustc_lint/late.rs b/src/librustc_lint/late.rs index ef62d44c4026b..8218f382e3188 100644 --- a/src/librustc_lint/late.rs +++ b/src/librustc_lint/late.rs @@ -107,13 +107,13 @@ impl<'a, 'tcx, T: LateLintPass<'a, 'tcx>> hir_visit::Visitor<'tcx> fn visit_nested_body(&mut self, body_id: hir::BodyId) { let old_enclosing_body = self.context.enclosing_body.replace(body_id); - let old_cached_typeck_tables = self.context.cached_typeck_tables.get(); + let old_cached_typeck_results = self.context.cached_typeck_results.get(); - // HACK(eddyb) avoid trashing `cached_typeck_tables` when we're + // HACK(eddyb) avoid trashing `cached_typeck_results` when we're // nested in `visit_fn`, which may have already resulted in them // being queried. if old_enclosing_body != Some(body_id) { - self.context.cached_typeck_tables.set(None); + self.context.cached_typeck_results.set(None); } let body = self.context.tcx.hir().body(body_id); @@ -122,7 +122,7 @@ impl<'a, 'tcx, T: LateLintPass<'a, 'tcx>> hir_visit::Visitor<'tcx> // See HACK comment above. if old_enclosing_body != Some(body_id) { - self.context.cached_typeck_tables.set(old_cached_typeck_tables); + self.context.cached_typeck_results.set(old_cached_typeck_results); } } @@ -193,16 +193,16 @@ impl<'a, 'tcx, T: LateLintPass<'a, 'tcx>> hir_visit::Visitor<'tcx> span: Span, id: hir::HirId, ) { - // Wrap in tables here, not just in visit_nested_body, + // Wrap in typeck_results here, not just in visit_nested_body, // in order for `check_fn` to be able to use them. let old_enclosing_body = self.context.enclosing_body.replace(body_id); - let old_cached_typeck_tables = self.context.cached_typeck_tables.take(); + let old_cached_typeck_results = self.context.cached_typeck_results.take(); let body = self.context.tcx.hir().body(body_id); lint_callback!(self, check_fn, fk, decl, body, span, id); hir_visit::walk_fn(self, fk, decl, body_id, span, id); lint_callback!(self, check_fn_post, fk, decl, body, span, id); self.context.enclosing_body = old_enclosing_body; - self.context.cached_typeck_tables.set(old_cached_typeck_tables); + self.context.cached_typeck_results.set(old_cached_typeck_results); } fn visit_variant_data( @@ -377,8 +377,8 @@ fn late_lint_mod_pass<'tcx, T: for<'a> LateLintPass<'a, 'tcx>>( let context = LateContext { tcx, enclosing_body: None, - cached_typeck_tables: Cell::new(None), - empty_typeck_tables: &ty::TypeckTables::empty(None), + cached_typeck_results: Cell::new(None), + empty_typeck_results: &ty::TypeckResults::empty(None), param_env: ty::ParamEnv::empty(), access_levels, lint_store: unerased_lint_store(tcx), @@ -426,8 +426,8 @@ fn late_lint_pass_crate<'tcx, T: for<'a> LateLintPass<'a, 'tcx>>(tcx: TyCtxt<'tc let context = LateContext { tcx, enclosing_body: None, - cached_typeck_tables: Cell::new(None), - empty_typeck_tables: &ty::TypeckTables::empty(None), + cached_typeck_results: Cell::new(None), + empty_typeck_results: &ty::TypeckResults::empty(None), param_env: ty::ParamEnv::empty(), access_levels, lint_store: unerased_lint_store(tcx), diff --git a/src/librustc_lint/types.rs b/src/librustc_lint/types.rs index d0275a0dd0dcb..5e1d42e48616b 100644 --- a/src/librustc_lint/types.rs +++ b/src/librustc_lint/types.rs @@ -168,7 +168,7 @@ fn report_bin_hex_error( repr_str, val, t, actually, t )); if let Some(sugg_ty) = - get_type_suggestion(&cx.tables().node_type(expr.hir_id), val, negative) + get_type_suggestion(&cx.typeck_results().node_type(expr.hir_id), val, negative) { if let Some(pos) = repr_str.chars().position(|c| c == 'i' || c == 'u') { let (sans_suffix, _) = repr_str.split_at(pos); @@ -302,7 +302,7 @@ fn lint_uint_literal<'a, 'tcx>( if let Node::Expr(par_e) = cx.tcx.hir().get(parent_id) { match par_e.kind { hir::ExprKind::Cast(..) => { - if let ty::Char = cx.tables().expr_ty(par_e).kind { + if let ty::Char = cx.typeck_results().expr_ty(par_e).kind { cx.struct_span_lint(OVERFLOWING_LITERALS, par_e.span, |lint| { lint.build("only `u8` can be cast into `char`") .span_suggestion( @@ -353,7 +353,7 @@ fn lint_literal<'a, 'tcx>( e: &'tcx hir::Expr<'tcx>, lit: &hir::Lit, ) { - match cx.tables().node_type(e.hir_id).kind { + match cx.typeck_results().node_type(e.hir_id).kind { ty::Int(t) => { match lit.node { ast::LitKind::Int(v, ast::LitIntType::Signed(_) | ast::LitIntType::Unsuffixed) => { @@ -449,7 +449,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeLimits { // Normalize the binop so that the literal is always on the RHS in // the comparison let norm_binop = if swap { rev_binop(binop) } else { binop }; - match cx.tables().node_type(expr.hir_id).kind { + match cx.typeck_results().node_type(expr.hir_id).kind { ty::Int(int_ty) => { let (min, max) = int_ty_range(int_ty); let lit_val: i128 = match lit.kind { diff --git a/src/librustc_lint/unused.rs b/src/librustc_lint/unused.rs index 506ac77894a41..581cef15c3b92 100644 --- a/src/librustc_lint/unused.rs +++ b/src/librustc_lint/unused.rs @@ -46,7 +46,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedResults { return; } - let ty = cx.tables().expr_ty(&expr); + let ty = cx.typeck_results().expr_ty(&expr); let type_permits_lack_of_use = check_must_use_ty(cx, ty, &expr, s.span, "", "", 1); let mut fn_warned = false; @@ -55,7 +55,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedResults { hir::ExprKind::Call(ref callee, _) => { match callee.kind { hir::ExprKind::Path(ref qpath) => { - match cx.tables().qpath_res(qpath, callee.hir_id) { + match cx.typeck_results().qpath_res(qpath, callee.hir_id) { Res::Def(DefKind::Fn | DefKind::AssocFn, def_id) => Some(def_id), // `Res::Local` if it was a closure, for which we // do not currently support must-use linting @@ -65,7 +65,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedResults { _ => None, } } - hir::ExprKind::MethodCall(..) => cx.tables().type_dependent_def_id(expr.hir_id), + hir::ExprKind::MethodCall(..) => cx.typeck_results().type_dependent_def_id(expr.hir_id), _ => None, }; if let Some(def_id) = maybe_def_id { @@ -950,7 +950,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedAllocation { _ => return, } - for adj in cx.tables().expr_adjustments(e) { + for adj in cx.typeck_results().expr_adjustments(e) { if let adjustment::Adjust::Borrow(adjustment::AutoBorrow::Ref(_, m)) = adj.kind { cx.struct_span_lint(UNUSED_ALLOCATION, e.span, |lint| { let msg = match m { diff --git a/src/librustc_metadata/rmeta/decoder/cstore_impl.rs b/src/librustc_metadata/rmeta/decoder/cstore_impl.rs index 1b168bf01178c..abbe45fe02e25 100644 --- a/src/librustc_metadata/rmeta/decoder/cstore_impl.rs +++ b/src/librustc_metadata/rmeta/decoder/cstore_impl.rs @@ -239,6 +239,8 @@ provide! { <'tcx> tcx, def_id, other, cdata, syms } + + crate_extern_paths => { cdata.source().paths().cloned().collect() } } pub fn provide(providers: &mut Providers<'_>) { diff --git a/src/librustc_metadata/rmeta/encoder.rs b/src/librustc_metadata/rmeta/encoder.rs index fb4fee402abfb..5f902d540cdf2 100644 --- a/src/librustc_metadata/rmeta/encoder.rs +++ b/src/librustc_metadata/rmeta/encoder.rs @@ -1369,9 +1369,9 @@ impl EncodeContext<'tcx> { debug!("EncodeContext::encode_info_for_closure({:?})", def_id); // NOTE(eddyb) `tcx.type_of(def_id)` isn't used because it's fully generic, - // including on the signature, which is inferred in `typeck_tables_of. + // including on the signature, which is inferred in `typeck. let hir_id = self.tcx.hir().as_local_hir_id(def_id); - let ty = self.tcx.typeck_tables_of(def_id).node_type(hir_id); + let ty = self.tcx.typeck(def_id).node_type(hir_id); record!(self.tables.kind[def_id.to_def_id()] <- match ty.kind { ty::Generator(..) => { diff --git a/src/librustc_middle/arena.rs b/src/librustc_middle/arena.rs index 4f1889aeb162a..c18b038a726f9 100644 --- a/src/librustc_middle/arena.rs +++ b/src/librustc_middle/arena.rs @@ -14,7 +14,7 @@ macro_rules! arena_types { [] layouts: rustc_target::abi::Layout, rustc_target::abi::Layout; // AdtDef are interned and compared by address [] adt_def: rustc_middle::ty::AdtDef, rustc_middle::ty::AdtDef; - [decode] tables: rustc_middle::ty::TypeckTables<$tcx>, rustc_middle::ty::TypeckTables<'_x>; + [decode] typeck_results: rustc_middle::ty::TypeckResults<$tcx>, rustc_middle::ty::TypeckResults<'_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, rustc_hir::def_id::DefIdSet; diff --git a/src/librustc_middle/mir/query.rs b/src/librustc_middle/mir/query.rs index 9ad79230a4f6d..9087add4309db 100644 --- a/src/librustc_middle/mir/query.rs +++ b/src/librustc_middle/mir/query.rs @@ -138,7 +138,7 @@ impl Debug for GeneratorLayout<'_> { #[derive(Debug, RustcEncodable, RustcDecodable, HashStable)] pub struct BorrowCheckResult<'tcx> { /// All the opaque types that are restricted to concrete types - /// by this function. Unlike the value in `TypeckTables`, this has + /// by this function. Unlike the value in `TypeckResults`, this has /// unerased regions. pub concrete_opaque_types: FxHashMap>, pub closure_requirements: Option>, diff --git a/src/librustc_middle/query/mod.rs b/src/librustc_middle/query/mod.rs index ba5a8c3ec2052..e4f8914c6a15d 100644 --- a/src/librustc_middle/query/mod.rs +++ b/src/librustc_middle/query/mod.rs @@ -531,19 +531,19 @@ rustc_queries! { desc { "type-checking all item bodies" } } - query typeck_tables_of(key: LocalDefId) -> &'tcx ty::TypeckTables<'tcx> { + query typeck(key: LocalDefId) -> &'tcx ty::TypeckResults<'tcx> { desc { |tcx| "type-checking `{}`", tcx.def_path_str(key.to_def_id()) } cache_on_disk_if { true } } - query diagnostic_only_typeck_tables_of(key: LocalDefId) -> &'tcx ty::TypeckTables<'tcx> { + query diagnostic_only_typeck(key: LocalDefId) -> &'tcx ty::TypeckResults<'tcx> { desc { |tcx| "type-checking `{}`", tcx.def_path_str(key.to_def_id()) } cache_on_disk_if { true } load_cached(tcx, id) { - let typeck_tables: Option> = tcx + let typeck_results: Option> = tcx .queries.on_disk_cache .try_load_query_result(tcx, id); - typeck_tables.map(|x| &*tcx.arena.alloc(x)) + typeck_results.map(|x| &*tcx.arena.alloc(x)) } } } @@ -556,7 +556,7 @@ rustc_queries! { } TypeChecking { - query has_typeck_tables(def_id: DefId) -> bool { + query has_typeck_results(def_id: DefId) -> bool { desc { |tcx| "checking whether `{}` has a body", tcx.def_path_str(def_id) } } @@ -1042,6 +1042,10 @@ rustc_queries! { eval_always desc { "looking up the extra filename for a crate" } } + query crate_extern_paths(_: CrateNum) -> Vec { + eval_always + desc { "looking up the paths for extern crates" } + } } TypeChecking { diff --git a/src/librustc_middle/ty/context.rs b/src/librustc_middle/ty/context.rs index e2f601371b1ee..9f5f202986db8 100644 --- a/src/librustc_middle/ty/context.rs +++ b/src/librustc_middle/ty/context.rs @@ -193,13 +193,13 @@ pub struct LocalTableInContext<'a, V> { } /// Validate that the given HirId (respectively its `local_id` part) can be -/// safely used as a key in the tables of a TypeckTable. For that to be +/// safely used as a key in the typeck_results of a TypeckTable. For that to be /// the case, the HirId must have the same `owner` as all the other IDs in /// this table (signified by `hir_owner`). Otherwise the HirId /// would be in a different frame of reference and using its `local_id` /// would result in lookup errors, or worse, in silently wrong data being /// stored/returned. -fn validate_hir_id_for_typeck_tables( +fn validate_hir_id_for_typeck_results( hir_owner: Option, hir_id: hir::HirId, mut_access: bool, @@ -208,7 +208,7 @@ fn validate_hir_id_for_typeck_tables( if hir_id.owner != hir_owner { ty::tls::with(|tcx| { bug!( - "node {} with HirId::owner {:?} cannot be placed in TypeckTables with hir_owner {:?}", + "node {} with HirId::owner {:?} cannot be placed in TypeckResults with hir_owner {:?}", tcx.hir().node_to_string(hir_id), hir_id.owner, hir_owner @@ -216,25 +216,25 @@ fn validate_hir_id_for_typeck_tables( }); } } else { - // We use "Null Object" TypeckTables in some of the analysis passes. + // We use "Null Object" TypeckResults in some of the analysis passes. // These are just expected to be empty and their `hir_owner` is // `None`. Therefore we cannot verify whether a given `HirId` would // be a valid key for the given table. Instead we make sure that // nobody tries to write to such a Null Object table. if mut_access { - bug!("access to invalid TypeckTables") + bug!("access to invalid TypeckResults") } } } impl<'a, V> LocalTableInContext<'a, V> { pub fn contains_key(&self, id: hir::HirId) -> bool { - validate_hir_id_for_typeck_tables(self.hir_owner, id, false); + validate_hir_id_for_typeck_results(self.hir_owner, id, false); self.data.contains_key(&id.local_id) } pub fn get(&self, id: hir::HirId) -> Option<&V> { - validate_hir_id_for_typeck_tables(self.hir_owner, id, false); + validate_hir_id_for_typeck_results(self.hir_owner, id, false); self.data.get(&id.local_id) } @@ -258,22 +258,22 @@ pub struct LocalTableInContextMut<'a, V> { impl<'a, V> LocalTableInContextMut<'a, V> { pub fn get_mut(&mut self, id: hir::HirId) -> Option<&mut V> { - validate_hir_id_for_typeck_tables(self.hir_owner, id, true); + validate_hir_id_for_typeck_results(self.hir_owner, id, true); self.data.get_mut(&id.local_id) } pub fn entry(&mut self, id: hir::HirId) -> Entry<'_, hir::ItemLocalId, V> { - validate_hir_id_for_typeck_tables(self.hir_owner, id, true); + validate_hir_id_for_typeck_results(self.hir_owner, id, true); self.data.entry(id.local_id) } pub fn insert(&mut self, id: hir::HirId, val: V) -> Option { - validate_hir_id_for_typeck_tables(self.hir_owner, id, true); + validate_hir_id_for_typeck_results(self.hir_owner, id, true); self.data.insert(id.local_id, val) } pub fn remove(&mut self, id: hir::HirId) -> Option { - validate_hir_id_for_typeck_tables(self.hir_owner, id, true); + validate_hir_id_for_typeck_results(self.hir_owner, id, true); self.data.remove(&id.local_id) } } @@ -322,7 +322,7 @@ pub struct GeneratorInteriorTypeCause<'tcx> { } #[derive(RustcEncodable, RustcDecodable, Debug)] -pub struct TypeckTables<'tcx> { +pub struct TypeckResults<'tcx> { /// The `HirId::owner` all `ItemLocalId`s in this table are relative to. pub hir_owner: Option, @@ -431,9 +431,9 @@ pub struct TypeckTables<'tcx> { pub generator_interior_types: Vec>, } -impl<'tcx> TypeckTables<'tcx> { - pub fn empty(hir_owner: Option) -> TypeckTables<'tcx> { - TypeckTables { +impl<'tcx> TypeckResults<'tcx> { + pub fn empty(hir_owner: Option) -> TypeckResults<'tcx> { + TypeckResults { hir_owner, type_dependent_defs: Default::default(), field_indices: Default::default(), @@ -474,7 +474,7 @@ impl<'tcx> TypeckTables<'tcx> { } pub fn type_dependent_def(&self, id: HirId) -> Option<(DefKind, DefId)> { - validate_hir_id_for_typeck_tables(self.hir_owner, id, false); + validate_hir_id_for_typeck_results(self.hir_owner, id, false); self.type_dependent_defs.get(&id.local_id).cloned().and_then(|r| r.ok()) } @@ -521,7 +521,7 @@ impl<'tcx> TypeckTables<'tcx> { } pub fn node_type_opt(&self, id: hir::HirId) -> Option> { - validate_hir_id_for_typeck_tables(self.hir_owner, id, false); + validate_hir_id_for_typeck_results(self.hir_owner, id, false); self.node_types.get(&id.local_id).cloned() } @@ -530,12 +530,12 @@ impl<'tcx> TypeckTables<'tcx> { } pub fn node_substs(&self, id: hir::HirId) -> SubstsRef<'tcx> { - validate_hir_id_for_typeck_tables(self.hir_owner, id, false); + validate_hir_id_for_typeck_results(self.hir_owner, id, false); self.node_substs.get(&id.local_id).cloned().unwrap_or_else(|| InternalSubsts::empty()) } pub fn node_substs_opt(&self, id: hir::HirId) -> Option> { - validate_hir_id_for_typeck_tables(self.hir_owner, id, false); + validate_hir_id_for_typeck_results(self.hir_owner, id, false); self.node_substs.get(&id.local_id).cloned() } @@ -578,7 +578,7 @@ impl<'tcx> TypeckTables<'tcx> { } pub fn expr_adjustments(&self, expr: &hir::Expr<'_>) -> &[ty::adjustment::Adjustment<'tcx>] { - validate_hir_id_for_typeck_tables(self.hir_owner, expr.hir_id, false); + validate_hir_id_for_typeck_results(self.hir_owner, expr.hir_id, false); self.adjustments.get(&expr.hir_id.local_id).map_or(&[], |a| &a[..]) } @@ -657,7 +657,7 @@ impl<'tcx> TypeckTables<'tcx> { } pub fn is_coercion_cast(&self, hir_id: hir::HirId) -> bool { - validate_hir_id_for_typeck_tables(self.hir_owner, hir_id, true); + validate_hir_id_for_typeck_results(self.hir_owner, hir_id, true); self.coercion_casts.contains(&hir_id.local_id) } @@ -670,9 +670,9 @@ impl<'tcx> TypeckTables<'tcx> { } } -impl<'a, 'tcx> HashStable> for TypeckTables<'tcx> { +impl<'a, 'tcx> HashStable> for TypeckResults<'tcx> { fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) { - let ty::TypeckTables { + let ty::TypeckResults { hir_owner, ref type_dependent_defs, ref field_indices, @@ -1049,6 +1049,7 @@ impl<'tcx> TyCtxt<'tcx> { Some(attr) => attr, None => return Bound::Unbounded, }; + debug!("layout_scalar_valid_range: attr={:?}", attr); for meta in attr.meta_item_list().expect("rustc_layout_scalar_valid_range takes args") { match meta.literal().expect("attribute takes lit").kind { ast::LitKind::Int(a, _) => return Bound::Included(a), @@ -1099,19 +1100,19 @@ impl<'tcx> TyCtxt<'tcx> { providers[LOCAL_CRATE] = local_providers; let def_path_hash_to_def_id = if s.opts.build_dep_graph() { - let def_path_tables = crates + let def_path_typeck_results = crates .iter() .map(|&cnum| (cnum, cstore.def_path_table(cnum))) .chain(iter::once((LOCAL_CRATE, definitions.def_path_table()))); // Precompute the capacity of the hashmap so we don't have to // re-allocate when populating it. - let capacity = def_path_tables.clone().map(|(_, t)| t.size()).sum::(); + let capacity = def_path_typeck_results.clone().map(|(_, t)| t.size()).sum::(); let mut map: FxHashMap<_, _> = FxHashMap::with_capacity_and_hasher(capacity, ::std::default::Default::default()); - for (cnum, def_path_table) in def_path_tables { + for (cnum, def_path_table) in def_path_typeck_results { def_path_table.add_def_path_hashes_to(cnum, &mut map); } diff --git a/src/librustc_middle/ty/mod.rs b/src/librustc_middle/ty/mod.rs index 03aab2c0f9f2c..640809b7c8ffb 100644 --- a/src/librustc_middle/ty/mod.rs +++ b/src/librustc_middle/ty/mod.rs @@ -73,7 +73,7 @@ pub use self::context::{ UserType, UserTypeAnnotationIndex, }; pub use self::context::{ - CtxtInterners, GeneratorInteriorTypeCause, GlobalCtxt, Lift, TypeckTables, + CtxtInterners, GeneratorInteriorTypeCause, GlobalCtxt, Lift, TypeckResults, }; pub use self::instance::{Instance, InstanceDef}; @@ -2568,8 +2568,8 @@ pub enum ImplOverlapKind { } impl<'tcx> TyCtxt<'tcx> { - pub fn body_tables(self, body: hir::BodyId) -> &'tcx TypeckTables<'tcx> { - self.typeck_tables_of(self.hir().body_owner_def_id(body)) + pub fn typeck_body(self, body: hir::BodyId) -> &'tcx TypeckResults<'tcx> { + self.typeck(self.hir().body_owner_def_id(body)) } /// Returns an iterator of the `DefId`s for all body-owners in this @@ -2616,8 +2616,8 @@ impl<'tcx> TyCtxt<'tcx> { is_associated_item.then(|| self.associated_item(def_id)) } - pub fn field_index(self, hir_id: hir::HirId, tables: &TypeckTables<'_>) -> usize { - tables.field_indices().get(hir_id).cloned().expect("no index for a field") + pub fn field_index(self, hir_id: hir::HirId, typeck_results: &TypeckResults<'_>) -> usize { + typeck_results.field_indices().get(hir_id).cloned().expect("no index for a field") } pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option { diff --git a/src/librustc_middle/ty/query/mod.rs b/src/librustc_middle/ty/query/mod.rs index 35d19b7603faf..2ad49b1acce43 100644 --- a/src/librustc_middle/ty/query/mod.rs +++ b/src/librustc_middle/ty/query/mod.rs @@ -57,6 +57,7 @@ use rustc_span::{Span, DUMMY_SP}; use std::borrow::Cow; use std::collections::BTreeMap; use std::ops::Deref; +use std::path::PathBuf; use std::sync::Arc; #[macro_use] diff --git a/src/librustc_middle/ty/query/on_disk_cache.rs b/src/librustc_middle/ty/query/on_disk_cache.rs index c84a7c38d0a0e..1ba305e63fb9c 100644 --- a/src/librustc_middle/ty/query/on_disk_cache.rs +++ b/src/librustc_middle/ty/query/on_disk_cache.rs @@ -35,7 +35,7 @@ const TAG_INVALID_SPAN: u8 = 1; /// Provides an interface to incremental compilation data cached from the /// previous compilation session. This data will eventually include the results -/// of a few selected queries (like `typeck_tables_of` and `mir_optimized`) and +/// of a few selected queries (like `typeck` and `mir_optimized`) and /// any diagnostics that have been emitted during a query. pub struct OnDiskCache<'sess> { // The complete cache data in serialized form. diff --git a/src/librustc_middle/ty/util.rs b/src/librustc_middle/ty/util.rs index 67ad7ee708267..adba45facc9b4 100644 --- a/src/librustc_middle/ty/util.rs +++ b/src/librustc_middle/ty/util.rs @@ -471,8 +471,8 @@ impl<'tcx> TyCtxt<'tcx> { /// This is a significant `DefId` because, when we do /// type-checking, we type-check this fn item and all of its /// (transitive) closures together. Therefore, when we fetch the - /// `typeck_tables_of` the closure, for example, we really wind up - /// fetching the `typeck_tables_of` the enclosing fn item. + /// `typeck` the closure, for example, we really wind up + /// fetching the `typeck` the enclosing fn item. pub fn closure_base_def_id(self, def_id: DefId) -> DefId { let mut def_id = def_id; while self.is_closure(def_id) { diff --git a/src/librustc_mir/borrow_check/diagnostics/conflict_errors.rs b/src/librustc_mir/borrow_check/diagnostics/conflict_errors.rs index 17846055f6c96..8e7c97c4a1bac 100644 --- a/src/librustc_mir/borrow_check/diagnostics/conflict_errors.rs +++ b/src/librustc_mir/borrow_check/diagnostics/conflict_errors.rs @@ -262,7 +262,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { .ty; let needs_note = match ty.kind { ty::Closure(id, _) => { - let tables = self.infcx.tcx.typeck_tables_of(id.expect_local()); + let tables = self.infcx.tcx.typeck(id.expect_local()); let hir_id = self.infcx.tcx.hir().as_local_hir_id(id.expect_local()); tables.closure_kind_origins().get(hir_id).is_none() @@ -966,12 +966,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { .opt_name(fn_hir_id) .map(|name| format!("function `{}`", name)) .unwrap_or_else(|| { - match &self - .infcx - .tcx - .typeck_tables_of(self.mir_def_id) - .node_type(fn_hir_id) - .kind + match &self.infcx.tcx.typeck(self.mir_def_id).node_type(fn_hir_id).kind { ty::Closure(..) => "enclosing closure", ty::Generator(..) => "enclosing generator", diff --git a/src/librustc_mir/borrow_check/diagnostics/mod.rs b/src/librustc_mir/borrow_check/diagnostics/mod.rs index e94952e1c543c..d8f6abd92f6b8 100644 --- a/src/librustc_mir/borrow_check/diagnostics/mod.rs +++ b/src/librustc_mir/borrow_check/diagnostics/mod.rs @@ -107,7 +107,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { let hir_id = self.infcx.tcx.hir().as_local_hir_id(did); if let Some((span, name)) = - self.infcx.tcx.typeck_tables_of(did).closure_kind_origins().get(hir_id) + self.infcx.tcx.typeck(did).closure_kind_origins().get(hir_id) { diag.span_note( *span, @@ -130,7 +130,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { let hir_id = self.infcx.tcx.hir().as_local_hir_id(did); if let Some((span, name)) = - self.infcx.tcx.typeck_tables_of(did).closure_kind_origins().get(hir_id) + self.infcx.tcx.typeck(did).closure_kind_origins().get(hir_id) { diag.span_note( *span, diff --git a/src/librustc_mir/borrow_check/diagnostics/mutability_errors.rs b/src/librustc_mir/borrow_check/diagnostics/mutability_errors.rs index b4bc89e827daa..ef0fe71abecb2 100644 --- a/src/librustc_mir/borrow_check/diagnostics/mutability_errors.rs +++ b/src/librustc_mir/borrow_check/diagnostics/mutability_errors.rs @@ -507,7 +507,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { .map(|(pos, _)| pos) .next(); let def_id = hir.local_def_id(item_id); - let tables = self.infcx.tcx.typeck_tables_of(def_id); + let tables = self.infcx.tcx.typeck(def_id); if let Some(ty::FnDef(def_id, _)) = tables.node_type_opt(func.hir_id).as_ref().map(|ty| &ty.kind) { diff --git a/src/librustc_mir/borrow_check/mod.rs b/src/librustc_mir/borrow_check/mod.rs index 83691d439eb81..78b595f83a02e 100644 --- a/src/librustc_mir/borrow_check/mod.rs +++ b/src/librustc_mir/borrow_check/mod.rs @@ -135,7 +135,7 @@ fn do_mir_borrowck<'a, 'tcx>( } // Gather the upvars of a closure, if any. - let tables = tcx.typeck_tables_of(def_id); + let tables = tcx.typeck(def_id); if let Some(ErrorReported) = tables.tainted_by_errors { infcx.set_tainted_by_errors(); } diff --git a/src/librustc_mir/borrow_check/type_check/input_output.rs b/src/librustc_mir/borrow_check/type_check/input_output.rs index edd2dc3c2de55..736c6c7a08aca 100644 --- a/src/librustc_mir/borrow_check/type_check/input_output.rs +++ b/src/librustc_mir/borrow_check/type_check/input_output.rs @@ -36,7 +36,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { if !self.tcx().is_closure(self.mir_def_id.to_def_id()) { user_provided_sig = None; } else { - let typeck_tables = self.tcx().typeck_tables_of(self.mir_def_id); + let typeck_tables = self.tcx().typeck(self.mir_def_id); user_provided_sig = match typeck_tables.user_provided_sigs.get(&self.mir_def_id.to_def_id()) { None => None, diff --git a/src/librustc_mir/borrow_check/type_check/mod.rs b/src/librustc_mir/borrow_check/type_check/mod.rs index 0e35cafb9f3e9..53955a47ad1f4 100644 --- a/src/librustc_mir/borrow_check/type_check/mod.rs +++ b/src/librustc_mir/borrow_check/type_check/mod.rs @@ -1239,7 +1239,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { let param_env = self.param_env; let body = self.body; let concrete_opaque_types = - &tcx.typeck_tables_of(anon_owner_def_id.expect_local()).concrete_opaque_types; + &tcx.typeck(anon_owner_def_id.expect_local()).concrete_opaque_types; let mut opaque_type_values = Vec::new(); debug!("eq_opaque_type_and_type: mir_def_id={:?}", self.mir_def_id); diff --git a/src/librustc_mir/borrow_check/universal_regions.rs b/src/librustc_mir/borrow_check/universal_regions.rs index 7b292ee71f99d..0437540afa577 100644 --- a/src/librustc_mir/borrow_check/universal_regions.rs +++ b/src/librustc_mir/borrow_check/universal_regions.rs @@ -514,8 +514,8 @@ impl<'cx, 'tcx> UniversalRegionsBuilder<'cx, 'tcx> { let defining_ty = if self.mir_def_id.to_def_id() == closure_base_def_id { tcx.type_of(closure_base_def_id) } else { - let tables = tcx.typeck_tables_of(self.mir_def_id); - tables.node_type(self.mir_hir_id) + let typeck_results = tcx.typeck(self.mir_def_id); + typeck_results.node_type(self.mir_hir_id) }; debug!("defining_ty (pre-replacement): {:?}", defining_ty); diff --git a/src/librustc_mir/const_eval/eval_queries.rs b/src/librustc_mir/const_eval/eval_queries.rs index d62300b3f5541..5eebd246954ef 100644 --- a/src/librustc_mir/const_eval/eval_queries.rs +++ b/src/librustc_mir/const_eval/eval_queries.rs @@ -291,8 +291,8 @@ pub fn const_eval_raw_provider<'tcx>( let def_id = cid.instance.def.def_id(); if let Some(def_id) = def_id.as_local() { - if tcx.has_typeck_tables(def_id) { - if let Some(error_reported) = tcx.typeck_tables_of(def_id).tainted_by_errors { + if tcx.has_typeck_results(def_id) { + if let Some(error_reported) = tcx.typeck(def_id).tainted_by_errors { return Err(ErrorHandled::Reported(error_reported)); } } diff --git a/src/librustc_mir/interpret/eval_context.rs b/src/librustc_mir/interpret/eval_context.rs index 602876e3de168..44e7e236cfdc2 100644 --- a/src/librustc_mir/interpret/eval_context.rs +++ b/src/librustc_mir/interpret/eval_context.rs @@ -396,8 +396,8 @@ 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.has_typeck_results(did) { + if let Some(error_reported) = self.tcx.typeck(did).tainted_by_errors { throw_inval!(TypeckError(error_reported)) } } diff --git a/src/librustc_mir/interpret/validity.rs b/src/librustc_mir/interpret/validity.rs index 3bb9ba3712058..755d05407a648 100644 --- a/src/librustc_mir/interpret/validity.rs +++ b/src/librustc_mir/interpret/validity.rs @@ -226,7 +226,7 @@ impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValidityVisitor<'rt, 'mir, ' ty::Closure(def_id, _) | ty::Generator(def_id, _, _) => { let mut name = None; if let Some(def_id) = def_id.as_local() { - let tables = self.ecx.tcx.typeck_tables_of(def_id); + let tables = self.ecx.tcx.typeck(def_id); if let Some(upvars) = tables.closure_captures.get(&def_id.to_def_id()) { // Sometimes the index is beyond the number of upvars (seen // for a generator). diff --git a/src/librustc_mir_build/build/mod.rs b/src/librustc_mir_build/build/mod.rs index e69f6b30abd5c..e9a4387a80513 100644 --- a/src/librustc_mir_build/build/mod.rs +++ b/src/librustc_mir_build/build/mod.rs @@ -62,12 +62,12 @@ fn mir_build(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Body<'_> { tcx.infer_ctxt().enter(|infcx| { let cx = Cx::new(&infcx, id); - let body = if let Some(ErrorReported) = cx.tables().tainted_by_errors { + let body = if let Some(ErrorReported) = cx.typeck_results().tainted_by_errors { build::construct_error(cx, body_id) } else if cx.body_owner_kind.is_fn_or_closure() { // fetch the fully liberated fn signature (that is, all bound // types/lifetimes replaced) - let fn_sig = cx.tables().liberated_fn_sigs()[id]; + let fn_sig = cx.typeck_results().liberated_fn_sigs()[id]; let fn_def_id = tcx.hir().local_def_id(id); let safety = match fn_sig.unsafety { @@ -86,7 +86,7 @@ fn mir_build(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Body<'_> { vec![ArgInfo(liberated_closure_env_ty(tcx, id, body_id), None, None, None)] } ty::Generator(..) => { - let gen_ty = tcx.body_tables(body_id).node_type(id); + let gen_ty = tcx.typeck_body(body_id).node_type(id); // The resume argument may be missing, in that case we need to provide it here. // It will always be `()` in this case. @@ -141,7 +141,7 @@ fn mir_build(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Body<'_> { let arguments = implicit_argument.into_iter().chain(explicit_arguments); let (yield_ty, return_ty) = if body.generator_kind.is_some() { - let gen_ty = tcx.body_tables(body_id).node_type(id); + let gen_ty = tcx.typeck_body(body_id).node_type(id); let gen_sig = match gen_ty.kind { ty::Generator(_, gen_substs, ..) => gen_substs.as_generator().sig(), _ => span_bug!(tcx.hir().span(id), "generator w/o generator type: {:?}", ty), @@ -176,7 +176,7 @@ fn mir_build(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Body<'_> { // place to be the type of the constant because NLL typeck will // equate them. - let return_ty = cx.tables().node_type(id); + let return_ty = cx.typeck_results().node_type(id); build::construct_const(cx, body_id, return_ty, return_ty_span) }; @@ -208,7 +208,7 @@ fn liberated_closure_env_ty( closure_expr_id: hir::HirId, body_id: hir::BodyId, ) -> Ty<'_> { - let closure_ty = tcx.body_tables(body_id).node_type(closure_expr_id); + let closure_ty = tcx.typeck_body(body_id).node_type(closure_expr_id); let (closure_def_id, closure_substs) = match closure_ty.kind { ty::Closure(closure_def_id, closure_substs) => (closure_def_id, closure_substs), @@ -810,14 +810,14 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { let tcx = self.hir.tcx(); let tcx_hir = tcx.hir(); - let hir_tables = self.hir.tables(); + let hir_typeck_results = self.hir.typeck_results(); // In analyze_closure() in upvar.rs we gathered a list of upvars used by a - // indexed closure and we stored in a map called closure_captures in TypeckTables + // indexed closure and we stored in a map called closure_captures in TypeckResults // with the closure's DefId. Here, we run through that vec of UpvarIds for // the given closure and use the necessary information to create upvar // debuginfo and to fill `self.upvar_mutbls`. - if let Some(upvars) = hir_tables.closure_captures.get(&fn_def_id) { + if let Some(upvars) = hir_typeck_results.closure_captures.get(&fn_def_id) { let closure_env_arg = Local::new(1); let mut closure_env_projs = vec![]; let mut closure_ty = self.local_decls[closure_env_arg].ty; @@ -835,14 +835,16 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { self.upvar_mutbls = upvars_with_tys .enumerate() .map(|(i, ((&var_id, &upvar_id), ty))| { - let capture = hir_tables.upvar_capture(upvar_id); + let capture = hir_typeck_results.upvar_capture(upvar_id); let mut mutability = Mutability::Not; let mut name = kw::Invalid; if let Some(Node::Binding(pat)) = tcx_hir.find(var_id) { if let hir::PatKind::Binding(_, _, ident, _) = pat.kind { name = ident.name; - match hir_tables.extract_binding_mode(tcx.sess, pat.hir_id, pat.span) { + match hir_typeck_results + .extract_binding_mode(tcx.sess, pat.hir_id, pat.span) + { Some(ty::BindByValue(hir::Mutability::Mut)) => { mutability = Mutability::Mut; } diff --git a/src/librustc_mir_build/hair/cx/block.rs b/src/librustc_mir_build/hair/cx/block.rs index c7b53024666d9..a5381781d1d80 100644 --- a/src/librustc_mir_build/hair/cx/block.rs +++ b/src/librustc_mir_build/hair/cx/block.rs @@ -65,7 +65,7 @@ fn mirror_stmts<'a, 'tcx>( let mut pattern = cx.pattern_from_hir(&local.pat); if let Some(ty) = &local.ty { - if let Some(&user_ty) = cx.tables.user_provided_types().get(ty.hir_id) { + if let Some(&user_ty) = cx.typeck_results.user_provided_types().get(ty.hir_id) { debug!("mirror_stmts: user_ty={:?}", user_ty); pattern = Pat { ty: pattern.ty, @@ -105,7 +105,7 @@ crate fn to_expr_ref<'a, 'tcx>( cx: &mut Cx<'a, 'tcx>, block: &'tcx hir::Block<'tcx>, ) -> ExprRef<'tcx> { - let block_ty = cx.tables().node_type(block.hir_id); + let block_ty = cx.typeck_results().node_type(block.hir_id); let temp_lifetime = cx.region_scope_tree.temporary_scope(block.hir_id.local_id); let expr = Expr { ty: block_ty, diff --git a/src/librustc_mir_build/hair/cx/expr.rs b/src/librustc_mir_build/hair/cx/expr.rs index d36990684e03b..31b6f48a0e465 100644 --- a/src/librustc_mir_build/hair/cx/expr.rs +++ b/src/librustc_mir_build/hair/cx/expr.rs @@ -27,7 +27,7 @@ impl<'tcx> Mirror<'tcx> for &'tcx hir::Expr<'tcx> { let mut expr = make_mirror_unadjusted(cx, self); // Now apply adjustments, if any. - for adjustment in cx.tables().expr_adjustments(self) { + for adjustment in cx.typeck_results().expr_adjustments(self) { debug!("make_mirror: expr={:?} applying adjustment={:?}", expr, adjustment); expr = apply_adjustment(cx, self, expr, adjustment); } @@ -134,7 +134,7 @@ fn make_mirror_unadjusted<'a, 'tcx>( cx: &mut Cx<'a, 'tcx>, expr: &'tcx hir::Expr<'tcx>, ) -> Expr<'tcx> { - let expr_ty = cx.tables().expr_ty(expr); + let expr_ty = cx.typeck_results().expr_ty(expr); let temp_lifetime = cx.region_scope_tree.temporary_scope(expr.hir_id.local_id); let kind = match expr.kind { @@ -147,7 +147,7 @@ fn make_mirror_unadjusted<'a, 'tcx>( } hir::ExprKind::Call(ref fun, ref args) => { - if cx.tables().is_method_call(expr) { + if cx.typeck_results().is_method_call(expr) { // The callee is something implementing Fn, FnMut, or FnOnce. // Find the actual method implementation being called and // build the appropriate UFCS call expression with the @@ -157,7 +157,7 @@ fn make_mirror_unadjusted<'a, 'tcx>( let method = method_callee(cx, expr, fun.span, None); - let arg_tys = args.iter().map(|e| cx.tables().expr_ty_adjusted(e)); + let arg_tys = args.iter().map(|e| cx.typeck_results().expr_ty_adjusted(e)); let tupled_args = Expr { ty: cx.tcx.mk_tup(arg_tys), temp_lifetime, @@ -187,8 +187,8 @@ fn make_mirror_unadjusted<'a, 'tcx>( None }; if let Some((adt_def, index)) = adt_data { - let substs = cx.tables().node_substs(fun.hir_id); - let user_provided_types = cx.tables().user_provided_types(); + let substs = cx.typeck_results().node_substs(fun.hir_id); + let user_provided_types = cx.typeck_results().user_provided_types(); let user_ty = user_provided_types.get(fun.hir_id).copied().map(|mut u_ty| { if let UserType::TypeOf(ref mut did, _) = &mut u_ty.value { *did = adt_def.did; @@ -212,7 +212,7 @@ fn make_mirror_unadjusted<'a, 'tcx>( } } else { ExprKind::Call { - ty: cx.tables().node_type(fun.hir_id), + ty: cx.typeck_results().node_type(fun.hir_id), fun: fun.to_ref(), args: args.to_ref(), from_hir_call: true, @@ -237,7 +237,7 @@ fn make_mirror_unadjusted<'a, 'tcx>( } hir::ExprKind::AssignOp(op, ref lhs, ref rhs) => { - if cx.tables().is_method_call(expr) { + if cx.typeck_results().is_method_call(expr) { overloaded_operator(cx, expr, vec![lhs.to_ref(), rhs.to_ref()]) } else { ExprKind::AssignOp { op: bin_op(op.node), lhs: lhs.to_ref(), rhs: rhs.to_ref() } @@ -250,7 +250,7 @@ fn make_mirror_unadjusted<'a, 'tcx>( }, hir::ExprKind::Binary(op, ref lhs, ref rhs) => { - if cx.tables().is_method_call(expr) { + if cx.typeck_results().is_method_call(expr) { overloaded_operator(cx, expr, vec![lhs.to_ref(), rhs.to_ref()]) } else { // FIXME overflow @@ -275,7 +275,7 @@ fn make_mirror_unadjusted<'a, 'tcx>( } hir::ExprKind::Index(ref lhs, ref index) => { - if cx.tables().is_method_call(expr) { + if cx.typeck_results().is_method_call(expr) { overloaded_place(cx, expr, expr_ty, None, vec![lhs.to_ref(), index.to_ref()]) } else { ExprKind::Index { lhs: lhs.to_ref(), index: index.to_ref() } @@ -283,7 +283,7 @@ fn make_mirror_unadjusted<'a, 'tcx>( } hir::ExprKind::Unary(hir::UnOp::UnDeref, ref arg) => { - if cx.tables().is_method_call(expr) { + if cx.typeck_results().is_method_call(expr) { overloaded_place(cx, expr, expr_ty, None, vec![arg.to_ref()]) } else { ExprKind::Deref { arg: arg.to_ref() } @@ -291,7 +291,7 @@ fn make_mirror_unadjusted<'a, 'tcx>( } hir::ExprKind::Unary(hir::UnOp::UnNot, ref arg) => { - if cx.tables().is_method_call(expr) { + if cx.typeck_results().is_method_call(expr) { overloaded_operator(cx, expr, vec![arg.to_ref()]) } else { ExprKind::Unary { op: UnOp::Not, arg: arg.to_ref() } @@ -299,7 +299,7 @@ fn make_mirror_unadjusted<'a, 'tcx>( } hir::ExprKind::Unary(hir::UnOp::UnNeg, ref arg) => { - if cx.tables().is_method_call(expr) { + if cx.typeck_results().is_method_call(expr) { overloaded_operator(cx, expr, vec![arg.to_ref()]) } else { if let hir::ExprKind::Lit(ref lit) = arg.kind { @@ -316,7 +316,7 @@ fn make_mirror_unadjusted<'a, 'tcx>( hir::ExprKind::Struct(ref qpath, ref fields, ref base) => match expr_ty.kind { ty::Adt(adt, substs) => match adt.adt_kind() { AdtKind::Struct | AdtKind::Union => { - let user_provided_types = cx.tables().user_provided_types(); + let user_provided_types = cx.typeck_results().user_provided_types(); let user_ty = user_provided_types.get(expr.hir_id).copied(); debug!("make_mirror_unadjusted: (struct/union) user_ty={:?}", user_ty); ExprKind::Adt { @@ -327,18 +327,18 @@ fn make_mirror_unadjusted<'a, 'tcx>( fields: field_refs(cx, fields), base: base.as_ref().map(|base| FruInfo { base: base.to_ref(), - field_types: cx.tables().fru_field_types()[expr.hir_id].clone(), + field_types: cx.typeck_results().fru_field_types()[expr.hir_id].clone(), }), } } AdtKind::Enum => { - let res = cx.tables().qpath_res(qpath, expr.hir_id); + let res = cx.typeck_results().qpath_res(qpath, expr.hir_id); match res { Res::Def(DefKind::Variant, variant_id) => { assert!(base.is_none()); let index = adt.variant_index_with_id(variant_id); - let user_provided_types = cx.tables().user_provided_types(); + let user_provided_types = cx.typeck_results().user_provided_types(); let user_ty = user_provided_types.get(expr.hir_id).copied(); debug!("make_mirror_unadjusted: (variant) user_ty={:?}", user_ty); ExprKind::Adt { @@ -362,7 +362,7 @@ fn make_mirror_unadjusted<'a, 'tcx>( }, hir::ExprKind::Closure(..) => { - let closure_ty = cx.tables().expr_ty(expr); + let closure_ty = cx.typeck_results().expr_ty(expr); let (def_id, substs, movability) = match closure_ty.kind { ty::Closure(def_id, substs) => (def_id, UpvarSubsts::Closure(substs), None), ty::Generator(def_id, substs, movability) => { @@ -384,7 +384,7 @@ fn make_mirror_unadjusted<'a, 'tcx>( } hir::ExprKind::Path(ref qpath) => { - let res = cx.tables().qpath_res(qpath, expr.hir_id); + let res = cx.typeck_results().qpath_res(qpath, expr.hir_id); convert_path_expr(cx, expr, res) } @@ -433,11 +433,11 @@ fn make_mirror_unadjusted<'a, 'tcx>( }; let temp_lifetime = cx.region_scope_tree.temporary_scope(expr.hir_id.local_id); - let res = cx.tables().qpath_res(qpath, expr.hir_id); + let res = cx.typeck_results().qpath_res(qpath, expr.hir_id); let ty; match res { Res::Def(DefKind::Fn, _) | Res::Def(DefKind::AssocFn, _) => { - ty = cx.tables().node_type(expr.hir_id); + ty = cx.typeck_results().node_type(expr.hir_id); let user_ty = user_substs_applied_to_res(cx, expr.hir_id, res); InlineAsmOperand::SymFn { expr: Expr { @@ -523,11 +523,11 @@ fn make_mirror_unadjusted<'a, 'tcx>( } hir::ExprKind::Field(ref source, ..) => ExprKind::Field { lhs: source.to_ref(), - name: Field::new(cx.tcx.field_index(expr.hir_id, cx.tables)), + name: Field::new(cx.tcx.field_index(expr.hir_id, cx.typeck_results)), }, hir::ExprKind::Cast(ref source, ref cast_ty) => { // Check for a user-given type annotation on this `cast` - let user_provided_types = cx.tables.user_provided_types(); + let user_provided_types = cx.typeck_results.user_provided_types(); let user_ty = user_provided_types.get(cast_ty.hir_id); debug!( @@ -537,10 +537,10 @@ fn make_mirror_unadjusted<'a, 'tcx>( // Check to see if this cast is a "coercion cast", where the cast is actually done // using a coercion (or is a no-op). - let cast = if cx.tables().is_coercion_cast(source.hir_id) { + let cast = if cx.typeck_results().is_coercion_cast(source.hir_id) { // Convert the lexpr to a vexpr. ExprKind::Use { source: source.to_ref() } - } else if cx.tables().expr_ty(source).is_region_ptr() { + } else if cx.typeck_results().expr_ty(source).is_region_ptr() { // Special cased so that we can type check that the element // type of the source matches the pointed to type of the // destination. @@ -558,9 +558,9 @@ fn make_mirror_unadjusted<'a, 'tcx>( // The correct solution would be to add symbolic computations to miri, // so we wouldn't have to compute and store the actual value let var = if let hir::ExprKind::Path(ref qpath) = source.kind { - let res = cx.tables().qpath_res(qpath, source.hir_id); - cx.tables().node_type(source.hir_id).ty_adt_def().and_then( - |adt_def| match res { + let res = cx.typeck_results().qpath_res(qpath, source.hir_id); + cx.typeck_results().node_type(source.hir_id).ty_adt_def().and_then(|adt_def| { + match res { Res::Def( DefKind::Ctor(CtorOf::Variant, CtorKind::Const), variant_ctor_id, @@ -573,8 +573,8 @@ fn make_mirror_unadjusted<'a, 'tcx>( Some((d, o, ty)) } _ => None, - }, - ) + } + }) } else { None }; @@ -630,7 +630,7 @@ fn make_mirror_unadjusted<'a, 'tcx>( } } hir::ExprKind::Type(ref source, ref ty) => { - let user_provided_types = cx.tables.user_provided_types(); + let user_provided_types = cx.typeck_results.user_provided_types(); let user_ty = user_provided_types.get(ty.hir_id).copied(); debug!("make_mirror_unadjusted: (type) user_ty={:?}", user_ty); if source.is_syntactic_place_expr() { @@ -666,7 +666,7 @@ fn user_substs_applied_to_res<'tcx>( | Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) | Res::Def(DefKind::Const, _) | Res::Def(DefKind::AssocConst, _) => { - cx.tables().user_provided_types().get(hir_id).copied() + cx.typeck_results().user_provided_types().get(hir_id).copied() } // A unit struct/variant which is used as a value (e.g., @@ -697,12 +697,12 @@ fn method_callee<'a, 'tcx>( Some((def_id, substs)) => (def_id, substs, None), None => { let (kind, def_id) = cx - .tables() + .typeck_results() .type_dependent_def(expr.hir_id) .unwrap_or_else(|| span_bug!(expr.span, "no type-dependent def for method callee")); let user_ty = user_substs_applied_to_res(cx, expr.hir_id, Res::Def(kind, def_id)); debug!("method_callee: user_ty={:?}", user_ty); - (def_id, cx.tables().node_substs(expr.hir_id), user_ty) + (def_id, cx.typeck_results().node_substs(expr.hir_id), user_ty) } }; let ty = cx.tcx().mk_fn_def(def_id, substs); @@ -761,7 +761,7 @@ fn convert_path_expr<'a, 'tcx>( expr: &'tcx hir::Expr<'tcx>, res: Res, ) -> ExprKind<'tcx> { - let substs = cx.tables().node_substs(expr.hir_id); + let substs = cx.typeck_results().node_substs(expr.hir_id); match res { // A regular function, constructor function or a constant. Res::Def(DefKind::Fn, _) @@ -771,7 +771,7 @@ fn convert_path_expr<'a, 'tcx>( let user_ty = user_substs_applied_to_res(cx, expr.hir_id, res); debug!("convert_path_expr: user_ty={:?}", user_ty); ExprKind::Literal { - literal: ty::Const::zero_sized(cx.tcx, cx.tables().node_type(expr.hir_id)), + literal: ty::Const::zero_sized(cx.tcx, cx.typeck_results().node_type(expr.hir_id)), user_ty, } } @@ -786,7 +786,9 @@ fn convert_path_expr<'a, 'tcx>( let name = cx.tcx.hir().name(hir_id); let val = ty::ConstKind::Param(ty::ParamConst::new(index, name)); ExprKind::Literal { - literal: cx.tcx.mk_const(ty::Const { val, ty: cx.tables().node_type(expr.hir_id) }), + literal: cx + .tcx + .mk_const(ty::Const { val, ty: cx.typeck_results().node_type(expr.hir_id) }), user_ty: None, } } @@ -797,17 +799,17 @@ fn convert_path_expr<'a, 'tcx>( ExprKind::Literal { literal: cx.tcx.mk_const(ty::Const { val: ty::ConstKind::Unevaluated(def_id, substs, None), - ty: cx.tables().node_type(expr.hir_id), + ty: cx.typeck_results().node_type(expr.hir_id), }), user_ty, } } Res::Def(DefKind::Ctor(_, CtorKind::Const), def_id) => { - let user_provided_types = cx.tables.user_provided_types(); + let user_provided_types = cx.typeck_results.user_provided_types(); let user_provided_type = user_provided_types.get(expr.hir_id).copied(); debug!("convert_path_expr: user_provided_type={:?}", user_provided_type); - let ty = cx.tables().node_type(expr.hir_id); + let ty = cx.typeck_results().node_type(expr.hir_id); match ty.kind { // A unit struct/variant which is used as a value. // We return a completely different ExprKind here to account for this special case. @@ -852,7 +854,7 @@ fn convert_var<'tcx>( var_hir_id: hir::HirId, ) -> ExprKind<'tcx> { let upvar_index = cx - .tables() + .typeck_results() .closure_captures .get(&cx.body_owner) .and_then(|upvars| upvars.get_full(&var_hir_id).map(|(i, _, _)| i)); @@ -873,11 +875,11 @@ fn convert_var<'tcx>( var_path: ty::UpvarPath { hir_id: var_hir_id }, closure_expr_id: closure_def_id.expect_local(), }; - let var_ty = cx.tables().node_type(var_hir_id); + let var_ty = cx.typeck_results().node_type(var_hir_id); // FIXME free regions in closures are not right let closure_ty = cx - .tables() + .typeck_results() .node_type(cx.tcx.hir().local_def_id_to_hir_id(upvar_id.closure_expr_id)); // FIXME we're just hard-coding the idea that the @@ -948,7 +950,7 @@ fn convert_var<'tcx>( // ...but the upvar might be an `&T` or `&mut T` capture, at which // point we need an implicit deref - match cx.tables().upvar_capture(upvar_id) { + match cx.typeck_results().upvar_capture(upvar_id) { ty::UpvarCapture::ByValue => field_kind, ty::UpvarCapture::ByRef(borrow) => ExprKind::Deref { arg: Expr { @@ -1010,7 +1012,7 @@ fn overloaded_place<'a, 'tcx>( // line up (this is because `*x` and `x[y]` represent places): let recv_ty = match args[0] { - ExprRef::Hair(e) => cx.tables().expr_ty_adjusted(e), + ExprRef::Hair(e) => cx.typeck_results().expr_ty_adjusted(e), ExprRef::Mirror(ref e) => e.ty, }; @@ -1054,9 +1056,9 @@ fn capture_upvar<'tcx>( var_path: ty::UpvarPath { hir_id: var_hir_id }, closure_expr_id: cx.tcx.hir().local_def_id(closure_expr.hir_id), }; - let upvar_capture = cx.tables().upvar_capture(upvar_id); + let upvar_capture = cx.typeck_results().upvar_capture(upvar_id); let temp_lifetime = cx.region_scope_tree.temporary_scope(closure_expr.hir_id.local_id); - let var_ty = cx.tables().node_type(var_hir_id); + let var_ty = cx.typeck_results().node_type(var_hir_id); let captured_var = Expr { temp_lifetime, ty: var_ty, @@ -1090,7 +1092,7 @@ fn field_refs<'a, 'tcx>( fields .iter() .map(|field| FieldExprRef { - name: Field::new(cx.tcx.field_index(field.hir_id, cx.tables)), + name: Field::new(cx.tcx.field_index(field.hir_id, cx.typeck_results)), expr: field.expr.to_ref(), }) .collect() diff --git a/src/librustc_mir_build/hair/cx/mod.rs b/src/librustc_mir_build/hair/cx/mod.rs index d8b3ac79e6b9c..b73c01edd776f 100644 --- a/src/librustc_mir_build/hair/cx/mod.rs +++ b/src/librustc_mir_build/hair/cx/mod.rs @@ -33,7 +33,7 @@ crate struct Cx<'a, 'tcx> { crate identity_substs: &'tcx InternalSubsts<'tcx>, crate region_scope_tree: &'tcx region::ScopeTree, - crate tables: &'a ty::TypeckTables<'tcx>, + crate typeck_results: &'a ty::TypeckResults<'tcx>, /// This is `Constness::Const` if we are compiling a `static`, /// `const`, or the body of a `const fn`. @@ -53,7 +53,7 @@ impl<'a, 'tcx> Cx<'a, 'tcx> { crate fn new(infcx: &'a InferCtxt<'a, 'tcx>, src_id: hir::HirId) -> Cx<'a, 'tcx> { let tcx = infcx.tcx; let src_def_id = tcx.hir().local_def_id(src_id); - let tables = tcx.typeck_tables_of(src_def_id); + let typeck_results = tcx.typeck(src_def_id); let body_owner_kind = tcx.hir().body_owner_kind(src_id); let constness = match body_owner_kind { @@ -81,7 +81,7 @@ impl<'a, 'tcx> Cx<'a, 'tcx> { param_env: tcx.param_env(src_def_id), identity_substs: InternalSubsts::identity_for_item(tcx, src_def_id.to_def_id()), region_scope_tree: tcx.region_scope_tree(src_def_id), - tables, + typeck_results, constness, body_owner: src_def_id.to_def_id(), body_owner_kind, @@ -150,7 +150,7 @@ impl<'a, 'tcx> Cx<'a, 'tcx> { Node::Pat(p) | Node::Binding(p) => p, node => bug!("pattern became {:?}", node), }; - Pat::from_hir(self.tcx, self.param_env, self.tables(), p) + Pat::from_hir(self.tcx, self.param_env, self.typeck_results(), p) } crate fn trait_method( @@ -188,8 +188,8 @@ impl<'a, 'tcx> Cx<'a, 'tcx> { self.tcx } - crate fn tables(&self) -> &'a ty::TypeckTables<'tcx> { - self.tables + crate fn typeck_results(&self) -> &'a ty::TypeckResults<'tcx> { + self.typeck_results } crate fn check_overflow(&self) -> bool { @@ -206,8 +206,8 @@ impl<'tcx> UserAnnotatedTyHelpers<'tcx> for Cx<'_, 'tcx> { self.tcx() } - fn tables(&self) -> &ty::TypeckTables<'tcx> { - self.tables() + fn typeck_results(&self) -> &ty::TypeckResults<'tcx> { + self.typeck_results() } } diff --git a/src/librustc_mir_build/hair/pattern/check_match.rs b/src/librustc_mir_build/hair/pattern/check_match.rs index 6fc447a87f57a..552fb4814bd2f 100644 --- a/src/librustc_mir_build/hair/pattern/check_match.rs +++ b/src/librustc_mir_build/hair/pattern/check_match.rs @@ -27,7 +27,7 @@ crate fn check_match(tcx: TyCtxt<'_>, def_id: DefId) { let mut visitor = MatchVisitor { tcx, - tables: tcx.body_tables(body_id), + typeck_results: tcx.typeck_body(body_id), param_env: tcx.param_env(def_id), pattern_arena: TypedArena::default(), }; @@ -40,7 +40,7 @@ fn create_e0004(sess: &Session, sp: Span, error_message: String) -> DiagnosticBu struct MatchVisitor<'a, 'tcx> { tcx: TyCtxt<'tcx>, - tables: &'a ty::TypeckTables<'tcx>, + typeck_results: &'a ty::TypeckResults<'tcx>, param_env: ty::ParamEnv<'tcx>, pattern_arena: TypedArena>, } @@ -135,7 +135,7 @@ impl<'tcx> MatchVisitor<'_, 'tcx> { pat: &'tcx hir::Pat<'tcx>, have_errors: &mut bool, ) -> (&'p super::Pat<'tcx>, Ty<'tcx>) { - let mut patcx = PatCtxt::new(self.tcx, self.param_env, self.tables); + let mut patcx = PatCtxt::new(self.tcx, self.param_env, self.typeck_results); patcx.include_lint_checks(); let pattern = patcx.lower_pattern(pat); let pattern_ty = pattern.ty; @@ -189,7 +189,7 @@ impl<'tcx> MatchVisitor<'_, 'tcx> { // Fifth, check if the match is exhaustive. // Note: An empty match isn't the same as an empty matrix for diagnostics purposes, // since an empty matrix can occur when there are arms, if those arms all have guards. - let scrut_ty = self.tables.expr_ty_adjusted(scrut); + let scrut_ty = self.typeck_results.expr_ty_adjusted(scrut); let is_empty_match = inlined_arms.is_empty(); check_exhaustive(&mut cx, scrut_ty, scrut.span, &matrix, scrut.hir_id, is_empty_match); } @@ -285,9 +285,9 @@ fn check_for_bindings_named_same_as_variants(cx: &MatchVisitor<'_, '_>, pat: &Pa pat.walk_always(|p| { if let hir::PatKind::Binding(_, _, ident, None) = p.kind { if let Some(ty::BindByValue(hir::Mutability::Not)) = - cx.tables.extract_binding_mode(cx.tcx.sess, p.hir_id, p.span) + cx.typeck_results.extract_binding_mode(cx.tcx.sess, p.hir_id, p.span) { - let pat_ty = cx.tables.pat_ty(p).peel_refs(); + let pat_ty = cx.typeck_results.pat_ty(p).peel_refs(); if let ty::Adt(edef, _) = pat_ty.kind { if edef.is_enum() && edef.variants.iter().any(|variant| { @@ -579,18 +579,20 @@ fn maybe_point_at_variant(ty: Ty<'_>, patterns: &[super::Pat<'_>]) -> Vec /// Check if a by-value binding is by-value. That is, check if the binding's type is not `Copy`. fn is_binding_by_move(cx: &MatchVisitor<'_, '_>, hir_id: HirId, span: Span) -> bool { - !cx.tables.node_type(hir_id).is_copy_modulo_regions(cx.tcx.at(span), cx.param_env) + !cx.typeck_results.node_type(hir_id).is_copy_modulo_regions(cx.tcx.at(span), cx.param_env) } /// Check the legality of legality of by-move bindings. fn check_legality_of_move_bindings(cx: &mut MatchVisitor<'_, '_>, has_guard: bool, pat: &Pat<'_>) { let sess = cx.tcx.sess; - let tables = cx.tables; + let typeck_results = cx.typeck_results; // Find all by-ref spans. let mut by_ref_spans = Vec::new(); pat.each_binding(|_, hir_id, span, _| { - if let Some(ty::BindByReference(_)) = tables.extract_binding_mode(sess, hir_id, span) { + if let Some(ty::BindByReference(_)) = + typeck_results.extract_binding_mode(sess, hir_id, span) + { by_ref_spans.push(span); } }); @@ -611,7 +613,9 @@ fn check_legality_of_move_bindings(cx: &mut MatchVisitor<'_, '_>, has_guard: boo }; pat.walk_always(|p| { if let hir::PatKind::Binding(.., sub) = &p.kind { - if let Some(ty::BindByValue(_)) = tables.extract_binding_mode(sess, p.hir_id, p.span) { + if let Some(ty::BindByValue(_)) = + typeck_results.extract_binding_mode(sess, p.hir_id, p.span) + { if is_binding_by_move(cx, p.hir_id, p.span) { check_move(p, sub.as_deref()); } @@ -655,16 +659,16 @@ fn check_borrow_conflicts_in_at_patterns(cx: &MatchVisitor<'_, '_>, pat: &Pat<'_ }; let binding_span = pat.span.with_hi(name.span.hi()); - let tables = cx.tables; + let typeck_results = cx.typeck_results; let sess = cx.tcx.sess; // Get the binding move, extract the mutability if by-ref. - let mut_outer = match tables.extract_binding_mode(sess, pat.hir_id, pat.span) { + let mut_outer = match typeck_results.extract_binding_mode(sess, pat.hir_id, pat.span) { Some(ty::BindByValue(_)) if is_binding_by_move(cx, pat.hir_id, pat.span) => { // We have `x @ pat` where `x` is by-move. Reject all borrows in `pat`. let mut conflicts_ref = Vec::new(); sub.each_binding(|_, hir_id, span, _| { - match tables.extract_binding_mode(sess, hir_id, span) { + match typeck_results.extract_binding_mode(sess, hir_id, span) { Some(ty::BindByValue(_)) | None => {} Some(ty::BindByReference(_)) => conflicts_ref.push(span), } @@ -673,7 +677,7 @@ fn check_borrow_conflicts_in_at_patterns(cx: &MatchVisitor<'_, '_>, pat: &Pat<'_ let occurs_because = format!( "move occurs because `{}` has type `{}` which does not implement the `Copy` trait", name, - tables.node_type(pat.hir_id), + typeck_results.node_type(pat.hir_id), ); sess.struct_span_err(pat.span, "borrow of moved value") .span_label(binding_span, format!("value moved into `{}` here", name)) @@ -693,7 +697,7 @@ fn check_borrow_conflicts_in_at_patterns(cx: &MatchVisitor<'_, '_>, pat: &Pat<'_ let mut conflicts_mut_mut = Vec::new(); let mut conflicts_mut_ref = Vec::new(); sub.each_binding(|_, hir_id, span, name| { - match tables.extract_binding_mode(sess, hir_id, span) { + match typeck_results.extract_binding_mode(sess, hir_id, span) { Some(ty::BindByReference(mut_inner)) => match (mut_outer, mut_inner) { (Mutability::Not, Mutability::Not) => {} // Both sides are `ref`. (Mutability::Mut, Mutability::Mut) => conflicts_mut_mut.push((span, name)), // 2x `ref mut`. diff --git a/src/librustc_mir_build/hair/pattern/mod.rs b/src/librustc_mir_build/hair/pattern/mod.rs index 5c30b2a448c6d..4fa23906a3568 100644 --- a/src/librustc_mir_build/hair/pattern/mod.rs +++ b/src/librustc_mir_build/hair/pattern/mod.rs @@ -349,7 +349,7 @@ impl<'tcx> fmt::Display for Pat<'tcx> { crate struct PatCtxt<'a, 'tcx> { crate tcx: TyCtxt<'tcx>, crate param_env: ty::ParamEnv<'tcx>, - crate tables: &'a ty::TypeckTables<'tcx>, + crate typeck_results: &'a ty::TypeckResults<'tcx>, crate errors: Vec, include_lint_checks: bool, } @@ -358,10 +358,10 @@ impl<'a, 'tcx> Pat<'tcx> { crate fn from_hir( tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, - tables: &'a ty::TypeckTables<'tcx>, + typeck_results: &'a ty::TypeckResults<'tcx>, pat: &'tcx hir::Pat<'tcx>, ) -> Self { - let mut pcx = PatCtxt::new(tcx, param_env, tables); + let mut pcx = PatCtxt::new(tcx, param_env, typeck_results); let result = pcx.lower_pattern(pat); if !pcx.errors.is_empty() { let msg = format!("encountered errors lowering pattern: {:?}", pcx.errors); @@ -376,9 +376,9 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { crate fn new( tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, - tables: &'a ty::TypeckTables<'tcx>, + typeck_results: &'a ty::TypeckResults<'tcx>, ) -> Self { - PatCtxt { tcx, param_env, tables, errors: vec![], include_lint_checks: false } + PatCtxt { tcx, param_env, typeck_results, errors: vec![], include_lint_checks: false } } crate fn include_lint_checks(&mut self) -> &mut Self { @@ -407,7 +407,7 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { // adjustments in *reverse order* (last-in-first-out, so that the last `Deref` inserted // gets the least-dereferenced type). let unadjusted_pat = self.lower_pattern_unadjusted(pat); - self.tables.pat_adjustments().get(pat.hir_id).unwrap_or(&vec![]).iter().rev().fold( + self.typeck_results.pat_adjustments().get(pat.hir_id).unwrap_or(&vec![]).iter().rev().fold( unadjusted_pat, |pat, ref_ty| { debug!("{:?}: wrapping pattern with type {:?}", pat, ref_ty); @@ -507,7 +507,7 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { } fn lower_pattern_unadjusted(&mut self, pat: &'tcx hir::Pat<'tcx>) -> Pat<'tcx> { - let mut ty = self.tables.node_type(pat.hir_id); + let mut ty = self.typeck_results.node_type(pat.hir_id); if let ty::Error(_) = ty.kind { // Avoid ICEs (e.g., #50577 and #50585). @@ -573,8 +573,11 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { } hir::PatKind::Binding(_, id, ident, ref sub) => { - let bm = - *self.tables.pat_binding_modes().get(pat.hir_id).expect("missing binding mode"); + let bm = *self + .typeck_results + .pat_binding_modes() + .get(pat.hir_id) + .expect("missing binding mode"); let (mutability, mode) = match bm { ty::BindByValue(mutbl) => (mutbl, BindingMode::ByValue), ty::BindByReference(hir::Mutability::Mut) => ( @@ -609,7 +612,7 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { } hir::PatKind::TupleStruct(ref qpath, ref pats, ddpos) => { - let res = self.tables.qpath_res(qpath, pat.hir_id); + let res = self.typeck_results.qpath_res(qpath, pat.hir_id); let adt_def = match ty.kind { ty::Adt(adt_def, _) => adt_def, _ => span_bug!(pat.span, "tuple struct pattern not applied to an ADT {:?}", ty), @@ -620,11 +623,11 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { } hir::PatKind::Struct(ref qpath, ref fields, _) => { - let res = self.tables.qpath_res(qpath, pat.hir_id); + let res = self.typeck_results.qpath_res(qpath, pat.hir_id); let subpatterns = fields .iter() .map(|field| FieldPat { - field: Field::new(self.tcx.field_index(field.hir_id, self.tables)), + field: Field::new(self.tcx.field_index(field.hir_id, self.typeck_results)), pattern: self.lower_pattern(&field.pat), }) .collect(); @@ -764,8 +767,8 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { /// it to `const_to_pat`. Any other path (like enum variants without fields) /// is converted to the corresponding pattern via `lower_variant_or_leaf`. fn lower_path(&mut self, qpath: &hir::QPath<'_>, id: hir::HirId, span: Span) -> Pat<'tcx> { - let ty = self.tables.node_type(id); - let res = self.tables.qpath_res(qpath, id); + let ty = self.typeck_results.node_type(id); + let res = self.typeck_results.qpath_res(qpath, id); let pat_from_kind = |kind| Pat { span, ty, kind: Box::new(kind) }; @@ -779,7 +782,7 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { // Use `Reveal::All` here because patterns are always monomorphic even if their function // isn't. let param_env_reveal_all = self.param_env.with_reveal_all(); - let substs = self.tables.node_substs(id); + let substs = self.typeck_results.node_substs(id); let instance = match ty::Instance::resolve(self.tcx, param_env_reveal_all, def_id, substs) { Ok(Some(i)) => i, Ok(None) => { @@ -806,7 +809,8 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { match self.tcx.const_eval_instance(param_env_reveal_all, instance, Some(span)) { Ok(value) => { - let const_ = ty::Const::from_value(self.tcx, value, self.tables.node_type(id)); + let const_ = + ty::Const::from_value(self.tcx, value, self.typeck_results.node_type(id)); let pattern = self.const_to_pat(&const_, id, span, mir_structural_match_violation); @@ -814,7 +818,7 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { return pattern; } - let user_provided_types = self.tables().user_provided_types(); + let user_provided_types = self.typeck_results().user_provided_types(); if let Some(u_ty) = user_provided_types.get(id) { let user_ty = PatTyProj::from_user_type(*u_ty); Pat { @@ -862,7 +866,8 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { _ => span_bug!(expr.span, "not a literal: {:?}", expr), }; - let lit_input = LitToConstInput { lit: &lit.node, ty: self.tables.expr_ty(expr), neg }; + let lit_input = + LitToConstInput { lit: &lit.node, ty: self.typeck_results.expr_ty(expr), neg }; match self.tcx.at(expr.span).lit_to_const(lit_input) { Ok(val) => *self.const_to_pat(val, expr.hir_id, lit.span, false).kind, Err(LitToConstError::UnparseableFloat) => { @@ -881,8 +886,8 @@ impl<'tcx> UserAnnotatedTyHelpers<'tcx> for PatCtxt<'_, 'tcx> { self.tcx } - fn tables(&self) -> &ty::TypeckTables<'tcx> { - self.tables + fn typeck_results(&self) -> &ty::TypeckResults<'tcx> { + self.typeck_results } } diff --git a/src/librustc_mir_build/hair/util.rs b/src/librustc_mir_build/hair/util.rs index 0ea0d5d1b0c19..7de60ddda41a3 100644 --- a/src/librustc_mir_build/hair/util.rs +++ b/src/librustc_mir_build/hair/util.rs @@ -4,7 +4,7 @@ use rustc_middle::ty::{self, CanonicalUserType, TyCtxt, UserType}; crate trait UserAnnotatedTyHelpers<'tcx> { fn tcx(&self) -> TyCtxt<'tcx>; - fn tables(&self) -> &ty::TypeckTables<'tcx>; + fn typeck_results(&self) -> &ty::TypeckResults<'tcx>; /// Looks up the type associated with this hir-id and applies the /// user-given substitutions; the hir-id must map to a suitable @@ -13,10 +13,10 @@ crate trait UserAnnotatedTyHelpers<'tcx> { &self, hir_id: hir::HirId, ) -> Option> { - let user_provided_types = self.tables().user_provided_types(); + let user_provided_types = self.typeck_results().user_provided_types(); let mut user_ty = *user_provided_types.get(hir_id)?; debug!("user_subts_applied_to_ty_of_hir_id: user_ty={:?}", user_ty); - let ty = self.tables().node_type(hir_id); + let ty = self.typeck_results().node_type(hir_id); match ty.kind { ty::Adt(adt_def, ..) => { if let UserType::TypeOf(ref mut did, _) = &mut user_ty.value { diff --git a/src/librustc_parse/parser/attr.rs b/src/librustc_parse/parser/attr.rs index b8cb146145b98..803f14a2a228a 100644 --- a/src/librustc_parse/parser/attr.rs +++ b/src/librustc_parse/parser/attr.rs @@ -155,7 +155,7 @@ impl<'a> Parser<'a> { /// The delimiters or `=` are still put into the resulting token stream. pub fn parse_attr_item(&mut self) -> PResult<'a, ast::AttrItem> { let item = match self.token.kind { - token::Interpolated(ref nt, _) => match **nt { + token::Interpolated(ref nt) => match **nt { Nonterminal::NtMeta(ref item) => Some(item.clone().into_inner()), _ => None, }, @@ -254,7 +254,7 @@ impl<'a> Parser<'a> { /// meta_item_inner : (meta_item | UNSUFFIXED_LIT) (',' meta_item_inner)? ; pub fn parse_meta_item(&mut self) -> PResult<'a, ast::MetaItem> { let nt_meta = match self.token.kind { - token::Interpolated(ref nt, _) => match **nt { + token::Interpolated(ref nt) => match **nt { token::NtMeta(ref e) => Some(e.clone()), _ => None, }, diff --git a/src/librustc_parse/parser/diagnostics.rs b/src/librustc_parse/parser/diagnostics.rs index e27bbc532cfc4..16a118cb48c91 100644 --- a/src/librustc_parse/parser/diagnostics.rs +++ b/src/librustc_parse/parser/diagnostics.rs @@ -376,7 +376,14 @@ impl<'a> Parser<'a> { /// let _ = vec![1, 2, 3].into_iter().collect::>>>(); /// ^^ help: remove extra angle brackets /// ``` - pub(super) fn check_trailing_angle_brackets(&mut self, segment: &PathSegment, end: TokenKind) { + /// + /// If `true` is returned, then trailing brackets were recovered, tokens were consumed + /// up until one of the tokens in 'end' was encountered, and an error was emitted. + pub(super) fn check_trailing_angle_brackets( + &mut self, + segment: &PathSegment, + end: &[&TokenKind], + ) -> bool { // This function is intended to be invoked after parsing a path segment where there are two // cases: // @@ -409,7 +416,7 @@ impl<'a> Parser<'a> { parsed_angle_bracket_args, ); if !parsed_angle_bracket_args { - return; + return false; } // Keep the span at the start so we can highlight the sequence of `>` characters to be @@ -447,18 +454,18 @@ impl<'a> Parser<'a> { number_of_gt, number_of_shr, ); if number_of_gt < 1 && number_of_shr < 1 { - return; + return false; } // Finally, double check that we have our end token as otherwise this is the // second case. if self.look_ahead(position, |t| { trace!("check_trailing_angle_brackets: t={:?}", t); - *t == end + end.contains(&&t.kind) }) { // Eat from where we started until the end token so that parsing can continue // as if we didn't have those extra angle brackets. - self.eat_to_tokens(&[&end]); + self.eat_to_tokens(end); let span = lo.until(self.token.span); let total_num_of_gt = number_of_gt + number_of_shr * 2; @@ -473,7 +480,9 @@ impl<'a> Parser<'a> { Applicability::MachineApplicable, ) .emit(); + return true; } + false } /// Check to see if a pair of chained operators looks like an attempt at chained comparison, diff --git a/src/librustc_parse/parser/expr.rs b/src/librustc_parse/parser/expr.rs index 2745b18a8cd51..abb444933536f 100644 --- a/src/librustc_parse/parser/expr.rs +++ b/src/librustc_parse/parser/expr.rs @@ -26,7 +26,7 @@ use std::mem; /// `token::Interpolated` tokens. macro_rules! maybe_whole_expr { ($p:expr) => { - if let token::Interpolated(nt, _) = &$p.token.kind { + if let token::Interpolated(nt) = &$p.token.kind { match &**nt { token::NtExpr(e) | token::NtLiteral(e) => { let e = e.clone(); @@ -867,7 +867,7 @@ impl<'a> Parser<'a> { let fn_span_lo = self.token.span; let segment = self.parse_path_segment(PathStyle::Expr)?; - self.check_trailing_angle_brackets(&segment, token::OpenDelim(token::Paren)); + self.check_trailing_angle_brackets(&segment, &[&token::OpenDelim(token::Paren)]); if self.check(&token::OpenDelim(token::Paren)) { // Method call `expr.f()` diff --git a/src/librustc_parse/parser/item.rs b/src/librustc_parse/parser/item.rs index 10df16964da08..5923a185dcf93 100644 --- a/src/librustc_parse/parser/item.rs +++ b/src/librustc_parse/parser/item.rs @@ -9,7 +9,7 @@ use rustc_ast::ast::{AssocItem, AssocItemKind, ForeignItemKind, Item, ItemKind, use rustc_ast::ast::{Async, Const, Defaultness, IsAuto, Mutability, Unsafe, UseTree, UseTreeKind}; use rustc_ast::ast::{BindingMode, Block, FnDecl, FnSig, Param, SelfKind}; use rustc_ast::ast::{EnumDef, Generics, StructField, TraitRef, Ty, TyKind, Variant, VariantData}; -use rustc_ast::ast::{FnHeader, ForeignItem, PathSegment, Visibility, VisibilityKind}; +use rustc_ast::ast::{FnHeader, ForeignItem, Path, PathSegment, Visibility, VisibilityKind}; use rustc_ast::ast::{MacArgs, MacCall, MacDelimiter}; use rustc_ast::ptr::P; use rustc_ast::token::{self, TokenKind}; @@ -1262,6 +1262,25 @@ impl<'a> Parser<'a> { sp, &format!("expected `,`, or `}}`, found {}", super::token_descr(&self.token)), ); + + // Try to recover extra trailing angle brackets + let mut recovered = false; + if let TyKind::Path(_, Path { segments, .. }) = &a_var.ty.kind { + if let Some(last_segment) = segments.last() { + recovered = self.check_trailing_angle_brackets( + last_segment, + &[&token::Comma, &token::CloseDelim(token::Brace)], + ); + if recovered { + // Handle a case like `Vec>,` where we can continue parsing fields + // after the comma + self.eat(&token::Comma); + // `check_trailing_angle_brackets` already emitted a nicer error + err.cancel(); + } + } + } + if self.token.is_ident() { // This is likely another field; emit the diagnostic and keep going err.span_suggestion( @@ -1271,6 +1290,14 @@ impl<'a> Parser<'a> { Applicability::MachineApplicable, ); err.emit(); + recovered = true; + } + + if recovered { + // Make sure an error was emitted (either by recovering an angle bracket, + // or by finding an identifier as the next token), since we're + // going to continue parsing + assert!(self.sess.span_diagnostic.has_errors()); } else { return Err(err); } @@ -1780,7 +1807,7 @@ impl<'a> Parser<'a> { fn is_named_param(&self) -> bool { let offset = match self.token.kind { - token::Interpolated(ref nt, _) => match **nt { + token::Interpolated(ref nt) => match **nt { token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon), _ => 0, }, diff --git a/src/librustc_parse/parser/mod.rs b/src/librustc_parse/parser/mod.rs index 04074479a21a4..7811d5fb741b2 100644 --- a/src/librustc_parse/parser/mod.rs +++ b/src/librustc_parse/parser/mod.rs @@ -54,7 +54,7 @@ enum BlockMode { #[macro_export] macro_rules! maybe_whole { ($p:expr, $constructor:ident, |$x:ident| $e:expr) => { - if let token::Interpolated(nt, _) = &$p.token.kind { + if let token::Interpolated(nt) = &$p.token.kind { if let token::$constructor(x) = &**nt { let $x = x.clone(); $p.bump(); @@ -69,7 +69,7 @@ macro_rules! maybe_whole { macro_rules! maybe_recover_from_interpolated_ty_qpath { ($self: expr, $allow_qpath_recovery: expr) => { if $allow_qpath_recovery && $self.look_ahead(1, |t| t == &token::ModSep) { - if let token::Interpolated(nt, _) = &$self.token.kind { + if let token::Interpolated(nt) = &$self.token.kind { if let token::NtTy(ty) = &**nt { let ty = ty.clone(); $self.bump(); @@ -922,7 +922,7 @@ impl<'a> Parser<'a> { if self.eat(&token::Eq) { let eq_span = self.prev_token.span; let mut is_interpolated_expr = false; - if let token::Interpolated(nt, _) = &self.token.kind { + if let token::Interpolated(nt) = &self.token.kind { if let token::NtExpr(..) = **nt { is_interpolated_expr = true; } diff --git a/src/librustc_parse/parser/pat.rs b/src/librustc_parse/parser/pat.rs index 742183d369735..6603d0afc0248 100644 --- a/src/librustc_parse/parser/pat.rs +++ b/src/librustc_parse/parser/pat.rs @@ -515,7 +515,7 @@ impl<'a> Parser<'a> { self.recover_additional_muts(); // Make sure we don't allow e.g. `let mut $p;` where `$p:pat`. - if let token::Interpolated(ref nt, _) = self.token.kind { + if let token::Interpolated(ref nt) = self.token.kind { if let token::NtPat(_) = **nt { self.expected_ident_found().emit(); } diff --git a/src/librustc_parse/parser/path.rs b/src/librustc_parse/parser/path.rs index 5210614548da3..67e9b3af4a8cf 100644 --- a/src/librustc_parse/parser/path.rs +++ b/src/librustc_parse/parser/path.rs @@ -169,7 +169,7 @@ impl<'a> Parser<'a> { // `PathStyle::Expr` is only provided at the root invocation and never in // `parse_path_segment` to recurse and therefore can be checked to maintain // this invariant. - self.check_trailing_angle_brackets(&segment, token::ModSep); + self.check_trailing_angle_brackets(&segment, &[&token::ModSep]); } segments.push(segment); diff --git a/src/librustc_passes/dead.rs b/src/librustc_passes/dead.rs index 503fbb64db83d..316bb95882289 100644 --- a/src/librustc_passes/dead.rs +++ b/src/librustc_passes/dead.rs @@ -40,7 +40,7 @@ fn should_explore(tcx: TyCtxt<'_>, hir_id: hir::HirId) -> bool { struct MarkSymbolVisitor<'a, 'tcx> { worklist: Vec, tcx: TyCtxt<'tcx>, - tables: &'a ty::TypeckTables<'tcx>, + typeck_results: &'a ty::TypeckResults<'tcx>, live_symbols: FxHashSet, repr_has_repr_c: bool, in_pat: bool, @@ -107,7 +107,7 @@ impl<'a, 'tcx> MarkSymbolVisitor<'a, 'tcx> { } fn lookup_and_handle_method(&mut self, id: hir::HirId) { - if let Some(def_id) = self.tables.type_dependent_def_id(id) { + if let Some(def_id) = self.typeck_results.type_dependent_def_id(id) { self.check_def_id(def_id); } else { bug!("no type-dependent def for method"); @@ -115,9 +115,9 @@ impl<'a, 'tcx> MarkSymbolVisitor<'a, 'tcx> { } fn handle_field_access(&mut self, lhs: &hir::Expr<'_>, hir_id: hir::HirId) { - match self.tables.expr_ty_adjusted(lhs).kind { + match self.typeck_results.expr_ty_adjusted(lhs).kind { ty::Adt(def, _) => { - let index = self.tcx.field_index(hir_id, self.tables); + let index = self.tcx.field_index(hir_id, self.typeck_results); self.insert_def_id(def.non_enum_variant().fields[index].did); } ty::Tuple(..) => {} @@ -131,7 +131,7 @@ impl<'a, 'tcx> MarkSymbolVisitor<'a, 'tcx> { res: Res, pats: &[hir::FieldPat<'_>], ) { - let variant = match self.tables.node_type(lhs.hir_id).kind { + let variant = match self.typeck_results.node_type(lhs.hir_id).kind { ty::Adt(adt, _) => adt.variant_of_res(res), _ => span_bug!(lhs.span, "non-ADT in struct pattern"), }; @@ -139,7 +139,7 @@ impl<'a, 'tcx> MarkSymbolVisitor<'a, 'tcx> { if let PatKind::Wild = pat.pat.kind { continue; } - let index = self.tcx.field_index(pat.hir_id, self.tables); + let index = self.tcx.field_index(pat.hir_id, self.typeck_results); self.insert_def_id(variant.fields[index].did); } } @@ -204,7 +204,7 @@ impl<'a, 'tcx> MarkSymbolVisitor<'a, 'tcx> { fn mark_as_used_if_union(&mut self, adt: &ty::AdtDef, fields: &[hir::Field<'_>]) { if adt.is_union() && adt.non_enum_variant().fields.len() > 1 && adt.did.is_local() { for field in fields { - let index = self.tcx.field_index(field.hir_id, self.tables); + let index = self.tcx.field_index(field.hir_id, self.typeck_results); self.insert_def_id(adt.non_enum_variant().fields[index].did); } } @@ -219,11 +219,11 @@ impl<'a, 'tcx> Visitor<'tcx> for MarkSymbolVisitor<'a, 'tcx> { } fn visit_nested_body(&mut self, body: hir::BodyId) { - let old_tables = self.tables; - self.tables = self.tcx.body_tables(body); + let old_typeck_results = self.typeck_results; + self.typeck_results = self.tcx.typeck_body(body); let body = self.tcx.hir().body(body); self.visit_body(body); - self.tables = old_tables; + self.typeck_results = old_typeck_results; } fn visit_variant_data( @@ -248,7 +248,7 @@ impl<'a, 'tcx> Visitor<'tcx> for MarkSymbolVisitor<'a, 'tcx> { fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) { match expr.kind { hir::ExprKind::Path(ref qpath @ hir::QPath::TypeRelative(..)) => { - let res = self.tables.qpath_res(qpath, expr.hir_id); + let res = self.typeck_results.qpath_res(qpath, expr.hir_id); self.handle_res(res); } hir::ExprKind::MethodCall(..) => { @@ -258,9 +258,9 @@ impl<'a, 'tcx> Visitor<'tcx> for MarkSymbolVisitor<'a, 'tcx> { self.handle_field_access(&lhs, expr.hir_id); } hir::ExprKind::Struct(ref qpath, ref fields, _) => { - let res = self.tables.qpath_res(qpath, expr.hir_id); + let res = self.typeck_results.qpath_res(qpath, expr.hir_id); self.handle_res(res); - if let ty::Adt(ref adt, _) = self.tables.expr_ty(expr).kind { + if let ty::Adt(ref adt, _) = self.typeck_results.expr_ty(expr).kind { self.mark_as_used_if_union(adt, fields); } } @@ -283,11 +283,11 @@ impl<'a, 'tcx> Visitor<'tcx> for MarkSymbolVisitor<'a, 'tcx> { fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) { match pat.kind { PatKind::Struct(ref path, ref fields, _) => { - let res = self.tables.qpath_res(path, pat.hir_id); + let res = self.typeck_results.qpath_res(path, pat.hir_id); self.handle_field_pattern_match(pat, res, fields); } PatKind::Path(ref qpath) => { - let res = self.tables.qpath_res(qpath, pat.hir_id); + let res = self.typeck_results.qpath_res(qpath, pat.hir_id); self.handle_res(res); } _ => (), @@ -473,7 +473,7 @@ fn find_live<'tcx>( let mut symbol_visitor = MarkSymbolVisitor { worklist, tcx, - tables: &ty::TypeckTables::empty(None), + typeck_results: &ty::TypeckResults::empty(None), live_symbols: Default::default(), repr_has_repr_c: false, in_pat: false, diff --git a/src/librustc_passes/intrinsicck.rs b/src/librustc_passes/intrinsicck.rs index e4f4885690fd9..4ce729efa3769 100644 --- a/src/librustc_passes/intrinsicck.rs +++ b/src/librustc_passes/intrinsicck.rs @@ -28,7 +28,7 @@ struct ItemVisitor<'tcx> { struct ExprVisitor<'tcx> { tcx: TyCtxt<'tcx>, - tables: &'tcx ty::TypeckTables<'tcx>, + typeck_results: &'tcx ty::TypeckResults<'tcx>, param_env: ty::ParamEnv<'tcx>, } @@ -142,7 +142,7 @@ impl ExprVisitor<'tcx> { tied_input: Option<(&hir::Expr<'tcx>, Option)>, ) -> Option { // Check the type against the allowed types for inline asm. - let ty = self.tables.expr_ty_adjusted(expr); + let ty = self.typeck_results.expr_ty_adjusted(expr); let asm_ty_isize = match self.tcx.sess.target.ptr_width { 16 => InlineAsmType::I16, 32 => InlineAsmType::I32, @@ -236,7 +236,7 @@ impl ExprVisitor<'tcx> { let mut err = self.tcx.sess.struct_span_err(vec![in_expr.span, expr.span], msg); err.span_label( in_expr.span, - &format!("type `{}`", self.tables.expr_ty_adjusted(in_expr)), + &format!("type `{}`", self.typeck_results.expr_ty_adjusted(in_expr)), ); err.span_label(expr.span, &format!("type `{}`", ty)); err.note( @@ -373,7 +373,7 @@ impl ExprVisitor<'tcx> { } } hir::InlineAsmOperand::Const { ref expr } => { - let ty = self.tables.expr_ty_adjusted(expr); + let ty = self.typeck_results.expr_ty_adjusted(expr); match ty.kind { ty::Int(_) | ty::Uint(_) | ty::Float(_) => {} _ => { @@ -400,8 +400,8 @@ impl Visitor<'tcx> for ItemVisitor<'tcx> { let owner_def_id = self.tcx.hir().body_owner_def_id(body_id); let body = self.tcx.hir().body(body_id); let param_env = self.tcx.param_env(owner_def_id.to_def_id()); - let tables = self.tcx.typeck_tables_of(owner_def_id); - ExprVisitor { tcx: self.tcx, param_env, tables }.visit_body(body); + let typeck_results = self.tcx.typeck(owner_def_id); + ExprVisitor { tcx: self.tcx, param_env, typeck_results }.visit_body(body); self.visit_body(body); } } @@ -416,10 +416,10 @@ impl Visitor<'tcx> for ExprVisitor<'tcx> { fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) { match expr.kind { hir::ExprKind::Path(ref qpath) => { - let res = self.tables.qpath_res(qpath, expr.hir_id); + let res = self.typeck_results.qpath_res(qpath, expr.hir_id); if let Res::Def(DefKind::Fn, did) = res { if self.def_id_is_transmute(did) { - let typ = self.tables.node_type(expr.hir_id); + let typ = self.typeck_results.node_type(expr.hir_id); let sig = typ.fn_sig(self.tcx); let from = sig.inputs().skip_binder()[0]; let to = sig.output().skip_binder(); diff --git a/src/librustc_passes/lang_items.rs b/src/librustc_passes/lang_items.rs index 0be37cb096038..0326591a931f5 100644 --- a/src/librustc_passes/lang_items.rs +++ b/src/librustc_passes/lang_items.rs @@ -146,6 +146,28 @@ impl LanguageItemCollector<'tcx> { )); } } + let mut note_def = |which, def_id: DefId| { + let crate_name = self.tcx.crate_name(def_id.krate); + let note = if def_id.is_local() { + format!("{} definition in the local crate (`{}`)", which, crate_name) + } else { + let paths: Vec<_> = self + .tcx + .crate_extern_paths(def_id.krate) + .iter() + .map(|p| p.display().to_string()) + .collect(); + format!( + "{} definition in `{}` loaded from {}", + which, + crate_name, + paths.join(", ") + ) + }; + err.note(¬e); + }; + note_def("first", original_def_id); + note_def("second", item_def_id); } err.emit(); } diff --git a/src/librustc_passes/liveness.rs b/src/librustc_passes/liveness.rs index 798c6b8925bbf..f8c1c39ad7a31 100644 --- a/src/librustc_passes/liveness.rs +++ b/src/librustc_passes/liveness.rs @@ -650,7 +650,7 @@ const ACC_USE: u32 = 4; struct Liveness<'a, 'tcx> { ir: &'a mut IrMaps<'tcx>, - tables: &'a ty::TypeckTables<'tcx>, + typeck_results: &'a ty::TypeckResults<'tcx>, param_env: ty::ParamEnv<'tcx>, s: Specials, successors: Vec, @@ -670,7 +670,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { exit_ln: ir.add_live_node(ExitNode), }; - let tables = ir.tcx.typeck_tables_of(def_id); + let typeck_results = ir.tcx.typeck(def_id); let param_env = ir.tcx.param_env(def_id); let num_live_nodes = ir.num_live_nodes; @@ -678,7 +678,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { Liveness { ir, - tables, + typeck_results, param_env, s: specials, successors: vec![invalid_node(); num_live_nodes], @@ -939,7 +939,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { var_path: ty::UpvarPath { hir_id: var_hir_id }, closure_expr_id: self.ir.body_owner, }; - match self.tables.upvar_capture(upvar_id) { + match self.typeck_results.upvar_capture(upvar_id) { ty::UpvarCapture::ByRef(_) => { let var = self.variable(var_hir_id, upvar.span); self.acc(self.s.exit_ln, var, ACC_READ | ACC_USE); @@ -956,7 +956,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { FnKind::Closure(..) => {} } - let ty = self.tables.node_type(id); + let ty = self.typeck_results.node_type(id); match ty.kind { ty::Closure(_def_id, substs) => match substs.as_closure().kind() { ty::ClosureKind::Fn => {} @@ -1160,7 +1160,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { hir::ExprKind::AssignOp(_, ref l, ref r) => { // an overloaded assign op is like a method call - if self.tables.is_method_call(expr) { + if self.typeck_results.is_method_call(expr) { let succ = self.propagate_through_expr(&l, succ); self.propagate_through_expr(&r, succ) } else { @@ -1187,7 +1187,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { let m = self.ir.tcx.parent_module(expr.hir_id).to_def_id(); let succ = if self.ir.tcx.is_ty_uninhabited_from( m, - self.tables.expr_ty(expr), + self.typeck_results.expr_ty(expr), self.param_env, ) { self.s.exit_ln @@ -1202,7 +1202,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { let m = self.ir.tcx.parent_module(expr.hir_id).to_def_id(); let succ = if self.ir.tcx.is_ty_uninhabited_from( m, - self.tables.expr_ty(expr), + self.typeck_results.expr_ty(expr), self.param_env, ) { self.s.exit_ln @@ -1506,7 +1506,7 @@ fn check_expr<'tcx>(this: &mut Liveness<'_, 'tcx>, expr: &'tcx Expr<'tcx>) { } hir::ExprKind::AssignOp(_, ref l, _) => { - if !this.tables.is_method_call(expr) { + if !this.typeck_results.is_method_call(expr) { this.check_place(&l); } } @@ -1616,7 +1616,7 @@ impl<'tcx> Liveness<'_, 'tcx> { var_path: ty::UpvarPath { hir_id: var_hir_id }, closure_expr_id: self.ir.body_owner, }; - match self.tables.upvar_capture(upvar_id) { + match self.typeck_results.upvar_capture(upvar_id) { ty::UpvarCapture::ByValue => {} ty::UpvarCapture::ByRef(..) => continue, }; diff --git a/src/librustc_passes/reachable.rs b/src/librustc_passes/reachable.rs index c9a4428c007aa..85f3a6fd59d97 100644 --- a/src/librustc_passes/reachable.rs +++ b/src/librustc_passes/reachable.rs @@ -63,7 +63,7 @@ fn method_might_be_inlined( struct ReachableContext<'a, 'tcx> { // The type context. tcx: TyCtxt<'tcx>, - tables: &'a ty::TypeckTables<'tcx>, + typeck_results: &'a ty::TypeckResults<'tcx>, // The set of items which must be exported in the linkage sense. reachable_symbols: HirIdSet, // A worklist of item IDs. Each item ID in this worklist will be inlined @@ -81,18 +81,20 @@ impl<'a, 'tcx> Visitor<'tcx> for ReachableContext<'a, 'tcx> { } fn visit_nested_body(&mut self, body: hir::BodyId) { - let old_tables = self.tables; - self.tables = self.tcx.body_tables(body); + let old_typeck_results = self.typeck_results; + self.typeck_results = self.tcx.typeck_body(body); let body = self.tcx.hir().body(body); self.visit_body(body); - self.tables = old_tables; + self.typeck_results = old_typeck_results; } fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) { let res = match expr.kind { - hir::ExprKind::Path(ref qpath) => Some(self.tables.qpath_res(qpath, expr.hir_id)), + hir::ExprKind::Path(ref qpath) => { + Some(self.typeck_results.qpath_res(qpath, expr.hir_id)) + } hir::ExprKind::MethodCall(..) => self - .tables + .typeck_results .type_dependent_def(expr.hir_id) .map(|(kind, def_id)| Res::Def(kind, def_id)), _ => None, @@ -381,7 +383,7 @@ fn reachable_set<'tcx>(tcx: TyCtxt<'tcx>, crate_num: CrateNum) -> &'tcx HirIdSet }); let mut reachable_context = ReachableContext { tcx, - tables: &ty::TypeckTables::empty(None), + typeck_results: &ty::TypeckResults::empty(None), reachable_symbols: Default::default(), worklist: Vec::new(), any_library, diff --git a/src/librustc_privacy/lib.rs b/src/librustc_privacy/lib.rs index 20f09ef52f00b..3c3fe190a8395 100644 --- a/src/librustc_privacy/lib.rs +++ b/src/librustc_privacy/lib.rs @@ -345,15 +345,15 @@ fn def_id_visibility<'tcx>( } } -// Set the correct `TypeckTables` for the given `item_id` (or an empty table if -// there is no `TypeckTables` for the item). -fn item_tables<'a, 'tcx>( +// Set the correct `TypeckResults` for the given `item_id` (or an empty table if +// there is no `TypeckResults` for the item). +fn item_typeck_results<'a, 'tcx>( tcx: TyCtxt<'tcx>, hir_id: hir::HirId, - empty_tables: &'a ty::TypeckTables<'tcx>, -) -> &'a ty::TypeckTables<'tcx> { + empty_typeck_results: &'a ty::TypeckResults<'tcx>, +) -> &'a ty::TypeckResults<'tcx> { let def_id = tcx.hir().local_def_id(hir_id); - if tcx.has_typeck_tables(def_id) { tcx.typeck_tables_of(def_id) } else { empty_tables } + if tcx.has_typeck_results(def_id) { tcx.typeck(def_id) } else { empty_typeck_results } } fn min(vis1: ty::Visibility, vis2: ty::Visibility, tcx: TyCtxt<'_>) -> ty::Visibility { @@ -1031,9 +1031,9 @@ impl DefIdVisitor<'tcx> for ReachEverythingInTheInterfaceVisitor<'_, 'tcx> { struct NamePrivacyVisitor<'a, 'tcx> { tcx: TyCtxt<'tcx>, - tables: &'a ty::TypeckTables<'tcx>, + typeck_results: &'a ty::TypeckResults<'tcx>, current_item: Option, - empty_tables: &'a ty::TypeckTables<'tcx>, + empty_typeck_results: &'a ty::TypeckResults<'tcx>, } impl<'a, 'tcx> NamePrivacyVisitor<'a, 'tcx> { @@ -1087,39 +1087,46 @@ impl<'a, 'tcx> Visitor<'tcx> for NamePrivacyVisitor<'a, 'tcx> { } fn visit_nested_body(&mut self, body: hir::BodyId) { - let orig_tables = mem::replace(&mut self.tables, self.tcx.body_tables(body)); + let orig_typeck_results = + mem::replace(&mut self.typeck_results, self.tcx.typeck_body(body)); let body = self.tcx.hir().body(body); self.visit_body(body); - self.tables = orig_tables; + self.typeck_results = orig_typeck_results; } fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) { let orig_current_item = mem::replace(&mut self.current_item, Some(item.hir_id)); - let orig_tables = - mem::replace(&mut self.tables, item_tables(self.tcx, item.hir_id, self.empty_tables)); + let orig_typeck_results = mem::replace( + &mut self.typeck_results, + item_typeck_results(self.tcx, item.hir_id, self.empty_typeck_results), + ); intravisit::walk_item(self, item); self.current_item = orig_current_item; - self.tables = orig_tables; + self.typeck_results = orig_typeck_results; } fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem<'tcx>) { - let orig_tables = - mem::replace(&mut self.tables, item_tables(self.tcx, ti.hir_id, self.empty_tables)); + let orig_typeck_results = mem::replace( + &mut self.typeck_results, + item_typeck_results(self.tcx, ti.hir_id, self.empty_typeck_results), + ); intravisit::walk_trait_item(self, ti); - self.tables = orig_tables; + self.typeck_results = orig_typeck_results; } fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem<'tcx>) { - let orig_tables = - mem::replace(&mut self.tables, item_tables(self.tcx, ii.hir_id, self.empty_tables)); + let orig_typeck_results = mem::replace( + &mut self.typeck_results, + item_typeck_results(self.tcx, ii.hir_id, self.empty_typeck_results), + ); intravisit::walk_impl_item(self, ii); - self.tables = orig_tables; + self.typeck_results = orig_typeck_results; } fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) { if let hir::ExprKind::Struct(ref qpath, fields, ref base) = expr.kind { - let res = self.tables.qpath_res(qpath, expr.hir_id); - let adt = self.tables.expr_ty(expr).ty_adt_def().unwrap(); + let res = self.typeck_results.qpath_res(qpath, expr.hir_id); + let adt = self.typeck_results.expr_ty(expr).ty_adt_def().unwrap(); let variant = adt.variant_of_res(res); if let Some(ref base) = *base { // If the expression uses FRU we need to make sure all the unmentioned fields @@ -1128,7 +1135,7 @@ impl<'a, 'tcx> Visitor<'tcx> for NamePrivacyVisitor<'a, 'tcx> { for (vf_index, variant_field) in variant.fields.iter().enumerate() { let field = fields .iter() - .find(|f| self.tcx.field_index(f.hir_id, self.tables) == vf_index); + .find(|f| self.tcx.field_index(f.hir_id, self.typeck_results) == vf_index); let (use_ctxt, span) = match field { Some(field) => (field.ident.span, field.span), None => (base.span, base.span), @@ -1138,7 +1145,7 @@ impl<'a, 'tcx> Visitor<'tcx> for NamePrivacyVisitor<'a, 'tcx> { } else { for field in fields { let use_ctxt = field.ident.span; - let index = self.tcx.field_index(field.hir_id, self.tables); + let index = self.tcx.field_index(field.hir_id, self.typeck_results); self.check_field(use_ctxt, field.span, adt, &variant.fields[index], false); } } @@ -1149,12 +1156,12 @@ impl<'a, 'tcx> Visitor<'tcx> for NamePrivacyVisitor<'a, 'tcx> { fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) { if let PatKind::Struct(ref qpath, fields, _) = pat.kind { - let res = self.tables.qpath_res(qpath, pat.hir_id); - let adt = self.tables.pat_ty(pat).ty_adt_def().unwrap(); + let res = self.typeck_results.qpath_res(qpath, pat.hir_id); + let adt = self.typeck_results.pat_ty(pat).ty_adt_def().unwrap(); let variant = adt.variant_of_res(res); for field in fields { let use_ctxt = field.ident.span; - let index = self.tcx.field_index(field.hir_id, self.tables); + let index = self.tcx.field_index(field.hir_id, self.typeck_results); self.check_field(use_ctxt, field.span, adt, &variant.fields[index], false); } } @@ -1171,11 +1178,11 @@ impl<'a, 'tcx> Visitor<'tcx> for NamePrivacyVisitor<'a, 'tcx> { struct TypePrivacyVisitor<'a, 'tcx> { tcx: TyCtxt<'tcx>, - tables: &'a ty::TypeckTables<'tcx>, + typeck_results: &'a ty::TypeckResults<'tcx>, current_item: LocalDefId, in_body: bool, span: Span, - empty_tables: &'a ty::TypeckTables<'tcx>, + empty_typeck_results: &'a ty::TypeckResults<'tcx>, } impl<'a, 'tcx> TypePrivacyVisitor<'a, 'tcx> { @@ -1188,10 +1195,12 @@ impl<'a, 'tcx> TypePrivacyVisitor<'a, 'tcx> { // Take node-id of an expression or pattern and check its type for privacy. fn check_expr_pat_type(&mut self, id: hir::HirId, span: Span) -> bool { self.span = span; - if self.visit(self.tables.node_type(id)) || self.visit(self.tables.node_substs(id)) { + if self.visit(self.typeck_results.node_type(id)) + || self.visit(self.typeck_results.node_substs(id)) + { return true; } - if let Some(adjustments) = self.tables.adjustments().get(id) { + if let Some(adjustments) = self.typeck_results.adjustments().get(id) { for adjustment in adjustments { if self.visit(adjustment.target) { return true; @@ -1229,11 +1238,12 @@ impl<'a, 'tcx> Visitor<'tcx> for TypePrivacyVisitor<'a, 'tcx> { } fn visit_nested_body(&mut self, body: hir::BodyId) { - let orig_tables = mem::replace(&mut self.tables, self.tcx.body_tables(body)); + let orig_typeck_results = + mem::replace(&mut self.typeck_results, self.tcx.typeck_body(body)); let orig_in_body = mem::replace(&mut self.in_body, true); let body = self.tcx.hir().body(body); self.visit_body(body); - self.tables = orig_tables; + self.typeck_results = orig_typeck_results; self.in_body = orig_in_body; } @@ -1241,7 +1251,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypePrivacyVisitor<'a, 'tcx> { self.span = hir_ty.span; if self.in_body { // Types in bodies. - if self.visit(self.tables.node_type(hir_ty.hir_id)) { + if self.visit(self.typeck_results.node_type(hir_ty.hir_id)) { return; } } else { @@ -1304,7 +1314,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypePrivacyVisitor<'a, 'tcx> { hir::ExprKind::MethodCall(_, span, _, _) => { // Method calls have to be checked specially. self.span = span; - if let Some(def_id) = self.tables.type_dependent_def_id(expr.hir_id) { + if let Some(def_id) = self.typeck_results.type_dependent_def_id(expr.hir_id) { if self.visit(self.tcx.type_of(def_id)) { return; } @@ -1327,7 +1337,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypePrivacyVisitor<'a, 'tcx> { // more code internal visibility at link time. (Access to private functions // is already prohibited by type privacy for function types.) fn visit_qpath(&mut self, qpath: &'tcx hir::QPath<'tcx>, id: hir::HirId, span: Span) { - let def = match self.tables.qpath_res(qpath, id) { + let def = match self.typeck_results.qpath_res(qpath, id) { Res::Def(kind, def_id) => Some((kind, def_id)), _ => None, }; @@ -1386,26 +1396,32 @@ impl<'a, 'tcx> Visitor<'tcx> for TypePrivacyVisitor<'a, 'tcx> { let orig_current_item = mem::replace(&mut self.current_item, self.tcx.hir().local_def_id(item.hir_id)); let orig_in_body = mem::replace(&mut self.in_body, false); - let orig_tables = - mem::replace(&mut self.tables, item_tables(self.tcx, item.hir_id, self.empty_tables)); + let orig_typeck_results = mem::replace( + &mut self.typeck_results, + item_typeck_results(self.tcx, item.hir_id, self.empty_typeck_results), + ); intravisit::walk_item(self, item); - self.tables = orig_tables; + self.typeck_results = orig_typeck_results; self.in_body = orig_in_body; self.current_item = orig_current_item; } fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem<'tcx>) { - let orig_tables = - mem::replace(&mut self.tables, item_tables(self.tcx, ti.hir_id, self.empty_tables)); + let orig_typeck_results = mem::replace( + &mut self.typeck_results, + item_typeck_results(self.tcx, ti.hir_id, self.empty_typeck_results), + ); intravisit::walk_trait_item(self, ti); - self.tables = orig_tables; + self.typeck_results = orig_typeck_results; } fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem<'tcx>) { - let orig_tables = - mem::replace(&mut self.tables, item_tables(self.tcx, ii.hir_id, self.empty_tables)); + let orig_typeck_results = mem::replace( + &mut self.typeck_results, + item_typeck_results(self.tcx, ii.hir_id, self.empty_typeck_results), + ); intravisit::walk_impl_item(self, ii); - self.tables = orig_tables; + self.typeck_results = orig_typeck_results; } } @@ -2066,14 +2082,14 @@ pub fn provide(providers: &mut Providers<'_>) { } fn check_mod_privacy(tcx: TyCtxt<'_>, module_def_id: LocalDefId) { - let empty_tables = ty::TypeckTables::empty(None); + let empty_typeck_results = ty::TypeckResults::empty(None); // Check privacy of names not checked in previous compilation stages. let mut visitor = NamePrivacyVisitor { tcx, - tables: &empty_tables, + typeck_results: &empty_typeck_results, current_item: None, - empty_tables: &empty_tables, + empty_typeck_results: &empty_typeck_results, }; let (module, span, hir_id) = tcx.hir().get_module(module_def_id); @@ -2083,11 +2099,11 @@ fn check_mod_privacy(tcx: TyCtxt<'_>, module_def_id: LocalDefId) { // inferred types of expressions and patterns. let mut visitor = TypePrivacyVisitor { tcx, - tables: &empty_tables, + typeck_results: &empty_typeck_results, current_item: module_def_id, in_body: false, span, - empty_tables: &empty_tables, + empty_typeck_results: &empty_typeck_results, }; intravisit::walk_mod(&mut visitor, module, hir_id); } diff --git a/src/librustc_resolve/build_reduced_graph.rs b/src/librustc_resolve/build_reduced_graph.rs index a92d451dfd006..bca65c63e9198 100644 --- a/src/librustc_resolve/build_reduced_graph.rs +++ b/src/librustc_resolve/build_reduced_graph.rs @@ -1325,7 +1325,7 @@ impl<'a, 'b> Visitor<'b> for BuildReducedGraphVisitor<'a, 'b> { } fn visit_token(&mut self, t: Token) { - if let token::Interpolated(nt, _) = t.kind { + if let token::Interpolated(nt) = t.kind { if let token::NtExpr(ref expr) = *nt { if let ast::ExprKind::MacCall(..) = expr.kind { self.visit_invoc(expr.id); diff --git a/src/librustc_resolve/def_collector.rs b/src/librustc_resolve/def_collector.rs index c25a20210e026..32af920020ce6 100644 --- a/src/librustc_resolve/def_collector.rs +++ b/src/librustc_resolve/def_collector.rs @@ -256,7 +256,7 @@ impl<'a, 'b> visit::Visitor<'a> for DefCollector<'a, 'b> { } fn visit_token(&mut self, t: Token) { - if let token::Interpolated(nt, _) = t.kind { + if let token::Interpolated(nt) = t.kind { if let token::NtExpr(ref expr) = *nt { if let ExprKind::MacCall(..) = expr.kind { self.visit_macro_invoc(expr.id); diff --git a/src/librustc_save_analysis/dump_visitor.rs b/src/librustc_save_analysis/dump_visitor.rs index e63e31e03c9f0..c005f353eb6e4 100644 --- a/src/librustc_save_analysis/dump_visitor.rs +++ b/src/librustc_save_analysis/dump_visitor.rs @@ -104,20 +104,20 @@ impl<'l, 'tcx> DumpVisitor<'l, 'tcx> { self.dumper.analysis() } - fn nest_tables(&mut self, item_def_id: LocalDefId, f: F) + fn nest_typeck_results(&mut self, item_def_id: LocalDefId, f: F) where F: FnOnce(&mut Self), { - let tables = if self.tcx.has_typeck_tables(item_def_id) { - self.tcx.typeck_tables_of(item_def_id) + let typeck_results = if self.tcx.has_typeck_results(item_def_id) { + self.tcx.typeck(item_def_id) } else { - self.save_ctxt.empty_tables + self.save_ctxt.empty_typeck_results }; - let old_tables = self.save_ctxt.tables; - self.save_ctxt.tables = tables; + let old_typeck_results = self.save_ctxt.typeck_results; + self.save_ctxt.typeck_results = typeck_results; f(self); - self.save_ctxt.tables = old_tables; + self.save_ctxt.typeck_results = old_typeck_results; } fn span_from_span(&self, span: Span) -> SpanData { @@ -226,7 +226,7 @@ impl<'l, 'tcx> DumpVisitor<'l, 'tcx> { collector.visit_pat(&arg.pat); for (hir_id, ident, ..) in collector.collected_idents { - let typ = match self.save_ctxt.tables.node_type_opt(hir_id) { + let typ = match self.save_ctxt.typeck_results.node_type_opt(hir_id) { Some(s) => s.to_string(), None => continue, }; @@ -269,7 +269,7 @@ impl<'l, 'tcx> DumpVisitor<'l, 'tcx> { debug!("process_method: {}:{}", hir_id, ident); let map = &self.tcx.hir(); - self.nest_tables(map.local_def_id(hir_id), |v| { + self.nest_typeck_results(map.local_def_id(hir_id), |v| { if let Some(mut method_data) = v.save_ctxt.get_method_data(hir_id, ident, span) { if let Some(body) = body { v.process_formals(map.body(body).params, &method_data.qualname); @@ -363,7 +363,7 @@ impl<'l, 'tcx> DumpVisitor<'l, 'tcx> { body: hir::BodyId, ) { let map = &self.tcx.hir(); - self.nest_tables(map.local_def_id(item.hir_id), |v| { + self.nest_typeck_results(map.local_def_id(item.hir_id), |v| { let body = map.body(body); if let Some(fn_data) = v.save_ctxt.get_item_data(item) { down_cast_data!(fn_data, DefData, item.span); @@ -391,7 +391,7 @@ impl<'l, 'tcx> DumpVisitor<'l, 'tcx> { typ: &'tcx hir::Ty<'tcx>, expr: &'tcx hir::Expr<'tcx>, ) { - self.nest_tables(self.tcx.hir().local_def_id(item.hir_id), |v| { + self.nest_typeck_results(self.tcx.hir().local_def_id(item.hir_id), |v| { if let Some(var_data) = v.save_ctxt.get_item_data(item) { down_cast_data!(var_data, DefData, item.span); v.dumper.dump_def(&access_from!(v.save_ctxt, item, item.hir_id), var_data); @@ -438,7 +438,7 @@ impl<'l, 'tcx> DumpVisitor<'l, 'tcx> { } // walk type and init value - self.nest_tables(self.tcx.hir().local_def_id(hir_id), |v| { + self.nest_typeck_results(self.tcx.hir().local_def_id(hir_id), |v| { v.visit_ty(typ); if let Some(expr) = expr { v.visit_expr(expr); @@ -508,7 +508,7 @@ impl<'l, 'tcx> DumpVisitor<'l, 'tcx> { ); } - self.nest_tables(self.tcx.hir().local_def_id(item.hir_id), |v| { + self.nest_typeck_results(self.tcx.hir().local_def_id(item.hir_id), |v| { for field in def.fields() { v.process_struct_field_def(field, item.hir_id); v.visit_ty(&field.ty); @@ -641,7 +641,7 @@ impl<'l, 'tcx> DumpVisitor<'l, 'tcx> { } let map = &self.tcx.hir(); - self.nest_tables(map.local_def_id(item.hir_id), |v| { + self.nest_typeck_results(map.local_def_id(item.hir_id), |v| { v.visit_ty(&typ); if let &Some(ref trait_ref) = trait_ref { v.process_path(trait_ref.hir_ref_id, &hir::QPath::Resolved(None, &trait_ref.path)); @@ -859,7 +859,7 @@ impl<'l, 'tcx> DumpVisitor<'l, 'tcx> { match p.kind { hir::PatKind::Struct(ref _path, fields, _) => { // FIXME do something with _path? - let adt = match self.save_ctxt.tables.node_type_opt(p.hir_id) { + let adt = match self.save_ctxt.typeck_results.node_type_opt(p.hir_id) { Some(ty) if ty.ty_adt_def().is_some() => ty.ty_adt_def().unwrap(), _ => { intravisit::walk_pat(self, p); @@ -900,7 +900,7 @@ impl<'l, 'tcx> DumpVisitor<'l, 'tcx> { Res::Local(hir_id) => { let typ = self .save_ctxt - .tables + .typeck_results .node_type_opt(hir_id) .map(|t| t.to_string()) .unwrap_or_default(); @@ -1375,13 +1375,15 @@ impl<'l, 'tcx> Visitor<'tcx> for DumpVisitor<'l, 'tcx> { hir::TyKind::Array(ref ty, ref anon_const) => { self.visit_ty(ty); let map = self.tcx.hir(); - self.nest_tables(self.tcx.hir().local_def_id(anon_const.hir_id), |v| { + self.nest_typeck_results(self.tcx.hir().local_def_id(anon_const.hir_id), |v| { v.visit_expr(&map.body(anon_const.body).value) }); } hir::TyKind::OpaqueDef(item_id, _) => { let item = self.tcx.hir().item(item_id.id); - self.nest_tables(self.tcx.hir().local_def_id(item_id.id), |v| v.visit_item(item)); + self.nest_typeck_results(self.tcx.hir().local_def_id(item_id.id), |v| { + v.visit_item(item) + }); } _ => intravisit::walk_ty(self, t), } @@ -1393,7 +1395,7 @@ impl<'l, 'tcx> Visitor<'tcx> for DumpVisitor<'l, 'tcx> { match ex.kind { hir::ExprKind::Struct(ref path, ref fields, ref base) => { let hir_expr = self.save_ctxt.tcx.hir().expect_expr(ex.hir_id); - let adt = match self.save_ctxt.tables.expr_ty_opt(&hir_expr) { + let adt = match self.save_ctxt.typeck_results.expr_ty_opt(&hir_expr) { Some(ty) if ty.ty_adt_def().is_some() => ty.ty_adt_def().unwrap(), _ => { intravisit::walk_expr(self, ex); @@ -1430,7 +1432,7 @@ impl<'l, 'tcx> Visitor<'tcx> for DumpVisitor<'l, 'tcx> { // walk the body let map = self.tcx.hir(); - self.nest_tables(self.tcx.hir().local_def_id(ex.hir_id), |v| { + self.nest_typeck_results(self.tcx.hir().local_def_id(ex.hir_id), |v| { let body = map.body(body); v.process_formals(body.params, &id); v.visit_expr(&body.value) @@ -1439,7 +1441,7 @@ impl<'l, 'tcx> Visitor<'tcx> for DumpVisitor<'l, 'tcx> { hir::ExprKind::Repeat(ref expr, ref anon_const) => { self.visit_expr(expr); let map = self.tcx.hir(); - self.nest_tables(self.tcx.hir().local_def_id(anon_const.hir_id), |v| { + self.nest_typeck_results(self.tcx.hir().local_def_id(anon_const.hir_id), |v| { v.visit_expr(&map.body(anon_const.body).value) }); } diff --git a/src/librustc_save_analysis/lib.rs b/src/librustc_save_analysis/lib.rs index f5c3e84c62426..68c465b7b998c 100644 --- a/src/librustc_save_analysis/lib.rs +++ b/src/librustc_save_analysis/lib.rs @@ -49,10 +49,10 @@ use log::{debug, error, info}; pub struct SaveContext<'l, 'tcx> { tcx: TyCtxt<'tcx>, - tables: &'l ty::TypeckTables<'tcx>, - /// Used as a fallback when nesting the typeck tables during item processing + typeck_results: &'l ty::TypeckResults<'tcx>, + /// Used as a fallback when nesting the typeck typeck_results during item processing /// (if these are not available for that item, e.g. don't own a body) - empty_tables: &'l ty::TypeckTables<'tcx>, + empty_typeck_results: &'l ty::TypeckResults<'tcx>, access_levels: &'l AccessLevels, span_utils: SpanUtils<'tcx>, config: Config, @@ -477,7 +477,7 @@ impl<'l, 'tcx> SaveContext<'l, 'tcx> { None => { debug!("could not find container for method {} at {:?}", hir_id, span); // This is not necessarily a bug, if there was a compilation error, - // the tables we need might not exist. + // the typeck_results we need might not exist. return None; } }, @@ -518,13 +518,13 @@ impl<'l, 'tcx> SaveContext<'l, 'tcx> { } pub fn get_expr_data(&self, expr: &hir::Expr<'_>) -> Option { - let ty = self.tables.expr_ty_adjusted_opt(expr)?; + let ty = self.typeck_results.expr_ty_adjusted_opt(expr)?; if matches!(ty.kind, ty::Error(_)) { return None; } match expr.kind { hir::ExprKind::Field(ref sub_ex, ident) => { - match self.tables.expr_ty_adjusted(&sub_ex).kind { + match self.typeck_results.expr_ty_adjusted(&sub_ex).kind { ty::Adt(def, _) if !def.is_enum() => { let variant = &def.non_enum_variant(); filter!(self.span_utils, ident.span); @@ -569,7 +569,7 @@ impl<'l, 'tcx> SaveContext<'l, 'tcx> { } } hir::ExprKind::MethodCall(ref seg, ..) => { - let method_id = match self.tables.type_dependent_def_id(expr.hir_id) { + let method_id = match self.typeck_results.type_dependent_def_id(expr.hir_id) { Some(id) => id, None => { debug!("could not resolve method id for {:?}", expr); @@ -618,7 +618,7 @@ impl<'l, 'tcx> SaveContext<'l, 'tcx> { }, Node::Expr(&hir::Expr { kind: hir::ExprKind::Struct(ref qpath, ..), .. }) => { - self.tables.qpath_res(qpath, hir_id) + self.typeck_results.qpath_res(qpath, hir_id) } Node::Expr(&hir::Expr { kind: hir::ExprKind::Path(ref qpath), .. }) @@ -630,7 +630,7 @@ impl<'l, 'tcx> SaveContext<'l, 'tcx> { .. }) | Node::Ty(&hir::Ty { kind: hir::TyKind::Path(ref qpath), .. }) => { - self.tables.qpath_res(qpath, hir_id) + self.typeck_results.qpath_res(qpath, hir_id) } Node::Binding(&hir::Pat { @@ -1001,8 +1001,8 @@ pub fn process_crate<'l, 'tcx, H: SaveHandler>( let save_ctxt = SaveContext { tcx, - tables: &ty::TypeckTables::empty(None), - empty_tables: &ty::TypeckTables::empty(None), + typeck_results: &ty::TypeckResults::empty(None), + empty_typeck_results: &ty::TypeckResults::empty(None), access_levels: &access_levels, span_utils: SpanUtils::new(&tcx.sess), config: find_config(config), diff --git a/src/librustc_session/options.rs b/src/librustc_session/options.rs index 9337f241d7022..ed5fd6dc7028b 100644 --- a/src/librustc_session/options.rs +++ b/src/librustc_session/options.rs @@ -958,9 +958,6 @@ options! {DebuggingOptions, DebuggingSetter, basic_debugging_options, "print the LLVM optimization passes being run (default: no)"), print_mono_items: Option = (None, parse_opt_string, [UNTRACKED], "print the result of the monomorphization collection pass"), - print_region_graph: bool = (false, parse_bool, [UNTRACKED], - "prints region inference graph. \ - Use with RUST_REGION_GRAPH=help for more info (default: no)"), print_type_sizes: bool = (false, parse_bool, [UNTRACKED], "print layout information for each type encountered (default: no)"), profile: bool = (false, parse_bool, [TRACKED], diff --git a/src/librustc_span/lib.rs b/src/librustc_span/lib.rs index 6dcb1430cdc17..046554067f4ce 100644 --- a/src/librustc_span/lib.rs +++ b/src/librustc_span/lib.rs @@ -309,7 +309,9 @@ impl Ord for Span { } } -/// A collection of spans. Spans have two orthogonal attributes: +/// A collection of `Span`s. +/// +/// Spans have two orthogonal attributes: /// /// - They can be *primary spans*. In this case they are the locus of /// the error, and would be rendered with `^^^`. diff --git a/src/librustc_span/symbol.rs b/src/librustc_span/symbol.rs index e2f0d0b94c46c..d1722942f35f7 100644 --- a/src/librustc_span/symbol.rs +++ b/src/librustc_span/symbol.rs @@ -152,10 +152,14 @@ symbols! { arm_target_feature, asm, assert, + assert_inhabited, + assert_uninit_valid, + assert_zero_valid, associated_consts, associated_type_bounds, associated_type_defaults, associated_types, + assume, assume_init, async_await, async_closure, @@ -181,11 +185,14 @@ symbols! { box_patterns, box_syntax, braced_empty_structs, + breakpoint, bswap, bitreverse, C, caller_location, cdylib, + ceilf32, + ceilf64, cfg, cfg_accessible, cfg_attr, @@ -239,8 +246,14 @@ symbols! { convert, Copy, copy_closures, + copy, + copy_nonoverlapping, + copysignf32, + copysignf64, core, core_intrinsics, + cosf32, + cosf64, count_code_region, crate_id, crate_in_paths, @@ -296,6 +309,7 @@ symbols! { dropck_eyepatch, dropck_parametricity, drop_types_in_const, + drop_in_place, dylib, dyn_trait, eh_personality, @@ -308,11 +322,16 @@ symbols! { Eq, Equal, enclosing_scope, + exact_div, except, exclusive_range_pattern, exhaustive_integer_patterns, exhaustive_patterns, existential_type, + expf32, + expf64, + exp2f32, + exp2f64, expected, export_name, expr, @@ -326,6 +345,10 @@ symbols! { f16c_target_feature, f32, f64, + fadd_fast, + fabsf32, + fabsf64, + fdiv_fast, feature, ffi_const, ffi_pure, @@ -333,12 +356,20 @@ symbols! { field, field_init_shorthand, file, + float_to_int_unchecked, + floorf64, + floorf32, + fmaf32, + fmaf64, fmt, fmt_internals, + fmul_fast, fn_must_use, forbid, + forget, format_args, format_args_nl, + frem_fast, from, From, from_desugaring, @@ -348,6 +379,7 @@ symbols! { from_ok, from_usize, from_trait, + fsub_fast, fundamental, future, Future, @@ -401,6 +433,7 @@ symbols! { infer_outlives_requirements, infer_static_outlives_requirements, inline, + Input, intel, into_iter, IntoIterator, @@ -443,6 +476,12 @@ symbols! { llvm_asm, local_inner_macros, log_syntax, + logf32, + logf64, + log10f32, + log10f64, + log2f32, + log2f64, loop_break_value, macro_at_most_once_rep, macro_escape, @@ -470,10 +509,16 @@ symbols! { message, meta, min_align_of, + min_align_of_val, min_const_fn, min_const_unsafe_fn, min_specialization, + minnumf32, + minnumf64, + maxnumf32, + maxnumf64, mips_target_feature, + miri_start_panic, mmx_target_feature, module, module_path, @@ -486,6 +531,8 @@ symbols! { naked, naked_functions, name, + nearbyintf32, + nearbyintf64, needs_allocator, needs_drop, needs_panic_runtime, @@ -513,6 +560,7 @@ symbols! { None, non_exhaustive, non_modrs_mods, + nontemporal_store, noreturn, no_niche, no_sanitize, @@ -571,8 +619,16 @@ symbols! { poll, Poll, powerpc_target_feature, + powf32, + powf64, + powif32, + powif64, precise_pointer_size_matching, pref_align_of, + prefetch_read_data, + prefetch_read_instruction, + prefetch_write_data, + prefetch_write_instruction, prelude, prelude_import, preserves_flags, @@ -589,6 +645,8 @@ symbols! { proc_macro_mod, proc_macro_non_items, proc_macro_path_invoc, + ProceduralMasqueradeDummyType, + ProcMacroHack, profiler_builtins, profiler_runtime, ptr_guaranteed_eq, @@ -632,10 +690,14 @@ symbols! { Result, Return, rhs, + rintf32, + rintf64, riscv_target_feature, rlib, rotate_left, rotate_right, + roundf32, + roundf64, rt, rtm_target_feature, rust, @@ -718,14 +780,19 @@ symbols! { simd_ffi, simd_insert, since, + sinf32, + sinf64, size, size_of, + size_of_val, slice_patterns, slicing_syntax, soft, Some, specialization, speed, + sqrtf32, + sqrtf64, sse4a_target_feature, stable, staged_api, @@ -779,6 +846,8 @@ symbols! { transparent_enums, transparent_unions, trivial_bounds, + truncf32, + truncf64, Try, try_blocks, try_trait, @@ -801,6 +870,8 @@ symbols! { u32, u64, u8, + unaligned_volatile_load, + unaligned_volatile_store, unboxed_closures, unchecked_add, unchecked_div, @@ -816,6 +887,7 @@ symbols! { universal_impl_trait, unlikely, unmarked_api, + unreachable, unreachable_code, unrestricted_attribute_tokens, unsafe_block_in_unsafe_fn, @@ -835,12 +907,21 @@ symbols! { val, var, variant_count, + va_arg, + va_copy, + va_end, + va_start, vec, Vec, version, vis, visible_private_types, volatile, + volatile_copy_memory, + volatile_copy_nonoverlapping_memory, + volatile_load, + volatile_set_memory, + volatile_store, warn, wasm_import_module, wasm_target_feature, @@ -850,6 +931,7 @@ symbols! { wrapping_add, wrapping_sub, wrapping_mul, + write_bytes, Yield, } } diff --git a/src/librustc_trait_selection/traits/error_reporting/mod.rs b/src/librustc_trait_selection/traits/error_reporting/mod.rs index 49e43873df759..6838aa2cf9bf8 100644 --- a/src/librustc_trait_selection/traits/error_reporting/mod.rs +++ b/src/librustc_trait_selection/traits/error_reporting/mod.rs @@ -429,6 +429,24 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { ); } + let is_fn_trait = [ + self.tcx.lang_items().fn_trait(), + self.tcx.lang_items().fn_mut_trait(), + self.tcx.lang_items().fn_once_trait(), + ] + .contains(&Some(trait_ref.def_id())); + let is_target_feature_fn = + if let ty::FnDef(def_id, _) = trait_ref.skip_binder().self_ty().kind { + !self.tcx.codegen_fn_attrs(def_id).target_features.is_empty() + } else { + false + }; + if is_fn_trait && is_target_feature_fn { + err.note( + "`#[target_feature]` functions do not implement the `Fn` traits", + ); + } + // Try to report a help message if !trait_ref.has_infer_types_or_consts() && self.predicate_can_apply(obligation.param_env, trait_ref) @@ -567,9 +585,9 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { // Additional context information explaining why the closure only implements // a particular trait. - if let Some(tables) = self.in_progress_tables { - let tables = tables.borrow(); - match (found_kind, tables.closure_kind_origins().get(hir_id)) { + if let Some(typeck_results) = self.in_progress_typeck_results { + let typeck_results = typeck_results.borrow(); + match (found_kind, typeck_results.closure_kind_origins().get(hir_id)) { (ty::ClosureKind::FnOnce, Some((span, name))) => { err.span_label( *span, diff --git a/src/librustc_trait_selection/traits/error_reporting/suggestions.rs b/src/librustc_trait_selection/traits/error_reporting/suggestions.rs index 1fafa9ec035ce..6c47654c9d163 100644 --- a/src/librustc_trait_selection/traits/error_reporting/suggestions.rs +++ b/src/librustc_trait_selection/traits/error_reporting/suggestions.rs @@ -18,7 +18,7 @@ use rustc_middle::ty::{ self, suggest_constraining_type_param, AdtKind, DefIdTree, Infer, InferTy, ToPredicate, Ty, TyCtxt, TypeFoldable, WithConstness, }; -use rustc_middle::ty::{TypeAndMut, TypeckTables}; +use rustc_middle::ty::{TypeAndMut, TypeckResults}; use rustc_span::symbol::{kw, sym, Ident, Symbol}; use rustc_span::{MultiSpan, Span, DUMMY_SP}; use std::fmt; @@ -151,7 +151,7 @@ pub trait InferCtxtExt<'tcx> { outer_generator: Option, trait_ref: ty::TraitRef<'tcx>, target_ty: Ty<'tcx>, - tables: &ty::TypeckTables<'tcx>, + typeck_results: &ty::TypeckResults<'tcx>, obligation: &PredicateObligation<'tcx>, next_code: Option<&ObligationCauseCode<'tcx>>, ); @@ -1000,12 +1000,12 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { let mut visitor = ReturnsVisitor::default(); visitor.visit_body(&body); - let tables = self.in_progress_tables.map(|t| t.borrow()).unwrap(); + let typeck_results = self.in_progress_typeck_results.map(|t| t.borrow()).unwrap(); let mut ret_types = visitor .returns .iter() - .filter_map(|expr| tables.node_type_opt(expr.hir_id)) + .filter_map(|expr| typeck_results.node_type_opt(expr.hir_id)) .map(|ty| self.resolve_vars_if_possible(&ty)); let (last_ty, all_returns_have_same_type, only_never_return) = ret_types.clone().fold( (None, true, true), @@ -1032,7 +1032,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { }, ); let all_returns_conform_to_trait = - if let Some(ty_ret_ty) = tables.node_type_opt(ret_ty.hir_id) { + if let Some(ty_ret_ty) = typeck_results.node_type_opt(ret_ty.hir_id) { match ty_ret_ty.kind { ty::Dynamic(predicates, _) => { let cause = ObligationCause::misc(ret_ty.span, ret_ty.hir_id); @@ -1160,9 +1160,9 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { // Point at all the `return`s in the function as they have failed trait bounds. let mut visitor = ReturnsVisitor::default(); visitor.visit_body(&body); - let tables = self.in_progress_tables.map(|t| t.borrow()).unwrap(); + let typeck_results = self.in_progress_typeck_results.map(|t| t.borrow()).unwrap(); for expr in &visitor.returns { - if let Some(returned_ty) = tables.node_type_opt(expr.hir_id) { + if let Some(returned_ty) = typeck_results.node_type_opt(expr.hir_id) { let ty = self.resolve_vars_if_possible(&returned_ty); err.span_label(expr.span, &format!("this returned value is of type `{}`", ty)); } @@ -1392,25 +1392,25 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { return false; } - // Get the tables from the infcx if the generator is the function we are + // Get the typeck_results from the infcx if the generator is the function we are // currently type-checking; otherwise, get them by performing a query. // This is needed to avoid cycles. - let in_progress_tables = self.in_progress_tables.map(|t| t.borrow()); + let in_progress_typeck_results = self.in_progress_typeck_results.map(|t| t.borrow()); let generator_did_root = self.tcx.closure_base_def_id(generator_did); debug!( "maybe_note_obligation_cause_for_async_await: generator_did={:?} \ - generator_did_root={:?} in_progress_tables.hir_owner={:?} span={:?}", + generator_did_root={:?} in_progress_typeck_results.hir_owner={:?} span={:?}", generator_did, generator_did_root, - in_progress_tables.as_ref().map(|t| t.hir_owner), + in_progress_typeck_results.as_ref().map(|t| t.hir_owner), span ); - let query_tables; - let tables: &TypeckTables<'tcx> = match &in_progress_tables { + let query_typeck_results; + let typeck_results: &TypeckResults<'tcx> = match &in_progress_typeck_results { Some(t) if t.hir_owner.map(|owner| owner.to_def_id()) == Some(generator_did_root) => t, _ => { - query_tables = self.tcx.typeck_tables_of(generator_did.expect_local()); - &query_tables + query_typeck_results = self.tcx.typeck(generator_did.expect_local()); + &query_typeck_results } }; @@ -1457,7 +1457,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { if let Some(upvars) = self.tcx.upvars_mentioned(generator_did) { interior_or_upvar_span = upvars.iter().find_map(|(upvar_id, upvar)| { - let upvar_ty = tables.node_type(*upvar_id); + let upvar_ty = typeck_results.node_type(*upvar_id); let upvar_ty = self.resolve_vars_if_possible(&upvar_ty); if ty_matches(&upvar_ty) { Some(GeneratorInteriorOrUpvar::Upvar(upvar.span)) @@ -1467,7 +1467,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { }); }; - tables + typeck_results .generator_interior_types .iter() .find(|ty::GeneratorInteriorTypeCause { ty, .. }| ty_matches(ty)) @@ -1478,7 +1478,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { .into_iter() .map(|id| hir.expect_expr(id)) .find(|await_expr| { - let ty = tables.expr_ty_adjusted(&await_expr); + let ty = typeck_results.expr_ty_adjusted(&await_expr); debug!( "maybe_note_obligation_cause_for_async_await: await_expr={:?}", await_expr @@ -1496,7 +1496,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { debug!( "maybe_note_obligation_cause_for_async_await: interior_or_upvar={:?} \ generator_interior_types={:?}", - interior_or_upvar_span, tables.generator_interior_types + interior_or_upvar_span, typeck_results.generator_interior_types ); if let Some(interior_or_upvar_span) = interior_or_upvar_span { self.note_obligation_cause_for_async_await( @@ -1507,7 +1507,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { outer_generator, trait_ref, target_ty, - tables, + typeck_results, obligation, next_code, ); @@ -1528,7 +1528,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { outer_generator: Option, trait_ref: ty::TraitRef<'tcx>, target_ty: Ty<'tcx>, - tables: &ty::TypeckTables<'tcx>, + typeck_results: &ty::TypeckResults<'tcx>, obligation: &PredicateObligation<'tcx>, next_code: Option<&ObligationCauseCode<'tcx>>, ) { @@ -1645,7 +1645,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { // Look at the last interior type to get a span for the `.await`. debug!( "note_obligation_cause_for_async_await generator_interior_types: {:#?}", - tables.generator_interior_types + typeck_results.generator_interior_types ); explain_yield(interior_span, yield_span, scope_span); } @@ -1666,7 +1666,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { // ^^^^^^^ a temporary `&T` created inside this method call due to `&self` // ``` // - let is_region_borrow = tables + let is_region_borrow = typeck_results .expr_adjustments(expr) .iter() .any(|adj| adj.is_region_borrow()); @@ -1683,7 +1683,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { _ => false, }; - if (tables.is_method_call(e) && is_region_borrow) + if (typeck_results.is_method_call(e) && is_region_borrow) || is_raw_borrow_inside_fn_like_call { err.span_help( diff --git a/src/librustc_trait_selection/traits/select/candidate_assembly.rs b/src/librustc_trait_selection/traits/select/candidate_assembly.rs index 91c162872b215..597a7a58022cd 100644 --- a/src/librustc_trait_selection/traits/select/candidate_assembly.rs +++ b/src/librustc_trait_selection/traits/select/candidate_assembly.rs @@ -306,7 +306,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { candidates.ambiguous = true; // Could wind up being a fn() type. } // Provide an impl, but only for suitable `fn` pointers. - ty::FnDef(..) | ty::FnPtr(_) => { + ty::FnPtr(_) => { if let ty::FnSig { unsafety: hir::Unsafety::Normal, abi: Abi::Rust, @@ -317,6 +317,20 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { candidates.vec.push(FnPointerCandidate); } } + // Provide an impl for suitable functions, rejecting `#[target_feature]` functions (RFC 2396). + ty::FnDef(def_id, _) => { + if let ty::FnSig { + unsafety: hir::Unsafety::Normal, + abi: Abi::Rust, + c_variadic: false, + .. + } = self_ty.fn_sig(self.tcx()).skip_binder() + { + if self.tcx().codegen_fn_attrs(def_id).target_features.is_empty() { + candidates.vec.push(FnPointerCandidate); + } + } + } _ => {} } diff --git a/src/librustc_typeck/check/callee.rs b/src/librustc_typeck/check/callee.rs index 308ed5d840202..95bb19d27def7 100644 --- a/src/librustc_typeck/check/callee.rs +++ b/src/librustc_typeck/check/callee.rs @@ -337,7 +337,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let mut inner_callee_path = None; let def = match callee.kind { hir::ExprKind::Path(ref qpath) => { - self.tables.borrow().qpath_res(qpath, callee.hir_id) + self.typeck_results.borrow().qpath_res(qpath, callee.hir_id) } hir::ExprKind::Call(ref inner_callee, _) => { // If the call spans more than one line and the callee kind is @@ -355,7 +355,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } if let hir::ExprKind::Path(ref inner_qpath) = inner_callee.kind { inner_callee_path = Some(inner_qpath); - self.tables.borrow().qpath_res(inner_qpath, inner_callee.hir_id) + self.typeck_results + .borrow() + .qpath_res(inner_qpath, inner_callee.hir_id) } else { Res::Err } diff --git a/src/librustc_typeck/check/cast.rs b/src/librustc_typeck/check/cast.rs index 1ea7bf25ef2ed..a27f84ff41603 100644 --- a/src/librustc_typeck/check/cast.rs +++ b/src/librustc_typeck/check/cast.rs @@ -565,7 +565,7 @@ impl<'a, 'tcx> CastCheck<'tcx> { Ok(()) => { self.trivial_cast_lint(fcx); debug!(" -> CoercionCast"); - fcx.tables.borrow_mut().set_coercion_cast(self.expr.hir_id.local_id); + fcx.typeck_results.borrow_mut().set_coercion_cast(self.expr.hir_id.local_id); } Err(ty::error::TypeError::ObjectUnsafeCoercion(did)) => { self.report_object_unsafe_cast(&fcx, did); @@ -695,7 +695,7 @@ impl<'a, 'tcx> CastCheck<'tcx> { m_cast: ty::TypeAndMut<'tcx>, ) -> Result { debug!("check_ptr_ptr_cast m_expr={:?} m_cast={:?}", m_expr, m_cast); - // ptr-ptr cast. vtables must match. + // ptr-ptr cast. vtypeck_results must match. let expr_kind = fcx.pointer_kind(m_expr.ty, self.span)?; let cast_kind = fcx.pointer_kind(m_cast.ty, self.span)?; diff --git a/src/librustc_typeck/check/closure.rs b/src/librustc_typeck/check/closure.rs index fce2b18b782fb..d95e18578f846 100644 --- a/src/librustc_typeck/check/closure.rs +++ b/src/librustc_typeck/check/closure.rs @@ -416,7 +416,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Up till this point, we have ignored the annotations that the user // gave. This function will check that they unify successfully. // Along the way, it also writes out entries for types that the user - // wrote into our tables, which are then later used by the privacy + // wrote into our typeck_results, which are then later used by the privacy // check. match self.check_supplied_sig_against_expectation(expr_def_id, decl, body, &closure_sigs) { Ok(infer_ok) => self.register_infer_ok_obligations(infer_ok), @@ -588,7 +588,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { debug!("supplied_sig_of_closure: result={:?}", result); let c_result = self.inh.infcx.canonicalize_response(&result); - self.tables.borrow_mut().user_provided_sigs.insert(expr_def_id, c_result); + self.typeck_results.borrow_mut().user_provided_sigs.insert(expr_def_id, c_result); result } diff --git a/src/librustc_typeck/check/coercion.rs b/src/librustc_typeck/check/coercion.rs index e6b3224050e9b..5cf2e2d64100c 100644 --- a/src/librustc_typeck/check/coercion.rs +++ b/src/librustc_typeck/check/coercion.rs @@ -1000,7 +1000,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // First try to coerce the new expression to the type of the previous ones, // but only if the new expression has no coercion already applied to it. let mut first_error = None; - if !self.tables.borrow().adjustments().contains_key(new.hir_id) { + if !self.typeck_results.borrow().adjustments().contains_key(new.hir_id) { let result = self.commit_if_ok(|_| coerce.coerce(new_ty, prev_ty)); match result { Ok(ok) => { @@ -1021,7 +1021,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // previous expressions, other than noop reborrows (ignoring lifetimes). for expr in exprs { let expr = expr.as_coercion_site(); - let noop = match self.tables.borrow().expr_adjustments(expr) { + let noop = match self.typeck_results.borrow().expr_adjustments(expr) { &[Adjustment { kind: Adjust::Deref(_), .. }, Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(_, mutbl_adj)), .. }] => { match self.node_ty(expr.hir_id).kind { diff --git a/src/librustc_typeck/check/demand.rs b/src/librustc_typeck/check/demand.rs index 85c073ca30034..a5c3070ba8860 100644 --- a/src/librustc_typeck/check/demand.rs +++ b/src/librustc_typeck/check/demand.rs @@ -320,7 +320,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { _ => return None, }; - let self_ty = self.tables.borrow().node_type(method_expr[0].hir_id); + let self_ty = self.typeck_results.borrow().node_type(method_expr[0].hir_id); let self_ty = format!("{:?}", self_ty); let name = method_path.ident.as_str(); let is_as_ref_able = (self_ty.starts_with("&std::option::Option") @@ -466,10 +466,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let clone_trait = self.tcx.require_lang_item(CloneTraitLangItem, Some(sp)); if let ([arg], Some(true), sym::clone) = ( &args[..], - self.tables.borrow().type_dependent_def_id(expr.hir_id).map(|did| { - let ai = self.tcx.associated_item(did); - ai.container == ty::TraitContainer(clone_trait) - }), + self.typeck_results.borrow().type_dependent_def_id(expr.hir_id).map( + |did| { + let ai = self.tcx.associated_item(did); + ai.container == ty::TraitContainer(clone_trait) + }, + ), segment.ident.name, ) { // If this expression had a clone call when suggesting borrowing diff --git a/src/librustc_typeck/check/expr.rs b/src/librustc_typeck/check/expr.rs index 1eaa5a6c31e20..eaee07d23638e 100644 --- a/src/librustc_typeck/check/expr.rs +++ b/src/librustc_typeck/check/expr.rs @@ -68,7 +68,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // coercions from ! to `expected`. if ty.is_never() { assert!( - !self.tables.borrow().adjustments().contains_key(expr.hir_id), + !self.typeck_results.borrow().adjustments().contains_key(expr.hir_id), "expression with never type wound up being adjusted" ); let adj_ty = self.next_diverging_ty_var(TypeVariableOrigin { @@ -430,7 +430,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // This is maybe too permissive, since it allows // `let u = &raw const Box::new((1,)).0`, which creates an // immediately dangling raw pointer. - self.tables.borrow().adjustments().get(base.hir_id).map_or(false, |x| { + self.typeck_results.borrow().adjustments().get(base.hir_id).map_or(false, |x| { x.iter().any(|adj| if let Adjust::Deref(_) = adj.kind { true } else { false }) }) }); @@ -509,7 +509,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // We always require that the type provided as the value for // a type parameter outlives the moment of instantiation. - let substs = self.tables.borrow().node_substs(expr.hir_id); + let substs = self.typeck_results.borrow().node_substs(expr.hir_id); self.add_wf_bounds(substs, expr); ty @@ -1123,7 +1123,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }) .collect(); - self.tables + self.typeck_results .borrow_mut() .fru_field_types_mut() .insert(expr.hir_id, fru_field_types); diff --git a/src/librustc_typeck/check/generator_interior.rs b/src/librustc_typeck/check/generator_interior.rs index ce376a08ea604..e696353d4dbaf 100644 --- a/src/librustc_typeck/check/generator_interior.rs +++ b/src/librustc_typeck/check/generator_interior.rs @@ -190,8 +190,8 @@ pub fn resolve_interior<'a, 'tcx>( let type_list = fcx.tcx.mk_type_list(type_causes.iter().map(|cause| cause.ty)); let witness = fcx.tcx.mk_generator_witness(ty::Binder::bind(type_list)); - // Store the generator types and spans into the tables for this generator. - visitor.fcx.inh.tables.borrow_mut().generator_interior_types = type_causes; + // Store the generator types and spans into the typeck_results for this generator. + visitor.fcx.inh.typeck_results.borrow_mut().generator_interior_types = type_causes; debug!( "types in generator after region replacement {:?}, span = {:?}", @@ -222,7 +222,7 @@ impl<'a, 'tcx> Visitor<'tcx> for InteriorVisitor<'a, 'tcx> { if let PatKind::Binding(..) = pat.kind { let scope = self.region_scope_tree.var_scope(pat.hir_id.local_id); - let ty = self.fcx.tables.borrow().pat_ty(pat); + let ty = self.fcx.typeck_results.borrow().pat_ty(pat); self.record(ty, Some(scope), None, pat.span); } } @@ -231,7 +231,7 @@ impl<'a, 'tcx> Visitor<'tcx> for InteriorVisitor<'a, 'tcx> { match &expr.kind { ExprKind::Call(callee, args) => match &callee.kind { ExprKind::Path(qpath) => { - let res = self.fcx.tables.borrow().qpath_res(qpath, callee.hir_id); + let res = self.fcx.typeck_results.borrow().qpath_res(qpath, callee.hir_id); match res { // Direct calls never need to keep the callee `ty::FnDef` // ZST in a temporary, so skip its type, just in case it @@ -263,7 +263,7 @@ impl<'a, 'tcx> Visitor<'tcx> for InteriorVisitor<'a, 'tcx> { // If there are adjustments, then record the final type -- // this is the actual value that is being produced. - if let Some(adjusted_ty) = self.fcx.tables.borrow().expr_ty_adjusted_opt(expr) { + if let Some(adjusted_ty) = self.fcx.typeck_results.borrow().expr_ty_adjusted_opt(expr) { self.record(adjusted_ty, scope, Some(expr), expr.span); } @@ -291,7 +291,7 @@ impl<'a, 'tcx> Visitor<'tcx> for InteriorVisitor<'a, 'tcx> { // // The type table might not have information for this expression // if it is in a malformed scope. (#66387) - if let Some(ty) = self.fcx.tables.borrow().expr_ty_opt(expr) { + if let Some(ty) = self.fcx.typeck_results.borrow().expr_ty_opt(expr) { self.record(ty, scope, Some(expr), expr.span); } else { self.fcx.tcx.sess.delay_span_bug(expr.span, "no type for node"); diff --git a/src/librustc_typeck/check/intrinsic.rs b/src/librustc_typeck/check/intrinsic.rs index 1c0b22ca7370b..62e62435a08ea 100644 --- a/src/librustc_typeck/check/intrinsic.rs +++ b/src/librustc_typeck/check/intrinsic.rs @@ -5,10 +5,11 @@ use crate::require_same_types; use rustc_errors::struct_span_err; use rustc_hir as hir; +use rustc_hir::def_id::DefId; use rustc_middle::traits::{ObligationCause, ObligationCauseCode}; use rustc_middle::ty::subst::Subst; use rustc_middle::ty::{self, Ty, TyCtxt}; -use rustc_span::symbol::Symbol; +use rustc_span::symbol::{kw, sym, Symbol}; use rustc_target::spec::abi::Abi; use std::iter; @@ -16,14 +17,13 @@ use std::iter; fn equate_intrinsic_type<'tcx>( tcx: TyCtxt<'tcx>, it: &hir::ForeignItem<'_>, + def_id: DefId, n_tps: usize, abi: Abi, safety: hir::Unsafety, inputs: Vec>, output: Ty<'tcx>, ) { - let def_id = tcx.hir().local_def_id(it.hir_id); - match it.kind { hir::ForeignItemKind::Fn(..) => {} _ => { @@ -67,15 +67,43 @@ fn equate_intrinsic_type<'tcx>( } /// Returns `true` if the given intrinsic is unsafe to call or not. -pub fn intrinsic_operation_unsafety(intrinsic: &str) -> hir::Unsafety { +pub fn intrinsic_operation_unsafety(intrinsic: Symbol) -> hir::Unsafety { match intrinsic { - "abort" | "size_of" | "min_align_of" | "needs_drop" | "caller_location" | "size_of_val" - | "min_align_of_val" | "add_with_overflow" | "sub_with_overflow" | "mul_with_overflow" - | "wrapping_add" | "wrapping_sub" | "wrapping_mul" | "saturating_add" - | "saturating_sub" | "rotate_left" | "rotate_right" | "ctpop" | "ctlz" | "cttz" - | "bswap" | "bitreverse" | "discriminant_value" | "type_id" | "likely" | "unlikely" - | "ptr_guaranteed_eq" | "ptr_guaranteed_ne" | "minnumf32" | "minnumf64" | "maxnumf32" - | "maxnumf64" | "type_name" | "variant_count" => hir::Unsafety::Normal, + sym::abort + | sym::size_of + | sym::min_align_of + | sym::needs_drop + | sym::caller_location + | sym::size_of_val + | sym::min_align_of_val + | sym::add_with_overflow + | sym::sub_with_overflow + | sym::mul_with_overflow + | sym::wrapping_add + | sym::wrapping_sub + | sym::wrapping_mul + | sym::saturating_add + | sym::saturating_sub + | sym::rotate_left + | sym::rotate_right + | sym::ctpop + | sym::ctlz + | sym::cttz + | sym::bswap + | sym::bitreverse + | sym::discriminant_value + | sym::type_id + | sym::likely + | sym::unlikely + | sym::ptr_guaranteed_eq + | sym::ptr_guaranteed_ne + | sym::minnumf32 + | sym::minnumf64 + | sym::maxnumf32 + | sym::rustc_peek + | sym::maxnumf64 + | sym::type_name + | sym::variant_count => hir::Unsafety::Normal, _ => hir::Unsafety::Unsafe, } } @@ -84,7 +112,9 @@ pub fn intrinsic_operation_unsafety(intrinsic: &str) -> hir::Unsafety { /// and in libcore/intrinsics.rs pub fn check_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem<'_>) { let param = |n| tcx.mk_ty_param(n, Symbol::intern(&format!("P{}", n))); - let name = it.ident.as_str(); + let def_id = tcx.hir().local_def_id(it.hir_id).to_def_id(); + let intrinsic_name = tcx.item_name(def_id); + let name_str = intrinsic_name.as_str(); let mk_va_list_ty = |mutbl| { tcx.lang_items().va_list().map(|did| { @@ -98,8 +128,8 @@ pub fn check_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem<'_>) { }) }; - let (n_tps, inputs, output, unsafety) = if name.starts_with("atomic_") { - let split: Vec<&str> = name.split('_').collect(); + let (n_tps, inputs, output, unsafety) = if name_str.starts_with("atomic_") { + let split: Vec<&str> = name_str.split('_').collect(); assert!(split.len() >= 2, "Atomic intrinsic in an incorrect format"); //We only care about the operation here @@ -129,32 +159,30 @@ pub fn check_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem<'_>) { } }; (n_tps, inputs, output, hir::Unsafety::Unsafe) - } else if &name[..] == "abort" { - (0, Vec::new(), tcx.types.never, hir::Unsafety::Normal) - } else if &name[..] == "unreachable" { - (0, Vec::new(), tcx.types.never, hir::Unsafety::Unsafe) } else { - let unsafety = intrinsic_operation_unsafety(&name[..]); - let (n_tps, inputs, output) = match &name[..] { - "breakpoint" => (0, Vec::new(), tcx.mk_unit()), - "size_of" | "pref_align_of" | "min_align_of" | "variant_count" => { + let unsafety = intrinsic_operation_unsafety(intrinsic_name); + let (n_tps, inputs, output) = match intrinsic_name { + sym::abort => (0, Vec::new(), tcx.types.never), + sym::unreachable => (0, Vec::new(), tcx.types.never), + sym::breakpoint => (0, Vec::new(), tcx.mk_unit()), + sym::size_of | sym::pref_align_of | sym::min_align_of | sym::variant_count => { (1, Vec::new(), tcx.types.usize) } - "size_of_val" | "min_align_of_val" => { + sym::size_of_val | sym::min_align_of_val => { (1, vec![tcx.mk_imm_ptr(param(0))], tcx.types.usize) } - "rustc_peek" => (1, vec![param(0)], param(0)), - "caller_location" => (0, vec![], tcx.caller_location_ty()), - "assert_inhabited" | "assert_zero_valid" | "assert_uninit_valid" => { + sym::rustc_peek => (1, vec![param(0)], param(0)), + sym::caller_location => (0, vec![], tcx.caller_location_ty()), + sym::assert_inhabited | sym::assert_zero_valid | sym::assert_uninit_valid => { (1, Vec::new(), tcx.mk_unit()) } - "forget" => (1, vec![param(0)], tcx.mk_unit()), - "transmute" => (2, vec![param(0)], param(1)), - "move_val_init" => (1, vec![tcx.mk_mut_ptr(param(0)), param(0)], tcx.mk_unit()), - "prefetch_read_data" - | "prefetch_write_data" - | "prefetch_read_instruction" - | "prefetch_write_instruction" => ( + sym::forget => (1, vec![param(0)], tcx.mk_unit()), + sym::transmute => (2, vec![param(0)], param(1)), + sym::move_val_init => (1, vec![tcx.mk_mut_ptr(param(0)), param(0)], tcx.mk_unit()), + sym::prefetch_read_data + | sym::prefetch_write_data + | sym::prefetch_read_instruction + | sym::prefetch_write_instruction => ( 1, vec![ tcx.mk_ptr(ty::TypeAndMut { ty: param(0), mutbl: hir::Mutability::Not }), @@ -162,12 +190,12 @@ pub fn check_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem<'_>) { ], tcx.mk_unit(), ), - "drop_in_place" => (1, vec![tcx.mk_mut_ptr(param(0))], tcx.mk_unit()), - "needs_drop" => (1, Vec::new(), tcx.types.bool), + sym::drop_in_place => (1, vec![tcx.mk_mut_ptr(param(0))], tcx.mk_unit()), + sym::needs_drop => (1, Vec::new(), tcx.types.bool), - "type_name" => (1, Vec::new(), tcx.mk_static_str()), - "type_id" => (1, Vec::new(), tcx.types.u64), - "offset" | "arith_offset" => ( + sym::type_name => (1, Vec::new(), tcx.mk_static_str()), + sym::type_id => (1, Vec::new(), tcx.types.u64), + sym::offset | sym::arith_offset => ( 1, vec![ tcx.mk_ptr(ty::TypeAndMut { ty: param(0), mutbl: hir::Mutability::Not }), @@ -175,7 +203,7 @@ pub fn check_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem<'_>) { ], tcx.mk_ptr(ty::TypeAndMut { ty: param(0), mutbl: hir::Mutability::Not }), ), - "copy" | "copy_nonoverlapping" => ( + sym::copy | sym::copy_nonoverlapping => ( 1, vec![ tcx.mk_ptr(ty::TypeAndMut { ty: param(0), mutbl: hir::Mutability::Not }), @@ -184,7 +212,7 @@ pub fn check_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem<'_>) { ], tcx.mk_unit(), ), - "volatile_copy_memory" | "volatile_copy_nonoverlapping_memory" => ( + sym::volatile_copy_memory | sym::volatile_copy_nonoverlapping_memory => ( 1, vec![ tcx.mk_ptr(ty::TypeAndMut { ty: param(0), mutbl: hir::Mutability::Mut }), @@ -193,7 +221,7 @@ pub fn check_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem<'_>) { ], tcx.mk_unit(), ), - "write_bytes" | "volatile_set_memory" => ( + sym::write_bytes | sym::volatile_set_memory => ( 1, vec![ tcx.mk_ptr(ty::TypeAndMut { ty: param(0), mutbl: hir::Mutability::Mut }), @@ -202,93 +230,98 @@ pub fn check_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem<'_>) { ], tcx.mk_unit(), ), - "sqrtf32" => (0, vec![tcx.types.f32], tcx.types.f32), - "sqrtf64" => (0, vec![tcx.types.f64], tcx.types.f64), - "powif32" => (0, vec![tcx.types.f32, tcx.types.i32], tcx.types.f32), - "powif64" => (0, vec![tcx.types.f64, tcx.types.i32], tcx.types.f64), - "sinf32" => (0, vec![tcx.types.f32], tcx.types.f32), - "sinf64" => (0, vec![tcx.types.f64], tcx.types.f64), - "cosf32" => (0, vec![tcx.types.f32], tcx.types.f32), - "cosf64" => (0, vec![tcx.types.f64], tcx.types.f64), - "powf32" => (0, vec![tcx.types.f32, tcx.types.f32], tcx.types.f32), - "powf64" => (0, vec![tcx.types.f64, tcx.types.f64], tcx.types.f64), - "expf32" => (0, vec![tcx.types.f32], tcx.types.f32), - "expf64" => (0, vec![tcx.types.f64], tcx.types.f64), - "exp2f32" => (0, vec![tcx.types.f32], tcx.types.f32), - "exp2f64" => (0, vec![tcx.types.f64], tcx.types.f64), - "logf32" => (0, vec![tcx.types.f32], tcx.types.f32), - "logf64" => (0, vec![tcx.types.f64], tcx.types.f64), - "log10f32" => (0, vec![tcx.types.f32], tcx.types.f32), - "log10f64" => (0, vec![tcx.types.f64], tcx.types.f64), - "log2f32" => (0, vec![tcx.types.f32], tcx.types.f32), - "log2f64" => (0, vec![tcx.types.f64], tcx.types.f64), - "fmaf32" => (0, vec![tcx.types.f32, tcx.types.f32, tcx.types.f32], tcx.types.f32), - "fmaf64" => (0, vec![tcx.types.f64, tcx.types.f64, tcx.types.f64], tcx.types.f64), - "fabsf32" => (0, vec![tcx.types.f32], tcx.types.f32), - "fabsf64" => (0, vec![tcx.types.f64], tcx.types.f64), - "minnumf32" => (0, vec![tcx.types.f32, tcx.types.f32], tcx.types.f32), - "minnumf64" => (0, vec![tcx.types.f64, tcx.types.f64], tcx.types.f64), - "maxnumf32" => (0, vec![tcx.types.f32, tcx.types.f32], tcx.types.f32), - "maxnumf64" => (0, vec![tcx.types.f64, tcx.types.f64], tcx.types.f64), - "copysignf32" => (0, vec![tcx.types.f32, tcx.types.f32], tcx.types.f32), - "copysignf64" => (0, vec![tcx.types.f64, tcx.types.f64], tcx.types.f64), - "floorf32" => (0, vec![tcx.types.f32], tcx.types.f32), - "floorf64" => (0, vec![tcx.types.f64], tcx.types.f64), - "ceilf32" => (0, vec![tcx.types.f32], tcx.types.f32), - "ceilf64" => (0, vec![tcx.types.f64], tcx.types.f64), - "truncf32" => (0, vec![tcx.types.f32], tcx.types.f32), - "truncf64" => (0, vec![tcx.types.f64], tcx.types.f64), - "rintf32" => (0, vec![tcx.types.f32], tcx.types.f32), - "rintf64" => (0, vec![tcx.types.f64], tcx.types.f64), - "nearbyintf32" => (0, vec![tcx.types.f32], tcx.types.f32), - "nearbyintf64" => (0, vec![tcx.types.f64], tcx.types.f64), - "roundf32" => (0, vec![tcx.types.f32], tcx.types.f32), - "roundf64" => (0, vec![tcx.types.f64], tcx.types.f64), - - "volatile_load" | "unaligned_volatile_load" => { + sym::sqrtf32 => (0, vec![tcx.types.f32], tcx.types.f32), + sym::sqrtf64 => (0, vec![tcx.types.f64], tcx.types.f64), + sym::powif32 => (0, vec![tcx.types.f32, tcx.types.i32], tcx.types.f32), + sym::powif64 => (0, vec![tcx.types.f64, tcx.types.i32], tcx.types.f64), + sym::sinf32 => (0, vec![tcx.types.f32], tcx.types.f32), + sym::sinf64 => (0, vec![tcx.types.f64], tcx.types.f64), + sym::cosf32 => (0, vec![tcx.types.f32], tcx.types.f32), + sym::cosf64 => (0, vec![tcx.types.f64], tcx.types.f64), + sym::powf32 => (0, vec![tcx.types.f32, tcx.types.f32], tcx.types.f32), + sym::powf64 => (0, vec![tcx.types.f64, tcx.types.f64], tcx.types.f64), + sym::expf32 => (0, vec![tcx.types.f32], tcx.types.f32), + sym::expf64 => (0, vec![tcx.types.f64], tcx.types.f64), + sym::exp2f32 => (0, vec![tcx.types.f32], tcx.types.f32), + sym::exp2f64 => (0, vec![tcx.types.f64], tcx.types.f64), + sym::logf32 => (0, vec![tcx.types.f32], tcx.types.f32), + sym::logf64 => (0, vec![tcx.types.f64], tcx.types.f64), + sym::log10f32 => (0, vec![tcx.types.f32], tcx.types.f32), + sym::log10f64 => (0, vec![tcx.types.f64], tcx.types.f64), + sym::log2f32 => (0, vec![tcx.types.f32], tcx.types.f32), + sym::log2f64 => (0, vec![tcx.types.f64], tcx.types.f64), + sym::fmaf32 => (0, vec![tcx.types.f32, tcx.types.f32, tcx.types.f32], tcx.types.f32), + sym::fmaf64 => (0, vec![tcx.types.f64, tcx.types.f64, tcx.types.f64], tcx.types.f64), + sym::fabsf32 => (0, vec![tcx.types.f32], tcx.types.f32), + sym::fabsf64 => (0, vec![tcx.types.f64], tcx.types.f64), + sym::minnumf32 => (0, vec![tcx.types.f32, tcx.types.f32], tcx.types.f32), + sym::minnumf64 => (0, vec![tcx.types.f64, tcx.types.f64], tcx.types.f64), + sym::maxnumf32 => (0, vec![tcx.types.f32, tcx.types.f32], tcx.types.f32), + sym::maxnumf64 => (0, vec![tcx.types.f64, tcx.types.f64], tcx.types.f64), + sym::copysignf32 => (0, vec![tcx.types.f32, tcx.types.f32], tcx.types.f32), + sym::copysignf64 => (0, vec![tcx.types.f64, tcx.types.f64], tcx.types.f64), + sym::floorf32 => (0, vec![tcx.types.f32], tcx.types.f32), + sym::floorf64 => (0, vec![tcx.types.f64], tcx.types.f64), + sym::ceilf32 => (0, vec![tcx.types.f32], tcx.types.f32), + sym::ceilf64 => (0, vec![tcx.types.f64], tcx.types.f64), + sym::truncf32 => (0, vec![tcx.types.f32], tcx.types.f32), + sym::truncf64 => (0, vec![tcx.types.f64], tcx.types.f64), + sym::rintf32 => (0, vec![tcx.types.f32], tcx.types.f32), + sym::rintf64 => (0, vec![tcx.types.f64], tcx.types.f64), + sym::nearbyintf32 => (0, vec![tcx.types.f32], tcx.types.f32), + sym::nearbyintf64 => (0, vec![tcx.types.f64], tcx.types.f64), + sym::roundf32 => (0, vec![tcx.types.f32], tcx.types.f32), + sym::roundf64 => (0, vec![tcx.types.f64], tcx.types.f64), + + sym::volatile_load | sym::unaligned_volatile_load => { (1, vec![tcx.mk_imm_ptr(param(0))], param(0)) } - "volatile_store" | "unaligned_volatile_store" => { + sym::volatile_store | sym::unaligned_volatile_store => { (1, vec![tcx.mk_mut_ptr(param(0)), param(0)], tcx.mk_unit()) } - "ctpop" | "ctlz" | "ctlz_nonzero" | "cttz" | "cttz_nonzero" | "bswap" - | "bitreverse" => (1, vec![param(0)], param(0)), + sym::ctpop + | sym::ctlz + | sym::ctlz_nonzero + | sym::cttz + | sym::cttz_nonzero + | sym::bswap + | sym::bitreverse => (1, vec![param(0)], param(0)), - "add_with_overflow" | "sub_with_overflow" | "mul_with_overflow" => { + sym::add_with_overflow | sym::sub_with_overflow | sym::mul_with_overflow => { (1, vec![param(0), param(0)], tcx.intern_tup(&[param(0), tcx.types.bool])) } - "ptr_guaranteed_eq" | "ptr_guaranteed_ne" => { + sym::ptr_guaranteed_eq | sym::ptr_guaranteed_ne => { (1, vec![tcx.mk_imm_ptr(param(0)), tcx.mk_imm_ptr(param(0))], tcx.types.bool) } - "ptr_offset_from" => { + sym::ptr_offset_from => { (1, vec![tcx.mk_imm_ptr(param(0)), tcx.mk_imm_ptr(param(0))], tcx.types.isize) } - "unchecked_div" | "unchecked_rem" | "exact_div" => { + sym::unchecked_div | sym::unchecked_rem | sym::exact_div => { (1, vec![param(0), param(0)], param(0)) } - "unchecked_shl" | "unchecked_shr" | "rotate_left" | "rotate_right" => { + sym::unchecked_shl | sym::unchecked_shr | sym::rotate_left | sym::rotate_right => { (1, vec![param(0), param(0)], param(0)) } - "unchecked_add" | "unchecked_sub" | "unchecked_mul" => { + sym::unchecked_add | sym::unchecked_sub | sym::unchecked_mul => { (1, vec![param(0), param(0)], param(0)) } - "wrapping_add" | "wrapping_sub" | "wrapping_mul" => { + sym::wrapping_add | sym::wrapping_sub | sym::wrapping_mul => { (1, vec![param(0), param(0)], param(0)) } - "saturating_add" | "saturating_sub" => (1, vec![param(0), param(0)], param(0)), - "fadd_fast" | "fsub_fast" | "fmul_fast" | "fdiv_fast" | "frem_fast" => { + sym::saturating_add | sym::saturating_sub => (1, vec![param(0), param(0)], param(0)), + sym::fadd_fast | sym::fsub_fast | sym::fmul_fast | sym::fdiv_fast | sym::frem_fast => { (1, vec![param(0), param(0)], param(0)) } - "float_to_int_unchecked" => (2, vec![param(0)], param(1)), + sym::float_to_int_unchecked => (2, vec![param(0)], param(1)), - "assume" => (0, vec![tcx.types.bool], tcx.mk_unit()), - "likely" => (0, vec![tcx.types.bool], tcx.types.bool), - "unlikely" => (0, vec![tcx.types.bool], tcx.types.bool), + sym::assume => (0, vec![tcx.types.bool], tcx.mk_unit()), + sym::likely => (0, vec![tcx.types.bool], tcx.types.bool), + sym::unlikely => (0, vec![tcx.types.bool], tcx.types.bool), - "discriminant_value" => { + sym::discriminant_value => { let assoc_items = tcx.associated_items(tcx.lang_items().discriminant_kind_trait().unwrap()); let discriminant_def_id = assoc_items.in_definition_order().next().unwrap().def_id; @@ -303,7 +336,7 @@ pub fn check_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem<'_>) { ) } - "try" => { + kw::Try => { let mut_u8 = tcx.mk_mut_ptr(tcx.types.u8); let try_fn_ty = ty::Binder::bind(tcx.mk_fn_sig( iter::once(mut_u8), @@ -326,12 +359,12 @@ pub fn check_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem<'_>) { ) } - "va_start" | "va_end" => match mk_va_list_ty(hir::Mutability::Mut) { + sym::va_start | sym::va_end => match mk_va_list_ty(hir::Mutability::Mut) { Some((va_list_ref_ty, _)) => (0, vec![va_list_ref_ty], tcx.mk_unit()), None => bug!("`va_list` language item needed for C-variadic intrinsics"), }, - "va_copy" => match mk_va_list_ty(hir::Mutability::Not) { + sym::va_copy => match mk_va_list_ty(hir::Mutability::Not) { Some((va_list_ref_ty, va_list_ty)) => { let va_list_ptr_ty = tcx.mk_mut_ptr(va_list_ty); (0, vec![va_list_ptr_ty, va_list_ref_ty], tcx.mk_unit()) @@ -339,28 +372,28 @@ pub fn check_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem<'_>) { None => bug!("`va_list` language item needed for C-variadic intrinsics"), }, - "va_arg" => match mk_va_list_ty(hir::Mutability::Mut) { + sym::va_arg => match mk_va_list_ty(hir::Mutability::Mut) { Some((va_list_ref_ty, _)) => (1, vec![va_list_ref_ty], param(0)), None => bug!("`va_list` language item needed for C-variadic intrinsics"), }, - "nontemporal_store" => (1, vec![tcx.mk_mut_ptr(param(0)), param(0)], tcx.mk_unit()), + sym::nontemporal_store => (1, vec![tcx.mk_mut_ptr(param(0)), param(0)], tcx.mk_unit()), - "miri_start_panic" => { + sym::miri_start_panic => { // FIXME - the relevant types aren't lang items, // so it's not trivial to check this return; } - "count_code_region" => (0, vec![tcx.types.u32], tcx.mk_unit()), + sym::count_code_region => (0, vec![tcx.types.u32], tcx.mk_unit()), - ref other => { + other => { struct_span_err!( tcx.sess, it.span, E0093, "unrecognized intrinsic function: `{}`", - *other + other, ) .span_label(it.span, "unrecognized intrinsic") .emit(); @@ -369,7 +402,7 @@ pub fn check_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem<'_>) { }; (n_tps, inputs, output, unsafety) }; - equate_intrinsic_type(tcx, it, n_tps, Abi::RustIntrinsic, unsafety, inputs, output) + equate_intrinsic_type(tcx, it, def_id, n_tps, Abi::RustIntrinsic, unsafety, inputs, output) } /// Type-check `extern "platform-intrinsic" { ... }` functions. @@ -379,6 +412,7 @@ pub fn check_platform_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem<'_>) tcx.mk_ty_param(n, name) }; + let def_id = tcx.hir().local_def_id(it.hir_id).to_def_id(); let name = it.ident.as_str(); let (n_tps, inputs, output) = match &*name { @@ -453,6 +487,7 @@ pub fn check_platform_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem<'_>) equate_intrinsic_type( tcx, it, + def_id, n_tps, Abi::PlatformIntrinsic, hir::Unsafety::Unsafe, diff --git a/src/librustc_typeck/check/method/confirm.rs b/src/librustc_typeck/check/method/confirm.rs index 1c3d23a3a241f..251ef30c15963 100644 --- a/src/librustc_typeck/check/method/confirm.rs +++ b/src/librustc_typeck/check/method/confirm.rs @@ -131,7 +131,7 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { pick: &probe::Pick<'tcx>, ) -> Ty<'tcx> { // Commit the autoderefs by calling `autoderef` again, but this - // time writing the results into the various tables. + // time writing the results into the various typeck_results. let mut autoderef = self.autoderef(self.span, unadjusted_self_ty); let (_, n) = match autoderef.nth(pick.autoderefs) { Some(n) => n, diff --git a/src/librustc_typeck/check/method/mod.rs b/src/librustc_typeck/check/method/mod.rs index 7bdf137f116c8..63afd8e115ca0 100644 --- a/src/librustc_typeck/check/method/mod.rs +++ b/src/librustc_typeck/check/method/mod.rs @@ -195,7 +195,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { for import_id in &pick.import_ids { debug!("used_trait_import: {:?}", import_id); - Lrc::get_mut(&mut self.tables.borrow_mut().used_trait_imports) + Lrc::get_mut(&mut self.typeck_results.borrow_mut().used_trait_imports) .unwrap() .insert(*import_id); } @@ -456,8 +456,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { )?; debug!("resolve_ufcs: pick={:?}", pick); { - let mut tables = self.tables.borrow_mut(); - let used_trait_imports = Lrc::get_mut(&mut tables.used_trait_imports).unwrap(); + let mut typeck_results = self.typeck_results.borrow_mut(); + let used_trait_imports = Lrc::get_mut(&mut typeck_results.used_trait_imports).unwrap(); for import_id in pick.import_ids { debug!("resolve_ufcs: used_trait_import: {:?}", import_id); used_trait_imports.insert(import_id); diff --git a/src/librustc_typeck/check/method/suggest.rs b/src/librustc_typeck/check/method/suggest.rs index b75dac52b93e5..8dc7827d468f4 100644 --- a/src/librustc_typeck/check/method/suggest.rs +++ b/src/librustc_typeck/check/method/suggest.rs @@ -1037,7 +1037,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }; // Obtain the span for `param` and use it for a structured suggestion. let mut suggested = false; - if let (Some(ref param), Some(ref table)) = (param_type, self.in_progress_tables) { + if let (Some(ref param), Some(ref table)) = + (param_type, self.in_progress_typeck_results) + { let table_owner = table.borrow().hir_owner; if let Some(table_owner) = table_owner { let generics = self.tcx.generics_of(table_owner.to_def_id()); diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs index b617937d6bd54..1e32860c667e5 100644 --- a/src/librustc_typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -51,7 +51,7 @@ and `fcx.expr_ty()` / `fcx.node_ty()` to write/obtain the types of nodes within the function. The types of top-level items, which never contain unbound type -variables, are stored directly into the `tcx` tables. +variables, are stored directly into the `tcx` typeck_results. N.B., a type variable is not the same thing as a type parameter. A type variable is rather an "instance" of a type parameter: that is, @@ -182,24 +182,28 @@ pub struct LocalTy<'tcx> { revealed_ty: Ty<'tcx>, } -/// A wrapper for `InferCtxt`'s `in_progress_tables` field. +/// A wrapper for `InferCtxt`'s `in_progress_typeck_results` field. #[derive(Copy, Clone)] struct MaybeInProgressTables<'a, 'tcx> { - maybe_tables: Option<&'a RefCell>>, + maybe_typeck_results: Option<&'a RefCell>>, } impl<'a, 'tcx> MaybeInProgressTables<'a, 'tcx> { - fn borrow(self) -> Ref<'a, ty::TypeckTables<'tcx>> { - match self.maybe_tables { - Some(tables) => tables.borrow(), - None => bug!("MaybeInProgressTables: inh/fcx.tables.borrow() with no tables"), + fn borrow(self) -> Ref<'a, ty::TypeckResults<'tcx>> { + match self.maybe_typeck_results { + Some(typeck_results) => typeck_results.borrow(), + None => bug!( + "MaybeInProgressTables: inh/fcx.typeck_results.borrow() with no typeck_results" + ), } } - fn borrow_mut(self) -> RefMut<'a, ty::TypeckTables<'tcx>> { - match self.maybe_tables { - Some(tables) => tables.borrow_mut(), - None => bug!("MaybeInProgressTables: inh/fcx.tables.borrow_mut() with no tables"), + fn borrow_mut(self) -> RefMut<'a, ty::TypeckResults<'tcx>> { + match self.maybe_typeck_results { + Some(typeck_results) => typeck_results.borrow_mut(), + None => bug!( + "MaybeInProgressTables: inh/fcx.typeck_results.borrow_mut() with no typeck_results" + ), } } } @@ -216,7 +220,7 @@ impl<'a, 'tcx> MaybeInProgressTables<'a, 'tcx> { pub struct Inherited<'a, 'tcx> { infcx: InferCtxt<'a, 'tcx>, - tables: MaybeInProgressTables<'a, 'tcx>, + typeck_results: MaybeInProgressTables<'a, 'tcx>, locals: RefCell>>, @@ -645,7 +649,7 @@ impl Inherited<'_, 'tcx> { let hir_owner = tcx.hir().local_def_id_to_hir_id(def_id).owner; InheritedBuilder { - infcx: tcx.infer_ctxt().with_fresh_in_progress_tables(hir_owner), + infcx: tcx.infer_ctxt().with_fresh_in_progress_typeck_results(hir_owner), def_id, } } @@ -668,7 +672,9 @@ impl Inherited<'a, 'tcx> { let body_id = tcx.hir().maybe_body_owned_by(item_id); Inherited { - tables: MaybeInProgressTables { maybe_tables: infcx.in_progress_tables }, + typeck_results: MaybeInProgressTables { + maybe_typeck_results: infcx.in_progress_typeck_results, + }, infcx, fulfillment_cx: RefCell::new(TraitEngine::new(tcx)), locals: RefCell::new(Default::default()), @@ -744,7 +750,7 @@ fn check_mod_item_types(tcx: TyCtxt<'_>, module_def_id: LocalDefId) { fn typeck_item_bodies(tcx: TyCtxt<'_>, crate_num: CrateNum) { debug_assert!(crate_num == LOCAL_CRATE); tcx.par_body_owners(|body_owner_def_id| { - tcx.ensure().typeck_tables_of(body_owner_def_id); + tcx.ensure().typeck(body_owner_def_id); }); } @@ -764,9 +770,9 @@ pub fn provide(providers: &mut Providers<'_>) { method::provide(providers); *providers = Providers { typeck_item_bodies, - typeck_tables_of, - diagnostic_only_typeck_tables_of, - has_typeck_tables, + typeck, + diagnostic_only_typeck, + has_typeck_results, adt_destructor, used_trait_imports, check_item_well_formed, @@ -781,15 +787,15 @@ fn adt_destructor(tcx: TyCtxt<'_>, def_id: DefId) -> Option { tcx.calculate_dtor(def_id, &mut dropck::check_drop_impl) } -/// If this `DefId` is a "primary tables entry", returns +/// If this `DefId` is a "primary typeck_results entry", returns /// `Some((body_id, header, decl))` with information about /// it's body-id, fn-header and fn-decl (if any). Otherwise, /// returns `None`. /// -/// If this function returns `Some`, then `typeck_tables(def_id)` will -/// succeed; if it returns `None`, then `typeck_tables(def_id)` may or +/// If this function returns `Some`, then `typeck_results(def_id)` will +/// succeed; if it returns `None`, then `typeck_results(def_id)` may or /// may not succeed. In some cases where this function returns `None` -/// (notably closures), `typeck_tables(def_id)` would wind up +/// (notably closures), `typeck_results(def_id)` would wind up /// redirecting to the owning function. fn primary_body_of( tcx: TyCtxt<'_>, @@ -824,12 +830,12 @@ fn primary_body_of( } } -fn has_typeck_tables(tcx: TyCtxt<'_>, def_id: DefId) -> bool { - // Closures' tables come from their outermost function, +fn has_typeck_results(tcx: TyCtxt<'_>, def_id: DefId) -> bool { + // Closures' typeck_results come from their outermost function, // as they are part of the same "inference environment". let outer_def_id = tcx.closure_base_def_id(def_id); if outer_def_id != def_id { - return tcx.has_typeck_tables(outer_def_id); + return tcx.has_typeck_results(outer_def_id); } if let Some(def_id) = def_id.as_local() { @@ -841,7 +847,7 @@ fn has_typeck_tables(tcx: TyCtxt<'_>, def_id: DefId) -> bool { } fn used_trait_imports(tcx: TyCtxt<'_>, def_id: LocalDefId) -> &FxHashSet { - &*tcx.typeck_tables_of(def_id).used_trait_imports + &*tcx.typeck(def_id).used_trait_imports } /// Inspects the substs of opaque types, replacing any inference variables @@ -955,34 +961,31 @@ where val.fold_with(&mut FixupFolder { tcx }) } -fn typeck_tables_of<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> &ty::TypeckTables<'tcx> { +fn typeck<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> &ty::TypeckResults<'tcx> { let fallback = move || tcx.type_of(def_id.to_def_id()); - typeck_tables_of_with_fallback(tcx, def_id, fallback) + typeck_with_fallback(tcx, def_id, fallback) } -/// Used only to get `TypeckTables` for type inference during error recovery. +/// Used only to get `TypeckResults` for type inference during error recovery. /// Currently only used for type inference of `static`s and `const`s to avoid type cycle errors. -fn diagnostic_only_typeck_tables_of<'tcx>( - tcx: TyCtxt<'tcx>, - def_id: LocalDefId, -) -> &ty::TypeckTables<'tcx> { +fn diagnostic_only_typeck<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> &ty::TypeckResults<'tcx> { let fallback = move || { let span = tcx.hir().span(tcx.hir().as_local_hir_id(def_id)); tcx.ty_error_with_message(span, "diagnostic only typeck table used") }; - typeck_tables_of_with_fallback(tcx, def_id, fallback) + typeck_with_fallback(tcx, def_id, fallback) } -fn typeck_tables_of_with_fallback<'tcx>( +fn typeck_with_fallback<'tcx>( tcx: TyCtxt<'tcx>, def_id: LocalDefId, fallback: impl Fn() -> Ty<'tcx> + 'tcx, -) -> &'tcx ty::TypeckTables<'tcx> { - // Closures' tables come from their outermost function, +) -> &'tcx ty::TypeckResults<'tcx> { + // Closures' typeck_results come from their outermost function, // as they are part of the same "inference environment". let outer_def_id = tcx.closure_base_def_id(def_id.to_def_id()).expect_local(); if outer_def_id != def_id { - return tcx.typeck_tables_of(outer_def_id); + return tcx.typeck(outer_def_id); } let id = tcx.hir().as_local_hir_id(def_id); @@ -994,7 +997,7 @@ fn typeck_tables_of_with_fallback<'tcx>( }); let body = tcx.hir().body(body_id); - let tables = Inherited::build(tcx, def_id).enter(|inh| { + let typeck_results = Inherited::build(tcx, def_id).enter(|inh| { let param_env = tcx.param_env(def_id); let fcx = if let (Some(header), Some(decl)) = (fn_header, fn_decl) { let fn_sig = if crate::collect::get_infer_ret_ty(&decl.output).is_some() { @@ -1124,11 +1127,11 @@ fn typeck_tables_of_with_fallback<'tcx>( fcx.resolve_type_vars_in_body(body) }); - // Consistency check our TypeckTables instance can hold all ItemLocalIds + // Consistency check our TypeckResults instance can hold all ItemLocalIds // it will need to hold. - assert_eq!(tables.hir_owner, Some(id.owner)); + assert_eq!(typeck_results.hir_owner, Some(id.owner)); - tables + typeck_results } fn check_abi(tcx: TyCtxt<'_>, span: Span, abi: Abi) { @@ -1201,7 +1204,11 @@ impl<'a, 'tcx> Visitor<'tcx> for GatherLocalsVisitor<'a, 'tcx> { "visit_local: ty.hir_id={:?} o_ty={:?} revealed_ty={:?} c_ty={:?}", ty.hir_id, o_ty, revealed_ty, c_ty ); - self.fcx.tables.borrow_mut().user_provided_types_mut().insert(ty.hir_id, c_ty); + self.fcx + .typeck_results + .borrow_mut() + .user_provided_types_mut() + .insert(ty.hir_id, c_ty); Some(LocalTy { decl_ty: o_ty, revealed_ty }) } @@ -1355,7 +1362,7 @@ fn check_fn<'a, 'tcx>( fcx.write_ty(param.hir_id, param_ty); } - inherited.tables.borrow_mut().liberated_fn_sigs_mut().insert(fn_id, fn_sig); + inherited.typeck_results.borrow_mut().liberated_fn_sigs_mut().insert(fn_id, fn_sig); if let ty::Dynamic(..) = declared_ret_ty.kind { // FIXME: We need to verify that the return type is `Sized` after the return expression has @@ -1744,17 +1751,17 @@ fn opaque_type_cycle_error(tcx: TyCtxt<'tcx>, def_id: LocalDefId, span: Span) { let mut label = false; if let Some((hir_id, visitor)) = get_owner_return_paths(tcx, def_id) { - let tables = tcx.typeck_tables_of(tcx.hir().local_def_id(hir_id)); + let typeck_results = tcx.typeck(tcx.hir().local_def_id(hir_id)); if visitor .returns .iter() - .filter_map(|expr| tables.node_type_opt(expr.hir_id)) + .filter_map(|expr| typeck_results.node_type_opt(expr.hir_id)) .all(|ty| matches!(ty.kind, ty::Never)) { let spans = visitor .returns .iter() - .filter(|expr| tables.node_type_opt(expr.hir_id).is_some()) + .filter(|expr| typeck_results.node_type_opt(expr.hir_id).is_some()) .map(|expr| expr.span) .collect::>(); let span_len = spans.len(); @@ -1777,7 +1784,7 @@ fn opaque_type_cycle_error(tcx: TyCtxt<'tcx>, def_id: LocalDefId, span: Span) { for (sp, ty) in visitor .returns .iter() - .filter_map(|e| tables.node_type_opt(e.hir_id).map(|t| (e.span, t))) + .filter_map(|e| typeck_results.node_type_opt(e.hir_id).map(|t| (e.span, t))) .filter(|(_, ty)| !matches!(ty.kind, ty::Never)) { struct VisitTypes(Vec); @@ -1847,9 +1854,9 @@ fn binding_opaque_type_cycle_error( .. }) => { let hir_id = tcx.hir().as_local_hir_id(def_id); - let tables = - tcx.typeck_tables_of(tcx.hir().local_def_id(tcx.hir().get_parent_item(hir_id))); - if let Some(ty) = tables.node_type_opt(expr.hir_id) { + let typeck_results = + tcx.typeck(tcx.hir().local_def_id(tcx.hir().get_parent_item(hir_id))); + if let Some(ty) = typeck_results.node_type_opt(expr.hir_id) { err.span_label( expr.span, &format!( @@ -1917,11 +1924,11 @@ pub fn check_item_type<'tcx>(tcx: TyCtxt<'tcx>, it: &'tcx hir::Item<'tcx>) { // Consts can play a role in type-checking, so they are included here. hir::ItemKind::Static(..) => { let def_id = tcx.hir().local_def_id(it.hir_id); - tcx.ensure().typeck_tables_of(def_id); + tcx.ensure().typeck(def_id); maybe_check_static_with_link_section(tcx, def_id, it.span); } hir::ItemKind::Const(..) => { - tcx.ensure().typeck_tables_of(tcx.hir().local_def_id(it.hir_id)); + tcx.ensure().typeck(tcx.hir().local_def_id(it.hir_id)); } hir::ItemKind::Enum(ref enum_definition, _) => { check_enum(tcx, it.span, &enum_definition.variants, it.hir_id); @@ -2832,7 +2839,7 @@ pub fn check_enum<'tcx>( for v in vs { if let Some(ref e) = v.disr_expr { - tcx.ensure().typeck_tables_of(tcx.hir().local_def_id(e.hir_id)); + tcx.ensure().typeck(tcx.hir().local_def_id(e.hir_id)); } } @@ -3199,7 +3206,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.resolve_vars_if_possible(&ty), self.tag() ); - self.tables.borrow_mut().node_types_mut().insert(id, ty); + self.typeck_results.borrow_mut().node_types_mut().insert(id, ty); if ty.references_error() { self.has_errors.set(true); @@ -3208,11 +3215,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } pub fn write_field_index(&self, hir_id: hir::HirId, index: usize) { - self.tables.borrow_mut().field_indices_mut().insert(hir_id, index); + self.typeck_results.borrow_mut().field_indices_mut().insert(hir_id, index); } fn write_resolution(&self, hir_id: hir::HirId, r: Result<(DefKind, DefId), ErrorReported>) { - self.tables.borrow_mut().type_dependent_defs_mut().insert(hir_id, r); + self.typeck_results.borrow_mut().type_dependent_defs_mut().insert(hir_id, r); } pub fn write_method_call(&self, hir_id: hir::HirId, method: MethodCallee<'tcx>) { @@ -3266,7 +3273,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if !substs.is_noop() { debug!("write_substs({:?}, {:?}) in fcx {}", node_id, substs, self.tag()); - self.tables.borrow_mut().node_substs_mut().insert(node_id, substs); + self.typeck_results.borrow_mut().node_substs_mut().insert(node_id, substs); } } @@ -3317,7 +3324,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ); if !canonical_user_type_annotation.is_identity() { - self.tables + self.typeck_results .borrow_mut() .user_provided_types_mut() .insert(hir_id, canonical_user_type_annotation); @@ -3340,7 +3347,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }) }); - match self.tables.borrow_mut().adjustments_mut().entry(expr.hir_id) { + match self.typeck_results.borrow_mut().adjustments_mut().entry(expr.hir_id) { Entry::Vacant(entry) => { entry.insert(adj); } @@ -3525,7 +3532,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if Self::can_contain_user_lifetime_bounds(ty) { let c_ty = self.infcx.canonicalize_response(&UserType::Ty(ty)); debug!("to_ty_saving_user_provided_ty: c_ty={:?}", c_ty); - self.tables.borrow_mut().user_provided_types_mut().insert(ast_ty.hir_id, c_ty); + self.typeck_results.borrow_mut().user_provided_types_mut().insert(ast_ty.hir_id, c_ty); } ty @@ -3557,7 +3564,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } pub fn node_ty(&self, id: hir::HirId) -> Ty<'tcx> { - match self.tables.borrow().node_types().get(id) { + match self.typeck_results.borrow().node_types().get(id) { Some(&t) => t, None if self.is_tainted_by_errors() => self.tcx.ty_error(), None => { @@ -4496,7 +4503,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } QPath::TypeRelative(ref qself, ref segment) => (self.to_ty(qself), qself, segment), }; - if let Some(&cached_result) = self.tables.borrow().type_dependent_defs().get(hir_id) { + if let Some(&cached_result) = self.typeck_results.borrow().type_dependent_defs().get(hir_id) + { // Return directly on cache hit. This is useful to avoid doubly reporting // errors with default match binding modes. See #44614. let def = @@ -4670,8 +4678,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let arm_spans: Vec = arms .iter() .filter_map(|arm| { - self.in_progress_tables - .and_then(|tables| tables.borrow().node_type_opt(arm.body.hir_id)) + self.in_progress_typeck_results + .and_then(|typeck_results| { + typeck_results.borrow().node_type_opt(arm.body.hir_id) + }) .and_then(|arm_ty| { if arm_ty.is_never() { None diff --git a/src/librustc_typeck/check/op.rs b/src/librustc_typeck/check/op.rs index a1e060b97ad28..cfe4baf526cee 100644 --- a/src/librustc_typeck/check/op.rs +++ b/src/librustc_typeck/check/op.rs @@ -240,7 +240,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // some cases applied on the RHS, on top of which we need // to autoref, which is not allowed by apply_adjustments. // self.apply_adjustments(rhs_expr, vec![autoref]); - self.tables + self.typeck_results .borrow_mut() .adjustments_mut() .entry(rhs_expr.hir_id) @@ -496,14 +496,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { err.span_label(span, ty.to_string()); if let FnDef(def_id, _) = ty.kind { let source_map = self.tcx.sess.source_map(); - if !self.tcx.has_typeck_tables(def_id) { + if !self.tcx.has_typeck_results(def_id) { return false; } // We're emitting a suggestion, so we can just ignore regions let fn_sig = self.tcx.fn_sig(def_id).skip_binder(); let other_ty = if let FnDef(def_id, _) = other_ty.kind { - if !self.tcx.has_typeck_tables(def_id) { + if !self.tcx.has_typeck_results(def_id) { return false; } // We're emitting a suggestion, so we can just ignore regions diff --git a/src/librustc_typeck/check/pat.rs b/src/librustc_typeck/check/pat.rs index ea47ae68ce7d3..7ce5d074ab1cd 100644 --- a/src/librustc_typeck/check/pat.rs +++ b/src/librustc_typeck/check/pat.rs @@ -363,7 +363,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if !pat_adjustments.is_empty() { debug!("default binding mode is now {:?}", def_bm); - self.inh.tables.borrow_mut().pat_adjustments_mut().insert(pat.hir_id, pat_adjustments); + self.inh + .typeck_results + .borrow_mut() + .pat_adjustments_mut() + .insert(pat.hir_id, pat_adjustments); } (expected, def_bm) @@ -534,7 +538,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { _ => BindingMode::convert(ba), }; // ...and store it in a side table: - self.inh.tables.borrow_mut().pat_binding_modes_mut().insert(pat.hir_id, bm); + self.inh.typeck_results.borrow_mut().pat_binding_modes_mut().insert(pat.hir_id, bm); debug!("check_pat_ident: pat.hir_id={:?} bm={:?}", pat.hir_id, bm); diff --git a/src/librustc_typeck/check/place_op.rs b/src/librustc_typeck/check/place_op.rs index b7c8f310a1414..6eea02308be05 100644 --- a/src/librustc_typeck/check/place_op.rs +++ b/src/librustc_typeck/check/place_op.rs @@ -221,9 +221,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let mut source = self.node_ty(expr.hir_id); // Do not mutate adjustments in place, but rather take them, // and replace them after mutating them, to avoid having the - // tables borrowed during (`deref_mut`) method resolution. + // typeck_results borrowed during (`deref_mut`) method resolution. let previous_adjustments = - self.tables.borrow_mut().adjustments_mut().remove(expr.hir_id); + self.typeck_results.borrow_mut().adjustments_mut().remove(expr.hir_id); if let Some(mut adjustments) = previous_adjustments { for adjustment in &mut adjustments { if let Adjust::Deref(Some(ref mut deref)) = adjustment.kind { @@ -241,14 +241,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } source = adjustment.target; } - self.tables.borrow_mut().adjustments_mut().insert(expr.hir_id, adjustments); + self.typeck_results.borrow_mut().adjustments_mut().insert(expr.hir_id, adjustments); } match expr.kind { hir::ExprKind::Index(ref base_expr, ref index_expr) => { // We need to get the final type in case dereferences were needed for the trait // to apply (#72002). - let index_expr_ty = self.tables.borrow().expr_ty_adjusted(index_expr); + let index_expr_ty = self.typeck_results.borrow().expr_ty_adjusted(index_expr); self.convert_place_op_to_mutable( PlaceOp::Index, expr, @@ -272,14 +272,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { arg_tys: &[Ty<'tcx>], ) { debug!("convert_place_op_to_mutable({:?}, {:?}, {:?}, {:?})", op, expr, base_expr, arg_tys); - if !self.tables.borrow().is_method_call(expr) { + if !self.typeck_results.borrow().is_method_call(expr) { debug!("convert_place_op_to_mutable - builtin, nothing to do"); return; } // Need to deref because overloaded place ops take self by-reference. let base_ty = self - .tables + .typeck_results .borrow() .expr_ty_adjusted(base_expr) .builtin_deref(false) @@ -306,7 +306,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // region and mutability. let base_expr_ty = self.node_ty(base_expr.hir_id); if let Some(adjustments) = - self.tables.borrow_mut().adjustments_mut().get_mut(base_expr.hir_id) + self.typeck_results.borrow_mut().adjustments_mut().get_mut(base_expr.hir_id) { let mut source = base_expr_ty; for adjustment in &mut adjustments[..] { diff --git a/src/librustc_typeck/check/regionck.rs b/src/librustc_typeck/check/regionck.rs index d3bccaaa3e4b9..b7aed5bbd7744 100644 --- a/src/librustc_typeck/check/regionck.rs +++ b/src/librustc_typeck/check/regionck.rs @@ -263,7 +263,7 @@ impl<'a, 'tcx> RegionCtxt<'a, 'tcx> { self.body_owner = self.tcx.hir().body_owner_def_id(body_id); let fn_sig = { - match self.tables.borrow().liberated_fn_sigs().get(id) { + match self.typeck_results.borrow().liberated_fn_sigs().get(id) { Some(f) => *f, None => { bug!("No fn-sig entry for id={:?}", id); @@ -433,7 +433,7 @@ impl<'a, 'tcx> RegionCtxt<'a, 'tcx> { &self.infcx, self.outlives_environment.param_env, self.body_owner, - &self.tables.borrow(), + &self.typeck_results.borrow(), )) } @@ -447,8 +447,8 @@ impl<'a, 'tcx> RegionCtxt<'a, 'tcx> { let mut place = self.with_mc(|mc| mc.cat_expr_unadjusted(expr))?; - let tables = self.tables.borrow(); - let adjustments = tables.expr_adjustments(&expr); + let typeck_results = self.typeck_results.borrow(); + let adjustments = typeck_results.expr_adjustments(&expr); if adjustments.is_empty() { return Ok(place); } @@ -580,7 +580,7 @@ impl<'a, 'tcx> RegionCtxt<'a, 'tcx> { // `ref x` pattern if let PatKind::Binding(..) = kind { if let Some(ty::BindByReference(mutbl)) = - mc.tables.extract_binding_mode(self.tcx.sess, *hir_id, *span) + mc.typeck_results.extract_binding_mode(self.tcx.sess, *hir_id, *span) { self.link_region_from_node_type(*span, *hir_id, mutbl, &sub_cmt); } @@ -773,7 +773,7 @@ impl<'a, 'tcx> RegionCtxt<'a, 'tcx> { debug!("link_upvar_region(borrorw_region={:?}, upvar_id={:?}", borrow_region, upvar_id); // A by-reference upvar can't be borrowed for longer than the // upvar is borrowed from the environment. - match self.tables.borrow().upvar_capture(upvar_id) { + match self.typeck_results.borrow().upvar_capture(upvar_id) { ty::UpvarCapture::ByRef(upvar_borrow) => { self.sub_regions( infer::ReborrowUpvar(span, upvar_id), diff --git a/src/librustc_typeck/check/upvar.rs b/src/librustc_typeck/check/upvar.rs index 0f3133e0695f1..ffaf9ef7c9fc2 100644 --- a/src/librustc_typeck/check/upvar.rs +++ b/src/librustc_typeck/check/upvar.rs @@ -135,13 +135,16 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } }; - self.tables.borrow_mut().upvar_capture_map.insert(upvar_id, capture_kind); + self.typeck_results.borrow_mut().upvar_capture_map.insert(upvar_id, capture_kind); } // Add the vector of upvars to the map keyed with the closure id. // This gives us an easier access to them without having to call // tcx.upvars again.. if !closure_captures.is_empty() { - self.tables.borrow_mut().closure_captures.insert(closure_def_id, closure_captures); + self.typeck_results + .borrow_mut() + .closure_captures + .insert(closure_def_id, closure_captures); } } @@ -159,7 +162,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { &self.infcx, body_owner_def_id, self.param_env, - &self.tables.borrow(), + &self.typeck_results.borrow(), ) .consume_body(body); @@ -172,11 +175,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // If we have an origin, store it. if let Some(origin) = delegate.current_origin { - self.tables.borrow_mut().closure_kind_origins_mut().insert(closure_hir_id, origin); + self.typeck_results + .borrow_mut() + .closure_kind_origins_mut() + .insert(closure_hir_id, origin); } } - self.tables.borrow_mut().upvar_capture_map.extend(delegate.adjust_upvar_captures); + self.typeck_results.borrow_mut().upvar_capture_map.extend(delegate.adjust_upvar_captures); // Now that we've analyzed the closure, we know how each // variable is borrowed, and we know what traits the closure @@ -227,7 +233,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { var_path: ty::UpvarPath { hir_id: var_hir_id }, closure_expr_id: closure_def_id, }; - let capture = self.tables.borrow().upvar_capture(upvar_id); + let capture = self.typeck_results.borrow().upvar_capture(upvar_id); debug!("var_id={:?} upvar_ty={:?} capture={:?}", var_hir_id, upvar_ty, capture); @@ -392,7 +398,7 @@ impl<'a, 'tcx> InferBorrowKind<'a, 'tcx> { .adjust_upvar_captures .get(&upvar_id) .copied() - .unwrap_or_else(|| self.fcx.tables.borrow().upvar_capture(upvar_id)); + .unwrap_or_else(|| self.fcx.typeck_results.borrow().upvar_capture(upvar_id)); debug!( "adjust_upvar_borrow_kind(upvar_id={:?}, upvar_capture={:?}, kind={:?})", upvar_id, upvar_capture, kind diff --git a/src/librustc_typeck/check/writeback.rs b/src/librustc_typeck/check/writeback.rs index 4704d8fc7666f..e6b5eb4c187fa 100644 --- a/src/librustc_typeck/check/writeback.rs +++ b/src/librustc_typeck/check/writeback.rs @@ -23,10 +23,10 @@ use std::mem; // During type inference, partially inferred types are // represented using Type variables (ty::Infer). These don't appear in -// the final TypeckTables since all of the types should have been -// inferred once typeck_tables_of is done. +// the final TypeckResults since all of the types should have been +// inferred once typeck is done. // When type inference is running however, having to update the typeck -// tables every time a new type is inferred would be unreasonably slow, +// typeck_results every time a new type is inferred would be unreasonably slow, // so instead all of the replacement happens at the end in // resolve_type_vars_in_body, which creates a new TypeTables which // doesn't contain any inference types. @@ -34,7 +34,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { pub fn resolve_type_vars_in_body( &self, body: &'tcx hir::Body<'tcx>, - ) -> &'tcx ty::TypeckTables<'tcx> { + ) -> &'tcx ty::TypeckResults<'tcx> { let item_id = self.tcx.hir().body_owner(body.id()); let item_def_id = self.tcx.hir().local_def_id(item_id); @@ -65,36 +65,39 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { wbcx.visit_user_provided_sigs(); wbcx.visit_generator_interior_types(); - let used_trait_imports = mem::take(&mut self.tables.borrow_mut().used_trait_imports); + let used_trait_imports = + mem::take(&mut self.typeck_results.borrow_mut().used_trait_imports); debug!("used_trait_imports({:?}) = {:?}", item_def_id, used_trait_imports); - wbcx.tables.used_trait_imports = used_trait_imports; + wbcx.typeck_results.used_trait_imports = used_trait_imports; - wbcx.tables.closure_captures = - mem::replace(&mut self.tables.borrow_mut().closure_captures, Default::default()); + wbcx.typeck_results.closure_captures = mem::replace( + &mut self.typeck_results.borrow_mut().closure_captures, + Default::default(), + ); if self.is_tainted_by_errors() { // FIXME(eddyb) keep track of `ErrorReported` from where the error was emitted. - wbcx.tables.tainted_by_errors = Some(ErrorReported); + wbcx.typeck_results.tainted_by_errors = Some(ErrorReported); } - debug!("writeback: tables for {:?} are {:#?}", item_def_id, wbcx.tables); + debug!("writeback: typeck_results for {:?} are {:#?}", item_def_id, wbcx.typeck_results); - self.tcx.arena.alloc(wbcx.tables) + self.tcx.arena.alloc(wbcx.typeck_results) } } /////////////////////////////////////////////////////////////////////////// // The Writeback context. This visitor walks the AST, checking the -// fn-specific tables to find references to types or regions. It +// fn-specific typeck_results to find references to types or regions. It // resolves those regions to remove inference variables and writes the -// final result back into the master tables in the tcx. Here and +// final result back into the master typeck_results in the tcx. Here and // there, it applies a few ad-hoc checks that were not convenient to // do elsewhere. struct WritebackCx<'cx, 'tcx> { fcx: &'cx FnCtxt<'cx, 'tcx>, - tables: ty::TypeckTables<'tcx>, + typeck_results: ty::TypeckResults<'tcx>, body: &'tcx hir::Body<'tcx>, @@ -111,7 +114,7 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { WritebackCx { fcx, - tables: ty::TypeckTables::empty(Some(owner)), + typeck_results: ty::TypeckResults::empty(Some(owner)), body, rustc_dump_user_substs, } @@ -121,10 +124,10 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { self.fcx.tcx } - fn write_ty_to_tables(&mut self, hir_id: hir::HirId, ty: Ty<'tcx>) { - debug!("write_ty_to_tables({:?}, {:?})", hir_id, ty); + fn write_ty_to_typeck_results(&mut self, hir_id: hir::HirId, ty: Ty<'tcx>) { + debug!("write_ty_to_typeck_results({:?}, {:?})", hir_id, ty); assert!(!ty.needs_infer() && !ty.has_placeholders() && !ty.has_free_regions()); - self.tables.node_types_mut().insert(hir_id, ty); + self.typeck_results.node_types_mut().insert(hir_id, ty); } // Hacky hack: During type-checking, we treat *all* operators @@ -138,9 +141,9 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { let inner_ty = self.fcx.resolve_vars_if_possible(&inner_ty); if inner_ty.is_scalar() { - let mut tables = self.fcx.tables.borrow_mut(); - tables.type_dependent_defs_mut().remove(e.hir_id); - tables.node_substs_mut().remove(e.hir_id); + let mut typeck_results = self.fcx.typeck_results.borrow_mut(); + typeck_results.type_dependent_defs_mut().remove(e.hir_id); + typeck_results.node_substs_mut().remove(e.hir_id); } } hir::ExprKind::Binary(ref op, ref lhs, ref rhs) @@ -152,14 +155,14 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { let rhs_ty = self.fcx.resolve_vars_if_possible(&rhs_ty); if lhs_ty.is_scalar() && rhs_ty.is_scalar() { - let mut tables = self.fcx.tables.borrow_mut(); - tables.type_dependent_defs_mut().remove(e.hir_id); - tables.node_substs_mut().remove(e.hir_id); + let mut typeck_results = self.fcx.typeck_results.borrow_mut(); + typeck_results.type_dependent_defs_mut().remove(e.hir_id); + typeck_results.node_substs_mut().remove(e.hir_id); match e.kind { hir::ExprKind::Binary(..) => { if !op.node.is_by_value() { - let mut adjustments = tables.adjustments_mut(); + let mut adjustments = typeck_results.adjustments_mut(); if let Some(a) = adjustments.get_mut(lhs.hir_id) { a.pop(); } @@ -169,7 +172,7 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { } } hir::ExprKind::AssignOp(..) => { - if let Some(a) = tables.adjustments_mut().get_mut(lhs.hir_id) { + if let Some(a) = typeck_results.adjustments_mut().get_mut(lhs.hir_id) { a.pop(); } } @@ -187,10 +190,10 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { // usize-ish fn fix_index_builtin_expr(&mut self, e: &hir::Expr<'_>) { if let hir::ExprKind::Index(ref base, ref index) = e.kind { - let mut tables = self.fcx.tables.borrow_mut(); + let mut typeck_results = self.fcx.typeck_results.borrow_mut(); // All valid indexing looks like this; might encounter non-valid indexes at this point. - let base_ty = tables.expr_ty_adjusted_opt(&base).map(|t| &t.kind); + let base_ty = typeck_results.expr_ty_adjusted_opt(&base).map(|t| &t.kind); if base_ty.is_none() { // When encountering `return [0][0]` outside of a `fn` body we can encounter a base // that isn't in the type table. We assume more relevant errors have already been @@ -198,7 +201,7 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { self.tcx().sess.delay_span_bug(e.span, &format!("bad base: `{:?}`", base)); } if let Some(ty::Ref(_, base_ty, _)) = base_ty { - let index_ty = tables.expr_ty_adjusted_opt(&index).unwrap_or_else(|| { + let index_ty = typeck_results.expr_ty_adjusted_opt(&index).unwrap_or_else(|| { // When encountering `return [0][0]` outside of a `fn` body we would attempt // to access an unexistend index. We assume that more relevant errors will // already have been emitted, so we only gate on this with an ICE if no @@ -212,10 +215,10 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { if base_ty.builtin_index().is_some() && index_ty == self.fcx.tcx.types.usize { // Remove the method call record - tables.type_dependent_defs_mut().remove(e.hir_id); - tables.node_substs_mut().remove(e.hir_id); + typeck_results.type_dependent_defs_mut().remove(e.hir_id); + typeck_results.node_substs_mut().remove(e.hir_id); - if let Some(a) = tables.adjustments_mut().get_mut(base.hir_id) { + if let Some(a) = typeck_results.adjustments_mut().get_mut(base.hir_id) { // Discard the need for a mutable borrow // Extra adjustment made when indexing causes a drop @@ -242,7 +245,7 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { // This is the master code which walks the AST. It delegates most of // the heavy lifting to the generic visit and resolve functions // below. In general, a function is made into a `visitor` if it must -// traffic in node-ids or update tables in the type context etc. +// traffic in node-ids or update typeck_results in the type context etc. impl<'cx, 'tcx> Visitor<'tcx> for WritebackCx<'cx, 'tcx> { type Map = intravisit::ErasedMap<'tcx>; @@ -288,9 +291,11 @@ impl<'cx, 'tcx> Visitor<'tcx> for WritebackCx<'cx, 'tcx> { fn visit_pat(&mut self, p: &'tcx hir::Pat<'tcx>) { match p.kind { hir::PatKind::Binding(..) => { - let tables = self.fcx.tables.borrow(); - if let Some(bm) = tables.extract_binding_mode(self.tcx().sess, p.hir_id, p.span) { - self.tables.pat_binding_modes_mut().insert(p.hir_id, bm); + let typeck_results = self.fcx.typeck_results.borrow(); + if let Some(bm) = + typeck_results.extract_binding_mode(self.tcx().sess, p.hir_id, p.span) + { + self.typeck_results.pat_binding_modes_mut().insert(p.hir_id, bm); } } hir::PatKind::Struct(_, fields, _) => { @@ -311,20 +316,20 @@ impl<'cx, 'tcx> Visitor<'tcx> for WritebackCx<'cx, 'tcx> { intravisit::walk_local(self, l); let var_ty = self.fcx.local_ty(l.span, l.hir_id).decl_ty; let var_ty = self.resolve(&var_ty, &l.span); - self.write_ty_to_tables(l.hir_id, var_ty); + self.write_ty_to_typeck_results(l.hir_id, var_ty); } fn visit_ty(&mut self, hir_ty: &'tcx hir::Ty<'tcx>) { intravisit::walk_ty(self, hir_ty); let ty = self.fcx.node_ty(hir_ty.hir_id); let ty = self.resolve(&ty, &hir_ty.span); - self.write_ty_to_tables(hir_ty.hir_id, ty); + self.write_ty_to_typeck_results(hir_ty.hir_id, ty); } } impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { fn visit_upvar_capture_map(&mut self) { - for (upvar_id, upvar_capture) in self.fcx.tables.borrow().upvar_capture_map.iter() { + for (upvar_id, upvar_capture) in self.fcx.typeck_results.borrow().upvar_capture_map.iter() { let new_upvar_capture = match *upvar_capture { ty::UpvarCapture::ByValue => ty::UpvarCapture::ByValue, ty::UpvarCapture::ByRef(ref upvar_borrow) => { @@ -335,38 +340,38 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { } }; debug!("Upvar capture for {:?} resolved to {:?}", upvar_id, new_upvar_capture); - self.tables.upvar_capture_map.insert(*upvar_id, new_upvar_capture); + self.typeck_results.upvar_capture_map.insert(*upvar_id, new_upvar_capture); } } fn visit_closures(&mut self) { - let fcx_tables = self.fcx.tables.borrow(); - assert_eq!(fcx_tables.hir_owner, self.tables.hir_owner); - let common_hir_owner = fcx_tables.hir_owner.unwrap(); + let fcx_typeck_results = self.fcx.typeck_results.borrow(); + assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner); + let common_hir_owner = fcx_typeck_results.hir_owner.unwrap(); - for (&id, &origin) in fcx_tables.closure_kind_origins().iter() { + for (&id, &origin) in fcx_typeck_results.closure_kind_origins().iter() { let hir_id = hir::HirId { owner: common_hir_owner, local_id: id }; - self.tables.closure_kind_origins_mut().insert(hir_id, origin); + self.typeck_results.closure_kind_origins_mut().insert(hir_id, origin); } } fn visit_coercion_casts(&mut self) { - let fcx_tables = self.fcx.tables.borrow(); - let fcx_coercion_casts = fcx_tables.coercion_casts(); - assert_eq!(fcx_tables.hir_owner, self.tables.hir_owner); + let fcx_typeck_results = self.fcx.typeck_results.borrow(); + let fcx_coercion_casts = fcx_typeck_results.coercion_casts(); + assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner); for local_id in fcx_coercion_casts { - self.tables.set_coercion_cast(*local_id); + self.typeck_results.set_coercion_cast(*local_id); } } fn visit_user_provided_tys(&mut self) { - let fcx_tables = self.fcx.tables.borrow(); - assert_eq!(fcx_tables.hir_owner, self.tables.hir_owner); - let common_hir_owner = fcx_tables.hir_owner.unwrap(); + let fcx_typeck_results = self.fcx.typeck_results.borrow(); + assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner); + let common_hir_owner = fcx_typeck_results.hir_owner.unwrap(); let mut errors_buffer = Vec::new(); - for (&local_id, c_ty) in fcx_tables.user_provided_types().iter() { + for (&local_id, c_ty) in fcx_typeck_results.user_provided_types().iter() { let hir_id = hir::HirId { owner: common_hir_owner, local_id }; if cfg!(debug_assertions) && c_ty.needs_infer() { @@ -377,7 +382,7 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { ); }; - self.tables.user_provided_types_mut().insert(hir_id, *c_ty); + self.typeck_results.user_provided_types_mut().insert(hir_id, *c_ty); if let ty::UserType::TypeOf(_, user_substs) = c_ty.value { if self.rustc_dump_user_substs { @@ -403,10 +408,10 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { } fn visit_user_provided_sigs(&mut self) { - let fcx_tables = self.fcx.tables.borrow(); - assert_eq!(fcx_tables.hir_owner, self.tables.hir_owner); + let fcx_typeck_results = self.fcx.typeck_results.borrow(); + assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner); - for (&def_id, c_sig) in fcx_tables.user_provided_sigs.iter() { + for (&def_id, c_sig) in fcx_typeck_results.user_provided_sigs.iter() { if cfg!(debug_assertions) && c_sig.needs_infer() { span_bug!( self.fcx.tcx.hir().span_if_local(def_id).unwrap(), @@ -415,14 +420,15 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { ); }; - self.tables.user_provided_sigs.insert(def_id, *c_sig); + self.typeck_results.user_provided_sigs.insert(def_id, *c_sig); } } fn visit_generator_interior_types(&mut self) { - let fcx_tables = self.fcx.tables.borrow(); - assert_eq!(fcx_tables.hir_owner, self.tables.hir_owner); - self.tables.generator_interior_types = fcx_tables.generator_interior_types.clone(); + let fcx_typeck_results = self.fcx.typeck_results.borrow(); + assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner); + self.typeck_results.generator_interior_types = + fcx_typeck_results.generator_interior_types.clone(); } fn visit_opaque_types(&mut self, span: Span) { @@ -477,7 +483,7 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { substs: opaque_defn.substs, }; - let old = self.tables.concrete_opaque_types.insert(def_id, new); + let old = self.typeck_results.concrete_opaque_types.insert(def_id, new); if let Some(old) = old { if old.concrete_type != definition_ty || old.substs != opaque_defn.substs { span_bug!( @@ -499,15 +505,18 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { } fn visit_field_id(&mut self, hir_id: hir::HirId) { - if let Some(index) = self.fcx.tables.borrow_mut().field_indices_mut().remove(hir_id) { - self.tables.field_indices_mut().insert(hir_id, index); + if let Some(index) = self.fcx.typeck_results.borrow_mut().field_indices_mut().remove(hir_id) + { + self.typeck_results.field_indices_mut().insert(hir_id, index); } } fn visit_node_id(&mut self, span: Span, hir_id: hir::HirId) { // Export associated path extensions and method resolutions. - if let Some(def) = self.fcx.tables.borrow_mut().type_dependent_defs_mut().remove(hir_id) { - self.tables.type_dependent_defs_mut().insert(hir_id, def); + if let Some(def) = + self.fcx.typeck_results.borrow_mut().type_dependent_defs_mut().remove(hir_id) + { + self.typeck_results.type_dependent_defs_mut().insert(hir_id, def); } // Resolve any borrowings for the node with id `node_id` @@ -516,20 +525,20 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { // Resolve the type of the node with id `node_id` let n_ty = self.fcx.node_ty(hir_id); let n_ty = self.resolve(&n_ty, &span); - self.write_ty_to_tables(hir_id, n_ty); + self.write_ty_to_typeck_results(hir_id, n_ty); debug!("node {:?} has type {:?}", hir_id, n_ty); // Resolve any substitutions - if let Some(substs) = self.fcx.tables.borrow().node_substs_opt(hir_id) { + if let Some(substs) = self.fcx.typeck_results.borrow().node_substs_opt(hir_id) { let substs = self.resolve(&substs, &span); debug!("write_substs_to_tcx({:?}, {:?})", hir_id, substs); assert!(!substs.needs_infer() && !substs.has_placeholders()); - self.tables.node_substs_mut().insert(hir_id, substs); + self.typeck_results.node_substs_mut().insert(hir_id, substs); } } fn visit_adjustments(&mut self, span: Span, hir_id: hir::HirId) { - let adjustment = self.fcx.tables.borrow_mut().adjustments_mut().remove(hir_id); + let adjustment = self.fcx.typeck_results.borrow_mut().adjustments_mut().remove(hir_id); match adjustment { None => { debug!("no adjustments for node {:?}", hir_id); @@ -538,13 +547,13 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { Some(adjustment) => { let resolved_adjustment = self.resolve(&adjustment, &span); debug!("adjustments for node {:?}: {:?}", hir_id, resolved_adjustment); - self.tables.adjustments_mut().insert(hir_id, resolved_adjustment); + self.typeck_results.adjustments_mut().insert(hir_id, resolved_adjustment); } } } fn visit_pat_adjustments(&mut self, span: Span, hir_id: hir::HirId) { - let adjustment = self.fcx.tables.borrow_mut().pat_adjustments_mut().remove(hir_id); + let adjustment = self.fcx.typeck_results.borrow_mut().pat_adjustments_mut().remove(hir_id); match adjustment { None => { debug!("no pat_adjustments for node {:?}", hir_id); @@ -553,32 +562,32 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { Some(adjustment) => { let resolved_adjustment = self.resolve(&adjustment, &span); debug!("pat_adjustments for node {:?}: {:?}", hir_id, resolved_adjustment); - self.tables.pat_adjustments_mut().insert(hir_id, resolved_adjustment); + self.typeck_results.pat_adjustments_mut().insert(hir_id, resolved_adjustment); } } } fn visit_liberated_fn_sigs(&mut self) { - let fcx_tables = self.fcx.tables.borrow(); - assert_eq!(fcx_tables.hir_owner, self.tables.hir_owner); - let common_hir_owner = fcx_tables.hir_owner.unwrap(); + let fcx_typeck_results = self.fcx.typeck_results.borrow(); + assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner); + let common_hir_owner = fcx_typeck_results.hir_owner.unwrap(); - for (&local_id, fn_sig) in fcx_tables.liberated_fn_sigs().iter() { + for (&local_id, fn_sig) in fcx_typeck_results.liberated_fn_sigs().iter() { let hir_id = hir::HirId { owner: common_hir_owner, local_id }; let fn_sig = self.resolve(fn_sig, &hir_id); - self.tables.liberated_fn_sigs_mut().insert(hir_id, fn_sig); + self.typeck_results.liberated_fn_sigs_mut().insert(hir_id, fn_sig); } } fn visit_fru_field_types(&mut self) { - let fcx_tables = self.fcx.tables.borrow(); - assert_eq!(fcx_tables.hir_owner, self.tables.hir_owner); - let common_hir_owner = fcx_tables.hir_owner.unwrap(); + let fcx_typeck_results = self.fcx.typeck_results.borrow(); + assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner); + let common_hir_owner = fcx_typeck_results.hir_owner.unwrap(); - for (&local_id, ftys) in fcx_tables.fru_field_types().iter() { + for (&local_id, ftys) in fcx_typeck_results.fru_field_types().iter() { let hir_id = hir::HirId { owner: common_hir_owner, local_id }; let ftys = self.resolve(ftys, &hir_id); - self.tables.fru_field_types_mut().insert(hir_id, ftys); + self.typeck_results.fru_field_types_mut().insert(hir_id, ftys); } } @@ -593,11 +602,11 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { } // We may have introduced e.g. `ty::Error`, if inference failed, make sure - // to mark the `TypeckTables` as tainted in that case, so that downstream - // users of the tables don't produce extra errors, or worse, ICEs. + // to mark the `TypeckResults` as tainted in that case, so that downstream + // users of the typeck_results don't produce extra errors, or worse, ICEs. if resolver.replaced_with_error { // FIXME(eddyb) keep track of `ErrorReported` from where the error was emitted. - self.tables.tainted_by_errors = Some(ErrorReported); + self.typeck_results.tainted_by_errors = Some(ErrorReported); } x diff --git a/src/librustc_typeck/collect.rs b/src/librustc_typeck/collect.rs index 8920203e6af40..40cff184fceab 100644 --- a/src/librustc_typeck/collect.rs +++ b/src/librustc_typeck/collect.rs @@ -1459,7 +1459,7 @@ fn fn_sig(tcx: TyCtxt<'_>, def_id: DefId) -> ty::PolyFnSig<'_> { | Item(hir::Item { kind: ItemKind::Fn(sig, generics, _), ident, .. }) => { match get_infer_ret_ty(&sig.decl.output) { Some(ty) => { - let fn_sig = tcx.typeck_tables_of(def_id).liberated_fn_sigs()[hir_id]; + let fn_sig = tcx.typeck(def_id).liberated_fn_sigs()[hir_id]; let mut visitor = PlaceholderHirTyCollector::default(); visitor.visit_ty(ty); let mut diag = bad_placeholder_type(tcx, visitor.0); @@ -2063,7 +2063,7 @@ fn compute_sig_of_foreign_fn_decl<'tcx>( ident: Ident, ) -> ty::PolyFnSig<'tcx> { let unsafety = if abi == abi::Abi::RustIntrinsic { - intrinsic_operation_unsafety(&tcx.item_name(def_id).as_str()) + intrinsic_operation_unsafety(tcx.item_name(def_id)) } else { hir::Unsafety::Unsafe }; diff --git a/src/librustc_typeck/collect/type_of.rs b/src/librustc_typeck/collect/type_of.rs index 3dd9c9c5c39db..8dcf0db8524d5 100644 --- a/src/librustc_typeck/collect/type_of.rs +++ b/src/librustc_typeck/collect/type_of.rs @@ -116,12 +116,12 @@ pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: DefId) -> Ty<'_> { tcx.sess.delay_span_bug( DUMMY_SP, &format!( - "owner {:?} has no opaque type for {:?} in its tables", + "owner {:?} has no opaque type for {:?} in its typeck_results", owner, def_id, ), ); if let Some(ErrorReported) = - tcx.typeck_tables_of(owner.expect_local()).tainted_by_errors + tcx.typeck(owner.expect_local()).tainted_by_errors { // Some error in the // owner fn prevented us from populating @@ -387,16 +387,16 @@ fn find_opaque_ty_constraints(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Ty<'_> { impl ConstraintLocator<'_> { fn check(&mut self, def_id: LocalDefId) { // Don't try to check items that cannot possibly constrain the type. - if !self.tcx.has_typeck_tables(def_id) { + if !self.tcx.has_typeck_results(def_id) { debug!( - "find_opaque_ty_constraints: no constraint for `{:?}` at `{:?}`: no tables", + "find_opaque_ty_constraints: no constraint for `{:?}` at `{:?}`: no typeck_results", self.def_id, def_id, ); return; } // Calling `mir_borrowck` can lead to cycle errors through // const-checking, avoid calling it if we don't have to. - if !self.tcx.typeck_tables_of(def_id).concrete_opaque_types.contains_key(&self.def_id) { + if !self.tcx.typeck(def_id).concrete_opaque_types.contains_key(&self.def_id) { debug!( "find_opaque_ty_constraints: no constraint for `{:?}` at `{:?}`", self.def_id, def_id, @@ -580,8 +580,8 @@ fn let_position_impl_trait_type(tcx: TyCtxt<'_>, opaque_ty_id: LocalDefId) -> Ty let opaque_ty_def_id = opaque_ty_id.to_def_id(); - let owner_tables = tcx.typeck_tables_of(scope_def_id); - let concrete_ty = owner_tables + let owner_typeck_results = tcx.typeck(scope_def_id); + let concrete_ty = owner_typeck_results .concrete_opaque_types .get(&opaque_ty_def_id) .map(|opaque| opaque.concrete_type) @@ -589,11 +589,11 @@ fn let_position_impl_trait_type(tcx: TyCtxt<'_>, opaque_ty_id: LocalDefId) -> Ty tcx.sess.delay_span_bug( DUMMY_SP, &format!( - "owner {:?} has no opaque type for {:?} in its tables", + "owner {:?} has no opaque type for {:?} in its typeck_results", scope_def_id, opaque_ty_id ), ); - if let Some(ErrorReported) = owner_tables.tainted_by_errors { + if let Some(ErrorReported) = owner_typeck_results.tainted_by_errors { // Some error in the owner fn prevented us from populating the // `concrete_opaque_types` table. tcx.ty_error() @@ -625,7 +625,7 @@ fn infer_placeholder_type( span: Span, item_ident: Ident, ) -> Ty<'_> { - let ty = tcx.diagnostic_only_typeck_tables_of(def_id).node_type(body_id.hir_id); + let ty = tcx.diagnostic_only_typeck(def_id).node_type(body_id.hir_id); // If this came from a free `const` or `static mut?` item, // then the user may have written e.g. `const A = 42;`. diff --git a/src/librustc_typeck/expr_use_visitor.rs b/src/librustc_typeck/expr_use_visitor.rs index b72fae96e4ca0..c25d98d21a07b 100644 --- a/src/librustc_typeck/expr_use_visitor.rs +++ b/src/librustc_typeck/expr_use_visitor.rs @@ -80,16 +80,16 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { /// /// - `delegate` -- who receives the callbacks /// - `param_env` --- parameter environment for trait lookups (esp. pertaining to `Copy`) - /// - `tables` --- typeck results for the code being analyzed + /// - `typeck_results` --- typeck results for the code being analyzed pub fn new( delegate: &'a mut (dyn Delegate<'tcx> + 'a), infcx: &'a InferCtxt<'a, 'tcx>, body_owner: LocalDefId, param_env: ty::ParamEnv<'tcx>, - tables: &'a ty::TypeckTables<'tcx>, + typeck_results: &'a ty::TypeckResults<'tcx>, ) -> Self { ExprUseVisitor { - mc: mc::MemCategorizationContext::new(infcx, param_env, body_owner, tables), + mc: mc::MemCategorizationContext::new(infcx, param_env, body_owner, typeck_results), delegate, } } @@ -294,7 +294,7 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { } hir::ExprKind::AssignOp(_, ref lhs, ref rhs) => { - if self.mc.tables.is_method_call(expr) { + if self.mc.typeck_results.is_method_call(expr) { self.consume_expr(lhs); } else { self.mutate_expr(lhs); @@ -388,9 +388,9 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { ty::Adt(adt, substs) if adt.is_struct() => { // Consume those fields of the with expression that are needed. for (f_index, with_field) in adt.non_enum_variant().fields.iter().enumerate() { - let is_mentioned = fields - .iter() - .any(|f| self.tcx().field_index(f.hir_id, self.mc.tables) == f_index); + let is_mentioned = fields.iter().any(|f| { + self.tcx().field_index(f.hir_id, self.mc.typeck_results) == f_index + }); if !is_mentioned { let field_place = self.mc.cat_projection( &*with_expr, @@ -421,7 +421,7 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { // consumed or borrowed as part of the automatic adjustment // process. fn walk_adjustment(&mut self, expr: &hir::Expr<'_>) { - let adjustments = self.mc.tables.expr_adjustments(expr); + let adjustments = self.mc.typeck_results.expr_adjustments(expr); let mut place_with_id = return_if_err!(self.mc.cat_expr_unadjusted(expr)); for adjustment in adjustments { debug!("walk_adjustment expr={:?} adj={:?}", expr, adjustment); @@ -505,7 +505,9 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { return_if_err!(mc.cat_pattern(discr_place.clone(), pat, |place, pat| { if let PatKind::Binding(_, canonical_id, ..) = pat.kind { debug!("walk_pat: binding place={:?} pat={:?}", place, pat,); - if let Some(bm) = mc.tables.extract_binding_mode(tcx.sess, pat.hir_id, pat.span) { + if let Some(bm) = + mc.typeck_results.extract_binding_mode(tcx.sess, pat.hir_id, pat.span) + { debug!("walk_pat: pat.hir_id={:?} bm={:?}", pat.hir_id, bm); // pat_ty: the type of the binding being produced. @@ -546,7 +548,7 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { var_path: ty::UpvarPath { hir_id: var_id }, closure_expr_id: closure_def_id, }; - let upvar_capture = self.mc.tables.upvar_capture(upvar_id); + let upvar_capture = self.mc.typeck_results.upvar_capture(upvar_id); let captured_place = return_if_err!(self.cat_captured_var( closure_expr.hir_id, fn_decl_span, diff --git a/src/librustc_typeck/mem_categorization.rs b/src/librustc_typeck/mem_categorization.rs index d619d37be2d7b..c6dac4ba82405 100644 --- a/src/librustc_typeck/mem_categorization.rs +++ b/src/librustc_typeck/mem_categorization.rs @@ -165,7 +165,7 @@ impl HirNode for hir::Pat<'_> { #[derive(Clone)] crate struct MemCategorizationContext<'a, 'tcx> { - crate tables: &'a ty::TypeckTables<'tcx>, + crate typeck_results: &'a ty::TypeckResults<'tcx>, infcx: &'a InferCtxt<'a, 'tcx>, param_env: ty::ParamEnv<'tcx>, body_owner: LocalDefId, @@ -180,10 +180,10 @@ impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> { infcx: &'a InferCtxt<'a, 'tcx>, param_env: ty::ParamEnv<'tcx>, body_owner: LocalDefId, - tables: &'a ty::TypeckTables<'tcx>, + typeck_results: &'a ty::TypeckResults<'tcx>, ) -> MemCategorizationContext<'a, 'tcx> { MemCategorizationContext { - tables, + typeck_results, infcx, param_env, body_owner, @@ -238,15 +238,15 @@ impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> { } crate fn node_ty(&self, hir_id: hir::HirId) -> McResult> { - self.resolve_type_vars_or_error(hir_id, self.tables.node_type_opt(hir_id)) + self.resolve_type_vars_or_error(hir_id, self.typeck_results.node_type_opt(hir_id)) } fn expr_ty(&self, expr: &hir::Expr<'_>) -> McResult> { - self.resolve_type_vars_or_error(expr.hir_id, self.tables.expr_ty_opt(expr)) + self.resolve_type_vars_or_error(expr.hir_id, self.typeck_results.expr_ty_opt(expr)) } crate fn expr_ty_adjusted(&self, expr: &hir::Expr<'_>) -> McResult> { - self.resolve_type_vars_or_error(expr.hir_id, self.tables.expr_ty_adjusted_opt(expr)) + self.resolve_type_vars_or_error(expr.hir_id, self.typeck_results.expr_ty_adjusted_opt(expr)) } /// Returns the type of value that this pattern matches against. @@ -264,7 +264,7 @@ impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> { // that these are never attached to binding patterns, so // actually this is somewhat "disjoint" from the code below // that aims to account for `ref x`. - if let Some(vec) = self.tables.pat_adjustments().get(pat.hir_id) { + if let Some(vec) = self.typeck_results.pat_adjustments().get(pat.hir_id) { if let Some(first_ty) = vec.first() { debug!("pat_ty(pat={:?}) found adjusted ty `{:?}`", pat, first_ty); return Ok(first_ty); @@ -283,8 +283,11 @@ impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> { // and if so, figures out what the type *being borrowed* is. let ret_ty = match pat.kind { PatKind::Binding(..) => { - let bm = - *self.tables.pat_binding_modes().get(pat.hir_id).expect("missing binding mode"); + let bm = *self + .typeck_results + .pat_binding_modes() + .get(pat.hir_id) + .expect("missing binding mode"); if let ty::BindByReference(_) = bm { // a bind-by-ref means that the base_ty will be the type of the ident itself, @@ -324,7 +327,7 @@ impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> { } } - helper(self, expr, self.tables.expr_adjustments(expr)) + helper(self, expr, self.typeck_results.expr_adjustments(expr)) } crate fn cat_expr_adjusted( @@ -376,7 +379,7 @@ impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> { let expr_ty = self.expr_ty(expr)?; match expr.kind { hir::ExprKind::Unary(hir::UnOp::UnDeref, ref e_base) => { - if self.tables.is_method_call(expr) { + if self.typeck_results.is_method_call(expr) { self.cat_overloaded_place(expr, e_base) } else { let base = self.cat_expr(&e_base)?; @@ -391,7 +394,7 @@ impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> { } hir::ExprKind::Index(ref base, _) => { - if self.tables.is_method_call(expr) { + if self.typeck_results.is_method_call(expr) { // If this is an index implemented by a method call, then it // will include an implicit deref of the result. // The call to index() returns a `&T` value, which @@ -405,7 +408,7 @@ impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> { } hir::ExprKind::Path(ref qpath) => { - let res = self.tables.qpath_res(qpath, expr.hir_id); + let res = self.typeck_results.qpath_res(qpath, expr.hir_id); self.cat_res(expr.hir_id, expr.span, expr_ty, res) } @@ -631,7 +634,9 @@ impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> { // Then we see that to get the same result, we must start with // `deref { deref { place_foo }}` instead of `place_foo` since the pattern is now `Some(x,)` // and not `&&Some(x,)`, even though its assigned type is that of `&&Some(x,)`. - for _ in 0..self.tables.pat_adjustments().get(pat.hir_id).map(|v| v.len()).unwrap_or(0) { + for _ in + 0..self.typeck_results.pat_adjustments().get(pat.hir_id).map(|v| v.len()).unwrap_or(0) + { debug!("cat_pattern: applying adjustment to place_with_id={:?}", place_with_id); place_with_id = self.cat_deref(pat, place_with_id)?; } diff --git a/src/llvm-project b/src/llvm-project index 6c040dd86ed62..0ddefeca92b2e 160000 --- a/src/llvm-project +++ b/src/llvm-project @@ -1 +1 @@ -Subproject commit 6c040dd86ed62d38e585279027486e6efc42fb36 +Subproject commit 0ddefeca92b2e1835c80e9b01d9ecc7efc906b1c diff --git a/src/test/incremental/add_private_fn_at_krate_root_cc/struct_point.rs b/src/test/incremental/add_private_fn_at_krate_root_cc/struct_point.rs index 34f30548c5a81..2af72f0e98764 100644 --- a/src/test/incremental/add_private_fn_at_krate_root_cc/struct_point.rs +++ b/src/test/incremental/add_private_fn_at_krate_root_cc/struct_point.rs @@ -24,7 +24,7 @@ extern crate point; pub mod fn_calls_methods_in_same_impl { use point::Point; - #[rustc_clean(label="typeck_tables_of", cfg="cfail2")] + #[rustc_clean(label="typeck", cfg="cfail2")] pub fn check() { let x = Point { x: 2.0, y: 2.0 }; x.distance_from_origin(); @@ -35,7 +35,7 @@ pub mod fn_calls_methods_in_same_impl { pub mod fn_calls_free_fn { use point::{self, Point}; - #[rustc_clean(label="typeck_tables_of", cfg="cfail2")] + #[rustc_clean(label="typeck", cfg="cfail2")] pub fn check() { let x = Point { x: 2.0, y: 2.0 }; point::distance_squared(&x); @@ -46,7 +46,7 @@ pub mod fn_calls_free_fn { pub mod fn_make_struct { use point::Point; - #[rustc_clean(label="typeck_tables_of", cfg="cfail2")] + #[rustc_clean(label="typeck", cfg="cfail2")] pub fn make_origin() -> Point { Point { x: 2.0, y: 2.0 } } @@ -56,7 +56,7 @@ pub mod fn_make_struct { pub mod fn_read_field { use point::Point; - #[rustc_clean(label="typeck_tables_of", cfg="cfail2")] + #[rustc_clean(label="typeck", cfg="cfail2")] pub fn get_x(p: Point) -> f32 { p.x } @@ -66,7 +66,7 @@ pub mod fn_read_field { pub mod fn_write_field { use point::Point; - #[rustc_clean(label="typeck_tables_of", cfg="cfail2")] + #[rustc_clean(label="typeck", cfg="cfail2")] pub fn inc_x(p: &mut Point) { p.x += 1.0; } diff --git a/src/test/incremental/callee_caller_cross_crate/b.rs b/src/test/incremental/callee_caller_cross_crate/b.rs index b49731b26e78f..0245374007985 100644 --- a/src/test/incremental/callee_caller_cross_crate/b.rs +++ b/src/test/incremental/callee_caller_cross_crate/b.rs @@ -6,12 +6,12 @@ extern crate a; -#[rustc_dirty(label="typeck_tables_of", cfg="rpass2")] +#[rustc_dirty(label="typeck", cfg="rpass2")] pub fn call_function0() { a::function0(77); } -#[rustc_clean(label="typeck_tables_of", cfg="rpass2")] +#[rustc_clean(label="typeck", cfg="rpass2")] pub fn call_function1() { a::function1(77); } diff --git a/src/test/incremental/change_add_field/struct_point.rs b/src/test/incremental/change_add_field/struct_point.rs index 662aa53533134..89699bce209f0 100644 --- a/src/test/incremental/change_add_field/struct_point.rs +++ b/src/test/incremental/change_add_field/struct_point.rs @@ -70,7 +70,7 @@ pub mod point { pub mod fn_with_type_in_sig { use point::Point; - #[rustc_dirty(label="typeck_tables_of", cfg="cfail2")] + #[rustc_dirty(label="typeck", cfg="cfail2")] pub fn boop(p: Option<&Point>) -> f32 { p.map(|p| p.total()).unwrap_or(0.0) } @@ -86,7 +86,7 @@ pub mod fn_with_type_in_sig { pub mod call_fn_with_type_in_sig { use fn_with_type_in_sig; - #[rustc_dirty(label="typeck_tables_of", cfg="cfail2")] + #[rustc_dirty(label="typeck", cfg="cfail2")] pub fn bip() -> f32 { fn_with_type_in_sig::boop(None) } @@ -102,7 +102,7 @@ pub mod call_fn_with_type_in_sig { pub mod fn_with_type_in_body { use point::Point; - #[rustc_dirty(label="typeck_tables_of", cfg="cfail2")] + #[rustc_dirty(label="typeck", cfg="cfail2")] pub fn boop() -> f32 { Point::origin().total() } @@ -115,7 +115,7 @@ pub mod fn_with_type_in_body { pub mod call_fn_with_type_in_body { use fn_with_type_in_body; - #[rustc_clean(label="typeck_tables_of", cfg="cfail2")] + #[rustc_clean(label="typeck", cfg="cfail2")] pub fn bip() -> f32 { fn_with_type_in_body::boop() } @@ -125,7 +125,7 @@ pub mod call_fn_with_type_in_body { pub mod fn_make_struct { use point::Point; - #[rustc_dirty(label="typeck_tables_of", cfg="cfail2")] + #[rustc_dirty(label="typeck", cfg="cfail2")] pub fn make_origin(p: Point) -> Point { Point { ..p } } @@ -135,7 +135,7 @@ pub mod fn_make_struct { pub mod fn_read_field { use point::Point; - #[rustc_dirty(label="typeck_tables_of", cfg="cfail2")] + #[rustc_dirty(label="typeck", cfg="cfail2")] pub fn get_x(p: Point) -> f32 { p.x } @@ -145,7 +145,7 @@ pub mod fn_read_field { pub mod fn_write_field { use point::Point; - #[rustc_dirty(label="typeck_tables_of", cfg="cfail2")] + #[rustc_dirty(label="typeck", cfg="cfail2")] pub fn inc_x(p: &mut Point) { p.x += 1.0; } diff --git a/src/test/incremental/change_crate_order/main.rs b/src/test/incremental/change_crate_order/main.rs index c167cf6e035d6..7448b54dd079c 100644 --- a/src/test/incremental/change_crate_order/main.rs +++ b/src/test/incremental/change_crate_order/main.rs @@ -18,7 +18,7 @@ extern crate a; use a::A; use b::B; -//? #[rustc_clean(label="typeck_tables_of", cfg="rpass2")] +//? #[rustc_clean(label="typeck", cfg="rpass2")] pub fn main() { A + B; } diff --git a/src/test/incremental/change_private_fn/struct_point.rs b/src/test/incremental/change_private_fn/struct_point.rs index 722e62ef11ded..ba4bf4e7b7d20 100644 --- a/src/test/incremental/change_private_fn/struct_point.rs +++ b/src/test/incremental/change_private_fn/struct_point.rs @@ -51,7 +51,7 @@ pub mod point { pub mod fn_calls_methods_in_same_impl { use point::Point; - #[rustc_clean(label="typeck_tables_of", cfg="cfail2")] + #[rustc_clean(label="typeck", cfg="cfail2")] pub fn check() { let x = Point { x: 2.0, y: 2.0 }; x.distance_from_origin(); @@ -62,7 +62,7 @@ pub mod fn_calls_methods_in_same_impl { pub mod fn_calls_methods_in_another_impl { use point::Point; - #[rustc_clean(label="typeck_tables_of", cfg="cfail2")] + #[rustc_clean(label="typeck", cfg="cfail2")] pub fn check() { let mut x = Point { x: 2.0, y: 2.0 }; x.translate(3.0, 3.0); @@ -73,7 +73,7 @@ pub mod fn_calls_methods_in_another_impl { pub mod fn_make_struct { use point::Point; - #[rustc_clean(label="typeck_tables_of", cfg="cfail2")] + #[rustc_clean(label="typeck", cfg="cfail2")] pub fn make_origin() -> Point { Point { x: 2.0, y: 2.0 } } @@ -83,7 +83,7 @@ pub mod fn_make_struct { pub mod fn_read_field { use point::Point; - #[rustc_clean(label="typeck_tables_of", cfg="cfail2")] + #[rustc_clean(label="typeck", cfg="cfail2")] pub fn get_x(p: Point) -> f32 { p.x } @@ -93,7 +93,7 @@ pub mod fn_read_field { pub mod fn_write_field { use point::Point; - #[rustc_clean(label="typeck_tables_of", cfg="cfail2")] + #[rustc_clean(label="typeck", cfg="cfail2")] pub fn inc_x(p: &mut Point) { p.x += 1.0; } diff --git a/src/test/incremental/change_private_fn_cc/struct_point.rs b/src/test/incremental/change_private_fn_cc/struct_point.rs index 384441d6d0c71..5072ef609e2cc 100644 --- a/src/test/incremental/change_private_fn_cc/struct_point.rs +++ b/src/test/incremental/change_private_fn_cc/struct_point.rs @@ -23,7 +23,7 @@ extern crate point; pub mod fn_calls_methods_in_same_impl { use point::Point; - #[rustc_clean(label="typeck_tables_of", cfg="cfail2")] + #[rustc_clean(label="typeck", cfg="cfail2")] pub fn check() { let x = Point { x: 2.0, y: 2.0 }; x.distance_from_origin(); @@ -34,7 +34,7 @@ pub mod fn_calls_methods_in_same_impl { pub mod fn_calls_methods_in_another_impl { use point::Point; - #[rustc_clean(label="typeck_tables_of", cfg="cfail2")] + #[rustc_clean(label="typeck", cfg="cfail2")] pub fn check() { let mut x = Point { x: 2.0, y: 2.0 }; x.translate(3.0, 3.0); @@ -45,7 +45,7 @@ pub mod fn_calls_methods_in_another_impl { pub mod fn_make_struct { use point::Point; - #[rustc_clean(label="typeck_tables_of", cfg="cfail2")] + #[rustc_clean(label="typeck", cfg="cfail2")] pub fn make_origin() -> Point { Point { x: 2.0, y: 2.0 } } @@ -55,7 +55,7 @@ pub mod fn_make_struct { pub mod fn_read_field { use point::Point; - #[rustc_clean(label="typeck_tables_of", cfg="cfail2")] + #[rustc_clean(label="typeck", cfg="cfail2")] pub fn get_x(p: Point) -> f32 { p.x } @@ -65,7 +65,7 @@ pub mod fn_read_field { pub mod fn_write_field { use point::Point; - #[rustc_clean(label="typeck_tables_of", cfg="cfail2")] + #[rustc_clean(label="typeck", cfg="cfail2")] pub fn inc_x(p: &mut Point) { p.x += 1.0; } diff --git a/src/test/incremental/change_private_impl_method/struct_point.rs b/src/test/incremental/change_private_impl_method/struct_point.rs index ec5899f3119d8..5c024ed91a3bf 100644 --- a/src/test/incremental/change_private_impl_method/struct_point.rs +++ b/src/test/incremental/change_private_impl_method/struct_point.rs @@ -51,7 +51,7 @@ pub mod point { pub mod fn_calls_methods_in_same_impl { use point::Point; - #[rustc_clean(label="typeck_tables_of", cfg="cfail2")] + #[rustc_clean(label="typeck", cfg="cfail2")] pub fn check() { let x = Point { x: 2.0, y: 2.0 }; x.distance_from_origin(); @@ -62,7 +62,7 @@ pub mod fn_calls_methods_in_same_impl { pub mod fn_calls_methods_in_another_impl { use point::Point; - #[rustc_clean(label="typeck_tables_of", cfg="cfail2")] + #[rustc_clean(label="typeck", cfg="cfail2")] pub fn check() { let mut x = Point { x: 2.0, y: 2.0 }; x.translate(3.0, 3.0); @@ -73,7 +73,7 @@ pub mod fn_calls_methods_in_another_impl { pub mod fn_make_struct { use point::Point; - #[rustc_clean(label="typeck_tables_of", cfg="cfail2")] + #[rustc_clean(label="typeck", cfg="cfail2")] pub fn make_origin() -> Point { Point { x: 2.0, y: 2.0 } } @@ -83,7 +83,7 @@ pub mod fn_make_struct { pub mod fn_read_field { use point::Point; - #[rustc_clean(label="typeck_tables_of", cfg="cfail2")] + #[rustc_clean(label="typeck", cfg="cfail2")] pub fn get_x(p: Point) -> f32 { p.x } @@ -93,7 +93,7 @@ pub mod fn_read_field { pub mod fn_write_field { use point::Point; - #[rustc_clean(label="typeck_tables_of", cfg="cfail2")] + #[rustc_clean(label="typeck", cfg="cfail2")] pub fn inc_x(p: &mut Point) { p.x += 1.0; } diff --git a/src/test/incremental/change_private_impl_method_cc/struct_point.rs b/src/test/incremental/change_private_impl_method_cc/struct_point.rs index f0e78f8d0a483..2aeecfc89d5c0 100644 --- a/src/test/incremental/change_private_impl_method_cc/struct_point.rs +++ b/src/test/incremental/change_private_impl_method_cc/struct_point.rs @@ -24,7 +24,7 @@ extern crate point; pub mod fn_calls_methods_in_same_impl { use point::Point; - #[rustc_clean(label="typeck_tables_of", cfg="cfail2")] + #[rustc_clean(label="typeck", cfg="cfail2")] pub fn check() { let x = Point { x: 2.0, y: 2.0 }; x.distance_from_origin(); @@ -35,7 +35,7 @@ pub mod fn_calls_methods_in_same_impl { pub mod fn_calls_methods_in_another_impl { use point::Point; - #[rustc_clean(label="typeck_tables_of", cfg="cfail2")] + #[rustc_clean(label="typeck", cfg="cfail2")] pub fn dirty() { let mut x = Point { x: 2.0, y: 2.0 }; x.translate(3.0, 3.0); @@ -46,7 +46,7 @@ pub mod fn_calls_methods_in_another_impl { pub mod fn_make_struct { use point::Point; - #[rustc_clean(label="typeck_tables_of", cfg="cfail2")] + #[rustc_clean(label="typeck", cfg="cfail2")] pub fn make_origin() -> Point { Point { x: 2.0, y: 2.0 } } @@ -56,7 +56,7 @@ pub mod fn_make_struct { pub mod fn_read_field { use point::Point; - #[rustc_clean(label="typeck_tables_of", cfg="cfail2")] + #[rustc_clean(label="typeck", cfg="cfail2")] pub fn get_x(p: Point) -> f32 { p.x } @@ -66,7 +66,7 @@ pub mod fn_read_field { pub mod fn_write_field { use point::Point; - #[rustc_clean(label="typeck_tables_of", cfg="cfail2")] + #[rustc_clean(label="typeck", cfg="cfail2")] pub fn inc_x(p: &mut Point) { p.x += 1.0; } diff --git a/src/test/incremental/change_pub_inherent_method_body/struct_point.rs b/src/test/incremental/change_pub_inherent_method_body/struct_point.rs index 641d20ed6cc8a..c944901e34542 100644 --- a/src/test/incremental/change_pub_inherent_method_body/struct_point.rs +++ b/src/test/incremental/change_pub_inherent_method_body/struct_point.rs @@ -42,7 +42,7 @@ pub mod point { pub mod fn_calls_changed_method { use point::Point; - #[rustc_clean(label="typeck_tables_of", cfg="cfail2")] + #[rustc_clean(label="typeck", cfg="cfail2")] pub fn check() { let p = Point { x: 2.0, y: 2.0 }; p.distance_from_origin(); @@ -53,7 +53,7 @@ pub mod fn_calls_changed_method { pub mod fn_calls_another_method { use point::Point; - #[rustc_clean(label="typeck_tables_of", cfg="cfail2")] + #[rustc_clean(label="typeck", cfg="cfail2")] pub fn check() { let p = Point { x: 2.0, y: 2.0 }; p.x(); @@ -64,7 +64,7 @@ pub mod fn_calls_another_method { pub mod fn_make_struct { use point::Point; - #[rustc_clean(label="typeck_tables_of", cfg="cfail2")] + #[rustc_clean(label="typeck", cfg="cfail2")] pub fn make_origin() -> Point { Point { x: 2.0, y: 2.0 } } @@ -74,7 +74,7 @@ pub mod fn_make_struct { pub mod fn_read_field { use point::Point; - #[rustc_clean(label="typeck_tables_of", cfg="cfail2")] + #[rustc_clean(label="typeck", cfg="cfail2")] pub fn get_x(p: Point) -> f32 { p.x } @@ -84,7 +84,7 @@ pub mod fn_read_field { pub mod fn_write_field { use point::Point; - #[rustc_clean(label="typeck_tables_of", cfg="cfail2")] + #[rustc_clean(label="typeck", cfg="cfail2")] pub fn inc_x(p: &mut Point) { p.x += 1.0; } diff --git a/src/test/incremental/change_pub_inherent_method_sig/struct_point.rs b/src/test/incremental/change_pub_inherent_method_sig/struct_point.rs index 9b8f9517bf149..4a5aac682f5aa 100644 --- a/src/test/incremental/change_pub_inherent_method_sig/struct_point.rs +++ b/src/test/incremental/change_pub_inherent_method_sig/struct_point.rs @@ -52,7 +52,7 @@ pub mod point { pub mod fn_calls_changed_method { use point::Point; - #[rustc_dirty(label="typeck_tables_of", cfg="cfail2")] + #[rustc_dirty(label="typeck", cfg="cfail2")] pub fn check() { let p = Point { x: 2.0, y: 2.0 }; p.distance_from_point(None); @@ -63,7 +63,7 @@ pub mod fn_calls_changed_method { pub mod fn_calls_another_method { use point::Point; - #[rustc_clean(label="typeck_tables_of", cfg="cfail2")] + #[rustc_clean(label="typeck", cfg="cfail2")] pub fn check() { let p = Point { x: 2.0, y: 2.0 }; p.x(); @@ -74,7 +74,7 @@ pub mod fn_calls_another_method { pub mod fn_make_struct { use point::Point; - #[rustc_clean(label="typeck_tables_of", cfg="cfail2")] + #[rustc_clean(label="typeck", cfg="cfail2")] pub fn make_origin() -> Point { Point { x: 2.0, y: 2.0 } } @@ -84,7 +84,7 @@ pub mod fn_make_struct { pub mod fn_read_field { use point::Point; - #[rustc_clean(label="typeck_tables_of", cfg="cfail2")] + #[rustc_clean(label="typeck", cfg="cfail2")] pub fn get_x(p: Point) -> f32 { p.x } @@ -94,7 +94,7 @@ pub mod fn_read_field { pub mod fn_write_field { use point::Point; - #[rustc_clean(label="typeck_tables_of", cfg="cfail2")] + #[rustc_clean(label="typeck", cfg="cfail2")] pub fn inc_x(p: &mut Point) { p.x += 1.0; } diff --git a/src/test/incremental/dirty_clean.rs b/src/test/incremental/dirty_clean.rs index b9a1846b37d44..2a1056df4ceca 100644 --- a/src/test/incremental/dirty_clean.rs +++ b/src/test/incremental/dirty_clean.rs @@ -25,16 +25,16 @@ mod x { mod y { use x; - #[rustc_clean(label="typeck_tables_of", cfg="cfail2")] + #[rustc_clean(label="typeck", cfg="cfail2")] pub fn y() { - //[cfail2]~^ ERROR `typeck_tables_of(y::y)` should be clean but is not + //[cfail2]~^ ERROR `typeck(y::y)` should be clean but is not x::x(); } } mod z { - #[rustc_dirty(label="typeck_tables_of", cfg="cfail2")] + #[rustc_dirty(label="typeck", cfg="cfail2")] pub fn z() { - //[cfail2]~^ ERROR `typeck_tables_of(z::z)` should be dirty but is not + //[cfail2]~^ ERROR `typeck(z::z)` should be dirty but is not } } diff --git a/src/test/incremental/hashes/call_expressions.rs b/src/test/incremental/hashes/call_expressions.rs index 3706ab4a02075..aafe0a839e895 100644 --- a/src/test/incremental/hashes/call_expressions.rs +++ b/src/test/incremental/hashes/call_expressions.rs @@ -25,7 +25,7 @@ pub fn change_callee_function() { } #[cfg(not(cfail1))] -#[rustc_clean(cfg="cfail2", except="hir_owner_nodes,mir_built,optimized_mir,typeck_tables_of")] +#[rustc_clean(cfg="cfail2", except="hir_owner_nodes,mir_built,optimized_mir,typeck")] #[rustc_clean(cfg="cfail3")] pub fn change_callee_function() { callee2(1, 2) @@ -81,7 +81,7 @@ pub fn change_callee_method() { } #[cfg(not(cfail1))] -#[rustc_clean(cfg="cfail2", except="hir_owner_nodes,mir_built,optimized_mir,typeck_tables_of")] +#[rustc_clean(cfg="cfail2", except="hir_owner_nodes,mir_built,optimized_mir,typeck")] #[rustc_clean(cfg="cfail3")] pub fn change_callee_method() { let s = Struct; @@ -115,7 +115,7 @@ pub fn change_ufcs_callee_method() { } #[cfg(not(cfail1))] -#[rustc_clean(cfg="cfail2", except="hir_owner_nodes,mir_built,optimized_mir,typeck_tables_of")] +#[rustc_clean(cfg="cfail2", except="hir_owner_nodes,mir_built,optimized_mir,typeck")] #[rustc_clean(cfg="cfail3")] pub fn change_ufcs_callee_method() { let s = Struct; @@ -149,7 +149,7 @@ pub fn change_to_ufcs() { } #[cfg(not(cfail1))] -#[rustc_clean(cfg="cfail2", except="hir_owner_nodes,mir_built,optimized_mir,typeck_tables_of")] +#[rustc_clean(cfg="cfail2", except="hir_owner_nodes,mir_built,optimized_mir,typeck")] #[rustc_clean(cfg="cfail3")] // One might think this would be expanded in the hir_owner_nodes/Mir, but it actually // results in slightly different hir_owner/Mir. @@ -171,7 +171,7 @@ pub mod change_ufcs_callee_indirectly { #[cfg(not(cfail1))] use super::Struct2 as Struct; - #[rustc_clean(cfg="cfail2", except="hir_owner_nodes,mir_built,optimized_mir,typeck_tables_of")] + #[rustc_clean(cfg="cfail2", except="hir_owner_nodes,mir_built,optimized_mir,typeck")] #[rustc_clean(cfg="cfail3")] diff --git a/src/test/incremental/hashes/closure_expressions.rs b/src/test/incremental/hashes/closure_expressions.rs index b1e9ed678c4c5..9d6b95c73b5cc 100644 --- a/src/test/incremental/hashes/closure_expressions.rs +++ b/src/test/incremental/hashes/closure_expressions.rs @@ -37,7 +37,7 @@ pub fn add_parameter() { } #[cfg(not(cfail1))] -#[rustc_clean(cfg="cfail2", except="hir_owner_nodes, mir_built, optimized_mir, typeck_tables_of")] +#[rustc_clean(cfg="cfail2", except="hir_owner_nodes, mir_built, optimized_mir, typeck")] #[rustc_clean(cfg="cfail3")] pub fn add_parameter() { let x = 0u32; @@ -53,7 +53,7 @@ pub fn change_parameter_pattern() { } #[cfg(not(cfail1))] -#[rustc_clean(cfg="cfail2", except="hir_owner_nodes, mir_built, typeck_tables_of")] +#[rustc_clean(cfg="cfail2", except="hir_owner_nodes, mir_built, typeck")] #[rustc_clean(cfg="cfail3")] pub fn change_parameter_pattern() { let _ = |(x,): (u32,)| x; @@ -84,7 +84,7 @@ pub fn add_type_ascription_to_parameter() { } #[cfg(not(cfail1))] -#[rustc_clean(cfg = "cfail2", except = "hir_owner_nodes, typeck_tables_of")] +#[rustc_clean(cfg = "cfail2", except = "hir_owner_nodes, typeck")] #[rustc_clean(cfg = "cfail3")] pub fn add_type_ascription_to_parameter() { let closure = |x: u32| x + 1u32; @@ -101,7 +101,7 @@ pub fn change_parameter_type() { } #[cfg(not(cfail1))] -#[rustc_clean(cfg="cfail2", except="hir_owner_nodes, mir_built, optimized_mir, typeck_tables_of")] +#[rustc_clean(cfg="cfail2", except="hir_owner_nodes, mir_built, optimized_mir, typeck")] #[rustc_clean(cfg="cfail3")] pub fn change_parameter_type() { let closure = |x: u16| (x as u64) + 1; diff --git a/src/test/incremental/hashes/enum_constructors.rs b/src/test/incremental/hashes/enum_constructors.rs index 2c07cbcb2054b..ba641b12a30ff 100644 --- a/src/test/incremental/hashes/enum_constructors.rs +++ b/src/test/incremental/hashes/enum_constructors.rs @@ -57,7 +57,7 @@ pub fn change_field_order_struct_like() -> Enum { } #[cfg(not(cfail1))] -#[rustc_clean(cfg="cfail2", except="hir_owner_nodes,typeck_tables_of")] +#[rustc_clean(cfg="cfail2", except="hir_owner_nodes,typeck")] #[rustc_clean(cfg="cfail3")] // FIXME(michaelwoerister):Interesting. I would have thought that that changes the MIR. And it // would if it were not all constants @@ -96,7 +96,7 @@ pub fn change_constructor_path_struct_like() { } #[cfg(not(cfail1))] -#[rustc_clean(cfg="cfail2", except="hir_owner_nodes,optimized_mir,mir_built,typeck_tables_of")] +#[rustc_clean(cfg="cfail2", except="hir_owner_nodes,optimized_mir,mir_built,typeck")] #[rustc_clean(cfg="cfail3")] pub fn change_constructor_path_struct_like() { let _ = Enum2::Struct { @@ -140,7 +140,7 @@ pub mod change_constructor_path_indirectly_struct_like { #[rustc_clean( cfg="cfail2", except="fn_sig,hir_owner,hir_owner_nodes,optimized_mir,mir_built,\ - typeck_tables_of" + typeck" )] #[rustc_clean(cfg="cfail3")] pub fn function() -> TheEnum { @@ -197,7 +197,7 @@ pub fn change_constructor_path_tuple_like() { #[cfg(not(cfail1))] #[rustc_clean( cfg="cfail2", - except="hir_owner_nodes,optimized_mir,mir_built,typeck_tables_of" + except="hir_owner_nodes,optimized_mir,mir_built,typeck" )] #[rustc_clean(cfg="cfail3")] pub fn change_constructor_path_tuple_like() { @@ -215,7 +215,7 @@ pub fn change_constructor_variant_tuple_like() { #[cfg(not(cfail1))] #[rustc_clean( cfg="cfail2", - except="hir_owner_nodes,optimized_mir,mir_built,typeck_tables_of" + except="hir_owner_nodes,optimized_mir,mir_built,typeck" )] #[rustc_clean(cfg="cfail3")] pub fn change_constructor_variant_tuple_like() { @@ -233,7 +233,7 @@ pub mod change_constructor_path_indirectly_tuple_like { #[rustc_clean( cfg="cfail2", except="fn_sig,hir_owner,hir_owner_nodes,optimized_mir,mir_built,\ - typeck_tables_of" + typeck" )] #[rustc_clean(cfg="cfail3")] pub fn function() -> TheEnum { @@ -251,7 +251,7 @@ pub mod change_constructor_variant_indirectly_tuple_like { #[cfg(not(cfail1))] use super::Enum2::Tuple2 as Variant; - #[rustc_clean(cfg="cfail2", except="hir_owner_nodes,optimized_mir,mir_built,typeck_tables_of")] + #[rustc_clean(cfg="cfail2", except="hir_owner_nodes,optimized_mir,mir_built,typeck")] #[rustc_clean(cfg="cfail3")] pub fn function() -> Enum2 { Variant(0, 1, 2) @@ -278,7 +278,7 @@ pub fn change_constructor_path_c_like() { } #[cfg(not(cfail1))] -#[rustc_clean(cfg="cfail2", except="hir_owner_nodes,optimized_mir,mir_built,typeck_tables_of")] +#[rustc_clean(cfg="cfail2", except="hir_owner_nodes,optimized_mir,mir_built,typeck")] #[rustc_clean(cfg="cfail3")] pub fn change_constructor_path_c_like() { let _x = Clike2::B; @@ -310,7 +310,7 @@ pub mod change_constructor_path_indirectly_c_like { #[rustc_clean( cfg="cfail2", except="fn_sig,hir_owner,hir_owner_nodes,optimized_mir,mir_built,\ - typeck_tables_of" + typeck" )] #[rustc_clean(cfg="cfail3")] pub fn function() -> TheEnum { diff --git a/src/test/incremental/hashes/for_loops.rs b/src/test/incremental/hashes/for_loops.rs index d3d5a69c171f9..4de4c6c1a5dd0 100644 --- a/src/test/incremental/hashes/for_loops.rs +++ b/src/test/incremental/hashes/for_loops.rs @@ -71,7 +71,7 @@ pub fn change_iteration_variable_pattern() { } #[cfg(not(cfail1))] -#[rustc_clean(cfg="cfail2", except="hir_owner_nodes, mir_built, optimized_mir, typeck_tables_of")] +#[rustc_clean(cfg="cfail2", except="hir_owner_nodes, mir_built, optimized_mir, typeck")] #[rustc_clean(cfg="cfail3")] pub fn change_iteration_variable_pattern() { let mut _x = 0; @@ -116,7 +116,7 @@ pub fn add_break() { } #[cfg(not(cfail1))] -#[rustc_clean(cfg="cfail2", except="hir_owner_nodes, mir_built, optimized_mir, typeck_tables_of")] +#[rustc_clean(cfg="cfail2", except="hir_owner_nodes, mir_built, optimized_mir, typeck")] #[rustc_clean(cfg="cfail3")] pub fn add_break() { let mut _x = 0; diff --git a/src/test/incremental/hashes/function_interfaces.rs b/src/test/incremental/hashes/function_interfaces.rs index a6b936fcbcf89..fae2b98196752 100644 --- a/src/test/incremental/hashes/function_interfaces.rs +++ b/src/test/incremental/hashes/function_interfaces.rs @@ -22,7 +22,7 @@ pub fn add_parameter() {} #[cfg(not(cfail1))] #[rustc_clean( cfg = "cfail2", - except = "hir_owner, hir_owner_nodes, mir_built, optimized_mir, typeck_tables_of, fn_sig" + except = "hir_owner, hir_owner_nodes, mir_built, optimized_mir, typeck, fn_sig" )] #[rustc_clean(cfg = "cfail3")] pub fn add_parameter(p: i32) {} @@ -45,7 +45,7 @@ pub fn type_of_parameter(p: i32) {} #[cfg(not(cfail1))] #[rustc_clean( cfg = "cfail2", - except = "hir_owner, hir_owner_nodes, mir_built, optimized_mir, typeck_tables_of, fn_sig" + except = "hir_owner, hir_owner_nodes, mir_built, optimized_mir, typeck, fn_sig" )] #[rustc_clean(cfg = "cfail3")] pub fn type_of_parameter(p: i64) {} @@ -58,7 +58,7 @@ pub fn type_of_parameter_ref(p: &i32) {} #[cfg(not(cfail1))] #[rustc_clean( cfg = "cfail2", - except = "hir_owner, hir_owner_nodes, mir_built, optimized_mir, typeck_tables_of, fn_sig" + except = "hir_owner, hir_owner_nodes, mir_built, optimized_mir, typeck, fn_sig" )] #[rustc_clean(cfg = "cfail3")] pub fn type_of_parameter_ref(p: &mut i32) {} @@ -71,7 +71,7 @@ pub fn order_of_parameters(p1: i32, p2: i64) {} #[cfg(not(cfail1))] #[rustc_clean( cfg = "cfail2", - except = "hir_owner, hir_owner_nodes, mir_built, optimized_mir, typeck_tables_of, fn_sig" + except = "hir_owner, hir_owner_nodes, mir_built, optimized_mir, typeck, fn_sig" )] #[rustc_clean(cfg = "cfail3")] pub fn order_of_parameters(p2: i64, p1: i32) {} @@ -84,7 +84,7 @@ pub fn make_unsafe() {} #[cfg(not(cfail1))] #[rustc_clean( cfg = "cfail2", - except = "hir_owner, hir_owner_nodes, mir_built, optimized_mir, typeck_tables_of, fn_sig" + except = "hir_owner, hir_owner_nodes, mir_built, optimized_mir, typeck, fn_sig" )] #[rustc_clean(cfg = "cfail3")] pub unsafe fn make_unsafe() {} @@ -95,7 +95,7 @@ pub unsafe fn make_unsafe() {} pub fn make_extern() {} #[cfg(not(cfail1))] -#[rustc_clean(cfg = "cfail2", except = "hir_owner, hir_owner_nodes, typeck_tables_of, fn_sig")] +#[rustc_clean(cfg = "cfail2", except = "hir_owner, hir_owner_nodes, typeck, fn_sig")] #[rustc_clean(cfg = "cfail3")] pub extern "C" fn make_extern() {} @@ -241,7 +241,7 @@ pub fn return_impl_trait() -> i32 { } #[cfg(not(cfail1))] -#[rustc_clean(cfg = "cfail2", except = "hir_owner, hir_owner_nodes, typeck_tables_of, fn_sig")] +#[rustc_clean(cfg = "cfail2", except = "hir_owner, hir_owner_nodes, typeck, fn_sig")] #[rustc_clean(cfg = "cfail3")] pub fn return_impl_trait() -> impl Clone { 0 @@ -274,7 +274,7 @@ pub mod change_return_type_indirectly { #[rustc_clean( cfg = "cfail2", - except = "hir_owner, hir_owner_nodes, mir_built, optimized_mir, typeck_tables_of, fn_sig" + except = "hir_owner, hir_owner_nodes, mir_built, optimized_mir, typeck, fn_sig" )] #[rustc_clean(cfg = "cfail3")] pub fn indirect_return_type() -> ReturnType { @@ -292,7 +292,7 @@ pub mod change_parameter_type_indirectly { #[rustc_clean( cfg = "cfail2", - except = "hir_owner, hir_owner_nodes, mir_built, optimized_mir, typeck_tables_of, fn_sig" + except = "hir_owner, hir_owner_nodes, mir_built, optimized_mir, typeck, fn_sig" )] #[rustc_clean(cfg = "cfail3")] pub fn indirect_parameter_type(p: ParameterType) {} diff --git a/src/test/incremental/hashes/if_expressions.rs b/src/test/incremental/hashes/if_expressions.rs index 29b3f1f5b1d83..acf92c299b482 100644 --- a/src/test/incremental/hashes/if_expressions.rs +++ b/src/test/incremental/hashes/if_expressions.rs @@ -25,7 +25,7 @@ pub fn change_condition(x: bool) -> u32 { } #[cfg(not(cfail1))] -#[rustc_clean(cfg="cfail2", except="hir_owner_nodes,mir_built,optimized_mir,typeck_tables_of")] +#[rustc_clean(cfg="cfail2", except="hir_owner_nodes,mir_built,optimized_mir,typeck")] #[rustc_clean(cfg="cfail3")] pub fn change_condition(x: bool) -> u32 { if !x { @@ -120,7 +120,7 @@ pub fn change_condition_if_let(x: Option) -> u32 { } #[cfg(not(cfail1))] -#[rustc_clean(cfg="cfail2", except="hir_owner_nodes,mir_built,optimized_mir,typeck_tables_of")] +#[rustc_clean(cfg="cfail2", except="hir_owner_nodes,mir_built,optimized_mir,typeck")] #[rustc_clean(cfg="cfail3")] pub fn change_condition_if_let(x: Option) -> u32 { if let Some(_) = x { @@ -143,7 +143,7 @@ pub fn change_then_branch_if_let(x: Option) -> u32 { } #[cfg(not(cfail1))] -#[rustc_clean(cfg="cfail2", except="hir_owner_nodes,mir_built,optimized_mir,typeck_tables_of")] +#[rustc_clean(cfg="cfail2", except="hir_owner_nodes,mir_built,optimized_mir,typeck")] #[rustc_clean(cfg="cfail3")] pub fn change_then_branch_if_let(x: Option) -> u32 { if let Some(x) = x { diff --git a/src/test/incremental/hashes/inherent_impls.rs b/src/test/incremental/hashes/inherent_impls.rs index a9c8457f7f260..322886ec1350e 100644 --- a/src/test/incremental/hashes/inherent_impls.rs +++ b/src/test/incremental/hashes/inherent_impls.rs @@ -44,7 +44,7 @@ impl Foo { impl Foo { #[rustc_clean( cfg="cfail2", - except="hir_owner_nodes,optimized_mir,promoted_mir,mir_built,typeck_tables_of" + except="hir_owner_nodes,optimized_mir,promoted_mir,mir_built,typeck" )] #[rustc_clean(cfg="cfail3")] pub fn method_body() { @@ -68,7 +68,7 @@ impl Foo { impl Foo { #[rustc_clean( cfg="cfail2", - except="hir_owner_nodes,optimized_mir,promoted_mir,mir_built,typeck_tables_of" + except="hir_owner_nodes,optimized_mir,promoted_mir,mir_built,typeck" )] #[rustc_clean(cfg="cfail3")] #[inline] @@ -120,7 +120,7 @@ impl Foo { impl Foo { #[rustc_clean( cfg="cfail2", - except="hir_owner,hir_owner_nodes,fn_sig,typeck_tables_of,optimized_mir,mir_built" + except="hir_owner,hir_owner_nodes,fn_sig,typeck,optimized_mir,mir_built" )] #[rustc_clean(cfg="cfail3")] pub fn method_selfmutness(&mut self) { } @@ -160,7 +160,7 @@ impl Foo { impl Foo { #[rustc_clean( cfg="cfail2", - except="hir_owner,hir_owner_nodes,fn_sig,typeck_tables_of,optimized_mir,mir_built" + except="hir_owner,hir_owner_nodes,fn_sig,typeck,optimized_mir,mir_built" )] #[rustc_clean(cfg="cfail3")] pub fn add_method_parameter(&self, _: i32) { } @@ -197,7 +197,7 @@ impl Foo { impl Foo { #[rustc_clean( cfg="cfail2", - except="hir_owner,hir_owner_nodes,fn_sig,optimized_mir,mir_built,typeck_tables_of")] + except="hir_owner,hir_owner_nodes,fn_sig,optimized_mir,mir_built,typeck")] #[rustc_clean(cfg="cfail3")] pub fn change_method_return_type(&self) -> u8 { 0 } } @@ -251,7 +251,7 @@ impl Foo { impl Foo { #[rustc_clean( cfg="cfail2", - except="hir_owner,hir_owner_nodes,fn_sig,typeck_tables_of,optimized_mir,mir_built" + except="hir_owner,hir_owner_nodes,fn_sig,typeck,optimized_mir,mir_built" )] #[rustc_clean(cfg="cfail3")] pub unsafe fn make_method_unsafe(&self) { } @@ -269,7 +269,7 @@ impl Foo { #[rustc_clean(cfg="cfail2")] #[rustc_clean(cfg="cfail3")] impl Foo { - #[rustc_clean(cfg="cfail2", except="hir_owner,hir_owner_nodes,fn_sig,typeck_tables_of")] + #[rustc_clean(cfg="cfail2", except="hir_owner,hir_owner_nodes,fn_sig,typeck")] #[rustc_clean(cfg="cfail3")] pub extern fn make_method_extern(&self) { } } @@ -286,7 +286,7 @@ impl Foo { #[rustc_clean(cfg="cfail2")] #[rustc_clean(cfg="cfail3")] impl Foo { - #[rustc_clean(cfg="cfail2", except="hir_owner,hir_owner_nodes,fn_sig,typeck_tables_of")] + #[rustc_clean(cfg="cfail2", except="hir_owner,hir_owner_nodes,fn_sig,typeck")] #[rustc_clean(cfg="cfail3")] pub extern "system" fn change_method_calling_convention(&self) { } } @@ -303,15 +303,15 @@ impl Foo { #[rustc_clean(cfg="cfail2")] #[rustc_clean(cfg="cfail3")] impl Foo { - // Warning: Note that `typeck_tables_of` are coming up clean here. + // Warning: Note that `typeck` are coming up clean here. // The addition or removal of lifetime parameters that don't // appear in the arguments or fn body in any way does not, in - // fact, affect the `typeck_tables_of` in any semantic way (at least + // fact, affect the `typeck` in any semantic way (at least // as of this writing). **However,** altering the order of - // lowering **can** cause it appear to affect the `typeck_tables_of`: + // lowering **can** cause it appear to affect the `typeck`: // if we lower generics before the body, then the `HirId` for // things in the body will be affected. So if you start to see - // `typeck_tables_of` appear dirty, that might be the cause. -nmatsakis + // `typeck` appear dirty, that might be the cause. -nmatsakis #[rustc_clean(cfg="cfail2", except="hir_owner,hir_owner_nodes")] #[rustc_clean(cfg="cfail3")] pub fn add_lifetime_parameter_to_method<'a>(&self) { } @@ -329,14 +329,14 @@ impl Foo { #[rustc_clean(cfg="cfail2")] #[rustc_clean(cfg="cfail3")] impl Foo { - // Warning: Note that `typeck_tables_of` are coming up clean here. + // Warning: Note that `typeck` are coming up clean here. // The addition or removal of type parameters that don't appear in // the arguments or fn body in any way does not, in fact, affect - // the `typeck_tables_of` in any semantic way (at least as of this + // the `typeck` in any semantic way (at least as of this // writing). **However,** altering the order of lowering **can** - // cause it appear to affect the `typeck_tables_of`: if we lower + // cause it appear to affect the `typeck`: if we lower // generics before the body, then the `HirId` for things in the - // body will be affected. So if you start to see `typeck_tables_of` + // body will be affected. So if you start to see `typeck` // appear dirty, that might be the cause. -nmatsakis #[rustc_clean( cfg="cfail2", @@ -378,14 +378,14 @@ impl Foo { #[rustc_clean(cfg="cfail2")] #[rustc_clean(cfg="cfail3")] impl Foo { - // Warning: Note that `typeck_tables_of` are coming up clean here. + // Warning: Note that `typeck` are coming up clean here. // The addition or removal of bounds that don't appear in the // arguments or fn body in any way does not, in fact, affect the - // `typeck_tables_of` in any semantic way (at least as of this + // `typeck` in any semantic way (at least as of this // writing). **However,** altering the order of lowering **can** - // cause it appear to affect the `typeck_tables_of`: if we lower + // cause it appear to affect the `typeck`: if we lower // generics before the body, then the `HirId` for things in the - // body will be affected. So if you start to see `typeck_tables_of` + // body will be affected. So if you start to see `typeck` // appear dirty, that might be the cause. -nmatsakis #[rustc_clean(cfg="cfail2", except="hir_owner,hir_owner_nodes,generics_of,predicates_of,\ type_of")] @@ -405,14 +405,14 @@ impl Foo { #[rustc_clean(cfg="cfail2")] #[rustc_clean(cfg="cfail3")] impl Foo { - // Warning: Note that `typeck_tables_of` are coming up clean here. + // Warning: Note that `typeck` are coming up clean here. // The addition or removal of bounds that don't appear in the // arguments or fn body in any way does not, in fact, affect the - // `typeck_tables_of` in any semantic way (at least as of this + // `typeck` in any semantic way (at least as of this // writing). **However,** altering the order of lowering **can** - // cause it appear to affect the `typeck_tables_of`: if we lower + // cause it appear to affect the `typeck`: if we lower // generics before the body, then the `HirId` for things in the - // body will be affected. So if you start to see `typeck_tables_of` + // body will be affected. So if you start to see `typeck` // appear dirty, that might be the cause. -nmatsakis #[rustc_clean(cfg="cfail2", except="hir_owner,hir_owner_nodes,predicates_of")] #[rustc_clean(cfg="cfail3")] @@ -453,7 +453,7 @@ impl Bar { impl Bar { #[rustc_clean( cfg="cfail2", - except="generics_of,fn_sig,typeck_tables_of,type_of,optimized_mir,mir_built" + except="generics_of,fn_sig,typeck,type_of,optimized_mir,mir_built" )] #[rustc_clean(cfg="cfail3")] pub fn add_type_parameter_to_impl(&self) { } @@ -471,7 +471,7 @@ impl Bar { #[rustc_clean(cfg="cfail2", except="hir_owner,hir_owner_nodes")] #[rustc_clean(cfg="cfail3")] impl Bar { - #[rustc_clean(cfg="cfail2", except="fn_sig,optimized_mir,mir_built,typeck_tables_of")] + #[rustc_clean(cfg="cfail2", except="fn_sig,optimized_mir,mir_built,typeck")] #[rustc_clean(cfg="cfail3")] pub fn change_impl_self_type(&self) { } } diff --git a/src/test/incremental/hashes/let_expressions.rs b/src/test/incremental/hashes/let_expressions.rs index 846bfc6d0e4db..3641357334bd6 100644 --- a/src/test/incremental/hashes/let_expressions.rs +++ b/src/test/incremental/hashes/let_expressions.rs @@ -38,7 +38,7 @@ pub fn add_type() { #[cfg(not(cfail1))] #[rustc_clean(cfg="cfail2", - except="hir_owner_nodes,typeck_tables_of,mir_built")] + except="hir_owner_nodes,typeck,mir_built")] #[rustc_clean(cfg="cfail3")] pub fn add_type() { let _x: u32 = 2u32; @@ -54,7 +54,7 @@ pub fn change_type() { #[cfg(not(cfail1))] #[rustc_clean(cfg="cfail2", - except="hir_owner_nodes,typeck_tables_of,mir_built,optimized_mir")] + except="hir_owner_nodes,typeck,mir_built,optimized_mir")] #[rustc_clean(cfg="cfail3")] pub fn change_type() { let _x: u8 = 2; @@ -70,7 +70,7 @@ pub fn change_mutability_of_reference_type() { #[cfg(not(cfail1))] #[rustc_clean(cfg="cfail2", - except="hir_owner_nodes,typeck_tables_of,mir_built,optimized_mir")] + except="hir_owner_nodes,typeck,mir_built,optimized_mir")] #[rustc_clean(cfg="cfail3")] pub fn change_mutability_of_reference_type() { let _x: &mut u64; @@ -86,7 +86,7 @@ pub fn change_mutability_of_slot() { #[cfg(not(cfail1))] #[rustc_clean(cfg="cfail2", - except="hir_owner_nodes,typeck_tables_of,mir_built,optimized_mir")] + except="hir_owner_nodes,typeck,mir_built,optimized_mir")] #[rustc_clean(cfg="cfail3")] pub fn change_mutability_of_slot() { let _x: u64 = 0; @@ -102,7 +102,7 @@ pub fn change_simple_binding_to_pattern() { #[cfg(not(cfail1))] #[rustc_clean(cfg="cfail2", - except="hir_owner_nodes,typeck_tables_of,mir_built,optimized_mir")] + except="hir_owner_nodes,typeck,mir_built,optimized_mir")] #[rustc_clean(cfg="cfail3")] pub fn change_simple_binding_to_pattern() { let (_a, _b) = (0u8, 'x'); @@ -134,7 +134,7 @@ pub fn add_ref_in_pattern() { #[cfg(not(cfail1))] #[rustc_clean(cfg="cfail2", - except="hir_owner_nodes,typeck_tables_of,mir_built,optimized_mir")] + except="hir_owner_nodes,typeck,mir_built,optimized_mir")] #[rustc_clean(cfg="cfail3")] pub fn add_ref_in_pattern() { let (ref _a, _b) = (1u8, 'y'); @@ -150,7 +150,7 @@ pub fn add_amp_in_pattern() { #[cfg(not(cfail1))] #[rustc_clean(cfg="cfail2", - except="hir_owner_nodes,typeck_tables_of,mir_built,optimized_mir")] + except="hir_owner_nodes,typeck,mir_built,optimized_mir")] #[rustc_clean(cfg="cfail3")] pub fn add_amp_in_pattern() { let (&_a, _b) = (&1u8, 'y'); @@ -166,7 +166,7 @@ pub fn change_mutability_of_binding_in_pattern() { #[cfg(not(cfail1))] #[rustc_clean(cfg="cfail2", - except="hir_owner_nodes,typeck_tables_of,mir_built,optimized_mir")] + except="hir_owner_nodes,typeck,mir_built,optimized_mir")] #[rustc_clean(cfg="cfail3")] pub fn change_mutability_of_binding_in_pattern() { let (mut _a, _b) = (99u8, 'q'); @@ -182,7 +182,7 @@ pub fn add_initializer() { #[cfg(not(cfail1))] #[rustc_clean(cfg="cfail2", - except="hir_owner_nodes,typeck_tables_of,mir_built,optimized_mir")] + except="hir_owner_nodes,typeck,mir_built,optimized_mir")] #[rustc_clean(cfg="cfail3")] pub fn add_initializer() { let _x: i16 = 3i16; diff --git a/src/test/incremental/hashes/loop_expressions.rs b/src/test/incremental/hashes/loop_expressions.rs index 65db89eb976cf..34d849d678a5e 100644 --- a/src/test/incremental/hashes/loop_expressions.rs +++ b/src/test/incremental/hashes/loop_expressions.rs @@ -47,7 +47,7 @@ pub fn add_break() { } #[cfg(not(cfail1))] -#[rustc_clean(cfg="cfail2", except="hir_owner_nodes, mir_built, optimized_mir, typeck_tables_of")] +#[rustc_clean(cfg="cfail2", except="hir_owner_nodes, mir_built, optimized_mir, typeck")] #[rustc_clean(cfg="cfail3")] pub fn add_break() { let mut _x = 0; @@ -118,7 +118,7 @@ pub fn change_break_label() { } #[cfg(not(cfail1))] -#[rustc_clean(cfg="cfail2", except="hir_owner_nodes, mir_built, optimized_mir, typeck_tables_of")] +#[rustc_clean(cfg="cfail2", except="hir_owner_nodes, mir_built, optimized_mir, typeck")] #[rustc_clean(cfg="cfail3")] pub fn change_break_label() { let mut _x = 0; @@ -168,7 +168,7 @@ pub fn change_continue_label() { } #[cfg(not(cfail1))] -#[rustc_clean(cfg="cfail2", except="hir_owner_nodes, mir_built, typeck_tables_of")] +#[rustc_clean(cfg="cfail2", except="hir_owner_nodes, mir_built, typeck")] #[rustc_clean(cfg="cfail3")] pub fn change_continue_label() { let mut _x = 0; @@ -193,7 +193,7 @@ pub fn change_continue_to_break() { } #[cfg(not(cfail1))] -#[rustc_clean(cfg="cfail2", except="hir_owner_nodes, mir_built, optimized_mir, typeck_tables_of")] +#[rustc_clean(cfg="cfail2", except="hir_owner_nodes, mir_built, optimized_mir, typeck")] #[rustc_clean(cfg="cfail3")] pub fn change_continue_to_break() { let mut _x = 0; diff --git a/src/test/incremental/hashes/match_expressions.rs b/src/test/incremental/hashes/match_expressions.rs index 033723a4c7796..2b315cdc0dc37 100644 --- a/src/test/incremental/hashes/match_expressions.rs +++ b/src/test/incremental/hashes/match_expressions.rs @@ -26,7 +26,7 @@ pub fn add_arm(x: u32) -> u32 { #[cfg(not(cfail1))] #[rustc_clean(cfg="cfail2", - except="hir_owner_nodes,mir_built,optimized_mir,typeck_tables_of")] + except="hir_owner_nodes,mir_built,optimized_mir,typeck")] #[rustc_clean(cfg="cfail3")] pub fn add_arm(x: u32) -> u32 { match x { @@ -75,7 +75,7 @@ pub fn add_guard_clause(x: u32, y: bool) -> u32 { #[cfg(not(cfail1))] #[rustc_clean(cfg="cfail2", - except="hir_owner_nodes,mir_built,optimized_mir,typeck_tables_of")] + except="hir_owner_nodes,mir_built,optimized_mir,typeck")] #[rustc_clean(cfg="cfail3")] pub fn add_guard_clause(x: u32, y: bool) -> u32 { match x { @@ -99,7 +99,7 @@ pub fn change_guard_clause(x: u32, y: bool) -> u32 { #[cfg(not(cfail1))] #[rustc_clean(cfg="cfail2", - except="hir_owner_nodes,mir_built,optimized_mir,typeck_tables_of")] + except="hir_owner_nodes,mir_built,optimized_mir,typeck")] #[rustc_clean(cfg="cfail3")] pub fn change_guard_clause(x: u32, y: bool) -> u32 { match x { @@ -123,7 +123,7 @@ pub fn add_at_binding(x: u32) -> u32 { #[cfg(not(cfail1))] #[rustc_clean(cfg="cfail2", - except="hir_owner_nodes,mir_built,optimized_mir,typeck_tables_of")] + except="hir_owner_nodes,mir_built,optimized_mir,typeck")] #[rustc_clean(cfg="cfail3")] pub fn add_at_binding(x: u32) -> u32 { match x { @@ -170,7 +170,7 @@ pub fn change_simple_name_to_pattern(x: u32) -> u32 { #[cfg(not(cfail1))] #[rustc_clean(cfg="cfail2", - except="hir_owner_nodes,mir_built,optimized_mir,typeck_tables_of")] + except="hir_owner_nodes,mir_built,optimized_mir,typeck")] #[rustc_clean(cfg="cfail3")] pub fn change_simple_name_to_pattern(x: u32) -> u32 { match (x, x & 1) { @@ -216,7 +216,7 @@ pub fn change_mutability_of_binding_in_pattern(x: u32) -> u32 { #[cfg(not(cfail1))] #[rustc_clean(cfg="cfail2", - except="hir_owner_nodes,mir_built,optimized_mir,typeck_tables_of")] + except="hir_owner_nodes,mir_built,optimized_mir,typeck")] #[rustc_clean(cfg="cfail3")] pub fn change_mutability_of_binding_in_pattern(x: u32) -> u32 { match (x, x & 1) { @@ -238,7 +238,7 @@ pub fn add_ref_to_binding_in_pattern(x: u32) -> u32 { #[cfg(not(cfail1))] #[rustc_clean(cfg="cfail2", - except="hir_owner_nodes,mir_built,optimized_mir,typeck_tables_of")] + except="hir_owner_nodes,mir_built,optimized_mir,typeck")] #[rustc_clean(cfg="cfail3")] pub fn add_ref_to_binding_in_pattern(x: u32) -> u32 { match (x, x & 1) { @@ -260,7 +260,7 @@ pub fn add_amp_to_binding_in_pattern(x: u32) -> u32 { #[cfg(not(cfail1))] #[rustc_clean(cfg="cfail2", -except="hir_owner_nodes,mir_built,optimized_mir,typeck_tables_of")] +except="hir_owner_nodes,mir_built,optimized_mir,typeck")] #[rustc_clean(cfg="cfail3")] pub fn add_amp_to_binding_in_pattern(x: u32) -> u32 { match (&x, x & 1) { @@ -307,7 +307,7 @@ pub fn add_alternative_to_arm(x: u32) -> u32 { #[cfg(not(cfail1))] #[rustc_clean(cfg="cfail2", - except="hir_owner_nodes,mir_built,optimized_mir,typeck_tables_of")] + except="hir_owner_nodes,mir_built,optimized_mir,typeck")] #[rustc_clean(cfg="cfail3")] pub fn add_alternative_to_arm(x: u32) -> u32 { match x { diff --git a/src/test/incremental/hashes/struct_constructors.rs b/src/test/incremental/hashes/struct_constructors.rs index 006b712923b99..8957a2b4fadeb 100644 --- a/src/test/incremental/hashes/struct_constructors.rs +++ b/src/test/incremental/hashes/struct_constructors.rs @@ -54,7 +54,7 @@ pub fn change_field_order_regular_struct() -> RegularStruct { } #[cfg(not(cfail1))] -#[rustc_clean(cfg="cfail2", except="hir_owner_nodes,typeck_tables_of")] +#[rustc_clean(cfg="cfail2", except="hir_owner_nodes,typeck")] #[rustc_clean(cfg="cfail3")] pub fn change_field_order_regular_struct() -> RegularStruct { RegularStruct { @@ -82,7 +82,7 @@ pub fn add_field_regular_struct() -> RegularStruct { } #[cfg(not(cfail1))] -#[rustc_clean(cfg="cfail2", except="hir_owner_nodes,optimized_mir,mir_built,typeck_tables_of")] +#[rustc_clean(cfg="cfail2", except="hir_owner_nodes,optimized_mir,mir_built,typeck")] #[rustc_clean(cfg="cfail3")] pub fn add_field_regular_struct() -> RegularStruct { let struct1 = RegularStruct { @@ -117,7 +117,7 @@ pub fn change_field_label_regular_struct() -> RegularStruct { } #[cfg(not(cfail1))] -#[rustc_clean(cfg="cfail2", except="hir_owner_nodes,optimized_mir,mir_built,typeck_tables_of")] +#[rustc_clean(cfg="cfail2", except="hir_owner_nodes,optimized_mir,mir_built,typeck")] #[rustc_clean(cfg="cfail3")] pub fn change_field_label_regular_struct() -> RegularStruct { let struct1 = RegularStruct { @@ -152,7 +152,7 @@ pub fn change_constructor_path_regular_struct() { } #[cfg(not(cfail1))] -#[rustc_clean(cfg="cfail2", except="hir_owner_nodes,mir_built,typeck_tables_of")] +#[rustc_clean(cfg="cfail2", except="hir_owner_nodes,mir_built,typeck")] #[rustc_clean(cfg="cfail3")] pub fn change_constructor_path_regular_struct() { let _ = RegularStruct2 { @@ -173,7 +173,7 @@ pub mod change_constructor_path_indirectly_regular_struct { #[rustc_clean( cfg="cfail2", - except="fn_sig,hir_owner,hir_owner_nodes,optimized_mir,mir_built,typeck_tables_of" + except="fn_sig,hir_owner,hir_owner_nodes,optimized_mir,mir_built,typeck" )] #[rustc_clean(cfg="cfail3")] pub fn function() -> Struct { @@ -213,7 +213,7 @@ pub fn change_constructor_path_tuple_struct() { } #[cfg(not(cfail1))] -#[rustc_clean(cfg="cfail2", except="hir_owner_nodes,mir_built,typeck_tables_of")] +#[rustc_clean(cfg="cfail2", except="hir_owner_nodes,mir_built,typeck")] #[rustc_clean(cfg="cfail3")] pub fn change_constructor_path_tuple_struct() { let _ = TupleStruct2(0, 1, 2); @@ -230,7 +230,7 @@ pub mod change_constructor_path_indirectly_tuple_struct { #[rustc_clean( cfg="cfail2", - except="fn_sig,hir_owner,hir_owner_nodes,optimized_mir,mir_built,typeck_tables_of" + except="fn_sig,hir_owner,hir_owner_nodes,optimized_mir,mir_built,typeck" )] #[rustc_clean(cfg="cfail3")] pub fn function() -> Struct { diff --git a/src/test/incremental/hashes/unary_and_binary_exprs.rs b/src/test/incremental/hashes/unary_and_binary_exprs.rs index c8b53c27b02c8..b357cb16b473a 100644 --- a/src/test/incremental/hashes/unary_and_binary_exprs.rs +++ b/src/test/incremental/hashes/unary_and_binary_exprs.rs @@ -368,7 +368,7 @@ pub fn type_cast(a: u8) -> u64 { } #[cfg(not(cfail1))] -#[rustc_clean(except="hir_owner_nodes,optimized_mir,mir_built,typeck_tables_of", cfg="cfail2")] +#[rustc_clean(except="hir_owner_nodes,optimized_mir,mir_built,typeck", cfg="cfail2")] #[rustc_clean(cfg="cfail3")] pub fn type_cast(a: u8) -> u64 { let b = a as u32; diff --git a/src/test/incremental/hashes/while_let_loops.rs b/src/test/incremental/hashes/while_let_loops.rs index 36e0fcdbe74d1..7f2e5674440a0 100644 --- a/src/test/incremental/hashes/while_let_loops.rs +++ b/src/test/incremental/hashes/while_let_loops.rs @@ -70,7 +70,7 @@ pub fn add_break() { } #[cfg(not(cfail1))] -#[rustc_clean(cfg="cfail2", except="hir_owner_nodes, mir_built, typeck_tables_of")] +#[rustc_clean(cfg="cfail2", except="hir_owner_nodes, mir_built, typeck")] #[rustc_clean(cfg="cfail3")] pub fn add_break() { let mut _x = 0; diff --git a/src/test/incremental/hashes/while_loops.rs b/src/test/incremental/hashes/while_loops.rs index 83f09bd7be614..fdf6853f0395d 100644 --- a/src/test/incremental/hashes/while_loops.rs +++ b/src/test/incremental/hashes/while_loops.rs @@ -70,7 +70,7 @@ pub fn add_break() { } #[cfg(not(cfail1))] -#[rustc_clean(cfg="cfail2", except="hir_owner_nodes, mir_built, optimized_mir, typeck_tables_of")] +#[rustc_clean(cfg="cfail2", except="hir_owner_nodes, mir_built, optimized_mir, typeck")] #[rustc_clean(cfg="cfail3")] pub fn add_break() { let mut _x = 0; diff --git a/src/test/incremental/hello_world.rs b/src/test/incremental/hello_world.rs index e4d8c56752c78..4c60d7bd9d526 100644 --- a/src/test/incremental/hello_world.rs +++ b/src/test/incremental/hello_world.rs @@ -21,7 +21,7 @@ mod x { mod y { use x; - #[rustc_clean(label="typeck_tables_of", cfg="rpass2")] + #[rustc_clean(label="typeck", cfg="rpass2")] pub fn yyyy() { x::xxxx(); } @@ -30,7 +30,7 @@ mod y { mod z { use y; - #[rustc_clean(label="typeck_tables_of", cfg="rpass2")] + #[rustc_clean(label="typeck", cfg="rpass2")] pub fn z() { y::yyyy(); } diff --git a/src/test/incremental/ich_method_call_trait_scope.rs b/src/test/incremental/ich_method_call_trait_scope.rs index 847bce7ef90b0..6d7d446cb7c55 100644 --- a/src/test/incremental/ich_method_call_trait_scope.rs +++ b/src/test/incremental/ich_method_call_trait_scope.rs @@ -28,14 +28,14 @@ mod mod3 { #[rustc_clean(label="hir_owner", cfg="rpass2")] #[rustc_clean(label="hir_owner_nodes", cfg="rpass2")] - #[rustc_dirty(label="typeck_tables_of", cfg="rpass2")] + #[rustc_dirty(label="typeck", cfg="rpass2")] fn bar() { ().method(); } #[rustc_clean(label="hir_owner", cfg="rpass2")] #[rustc_clean(label="hir_owner_nodes", cfg="rpass2")] - #[rustc_clean(label="typeck_tables_of", cfg="rpass2")] + #[rustc_clean(label="typeck", cfg="rpass2")] fn baz() { 22; // no method call, traits in scope don't matter } diff --git a/src/test/incremental/rlib_cross_crate/b.rs b/src/test/incremental/rlib_cross_crate/b.rs index 81b84ba741dc8..73846712b5960 100644 --- a/src/test/incremental/rlib_cross_crate/b.rs +++ b/src/test/incremental/rlib_cross_crate/b.rs @@ -12,15 +12,15 @@ extern crate a; -#[rustc_dirty(label="typeck_tables_of", cfg="rpass2")] -#[rustc_clean(label="typeck_tables_of", cfg="rpass3")] +#[rustc_dirty(label="typeck", cfg="rpass2")] +#[rustc_clean(label="typeck", cfg="rpass3")] pub fn use_X() -> u32 { let x: a::X = 22; x as u32 } -#[rustc_clean(label="typeck_tables_of", cfg="rpass2")] -#[rustc_clean(label="typeck_tables_of", cfg="rpass3")] +#[rustc_clean(label="typeck", cfg="rpass2")] +#[rustc_clean(label="typeck", cfg="rpass3")] pub fn use_Y() { let x: a::Y = 'c'; } diff --git a/src/test/incremental/string_constant.rs b/src/test/incremental/string_constant.rs index cc35f3bdf299b..2fc725294313b 100644 --- a/src/test/incremental/string_constant.rs +++ b/src/test/incremental/string_constant.rs @@ -28,7 +28,7 @@ pub mod x { pub mod y { use x; - #[rustc_clean(label="typeck_tables_of", cfg="cfail2")] + #[rustc_clean(label="typeck", cfg="cfail2")] #[rustc_clean(label="optimized_mir", cfg="cfail2")] pub fn y() { x::x(); @@ -38,7 +38,7 @@ pub mod y { pub mod z { use y; - #[rustc_clean(label="typeck_tables_of", cfg="cfail2")] + #[rustc_clean(label="typeck", cfg="cfail2")] #[rustc_clean(label="optimized_mir", cfg="cfail2")] pub fn z() { y::y(); diff --git a/src/test/incremental/struct_add_field.rs b/src/test/incremental/struct_add_field.rs index d2e1e7decf54e..4c29f196f67c9 100644 --- a/src/test/incremental/struct_add_field.rs +++ b/src/test/incremental/struct_add_field.rs @@ -21,17 +21,17 @@ pub struct Y { pub y: char } -#[rustc_dirty(label="typeck_tables_of", cfg="rpass2")] +#[rustc_dirty(label="typeck", cfg="rpass2")] pub fn use_X(x: X) -> u32 { x.x as u32 } -#[rustc_dirty(label="typeck_tables_of", cfg="rpass2")] +#[rustc_dirty(label="typeck", cfg="rpass2")] pub fn use_EmbedX(embed: EmbedX) -> u32 { embed.x.x as u32 } -#[rustc_clean(label="typeck_tables_of", cfg="rpass2")] +#[rustc_clean(label="typeck", cfg="rpass2")] pub fn use_Y() { let x: Y = Y { y: 'c' }; } diff --git a/src/test/incremental/struct_change_field_name.rs b/src/test/incremental/struct_change_field_name.rs index 68356f703bcf8..ee88fbdf59275 100644 --- a/src/test/incremental/struct_change_field_name.rs +++ b/src/test/incremental/struct_change_field_name.rs @@ -24,7 +24,7 @@ pub struct Y { pub y: char } -#[rustc_dirty(label="typeck_tables_of", cfg="cfail2")] +#[rustc_dirty(label="typeck", cfg="cfail2")] pub fn use_X() -> u32 { let x: X = X { x: 22 }; //[cfail2]~^ ERROR struct `X` has no field named `x` @@ -32,13 +32,13 @@ pub fn use_X() -> u32 { //[cfail2]~^ ERROR no field `x` on type `X` } -#[rustc_dirty(label="typeck_tables_of", cfg="cfail2")] +#[rustc_dirty(label="typeck", cfg="cfail2")] pub fn use_EmbedX(embed: EmbedX) -> u32 { embed.x.x as u32 //[cfail2]~^ ERROR no field `x` on type `X` } -#[rustc_clean(label="typeck_tables_of", cfg="cfail2")] +#[rustc_clean(label="typeck", cfg="cfail2")] pub fn use_Y() { let x: Y = Y { y: 'c' }; } diff --git a/src/test/incremental/struct_change_field_type.rs b/src/test/incremental/struct_change_field_type.rs index 308ec84fa72ef..b60b4b311eeb3 100644 --- a/src/test/incremental/struct_change_field_type.rs +++ b/src/test/incremental/struct_change_field_type.rs @@ -24,19 +24,19 @@ pub struct Y { pub y: char } -#[rustc_dirty(label="typeck_tables_of", cfg="rpass2")] +#[rustc_dirty(label="typeck", cfg="rpass2")] pub fn use_X() -> u32 { let x: X = X { x: 22 }; x.x as u32 } -#[rustc_dirty(label="typeck_tables_of", cfg="rpass2")] +#[rustc_dirty(label="typeck", cfg="rpass2")] pub fn use_EmbedX(x: EmbedX) -> u32 { let x: X = X { x: 22 }; x.x as u32 } -#[rustc_clean(label="typeck_tables_of", cfg="rpass2")] +#[rustc_clean(label="typeck", cfg="rpass2")] pub fn use_Y() { let x: Y = Y { y: 'c' }; } diff --git a/src/test/incremental/struct_change_field_type_cross_crate/b.rs b/src/test/incremental/struct_change_field_type_cross_crate/b.rs index 9d84c2cf773b8..0221d510eaba7 100644 --- a/src/test/incremental/struct_change_field_type_cross_crate/b.rs +++ b/src/test/incremental/struct_change_field_type_cross_crate/b.rs @@ -8,18 +8,18 @@ extern crate a; use a::*; -#[rustc_dirty(label="typeck_tables_of", cfg="rpass2")] +#[rustc_dirty(label="typeck", cfg="rpass2")] pub fn use_X() -> u32 { let x: X = X { x: 22 }; x.x as u32 } -#[rustc_dirty(label="typeck_tables_of", cfg="rpass2")] +#[rustc_dirty(label="typeck", cfg="rpass2")] pub fn use_EmbedX(embed: EmbedX) -> u32 { embed.x.x as u32 } -#[rustc_clean(label="typeck_tables_of", cfg="rpass2")] +#[rustc_clean(label="typeck", cfg="rpass2")] pub fn use_Y() { let x: Y = Y { y: 'c' }; } diff --git a/src/test/incremental/struct_change_nothing.rs b/src/test/incremental/struct_change_nothing.rs index bbded1da21619..3ab90e966fb6d 100644 --- a/src/test/incremental/struct_change_nothing.rs +++ b/src/test/incremental/struct_change_nothing.rs @@ -24,19 +24,19 @@ pub struct Y { pub y: char } -#[rustc_clean(label="typeck_tables_of", cfg="rpass2")] +#[rustc_clean(label="typeck", cfg="rpass2")] pub fn use_X() -> u32 { let x: X = X { x: 22 }; x.x as u32 } -#[rustc_clean(label="typeck_tables_of", cfg="rpass2")] +#[rustc_clean(label="typeck", cfg="rpass2")] pub fn use_EmbedX(x: EmbedX) -> u32 { let x: X = X { x: 22 }; x.x as u32 } -#[rustc_clean(label="typeck_tables_of", cfg="rpass2")] +#[rustc_clean(label="typeck", cfg="rpass2")] pub fn use_Y() { let x: Y = Y { y: 'c' }; } diff --git a/src/test/incremental/struct_remove_field.rs b/src/test/incremental/struct_remove_field.rs index 4c4028bbe5bdd..f6017b1b1c3a6 100644 --- a/src/test/incremental/struct_remove_field.rs +++ b/src/test/incremental/struct_remove_field.rs @@ -25,17 +25,17 @@ pub struct Y { pub y: char } -#[rustc_dirty(label="typeck_tables_of", cfg="rpass2")] +#[rustc_dirty(label="typeck", cfg="rpass2")] pub fn use_X(x: X) -> u32 { x.x as u32 } -#[rustc_dirty(label="typeck_tables_of", cfg="rpass2")] +#[rustc_dirty(label="typeck", cfg="rpass2")] pub fn use_EmbedX(embed: EmbedX) -> u32 { embed.x.x as u32 } -#[rustc_clean(label="typeck_tables_of", cfg="rpass2")] +#[rustc_clean(label="typeck", cfg="rpass2")] pub fn use_Y() { let x: Y = Y { y: 'c' }; } diff --git a/src/test/incremental/type_alias_cross_crate/b.rs b/src/test/incremental/type_alias_cross_crate/b.rs index cef2e4bab12d7..05c926fdded7c 100644 --- a/src/test/incremental/type_alias_cross_crate/b.rs +++ b/src/test/incremental/type_alias_cross_crate/b.rs @@ -6,15 +6,15 @@ extern crate a; -#[rustc_dirty(label="typeck_tables_of", cfg="rpass2")] -#[rustc_clean(label="typeck_tables_of", cfg="rpass3")] +#[rustc_dirty(label="typeck", cfg="rpass2")] +#[rustc_clean(label="typeck", cfg="rpass3")] pub fn use_X() -> u32 { let x: a::X = 22; x as u32 } -#[rustc_clean(label="typeck_tables_of", cfg="rpass2")] -#[rustc_clean(label="typeck_tables_of", cfg="rpass3")] +#[rustc_clean(label="typeck", cfg="rpass2")] +#[rustc_clean(label="typeck", cfg="rpass3")] pub fn use_Y() { let x: a::Y = 'c'; } diff --git a/src/test/run-make/rustc-macro-dep-files/foo.rs b/src/test/run-make/rustc-macro-dep-files/foo.rs index 00b1c26d43f10..66db1a2173665 100644 --- a/src/test/run-make/rustc-macro-dep-files/foo.rs +++ b/src/test/run-make/rustc-macro-dep-files/foo.rs @@ -7,6 +7,6 @@ use proc_macro::TokenStream; #[proc_macro_derive(A)] pub fn derive(input: TokenStream) -> TokenStream { let input = input.to_string(); - assert!(input.contains("struct A;")); + assert!(input.contains("struct A ;")); "struct B;".parse().unwrap() } diff --git a/src/test/ui/async-await/issues/issue-60674.stdout b/src/test/ui/async-await/issues/issue-60674.stdout index 86c3591b3afc0..395d9e21b3848 100644 --- a/src/test/ui/async-await/issues/issue-60674.stdout +++ b/src/test/ui/async-await/issues/issue-60674.stdout @@ -1,3 +1,3 @@ -async fn f(mut x: u8) { } -async fn g((mut x, y, mut z): (u8, u8, u8)) { } -async fn g(mut x: u8, (a, mut b, c): (u8, u8, u8), y: u8) { } +async fn f(mut x : u8) { } +async fn g((mut x, y, mut z) : (u8, u8, u8)) { } +async fn g(mut x : u8, (a, mut b, c) : (u8, u8, u8), y : u8) { } diff --git a/src/test/ui/const-generics/lazy-normalization/issue-71922.rs b/src/test/ui/const-generics/lazy-normalization/issue-71922.rs deleted file mode 100644 index 0d392ddcaedcc..0000000000000 --- a/src/test/ui/const-generics/lazy-normalization/issue-71922.rs +++ /dev/null @@ -1,19 +0,0 @@ -#![feature(const_generics)] -//~^ WARN the feature `const_generics` is incomplete -trait Foo {} - -impl Foo for [(); N] where Self: FooImpl<{ N == 0 }> {} -//~^ ERROR constant expression depends on a generic parameter - -trait FooImpl {} - -impl FooImpl<{ 0u8 == 0u8 }> for [(); 0] {} - -impl FooImpl<{ 0u8 != 0u8 }> for [(); N] {} - -fn foo(_: T) {} - -fn main() { - foo([]); - foo([()]); -} diff --git a/src/test/ui/const-generics/lazy-normalization/issue-71922.stderr b/src/test/ui/const-generics/lazy-normalization/issue-71922.stderr deleted file mode 100644 index 00917571e716d..0000000000000 --- a/src/test/ui/const-generics/lazy-normalization/issue-71922.stderr +++ /dev/null @@ -1,19 +0,0 @@ -warning: the feature `const_generics` is incomplete and may not be safe to use and/or cause compiler crashes - --> $DIR/issue-71922.rs:1:12 - | -LL | #![feature(const_generics)] - | ^^^^^^^^^^^^^^ - | - = note: `#[warn(incomplete_features)]` on by default - = note: see issue #44580 for more information - -error: constant expression depends on a generic parameter - --> $DIR/issue-71922.rs:5:50 - | -LL | impl Foo for [(); N] where Self: FooImpl<{ N == 0 }> {} - | ^^^^^^^^^^^^^^^^^^^ - | - = note: this may fail depending on what value the parameter takes - -error: aborting due to previous error; 1 warning emitted - diff --git a/src/test/ui/consts/miri_unleashed/drop.stderr b/src/test/ui/consts/miri_unleashed/drop.stderr index 34ab5155e22d0..1fa3992cc5afd 100644 --- a/src/test/ui/consts/miri_unleashed/drop.stderr +++ b/src/test/ui/consts/miri_unleashed/drop.stderr @@ -4,7 +4,9 @@ error[E0080]: could not evaluate static initializer LL | / pub unsafe fn drop_in_place(to_drop: *mut T) { LL | | // Code here does not matter - this is replaced by the LL | | // real drop glue by the compiler. -LL | | drop_in_place(to_drop) +LL | | +LL | | // SAFETY: see comment above +LL | | unsafe { drop_in_place(to_drop) } LL | | } | | ^ | | | diff --git a/src/test/ui/consts/offset_from_ub.stderr b/src/test/ui/consts/offset_from_ub.stderr index cde2fe3262692..aa65f4de3e17e 100644 --- a/src/test/ui/consts/offset_from_ub.stderr +++ b/src/test/ui/consts/offset_from_ub.stderr @@ -1,12 +1,12 @@ error: any use of this value will cause an error --> $SRC_DIR/libcore/ptr/const_ptr.rs:LL:COL | -LL | intrinsics::ptr_offset_from(self, origin) - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | ptr_offset_from cannot compute offset of pointers into different allocations. - | inside `std::ptr::const_ptr::::offset_from` at $SRC_DIR/libcore/ptr/const_ptr.rs:LL:COL - | inside `DIFFERENT_ALLOC` at $DIR/offset_from_ub.rs:17:27 +LL | unsafe { intrinsics::ptr_offset_from(self, origin) } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | | + | ptr_offset_from cannot compute offset of pointers into different allocations. + | inside `std::ptr::const_ptr::::offset_from` at $SRC_DIR/libcore/ptr/const_ptr.rs:LL:COL + | inside `DIFFERENT_ALLOC` at $DIR/offset_from_ub.rs:17:27 | ::: $DIR/offset_from_ub.rs:11:1 | @@ -24,12 +24,12 @@ LL | | }; error: any use of this value will cause an error --> $SRC_DIR/libcore/ptr/const_ptr.rs:LL:COL | -LL | intrinsics::ptr_offset_from(self, origin) - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | unable to turn bytes into a pointer - | inside `std::ptr::const_ptr::::offset_from` at $SRC_DIR/libcore/ptr/const_ptr.rs:LL:COL - | inside `NOT_PTR` at $DIR/offset_from_ub.rs:23:14 +LL | unsafe { intrinsics::ptr_offset_from(self, origin) } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | | + | unable to turn bytes into a pointer + | inside `std::ptr::const_ptr::::offset_from` at $SRC_DIR/libcore/ptr/const_ptr.rs:LL:COL + | inside `NOT_PTR` at $DIR/offset_from_ub.rs:23:14 | ::: $DIR/offset_from_ub.rs:21:1 | @@ -42,12 +42,12 @@ LL | | }; error: any use of this value will cause an error --> $SRC_DIR/libcore/ptr/const_ptr.rs:LL:COL | -LL | intrinsics::ptr_offset_from(self, origin) - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | exact_div: 1_isize cannot be divided by 2_isize without remainder - | inside `std::ptr::const_ptr::::offset_from` at $SRC_DIR/libcore/ptr/const_ptr.rs:LL:COL - | inside `NOT_MULTIPLE_OF_SIZE` at $DIR/offset_from_ub.rs:31:14 +LL | unsafe { intrinsics::ptr_offset_from(self, origin) } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | | + | exact_div: 1_isize cannot be divided by 2_isize without remainder + | inside `std::ptr::const_ptr::::offset_from` at $SRC_DIR/libcore/ptr/const_ptr.rs:LL:COL + | inside `NOT_MULTIPLE_OF_SIZE` at $DIR/offset_from_ub.rs:31:14 | ::: $DIR/offset_from_ub.rs:26:1 | @@ -63,12 +63,12 @@ LL | | }; error: any use of this value will cause an error --> $SRC_DIR/libcore/ptr/const_ptr.rs:LL:COL | -LL | intrinsics::ptr_offset_from(self, origin) - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | inbounds test failed: 0x0 is not a valid pointer - | inside `std::ptr::const_ptr::::offset_from` at $SRC_DIR/libcore/ptr/const_ptr.rs:LL:COL - | inside `OFFSET_FROM_NULL` at $DIR/offset_from_ub.rs:37:14 +LL | unsafe { intrinsics::ptr_offset_from(self, origin) } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | | + | inbounds test failed: 0x0 is not a valid pointer + | inside `std::ptr::const_ptr::::offset_from` at $SRC_DIR/libcore/ptr/const_ptr.rs:LL:COL + | inside `OFFSET_FROM_NULL` at $DIR/offset_from_ub.rs:37:14 | ::: $DIR/offset_from_ub.rs:34:1 | @@ -82,12 +82,12 @@ LL | | }; error: any use of this value will cause an error --> $SRC_DIR/libcore/ptr/const_ptr.rs:LL:COL | -LL | intrinsics::ptr_offset_from(self, origin) - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | unable to turn bytes into a pointer - | inside `std::ptr::const_ptr::::offset_from` at $SRC_DIR/libcore/ptr/const_ptr.rs:LL:COL - | inside `DIFFERENT_INT` at $DIR/offset_from_ub.rs:44:14 +LL | unsafe { intrinsics::ptr_offset_from(self, origin) } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | | + | unable to turn bytes into a pointer + | inside `std::ptr::const_ptr::::offset_from` at $SRC_DIR/libcore/ptr/const_ptr.rs:LL:COL + | inside `DIFFERENT_INT` at $DIR/offset_from_ub.rs:44:14 | ::: $DIR/offset_from_ub.rs:40:1 | diff --git a/src/test/ui/consts/offset_ub.stderr b/src/test/ui/consts/offset_ub.stderr index 0ab81cc0c5b31..0a144a6bac2f1 100644 --- a/src/test/ui/consts/offset_ub.stderr +++ b/src/test/ui/consts/offset_ub.stderr @@ -1,12 +1,12 @@ error: any use of this value will cause an error --> $SRC_DIR/libcore/ptr/const_ptr.rs:LL:COL | -LL | intrinsics::offset(self, count) - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | overflowing in-bounds pointer arithmetic - | inside `std::ptr::const_ptr::::offset` at $SRC_DIR/libcore/ptr/const_ptr.rs:LL:COL - | inside `BEFORE_START` at $DIR/offset_ub.rs:7:46 +LL | unsafe { intrinsics::offset(self, count) } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | | + | overflowing in-bounds pointer arithmetic + | inside `std::ptr::const_ptr::::offset` at $SRC_DIR/libcore/ptr/const_ptr.rs:LL:COL + | inside `BEFORE_START` at $DIR/offset_ub.rs:7:46 | ::: $DIR/offset_ub.rs:7:1 | @@ -18,12 +18,12 @@ LL | pub const BEFORE_START: *const u8 = unsafe { (&0u8 as *const u8).offset(-1) error: any use of this value will cause an error --> $SRC_DIR/libcore/ptr/const_ptr.rs:LL:COL | -LL | intrinsics::offset(self, count) - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | inbounds test failed: pointer must be in-bounds at offset 2, but is outside bounds of allocN which has size 1 - | inside `std::ptr::const_ptr::::offset` at $SRC_DIR/libcore/ptr/const_ptr.rs:LL:COL - | inside `AFTER_END` at $DIR/offset_ub.rs:8:43 +LL | unsafe { intrinsics::offset(self, count) } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | | + | inbounds test failed: pointer must be in-bounds at offset 2, but is outside bounds of allocN which has size 1 + | inside `std::ptr::const_ptr::::offset` at $SRC_DIR/libcore/ptr/const_ptr.rs:LL:COL + | inside `AFTER_END` at $DIR/offset_ub.rs:8:43 | ::: $DIR/offset_ub.rs:8:1 | @@ -33,12 +33,12 @@ LL | pub const AFTER_END: *const u8 = unsafe { (&0u8 as *const u8).offset(2) }; error: any use of this value will cause an error --> $SRC_DIR/libcore/ptr/const_ptr.rs:LL:COL | -LL | intrinsics::offset(self, count) - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | inbounds test failed: pointer must be in-bounds at offset 101, but is outside bounds of allocN which has size 100 - | inside `std::ptr::const_ptr::::offset` at $SRC_DIR/libcore/ptr/const_ptr.rs:LL:COL - | inside `AFTER_ARRAY` at $DIR/offset_ub.rs:9:45 +LL | unsafe { intrinsics::offset(self, count) } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | | + | inbounds test failed: pointer must be in-bounds at offset 101, but is outside bounds of allocN which has size 100 + | inside `std::ptr::const_ptr::::offset` at $SRC_DIR/libcore/ptr/const_ptr.rs:LL:COL + | inside `AFTER_ARRAY` at $DIR/offset_ub.rs:9:45 | ::: $DIR/offset_ub.rs:9:1 | @@ -48,12 +48,12 @@ LL | pub const AFTER_ARRAY: *const u8 = unsafe { [0u8; 100].as_ptr().offset(101) error: any use of this value will cause an error --> $SRC_DIR/libcore/ptr/const_ptr.rs:LL:COL | -LL | intrinsics::offset(self, count) - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | overflowing in-bounds pointer arithmetic - | inside `std::ptr::const_ptr::::offset` at $SRC_DIR/libcore/ptr/const_ptr.rs:LL:COL - | inside `OVERFLOW` at $DIR/offset_ub.rs:11:43 +LL | unsafe { intrinsics::offset(self, count) } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | | + | overflowing in-bounds pointer arithmetic + | inside `std::ptr::const_ptr::::offset` at $SRC_DIR/libcore/ptr/const_ptr.rs:LL:COL + | inside `OVERFLOW` at $DIR/offset_ub.rs:11:43 | ::: $DIR/offset_ub.rs:11:1 | @@ -63,12 +63,12 @@ LL | pub const OVERFLOW: *const u16 = unsafe { [0u16; 1].as_ptr().offset(isize:: error: any use of this value will cause an error --> $SRC_DIR/libcore/ptr/const_ptr.rs:LL:COL | -LL | intrinsics::offset(self, count) - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | overflowing in-bounds pointer arithmetic - | inside `std::ptr::const_ptr::::offset` at $SRC_DIR/libcore/ptr/const_ptr.rs:LL:COL - | inside `UNDERFLOW` at $DIR/offset_ub.rs:12:44 +LL | unsafe { intrinsics::offset(self, count) } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | | + | overflowing in-bounds pointer arithmetic + | inside `std::ptr::const_ptr::::offset` at $SRC_DIR/libcore/ptr/const_ptr.rs:LL:COL + | inside `UNDERFLOW` at $DIR/offset_ub.rs:12:44 | ::: $DIR/offset_ub.rs:12:1 | @@ -78,12 +78,12 @@ LL | pub const UNDERFLOW: *const u16 = unsafe { [0u16; 1].as_ptr().offset(isize: error: any use of this value will cause an error --> $SRC_DIR/libcore/ptr/const_ptr.rs:LL:COL | -LL | intrinsics::offset(self, count) - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | overflowing in-bounds pointer arithmetic - | inside `std::ptr::const_ptr::::offset` at $SRC_DIR/libcore/ptr/const_ptr.rs:LL:COL - | inside `OVERFLOW_ADDRESS_SPACE` at $DIR/offset_ub.rs:13:56 +LL | unsafe { intrinsics::offset(self, count) } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | | + | overflowing in-bounds pointer arithmetic + | inside `std::ptr::const_ptr::::offset` at $SRC_DIR/libcore/ptr/const_ptr.rs:LL:COL + | inside `OVERFLOW_ADDRESS_SPACE` at $DIR/offset_ub.rs:13:56 | ::: $DIR/offset_ub.rs:13:1 | @@ -93,12 +93,12 @@ LL | pub const OVERFLOW_ADDRESS_SPACE: *const u8 = unsafe { (usize::MAX as *cons error: any use of this value will cause an error --> $SRC_DIR/libcore/ptr/const_ptr.rs:LL:COL | -LL | intrinsics::offset(self, count) - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | overflowing in-bounds pointer arithmetic - | inside `std::ptr::const_ptr::::offset` at $SRC_DIR/libcore/ptr/const_ptr.rs:LL:COL - | inside `UNDERFLOW_ADDRESS_SPACE` at $DIR/offset_ub.rs:14:57 +LL | unsafe { intrinsics::offset(self, count) } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | | + | overflowing in-bounds pointer arithmetic + | inside `std::ptr::const_ptr::::offset` at $SRC_DIR/libcore/ptr/const_ptr.rs:LL:COL + | inside `UNDERFLOW_ADDRESS_SPACE` at $DIR/offset_ub.rs:14:57 | ::: $DIR/offset_ub.rs:14:1 | @@ -108,12 +108,12 @@ LL | pub const UNDERFLOW_ADDRESS_SPACE: *const u8 = unsafe { (1 as *const u8).of error: any use of this value will cause an error --> $SRC_DIR/libcore/ptr/const_ptr.rs:LL:COL | -LL | intrinsics::offset(self, count) - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | inbounds test failed: pointer must be in-bounds at offset 1, but is outside bounds of allocN which has size 0 - | inside `std::ptr::const_ptr::::offset` at $SRC_DIR/libcore/ptr/const_ptr.rs:LL:COL - | inside `ZERO_SIZED_ALLOC` at $DIR/offset_ub.rs:16:50 +LL | unsafe { intrinsics::offset(self, count) } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | | + | inbounds test failed: pointer must be in-bounds at offset 1, but is outside bounds of allocN which has size 0 + | inside `std::ptr::const_ptr::::offset` at $SRC_DIR/libcore/ptr/const_ptr.rs:LL:COL + | inside `ZERO_SIZED_ALLOC` at $DIR/offset_ub.rs:16:50 | ::: $DIR/offset_ub.rs:16:1 | @@ -123,12 +123,12 @@ LL | pub const ZERO_SIZED_ALLOC: *const u8 = unsafe { [0u8; 0].as_ptr().offset(1 error: any use of this value will cause an error --> $SRC_DIR/libcore/ptr/mut_ptr.rs:LL:COL | -LL | intrinsics::offset(self, count) as *mut T - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | unable to turn bytes into a pointer - | inside `std::ptr::mut_ptr::::offset` at $SRC_DIR/libcore/ptr/mut_ptr.rs:LL:COL - | inside `DANGLING` at $DIR/offset_ub.rs:17:42 +LL | unsafe { intrinsics::offset(self, count) as *mut T } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | | + | unable to turn bytes into a pointer + | inside `std::ptr::mut_ptr::::offset` at $SRC_DIR/libcore/ptr/mut_ptr.rs:LL:COL + | inside `DANGLING` at $DIR/offset_ub.rs:17:42 | ::: $DIR/offset_ub.rs:17:1 | @@ -138,12 +138,12 @@ LL | pub const DANGLING: *const u8 = unsafe { ptr::NonNull::::dangling().as_ error: any use of this value will cause an error --> $SRC_DIR/libcore/ptr/const_ptr.rs:LL:COL | -LL | intrinsics::offset(self, count) - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | inbounds test failed: 0x0 is not a valid pointer - | inside `std::ptr::const_ptr::::offset` at $SRC_DIR/libcore/ptr/const_ptr.rs:LL:COL - | inside `NULL_OFFSET_ZERO` at $DIR/offset_ub.rs:20:50 +LL | unsafe { intrinsics::offset(self, count) } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | | + | inbounds test failed: 0x0 is not a valid pointer + | inside `std::ptr::const_ptr::::offset` at $SRC_DIR/libcore/ptr/const_ptr.rs:LL:COL + | inside `NULL_OFFSET_ZERO` at $DIR/offset_ub.rs:20:50 | ::: $DIR/offset_ub.rs:20:1 | @@ -153,12 +153,12 @@ LL | pub const NULL_OFFSET_ZERO: *const u8 = unsafe { ptr::null::().offset(0 error: any use of this value will cause an error --> $SRC_DIR/libcore/ptr/const_ptr.rs:LL:COL | -LL | intrinsics::offset(self, count) - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | | - | unable to turn bytes into a pointer - | inside `std::ptr::const_ptr::::offset` at $SRC_DIR/libcore/ptr/const_ptr.rs:LL:COL - | inside `UNDERFLOW_ABS` at $DIR/offset_ub.rs:23:47 +LL | unsafe { intrinsics::offset(self, count) } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | | + | unable to turn bytes into a pointer + | inside `std::ptr::const_ptr::::offset` at $SRC_DIR/libcore/ptr/const_ptr.rs:LL:COL + | inside `UNDERFLOW_ABS` at $DIR/offset_ub.rs:23:47 | ::: $DIR/offset_ub.rs:23:1 | diff --git a/src/test/ui/dep-graph/dep-graph-assoc-type-codegen.rs b/src/test/ui/dep-graph/dep-graph-assoc-type-codegen.rs index bcf7e3e6608ea..0d11d933af04e 100644 --- a/src/test/ui/dep-graph/dep-graph-assoc-type-codegen.rs +++ b/src/test/ui/dep-graph/dep-graph-assoc-type-codegen.rs @@ -25,7 +25,7 @@ mod x { mod y { use Foo; - #[rustc_then_this_would_need(typeck_tables_of)] //~ ERROR OK + #[rustc_then_this_would_need(typeck)] //~ ERROR OK pub fn use_char_assoc() { // Careful here: in the representation, ::T gets // normalized away, so at a certain point we had no edge to diff --git a/src/test/ui/dep-graph/dep-graph-assoc-type-codegen.stderr b/src/test/ui/dep-graph/dep-graph-assoc-type-codegen.stderr index a603d71596ba6..4e659648e9edc 100644 --- a/src/test/ui/dep-graph/dep-graph-assoc-type-codegen.stderr +++ b/src/test/ui/dep-graph/dep-graph-assoc-type-codegen.stderr @@ -1,8 +1,8 @@ error: OK --> $DIR/dep-graph-assoc-type-codegen.rs:28:5 | -LL | #[rustc_then_this_would_need(typeck_tables_of)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | #[rustc_then_this_would_need(typeck)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to previous error diff --git a/src/test/ui/dep-graph/dep-graph-caller-callee.rs b/src/test/ui/dep-graph/dep-graph-caller-callee.rs index 18b4252a06b84..b12c635d2e733 100644 --- a/src/test/ui/dep-graph/dep-graph-caller-callee.rs +++ b/src/test/ui/dep-graph/dep-graph-caller-callee.rs @@ -17,7 +17,7 @@ mod y { use x; // These dependencies SHOULD exist: - #[rustc_then_this_would_need(typeck_tables_of)] //~ ERROR OK + #[rustc_then_this_would_need(typeck)] //~ ERROR OK pub fn y() { x::x(); } @@ -28,7 +28,7 @@ mod z { // These are expected to yield errors, because changes to `x` // affect the BODY of `y`, but not its signature. - #[rustc_then_this_would_need(typeck_tables_of)] //~ ERROR no path + #[rustc_then_this_would_need(typeck)] //~ ERROR no path pub fn z() { y::y(); } diff --git a/src/test/ui/dep-graph/dep-graph-caller-callee.stderr b/src/test/ui/dep-graph/dep-graph-caller-callee.stderr index de041e600672d..164c474183ad0 100644 --- a/src/test/ui/dep-graph/dep-graph-caller-callee.stderr +++ b/src/test/ui/dep-graph/dep-graph-caller-callee.stderr @@ -1,14 +1,14 @@ error: OK --> $DIR/dep-graph-caller-callee.rs:20:5 | -LL | #[rustc_then_this_would_need(typeck_tables_of)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | #[rustc_then_this_would_need(typeck)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error: no path from `x::x` to `typeck_tables_of` +error: no path from `x::x` to `typeck` --> $DIR/dep-graph-caller-callee.rs:31:5 | -LL | #[rustc_then_this_would_need(typeck_tables_of)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | #[rustc_then_this_would_need(typeck)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to 2 previous errors diff --git a/src/test/ui/dep-graph/dep-graph-struct-signature.rs b/src/test/ui/dep-graph/dep-graph-struct-signature.rs index 8b78d39ecae33..7ef6fac48c3a6 100644 --- a/src/test/ui/dep-graph/dep-graph-struct-signature.rs +++ b/src/test/ui/dep-graph/dep-graph-struct-signature.rs @@ -33,11 +33,11 @@ mod signatures { } #[rustc_then_this_would_need(fn_sig)] //~ ERROR OK - #[rustc_then_this_would_need(typeck_tables_of)] //~ ERROR OK + #[rustc_then_this_would_need(typeck)] //~ ERROR OK fn some_fn(x: WillChange) { } #[rustc_then_this_would_need(fn_sig)] //~ ERROR OK - #[rustc_then_this_would_need(typeck_tables_of)] //~ ERROR OK + #[rustc_then_this_would_need(typeck)] //~ ERROR OK fn new_foo(x: u32, y: u32) -> WillChange { WillChange { x: x, y: y } } @@ -45,14 +45,14 @@ mod signatures { #[rustc_then_this_would_need(type_of)] //~ ERROR OK impl WillChange { #[rustc_then_this_would_need(fn_sig)] //~ ERROR OK - #[rustc_then_this_would_need(typeck_tables_of)] //~ ERROR OK + #[rustc_then_this_would_need(typeck)] //~ ERROR OK fn new(x: u32, y: u32) -> WillChange { loop { } } } #[rustc_then_this_would_need(type_of)] //~ ERROR OK impl WillChange { #[rustc_then_this_would_need(fn_sig)] //~ ERROR OK - #[rustc_then_this_would_need(typeck_tables_of)] //~ ERROR OK + #[rustc_then_this_would_need(typeck)] //~ ERROR OK fn method(&self, x: u32) { } } @@ -81,6 +81,6 @@ mod invalid_signatures { fn b(x: WontChange) { } #[rustc_then_this_would_need(fn_sig)] //~ ERROR no path from `WillChange` - #[rustc_then_this_would_need(typeck_tables_of)] //~ ERROR no path from `WillChange` + #[rustc_then_this_would_need(typeck)] //~ ERROR no path from `WillChange` fn c(x: u32) { } } diff --git a/src/test/ui/dep-graph/dep-graph-struct-signature.stderr b/src/test/ui/dep-graph/dep-graph-struct-signature.stderr index 2e00e5a2cbd2f..9d1644a00d002 100644 --- a/src/test/ui/dep-graph/dep-graph-struct-signature.stderr +++ b/src/test/ui/dep-graph/dep-graph-struct-signature.stderr @@ -25,8 +25,8 @@ LL | #[rustc_then_this_would_need(fn_sig)] error: OK --> $DIR/dep-graph-struct-signature.rs:36:5 | -LL | #[rustc_then_this_would_need(typeck_tables_of)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | #[rustc_then_this_would_need(typeck)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: OK --> $DIR/dep-graph-struct-signature.rs:39:5 @@ -37,8 +37,8 @@ LL | #[rustc_then_this_would_need(fn_sig)] error: OK --> $DIR/dep-graph-struct-signature.rs:40:5 | -LL | #[rustc_then_this_would_need(typeck_tables_of)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | #[rustc_then_this_would_need(typeck)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: OK --> $DIR/dep-graph-struct-signature.rs:45:5 @@ -88,11 +88,11 @@ error: no path from `WillChange` to `fn_sig` LL | #[rustc_then_this_would_need(fn_sig)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error: no path from `WillChange` to `typeck_tables_of` +error: no path from `WillChange` to `typeck` --> $DIR/dep-graph-struct-signature.rs:84:5 | -LL | #[rustc_then_this_would_need(typeck_tables_of)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | #[rustc_then_this_would_need(typeck)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: OK --> $DIR/dep-graph-struct-signature.rs:31:9 @@ -115,8 +115,8 @@ LL | #[rustc_then_this_would_need(fn_sig)] error: OK --> $DIR/dep-graph-struct-signature.rs:48:9 | -LL | #[rustc_then_this_would_need(typeck_tables_of)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | #[rustc_then_this_would_need(typeck)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: OK --> $DIR/dep-graph-struct-signature.rs:54:9 @@ -127,8 +127,8 @@ LL | #[rustc_then_this_would_need(fn_sig)] error: OK --> $DIR/dep-graph-struct-signature.rs:55:9 | -LL | #[rustc_then_this_would_need(typeck_tables_of)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | #[rustc_then_this_would_need(typeck)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to 22 previous errors diff --git a/src/test/ui/dep-graph/dep-graph-trait-impl-two-traits-same-method.rs b/src/test/ui/dep-graph/dep-graph-trait-impl-two-traits-same-method.rs index 38622a754ddb2..1b3bf5a3933fe 100644 --- a/src/test/ui/dep-graph/dep-graph-trait-impl-two-traits-same-method.rs +++ b/src/test/ui/dep-graph/dep-graph-trait-impl-two-traits-same-method.rs @@ -29,7 +29,7 @@ mod x { mod y { use {Foo, Bar}; - #[rustc_then_this_would_need(typeck_tables_of)] //~ ERROR OK + #[rustc_then_this_would_need(typeck)] //~ ERROR OK pub fn with_char() { char::method('a'); } @@ -38,7 +38,7 @@ mod y { mod z { use y; - #[rustc_then_this_would_need(typeck_tables_of)] //~ ERROR no path + #[rustc_then_this_would_need(typeck)] //~ ERROR no path pub fn z() { y::with_char(); } diff --git a/src/test/ui/dep-graph/dep-graph-trait-impl-two-traits-same-method.stderr b/src/test/ui/dep-graph/dep-graph-trait-impl-two-traits-same-method.stderr index 3384fd7b4acf5..ae3d725e1c051 100644 --- a/src/test/ui/dep-graph/dep-graph-trait-impl-two-traits-same-method.stderr +++ b/src/test/ui/dep-graph/dep-graph-trait-impl-two-traits-same-method.stderr @@ -1,14 +1,14 @@ error: OK --> $DIR/dep-graph-trait-impl-two-traits-same-method.rs:32:5 | -LL | #[rustc_then_this_would_need(typeck_tables_of)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | #[rustc_then_this_would_need(typeck)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error: no path from `x::` to `typeck_tables_of` +error: no path from `x::` to `typeck` --> $DIR/dep-graph-trait-impl-two-traits-same-method.rs:41:5 | -LL | #[rustc_then_this_would_need(typeck_tables_of)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | #[rustc_then_this_would_need(typeck)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to 2 previous errors diff --git a/src/test/ui/dep-graph/dep-graph-trait-impl-two-traits.rs b/src/test/ui/dep-graph/dep-graph-trait-impl-two-traits.rs index 82306b6539c15..ebfe8ccc3dfaf 100644 --- a/src/test/ui/dep-graph/dep-graph-trait-impl-two-traits.rs +++ b/src/test/ui/dep-graph/dep-graph-trait-impl-two-traits.rs @@ -28,7 +28,7 @@ mod x { mod y { use {Foo, Bar}; - #[rustc_then_this_would_need(typeck_tables_of)] //~ ERROR no path + #[rustc_then_this_would_need(typeck)] //~ ERROR no path pub fn call_bar() { char::bar('a'); } @@ -37,7 +37,7 @@ mod y { mod z { use y; - #[rustc_then_this_would_need(typeck_tables_of)] //~ ERROR no path + #[rustc_then_this_would_need(typeck)] //~ ERROR no path pub fn z() { y::call_bar(); } diff --git a/src/test/ui/dep-graph/dep-graph-trait-impl-two-traits.stderr b/src/test/ui/dep-graph/dep-graph-trait-impl-two-traits.stderr index d8a1f05dcaa79..4823927477fe0 100644 --- a/src/test/ui/dep-graph/dep-graph-trait-impl-two-traits.stderr +++ b/src/test/ui/dep-graph/dep-graph-trait-impl-two-traits.stderr @@ -1,14 +1,14 @@ -error: no path from `x::` to `typeck_tables_of` +error: no path from `x::` to `typeck` --> $DIR/dep-graph-trait-impl-two-traits.rs:31:5 | -LL | #[rustc_then_this_would_need(typeck_tables_of)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | #[rustc_then_this_would_need(typeck)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error: no path from `x::` to `typeck_tables_of` +error: no path from `x::` to `typeck` --> $DIR/dep-graph-trait-impl-two-traits.rs:40:5 | -LL | #[rustc_then_this_would_need(typeck_tables_of)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | #[rustc_then_this_would_need(typeck)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to 2 previous errors diff --git a/src/test/ui/dep-graph/dep-graph-trait-impl.rs b/src/test/ui/dep-graph/dep-graph-trait-impl.rs index e4483b9f71ddb..9dd201e2a1fbc 100644 --- a/src/test/ui/dep-graph/dep-graph-trait-impl.rs +++ b/src/test/ui/dep-graph/dep-graph-trait-impl.rs @@ -24,22 +24,22 @@ mod x { mod y { use Foo; - #[rustc_then_this_would_need(typeck_tables_of)] //~ ERROR OK + #[rustc_then_this_would_need(typeck)] //~ ERROR OK pub fn with_char() { char::method('a'); } - #[rustc_then_this_would_need(typeck_tables_of)] //~ ERROR OK + #[rustc_then_this_would_need(typeck)] //~ ERROR OK pub fn take_foo_with_char() { take_foo::('a'); } - #[rustc_then_this_would_need(typeck_tables_of)] //~ ERROR OK + #[rustc_then_this_would_need(typeck)] //~ ERROR OK pub fn with_u32() { u32::method(22); } - #[rustc_then_this_would_need(typeck_tables_of)] //~ ERROR OK + #[rustc_then_this_would_need(typeck)] //~ ERROR OK pub fn take_foo_with_u32() { take_foo::(22); } @@ -52,7 +52,7 @@ mod z { // These are expected to yield errors, because changes to `x` // affect the BODY of `y`, but not its signature. - #[rustc_then_this_would_need(typeck_tables_of)] //~ ERROR no path + #[rustc_then_this_would_need(typeck)] //~ ERROR no path pub fn z() { y::with_char(); y::with_u32(); diff --git a/src/test/ui/dep-graph/dep-graph-trait-impl.stderr b/src/test/ui/dep-graph/dep-graph-trait-impl.stderr index ca9676a9478e4..f8ead80894276 100644 --- a/src/test/ui/dep-graph/dep-graph-trait-impl.stderr +++ b/src/test/ui/dep-graph/dep-graph-trait-impl.stderr @@ -1,32 +1,32 @@ error: OK --> $DIR/dep-graph-trait-impl.rs:27:5 | -LL | #[rustc_then_this_would_need(typeck_tables_of)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | #[rustc_then_this_would_need(typeck)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: OK --> $DIR/dep-graph-trait-impl.rs:32:5 | -LL | #[rustc_then_this_would_need(typeck_tables_of)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | #[rustc_then_this_would_need(typeck)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: OK --> $DIR/dep-graph-trait-impl.rs:37:5 | -LL | #[rustc_then_this_would_need(typeck_tables_of)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | #[rustc_then_this_would_need(typeck)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: OK --> $DIR/dep-graph-trait-impl.rs:42:5 | -LL | #[rustc_then_this_would_need(typeck_tables_of)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | #[rustc_then_this_would_need(typeck)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error: no path from `x::` to `typeck_tables_of` +error: no path from `x::` to `typeck` --> $DIR/dep-graph-trait-impl.rs:55:5 | -LL | #[rustc_then_this_would_need(typeck_tables_of)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | #[rustc_then_this_would_need(typeck)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to 5 previous errors diff --git a/src/test/ui/dep-graph/dep-graph-type-alias.rs b/src/test/ui/dep-graph/dep-graph-type-alias.rs index 2d4a18f2818b5..c9151ce79c5f6 100644 --- a/src/test/ui/dep-graph/dep-graph-type-alias.rs +++ b/src/test/ui/dep-graph/dep-graph-type-alias.rs @@ -41,7 +41,7 @@ struct SomeType; #[rustc_then_this_would_need(type_of)] //~ ERROR no path impl SomeType { #[rustc_then_this_would_need(fn_sig)] //~ ERROR OK - #[rustc_then_this_would_need(typeck_tables_of)] //~ ERROR OK + #[rustc_then_this_would_need(typeck)] //~ ERROR OK fn method(&self, _: TypeAlias) {} } @@ -49,7 +49,7 @@ impl SomeType { type TypeAlias2 = TypeAlias; #[rustc_then_this_would_need(fn_sig)] //~ ERROR OK -#[rustc_then_this_would_need(typeck_tables_of)] //~ ERROR OK +#[rustc_then_this_would_need(typeck)] //~ ERROR OK fn function(_: TypeAlias) { } diff --git a/src/test/ui/dep-graph/dep-graph-type-alias.stderr b/src/test/ui/dep-graph/dep-graph-type-alias.stderr index 393e4badc1608..9baaf746fc210 100644 --- a/src/test/ui/dep-graph/dep-graph-type-alias.stderr +++ b/src/test/ui/dep-graph/dep-graph-type-alias.stderr @@ -49,8 +49,8 @@ LL | #[rustc_then_this_would_need(fn_sig)] error: OK --> $DIR/dep-graph-type-alias.rs:52:1 | -LL | #[rustc_then_this_would_need(typeck_tables_of)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | #[rustc_then_this_would_need(typeck)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: OK --> $DIR/dep-graph-type-alias.rs:35:5 @@ -67,8 +67,8 @@ LL | #[rustc_then_this_would_need(fn_sig)] error: OK --> $DIR/dep-graph-type-alias.rs:44:5 | -LL | #[rustc_then_this_would_need(typeck_tables_of)] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | #[rustc_then_this_would_need(typeck)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to 12 previous errors diff --git a/src/test/ui/duplicate_entry_error.rs b/src/test/ui/duplicate_entry_error.rs index b8d98a8999b9d..776ecedea7e7e 100644 --- a/src/test/ui/duplicate_entry_error.rs +++ b/src/test/ui/duplicate_entry_error.rs @@ -1,3 +1,4 @@ +// normalize-stderr-test "loaded from .*libstd-.*.rlib" -> "loaded from SYSROOT/libstd-*.rlib" // note-pattern: first defined in crate `std`. // Test for issue #31788 and E0152 diff --git a/src/test/ui/duplicate_entry_error.stderr b/src/test/ui/duplicate_entry_error.stderr index 2d52ea3f6c20e..61cccf40ed8a5 100644 --- a/src/test/ui/duplicate_entry_error.stderr +++ b/src/test/ui/duplicate_entry_error.stderr @@ -1,5 +1,5 @@ error[E0152]: found duplicate lang item `panic_impl` - --> $DIR/duplicate_entry_error.rs:10:1 + --> $DIR/duplicate_entry_error.rs:11:1 | LL | / fn panic_impl(info: &PanicInfo) -> ! { LL | | @@ -8,6 +8,8 @@ LL | | } | |_^ | = note: the lang item is first defined in crate `std` (which `duplicate_entry_error` depends on) + = note: first definition in `std` loaded from SYSROOT/libstd-*.rlib + = note: second definition in the local crate (`duplicate_entry_error`) error: aborting due to previous error diff --git a/src/test/ui/error-codes/E0152.rs b/src/test/ui/error-codes/E0152.rs index 94467b9bddeb0..d716ca1a14fdf 100644 --- a/src/test/ui/error-codes/E0152.rs +++ b/src/test/ui/error-codes/E0152.rs @@ -1,3 +1,4 @@ +// normalize-stderr-test "loaded from .*liballoc-.*.rlib" -> "loaded from SYSROOT/liballoc-*.rlib" #![feature(lang_items)] #[lang = "owned_box"] diff --git a/src/test/ui/error-codes/E0152.stderr b/src/test/ui/error-codes/E0152.stderr index fbaa276ce1093..7445c2880af1c 100644 --- a/src/test/ui/error-codes/E0152.stderr +++ b/src/test/ui/error-codes/E0152.stderr @@ -1,10 +1,12 @@ error[E0152]: found duplicate lang item `owned_box` - --> $DIR/E0152.rs:4:1 + --> $DIR/E0152.rs:5:1 | LL | struct Foo; | ^^^^^^^^^^^ | = note: the lang item is first defined in crate `alloc` (which `std` depends on) + = note: first definition in `alloc` loaded from SYSROOT/liballoc-*.rlib + = note: second definition in the local crate (`E0152`) error: aborting due to previous error diff --git a/src/test/ui/lint/lint-nonstandard-style-unicode-1.rs b/src/test/ui/lint/lint-nonstandard-style-unicode-1.rs new file mode 100644 index 0000000000000..4f90bd98c63e5 --- /dev/null +++ b/src/test/ui/lint/lint-nonstandard-style-unicode-1.rs @@ -0,0 +1,50 @@ +#![allow(dead_code)] + +#![forbid(non_camel_case_types)] +#![feature(non_ascii_idents)] + +// Some scripts (e.g., hiragana) don't have a concept of +// upper/lowercase + +// 1. non_camel_case_types + +// Can start with non-lowercase letter +struct Θχ; +struct ヒa; + +struct χa; +//~^ ERROR type `χa` should have an upper camel case name + +// If there's already leading or trailing underscores, they get trimmed before checking. +// This is fine: +struct _ヒb; + +// This is not: +struct __χa; +//~^ ERROR type `__χa` should have an upper camel case name + +// Besides this, we cannot have two continous underscores in the middle. + +struct 对__否; +//~^ ERROR type `对__否` should have an upper camel case name + +struct ヒ__χ; +//~^ ERROR type `ヒ__χ` should have an upper camel case name + +// also cannot have lowercase letter next to a underscore. +// so this triggers the lint: + +struct Hello_你好; +//~^ ERROR type `Hello_你好` should have an upper camel case name + +struct Hello_World; +//~^ ERROR type `Hello_World` should have an upper camel case name + +struct 你_ӟ; +//~^ ERROR type `你_ӟ` should have an upper camel case name + +// and this is ok: + +struct 你_好; + +fn main() {} diff --git a/src/test/ui/lint/lint-nonstandard-style-unicode-1.stderr b/src/test/ui/lint/lint-nonstandard-style-unicode-1.stderr new file mode 100644 index 0000000000000..371002656591c --- /dev/null +++ b/src/test/ui/lint/lint-nonstandard-style-unicode-1.stderr @@ -0,0 +1,50 @@ +error: type `χa` should have an upper camel case name + --> $DIR/lint-nonstandard-style-unicode-1.rs:15:8 + | +LL | struct χa; + | ^^ help: convert the identifier to upper camel case: `Χa` + | +note: the lint level is defined here + --> $DIR/lint-nonstandard-style-unicode-1.rs:3:11 + | +LL | #![forbid(non_camel_case_types)] + | ^^^^^^^^^^^^^^^^^^^^ + +error: type `__χa` should have an upper camel case name + --> $DIR/lint-nonstandard-style-unicode-1.rs:23:8 + | +LL | struct __χa; + | ^^^^ help: convert the identifier to upper camel case: `Χa` + +error: type `对__否` should have an upper camel case name + --> $DIR/lint-nonstandard-style-unicode-1.rs:28:8 + | +LL | struct 对__否; + | ^^^^^^ help: convert the identifier to upper camel case: `对_否` + +error: type `ヒ__χ` should have an upper camel case name + --> $DIR/lint-nonstandard-style-unicode-1.rs:31:8 + | +LL | struct ヒ__χ; + | ^^^^^ help: convert the identifier to upper camel case: `ヒΧ` + +error: type `Hello_你好` should have an upper camel case name + --> $DIR/lint-nonstandard-style-unicode-1.rs:37:8 + | +LL | struct Hello_你好; + | ^^^^^^^^^^ help: convert the identifier to upper camel case: `Hello你好` + +error: type `Hello_World` should have an upper camel case name + --> $DIR/lint-nonstandard-style-unicode-1.rs:40:8 + | +LL | struct Hello_World; + | ^^^^^^^^^^^ help: convert the identifier to upper camel case: `HelloWorld` + +error: type `你_ӟ` should have an upper camel case name + --> $DIR/lint-nonstandard-style-unicode-1.rs:43:8 + | +LL | struct 你_ӟ; + | ^^^^ help: convert the identifier to upper camel case: `你Ӟ` + +error: aborting due to 7 previous errors + diff --git a/src/test/ui/lint/lint-nonstandard-style-unicode-2.rs b/src/test/ui/lint/lint-nonstandard-style-unicode-2.rs new file mode 100644 index 0000000000000..813e0ea5c5708 --- /dev/null +++ b/src/test/ui/lint/lint-nonstandard-style-unicode-2.rs @@ -0,0 +1,30 @@ +#![allow(dead_code)] + +#![forbid(non_snake_case)] +#![feature(non_ascii_idents)] + +// Some scripts (e.g., hiragana) don't have a concept of +// upper/lowercase + +// 2. non_snake_case + +// Can only use non-uppercase letters. +// So this works: + +fn 编程() {} + +// but this doesn't: + +fn Ц() {} +//~^ ERROR function `Ц` should have a snake case name + +// besides this, you cannot use continous underscores in the middle + +fn 分__隔() {} +//~^ ERROR function `分__隔` should have a snake case name + +// but you can use them both at the beginning and at the end. + +fn _______不_连_续_的_存_在_______() {} + +fn main() {} diff --git a/src/test/ui/lint/lint-nonstandard-style-unicode-2.stderr b/src/test/ui/lint/lint-nonstandard-style-unicode-2.stderr new file mode 100644 index 0000000000000..0b309e315a411 --- /dev/null +++ b/src/test/ui/lint/lint-nonstandard-style-unicode-2.stderr @@ -0,0 +1,20 @@ +error: function `Ц` should have a snake case name + --> $DIR/lint-nonstandard-style-unicode-2.rs:18:4 + | +LL | fn Ц() {} + | ^ help: convert the identifier to snake case: `ц` + | +note: the lint level is defined here + --> $DIR/lint-nonstandard-style-unicode-2.rs:3:11 + | +LL | #![forbid(non_snake_case)] + | ^^^^^^^^^^^^^^ + +error: function `分__隔` should have a snake case name + --> $DIR/lint-nonstandard-style-unicode-2.rs:23:4 + | +LL | fn 分__隔() {} + | ^^^^^^ help: convert the identifier to snake case: `分_隔` + +error: aborting due to 2 previous errors + diff --git a/src/test/ui/lint/lint-nonstandard-style-unicode-3.rs b/src/test/ui/lint/lint-nonstandard-style-unicode-3.rs new file mode 100644 index 0000000000000..b17c2de39a0c0 --- /dev/null +++ b/src/test/ui/lint/lint-nonstandard-style-unicode-3.rs @@ -0,0 +1,25 @@ +#![allow(dead_code)] + +#![forbid(non_upper_case_globals)] +#![feature(non_ascii_idents)] + +// Some scripts (e.g., hiragana) don't have a concept of +// upper/lowercase + +// 3. non_upper_case_globals + +// Can only use non-lowercase letters. +// So this works: + +static ラ: usize = 0; + +// but this doesn't: + +static τεχ: f32 = 3.14159265; +//~^ ERROR static variable `τεχ` should have an upper case name + +// This has no limit at all on underscore usages. + +static __密__封__线__内__禁__止__答__题__: bool = true; + +fn main() {} diff --git a/src/test/ui/lint/lint-nonstandard-style-unicode-3.stderr b/src/test/ui/lint/lint-nonstandard-style-unicode-3.stderr new file mode 100644 index 0000000000000..44bd5ad55ff5c --- /dev/null +++ b/src/test/ui/lint/lint-nonstandard-style-unicode-3.stderr @@ -0,0 +1,14 @@ +error: static variable `τεχ` should have an upper case name + --> $DIR/lint-nonstandard-style-unicode-3.rs:18:8 + | +LL | static τεχ: f32 = 3.14159265; + | ^^^ help: convert the identifier to upper case: `ΤΕΧ` + | +note: the lint level is defined here + --> $DIR/lint-nonstandard-style-unicode-3.rs:3:11 + | +LL | #![forbid(non_upper_case_globals)] + | ^^^^^^^^^^^^^^^^^^^^^^ + +error: aborting due to previous error + diff --git a/src/test/ui/lint/lint-nonstandard-style-unicode.rs b/src/test/ui/lint/lint-nonstandard-style-unicode.rs deleted file mode 100644 index 9f16cb20fb32c..0000000000000 --- a/src/test/ui/lint/lint-nonstandard-style-unicode.rs +++ /dev/null @@ -1,16 +0,0 @@ -// check-pass - -#![allow(dead_code)] - -#![forbid(non_camel_case_types)] -#![forbid(non_upper_case_globals)] -#![feature(non_ascii_idents)] - -// Some scripts (e.g., hiragana) don't have a concept of -// upper/lowercase - -struct ヒ; - -static ラ: usize = 0; - -pub fn main() {} diff --git a/src/test/ui/macros/doc-comment.rs b/src/test/ui/macros/doc-comment.rs new file mode 100644 index 0000000000000..9de39e9b56c98 --- /dev/null +++ b/src/test/ui/macros/doc-comment.rs @@ -0,0 +1,25 @@ +// check-pass +// Tests that we properly handle a nested macro expansion +// involving a `#[doc]` attribute +#![deny(missing_docs)] +//! Crate docs + +macro_rules! doc_comment { + ($x:expr, $($tt:tt)*) => { + #[doc = $x] + $($tt)* + } +} + +macro_rules! make_comment { + () => { + doc_comment!("Function docs", + pub fn bar() {} + ); + } +} + + +make_comment!(); + +fn main() {} diff --git a/src/test/ui/mir-dataflow/def-inits-1.rs b/src/test/ui/mir-dataflow/def-inits-1.rs index 91d41e9b5794e..30460824a1678 100644 --- a/src/test/ui/mir-dataflow/def-inits-1.rs +++ b/src/test/ui/mir-dataflow/def-inits-1.rs @@ -11,13 +11,13 @@ struct S(i32); fn foo(test: bool, x: &mut S, y: S, mut z: S) -> S { let ret; // `ret` starts off uninitialized - unsafe { rustc_peek(&ret); } //~ ERROR rustc_peek: bit not set + rustc_peek(&ret); //~ ERROR rustc_peek: bit not set // All function formal parameters start off initialized. - unsafe { rustc_peek(&x) }; - unsafe { rustc_peek(&y) }; - unsafe { rustc_peek(&z) }; + rustc_peek(&x); + rustc_peek(&y); + rustc_peek(&z); ret = if test { ::std::mem::replace(x, y) @@ -27,21 +27,21 @@ fn foo(test: bool, x: &mut S, y: S, mut z: S) -> S { }; // `z` may be uninitialized here. - unsafe { rustc_peek(&z); } //~ ERROR rustc_peek: bit not set + rustc_peek(&z); //~ ERROR rustc_peek: bit not set // `y` is definitely uninitialized here. - unsafe { rustc_peek(&y); } //~ ERROR rustc_peek: bit not set + rustc_peek(&y); //~ ERROR rustc_peek: bit not set // `x` is still (definitely) initialized (replace above is a reborrow). - unsafe { rustc_peek(&x); } + rustc_peek(&x); ::std::mem::drop(x); // `x` is *definitely* uninitialized here - unsafe { rustc_peek(&x); } //~ ERROR rustc_peek: bit not set + rustc_peek(&x); //~ ERROR rustc_peek: bit not set // `ret` is now definitely initialized (via `if` above). - unsafe { rustc_peek(&ret); } + rustc_peek(&ret); ret } diff --git a/src/test/ui/mir-dataflow/def-inits-1.stderr b/src/test/ui/mir-dataflow/def-inits-1.stderr index 48d8450489488..e2bddb54d9ba8 100644 --- a/src/test/ui/mir-dataflow/def-inits-1.stderr +++ b/src/test/ui/mir-dataflow/def-inits-1.stderr @@ -1,26 +1,26 @@ error: rustc_peek: bit not set - --> $DIR/def-inits-1.rs:14:14 + --> $DIR/def-inits-1.rs:14:5 | -LL | unsafe { rustc_peek(&ret); } - | ^^^^^^^^^^^^^^^^ +LL | rustc_peek(&ret); + | ^^^^^^^^^^^^^^^^ error: rustc_peek: bit not set - --> $DIR/def-inits-1.rs:30:14 + --> $DIR/def-inits-1.rs:30:5 | -LL | unsafe { rustc_peek(&z); } - | ^^^^^^^^^^^^^^ +LL | rustc_peek(&z); + | ^^^^^^^^^^^^^^ error: rustc_peek: bit not set - --> $DIR/def-inits-1.rs:33:14 + --> $DIR/def-inits-1.rs:33:5 | -LL | unsafe { rustc_peek(&y); } - | ^^^^^^^^^^^^^^ +LL | rustc_peek(&y); + | ^^^^^^^^^^^^^^ error: rustc_peek: bit not set - --> $DIR/def-inits-1.rs:41:14 + --> $DIR/def-inits-1.rs:41:5 | -LL | unsafe { rustc_peek(&x); } - | ^^^^^^^^^^^^^^ +LL | rustc_peek(&x); + | ^^^^^^^^^^^^^^ error: stop_after_dataflow ended compilation diff --git a/src/test/ui/mir-dataflow/indirect-mutation-offset.rs b/src/test/ui/mir-dataflow/indirect-mutation-offset.rs index caa307e269fe7..374a9f75a134b 100644 --- a/src/test/ui/mir-dataflow/indirect-mutation-offset.rs +++ b/src/test/ui/mir-dataflow/indirect-mutation-offset.rs @@ -38,7 +38,7 @@ const BOO: i32 = { *rmut_cell = 42; // Mutates `x` indirectly even though `x` is not marked indirectly mutable!!! let val = *rmut_cell; - unsafe { rustc_peek(x) }; //~ ERROR rustc_peek: bit not set + rustc_peek(x); //~ ERROR rustc_peek: bit not set val }; diff --git a/src/test/ui/mir-dataflow/indirect-mutation-offset.stderr b/src/test/ui/mir-dataflow/indirect-mutation-offset.stderr index 8d3548ececdd9..1d5287c15ab79 100644 --- a/src/test/ui/mir-dataflow/indirect-mutation-offset.stderr +++ b/src/test/ui/mir-dataflow/indirect-mutation-offset.stderr @@ -1,8 +1,8 @@ error: rustc_peek: bit not set - --> $DIR/indirect-mutation-offset.rs:41:14 + --> $DIR/indirect-mutation-offset.rs:41:5 | -LL | unsafe { rustc_peek(x) }; - | ^^^^^^^^^^^^^ +LL | rustc_peek(x); + | ^^^^^^^^^^^^^ error: stop_after_dataflow ended compilation diff --git a/src/test/ui/mir-dataflow/inits-1.rs b/src/test/ui/mir-dataflow/inits-1.rs index 4a4786a2a7378..8fb1d4bc736d6 100644 --- a/src/test/ui/mir-dataflow/inits-1.rs +++ b/src/test/ui/mir-dataflow/inits-1.rs @@ -11,13 +11,13 @@ struct S(i32); fn foo(test: bool, x: &mut S, y: S, mut z: S) -> S { let ret; // `ret` starts off uninitialized, so we get an error report here. - unsafe { rustc_peek(&ret); } //~ ERROR rustc_peek: bit not set + rustc_peek(&ret); //~ ERROR rustc_peek: bit not set // All function formal parameters start off initialized. - unsafe { rustc_peek(&x) }; - unsafe { rustc_peek(&y) }; - unsafe { rustc_peek(&z) }; + rustc_peek(&x); + rustc_peek(&y); + rustc_peek(&z); ret = if test { ::std::mem::replace(x, y) @@ -28,21 +28,21 @@ fn foo(test: bool, x: &mut S, y: S, mut z: S) -> S { // `z` may be initialized here. - unsafe { rustc_peek(&z); } + rustc_peek(&z); // `y` is definitely uninitialized here. - unsafe { rustc_peek(&y); } //~ ERROR rustc_peek: bit not set + rustc_peek(&y); //~ ERROR rustc_peek: bit not set // `x` is still (definitely) initialized (replace above is a reborrow). - unsafe { rustc_peek(&x); } + rustc_peek(&x); ::std::mem::drop(x); // `x` is *definitely* uninitialized here - unsafe { rustc_peek(&x); } //~ ERROR rustc_peek: bit not set + rustc_peek(&x); //~ ERROR rustc_peek: bit not set // `ret` is now definitely initialized (via `if` above). - unsafe { rustc_peek(&ret); } + rustc_peek(&ret); ret } diff --git a/src/test/ui/mir-dataflow/inits-1.stderr b/src/test/ui/mir-dataflow/inits-1.stderr index 23d0679cb1ac1..7a00a70af6f84 100644 --- a/src/test/ui/mir-dataflow/inits-1.stderr +++ b/src/test/ui/mir-dataflow/inits-1.stderr @@ -1,20 +1,20 @@ error: rustc_peek: bit not set - --> $DIR/inits-1.rs:14:14 + --> $DIR/inits-1.rs:14:5 | -LL | unsafe { rustc_peek(&ret); } - | ^^^^^^^^^^^^^^^^ +LL | rustc_peek(&ret); + | ^^^^^^^^^^^^^^^^ error: rustc_peek: bit not set - --> $DIR/inits-1.rs:34:14 + --> $DIR/inits-1.rs:34:5 | -LL | unsafe { rustc_peek(&y); } - | ^^^^^^^^^^^^^^ +LL | rustc_peek(&y); + | ^^^^^^^^^^^^^^ error: rustc_peek: bit not set - --> $DIR/inits-1.rs:42:14 + --> $DIR/inits-1.rs:42:5 | -LL | unsafe { rustc_peek(&x); } - | ^^^^^^^^^^^^^^ +LL | rustc_peek(&x); + | ^^^^^^^^^^^^^^ error: stop_after_dataflow ended compilation diff --git a/src/test/ui/mir-dataflow/liveness-ptr.rs b/src/test/ui/mir-dataflow/liveness-ptr.rs index 34097d7526a6e..786da523a3391 100644 --- a/src/test/ui/mir-dataflow/liveness-ptr.rs +++ b/src/test/ui/mir-dataflow/liveness-ptr.rs @@ -10,17 +10,17 @@ fn foo() -> i32 { x = 0; // `x` is live here since it is used in the next statement... - unsafe { rustc_peek(x); } + rustc_peek(x); p = &x; // ... but not here, even while it can be accessed through `p`. - unsafe { rustc_peek(x); } //~ ERROR rustc_peek: bit not set + rustc_peek(x); //~ ERROR rustc_peek: bit not set let tmp = unsafe { *p }; x = tmp + 1; - unsafe { rustc_peek(x); } + rustc_peek(x); x } diff --git a/src/test/ui/mir-dataflow/liveness-ptr.stderr b/src/test/ui/mir-dataflow/liveness-ptr.stderr index 3397d0c5a121d..858cdbac3d312 100644 --- a/src/test/ui/mir-dataflow/liveness-ptr.stderr +++ b/src/test/ui/mir-dataflow/liveness-ptr.stderr @@ -1,8 +1,8 @@ error: rustc_peek: bit not set - --> $DIR/liveness-ptr.rs:18:14 + --> $DIR/liveness-ptr.rs:18:5 | -LL | unsafe { rustc_peek(x); } - | ^^^^^^^^^^^^^ +LL | rustc_peek(x); + | ^^^^^^^^^^^^^ error: stop_after_dataflow ended compilation diff --git a/src/test/ui/mir-dataflow/uninits-1.rs b/src/test/ui/mir-dataflow/uninits-1.rs index 66b3f458a5159..c2b4284a7b4f8 100644 --- a/src/test/ui/mir-dataflow/uninits-1.rs +++ b/src/test/ui/mir-dataflow/uninits-1.rs @@ -11,13 +11,13 @@ struct S(i32); fn foo(test: bool, x: &mut S, y: S, mut z: S) -> S { let ret; // `ret` starts off uninitialized - unsafe { rustc_peek(&ret); } + rustc_peek(&ret); // All function formal parameters start off initialized. - unsafe { rustc_peek(&x) }; //~ ERROR rustc_peek: bit not set - unsafe { rustc_peek(&y) }; //~ ERROR rustc_peek: bit not set - unsafe { rustc_peek(&z) }; //~ ERROR rustc_peek: bit not set + rustc_peek(&x); //~ ERROR rustc_peek: bit not set + rustc_peek(&y); //~ ERROR rustc_peek: bit not set + rustc_peek(&z); //~ ERROR rustc_peek: bit not set ret = if test { ::std::mem::replace(x, y) @@ -27,21 +27,21 @@ fn foo(test: bool, x: &mut S, y: S, mut z: S) -> S { }; // `z` may be uninitialized here. - unsafe { rustc_peek(&z); } + rustc_peek(&z); // `y` is definitely uninitialized here. - unsafe { rustc_peek(&y); } + rustc_peek(&y); // `x` is still (definitely) initialized (replace above is a reborrow). - unsafe { rustc_peek(&x); } //~ ERROR rustc_peek: bit not set + rustc_peek(&x); //~ ERROR rustc_peek: bit not set ::std::mem::drop(x); // `x` is *definitely* uninitialized here - unsafe { rustc_peek(&x); } + rustc_peek(&x); // `ret` is now definitely initialized (via `if` above). - unsafe { rustc_peek(&ret); } //~ ERROR rustc_peek: bit not set + rustc_peek(&ret); //~ ERROR rustc_peek: bit not set ret } diff --git a/src/test/ui/mir-dataflow/uninits-1.stderr b/src/test/ui/mir-dataflow/uninits-1.stderr index 5f6dbde212d0a..c52f5ac7bd9b6 100644 --- a/src/test/ui/mir-dataflow/uninits-1.stderr +++ b/src/test/ui/mir-dataflow/uninits-1.stderr @@ -1,32 +1,32 @@ error: rustc_peek: bit not set - --> $DIR/uninits-1.rs:18:14 + --> $DIR/uninits-1.rs:18:5 | -LL | unsafe { rustc_peek(&x) }; - | ^^^^^^^^^^^^^^ +LL | rustc_peek(&x); + | ^^^^^^^^^^^^^^ error: rustc_peek: bit not set - --> $DIR/uninits-1.rs:19:14 + --> $DIR/uninits-1.rs:19:5 | -LL | unsafe { rustc_peek(&y) }; - | ^^^^^^^^^^^^^^ +LL | rustc_peek(&y); + | ^^^^^^^^^^^^^^ error: rustc_peek: bit not set - --> $DIR/uninits-1.rs:20:14 + --> $DIR/uninits-1.rs:20:5 | -LL | unsafe { rustc_peek(&z) }; - | ^^^^^^^^^^^^^^ +LL | rustc_peek(&z); + | ^^^^^^^^^^^^^^ error: rustc_peek: bit not set - --> $DIR/uninits-1.rs:36:14 + --> $DIR/uninits-1.rs:36:5 | -LL | unsafe { rustc_peek(&x); } - | ^^^^^^^^^^^^^^ +LL | rustc_peek(&x); + | ^^^^^^^^^^^^^^ error: rustc_peek: bit not set - --> $DIR/uninits-1.rs:44:14 + --> $DIR/uninits-1.rs:44:5 | -LL | unsafe { rustc_peek(&ret); } - | ^^^^^^^^^^^^^^^^ +LL | rustc_peek(&ret); + | ^^^^^^^^^^^^^^^^ error: stop_after_dataflow ended compilation diff --git a/src/test/ui/mir-dataflow/uninits-2.rs b/src/test/ui/mir-dataflow/uninits-2.rs index 2ccf1c7f9d6c6..c584ee74afb48 100644 --- a/src/test/ui/mir-dataflow/uninits-2.rs +++ b/src/test/ui/mir-dataflow/uninits-2.rs @@ -11,12 +11,12 @@ struct S(i32); fn foo(x: &mut S) { // `x` is initialized here, so maybe-uninit bit is 0. - unsafe { rustc_peek(&x) }; //~ ERROR rustc_peek: bit not set + rustc_peek(&x); //~ ERROR rustc_peek: bit not set ::std::mem::drop(x); // `x` definitely uninitialized here, so maybe-uninit bit is 1. - unsafe { rustc_peek(&x) }; + rustc_peek(&x); } fn main() { foo(&mut S(13)); diff --git a/src/test/ui/mir-dataflow/uninits-2.stderr b/src/test/ui/mir-dataflow/uninits-2.stderr index dcb61371994db..0ef954e35a4d8 100644 --- a/src/test/ui/mir-dataflow/uninits-2.stderr +++ b/src/test/ui/mir-dataflow/uninits-2.stderr @@ -1,8 +1,8 @@ error: rustc_peek: bit not set - --> $DIR/uninits-2.rs:14:14 + --> $DIR/uninits-2.rs:14:5 | -LL | unsafe { rustc_peek(&x) }; - | ^^^^^^^^^^^^^^ +LL | rustc_peek(&x); + | ^^^^^^^^^^^^^^ error: stop_after_dataflow ended compilation diff --git a/src/test/ui/panic-handler/panic-handler-std.rs b/src/test/ui/panic-handler/panic-handler-std.rs index 0acc2722cb21f..6183c886cfac7 100644 --- a/src/test/ui/panic-handler/panic-handler-std.rs +++ b/src/test/ui/panic-handler/panic-handler-std.rs @@ -1,3 +1,4 @@ +// normalize-stderr-test "loaded from .*libstd-.*.rlib" -> "loaded from SYSROOT/libstd-*.rlib" // error-pattern: found duplicate lang item `panic_impl` diff --git a/src/test/ui/panic-handler/panic-handler-std.stderr b/src/test/ui/panic-handler/panic-handler-std.stderr index f71c28e5aa641..bb656089bcaff 100644 --- a/src/test/ui/panic-handler/panic-handler-std.stderr +++ b/src/test/ui/panic-handler/panic-handler-std.stderr @@ -1,5 +1,5 @@ error[E0152]: found duplicate lang item `panic_impl` - --> $DIR/panic-handler-std.rs:7:1 + --> $DIR/panic-handler-std.rs:8:1 | LL | / fn panic(info: PanicInfo) -> ! { LL | | loop {} @@ -7,9 +7,11 @@ LL | | } | |_^ | = note: the lang item is first defined in crate `std` (which `panic_handler_std` depends on) + = note: first definition in `std` loaded from SYSROOT/libstd-*.rlib + = note: second definition in the local crate (`panic_handler_std`) error: argument should be `&PanicInfo` - --> $DIR/panic-handler-std.rs:7:16 + --> $DIR/panic-handler-std.rs:8:16 | LL | fn panic(info: PanicInfo) -> ! { | ^^^^^^^^^ diff --git a/src/test/ui/parser/recover-field-extra-angle-brackets.rs b/src/test/ui/parser/recover-field-extra-angle-brackets.rs new file mode 100644 index 0000000000000..5e0e00bcb5e8d --- /dev/null +++ b/src/test/ui/parser/recover-field-extra-angle-brackets.rs @@ -0,0 +1,14 @@ +// Tests that we recover from extra trailing angle brackets +// in a struct field + +struct BadStruct { + first: Vec>, //~ ERROR unmatched angle bracket + second: bool +} + +fn bar(val: BadStruct) { + val.first; + val.second; +} + +fn main() {} diff --git a/src/test/ui/parser/recover-field-extra-angle-brackets.stderr b/src/test/ui/parser/recover-field-extra-angle-brackets.stderr new file mode 100644 index 0000000000000..318e55f6e99ac --- /dev/null +++ b/src/test/ui/parser/recover-field-extra-angle-brackets.stderr @@ -0,0 +1,8 @@ +error: unmatched angle bracket + --> $DIR/recover-field-extra-angle-brackets.rs:5:19 + | +LL | first: Vec>, + | ^ help: remove extra angle bracket + +error: aborting due to previous error + diff --git a/src/test/ui/proc-macro/auxiliary/attr-cfg.rs b/src/test/ui/proc-macro/auxiliary/attr-cfg.rs index f50e18d7be30e..2f0054cc14aa6 100644 --- a/src/test/ui/proc-macro/auxiliary/attr-cfg.rs +++ b/src/test/ui/proc-macro/auxiliary/attr-cfg.rs @@ -11,11 +11,9 @@ use proc_macro::TokenStream; pub fn attr_cfg(args: TokenStream, input: TokenStream) -> TokenStream { let input_str = input.to_string(); - assert_eq!(input_str, "fn outer() -> u8 { - #[cfg(foo)] - fn inner() -> u8 { 1 } - #[cfg(bar)] - fn inner() -> u8 { 2 } + assert_eq!(input_str, "fn outer() -> u8 +{ + #[cfg(foo)] fn inner() -> u8 { 1 } #[cfg(bar)] fn inner() -> u8 { 2 } inner() }"); diff --git a/src/test/ui/proc-macro/auxiliary/attr-stmt-expr-rpass.rs b/src/test/ui/proc-macro/auxiliary/attr-stmt-expr-rpass.rs index f1de3709b166b..e056bd32d2d0e 100644 --- a/src/test/ui/proc-macro/auxiliary/attr-stmt-expr-rpass.rs +++ b/src/test/ui/proc-macro/auxiliary/attr-stmt-expr-rpass.rs @@ -10,14 +10,14 @@ use proc_macro::TokenStream; #[proc_macro_attribute] pub fn expect_let(attr: TokenStream, item: TokenStream) -> TokenStream { assert!(attr.to_string().is_empty()); - assert_eq!(item.to_string(), "let string = \"Hello, world!\";"); + assert_eq!(item.to_string(), "let string = \"Hello, world!\" ;"); item } #[proc_macro_attribute] pub fn expect_print_stmt(attr: TokenStream, item: TokenStream) -> TokenStream { assert!(attr.to_string().is_empty()); - assert_eq!(item.to_string(), "println!(\"{}\", string);"); + assert_eq!(item.to_string(), "println ! (\"{}\", string) ;"); item } @@ -31,7 +31,7 @@ pub fn expect_expr(attr: TokenStream, item: TokenStream) -> TokenStream { #[proc_macro_attribute] pub fn expect_print_expr(attr: TokenStream, item: TokenStream) -> TokenStream { assert!(attr.to_string().is_empty()); - assert_eq!(item.to_string(), "println!(\"{}\", string)"); + assert_eq!(item.to_string(), "println ! (\"{}\", string)"); item } diff --git a/src/test/ui/proc-macro/auxiliary/attr-stmt-expr.rs b/src/test/ui/proc-macro/auxiliary/attr-stmt-expr.rs index d2180def5b760..213f999e9d0ea 100644 --- a/src/test/ui/proc-macro/auxiliary/attr-stmt-expr.rs +++ b/src/test/ui/proc-macro/auxiliary/attr-stmt-expr.rs @@ -10,14 +10,14 @@ use proc_macro::TokenStream; #[proc_macro_attribute] pub fn expect_let(attr: TokenStream, item: TokenStream) -> TokenStream { assert!(attr.to_string().is_empty()); - assert_eq!(item.to_string(), "let string = \"Hello, world!\";"); + assert_eq!(item.to_string(), "let string = \"Hello, world!\" ;"); item } #[proc_macro_attribute] pub fn expect_print_stmt(attr: TokenStream, item: TokenStream) -> TokenStream { assert!(attr.to_string().is_empty()); - assert_eq!(item.to_string(), "println!(\"{}\", string);"); + assert_eq!(item.to_string(), "println ! (\"{}\", string) ;"); item } @@ -31,7 +31,7 @@ pub fn expect_expr(attr: TokenStream, item: TokenStream) -> TokenStream { #[proc_macro_attribute] pub fn expect_print_expr(attr: TokenStream, item: TokenStream) -> TokenStream { assert!(attr.to_string().is_empty()); - assert_eq!(item.to_string(), "println!(\"{}\", string)"); + assert_eq!(item.to_string(), "println ! (\"{}\", string)"); item } diff --git a/src/test/ui/proc-macro/auxiliary/derive-a.rs b/src/test/ui/proc-macro/auxiliary/derive-a.rs index cd2be5fd84d44..79a3864bf991d 100644 --- a/src/test/ui/proc-macro/auxiliary/derive-a.rs +++ b/src/test/ui/proc-macro/auxiliary/derive-a.rs @@ -10,6 +10,6 @@ use proc_macro::TokenStream; #[proc_macro_derive(A)] pub fn derive(input: TokenStream) -> TokenStream { let input = input.to_string(); - assert!(input.contains("struct A;")); + assert!(input.contains("struct A ;")); "".parse().unwrap() } diff --git a/src/test/ui/proc-macro/auxiliary/derive-atob.rs b/src/test/ui/proc-macro/auxiliary/derive-atob.rs index e78e5bb8f4c75..207b7fd320360 100644 --- a/src/test/ui/proc-macro/auxiliary/derive-atob.rs +++ b/src/test/ui/proc-macro/auxiliary/derive-atob.rs @@ -10,6 +10,6 @@ use proc_macro::TokenStream; #[proc_macro_derive(AToB)] pub fn derive(input: TokenStream) -> TokenStream { let input = input.to_string(); - assert_eq!(input, "struct A;"); + assert_eq!(input, "struct A ;"); "struct B;".parse().unwrap() } diff --git a/src/test/ui/proc-macro/auxiliary/derive-b-rpass.rs b/src/test/ui/proc-macro/auxiliary/derive-b-rpass.rs index 3e6af67a9f412..641a95f78c112 100644 --- a/src/test/ui/proc-macro/auxiliary/derive-b-rpass.rs +++ b/src/test/ui/proc-macro/auxiliary/derive-b-rpass.rs @@ -10,7 +10,7 @@ use proc_macro::TokenStream; #[proc_macro_derive(B, attributes(B, C))] pub fn derive(input: TokenStream) -> TokenStream { let input = input.to_string(); - assert!(input.contains("#[B[arbitrary tokens]]")); + assert!(input.contains("#[B [arbitrary tokens]]")); assert!(input.contains("struct B {")); assert!(input.contains("#[C]")); "".parse().unwrap() diff --git a/src/test/ui/proc-macro/auxiliary/derive-ctod.rs b/src/test/ui/proc-macro/auxiliary/derive-ctod.rs index dbf44ed1b0537..2efe5a9134054 100644 --- a/src/test/ui/proc-macro/auxiliary/derive-ctod.rs +++ b/src/test/ui/proc-macro/auxiliary/derive-ctod.rs @@ -10,6 +10,6 @@ use proc_macro::TokenStream; #[proc_macro_derive(CToD)] pub fn derive(input: TokenStream) -> TokenStream { let input = input.to_string(); - assert_eq!(input, "struct C;"); + assert_eq!(input, "struct C ;"); "struct D;".parse().unwrap() } diff --git a/src/test/ui/proc-macro/auxiliary/derive-same-struct.rs b/src/test/ui/proc-macro/auxiliary/derive-same-struct.rs index ce7a50d2381cd..7598d632cb6d5 100644 --- a/src/test/ui/proc-macro/auxiliary/derive-same-struct.rs +++ b/src/test/ui/proc-macro/auxiliary/derive-same-struct.rs @@ -10,12 +10,12 @@ use proc_macro::TokenStream; #[proc_macro_derive(AToB)] pub fn derive1(input: TokenStream) -> TokenStream { println!("input1: {:?}", input.to_string()); - assert_eq!(input.to_string(), "struct A;"); + assert_eq!(input.to_string(), "struct A ;"); "#[derive(BToC)] struct B;".parse().unwrap() } #[proc_macro_derive(BToC)] pub fn derive2(input: TokenStream) -> TokenStream { - assert_eq!(input.to_string(), "struct B;"); + assert_eq!(input.to_string(), "struct B ;"); "struct C;".parse().unwrap() } diff --git a/src/test/ui/proc-macro/auxiliary/derive-union.rs b/src/test/ui/proc-macro/auxiliary/derive-union.rs index d950e1e773c70..05883170c6c48 100644 --- a/src/test/ui/proc-macro/auxiliary/derive-union.rs +++ b/src/test/ui/proc-macro/auxiliary/derive-union.rs @@ -12,7 +12,7 @@ pub fn derive(input: TokenStream) -> TokenStream { let input = input.to_string(); assert!(input.contains("#[repr(C)]")); assert!(input.contains("union Test {")); - assert!(input.contains("a: u8,")); + assert!(input.contains("a : u8,")); assert!(input.contains("}")); "".parse().unwrap() } diff --git a/src/test/ui/proc-macro/auxiliary/double.rs b/src/test/ui/proc-macro/auxiliary/double.rs index 3a2e8d04c36b5..99eb4e3754672 100644 --- a/src/test/ui/proc-macro/auxiliary/double.rs +++ b/src/test/ui/proc-macro/auxiliary/double.rs @@ -1,15 +1,16 @@ // force-host // no-prefer-dynamic +#![feature(proc_macro_quote)] + #![crate_type = "proc-macro"] extern crate proc_macro; - -use proc_macro::TokenStream; +use proc_macro::*; // Outputs another copy of the struct. Useful for testing the tokens // seen by the proc_macro. #[proc_macro_derive(Double)] pub fn derive(input: TokenStream) -> TokenStream { - format!("mod foo {{ {} }}", input.to_string()).parse().unwrap() + quote!(mod foo { $input }) } diff --git a/src/test/ui/proc-macro/auxiliary/expand-with-a-macro.rs b/src/test/ui/proc-macro/auxiliary/expand-with-a-macro.rs index 5155a4b855865..d779d57af14c7 100644 --- a/src/test/ui/proc-macro/auxiliary/expand-with-a-macro.rs +++ b/src/test/ui/proc-macro/auxiliary/expand-with-a-macro.rs @@ -11,7 +11,7 @@ use proc_macro::TokenStream; #[proc_macro_derive(A)] pub fn derive(input: TokenStream) -> TokenStream { let input = input.to_string(); - assert!(input.contains("struct A;")); + assert!(input.contains("struct A ;")); r#" impl A { fn a(&self) { diff --git a/src/test/ui/proc-macro/auxiliary/meta-delim.rs b/src/test/ui/proc-macro/auxiliary/meta-delim.rs new file mode 100644 index 0000000000000..54e3d7857267b --- /dev/null +++ b/src/test/ui/proc-macro/auxiliary/meta-delim.rs @@ -0,0 +1,12 @@ +macro_rules! produce_it { + ($dollar_one:tt $foo:ident $my_name:ident) => { + #[macro_export] + macro_rules! meta_delim { + ($dollar_one ($dollar_one $my_name:ident)*) => { + stringify!($dollar_one ($dollar_one $my_name)*) + } + } + } +} + +produce_it!($my_name name); diff --git a/src/test/ui/proc-macro/auxiliary/nested-macro-rules.rs b/src/test/ui/proc-macro/auxiliary/nested-macro-rules.rs new file mode 100644 index 0000000000000..52ebe8e7fb2ef --- /dev/null +++ b/src/test/ui/proc-macro/auxiliary/nested-macro-rules.rs @@ -0,0 +1,15 @@ +pub struct FirstStruct; + +#[macro_export] +macro_rules! outer_macro { + ($name:ident) => { + #[macro_export] + macro_rules! inner_macro { + ($wrapper:ident) => { + $wrapper!($name) + } + } + } +} + +outer_macro!(FirstStruct); diff --git a/src/test/ui/proc-macro/auxiliary/test-macros.rs b/src/test/ui/proc-macro/auxiliary/test-macros.rs index fb8016cd43896..8682ebdd109f0 100644 --- a/src/test/ui/proc-macro/auxiliary/test-macros.rs +++ b/src/test/ui/proc-macro/auxiliary/test-macros.rs @@ -101,6 +101,12 @@ pub fn print_bang(input: TokenStream) -> TokenStream { print_helper(input, "BANG") } +#[proc_macro] +pub fn print_bang_consume(input: TokenStream) -> TokenStream { + print_helper(input, "BANG"); + TokenStream::new() +} + #[proc_macro_attribute] pub fn print_attr(_: TokenStream, input: TokenStream) -> TokenStream { print_helper(input, "ATTR") diff --git a/src/test/ui/proc-macro/derive-same-struct.stdout b/src/test/ui/proc-macro/derive-same-struct.stdout index 77605de5e33fc..7478d9741409b 100644 --- a/src/test/ui/proc-macro/derive-same-struct.stdout +++ b/src/test/ui/proc-macro/derive-same-struct.stdout @@ -1 +1 @@ -input1: "struct A;" +input1: "struct A ;" diff --git a/src/test/ui/proc-macro/dollar-crate-issue-57089.stdout b/src/test/ui/proc-macro/dollar-crate-issue-57089.stdout index 15433bebde967..5d93144b44553 100644 --- a/src/test/ui/proc-macro/dollar-crate-issue-57089.stdout +++ b/src/test/ui/proc-macro/dollar-crate-issue-57089.stdout @@ -38,8 +38,7 @@ PRINT-BANG INPUT (DEBUG): TokenStream [ span: #3 bytes(LO..HI), }, ] -PRINT-ATTR INPUT (DISPLAY): struct A(crate::S); -PRINT-ATTR RE-COLLECTED (DISPLAY): struct A($crate :: S) ; +PRINT-ATTR INPUT (DISPLAY): struct A($crate :: S) ; PRINT-ATTR INPUT (DEBUG): TokenStream [ Ident { ident: "struct", diff --git a/src/test/ui/proc-macro/dollar-crate-issue-62325.stdout b/src/test/ui/proc-macro/dollar-crate-issue-62325.stdout index 73e407918ec8c..e4212377626ca 100644 --- a/src/test/ui/proc-macro/dollar-crate-issue-62325.stdout +++ b/src/test/ui/proc-macro/dollar-crate-issue-62325.stdout @@ -1,5 +1,4 @@ -PRINT-ATTR INPUT (DISPLAY): struct A(identity!(crate :: S)); -PRINT-ATTR RE-COLLECTED (DISPLAY): struct A(identity ! ($crate :: S)) ; +PRINT-ATTR INPUT (DISPLAY): struct A(identity ! ($crate :: S)) ; PRINT-ATTR INPUT (DEBUG): TokenStream [ Ident { ident: "struct", @@ -54,8 +53,7 @@ PRINT-ATTR INPUT (DEBUG): TokenStream [ span: #3 bytes(LO..HI), }, ] -PRINT-ATTR INPUT (DISPLAY): struct B(identity!(::dollar_crate_external :: S)); -PRINT-ATTR RE-COLLECTED (DISPLAY): struct B(identity ! ($crate :: S)) ; +PRINT-ATTR INPUT (DISPLAY): struct B(identity ! ($crate :: S)) ; PRINT-ATTR INPUT (DEBUG): TokenStream [ Ident { ident: "struct", diff --git a/src/test/ui/proc-macro/dollar-crate.stdout b/src/test/ui/proc-macro/dollar-crate.stdout index e125a3e7f1737..8a7406b1a3d13 100644 --- a/src/test/ui/proc-macro/dollar-crate.stdout +++ b/src/test/ui/proc-macro/dollar-crate.stdout @@ -38,8 +38,7 @@ PRINT-BANG INPUT (DEBUG): TokenStream [ span: #3 bytes(LO..HI), }, ] -PRINT-ATTR INPUT (DISPLAY): struct A(crate::S); -PRINT-ATTR RE-COLLECTED (DISPLAY): struct A($crate :: S) ; +PRINT-ATTR INPUT (DISPLAY): struct A($crate :: S) ; PRINT-ATTR INPUT (DEBUG): TokenStream [ Ident { ident: "struct", @@ -79,8 +78,7 @@ PRINT-ATTR INPUT (DEBUG): TokenStream [ span: #3 bytes(LO..HI), }, ] -PRINT-DERIVE INPUT (DISPLAY): struct D(crate::S); -PRINT-DERIVE RE-COLLECTED (DISPLAY): struct D($crate :: S) ; +PRINT-DERIVE INPUT (DISPLAY): struct D($crate :: S) ; PRINT-DERIVE INPUT (DEBUG): TokenStream [ Ident { ident: "struct", @@ -160,8 +158,7 @@ PRINT-BANG INPUT (DEBUG): TokenStream [ span: #13 bytes(LO..HI), }, ] -PRINT-ATTR INPUT (DISPLAY): struct A(::dollar_crate_external::S); -PRINT-ATTR RE-COLLECTED (DISPLAY): struct A($crate :: S) ; +PRINT-ATTR INPUT (DISPLAY): struct A($crate :: S) ; PRINT-ATTR INPUT (DEBUG): TokenStream [ Ident { ident: "struct", @@ -201,8 +198,7 @@ PRINT-ATTR INPUT (DEBUG): TokenStream [ span: #13 bytes(LO..HI), }, ] -PRINT-DERIVE INPUT (DISPLAY): struct D(::dollar_crate_external::S); -PRINT-DERIVE RE-COLLECTED (DISPLAY): struct D($crate :: S) ; +PRINT-DERIVE INPUT (DISPLAY): struct D($crate :: S) ; PRINT-DERIVE INPUT (DEBUG): TokenStream [ Ident { ident: "struct", diff --git a/src/test/ui/proc-macro/input-interpolated.stdout b/src/test/ui/proc-macro/input-interpolated.stdout index 7529db3bd06f8..ee988d48b461d 100644 --- a/src/test/ui/proc-macro/input-interpolated.stdout +++ b/src/test/ui/proc-macro/input-interpolated.stdout @@ -1,5 +1,4 @@ PRINT-BANG INPUT (DISPLAY): A -PRINT-BANG RE-COLLECTED (DISPLAY): A PRINT-BANG INPUT (DEBUG): TokenStream [ Group { delimiter: None, @@ -12,8 +11,7 @@ PRINT-BANG INPUT (DEBUG): TokenStream [ span: #3 bytes(269..271), }, ] -PRINT-ATTR INPUT (DISPLAY): const A: u8 = 0; -PRINT-ATTR RE-COLLECTED (DISPLAY): const A : u8 = 0 ; +PRINT-ATTR INPUT (DISPLAY): const A : u8 = 0 ; PRINT-ATTR INPUT (DEBUG): TokenStream [ Ident { ident: "const", @@ -49,9 +47,7 @@ PRINT-ATTR INPUT (DEBUG): TokenStream [ span: #0 bytes(0..0), }, ] -PRINT-DERIVE INPUT (DISPLAY): struct A { -} -PRINT-DERIVE RE-COLLECTED (DISPLAY): struct A { } +PRINT-DERIVE INPUT (DISPLAY): struct A { } PRINT-DERIVE INPUT (DEBUG): TokenStream [ Ident { ident: "struct", diff --git a/src/test/ui/proc-macro/meta-delim.rs b/src/test/ui/proc-macro/meta-delim.rs new file mode 100644 index 0000000000000..964291bc6784c --- /dev/null +++ b/src/test/ui/proc-macro/meta-delim.rs @@ -0,0 +1,12 @@ +// aux-build:meta-delim.rs +// edition:2018 +// run-pass + +// Tests that we can properly deserialize a macro with strange delimiters +// See https://github.com/rust-lang/rust/pull/73569#issuecomment-650860457 + +extern crate meta_delim; + +fn main() { + assert_eq!("a bunch of idents", meta_delim::meta_delim!(a bunch of idents)); +} diff --git a/src/test/ui/proc-macro/nested-macro-rules.rs b/src/test/ui/proc-macro/nested-macro-rules.rs new file mode 100644 index 0000000000000..2f8ef20232782 --- /dev/null +++ b/src/test/ui/proc-macro/nested-macro-rules.rs @@ -0,0 +1,20 @@ +// run-pass +// aux-build:nested-macro-rules.rs +// aux-build:test-macros.rs +// compile-flags: -Z span-debug +// edition:2018 + +extern crate nested_macro_rules; +extern crate test_macros; + +use test_macros::print_bang; + +use nested_macro_rules::FirstStruct; +struct SecondStruct; + +fn main() { + nested_macro_rules::inner_macro!(print_bang); + + nested_macro_rules::outer_macro!(SecondStruct); + inner_macro!(print_bang); +} diff --git a/src/test/ui/proc-macro/nested-macro-rules.stdout b/src/test/ui/proc-macro/nested-macro-rules.stdout new file mode 100644 index 0000000000000..e4cfe020324b8 --- /dev/null +++ b/src/test/ui/proc-macro/nested-macro-rules.stdout @@ -0,0 +1,26 @@ +PRINT-BANG INPUT (DISPLAY): FirstStruct +PRINT-BANG INPUT (DEBUG): TokenStream [ + Group { + delimiter: None, + stream: TokenStream [ + Ident { + ident: "FirstStruct", + span: $DIR/auxiliary/nested-macro-rules.rs:15:14: 15:25 (#3), + }, + ], + span: $DIR/auxiliary/nested-macro-rules.rs:9:27: 9:32 (#3), + }, +] +PRINT-BANG INPUT (DISPLAY): SecondStruct +PRINT-BANG INPUT (DEBUG): TokenStream [ + Group { + delimiter: None, + stream: TokenStream [ + Ident { + ident: "SecondStruct", + span: $DIR/nested-macro-rules.rs:18:38: 18:50 (#9), + }, + ], + span: $DIR/auxiliary/nested-macro-rules.rs:9:27: 9:32 (#8), + }, +] diff --git a/src/test/ui/proc-macro/nodelim-groups.rs b/src/test/ui/proc-macro/nodelim-groups.rs new file mode 100644 index 0000000000000..cfcd4c0d2a658 --- /dev/null +++ b/src/test/ui/proc-macro/nodelim-groups.rs @@ -0,0 +1,19 @@ +// run-pass +// aux-build:test-macros.rs +// compile-flags: -Z span-debug +// edition:2018 +// +// Tests the pretty-printing behavior of inserting `NoDelim` groups + +extern crate test_macros; +use test_macros::print_bang_consume; + +macro_rules! expand_it { + (($val1:expr) ($val2:expr)) => { expand_it!($val1 + $val2) }; + ($val:expr) => { print_bang_consume!("hi" $val (1 + 1)) }; +} + +fn main() { + expand_it!(1 + (25) + 1); + expand_it!(("hello".len()) ("world".len())); +} diff --git a/src/test/ui/proc-macro/nodelim-groups.stdout b/src/test/ui/proc-macro/nodelim-groups.stdout new file mode 100644 index 0000000000000..75a189a9fcdea --- /dev/null +++ b/src/test/ui/proc-macro/nodelim-groups.stdout @@ -0,0 +1,156 @@ +PRINT-BANG INPUT (DISPLAY): "hi" 1 + (25) + 1 (1 + 1) +PRINT-BANG INPUT (DEBUG): TokenStream [ + Literal { + kind: Str, + symbol: "hi", + suffix: None, + span: $DIR/nodelim-groups.rs:13:42: 13:46 (#3), + }, + Group { + delimiter: None, + stream: TokenStream [ + Literal { + kind: Integer, + symbol: "1", + suffix: None, + span: $DIR/nodelim-groups.rs:17:16: 17:17 (#0), + }, + Punct { + ch: '+', + spacing: Alone, + span: $DIR/nodelim-groups.rs:17:18: 17:19 (#0), + }, + Group { + delimiter: Parenthesis, + stream: TokenStream [ + Literal { + kind: Integer, + symbol: "25", + suffix: None, + span: $DIR/nodelim-groups.rs:17:21: 17:23 (#0), + }, + ], + span: $DIR/nodelim-groups.rs:17:20: 17:24 (#0), + }, + Punct { + ch: '+', + spacing: Alone, + span: $DIR/nodelim-groups.rs:17:25: 17:26 (#0), + }, + Literal { + kind: Integer, + symbol: "1", + suffix: None, + span: $DIR/nodelim-groups.rs:17:27: 17:28 (#0), + }, + ], + span: $DIR/nodelim-groups.rs:13:47: 13:51 (#3), + }, + Group { + delimiter: Parenthesis, + stream: TokenStream [ + Literal { + kind: Integer, + symbol: "1", + suffix: None, + span: $DIR/nodelim-groups.rs:13:53: 13:54 (#3), + }, + Punct { + ch: '+', + spacing: Alone, + span: $DIR/nodelim-groups.rs:13:55: 13:56 (#3), + }, + Literal { + kind: Integer, + symbol: "1", + suffix: None, + span: $DIR/nodelim-groups.rs:13:57: 13:58 (#3), + }, + ], + span: $DIR/nodelim-groups.rs:13:52: 13:59 (#3), + }, +] +PRINT-BANG INPUT (DISPLAY): "hi" "hello".len() + "world".len() (1 + 1) +PRINT-BANG RE-COLLECTED (DISPLAY): "hi" "hello" . len() + "world" . len() (1 + 1) +PRINT-BANG INPUT (DEBUG): TokenStream [ + Literal { + kind: Str, + symbol: "hi", + suffix: None, + span: $DIR/nodelim-groups.rs:13:42: 13:46 (#8), + }, + Group { + delimiter: None, + stream: TokenStream [ + Literal { + kind: Str, + symbol: "hello", + suffix: None, + span: $DIR/nodelim-groups.rs:13:47: 13:51 (#8), + }, + Punct { + ch: '.', + spacing: Alone, + span: $DIR/nodelim-groups.rs:13:47: 13:51 (#8), + }, + Ident { + ident: "len", + span: $DIR/nodelim-groups.rs:13:47: 13:51 (#8), + }, + Group { + delimiter: Parenthesis, + stream: TokenStream [], + span: $DIR/nodelim-groups.rs:13:47: 13:51 (#8), + }, + Punct { + ch: '+', + spacing: Alone, + span: $DIR/nodelim-groups.rs:13:47: 13:51 (#8), + }, + Literal { + kind: Str, + symbol: "world", + suffix: None, + span: $DIR/nodelim-groups.rs:13:47: 13:51 (#8), + }, + Punct { + ch: '.', + spacing: Alone, + span: $DIR/nodelim-groups.rs:13:47: 13:51 (#8), + }, + Ident { + ident: "len", + span: $DIR/nodelim-groups.rs:13:47: 13:51 (#8), + }, + Group { + delimiter: Parenthesis, + stream: TokenStream [], + span: $DIR/nodelim-groups.rs:13:47: 13:51 (#8), + }, + ], + span: $DIR/nodelim-groups.rs:13:47: 13:51 (#8), + }, + Group { + delimiter: Parenthesis, + stream: TokenStream [ + Literal { + kind: Integer, + symbol: "1", + suffix: None, + span: $DIR/nodelim-groups.rs:13:53: 13:54 (#8), + }, + Punct { + ch: '+', + spacing: Alone, + span: $DIR/nodelim-groups.rs:13:55: 13:56 (#8), + }, + Literal { + kind: Integer, + symbol: "1", + suffix: None, + span: $DIR/nodelim-groups.rs:13:57: 13:58 (#8), + }, + ], + span: $DIR/nodelim-groups.rs:13:52: 13:59 (#8), + }, +] diff --git a/src/test/ui/recursion/issue-38591-non-regular-dropck-recursion.stderr b/src/test/ui/recursion/issue-38591-non-regular-dropck-recursion.stderr index 0552847c48ca9..3296a2cb094a1 100644 --- a/src/test/ui/recursion/issue-38591-non-regular-dropck-recursion.stderr +++ b/src/test/ui/recursion/issue-38591-non-regular-dropck-recursion.stderr @@ -4,7 +4,9 @@ error: reached the recursion limit while instantiating `std::intrinsics::drop_in LL | / pub unsafe fn drop_in_place(to_drop: *mut T) { LL | | // Code here does not matter - this is replaced by the LL | | // real drop glue by the compiler. -LL | | drop_in_place(to_drop) +LL | | +LL | | // SAFETY: see comment above +LL | | unsafe { drop_in_place(to_drop) } LL | | } | |_^ | @@ -14,7 +16,9 @@ note: `std::intrinsics::drop_in_place` defined here LL | / pub unsafe fn drop_in_place(to_drop: *mut T) { LL | | // Code here does not matter - this is replaced by the LL | | // real drop glue by the compiler. -LL | | drop_in_place(to_drop) +LL | | +LL | | // SAFETY: see comment above +LL | | unsafe { drop_in_place(to_drop) } LL | | } | |_^ diff --git a/src/test/ui/rfc-2565-param-attrs/auxiliary/param-attrs.rs b/src/test/ui/rfc-2565-param-attrs/auxiliary/param-attrs.rs index c537c1034b5a6..2a172c8458d71 100644 --- a/src/test/ui/rfc-2565-param-attrs/auxiliary/param-attrs.rs +++ b/src/test/ui/rfc-2565-param-attrs/auxiliary/param-attrs.rs @@ -17,28 +17,27 @@ macro_rules! checker { } } -checker!(attr_extern, r#"extern "C" { - fn ffi(#[a1] arg1: i32, #[a2] ...); -}"#); -checker!(attr_extern_cvar, r#"unsafe extern "C" fn cvar(arg1: i32, #[a1] mut args: ...) { }"#); -checker!(attr_alias, "type Alias = fn(#[a1] u8, #[a2] ...);"); -checker!(attr_free, "fn free(#[a1] arg1: u8) { let lam = |#[a2] W(x), #[a3] y| (); }"); -checker!(attr_inherent_1, "fn inherent1(#[a1] self, #[a2] arg1: u8) { }"); -checker!(attr_inherent_2, "fn inherent2(#[a1] &self, #[a2] arg1: u8) { }"); -checker!(attr_inherent_3, "fn inherent3<'a>(#[a1] &'a mut self, #[a2] arg1: u8) { }"); -checker!(attr_inherent_4, "fn inherent4<'a>(#[a1] self: Box, #[a2] arg1: u8) { }"); -checker!(attr_inherent_issue_64682, "fn inherent5(#[a1] #[a2] arg1: u8, #[a3] arg2: u8) { }"); -checker!(attr_trait_1, "fn trait1(#[a1] self, #[a2] arg1: u8);"); -checker!(attr_trait_2, "fn trait2(#[a1] &self, #[a2] arg1: u8);"); -checker!(attr_trait_3, "fn trait3<'a>(#[a1] &'a mut self, #[a2] arg1: u8);"); -checker!(attr_trait_4, "fn trait4<'a>(#[a1] self: Box, #[a2] arg1: u8, #[a3] Vec);"); -checker!(attr_trait_issue_64682, "fn trait5(#[a1] #[a2] arg1: u8, #[a3] arg2: u8);"); -checker!(rename_params, r#"impl Foo { - fn hello(#[angery(true)] a: i32, #[a2] b: i32, #[what = "how"] c: u32) { } - fn hello2(#[a1] #[a2] a: i32, #[what = "how"] b: i32, - #[angery(true)] c: u32) { - } - fn hello_self(#[a1] #[a2] &self, #[a1] #[a2] a: i32, - #[what = "how"] b: i32, #[angery(true)] c: u32) { - } +checker!(attr_extern, r#"extern "C" { fn ffi(#[a1] arg1 : i32, #[a2] ...) ; }"#); +checker!(attr_extern_cvar, r#"unsafe extern "C" fn cvar(arg1 : i32, #[a1] mut args : ...) { }"#); +checker!(attr_alias, "type Alias = fn(#[a1] u8, #[a2] ...) ;"); +checker!(attr_free, "fn free(#[a1] arg1 : u8) { let lam = | #[a2] W(x), #[a3] y | () ; }"); +checker!(attr_inherent_1, "fn inherent1(#[a1] self, #[a2] arg1 : u8) { }"); +checker!(attr_inherent_2, "fn inherent2(#[a1] & self, #[a2] arg1 : u8) { }"); +checker!(attr_inherent_3, "fn inherent3 < 'a > (#[a1] & 'a mut self, #[a2] arg1 : u8) { }"); +checker!(attr_inherent_4, "fn inherent4 < 'a > (#[a1] self : Box < Self >, #[a2] arg1 : u8) { }"); +checker!(attr_inherent_issue_64682, "fn inherent5(#[a1] #[a2] arg1 : u8, #[a3] arg2 : u8) { }"); +checker!(attr_trait_1, "fn trait1(#[a1] self, #[a2] arg1 : u8) ;"); +checker!(attr_trait_2, "fn trait2(#[a1] & self, #[a2] arg1 : u8) ;"); +checker!(attr_trait_3, "fn trait3 < 'a > (#[a1] & 'a mut self, #[a2] arg1 : u8) ;"); +checker!(attr_trait_4, r#"fn trait4 < 'a > +(#[a1] self : Box < Self >, #[a2] arg1 : u8, #[a3] Vec < u8 >) ;"#); +checker!(attr_trait_issue_64682, "fn trait5(#[a1] #[a2] arg1 : u8, #[a3] arg2 : u8) ;"); +checker!(rename_params, r#"impl Foo +{ + fn hello(#[angery(true)] a : i32, #[a2] b : i32, #[what = "how"] c : u32) + { } fn + hello2(#[a1] #[a2] a : i32, #[what = "how"] b : i32, #[angery(true)] c : + u32) { } fn + hello_self(#[a1] #[a2] & self, #[a1] #[a2] a : i32, #[what = "how"] b : + i32, #[angery(true)] c : u32) { } }"#); diff --git a/src/test/ui/rfcs/rfc-2396-target_feature-11/fn-traits.rs b/src/test/ui/rfcs/rfc-2396-target_feature-11/fn-traits.rs new file mode 100644 index 0000000000000..5c838fd719cd9 --- /dev/null +++ b/src/test/ui/rfcs/rfc-2396-target_feature-11/fn-traits.rs @@ -0,0 +1,34 @@ +// only-x86_64 + +#![feature(target_feature_11)] + +#[target_feature(enable = "avx")] +fn foo() {} + +#[target_feature(enable = "avx")] +unsafe fn foo_unsafe() {} + +fn call(f: impl Fn()) { + f() +} + +fn call_mut(f: impl FnMut()) { + f() +} + +fn call_once(f: impl FnOnce()) { + f() +} + +fn main() { + call(foo); //~ ERROR expected a `std::ops::Fn<()>` closure, found `fn() {foo}` + call_mut(foo); //~ ERROR expected a `std::ops::FnMut<()>` closure, found `fn() {foo}` + call_once(foo); //~ ERROR expected a `std::ops::FnOnce<()>` closure, found `fn() {foo}` + + call(foo_unsafe); + //~^ ERROR expected a `std::ops::Fn<()>` closure, found `unsafe fn() {foo_unsafe}` + call_mut(foo_unsafe); + //~^ ERROR expected a `std::ops::FnMut<()>` closure, found `unsafe fn() {foo_unsafe}` + call_once(foo_unsafe); + //~^ ERROR expected a `std::ops::FnOnce<()>` closure, found `unsafe fn() {foo_unsafe}` +} diff --git a/src/test/ui/rfcs/rfc-2396-target_feature-11/fn-traits.stderr b/src/test/ui/rfcs/rfc-2396-target_feature-11/fn-traits.stderr new file mode 100644 index 0000000000000..448077b439e80 --- /dev/null +++ b/src/test/ui/rfcs/rfc-2396-target_feature-11/fn-traits.stderr @@ -0,0 +1,81 @@ +error[E0277]: expected a `std::ops::Fn<()>` closure, found `fn() {foo}` + --> $DIR/fn-traits.rs:24:10 + | +LL | fn call(f: impl Fn()) { + | ---- required by this bound in `call` +... +LL | call(foo); + | ^^^ expected an `Fn<()>` closure, found `fn() {foo}` + | + = help: the trait `std::ops::Fn<()>` is not implemented for `fn() {foo}` + = note: wrap the `fn() {foo}` in a closure with no arguments: `|| { /* code */ } + = note: `#[target_feature]` functions do not implement the `Fn` traits + +error[E0277]: expected a `std::ops::FnMut<()>` closure, found `fn() {foo}` + --> $DIR/fn-traits.rs:25:14 + | +LL | fn call_mut(f: impl FnMut()) { + | ------- required by this bound in `call_mut` +... +LL | call_mut(foo); + | ^^^ expected an `FnMut<()>` closure, found `fn() {foo}` + | + = help: the trait `std::ops::FnMut<()>` is not implemented for `fn() {foo}` + = note: wrap the `fn() {foo}` in a closure with no arguments: `|| { /* code */ } + = note: `#[target_feature]` functions do not implement the `Fn` traits + +error[E0277]: expected a `std::ops::FnOnce<()>` closure, found `fn() {foo}` + --> $DIR/fn-traits.rs:26:15 + | +LL | fn call_once(f: impl FnOnce()) { + | -------- required by this bound in `call_once` +... +LL | call_once(foo); + | ^^^ expected an `FnOnce<()>` closure, found `fn() {foo}` + | + = help: the trait `std::ops::FnOnce<()>` is not implemented for `fn() {foo}` + = note: wrap the `fn() {foo}` in a closure with no arguments: `|| { /* code */ } + = note: `#[target_feature]` functions do not implement the `Fn` traits + +error[E0277]: expected a `std::ops::Fn<()>` closure, found `unsafe fn() {foo_unsafe}` + --> $DIR/fn-traits.rs:28:10 + | +LL | fn call(f: impl Fn()) { + | ---- required by this bound in `call` +... +LL | call(foo_unsafe); + | ^^^^^^^^^^ expected an `Fn<()>` closure, found `unsafe fn() {foo_unsafe}` + | + = help: the trait `std::ops::Fn<()>` is not implemented for `unsafe fn() {foo_unsafe}` + = note: wrap the `unsafe fn() {foo_unsafe}` in a closure with no arguments: `|| { /* code */ } + = note: `#[target_feature]` functions do not implement the `Fn` traits + +error[E0277]: expected a `std::ops::FnMut<()>` closure, found `unsafe fn() {foo_unsafe}` + --> $DIR/fn-traits.rs:30:14 + | +LL | fn call_mut(f: impl FnMut()) { + | ------- required by this bound in `call_mut` +... +LL | call_mut(foo_unsafe); + | ^^^^^^^^^^ expected an `FnMut<()>` closure, found `unsafe fn() {foo_unsafe}` + | + = help: the trait `std::ops::FnMut<()>` is not implemented for `unsafe fn() {foo_unsafe}` + = note: wrap the `unsafe fn() {foo_unsafe}` in a closure with no arguments: `|| { /* code */ } + = note: `#[target_feature]` functions do not implement the `Fn` traits + +error[E0277]: expected a `std::ops::FnOnce<()>` closure, found `unsafe fn() {foo_unsafe}` + --> $DIR/fn-traits.rs:32:15 + | +LL | fn call_once(f: impl FnOnce()) { + | -------- required by this bound in `call_once` +... +LL | call_once(foo_unsafe); + | ^^^^^^^^^^ expected an `FnOnce<()>` closure, found `unsafe fn() {foo_unsafe}` + | + = help: the trait `std::ops::FnOnce<()>` is not implemented for `unsafe fn() {foo_unsafe}` + = note: wrap the `unsafe fn() {foo_unsafe}` in a closure with no arguments: `|| { /* code */ } + = note: `#[target_feature]` functions do not implement the `Fn` traits + +error: aborting due to 6 previous errors + +For more information about this error, try `rustc --explain E0277`. diff --git a/src/test/ui/unsafe/ranged_ints_macro.rs b/src/test/ui/unsafe/ranged_ints_macro.rs new file mode 100644 index 0000000000000..9192ecfe196cb --- /dev/null +++ b/src/test/ui/unsafe/ranged_ints_macro.rs @@ -0,0 +1,16 @@ +// build-pass +#![feature(rustc_attrs)] + +macro_rules! apply { + ($val:expr) => { + #[rustc_layout_scalar_valid_range_start($val)] + #[repr(transparent)] + pub(crate) struct NonZero(pub(crate) T); + } +} + +apply!(1); + +fn main() { + let _x = unsafe { NonZero(1) }; +} diff --git a/src/tools/clippy/clippy_lints/src/arithmetic.rs b/src/tools/clippy/clippy_lints/src/arithmetic.rs index cc09b99cf1dd1..b0db94c2e3260 100644 --- a/src/tools/clippy/clippy_lints/src/arithmetic.rs +++ b/src/tools/clippy/clippy_lints/src/arithmetic.rs @@ -86,27 +86,39 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Arithmetic { _ => (), } - let (l_ty, r_ty) = (cx.tables().expr_ty(l), cx.tables().expr_ty(r)); + let (l_ty, r_ty) = (cx.typeck_results().expr_ty(l), cx.typeck_results().expr_ty(r)); if l_ty.peel_refs().is_integral() && r_ty.peel_refs().is_integral() { span_lint(cx, INTEGER_ARITHMETIC, expr.span, "integer arithmetic detected"); self.expr_span = Some(expr.span); - } else if l_ty.peel_refs().is_floating_point() && r_ty.peel_refs().is_floating_point() { - span_lint(cx, FLOAT_ARITHMETIC, expr.span, "floating-point arithmetic detected"); + } else if l_ty.peel_refs().is_floating_point() + && r_ty.peel_refs().is_floating_point() + { + span_lint( + cx, + FLOAT_ARITHMETIC, + expr.span, + "floating-point arithmetic detected", + ); self.expr_span = Some(expr.span); } - }, + } hir::ExprKind::Unary(hir::UnOp::UnNeg, arg) => { - let ty = cx.tables().expr_ty(arg); - if constant_simple(cx, cx.tables(), expr).is_none() { + let ty = cx.typeck_results().expr_ty(arg); + if constant_simple(cx, cx.typeck_results(), expr).is_none() { if ty.is_integral() { span_lint(cx, INTEGER_ARITHMETIC, expr.span, "integer arithmetic detected"); self.expr_span = Some(expr.span); } else if ty.is_floating_point() { - span_lint(cx, FLOAT_ARITHMETIC, expr.span, "floating-point arithmetic detected"); + span_lint( + cx, + FLOAT_ARITHMETIC, + expr.span, + "floating-point arithmetic detected", + ); self.expr_span = Some(expr.span); } } - }, + } _ => (), } } @@ -130,7 +142,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Arithmetic { } } self.const_span = Some(body_span); - }, + } hir::BodyOwnerKind::Fn | hir::BodyOwnerKind::Closure => (), } } diff --git a/src/tools/clippy/clippy_lints/src/assertions_on_constants.rs b/src/tools/clippy/clippy_lints/src/assertions_on_constants.rs index c4536b57f8a99..fde9a4d554d13 100644 --- a/src/tools/clippy/clippy_lints/src/assertions_on_constants.rs +++ b/src/tools/clippy/clippy_lints/src/assertions_on_constants.rs @@ -1,6 +1,8 @@ use crate::consts::{constant, Constant}; use crate::utils::paths; -use crate::utils::{is_direct_expn_of, is_expn_of, match_function_call, snippet_opt, span_lint_and_help}; +use crate::utils::{ + is_direct_expn_of, is_expn_of, match_function_call, snippet_opt, span_lint_and_help, +}; use if_chain::if_chain; use rustc_ast::ast::LitKind; use rustc_hir::{Expr, ExprKind, PatKind, UnOp}; @@ -72,7 +74,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AssertionsOnConstants { } if_chain! { if let ExprKind::Unary(_, ref lit) = e.kind; - if let Some((Constant::Bool(is_true), _)) = constant(cx, cx.tables(), lit); + if let Some((Constant::Bool(is_true), _)) = constant(cx, cx.typeck_results(), lit); if is_true; then { lint_true(true); @@ -86,8 +88,12 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AssertionsOnConstants { match assert_match { // matched assert but not message AssertKind::WithoutMessage(false) => lint_false_without_message(), - AssertKind::WithoutMessage(true) | AssertKind::WithMessage(_, true) => lint_true(false), - AssertKind::WithMessage(panic_message, false) => lint_false_with_message(panic_message), + AssertKind::WithoutMessage(true) | AssertKind::WithMessage(_, true) => { + lint_true(false) + } + AssertKind::WithMessage(panic_message, false) => { + lint_false_with_message(panic_message) + } }; } } @@ -114,14 +120,17 @@ enum AssertKind { /// ``` /// /// where `message` is any expression and `c` is a constant bool. -fn match_assert_with_message<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) -> Option { +fn match_assert_with_message<'a, 'tcx>( + cx: &LateContext<'a, 'tcx>, + expr: &'tcx Expr<'_>, +) -> Option { if_chain! { if let ExprKind::Match(ref expr, ref arms, _) = expr.kind; // matches { let _t = expr; _t } if let ExprKind::DropTemps(ref expr) = expr.kind; if let ExprKind::Unary(UnOp::UnNot, ref expr) = expr.kind; // bind the first argument of the `assert!` macro - if let Some((Constant::Bool(is_true), _)) = constant(cx, cx.tables(), expr); + if let Some((Constant::Bool(is_true), _)) = constant(cx, cx.typeck_results(), expr); // arm 1 pattern if let PatKind::Lit(ref lit_expr) = arms[0].pat.kind; if let ExprKind::Lit(ref lit) = lit_expr.kind; diff --git a/src/tools/clippy/clippy_lints/src/assign_ops.rs b/src/tools/clippy/clippy_lints/src/assign_ops.rs index 51a7647d3208f..5df21dbb1d8a5 100644 --- a/src/tools/clippy/clippy_lints/src/assign_ops.rs +++ b/src/tools/clippy/clippy_lints/src/assign_ops.rs @@ -1,5 +1,6 @@ use crate::utils::{ - get_trait_def_id, implements_trait, snippet_opt, span_lint_and_then, trait_ref_of_method, SpanlessEq, + get_trait_def_id, implements_trait, snippet_opt, span_lint_and_then, trait_ref_of_method, + SpanlessEq, }; use crate::utils::{higher, sugg}; use if_chain::if_chain; @@ -78,12 +79,12 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AssignOps { lint_misrefactored_assign_op(cx, expr, *op, rhs, lhs, l); } } - }, + } hir::ExprKind::Assign(assignee, e, _) => { if let hir::ExprKind::Binary(op, l, r) = &e.kind { let lint = |assignee: &hir::Expr<'_>, rhs: &hir::Expr<'_>| { - let ty = cx.tables().expr_ty(assignee); - let rty = cx.tables().expr_ty(rhs); + let ty = cx.typeck_results().expr_ty(assignee); + let rty = cx.typeck_results().expr_ty(rhs); macro_rules! ops { ($op:expr, $cx:expr, @@ -151,11 +152,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AssignOps { } }; - let mut visitor = ExprVisitor { - assignee, - counter: 0, - cx, - }; + let mut visitor = ExprVisitor { assignee, counter: 0, cx }; walk_expr(&mut visitor, e); @@ -167,7 +164,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AssignOps { // a = b commutative_op a // Limited to primitive type as these ops are know to be commutative if SpanlessEq::new(cx).ignore_fn().eq_expr(assignee, r) - && cx.tables().expr_ty(assignee).is_primitive_ty() + && cx.typeck_results().expr_ty(assignee).is_primitive_ty() { match op.node { hir::BinOpKind::Add @@ -178,14 +175,14 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AssignOps { | hir::BinOpKind::BitAnd | hir::BinOpKind::BitOr => { lint(assignee, l); - }, - _ => {}, + } + _ => {} } } } } - }, - _ => {}, + } + _ => {} } } } @@ -204,10 +201,13 @@ fn lint_misrefactored_assign_op( expr.span, "variable appears on both sides of an assignment operation", |diag| { - if let (Some(snip_a), Some(snip_r)) = (snippet_opt(cx, assignee.span), snippet_opt(cx, rhs_other.span)) { + if let (Some(snip_a), Some(snip_r)) = + (snippet_opt(cx, assignee.span), snippet_opt(cx, rhs_other.span)) + { let a = &sugg::Sugg::hir(cx, assignee, ".."); let r = &sugg::Sugg::hir(cx, rhs, ".."); - let long = format!("{} = {}", snip_a, sugg::make_binop(higher::binop(op.node), a, r)); + let long = + format!("{} = {}", snip_a, sugg::make_binop(higher::binop(op.node), a, r)); diag.span_suggestion( expr.span, &format!( diff --git a/src/tools/clippy/clippy_lints/src/atomic_ordering.rs b/src/tools/clippy/clippy_lints/src/atomic_ordering.rs index 65e1e2c519c26..275fb2a6a4bd5 100644 --- a/src/tools/clippy/clippy_lints/src/atomic_ordering.rs +++ b/src/tools/clippy/clippy_lints/src/atomic_ordering.rs @@ -53,10 +53,8 @@ const ATOMIC_TYPES: [&str; 12] = [ ]; fn type_is_atomic(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> bool { - if let ty::Adt(&ty::AdtDef { did, .. }, _) = cx.tables().expr_ty(expr).kind { - ATOMIC_TYPES - .iter() - .any(|ty| match_def_path(cx, did, &["core", "sync", "atomic", ty])) + if let ty::Adt(&ty::AdtDef { did, .. }, _) = cx.typeck_results().expr_ty(expr).kind { + ATOMIC_TYPES.iter().any(|ty| match_def_path(cx, did, &["core", "sync", "atomic", ty])) } else { false } @@ -76,7 +74,7 @@ fn check_atomic_load_store(cx: &LateContext<'_, '_>, expr: &Expr<'_>) { if method == "load" || method == "store"; let ordering_arg = if method == "load" { &args[1] } else { &args[2] }; if let ExprKind::Path(ref ordering_qpath) = ordering_arg.kind; - if let Some(ordering_def_id) = cx.tables().qpath_res(ordering_qpath, ordering_arg.hir_id).opt_def_id(); + if let Some(ordering_def_id) = cx.typeck_results().qpath_res(ordering_qpath, ordering_arg.hir_id).opt_def_id(); then { if method == "load" && match_ordering_def_path(cx, ordering_def_id, &["Release", "AcqRel"]) { @@ -107,12 +105,12 @@ fn check_memory_fence(cx: &LateContext<'_, '_>, expr: &Expr<'_>) { if_chain! { if let ExprKind::Call(ref func, ref args) = expr.kind; if let ExprKind::Path(ref func_qpath) = func.kind; - if let Some(def_id) = cx.tables().qpath_res(func_qpath, func.hir_id).opt_def_id(); + if let Some(def_id) = cx.typeck_results().qpath_res(func_qpath, func.hir_id).opt_def_id(); if ["fence", "compiler_fence"] .iter() .any(|func| match_def_path(cx, def_id, &["core", "sync", "atomic", func])); if let ExprKind::Path(ref ordering_qpath) = &args[0].kind; - if let Some(ordering_def_id) = cx.tables().qpath_res(ordering_qpath, args[0].hir_id).opt_def_id(); + if let Some(ordering_def_id) = cx.typeck_results().qpath_res(ordering_qpath, args[0].hir_id).opt_def_id(); if match_ordering_def_path(cx, ordering_def_id, &["Relaxed"]); then { span_lint_and_help( diff --git a/src/tools/clippy/clippy_lints/src/attrs.rs b/src/tools/clippy/clippy_lints/src/attrs.rs index 41f125d48398f..79110d4a8afe3 100644 --- a/src/tools/clippy/clippy_lints/src/attrs.rs +++ b/src/tools/clippy/clippy_lints/src/attrs.rs @@ -2,17 +2,20 @@ use crate::reexport::Name; use crate::utils::{ - first_line_of_span, is_present_in_source, match_def_path, paths, snippet_opt, span_lint, span_lint_and_sugg, - span_lint_and_then, without_block_comments, + first_line_of_span, is_present_in_source, match_def_path, paths, snippet_opt, span_lint, + span_lint_and_sugg, span_lint_and_then, without_block_comments, }; use if_chain::if_chain; use rustc_ast::ast::{AttrKind, AttrStyle, Attribute, Lit, LitKind, MetaItemKind, NestedMetaItem}; use rustc_ast::util::lev_distance::find_best_match_for_name; use rustc_errors::Applicability; use rustc_hir::{ - Block, Expr, ExprKind, ImplItem, ImplItemKind, Item, ItemKind, StmtKind, TraitFn, TraitItem, TraitItemKind, + Block, Expr, ExprKind, ImplItem, ImplItemKind, Item, ItemKind, StmtKind, TraitFn, TraitItem, + TraitItemKind, +}; +use rustc_lint::{ + CheckLintNameResult, EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext, }; -use rustc_lint::{CheckLintNameResult, EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext}; use rustc_middle::lint::in_external_macro; use rustc_middle::ty; use rustc_session::{declare_lint_pass, declare_tool_lint}; @@ -258,8 +261,8 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Attributes { match &*ident.as_str() { "allow" | "warn" | "deny" | "forbid" => { check_clippy_lint_names(cx, items); - }, - _ => {}, + } + _ => {} } if items.is_empty() || !attr.check_name(sym!(deprecated)) { return; @@ -284,7 +287,8 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Attributes { } match item.kind { ItemKind::ExternCrate(..) | ItemKind::Use(..) => { - let skip_unused_imports = item.attrs.iter().any(|attr| attr.check_name(sym!(macro_use))); + let skip_unused_imports = + item.attrs.iter().any(|attr| attr.check_name(sym!(macro_use))); for attr in item.attrs { if in_external_macro(cx.sess(), attr.span) { @@ -306,16 +310,18 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Attributes { { return; } - }, + } ItemKind::ExternCrate(..) => { - if is_word(lint, sym!(unused_imports)) && skip_unused_imports { + if is_word(lint, sym!(unused_imports)) + && skip_unused_imports + { return; } if is_word(lint, sym!(unused_extern_crates)) { return; } - }, - _ => {}, + } + _ => {} } } let line_span = first_line_of_span(cx, attr.span); @@ -339,14 +345,14 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Attributes { ); } } - }, - _ => {}, + } + _ => {} } } } } - }, - _ => {}, + } + _ => {} } } @@ -418,7 +424,7 @@ fn check_clippy_lint_names(cx: &LateContext<'_, '_>, items: &[NestedMetaItem]) { fn is_relevant_item(cx: &LateContext<'_, '_>, item: &Item<'_>) -> bool { if let ItemKind::Fn(_, _, eid) = item.kind { - is_relevant_expr(cx, cx.tcx.body_tables(eid), &cx.tcx.hir().body(eid).value) + is_relevant_expr(cx, cx.tcx.typeck_body(eid), &cx.tcx.hir().body(eid).value) } else { true } @@ -426,7 +432,9 @@ fn is_relevant_item(cx: &LateContext<'_, '_>, item: &Item<'_>) -> bool { fn is_relevant_impl(cx: &LateContext<'_, '_>, item: &ImplItem<'_>) -> bool { match item.kind { - ImplItemKind::Fn(_, eid) => is_relevant_expr(cx, cx.tcx.body_tables(eid), &cx.tcx.hir().body(eid).value), + ImplItemKind::Fn(_, eid) => { + is_relevant_expr(cx, cx.tcx.typeck_body(eid), &cx.tcx.hir().body(eid).value) + } _ => false, } } @@ -435,32 +443,43 @@ fn is_relevant_trait(cx: &LateContext<'_, '_>, item: &TraitItem<'_>) -> bool { match item.kind { TraitItemKind::Fn(_, TraitFn::Required(_)) => true, TraitItemKind::Fn(_, TraitFn::Provided(eid)) => { - is_relevant_expr(cx, cx.tcx.body_tables(eid), &cx.tcx.hir().body(eid).value) - }, + is_relevant_expr(cx, cx.tcx.typeck_body(eid), &cx.tcx.hir().body(eid).value) + } _ => false, } } -fn is_relevant_block(cx: &LateContext<'_, '_>, tables: &ty::TypeckTables<'_>, block: &Block<'_>) -> bool { +fn is_relevant_block( + cx: &LateContext<'_, '_>, + typeck_results: &ty::TypeckResults<'_>, + block: &Block<'_>, +) -> bool { if let Some(stmt) = block.stmts.first() { match &stmt.kind { StmtKind::Local(_) => true, - StmtKind::Expr(expr) | StmtKind::Semi(expr) => is_relevant_expr(cx, tables, expr), + StmtKind::Expr(expr) | StmtKind::Semi(expr) => { + is_relevant_expr(cx, typeck_results, expr) + } _ => false, } } else { - block.expr.as_ref().map_or(false, |e| is_relevant_expr(cx, tables, e)) + block.expr.as_ref().map_or(false, |e| is_relevant_expr(cx, typeck_results, e)) } } -fn is_relevant_expr(cx: &LateContext<'_, '_>, tables: &ty::TypeckTables<'_>, expr: &Expr<'_>) -> bool { +fn is_relevant_expr( + cx: &LateContext<'_, '_>, + typeck_results: &ty::TypeckResults<'_>, + expr: &Expr<'_>, +) -> bool { match &expr.kind { - ExprKind::Block(block, _) => is_relevant_block(cx, tables, block), - ExprKind::Ret(Some(e)) => is_relevant_expr(cx, tables, e), + ExprKind::Block(block, _) => is_relevant_block(cx, typeck_results, block), + ExprKind::Ret(Some(e)) => is_relevant_expr(cx, typeck_results, e), ExprKind::Ret(None) | ExprKind::Break(_, None) => false, ExprKind::Call(path_expr, _) => { if let ExprKind::Path(qpath) = &path_expr.kind { - if let Some(fun_id) = tables.qpath_res(qpath, path_expr.hir_id).opt_def_id() { + if let Some(fun_id) = typeck_results.qpath_res(qpath, path_expr.hir_id).opt_def_id() + { !match_def_path(cx, fun_id, &paths::BEGIN_PANIC) } else { true @@ -468,7 +487,7 @@ fn is_relevant_expr(cx: &LateContext<'_, '_>, tables: &ty::TypeckTables<'_>, exp } else { true } - }, + } _ => true, } } @@ -603,11 +622,7 @@ fn check_deprecated_cfg_attr(cx: &EarlyContext<'_>, attr: &Attribute) { fn check_mismatched_target_os(cx: &EarlyContext<'_>, attr: &Attribute) { fn find_os(name: &str) -> Option<&'static str> { - UNIX_SYSTEMS - .iter() - .chain(NON_UNIX_SYSTEMS.iter()) - .find(|&&os| os == name) - .copied() + UNIX_SYSTEMS.iter().chain(NON_UNIX_SYSTEMS.iter()).find(|&&os| os == name).copied() } fn is_unix(name: &str) -> bool { @@ -622,7 +637,7 @@ fn check_mismatched_target_os(cx: &EarlyContext<'_>, attr: &Attribute) { match &meta.kind { MetaItemKind::List(list) => { mismatched.extend(find_mismatched_target_os(&list)); - }, + } MetaItemKind::Word => { if_chain! { if let Some(ident) = meta.ident(); @@ -631,8 +646,8 @@ fn check_mismatched_target_os(cx: &EarlyContext<'_>, attr: &Attribute) { mismatched.push((os, ident.span)); } } - }, - _ => {}, + } + _ => {} } } } diff --git a/src/tools/clippy/clippy_lints/src/await_holding_lock.rs b/src/tools/clippy/clippy_lints/src/await_holding_lock.rs index a88f922d8e03d..5b4c7a09791e6 100644 --- a/src/tools/clippy/clippy_lints/src/await_holding_lock.rs +++ b/src/tools/clippy/clippy_lints/src/await_holding_lock.rs @@ -55,17 +55,19 @@ impl LateLintPass<'_, '_> for AwaitHoldingLock { fn check_body(&mut self, cx: &LateContext<'_, '_>, body: &'_ Body<'_>) { use AsyncGeneratorKind::{Block, Closure, Fn}; if let Some(GeneratorKind::Async(Block | Closure | Fn)) = body.generator_kind { - let body_id = BodyId { - hir_id: body.value.hir_id, - }; + let body_id = BodyId { hir_id: body.value.hir_id }; let def_id = cx.tcx.hir().body_owner_def_id(body_id); - let tables = cx.tcx.typeck_tables_of(def_id); + let tables = cx.tcx.typeck(def_id); check_interior_types(cx, &tables.generator_interior_types, body.value.span); } } } -fn check_interior_types(cx: &LateContext<'_, '_>, ty_causes: &[GeneratorInteriorTypeCause<'_>], span: Span) { +fn check_interior_types( + cx: &LateContext<'_, '_>, + ty_causes: &[GeneratorInteriorTypeCause<'_>], + span: Span, +) { for ty_cause in ty_causes { if let rustc_middle::ty::Adt(adt, _) = ty_cause.ty.kind { if is_mutex_guard(cx, adt.did) { diff --git a/src/tools/clippy/clippy_lints/src/bit_mask.rs b/src/tools/clippy/clippy_lints/src/bit_mask.rs index a53f3249b85b6..3d1cb369f7a3d 100644 --- a/src/tools/clippy/clippy_lints/src/bit_mask.rs +++ b/src/tools/clippy/clippy_lints/src/bit_mask.rs @@ -102,9 +102,7 @@ pub struct BitMask { impl BitMask { #[must_use] pub fn new(verbose_bit_mask_threshold: u64) -> Self { - Self { - verbose_bit_mask_threshold, - } + Self { verbose_bit_mask_threshold } } } @@ -164,7 +162,13 @@ fn invert_cmp(cmp: BinOpKind) -> BinOpKind { } } -fn check_compare(cx: &LateContext<'_, '_>, bit_op: &Expr<'_>, cmp_op: BinOpKind, cmp_value: u128, span: Span) { +fn check_compare( + cx: &LateContext<'_, '_>, + bit_op: &Expr<'_>, + cmp_op: BinOpKind, + cmp_value: u128, + span: Span, +) { if let ExprKind::Binary(op, left, right) = &bit_op.kind { if op.node != BinOpKind::BitAnd && op.node != BinOpKind::BitOr { return; @@ -202,7 +206,7 @@ fn check_bit_mask( } else if mask_value == 0 { span_lint(cx, BAD_BIT_MASK, span, "&-masking with zero"); } - }, + } BinOpKind::BitOr => { if mask_value | cmp_value != cmp_value { span_lint( @@ -215,7 +219,7 @@ fn check_bit_mask( ), ); } - }, + } _ => (), }, BinOpKind::Lt | BinOpKind::Ge => match bit_op { @@ -233,7 +237,7 @@ fn check_bit_mask( } else if mask_value == 0 { span_lint(cx, BAD_BIT_MASK, span, "&-masking with zero"); } - }, + } BinOpKind::BitOr => { if mask_value >= cmp_value { span_lint( @@ -248,7 +252,7 @@ fn check_bit_mask( } else { check_ineffective_lt(cx, span, mask_value, cmp_value, "|"); } - }, + } BinOpKind::BitXor => check_ineffective_lt(cx, span, mask_value, cmp_value, "^"), _ => (), }, @@ -267,7 +271,7 @@ fn check_bit_mask( } else if mask_value == 0 { span_lint(cx, BAD_BIT_MASK, span, "&-masking with zero"); } - }, + } BinOpKind::BitOr => { if mask_value > cmp_value { span_lint( @@ -282,7 +286,7 @@ fn check_bit_mask( } else { check_ineffective_gt(cx, span, mask_value, cmp_value, "|"); } - }, + } BinOpKind::BitXor => check_ineffective_gt(cx, span, mask_value, cmp_value, "^"), _ => (), }, @@ -319,7 +323,7 @@ fn check_ineffective_gt(cx: &LateContext<'_, '_>, span: Span, m: u128, c: u128, } fn fetch_int_literal(cx: &LateContext<'_, '_>, lit: &Expr<'_>) -> Option { - match constant(cx, cx.tables(), lit)?.0 { + match constant(cx, cx.typeck_results(), lit)?.0 { Constant::Int(n) => Some(n), _ => None, } diff --git a/src/tools/clippy/clippy_lints/src/booleans.rs b/src/tools/clippy/clippy_lints/src/booleans.rs index cc399a1f8a009..3d0e72a1cb552 100644 --- a/src/tools/clippy/clippy_lints/src/booleans.rs +++ b/src/tools/clippy/clippy_lints/src/booleans.rs @@ -248,7 +248,7 @@ fn simplify_not(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> Option { }) }, ExprKind::MethodCall(path, _, args, _) if args.len() == 1 => { - let type_of_receiver = cx.tables().expr_ty(&args[0]); + let type_of_receiver = cx.typeck_results().expr_ty(&args[0]); if !is_type_diagnostic_item(cx, type_of_receiver, sym!(option_type)) && !is_type_diagnostic_item(cx, type_of_receiver, sym!(result_type)) { @@ -450,7 +450,7 @@ impl<'a, 'tcx> Visitor<'tcx> for NonminimalBoolVisitor<'a, 'tcx> { self.bool_expr(e) }, ExprKind::Unary(UnOp::UnNot, inner) => { - if self.cx.tables().node_types()[inner.hir_id].is_bool() { + if self.cx.typeck_results().node_types()[inner.hir_id].is_bool() { self.bool_expr(e); } else { walk_expr(self, e); @@ -465,7 +465,7 @@ impl<'a, 'tcx> Visitor<'tcx> for NonminimalBoolVisitor<'a, 'tcx> { } fn implements_ord<'a, 'tcx>(cx: &'a LateContext<'a, 'tcx>, expr: &Expr<'_>) -> bool { - let ty = cx.tables().expr_ty(expr); + let ty = cx.typeck_results().expr_ty(expr); get_trait_def_id(cx, &paths::ORD).map_or(false, |id| implements_trait(cx, ty, id, &[])) } diff --git a/src/tools/clippy/clippy_lints/src/bytecount.rs b/src/tools/clippy/clippy_lints/src/bytecount.rs index c00bb23069bf4..b922e40cbb428 100644 --- a/src/tools/clippy/clippy_lints/src/bytecount.rs +++ b/src/tools/clippy/clippy_lints/src/bytecount.rs @@ -53,7 +53,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ByteCount { if let ExprKind::Binary(ref op, ref l, ref r) = body.value.kind; if op.node == BinOpKind::Eq; if match_type(cx, - walk_ptrs_ty(cx.tables().expr_ty(&filter_args[0])), + walk_ptrs_ty(cx.typeck_results().expr_ty(&filter_args[0])), &paths::SLICE_ITER); then { let needle = match get_path_name(l) { @@ -63,7 +63,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ByteCount { _ => { return; } } }; - if ty::Uint(UintTy::U8) != walk_ptrs_ty(cx.tables().expr_ty(needle)).kind { + if ty::Uint(UintTy::U8) != walk_ptrs_ty(cx.typeck_results().expr_ty(needle)).kind { return; } let haystack = if let ExprKind::MethodCall(ref path, _, ref args, _) = diff --git a/src/tools/clippy/clippy_lints/src/cognitive_complexity.rs b/src/tools/clippy/clippy_lints/src/cognitive_complexity.rs index 78e509d2ecd83..f48480f8e71c0 100644 --- a/src/tools/clippy/clippy_lints/src/cognitive_complexity.rs +++ b/src/tools/clippy/clippy_lints/src/cognitive_complexity.rs @@ -60,7 +60,7 @@ impl CognitiveComplexity { let mut helper = CCHelper { cc: 1, returns: 0 }; helper.visit_expr(expr); let CCHelper { cc, returns } = helper; - let ret_ty = cx.tables().node_type(expr.hir_id); + let ret_ty = cx.typeck_results().node_type(expr.hir_id); let ret_adjust = if is_type_diagnostic_item(cx, ret_ty, sym!(result_type)) { returns } else { diff --git a/src/tools/clippy/clippy_lints/src/comparison_chain.rs b/src/tools/clippy/clippy_lints/src/comparison_chain.rs index 9c0d33f928015..c64947151a1bf 100644 --- a/src/tools/clippy/clippy_lints/src/comparison_chain.rs +++ b/src/tools/clippy/clippy_lints/src/comparison_chain.rs @@ -99,7 +99,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ComparisonChain { } // Check that the type being compared implements `core::cmp::Ord` - let ty = cx.tables().expr_ty(lhs1); + let ty = cx.typeck_results().expr_ty(lhs1); let is_ord = get_trait_def_id(cx, &paths::ORD).map_or(false, |id| implements_trait(cx, ty, id, &[])); if !is_ord { diff --git a/src/tools/clippy/clippy_lints/src/consts.rs b/src/tools/clippy/clippy_lints/src/consts.rs index 550752396c732..f3cde82723f9c 100644 --- a/src/tools/clippy/clippy_lints/src/consts.rs +++ b/src/tools/clippy/clippy_lints/src/consts.rs @@ -56,15 +56,17 @@ impl PartialEq for Constant { // `Fw32 == Fw64`, so don’t compare them. // `to_bits` is required to catch non-matching 0.0, -0.0, and NaNs. l.to_bits() == r.to_bits() - }, + } (&Self::F32(l), &Self::F32(r)) => { // We want `Fw32 == FwAny` and `FwAny == Fw64`, and by transitivity we must have // `Fw32 == Fw64`, so don’t compare them. // `to_bits` is required to catch non-matching 0.0, -0.0, and NaNs. f64::from(l).to_bits() == f64::from(r).to_bits() - }, + } (&Self::Bool(l), &Self::Bool(r)) => l == r, - (&Self::Vec(ref l), &Self::Vec(ref r)) | (&Self::Tuple(ref l), &Self::Tuple(ref r)) => l == r, + (&Self::Vec(ref l), &Self::Vec(ref r)) | (&Self::Tuple(ref l), &Self::Tuple(ref r)) => { + l == r + } (&Self::Repeat(ref lv, ref ls), &Self::Repeat(ref rv, ref rs)) => ls == rs && lv == rv, // TODO: are there inter-type equalities? _ => false, @@ -81,44 +83,49 @@ impl Hash for Constant { match *self { Self::Str(ref s) => { s.hash(state); - }, + } Self::Binary(ref b) => { b.hash(state); - }, + } Self::Char(c) => { c.hash(state); - }, + } Self::Int(i) => { i.hash(state); - }, + } Self::F32(f) => { f64::from(f).to_bits().hash(state); - }, + } Self::F64(f) => { f.to_bits().hash(state); - }, + } Self::Bool(b) => { b.hash(state); - }, + } Self::Vec(ref v) | Self::Tuple(ref v) => { v.hash(state); - }, + } Self::Repeat(ref c, l) => { c.hash(state); l.hash(state); - }, + } Self::RawPtr(u) => { u.hash(state); - }, + } Self::Err(ref s) => { s.hash(state); - }, + } } } } impl Constant { - pub fn partial_cmp(tcx: TyCtxt<'_>, cmp_type: Ty<'_>, left: &Self, right: &Self) -> Option { + pub fn partial_cmp( + tcx: TyCtxt<'_>, + cmp_type: Ty<'_>, + left: &Self, + right: &Self, + ) -> Option { match (left, right) { (&Self::Str(ref ls), &Self::Str(ref rs)) => Some(ls.cmp(rs)), (&Self::Char(ref l), &Self::Char(ref r)) => Some(l.cmp(r)), @@ -128,22 +135,23 @@ impl Constant { } else { Some(l.cmp(&r)) } - }, + } (&Self::F64(l), &Self::F64(r)) => l.partial_cmp(&r), (&Self::F32(l), &Self::F32(r)) => l.partial_cmp(&r), (&Self::Bool(ref l), &Self::Bool(ref r)) => Some(l.cmp(r)), - (&Self::Tuple(ref l), &Self::Tuple(ref r)) | (&Self::Vec(ref l), &Self::Vec(ref r)) => l - .iter() - .zip(r.iter()) - .map(|(li, ri)| Self::partial_cmp(tcx, cmp_type, li, ri)) - .find(|r| r.map_or(true, |o| o != Ordering::Equal)) - .unwrap_or_else(|| Some(l.len().cmp(&r.len()))), + (&Self::Tuple(ref l), &Self::Tuple(ref r)) | (&Self::Vec(ref l), &Self::Vec(ref r)) => { + l.iter() + .zip(r.iter()) + .map(|(li, ri)| Self::partial_cmp(tcx, cmp_type, li, ri)) + .find(|r| r.map_or(true, |o| o != Ordering::Equal)) + .unwrap_or_else(|| Some(l.len().cmp(&r.len()))) + } (&Self::Repeat(ref lv, ref ls), &Self::Repeat(ref rv, ref rs)) => { match Self::partial_cmp(tcx, cmp_type, lv, rv) { Some(Equal) => Some(ls.cmp(rs)), x => x, } - }, + } // TODO: are there any useful inter-type orderings? _ => None, } @@ -162,11 +170,13 @@ pub fn lit_to_constant(lit: &LitKind, ty: Option>) -> Constant { FloatTy::F32 => Constant::F32(is.as_str().parse().unwrap()), FloatTy::F64 => Constant::F64(is.as_str().parse().unwrap()), }, - LitKind::Float(ref is, LitFloatType::Unsuffixed) => match ty.expect("type of float is known").kind { - ty::Float(FloatTy::F32) => Constant::F32(is.as_str().parse().unwrap()), - ty::Float(FloatTy::F64) => Constant::F64(is.as_str().parse().unwrap()), - _ => bug!(), - }, + LitKind::Float(ref is, LitFloatType::Unsuffixed) => { + match ty.expect("type of float is known").kind { + ty::Float(FloatTy::F32) => Constant::F32(is.as_str().parse().unwrap()), + ty::Float(FloatTy::F64) => Constant::F64(is.as_str().parse().unwrap()), + _ => bug!(), + } + } LitKind::Bool(b) => Constant::Bool(b), LitKind::Err(s) => Constant::Err(s), } @@ -174,7 +184,7 @@ pub fn lit_to_constant(lit: &LitKind, ty: Option>) -> Constant { pub fn constant<'c, 'cc>( lcx: &LateContext<'c, 'cc>, - tables: &'c ty::TypeckTables<'cc>, + tables: &'c ty::TypeckResults<'cc>, e: &Expr<'_>, ) -> Option<(Constant, bool)> { let mut cx = ConstEvalLateContext { @@ -189,16 +199,16 @@ pub fn constant<'c, 'cc>( pub fn constant_simple<'c, 'cc>( lcx: &LateContext<'c, 'cc>, - tables: &'c ty::TypeckTables<'cc>, + tables: &'c ty::TypeckResults<'cc>, e: &Expr<'_>, ) -> Option { constant(lcx, tables, e).and_then(|(cst, res)| if res { None } else { Some(cst) }) } -/// Creates a `ConstEvalLateContext` from the given `LateContext` and `TypeckTables`. +/// Creates a `ConstEvalLateContext` from the given `LateContext` and `TypeckResults`. pub fn constant_context<'c, 'cc>( lcx: &'c LateContext<'c, 'cc>, - tables: &'c ty::TypeckTables<'cc>, + tables: &'c ty::TypeckResults<'cc>, ) -> ConstEvalLateContext<'c, 'cc> { ConstEvalLateContext { lcx, @@ -211,7 +221,7 @@ pub fn constant_context<'c, 'cc>( pub struct ConstEvalLateContext<'a, 'tcx> { lcx: &'a LateContext<'a, 'tcx>, - tables: &'a ty::TypeckTables<'tcx>, + tables: &'a ty::TypeckResults<'tcx>, param_env: ty::ParamEnv<'tcx>, needed_resolution: bool, substs: SubstsRef<'tcx>, @@ -235,7 +245,7 @@ impl<'c, 'cc> ConstEvalLateContext<'c, 'cc> { _ => span_bug!(e.span, "typeck error"), }; self.expr(value).map(|v| Constant::Repeat(Box::new(v), n)) - }, + } ExprKind::Unary(op, ref operand) => self.expr(operand).and_then(|o| match op { UnOp::UnNot => self.constant_not(&o, self.tables.expr_ty(e)), UnOp::UnNeg => self.constant_negate(&o, self.tables.expr_ty(e)), @@ -267,7 +277,7 @@ impl<'c, 'cc> ConstEvalLateContext<'c, 'cc> { None } } - }, + } ExprKind::Index(ref arr, ref index) => self.index(arr, index), // TODO: add other expressions. _ => None, @@ -286,7 +296,7 @@ impl<'c, 'cc> ConstEvalLateContext<'c, 'cc> { ty::Uint(ity) => Some(Int(clip(self.lcx.tcx, value, ity))), _ => None, } - }, + } _ => None, } } @@ -304,7 +314,7 @@ impl<'c, 'cc> ConstEvalLateContext<'c, 'cc> { let value = value.checked_neg()?; // clear unused bits Some(Int(unsext(self.lcx.tcx, value, ity))) - }, + } F32(f) => Some(F32(-f)), F64(f) => Some(F64(-f)), _ => None, @@ -340,7 +350,7 @@ impl<'c, 'cc> ConstEvalLateContext<'c, 'cc> { self.needed_resolution = true; } result - }, + } // FIXME: cover all usable cases. _ => None, } @@ -351,7 +361,8 @@ impl<'c, 'cc> ConstEvalLateContext<'c, 'cc> { let index = self.expr(index); match (lhs, index) { - (Some(Constant::Vec(vec)), Some(Constant::Int(index))) => match vec.get(index as usize) { + (Some(Constant::Vec(vec)), Some(Constant::Int(index))) => match vec.get(index as usize) + { Some(Constant::F32(x)) => Some(Constant::F32(*x)), Some(Constant::F64(x)) => Some(Constant::F64(*x)), _ => None, @@ -366,27 +377,24 @@ impl<'c, 'cc> ConstEvalLateContext<'c, 'cc> { } else { None } - }, + } _ => None, } } /// A block can only yield a constant if it only has one constant expression. fn block(&mut self, block: &Block<'_>) -> Option { - if block.stmts.is_empty() { - block.expr.as_ref().and_then(|b| self.expr(b)) - } else { - None - } + if block.stmts.is_empty() { block.expr.as_ref().and_then(|b| self.expr(b)) } else { None } } - fn ifthenelse(&mut self, cond: &Expr<'_>, then: &Expr<'_>, otherwise: Option<&Expr<'_>>) -> Option { + fn ifthenelse( + &mut self, + cond: &Expr<'_>, + then: &Expr<'_>, + otherwise: Option<&Expr<'_>>, + ) -> Option { if let Some(Constant::Bool(b)) = self.expr(cond) { - if b { - self.expr(&*then) - } else { - otherwise.as_ref().and_then(|expr| self.expr(expr)) - } + if b { self.expr(&*then) } else { otherwise.as_ref().and_then(|expr| self.expr(expr)) } } else { None } @@ -396,7 +404,8 @@ impl<'c, 'cc> ConstEvalLateContext<'c, 'cc> { let l = self.expr(left)?; let r = self.expr(right); match (l, r) { - (Constant::Int(l), Some(Constant::Int(r))) => match self.tables.expr_ty_opt(left)?.kind { + (Constant::Int(l), Some(Constant::Int(r))) => match self.tables.expr_ty_opt(left)?.kind + { ty::Int(ity) => { let l = sext(self.lcx.tcx, l, ity); let r = sext(self.lcx.tcx, r, ity); @@ -407,8 +416,12 @@ impl<'c, 'cc> ConstEvalLateContext<'c, 'cc> { BinOpKind::Mul => l.checked_mul(r).map(zext), BinOpKind::Div if r != 0 => l.checked_div(r).map(zext), BinOpKind::Rem if r != 0 => l.checked_rem(r).map(zext), - BinOpKind::Shr => l.checked_shr(r.try_into().expect("invalid shift")).map(zext), - BinOpKind::Shl => l.checked_shl(r.try_into().expect("invalid shift")).map(zext), + BinOpKind::Shr => { + l.checked_shr(r.try_into().expect("invalid shift")).map(zext) + } + BinOpKind::Shl => { + l.checked_shl(r.try_into().expect("invalid shift")).map(zext) + } BinOpKind::BitXor => Some(zext(l ^ r)), BinOpKind::BitOr => Some(zext(l | r)), BinOpKind::BitAnd => Some(zext(l & r)), @@ -420,15 +433,19 @@ impl<'c, 'cc> ConstEvalLateContext<'c, 'cc> { BinOpKind::Gt => Some(Constant::Bool(l > r)), _ => None, } - }, + } ty::Uint(_) => match op.node { BinOpKind::Add => l.checked_add(r).map(Constant::Int), BinOpKind::Sub => l.checked_sub(r).map(Constant::Int), BinOpKind::Mul => l.checked_mul(r).map(Constant::Int), BinOpKind::Div => l.checked_div(r).map(Constant::Int), BinOpKind::Rem => l.checked_rem(r).map(Constant::Int), - BinOpKind::Shr => l.checked_shr(r.try_into().expect("shift too large")).map(Constant::Int), - BinOpKind::Shl => l.checked_shl(r.try_into().expect("shift too large")).map(Constant::Int), + BinOpKind::Shr => { + l.checked_shr(r.try_into().expect("shift too large")).map(Constant::Int) + } + BinOpKind::Shl => { + l.checked_shl(r.try_into().expect("shift too large")).map(Constant::Int) + } BinOpKind::BitXor => Some(Constant::Int(l ^ r)), BinOpKind::BitOr => Some(Constant::Int(l | r)), BinOpKind::BitAnd => Some(Constant::Int(l & r)), @@ -473,12 +490,17 @@ impl<'c, 'cc> ConstEvalLateContext<'c, 'cc> { (l, r) => match (op.node, l, r) { (BinOpKind::And, Constant::Bool(false), _) => Some(Constant::Bool(false)), (BinOpKind::Or, Constant::Bool(true), _) => Some(Constant::Bool(true)), - (BinOpKind::And, Constant::Bool(true), Some(r)) | (BinOpKind::Or, Constant::Bool(false), Some(r)) => { - Some(r) - }, - (BinOpKind::BitXor, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l ^ r)), - (BinOpKind::BitAnd, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l & r)), - (BinOpKind::BitOr, Constant::Bool(l), Some(Constant::Bool(r))) => Some(Constant::Bool(l | r)), + (BinOpKind::And, Constant::Bool(true), Some(r)) + | (BinOpKind::Or, Constant::Bool(false), Some(r)) => Some(r), + (BinOpKind::BitXor, Constant::Bool(l), Some(Constant::Bool(r))) => { + Some(Constant::Bool(l ^ r)) + } + (BinOpKind::BitAnd, Constant::Bool(l), Some(Constant::Bool(r))) => { + Some(Constant::Bool(l & r)) + } + (BinOpKind::BitOr, Constant::Bool(l), Some(Constant::Bool(r))) => { + Some(Constant::Bool(l | r)) + } _ => None, }, } @@ -488,29 +510,30 @@ impl<'c, 'cc> ConstEvalLateContext<'c, 'cc> { pub fn miri_to_const(result: &ty::Const<'_>) -> Option { use rustc_middle::mir::interpret::{ConstValue, Scalar}; match result.val { - ty::ConstKind::Value(ConstValue::Scalar(Scalar::Raw { data: d, .. })) => match result.ty.kind { - ty::Bool => Some(Constant::Bool(d == 1)), - ty::Uint(_) | ty::Int(_) => Some(Constant::Int(d)), - ty::Float(FloatTy::F32) => Some(Constant::F32(f32::from_bits( - d.try_into().expect("invalid f32 bit representation"), - ))), - ty::Float(FloatTy::F64) => Some(Constant::F64(f64::from_bits( - d.try_into().expect("invalid f64 bit representation"), - ))), - ty::RawPtr(type_and_mut) => { - if let ty::Uint(_) = type_and_mut.ty.kind { - return Some(Constant::RawPtr(d)); + ty::ConstKind::Value(ConstValue::Scalar(Scalar::Raw { data: d, .. })) => { + match result.ty.kind { + ty::Bool => Some(Constant::Bool(d == 1)), + ty::Uint(_) | ty::Int(_) => Some(Constant::Int(d)), + ty::Float(FloatTy::F32) => Some(Constant::F32(f32::from_bits( + d.try_into().expect("invalid f32 bit representation"), + ))), + ty::Float(FloatTy::F64) => Some(Constant::F64(f64::from_bits( + d.try_into().expect("invalid f64 bit representation"), + ))), + ty::RawPtr(type_and_mut) => { + if let ty::Uint(_) = type_and_mut.ty.kind { + return Some(Constant::RawPtr(d)); + } + None } - None - }, - // FIXME: implement other conversions. - _ => None, - }, + // FIXME: implement other conversions. + _ => None, + } + } ty::ConstKind::Value(ConstValue::Slice { data, start, end }) => match result.ty.kind { ty::Ref(_, tam, _) => match tam.kind { ty::Str => String::from_utf8( - data.inspect_with_undef_and_ptr_outside_interpreter(start..end) - .to_owned(), + data.inspect_with_undef_and_ptr_outside_interpreter(start..end).to_owned(), ) .ok() .map(Constant::Str), diff --git a/src/tools/clippy/clippy_lints/src/copies.rs b/src/tools/clippy/clippy_lints/src/copies.rs index efd4a31f55960..0f0a7c8cbe44d 100644 --- a/src/tools/clippy/clippy_lints/src/copies.rs +++ b/src/tools/clippy/clippy_lints/src/copies.rs @@ -192,7 +192,7 @@ fn lint_same_then_else(cx: &LateContext<'_, '_>, blocks: &[&Block<'_>]) { /// Implementation of `IFS_SAME_COND`. fn lint_same_cond(cx: &LateContext<'_, '_>, conds: &[&Expr<'_>]) { let hash: &dyn Fn(&&Expr<'_>) -> u64 = &|expr| -> u64 { - let mut h = SpanlessHash::new(cx, cx.tables()); + let mut h = SpanlessHash::new(cx, cx.typeck_results()); h.hash_expr(expr); h.finish() }; @@ -215,7 +215,7 @@ fn lint_same_cond(cx: &LateContext<'_, '_>, conds: &[&Expr<'_>]) { /// Implementation of `SAME_FUNCTIONS_IN_IF_CONDITION`. fn lint_same_fns_in_if_cond(cx: &LateContext<'_, '_>, conds: &[&Expr<'_>]) { let hash: &dyn Fn(&&Expr<'_>) -> u64 = &|expr| -> u64 { - let mut h = SpanlessHash::new(cx, cx.tables()); + let mut h = SpanlessHash::new(cx, cx.typeck_results()); h.hash_expr(expr); h.finish() }; @@ -251,7 +251,7 @@ fn lint_match_arms<'tcx>(cx: &LateContext<'_, 'tcx>, expr: &Expr<'_>) { if let ExprKind::Match(_, ref arms, MatchSource::Normal) = expr.kind { let hash = |&(_, arm): &(usize, &Arm<'_>)| -> u64 { - let mut h = SpanlessHash::new(cx, cx.tables()); + let mut h = SpanlessHash::new(cx, cx.typeck_results()); h.hash_expr(&arm.body); h.finish() }; @@ -320,7 +320,7 @@ fn bindings<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, pat: &Pat<'_>) -> FxHashMap { if let Entry::Vacant(v) = map.entry(ident.name) { - v.insert(cx.tables().pat_ty(pat)); + v.insert(cx.typeck_results().pat_ty(pat)); } if let Some(ref as_pat) = *as_pat { bindings_impl(cx, as_pat, map); diff --git a/src/tools/clippy/clippy_lints/src/default_trait_access.rs b/src/tools/clippy/clippy_lints/src/default_trait_access.rs index 69ae509fb23e9..04438e2963e3d 100644 --- a/src/tools/clippy/clippy_lints/src/default_trait_access.rs +++ b/src/tools/clippy/clippy_lints/src/default_trait_access.rs @@ -5,7 +5,9 @@ use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty; use rustc_session::{declare_lint_pass, declare_tool_lint}; -use crate::utils::{any_parent_is_automatically_derived, match_def_path, paths, span_lint_and_sugg}; +use crate::utils::{ + any_parent_is_automatically_derived, match_def_path, paths, span_lint_and_sugg, +}; declare_clippy_lint! { /// **What it does:** Checks for literal calls to `Default::default()`. @@ -36,7 +38,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for DefaultTraitAccess { if let ExprKind::Call(ref path, ..) = expr.kind; if !any_parent_is_automatically_derived(cx.tcx, expr.hir_id); if let ExprKind::Path(ref qpath) = path.kind; - if let Some(def_id) = cx.tables().qpath_res(qpath, path.hir_id).opt_def_id(); + if let Some(def_id) = cx.typeck_results().qpath_res(qpath, path.hir_id).opt_def_id(); if match_def_path(cx, def_id, &paths::DEFAULT_TRAIT_METHOD); then { match qpath { @@ -54,7 +56,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for DefaultTraitAccess { // TODO: Work out a way to put "whatever the imported way of referencing // this type in this file" rather than a fully-qualified type. - let expr_ty = cx.tables().expr_ty(expr); + let expr_ty = cx.typeck_results().expr_ty(expr); if let ty::Adt(..) = expr_ty.kind { let replacement = format!("{}::default()", expr_ty); span_lint_and_sugg( diff --git a/src/tools/clippy/clippy_lints/src/dereference.rs b/src/tools/clippy/clippy_lints/src/dereference.rs index 1c6cc93690096..2879bd86a800a 100644 --- a/src/tools/clippy/clippy_lints/src/dereference.rs +++ b/src/tools/clippy/clippy_lints/src/dereference.rs @@ -74,7 +74,7 @@ fn lint_deref(cx: &LateContext<'_, '_>, method_name: &str, call_expr: &Expr<'_>, match method_name { "deref" => { if cx.tcx.lang_items().deref_trait().map_or(false, |id| { - implements_trait(cx, cx.tables().expr_ty(&call_expr), id, &[]) + implements_trait(cx, cx.typeck_results().expr_ty(&call_expr), id, &[]) }) { span_lint_and_sugg( cx, @@ -89,7 +89,7 @@ fn lint_deref(cx: &LateContext<'_, '_>, method_name: &str, call_expr: &Expr<'_>, }, "deref_mut" => { if cx.tcx.lang_items().deref_mut_trait().map_or(false, |id| { - implements_trait(cx, cx.tables().expr_ty(&call_expr), id, &[]) + implements_trait(cx, cx.typeck_results().expr_ty(&call_expr), id, &[]) }) { span_lint_and_sugg( cx, diff --git a/src/tools/clippy/clippy_lints/src/drop_forget_ref.rs b/src/tools/clippy/clippy_lints/src/drop_forget_ref.rs index 014873eb13255..765aa09ebba4b 100644 --- a/src/tools/clippy/clippy_lints/src/drop_forget_ref.rs +++ b/src/tools/clippy/clippy_lints/src/drop_forget_ref.rs @@ -119,7 +119,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for DropForgetRef { let lint; let msg; let arg = &args[0]; - let arg_ty = cx.tables().expr_ty(arg); + let arg_ty = cx.typeck_results().expr_ty(arg); if let ty::Ref(..) = arg_ty.kind { if match_def_path(cx, def_id, &paths::DROP) { diff --git a/src/tools/clippy/clippy_lints/src/duration_subsec.rs b/src/tools/clippy/clippy_lints/src/duration_subsec.rs index 5eb320ceca247..90d533629228e 100644 --- a/src/tools/clippy/clippy_lints/src/duration_subsec.rs +++ b/src/tools/clippy/clippy_lints/src/duration_subsec.rs @@ -43,8 +43,8 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for DurationSubsec { if_chain! { if let ExprKind::Binary(Spanned { node: BinOpKind::Div, .. }, ref left, ref right) = expr.kind; if let ExprKind::MethodCall(ref method_path, _ , ref args, _) = left.kind; - if match_type(cx, walk_ptrs_ty(cx.tables().expr_ty(&args[0])), &paths::DURATION); - if let Some((Constant::Int(divisor), _)) = constant(cx, cx.tables(), right); + if match_type(cx, walk_ptrs_ty(cx.typeck_results().expr_ty(&args[0])), &paths::DURATION); + if let Some((Constant::Int(divisor), _)) = constant(cx, cx.typeck_results(), right); then { let suggested_fn = match (method_path.ident.as_str().as_ref(), divisor) { ("subsec_micros", 1_000) | ("subsec_nanos", 1_000_000) => "subsec_millis", diff --git a/src/tools/clippy/clippy_lints/src/entry.rs b/src/tools/clippy/clippy_lints/src/entry.rs index e37e23b8944d7..0f647a2a2e8f8 100644 --- a/src/tools/clippy/clippy_lints/src/entry.rs +++ b/src/tools/clippy/clippy_lints/src/entry.rs @@ -1,5 +1,7 @@ use crate::utils::SpanlessEq; -use crate::utils::{get_item_name, higher, is_type_diagnostic_item, match_type, paths, snippet, snippet_opt}; +use crate::utils::{ + get_item_name, higher, is_type_diagnostic_item, match_type, paths, snippet, snippet_opt, +}; use crate::utils::{snippet_with_applicability, span_lint_and_then, walk_ptrs_ty}; use if_chain::if_chain; use rustc_errors::Applicability; @@ -69,27 +71,15 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for HashMapPass { // XXXManishearth we can also check for if/else blocks containing `None`. }; - let mut visitor = InsertVisitor { - cx, - span: expr.span, - ty, - map, - key, - sole_expr, - }; + let mut visitor = + InsertVisitor { cx, span: expr.span, ty, map, key, sole_expr }; walk_expr(&mut visitor, &**then_block); } } else if let Some(ref else_block) = *else_block { if let Some((ty, map, key)) = check_cond(cx, check) { - let mut visitor = InsertVisitor { - cx, - span: expr.span, - ty, - map, - key, - sole_expr: false, - }; + let mut visitor = + InsertVisitor { cx, span: expr.span, ty, map, key, sole_expr: false }; walk_expr(&mut visitor, else_block); } @@ -109,7 +99,7 @@ fn check_cond<'a, 'tcx, 'b>( if let ExprKind::AddrOf(BorrowKind::Ref, _, ref key) = params[1].kind; then { let map = ¶ms[0]; - let obj_ty = walk_ptrs_ty(cx.tables().expr_ty(map)); + let obj_ty = walk_ptrs_ty(cx.typeck_results().expr_ty(map)); return if match_type(cx, obj_ty, &paths::BTREEMAP) { Some(("BTreeMap", map, key)) diff --git a/src/tools/clippy/clippy_lints/src/eq_op.rs b/src/tools/clippy/clippy_lints/src/eq_op.rs index 98757624a13b5..01676ceca0526 100644 --- a/src/tools/clippy/clippy_lints/src/eq_op.rs +++ b/src/tools/clippy/clippy_lints/src/eq_op.rs @@ -1,5 +1,6 @@ use crate::utils::{ - implements_trait, in_macro, is_copy, multispan_sugg, snippet, span_lint, span_lint_and_then, SpanlessEq, + implements_trait, in_macro, is_copy, multispan_sugg, snippet, span_lint, span_lint_and_then, + SpanlessEq, }; use rustc_errors::Applicability; use rustc_hir::{BinOp, BinOpKind, BorrowKind, Expr, ExprKind}; @@ -94,21 +95,26 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for EqOp { BinOpKind::Ne | BinOpKind::Eq => (cx.tcx.lang_items().eq_trait(), true), BinOpKind::Lt | BinOpKind::Le | BinOpKind::Ge | BinOpKind::Gt => { (cx.tcx.lang_items().partial_ord_trait(), true) - }, + } }; if let Some(trait_id) = trait_id { #[allow(clippy::match_same_arms)] match (&left.kind, &right.kind) { // do not suggest to dereference literals - (&ExprKind::Lit(..), _) | (_, &ExprKind::Lit(..)) => {}, + (&ExprKind::Lit(..), _) | (_, &ExprKind::Lit(..)) => {} // &foo == &bar - (&ExprKind::AddrOf(BorrowKind::Ref, _, ref l), &ExprKind::AddrOf(BorrowKind::Ref, _, ref r)) => { - let lty = cx.tables().expr_ty(l); - let rty = cx.tables().expr_ty(r); + ( + &ExprKind::AddrOf(BorrowKind::Ref, _, ref l), + &ExprKind::AddrOf(BorrowKind::Ref, _, ref r), + ) => { + let lty = cx.typeck_results().expr_ty(l); + let rty = cx.typeck_results().expr_ty(r); let lcpy = is_copy(cx, lty); let rcpy = is_copy(cx, rty); // either operator autorefs or both args are copyable - if (requires_ref || (lcpy && rcpy)) && implements_trait(cx, lty, trait_id, &[rty.into()]) { + if (requires_ref || (lcpy && rcpy)) + && implements_trait(cx, lty, trait_id, &[rty.into()]) + { span_lint_and_then( cx, OP_REF, @@ -126,7 +132,12 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for EqOp { ) } else if lcpy && !rcpy - && implements_trait(cx, lty, trait_id, &[cx.tables().expr_ty(right).into()]) + && implements_trait( + cx, + lty, + trait_id, + &[cx.typeck_results().expr_ty(right).into()], + ) { span_lint_and_then( cx, @@ -145,7 +156,12 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for EqOp { ) } else if !lcpy && rcpy - && implements_trait(cx, cx.tables().expr_ty(left), trait_id, &[rty.into()]) + && implements_trait( + cx, + cx.typeck_results().expr_ty(left), + trait_id, + &[rty.into()], + ) { span_lint_and_then( cx, @@ -163,13 +179,18 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for EqOp { }, ) } - }, + } // &foo == bar (&ExprKind::AddrOf(BorrowKind::Ref, _, ref l), _) => { - let lty = cx.tables().expr_ty(l); + let lty = cx.typeck_results().expr_ty(l); let lcpy = is_copy(cx, lty); if (requires_ref || lcpy) - && implements_trait(cx, lty, trait_id, &[cx.tables().expr_ty(right).into()]) + && implements_trait( + cx, + lty, + trait_id, + &[cx.typeck_results().expr_ty(right).into()], + ) { span_lint_and_then( cx, @@ -187,26 +208,37 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for EqOp { }, ) } - }, + } // foo == &bar (_, &ExprKind::AddrOf(BorrowKind::Ref, _, ref r)) => { - let rty = cx.tables().expr_ty(r); + let rty = cx.typeck_results().expr_ty(r); let rcpy = is_copy(cx, rty); if (requires_ref || rcpy) - && implements_trait(cx, cx.tables().expr_ty(left), trait_id, &[rty.into()]) + && implements_trait( + cx, + cx.typeck_results().expr_ty(left), + trait_id, + &[rty.into()], + ) { - span_lint_and_then(cx, OP_REF, e.span, "taken reference of right operand", |diag| { - let rsnip = snippet(cx, r.span, "...").to_string(); - diag.span_suggestion( - right.span, - "use the right value directly", - rsnip, - Applicability::MaybeIncorrect, // FIXME #2597 - ); - }) + span_lint_and_then( + cx, + OP_REF, + e.span, + "taken reference of right operand", + |diag| { + let rsnip = snippet(cx, r.span, "...").to_string(); + diag.span_suggestion( + right.span, + "use the right value directly", + rsnip, + Applicability::MaybeIncorrect, // FIXME #2597 + ); + }, + ) } - }, - _ => {}, + } + _ => {} } } } diff --git a/src/tools/clippy/clippy_lints/src/erasing_op.rs b/src/tools/clippy/clippy_lints/src/erasing_op.rs index 804a9c1904b73..2ea268f429297 100644 --- a/src/tools/clippy/clippy_lints/src/erasing_op.rs +++ b/src/tools/clippy/clippy_lints/src/erasing_op.rs @@ -48,7 +48,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ErasingOp { } fn check(cx: &LateContext<'_, '_>, e: &Expr<'_>, span: Span) { - if let Some(Constant::Int(0)) = constant_simple(cx, cx.tables(), e) { + if let Some(Constant::Int(0)) = constant_simple(cx, cx.typeck_results(), e) { span_lint( cx, ERASING_OP, diff --git a/src/tools/clippy/clippy_lints/src/escape.rs b/src/tools/clippy/clippy_lints/src/escape.rs index bb74f193a48e7..3d05748398307 100644 --- a/src/tools/clippy/clippy_lints/src/escape.rs +++ b/src/tools/clippy/clippy_lints/src/escape.rs @@ -84,7 +84,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BoxedLocal { let fn_def_id = cx.tcx.hir().local_def_id(hir_id); cx.tcx.infer_ctxt().enter(|infcx| { - ExprUseVisitor::new(&mut v, &infcx, fn_def_id, cx.param_env, cx.tables()).consume_body(body); + ExprUseVisitor::new(&mut v, &infcx, fn_def_id, cx.param_env, cx.typeck_results()).consume_body(body); }); for node in v.set { diff --git a/src/tools/clippy/clippy_lints/src/eta_reduction.rs b/src/tools/clippy/clippy_lints/src/eta_reduction.rs index 0ac8b95de8d61..8edd0c393829d 100644 --- a/src/tools/clippy/clippy_lints/src/eta_reduction.rs +++ b/src/tools/clippy/clippy_lints/src/eta_reduction.rs @@ -7,8 +7,8 @@ use rustc_middle::ty::{self, Ty}; use rustc_session::{declare_lint_pass, declare_tool_lint}; use crate::utils::{ - implements_trait, is_adjusted, iter_input_pats, snippet_opt, span_lint_and_sugg, span_lint_and_then, - type_is_unsafe_function, + implements_trait, is_adjusted, iter_input_pats, snippet_opt, span_lint_and_sugg, + span_lint_and_then, type_is_unsafe_function, }; declare_clippy_lint! { @@ -75,7 +75,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for EtaReduction { for arg in args { check_closure(cx, arg) } - }, + } _ => (), } } @@ -97,7 +97,7 @@ fn check_closure(cx: &LateContext<'_, '_>, expr: &Expr<'_>) { // Are the expression or the arguments type-adjusted? Then we need the closure if !(is_adjusted(cx, ex) || args.iter().any(|arg| is_adjusted(cx, arg))); - let fn_ty = cx.tables().expr_ty(caller); + let fn_ty = cx.typeck_results().expr_ty(caller); if matches!(fn_ty.kind, ty::FnDef(_, _) | ty::FnPtr(_) | ty::Closure(_, _)); @@ -128,7 +128,7 @@ fn check_closure(cx: &LateContext<'_, '_>, expr: &Expr<'_>) { // Are the expression or the arguments type-adjusted? Then we need the closure if !(is_adjusted(cx, ex) || args.iter().skip(1).any(|arg| is_adjusted(cx, arg))); - let method_def_id = cx.tables().type_dependent_def_id(ex.hir_id).unwrap(); + let method_def_id = cx.typeck_results().type_dependent_def_id(ex.hir_id).unwrap(); if !type_is_unsafe_function(cx, cx.tcx.type_of(method_def_id)); if compare_inputs(&mut iter_input_pats(decl, body), &mut args.iter()); @@ -151,9 +151,13 @@ fn check_closure(cx: &LateContext<'_, '_>, expr: &Expr<'_>) { } /// Tries to determine the type for universal function call to be used instead of the closure -fn get_ufcs_type_name(cx: &LateContext<'_, '_>, method_def_id: def_id::DefId, self_arg: &Expr<'_>) -> Option { +fn get_ufcs_type_name( + cx: &LateContext<'_, '_>, + method_def_id: def_id::DefId, + self_arg: &Expr<'_>, +) -> Option { let expected_type_of_self = &cx.tcx.fn_sig(method_def_id).inputs_and_output().skip_binder()[0]; - let actual_type_of_self = &cx.tables().node_type(self_arg.hir_id); + let actual_type_of_self = &cx.typeck_results().node_type(self_arg.hir_id); if let Some(trait_id) = cx.tcx.trait_of_item(method_def_id) { if match_borrow_depth(expected_type_of_self, &actual_type_of_self) @@ -174,7 +178,9 @@ fn get_ufcs_type_name(cx: &LateContext<'_, '_>, method_def_id: def_id::DefId, se fn match_borrow_depth(lhs: Ty<'_>, rhs: Ty<'_>) -> bool { match (&lhs.kind, &rhs.kind) { - (ty::Ref(_, t1, mut1), ty::Ref(_, t2, mut2)) => mut1 == mut2 && match_borrow_depth(&t1, &t2), + (ty::Ref(_, t1, mut1), ty::Ref(_, t2, mut2)) => { + mut1 == mut2 && match_borrow_depth(&t1, &t2) + } (l, r) => match (l, r) { (ty::Ref(_, _, _), _) | (_, ty::Ref(_, _, _)) => false, (_, _) => true, @@ -190,7 +196,9 @@ fn match_types(lhs: Ty<'_>, rhs: Ty<'_>) -> bool { | (ty::Uint(_), ty::Uint(_)) | (ty::Str, ty::Str) => true, (ty::Ref(_, t1, mut1), ty::Ref(_, t2, mut2)) => mut1 == mut2 && match_types(t1, t2), - (ty::Array(t1, _), ty::Array(t2, _)) | (ty::Slice(t1), ty::Slice(t2)) => match_types(t1, t2), + (ty::Array(t1, _), ty::Array(t2, _)) | (ty::Slice(t1), ty::Slice(t2)) => { + match_types(t1, t2) + } (ty::Adt(def1, _), ty::Adt(def2, _)) => def1 == def2, (_, _) => false, } diff --git a/src/tools/clippy/clippy_lints/src/eval_order_dependence.rs b/src/tools/clippy/clippy_lints/src/eval_order_dependence.rs index 04af6c2c1f85d..57d26087111ac 100644 --- a/src/tools/clippy/clippy_lints/src/eval_order_dependence.rs +++ b/src/tools/clippy/clippy_lints/src/eval_order_dependence.rs @@ -1,7 +1,9 @@ use crate::utils::{get_parent_expr, span_lint, span_lint_and_note}; use if_chain::if_chain; use rustc_hir::intravisit::{walk_expr, NestedVisitorMap, Visitor}; -use rustc_hir::{def, BinOpKind, Block, Expr, ExprKind, Guard, HirId, Local, Node, QPath, Stmt, StmtKind}; +use rustc_hir::{ + def, BinOpKind, Block, Expr, ExprKind, Guard, HirId, Local, Node, QPath, Stmt, StmtKind, +}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::hir::map::Map; use rustc_middle::ty; @@ -75,20 +77,18 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for EvalOrderDependence { if let ExprKind::Path(ref qpath) = lhs.kind { if let QPath::Resolved(_, ref path) = *qpath { if path.segments.len() == 1 { - if let def::Res::Local(var) = cx.tables().qpath_res(qpath, lhs.hir_id) { - let mut visitor = ReadVisitor { - cx, - var, - write_expr: expr, - last_expr: expr, - }; + if let def::Res::Local(var) = + cx.typeck_results().qpath_res(qpath, lhs.hir_id) + { + let mut visitor = + ReadVisitor { cx, var, write_expr: expr, last_expr: expr }; check_for_unsequenced_reads(&mut visitor); } } } } - }, - _ => {}, + } + _ => {} } } fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx Stmt<'_>) { @@ -97,9 +97,11 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for EvalOrderDependence { if let Local { init: Some(ref e), .. } = **local { DivergenceVisitor { cx }.visit_expr(e); } - }, - StmtKind::Expr(ref e) | StmtKind::Semi(ref e) => DivergenceVisitor { cx }.maybe_walk_expr(e), - StmtKind::Item(..) => {}, + } + StmtKind::Expr(ref e) | StmtKind::Semi(ref e) => { + DivergenceVisitor { cx }.maybe_walk_expr(e) + } + StmtKind::Item(..) => {} } } } @@ -111,7 +113,7 @@ struct DivergenceVisitor<'a, 'tcx> { impl<'a, 'tcx> DivergenceVisitor<'a, 'tcx> { fn maybe_walk_expr(&mut self, e: &'tcx Expr<'_>) { match e.kind { - ExprKind::Closure(..) => {}, + ExprKind::Closure(..) => {} ExprKind::Match(ref e, arms, _) => { self.visit_expr(e); for arm in arms { @@ -121,7 +123,7 @@ impl<'a, 'tcx> DivergenceVisitor<'a, 'tcx> { // make sure top level arm expressions aren't linted self.maybe_walk_expr(&*arm.body); } - }, + } _ => walk_expr(self, e), } } @@ -135,30 +137,33 @@ impl<'a, 'tcx> Visitor<'tcx> for DivergenceVisitor<'a, 'tcx> { fn visit_expr(&mut self, e: &'tcx Expr<'_>) { match e.kind { - ExprKind::Continue(_) | ExprKind::Break(_, _) | ExprKind::Ret(_) => self.report_diverging_sub_expr(e), + ExprKind::Continue(_) | ExprKind::Break(_, _) | ExprKind::Ret(_) => { + self.report_diverging_sub_expr(e) + } ExprKind::Call(ref func, _) => { - let typ = self.cx.tables().expr_ty(func); + let typ = self.cx.typeck_results().expr_ty(func); match typ.kind { ty::FnDef(..) | ty::FnPtr(_) => { let sig = typ.fn_sig(self.cx.tcx); - if let ty::Never = self.cx.tcx.erase_late_bound_regions(&sig).output().kind { + if let ty::Never = self.cx.tcx.erase_late_bound_regions(&sig).output().kind + { self.report_diverging_sub_expr(e); } - }, - _ => {}, + } + _ => {} } - }, + } ExprKind::MethodCall(..) => { - let borrowed_table = self.cx.tables(); + let borrowed_table = self.cx.typeck_results(); if borrowed_table.expr_ty(e).is_never() { self.report_diverging_sub_expr(e); } - }, + } _ => { // do not lint expressions referencing objects of type `!`, as that required a // diverging expression // to begin with - }, + } } self.maybe_walk_expr(e); } @@ -203,12 +208,12 @@ fn check_for_unsequenced_reads(vis: &mut ReadVisitor<'_, '_>) { Node::Item(_) => { // We reached the top of the function, stop. break; - }, + } _ => StopEarly::KeepGoing, }; match stop_early { StopEarly::Stop => break, - StopEarly::KeepGoing => {}, + StopEarly::KeepGoing => {} } cur_id = parent_id; @@ -238,7 +243,7 @@ fn check_expr<'a, 'tcx>(vis: &mut ReadVisitor<'a, 'tcx>, expr: &'tcx Expr<'_>) - | ExprKind::Repeat(_, _) | ExprKind::Struct(_, _, _) => { walk_expr(vis, expr); - }, + } ExprKind::Binary(op, _, _) | ExprKind::AssignOp(op, _, _) => { if op.node == BinOpKind::And || op.node == BinOpKind::Or { // x && y and x || y always evaluate x first, so these are @@ -246,7 +251,7 @@ fn check_expr<'a, 'tcx>(vis: &mut ReadVisitor<'a, 'tcx>, expr: &'tcx Expr<'_>) - } else { walk_expr(vis, expr); } - }, + } ExprKind::Closure(_, _, _, _, _) => { // Either // @@ -259,10 +264,10 @@ fn check_expr<'a, 'tcx>(vis: &mut ReadVisitor<'a, 'tcx>, expr: &'tcx Expr<'_>) - // // This is also the only place we need to stop early (grrr). return StopEarly::Stop; - }, + } // All other expressions either have only one child or strictly // sequence the evaluation order of their sub-expressions. - _ => {}, + _ => {} } vis.last_expr = expr; @@ -275,10 +280,9 @@ fn check_stmt<'a, 'tcx>(vis: &mut ReadVisitor<'a, 'tcx>, stmt: &'tcx Stmt<'_>) - StmtKind::Expr(ref expr) | StmtKind::Semi(ref expr) => check_expr(vis, expr), // If the declaration is of a local variable, check its initializer // expression if it has one. Otherwise, keep going. - StmtKind::Local(ref local) => local - .init - .as_ref() - .map_or(StopEarly::KeepGoing, |expr| check_expr(vis, expr)), + StmtKind::Local(ref local) => { + local.init.as_ref().map_or(StopEarly::KeepGoing, |expr| check_expr(vis, expr)) + } _ => StopEarly::KeepGoing, } } @@ -309,7 +313,7 @@ impl<'a, 'tcx> Visitor<'tcx> for ReadVisitor<'a, 'tcx> { if_chain! { if let QPath::Resolved(None, ref path) = *qpath; if path.segments.len() == 1; - if let def::Res::Local(local_id) = self.cx.tables().qpath_res(qpath, expr.hir_id); + if let def::Res::Local(local_id) = self.cx.typeck_results().qpath_res(qpath, expr.hir_id); if local_id == self.var; // Check that this is a read, not a write. if !is_in_assignment_position(self.cx, expr); diff --git a/src/tools/clippy/clippy_lints/src/fallible_impl_from.rs b/src/tools/clippy/clippy_lints/src/fallible_impl_from.rs index 92812816461c5..d433a4a394299 100644 --- a/src/tools/clippy/clippy_lints/src/fallible_impl_from.rs +++ b/src/tools/clippy/clippy_lints/src/fallible_impl_from.rs @@ -1,6 +1,7 @@ use crate::utils::paths::{BEGIN_PANIC, BEGIN_PANIC_FMT, FROM_TRAIT}; use crate::utils::{ - is_expn_of, is_type_diagnostic_item, match_def_path, method_chain_args, span_lint_and_then, walk_ptrs_ty, + is_expn_of, is_type_diagnostic_item, match_def_path, method_chain_args, span_lint_and_then, + walk_ptrs_ty, }; use if_chain::if_chain; use rustc_hir as hir; @@ -67,13 +68,17 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for FallibleImplFrom { } } -fn lint_impl_body<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, impl_span: Span, impl_items: &[hir::ImplItemRef<'_>]) { +fn lint_impl_body<'a, 'tcx>( + cx: &LateContext<'a, 'tcx>, + impl_span: Span, + impl_items: &[hir::ImplItemRef<'_>], +) { use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor}; use rustc_hir::{Expr, ExprKind, ImplItemKind, QPath}; struct FindPanicUnwrap<'a, 'tcx> { lcx: &'a LateContext<'a, 'tcx>, - tables: &'tcx ty::TypeckTables<'tcx>, + typeck_results: &'tcx ty::TypeckResults<'tcx>, result: Vec, } @@ -96,7 +101,7 @@ fn lint_impl_body<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, impl_span: Span, impl_it // check for `unwrap` if let Some(arglists) = method_chain_args(expr, &["unwrap"]) { - let reciever_ty = walk_ptrs_ty(self.tables.expr_ty(&arglists[0][0])); + let reciever_ty = walk_ptrs_ty(self.typeck_results.expr_ty(&arglists[0][0])); if is_type_diagnostic_item(self.lcx, reciever_ty, sym!(option_type)) || is_type_diagnostic_item(self.lcx, reciever_ty, sym!(result_type)) { @@ -124,7 +129,7 @@ fn lint_impl_body<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, impl_span: Span, impl_it let impl_item_def_id = cx.tcx.hir().local_def_id(impl_item.id.hir_id); let mut fpu = FindPanicUnwrap { lcx: cx, - tables: cx.tcx.typeck_tables_of(impl_item_def_id), + typeck_results: cx.tcx.typeck(impl_item_def_id), result: Vec::new(), }; fpu.visit_expr(&body.value); diff --git a/src/tools/clippy/clippy_lints/src/float_literal.rs b/src/tools/clippy/clippy_lints/src/float_literal.rs index cd3d443ec58ef..d8456d2a3a0d3 100644 --- a/src/tools/clippy/clippy_lints/src/float_literal.rs +++ b/src/tools/clippy/clippy_lints/src/float_literal.rs @@ -61,7 +61,7 @@ declare_lint_pass!(FloatLiteral => [EXCESSIVE_PRECISION, LOSSY_FLOAT_LITERAL]); impl<'a, 'tcx> LateLintPass<'a, 'tcx> for FloatLiteral { fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr<'_>) { if_chain! { - let ty = cx.tables().expr_ty(expr); + let ty = cx.typeck_results().expr_ty(expr); if let ty::Float(fty) = ty.kind; if let hir::ExprKind::Lit(ref lit) = expr.kind; if let LitKind::Float(sym, lit_float_ty) = lit.node; @@ -140,17 +140,13 @@ fn max_digits(fty: FloatTy) -> u32 { #[must_use] fn count_digits(s: &str) -> usize { // Note that s does not contain the f32/64 suffix, and underscores have been stripped - s.chars() - .filter(|c| *c != '-' && *c != '.') - .take_while(|c| *c != 'e' && *c != 'E') - .fold(0, |count, c| { + s.chars().filter(|c| *c != '-' && *c != '.').take_while(|c| *c != 'e' && *c != 'E').fold( + 0, + |count, c| { // leading zeros - if c == '0' && count == 0 { - count - } else { - count + 1 - } - }) + if c == '0' && count == 0 { count } else { count + 1 } + }, + ) } enum FloatFormat { diff --git a/src/tools/clippy/clippy_lints/src/floating_point_arithmetic.rs b/src/tools/clippy/clippy_lints/src/floating_point_arithmetic.rs index 76713cb1afc41..0dece24e611c8 100644 --- a/src/tools/clippy/clippy_lints/src/floating_point_arithmetic.rs +++ b/src/tools/clippy/clippy_lints/src/floating_point_arithmetic.rs @@ -112,7 +112,7 @@ declare_lint_pass!(FloatingPointArithmetic => [ // Returns the specialized log method for a given base if base is constant // and is one of 2, 10 and e fn get_specialized_log_method(cx: &LateContext<'_, '_>, base: &Expr<'_>) -> Option<&'static str> { - if let Some((value, _)) = constant(cx, cx.tables(), base) { + if let Some((value, _)) = constant(cx, cx.typeck_results(), base) { if F32(2.0) == value || F64(2.0) == value { return Some("log2"); } else if F32(10.0) == value || F64(10.0) == value { @@ -136,7 +136,7 @@ fn prepare_receiver_sugg<'a>(cx: &LateContext<'_, '_>, mut expr: &'a Expr<'a>) - if_chain! { // if the expression is a float literal and it is unsuffixed then // add a suffix so the suggestion is valid and unambiguous - if let ty::Float(float_ty) = cx.tables().expr_ty(expr).kind; + if let ty::Float(float_ty) = cx.typeck_results().expr_ty(expr).kind; if let ExprKind::Lit(lit) = &expr.kind; if let ast::LitKind::Float(sym, ast::LitFloatType::Unsuffixed) = lit.node; then { @@ -180,15 +180,11 @@ fn check_log_base(cx: &LateContext<'_, '_>, expr: &Expr<'_>, args: &[Expr<'_>]) // TODO: Lint expressions of the form `(x + y).ln()` where y > 1 and // suggest usage of `(x + (y - 1)).ln_1p()` instead fn check_ln1p(cx: &LateContext<'_, '_>, expr: &Expr<'_>, args: &[Expr<'_>]) { - if let ExprKind::Binary( - Spanned { - node: BinOpKind::Add, .. - }, - lhs, - rhs, - ) = &args[0].kind - { - let recv = match (constant(cx, cx.tables(), lhs), constant(cx, cx.tables(), rhs)) { + if let ExprKind::Binary(Spanned { node: BinOpKind::Add, .. }, lhs, rhs) = &args[0].kind { + let recv = match ( + constant(cx, cx.typeck_results(), lhs), + constant(cx, cx.typeck_results(), rhs), + ) { (Some((value, _)), _) if F32(1.0) == value || F64(1.0) == value => rhs, (_, Some((value, _))) if F32(1.0) == value || F64(1.0) == value => lhs, _ => return, @@ -219,21 +215,21 @@ fn get_integer_from_float_constant(value: &Constant) -> Option { } else { None } - }, + } F64(num) if num.fract() == 0.0 => { if (-2_147_483_648.0..2_147_483_648.0).contains(num) { Some(num.round() as i32) } else { None } - }, + } _ => None, } } fn check_powf(cx: &LateContext<'_, '_>, expr: &Expr<'_>, args: &[Expr<'_>]) { // Check receiver - if let Some((value, _)) = constant(cx, cx.tables(), &args[0]) { + if let Some((value, _)) = constant(cx, cx.typeck_results(), &args[0]) { let method = if F32(f32_consts::E) == value || F64(f64_consts::E) == value { "exp" } else if F32(2.0) == value || F64(2.0) == value { @@ -254,7 +250,7 @@ fn check_powf(cx: &LateContext<'_, '_>, expr: &Expr<'_>, args: &[Expr<'_>]) { } // Check argument - if let Some((value, _)) = constant(cx, cx.tables(), &args[1]) { + if let Some((value, _)) = constant(cx, cx.typeck_results(), &args[1]) { let (lint, help, suggestion) = if F32(1.0 / 2.0) == value || F64(1.0 / 2.0) == value { ( SUBOPTIMAL_FLOPS, @@ -298,11 +294,11 @@ fn check_powf(cx: &LateContext<'_, '_>, expr: &Expr<'_>, args: &[Expr<'_>]) { fn check_expm1(cx: &LateContext<'_, '_>, expr: &Expr<'_>) { if_chain! { if let ExprKind::Binary(Spanned { node: BinOpKind::Sub, .. }, ref lhs, ref rhs) = expr.kind; - if cx.tables().expr_ty(lhs).is_floating_point(); - if let Some((value, _)) = constant(cx, cx.tables(), rhs); + if cx.typeck_results().expr_ty(lhs).is_floating_point(); + if let Some((value, _)) = constant(cx, cx.typeck_results(), rhs); if F32(1.0) == value || F64(1.0) == value; if let ExprKind::MethodCall(ref path, _, ref method_args, _) = lhs.kind; - if cx.tables().expr_ty(&method_args[0]).is_floating_point(); + if cx.typeck_results().expr_ty(&method_args[0]).is_floating_point(); if path.ident.name.as_str() == "exp"; then { span_lint_and_sugg( @@ -321,11 +317,14 @@ fn check_expm1(cx: &LateContext<'_, '_>, expr: &Expr<'_>) { } } -fn is_float_mul_expr<'a>(cx: &LateContext<'_, '_>, expr: &'a Expr<'a>) -> Option<(&'a Expr<'a>, &'a Expr<'a>)> { +fn is_float_mul_expr<'a>( + cx: &LateContext<'_, '_>, + expr: &'a Expr<'a>, +) -> Option<(&'a Expr<'a>, &'a Expr<'a>)> { if_chain! { if let ExprKind::Binary(Spanned { node: BinOpKind::Mul, .. }, ref lhs, ref rhs) = &expr.kind; - if cx.tables().expr_ty(lhs).is_floating_point(); - if cx.tables().expr_ty(rhs).is_floating_point(); + if cx.typeck_results().expr_ty(lhs).is_floating_point(); + if cx.typeck_results().expr_ty(rhs).is_floating_point(); then { return Some((lhs, rhs)); } @@ -336,14 +335,7 @@ fn is_float_mul_expr<'a>(cx: &LateContext<'_, '_>, expr: &'a Expr<'a>) -> Option // TODO: Fix rust-lang/rust-clippy#4735 fn check_mul_add(cx: &LateContext<'_, '_>, expr: &Expr<'_>) { - if let ExprKind::Binary( - Spanned { - node: BinOpKind::Add, .. - }, - lhs, - rhs, - ) = &expr.kind - { + if let ExprKind::Binary(Spanned { node: BinOpKind::Add, .. }, lhs, rhs) = &expr.kind { let (recv, arg1, arg2) = if let Some((inner_lhs, inner_rhs)) = is_float_mul_expr(cx, lhs) { (inner_lhs, inner_rhs, rhs) } else if let Some((inner_lhs, inner_rhs)) = is_float_mul_expr(cx, rhs) { @@ -404,7 +396,7 @@ fn are_exprs_equal(cx: &LateContext<'_, '_>, expr1: &Expr<'_>, expr2: &Expr<'_>) /// Returns true iff expr is some zero literal fn is_zero(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> bool { - match constant_simple(cx, cx.tables(), expr) { + match constant_simple(cx, cx.typeck_results(), expr) { Some(Constant::Int(i)) => i == 0, Some(Constant::F32(f)) => f == 0.0, Some(Constant::F64(f)) => f == 0.0, @@ -418,7 +410,11 @@ fn is_zero(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> bool { /// one of the two expressions /// If the two expressions are not negations of each other, then it /// returns None. -fn are_negated<'a>(cx: &LateContext<'_, '_>, expr1: &'a Expr<'a>, expr2: &'a Expr<'a>) -> Option<(bool, &'a Expr<'a>)> { +fn are_negated<'a>( + cx: &LateContext<'_, '_>, + expr1: &'a Expr<'a>, + expr2: &'a Expr<'a>, +) -> Option<(bool, &'a Expr<'a>)> { if let ExprKind::Unary(UnOp::UnNeg, expr1_negated) = &expr1.kind { if are_exprs_equal(cx, expr1_negated, expr2) { return Some((false, expr2)); @@ -482,14 +478,14 @@ fn check_custom_abs(cx: &LateContext<'_, '_>, expr: &Expr<'_>) { impl<'a, 'tcx> LateLintPass<'a, 'tcx> for FloatingPointArithmetic { fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) { if let ExprKind::MethodCall(ref path, _, args, _) = &expr.kind { - let recv_ty = cx.tables().expr_ty(&args[0]); + let recv_ty = cx.typeck_results().expr_ty(&args[0]); if recv_ty.is_floating_point() { match &*path.ident.name.as_str() { "ln" => check_ln1p(cx, expr, args), "log" => check_log_base(cx, expr, args), "powf" => check_powf(cx, expr, args), - _ => {}, + _ => {} } } } else { diff --git a/src/tools/clippy/clippy_lints/src/format.rs b/src/tools/clippy/clippy_lints/src/format.rs index 58cf0027ea4d4..4fd8afe215ff8 100644 --- a/src/tools/clippy/clippy_lints/src/format.rs +++ b/src/tools/clippy/clippy_lints/src/format.rs @@ -1,7 +1,7 @@ use crate::utils::paths; use crate::utils::{ - is_expn_of, is_type_diagnostic_item, last_path_segment, match_def_path, match_function_call, snippet, - span_lint_and_then, walk_ptrs_ty, + is_expn_of, is_type_diagnostic_item, last_path_segment, match_def_path, match_function_call, + snippet, span_lint_and_then, walk_ptrs_ty, }; use if_chain::if_chain; use rustc_ast::ast::LitKind; @@ -88,13 +88,13 @@ fn on_argumentv1_new<'a, 'tcx>( // matches `core::fmt::Display::fmt` if args.len() == 2; if let ExprKind::Path(ref qpath) = args[1].kind; - if let Some(did) = cx.tables().qpath_res(qpath, args[1].hir_id).opt_def_id(); + if let Some(did) = cx.typeck_results().qpath_res(qpath, args[1].hir_id).opt_def_id(); if match_def_path(cx, did, &paths::DISPLAY_FMT_METHOD); // check `(arg0,)` in match block if let PatKind::Tuple(ref pats, None) = arms[0].pat.kind; if pats.len() == 1; then { - let ty = walk_ptrs_ty(cx.tables().pat_ty(&pats[0])); + let ty = walk_ptrs_ty(cx.typeck_results().pat_ty(&pats[0])); if ty.kind != rustc_middle::ty::Str && !is_type_diagnostic_item(cx, ty, sym!(string_type)) { return None; } diff --git a/src/tools/clippy/clippy_lints/src/functions.rs b/src/tools/clippy/clippy_lints/src/functions.rs index 1f9bd7a691b52..ae9a2330c292e 100644 --- a/src/tools/clippy/clippy_lints/src/functions.rs +++ b/src/tools/clippy/clippy_lints/src/functions.rs @@ -1,7 +1,7 @@ use crate::utils::{ - attr_by_name, attrs::is_proc_macro, is_must_use_ty, is_trait_impl_item, iter_input_pats, match_def_path, - must_use_attr, qpath_res, return_ty, snippet, snippet_opt, span_lint, span_lint_and_help, span_lint_and_then, - trait_ref_of_method, type_is_unsafe_function, + attr_by_name, attrs::is_proc_macro, is_must_use_ty, is_trait_impl_item, iter_input_pats, + match_def_path, must_use_attr, qpath_res, return_ty, snippet, snippet_opt, span_lint, + span_lint_and_help, span_lint_and_then, trait_ref_of_method, type_is_unsafe_function, }; use rustc_ast::ast::Attribute; use rustc_data_structures::fx::FxHashSet; @@ -212,17 +212,14 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Functions { match kind { intravisit::FnKind::Method( _, - &hir::FnSig { - header: hir::FnHeader { abi: Abi::Rust, .. }, - .. - }, + &hir::FnSig { header: hir::FnHeader { abi: Abi::Rust, .. }, .. }, _, _, ) | intravisit::FnKind::ItemFn(_, _, hir::FnHeader { abi: Abi::Rust, .. }, _, _) => { self.check_arg_number(cx, decl, span.with_hi(decl.output.span().hi())) - }, - _ => {}, + } + _ => {} } } @@ -235,7 +232,14 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Functions { if let hir::ItemKind::Fn(ref sig, ref _generics, ref body_id) = item.kind { if let Some(attr) = attr { let fn_header_span = item.span.with_hi(sig.decl.output.span().hi()); - check_needless_must_use(cx, &sig.decl, item.hir_id, item.span, fn_header_span, attr); + check_needless_must_use( + cx, + &sig.decl, + item.hir_id, + item.span, + fn_header_span, + attr, + ); return; } if cx.access_levels.is_exported(item.hir_id) @@ -260,7 +264,14 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Functions { let attr = must_use_attr(&item.attrs); if let Some(attr) = attr { let fn_header_span = item.span.with_hi(sig.decl.output.span().hi()); - check_needless_must_use(cx, &sig.decl, item.hir_id, item.span, fn_header_span, attr); + check_needless_must_use( + cx, + &sig.decl, + item.hir_id, + item.span, + fn_header_span, + attr, + ); } else if cx.access_levels.is_exported(item.hir_id) && !is_proc_macro(&item.attrs) && trait_ref_of_method(cx, item.hir_id).is_none() @@ -282,19 +293,33 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Functions { if let hir::TraitItemKind::Fn(ref sig, ref eid) = item.kind { // don't lint extern functions decls, it's not their fault if sig.header.abi == Abi::Rust { - self.check_arg_number(cx, &sig.decl, item.span.with_hi(sig.decl.output.span().hi())); + self.check_arg_number( + cx, + &sig.decl, + item.span.with_hi(sig.decl.output.span().hi()), + ); } let attr = must_use_attr(&item.attrs); if let Some(attr) = attr { let fn_header_span = item.span.with_hi(sig.decl.output.span().hi()); - check_needless_must_use(cx, &sig.decl, item.hir_id, item.span, fn_header_span, attr); + check_needless_must_use( + cx, + &sig.decl, + item.hir_id, + item.span, + fn_header_span, + attr, + ); } if let hir::TraitFn::Provided(eid) = *eid { let body = cx.tcx.hir().body(eid); Self::check_raw_ptr(cx, sig.header.unsafety, &sig.decl, body, item.hir_id); - if attr.is_none() && cx.access_levels.is_exported(item.hir_id) && !is_proc_macro(&item.attrs) { + if attr.is_none() + && cx.access_levels.is_exported(item.hir_id) + && !is_proc_macro(&item.attrs) + { check_must_use_candidate( cx, &sig.decl, @@ -351,7 +376,7 @@ impl<'a, 'tcx> Functions { line = &line[i + 2..]; in_comment = false; continue; - }, + } None => break, } } else { @@ -392,12 +417,8 @@ impl<'a, 'tcx> Functions { .collect::>(); if !raw_ptrs.is_empty() { - let tables = cx.tcx.body_tables(body.id()); - let mut v = DerefVisitor { - cx, - ptrs: raw_ptrs, - tables, - }; + let tables = cx.tcx.typeck_body(body.id()); + let mut v = DerefVisitor { cx, ptrs: raw_ptrs, tables }; intravisit::walk_expr(&mut v, expr); } @@ -489,18 +510,17 @@ fn has_mutable_arg(cx: &LateContext<'_, '_>, body: &hir::Body<'_>) -> bool { body.params.iter().any(|param| is_mutable_pat(cx, ¶m.pat, &mut tys)) } -fn is_mutable_pat(cx: &LateContext<'_, '_>, pat: &hir::Pat<'_>, tys: &mut FxHashSet) -> bool { +fn is_mutable_pat( + cx: &LateContext<'_, '_>, + pat: &hir::Pat<'_>, + tys: &mut FxHashSet, +) -> bool { if let hir::PatKind::Wild = pat.kind { return false; // ignore `_` patterns } let def_id = pat.hir_id.owner.to_def_id(); - if cx.tcx.has_typeck_tables(def_id) { - is_mutable_ty( - cx, - &cx.tcx.typeck_tables_of(def_id.expect_local()).pat_ty(pat), - pat.span, - tys, - ) + if cx.tcx.has_typeck_results(def_id) { + is_mutable_ty(cx, &cx.tcx.typeck(def_id.expect_local()).pat_ty(pat), pat.span, tys) } else { false } @@ -508,7 +528,12 @@ fn is_mutable_pat(cx: &LateContext<'_, '_>, pat: &hir::Pat<'_>, tys: &mut FxHash static KNOWN_WRAPPER_TYS: &[&[&str]] = &[&["alloc", "rc", "Rc"], &["std", "sync", "Arc"]]; -fn is_mutable_ty<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>, span: Span, tys: &mut FxHashSet) -> bool { +fn is_mutable_ty<'a, 'tcx>( + cx: &LateContext<'a, 'tcx>, + ty: Ty<'tcx>, + span: Span, + tys: &mut FxHashSet, +) -> bool { match ty.kind { // primitive types are never mutable ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Str => false, @@ -516,12 +541,12 @@ fn is_mutable_ty<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>, span: Span, tys.insert(adt.did) && !ty.is_freeze(cx.tcx.at(span), cx.param_env) || KNOWN_WRAPPER_TYS.iter().any(|path| match_def_path(cx, adt.did, path)) && substs.types().any(|ty| is_mutable_ty(cx, ty, span, tys)) - }, + } ty::Tuple(ref substs) => substs.types().any(|ty| is_mutable_ty(cx, ty, span, tys)), ty::Array(ty, _) | ty::Slice(ty) => is_mutable_ty(cx, ty, span, tys), ty::RawPtr(ty::TypeAndMut { ty, mutbl }) | ty::Ref(_, ty, mutbl) => { mutbl == hir::Mutability::Mut || is_mutable_ty(cx, ty, span, tys) - }, + } // calling something constitutes a side effect, so return true on all callables // also never calls need not be used, so return true for them, too _ => true, @@ -539,7 +564,7 @@ fn raw_ptr_arg(arg: &hir::Param<'_>, ty: &hir::Ty<'_>) -> Option { struct DerefVisitor<'a, 'tcx> { cx: &'a LateContext<'a, 'tcx>, ptrs: FxHashSet, - tables: &'a ty::TypeckTables<'tcx>, + tables: &'a ty::TypeckResults<'tcx>, } impl<'a, 'tcx> intravisit::Visitor<'tcx> for DerefVisitor<'a, 'tcx> { @@ -555,7 +580,7 @@ impl<'a, 'tcx> intravisit::Visitor<'tcx> for DerefVisitor<'a, 'tcx> { self.check_arg(arg); } } - }, + } hir::ExprKind::MethodCall(_, _, args, _) => { let def_id = self.tables.type_dependent_def_id(expr.hir_id).unwrap(); let base_type = self.cx.tcx.type_of(def_id); @@ -565,7 +590,7 @@ impl<'a, 'tcx> intravisit::Visitor<'tcx> for DerefVisitor<'a, 'tcx> { self.check_arg(arg); } } - }, + } hir::ExprKind::Unary(hir::UnOp::UnDeref, ref ptr) => self.check_arg(ptr), _ => (), } @@ -614,10 +639,10 @@ impl<'a, 'tcx> intravisit::Visitor<'tcx> for StaticMutVisitor<'a, 'tcx> { let mut tys = FxHashSet::default(); for arg in args { let def_id = arg.hir_id.owner.to_def_id(); - if self.cx.tcx.has_typeck_tables(def_id) + if self.cx.tcx.has_typeck_results(def_id) && is_mutable_ty( self.cx, - self.cx.tcx.typeck_tables_of(def_id.expect_local()).expr_ty(arg), + self.cx.tcx.typeck(def_id.expect_local()).expr_ty(arg), arg.span, &mut tys, ) @@ -628,11 +653,13 @@ impl<'a, 'tcx> intravisit::Visitor<'tcx> for StaticMutVisitor<'a, 'tcx> { } tys.clear(); } - }, - Assign(ref target, ..) | AssignOp(_, ref target, _) | AddrOf(_, hir::Mutability::Mut, ref target) => { + } + Assign(ref target, ..) + | AssignOp(_, ref target, _) + | AddrOf(_, hir::Mutability::Mut, ref target) => { self.mutates_static |= is_mutated_static(self.cx, target) - }, - _ => {}, + } + _ => {} } } @@ -651,17 +678,14 @@ fn is_mutated_static(cx: &LateContext<'_, '_>, e: &hir::Expr<'_>) -> bool { } else { true } - }, + } Field(ref inner, _) | Index(ref inner, _) => is_mutated_static(cx, inner), _ => false, } } fn mutates_static<'a, 'tcx>(cx: &'a LateContext<'a, 'tcx>, body: &'tcx hir::Body<'_>) -> bool { - let mut v = StaticMutVisitor { - cx, - mutates_static: false, - }; + let mut v = StaticMutVisitor { cx, mutates_static: false }; intravisit::walk_expr(&mut v, &body.value); v.mutates_static } diff --git a/src/tools/clippy/clippy_lints/src/get_last_with_len.rs b/src/tools/clippy/clippy_lints/src/get_last_with_len.rs index 57a7fbb565679..c21d0e8f3dadd 100644 --- a/src/tools/clippy/clippy_lints/src/get_last_with_len.rs +++ b/src/tools/clippy/clippy_lints/src/get_last_with_len.rs @@ -1,6 +1,8 @@ //! lint on using `x.get(x.len() - 1)` instead of `x.last()` -use crate::utils::{is_type_diagnostic_item, snippet_with_applicability, span_lint_and_sugg, SpanlessEq}; +use crate::utils::{ + is_type_diagnostic_item, snippet_with_applicability, span_lint_and_sugg, SpanlessEq, +}; use if_chain::if_chain; use rustc_ast::ast::LitKind; use rustc_errors::Applicability; @@ -54,7 +56,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for GetLastWithLen { // Argument 0 (the struct we're calling the method on) is a vector if let Some(struct_calling_on) = args.get(0); - let struct_ty = cx.tables().expr_ty(struct_calling_on); + let struct_ty = cx.typeck_results().expr_ty(struct_calling_on); if is_type_diagnostic_item(cx, struct_ty, sym!(vec_type)); // Argument to "get" is a subtraction diff --git a/src/tools/clippy/clippy_lints/src/identity_op.rs b/src/tools/clippy/clippy_lints/src/identity_op.rs index 1c25e050997ea..dabc925232d7a 100644 --- a/src/tools/clippy/clippy_lints/src/identity_op.rs +++ b/src/tools/clippy/clippy_lints/src/identity_op.rs @@ -62,8 +62,8 @@ fn is_allowed(cx: &LateContext<'_, '_>, cmp: BinOp, left: &Expr<'_>, right: &Exp // `1 << 0` is a common pattern in bit manipulation code if_chain! { if let BinOpKind::Shl = cmp.node; - if let Some(Constant::Int(0)) = constant_simple(cx, cx.tables(), right); - if let Some(Constant::Int(1)) = constant_simple(cx, cx.tables(), left); + if let Some(Constant::Int(0)) = constant_simple(cx, cx.typeck_results(), right); + if let Some(Constant::Int(1)) = constant_simple(cx, cx.typeck_results(), left); then { return true; } @@ -74,8 +74,8 @@ fn is_allowed(cx: &LateContext<'_, '_>, cmp: BinOp, left: &Expr<'_>, right: &Exp #[allow(clippy::cast_possible_wrap)] fn check(cx: &LateContext<'_, '_>, e: &Expr<'_>, m: i8, span: Span, arg: Span) { - if let Some(Constant::Int(v)) = constant_simple(cx, cx.tables(), e) { - let check = match cx.tables().expr_ty(e).kind { + if let Some(Constant::Int(v)) = constant_simple(cx, cx.typeck_results(), e) { + let check = match cx.typeck_results().expr_ty(e).kind { ty::Int(ity) => unsext(cx.tcx, -1_i128, ity), ty::Uint(uty) => clip(cx.tcx, !0, uty), _ => return, diff --git a/src/tools/clippy/clippy_lints/src/if_let_mutex.rs b/src/tools/clippy/clippy_lints/src/if_let_mutex.rs index e357c7b3b2eb2..5dd8d605c5f3d 100644 --- a/src/tools/clippy/clippy_lints/src/if_let_mutex.rs +++ b/src/tools/clippy/clippy_lints/src/if_let_mutex.rs @@ -149,7 +149,7 @@ fn is_mutex_lock_call<'a>(cx: &LateContext<'a, '_>, expr: &'a Expr<'_>) -> Optio if_chain! { if let ExprKind::MethodCall(path, _span, args, _) = &expr.kind; if path.ident.to_string() == "lock"; - let ty = cx.tables().expr_ty(&args[0]); + let ty = cx.typeck_results().expr_ty(&args[0]); if is_type_diagnostic_item(cx, ty, sym!(mutex_type)); then { Some(&args[0]) diff --git a/src/tools/clippy/clippy_lints/src/if_let_some_result.rs b/src/tools/clippy/clippy_lints/src/if_let_some_result.rs index 3f1ae9b86d387..c4095298ce4fc 100644 --- a/src/tools/clippy/clippy_lints/src/if_let_some_result.rs +++ b/src/tools/clippy/clippy_lints/src/if_let_some_result.rs @@ -45,7 +45,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for OkIfLet { if let ExprKind::MethodCall(_, ok_span, ref result_types, _) = op.kind; //check is expr.ok() has type Result.ok(, _) if let PatKind::TupleStruct(QPath::Resolved(_, ref x), ref y, _) = body[0].pat.kind; //get operation if method_chain_args(op, &["ok"]).is_some(); //test to see if using ok() methoduse std::marker::Sized; - if is_type_diagnostic_item(cx, cx.tables().expr_ty(&result_types[0]), sym!(result_type)); + if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&result_types[0]), sym!(result_type)); if rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_path(x, false)) == "Some"; then { diff --git a/src/tools/clippy/clippy_lints/src/implicit_return.rs b/src/tools/clippy/clippy_lints/src/implicit_return.rs index 5a0531ff749e9..97f0df00131d4 100644 --- a/src/tools/clippy/clippy_lints/src/implicit_return.rs +++ b/src/tools/clippy/clippy_lints/src/implicit_return.rs @@ -108,7 +108,7 @@ fn expr_match(cx: &LateContext<'_, '_>, expr: &Expr<'_>) { ExprKind::Call(expr, ..) => { if_chain! { if let ExprKind::Path(qpath) = &expr.kind; - if let Some(path_def_id) = cx.tables().qpath_res(qpath, expr.hir_id).opt_def_id(); + if let Some(path_def_id) = cx.typeck_results().qpath_res(qpath, expr.hir_id).opt_def_id(); if match_def_path(cx, path_def_id, &BEGIN_PANIC) || match_def_path(cx, path_def_id, &BEGIN_PANIC_FMT); then { } diff --git a/src/tools/clippy/clippy_lints/src/implicit_saturating_sub.rs b/src/tools/clippy/clippy_lints/src/implicit_saturating_sub.rs index 1a6cb0b0c566e..9f3e9b7b98318 100644 --- a/src/tools/clippy/clippy_lints/src/implicit_saturating_sub.rs +++ b/src/tools/clippy/clippy_lints/src/implicit_saturating_sub.rs @@ -81,7 +81,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ImplicitSaturatingSub { }; // Check if the variable in the condition statement is an integer - if !cx.tables().expr_ty(cond_var).is_integral() { + if !cx.typeck_results().expr_ty(cond_var).is_integral() { return; } @@ -93,7 +93,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ImplicitSaturatingSub { ExprKind::Lit(ref cond_lit) => { // Check if the constant is zero if let LitKind::Int(0, _) = cond_lit.node { - if cx.tables().expr_ty(cond_left).is_signed() { + if cx.typeck_results().expr_ty(cond_left).is_signed() { } else { print_lint_and_sugg(cx, &var_name, expr); }; @@ -132,7 +132,7 @@ fn subtracts_one<'a>(cx: &LateContext<'_, '_>, expr: &Expr<'a>) -> Option<&'a Ex None } } - }, + } ExprKind::Assign(ref target, ref value, _) => { if_chain! { if let ExprKind::Binary(ref op1, ref left1, ref right1) = value.kind; @@ -148,7 +148,7 @@ fn subtracts_one<'a>(cx: &LateContext<'_, '_>, expr: &Expr<'a>) -> Option<&'a Ex None } } - }, + } _ => None, } } diff --git a/src/tools/clippy/clippy_lints/src/indexing_slicing.rs b/src/tools/clippy/clippy_lints/src/indexing_slicing.rs index c5e4abc94a8a6..3e1d15aba1831 100644 --- a/src/tools/clippy/clippy_lints/src/indexing_slicing.rs +++ b/src/tools/clippy/clippy_lints/src/indexing_slicing.rs @@ -88,7 +88,7 @@ declare_lint_pass!(IndexingSlicing => [INDEXING_SLICING, OUT_OF_BOUNDS_INDEXING] impl<'a, 'tcx> LateLintPass<'a, 'tcx> for IndexingSlicing { fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) { if let ExprKind::Index(ref array, ref index) = &expr.kind { - let ty = cx.tables().expr_ty(array); + let ty = cx.typeck_results().expr_ty(array); if let Some(range) = higher::range(cx, index) { // Ranged indexes, i.e., &x[n..m], &x[n..], &x[..n] and &x[..] if let ty::Array(_, s) = ty.kind { @@ -138,12 +138,19 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for IndexingSlicing { (None, None) => return, // [..] is ok. }; - span_lint_and_help(cx, INDEXING_SLICING, expr.span, "slicing may panic.", None, help_msg); + span_lint_and_help( + cx, + INDEXING_SLICING, + expr.span, + "slicing may panic.", + None, + help_msg, + ); } else { // Catchall non-range index, i.e., [n] or [n << m] if let ty::Array(..) = ty.kind { // Index is a constant uint. - if let Some(..) = constant(cx, cx.tables(), index) { + if let Some(..) = constant(cx, cx.typeck_results(), index) { // Let rustc's `const_err` lint handle constant `usize` indexing on arrays. return; } @@ -169,14 +176,14 @@ fn to_const_range<'a, 'tcx>( range: higher::Range<'_>, array_size: u128, ) -> (Option, Option) { - let s = range.start.map(|expr| constant(cx, cx.tables(), expr).map(|(c, _)| c)); + let s = range.start.map(|expr| constant(cx, cx.typeck_results(), expr).map(|(c, _)| c)); let start = match s { Some(Some(Constant::Int(x))) => Some(x), Some(_) => None, None => Some(0), }; - let e = range.end.map(|expr| constant(cx, cx.tables(), expr).map(|(c, _)| c)); + let e = range.end.map(|expr| constant(cx, cx.typeck_results(), expr).map(|(c, _)| c)); let end = match e { Some(Some(Constant::Int(x))) => { if range.limits == RangeLimits::Closed { @@ -184,7 +191,7 @@ fn to_const_range<'a, 'tcx>( } else { Some(x) } - }, + } Some(_) => None, None => Some(array_size), }; diff --git a/src/tools/clippy/clippy_lints/src/infinite_iter.rs b/src/tools/clippy/clippy_lints/src/infinite_iter.rs index 38f086c9221fe..d30942c741a02 100644 --- a/src/tools/clippy/clippy_lints/src/infinite_iter.rs +++ b/src/tools/clippy/clippy_lints/src/infinite_iter.rs @@ -231,13 +231,13 @@ fn complete_infinite_iter(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> Finitene } if method.ident.name == sym!(last) && args.len() == 1 { let not_double_ended = get_trait_def_id(cx, &paths::DOUBLE_ENDED_ITERATOR).map_or(false, |id| { - !implements_trait(cx, cx.tables().expr_ty(&args[0]), id, &[]) + !implements_trait(cx, cx.typeck_results().expr_ty(&args[0]), id, &[]) }); if not_double_ended { return is_infinite(cx, &args[0]); } } else if method.ident.name == sym!(collect) { - let ty = cx.tables().expr_ty(expr); + let ty = cx.typeck_results().expr_ty(expr); if INFINITE_COLLECTORS.iter().any(|path| match_type(cx, ty, path)) { return is_infinite(cx, &args[0]); } diff --git a/src/tools/clippy/clippy_lints/src/integer_division.rs b/src/tools/clippy/clippy_lints/src/integer_division.rs index 83ae1c1a971e1..9e049ff25b895 100644 --- a/src/tools/clippy/clippy_lints/src/integer_division.rs +++ b/src/tools/clippy/clippy_lints/src/integer_division.rs @@ -50,7 +50,7 @@ fn is_integer_division<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Ex if let hir::ExprKind::Binary(binop, left, right) = &expr.kind; if let hir::BinOpKind::Div = &binop.node; then { - let (left_ty, right_ty) = (cx.tables().expr_ty(left), cx.tables().expr_ty(right)); + let (left_ty, right_ty) = (cx.typeck_results().expr_ty(left), cx.typeck_results().expr_ty(right)); return left_ty.is_integral() && right_ty.is_integral(); } } diff --git a/src/tools/clippy/clippy_lints/src/large_stack_arrays.rs b/src/tools/clippy/clippy_lints/src/large_stack_arrays.rs index 0301f263489f4..cd61aaf44d73f 100644 --- a/src/tools/clippy/clippy_lints/src/large_stack_arrays.rs +++ b/src/tools/clippy/clippy_lints/src/large_stack_arrays.rs @@ -42,7 +42,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LargeStackArrays { fn check_expr(&mut self, cx: &LateContext<'_, '_>, expr: &Expr<'_>) { if_chain! { if let ExprKind::Repeat(_, _) = expr.kind; - if let ty::Array(element_type, cst) = cx.tables().expr_ty(expr).kind; + if let ty::Array(element_type, cst) = cx.typeck_results().expr_ty(expr).kind; if let ConstKind::Value(val) = cst.val; if let ConstValue::Scalar(element_count) = val; if let Ok(element_count) = element_count.to_machine_usize(&cx.tcx); diff --git a/src/tools/clippy/clippy_lints/src/len_zero.rs b/src/tools/clippy/clippy_lints/src/len_zero.rs index e17297e969516..f46a7c517120a 100644 --- a/src/tools/clippy/clippy_lints/src/len_zero.rs +++ b/src/tools/clippy/clippy_lints/src/len_zero.rs @@ -300,7 +300,7 @@ fn has_is_empty(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> bool { return false; } - let ty = &walk_ptrs_ty(cx.tables().expr_ty(expr)); + let ty = &walk_ptrs_ty(cx.typeck_results().expr_ty(expr)); match ty.kind { ty::Dynamic(ref tt, ..) => { if let Some(principal) = tt.principal() { diff --git a/src/tools/clippy/clippy_lints/src/let_and_return.rs b/src/tools/clippy/clippy_lints/src/let_and_return.rs index 299202981b1f3..f621a2b2c43b8 100644 --- a/src/tools/clippy/clippy_lints/src/let_and_return.rs +++ b/src/tools/clippy/clippy_lints/src/let_and_return.rs @@ -100,14 +100,10 @@ struct BorrowVisitor<'a, 'tcx> { impl BorrowVisitor<'_, '_> { fn fn_def_id(&self, expr: &Expr<'_>) -> Option { match &expr.kind { - ExprKind::MethodCall(..) => self.cx.tables().type_dependent_def_id(expr.hir_id), - ExprKind::Call( - Expr { - kind: ExprKind::Path(qpath), - .. - }, - .., - ) => self.cx.tables().qpath_res(qpath, expr.hir_id).opt_def_id(), + ExprKind::MethodCall(..) => self.cx.typeck_results().type_dependent_def_id(expr.hir_id), + ExprKind::Call(Expr { kind: ExprKind::Path(qpath), .. }, ..) => { + self.cx.typeck_results().qpath_res(qpath, expr.hir_id).opt_def_id() + } _ => None, } } diff --git a/src/tools/clippy/clippy_lints/src/let_if_seq.rs b/src/tools/clippy/clippy_lints/src/let_if_seq.rs index 7b03812b82260..b189359357aeb 100644 --- a/src/tools/clippy/clippy_lints/src/let_if_seq.rs +++ b/src/tools/clippy/clippy_lints/src/let_if_seq.rs @@ -73,7 +73,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LetIfSeq { then { let span = stmt.span.to(if_.span); - let has_interior_mutability = !cx.tables().node_type(canonical_id).is_freeze( + let has_interior_mutability = !cx.typeck_results().node_type(canonical_id).is_freeze( cx.tcx.at(span), cx.param_env, ); diff --git a/src/tools/clippy/clippy_lints/src/let_underscore.rs b/src/tools/clippy/clippy_lints/src/let_underscore.rs index 0864bbe0f9127..541d23029a6c3 100644 --- a/src/tools/clippy/clippy_lints/src/let_underscore.rs +++ b/src/tools/clippy/clippy_lints/src/let_underscore.rs @@ -60,11 +60,8 @@ declare_clippy_lint! { declare_lint_pass!(LetUnderscore => [LET_UNDERSCORE_MUST_USE, LET_UNDERSCORE_LOCK]); -const SYNC_GUARD_PATHS: [&[&str]; 3] = [ - &paths::MUTEX_GUARD, - &paths::RWLOCK_READ_GUARD, - &paths::RWLOCK_WRITE_GUARD, -]; +const SYNC_GUARD_PATHS: [&[&str]; 3] = + [&paths::MUTEX_GUARD, &paths::RWLOCK_READ_GUARD, &paths::RWLOCK_WRITE_GUARD]; impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LetUnderscore { fn check_local(&mut self, cx: &LateContext<'_, '_>, local: &Local<'_>) { @@ -76,7 +73,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LetUnderscore { if let PatKind::Wild = local.pat.kind; if let Some(ref init) = local.init; then { - let init_ty = cx.tables().expr_ty(init); + let init_ty = cx.typeck_results().expr_ty(init); let contains_sync_guard = init_ty.walk().any(|inner| match inner.unpack() { GenericArgKind::Type(inner_ty) => { SYNC_GUARD_PATHS.iter().any(|path| match_type(cx, inner_ty, path)) @@ -94,7 +91,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LetUnderscore { "consider using an underscore-prefixed named \ binding or dropping explicitly with `std::mem::drop`" ) - } else if is_must_use_ty(cx, cx.tables().expr_ty(init)) { + } else if is_must_use_ty(cx, cx.typeck_results().expr_ty(init)) { span_lint_and_help( cx, LET_UNDERSCORE_MUST_USE, diff --git a/src/tools/clippy/clippy_lints/src/lifetimes.rs b/src/tools/clippy/clippy_lints/src/lifetimes.rs index 6840e82d4bf1b..e35e4c0bfcecb 100644 --- a/src/tools/clippy/clippy_lints/src/lifetimes.rs +++ b/src/tools/clippy/clippy_lints/src/lifetimes.rs @@ -343,7 +343,7 @@ impl<'v, 't> RefVisitor<'v, 't> { }) { let hir_id = ty.hir_id; - match self.cx.tables().qpath_res(qpath, hir_id) { + match self.cx.typeck_results().qpath_res(qpath, hir_id) { Res::Def(DefKind::TyAlias | DefKind::Struct, def_id) => { let generics = self.cx.tcx.generics_of(def_id); for _ in generics.params.as_slice() { diff --git a/src/tools/clippy/clippy_lints/src/loops.rs b/src/tools/clippy/clippy_lints/src/loops.rs index 18b979176a0a0..e4bf3a653fe3a 100644 --- a/src/tools/clippy/clippy_lints/src/loops.rs +++ b/src/tools/clippy/clippy_lints/src/loops.rs @@ -535,7 +535,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Loops { if_chain! { if let ExprKind::MethodCall(..) | ExprKind::Call(..) = iter_expr.kind; if let Some(iter_def_id) = get_trait_def_id(cx, &paths::ITERATOR); - if implements_trait(cx, cx.tables().expr_ty(iter_expr), iter_def_id, &[]); + if implements_trait(cx, cx.typeck_results().expr_ty(iter_expr), iter_def_id, &[]); then { return; } @@ -985,8 +985,8 @@ fn detect_manual_memcpy<'a, 'tcx>( if_chain! { if let ExprKind::Index(seqexpr_left, idx_left) = lhs.kind; if let ExprKind::Index(seqexpr_right, idx_right) = rhs.kind; - if is_slice_like(cx, cx.tables().expr_ty(seqexpr_left)) - && is_slice_like(cx, cx.tables().expr_ty(seqexpr_right)); + if is_slice_like(cx, cx.typeck_results().expr_ty(seqexpr_left)) + && is_slice_like(cx, cx.typeck_results().expr_ty(seqexpr_right)); if let Some(offset_left) = get_offset(cx, &idx_left, canonical_id); if let Some(offset_right) = get_offset(cx, &idx_right, canonical_id); @@ -1254,8 +1254,8 @@ fn check_for_loop_arg(cx: &LateContext<'_, '_>, pat: &Pat<'_>, arg: &Expr<'_>, e lint_iter_method(cx, args, arg, method_name); } } else if method_name == "into_iter" && match_trait_method(cx, arg, &paths::INTO_ITERATOR) { - let receiver_ty = cx.tables().expr_ty(&args[0]); - let receiver_ty_adjusted = cx.tables().expr_ty_adjusted(&args[0]); + let receiver_ty = cx.typeck_results().expr_ty(&args[0]); + let receiver_ty_adjusted = cx.typeck_results().expr_ty_adjusted(&args[0]); if TyS::same_type(receiver_ty, receiver_ty_adjusted) { let mut applicability = Applicability::MachineApplicable; let object = snippet_with_applicability(cx, args[0].span, "_", &mut applicability); @@ -1300,7 +1300,7 @@ fn check_for_loop_arg(cx: &LateContext<'_, '_>, pat: &Pat<'_>, arg: &Expr<'_>, e /// Checks for `for` loops over `Option`s and `Result`s. fn check_arg_type(cx: &LateContext<'_, '_>, pat: &Pat<'_>, arg: &Expr<'_>) { - let ty = cx.tables().expr_ty(arg); + let ty = cx.typeck_results().expr_ty(arg); if is_type_diagnostic_item(cx, ty, sym!(option_type)) { span_lint_and_help( cx, @@ -1405,7 +1405,7 @@ fn check_for_loop_explicit_counter<'a, 'tcx>( /// actual `Iterator` that the loop uses. fn make_iterator_snippet(cx: &LateContext<'_, '_>, arg: &Expr<'_>, applic_ref: &mut Applicability) -> String { let impls_iterator = get_trait_def_id(cx, &paths::ITERATOR) - .map_or(false, |id| implements_trait(cx, cx.tables().expr_ty(arg), id, &[])); + .map_or(false, |id| implements_trait(cx, cx.typeck_results().expr_ty(arg), id, &[])); if impls_iterator { format!( "{}", @@ -1416,7 +1416,7 @@ fn make_iterator_snippet(cx: &LateContext<'_, '_>, arg: &Expr<'_>, applic_ref: & // (&mut x).into_iter() ==> x.iter_mut() match &arg.kind { ExprKind::AddrOf(BorrowKind::Ref, mutability, arg_inner) - if has_iter_method(cx, cx.tables().expr_ty(&arg_inner)).is_some() => + if has_iter_method(cx, cx.typeck_results().expr_ty(&arg_inner)).is_some() => { let meth_name = match mutability { Mutability::Mut => "iter_mut", @@ -1449,7 +1449,7 @@ fn check_for_loop_over_map_kv<'a, 'tcx>( if let PatKind::Tuple(ref pat, _) = pat.kind { if pat.len() == 2 { let arg_span = arg.span; - let (new_pat_span, kind, ty, mutbl) = match cx.tables().expr_ty(arg).kind { + let (new_pat_span, kind, ty, mutbl) = match cx.typeck_results().expr_ty(arg).kind { ty::Ref(_, ty, mutbl) => match (&pat[0].kind, &pat[1].kind) { (key, _) if pat_is_wild(key, body) => (pat[1].span, "value", ty, mutbl), (_, value) if pat_is_wild(value, body) => (pat[0].span, "key", ty, Mutability::Not), @@ -1594,7 +1594,7 @@ fn check_for_mutation<'a, 'tcx>( }; let def_id = body.hir_id.owner.to_def_id(); cx.tcx.infer_ctxt().enter(|infcx| { - ExprUseVisitor::new(&mut delegate, &infcx, def_id.expect_local(), cx.param_env, cx.tables()).walk_expr(body); + ExprUseVisitor::new(&mut delegate, &infcx, def_id.expect_local(), cx.param_env, cx.typeck_results()).walk_expr(body); }); delegate.mutation_span() } @@ -1688,7 +1688,7 @@ impl<'a, 'tcx> VarVisitor<'a, 'tcx> { if index_used_directly { self.indexed_directly.insert( seqvar.segments[0].ident.name, - (Some(extent), self.cx.tables().node_type(seqexpr.hir_id)), + (Some(extent), self.cx.typeck_results().node_type(seqexpr.hir_id)), ); } return false; // no need to walk further *on the variable* @@ -1700,7 +1700,7 @@ impl<'a, 'tcx> VarVisitor<'a, 'tcx> { if index_used_directly { self.indexed_directly.insert( seqvar.segments[0].ident.name, - (None, self.cx.tables().node_type(seqexpr.hir_id)), + (None, self.cx.typeck_results().node_type(seqexpr.hir_id)), ); } return false; // no need to walk further *on the variable* @@ -1768,7 +1768,7 @@ impl<'a, 'tcx> Visitor<'tcx> for VarVisitor<'a, 'tcx> { ExprKind::Call(ref f, args) => { self.visit_expr(f); for expr in args { - let ty = self.cx.tables().expr_ty_adjusted(expr); + let ty = self.cx.typeck_results().expr_ty_adjusted(expr); self.prefer_mutable = false; if let ty::Ref(_, _, mutbl) = ty.kind { if mutbl == Mutability::Mut { @@ -1779,7 +1779,7 @@ impl<'a, 'tcx> Visitor<'tcx> for VarVisitor<'a, 'tcx> { } }, ExprKind::MethodCall(_, _, args, _) => { - let def_id = self.cx.tables().type_dependent_def_id(expr.hir_id).unwrap(); + let def_id = self.cx.typeck_results().type_dependent_def_id(expr.hir_id).unwrap(); for (ty, expr) in self.cx.tcx.fn_sig(def_id).inputs().skip_binder().iter().zip(args) { self.prefer_mutable = false; if let ty::Ref(_, _, mutbl) = ty.kind { @@ -1866,7 +1866,7 @@ impl<'a, 'tcx> Visitor<'tcx> for VarUsedAfterLoopVisitor<'a, 'tcx> { fn is_ref_iterable_type(cx: &LateContext<'_, '_>, e: &Expr<'_>) -> bool { // no walk_ptrs_ty: calling iter() on a reference can make sense because it // will allow further borrows afterwards - let ty = cx.tables().expr_ty(e); + let ty = cx.typeck_results().expr_ty(e); is_iterable_array(ty, cx) || is_type_diagnostic_item(cx, ty, sym!(vec_type)) || match_type(cx, ty, &paths::LINKED_LIST) || @@ -2241,7 +2241,7 @@ fn path_name(e: &Expr<'_>) -> Option { } fn check_infinite_loop<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, cond: &'tcx Expr<'_>, expr: &'tcx Expr<'_>) { - if constant(cx, cx.tables(), cond).is_some() { + if constant(cx, cx.typeck_results(), cond).is_some() { // A pure constant condition (e.g., `while false`) is not linted. return; } @@ -2377,7 +2377,7 @@ fn check_needless_collect<'a, 'tcx>(expr: &'tcx Expr<'_>, cx: &LateContext<'a, ' if let Some(ref generic_args) = chain_method.args; if let Some(GenericArg::Type(ref ty)) = generic_args.args.get(0); then { - let ty = cx.tables().node_type(ty.hir_id); + let ty = cx.typeck_results().node_type(ty.hir_id); if is_type_diagnostic_item(cx, ty, sym!(vec_type)) || is_type_diagnostic_item(cx, ty, sym!(vecdeque_type)) || match_type(cx, ty, &paths::BTREEMAP) || diff --git a/src/tools/clippy/clippy_lints/src/map_clone.rs b/src/tools/clippy/clippy_lints/src/map_clone.rs index 9109de9458f1c..133e2b77d2dd3 100644 --- a/src/tools/clippy/clippy_lints/src/map_clone.rs +++ b/src/tools/clippy/clippy_lints/src/map_clone.rs @@ -1,6 +1,7 @@ use crate::utils::paths; use crate::utils::{ - is_copy, is_type_diagnostic_item, match_trait_method, remove_blocks, snippet_with_applicability, span_lint_and_sugg, + is_copy, is_type_diagnostic_item, match_trait_method, remove_blocks, + snippet_with_applicability, span_lint_and_sugg, }; use if_chain::if_chain; use rustc_errors::Applicability; @@ -52,7 +53,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MapClone { if let hir::ExprKind::MethodCall(ref method, _, ref args, _) = e.kind; if args.len() == 2; if method.ident.as_str() == "map"; - let ty = cx.tables().expr_ty(&args[0]); + let ty = cx.typeck_results().expr_ty(&args[0]); if is_type_diagnostic_item(cx, ty, sym!(option_type)) || match_trait_method(cx, e, &paths::ITERATOR); if let hir::ExprKind::Closure(_, _, body_id, _, _) = args[1].kind; let closure_body = cx.tcx.hir().body(body_id); @@ -70,7 +71,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MapClone { match closure_expr.kind { hir::ExprKind::Unary(hir::UnOp::UnDeref, ref inner) => { if ident_eq(name, inner) { - if let ty::Ref(.., Mutability::Not) = cx.tables().expr_ty(inner).kind { + if let ty::Ref(.., Mutability::Not) = cx.typeck_results().expr_ty(inner).kind { lint(cx, e.span, args[0].span, true); } } @@ -79,7 +80,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MapClone { if ident_eq(name, &obj[0]) && method.ident.as_str() == "clone" && match_trait_method(cx, closure_expr, &paths::CLONE_TRAIT) { - let obj_ty = cx.tables().expr_ty(&obj[0]); + let obj_ty = cx.typeck_results().expr_ty(&obj[0]); if let ty::Ref(_, ty, _) = obj_ty.kind { let copy = is_copy(cx, ty); lint(cx, e.span, args[0].span, copy); @@ -127,10 +128,7 @@ fn lint(cx: &LateContext<'_, '_>, replace: Span, root: Span, copied: bool) { replace, "You are using an explicit closure for copying elements", "Consider calling the dedicated `copied` method", - format!( - "{}.copied()", - snippet_with_applicability(cx, root, "..", &mut applicability) - ), + format!("{}.copied()", snippet_with_applicability(cx, root, "..", &mut applicability)), applicability, ) } else { @@ -140,10 +138,7 @@ fn lint(cx: &LateContext<'_, '_>, replace: Span, root: Span, copied: bool) { replace, "You are using an explicit closure for cloning elements", "Consider calling the dedicated `cloned` method", - format!( - "{}.cloned()", - snippet_with_applicability(cx, root, "..", &mut applicability) - ), + format!("{}.cloned()", snippet_with_applicability(cx, root, "..", &mut applicability)), applicability, ) } diff --git a/src/tools/clippy/clippy_lints/src/map_unit_fn.rs b/src/tools/clippy/clippy_lints/src/map_unit_fn.rs index a4550f707ee22..95b0daa0d97fa 100644 --- a/src/tools/clippy/clippy_lints/src/map_unit_fn.rs +++ b/src/tools/clippy/clippy_lints/src/map_unit_fn.rs @@ -1,4 +1,6 @@ -use crate::utils::{is_type_diagnostic_item, iter_input_pats, method_chain_args, snippet, span_lint_and_then}; +use crate::utils::{ + is_type_diagnostic_item, iter_input_pats, method_chain_args, snippet, span_lint_and_then, +}; use if_chain::if_chain; use rustc_errors::Applicability; use rustc_hir as hir; @@ -101,7 +103,7 @@ fn is_unit_type(ty: Ty<'_>) -> bool { } fn is_unit_function(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>) -> bool { - let ty = cx.tables().expr_ty(expr); + let ty = cx.typeck_results().expr_ty(expr); if let ty::FnDef(id, _) = ty.kind { if let Some(fn_type) = cx.tcx.fn_sig(id).no_bound_vars() { @@ -112,7 +114,7 @@ fn is_unit_function(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>) -> bool { } fn is_unit_expression(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>) -> bool { - is_unit_type(cx.tables().expr_ty(expr)) + is_unit_type(cx.typeck_results().expr_ty(expr)) } /// The expression inside a closure may or may not have surrounding braces and @@ -128,14 +130,14 @@ fn reduce_unit_expression<'a>(cx: &LateContext<'_, '_>, expr: &'a hir::Expr<'_>) hir::ExprKind::Call(_, _) | hir::ExprKind::MethodCall(_, _, _, _) => { // Calls can't be reduced any more Some(expr.span) - }, + } hir::ExprKind::Block(ref block, _) => { match (&block.stmts[..], block.expr.as_ref()) { (&[], Some(inner_expr)) => { // If block only contains an expression, // reduce `{ X }` to `X` reduce_unit_expression(cx, inner_expr) - }, + } (&[ref inner_stmt], None) => { // If block only contains statements, // reduce `{ X; }` to `X` or `X;` @@ -145,7 +147,7 @@ fn reduce_unit_expression<'a>(cx: &LateContext<'_, '_>, expr: &'a hir::Expr<'_>) hir::StmtKind::Semi(..) => Some(inner_stmt.span), hir::StmtKind::Item(..) => None, } - }, + } _ => { // For closures that contain multiple statements // it's difficult to get a correct suggestion span @@ -153,9 +155,9 @@ fn reduce_unit_expression<'a>(cx: &LateContext<'_, '_>, expr: &'a hir::Expr<'_>) // // We do not attempt to build a suggestion for those right now. None - }, + } } - }, + } _ => None, } } @@ -202,16 +204,26 @@ fn suggestion_msg(function_type: &str, map_type: &str) -> String { ) } -fn lint_map_unit_fn(cx: &LateContext<'_, '_>, stmt: &hir::Stmt<'_>, expr: &hir::Expr<'_>, map_args: &[hir::Expr<'_>]) { +fn lint_map_unit_fn( + cx: &LateContext<'_, '_>, + stmt: &hir::Stmt<'_>, + expr: &hir::Expr<'_>, + map_args: &[hir::Expr<'_>], +) { let var_arg = &map_args[0]; - let (map_type, variant, lint) = if is_type_diagnostic_item(cx, cx.tables().expr_ty(var_arg), sym!(option_type)) { - ("Option", "Some", OPTION_MAP_UNIT_FN) - } else if is_type_diagnostic_item(cx, cx.tables().expr_ty(var_arg), sym!(result_type)) { - ("Result", "Ok", RESULT_MAP_UNIT_FN) - } else { - return; - }; + let (map_type, variant, lint) = + if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(var_arg), sym!(option_type)) { + ("Option", "Some", OPTION_MAP_UNIT_FN) + } else if is_type_diagnostic_item( + cx, + cx.typeck_results().expr_ty(var_arg), + sym!(result_type), + ) { + ("Result", "Ok", RESULT_MAP_UNIT_FN) + } else { + return; + }; let fn_arg = &map_args[1]; if is_unit_function(cx, fn_arg) { @@ -225,7 +237,12 @@ fn lint_map_unit_fn(cx: &LateContext<'_, '_>, stmt: &hir::Stmt<'_>, expr: &hir:: ); span_lint_and_then(cx, lint, expr.span, &msg, |diag| { - diag.span_suggestion(stmt.span, "try this", suggestion, Applicability::MachineApplicable); + diag.span_suggestion( + stmt.span, + "try this", + suggestion, + Applicability::MachineApplicable, + ); }); } else if let Some((binding, closure_expr)) = unit_closure(cx, fn_arg) { let msg = suggestion_msg("closure", map_type); @@ -252,7 +269,12 @@ fn lint_map_unit_fn(cx: &LateContext<'_, '_>, stmt: &hir::Stmt<'_>, expr: &hir:: snippet(cx, binding.pat.span, "_"), snippet(cx, var_arg.span, "_"), ); - diag.span_suggestion(stmt.span, "try this", suggestion, Applicability::HasPlaceholders); + diag.span_suggestion( + stmt.span, + "try this", + suggestion, + Applicability::HasPlaceholders, + ); } }); } diff --git a/src/tools/clippy/clippy_lints/src/match_on_vec_items.rs b/src/tools/clippy/clippy_lints/src/match_on_vec_items.rs index 4a025e0621f96..4494b99aa4c4f 100644 --- a/src/tools/clippy/clippy_lints/src/match_on_vec_items.rs +++ b/src/tools/clippy/clippy_lints/src/match_on_vec_items.rs @@ -1,4 +1,6 @@ -use crate::utils::{self, is_type_diagnostic_item, match_type, snippet, span_lint_and_sugg, walk_ptrs_ty}; +use crate::utils::{ + self, is_type_diagnostic_item, match_type, snippet, span_lint_and_sugg, walk_ptrs_ty, +}; use if_chain::if_chain; use rustc_errors::Applicability; use rustc_hir::{Expr, ExprKind, MatchSource}; @@ -73,7 +75,10 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MatchOnVecItems { } } -fn is_vec_indexing<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'tcx>) -> Option<&'tcx Expr<'tcx>> { +fn is_vec_indexing<'a, 'tcx>( + cx: &LateContext<'a, 'tcx>, + expr: &'tcx Expr<'tcx>, +) -> Option<&'tcx Expr<'tcx>> { if_chain! { if let ExprKind::Index(ref array, ref index) = expr.kind; if is_vector(cx, array); @@ -88,13 +93,13 @@ fn is_vec_indexing<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'tcx>) } fn is_vector(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> bool { - let ty = cx.tables().expr_ty(expr); + let ty = cx.typeck_results().expr_ty(expr); let ty = walk_ptrs_ty(ty); is_type_diagnostic_item(cx, ty, sym!(vec_type)) } fn is_full_range(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> bool { - let ty = cx.tables().expr_ty(expr); + let ty = cx.typeck_results().expr_ty(expr); let ty = walk_ptrs_ty(ty); match_type(cx, ty, &utils::paths::RANGE_FULL) } diff --git a/src/tools/clippy/clippy_lints/src/matches.rs b/src/tools/clippy/clippy_lints/src/matches.rs index 0c91d8885d924..542f083c6b823 100644 --- a/src/tools/clippy/clippy_lints/src/matches.rs +++ b/src/tools/clippy/clippy_lints/src/matches.rs @@ -540,7 +540,7 @@ fn check_single_match(cx: &LateContext<'_, '_>, ex: &Expr<'_>, arms: &[Arm<'_>], // allow match arms with just expressions return; }; - let ty = cx.tables().expr_ty(ex); + let ty = cx.typeck_results().expr_ty(ex); if ty.kind != ty::Bool || is_allowed(cx, MATCH_BOOL, ex.hir_id) { check_single_match_single_pattern(cx, ex, arms, expr, els); check_single_match_opt_like(cx, ex, arms, expr, ty, els); @@ -632,7 +632,7 @@ fn check_single_match_opt_like( fn check_match_bool(cx: &LateContext<'_, '_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: &Expr<'_>) { // Type of expression is `bool`. - if cx.tables().expr_ty(ex).kind == ty::Bool { + if cx.typeck_results().expr_ty(ex).kind == ty::Bool { span_lint_and_then( cx, MATCH_BOOL, @@ -695,8 +695,8 @@ fn check_match_bool(cx: &LateContext<'_, '_>, ex: &Expr<'_>, arms: &[Arm<'_>], e } fn check_overlapping_arms<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ex: &'tcx Expr<'_>, arms: &'tcx [Arm<'_>]) { - if arms.len() >= 2 && cx.tables().expr_ty(ex).is_integral() { - let ranges = all_ranges(cx, arms, cx.tables().expr_ty(ex)); + if arms.len() >= 2 && cx.typeck_results().expr_ty(ex).is_integral() { + let ranges = all_ranges(cx, arms, cx.typeck_results().expr_ty(ex)); let type_ranges = type_ranges(&ranges); if !type_ranges.is_empty() { if let Some((start, end)) = overlapping(&type_ranges) { @@ -714,7 +714,7 @@ fn check_overlapping_arms<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ex: &'tcx Expr<' } fn check_wild_err_arm(cx: &LateContext<'_, '_>, ex: &Expr<'_>, arms: &[Arm<'_>]) { - let ex_ty = walk_ptrs_ty(cx.tables().expr_ty(ex)); + let ex_ty = walk_ptrs_ty(cx.typeck_results().expr_ty(ex)); if is_type_diagnostic_item(cx, ex_ty, sym!(result_type)) { for arm in arms { if let PatKind::TupleStruct(ref path, ref inner, _) = arm.pat.kind { @@ -755,7 +755,7 @@ fn check_wild_err_arm(cx: &LateContext<'_, '_>, ex: &Expr<'_>, arms: &[Arm<'_>]) } fn check_wild_enum_match(cx: &LateContext<'_, '_>, ex: &Expr<'_>, arms: &[Arm<'_>]) { - let ty = cx.tables().expr_ty(ex); + let ty = cx.typeck_results().expr_ty(ex); if !ty.is_enum() { // If there isn't a nice closed set of possible values that can be conveniently enumerated, // don't complain about not enumerating the mall. @@ -935,8 +935,8 @@ fn check_match_as_ref(cx: &LateContext<'_, '_>, ex: &Expr<'_>, arms: &[Arm<'_>], "as_mut" }; - let output_ty = cx.tables().expr_ty(expr); - let input_ty = cx.tables().expr_ty(ex); + let output_ty = cx.typeck_results().expr_ty(expr); + let input_ty = cx.typeck_results().expr_ty(ex); let cast = if_chain! { if let ty::Adt(_, substs) = input_ty.kind; @@ -1006,13 +1006,13 @@ fn check_match_single_binding<'a>(cx: &LateContext<'_, 'a>, ex: &Expr<'a>, arms: match match_body.kind { ExprKind::Block(block, _) => { // macro + expr_ty(body) == () - if block.span.from_expansion() && cx.tables().expr_ty(&match_body).is_unit() { + if block.span.from_expansion() && cx.typeck_results().expr_ty(&match_body).is_unit() { snippet_body.push(';'); } }, _ => { // expr_ty(body) == () - if cx.tables().expr_ty(&match_body).is_unit() { + if cx.typeck_results().expr_ty(&match_body).is_unit() { snippet_body.push(';'); } }, @@ -1111,11 +1111,11 @@ fn all_ranges<'a, 'tcx>( { if let PatKind::Range(ref lhs, ref rhs, range_end) = pat.kind { let lhs = match lhs { - Some(lhs) => constant(cx, cx.tables(), lhs)?.0, + Some(lhs) => constant(cx, cx.typeck_results(), lhs)?.0, None => miri_to_const(ty.numeric_min_val(cx.tcx)?)?, }; let rhs = match rhs { - Some(rhs) => constant(cx, cx.tables(), rhs)?.0, + Some(rhs) => constant(cx, cx.typeck_results(), rhs)?.0, None => miri_to_const(ty.numeric_max_val(cx.tcx)?)?, }; let rhs = match range_end { @@ -1129,7 +1129,7 @@ fn all_ranges<'a, 'tcx>( } if let PatKind::Lit(ref value) = pat.kind { - let value = constant(cx, cx.tables(), value)?.0; + let value = constant(cx, cx.typeck_results(), value)?.0; return Some(SpannedRange { span: pat.span, node: (value.clone(), Bound::Included(value)), diff --git a/src/tools/clippy/clippy_lints/src/mem_discriminant.rs b/src/tools/clippy/clippy_lints/src/mem_discriminant.rs index d315c5ef89a88..0e56243dc176c 100644 --- a/src/tools/clippy/clippy_lints/src/mem_discriminant.rs +++ b/src/tools/clippy/clippy_lints/src/mem_discriminant.rs @@ -35,10 +35,10 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MemDiscriminant { if let ExprKind::Call(ref func, ref func_args) = expr.kind; // is `mem::discriminant` if let ExprKind::Path(ref func_qpath) = func.kind; - if let Some(def_id) = cx.tables().qpath_res(func_qpath, func.hir_id).opt_def_id(); + if let Some(def_id) = cx.typeck_results().qpath_res(func_qpath, func.hir_id).opt_def_id(); if match_def_path(cx, def_id, &paths::MEM_DISCRIMINANT); // type is non-enum - let ty_param = cx.tables().node_substs(func.hir_id).type_at(0); + let ty_param = cx.typeck_results().node_substs(func.hir_id).type_at(0); if !ty_param.is_enum(); then { diff --git a/src/tools/clippy/clippy_lints/src/mem_forget.rs b/src/tools/clippy/clippy_lints/src/mem_forget.rs index 1821bd9135f98..e511ad3cf28b4 100644 --- a/src/tools/clippy/clippy_lints/src/mem_forget.rs +++ b/src/tools/clippy/clippy_lints/src/mem_forget.rs @@ -31,10 +31,15 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MemForget { if let ExprKind::Path(ref qpath) = path_expr.kind { if let Some(def_id) = qpath_res(cx, qpath, path_expr.hir_id).opt_def_id() { if match_def_path(cx, def_id, &paths::MEM_FORGET) { - let forgot_ty = cx.tables().expr_ty(&args[0]); + let forgot_ty = cx.typeck_results().expr_ty(&args[0]); if forgot_ty.ty_adt_def().map_or(false, |def| def.has_dtor(cx.tcx)) { - span_lint(cx, MEM_FORGET, e.span, "usage of `mem::forget` on `Drop` type"); + span_lint( + cx, + MEM_FORGET, + e.span, + "usage of `mem::forget` on `Drop` type", + ); } } } diff --git a/src/tools/clippy/clippy_lints/src/mem_replace.rs b/src/tools/clippy/clippy_lints/src/mem_replace.rs index 16d31fc8346ea..a76de56b8db37 100644 --- a/src/tools/clippy/clippy_lints/src/mem_replace.rs +++ b/src/tools/clippy/clippy_lints/src/mem_replace.rs @@ -1,6 +1,6 @@ use crate::utils::{ - in_macro, match_def_path, match_qpath, paths, snippet, snippet_with_applicability, span_lint_and_help, - span_lint_and_sugg, span_lint_and_then, + in_macro, match_def_path, match_qpath, paths, snippet, snippet_with_applicability, + span_lint_and_help, span_lint_and_sugg, span_lint_and_then, }; use if_chain::if_chain; use rustc_errors::Applicability; @@ -97,7 +97,12 @@ declare_clippy_lint! { declare_lint_pass!(MemReplace => [MEM_REPLACE_OPTION_WITH_NONE, MEM_REPLACE_WITH_UNINIT, MEM_REPLACE_WITH_DEFAULT]); -fn check_replace_option_with_none(cx: &LateContext<'_, '_>, src: &Expr<'_>, dest: &Expr<'_>, expr_span: Span) { +fn check_replace_option_with_none( + cx: &LateContext<'_, '_>, + src: &Expr<'_>, + dest: &Expr<'_>, + expr_span: Span, +) { if let ExprKind::Path(ref replacement_qpath) = src.kind { // Check that second argument is `Option::None` if match_qpath(replacement_qpath, &paths::OPTION_NONE) { @@ -108,12 +113,13 @@ fn check_replace_option_with_none(cx: &LateContext<'_, '_>, src: &Expr<'_>, dest // replacee's path. let replaced_path = match dest.kind { ExprKind::AddrOf(BorrowKind::Ref, Mutability::Mut, ref replaced) => { - if let ExprKind::Path(QPath::Resolved(None, ref replaced_path)) = replaced.kind { + if let ExprKind::Path(QPath::Resolved(None, ref replaced_path)) = replaced.kind + { replaced_path } else { return; } - }, + } ExprKind::Path(QPath::Resolved(None, ref replaced_path)) => replaced_path, _ => return, }; @@ -135,10 +141,15 @@ fn check_replace_option_with_none(cx: &LateContext<'_, '_>, src: &Expr<'_>, dest } } -fn check_replace_with_uninit(cx: &LateContext<'_, '_>, src: &Expr<'_>, dest: &Expr<'_>, expr_span: Span) { +fn check_replace_with_uninit( + cx: &LateContext<'_, '_>, + src: &Expr<'_>, + dest: &Expr<'_>, + expr_span: Span, +) { if_chain! { // check if replacement is mem::MaybeUninit::uninit().assume_init() - if let Some(method_def_id) = cx.tables().type_dependent_def_id(src.hir_id); + if let Some(method_def_id) = cx.typeck_results().type_dependent_def_id(src.hir_id); if cx.tcx.is_diagnostic_item(sym::assume_init, method_def_id); then { let mut applicability = Applicability::MachineApplicable; @@ -162,7 +173,7 @@ fn check_replace_with_uninit(cx: &LateContext<'_, '_>, src: &Expr<'_>, dest: &Ex if let ExprKind::Call(ref repl_func, ref repl_args) = src.kind; if repl_args.is_empty(); if let ExprKind::Path(ref repl_func_qpath) = repl_func.kind; - if let Some(repl_def_id) = cx.tables().qpath_res(repl_func_qpath, repl_func.hir_id).opt_def_id(); + if let Some(repl_def_id) = cx.typeck_results().qpath_res(repl_func_qpath, repl_func.hir_id).opt_def_id(); then { if cx.tcx.is_diagnostic_item(sym::mem_uninitialized, repl_def_id) { let mut applicability = Applicability::MachineApplicable; @@ -179,7 +190,7 @@ fn check_replace_with_uninit(cx: &LateContext<'_, '_>, src: &Expr<'_>, dest: &Ex applicability, ); } else if cx.tcx.is_diagnostic_item(sym::mem_zeroed, repl_def_id) && - !cx.tables().expr_ty(src).is_primitive() { + !cx.typeck_results().expr_ty(src).is_primitive() { span_lint_and_help( cx, MEM_REPLACE_WITH_UNINIT, @@ -193,12 +204,17 @@ fn check_replace_with_uninit(cx: &LateContext<'_, '_>, src: &Expr<'_>, dest: &Ex } } -fn check_replace_with_default(cx: &LateContext<'_, '_>, src: &Expr<'_>, dest: &Expr<'_>, expr_span: Span) { +fn check_replace_with_default( + cx: &LateContext<'_, '_>, + src: &Expr<'_>, + dest: &Expr<'_>, + expr_span: Span, +) { if let ExprKind::Call(ref repl_func, _) = src.kind { if_chain! { if !in_external_macro(cx.tcx.sess, expr_span); if let ExprKind::Path(ref repl_func_qpath) = repl_func.kind; - if let Some(repl_def_id) = cx.tables().qpath_res(repl_func_qpath, repl_func.hir_id).opt_def_id(); + if let Some(repl_def_id) = cx.typeck_results().qpath_res(repl_func_qpath, repl_func.hir_id).opt_def_id(); if match_def_path(cx, repl_def_id, &paths::DEFAULT_TRAIT_METHOD); then { span_lint_and_then( @@ -230,7 +246,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MemReplace { // Check that `expr` is a call to `mem::replace()` if let ExprKind::Call(ref func, ref func_args) = expr.kind; if let ExprKind::Path(ref func_qpath) = func.kind; - if let Some(def_id) = cx.tables().qpath_res(func_qpath, func.hir_id).opt_def_id(); + if let Some(def_id) = cx.typeck_results().qpath_res(func_qpath, func.hir_id).opt_def_id(); if match_def_path(cx, def_id, &paths::MEM_REPLACE); if let [dest, src] = &**func_args; then { diff --git a/src/tools/clippy/clippy_lints/src/methods/bind_instead_of_map.rs b/src/tools/clippy/clippy_lints/src/methods/bind_instead_of_map.rs index 092702c8b8c7b..ed420d3dea353 100644 --- a/src/tools/clippy/clippy_lints/src/methods/bind_instead_of_map.rs +++ b/src/tools/clippy/clippy_lints/src/methods/bind_instead_of_map.rs @@ -157,7 +157,7 @@ pub(crate) trait BindInsteadOfMap { /// Lint use of `_.and_then(|x| Some(y))` for `Option`s fn lint(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) { - if !match_type(cx, cx.tables().expr_ty(&args[0]), Self::TYPE_QPATH) { + if !match_type(cx, cx.typeck_results().expr_ty(&args[0]), Self::TYPE_QPATH) { return; } diff --git a/src/tools/clippy/clippy_lints/src/methods/inefficient_to_string.rs b/src/tools/clippy/clippy_lints/src/methods/inefficient_to_string.rs index d29b9adcb7d43..61f15272acdf4 100644 --- a/src/tools/clippy/clippy_lints/src/methods/inefficient_to_string.rs +++ b/src/tools/clippy/clippy_lints/src/methods/inefficient_to_string.rs @@ -11,9 +11,9 @@ use rustc_middle::ty::{self, Ty}; /// Checks for the `INEFFICIENT_TO_STRING` lint pub fn lint<'tcx>(cx: &LateContext<'_, 'tcx>, expr: &hir::Expr<'_>, arg: &hir::Expr<'_>, arg_ty: Ty<'tcx>) { if_chain! { - if let Some(to_string_meth_did) = cx.tables().type_dependent_def_id(expr.hir_id); + if let Some(to_string_meth_did) = cx.typeck_results().type_dependent_def_id(expr.hir_id); if match_def_path(cx, to_string_meth_did, &paths::TO_STRING_METHOD); - if let Some(substs) = cx.tables().node_substs_opt(expr.hir_id); + if let Some(substs) = cx.typeck_results().node_substs_opt(expr.hir_id); let self_ty = substs.type_at(0); let (deref_self_ty, deref_count) = walk_ptrs_ty_depth(self_ty); if deref_count >= 1; diff --git a/src/tools/clippy/clippy_lints/src/methods/manual_saturating_arithmetic.rs b/src/tools/clippy/clippy_lints/src/methods/manual_saturating_arithmetic.rs index eb02314f4680a..73ab49e37eb1c 100644 --- a/src/tools/clippy/clippy_lints/src/methods/manual_saturating_arithmetic.rs +++ b/src/tools/clippy/clippy_lints/src/methods/manual_saturating_arithmetic.rs @@ -11,7 +11,7 @@ pub fn lint(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, args: &[&[hir::Expr< let arith_lhs = &args[1][0]; let arith_rhs = &args[1][1]; - let ty = cx.tables().expr_ty(arith_lhs); + let ty = cx.typeck_results().expr_ty(arith_lhs); if !ty.is_integral() { return; } @@ -101,7 +101,7 @@ fn is_min_or_max<'tcx>(cx: &LateContext<'_, 'tcx>, expr: &hir::Expr<'_>) -> Opti } } - let ty = cx.tables().expr_ty(expr); + let ty = cx.typeck_results().expr_ty(expr); let ty_str = ty.to_string(); // `std::T::MAX` `std::T::MIN` constants diff --git a/src/tools/clippy/clippy_lints/src/methods/mod.rs b/src/tools/clippy/clippy_lints/src/methods/mod.rs index c4e707ecf03ad..b11e34926eae8 100644 --- a/src/tools/clippy/clippy_lints/src/methods/mod.rs +++ b/src/tools/clippy/clippy_lints/src/methods/mod.rs @@ -1433,7 +1433,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Methods { lint_or_fun_call(cx, expr, *method_span, &method_call.ident.as_str(), args); lint_expect_fun_call(cx, expr, *method_span, &method_call.ident.as_str(), args); - let self_ty = cx.tables().expr_ty_adjusted(&args[0]); + let self_ty = cx.typeck_results().expr_ty_adjusted(&args[0]); if args.len() == 1 && method_call.ident.name == sym!(clone) { lint_clone_on_copy(cx, expr, &args[0], self_ty); lint_clone_on_ref_ptr(cx, expr, &args[0]); @@ -1639,7 +1639,7 @@ fn lint_or_fun_call<'a, 'tcx>( if let hir::ExprKind::Path(ref qpath) = fun.kind; let path = &*last_path_segment(qpath).ident.as_str(); if ["default", "new"].contains(&path); - let arg_ty = cx.tables().expr_ty(arg); + let arg_ty = cx.typeck_results().expr_ty(arg); if let Some(default_trait_id) = get_trait_def_id(cx, &paths::DEFAULT_TRAIT); if implements_trait(cx, arg_ty, default_trait_id, &[]); @@ -1679,7 +1679,7 @@ fn lint_or_fun_call<'a, 'tcx>( ) { if let hir::ExprKind::MethodCall(ref path, _, ref args, _) = &arg.kind { if path.ident.as_str() == "len" { - let ty = walk_ptrs_ty(cx.tables().expr_ty(&args[0])); + let ty = walk_ptrs_ty(cx.typeck_results().expr_ty(&args[0])); match ty.kind { ty::Slice(_) | ty::Array(_, _) => return, @@ -1707,7 +1707,7 @@ fn lint_or_fun_call<'a, 'tcx>( if { finder.visit_expr(&arg); finder.found }; if !contains_return(&arg); - let self_ty = cx.tables().expr_ty(self_expr); + let self_ty = cx.typeck_results().expr_ty(self_expr); if let Some(&(_, fn_has_arguments, poss, suffix)) = know_types.iter().find(|&&i| match_type(cx, self_ty, i.0)); @@ -1786,7 +1786,7 @@ fn lint_expect_fun_call( if call_args.len() == 1 && (method_name.ident.name == sym!(as_str) || method_name.ident.name == sym!(as_ref)) && { - let arg_type = cx.tables().expr_ty(&call_args[0]); + let arg_type = cx.typeck_results().expr_ty(&call_args[0]); let base_type = walk_ptrs_ty(arg_type); base_type.kind == ty::Str || is_type_diagnostic_item(cx, base_type, sym!(string_type)) } @@ -1805,7 +1805,7 @@ fn lint_expect_fun_call( // Only `&'static str` or `String` can be used directly in the `panic!`. Other types should be // converted to string. fn requires_to_string(cx: &LateContext<'_, '_>, arg: &hir::Expr<'_>) -> bool { - let arg_ty = cx.tables().expr_ty(arg); + let arg_ty = cx.typeck_results().expr_ty(arg); if is_type_diagnostic_item(cx, arg_ty, sym!(string_type)) { return false; } @@ -1824,7 +1824,7 @@ fn lint_expect_fun_call( hir::ExprKind::Lit(_) => true, hir::ExprKind::Call(fun, _) => { if let hir::ExprKind::Path(ref p) = fun.kind { - match cx.tables().qpath_res(p, fun.hir_id) { + match cx.typeck_results().qpath_res(p, fun.hir_id) { hir::def::Res::Def(hir::def::DefKind::Fn | hir::def::DefKind::AssocFn, def_id) => matches!( cx.tcx.fn_sig(def_id).output().skip_binder().kind, ty::Ref(ty::ReStatic, ..) @@ -1836,7 +1836,7 @@ fn lint_expect_fun_call( } }, hir::ExprKind::MethodCall(..) => cx - .tables() + .typeck_results() .type_dependent_def_id(arg.hir_id) .map_or(false, |method_id| { matches!( @@ -1844,7 +1844,7 @@ fn lint_expect_fun_call( ty::Ref(ty::ReStatic, ..) ) }), - hir::ExprKind::Path(ref p) => match cx.tables().qpath_res(p, arg.hir_id) { + hir::ExprKind::Path(ref p) => match cx.typeck_results().qpath_res(p, arg.hir_id) { hir::def::Res::Def(hir::def::DefKind::Const | hir::def::DefKind::Static, _) => true, _ => false, }, @@ -1891,7 +1891,7 @@ fn lint_expect_fun_call( return; } - let receiver_type = cx.tables().expr_ty_adjusted(&args[0]); + let receiver_type = cx.typeck_results().expr_ty_adjusted(&args[0]); let closure_args = if is_type_diagnostic_item(cx, receiver_type, sym!(option_type)) { "||" } else if is_type_diagnostic_item(cx, receiver_type, sym!(result_type)) { @@ -1957,7 +1957,7 @@ fn lint_expect_fun_call( /// Checks for the `CLONE_ON_COPY` lint. fn lint_clone_on_copy(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, arg: &hir::Expr<'_>, arg_ty: Ty<'_>) { - let ty = cx.tables().expr_ty(expr); + let ty = cx.typeck_results().expr_ty(expr); if let ty::Ref(_, inner, _) = arg_ty.kind { if let ty::Ref(_, innermost, _) = inner.kind { span_lint_and_then( @@ -2021,11 +2021,11 @@ fn lint_clone_on_copy(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, arg: &hir: } // x.clone() might have dereferenced x, possibly through Deref impls - if cx.tables().expr_ty(arg) == ty { + if cx.typeck_results().expr_ty(arg) == ty { snip = Some(("try removing the `clone` call", format!("{}", snippet))); } else { let deref_count = cx - .tables() + .typeck_results() .expr_adjustments(arg) .iter() .filter(|adj| { @@ -2051,7 +2051,7 @@ fn lint_clone_on_copy(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, arg: &hir: } fn lint_clone_on_ref_ptr(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, arg: &hir::Expr<'_>) { - let obj_ty = walk_ptrs_ty(cx.tables().expr_ty(arg)); + let obj_ty = walk_ptrs_ty(cx.typeck_results().expr_ty(arg)); if let ty::Adt(_, subst) = obj_ty.kind { let caller_type = if is_type_diagnostic_item(cx, obj_ty, sym::Rc) { @@ -2085,7 +2085,7 @@ fn lint_string_extend(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, args: &[hi let arg = &args[1]; if let Some(arglists) = method_chain_args(arg, &["chars"]) { let target = &arglists[0][0]; - let self_ty = walk_ptrs_ty(cx.tables().expr_ty(target)); + let self_ty = walk_ptrs_ty(cx.typeck_results().expr_ty(target)); let ref_str = if self_ty.kind == ty::Str { "" } else if is_type_diagnostic_item(cx, self_ty, sym!(string_type)) { @@ -2113,7 +2113,7 @@ fn lint_string_extend(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, args: &[hi } fn lint_extend(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) { - let obj_ty = walk_ptrs_ty(cx.tables().expr_ty(&args[0])); + let obj_ty = walk_ptrs_ty(cx.typeck_results().expr_ty(&args[0])); if is_type_diagnostic_item(cx, obj_ty, sym!(string_type)) { lint_string_extend(cx, expr, args); } @@ -2121,7 +2121,7 @@ fn lint_extend(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, args: &[hir::Expr fn lint_cstring_as_ptr(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, source: &hir::Expr<'_>, unwrap: &hir::Expr<'_>) { if_chain! { - let source_type = cx.tables().expr_ty(source); + let source_type = cx.typeck_results().expr_ty(source); if let ty::Adt(def, substs) = source_type.kind; if cx.tcx.is_diagnostic_item(sym!(result_type), def.did); if match_type(cx, substs.type_at(0), &paths::CSTRING); @@ -2145,8 +2145,8 @@ fn lint_iter_cloned_collect<'a, 'tcx>( iter_args: &'tcx [hir::Expr<'_>], ) { if_chain! { - if is_type_diagnostic_item(cx, cx.tables().expr_ty(expr), sym!(vec_type)); - if let Some(slice) = derefs_to_slice(cx, &iter_args[0], cx.tables().expr_ty(&iter_args[0])); + if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(expr), sym!(vec_type)); + if let Some(slice) = derefs_to_slice(cx, &iter_args[0], cx.typeck_results().expr_ty(&iter_args[0])); if let Some(to_replace) = expr.span.trim_start(slice.span.source_callsite()); then { @@ -2253,7 +2253,7 @@ fn lint_unnecessary_fold(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, fold_ar fn lint_step_by<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &hir::Expr<'_>, args: &'tcx [hir::Expr<'_>]) { if match_trait_method(cx, expr, &paths::ITERATOR) { - if let Some((Constant::Int(0), _)) = constant(cx, cx.tables(), &args[1]) { + if let Some((Constant::Int(0), _)) = constant(cx, cx.typeck_results(), &args[1]) { span_lint( cx, ITERATOR_STEP_BY_ZERO, @@ -2277,7 +2277,7 @@ fn lint_iter_next<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr<'_ parent_expr_opt = get_parent_expr(cx, parent_expr); } - if derefs_to_slice(cx, caller_expr, cx.tables().expr_ty(caller_expr)).is_some() { + if derefs_to_slice(cx, caller_expr, cx.typeck_results().expr_ty(caller_expr)).is_some() { // caller is a Slice if_chain! { if let hir::ExprKind::Index(ref caller_var, ref index_expr) = &caller_expr.kind; @@ -2298,8 +2298,8 @@ fn lint_iter_next<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr<'_ ); } } - } else if is_type_diagnostic_item(cx, cx.tables().expr_ty(caller_expr), sym!(vec_type)) - || matches!(&walk_ptrs_ty(cx.tables().expr_ty(caller_expr)).kind, ty::Array(_, _)) + } else if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(caller_expr), sym!(vec_type)) + || matches!(&walk_ptrs_ty(cx.typeck_results().expr_ty(caller_expr)).kind, ty::Array(_, _)) { // caller is a Vec or an Array let mut applicability = Applicability::MachineApplicable; @@ -2326,11 +2326,11 @@ fn lint_iter_nth<'a, 'tcx>( ) { let iter_args = nth_and_iter_args[1]; let mut_str = if is_mut { "_mut" } else { "" }; - let caller_type = if derefs_to_slice(cx, &iter_args[0], cx.tables().expr_ty(&iter_args[0])).is_some() { + let caller_type = if derefs_to_slice(cx, &iter_args[0], cx.typeck_results().expr_ty(&iter_args[0])).is_some() { "slice" - } else if is_type_diagnostic_item(cx, cx.tables().expr_ty(&iter_args[0]), sym!(vec_type)) { + } else if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&iter_args[0]), sym!(vec_type)) { "Vec" - } else if is_type_diagnostic_item(cx, cx.tables().expr_ty(&iter_args[0]), sym!(vecdeque_type)) { + } else if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&iter_args[0]), sym!(vecdeque_type)) { "VecDeque" } else { let nth_args = nth_and_iter_args[0]; @@ -2351,7 +2351,7 @@ fn lint_iter_nth<'a, 'tcx>( fn lint_iter_nth_zero<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &hir::Expr<'_>, nth_args: &'tcx [hir::Expr<'_>]) { if_chain! { if match_trait_method(cx, expr, &paths::ITERATOR); - if let Some((Constant::Int(0), _)) = constant(cx, cx.tables(), &nth_args[1]); + if let Some((Constant::Int(0), _)) = constant(cx, cx.typeck_results(), &nth_args[1]); then { let mut applicability = Applicability::MachineApplicable; span_lint_and_sugg( @@ -2376,7 +2376,7 @@ fn lint_get_unwrap<'a, 'tcx>( // Note: we don't want to lint `get_mut().unwrap` for `HashMap` or `BTreeMap`, // because they do not implement `IndexMut` let mut applicability = Applicability::MachineApplicable; - let expr_ty = cx.tables().expr_ty(&get_args[0]); + let expr_ty = cx.typeck_results().expr_ty(&get_args[0]); let get_args_str = if get_args.len() > 1 { snippet_with_applicability(cx, get_args[1].span, "_", &mut applicability) } else { @@ -2482,7 +2482,7 @@ fn derefs_to_slice<'a, 'tcx>( } if let hir::ExprKind::MethodCall(ref path, _, ref args, _) = expr.kind { - if path.ident.name == sym!(iter) && may_slice(cx, cx.tables().expr_ty(&args[0])) { + if path.ident.name == sym!(iter) && may_slice(cx, cx.typeck_results().expr_ty(&args[0])) { Some(&args[0]) } else { None @@ -2505,7 +2505,7 @@ fn derefs_to_slice<'a, 'tcx>( /// lint use of `unwrap()` for `Option`s and `Result`s fn lint_unwrap(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, unwrap_args: &[hir::Expr<'_>]) { - let obj_ty = walk_ptrs_ty(cx.tables().expr_ty(&unwrap_args[0])); + let obj_ty = walk_ptrs_ty(cx.typeck_results().expr_ty(&unwrap_args[0])); let mess = if is_type_diagnostic_item(cx, obj_ty, sym!(option_type)) { Some((UNWRAP_USED, "an Option", "None")) @@ -2533,7 +2533,7 @@ fn lint_unwrap(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, unwrap_args: &[hi /// lint use of `expect()` for `Option`s and `Result`s fn lint_expect(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, expect_args: &[hir::Expr<'_>]) { - let obj_ty = walk_ptrs_ty(cx.tables().expr_ty(&expect_args[0])); + let obj_ty = walk_ptrs_ty(cx.typeck_results().expr_ty(&expect_args[0])); let mess = if is_type_diagnostic_item(cx, obj_ty, sym!(option_type)) { Some((EXPECT_USED, "an Option", "None")) @@ -2559,8 +2559,8 @@ fn lint_expect(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, expect_args: &[hi fn lint_ok_expect(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, ok_args: &[hir::Expr<'_>]) { if_chain! { // lint if the caller of `ok()` is a `Result` - if is_type_diagnostic_item(cx, cx.tables().expr_ty(&ok_args[0]), sym!(result_type)); - let result_type = cx.tables().expr_ty(&ok_args[0]); + if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&ok_args[0]), sym!(result_type)); + let result_type = cx.typeck_results().expr_ty(&ok_args[0]); if let Some(error_type) = get_error_type(cx, result_type); if has_debug_impl(error_type, cx); @@ -2598,7 +2598,7 @@ fn lint_map_flatten<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr< } // lint if caller of `.map().flatten()` is an Option - if is_type_diagnostic_item(cx, cx.tables().expr_ty(&map_args[0]), sym!(option_type)) { + if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&map_args[0]), sym!(option_type)) { let msg = "called `map(..).flatten()` on an `Option`. \ This is more succinctly expressed by calling `.and_then(..)`"; let self_snippet = snippet(cx, map_args[0].span, ".."); @@ -2624,8 +2624,8 @@ fn lint_map_unwrap_or_else<'a, 'tcx>( unwrap_args: &'tcx [hir::Expr<'_>], ) { // lint if the caller of `map()` is an `Option` - let is_option = is_type_diagnostic_item(cx, cx.tables().expr_ty(&map_args[0]), sym!(option_type)); - let is_result = is_type_diagnostic_item(cx, cx.tables().expr_ty(&map_args[0]), sym!(result_type)); + let is_option = is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&map_args[0]), sym!(option_type)); + let is_result = is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&map_args[0]), sym!(result_type)); if is_option || is_result { // Don't make a suggestion that may fail to compile due to mutably borrowing @@ -2679,8 +2679,8 @@ fn lint_map_or_none<'a, 'tcx>( expr: &'tcx hir::Expr<'_>, map_or_args: &'tcx [hir::Expr<'_>], ) { - let is_option = is_type_diagnostic_item(cx, cx.tables().expr_ty(&map_or_args[0]), sym!(option_type)); - let is_result = is_type_diagnostic_item(cx, cx.tables().expr_ty(&map_or_args[0]), sym!(result_type)); + let is_option = is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&map_or_args[0]), sym!(option_type)); + let is_result = is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&map_or_args[0]), sym!(result_type)); // There are two variants of this `map_or` lint: // (1) using `map_or` as an adapter from `Result` to `Option` @@ -3045,7 +3045,7 @@ fn lint_chars_cmp( if segment.ident.name == sym!(Some); then { let mut applicability = Applicability::MachineApplicable; - let self_ty = walk_ptrs_ty(cx.tables().expr_ty_adjusted(&args[0][0])); + let self_ty = walk_ptrs_ty(cx.typeck_results().expr_ty_adjusted(&args[0][0])); if self_ty.kind != ty::Str { return false; @@ -3177,8 +3177,8 @@ fn lint_asref(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, call_name: &str, a if match_trait_method(cx, expr, &paths::ASREF_TRAIT) || match_trait_method(cx, expr, &paths::ASMUT_TRAIT) { // check if the type after `as_ref` or `as_mut` is the same as before let recvr = &as_ref_args[0]; - let rcv_ty = cx.tables().expr_ty(recvr); - let res_ty = cx.tables().expr_ty(expr); + let rcv_ty = cx.typeck_results().expr_ty(recvr); + let res_ty = cx.typeck_results().expr_ty(expr); let (base_res_ty, res_depth) = walk_ptrs_ty_depth(res_ty); let (base_rcv_ty, rcv_depth) = walk_ptrs_ty_depth(rcv_ty); if base_rcv_ty == base_res_ty && rcv_depth >= res_depth { @@ -3247,7 +3247,7 @@ fn lint_maybe_uninit(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, outer: &hir if args.is_empty(); if let hir::ExprKind::Path(ref path) = callee.kind; if match_qpath(path, &paths::MEM_MAYBEUNINIT_UNINIT); - if !is_maybe_uninit_ty_valid(cx, cx.tables().expr_ty_adjusted(outer)); + if !is_maybe_uninit_ty_valid(cx, cx.typeck_results().expr_ty_adjusted(outer)); then { span_lint( cx, @@ -3289,7 +3289,7 @@ fn lint_option_as_ref_deref<'a, 'tcx>( ) { let same_mutability = |m| (is_mut && m == &hir::Mutability::Mut) || (!is_mut && m == &hir::Mutability::Not); - let option_ty = cx.tables().expr_ty(&as_ref_args[0]); + let option_ty = cx.typeck_results().expr_ty(&as_ref_args[0]); if !is_type_diagnostic_item(cx, option_ty, sym!(option_type)) { return; } @@ -3317,12 +3317,12 @@ fn lint_option_as_ref_deref<'a, 'tcx>( if_chain! { if args.len() == 1; if let hir::ExprKind::Path(qpath) = &args[0].kind; - if let hir::def::Res::Local(local_id) = cx.tables().qpath_res(qpath, args[0].hir_id); + if let hir::def::Res::Local(local_id) = cx.typeck_results().qpath_res(qpath, args[0].hir_id); if closure_body.params[0].pat.hir_id == local_id; - let adj = cx.tables().expr_adjustments(&args[0]).iter().map(|x| &x.kind).collect::>(); + let adj = cx.typeck_results().expr_adjustments(&args[0]).iter().map(|x| &x.kind).collect::>(); if let [ty::adjustment::Adjust::Deref(None), ty::adjustment::Adjust::Borrow(_)] = *adj; then { - let method_did = cx.tables().type_dependent_def_id(closure_expr.hir_id).unwrap(); + let method_did = cx.typeck_results().type_dependent_def_id(closure_expr.hir_id).unwrap(); deref_aliases.iter().any(|path| match_def_path(cx, method_did, path)) } else { false @@ -3334,7 +3334,7 @@ fn lint_option_as_ref_deref<'a, 'tcx>( if let hir::ExprKind::Unary(hir::UnOp::UnDeref, ref inner1) = inner.kind; if let hir::ExprKind::Unary(hir::UnOp::UnDeref, ref inner2) = inner1.kind; if let hir::ExprKind::Path(ref qpath) = inner2.kind; - if let hir::def::Res::Local(local_id) = cx.tables().qpath_res(qpath, inner2.hir_id); + if let hir::def::Res::Local(local_id) = cx.typeck_results().qpath_res(qpath, inner2.hir_id); then { closure_body.params[0].pat.hir_id == local_id } else { @@ -3617,7 +3617,7 @@ fn contains_return(expr: &hir::Expr<'_>) -> bool { fn check_pointer_offset(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) { if_chain! { if args.len() == 2; - if let ty::RawPtr(ty::TypeAndMut { ref ty, .. }) = cx.tables().expr_ty(&args[0]).kind; + if let ty::RawPtr(ty::TypeAndMut { ref ty, .. }) = cx.typeck_results().expr_ty(&args[0]).kind; if let Ok(layout) = cx.tcx.layout_of(cx.param_env.and(ty)); if layout.is_zst(); then { @@ -3627,7 +3627,7 @@ fn check_pointer_offset(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, args: &[ } fn lint_filetype_is_file(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, args: &[hir::Expr<'_>]) { - let ty = cx.tables().expr_ty(&args[0]); + let ty = cx.typeck_results().expr_ty(&args[0]); if !match_type(cx, ty, &paths::FILE_TYPE) { return; diff --git a/src/tools/clippy/clippy_lints/src/methods/option_map_unwrap_or.rs b/src/tools/clippy/clippy_lints/src/methods/option_map_unwrap_or.rs index 7f4529a5870ac..66955a462a9f4 100644 --- a/src/tools/clippy/clippy_lints/src/methods/option_map_unwrap_or.rs +++ b/src/tools/clippy/clippy_lints/src/methods/option_map_unwrap_or.rs @@ -20,8 +20,8 @@ pub(super) fn lint<'a, 'tcx>( map_span: Span, ) { // lint if the caller of `map()` is an `Option` - if is_type_diagnostic_item(cx, cx.tables().expr_ty(&map_args[0]), sym!(option_type)) { - if !is_copy(cx, cx.tables().expr_ty(&unwrap_args[1])) { + if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&map_args[0]), sym!(option_type)) { + if !is_copy(cx, cx.typeck_results().expr_ty(&unwrap_args[1])) { // Do not lint if the `map` argument uses identifiers in the `map` // argument that are also used in the `unwrap_or` argument diff --git a/src/tools/clippy/clippy_lints/src/methods/unnecessary_filter_map.rs b/src/tools/clippy/clippy_lints/src/methods/unnecessary_filter_map.rs index 88243a88d9dd7..28b4b683ae03a 100644 --- a/src/tools/clippy/clippy_lints/src/methods/unnecessary_filter_map.rs +++ b/src/tools/clippy/clippy_lints/src/methods/unnecessary_filter_map.rs @@ -65,7 +65,7 @@ fn check_expression<'a, 'tcx>( if match_qpath(path, &paths::OPTION_SOME) { if_chain! { if let hir::ExprKind::Path(path) = &args[0].kind; - if let Res::Local(ref local) = cx.tables().qpath_res(path, args[0].hir_id); + if let Res::Local(ref local) = cx.typeck_results().qpath_res(path, args[0].hir_id); then { if arg_id == *local { return (false, false) diff --git a/src/tools/clippy/clippy_lints/src/minmax.rs b/src/tools/clippy/clippy_lints/src/minmax.rs index 8e6f3925d6605..8a9948e1a00ec 100644 --- a/src/tools/clippy/clippy_lints/src/minmax.rs +++ b/src/tools/clippy/clippy_lints/src/minmax.rs @@ -36,7 +36,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MinMaxPass { } match ( outer_max, - Constant::partial_cmp(cx.tcx, cx.tables().expr_ty(ie), &outer_c, &inner_c), + Constant::partial_cmp(cx.tcx, cx.typeck_results().expr_ty(ie), &outer_c, &inner_c), ) { (_, None) | (MinMax::Max, Some(Ordering::Less)) | (MinMax::Min, Some(Ordering::Greater)) => (), _ => { @@ -62,7 +62,7 @@ enum MinMax { fn min_max<'a>(cx: &LateContext<'_, '_>, expr: &'a Expr<'a>) -> Option<(MinMax, Constant, &'a Expr<'a>)> { if let ExprKind::Call(ref path, ref args) = expr.kind { if let ExprKind::Path(ref qpath) = path.kind { - cx.tables() + cx.typeck_results() .qpath_res(qpath, path.hir_id) .opt_def_id() .and_then(|def_id| { @@ -90,14 +90,14 @@ fn fetch_const<'a>( if args.len() != 2 { return None; } - if let Some(c) = constant_simple(cx, cx.tables(), &args[0]) { - if constant_simple(cx, cx.tables(), &args[1]).is_none() { + if let Some(c) = constant_simple(cx, cx.typeck_results(), &args[0]) { + if constant_simple(cx, cx.typeck_results(), &args[1]).is_none() { // otherwise ignore Some((m, c, &args[1])) } else { None } - } else if let Some(c) = constant_simple(cx, cx.tables(), &args[1]) { + } else if let Some(c) = constant_simple(cx, cx.typeck_results(), &args[1]) { Some((m, c, &args[0])) } else { None diff --git a/src/tools/clippy/clippy_lints/src/misc.rs b/src/tools/clippy/clippy_lints/src/misc.rs index 99cd864cae4e3..e078375d9754b 100644 --- a/src/tools/clippy/clippy_lints/src/misc.rs +++ b/src/tools/clippy/clippy_lints/src/misc.rs @@ -3,8 +3,8 @@ use rustc_ast::ast::LitKind; use rustc_errors::Applicability; use rustc_hir::intravisit::FnKind; use rustc_hir::{ - def, BinOpKind, BindingAnnotation, Body, Expr, ExprKind, FnDecl, HirId, Mutability, PatKind, Stmt, StmtKind, Ty, - TyKind, UnOp, + def, BinOpKind, BindingAnnotation, Body, Expr, ExprKind, FnDecl, HirId, Mutability, PatKind, + Stmt, StmtKind, Ty, TyKind, UnOp, }; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty; @@ -15,9 +15,10 @@ use rustc_span::source_map::{ExpnKind, Span}; use crate::consts::{constant, Constant}; use crate::utils::sugg::Sugg; use crate::utils::{ - get_item_name, get_parent_expr, higher, implements_trait, in_constant, is_integer_const, iter_input_pats, - last_path_segment, match_qpath, match_trait_method, paths, snippet, snippet_opt, span_lint, span_lint_and_sugg, - span_lint_and_then, span_lint_hir_and_then, walk_ptrs_ty, SpanlessEq, + get_item_name, get_parent_expr, higher, implements_trait, in_constant, is_integer_const, + iter_input_pats, last_path_segment, match_qpath, match_trait_method, paths, snippet, + snippet_opt, span_lint, span_lint_and_sugg, span_lint_and_then, span_lint_hir_and_then, + walk_ptrs_ty, SpanlessEq, }; declare_clippy_lint! { @@ -275,7 +276,9 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MiscLints { return; } for arg in iter_input_pats(decl, body) { - if let PatKind::Binding(BindingAnnotation::Ref | BindingAnnotation::RefMut, ..) = arg.pat.kind { + if let PatKind::Binding(BindingAnnotation::Ref | BindingAnnotation::RefMut, ..) = + arg.pat.kind + { span_lint( cx, TOPLEVEL_REF_ARG, @@ -365,7 +368,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MiscLints { ExprKind::Cast(ref e, ref ty) => { check_cast(cx, expr.span, e, ty); return; - }, + } ExprKind::Binary(ref cmp, ref left, ref right) => { let op = cmp.node; if op.is_comparison() { @@ -374,7 +377,9 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MiscLints { check_to_owned(cx, left, right); check_to_owned(cx, right, left); } - if (op == BinOpKind::Eq || op == BinOpKind::Ne) && (is_float(cx, left) || is_float(cx, right)) { + if (op == BinOpKind::Eq || op == BinOpKind::Ne) + && (is_float(cx, left) || is_float(cx, right)) + { if is_allowed(cx, left) || is_allowed(cx, right) { return; } @@ -416,13 +421,15 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MiscLints { Applicability::HasPlaceholders, // snippet ); } - diag.note("`f32::EPSILON` and `f64::EPSILON` are available for the `error`"); + diag.note( + "`f32::EPSILON` and `f64::EPSILON` are available for the `error`", + ); }); } else if op == BinOpKind::Rem && is_integer_const(cx, right, 1) { span_lint(cx, MODULO_ONE, expr.span, "any number modulo 1 will be 0"); } - }, - _ => {}, + } + _ => {} } if in_attributes_expansion(expr) || expr.span.is_desugaring(DesugaringKind::Await) { // Don't lint things expanded by #[derive(...)], etc or `await` desugaring @@ -436,21 +443,17 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MiscLints { binding != "_result" && // FIXME: #944 is_used(cx, expr) && // don't lint if the declaration is in a macro - non_macro_local(cx, cx.tables().qpath_res(qpath, expr.hir_id)) + non_macro_local(cx, cx.typeck_results().qpath_res(qpath, expr.hir_id)) { Some(binding) } else { None } - }, + } ExprKind::Field(_, ident) => { let name = ident.as_str(); - if name.starts_with('_') && !name.starts_with("__") { - Some(name) - } else { - None - } - }, + if name.starts_with('_') && !name.starts_with("__") { Some(name) } else { None } + } _ => None, }; if let Some(binding) = binding { @@ -496,7 +499,7 @@ fn get_lint_and_message( fn check_nan(cx: &LateContext<'_, '_>, expr: &Expr<'_>, cmp_expr: &Expr<'_>) { if_chain! { if !in_constant(cx, cmp_expr.hir_id); - if let Some((value, _)) = constant(cx, cx.tables(), expr); + if let Some((value, _)) = constant(cx, cx.typeck_results(), expr); then { let needs_lint = match value { Constant::F32(num) => num.is_nan(), @@ -517,15 +520,11 @@ fn check_nan(cx: &LateContext<'_, '_>, expr: &Expr<'_>, cmp_expr: &Expr<'_>) { } fn is_named_constant<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) -> bool { - if let Some((_, res)) = constant(cx, cx.tables(), expr) { - res - } else { - false - } + if let Some((_, res)) = constant(cx, cx.typeck_results(), expr) { res } else { false } } fn is_allowed<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) -> bool { - match constant(cx, cx.tables(), expr) { + match constant(cx, cx.typeck_results(), expr) { Some((Constant::F32(f), _)) => f == 0.0 || f.is_infinite(), Some((Constant::F64(f), _)) => f == 0.0 || f.is_infinite(), Some((Constant::Vec(vec), _)) => vec.iter().all(|f| match f { @@ -557,7 +556,7 @@ fn is_signum(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> bool { } fn is_float(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> bool { - let value = &walk_ptrs_ty(cx.tables().expr_ty(expr)).kind; + let value = &walk_ptrs_ty(cx.typeck_results().expr_ty(expr)).kind; if let ty::Array(arr_ty, _) = value { return matches!(arr_ty.kind, ty::Float(_)); @@ -567,47 +566,55 @@ fn is_float(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> bool { } fn is_array(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> bool { - matches!(&walk_ptrs_ty(cx.tables().expr_ty(expr)).kind, ty::Array(_, _)) + matches!(&walk_ptrs_ty(cx.typeck_results().expr_ty(expr)).kind, ty::Array(_, _)) } fn check_to_owned(cx: &LateContext<'_, '_>, expr: &Expr<'_>, other: &Expr<'_>) { let (arg_ty, snip) = match expr.kind { ExprKind::MethodCall(.., ref args, _) if args.len() == 1 => { - if match_trait_method(cx, expr, &paths::TO_STRING) || match_trait_method(cx, expr, &paths::TO_OWNED) { - (cx.tables().expr_ty_adjusted(&args[0]), snippet(cx, args[0].span, "..")) + if match_trait_method(cx, expr, &paths::TO_STRING) + || match_trait_method(cx, expr, &paths::TO_OWNED) + { + (cx.typeck_results().expr_ty_adjusted(&args[0]), snippet(cx, args[0].span, "..")) } else { return; } - }, + } ExprKind::Call(ref path, ref v) if v.len() == 1 => { if let ExprKind::Path(ref path) = path.kind { - if match_qpath(path, &["String", "from_str"]) || match_qpath(path, &["String", "from"]) { - (cx.tables().expr_ty_adjusted(&v[0]), snippet(cx, v[0].span, "..")) + if match_qpath(path, &["String", "from_str"]) + || match_qpath(path, &["String", "from"]) + { + (cx.typeck_results().expr_ty_adjusted(&v[0]), snippet(cx, v[0].span, "..")) } else { return; } } else { return; } - }, + } _ => return, }; - let other_ty = cx.tables().expr_ty_adjusted(other); + let other_ty = cx.typeck_results().expr_ty_adjusted(other); let partial_eq_trait_id = match cx.tcx.lang_items().eq_trait() { Some(id) => id, None => return, }; - let deref_arg_impl_partial_eq_other = arg_ty.builtin_deref(true).map_or(false, |tam| { - implements_trait(cx, tam.ty, partial_eq_trait_id, &[other_ty.into()]) - }); - let arg_impl_partial_eq_deref_other = other_ty.builtin_deref(true).map_or(false, |tam| { - implements_trait(cx, arg_ty, partial_eq_trait_id, &[tam.ty.into()]) - }); - let arg_impl_partial_eq_other = implements_trait(cx, arg_ty, partial_eq_trait_id, &[other_ty.into()]); - - if !deref_arg_impl_partial_eq_other && !arg_impl_partial_eq_deref_other && !arg_impl_partial_eq_other { + let deref_arg_impl_partial_eq_other = arg_ty + .builtin_deref(true) + .map_or(false, |tam| implements_trait(cx, tam.ty, partial_eq_trait_id, &[other_ty.into()])); + let arg_impl_partial_eq_deref_other = other_ty + .builtin_deref(true) + .map_or(false, |tam| implements_trait(cx, arg_ty, partial_eq_trait_id, &[tam.ty.into()])); + let arg_impl_partial_eq_other = + implements_trait(cx, arg_ty, partial_eq_trait_id, &[other_ty.into()]); + + if !deref_arg_impl_partial_eq_other + && !arg_impl_partial_eq_deref_other + && !arg_impl_partial_eq_other + { return; } @@ -616,11 +623,7 @@ fn check_to_owned(cx: &LateContext<'_, '_>, expr: &Expr<'_>, other: &Expr<'_>) { _ => false, }; - let lint_span = if other_gets_derefed { - expr.span.to(other.span) - } else { - expr.span - }; + let lint_span = if other_gets_derefed { expr.span.to(other.span) } else { expr.span }; span_lint_and_then( cx, @@ -660,7 +663,7 @@ fn is_used(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> bool { match parent.kind { ExprKind::Assign(_, ref rhs, _) | ExprKind::AssignOp(_, _, ref rhs) => { SpanlessEq::new(cx).eq_expr(rhs, expr) - }, + } _ => is_used(cx, parent), } } else { @@ -675,11 +678,7 @@ fn in_attributes_expansion(expr: &Expr<'_>) -> bool { if expr.span.from_expansion() { let data = expr.span.ctxt().outer_expn_data(); - if let ExpnKind::Macro(MacroKind::Attr, _) = data.kind { - true - } else { - false - } + if let ExpnKind::Macro(MacroKind::Attr, _) = data.kind { true } else { false } } else { false } @@ -687,11 +686,7 @@ fn in_attributes_expansion(expr: &Expr<'_>) -> bool { /// Tests whether `res` is a variable defined outside a macro. fn non_macro_local(cx: &LateContext<'_, '_>, res: def::Res) -> bool { - if let def::Res::Local(id) = res { - !cx.tcx.hir().span(id).from_expansion() - } else { - false - } + if let def::Res::Local(id) = res { !cx.tcx.hir().span(id).from_expansion() } else { false } } fn check_cast(cx: &LateContext<'_, '_>, span: Span, e: &Expr<'_>, ty: &Ty<'_>) { diff --git a/src/tools/clippy/clippy_lints/src/modulo_arithmetic.rs b/src/tools/clippy/clippy_lints/src/modulo_arithmetic.rs index f76e4721e1f63..dd258b211423a 100644 --- a/src/tools/clippy/clippy_lints/src/modulo_arithmetic.rs +++ b/src/tools/clippy/clippy_lints/src/modulo_arithmetic.rs @@ -36,9 +36,13 @@ struct OperandInfo { is_integral: bool, } -fn analyze_operand(operand: &Expr<'_>, cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> Option { - match constant(cx, cx.tables(), operand) { - Some((Constant::Int(v), _)) => match cx.tables().expr_ty(expr).kind { +fn analyze_operand( + operand: &Expr<'_>, + cx: &LateContext<'_, '_>, + expr: &Expr<'_>, +) -> Option { + match constant(cx, cx.typeck_results(), operand) { + Some((Constant::Int(v), _)) => match cx.typeck_results().expr_ty(expr).kind { ty::Int(ity) => { let value = sext(cx.tcx, v, ity); return Some(OperandInfo { @@ -46,23 +50,23 @@ fn analyze_operand(operand: &Expr<'_>, cx: &LateContext<'_, '_>, expr: &Expr<'_> is_negative: value < 0, is_integral: true, }); - }, + } ty::Uint(_) => { return Some(OperandInfo { string_representation: None, is_negative: false, is_integral: true, }); - }, - _ => {}, + } + _ => {} }, Some((Constant::F32(f), _)) => { return Some(floating_point_operand_info(&f)); - }, + } Some((Constant::F64(f), _)) => { return Some(floating_point_operand_info(&f)); - }, - _ => {}, + } + _ => {} } None } @@ -105,8 +109,12 @@ fn check_const_operands<'a, 'tcx>( } } -fn check_non_const_operands<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>, operand: &Expr<'_>) { - let operand_type = cx.tables().expr_ty(operand); +fn check_non_const_operands<'a, 'tcx>( + cx: &LateContext<'a, 'tcx>, + expr: &'tcx Expr<'_>, + operand: &Expr<'_>, +) { + let operand_type = cx.typeck_results().expr_ty(operand); if might_have_negative_value(operand_type) { span_lint_and_then( cx, @@ -141,8 +149,8 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ModuloArithmetic { } } }; - }, - _ => {}, + } + _ => {} } } } diff --git a/src/tools/clippy/clippy_lints/src/mut_key.rs b/src/tools/clippy/clippy_lints/src/mut_key.rs index 755b196c698c2..f6daf810bfde7 100644 --- a/src/tools/clippy/clippy_lints/src/mut_key.rs +++ b/src/tools/clippy/clippy_lints/src/mut_key.rs @@ -76,21 +76,21 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MutableKeyType { if let hir::PatKind::Wild = local.pat.kind { return; } - check_ty(cx, local.span, cx.tables().pat_ty(&*local.pat)); + check_ty(cx, local.span, cx.typeck_results().pat_ty(&*local.pat)); } } -fn check_sig<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, item_hir_id: hir::HirId, decl: &hir::FnDecl<'_>) { +fn check_sig<'a, 'tcx>( + cx: &LateContext<'a, 'tcx>, + item_hir_id: hir::HirId, + decl: &hir::FnDecl<'_>, +) { let fn_def_id = cx.tcx.hir().local_def_id(item_hir_id); let fn_sig = cx.tcx.fn_sig(fn_def_id); for (hir_ty, ty) in decl.inputs.iter().zip(fn_sig.inputs().skip_binder().iter()) { check_ty(cx, hir_ty.span, ty); } - check_ty( - cx, - decl.output.span(), - cx.tcx.erase_late_bound_regions(&fn_sig.output()), - ); + check_ty(cx, decl.output.span(), cx.tcx.erase_late_bound_regions(&fn_sig.output())); } // We want to lint 1. sets or maps with 2. not immutable key types and 3. no unerased @@ -112,13 +112,17 @@ fn is_mutable_type<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>, span: Spa match ty.kind { RawPtr(TypeAndMut { ty: inner_ty, mutbl }) | Ref(_, inner_ty, mutbl) => { mutbl == hir::Mutability::Mut || is_mutable_type(cx, inner_ty, span) - }, + } Slice(inner_ty) => is_mutable_type(cx, inner_ty, span), Array(inner_ty, size) => { - size.try_eval_usize(cx.tcx, cx.param_env).map_or(true, |u| u != 0) && is_mutable_type(cx, inner_ty, span) - }, + size.try_eval_usize(cx.tcx, cx.param_env).map_or(true, |u| u != 0) + && is_mutable_type(cx, inner_ty, span) + } Tuple(..) => ty.tuple_fields().any(|ty| is_mutable_type(cx, ty, span)), - Adt(..) => cx.tcx.layout_of(cx.param_env.and(ty)).is_ok() && !ty.is_freeze(cx.tcx.at(span), cx.param_env), + Adt(..) => { + cx.tcx.layout_of(cx.param_env.and(ty)).is_ok() + && !ty.is_freeze(cx.tcx.at(span), cx.param_env) + } _ => false, } } diff --git a/src/tools/clippy/clippy_lints/src/mut_mut.rs b/src/tools/clippy/clippy_lints/src/mut_mut.rs index 6aa77b4df83aa..799963e6c2ae7 100644 --- a/src/tools/clippy/clippy_lints/src/mut_mut.rs +++ b/src/tools/clippy/clippy_lints/src/mut_mut.rs @@ -69,7 +69,7 @@ impl<'a, 'tcx> intravisit::Visitor<'tcx> for MutVisitor<'a, 'tcx> { expr.span, "generally you want to avoid `&mut &mut _` if possible", ); - } else if let ty::Ref(_, _, hir::Mutability::Mut) = self.cx.tables().expr_ty(e).kind { + } else if let ty::Ref(_, _, hir::Mutability::Mut) = self.cx.typeck_results().expr_ty(e).kind { span_lint( self.cx, MUT_MUT, diff --git a/src/tools/clippy/clippy_lints/src/mut_reference.rs b/src/tools/clippy/clippy_lints/src/mut_reference.rs index dbe257069c3e2..ceb066a3b1240 100644 --- a/src/tools/clippy/clippy_lints/src/mut_reference.rs +++ b/src/tools/clippy/clippy_lints/src/mut_reference.rs @@ -37,17 +37,19 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnnecessaryMutPassed { check_arguments( cx, arguments, - cx.tables().expr_ty(fn_expr), - &rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| s.print_qpath(path, false)), + cx.typeck_results().expr_ty(fn_expr), + &rustc_hir_pretty::to_string(rustc_hir_pretty::NO_ANN, |s| { + s.print_qpath(path, false) + }), ); } - }, + } ExprKind::MethodCall(ref path, _, ref arguments, _) => { - let def_id = cx.tables().type_dependent_def_id(e.hir_id).unwrap(); - let substs = cx.tables().node_substs(e.hir_id); + let def_id = cx.typeck_results().type_dependent_def_id(e.hir_id).unwrap(); + let substs = cx.typeck_results().node_substs(e.hir_id); let method_type = cx.tcx.type_of(def_id).subst(cx.tcx, substs); check_arguments(cx, arguments, method_type, &path.ident.as_str()) - }, + } _ => (), } } @@ -65,22 +67,24 @@ fn check_arguments<'a, 'tcx>( for (argument, parameter) in arguments.iter().zip(parameters.iter()) { match parameter.kind { ty::Ref(_, _, Mutability::Not) - | ty::RawPtr(ty::TypeAndMut { - mutbl: Mutability::Not, .. - }) => { - if let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Mut, _) = argument.kind { + | ty::RawPtr(ty::TypeAndMut { mutbl: Mutability::Not, .. }) => { + if let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Mut, _) = argument.kind + { span_lint( cx, UNNECESSARY_MUT_PASSED, argument.span, - &format!("The function/method `{}` doesn't need a mutable reference", name), + &format!( + "The function/method `{}` doesn't need a mutable reference", + name + ), ); } - }, + } _ => (), } } - }, + } _ => (), } } diff --git a/src/tools/clippy/clippy_lints/src/mutable_debug_assertion.rs b/src/tools/clippy/clippy_lints/src/mutable_debug_assertion.rs index 45db5140711ad..adaeb2d14fbc3 100644 --- a/src/tools/clippy/clippy_lints/src/mutable_debug_assertion.rs +++ b/src/tools/clippy/clippy_lints/src/mutable_debug_assertion.rs @@ -44,7 +44,10 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for DebugAssertWithMutCall { cx, DEBUG_ASSERT_WITH_MUT_CALL, span, - &format!("do not call a function with mutable arguments inside of `{}!`", dmn), + &format!( + "do not call a function with mutable arguments inside of `{}!`", + dmn + ), ); } } @@ -109,19 +112,11 @@ struct MutArgVisitor<'a, 'tcx> { impl<'a, 'tcx> MutArgVisitor<'a, 'tcx> { fn new(cx: &'a LateContext<'a, 'tcx>) -> Self { - Self { - cx, - expr_span: None, - found: false, - } + Self { cx, expr_span: None, found: false } } fn expr_span(&self) -> Option { - if self.found { - self.expr_span - } else { - None - } + if self.found { self.expr_span } else { None } } } @@ -133,18 +128,15 @@ impl<'a, 'tcx> Visitor<'tcx> for MutArgVisitor<'a, 'tcx> { ExprKind::AddrOf(BorrowKind::Ref, Mutability::Mut, _) => { self.found = true; return; - }, + } ExprKind::Path(_) => { - if let Some(adj) = self.cx.tables().adjustments().get(expr.hir_id) { - if adj - .iter() - .any(|a| matches!(a.target.kind, ty::Ref(_, _, Mutability::Mut))) - { + if let Some(adj) = self.cx.typeck_results().adjustments().get(expr.hir_id) { + if adj.iter().any(|a| matches!(a.target.kind, ty::Ref(_, _, Mutability::Mut))) { self.found = true; return; } } - }, + } // Don't check await desugars ExprKind::Match(_, _, MatchSource::AwaitDesugar) => return, _ if !self.found => self.expr_span = Some(expr.span), diff --git a/src/tools/clippy/clippy_lints/src/mutex_atomic.rs b/src/tools/clippy/clippy_lints/src/mutex_atomic.rs index c227dc54f2939..047445a66a3a7 100644 --- a/src/tools/clippy/clippy_lints/src/mutex_atomic.rs +++ b/src/tools/clippy/clippy_lints/src/mutex_atomic.rs @@ -66,7 +66,7 @@ declare_lint_pass!(Mutex => [MUTEX_ATOMIC, MUTEX_INTEGER]); impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Mutex { fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) { - let ty = cx.tables().expr_ty(expr); + let ty = cx.typeck_results().expr_ty(expr); if let ty::Adt(_, subst) = ty.kind { if is_type_diagnostic_item(cx, ty, sym!(mutex_type)) { let mutex_param = subst.type_at(0); diff --git a/src/tools/clippy/clippy_lints/src/needless_bool.rs b/src/tools/clippy/clippy_lints/src/needless_bool.rs index 653f9e2ae8625..016eac6fb03f6 100644 --- a/src/tools/clippy/clippy_lints/src/needless_bool.rs +++ b/src/tools/clippy/clippy_lints/src/needless_bool.rs @@ -229,7 +229,7 @@ fn check_comparison<'a, 'tcx>( use self::Expression::{Bool, Other}; if let ExprKind::Binary(op, ref left_side, ref right_side) = e.kind { - let (l_ty, r_ty) = (cx.tables().expr_ty(left_side), cx.tables().expr_ty(right_side)); + let (l_ty, r_ty) = (cx.typeck_results().expr_ty(left_side), cx.typeck_results().expr_ty(right_side)); if l_ty.is_bool() && r_ty.is_bool() { let mut applicability = Applicability::MachineApplicable; diff --git a/src/tools/clippy/clippy_lints/src/needless_borrow.rs b/src/tools/clippy/clippy_lints/src/needless_borrow.rs index 6bb06defb7034..78ef3a40e8ab4 100644 --- a/src/tools/clippy/clippy_lints/src/needless_borrow.rs +++ b/src/tools/clippy/clippy_lints/src/needless_borrow.rs @@ -46,8 +46,8 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessBorrow { return; } if let ExprKind::AddrOf(BorrowKind::Ref, Mutability::Not, ref inner) = e.kind { - if let ty::Ref(..) = cx.tables().expr_ty(inner).kind { - for adj3 in cx.tables().expr_adjustments(e).windows(3) { + if let ty::Ref(..) = cx.typeck_results().expr_ty(inner).kind { + for adj3 in cx.typeck_results().expr_adjustments(e).windows(3) { if let [Adjustment { kind: Adjust::Deref(_), .. }, Adjustment { @@ -85,7 +85,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessBorrow { } if_chain! { if let PatKind::Binding(BindingAnnotation::Ref, .., name, _) = pat.kind; - if let ty::Ref(_, tam, mutbl) = cx.tables().pat_ty(pat).kind; + if let ty::Ref(_, tam, mutbl) = cx.typeck_results().pat_ty(pat).kind; if mutbl == Mutability::Not; if let ty::Ref(_, _, mutbl) = tam.kind; // only lint immutable refs, because borrowed `&mut T` cannot be moved out diff --git a/src/tools/clippy/clippy_lints/src/needless_pass_by_value.rs b/src/tools/clippy/clippy_lints/src/needless_pass_by_value.rs index 6954f0cc683f1..bf532c178d113 100644 --- a/src/tools/clippy/clippy_lints/src/needless_pass_by_value.rs +++ b/src/tools/clippy/clippy_lints/src/needless_pass_by_value.rs @@ -135,7 +135,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessPassByValue { } = { let mut ctx = MovedVariablesCtxt::default(); cx.tcx.infer_ctxt().enter(|infcx| { - euv::ExprUseVisitor::new(&mut ctx, &infcx, fn_def_id, cx.param_env, cx.tables()).consume_body(body); + euv::ExprUseVisitor::new(&mut ctx, &infcx, fn_def_id, cx.param_env, cx.typeck_results()).consume_body(body); }); ctx }; diff --git a/src/tools/clippy/clippy_lints/src/needless_update.rs b/src/tools/clippy/clippy_lints/src/needless_update.rs index 9b556dbb8540e..85d4fd3feab97 100644 --- a/src/tools/clippy/clippy_lints/src/needless_update.rs +++ b/src/tools/clippy/clippy_lints/src/needless_update.rs @@ -47,7 +47,7 @@ declare_lint_pass!(NeedlessUpdate => [NEEDLESS_UPDATE]); impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NeedlessUpdate { fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) { if let ExprKind::Struct(_, ref fields, Some(ref base)) = expr.kind { - let ty = cx.tables().expr_ty(expr); + let ty = cx.typeck_results().expr_ty(expr); if let ty::Adt(def, _) = ty.kind { if fields.len() == def.non_enum_variant().fields.len() { span_lint( diff --git a/src/tools/clippy/clippy_lints/src/neg_cmp_op_on_partial_ord.rs b/src/tools/clippy/clippy_lints/src/neg_cmp_op_on_partial_ord.rs index 0f56daa3659e8..bda082fe236fe 100644 --- a/src/tools/clippy/clippy_lints/src/neg_cmp_op_on_partial_ord.rs +++ b/src/tools/clippy/clippy_lints/src/neg_cmp_op_on_partial_ord.rs @@ -56,7 +56,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NoNegCompOpForPartialOrd { then { - let ty = cx.tables().expr_ty(left); + let ty = cx.typeck_results().expr_ty(left); let implements_ord = { if let Some(id) = utils::get_trait_def_id(cx, &paths::ORD) { diff --git a/src/tools/clippy/clippy_lints/src/neg_multiply.rs b/src/tools/clippy/clippy_lints/src/neg_multiply.rs index a9ce01b67b097..67f7951f1fef0 100644 --- a/src/tools/clippy/clippy_lints/src/neg_multiply.rs +++ b/src/tools/clippy/clippy_lints/src/neg_multiply.rs @@ -31,10 +31,12 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NegMultiply { if let ExprKind::Binary(ref op, ref left, ref right) = e.kind { if BinOpKind::Mul == op.node { match (&left.kind, &right.kind) { - (&ExprKind::Unary(..), &ExprKind::Unary(..)) => {}, - (&ExprKind::Unary(UnOp::UnNeg, ref lit), _) => check_mul(cx, e.span, lit, right), + (&ExprKind::Unary(..), &ExprKind::Unary(..)) => {} + (&ExprKind::Unary(UnOp::UnNeg, ref lit), _) => { + check_mul(cx, e.span, lit, right) + } (_, &ExprKind::Unary(UnOp::UnNeg, ref lit)) => check_mul(cx, e.span, lit, left), - _ => {}, + _ => {} } } } @@ -44,8 +46,8 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NegMultiply { fn check_mul(cx: &LateContext<'_, '_>, span: Span, lit: &Expr<'_>, exp: &Expr<'_>) { if_chain! { if let ExprKind::Lit(ref l) = lit.kind; - if let Constant::Int(1) = consts::lit_to_constant(&l.node, cx.tables().expr_ty_opt(lit)); - if cx.tables().expr_ty(exp).is_integral(); + if let Constant::Int(1) = consts::lit_to_constant(&l.node, cx.typeck_results().expr_ty_opt(lit)); + if cx.typeck_results().expr_ty(exp).is_integral(); then { span_lint(cx, NEG_MULTIPLY, span, "Negation by multiplying with `-1`"); } diff --git a/src/tools/clippy/clippy_lints/src/no_effect.rs b/src/tools/clippy/clippy_lints/src/no_effect.rs index 5fdc656580f29..882a064df3217 100644 --- a/src/tools/clippy/clippy_lints/src/no_effect.rs +++ b/src/tools/clippy/clippy_lints/src/no_effect.rs @@ -48,7 +48,7 @@ fn has_no_effect(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> bool { } match expr.kind { ExprKind::Lit(..) | ExprKind::Closure(..) => true, - ExprKind::Path(..) => !has_drop(cx, cx.tables().expr_ty(expr)), + ExprKind::Path(..) => !has_drop(cx, cx.typeck_results().expr_ty(expr)), ExprKind::Index(ref a, ref b) | ExprKind::Binary(_, ref a, ref b) => { has_no_effect(cx, a) && has_no_effect(cx, b) }, @@ -61,7 +61,7 @@ fn has_no_effect(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> bool { | ExprKind::AddrOf(_, _, ref inner) | ExprKind::Box(ref inner) => has_no_effect(cx, inner), ExprKind::Struct(_, ref fields, ref base) => { - !has_drop(cx, cx.tables().expr_ty(expr)) + !has_drop(cx, cx.typeck_results().expr_ty(expr)) && fields.iter().all(|field| has_no_effect(cx, &field.expr)) && base.as_ref().map_or(true, |base| has_no_effect(cx, base)) }, @@ -70,7 +70,7 @@ fn has_no_effect(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> bool { let res = qpath_res(cx, qpath, callee.hir_id); match res { Res::Def(DefKind::Struct | DefKind::Variant | DefKind::Ctor(..), ..) => { - !has_drop(cx, cx.tables().expr_ty(expr)) && args.iter().all(|arg| has_no_effect(cx, arg)) + !has_drop(cx, cx.typeck_results().expr_ty(expr)) && args.iter().all(|arg| has_no_effect(cx, arg)) }, _ => false, } @@ -137,7 +137,7 @@ fn reduce_expression<'a>(cx: &LateContext<'_, '_>, expr: &'a Expr<'a>) -> Option | ExprKind::AddrOf(_, _, ref inner) | ExprKind::Box(ref inner) => reduce_expression(cx, inner).or_else(|| Some(vec![inner])), ExprKind::Struct(_, ref fields, ref base) => { - if has_drop(cx, cx.tables().expr_ty(expr)) { + if has_drop(cx, cx.typeck_results().expr_ty(expr)) { None } else { Some(fields.iter().map(|f| &f.expr).chain(base).map(Deref::deref).collect()) @@ -148,7 +148,7 @@ fn reduce_expression<'a>(cx: &LateContext<'_, '_>, expr: &'a Expr<'a>) -> Option let res = qpath_res(cx, qpath, callee.hir_id); match res { Res::Def(DefKind::Struct | DefKind::Variant | DefKind::Ctor(..), ..) - if !has_drop(cx, cx.tables().expr_ty(expr)) => + if !has_drop(cx, cx.typeck_results().expr_ty(expr)) => { Some(args.iter().collect()) }, diff --git a/src/tools/clippy/clippy_lints/src/non_copy_const.rs b/src/tools/clippy/clippy_lints/src/non_copy_const.rs index 21d7a7439f25c..07c74a656b97e 100644 --- a/src/tools/clippy/clippy_lints/src/non_copy_const.rs +++ b/src/tools/clippy/clippy_lints/src/non_copy_const.rs @@ -237,13 +237,13 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonCopyConst { } let ty = if needs_check_adjustment { - let adjustments = cx.tables().expr_adjustments(dereferenced_expr); + let adjustments = cx.typeck_results().expr_adjustments(dereferenced_expr); if let Some(i) = adjustments.iter().position(|adj| match adj.kind { Adjust::Borrow(_) | Adjust::Deref(_) => true, _ => false, }) { if i == 0 { - cx.tables().expr_ty(dereferenced_expr) + cx.typeck_results().expr_ty(dereferenced_expr) } else { adjustments[i - 1].target } @@ -252,7 +252,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonCopyConst { return; } } else { - cx.tables().expr_ty(dereferenced_expr) + cx.typeck_results().expr_ty(dereferenced_expr) }; verify_ty_bound(cx, ty, Source::Expr { expr: expr.span }); diff --git a/src/tools/clippy/clippy_lints/src/open_options.rs b/src/tools/clippy/clippy_lints/src/open_options.rs index 2467a14cea12f..461db7e05ac34 100644 --- a/src/tools/clippy/clippy_lints/src/open_options.rs +++ b/src/tools/clippy/clippy_lints/src/open_options.rs @@ -30,7 +30,7 @@ declare_lint_pass!(OpenOptions => [NONSENSICAL_OPEN_OPTIONS]); impl<'a, 'tcx> LateLintPass<'a, 'tcx> for OpenOptions { fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, e: &'tcx Expr<'_>) { if let ExprKind::MethodCall(ref path, _, ref arguments, _) = e.kind { - let obj_ty = walk_ptrs_ty(cx.tables().expr_ty(&arguments[0])); + let obj_ty = walk_ptrs_ty(cx.typeck_results().expr_ty(&arguments[0])); if path.ident.name == sym!(open) && match_type(cx, obj_ty, &paths::OPEN_OPTIONS) { let mut options = Vec::new(); get_open_options(cx, &arguments[0], &mut options); @@ -56,49 +56,45 @@ enum OpenOption { Append, } -fn get_open_options(cx: &LateContext<'_, '_>, argument: &Expr<'_>, options: &mut Vec<(OpenOption, Argument)>) { +fn get_open_options( + cx: &LateContext<'_, '_>, + argument: &Expr<'_>, + options: &mut Vec<(OpenOption, Argument)>, +) { if let ExprKind::MethodCall(ref path, _, ref arguments, _) = argument.kind { - let obj_ty = walk_ptrs_ty(cx.tables().expr_ty(&arguments[0])); + let obj_ty = walk_ptrs_ty(cx.typeck_results().expr_ty(&arguments[0])); // Only proceed if this is a call on some object of type std::fs::OpenOptions if match_type(cx, obj_ty, &paths::OPEN_OPTIONS) && arguments.len() >= 2 { let argument_option = match arguments[1].kind { ExprKind::Lit(ref span) => { - if let Spanned { - node: LitKind::Bool(lit), - .. - } = *span - { - if lit { - Argument::True - } else { - Argument::False - } + if let Spanned { node: LitKind::Bool(lit), .. } = *span { + if lit { Argument::True } else { Argument::False } } else { return; // The function is called with a literal - // which is not a boolean literal. This is theoretically - // possible, but not very likely. + // which is not a boolean literal. This is theoretically + // possible, but not very likely. } - }, + } _ => Argument::Unknown, }; match &*path.ident.as_str() { "create" => { options.push((OpenOption::Create, argument_option)); - }, + } "append" => { options.push((OpenOption::Append, argument_option)); - }, + } "truncate" => { options.push((OpenOption::Truncate, argument_option)); - }, + } "read" => { options.push((OpenOption::Read, argument_option)); - }, + } "write" => { options.push((OpenOption::Write, argument_option)); - }, + } _ => (), } @@ -108,7 +104,8 @@ fn get_open_options(cx: &LateContext<'_, '_>, argument: &Expr<'_>, options: &mut } fn check_open_options(cx: &LateContext<'_, '_>, options: &[(OpenOption, Argument)], span: Span) { - let (mut create, mut append, mut truncate, mut read, mut write) = (false, false, false, false, false); + let (mut create, mut append, mut truncate, mut read, mut write) = + (false, false, false, false, false); let (mut create_arg, mut append_arg, mut truncate_arg, mut read_arg, mut write_arg) = (false, false, false, false, false); // This code is almost duplicated (oh, the irony), but I haven't found a way to @@ -128,7 +125,7 @@ fn check_open_options(cx: &LateContext<'_, '_>, options: &[(OpenOption, Argument create = true } create_arg = create_arg || (arg == Argument::True); - }, + } (OpenOption::Append, arg) => { if append { span_lint( @@ -141,7 +138,7 @@ fn check_open_options(cx: &LateContext<'_, '_>, options: &[(OpenOption, Argument append = true } append_arg = append_arg || (arg == Argument::True); - }, + } (OpenOption::Truncate, arg) => { if truncate { span_lint( @@ -154,7 +151,7 @@ fn check_open_options(cx: &LateContext<'_, '_>, options: &[(OpenOption, Argument truncate = true } truncate_arg = truncate_arg || (arg == Argument::True); - }, + } (OpenOption::Read, arg) => { if read { span_lint( @@ -167,7 +164,7 @@ fn check_open_options(cx: &LateContext<'_, '_>, options: &[(OpenOption, Argument read = true } read_arg = read_arg || (arg == Argument::True); - }, + } (OpenOption::Write, arg) => { if write { span_lint( @@ -180,24 +177,14 @@ fn check_open_options(cx: &LateContext<'_, '_>, options: &[(OpenOption, Argument write = true } write_arg = write_arg || (arg == Argument::True); - }, + } } } if read && truncate && read_arg && truncate_arg && !(write && write_arg) { - span_lint( - cx, - NONSENSICAL_OPEN_OPTIONS, - span, - "file opened with `truncate` and `read`", - ); + span_lint(cx, NONSENSICAL_OPEN_OPTIONS, span, "file opened with `truncate` and `read`"); } if append && truncate && append_arg && truncate_arg { - span_lint( - cx, - NONSENSICAL_OPEN_OPTIONS, - span, - "file opened with `append` and `truncate`", - ); + span_lint(cx, NONSENSICAL_OPEN_OPTIONS, span, "file opened with `append` and `truncate`"); } } diff --git a/src/tools/clippy/clippy_lints/src/overflow_check_conditional.rs b/src/tools/clippy/clippy_lints/src/overflow_check_conditional.rs index 5984b09120d0e..e732af1b165c1 100644 --- a/src/tools/clippy/clippy_lints/src/overflow_check_conditional.rs +++ b/src/tools/clippy/clippy_lints/src/overflow_check_conditional.rs @@ -36,8 +36,8 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for OverflowCheckConditional { if let ExprKind::Path(QPath::Resolved(_, ref path2)) = ident2.kind; if let ExprKind::Path(QPath::Resolved(_, ref path3)) = second.kind; if eq(&path1.segments[0], &path3.segments[0]) || eq(&path2.segments[0], &path3.segments[0]); - if cx.tables().expr_ty(ident1).is_integral(); - if cx.tables().expr_ty(ident2).is_integral(); + if cx.typeck_results().expr_ty(ident1).is_integral(); + if cx.typeck_results().expr_ty(ident2).is_integral(); then { if let BinOpKind::Lt = op.node { if let BinOpKind::Add = op2.node { @@ -61,8 +61,8 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for OverflowCheckConditional { if let ExprKind::Path(QPath::Resolved(_, ref path2)) = ident2.kind; if let ExprKind::Path(QPath::Resolved(_, ref path3)) = first.kind; if eq(&path1.segments[0], &path3.segments[0]) || eq(&path2.segments[0], &path3.segments[0]); - if cx.tables().expr_ty(ident1).is_integral(); - if cx.tables().expr_ty(ident2).is_integral(); + if cx.typeck_results().expr_ty(ident1).is_integral(); + if cx.typeck_results().expr_ty(ident2).is_integral(); then { if let BinOpKind::Gt = op.node { if let BinOpKind::Add = op2.node { diff --git a/src/tools/clippy/clippy_lints/src/path_buf_push_overwrite.rs b/src/tools/clippy/clippy_lints/src/path_buf_push_overwrite.rs index f26a5258782a7..685929500c1de 100644 --- a/src/tools/clippy/clippy_lints/src/path_buf_push_overwrite.rs +++ b/src/tools/clippy/clippy_lints/src/path_buf_push_overwrite.rs @@ -46,7 +46,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PathBufPushOverwrite { if let ExprKind::MethodCall(ref path, _, ref args, _) = expr.kind; if path.ident.name == sym!(push); if args.len() == 2; - if match_type(cx, walk_ptrs_ty(cx.tables().expr_ty(&args[0])), &paths::PATH_BUF); + if match_type(cx, walk_ptrs_ty(cx.typeck_results().expr_ty(&args[0])), &paths::PATH_BUF); if let Some(get_index_arg) = args.get(1); if let ExprKind::Lit(ref lit) = get_index_arg.kind; if let LitKind::Str(ref path_lit, _) = lit.node; diff --git a/src/tools/clippy/clippy_lints/src/ptr_offset_with_cast.rs b/src/tools/clippy/clippy_lints/src/ptr_offset_with_cast.rs index b35a7e64bff27..f1aee3e060acb 100644 --- a/src/tools/clippy/clippy_lints/src/ptr_offset_with_cast.rs +++ b/src/tools/clippy/clippy_lints/src/ptr_offset_with_cast.rs @@ -75,7 +75,10 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PtrOffsetWithCast { } // If the given expression is a cast from a usize, return the lhs of the cast -fn expr_as_cast_from_usize<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'tcx>) -> Option<&'tcx Expr<'tcx>> { +fn expr_as_cast_from_usize<'a, 'tcx>( + cx: &LateContext<'a, 'tcx>, + expr: &'tcx Expr<'tcx>, +) -> Option<&'tcx Expr<'tcx>> { if let ExprKind::Cast(ref cast_lhs_expr, _) = expr.kind { if is_expr_ty_usize(cx, &cast_lhs_expr) { return Some(cast_lhs_expr); @@ -105,12 +108,12 @@ fn expr_as_ptr_offset_call<'a, 'tcx>( // Is the type of the expression a usize? fn is_expr_ty_usize<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &Expr<'_>) -> bool { - cx.tables().expr_ty(expr) == cx.tcx.types.usize + cx.typeck_results().expr_ty(expr) == cx.tcx.types.usize } // Is the type of the expression a raw pointer? fn is_expr_ty_raw_ptr<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &Expr<'_>) -> bool { - cx.tables().expr_ty(expr).is_unsafe_ptr() + cx.typeck_results().expr_ty(expr).is_unsafe_ptr() } fn build_suggestion<'a, 'tcx>( diff --git a/src/tools/clippy/clippy_lints/src/question_mark.rs b/src/tools/clippy/clippy_lints/src/question_mark.rs index 4a6395da01c99..7322d0a5e1cbc 100644 --- a/src/tools/clippy/clippy_lints/src/question_mark.rs +++ b/src/tools/clippy/clippy_lints/src/question_mark.rs @@ -7,8 +7,8 @@ use rustc_session::{declare_lint_pass, declare_tool_lint}; use crate::utils::sugg::Sugg; use crate::utils::{ - higher, is_type_diagnostic_item, match_def_path, match_qpath, paths, snippet_with_applicability, - span_lint_and_sugg, SpanlessEq, + higher, is_type_diagnostic_item, match_def_path, match_qpath, paths, + snippet_with_applicability, span_lint_and_sugg, SpanlessEq, }; declare_clippy_lint! { @@ -135,13 +135,13 @@ impl QuestionMark { } fn moves_by_default(cx: &LateContext<'_, '_>, expression: &Expr<'_>) -> bool { - let expr_ty = cx.tables().expr_ty(expression); + let expr_ty = cx.typeck_results().expr_ty(expression); !expr_ty.is_copy_modulo_regions(cx.tcx.at(expression.span), cx.param_env) } fn is_option(cx: &LateContext<'_, '_>, expression: &Expr<'_>) -> bool { - let expr_ty = cx.tables().expr_ty(expression); + let expr_ty = cx.typeck_results().expr_ty(expression); is_type_diagnostic_item(cx, expr_ty, sym!(option_type)) } @@ -154,17 +154,17 @@ impl QuestionMark { } false - }, + } ExprKind::Ret(Some(ref expr)) => Self::expression_returns_none(cx, expr), ExprKind::Path(ref qp) => { if let Res::Def(DefKind::Ctor(def::CtorOf::Variant, def::CtorKind::Const), def_id) = - cx.tables().qpath_res(qp, expression.hir_id) + cx.typeck_results().qpath_res(qp, expression.hir_id) { return match_def_path(cx, def_id, &paths::OPTION_NONE); } false - }, + } _ => false, } } diff --git a/src/tools/clippy/clippy_lints/src/ranges.rs b/src/tools/clippy/clippy_lints/src/ranges.rs index 43ef236a92420..781cc567bab01 100644 --- a/src/tools/clippy/clippy_lints/src/ranges.rs +++ b/src/tools/clippy/clippy_lints/src/ranges.rs @@ -10,7 +10,9 @@ use rustc_span::source_map::Spanned; use std::cmp::Ordering; use crate::utils::sugg::Sugg; -use crate::utils::{get_parent_expr, is_integer_const, snippet, snippet_opt, span_lint, span_lint_and_then}; +use crate::utils::{ + get_parent_expr, is_integer_const, snippet, snippet_opt, span_lint, span_lint_and_then, +}; use crate::utils::{higher, SpanlessEq}; declare_clippy_lint! { @@ -242,13 +244,7 @@ fn check_inclusive_range_minus_one(cx: &LateContext<'_, '_>, expr: &Expr<'_>) { fn check_reversed_empty_range(cx: &LateContext<'_, '_>, expr: &Expr<'_>) { fn inside_indexing_expr(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> bool { - matches!( - get_parent_expr(cx, expr), - Some(Expr { - kind: ExprKind::Index(..), - .. - }) - ) + matches!(get_parent_expr(cx, expr), Some(Expr { kind: ExprKind::Index(..), .. })) } fn is_for_loop_arg(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> bool { @@ -272,10 +268,10 @@ fn check_reversed_empty_range(cx: &LateContext<'_, '_>, expr: &Expr<'_>) { if_chain! { if let Some(higher::Range { start: Some(start), end: Some(end), limits }) = higher::range(cx, expr); - let ty = cx.tables().expr_ty(start); + let ty = cx.typeck_results().expr_ty(start); if let ty::Int(_) | ty::Uint(_) = ty.kind; - if let Some((start_idx, _)) = constant(cx, cx.tables(), start); - if let Some((end_idx, _)) = constant(cx, cx.tables(), end); + if let Some((start_idx, _)) = constant(cx, cx.typeck_results(), start); + if let Some((end_idx, _)) = constant(cx, cx.typeck_results(), end); if let Some(ordering) = Constant::partial_cmp(cx.tcx, ty, &start_idx, &end_idx); if is_empty_range(limits, ordering); then { @@ -322,13 +318,7 @@ fn check_reversed_empty_range(cx: &LateContext<'_, '_>, expr: &Expr<'_>) { fn y_plus_one<'t>(cx: &LateContext<'_, '_>, expr: &'t Expr<'_>) -> Option<&'t Expr<'t>> { match expr.kind { - ExprKind::Binary( - Spanned { - node: BinOpKind::Add, .. - }, - ref lhs, - ref rhs, - ) => { + ExprKind::Binary(Spanned { node: BinOpKind::Add, .. }, ref lhs, ref rhs) => { if is_integer_const(cx, lhs, 1) { Some(rhs) } else if is_integer_const(cx, rhs, 1) { @@ -336,20 +326,18 @@ fn y_plus_one<'t>(cx: &LateContext<'_, '_>, expr: &'t Expr<'_>) -> Option<&'t Ex } else { None } - }, + } _ => None, } } fn y_minus_one<'t>(cx: &LateContext<'_, '_>, expr: &'t Expr<'_>) -> Option<&'t Expr<'t>> { match expr.kind { - ExprKind::Binary( - Spanned { - node: BinOpKind::Sub, .. - }, - ref lhs, - ref rhs, - ) if is_integer_const(cx, rhs, 1) => Some(lhs), + ExprKind::Binary(Spanned { node: BinOpKind::Sub, .. }, ref lhs, ref rhs) + if is_integer_const(cx, rhs, 1) => + { + Some(lhs) + } _ => None, } } diff --git a/src/tools/clippy/clippy_lints/src/regex.rs b/src/tools/clippy/clippy_lints/src/regex.rs index 9c54c3cbac02b..4bba02929eb44 100644 --- a/src/tools/clippy/clippy_lints/src/regex.rs +++ b/src/tools/clippy/clippy_lints/src/regex.rs @@ -82,7 +82,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Regex { if_chain! { if self.last.is_none(); if let Some(ref expr) = block.expr; - if match_type(cx, cx.tables().expr_ty(expr), &paths::REGEX); + if match_type(cx, cx.typeck_results().expr_ty(expr), &paths::REGEX); if let Some(span) = is_expn_of(expr.span, "regex"); then { if !self.spans.contains(&span) { @@ -111,7 +111,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Regex { if let ExprKind::Call(ref fun, ref args) = expr.kind; if let ExprKind::Path(ref qpath) = fun.kind; if args.len() == 1; - if let Some(def_id) = cx.tables().qpath_res(qpath, fun.hir_id).opt_def_id(); + if let Some(def_id) = cx.typeck_results().qpath_res(qpath, fun.hir_id).opt_def_id(); then { if match_def_path(cx, def_id, &paths::REGEX_NEW) || match_def_path(cx, def_id, &paths::REGEX_BUILDER_NEW) { @@ -140,7 +140,7 @@ fn str_span(base: Span, c: regex_syntax::ast::Span, offset: u16) -> Span { } fn const_str<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, e: &'tcx Expr<'_>) -> Option { - constant(cx, cx.tables(), e).and_then(|(c, _)| match c { + constant(cx, cx.typeck_results(), e).and_then(|(c, _)| match c { Constant::Str(s) => Some(s), _ => None, }) diff --git a/src/tools/clippy/clippy_lints/src/shadow.rs b/src/tools/clippy/clippy_lints/src/shadow.rs index 4780249bcb8e3..d316faaa3fa57 100644 --- a/src/tools/clippy/clippy_lints/src/shadow.rs +++ b/src/tools/clippy/clippy_lints/src/shadow.rs @@ -164,7 +164,7 @@ fn check_local<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, local: &'tcx Local<'_>, bin } fn is_binding(cx: &LateContext<'_, '_>, pat_id: HirId) -> bool { - let var_ty = cx.tables().node_type_opt(pat_id); + let var_ty = cx.typeck_results().node_type_opt(pat_id); if let Some(var_ty) = var_ty { match var_ty.kind { ty::Adt(..) => false, diff --git a/src/tools/clippy/clippy_lints/src/strings.rs b/src/tools/clippy/clippy_lints/src/strings.rs index ef66850358e57..a31346e6e8726 100644 --- a/src/tools/clippy/clippy_lints/src/strings.rs +++ b/src/tools/clippy/clippy_lints/src/strings.rs @@ -134,7 +134,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for StringAdd { } fn is_string(cx: &LateContext<'_, '_>, e: &Expr<'_>) -> bool { - is_type_diagnostic_item(cx, walk_ptrs_ty(cx.tables().expr_ty(e)), sym!(string_type)) + is_type_diagnostic_item(cx, walk_ptrs_ty(cx.typeck_results().expr_ty(e)), sym!(string_type)) } fn is_add(cx: &LateContext<'_, '_>, src: &Expr<'_>, target: &Expr<'_>) -> bool { diff --git a/src/tools/clippy/clippy_lints/src/swap.rs b/src/tools/clippy/clippy_lints/src/swap.rs index 7fdc872c01f54..6054eb597a2d0 100644 --- a/src/tools/clippy/clippy_lints/src/swap.rs +++ b/src/tools/clippy/clippy_lints/src/swap.rs @@ -194,7 +194,7 @@ fn check_for_slice<'a>(cx: &LateContext<'_, '_>, lhs1: &'a Expr<'_>, lhs2: &'a E if let ExprKind::Index(ref lhs1, ref idx1) = lhs1.kind { if let ExprKind::Index(ref lhs2, ref idx2) = lhs2.kind { if SpanlessEq::new(cx).ignore_fn().eq_expr(lhs1, lhs2) { - let ty = walk_ptrs_ty(cx.tables().expr_ty(lhs1)); + let ty = walk_ptrs_ty(cx.typeck_results().expr_ty(lhs1)); if matches!(ty.kind, ty::Slice(_)) || matches!(ty.kind, ty::Array(_, _)) diff --git a/src/tools/clippy/clippy_lints/src/temporary_assignment.rs b/src/tools/clippy/clippy_lints/src/temporary_assignment.rs index f2bbf19bea92f..e2e0489165637 100644 --- a/src/tools/clippy/clippy_lints/src/temporary_assignment.rs +++ b/src/tools/clippy/clippy_lints/src/temporary_assignment.rs @@ -26,7 +26,7 @@ fn is_temporary(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> bool { match &expr.kind { ExprKind::Struct(..) | ExprKind::Tup(..) => true, ExprKind::Path(qpath) => { - if let Res::Def(DefKind::Const, ..) = cx.tables().qpath_res(qpath, expr.hir_id) { + if let Res::Def(DefKind::Const, ..) = cx.typeck_results().qpath_res(qpath, expr.hir_id) { true } else { false diff --git a/src/tools/clippy/clippy_lints/src/to_digit_is_some.rs b/src/tools/clippy/clippy_lints/src/to_digit_is_some.rs index 1efba3580fef0..321968e134c90 100644 --- a/src/tools/clippy/clippy_lints/src/to_digit_is_some.rs +++ b/src/tools/clippy/clippy_lints/src/to_digit_is_some.rs @@ -43,7 +43,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ToDigitIsSome { if_chain! { if let [char_arg, radix_arg] = &**to_digit_args; if to_digits_path.ident.name.as_str() == "to_digit"; - let char_arg_ty = cx.tables().expr_ty_adjusted(char_arg); + let char_arg_ty = cx.typeck_results().expr_ty_adjusted(char_arg); if char_arg_ty.kind == ty::Char; then { Some((true, char_arg, radix_arg)) @@ -56,7 +56,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ToDigitIsSome { if_chain! { if let [char_arg, radix_arg] = &**to_digit_args; if let hir::ExprKind::Path(to_digits_path) = &to_digits_call.kind; - if let to_digits_call_res = cx.tables().qpath_res(to_digits_path, to_digits_call.hir_id); + if let to_digits_call_res = cx.typeck_results().qpath_res(to_digits_path, to_digits_call.hir_id); if let Some(to_digits_def_id) = to_digits_call_res.opt_def_id(); if match_def_path(cx, to_digits_def_id, &["core", "char", "methods", "", "to_digit"]); then { diff --git a/src/tools/clippy/clippy_lints/src/trait_bounds.rs b/src/tools/clippy/clippy_lints/src/trait_bounds.rs index 1b233b8302f93..743ced7204503 100644 --- a/src/tools/clippy/clippy_lints/src/trait_bounds.rs +++ b/src/tools/clippy/clippy_lints/src/trait_bounds.rs @@ -37,7 +37,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TraitBounds { return; } let hash = |ty| -> u64 { - let mut hasher = SpanlessHash::new(cx, cx.tables()); + let mut hasher = SpanlessHash::new(cx, cx.typeck_results()); hasher.hash_ty(ty); hasher.finish() }; diff --git a/src/tools/clippy/clippy_lints/src/transmute.rs b/src/tools/clippy/clippy_lints/src/transmute.rs index 9b1344949470a..aa7104d5377a2 100644 --- a/src/tools/clippy/clippy_lints/src/transmute.rs +++ b/src/tools/clippy/clippy_lints/src/transmute.rs @@ -1,6 +1,6 @@ use crate::utils::{ - is_normalizable, last_path_segment, match_def_path, paths, snippet, span_lint, span_lint_and_sugg, - span_lint_and_then, sugg, + is_normalizable, last_path_segment, match_def_path, paths, snippet, span_lint, + span_lint_and_sugg, span_lint_and_then, sugg, }; use if_chain::if_chain; use rustc_ast::ast; @@ -299,11 +299,11 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Transmute { if_chain! { if let ExprKind::Call(ref path_expr, ref args) = e.kind; if let ExprKind::Path(ref qpath) = path_expr.kind; - if let Some(def_id) = cx.tables().qpath_res(qpath, path_expr.hir_id).opt_def_id(); + if let Some(def_id) = cx.typeck_results().qpath_res(qpath, path_expr.hir_id).opt_def_id(); if match_def_path(cx, def_id, &paths::TRANSMUTE); then { - let from_ty = cx.tables().expr_ty(&args[0]); - let to_ty = cx.tables().expr_ty(e); + let from_ty = cx.typeck_results().expr_ty(&args[0]); + let to_ty = cx.typeck_results().expr_ty(e); match (&from_ty.kind, &to_ty.kind) { _ if from_ty == to_ty => span_lint( @@ -633,7 +633,11 @@ fn get_type_snippet(cx: &LateContext<'_, '_>, path: &QPath<'_>, to_ref_ty: Ty<'_ // check if the component types of the transmuted collection and the result have different ABI, // size or alignment -fn is_layout_incompatible<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, from: Ty<'tcx>, to: Ty<'tcx>) -> bool { +fn is_layout_incompatible<'a, 'tcx>( + cx: &LateContext<'a, 'tcx>, + from: Ty<'tcx>, + to: Ty<'tcx>, +) -> bool { let empty_param_env = ty::ParamEnv::empty(); // check if `from` and `to` are normalizable to avoid ICE (#4968) if !(is_normalizable(cx, empty_param_env, from) && is_normalizable(cx, empty_param_env, to)) { @@ -642,7 +646,9 @@ fn is_layout_incompatible<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, from: Ty<'tcx>, let from_ty_layout = cx.tcx.layout_of(empty_param_env.and(from)); let to_ty_layout = cx.tcx.layout_of(empty_param_env.and(to)); if let (Ok(from_layout), Ok(to_layout)) = (from_ty_layout, to_ty_layout) { - from_layout.size != to_layout.size || from_layout.align != to_layout.align || from_layout.abi != to_layout.abi + from_layout.size != to_layout.size + || from_layout.align != to_layout.align + || from_layout.abi != to_layout.abi } else { // no idea about layout, so don't lint false diff --git a/src/tools/clippy/clippy_lints/src/transmuting_null.rs b/src/tools/clippy/clippy_lints/src/transmuting_null.rs index 3351488a45c4d..69346f22c0554 100644 --- a/src/tools/clippy/clippy_lints/src/transmuting_null.rs +++ b/src/tools/clippy/clippy_lints/src/transmuting_null.rs @@ -44,7 +44,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TransmutingNull { then { // Catching transmute over constants that resolve to `null`. - let mut const_eval_context = constant_context(cx, cx.tables()); + let mut const_eval_context = constant_context(cx, cx.typeck_results()); if_chain! { if let ExprKind::Path(ref _qpath) = args[0].kind; let x = const_eval_context.expr(&args[0]); diff --git a/src/tools/clippy/clippy_lints/src/try_err.rs b/src/tools/clippy/clippy_lints/src/try_err.rs index e129dd84d15a6..42e9564a579e5 100644 --- a/src/tools/clippy/clippy_lints/src/try_err.rs +++ b/src/tools/clippy/clippy_lints/src/try_err.rs @@ -68,7 +68,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TryErr { if let Some(return_type) = find_err_return_type(cx, &expr.kind); then { - let err_type = cx.tables().expr_ty(err_arg); + let err_type = cx.typeck_results().expr_ty(err_arg); let origin_snippet = if err_arg.span.from_expansion() { snippet_with_macro_callsite(cx, err_arg.span, "_") } else { @@ -97,7 +97,10 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TryErr { // In order to determine whether to suggest `.into()` or not, we need to find the error type the // function returns. To do that, we look for the From::from call (see tree above), and capture // its output type. -fn find_err_return_type<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx ExprKind<'_>) -> Option> { +fn find_err_return_type<'a, 'tcx>( + cx: &LateContext<'a, 'tcx>, + expr: &'tcx ExprKind<'_>, +) -> Option> { if let ExprKind::Match(_, ref arms, MatchSource::TryDesugar) = expr { arms.iter().find_map(|ty| find_err_return_type_arm(cx, ty)) } else { @@ -106,7 +109,10 @@ fn find_err_return_type<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx ExprKi } // Check for From::from in one of the match arms. -fn find_err_return_type_arm<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, arm: &'tcx Arm<'_>) -> Option> { +fn find_err_return_type_arm<'a, 'tcx>( + cx: &LateContext<'a, 'tcx>, + arm: &'tcx Arm<'_>, +) -> Option> { if_chain! { if let ExprKind::Ret(Some(ref err_ret)) = arm.body.kind; if let ExprKind::Call(ref from_error_path, ref from_error_args) = err_ret.kind; @@ -114,7 +120,7 @@ fn find_err_return_type_arm<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, arm: &'tcx Arm if match_qpath(from_error_fn, &paths::TRY_FROM_ERROR); if let Some(from_error_arg) = from_error_args.get(0); then { - Some(cx.tables().expr_ty(from_error_arg)) + Some(cx.typeck_results().expr_ty(from_error_arg)) } else { None } diff --git a/src/tools/clippy/clippy_lints/src/types.rs b/src/tools/clippy/clippy_lints/src/types.rs index ecfb6ee2a7de9..323e6e0ba1ba1 100644 --- a/src/tools/clippy/clippy_lints/src/types.rs +++ b/src/tools/clippy/clippy_lints/src/types.rs @@ -10,14 +10,14 @@ use rustc_errors::{Applicability, DiagnosticBuilder}; use rustc_hir as hir; use rustc_hir::intravisit::{walk_body, walk_expr, walk_ty, FnKind, NestedVisitorMap, Visitor}; use rustc_hir::{ - BinOpKind, Block, Body, Expr, ExprKind, FnDecl, FnRetTy, FnSig, GenericArg, GenericParamKind, HirId, ImplItem, - ImplItemKind, Item, ItemKind, Lifetime, Local, MatchSource, MutTy, Mutability, QPath, Stmt, StmtKind, TraitFn, - TraitItem, TraitItemKind, TyKind, UnOp, + BinOpKind, Block, Body, Expr, ExprKind, FnDecl, FnRetTy, FnSig, GenericArg, GenericParamKind, + HirId, ImplItem, ImplItemKind, Item, ItemKind, Lifetime, Local, MatchSource, MutTy, Mutability, + QPath, Stmt, StmtKind, TraitFn, TraitItem, TraitItemKind, TyKind, UnOp, }; use rustc_lint::{LateContext, LateLintPass, LintContext}; use rustc_middle::hir::map::Map; use rustc_middle::lint::in_external_macro; -use rustc_middle::ty::{self, InferTy, Ty, TyCtxt, TyS, TypeckTables}; +use rustc_middle::ty::{self, InferTy, Ty, TyCtxt, TyS, TypeckResults}; use rustc_session::{declare_lint_pass, declare_tool_lint, impl_lint_pass}; use rustc_span::hygiene::{ExpnKind, MacroKind}; use rustc_span::source_map::Span; @@ -29,10 +29,12 @@ use rustc_typeck::hir_ty_to_ty; use crate::consts::{constant, Constant}; use crate::utils::paths; use crate::utils::{ - clip, comparisons, differing_macro_contexts, higher, in_constant, indent_of, int_bits, is_type_diagnostic_item, - last_path_segment, match_def_path, match_path, method_chain_args, multispan_sugg, numeric_literal::NumericLiteral, - qpath_res, sext, snippet, snippet_block_with_applicability, snippet_opt, snippet_with_applicability, - snippet_with_macro_callsite, span_lint, span_lint_and_help, span_lint_and_sugg, span_lint_and_then, unsext, + clip, comparisons, differing_macro_contexts, higher, in_constant, indent_of, int_bits, + is_type_diagnostic_item, last_path_segment, match_def_path, match_path, method_chain_args, + multispan_sugg, numeric_literal::NumericLiteral, qpath_res, sext, snippet, + snippet_block_with_applicability, snippet_opt, snippet_with_applicability, + snippet_with_macro_callsite, span_lint, span_lint_and_help, span_lint_and_sugg, + span_lint_and_then, unsext, }; declare_clippy_lint! { @@ -244,7 +246,9 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Types { fn check_trait_item(&mut self, cx: &LateContext<'_, '_>, item: &TraitItem<'_>) { match item.kind { - TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => self.check_ty(cx, ty, false), + TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => { + self.check_ty(cx, ty, false) + } TraitItemKind::Fn(ref sig, _) => self.check_fn_decl(cx, &sig.decl), _ => (), } @@ -258,7 +262,11 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Types { } /// Checks if `qpath` has last segment with type parameter matching `path` -fn match_type_parameter(cx: &LateContext<'_, '_>, qpath: &QPath<'_>, path: &[&str]) -> Option { +fn match_type_parameter( + cx: &LateContext<'_, '_>, + qpath: &QPath<'_>, + path: &[&str], +) -> Option { let last = last_path_segment(qpath); if_chain! { if let Some(ref params) = last.args; @@ -458,7 +466,7 @@ impl Types { }) { self.check_ty(cx, ty, is_local); } - }, + } QPath::Resolved(None, ref p) => { for ty in p.segments.iter().flat_map(|seg| { seg.args @@ -471,7 +479,7 @@ impl Types { }) { self.check_ty(cx, ty, is_local); } - }, + } QPath::TypeRelative(ref ty, ref seg) => { self.check_ty(cx, ty, is_local); if let Some(ref params) = seg.args { @@ -482,20 +490,22 @@ impl Types { self.check_ty(cx, ty, is_local); } } - }, + } } - }, - TyKind::Rptr(ref lt, ref mut_ty) => self.check_ty_rptr(cx, hir_ty, is_local, lt, mut_ty), + } + TyKind::Rptr(ref lt, ref mut_ty) => { + self.check_ty_rptr(cx, hir_ty, is_local, lt, mut_ty) + } // recurse - TyKind::Slice(ref ty) | TyKind::Array(ref ty, _) | TyKind::Ptr(MutTy { ref ty, .. }) => { - self.check_ty(cx, ty, is_local) - }, + TyKind::Slice(ref ty) + | TyKind::Array(ref ty, _) + | TyKind::Ptr(MutTy { ref ty, .. }) => self.check_ty(cx, ty, is_local), TyKind::Tup(tys) => { for ty in tys { self.check_ty(cx, ty, is_local); } - }, - _ => {}, + } + _ => {} } } @@ -557,7 +567,7 @@ impl Types { } }; self.check_ty(cx, &mut_ty.ty, is_local); - }, + } _ => self.check_ty(cx, &mut_ty.ty, is_local), } } @@ -603,7 +613,7 @@ declare_lint_pass!(LetUnitValue => [LET_UNIT_VALUE]); impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LetUnitValue { fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx Stmt<'_>) { if let StmtKind::Local(ref local) = stmt.kind { - if is_unit(cx.tables().pat_ty(&local.pat)) { + if is_unit(cx.typeck_results().pat_ty(&local.pat)) { if in_external_macro(cx.sess(), stmt.span) || local.pat.span.from_expansion() { return; } @@ -688,7 +698,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnitCmp { if let ExpnKind::Macro(MacroKind::Bang, symbol) = callee.kind { if let ExprKind::Binary(ref cmp, ref left, _) = expr.kind { let op = cmp.node; - if op.is_comparison() && is_unit(cx.tables().expr_ty(left)) { + if op.is_comparison() && is_unit(cx.typeck_results().expr_ty(left)) { let result = match &*symbol.as_str() { "assert_eq" | "debug_assert_eq" => "succeed", "assert_ne" | "debug_assert_ne" => "fail", @@ -712,7 +722,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnitCmp { } if let ExprKind::Binary(ref cmp, ref left, _) = expr.kind { let op = cmp.node; - if op.is_comparison() && is_unit(cx.tables().expr_ty(left)) { + if op.is_comparison() && is_unit(cx.typeck_results().expr_ty(left)) { let result = match op { BinOpKind::Eq | BinOpKind::Le | BinOpKind::Ge => "true", _ => "false", @@ -782,7 +792,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnitArg { let args_to_recover = args .iter() .filter(|arg| { - if is_unit(cx.tables().expr_ty(arg)) && !is_unit_literal(arg) { + if is_unit(cx.typeck_results().expr_ty(arg)) && !is_unit_literal(arg) { if let ExprKind::Match(.., MatchSource::TryDesugar) = &arg.kind { false } else { @@ -796,7 +806,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnitArg { if !args_to_recover.is_empty() { lint_unit_args(cx, expr, &args_to_recover); } - }, + } _ => (), } } @@ -804,11 +814,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnitArg { fn lint_unit_args(cx: &LateContext<'_, '_>, expr: &Expr<'_>, args_to_recover: &[&Expr<'_>]) { let mut applicability = Applicability::MachineApplicable; - let (singular, plural) = if args_to_recover.len() > 1 { - ("", "s") - } else { - ("a ", "") - }; + let (singular, plural) = if args_to_recover.len() > 1 { ("", "s") } else { ("a ", "") }; span_lint_and_then( cx, UNIT_ARG, @@ -850,15 +856,17 @@ fn lint_unit_args(cx: &LateContext<'_, '_>, expr: &Expr<'_>, args_to_recover: &[ .filter(|arg| !is_empty_block(arg)) .enumerate() .map(|(i, arg)| { - let indent = if i == 0 { - 0 - } else { - indent_of(cx, expr.span).unwrap_or(0) - }; + let indent = if i == 0 { 0 } else { indent_of(cx, expr.span).unwrap_or(0) }; format!( "{}{};", " ".repeat(indent), - snippet_block_with_applicability(cx, arg.span, "..", Some(expr.span), &mut applicability) + snippet_block_with_applicability( + cx, + arg.span, + "..", + Some(expr.span), + &mut applicability + ) ) }) .collect::>(); @@ -875,10 +883,7 @@ fn lint_unit_args(cx: &LateContext<'_, '_>, expr: &Expr<'_>, args_to_recover: &[ } db.multipart_suggestion( &format!("{}use {}unit literal{} instead", and, singular, plural), - args_to_recover - .iter() - .map(|arg| (arg.span, "()".to_string())) - .collect::>(), + args_to_recover.iter().map(|arg| (arg.span, "()".to_string())).collect::>(), applicability, ); }, @@ -886,15 +891,7 @@ fn lint_unit_args(cx: &LateContext<'_, '_>, expr: &Expr<'_>, args_to_recover: &[ } fn is_empty_block(expr: &Expr<'_>) -> bool { - matches!( - expr.kind, - ExprKind::Block( - Block { - stmts: &[], expr: None, .. - }, - _, - ) - ) + matches!(expr.kind, ExprKind::Block(Block { stmts: &[], expr: None, .. }, _)) } fn is_questionmark_desugar_marked_call(expr: &Expr<'_>) -> bool { @@ -1168,7 +1165,12 @@ fn is_isize_or_usize(typ: Ty<'_>) -> bool { } } -fn span_precision_loss_lint(cx: &LateContext<'_, '_>, expr: &Expr<'_>, cast_from: Ty<'_>, cast_to_f64: bool) { +fn span_precision_loss_lint( + cx: &LateContext<'_, '_>, + expr: &Expr<'_>, + cast_from: Ty<'_>, + cast_to_f64: bool, +) { let mantissa_nbits = if cast_to_f64 { 52 } else { 23 }; let arch_dependent = is_isize_or_usize(cast_from) && cast_to_f64; let arch_dependent_str = "on targets with 64-bit wide pointers "; @@ -1204,7 +1206,13 @@ fn should_strip_parens(op: &Expr<'_>, snip: &str) -> bool { false } -fn span_lossless_lint(cx: &LateContext<'_, '_>, expr: &Expr<'_>, op: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) { +fn span_lossless_lint( + cx: &LateContext<'_, '_>, + expr: &Expr<'_>, + op: &Expr<'_>, + cast_from: Ty<'_>, + cast_to: Ty<'_>, +) { // Do not suggest using From in consts/statics until it is valid to do so (see #2267). if in_constant(cx, expr.hir_id) { return; @@ -1214,11 +1222,7 @@ fn span_lossless_lint(cx: &LateContext<'_, '_>, expr: &Expr<'_>, op: &Expr<'_>, let mut applicability = Applicability::MachineApplicable; let opt = snippet_opt(cx, op.span); let sugg = if let Some(ref snip) = opt { - if should_strip_parens(op, snip) { - &snip[1..snip.len() - 1] - } else { - snip.as_str() - } + if should_strip_parens(op, snip) { &snip[1..snip.len() - 1] } else { snip.as_str() } } else { applicability = Applicability::HasPlaceholders; ".." @@ -1244,13 +1248,19 @@ enum ArchSuffix { None, } -fn check_loss_of_sign(cx: &LateContext<'_, '_>, expr: &Expr<'_>, op: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) { +fn check_loss_of_sign( + cx: &LateContext<'_, '_>, + expr: &Expr<'_>, + op: &Expr<'_>, + cast_from: Ty<'_>, + cast_to: Ty<'_>, +) { if !cast_from.is_signed() || cast_to.is_signed() { return; } // don't lint for positive constants - let const_val = constant(cx, &cx.tables(), op); + let const_val = constant(cx, &cx.typeck_results(), op); if_chain! { if let Some((const_val, _)) = const_val; if let Constant::Int(n) = const_val; @@ -1284,14 +1294,16 @@ fn check_loss_of_sign(cx: &LateContext<'_, '_>, expr: &Expr<'_>, op: &Expr<'_>, cx, CAST_SIGN_LOSS, expr.span, - &format!( - "casting `{}` to `{}` may lose the sign of the value", - cast_from, cast_to - ), + &format!("casting `{}` to `{}` may lose the sign of the value", cast_from, cast_to), ); } -fn check_truncation_and_wrapping(cx: &LateContext<'_, '_>, expr: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) { +fn check_truncation_and_wrapping( + cx: &LateContext<'_, '_>, + expr: &Expr<'_>, + cast_from: Ty<'_>, + cast_to: Ty<'_>, +) { let arch_64_suffix = " on targets with 64-bit wide pointers"; let arch_32_suffix = " on targets with 32-bit wide pointers"; let cast_unsigned_to_signed = !cast_from.is_signed() && cast_to.is_signed(); @@ -1307,11 +1319,7 @@ fn check_truncation_and_wrapping(cx: &LateContext<'_, '_>, expr: &Expr<'_>, cast ), (true, false) => ( to_nbits <= 32, - if to_nbits == 32 { - ArchSuffix::_64 - } else { - ArchSuffix::None - }, + if to_nbits == 32 { ArchSuffix::_64 } else { ArchSuffix::None }, to_nbits <= 32 && cast_unsigned_to_signed, ArchSuffix::_32, ), @@ -1319,11 +1327,7 @@ fn check_truncation_and_wrapping(cx: &LateContext<'_, '_>, expr: &Expr<'_>, cast from_nbits == 64, ArchSuffix::_32, cast_unsigned_to_signed, - if from_nbits == 64 { - ArchSuffix::_64 - } else { - ArchSuffix::_32 - }, + if from_nbits == 64 { ArchSuffix::_64 } else { ArchSuffix::_32 }, ), }; if span_truncation { @@ -1362,11 +1366,20 @@ fn check_truncation_and_wrapping(cx: &LateContext<'_, '_>, expr: &Expr<'_>, cast } } -fn check_lossless(cx: &LateContext<'_, '_>, expr: &Expr<'_>, op: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) { +fn check_lossless( + cx: &LateContext<'_, '_>, + expr: &Expr<'_>, + op: &Expr<'_>, + cast_from: Ty<'_>, + cast_to: Ty<'_>, +) { let cast_signed_to_unsigned = cast_from.is_signed() && !cast_to.is_signed(); let from_nbits = int_ty_to_nbits(cast_from, cx.tcx); let to_nbits = int_ty_to_nbits(cast_to, cx.tcx); - if !is_isize_or_usize(cast_from) && !is_isize_or_usize(cast_to) && from_nbits < to_nbits && !cast_signed_to_unsigned + if !is_isize_or_usize(cast_from) + && !is_isize_or_usize(cast_to) + && from_nbits < to_nbits + && !cast_signed_to_unsigned { span_lossless_lint(cx, expr, op, cast_from, cast_to); } @@ -1393,7 +1406,8 @@ fn is_c_void(cx: &LateContext<'_, '_>, ty: Ty<'_>) -> bool { if names.is_empty() { return false; } - if names[0] == sym!(libc) || names[0] == sym::core && *names.last().unwrap() == sym!(c_void) { + if names[0] == sym!(libc) || names[0] == sym::core && *names.last().unwrap() == sym!(c_void) + { return true; } } @@ -1416,7 +1430,8 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Casts { return; } if let ExprKind::Cast(ref ex, _) = expr.kind { - let (cast_from, cast_to) = (cx.tables().expr_ty(ex), cx.tables().expr_ty(expr)); + let (cast_from, cast_to) = + (cx.typeck_results().expr_ty(ex), cx.typeck_results().expr_ty(expr)); lint_fn_to_numeric_cast(cx, expr, ex, cast_from, cast_to); if let ExprKind::Lit(ref lit) = ex.kind { if_chain! { @@ -1441,9 +1456,12 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Casts { } } match lit.node { - LitKind::Int(_, LitIntType::Unsuffixed) | LitKind::Float(_, LitFloatType::Unsuffixed) => {}, + LitKind::Int(_, LitIntType::Unsuffixed) + | LitKind::Float(_, LitFloatType::Unsuffixed) => {} _ => { - if cast_from.kind == cast_to.kind && !in_external_macro(cx.sess(), expr.span) { + if cast_from.kind == cast_to.kind + && !in_external_macro(cx.sess(), expr.span) + { span_lint( cx, UNNECESSARY_CAST, @@ -1454,10 +1472,13 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Casts { ), ); } - }, + } } } - if cast_from.is_numeric() && cast_to.is_numeric() && !in_external_macro(cx.sess(), expr.span) { + if cast_from.is_numeric() + && cast_to.is_numeric() + && !in_external_macro(cx.sess(), expr.span) + { lint_numeric_casts(cx, expr, ex, cast_from, cast_to); } @@ -1476,18 +1497,14 @@ fn lint_numeric_casts<'tcx>( match (cast_from.is_integral(), cast_to.is_integral()) { (true, false) => { let from_nbits = int_ty_to_nbits(cast_from, cx.tcx); - let to_nbits = if let ty::Float(FloatTy::F32) = cast_to.kind { - 32 - } else { - 64 - }; + let to_nbits = if let ty::Float(FloatTy::F32) = cast_to.kind { 32 } else { 64 }; if is_isize_or_usize(cast_from) || from_nbits >= to_nbits { span_precision_loss_lint(cx, expr, cast_from, to_nbits == 64); } if from_nbits < to_nbits { span_lossless_lint(cx, expr, cast_expr, cast_from, cast_to); } - }, + } (false, true) => { span_lint( cx, @@ -1506,14 +1523,16 @@ fn lint_numeric_casts<'tcx>( ), ); } - }, + } (true, true) => { check_loss_of_sign(cx, expr, cast_expr, cast_from, cast_to); check_truncation_and_wrapping(cx, expr, cast_from, cast_to); check_lossless(cx, expr, cast_expr, cast_from, cast_to); - }, + } (false, false) => { - if let (&ty::Float(FloatTy::F64), &ty::Float(FloatTy::F32)) = (&cast_from.kind, &cast_to.kind) { + if let (&ty::Float(FloatTy::F64), &ty::Float(FloatTy::F32)) = + (&cast_from.kind, &cast_to.kind) + { span_lint( cx, CAST_POSSIBLE_TRUNCATION, @@ -1521,14 +1540,21 @@ fn lint_numeric_casts<'tcx>( "casting `f64` to `f32` may truncate the value", ); } - if let (&ty::Float(FloatTy::F32), &ty::Float(FloatTy::F64)) = (&cast_from.kind, &cast_to.kind) { + if let (&ty::Float(FloatTy::F32), &ty::Float(FloatTy::F64)) = + (&cast_from.kind, &cast_to.kind) + { span_lossless_lint(cx, expr, cast_expr, cast_from, cast_to); } - }, + } } } -fn lint_cast_ptr_alignment<'tcx>(cx: &LateContext<'_, 'tcx>, expr: &Expr<'_>, cast_from: Ty<'tcx>, cast_to: Ty<'tcx>) { +fn lint_cast_ptr_alignment<'tcx>( + cx: &LateContext<'_, 'tcx>, + expr: &Expr<'_>, + cast_from: Ty<'tcx>, + cast_to: Ty<'tcx>, +) { if_chain! { if let ty::RawPtr(from_ptr_ty) = &cast_from.kind; if let ty::RawPtr(to_ptr_ty) = &cast_to.kind; @@ -1565,13 +1591,14 @@ fn lint_fn_to_numeric_cast( ) { // We only want to check casts to `ty::Uint` or `ty::Int` match cast_to.kind { - ty::Uint(_) | ty::Int(..) => { /* continue on */ }, + ty::Uint(_) | ty::Int(..) => { /* continue on */ } _ => return, } match cast_from.kind { ty::FnDef(..) | ty::FnPtr(_) => { let mut applicability = Applicability::MaybeIncorrect; - let from_snippet = snippet_with_applicability(cx, cast_expr.span, "x", &mut applicability); + let from_snippet = + snippet_with_applicability(cx, cast_expr.span, "x", &mut applicability); let to_nbits = int_ty_to_nbits(cast_to, cx.tcx); if to_nbits < cx.tcx.data_layout.pointer_size.bits() { @@ -1598,8 +1625,8 @@ fn lint_fn_to_numeric_cast( applicability, ); } - }, - _ => {}, + } + _ => {} } } @@ -1650,7 +1677,11 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeComplexity { self.check_fndecl(cx, decl); } - fn check_struct_field(&mut self, cx: &LateContext<'a, 'tcx>, field: &'tcx hir::StructField<'_>) { + fn check_struct_field( + &mut self, + cx: &LateContext<'a, 'tcx>, + field: &'tcx hir::StructField<'_>, + ) { // enum variants are also struct fields now self.check_type(cx, &field.ty); } @@ -1665,8 +1696,12 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeComplexity { fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem<'_>) { match item.kind { - TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => self.check_type(cx, ty), - TraitItemKind::Fn(FnSig { ref decl, .. }, TraitFn::Required(_)) => self.check_fndecl(cx, decl), + TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => { + self.check_type(cx, ty) + } + TraitItemKind::Fn(FnSig { ref decl, .. }, TraitFn::Required(_)) => { + self.check_fndecl(cx, decl) + } // methods with default impl are covered by check_fn _ => (), } @@ -1674,7 +1709,9 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeComplexity { fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem<'_>) { match item.kind { - ImplItemKind::Const(ref ty, _) | ImplItemKind::TyAlias(ref ty) => self.check_type(cx, ty), + ImplItemKind::Const(ref ty, _) | ImplItemKind::TyAlias(ref ty) => { + self.check_type(cx, ty) + } // methods are covered by check_fn _ => (), } @@ -1735,7 +1772,9 @@ impl<'tcx> Visitor<'tcx> for TypeComplexityVisitor { TyKind::Infer | TyKind::Ptr(..) | TyKind::Rptr(..) => (1, 0), // the "normal" components of a type: named types, arrays/tuples - TyKind::Path(..) | TyKind::Slice(..) | TyKind::Tup(..) | TyKind::Array(..) => (10 * self.nest, 1), + TyKind::Path(..) | TyKind::Slice(..) | TyKind::Tup(..) | TyKind::Array(..) => { + (10 * self.nest, 1) + } // function types bring a lot of overhead TyKind::BareFn(ref bare) if bare.abi == Abi::Rust => (50 * self.nest, 1), @@ -1754,7 +1793,7 @@ impl<'tcx> Visitor<'tcx> for TypeComplexityVisitor { // simple trait bounds like A + B (20 * self.nest, 0) } - }, + } _ => (0, 0), }; @@ -1804,7 +1843,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CharLitAsU8 { if let ExprKind::Cast(e, _) = &expr.kind; if let ExprKind::Lit(l) = &e.kind; if let LitKind::Char(c) = l.node; - if ty::Uint(UintTy::U8) == cx.tables().expr_ty(expr).kind; + if ty::Uint(UintTy::U8) == cx.typeck_results().expr_ty(expr).kind; then { let mut applicability = Applicability::MachineApplicable; let snippet = snippet_with_applicability(cx, e.span, "'x'", &mut applicability); @@ -1878,10 +1917,13 @@ enum AbsurdComparisonResult { InequalityImpossible, } -fn is_cast_between_fixed_and_target<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'tcx>) -> bool { +fn is_cast_between_fixed_and_target<'a, 'tcx>( + cx: &LateContext<'a, 'tcx>, + expr: &'tcx Expr<'tcx>, +) -> bool { if let ExprKind::Cast(ref cast_exp, _) = expr.kind { - let precast_ty = cx.tables().expr_ty(cast_exp); - let cast_ty = cx.tables().expr_ty(expr); + let precast_ty = cx.typeck_results().expr_ty(cast_exp); + let cast_ty = cx.typeck_results().expr_ty(expr); return is_isize_or_usize(precast_ty) != is_isize_or_usize(cast_ty); } @@ -1901,7 +1943,7 @@ fn detect_absurd_comparison<'a, 'tcx>( // absurd comparison only makes sense on primitive types // primitive types don't implement comparison operators with each other - if cx.tables().expr_ty(lhs) != cx.tables().expr_ty(rhs) { + if cx.typeck_results().expr_ty(lhs) != cx.typeck_results().expr_ty(rhs) { return None; } @@ -1922,7 +1964,7 @@ fn detect_absurd_comparison<'a, 'tcx>( (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, AlwaysFalse), // x < min _ => return None, } - }, + } Rel::Le => { match (lx, rx) { (Some(l @ ExtremeExpr { which: Minimum, .. }), _) => (l, AlwaysTrue), // min <= x @@ -1931,28 +1973,35 @@ fn detect_absurd_comparison<'a, 'tcx>( (_, Some(r @ ExtremeExpr { which: Maximum, .. })) => (r, AlwaysTrue), // x <= max _ => return None, } - }, + } Rel::Ne | Rel::Eq => return None, }) } -fn detect_extreme_expr<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) -> Option> { +fn detect_extreme_expr<'a, 'tcx>( + cx: &LateContext<'a, 'tcx>, + expr: &'tcx Expr<'_>, +) -> Option> { use crate::types::ExtremeType::{Maximum, Minimum}; - let ty = cx.tables().expr_ty(expr); + let ty = cx.typeck_results().expr_ty(expr); - let cv = constant(cx, cx.tables(), expr)?.0; + let cv = constant(cx, cx.typeck_results(), expr)?.0; let which = match (&ty.kind, cv) { (&ty::Bool, Constant::Bool(false)) | (&ty::Uint(_), Constant::Int(0)) => Minimum, - (&ty::Int(ity), Constant::Int(i)) if i == unsext(cx.tcx, i128::MIN >> (128 - int_bits(cx.tcx, ity)), ity) => { + (&ty::Int(ity), Constant::Int(i)) + if i == unsext(cx.tcx, i128::MIN >> (128 - int_bits(cx.tcx, ity)), ity) => + { Minimum - }, + } (&ty::Bool, Constant::Bool(true)) => Maximum, - (&ty::Int(ity), Constant::Int(i)) if i == unsext(cx.tcx, i128::MAX >> (128 - int_bits(cx.tcx, ity)), ity) => { + (&ty::Int(ity), Constant::Int(i)) + if i == unsext(cx.tcx, i128::MAX >> (128 - int_bits(cx.tcx, ity)), ity) => + { Maximum - }, + } (&ty::Uint(uty), Constant::Int(i)) if clip(cx.tcx, u128::MAX, uty) == i => Maximum, _ => return None, @@ -2064,17 +2113,21 @@ impl PartialOrd for FullInt { impl Ord for FullInt { #[must_use] fn cmp(&self, other: &Self) -> Ordering { - self.partial_cmp(other) - .expect("`partial_cmp` for FullInt can never return `None`") + self.partial_cmp(other).expect("`partial_cmp` for FullInt can never return `None`") } } -fn numeric_cast_precast_bounds<'a>(cx: &LateContext<'_, '_>, expr: &'a Expr<'_>) -> Option<(FullInt, FullInt)> { +fn numeric_cast_precast_bounds<'a>( + cx: &LateContext<'_, '_>, + expr: &'a Expr<'_>, +) -> Option<(FullInt, FullInt)> { if let ExprKind::Cast(ref cast_exp, _) = expr.kind { - let pre_cast_ty = cx.tables().expr_ty(cast_exp); - let cast_ty = cx.tables().expr_ty(expr); + let pre_cast_ty = cx.typeck_results().expr_ty(cast_exp); + let cast_ty = cx.typeck_results().expr_ty(expr); // if it's a cast from i32 to u32 wrapping will invalidate all these checks - if cx.layout_of(pre_cast_ty).ok().map(|l| l.size) == cx.layout_of(cast_ty).ok().map(|l| l.size) { + if cx.layout_of(pre_cast_ty).ok().map(|l| l.size) + == cx.layout_of(cast_ty).ok().map(|l| l.size) + { return None; } match pre_cast_ty.kind { @@ -2101,10 +2154,13 @@ fn numeric_cast_precast_bounds<'a>(cx: &LateContext<'_, '_>, expr: &'a Expr<'_>) } } -fn node_as_const_fullint<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) -> Option { - let val = constant(cx, cx.tables(), expr)?.0; +fn node_as_const_fullint<'a, 'tcx>( + cx: &LateContext<'a, 'tcx>, + expr: &'tcx Expr<'_>, +) -> Option { + let val = constant(cx, cx.typeck_results(), expr)?.0; if let Constant::Int(const_int) = val { - match cx.tables().expr_ty(expr).kind { + match cx.typeck_results().expr_ty(expr).kind { ty::Int(ity) => Some(FullInt::S(sext(cx.tcx, const_int, ity))), ty::Uint(_) => Some(FullInt::U(const_int)), _ => None, @@ -2153,14 +2209,14 @@ fn upcast_comparison_bounds_err<'a, 'tcx>( } else { ub < norm_rhs_val } - }, + } Rel::Le => { if invert { norm_rhs_val <= lb } else { ub <= norm_rhs_val } - }, + } Rel::Eq | Rel::Ne => unreachable!(), } { err_upcast_comparison(cx, span, lhs, true) @@ -2171,14 +2227,14 @@ fn upcast_comparison_bounds_err<'a, 'tcx>( } else { lb >= norm_rhs_val } - }, + } Rel::Le => { if invert { norm_rhs_val > ub } else { lb > norm_rhs_val } - }, + } Rel::Eq | Rel::Ne => unreachable!(), } { err_upcast_comparison(cx, span, lhs, false) @@ -2200,8 +2256,24 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidUpcastComparisons { let lhs_bounds = numeric_cast_precast_bounds(cx, normalized_lhs); let rhs_bounds = numeric_cast_precast_bounds(cx, normalized_rhs); - upcast_comparison_bounds_err(cx, expr.span, rel, lhs_bounds, normalized_lhs, normalized_rhs, false); - upcast_comparison_bounds_err(cx, expr.span, rel, rhs_bounds, normalized_rhs, normalized_lhs, true); + upcast_comparison_bounds_err( + cx, + expr.span, + rel, + lhs_bounds, + normalized_lhs, + normalized_rhs, + false, + ); + upcast_comparison_bounds_err( + cx, + expr.span, + rel, + rhs_bounds, + normalized_rhs, + normalized_lhs, + true, + ); } } } @@ -2299,12 +2371,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ImplicitHasher { } match item.kind { - ItemKind::Impl { - ref generics, - self_ty: ref ty, - ref items, - .. - } => { + ItemKind::Impl { ref generics, self_ty: ref ty, ref items, .. } => { let mut vis = ImplicitHasherTypeVisitor::new(cx); vis.visit_ty(ty); @@ -2314,8 +2381,10 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ImplicitHasher { } let generics_suggestion_span = generics.span.substitute_dummy({ - let pos = snippet_opt(cx, item.span.until(target.span())) - .and_then(|snip| Some(item.span.lo() + BytePos(snip.find("impl")? as u32 + 4))); + let pos = + snippet_opt(cx, item.span.until(target.span())).and_then(|snip| { + Some(item.span.lo() + BytePos(snip.find("impl")? as u32 + 4)) + }); if let Some(pos) = pos { Span::new(pos, pos, item.span.data().ctxt) } else { @@ -2337,11 +2406,18 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ImplicitHasher { target.type_name() ), move |diag| { - suggestion(cx, diag, generics.span, generics_suggestion_span, target, ctr_vis); + suggestion( + cx, + diag, + generics.span, + generics_suggestion_span, + target, + ctr_vis, + ); }, ); } - }, + } ItemKind::Fn(ref sig, ref generics, body_id) => { let body = cx.tcx.hir().body(body_id); @@ -2357,7 +2433,10 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ImplicitHasher { let pos = snippet_opt(cx, item.span.until(body.params[0].pat.span)) .and_then(|snip| { let i = snip.find("fn")?; - Some(item.span.lo() + BytePos((i + (&snip[i..]).find('(')?) as u32)) + Some( + item.span.lo() + + BytePos((i + (&snip[i..]).find('(')?) as u32), + ) }) .expect("failed to create span for type parameters"); Span::new(pos, pos, item.span.data().ctxt) @@ -2375,13 +2454,20 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ImplicitHasher { target.type_name() ), move |diag| { - suggestion(cx, diag, generics.span, generics_suggestion_span, target, ctr_vis); + suggestion( + cx, + diag, + generics.span, + generics_suggestion_span, + target, + ctr_vis, + ); }, ); } } - }, - _ => {}, + } + _ => {} } } } @@ -2420,11 +2506,7 @@ impl<'tcx> ImplicitHasherType<'tcx> { snippet(cx, params[1].span, "V"), )) } else if is_type_diagnostic_item(cx, ty, sym!(hashset_type)) && params_len == 1 { - Some(ImplicitHasherType::HashSet( - hir_ty.span, - ty, - snippet(cx, params[0].span, "T"), - )) + Some(ImplicitHasherType::HashSet(hir_ty.span, ty, snippet(cx, params[0].span, "T"))) } else { None } @@ -2490,19 +2572,14 @@ impl<'a, 'tcx> Visitor<'tcx> for ImplicitHasherTypeVisitor<'a, 'tcx> { /// Looks for default-hasher-dependent constructors like `HashMap::new`. struct ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> { cx: &'a LateContext<'a, 'tcx>, - body: &'a TypeckTables<'tcx>, + body: &'a TypeckResults<'tcx>, target: &'b ImplicitHasherType<'tcx>, suggestions: BTreeMap, } impl<'a, 'b, 'tcx> ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> { fn new(cx: &'a LateContext<'a, 'tcx>, target: &'b ImplicitHasherType<'tcx>) -> Self { - Self { - cx, - body: cx.tables(), - target, - suggestions: BTreeMap::new(), - } + Self { cx, body: cx.typeck_results(), target, suggestions: BTreeMap::new() } } } @@ -2511,7 +2588,7 @@ impl<'a, 'b, 'tcx> Visitor<'tcx> for ImplicitHasherConstructorVisitor<'a, 'b, 't fn visit_body(&mut self, body: &'tcx Body<'_>) { let prev_body = self.body; - self.body = self.cx.tcx.body_tables(body.id()); + self.body = self.cx.tcx.typeck_body(body.id()); walk_body(self, body); self.body = prev_body; } @@ -2608,7 +2685,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for RefToMut { if let TyKind::Ptr(MutTy { mutbl: Mutability::Mut, .. }) = t.kind; if let ExprKind::Cast(e, t) = &e.kind; if let TyKind::Ptr(MutTy { mutbl: Mutability::Not, .. }) = t.kind; - if let ty::Ref(..) = cx.tables().node_type(e.hir_id).kind; + if let ty::Ref(..) = cx.typeck_results().node_type(e.hir_id).kind; then { span_lint( cx, diff --git a/src/tools/clippy/clippy_lints/src/unnamed_address.rs b/src/tools/clippy/clippy_lints/src/unnamed_address.rs index 53e47f09ae55c..9b3ca4ab4bad6 100644 --- a/src/tools/clippy/clippy_lints/src/unnamed_address.rs +++ b/src/tools/clippy/clippy_lints/src/unnamed_address.rs @@ -65,14 +65,14 @@ impl LateLintPass<'_, '_> for UnnamedAddress { } fn is_trait_ptr(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> bool { - match cx.tables().expr_ty_adjusted(expr).kind { + match cx.typeck_results().expr_ty_adjusted(expr).kind { ty::RawPtr(ty::TypeAndMut { ty, .. }) => ty.is_trait(), _ => false, } } fn is_fn_def(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> bool { - if let ty::FnDef(..) = cx.tables().expr_ty(expr).kind { + if let ty::FnDef(..) = cx.typeck_results().expr_ty(expr).kind { true } else { false @@ -98,11 +98,11 @@ impl LateLintPass<'_, '_> for UnnamedAddress { if_chain! { if let ExprKind::Call(ref func, [ref _left, ref _right]) = expr.kind; if let ExprKind::Path(ref func_qpath) = func.kind; - if let Some(def_id) = cx.tables().qpath_res(func_qpath, func.hir_id).opt_def_id(); + if let Some(def_id) = cx.typeck_results().qpath_res(func_qpath, func.hir_id).opt_def_id(); if match_def_path(cx, def_id, &paths::PTR_EQ) || match_def_path(cx, def_id, &paths::RC_PTR_EQ) || match_def_path(cx, def_id, &paths::ARC_PTR_EQ); - let ty_param = cx.tables().node_substs(func.hir_id).type_at(0); + let ty_param = cx.typeck_results().node_substs(func.hir_id).type_at(0); if ty_param.is_trait(); then { span_lint_and_help( @@ -119,8 +119,8 @@ impl LateLintPass<'_, '_> for UnnamedAddress { if_chain! { if let ExprKind::Binary(binop, ref left, ref right) = expr.kind; if is_comparison(binop.node); - if cx.tables().expr_ty_adjusted(left).is_fn_ptr() && - cx.tables().expr_ty_adjusted(right).is_fn_ptr(); + if cx.typeck_results().expr_ty_adjusted(left).is_fn_ptr() && + cx.typeck_results().expr_ty_adjusted(right).is_fn_ptr(); if is_fn_def(cx, left) || is_fn_def(cx, right); then { span_lint( diff --git a/src/tools/clippy/clippy_lints/src/unnecessary_sort_by.rs b/src/tools/clippy/clippy_lints/src/unnecessary_sort_by.rs index bb68e50b33195..0fada704462ac 100644 --- a/src/tools/clippy/clippy_lints/src/unnecessary_sort_by.rs +++ b/src/tools/clippy/clippy_lints/src/unnecessary_sort_by.rs @@ -77,7 +77,7 @@ fn mirrored_exprs( // Two boxes with mirrored contents (ExprKind::Box(left_expr), ExprKind::Box(right_expr)) => { mirrored_exprs(cx, left_expr, a_ident, right_expr, b_ident) - }, + } // Two arrays with mirrored contents (ExprKind::Array(left_exprs), ExprKind::Array(right_exprs)) => left_exprs .iter() @@ -91,7 +91,7 @@ fn mirrored_exprs( .iter() .zip(right_args.iter()) .all(|(left, right)| mirrored_exprs(cx, left, a_ident, right, b_ident)) - }, + } // The two exprs are method calls. // Check to see that the function is the same and the arguments are mirrored // This is enough because the receiver of the method is listed in the arguments @@ -104,60 +104,52 @@ fn mirrored_exprs( .iter() .zip(right_args.iter()) .all(|(left, right)| mirrored_exprs(cx, left, a_ident, right, b_ident)) - }, + } // Two tuples with mirrored contents (ExprKind::Tup(left_exprs), ExprKind::Tup(right_exprs)) => left_exprs .iter() .zip(right_exprs.iter()) .all(|(left, right)| mirrored_exprs(cx, left, a_ident, right, b_ident)), // Two binary ops, which are the same operation and which have mirrored arguments - (ExprKind::Binary(left_op, left_left, left_right), ExprKind::Binary(right_op, right_left, right_right)) => { + ( + ExprKind::Binary(left_op, left_left, left_right), + ExprKind::Binary(right_op, right_left, right_right), + ) => { left_op.node == right_op.node && mirrored_exprs(cx, left_left, a_ident, right_left, b_ident) && mirrored_exprs(cx, left_right, a_ident, right_right, b_ident) - }, + } // Two unary ops, which are the same operation and which have the same argument (ExprKind::Unary(left_op, left_expr), ExprKind::Unary(right_op, right_expr)) => { left_op == right_op && mirrored_exprs(cx, left_expr, a_ident, right_expr, b_ident) - }, + } // The two exprs are literals of some kind (ExprKind::Lit(left_lit), ExprKind::Lit(right_lit)) => left_lit.node == right_lit.node, - (ExprKind::Cast(left, _), ExprKind::Cast(right, _)) => mirrored_exprs(cx, left, a_ident, right, b_ident), + (ExprKind::Cast(left, _), ExprKind::Cast(right, _)) => { + mirrored_exprs(cx, left, a_ident, right, b_ident) + } (ExprKind::DropTemps(left_block), ExprKind::DropTemps(right_block)) => { mirrored_exprs(cx, left_block, a_ident, right_block, b_ident) - }, + } (ExprKind::Field(left_expr, left_ident), ExprKind::Field(right_expr, right_ident)) => { - left_ident.name == right_ident.name && mirrored_exprs(cx, left_expr, a_ident, right_expr, right_ident) - }, + left_ident.name == right_ident.name + && mirrored_exprs(cx, left_expr, a_ident, right_expr, right_ident) + } // Two paths: either one is a and the other is b, or they're identical to each other ( - ExprKind::Path(QPath::Resolved( - _, - Path { - segments: left_segments, - .. - }, - )), - ExprKind::Path(QPath::Resolved( - _, - Path { - segments: right_segments, - .. - }, - )), + ExprKind::Path(QPath::Resolved(_, Path { segments: left_segments, .. })), + ExprKind::Path(QPath::Resolved(_, Path { segments: right_segments, .. })), ) => { (left_segments .iter() .zip(right_segments.iter()) .all(|(left, right)| left.ident == right.ident) - && left_segments - .iter() - .all(|seg| &seg.ident != a_ident && &seg.ident != b_ident)) + && left_segments.iter().all(|seg| &seg.ident != a_ident && &seg.ident != b_ident)) || (left_segments.len() == 1 && &left_segments[0].ident == a_ident && right_segments.len() == 1 && &right_segments[0].ident == b_ident) - }, + } // Matching expressions, but one or both is borrowed ( ExprKind::AddrOf(left_kind, Mutability::Not, left_expr), @@ -165,8 +157,10 @@ fn mirrored_exprs( ) => left_kind == right_kind && mirrored_exprs(cx, left_expr, a_ident, right_expr, b_ident), (_, ExprKind::AddrOf(_, Mutability::Not, right_expr)) => { mirrored_exprs(cx, a_expr, a_ident, right_expr, b_ident) - }, - (ExprKind::AddrOf(_, Mutability::Not, left_expr), _) => mirrored_exprs(cx, left_expr, a_ident, b_expr, b_ident), + } + (ExprKind::AddrOf(_, Mutability::Not, left_expr), _) => { + mirrored_exprs(cx, left_expr, a_ident, b_expr, b_ident) + } _ => false, } } @@ -177,7 +171,7 @@ fn detect_lint(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> Option if let name = name_ident.ident.name.to_ident_string(); if name == "sort_by" || name == "sort_unstable_by"; if let [vec, Expr { kind: ExprKind::Closure(_, _, closure_body_id, _, _), .. }] = args; - if utils::match_type(cx, &cx.tables().expr_ty(vec), &paths::VEC); + if utils::match_type(cx, &cx.typeck_results().expr_ty(vec), &paths::VEC); if let closure_body = cx.tcx.hir().body(*closure_body_id); if let &[ Param { pat: Pat { kind: PatKind::Binding(_, _, left_ident, _), .. }, ..}, @@ -264,7 +258,7 @@ impl LateLintPass<'_, '_> for UnnecessarySortBy { ), Applicability::MachineApplicable, ), - None => {}, + None => {} } } } diff --git a/src/tools/clippy/clippy_lints/src/unwrap.rs b/src/tools/clippy/clippy_lints/src/unwrap.rs index be55982f90556..a6bf2d08163aa 100644 --- a/src/tools/clippy/clippy_lints/src/unwrap.rs +++ b/src/tools/clippy/clippy_lints/src/unwrap.rs @@ -92,20 +92,23 @@ fn collect_unwrap_info<'a, 'tcx>( invert: bool, ) -> Vec> { fn is_relevant_option_call(cx: &LateContext<'_, '_>, ty: Ty<'_>, method_name: &str) -> bool { - is_type_diagnostic_item(cx, ty, sym!(option_type)) && ["is_some", "is_none"].contains(&method_name) + is_type_diagnostic_item(cx, ty, sym!(option_type)) + && ["is_some", "is_none"].contains(&method_name) } fn is_relevant_result_call(cx: &LateContext<'_, '_>, ty: Ty<'_>, method_name: &str) -> bool { - is_type_diagnostic_item(cx, ty, sym!(result_type)) && ["is_ok", "is_err"].contains(&method_name) + is_type_diagnostic_item(cx, ty, sym!(result_type)) + && ["is_ok", "is_err"].contains(&method_name) } if let ExprKind::Binary(op, left, right) = &expr.kind { match (invert, op.node) { - (false, BinOpKind::And | BinOpKind::BitAnd) | (true, BinOpKind::Or | BinOpKind::BitOr) => { + (false, BinOpKind::And | BinOpKind::BitAnd) + | (true, BinOpKind::Or | BinOpKind::BitOr) => { let mut unwrap_info = collect_unwrap_info(cx, left, branch, invert); unwrap_info.append(&mut collect_unwrap_info(cx, right, branch, invert)); return unwrap_info; - }, + } _ => (), } } else if let ExprKind::Unary(UnOp::UnNot, expr) = &expr.kind { @@ -114,7 +117,7 @@ fn collect_unwrap_info<'a, 'tcx>( if_chain! { if let ExprKind::MethodCall(method_name, _, args, _) = &expr.kind; if let ExprKind::Path(QPath::Resolved(None, path)) = &args[0].kind; - let ty = cx.tables().expr_ty(&args[0]); + let ty = cx.typeck_results().expr_ty(&args[0]); let name = method_name.ident.as_str(); if is_relevant_option_call(cx, ty, &name) || is_relevant_result_call(cx, ty, &name); then { @@ -223,10 +226,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Unwrap { return; } - let mut v = UnwrappableVariablesVisitor { - cx, - unwrappables: Vec::new(), - }; + let mut v = UnwrappableVariablesVisitor { cx, unwrappables: Vec::new() }; walk_fn(&mut v, kind, decl, body.id(), span, fn_id); } diff --git a/src/tools/clippy/clippy_lints/src/useless_conversion.rs b/src/tools/clippy/clippy_lints/src/useless_conversion.rs index 5d150ad4f03e4..dfddded118165 100644 --- a/src/tools/clippy/clippy_lints/src/useless_conversion.rs +++ b/src/tools/clippy/clippy_lints/src/useless_conversion.rs @@ -63,8 +63,8 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UselessConversion { ExprKind::MethodCall(ref name, .., ref args, _) => { if match_trait_method(cx, e, &paths::INTO) && &*name.ident.as_str() == "into" { - let a = cx.tables().expr_ty(e); - let b = cx.tables().expr_ty(&args[0]); + let a = cx.typeck_results().expr_ty(e); + let b = cx.typeck_results().expr_ty(&args[0]); if TyS::same_type(a, b) { let sugg = snippet_with_macro_callsite(cx, args[0].span, "").to_string(); span_lint_and_sugg( @@ -79,8 +79,8 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UselessConversion { } } if match_trait_method(cx, e, &paths::INTO_ITERATOR) && &*name.ident.as_str() == "into_iter" { - let a = cx.tables().expr_ty(e); - let b = cx.tables().expr_ty(&args[0]); + let a = cx.typeck_results().expr_ty(e); + let b = cx.typeck_results().expr_ty(&args[0]); if TyS::same_type(a, b) { let sugg = snippet(cx, args[0].span, "").into_owned(); span_lint_and_sugg( @@ -96,8 +96,8 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UselessConversion { } if match_trait_method(cx, e, &paths::TRY_INTO_TRAIT) && &*name.ident.as_str() == "try_into" { if_chain! { - let a = cx.tables().expr_ty(e); - let b = cx.tables().expr_ty(&args[0]); + let a = cx.typeck_results().expr_ty(e); + let b = cx.typeck_results().expr_ty(&args[0]); if is_type_diagnostic_item(cx, a, sym!(result_type)); if let ty::Adt(_, substs) = a.kind; if let Some(a_type) = substs.types().next(); @@ -121,9 +121,9 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UselessConversion { if_chain! { if args.len() == 1; if let ExprKind::Path(ref qpath) = path.kind; - if let Some(def_id) = cx.tables().qpath_res(qpath, path.hir_id).opt_def_id(); - let a = cx.tables().expr_ty(e); - let b = cx.tables().expr_ty(&args[0]); + if let Some(def_id) = cx.typeck_results().qpath_res(qpath, path.hir_id).opt_def_id(); + let a = cx.typeck_results().expr_ty(e); + let b = cx.typeck_results().expr_ty(&args[0]); then { if_chain! { diff --git a/src/tools/clippy/clippy_lints/src/utils/higher.rs b/src/tools/clippy/clippy_lints/src/utils/higher.rs index 0e78f35a1290a..194205858bfde 100644 --- a/src/tools/clippy/clippy_lints/src/utils/higher.rs +++ b/src/tools/clippy/clippy_lints/src/utils/higher.rs @@ -56,7 +56,7 @@ pub fn range<'a, 'b, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'b hir::Expr<'_>) Some(expr) } - let def_path = match cx.tables().expr_ty(expr).kind { + let def_path = match cx.typeck_results().expr_ty(expr).kind { ty::Adt(def, _) => cx.tcx.def_path(def.did), _ => return None, }; @@ -262,7 +262,7 @@ pub fn vec_macro<'e>(cx: &LateContext<'_, '_>, expr: &'e hir::Expr<'_>) -> Optio if let hir::ExprKind::Call(ref fun, ref args) = expr.kind; if let hir::ExprKind::Path(ref qpath) = fun.kind; if is_expn_of(fun.span, "vec").is_some(); - if let Some(fun_def_id) = cx.tables().qpath_res(qpath, fun.hir_id).opt_def_id(); + if let Some(fun_def_id) = cx.typeck_results().qpath_res(qpath, fun.hir_id).opt_def_id(); then { return if match_def_path(cx, fun_def_id, &paths::VEC_FROM_ELEM) && args.len() == 2 { // `vec![elem; size]` case diff --git a/src/tools/clippy/clippy_lints/src/utils/hir_utils.rs b/src/tools/clippy/clippy_lints/src/utils/hir_utils.rs index a74ab18a063b2..4f28b7ee7a345 100644 --- a/src/tools/clippy/clippy_lints/src/utils/hir_utils.rs +++ b/src/tools/clippy/clippy_lints/src/utils/hir_utils.rs @@ -3,13 +3,13 @@ use crate::utils::differing_macro_contexts; use rustc_ast::ast::InlineAsmTemplatePiece; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; use rustc_hir::{ - BinOpKind, Block, BlockCheckMode, BodyId, BorrowKind, CaptureBy, Expr, ExprKind, Field, FnRetTy, GenericArg, - GenericArgs, Guard, InlineAsmOperand, Lifetime, LifetimeName, ParamName, Pat, PatKind, Path, PathSegment, QPath, - Stmt, StmtKind, Ty, TyKind, TypeBinding, + BinOpKind, Block, BlockCheckMode, BodyId, BorrowKind, CaptureBy, Expr, ExprKind, Field, + FnRetTy, GenericArg, GenericArgs, Guard, InlineAsmOperand, Lifetime, LifetimeName, ParamName, + Pat, PatKind, Path, PathSegment, QPath, Stmt, StmtKind, Ty, TyKind, TypeBinding, }; use rustc_lint::LateContext; use rustc_middle::ich::StableHashingContextProvider; -use rustc_middle::ty::TypeckTables; +use rustc_middle::ty::TypeckResults; use rustc_span::Symbol; use std::hash::Hash; @@ -22,7 +22,7 @@ use std::hash::Hash; pub struct SpanlessEq<'a, 'tcx> { /// Context used to evaluate constant expressions. cx: &'a LateContext<'a, 'tcx>, - tables: &'a TypeckTables<'tcx>, + tables: &'a TypeckResults<'tcx>, /// If is true, never consider as equal expressions containing function /// calls. ignore_fn: bool, @@ -30,19 +30,11 @@ pub struct SpanlessEq<'a, 'tcx> { impl<'a, 'tcx> SpanlessEq<'a, 'tcx> { pub fn new(cx: &'a LateContext<'a, 'tcx>) -> Self { - Self { - cx, - tables: cx.tables(), - ignore_fn: false, - } + Self { cx, tables: cx.typeck_results(), ignore_fn: false } } pub fn ignore_fn(self) -> Self { - Self { - cx: self.cx, - tables: self.cx.tables(), - ignore_fn: true, - } + Self { cx: self.cx, tables: self.cx.typeck_results(), ignore_fn: true } } /// Checks whether two statements are the same. @@ -52,10 +44,9 @@ impl<'a, 'tcx> SpanlessEq<'a, 'tcx> { self.eq_pat(&l.pat, &r.pat) && both(&l.ty, &r.ty, |l, r| self.eq_ty(l, r)) && both(&l.init, &r.init, |l, r| self.eq_expr(l, r)) - }, - (&StmtKind::Expr(ref l), &StmtKind::Expr(ref r)) | (&StmtKind::Semi(ref l), &StmtKind::Semi(ref r)) => { - self.eq_expr(l, r) - }, + } + (&StmtKind::Expr(ref l), &StmtKind::Expr(ref r)) + | (&StmtKind::Semi(ref l), &StmtKind::Semi(ref r)) => self.eq_expr(l, r), _ => false, } } @@ -84,46 +75,56 @@ impl<'a, 'tcx> SpanlessEq<'a, 'tcx> { match (&left.kind, &right.kind) { (&ExprKind::AddrOf(lb, l_mut, ref le), &ExprKind::AddrOf(rb, r_mut, ref re)) => { lb == rb && l_mut == r_mut && self.eq_expr(le, re) - }, + } (&ExprKind::Continue(li), &ExprKind::Continue(ri)) => { both(&li.label, &ri.label, |l, r| l.ident.as_str() == r.ident.as_str()) - }, + } (&ExprKind::Assign(ref ll, ref lr, _), &ExprKind::Assign(ref rl, ref rr, _)) => { self.eq_expr(ll, rl) && self.eq_expr(lr, rr) - }, - (&ExprKind::AssignOp(ref lo, ref ll, ref lr), &ExprKind::AssignOp(ref ro, ref rl, ref rr)) => { - lo.node == ro.node && self.eq_expr(ll, rl) && self.eq_expr(lr, rr) - }, + } + ( + &ExprKind::AssignOp(ref lo, ref ll, ref lr), + &ExprKind::AssignOp(ref ro, ref rl, ref rr), + ) => lo.node == ro.node && self.eq_expr(ll, rl) && self.eq_expr(lr, rr), (&ExprKind::Block(ref l, _), &ExprKind::Block(ref r, _)) => self.eq_block(l, r), (&ExprKind::Binary(l_op, ref ll, ref lr), &ExprKind::Binary(r_op, ref rl, ref rr)) => { l_op.node == r_op.node && self.eq_expr(ll, rl) && self.eq_expr(lr, rr) || swap_binop(l_op.node, ll, lr).map_or(false, |(l_op, ll, lr)| { l_op == r_op.node && self.eq_expr(ll, rl) && self.eq_expr(lr, rr) }) - }, + } (&ExprKind::Break(li, ref le), &ExprKind::Break(ri, ref re)) => { both(&li.label, &ri.label, |l, r| l.ident.as_str() == r.ident.as_str()) && both(le, re, |l, r| self.eq_expr(l, r)) - }, + } (&ExprKind::Box(ref l), &ExprKind::Box(ref r)) => self.eq_expr(l, r), (&ExprKind::Call(l_fun, l_args), &ExprKind::Call(r_fun, r_args)) => { !self.ignore_fn && self.eq_expr(l_fun, r_fun) && self.eq_exprs(l_args, r_args) - }, + } (&ExprKind::Cast(ref lx, ref lt), &ExprKind::Cast(ref rx, ref rt)) | (&ExprKind::Type(ref lx, ref lt), &ExprKind::Type(ref rx, ref rt)) => { self.eq_expr(lx, rx) && self.eq_ty(lt, rt) - }, - (&ExprKind::Field(ref l_f_exp, ref l_f_ident), &ExprKind::Field(ref r_f_exp, ref r_f_ident)) => { - l_f_ident.name == r_f_ident.name && self.eq_expr(l_f_exp, r_f_exp) - }, + } + ( + &ExprKind::Field(ref l_f_exp, ref l_f_ident), + &ExprKind::Field(ref r_f_exp, ref r_f_ident), + ) => l_f_ident.name == r_f_ident.name && self.eq_expr(l_f_exp, r_f_exp), (&ExprKind::Index(ref la, ref li), &ExprKind::Index(ref ra, ref ri)) => { self.eq_expr(la, ra) && self.eq_expr(li, ri) - }, + } (&ExprKind::Lit(ref l), &ExprKind::Lit(ref r)) => l.node == r.node, - (&ExprKind::Loop(ref lb, ref ll, ref lls), &ExprKind::Loop(ref rb, ref rl, ref rls)) => { - lls == rls && self.eq_block(lb, rb) && both(ll, rl, |l, r| l.ident.as_str() == r.ident.as_str()) - }, - (&ExprKind::Match(ref le, ref la, ref ls), &ExprKind::Match(ref re, ref ra, ref rs)) => { + ( + &ExprKind::Loop(ref lb, ref ll, ref lls), + &ExprKind::Loop(ref rb, ref rl, ref rls), + ) => { + lls == rls + && self.eq_block(lb, rb) + && both(ll, rl, |l, r| l.ident.as_str() == r.ident.as_str()) + } + ( + &ExprKind::Match(ref le, ref la, ref ls), + &ExprKind::Match(ref re, ref ra, ref rs), + ) => { ls == rs && self.eq_expr(le, re) && over(la, ra, |l, r| { @@ -131,27 +132,37 @@ impl<'a, 'tcx> SpanlessEq<'a, 'tcx> { && both(&l.guard, &r.guard, |l, r| self.eq_guard(l, r)) && self.eq_pat(&l.pat, &r.pat) }) - }, - (&ExprKind::MethodCall(l_path, _, l_args, _), &ExprKind::MethodCall(r_path, _, r_args, _)) => { - !self.ignore_fn && self.eq_path_segment(l_path, r_path) && self.eq_exprs(l_args, r_args) - }, + } + ( + &ExprKind::MethodCall(l_path, _, l_args, _), + &ExprKind::MethodCall(r_path, _, r_args, _), + ) => { + !self.ignore_fn + && self.eq_path_segment(l_path, r_path) + && self.eq_exprs(l_args, r_args) + } (&ExprKind::Repeat(ref le, ref ll_id), &ExprKind::Repeat(ref re, ref rl_id)) => { - let mut celcx = constant_context(self.cx, self.cx.tcx.body_tables(ll_id.body)); + let mut celcx = constant_context(self.cx, self.cx.tcx.typeck_body(ll_id.body)); let ll = celcx.expr(&self.cx.tcx.hir().body(ll_id.body).value); - let mut celcx = constant_context(self.cx, self.cx.tcx.body_tables(rl_id.body)); + let mut celcx = constant_context(self.cx, self.cx.tcx.typeck_body(rl_id.body)); let rl = celcx.expr(&self.cx.tcx.hir().body(rl_id.body).value); self.eq_expr(le, re) && ll == rl - }, + } (&ExprKind::Ret(ref l), &ExprKind::Ret(ref r)) => both(l, r, |l, r| self.eq_expr(l, r)), (&ExprKind::Path(ref l), &ExprKind::Path(ref r)) => self.eq_qpath(l, r), - (&ExprKind::Struct(ref l_path, ref lf, ref lo), &ExprKind::Struct(ref r_path, ref rf, ref ro)) => { + ( + &ExprKind::Struct(ref l_path, ref lf, ref lo), + &ExprKind::Struct(ref r_path, ref rf, ref ro), + ) => { self.eq_qpath(l_path, r_path) && both(lo, ro, |l, r| self.eq_expr(l, r)) && over(lf, rf, |l, r| self.eq_field(l, r)) - }, + } (&ExprKind::Tup(l_tup), &ExprKind::Tup(r_tup)) => self.eq_exprs(l_tup, r_tup), - (&ExprKind::Unary(l_op, ref le), &ExprKind::Unary(r_op, ref re)) => l_op == r_op && self.eq_expr(le, re), + (&ExprKind::Unary(l_op, ref le), &ExprKind::Unary(r_op, ref re)) => { + l_op == r_op && self.eq_expr(le, re) + } (&ExprKind::Array(l), &ExprKind::Array(r)) => self.eq_exprs(l, r), (&ExprKind::DropTemps(ref le), &ExprKind::DropTemps(ref re)) => self.eq_expr(le, re), _ => false, @@ -174,7 +185,9 @@ impl<'a, 'tcx> SpanlessEq<'a, 'tcx> { fn eq_generic_arg(&mut self, left: &GenericArg<'_>, right: &GenericArg<'_>) -> bool { match (left, right) { - (GenericArg::Lifetime(l_lt), GenericArg::Lifetime(r_lt)) => Self::eq_lifetime(l_lt, r_lt), + (GenericArg::Lifetime(l_lt), GenericArg::Lifetime(r_lt)) => { + Self::eq_lifetime(l_lt, r_lt) + } (GenericArg::Type(l_ty), GenericArg::Type(r_ty)) => self.eq_ty(l_ty, r_ty), _ => false, } @@ -188,26 +201,36 @@ impl<'a, 'tcx> SpanlessEq<'a, 'tcx> { pub fn eq_pat(&mut self, left: &Pat<'_>, right: &Pat<'_>) -> bool { match (&left.kind, &right.kind) { (&PatKind::Box(ref l), &PatKind::Box(ref r)) => self.eq_pat(l, r), - (&PatKind::TupleStruct(ref lp, ref la, ls), &PatKind::TupleStruct(ref rp, ref ra, rs)) => { - self.eq_qpath(lp, rp) && over(la, ra, |l, r| self.eq_pat(l, r)) && ls == rs - }, - (&PatKind::Binding(ref lb, .., ref li, ref lp), &PatKind::Binding(ref rb, .., ref ri, ref rp)) => { - lb == rb && li.name.as_str() == ri.name.as_str() && both(lp, rp, |l, r| self.eq_pat(l, r)) - }, + ( + &PatKind::TupleStruct(ref lp, ref la, ls), + &PatKind::TupleStruct(ref rp, ref ra, rs), + ) => self.eq_qpath(lp, rp) && over(la, ra, |l, r| self.eq_pat(l, r)) && ls == rs, + ( + &PatKind::Binding(ref lb, .., ref li, ref lp), + &PatKind::Binding(ref rb, .., ref ri, ref rp), + ) => { + lb == rb + && li.name.as_str() == ri.name.as_str() + && both(lp, rp, |l, r| self.eq_pat(l, r)) + } (&PatKind::Path(ref l), &PatKind::Path(ref r)) => self.eq_qpath(l, r), (&PatKind::Lit(ref l), &PatKind::Lit(ref r)) => self.eq_expr(l, r), (&PatKind::Tuple(ref l, ls), &PatKind::Tuple(ref r, rs)) => { ls == rs && over(l, r, |l, r| self.eq_pat(l, r)) - }, + } (&PatKind::Range(ref ls, ref le, li), &PatKind::Range(ref rs, ref re, ri)) => { - both(ls, rs, |a, b| self.eq_expr(a, b)) && both(le, re, |a, b| self.eq_expr(a, b)) && (li == ri) - }, - (&PatKind::Ref(ref le, ref lm), &PatKind::Ref(ref re, ref rm)) => lm == rm && self.eq_pat(le, re), + both(ls, rs, |a, b| self.eq_expr(a, b)) + && both(le, re, |a, b| self.eq_expr(a, b)) + && (li == ri) + } + (&PatKind::Ref(ref le, ref lm), &PatKind::Ref(ref re, ref rm)) => { + lm == rm && self.eq_pat(le, re) + } (&PatKind::Slice(ref ls, ref li, ref le), &PatKind::Slice(ref rs, ref ri, ref re)) => { over(ls, rs, |l, r| self.eq_pat(l, r)) && over(le, re, |l, r| self.eq_pat(l, r)) && both(li, ri, |l, r| self.eq_pat(l, r)) - }, + } (&PatKind::Wild, &PatKind::Wild) => true, _ => false, } @@ -218,10 +241,10 @@ impl<'a, 'tcx> SpanlessEq<'a, 'tcx> { match (left, right) { (&QPath::Resolved(ref lty, ref lpath), &QPath::Resolved(ref rty, ref rpath)) => { both(lty, rty, |l, r| self.eq_ty(l, r)) && self.eq_path(lpath, rpath) - }, + } (&QPath::TypeRelative(ref lty, ref lseg), &QPath::TypeRelative(ref rty, ref rseg)) => { self.eq_ty(lty, rty) && self.eq_path_segment(lseg, rseg) - }, + } _ => false, } } @@ -245,7 +268,11 @@ impl<'a, 'tcx> SpanlessEq<'a, 'tcx> { } } - pub fn eq_path_segments(&mut self, left: &[PathSegment<'_>], right: &[PathSegment<'_>]) -> bool { + pub fn eq_path_segments( + &mut self, + left: &[PathSegment<'_>], + right: &[PathSegment<'_>], + ) -> bool { left.len() == right.len() && left.iter().zip(right).all(|(l, r)| self.eq_path_segment(l, r)) } @@ -273,24 +300,24 @@ impl<'a, 'tcx> SpanlessEq<'a, 'tcx> { (&TyKind::Array(ref lt, ref ll_id), &TyKind::Array(ref rt, ref rl_id)) => { let full_table = self.tables; - let mut celcx = constant_context(self.cx, self.cx.tcx.body_tables(ll_id.body)); - self.tables = self.cx.tcx.body_tables(ll_id.body); + let mut celcx = constant_context(self.cx, self.cx.tcx.typeck_body(ll_id.body)); + self.tables = self.cx.tcx.typeck_body(ll_id.body); let ll = celcx.expr(&self.cx.tcx.hir().body(ll_id.body).value); - let mut celcx = constant_context(self.cx, self.cx.tcx.body_tables(rl_id.body)); - self.tables = self.cx.tcx.body_tables(rl_id.body); + let mut celcx = constant_context(self.cx, self.cx.tcx.typeck_body(rl_id.body)); + self.tables = self.cx.tcx.typeck_body(rl_id.body); let rl = celcx.expr(&self.cx.tcx.hir().body(rl_id.body).value); let eq_ty = self.eq_ty(lt, rt); self.tables = full_table; eq_ty && ll == rl - }, + } (&TyKind::Ptr(ref l_mut), &TyKind::Ptr(ref r_mut)) => { l_mut.mutbl == r_mut.mutbl && self.eq_ty(&*l_mut.ty, &*r_mut.ty) - }, + } (&TyKind::Rptr(_, ref l_rmut), &TyKind::Rptr(_, ref r_rmut)) => { l_rmut.mutbl == r_rmut.mutbl && self.eq_ty(&*l_rmut.ty, &*r_rmut.ty) - }, + } (&TyKind::Path(ref l), &TyKind::Path(ref r)) => self.eq_qpath(l, r), (&TyKind::Tup(ref l), &TyKind::Tup(ref r)) => over(l, r, |l, r| self.eq_ty(l, r)), (&TyKind::Infer, &TyKind::Infer) => true, @@ -330,8 +357,7 @@ fn swap_binop<'a>( /// Checks if the two `Option`s are both `None` or some equal values as per /// `eq_fn`. pub fn both(l: &Option, r: &Option, mut eq_fn: impl FnMut(&X, &X) -> bool) -> bool { - l.as_ref() - .map_or_else(|| r.is_none(), |x| r.as_ref().map_or(false, |y| eq_fn(x, y))) + l.as_ref().map_or_else(|| r.is_none(), |x| r.as_ref().map_or(false, |y| eq_fn(x, y))) } /// Checks if two slices are equal as per `eq_fn`. @@ -347,17 +373,13 @@ pub fn over(left: &[X], right: &[X], mut eq_fn: impl FnMut(&X, &X) -> bool) - pub struct SpanlessHash<'a, 'tcx> { /// Context used to evaluate constant expressions. cx: &'a LateContext<'a, 'tcx>, - tables: &'a TypeckTables<'tcx>, + tables: &'a TypeckResults<'tcx>, s: StableHasher, } impl<'a, 'tcx> SpanlessHash<'a, 'tcx> { - pub fn new(cx: &'a LateContext<'a, 'tcx>, tables: &'a TypeckTables<'tcx>) -> Self { - Self { - cx, - tables, - s: StableHasher::new(), - } + pub fn new(cx: &'a LateContext<'a, 'tcx>, tables: &'a TypeckResults<'tcx>) -> Self { + Self { cx, tables, s: StableHasher::new() } } pub fn finish(self) -> u64 { @@ -405,31 +427,29 @@ impl<'a, 'tcx> SpanlessHash<'a, 'tcx> { .hash(&mut self.s); m.hash(&mut self.s); self.hash_expr(e); - }, + } ExprKind::Continue(i) => { if let Some(i) = i.label { self.hash_name(i.ident.name); } - }, + } ExprKind::Assign(ref l, ref r, _) => { self.hash_expr(l); self.hash_expr(r); - }, + } ExprKind::AssignOp(ref o, ref l, ref r) => { - o.node - .hash_stable(&mut self.cx.tcx.get_stable_hashing_context(), &mut self.s); + o.node.hash_stable(&mut self.cx.tcx.get_stable_hashing_context(), &mut self.s); self.hash_expr(l); self.hash_expr(r); - }, + } ExprKind::Block(ref b, _) => { self.hash_block(b); - }, + } ExprKind::Binary(op, ref l, ref r) => { - op.node - .hash_stable(&mut self.cx.tcx.get_stable_hashing_context(), &mut self.s); + op.node.hash_stable(&mut self.cx.tcx.get_stable_hashing_context(), &mut self.s); self.hash_expr(l); self.hash_expr(r); - }, + } ExprKind::Break(i, ref j) => { if let Some(i) = i.label { self.hash_name(i.ident.name); @@ -437,47 +457,43 @@ impl<'a, 'tcx> SpanlessHash<'a, 'tcx> { if let Some(ref j) = *j { self.hash_expr(&*j); } - }, + } ExprKind::Box(ref e) | ExprKind::DropTemps(ref e) | ExprKind::Yield(ref e, _) => { self.hash_expr(e); - }, + } ExprKind::Call(ref fun, args) => { self.hash_expr(fun); self.hash_exprs(args); - }, + } ExprKind::Cast(ref e, ref ty) | ExprKind::Type(ref e, ref ty) => { self.hash_expr(e); self.hash_ty(ty); - }, + } ExprKind::Closure(cap, _, eid, _, _) => { match cap { CaptureBy::Value => 0, CaptureBy::Ref => 1, } .hash(&mut self.s); - // closures inherit TypeckTables + // closures inherit TypeckResults self.hash_expr(&self.cx.tcx.hir().body(eid).value); - }, + } ExprKind::Field(ref e, ref f) => { self.hash_expr(e); self.hash_name(f.name); - }, + } ExprKind::Index(ref a, ref i) => { self.hash_expr(a); self.hash_expr(i); - }, + } ExprKind::InlineAsm(ref asm) => { for piece in asm.template { match piece { InlineAsmTemplatePiece::String(s) => s.hash(&mut self.s), - InlineAsmTemplatePiece::Placeholder { - operand_idx, - modifier, - span: _, - } => { + InlineAsmTemplatePiece::Placeholder { operand_idx, modifier, span: _ } => { operand_idx.hash(&mut self.s); modifier.hash(&mut self.s); - }, + } } } asm.options.hash(&mut self.s); @@ -486,46 +502,43 @@ impl<'a, 'tcx> SpanlessHash<'a, 'tcx> { InlineAsmOperand::In { reg, expr } => { reg.hash(&mut self.s); self.hash_expr(expr); - }, + } InlineAsmOperand::Out { reg, late, expr } => { reg.hash(&mut self.s); late.hash(&mut self.s); if let Some(expr) = expr { self.hash_expr(expr); } - }, + } InlineAsmOperand::InOut { reg, late, expr } => { reg.hash(&mut self.s); late.hash(&mut self.s); self.hash_expr(expr); - }, - InlineAsmOperand::SplitInOut { - reg, - late, - in_expr, - out_expr, - } => { + } + InlineAsmOperand::SplitInOut { reg, late, in_expr, out_expr } => { reg.hash(&mut self.s); late.hash(&mut self.s); self.hash_expr(in_expr); if let Some(out_expr) = out_expr { self.hash_expr(out_expr); } - }, - InlineAsmOperand::Const { expr } | InlineAsmOperand::Sym { expr } => self.hash_expr(expr), + } + InlineAsmOperand::Const { expr } | InlineAsmOperand::Sym { expr } => { + self.hash_expr(expr) + } } } - }, - ExprKind::LlvmInlineAsm(..) | ExprKind::Err => {}, + } + ExprKind::LlvmInlineAsm(..) | ExprKind::Err => {} ExprKind::Lit(ref l) => { l.node.hash(&mut self.s); - }, + } ExprKind::Loop(ref b, ref i, _) => { self.hash_block(b); if let Some(i) = *i { self.hash_name(i.ident.name); } - }, + } ExprKind::Match(ref e, arms, ref s) => { self.hash_expr(e); @@ -538,23 +551,23 @@ impl<'a, 'tcx> SpanlessHash<'a, 'tcx> { } s.hash(&mut self.s); - }, + } ExprKind::MethodCall(ref path, ref _tys, args, ref _fn_span) => { self.hash_name(path.ident.name); self.hash_exprs(args); - }, + } ExprKind::Repeat(ref e, ref l_id) => { self.hash_expr(e); self.hash_body(l_id.body); - }, + } ExprKind::Ret(ref e) => { if let Some(ref e) = *e { self.hash_expr(e); } - }, + } ExprKind::Path(ref qpath) => { self.hash_qpath(qpath); - }, + } ExprKind::Struct(ref path, fields, ref expr) => { self.hash_qpath(path); @@ -566,17 +579,17 @@ impl<'a, 'tcx> SpanlessHash<'a, 'tcx> { if let Some(ref e) = *expr { self.hash_expr(e); } - }, + } ExprKind::Tup(tup) => { self.hash_exprs(tup); - }, + } ExprKind::Array(v) => { self.hash_exprs(v); - }, + } ExprKind::Unary(lop, ref le) => { lop.hash_stable(&mut self.cx.tcx.get_stable_hashing_context(), &mut self.s); self.hash_expr(le); - }, + } } } @@ -594,10 +607,10 @@ impl<'a, 'tcx> SpanlessHash<'a, 'tcx> { match *p { QPath::Resolved(_, ref path) => { self.hash_path(path); - }, + } QPath::TypeRelative(_, ref path) => { self.hash_name(path.ident.name); - }, + } } // self.cx.tables.qpath_res(p, id).hash(&mut self.s); } @@ -617,11 +630,11 @@ impl<'a, 'tcx> SpanlessHash<'a, 'tcx> { if let Some(ref init) = local.init { self.hash_expr(init); } - }, - StmtKind::Item(..) => {}, + } + StmtKind::Item(..) => {} StmtKind::Expr(expr) | StmtKind::Semi(expr) => { self.hash_expr(expr); - }, + } } } @@ -629,7 +642,7 @@ impl<'a, 'tcx> SpanlessHash<'a, 'tcx> { match g { Guard::If(ref expr) => { self.hash_expr(expr); - }, + } } } @@ -640,11 +653,11 @@ impl<'a, 'tcx> SpanlessHash<'a, 'tcx> { match name { ParamName::Plain(ref ident) => { ident.name.hash(&mut self.s); - }, + } ParamName::Fresh(ref size) => { size.hash(&mut self.s); - }, - ParamName::Error => {}, + } + ParamName::Error => {} } } } @@ -658,20 +671,20 @@ impl<'a, 'tcx> SpanlessHash<'a, 'tcx> { match ty { TyKind::Slice(ty) => { self.hash_ty(ty); - }, + } TyKind::Array(ty, anon_const) => { self.hash_ty(ty); self.hash_body(anon_const.body); - }, + } TyKind::Ptr(mut_ty) => { self.hash_ty(&mut_ty.ty); mut_ty.mutbl.hash(&mut self.s); - }, + } TyKind::Rptr(lifetime, mut_ty) => { self.hash_lifetime(lifetime); self.hash_ty(&mut_ty.ty); mut_ty.mutbl.hash(&mut self.s); - }, + } TyKind::BareFn(bfn) => { bfn.unsafety.hash(&mut self.s); bfn.abi.hash(&mut self.s); @@ -681,18 +694,18 @@ impl<'a, 'tcx> SpanlessHash<'a, 'tcx> { match bfn.decl.output { FnRetTy::DefaultReturn(_) => { ().hash(&mut self.s); - }, + } FnRetTy::Return(ref ty) => { self.hash_ty(ty); - }, + } } bfn.decl.c_variadic.hash(&mut self.s); - }, + } TyKind::Tup(ty_list) => { for ty in *ty_list { self.hash_ty(ty); } - }, + } TyKind::Path(qpath) => match qpath { QPath::Resolved(ref maybe_ty, ref path) => { if let Some(ref ty) = maybe_ty { @@ -701,11 +714,11 @@ impl<'a, 'tcx> SpanlessHash<'a, 'tcx> { for segment in path.segments { segment.ident.name.hash(&mut self.s); } - }, + } QPath::TypeRelative(ref ty, ref segment) => { self.hash_ty(ty); segment.ident.name.hash(&mut self.s); - }, + } }, TyKind::OpaqueDef(_, arg_list) => { for arg in *arg_list { @@ -715,21 +728,21 @@ impl<'a, 'tcx> SpanlessHash<'a, 'tcx> { GenericArg::Const(ref ca) => self.hash_body(ca.value.body), } } - }, + } TyKind::TraitObject(_, lifetime) => { self.hash_lifetime(lifetime); - }, + } TyKind::Typeof(anon_const) => { self.hash_body(anon_const.body); - }, - TyKind::Err | TyKind::Infer | TyKind::Never => {}, + } + TyKind::Err | TyKind::Infer | TyKind::Never => {} } } pub fn hash_body(&mut self, body_id: BodyId) { - // swap out TypeckTables when hashing a body + // swap out TypeckResults when hashing a body let old_tables = self.tables; - self.tables = self.cx.tcx.body_tables(body_id); + self.tables = self.cx.tcx.typeck_body(body_id); self.hash_expr(&self.cx.tcx.hir().body(body_id).value); self.tables = old_tables; } diff --git a/src/tools/clippy/clippy_lints/src/utils/inspector.rs b/src/tools/clippy/clippy_lints/src/utils/inspector.rs index 3f5659c3d8c0f..ff42f24001989 100644 --- a/src/tools/clippy/clippy_lints/src/utils/inspector.rs +++ b/src/tools/clippy/clippy_lints/src/utils/inspector.rs @@ -114,7 +114,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for DeepCodeInspector { } match stmt.kind { hir::StmtKind::Local(ref local) => { - println!("local variable of type {}", cx.tables().node_type(local.hir_id)); + println!("local variable of type {}", cx.typeck_results().node_type(local.hir_id)); println!("pattern:"); print_pat(cx, &local.pat, 0); if let Some(ref e) = local.init { @@ -144,8 +144,8 @@ fn has_attr(sess: &Session, attrs: &[Attribute]) -> bool { fn print_expr(cx: &LateContext<'_, '_>, expr: &hir::Expr<'_>, indent: usize) { let ind = " ".repeat(indent); println!("{}+", ind); - println!("{}ty: {}", ind, cx.tables().expr_ty(expr)); - println!("{}adjustments: {:?}", ind, cx.tables().adjustments().get(expr.hir_id)); + println!("{}ty: {}", ind, cx.typeck_results().expr_ty(expr)); + println!("{}adjustments: {:?}", ind, cx.typeck_results().adjustments().get(expr.hir_id)); match expr.kind { hir::ExprKind::Box(ref e) => { println!("{}Box", ind); diff --git a/src/tools/clippy/clippy_lints/src/utils/internal_lints.rs b/src/tools/clippy/clippy_lints/src/utils/internal_lints.rs index 38468181d0261..ca5b11d8b526e 100644 --- a/src/tools/clippy/clippy_lints/src/utils/internal_lints.rs +++ b/src/tools/clippy/clippy_lints/src/utils/internal_lints.rs @@ -347,7 +347,7 @@ fn is_lint_ref_type<'tcx>(cx: &LateContext<'_, 'tcx>, ty: &Ty<'_>) -> bool { ) = ty.kind { if let TyKind::Path(ref path) = inner.kind { - if let Res::Def(DefKind::Struct, def_id) = cx.tables().qpath_res(path, inner.hir_id) { + if let Res::Def(DefKind::Struct, def_id) = cx.typeck_results().qpath_res(path, inner.hir_id) { return match_def_path(cx, def_id, &paths::LINT); } } @@ -405,7 +405,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CompilerLintFunctions { if let ExprKind::MethodCall(ref path, _, ref args, _) = expr.kind; let fn_name = path.ident; if let Some(sugg) = self.map.get(&*fn_name.as_str()); - let ty = walk_ptrs_ty(cx.tables().expr_ty(&args[0])); + let ty = walk_ptrs_ty(cx.typeck_results().expr_ty(&args[0])); if match_type(cx, ty, &paths::EARLY_CONTEXT) || match_type(cx, ty, &paths::LATE_CONTEXT); then { @@ -438,7 +438,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for OuterExpnDataPass { let args = arg_lists[1]; if args.len() == 1; let self_arg = &args[0]; - let self_ty = walk_ptrs_ty(cx.tables().expr_ty(self_arg)); + let self_ty = walk_ptrs_ty(cx.typeck_results().expr_ty(self_arg)); if match_type(cx, self_ty, &paths::SYNTAX_CONTEXT); then { span_lint_and_sugg( diff --git a/src/tools/clippy/clippy_lints/src/utils/mod.rs b/src/tools/clippy/clippy_lints/src/utils/mod.rs index 69ec4b7ad6d18..1b373ee4aaa26 100644 --- a/src/tools/clippy/clippy_lints/src/utils/mod.rs +++ b/src/tools/clippy/clippy_lints/src/utils/mod.rs @@ -36,8 +36,9 @@ use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX, LOCAL_CRATE}; use rustc_hir::intravisit::{NestedVisitorMap, Visitor}; use rustc_hir::Node; use rustc_hir::{ - def, Arm, Block, Body, Constness, Crate, Expr, ExprKind, FnDecl, HirId, ImplItem, ImplItemKind, Item, ItemKind, - MatchSource, Param, Pat, PatKind, Path, PathSegment, QPath, TraitItem, TraitItemKind, TraitRef, TyKind, Unsafety, + def, Arm, Block, Body, Constness, Crate, Expr, ExprKind, FnDecl, HirId, ImplItem, ImplItemKind, + Item, ItemKind, MatchSource, Param, Pat, PatKind, Path, PathSegment, QPath, TraitItem, + TraitItemKind, TraitRef, TyKind, Unsafety, }; use rustc_infer::infer::TyCtxtInferExt; use rustc_lint::{LateContext, Level, Lint, LintContext}; @@ -73,27 +74,14 @@ pub fn differing_macro_contexts(lhs: Span, rhs: Span) -> bool { pub fn in_constant(cx: &LateContext<'_, '_>, id: HirId) -> bool { let parent_id = cx.tcx.hir().get_parent_item(id); match cx.tcx.hir().get(parent_id) { - Node::Item(&Item { - kind: ItemKind::Const(..) | ItemKind::Static(..), - .. - }) - | Node::TraitItem(&TraitItem { - kind: TraitItemKind::Const(..), - .. - }) - | Node::ImplItem(&ImplItem { - kind: ImplItemKind::Const(..), - .. - }) + Node::Item(&Item { kind: ItemKind::Const(..) | ItemKind::Static(..), .. }) + | Node::TraitItem(&TraitItem { kind: TraitItemKind::Const(..), .. }) + | Node::ImplItem(&ImplItem { kind: ImplItemKind::Const(..), .. }) | Node::AnonConst(_) => true, - Node::Item(&Item { - kind: ItemKind::Fn(ref sig, ..), - .. - }) - | Node::ImplItem(&ImplItem { - kind: ImplItemKind::Fn(ref sig, _), - .. - }) => sig.header.constness == Constness::Const, + Node::Item(&Item { kind: ItemKind::Fn(ref sig, ..), .. }) + | Node::ImplItem(&ImplItem { kind: ImplItemKind::Fn(ref sig, _), .. }) => { + sig.header.constness == Constness::Const + } _ => false, } } @@ -102,11 +90,7 @@ pub fn in_constant(cx: &LateContext<'_, '_>, id: HirId) -> bool { #[must_use] pub fn in_macro(span: Span) -> bool { if span.from_expansion() { - if let ExpnKind::Desugaring(..) = span.ctxt().outer_expn_data().kind { - false - } else { - true - } + if let ExpnKind::Desugaring(..) = span.ctxt().outer_expn_data().kind { false } else { true } } else { false } @@ -151,13 +135,9 @@ pub fn is_type_diagnostic_item(cx: &LateContext<'_, '_>, ty: Ty<'_>, diag_item: /// Checks if the method call given in `expr` belongs to the given trait. pub fn match_trait_method(cx: &LateContext<'_, '_>, expr: &Expr<'_>, path: &[&str]) -> bool { - let def_id = cx.tables().type_dependent_def_id(expr.hir_id).unwrap(); + let def_id = cx.typeck_results().type_dependent_def_id(expr.hir_id).unwrap(); let trt_id = cx.tcx.trait_of_item(def_id); - if let Some(trt_id) = trt_id { - match_def_path(cx, trt_id, path) - } else { - false - } + if let Some(trt_id) = trt_id { match_def_path(cx, trt_id, path) } else { false } } /// Checks if an expression references a variable of the given name. @@ -172,7 +152,9 @@ pub fn match_var(expr: &Expr<'_>, var: Name) -> bool { pub fn last_path_segment<'tcx>(path: &QPath<'tcx>) -> &'tcx PathSegment<'tcx> { match *path { - QPath::Resolved(_, ref path) => path.segments.last().expect("A path must have at least one segment"), + QPath::Resolved(_, ref path) => { + path.segments.last().expect("A path must have at least one segment") + } QPath::TypeRelative(_, ref seg) => seg, } } @@ -204,7 +186,7 @@ pub fn match_qpath(path: &QPath<'_>, segments: &[&str]) -> bool { } } false - }, + } _ => false, }, } @@ -227,11 +209,7 @@ pub fn match_qpath(path: &QPath<'_>, segments: &[&str]) -> bool { /// } /// ``` pub fn match_path(path: &Path<'_>, segments: &[&str]) -> bool { - path.segments - .iter() - .rev() - .zip(segments.iter().rev()) - .all(|(a, b)| a.ident.name.as_str() == *b) + path.segments.iter().rev().zip(segments.iter().rev()).all(|(a, b)| a.ident.name.as_str() == *b) } /// Matches a `Path` against a slice of segment string literals, e.g. @@ -241,24 +219,15 @@ pub fn match_path(path: &Path<'_>, segments: &[&str]) -> bool { /// match_path_ast(path, &["std", "rt", "begin_unwind"]) /// ``` pub fn match_path_ast(path: &ast::Path, segments: &[&str]) -> bool { - path.segments - .iter() - .rev() - .zip(segments.iter().rev()) - .all(|(a, b)| a.ident.name.as_str() == *b) + path.segments.iter().rev().zip(segments.iter().rev()).all(|(a, b)| a.ident.name.as_str() == *b) } /// Gets the definition associated to a path. pub fn path_to_res(cx: &LateContext<'_, '_>, path: &[&str]) -> Option { let crates = cx.tcx.crates(); - let krate = crates - .iter() - .find(|&&krate| cx.tcx.crate_name(krate).as_str() == path[0]); + let krate = crates.iter().find(|&&krate| cx.tcx.crate_name(krate).as_str() == path[0]); if let Some(krate) = krate { - let krate = DefId { - krate: *krate, - index: CRATE_DEF_INDEX, - }; + let krate = DefId { krate: *krate, index: CRATE_DEF_INDEX }; let mut items = cx.tcx.item_children(krate); let mut path_it = path.iter().skip(1).peekable(); @@ -289,14 +258,12 @@ pub fn qpath_res(cx: &LateContext<'_, '_>, qpath: &hir::QPath<'_>, id: hir::HirI match qpath { hir::QPath::Resolved(_, path) => path.res, hir::QPath::TypeRelative(..) => { - if cx.tcx.has_typeck_tables(id.owner.to_def_id()) { - cx.tcx - .typeck_tables_of(id.owner.to_def_id().expect_local()) - .qpath_res(qpath, id) + if cx.tcx.has_typeck_results(id.owner.to_def_id()) { + cx.tcx.typeck(id.owner.to_def_id().expect_local()).qpath_res(qpath, id) } else { Res::Err } - }, + } } } @@ -347,7 +314,10 @@ pub fn implements_trait<'a, 'tcx>( /// } /// } /// ``` -pub fn trait_ref_of_method<'tcx>(cx: &LateContext<'_, 'tcx>, hir_id: HirId) -> Option<&'tcx TraitRef<'tcx>> { +pub fn trait_ref_of_method<'tcx>( + cx: &LateContext<'_, 'tcx>, + hir_id: HirId, +) -> Option<&'tcx TraitRef<'tcx>> { // Get the implemented trait for the current function let parent_impl = cx.tcx.hir().get_parent_item(hir_id); if_chain! { @@ -521,7 +491,11 @@ pub fn snippet_with_applicability<'a, T: LintContext>( /// Same as `snippet`, but should only be used when it's clear that the input span is /// not a macro argument. -pub fn snippet_with_macro_callsite<'a, T: LintContext>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> { +pub fn snippet_with_macro_callsite<'a, T: LintContext>( + cx: &T, + span: Span, + default: &'a str, +) -> Cow<'a, str> { snippet(cx, span.source_callsite(), default) } @@ -610,8 +584,7 @@ pub fn first_line_of_span(cx: &T, span: Span) -> Span { fn first_char_in_first_line(cx: &T, span: Span) -> Option { let line_span = line_span(cx, span); if let Some(snip) = snippet_opt(cx, line_span) { - snip.find(|c: char| !c.is_whitespace()) - .map(|pos| line_span.lo() + BytePos::from_usize(pos)) + snip.find(|c: char| !c.is_whitespace()).map(|pos| line_span.lo() + BytePos::from_usize(pos)) } else { None } @@ -680,7 +653,12 @@ fn trim_multiline(s: Cow<'_, str>, ignore_first: bool, indent: Option) -> trim_multiline_inner(s_tab, ignore_first, indent, ' ') } -fn trim_multiline_inner(s: Cow<'_, str>, ignore_first: bool, indent: Option, ch: char) -> Cow<'_, str> { +fn trim_multiline_inner( + s: Cow<'_, str>, + ignore_first: bool, + indent: Option, + ch: char, +) -> Cow<'_, str> { let mut x = s .lines() .skip(ignore_first as usize) @@ -701,13 +679,11 @@ fn trim_multiline_inner(s: Cow<'_, str>, ignore_first: bool, indent: Option>() .join("\n"), ) @@ -724,34 +700,30 @@ pub fn get_parent_expr<'c>(cx: &'c LateContext<'_, '_>, e: &Expr<'_>) -> Option< if hir_id == parent_id { return None; } - map.find(parent_id).and_then(|node| { - if let Node::Expr(parent) = node { - Some(parent) - } else { - None - } - }) + map.find(parent_id).and_then( + |node| { + if let Node::Expr(parent) = node { Some(parent) } else { None } + }, + ) } -pub fn get_enclosing_block<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, hir_id: HirId) -> Option<&'tcx Block<'tcx>> { +pub fn get_enclosing_block<'a, 'tcx>( + cx: &LateContext<'a, 'tcx>, + hir_id: HirId, +) -> Option<&'tcx Block<'tcx>> { let map = &cx.tcx.hir(); - let enclosing_node = map - .get_enclosing_scope(hir_id) - .and_then(|enclosing_id| map.find(enclosing_id)); + let enclosing_node = + map.get_enclosing_scope(hir_id).and_then(|enclosing_id| map.find(enclosing_id)); if let Some(node) = enclosing_node { match node { Node::Block(block) => Some(block), - Node::Item(&Item { - kind: ItemKind::Fn(_, _, eid), - .. - }) - | Node::ImplItem(&ImplItem { - kind: ImplItemKind::Fn(_, eid), - .. - }) => match cx.tcx.hir().body(eid).value.kind { - ExprKind::Block(ref block, _) => Some(block), - _ => None, - }, + Node::Item(&Item { kind: ItemKind::Fn(_, _, eid), .. }) + | Node::ImplItem(&ImplItem { kind: ImplItemKind::Fn(_, eid), .. }) => { + match cx.tcx.hir().body(eid).value.kind { + ExprKind::Block(ref block, _) => Some(block), + _ => None, + } + } _ => None, } } else { @@ -797,7 +769,7 @@ pub fn is_integer_const(cx: &LateContext<'_, '_>, e: &Expr<'_>, value: u128) -> let parent_item = map.get_parent_item(e.hir_id); if let Some((Constant::Int(v), _)) = map .maybe_body_owned_by(parent_item) - .and_then(|body_id| constant(cx, cx.tcx.body_tables(body_id), e)) + .and_then(|body_id| constant(cx, cx.tcx.typeck_body(body_id), e)) { value == v } else { @@ -824,7 +796,7 @@ pub fn is_integer_literal(expr: &Expr<'_>, value: u128) -> bool { /// See `rustc_middle::ty::adjustment::Adjustment` and `rustc_typeck::check::coercion` for more /// information on adjustments and coercions. pub fn is_adjusted(cx: &LateContext<'_, '_>, e: &Expr<'_>) -> bool { - cx.tables().adjustments().get(e.hir_id).is_some() + cx.typeck_results().adjustments().get(e.hir_id).is_some() } /// Returns the pre-expansion span if is this comes from an expansion of the @@ -898,7 +870,7 @@ pub fn is_copy<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool { pub fn is_ctor_or_promotable_const_function(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> bool { if let ExprKind::Call(ref fun, _) = expr.kind { if let ExprKind::Path(ref qp) = fun.kind { - let res = cx.tables().qpath_res(qp, fun.hir_id); + let res = cx.typeck_results().qpath_res(qp, fun.hir_id); return match res { def::Res::Def(DefKind::Variant | DefKind::Ctor(..), ..) => true, def::Res::Def(_, def_id) => cx.tcx.is_promotable_const_fn(def_id), @@ -914,12 +886,15 @@ pub fn is_ctor_or_promotable_const_function(cx: &LateContext<'_, '_>, expr: &Exp pub fn is_refutable(cx: &LateContext<'_, '_>, pat: &Pat<'_>) -> bool { fn is_enum_variant(cx: &LateContext<'_, '_>, qpath: &QPath<'_>, id: HirId) -> bool { matches!( - cx.tables().qpath_res(qpath, id), + cx.typeck_results().qpath_res(qpath, id), def::Res::Def(DefKind::Variant, ..) | Res::Def(DefKind::Ctor(def::CtorOf::Variant, _), _) ) } - fn are_refutable<'a, I: Iterator>>(cx: &LateContext<'_, '_>, mut i: I) -> bool { + fn are_refutable<'a, I: Iterator>>( + cx: &LateContext<'_, '_>, + mut i: I, + ) -> bool { i.any(|pat| is_refutable(cx, pat)) } @@ -932,27 +907,32 @@ pub fn is_refutable(cx: &LateContext<'_, '_>, pat: &Pat<'_>) -> bool { PatKind::Or(ref pats) => { // TODO: should be the honest check, that pats is exhaustive set are_refutable(cx, pats.iter().map(|pat| &**pat)) - }, + } PatKind::Tuple(ref pats, _) => are_refutable(cx, pats.iter().map(|pat| &**pat)), PatKind::Struct(ref qpath, ref fields, _) => { - is_enum_variant(cx, qpath, pat.hir_id) || are_refutable(cx, fields.iter().map(|field| &*field.pat)) - }, + is_enum_variant(cx, qpath, pat.hir_id) + || are_refutable(cx, fields.iter().map(|field| &*field.pat)) + } PatKind::TupleStruct(ref qpath, ref pats, _) => { - is_enum_variant(cx, qpath, pat.hir_id) || are_refutable(cx, pats.iter().map(|pat| &**pat)) - }, + is_enum_variant(cx, qpath, pat.hir_id) + || are_refutable(cx, pats.iter().map(|pat| &**pat)) + } PatKind::Slice(ref head, ref middle, ref tail) => { - match &cx.tables().node_type(pat.hir_id).kind { + match &cx.typeck_results().node_type(pat.hir_id).kind { ty::Slice(..) => { // [..] is the only irrefutable slice pattern. !head.is_empty() || middle.is_none() || !tail.is_empty() - }, - ty::Array(..) => are_refutable(cx, head.iter().chain(middle).chain(tail.iter()).map(|pat| &**pat)), + } + ty::Array(..) => are_refutable( + cx, + head.iter().chain(middle).chain(tail.iter()).map(|pat| &**pat), + ), _ => { // unreachable!() true - }, + } } - }, + } } } @@ -996,7 +976,10 @@ pub fn is_self_ty(slf: &hir::Ty<'_>) -> bool { false } -pub fn iter_input_pats<'tcx>(decl: &FnDecl<'_>, body: &'tcx Body<'_>) -> impl Iterator> { +pub fn iter_input_pats<'tcx>( + decl: &FnDecl<'_>, + body: &'tcx Body<'_>, +) -> impl Iterator> { (0..decl.inputs.len()).map(move |i| &body.params[i]) } @@ -1190,7 +1173,7 @@ pub fn match_function_call<'a, 'tcx>( if_chain! { if let ExprKind::Call(ref fun, ref args) = expr.kind; if let ExprKind::Path(ref qpath) = fun.kind; - if let Some(fun_def_id) = cx.tables().qpath_res(qpath, fun.hir_id).opt_def_id(); + if let Some(fun_def_id) = cx.typeck_results().qpath_res(qpath, fun.hir_id).opt_def_id(); if match_def_path(cx, fun_def_id, path); then { return Some(&args) @@ -1201,7 +1184,11 @@ pub fn match_function_call<'a, 'tcx>( /// Checks if `Ty` is normalizable. This function is useful /// to avoid crashes on `layout_of`. -pub fn is_normalizable<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, param_env: ty::ParamEnv<'tcx>, ty: Ty<'tcx>) -> bool { +pub fn is_normalizable<'a, 'tcx>( + cx: &LateContext<'a, 'tcx>, + param_env: ty::ParamEnv<'tcx>, + ty: Ty<'tcx>, +) -> bool { cx.tcx.infer_ctxt().enter(|infcx| { let cause = rustc_middle::traits::ObligationCause::dummy(); infcx.at(&cause, param_env).normalize(&ty).is_ok() @@ -1264,9 +1251,7 @@ pub fn parent_node_is_if_expr<'a, 'b>(expr: &Expr<'_>, cx: &LateContext<'a, 'b>) // Finds the attribute with the given name, if any pub fn attr_by_name<'a>(attrs: &'a [Attribute], name: &'_ str) -> Option<&'a Attribute> { - attrs - .iter() - .find(|attr| attr.ident().map_or(false, |ident| ident.as_str() == name)) + attrs.iter().find(|attr| attr.ident().map_or(false, |ident| ident.as_str() == name)) } // Finds the `#[must_use]` attribute, if any @@ -1286,18 +1271,22 @@ pub fn is_must_use_ty<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> boo // for the Array case we don't need to care for the len == 0 case // because we don't want to lint functions returning empty arrays is_must_use_ty(cx, *ty) - }, + } ty::Tuple(ref substs) => substs.types().any(|ty| is_must_use_ty(cx, ty)), ty::Opaque(ref def_id, _) => { for (predicate, _) in cx.tcx.predicates_of(*def_id).predicates { if let ty::PredicateKind::Trait(ref poly_trait_predicate, _) = predicate.kind() { - if must_use_attr(&cx.tcx.get_attrs(poly_trait_predicate.skip_binder().trait_ref.def_id)).is_some() { + if must_use_attr( + &cx.tcx.get_attrs(poly_trait_predicate.skip_binder().trait_ref.def_id), + ) + .is_some() + { return true; } } } false - }, + } ty::Dynamic(binder, _) => { for predicate in binder.skip_binder().iter() { if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate { @@ -1307,7 +1296,7 @@ pub fn is_must_use_ty<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, ty: Ty<'tcx>) -> boo } } false - }, + } _ => false, } } @@ -1317,22 +1306,18 @@ pub fn is_must_use_func_call(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> bool let did = match expr.kind { ExprKind::Call(ref path, _) => if_chain! { if let ExprKind::Path(ref qpath) = path.kind; - if let def::Res::Def(_, did) = cx.tables().qpath_res(qpath, path.hir_id); + if let def::Res::Def(_, did) = cx.typeck_results().qpath_res(qpath, path.hir_id); then { Some(did) } else { None } }, - ExprKind::MethodCall(_, _, _, _) => cx.tables().type_dependent_def_id(expr.hir_id), + ExprKind::MethodCall(_, _, _, _) => cx.typeck_results().type_dependent_def_id(expr.hir_id), _ => None, }; - if let Some(did) = did { - must_use_attr(&cx.tcx.get_attrs(did)).is_some() - } else { - false - } + if let Some(did) = did { must_use_attr(&cx.tcx.get_attrs(did)).is_some() } else { false } } pub fn is_no_std_crate(krate: &Crate<'_>) -> bool { @@ -1371,17 +1356,15 @@ pub fn is_trait_impl_item(cx: &LateContext<'_, '_>, hir_id: HirId) -> bool { /// ``` pub fn fn_has_unsatisfiable_preds(cx: &LateContext<'_, '_>, did: DefId) -> bool { use rustc_trait_selection::traits; - let predicates = - cx.tcx - .predicates_of(did) - .predicates - .iter() - .filter_map(|(p, _)| if p.is_global() { Some(*p) } else { None }); + let predicates = cx + .tcx + .predicates_of(did) + .predicates + .iter() + .filter_map(|(p, _)| if p.is_global() { Some(*p) } else { None }); !traits::normalize_and_test_predicates( cx.tcx, - traits::elaborate_predicates(cx.tcx, predicates) - .map(|o| o.predicate) - .collect::>(), + traits::elaborate_predicates(cx.tcx, predicates).map(|o| o.predicate).collect::>(), ) } @@ -1407,7 +1390,7 @@ macro_rules! unwrap_cargo_metadata { Err(err) => { span_lint($cx, $lint, DUMMY_SP, &format!("could not read cargo metadata: {}", err)); return; - }, + } } }}; } @@ -1473,7 +1456,17 @@ mod test { println!("result: {:?}", result); assert!(result.is_empty()); - let result = without_block_comments(vec!["", "/*", "", "*/", "#[crate_type = \"lib\"]", "/*", "", "*/", ""]); + let result = without_block_comments(vec![ + "", + "/*", + "", + "*/", + "#[crate_type = \"lib\"]", + "/*", + "", + "*/", + "", + ]); assert_eq!(result, vec!["", "#[crate_type = \"lib\"]", ""]); let result = without_block_comments(vec!["/* rust", "", "*/"]); @@ -1482,7 +1475,14 @@ mod test { let result = without_block_comments(vec!["/* one-line comment */"]); assert!(result.is_empty()); - let result = without_block_comments(vec!["/* nested", "/* multi-line", "comment", "*/", "test", "*/"]); + let result = without_block_comments(vec![ + "/* nested", + "/* multi-line", + "comment", + "*/", + "test", + "*/", + ]); assert!(result.is_empty()); let result = without_block_comments(vec!["/* nested /* inline /* comment */ test */ */"]); diff --git a/src/tools/clippy/clippy_lints/src/utils/usage.rs b/src/tools/clippy/clippy_lints/src/utils/usage.rs index d280fe4ab4e02..3bad26dbd3c4a 100644 --- a/src/tools/clippy/clippy_lints/src/utils/usage.rs +++ b/src/tools/clippy/clippy_lints/src/utils/usage.rs @@ -18,7 +18,7 @@ pub fn mutated_variables<'a, 'tcx>(expr: &'tcx Expr<'_>, cx: &'a LateContext<'a, }; let def_id = expr.hir_id.owner.to_def_id(); cx.tcx.infer_ctxt().enter(|infcx| { - ExprUseVisitor::new(&mut delegate, &infcx, def_id.expect_local(), cx.param_env, cx.tables()).walk_expr(expr); + ExprUseVisitor::new(&mut delegate, &infcx, def_id.expect_local(), cx.param_env, cx.typeck_results()).walk_expr(expr); }); if delegate.skip { diff --git a/src/tools/clippy/clippy_lints/src/vec.rs b/src/tools/clippy/clippy_lints/src/vec.rs index 080785b177d65..9aece84591a7b 100644 --- a/src/tools/clippy/clippy_lints/src/vec.rs +++ b/src/tools/clippy/clippy_lints/src/vec.rs @@ -37,7 +37,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UselessVec { fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) { // search for `&vec![_]` expressions where the adjusted type is `&[_]` if_chain! { - if let ty::Ref(_, ty, _) = cx.tables().expr_ty_adjusted(expr).kind; + if let ty::Ref(_, ty, _) = cx.typeck_results().expr_ty_adjusted(expr).kind; if let ty::Slice(..) = ty.kind; if let ExprKind::AddrOf(BorrowKind::Ref, _, ref addressee) = expr.kind; if let Some(vec_args) = higher::vec_macro(cx, addressee); @@ -50,7 +50,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UselessVec { if_chain! { if let Some((_, arg, _)) = higher::for_loop(expr); if let Some(vec_args) = higher::vec_macro(cx, arg); - if is_copy(cx, vec_type(cx.tables().expr_ty_adjusted(arg))); + if is_copy(cx, vec_type(cx.typeck_results().expr_ty_adjusted(arg))); then { // report the error around the `vec!` not inside `:` let span = arg.span @@ -66,11 +66,15 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UselessVec { } } -fn check_vec_macro<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, vec_args: &higher::VecArgs<'tcx>, span: Span) { +fn check_vec_macro<'a, 'tcx>( + cx: &LateContext<'a, 'tcx>, + vec_args: &higher::VecArgs<'tcx>, + span: Span, +) { let mut applicability = Applicability::MachineApplicable; let snippet = match *vec_args { higher::VecArgs::Repeat(elem, len) => { - if constant(cx, cx.tables(), len).is_some() { + if constant(cx, cx.typeck_results(), len).is_some() { format!( "&[{}; {}]", snippet_with_applicability(cx, elem.span, "elem", &mut applicability), @@ -79,7 +83,7 @@ fn check_vec_macro<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, vec_args: &higher::VecA } else { return; } - }, + } higher::VecArgs::Vec(args) => { if let Some(last) = args.iter().last() { let span = args[0].span.to(last.span); @@ -88,7 +92,7 @@ fn check_vec_macro<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, vec_args: &higher::VecA } else { "&[]".into() } - }, + } }; span_lint_and_sugg( diff --git a/src/tools/clippy/clippy_lints/src/vec_resize_to_zero.rs b/src/tools/clippy/clippy_lints/src/vec_resize_to_zero.rs index bb315e64e5de1..3de71de9e312b 100644 --- a/src/tools/clippy/clippy_lints/src/vec_resize_to_zero.rs +++ b/src/tools/clippy/clippy_lints/src/vec_resize_to_zero.rs @@ -32,7 +32,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for VecResizeToZero { fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) { if_chain! { if let hir::ExprKind::MethodCall(path_segment, _, ref args, _) = expr.kind; - if let Some(method_def_id) = cx.tables().type_dependent_def_id(expr.hir_id); + if let Some(method_def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id); if match_def_path(cx, method_def_id, &paths::VEC_RESIZE) && args.len() == 3; if let ExprKind::Lit(Spanned { node: LitKind::Int(0, _), .. }) = args[1].kind; if let ExprKind::Lit(Spanned { node: LitKind::Int(..), .. }) = args[2].kind; diff --git a/src/tools/clippy/clippy_lints/src/verbose_file_reads.rs b/src/tools/clippy/clippy_lints/src/verbose_file_reads.rs index 85f9208457448..f267732aca699 100644 --- a/src/tools/clippy/clippy_lints/src/verbose_file_reads.rs +++ b/src/tools/clippy/clippy_lints/src/verbose_file_reads.rs @@ -62,7 +62,7 @@ fn is_file_read_to_end<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'t if let ExprKind::MethodCall(method_name, _, exprs, _) = expr.kind; if method_name.ident.as_str() == "read_to_end"; if let ExprKind::Path(QPath::Resolved(None, _)) = &exprs[0].kind; - let ty = cx.tables().expr_ty(&exprs[0]); + let ty = cx.typeck_results().expr_ty(&exprs[0]); if match_type(cx, ty, &paths::FILE); then { return true @@ -76,7 +76,7 @@ fn is_file_read_to_string<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr if let ExprKind::MethodCall(method_name, _, exprs, _) = expr.kind; if method_name.ident.as_str() == "read_to_string"; if let ExprKind::Path(QPath::Resolved(None, _)) = &exprs[0].kind; - let ty = cx.tables().expr_ty(&exprs[0]); + let ty = cx.typeck_results().expr_ty(&exprs[0]); if match_type(cx, ty, &paths::FILE); then { return true diff --git a/src/tools/clippy/clippy_lints/src/zero_div_zero.rs b/src/tools/clippy/clippy_lints/src/zero_div_zero.rs index f0cf17c3b9549..df82493982a3f 100644 --- a/src/tools/clippy/clippy_lints/src/zero_div_zero.rs +++ b/src/tools/clippy/clippy_lints/src/zero_div_zero.rs @@ -36,8 +36,8 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ZeroDiv { // TODO - constant_simple does not fold many operations involving floats. // That's probably fine for this lint - it's pretty unlikely that someone would // do something like 0.0/(2.0 - 2.0), but it would be nice to warn on that case too. - if let Some(lhs_value) = constant_simple(cx, cx.tables(), left); - if let Some(rhs_value) = constant_simple(cx, cx.tables(), right); + if let Some(lhs_value) = constant_simple(cx, cx.typeck_results(), left); + if let Some(rhs_value) = constant_simple(cx, cx.typeck_results(), right); if Constant::F32(0.0) == lhs_value || Constant::F64(0.0) == lhs_value; if Constant::F32(0.0) == rhs_value || Constant::F64(0.0) == rhs_value; then { diff --git a/src/tools/clippy/doc/common_tools_writing_lints.md b/src/tools/clippy/doc/common_tools_writing_lints.md index d06e359bc7aa5..bbce0a2ae346b 100644 --- a/src/tools/clippy/doc/common_tools_writing_lints.md +++ b/src/tools/clippy/doc/common_tools_writing_lints.md @@ -31,7 +31,7 @@ Example of use: impl LateLintPass<'_, '_> for MyStructLint { fn check_expr(&mut self, cx: &LateContext<'_, '_>, expr: &Expr<'_>) { // Get type of `expr` - let ty = cx.tables().expr_ty(expr); + let ty = cx.typeck_results().expr_ty(expr); // Match its kind to enter its type match ty.kind { ty::Adt(adt_def, _) if adt_def.is_struct() => println!("Our `expr` is a struct!"), @@ -87,7 +87,7 @@ impl LateLintPass<'_, '_> for MyStructLint { } // 2. Using type context `TyCtxt` - let ty = cx.tables().expr_ty(expr); + let ty = cx.typeck_results().expr_ty(expr); if cx.tcx.lang_items() // we are looking for the `DefId` of `Drop` trait in lang items .drop_trait() diff --git a/src/tools/miri b/src/tools/miri index fd8101247749c..59619775ee44a 160000 --- a/src/tools/miri +++ b/src/tools/miri @@ -1 +1 @@ -Subproject commit fd8101247749c5be6850d5cb5096f01a1867e5ba +Subproject commit 59619775ee44a5e0c875efffc4ca55ae96fca7dc