diff --git a/rustfmt.toml b/rustfmt.toml index 0a90c89bffe8d..73f8cc1ff68c6 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -10,51 +10,6 @@ ignore = [ # (and generally rustfmt can move around comments in UI-testing incompatible ways) "src/test", - # tidy issues (line length, etc.) - # to be fixed shortly - "src/libcore/iter/adapters/mod.rs", - "src/libcore/iter/traits/iterator.rs", - "src/librustc/hir/lowering.rs", - "src/librustc/infer/error_reporting/nice_region_error/outlives_closure.rs", - "src/librustc/lint/mod.rs", - "src/librustc/middle/resolve_lifetime.rs", - "src/librustc/traits/mod.rs", - "src/librustc/ty/constness.rs", - "src/librustc/ty/context.rs", - "src/librustc/ty/wf.rs", - "src/librustc_codegen_llvm/back/write.rs", - "src/librustc_codegen_llvm/consts.rs", - "src/librustc_codegen_llvm/debuginfo/metadata.rs", - "src/librustc_codegen_ssa/base.rs", - "src/librustc_codegen_ssa/mir/place.rs", - "src/librustc_codegen_utils/symbol_names/v0.rs", - "src/librustc_errors/emitter.rs", - "src/librustc_mir/borrow_check/diagnostics/mutability_errors.rs", - "src/librustc_mir/borrow_check/type_check/mod.rs", - "src/librustc_mir/build/expr/as_rvalue.rs", - "src/librustc_mir/build/matches/mod.rs", - "src/librustc_mir/build/mod.rs", - "src/librustc_mir/const_eval.rs", - "src/librustc_mir/interpret/place.rs", - "src/librustc_mir/monomorphize/collector.rs", - "src/librustc_passes/ast_validation.rs", - "src/librustc_resolve/lib.rs", - "src/librustc_resolve/resolve_imports.rs", - "src/librustc_typeck/astconv.rs", - "src/librustc_typeck/check/_match.rs", - "src/librustc_typeck/check/coercion.rs", - "src/librustc_typeck/check/method/confirm.rs", - "src/librustc_typeck/check/mod.rs", - "src/librustc_typeck/check/wfcheck.rs", - "src/librustdoc/html/markdown/tests.rs", - "src/libstd/sys/sgx/abi/mem.rs", - "src/libstd/sys/unix/os.rs", - "src/libsyntax_expand/parse/lexer/tests.rs", - "src/libsyntax_expand/parse/tests.rs", - "src/libsyntax_ext/test.rs", - "src/tools/build-manifest/src/main.rs", - "src/librustc_feature", - # do not format submodules "src/doc/book", "src/doc/edition-guide", @@ -71,4 +26,7 @@ ignore = [ "src/tools/rls", "src/tools/rust-installer", "src/tools/rustfmt", + + # We do not format this file as it is externally sourced and auto-generated. + "src/libstd/sys/cloudabi/abi/cloudabi.rs", ] diff --git a/src/libcore/iter/adapters/mod.rs b/src/libcore/iter/adapters/mod.rs index 019a3290f01e1..6eb837ed0fed8 100644 --- a/src/libcore/iter/adapters/mod.rs +++ b/src/libcore/iter/adapters/mod.rs @@ -1,11 +1,11 @@ use crate::cmp; use crate::fmt; +use crate::intrinsics; use crate::ops::{Add, AddAssign, Try}; use crate::usize; -use crate::intrinsics; -use super::{Iterator, DoubleEndedIterator, ExactSizeIterator, FusedIterator, TrustedLen}; -use super::{LoopState, from_fn}; +use super::{from_fn, LoopState}; +use super::{DoubleEndedIterator, ExactSizeIterator, FusedIterator, Iterator, TrustedLen}; mod chain; mod flatten; @@ -14,8 +14,8 @@ mod zip; pub use self::chain::Chain; #[stable(feature = "rust1", since = "1.0.0")] pub use self::flatten::{FlatMap, Flatten}; -pub use self::zip::Zip; pub(crate) use self::zip::TrustedRandomAccess; +pub use self::zip::Zip; /// A double-ended iterator with the direction inverted. /// @@ -28,7 +28,7 @@ pub(crate) use self::zip::TrustedRandomAccess; #[must_use = "iterators are lazy and do nothing unless consumed"] #[stable(feature = "rust1", since = "1.0.0")] pub struct Rev { - iter: T + iter: T, } impl Rev { pub(super) fn new(iter: T) -> Rev { @@ -37,59 +37,85 @@ impl Rev { } #[stable(feature = "rust1", since = "1.0.0")] -impl Iterator for Rev where I: DoubleEndedIterator { +impl Iterator for Rev +where + I: DoubleEndedIterator, +{ type Item = ::Item; #[inline] - fn next(&mut self) -> Option<::Item> { self.iter.next_back() } + fn next(&mut self) -> Option<::Item> { + self.iter.next_back() + } #[inline] - fn size_hint(&self) -> (usize, Option) { self.iter.size_hint() } + fn size_hint(&self) -> (usize, Option) { + self.iter.size_hint() + } #[inline] - fn nth(&mut self, n: usize) -> Option<::Item> { self.iter.nth_back(n) } + fn nth(&mut self, n: usize) -> Option<::Item> { + self.iter.nth_back(n) + } - fn try_fold(&mut self, init: B, f: F) -> R where - Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try + fn try_fold(&mut self, init: B, f: F) -> R + where + Self: Sized, + F: FnMut(B, Self::Item) -> R, + R: Try, { self.iter.try_rfold(init, f) } fn fold(self, init: Acc, f: F) -> Acc - where F: FnMut(Acc, Self::Item) -> Acc, + where + F: FnMut(Acc, Self::Item) -> Acc, { self.iter.rfold(init, f) } #[inline] fn find

(&mut self, predicate: P) -> Option - where P: FnMut(&Self::Item) -> bool + where + P: FnMut(&Self::Item) -> bool, { self.iter.rfind(predicate) } } #[stable(feature = "rust1", since = "1.0.0")] -impl DoubleEndedIterator for Rev where I: DoubleEndedIterator { +impl DoubleEndedIterator for Rev +where + I: DoubleEndedIterator, +{ #[inline] - fn next_back(&mut self) -> Option<::Item> { self.iter.next() } + fn next_back(&mut self) -> Option<::Item> { + self.iter.next() + } #[inline] - fn nth_back(&mut self, n: usize) -> Option<::Item> { self.iter.nth(n) } + fn nth_back(&mut self, n: usize) -> Option<::Item> { + self.iter.nth(n) + } - fn try_rfold(&mut self, init: B, f: F) -> R where - Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try + fn try_rfold(&mut self, init: B, f: F) -> R + where + Self: Sized, + F: FnMut(B, Self::Item) -> R, + R: Try, { self.iter.try_fold(init, f) } fn rfold(self, init: Acc, f: F) -> Acc - where F: FnMut(Acc, Self::Item) -> Acc, + where + F: FnMut(Acc, Self::Item) -> Acc, { self.iter.fold(init, f) } fn rfind

(&mut self, predicate: P) -> Option - where P: FnMut(&Self::Item) -> bool + where + P: FnMut(&Self::Item) -> bool, { self.iter.find(predicate) } @@ -97,7 +123,8 @@ impl DoubleEndedIterator for Rev where I: DoubleEndedIterator { #[stable(feature = "rust1", since = "1.0.0")] impl ExactSizeIterator for Rev - where I: ExactSizeIterator + DoubleEndedIterator +where + I: ExactSizeIterator + DoubleEndedIterator, { fn len(&self) -> usize { self.iter.len() @@ -109,12 +136,10 @@ impl ExactSizeIterator for Rev } #[stable(feature = "fused", since = "1.26.0")] -impl FusedIterator for Rev - where I: FusedIterator + DoubleEndedIterator {} +impl FusedIterator for Rev where I: FusedIterator + DoubleEndedIterator {} #[unstable(feature = "trusted_len", issue = "37572")] -unsafe impl TrustedLen for Rev - where I: TrustedLen + DoubleEndedIterator {} +unsafe impl TrustedLen for Rev where I: TrustedLen + DoubleEndedIterator {} /// An iterator that copies the elements of an underlying iterator. /// @@ -136,21 +161,19 @@ impl Copied { } } -fn copy_fold( - mut f: impl FnMut(Acc, T) -> Acc, -) -> impl FnMut(Acc, &T) -> Acc { +fn copy_fold(mut f: impl FnMut(Acc, T) -> Acc) -> impl FnMut(Acc, &T) -> Acc { move |acc, &elt| f(acc, elt) } -fn copy_try_fold( - mut f: impl FnMut(Acc, T) -> R, -) -> impl FnMut(Acc, &T) -> R { +fn copy_try_fold(mut f: impl FnMut(Acc, T) -> R) -> impl FnMut(Acc, &T) -> R { move |acc, &elt| f(acc, elt) } #[stable(feature = "iter_copied", since = "1.36.0")] impl<'a, I, T: 'a> Iterator for Copied - where I: Iterator, T: Copy +where + I: Iterator, + T: Copy, { type Item = T; @@ -162,14 +185,18 @@ impl<'a, I, T: 'a> Iterator for Copied self.it.size_hint() } - fn try_fold(&mut self, init: B, f: F) -> R where - Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try + fn try_fold(&mut self, init: B, f: F) -> R + where + Self: Sized, + F: FnMut(B, Self::Item) -> R, + R: Try, { self.it.try_fold(init, copy_try_fold(f)) } fn fold(self, init: Acc, f: F) -> Acc - where F: FnMut(Acc, Self::Item) -> Acc, + where + F: FnMut(Acc, Self::Item) -> Acc, { self.it.fold(init, copy_fold(f)) } @@ -177,20 +204,26 @@ impl<'a, I, T: 'a> Iterator for Copied #[stable(feature = "iter_copied", since = "1.36.0")] impl<'a, I, T: 'a> DoubleEndedIterator for Copied - where I: DoubleEndedIterator, T: Copy +where + I: DoubleEndedIterator, + T: Copy, { fn next_back(&mut self) -> Option { self.it.next_back().copied() } - fn try_rfold(&mut self, init: B, f: F) -> R where - Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try + fn try_rfold(&mut self, init: B, f: F) -> R + where + Self: Sized, + F: FnMut(B, Self::Item) -> R, + R: Try, { self.it.try_rfold(init, copy_try_fold(f)) } fn rfold(self, init: Acc, f: F) -> Acc - where F: FnMut(Acc, Self::Item) -> Acc, + where + F: FnMut(Acc, Self::Item) -> Acc, { self.it.rfold(init, copy_fold(f)) } @@ -198,7 +231,9 @@ impl<'a, I, T: 'a> DoubleEndedIterator for Copied #[stable(feature = "iter_copied", since = "1.36.0")] impl<'a, I, T: 'a> ExactSizeIterator for Copied - where I: ExactSizeIterator, T: Copy +where + I: ExactSizeIterator, + T: Copy, { fn len(&self) -> usize { self.it.len() @@ -211,12 +246,17 @@ impl<'a, I, T: 'a> ExactSizeIterator for Copied #[stable(feature = "iter_copied", since = "1.36.0")] impl<'a, I, T: 'a> FusedIterator for Copied - where I: FusedIterator, T: Copy -{} +where + I: FusedIterator, + T: Copy, +{ +} #[doc(hidden)] unsafe impl<'a, I, T: 'a> TrustedRandomAccess for Copied - where I: TrustedRandomAccess, T: Copy +where + I: TrustedRandomAccess, + T: Copy, { unsafe fn get_unchecked(&mut self, i: usize) -> Self::Item { *self.it.get_unchecked(i) @@ -230,9 +270,11 @@ unsafe impl<'a, I, T: 'a> TrustedRandomAccess for Copied #[stable(feature = "iter_copied", since = "1.36.0")] unsafe impl<'a, I, T: 'a> TrustedLen for Copied - where I: TrustedLen, - T: Copy -{} +where + I: TrustedLen, + T: Copy, +{ +} /// An iterator that clones the elements of an underlying iterator. /// @@ -253,15 +295,15 @@ impl Cloned { } } -fn clone_try_fold( - mut f: impl FnMut(Acc, T) -> R, -) -> impl FnMut(Acc, &T) -> R { +fn clone_try_fold(mut f: impl FnMut(Acc, T) -> R) -> impl FnMut(Acc, &T) -> R { move |acc, elt| f(acc, elt.clone()) } #[stable(feature = "iter_cloned", since = "1.1.0")] impl<'a, I, T: 'a> Iterator for Cloned - where I: Iterator, T: Clone +where + I: Iterator, + T: Clone, { type Item = T; @@ -273,14 +315,18 @@ impl<'a, I, T: 'a> Iterator for Cloned self.it.size_hint() } - fn try_fold(&mut self, init: B, f: F) -> R where - Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try + fn try_fold(&mut self, init: B, f: F) -> R + where + Self: Sized, + F: FnMut(B, Self::Item) -> R, + R: Try, { self.it.try_fold(init, clone_try_fold(f)) } fn fold(self, init: Acc, f: F) -> Acc - where F: FnMut(Acc, Self::Item) -> Acc, + where + F: FnMut(Acc, Self::Item) -> Acc, { self.it.map(T::clone).fold(init, f) } @@ -288,20 +334,26 @@ impl<'a, I, T: 'a> Iterator for Cloned #[stable(feature = "iter_cloned", since = "1.1.0")] impl<'a, I, T: 'a> DoubleEndedIterator for Cloned - where I: DoubleEndedIterator, T: Clone +where + I: DoubleEndedIterator, + T: Clone, { fn next_back(&mut self) -> Option { self.it.next_back().cloned() } - fn try_rfold(&mut self, init: B, f: F) -> R where - Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try + fn try_rfold(&mut self, init: B, f: F) -> R + where + Self: Sized, + F: FnMut(B, Self::Item) -> R, + R: Try, { self.it.try_rfold(init, clone_try_fold(f)) } fn rfold(self, init: Acc, f: F) -> Acc - where F: FnMut(Acc, Self::Item) -> Acc, + where + F: FnMut(Acc, Self::Item) -> Acc, { self.it.map(T::clone).rfold(init, f) } @@ -309,7 +361,9 @@ impl<'a, I, T: 'a> DoubleEndedIterator for Cloned #[stable(feature = "iter_cloned", since = "1.1.0")] impl<'a, I, T: 'a> ExactSizeIterator for Cloned - where I: ExactSizeIterator, T: Clone +where + I: ExactSizeIterator, + T: Clone, { fn len(&self) -> usize { self.it.len() @@ -322,24 +376,33 @@ impl<'a, I, T: 'a> ExactSizeIterator for Cloned #[stable(feature = "fused", since = "1.26.0")] impl<'a, I, T: 'a> FusedIterator for Cloned - where I: FusedIterator, T: Clone -{} +where + I: FusedIterator, + T: Clone, +{ +} #[doc(hidden)] unsafe impl<'a, I, T: 'a> TrustedRandomAccess for Cloned - where I: TrustedRandomAccess, T: Clone +where + I: TrustedRandomAccess, + T: Clone, { default unsafe fn get_unchecked(&mut self, i: usize) -> Self::Item { self.it.get_unchecked(i).clone() } #[inline] - default fn may_have_side_effect() -> bool { true } + default fn may_have_side_effect() -> bool { + true + } } #[doc(hidden)] unsafe impl<'a, I, T: 'a> TrustedRandomAccess for Cloned - where I: TrustedRandomAccess, T: Copy +where + I: TrustedRandomAccess, + T: Copy, { unsafe fn get_unchecked(&mut self, i: usize) -> Self::Item { *self.it.get_unchecked(i) @@ -353,9 +416,11 @@ unsafe impl<'a, I, T: 'a> TrustedRandomAccess for Cloned #[unstable(feature = "trusted_len", issue = "37572")] unsafe impl<'a, I, T: 'a> TrustedLen for Cloned - where I: TrustedLen, - T: Clone -{} +where + I: TrustedLen, + T: Clone, +{ +} /// An iterator that repeats endlessly. /// @@ -378,14 +443,20 @@ impl Cycle { } #[stable(feature = "rust1", since = "1.0.0")] -impl Iterator for Cycle where I: Clone + Iterator { +impl Iterator for Cycle +where + I: Clone + Iterator, +{ type Item = ::Item; #[inline] fn next(&mut self) -> Option<::Item> { match self.iter.next() { - None => { self.iter = self.orig.clone(); self.iter.next() } - y => y + None => { + self.iter = self.orig.clone(); + self.iter.next() + } + y => y, } } @@ -395,7 +466,7 @@ impl Iterator for Cycle where I: Clone + Iterator { match self.orig.size_hint() { sz @ (0, Some(0)) => sz, (0, _) => (0, None), - _ => (usize::MAX, None) + _ => (usize::MAX, None), } } @@ -456,7 +527,10 @@ impl StepBy { } #[stable(feature = "iterator_step_by", since = "1.28.0")] -impl Iterator for StepBy where I: Iterator { +impl Iterator for StepBy +where + I: Iterator, +{ type Item = I::Item; #[inline] @@ -558,7 +632,10 @@ impl Iterator for StepBy where I: Iterator { } } -impl StepBy where I: ExactSizeIterator { +impl StepBy +where + I: ExactSizeIterator, +{ // The zero-based index starting from the end of the iterator of the // last element. Used in the `DoubleEndedIterator` implementation. fn next_back_index(&self) -> usize { @@ -572,7 +649,10 @@ impl StepBy where I: ExactSizeIterator { } #[stable(feature = "double_ended_step_by_iterator", since = "1.38.0")] -impl DoubleEndedIterator for StepBy where I: DoubleEndedIterator + ExactSizeIterator { +impl DoubleEndedIterator for StepBy +where + I: DoubleEndedIterator + ExactSizeIterator, +{ #[inline] fn next_back(&mut self) -> Option { self.iter.nth_back(self.next_back_index()) @@ -584,9 +664,7 @@ impl DoubleEndedIterator for StepBy where I: DoubleEndedIterator + ExactSi // is out of bounds because the length of `self.iter` does not exceed // `usize::MAX` (because `I: ExactSizeIterator`) and `nth_back` is // zero-indexed - let n = n - .saturating_mul(self.step + 1) - .saturating_add(self.next_back_index()); + let n = n.saturating_mul(self.step + 1).saturating_add(self.next_back_index()); self.iter.nth_back(n) } @@ -683,9 +761,7 @@ impl Map { #[stable(feature = "core_impl_debug", since = "1.9.0")] impl fmt::Debug for Map { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Map") - .field("iter", &self.iter) - .finish() + f.debug_struct("Map").field("iter", &self.iter).finish() } } @@ -704,7 +780,10 @@ fn map_try_fold<'a, T, B, Acc, R>( } #[stable(feature = "rust1", since = "1.0.0")] -impl Iterator for Map where F: FnMut(I::Item) -> B { +impl Iterator for Map +where + F: FnMut(I::Item) -> B, +{ type Item = B; #[inline] @@ -717,21 +796,26 @@ impl Iterator for Map where F: FnMut(I::Item) -> B { self.iter.size_hint() } - fn try_fold(&mut self, init: Acc, g: G) -> R where - Self: Sized, G: FnMut(Acc, Self::Item) -> R, R: Try + fn try_fold(&mut self, init: Acc, g: G) -> R + where + Self: Sized, + G: FnMut(Acc, Self::Item) -> R, + R: Try, { self.iter.try_fold(init, map_try_fold(&mut self.f, g)) } fn fold(self, init: Acc, g: G) -> Acc - where G: FnMut(Acc, Self::Item) -> Acc, + where + G: FnMut(Acc, Self::Item) -> Acc, { self.iter.fold(init, map_fold(self.f, g)) } } #[stable(feature = "rust1", since = "1.0.0")] -impl DoubleEndedIterator for Map where +impl DoubleEndedIterator for Map +where F: FnMut(I::Item) -> B, { #[inline] @@ -739,14 +823,18 @@ impl DoubleEndedIterator for Map where self.iter.next_back().map(&mut self.f) } - fn try_rfold(&mut self, init: Acc, g: G) -> R where - Self: Sized, G: FnMut(Acc, Self::Item) -> R, R: Try + fn try_rfold(&mut self, init: Acc, g: G) -> R + where + Self: Sized, + G: FnMut(Acc, Self::Item) -> R, + R: Try, { self.iter.try_rfold(init, map_try_fold(&mut self.f, g)) } fn rfold(self, init: Acc, g: G) -> Acc - where G: FnMut(Acc, Self::Item) -> Acc, + where + G: FnMut(Acc, Self::Item) -> Acc, { self.iter.rfold(init, map_fold(self.f, g)) } @@ -754,7 +842,8 @@ impl DoubleEndedIterator for Map where #[stable(feature = "rust1", since = "1.0.0")] impl ExactSizeIterator for Map - where F: FnMut(I::Item) -> B +where + F: FnMut(I::Item) -> B, { fn len(&self) -> usize { self.iter.len() @@ -766,24 +855,29 @@ impl ExactSizeIterator for Map } #[stable(feature = "fused", since = "1.26.0")] -impl FusedIterator for Map - where F: FnMut(I::Item) -> B {} +impl FusedIterator for Map where F: FnMut(I::Item) -> B {} #[unstable(feature = "trusted_len", issue = "37572")] unsafe impl TrustedLen for Map - where I: TrustedLen, - F: FnMut(I::Item) -> B {} +where + I: TrustedLen, + F: FnMut(I::Item) -> B, +{ +} #[doc(hidden)] unsafe impl TrustedRandomAccess for Map - where I: TrustedRandomAccess, - F: FnMut(I::Item) -> B, +where + I: TrustedRandomAccess, + F: FnMut(I::Item) -> B, { unsafe fn get_unchecked(&mut self, i: usize) -> Self::Item { (self.f)(self.iter.get_unchecked(i)) } #[inline] - fn may_have_side_effect() -> bool { true } + fn may_have_side_effect() -> bool { + true + } } /// An iterator that filters the elements of `iter` with `predicate`. @@ -809,9 +903,7 @@ impl Filter { #[stable(feature = "core_impl_debug", since = "1.9.0")] impl fmt::Debug for Filter { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Filter") - .field("iter", &self.iter) - .finish() + f.debug_struct("Filter").field("iter", &self.iter).finish() } } @@ -830,7 +922,10 @@ fn filter_try_fold<'a, T, Acc, R: Try>( } #[stable(feature = "rust1", since = "1.0.0")] -impl Iterator for Filter where P: FnMut(&I::Item) -> bool { +impl Iterator for Filter +where + P: FnMut(&I::Item) -> bool, +{ type Item = I::Item; #[inline] @@ -866,15 +961,19 @@ impl Iterator for Filter where P: FnMut(&I::Item) -> bool } #[inline] - fn try_fold(&mut self, init: Acc, fold: Fold) -> R where - Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try + fn try_fold(&mut self, init: Acc, fold: Fold) -> R + where + Self: Sized, + Fold: FnMut(Acc, Self::Item) -> R, + R: Try, { self.iter.try_fold(init, filter_try_fold(&mut self.predicate, fold)) } #[inline] fn fold(self, init: Acc, fold: Fold) -> Acc - where Fold: FnMut(Acc, Self::Item) -> Acc, + where + Fold: FnMut(Acc, Self::Item) -> Acc, { self.iter.fold(init, filter_fold(self.predicate, fold)) } @@ -882,7 +981,8 @@ impl Iterator for Filter where P: FnMut(&I::Item) -> bool #[stable(feature = "rust1", since = "1.0.0")] impl DoubleEndedIterator for Filter - where P: FnMut(&I::Item) -> bool, +where + P: FnMut(&I::Item) -> bool, { #[inline] fn next_back(&mut self) -> Option { @@ -890,23 +990,26 @@ impl DoubleEndedIterator for Filter } #[inline] - fn try_rfold(&mut self, init: Acc, fold: Fold) -> R where - Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try + fn try_rfold(&mut self, init: Acc, fold: Fold) -> R + where + Self: Sized, + Fold: FnMut(Acc, Self::Item) -> R, + R: Try, { self.iter.try_rfold(init, filter_try_fold(&mut self.predicate, fold)) } #[inline] fn rfold(self, init: Acc, fold: Fold) -> Acc - where Fold: FnMut(Acc, Self::Item) -> Acc, + where + Fold: FnMut(Acc, Self::Item) -> Acc, { self.iter.rfold(init, filter_fold(self.predicate, fold)) } } #[stable(feature = "fused", since = "1.26.0")] -impl FusedIterator for Filter - where P: FnMut(&I::Item) -> bool {} +impl FusedIterator for Filter where P: FnMut(&I::Item) -> bool {} /// An iterator that uses `f` to both filter and map elements from `iter`. /// @@ -931,9 +1034,7 @@ impl FilterMap { #[stable(feature = "core_impl_debug", since = "1.9.0")] impl fmt::Debug for FilterMap { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("FilterMap") - .field("iter", &self.iter) - .finish() + f.debug_struct("FilterMap").field("iter", &self.iter).finish() } } @@ -959,7 +1060,8 @@ fn filter_map_try_fold<'a, T, B, Acc, R: Try>( #[stable(feature = "rust1", since = "1.0.0")] impl Iterator for FilterMap - where F: FnMut(I::Item) -> Option, +where + F: FnMut(I::Item) -> Option, { type Item = B; @@ -975,15 +1077,19 @@ impl Iterator for FilterMap } #[inline] - fn try_fold(&mut self, init: Acc, fold: Fold) -> R where - Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try + fn try_fold(&mut self, init: Acc, fold: Fold) -> R + where + Self: Sized, + Fold: FnMut(Acc, Self::Item) -> R, + R: Try, { self.iter.try_fold(init, filter_map_try_fold(&mut self.f, fold)) } #[inline] fn fold(self, init: Acc, fold: Fold) -> Acc - where Fold: FnMut(Acc, Self::Item) -> Acc, + where + Fold: FnMut(Acc, Self::Item) -> Acc, { self.iter.fold(init, filter_map_fold(self.f, fold)) } @@ -991,13 +1097,14 @@ impl Iterator for FilterMap #[stable(feature = "rust1", since = "1.0.0")] impl DoubleEndedIterator for FilterMap - where F: FnMut(I::Item) -> Option, +where + F: FnMut(I::Item) -> Option, { #[inline] fn next_back(&mut self) -> Option { #[inline] fn find( - f: &mut impl FnMut(T) -> Option + f: &mut impl FnMut(T) -> Option, ) -> impl FnMut((), T) -> LoopState<(), B> + '_ { move |(), x| match f(x) { Some(x) => LoopState::Break(x), @@ -1009,23 +1116,26 @@ impl DoubleEndedIterator for FilterMap } #[inline] - fn try_rfold(&mut self, init: Acc, fold: Fold) -> R where - Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try + fn try_rfold(&mut self, init: Acc, fold: Fold) -> R + where + Self: Sized, + Fold: FnMut(Acc, Self::Item) -> R, + R: Try, { self.iter.try_rfold(init, filter_map_try_fold(&mut self.f, fold)) } #[inline] fn rfold(self, init: Acc, fold: Fold) -> Acc - where Fold: FnMut(Acc, Self::Item) -> Acc, + where + Fold: FnMut(Acc, Self::Item) -> Acc, { self.iter.rfold(init, filter_map_fold(self.f, fold)) } } #[stable(feature = "fused", since = "1.26.0")] -impl FusedIterator for FilterMap - where F: FnMut(I::Item) -> Option {} +impl FusedIterator for FilterMap where F: FnMut(I::Item) -> Option {} /// An iterator that yields the current count and the element during iteration. /// @@ -1048,7 +1158,10 @@ impl Enumerate { } #[stable(feature = "rust1", since = "1.0.0")] -impl Iterator for Enumerate where I: Iterator { +impl Iterator for Enumerate +where + I: Iterator, +{ type Item = (usize, ::Item); /// # Overflow Behavior @@ -1089,8 +1202,11 @@ impl Iterator for Enumerate where I: Iterator { } #[inline] - fn try_fold(&mut self, init: Acc, fold: Fold) -> R where - Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try + fn try_fold(&mut self, init: Acc, fold: Fold) -> R + where + Self: Sized, + Fold: FnMut(Acc, Self::Item) -> R, + R: Try, { #[inline] fn enumerate<'a, T, Acc, R>( @@ -1110,7 +1226,8 @@ impl Iterator for Enumerate where I: Iterator { #[inline] fn fold(self, init: Acc, fold: Fold) -> Acc - where Fold: FnMut(Acc, Self::Item) -> Acc, + where + Fold: FnMut(Acc, Self::Item) -> Acc, { #[inline] fn enumerate( @@ -1130,8 +1247,9 @@ impl Iterator for Enumerate where I: Iterator { } #[stable(feature = "rust1", since = "1.0.0")] -impl DoubleEndedIterator for Enumerate where - I: ExactSizeIterator + DoubleEndedIterator +impl DoubleEndedIterator for Enumerate +where + I: ExactSizeIterator + DoubleEndedIterator, { #[inline] fn next_back(&mut self) -> Option<(usize, ::Item)> { @@ -1152,8 +1270,11 @@ impl DoubleEndedIterator for Enumerate where } #[inline] - fn try_rfold(&mut self, init: Acc, fold: Fold) -> R where - Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try + fn try_rfold(&mut self, init: Acc, fold: Fold) -> R + where + Self: Sized, + Fold: FnMut(Acc, Self::Item) -> R, + R: Try, { // Can safely add and subtract the count, as `ExactSizeIterator` promises // that the number of elements fits into a `usize`. @@ -1173,7 +1294,8 @@ impl DoubleEndedIterator for Enumerate where #[inline] fn rfold(self, init: Acc, fold: Fold) -> Acc - where Fold: FnMut(Acc, Self::Item) -> Acc, + where + Fold: FnMut(Acc, Self::Item) -> Acc, { // Can safely add and subtract the count, as `ExactSizeIterator` promises // that the number of elements fits into a `usize`. @@ -1193,7 +1315,10 @@ impl DoubleEndedIterator for Enumerate where } #[stable(feature = "rust1", since = "1.0.0")] -impl ExactSizeIterator for Enumerate where I: ExactSizeIterator { +impl ExactSizeIterator for Enumerate +where + I: ExactSizeIterator, +{ fn len(&self) -> usize { self.iter.len() } @@ -1205,7 +1330,8 @@ impl ExactSizeIterator for Enumerate where I: ExactSizeIterator { #[doc(hidden)] unsafe impl TrustedRandomAccess for Enumerate - where I: TrustedRandomAccess +where + I: TrustedRandomAccess, { unsafe fn get_unchecked(&mut self, i: usize) -> (usize, I::Item) { (self.count + i, self.iter.get_unchecked(i)) @@ -1220,10 +1346,7 @@ unsafe impl TrustedRandomAccess for Enumerate impl FusedIterator for Enumerate where I: FusedIterator {} #[unstable(feature = "trusted_len", issue = "37572")] -unsafe impl TrustedLen for Enumerate - where I: TrustedLen, -{} - +unsafe impl TrustedLen for Enumerate where I: TrustedLen {} /// An iterator with a `peek()` that returns an optional reference to the next /// element. @@ -1310,8 +1433,11 @@ impl Iterator for Peekable { } #[inline] - fn try_fold(&mut self, init: B, mut f: F) -> R where - Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try + fn try_fold(&mut self, init: B, mut f: F) -> R + where + Self: Sized, + F: FnMut(B, Self::Item) -> R, + R: Try, { let acc = match self.peeked.take() { Some(None) => return Try::from_ok(init), @@ -1323,7 +1449,8 @@ impl Iterator for Peekable { #[inline] fn fold(self, init: Acc, mut fold: Fold) -> Acc - where Fold: FnMut(Acc, Self::Item) -> Acc, + where + Fold: FnMut(Acc, Self::Item) -> Acc, { let acc = match self.peeked { Some(None) => return init, @@ -1335,15 +1462,21 @@ impl Iterator for Peekable { } #[stable(feature = "double_ended_peek_iterator", since = "1.38.0")] -impl DoubleEndedIterator for Peekable where I: DoubleEndedIterator { +impl DoubleEndedIterator for Peekable +where + I: DoubleEndedIterator, +{ #[inline] fn next_back(&mut self) -> Option { self.iter.next_back().or_else(|| self.peeked.take().and_then(|x| x)) } #[inline] - fn try_rfold(&mut self, init: B, mut f: F) -> R where - Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try + fn try_rfold(&mut self, init: B, mut f: F) -> R + where + Self: Sized, + F: FnMut(B, Self::Item) -> R, + R: Try, { match self.peeked.take() { Some(None) => Try::from_ok(init), @@ -1360,7 +1493,8 @@ impl DoubleEndedIterator for Peekable where I: DoubleEndedIterator { #[inline] fn rfold(self, init: Acc, mut fold: Fold) -> Acc - where Fold: FnMut(Acc, Self::Item) -> Acc, + where + Fold: FnMut(Acc, Self::Item) -> Acc, { match self.peeked { Some(None) => init, @@ -1449,16 +1583,14 @@ impl SkipWhile { #[stable(feature = "core_impl_debug", since = "1.9.0")] impl fmt::Debug for SkipWhile { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("SkipWhile") - .field("iter", &self.iter) - .field("flag", &self.flag) - .finish() + f.debug_struct("SkipWhile").field("iter", &self.iter).field("flag", &self.flag).finish() } } #[stable(feature = "rust1", since = "1.0.0")] impl Iterator for SkipWhile - where P: FnMut(&I::Item) -> bool +where + P: FnMut(&I::Item) -> bool, { type Item = I::Item; @@ -1490,8 +1622,11 @@ impl Iterator for SkipWhile } #[inline] - fn try_fold(&mut self, mut init: Acc, mut fold: Fold) -> R where - Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try + fn try_fold(&mut self, mut init: Acc, mut fold: Fold) -> R + where + Self: Sized, + Fold: FnMut(Acc, Self::Item) -> R, + R: Try, { if !self.flag { match self.next() { @@ -1504,7 +1639,8 @@ impl Iterator for SkipWhile #[inline] fn fold(mut self, mut init: Acc, mut fold: Fold) -> Acc - where Fold: FnMut(Acc, Self::Item) -> Acc, + where + Fold: FnMut(Acc, Self::Item) -> Acc, { if !self.flag { match self.next() { @@ -1518,7 +1654,11 @@ impl Iterator for SkipWhile #[stable(feature = "fused", since = "1.26.0")] impl FusedIterator for SkipWhile - where I: FusedIterator, P: FnMut(&I::Item) -> bool {} +where + I: FusedIterator, + P: FnMut(&I::Item) -> bool, +{ +} /// An iterator that only accepts elements while `predicate` returns `true`. /// @@ -1544,16 +1684,14 @@ impl TakeWhile { #[stable(feature = "core_impl_debug", since = "1.9.0")] impl fmt::Debug for TakeWhile { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("TakeWhile") - .field("iter", &self.iter) - .field("flag", &self.flag) - .finish() + f.debug_struct("TakeWhile").field("iter", &self.iter).field("flag", &self.flag).finish() } } #[stable(feature = "rust1", since = "1.0.0")] impl Iterator for TakeWhile - where P: FnMut(&I::Item) -> bool +where + P: FnMut(&I::Item) -> bool, { type Item = I::Item; @@ -1583,8 +1721,11 @@ impl Iterator for TakeWhile } #[inline] - fn try_fold(&mut self, init: Acc, fold: Fold) -> R where - Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try + fn try_fold(&mut self, init: Acc, fold: Fold) -> R + where + Self: Sized, + Fold: FnMut(Acc, Self::Item) -> R, + R: Try, { fn check<'a, T, Acc, R: Try>( flag: &'a mut bool, @@ -1613,7 +1754,11 @@ impl Iterator for TakeWhile #[stable(feature = "fused", since = "1.26.0")] impl FusedIterator for TakeWhile - where I: FusedIterator, P: FnMut(&I::Item) -> bool {} +where + I: FusedIterator, + P: FnMut(&I::Item) -> bool, +{ +} /// An iterator that skips over `n` elements of `iter`. /// @@ -1627,7 +1772,7 @@ impl FusedIterator for TakeWhile #[stable(feature = "rust1", since = "1.0.0")] pub struct Skip { iter: I, - n: usize + n: usize, } impl Skip { pub(super) fn new(iter: I, n: usize) -> Skip { @@ -1636,7 +1781,10 @@ impl Skip { } #[stable(feature = "rust1", since = "1.0.0")] -impl Iterator for Skip where I: Iterator { +impl Iterator for Skip +where + I: Iterator, +{ type Item = ::Item; #[inline] @@ -1659,7 +1807,7 @@ impl Iterator for Skip where I: Iterator { let to_skip = self.n; self.n = 0; // nth(n) skips n+1 - if self.iter.nth(to_skip-1).is_none() { + if self.iter.nth(to_skip - 1).is_none() { return None; } self.iter.nth(n) @@ -1700,8 +1848,11 @@ impl Iterator for Skip where I: Iterator { } #[inline] - fn try_fold(&mut self, init: Acc, fold: Fold) -> R where - Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try + fn try_fold(&mut self, init: Acc, fold: Fold) -> R + where + Self: Sized, + Fold: FnMut(Acc, Self::Item) -> R, + R: Try, { let n = self.n; self.n = 0; @@ -1716,7 +1867,8 @@ impl Iterator for Skip where I: Iterator { #[inline] fn fold(mut self, init: Acc, fold: Fold) -> Acc - where Fold: FnMut(Acc, Self::Item) -> Acc, + where + Fold: FnMut(Acc, Self::Item) -> Acc, { if self.n > 0 { // nth(n) skips n+1 @@ -1732,13 +1884,12 @@ impl Iterator for Skip where I: Iterator { impl ExactSizeIterator for Skip where I: ExactSizeIterator {} #[stable(feature = "double_ended_skip_iterator", since = "1.9.0")] -impl DoubleEndedIterator for Skip where I: DoubleEndedIterator + ExactSizeIterator { +impl DoubleEndedIterator for Skip +where + I: DoubleEndedIterator + ExactSizeIterator, +{ fn next_back(&mut self) -> Option { - if self.len() > 0 { - self.iter.next_back() - } else { - None - } + if self.len() > 0 { self.iter.next_back() } else { None } } #[inline] @@ -1749,14 +1900,17 @@ impl DoubleEndedIterator for Skip where I: DoubleEndedIterator + ExactSize } else { if len > 0 { // consume the original iterator - self.iter.nth_back(len-1); + self.iter.nth_back(len - 1); } None } } - fn try_rfold(&mut self, init: Acc, fold: Fold) -> R where - Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try + fn try_rfold(&mut self, init: Acc, fold: Fold) -> R + where + Self: Sized, + Fold: FnMut(Acc, Self::Item) -> R, + R: Try, { fn check>( mut n: usize, @@ -1765,8 +1919,7 @@ impl DoubleEndedIterator for Skip where I: DoubleEndedIterator + ExactSize move |acc, x| { n -= 1; let r = fold(acc, x); - if n == 0 { LoopState::Break(r) } - else { LoopState::from_try(r) } + if n == 0 { LoopState::Break(r) } else { LoopState::from_try(r) } } } @@ -1794,7 +1947,7 @@ impl FusedIterator for Skip where I: FusedIterator {} #[stable(feature = "rust1", since = "1.0.0")] pub struct Take { pub(super) iter: I, - pub(super) n: usize + pub(super) n: usize, } impl Take { pub(super) fn new(iter: I, n: usize) -> Take { @@ -1803,7 +1956,10 @@ impl Take { } #[stable(feature = "rust1", since = "1.0.0")] -impl Iterator for Take where I: Iterator{ +impl Iterator for Take +where + I: Iterator, +{ type Item = ::Item; #[inline] @@ -1842,15 +1998,18 @@ impl Iterator for Take where I: Iterator{ let upper = match upper { Some(x) if x < self.n => Some(x), - _ => Some(self.n) + _ => Some(self.n), }; (lower, upper) } #[inline] - fn try_fold(&mut self, init: Acc, fold: Fold) -> R where - Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try + fn try_fold(&mut self, init: Acc, fold: Fold) -> R + where + Self: Sized, + Fold: FnMut(Acc, Self::Item) -> R, + R: Try, { fn check<'a, T, Acc, R: Try>( n: &'a mut usize, @@ -1859,8 +2018,7 @@ impl Iterator for Take where I: Iterator{ move |acc, x| { *n -= 1; let r = fold(acc, x); - if *n == 0 { LoopState::Break(r) } - else { LoopState::from_try(r) } + if *n == 0 { LoopState::Break(r) } else { LoopState::from_try(r) } } } @@ -1874,7 +2032,10 @@ impl Iterator for Take where I: Iterator{ } #[stable(feature = "double_ended_take_iterator", since = "1.38.0")] -impl DoubleEndedIterator for Take where I: DoubleEndedIterator + ExactSizeIterator { +impl DoubleEndedIterator for Take +where + I: DoubleEndedIterator + ExactSizeIterator, +{ #[inline] fn next_back(&mut self) -> Option { if self.n == 0 { @@ -1902,8 +2063,11 @@ impl DoubleEndedIterator for Take where I: DoubleEndedIterator + ExactSize } #[inline] - fn try_rfold(&mut self, init: Acc, fold: Fold) -> R where - Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try + fn try_rfold(&mut self, init: Acc, fold: Fold) -> R + where + Self: Sized, + Fold: FnMut(Acc, Self::Item) -> R, + R: Try, { if self.n == 0 { Try::from_ok(init) @@ -1951,15 +2115,13 @@ impl Scan { #[stable(feature = "core_impl_debug", since = "1.9.0")] impl fmt::Debug for Scan { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Scan") - .field("iter", &self.iter) - .field("state", &self.state) - .finish() + f.debug_struct("Scan").field("iter", &self.iter).field("state", &self.state).finish() } } #[stable(feature = "rust1", since = "1.0.0")] -impl Iterator for Scan where +impl Iterator for Scan +where I: Iterator, F: FnMut(&mut St, I::Item) -> Option, { @@ -1978,19 +2140,20 @@ impl Iterator for Scan where } #[inline] - fn try_fold(&mut self, init: Acc, fold: Fold) -> R where - Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try + fn try_fold(&mut self, init: Acc, fold: Fold) -> R + where + Self: Sized, + Fold: FnMut(Acc, Self::Item) -> R, + R: Try, { fn scan<'a, T, St, B, Acc, R: Try>( state: &'a mut St, f: &'a mut impl FnMut(&mut St, T) -> Option, mut fold: impl FnMut(Acc, B) -> R + 'a, ) -> impl FnMut(Acc, T) -> LoopState + 'a { - move |acc, x| { - match f(state, x) { - None => LoopState::Break(Try::from_ok(acc)), - Some(x) => LoopState::from_try(fold(acc, x)), - } + move |acc, x| match f(state, x) { + None => LoopState::Break(Try::from_ok(acc)), + Some(x) => LoopState::from_try(fold(acc, x)), } } @@ -2013,7 +2176,7 @@ impl Iterator for Scan where #[stable(feature = "rust1", since = "1.0.0")] pub struct Fuse { iter: I, - done: bool + done: bool, } impl Fuse { pub(super) fn new(iter: I) -> Fuse { @@ -2025,7 +2188,10 @@ impl Fuse { impl FusedIterator for Fuse where I: Iterator {} #[stable(feature = "rust1", since = "1.0.0")] -impl Iterator for Fuse where I: Iterator { +impl Iterator for Fuse +where + I: Iterator, +{ type Item = ::Item; #[inline] @@ -2052,34 +2218,25 @@ impl Iterator for Fuse where I: Iterator { #[inline] default fn last(self) -> Option { - if self.done { - None - } else { - self.iter.last() - } + if self.done { None } else { self.iter.last() } } #[inline] default fn count(self) -> usize { - if self.done { - 0 - } else { - self.iter.count() - } + if self.done { 0 } else { self.iter.count() } } #[inline] default fn size_hint(&self) -> (usize, Option) { - if self.done { - (0, Some(0)) - } else { - self.iter.size_hint() - } + if self.done { (0, Some(0)) } else { self.iter.size_hint() } } #[inline] - default fn try_fold(&mut self, init: Acc, fold: Fold) -> R where - Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try + default fn try_fold(&mut self, init: Acc, fold: Fold) -> R + where + Self: Sized, + Fold: FnMut(Acc, Self::Item) -> R, + R: Try, { if self.done { Try::from_ok(init) @@ -2092,18 +2249,18 @@ impl Iterator for Fuse where I: Iterator { #[inline] default fn fold(self, init: Acc, fold: Fold) -> Acc - where Fold: FnMut(Acc, Self::Item) -> Acc, + where + Fold: FnMut(Acc, Self::Item) -> Acc, { - if self.done { - init - } else { - self.iter.fold(init, fold) - } + if self.done { init } else { self.iter.fold(init, fold) } } } #[stable(feature = "rust1", since = "1.0.0")] -impl DoubleEndedIterator for Fuse where I: DoubleEndedIterator { +impl DoubleEndedIterator for Fuse +where + I: DoubleEndedIterator, +{ #[inline] default fn next_back(&mut self) -> Option<::Item> { if self.done { @@ -2127,8 +2284,11 @@ impl DoubleEndedIterator for Fuse where I: DoubleEndedIterator { } #[inline] - default fn try_rfold(&mut self, init: Acc, fold: Fold) -> R where - Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try + default fn try_rfold(&mut self, init: Acc, fold: Fold) -> R + where + Self: Sized, + Fold: FnMut(Acc, Self::Item) -> R, + R: Try, { if self.done { Try::from_ok(init) @@ -2141,18 +2301,16 @@ impl DoubleEndedIterator for Fuse where I: DoubleEndedIterator { #[inline] default fn rfold(self, init: Acc, fold: Fold) -> Acc - where Fold: FnMut(Acc, Self::Item) -> Acc, + where + Fold: FnMut(Acc, Self::Item) -> Acc, { - if self.done { - init - } else { - self.iter.rfold(init, fold) - } + if self.done { init } else { self.iter.rfold(init, fold) } } } unsafe impl TrustedRandomAccess for Fuse - where I: TrustedRandomAccess, +where + I: TrustedRandomAccess, { unsafe fn get_unchecked(&mut self, i: usize) -> I::Item { self.iter.get_unchecked(i) @@ -2164,7 +2322,10 @@ unsafe impl TrustedRandomAccess for Fuse } #[stable(feature = "fused", since = "1.26.0")] -impl Iterator for Fuse where I: FusedIterator { +impl Iterator for Fuse +where + I: FusedIterator, +{ #[inline] fn next(&mut self) -> Option<::Item> { self.iter.next() @@ -2191,15 +2352,19 @@ impl Iterator for Fuse where I: FusedIterator { } #[inline] - fn try_fold(&mut self, init: Acc, fold: Fold) -> R where - Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try + fn try_fold(&mut self, init: Acc, fold: Fold) -> R + where + Self: Sized, + Fold: FnMut(Acc, Self::Item) -> R, + R: Try, { self.iter.try_fold(init, fold) } #[inline] fn fold(self, init: Acc, fold: Fold) -> Acc - where Fold: FnMut(Acc, Self::Item) -> Acc, + where + Fold: FnMut(Acc, Self::Item) -> Acc, { self.iter.fold(init, fold) } @@ -2207,7 +2372,8 @@ impl Iterator for Fuse where I: FusedIterator { #[stable(feature = "fused", since = "1.26.0")] impl DoubleEndedIterator for Fuse - where I: DoubleEndedIterator + FusedIterator +where + I: DoubleEndedIterator + FusedIterator, { #[inline] fn next_back(&mut self) -> Option<::Item> { @@ -2220,23 +2386,29 @@ impl DoubleEndedIterator for Fuse } #[inline] - fn try_rfold(&mut self, init: Acc, fold: Fold) -> R where - Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try + fn try_rfold(&mut self, init: Acc, fold: Fold) -> R + where + Self: Sized, + Fold: FnMut(Acc, Self::Item) -> R, + R: Try, { self.iter.try_rfold(init, fold) } #[inline] fn rfold(self, init: Acc, fold: Fold) -> Acc - where Fold: FnMut(Acc, Self::Item) -> Acc, + where + Fold: FnMut(Acc, Self::Item) -> Acc, { self.iter.rfold(init, fold) } } - #[stable(feature = "rust1", since = "1.0.0")] -impl ExactSizeIterator for Fuse where I: ExactSizeIterator { +impl ExactSizeIterator for Fuse +where + I: ExactSizeIterator, +{ fn len(&self) -> usize { self.iter.len() } @@ -2270,13 +2442,14 @@ impl Inspect { #[stable(feature = "core_impl_debug", since = "1.9.0")] impl fmt::Debug for Inspect { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Inspect") - .field("iter", &self.iter) - .finish() + f.debug_struct("Inspect").field("iter", &self.iter).finish() } } -impl Inspect where F: FnMut(&I::Item) { +impl Inspect +where + F: FnMut(&I::Item), +{ #[inline] fn do_inspect(&mut self, elt: Option) -> Option { if let Some(ref a) = elt { @@ -2291,18 +2464,27 @@ fn inspect_fold( mut f: impl FnMut(&T), mut fold: impl FnMut(Acc, T) -> Acc, ) -> impl FnMut(Acc, T) -> Acc { - move |acc, item| { f(&item); fold(acc, item) } + move |acc, item| { + f(&item); + fold(acc, item) + } } fn inspect_try_fold<'a, T, Acc, R>( f: &'a mut impl FnMut(&T), mut fold: impl FnMut(Acc, T) -> R + 'a, ) -> impl FnMut(Acc, T) -> R + 'a { - move |acc, item| { f(&item); fold(acc, item) } + move |acc, item| { + f(&item); + fold(acc, item) + } } #[stable(feature = "rust1", since = "1.0.0")] -impl Iterator for Inspect where F: FnMut(&I::Item) { +impl Iterator for Inspect +where + F: FnMut(&I::Item), +{ type Item = I::Item; #[inline] @@ -2317,15 +2499,19 @@ impl Iterator for Inspect where F: FnMut(&I::Item) { } #[inline] - fn try_fold(&mut self, init: Acc, fold: Fold) -> R where - Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try + fn try_fold(&mut self, init: Acc, fold: Fold) -> R + where + Self: Sized, + Fold: FnMut(Acc, Self::Item) -> R, + R: Try, { self.iter.try_fold(init, inspect_try_fold(&mut self.f, fold)) } #[inline] fn fold(self, init: Acc, fold: Fold) -> Acc - where Fold: FnMut(Acc, Self::Item) -> Acc, + where + Fold: FnMut(Acc, Self::Item) -> Acc, { self.iter.fold(init, inspect_fold(self.f, fold)) } @@ -2333,7 +2519,8 @@ impl Iterator for Inspect where F: FnMut(&I::Item) { #[stable(feature = "rust1", since = "1.0.0")] impl DoubleEndedIterator for Inspect - where F: FnMut(&I::Item), +where + F: FnMut(&I::Item), { #[inline] fn next_back(&mut self) -> Option { @@ -2342,15 +2529,19 @@ impl DoubleEndedIterator for Inspect } #[inline] - fn try_rfold(&mut self, init: Acc, fold: Fold) -> R where - Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try + fn try_rfold(&mut self, init: Acc, fold: Fold) -> R + where + Self: Sized, + Fold: FnMut(Acc, Self::Item) -> R, + R: Try, { self.iter.try_rfold(init, inspect_try_fold(&mut self.f, fold)) } #[inline] fn rfold(self, init: Acc, fold: Fold) -> Acc - where Fold: FnMut(Acc, Self::Item) -> Acc, + where + Fold: FnMut(Acc, Self::Item) -> Acc, { self.iter.rfold(init, inspect_fold(self.f, fold)) } @@ -2358,7 +2549,8 @@ impl DoubleEndedIterator for Inspect #[stable(feature = "rust1", since = "1.0.0")] impl ExactSizeIterator for Inspect - where F: FnMut(&I::Item) +where + F: FnMut(&I::Item), { fn len(&self) -> usize { self.iter.len() @@ -2370,8 +2562,7 @@ impl ExactSizeIterator for Inspect } #[stable(feature = "fused", since = "1.26.0")] -impl FusedIterator for Inspect - where F: FnMut(&I::Item) {} +impl FusedIterator for Inspect where F: FnMut(&I::Item) {} /// An iterator adapter that produces output as long as the underlying /// iterator produces `Result::Ok` values. @@ -2392,16 +2583,14 @@ where for<'a> F: FnMut(ResultShunt<'a, I, E>) -> U, { let mut error = Ok(()); - let shunt = ResultShunt { - iter, - error: &mut error, - }; + let shunt = ResultShunt { iter, error: &mut error }; let value = f(shunt); error.map(|()| value) } impl Iterator for ResultShunt<'_, I, E> - where I: Iterator> +where + I: Iterator>, { type Item = T; diff --git a/src/libcore/iter/traits/iterator.rs b/src/libcore/iter/traits/iterator.rs index 61e8b07511a67..25be26491e327 100644 --- a/src/libcore/iter/traits/iterator.rs +++ b/src/libcore/iter/traits/iterator.rs @@ -1,13 +1,15 @@ +// ignore-tidy-filelength + use crate::cmp::{self, Ordering}; use crate::ops::{Add, Try}; use super::super::LoopState; -use super::super::{Chain, Cycle, Copied, Cloned, Enumerate, Filter, FilterMap, Fuse}; -use super::super::{Flatten, FlatMap}; -use super::super::{Inspect, Map, Peekable, Scan, Skip, SkipWhile, StepBy, Take, TakeWhile, Rev}; -use super::super::{Zip, Sum, Product, FromIterator}; +use super::super::{Chain, Cloned, Copied, Cycle, Enumerate, Filter, FilterMap, Fuse}; +use super::super::{FlatMap, Flatten}; +use super::super::{FromIterator, Product, Sum, Zip}; +use super::super::{Inspect, Map, Peekable, Rev, Scan, Skip, SkipWhile, StepBy, Take, TakeWhile}; -fn _assert_is_object_safe(_: &dyn Iterator) {} +fn _assert_is_object_safe(_: &dyn Iterator) {} /// An interface for dealing with iterators. /// @@ -20,71 +22,71 @@ fn _assert_is_object_safe(_: &dyn Iterator) {} #[stable(feature = "rust1", since = "1.0.0")] #[rustc_on_unimplemented( on( - _Self="[std::ops::Range; 1]", - label="if you meant to iterate between two values, remove the square brackets", - note="`[start..end]` is an array of one `Range`; you might have meant to have a `Range` \ - without the brackets: `start..end`" + _Self = "[std::ops::Range; 1]", + label = "if you meant to iterate between two values, remove the square brackets", + note = "`[start..end]` is an array of one `Range`; you might have meant to have a `Range` \ + without the brackets: `start..end`" ), on( - _Self="[std::ops::RangeFrom; 1]", - label="if you meant to iterate from a value onwards, remove the square brackets", - note="`[start..]` is an array of one `RangeFrom`; you might have meant to have a \ + _Self = "[std::ops::RangeFrom; 1]", + label = "if you meant to iterate from a value onwards, remove the square brackets", + note = "`[start..]` is an array of one `RangeFrom`; you might have meant to have a \ `RangeFrom` without the brackets: `start..`, keeping in mind that iterating over an \ unbounded iterator will run forever unless you `break` or `return` from within the \ loop" ), on( - _Self="[std::ops::RangeTo; 1]", - label="if you meant to iterate until a value, remove the square brackets and add a \ - starting value", - note="`[..end]` is an array of one `RangeTo`; you might have meant to have a bounded \ - `Range` without the brackets: `0..end`" + _Self = "[std::ops::RangeTo; 1]", + label = "if you meant to iterate until a value, remove the square brackets and add a \ + starting value", + note = "`[..end]` is an array of one `RangeTo`; you might have meant to have a bounded \ + `Range` without the brackets: `0..end`" ), on( - _Self="[std::ops::RangeInclusive; 1]", - label="if you meant to iterate between two values, remove the square brackets", - note="`[start..=end]` is an array of one `RangeInclusive`; you might have meant to have a \ + _Self = "[std::ops::RangeInclusive; 1]", + label = "if you meant to iterate between two values, remove the square brackets", + note = "`[start..=end]` is an array of one `RangeInclusive`; you might have meant to have a \ `RangeInclusive` without the brackets: `start..=end`" ), on( - _Self="[std::ops::RangeToInclusive; 1]", - label="if you meant to iterate until a value (including it), remove the square brackets \ - and add a starting value", - note="`[..=end]` is an array of one `RangeToInclusive`; you might have meant to have a \ - bounded `RangeInclusive` without the brackets: `0..=end`" + _Self = "[std::ops::RangeToInclusive; 1]", + label = "if you meant to iterate until a value (including it), remove the square brackets \ + and add a starting value", + note = "`[..=end]` is an array of one `RangeToInclusive`; you might have meant to have a \ + bounded `RangeInclusive` without the brackets: `0..=end`" ), on( - _Self="std::ops::RangeTo", - label="if you meant to iterate until a value, add a starting value", - note="`..end` is a `RangeTo`, which cannot be iterated on; you might have meant to have a \ + _Self = "std::ops::RangeTo", + label = "if you meant to iterate until a value, add a starting value", + note = "`..end` is a `RangeTo`, which cannot be iterated on; you might have meant to have a \ bounded `Range`: `0..end`" ), on( - _Self="std::ops::RangeToInclusive", - label="if you meant to iterate until a value (including it), add a starting value", - note="`..=end` is a `RangeToInclusive`, which cannot be iterated on; you might have meant \ + _Self = "std::ops::RangeToInclusive", + label = "if you meant to iterate until a value (including it), add a starting value", + note = "`..=end` is a `RangeToInclusive`, which cannot be iterated on; you might have meant \ to have a bounded `RangeInclusive`: `0..=end`" ), on( - _Self="&str", - label="`{Self}` is not an iterator; try calling `.chars()` or `.bytes()`" + _Self = "&str", + label = "`{Self}` is not an iterator; try calling `.chars()` or `.bytes()`" ), on( - _Self="std::string::String", - label="`{Self}` is not an iterator; try calling `.chars()` or `.bytes()`" + _Self = "std::string::String", + label = "`{Self}` is not an iterator; try calling `.chars()` or `.bytes()`" ), on( - _Self="[]", - label="borrow the array with `&` or call `.iter()` on it to iterate over it", - note="arrays are not iterators, but slices like the following are: `&[1, 2, 3]`" + _Self = "[]", + label = "borrow the array with `&` or call `.iter()` on it to iterate over it", + note = "arrays are not iterators, but slices like the following are: `&[1, 2, 3]`" ), on( - _Self="{integral}", - note="if you want to iterate between `start` until a value `end`, use the exclusive range \ + _Self = "{integral}", + note = "if you want to iterate between `start` until a value `end`, use the exclusive range \ syntax `start..end` or the inclusive range syntax `start..=end`" ), - label="`{Self}` is not an iterator", - message="`{Self}` is not an iterator" + label = "`{Self}` is not an iterator", + message = "`{Self}` is not an iterator" )] #[doc(spotlight)] #[must_use = "iterators are lazy and do nothing unless consumed"] @@ -197,7 +199,9 @@ pub trait Iterator { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - fn size_hint(&self) -> (usize, Option) { (0, None) } + fn size_hint(&self) -> (usize, Option) { + (0, None) + } /// Consumes the iterator, counting the number of iterations and returning it. /// @@ -236,7 +240,10 @@ pub trait Iterator { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - fn count(self) -> usize where Self: Sized { + fn count(self) -> usize + where + Self: Sized, + { #[inline] fn add1(count: usize, _: T) -> usize { // Might overflow. @@ -267,7 +274,10 @@ pub trait Iterator { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - fn last(self) -> Option where Self: Sized { + fn last(self) -> Option + where + Self: Sized, + { #[inline] fn some(_: Option, x: T) -> Option { Some(x) @@ -321,7 +331,9 @@ pub trait Iterator { #[stable(feature = "rust1", since = "1.0.0")] fn nth(&mut self, mut n: usize) -> Option { for x in self { - if n == 0 { return Some(x) } + if n == 0 { + return Some(x); + } n -= 1; } None @@ -373,7 +385,10 @@ pub trait Iterator { /// ``` #[inline] #[stable(feature = "iterator_step_by", since = "1.28.0")] - fn step_by(self, step: usize) -> StepBy where Self: Sized { + fn step_by(self, step: usize) -> StepBy + where + Self: Sized, + { StepBy::new(self, step) } @@ -443,8 +458,10 @@ pub trait Iterator { /// [`OsStr`]: ../../std/ffi/struct.OsStr.html #[inline] #[stable(feature = "rust1", since = "1.0.0")] - fn chain(self, other: U) -> Chain where - Self: Sized, U: IntoIterator, + fn chain(self, other: U) -> Chain + where + Self: Sized, + U: IntoIterator, { Chain::new(self, other.into_iter()) } @@ -521,8 +538,10 @@ pub trait Iterator { /// [`None`]: ../../std/option/enum.Option.html#variant.None #[inline] #[stable(feature = "rust1", since = "1.0.0")] - fn zip(self, other: U) -> Zip where - Self: Sized, U: IntoIterator + fn zip(self, other: U) -> Zip + where + Self: Sized, + U: IntoIterator, { Zip::new(self, other.into_iter()) } @@ -578,8 +597,10 @@ pub trait Iterator { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - fn map(self, f: F) -> Map where - Self: Sized, F: FnMut(Self::Item) -> B, + fn map(self, f: F) -> Map + where + Self: Sized, + F: FnMut(Self::Item) -> B, { Map::new(self, f) } @@ -621,8 +642,10 @@ pub trait Iterator { /// ``` #[inline] #[stable(feature = "iterator_for_each", since = "1.21.0")] - fn for_each(self, f: F) where - Self: Sized, F: FnMut(Self::Item), + fn for_each(self, f: F) + where + Self: Sized, + F: FnMut(Self::Item), { #[inline] fn call(mut f: impl FnMut(T)) -> impl FnMut((), T) { @@ -694,8 +717,10 @@ pub trait Iterator { /// of these layers. #[inline] #[stable(feature = "rust1", since = "1.0.0")] - fn filter

(self, predicate: P) -> Filter where - Self: Sized, P: FnMut(&Self::Item) -> bool, + fn filter

(self, predicate: P) -> Filter + where + Self: Sized, + P: FnMut(&Self::Item) -> bool, { Filter::new(self, predicate) } @@ -751,8 +776,10 @@ pub trait Iterator { /// [`None`]: ../../std/option/enum.Option.html#variant.None #[inline] #[stable(feature = "rust1", since = "1.0.0")] - fn filter_map(self, f: F) -> FilterMap where - Self: Sized, F: FnMut(Self::Item) -> Option, + fn filter_map(self, f: F) -> FilterMap + where + Self: Sized, + F: FnMut(Self::Item) -> Option, { FilterMap::new(self, f) } @@ -797,7 +824,10 @@ pub trait Iterator { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - fn enumerate(self) -> Enumerate where Self: Sized { + fn enumerate(self) -> Enumerate + where + Self: Sized, + { Enumerate::new(self) } @@ -843,7 +873,10 @@ pub trait Iterator { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - fn peekable(self) -> Peekable where Self: Sized { + fn peekable(self) -> Peekable + where + Self: Sized, + { Peekable::new(self) } @@ -904,8 +937,10 @@ pub trait Iterator { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - fn skip_while

(self, predicate: P) -> SkipWhile where - Self: Sized, P: FnMut(&Self::Item) -> bool, + fn skip_while

(self, predicate: P) -> SkipWhile + where + Self: Sized, + P: FnMut(&Self::Item) -> bool, { SkipWhile::new(self, predicate) } @@ -983,8 +1018,10 @@ pub trait Iterator { /// the iteration should stop, but wasn't placed back into the iterator. #[inline] #[stable(feature = "rust1", since = "1.0.0")] - fn take_while

(self, predicate: P) -> TakeWhile where - Self: Sized, P: FnMut(&Self::Item) -> bool, + fn take_while

(self, predicate: P) -> TakeWhile + where + Self: Sized, + P: FnMut(&Self::Item) -> bool, { TakeWhile::new(self, predicate) } @@ -1008,7 +1045,10 @@ pub trait Iterator { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - fn skip(self, n: usize) -> Skip where Self: Sized { + fn skip(self, n: usize) -> Skip + where + Self: Sized, + { Skip::new(self, n) } @@ -1040,7 +1080,10 @@ pub trait Iterator { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - fn take(self, n: usize) -> Take where Self: Sized, { + fn take(self, n: usize) -> Take + where + Self: Sized, + { Take::new(self, n) } @@ -1084,7 +1127,9 @@ pub trait Iterator { #[inline] #[stable(feature = "rust1", since = "1.0.0")] fn scan(self, initial_state: St, f: F) -> Scan - where Self: Sized, F: FnMut(&mut St, Self::Item) -> Option, + where + Self: Sized, + F: FnMut(&mut St, Self::Item) -> Option, { Scan::new(self, initial_state, f) } @@ -1122,7 +1167,10 @@ pub trait Iterator { #[inline] #[stable(feature = "rust1", since = "1.0.0")] fn flat_map(self, f: F) -> FlatMap - where Self: Sized, U: IntoIterator, F: FnMut(Self::Item) -> U, + where + Self: Sized, + U: IntoIterator, + F: FnMut(Self::Item) -> U, { FlatMap::new(self, f) } @@ -1191,7 +1239,10 @@ pub trait Iterator { #[inline] #[stable(feature = "iterator_flatten", since = "1.29.0")] fn flatten(self) -> Flatten - where Self: Sized, Self::Item: IntoIterator { + where + Self: Sized, + Self::Item: IntoIterator, + { Flatten::new(self) } @@ -1251,7 +1302,10 @@ pub trait Iterator { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - fn fuse(self) -> Fuse where Self: Sized { + fn fuse(self) -> Fuse + where + Self: Sized, + { Fuse::new(self) } @@ -1332,8 +1386,10 @@ pub trait Iterator { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - fn inspect(self, f: F) -> Inspect where - Self: Sized, F: FnMut(&Self::Item), + fn inspect(self, f: F) -> Inspect + where + Self: Sized, + F: FnMut(&Self::Item), { Inspect::new(self, f) } @@ -1375,7 +1431,12 @@ pub trait Iterator { /// assert_eq!(iter.next(), None); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - fn by_ref(&mut self) -> &mut Self where Self: Sized { self } + fn by_ref(&mut self) -> &mut Self + where + Self: Sized, + { + self + } /// Transforms an iterator into a collection. /// @@ -1490,7 +1551,10 @@ pub trait Iterator { #[inline] #[stable(feature = "rust1", since = "1.0.0")] #[must_use = "if you really need to exhaust the iterator, consider `.for_each(drop)` instead"] - fn collect>(self) -> B where Self: Sized { + fn collect>(self) -> B + where + Self: Sized, + { FromIterator::from_iter(self) } @@ -1520,10 +1584,11 @@ pub trait Iterator { /// assert_eq!(odd, vec![1, 3]); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - fn partition(self, f: F) -> (B, B) where + fn partition(self, f: F) -> (B, B) + where Self: Sized, B: Default + Extend, - F: FnMut(&Self::Item) -> bool + F: FnMut(&Self::Item) -> bool, { #[inline] fn extend<'a, T, B: Extend>( @@ -1597,9 +1662,7 @@ pub trait Iterator { } #[inline] - fn is_true( - predicate: &mut impl FnMut(&T) -> bool - ) -> impl FnMut(&&mut T) -> bool + '_ { + fn is_true(predicate: &mut impl FnMut(&T) -> bool) -> impl FnMut(&&mut T) -> bool + '_ { move |x| predicate(&**x) } @@ -1702,8 +1765,11 @@ pub trait Iterator { /// ``` #[inline] #[stable(feature = "iterator_try_fold", since = "1.27.0")] - fn try_fold(&mut self, init: B, mut f: F) -> R where - Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try + fn try_fold(&mut self, init: B, mut f: F) -> R + where + Self: Sized, + F: FnMut(B, Self::Item) -> R, + R: Try, { let mut accum = init; while let Some(x) = self.next() { @@ -1741,8 +1807,11 @@ pub trait Iterator { /// ``` #[inline] #[stable(feature = "iterator_try_fold", since = "1.27.0")] - fn try_for_each(&mut self, f: F) -> R where - Self: Sized, F: FnMut(Self::Item) -> R, R: Try + fn try_for_each(&mut self, f: F) -> R + where + Self: Sized, + F: FnMut(Self::Item) -> R, + R: Try, { #[inline] fn call(mut f: impl FnMut(T) -> R) -> impl FnMut((), T) -> R { @@ -1821,8 +1890,10 @@ pub trait Iterator { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - fn fold(mut self, init: B, f: F) -> B where - Self: Sized, F: FnMut(B, Self::Item) -> B, + fn fold(mut self, init: B, f: F) -> B + where + Self: Sized, + F: FnMut(B, Self::Item) -> B, { #[inline] fn ok(mut f: impl FnMut(B, T) -> B) -> impl FnMut(B, T) -> Result { @@ -1871,14 +1942,15 @@ pub trait Iterator { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - fn all(&mut self, f: F) -> bool where - Self: Sized, F: FnMut(Self::Item) -> bool + fn all(&mut self, f: F) -> bool + where + Self: Sized, + F: FnMut(Self::Item) -> bool, { #[inline] fn check(mut f: impl FnMut(T) -> bool) -> impl FnMut((), T) -> LoopState<(), ()> { move |(), x| { - if f(x) { LoopState::Continue(()) } - else { LoopState::Break(()) } + if f(x) { LoopState::Continue(()) } else { LoopState::Break(()) } } } self.try_fold((), check(f)) == LoopState::Continue(()) @@ -1923,15 +1995,15 @@ pub trait Iterator { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - fn any(&mut self, f: F) -> bool where + fn any(&mut self, f: F) -> bool + where Self: Sized, - F: FnMut(Self::Item) -> bool + F: FnMut(Self::Item) -> bool, { #[inline] fn check(mut f: impl FnMut(T) -> bool) -> impl FnMut((), T) -> LoopState<(), ()> { move |(), x| { - if f(x) { LoopState::Break(()) } - else { LoopState::Continue(()) } + if f(x) { LoopState::Break(()) } else { LoopState::Continue(()) } } } @@ -1982,17 +2054,17 @@ pub trait Iterator { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - fn find

(&mut self, predicate: P) -> Option where + fn find

(&mut self, predicate: P) -> Option + where Self: Sized, P: FnMut(&Self::Item) -> bool, { #[inline] fn check( - mut predicate: impl FnMut(&T) -> bool + mut predicate: impl FnMut(&T) -> bool, ) -> impl FnMut((), T) -> LoopState<(), T> { move |(), x| { - if predicate(&x) { LoopState::Break(x) } - else { LoopState::Continue(()) } + if predicate(&x) { LoopState::Break(x) } else { LoopState::Continue(()) } } } @@ -2016,7 +2088,8 @@ pub trait Iterator { /// ``` #[inline] #[stable(feature = "iterator_find_map", since = "1.30.0")] - fn find_map(&mut self, f: F) -> Option where + fn find_map(&mut self, f: F) -> Option + where Self: Sized, F: FnMut(Self::Item) -> Option, { @@ -2087,7 +2160,8 @@ pub trait Iterator { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - fn position

(&mut self, predicate: P) -> Option where + fn position

(&mut self, predicate: P) -> Option + where Self: Sized, P: FnMut(Self::Item) -> bool, { @@ -2097,8 +2171,7 @@ pub trait Iterator { ) -> impl FnMut(usize, T) -> LoopState { // The addition might panic on overflow move |i, x| { - if predicate(x) { LoopState::Break(i) } - else { LoopState::Continue(Add::add(i, 1)) } + if predicate(x) { LoopState::Break(i) } else { LoopState::Continue(Add::add(i, 1)) } } } @@ -2145,9 +2218,10 @@ pub trait Iterator { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - fn rposition

(&mut self, predicate: P) -> Option where + fn rposition

(&mut self, predicate: P) -> Option + where P: FnMut(Self::Item) -> bool, - Self: Sized + ExactSizeIterator + DoubleEndedIterator + Self: Sized + ExactSizeIterator + DoubleEndedIterator, { // No need for an overflow check here, because `ExactSizeIterator` // implies that the number of elements fits into a `usize`. @@ -2157,8 +2231,7 @@ pub trait Iterator { ) -> impl FnMut(usize, T) -> LoopState { move |i, x| { let i = i - 1; - if predicate(x) { LoopState::Break(i) } - else { LoopState::Continue(i) } + if predicate(x) { LoopState::Break(i) } else { LoopState::Continue(i) } } } @@ -2186,7 +2259,10 @@ pub trait Iterator { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - fn max(self) -> Option where Self: Sized, Self::Item: Ord + fn max(self) -> Option + where + Self: Sized, + Self::Item: Ord, { self.max_by(Ord::cmp) } @@ -2211,7 +2287,10 @@ pub trait Iterator { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - fn min(self) -> Option where Self: Sized, Self::Item: Ord + fn min(self) -> Option + where + Self: Sized, + Self::Item: Ord, { self.min_by(Ord::cmp) } @@ -2233,7 +2312,9 @@ pub trait Iterator { #[inline] #[stable(feature = "iter_cmp_by_key", since = "1.6.0")] fn max_by_key(self, f: F) -> Option - where Self: Sized, F: FnMut(&Self::Item) -> B, + where + Self: Sized, + F: FnMut(&Self::Item) -> B, { #[inline] fn key(mut f: impl FnMut(&T) -> B) -> impl FnMut(T) -> (B, T) { @@ -2266,7 +2347,9 @@ pub trait Iterator { #[inline] #[stable(feature = "iter_max_by", since = "1.15.0")] fn max_by(self, compare: F) -> Option - where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering, + where + Self: Sized, + F: FnMut(&Self::Item, &Self::Item) -> Ordering, { #[inline] fn fold(mut compare: impl FnMut(&T, &T) -> Ordering) -> impl FnMut(T, T) -> T { @@ -2293,7 +2376,9 @@ pub trait Iterator { #[inline] #[stable(feature = "iter_cmp_by_key", since = "1.6.0")] fn min_by_key(self, f: F) -> Option - where Self: Sized, F: FnMut(&Self::Item) -> B, + where + Self: Sized, + F: FnMut(&Self::Item) -> B, { #[inline] fn key(mut f: impl FnMut(&T) -> B) -> impl FnMut(T) -> (B, T) { @@ -2326,7 +2411,9 @@ pub trait Iterator { #[inline] #[stable(feature = "iter_min_by", since = "1.15.0")] fn min_by(self, compare: F) -> Option - where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering, + where + Self: Sized, + F: FnMut(&Self::Item, &Self::Item) -> Ordering, { #[inline] fn fold(mut compare: impl FnMut(&T, &T) -> Ordering) -> impl FnMut(T, T) -> T { @@ -2336,7 +2423,6 @@ pub trait Iterator { fold1(self, fold(compare)) } - /// Reverses an iterator's direction. /// /// Usually, iterators iterate from left to right. After using `rev()`, @@ -2362,7 +2448,10 @@ pub trait Iterator { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - fn rev(self) -> Rev where Self: Sized + DoubleEndedIterator { + fn rev(self) -> Rev + where + Self: Sized + DoubleEndedIterator, + { Rev::new(self) } @@ -2389,10 +2478,11 @@ pub trait Iterator { /// assert_eq!(right, [2, 4]); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - fn unzip(self) -> (FromA, FromB) where + fn unzip(self) -> (FromA, FromB) + where FromA: Default + Extend, FromB: Default + Extend, - Self: Sized + Iterator, + Self: Sized + Iterator, { fn extend<'a, A, B>( ts: &'a mut impl Extend, @@ -2434,7 +2524,9 @@ pub trait Iterator { /// ``` #[stable(feature = "iter_copied", since = "1.36.0")] fn copied<'a, T: 'a>(self) -> Copied - where Self: Sized + Iterator, T: Copy + where + Self: Sized + Iterator, + T: Copy, { Copied::new(self) } @@ -2463,7 +2555,9 @@ pub trait Iterator { /// ``` #[stable(feature = "rust1", since = "1.0.0")] fn cloned<'a, T: 'a>(self) -> Cloned - where Self: Sized + Iterator, T: Clone + where + Self: Sized + Iterator, + T: Clone, { Cloned::new(self) } @@ -2495,7 +2589,10 @@ pub trait Iterator { /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[inline] - fn cycle(self) -> Cycle where Self: Sized + Clone { + fn cycle(self) -> Cycle + where + Self: Sized + Clone, + { Cycle::new(self) } @@ -2523,8 +2620,9 @@ pub trait Iterator { /// ``` #[stable(feature = "iter_arith", since = "1.11.0")] fn sum(self) -> S - where Self: Sized, - S: Sum, + where + Self: Sized, + S: Sum, { Sum::sum(self) } @@ -2551,8 +2649,9 @@ pub trait Iterator { /// ``` #[stable(feature = "iter_arith", since = "1.11.0")] fn product

(self) -> P - where Self: Sized, - P: Product, + where + Self: Sized, + P: Product, { Product::product(self) } @@ -2609,11 +2708,13 @@ pub trait Iterator { loop { let x = match self.next() { - None => if other.next().is_none() { - return Ordering::Equal - } else { - return Ordering::Less - }, + None => { + if other.next().is_none() { + return Ordering::Equal; + } else { + return Ordering::Less; + } + } Some(val) => val, }; @@ -2692,11 +2793,13 @@ pub trait Iterator { loop { let x = match self.next() { - None => if other.next().is_none() { - return Some(Ordering::Equal) - } else { - return Some(Ordering::Less) - }, + None => { + if other.next().is_none() { + return Some(Ordering::Equal); + } else { + return Some(Ordering::Less); + } + } Some(val) => val, }; @@ -2782,7 +2885,8 @@ pub trait Iterator { /// assert_eq!([1].iter().ne([1, 2].iter()), true); /// ``` #[stable(feature = "iter_order", since = "1.5.0")] - fn ne(self, other: I) -> bool where + fn ne(self, other: I) -> bool + where I: IntoIterator, Self::Item: PartialEq, Self: Sized, @@ -2801,7 +2905,8 @@ pub trait Iterator { /// assert_eq!([1, 2].iter().lt([1].iter()), false); /// ``` #[stable(feature = "iter_order", since = "1.5.0")] - fn lt(self, other: I) -> bool where + fn lt(self, other: I) -> bool + where I: IntoIterator, Self::Item: PartialOrd, Self: Sized, @@ -2820,7 +2925,8 @@ pub trait Iterator { /// assert_eq!([1, 2].iter().le([1].iter()), false); /// ``` #[stable(feature = "iter_order", since = "1.5.0")] - fn le(self, other: I) -> bool where + fn le(self, other: I) -> bool + where I: IntoIterator, Self::Item: PartialOrd, Self: Sized, @@ -2842,7 +2948,8 @@ pub trait Iterator { /// assert_eq!([1, 2].iter().gt([1].iter()), true); /// ``` #[stable(feature = "iter_order", since = "1.5.0")] - fn gt(self, other: I) -> bool where + fn gt(self, other: I) -> bool + where I: IntoIterator, Self::Item: PartialOrd, Self: Sized, @@ -2861,7 +2968,8 @@ pub trait Iterator { /// assert_eq!([1, 2].iter().ge([1].iter()), true); /// ``` #[stable(feature = "iter_order", since = "1.5.0")] - fn ge(self, other: I) -> bool where + fn ge(self, other: I) -> bool + where I: IntoIterator, Self::Item: PartialOrd, Self: Sized, @@ -2925,7 +3033,7 @@ pub trait Iterator { fn is_sorted_by(mut self, mut compare: F) -> bool where Self: Sized, - F: FnMut(&Self::Item, &Self::Item) -> Option + F: FnMut(&Self::Item, &Self::Item) -> Option, { let mut last = match self.next() { Some(e) => e, @@ -2965,7 +3073,7 @@ pub trait Iterator { where Self: Sized, F: FnMut(Self::Item) -> K, - K: PartialOrd + K: PartialOrd, { self.map(f).is_sorted() } @@ -2974,9 +3082,9 @@ pub trait Iterator { /// Fold an iterator without having to provide an initial value. #[inline] fn fold1(mut it: I, f: F) -> Option - where - I: Iterator, - F: FnMut(I::Item, I::Item) -> I::Item, +where + I: Iterator, + F: FnMut(I::Item, I::Item) -> I::Item, { // start with the first element as our selection. This avoids // having to use `Option`s inside the loop, translating to a @@ -2988,8 +3096,12 @@ fn fold1(mut it: I, f: F) -> Option #[stable(feature = "rust1", since = "1.0.0")] impl Iterator for &mut I { type Item = I::Item; - fn next(&mut self) -> Option { (**self).next() } - fn size_hint(&self) -> (usize, Option) { (**self).size_hint() } + fn next(&mut self) -> Option { + (**self).next() + } + fn size_hint(&self) -> (usize, Option) { + (**self).size_hint() + } fn nth(&mut self, n: usize) -> Option { (**self).nth(n) } diff --git a/src/libcore/tests/pattern.rs b/src/libcore/tests/pattern.rs index 6ec61cc97c972..d4bec996d89a1 100644 --- a/src/libcore/tests/pattern.rs +++ b/src/libcore/tests/pattern.rs @@ -42,8 +42,6 @@ impl From> for Step { } } -// ignore-tidy-linelength - // FIXME(Manishearth) these tests focus on single-character searching (CharSearcher) // and on next()/next_match(), not next_reject(). This is because // the memchr changes make next_match() for single chars complex, but next_reject() diff --git a/src/librustc/hir/lowering.rs b/src/librustc/hir/lowering.rs index a702eb839845e..f6db451d57ead 100644 --- a/src/librustc/hir/lowering.rs +++ b/src/librustc/hir/lowering.rs @@ -37,39 +37,39 @@ mod item; use crate::arena::Arena; use crate::dep_graph::DepGraph; -use crate::hir::{self, ParamName}; -use crate::hir::HirVec; -use crate::hir::map::{DefKey, DefPathData, Definitions}; +use crate::hir::def::{DefKind, Namespace, PartialRes, PerNS, Res}; use crate::hir::def_id::{DefId, DefIndex, CRATE_DEF_INDEX}; -use crate::hir::def::{Namespace, Res, DefKind, PartialRes, PerNS}; -use crate::hir::{GenericArg, ConstArg}; +use crate::hir::map::{DefKey, DefPathData, Definitions}; use crate::hir::ptr::P; +use crate::hir::HirVec; +use crate::hir::{self, ParamName}; +use crate::hir::{ConstArg, GenericArg}; use crate::lint; use crate::lint::builtin::{self, ELIDED_LIFETIMES_IN_PATHS}; use crate::middle::cstore::CrateStore; -use crate::session::Session; use crate::session::config::nightly_options; +use crate::session::Session; use crate::util::common::FN_OUTPUT_NAME; use crate::util::nodemap::{DefIdMap, NodeMap}; use errors::Applicability; use rustc_data_structures::fx::FxHashSet; -use rustc_index::vec::IndexVec; use rustc_data_structures::sync::Lrc; +use rustc_index::vec::IndexVec; +use smallvec::SmallVec; use std::collections::BTreeMap; use std::mem; -use smallvec::SmallVec; -use syntax::attr; use syntax::ast; -use syntax::ptr::P as AstP; use syntax::ast::*; +use syntax::attr; use syntax::errors; use syntax::print::pprust; -use syntax::token::{self, Nonterminal, Token}; -use syntax::tokenstream::{TokenStream, TokenTree}; +use syntax::ptr::P as AstP; use syntax::sess::ParseSess; -use syntax::source_map::{respan, ExpnData, ExpnKind, DesugaringKind, Spanned}; +use syntax::source_map::{respan, DesugaringKind, ExpnData, ExpnKind, Spanned}; use syntax::symbol::{kw, sym, Symbol}; +use syntax::token::{self, Nonterminal, Token}; +use syntax::tokenstream::{TokenStream, TokenTree}; use syntax::visit::{self, Visitor}; use syntax_pos::hygiene::ExpnId; use syntax_pos::Span; @@ -291,7 +291,8 @@ pub fn lower_crate<'a, 'hir>( in_scope_lifetimes: Vec::new(), allow_try_trait: Some([sym::try_trait][..].into()), allow_gen_future: Some([sym::gen_future][..].into()), - }.lower_crate(krate) + } + .lower_crate(krate) } #[derive(Copy, Clone, PartialEq)] @@ -359,26 +360,22 @@ enum AnonymousLifetimeMode { PassThrough, } -struct ImplTraitTypeIdVisitor<'a> { ids: &'a mut SmallVec<[NodeId; 1]> } +struct ImplTraitTypeIdVisitor<'a> { + ids: &'a mut SmallVec<[NodeId; 1]>, +} impl<'a, 'b> Visitor<'a> for ImplTraitTypeIdVisitor<'b> { fn visit_ty(&mut self, ty: &'a Ty) { match ty.kind { - | TyKind::Typeof(_) - | TyKind::BareFn(_) - => return, + TyKind::Typeof(_) | TyKind::BareFn(_) => return, TyKind::ImplTrait(id, _) => self.ids.push(id), - _ => {}, + _ => {} } visit::walk_ty(self, ty); } - fn visit_path_segment( - &mut self, - path_span: Span, - path_segment: &'v PathSegment, - ) { + fn visit_path_segment(&mut self, path_span: Span, path_segment: &'v PathSegment) { if let Some(ref p) = path_segment.args { if let GenericArgs::Parenthesized(_) = **p { return; @@ -401,11 +398,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { } impl MiscCollector<'_, '_, '_> { - fn allocate_use_tree_hir_id_counters( - &mut self, - tree: &UseTree, - owner: DefIndex, - ) { + fn allocate_use_tree_hir_id_counters(&mut self, tree: &UseTree, owner: DefIndex) { match tree.kind { UseTreeKind::Simple(_, id1, id2) => { for &id in &[id1, id2] { @@ -488,13 +481,11 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { match item.kind { AssocItemKind::Fn(_, None) => { // Ignore patterns in trait methods without bodies - self.with_hir_id_owner(None, |this| { - visit::walk_trait_item(this, item) - }); + self.with_hir_id_owner(None, |this| visit::walk_trait_item(this, item)); } _ => self.with_hir_id_owner(Some(item.id), |this| { visit::walk_trait_item(this, item); - }) + }), } } @@ -507,20 +498,14 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { fn visit_foreign_item(&mut self, i: &'tcx ForeignItem) { // Ignore patterns in foreign items - self.with_hir_id_owner(None, |this| { - visit::walk_foreign_item(this, i) - }); + self.with_hir_id_owner(None, |this| visit::walk_foreign_item(this, i)); } fn visit_ty(&mut self, t: &'tcx Ty) { match t.kind { // Mirrors the case in visit::walk_ty TyKind::BareFn(ref f) => { - walk_list!( - self, - visit_generic_param, - &f.generic_params - ); + walk_list!(self, visit_generic_param, &f.generic_params); // Mirrors visit::walk_fn_decl for parameter in &f.decl.inputs { // We don't lower the ids of argument patterns @@ -546,9 +531,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let attrs = self.arena.alloc_from_iter(self.lower_attrs(&c.attrs).into_iter()); let body_ids = body_ids(&self.bodies); - self.resolver - .definitions() - .init_node_id_to_hir_id_mapping(self.node_id_to_hir_id); + self.resolver.definitions().init_node_id_to_hir_id_mapping(self.node_id_to_hir_id); hir::Crate { module, @@ -614,7 +597,8 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { where F: FnOnce(&mut Self) -> T, { - let counter = self.item_local_id_counters + let counter = self + .item_local_id_counters .insert(owner, HIR_ID_COUNTER_LOCKED) .unwrap_or_else(|| panic!("no `item_local_id_counters` entry for {:?}", owner)); let def_index = self.resolver.definitions().opt_def_index(owner).unwrap(); @@ -625,9 +609,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { debug_assert!(def_index == new_def_index); debug_assert!(new_counter >= counter); - let prev = self.item_local_id_counters - .insert(owner, new_counter) - .unwrap(); + let prev = self.item_local_id_counters.insert(owner, new_counter).unwrap(); debug_assert!(prev == HIR_ID_COUNTER_LOCKED); ret } @@ -644,10 +626,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { this.current_hir_id_owner.last_mut().unwrap(); let local_id = *local_id_counter; *local_id_counter += 1; - hir::HirId { - owner: def_index, - local_id: hir::ItemLocalId::from_u32(local_id), - } + hir::HirId { owner: def_index, local_id: hir::ItemLocalId::from_u32(local_id) } }) } @@ -665,17 +644,12 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { debug_assert!(local_id != HIR_ID_COUNTER_LOCKED); *local_id_counter += 1; - let def_index = this - .resolver - .definitions() - .opt_def_index(owner) - .expect("you forgot to call `create_def_with_parent` or are lowering node-IDs \ - that do not belong to the current owner"); - - hir::HirId { - owner: def_index, - local_id: hir::ItemLocalId::from_u32(local_id), - } + let def_index = this.resolver.definitions().opt_def_index(owner).expect( + "you forgot to call `create_def_with_parent` or are lowering node-IDs \ + that do not belong to the current owner", + ); + + hir::HirId { owner: def_index, local_id: hir::ItemLocalId::from_u32(local_id) } }) } @@ -736,8 +710,10 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { self.anonymous_lifetime_mode = anonymous_lifetime_mode; let result = op(self); self.anonymous_lifetime_mode = old_anonymous_lifetime_mode; - debug!("with_anonymous_lifetime_mode: restoring anonymous_lifetime_mode={:?}", - old_anonymous_lifetime_mode); + debug!( + "with_anonymous_lifetime_mode: restoring anonymous_lifetime_mode={:?}", + old_anonymous_lifetime_mode + ); result } @@ -774,9 +750,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let params = lifetimes_to_define .into_iter() - .map(|(span, hir_name)| self.lifetime_to_generic_param( - span, hir_name, parent_id.index, - )) + .map(|(span, hir_name)| self.lifetime_to_generic_param(span, hir_name, parent_id.index)) .chain(in_band_ty_params.into_iter()) .collect(); @@ -796,18 +770,9 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { // that collisions are ok here and this shouldn't // really show up for end-user. let (str_name, kind) = match hir_name { - ParamName::Plain(ident) => ( - ident.name, - hir::LifetimeParamKind::InBand, - ), - ParamName::Fresh(_) => ( - kw::UnderscoreLifetime, - hir::LifetimeParamKind::Elided, - ), - ParamName::Error => ( - kw::UnderscoreLifetime, - hir::LifetimeParamKind::Error, - ), + ParamName::Plain(ident) => (ident.name, hir::LifetimeParamKind::InBand), + ParamName::Fresh(_) => (kw::UnderscoreLifetime, hir::LifetimeParamKind::Elided), + ParamName::Error => (kw::UnderscoreLifetime, hir::LifetimeParamKind::Error), }; // Add a definition for the in-band lifetime def. @@ -826,7 +791,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { bounds: hir_vec![], span, pure_wrt_drop: false, - kind: hir::GenericParamKind::Lifetime { kind } + kind: hir::GenericParamKind::Lifetime { kind }, } } @@ -849,8 +814,8 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let hir_name = ParamName::Plain(ident); - if self.lifetimes_to_define.iter() - .any(|(_, lt_name)| lt_name.modern() == hir_name.modern()) { + if self.lifetimes_to_define.iter().any(|(_, lt_name)| lt_name.modern() == hir_name.modern()) + { return; } @@ -904,9 +869,8 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { where F: FnOnce(&mut LoweringContext<'_, '_>, &mut Vec) -> T, { - let (in_band_defs, (mut lowered_generics, res)) = self.with_in_scope_lifetime_defs( - &generics.params, - |this| { + let (in_band_defs, (mut lowered_generics, res)) = + self.with_in_scope_lifetime_defs(&generics.params, |this| { this.collect_in_band_defs(parent_id, anonymous_lifetime_mode, |this| { let mut params = Vec::new(); // Note: it is necessary to lower generics *before* calling `f`. @@ -916,32 +880,24 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { // `lifetimes_to_define`. If we swapped the order of these two, // in-band-lifetimes introduced by generics or where-clauses // wouldn't have been added yet. - let generics = this.lower_generics( - generics, - ImplTraitContext::Universal(&mut params), - ); + let generics = + this.lower_generics(generics, ImplTraitContext::Universal(&mut params)); let res = f(this, &mut params); (params, (generics, res)) }) - }, - ); + }); - let mut lowered_params: Vec<_> = lowered_generics - .params - .into_iter() - .chain(in_band_defs) - .collect(); + let mut lowered_params: Vec<_> = + lowered_generics.params.into_iter().chain(in_band_defs).collect(); // FIXME(const_generics): the compiler doesn't always cope with // unsorted generic parameters at the moment, so we make sure // that they're ordered correctly here for now. (When we chain // the `in_band_defs`, we might make the order unsorted.) - lowered_params.sort_by_key(|param| { - match param.kind { - hir::GenericParamKind::Lifetime { .. } => ParamKindOrd::Lifetime, - hir::GenericParamKind::Type { .. } => ParamKindOrd::Type, - hir::GenericParamKind::Const { .. } => ParamKindOrd::Const, - } + lowered_params.sort_by_key(|param| match param.kind { + hir::GenericParamKind::Lifetime { .. } => ParamKindOrd::Lifetime, + hir::GenericParamKind::Type { .. } => ParamKindOrd::Type, + hir::GenericParamKind::Const { .. } => ParamKindOrd::Const, }); lowered_generics.params = lowered_params.into(); @@ -990,9 +946,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { } fn lower_attrs_arena(&mut self, attrs: &[Attribute]) -> &'hir [Attribute] { - self.arena.alloc_from_iter( - attrs.iter().map(|a| self.lower_attr(a)) - ) + self.arena.alloc_from_iter(attrs.iter().map(|a| self.lower_attr(a))) } fn lower_attrs(&mut self, attrs: &[Attribute]) -> hir::HirVec { @@ -1004,48 +958,38 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { // lower attributes (we use the AST version) there is nowhere to keep // the `HirId`s. We don't actually need HIR version of attributes anyway. let kind = match attr.kind { - AttrKind::Normal(ref item) => { - AttrKind::Normal(AttrItem { - path: item.path.clone(), - args: self.lower_mac_args(&item.args), - }) - } - AttrKind::DocComment(comment) => AttrKind::DocComment(comment) + AttrKind::Normal(ref item) => AttrKind::Normal(AttrItem { + path: item.path.clone(), + args: self.lower_mac_args(&item.args), + }), + AttrKind::DocComment(comment) => AttrKind::DocComment(comment), }; - Attribute { - kind, - id: attr.id, - style: attr.style, - span: attr.span, - } + Attribute { kind, id: attr.id, style: attr.style, span: attr.span } } fn lower_mac_args(&mut self, args: &MacArgs) -> MacArgs { match *args { MacArgs::Empty => MacArgs::Empty, - MacArgs::Delimited(dspan, delim, ref tokens) => - MacArgs::Delimited(dspan, delim, self.lower_token_stream(tokens.clone())), - MacArgs::Eq(eq_span, ref tokens) => - MacArgs::Eq(eq_span, self.lower_token_stream(tokens.clone())), + MacArgs::Delimited(dspan, delim, ref tokens) => { + MacArgs::Delimited(dspan, delim, self.lower_token_stream(tokens.clone())) + } + MacArgs::Eq(eq_span, ref tokens) => { + MacArgs::Eq(eq_span, self.lower_token_stream(tokens.clone())) + } } } fn lower_token_stream(&mut self, tokens: TokenStream) -> TokenStream { - tokens - .into_trees() - .flat_map(|tree| self.lower_token_tree(tree).into_trees()) - .collect() + tokens.into_trees().flat_map(|tree| self.lower_token_tree(tree).into_trees()).collect() } fn lower_token_tree(&mut self, tree: TokenTree) -> TokenStream { match tree { TokenTree::Token(token) => self.lower_token(token), - TokenTree::Delimited(span, delim, tts) => TokenTree::Delimited( - span, - delim, - self.lower_token_stream(tts), - ).into(), + TokenTree::Delimited(span, delim, tts) => { + TokenTree::Delimited(span, delim, self.lower_token_stream(tts)).into() + } } } @@ -1077,9 +1021,9 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { debug!("lower_assoc_ty_constraint(constraint={:?}, itctx={:?})", constraint, itctx); let kind = match constraint.kind { - AssocTyConstraintKind::Equality { ref ty } => hir::TypeBindingKind::Equality { - ty: self.lower_ty(ty, itctx) - }, + AssocTyConstraintKind::Equality { ref ty } => { + hir::TypeBindingKind::Equality { ty: self.lower_ty(ty, itctx) } + } AssocTyConstraintKind::Bound { ref bounds } => { // Piggy-back on the `impl Trait` context to figure out the correct behavior. let (desugar_to_impl_trait, itctx) = match itctx { @@ -1107,8 +1051,9 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { // then to an opaque type). // // FIXME: this is only needed until `impl Trait` is allowed in type aliases. - ImplTraitContext::Disallowed(_) if self.is_in_dyn_type => - (true, ImplTraitContext::OpaqueTy(None)), + ImplTraitContext::Disallowed(_) if self.is_in_dyn_type => { + (true, ImplTraitContext::OpaqueTy(None)) + } // We are in the parameter position, but not within a dyn type: // @@ -1145,18 +1090,14 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { itctx, ); - hir::TypeBindingKind::Equality { - ty - } + hir::TypeBindingKind::Equality { ty } }) } else { // Desugar `AssocTy: Bounds` into a type binding where the // later desugars into a trait predicate. let bounds = self.lower_param_bounds(bounds, itctx); - hir::TypeBindingKind::Constraint { - bounds - } + hir::TypeBindingKind::Constraint { bounds } } } }; @@ -1172,7 +1113,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { fn lower_generic_arg( &mut self, arg: &ast::GenericArg, - itctx: ImplTraitContext<'_> + itctx: ImplTraitContext<'_>, ) -> hir::GenericArg { match arg { ast::GenericArg::Lifetime(lt) => GenericArg::Lifetime(self.lower_lifetime(<)), @@ -1192,8 +1133,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { // Construct a AnonConst where the expr is the "ty"'s path. - let parent_def_index = - self.current_hir_id_owner.last().unwrap().0; + let parent_def_index = self.current_hir_id_owner.last().unwrap().0; let node_id = self.resolver.next_node_id(); // Add a definition for the in-band const def. @@ -1212,27 +1152,20 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { attrs: AttrVec::new(), }; - let ct = self.with_new_scopes(|this| { - hir::AnonConst { - hir_id: this.lower_node_id(node_id), - body: this.lower_const_body(path_expr.span, Some(&path_expr)), - } - }); - return GenericArg::Const(ConstArg { - value: ct, - span: ty.span, + let ct = self.with_new_scopes(|this| hir::AnonConst { + hir_id: this.lower_node_id(node_id), + body: this.lower_const_body(path_expr.span, Some(&path_expr)), }); + return GenericArg::Const(ConstArg { value: ct, span: ty.span }); } } } GenericArg::Type(self.lower_ty_direct(&ty, itctx)) } - ast::GenericArg::Const(ct) => { - GenericArg::Const(ConstArg { - value: self.lower_anon_const(&ct), - span: ct.value.span, - }) - } + ast::GenericArg::Const(ct) => GenericArg::Const(ConstArg { + value: self.lower_anon_const(&ct), + span: ct.value.span, + }), } } @@ -1246,7 +1179,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { qself: &Option, path: &Path, param_mode: ParamMode, - itctx: ImplTraitContext<'_> + itctx: ImplTraitContext<'_>, ) -> hir::Ty { let id = self.lower_node_id(t.id); let qpath = self.lower_qpath(t.id, qself, path, param_mode, itctx); @@ -1279,33 +1212,25 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { }; hir::TyKind::Rptr(lifetime, self.lower_mt(mt, itctx)) } - TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs( - &f.generic_params, - |this| { - this.with_anonymous_lifetime_mode( - AnonymousLifetimeMode::PassThrough, - |this| { - hir::TyKind::BareFn(P(hir::BareFnTy { - generic_params: this.lower_generic_params( - &f.generic_params, - &NodeMap::default(), - ImplTraitContext::disallowed(), - ), - unsafety: f.unsafety, - abi: this.lower_extern(f.ext), - decl: this.lower_fn_decl(&f.decl, None, false, None), - param_names: this.lower_fn_params_to_names(&f.decl), - })) - }, - ) - }, - ), + TyKind::BareFn(ref f) => self.with_in_scope_lifetime_defs(&f.generic_params, |this| { + this.with_anonymous_lifetime_mode(AnonymousLifetimeMode::PassThrough, |this| { + hir::TyKind::BareFn(P(hir::BareFnTy { + generic_params: this.lower_generic_params( + &f.generic_params, + &NodeMap::default(), + ImplTraitContext::disallowed(), + ), + unsafety: f.unsafety, + abi: this.lower_extern(f.ext), + decl: this.lower_fn_decl(&f.decl, None, false, None), + param_names: this.lower_fn_params_to_names(&f.decl), + })) + }) + }), TyKind::Never => hir::TyKind::Never, - TyKind::Tup(ref tys) => { - hir::TyKind::Tup(tys.iter().map(|ty| { - self.lower_ty_direct(ty, itctx.reborrow()) - }).collect()) - } + TyKind::Tup(ref tys) => hir::TyKind::Tup( + tys.iter().map(|ty| self.lower_ty_direct(ty, itctx.reborrow())).collect(), + ), TyKind::Paren(ref ty) => { return self.lower_ty_direct(ty, itctx); } @@ -1319,19 +1244,17 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { None, P(hir::Path { res, - segments: hir_vec![hir::PathSegment::from_ident( - Ident::with_dummy_span(kw::SelfUpper) - )], + segments: hir_vec![hir::PathSegment::from_ident(Ident::with_dummy_span( + kw::SelfUpper + ))], span: t.span, }), )) - }, + } TyKind::Array(ref ty, ref length) => { hir::TyKind::Array(self.lower_ty(ty, itctx), self.lower_anon_const(length)) } - TyKind::Typeof(ref expr) => { - hir::TyKind::Typeof(self.lower_anon_const(expr)) - } + TyKind::Typeof(ref expr) => hir::TyKind::Typeof(self.lower_anon_const(expr)), TyKind::TraitObject(ref bounds, kind) => { let mut lifetime_bound = None; let (bounds, lifetime_bound) = self.with_dyn_type_scope(true, |this| { @@ -1363,18 +1286,14 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let span = t.span; match itctx { ImplTraitContext::OpaqueTy(fn_def_id) => { - self.lower_opaque_impl_trait( - span, fn_def_id, def_node_id, - |this| this.lower_param_bounds(bounds, itctx), - ) + self.lower_opaque_impl_trait(span, fn_def_id, def_node_id, |this| { + this.lower_param_bounds(bounds, itctx) + }) } ImplTraitContext::Universal(in_band_ty_params) => { // Add a definition for the in-band `Param`. - let def_index = self - .resolver - .definitions() - .opt_def_index(def_node_id) - .unwrap(); + let def_index = + self.resolver.definitions().opt_def_index(def_node_id).unwrap(); let hir_bounds = self.lower_param_bounds( bounds, @@ -1392,7 +1311,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { kind: hir::GenericParamKind::Type { default: None, synthetic: Some(hir::SyntheticTyParamKind::ImplTrait), - } + }, }); hir::TyKind::Path(hir::QPath::Resolved( @@ -1405,8 +1324,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { )) } ImplTraitContext::Disallowed(pos) => { - let allowed_in = if self.sess.features_untracked() - .impl_trait_in_bindings { + let allowed_in = if self.sess.features_untracked().impl_trait_in_bindings { "bindings or function and inherent method return types" } else { "function and inherent method return types" @@ -1418,11 +1336,13 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { "`impl Trait` not allowed outside of {}", allowed_in, ); - if pos == ImplTraitPosition::Binding && - nightly_options::is_nightly_build() { - help!(err, - "add `#![feature(impl_trait_in_bindings)]` to the crate \ - attributes to enable"); + if pos == ImplTraitPosition::Binding && nightly_options::is_nightly_build() + { + help!( + err, + "add `#![feature(impl_trait_in_bindings)]` to the crate \ + attributes to enable" + ); } err.emit(); hir::TyKind::Err @@ -1439,11 +1359,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { } }; - hir::Ty { - kind, - span: t.span, - hir_id: self.lower_node_id(t.id), - } + hir::Ty { kind, span: t.span, hir_id: self.lower_node_id(t.id) } } fn lower_opaque_impl_trait( @@ -1455,9 +1371,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { ) -> hir::TyKind { debug!( "lower_opaque_impl_trait(fn_def_id={:?}, opaque_ty_node_id={:?}, span={:?})", - fn_def_id, - opaque_ty_node_id, - span, + fn_def_id, opaque_ty_node_id, span, ); // Make sure we know that some funky desugaring has been going on here. @@ -1465,17 +1379,10 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { // desugaring that explicitly states that we don't want to track that. // Not tracking it makes lints in rustc and clippy very fragile, as // frequently opened issues show. - let opaque_ty_span = self.mark_span_with_reason( - DesugaringKind::OpaqueTy, - span, - None, - ); + let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::OpaqueTy, span, None); - let opaque_ty_def_index = self - .resolver - .definitions() - .opt_def_index(opaque_ty_node_id) - .unwrap(); + let opaque_ty_def_index = + self.resolver.definitions().opt_def_index(opaque_ty_node_id).unwrap(); self.allocate_hir_id_counter(opaque_ty_node_id); @@ -1487,22 +1394,15 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { &hir_bounds, ); - debug!( - "lower_opaque_impl_trait: lifetimes={:#?}", lifetimes, - ); + debug!("lower_opaque_impl_trait: lifetimes={:#?}", lifetimes,); - debug!( - "lower_opaque_impl_trait: lifetime_defs={:#?}", lifetime_defs, - ); + debug!("lower_opaque_impl_trait: lifetime_defs={:#?}", lifetime_defs,); self.with_hir_id_owner(opaque_ty_node_id, |lctx| { let opaque_ty_item = hir::OpaqueTy { generics: hir::Generics { params: lifetime_defs, - where_clause: hir::WhereClause { - predicates: hir_vec![], - span, - }, + where_clause: hir::WhereClause { predicates: hir_vec![], span }, span, }, bounds: hir_bounds, @@ -1511,12 +1411,8 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { }; trace!("lower_opaque_impl_trait: {:#?}", opaque_ty_def_index); - let opaque_ty_id = lctx.generate_opaque_type( - opaque_ty_node_id, - opaque_ty_item, - span, - opaque_ty_span, - ); + let opaque_ty_id = + lctx.generate_opaque_type(opaque_ty_node_id, opaque_ty_item, span, opaque_ty_span); // `impl Trait` now just becomes `Foo<'a, 'b, ..>`. hir::TyKind::Def(hir::ItemId { id: opaque_ty_id }, lifetimes) @@ -1579,9 +1475,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { output_lifetime_params: Vec, } - impl<'r, 'a, 'v, 'hir> hir::intravisit::Visitor<'v> - for ImplTraitLifetimeCollector<'r, 'a, 'hir> - { + impl<'r, 'a, 'v, 'hir> hir::intravisit::Visitor<'v> for ImplTraitLifetimeCollector<'r, 'a, 'hir> { fn nested_visit_map<'this>( &'this mut self, ) -> hir::intravisit::NestedVisitorMap<'this, 'v> { @@ -1663,7 +1557,8 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { }; if !self.currently_bound_lifetimes.contains(&name) - && !self.already_defined_lifetimes.contains(&name) { + && !self.already_defined_lifetimes.contains(&name) + { self.already_defined_lifetimes.insert(name); self.output_lifetimes.push(hir::GenericArg::Lifetime(hir::Lifetime { @@ -1680,17 +1575,17 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { def_node_id, DefPathData::LifetimeNs(name.ident().name), ExpnId::root(), - lifetime.span); + lifetime.span, + ); let (name, kind) = match name { hir::LifetimeName::Underscore => ( hir::ParamName::Plain(Ident::with_dummy_span(kw::UnderscoreLifetime)), hir::LifetimeParamKind::Elided, ), - hir::LifetimeName::Param(param_name) => ( - param_name, - hir::LifetimeParamKind::Explicit, - ), + hir::LifetimeName::Param(param_name) => { + (param_name, hir::LifetimeParamKind::Explicit) + } _ => bug!("expected `LifetimeName::Param` or `ParamName::Plain`"), }; @@ -1701,7 +1596,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { pure_wrt_drop: false, attrs: hir_vec![], bounds: hir_vec![], - kind: hir::GenericParamKind::Lifetime { kind } + kind: hir::GenericParamKind::Lifetime { kind }, }); } } @@ -1739,9 +1634,8 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let qself_position = qself.as_ref().map(|q| q.position); let qself = qself.as_ref().map(|q| self.lower_ty(&q.ty, itctx.reborrow())); - let partial_res = self.resolver - .get_partial_res(id) - .unwrap_or_else(|| PartialRes::new(Res::Err)); + let partial_res = + self.resolver.get_partial_res(id).unwrap_or_else(|| PartialRes::new(Res::Err)); let proj_start = p.segments.len() - partial_res.unresolved_segments(); let path = P(hir::Path { @@ -1777,7 +1671,8 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { | Res::Def(DefKind::Union, def_id) | Res::Def(DefKind::Enum, def_id) | Res::Def(DefKind::TyAlias, def_id) - | Res::Def(DefKind::Trait, def_id) if i + 1 == proj_start => + | Res::Def(DefKind::Trait, def_id) + if i + 1 == proj_start => { Some(def_id) } @@ -1789,9 +1684,11 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { ParenthesizedGenericArgs::Ok } // `a::b::Trait(Args)::TraitItem` - Res::Def(DefKind::Method, _) | - Res::Def(DefKind::AssocConst, _) | - Res::Def(DefKind::AssocTy, _) if i + 2 == proj_start => { + Res::Def(DefKind::Method, _) + | Res::Def(DefKind::AssocConst, _) + | Res::Def(DefKind::AssocTy, _) + if i + 2 == proj_start => + { ParenthesizedGenericArgs::Ok } // Avoid duplicated errors. @@ -1805,7 +1702,9 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { return n; } assert!(!def_id.is_local()); - let item_generics = self.resolver.cstore() + let item_generics = self + .resolver + .cstore() .item_generics_cloned_untracked(def_id, self.sess); let n = item_generics.own_counts().lifetimes; self.type_def_lifetime_params.insert(def_id, n); @@ -1894,7 +1793,8 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { ) -> hir::Path { hir::Path { res, - segments: p.segments + segments: p + .segments .iter() .map(|segment| { self.lower_path_segment( @@ -1944,7 +1844,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { if data.inputs.len() > 0 { if let Some(split) = snippet.find('(') { let trait_name = &snippet[0..split]; - let args = &snippet[split + 1 .. snippet.len() - 1]; + let args = &snippet[split + 1..snippet.len() - 1]; err.span_suggestion( data.span, "use angle brackets instead", @@ -1959,8 +1859,9 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { self.lower_angle_bracketed_parameter_data( &data.as_angle_bracketed_args(), param_mode, - itctx - ).0, + itctx, + ) + .0, false, ) } @@ -1974,14 +1875,18 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { GenericArg::Lifetime(_) => true, _ => false, }); - let first_generic_span = generic_args.args.iter().map(|a| a.span()) - .chain(generic_args.bindings.iter().map(|b| b.span)).next(); + let first_generic_span = generic_args + .args + .iter() + .map(|a| a.span()) + .chain(generic_args.bindings.iter().map(|b| b.span)) + .next(); if !generic_args.parenthesized && !has_lifetimes { - generic_args.args = - self.elided_path_lifetimes(path_span, expected_lifetimes) - .into_iter() - .map(|lt| GenericArg::Lifetime(lt)) - .chain(generic_args.args.into_iter()) + generic_args.args = self + .elided_path_lifetimes(path_span, expected_lifetimes) + .into_iter() + .map(|lt| GenericArg::Lifetime(lt)) + .chain(generic_args.args.into_iter()) .collect(); if expected_lifetimes > 0 && param_mode == ParamMode::Explicit { let anon_lt_suggestion = vec!["'_"; expected_lifetimes].join(", "); @@ -2023,8 +1928,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { ); err.emit(); } - AnonymousLifetimeMode::PassThrough | - AnonymousLifetimeMode::ReportError => { + AnonymousLifetimeMode::PassThrough | AnonymousLifetimeMode::ReportError => { self.resolver.lint_buffer().buffer_lint_with_diagnostic( ELIDED_LIFETIMES_IN_PATHS, CRATE_NODE_ID, @@ -2036,7 +1940,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { incl_angl_brckt, insertion_sp, suggestion, - ) + ), ); } } @@ -2078,12 +1982,13 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { ( hir::GenericArgs { args: args.iter().map(|a| self.lower_generic_arg(a, itctx.reborrow())).collect(), - bindings: constraints.iter() + bindings: constraints + .iter() .map(|b| self.lower_assoc_ty_constraint(b, itctx.reborrow())) .collect(), parenthesized: false, }, - !has_non_lt_args && param_mode == ParamMode::Optional + !has_non_lt_args && param_mode == ParamMode::Optional, ) } @@ -2096,31 +2001,25 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { // a hidden lifetime parameter. This is needed for backwards // compatibility, even in contexts like an impl header where // we generally don't permit such things (see #51008). - self.with_anonymous_lifetime_mode( - AnonymousLifetimeMode::PassThrough, - |this| { - let &ParenthesizedArgs { ref inputs, ref output, span } = data; - let inputs = inputs - .iter() - .map(|ty| this.lower_ty_direct(ty, ImplTraitContext::disallowed())) - .collect(); - let output_ty = match output { - FunctionRetTy::Ty(ty) => this.lower_ty(&ty, ImplTraitContext::disallowed()), - FunctionRetTy::Default(_) => P(this.ty_tup(span, hir::HirVec::new())), - }; - let args = hir_vec![GenericArg::Type(this.ty_tup(span, inputs))]; - let binding = hir::TypeBinding { - hir_id: this.next_id(), - ident: Ident::with_dummy_span(FN_OUTPUT_NAME), - span: output_ty.span, - kind: hir::TypeBindingKind::Equality { ty: output_ty }, - }; - ( - hir::GenericArgs { args, bindings: hir_vec![binding], parenthesized: true }, - false, - ) - } - ) + self.with_anonymous_lifetime_mode(AnonymousLifetimeMode::PassThrough, |this| { + let &ParenthesizedArgs { ref inputs, ref output, span } = data; + let inputs = inputs + .iter() + .map(|ty| this.lower_ty_direct(ty, ImplTraitContext::disallowed())) + .collect(); + let output_ty = match output { + FunctionRetTy::Ty(ty) => this.lower_ty(&ty, ImplTraitContext::disallowed()), + FunctionRetTy::Default(_) => P(this.ty_tup(span, hir::HirVec::new())), + }; + let args = hir_vec![GenericArg::Type(this.ty_tup(span, inputs))]; + let binding = hir::TypeBinding { + hir_id: this.next_id(), + ident: Ident::with_dummy_span(FN_OUTPUT_NAME), + span: output_ty.span, + kind: hir::TypeBindingKind::Equality { ty: output_ty }, + }; + (hir::GenericArgs { args, bindings: hir_vec![binding], parenthesized: true }, false) + }) } fn lower_local(&mut self, l: &Local) -> (hir::Local, SmallVec<[NodeId; 1]>) { @@ -2132,23 +2031,27 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { } } let parent_def_id = DefId::local(self.current_hir_id_owner.last().unwrap().0); - (hir::Local { - hir_id: self.lower_node_id(l.id), - ty: l.ty - .as_ref() - .map(|t| self.lower_ty(t, - if self.sess.features_untracked().impl_trait_in_bindings { - ImplTraitContext::OpaqueTy(Some(parent_def_id)) - } else { - ImplTraitContext::Disallowed(ImplTraitPosition::Binding) - } - )), - pat: self.lower_pat(&l.pat), - init: l.init.as_ref().map(|e| P(self.lower_expr(e))), - span: l.span, - attrs: l.attrs.clone(), - source: hir::LocalSource::Normal, - }, ids) + ( + hir::Local { + hir_id: self.lower_node_id(l.id), + ty: l.ty.as_ref().map(|t| { + self.lower_ty( + t, + if self.sess.features_untracked().impl_trait_in_bindings { + ImplTraitContext::OpaqueTy(Some(parent_def_id)) + } else { + ImplTraitContext::Disallowed(ImplTraitPosition::Binding) + }, + ) + }), + pat: self.lower_pat(&l.pat), + init: l.init.as_ref().map(|e| P(self.lower_expr(e))), + span: l.span, + attrs: l.attrs.clone(), + source: hir::LocalSource::Normal, + }, + ids, + ) } fn lower_fn_params_to_names(&mut self, decl: &FnDecl) -> hir::HirVec { @@ -2187,15 +2090,13 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { impl_trait_return_allow: bool, make_ret_async: Option, ) -> P { - debug!("lower_fn_decl(\ + debug!( + "lower_fn_decl(\ fn_decl: {:?}, \ in_band_ty_params: {:?}, \ impl_trait_return_allow: {}, \ make_ret_async: {:?})", - decl, - in_band_ty_params, - impl_trait_return_allow, - make_ret_async, + decl, in_band_ty_params, impl_trait_return_allow, make_ret_async, ); let lt_mode = if make_ret_async.is_some() { // In `async fn`, argument-position elided lifetimes @@ -2242,9 +2143,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { Some((def_id, _)) if impl_trait_return_allow => { hir::Return(self.lower_ty(ty, ImplTraitContext::OpaqueTy(Some(def_id)))) } - _ => { - hir::Return(self.lower_ty(ty, ImplTraitContext::disallowed())) - } + _ => hir::Return(self.lower_ty(ty, ImplTraitContext::disallowed())), }, FunctionRetTy::Default(span) => hir::DefaultReturn(span), } @@ -2254,31 +2153,30 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { inputs, output, c_variadic, - implicit_self: decl.inputs.get(0).map_or( - hir::ImplicitSelfKind::None, - |arg| { - let is_mutable_pat = match arg.pat.kind { - PatKind::Ident(BindingMode::ByValue(mt), _, _) | - PatKind::Ident(BindingMode::ByRef(mt), _, _) => - mt == Mutability::Mut, - _ => false, - }; + implicit_self: decl.inputs.get(0).map_or(hir::ImplicitSelfKind::None, |arg| { + let is_mutable_pat = match arg.pat.kind { + PatKind::Ident(BindingMode::ByValue(mt), _, _) + | PatKind::Ident(BindingMode::ByRef(mt), _, _) => mt == Mutability::Mut, + _ => false, + }; - match arg.ty.kind { - TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut, - TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm, - // Given we are only considering `ImplicitSelf` types, we needn't consider - // the case where we have a mutable pattern to a reference as that would - // no longer be an `ImplicitSelf`. - TyKind::Rptr(_, ref mt) if mt.ty.kind.is_implicit_self() && - mt.mutbl == ast::Mutability::Mut => - hir::ImplicitSelfKind::MutRef, - TyKind::Rptr(_, ref mt) if mt.ty.kind.is_implicit_self() => - hir::ImplicitSelfKind::ImmRef, - _ => hir::ImplicitSelfKind::None, + match arg.ty.kind { + TyKind::ImplicitSelf if is_mutable_pat => hir::ImplicitSelfKind::Mut, + TyKind::ImplicitSelf => hir::ImplicitSelfKind::Imm, + // Given we are only considering `ImplicitSelf` types, we needn't consider + // the case where we have a mutable pattern to a reference as that would + // no longer be an `ImplicitSelf`. + TyKind::Rptr(_, ref mt) + if mt.ty.kind.is_implicit_self() && mt.mutbl == ast::Mutability::Mut => + { + hir::ImplicitSelfKind::MutRef } - }, - ), + TyKind::Rptr(_, ref mt) if mt.ty.kind.is_implicit_self() => { + hir::ImplicitSelfKind::ImmRef + } + _ => hir::ImplicitSelfKind::None, + } + }), }) } @@ -2308,17 +2206,10 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let span = output.span(); - let opaque_ty_span = self.mark_span_with_reason( - DesugaringKind::Async, - span, - None, - ); + let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::Async, span, None); - let opaque_ty_def_index = self - .resolver - .definitions() - .opt_def_index(opaque_ty_node_id) - .unwrap(); + let opaque_ty_def_index = + self.resolver.definitions().opt_def_index(opaque_ty_node_id).unwrap(); self.allocate_hir_id_counter(opaque_ty_node_id); @@ -2379,14 +2270,10 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { // // Then, we will create `fn foo(..) -> Foo<'_, '_>`, and // hence the elision takes place at the fn site. - let future_bound = this.with_anonymous_lifetime_mode( - AnonymousLifetimeMode::CreateParameter, - |this| this.lower_async_fn_output_type_to_future_bound( - output, - fn_def_id, - span, - ), - ); + let future_bound = this + .with_anonymous_lifetime_mode(AnonymousLifetimeMode::CreateParameter, |this| { + this.lower_async_fn_output_type_to_future_bound(output, fn_def_id, span) + }); debug!("lower_async_fn_ret_ty: future_bound={:#?}", future_bound); @@ -2396,32 +2283,30 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { // // Note: this must be done after lowering the output type, // as the output type may introduce new in-band lifetimes. - let lifetime_params: Vec<(Span, ParamName)> = - this.in_scope_lifetimes - .iter().cloned() - .map(|name| (name.ident().span, name)) - .chain(this.lifetimes_to_define.iter().cloned()) - .collect(); + let lifetime_params: Vec<(Span, ParamName)> = this + .in_scope_lifetimes + .iter() + .cloned() + .map(|name| (name.ident().span, name)) + .chain(this.lifetimes_to_define.iter().cloned()) + .collect(); debug!("lower_async_fn_ret_ty: in_scope_lifetimes={:#?}", this.in_scope_lifetimes); debug!("lower_async_fn_ret_ty: lifetimes_to_define={:#?}", this.lifetimes_to_define); debug!("lower_async_fn_ret_ty: lifetime_params={:#?}", lifetime_params); - let generic_params = - lifetime_params - .iter().cloned() - .map(|(span, hir_name)| { - this.lifetime_to_generic_param(span, hir_name, opaque_ty_def_index) - }) - .collect(); + let generic_params = lifetime_params + .iter() + .cloned() + .map(|(span, hir_name)| { + this.lifetime_to_generic_param(span, hir_name, opaque_ty_def_index) + }) + .collect(); let opaque_ty_item = hir::OpaqueTy { generics: hir::Generics { params: generic_params, - where_clause: hir::WhereClause { - predicates: hir_vec![], - span, - }, + where_clause: hir::WhereClause { predicates: hir_vec![], span }, span, }, bounds: hir_vec![future_bound], @@ -2430,12 +2315,8 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { }; trace!("exist ty from async fn def index: {:#?}", opaque_ty_def_index); - let opaque_ty_id = this.generate_opaque_type( - opaque_ty_node_id, - opaque_ty_item, - span, - opaque_ty_span, - ); + let opaque_ty_id = + this.generate_opaque_type(opaque_ty_node_id, opaque_ty_item, span, opaque_ty_span); (opaque_ty_id, lifetime_params) }); @@ -2456,8 +2337,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { // // For the "output" lifetime parameters, we just want to // generate `'_`. - let mut generic_args: Vec<_> = - lifetime_params[..input_lifetimes_count] + let mut generic_args: Vec<_> = lifetime_params[..input_lifetimes_count] .iter() .map(|&(span, hir_name)| { // Input lifetime like `'a` or `'1`: @@ -2468,18 +2348,14 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { }) }) .collect(); - generic_args.extend( - lifetime_params[input_lifetimes_count..] - .iter() - .map(|&(span, _)| { - // Output lifetime like `'_`. - GenericArg::Lifetime(hir::Lifetime { - hir_id: self.next_id(), - span, - name: hir::LifetimeName::Implicit, - }) + generic_args.extend(lifetime_params[input_lifetimes_count..].iter().map(|&(span, _)| { + // Output lifetime like `'_`. + GenericArg::Lifetime(hir::Lifetime { + hir_id: self.next_id(), + span, + name: hir::LifetimeName::Implicit, }) - ); + })); // Create the `Foo<...>` reference itself. Note that the `type // Foo = impl Trait` is, internally, created as a child of the @@ -2508,9 +2384,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { args: hir_vec![], bindings: hir_vec![hir::TypeBinding { ident: Ident::with_dummy_span(FN_OUTPUT_NAME), - kind: hir::TypeBindingKind::Equality { - ty: output_ty, - }, + kind: hir::TypeBindingKind::Equality { ty: output_ty }, hir_id: self.next_id(), span, }], @@ -2523,10 +2397,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { hir::GenericBound::Trait( hir::PolyTraitRef { - trait_ref: hir::TraitRef { - path: future_path, - hir_ref_id: self.next_id(), - }, + trait_ref: hir::TraitRef { path: future_path, hir_ref_id: self.next_id() }, bound_generic_params: hir_vec![], span, }, @@ -2540,12 +2411,10 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { itctx: ImplTraitContext<'_>, ) -> hir::GenericBound { match *tpb { - GenericBound::Trait(ref ty, modifier) => { - hir::GenericBound::Trait( - self.lower_poly_trait_ref(ty, itctx), - self.lower_trait_bound_modifier(modifier), - ) - } + GenericBound::Trait(ref ty, modifier) => hir::GenericBound::Trait( + self.lower_poly_trait_ref(ty, itctx), + self.lower_trait_bound_modifier(modifier), + ), GenericBound::Outlives(ref lifetime) => { hir::GenericBound::Outlives(self.lower_lifetime(lifetime)) } @@ -2555,21 +2424,21 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { fn lower_lifetime(&mut self, l: &Lifetime) -> hir::Lifetime { let span = l.ident.span; match l.ident { - ident if ident.name == kw::StaticLifetime => - self.new_named_lifetime(l.id, span, hir::LifetimeName::Static), - ident if ident.name == kw::UnderscoreLifetime => - match self.anonymous_lifetime_mode { - AnonymousLifetimeMode::CreateParameter => { - let fresh_name = self.collect_fresh_in_band_lifetime(span); - self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name)) - } + ident if ident.name == kw::StaticLifetime => { + self.new_named_lifetime(l.id, span, hir::LifetimeName::Static) + } + ident if ident.name == kw::UnderscoreLifetime => match self.anonymous_lifetime_mode { + AnonymousLifetimeMode::CreateParameter => { + let fresh_name = self.collect_fresh_in_band_lifetime(span); + self.new_named_lifetime(l.id, span, hir::LifetimeName::Param(fresh_name)) + } - AnonymousLifetimeMode::PassThrough => { - self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore) - } + AnonymousLifetimeMode::PassThrough => { + self.new_named_lifetime(l.id, span, hir::LifetimeName::Underscore) + } - AnonymousLifetimeMode::ReportError => self.new_error_lifetime(Some(l.id), span), - }, + AnonymousLifetimeMode::ReportError => self.new_error_lifetime(Some(l.id), span), + }, ident => { self.maybe_collect_in_band_lifetime(ident); let param_name = ParamName::Plain(ident); @@ -2584,11 +2453,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { span: Span, name: hir::LifetimeName, ) -> hir::Lifetime { - hir::Lifetime { - hir_id: self.lower_node_id(id), - span, - name, - } + hir::Lifetime { hir_id: self.lower_node_id(id), span, name } } fn lower_generic_params( @@ -2597,35 +2462,37 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { add_bounds: &NodeMap>, mut itctx: ImplTraitContext<'_>, ) -> hir::HirVec { - params.iter().map(|param| { - self.lower_generic_param(param, add_bounds, itctx.reborrow()) - }).collect() - } - - fn lower_generic_param(&mut self, - param: &GenericParam, - add_bounds: &NodeMap>, - mut itctx: ImplTraitContext<'_>) - -> hir::GenericParam { - let mut bounds = self.with_anonymous_lifetime_mode( - AnonymousLifetimeMode::ReportError, - |this| this.lower_param_bounds(¶m.bounds, itctx.reborrow()), - ); + params + .iter() + .map(|param| self.lower_generic_param(param, add_bounds, itctx.reborrow())) + .collect() + } + + fn lower_generic_param( + &mut self, + param: &GenericParam, + add_bounds: &NodeMap>, + mut itctx: ImplTraitContext<'_>, + ) -> hir::GenericParam { + let mut bounds = self + .with_anonymous_lifetime_mode(AnonymousLifetimeMode::ReportError, |this| { + this.lower_param_bounds(¶m.bounds, itctx.reborrow()) + }); let (name, kind) = match param.kind { GenericParamKind::Lifetime => { let was_collecting_in_band = self.is_collecting_in_band_lifetimes; self.is_collecting_in_band_lifetimes = false; - let lt = self.with_anonymous_lifetime_mode( - AnonymousLifetimeMode::ReportError, - |this| this.lower_lifetime(&Lifetime { id: param.id, ident: param.ident }), - ); + let lt = self + .with_anonymous_lifetime_mode(AnonymousLifetimeMode::ReportError, |this| { + this.lower_lifetime(&Lifetime { id: param.id, ident: param.ident }) + }); let param_name = match lt.name { hir::LifetimeName::Param(param_name) => param_name, hir::LifetimeName::Implicit - | hir::LifetimeName::Underscore - | hir::LifetimeName::Static => hir::ParamName::Plain(lt.name.ident()), + | hir::LifetimeName::Underscore + | hir::LifetimeName::Static => hir::ParamName::Plain(lt.name.ident()), hir::LifetimeName::ImplicitObjectLifetimeDefault => { span_bug!( param.ident.span, @@ -2635,9 +2502,8 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { hir::LifetimeName::Error => ParamName::Error, }; - let kind = hir::GenericParamKind::Lifetime { - kind: hir::LifetimeParamKind::Explicit - }; + let kind = + hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Explicit }; self.is_collecting_in_band_lifetimes = was_collecting_in_band; @@ -2647,28 +2513,29 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let add_bounds = add_bounds.get(¶m.id).map_or(&[][..], |x| &x); if !add_bounds.is_empty() { let params = self.lower_param_bounds(add_bounds, itctx.reborrow()).into_iter(); - bounds = bounds.into_iter() - .chain(params) - .collect(); + bounds = bounds.into_iter().chain(params).collect(); } let kind = hir::GenericParamKind::Type { - default: default.as_ref().map(|x| { - self.lower_ty(x, ImplTraitContext::OpaqueTy(None)) - }), - synthetic: param.attrs.iter() - .filter(|attr| attr.check_name(sym::rustc_synthetic)) - .map(|_| hir::SyntheticTyParamKind::ImplTrait) - .next(), + default: default + .as_ref() + .map(|x| self.lower_ty(x, ImplTraitContext::OpaqueTy(None))), + synthetic: param + .attrs + .iter() + .filter(|attr| attr.check_name(sym::rustc_synthetic)) + .map(|_| hir::SyntheticTyParamKind::ImplTrait) + .next(), }; (hir::ParamName::Plain(param.ident), kind) } - GenericParamKind::Const { ref ty } => { - (hir::ParamName::Plain(param.ident), hir::GenericParamKind::Const { + GenericParamKind::Const { ref ty } => ( + hir::ParamName::Plain(param.ident), + hir::GenericParamKind::Const { ty: self.lower_ty(&ty, ImplTraitContext::disallowed()), - }) - } + }, + ), }; hir::GenericParam { @@ -2687,10 +2554,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { hir::QPath::Resolved(None, path) => path, qpath => bug!("lower_trait_ref: unexpected QPath `{:?}`", qpath), }; - hir::TraitRef { - path, - hir_ref_id: self.lower_node_id(p.ref_id), - } + hir::TraitRef { path, hir_ref_id: self.lower_node_id(p.ref_id) } } fn lower_poly_trait_ref( @@ -2703,27 +2567,22 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { &NodeMap::default(), itctx.reborrow(), ); - let trait_ref = self.with_in_scope_lifetime_defs( - &p.bound_generic_params, - |this| this.lower_trait_ref(&p.trait_ref, itctx), - ); + let trait_ref = self.with_in_scope_lifetime_defs(&p.bound_generic_params, |this| { + this.lower_trait_ref(&p.trait_ref, itctx) + }); - hir::PolyTraitRef { - bound_generic_params, - trait_ref, - span: p.span, - } + hir::PolyTraitRef { bound_generic_params, trait_ref, span: p.span } } fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext<'_>) -> hir::MutTy { - hir::MutTy { - ty: self.lower_ty(&mt.ty, itctx), - mutbl: mt.mutbl, - } + hir::MutTy { ty: self.lower_ty(&mt.ty, itctx), mutbl: mt.mutbl } } - fn lower_param_bounds(&mut self, bounds: &[GenericBound], mut itctx: ImplTraitContext<'_>) - -> hir::GenericBounds { + fn lower_param_bounds( + &mut self, + bounds: &[GenericBound], + mut itctx: ImplTraitContext<'_>, + ) -> hir::GenericBounds { bounds.iter().map(|bound| self.lower_param_bound(bound, itctx.reborrow())).collect() } @@ -2819,9 +2678,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { hir::PatKind::Tuple(pats, ddpos) } PatKind::Box(ref inner) => hir::PatKind::Box(self.lower_pat(inner)), - PatKind::Ref(ref inner, mutbl) => { - hir::PatKind::Ref(self.lower_pat(inner), mutbl) - } + PatKind::Ref(ref inner, mutbl) => hir::PatKind::Ref(self.lower_pat(inner), mutbl), PatKind::Range(ref e1, ref e2, Spanned { node: ref end, .. }) => hir::PatKind::Range( P(self.lower_expr(e1)), P(self.lower_expr(e2)), @@ -2895,7 +2752,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { prev_rest_span = Some(pat.span); slice = Some(self.pat_wild_with_node_id_of(pat)); break; - }, + } // Found a sub-slice pattern `$binding_mode $ident @ ..`. // Record, lower it to `$binding_mode $ident @ _`, and stop here. PatKind::Ident(ref bm, ident, Some(ref sub)) if sub.is_rest() => { @@ -2904,7 +2761,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let node = self.lower_pat_ident(pat, bm, ident, lower_sub); slice = Some(self.pat_with_node_id_of(pat, node)); break; - }, + } // It was not a subslice pattern so lower it normally. _ => before.push(self.lower_pat(pat)), } @@ -2919,7 +2776,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { // The `HirValidator` is merciless; add a `_` pattern to avoid ICEs. after.push(self.pat_wild_with_node_id_of(pat)); Some(sub.span) - }, + } _ => None, }; if let Some(rest_span) = rest_span { @@ -2973,11 +2830,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { /// Construct a `Pat` with the `HirId` of `p.id` lowered. fn pat_with_node_id_of(&mut self, p: &Pat, kind: hir::PatKind) -> P { - P(hir::Pat { - hir_id: self.lower_node_id(p.id), - kind, - span: p.span, - }) + P(hir::Pat { hir_id: self.lower_node_id(p.id), kind, span: p.span }) } /// Emit a friendly error for extra `..` patterns in a tuple/tuple struct/slice pattern. @@ -3010,11 +2863,9 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { } fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst { - self.with_new_scopes(|this| { - hir::AnonConst { - hir_id: this.lower_node_id(c.id), - body: this.lower_const_body(c.value.span, Some(&c.value)), - } + self.with_new_scopes(|this| hir::AnonConst { + hir_id: this.lower_node_id(c.id), + body: this.lower_const_body(c.value.span, Some(&c.value)), }) } @@ -3037,22 +2888,20 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { } }); return ids; - }, + } StmtKind::Item(ref it) => { // Can only use the ID once. let mut id = Some(s.id); - return self.lower_item_id(it) + return self + .lower_item_id(it) .into_iter() .map(|item_id| { - let hir_id = id.take() - .map(|id| self.lower_node_id(id)) - .unwrap_or_else(|| self.next_id()); - - hir::Stmt { - hir_id, - kind: hir::StmtKind::Item(item_id), - span: s.span, - } + let hir_id = id + .take() + .map(|id| self.lower_node_id(id)) + .unwrap_or_else(|| self.next_id()); + + hir::Stmt { hir_id, kind: hir::StmtKind::Item(item_id), span: s.span } }) .collect(); } @@ -3060,11 +2909,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { StmtKind::Semi(ref e) => hir::StmtKind::Semi(P(self.lower_expr(e))), StmtKind::Mac(..) => panic!("shouldn't exist here"), }; - smallvec![hir::Stmt { - hir_id: self.lower_node_id(s.id), - kind, - span: s.span, - }] + smallvec![hir::Stmt { hir_id: self.lower_node_id(s.id), kind, span: s.span }] } fn lower_block_check_mode(&mut self, b: &BlockCheckMode) -> hir::BlockCheckMode { @@ -3115,15 +2960,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { pat: P, source: hir::LocalSource, ) -> hir::Stmt { - let local = hir::Local { - attrs, - hir_id: self.next_id(), - init, - pat, - source, - span, - ty: None, - }; + let local = hir::Local { attrs, hir_id: self.next_id(), init, pat, source, span, ty: None }; self.stmt(span, hir::StmtKind::Local(P(local))) } @@ -3203,7 +3040,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { kind: hir::PatKind::Binding(bm, hir_id, ident.with_span_pos(span), None), span, }), - hir_id + hir_id, ) } @@ -3212,11 +3049,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { } fn pat(&mut self, span: Span, kind: hir::PatKind) -> P { - P(hir::Pat { - hir_id: self.next_id(), - kind, - span, - }) + P(hir::Pat { hir_id: self.next_id(), kind, span }) } /// Given a suffix `["b", "c", "d"]`, returns path `::std::b::c::d` when @@ -3232,16 +3065,20 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let ns = if is_value { Namespace::ValueNS } else { Namespace::TypeNS }; let (path, res) = self.resolver.resolve_str_path(span, self.crate_root, components, ns); - let mut segments: Vec<_> = path.segments.iter().map(|segment| { - let res = self.expect_full_res(segment.id); - hir::PathSegment { - ident: segment.ident, - hir_id: Some(self.lower_node_id(segment.id)), - res: Some(self.lower_res(res)), - infer_args: true, - args: None, - } - }).collect(); + let mut segments: Vec<_> = path + .segments + .iter() + .map(|segment| { + let res = self.expect_full_res(segment.id); + hir::PathSegment { + ident: segment.ident, + hir_id: Some(self.lower_node_id(segment.id)), + res: Some(self.lower_res(res)), + infer_args: true, + args: None, + } + }) + .collect(); segments.last_mut().unwrap().args = params; hir::Path { @@ -3259,10 +3096,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { Res::Def(DefKind::Trait, _) | Res::Def(DefKind::TraitAlias, _) => { let principal = hir::PolyTraitRef { bound_generic_params: hir::HirVec::new(), - trait_ref: hir::TraitRef { - path, - hir_ref_id: hir_id, - }, + trait_ref: hir::TraitRef { path, hir_ref_id: hir_id }, span, }; @@ -3277,11 +3111,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { _ => hir::TyKind::Path(qpath), }; - hir::Ty { - hir_id, - kind, - span, - } + hir::Ty { hir_id, kind, span } } /// Invoked to create the lifetime argument for a type `&T` @@ -3320,13 +3150,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { ), }; - let mut err = struct_span_err!( - self.sess, - span, - E0637, - "{}", - msg, - ); + let mut err = struct_span_err!(self.sess, span, E0637, "{}", msg,); err.span_label(span, label); err.emit(); @@ -3338,19 +3162,15 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { /// sorts of cases are deprecated. This may therefore report a warning or an /// error, depending on the mode. fn elided_path_lifetimes(&mut self, span: Span, count: usize) -> P<[hir::Lifetime]> { - (0..count) - .map(|_| self.elided_path_lifetime(span)) - .collect() + (0..count).map(|_| self.elided_path_lifetime(span)).collect() } fn elided_path_lifetime(&mut self, span: Span) -> hir::Lifetime { match self.anonymous_lifetime_mode { AnonymousLifetimeMode::CreateParameter => { // We should have emitted E0726 when processing this path above - self.sess.delay_span_bug( - span, - "expected 'implicit elided lifetime not allowed' error", - ); + self.sess + .delay_span_bug(span, "expected 'implicit elided lifetime not allowed' error"); let id = self.resolver.next_node_id(); self.new_named_lifetime(id, span, hir::LifetimeName::Error) } @@ -3360,8 +3180,9 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { // `PathSegment`, for which there is no associated `'_` or `&T` with no explicit // lifetime. Instead, we simply create an implicit lifetime, which will be checked // later, at which point a suitable error will be emitted. - | AnonymousLifetimeMode::PassThrough - | AnonymousLifetimeMode::ReportError => self.new_implicit_lifetime(span), + AnonymousLifetimeMode::PassThrough | AnonymousLifetimeMode::ReportError => { + self.new_implicit_lifetime(span) + } } } @@ -3404,17 +3225,15 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { } fn new_implicit_lifetime(&mut self, span: Span) -> hir::Lifetime { - hir::Lifetime { - hir_id: self.next_id(), - span, - name: hir::LifetimeName::Implicit, - } + hir::Lifetime { hir_id: self.next_id(), span, name: hir::LifetimeName::Implicit } } fn maybe_lint_bare_trait(&mut self, span: Span, id: NodeId, is_global: bool) { // FIXME(davidtwco): This is a hack to detect macros which produce spans of the // call site which do not have a macro backtrace. See #61963. - let is_macro_callsite = self.sess.source_map() + let is_macro_callsite = self + .sess + .source_map() .span_to_snippet(span) .map(|snippet| snippet.starts_with("#[")) .unwrap_or(true); diff --git a/src/librustc/infer/error_reporting/nice_region_error/outlives_closure.rs b/src/librustc/infer/error_reporting/nice_region_error/outlives_closure.rs index 9231e4f779eb7..8914ff8add8d7 100644 --- a/src/librustc/infer/error_reporting/nice_region_error/outlives_closure.rs +++ b/src/librustc/infer/error_reporting/nice_region_error/outlives_closure.rs @@ -1,13 +1,13 @@ //! Error Reporting for Anonymous Region Lifetime Errors //! where both the regions are anonymous. +use crate::hir::Node; +use crate::hir::{Expr, ExprKind::Closure}; use crate::infer::error_reporting::nice_region_error::NiceRegionError; +use crate::infer::lexical_region_resolve::RegionResolutionError::SubSupConflict; use crate::infer::SubregionOrigin; use crate::ty::RegionKind; -use crate::hir::{Expr, ExprKind::Closure}; -use crate::hir::Node; use crate::util::common::ErrorReported; -use crate::infer::lexical_region_resolve::RegionResolutionError::SubSupConflict; impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { /// Print the error message for lifetime errors when binding escapes a closure. @@ -36,69 +36,75 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { /// ...because it cannot outlive this closure /// ``` pub(super) fn try_report_outlives_closure(&self) -> Option { - if let Some(SubSupConflict(_, - origin, - ref sub_origin, - _, - ref sup_origin, - sup_region)) = self.error { - + if let Some(SubSupConflict(_, origin, ref sub_origin, _, ref sup_origin, sup_region)) = + self.error + { // #45983: when trying to assign the contents of an argument to a binding outside of a // closure, provide a specific message pointing this out. - if let (&SubregionOrigin::BindingTypeIsNotValidAtDecl(ref external_span), - &RegionKind::ReFree(ref free_region)) = (&sub_origin, sup_region) { + if let ( + &SubregionOrigin::BindingTypeIsNotValidAtDecl(ref external_span), + &RegionKind::ReFree(ref free_region), + ) = (&sub_origin, sup_region) + { let hir = &self.tcx().hir(); if let Some(hir_id) = hir.as_local_hir_id(free_region.scope) { - if let Node::Expr(Expr { - kind: Closure(_, _, _, closure_span, None), - .. - }) = hir.get(hir_id) { + if let Node::Expr(Expr { kind: Closure(_, _, _, closure_span, None), .. }) = + hir.get(hir_id) + { let sup_sp = sup_origin.span(); let origin_sp = origin.span(); let mut err = self.tcx().sess.struct_span_err( sup_sp, - "borrowed data cannot be stored outside of its closure"); + "borrowed data cannot be stored outside of its closure", + ); err.span_label(sup_sp, "cannot be stored outside of its closure"); if origin_sp == sup_sp || origin_sp.contains(sup_sp) { -// // sup_sp == origin.span(): -// -// let mut x = None; -// ----- borrowed data cannot be stored into here... -// with_int(|y| x = Some(y)); -// --- ^ cannot be stored outside of its closure -// | -// ...because it cannot outlive this closure -// -// // origin.contains(&sup_sp): -// -// let mut f: Option<&u32> = None; -// ----- borrowed data cannot be stored into here... -// closure_expecting_bound(|x: &'x u32| { -// ------------ ... because it cannot outlive this closure -// f = Some(x); -// ^ cannot be stored outside of its closure - err.span_label(*external_span, - "borrowed data cannot be stored into here..."); - err.span_label(*closure_span, - "...because it cannot outlive this closure"); + // // sup_sp == origin.span(): + // + // let mut x = None; + // ----- borrowed data cannot be stored into here... + // with_int(|y| x = Some(y)); + // --- ^ cannot be stored outside of its closure + // | + // ...because it cannot outlive this closure + // + // // origin.contains(&sup_sp): + // + // let mut f: Option<&u32> = None; + // ----- borrowed data cannot be stored into here... + // closure_expecting_bound(|x: &'x u32| { + // ------------ ... because it cannot outlive this closure + // f = Some(x); + // ^ cannot be stored outside of its closure + err.span_label( + *external_span, + "borrowed data cannot be stored into here...", + ); + err.span_label( + *closure_span, + "...because it cannot outlive this closure", + ); } else { -// FIXME: the wording for this case could be much improved -// -// let mut lines_to_use: Vec<&CrateId> = Vec::new(); -// - cannot infer an appropriate lifetime... -// let push_id = |installed_id: &CrateId| { -// ------- ------------------------ borrowed data cannot outlive this closure -// | -// ...so that variable is valid at time of its declaration -// lines_to_use.push(installed_id); -// ^^^^^^^^^^^^ cannot be stored outside of its closure - err.span_label(origin_sp, - "cannot infer an appropriate lifetime..."); - err.span_label(*external_span, - "...so that variable is valid at time of its \ - declaration"); - err.span_label(*closure_span, - "borrowed data cannot outlive this closure"); + // FIXME: the wording for this case could be much improved + // + // let mut lines_to_use: Vec<&CrateId> = Vec::new(); + // - cannot infer an appropriate lifetime... + // let push_id = |installed_id: &CrateId| { + // ------- ------------------------ borrowed data cannot outlive this closure + // | + // ...so that variable is valid at time of its declaration + // lines_to_use.push(installed_id); + // ^^^^^^^^^^^^ cannot be stored outside of its closure + err.span_label(origin_sp, "cannot infer an appropriate lifetime..."); + err.span_label( + *external_span, + "...so that variable is valid at time of its \ + declaration", + ); + err.span_label( + *closure_span, + "borrowed data cannot outlive this closure", + ); } err.emit(); return Some(ErrorReported); diff --git a/src/librustc/lint/mod.rs b/src/librustc/lint/mod.rs index 3d6015ecfbff6..6900ed4f47565 100644 --- a/src/librustc/lint/mod.rs +++ b/src/librustc/lint/mod.rs @@ -23,26 +23,27 @@ pub use self::LintSource::*; use rustc_data_structures::sync; +use crate::hir; use crate::hir::def_id::{CrateNum, LOCAL_CRATE}; use crate::hir::intravisit; -use crate::hir; use crate::lint::builtin::BuiltinLintDiagnostics; -use crate::session::{Session, DiagnosticMessageId}; -use crate::ty::TyCtxt; +use crate::session::{DiagnosticMessageId, Session}; use crate::ty::query::Providers; +use crate::ty::TyCtxt; use crate::util::nodemap::NodeMap; use errors::{DiagnosticBuilder, DiagnosticId}; use syntax::ast; -use syntax::source_map::{MultiSpan, ExpnKind, DesugaringKind}; +use syntax::source_map::{DesugaringKind, ExpnKind, MultiSpan}; use syntax::symbol::Symbol; use syntax_pos::hygiene::MacroKind; use syntax_pos::Span; -pub use crate::lint::context::{LateContext, EarlyContext, LintContext, LintStore, - check_crate, check_ast_crate, late_lint_mod, CheckLintNameResult, - BufferedEarlyLint,}; +pub use crate::lint::context::{ + check_ast_crate, check_crate, late_lint_mod, BufferedEarlyLint, CheckLintNameResult, + EarlyContext, LateContext, LintContext, LintStore, +}; -pub use rustc_session::lint::{Lint, LintId, Level, FutureIncompatibleInfo}; +pub use rustc_session::lint::{FutureIncompatibleInfo, Level, Lint, LintId}; /// Declares a static `LintArray` and return it as an expression. #[macro_export] @@ -351,8 +352,8 @@ macro_rules! declare_combined_early_lint_pass { /// A lint pass boxed up as a trait object. pub type EarlyLintPassObject = Box; -pub type LateLintPassObject = Box LateLintPass<'a, 'tcx> + sync::Send - + sync::Sync + 'static>; +pub type LateLintPassObject = + Box LateLintPass<'a, 'tcx> + sync::Send + sync::Sync + 'static>; /// How a lint level was set. #[derive(Clone, Copy, PartialEq, Eq, HashStable)] @@ -371,11 +372,11 @@ pub enum LintSource { pub type LevelSource = (Level, LintSource); pub mod builtin; -pub mod internal; mod context; +pub mod internal; mod levels; -pub use self::levels::{LintLevelSets, LintLevelMap}; +pub use self::levels::{LintLevelMap, LintLevelSets}; #[derive(Default)] pub struct LintBuffer { @@ -383,18 +384,20 @@ pub struct LintBuffer { } impl LintBuffer { - pub fn add_lint(&mut self, - lint: &'static Lint, - id: ast::NodeId, - sp: MultiSpan, - msg: &str, - diagnostic: BuiltinLintDiagnostics) { + pub fn add_lint( + &mut self, + lint: &'static Lint, + id: ast::NodeId, + sp: MultiSpan, + msg: &str, + diagnostic: BuiltinLintDiagnostics, + ) { let early_lint = BufferedEarlyLint { lint_id: LintId::of(lint), ast_id: id, span: sp, msg: msg.to_string(), - diagnostic + diagnostic, }; let arr = self.map.entry(id).or_default(); if !arr.contains(&early_lint) { @@ -428,22 +431,20 @@ impl LintBuffer { } } -pub fn struct_lint_level<'a>(sess: &'a Session, - lint: &'static Lint, - level: Level, - src: LintSource, - span: Option, - msg: &str) - -> DiagnosticBuilder<'a> -{ +pub fn struct_lint_level<'a>( + sess: &'a Session, + lint: &'static Lint, + level: Level, + src: LintSource, + span: Option, + msg: &str, +) -> DiagnosticBuilder<'a> { let mut err = match (level, span) { (Level::Allow, _) => return sess.diagnostic().struct_dummy(), (Level::Warn, Some(span)) => sess.struct_span_warn(span, msg), (Level::Warn, None) => sess.struct_warn(msg), - (Level::Deny, Some(span)) | - (Level::Forbid, Some(span)) => sess.struct_span_err(span, msg), - (Level::Deny, None) | - (Level::Forbid, None) => sess.struct_err(msg), + (Level::Deny, Some(span)) | (Level::Forbid, Some(span)) => sess.struct_span_err(span, msg), + (Level::Deny, None) | (Level::Forbid, None) => sess.struct_err(msg), }; // Check for future incompatibility lints and issue a stronger warning. @@ -475,7 +476,8 @@ pub fn struct_lint_level<'a>(sess: &'a Session, sess.diag_note_once( &mut err, DiagnosticMessageId::from(lint), - &format!("`#[{}({})]` on by default", level.as_str(), name)); + &format!("`#[{}({})]` on by default", level.as_str(), name), + ); } LintSource::CommandLine(lint_flag_val) => { let flag = match level { @@ -489,29 +491,43 @@ pub fn struct_lint_level<'a>(sess: &'a Session, sess.diag_note_once( &mut err, DiagnosticMessageId::from(lint), - &format!("requested on the command line with `{} {}`", - flag, hyphen_case_lint_name)); + &format!( + "requested on the command line with `{} {}`", + flag, hyphen_case_lint_name + ), + ); } else { let hyphen_case_flag_val = lint_flag_val.as_str().replace("_", "-"); sess.diag_note_once( &mut err, DiagnosticMessageId::from(lint), - &format!("`{} {}` implied by `{} {}`", - flag, hyphen_case_lint_name, flag, - hyphen_case_flag_val)); + &format!( + "`{} {}` implied by `{} {}`", + flag, hyphen_case_lint_name, flag, hyphen_case_flag_val + ), + ); } } LintSource::Node(lint_attr_name, src, reason) => { if let Some(rationale) = reason { err.note(&rationale.as_str()); } - sess.diag_span_note_once(&mut err, DiagnosticMessageId::from(lint), - src, "lint level defined here"); + sess.diag_span_note_once( + &mut err, + DiagnosticMessageId::from(lint), + src, + "lint level defined here", + ); if lint_attr_name.as_str() != name { let level_str = level.as_str(); - sess.diag_note_once(&mut err, DiagnosticMessageId::from(lint), - &format!("`#[{}({})]` implied by `#[{}({})]`", - level_str, name, level_str, lint_attr_name)); + sess.diag_note_once( + &mut err, + DiagnosticMessageId::from(lint), + &format!( + "`#[{}({})]` implied by `#[{}({})]`", + level_str, name, level_str, lint_attr_name + ), + ); } } } @@ -519,8 +535,7 @@ pub fn struct_lint_level<'a>(sess: &'a Session, err.code(DiagnosticId::Lint(name)); if let Some(future_incompatible) = future_incompatible { - const STANDARD_MESSAGE: &str = - "this was previously accepted by the compiler but is being phased out; \ + const STANDARD_MESSAGE: &str = "this was previously accepted by the compiler but is being phased out; \ it will become a hard error"; let explanation = if lint_id == LintId::of(builtin::UNSTABLE_NAME_COLLISIONS) { @@ -536,13 +551,12 @@ pub fn struct_lint_level<'a>(sess: &'a Session, } else { format!("{} in a future release!", STANDARD_MESSAGE) }; - let citation = format!("for more information, see {}", - future_incompatible.reference); + let citation = format!("for more information, see {}", future_incompatible.reference); err.warn(&explanation); err.note(&citation); } - return err + return err; } pub fn maybe_lint_level_root(tcx: TyCtxt<'_>, id: hir::HirId) -> bool { @@ -563,7 +577,7 @@ fn lint_levels(tcx: TyCtxt<'_>, cnum: CrateNum) -> &LintLevelMap { let push = builder.levels.push(&krate.attrs, &store); builder.levels.register_id(hir::CRATE_HIR_ID); for macro_def in krate.exported_macros { - builder.levels.register_id(macro_def.hir_id); + builder.levels.register_id(macro_def.hir_id); } intravisit::walk_crate(&mut builder, krate); builder.levels.pop(push); @@ -578,11 +592,9 @@ struct LintLevelMapBuilder<'a, 'tcx> { } impl LintLevelMapBuilder<'_, '_> { - fn with_lint_attrs(&mut self, - id: hir::HirId, - attrs: &[ast::Attribute], - f: F) - where F: FnOnce(&mut Self) + fn with_lint_attrs(&mut self, id: hir::HirId, attrs: &[ast::Attribute], f: F) + where + F: FnOnce(&mut Self), { let push = self.levels.push(attrs, self.store); if push.changed { @@ -628,10 +640,12 @@ impl intravisit::Visitor<'tcx> for LintLevelMapBuilder<'_, 'tcx> { }) } - fn visit_variant(&mut self, - v: &'tcx hir::Variant<'tcx>, - g: &'tcx hir::Generics, - item_id: hir::HirId) { + fn visit_variant( + &mut self, + v: &'tcx hir::Variant<'tcx>, + g: &'tcx hir::Generics, + item_id: hir::HirId, + ) { self.with_lint_attrs(v.id, &v.attrs, |builder| { intravisit::walk_variant(builder, v, g, item_id); }) diff --git a/src/librustc/middle/resolve_lifetime.rs b/src/librustc/middle/resolve_lifetime.rs index 4b838d040596b..67630a75768d0 100644 --- a/src/librustc/middle/resolve_lifetime.rs +++ b/src/librustc/middle/resolve_lifetime.rs @@ -5,9 +5,7 @@ //! used between functions, and they operate in a purely top-down //! way. Therefore, we break lifetime name resolution into a separate pass. -// ignore-tidy-filelength - -use crate::hir::def::{Res, DefKind}; +use crate::hir::def::{DefKind, Res}; use crate::hir::def_id::{CrateNum, DefId, LocalDefId, LOCAL_CRATE}; use crate::hir::map::Map; use crate::hir::ptr::P; @@ -17,7 +15,7 @@ use crate::ty::{self, DefIdTree, GenericParamDefKind, TyCtxt}; use crate::rustc::lint; use crate::session::Session; use crate::util::nodemap::{DefIdMap, FxHashMap, FxHashSet, HirIdMap, HirIdSet}; -use errors::{Applicability, DiagnosticBuilder, pluralize}; +use errors::{pluralize, Applicability, DiagnosticBuilder}; use rustc_macros::HashStable; use std::borrow::Cow; use std::cell::Cell; @@ -69,16 +67,8 @@ pub enum LifetimeUseSet<'tcx> { #[derive(Clone, Copy, PartialEq, Eq, Hash, RustcEncodable, RustcDecodable, Debug, HashStable)] pub enum Region { Static, - EarlyBound( - /* index */ u32, - /* lifetime decl */ DefId, - LifetimeDefOrigin, - ), - LateBound( - ty::DebruijnIndex, - /* lifetime decl */ DefId, - LifetimeDefOrigin, - ), + EarlyBound(/* index */ u32, /* lifetime decl */ DefId, LifetimeDefOrigin), + LateBound(ty::DebruijnIndex, /* lifetime decl */ DefId, LifetimeDefOrigin), LateBoundAnon(ty::DebruijnIndex, /* anon index */ u32), Free(DefId, /* lifetime decl */ DefId), } @@ -101,10 +91,7 @@ impl Region { "Region::late: param={:?} depth={:?} def_id={:?} origin={:?}", param, depth, def_id, origin, ); - ( - param.name.modern(), - Region::LateBound(depth, def_id, origin), - ) + (param.name.modern(), Region::LateBound(depth, def_id, origin)) } fn late_anon(index: &Cell) -> Region { @@ -153,9 +140,7 @@ impl Region { L: Iterator, { if let Region::EarlyBound(index, _, _) = self { - params - .nth(index as usize) - .and_then(|lifetime| map.defs.get(&lifetime.hir_id).cloned()) + params.nth(index as usize).and_then(|lifetime| map.defs.get(&lifetime.hir_id).cloned()) } else { Some(self) } @@ -344,16 +329,12 @@ pub fn provide(providers: &mut ty::query::Providers<'_>) { is_late_bound_map: |tcx, id| { let id = LocalDefId::from_def_id(DefId::local(id)); // (*) - tcx.resolve_lifetimes(LOCAL_CRATE) - .late_bound - .get(&id) + tcx.resolve_lifetimes(LOCAL_CRATE).late_bound.get(&id) }, object_lifetime_defaults_map: |tcx, id| { let id = LocalDefId::from_def_id(DefId::local(id)); // (*) - tcx.resolve_lifetimes(LOCAL_CRATE) - .object_lifetime_defaults - .get(&id) + tcx.resolve_lifetimes(LOCAL_CRATE).object_lifetime_defaults.get(&id) }, ..*providers @@ -378,15 +359,11 @@ fn resolve_lifetimes(tcx: TyCtxt<'_>, for_krate: CrateNum) -> &ResolveLifetimes map.insert(hir_id.local_id, v); } for hir_id in named_region_map.late_bound { - let map = rl.late_bound - .entry(hir_id.owner_local_def_id()) - .or_default(); + let map = rl.late_bound.entry(hir_id.owner_local_def_id()).or_default(); map.insert(hir_id.local_id); } for (hir_id, v) in named_region_map.object_lifetime_defaults { - let map = rl.object_lifetime_defaults - .entry(hir_id.owner_local_def_id()) - .or_default(); + let map = rl.object_lifetime_defaults.entry(hir_id.owner_local_def_id()).or_default(); map.insert(hir_id.local_id, v); } @@ -423,8 +400,7 @@ fn krate(tcx: TyCtxt<'_>) -> NamedRegionMap { /// This function returns whether there is such an implicit parameter defined on the given item. fn sub_items_have_self_param(node: &hir::ItemKind<'_>) -> bool { match *node { - hir::ItemKind::Trait(..) | - hir::ItemKind::TraitAlias(..) => true, + hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..) => true, _ => false, } } @@ -442,15 +418,9 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { let saved = take(&mut self.labels_in_fn); let body = self.tcx.hir().body(body); extract_labels(self, body); - self.with( - Scope::Body { - id: body.id(), - s: self.scope, - }, - |_, this| { - this.visit_body(body); - }, - ); + self.with(Scope::Body { id: body.id(), s: self.scope }, |_, this| { + this.visit_body(body); + }); replace(&mut self.labels_in_fn, saved); } @@ -472,25 +442,17 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { } hir::ItemKind::Static(..) | hir::ItemKind::Const(..) => { // No lifetime parameters, but implied 'static. - let scope = Scope::Elision { - elide: Elide::Exact(Region::Static), - s: ROOT_SCOPE, - }; + let scope = Scope::Elision { elide: Elide::Exact(Region::Static), s: ROOT_SCOPE }; self.with(scope, |_, this| intravisit::walk_item(this, item)); } - hir::ItemKind::OpaqueTy(hir::OpaqueTy { - impl_trait_fn: Some(_), - .. - }) => { + hir::ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn: Some(_), .. }) => { // Currently opaque type declarations are just generated from `impl Trait` // items. Doing anything on this node is irrelevant, as we currently don't need // it. } hir::ItemKind::TyAlias(_, ref generics) | hir::ItemKind::OpaqueTy(hir::OpaqueTy { - impl_trait_fn: None, - ref generics, - .. + impl_trait_fn: None, ref generics, .. }) | hir::ItemKind::Enum(_, ref generics) | hir::ItemKind::Struct(_, ref generics) @@ -511,16 +473,19 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { 0 }; let mut non_lifetime_count = 0; - let lifetimes = generics.params.iter().filter_map(|param| match param.kind { - GenericParamKind::Lifetime { .. } => { - Some(Region::early(&self.tcx.hir(), &mut index, param)) - } - GenericParamKind::Type { .. } | - GenericParamKind::Const { .. } => { - non_lifetime_count += 1; - None - } - }).collect(); + let lifetimes = generics + .params + .iter() + .filter_map(|param| match param.kind { + GenericParamKind::Lifetime { .. } => { + Some(Region::early(&self.tcx.hir(), &mut index, param)) + } + GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => { + non_lifetime_count += 1; + None + } + }) + .collect(); let scope = Scope::Binder { lifetimes, next_early_index: index + non_lifetime_count, @@ -561,7 +526,8 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { let was_in_fn_syntax = self.is_in_fn_syntax; self.is_in_fn_syntax = true; let scope = Scope::Binder { - lifetimes: c.generic_params + lifetimes: c + .generic_params .iter() .filter_map(|param| match param.kind { GenericParamKind::Lifetime { .. } => { @@ -592,10 +558,7 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { LifetimeName::Implicit => { // For types like `dyn Foo`, we should // generate a special form of elided. - span_bug!( - ty.span, - "object-lifetime-default expected, not implict", - ); + span_bug!(ty.span, "object-lifetime-default expected, not implict",); } LifetimeName::ImplicitObjectLifetimeDefault => { // If the user does not write *anything*, we @@ -636,19 +599,14 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { let (generics, bounds) = match self.tcx.hir().expect_item(item_id.id).kind { // Named opaque `impl Trait` types are reached via `TyKind::Path`. // This arm is for `impl Trait` in the types of statics, constants and locals. - hir::ItemKind::OpaqueTy(hir::OpaqueTy { - impl_trait_fn: None, - .. - }) => { + hir::ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn: None, .. }) => { intravisit::walk_ty(self, ty); return; } // RPIT (return position impl trait) - hir::ItemKind::OpaqueTy(hir::OpaqueTy { - ref generics, - ref bounds, - .. - }) => (generics, bounds), + hir::ItemKind::OpaqueTy(hir::OpaqueTy { ref generics, ref bounds, .. }) => { + (generics, bounds) + } ref i => bug!("`impl Trait` pointed to non-opaque type?? {:#?}", i), }; @@ -704,7 +662,7 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { match param.kind { GenericParamKind::Lifetime { .. } => { let (name, reg) = Region::early(&self.tcx.hir(), &mut index, ¶m); - let def_id = if let Region::EarlyBound(_ ,def_id , _) = reg { + let def_id = if let Region::EarlyBound(_, def_id, _) = reg { def_id } else { bug!(); @@ -723,8 +681,7 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { lifetimes.insert(name, reg); } } - GenericParamKind::Type { .. } | - GenericParamKind::Const { .. } => { + GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => { non_lifetime_count += 1; } } @@ -732,10 +689,8 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { let next_early_index = index + non_lifetime_count; if let Some(elision_region) = elision { - let scope = Scope::Elision { - elide: Elide::Exact(elision_region), - s: self.scope, - }; + let scope = + Scope::Elision { elide: Elide::Exact(elision_region), s: self.scope }; self.with(scope, |_old_scope, this| { let scope = Scope::Binder { lifetimes, @@ -788,16 +743,19 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { let mut index = self.next_early_index(); debug!("visit_ty: index = {}", index); let mut non_lifetime_count = 0; - let lifetimes = generics.params.iter().filter_map(|param| match param.kind { - GenericParamKind::Lifetime { .. } => { - Some(Region::early(&self.tcx.hir(), &mut index, param)) - } - GenericParamKind::Type { .. } | - GenericParamKind::Const { .. } => { - non_lifetime_count += 1; - None - } - }).collect(); + let lifetimes = generics + .params + .iter() + .filter_map(|param| match param.kind { + GenericParamKind::Lifetime { .. } => { + Some(Region::early(&self.tcx.hir(), &mut index, param)) + } + GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => { + non_lifetime_count += 1; + None + } + }) + .collect(); let scope = Scope::Binder { lifetimes, next_early_index: index + non_lifetime_count, @@ -840,16 +798,19 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { let mut index = self.next_early_index(); let mut non_lifetime_count = 0; debug!("visit_ty: index = {}", index); - let lifetimes = generics.params.iter().filter_map(|param| match param.kind { - GenericParamKind::Lifetime { .. } => { - Some(Region::early(&self.tcx.hir(), &mut index, param)) - } - GenericParamKind::Const { .. } | - GenericParamKind::Type { .. } => { - non_lifetime_count += 1; - None - } - }).collect(); + let lifetimes = generics + .params + .iter() + .filter_map(|param| match param.kind { + GenericParamKind::Lifetime { .. } => { + Some(Region::early(&self.tcx.hir(), &mut index, param)) + } + GenericParamKind::Const { .. } | GenericParamKind::Type { .. } => { + non_lifetime_count += 1; + None + } + }) + .collect(); let scope = Scope::Binder { lifetimes, next_early_index: index + non_lifetime_count, @@ -867,19 +828,23 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { let mut index = self.next_early_index(); let mut next_early_index = index; debug!("visit_ty: index = {}", index); - let lifetimes = generics.params.iter().filter_map(|param| match param.kind { - GenericParamKind::Lifetime { .. } => { - Some(Region::early(&self.tcx.hir(), &mut index, param)) - } - GenericParamKind::Type { .. } => { - next_early_index += 1; - None - } - GenericParamKind::Const { .. } => { - next_early_index += 1; - None - } - }).collect(); + let lifetimes = generics + .params + .iter() + .filter_map(|param| match param.kind { + GenericParamKind::Lifetime { .. } => { + Some(Region::early(&self.tcx.hir(), &mut index, param)) + } + GenericParamKind::Type { .. } => { + next_early_index += 1; + None + } + GenericParamKind::Const { .. } => { + next_early_index += 1; + None + } + }) + .collect(); let scope = Scope::Binder { lifetimes, @@ -1016,12 +981,12 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { ) { debug!("visit_poly_trait_ref(trait_ref={:?})", trait_ref); - if !self.trait_ref_hack || trait_ref.bound_generic_params.iter().any(|param| { - match param.kind { + if !self.trait_ref_hack + || trait_ref.bound_generic_params.iter().any(|param| match param.kind { GenericParamKind::Lifetime { .. } => true, _ => false, - } - }) { + }) + { if self.trait_ref_hack { span_err!( self.tcx.sess, @@ -1073,28 +1038,16 @@ struct Shadower { } fn original_label(span: Span) -> Original { - Original { - kind: ShadowKind::Label, - span: span, - } + Original { kind: ShadowKind::Label, span: span } } fn shadower_label(span: Span) -> Shadower { - Shadower { - kind: ShadowKind::Label, - span: span, - } + Shadower { kind: ShadowKind::Label, span: span } } fn original_lifetime(span: Span) -> Original { - Original { - kind: ShadowKind::Lifetime, - span: span, - } + Original { kind: ShadowKind::Lifetime, span: span } } fn shadower_lifetime(param: &hir::GenericParam) -> Shadower { - Shadower { - kind: ShadowKind::Lifetime, - span: param.span, - } + Shadower { kind: ShadowKind::Lifetime, span: param.span } } impl ShadowKind { @@ -1114,12 +1067,8 @@ fn check_mixed_explicit_and_in_band_defs(tcx: TyCtxt<'_>, params: &P<[hir::Gener _ => None, }) .collect(); - let explicit = lifetime_params - .iter() - .find(|(kind, _)| *kind == LifetimeParamKind::Explicit); - let in_band = lifetime_params - .iter() - .find(|(kind, _)| *kind == LifetimeParamKind::InBand); + let explicit = lifetime_params.iter().find(|(kind, _)| *kind == LifetimeParamKind::Explicit); + let in_band = lifetime_params.iter().find(|(kind, _)| *kind == LifetimeParamKind::InBand); if let (Some((_, explicit_span)), Some((_, in_band_span))) = (explicit, in_band) { struct_span_err!( @@ -1127,9 +1076,10 @@ fn check_mixed_explicit_and_in_band_defs(tcx: TyCtxt<'_>, params: &P<[hir::Gener *in_band_span, E0688, "cannot mix in-band and explicit lifetime definitions" - ).span_label(*in_band_span, "in-band lifetime definition here") - .span_label(*explicit_span, "explicit lifetime definition here") - .emit(); + ) + .span_label(*in_band_span, "in-band lifetime definition here") + .span_label(*explicit_span, "explicit lifetime definition here") + .emit(); } } @@ -1174,11 +1124,8 @@ fn extract_labels(ctxt: &mut LifetimeContext<'_, '_>, body: &hir::Body<'_>) { labels_in_fn: &'a mut Vec, } - let mut gather = GatherLabels { - tcx: ctxt.tcx, - scope: ctxt.scope, - labels_in_fn: &mut ctxt.labels_in_fn, - }; + let mut gather = + GatherLabels { tcx: ctxt.tcx, scope: ctxt.scope, labels_in_fn: &mut ctxt.labels_in_fn }; gather.visit_body(body); impl<'v, 'a, 'tcx> Visitor<'v> for GatherLabels<'a, 'tcx> { @@ -1209,11 +1156,7 @@ fn extract_labels(ctxt: &mut LifetimeContext<'_, '_>, body: &hir::Body<'_>) { } fn expression_label(ex: &hir::Expr) -> Option { - if let hir::ExprKind::Loop(_, Some(label), _) = ex.kind { - Some(label.ident) - } else { - None - } + if let hir::ExprKind::Loop(_, Some(label), _) = ex.kind { Some(label.ident) } else { None } } fn check_if_label_shadows_lifetime( @@ -1233,9 +1176,7 @@ fn extract_labels(ctxt: &mut LifetimeContext<'_, '_>, body: &hir::Body<'_>) { return; } - Scope::Binder { - ref lifetimes, s, .. - } => { + Scope::Binder { ref lifetimes, s, .. } => { // FIXME (#24278): non-hygienic comparison if let Some(def) = lifetimes.get(&hir::ParamName::Plain(label.modern())) { let hir_id = tcx.hir().as_local_hir_id(def.id().unwrap()).unwrap(); @@ -1263,9 +1204,7 @@ fn compute_object_lifetime_defaults(tcx: TyCtxt<'_>) -> HirIdMap { @@ -1406,12 +1345,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { where F: for<'b> FnOnce(ScopeRef<'_>, &mut LifetimeContext<'b, 'tcx>), { - let LifetimeContext { - tcx, - map, - lifetime_uses, - .. - } = self; + let LifetimeContext { tcx, map, lifetime_uses, .. } = self; let labels_in_fn = take(&mut self.labels_in_fn); let xcrate_object_lifetime_defaults = take(&mut self.xcrate_object_lifetime_defaults); let mut this = LifetimeContext { @@ -1468,7 +1402,10 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { // helper method to issue suggestions from `fn rah<'a>(&'a T)` to `fn rah(&T)` // or from `fn rah<'a>(T<'a>)` to `fn rah(T<'_>)` fn suggest_eliding_single_use_lifetime( - &self, err: &mut DiagnosticBuilder<'_>, def_id: DefId, lifetime: &hir::Lifetime + &self, + err: &mut DiagnosticBuilder<'_>, + def_id: DefId, + lifetime: &hir::Lifetime, ) { let name = lifetime.name.ident(); let mut remove_decl = None; @@ -1488,16 +1425,17 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { // include the trailing whitespace between the lifetime and type names let lt_through_ty_span = lifetime.span.to(input.span.shrink_to_hi()); remove_use = Some( - self.tcx.sess.source_map() - .span_until_non_whitespace(lt_through_ty_span) + self.tcx + .sess + .source_map() + .span_until_non_whitespace(lt_through_ty_span), ); break; } } hir::TyKind::Path(ref qpath) => { if let QPath::Resolved(_, path) = qpath { - - let last_segment = &path.segments[path.segments.len()-1]; + let last_segment = &path.segments[path.segments.len() - 1]; let generics = last_segment.generic_args(); for arg in generics.args.iter() { if let GenericArg::Lifetime(lt) = arg { @@ -1509,21 +1447,21 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { } break; } - }, + } _ => {} } } }; if let Node::Lifetime(hir_lifetime) = self.tcx.hir().get(lifetime.hir_id) { - if let Some(parent) = self.tcx.hir().find( - self.tcx.hir().get_parent_item(hir_lifetime.hir_id)) + if let Some(parent) = + self.tcx.hir().find(self.tcx.hir().get_parent_item(hir_lifetime.hir_id)) { match parent { Node::Item(item) => { if let hir::ItemKind::Fn(sig, _, _) = &item.kind { find_arg_use_span(&sig.decl.inputs); } - }, + } Node::ImplItem(impl_item) => { if let hir::ImplItemKind::Method(sig, _) = &impl_item.kind { find_arg_use_span(&sig.decl.inputs); @@ -1590,10 +1528,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { def_ids.sort_by_cached_key(|&def_id| self.tcx.def_path_hash(def_id)); for def_id in def_ids { - debug!( - "check_uses_for_lifetimes_defined_by_scope: def_id = {:?}", - def_id - ); + debug!("check_uses_for_lifetimes_defined_by_scope: def_id = {:?}", def_id); let lifetimeuseset = self.lifetime_uses.remove(&def_id); @@ -1623,14 +1558,20 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { } if let Some(parent_def_id) = self.tcx.parent(def_id) { - if let Some(parent_hir_id) = self.tcx.hir() - .as_local_hir_id(parent_def_id) { - // lifetimes in `derive` expansions don't count (Issue #53738) - if self.tcx.hir().attrs(parent_hir_id).iter() - .any(|attr| attr.check_name(sym::automatically_derived)) { - continue; - } + if let Some(parent_hir_id) = + self.tcx.hir().as_local_hir_id(parent_def_id) + { + // lifetimes in `derive` expansions don't count (Issue #53738) + if self + .tcx + .hir() + .attrs(parent_hir_id) + .iter() + .any(|attr| attr.check_name(sym::automatically_derived)) + { + continue; } + } } let mut err = self.tcx.struct_span_lint_hir( @@ -1740,20 +1681,23 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { } let mut non_lifetime_count = 0; - let lifetimes = generics.params.iter().filter_map(|param| match param.kind { - GenericParamKind::Lifetime { .. } => { - if self.map.late_bound.contains(¶m.hir_id) { - Some(Region::late(&self.tcx.hir(), param)) - } else { - Some(Region::early(&self.tcx.hir(), &mut index, param)) + let lifetimes = generics + .params + .iter() + .filter_map(|param| match param.kind { + GenericParamKind::Lifetime { .. } => { + if self.map.late_bound.contains(¶m.hir_id) { + Some(Region::late(&self.tcx.hir(), param)) + } else { + Some(Region::early(&self.tcx.hir(), &mut index, param)) + } } - } - GenericParamKind::Type { .. } | - GenericParamKind::Const { .. } => { - non_lifetime_count += 1; - None - } - }).collect(); + GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => { + non_lifetime_count += 1; + None + } + }) + .collect(); let next_early_index = index + non_lifetime_count; let scope = Scope::Binder { @@ -1775,13 +1719,10 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { match *scope { Scope::Root => return 0, - Scope::Binder { - next_early_index, - opaque_type_parent, - .. - } if (!only_opaque_type_parent || opaque_type_parent) => + Scope::Binder { next_early_index, opaque_type_parent, .. } + if (!only_opaque_type_parent || opaque_type_parent) => { - return next_early_index + return next_early_index; } Scope::Binder { s, .. } @@ -1832,9 +1773,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { break None; } - Scope::Binder { - ref lifetimes, s, .. - } => { + Scope::Binder { ref lifetimes, s, .. } => { match lifetime_ref.name { LifetimeName::Param(param_name) => { if let Some(&def) = lifetimes.get(¶m_name.modern()) { @@ -1860,17 +1799,13 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { } else if let Some(body_id) = outermost_body { let fn_id = self.tcx.hir().body_owner(body_id); match self.tcx.hir().get(fn_id) { - Node::Item(&hir::Item { - kind: hir::ItemKind::Fn(..), - .. - }) + Node::Item(&hir::Item { kind: hir::ItemKind::Fn(..), .. }) | Node::TraitItem(&hir::TraitItem { kind: hir::TraitItemKind::Method(..), .. }) | Node::ImplItem(&hir::ImplItem { - kind: hir::ImplItemKind::Method(..), - .. + kind: hir::ImplItemKind::Method(..), .. }) => { let scope = self.tcx.hir().local_def_id(fn_id); def = Region::Free(scope, def.id().unwrap()); @@ -1890,8 +1825,9 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { E0687, "lifetimes used in `fn` or `Fn` syntax must be \ explicitly declared using `<...>` binders" - ).span_label(lifetime_ref.span, "in-band lifetime definition") - .emit(); + ) + .span_label(lifetime_ref.span, "in-band lifetime definition") + .emit(); } Region::Static @@ -1912,17 +1848,16 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { E0261, "use of undeclared lifetime name `{}`", lifetime_ref - ).span_label(lifetime_ref.span, "undeclared lifetime") - .emit(); + ) + .span_label(lifetime_ref.span, "undeclared lifetime") + .emit(); } } fn visit_segment_args(&mut self, res: Res, depth: usize, generic_args: &'tcx hir::GenericArgs) { debug!( "visit_segment_args(res={:?}, depth={:?}, generic_args={:?})", - res, - depth, - generic_args, + res, depth, generic_args, ); if generic_args.parenthesized { @@ -1957,21 +1892,17 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { // which requires object lifetime defaults. let parent_def_id = |this: &mut Self, def_id: DefId| { let def_key = this.tcx.def_key(def_id); - DefId { - krate: def_id.krate, - index: def_key.parent.expect("missing parent"), - } + DefId { krate: def_id.krate, index: def_key.parent.expect("missing parent") } }; let type_def_id = match res { - Res::Def(DefKind::AssocTy, def_id) - if depth == 1 => Some(parent_def_id(self, def_id)), - Res::Def(DefKind::Variant, def_id) - if depth == 0 => Some(parent_def_id(self, def_id)), + Res::Def(DefKind::AssocTy, def_id) if depth == 1 => Some(parent_def_id(self, def_id)), + Res::Def(DefKind::Variant, def_id) if depth == 0 => Some(parent_def_id(self, def_id)), Res::Def(DefKind::Struct, def_id) | Res::Def(DefKind::Union, def_id) | Res::Def(DefKind::Enum, def_id) | Res::Def(DefKind::TyAlias, def_id) - | Res::Def(DefKind::Trait, def_id) if depth == 0 => + | Res::Def(DefKind::Trait, def_id) + if depth == 0 => { Some(def_id) } @@ -2018,31 +1949,30 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { &map.object_lifetime_defaults[&id] } else { let tcx = self.tcx; - self.xcrate_object_lifetime_defaults - .entry(def_id) - .or_insert_with(|| { - tcx.generics_of(def_id) - .params - .iter() - .filter_map(|param| match param.kind { - GenericParamDefKind::Type { - object_lifetime_default, - .. - } => Some(object_lifetime_default), - GenericParamDefKind::Lifetime | GenericParamDefKind::Const => None, - }) - .collect() - }) + self.xcrate_object_lifetime_defaults.entry(def_id).or_insert_with(|| { + tcx.generics_of(def_id) + .params + .iter() + .filter_map(|param| match param.kind { + GenericParamDefKind::Type { object_lifetime_default, .. } => { + Some(object_lifetime_default) + } + GenericParamDefKind::Lifetime | GenericParamDefKind::Const => None, + }) + .collect() + }) }; debug!("visit_segment_args: unsubst={:?}", unsubst); unsubst .iter() .map(|set| match *set { - Set1::Empty => if in_body { - None - } else { - Some(Region::Static) - }, + Set1::Empty => { + if in_body { + None + } else { + Some(Region::Static) + } + } Set1::One(r) => { let lifetimes = generic_args.args.iter().filter_map(|arg| match arg { GenericArg::Lifetime(lt) => Some(lt), @@ -2063,10 +1993,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { GenericArg::Lifetime(_) => {} GenericArg::Type(ty) => { if let Some(<) = object_lifetime_defaults.get(i) { - let scope = Scope::ObjectLifetimeDefault { - lifetime: lt, - s: self.scope, - }; + let scope = Scope::ObjectLifetimeDefault { lifetime: lt, s: self.scope }; self.with(scope, |_, this| this.visit_ty(ty)); } else { self.visit_ty(ty); @@ -2103,22 +2030,15 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { // // This is intended to leave room for us to implement the // correct behavior in the future. - let has_lifetime_parameter = generic_args - .args - .iter() - .any(|arg| match arg { - GenericArg::Lifetime(_) => true, - _ => false, - }); + let has_lifetime_parameter = generic_args.args.iter().any(|arg| match arg { + GenericArg::Lifetime(_) => true, + _ => false, + }); // Resolve lifetimes found in the type `XX` from `Item = XX` bindings. for b in &generic_args.bindings { let scope = Scope::ObjectLifetimeDefault { - lifetime: if has_lifetime_parameter { - None - } else { - Some(Region::Static) - }, + lifetime: if has_lifetime_parameter { None } else { Some(Region::Static) }, s: self.scope, }; self.with(scope, |_, this| this.visit_assoc_type_binding(b)); @@ -2128,10 +2048,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { fn visit_fn_like_elision(&mut self, inputs: &'tcx [hir::Ty], output: Option<&'tcx hir::Ty>) { debug!("visit_fn_like_elision: enter"); let mut arg_elide = Elide::FreshLateAnon(Cell::new(0)); - let arg_scope = Scope::Elision { - elide: arg_elide.clone(), - s: self.scope, - }; + let arg_scope = Scope::Elision { elide: arg_elide.clone(), s: self.scope }; self.with(arg_scope, |_, this| { for input in inputs { this.visit_ty(input); @@ -2158,24 +2075,16 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { let parent = self.tcx.hir().get_parent_node(output.hir_id); let body = match self.tcx.hir().get(parent) { // `fn` definitions and methods. - Node::Item(&hir::Item { - kind: hir::ItemKind::Fn(.., body), - .. - }) => Some(body), + Node::Item(&hir::Item { kind: hir::ItemKind::Fn(.., body), .. }) => Some(body), Node::TraitItem(&hir::TraitItem { - kind: hir::TraitItemKind::Method(_, ref m), - .. + kind: hir::TraitItemKind::Method(_, ref m), .. }) => { - if let hir::ItemKind::Trait(.., ref trait_items) = self.tcx - .hir() - .expect_item(self.tcx.hir().get_parent_item(parent)) - .kind + if let hir::ItemKind::Trait(.., ref trait_items) = + self.tcx.hir().expect_item(self.tcx.hir().get_parent_item(parent)).kind { - assoc_item_kind = trait_items - .iter() - .find(|ti| ti.id.hir_id == parent) - .map(|ti| ti.kind); + assoc_item_kind = + trait_items.iter().find(|ti| ti.id.hir_id == parent).map(|ti| ti.kind); } match *m { hir::TraitMethod::Required(_) => None, @@ -2183,20 +2092,13 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { } } - Node::ImplItem(&hir::ImplItem { - kind: hir::ImplItemKind::Method(_, body), - .. - }) => { - if let hir::ItemKind::Impl(.., ref self_ty, ref impl_items) = self.tcx - .hir() - .expect_item(self.tcx.hir().get_parent_item(parent)) - .kind + Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Method(_, body), .. }) => { + if let hir::ItemKind::Impl(.., ref self_ty, ref impl_items) = + self.tcx.hir().expect_item(self.tcx.hir().get_parent_item(parent)).kind { impl_self = Some(self_ty); - assoc_item_kind = impl_items - .iter() - .find(|ii| ii.id.hir_id == parent) - .map(|ii| ii.kind); + assoc_item_kind = + impl_items.iter().find(|ii| ii.id.hir_id == parent).map(|ii| ii.kind); } Some(body) } @@ -2247,9 +2149,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { Res::Def(DefKind::Struct, _) | Res::Def(DefKind::Union, _) | Res::Def(DefKind::Enum, _) - | Res::PrimTy(_) => { - return res == path.res - } + | Res::PrimTy(_) => return res == path.res, _ => {} } } @@ -2285,10 +2185,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { }; visitor.visit_ty(&inputs[0]); if let Set1::One(lifetime) = visitor.lifetime { - let scope = Scope::Elision { - elide: Elide::Exact(lifetime), - s: self.scope, - }; + let scope = Scope::Elision { elide: Elide::Exact(lifetime), s: self.scope }; self.with(scope, |_, this| this.visit_ty(output)); return; } @@ -2338,10 +2235,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { debug!("visit_fn_like_elision: elide={:?}", elide); - let scope = Scope::Elision { - elide, - s: self.scope, - }; + let scope = Scope::Elision { elide, s: self.scope }; self.with(scope, |_, this| this.visit_ty(output)); debug!("visit_fn_like_elision: exit"); @@ -2411,8 +2305,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { self.have_bound_regions = true; } _ => { - self.lifetimes - .insert(lifetime.shifted_out_to_binder(self.outer_index)); + self.lifetimes.insert(lifetime.shifted_out_to_binder(self.outer_index)); } } } @@ -2533,25 +2426,17 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { let mut m = String::new(); let len = params.len(); - let elided_params: Vec<_> = params - .iter() - .cloned() - .filter(|info| info.lifetime_count > 0) - .collect(); + let elided_params: Vec<_> = + params.iter().cloned().filter(|info| info.lifetime_count > 0).collect(); let elided_len = elided_params.len(); for (i, info) in elided_params.into_iter().enumerate() { - let ElisionFailureInfo { - parent, - index, - lifetime_count: n, - have_bound_regions, - } = info; - - let help_name = if let Some(ident) = parent.and_then(|body| { - self.tcx.hir().body(body).params[index].pat.simple_ident() - }) { + let ElisionFailureInfo { parent, index, lifetime_count: n, have_bound_regions } = info; + + let help_name = if let Some(ident) = + parent.and_then(|body| self.tcx.hir().body(body).params[index].pat.simple_ident()) + { format!("`{}`", ident) } else { format!("argument {}", index + 1) @@ -2629,9 +2514,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { Scope::Body { .. } | Scope::ObjectLifetimeDefault { lifetime: None, .. } => return, - Scope::ObjectLifetimeDefault { - lifetime: Some(l), .. - } => break l, + Scope::ObjectLifetimeDefault { lifetime: Some(l), .. } => break l, } }; self.insert_lifetime(lifetime_ref, lifetime.shifted(late_depth)); @@ -2652,9 +2535,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { for (i, (lifetime_i, lifetime_i_name)) in lifetimes.iter().enumerate() { if let hir::ParamName::Plain(_) = lifetime_i_name { let name = lifetime_i_name.ident().name; - if name == kw::UnderscoreLifetime - || name == kw::StaticLifetime - { + if name == kw::UnderscoreLifetime || name == kw::StaticLifetime { let mut err = struct_span_err!( self.tcx.sess, lifetime_i.span, @@ -2679,9 +2560,10 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { E0263, "lifetime name `{}` declared twice in the same scope", lifetime_j.name.ident() - ).span_label(lifetime_j.span, "declared twice") - .span_label(lifetime_i.span, "previous declaration here") - .emit(); + ) + .span_label(lifetime_j.span, "declared twice") + .span_label(lifetime_i.span, "previous declaration here") + .emit(); } } @@ -2762,9 +2644,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { return; } - Scope::Binder { - ref lifetimes, s, .. - } => { + Scope::Binder { ref lifetimes, s, .. } => { if let Some(&def) = lifetimes.get(¶m.name.modern()) { let hir_id = self.tcx.hir().as_local_hir_id(def.id().unwrap()).unwrap(); @@ -2792,10 +2672,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { Scope::Root => break false, // Inside of items, it depends on the kind of item. - Scope::Binder { - track_lifetime_uses, - .. - } => break track_lifetime_uses, + Scope::Binder { track_lifetime_uses, .. } => break track_lifetime_uses, // Inside a body, `'_` will use an inference variable, // should be fine. @@ -2804,23 +2681,14 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { // A lifetime only used in a fn argument could as well // be replaced with `'_`, as that would generate a // fresh name, too. - Scope::Elision { - elide: Elide::FreshLateAnon(_), - .. - } => break true, + Scope::Elision { elide: Elide::FreshLateAnon(_), .. } => break true, // In the return type or other such place, `'_` is not // going to make a fresh name, so we cannot // necessarily replace a single-use lifetime with // `'_`. - Scope::Elision { - elide: Elide::Exact(_), - .. - } => break false, - Scope::Elision { - elide: Elide::Error(_), - .. - } => break false, + Scope::Elision { elide: Elide::Exact(_), .. } => break false, + Scope::Elision { elide: Elide::Error(_), .. } => break false, Scope::ObjectLifetimeDefault { s, .. } => scope = s, } @@ -2854,14 +2722,10 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { | Region::EarlyBound(_, def_id, _) => { // A lifetime declared by the user. let track_lifetime_uses = self.track_lifetime_uses(); - debug!( - "insert_lifetime: track_lifetime_uses={}", - track_lifetime_uses - ); + debug!("insert_lifetime: track_lifetime_uses={}", track_lifetime_uses); if track_lifetime_uses && !self.lifetime_uses.contains_key(&def_id) { debug!("insert_lifetime: first use of {:?}", def_id); - self.lifetime_uses - .insert(def_id, LifetimeUseSet::One(lifetime_ref)); + self.lifetime_uses.insert(def_id, LifetimeUseSet::One(lifetime_ref)); } else { debug!("insert_lifetime: many uses of {:?}", def_id); self.lifetime_uses.insert(def_id, LifetimeUseSet::Many); @@ -2894,10 +2758,7 @@ fn insert_late_bound_lifetimes( decl: &hir::FnDecl, generics: &hir::Generics, ) { - debug!( - "insert_late_bound_lifetimes(decl={:?}, generics={:?})", - decl, generics - ); + debug!("insert_late_bound_lifetimes(decl={:?}, generics={:?})", decl, generics); let mut constrained_by_input = ConstrainedCollector::default(); for arg_ty in &decl.inputs { @@ -2907,10 +2768,7 @@ fn insert_late_bound_lifetimes( let mut appears_in_output = AllCollector::default(); intravisit::walk_fn_ret_ty(&mut appears_in_output, &decl.output); - debug!( - "insert_late_bound_lifetimes: constrained_by_input={:?}", - constrained_by_input.regions - ); + debug!("insert_late_bound_lifetimes: constrained_by_input={:?}", constrained_by_input.regions); // Walk the lifetimes that appear in where clauses. // @@ -2944,8 +2802,7 @@ fn insert_late_bound_lifetimes( hir::GenericParamKind::Lifetime { .. } => { /* fall through */ } // Neither types nor consts are late-bound. - hir::GenericParamKind::Type { .. } - | hir::GenericParamKind::Const { .. } => continue, + hir::GenericParamKind::Type { .. } | hir::GenericParamKind::Const { .. } => continue, } let lt_name = hir::LifetimeName::Param(param.name.modern()); @@ -3035,13 +2892,7 @@ pub fn report_missing_lifetime_specifiers( span: Span, count: usize, ) -> DiagnosticBuilder<'_> { - struct_span_err!( - sess, - span, - E0106, - "missing lifetime specifier{}", - pluralize!(count) - ) + struct_span_err!(sess, span, E0106, "missing lifetime specifier{}", pluralize!(count)) } fn add_missing_lifetime_specifiers_label( @@ -3053,11 +2904,9 @@ fn add_missing_lifetime_specifiers_label( ) { if count > 1 { err.span_label(span, format!("expected {} lifetime parameters", count)); - } else if let (1, Some(name), Some("&")) = ( - lifetime_names.len(), - lifetime_names.iter().next(), - snippet, - ) { + } else if let (1, Some(name), Some("&")) = + (lifetime_names.len(), lifetime_names.iter().next(), snippet) + { err.span_suggestion( span, "consider using the named lifetime", diff --git a/src/librustc/traits/mod.rs b/src/librustc/traits/mod.rs index 8baedfed9d601..e6ecf1b676e85 100644 --- a/src/librustc/traits/mod.rs +++ b/src/librustc/traits/mod.rs @@ -5,73 +5,72 @@ #[allow(dead_code)] pub mod auto_trait; mod chalk_fulfill; +pub mod codegen; mod coherence; -pub mod error_reporting; mod engine; +pub mod error_reporting; mod fulfill; -mod project; mod object_safety; mod on_unimplemented; +mod project; +pub mod query; mod select; mod specialize; mod structural_impls; -pub mod codegen; mod util; -pub mod query; -use chalk_engine; use crate::hir; use crate::hir::def_id::DefId; -use crate::infer::{InferCtxt, SuppressRegionErrors}; use crate::infer::outlives::env::OutlivesEnvironment; +use crate::infer::{InferCtxt, SuppressRegionErrors}; use crate::middle::region; use crate::mir::interpret::ErrorHandled; +use crate::ty::error::{ExpectedFound, TypeError}; +use crate::ty::fold::{TypeFoldable, TypeFolder, TypeVisitor}; +use crate::ty::subst::{InternalSubsts, SubstsRef}; +use crate::ty::{self, AdtKind, GenericParamDefKind, List, ToPredicate, Ty, TyCtxt}; +use crate::util::common::ErrorReported; +use chalk_engine; use rustc_macros::HashStable; use syntax::ast; use syntax_pos::{Span, DUMMY_SP}; -use crate::ty::subst::{InternalSubsts, SubstsRef}; -use crate::ty::{self, AdtKind, List, Ty, TyCtxt, GenericParamDefKind, ToPredicate}; -use crate::ty::error::{ExpectedFound, TypeError}; -use crate::ty::fold::{TypeFolder, TypeFoldable, TypeVisitor}; -use crate::util::common::ErrorReported; use std::fmt::Debug; use std::rc::Rc; -pub use self::SelectionError::*; pub use self::FulfillmentErrorCode::*; -pub use self::Vtable::*; pub use self::ObligationCauseCode::*; +pub use self::SelectionError::*; +pub use self::Vtable::*; pub use self::coherence::{add_placeholder_note, orphan_check, overlapping_impls}; pub use self::coherence::{OrphanCheckErr, OverlapResult}; +pub use self::engine::{TraitEngine, TraitEngineExt}; pub use self::fulfill::{FulfillmentContext, PendingPredicateObligation}; -pub use self::project::MismatchedProjectionTypes; -pub use self::project::{normalize, normalize_projection_type, poly_project_and_unify_type}; -pub use self::project::{ProjectionCache, ProjectionCacheSnapshot, Reveal, Normalized}; -pub use self::object_safety::ObjectSafetyViolation; pub use self::object_safety::MethodViolationCode; +pub use self::object_safety::ObjectSafetyViolation; pub use self::on_unimplemented::{OnUnimplementedDirective, OnUnimplementedNote}; -pub use self::select::{EvaluationCache, SelectionContext, SelectionCache}; +pub use self::project::MismatchedProjectionTypes; +pub use self::project::{normalize, normalize_projection_type, poly_project_and_unify_type}; +pub use self::project::{Normalized, ProjectionCache, ProjectionCacheSnapshot, Reveal}; +pub use self::select::{EvaluationCache, SelectionCache, SelectionContext}; pub use self::select::{EvaluationResult, IntercrateAmbiguityCause, OverflowError}; -pub use self::specialize::{OverlapError, specialization_graph, translate_substs}; pub use self::specialize::find_associated_item; pub use self::specialize::specialization_graph::FutureCompatOverlapError; pub use self::specialize::specialization_graph::FutureCompatOverlapErrorKind; -pub use self::engine::{TraitEngine, TraitEngineExt}; +pub use self::specialize::{specialization_graph, translate_substs, OverlapError}; pub use self::util::{elaborate_predicates, elaborate_trait_ref, elaborate_trait_refs}; +pub use self::util::{expand_trait_aliases, TraitAliasExpander}; pub use self::util::{ - supertraits, supertrait_def_ids, transitive_bounds, Supertraits, SupertraitDefIds, + supertrait_def_ids, supertraits, transitive_bounds, SupertraitDefIds, Supertraits, }; -pub use self::util::{expand_trait_aliases, TraitAliasExpander}; pub use self::chalk_fulfill::{ - CanonicalGoal as ChalkCanonicalGoal, - FulfillmentContext as ChalkFulfillmentContext + CanonicalGoal as ChalkCanonicalGoal, FulfillmentContext as ChalkFulfillmentContext, }; -pub use self::ObligationCauseCode::*; pub use self::FulfillmentErrorCode::*; +pub use self::ObligationCauseCode::*; pub use self::SelectionError::*; pub use self::Vtable::*; @@ -79,7 +78,7 @@ pub use self::Vtable::*; #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub enum IntercrateMode { Issue43355, - Fixed + Fixed, } /// The mode that trait queries run in. @@ -140,19 +139,19 @@ pub struct ObligationCause<'tcx> { /// information. pub body_id: hir::HirId, - pub code: ObligationCauseCode<'tcx> + pub code: ObligationCauseCode<'tcx>, } impl<'tcx> ObligationCause<'tcx> { pub fn span(&self, tcx: TyCtxt<'tcx>) -> Span { match self.code { - ObligationCauseCode::CompareImplMethodObligation { .. } | - ObligationCauseCode::MainFunctionType | - ObligationCauseCode::StartFunctionType => { - tcx.sess.source_map().def_span(self.span) - } - ObligationCauseCode::MatchExpressionArm( - box MatchExpressionArmCause { arm_span, .. }) => arm_span, + ObligationCauseCode::CompareImplMethodObligation { .. } + | ObligationCauseCode::MainFunctionType + | ObligationCauseCode::StartFunctionType => tcx.sess.source_map().def_span(self.span), + ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause { + arm_span, + .. + }) => arm_span, _ => self.span, } } @@ -189,7 +188,10 @@ pub enum ObligationCauseCode<'tcx> { ObjectCastObligation(/* Object type */ Ty<'tcx>), /// Obligation incurred due to a coercion. - Coercion { source: Ty<'tcx>, target: Ty<'tcx> }, + Coercion { + source: Ty<'tcx>, + target: Ty<'tcx>, + }, /// Various cases where expressions must be `Sized` / `Copy` / etc. /// `L = X` implies that `L` is `Sized`. @@ -211,7 +213,10 @@ pub enum ObligationCauseCode<'tcx> { RepeatVec(bool), /// Types of fields (other than the last, except for packed structs) in a struct must be sized. - FieldSized { adt_kind: AdtKind, last: bool }, + FieldSized { + adt_kind: AdtKind, + last: bool, + }, /// Constant expressions must be sized. ConstSized, @@ -245,7 +250,10 @@ pub enum ObligationCauseCode<'tcx> { MatchExpressionArm(Box>), /// Computing common supertype in the pattern guard for the arms of a match expression - MatchExpressionArmPattern { span: Span, ty: Ty<'tcx> }, + MatchExpressionArmPattern { + span: Span, + ty: Ty<'tcx>, + }, /// Constants in patterns must have `Structural` type. ConstPatternStructural, @@ -322,7 +330,7 @@ pub struct DerivedObligationCause<'tcx> { parent_trait_ref: ty::PolyTraitRef<'tcx>, /// The parent trait had this cause. - parent_code: Rc> + parent_code: Rc>, } pub type Obligations<'tcx, O> = Vec>; @@ -415,7 +423,7 @@ impl<'tcx> GoalKind<'tcx> { Some(p) => p.into_goal(), None => GoalKind::Quantified( QuantifierKind::Universal, - domain_goal.map_bound(|p| tcx.mk_goal(p.into_goal())) + domain_goal.map_bound(|p| tcx.mk_goal(p.into_goal())), ), } } @@ -474,10 +482,7 @@ pub struct Environment<'tcx> { impl Environment<'tcx> { pub fn with(self, goal: G) -> InEnvironment<'tcx, G> { - InEnvironment { - environment: self, - goal, - } + InEnvironment { environment: self, goal } } } @@ -490,12 +495,14 @@ pub struct InEnvironment<'tcx, G> { pub type Selection<'tcx> = Vtable<'tcx, PredicateObligation<'tcx>>; -#[derive(Clone,Debug,TypeFoldable)] +#[derive(Clone, Debug, TypeFoldable)] pub enum SelectionError<'tcx> { Unimplemented, - OutputTypeParameterMismatch(ty::PolyTraitRef<'tcx>, - ty::PolyTraitRef<'tcx>, - ty::error::TypeError<'tcx>), + OutputTypeParameterMismatch( + ty::PolyTraitRef<'tcx>, + ty::PolyTraitRef<'tcx>, + ty::error::TypeError<'tcx>, + ), TraitNotObjectSafe(DefId), ConstEvalFailure(ErrorHandled), Overflow, @@ -514,8 +521,7 @@ pub struct FulfillmentError<'tcx> { pub enum FulfillmentErrorCode<'tcx> { CodeSelectionError(SelectionError<'tcx>), CodeProjectionError(MismatchedProjectionTypes<'tcx>), - CodeSubtypeError(ExpectedFound>, - TypeError<'tcx>), // always comes from a SubtypePredicate + CodeSubtypeError(ExpectedFound>, TypeError<'tcx>), // always comes from a SubtypePredicate CodeAmbiguity, } @@ -617,7 +623,7 @@ pub enum Vtable<'tcx, N> { pub struct VtableImplData<'tcx, N> { pub impl_def_id: DefId, pub substs: SubstsRef<'tcx>, - pub nested: Vec + pub nested: Vec, } #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)] @@ -626,7 +632,7 @@ pub struct VtableGeneratorData<'tcx, N> { pub substs: SubstsRef<'tcx>, /// Nested obligations. This can be non-empty if the generator /// signature contains associated types. - pub nested: Vec + pub nested: Vec, } #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)] @@ -635,18 +641,18 @@ pub struct VtableClosureData<'tcx, N> { pub substs: SubstsRef<'tcx>, /// Nested obligations. This can be non-empty if the closure /// signature contains associated types. - pub nested: Vec + pub nested: Vec, } #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)] pub struct VtableAutoImplData { pub trait_def_id: DefId, - pub nested: Vec + pub nested: Vec, } #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)] pub struct VtableBuiltinData { - pub nested: Vec + pub nested: Vec, } /// A vtable for some object-safe trait `Foo` automatically derived @@ -667,7 +673,7 @@ pub struct VtableObjectData<'tcx, N> { #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)] pub struct VtableFnPointerData<'tcx, N> { pub fn_ty: Ty<'tcx>, - pub nested: Vec + pub nested: Vec, } #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)] @@ -698,14 +704,13 @@ pub fn type_known_to_meet_bound_modulo_regions<'a, 'tcx>( def_id: DefId, span: Span, ) -> bool { - debug!("type_known_to_meet_bound_modulo_regions(ty={:?}, bound={:?})", - ty, - infcx.tcx.def_path_str(def_id)); + debug!( + "type_known_to_meet_bound_modulo_regions(ty={:?}, bound={:?})", + ty, + infcx.tcx.def_path_str(def_id) + ); - let trait_ref = ty::TraitRef { - def_id, - substs: infcx.tcx.mk_substs_trait(ty, &[]), - }; + let trait_ref = ty::TraitRef { def_id, substs: infcx.tcx.mk_substs_trait(ty, &[]) }; let obligation = Obligation { param_env, cause: ObligationCause::misc(span, hir::DUMMY_HIR_ID), @@ -714,8 +719,12 @@ pub fn type_known_to_meet_bound_modulo_regions<'a, 'tcx>( }; let result = infcx.predicate_must_hold_modulo_regions(&obligation); - debug!("type_known_to_meet_ty={:?} bound={} => {:?}", - ty, infcx.tcx.def_path_str(def_id), result); + debug!( + "type_known_to_meet_ty={:?} bound={} => {:?}", + ty, + infcx.tcx.def_path_str(def_id), + result + ); if result && (ty.has_infer_types() || ty.has_closure_types()) { // Because of inference "guessing", selection can sometimes claim @@ -740,16 +749,20 @@ pub fn type_known_to_meet_bound_modulo_regions<'a, 'tcx>( // assume it is move; linear is always ok. match fulfill_cx.select_all_or_error(infcx) { Ok(()) => { - debug!("type_known_to_meet_bound_modulo_regions: ty={:?} bound={} success", - ty, - infcx.tcx.def_path_str(def_id)); + debug!( + "type_known_to_meet_bound_modulo_regions: ty={:?} bound={} success", + ty, + infcx.tcx.def_path_str(def_id) + ); true } Err(e) => { - debug!("type_known_to_meet_bound_modulo_regions: ty={:?} bound={} errors={:?}", - ty, - infcx.tcx.def_path_str(def_id), - e); + debug!( + "type_known_to_meet_bound_modulo_regions: ty={:?} bound={} errors={:?}", + ty, + infcx.tcx.def_path_str(def_id), + e + ); false } } @@ -767,9 +780,7 @@ fn do_normalize_predicates<'tcx>( ) -> Result>, ErrorReported> { debug!( "do_normalize_predicates(predicates={:?}, region_context={:?}, cause={:?})", - predicates, - region_context, - cause, + predicates, region_context, cause, ); let span = cause.span; tcx.infer_ctxt().enter(|infcx| { @@ -787,19 +798,14 @@ fn do_normalize_predicates<'tcx>( // them here too, and we will remove this function when // we move over to lazy normalization *anyway*. let fulfill_cx = FulfillmentContext::new_ignoring_regions(); - let predicates = match fully_normalize( - &infcx, - fulfill_cx, - cause, - elaborated_env, - &predicates, - ) { - Ok(predicates) => predicates, - Err(errors) => { - infcx.report_fulfillment_errors(&errors, None, false); - return Err(ErrorReported) - } - }; + let predicates = + match fully_normalize(&infcx, fulfill_cx, cause, elaborated_env, &predicates) { + Ok(predicates) => predicates, + Err(errors) => { + infcx.report_fulfillment_errors(&errors, None, false); + return Err(ErrorReported); + } + }; debug!("do_normalize_predictes: normalized predicates = {:?}", predicates); @@ -827,7 +833,7 @@ fn do_normalize_predicates<'tcx>( // unconstrained variable, and it seems better not to ICE, // all things considered. tcx.sess.span_err(span, &fixup_err.to_string()); - return Err(ErrorReported) + return Err(ErrorReported); } }; if predicates.has_local_value() { @@ -862,20 +868,20 @@ pub fn normalize_param_env_or_error<'tcx>( // and errors will get reported then; so after typeck we // can be sure that no errors should occur. - debug!("normalize_param_env_or_error(region_context={:?}, unnormalized_env={:?}, cause={:?})", - region_context, unnormalized_env, cause); + debug!( + "normalize_param_env_or_error(region_context={:?}, unnormalized_env={:?}, cause={:?})", + region_context, unnormalized_env, cause + ); let mut predicates: Vec<_> = - util::elaborate_predicates(tcx, unnormalized_env.caller_bounds.to_vec()) - .collect(); + util::elaborate_predicates(tcx, unnormalized_env.caller_bounds.to_vec()).collect(); - debug!("normalize_param_env_or_error: elaborated-predicates={:?}", - predicates); + debug!("normalize_param_env_or_error: elaborated-predicates={:?}", predicates); let elaborated_env = ty::ParamEnv::new( tcx.intern_predicates(&predicates), unnormalized_env.reveal, - unnormalized_env.def_id + unnormalized_env.def_id, ); // HACK: we are trying to normalize the param-env inside *itself*. The problem is that @@ -896,25 +902,31 @@ pub fn normalize_param_env_or_error<'tcx>( // // This works fairly well because trait matching does not actually care about param-env // TypeOutlives predicates - these are normally used by regionck. - let outlives_predicates: Vec<_> = predicates.drain_filter(|predicate| { - match predicate { + let outlives_predicates: Vec<_> = predicates + .drain_filter(|predicate| match predicate { ty::Predicate::TypeOutlives(..) => true, - _ => false - } - }).collect(); + _ => false, + }) + .collect(); - debug!("normalize_param_env_or_error: predicates=(non-outlives={:?}, outlives={:?})", - predicates, outlives_predicates); - let non_outlives_predicates = - match do_normalize_predicates(tcx, region_context, cause.clone(), - elaborated_env, predicates) { - Ok(predicates) => predicates, - // An unnormalized env is better than nothing. - Err(ErrorReported) => { - debug!("normalize_param_env_or_error: errored resolving non-outlives predicates"); - return elaborated_env - } - }; + debug!( + "normalize_param_env_or_error: predicates=(non-outlives={:?}, outlives={:?})", + predicates, outlives_predicates + ); + let non_outlives_predicates = match do_normalize_predicates( + tcx, + region_context, + cause.clone(), + elaborated_env, + predicates, + ) { + Ok(predicates) => predicates, + // An unnormalized env is better than nothing. + Err(ErrorReported) => { + debug!("normalize_param_env_or_error: errored resolving non-outlives predicates"); + return elaborated_env; + } + }; debug!("normalize_param_env_or_error: non-outlives predicates={:?}", non_outlives_predicates); @@ -923,21 +935,22 @@ pub fn normalize_param_env_or_error<'tcx>( // predicates here anyway. Keeping them here anyway because it seems safer. let outlives_env: Vec<_> = non_outlives_predicates.iter().chain(&outlives_predicates).cloned().collect(); - let outlives_env = ty::ParamEnv::new( - tcx.intern_predicates(&outlives_env), - unnormalized_env.reveal, - None - ); - let outlives_predicates = - match do_normalize_predicates(tcx, region_context, cause, - outlives_env, outlives_predicates) { - Ok(predicates) => predicates, - // An unnormalized env is better than nothing. - Err(ErrorReported) => { - debug!("normalize_param_env_or_error: errored resolving outlives predicates"); - return elaborated_env - } - }; + let outlives_env = + ty::ParamEnv::new(tcx.intern_predicates(&outlives_env), unnormalized_env.reveal, None); + let outlives_predicates = match do_normalize_predicates( + tcx, + region_context, + cause, + outlives_env, + outlives_predicates, + ) { + Ok(predicates) => predicates, + // An unnormalized env is better than nothing. + Err(ErrorReported) => { + debug!("normalize_param_env_or_error: errored resolving outlives predicates"); + return elaborated_env; + } + }; debug!("normalize_param_env_or_error: outlives predicates={:?}", outlives_predicates); let mut predicates = non_outlives_predicates; @@ -946,7 +959,7 @@ pub fn normalize_param_env_or_error<'tcx>( ty::ParamEnv::new( tcx.intern_predicates(&predicates), unnormalized_env.reveal, - unnormalized_env.def_id + unnormalized_env.def_id, ) } @@ -964,9 +977,10 @@ where let selcx = &mut SelectionContext::new(infcx); let Normalized { value: normalized_value, obligations } = project::normalize(selcx, param_env, cause, value); - debug!("fully_normalize: normalized_value={:?} obligations={:?}", - normalized_value, - obligations); + debug!( + "fully_normalize: normalized_value={:?} obligations={:?}", + normalized_value, obligations + ); for obligation in obligations { fulfill_cx.register_predicate_obligation(selcx.infcx(), obligation); } @@ -987,8 +1001,7 @@ fn normalize_and_test_predicates<'tcx>( tcx: TyCtxt<'tcx>, predicates: Vec>, ) -> bool { - debug!("normalize_and_test_predicates(predicates={:?})", - predicates); + debug!("normalize_and_test_predicates(predicates={:?})", predicates); let result = tcx.infer_ctxt().enter(|infcx| { let param_env = ty::ParamEnv::reveal_all(); @@ -1007,8 +1020,7 @@ fn normalize_and_test_predicates<'tcx>( fulfill_cx.select_all_or_error(&infcx).is_ok() }); - debug!("normalize_and_test_predicates(predicates={:?}) = {:?}", - predicates, result); + debug!("normalize_and_test_predicates(predicates={:?}) = {:?}", predicates, result); result } @@ -1016,14 +1028,12 @@ fn substitute_normalize_and_test_predicates<'tcx>( tcx: TyCtxt<'tcx>, key: (DefId, SubstsRef<'tcx>), ) -> bool { - debug!("substitute_normalize_and_test_predicates(key={:?})", - key); + debug!("substitute_normalize_and_test_predicates(key={:?})", key); let predicates = tcx.predicates_of(key.0).instantiate(tcx, key.1).predicates; let result = normalize_and_test_predicates(tcx, predicates); - debug!("substitute_normalize_and_test_predicates(key={:?}) = {:?}", - key, result); + debug!("substitute_normalize_and_test_predicates(key={:?}) = {:?}", key, result); result } @@ -1036,100 +1046,98 @@ fn vtable_methods<'tcx>( ) -> &'tcx [Option<(DefId, SubstsRef<'tcx>)>] { debug!("vtable_methods({:?})", trait_ref); - tcx.arena.alloc_from_iter( - supertraits(tcx, trait_ref).flat_map(move |trait_ref| { - let trait_methods = tcx.associated_items(trait_ref.def_id()) - .filter(|item| item.kind == ty::AssocKind::Method); - - // Now list each method's DefId and InternalSubsts (for within its trait). - // If the method can never be called from this object, produce None. - trait_methods.map(move |trait_method| { - debug!("vtable_methods: trait_method={:?}", trait_method); - let def_id = trait_method.def_id; - - // Some methods cannot be called on an object; skip those. - if !tcx.is_vtable_safe_method(trait_ref.def_id(), &trait_method) { - debug!("vtable_methods: not vtable safe"); - return None; - } - - // The method may have some early-bound lifetimes; add regions for those. - let substs = trait_ref.map_bound(|trait_ref| - InternalSubsts::for_item(tcx, def_id, |param, _| - match param.kind { - GenericParamDefKind::Lifetime => tcx.lifetimes.re_erased.into(), - GenericParamDefKind::Type { .. } | - GenericParamDefKind::Const => { - trait_ref.substs[param.index as usize] - } - } - ) - ); - - // The trait type may have higher-ranked lifetimes in it; - // erase them if they appear, so that we get the type - // at some particular call site. - let substs = tcx.normalize_erasing_late_bound_regions( - ty::ParamEnv::reveal_all(), - &substs - ); + tcx.arena.alloc_from_iter(supertraits(tcx, trait_ref).flat_map(move |trait_ref| { + let trait_methods = tcx + .associated_items(trait_ref.def_id()) + .filter(|item| item.kind == ty::AssocKind::Method); + + // Now list each method's DefId and InternalSubsts (for within its trait). + // If the method can never be called from this object, produce None. + trait_methods.map(move |trait_method| { + debug!("vtable_methods: trait_method={:?}", trait_method); + let def_id = trait_method.def_id; + + // Some methods cannot be called on an object; skip those. + if !tcx.is_vtable_safe_method(trait_ref.def_id(), &trait_method) { + debug!("vtable_methods: not vtable safe"); + return None; + } - // It's possible that the method relies on where-clauses that - // do not hold for this particular set of type parameters. - // Note that this method could then never be called, so we - // do not want to try and codegen it, in that case (see #23435). - let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs); - if !normalize_and_test_predicates(tcx, predicates.predicates) { - debug!("vtable_methods: predicates do not hold"); - return None; - } + // The method may have some early-bound lifetimes; add regions for those. + let substs = trait_ref.map_bound(|trait_ref| { + InternalSubsts::for_item(tcx, def_id, |param, _| match param.kind { + GenericParamDefKind::Lifetime => tcx.lifetimes.re_erased.into(), + GenericParamDefKind::Type { .. } | GenericParamDefKind::Const => { + trait_ref.substs[param.index as usize] + } + }) + }); + + // The trait type may have higher-ranked lifetimes in it; + // erase them if they appear, so that we get the type + // at some particular call site. + let substs = + tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &substs); + + // It's possible that the method relies on where-clauses that + // do not hold for this particular set of type parameters. + // Note that this method could then never be called, so we + // do not want to try and codegen it, in that case (see #23435). + let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs); + if !normalize_and_test_predicates(tcx, predicates.predicates) { + debug!("vtable_methods: predicates do not hold"); + return None; + } - Some((def_id, substs)) - }) + Some((def_id, substs)) }) - ) + })) } impl<'tcx, O> Obligation<'tcx, O> { - pub fn new(cause: ObligationCause<'tcx>, - param_env: ty::ParamEnv<'tcx>, - predicate: O) - -> Obligation<'tcx, O> - { + pub fn new( + cause: ObligationCause<'tcx>, + param_env: ty::ParamEnv<'tcx>, + predicate: O, + ) -> Obligation<'tcx, O> { Obligation { cause, param_env, recursion_depth: 0, predicate } } - fn with_depth(cause: ObligationCause<'tcx>, - recursion_depth: usize, - param_env: ty::ParamEnv<'tcx>, - predicate: O) - -> Obligation<'tcx, O> - { + fn with_depth( + cause: ObligationCause<'tcx>, + recursion_depth: usize, + param_env: ty::ParamEnv<'tcx>, + predicate: O, + ) -> Obligation<'tcx, O> { Obligation { cause, param_env, recursion_depth, predicate } } - pub fn misc(span: Span, - body_id: hir::HirId, - param_env: ty::ParamEnv<'tcx>, - trait_ref: O) - -> Obligation<'tcx, O> { + pub fn misc( + span: Span, + body_id: hir::HirId, + param_env: ty::ParamEnv<'tcx>, + trait_ref: O, + ) -> Obligation<'tcx, O> { Obligation::new(ObligationCause::misc(span, body_id), param_env, trait_ref) } - pub fn with

(&self, value: P) -> Obligation<'tcx,P> { - Obligation { cause: self.cause.clone(), - param_env: self.param_env, - recursion_depth: self.recursion_depth, - predicate: value } + pub fn with

(&self, value: P) -> Obligation<'tcx, P> { + Obligation { + cause: self.cause.clone(), + param_env: self.param_env, + recursion_depth: self.recursion_depth, + predicate: value, + } } } impl<'tcx> ObligationCause<'tcx> { #[inline] - pub fn new(span: Span, - body_id: hir::HirId, - code: ObligationCauseCode<'tcx>) - -> ObligationCause<'tcx> { + pub fn new( + span: Span, + body_id: hir::HirId, + code: ObligationCauseCode<'tcx>, + ) -> ObligationCause<'tcx> { ObligationCause { span, body_id, code } } @@ -1157,7 +1165,10 @@ impl<'tcx, N> Vtable<'tcx, N> { } } - pub fn map(self, f: F) -> Vtable<'tcx, M> where F: FnMut(N) -> M { + pub fn map(self, f: F) -> Vtable<'tcx, M> + where + F: FnMut(N) -> M, + { match self { VtableImpl(i) => VtableImpl(VtableImplData { impl_def_id: i.impl_def_id, @@ -1165,9 +1176,9 @@ impl<'tcx, N> Vtable<'tcx, N> { nested: i.nested.into_iter().map(f).collect(), }), VtableParam(n) => VtableParam(n.into_iter().map(f).collect()), - VtableBuiltin(i) => VtableBuiltin(VtableBuiltinData { - nested: i.nested.into_iter().map(f).collect(), - }), + VtableBuiltin(i) => { + VtableBuiltin(VtableBuiltinData { nested: i.nested.into_iter().map(f).collect() }) + } VtableObject(o) => VtableObject(VtableObjectData { upcast_trait_ref: o.upcast_trait_ref, vtable_base: o.vtable_base, @@ -1201,10 +1212,10 @@ impl<'tcx, N> Vtable<'tcx, N> { } impl<'tcx> FulfillmentError<'tcx> { - fn new(obligation: PredicateObligation<'tcx>, - code: FulfillmentErrorCode<'tcx>) - -> FulfillmentError<'tcx> - { + fn new( + obligation: PredicateObligation<'tcx>, + code: FulfillmentErrorCode<'tcx>, + ) -> FulfillmentError<'tcx> { FulfillmentError { obligation: obligation, code: code, points_at_arg_span: false } } } diff --git a/src/librustc/ty/constness.rs b/src/librustc/ty/constness.rs index 7fe950ef7b7f6..35d5bdaf1820c 100644 --- a/src/librustc/ty/constness.rs +++ b/src/librustc/ty/constness.rs @@ -1,41 +1,38 @@ -use crate::ty::query::Providers; -use crate::hir::def_id::DefId; use crate::hir; +use crate::hir::def_id::DefId; +use crate::hir::map::blocks::FnLikeNode; +use crate::ty::query::Providers; use crate::ty::TyCtxt; -use syntax_pos::symbol::Symbol; use rustc_target::spec::abi::Abi; -use crate::hir::map::blocks::FnLikeNode; use syntax::attr; +use syntax_pos::symbol::Symbol; impl<'tcx> TyCtxt<'tcx> { /// Whether the `def_id` counts as const fn in your current crate, considering all active /// feature gates pub fn is_const_fn(self, def_id: DefId) -> bool { - self.is_const_fn_raw(def_id) && match self.is_unstable_const_fn(def_id) { - Some(feature_name) => { - // has a `rustc_const_unstable` attribute, check whether the user enabled the - // corresponding feature gate. - self.features() - .declared_lib_features - .iter() - .any(|&(sym, _)| sym == feature_name) - }, - // functions without const stability are either stable user written - // const fn or the user is using feature gates and we thus don't - // care what they do - None => true, - } + self.is_const_fn_raw(def_id) + && match self.is_unstable_const_fn(def_id) { + Some(feature_name) => { + // has a `rustc_const_unstable` attribute, check whether the user enabled the + // corresponding feature gate. + self.features() + .declared_lib_features + .iter() + .any(|&(sym, _)| sym == feature_name) + } + // functions without const stability are either stable user written + // const fn or the user is using feature gates and we thus don't + // care what they do + None => true, + } } /// Whether the `def_id` is an unstable const fn and what feature gate is necessary to enable it pub fn is_unstable_const_fn(self, def_id: DefId) -> Option { if self.is_const_fn_raw(def_id) { let const_stab = self.lookup_const_stability(def_id)?; - if const_stab.level.is_unstable() { - Some(const_stab.feature) - } else { - None - } + if const_stab.level.is_unstable() { Some(const_stab.feature) } else { None } } else { None } @@ -54,29 +51,31 @@ impl<'tcx> TyCtxt<'tcx> { match self.lookup_const_stability(def_id) { // `rustc_const_unstable` functions don't need to conform. Some(&attr::ConstStability { ref level, .. }) if level.is_unstable() => false, - None => if let Some(stab) = self.lookup_stability(def_id) { - if stab.level.is_stable() { - self.sess.span_err( - self.def_span(def_id), - "stable const functions must have either `rustc_const_stable` or \ + None => { + if let Some(stab) = self.lookup_stability(def_id) { + if stab.level.is_stable() { + self.sess.span_err( + self.def_span(def_id), + "stable const functions must have either `rustc_const_stable` or \ `rustc_const_unstable` attribute", - ); - // While we errored above, because we don't know if we need to conform, we - // err on the "safe" side and require min_const_fn. - true + ); + // While we errored above, because we don't know if we need to conform, we + // err on the "safe" side and require min_const_fn. + true + } else { + // Unstable functions need not conform to min_const_fn. + false + } } else { - // Unstable functions need not conform to min_const_fn. - false + // Internal functions are forced to conform to min_const_fn. + // Annotate the internal function with a const stability attribute if + // you need to use unstable features. + // Note: this is an arbitrary choice that does not affect stability or const + // safety or anything, it just changes whether we need to annotate some + // internal functions with `rustc_const_stable` or with `rustc_const_unstable` + true } - } else { - // Internal functions are forced to conform to min_const_fn. - // Annotate the internal function with a const stability attribute if - // you need to use unstable features. - // Note: this is an arbitrary choice that does not affect stability or const - // safety or anything, it just changes whether we need to annotate some - // internal functions with `rustc_const_stable` or with `rustc_const_unstable` - true - }, + } // Everything else needs to conform, because it would be callable from // other `min_const_fn` functions. _ => true, @@ -88,23 +87,25 @@ impl<'tcx> TyCtxt<'tcx> { } } - pub fn provide(providers: &mut Providers<'_>) { /// Const evaluability whitelist is here to check evaluability at the /// top level beforehand. fn is_const_intrinsic(tcx: TyCtxt<'_>, def_id: DefId) -> Option { match tcx.fn_sig(def_id).abi() { - Abi::RustIntrinsic | - Abi::PlatformIntrinsic => Some(tcx.lookup_const_stability(def_id).is_some()), - _ => None + Abi::RustIntrinsic | Abi::PlatformIntrinsic => { + Some(tcx.lookup_const_stability(def_id).is_some()) + } + _ => None, } } /// Checks whether the function has a `const` modifier or, in case it is an intrinsic, whether /// said intrinsic is on the whitelist for being const callable. fn is_const_fn_raw(tcx: TyCtxt<'_>, def_id: DefId) -> bool { - let hir_id = tcx.hir().as_local_hir_id(def_id) - .expect("Non-local call to local provider is_const_fn"); + let hir_id = tcx + .hir() + .as_local_hir_id(def_id) + .expect("Non-local call to local provider is_const_fn"); let node = tcx.hir().get(hir_id); @@ -120,27 +121,30 @@ pub fn provide(providers: &mut Providers<'_>) { } fn is_promotable_const_fn(tcx: TyCtxt<'_>, def_id: DefId) -> bool { - tcx.is_const_fn(def_id) && match tcx.lookup_const_stability(def_id) { - Some(stab) => { - if cfg!(debug_assertions) && stab.promotable { - let sig = tcx.fn_sig(def_id); - assert_eq!( - sig.unsafety(), - hir::Unsafety::Normal, - "don't mark const unsafe fns as promotable", - // https://github.com/rust-lang/rust/pull/53851#issuecomment-418760682 - ); + tcx.is_const_fn(def_id) + && match tcx.lookup_const_stability(def_id) { + Some(stab) => { + if cfg!(debug_assertions) && stab.promotable { + let sig = tcx.fn_sig(def_id); + assert_eq!( + sig.unsafety(), + hir::Unsafety::Normal, + "don't mark const unsafe fns as promotable", + // https://github.com/rust-lang/rust/pull/53851#issuecomment-418760682 + ); + } + stab.promotable } - stab.promotable - }, - None => false, - } + None => false, + } } fn const_fn_is_allowed_fn_ptr(tcx: TyCtxt<'_>, def_id: DefId) -> bool { - tcx.is_const_fn(def_id) && - tcx.lookup_const_stability(def_id) - .map(|stab| stab.allow_const_fn_ptr).unwrap_or(false) + tcx.is_const_fn(def_id) + && tcx + .lookup_const_stability(def_id) + .map(|stab| stab.allow_const_fn_ptr) + .unwrap_or(false) } *providers = Providers { diff --git a/src/librustc/ty/context.rs b/src/librustc/ty/context.rs index e36b11ae0050c..39341de6367f1 100644 --- a/src/librustc/ty/context.rs +++ b/src/librustc/ty/context.rs @@ -1,81 +1,82 @@ -// ignore-tidy-filelength //! Type context book-keeping. use crate::arena::Arena; use crate::dep_graph::DepGraph; -use crate::dep_graph::{self, DepNode, DepConstructor}; -use crate::session::Session; -use crate::session::config::{BorrowckMode, OutputFilenames}; -use crate::session::config::CrateType; -use crate::middle; -use crate::middle::lang_items::PanicLocationLangItem; -use crate::hir::{self, TraitCandidate, HirId, ItemKind, ItemLocalId, Node}; -use crate::hir::def::{Res, DefKind, Export}; +use crate::dep_graph::{self, DepConstructor, DepNode}; +use crate::hir::def::{DefKind, Export, Res}; use crate::hir::def_id::{CrateNum, DefId, DefIndex, LOCAL_CRATE}; use crate::hir::map as hir_map; use crate::hir::map::DefPathHash; -use crate::lint::{self, Lint}; -use crate::ich::{StableHashingContext, NodeIdHashingMode}; +use crate::hir::{self, HirId, ItemKind, ItemLocalId, Node, TraitCandidate}; +use crate::ich::{NodeIdHashingMode, StableHashingContext}; use crate::infer::canonical::{Canonical, CanonicalVarInfo, CanonicalVarInfos}; use crate::infer::outlives::free_region_map::FreeRegionMap; +use crate::lint::{self, Lint}; +use crate::middle; use crate::middle::cstore::CrateStoreDyn; use crate::middle::cstore::EncodedMetadata; use crate::middle::lang_items; +use crate::middle::lang_items::PanicLocationLangItem; use crate::middle::resolve_lifetime::{self, ObjectLifetimeDefault}; use crate::middle::stability; -use crate::mir::{BodyAndCache, Field, interpret, Local, Place, PlaceElem, ProjectionKind, Promoted}; -use crate::mir::interpret::{ConstValue, Allocation, Scalar}; -use crate::ty::subst::{GenericArg, InternalSubsts, SubstsRef, Subst}; -use crate::ty::ReprOptions; +use crate::mir::interpret::{Allocation, ConstValue, Scalar}; +use crate::mir::{ + interpret, BodyAndCache, Field, Local, Place, PlaceElem, ProjectionKind, Promoted, +}; +use crate::session::config::CrateType; +use crate::session::config::{BorrowckMode, OutputFilenames}; +use crate::session::Session; use crate::traits; -use crate::traits::{Clause, Clauses, GoalKind, Goal, Goals}; -use crate::ty::{self, DefIdTree, Ty, TypeAndMut}; -use crate::ty::{TyS, TyKind, List}; -use crate::ty::{AdtKind, AdtDef, Region, Const}; -use crate::ty::{PolyFnSig, InferTy, ParamTy, ProjectionTy, ExistentialPredicate, Predicate}; -use crate::ty::RegionKind; -use crate::ty::{TyVar, TyVid, IntVar, IntVid, FloatVar, FloatVid, ConstVid}; -use crate::ty::TyKind::*; -use crate::ty::{InferConst, ParamConst}; -use crate::ty::GenericParamDefKind; +use crate::traits::{Clause, Clauses, Goal, GoalKind, Goals}; use crate::ty::layout::{LayoutDetails, TargetDataLayout, VariantIdx}; use crate::ty::query; use crate::ty::steal::Steal; -use crate::ty::subst::{UserSubsts, GenericArgKind}; -use crate::ty::{BoundVar, BindingMode}; +use crate::ty::subst::{GenericArg, InternalSubsts, Subst, SubstsRef}; +use crate::ty::subst::{GenericArgKind, UserSubsts}; use crate::ty::CanonicalPolyFnSig; +use crate::ty::GenericParamDefKind; +use crate::ty::RegionKind; +use crate::ty::ReprOptions; +use crate::ty::TyKind::*; +use crate::ty::{self, DefIdTree, Ty, TypeAndMut}; +use crate::ty::{AdtDef, AdtKind, Const, Region}; +use crate::ty::{BindingMode, BoundVar}; +use crate::ty::{ConstVid, FloatVar, FloatVid, IntVar, IntVid, TyVar, TyVid}; +use crate::ty::{ExistentialPredicate, InferTy, ParamTy, PolyFnSig, Predicate, ProjectionTy}; +use crate::ty::{InferConst, ParamConst}; +use crate::ty::{List, TyKind, TyS}; use crate::util::common::ErrorReported; use crate::util::nodemap::{DefIdMap, DefIdSet, ItemLocalMap, ItemLocalSet, NodeMap}; use crate::util::nodemap::{FxHashMap, FxHashSet}; -use errors::DiagnosticBuilder; use arena::SyncDroplessArena; -use smallvec::SmallVec; +use errors::DiagnosticBuilder; use rustc_data_structures::profiling::SelfProfilerRef; +use rustc_data_structures::sharded::ShardedHashMap; use rustc_data_structures::stable_hasher::{ - HashStable, StableHasher, StableVec, hash_stable_hashmap, + hash_stable_hashmap, HashStable, StableHasher, StableVec, }; +use rustc_data_structures::sync::{Lock, Lrc, WorkerLocal}; use rustc_index::vec::{Idx, IndexVec}; -use rustc_data_structures::sharded::ShardedHashMap; -use rustc_data_structures::sync::{Lrc, Lock, WorkerLocal}; +use rustc_macros::HashStable; +use rustc_target::spec::abi; +use smallvec::SmallVec; use std::any::Any; use std::borrow::Borrow; use std::cmp::Ordering; use std::collections::hash_map::{self, Entry}; -use std::hash::{Hash, Hasher}; use std::fmt; -use std::mem; -use std::ops::{Deref, Bound}; +use std::hash::{Hash, Hasher}; use std::iter; +use std::mem; +use std::ops::{Bound, Deref}; use std::sync::Arc; -use rustc_target::spec::abi; -use rustc_macros::HashStable; use syntax::ast; use syntax::attr; +use syntax::expand::allocator::AllocatorKind; use syntax::source_map::MultiSpan; -use syntax::symbol::{Symbol, kw, sym}; +use syntax::symbol::{kw, sym, Symbol}; use syntax_pos::Span; -use syntax::expand::allocator::AllocatorKind; pub struct AllArenas { pub interner: SyncDroplessArena, @@ -83,9 +84,7 @@ pub struct AllArenas { impl AllArenas { pub fn new() -> Self { - AllArenas { - interner: SyncDroplessArena::default(), - } + AllArenas { interner: SyncDroplessArena::default() } } } @@ -135,20 +134,20 @@ impl<'tcx> CtxtInterners<'tcx> { /// Interns a type. #[allow(rustc::usage_of_ty_tykind)] #[inline(never)] - fn intern_ty(&self, - kind: TyKind<'tcx> - ) -> Ty<'tcx> { - self.type_.intern(kind, |kind| { - let flags = super::flags::FlagComputation::for_kind(&kind); - - let ty_struct = TyS { - kind, - flags: flags.flags, - outer_exclusive_binder: flags.outer_exclusive_binder, - }; + fn intern_ty(&self, kind: TyKind<'tcx>) -> Ty<'tcx> { + self.type_ + .intern(kind, |kind| { + let flags = super::flags::FlagComputation::for_kind(&kind); + + let ty_struct = TyS { + kind, + flags: flags.flags, + outer_exclusive_binder: flags.outer_exclusive_binder, + }; - Interned(self.arena.alloc(ty_struct)) - }).0 + Interned(self.arena.alloc(ty_struct)) + }) + .0 } } @@ -192,7 +191,7 @@ pub struct CommonConsts<'tcx> { pub struct LocalTableInContext<'a, V> { local_id_root: Option, - data: &'a ItemLocalMap + data: &'a ItemLocalMap, } /// Validate that the given HirId (respectively its `local_id` part) can be @@ -202,17 +201,21 @@ pub struct LocalTableInContext<'a, V> { /// 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(local_id_root: Option, - hir_id: hir::HirId, - mut_access: bool) { +fn validate_hir_id_for_typeck_tables( + local_id_root: Option, + hir_id: hir::HirId, + mut_access: bool, +) { if let Some(local_id_root) = local_id_root { if hir_id.owner != local_id_root.index { ty::tls::with(|tcx| { - bug!("node {} with HirId::owner {:?} cannot be placed in \ + bug!( + "node {} with HirId::owner {:?} cannot be placed in \ TypeckTables with local_id_root {:?}", - tcx.hir().node_to_string(hir_id), - DefId::local(hir_id.owner), - local_id_root) + tcx.hir().node_to_string(hir_id), + DefId::local(hir_id.owner), + local_id_root + ) }); } } else { @@ -253,7 +256,7 @@ impl<'a, V> ::std::ops::Index for LocalTableInContext<'a, V> { pub struct LocalTableInContextMut<'a, V> { local_id_root: Option, - data: &'a mut ItemLocalMap + data: &'a mut ItemLocalMap, } impl<'a, V> LocalTableInContextMut<'a, V> { @@ -464,7 +467,8 @@ impl<'tcx> TypeckTables<'tcx> { pub fn qpath_res(&self, qpath: &hir::QPath, id: hir::HirId) -> Res { match *qpath { hir::QPath::Resolved(_, ref path) => path.res, - hir::QPath::TypeRelative(..) => self.type_dependent_def(id) + hir::QPath::TypeRelative(..) => self + .type_dependent_def(id) .map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)), } } @@ -472,10 +476,7 @@ impl<'tcx> TypeckTables<'tcx> { pub fn type_dependent_defs( &self, ) -> LocalTableInContext<'_, Result<(DefKind, DefId), ErrorReported>> { - LocalTableInContext { - local_id_root: self.local_id_root, - data: &self.type_dependent_defs - } + LocalTableInContext { local_id_root: self.local_id_root, data: &self.type_dependent_defs } } pub fn type_dependent_def(&self, id: HirId) -> Option<(DefKind, DefId)> { @@ -492,61 +493,43 @@ impl<'tcx> TypeckTables<'tcx> { ) -> LocalTableInContextMut<'_, Result<(DefKind, DefId), ErrorReported>> { LocalTableInContextMut { local_id_root: self.local_id_root, - data: &mut self.type_dependent_defs + data: &mut self.type_dependent_defs, } } pub fn field_indices(&self) -> LocalTableInContext<'_, usize> { - LocalTableInContext { - local_id_root: self.local_id_root, - data: &self.field_indices - } + LocalTableInContext { local_id_root: self.local_id_root, data: &self.field_indices } } pub fn field_indices_mut(&mut self) -> LocalTableInContextMut<'_, usize> { - LocalTableInContextMut { - local_id_root: self.local_id_root, - data: &mut self.field_indices - } + LocalTableInContextMut { local_id_root: self.local_id_root, data: &mut self.field_indices } } - pub fn user_provided_types( - &self - ) -> LocalTableInContext<'_, CanonicalUserType<'tcx>> { - LocalTableInContext { - local_id_root: self.local_id_root, - data: &self.user_provided_types - } + pub fn user_provided_types(&self) -> LocalTableInContext<'_, CanonicalUserType<'tcx>> { + LocalTableInContext { local_id_root: self.local_id_root, data: &self.user_provided_types } } pub fn user_provided_types_mut( - &mut self + &mut self, ) -> LocalTableInContextMut<'_, CanonicalUserType<'tcx>> { LocalTableInContextMut { local_id_root: self.local_id_root, - data: &mut self.user_provided_types + data: &mut self.user_provided_types, } } pub fn node_types(&self) -> LocalTableInContext<'_, Ty<'tcx>> { - LocalTableInContext { - local_id_root: self.local_id_root, - data: &self.node_types - } + LocalTableInContext { local_id_root: self.local_id_root, data: &self.node_types } } pub fn node_types_mut(&mut self) -> LocalTableInContextMut<'_, Ty<'tcx>> { - LocalTableInContextMut { - local_id_root: self.local_id_root, - data: &mut self.node_types - } + LocalTableInContextMut { local_id_root: self.local_id_root, data: &mut self.node_types } } pub fn node_type(&self, id: hir::HirId) -> Ty<'tcx> { - self.node_type_opt(id).unwrap_or_else(|| - bug!("node_type: no type for node `{}`", - tls::with(|tcx| tcx.hir().node_to_string(id))) - ) + self.node_type_opt(id).unwrap_or_else(|| { + bug!("node_type: no type for node `{}`", tls::with(|tcx| tcx.hir().node_to_string(id))) + }) } pub fn node_type_opt(&self, id: hir::HirId) -> Option> { @@ -555,10 +538,7 @@ impl<'tcx> TypeckTables<'tcx> { } pub fn node_substs_mut(&mut self) -> LocalTableInContextMut<'_, SubstsRef<'tcx>> { - LocalTableInContextMut { - local_id_root: self.local_id_root, - data: &mut self.node_substs - } + LocalTableInContextMut { local_id_root: self.local_id_root, data: &mut self.node_substs } } pub fn node_substs(&self, id: hir::HirId) -> SubstsRef<'tcx> { @@ -600,22 +580,16 @@ impl<'tcx> TypeckTables<'tcx> { } pub fn adjustments(&self) -> LocalTableInContext<'_, Vec>> { - LocalTableInContext { - local_id_root: self.local_id_root, - data: &self.adjustments - } + LocalTableInContext { local_id_root: self.local_id_root, data: &self.adjustments } } - pub fn adjustments_mut(&mut self) - -> LocalTableInContextMut<'_, Vec>> { - LocalTableInContextMut { - local_id_root: self.local_id_root, - data: &mut self.adjustments - } + pub fn adjustments_mut( + &mut self, + ) -> LocalTableInContextMut<'_, Vec>> { + LocalTableInContextMut { local_id_root: self.local_id_root, data: &mut self.adjustments } } - pub fn expr_adjustments(&self, expr: &hir::Expr) - -> &[ty::adjustment::Adjustment<'tcx>] { + pub fn expr_adjustments(&self, expr: &hir::Expr) -> &[ty::adjustment::Adjustment<'tcx>] { validate_hir_id_for_typeck_tables(self.local_id_root, expr.hir_id, false); self.adjustments.get(&expr.hir_id.local_id).map_or(&[], |a| &a[..]) } @@ -623,16 +597,11 @@ impl<'tcx> TypeckTables<'tcx> { /// Returns the type of `expr`, considering any `Adjustment` /// entry recorded for that expression. pub fn expr_ty_adjusted(&self, expr: &hir::Expr) -> Ty<'tcx> { - self.expr_adjustments(expr) - .last() - .map_or_else(|| self.expr_ty(expr), |adj| adj.target) + self.expr_adjustments(expr).last().map_or_else(|| self.expr_ty(expr), |adj| adj.target) } pub fn expr_ty_adjusted_opt(&self, expr: &hir::Expr) -> Option> { - self.expr_adjustments(expr) - .last() - .map(|adj| adj.target) - .or_else(|| self.expr_ty_opt(expr)) + self.expr_adjustments(expr).last().map(|adj| adj.target).or_else(|| self.expr_ty_opt(expr)) } pub fn is_method_call(&self, expr: &hir::Expr) -> bool { @@ -644,7 +613,7 @@ impl<'tcx> TypeckTables<'tcx> { match self.type_dependent_defs().get(expr.hir_id) { Some(Ok((DefKind::Method, _))) => true, - _ => false + _ => false, } } @@ -656,29 +625,21 @@ impl<'tcx> TypeckTables<'tcx> { } pub fn pat_binding_modes(&self) -> LocalTableInContext<'_, BindingMode> { - LocalTableInContext { - local_id_root: self.local_id_root, - data: &self.pat_binding_modes - } + LocalTableInContext { local_id_root: self.local_id_root, data: &self.pat_binding_modes } } - pub fn pat_binding_modes_mut(&mut self) - -> LocalTableInContextMut<'_, BindingMode> { + pub fn pat_binding_modes_mut(&mut self) -> LocalTableInContextMut<'_, BindingMode> { LocalTableInContextMut { local_id_root: self.local_id_root, - data: &mut self.pat_binding_modes + data: &mut self.pat_binding_modes, } } pub fn pat_adjustments(&self) -> LocalTableInContext<'_, Vec>> { - LocalTableInContext { - local_id_root: self.local_id_root, - data: &self.pat_adjustments, - } + LocalTableInContext { local_id_root: self.local_id_root, data: &self.pat_adjustments } } - pub fn pat_adjustments_mut(&mut self) - -> LocalTableInContextMut<'_, Vec>> { + pub fn pat_adjustments_mut(&mut self) -> LocalTableInContextMut<'_, Vec>> { LocalTableInContextMut { local_id_root: self.local_id_root, data: &mut self.pat_adjustments, @@ -690,44 +651,35 @@ impl<'tcx> TypeckTables<'tcx> { } pub fn closure_kind_origins(&self) -> LocalTableInContext<'_, (Span, ast::Name)> { - LocalTableInContext { - local_id_root: self.local_id_root, - data: &self.closure_kind_origins - } + LocalTableInContext { local_id_root: self.local_id_root, data: &self.closure_kind_origins } } pub fn closure_kind_origins_mut(&mut self) -> LocalTableInContextMut<'_, (Span, ast::Name)> { LocalTableInContextMut { local_id_root: self.local_id_root, - data: &mut self.closure_kind_origins + data: &mut self.closure_kind_origins, } } pub fn liberated_fn_sigs(&self) -> LocalTableInContext<'_, ty::FnSig<'tcx>> { - LocalTableInContext { - local_id_root: self.local_id_root, - data: &self.liberated_fn_sigs - } + LocalTableInContext { local_id_root: self.local_id_root, data: &self.liberated_fn_sigs } } pub fn liberated_fn_sigs_mut(&mut self) -> LocalTableInContextMut<'_, ty::FnSig<'tcx>> { LocalTableInContextMut { local_id_root: self.local_id_root, - data: &mut self.liberated_fn_sigs + data: &mut self.liberated_fn_sigs, } } pub fn fru_field_types(&self) -> LocalTableInContext<'_, Vec>> { - LocalTableInContext { - local_id_root: self.local_id_root, - data: &self.fru_field_types - } + LocalTableInContext { local_id_root: self.local_id_root, data: &self.fru_field_types } } pub fn fru_field_types_mut(&mut self) -> LocalTableInContextMut<'_, Vec>> { LocalTableInContextMut { local_id_root: self.local_id_root, - data: &mut self.fru_field_types + data: &mut self.fru_field_types, } } @@ -743,7 +695,6 @@ impl<'tcx> TypeckTables<'tcx> { pub fn coercion_casts(&self) -> &ItemLocalSet { &self.coercion_casts } - } impl<'a, 'tcx> HashStable> for TypeckTables<'tcx> { @@ -772,7 +723,6 @@ impl<'a, 'tcx> HashStable> for TypeckTables<'tcx> { ref concrete_opaque_types, ref upvar_list, ref generator_interior_types, - } = *self; hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| { @@ -786,25 +736,19 @@ impl<'a, 'tcx> HashStable> for TypeckTables<'tcx> { pat_binding_modes.hash_stable(hcx, hasher); pat_adjustments.hash_stable(hcx, hasher); hash_stable_hashmap(hcx, hasher, upvar_capture_map, |up_var_id, hcx| { - let ty::UpvarId { - var_path, - closure_expr_id - } = *up_var_id; - - let local_id_root = - local_id_root.expect("trying to hash invalid TypeckTables"); - - let var_owner_def_id = DefId { - krate: local_id_root.krate, - index: var_path.hir_id.owner, - }; - let closure_def_id = DefId { - krate: local_id_root.krate, - index: closure_expr_id.to_def_id().index, - }; - (hcx.def_path_hash(var_owner_def_id), - var_path.hir_id.local_id, - hcx.def_path_hash(closure_def_id)) + let ty::UpvarId { var_path, closure_expr_id } = *up_var_id; + + let local_id_root = local_id_root.expect("trying to hash invalid TypeckTables"); + + let var_owner_def_id = + DefId { krate: local_id_root.krate, index: var_path.hir_id.owner }; + let closure_def_id = + DefId { krate: local_id_root.krate, index: closure_expr_id.to_def_id().index }; + ( + hcx.def_path_hash(var_owner_def_id), + var_path.hir_id.local_id, + hcx.def_path_hash(closure_def_id), + ) }); closure_kind_origins.hash_stable(hcx, hasher); @@ -884,7 +828,7 @@ impl CanonicalUserType<'tcx> { }, } }) - }, + } } } } @@ -926,10 +870,7 @@ impl<'tcx> CommonTypes<'tcx> { u128: mk(Uint(ast::UintTy::U128)), f32: mk(Float(ast::FloatTy::F32)), f64: mk(Float(ast::FloatTy::F64)), - self_param: mk(ty::Param(ty::ParamTy { - index: 0, - name: kw::SelfUpper, - })), + self_param: mk(ty::Param(ty::ParamTy { index: 0, name: kw::SelfUpper })), trait_object_dummy_self: mk(Infer(ty::FreshTy(0))), } @@ -938,11 +879,7 @@ impl<'tcx> CommonTypes<'tcx> { impl<'tcx> CommonLifetimes<'tcx> { fn new(interners: &CtxtInterners<'tcx>) -> CommonLifetimes<'tcx> { - let mk = |r| { - interners.region.intern(r, |r| { - Interned(interners.arena.alloc(r)) - }).0 - }; + let mk = |r| interners.region.intern(r, |r| Interned(interners.arena.alloc(r))).0; CommonLifetimes { re_empty: mk(RegionKind::ReEmpty), @@ -954,11 +891,7 @@ impl<'tcx> CommonLifetimes<'tcx> { impl<'tcx> CommonConsts<'tcx> { fn new(interners: &CtxtInterners<'tcx>, types: &CommonTypes<'tcx>) -> CommonConsts<'tcx> { - let mk_const = |c| { - interners.const_.intern(c, |c| { - Interned(interners.arena.alloc(c)) - }).0 - }; + let mk_const = |c| interners.const_.intern(c, |c| Interned(interners.arena.alloc(c))).0; CommonConsts { err: mk_const(ty::Const { @@ -1030,9 +963,7 @@ pub struct GlobalCtxt<'tcx> { /// Map indicating what traits are in scope for places where this /// is relevant; generated by resolve. - trait_map: FxHashMap>>, + trait_map: FxHashMap>>, /// Export map produced by name resolution. export_map: FxHashMap>>, @@ -1099,13 +1030,17 @@ impl<'tcx> TyCtxt<'tcx> { self.arena.alloc(Steal::new(mir)) } - pub fn alloc_steal_promoted(self, promoted: IndexVec>) -> - &'tcx Steal>> { + pub fn alloc_steal_promoted( + self, + promoted: IndexVec>, + ) -> &'tcx Steal>> { self.arena.alloc(Steal::new(promoted)) } - pub fn intern_promoted(self, promoted: IndexVec>) -> - &'tcx IndexVec> { + pub fn intern_promoted( + self, + promoted: IndexVec>, + ) -> &'tcx IndexVec> { self.arena.alloc(promoted) } @@ -1121,9 +1056,7 @@ impl<'tcx> TyCtxt<'tcx> { } pub fn intern_const_alloc(self, alloc: Allocation) -> &'tcx Allocation { - self.allocation_interner.intern(alloc, |alloc| { - self.arena.alloc(alloc) - }) + self.allocation_interner.intern(alloc, |alloc| self.arena.alloc(alloc)) } /// Allocates a read-only byte or string literal for `mir::interpret`. @@ -1135,21 +1068,15 @@ impl<'tcx> TyCtxt<'tcx> { } pub fn intern_stability(self, stab: attr::Stability) -> &'tcx attr::Stability { - self.stability_interner.intern(stab, |stab| { - self.arena.alloc(stab) - }) + self.stability_interner.intern(stab, |stab| self.arena.alloc(stab)) } pub fn intern_const_stability(self, stab: attr::ConstStability) -> &'tcx attr::ConstStability { - self.const_stability_interner.intern(stab, |stab| { - self.arena.alloc(stab) - }) + self.const_stability_interner.intern(stab, |stab| self.arena.alloc(stab)) } pub fn intern_layout(self, layout: LayoutDetails) -> &'tcx LayoutDetails { - self.layout_interner.intern(layout, |layout| { - self.arena.alloc(layout) - }) + self.layout_interner.intern(layout, |layout| self.arena.alloc(layout)) } /// Returns a range of the start/end indices specified with the @@ -1169,8 +1096,10 @@ impl<'tcx> TyCtxt<'tcx> { } span_bug!(attr.span, "no arguments to `rustc_layout_scalar_valid_range` attribute"); }; - (get(sym::rustc_layout_scalar_valid_range_start), - get(sym::rustc_layout_scalar_valid_range_end)) + ( + get(sym::rustc_layout_scalar_valid_range_start), + get(sym::rustc_layout_scalar_valid_range_end), + ) } pub fn lift>(self, value: &T) -> Option { @@ -1218,10 +1147,8 @@ impl<'tcx> TyCtxt<'tcx> { // re-allocate when populating it. let capacity = def_path_tables.clone().map(|(_, t)| t.size()).sum::(); - let mut map: FxHashMap<_, _> = FxHashMap::with_capacity_and_hasher( - capacity, - ::std::default::Default::default() - ); + let mut map: FxHashMap<_, _> = + FxHashMap::with_capacity_and_hasher(capacity, ::std::default::Default::default()); for (cnum, def_path_table) in def_path_tables { def_path_table.add_def_path_hashes_to(cnum, &mut map); @@ -1252,33 +1179,34 @@ impl<'tcx> TyCtxt<'tcx> { consts: common_consts, extern_crate_map: resolutions.extern_crate_map, trait_map, - export_map: resolutions.export_map.into_iter().map(|(k, v)| { - let exports: Vec<_> = v.into_iter().map(|e| { - e.map_id(|id| hir.node_to_hir_id(id)) - }).collect(); - (k, exports) - }).collect(), - maybe_unused_trait_imports: - resolutions.maybe_unused_trait_imports - .into_iter() - .map(|id| hir.local_def_id_from_node_id(id)) - .collect(), - maybe_unused_extern_crates: - resolutions.maybe_unused_extern_crates - .into_iter() - .map(|(id, sp)| (hir.local_def_id_from_node_id(id), sp)) - .collect(), - glob_map: resolutions.glob_map.into_iter().map(|(id, names)| { - (hir.local_def_id_from_node_id(id), names) - }).collect(), + export_map: resolutions + .export_map + .into_iter() + .map(|(k, v)| { + let exports: Vec<_> = + v.into_iter().map(|e| e.map_id(|id| hir.node_to_hir_id(id))).collect(); + (k, exports) + }) + .collect(), + maybe_unused_trait_imports: resolutions + .maybe_unused_trait_imports + .into_iter() + .map(|id| hir.local_def_id_from_node_id(id)) + .collect(), + maybe_unused_extern_crates: resolutions + .maybe_unused_extern_crates + .into_iter() + .map(|(id, sp)| (hir.local_def_id_from_node_id(id), sp)) + .collect(), + glob_map: resolutions + .glob_map + .into_iter() + .map(|(id, names)| (hir.local_def_id_from_node_id(id), names)) + .collect(), extern_prelude: resolutions.extern_prelude, hir_map: hir, def_path_hash_to_def_id, - queries: query::Queries::new( - providers, - extern_providers, - on_disk_query_result_cache, - ), + queries: query::Queries::new(providers, extern_providers, on_disk_query_result_cache), rcache: Default::default(), selection_cache: Default::default(), evaluation_cache: Default::default(), @@ -1335,11 +1263,7 @@ impl<'tcx> TyCtxt<'tcx> { } pub fn def_key(self, id: DefId) -> hir_map::DefKey { - if id.is_local() { - self.hir().def_key(id) - } else { - self.cstore.def_key(id) - } + if id.is_local() { self.hir().def_key(id) } else { self.cstore.def_key(id) } } /// Converts a `DefId` into its fully expanded `DefPath` (every @@ -1348,21 +1272,13 @@ impl<'tcx> TyCtxt<'tcx> { /// Note that if `id` is not local to this crate, the result will /// be a non-local `DefPath`. pub fn def_path(self, id: DefId) -> hir_map::DefPath { - if id.is_local() { - self.hir().def_path(id) - } else { - self.cstore.def_path(id) - } + if id.is_local() { self.hir().def_path(id) } else { self.cstore.def_path(id) } } /// Returns whether or not the crate with CrateNum 'cnum' /// is marked as a private dependency pub fn is_private_dep(self, cnum: CrateNum) -> bool { - if cnum == LOCAL_CRATE { - false - } else { - self.cstore.crate_is_private_dep_untracked(cnum) - } + if cnum == LOCAL_CRATE { false } else { self.cstore.crate_is_private_dep_untracked(cnum) } } #[inline] @@ -1380,26 +1296,29 @@ impl<'tcx> TyCtxt<'tcx> { // statements within the query system and we'd run into endless // recursion otherwise. let (crate_name, crate_disambiguator) = if def_id.is_local() { - (self.crate_name.clone(), - self.sess.local_crate_disambiguator()) + (self.crate_name.clone(), self.sess.local_crate_disambiguator()) } else { - (self.cstore.crate_name_untracked(def_id.krate), - self.cstore.crate_disambiguator_untracked(def_id.krate)) + ( + self.cstore.crate_name_untracked(def_id.krate), + self.cstore.crate_disambiguator_untracked(def_id.krate), + ) }; - format!("{}[{}]{}", - crate_name, - // Don't print the whole crate disambiguator. That's just - // annoying in debug output. - &(crate_disambiguator.to_fingerprint().to_hex())[..4], - self.def_path(def_id).to_string_no_crate()) + format!( + "{}[{}]{}", + crate_name, + // Don't print the whole crate disambiguator. That's just + // annoying in debug output. + &(crate_disambiguator.to_fingerprint().to_hex())[..4], + self.def_path(def_id).to_string_no_crate() + ) } pub fn metadata_encoding_version(self) -> Vec { self.cstore.metadata_encoding_version().to_vec() } - pub fn encode_metadata(self)-> EncodedMetadata { + pub fn encode_metadata(self) -> EncodedMetadata { let _prof_timer = self.prof.generic_activity("generate_crate_metadata"); self.cstore.encode_metadata(self) } @@ -1414,10 +1333,7 @@ impl<'tcx> TyCtxt<'tcx> { pub fn create_stable_hashing_context(self) -> StableHashingContext<'tcx> { let krate = self.gcx.hir_map.forest.untracked_krate(); - StableHashingContext::new(self.sess, - krate, - self.hir().definitions(), - &*self.cstore) + StableHashingContext::new(self.sess, krate, self.hir().definitions(), &*self.cstore) } // This method makes sure that we have a DepNode and a Fingerprint for @@ -1431,19 +1347,19 @@ impl<'tcx> TyCtxt<'tcx> { for cnum in self.cstore.crates_untracked() { let dep_node = DepNode::new(self, DepConstructor::CrateMetadata(cnum)); let crate_hash = self.cstore.crate_hash_untracked(cnum); - self.dep_graph.with_task(dep_node, - self, - crate_hash, - |_, x| x, // No transformation needed - dep_graph::hash_result, + self.dep_graph.with_task( + dep_node, + self, + crate_hash, + |_, x| x, // No transformation needed + dep_graph::hash_result, ); } } - pub fn serialize_query_result_cache(self, - encoder: &mut E) - -> Result<(), E::Error> - where E: ty::codec::TyEncoder + pub fn serialize_query_result_cache(self, encoder: &mut E) -> Result<(), E::Error> + where + E: ty::codec::TyEncoder, { self.queries.on_disk_cache.serialize(self, encoder) } @@ -1492,7 +1408,9 @@ impl<'tcx> TyCtxt<'tcx> { // // * Otherwise, use the behavior requested via `-Z borrowck=...` - if self.features().nll { return BorrowckMode::Mir; } + if self.features().nll { + return BorrowckMode::Mir; + } self.sess.opts.borrowck_mode } @@ -1503,18 +1421,18 @@ impl<'tcx> TyCtxt<'tcx> { self.sess.crate_types.borrow().iter().any(|crate_type| { match crate_type { - CrateType::Executable | - CrateType::Staticlib | - CrateType::ProcMacro | - CrateType::Cdylib => false, + CrateType::Executable + | CrateType::Staticlib + | CrateType::ProcMacro + | CrateType::Cdylib => false, // FIXME rust-lang/rust#64319, rust-lang/rust#64872: // We want to block export of generics from dylibs, // but we must fix rust-lang/rust#65890 before we can // do that robustly. - CrateType::Dylib => true, + CrateType::Dylib => true, - CrateType::Rlib => true, + CrateType::Rlib => true, } }) } @@ -1523,16 +1441,13 @@ impl<'tcx> TyCtxt<'tcx> { pub fn is_suitable_region(&self, region: Region<'tcx>) -> Option { let (suitable_region_binding_scope, bound_region) = match *region { ty::ReFree(ref free_region) => (free_region.scope, free_region.bound_region), - ty::ReEarlyBound(ref ebr) => ( - self.parent(ebr.def_id).unwrap(), - ty::BoundRegion::BrNamed(ebr.def_id, ebr.name), - ), + ty::ReEarlyBound(ref ebr) => { + (self.parent(ebr.def_id).unwrap(), ty::BoundRegion::BrNamed(ebr.def_id, ebr.name)) + } _ => return None, // not a free region }; - let hir_id = self.hir() - .as_local_hir_id(suitable_region_binding_scope) - .unwrap(); + let hir_id = self.hir().as_local_hir_id(suitable_region_binding_scope).unwrap(); let is_impl_item = match self.hir().find(hir_id) { Some(Node::Item(..)) | Some(Node::TraitItem(..)) => false, Some(Node::ImplItem(..)) => { @@ -1548,10 +1463,7 @@ impl<'tcx> TyCtxt<'tcx> { }); } - pub fn return_type_impl_trait( - &self, - scope_def_id: DefId, - ) -> Option<(Ty<'tcx>, Span)> { + pub fn return_type_impl_trait(&self, scope_def_id: DefId) -> Option<(Ty<'tcx>, Span)> { // HACK: `type_of_def_id()` will fail on these (#55796), so return `None`. let hir_id = self.hir().as_local_hir_id(scope_def_id).unwrap(); match self.hir().get(hir_id) { @@ -1578,18 +1490,13 @@ impl<'tcx> TyCtxt<'tcx> { None } } - _ => None + _ => None, } } // Checks if the bound region is in Impl Item. - pub fn is_bound_region_in_impl_item( - &self, - suitable_region_binding_scope: DefId, - ) -> bool { - let container_id = self.associated_item(suitable_region_binding_scope) - .container - .id(); + pub fn is_bound_region_in_impl_item(&self, suitable_region_binding_scope: DefId) -> bool { + let container_id = self.associated_item(suitable_region_binding_scope).container.id(); if self.impl_trait_ref(container_id).is_some() { // For now, we do not try to target impls of traits. This is // because this message is going to suggest that the user @@ -1626,9 +1533,7 @@ impl<'tcx> GlobalCtxt<'tcx> { where F: FnOnce(TyCtxt<'tcx>) -> R, { - let tcx = TyCtxt { - gcx: self, - }; + let tcx = TyCtxt { gcx: self }; ty::tls::with_related_context(tcx, |icx| { let new_icx = ty::tls::ImplicitCtxt { tcx, @@ -1637,9 +1542,7 @@ impl<'tcx> GlobalCtxt<'tcx> { layout_depth: icx.layout_depth, task_deps: icx.task_deps, }; - ty::tls::enter_context(&new_icx, |_| { - f(tcx) - }) + ty::tls::enter_context(&new_icx, |_| f(tcx)) }) } } @@ -1669,64 +1572,64 @@ pub trait Lift<'tcx>: fmt::Debug { macro_rules! nop_lift { ($ty:ty => $lifted:ty) => { impl<'a, 'tcx> Lift<'tcx> for $ty { - type Lifted = $lifted; - fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option { - if tcx.interners.arena.in_arena(*self as *const _) { - Some(unsafe { mem::transmute(*self) }) - } else { - None - } - } + type Lifted = $lifted; + fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option { + if tcx.interners.arena.in_arena(*self as *const _) { + Some(unsafe { mem::transmute(*self) }) + } else { + None } + } + } }; } macro_rules! nop_list_lift { ($ty:ty => $lifted:ty) => { impl<'a, 'tcx> Lift<'tcx> for &'a List<$ty> { - type Lifted = &'tcx List<$lifted>; - fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option { - if self.is_empty() { - return Some(List::empty()); - } - if tcx.interners.arena.in_arena(*self as *const _) { - Some(unsafe { mem::transmute(*self) }) - } else { - None - } - } + type Lifted = &'tcx List<$lifted>; + fn lift_to_tcx(&self, tcx: TyCtxt<'tcx>) -> Option { + if self.is_empty() { + return Some(List::empty()); } + if tcx.interners.arena.in_arena(*self as *const _) { + Some(unsafe { mem::transmute(*self) }) + } else { + None + } + } + } }; } -nop_lift!{Ty<'a> => Ty<'tcx>} -nop_lift!{Region<'a> => Region<'tcx>} -nop_lift!{Goal<'a> => Goal<'tcx>} -nop_lift!{&'a Const<'a> => &'tcx Const<'tcx>} +nop_lift! {Ty<'a> => Ty<'tcx>} +nop_lift! {Region<'a> => Region<'tcx>} +nop_lift! {Goal<'a> => Goal<'tcx>} +nop_lift! {&'a Const<'a> => &'tcx Const<'tcx>} -nop_list_lift!{Goal<'a> => Goal<'tcx>} -nop_list_lift!{Clause<'a> => Clause<'tcx>} -nop_list_lift!{Ty<'a> => Ty<'tcx>} -nop_list_lift!{ExistentialPredicate<'a> => ExistentialPredicate<'tcx>} -nop_list_lift!{Predicate<'a> => Predicate<'tcx>} -nop_list_lift!{CanonicalVarInfo => CanonicalVarInfo} -nop_list_lift!{ProjectionKind => ProjectionKind} +nop_list_lift! {Goal<'a> => Goal<'tcx>} +nop_list_lift! {Clause<'a> => Clause<'tcx>} +nop_list_lift! {Ty<'a> => Ty<'tcx>} +nop_list_lift! {ExistentialPredicate<'a> => ExistentialPredicate<'tcx>} +nop_list_lift! {Predicate<'a> => Predicate<'tcx>} +nop_list_lift! {CanonicalVarInfo => CanonicalVarInfo} +nop_list_lift! {ProjectionKind => ProjectionKind} // This is the impl for `&'a InternalSubsts<'a>`. -nop_list_lift!{GenericArg<'a> => GenericArg<'tcx>} +nop_list_lift! {GenericArg<'a> => GenericArg<'tcx>} pub mod tls { - use super::{GlobalCtxt, TyCtxt, ptr_eq}; + use super::{ptr_eq, GlobalCtxt, TyCtxt}; - use std::fmt; - use std::mem; - use syntax_pos; + use crate::dep_graph::TaskDeps; use crate::ty::query; use errors::{Diagnostic, TRACK_DIAGNOSTICS}; - use rustc_data_structures::OnDrop; - use rustc_data_structures::sync::{self, Lrc, Lock}; + use rustc_data_structures::sync::{self, Lock, Lrc}; use rustc_data_structures::thin_vec::ThinVec; - use crate::dep_graph::TaskDeps; + use rustc_data_structures::OnDrop; + use std::fmt; + use std::mem; + use syntax_pos; #[cfg(not(parallel_compiler))] use std::cell::Cell; @@ -1830,7 +1733,8 @@ pub mod tls { /// Sets up the callbacks from libsyntax on the current thread. pub fn with_thread_locals(f: F) -> R - where F: FnOnce() -> R + where + F: FnOnce() -> R, { syntax_pos::SPAN_DEBUG.with(|span_dbg| { let original_span_debug = span_dbg.get(); @@ -1859,9 +1763,7 @@ pub mod tls { where F: FnOnce(&ImplicitCtxt<'a, 'tcx>) -> R, { - set_tlv(context as *const _ as usize, || { - f(&context) - }) + set_tlv(context as *const _ as usize, || f(&context)) } /// Enters `GlobalCtxt` by setting up libsyntax callbacks and @@ -1881,19 +1783,10 @@ pub mod tls { GCX_PTR.with(|lock| *lock.lock() = 0); }); - let tcx = TyCtxt { - gcx, - }; - let icx = ImplicitCtxt { - tcx, - query: None, - diagnostics: None, - layout_depth: 0, - task_deps: None, - }; - enter_context(&icx, |_| { - f(tcx) - }) + let tcx = TyCtxt { gcx }; + let icx = + ImplicitCtxt { tcx, query: None, diagnostics: None, layout_depth: 0, task_deps: None }; + enter_context(&icx, |_| f(tcx)) } scoped_thread_local! { @@ -1911,16 +1804,9 @@ pub mod tls { let gcx = GCX_PTR.with(|lock| *lock.lock()); assert!(gcx != 0); let gcx = &*(gcx as *const GlobalCtxt<'_>); - let tcx = TyCtxt { - gcx, - }; - let icx = ImplicitCtxt { - query: None, - diagnostics: None, - tcx, - layout_depth: 0, - task_deps: None, - }; + let tcx = TyCtxt { gcx }; + let icx = + ImplicitCtxt { query: None, diagnostics: None, tcx, layout_depth: 0, task_deps: None }; enter_context(&icx, |_| f(tcx)) } @@ -1962,12 +1848,10 @@ pub mod tls { where F: FnOnce(&ImplicitCtxt<'_, 'tcx>) -> R, { - with_context(|context| { - unsafe { - assert!(ptr_eq(context.tcx.gcx, tcx.gcx)); - let context: &ImplicitCtxt<'_, '_> = mem::transmute(context); - f(context) - } + with_context(|context| unsafe { + assert!(ptr_eq(context.tcx.gcx, tcx.gcx)); + let context: &ImplicitCtxt<'_, '_> = mem::transmute(context); + f(context) }) } @@ -2069,9 +1953,27 @@ impl<'tcx> TyCtxt<'tcx> { pub fn print_debug_stats(self) { sty_debug_print!( self, - Adt, Array, Slice, RawPtr, Ref, FnDef, FnPtr, Placeholder, - Generator, GeneratorWitness, Dynamic, Closure, Tuple, Bound, - Param, Infer, UnnormalizedProjection, Projection, Opaque, Foreign); + Adt, + Array, + Slice, + RawPtr, + Ref, + FnDef, + FnPtr, + Placeholder, + Generator, + GeneratorWitness, + Dynamic, + Closure, + Tuple, + Bound, + Param, + Infer, + UnnormalizedProjection, + Projection, + Opaque, + Foreign + ); println!("InternalSubsts interner: #{}", self.interners.substs.len()); println!("Region interner: #{}", self.interners.region.len()); @@ -2082,16 +1984,15 @@ impl<'tcx> TyCtxt<'tcx> { } } - /// An entry in an interner. struct Interned<'tcx, T: ?Sized>(&'tcx T); -impl<'tcx, T: 'tcx+?Sized> Clone for Interned<'tcx, T> { +impl<'tcx, T: 'tcx + ?Sized> Clone for Interned<'tcx, T> { fn clone(&self) -> Self { Interned(self.0) } } -impl<'tcx, T: 'tcx+?Sized> Copy for Interned<'tcx, T> {} +impl<'tcx, T: 'tcx + ?Sized> Copy for Interned<'tcx, T> {} // N.B., an `Interned` compares and hashes as a `TyKind`. impl<'tcx> PartialEq for Interned<'tcx, TyS<'tcx>> { @@ -2148,15 +2049,13 @@ impl<'tcx> Borrow<[GenericArg<'tcx>]> for Interned<'tcx, InternalSubsts<'tcx>> { } } -impl<'tcx> Borrow<[ProjectionKind]> - for Interned<'tcx, List> { +impl<'tcx> Borrow<[ProjectionKind]> for Interned<'tcx, List> { fn borrow(&self) -> &[ProjectionKind] { &self.0[..] } } -impl<'tcx> Borrow<[PlaceElem<'tcx>]> - for Interned<'tcx, List>> { +impl<'tcx> Borrow<[PlaceElem<'tcx>]> for Interned<'tcx, List>> { fn borrow(&self) -> &[PlaceElem<'tcx>] { &self.0[..] } @@ -2272,10 +2171,7 @@ impl<'tcx> TyCtxt<'tcx> { /// unsafe. pub fn safe_to_unsafe_fn_ty(self, sig: PolyFnSig<'tcx>) -> Ty<'tcx> { assert_eq!(sig.unsafety(), hir::Unsafety::Normal); - self.mk_fn_ptr(sig.map_bound(|sig| ty::FnSig { - unsafety: hir::Unsafety::Unsafe, - ..sig - })) + self.mk_fn_ptr(sig.map_bound(|sig| ty::FnSig { unsafety: hir::Unsafety::Unsafe, ..sig })) } /// Given a closure signature `sig`, returns an equivalent `fn` @@ -2289,18 +2185,10 @@ impl<'tcx> TyCtxt<'tcx> { pub fn coerce_closure_fn_ty(self, sig: PolyFnSig<'tcx>, unsafety: hir::Unsafety) -> Ty<'tcx> { let converted_sig = sig.map_bound(|s| { let params_iter = match s.inputs()[0].kind { - ty::Tuple(params) => { - params.into_iter().map(|k| k.expect_ty()) - } + ty::Tuple(params) => params.into_iter().map(|k| k.expect_ty()), _ => bug!(), }; - self.mk_fn_sig( - params_iter, - s.output(), - s.c_variadic, - unsafety, - abi::Abi::Rust, - ) + self.mk_fn_sig(params_iter, s.output(), s.c_variadic, unsafety, abi::Abi::Rust) }); self.mk_fn_ptr(converted_sig) @@ -2314,30 +2202,30 @@ impl<'tcx> TyCtxt<'tcx> { pub fn mk_mach_int(self, tm: ast::IntTy) -> Ty<'tcx> { match tm { - ast::IntTy::Isize => self.types.isize, - ast::IntTy::I8 => self.types.i8, - ast::IntTy::I16 => self.types.i16, - ast::IntTy::I32 => self.types.i32, - ast::IntTy::I64 => self.types.i64, - ast::IntTy::I128 => self.types.i128, + ast::IntTy::Isize => self.types.isize, + ast::IntTy::I8 => self.types.i8, + ast::IntTy::I16 => self.types.i16, + ast::IntTy::I32 => self.types.i32, + ast::IntTy::I64 => self.types.i64, + ast::IntTy::I128 => self.types.i128, } } pub fn mk_mach_uint(self, tm: ast::UintTy) -> Ty<'tcx> { match tm { - ast::UintTy::Usize => self.types.usize, - ast::UintTy::U8 => self.types.u8, - ast::UintTy::U16 => self.types.u16, - ast::UintTy::U32 => self.types.u32, - ast::UintTy::U64 => self.types.u64, - ast::UintTy::U128 => self.types.u128, + ast::UintTy::Usize => self.types.usize, + ast::UintTy::U8 => self.types.u8, + ast::UintTy::U16 => self.types.u16, + ast::UintTy::U32 => self.types.u32, + ast::UintTy::U64 => self.types.u64, + ast::UintTy::U128 => self.types.u128, } } pub fn mk_mach_float(self, tm: ast::FloatTy) -> Ty<'tcx> { match tm { - ast::FloatTy::F32 => self.types.f32, - ast::FloatTy::F64 => self.types.f64, + ast::FloatTy::F32 => self.types.f32, + ast::FloatTy::F64 => self.types.f64, } } @@ -2364,12 +2252,9 @@ impl<'tcx> TyCtxt<'tcx> { fn mk_generic_adt(self, wrapper_def_id: DefId, ty_param: Ty<'tcx>) -> Ty<'tcx> { let adt_def = self.adt_def(wrapper_def_id); - let substs = InternalSubsts::for_item(self, wrapper_def_id, |param, substs| { - match param.kind { - GenericParamDefKind::Lifetime | - GenericParamDefKind::Const => { - bug!() - } + let substs = + InternalSubsts::for_item(self, wrapper_def_id, |param, substs| match param.kind { + GenericParamDefKind::Lifetime | GenericParamDefKind::Const => bug!(), GenericParamDefKind::Type { has_default, .. } => { if param.index == 0 { ty_param.into() @@ -2378,8 +2263,7 @@ impl<'tcx> TyCtxt<'tcx> { self.type_of(param.def_id).subst(self, substs).into() } } - } - }); + }); self.mk_ty(Adt(adt_def, substs)) } @@ -2390,7 +2274,7 @@ impl<'tcx> TyCtxt<'tcx> { } #[inline] - pub fn mk_lang_item(self, ty: Ty<'tcx>, item: lang_items::LangItem) -> Option> { + pub fn mk_lang_item(self, ty: Ty<'tcx>, item: lang_items::LangItem) -> Option> { let def_id = self.lang_items().require(item).ok()?; Some(self.mk_generic_adt(def_id, ty)) } @@ -2413,22 +2297,22 @@ impl<'tcx> TyCtxt<'tcx> { #[inline] pub fn mk_mut_ref(self, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> { - self.mk_ref(r, TypeAndMut {ty: ty, mutbl: hir::Mutability::Mut }) + self.mk_ref(r, TypeAndMut { ty: ty, mutbl: hir::Mutability::Mut }) } #[inline] pub fn mk_imm_ref(self, r: Region<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> { - self.mk_ref(r, TypeAndMut {ty: ty, mutbl: hir::Mutability::Not }) + self.mk_ref(r, TypeAndMut { ty: ty, mutbl: hir::Mutability::Not }) } #[inline] pub fn mk_mut_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> { - self.mk_ptr(TypeAndMut {ty: ty, mutbl: hir::Mutability::Mut }) + self.mk_ptr(TypeAndMut { ty: ty, mutbl: hir::Mutability::Mut }) } #[inline] pub fn mk_imm_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> { - self.mk_ptr(TypeAndMut {ty: ty, mutbl: hir::Mutability::Not }) + self.mk_ptr(TypeAndMut { ty: ty, mutbl: hir::Mutability::Not }) } #[inline] @@ -2466,11 +2350,7 @@ impl<'tcx> TyCtxt<'tcx> { #[inline] pub fn mk_diverging_default(self) -> Ty<'tcx> { - if self.features().never_type_fallback { - self.types.never - } else { - self.types.unit - } + if self.features().never_type_fallback { self.types.never } else { self.types.unit } } #[inline] @@ -2479,8 +2359,7 @@ impl<'tcx> TyCtxt<'tcx> { } #[inline] - pub fn mk_fn_def(self, def_id: DefId, - substs: SubstsRef<'tcx>) -> Ty<'tcx> { + pub fn mk_fn_def(self, def_id: DefId, substs: SubstsRef<'tcx>) -> Ty<'tcx> { self.mk_ty(FnDef(def_id, substs)) } @@ -2493,34 +2372,28 @@ impl<'tcx> TyCtxt<'tcx> { pub fn mk_dynamic( self, obj: ty::Binder<&'tcx List>>, - reg: ty::Region<'tcx> + reg: ty::Region<'tcx>, ) -> Ty<'tcx> { self.mk_ty(Dynamic(obj, reg)) } #[inline] - pub fn mk_projection(self, - item_def_id: DefId, - substs: SubstsRef<'tcx>) - -> Ty<'tcx> { - self.mk_ty(Projection(ProjectionTy { - item_def_id, - substs, - })) - } + pub fn mk_projection(self, item_def_id: DefId, substs: SubstsRef<'tcx>) -> Ty<'tcx> { + self.mk_ty(Projection(ProjectionTy { item_def_id, substs })) + } #[inline] - pub fn mk_closure(self, closure_id: DefId, closure_substs: SubstsRef<'tcx>) - -> Ty<'tcx> { + pub fn mk_closure(self, closure_id: DefId, closure_substs: SubstsRef<'tcx>) -> Ty<'tcx> { self.mk_ty(Closure(closure_id, closure_substs)) } #[inline] - pub fn mk_generator(self, - id: DefId, - generator_substs: SubstsRef<'tcx>, - movability: hir::Movability) - -> Ty<'tcx> { + pub fn mk_generator( + self, + id: DefId, + generator_substs: SubstsRef<'tcx>, + movability: hir::Movability, + ) -> Ty<'tcx> { self.mk_ty(Generator(id, generator_substs, movability)) } @@ -2536,10 +2409,7 @@ impl<'tcx> TyCtxt<'tcx> { #[inline] pub fn mk_const_var(self, v: ConstVid<'tcx>, ty: Ty<'tcx>) -> &'tcx Const<'tcx> { - self.mk_const(ty::Const { - val: ty::ConstKind::Infer(InferConst::Var(v)), - ty, - }) + self.mk_const(ty::Const { val: ty::ConstKind::Infer(InferConst::Var(v)), ty }) } #[inline] @@ -2558,15 +2428,8 @@ impl<'tcx> TyCtxt<'tcx> { } #[inline] - pub fn mk_const_infer( - self, - ic: InferConst<'tcx>, - ty: Ty<'tcx>, - ) -> &'tcx ty::Const<'tcx> { - self.mk_const(ty::Const { - val: ty::ConstKind::Infer(ic), - ty, - }) + pub fn mk_const_infer(self, ic: InferConst<'tcx>, ty: Ty<'tcx>) -> &'tcx ty::Const<'tcx> { + self.mk_const(ty::Const { val: ty::ConstKind::Infer(ic), ty }) } #[inline] @@ -2575,19 +2438,10 @@ impl<'tcx> TyCtxt<'tcx> { } #[inline] - pub fn mk_const_param( - self, - index: u32, - name: Symbol, - ty: Ty<'tcx> - ) -> &'tcx Const<'tcx> { - self.mk_const(ty::Const { - val: ty::ConstKind::Param(ParamConst { index, name }), - ty, - }) + pub fn mk_const_param(self, index: u32, name: Symbol, ty: Ty<'tcx>) -> &'tcx Const<'tcx> { + self.mk_const(ty::Const { val: ty::ConstKind::Param(ParamConst { index, name }), ty }) } - pub fn mk_param_from_def(self, param: &ty::GenericParamDef) -> GenericArg<'tcx> { match param.kind { GenericParamDefKind::Lifetime => { @@ -2647,15 +2501,16 @@ impl<'tcx> TyCtxt<'tcx> { Place { base: place.base, projection: self.intern_place_elems(&projection) } } - pub fn intern_existential_predicates(self, eps: &[ExistentialPredicate<'tcx>]) - -> &'tcx List> { + pub fn intern_existential_predicates( + self, + eps: &[ExistentialPredicate<'tcx>], + ) -> &'tcx List> { assert!(!eps.is_empty()); assert!(eps.windows(2).all(|w| w[0].stable_cmp(self, &w[1]) != Ordering::Greater)); self._intern_existential_predicates(eps) } - pub fn intern_predicates(self, preds: &[Predicate<'tcx>]) - -> &'tcx List> { + pub fn intern_predicates(self, preds: &[Predicate<'tcx>]) -> &'tcx List> { // FIXME consider asking the input slice to be sorted to avoid // re-interning permutations, in which case that would be asserted // here. @@ -2668,109 +2523,87 @@ impl<'tcx> TyCtxt<'tcx> { } pub fn intern_type_list(self, ts: &[Ty<'tcx>]) -> &'tcx List> { - if ts.len() == 0 { - List::empty() - } else { - self._intern_type_list(ts) - } + if ts.len() == 0 { List::empty() } else { self._intern_type_list(ts) } } pub fn intern_substs(self, ts: &[GenericArg<'tcx>]) -> &'tcx List> { - if ts.len() == 0 { - List::empty() - } else { - self._intern_substs(ts) - } + if ts.len() == 0 { List::empty() } else { self._intern_substs(ts) } } pub fn intern_projs(self, ps: &[ProjectionKind]) -> &'tcx List { - if ps.len() == 0 { - List::empty() - } else { - self._intern_projs(ps) - } + if ps.len() == 0 { List::empty() } else { self._intern_projs(ps) } } pub fn intern_place_elems(self, ts: &[PlaceElem<'tcx>]) -> &'tcx List> { - if ts.len() == 0 { - List::empty() - } else { - self._intern_place_elems(ts) - } + if ts.len() == 0 { List::empty() } else { self._intern_place_elems(ts) } } pub fn intern_canonical_var_infos(self, ts: &[CanonicalVarInfo]) -> CanonicalVarInfos<'tcx> { - if ts.len() == 0 { - List::empty() - } else { - self._intern_canonical_var_infos(ts) - } + if ts.len() == 0 { List::empty() } else { self._intern_canonical_var_infos(ts) } } pub fn intern_clauses(self, ts: &[Clause<'tcx>]) -> Clauses<'tcx> { - if ts.len() == 0 { - List::empty() - } else { - self._intern_clauses(ts) - } + if ts.len() == 0 { List::empty() } else { self._intern_clauses(ts) } } pub fn intern_goals(self, ts: &[Goal<'tcx>]) -> Goals<'tcx> { - if ts.len() == 0 { - List::empty() - } else { - self._intern_goals(ts) - } + if ts.len() == 0 { List::empty() } else { self._intern_goals(ts) } } - pub fn mk_fn_sig(self, - inputs: I, - output: I::Item, - c_variadic: bool, - unsafety: hir::Unsafety, - abi: abi::Abi) - -> , ty::FnSig<'tcx>>>::Output + pub fn mk_fn_sig( + self, + inputs: I, + output: I::Item, + c_variadic: bool, + unsafety: hir::Unsafety, + abi: abi::Abi, + ) -> , ty::FnSig<'tcx>>>::Output where I: Iterator, ty::FnSig<'tcx>>>, { inputs.chain(iter::once(output)).intern_with(|xs| ty::FnSig { inputs_and_output: self.intern_type_list(xs), - c_variadic, unsafety, abi + c_variadic, + unsafety, + abi, }) } - pub fn mk_existential_predicates], - &'tcx List>>>(self, iter: I) - -> I::Output { + pub fn mk_existential_predicates< + I: InternAs<[ExistentialPredicate<'tcx>], &'tcx List>>, + >( + self, + iter: I, + ) -> I::Output { iter.intern_with(|xs| self.intern_existential_predicates(xs)) } - pub fn mk_predicates], - &'tcx List>>>(self, iter: I) - -> I::Output { + pub fn mk_predicates], &'tcx List>>>( + self, + iter: I, + ) -> I::Output { iter.intern_with(|xs| self.intern_predicates(xs)) } - pub fn mk_type_list], - &'tcx List>>>(self, iter: I) -> I::Output { + pub fn mk_type_list], &'tcx List>>>(self, iter: I) -> I::Output { iter.intern_with(|xs| self.intern_type_list(xs)) } - pub fn mk_substs], - &'tcx List>>>(self, iter: I) -> I::Output { + pub fn mk_substs], &'tcx List>>>( + self, + iter: I, + ) -> I::Output { iter.intern_with(|xs| self.intern_substs(xs)) } - pub fn mk_place_elems], - &'tcx List>>>(self, iter: I) -> I::Output { + pub fn mk_place_elems], &'tcx List>>>( + self, + iter: I, + ) -> I::Output { iter.intern_with(|xs| self.intern_place_elems(xs)) } - pub fn mk_substs_trait(self, - self_ty: Ty<'tcx>, - rest: &[GenericArg<'tcx>]) - -> SubstsRef<'tcx> - { + pub fn mk_substs_trait(self, self_ty: Ty<'tcx>, rest: &[GenericArg<'tcx>]) -> SubstsRef<'tcx> { self.mk_substs(iter::once(self_ty.into()).chain(rest.iter().cloned())) } @@ -2782,31 +2615,37 @@ impl<'tcx> TyCtxt<'tcx> { iter.intern_with(|xs| self.intern_goals(xs)) } - pub fn lint_hir>(self, - lint: &'static Lint, - hir_id: HirId, - span: S, - msg: &str) { + pub fn lint_hir>( + self, + lint: &'static Lint, + hir_id: HirId, + span: S, + msg: &str, + ) { self.struct_span_lint_hir(lint, hir_id, span.into(), msg).emit() } - pub fn lint_hir_note>(self, - lint: &'static Lint, - hir_id: HirId, - span: S, - msg: &str, - note: &str) { + pub fn lint_hir_note>( + self, + lint: &'static Lint, + hir_id: HirId, + span: S, + msg: &str, + note: &str, + ) { let mut err = self.struct_span_lint_hir(lint, hir_id, span.into(), msg); err.note(note); err.emit() } - pub fn lint_node_note>(self, - lint: &'static Lint, - id: hir::HirId, - span: S, - msg: &str, - note: &str) { + pub fn lint_node_note>( + self, + lint: &'static Lint, + id: hir::HirId, + span: S, + msg: &str, + note: &str, + ) { let mut err = self.struct_span_lint_hir(lint, id, span.into(), msg); err.note(note); err.emit() @@ -2837,12 +2676,12 @@ impl<'tcx> TyCtxt<'tcx> { pub fn lint_level_at_node( self, lint: &'static Lint, - mut id: hir::HirId + mut id: hir::HirId, ) -> (lint::Level, lint::LintSource) { let sets = self.lint_levels(LOCAL_CRATE); loop { if let Some(pair) = sets.level_and_source(lint, id, self.sess) { - return pair + return pair; } let next = self.hir().get_parent_node(id); if next == id { @@ -2852,38 +2691,37 @@ impl<'tcx> TyCtxt<'tcx> { } } - pub fn struct_span_lint_hir>(self, - lint: &'static Lint, - hir_id: HirId, - span: S, - msg: &str) - -> DiagnosticBuilder<'tcx> - { + pub fn struct_span_lint_hir>( + self, + lint: &'static Lint, + hir_id: HirId, + span: S, + msg: &str, + ) -> DiagnosticBuilder<'tcx> { let (level, src) = self.lint_level_at_node(lint, hir_id); lint::struct_lint_level(self.sess, lint, level, src, Some(span.into()), msg) } - pub fn struct_lint_node(self, lint: &'static Lint, id: HirId, msg: &str) - -> DiagnosticBuilder<'tcx> - { + pub fn struct_lint_node( + self, + lint: &'static Lint, + id: HirId, + msg: &str, + ) -> DiagnosticBuilder<'tcx> { let (level, src) = self.lint_level_at_node(lint, id); lint::struct_lint_level(self.sess, lint, level, src, None, msg) } pub fn in_scope_traits(self, id: HirId) -> Option<&'tcx StableVec> { - self.in_scope_traits_map(id.owner) - .and_then(|map| map.get(&id.local_id)) + self.in_scope_traits_map(id.owner).and_then(|map| map.get(&id.local_id)) } pub fn named_region(self, id: HirId) -> Option { - self.named_region_map(id.owner) - .and_then(|map| map.get(&id.local_id).cloned()) + self.named_region_map(id.owner).and_then(|map| map.get(&id.local_id).cloned()) } pub fn is_late_bound(self, id: HirId) -> bool { - self.is_late_bound_map(id.owner) - .map(|set| set.contains(&id.local_id)) - .unwrap_or(false) + self.is_late_bound_map(id.owner).map(|set| set.contains(&id.local_id)).unwrap_or(false) } pub fn object_lifetime_defaults(self, id: HirId) -> Option<&'tcx [ObjectLifetimeDefault]> { @@ -2895,44 +2733,52 @@ impl<'tcx> TyCtxt<'tcx> { pub trait InternAs { type Output; fn intern_with(self, f: F) -> Self::Output - where F: FnOnce(&T) -> R; + where + F: FnOnce(&T) -> R; } impl InternAs<[T], R> for I - where E: InternIteratorElement, - I: Iterator { +where + E: InternIteratorElement, + I: Iterator, +{ type Output = E::Output; fn intern_with(self, f: F) -> Self::Output - where F: FnOnce(&[T]) -> R { + where + F: FnOnce(&[T]) -> R, + { E::intern_with(self, f) } } pub trait InternIteratorElement: Sized { type Output; - fn intern_with, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output; + fn intern_with, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output; } impl InternIteratorElement for T { type Output = R; - fn intern_with, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output { + fn intern_with, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output { f(&iter.collect::>()) } } impl<'a, T, R> InternIteratorElement for &'a T - where T: Clone + 'a +where + T: Clone + 'a, { type Output = R; - fn intern_with, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output { + fn intern_with, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output { f(&iter.cloned().collect::>()) } } impl InternIteratorElement for Result { type Output = Result; - fn intern_with, F: FnOnce(&[T]) -> R>(mut iter: I, f: F) - -> Self::Output { + fn intern_with, F: FnOnce(&[T]) -> R>( + mut iter: I, + f: F, + ) -> Self::Output { // This code is hot enough that it's worth specializing for the most // common length lists, to avoid the overhead of `SmallVec` creation. // The match arms are in order of frequency. The 1, 2, and 0 cases are @@ -2954,9 +2800,7 @@ impl InternIteratorElement for Result { assert!(iter.next().is_none()); f(&[]) } - _ => { - f(&iter.collect::, _>>()?) - } + _ => f(&iter.collect::, _>>()?), }) } } @@ -2990,9 +2834,7 @@ pub fn provide(providers: &mut ty::query::Providers<'_>) { assert_eq!(id, LOCAL_CRATE); middle::diagnostic_items::collect_all(tcx) }; - providers.maybe_unused_trait_import = |tcx, id| { - tcx.maybe_unused_trait_imports.contains(&id) - }; + providers.maybe_unused_trait_import = |tcx, id| tcx.maybe_unused_trait_imports.contains(&id); providers.maybe_unused_extern_crates = |tcx, cnum| { assert_eq!(cnum, LOCAL_CRATE); &tcx.maybe_unused_extern_crates[..] diff --git a/src/librustc/ty/wf.rs b/src/librustc/ty/wf.rs index 8af98c6117e55..900c425fac2da 100644 --- a/src/librustc/ty/wf.rs +++ b/src/librustc/ty/wf.rs @@ -1,13 +1,13 @@ use crate::hir; use crate::hir::def_id::DefId; use crate::infer::InferCtxt; -use crate::ty::subst::SubstsRef; +use crate::middle::lang_items; use crate::traits::{self, AssocTypeBoundData}; +use crate::ty::subst::SubstsRef; use crate::ty::{self, ToPredicate, Ty, TyCtxt, TypeFoldable}; use std::iter::once; use syntax::symbol::{kw, Ident}; use syntax_pos::Span; -use crate::middle::lang_items; /// Returns the set of obligations needed to make `ty` well-formed. /// If `ty` contains unresolved inference variables, this may include @@ -22,14 +22,7 @@ pub fn obligations<'a, 'tcx>( ty: Ty<'tcx>, span: Span, ) -> Option>> { - let mut wf = WfPredicates { - infcx, - param_env, - body_id, - span, - out: vec![], - item: None, - }; + let mut wf = WfPredicates { infcx, param_env, body_id, span, out: vec![], item: None }; if wf.compute(ty) { debug!("wf::obligations({:?}, body_id={:?}) = {:?}", ty, body_id, wf.out); let result = wf.normalize(); @@ -71,8 +64,7 @@ pub fn predicate_obligations<'a, 'tcx>( ty::Predicate::Trait(ref t) => { wf.compute_trait_ref(&t.skip_binder().trait_ref, Elaborate::None); // (*) } - ty::Predicate::RegionOutlives(..) => { - } + ty::Predicate::RegionOutlives(..) => {} ty::Predicate::TypeOutlives(ref t) => { wf.compute(t.skip_binder().0); } @@ -84,10 +76,8 @@ pub fn predicate_obligations<'a, 'tcx>( ty::Predicate::WellFormed(t) => { wf.compute(t); } - ty::Predicate::ObjectSafe(_) => { - } - ty::Predicate::ClosureKind(..) => { - } + ty::Predicate::ObjectSafe(_) => {} + ty::Predicate::ClosureKind(..) => {} ty::Predicate::Subtype(ref data) => { wf.compute(data.skip_binder().a); // (*) wf.compute(data.skip_binder().b); // (*) @@ -152,14 +142,15 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { let cause = self.cause(traits::MiscObligation); let infcx = &mut self.infcx; let param_env = self.param_env; - self.out.iter() - .inspect(|pred| assert!(!pred.has_escaping_bound_vars())) - .flat_map(|pred| { - let mut selcx = traits::SelectionContext::new(infcx); - let pred = traits::normalize(&mut selcx, param_env, cause.clone(), pred); - once(pred.value).chain(pred.obligations) - }) - .collect() + self.out + .iter() + .inspect(|pred| assert!(!pred.has_escaping_bound_vars())) + .flat_map(|pred| { + let mut selcx = traits::SelectionContext::new(infcx); + let pred = traits::normalize(&mut selcx, param_env, cause.clone(), pred); + once(pred.value).chain(pred.obligations) + }) + .collect() } /// Pushes the obligations required for `trait_ref` to be WF into `self.out`. @@ -171,154 +162,163 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { let param_env = self.param_env; let item = &self.item; - let extend_cause_with_original_assoc_item_obligation = | - cause: &mut traits::ObligationCause<'_>, - pred: &ty::Predicate<'_>, - trait_assoc_items: ty::AssocItemsIterator<'_>, - | { - let trait_item = tcx.hir().as_local_hir_id(trait_ref.def_id).and_then(|trait_id| { - tcx.hir().find(trait_id) - }); - let (trait_name, trait_generics) = match trait_item { - Some(hir::Node::Item(hir::Item { - ident, - kind: hir::ItemKind::Trait(.., generics, _, _), - .. - })) | - Some(hir::Node::Item(hir::Item { - ident, - kind: hir::ItemKind::TraitAlias(generics, _), - .. - })) => (Some(ident), Some(generics)), - _ => (None, None), - }; - - let item_span = item.map(|i| tcx.sess.source_map().def_span(i.span)); - match pred { - ty::Predicate::Projection(proj) => { - // The obligation comes not from the current `impl` nor the `trait` being - // implemented, but rather from a "second order" obligation, like in - // `src/test/ui/associated-types/point-at-type-on-obligation-failure.rs`: - // - // error[E0271]: type mismatch resolving `::Ok == ()` - // --> $DIR/point-at-type-on-obligation-failure.rs:13:5 - // | - // LL | type Ok; - // | -- associated type defined here - // ... - // LL | impl Bar for Foo { - // | ---------------- in this `impl` item - // LL | type Ok = (); - // | ^^^^^^^^^^^^^ expected `u32`, found `()` - // | - // = note: expected type `u32` - // found type `()` - // - // FIXME: we would want to point a span to all places that contributed to this - // obligation. In the case above, it should be closer to: - // - // error[E0271]: type mismatch resolving `::Ok == ()` - // --> $DIR/point-at-type-on-obligation-failure.rs:13:5 - // | - // LL | type Ok; - // | -- associated type defined here - // LL | type Sibling: Bar2; - // | -------------------------------- obligation set here - // ... - // LL | impl Bar for Foo { - // | ---------------- in this `impl` item - // LL | type Ok = (); - // | ^^^^^^^^^^^^^ expected `u32`, found `()` - // ... - // LL | impl Bar2 for Foo2 { - // | ---------------- in this `impl` item - // LL | type Ok = u32; - // | -------------- obligation set here - // | - // = note: expected type `u32` - // found type `()` - if let Some(hir::ItemKind::Impl(.., impl_items)) = item.map(|i| &i.kind) { - let trait_assoc_item = tcx.associated_item(proj.projection_def_id()); - if let Some(impl_item) = impl_items.iter().filter(|item| { - item.ident == trait_assoc_item.ident - }).next() { - cause.span = impl_item.span; - cause.code = traits::AssocTypeBound(Box::new(AssocTypeBoundData { - impl_span: item_span, - original: trait_assoc_item.ident.span, - bounds: vec![], - })); + let extend_cause_with_original_assoc_item_obligation = + |cause: &mut traits::ObligationCause<'_>, + pred: &ty::Predicate<'_>, + trait_assoc_items: ty::AssocItemsIterator<'_>| { + let trait_item = tcx + .hir() + .as_local_hir_id(trait_ref.def_id) + .and_then(|trait_id| tcx.hir().find(trait_id)); + let (trait_name, trait_generics) = match trait_item { + Some(hir::Node::Item(hir::Item { + ident, + kind: hir::ItemKind::Trait(.., generics, _, _), + .. + })) + | Some(hir::Node::Item(hir::Item { + ident, + kind: hir::ItemKind::TraitAlias(generics, _), + .. + })) => (Some(ident), Some(generics)), + _ => (None, None), + }; + + let item_span = item.map(|i| tcx.sess.source_map().def_span(i.span)); + match pred { + ty::Predicate::Projection(proj) => { + // The obligation comes not from the current `impl` nor the `trait` being + // implemented, but rather from a "second order" obligation, like in + // `src/test/ui/associated-types/point-at-type-on-obligation-failure.rs`: + // + // error[E0271]: type mismatch resolving `::Ok == ()` + // --> $DIR/point-at-type-on-obligation-failure.rs:13:5 + // | + // LL | type Ok; + // | -- associated type defined here + // ... + // LL | impl Bar for Foo { + // | ---------------- in this `impl` item + // LL | type Ok = (); + // | ^^^^^^^^^^^^^ expected `u32`, found `()` + // | + // = note: expected type `u32` + // found type `()` + // + // FIXME: we would want to point a span to all places that contributed to this + // obligation. In the case above, it should be closer to: + // + // error[E0271]: type mismatch resolving `::Ok == ()` + // --> $DIR/point-at-type-on-obligation-failure.rs:13:5 + // | + // LL | type Ok; + // | -- associated type defined here + // LL | type Sibling: Bar2; + // | -------------------------------- obligation set here + // ... + // LL | impl Bar for Foo { + // | ---------------- in this `impl` item + // LL | type Ok = (); + // | ^^^^^^^^^^^^^ expected `u32`, found `()` + // ... + // LL | impl Bar2 for Foo2 { + // | ---------------- in this `impl` item + // LL | type Ok = u32; + // | -------------- obligation set here + // | + // = note: expected type `u32` + // found type `()` + if let Some(hir::ItemKind::Impl(.., impl_items)) = item.map(|i| &i.kind) { + let trait_assoc_item = tcx.associated_item(proj.projection_def_id()); + if let Some(impl_item) = impl_items + .iter() + .filter(|item| item.ident == trait_assoc_item.ident) + .next() + { + cause.span = impl_item.span; + cause.code = traits::AssocTypeBound(Box::new(AssocTypeBoundData { + impl_span: item_span, + original: trait_assoc_item.ident.span, + bounds: vec![], + })); + } } } - } - ty::Predicate::Trait(proj) => { - // An associated item obligation born out of the `trait` failed to be met. - // Point at the `impl` that failed the obligation, the associated item that - // needed to meet the obligation, and the definition of that associated item, - // which should hold the obligation in most cases. An example can be seen in - // `src/test/ui/associated-types/point-at-type-on-obligation-failure-2.rs`: - // - // error[E0277]: the trait bound `bool: Bar` is not satisfied - // --> $DIR/point-at-type-on-obligation-failure-2.rs:8:5 - // | - // LL | type Assoc: Bar; - // | ----- associated type defined here - // ... - // LL | impl Foo for () { - // | --------------- in this `impl` item - // LL | type Assoc = bool; - // | ^^^^^^^^^^^^^^^^^^ the trait `Bar` is not implemented for `bool` - // - // If the obligation comes from the where clause in the `trait`, we point at it: - // - // error[E0277]: the trait bound `bool: Bar` is not satisfied - // --> $DIR/point-at-type-on-obligation-failure-2.rs:8:5 - // | - // | trait Foo where >::Assoc: Bar { - // | -------------------------- restricted in this bound - // LL | type Assoc; - // | ----- associated type defined here - // ... - // LL | impl Foo for () { - // | --------------- in this `impl` item - // LL | type Assoc = bool; - // | ^^^^^^^^^^^^^^^^^^ the trait `Bar` is not implemented for `bool` - if let ( - ty::Projection(ty::ProjectionTy { item_def_id, .. }), - Some(hir::ItemKind::Impl(.., impl_items)), - ) = (&proj.skip_binder().self_ty().kind, item.map(|i| &i.kind)) { - if let Some((impl_item, trait_assoc_item)) = trait_assoc_items - .filter(|i| i.def_id == *item_def_id) - .next() - .and_then(|trait_assoc_item| impl_items.iter() - .filter(|i| i.ident == trait_assoc_item.ident) - .next() - .map(|impl_item| (impl_item, trait_assoc_item))) + ty::Predicate::Trait(proj) => { + // An associated item obligation born out of the `trait` failed to be met. + // Point at the `impl` that failed the obligation, the associated item that + // needed to meet the obligation, and the definition of that associated item, + // which should hold the obligation in most cases. An example can be seen in + // `src/test/ui/associated-types/point-at-type-on-obligation-failure-2.rs`: + // + // error[E0277]: the trait bound `bool: Bar` is not satisfied + // --> $DIR/point-at-type-on-obligation-failure-2.rs:8:5 + // | + // LL | type Assoc: Bar; + // | ----- associated type defined here + // ... + // LL | impl Foo for () { + // | --------------- in this `impl` item + // LL | type Assoc = bool; + // | ^^^^^^^^^^^^^^^^^^ the trait `Bar` is not implemented for `bool` + // + // If the obligation comes from the where clause in the `trait`, we point at it: + // + // error[E0277]: the trait bound `bool: Bar` is not satisfied + // --> $DIR/point-at-type-on-obligation-failure-2.rs:8:5 + // | + // | trait Foo where >::Assoc: Bar { + // | -------------------------- restricted in this bound + // LL | type Assoc; + // | ----- associated type defined here + // ... + // LL | impl Foo for () { + // | --------------- in this `impl` item + // LL | type Assoc = bool; + // | ^^^^^^^^^^^^^^^^^^ the trait `Bar` is not implemented for `bool` + if let ( + ty::Projection(ty::ProjectionTy { item_def_id, .. }), + Some(hir::ItemKind::Impl(.., impl_items)), + ) = (&proj.skip_binder().self_ty().kind, item.map(|i| &i.kind)) { - let bounds = trait_generics.map(|generics| get_generic_bound_spans( - &generics, - trait_name, - trait_assoc_item.ident, - )).unwrap_or_else(Vec::new); - cause.span = impl_item.span; - cause.code = traits::AssocTypeBound(Box::new(AssocTypeBoundData { - impl_span: item_span, - original: trait_assoc_item.ident.span, - bounds, - })); + if let Some((impl_item, trait_assoc_item)) = trait_assoc_items + .filter(|i| i.def_id == *item_def_id) + .next() + .and_then(|trait_assoc_item| { + impl_items + .iter() + .filter(|i| i.ident == trait_assoc_item.ident) + .next() + .map(|impl_item| (impl_item, trait_assoc_item)) + }) + { + let bounds = trait_generics + .map(|generics| { + get_generic_bound_spans( + &generics, + trait_name, + trait_assoc_item.ident, + ) + }) + .unwrap_or_else(Vec::new); + cause.span = impl_item.span; + cause.code = traits::AssocTypeBound(Box::new(AssocTypeBoundData { + impl_span: item_span, + original: trait_assoc_item.ident.span, + bounds, + })); + } } } + _ => {} } - _ => {} - } - }; + }; if let Elaborate::All = elaborate { let trait_assoc_items = tcx.associated_items(trait_ref.def_id); - let predicates = obligations.iter() - .map(|obligation| obligation.predicate.clone()) - .collect(); + let predicates = + obligations.iter().map(|obligation| obligation.predicate.clone()).collect(); let implied_obligations = traits::elaborate_predicates(tcx, predicates); let implied_obligations = implied_obligations.map(|pred| { let mut cause = cause.clone(); @@ -334,13 +334,9 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { self.out.extend(obligations); - self.out.extend(trait_ref.substs.types() - .filter(|ty| !ty.has_escaping_bound_vars()) - .map(|ty| traits::Obligation::new( - cause.clone(), - param_env, - ty::Predicate::WellFormed(ty), - ))); + self.out.extend(trait_ref.substs.types().filter(|ty| !ty.has_escaping_bound_vars()).map( + |ty| traits::Obligation::new(cause.clone(), param_env, ty::Predicate::WellFormed(ty)), + )); } /// Pushes the obligations required for `trait_ref::Item` to be WF @@ -368,9 +364,7 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { let predicate = ty::Predicate::ConstEvaluatable(def_id, substs); let cause = self.cause(traits::MiscObligation); - self.out.push(traits::Obligation::new(cause, - self.param_env, - predicate)); + self.out.push(traits::Obligation::new(cause, self.param_env, predicate)); } } @@ -394,19 +388,19 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { let param_env = self.param_env; while let Some(ty) = subtys.next() { match ty.kind { - ty::Bool | - ty::Char | - ty::Int(..) | - ty::Uint(..) | - ty::Float(..) | - ty::Error | - ty::Str | - ty::GeneratorWitness(..) | - ty::Never | - ty::Param(_) | - ty::Bound(..) | - ty::Placeholder(..) | - ty::Foreign(..) => { + ty::Bool + | ty::Char + | ty::Int(..) + | ty::Uint(..) + | ty::Float(..) + | ty::Error + | ty::Str + | ty::GeneratorWitness(..) + | ty::Never + | ty::Param(_) + | ty::Bound(..) + | ty::Placeholder(..) + | ty::Foreign(..) => { // WfScalar, WfParameter, etc } @@ -453,13 +447,13 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { // WfReference if !r.has_escaping_bound_vars() && !rty.has_escaping_bound_vars() { let cause = self.cause(traits::ReferenceOutlivesReferent(ty)); - self.out.push( - traits::Obligation::new( - cause, - param_env, - ty::Predicate::TypeOutlives( - ty::Binder::dummy( - ty::OutlivesPredicate(rty, r))))); + self.out.push(traits::Obligation::new( + cause, + param_env, + ty::Predicate::TypeOutlives(ty::Binder::dummy(ty::OutlivesPredicate( + rty, r, + ))), + )); } } @@ -537,20 +531,18 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { // obligations that don't refer to Self and // checking those - let defer_to_coercion = - self.infcx.tcx.features().object_safe_for_dispatch; + let defer_to_coercion = self.infcx.tcx.features().object_safe_for_dispatch; if !defer_to_coercion { let cause = self.cause(traits::MiscObligation); - let component_traits = - data.auto_traits().chain(data.principal_def_id()); - self.out.extend( - component_traits.map(|did| traits::Obligation::new( + let component_traits = data.auto_traits().chain(data.principal_def_id()); + self.out.extend(component_traits.map(|did| { + traits::Obligation::new( cause.clone(), param_env, - ty::Predicate::ObjectSafe(did) - )) - ); + ty::Predicate::ObjectSafe(did), + ) + })); } } @@ -569,16 +561,22 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { // is satisfied to ensure termination.) ty::Infer(_) => { let ty = self.infcx.shallow_resolve(ty); - if let ty::Infer(_) = ty.kind { // not yet resolved... - if ty == ty0 { // ...this is the type we started from! no progress. + if let ty::Infer(_) = ty.kind { + // not yet resolved... + if ty == ty0 { + // ...this is the type we started from! no progress. return false; } let cause = self.cause(traits::MiscObligation); - self.out.push( // ...not the type we started from, so we made progress. - traits::Obligation::new(cause, - self.param_env, - ty::Predicate::WellFormed(ty))); + self.out.push( + // ...not the type we started from, so we made progress. + traits::Obligation::new( + cause, + self.param_env, + ty::Predicate::WellFormed(ty), + ), + ); } else { // Yes, resolved, proceed with the // result. Should never return false because @@ -593,27 +591,27 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { return true; } - fn nominal_obligations(&mut self, - def_id: DefId, - substs: SubstsRef<'tcx>) - -> Vec> - { - let predicates = - self.infcx.tcx.predicates_of(def_id) - .instantiate(self.infcx.tcx, substs); + fn nominal_obligations( + &mut self, + def_id: DefId, + substs: SubstsRef<'tcx>, + ) -> Vec> { + let predicates = self.infcx.tcx.predicates_of(def_id).instantiate(self.infcx.tcx, substs); let cause = self.cause(traits::ItemObligation(def_id)); - predicates.predicates - .into_iter() - .map(|pred| traits::Obligation::new(cause.clone(), - self.param_env, - pred)) - .filter(|pred| !pred.has_escaping_bound_vars()) - .collect() + predicates + .predicates + .into_iter() + .map(|pred| traits::Obligation::new(cause.clone(), self.param_env, pred)) + .filter(|pred| !pred.has_escaping_bound_vars()) + .collect() } - fn from_object_ty(&mut self, ty: Ty<'tcx>, - data: ty::Binder<&'tcx ty::List>>, - region: ty::Region<'tcx>) { + fn from_object_ty( + &mut self, + ty: Ty<'tcx>, + data: ty::Binder<&'tcx ty::List>>, + region: ty::Region<'tcx>, + ) { // Imagine a type like this: // // trait Foo { } @@ -646,19 +644,20 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { // Note: in fact we only permit builtin traits, not `Bar<'d>`, I // am looking forward to the future here. if !data.has_escaping_bound_vars() && !region.has_escaping_bound_vars() { - let implicit_bounds = - object_region_bounds(self.infcx.tcx, data); + let implicit_bounds = object_region_bounds(self.infcx.tcx, data); let explicit_bound = region; self.out.reserve(implicit_bounds.len()); for implicit_bound in implicit_bounds { let cause = self.cause(traits::ObjectTypeBound(ty, explicit_bound)); - let outlives = ty::Binder::dummy( - ty::OutlivesPredicate(explicit_bound, implicit_bound)); - self.out.push(traits::Obligation::new(cause, - self.param_env, - outlives.to_predicate())); + let outlives = + ty::Binder::dummy(ty::OutlivesPredicate(explicit_bound, implicit_bound)); + self.out.push(traits::Obligation::new( + cause, + self.param_env, + outlives.to_predicate(), + )); } } } @@ -679,13 +678,16 @@ pub fn object_region_bounds<'tcx>( // a placeholder type. let open_ty = tcx.mk_ty_infer(ty::FreshTy(0)); - let predicates = existential_predicates.iter().filter_map(|predicate| { - if let ty::ExistentialPredicate::Projection(_) = *predicate.skip_binder() { - None - } else { - Some(predicate.with_self_ty(tcx, open_ty)) - } - }).collect(); + let predicates = existential_predicates + .iter() + .filter_map(|predicate| { + if let ty::ExistentialPredicate::Projection(_) = *predicate.skip_binder() { + None + } else { + Some(predicate.with_self_ty(tcx, open_ty)) + } + }) + .collect(); tcx.required_region_bounds(open_ty, predicates) } diff --git a/src/librustc_codegen_llvm/back/write.rs b/src/librustc_codegen_llvm/back/write.rs index 796ea7aac36a2..818d09ce6914a 100644 --- a/src/librustc_codegen_llvm/back/write.rs +++ b/src/librustc_codegen_llvm/back/write.rs @@ -2,38 +2,38 @@ use crate::attributes; use crate::back::bytecode; use crate::back::lto::ThinBuffer; use crate::base; +use crate::common; use crate::consts; +use crate::context::{get_reloc_model, is_pie_binary}; use crate::llvm::{self, DiagnosticInfo, PassManager, SMDiagnostic}; use crate::llvm_util; -use crate::ModuleLlvm; use crate::type_::Type; -use crate::context::{is_pie_binary, get_reloc_model}; -use crate::common; use crate::LlvmCodegenBackend; +use crate::ModuleLlvm; +use log::debug; use rustc::bug; use rustc::hir::def_id::LOCAL_CRATE; -use rustc_codegen_ssa::back::write::{CodegenContext, ModuleConfig, run_assembler}; -use rustc_codegen_ssa::traits::*; -use rustc::session::config::{self, OutputType, Passes, Lto, Sanitizer, SwitchWithOptPath}; +use rustc::session::config::{self, Lto, OutputType, Passes, Sanitizer, SwitchWithOptPath}; use rustc::session::Session; use rustc::ty::TyCtxt; -use rustc_codegen_ssa::{RLIB_BYTECODE_EXTENSION, ModuleCodegen, CompiledModule}; use rustc::util::common::time_ext; -use rustc_fs_util::{path_to_c_string, link_or_copy}; +use rustc_codegen_ssa::back::write::{run_assembler, CodegenContext, ModuleConfig}; +use rustc_codegen_ssa::traits::*; +use rustc_codegen_ssa::{CompiledModule, ModuleCodegen, RLIB_BYTECODE_EXTENSION}; use rustc_data_structures::small_c_str::SmallCStr; -use rustc_errors::{Handler, FatalError}; -use log::debug; +use rustc_errors::{FatalError, Handler}; +use rustc_fs_util::{link_or_copy, path_to_c_string}; +use libc::{c_char, c_int, c_uint, c_void, size_t}; use std::ffi::CString; use std::fs; use std::io::{self, Write}; use std::path::{Path, PathBuf}; +use std::slice; use std::str; use std::sync::Arc; -use std::slice; -use libc::{c_int, c_uint, c_void, c_char, size_t}; -pub const RELOC_MODEL_ARGS : [(&str, llvm::RelocMode); 7] = [ +pub const RELOC_MODEL_ARGS: [(&str, llvm::RelocMode); 7] = [ ("pic", llvm::RelocMode::PIC), ("static", llvm::RelocMode::Static), ("default", llvm::RelocMode::Default), @@ -50,7 +50,7 @@ pub const CODE_GEN_MODEL_ARGS: &[(&str, llvm::CodeModel)] = &[ ("large", llvm::CodeModel::Large), ]; -pub const TLS_MODEL_ARGS : [(&str, llvm::ThreadLocalMode); 4] = [ +pub const TLS_MODEL_ARGS: [(&str, llvm::ThreadLocalMode); 4] = [ ("global-dynamic", llvm::ThreadLocalMode::GeneralDynamic), ("local-dynamic", llvm::ThreadLocalMode::LocalDynamic), ("initial-exec", llvm::ThreadLocalMode::InitialExec), @@ -65,12 +65,13 @@ pub fn llvm_err(handler: &rustc_errors::Handler, msg: &str) -> FatalError { } pub fn write_output_file( - handler: &rustc_errors::Handler, - target: &'ll llvm::TargetMachine, - pm: &llvm::PassManager<'ll>, - m: &'ll llvm::Module, - output: &Path, - file_type: llvm::FileType) -> Result<(), FatalError> { + handler: &rustc_errors::Handler, + target: &'ll llvm::TargetMachine, + pm: &llvm::PassManager<'ll>, + m: &'ll llvm::Module, + output: &Path, + file_type: llvm::FileType, +) -> Result<(), FatalError> { unsafe { let output_c = path_to_c_string(output); let result = llvm::LLVMRustWriteOutputFile(target, pm, m, output_c.as_ptr(), file_type); @@ -85,9 +86,8 @@ pub fn create_informational_target_machine( sess: &Session, find_features: bool, ) -> &'static mut llvm::TargetMachine { - target_machine_factory(sess, config::OptLevel::No, find_features)().unwrap_or_else(|err| { - llvm_err(sess.diagnostic(), &err).raise() - }) + target_machine_factory(sess, config::OptLevel::No, find_features)() + .unwrap_or_else(|err| llvm_err(sess.diagnostic(), &err).raise()) } pub fn create_target_machine( @@ -95,13 +95,12 @@ pub fn create_target_machine( find_features: bool, ) -> &'static mut llvm::TargetMachine { target_machine_factory(&tcx.sess, tcx.backend_optimization_level(LOCAL_CRATE), find_features)() - .unwrap_or_else(|err| { - llvm_err(tcx.sess.diagnostic(), &err).raise() - }) + .unwrap_or_else(|err| llvm_err(tcx.sess.diagnostic(), &err).raise()) } -pub fn to_llvm_opt_settings(cfg: config::OptLevel) -> (llvm::CodeGenOptLevel, llvm::CodeGenOptSize) -{ +pub fn to_llvm_opt_settings( + cfg: config::OptLevel, +) -> (llvm::CodeGenOptLevel, llvm::CodeGenOptSize) { use self::config::OptLevel::*; match cfg { No => (llvm::CodeGenOptLevel::None, llvm::CodeGenOptSizeNone), @@ -116,9 +115,11 @@ pub fn to_llvm_opt_settings(cfg: config::OptLevel) -> (llvm::CodeGenOptLevel, ll // If find_features is true this won't access `sess.crate_types` by assuming // that `is_pie_binary` is false. When we discover LLVM target features // `sess.crate_types` is uninitialized so we cannot access it. -pub fn target_machine_factory(sess: &Session, optlvl: config::OptLevel, find_features: bool) - -> Arc Result<&'static mut llvm::TargetMachine, String> + Send + Sync> -{ +pub fn target_machine_factory( + sess: &Session, + optlvl: config::OptLevel, + find_features: bool, +) -> Arc Result<&'static mut llvm::TargetMachine, String> + Send + Sync> { let reloc_model = get_reloc_model(sess); let (opt_level, _) = to_llvm_opt_settings(optlvl); @@ -127,22 +128,18 @@ pub fn target_machine_factory(sess: &Session, optlvl: config::OptLevel, find_fea let ffunction_sections = sess.target.target.options.function_sections; let fdata_sections = ffunction_sections; - let code_model_arg = sess.opts.cg.code_model.as_ref().or( - sess.target.target.options.code_model.as_ref(), - ); + let code_model_arg = + sess.opts.cg.code_model.as_ref().or(sess.target.target.options.code_model.as_ref()); let code_model = match code_model_arg { - Some(s) => { - match CODE_GEN_MODEL_ARGS.iter().find(|arg| arg.0 == s) { - Some(x) => x.1, - _ => { - sess.err(&format!("{:?} is not a valid code model", - code_model_arg)); - sess.abort_if_errors(); - bug!(); - } + Some(s) => match CODE_GEN_MODEL_ARGS.iter().find(|arg| arg.0 == s) { + Some(x) => x.1, + _ => { + sess.err(&format!("{:?} is not a valid code model", code_model_arg)); + sess.abort_if_errors(); + bug!(); } - } + }, None => llvm::CodeModel::None, }; @@ -152,9 +149,9 @@ pub fn target_machine_factory(sess: &Session, optlvl: config::OptLevel, find_fea // On the wasm target once the `atomics` feature is enabled that means that // we're no longer single-threaded, or otherwise we don't want LLVM to // lower atomic operations to single-threaded operations. - if singlethread && - sess.target.target.llvm_target.contains("wasm32") && - features.iter().any(|s| *s == "+atomics") + if singlethread + && sess.target.target.llvm_target.contains("wasm32") + && features.iter().any(|s| *s == "+atomics") { singlethread = false; } @@ -173,7 +170,10 @@ pub fn target_machine_factory(sess: &Session, optlvl: config::OptLevel, find_fea Arc::new(move || { let tm = unsafe { llvm::LLVMRustCreateTargetMachine( - triple.as_ptr(), cpu.as_ptr(), features.as_ptr(), abi.as_ptr(), + triple.as_ptr(), + cpu.as_ptr(), + features.as_ptr(), + abi.as_ptr(), code_model, reloc_model, opt_level, @@ -190,8 +190,7 @@ pub fn target_machine_factory(sess: &Session, optlvl: config::OptLevel, find_fea }; tm.ok_or_else(|| { - format!("Could not create LLVM TargetMachine for triple: {}", - triple.to_str().unwrap()) + format!("Could not create LLVM TargetMachine for triple: {}", triple.to_str().unwrap()) }) }) } @@ -199,10 +198,10 @@ pub fn target_machine_factory(sess: &Session, optlvl: config::OptLevel, find_fea pub(crate) fn save_temp_bitcode( cgcx: &CodegenContext, module: &ModuleCodegen, - name: &str + name: &str, ) { if !cgcx.save_temps { - return + return; } unsafe { let ext = format!("{}.bc", name); @@ -220,9 +219,11 @@ pub struct DiagnosticHandlers<'a> { } impl<'a> DiagnosticHandlers<'a> { - pub fn new(cgcx: &'a CodegenContext, - handler: &'a Handler, - llcx: &'a llvm::Context) -> Self { + pub fn new( + cgcx: &'a CodegenContext, + handler: &'a Handler, + llcx: &'a llvm::Context, + ) -> Self { let data = Box::into_raw(Box::new((cgcx, handler))); unsafe { llvm::LLVMRustSetInlineAsmDiagnosticHandler(llcx, inline_asm_handler, data.cast()); @@ -243,17 +244,17 @@ impl<'a> Drop for DiagnosticHandlers<'a> { } } -unsafe extern "C" fn report_inline_asm(cgcx: &CodegenContext, - msg: &str, - cookie: c_uint) { +unsafe extern "C" fn report_inline_asm( + cgcx: &CodegenContext, + msg: &str, + cookie: c_uint, +) { cgcx.diag_emitter.inline_asm_error(cookie as u32, msg.to_owned()); } -unsafe extern "C" fn inline_asm_handler(diag: &SMDiagnostic, - user: *const c_void, - cookie: c_uint) { +unsafe extern "C" fn inline_asm_handler(diag: &SMDiagnostic, user: *const c_void, cookie: c_uint) { if user.is_null() { - return + return; } let (cgcx, _) = *(user as *const (&CodegenContext, &Handler)); @@ -265,15 +266,13 @@ unsafe extern "C" fn inline_asm_handler(diag: &SMDiagnostic, unsafe extern "C" fn diagnostic_handler(info: &DiagnosticInfo, user: *mut c_void) { if user.is_null() { - return + return; } let (cgcx, diag_handler) = *(user as *const (&CodegenContext, &Handler)); match llvm::diagnostic::Diagnostic::unpack(info) { llvm::diagnostic::InlineAsm(inline) => { - report_inline_asm(cgcx, - &llvm::twine_to_string(inline.message), - inline.cookie); + report_inline_asm(cgcx, &llvm::twine_to_string(inline.message), inline.cookie); } llvm::diagnostic::Optimization(opt) => { @@ -283,33 +282,35 @@ unsafe extern "C" fn diagnostic_handler(info: &DiagnosticInfo, user: *mut c_void }; if enabled { - diag_handler.note_without_error(&format!("optimization {} for {} at {}:{}:{}: {}", - opt.kind.describe(), - opt.pass_name, - opt.filename, - opt.line, - opt.column, - opt.message)); + diag_handler.note_without_error(&format!( + "optimization {} for {} at {}:{}:{}: {}", + opt.kind.describe(), + opt.pass_name, + opt.filename, + opt.line, + opt.column, + opt.message + )); } } - llvm::diagnostic::PGO(diagnostic_ref) | - llvm::diagnostic::Linker(diagnostic_ref) => { + llvm::diagnostic::PGO(diagnostic_ref) | llvm::diagnostic::Linker(diagnostic_ref) => { let msg = llvm::build_string(|s| { llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s) - }).expect("non-UTF8 diagnostic"); + }) + .expect("non-UTF8 diagnostic"); diag_handler.warn(&msg); } - llvm::diagnostic::UnknownDiagnostic(..) => {}, + llvm::diagnostic::UnknownDiagnostic(..) => {} } } // Unsafe due to LLVM calls. -pub(crate) unsafe fn optimize(cgcx: &CodegenContext, - diag_handler: &Handler, - module: &ModuleCodegen, - config: &ModuleConfig) - -> Result<(), FatalError> -{ +pub(crate) unsafe fn optimize( + cgcx: &CodegenContext, + diag_handler: &Handler, + module: &ModuleCodegen, + config: &ModuleConfig, +) -> Result<(), FatalError> { let _timer = cgcx.prof.generic_activity("LLVM_module_optimize"); let llmod = module.module_llvm.llmod(); @@ -376,11 +377,15 @@ pub(crate) unsafe fn optimize(cgcx: &CodegenContext, llvm::LLVMAddAnalysisPasses(tm, fpm); llvm::LLVMAddAnalysisPasses(tm, mpm); let opt_level = to_llvm_opt_settings(opt_level).0; - let prepare_for_thin_lto = cgcx.lto == Lto::Thin || cgcx.lto == Lto::ThinLocal || - (cgcx.lto != Lto::Fat && cgcx.opts.cg.linker_plugin_lto.enabled()); + let prepare_for_thin_lto = cgcx.lto == Lto::Thin + || cgcx.lto == Lto::ThinLocal + || (cgcx.lto != Lto::Fat && cgcx.opts.cg.linker_plugin_lto.enabled()); with_llvm_pmb(llmod, &config, opt_level, prepare_for_thin_lto, &mut |b| { llvm::LLVMRustAddLastExtensionPasses( - b, extra_passes.as_ptr(), extra_passes.len() as size_t); + b, + extra_passes.as_ptr(), + extra_passes.len() as size_t, + ); llvm::LLVMPassManagerBuilderPopulateFunctionPassManager(b, fpm); llvm::LLVMPassManagerBuilderPopulateModulePassManager(b, mpm); }); @@ -401,13 +406,17 @@ pub(crate) unsafe fn optimize(cgcx: &CodegenContext, if using_thin_buffers && !have_name_anon_globals_pass { // As described above, this will probably cause an error in LLVM if config.no_prepopulate_passes { - diag_handler.err("The current compilation is going to use thin LTO buffers \ + diag_handler.err( + "The current compilation is going to use thin LTO buffers \ without running LLVM's NameAnonGlobals pass. \ This will likely cause errors in LLVM. Consider adding \ - -C passes=name-anon-globals to the compiler command line."); + -C passes=name-anon-globals to the compiler command line.", + ); } else { - bug!("We are using thin LTO buffers without running the NameAnonGlobals pass. \ - This will likely cause errors in LLVM and should never happen."); + bug!( + "We are using thin LTO buffers without running the NameAnonGlobals pass. \ + This will likely cause errors in LLVM and should never happen." + ); } } } @@ -417,19 +426,19 @@ pub(crate) unsafe fn optimize(cgcx: &CodegenContext, // Finally, run the actual optimization passes { let _timer = cgcx.prof.generic_activity("LLVM_module_optimize_function_passes"); - time_ext(config.time_passes, - &format!("llvm function passes [{}]", module_name.unwrap()), - || { - llvm::LLVMRustRunFunctionPassManager(fpm, llmod) - }); + time_ext( + config.time_passes, + &format!("llvm function passes [{}]", module_name.unwrap()), + || llvm::LLVMRustRunFunctionPassManager(fpm, llmod), + ); } { let _timer = cgcx.prof.generic_activity("LLVM_module_optimize_module_passes"); - time_ext(config.time_passes, - &format!("llvm module passes [{}]", module_name.unwrap()), - || { - llvm::LLVMRunPassManager(mpm, llmod) - }); + time_ext( + config.time_passes, + &format!("llvm module passes [{}]", module_name.unwrap()), + || llvm::LLVMRunPassManager(mpm, llmod), + ); } // Deallocate managers that we're now done with @@ -439,9 +448,7 @@ pub(crate) unsafe fn optimize(cgcx: &CodegenContext, Ok(()) } -unsafe fn add_sanitizer_passes(config: &ModuleConfig, - passes: &mut Vec<&'static mut llvm::Pass>) { - +unsafe fn add_sanitizer_passes(config: &ModuleConfig, passes: &mut Vec<&'static mut llvm::Pass>) { let sanitizer = match &config.sanitizer { None => return, Some(s) => s, @@ -464,12 +471,12 @@ unsafe fn add_sanitizer_passes(config: &ModuleConfig, } } -pub(crate) unsafe fn codegen(cgcx: &CodegenContext, - diag_handler: &Handler, - module: ModuleCodegen, - config: &ModuleConfig) - -> Result -{ +pub(crate) unsafe fn codegen( + cgcx: &CodegenContext, + diag_handler: &Handler, + module: ModuleCodegen, + config: &ModuleConfig, +) -> Result { let _timer = cgcx.prof.generic_activity("LLVM_module_codegen"); { let llmod = module.module_llvm.llmod(); @@ -491,11 +498,14 @@ pub(crate) unsafe fn codegen(cgcx: &CodegenContext, // pass manager passed to the closure should be ensured to not // escape the closure itself, and the manager should only be // used once. - unsafe fn with_codegen<'ll, F, R>(tm: &'ll llvm::TargetMachine, - llmod: &'ll llvm::Module, - no_builtins: bool, - f: F) -> R - where F: FnOnce(&'ll mut PassManager<'ll>) -> R, + unsafe fn with_codegen<'ll, F, R>( + tm: &'ll llvm::TargetMachine, + llmod: &'ll llvm::Module, + no_builtins: bool, + f: F, + ) -> R + where + F: FnOnce(&'ll mut PassManager<'ll>) -> R, { let cpm = llvm::LLVMCreatePassManager(); llvm::LLVMAddAnalysisPasses(tm, cpm); @@ -519,7 +529,6 @@ pub(crate) unsafe fn codegen(cgcx: &CodegenContext, let bc_out = cgcx.output_filenames.temp_path(OutputType::Bitcode, module_name); let obj_out = cgcx.output_filenames.temp_path(OutputType::Object, module_name); - if write_bc || config.emit_bc_compressed || config.embed_bitcode { let _timer = cgcx.prof.generic_activity("LLVM_module_codegen_make_bitcode"); let thin = ThinBuffer::new(llmod); @@ -552,88 +561,103 @@ pub(crate) unsafe fn codegen(cgcx: &CodegenContext, embed_bitcode(cgcx, llcx, llmod, None); } - time_ext(config.time_passes, &format!("codegen passes [{}]", module_name.unwrap()), + time_ext( + config.time_passes, + &format!("codegen passes [{}]", module_name.unwrap()), || -> Result<(), FatalError> { - if config.emit_ir { - let _timer = cgcx.prof.generic_activity("LLVM_module_codegen_emit_ir"); - let out = cgcx.output_filenames.temp_path(OutputType::LlvmAssembly, module_name); - let out_c = path_to_c_string(&out); - - extern "C" fn demangle_callback(input_ptr: *const c_char, - input_len: size_t, - output_ptr: *mut c_char, - output_len: size_t) -> size_t { - let input = unsafe { - slice::from_raw_parts(input_ptr as *const u8, input_len as usize) - }; - - let input = match str::from_utf8(input) { - Ok(s) => s, - Err(_) => return 0, - }; - - let output = unsafe { - slice::from_raw_parts_mut(output_ptr as *mut u8, output_len as usize) - }; - let mut cursor = io::Cursor::new(output); - - let demangled = match rustc_demangle::try_demangle(input) { - Ok(d) => d, - Err(_) => return 0, - }; - - if let Err(_) = write!(cursor, "{:#}", demangled) { - // Possible only if provided buffer is not big enough - return 0; + if config.emit_ir { + let _timer = cgcx.prof.generic_activity("LLVM_module_codegen_emit_ir"); + let out = + cgcx.output_filenames.temp_path(OutputType::LlvmAssembly, module_name); + let out_c = path_to_c_string(&out); + + extern "C" fn demangle_callback( + input_ptr: *const c_char, + input_len: size_t, + output_ptr: *mut c_char, + output_len: size_t, + ) -> size_t { + let input = unsafe { + slice::from_raw_parts(input_ptr as *const u8, input_len as usize) + }; + + let input = match str::from_utf8(input) { + Ok(s) => s, + Err(_) => return 0, + }; + + let output = unsafe { + slice::from_raw_parts_mut(output_ptr as *mut u8, output_len as usize) + }; + let mut cursor = io::Cursor::new(output); + + let demangled = match rustc_demangle::try_demangle(input) { + Ok(d) => d, + Err(_) => return 0, + }; + + if let Err(_) = write!(cursor, "{:#}", demangled) { + // Possible only if provided buffer is not big enough + return 0; + } + + cursor.position() as size_t } - cursor.position() as size_t + let result = + llvm::LLVMRustPrintModule(llmod, out_c.as_ptr(), demangle_callback); + result.into_result().map_err(|()| { + let msg = format!("failed to write LLVM IR to {}", out.display()); + llvm_err(diag_handler, &msg) + })?; } - let result = - llvm::LLVMRustPrintModule(llmod, out_c.as_ptr(), demangle_callback); - result.into_result().map_err(|()| { - let msg = format!("failed to write LLVM IR to {}", out.display()); - llvm_err(diag_handler, &msg) - })?; - } - - if config.emit_asm || asm_to_obj { - let _timer = cgcx.prof.generic_activity("LLVM_module_codegen_emit_asm"); - let path = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name); - - // We can't use the same module for asm and binary output, because that triggers - // various errors like invalid IR or broken binaries, so we might have to clone the - // module to produce the asm output - let llmod = if config.emit_obj { - llvm::LLVMCloneModule(llmod) - } else { - llmod - }; - with_codegen(tm, llmod, config.no_builtins, |cpm| { - write_output_file(diag_handler, tm, cpm, llmod, &path, - llvm::FileType::AssemblyFile) - })?; - } + if config.emit_asm || asm_to_obj { + let _timer = cgcx.prof.generic_activity("LLVM_module_codegen_emit_asm"); + let path = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name); + + // We can't use the same module for asm and binary output, because that triggers + // various errors like invalid IR or broken binaries, so we might have to clone the + // module to produce the asm output + let llmod = if config.emit_obj { llvm::LLVMCloneModule(llmod) } else { llmod }; + with_codegen(tm, llmod, config.no_builtins, |cpm| { + write_output_file( + diag_handler, + tm, + cpm, + llmod, + &path, + llvm::FileType::AssemblyFile, + ) + })?; + } - if write_obj { - let _timer = cgcx.prof.generic_activity("LLVM_module_codegen_emit_obj"); - with_codegen(tm, llmod, config.no_builtins, |cpm| { - write_output_file(diag_handler, tm, cpm, llmod, &obj_out, - llvm::FileType::ObjectFile) - })?; - } else if asm_to_obj { - let _timer = cgcx.prof.generic_activity("LLVM_module_codegen_asm_to_obj"); - let assembly = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name); - run_assembler(cgcx, diag_handler, &assembly, &obj_out); - - if !config.emit_asm && !cgcx.save_temps { - drop(fs::remove_file(&assembly)); + if write_obj { + let _timer = cgcx.prof.generic_activity("LLVM_module_codegen_emit_obj"); + with_codegen(tm, llmod, config.no_builtins, |cpm| { + write_output_file( + diag_handler, + tm, + cpm, + llmod, + &obj_out, + llvm::FileType::ObjectFile, + ) + })?; + } else if asm_to_obj { + let _timer = cgcx.prof.generic_activity("LLVM_module_codegen_asm_to_obj"); + let assembly = + cgcx.output_filenames.temp_path(OutputType::Assembly, module_name); + run_assembler(cgcx, diag_handler, &assembly, &obj_out); + + if !config.emit_asm && !cgcx.save_temps { + drop(fs::remove_file(&assembly)); + } } - } - Ok(()) - })?; + Ok(()) + }, + )?; if copy_bc_to_obj { debug!("copying bitcode {:?} to obj {:?}", bc_out, obj_out); @@ -651,10 +675,12 @@ pub(crate) unsafe fn codegen(cgcx: &CodegenContext, drop(handlers); } - Ok(module.into_compiled_module(config.emit_obj, - config.emit_bc, - config.emit_bc_compressed, - &cgcx.output_filenames)) + Ok(module.into_compiled_module( + config.emit_obj, + config.emit_bc, + config.emit_bc_compressed, + &cgcx.output_filenames, + )) } /// Embed the bitcode of an LLVM module in the LLVM module itself. @@ -675,10 +701,12 @@ pub(crate) unsafe fn codegen(cgcx: &CodegenContext, /// /// Basically all of this is us attempting to follow in the footsteps of clang /// on iOS. See #35968 for lots more info. -unsafe fn embed_bitcode(cgcx: &CodegenContext, - llcx: &llvm::Context, - llmod: &llvm::Module, - bitcode: Option<&[u8]>) { +unsafe fn embed_bitcode( + cgcx: &CodegenContext, + llcx: &llvm::Context, + llmod: &llvm::Module, + bitcode: Option<&[u8]>, +) { let llconst = common::bytes_in_context(llcx, bitcode.unwrap_or(&[])); let llglobal = llvm::LLVMAddGlobal( llmod, @@ -687,14 +715,10 @@ unsafe fn embed_bitcode(cgcx: &CodegenContext, ); llvm::LLVMSetInitializer(llglobal, llconst); - let is_apple = cgcx.opts.target_triple.triple().contains("-ios") || - cgcx.opts.target_triple.triple().contains("-darwin"); + let is_apple = cgcx.opts.target_triple.triple().contains("-ios") + || cgcx.opts.target_triple.triple().contains("-darwin"); - let section = if is_apple { - "__LLVM,__bitcode\0" - } else { - ".llvmbc\0" - }; + let section = if is_apple { "__LLVM,__bitcode\0" } else { ".llvmbc\0" }; llvm::LLVMSetSection(llglobal, section.as_ptr().cast()); llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage); llvm::LLVMSetGlobalConstant(llglobal, llvm::True); @@ -706,28 +730,26 @@ unsafe fn embed_bitcode(cgcx: &CodegenContext, "rustc.embedded.cmdline\0".as_ptr().cast(), ); llvm::LLVMSetInitializer(llglobal, llconst); - let section = if is_apple { - "__LLVM,__cmdline\0" - } else { - ".llvmcmd\0" - }; + let section = if is_apple { "__LLVM,__cmdline\0" } else { ".llvmcmd\0" }; llvm::LLVMSetSection(llglobal, section.as_ptr().cast()); llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage); } -pub unsafe fn with_llvm_pmb(llmod: &llvm::Module, - config: &ModuleConfig, - opt_level: llvm::CodeGenOptLevel, - prepare_for_thin_lto: bool, - f: &mut dyn FnMut(&llvm::PassManagerBuilder)) { +pub unsafe fn with_llvm_pmb( + llmod: &llvm::Module, + config: &ModuleConfig, + opt_level: llvm::CodeGenOptLevel, + prepare_for_thin_lto: bool, + f: &mut dyn FnMut(&llvm::PassManagerBuilder), +) { use std::ptr; // Create the PassManagerBuilder for LLVM. We configure it with // reasonable defaults and prepare it to actually populate the pass // manager. let builder = llvm::LLVMPassManagerBuilderCreate(); - let opt_size = config.opt_size.map(|x| to_llvm_opt_settings(x).1) - .unwrap_or(llvm::CodeGenOptSizeNone); + let opt_size = + config.opt_size.map(|x| to_llvm_opt_settings(x).1).unwrap_or(llvm::CodeGenOptSizeNone); let inline_threshold = config.inline_threshold; let pgo_gen_path = match config.pgo_gen { @@ -740,14 +762,13 @@ pub unsafe fn with_llvm_pmb(llmod: &llvm::Module, Some(CString::new(format!("{}", path.display())).unwrap()) } - SwitchWithOptPath::Disabled => { - None - } + SwitchWithOptPath::Disabled => None, }; - let pgo_use_path = config.pgo_use.as_ref().map(|path_buf| { - CString::new(path_buf.to_string_lossy().as_bytes()).unwrap() - }); + let pgo_use_path = config + .pgo_use + .as_ref() + .map(|path_buf| CString::new(path_buf.to_string_lossy().as_bytes()).unwrap()); llvm::LLVMRustConfigurePassManagerBuilder( builder, @@ -794,9 +815,7 @@ pub unsafe fn with_llvm_pmb(llmod: &llvm::Module, (llvm::CodeGenOptLevel::Default, ..) => { llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 225); } - (llvm::CodeGenOptLevel::Other, ..) => { - bug!("CodeGenOptLevel::Other selected") - } + (llvm::CodeGenOptLevel::Other, ..) => bug!("CodeGenOptLevel::Other selected"), } f(builder); @@ -811,36 +830,28 @@ pub unsafe fn with_llvm_pmb(llmod: &llvm::Module, fn create_msvc_imps( cgcx: &CodegenContext, llcx: &llvm::Context, - llmod: &llvm::Module + llmod: &llvm::Module, ) { if !cgcx.msvc_imps_needed { - return + return; } // The x86 ABI seems to require that leading underscores are added to symbol // names, so we need an extra underscore on x86. There's also a leading // '\x01' here which disables LLVM's symbol mangling (e.g., no extra // underscores added in front). - let prefix = if cgcx.target_arch == "x86" { - "\x01__imp__" - } else { - "\x01__imp_" - }; + let prefix = if cgcx.target_arch == "x86" { "\x01__imp__" } else { "\x01__imp_" }; unsafe { let i8p_ty = Type::i8p_llcx(llcx); let globals = base::iter_globals(llmod) .filter(|&val| { - llvm::LLVMRustGetLinkage(val) == llvm::Linkage::ExternalLinkage && - llvm::LLVMIsDeclaration(val) == 0 + llvm::LLVMRustGetLinkage(val) == llvm::Linkage::ExternalLinkage + && llvm::LLVMIsDeclaration(val) == 0 }) .filter_map(|val| { // Exclude some symbols that we know are not Rust symbols. let name = llvm::get_value_name(val); - if ignored(name) { - None - } else { - Some((val, name)) - } + if ignored(name) { None } else { Some((val, name)) } }) .map(move |(val, name)| { let mut imp_name = prefix.as_bytes().to_vec(); @@ -851,9 +862,7 @@ fn create_msvc_imps( .collect::>(); for (imp_name, val) in globals { - let imp = llvm::LLVMAddGlobal(llmod, - i8p_ty, - imp_name.as_ptr().cast()); + let imp = llvm::LLVMAddGlobal(llmod, i8p_ty, imp_name.as_ptr().cast()); llvm::LLVMSetInitializer(imp, consts::ptrcast(val, i8p_ty)); llvm::LLVMRustSetLinkage(imp, llvm::Linkage::ExternalLinkage); } diff --git a/src/librustc_codegen_llvm/consts.rs b/src/librustc_codegen_llvm/consts.rs index 78a86d33a145b..12c44513159ba 100644 --- a/src/librustc_codegen_llvm/consts.rs +++ b/src/librustc_codegen_llvm/consts.rs @@ -1,27 +1,26 @@ -use crate::llvm::{self, SetUnnamedAddr, True}; -use crate::debuginfo; -use crate::common::CodegenCx; use crate::base; +use crate::common::CodegenCx; +use crate::debuginfo; +use crate::llvm::{self, SetUnnamedAddr, True}; use crate::type_::Type; use crate::type_of::LayoutLlvmExt; use crate::value::Value; use libc::c_uint; +use log::debug; use rustc::hir::def_id::DefId; -use rustc::mir::interpret::{ConstValue, Allocation, read_target_uint, - Pointer, ErrorHandled}; -use rustc::mir::mono::MonoItem; use rustc::hir::Node; -use rustc_target::abi::HasDataLayout; -use rustc::ty::{self, Ty, Instance}; +use rustc::mir::interpret::{read_target_uint, Allocation, ConstValue, ErrorHandled, Pointer}; +use rustc::mir::mono::MonoItem; +use rustc::ty::{self, Instance, Ty}; +use rustc::{bug, span_bug}; use rustc_codegen_ssa::traits::*; -use syntax::symbol::{Symbol, sym}; +use rustc_target::abi::HasDataLayout; +use syntax::symbol::{sym, Symbol}; use syntax_pos::Span; -use rustc::{bug, span_bug}; -use log::debug; -use rustc::ty::layout::{self, Size, Align, LayoutOf}; +use rustc::ty::layout::{self, Align, LayoutOf, Size}; -use rustc::hir::{self, CodegenFnAttrs, CodegenFnAttrFlags}; +use rustc::hir::{self, CodegenFnAttrFlags, CodegenFnAttrs}; use std::ffi::CStr; @@ -51,14 +50,13 @@ pub fn const_alloc_to_llvm(cx: &CodegenCx<'ll, '_>, alloc: &Allocation) -> &'ll // affect interpreter execution (we inspect the result after interpreter execution), // and we properly interpret the relocation as a relocation pointer offset. alloc.inspect_with_undef_and_ptr_outside_interpreter(offset..(offset + pointer_size)), - ).expect("const_alloc_to_llvm: could not read relocation pointer") as u64; + ) + .expect("const_alloc_to_llvm: could not read relocation pointer") + as u64; llvals.push(cx.scalar_to_backend( Pointer::new(alloc_id, Size::from_bytes(ptr_offset)).into(), - &layout::Scalar { - value: layout::Primitive::Pointer, - valid_range: 0..=!0 - }, - cx.type_i8p() + &layout::Scalar { value: layout::Primitive::Pointer, valid_range: 0..=!0 }, + cx.type_i8p(), )); next_offset = offset + pointer_size; } @@ -84,19 +82,13 @@ pub fn codegen_static_initializer( let static_ = cx.tcx.const_eval_poly(def_id)?; let alloc = match static_.val { - ty::ConstKind::Value(ConstValue::ByRef { - alloc, offset, - }) if offset.bytes() == 0 => { - alloc - }, + ty::ConstKind::Value(ConstValue::ByRef { alloc, offset }) if offset.bytes() == 0 => alloc, _ => bug!("static const eval returned {:#?}", static_), }; Ok((const_alloc_to_llvm(cx, alloc), alloc)) } -fn set_global_alignment(cx: &CodegenCx<'ll, '_>, - gv: &'ll Value, - mut align: Align) { +fn set_global_alignment(cx: &CodegenCx<'ll, '_>, gv: &'ll Value, mut align: Align) { // The target may require greater alignment for globals than the type does. // Note: GCC and Clang also allow `__attribute__((aligned))` on variables, // which can force it to be smaller. Rust doesn't support this yet. @@ -118,7 +110,7 @@ fn check_and_apply_linkage( attrs: &CodegenFnAttrs, ty: Ty<'tcx>, sym: Symbol, - span: Span + span: Span, ) -> &'ll Value { let llty = cx.layout_of(ty).llvm_type(cx); let sym = sym.as_str(); @@ -134,7 +126,9 @@ fn check_and_apply_linkage( cx.layout_of(mt.ty).llvm_type(cx) } else { cx.sess().span_fatal( - span, "must have type `*const T` or `*mut T` due to `#[linkage]` attribute") + span, + "must have type `*const T` or `*mut T` due to `#[linkage]` attribute", + ) }; unsafe { // Declare a symbol `foo` with the desired linkage. @@ -149,7 +143,7 @@ fn check_and_apply_linkage( // zero. let mut real_name = "_rust_extern_with_linkage_".to_string(); real_name.push_str(&sym); - let g2 = cx.define_global(&real_name, llty).unwrap_or_else(||{ + let g2 = cx.define_global(&real_name, llty).unwrap_or_else(|| { cx.sess().span_fatal(span, &format!("symbol `{}` is already defined", &sym)) }); llvm::LLVMRustSetLinkage(g2, llvm::Linkage::InternalLinkage); @@ -164,16 +158,12 @@ fn check_and_apply_linkage( } pub fn ptrcast(val: &'ll Value, ty: &'ll Type) -> &'ll Value { - unsafe { - llvm::LLVMConstPointerCast(val, ty) - } + unsafe { llvm::LLVMConstPointerCast(val, ty) } } impl CodegenCx<'ll, 'tcx> { crate fn const_bitcast(&self, val: &'ll Value, ty: &'ll Type) -> &'ll Value { - unsafe { - llvm::LLVMConstBitCast(val, ty) - } + unsafe { llvm::LLVMConstBitCast(val, ty) } } crate fn static_addr_of_mut( @@ -186,13 +176,12 @@ impl CodegenCx<'ll, 'tcx> { let gv = match kind { Some(kind) if !self.tcx.sess.fewer_names() => { let name = self.generate_local_symbol_name(kind); - let gv = self.define_global(&name[..], - self.val_ty(cv)).unwrap_or_else(||{ - bug!("symbol `{}` is already defined", name); + let gv = self.define_global(&name[..], self.val_ty(cv)).unwrap_or_else(|| { + bug!("symbol `{}` is already defined", name); }); llvm::LLVMRustSetLinkage(gv, llvm::Linkage::PrivateLinkage); gv - }, + } _ => self.define_private_global(self.val_ty(cv)), }; llvm::LLVMSetInitializer(gv, cv); @@ -208,13 +197,14 @@ impl CodegenCx<'ll, 'tcx> { return g; } - let defined_in_current_codegen_unit = self.codegen_unit - .items() - .contains_key(&MonoItem::Static(def_id)); - assert!(!defined_in_current_codegen_unit, - "consts::get_static() should always hit the cache for \ + let defined_in_current_codegen_unit = + self.codegen_unit.items().contains_key(&MonoItem::Static(def_id)); + assert!( + !defined_in_current_codegen_unit, + "consts::get_static() should always hit the cache for \ statics defined in the same CGU, but did not for `{:?}`", - def_id); + def_id + ); let ty = instance.ty(self.tcx); let sym = self.tcx.symbol_name(instance).name; @@ -222,12 +212,9 @@ impl CodegenCx<'ll, 'tcx> { debug!("get_static: sym={} instance={:?}", sym, instance); let g = if let Some(id) = self.tcx.hir().as_local_hir_id(def_id) { - let llty = self.layout_of(ty).llvm_type(self); let (g, attrs) = match self.tcx.hir().get(id) { - Node::Item(&hir::Item { - attrs, span, kind: hir::ItemKind::Static(..), .. - }) => { + Node::Item(&hir::Item { attrs, span, kind: hir::ItemKind::Static(..), .. }) => { let sym_str = sym.as_str(); if let Some(g) = self.get_declared_value(&sym_str) { if self.val_ty(g) != self.type_ptr_to(llty) { @@ -247,13 +234,16 @@ impl CodegenCx<'ll, 'tcx> { } Node::ForeignItem(&hir::ForeignItem { - ref attrs, span, kind: hir::ForeignItemKind::Static(..), .. + ref attrs, + span, + kind: hir::ForeignItemKind::Static(..), + .. }) => { let fn_attrs = self.tcx.codegen_fn_attrs(def_id); (check_and_apply_linkage(&self, &fn_attrs, ty, sym, span), &**attrs) } - item => bug!("get_static: expected static, found {:?}", item) + item => bug!("get_static: expected static, found {:?}", item), }; debug!("get_static: sym={} attrs={:?}", sym, attrs); @@ -283,8 +273,7 @@ impl CodegenCx<'ll, 'tcx> { llvm::set_thread_local_mode(g, self.tls_model); } - let needs_dll_storage_attr = - self.use_dll_storage_attrs && !self.tcx.is_foreign_item(def_id) && + let needs_dll_storage_attr = self.use_dll_storage_attrs && !self.tcx.is_foreign_item(def_id) && // ThinLTO can't handle this workaround in all cases, so we don't // emit the attrs. Instead we make them unnecessary by disallowing // dynamic linking when linker plugin based LTO is enabled. @@ -292,9 +281,11 @@ impl CodegenCx<'ll, 'tcx> { // If this assertion triggers, there's something wrong with commandline // argument validation. - debug_assert!(!(self.tcx.sess.opts.cg.linker_plugin_lto.enabled() && - self.tcx.sess.target.target.options.is_like_msvc && - self.tcx.sess.opts.cg.prefer_dynamic)); + debug_assert!( + !(self.tcx.sess.opts.cg.linker_plugin_lto.enabled() + && self.tcx.sess.target.target.options.is_like_msvc + && self.tcx.sess.opts.cg.prefer_dynamic) + ); if needs_dll_storage_attr { // This item is external but not foreign, i.e., it originates from an external Rust @@ -329,12 +320,7 @@ impl CodegenCx<'ll, 'tcx> { } impl StaticMethods for CodegenCx<'ll, 'tcx> { - fn static_addr_of( - &self, - cv: &'ll Value, - align: Align, - kind: Option<&str>, - ) -> &'ll Value { + fn static_addr_of(&self, cv: &'ll Value, align: Align, kind: Option<&str>) -> &'ll Value { if let Some(&gv) = self.const_globals.borrow().get(&cv) { unsafe { // Upgrade the alignment in cases where the same constant is used with different @@ -354,11 +340,7 @@ impl StaticMethods for CodegenCx<'ll, 'tcx> { gv } - fn codegen_static( - &self, - def_id: DefId, - is_mutable: bool, - ) { + fn codegen_static(&self, def_id: DefId, is_mutable: bool) { unsafe { let attrs = self.tcx.codegen_fn_attrs(def_id); @@ -395,7 +377,11 @@ impl StaticMethods for CodegenCx<'ll, 'tcx> { let visibility = llvm::LLVMRustGetVisibility(g); let new_g = llvm::LLVMRustGetOrInsertGlobal( - self.llmod, name.as_ptr().cast(), name.len(), val_llty); + self.llmod, + name.as_ptr().cast(), + name.len(), + val_llty, + ); llvm::LLVMRustSetLinkage(new_g, linkage); llvm::LLVMRustSetVisibility(new_g, visibility); @@ -464,7 +450,8 @@ impl StaticMethods for CodegenCx<'ll, 'tcx> { // The `inspect` method is okay here because we checked relocations, and // because we are doing this access to inspect the final interpreter state // (not as part of the interpreter execution). - alloc.inspect_with_undef_and_ptr_outside_interpreter(0..alloc.len()) + alloc + .inspect_with_undef_and_ptr_outside_interpreter(0..alloc.len()) .iter() .all(|b| *b == 0) }; @@ -477,7 +464,6 @@ impl StaticMethods for CodegenCx<'ll, 'tcx> { } } - // Wasm statics with custom link sections get special treatment as they // go into custom sections of the wasm executable. if self.tcx.sess.opts.target_triple.triple().starts_with("wasm32") { @@ -492,8 +478,8 @@ impl StaticMethods for CodegenCx<'ll, 'tcx> { // The `inspect` method is okay here because we checked relocations, and // because we are doing this access to inspect the final interpreter state (not // as part of the interpreter execution). - let bytes = alloc.inspect_with_undef_and_ptr_outside_interpreter( - 0..alloc.len()); + let bytes = + alloc.inspect_with_undef_and_ptr_outside_interpreter(0..alloc.len()); let alloc = llvm::LLVMMDStringInContext( self.llcx, bytes.as_ptr().cast(), diff --git a/src/librustc_codegen_llvm/debuginfo/metadata.rs b/src/librustc_codegen_llvm/debuginfo/metadata.rs index 8327ff257c210..e3c2dfac58b3c 100644 --- a/src/librustc_codegen_llvm/debuginfo/metadata.rs +++ b/src/librustc_codegen_llvm/debuginfo/metadata.rs @@ -1,56 +1,60 @@ -use self::RecursiveTypeDescription::*; -use self::MemberDescriptionFactory::*; use self::EnumDiscriminantInfo::*; +use self::MemberDescriptionFactory::*; +use self::RecursiveTypeDescription::*; -use super::utils::{debug_context, DIB, span_start, - get_namespace_for_item, create_DIArray, is_node_local_to_unit}; use super::namespace::mangled_name_of_instance; use super::type_names::compute_debuginfo_type_name; +use super::utils::{ + create_DIArray, debug_context, get_namespace_for_item, is_node_local_to_unit, span_start, DIB, +}; use super::CrateDebugContext; use crate::abi; use crate::common::CodegenCx; use crate::llvm; -use crate::llvm::debuginfo::{DIArray, DIType, DIFile, DIScope, DIDescriptor, - DICompositeType, DILexicalBlock, DIFlags, DebugEmissionKind}; +use crate::llvm::debuginfo::{ + DIArray, DICompositeType, DIDescriptor, DIFile, DIFlags, DILexicalBlock, DIScope, DIType, + DebugEmissionKind, +}; use crate::llvm_util; use crate::value::Value; -use rustc_codegen_ssa::traits::*; -use rustc_index::vec::{Idx, IndexVec}; -use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; -use rustc::hir::CodegenFnAttrFlags; +use log::debug; use rustc::hir::def::CtorKind; -use rustc::hir::def_id::{DefId, CrateNum, LOCAL_CRATE}; +use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE}; +use rustc::hir::CodegenFnAttrFlags; use rustc::ich::NodeIdHashingMode; -use rustc::mir::{self, Field, GeneratorLayout}; use rustc::mir::interpret::truncate; -use rustc_data_structures::fingerprint::Fingerprint; +use rustc::mir::{self, Field, GeneratorLayout}; +use rustc::session::config::{self, DebugInfo}; +use rustc::ty::layout::{ + self, Align, Integer, IntegerExt, LayoutOf, PrimitiveExt, Size, TyLayout, VariantIdx, +}; +use rustc::ty::subst::{GenericArgKind, SubstsRef}; use rustc::ty::Instance; use rustc::ty::{self, AdtKind, ParamEnv, Ty, TyCtxt}; -use rustc::ty::layout::{self, Align, Integer, IntegerExt, LayoutOf, - PrimitiveExt, Size, TyLayout, VariantIdx}; -use rustc::ty::subst::{GenericArgKind, SubstsRef}; -use rustc::session::config::{self, DebugInfo}; use rustc::util::nodemap::FxHashMap; -use rustc_fs_util::path_to_c_string; -use rustc_data_structures::small_c_str::SmallCStr; +use rustc::{bug, span_bug}; +use rustc_codegen_ssa::traits::*; use rustc_data_structures::const_cstr; +use rustc_data_structures::fingerprint::Fingerprint; +use rustc_data_structures::small_c_str::SmallCStr; +use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; +use rustc_fs_util::path_to_c_string; +use rustc_index::vec::{Idx, IndexVec}; use rustc_target::abi::HasDataLayout; use syntax::ast; use syntax::symbol::{Interner, Symbol}; -use syntax_pos::{self, Span, FileName}; -use rustc::{bug, span_bug}; -use log::debug; +use syntax_pos::{self, FileName, Span}; -use libc::{c_uint, c_longlong}; +use libc::{c_longlong, c_uint}; use std::collections::hash_map::Entry; use std::ffi::CString; use std::fmt::{self, Write}; use std::hash::{Hash, Hasher}; use std::iter; -use std::ptr; use std::path::{Path, PathBuf}; +use std::ptr; impl PartialEq for llvm::Metadata { fn eq(&self, other: &Self) -> bool { @@ -107,17 +111,13 @@ pub struct TypeMap<'ll, 'tcx> { /// A map from types to debuginfo metadata. This is an N:1 mapping. type_to_metadata: FxHashMap, &'ll DIType>, /// A map from types to `UniqueTypeId`. This is an N:1 mapping. - type_to_unique_id: FxHashMap, UniqueTypeId> + type_to_unique_id: FxHashMap, UniqueTypeId>, } impl TypeMap<'ll, 'tcx> { /// Adds a Ty to metadata mapping to the TypeMap. The method will fail if /// the mapping already exists. - fn register_type_with_metadata( - &mut self, - type_: Ty<'tcx>, - metadata: &'ll DIType, - ) { + fn register_type_with_metadata(&mut self, type_: Ty<'tcx>, metadata: &'ll DIType) { if self.type_to_metadata.insert(type_, metadata).is_some() { bug!("type metadata for `Ty` '{}' is already in the `TypeMap`!", type_); } @@ -140,10 +140,7 @@ impl TypeMap<'ll, 'tcx> { /// /// This function is used to remove the temporary metadata /// mapping after we've computed the actual metadata. - fn remove_type( - &mut self, - type_: Ty<'tcx>, - ) { + fn remove_type(&mut self, type_: Ty<'tcx>) { if self.type_to_metadata.remove(type_).is_none() { bug!("type metadata `Ty` '{}' is not in the `TypeMap`!", type_); } @@ -157,8 +154,10 @@ impl TypeMap<'ll, 'tcx> { metadata: &'ll DIType, ) { if self.unique_id_to_metadata.insert(unique_type_id, metadata).is_some() { - bug!("type metadata for unique ID '{}' is already in the `TypeMap`!", - self.get_unique_type_id_as_string(unique_type_id)); + bug!( + "type metadata for unique ID '{}' is already in the `TypeMap`!", + self.get_unique_type_id_as_string(unique_type_id) + ); } } @@ -180,8 +179,11 @@ impl TypeMap<'ll, 'tcx> { /// Gets the `UniqueTypeId` for the given type. If the `UniqueTypeId` for the given /// type has been requested before, this is just a table lookup. Otherwise, an /// ID will be generated and stored for later lookup. - fn get_unique_type_id_of_type<'a>(&mut self, cx: &CodegenCx<'a, 'tcx>, - type_: Ty<'tcx>) -> UniqueTypeId { + fn get_unique_type_id_of_type<'a>( + &mut self, + cx: &CodegenCx<'a, 'tcx>, + type_: Ty<'tcx>, + ) -> UniqueTypeId { // Let's see if we already have something in the cache. if let Some(unique_type_id) = self.type_to_unique_id.get(&type_).cloned() { return unique_type_id; @@ -209,15 +211,15 @@ impl TypeMap<'ll, 'tcx> { /// Gets the `UniqueTypeId` for an enum variant. Enum variants are not really /// types of their own, so they need special handling. We still need a /// `UniqueTypeId` for them, since to debuginfo they *are* real types. - fn get_unique_type_id_of_enum_variant<'a>(&mut self, - cx: &CodegenCx<'a, 'tcx>, - enum_type: Ty<'tcx>, - variant_name: &str) - -> UniqueTypeId { + fn get_unique_type_id_of_enum_variant<'a>( + &mut self, + cx: &CodegenCx<'a, 'tcx>, + enum_type: Ty<'tcx>, + variant_name: &str, + ) -> UniqueTypeId { let enum_type_id = self.get_unique_type_id_of_type(cx, enum_type); - let enum_variant_type_id = format!("{}::{}", - self.get_unique_type_id_as_string(enum_type_id), - variant_name); + let enum_variant_type_id = + format!("{}::{}", self.get_unique_type_id_as_string(enum_type_id), variant_name); let interner_key = self.unique_id_interner.intern(&enum_variant_type_id); UniqueTypeId(interner_key) } @@ -226,8 +228,8 @@ impl TypeMap<'ll, 'tcx> { /// Variant parts are not types and shouldn't really have their own ID, /// but it makes `set_members_of_composite_type()` simpler. fn get_unique_type_id_str_of_enum_variant_part(&mut self, enum_type_id: UniqueTypeId) -> &str { - let variant_part_type_id = format!("{}_variant_part", - self.get_unique_type_id_as_string(enum_type_id)); + let variant_part_type_id = + format!("{}_variant_part", self.get_unique_type_id_as_string(enum_type_id)); let interner_key = self.unique_id_interner.intern(&variant_part_type_id); self.unique_id_interner.get(interner_key) } @@ -246,7 +248,7 @@ enum RecursiveTypeDescription<'ll, 'tcx> { member_holding_stub: &'ll DICompositeType, member_description_factory: MemberDescriptionFactory<'ll, 'tcx>, }, - FinalMetadata(&'ll DICompositeType) + FinalMetadata(&'ll DICompositeType), } fn create_and_register_recursive_type_forward_declaration( @@ -257,7 +259,6 @@ fn create_and_register_recursive_type_forward_declaration( member_holding_stub: &'ll DICompositeType, member_description_factory: MemberDescriptionFactory<'ll, 'tcx>, ) -> RecursiveTypeDescription<'ll, 'tcx> { - // Insert the stub into the `TypeMap` in order to allow for recursive references. let mut type_map = debug_context(cx).type_map.borrow_mut(); type_map.register_unique_id_with_metadata(unique_type_id, metadata_stub); @@ -294,23 +295,27 @@ impl RecursiveTypeDescription<'ll, 'tcx> { // function. { let type_map = debug_context(cx).type_map.borrow(); - if type_map.find_metadata_for_unique_id(unique_type_id).is_none() || - type_map.find_metadata_for_type(unfinished_type).is_none() { - bug!("Forward declaration of potentially recursive type \ + if type_map.find_metadata_for_unique_id(unique_type_id).is_none() + || type_map.find_metadata_for_type(unfinished_type).is_none() + { + bug!( + "Forward declaration of potentially recursive type \ '{:?}' was not found in TypeMap!", - unfinished_type); + unfinished_type + ); } } // ... then create the member descriptions ... - let member_descriptions = - member_description_factory.create_member_descriptions(cx); + let member_descriptions = member_description_factory.create_member_descriptions(cx); // ... and attach them to the stub to complete it. - set_members_of_composite_type(cx, - unfinished_type, - member_holding_stub, - member_descriptions); + set_members_of_composite_type( + cx, + unfinished_type, + member_holding_stub, + member_descriptions, + ); return MetadataCreationResult::new(metadata_stub, true); } } @@ -320,14 +325,13 @@ impl RecursiveTypeDescription<'ll, 'tcx> { /// Returns from the enclosing function if the type metadata with the given /// unique ID can be found in the type map. macro_rules! return_if_metadata_created_in_meantime { - ($cx: expr, $unique_type_id: expr) => ( - if let Some(metadata) = debug_context($cx).type_map - .borrow() - .find_metadata_for_unique_id($unique_type_id) + ($cx: expr, $unique_type_id: expr) => { + if let Some(metadata) = + debug_context($cx).type_map.borrow().find_metadata_for_unique_id($unique_type_id) { return MetadataCreationResult::new(metadata, true); } - ) + }; } fn fixed_vec_metadata( @@ -345,12 +349,11 @@ fn fixed_vec_metadata( let upper_bound = match array_or_slice_type.kind { ty::Array(_, len) => len.eval_usize(cx.tcx, ty::ParamEnv::reveal_all()) as c_longlong, - _ => -1 + _ => -1, }; - let subrange = unsafe { - Some(llvm::LLVMRustDIBuilderGetOrCreateSubrange(DIB(cx), 0, upper_bound)) - }; + let subrange = + unsafe { Some(llvm::LLVMRustDIBuilderGetOrCreateSubrange(DIB(cx), 0, upper_bound)) }; let subscripts = create_DIArray(DIB(cx), &[subrange]); let metadata = unsafe { @@ -359,7 +362,8 @@ fn fixed_vec_metadata( size.bits(), align.bits() as u32, element_type_metadata, - subscripts) + subscripts, + ) }; return MetadataCreationResult::new(metadata, false); @@ -406,14 +410,16 @@ fn vec_slice_metadata( let file_metadata = unknown_file_metadata(cx); - let metadata = composite_type_metadata(cx, - slice_ptr_type, - &slice_type_name[..], - unique_type_id, - member_descriptions, - NO_SCOPE_METADATA, - file_metadata, - span); + let metadata = composite_type_metadata( + cx, + slice_ptr_type, + &slice_type_name[..], + unique_type_id, + member_descriptions, + NO_SCOPE_METADATA, + file_metadata, + span, + ); MetadataCreationResult::new(metadata, false) } @@ -423,23 +429,21 @@ fn subroutine_type_metadata( signature: ty::PolyFnSig<'tcx>, span: Span, ) -> MetadataCreationResult<'ll> { - let signature = cx.tcx.normalize_erasing_late_bound_regions( - ty::ParamEnv::reveal_all(), - &signature, - ); + let signature = + cx.tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &signature); let signature_metadata: Vec<_> = iter::once( // return type match signature.output().kind { ty::Tuple(ref tys) if tys.is_empty() => None, - _ => Some(type_metadata(cx, signature.output(), span)) - } - ).chain( + _ => Some(type_metadata(cx, signature.output(), span)), + }, + ) + .chain( // regular arguments - signature.inputs().iter().map(|argument_type| { - Some(type_metadata(cx, argument_type, span)) - }) - ).collect(); + signature.inputs().iter().map(|argument_type| Some(type_metadata(cx, argument_type, span))), + ) + .collect(); return_if_metadata_created_in_meantime!(cx, unique_type_id); @@ -448,9 +452,11 @@ fn subroutine_type_metadata( llvm::LLVMRustDIBuilderCreateSubroutineType( DIB(cx), unknown_file_metadata(cx), - create_DIArray(DIB(cx), &signature_metadata[..])) + create_DIArray(DIB(cx), &signature_metadata[..]), + ) }, - false); + false, + ); } // FIXME(1563): This is all a bit of a hack because 'trait pointer' is an ill- @@ -470,18 +476,20 @@ fn trait_pointer_metadata( // However, it does not describe the trait's methods. let containing_scope = match trait_type.kind { - ty::Dynamic(ref data, ..) => - data.principal_def_id().map(|did| get_namespace_for_item(cx, did)), + ty::Dynamic(ref data, ..) => { + data.principal_def_id().map(|did| get_namespace_for_item(cx, did)) + } _ => { - bug!("debuginfo: unexpected trait-object type in \ + bug!( + "debuginfo: unexpected trait-object type in \ trait_pointer_metadata(): {:?}", - trait_type); + trait_type + ); } }; let trait_object_type = trait_object_type.unwrap_or(trait_type); - let trait_type_name = - compute_debuginfo_type_name(cx.tcx, trait_object_type, false); + let trait_type_name = compute_debuginfo_type_name(cx.tcx, trait_object_type, false); let file_metadata = unknown_file_metadata(cx); @@ -495,9 +503,11 @@ fn trait_pointer_metadata( let member_descriptions = vec![ MemberDescription { name: "pointer".to_owned(), - type_metadata: type_metadata(cx, + type_metadata: type_metadata( + cx, cx.tcx.mk_mut_ptr(cx.tcx.types.u8), - syntax_pos::DUMMY_SP), + syntax_pos::DUMMY_SP, + ), offset: layout.fields.offset(0), size: data_ptr_field.size, align: data_ptr_field.align.abi, @@ -515,21 +525,19 @@ fn trait_pointer_metadata( }, ]; - composite_type_metadata(cx, - trait_object_type, - &trait_type_name[..], - unique_type_id, - member_descriptions, - containing_scope, - file_metadata, - syntax_pos::DUMMY_SP) + composite_type_metadata( + cx, + trait_object_type, + &trait_type_name[..], + unique_type_id, + member_descriptions, + containing_scope, + file_metadata, + syntax_pos::DUMMY_SP, + ) } -pub fn type_metadata( - cx: &CodegenCx<'ll, 'tcx>, - t: Ty<'tcx>, - usage_site_span: Span, -) -> &'ll DIType { +pub fn type_metadata(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>, usage_site_span: Span) -> &'ll DIType { // Get the unique type ID of this type. let unique_type_id = { let mut type_map = debug_context(cx).type_map.borrow_mut(); @@ -538,7 +546,7 @@ pub fn type_metadata( match type_map.find_metadata_for_type(t) { Some(metadata) => { return metadata; - }, + } None => { // The Ty is not in the `TypeMap` but maybe we have already seen // an equivalent type (e.g., only differing in region arguments). @@ -552,7 +560,7 @@ pub fn type_metadata( // return the cached metadata. type_map.register_type_with_metadata(t, metadata); return metadata; - }, + } None => { // There really is no type metadata for this type, so // proceed by creating it. @@ -565,82 +573,54 @@ pub fn type_metadata( debug!("type_metadata: {:?}", t); - let ptr_metadata = |ty: Ty<'tcx>| { - match ty.kind { - ty::Slice(typ) => { - Ok(vec_slice_metadata(cx, t, typ, unique_type_id, usage_site_span)) - } - ty::Str => { - Ok(vec_slice_metadata(cx, t, cx.tcx.types.u8, unique_type_id, usage_site_span)) - } - ty::Dynamic(..) => { - Ok(MetadataCreationResult::new( - trait_pointer_metadata(cx, ty, Some(t), unique_type_id), - false)) - } - _ => { - let pointee_metadata = type_metadata(cx, ty, usage_site_span); - - if let Some(metadata) = debug_context(cx).type_map - .borrow() - .find_metadata_for_unique_id(unique_type_id) - { - return Err(metadata); - } + let ptr_metadata = |ty: Ty<'tcx>| match ty.kind { + ty::Slice(typ) => Ok(vec_slice_metadata(cx, t, typ, unique_type_id, usage_site_span)), + ty::Str => Ok(vec_slice_metadata(cx, t, cx.tcx.types.u8, unique_type_id, usage_site_span)), + ty::Dynamic(..) => Ok(MetadataCreationResult::new( + trait_pointer_metadata(cx, ty, Some(t), unique_type_id), + false, + )), + _ => { + let pointee_metadata = type_metadata(cx, ty, usage_site_span); - Ok(MetadataCreationResult::new(pointer_type_metadata(cx, t, pointee_metadata), - false)) + if let Some(metadata) = + debug_context(cx).type_map.borrow().find_metadata_for_unique_id(unique_type_id) + { + return Err(metadata); } + + Ok(MetadataCreationResult::new(pointer_type_metadata(cx, t, pointee_metadata), false)) } }; let MetadataCreationResult { metadata, already_stored_in_typemap } = match t.kind { - ty::Never | - ty::Bool | - ty::Char | - ty::Int(_) | - ty::Uint(_) | - ty::Float(_) => { + ty::Never | ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) => { MetadataCreationResult::new(basic_type_metadata(cx, t), false) } ty::Tuple(ref elements) if elements.is_empty() => { MetadataCreationResult::new(basic_type_metadata(cx, t), false) } - ty::Array(typ, _) | - ty::Slice(typ) => { + ty::Array(typ, _) | ty::Slice(typ) => { fixed_vec_metadata(cx, unique_type_id, t, typ, usage_site_span) } - ty::Str => { - fixed_vec_metadata(cx, unique_type_id, t, cx.tcx.types.i8, usage_site_span) - } + ty::Str => fixed_vec_metadata(cx, unique_type_id, t, cx.tcx.types.i8, usage_site_span), ty::Dynamic(..) => { - MetadataCreationResult::new( - trait_pointer_metadata(cx, t, None, unique_type_id), - false) + MetadataCreationResult::new(trait_pointer_metadata(cx, t, None, unique_type_id), false) } ty::Foreign(..) => { - MetadataCreationResult::new( - foreign_type_metadata(cx, t, unique_type_id), - false) - } - ty::RawPtr(ty::TypeAndMut{ty, ..}) | - ty::Ref(_, ty, _) => { - match ptr_metadata(ty) { - Ok(res) => res, - Err(metadata) => return metadata, - } - } - ty::Adt(def, _) if def.is_box() => { - match ptr_metadata(t.boxed_ty()) { - Ok(res) => res, - Err(metadata) => return metadata, - } + MetadataCreationResult::new(foreign_type_metadata(cx, t, unique_type_id), false) } + ty::RawPtr(ty::TypeAndMut { ty, .. }) | ty::Ref(_, ty, _) => match ptr_metadata(ty) { + Ok(res) => res, + Err(metadata) => return metadata, + }, + ty::Adt(def, _) if def.is_box() => match ptr_metadata(t.boxed_ty()) { + Ok(res) => res, + Err(metadata) => return metadata, + }, ty::FnDef(..) | ty::FnPtr(_) => { - - if let Some(metadata) = debug_context(cx).type_map - .borrow() - .find_metadata_for_unique_id(unique_type_id) + if let Some(metadata) = + debug_context(cx).type_map.borrow().find_metadata_for_unique_id(unique_type_id) { return metadata; } @@ -665,81 +645,63 @@ pub fn type_metadata( SmallCStr::new("").as_ptr(), size.bits(), align.bits() as u32, - DW_ATE_unsigned) + DW_ATE_unsigned, + ) } }; let type_map = &debug_context(cx).type_map; type_map.borrow_mut().register_type_with_metadata(t, temp_type); - let fn_metadata = subroutine_type_metadata(cx, - unique_type_id, - t.fn_sig(cx.tcx), - usage_site_span).metadata; + let fn_metadata = + subroutine_type_metadata(cx, unique_type_id, t.fn_sig(cx.tcx), usage_site_span) + .metadata; type_map.borrow_mut().remove_type(t); - // This is actually a function pointer, so wrap it in pointer DI. MetadataCreationResult::new(pointer_type_metadata(cx, t, fn_metadata), false) - } ty::Closure(def_id, substs) => { - let upvar_tys : Vec<_> = substs.as_closure().upvar_tys(def_id, cx.tcx).collect(); + let upvar_tys: Vec<_> = substs.as_closure().upvar_tys(def_id, cx.tcx).collect(); let containing_scope = get_namespace_for_item(cx, def_id); - prepare_tuple_metadata(cx, - t, - &upvar_tys, - unique_type_id, - usage_site_span, - Some(containing_scope)).finalize(cx) + prepare_tuple_metadata( + cx, + t, + &upvar_tys, + unique_type_id, + usage_site_span, + Some(containing_scope), + ) + .finalize(cx) } - ty::Generator(def_id, substs, _) => { - let upvar_tys : Vec<_> = substs - .as_generator().prefix_tys(def_id, cx.tcx).map(|t| { - cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), t) - }).collect(); - prepare_enum_metadata(cx, - t, - def_id, - unique_type_id, - usage_site_span, - upvar_tys).finalize(cx) + ty::Generator(def_id, substs, _) => { + let upvar_tys: Vec<_> = substs + .as_generator() + .prefix_tys(def_id, cx.tcx) + .map(|t| cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), t)) + .collect(); + prepare_enum_metadata(cx, t, def_id, unique_type_id, usage_site_span, upvar_tys) + .finalize(cx) } ty::Adt(def, ..) => match def.adt_kind() { AdtKind::Struct => { - prepare_struct_metadata(cx, - t, - unique_type_id, - usage_site_span).finalize(cx) + prepare_struct_metadata(cx, t, unique_type_id, usage_site_span).finalize(cx) } AdtKind::Union => { - prepare_union_metadata(cx, - t, - unique_type_id, - usage_site_span).finalize(cx) + prepare_union_metadata(cx, t, unique_type_id, usage_site_span).finalize(cx) } AdtKind::Enum => { - prepare_enum_metadata(cx, - t, - def.did, - unique_type_id, - usage_site_span, - vec![]).finalize(cx) + prepare_enum_metadata(cx, t, def.did, unique_type_id, usage_site_span, vec![]) + .finalize(cx) } }, ty::Tuple(ref elements) => { let tys: Vec<_> = elements.iter().map(|k| k.expect_ty()).collect(); - prepare_tuple_metadata(cx, - t, - &tys, - unique_type_id, - usage_site_span, - NO_SCOPE_METADATA).finalize(cx) - } - _ => { - bug!("debuginfo: unexpected type in type_metadata: {:?}", t) + prepare_tuple_metadata(cx, t, &tys, unique_type_id, usage_site_span, NO_SCOPE_METADATA) + .finalize(cx) } + _ => bug!("debuginfo: unexpected type in type_metadata: {:?}", t), }; { @@ -750,26 +712,30 @@ pub fn type_metadata( let metadata_for_uid = match type_map.find_metadata_for_unique_id(unique_type_id) { Some(metadata) => metadata, None => { - span_bug!(usage_site_span, - "expected type metadata for unique \ + span_bug!( + usage_site_span, + "expected type metadata for unique \ type ID '{}' to already be in \ the `debuginfo::TypeMap` but it \ was not. (Ty = {})", - type_map.get_unique_type_id_as_string(unique_type_id), - t); + type_map.get_unique_type_id_as_string(unique_type_id), + t + ); } }; match type_map.find_metadata_for_type(t) { Some(metadata) => { if metadata != metadata_for_uid { - span_bug!(usage_site_span, - "mismatch between `Ty` and \ + span_bug!( + usage_site_span, + "mismatch between `Ty` and \ `UniqueTypeId` maps in \ `debuginfo::TypeMap`. \ UniqueTypeId={}, Ty={}", - type_map.get_unique_type_id_as_string(unique_type_id), - t); + type_map.get_unique_type_id_as_string(unique_type_id), + t + ); } } None => { @@ -785,12 +751,12 @@ pub fn type_metadata( metadata } -pub fn file_metadata(cx: &CodegenCx<'ll, '_>, - file_name: &FileName, - defining_crate: CrateNum) -> &'ll DIFile { - debug!("file_metadata: file_name: {}, defining_crate: {}", - file_name, - defining_crate); +pub fn file_metadata( + cx: &CodegenCx<'ll, '_>, + file_name: &FileName, + defining_crate: CrateNum, +) -> &'ll DIFile { + debug!("file_metadata: file_name: {}, defining_crate: {}", file_name, defining_crate); let file_name = Some(file_name.to_string()); let directory = if defining_crate == LOCAL_CRATE { @@ -807,10 +773,11 @@ pub fn unknown_file_metadata(cx: &CodegenCx<'ll, '_>) -> &'ll DIFile { file_metadata_raw(cx, None, None) } -fn file_metadata_raw(cx: &CodegenCx<'ll, '_>, - file_name: Option, - directory: Option) - -> &'ll DIFile { +fn file_metadata_raw( + cx: &CodegenCx<'ll, '_>, + file_name: Option, + directory: Option, +) -> &'ll DIFile { let key = (file_name, directory); match debug_context(cx).created_files.borrow_mut().entry(key) { @@ -819,15 +786,16 @@ fn file_metadata_raw(cx: &CodegenCx<'ll, '_>, let (file_name, directory) = v.key(); debug!("file_metadata: file_name: {:?}, directory: {:?}", file_name, directory); - let file_name = SmallCStr::new( - if let Some(file_name) = file_name { &file_name } else { "" }); - let directory = SmallCStr::new( - if let Some(directory) = directory { &directory } else { "" }); + let file_name = SmallCStr::new(if let Some(file_name) = file_name { + &file_name + } else { + "" + }); + let directory = + SmallCStr::new(if let Some(directory) = directory { &directory } else { "" }); let file_metadata = unsafe { - llvm::LLVMRustDIBuilderCreateFile(DIB(cx), - file_name.as_ptr(), - directory.as_ptr()) + llvm::LLVMRustDIBuilderCreateFile(DIB(cx), file_name.as_ptr(), directory.as_ptr()) }; v.insert(file_metadata); @@ -841,20 +809,13 @@ fn basic_type_metadata(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>) -> &'ll DIType { let (name, encoding) = match t.kind { ty::Never => ("!", DW_ATE_unsigned), - ty::Tuple(ref elements) if elements.is_empty() => - ("()", DW_ATE_unsigned), + ty::Tuple(ref elements) if elements.is_empty() => ("()", DW_ATE_unsigned), ty::Bool => ("bool", DW_ATE_boolean), ty::Char => ("char", DW_ATE_unsigned_char), - ty::Int(int_ty) => { - (int_ty.name_str(), DW_ATE_signed) - }, - ty::Uint(uint_ty) => { - (uint_ty.name_str(), DW_ATE_unsigned) - }, - ty::Float(float_ty) => { - (float_ty.name_str(), DW_ATE_float) - }, - _ => bug!("debuginfo::basic_type_metadata - `t` is invalid type") + ty::Int(int_ty) => (int_ty.name_str(), DW_ATE_signed), + ty::Uint(uint_ty) => (uint_ty.name_str(), DW_ATE_unsigned), + ty::Float(float_ty) => (float_ty.name_str(), DW_ATE_float), + _ => bug!("debuginfo::basic_type_metadata - `t` is invalid type"), }; let (size, align) = cx.size_and_align_of(t); @@ -865,7 +826,8 @@ fn basic_type_metadata(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>) -> &'ll DIType { name.as_ptr(), size.bits(), align.bits() as u32, - encoding) + encoding, + ) }; return ty_metadata; @@ -896,7 +858,8 @@ fn pointer_type_metadata( pointee_type_metadata, pointer_size.bits(), pointer_align.bits() as u32, - name.as_ptr()) + name.as_ptr(), + ) } } @@ -920,10 +883,8 @@ pub fn compile_unit_metadata( } debug!("compile_unit_metadata: {:?}", name_in_debuginfo); - let rustc_producer = format!( - "rustc version {}", - option_env!("CFG_VERSION").expect("CFG_VERSION"), - ); + let rustc_producer = + format!("rustc version {}", option_env!("CFG_VERSION").expect("CFG_VERSION"),); // FIXME(#41252) Remove "clang LLVM" if we can get GDB and LLVM to play nice. let producer = format!("clang LLVM ({})", rustc_producer); @@ -954,7 +915,10 @@ pub fn compile_unit_metadata( unsafe { let file_metadata = llvm::LLVMRustDIBuilderCreateFile( - debug_context.builder, name_in_debuginfo.as_ptr(), work_dir.as_ptr()); + debug_context.builder, + name_in_debuginfo.as_ptr(), + work_dir.as_ptr(), + ); let unit_metadata = llvm::LLVMRustDIBuilderCreateCompileUnit( debug_context.builder, @@ -965,27 +929,36 @@ pub fn compile_unit_metadata( flags.as_ptr().cast(), 0, split_name.as_ptr().cast(), - kind); + kind, + ); if tcx.sess.opts.debugging_opts.profile { - let cu_desc_metadata = llvm::LLVMRustMetadataAsValue(debug_context.llcontext, - unit_metadata); + let cu_desc_metadata = + llvm::LLVMRustMetadataAsValue(debug_context.llcontext, unit_metadata); let gcov_cu_info = [ - path_to_mdstring(debug_context.llcontext, - &tcx.output_filenames(LOCAL_CRATE).with_extension("gcno")), - path_to_mdstring(debug_context.llcontext, - &tcx.output_filenames(LOCAL_CRATE).with_extension("gcda")), + path_to_mdstring( + debug_context.llcontext, + &tcx.output_filenames(LOCAL_CRATE).with_extension("gcno"), + ), + path_to_mdstring( + debug_context.llcontext, + &tcx.output_filenames(LOCAL_CRATE).with_extension("gcda"), + ), cu_desc_metadata, ]; - let gcov_metadata = llvm::LLVMMDNodeInContext(debug_context.llcontext, - gcov_cu_info.as_ptr(), - gcov_cu_info.len() as c_uint); + let gcov_metadata = llvm::LLVMMDNodeInContext( + debug_context.llcontext, + gcov_cu_info.as_ptr(), + gcov_cu_info.len() as c_uint, + ); let llvm_gcov_ident = const_cstr!("llvm.gcov"); - llvm::LLVMAddNamedMetadataOperand(debug_context.llmod, - llvm_gcov_ident.as_ptr(), - gcov_metadata); + llvm::LLVMAddNamedMetadataOperand( + debug_context.llmod, + llvm_gcov_ident.as_ptr(), + gcov_metadata, + ); } // Insert `llvm.ident` metadata on the wasm32 targets since that will @@ -1009,24 +982,23 @@ pub fn compile_unit_metadata( fn path_to_mdstring(llcx: &'ll llvm::Context, path: &Path) -> &'ll Value { let path_str = path_to_c_string(path); unsafe { - llvm::LLVMMDStringInContext(llcx, - path_str.as_ptr(), - path_str.as_bytes().len() as c_uint) + llvm::LLVMMDStringInContext( + llcx, + path_str.as_ptr(), + path_str.as_bytes().len() as c_uint, + ) } } } struct MetadataCreationResult<'ll> { metadata: &'ll DIType, - already_stored_in_typemap: bool + already_stored_in_typemap: bool, } impl MetadataCreationResult<'ll> { fn new(metadata: &'ll DIType, already_stored_in_typemap: bool) -> Self { - MetadataCreationResult { - metadata, - already_stored_in_typemap, - } + MetadataCreationResult { metadata, already_stored_in_typemap } } } @@ -1044,9 +1016,11 @@ struct MemberDescription<'ll> { } impl<'ll> MemberDescription<'ll> { - fn into_metadata(self, - cx: &CodegenCx<'ll, '_>, - composite_type_metadata: &'ll DIScope) -> &'ll DIType { + fn into_metadata( + self, + cx: &CodegenCx<'ll, '_>, + composite_type_metadata: &'ll DIScope, + ) -> &'ll DIType { let member_name = CString::new(self.name).unwrap(); unsafe { llvm::LLVMRustDIBuilderCreateVariantMemberType( @@ -1063,7 +1037,8 @@ impl<'ll> MemberDescription<'ll> { Some(value) => Some(cx.const_u64(value)), }, self.flags, - self.type_metadata) + self.type_metadata, + ) } } } @@ -1077,28 +1052,17 @@ enum MemberDescriptionFactory<'ll, 'tcx> { TupleMDF(TupleMemberDescriptionFactory<'tcx>), EnumMDF(EnumMemberDescriptionFactory<'ll, 'tcx>), UnionMDF(UnionMemberDescriptionFactory<'tcx>), - VariantMDF(VariantMemberDescriptionFactory<'ll, 'tcx>) + VariantMDF(VariantMemberDescriptionFactory<'ll, 'tcx>), } impl MemberDescriptionFactory<'ll, 'tcx> { - fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>) - -> Vec> { + fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>) -> Vec> { match *self { - StructMDF(ref this) => { - this.create_member_descriptions(cx) - } - TupleMDF(ref this) => { - this.create_member_descriptions(cx) - } - EnumMDF(ref this) => { - this.create_member_descriptions(cx) - } - UnionMDF(ref this) => { - this.create_member_descriptions(cx) - } - VariantMDF(ref this) => { - this.create_member_descriptions(cx) - } + StructMDF(ref this) => this.create_member_descriptions(cx), + TupleMDF(ref this) => this.create_member_descriptions(cx), + EnumMDF(ref this) => this.create_member_descriptions(cx), + UnionMDF(ref this) => this.create_member_descriptions(cx), + VariantMDF(ref this) => this.create_member_descriptions(cx), } } } @@ -1115,30 +1079,33 @@ struct StructMemberDescriptionFactory<'tcx> { } impl<'tcx> StructMemberDescriptionFactory<'tcx> { - fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>) - -> Vec> { + fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>) -> Vec> { let layout = cx.layout_of(self.ty); - self.variant.fields.iter().enumerate().map(|(i, f)| { - let name = if self.variant.ctor_kind == CtorKind::Fn { - format!("__{}", i) - } else { - f.ident.to_string() - }; - let field = layout.field(cx, i); - MemberDescription { - name, - type_metadata: type_metadata(cx, field.ty, self.span), - offset: layout.fields.offset(i), - size: field.size, - align: field.align.abi, - flags: DIFlags::FlagZero, - discriminant: None, - } - }).collect() + self.variant + .fields + .iter() + .enumerate() + .map(|(i, f)| { + let name = if self.variant.ctor_kind == CtorKind::Fn { + format!("__{}", i) + } else { + f.ident.to_string() + }; + let field = layout.field(cx, i); + MemberDescription { + name, + type_metadata: type_metadata(cx, field.ty, self.span), + offset: layout.fields.offset(i), + size: field.size, + align: field.align.abi, + flags: DIFlags::FlagZero, + discriminant: None, + } + }) + .collect() } } - fn prepare_struct_metadata( cx: &CodegenCx<'ll, 'tcx>, struct_type: Ty<'tcx>, @@ -1149,16 +1116,13 @@ fn prepare_struct_metadata( let (struct_def_id, variant) = match struct_type.kind { ty::Adt(def, _) => (def.did, def.non_enum_variant()), - _ => bug!("prepare_struct_metadata on a non-ADT") + _ => bug!("prepare_struct_metadata on a non-ADT"), }; let containing_scope = get_namespace_for_item(cx, struct_def_id); - let struct_metadata_stub = create_struct_stub(cx, - struct_type, - &struct_name, - unique_type_id, - Some(containing_scope)); + let struct_metadata_stub = + create_struct_stub(cx, struct_type, &struct_name, unique_type_id, Some(containing_scope)); create_and_register_recursive_type_forward_declaration( cx, @@ -1166,11 +1130,7 @@ fn prepare_struct_metadata( unique_type_id, struct_metadata_stub, struct_metadata_stub, - StructMDF(StructMemberDescriptionFactory { - ty: struct_type, - variant, - span, - }) + StructMDF(StructMemberDescriptionFactory { ty: struct_type, variant, span }), ) } @@ -1186,21 +1146,24 @@ struct TupleMemberDescriptionFactory<'tcx> { } impl<'tcx> TupleMemberDescriptionFactory<'tcx> { - fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>) - -> Vec> { + fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>) -> Vec> { let layout = cx.layout_of(self.ty); - self.component_types.iter().enumerate().map(|(i, &component_type)| { - let (size, align) = cx.size_and_align_of(component_type); - MemberDescription { - name: format!("__{}", i), - type_metadata: type_metadata(cx, component_type, self.span), - offset: layout.fields.offset(i), - size, - align, - flags: DIFlags::FlagZero, - discriminant: None, - } - }).collect() + self.component_types + .iter() + .enumerate() + .map(|(i, &component_type)| { + let (size, align) = cx.size_and_align_of(component_type); + MemberDescription { + name: format!("__{}", i), + type_metadata: type_metadata(cx, component_type, self.span), + offset: layout.fields.offset(i), + size, + align, + flags: DIFlags::FlagZero, + discriminant: None, + } + }) + .collect() } } @@ -1214,11 +1177,8 @@ fn prepare_tuple_metadata( ) -> RecursiveTypeDescription<'ll, 'tcx> { let tuple_name = compute_debuginfo_type_name(cx.tcx, tuple_type, false); - let struct_stub = create_struct_stub(cx, - tuple_type, - &tuple_name[..], - unique_type_id, - containing_scope); + let struct_stub = + create_struct_stub(cx, tuple_type, &tuple_name[..], unique_type_id, containing_scope); create_and_register_recursive_type_forward_declaration( cx, @@ -1230,7 +1190,7 @@ fn prepare_tuple_metadata( ty: tuple_type, component_types: component_types.to_vec(), span, - }) + }), ) } @@ -1245,20 +1205,24 @@ struct UnionMemberDescriptionFactory<'tcx> { } impl<'tcx> UnionMemberDescriptionFactory<'tcx> { - fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>) - -> Vec> { - self.variant.fields.iter().enumerate().map(|(i, f)| { - let field = self.layout.field(cx, i); - MemberDescription { - name: f.ident.to_string(), - type_metadata: type_metadata(cx, field.ty, self.span), - offset: Size::ZERO, - size: field.size, - align: field.align.abi, - flags: DIFlags::FlagZero, - discriminant: None, - } - }).collect() + fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>) -> Vec> { + self.variant + .fields + .iter() + .enumerate() + .map(|(i, f)| { + let field = self.layout.field(cx, i); + MemberDescription { + name: f.ident.to_string(), + type_metadata: type_metadata(cx, field.ty, self.span), + offset: Size::ZERO, + size: field.size, + align: field.align.abi, + flags: DIFlags::FlagZero, + discriminant: None, + } + }) + .collect() } } @@ -1272,16 +1236,13 @@ fn prepare_union_metadata( let (union_def_id, variant) = match union_type.kind { ty::Adt(def, _) => (def.did, def.non_enum_variant()), - _ => bug!("prepare_union_metadata on a non-ADT") + _ => bug!("prepare_union_metadata on a non-ADT"), }; let containing_scope = get_namespace_for_item(cx, union_def_id); - let union_metadata_stub = create_union_stub(cx, - union_type, - &union_name, - unique_type_id, - containing_scope); + let union_metadata_stub = + create_union_stub(cx, union_type, &union_name, unique_type_id, containing_scope); create_and_register_recursive_type_forward_declaration( cx, @@ -1289,11 +1250,7 @@ fn prepare_union_metadata( unique_type_id, union_metadata_stub, union_metadata_stub, - UnionMDF(UnionMemberDescriptionFactory { - layout: cx.layout_of(union_type), - variant, - span, - }) + UnionMDF(UnionMemberDescriptionFactory { layout: cx.layout_of(union_type), variant, span }), ) } @@ -1327,8 +1284,7 @@ fn generator_layout_and_saved_local_names( ) -> (&'tcx GeneratorLayout<'tcx>, IndexVec>) { let body = tcx.optimized_mir(def_id); let generator_layout = body.generator_layout.as_ref().unwrap(); - let mut generator_saved_local_names = - IndexVec::from_elem(None, &generator_layout.field_tys); + let mut generator_saved_local_names = IndexVec::from_elem(None, &generator_layout.field_tys); let state_arg = mir::PlaceBase::Local(mir::Local::new(1)); for var in &body.var_debug_info { @@ -1372,8 +1328,7 @@ struct EnumMemberDescriptionFactory<'ll, 'tcx> { } impl EnumMemberDescriptionFactory<'ll, 'tcx> { - fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>) - -> Vec> { + fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>) -> Vec> { let generator_variant_info_data = match self.enum_type.kind { ty::Generator(def_id, ..) => { Some(generator_layout_and_saved_local_names(cx.tcx, def_id)) @@ -1381,21 +1336,19 @@ impl EnumMemberDescriptionFactory<'ll, 'tcx> { _ => None, }; - let variant_info_for = |index: VariantIdx| { - match self.enum_type.kind { - ty::Adt(adt, _) => VariantInfo::Adt(&adt.variants[index]), - ty::Generator(_, substs, _) => { - let (generator_layout, generator_saved_local_names) = - generator_variant_info_data.as_ref().unwrap(); - VariantInfo::Generator { - substs, - generator_layout: *generator_layout, - generator_saved_local_names, - variant_index: index, - } + let variant_info_for = |index: VariantIdx| match self.enum_type.kind { + ty::Adt(adt, _) => VariantInfo::Adt(&adt.variants[index]), + ty::Generator(_, substs, _) => { + let (generator_layout, generator_saved_local_names) = + generator_variant_info_data.as_ref().unwrap(); + VariantInfo::Generator { + substs, + generator_layout: *generator_layout, + generator_saved_local_names, + variant_index: index, } - _ => bug!(), } + _ => bug!(), }; // This will always find the metadata in the type map. @@ -1415,36 +1368,32 @@ impl EnumMemberDescriptionFactory<'ll, 'tcx> { } let variant_info = variant_info_for(index); - let (variant_type_metadata, member_description_factory) = - describe_enum_variant(cx, - self.layout, - variant_info, - NoDiscriminant, - self_metadata, - self.span); - - let member_descriptions = - member_description_factory.create_member_descriptions(cx); - - set_members_of_composite_type(cx, - self.enum_type, - variant_type_metadata, - member_descriptions); - vec![ - MemberDescription { - name: if fallback { - String::new() - } else { - variant_info.variant_name() - }, - type_metadata: variant_type_metadata, - offset: Size::ZERO, - size: self.layout.size, - align: self.layout.align.abi, - flags: DIFlags::FlagZero, - discriminant: None, - } - ] + let (variant_type_metadata, member_description_factory) = describe_enum_variant( + cx, + self.layout, + variant_info, + NoDiscriminant, + self_metadata, + self.span, + ); + + let member_descriptions = member_description_factory.create_member_descriptions(cx); + + set_members_of_composite_type( + cx, + self.enum_type, + variant_type_metadata, + member_descriptions, + ); + vec![MemberDescription { + name: if fallback { String::new() } else { variant_info.variant_name() }, + type_metadata: variant_type_metadata, + offset: Size::ZERO, + size: self.layout.size, + align: self.layout.align.abi, + flags: DIFlags::FlagZero, + discriminant: None, + }] } layout::Variants::Multiple { discr_kind: layout::DiscriminantKind::Tag, @@ -1455,54 +1404,58 @@ impl EnumMemberDescriptionFactory<'ll, 'tcx> { let discriminant_info = if fallback { RegularDiscriminant { discr_field: Field::from(discr_index), - discr_type_metadata: self.discriminant_type_metadata.unwrap() + discr_type_metadata: self.discriminant_type_metadata.unwrap(), } } else { // This doesn't matter in this case. NoDiscriminant }; - variants.iter_enumerated().map(|(i, _)| { - let variant = self.layout.for_variant(cx, i); - let variant_info = variant_info_for(i); - let (variant_type_metadata, member_desc_factory) = - describe_enum_variant(cx, - variant, - variant_info, - discriminant_info, - self_metadata, - self.span); - - let member_descriptions = member_desc_factory - .create_member_descriptions(cx); - - set_members_of_composite_type(cx, - self.enum_type, - variant_type_metadata, - member_descriptions); - - MemberDescription { - name: if fallback { - String::new() - } else { - variant_info.variant_name() - }, - type_metadata: variant_type_metadata, - offset: Size::ZERO, - size: self.layout.size, - align: self.layout.align.abi, - flags: DIFlags::FlagZero, - discriminant: Some( - self.layout.ty.discriminant_for_variant(cx.tcx, i).unwrap().val as u64 - ), - } - }).collect() + variants + .iter_enumerated() + .map(|(i, _)| { + let variant = self.layout.for_variant(cx, i); + let variant_info = variant_info_for(i); + let (variant_type_metadata, member_desc_factory) = describe_enum_variant( + cx, + variant, + variant_info, + discriminant_info, + self_metadata, + self.span, + ); + + let member_descriptions = + member_desc_factory.create_member_descriptions(cx); + + set_members_of_composite_type( + cx, + self.enum_type, + variant_type_metadata, + member_descriptions, + ); + + MemberDescription { + name: if fallback { + String::new() + } else { + variant_info.variant_name() + }, + type_metadata: variant_type_metadata, + offset: Size::ZERO, + size: self.layout.size, + align: self.layout.align.abi, + flags: DIFlags::FlagZero, + discriminant: Some( + self.layout.ty.discriminant_for_variant(cx.tcx, i).unwrap().val + as u64, + ), + } + }) + .collect() } layout::Variants::Multiple { - discr_kind: layout::DiscriminantKind::Niche { - ref niche_variants, - niche_start, - dataful_variant, - }, + discr_kind: + layout::DiscriminantKind::Niche { ref niche_variants, niche_start, dataful_variant }, ref discr, ref variants, discr_index, @@ -1510,32 +1463,37 @@ impl EnumMemberDescriptionFactory<'ll, 'tcx> { if fallback { let variant = self.layout.for_variant(cx, dataful_variant); // Create a description of the non-null variant. - let (variant_type_metadata, member_description_factory) = - describe_enum_variant(cx, - variant, - variant_info_for(dataful_variant), - OptimizedDiscriminant, - self.containing_scope, - self.span); + let (variant_type_metadata, member_description_factory) = describe_enum_variant( + cx, + variant, + variant_info_for(dataful_variant), + OptimizedDiscriminant, + self.containing_scope, + self.span, + ); let variant_member_descriptions = member_description_factory.create_member_descriptions(cx); - set_members_of_composite_type(cx, - self.enum_type, - variant_type_metadata, - variant_member_descriptions); + set_members_of_composite_type( + cx, + self.enum_type, + variant_type_metadata, + variant_member_descriptions, + ); // Encode the information about the null variant in the union // member's name. let mut name = String::from("RUST$ENCODED$ENUM$"); // Right now it's not even going to work for `niche_start > 0`, // and for multiple niche variants it only supports the first. - fn compute_field_path<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>, - name: &mut String, - layout: TyLayout<'tcx>, - offset: Size, - size: Size) { + fn compute_field_path<'a, 'tcx>( + cx: &CodegenCx<'a, 'tcx>, + name: &mut String, + layout: TyLayout<'tcx>, + offset: Size, + size: Size, + ) { for i in 0..layout.fields.count() { let field_offset = layout.fields.offset(i); if field_offset > offset { @@ -1549,70 +1507,78 @@ impl EnumMemberDescriptionFactory<'ll, 'tcx> { } } } - compute_field_path(cx, &mut name, - self.layout, - self.layout.fields.offset(discr_index), - self.layout.field(cx, discr_index).size); + compute_field_path( + cx, + &mut name, + self.layout, + self.layout.fields.offset(discr_index), + self.layout.field(cx, discr_index).size, + ); variant_info_for(*niche_variants.start()).map_struct_name(|variant_name| { name.push_str(variant_name); }); // Create the (singleton) list of descriptions of union members. - vec![ - MemberDescription { - name, - type_metadata: variant_type_metadata, - offset: Size::ZERO, - size: variant.size, - align: variant.align.abi, - flags: DIFlags::FlagZero, - discriminant: None, - } - ] + vec![MemberDescription { + name, + type_metadata: variant_type_metadata, + offset: Size::ZERO, + size: variant.size, + align: variant.align.abi, + flags: DIFlags::FlagZero, + discriminant: None, + }] } else { - variants.iter_enumerated().map(|(i, _)| { - let variant = self.layout.for_variant(cx, i); - let variant_info = variant_info_for(i); - let (variant_type_metadata, member_desc_factory) = - describe_enum_variant(cx, - variant, - variant_info, - OptimizedDiscriminant, - self_metadata, - self.span); - - let member_descriptions = member_desc_factory - .create_member_descriptions(cx); - - set_members_of_composite_type(cx, - self.enum_type, - variant_type_metadata, - member_descriptions); - - let niche_value = if i == dataful_variant { - None - } else { - let value = (i.as_u32() as u128) - .wrapping_sub(niche_variants.start().as_u32() as u128) - .wrapping_add(niche_start); - let value = truncate(value, discr.value.size(cx)); - // NOTE(eddyb) do *NOT* remove this assert, until - // we pass the full 128-bit value to LLVM, otherwise - // truncation will be silent and remain undetected. - assert_eq!(value as u64 as u128, value); - Some(value as u64) - }; - - MemberDescription { - name: variant_info.variant_name(), - type_metadata: variant_type_metadata, - offset: Size::ZERO, - size: self.layout.size, - align: self.layout.align.abi, - flags: DIFlags::FlagZero, - discriminant: niche_value, - } - }).collect() + variants + .iter_enumerated() + .map(|(i, _)| { + let variant = self.layout.for_variant(cx, i); + let variant_info = variant_info_for(i); + let (variant_type_metadata, member_desc_factory) = + describe_enum_variant( + cx, + variant, + variant_info, + OptimizedDiscriminant, + self_metadata, + self.span, + ); + + let member_descriptions = + member_desc_factory.create_member_descriptions(cx); + + set_members_of_composite_type( + cx, + self.enum_type, + variant_type_metadata, + member_descriptions, + ); + + let niche_value = if i == dataful_variant { + None + } else { + let value = (i.as_u32() as u128) + .wrapping_sub(niche_variants.start().as_u32() as u128) + .wrapping_add(niche_start); + let value = truncate(value, discr.value.size(cx)); + // NOTE(eddyb) do *NOT* remove this assert, until + // we pass the full 128-bit value to LLVM, otherwise + // truncation will be silent and remain undetected. + assert_eq!(value as u64 as u128, value); + Some(value as u64) + }; + + MemberDescription { + name: variant_info.variant_name(), + type_metadata: variant_type_metadata, + offset: Size::ZERO, + size: self.layout.size, + align: self.layout.align.abi, + flags: DIFlags::FlagZero, + discriminant: niche_value, + } + }) + .collect() } } } @@ -1629,37 +1595,40 @@ struct VariantMemberDescriptionFactory<'ll, 'tcx> { } impl VariantMemberDescriptionFactory<'ll, 'tcx> { - fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>) - -> Vec> { - self.args.iter().enumerate().map(|(i, &(ref name, ty))| { - let (size, align) = cx.size_and_align_of(ty); - MemberDescription { - name: name.to_string(), - type_metadata: if use_enum_fallback(cx) { - match self.discriminant_type_metadata { - // Discriminant is always the first field of our variant - // when using the enum fallback. - Some(metadata) if i == 0 => metadata, - _ => type_metadata(cx, ty, self.span) - } - } else { - type_metadata(cx, ty, self.span) - }, - offset: self.offsets[i], - size, - align, - flags: DIFlags::FlagZero, - discriminant: None, - } - }).collect() + fn create_member_descriptions(&self, cx: &CodegenCx<'ll, 'tcx>) -> Vec> { + self.args + .iter() + .enumerate() + .map(|(i, &(ref name, ty))| { + let (size, align) = cx.size_and_align_of(ty); + MemberDescription { + name: name.to_string(), + type_metadata: if use_enum_fallback(cx) { + match self.discriminant_type_metadata { + // Discriminant is always the first field of our variant + // when using the enum fallback. + Some(metadata) if i == 0 => metadata, + _ => type_metadata(cx, ty, self.span), + } + } else { + type_metadata(cx, ty, self.span) + }, + offset: self.offsets[i], + size, + align, + flags: DIFlags::FlagZero, + discriminant: None, + } + }) + .collect() } } #[derive(Copy, Clone)] enum EnumDiscriminantInfo<'ll> { - RegularDiscriminant{ discr_field: Field, discr_type_metadata: &'ll DIType }, + RegularDiscriminant { discr_field: Field, discr_type_metadata: &'ll DIType }, OptimizedDiscriminant, - NoDiscriminant + NoDiscriminant, } #[derive(Copy, Clone)] @@ -1677,8 +1646,9 @@ impl<'tcx> VariantInfo<'_, 'tcx> { fn map_struct_name(&self, f: impl FnOnce(&str) -> R) -> R { match self { VariantInfo::Adt(variant) => f(&variant.ident.as_str()), - VariantInfo::Generator { substs, variant_index, .. } => - f(&substs.as_generator().variant_name(*variant_index)), + VariantInfo::Generator { substs, variant_index, .. } => { + f(&substs.as_generator().variant_name(*variant_index)) + } } } @@ -1697,16 +1667,18 @@ impl<'tcx> VariantInfo<'_, 'tcx> { fn field_name(&self, i: usize) -> String { let field_name = match *self { - VariantInfo::Adt(variant) if variant.ctor_kind != CtorKind::Fn => - Some(variant.fields[i].ident.name), + VariantInfo::Adt(variant) if variant.ctor_kind != CtorKind::Fn => { + Some(variant.fields[i].ident.name) + } VariantInfo::Generator { generator_layout, generator_saved_local_names, variant_index, .. - } => generator_saved_local_names[ - generator_layout.variant_fields[variant_index][i.into()] - ], + } => { + generator_saved_local_names + [generator_layout.variant_fields[variant_index][i.into()]] + } _ => None, }; field_name.map(|name| name.to_string()).unwrap_or_else(|| format!("__{}", i)) @@ -1726,17 +1698,11 @@ fn describe_enum_variant( span: Span, ) -> (&'ll DICompositeType, MemberDescriptionFactory<'ll, 'tcx>) { let metadata_stub = variant.map_struct_name(|variant_name| { - let unique_type_id = debug_context(cx).type_map - .borrow_mut() - .get_unique_type_id_of_enum_variant( - cx, - layout.ty, - &variant_name); - create_struct_stub(cx, - layout.ty, - &variant_name, - unique_type_id, - Some(containing_scope)) + let unique_type_id = debug_context(cx) + .type_map + .borrow_mut() + .get_unique_type_id_of_enum_variant(cx, layout.ty, &variant_name); + create_struct_stub(cx, layout.ty, &variant_name, unique_type_id, Some(containing_scope)) }); // Build an array of (field name, field type) pairs to be captured in the factory closure. @@ -1747,44 +1713,43 @@ fn describe_enum_variant( // We have the layout of an enum variant, we need the layout of the outer enum let enum_layout = cx.layout_of(layout.ty); let offset = enum_layout.fields.offset(discr_field.as_usize()); - let args = ( - "RUST$ENUM$DISR".to_owned(), - enum_layout.field(cx, discr_field.as_usize()).ty); + let args = + ("RUST$ENUM$DISR".to_owned(), enum_layout.field(cx, discr_field.as_usize()).ty); (Some(offset), Some(args)) } _ => (None, None), }; ( - discr_offset.into_iter().chain((0..layout.fields.count()).map(|i| { - layout.fields.offset(i) - })).collect(), - discr_arg.into_iter().chain((0..layout.fields.count()).map(|i| { - (variant.field_name(i), layout.field(cx, i).ty) - })).collect() + discr_offset + .into_iter() + .chain((0..layout.fields.count()).map(|i| layout.fields.offset(i))) + .collect(), + discr_arg + .into_iter() + .chain( + (0..layout.fields.count()) + .map(|i| (variant.field_name(i), layout.field(cx, i).ty)), + ) + .collect(), ) } else { ( - (0..layout.fields.count()).map(|i| { - layout.fields.offset(i) - }).collect(), - (0..layout.fields.count()).map(|i| { - (variant.field_name(i), layout.field(cx, i).ty) - }).collect() + (0..layout.fields.count()).map(|i| layout.fields.offset(i)).collect(), + (0..layout.fields.count()) + .map(|i| (variant.field_name(i), layout.field(cx, i).ty)) + .collect(), ) }; - let member_description_factory = - VariantMDF(VariantMemberDescriptionFactory { - offsets, - args, - discriminant_type_metadata: match discriminant_info { - RegularDiscriminant { discr_type_metadata, .. } => { - Some(discr_type_metadata) - } - _ => None - }, - span, - }); + let member_description_factory = VariantMDF(VariantMemberDescriptionFactory { + offsets, + args, + discriminant_type_metadata: match discriminant_info { + RegularDiscriminant { discr_type_metadata, .. } => Some(discr_type_metadata), + _ => None, + }, + span, + }); (metadata_stub, member_description_factory) } @@ -1820,7 +1785,8 @@ fn prepare_enum_metadata( DIB(cx), name.as_ptr(), // FIXME: what if enumeration has i128 discriminant? - discr.val as u64)) + discr.val as u64, + )) } }) .collect(), @@ -1834,7 +1800,8 @@ fn prepare_enum_metadata( DIB(cx), name.as_ptr(), // FIXME: what if enumeration has i128 discriminant? - variant_index.as_usize() as u64)) + variant_index.as_usize() as u64, + )) } }) .collect(), @@ -1842,14 +1809,12 @@ fn prepare_enum_metadata( }; let disr_type_key = (enum_def_id, discr); - let cached_discriminant_type_metadata = debug_context(cx).created_enum_disr_types - .borrow() - .get(&disr_type_key).cloned(); + let cached_discriminant_type_metadata = + debug_context(cx).created_enum_disr_types.borrow().get(&disr_type_key).cloned(); match cached_discriminant_type_metadata { Some(discriminant_type_metadata) => discriminant_type_metadata, None => { - let (discriminant_size, discriminant_align) = - (discr.size(cx), discr.align(cx)); + let (discriminant_size, discriminant_align) = (discr.size(cx), discr.align(cx)); let discriminant_base_type_metadata = type_metadata(cx, discr.to_ty(cx.tcx), syntax_pos::DUMMY_SP); @@ -1869,12 +1834,15 @@ fn prepare_enum_metadata( discriminant_size.bits(), discriminant_align.abi.bits() as u32, create_DIArray(DIB(cx), &enumerators_metadata), - discriminant_base_type_metadata, true) + discriminant_base_type_metadata, + true, + ) }; - debug_context(cx).created_enum_disr_types - .borrow_mut() - .insert(disr_type_key, discriminant_type_metadata); + debug_context(cx) + .created_enum_disr_types + .borrow_mut() + .insert(disr_type_key, discriminant_type_metadata); discriminant_type_metadata } @@ -1884,23 +1852,26 @@ fn prepare_enum_metadata( let layout = cx.layout_of(enum_type); match (&layout.abi, &layout.variants) { - (&layout::Abi::Scalar(_), &layout::Variants::Multiple { - discr_kind: layout::DiscriminantKind::Tag, - ref discr, - .. - }) => return FinalMetadata(discriminant_type_metadata(discr.value)), + ( + &layout::Abi::Scalar(_), + &layout::Variants::Multiple { + discr_kind: layout::DiscriminantKind::Tag, + ref discr, + .. + }, + ) => return FinalMetadata(discriminant_type_metadata(discr.value)), _ => {} } let enum_name = SmallCStr::new(&enum_name); let unique_type_id_str = SmallCStr::new( - debug_context(cx).type_map.borrow().get_unique_type_id_as_string(unique_type_id) + debug_context(cx).type_map.borrow().get_unique_type_id_as_string(unique_type_id), ); if use_enum_fallback(cx) { let discriminant_type_metadata = match layout.variants { - layout::Variants::Single { .. } | - layout::Variants::Multiple { + layout::Variants::Single { .. } + | layout::Variants::Multiple { discr_kind: layout::DiscriminantKind::Niche { .. }, .. } => None, @@ -1908,9 +1879,7 @@ fn prepare_enum_metadata( discr_kind: layout::DiscriminantKind::Tag, ref discr, .. - } => { - Some(discriminant_type_metadata(discr.value)) - } + } => Some(discriminant_type_metadata(discr.value)), }; let enum_metadata = unsafe { @@ -1925,7 +1894,8 @@ fn prepare_enum_metadata( DIFlags::FlagZero, None, 0, // RuntimeLang - unique_type_id_str.as_ptr()) + unique_type_id_str.as_ptr(), + ) }; return create_and_register_recursive_type_forward_declaration( @@ -1968,7 +1938,8 @@ fn prepare_enum_metadata( layout::F32 => Integer::I32, layout::F64 => Integer::I64, layout::Pointer => cx.data_layout().ptr_sized_integer(), - }.to_ty(cx.tcx, false); + } + .to_ty(cx.tcx, false); let discr_metadata = basic_type_metadata(cx, discr_type); unsafe { @@ -1982,9 +1953,10 @@ fn prepare_enum_metadata( align.abi.bits() as u32, layout.fields.offset(discr_index).bits(), DIFlags::FlagArtificial, - discr_metadata)) + discr_metadata, + )) } - }, + } layout::Variants::Multiple { discr_kind: layout::DiscriminantKind::Tag, @@ -2007,9 +1979,10 @@ fn prepare_enum_metadata( align.bits() as u32, layout.fields.offset(discr_index).bits(), DIFlags::FlagArtificial, - discr_metadata)) + discr_metadata, + )) } - }, + } }; let mut outer_fields = match layout.variants { @@ -2018,7 +1991,7 @@ fn prepare_enum_metadata( let tuple_mdf = TupleMemberDescriptionFactory { ty: enum_type, component_types: outer_field_tys, - span + span, }; tuple_mdf .create_member_descriptions(cx) @@ -2029,9 +2002,10 @@ fn prepare_enum_metadata( }; let variant_part_unique_type_id_str = SmallCStr::new( - debug_context(cx).type_map + debug_context(cx) + .type_map .borrow_mut() - .get_unique_type_id_str_of_enum_variant_part(unique_type_id) + .get_unique_type_id_str_of_enum_variant_part(unique_type_id), ); let empty_array = create_DIArray(DIB(cx), &[]); let variant_part = unsafe { @@ -2046,7 +2020,8 @@ fn prepare_enum_metadata( DIFlags::FlagZero, discriminator_metadata, empty_array, - variant_part_unique_type_id_str.as_ptr()) + variant_part_unique_type_id_str.as_ptr(), + ) }; outer_fields.push(Some(variant_part)); @@ -2066,7 +2041,8 @@ fn prepare_enum_metadata( type_array, 0, None, - unique_type_id_str.as_ptr()) + unique_type_id_str.as_ptr(), + ) }; return create_and_register_recursive_type_forward_declaration( @@ -2103,24 +2079,25 @@ fn composite_type_metadata( _definition_span: Span, ) -> &'ll DICompositeType { // Create the (empty) struct metadata node ... - let composite_type_metadata = create_struct_stub(cx, - composite_type, - composite_type_name, - composite_type_unique_id, - containing_scope); + let composite_type_metadata = create_struct_stub( + cx, + composite_type, + composite_type_name, + composite_type_unique_id, + containing_scope, + ); // ... and immediately create and add the member descriptions. - set_members_of_composite_type(cx, - composite_type, - composite_type_metadata, - member_descriptions); + set_members_of_composite_type(cx, composite_type, composite_type_metadata, member_descriptions); composite_type_metadata } -fn set_members_of_composite_type(cx: &CodegenCx<'ll, 'tcx>, - composite_type: Ty<'tcx>, - composite_type_metadata: &'ll DICompositeType, - member_descriptions: Vec>) { +fn set_members_of_composite_type( + cx: &CodegenCx<'ll, 'tcx>, + composite_type: Ty<'tcx>, + composite_type_metadata: &'ll DICompositeType, + member_descriptions: Vec>, +) { // In some rare cases LLVM metadata uniquing would lead to an existing type // description being used instead of a new one created in // create_struct_stub. This would cause a hard to trace assertion in @@ -2131,8 +2108,10 @@ fn set_members_of_composite_type(cx: &CodegenCx<'ll, 'tcx>, let mut composite_types_completed = debug_context(cx).composite_types_completed.borrow_mut(); if !composite_types_completed.insert(&composite_type_metadata) { - bug!("debuginfo::set_members_of_composite_type() - \ - Already completed forward declaration re-encountered."); + bug!( + "debuginfo::set_members_of_composite_type() - \ + Already completed forward declaration re-encountered." + ); } } @@ -2145,7 +2124,11 @@ fn set_members_of_composite_type(cx: &CodegenCx<'ll, 'tcx>, unsafe { let type_array = create_DIArray(DIB(cx), &member_metadata[..]); llvm::LLVMRustDICompositeTypeReplaceArrays( - DIB(cx), composite_type_metadata, Some(type_array), type_params); + DIB(cx), + composite_type_metadata, + Some(type_array), + type_params, + ); } } @@ -2155,40 +2138,42 @@ fn compute_type_parameters(cx: &CodegenCx<'ll, 'tcx>, ty: Ty<'tcx>) -> Option<&' if !substs.types().next().is_none() { let generics = cx.tcx.generics_of(def.did); let names = get_parameter_names(cx, generics); - let template_params: Vec<_> = substs.iter().zip(names).filter_map(|(kind, name)| { - if let GenericArgKind::Type(ty) = kind.unpack() { - let actual_type = cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), ty); - let actual_type_metadata = - type_metadata(cx, actual_type, syntax_pos::DUMMY_SP); - let name = SmallCStr::new(&name.as_str()); - Some(unsafe { - - Some(llvm::LLVMRustDIBuilderCreateTemplateTypeParameter( - DIB(cx), - None, - name.as_ptr(), - actual_type_metadata, - unknown_file_metadata(cx), - 0, - 0, - )) - }) - } else { - None - } - }).collect(); + let template_params: Vec<_> = substs + .iter() + .zip(names) + .filter_map(|(kind, name)| { + if let GenericArgKind::Type(ty) = kind.unpack() { + let actual_type = + cx.tcx.normalize_erasing_regions(ParamEnv::reveal_all(), ty); + let actual_type_metadata = + type_metadata(cx, actual_type, syntax_pos::DUMMY_SP); + let name = SmallCStr::new(&name.as_str()); + Some(unsafe { + Some(llvm::LLVMRustDIBuilderCreateTemplateTypeParameter( + DIB(cx), + None, + name.as_ptr(), + actual_type_metadata, + unknown_file_metadata(cx), + 0, + 0, + )) + }) + } else { + None + } + }) + .collect(); return Some(create_DIArray(DIB(cx), &template_params[..])); } } return Some(create_DIArray(DIB(cx), &[])); - fn get_parameter_names(cx: &CodegenCx<'_, '_>, - generics: &ty::Generics) - -> Vec { - let mut names = generics.parent.map_or(vec![], |def_id| { - get_parameter_names(cx, cx.tcx.generics_of(def_id)) - }); + fn get_parameter_names(cx: &CodegenCx<'_, '_>, generics: &ty::Generics) -> Vec { + let mut names = generics + .parent + .map_or(vec![], |def_id| get_parameter_names(cx, cx.tcx.generics_of(def_id))); names.extend(generics.params.iter().map(|param| param.name)); names } @@ -2208,7 +2193,7 @@ fn create_struct_stub( let name = SmallCStr::new(struct_type_name); let unique_type_id = SmallCStr::new( - debug_context(cx).type_map.borrow().get_unique_type_id_as_string(unique_type_id) + debug_context(cx).type_map.borrow().get_unique_type_id_as_string(unique_type_id), ); let metadata_stub = unsafe { // `LLVMRustDIBuilderCreateStructType()` wants an empty array. A null @@ -2229,7 +2214,8 @@ fn create_struct_stub( empty_array, 0, None, - unique_type_id.as_ptr()) + unique_type_id.as_ptr(), + ) }; metadata_stub @@ -2246,7 +2232,7 @@ fn create_union_stub( let name = SmallCStr::new(union_type_name); let unique_type_id = SmallCStr::new( - debug_context(cx).type_map.borrow().get_unique_type_id_as_string(unique_type_id) + debug_context(cx).type_map.borrow().get_unique_type_id_as_string(unique_type_id), ); let metadata_stub = unsafe { // `LLVMRustDIBuilderCreateUnionType()` wants an empty array. A null @@ -2265,7 +2251,8 @@ fn create_union_stub( DIFlags::FlagZero, Some(empty_array), 0, // RuntimeLang - unique_type_id.as_ptr()) + unique_type_id.as_ptr(), + ) }; metadata_stub @@ -2274,11 +2261,7 @@ fn create_union_stub( /// Creates debug information for the given global variable. /// /// Adds the created metadata nodes directly to the crate's IR. -pub fn create_global_var_metadata( - cx: &CodegenCx<'ll, '_>, - def_id: DefId, - global: &'ll Value, -) { +pub fn create_global_var_metadata(cx: &CodegenCx<'ll, '_>, def_id: DefId, global: &'ll Value) { if cx.dbg_cx.is_none() { return; } @@ -2317,20 +2300,20 @@ pub fn create_global_var_metadata( let global_align = cx.align_of(variable_type); unsafe { - llvm::LLVMRustDIBuilderCreateStaticVariable(DIB(cx), - Some(var_scope), - var_name.as_ptr(), - // If null, linkage_name field is omitted, - // which is what we want for no_mangle statics - linkage_name.as_ref() - .map_or(ptr::null(), |name| name.as_ptr()), - file_metadata, - line_number, - type_metadata, - is_local_to_unit, - global, - None, - global_align.bytes() as u32, + llvm::LLVMRustDIBuilderCreateStaticVariable( + DIB(cx), + Some(var_scope), + var_name.as_ptr(), + // If null, linkage_name field is omitted, + // which is what we want for no_mangle statics + linkage_name.as_ref().map_or(ptr::null(), |name| name.as_ptr()), + file_metadata, + line_number, + type_metadata, + is_local_to_unit, + global, + None, + global_align.bytes() as u32, ); } } @@ -2370,20 +2353,22 @@ pub fn create_vtable_metadata(cx: &CodegenCx<'ll, 'tcx>, ty: Ty<'tcx>, vtable: & empty_array, 0, Some(type_metadata), - name.as_ptr() + name.as_ptr(), ); - llvm::LLVMRustDIBuilderCreateStaticVariable(DIB(cx), - NO_SCOPE_METADATA, - name.as_ptr(), - ptr::null(), - unknown_file_metadata(cx), - UNKNOWN_LINE_NUMBER, - vtable_type, - true, - vtable, - None, - 0); + llvm::LLVMRustDIBuilderCreateStaticVariable( + DIB(cx), + NO_SCOPE_METADATA, + name.as_ptr(), + ptr::null(), + unknown_file_metadata(cx), + UNKNOWN_LINE_NUMBER, + vtable_type, + true, + vtable, + None, + 0, + ); } } @@ -2395,10 +2380,5 @@ pub fn extend_scope_to_file( defining_crate: CrateNum, ) -> &'ll DILexicalBlock { let file_metadata = file_metadata(cx, &file.name, defining_crate); - unsafe { - llvm::LLVMRustDIBuilderCreateLexicalBlockFile( - DIB(cx), - scope_metadata, - file_metadata) - } + unsafe { llvm::LLVMRustDIBuilderCreateLexicalBlockFile(DIB(cx), scope_metadata, file_metadata) } } diff --git a/src/librustc_codegen_ssa/base.rs b/src/librustc_codegen_ssa/base.rs index f6725e66f03e6..2d783d6d71336 100644 --- a/src/librustc_codegen_ssa/base.rs +++ b/src/librustc_codegen_ssa/base.rs @@ -13,58 +13,80 @@ //! but one `llvm::Type` corresponds to many `Ty`s; for instance, `tup(int, int, //! int)` and `rec(x=int, y=int, z=int)` will have the same `llvm::Type`. -use crate::{CachedModuleCodegen, CrateInfo, MemFlags, ModuleCodegen, ModuleKind}; use crate::back::write::{ - OngoingCodegen, start_async_codegen, submit_pre_lto_module_to_llvm, - submit_post_lto_module_to_llvm, + start_async_codegen, submit_post_lto_module_to_llvm, submit_pre_lto_module_to_llvm, + OngoingCodegen, }; -use crate::common::{RealPredicate, TypeKind, IntPredicate}; +use crate::common::{IntPredicate, RealPredicate, TypeKind}; use crate::meth; use crate::mir; use crate::mir::operand::OperandValue; use crate::mir::place::PlaceRef; use crate::traits::*; +use crate::{CachedModuleCodegen, CrateInfo, MemFlags, ModuleCodegen, ModuleKind}; use rustc::hir; -use rustc_session::cgu_reuse_tracker::CguReuse; use rustc::hir::def_id::{DefId, LOCAL_CRATE}; use rustc::middle::cstore::EncodedMetadata; +use rustc::middle::cstore::{self, LinkagePreference}; use rustc::middle::lang_items::StartFnLangItem; use rustc::middle::weak_lang_items; -use rustc::mir::mono::{CodegenUnitNameBuilder, CodegenUnit, MonoItem}; -use rustc::ty::{self, Ty, TyCtxt, Instance}; -use rustc::ty::layout::{self, Align, TyLayout, LayoutOf, VariantIdx, HasTyCtxt}; -use rustc::ty::layout::{FAT_PTR_ADDR, FAT_PTR_EXTRA}; -use rustc::ty::query::Providers; -use rustc::middle::cstore::{self, LinkagePreference}; -use rustc::util::common::{time, print_time_passes_entry, set_time_depth, time_depth}; +use rustc::mir::mono::{CodegenUnit, CodegenUnitNameBuilder, MonoItem}; use rustc::session::config::{self, EntryFnType, Lto}; use rustc::session::Session; +use rustc::ty::layout::{self, Align, HasTyCtxt, LayoutOf, TyLayout, VariantIdx}; +use rustc::ty::layout::{FAT_PTR_ADDR, FAT_PTR_EXTRA}; +use rustc::ty::query::Providers; +use rustc::ty::{self, Instance, Ty, TyCtxt}; +use rustc::util::common::{print_time_passes_entry, set_time_depth, time, time_depth}; use rustc::util::nodemap::FxHashMap; +use rustc_codegen_utils::{check_for_rustc_errors_attr, symbol_names_test}; use rustc_index::vec::Idx; -use rustc_codegen_utils::{symbol_names_test, check_for_rustc_errors_attr}; +use rustc_session::cgu_reuse_tracker::CguReuse; use syntax::attr; use syntax_pos::Span; use std::cmp; use std::ops::{Deref, DerefMut}; -use std::time::{Instant, Duration}; +use std::time::{Duration, Instant}; -pub fn bin_op_to_icmp_predicate(op: hir::BinOpKind, - signed: bool) - -> IntPredicate { +pub fn bin_op_to_icmp_predicate(op: hir::BinOpKind, signed: bool) -> IntPredicate { match op { hir::BinOpKind::Eq => IntPredicate::IntEQ, hir::BinOpKind::Ne => IntPredicate::IntNE, - hir::BinOpKind::Lt => if signed { IntPredicate::IntSLT } else { IntPredicate::IntULT }, - hir::BinOpKind::Le => if signed { IntPredicate::IntSLE } else { IntPredicate::IntULE }, - hir::BinOpKind::Gt => if signed { IntPredicate::IntSGT } else { IntPredicate::IntUGT }, - hir::BinOpKind::Ge => if signed { IntPredicate::IntSGE } else { IntPredicate::IntUGE }, - op => { - bug!("comparison_op_to_icmp_predicate: expected comparison operator, \ - found {:?}", - op) + hir::BinOpKind::Lt => { + if signed { + IntPredicate::IntSLT + } else { + IntPredicate::IntULT + } + } + hir::BinOpKind::Le => { + if signed { + IntPredicate::IntSLE + } else { + IntPredicate::IntULE + } + } + hir::BinOpKind::Gt => { + if signed { + IntPredicate::IntSGT + } else { + IntPredicate::IntUGT + } + } + hir::BinOpKind::Ge => { + if signed { + IntPredicate::IntSGE + } else { + IntPredicate::IntUGE + } } + op => bug!( + "comparison_op_to_icmp_predicate: expected comparison operator, \ + found {:?}", + op + ), } } @@ -77,9 +99,11 @@ pub fn bin_op_to_fcmp_predicate(op: hir::BinOpKind) -> RealPredicate { hir::BinOpKind::Gt => RealPredicate::RealOGT, hir::BinOpKind::Ge => RealPredicate::RealOGE, op => { - bug!("comparison_op_to_fcmp_predicate: expected comparison operator, \ + bug!( + "comparison_op_to_fcmp_predicate: expected comparison operator, \ found {:?}", - op); + op + ); } } } @@ -97,7 +121,7 @@ pub fn compare_simd_types<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( let cmp = bin_op_to_fcmp_predicate(op); let cmp = bx.fcmp(cmp, lhs, rhs); return bx.sext(cmp, ret_ty); - }, + } ty::Uint(_) => false, ty::Int(_) => true, _ => bug!("compare_simd_types: invalid SIMD type"), @@ -136,17 +160,13 @@ pub fn unsized_info<'tcx, Cx: CodegenMethods<'tcx>>( old_info.expect("unsized_info: missing old info for trait upcast") } (_, &ty::Dynamic(ref data, ..)) => { - let vtable_ptr = cx.layout_of(cx.tcx().mk_mut_ptr(target)) - .field(cx, FAT_PTR_EXTRA); + let vtable_ptr = cx.layout_of(cx.tcx().mk_mut_ptr(target)).field(cx, FAT_PTR_EXTRA); cx.const_ptrcast( meth::get_vtable(cx, source, data.principal()), cx.backend_type(vtable_ptr), ) } - _ => bug!( - "unsized_info: invalid unsizing {:?} -> {:?}", - source, target - ), + _ => bug!("unsized_info: invalid unsizing {:?} -> {:?}", source, target), } } @@ -159,12 +179,9 @@ pub fn unsize_thin_ptr<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( ) -> (Bx::Value, Bx::Value) { debug!("unsize_thin_ptr: {:?} => {:?}", src_ty, dst_ty); match (&src_ty.kind, &dst_ty.kind) { - (&ty::Ref(_, a, _), - &ty::Ref(_, b, _)) | - (&ty::Ref(_, a, _), - &ty::RawPtr(ty::TypeAndMut { ty: b, .. })) | - (&ty::RawPtr(ty::TypeAndMut { ty: a, .. }), - &ty::RawPtr(ty::TypeAndMut { ty: b, .. })) => { + (&ty::Ref(_, a, _), &ty::Ref(_, b, _)) + | (&ty::Ref(_, a, _), &ty::RawPtr(ty::TypeAndMut { ty: b, .. })) + | (&ty::RawPtr(ty::TypeAndMut { ty: a, .. }), &ty::RawPtr(ty::TypeAndMut { ty: b, .. })) => { assert!(bx.cx().type_is_sized(a)); let ptr_ty = bx.cx().type_ptr_to(bx.cx().backend_type(bx.cx().layout_of(b))); (bx.pointercast(src, ptr_ty), unsized_info(bx.cx(), a, b, None)) @@ -193,8 +210,10 @@ pub fn unsize_thin_ptr<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( // HACK(eddyb) have to bitcast pointers until LLVM removes pointee types. // FIXME(eddyb) move these out of this `match` arm, so they're always // applied, uniformly, no matter the source/destination types. - (bx.bitcast(lldata, bx.cx().scalar_pair_element_backend_type(dst_layout, 0, true)), - bx.bitcast(llextra, bx.cx().scalar_pair_element_backend_type(dst_layout, 1, true))) + ( + bx.bitcast(lldata, bx.cx().scalar_pair_element_backend_type(dst_layout, 0, true)), + bx.bitcast(llextra, bx.cx().scalar_pair_element_backend_type(dst_layout, 1, true)), + ) } _ => bug!("unsize_thin_ptr: called on bad types"), } @@ -210,9 +229,9 @@ pub fn coerce_unsized_into<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( let src_ty = src.layout.ty; let dst_ty = dst.layout.ty; match (&src_ty.kind, &dst_ty.kind) { - (&ty::Ref(..), &ty::Ref(..)) | - (&ty::Ref(..), &ty::RawPtr(..)) | - (&ty::RawPtr(..), &ty::RawPtr(..)) => { + (&ty::Ref(..), &ty::Ref(..)) + | (&ty::Ref(..), &ty::RawPtr(..)) + | (&ty::RawPtr(..), &ty::RawPtr(..)) => { let (base, info) = match bx.load_operand(src).val { OperandValue::Pair(base, info) => { // fat-ptr to fat-ptr unsize preserves the vtable @@ -224,10 +243,8 @@ pub fn coerce_unsized_into<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( let thin_ptr = dst.layout.field(bx.cx(), FAT_PTR_ADDR); (bx.pointercast(base, bx.cx().backend_type(thin_ptr)), info) } - OperandValue::Immediate(base) => { - unsize_thin_ptr(bx, base, src_ty, dst_ty) - } - OperandValue::Ref(..) => bug!() + OperandValue::Immediate(base) => unsize_thin_ptr(bx, base, src_ty, dst_ty), + OperandValue::Ref(..) => bug!(), }; OperandValue::Pair(base, info).store(bx, dst); } @@ -244,18 +261,21 @@ pub fn coerce_unsized_into<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( } if src_f.layout.ty == dst_f.layout.ty { - memcpy_ty(bx, dst_f.llval, dst_f.align, src_f.llval, src_f.align, - src_f.layout, MemFlags::empty()); + memcpy_ty( + bx, + dst_f.llval, + dst_f.align, + src_f.llval, + src_f.align, + src_f.layout, + MemFlags::empty(), + ); } else { coerce_unsized_into(bx, src_f, dst_f); } } } - _ => bug!( - "coerce_unsized_into: invalid coercion {:?} -> {:?}", - src_ty, - dst_ty, - ), + _ => bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}", src_ty, dst_ty,), } } @@ -313,11 +333,7 @@ pub fn from_immediate<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( bx: &mut Bx, val: Bx::Value, ) -> Bx::Value { - if bx.cx().val_ty(val) == bx.cx().type_i1() { - bx.zext(val, bx.cx().type_i8()) - } else { - val - } + if bx.cx().val_ty(val) == bx.cx().type_i1() { bx.zext(val, bx.cx().type_i8()) } else { val } } pub fn to_immediate<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( @@ -375,7 +391,7 @@ pub fn codegen_instance<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>( /// users main function. pub fn maybe_create_entry_wrapper<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(cx: &'a Bx::CodegenCx) { let (main_def_id, span) = match cx.tcx().entry_fn(LOCAL_CRATE) { - Some((def_id, _)) => { (def_id, cx.tcx().def_span(def_id)) }, + Some((def_id, _)) => (def_id, cx.tcx().def_span(def_id)), None => return, }; @@ -393,7 +409,7 @@ pub fn maybe_create_entry_wrapper<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(cx: &' match et { Some(EntryFnType::Main) => create_entry_fn::(cx, span, main_llfn, main_def_id, true), Some(EntryFnType::Start) => create_entry_fn::(cx, span, main_llfn, main_def_id, false), - None => {} // Do nothing. + None => {} // Do nothing. } fn create_entry_fn<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( @@ -417,15 +433,14 @@ pub fn maybe_create_entry_wrapper<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(cx: &' // late-bound regions, since late-bound // regions must appear in the argument // listing. - let main_ret_ty = cx.tcx().erase_regions( - &main_ret_ty.no_bound_vars().unwrap(), - ); + let main_ret_ty = cx.tcx().erase_regions(&main_ret_ty.no_bound_vars().unwrap()); if cx.get_defined_value("main").is_some() { // FIXME: We should be smart and show a better diagnostic here. - cx.sess().struct_span_err(sp, "entry symbol `main` defined multiple times") - .help("did you use `#[no_mangle]` on `fn main`? Use `#[start]` instead") - .emit(); + cx.sess() + .struct_span_err(sp, "entry symbol `main` defined multiple times") + .help("did you use `#[no_mangle]` on `fn main`? Use `#[start]` instead") + .emit(); cx.sess().abort_if_errors(); bug!(); } @@ -449,10 +464,13 @@ pub fn maybe_create_entry_wrapper<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(cx: &' ty::ParamEnv::reveal_all(), start_def_id, cx.tcx().intern_substs(&[main_ret_ty.into()]), - ).unwrap() + ) + .unwrap(), ); - (start_fn, vec![bx.pointercast(rust_main, cx.type_ptr_to(cx.type_i8p())), - arg_argc, arg_argv]) + ( + start_fn, + vec![bx.pointercast(rust_main, cx.type_ptr_to(cx.type_i8p())), arg_argc, arg_argv], + ) } else { debug!("using user-defined start fn"); (rust_main, vec![arg_argc, arg_argv]) @@ -467,9 +485,8 @@ pub fn maybe_create_entry_wrapper<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(cx: &' /// Obtain the `argc` and `argv` values to pass to the rust start function. fn get_argc_argv<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( cx: &'a Bx::CodegenCx, - bx: &mut Bx -) -> (Bx::Value, Bx::Value) -{ + bx: &mut Bx, +) -> (Bx::Value, Bx::Value) { if cx.sess().target.target.options.main_needs_argc_argv { // Params from native `main()` used as args for rust start function let param_argc = bx.get_param(0); @@ -496,8 +513,7 @@ pub fn codegen_crate( check_for_rustc_errors_attr(tcx); // Skip crate items and just output metadata in -Z no-codegen mode. - if tcx.sess.opts.debugging_opts.no_codegen || - !tcx.sess.opts.output_types.should_codegen() { + if tcx.sess.opts.debugging_opts.no_codegen || !tcx.sess.opts.output_types.should_codegen() { let ongoing_codegen = start_async_codegen(backend, tcx, metadata, 1); ongoing_codegen.codegen_finished(tcx); @@ -538,28 +554,21 @@ pub fn codegen_crate( // linkage, then it's already got an allocator shim and we'll be using that // one instead. If nothing exists then it's our job to generate the // allocator! - let any_dynamic_crate = tcx.dependency_formats(LOCAL_CRATE) - .iter() - .any(|(_, list)| { - use rustc::middle::dependency_format::Linkage; - list.iter().any(|&linkage| linkage == Linkage::Dynamic) - }); + let any_dynamic_crate = tcx.dependency_formats(LOCAL_CRATE).iter().any(|(_, list)| { + use rustc::middle::dependency_format::Linkage; + list.iter().any(|&linkage| linkage == Linkage::Dynamic) + }); let allocator_module = if any_dynamic_crate { None } else if let Some(kind) = tcx.allocator_kind() { - let llmod_id = cgu_name_builder.build_cgu_name(LOCAL_CRATE, - &["crate"], - Some("allocator")).to_string(); + let llmod_id = + cgu_name_builder.build_cgu_name(LOCAL_CRATE, &["crate"], Some("allocator")).to_string(); let mut modules = backend.new_metadata(tcx, &llmod_id); time(tcx.sess, "write allocator module", || { backend.codegen_allocator(tcx, &mut modules, kind) }); - Some(ModuleCodegen { - name: llmod_id, - module_llvm: modules, - kind: ModuleKind::Allocator, - }) + Some(ModuleCodegen { name: llmod_id, module_llvm: modules, kind: ModuleKind::Allocator }) } else { None }; @@ -570,13 +579,15 @@ pub fn codegen_crate( if need_metadata_module { // Codegen the encoded metadata. - let metadata_cgu_name = cgu_name_builder.build_cgu_name(LOCAL_CRATE, - &["crate"], - Some("metadata")).to_string(); + let metadata_cgu_name = + cgu_name_builder.build_cgu_name(LOCAL_CRATE, &["crate"], Some("metadata")).to_string(); let mut metadata_llvm_module = backend.new_metadata(tcx, &metadata_cgu_name); time(tcx.sess, "write compressed metadata", || { - backend.write_compressed_metadata(tcx, &ongoing_codegen.metadata, - &mut metadata_llvm_module); + backend.write_compressed_metadata( + tcx, + &ongoing_codegen.metadata, + &mut metadata_llvm_module, + ); }); let metadata_module = ModuleCodegen { @@ -612,19 +623,26 @@ pub fn codegen_crate( false } CguReuse::PreLto => { - submit_pre_lto_module_to_llvm(&backend, tcx, &ongoing_codegen.coordinator_send, - CachedModuleCodegen { - name: cgu.name().to_string(), - source: cgu.work_product(tcx), - }); + submit_pre_lto_module_to_llvm( + &backend, + tcx, + &ongoing_codegen.coordinator_send, + CachedModuleCodegen { + name: cgu.name().to_string(), + source: cgu.work_product(tcx), + }, + ); true } CguReuse::PostLto => { - submit_post_lto_module_to_llvm(&backend, &ongoing_codegen.coordinator_send, - CachedModuleCodegen { - name: cgu.name().to_string(), - source: cgu.work_product(tcx), - }); + submit_post_lto_module_to_llvm( + &backend, + &ongoing_codegen.coordinator_send, + CachedModuleCodegen { + name: cgu.name().to_string(), + source: cgu.work_product(tcx), + }, + ); true } }; @@ -636,9 +654,7 @@ pub fn codegen_crate( // -Ztime-passes output manually. let time_depth = time_depth(); set_time_depth(time_depth + 1); - print_time_passes_entry(tcx.sess.time_passes(), - "codegen to LLVM IR", - total_codegen_time); + print_time_passes_entry(tcx.sess.time_passes(), "codegen to LLVM IR", total_codegen_time); set_time_depth(time_depth); ::rustc_incremental::assert_module_sources::assert_module_sources(tcx); @@ -699,13 +715,9 @@ impl Drop for AbortCodegenOnDrop { } fn assert_and_save_dep_graph(tcx: TyCtxt<'_>) { - time(tcx.sess, - "assert dep graph", - || ::rustc_incremental::assert_dep_graph(tcx)); + time(tcx.sess, "assert dep graph", || ::rustc_incremental::assert_dep_graph(tcx)); - time(tcx.sess, - "serialize dep graph", - || ::rustc_incremental::save_dep_graph(tcx)); + time(tcx.sess, "serialize dep graph", || ::rustc_incremental::save_dep_graph(tcx)); } impl CrateInfo { @@ -765,7 +777,8 @@ impl CrateInfo { // No need to look for lang items that are whitelisted and don't // actually need to exist. - let missing = missing.iter() + let missing = missing + .iter() .cloned() .filter(|&l| !weak_lang_items::whitelisted(tcx, l)) .collect(); @@ -812,15 +825,15 @@ pub fn provide_both(providers: &mut Providers<'_>) { providers.dllimport_foreign_items = |tcx, krate| { let module_map = tcx.foreign_modules(krate); - let module_map = module_map.iter() - .map(|lib| (lib.def_id, lib)) - .collect::>(); + let module_map = + module_map.iter().map(|lib| (lib.def_id, lib)).collect::>(); - let dllimports = tcx.native_libraries(krate) + let dllimports = tcx + .native_libraries(krate) .iter() .filter(|lib| { if lib.kind != cstore::NativeLibraryKind::NativeUnknown { - return false + return false; } let cfg = match lib.cfg { Some(ref cfg) => cfg, @@ -835,21 +848,20 @@ pub fn provide_both(providers: &mut Providers<'_>) { tcx.arena.alloc(dllimports) }; - providers.is_dllimport_foreign_item = |tcx, def_id| { - tcx.dllimport_foreign_items(def_id.krate).contains(&def_id) - }; + providers.is_dllimport_foreign_item = + |tcx, def_id| tcx.dllimport_foreign_items(def_id.krate).contains(&def_id); } fn determine_cgu_reuse<'tcx>(tcx: TyCtxt<'tcx>, cgu: &CodegenUnit<'tcx>) -> CguReuse { if !tcx.dep_graph.is_fully_enabled() { - return CguReuse::No + return CguReuse::No; } let work_product_id = &cgu.work_product_id(); if tcx.dep_graph.previous_work_product(work_product_id).is_none() { // We don't have anything cached for this CGU. This can happen // if the CGU did not exist in the previous session. - return CguReuse::No + return CguReuse::No; } // Try to mark the CGU as green. If it we can do so, it means that nothing @@ -859,17 +871,15 @@ fn determine_cgu_reuse<'tcx>(tcx: TyCtxt<'tcx>, cgu: &CodegenUnit<'tcx>) -> CguR // know that later). If we are not doing LTO, there is only one optimized // version of each module, so we re-use that. let dep_node = cgu.codegen_dep_node(tcx); - assert!(!tcx.dep_graph.dep_node_exists(&dep_node), + assert!( + !tcx.dep_graph.dep_node_exists(&dep_node), "CompileCodegenUnit dep-node for CGU `{}` already exists before marking.", - cgu.name()); + cgu.name() + ); if tcx.dep_graph.try_mark_green(tcx, &dep_node).is_some() { // We can re-use either the pre- or the post-thinlto state - if tcx.sess.lto() != Lto::No { - CguReuse::PreLto - } else { - CguReuse::PostLto - } + if tcx.sess.lto() != Lto::No { CguReuse::PreLto } else { CguReuse::PostLto } } else { CguReuse::No } diff --git a/src/librustc_codegen_ssa/mir/place.rs b/src/librustc_codegen_ssa/mir/place.rs index 98d239d353d3a..7399db1f2b950 100644 --- a/src/librustc_codegen_ssa/mir/place.rs +++ b/src/librustc_codegen_ssa/mir/place.rs @@ -1,15 +1,15 @@ -use super::{FunctionCx, LocalRef}; use super::operand::OperandValue; +use super::{FunctionCx, LocalRef}; -use crate::MemFlags; use crate::common::IntPredicate; use crate::glue; use crate::traits::*; +use crate::MemFlags; -use rustc::ty::{self, Instance, Ty}; -use rustc::ty::layout::{self, Align, TyLayout, LayoutOf, VariantIdx, HasTyCtxt}; use rustc::mir; use rustc::mir::tcx::PlaceTy; +use rustc::ty::layout::{self, Align, HasTyCtxt, LayoutOf, TyLayout, VariantIdx}; +use rustc::ty::{self, Instance, Ty}; #[derive(Copy, Clone, Debug)] pub struct PlaceRef<'tcx, V> { @@ -27,31 +27,14 @@ pub struct PlaceRef<'tcx, V> { } impl<'a, 'tcx, V: CodegenObject> PlaceRef<'tcx, V> { - pub fn new_sized( - llval: V, - layout: TyLayout<'tcx>, - ) -> PlaceRef<'tcx, V> { + pub fn new_sized(llval: V, layout: TyLayout<'tcx>) -> PlaceRef<'tcx, V> { assert!(!layout.is_unsized()); - PlaceRef { - llval, - llextra: None, - layout, - align: layout.align.abi - } + PlaceRef { llval, llextra: None, layout, align: layout.align.abi } } - pub fn new_sized_aligned( - llval: V, - layout: TyLayout<'tcx>, - align: Align, - ) -> PlaceRef<'tcx, V> { + pub fn new_sized_aligned(llval: V, layout: TyLayout<'tcx>, align: Align) -> PlaceRef<'tcx, V> { assert!(!layout.is_unsized()); - PlaceRef { - llval, - llextra: None, - layout, - align - } + PlaceRef { llval, llextra: None, layout, align } } fn new_thin_place>( @@ -60,12 +43,7 @@ impl<'a, 'tcx, V: CodegenObject> PlaceRef<'tcx, V> { layout: TyLayout<'tcx>, ) -> PlaceRef<'tcx, V> { assert!(!bx.cx().type_has_metadata(layout.ty)); - PlaceRef { - llval, - llextra: None, - layout, - align: layout.align.abi - } + PlaceRef { llval, llextra: None, layout, align: layout.align.abi } } // FIXME(eddyb) pass something else for the name so no work is done @@ -92,10 +70,7 @@ impl<'a, 'tcx, V: CodegenObject> PlaceRef<'tcx, V> { Self::alloca(bx, ptr_layout) } - pub fn len>( - &self, - cx: &Cx - ) -> V { + pub fn len>(&self, cx: &Cx) -> V { if let layout::FieldPlacement::Array { count, .. } = self.layout.fields { if self.layout.is_unsized() { assert_eq!(count, 0); @@ -112,7 +87,8 @@ impl<'a, 'tcx, V: CodegenObject> PlaceRef<'tcx, V> { impl<'a, 'tcx, V: CodegenObject> PlaceRef<'tcx, V> { /// Access a field, at a point when the value's case is known. pub fn project_field>( - self, bx: &mut Bx, + self, + bx: &mut Bx, ix: usize, ) -> Self { let field = self.layout.field(bx.cx(), ix); @@ -133,11 +109,7 @@ impl<'a, 'tcx, V: CodegenObject> PlaceRef<'tcx, V> { PlaceRef { // HACK(eddyb): have to bitcast pointers until LLVM removes pointee types. llval: bx.pointercast(llval, bx.cx().type_ptr_to(bx.cx().backend_type(field))), - llextra: if bx.cx().type_has_metadata(field.ty) { - self.llextra - } else { - None - }, + llextra: if bx.cx().type_has_metadata(field.ty) { self.llextra } else { None }, layout: field, align: effective_field_align, } @@ -149,8 +121,10 @@ impl<'a, 'tcx, V: CodegenObject> PlaceRef<'tcx, V> { // * packed struct - there is no alignment padding match field.ty.kind { _ if self.llextra.is_none() => { - debug!("unsized field `{}`, of `{:?}` has no metadata for adjustment", - ix, self.llval); + debug!( + "unsized field `{}`, of `{:?}` has no metadata for adjustment", + ix, self.llval + ); return simple(); } _ if !field.is_unsized() => return simple(), @@ -222,7 +196,7 @@ impl<'a, 'tcx, V: CodegenObject> PlaceRef<'tcx, V> { pub fn codegen_get_discr>( self, bx: &mut Bx, - cast_to: Ty<'tcx> + cast_to: Ty<'tcx>, ) -> V { let cast_to = bx.cx().immediate_backend_type(bx.cx().layout_of(cast_to)); if self.layout.abi.is_uninhabited() { @@ -230,7 +204,10 @@ impl<'a, 'tcx, V: CodegenObject> PlaceRef<'tcx, V> { } let (discr_scalar, discr_kind, discr_index) = match self.layout.variants { layout::Variants::Single { index } => { - let discr_val = self.layout.ty.discriminant_for_variant(bx.cx().tcx(), index) + let discr_val = self + .layout + .ty + .discriminant_for_variant(bx.cx().tcx(), index) .map_or(index.as_u32() as u128, |discr| discr.val); return bx.cx().const_uint_big(cast_to, discr_val); } @@ -252,7 +229,7 @@ impl<'a, 'tcx, V: CodegenObject> PlaceRef<'tcx, V> { // let LLVM interpret the `i1` as signed, because // then `i1 1` (i.e., `E::B`) is effectively `i8 -1`. layout::Int(_, signed) => !discr_scalar.is_bool() && signed, - _ => false + _ => false, }; bx.intcast(encoded_discr.immediate(), cast_to, signed) } @@ -330,7 +307,7 @@ impl<'a, 'tcx, V: CodegenObject> PlaceRef<'tcx, V> { pub fn codegen_set_discr>( &self, bx: &mut Bx, - variant_index: VariantIdx + variant_index: VariantIdx, ) { if self.layout.for_variant(bx.cx(), variant_index).abi.is_uninhabited() { // We play it safe by using a well-defined `abort`, but we could go for immediate UB @@ -353,20 +330,19 @@ impl<'a, 'tcx, V: CodegenObject> PlaceRef<'tcx, V> { bx.store( bx.cx().const_uint_big(bx.cx().backend_type(ptr.layout), to), ptr.llval, - ptr.align); + ptr.align, + ); } layout::Variants::Multiple { - discr_kind: layout::DiscriminantKind::Niche { - dataful_variant, - ref niche_variants, - niche_start, - }, + discr_kind: + layout::DiscriminantKind::Niche { dataful_variant, ref niche_variants, niche_start }, discr_index, .. } => { if variant_index != dataful_variant { - if bx.cx().sess().target.target.arch == "arm" || - bx.cx().sess().target.target.arch == "aarch64" { + if bx.cx().sess().target.target.arch == "arm" + || bx.cx().sess().target.target.arch == "aarch64" + { // FIXME(#34427): as workaround for LLVM bug on ARM, // use memset of 0 before assigning niche value. let fill_byte = bx.cx().const_u8(0); @@ -377,8 +353,7 @@ impl<'a, 'tcx, V: CodegenObject> PlaceRef<'tcx, V> { let niche = self.project_field(bx, discr_index); let niche_llty = bx.cx().immediate_backend_type(niche.layout); let niche_value = variant_index.as_u32() - niche_variants.start().as_u32(); - let niche_value = (niche_value as u128) - .wrapping_add(niche_start); + let niche_value = (niche_value as u128).wrapping_add(niche_start); // FIXME(eddyb): check the actual primitive type here. let niche_llval = if niche_value == 0 { // HACK(eddyb): using `c_null` as it works on all types. @@ -395,7 +370,7 @@ impl<'a, 'tcx, V: CodegenObject> PlaceRef<'tcx, V> { pub fn project_index>( &self, bx: &mut Bx, - llindex: V + llindex: V, ) -> Self { // Statically compute the offset if we can, otherwise just use the element size, // as this will yield the lowest alignment. @@ -417,7 +392,7 @@ impl<'a, 'tcx, V: CodegenObject> PlaceRef<'tcx, V> { pub fn project_downcast>( &self, bx: &mut Bx, - variant_index: VariantIdx + variant_index: VariantIdx, ) -> Self { let mut downcast = *self; downcast.layout = self.layout.for_variant(bx.cx(), variant_index); @@ -442,17 +417,14 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { pub fn codegen_place( &mut self, bx: &mut Bx, - place_ref: &mir::PlaceRef<'_, 'tcx> + place_ref: &mir::PlaceRef<'_, 'tcx>, ) -> PlaceRef<'tcx, Bx::Value> { debug!("codegen_place(place_ref={:?})", place_ref); let cx = self.cx; let tcx = self.cx.tcx(); let result = match place_ref { - mir::PlaceRef { - base: mir::PlaceBase::Local(index), - projection: [], - } => { + mir::PlaceRef { base: mir::PlaceBase::Local(index), projection: [] } => { match self.locals[*index] { LocalRef::Place(place) => { return place; @@ -466,11 +438,12 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { } } mir::PlaceRef { - base: mir::PlaceBase::Static(box mir::Static { - ty, - kind: mir::StaticKind::Promoted(promoted, substs), - def_id, - }), + base: + mir::PlaceBase::Static(box mir::Static { + ty, + kind: mir::StaticKind::Promoted(promoted, substs), + def_id, + }), projection: [], } => { let instance = Instance::new(*def_id, self.monomorphize(substs)); @@ -478,10 +451,9 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { match bx.tcx().const_eval_promoted(instance, *promoted) { Ok(val) => match val.val { ty::ConstKind::Value(mir::interpret::ConstValue::ByRef { - alloc, offset - }) => { - bx.cx().from_const_alloc(layout, alloc, offset) - } + alloc, + offset, + }) => bx.cx().from_const_alloc(layout, alloc, offset), _ => bug!("promoteds should have an allocation: {:?}", val), }, Err(_) => { @@ -492,19 +464,19 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { bx.abort(); // We still have to return a place but it doesn't matter, // this code is unreachable. - let llval = bx.cx().const_undef( - bx.cx().type_ptr_to(bx.cx().backend_type(layout)) - ); + let llval = + bx.cx().const_undef(bx.cx().type_ptr_to(bx.cx().backend_type(layout))); PlaceRef::new_sized(llval, layout) } } } mir::PlaceRef { - base: mir::PlaceBase::Static(box mir::Static { - ty, - kind: mir::StaticKind::Static, - def_id, - }), + base: + mir::PlaceBase::Static(box mir::Static { + ty, + kind: mir::StaticKind::Static, + def_id, + }), projection: [], } => { // NB: The layout of a static may be unsized as is the case when working @@ -512,26 +484,16 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { let layout = cx.layout_of(self.monomorphize(&ty)); let static_ = bx.get_static(*def_id); PlaceRef::new_thin_place(bx, static_, layout) - }, - mir::PlaceRef { - base, - projection: [proj_base @ .., mir::ProjectionElem::Deref], - } => { + } + mir::PlaceRef { base, projection: [proj_base @ .., mir::ProjectionElem::Deref] } => { // Load the pointer from its location. - self.codegen_consume(bx, &mir::PlaceRef { - base, - projection: proj_base, - }).deref(bx.cx()) + self.codegen_consume(bx, &mir::PlaceRef { base, projection: proj_base }) + .deref(bx.cx()) } - mir::PlaceRef { - base, - projection: [proj_base @ .., elem], - } => { + mir::PlaceRef { base, projection: [proj_base @ .., elem] } => { // FIXME turn this recursion into iteration - let cg_base = self.codegen_place(bx, &mir::PlaceRef { - base, - projection: proj_base, - }); + let cg_base = + self.codegen_place(bx, &mir::PlaceRef { base, projection: proj_base }); match elem { mir::ProjectionElem::Deref => bug!(), @@ -539,50 +501,54 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { cg_base.project_field(bx, field.index()) } mir::ProjectionElem::Index(index) => { - let index = &mir::Operand::Copy( - mir::Place::from(*index) - ); + let index = &mir::Operand::Copy(mir::Place::from(*index)); let index = self.codegen_operand(bx, index); let llindex = index.immediate(); cg_base.project_index(bx, llindex) } - mir::ProjectionElem::ConstantIndex { offset, - from_end: false, - min_length: _ } => { + mir::ProjectionElem::ConstantIndex { + offset, + from_end: false, + min_length: _, + } => { let lloffset = bx.cx().const_usize(*offset as u64); cg_base.project_index(bx, lloffset) } - mir::ProjectionElem::ConstantIndex { offset, - from_end: true, - min_length: _ } => { + mir::ProjectionElem::ConstantIndex { + offset, + from_end: true, + min_length: _, + } => { let lloffset = bx.cx().const_usize(*offset as u64); let lllen = cg_base.len(bx.cx()); let llindex = bx.sub(lllen, lloffset); cg_base.project_index(bx, llindex) } mir::ProjectionElem::Subslice { from, to, from_end } => { - let mut subslice = cg_base.project_index(bx, - bx.cx().const_usize(*from as u64)); - let projected_ty = PlaceTy::from_ty(cg_base.layout.ty) - .projection_ty(tcx, elem).ty; + let mut subslice = + cg_base.project_index(bx, bx.cx().const_usize(*from as u64)); + let projected_ty = + PlaceTy::from_ty(cg_base.layout.ty).projection_ty(tcx, elem).ty; subslice.layout = bx.cx().layout_of(self.monomorphize(&projected_ty)); if subslice.layout.is_unsized() { assert!(from_end, "slice subslices should be `from_end`"); - subslice.llextra = Some(bx.sub(cg_base.llextra.unwrap(), - bx.cx().const_usize((*from as u64) + (*to as u64)))); + subslice.llextra = Some(bx.sub( + cg_base.llextra.unwrap(), + bx.cx().const_usize((*from as u64) + (*to as u64)), + )); } // Cast the place pointer type to the new // array or slice type (`*[%_; new_len]`). - subslice.llval = bx.pointercast(subslice.llval, - bx.cx().type_ptr_to(bx.cx().backend_type(subslice.layout))); + subslice.llval = bx.pointercast( + subslice.llval, + bx.cx().type_ptr_to(bx.cx().backend_type(subslice.layout)), + ); subslice } - mir::ProjectionElem::Downcast(_, v) => { - cg_base.project_downcast(bx, *v) - } + mir::ProjectionElem::Downcast(_, v) => cg_base.project_downcast(bx, *v), } } }; @@ -592,12 +558,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { pub fn monomorphized_place_ty(&self, place_ref: &mir::PlaceRef<'_, 'tcx>) -> Ty<'tcx> { let tcx = self.cx.tcx(); - let place_ty = mir::Place::ty_from( - place_ref.base, - place_ref.projection, - *self.mir, - tcx, - ); + let place_ty = mir::Place::ty_from(place_ref.base, place_ref.projection, *self.mir, tcx); self.monomorphize(&place_ty.ty) } } diff --git a/src/librustc_codegen_utils/symbol_names/v0.rs b/src/librustc_codegen_utils/symbol_names/v0.rs index 858ad9f1cfda7..045d06a2e1de0 100644 --- a/src/librustc_codegen_utils/symbol_names/v0.rs +++ b/src/librustc_codegen_utils/symbol_names/v0.rs @@ -1,13 +1,13 @@ use rustc::hir; use rustc::hir::def_id::{CrateNum, DefId}; use rustc::hir::map::{DefPathData, DisambiguatedDefPathData}; -use rustc::ty::{self, Ty, TyCtxt, TypeFoldable, Instance}; -use rustc::ty::print::{Printer, Print}; -use rustc::ty::subst::{GenericArg, Subst, GenericArgKind}; +use rustc::ty::print::{Print, Printer}; +use rustc::ty::subst::{GenericArg, GenericArgKind, Subst}; +use rustc::ty::{self, Instance, Ty, TyCtxt, TypeFoldable}; use rustc_data_structures::base_n; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_target::spec::abi::Abi; -use syntax::ast::{IntTy, UintTy, FloatTy}; +use syntax::ast::{FloatTy, IntTy, UintTy}; use std::fmt::Write; use std::ops::Range; @@ -19,8 +19,7 @@ pub(super) fn mangle( ) -> String { let def_id = instance.def_id(); // FIXME(eddyb) this should ideally not be needed. - let substs = - tcx.normalize_erasing_regions(ty::ParamEnv::reveal_all(), instance.substs); + let substs = tcx.normalize_erasing_regions(ty::ParamEnv::reveal_all(), instance.substs); let prefix = "_R"; let mut cx = SymbolMangler { @@ -36,12 +35,7 @@ pub(super) fn mangle( out: String::from(prefix), }; cx = if instance.is_vtable_shim() { - cx.path_append_ns( - |cx| cx.print_def_path(def_id, substs), - 'S', - 0, - "", - ).unwrap() + cx.path_append_ns(|cx| cx.print_def_path(def_id, substs), 'S', 0, "").unwrap() } else { cx.print_def_path(def_id, substs).unwrap() }; @@ -183,9 +177,10 @@ impl SymbolMangler<'tcx> { fn in_binder( mut self, value: &ty::Binder, - print_value: impl FnOnce(Self, &T) -> Result + print_value: impl FnOnce(Self, &T) -> Result, ) -> Result - where T: TypeFoldable<'tcx> + where + T: TypeFoldable<'tcx>, { let regions = if value.has_late_bound_regions() { self.tcx.collect_referenced_late_bound_regions(value) @@ -196,16 +191,20 @@ impl SymbolMangler<'tcx> { let mut lifetime_depths = self.binders.last().map(|b| b.lifetime_depths.end).map_or(0..0, |i| i..i); - let lifetimes = regions.into_iter().map(|br| { - match br { - ty::BrAnon(i) => { - // FIXME(eddyb) for some reason, `anonymize_late_bound_regions` starts at `1`. - assert_ne!(i, 0); - i - 1 - }, - _ => bug!("symbol_names: non-anonymized region `{:?}` in `{:?}`", br, value), - } - }).max().map_or(0, |max| max + 1); + let lifetimes = regions + .into_iter() + .map(|br| { + match br { + ty::BrAnon(i) => { + // FIXME(eddyb) for some reason, `anonymize_late_bound_regions` starts at `1`. + assert_ne!(i, 0); + i - 1 + } + _ => bug!("symbol_names: non-anonymized region `{:?}` in `{:?}`", br, value), + } + }) + .max() + .map_or(0, |max| max + 1); self.push_opt_integer_62("G", lifetimes as u64); lifetime_depths.end += lifetimes; @@ -263,8 +262,7 @@ impl Printer<'tcx> for SymbolMangler<'tcx> { let key = self.tcx.def_key(impl_def_id); let parent_def_id = DefId { index: key.parent.unwrap(), ..impl_def_id }; - let mut param_env = self.tcx.param_env(impl_def_id) - .with_reveal_all(); + let mut param_env = self.tcx.param_env(impl_def_id).with_reveal_all(); if !substs.is_empty() { param_env = param_env.subst(self.tcx, substs); } @@ -272,8 +270,7 @@ impl Printer<'tcx> for SymbolMangler<'tcx> { match &mut impl_trait_ref { Some(impl_trait_ref) => { assert_eq!(impl_trait_ref.self_ty(), self_ty); - *impl_trait_ref = - self.tcx.normalize_erasing_regions(param_env, *impl_trait_ref); + *impl_trait_ref = self.tcx.normalize_erasing_regions(param_env, *impl_trait_ref); self_ty = impl_trait_ref.self_ty(); } None => { @@ -289,10 +286,7 @@ impl Printer<'tcx> for SymbolMangler<'tcx> { ) } - fn print_region( - mut self, - region: ty::Region<'_>, - ) -> Result { + fn print_region(mut self, region: ty::Region<'_>) -> Result { let i = match *region { // Erased lifetimes use the index 0, for a // shorter mangling of `L_`. @@ -318,10 +312,7 @@ impl Printer<'tcx> for SymbolMangler<'tcx> { Ok(self) } - fn print_type( - mut self, - ty: Ty<'tcx>, - ) -> Result { + fn print_type(mut self, ty: Ty<'tcx>) -> Result { // Basic types, never cached (single-character). let basic_type = match ty.kind { ty::Bool => "b", @@ -345,8 +336,7 @@ impl Printer<'tcx> for SymbolMangler<'tcx> { ty::Never => "z", // Placeholders (should be demangled as `_`). - ty::Param(_) | ty::Bound(..) | ty::Placeholder(_) | - ty::Infer(_) | ty::Error => "p", + ty::Param(_) | ty::Bound(..) | ty::Placeholder(_) | ty::Infer(_) | ty::Error => "p", _ => "", }; @@ -362,14 +352,15 @@ impl Printer<'tcx> for SymbolMangler<'tcx> { match ty.kind { // Basic types, handled above. - ty::Bool | ty::Char | ty::Str | - ty::Int(_) | ty::Uint(_) | ty::Float(_) | - ty::Never => unreachable!(), + ty::Bool | ty::Char | ty::Str | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Never => { + unreachable!() + } ty::Tuple(_) if ty.is_unit() => unreachable!(), // Placeholders, also handled as part of basic types. - ty::Param(_) | ty::Bound(..) | ty::Placeholder(_) | - ty::Infer(_) | ty::Error => unreachable!(), + ty::Param(_) | ty::Bound(..) | ty::Placeholder(_) | ty::Infer(_) | ty::Error => { + unreachable!() + } ty::Ref(r, ty, mutbl) => { self.push(match mutbl { @@ -409,13 +400,13 @@ impl Printer<'tcx> for SymbolMangler<'tcx> { } // Mangle all nominal types as paths. - ty::Adt(&ty::AdtDef { did: def_id, .. }, substs) | - ty::FnDef(def_id, substs) | - ty::Opaque(def_id, substs) | - ty::Projection(ty::ProjectionTy { item_def_id: def_id, substs }) | - ty::UnnormalizedProjection(ty::ProjectionTy { item_def_id: def_id, substs }) | - ty::Closure(def_id, substs) | - ty::Generator(def_id, substs, _) => { + ty::Adt(&ty::AdtDef { did: def_id, .. }, substs) + | ty::FnDef(def_id, substs) + | ty::Opaque(def_id, substs) + | ty::Projection(ty::ProjectionTy { item_def_id: def_id, substs }) + | ty::UnnormalizedProjection(ty::ProjectionTy { item_def_id: def_id, substs }) + | ty::Closure(def_id, substs) + | ty::Generator(def_id, substs, _) => { self = self.print_def_path(def_id, substs)?; } ty::Foreign(def_id) => { @@ -460,9 +451,7 @@ impl Printer<'tcx> for SymbolMangler<'tcx> { self = r.print(self)?; } - ty::GeneratorWitness(_) => { - bug!("symbol_names: unexpected `GeneratorWitness`") - } + ty::GeneratorWitness(_) => bug!("symbol_names: unexpected `GeneratorWitness`"), } // Only cache types that do not refer to an enclosing @@ -502,10 +491,7 @@ impl Printer<'tcx> for SymbolMangler<'tcx> { Ok(self) } - fn print_const( - mut self, - ct: &'tcx ty::Const<'tcx>, - ) -> Result { + fn print_const(mut self, ct: &'tcx ty::Const<'tcx>) -> Result { if let Some(&i) = self.compress.as_ref().and_then(|c| c.consts.get(&ct)) { return self.print_backref(i); } @@ -514,8 +500,7 @@ impl Printer<'tcx> for SymbolMangler<'tcx> { match ct.ty.kind { ty::Uint(_) => {} _ => { - bug!("symbol_names: unsupported constant of type `{}` ({:?})", - ct.ty, ct); + bug!("symbol_names: unsupported constant of type `{}` ({:?})", ct.ty, ct); } } self = ct.ty.print(self)?; @@ -539,10 +524,7 @@ impl Printer<'tcx> for SymbolMangler<'tcx> { Ok(self) } - fn path_crate( - mut self, - cnum: CrateNum, - ) -> Result { + fn path_crate(mut self, cnum: CrateNum) -> Result { self.push("C"); let fingerprint = self.tcx.crate_disambiguator(cnum).to_fingerprint(); self.push_disambiguator(fingerprint.to_smaller_hash()); @@ -612,7 +594,7 @@ impl Printer<'tcx> for SymbolMangler<'tcx> { print_prefix, ns, disambiguated_data.disambiguator as u64, - name.as_ref().map_or("", |s| &s[..]) + name.as_ref().map_or("", |s| &s[..]), ) } fn path_generic_args( @@ -621,17 +603,13 @@ impl Printer<'tcx> for SymbolMangler<'tcx> { args: &[GenericArg<'tcx>], ) -> Result { // Don't print any regions if they're all erased. - let print_regions = args.iter().any(|arg| { - match arg.unpack() { - GenericArgKind::Lifetime(r) => *r != ty::ReErased, - _ => false, - } + let print_regions = args.iter().any(|arg| match arg.unpack() { + GenericArgKind::Lifetime(r) => *r != ty::ReErased, + _ => false, }); - let args = args.iter().cloned().filter(|arg| { - match arg.unpack() { - GenericArgKind::Lifetime(_) => print_regions, - _ => true, - } + let args = args.iter().cloned().filter(|arg| match arg.unpack() { + GenericArgKind::Lifetime(_) => print_regions, + _ => true, }); if args.clone().next().is_none() { diff --git a/src/librustc_errors/emitter.rs b/src/librustc_errors/emitter.rs index 451913757482a..fdac4390b2675 100644 --- a/src/librustc_errors/emitter.rs +++ b/src/librustc_errors/emitter.rs @@ -9,26 +9,25 @@ use Destination::*; -use syntax_pos::{SourceFile, Span, MultiSpan}; use syntax_pos::source_map::SourceMap; +use syntax_pos::{MultiSpan, SourceFile, Span}; +use crate::snippet::{Annotation, AnnotationType, Line, MultilineAnnotation, Style, StyledString}; +use crate::styled_buffer::StyledBuffer; +use crate::Level::Error; use crate::{ - Level, CodeSuggestion, Diagnostic, SubDiagnostic, pluralize, - SuggestionStyle, DiagnosticId, + pluralize, CodeSuggestion, Diagnostic, DiagnosticId, Level, SubDiagnostic, SuggestionStyle, }; -use crate::Level::Error; -use crate::snippet::{Annotation, AnnotationType, Line, MultilineAnnotation, StyledString, Style}; -use crate::styled_buffer::StyledBuffer; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::sync::Lrc; use std::borrow::Cow; -use std::io::prelude::*; +use std::cmp::{max, min, Reverse}; use std::io; -use std::cmp::{min, max, Reverse}; +use std::io::prelude::*; use std::path::Path; -use termcolor::{StandardStream, ColorChoice, ColorSpec, BufferWriter, Ansi}; -use termcolor::{WriteColor, Color, Buffer}; +use termcolor::{Ansi, BufferWriter, ColorChoice, ColorSpec, StandardStream}; +use termcolor::{Buffer, Color, WriteColor}; /// Describes the way the content of the `rendered` field of the json output is generated #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -57,8 +56,15 @@ impl HumanReadableErrorType { ) -> EmitterWriter { let (short, color_config) = self.unzip(); let color = color_config.suggests_using_colors(); - EmitterWriter::new(dst, source_map, short, teach, color, terminal_width, - external_macro_backtrace) + EmitterWriter::new( + dst, + source_map, + short, + teach, + color, + terminal_width, + external_macro_backtrace, + ) } } @@ -117,15 +123,14 @@ impl Margin { } fn was_cut_right(&self, line_len: usize) -> bool { - let right = if self.computed_right == self.span_right || - self.computed_right == self.label_right - { - // Account for the "..." padding given above. Otherwise we end up with code lines that - // do fit but end in "..." as if they were trimmed. - self.computed_right - 6 - } else { - self.computed_right - }; + let right = + if self.computed_right == self.span_right || self.computed_right == self.label_right { + // Account for the "..." padding given above. Otherwise we end up with code lines that + // do fit but end in "..." as if they were trimmed. + self.computed_right - 6 + } else { + self.computed_right + }; right < line_len && self.computed_left + self.column_width < line_len } @@ -156,7 +161,8 @@ impl Margin { let padding_left = (self.column_width - (self.span_right - self.span_left)) / 5 * 2; self.computed_left = self.span_left.saturating_sub(padding_left); self.computed_right = self.computed_left + self.column_width; - } else { // Mostly give up but still don't show the full line. + } else { + // Mostly give up but still don't show the full line. self.computed_left = self.span_left; self.computed_right = self.span_right; } @@ -240,11 +246,15 @@ pub trait Emitter { format!( "help: {}{}: `{}`", sugg.msg, - if self.source_map().map(|sm| is_case_difference( - &**sm, - substitution, - sugg.substitutions[0].parts[0].span, - )).unwrap_or(false) { + if self + .source_map() + .map(|sm| is_case_difference( + &**sm, + substitution, + sugg.substitutions[0].parts[0].span, + )) + .unwrap_or(false) + { " (notice the capitalization)" } else { "" @@ -271,37 +281,35 @@ pub trait Emitter { // This does a small "fix" for multispans by looking to see if it can find any that // point directly at <*macros>. Since these are often difficult to read, this // will change the span to point at the use site. - fn fix_multispans_in_std_macros(&self, - source_map: &Option>, - span: &mut MultiSpan, - children: &mut Vec, - level: &Level, - backtrace: bool) { + fn fix_multispans_in_std_macros( + &self, + source_map: &Option>, + span: &mut MultiSpan, + children: &mut Vec, + level: &Level, + backtrace: bool, + ) { let mut spans_updated = self.fix_multispan_in_std_macros(source_map, span, backtrace); for child in children.iter_mut() { - spans_updated |= self.fix_multispan_in_std_macros( - source_map, - &mut child.span, - backtrace - ); + spans_updated |= + self.fix_multispan_in_std_macros(source_map, &mut child.span, backtrace); } let msg = if level == &Error { "this error originates in a macro outside of the current crate \ (in Nightly builds, run with -Z external-macro-backtrace \ - for more info)".to_string() + for more info)" + .to_string() } else { "this warning originates in a macro outside of the current crate \ (in Nightly builds, run with -Z external-macro-backtrace \ - for more info)".to_string() + for more info)" + .to_string() }; if spans_updated { children.push(SubDiagnostic { level: Level::Note, - message: vec![ - (msg, - Style::NoStyle), - ], + message: vec![(msg, Style::NoStyle)], span: MultiSpan::new(), render_span: None, }); @@ -311,10 +319,12 @@ pub trait Emitter { // This "fixes" MultiSpans that contain Spans that are pointing to locations inside of // <*macros>. Since these locations are often difficult to read, we move these Spans from // <*macros> to their corresponding use site. - fn fix_multispan_in_std_macros(&self, - source_map: &Option>, - span: &mut MultiSpan, - always_backtrace: bool) -> bool { + fn fix_multispan_in_std_macros( + &self, + source_map: &Option>, + span: &mut MultiSpan, + always_backtrace: bool, + ) -> bool { let sm = match source_map { Some(ref sm) => sm, None => return false, @@ -340,31 +350,40 @@ pub trait Emitter { continue; } if always_backtrace { - new_labels.push((trace.def_site_span, - format!("in this expansion of `{}`{}", - trace.macro_decl_name, - if backtrace_len > 2 { - // if backtrace_len == 1 it'll be pointed - // at by "in this macro invocation" - format!(" (#{})", i + 1) - } else { - String::new() - }))); + new_labels.push(( + trace.def_site_span, + format!( + "in this expansion of `{}`{}", + trace.macro_decl_name, + if backtrace_len > 2 { + // if backtrace_len == 1 it'll be pointed + // at by "in this macro invocation" + format!(" (#{})", i + 1) + } else { + String::new() + } + ), + )); } // Check to make sure we're not in any <*macros> - if !sm.span_to_filename(trace.def_site_span).is_macros() && - !trace.macro_decl_name.starts_with("desugaring of ") && - !trace.macro_decl_name.starts_with("#[") || - always_backtrace { - new_labels.push((trace.call_site, - format!("in this macro invocation{}", - if backtrace_len > 2 && always_backtrace { - // only specify order when the macro - // backtrace is multiple levels deep - format!(" (#{})", i + 1) - } else { - String::new() - }))); + if !sm.span_to_filename(trace.def_site_span).is_macros() + && !trace.macro_decl_name.starts_with("desugaring of ") + && !trace.macro_decl_name.starts_with("#[") + || always_backtrace + { + new_labels.push(( + trace.call_site, + format!( + "in this macro invocation{}", + if backtrace_len > 2 && always_backtrace { + // only specify order when the macro + // backtrace is multiple levels deep + format!(" (#{})", i + 1) + } else { + String::new() + } + ), + )); if !always_backtrace { break; } @@ -378,9 +397,7 @@ pub trait Emitter { if sp_label.span.is_dummy() { continue; } - if sm.span_to_filename(sp_label.span.clone()).is_macros() && - !always_backtrace - { + if sm.span_to_filename(sp_label.span.clone()).is_macros() && !always_backtrace { let v = sp_label.span.macro_backtrace(); if let Some(use_site) = v.last() { before_after.push((sp_label.span.clone(), use_site.call_site.clone())); @@ -406,18 +423,22 @@ impl Emitter for EmitterWriter { let mut children = diag.children.clone(); let (mut primary_span, suggestions) = self.primary_span_formatted(&diag); - self.fix_multispans_in_std_macros(&self.sm, - &mut primary_span, - &mut children, - &diag.level, - self.external_macro_backtrace); - - self.emit_messages_default(&diag.level, - &diag.styled_message(), - &diag.code, - &primary_span, - &children, - &suggestions); + self.fix_multispans_in_std_macros( + &self.sm, + &mut primary_span, + &mut children, + &diag.level, + self.external_macro_backtrace, + ); + + self.emit_messages_default( + &diag.level, + &diag.styled_message(), + &diag.code, + &primary_span, + &children, + &suggestions, + ); } fn should_show_explain(&self) -> bool { @@ -429,7 +450,9 @@ impl Emitter for EmitterWriter { pub struct SilentEmitter; impl Emitter for SilentEmitter { - fn source_map(&self) -> Option<&Lrc> { None } + fn source_map(&self) -> Option<&Lrc> { + None + } fn emit_diagnostic(&mut self, _: &Diagnostic) {} } @@ -458,17 +481,13 @@ impl ColorConfig { } } ColorConfig::Never => ColorChoice::Never, - ColorConfig::Auto if atty::is(atty::Stream::Stderr) => { - ColorChoice::Auto - } + ColorConfig::Auto if atty::is(atty::Stream::Stderr) => ColorChoice::Auto, ColorConfig::Auto => ColorChoice::Never, } } fn suggests_using_colors(self) -> bool { match self { - | ColorConfig::Always - | ColorConfig::Auto - => true, + ColorConfig::Always | ColorConfig::Auto => true, ColorConfig::Never => false, } } @@ -540,11 +559,7 @@ impl EmitterWriter { } fn maybe_anonymized(&self, line_num: usize) -> String { - if self.ui_testing { - ANONYMIZED_LINE_NUM.to_string() - } else { - line_num.to_string() - } + if self.ui_testing { ANONYMIZED_LINE_NUM.to_string() } else { line_num.to_string() } } fn draw_line( @@ -563,17 +578,21 @@ impl EmitterWriter { let right = margin.right(line_len); // On long lines, we strip the source line, accounting for unicode. let mut taken = 0; - let code: String = source_string.chars().skip(left).take_while(|ch| { - // Make sure that the trimming on the right will fall within the terminal width. - // FIXME: `unicode_width` sometimes disagrees with terminals on how wide a `char` is. - // For now, just accept that sometimes the code line will be longer than desired. - let next = unicode_width::UnicodeWidthChar::width(*ch).unwrap_or(1); - if taken + next > right - left { - return false; - } - taken += next; - true - }).collect(); + let code: String = source_string + .chars() + .skip(left) + .take_while(|ch| { + // Make sure that the trimming on the right will fall within the terminal width. + // FIXME: `unicode_width` sometimes disagrees with terminals on how wide a `char` is. + // For now, just accept that sometimes the code line will be longer than desired. + let next = unicode_width::UnicodeWidthChar::width(*ch).unwrap_or(1); + if taken + next > right - left { + return false; + } + taken += next; + true + }) + .collect(); buffer.puts(line_offset, code_offset, &code, Style::Quotation); if margin.was_cut_left() { // We have stripped some code/whitespace from the beginning, make it clear. @@ -624,7 +643,9 @@ impl EmitterWriter { let left = margin.left(source_string.len()); // Left trim // Account for unicode characters of width !=0 that were removed. - let left = source_string.chars().take(left) + let left = source_string + .chars() + .take(left) .map(|ch| unicode_width::UnicodeWidthChar::width(ch).unwrap_or(1)) .sum(); @@ -773,13 +794,14 @@ impl EmitterWriter { if overlaps(next, annotation, 0) // This label overlaps with another one and both && annotation.has_label() // take space (they have text and are not && j > i // multiline lines). - && p == 0 // We're currently on the first line, move the label one line down + && p == 0 + // We're currently on the first line, move the label one line down { // If we're overlapping with an un-labelled annotation with the same span // we can just merge them in the output if next.start_col == annotation.start_col - && next.end_col == annotation.end_col - && !next.has_label() + && next.end_col == annotation.end_col + && !next.has_label() { continue; } @@ -791,7 +813,7 @@ impl EmitterWriter { } annotations_position.push((p, annotation)); for (j, next) in annotations.iter().enumerate() { - if j > i { + if j > i { let l = next.label.as_ref().map_or(0, |label| label.len() + 2); if (overlaps(next, annotation, l) // Do not allow two labels to be in the same // line if they overlap including padding, to @@ -814,7 +836,8 @@ impl EmitterWriter { || (overlaps(next, annotation, l) && next.end_col <= annotation.end_col && next.has_label() - && p == 0) // Avoid #42595. + && p == 0) + // Avoid #42595. { // This annotation needs a new line in the output. p += 1; @@ -848,10 +871,7 @@ impl EmitterWriter { // | for pos in 0..=line_len { draw_col_separator(buffer, line_offset + pos + 1, width_offset - 2); - buffer.putc(line_offset + pos + 1, - width_offset - 2, - '|', - Style::LineNumber); + buffer.putc(line_offset + pos + 1, width_offset - 2, '|', Style::LineNumber); } // Write the horizontal lines for multiline annotations @@ -874,8 +894,7 @@ impl EmitterWriter { }; let pos = pos + 1; match annotation.annotation_type { - AnnotationType::MultilineStart(depth) | - AnnotationType::MultilineEnd(depth) => { + AnnotationType::MultilineStart(depth) | AnnotationType::MultilineEnd(depth) => { draw_range( buffer, '_', @@ -919,27 +938,23 @@ impl EmitterWriter { if pos > 1 && (annotation.has_label() || annotation.takes_space()) { for p in line_offset + 1..=line_offset + pos { - buffer.putc(p, - (code_offset + annotation.start_col).saturating_sub(left), - '|', - style); + buffer.putc( + p, + (code_offset + annotation.start_col).saturating_sub(left), + '|', + style, + ); } } match annotation.annotation_type { AnnotationType::MultilineStart(depth) => { for p in line_offset + pos + 1..line_offset + line_len + 2 { - buffer.putc(p, - width_offset + depth - 1, - '|', - style); + buffer.putc(p, width_offset + depth - 1, '|', style); } } AnnotationType::MultilineEnd(depth) => { for p in line_offset..=line_offset + pos { - buffer.putc(p, - width_offset + depth - 1, - '|', - style); + buffer.putc(p, width_offset + depth - 1, '|', style); } } _ => (), @@ -958,11 +973,8 @@ impl EmitterWriter { // 4 | } // | _ test for &(pos, annotation) in &annotations_position { - let style = if annotation.is_primary { - Style::LabelPrimary - } else { - Style::LabelSecondary - }; + let style = + if annotation.is_primary { Style::LabelPrimary } else { Style::LabelSecondary }; let (pos, col) = if pos == 0 { (pos + 1, (annotation.end_col + 1).saturating_sub(left)) } else { @@ -1012,8 +1024,9 @@ impl EmitterWriter { ); } } - annotations_position.iter().filter_map(|&(_, annotation)| { - match annotation.annotation_type { + annotations_position + .iter() + .filter_map(|&(_, annotation)| match annotation.annotation_type { AnnotationType::MultilineStart(p) | AnnotationType::MultilineEnd(p) => { let style = if annotation.is_primary { Style::LabelPrimary @@ -1022,10 +1035,9 @@ impl EmitterWriter { }; Some((p, style)) } - _ => None - } - - }).collect::>() + _ => None, + }) + .collect::>() } fn get_multispan_max_line_num(&mut self, msp: &MultiSpan) -> usize { @@ -1055,7 +1067,8 @@ impl EmitterWriter { fn get_max_line_num(&mut self, span: &MultiSpan, children: &[SubDiagnostic]) -> usize { let primary = self.get_multispan_max_line_num(span); - children.iter() + children + .iter() .map(|sub| self.get_multispan_max_line_num(&sub.span)) .max() .unwrap_or(0) @@ -1064,13 +1077,14 @@ impl EmitterWriter { /// Adds a left margin to every line but the first, given a padding length and the label being /// displayed, keeping the provided highlighting. - fn msg_to_buffer(&self, - buffer: &mut StyledBuffer, - msg: &[(String, Style)], - padding: usize, - label: &str, - override_style: Option