diff options
1100 files changed, 14474 insertions, 9969 deletions
diff --git a/.editorconfig b/.editorconfig index d065fa46469..eadd72e4993 100644 --- a/.editorconfig +++ b/.editorconfig @@ -11,6 +11,8 @@ trim_trailing_whitespace = true insert_final_newline = true indent_style = space indent_size = 4 + +[*.rs] max_line_length = 100 [*.md] diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs index 19078c1b842..8040cb22855 100644 --- a/.git-blame-ignore-revs +++ b/.git-blame-ignore-revs @@ -16,3 +16,5 @@ cf2dff2b1e3fa55fa5415d524200070d0d7aacfe b39a1d6f1a30ba29f25d7141038b9a5bf0126e36 # reorder fluent message files f97fddab91fbf290ea5b691fe355d6f915220b6e +# format let-else +cc907f80b95c6ec530c5ee1b05b044a468f07eca diff --git a/.mailmap b/.mailmap index 92be3174750..d526b43e4eb 100644 --- a/.mailmap +++ b/.mailmap @@ -299,10 +299,14 @@ Joseph T. Lyons <JosephTLyons@gmail.com> <JosephTLyons@users.noreply.github.com> Josh Cotton <jcotton42@outlook.com> Josh Driver <keeperofdakeys@gmail.com> Josh Holmer <jholmer.in@gmail.com> -Joshua Nelson <jyn514@gmail.com> <joshua@yottadb.com> Julian Knodt <julianknodt@gmail.com> jumbatm <jumbatm@gmail.com> <30644300+jumbatm@users.noreply.github.com> Junyoung Cho <june0.cho@samsung.com> +Jynn Nelson <github@jyn.dev> <jyn514@gmail.com> +Jynn Nelson <github@jyn.dev> <joshua@yottadb.com> +Jynn Nelson <github@jyn.dev> <jyn.nelson@redjack.com> +Jynn Nelson <github@jyn.dev> <jnelson@cloudflare.com> +Jynn Nelson <github@jyn.dev> Jyun-Yan You <jyyou.tw@gmail.com> <jyyou@cs.nctu.edu.tw> Kalita Alexey <kalita.alexey@outlook.com> Kampfkarren <boynedmaster@gmail.com> diff --git a/Cargo.lock b/Cargo.lock index a1bbc1dca76..2390850b567 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1529,9 +1529,9 @@ dependencies = [ [[package]] name = "hermit-abi" -version = "0.3.1" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fed44880c466736ef9a5c5b5facefb5ed0785676d0c02d612db14e54f0d84286" +checksum = "443144c8cdadd93ebf52ddb4056d257f5b52c04d3c804e657d19eb73fc33668b" dependencies = [ "compiler_builtins", "rustc-std-workspace-alloc", @@ -1864,7 +1864,7 @@ version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eae7b9aee968036d54dce06cebaefd919e4472e753296daccd6d344e3e2df0c2" dependencies = [ - "hermit-abi 0.3.1", + "hermit-abi 0.3.2", "libc", "windows-sys 0.48.0", ] @@ -1881,7 +1881,7 @@ version = "0.4.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24fddda5af7e54bf7da53067d6e802dbcc381d0a8eef629df528e3ebf68755cb" dependencies = [ - "hermit-abi 0.3.1", + "hermit-abi 0.3.2", "rustix 0.38.2", "windows-sys 0.48.0", ] @@ -2396,7 +2396,7 @@ version = "1.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4161fcb6d602d4d2081af7c3a45852d875a03dd337a6bfdd6e06407b61342a43" dependencies = [ - "hermit-abi 0.3.1", + "hermit-abi 0.3.2", "libc", ] @@ -3665,6 +3665,7 @@ name = "rustc_hir_typeck" version = "0.1.0" dependencies = [ "rustc_ast", + "rustc_attr", "rustc_data_structures", "rustc_errors", "rustc_fluent_macro", @@ -4233,6 +4234,7 @@ dependencies = [ "rustc_hir", "rustc_middle", "rustc_span", + "rustc_target", "scoped-tls", "tracing", ] @@ -4818,7 +4820,7 @@ dependencies = [ "dlmalloc", "fortanix-sgx-abi", "hashbrown 0.14.0", - "hermit-abi 0.3.1", + "hermit-abi 0.3.2", "libc", "miniz_oxide", "object", diff --git a/RELEASES.md b/RELEASES.md index 419c20b9071..3205b02e5c4 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -203,7 +203,7 @@ Stabilized APIs - [`Default for std::collections::binary_heap::IntoIter`](https://doc.rust-lang.org/stable/std/collections/binary_heap/struct.IntoIter.html) - [`Default for std::collections::btree_map::{IntoIter, Iter, IterMut}`](https://doc.rust-lang.org/stable/std/collections/btree_map/struct.IntoIter.html) - [`Default for std::collections::btree_map::{IntoKeys, Keys}`](https://doc.rust-lang.org/stable/std/collections/btree_map/struct.IntoKeys.html) -- [`Default for std::collections::btree_map::{IntoValues, Values}`](https://doc.rust-lang.org/stable/std/collections/btree_map/struct.IntoKeys.html) +- [`Default for std::collections::btree_map::{IntoValues, Values}`](https://doc.rust-lang.org/stable/std/collections/btree_map/struct.IntoValues.html) - [`Default for std::collections::btree_map::Range`](https://doc.rust-lang.org/stable/std/collections/btree_map/struct.Range.html) - [`Default for std::collections::btree_set::{IntoIter, Iter}`](https://doc.rust-lang.org/stable/std/collections/btree_set/struct.IntoIter.html) - [`Default for std::collections::btree_set::Range`](https://doc.rust-lang.org/stable/std/collections/btree_set/struct.Range.html) @@ -2618,7 +2618,7 @@ related tools. [`OsStr::to_ascii_lowercase`]: https://doc.rust-lang.org/std/ffi/struct.OsStr.html#method.to_ascii_lowercase [`OsStr::to_ascii_uppercase`]: https://doc.rust-lang.org/std/ffi/struct.OsStr.html#method.to_ascii_uppercase [`Peekable::peek_mut`]: https://doc.rust-lang.org/std/iter/struct.Peekable.html#method.peek_mut -[`Rc::decrement_strong_count`]: https://doc.rust-lang.org/std/rc/struct.Rc.html#method.increment_strong_count +[`Rc::decrement_strong_count`]: https://doc.rust-lang.org/std/rc/struct.Rc.html#method.decrement_strong_count [`Rc::increment_strong_count`]: https://doc.rust-lang.org/std/rc/struct.Rc.html#method.increment_strong_count [`Vec::extend_from_within`]: https://doc.rust-lang.org/beta/std/vec/struct.Vec.html#method.extend_from_within [`array::from_mut`]: https://doc.rust-lang.org/beta/std/array/fn.from_mut.html @@ -2627,7 +2627,7 @@ related tools. [`cmp::max_by`]: https://doc.rust-lang.org/beta/std/cmp/fn.max_by.html [`cmp::min_by_key`]: https://doc.rust-lang.org/beta/std/cmp/fn.min_by_key.html [`cmp::min_by`]: https://doc.rust-lang.org/beta/std/cmp/fn.min_by.html -[`f32::is_subnormal`]: https://doc.rust-lang.org/std/primitive.f64.html#method.is_subnormal +[`f32::is_subnormal`]: https://doc.rust-lang.org/std/primitive.f32.html#method.is_subnormal [`f64::is_subnormal`]: https://doc.rust-lang.org/std/primitive.f64.html#method.is_subnormal [ietf6943]: https://datatracker.ietf.org/doc/html/rfc6943#section-3.1.1 @@ -2963,7 +2963,7 @@ Internal Only [`sync::OnceState`]: https://doc.rust-lang.org/stable/std/sync/struct.OnceState.html [`panic::panic_any`]: https://doc.rust-lang.org/stable/std/panic/fn.panic_any.html [`slice::strip_prefix`]: https://doc.rust-lang.org/stable/std/primitive.slice.html#method.strip_prefix -[`slice::strip_suffix`]: https://doc.rust-lang.org/stable/std/primitive.slice.html#method.strip_prefix +[`slice::strip_suffix`]: https://doc.rust-lang.org/stable/std/primitive.slice.html#method.strip_suffix [`Arc::increment_strong_count`]: https://doc.rust-lang.org/nightly/std/sync/struct.Arc.html#method.increment_strong_count [`Arc::decrement_strong_count`]: https://doc.rust-lang.org/nightly/std/sync/struct.Arc.html#method.decrement_strong_count [`slice::fill_with`]: https://doc.rust-lang.org/nightly/std/primitive.slice.html#method.fill_with @@ -8033,7 +8033,7 @@ Compatibility Notes [39379]: https://github.com/rust-lang/rust/pull/39379 [41105]: https://github.com/rust-lang/rust/issues/41105 [`<*const T>::wrapping_offset`]: https://doc.rust-lang.org/std/primitive.pointer.html#method.wrapping_offset -[`<*mut T>::wrapping_offset`]: https://doc.rust-lang.org/std/primitive.pointer.html#method.wrapping_offset +[`<*mut T>::wrapping_offset`]: https://doc.rust-lang.org/std/primitive.pointer.html#method.wrapping_offset-1 [`Duration::checked_add`]: https://doc.rust-lang.org/std/time/struct.Duration.html#method.checked_add [`Duration::checked_div`]: https://doc.rust-lang.org/std/time/struct.Duration.html#method.checked_div [`Duration::checked_mul`]: https://doc.rust-lang.org/std/time/struct.Duration.html#method.checked_mul @@ -9011,7 +9011,7 @@ Stabilized APIs * [`f64::to_radians`](https://doc.rust-lang.org/std/primitive.f64.html#method.to_radians) (in libcore - previously stabilized in libstd) * [`Iterator::sum`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.sum) -* [`Iterator::product`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.sum) +* [`Iterator::product`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.product) * [`Cell::get_mut`](https://doc.rust-lang.org/std/cell/struct.Cell.html#method.get_mut) * [`RefCell::get_mut`](https://doc.rust-lang.org/std/cell/struct.RefCell.html#method.get_mut) diff --git a/compiler/rustc_abi/src/layout.rs b/compiler/rustc_abi/src/layout.rs index f6875d895d3..aea88641f82 100644 --- a/compiler/rustc_abi/src/layout.rs +++ b/compiler/rustc_abi/src/layout.rs @@ -40,6 +40,8 @@ pub trait LayoutCalculator { largest_niche, align, size, + max_repr_align: None, + unadjusted_abi_align: align.abi, } } @@ -122,6 +124,8 @@ pub trait LayoutCalculator { largest_niche: None, align: dl.i8_align, size: Size::ZERO, + max_repr_align: None, + unadjusted_abi_align: dl.i8_align.abi, } } @@ -289,6 +293,9 @@ pub trait LayoutCalculator { } let mut align = dl.aggregate_align; + let mut max_repr_align = repr.align; + let mut unadjusted_abi_align = align.abi; + let mut variant_layouts = variants .iter_enumerated() .map(|(j, v)| { @@ -296,6 +303,8 @@ pub trait LayoutCalculator { st.variants = Variants::Single { index: j }; align = align.max(st.align); + max_repr_align = max_repr_align.max(st.max_repr_align); + unadjusted_abi_align = unadjusted_abi_align.max(st.unadjusted_abi_align); Some(st) }) @@ -422,6 +431,8 @@ pub trait LayoutCalculator { largest_niche, size, align, + max_repr_align, + unadjusted_abi_align, }; Some(TmpLayout { layout, variants: variant_layouts }) @@ -456,6 +467,9 @@ pub trait LayoutCalculator { let (min_ity, signed) = discr_range_of_repr(min, max); //Integer::repr_discr(tcx, ty, &repr, min, max); let mut align = dl.aggregate_align; + let mut max_repr_align = repr.align; + let mut unadjusted_abi_align = align.abi; + let mut size = Size::ZERO; // We're interested in the smallest alignment, so start large. @@ -498,6 +512,8 @@ pub trait LayoutCalculator { } size = cmp::max(size, st.size); align = align.max(st.align); + max_repr_align = max_repr_align.max(st.max_repr_align); + unadjusted_abi_align = unadjusted_abi_align.max(st.unadjusted_abi_align); Some(st) }) .collect::<Option<IndexVec<VariantIdx, _>>>()?; @@ -691,6 +707,8 @@ pub trait LayoutCalculator { abi, align, size, + max_repr_align, + unadjusted_abi_align, }; let tagged_layout = TmpLayout { layout: tagged_layout, variants: layout_variants }; @@ -730,10 +748,7 @@ pub trait LayoutCalculator { let dl = self.current_data_layout(); let dl = dl.borrow(); let mut align = if repr.pack.is_some() { dl.i8_align } else { dl.aggregate_align }; - - if let Some(repr_align) = repr.align { - align = align.max(AbiAndPrefAlign::new(repr_align)); - } + let mut max_repr_align = repr.align; // If all the non-ZST fields have the same ABI and union ABI optimizations aren't // disabled, we can use that common ABI for the union as a whole. @@ -751,6 +766,7 @@ pub trait LayoutCalculator { assert!(field.0.is_sized()); align = align.max(field.align()); + max_repr_align = max_repr_align.max(field.max_repr_align()); size = cmp::max(size, field.size()); if field.0.is_zst() { @@ -787,6 +803,14 @@ pub trait LayoutCalculator { if let Some(pack) = repr.pack { align = align.min(AbiAndPrefAlign::new(pack)); } + // The unadjusted ABI alignment does not include repr(align), but does include repr(pack). + // See documentation on `LayoutS::unadjusted_abi_align`. + let unadjusted_abi_align = align.abi; + if let Some(repr_align) = repr.align { + align = align.max(AbiAndPrefAlign::new(repr_align)); + } + // `align` must not be modified after this, or `unadjusted_abi_align` could be inaccurate. + let align = align; // If all non-ZST fields have the same ABI, we may forward that ABI // for the union as a whole, unless otherwise inhibited. @@ -809,6 +833,8 @@ pub trait LayoutCalculator { largest_niche: None, align, size: size.align_to(align.abi), + max_repr_align, + unadjusted_abi_align, }) } } @@ -829,6 +855,7 @@ fn univariant( ) -> Option<LayoutS> { let pack = repr.pack; let mut align = if pack.is_some() { dl.i8_align } else { dl.aggregate_align }; + let mut max_repr_align = repr.align; let mut inverse_memory_index: IndexVec<u32, FieldIdx> = fields.indices().collect(); let optimize = !repr.inhibit_struct_field_reordering_opt(); if optimize && fields.len() > 1 { @@ -997,6 +1024,7 @@ fn univariant( }; offset = offset.align_to(field_align.abi); align = align.max(field_align); + max_repr_align = max_repr_align.max(field.max_repr_align()); debug!("univariant offset: {:?} field: {:#?}", offset, field); offsets[i] = offset; @@ -1018,9 +1046,16 @@ fn univariant( offset = offset.checked_add(field.size(), dl)?; } + + // The unadjusted ABI alignment does not include repr(align), but does include repr(pack). + // See documentation on `LayoutS::unadjusted_abi_align`. + let unadjusted_abi_align = align.abi; if let Some(repr_align) = repr.align { align = align.max(AbiAndPrefAlign::new(repr_align)); } + // `align` must not be modified after this point, or `unadjusted_abi_align` could be inaccurate. + let align = align; + debug!("univariant min_size: {:?}", offset); let min_size = offset; // As stated above, inverse_memory_index holds field indices by increasing offset. @@ -1036,6 +1071,7 @@ fn univariant( inverse_memory_index.into_iter().map(FieldIdx::as_u32).collect() }; let size = min_size.align_to(align.abi); + let mut layout_of_single_non_zst_field = None; let mut abi = Abi::Aggregate { sized }; // Unpack newtype ABIs and find scalar pairs. if sized && size.bytes() > 0 { @@ -1045,6 +1081,8 @@ fn univariant( match (non_zst_fields.next(), non_zst_fields.next(), non_zst_fields.next()) { // We have exactly one non-ZST field. (Some((i, field)), None, None) => { + layout_of_single_non_zst_field = Some(field); + // Field fills the struct and it has a scalar or scalar pair ABI. if offsets[i].bytes() == 0 && align.abi == field.align().abi && size == field.size() { @@ -1102,6 +1140,19 @@ fn univariant( if fields.iter().any(|f| f.abi().is_uninhabited()) { abi = Abi::Uninhabited; } + + let unadjusted_abi_align = if repr.transparent() { + match layout_of_single_non_zst_field { + Some(l) => l.unadjusted_abi_align(), + None => { + // `repr(transparent)` with all ZST fields. + align.abi + } + } + } else { + unadjusted_abi_align + }; + Some(LayoutS { variants: Variants::Single { index: FIRST_VARIANT }, fields: FieldsShape::Arbitrary { offsets, memory_index }, @@ -1109,6 +1160,8 @@ fn univariant( largest_niche, align, size, + max_repr_align, + unadjusted_abi_align, }) } diff --git a/compiler/rustc_abi/src/lib.rs b/compiler/rustc_abi/src/lib.rs index e1b9987f578..ef0c763ac20 100644 --- a/compiler/rustc_abi/src/lib.rs +++ b/compiler/rustc_abi/src/lib.rs @@ -1531,6 +1531,16 @@ pub struct LayoutS { pub align: AbiAndPrefAlign, pub size: Size, + + /// The largest alignment explicitly requested with `repr(align)` on this type or any field. + /// Only used on i686-windows, where the argument passing ABI is different when alignment is + /// requested, even if the requested alignment is equal to the natural alignment. + pub max_repr_align: Option<Align>, + + /// The alignment the type would have, ignoring any `repr(align)` but including `repr(packed)`. + /// Only used on aarch64-linux, where the argument passing ABI ignores the requested alignment + /// in some cases. + pub unadjusted_abi_align: Align, } impl LayoutS { @@ -1545,6 +1555,8 @@ impl LayoutS { largest_niche, size, align, + max_repr_align: None, + unadjusted_abi_align: align.abi, } } } @@ -1554,7 +1566,16 @@ impl fmt::Debug for LayoutS { // This is how `Layout` used to print before it become // `Interned<LayoutS>`. We print it like this to avoid having to update // expected output in a lot of tests. - let LayoutS { size, align, abi, fields, largest_niche, variants } = self; + let LayoutS { + size, + align, + abi, + fields, + largest_niche, + variants, + max_repr_align, + unadjusted_abi_align, + } = self; f.debug_struct("Layout") .field("size", size) .field("align", align) @@ -1562,6 +1583,8 @@ impl fmt::Debug for LayoutS { .field("fields", fields) .field("largest_niche", largest_niche) .field("variants", variants) + .field("max_repr_align", max_repr_align) + .field("unadjusted_abi_align", unadjusted_abi_align) .finish() } } @@ -1602,6 +1625,14 @@ impl<'a> Layout<'a> { self.0.0.size } + pub fn max_repr_align(self) -> Option<Align> { + self.0.0.max_repr_align + } + + pub fn unadjusted_abi_align(self) -> Align { + self.0.0.unadjusted_abi_align + } + /// Whether the layout is from a type that implements [`std::marker::PointerLike`]. /// /// Currently, that means that the type is pointer-sized, pointer-aligned, diff --git a/compiler/rustc_ast/src/token.rs b/compiler/rustc_ast/src/token.rs index 6646fa9446f..303bdd3a307 100644 --- a/compiler/rustc_ast/src/token.rs +++ b/compiler/rustc_ast/src/token.rs @@ -11,7 +11,7 @@ use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; use rustc_data_structures::sync::Lrc; use rustc_macros::HashStable_Generic; use rustc_span::symbol::{kw, sym}; -#[cfg_attr(not(bootstrap), allow(hidden_glob_reexports))] +#[allow(hidden_glob_reexports)] use rustc_span::symbol::{Ident, Symbol}; use rustc_span::{self, edition::Edition, Span, DUMMY_SP}; use std::borrow::Cow; diff --git a/compiler/rustc_ast_lowering/src/asm.rs b/compiler/rustc_ast_lowering/src/asm.rs index d350498bc96..ab55c09465b 100644 --- a/compiler/rustc_ast_lowering/src/asm.rs +++ b/compiler/rustc_ast_lowering/src/asm.rs @@ -352,7 +352,8 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let idx2 = *o.get(); let (ref op2, op_sp2) = operands[idx2]; - let Some(asm::InlineAsmRegOrRegClass::Reg(reg2)) = op2.reg() else { + let Some(asm::InlineAsmRegOrRegClass::Reg(reg2)) = op2.reg() + else { unreachable!(); }; @@ -368,7 +369,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { assert!(!*late); let out_op_sp = if input { op_sp2 } else { op_sp }; Some(out_op_sp) - }, + } _ => None, }; @@ -377,7 +378,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { op_span2: op_sp2, reg1_name: reg.name(), reg2_name: reg2.name(), - in_out + in_out, }); } Entry::Vacant(v) => { diff --git a/compiler/rustc_ast_passes/src/ast_validation.rs b/compiler/rustc_ast_passes/src/ast_validation.rs index 096cea945b0..418e1df5857 100644 --- a/compiler/rustc_ast_passes/src/ast_validation.rs +++ b/compiler/rustc_ast_passes/src/ast_validation.rs @@ -1300,14 +1300,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> { }); } } - AssocItemKind::Type(box TyAlias { - generics, - where_clauses, - where_predicates_split, - bounds, - ty, - .. - }) => { + AssocItemKind::Type(box TyAlias { bounds, ty, .. }) => { if ty.is_none() { self.session.emit_err(errors::AssocTypeWithoutBody { span: item.span, @@ -1315,18 +1308,26 @@ impl<'a> Visitor<'a> for AstValidator<'a> { }); } self.check_type_no_bounds(bounds, "`impl`s"); - if ty.is_some() { - self.check_gat_where( - item.id, - generics.where_clause.predicates.split_at(*where_predicates_split).0, - *where_clauses, - ); - } } _ => {} } } + if let AssocItemKind::Type(box TyAlias { + generics, + where_clauses, + where_predicates_split, + ty: Some(_), + .. + }) = &item.kind + { + self.check_gat_where( + item.id, + generics.where_clause.predicates.split_at(*where_predicates_split).0, + *where_clauses, + ); + } + if ctxt == AssocCtxt::Trait || self.in_trait_impl { self.visibility_not_permitted(&item.vis, errors::VisibilityNotPermittedNote::TraitImpl); if let AssocItemKind::Fn(box Fn { sig, .. }) = &item.kind { diff --git a/compiler/rustc_attr/src/builtin.rs b/compiler/rustc_attr/src/builtin.rs index 372a58857f3..6cce3a56f08 100644 --- a/compiler/rustc_attr/src/builtin.rs +++ b/compiler/rustc_attr/src/builtin.rs @@ -1217,3 +1217,20 @@ pub fn parse_alignment(node: &ast::LitKind) -> Result<u32, &'static str> { Err("not an unsuffixed integer") } } + +/// Read the content of a `rustc_confusables` attribute, and return the list of candidate names. +pub fn parse_confusables(attr: &Attribute) -> Option<Vec<Symbol>> { + let meta = attr.meta()?; + let MetaItem { kind: MetaItemKind::List(ref metas), .. } = meta else { return None }; + + let mut candidates = Vec::new(); + + for meta in metas { + let NestedMetaItem::Lit(meta_lit) = meta else { + return None; + }; + candidates.push(meta_lit.symbol); + } + + return Some(candidates); +} diff --git a/compiler/rustc_borrowck/src/constraint_generation.rs b/compiler/rustc_borrowck/src/constraint_generation.rs index 743d117e00f..1f642099f08 100644 --- a/compiler/rustc_borrowck/src/constraint_generation.rs +++ b/compiler/rustc_borrowck/src/constraint_generation.rs @@ -7,8 +7,8 @@ use rustc_middle::mir::{ Body, Local, Location, Place, PlaceRef, ProjectionElem, Rvalue, SourceInfo, Statement, StatementKind, Terminator, TerminatorKind, UserTypeProjection, }; -use rustc_middle::ty::subst::SubstsRef; use rustc_middle::ty::visit::TypeVisitable; +use rustc_middle::ty::GenericArgsRef; use rustc_middle::ty::{self, RegionVid, Ty, TyCtxt}; use crate::{ @@ -49,11 +49,11 @@ struct ConstraintGeneration<'cg, 'tcx> { } impl<'cg, 'tcx> Visitor<'tcx> for ConstraintGeneration<'cg, 'tcx> { - /// We sometimes have `substs` within an rvalue, or within a + /// We sometimes have `args` within an rvalue, or within a /// call. Make them live at the location where they appear. - fn visit_substs(&mut self, substs: &SubstsRef<'tcx>, location: Location) { - self.add_regular_live_constraint(*substs, location); - self.super_substs(substs); + fn visit_args(&mut self, args: &GenericArgsRef<'tcx>, location: Location) { + self.add_regular_live_constraint(*args, location); + self.super_args(args); } /// We sometimes have `region` within an rvalue, or within a diff --git a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs index c8c8b72b389..278e450c6b5 100644 --- a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs @@ -363,21 +363,12 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { } } let hir = self.infcx.tcx.hir(); - if let Some(hir::Node::Item(hir::Item { - kind: hir::ItemKind::Fn(_, _, body_id), - .. - })) = hir.find(self.mir_hir_id()) - && let Some(hir::Node::Expr(expr)) = hir.find(body_id.hir_id) - { + if let Some(body_id) = hir.maybe_body_owned_by(self.mir_def_id()) { + let expr = hir.body(body_id).value; let place = &self.move_data.move_paths[mpi].place; - let span = place.as_local() - .map(|local| self.body.local_decls[local].source_info.span); - let mut finder = ExpressionFinder { - expr_span: move_span, - expr: None, - pat: None, - parent_pat: None, - }; + let span = place.as_local().map(|local| self.body.local_decls[local].source_info.span); + let mut finder = + ExpressionFinder { expr_span: move_span, expr: None, pat: None, parent_pat: None }; finder.visit_expr(expr); if let Some(span) = span && let Some(expr) = finder.expr { for (_, expr) in hir.parent_iter(expr.hir_id) { @@ -461,7 +452,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { } = move_spans { // We already suggest cloning for these cases in `explain_captures`. } else { - self.suggest_cloning(err, ty, move_span); + self.suggest_cloning(err, ty, expr, move_span); } } } @@ -702,11 +693,11 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { .iter() .copied() .find_map(find_fn_kind_from_did), - ty::Alias(ty::Opaque, ty::AliasTy { def_id, substs, .. }) => tcx + ty::Alias(ty::Opaque, ty::AliasTy { def_id, args, .. }) => tcx .explicit_item_bounds(def_id) - .subst_iter_copied(tcx, substs) + .arg_iter_copied(tcx, args) .find_map(|(clause, span)| find_fn_kind_from_did((clause, span))), - ty::Closure(_, substs) => match substs.as_closure().kind() { + ty::Closure(_, args) => match args.as_closure().kind() { ty::ClosureKind::Fn => Some(hir::Mutability::Not), ty::ClosureKind::FnMut => Some(hir::Mutability::Mut), _ => None, @@ -714,7 +705,9 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { _ => None, }; - let Some(borrow_level) = borrow_level else { return false; }; + let Some(borrow_level) = borrow_level else { + return false; + }; let sugg = move_sites .iter() .map(|move_site| { @@ -734,9 +727,21 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { true } - fn suggest_cloning(&self, err: &mut Diagnostic, ty: Ty<'tcx>, span: Span) { + fn suggest_cloning( + &self, + err: &mut Diagnostic, + ty: Ty<'tcx>, + expr: &hir::Expr<'_>, + span: Span, + ) { let tcx = self.infcx.tcx; // Try to find predicates on *generic params* that would allow copying `ty` + let suggestion = + if let Some(symbol) = tcx.hir().maybe_get_struct_pattern_shorthand_field(expr) { + format!(": {}.clone()", symbol) + } else { + ".clone()".to_owned() + }; if let Some(clone_trait_def) = tcx.lang_items().clone_trait() && self.infcx .type_implements_trait( @@ -749,7 +754,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { err.span_suggestion_verbose( span.shrink_to_hi(), "consider cloning the value if the performance cost is acceptable", - ".clone()", + suggestion, Applicability::MachineApplicable, ); } @@ -763,7 +768,9 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { .typeck_root_def_id(self.mir_def_id().to_def_id()) .as_local() .and_then(|def_id| tcx.hir().get_generics(def_id)) - else { return; }; + else { + return; + }; // Try to find predicates on *generic params* that would allow copying `ty` let ocx = ObligationCtxt::new(&self.infcx); let copy_did = tcx.require_lang_item(LangItem::Copy, Some(span)); @@ -1220,18 +1227,20 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { return; }; let inner_param_uses = find_all_local_uses::find(self.body, inner_param.local); - let Some((inner_call_loc, inner_call_term)) = inner_param_uses.into_iter().find_map(|loc| { - let Either::Right(term) = self.body.stmt_at(loc) else { - debug!("{:?} is a statement, so it can't be a call", loc); - return None; - }; - let TerminatorKind::Call { args, .. } = &term.kind else { - debug!("not a call: {:?}", term); - return None; - }; - debug!("checking call args for uses of inner_param: {:?}", args); - args.contains(&Operand::Move(inner_param)).then_some((loc, term)) - }) else { + let Some((inner_call_loc, inner_call_term)) = + inner_param_uses.into_iter().find_map(|loc| { + let Either::Right(term) = self.body.stmt_at(loc) else { + debug!("{:?} is a statement, so it can't be a call", loc); + return None; + }; + let TerminatorKind::Call { args, .. } = &term.kind else { + debug!("not a call: {:?}", term); + return None; + }; + debug!("checking call args for uses of inner_param: {:?}", args); + args.contains(&Operand::Move(inner_param)).then_some((loc, term)) + }) + else { debug!("no uses of inner_param found as a by-move call arg"); return; }; @@ -1442,21 +1451,24 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { } // Get closure's arguments - let ty::Closure(_, substs) = typeck_results.expr_ty(closure_expr).kind() else { /* hir::Closure can be a generator too */ return }; - let sig = substs.as_closure().sig(); + let ty::Closure(_, args) = typeck_results.expr_ty(closure_expr).kind() else { + /* hir::Closure can be a generator too */ + return; + }; + let sig = args.as_closure().sig(); let tupled_params = tcx.erase_late_bound_regions(sig.inputs().iter().next().unwrap().map_bound(|&b| b)); let ty::Tuple(params) = tupled_params.kind() else { return }; // Find the first argument with a matching type, get its name - let Some((_, this_name)) = params - .iter() - .zip(hir.body_param_names(closure.body)) - .find(|(param_ty, name)|{ + let Some((_, this_name)) = + params.iter().zip(hir.body_param_names(closure.body)).find(|(param_ty, name)| { // FIXME: also support deref for stuff like `Rc` arguments param_ty.peel_refs() == local_ty && name != &Ident::empty() }) - else { return }; + else { + return; + }; let spans; if let Some((_path_expr, qpath)) = finder.error_path @@ -2667,7 +2679,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { kind: TerminatorKind::Call { call_source: CallSource::OverloadedOperator, .. }, .. }), - Some((method_did, method_substs)), + Some((method_did, method_args)), ) = ( &self.body[loan.reserve_location.block].terminator, rustc_middle::util::find_self_call( @@ -2680,7 +2692,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { if tcx.is_diagnostic_item(sym::deref_method, method_did) { let deref_target = tcx.get_diagnostic_item(sym::deref_target).and_then(|deref_target| { - Instance::resolve(tcx, self.param_env, deref_target, method_substs) + Instance::resolve(tcx, self.param_env, deref_target, method_args) .transpose() }); if let Some(Ok(instance)) = deref_target { @@ -2847,11 +2859,11 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { if is_closure { None } else { - let ty = self.infcx.tcx.type_of(self.mir_def_id()).subst_identity(); + let ty = self.infcx.tcx.type_of(self.mir_def_id()).instantiate_identity(); match ty.kind() { ty::FnDef(_, _) | ty::FnPtr(_) => self.annotate_fn_sig( self.mir_def_id(), - self.infcx.tcx.fn_sig(self.mir_def_id()).subst_identity(), + self.infcx.tcx.fn_sig(self.mir_def_id()).instantiate_identity(), ), _ => None, } @@ -2893,13 +2905,15 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { ); // Check if our `target` was captured by a closure. if let Rvalue::Aggregate( - box AggregateKind::Closure(def_id, substs), + box AggregateKind::Closure(def_id, args), operands, ) = rvalue { let def_id = def_id.expect_local(); for operand in operands { - let (Operand::Copy(assigned_from) | Operand::Move(assigned_from)) = operand else { + let (Operand::Copy(assigned_from) | Operand::Move(assigned_from)) = + operand + else { continue; }; debug!( @@ -2908,7 +2922,9 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { ); // Find the local from the operand. - let Some(assigned_from_local) = assigned_from.local_or_deref_local() else { + let Some(assigned_from_local) = + assigned_from.local_or_deref_local() + else { continue; }; @@ -2920,7 +2936,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { // into a place then we should annotate the closure in // case it ends up being assigned into the return place. annotated_closure = - self.annotate_fn_sig(def_id, substs.as_closure().sig()); + self.annotate_fn_sig(def_id, args.as_closure().sig()); debug!( "annotate_argument_and_return_for_borrow: \ annotated_closure={:?} assigned_from_local={:?} \ @@ -2961,7 +2977,9 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { ); // Find the local from the rvalue. - let Some(assigned_from_local) = assigned_from.local_or_deref_local() else { continue }; + let Some(assigned_from_local) = assigned_from.local_or_deref_local() else { + continue; + }; debug!( "annotate_argument_and_return_for_borrow: \ assigned_from_local={:?}", @@ -3009,7 +3027,8 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { assigned_to, args ); for operand in args { - let (Operand::Copy(assigned_from) | Operand::Move(assigned_from)) = operand else { + let (Operand::Copy(assigned_from) | Operand::Move(assigned_from)) = operand + else { continue; }; debug!( diff --git a/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs b/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs index 225c38efb2c..c92f32071f4 100644 --- a/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs +++ b/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs @@ -168,17 +168,17 @@ impl<'tcx> BorrowExplanation<'tcx> { let local_decl = &body.local_decls[dropped_local]; let mut ty = local_decl.ty; if local_decl.source_info.span.desugaring_kind() == Some(DesugaringKind::ForLoop) { - if let ty::Adt(adt, substs) = local_decl.ty.kind() { + if let ty::Adt(adt, args) = local_decl.ty.kind() { if tcx.is_diagnostic_item(sym::Option, adt.did()) { // in for loop desugaring, only look at the `Some(..)` inner type - ty = substs.type_at(0); + ty = args.type_at(0); } } } let (dtor_desc, type_desc) = match ty.kind() { // If type is an ADT that implements Drop, then // simplify output by reporting just the ADT name. - ty::Adt(adt, _substs) if adt.has_dtor(tcx) && !adt.is_box() => { + ty::Adt(adt, _args) if adt.has_dtor(tcx) && !adt.is_box() => { ("`Drop` code", format!("type `{}`", tcx.def_path_str(adt.did()))) } diff --git a/compiler/rustc_borrowck/src/diagnostics/mod.rs b/compiler/rustc_borrowck/src/diagnostics/mod.rs index d292611e6a2..099e07e8841 100644 --- a/compiler/rustc_borrowck/src/diagnostics/mod.rs +++ b/compiler/rustc_borrowck/src/diagnostics/mod.rs @@ -732,18 +732,18 @@ impl<'tcx> BorrowedContentSource<'tcx> { fn from_call(func: Ty<'tcx>, tcx: TyCtxt<'tcx>) -> Option<Self> { match *func.kind() { - ty::FnDef(def_id, substs) => { + ty::FnDef(def_id, args) => { let trait_id = tcx.trait_of_item(def_id)?; let lang_items = tcx.lang_items(); if Some(trait_id) == lang_items.deref_trait() || Some(trait_id) == lang_items.deref_mut_trait() { - Some(BorrowedContentSource::OverloadedDeref(substs.type_at(0))) + Some(BorrowedContentSource::OverloadedDeref(args.type_at(0))) } else if Some(trait_id) == lang_items.index_trait() || Some(trait_id) == lang_items.index_mut_trait() { - Some(BorrowedContentSource::OverloadedIndex(substs.type_at(0))) + Some(BorrowedContentSource::OverloadedIndex(args.type_at(0))) } else { None } @@ -847,14 +847,12 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { kind: TerminatorKind::Call { fn_span, call_source, .. }, .. }) = &self.body[location.block].terminator { - let Some((method_did, method_substs)) = - rustc_middle::util::find_self_call( - self.infcx.tcx, - &self.body, - target_temp, - location.block, - ) - else { + let Some((method_did, method_args)) = rustc_middle::util::find_self_call( + self.infcx.tcx, + &self.body, + target_temp, + location.block, + ) else { return normal_ret; }; @@ -862,7 +860,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { self.infcx.tcx, self.param_env, method_did, - method_substs, + method_args, *fn_span, call_source.from_hir_call(), Some(self.infcx.tcx.fn_arg_names(method_did)[0]), @@ -1041,7 +1039,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { }); } } - CallKind::Normal { self_arg, desugaring, method_did, method_substs } => { + CallKind::Normal { self_arg, desugaring, method_did, method_args } => { let self_arg = self_arg.unwrap(); let tcx = self.infcx.tcx; if let Some((CallDesugaringKind::ForLoopIntoIter, _)) = desugaring { @@ -1108,20 +1106,20 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { // Erase and shadow everything that could be passed to the new infcx. let ty = moved_place.ty(self.body, tcx).ty; - if let ty::Adt(def, substs) = ty.kind() + if let ty::Adt(def, args) = ty.kind() && Some(def.did()) == tcx.lang_items().pin_type() - && let ty::Ref(_, _, hir::Mutability::Mut) = substs.type_at(0).kind() + && let ty::Ref(_, _, hir::Mutability::Mut) = args.type_at(0).kind() && let self_ty = self.infcx.instantiate_binder_with_fresh_vars( fn_call_span, LateBoundRegionConversionTime::FnCall, - tcx.fn_sig(method_did).subst(tcx, method_substs).input(0), + tcx.fn_sig(method_did).instantiate(tcx, method_args).input(0), ) && self.infcx.can_eq(self.param_env, ty, self_ty) { err.eager_subdiagnostic( &self.infcx.tcx.sess.parse_sess.span_diagnostic, CaptureReasonSuggest::FreshReborrow { - span: fn_call_span.shrink_to_lo(), + span: move_span.shrink_to_hi(), }); } if let Some(clone_trait) = tcx.lang_items().clone_trait() @@ -1135,10 +1133,10 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { && self.infcx.predicate_must_hold_modulo_regions(&o) { err.span_suggestion_verbose( - fn_call_span.shrink_to_lo(), + move_span.shrink_to_hi(), "you can `clone` the value and consume it, but this might not be \ your desired behavior", - "clone().".to_string(), + ".clone()".to_string(), Applicability::MaybeIncorrect, ); } @@ -1163,7 +1161,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { let parent_self_ty = matches!(tcx.def_kind(parent_did), rustc_hir::def::DefKind::Impl { .. }) .then_some(parent_did) - .and_then(|did| match tcx.type_of(did).subst_identity().kind() { + .and_then(|did| match tcx.type_of(did).instantiate_identity().kind() { ty::Adt(def, ..) => Some(def.did()), _ => None, }); diff --git a/compiler/rustc_borrowck/src/diagnostics/move_errors.rs b/compiler/rustc_borrowck/src/diagnostics/move_errors.rs index 8b77477a31a..e05c04e1188 100644 --- a/compiler/rustc_borrowck/src/diagnostics/move_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/move_errors.rs @@ -184,7 +184,9 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { } // Error with the pattern LookupResult::Exact(_) => { - let LookupResult::Parent(Some(mpi)) = self.move_data.rev_lookup.find(move_from.as_ref()) else { + let LookupResult::Parent(Some(mpi)) = + self.move_data.rev_lookup.find(move_from.as_ref()) + else { // move_from should be a projection from match_place. unreachable!("Probably not unreachable..."); }; @@ -322,10 +324,10 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { ty::Array(..) | ty::Slice(..) => { self.cannot_move_out_of_interior_noncopy(span, ty, None) } - ty::Closure(def_id, closure_substs) + ty::Closure(def_id, closure_args) if def_id.as_local() == Some(self.mir_def_id()) && upvar_field.is_some() => { - let closure_kind_ty = closure_substs.as_closure().kind_ty(); + let closure_kind_ty = closure_args.as_closure().kind_ty(); let closure_kind = match closure_kind_ty.to_opt_closure_kind() { Some(kind @ (ty::ClosureKind::Fn | ty::ClosureKind::FnMut)) => kind, Some(ty::ClosureKind::FnOnce) => { @@ -494,8 +496,10 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { if let LocalInfo::User(BindingForm::Var(VarBindingForm { pat_span, .. })) = *bind_to.local_info() { - let Ok(pat_snippet) = - self.infcx.tcx.sess.source_map().span_to_snippet(pat_span) else { continue; }; + let Ok(pat_snippet) = self.infcx.tcx.sess.source_map().span_to_snippet(pat_span) + else { + continue; + }; let Some(stripped) = pat_snippet.strip_prefix('&') else { suggestions.push(( bind_to.source_info.span.shrink_to_lo(), diff --git a/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs b/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs index 1f2fefadf65..3c32121a51a 100644 --- a/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs @@ -2,7 +2,6 @@ use rustc_errors::{Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed use rustc_hir as hir; use rustc_hir::intravisit::Visitor; use rustc_hir::Node; -use rustc_middle::hir::map::Map; use rustc_middle::mir::{Mutability, Place, PlaceRef, ProjectionElem}; use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_middle::{ @@ -646,10 +645,8 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { } let hir_map = self.infcx.tcx.hir(); let def_id = self.body.source.def_id(); - let hir_id = hir_map.local_def_id_to_hir_id(def_id.as_local().unwrap()); - let node = hir_map.find(hir_id); - let Some(hir::Node::Item(item)) = node else { return; }; - let hir::ItemKind::Fn(.., body_id) = item.kind else { return; }; + let Some(local_def_id) = def_id.as_local() else { return }; + let Some(body_id) = hir_map.maybe_body_owned_by(local_def_id) else { return }; let body = self.infcx.tcx.hir().body(body_id); let mut v = V { assign_span: span, err, ty, suggested: false }; @@ -786,23 +783,12 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { // In the future, attempt in all path but initially for RHS of for_loop fn suggest_similar_mut_method_for_for_loop(&self, err: &mut Diagnostic) { use hir::{ - BodyId, Expr, + Expr, ExprKind::{Block, Call, DropTemps, Match, MethodCall}, - HirId, ImplItem, ImplItemKind, Item, ItemKind, }; - fn maybe_body_id_of_fn(hir_map: Map<'_>, id: HirId) -> Option<BodyId> { - match hir_map.find(id) { - Some(Node::Item(Item { kind: ItemKind::Fn(_, _, body_id), .. })) - | Some(Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(_, body_id), .. })) => { - Some(*body_id) - } - _ => None, - } - } let hir_map = self.infcx.tcx.hir(); - let mir_body_hir_id = self.mir_hir_id(); - if let Some(fn_body_id) = maybe_body_id_of_fn(hir_map, mir_body_hir_id) { + if let Some(body_id) = hir_map.maybe_body_owned_by(self.mir_def_id()) { if let Block( hir::Block { expr: @@ -836,7 +822,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { .. }, _, - ) = hir_map.body(fn_body_id).value.kind + ) = hir_map.body(body_id).value.kind { let opt_suggestions = self .infcx @@ -1098,46 +1084,45 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { } let hir_map = self.infcx.tcx.hir(); let def_id = self.body.source.def_id(); - let hir_id = hir_map.local_def_id_to_hir_id(def_id.expect_local()); - let node = hir_map.find(hir_id); - let hir_id = if let Some(hir::Node::Item(item)) = node - && let hir::ItemKind::Fn(.., body_id) = item.kind - { - let body = hir_map.body(body_id); - let mut v = BindingFinder { - span: err_label_span, - hir_id: None, + let hir_id = if let Some(local_def_id) = def_id.as_local() && + let Some(body_id) = hir_map.maybe_body_owned_by(local_def_id) + { + let body = hir_map.body(body_id); + let mut v = BindingFinder { + span: err_label_span, + hir_id: None, + }; + v.visit_body(body); + v.hir_id + } else { + None }; - v.visit_body(body); - v.hir_id - } else { - None - }; + if let Some(hir_id) = hir_id && let Some(hir::Node::Local(local)) = hir_map.find(hir_id) - { - let (changing, span, sugg) = match local.ty { - Some(ty) => ("changing", ty.span, message), - None => ( - "specifying", - local.pat.span.shrink_to_hi(), - format!(": {message}"), - ), - }; - err.span_suggestion_verbose( - span, - format!("consider {changing} this binding's type"), - sugg, - Applicability::HasPlaceholders, - ); - } else { - err.span_label( - err_label_span, - format!( - "consider changing this binding's type to be: `{message}`" - ), - ); - } + { + let (changing, span, sugg) = match local.ty { + Some(ty) => ("changing", ty.span, message), + None => ( + "specifying", + local.pat.span.shrink_to_hi(), + format!(": {message}"), + ), + }; + err.span_suggestion_verbose( + span, + format!("consider {changing} this binding's type"), + sugg, + Applicability::HasPlaceholders, + ); + } else { + err.span_label( + err_label_span, + format!( + "consider changing this binding's type to be: `{message}`" + ), + ); + } } None => {} } diff --git a/compiler/rustc_borrowck/src/diagnostics/region_errors.rs b/compiler/rustc_borrowck/src/diagnostics/region_errors.rs index 617c85174cb..2ea399789b9 100644 --- a/compiler/rustc_borrowck/src/diagnostics/region_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/region_errors.rs @@ -22,7 +22,7 @@ use rustc_infer::infer::{ }; use rustc_middle::hir::place::PlaceBase; use rustc_middle::mir::{ConstraintCategory, ReturnConstraint}; -use rustc_middle::ty::subst::InternalSubsts; +use rustc_middle::ty::GenericArgs; use rustc_middle::ty::TypeVisitor; use rustc_middle::ty::{self, RegionVid, Ty}; use rustc_middle::ty::{Region, TyCtxt}; @@ -183,9 +183,9 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { fn is_closure_fn_mut(&self, fr: RegionVid) -> bool { if let Some(ty::ReFree(free_region)) = self.to_error_region(fr).as_deref() && let ty::BoundRegionKind::BrEnv = free_region.bound_region - && let DefiningTy::Closure(_, substs) = self.regioncx.universal_regions().defining_ty + && let DefiningTy::Closure(_, args) = self.regioncx.universal_regions().defining_ty { - return substs.as_closure().kind() == ty::ClosureKind::FnMut; + return args.as_closure().kind() == ty::ClosureKind::FnMut; } false @@ -224,12 +224,10 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { let mut hrtb_bounds = vec![]; gat_id_and_generics.iter().flatten().for_each(|(gat_hir_id, generics)| { for pred in generics.predicates { - let BoundPredicate( - WhereBoundPredicate { - bound_generic_params, - bounds, - .. - }) = pred else { continue; }; + let BoundPredicate(WhereBoundPredicate { bound_generic_params, bounds, .. }) = pred + else { + continue; + }; if bound_generic_params .iter() .rfind(|bgp| hir.local_def_id_to_hir_id(bgp.def_id) == *gat_hir_id) @@ -504,12 +502,12 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { .to_string(), ) } - ty::Adt(adt, substs) => { - let generic_arg = substs[param_index as usize]; - let identity_substs = - InternalSubsts::identity_for_item(self.infcx.tcx, adt.did()); - let base_ty = Ty::new_adt(self.infcx.tcx, *adt, identity_substs); - let base_generic_arg = identity_substs[param_index as usize]; + ty::Adt(adt, args) => { + let generic_arg = args[param_index as usize]; + let identity_args = + GenericArgs::identity_for_item(self.infcx.tcx, adt.did()); + let base_ty = Ty::new_adt(self.infcx.tcx, *adt, identity_args); + let base_generic_arg = identity_args[param_index as usize]; let adt_desc = adt.descr(); let desc = format!( @@ -522,12 +520,11 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { } ty::FnDef(def_id, _) => { let name = self.infcx.tcx.item_name(*def_id); - let identity_substs = - InternalSubsts::identity_for_item(self.infcx.tcx, *def_id); + let identity_args = GenericArgs::identity_for_item(self.infcx.tcx, *def_id); let desc = format!("a function pointer to `{name}`"); let note = format!( "the function `{name}` is invariant over the parameter `{}`", - identity_substs[param_index as usize] + identity_args[param_index as usize] ); (desc, note) } @@ -575,7 +572,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { let mut output_ty = self.regioncx.universal_regions().unnormalized_output_ty; if let ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }) = *output_ty.kind() { - output_ty = self.infcx.tcx.type_of(def_id).subst_identity() + output_ty = self.infcx.tcx.type_of(def_id).instantiate_identity() }; debug!("report_fnmut_error: output_ty={:?}", output_ty); @@ -813,7 +810,9 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { return; } let suitable_region = self.infcx.tcx.is_suitable_region(f); - let Some(suitable_region) = suitable_region else { return; }; + let Some(suitable_region) = suitable_region else { + return; + }; let fn_returns = self.infcx.tcx.return_type_impl_or_dyn_traits(suitable_region.def_id); @@ -848,7 +847,10 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { let Some((alias_tys, alias_span, lt_addition_span)) = self .infcx .tcx - .return_type_impl_or_dyn_traits_with_type_alias(suitable_region.def_id) else { return; }; + .return_type_impl_or_dyn_traits_with_type_alias(suitable_region.def_id) + else { + return; + }; // in case the return type of the method is a type alias let mut spans_suggs: Vec<_> = Vec::new(); @@ -896,14 +898,14 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { let tcx = self.infcx.tcx; let instance = if let ConstraintCategory::CallArgument(Some(func_ty)) = category { - let (fn_did, substs) = match func_ty.kind() { - ty::FnDef(fn_did, substs) => (fn_did, substs), + let (fn_did, args) = match func_ty.kind() { + ty::FnDef(fn_did, args) => (fn_did, args), _ => return, }; - debug!(?fn_did, ?substs); + debug!(?fn_did, ?args); // Only suggest this on function calls, not closures - let ty = tcx.type_of(fn_did).subst_identity(); + let ty = tcx.type_of(fn_did).instantiate_identity(); debug!("ty: {:?}, ty.kind: {:?}", ty, ty.kind()); if let ty::Closure(_, _) = ty.kind() { return; @@ -913,7 +915,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { tcx, self.param_env, *fn_did, - self.infcx.resolve_vars_if_possible(substs), + self.infcx.resolve_vars_if_possible(args), ) { instance } else { @@ -932,8 +934,13 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { let mut visitor = TraitObjectVisitor(FxIndexSet::default()); visitor.visit_ty(param.param_ty); - let Some((ident, self_ty)) = - NiceRegionError::get_impl_ident_and_self_ty_from_trait(tcx, instance.def_id(), &visitor.0) else { return; }; + let Some((ident, self_ty)) = NiceRegionError::get_impl_ident_and_self_ty_from_trait( + tcx, + instance.def_id(), + &visitor.0, + ) else { + return; + }; self.suggest_constrain_dyn_trait_in_impl(diag, &visitor.0, ident, self_ty); } @@ -981,23 +988,25 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { sup: RegionVid, ) { let (Some(sub), Some(sup)) = (self.to_error_region(sub), self.to_error_region(sup)) else { - return + return; }; let Some((ty_sub, _)) = self .infcx .tcx .is_suitable_region(sub) - .and_then(|anon_reg| find_anon_type(self.infcx.tcx, sub, &anon_reg.boundregion)) else { - return + .and_then(|anon_reg| find_anon_type(self.infcx.tcx, sub, &anon_reg.boundregion)) + else { + return; }; let Some((ty_sup, _)) = self .infcx .tcx .is_suitable_region(sup) - .and_then(|anon_reg| find_anon_type(self.infcx.tcx, sup, &anon_reg.boundregion)) else { - return + .and_then(|anon_reg| find_anon_type(self.infcx.tcx, sup, &anon_reg.boundregion)) + else { + return; }; suggest_adding_lifetime_params(self.infcx.tcx, sub, ty_sup, ty_sub, diag); diff --git a/compiler/rustc_borrowck/src/diagnostics/region_name.rs b/compiler/rustc_borrowck/src/diagnostics/region_name.rs index 074f37bed13..9cad8fa5318 100644 --- a/compiler/rustc_borrowck/src/diagnostics/region_name.rs +++ b/compiler/rustc_borrowck/src/diagnostics/region_name.rs @@ -5,8 +5,8 @@ use rustc_errors::Diagnostic; use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; use rustc_middle::ty::print::RegionHighlightMode; -use rustc_middle::ty::subst::{GenericArgKind, SubstsRef}; use rustc_middle::ty::{self, RegionVid, Ty}; +use rustc_middle::ty::{GenericArgKind, GenericArgsRef}; use rustc_span::symbol::{kw, sym, Ident, Symbol}; use rustc_span::{Span, DUMMY_SP}; @@ -321,18 +321,18 @@ impl<'tcx> MirBorrowckCtxt<'_, 'tcx> { ty::BoundRegionKind::BrEnv => { let def_ty = self.regioncx.universal_regions().defining_ty; - let DefiningTy::Closure(_, substs) = def_ty else { + let DefiningTy::Closure(_, args) = def_ty else { // Can't have BrEnv in functions, constants or generators. bug!("BrEnv outside of closure."); }; - let hir::ExprKind::Closure(&hir::Closure { fn_decl_span, .. }) - = tcx.hir().expect_expr(self.mir_hir_id()).kind + let hir::ExprKind::Closure(&hir::Closure { fn_decl_span, .. }) = + tcx.hir().expect_expr(self.mir_hir_id()).kind else { bug!("Closure is not defined by a closure expr"); }; let region_name = self.synthesize_region_name(); - let closure_kind_ty = substs.as_closure().kind_ty(); + let closure_kind_ty = args.as_closure().kind_ty(); let note = match closure_kind_ty.to_opt_closure_kind() { Some(ty::ClosureKind::Fn) => { "closure implements `Fn`, so references to captured variables \ @@ -510,10 +510,7 @@ impl<'tcx> MirBorrowckCtxt<'_, 'tcx> { } // Match up something like `Foo<'1>` - ( - ty::Adt(_adt_def, substs), - hir::TyKind::Path(hir::QPath::Resolved(None, path)), - ) => { + (ty::Adt(_adt_def, args), hir::TyKind::Path(hir::QPath::Resolved(None, path))) => { match path.res { // Type parameters of the type alias have no reason to // be the same as those of the ADT. @@ -523,7 +520,7 @@ impl<'tcx> MirBorrowckCtxt<'_, 'tcx> { _ => { if let Some(last_segment) = path.segments.last() { if let Some(highlight) = self.match_adt_and_segment( - substs, + args, needle_fr, last_segment, search_stack, @@ -560,22 +557,22 @@ impl<'tcx> MirBorrowckCtxt<'_, 'tcx> { None } - /// We've found an enum/struct/union type with the substitutions - /// `substs` and -- in the HIR -- a path type with the final + /// We've found an enum/struct/union type with the generic args + /// `args` and -- in the HIR -- a path type with the final /// segment `last_segment`. Try to find a `'_` to highlight in /// the generic args (or, if not, to produce new zipped pairs of /// types+hir to search through). fn match_adt_and_segment<'hir>( &self, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, needle_fr: RegionVid, last_segment: &'hir hir::PathSegment<'hir>, search_stack: &mut Vec<(Ty<'tcx>, &'hir hir::Ty<'hir>)>, ) -> Option<RegionNameHighlight> { // Did the user give explicit arguments? (e.g., `Foo<..>`) - let args = last_segment.args.as_ref()?; + let explicit_args = last_segment.args.as_ref()?; let lifetime = - self.try_match_adt_and_generic_args(substs, needle_fr, args, search_stack)?; + self.try_match_adt_and_generic_args(args, needle_fr, explicit_args, search_stack)?; if lifetime.is_anonymous() { None } else { @@ -583,19 +580,19 @@ impl<'tcx> MirBorrowckCtxt<'_, 'tcx> { } } - /// We've found an enum/struct/union type with the substitutions - /// `substs` and -- in the HIR -- a path with the generic - /// arguments `args`. If `needle_fr` appears in the args, return + /// We've found an enum/struct/union type with the generic args + /// `args` and -- in the HIR -- a path with the generic + /// arguments `hir_args`. If `needle_fr` appears in the args, return /// the `hir::Lifetime` that corresponds to it. If not, push onto /// `search_stack` the types+hir to search through. fn try_match_adt_and_generic_args<'hir>( &self, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, needle_fr: RegionVid, - args: &'hir hir::GenericArgs<'hir>, + hir_args: &'hir hir::GenericArgs<'hir>, search_stack: &mut Vec<(Ty<'tcx>, &'hir hir::Ty<'hir>)>, ) -> Option<&'hir hir::Lifetime> { - for (kind, hir_arg) in iter::zip(substs, args.args) { + for (kind, hir_arg) in iter::zip(args, hir_args.args) { match (kind.unpack(), hir_arg) { (GenericArgKind::Lifetime(r), hir::GenericArg::Lifetime(lt)) => { if r.as_var() == needle_fr { @@ -849,9 +846,10 @@ impl<'tcx> MirBorrowckCtxt<'_, 'tcx> { return None; }; - let found = tcx.any_free_region_meets(&tcx.type_of(region_parent).subst_identity(), |r| { - *r == ty::ReEarlyBound(region) - }); + let found = tcx + .any_free_region_meets(&tcx.type_of(region_parent).instantiate_identity(), |r| { + *r == ty::ReEarlyBound(region) + }); Some(RegionName { name: self.synthesize_region_name(), diff --git a/compiler/rustc_borrowck/src/lib.rs b/compiler/rustc_borrowck/src/lib.rs index 97d15cb53db..ea32506fc89 100644 --- a/compiler/rustc_borrowck/src/lib.rs +++ b/compiler/rustc_borrowck/src/lib.rs @@ -301,7 +301,7 @@ fn do_mir_borrowck<'tcx>( let movable_generator = // The first argument is the generator type passed by value if let Some(local) = body.local_decls.raw.get(1) - // Get the interior types and substs which typeck computed + // Get the interior types and args which typeck computed && let ty::Generator(_, _, hir::Movability::Static) = local.ty.kind() { false diff --git a/compiler/rustc_borrowck/src/region_infer/mod.rs b/compiler/rustc_borrowck/src/region_infer/mod.rs index e45d3a2c882..fbbccc58ad6 100644 --- a/compiler/rustc_borrowck/src/region_infer/mod.rs +++ b/compiler/rustc_borrowck/src/region_infer/mod.rs @@ -1115,7 +1115,7 @@ impl<'tcx> RegionInferenceContext<'tcx> { ) -> Option<ClosureOutlivesSubject<'tcx>> { let tcx = infcx.tcx; - // Opaque types' substs may include useless lifetimes. + // Opaque types' args may include useless lifetimes. // We will replace them with ReStatic. struct OpaqueFolder<'tcx> { tcx: TyCtxt<'tcx>, @@ -1127,19 +1127,18 @@ impl<'tcx> RegionInferenceContext<'tcx> { fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> { use ty::TypeSuperFoldable as _; let tcx = self.tcx; - let &ty::Alias(ty::Opaque, ty::AliasTy { substs, def_id, .. }) = t.kind() else { + let &ty::Alias(ty::Opaque, ty::AliasTy { args, def_id, .. }) = t.kind() else { return t.super_fold_with(self); }; - let substs = - std::iter::zip(substs, tcx.variances_of(def_id)).map(|(arg, v)| { - match (arg.unpack(), v) { - (ty::GenericArgKind::Lifetime(_), ty::Bivariant) => { - tcx.lifetimes.re_static.into() - } - _ => arg.fold_with(self), + let args = std::iter::zip(args, tcx.variances_of(def_id)).map(|(arg, v)| { + match (arg.unpack(), v) { + (ty::GenericArgKind::Lifetime(_), ty::Bivariant) => { + tcx.lifetimes.re_static.into() } - }); - Ty::new_opaque(tcx, def_id, tcx.mk_substs_from_iter(substs)) + _ => arg.fold_with(self), + } + }); + Ty::new_opaque(tcx, def_id, tcx.mk_args_from_iter(args)) } } @@ -2058,10 +2057,17 @@ impl<'tcx> RegionInferenceContext<'tcx> { let mut extra_info = vec![]; for constraint in path.iter() { let outlived = constraint.sub; - let Some(origin) = self.var_infos.get(outlived) else { continue; }; - let RegionVariableOrigin::Nll(NllRegionVariableOrigin::Placeholder(p)) = origin.origin else { continue; }; + let Some(origin) = self.var_infos.get(outlived) else { + continue; + }; + let RegionVariableOrigin::Nll(NllRegionVariableOrigin::Placeholder(p)) = origin.origin + else { + continue; + }; debug!(?constraint, ?p); - let ConstraintCategory::Predicate(span) = constraint.category else { continue; }; + let ConstraintCategory::Predicate(span) = constraint.category else { + continue; + }; extra_info.push(ExtraConstraintInfo::PlaceholderFromPredicate(span)); // We only want to point to one break; diff --git a/compiler/rustc_borrowck/src/region_infer/opaque_types.rs b/compiler/rustc_borrowck/src/region_infer/opaque_types.rs index 1a227f2d110..d8e81827a3b 100644 --- a/compiler/rustc_borrowck/src/region_infer/opaque_types.rs +++ b/compiler/rustc_borrowck/src/region_infer/opaque_types.rs @@ -6,9 +6,9 @@ use rustc_infer::infer::InferCtxt; use rustc_infer::infer::TyCtxtInferExt as _; use rustc_infer::traits::{Obligation, ObligationCause}; use rustc_middle::traits::DefiningAnchor; -use rustc_middle::ty::subst::{GenericArgKind, InternalSubsts}; use rustc_middle::ty::visit::TypeVisitableExt; use rustc_middle::ty::{self, OpaqueHiddenType, OpaqueTypeKey, Ty, TyCtxt, TypeFoldable}; +use rustc_middle::ty::{GenericArgKind, GenericArgs}; use rustc_span::Span; use rustc_trait_selection::traits::error_reporting::TypeErrCtxtExt as _; use rustc_trait_selection::traits::ObligationCtxt; @@ -38,15 +38,15 @@ impl<'tcx> RegionInferenceContext<'tcx> { /// back to concrete lifetimes: `'static`, `ReEarlyBound` or `ReFree`. /// /// First we map all the lifetimes in the concrete type to an equal - /// universal region that occurs in the concrete type's substs, in this case - /// this would result in `&'1 i32`. We only consider regions in the substs + /// universal region that occurs in the concrete type's args, in this case + /// this would result in `&'1 i32`. We only consider regions in the args /// in case there is an equal region that does not. For example, this should /// be allowed: /// `fn f<'a: 'b, 'b: 'a>(x: *mut &'b i32) -> impl Sized + 'a { x }` /// /// Then we map the regions in both the type and the subst to their /// `external_name` giving `concrete_type = &'a i32`, - /// `substs = ['static, 'a]`. This will then allow + /// `args = ['static, 'a]`. This will then allow /// `infer_opaque_definition_from_instantiation` to determine that /// `_Return<'_a> = &'_a i32`. /// @@ -73,8 +73,8 @@ impl<'tcx> RegionInferenceContext<'tcx> { debug!(?member_constraints); for (opaque_type_key, concrete_type) in opaque_ty_decls { - let substs = opaque_type_key.substs; - debug!(?concrete_type, ?substs); + let args = opaque_type_key.args; + debug!(?concrete_type, ?args); let mut subst_regions = vec![self.universal_regions.fr_static]; @@ -95,7 +95,7 @@ impl<'tcx> RegionInferenceContext<'tcx> { ty::Region::new_error_with_message( infcx.tcx, concrete_type.span, - "opaque type with non-universal region substs", + "opaque type with non-universal region args", ) } } @@ -110,17 +110,17 @@ impl<'tcx> RegionInferenceContext<'tcx> { } debug!(?subst_regions); - // Next, insert universal regions from substs, so we can translate regions that appear - // in them but are not subject to member constraints, for instance closure substs. - let universal_substs = infcx.tcx.fold_regions(substs, |region, _| { + // Next, insert universal regions from args, so we can translate regions that appear + // in them but are not subject to member constraints, for instance closure args. + let universal_args = infcx.tcx.fold_regions(args, |region, _| { if let ty::RePlaceholder(..) = region.kind() { - // Higher kinded regions don't need remapping, they don't refer to anything outside of this the substs. + // Higher kinded regions don't need remapping, they don't refer to anything outside of this the args. return region; } let vid = self.to_region_vid(region); to_universal_region(vid, &mut subst_regions) }); - debug!(?universal_substs); + debug!(?universal_args); debug!(?subst_regions); // Deduplicate the set of regions while keeping the chosen order. @@ -139,7 +139,7 @@ impl<'tcx> RegionInferenceContext<'tcx> { debug!(?universal_concrete_type); let opaque_type_key = - OpaqueTypeKey { def_id: opaque_type_key.def_id, substs: universal_substs }; + OpaqueTypeKey { def_id: opaque_type_key.def_id, args: universal_args }; let ty = infcx.infer_opaque_definition_from_instantiation( opaque_type_key, universal_concrete_type, @@ -175,7 +175,7 @@ impl<'tcx> RegionInferenceContext<'tcx> { /// Map the regions in the type to named regions. This is similar to what /// `infer_opaque_types` does, but can infer any universal region, not only - /// ones from the substs for the opaque type. It also doesn't double check + /// ones from the args for the opaque type. It also doesn't double check /// that the regions produced are in fact equal to the named region they are /// replaced with. This is fine because this function is only to improve the /// region names in error messages. @@ -238,7 +238,7 @@ impl<'tcx> InferCtxtExt<'tcx> for InferCtxt<'tcx> { /// # Parameters /// /// - `def_id`, the `impl Trait` type - /// - `substs`, the substs used to instantiate this opaque type + /// - `args`, the args used to instantiate this opaque type /// - `instantiated_ty`, the inferred type C1 -- fully resolved, lifted version of /// `opaque_defn.concrete_ty` #[instrument(level = "debug", skip(self))] @@ -309,11 +309,11 @@ fn check_opaque_type_well_formed<'tcx>( }) .build(); let ocx = ObligationCtxt::new(&infcx); - let identity_substs = InternalSubsts::identity_for_item(tcx, def_id); + let identity_args = GenericArgs::identity_for_item(tcx, def_id); // Require that the hidden type actually fulfills all the bounds of the opaque type, even without // the bounds that the function supplies. - let opaque_ty = Ty::new_opaque(tcx, def_id.to_def_id(), identity_substs); + let opaque_ty = Ty::new_opaque(tcx, def_id.to_def_id(), identity_args); ocx.eq(&ObligationCause::misc(definition_span, def_id), param_env, opaque_ty, definition_ty) .map_err(|err| { infcx @@ -384,7 +384,7 @@ fn check_opaque_type_parameter_valid( } let opaque_generics = tcx.generics_of(opaque_type_key.def_id); let mut seen_params: FxIndexMap<_, Vec<_>> = FxIndexMap::default(); - for (i, arg) in opaque_type_key.substs.iter().enumerate() { + for (i, arg) in opaque_type_key.args.iter().enumerate() { let arg_is_param = match arg.unpack() { GenericArgKind::Type(ty) => matches!(ty.kind(), ty::Param(_)), GenericArgKind::Lifetime(lt) => { diff --git a/compiler/rustc_borrowck/src/renumber.rs b/compiler/rustc_borrowck/src/renumber.rs index 4389d2b60bc..4c69ea843c7 100644 --- a/compiler/rustc_borrowck/src/renumber.rs +++ b/compiler/rustc_borrowck/src/renumber.rs @@ -6,7 +6,7 @@ use rustc_infer::infer::NllRegionVariableOrigin; use rustc_middle::mir::visit::{MutVisitor, TyContext}; use rustc_middle::mir::Constant; use rustc_middle::mir::{Body, Location, Promoted}; -use rustc_middle::ty::subst::SubstsRef; +use rustc_middle::ty::GenericArgsRef; use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable}; use rustc_span::{Span, Symbol}; @@ -94,10 +94,10 @@ impl<'a, 'tcx> MutVisitor<'tcx> for RegionRenumberer<'a, 'tcx> { } #[instrument(skip(self), level = "debug")] - fn visit_substs(&mut self, substs: &mut SubstsRef<'tcx>, location: Location) { - *substs = self.renumber_regions(*substs, || RegionCtxt::Location(location)); + fn visit_args(&mut self, args: &mut GenericArgsRef<'tcx>, location: Location) { + *args = self.renumber_regions(*args, || RegionCtxt::Location(location)); - debug!(?substs); + debug!(?args); } #[instrument(skip(self), level = "debug")] diff --git a/compiler/rustc_borrowck/src/session_diagnostics.rs b/compiler/rustc_borrowck/src/session_diagnostics.rs index fceae5bb3ff..d1d8cfa74aa 100644 --- a/compiler/rustc_borrowck/src/session_diagnostics.rs +++ b/compiler/rustc_borrowck/src/session_diagnostics.rs @@ -398,7 +398,7 @@ pub(crate) enum CaptureReasonSuggest<'tcx> { #[suggestion( borrowck_suggest_create_freash_reborrow, applicability = "maybe-incorrect", - code = "as_mut().", + code = ".as_mut()", style = "verbose" )] FreshReborrow { diff --git a/compiler/rustc_borrowck/src/type_check/constraint_conversion.rs b/compiler/rustc_borrowck/src/type_check/constraint_conversion.rs index 71eae7b27d1..21d8026e170 100644 --- a/compiler/rustc_borrowck/src/type_check/constraint_conversion.rs +++ b/compiler/rustc_borrowck/src/type_check/constraint_conversion.rs @@ -5,7 +5,7 @@ use rustc_infer::infer::outlives::obligations::{TypeOutlives, TypeOutlivesDelega use rustc_infer::infer::region_constraints::{GenericKind, VerifyBound}; use rustc_infer::infer::{self, InferCtxt, SubregionOrigin}; use rustc_middle::mir::{ClosureOutlivesSubject, ClosureRegionRequirements, ConstraintCategory}; -use rustc_middle::ty::subst::GenericArgKind; +use rustc_middle::ty::GenericArgKind; use rustc_middle::ty::{self, TyCtxt}; use rustc_middle::ty::{TypeFoldable, TypeVisitableExt}; use rustc_span::{Span, DUMMY_SP}; @@ -89,20 +89,20 @@ impl<'a, 'tcx> ConstraintConversion<'a, 'tcx> { /// Given an instance of the closure type, this method instantiates the "extra" requirements /// that we computed for the closure. This has the effect of adding new outlives obligations - /// to existing region variables in `closure_substs`. + /// to existing region variables in `closure_args`. #[instrument(skip(self), level = "debug")] pub fn apply_closure_requirements( &mut self, closure_requirements: &ClosureRegionRequirements<'tcx>, closure_def_id: DefId, - closure_substs: ty::SubstsRef<'tcx>, + closure_args: ty::GenericArgsRef<'tcx>, ) { - // Extract the values of the free regions in `closure_substs` + // Extract the values of the free regions in `closure_args` // into a vector. These are the regions that we will be // relating to one another. let closure_mapping = &UniversalRegions::closure_mapping( self.tcx, - closure_substs, + closure_args, closure_requirements.num_external_vids, closure_def_id.expect_local(), ); diff --git a/compiler/rustc_borrowck/src/type_check/liveness/polonius.rs b/compiler/rustc_borrowck/src/type_check/liveness/polonius.rs index 012075d7114..c621df37106 100644 --- a/compiler/rustc_borrowck/src/type_check/liveness/polonius.rs +++ b/compiler/rustc_borrowck/src/type_check/liveness/polonius.rs @@ -2,7 +2,7 @@ use crate::def_use::{self, DefUse}; use crate::location::{LocationIndex, LocationTable}; use rustc_middle::mir::visit::{MutatingUseContext, PlaceContext, Visitor}; use rustc_middle::mir::{Body, Local, Location, Place}; -use rustc_middle::ty::subst::GenericArg; +use rustc_middle::ty::GenericArg; use rustc_mir_dataflow::move_paths::{LookupResult, MoveData, MovePathIndex}; use super::TypeChecker; diff --git a/compiler/rustc_borrowck/src/type_check/mod.rs b/compiler/rustc_borrowck/src/type_check/mod.rs index a15e1065c81..78aa513033c 100644 --- a/compiler/rustc_borrowck/src/type_check/mod.rs +++ b/compiler/rustc_borrowck/src/type_check/mod.rs @@ -30,12 +30,12 @@ use rustc_middle::traits::query::NoSolution; use rustc_middle::traits::ObligationCause; use rustc_middle::ty::adjustment::PointerCoercion; use rustc_middle::ty::cast::CastTy; -use rustc_middle::ty::subst::{SubstsRef, UserSubsts}; use rustc_middle::ty::visit::TypeVisitableExt; use rustc_middle::ty::{ self, Binder, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, Dynamic, OpaqueHiddenType, OpaqueTypeKey, RegionVid, Ty, TyCtxt, UserType, UserTypeAnnotationIndex, }; +use rustc_middle::ty::{GenericArgsRef, UserArgs}; use rustc_span::def_id::CRATE_DEF_ID; use rustc_span::symbol::sym; use rustc_span::{Span, DUMMY_SP}; @@ -389,15 +389,12 @@ impl<'a, 'b, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, 'tcx> { } else { self.cx.ascribe_user_type( constant.literal.ty(), - UserType::TypeOf( - uv.def, - UserSubsts { substs: uv.substs, user_self_ty: None }, - ), + UserType::TypeOf(uv.def, UserArgs { args: uv.args, user_self_ty: None }), locations.span(&self.cx.body), ); } } else if let Some(static_def_id) = constant.check_static_ptr(tcx) { - let unnormalized_ty = tcx.type_of(static_def_id).subst_identity(); + let unnormalized_ty = tcx.type_of(static_def_id).instantiate_identity(); let normalized_ty = self.cx.normalize(unnormalized_ty, locations); let literal_ty = constant.literal.ty().builtin_deref(true).unwrap().ty; @@ -411,11 +408,11 @@ impl<'a, 'b, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, 'tcx> { } } - if let ty::FnDef(def_id, substs) = *constant.literal.ty().kind() { + if let ty::FnDef(def_id, args) = *constant.literal.ty().kind() { // const_trait_impl: use a non-const param env when checking that a FnDef type is well formed. // this is because the well-formedness of the function does not need to be proved to have `const` // impls for trait bounds. - let instantiated_predicates = tcx.predicates_of(def_id).instantiate(tcx, substs); + let instantiated_predicates = tcx.predicates_of(def_id).instantiate(tcx, args); let prev = self.cx.param_env; self.cx.param_env = prev.without_const(); self.cx.normalize_and_prove_instantiated_predicates( @@ -666,7 +663,7 @@ impl<'a, 'b, 'tcx> TypeVerifier<'a, 'b, 'tcx> { }) } ProjectionElem::Downcast(maybe_name, index) => match base_ty.kind() { - ty::Adt(adt_def, _substs) if adt_def.is_enum() => { + ty::Adt(adt_def, _args) if adt_def.is_enum() => { if index.as_usize() >= adt_def.variants().len() { PlaceTy::from_ty(span_mirbug_and_err!( self, @@ -776,16 +773,16 @@ impl<'a, 'b, 'tcx> TypeVerifier<'a, 'b, 'tcx> { ) -> Result<Ty<'tcx>, FieldAccessError> { let tcx = self.tcx(); - let (variant, substs) = match base_ty { + let (variant, args) = match base_ty { PlaceTy { ty, variant_index: Some(variant_index) } => match *ty.kind() { - ty::Adt(adt_def, substs) => (adt_def.variant(variant_index), substs), - ty::Generator(def_id, substs, _) => { - let mut variants = substs.as_generator().state_tys(def_id, tcx); + ty::Adt(adt_def, args) => (adt_def.variant(variant_index), args), + ty::Generator(def_id, args, _) => { + let mut variants = args.as_generator().state_tys(def_id, tcx); let Some(mut variant) = variants.nth(variant_index.into()) else { bug!( "variant_index of generator out of range: {:?}/{:?}", variant_index, - substs.as_generator().state_tys(def_id, tcx).count() + args.as_generator().state_tys(def_id, tcx).count() ); }; return match variant.nth(field.index()) { @@ -796,11 +793,11 @@ impl<'a, 'b, 'tcx> TypeVerifier<'a, 'b, 'tcx> { _ => bug!("can't have downcast of non-adt non-generator type"), }, PlaceTy { ty, variant_index: None } => match *ty.kind() { - ty::Adt(adt_def, substs) if !adt_def.is_enum() => { - (adt_def.variant(FIRST_VARIANT), substs) + ty::Adt(adt_def, args) if !adt_def.is_enum() => { + (adt_def.variant(FIRST_VARIANT), args) } - ty::Closure(_, substs) => { - return match substs + ty::Closure(_, args) => { + return match args .as_closure() .tupled_upvars_ty() .tuple_fields() @@ -808,17 +805,17 @@ impl<'a, 'b, 'tcx> TypeVerifier<'a, 'b, 'tcx> { { Some(&ty) => Ok(ty), None => Err(FieldAccessError::OutOfRange { - field_count: substs.as_closure().upvar_tys().count(), + field_count: args.as_closure().upvar_tys().count(), }), }; } - ty::Generator(_, substs, _) => { + ty::Generator(_, args, _) => { // Only prefix fields (upvars and current state) are // accessible without a variant index. - return match substs.as_generator().prefix_tys().nth(field.index()) { + return match args.as_generator().prefix_tys().nth(field.index()) { Some(ty) => Ok(ty), None => Err(FieldAccessError::OutOfRange { - field_count: substs.as_generator().prefix_tys().count(), + field_count: args.as_generator().prefix_tys().count(), }), }; } @@ -840,7 +837,7 @@ impl<'a, 'b, 'tcx> TypeVerifier<'a, 'b, 'tcx> { }; if let Some(field) = variant.fields.get(field) { - Ok(self.cx.normalize(field.ty(tcx, substs), location)) + Ok(self.cx.normalize(field.ty(tcx, args), location)) } else { Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() }) } @@ -1065,7 +1062,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { ocx.infcx.add_item_bounds_for_hidden_type( opaque_type_key.def_id.to_def_id(), - opaque_type_key.substs, + opaque_type_key.args, cause, param_env, hidden_ty.ty, @@ -1770,32 +1767,32 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { let tcx = self.tcx(); match *ak { - AggregateKind::Adt(adt_did, variant_index, substs, _, active_field_index) => { + AggregateKind::Adt(adt_did, variant_index, args, _, active_field_index) => { let def = tcx.adt_def(adt_did); let variant = &def.variant(variant_index); let adj_field_index = active_field_index.unwrap_or(field_index); if let Some(field) = variant.fields.get(adj_field_index) { - Ok(self.normalize(field.ty(tcx, substs), location)) + Ok(self.normalize(field.ty(tcx, args), location)) } else { Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() }) } } - AggregateKind::Closure(_, substs) => { - match substs.as_closure().upvar_tys().nth(field_index.as_usize()) { + AggregateKind::Closure(_, args) => { + match args.as_closure().upvar_tys().nth(field_index.as_usize()) { Some(ty) => Ok(ty), None => Err(FieldAccessError::OutOfRange { - field_count: substs.as_closure().upvar_tys().count(), + field_count: args.as_closure().upvar_tys().count(), }), } } - AggregateKind::Generator(_, substs, _) => { + AggregateKind::Generator(_, args, _) => { // It doesn't make sense to look at a field beyond the prefix; // these require a variant index, and are not initialized in // aggregate rvalues. - match substs.as_generator().prefix_tys().nth(field_index.as_usize()) { + match args.as_generator().prefix_tys().nth(field_index.as_usize()) { Some(ty) => Ok(ty), None => Err(FieldAccessError::OutOfRange { - field_count: substs.as_generator().prefix_tys().count(), + field_count: args.as_generator().prefix_tys().count(), }), } } @@ -1821,8 +1818,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { let def_id = uv.def; if tcx.def_kind(def_id) == DefKind::InlineConst { let def_id = def_id.expect_local(); - let predicates = - self.prove_closure_bounds(tcx, def_id, uv.substs, location); + let predicates = self.prove_closure_bounds(tcx, def_id, uv.args, location); self.normalize_and_prove_instantiated_predicates( def_id.to_def_id(), predicates, @@ -1939,7 +1935,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { CastKind::PointerCoercion(PointerCoercion::ClosureFnPointer(unsafety)) => { let sig = match op.ty(body, tcx).kind() { - ty::Closure(_, substs) => substs.as_closure().sig(), + ty::Closure(_, args) => args.as_closure().sig(), _ => bug!(), }; let ty_fn_ptr_from = @@ -2039,28 +2035,16 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { } CastKind::PointerCoercion(PointerCoercion::MutToConstPointer) => { - let ty::RawPtr(ty::TypeAndMut { - ty: ty_from, - mutbl: hir::Mutability::Mut, - }) = op.ty(body, tcx).kind() else { - span_mirbug!( - self, - rvalue, - "unexpected base type for cast {:?}", - ty, - ); + let ty::RawPtr(ty::TypeAndMut { ty: ty_from, mutbl: hir::Mutability::Mut }) = + op.ty(body, tcx).kind() + else { + span_mirbug!(self, rvalue, "unexpected base type for cast {:?}", ty,); return; }; - let ty::RawPtr(ty::TypeAndMut { - ty: ty_to, - mutbl: hir::Mutability::Not, - }) = ty.kind() else { - span_mirbug!( - self, - rvalue, - "unexpected target type for cast {:?}", - ty, - ); + let ty::RawPtr(ty::TypeAndMut { ty: ty_to, mutbl: hir::Mutability::Not }) = + ty.kind() + else { + span_mirbug!(self, rvalue, "unexpected target type for cast {:?}", ty,); return; }; if let Err(terr) = self.sub_types( @@ -2603,8 +2587,8 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { ); let (def_id, instantiated_predicates) = match *aggregate_kind { - AggregateKind::Adt(adt_did, _, substs, _, _) => { - (adt_did, tcx.predicates_of(adt_did).instantiate(tcx, substs)) + AggregateKind::Adt(adt_did, _, args, _, _) => { + (adt_did, tcx.predicates_of(adt_did).instantiate(tcx, args)) } // For closures, we have some **extra requirements** we @@ -2626,9 +2610,8 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { // desugaring. A closure gets desugared to a struct, and // these extra requirements are basically like where // clauses on the struct. - AggregateKind::Closure(def_id, substs) - | AggregateKind::Generator(def_id, substs, _) => { - (def_id, self.prove_closure_bounds(tcx, def_id.expect_local(), substs, location)) + AggregateKind::Closure(def_id, args) | AggregateKind::Generator(def_id, args, _) => { + (def_id, self.prove_closure_bounds(tcx, def_id.expect_local(), args, location)) } AggregateKind::Array(_) | AggregateKind::Tuple => { @@ -2647,7 +2630,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { &mut self, tcx: TyCtxt<'tcx>, def_id: LocalDefId, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, location: Location, ) -> ty::InstantiatedPredicates<'tcx> { if let Some(closure_requirements) = &tcx.mir_borrowck(def_id).closure_requirements { @@ -2665,26 +2648,26 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { .apply_closure_requirements( &closure_requirements, def_id.to_def_id(), - substs, + args, ); } - // Now equate closure substs to regions inherited from `typeck_root_def_id`. Fixes #98589. + // Now equate closure args to regions inherited from `typeck_root_def_id`. Fixes #98589. let typeck_root_def_id = tcx.typeck_root_def_id(self.body.source.def_id()); - let typeck_root_substs = ty::InternalSubsts::identity_for_item(tcx, typeck_root_def_id); + let typeck_root_args = ty::GenericArgs::identity_for_item(tcx, typeck_root_def_id); - let parent_substs = match tcx.def_kind(def_id) { - DefKind::Closure => substs.as_closure().parent_substs(), - DefKind::Generator => substs.as_generator().parent_substs(), - DefKind::InlineConst => substs.as_inline_const().parent_substs(), + let parent_args = match tcx.def_kind(def_id) { + DefKind::Closure => args.as_closure().parent_args(), + DefKind::Generator => args.as_generator().parent_args(), + DefKind::InlineConst => args.as_inline_const().parent_args(), other => bug!("unexpected item {:?}", other), }; - let parent_substs = tcx.mk_substs(parent_substs); + let parent_args = tcx.mk_args(parent_args); - assert_eq!(typeck_root_substs.len(), parent_substs.len()); - if let Err(_) = self.eq_substs( - typeck_root_substs, - parent_substs, + assert_eq!(typeck_root_args.len(), parent_args.len()); + if let Err(_) = self.eq_args( + typeck_root_args, + parent_args, location.to_locations(), ConstraintCategory::BoringNoLocation, ) { @@ -2692,12 +2675,12 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { self, def_id, "could not relate closure to parent {:?} != {:?}", - typeck_root_substs, - parent_substs + typeck_root_args, + parent_args ); } - tcx.predicates_of(def_id).instantiate(tcx, substs) + tcx.predicates_of(def_id).instantiate(tcx, args) } #[instrument(skip(self, body), level = "debug")] diff --git a/compiler/rustc_borrowck/src/type_check/relate_tys.rs b/compiler/rustc_borrowck/src/type_check/relate_tys.rs index 8c4bfb2c6e0..e0c6295627b 100644 --- a/compiler/rustc_borrowck/src/type_check/relate_tys.rs +++ b/compiler/rustc_borrowck/src/type_check/relate_tys.rs @@ -42,10 +42,10 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { } /// Add sufficient constraints to ensure `a == b`. See also [Self::relate_types]. - pub(super) fn eq_substs( + pub(super) fn eq_args( &mut self, - a: ty::SubstsRef<'tcx>, - b: ty::SubstsRef<'tcx>, + a: ty::GenericArgsRef<'tcx>, + b: ty::GenericArgsRef<'tcx>, locations: Locations, category: ConstraintCategory<'tcx>, ) -> Result<(), NoSolution> { diff --git a/compiler/rustc_borrowck/src/universal_regions.rs b/compiler/rustc_borrowck/src/universal_regions.rs index 7821b82bf2b..a751a9732f0 100644 --- a/compiler/rustc_borrowck/src/universal_regions.rs +++ b/compiler/rustc_borrowck/src/universal_regions.rs @@ -22,8 +22,8 @@ use rustc_hir::BodyOwnerKind; use rustc_index::IndexVec; use rustc_infer::infer::NllRegionVariableOrigin; use rustc_middle::ty::fold::TypeFoldable; -use rustc_middle::ty::{self, InlineConstSubsts, InlineConstSubstsParts, RegionVid, Ty, TyCtxt}; -use rustc_middle::ty::{InternalSubsts, SubstsRef}; +use rustc_middle::ty::{self, InlineConstArgs, InlineConstArgsParts, RegionVid, Ty, TyCtxt}; +use rustc_middle::ty::{GenericArgs, GenericArgsRef}; use rustc_span::symbol::{kw, sym}; use rustc_span::Symbol; use std::iter; @@ -88,26 +88,26 @@ pub struct UniversalRegions<'tcx> { #[derive(Copy, Clone, Debug)] pub enum DefiningTy<'tcx> { /// The MIR is a closure. The signature is found via - /// `ClosureSubsts::closure_sig_ty`. - Closure(DefId, SubstsRef<'tcx>), + /// `ClosureArgs::closure_sig_ty`. + Closure(DefId, GenericArgsRef<'tcx>), /// The MIR is a generator. The signature is that generators take /// no parameters and return the result of - /// `ClosureSubsts::generator_return_ty`. - Generator(DefId, SubstsRef<'tcx>, hir::Movability), + /// `ClosureArgs::generator_return_ty`. + Generator(DefId, GenericArgsRef<'tcx>, hir::Movability), - /// The MIR is a fn item with the given `DefId` and substs. The signature + /// The MIR is a fn item with the given `DefId` and args. The signature /// of the function can be bound then with the `fn_sig` query. - FnDef(DefId, SubstsRef<'tcx>), + FnDef(DefId, GenericArgsRef<'tcx>), /// The MIR represents some form of constant. The signature then /// is that it has no inputs and a single return value, which is /// the value of the constant. - Const(DefId, SubstsRef<'tcx>), + Const(DefId, GenericArgsRef<'tcx>), /// The MIR represents an inline const. The signature has no inputs and a - /// single return value found via `InlineConstSubsts::ty`. - InlineConst(DefId, SubstsRef<'tcx>), + /// single return value found via `InlineConstArgs::ty`. + InlineConst(DefId, GenericArgsRef<'tcx>), } impl<'tcx> DefiningTy<'tcx> { @@ -117,9 +117,9 @@ impl<'tcx> DefiningTy<'tcx> { /// match up with the upvar order in the HIR, typesystem, and MIR. pub fn upvar_tys(self) -> impl Iterator<Item = Ty<'tcx>> + 'tcx { match self { - DefiningTy::Closure(_, substs) => Either::Left(substs.as_closure().upvar_tys()), - DefiningTy::Generator(_, substs, _) => { - Either::Right(Either::Left(substs.as_generator().upvar_tys())) + DefiningTy::Closure(_, args) => Either::Left(args.as_closure().upvar_tys()), + DefiningTy::Generator(_, args, _) => { + Either::Right(Either::Left(args.as_generator().upvar_tys())) } DefiningTy::FnDef(..) | DefiningTy::Const(..) | DefiningTy::InlineConst(..) => { Either::Right(Either::Right(iter::empty())) @@ -164,9 +164,9 @@ struct UniversalRegionIndices<'tcx> { /// used because trait matching and type-checking will feed us /// region constraints that reference those regions and we need to /// be able to map them to our internal `RegionVid`. This is - /// basically equivalent to an `InternalSubsts`, except that it also + /// basically equivalent to an `GenericArgs`, except that it also /// contains an entry for `ReStatic` -- it might be nice to just - /// use a substs, and then handle `ReStatic` another way. + /// use a args, and then handle `ReStatic` another way. indices: FxHashMap<ty::Region<'tcx>, RegionVid>, /// The vid assigned to `'static`. Used only for diagnostics. @@ -243,13 +243,13 @@ impl<'tcx> UniversalRegions<'tcx> { /// `V[1]: V[2]`. pub fn closure_mapping( tcx: TyCtxt<'tcx>, - closure_substs: SubstsRef<'tcx>, + closure_args: GenericArgsRef<'tcx>, expected_num_vars: usize, closure_def_id: LocalDefId, ) -> IndexVec<RegionVid, ty::Region<'tcx>> { let mut region_mapping = IndexVec::with_capacity(expected_num_vars); region_mapping.push(tcx.lifetimes.re_static); - tcx.for_each_free_region(&closure_substs, |fr| { + tcx.for_each_free_region(&closure_args, |fr| { region_mapping.push(fr); }); @@ -334,11 +334,11 @@ impl<'tcx> UniversalRegions<'tcx> { /// state. pub(crate) fn annotate(&self, tcx: TyCtxt<'tcx>, err: &mut Diagnostic) { match self.defining_ty { - DefiningTy::Closure(def_id, substs) => { + DefiningTy::Closure(def_id, args) => { err.note(format!( - "defining type: {} with closure substs {:#?}", - tcx.def_path_str_with_substs(def_id, substs), - &substs[tcx.generics_of(def_id).parent_count..], + "defining type: {} with closure args {:#?}", + tcx.def_path_str_with_args(def_id, args), + &args[tcx.generics_of(def_id).parent_count..], )); // FIXME: It'd be nice to print the late-bound regions @@ -350,11 +350,11 @@ impl<'tcx> UniversalRegions<'tcx> { err.note(format!("late-bound region is {:?}", self.to_region_vid(r))); }); } - DefiningTy::Generator(def_id, substs, _) => { + DefiningTy::Generator(def_id, args, _) => { err.note(format!( - "defining type: {} with generator substs {:#?}", - tcx.def_path_str_with_substs(def_id, substs), - &substs[tcx.generics_of(def_id).parent_count..], + "defining type: {} with generator args {:#?}", + tcx.def_path_str_with_args(def_id, args), + &args[tcx.generics_of(def_id).parent_count..], )); // FIXME: As above, we'd like to print out the region @@ -364,22 +364,19 @@ impl<'tcx> UniversalRegions<'tcx> { err.note(format!("late-bound region is {:?}", self.to_region_vid(r))); }); } - DefiningTy::FnDef(def_id, substs) => { - err.note(format!( - "defining type: {}", - tcx.def_path_str_with_substs(def_id, substs), - )); + DefiningTy::FnDef(def_id, args) => { + err.note(format!("defining type: {}", tcx.def_path_str_with_args(def_id, args),)); } - DefiningTy::Const(def_id, substs) => { + DefiningTy::Const(def_id, args) => { err.note(format!( "defining constant type: {}", - tcx.def_path_str_with_substs(def_id, substs), + tcx.def_path_str_with_args(def_id, args), )); } - DefiningTy::InlineConst(def_id, substs) => { + DefiningTy::InlineConst(def_id, args) => { err.note(format!( "defining inline constant type: {}", - tcx.def_path_str_with_substs(def_id, substs), + tcx.def_path_str_with_args(def_id, args), )); } } @@ -501,8 +498,11 @@ impl<'cx, 'tcx> UniversalRegionsBuilder<'cx, 'tcx> { .as_var(); let region = ty::Region::new_var(self.infcx.tcx, reg_vid); - let va_list_ty = - self.infcx.tcx.type_of(va_list_did).subst(self.infcx.tcx, &[region.into()]); + let va_list_ty = self + .infcx + .tcx + .type_of(va_list_did) + .instantiate(self.infcx.tcx, &[region.into()]); unnormalized_input_tys = self.infcx.tcx.mk_type_list_from_iter( unnormalized_input_tys.iter().copied().chain(iter::once(va_list_ty)), @@ -522,7 +522,7 @@ impl<'cx, 'tcx> UniversalRegionsBuilder<'cx, 'tcx> { debug!("build: local regions = {}..{}", first_local_index, num_universals); let yield_ty = match defining_ty { - DefiningTy::Generator(_, substs, _) => Some(substs.as_generator().yield_ty()), + DefiningTy::Generator(_, args, _) => Some(args.as_generator().yield_ty()), _ => None, }; @@ -548,7 +548,7 @@ impl<'cx, 'tcx> UniversalRegionsBuilder<'cx, 'tcx> { match tcx.hir().body_owner_kind(self.mir_def) { BodyOwnerKind::Closure | BodyOwnerKind::Fn => { - let defining_ty = tcx.type_of(self.mir_def).subst_identity(); + let defining_ty = tcx.type_of(self.mir_def).instantiate_identity(); debug!("defining_ty (pre-replacement): {:?}", defining_ty); @@ -556,11 +556,11 @@ impl<'cx, 'tcx> UniversalRegionsBuilder<'cx, 'tcx> { self.infcx.replace_free_regions_with_nll_infer_vars(FR, defining_ty); match *defining_ty.kind() { - ty::Closure(def_id, substs) => DefiningTy::Closure(def_id, substs), - ty::Generator(def_id, substs, movability) => { - DefiningTy::Generator(def_id, substs, movability) + ty::Closure(def_id, args) => DefiningTy::Closure(def_id, args), + ty::Generator(def_id, args, movability) => { + DefiningTy::Generator(def_id, args, movability) } - ty::FnDef(def_id, substs) => DefiningTy::FnDef(def_id, substs), + ty::FnDef(def_id, args) => DefiningTy::FnDef(def_id, args), _ => span_bug!( tcx.def_span(self.mir_def), "expected defining type for `{:?}`: `{:?}`", @@ -571,11 +571,11 @@ impl<'cx, 'tcx> UniversalRegionsBuilder<'cx, 'tcx> { } BodyOwnerKind::Const | BodyOwnerKind::Static(..) => { - let identity_substs = InternalSubsts::identity_for_item(tcx, typeck_root_def_id); + let identity_args = GenericArgs::identity_for_item(tcx, typeck_root_def_id); if self.mir_def.to_def_id() == typeck_root_def_id { - let substs = - self.infcx.replace_free_regions_with_nll_infer_vars(FR, identity_substs); - DefiningTy::Const(self.mir_def.to_def_id(), substs) + let args = + self.infcx.replace_free_regions_with_nll_infer_vars(FR, identity_args); + DefiningTy::Const(self.mir_def.to_def_id(), args) } else { // FIXME this line creates a dependency between borrowck and typeck. // @@ -584,18 +584,18 @@ impl<'cx, 'tcx> UniversalRegionsBuilder<'cx, 'tcx> { // into borrowck, which is ICE #78174. // // As a workaround, inline consts have an additional generic param (`ty` - // below), so that `type_of(inline_const_def_id).substs(substs)` uses the + // below), so that `type_of(inline_const_def_id).args(args)` uses the // proper type with NLL infer vars. let ty = tcx .typeck(self.mir_def) .node_type(tcx.local_def_id_to_hir_id(self.mir_def)); - let substs = InlineConstSubsts::new( + let args = InlineConstArgs::new( tcx, - InlineConstSubstsParts { parent_substs: identity_substs, ty }, + InlineConstArgsParts { parent_args: identity_args, ty }, ) - .substs; - let substs = self.infcx.replace_free_regions_with_nll_infer_vars(FR, substs); - DefiningTy::InlineConst(self.mir_def.to_def_id(), substs) + .args; + let args = self.infcx.replace_free_regions_with_nll_infer_vars(FR, args); + DefiningTy::InlineConst(self.mir_def.to_def_id(), args) } } } @@ -612,29 +612,29 @@ impl<'cx, 'tcx> UniversalRegionsBuilder<'cx, 'tcx> { ) -> UniversalRegionIndices<'tcx> { let tcx = self.infcx.tcx; let typeck_root_def_id = tcx.typeck_root_def_id(self.mir_def.to_def_id()); - let identity_substs = InternalSubsts::identity_for_item(tcx, typeck_root_def_id); - let fr_substs = match defining_ty { - DefiningTy::Closure(_, substs) - | DefiningTy::Generator(_, substs, _) - | DefiningTy::InlineConst(_, substs) => { + let identity_args = GenericArgs::identity_for_item(tcx, typeck_root_def_id); + let fr_args = match defining_ty { + DefiningTy::Closure(_, args) + | DefiningTy::Generator(_, args, _) + | DefiningTy::InlineConst(_, args) => { // In the case of closures, we rely on the fact that - // the first N elements in the ClosureSubsts are + // the first N elements in the ClosureArgs are // inherited from the `typeck_root_def_id`. // Therefore, when we zip together (below) with - // `identity_substs`, we will get only those regions + // `identity_args`, we will get only those regions // that correspond to early-bound regions declared on // the `typeck_root_def_id`. - assert!(substs.len() >= identity_substs.len()); - assert_eq!(substs.regions().count(), identity_substs.regions().count()); - substs + assert!(args.len() >= identity_args.len()); + assert_eq!(args.regions().count(), identity_args.regions().count()); + args } - DefiningTy::FnDef(_, substs) | DefiningTy::Const(_, substs) => substs, + DefiningTy::FnDef(_, args) | DefiningTy::Const(_, args) => args, }; let global_mapping = iter::once((tcx.lifetimes.re_static, fr_static)); let subst_mapping = - iter::zip(identity_substs.regions(), fr_substs.regions().map(|r| r.as_var())); + iter::zip(identity_args.regions(), fr_args.regions().map(|r| r.as_var())); UniversalRegionIndices { indices: global_mapping.chain(subst_mapping).collect(), fr_static } } @@ -646,9 +646,9 @@ impl<'cx, 'tcx> UniversalRegionsBuilder<'cx, 'tcx> { ) -> ty::Binder<'tcx, &'tcx ty::List<Ty<'tcx>>> { let tcx = self.infcx.tcx; match defining_ty { - DefiningTy::Closure(def_id, substs) => { + DefiningTy::Closure(def_id, args) => { assert_eq!(self.mir_def.to_def_id(), def_id); - let closure_sig = substs.as_closure().sig(); + let closure_sig = args.as_closure().sig(); let inputs_and_output = closure_sig.inputs_and_output(); let bound_vars = tcx.mk_bound_variable_kinds_from_iter( inputs_and_output @@ -661,7 +661,7 @@ impl<'cx, 'tcx> UniversalRegionsBuilder<'cx, 'tcx> { kind: ty::BrEnv, }; let env_region = ty::Region::new_late_bound(tcx, ty::INNERMOST, br); - let closure_ty = tcx.closure_env_ty(def_id, substs, env_region).unwrap(); + let closure_ty = tcx.closure_env_ty(def_id, args, env_region).unwrap(); // The "inputs" of the closure in the // signature appear as a tuple. The MIR side @@ -681,18 +681,18 @@ impl<'cx, 'tcx> UniversalRegionsBuilder<'cx, 'tcx> { ) } - DefiningTy::Generator(def_id, substs, movability) => { + DefiningTy::Generator(def_id, args, movability) => { assert_eq!(self.mir_def.to_def_id(), def_id); - let resume_ty = substs.as_generator().resume_ty(); - let output = substs.as_generator().return_ty(); - let generator_ty = Ty::new_generator(tcx, def_id, substs, movability); + let resume_ty = args.as_generator().resume_ty(); + let output = args.as_generator().return_ty(); + let generator_ty = Ty::new_generator(tcx, def_id, args, movability); let inputs_and_output = self.infcx.tcx.mk_type_list(&[generator_ty, resume_ty, output]); ty::Binder::dummy(inputs_and_output) } DefiningTy::FnDef(def_id, _) => { - let sig = tcx.fn_sig(def_id).subst_identity(); + let sig = tcx.fn_sig(def_id).instantiate_identity(); let sig = indices.fold_to_region_vids(tcx, sig); sig.inputs_and_output() } @@ -701,14 +701,14 @@ impl<'cx, 'tcx> UniversalRegionsBuilder<'cx, 'tcx> { // For a constant body, there are no inputs, and one // "output" (the type of the constant). assert_eq!(self.mir_def.to_def_id(), def_id); - let ty = tcx.type_of(self.mir_def).subst_identity(); + let ty = tcx.type_of(self.mir_def).instantiate_identity(); let ty = indices.fold_to_region_vids(tcx, ty); ty::Binder::dummy(tcx.mk_type_list(&[ty])) } - DefiningTy::InlineConst(def_id, substs) => { + DefiningTy::InlineConst(def_id, args) => { assert_eq!(self.mir_def.to_def_id(), def_id); - let ty = substs.as_inline_const().ty(); + let ty = args.as_inline_const().ty(); ty::Binder::dummy(tcx.mk_type_list(&[ty])) } } @@ -929,7 +929,9 @@ fn for_each_late_bound_region_in_item<'tcx>( } for bound_var in tcx.late_bound_vars(tcx.hir().local_def_id_to_hir_id(mir_def_id)) { - let ty::BoundVariableKind::Region(bound_region) = bound_var else { continue; }; + let ty::BoundVariableKind::Region(bound_region) = bound_var else { + continue; + }; let liberated_region = ty::Region::new_free(tcx, mir_def_id.to_def_id(), bound_region); f(liberated_region); } diff --git a/compiler/rustc_builtin_macros/src/asm.rs b/compiler/rustc_builtin_macros/src/asm.rs index 6187e4f513b..19acefc38e3 100644 --- a/compiler/rustc_builtin_macros/src/asm.rs +++ b/compiler/rustc_builtin_macros/src/asm.rs @@ -157,8 +157,7 @@ pub fn parse_asm_args<'a>( } else if p.eat_keyword(sym::sym) { let expr = p.parse_expr()?; let ast::ExprKind::Path(qself, path) = &expr.kind else { - let err = diag - .create_err(errors::AsmSymNoPath { span: expr.span }); + let err = diag.create_err(errors::AsmSymNoPath { span: expr.span }); return Err(err); }; let sym = ast::InlineAsmSym { diff --git a/compiler/rustc_builtin_macros/src/deriving/cmp/ord.rs b/compiler/rustc_builtin_macros/src/deriving/cmp/ord.rs index 4401cf8a9c5..ea81cee78b7 100644 --- a/compiler/rustc_builtin_macros/src/deriving/cmp/ord.rs +++ b/compiler/rustc_builtin_macros/src/deriving/cmp/ord.rs @@ -61,8 +61,8 @@ pub fn cs_cmp(cx: &mut ExtCtxt<'_>, span: Span, substr: &Substructure<'_>) -> Bl |cx, fold| match fold { CsFold::Single(field) => { let [other_expr] = &field.other_selflike_exprs[..] else { - cx.span_bug(field.span, "not exactly 2 arguments in `derive(Ord)`"); - }; + cx.span_bug(field.span, "not exactly 2 arguments in `derive(Ord)`"); + }; let args = thin_vec![field.self_expr.clone(), other_expr.clone()]; cx.expr_call_global(field.span, cmp_path.clone(), args) } diff --git a/compiler/rustc_builtin_macros/src/deriving/cmp/partial_ord.rs b/compiler/rustc_builtin_macros/src/deriving/cmp/partial_ord.rs index 54b6cb7d713..a5b3a504e38 100644 --- a/compiler/rustc_builtin_macros/src/deriving/cmp/partial_ord.rs +++ b/compiler/rustc_builtin_macros/src/deriving/cmp/partial_ord.rs @@ -94,8 +94,8 @@ fn cs_partial_cmp( |cx, fold| match fold { CsFold::Single(field) => { let [other_expr] = &field.other_selflike_exprs[..] else { - cx.span_bug(field.span, "not exactly 2 arguments in `derive(Ord)`"); - }; + cx.span_bug(field.span, "not exactly 2 arguments in `derive(Ord)`"); + }; let args = thin_vec![field.self_expr.clone(), other_expr.clone()]; cx.expr_call_global(field.span, partial_cmp_path.clone(), args) } diff --git a/compiler/rustc_builtin_macros/src/env.rs b/compiler/rustc_builtin_macros/src/env.rs index 8f64e332861..bcff475f626 100644 --- a/compiler/rustc_builtin_macros/src/env.rs +++ b/compiler/rustc_builtin_macros/src/env.rs @@ -83,7 +83,12 @@ pub fn expand_env<'cx>( None => { // Use the string literal in the code in the diagnostic to avoid confusing diagnostics, // e.g. when the literal contains escape sequences. - let ast::ExprKind::Lit(ast::token::Lit { kind: ast::token::LitKind::Str, symbol: original_var, ..}) = &var_expr.kind else { + let ast::ExprKind::Lit(ast::token::Lit { + kind: ast::token::LitKind::Str, + symbol: original_var, + .. + }) = &var_expr.kind + else { unreachable!("`expr_to_string` ensures this is a string lit") }; cx.emit_err(errors::EnvNotDefined { diff --git a/compiler/rustc_builtin_macros/src/proc_macro_harness.rs b/compiler/rustc_builtin_macros/src/proc_macro_harness.rs index b35a2e2a292..a7908373b6d 100644 --- a/compiler/rustc_builtin_macros/src/proc_macro_harness.rs +++ b/compiler/rustc_builtin_macros/src/proc_macro_harness.rs @@ -89,7 +89,9 @@ impl<'a> CollectProcMacros<'a> { } fn collect_custom_derive(&mut self, item: &'a ast::Item, attr: &'a ast::Attribute) { - let Some((trait_name, proc_attrs)) = parse_macro_name_and_helper_attrs(self.handler, attr, "derive") else { + let Some((trait_name, proc_attrs)) = + parse_macro_name_and_helper_attrs(self.handler, attr, "derive") + else { return; }; diff --git a/compiler/rustc_builtin_macros/src/standard_library_imports.rs b/compiler/rustc_builtin_macros/src/standard_library_imports.rs index 6493c6f13d5..07e6288ed8c 100644 --- a/compiler/rustc_builtin_macros/src/standard_library_imports.rs +++ b/compiler/rustc_builtin_macros/src/standard_library_imports.rs @@ -44,20 +44,29 @@ pub fn inject( // .rev() to preserve ordering above in combination with insert(0, ...) for &name in names.iter().rev() { - let ident = if edition >= Edition2018 { - Ident::new(name, span) + let ident_span = if edition >= Edition2018 { span } else { call_site }; + let item = if name == sym::compiler_builtins { + // compiler_builtins is a private implementation detail. We only + // need to insert it into the crate graph for linking and should not + // expose any of its public API. + // + // FIXME(#113634) We should inject this during post-processing like + // we do for the panic runtime, profiler runtime, etc. + cx.item( + span, + Ident::new(kw::Underscore, ident_span), + thin_vec![], + ast::ItemKind::ExternCrate(Some(name)), + ) } else { - Ident::new(name, call_site) - }; - krate.items.insert( - 0, cx.item( span, - ident, + Ident::new(name, ident_span), thin_vec![cx.attr_word(sym::macro_use, span)], ast::ItemKind::ExternCrate(None), - ), - ); + ) + }; + krate.items.insert(0, item); } // The crates have been injected, the assumption is that the first one is diff --git a/compiler/rustc_codegen_cranelift/src/abi/comments.rs b/compiler/rustc_codegen_cranelift/src/abi/comments.rs index 364503fd363..ade6968de2b 100644 --- a/compiler/rustc_codegen_cranelift/src/abi/comments.rs +++ b/compiler/rustc_codegen_cranelift/src/abi/comments.rs @@ -80,14 +80,7 @@ pub(super) fn add_local_place_comments<'tcx>( return; } let TyAndLayout { ty, layout } = place.layout(); - let rustc_target::abi::LayoutS { - size, - align, - abi: _, - variants: _, - fields: _, - largest_niche: _, - } = layout.0.0; + let rustc_target::abi::LayoutS { size, align, .. } = layout.0.0; let (kind, extra) = place.debug_comment(); diff --git a/compiler/rustc_codegen_cranelift/src/abi/mod.rs b/compiler/rustc_codegen_cranelift/src/abi/mod.rs index 199fa6861cf..eddb479073c 100644 --- a/compiler/rustc_codegen_cranelift/src/abi/mod.rs +++ b/compiler/rustc_codegen_cranelift/src/abi/mod.rs @@ -70,7 +70,7 @@ pub(crate) fn get_function_sig<'tcx>( default_call_conv: CallConv, inst: Instance<'tcx>, ) -> Signature { - assert!(!inst.substs.has_infer()); + assert!(!inst.args.has_infer()); clif_sig_from_fn_abi( tcx, default_call_conv, @@ -377,16 +377,16 @@ pub(crate) fn codegen_terminator_call<'tcx>( let ret_place = codegen_place(fx, destination); // Handle special calls like intrinsics and empty drop glue. - let instance = if let ty::FnDef(def_id, substs) = *func.layout().ty.kind() { + let instance = if let ty::FnDef(def_id, fn_args) = *func.layout().ty.kind() { let instance = - ty::Instance::expect_resolve(fx.tcx, ty::ParamEnv::reveal_all(), def_id, substs) + ty::Instance::expect_resolve(fx.tcx, ty::ParamEnv::reveal_all(), def_id, fn_args) .polymorphize(fx.tcx); if fx.tcx.symbol_name(instance).name.starts_with("llvm.") { crate::intrinsics::codegen_llvm_intrinsic_call( fx, &fx.tcx.symbol_name(instance).name, - substs, + fn_args, args, ret_place, target, @@ -611,7 +611,7 @@ pub(crate) fn codegen_drop<'tcx>( // `Instance::resolve_drop_in_place`? let virtual_drop = Instance { def: ty::InstanceDef::Virtual(drop_instance.def_id(), 0), - substs: drop_instance.substs, + args: drop_instance.args, }; let fn_abi = RevealAllLayoutCx(fx.tcx).fn_abi_of_instance(virtual_drop, ty::List::empty()); @@ -648,7 +648,7 @@ pub(crate) fn codegen_drop<'tcx>( let virtual_drop = Instance { def: ty::InstanceDef::Virtual(drop_instance.def_id(), 0), - substs: drop_instance.substs, + args: drop_instance.args, }; let fn_abi = RevealAllLayoutCx(fx.tcx).fn_abi_of_instance(virtual_drop, ty::List::empty()); diff --git a/compiler/rustc_codegen_cranelift/src/base.rs b/compiler/rustc_codegen_cranelift/src/base.rs index 334b2780b49..e05f2146f0c 100644 --- a/compiler/rustc_codegen_cranelift/src/base.rs +++ b/compiler/rustc_codegen_cranelift/src/base.rs @@ -28,7 +28,7 @@ pub(crate) fn codegen_fn<'tcx>( module: &mut dyn Module, instance: Instance<'tcx>, ) -> CodegenedFunction { - debug_assert!(!instance.substs.has_infer()); + debug_assert!(!instance.args.has_infer()); let symbol_name = tcx.symbol_name(instance).name.to_string(); let _timer = tcx.prof.generic_activity_with_arg("codegen fn", &*symbol_name); @@ -578,13 +578,13 @@ fn codegen_stmt<'tcx>( let from_ty = fx.monomorphize(operand.ty(&fx.mir.local_decls, fx.tcx)); let to_layout = fx.layout_of(fx.monomorphize(to_ty)); match *from_ty.kind() { - ty::FnDef(def_id, substs) => { + ty::FnDef(def_id, args) => { let func_ref = fx.get_function_ref( Instance::resolve_for_fn_ptr( fx.tcx, ParamEnv::reveal_all(), def_id, - substs, + args, ) .unwrap() .polymorphize(fx.tcx), @@ -668,11 +668,11 @@ fn codegen_stmt<'tcx>( ) => { let operand = codegen_operand(fx, operand); match *operand.layout().ty.kind() { - ty::Closure(def_id, substs) => { + ty::Closure(def_id, args) => { let instance = Instance::resolve_closure( fx.tcx, def_id, - substs, + args, ty::ClosureKind::FnOnce, ) .expect("failed to normalize and resolve closure during codegen") diff --git a/compiler/rustc_codegen_cranelift/src/constant.rs b/compiler/rustc_codegen_cranelift/src/constant.rs index 427340c333e..c3153574295 100644 --- a/compiler/rustc_codegen_cranelift/src/constant.rs +++ b/compiler/rustc_codegen_cranelift/src/constant.rs @@ -57,7 +57,7 @@ pub(crate) fn codegen_tls_ref<'tcx>( let tls_ptr = if !def_id.is_local() && fx.tcx.needs_thread_local_shim(def_id) { let instance = ty::Instance { def: ty::InstanceDef::ThreadLocalShim(def_id), - substs: ty::InternalSubsts::empty(), + args: ty::GenericArgs::empty(), }; let func_ref = fx.get_function_ref(instance); let call = fx.bcx.ins().call(func_ref, &[]); diff --git a/compiler/rustc_codegen_cranelift/src/driver/mod.rs b/compiler/rustc_codegen_cranelift/src/driver/mod.rs index 5c52c9c18ad..12e90b58410 100644 --- a/compiler/rustc_codegen_cranelift/src/driver/mod.rs +++ b/compiler/rustc_codegen_cranelift/src/driver/mod.rs @@ -5,7 +5,7 @@ //! [`codegen_static`]: crate::constant::codegen_static use rustc_data_structures::profiling::SelfProfilerRef; -use rustc_middle::mir::mono::{Linkage as RLinkage, MonoItem, Visibility}; +use rustc_middle::mir::mono::{MonoItem, MonoItemData}; use crate::prelude::*; @@ -16,11 +16,11 @@ pub(crate) mod jit; fn predefine_mono_items<'tcx>( tcx: TyCtxt<'tcx>, module: &mut dyn Module, - mono_items: &[(MonoItem<'tcx>, (RLinkage, Visibility))], + mono_items: &[(MonoItem<'tcx>, MonoItemData)], ) { tcx.prof.generic_activity("predefine functions").run(|| { let is_compiler_builtins = tcx.is_compiler_builtins(LOCAL_CRATE); - for &(mono_item, (linkage, visibility)) in mono_items { + for &(mono_item, data) in mono_items { match mono_item { MonoItem::Fn(instance) => { let name = tcx.symbol_name(instance).name; @@ -29,8 +29,8 @@ fn predefine_mono_items<'tcx>( get_function_sig(tcx, module.target_config().default_call_conv, instance); let linkage = crate::linkage::get_clif_linkage( mono_item, - linkage, - visibility, + data.linkage, + data.visibility, is_compiler_builtins, ); module.declare_function(name, linkage, &sig).unwrap(); diff --git a/compiler/rustc_codegen_cranelift/src/global_asm.rs b/compiler/rustc_codegen_cranelift/src/global_asm.rs index 63a1f6959dd..baadd7a9e81 100644 --- a/compiler/rustc_codegen_cranelift/src/global_asm.rs +++ b/compiler/rustc_codegen_cranelift/src/global_asm.rs @@ -42,7 +42,7 @@ pub(crate) fn codegen_global_asm_item(tcx: TyCtxt<'_>, global_asm: &mut String, InlineAsmOperand::SymFn { anon_const } => { let ty = tcx.typeck_body(anon_const.body).node_type(anon_const.hir_id); let instance = match ty.kind() { - &ty::FnDef(def_id, substs) => Instance::new(def_id, substs), + &ty::FnDef(def_id, args) => Instance::new(def_id, args), _ => span_bug!(op_sp, "asm sym is not a function"), }; let symbol = tcx.symbol_name(instance); diff --git a/compiler/rustc_codegen_cranelift/src/inline_asm.rs b/compiler/rustc_codegen_cranelift/src/inline_asm.rs index 3ba530c040f..518e3da07a4 100644 --- a/compiler/rustc_codegen_cranelift/src/inline_asm.rs +++ b/compiler/rustc_codegen_cranelift/src/inline_asm.rs @@ -254,12 +254,12 @@ pub(crate) fn codegen_inline_asm<'tcx>( } InlineAsmOperand::SymFn { ref value } => { let literal = fx.monomorphize(value.literal); - if let ty::FnDef(def_id, substs) = *literal.ty().kind() { + if let ty::FnDef(def_id, args) = *literal.ty().kind() { let instance = ty::Instance::resolve_for_fn_ptr( fx.tcx, ty::ParamEnv::reveal_all(), def_id, - substs, + args, ) .unwrap(); let symbol = fx.tcx.symbol_name(instance); diff --git a/compiler/rustc_codegen_cranelift/src/intrinsics/llvm.rs b/compiler/rustc_codegen_cranelift/src/intrinsics/llvm.rs index f67fdb59270..63b5402f2b6 100644 --- a/compiler/rustc_codegen_cranelift/src/intrinsics/llvm.rs +++ b/compiler/rustc_codegen_cranelift/src/intrinsics/llvm.rs @@ -3,23 +3,35 @@ use crate::intrinsics::*; use crate::prelude::*; -use rustc_middle::ty::subst::SubstsRef; +use rustc_middle::ty::GenericArgsRef; pub(crate) fn codegen_llvm_intrinsic_call<'tcx>( fx: &mut FunctionCx<'_, '_, 'tcx>, intrinsic: &str, - substs: SubstsRef<'tcx>, + generic_args: GenericArgsRef<'tcx>, args: &[mir::Operand<'tcx>], ret: CPlace<'tcx>, target: Option<BasicBlock>, ) { if intrinsic.starts_with("llvm.aarch64") { return llvm_aarch64::codegen_aarch64_llvm_intrinsic_call( - fx, intrinsic, substs, args, ret, target, + fx, + intrinsic, + generic_args, + args, + ret, + target, ); } if intrinsic.starts_with("llvm.x86") { - return llvm_x86::codegen_x86_llvm_intrinsic_call(fx, intrinsic, substs, args, ret, target); + return llvm_x86::codegen_x86_llvm_intrinsic_call( + fx, + intrinsic, + generic_args, + args, + ret, + target, + ); } match intrinsic { diff --git a/compiler/rustc_codegen_cranelift/src/intrinsics/llvm_aarch64.rs b/compiler/rustc_codegen_cranelift/src/intrinsics/llvm_aarch64.rs index 33b2f4702a7..c20a9915930 100644 --- a/compiler/rustc_codegen_cranelift/src/intrinsics/llvm_aarch64.rs +++ b/compiler/rustc_codegen_cranelift/src/intrinsics/llvm_aarch64.rs @@ -3,12 +3,12 @@ use crate::intrinsics::*; use crate::prelude::*; -use rustc_middle::ty::subst::SubstsRef; +use rustc_middle::ty::GenericArgsRef; pub(crate) fn codegen_aarch64_llvm_intrinsic_call<'tcx>( fx: &mut FunctionCx<'_, '_, 'tcx>, intrinsic: &str, - _substs: SubstsRef<'tcx>, + _args: GenericArgsRef<'tcx>, args: &[mir::Operand<'tcx>], ret: CPlace<'tcx>, target: Option<BasicBlock>, diff --git a/compiler/rustc_codegen_cranelift/src/intrinsics/llvm_x86.rs b/compiler/rustc_codegen_cranelift/src/intrinsics/llvm_x86.rs index 24ad0083a22..18162fb5ab2 100644 --- a/compiler/rustc_codegen_cranelift/src/intrinsics/llvm_x86.rs +++ b/compiler/rustc_codegen_cranelift/src/intrinsics/llvm_x86.rs @@ -3,12 +3,12 @@ use crate::intrinsics::*; use crate::prelude::*; -use rustc_middle::ty::subst::SubstsRef; +use rustc_middle::ty::GenericArgsRef; pub(crate) fn codegen_x86_llvm_intrinsic_call<'tcx>( fx: &mut FunctionCx<'_, '_, 'tcx>, intrinsic: &str, - _substs: SubstsRef<'tcx>, + _args: GenericArgsRef<'tcx>, args: &[mir::Operand<'tcx>], ret: CPlace<'tcx>, target: Option<BasicBlock>, diff --git a/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs b/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs index 5862f18299e..da8ab361331 100644 --- a/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs +++ b/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs @@ -24,7 +24,7 @@ pub(crate) use llvm::codegen_llvm_intrinsic_call; use rustc_middle::ty; use rustc_middle::ty::layout::{HasParamEnv, ValidityRequirement}; use rustc_middle::ty::print::{with_no_trimmed_paths, with_no_visible_paths}; -use rustc_middle::ty::subst::SubstsRef; +use rustc_middle::ty::GenericArgsRef; use rustc_span::symbol::{kw, sym, Symbol}; use crate::prelude::*; @@ -213,13 +213,13 @@ pub(crate) fn codegen_intrinsic_call<'tcx>( source_info: mir::SourceInfo, ) { let intrinsic = fx.tcx.item_name(instance.def_id()); - let substs = instance.substs; + let instance_args = instance.args; if intrinsic.as_str().starts_with("simd_") { self::simd::codegen_simd_intrinsic_call( fx, intrinsic, - substs, + instance_args, args, destination, target.expect("target for simd intrinsic"), @@ -233,7 +233,7 @@ pub(crate) fn codegen_intrinsic_call<'tcx>( fx, instance, intrinsic, - substs, + instance_args, args, destination, target, @@ -365,7 +365,7 @@ fn codegen_regular_intrinsic_call<'tcx>( fx: &mut FunctionCx<'_, '_, 'tcx>, instance: Instance<'tcx>, intrinsic: Symbol, - substs: SubstsRef<'tcx>, + generic_args: GenericArgsRef<'tcx>, args: &[mir::Operand<'tcx>], ret: CPlace<'tcx>, destination: Option<BasicBlock>, @@ -394,7 +394,7 @@ fn codegen_regular_intrinsic_call<'tcx>( let dst = dst.load_scalar(fx); let count = count.load_scalar(fx); - let elem_ty = substs.type_at(0); + let elem_ty = generic_args.type_at(0); let elem_size: u64 = fx.layout_of(elem_ty).size.bytes(); assert_eq!(args.len(), 3); let byte_amount = @@ -410,7 +410,7 @@ fn codegen_regular_intrinsic_call<'tcx>( let src = src.load_scalar(fx); let count = count.load_scalar(fx); - let elem_ty = substs.type_at(0); + let elem_ty = generic_args.type_at(0); let elem_size: u64 = fx.layout_of(elem_ty).size.bytes(); assert_eq!(args.len(), 3); let byte_amount = @@ -428,7 +428,7 @@ fn codegen_regular_intrinsic_call<'tcx>( sym::size_of_val => { intrinsic_args!(fx, args => (ptr); intrinsic); - let layout = fx.layout_of(substs.type_at(0)); + let layout = fx.layout_of(generic_args.type_at(0)); // Note: Can't use is_unsized here as truly unsized types need to take the fixed size // branch let size = if let Abi::ScalarPair(_, _) = ptr.layout().abi { @@ -443,7 +443,7 @@ fn codegen_regular_intrinsic_call<'tcx>( sym::min_align_of_val => { intrinsic_args!(fx, args => (ptr); intrinsic); - let layout = fx.layout_of(substs.type_at(0)); + let layout = fx.layout_of(generic_args.type_at(0)); // Note: Can't use is_unsized here as truly unsized types need to take the fixed size // branch let align = if let Abi::ScalarPair(_, _) = ptr.layout().abi { @@ -602,7 +602,7 @@ fn codegen_regular_intrinsic_call<'tcx>( sym::assert_inhabited | sym::assert_zero_valid | sym::assert_mem_uninitialized_valid => { intrinsic_args!(fx, args => (); intrinsic); - let ty = substs.type_at(0); + let ty = generic_args.type_at(0); let requirement = ValidityRequirement::from_intrinsic(intrinsic); @@ -674,7 +674,7 @@ fn codegen_regular_intrinsic_call<'tcx>( intrinsic_args!(fx, args => (ptr, base); intrinsic); let ptr = ptr.load_scalar(fx); let base = base.load_scalar(fx); - let ty = substs.type_at(0); + let ty = generic_args.type_at(0); let pointee_size: u64 = fx.layout_of(ty).size.bytes(); let diff_bytes = fx.bcx.ins().isub(ptr, base); @@ -720,7 +720,7 @@ fn codegen_regular_intrinsic_call<'tcx>( intrinsic_args!(fx, args => (ptr); intrinsic); let ptr = ptr.load_scalar(fx); - let ty = substs.type_at(0); + let ty = generic_args.type_at(0); match ty.kind() { ty::Uint(UintTy::U128) | ty::Int(IntTy::I128) => { // FIXME implement 128bit atomics @@ -751,7 +751,7 @@ fn codegen_regular_intrinsic_call<'tcx>( intrinsic_args!(fx, args => (ptr, val); intrinsic); let ptr = ptr.load_scalar(fx); - let ty = substs.type_at(0); + let ty = generic_args.type_at(0); match ty.kind() { ty::Uint(UintTy::U128) | ty::Int(IntTy::I128) => { // FIXME implement 128bit atomics @@ -1128,7 +1128,7 @@ fn codegen_regular_intrinsic_call<'tcx>( let lhs_ref = lhs_ref.load_scalar(fx); let rhs_ref = rhs_ref.load_scalar(fx); - let size = fx.layout_of(substs.type_at(0)).layout.size(); + let size = fx.layout_of(generic_args.type_at(0)).layout.size(); // FIXME add and use emit_small_memcmp let is_eq_value = if size == Size::ZERO { // No bytes means they're trivially equal diff --git a/compiler/rustc_codegen_cranelift/src/intrinsics/simd.rs b/compiler/rustc_codegen_cranelift/src/intrinsics/simd.rs index 6741362e8b6..d1c29f24ab9 100644 --- a/compiler/rustc_codegen_cranelift/src/intrinsics/simd.rs +++ b/compiler/rustc_codegen_cranelift/src/intrinsics/simd.rs @@ -1,6 +1,6 @@ //! Codegen `extern "platform-intrinsic"` intrinsics. -use rustc_middle::ty::subst::SubstsRef; +use rustc_middle::ty::GenericArgsRef; use rustc_span::Symbol; use rustc_target::abi::Endian; @@ -21,7 +21,7 @@ fn report_simd_type_validation_error( pub(super) fn codegen_simd_intrinsic_call<'tcx>( fx: &mut FunctionCx<'_, '_, 'tcx>, intrinsic: Symbol, - _substs: SubstsRef<'tcx>, + _args: GenericArgsRef<'tcx>, args: &[mir::Operand<'tcx>], ret: CPlace<'tcx>, target: BasicBlock, diff --git a/compiler/rustc_codegen_cranelift/src/main_shim.rs b/compiler/rustc_codegen_cranelift/src/main_shim.rs index 20ba73f3852..b5efe44d8b3 100644 --- a/compiler/rustc_codegen_cranelift/src/main_shim.rs +++ b/compiler/rustc_codegen_cranelift/src/main_shim.rs @@ -1,6 +1,6 @@ use rustc_hir::LangItem; -use rustc_middle::ty::subst::GenericArg; use rustc_middle::ty::AssocKind; +use rustc_middle::ty::GenericArg; use rustc_session::config::{sigpipe, EntryFnType}; use rustc_span::symbol::Ident; @@ -119,7 +119,7 @@ pub(crate) fn maybe_create_entry_wrapper( tcx, ParamEnv::reveal_all(), report.def_id, - tcx.mk_substs(&[GenericArg::from(main_ret_ty)]), + tcx.mk_args(&[GenericArg::from(main_ret_ty)]), ) .unwrap() .unwrap() @@ -146,7 +146,7 @@ pub(crate) fn maybe_create_entry_wrapper( tcx, ParamEnv::reveal_all(), start_def_id, - tcx.mk_substs(&[main_ret_ty.into()]), + tcx.mk_args(&[main_ret_ty.into()]), ) .unwrap() .unwrap() diff --git a/compiler/rustc_codegen_cranelift/src/pretty_clif.rs b/compiler/rustc_codegen_cranelift/src/pretty_clif.rs index 5a4f9e80445..0ead50c34ea 100644 --- a/compiler/rustc_codegen_cranelift/src/pretty_clif.rs +++ b/compiler/rustc_codegen_cranelift/src/pretty_clif.rs @@ -9,7 +9,7 @@ //! //! function u0:22(i64) -> i8, i8 system_v { //! ; symbol _ZN97_$LT$example..IsNotEmpty$u20$as$u20$mini_core..FnOnce$LT$$LP$$RF$$RF$$u5b$u16$u5d$$C$$RP$$GT$$GT$9call_once17hd517c453d67c0915E -//! ; instance Instance { def: Item(WithOptConstParam { did: DefId(0:42 ~ example[4e51]::{impl#0}::call_once), const_param_did: None }), substs: [ReErased, ReErased] } +//! ; instance Instance { def: Item(WithOptConstParam { did: DefId(0:42 ~ example[4e51]::{impl#0}::call_once), const_param_did: None }), args: [ReErased, ReErased] } //! ; abi FnAbi { args: [ArgAbi { layout: TyAndLayout { ty: IsNotEmpty, layout: Layout { size: Size(0 bytes), align: AbiAndPrefAlign { abi: Align(1 bytes), pref: Align(8 bytes) }, abi: Aggregate { sized: true }, fields: Arbitrary { offsets: [], memory_index: [] }, largest_niche: None, variants: Single { index: 0 } } }, mode: Ignore }, ArgAbi { layout: TyAndLayout { ty: &&[u16], layout: Layout { size: Size(8 bytes), align: AbiAndPrefAlign { abi: Align(8 bytes), pref: Align(8 bytes) }, abi: Scalar(Initialized { value: Pointer(AddressSpace(0)), valid_range: 1..=18446744073709551615 }), fields: Primitive, largest_niche: Some(Niche { offset: Size(0 bytes), value: Pointer(AddressSpace(0)), valid_range: 1..=18446744073709551615 }), variants: Single { index: 0 } } }, mode: Direct(ArgAttributes { regular: NonNull | NoUndef, arg_ext: None, pointee_size: Size(0 bytes), pointee_align: Some(Align(8 bytes)) }) }], ret: ArgAbi { layout: TyAndLayout { ty: (u8, u8), layout: Layout { size: Size(2 bytes), align: AbiAndPrefAlign { abi: Align(1 bytes), pref: Align(8 bytes) }, abi: ScalarPair(Initialized { value: Int(I8, false), valid_range: 0..=255 }, Initialized { value: Int(I8, false), valid_range: 0..=255 }), fields: Arbitrary { offsets: [Size(0 bytes), Size(1 bytes)], memory_index: [0, 1] }, largest_niche: None, variants: Single { index: 0 } } }, mode: Pair(ArgAttributes { regular: NoUndef, arg_ext: None, pointee_size: Size(0 bytes), pointee_align: None }, ArgAttributes { regular: NoUndef, arg_ext: None, pointee_size: Size(0 bytes), pointee_align: None }) }, c_variadic: false, fixed_count: 1, conv: Rust, can_unwind: false } //! //! ; kind loc.idx param pass mode ty @@ -25,7 +25,7 @@ //! //! ss0 = explicit_slot 16 //! sig0 = (i64, i64) -> i8, i8 system_v -//! fn0 = colocated u0:23 sig0 ; Instance { def: Item(WithOptConstParam { did: DefId(0:46 ~ example[4e51]::{impl#1}::call_mut), const_param_did: None }), substs: [ReErased, ReErased] } +//! fn0 = colocated u0:23 sig0 ; Instance { def: Item(WithOptConstParam { did: DefId(0:46 ~ example[4e51]::{impl#1}::call_mut), const_param_did: None }), args: [ReErased, ReErased] } //! //! block0(v0: i64): //! nop @@ -261,7 +261,7 @@ pub(crate) fn write_clif_file( impl fmt::Debug for FunctionCx<'_, '_, '_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - writeln!(f, "{:?}", self.instance.substs)?; + writeln!(f, "{:?}", self.instance.args)?; writeln!(f, "{:?}", self.local_map)?; let mut clif = String::new(); diff --git a/compiler/rustc_codegen_cranelift/src/value_and_place.rs b/compiler/rustc_codegen_cranelift/src/value_and_place.rs index 133c989b686..ec0b61a7ce5 100644 --- a/compiler/rustc_codegen_cranelift/src/value_and_place.rs +++ b/compiler/rustc_codegen_cranelift/src/value_and_place.rs @@ -850,11 +850,11 @@ pub(crate) fn assert_assignable<'tcx>( } } } - (&ty::Adt(adt_def_a, substs_a), &ty::Adt(adt_def_b, substs_b)) + (&ty::Adt(adt_def_a, args_a), &ty::Adt(adt_def_b, args_b)) if adt_def_a.did() == adt_def_b.did() => { - let mut types_a = substs_a.types(); - let mut types_b = substs_b.types(); + let mut types_a = args_a.types(); + let mut types_b = args_b.types(); loop { match (types_a.next(), types_b.next()) { (Some(a), Some(b)) => assert_assignable(fx, a, b, limit - 1), @@ -864,11 +864,11 @@ pub(crate) fn assert_assignable<'tcx>( } } (ty::Array(a, _), ty::Array(b, _)) => assert_assignable(fx, *a, *b, limit - 1), - (&ty::Closure(def_id_a, substs_a), &ty::Closure(def_id_b, substs_b)) + (&ty::Closure(def_id_a, args_a), &ty::Closure(def_id_b, args_b)) if def_id_a == def_id_b => { - let mut types_a = substs_a.types(); - let mut types_b = substs_b.types(); + let mut types_a = args_a.types(); + let mut types_b = args_b.types(); loop { match (types_a.next(), types_b.next()) { (Some(a), Some(b)) => assert_assignable(fx, a, b, limit - 1), diff --git a/compiler/rustc_codegen_gcc/src/base.rs b/compiler/rustc_codegen_gcc/src/base.rs index dcd560b3dcd..9e614ca4ace 100644 --- a/compiler/rustc_codegen_gcc/src/base.rs +++ b/compiler/rustc_codegen_gcc/src/base.rs @@ -159,8 +159,8 @@ pub fn compile_codegen_unit(tcx: TyCtxt<'_>, cgu_name: Symbol, supports_128bit_i let cx = CodegenCx::new(&context, cgu, tcx, supports_128bit_integers); let mono_items = cgu.items_in_deterministic_order(tcx); - for &(mono_item, (linkage, visibility)) in &mono_items { - mono_item.predefine::<Builder<'_, '_, '_>>(&cx, linkage, visibility); + for &(mono_item, data) in &mono_items { + mono_item.predefine::<Builder<'_, '_, '_>>(&cx, data.linkage, data.visibility); } // ... and now that we have everything pre-defined, fill out those definitions. diff --git a/compiler/rustc_codegen_gcc/src/callee.rs b/compiler/rustc_codegen_gcc/src/callee.rs index 433b2585f82..a96bd66ba79 100644 --- a/compiler/rustc_codegen_gcc/src/callee.rs +++ b/compiler/rustc_codegen_gcc/src/callee.rs @@ -17,8 +17,8 @@ use crate::context::CodegenCx; pub fn get_fn<'gcc, 'tcx>(cx: &CodegenCx<'gcc, 'tcx>, instance: Instance<'tcx>) -> Function<'gcc> { let tcx = cx.tcx(); - assert!(!instance.substs.has_infer()); - assert!(!instance.substs.has_escaping_bound_vars()); + assert!(!instance.args.has_infer()); + assert!(!instance.args.has_escaping_bound_vars()); let sym = tcx.symbol_name(instance).name; @@ -100,7 +100,7 @@ pub fn get_fn<'gcc, 'tcx>(cx: &CodegenCx<'gcc, 'tcx>, instance: Instance<'tcx>) // whether we are sharing generics or not. The important thing here is // that the visibility we apply to the declaration is the same one that // has been applied to the definition (wherever that definition may be). - let is_generic = instance.substs.non_erasable_generics().next().is_some(); + let is_generic = instance.args.non_erasable_generics().next().is_some(); if is_generic { // This is a monomorphization. Its expected visibility depends diff --git a/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs b/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs index 0b208be4e62..fe604be33b6 100644 --- a/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs +++ b/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs @@ -92,8 +92,8 @@ impl<'a, 'gcc, 'tcx> IntrinsicCallMethods<'tcx> for Builder<'a, 'gcc, 'tcx> { let tcx = self.tcx; let callee_ty = instance.ty(tcx, ty::ParamEnv::reveal_all()); - let (def_id, substs) = match *callee_ty.kind() { - ty::FnDef(def_id, substs) => (def_id, substs), + let (def_id, fn_args) = match *callee_ty.kind() { + ty::FnDef(def_id, fn_args) => (def_id, fn_args), _ => bug!("expected fn item type, found {}", callee_ty), }; @@ -142,7 +142,7 @@ impl<'a, 'gcc, 'tcx> IntrinsicCallMethods<'tcx> for Builder<'a, 'gcc, 'tcx> { } sym::volatile_load | sym::unaligned_volatile_load => { - let tp_ty = substs.type_at(0); + let tp_ty = fn_args.type_at(0); let mut ptr = args[0].immediate(); if let PassMode::Cast(ty, _) = &fn_abi.ret.mode { ptr = self.pointercast(ptr, self.type_ptr_to(ty.gcc_type(self))); @@ -264,7 +264,7 @@ impl<'a, 'gcc, 'tcx> IntrinsicCallMethods<'tcx> for Builder<'a, 'gcc, 'tcx> { sym::raw_eq => { use rustc_target::abi::Abi::*; - let tp_ty = substs.type_at(0); + let tp_ty = fn_args.type_at(0); let layout = self.layout_of(tp_ty).layout; let _use_integer_compare = match layout.abi() { Scalar(_) | ScalarPair(_, _) => true, diff --git a/compiler/rustc_codegen_gcc/src/mono_item.rs b/compiler/rustc_codegen_gcc/src/mono_item.rs index 342b830cedb..3322d56513b 100644 --- a/compiler/rustc_codegen_gcc/src/mono_item.rs +++ b/compiler/rustc_codegen_gcc/src/mono_item.rs @@ -31,7 +31,7 @@ impl<'gcc, 'tcx> PreDefineMethods<'tcx> for CodegenCx<'gcc, 'tcx> { #[cfg_attr(not(feature="master"), allow(unused_variables))] fn predefine_fn(&self, instance: Instance<'tcx>, linkage: Linkage, visibility: Visibility, symbol_name: &str) { - assert!(!instance.substs.has_infer()); + assert!(!instance.args.has_infer()); let fn_abi = self.fn_abi_of_instance(instance, ty::List::empty()); self.linkage.set(base::linkage_to_gcc(linkage)); diff --git a/compiler/rustc_codegen_gcc/src/type_of.rs b/compiler/rustc_codegen_gcc/src/type_of.rs index e0823888f67..84d57838512 100644 --- a/compiler/rustc_codegen_gcc/src/type_of.rs +++ b/compiler/rustc_codegen_gcc/src/type_of.rs @@ -101,7 +101,7 @@ fn uncached_gcc_type<'gcc, 'tcx>(cx: &CodegenCx<'gcc, 'tcx>, layout: TyAndLayout if let (&ty::Generator(_, _, _), &Variants::Single { index }) = (layout.ty.kind(), &layout.variants) { - write!(&mut name, "::{}", ty::GeneratorSubsts::variant_name(index)).unwrap(); + write!(&mut name, "::{}", ty::GeneratorArgs::variant_name(index)).unwrap(); } Some(name) } @@ -282,7 +282,7 @@ impl<'tcx> LayoutGccExt<'tcx> for TyAndLayout<'tcx> { } // only wide pointer boxes are handled as pointers // thin pointer boxes with scalar allocators are handled by the general logic below - ty::Adt(def, substs) if def.is_box() && cx.layout_of(substs.type_at(1)).is_zst() => { + ty::Adt(def, args) if def.is_box() && cx.layout_of(args.type_at(1)).is_zst() => { let ptr_ty = Ty::new_mut_ptr(cx.tcx,self.ty.boxed_ty()); return cx.layout_of(ptr_ty).scalar_pair_element_gcc_type(cx, index, immediate); } diff --git a/compiler/rustc_codegen_llvm/src/base.rs b/compiler/rustc_codegen_llvm/src/base.rs index 5b2bbdb4bde..5b5f81c0329 100644 --- a/compiler/rustc_codegen_llvm/src/base.rs +++ b/compiler/rustc_codegen_llvm/src/base.rs @@ -86,8 +86,8 @@ pub fn compile_codegen_unit(tcx: TyCtxt<'_>, cgu_name: Symbol) -> (ModuleCodegen { let cx = CodegenCx::new(tcx, cgu, &llvm_module); let mono_items = cx.codegen_unit.items_in_deterministic_order(cx.tcx); - for &(mono_item, (linkage, visibility)) in &mono_items { - mono_item.predefine::<Builder<'_, '_, '_>>(&cx, linkage, visibility); + for &(mono_item, data) in &mono_items { + mono_item.predefine::<Builder<'_, '_, '_>>(&cx, data.linkage, data.visibility); } // ... and now that we have everything pre-defined, fill out those definitions. diff --git a/compiler/rustc_codegen_llvm/src/callee.rs b/compiler/rustc_codegen_llvm/src/callee.rs index 4b9ca2e7d19..5d3e245f45f 100644 --- a/compiler/rustc_codegen_llvm/src/callee.rs +++ b/compiler/rustc_codegen_llvm/src/callee.rs @@ -27,8 +27,8 @@ pub fn get_fn<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>, instance: Instance<'tcx>) -> debug!("get_fn(instance={:?})", instance); - assert!(!instance.substs.has_infer()); - assert!(!instance.substs.has_escaping_bound_vars()); + assert!(!instance.args.has_infer()); + assert!(!instance.args.has_escaping_bound_vars()); if let Some(&llfn) = cx.instances.borrow().get(&instance) { return llfn; @@ -129,7 +129,7 @@ pub fn get_fn<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>, instance: Instance<'tcx>) -> unsafe { llvm::LLVMRustSetLinkage(llfn, llvm::Linkage::ExternalLinkage); - let is_generic = instance.substs.non_erasable_generics().next().is_some(); + let is_generic = instance.args.non_erasable_generics().next().is_some(); if is_generic { // This is a monomorphization. Its expected visibility depends diff --git a/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs b/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs index a1ff2aa6625..6e815ab3ff5 100644 --- a/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs +++ b/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs @@ -63,7 +63,7 @@ pub fn finalize(cx: &CodegenCx<'_, '_>) { let mut function_data = Vec::new(); for (instance, function_coverage) in function_coverage_map { debug!("Generate function coverage for {}, {:?}", cx.codegen_unit.name(), instance); - let mangled_function_name = tcx.symbol_name(instance).to_string(); + let mangled_function_name = tcx.symbol_name(instance).name; let source_hash = function_coverage.source_hash(); let is_used = function_coverage.is_used(); let (expressions, counter_regions) = @@ -95,7 +95,7 @@ pub fn finalize(cx: &CodegenCx<'_, '_>) { let filenames_size = filenames_buffer.len(); let filenames_val = cx.const_bytes(&filenames_buffer); - let filenames_ref = coverageinfo::hash_bytes(filenames_buffer); + let filenames_ref = coverageinfo::hash_bytes(&filenames_buffer); // Generate the LLVM IR representation of the coverage map and store it in a well-known global let cov_data_val = mapgen.generate_coverage_map(cx, version, filenames_size, filenames_val); @@ -228,7 +228,7 @@ impl CoverageMapGenerator { /// specific, well-known section and name. fn save_function_record( cx: &CodegenCx<'_, '_>, - mangled_function_name: String, + mangled_function_name: &str, source_hash: u64, filenames_ref: u64, coverage_mapping_buffer: Vec<u8>, @@ -238,7 +238,7 @@ fn save_function_record( let coverage_mapping_size = coverage_mapping_buffer.len(); let coverage_mapping_val = cx.const_bytes(&coverage_mapping_buffer); - let func_name_hash = coverageinfo::hash_str(&mangled_function_name); + let func_name_hash = coverageinfo::hash_bytes(mangled_function_name.as_bytes()); let func_name_hash_val = cx.const_u64(func_name_hash); let coverage_mapping_size_val = cx.const_u32(coverage_mapping_size as u32); let source_hash_val = cx.const_u64(source_hash); diff --git a/compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs b/compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs index 42fdbd78618..1f8f4033931 100644 --- a/compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs +++ b/compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs @@ -22,7 +22,7 @@ use rustc_middle::mir::coverage::{ use rustc_middle::mir::Coverage; use rustc_middle::ty; use rustc_middle::ty::layout::{FnAbiOf, HasTyCtxt}; -use rustc_middle::ty::subst::InternalSubsts; +use rustc_middle::ty::GenericArgs; use rustc_middle::ty::Instance; use rustc_middle::ty::Ty; @@ -250,7 +250,7 @@ fn declare_unused_fn<'tcx>(cx: &CodegenCx<'_, 'tcx>, def_id: DefId) -> Instance< let instance = Instance::new( def_id, - InternalSubsts::for_item(tcx, def_id, |param, _| { + GenericArgs::for_item(tcx, def_id, |param, _| { if let ty::GenericParamDefKind::Lifetime = param.kind { tcx.lifetimes.re_erased.into() } else { @@ -373,12 +373,7 @@ pub(crate) fn write_mapping_to_buffer( } } -pub(crate) fn hash_str(strval: &str) -> u64 { - let strval = CString::new(strval).expect("null error converting hashable str to C string"); - unsafe { llvm::LLVMRustCoverageHashCString(strval.as_ptr()) } -} - -pub(crate) fn hash_bytes(bytes: Vec<u8>) -> u64 { +pub(crate) fn hash_bytes(bytes: &[u8]) -> u64 { unsafe { llvm::LLVMRustCoverageHashByteArray(bytes.as_ptr().cast(), bytes.len()) } } diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/create_scope_map.rs b/compiler/rustc_codegen_llvm/src/debuginfo/create_scope_map.rs index 65cbd5edc59..d174a3593b9 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/create_scope_map.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/create_scope_map.rs @@ -91,7 +91,7 @@ fn make_mir_scope<'ll, 'tcx>( // FIXME(eddyb) this would be `self.monomorphize(&callee)` // if this is moved to `rustc_codegen_ssa::mir::debuginfo`. let callee = cx.tcx.subst_and_normalize_erasing_regions( - instance.substs, + instance.args, ty::ParamEnv::reveal_all(), ty::EarlyBinder::bind(callee), ); diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs b/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs index d61400d3fa3..c6996f2e16a 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs @@ -449,7 +449,7 @@ pub fn type_di_node<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>) -> &'ll D } // Box<T, A> may have a non-ZST allocator A. In that case, we // cannot treat Box<T, A> as just an owned alias of `*mut T`. - ty::Adt(def, substs) if def.is_box() && cx.layout_of(substs.type_at(1)).is_zst() => { + ty::Adt(def, args) if def.is_box() && cx.layout_of(args.type_at(1)).is_zst() => { build_pointer_or_reference_di_node(cx, t, t.boxed_ty(), unique_type_id) } ty::FnDef(..) | ty::FnPtr(_) => build_subroutine_type_di_node(cx, unique_type_id), @@ -739,7 +739,10 @@ fn build_foreign_type_di_node<'ll, 'tcx>( debug!("build_foreign_type_di_node: {:?}", t); let &ty::Foreign(def_id) = unique_type_id.expect_ty().kind() else { - bug!("build_foreign_type_di_node() called with unexpected type: {:?}", unique_type_id.expect_ty()); + bug!( + "build_foreign_type_di_node() called with unexpected type: {:?}", + unique_type_id.expect_ty() + ); }; build_type_with_children( @@ -1004,12 +1007,12 @@ fn build_upvar_field_di_nodes<'ll, 'tcx>( closure_or_generator_di_node: &'ll DIType, ) -> SmallVec<&'ll DIType> { let (&def_id, up_var_tys) = match closure_or_generator_ty.kind() { - ty::Generator(def_id, substs, _) => { - let upvar_tys: SmallVec<_> = substs.as_generator().prefix_tys().collect(); + ty::Generator(def_id, args, _) => { + let upvar_tys: SmallVec<_> = args.as_generator().prefix_tys().collect(); (def_id, upvar_tys) } - ty::Closure(def_id, substs) => { - let upvar_tys: SmallVec<_> = substs.as_closure().upvar_tys().collect(); + ty::Closure(def_id, args) => { + let upvar_tys: SmallVec<_> = args.as_closure().upvar_tys().collect(); (def_id, upvar_tys) } _ => { @@ -1099,7 +1102,7 @@ fn build_closure_env_di_node<'ll, 'tcx>( unique_type_id: UniqueTypeId<'tcx>, ) -> DINodeCreationResult<'ll> { let closure_env_type = unique_type_id.expect_ty(); - let &ty::Closure(def_id, _substs) = closure_env_type.kind() else { + let &ty::Closure(def_id, _args) = closure_env_type.kind() else { bug!("build_closure_env_di_node() called with non-closure-type: {:?}", closure_env_type) }; let containing_scope = get_namespace_for_item(cx, def_id); @@ -1177,11 +1180,11 @@ fn build_generic_type_param_di_nodes<'ll, 'tcx>( cx: &CodegenCx<'ll, 'tcx>, ty: Ty<'tcx>, ) -> SmallVec<&'ll DIType> { - if let ty::Adt(def, substs) = *ty.kind() { - if substs.types().next().is_some() { + if let ty::Adt(def, args) = *ty.kind() { + if args.types().next().is_some() { let generics = cx.tcx.generics_of(def.did()); let names = get_parameter_names(cx, generics); - let template_params: SmallVec<_> = iter::zip(substs, names) + let template_params: SmallVec<_> = iter::zip(args, names) .filter_map(|(kind, name)| { kind.as_type().map(|ty| { let actual_type = diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/cpp_like.rs b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/cpp_like.rs index b2765ffc934..88040557a9b 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/cpp_like.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/cpp_like.rs @@ -12,7 +12,7 @@ use rustc_middle::{ ty::{ self, layout::{LayoutOf, TyAndLayout}, - AdtDef, GeneratorSubsts, Ty, + AdtDef, GeneratorArgs, Ty, }, }; use rustc_target::abi::{Align, Endian, Size, TagEncoding, VariantIdx, Variants}; @@ -199,7 +199,7 @@ pub(super) fn build_enum_type_di_node<'ll, 'tcx>( let enum_type = unique_type_id.expect_ty(); let &ty::Adt(enum_adt_def, _) = enum_type.kind() else { bug!("build_enum_type_di_node() called with non-enum type: `{:?}`", enum_type) - }; + }; let enum_type_and_layout = cx.layout_of(enum_type); let enum_type_name = compute_debuginfo_type_name(cx.tcx, enum_type, false); @@ -667,19 +667,21 @@ fn build_union_fields_for_direct_tag_generator<'ll, 'tcx>( generator_type_and_layout: TyAndLayout<'tcx>, generator_type_di_node: &'ll DIType, ) -> SmallVec<&'ll DIType> { - let Variants::Multiple { tag_encoding: TagEncoding::Direct, tag_field, .. } = generator_type_and_layout.variants else { + let Variants::Multiple { tag_encoding: TagEncoding::Direct, tag_field, .. } = + generator_type_and_layout.variants + else { bug!("This function only supports layouts with directly encoded tags.") }; - let (generator_def_id, generator_substs) = match generator_type_and_layout.ty.kind() { - &ty::Generator(def_id, substs, _) => (def_id, substs.as_generator()), + let (generator_def_id, generator_args) = match generator_type_and_layout.ty.kind() { + &ty::Generator(def_id, args, _) => (def_id, args.as_generator()), _ => unreachable!(), }; let generator_layout = cx.tcx.optimized_mir(generator_def_id).generator_layout().unwrap(); let common_upvar_names = cx.tcx.closure_saved_names_of_captured_variables(generator_def_id); - let variant_range = generator_substs.variant_range(generator_def_id, cx.tcx); + let variant_range = generator_args.variant_range(generator_def_id, cx.tcx); let variant_count = (variant_range.start.as_u32()..variant_range.end.as_u32()).len(); let tag_base_type = tag_base_type(cx, generator_type_and_layout); @@ -689,11 +691,11 @@ fn build_union_fields_for_direct_tag_generator<'ll, 'tcx>( generator_type_di_node, variant_range .clone() - .map(|variant_index| (variant_index, GeneratorSubsts::variant_name(variant_index))), + .map(|variant_index| (variant_index, GeneratorArgs::variant_name(variant_index))), ); let discriminants: IndexVec<VariantIdx, DiscrResult> = { - let discriminants_iter = generator_substs.discriminants(generator_def_id, cx.tcx); + let discriminants_iter = generator_args.discriminants(generator_def_id, cx.tcx); let mut discriminants: IndexVec<VariantIdx, DiscrResult> = IndexVec::with_capacity(variant_count); for (variant_index, discr) in discriminants_iter { diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/mod.rs b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/mod.rs index 8746ce0c5b1..b4beb80ca8b 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/mod.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/mod.rs @@ -10,7 +10,7 @@ use rustc_middle::{ ty::{ self, layout::{IntegerExt, LayoutOf, PrimitiveExt, TyAndLayout}, - AdtDef, GeneratorSubsts, Ty, VariantDef, + AdtDef, GeneratorArgs, Ty, VariantDef, }, }; use rustc_span::Symbol; @@ -51,7 +51,7 @@ pub(super) fn build_enum_type_di_node<'ll, 'tcx>( let enum_type = unique_type_id.expect_ty(); let &ty::Adt(enum_adt_def, _) = enum_type.kind() else { bug!("build_enum_type_di_node() called with non-enum type: `{:?}`", enum_type) - }; + }; let enum_type_and_layout = cx.layout_of(enum_type); @@ -325,7 +325,7 @@ pub fn build_generator_variant_struct_type_di_node<'ll, 'tcx>( generator_layout: &GeneratorLayout<'tcx>, common_upvar_names: &IndexSlice<FieldIdx, Symbol>, ) -> &'ll DIType { - let variant_name = GeneratorSubsts::variant_name(variant_index); + let variant_name = GeneratorArgs::variant_name(variant_index); let unique_type_id = UniqueTypeId::for_enum_variant_struct_type( cx.tcx, generator_type_and_layout.ty, @@ -334,8 +334,8 @@ pub fn build_generator_variant_struct_type_di_node<'ll, 'tcx>( let variant_layout = generator_type_and_layout.for_variant(cx, variant_index); - let generator_substs = match generator_type_and_layout.ty.kind() { - ty::Generator(_, substs, _) => substs.as_generator(), + let generator_args = match generator_type_and_layout.ty.kind() { + ty::Generator(_, args, _) => args.as_generator(), _ => unreachable!(), }; @@ -377,7 +377,7 @@ pub fn build_generator_variant_struct_type_di_node<'ll, 'tcx>( .collect(); // Fields that are common to all states - let common_fields: SmallVec<_> = generator_substs + let common_fields: SmallVec<_> = generator_args .prefix_tys() .zip(common_upvar_names) .enumerate() diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/native.rs b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/native.rs index 4d1cd64865f..feac40d8c30 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/native.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/native.rs @@ -57,7 +57,7 @@ pub(super) fn build_enum_type_di_node<'ll, 'tcx>( let enum_type = unique_type_id.expect_ty(); let &ty::Adt(enum_adt_def, _) = enum_type.kind() else { bug!("build_enum_type_di_node() called with non-enum type: `{:?}`", enum_type) - }; + }; let containing_scope = get_namespace_for_item(cx, enum_adt_def.did()); let enum_type_and_layout = cx.layout_of(enum_type); @@ -132,9 +132,9 @@ pub(super) fn build_generator_di_node<'ll, 'tcx>( unique_type_id: UniqueTypeId<'tcx>, ) -> DINodeCreationResult<'ll> { let generator_type = unique_type_id.expect_ty(); - let &ty::Generator(generator_def_id, _, _ ) = generator_type.kind() else { + let &ty::Generator(generator_def_id, _, _) = generator_type.kind() else { bug!("build_generator_di_node() called with non-generator type: `{:?}`", generator_type) - }; + }; let containing_scope = get_namespace_for_item(cx, generator_def_id); let generator_type_and_layout = cx.layout_of(generator_type); @@ -158,7 +158,9 @@ pub(super) fn build_generator_di_node<'ll, 'tcx>( let generator_layout = cx.tcx.optimized_mir(generator_def_id).generator_layout().unwrap(); - let Variants::Multiple { tag_encoding: TagEncoding::Direct, ref variants, .. } = generator_type_and_layout.variants else { + let Variants::Multiple { tag_encoding: TagEncoding::Direct, ref variants, .. } = + generator_type_and_layout.variants + else { bug!( "Encountered generator with non-direct-tag layout: {:?}", generator_type_and_layout @@ -173,7 +175,7 @@ pub(super) fn build_generator_di_node<'ll, 'tcx>( .indices() .map(|variant_index| { // FIXME: This is problematic because just a number is not a valid identifier. - // GeneratorSubsts::variant_name(variant_index), would be consistent + // GeneratorArgs::variant_name(variant_index), would be consistent // with enums? let variant_name = format!("{}", variant_index.as_usize()).into(); diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs b/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs index b924c771af7..40714a0afe9 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs @@ -27,7 +27,7 @@ use rustc_hir::def_id::{DefId, DefIdMap}; use rustc_index::IndexVec; use rustc_middle::mir; use rustc_middle::ty::layout::LayoutOf; -use rustc_middle::ty::subst::SubstsRef; +use rustc_middle::ty::GenericArgsRef; use rustc_middle::ty::{self, Instance, ParamEnv, Ty, TypeVisitableExt}; use rustc_session::config::{self, DebugInfo}; use rustc_session::Session; @@ -338,19 +338,19 @@ impl<'ll, 'tcx> DebugInfoMethods<'tcx> for CodegenCx<'ll, 'tcx> { // Find the enclosing function, in case this is a closure. let enclosing_fn_def_id = tcx.typeck_root_def_id(def_id); - // We look up the generics of the enclosing function and truncate the substs + // We look up the generics of the enclosing function and truncate the args // to their length in order to cut off extra stuff that might be in there for // closures or generators. let generics = tcx.generics_of(enclosing_fn_def_id); - let substs = instance.substs.truncate_to(tcx, generics); + let args = instance.args.truncate_to(tcx, generics); type_names::push_generic_params( tcx, - tcx.normalize_erasing_regions(ty::ParamEnv::reveal_all(), substs), + tcx.normalize_erasing_regions(ty::ParamEnv::reveal_all(), args), &mut name, ); - let template_parameters = get_template_parameters(self, generics, substs); + let template_parameters = get_template_parameters(self, generics, args); let linkage_name = &mangled_name_of_instance(self, instance).name; // Omit the linkage_name if it is the same as subprogram name. @@ -471,16 +471,16 @@ impl<'ll, 'tcx> DebugInfoMethods<'tcx> for CodegenCx<'ll, 'tcx> { fn get_template_parameters<'ll, 'tcx>( cx: &CodegenCx<'ll, 'tcx>, generics: &ty::Generics, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, ) -> &'ll DIArray { - if substs.types().next().is_none() { + if args.types().next().is_none() { return create_DIArray(DIB(cx), &[]); } // Again, only create type information if full debuginfo is enabled let template_params: Vec<_> = if cx.sess().opts.debuginfo == DebugInfo::Full { let names = get_parameter_names(cx, generics); - iter::zip(substs, names) + iter::zip(args, names) .filter_map(|(kind, name)| { kind.as_type().map(|ty| { let actual_type = @@ -527,7 +527,7 @@ impl<'ll, 'tcx> DebugInfoMethods<'tcx> for CodegenCx<'ll, 'tcx> { // If the method does *not* belong to a trait, proceed if cx.tcx.trait_id_of_impl(impl_def_id).is_none() { let impl_self_ty = cx.tcx.subst_and_normalize_erasing_regions( - instance.substs, + instance.args, ty::ParamEnv::reveal_all(), cx.tcx.type_of(impl_def_id), ); diff --git a/compiler/rustc_codegen_llvm/src/intrinsic.rs b/compiler/rustc_codegen_llvm/src/intrinsic.rs index a254c86c291..6df1b708ccd 100644 --- a/compiler/rustc_codegen_llvm/src/intrinsic.rs +++ b/compiler/rustc_codegen_llvm/src/intrinsic.rs @@ -90,7 +90,7 @@ impl<'ll, 'tcx> IntrinsicCallMethods<'tcx> for Builder<'_, 'll, 'tcx> { let tcx = self.tcx; let callee_ty = instance.ty(tcx, ty::ParamEnv::reveal_all()); - let ty::FnDef(def_id, substs) = *callee_ty.kind() else { + let ty::FnDef(def_id, fn_args) = *callee_ty.kind() else { bug!("expected fn item type, found {}", callee_ty); }; @@ -163,7 +163,7 @@ impl<'ll, 'tcx> IntrinsicCallMethods<'tcx> for Builder<'_, 'll, 'tcx> { } sym::volatile_load | sym::unaligned_volatile_load => { - let tp_ty = substs.type_at(0); + let tp_ty = fn_args.type_at(0); let ptr = args[0].immediate(); let load = if let PassMode::Cast(ty, _) = &fn_abi.ret.mode { let llty = ty.llvm_type(self); @@ -298,7 +298,7 @@ impl<'ll, 'tcx> IntrinsicCallMethods<'tcx> for Builder<'_, 'll, 'tcx> { sym::raw_eq => { use abi::Abi::*; - let tp_ty = substs.type_at(0); + let tp_ty = fn_args.type_at(0); let layout = self.layout_of(tp_ty).layout; let use_integer_compare = match layout.abi() { Scalar(_) | ScalarPair(_, _) => true, diff --git a/compiler/rustc_codegen_llvm/src/llvm/ffi.rs b/compiler/rustc_codegen_llvm/src/llvm/ffi.rs index e1dfc1b2dd6..605f0154773 100644 --- a/compiler/rustc_codegen_llvm/src/llvm/ffi.rs +++ b/compiler/rustc_codegen_llvm/src/llvm/ffi.rs @@ -1916,7 +1916,6 @@ extern "C" { ); pub fn LLVMRustCoverageCreatePGOFuncNameVar(F: &Value, FuncName: *const c_char) -> &Value; - pub fn LLVMRustCoverageHashCString(StrVal: *const c_char) -> u64; pub fn LLVMRustCoverageHashByteArray(Bytes: *const c_char, NumBytes: size_t) -> u64; #[allow(improper_ctypes)] diff --git a/compiler/rustc_codegen_llvm/src/mono_item.rs b/compiler/rustc_codegen_llvm/src/mono_item.rs index c24854b27a0..e8cda626f54 100644 --- a/compiler/rustc_codegen_llvm/src/mono_item.rs +++ b/compiler/rustc_codegen_llvm/src/mono_item.rs @@ -48,7 +48,7 @@ impl<'tcx> PreDefineMethods<'tcx> for CodegenCx<'_, 'tcx> { visibility: Visibility, symbol_name: &str, ) { - assert!(!instance.substs.has_infer()); + assert!(!instance.args.has_infer()); let fn_abi = self.fn_abi_of_instance(instance, ty::List::empty()); let lldecl = self.declare_fn(symbol_name, fn_abi, Some(instance)); diff --git a/compiler/rustc_codegen_llvm/src/type_of.rs b/compiler/rustc_codegen_llvm/src/type_of.rs index 58e97be34f2..2dbd467cc84 100644 --- a/compiler/rustc_codegen_llvm/src/type_of.rs +++ b/compiler/rustc_codegen_llvm/src/type_of.rs @@ -57,7 +57,7 @@ fn uncached_llvm_type<'a, 'tcx>( if let (&ty::Generator(_, _, _), &Variants::Single { index }) = (layout.ty.kind(), &layout.variants) { - write!(&mut name, "::{}", ty::GeneratorSubsts::variant_name(index)).unwrap(); + write!(&mut name, "::{}", ty::GeneratorArgs::variant_name(index)).unwrap(); } Some(name) } @@ -336,7 +336,7 @@ impl<'tcx> LayoutLlvmExt<'tcx> for TyAndLayout<'tcx> { } // only wide pointer boxes are handled as pointers // thin pointer boxes with scalar allocators are handled by the general logic below - ty::Adt(def, substs) if def.is_box() && cx.layout_of(substs.type_at(1)).is_zst() => { + ty::Adt(def, args) if def.is_box() && cx.layout_of(args.type_at(1)).is_zst() => { let ptr_ty = Ty::new_mut_ptr(cx.tcx, self.ty.boxed_ty()); return cx.layout_of(ptr_ty).scalar_pair_element_llvm_type(cx, index, immediate); } diff --git a/compiler/rustc_codegen_ssa/src/back/link.rs b/compiler/rustc_codegen_ssa/src/back/link.rs index c7925be0d7d..0dfb41f42f0 100644 --- a/compiler/rustc_codegen_ssa/src/back/link.rs +++ b/compiler/rustc_codegen_ssa/src/back/link.rs @@ -1392,6 +1392,11 @@ fn print_native_static_libs( let mut lib_args: Vec<_> = all_native_libs .iter() .filter(|l| relevant_lib(sess, l)) + // Deduplication of successive repeated libraries, see rust-lang/rust#113209 + // + // note: we don't use PartialEq/Eq because NativeLib transitively depends on local + // elements like spans, which we don't care about and would make the deduplication impossible + .dedup_by(|l1, l2| l1.name == l2.name && l1.kind == l2.kind && l1.verbatim == l2.verbatim) .filter_map(|lib| { let name = lib.name; match lib.kind { @@ -2970,10 +2975,25 @@ fn add_lld_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) { return; } + let self_contained_linker = sess.opts.cg.link_self_contained.linker(); + + // FIXME: some targets default to using `lld`, but users can only override the linker on the CLI + // and cannot yet select the precise linker flavor to opt out of that. See for example issue + // #113597 for the `thumbv6m-none-eabi` target: a driver is used, and its default linker + // conflicts with the target's flavor, causing unexpected arguments being passed. + // + // Until the new `LinkerFlavor`-like CLI options are stabilized, we only adopt MCP510's behavior + // if its dedicated unstable CLI flags are used, to keep the current sub-optimal stable + // behavior. + let using_mcp510 = + self_contained_linker || sess.opts.cg.linker_flavor.is_some_and(|f| f.is_unstable()); + if !using_mcp510 && !unstable_use_lld { + return; + } + // 1. Implement the "self-contained" part of this feature by adding rustc distribution // directories to the tool's search path. - let self_contained_linker = sess.opts.cg.link_self_contained.linker() || unstable_use_lld; - if self_contained_linker { + if self_contained_linker || unstable_use_lld { for path in sess.get_tools_search_paths(false) { cmd.arg({ let mut arg = OsString::from("-B"); diff --git a/compiler/rustc_codegen_ssa/src/back/metadata.rs b/compiler/rustc_codegen_ssa/src/back/metadata.rs index 00e6acb5c1a..1f827a2375d 100644 --- a/compiler/rustc_codegen_ssa/src/back/metadata.rs +++ b/compiler/rustc_codegen_ssa/src/back/metadata.rs @@ -12,7 +12,6 @@ use object::{ use snap::write::FrameEncoder; -use object::elf::NT_GNU_PROPERTY_TYPE_0; use rustc_data_structures::memmap::Mmap; use rustc_data_structures::owned_slice::{try_slice_owned, OwnedSlice}; use rustc_metadata::fs::METADATA_FILENAME; @@ -124,7 +123,7 @@ fn add_gnu_property_note( let mut data: Vec<u8> = Vec::new(); let n_namsz: u32 = 4; // Size of the n_name field let n_descsz: u32 = 16; // Size of the n_desc field - let n_type: u32 = NT_GNU_PROPERTY_TYPE_0; // Type of note descriptor + let n_type: u32 = object::elf::NT_GNU_PROPERTY_TYPE_0; // Type of note descriptor let header_values = [n_namsz, n_descsz, n_type]; header_values.iter().for_each(|v| { data.extend_from_slice(&match endianness { @@ -134,8 +133,8 @@ fn add_gnu_property_note( }); data.extend_from_slice(b"GNU\0"); // Owner of the program property note let pr_type: u32 = match architecture { - Architecture::X86_64 => 0xc0000002, - Architecture::Aarch64 => 0xc0000000, + Architecture::X86_64 => object::elf::GNU_PROPERTY_X86_FEATURE_1_AND, + Architecture::Aarch64 => object::elf::GNU_PROPERTY_AARCH64_FEATURE_1_AND, _ => unreachable!(), }; let pr_datasz: u32 = 4; //size of the pr_data field @@ -243,8 +242,16 @@ pub(crate) fn create_object_file(sess: &Session) -> Option<write::Object<'static s if s.contains("r6") => elf::EF_MIPS_ARCH_32R6, _ => elf::EF_MIPS_ARCH_32R2, }; - // The only ABI LLVM supports for 32-bit MIPS CPUs is o32. - let mut e_flags = elf::EF_MIPS_CPIC | elf::EF_MIPS_ABI_O32 | arch; + + let mut e_flags = elf::EF_MIPS_CPIC | arch; + + // If the ABI is explicitly given, use it or default to O32. + match sess.target.options.llvm_abiname.to_lowercase().as_str() { + "n32" => e_flags |= elf::EF_MIPS_ABI2, + "o32" => e_flags |= elf::EF_MIPS_ABI_O32, + _ => e_flags |= elf::EF_MIPS_ABI_O32, + }; + if sess.target.options.relocation_model != RelocModel::Static { e_flags |= elf::EF_MIPS_PIC; } diff --git a/compiler/rustc_codegen_ssa/src/back/symbol_export.rs b/compiler/rustc_codegen_ssa/src/back/symbol_export.rs index a8b6030ac85..cbe7e519079 100644 --- a/compiler/rustc_codegen_ssa/src/back/symbol_export.rs +++ b/compiler/rustc_codegen_ssa/src/back/symbol_export.rs @@ -12,9 +12,9 @@ use rustc_middle::middle::exported_symbols::{ }; use rustc_middle::query::LocalCrate; use rustc_middle::query::{ExternProviders, Providers}; -use rustc_middle::ty::subst::{GenericArgKind, SubstsRef}; use rustc_middle::ty::Instance; use rustc_middle::ty::{self, SymbolName, TyCtxt}; +use rustc_middle::ty::{GenericArgKind, GenericArgsRef}; use rustc_session::config::{CrateType, OomStrategy}; use rustc_target::spec::SanitizerSet; @@ -328,23 +328,23 @@ fn exported_symbols_provider_local( let (_, cgus) = tcx.collect_and_partition_mono_items(()); - for (mono_item, &(linkage, visibility)) in cgus.iter().flat_map(|cgu| cgu.items().iter()) { - if linkage != Linkage::External { + for (mono_item, data) in cgus.iter().flat_map(|cgu| cgu.items().iter()) { + if data.linkage != Linkage::External { // We can only re-use things with external linkage, otherwise // we'll get a linker error continue; } - if need_visibility && visibility == Visibility::Hidden { + if need_visibility && data.visibility == Visibility::Hidden { // If we potentially share things from Rust dylibs, they must // not be hidden continue; } match *mono_item { - MonoItem::Fn(Instance { def: InstanceDef::Item(def), substs }) => { - if substs.non_erasable_generics().next().is_some() { - let symbol = ExportedSymbol::Generic(def, substs); + MonoItem::Fn(Instance { def: InstanceDef::Item(def), args }) => { + if args.non_erasable_generics().next().is_some() { + let symbol = ExportedSymbol::Generic(def, args); symbols.push(( symbol, SymbolExportInfo { @@ -355,10 +355,10 @@ fn exported_symbols_provider_local( )); } } - MonoItem::Fn(Instance { def: InstanceDef::DropGlue(_, Some(ty)), substs }) => { + MonoItem::Fn(Instance { def: InstanceDef::DropGlue(_, Some(ty)), args }) => { // A little sanity-check debug_assert_eq!( - substs.non_erasable_generics().next(), + args.non_erasable_generics().next(), Some(GenericArgKind::Type(ty)) ); symbols.push(( @@ -386,7 +386,7 @@ fn exported_symbols_provider_local( fn upstream_monomorphizations_provider( tcx: TyCtxt<'_>, (): (), -) -> DefIdMap<FxHashMap<SubstsRef<'_>, CrateNum>> { +) -> DefIdMap<FxHashMap<GenericArgsRef<'_>, CrateNum>> { let cnums = tcx.crates(()); let mut instances: DefIdMap<FxHashMap<_, _>> = Default::default(); @@ -395,11 +395,11 @@ fn upstream_monomorphizations_provider( for &cnum in cnums.iter() { for (exported_symbol, _) in tcx.exported_symbols(cnum).iter() { - let (def_id, substs) = match *exported_symbol { - ExportedSymbol::Generic(def_id, substs) => (def_id, substs), + let (def_id, args) = match *exported_symbol { + ExportedSymbol::Generic(def_id, args) => (def_id, args), ExportedSymbol::DropGlue(ty) => { if let Some(drop_in_place_fn_def_id) = drop_in_place_fn_def_id { - (drop_in_place_fn_def_id, tcx.mk_substs(&[ty.into()])) + (drop_in_place_fn_def_id, tcx.mk_args(&[ty.into()])) } else { // `drop_in_place` in place does not exist, don't try // to use it. @@ -414,9 +414,9 @@ fn upstream_monomorphizations_provider( } }; - let substs_map = instances.entry(def_id).or_default(); + let args_map = instances.entry(def_id).or_default(); - match substs_map.entry(substs) { + match args_map.entry(args) { Occupied(mut e) => { // If there are multiple monomorphizations available, // we select one deterministically. @@ -438,17 +438,17 @@ fn upstream_monomorphizations_provider( fn upstream_monomorphizations_for_provider( tcx: TyCtxt<'_>, def_id: DefId, -) -> Option<&FxHashMap<SubstsRef<'_>, CrateNum>> { +) -> Option<&FxHashMap<GenericArgsRef<'_>, CrateNum>> { debug_assert!(!def_id.is_local()); tcx.upstream_monomorphizations(()).get(&def_id) } fn upstream_drop_glue_for_provider<'tcx>( tcx: TyCtxt<'tcx>, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, ) -> Option<CrateNum> { if let Some(def_id) = tcx.lang_items().drop_in_place_fn() { - tcx.upstream_monomorphizations_for(def_id).and_then(|monos| monos.get(&substs).cloned()) + tcx.upstream_monomorphizations_for(def_id).and_then(|monos| monos.get(&args).cloned()) } else { None } @@ -521,10 +521,10 @@ pub fn symbol_name_for_instance_in_crate<'tcx>( instantiating_crate, ) } - ExportedSymbol::Generic(def_id, substs) => { + ExportedSymbol::Generic(def_id, args) => { rustc_symbol_mangling::symbol_name_for_instance_in_crate( tcx, - Instance::new(def_id, substs), + Instance::new(def_id, args), instantiating_crate, ) } @@ -533,7 +533,7 @@ pub fn symbol_name_for_instance_in_crate<'tcx>( tcx, ty::Instance { def: ty::InstanceDef::ThreadLocalShim(def_id), - substs: ty::InternalSubsts::empty(), + args: ty::GenericArgs::empty(), }, instantiating_crate, ) @@ -580,7 +580,7 @@ pub fn linking_symbol_name_for_instance_in_crate<'tcx>( None } ExportedSymbol::NonGeneric(def_id) => Some(Instance::mono(tcx, def_id)), - ExportedSymbol::Generic(def_id, substs) => Some(Instance::new(def_id, substs)), + ExportedSymbol::Generic(def_id, args) => Some(Instance::new(def_id, args)), // DropGlue always use the Rust calling convention and thus follow the target's default // symbol decoration scheme. ExportedSymbol::DropGlue(..) => None, diff --git a/compiler/rustc_codegen_ssa/src/base.rs b/compiler/rustc_codegen_ssa/src/base.rs index 9133601ecd1..dc862803274 100644 --- a/compiler/rustc_codegen_ssa/src/base.rs +++ b/compiler/rustc_codegen_ssa/src/base.rs @@ -499,7 +499,7 @@ pub fn maybe_create_entry_wrapper<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( cx.tcx(), ty::ParamEnv::reveal_all(), start_def_id, - cx.tcx().mk_substs(&[main_ret_ty.into()]), + cx.tcx().mk_args(&[main_ret_ty.into()]), ) .unwrap() .unwrap(), diff --git a/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs b/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs index e91f7b86e5e..64f799bb1e6 100644 --- a/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs +++ b/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs @@ -17,8 +17,8 @@ use rustc_hir::def_id::DefId; use rustc_hir::definitions::{DefPathData, DefPathDataName, DisambiguatedDefPathData}; use rustc_hir::{AsyncGeneratorKind, GeneratorKind, Mutability}; use rustc_middle::ty::layout::{IntegerExt, TyAndLayout}; -use rustc_middle::ty::subst::{GenericArgKind, SubstsRef}; use rustc_middle::ty::{self, ExistentialProjection, ParamEnv, Ty, TyCtxt}; +use rustc_middle::ty::{GenericArgKind, GenericArgsRef}; use rustc_target::abi::Integer; use smallvec::SmallVec; @@ -77,7 +77,7 @@ fn push_debuginfo_type_name<'tcx>( ty::Uint(uint_ty) => output.push_str(uint_ty.name_str()), ty::Float(float_ty) => output.push_str(float_ty.name_str()), ty::Foreign(def_id) => push_item_name(tcx, def_id, qualified, output), - ty::Adt(def, substs) => { + ty::Adt(def, args) => { // `layout_for_cpp_like_fallback` will be `Some` if we want to use the fallback encoding. let layout_for_cpp_like_fallback = if cpp_like_debuginfo && def.is_enum() { match tcx.layout_of(ParamEnv::reveal_all().and(t)) { @@ -106,14 +106,14 @@ fn push_debuginfo_type_name<'tcx>( ty_and_layout, &|output, visited| { push_item_name(tcx, def.did(), true, output); - push_generic_params_internal(tcx, substs, output, visited); + push_generic_params_internal(tcx, args, output, visited); }, output, visited, ); } else { push_item_name(tcx, def.did(), qualified, output); - push_generic_params_internal(tcx, substs, output, visited); + push_generic_params_internal(tcx, args, output, visited); } } ty::Tuple(component_types) => { @@ -238,7 +238,7 @@ fn push_debuginfo_type_name<'tcx>( tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), principal); push_item_name(tcx, principal.def_id, qualified, output); let principal_has_generic_params = - push_generic_params_internal(tcx, principal.substs, output, visited); + push_generic_params_internal(tcx, principal.args, output, visited); let projection_bounds: SmallVec<[_; 4]> = trait_data .projection_bounds() @@ -393,7 +393,7 @@ fn push_debuginfo_type_name<'tcx>( // processing visited.remove(&t); } - ty::Closure(def_id, substs) | ty::Generator(def_id, substs, ..) => { + ty::Closure(def_id, args) | ty::Generator(def_id, args, ..) => { // Name will be "{closure_env#0}<T1, T2, ...>", "{generator_env#0}<T1, T2, ...>", or // "{async_fn_env#0}<T1, T2, ...>", etc. // In the case of cpp-like debuginfo, the name additionally gets wrapped inside of @@ -403,13 +403,13 @@ fn push_debuginfo_type_name<'tcx>( msvc_enum_fallback( ty_and_layout, &|output, visited| { - push_closure_or_generator_name(tcx, def_id, substs, true, output, visited); + push_closure_or_generator_name(tcx, def_id, args, true, output, visited); }, output, visited, ); } else { - push_closure_or_generator_name(tcx, def_id, substs, qualified, output, visited); + push_closure_or_generator_name(tcx, def_id, args, qualified, output, visited); } } // Type parameters from polymorphized functions. @@ -516,7 +516,7 @@ pub fn compute_debuginfo_vtable_name<'tcx>( tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), trait_ref); push_item_name(tcx, trait_ref.def_id, true, &mut vtable_name); visited.clear(); - push_generic_params_internal(tcx, trait_ref.substs, &mut vtable_name, &mut visited); + push_generic_params_internal(tcx, trait_ref.args, &mut vtable_name, &mut visited); } else { vtable_name.push('_'); } @@ -609,21 +609,21 @@ fn push_unqualified_item_name( fn push_generic_params_internal<'tcx>( tcx: TyCtxt<'tcx>, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, output: &mut String, visited: &mut FxHashSet<Ty<'tcx>>, ) -> bool { - if substs.non_erasable_generics().next().is_none() { + if args.non_erasable_generics().next().is_none() { return false; } - debug_assert_eq!(substs, tcx.normalize_erasing_regions(ty::ParamEnv::reveal_all(), substs)); + debug_assert_eq!(args, tcx.normalize_erasing_regions(ty::ParamEnv::reveal_all(), args)); let cpp_like_debuginfo = cpp_like_debuginfo(tcx); output.push('<'); - for type_parameter in substs.non_erasable_generics() { + for type_parameter in args.non_erasable_generics() { match type_parameter { GenericArgKind::Type(type_parameter) => { push_debuginfo_type_name(tcx, type_parameter, true, output, visited); @@ -688,16 +688,20 @@ fn push_const_param<'tcx>(tcx: TyCtxt<'tcx>, ct: ty::Const<'tcx>, output: &mut S .unwrap(); } -pub fn push_generic_params<'tcx>(tcx: TyCtxt<'tcx>, substs: SubstsRef<'tcx>, output: &mut String) { +pub fn push_generic_params<'tcx>( + tcx: TyCtxt<'tcx>, + args: GenericArgsRef<'tcx>, + output: &mut String, +) { let _prof = tcx.prof.generic_activity("compute_debuginfo_type_name"); let mut visited = FxHashSet::default(); - push_generic_params_internal(tcx, substs, output, &mut visited); + push_generic_params_internal(tcx, args, output, &mut visited); } fn push_closure_or_generator_name<'tcx>( tcx: TyCtxt<'tcx>, def_id: DefId, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, qualified: bool, output: &mut String, visited: &mut FxHashSet<Ty<'tcx>>, @@ -731,10 +735,10 @@ fn push_closure_or_generator_name<'tcx>( let enclosing_fn_def_id = tcx.typeck_root_def_id(def_id); let generics = tcx.generics_of(enclosing_fn_def_id); - // Truncate the substs to the length of the above generics. This will cut off + // Truncate the args to the length of the above generics. This will cut off // anything closure- or generator-specific. - let substs = substs.truncate_to(tcx, generics); - push_generic_params_internal(tcx, substs, output, visited); + let args = args.truncate_to(tcx, generics); + push_generic_params_internal(tcx, args, output, visited); } fn push_close_angle_bracket(cpp_like_debuginfo: bool, output: &mut String) { diff --git a/compiler/rustc_codegen_ssa/src/meth.rs b/compiler/rustc_codegen_ssa/src/meth.rs index a8b935bd65c..9abe7b25d0e 100644 --- a/compiler/rustc_codegen_ssa/src/meth.rs +++ b/compiler/rustc_codegen_ssa/src/meth.rs @@ -1,6 +1,6 @@ use crate::traits::*; -use rustc_middle::ty::{self, subst::GenericArgKind, Ty}; +use rustc_middle::ty::{self, GenericArgKind, Ty}; use rustc_session::config::Lto; use rustc_symbol_mangling::typeid_for_trait_ref; use rustc_target::abi::call::FnAbi; diff --git a/compiler/rustc_codegen_ssa/src/mir/block.rs b/compiler/rustc_codegen_ssa/src/mir/block.rs index 9d1b3ce8266..ed608bdbe9a 100644 --- a/compiler/rustc_codegen_ssa/src/mir/block.rs +++ b/compiler/rustc_codegen_ssa/src/mir/block.rs @@ -23,6 +23,8 @@ use rustc_target::abi::call::{ArgAbi, FnAbi, PassMode, Reg}; use rustc_target::abi::{self, HasDataLayout, WrappingRange}; use rustc_target::spec::abi::Abi; +use std::cmp; + // Indicates if we are in the middle of merging a BB's successor into it. This // can happen when BB jumps directly to its successor and the successor has no // other predecessors. @@ -491,7 +493,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { // let virtual_drop = Instance { def: ty::InstanceDef::Virtual(drop_fn.def_id(), 0), - substs: drop_fn.substs, + args: drop_fn.args, }; debug!("ty = {:?}", ty); debug!("drop_fn = {:?}", drop_fn); @@ -531,7 +533,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { // SO THEN WE CAN USE THE ABOVE CODE. let virtual_drop = Instance { def: ty::InstanceDef::Virtual(drop_fn.def_id(), 0), - substs: drop_fn.substs, + args: drop_fn.args, }; debug!("ty = {:?}", ty); debug!("drop_fn = {:?}", drop_fn); @@ -687,7 +689,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { // which mentions the offending type, even from a const context. let panic_intrinsic = intrinsic.and_then(|s| ValidityRequirement::from_intrinsic(s)); if let Some(requirement) = panic_intrinsic { - let ty = instance.unwrap().substs.type_at(0); + let ty = instance.unwrap().args.type_at(0); let do_panic = !bx .tcx() @@ -760,13 +762,13 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { let callee = self.codegen_operand(bx, func); let (instance, mut llfn) = match *callee.layout.ty.kind() { - ty::FnDef(def_id, substs) => ( + ty::FnDef(def_id, args) => ( Some( ty::Instance::expect_resolve( bx.tcx(), ty::ParamEnv::reveal_all(), def_id, - substs, + args, ) .polymorphize(bx.tcx()), ), @@ -1125,12 +1127,12 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { } mir::InlineAsmOperand::SymFn { ref value } => { let literal = self.monomorphize(value.literal); - if let ty::FnDef(def_id, substs) = *literal.ty().kind() { + if let ty::FnDef(def_id, args) = *literal.ty().kind() { let instance = ty::Instance::resolve_for_fn_ptr( bx.tcx(), ty::ParamEnv::reveal_all(), def_id, - substs, + args, ) .unwrap(); InlineAsmOperandRef::SymFn { instance } @@ -1360,36 +1362,58 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { // Force by-ref if we have to load through a cast pointer. let (mut llval, align, by_ref) = match op.val { Immediate(_) | Pair(..) => match arg.mode { - PassMode::Indirect { .. } | PassMode::Cast(..) => { + PassMode::Indirect { attrs, .. } => { + // Indirect argument may have higher alignment requirements than the type's alignment. + // This can happen, e.g. when passing types with <4 byte alignment on the stack on x86. + let required_align = match attrs.pointee_align { + Some(pointee_align) => cmp::max(pointee_align, arg.layout.align.abi), + None => arg.layout.align.abi, + }; + let scratch = PlaceRef::alloca_aligned(bx, arg.layout, required_align); + op.val.store(bx, scratch); + (scratch.llval, scratch.align, true) + } + PassMode::Cast(..) => { let scratch = PlaceRef::alloca(bx, arg.layout); op.val.store(bx, scratch); (scratch.llval, scratch.align, true) } _ => (op.immediate_or_packed_pair(bx), arg.layout.align.abi, false), }, - Ref(llval, _, align) => { - if arg.is_indirect() && align < arg.layout.align.abi { - // `foo(packed.large_field)`. We can't pass the (unaligned) field directly. I - // think that ATM (Rust 1.16) we only pass temporaries, but we shouldn't - // have scary latent bugs around. - - let scratch = PlaceRef::alloca(bx, arg.layout); - base::memcpy_ty( - bx, - scratch.llval, - scratch.align, - llval, - align, - op.layout, - MemFlags::empty(), - ); - (scratch.llval, scratch.align, true) - } else { - (llval, align, true) + Ref(llval, _, align) => match arg.mode { + PassMode::Indirect { attrs, .. } => { + let required_align = match attrs.pointee_align { + Some(pointee_align) => cmp::max(pointee_align, arg.layout.align.abi), + None => arg.layout.align.abi, + }; + if align < required_align { + // For `foo(packed.large_field)`, and types with <4 byte alignment on x86, + // alignment requirements may be higher than the type's alignment, so copy + // to a higher-aligned alloca. + let scratch = PlaceRef::alloca_aligned(bx, arg.layout, required_align); + base::memcpy_ty( + bx, + scratch.llval, + scratch.align, + llval, + align, + op.layout, + MemFlags::empty(), + ); + (scratch.llval, scratch.align, true) + } else { + (llval, align, true) + } } - } + _ => (llval, align, true), + }, ZeroSized => match arg.mode { - PassMode::Indirect { .. } => { + PassMode::Indirect { on_stack, .. } => { + if on_stack { + // It doesn't seem like any target can have `byval` ZSTs, so this assert + // is here to replace a would-be untested codepath. + bug!("ZST {op:?} passed on stack with abi {arg:?}"); + } // Though `extern "Rust"` doesn't pass ZSTs, some ABIs pass // a pointer for `repr(C)` structs even when empty, so get // one from an `alloca` (which can be left uninitialized). diff --git a/compiler/rustc_codegen_ssa/src/mir/debuginfo.rs b/compiler/rustc_codegen_ssa/src/mir/debuginfo.rs index 4b27b64962d..34b8d8b5a6f 100644 --- a/compiler/rustc_codegen_ssa/src/mir/debuginfo.rs +++ b/compiler/rustc_codegen_ssa/src/mir/debuginfo.rs @@ -186,7 +186,11 @@ fn calculate_debuginfo_offset< } => { let offset = indirect_offsets.last_mut().unwrap_or(&mut direct_offset); let FieldsShape::Array { stride, count: _ } = place.layout().fields else { - span_bug!(var.source_info.span, "ConstantIndex on non-array type {:?}", place.layout()) + span_bug!( + var.source_info.span, + "ConstantIndex on non-array type {:?}", + place.layout() + ) }; *offset += stride * index; place = place.project_constant_index(bx, index); diff --git a/compiler/rustc_codegen_ssa/src/mir/intrinsic.rs b/compiler/rustc_codegen_ssa/src/mir/intrinsic.rs index 8a65dd593b8..18201abd631 100644 --- a/compiler/rustc_codegen_ssa/src/mir/intrinsic.rs +++ b/compiler/rustc_codegen_ssa/src/mir/intrinsic.rs @@ -64,7 +64,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { ) { let callee_ty = instance.ty(bx.tcx(), ty::ParamEnv::reveal_all()); - let ty::FnDef(def_id, substs) = *callee_ty.kind() else { + let ty::FnDef(def_id, fn_args) = *callee_ty.kind() else { bug!("expected fn item type, found {}", callee_ty); }; @@ -87,7 +87,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { sym::va_start => bx.va_start(args[0].immediate()), sym::va_end => bx.va_end(args[0].immediate()), sym::size_of_val => { - let tp_ty = substs.type_at(0); + let tp_ty = fn_args.type_at(0); if let OperandValue::Pair(_, meta) = args[0].val { let (llsize, _) = glue::size_and_align_of_dst(bx, tp_ty, Some(meta)); llsize @@ -96,7 +96,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { } } sym::min_align_of_val => { - let tp_ty = substs.type_at(0); + let tp_ty = fn_args.type_at(0); if let OperandValue::Pair(_, meta) = args[0].val { let (_, llalign) = glue::size_and_align_of_dst(bx, tp_ty, Some(meta)); llalign @@ -136,7 +136,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { OperandRef::from_const(bx, value, ret_ty).immediate_or_packed_pair(bx) } sym::arith_offset => { - let ty = substs.type_at(0); + let ty = fn_args.type_at(0); let layout = bx.layout_of(ty); let ptr = args[0].immediate(); let offset = args[1].immediate(); @@ -147,7 +147,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { bx, true, false, - substs.type_at(0), + fn_args.type_at(0), args[1].immediate(), args[0].immediate(), args[2].immediate(), @@ -158,7 +158,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { memset_intrinsic( bx, false, - substs.type_at(0), + fn_args.type_at(0), args[0].immediate(), args[1].immediate(), args[2].immediate(), @@ -171,7 +171,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { bx, false, true, - substs.type_at(0), + fn_args.type_at(0), args[0].immediate(), args[1].immediate(), args[2].immediate(), @@ -183,7 +183,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { bx, true, true, - substs.type_at(0), + fn_args.type_at(0), args[0].immediate(), args[1].immediate(), args[2].immediate(), @@ -194,7 +194,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { memset_intrinsic( bx, true, - substs.type_at(0), + fn_args.type_at(0), args[0].immediate(), args[1].immediate(), args[2].immediate(), @@ -307,7 +307,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { let Some((success, failure)) = ordering.split_once('_') else { bx.sess().emit_fatal(errors::AtomicCompareExchange); }; - let ty = substs.type_at(0); + let ty = fn_args.type_at(0); if int_type_width_signed(ty, bx.tcx()).is_some() || ty.is_unsafe_ptr() { let weak = instruction == "cxchgweak"; let mut dst = args[0].immediate(); @@ -338,7 +338,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { } "load" => { - let ty = substs.type_at(0); + let ty = fn_args.type_at(0); if int_type_width_signed(ty, bx.tcx()).is_some() || ty.is_unsafe_ptr() { let layout = bx.layout_of(ty); let size = layout.size; @@ -361,7 +361,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { } "store" => { - let ty = substs.type_at(0); + let ty = fn_args.type_at(0); if int_type_width_signed(ty, bx.tcx()).is_some() || ty.is_unsafe_ptr() { let size = bx.layout_of(ty).size; let mut val = args[1].immediate(); @@ -407,7 +407,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { _ => bx.sess().emit_fatal(errors::UnknownAtomicOperation), }; - let ty = substs.type_at(0); + let ty = fn_args.type_at(0); if int_type_width_signed(ty, bx.tcx()).is_some() || ty.is_unsafe_ptr() { let mut ptr = args[0].immediate(); let mut val = args[1].immediate(); @@ -439,7 +439,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { } sym::ptr_offset_from | sym::ptr_offset_from_unsigned => { - let ty = substs.type_at(0); + let ty = fn_args.type_at(0); let pointee_size = bx.layout_of(ty).size; let a = args[0].immediate(); diff --git a/compiler/rustc_codegen_ssa/src/mir/mod.rs b/compiler/rustc_codegen_ssa/src/mir/mod.rs index 9ff6a249748..3464f910829 100644 --- a/compiler/rustc_codegen_ssa/src/mir/mod.rs +++ b/compiler/rustc_codegen_ssa/src/mir/mod.rs @@ -159,7 +159,7 @@ pub fn codegen_mir<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( cx: &'a Bx::CodegenCx, instance: Instance<'tcx>, ) { - assert!(!instance.substs.has_infer()); + assert!(!instance.args.has_infer()); let llfn = cx.get_fn(instance); diff --git a/compiler/rustc_codegen_ssa/src/mir/place.rs b/compiler/rustc_codegen_ssa/src/mir/place.rs index ab493ae5c1f..90eab55f76e 100644 --- a/compiler/rustc_codegen_ssa/src/mir/place.rs +++ b/compiler/rustc_codegen_ssa/src/mir/place.rs @@ -48,9 +48,17 @@ impl<'a, 'tcx, V: CodegenObject> PlaceRef<'tcx, V> { bx: &mut Bx, layout: TyAndLayout<'tcx>, ) -> Self { + Self::alloca_aligned(bx, layout, layout.align.abi) + } + + pub fn alloca_aligned<Bx: BuilderMethods<'a, 'tcx, Value = V>>( + bx: &mut Bx, + layout: TyAndLayout<'tcx>, + align: Align, + ) -> Self { assert!(layout.is_sized(), "tried to statically allocate unsized place"); - let tmp = bx.alloca(bx.cx().backend_type(layout), layout.align.abi); - Self::new_sized(tmp, layout) + let tmp = bx.alloca(bx.cx().backend_type(layout), align); + Self::new_sized_aligned(tmp, layout, align) } /// Returns a place for an indirect reference to an unsized place. diff --git a/compiler/rustc_codegen_ssa/src/mir/rvalue.rs b/compiler/rustc_codegen_ssa/src/mir/rvalue.rs index 956f03d2578..1f90a28eb8e 100644 --- a/compiler/rustc_codegen_ssa/src/mir/rvalue.rs +++ b/compiler/rustc_codegen_ssa/src/mir/rvalue.rs @@ -417,12 +417,12 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { } mir::CastKind::PointerCoercion(PointerCoercion::ReifyFnPointer) => { match *operand.layout.ty.kind() { - ty::FnDef(def_id, substs) => { + ty::FnDef(def_id, args) => { let instance = ty::Instance::resolve_for_fn_ptr( bx.tcx(), ty::ParamEnv::reveal_all(), def_id, - substs, + args, ) .unwrap() .polymorphize(bx.cx().tcx()); @@ -433,11 +433,11 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { } mir::CastKind::PointerCoercion(PointerCoercion::ClosureFnPointer(_)) => { match *operand.layout.ty.kind() { - ty::Closure(def_id, substs) => { + ty::Closure(def_id, args) => { let instance = Instance::resolve_closure( bx.cx().tcx(), def_id, - substs, + args, ty::ClosureKind::FnOnce, ) .expect("failed to normalize and resolve closure during codegen") @@ -711,7 +711,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { { let instance = ty::Instance { def: ty::InstanceDef::ThreadLocalShim(def_id), - substs: ty::InternalSubsts::empty(), + args: ty::GenericArgs::empty(), }; let fn_ptr = bx.get_fn_addr(instance); let fn_abi = bx.fn_abi_of_instance(instance, ty::List::empty()); diff --git a/compiler/rustc_codegen_ssa/src/mono_item.rs b/compiler/rustc_codegen_ssa/src/mono_item.rs index 27da33581a1..b72a1a07866 100644 --- a/compiler/rustc_codegen_ssa/src/mono_item.rs +++ b/compiler/rustc_codegen_ssa/src/mono_item.rs @@ -64,7 +64,7 @@ impl<'a, 'tcx: 'a> MonoItemExt<'a, 'tcx> for MonoItem<'tcx> { .typeck_body(anon_const.body) .node_type(anon_const.hir_id); let instance = match ty.kind() { - &ty::FnDef(def_id, substs) => Instance::new(def_id, substs), + &ty::FnDef(def_id, args) => Instance::new(def_id, args), _ => span_bug!(*op_sp, "asm sym is not a function"), }; @@ -138,7 +138,7 @@ impl<'a, 'tcx: 'a> MonoItemExt<'a, 'tcx> for MonoItem<'tcx> { fn to_raw_string(&self) -> String { match *self { MonoItem::Fn(instance) => { - format!("Fn({:?}, {})", instance.def, instance.substs.as_ptr().addr()) + format!("Fn({:?}, {})", instance.def, instance.args.as_ptr().addr()) } MonoItem::Static(id) => format!("Static({:?})", id), MonoItem::GlobalAsm(id) => format!("GlobalAsm({:?})", id), diff --git a/compiler/rustc_codegen_ssa/src/target_features.rs b/compiler/rustc_codegen_ssa/src/target_features.rs index 9e06fec550d..7b5d83c612a 100644 --- a/compiler/rustc_codegen_ssa/src/target_features.rs +++ b/compiler/rustc_codegen_ssa/src/target_features.rs @@ -369,13 +369,9 @@ pub fn from_target_feature( // We allow comma separation to enable multiple features. target_features.extend(value.as_str().split(',').filter_map(|feature| { let Some(feature_gate) = supported_target_features.get(feature) else { - let msg = - format!("the feature named `{}` is not valid for this target", feature); + let msg = format!("the feature named `{}` is not valid for this target", feature); let mut err = tcx.sess.struct_span_err(item.span(), msg); - err.span_label( - item.span(), - format!("`{}` is not valid for this target", feature), - ); + err.span_label(item.span(), format!("`{}` is not valid for this target", feature)); if let Some(stripped) = feature.strip_prefix('+') { let valid = supported_target_features.contains_key(stripped); if valid { diff --git a/compiler/rustc_const_eval/src/const_eval/error.rs b/compiler/rustc_const_eval/src/const_eval/error.rs index 7890d878d08..ffeff8d079a 100644 --- a/compiler/rustc_const_eval/src/const_eval/error.rs +++ b/compiler/rustc_const_eval/src/const_eval/error.rs @@ -150,8 +150,8 @@ where tcx.sess.create_err(Spanned { span, node: layout_error.into_diagnostic() }); err.code(rustc_errors::error_code!(E0080)); let Some((mut err, handler)) = err.into_diagnostic() else { - panic!("did not emit diag"); - }; + panic!("did not emit diag"); + }; for frame in frames { err.eager_subdiagnostic(handler, frame); } diff --git a/compiler/rustc_const_eval/src/const_eval/eval_queries.rs b/compiler/rustc_const_eval/src/const_eval/eval_queries.rs index 417ab78fd54..b21cb984de6 100644 --- a/compiler/rustc_const_eval/src/const_eval/eval_queries.rs +++ b/compiler/rustc_const_eval/src/const_eval/eval_queries.rs @@ -45,7 +45,7 @@ fn eval_body_using_ecx<'mir, 'tcx>( "Unexpected DefKind: {:?}", ecx.tcx.def_kind(cid.instance.def_id()) ); - let layout = ecx.layout_of(body.bound_return_ty().subst(tcx, cid.instance.substs))?; + let layout = ecx.layout_of(body.bound_return_ty().instantiate(tcx, cid.instance.args))?; assert!(layout.is_sized()); let ret = ecx.allocate(layout, MemoryKind::Stack)?; @@ -245,10 +245,10 @@ pub fn eval_to_const_value_raw_provider<'tcx>( // Catch such calls and evaluate them instead of trying to load a constant's MIR. if let ty::InstanceDef::Intrinsic(def_id) = key.value.instance.def { let ty = key.value.instance.ty(tcx, key.param_env); - let ty::FnDef(_, substs) = ty.kind() else { + let ty::FnDef(_, args) = ty.kind() else { bug!("intrinsic with type {:?}", ty); }; - return eval_nullary_intrinsic(tcx, key.param_env, def_id, substs).map_err(|error| { + return eval_nullary_intrinsic(tcx, key.param_env, def_id, args).map_err(|error| { let span = tcx.def_span(def_id); super::report( @@ -328,10 +328,10 @@ pub fn eval_to_allocation_raw_provider<'tcx>( ("static", String::new()) } else { // If the current item has generics, we'd like to enrich the message with the - // instance and its substs: to show the actual compile-time values, in addition to + // instance and its args: to show the actual compile-time values, in addition to // the expression, leading to the const eval error. let instance = &key.value.instance; - if !instance.substs.is_empty() { + if !instance.args.is_empty() { let instance = with_no_trimmed_paths!(instance.to_string()); ("const_with_path", instance) } else { diff --git a/compiler/rustc_const_eval/src/const_eval/machine.rs b/compiler/rustc_const_eval/src/const_eval/machine.rs index f9f645af41f..267795a6cb4 100644 --- a/compiler/rustc_const_eval/src/const_eval/machine.rs +++ b/compiler/rustc_const_eval/src/const_eval/machine.rs @@ -22,7 +22,7 @@ use rustc_target::spec::abi::Abi as CallAbi; use crate::errors::{LongRunning, LongRunningWarn}; use crate::interpret::{ - self, compile_time_machine, AllocId, ConstAllocation, FnVal, Frame, ImmTy, InterpCx, + self, compile_time_machine, AllocId, ConstAllocation, FnArg, FnVal, Frame, ImmTy, InterpCx, InterpResult, OpTy, PlaceTy, Pointer, Scalar, }; use crate::{errors, fluent_generated as fluent}; @@ -201,7 +201,7 @@ impl<'mir, 'tcx: 'mir> CompileTimeEvalContext<'mir, 'tcx> { fn hook_special_const_fn( &mut self, instance: ty::Instance<'tcx>, - args: &[OpTy<'tcx>], + args: &[FnArg<'tcx>], dest: &PlaceTy<'tcx>, ret: Option<mir::BasicBlock>, ) -> InterpResult<'tcx, Option<ty::Instance<'tcx>>> { @@ -210,6 +210,7 @@ impl<'mir, 'tcx: 'mir> CompileTimeEvalContext<'mir, 'tcx> { if Some(def_id) == self.tcx.lang_items().panic_display() || Some(def_id) == self.tcx.lang_items().begin_panic_fn() { + let args = self.copy_fn_args(args)?; // &str or &&str assert!(args.len() == 1); @@ -229,15 +230,16 @@ impl<'mir, 'tcx: 'mir> CompileTimeEvalContext<'mir, 'tcx> { *self.tcx, ty::ParamEnv::reveal_all(), const_def_id, - instance.substs, + instance.args, ) .unwrap() .unwrap(); return Ok(Some(new_instance)); } else if Some(def_id) == self.tcx.lang_items().align_offset_fn() { + let args = self.copy_fn_args(args)?; // For align_offset, we replace the function call if the pointer has no address. - match self.align_offset(instance, args, dest, ret)? { + match self.align_offset(instance, &args, dest, ret)? { ControlFlow::Continue(()) => return Ok(Some(instance)), ControlFlow::Break(()) => return Ok(None), } @@ -293,7 +295,7 @@ impl<'mir, 'tcx: 'mir> CompileTimeEvalContext<'mir, 'tcx> { self.eval_fn_call( FnVal::Instance(instance), (CallAbi::Rust, fn_abi), - &[addr, align], + &[FnArg::Copy(addr), FnArg::Copy(align)], /* with_caller_location = */ false, dest, ret, @@ -427,7 +429,7 @@ impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for CompileTimeInterpreter<'mir, ecx: &mut InterpCx<'mir, 'tcx, Self>, instance: ty::Instance<'tcx>, _abi: CallAbi, - args: &[OpTy<'tcx>], + args: &[FnArg<'tcx>], dest: &PlaceTy<'tcx>, ret: Option<mir::BasicBlock>, _unwind: mir::UnwindAction, // unwinding is not supported in consts diff --git a/compiler/rustc_const_eval/src/const_eval/mod.rs b/compiler/rustc_const_eval/src/const_eval/mod.rs index a3064b53db1..0a3c3914ff9 100644 --- a/compiler/rustc_const_eval/src/const_eval/mod.rs +++ b/compiler/rustc_const_eval/src/const_eval/mod.rs @@ -105,7 +105,7 @@ pub(crate) fn try_destructure_mir_constant_for_diagnostics<'tcx>( let down = ecx.operand_downcast(&op, variant).ok()?; (def.variants()[variant].fields.len(), Some(variant), down) } - ty::Tuple(substs) => (substs.len(), None, op), + ty::Tuple(args) => (args.len(), None, op), _ => bug!("cannot destructure mir constant {:?}", val), }; diff --git a/compiler/rustc_const_eval/src/const_eval/valtrees.rs b/compiler/rustc_const_eval/src/const_eval/valtrees.rs index e574df27694..9531d973eb3 100644 --- a/compiler/rustc_const_eval/src/const_eval/valtrees.rs +++ b/compiler/rustc_const_eval/src/const_eval/valtrees.rs @@ -416,9 +416,9 @@ fn valtree_into_mplace<'tcx>( debug!(?unsized_inner_ty); let inner_ty = match ty.kind() { - ty::Adt(def, substs) => { + ty::Adt(def, args) => { let i = FieldIdx::from_usize(i); - def.variant(FIRST_VARIANT).fields[i].ty(tcx, substs) + def.variant(FIRST_VARIANT).fields[i].ty(tcx, args) } ty::Tuple(inner_tys) => inner_tys[i], _ => bug!("unexpected unsized type {:?}", ty), diff --git a/compiler/rustc_const_eval/src/interpret/cast.rs b/compiler/rustc_const_eval/src/interpret/cast.rs index 83a072d6f8b..dd7a1fcc165 100644 --- a/compiler/rustc_const_eval/src/interpret/cast.rs +++ b/compiler/rustc_const_eval/src/interpret/cast.rs @@ -75,12 +75,12 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // The src operand does not matter, just its type match *src.layout.ty.kind() { - ty::FnDef(def_id, substs) => { + ty::FnDef(def_id, args) => { let instance = ty::Instance::resolve_for_fn_ptr( *self.tcx, self.param_env, def_id, - substs, + args, ) .ok_or_else(|| err_inval!(TooGeneric))?; @@ -108,11 +108,11 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // The src operand does not matter, just its type match *src.layout.ty.kind() { - ty::Closure(def_id, substs) => { + ty::Closure(def_id, args) => { let instance = ty::Instance::resolve_closure( *self.tcx, def_id, - substs, + args, ty::ClosureKind::FnOnce, ) .ok_or_else(|| err_inval!(TooGeneric))?; diff --git a/compiler/rustc_const_eval/src/interpret/discriminant.rs b/compiler/rustc_const_eval/src/interpret/discriminant.rs index 015a9beab83..f23a455c2ca 100644 --- a/compiler/rustc_const_eval/src/interpret/discriminant.rs +++ b/compiler/rustc_const_eval/src/interpret/discriminant.rs @@ -164,11 +164,9 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { ty::Adt(adt, _) => { adt.discriminants(*self.tcx).find(|(_, var)| var.val == discr_bits) } - ty::Generator(def_id, substs, _) => { - let substs = substs.as_generator(); - substs - .discriminants(def_id, *self.tcx) - .find(|(_, var)| var.val == discr_bits) + ty::Generator(def_id, args, _) => { + let args = args.as_generator(); + args.discriminants(def_id, *self.tcx).find(|(_, var)| var.val == discr_bits) } _ => span_bug!(self.cur_span(), "tagged layout for non-adt non-generator"), } diff --git a/compiler/rustc_const_eval/src/interpret/eval_context.rs b/compiler/rustc_const_eval/src/interpret/eval_context.rs index 36606ff69a6..04e046fbda3 100644 --- a/compiler/rustc_const_eval/src/interpret/eval_context.rs +++ b/compiler/rustc_const_eval/src/interpret/eval_context.rs @@ -13,7 +13,7 @@ use rustc_middle::ty::layout::{ self, FnAbiError, FnAbiOfHelpers, FnAbiRequest, LayoutError, LayoutOf, LayoutOfHelpers, TyAndLayout, }; -use rustc_middle::ty::{self, subst::SubstsRef, ParamEnv, Ty, TyCtxt, TypeFoldable}; +use rustc_middle::ty::{self, GenericArgsRef, ParamEnv, Ty, TyCtxt, TypeFoldable}; use rustc_mir_dataflow::storage::always_storage_live_locals; use rustc_session::Limit; use rustc_span::Span; @@ -91,7 +91,7 @@ pub struct Frame<'mir, 'tcx, Prov: Provenance = AllocId, Extra = ()> { /// The MIR for the function called on this frame. pub body: &'mir mir::Body<'tcx>, - /// The def_id and substs of the current function. + /// The def_id and args of the current function. pub instance: ty::Instance<'tcx>, /// Extra data for the machine. @@ -529,16 +529,16 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { .map_err(|_| err_inval!(TooGeneric)) } - /// The `substs` are assumed to already be in our interpreter "universe" (param_env). + /// The `args` are assumed to already be in our interpreter "universe" (param_env). pub(super) fn resolve( &self, def: DefId, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, ) -> InterpResult<'tcx, ty::Instance<'tcx>> { - trace!("resolve: {:?}, {:#?}", def, substs); + trace!("resolve: {:?}, {:#?}", def, args); trace!("param_env: {:#?}", self.param_env); - trace!("substs: {:#?}", substs); - match ty::Instance::resolve(*self.tcx, self.param_env, def, substs) { + trace!("args: {:#?}", args); + match ty::Instance::resolve(*self.tcx, self.param_env, def, args) { Ok(Some(instance)) => Ok(instance), Ok(None) => throw_inval!(TooGeneric), @@ -604,7 +604,9 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // the last field). Can't have foreign types here, how would we // adjust alignment and size for them? let field = layout.field(self, layout.fields.count() - 1); - let Some((unsized_size, mut unsized_align)) = self.size_and_align_of(metadata, &field)? else { + let Some((unsized_size, mut unsized_align)) = + self.size_and_align_of(metadata, &field)? + else { // A field with an extern type. We don't know the actual dynamic size // or the alignment. return Ok(None); @@ -682,11 +684,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { return_to_block: StackPopCleanup, ) -> InterpResult<'tcx> { trace!("body: {:#?}", body); - // Clobber previous return place contents, nobody is supposed to be able to see them any more - // This also checks dereferenceable, but not align. We rely on all constructed places being - // sufficiently aligned (in particular we rely on `deref_operand` checking alignment). - self.write_uninit(return_place)?; - // first push a stack frame so we have access to the local substs + // First push a stack frame so we have access to the local args let pre_frame = Frame { body, loc: Right(body.span), // Span used for errors caused during preamble. @@ -805,6 +803,8 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { throw_ub_custom!(fluent::const_eval_unwind_past_top); } + M::before_stack_pop(self, self.frame())?; + // Copy return value. Must of course happen *before* we deallocate the locals. let copy_ret_result = if !unwinding { let op = self diff --git a/compiler/rustc_const_eval/src/interpret/intern.rs b/compiler/rustc_const_eval/src/interpret/intern.rs index 7b11ad33091..107e5bec614 100644 --- a/compiler/rustc_const_eval/src/interpret/intern.rs +++ b/compiler/rustc_const_eval/src/interpret/intern.rs @@ -30,7 +30,7 @@ use super::{ use crate::const_eval; use crate::errors::{DanglingPtrInFinal, UnsupportedUntypedPointer}; -pub trait CompileTimeMachine<'mir, 'tcx, T> = Machine< +pub trait CompileTimeMachine<'mir, 'tcx: 'mir, T> = Machine< 'mir, 'tcx, MemoryKind = T, diff --git a/compiler/rustc_const_eval/src/interpret/intrinsics.rs b/compiler/rustc_const_eval/src/interpret/intrinsics.rs index ed64a7655b5..04cae23f852 100644 --- a/compiler/rustc_const_eval/src/interpret/intrinsics.rs +++ b/compiler/rustc_const_eval/src/interpret/intrinsics.rs @@ -12,7 +12,7 @@ use rustc_middle::mir::{ }; use rustc_middle::ty; use rustc_middle::ty::layout::{LayoutOf as _, ValidityRequirement}; -use rustc_middle::ty::subst::SubstsRef; +use rustc_middle::ty::GenericArgsRef; use rustc_middle::ty::{Ty, TyCtxt}; use rustc_span::symbol::{sym, Symbol}; use rustc_target::abi::{Abi, Align, Primitive, Size}; @@ -56,9 +56,9 @@ pub(crate) fn eval_nullary_intrinsic<'tcx>( tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, def_id: DefId, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, ) -> InterpResult<'tcx, ConstValue<'tcx>> { - let tp_ty = substs.type_at(0); + let tp_ty = args.type_at(0); let name = tcx.item_name(def_id); Ok(match name { sym::type_name => { @@ -123,7 +123,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { dest: &PlaceTy<'tcx, M::Provenance>, ret: Option<mir::BasicBlock>, ) -> InterpResult<'tcx, bool> { - let substs = instance.substs; + let instance_args = instance.args; let intrinsic_name = self.tcx.item_name(instance.def_id()); // First handle intrinsics without return place. @@ -187,7 +187,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { | sym::ctlz_nonzero | sym::bswap | sym::bitreverse => { - let ty = substs.type_at(0); + let ty = instance_args.type_at(0); let layout_of = self.layout_of(ty)?; let val = self.read_scalar(&args[0])?; let bits = val.to_bits(layout_of.size)?; @@ -237,7 +237,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { sym::rotate_left | sym::rotate_right => { // rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW)) // rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW)) - let layout = self.layout_of(substs.type_at(0))?; + let layout = self.layout_of(instance_args.type_at(0))?; let val = self.read_scalar(&args[0])?; let val_bits = val.to_bits(layout.size)?; let raw_shift = self.read_scalar(&args[1])?; @@ -263,7 +263,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { sym::arith_offset => { let ptr = self.read_pointer(&args[0])?; let offset_count = self.read_target_isize(&args[1])?; - let pointee_ty = substs.type_at(0); + let pointee_ty = instance_args.type_at(0); let pointee_size = i64::try_from(self.layout_of(pointee_ty)?.size.bytes()).unwrap(); let offset_bytes = offset_count.wrapping_mul(pointee_size); @@ -368,7 +368,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { assert!(self.target_isize_min() <= dist && dist <= self.target_isize_max()); isize_layout }; - let pointee_layout = self.layout_of(substs.type_at(0))?; + let pointee_layout = self.layout_of(instance_args.type_at(0))?; // If ret_layout is unsigned, we checked that so is the distance, so we are good. let val = ImmTy::from_int(dist, ret_layout); let size = ImmTy::from_int(pointee_layout.size.bytes(), ret_layout); @@ -378,7 +378,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { sym::assert_inhabited | sym::assert_zero_valid | sym::assert_mem_uninitialized_valid => { - let ty = instance.substs.type_at(0); + let ty = instance.args.type_at(0); let requirement = ValidityRequirement::from_intrinsic(intrinsic_name).unwrap(); let should_panic = !self diff --git a/compiler/rustc_const_eval/src/interpret/intrinsics/caller_location.rs b/compiler/rustc_const_eval/src/interpret/intrinsics/caller_location.rs index df5b581000b..c4fe293bfac 100644 --- a/compiler/rustc_const_eval/src/interpret/intrinsics/caller_location.rs +++ b/compiler/rustc_const_eval/src/interpret/intrinsics/caller_location.rs @@ -96,7 +96,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { let loc_ty = self .tcx .type_of(self.tcx.require_lang_item(LangItem::PanicLocation, None)) - .subst(*self.tcx, self.tcx.mk_substs(&[self.tcx.lifetimes.re_erased.into()])); + .instantiate(*self.tcx, self.tcx.mk_args(&[self.tcx.lifetimes.re_erased.into()])); let loc_layout = self.layout_of(loc_ty).unwrap(); let location = self.allocate(loc_layout, MemoryKind::CallerLocation).unwrap(); diff --git a/compiler/rustc_const_eval/src/interpret/machine.rs b/compiler/rustc_const_eval/src/interpret/machine.rs index b448e3a24c6..e101785b6e2 100644 --- a/compiler/rustc_const_eval/src/interpret/machine.rs +++ b/compiler/rustc_const_eval/src/interpret/machine.rs @@ -17,7 +17,7 @@ use rustc_target::spec::abi::Abi as CallAbi; use crate::const_eval::CheckAlignment; use super::{ - AllocBytes, AllocId, AllocRange, Allocation, ConstAllocation, Frame, ImmTy, InterpCx, + AllocBytes, AllocId, AllocRange, Allocation, ConstAllocation, FnArg, Frame, ImmTy, InterpCx, InterpResult, MemoryKind, OpTy, Operand, PlaceTy, Pointer, Provenance, Scalar, }; @@ -84,7 +84,7 @@ pub trait AllocMap<K: Hash + Eq, V> { /// Methods of this trait signifies a point where CTFE evaluation would fail /// and some use case dependent behaviour can instead be applied. -pub trait Machine<'mir, 'tcx>: Sized { +pub trait Machine<'mir, 'tcx: 'mir>: Sized { /// Additional memory kinds a machine wishes to distinguish from the builtin ones type MemoryKind: Debug + std::fmt::Display + MayLeak + Eq + 'static; @@ -182,7 +182,7 @@ pub trait Machine<'mir, 'tcx>: Sized { ecx: &mut InterpCx<'mir, 'tcx, Self>, instance: ty::Instance<'tcx>, abi: CallAbi, - args: &[OpTy<'tcx, Self::Provenance>], + args: &[FnArg<'tcx, Self::Provenance>], destination: &PlaceTy<'tcx, Self::Provenance>, target: Option<mir::BasicBlock>, unwind: mir::UnwindAction, @@ -194,7 +194,7 @@ pub trait Machine<'mir, 'tcx>: Sized { ecx: &mut InterpCx<'mir, 'tcx, Self>, fn_val: Self::ExtraFnVal, abi: CallAbi, - args: &[OpTy<'tcx, Self::Provenance>], + args: &[FnArg<'tcx, Self::Provenance>], destination: &PlaceTy<'tcx, Self::Provenance>, target: Option<mir::BasicBlock>, unwind: mir::UnwindAction, @@ -418,6 +418,18 @@ pub trait Machine<'mir, 'tcx>: Sized { Ok(()) } + /// Called on places used for in-place function argument and return value handling. + /// + /// These places need to be protected to make sure the program cannot tell whether the + /// argument/return value was actually copied or passed in-place.. + fn protect_in_place_function_argument( + ecx: &mut InterpCx<'mir, 'tcx, Self>, + place: &PlaceTy<'tcx, Self::Provenance>, + ) -> InterpResult<'tcx> { + // Without an aliasing model, all we can do is put `Uninit` into the place. + ecx.write_uninit(place) + } + /// Called immediately before a new stack frame gets pushed. fn init_frame_extra( ecx: &mut InterpCx<'mir, 'tcx, Self>, @@ -439,6 +451,14 @@ pub trait Machine<'mir, 'tcx>: Sized { Ok(()) } + /// Called just before the return value is copied to the caller-provided return place. + fn before_stack_pop( + _ecx: &InterpCx<'mir, 'tcx, Self>, + _frame: &Frame<'mir, 'tcx, Self::Provenance, Self::FrameExtra>, + ) -> InterpResult<'tcx> { + Ok(()) + } + /// Called immediately after a stack frame got popped, but before jumping back to the caller. /// The `locals` have already been destroyed! fn after_stack_pop( @@ -484,7 +504,7 @@ pub macro compile_time_machine(<$mir: lifetime, $tcx: lifetime>) { _ecx: &mut InterpCx<$mir, $tcx, Self>, fn_val: !, _abi: CallAbi, - _args: &[OpTy<$tcx>], + _args: &[FnArg<$tcx>], _destination: &PlaceTy<$tcx, Self::Provenance>, _target: Option<mir::BasicBlock>, _unwind: mir::UnwindAction, diff --git a/compiler/rustc_const_eval/src/interpret/memory.rs b/compiler/rustc_const_eval/src/interpret/memory.rs index 1125d8d1f0e..7b44a20ef03 100644 --- a/compiler/rustc_const_eval/src/interpret/memory.rs +++ b/compiler/rustc_const_eval/src/interpret/memory.rs @@ -1060,11 +1060,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { let size = Size::from_bytes(len); let Some(alloc_ref) = self.get_ptr_alloc_mut(ptr, size, Align::ONE)? else { // zero-sized access - assert_matches!( - src.next(), - None, - "iterator said it was empty but returned an element" - ); + assert_matches!(src.next(), None, "iterator said it was empty but returned an element"); return Ok(()); }; diff --git a/compiler/rustc_const_eval/src/interpret/mod.rs b/compiler/rustc_const_eval/src/interpret/mod.rs index 898d62361ab..f657f954f9c 100644 --- a/compiler/rustc_const_eval/src/interpret/mod.rs +++ b/compiler/rustc_const_eval/src/interpret/mod.rs @@ -26,6 +26,7 @@ pub use self::machine::{compile_time_machine, AllocMap, Machine, MayLeak, StackP pub use self::memory::{AllocKind, AllocRef, AllocRefMut, FnVal, Memory, MemoryKind}; pub use self::operand::{ImmTy, Immediate, OpTy, Operand}; pub use self::place::{MPlaceTy, MemPlace, MemPlaceMeta, Place, PlaceTy}; +pub use self::terminator::FnArg; pub use self::validity::{CtfeValidationMode, RefTracking}; pub use self::visitor::{MutValueVisitor, Value, ValueVisitor}; diff --git a/compiler/rustc_const_eval/src/interpret/operand.rs b/compiler/rustc_const_eval/src/interpret/operand.rs index 5f89d652fab..da45fdca1a1 100644 --- a/compiler/rustc_const_eval/src/interpret/operand.rs +++ b/compiler/rustc_const_eval/src/interpret/operand.rs @@ -575,14 +575,6 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { Ok(op) } - /// Evaluate a bunch of operands at once - pub(super) fn eval_operands( - &self, - ops: &[mir::Operand<'tcx>], - ) -> InterpResult<'tcx, Vec<OpTy<'tcx, M::Provenance>>> { - ops.iter().map(|op| self.eval_operand(op, None)).collect() - } - fn eval_ty_constant( &self, val: ty::Const<'tcx>, @@ -598,7 +590,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { throw_inval!(AlreadyReported(reported.into())) } ty::ConstKind::Unevaluated(uv) => { - let instance = self.resolve(uv.def, uv.substs)?; + let instance = self.resolve(uv.def, uv.args)?; let cid = GlobalId { instance, promoted: None }; self.ctfe_query(span, |tcx| { tcx.eval_to_valtree(self.param_env.with_const().and(cid)) @@ -627,7 +619,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { } mir::ConstantKind::Val(val, ty) => self.const_val_to_op(val, ty, layout), mir::ConstantKind::Unevaluated(uv, _) => { - let instance = self.resolve(uv.def, uv.substs)?; + let instance = self.resolve(uv.def, uv.args)?; Ok(self.eval_global(GlobalId { instance, promoted: uv.promoted }, span)?.into()) } } diff --git a/compiler/rustc_const_eval/src/interpret/place.rs b/compiler/rustc_const_eval/src/interpret/place.rs index ca1106384fd..a9b2b43f1e6 100644 --- a/compiler/rustc_const_eval/src/interpret/place.rs +++ b/compiler/rustc_const_eval/src/interpret/place.rs @@ -328,7 +328,8 @@ where }; let mplace = MemPlace { ptr: ptr.to_pointer(self)?, meta }; - // When deref'ing a pointer, the *static* alignment given by the type is what matters. + // `ref_to_mplace` is called on raw pointers even if they don't actually get dereferenced; + // we hence can't call `size_and_align_of` since that asserts more validity than we want. let align = layout.align.abi; Ok(MPlaceTy { mplace, layout, align }) } @@ -354,34 +355,37 @@ where #[inline] pub(super) fn get_place_alloc( &self, - place: &MPlaceTy<'tcx, M::Provenance>, + mplace: &MPlaceTy<'tcx, M::Provenance>, ) -> InterpResult<'tcx, Option<AllocRef<'_, 'tcx, M::Provenance, M::AllocExtra, M::Bytes>>> { - assert!(place.layout.is_sized()); - assert!(!place.meta.has_meta()); - let size = place.layout.size; - self.get_ptr_alloc(place.ptr, size, place.align) + let (size, _align) = self + .size_and_align_of_mplace(&mplace)? + .unwrap_or((mplace.layout.size, mplace.layout.align.abi)); + // Due to packed places, only `mplace.align` matters. + self.get_ptr_alloc(mplace.ptr, size, mplace.align) } #[inline] pub(super) fn get_place_alloc_mut( &mut self, - place: &MPlaceTy<'tcx, M::Provenance>, + mplace: &MPlaceTy<'tcx, M::Provenance>, ) -> InterpResult<'tcx, Option<AllocRefMut<'_, 'tcx, M::Provenance, M::AllocExtra, M::Bytes>>> { - assert!(place.layout.is_sized()); - assert!(!place.meta.has_meta()); - let size = place.layout.size; - self.get_ptr_alloc_mut(place.ptr, size, place.align) + let (size, _align) = self + .size_and_align_of_mplace(&mplace)? + .unwrap_or((mplace.layout.size, mplace.layout.align.abi)); + // Due to packed places, only `mplace.align` matters. + self.get_ptr_alloc_mut(mplace.ptr, size, mplace.align) } /// Check if this mplace is dereferenceable and sufficiently aligned. pub fn check_mplace(&self, mplace: MPlaceTy<'tcx, M::Provenance>) -> InterpResult<'tcx> { - let (size, align) = self + let (size, _align) = self .size_and_align_of_mplace(&mplace)? .unwrap_or((mplace.layout.size, mplace.layout.align.abi)); - assert!(mplace.align <= align, "dynamic alignment less strict than static one?"); - let align = if M::enforce_alignment(self).should_check() { align } else { Align::ONE }; + // Due to packed places, only `mplace.align` matters. + let align = + if M::enforce_alignment(self).should_check() { mplace.align } else { Align::ONE }; self.check_ptr_access_align(mplace.ptr, size, align, CheckInAllocMsg::DerefTest)?; Ok(()) } @@ -541,14 +545,17 @@ where // wrong type. let tcx = *self.tcx; - let Some(mut alloc) = self.get_place_alloc_mut(&MPlaceTy { mplace: dest, layout, align })? else { + let Some(mut alloc) = + self.get_place_alloc_mut(&MPlaceTy { mplace: dest, layout, align })? + else { // zero-sized access return Ok(()); }; match value { Immediate::Scalar(scalar) => { - let Abi::Scalar(s) = layout.abi else { span_bug!( + let Abi::Scalar(s) = layout.abi else { + span_bug!( self.cur_span(), "write_immediate_to_mplace: invalid Scalar layout: {layout:#?}", ) @@ -561,7 +568,8 @@ where // We checked `ptr_align` above, so all fields will have the alignment they need. // We would anyway check against `ptr_align.restrict_for_offset(b_offset)`, // which `ptr.offset(b_offset)` cannot possibly fail to satisfy. - let Abi::ScalarPair(a, b) = layout.abi else { span_bug!( + let Abi::ScalarPair(a, b) = layout.abi else { + span_bug!( self.cur_span(), "write_immediate_to_mplace: invalid ScalarPair layout: {:#?}", layout diff --git a/compiler/rustc_const_eval/src/interpret/terminator.rs b/compiler/rustc_const_eval/src/interpret/terminator.rs index 15823a5975e..c944782b487 100644 --- a/compiler/rustc_const_eval/src/interpret/terminator.rs +++ b/compiler/rustc_const_eval/src/interpret/terminator.rs @@ -1,7 +1,8 @@ use std::borrow::Cow; +use either::Either; use rustc_ast::ast::InlineAsmOptions; -use rustc_middle::ty::layout::{FnAbiOf, LayoutOf}; +use rustc_middle::ty::layout::{FnAbiOf, LayoutOf, TyAndLayout}; use rustc_middle::ty::Instance; use rustc_middle::{ mir, @@ -12,12 +13,63 @@ use rustc_target::abi::call::{ArgAbi, ArgAttribute, ArgAttributes, FnAbi, PassMo use rustc_target::spec::abi::Abi; use super::{ - FnVal, ImmTy, Immediate, InterpCx, InterpResult, MPlaceTy, Machine, MemoryKind, OpTy, Operand, - PlaceTy, Scalar, StackPopCleanup, + AllocId, FnVal, ImmTy, Immediate, InterpCx, InterpResult, MPlaceTy, Machine, MemoryKind, OpTy, + Operand, PlaceTy, Provenance, Scalar, StackPopCleanup, }; use crate::fluent_generated as fluent; +/// An argment passed to a function. +#[derive(Clone, Debug)] +pub enum FnArg<'tcx, Prov: Provenance = AllocId> { + /// Pass a copy of the given operand. + Copy(OpTy<'tcx, Prov>), + /// Allow for the argument to be passed in-place: destroy the value originally stored at that place and + /// make the place inaccessible for the duration of the function call. + InPlace(PlaceTy<'tcx, Prov>), +} + +impl<'tcx, Prov: Provenance> FnArg<'tcx, Prov> { + pub fn layout(&self) -> &TyAndLayout<'tcx> { + match self { + FnArg::Copy(op) => &op.layout, + FnArg::InPlace(place) => &place.layout, + } + } +} + impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { + /// Make a copy of the given fn_arg. Any `InPlace` are degenerated to copies, no protection of the + /// original memory occurs. + pub fn copy_fn_arg( + &self, + arg: &FnArg<'tcx, M::Provenance>, + ) -> InterpResult<'tcx, OpTy<'tcx, M::Provenance>> { + match arg { + FnArg::Copy(op) => Ok(op.clone()), + FnArg::InPlace(place) => self.place_to_op(&place), + } + } + + /// Make a copy of the given fn_args. Any `InPlace` are degenerated to copies, no protection of the + /// original memory occurs. + pub fn copy_fn_args( + &self, + args: &[FnArg<'tcx, M::Provenance>], + ) -> InterpResult<'tcx, Vec<OpTy<'tcx, M::Provenance>>> { + args.iter().map(|fn_arg| self.copy_fn_arg(fn_arg)).collect() + } + + pub fn fn_arg_field( + &mut self, + arg: &FnArg<'tcx, M::Provenance>, + field: usize, + ) -> InterpResult<'tcx, FnArg<'tcx, M::Provenance>> { + Ok(match arg { + FnArg::Copy(op) => FnArg::Copy(self.operand_field(op, field)?), + FnArg::InPlace(place) => FnArg::InPlace(self.place_field(place, field)?), + }) + } + pub(super) fn eval_terminator( &mut self, terminator: &mir::Terminator<'tcx>, @@ -68,14 +120,14 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { let old_stack = self.frame_idx(); let old_loc = self.frame().loc; let func = self.eval_operand(func, None)?; - let args = self.eval_operands(args)?; + let args = self.eval_fn_call_arguments(args)?; let fn_sig_binder = func.layout.ty.fn_sig(*self.tcx); let fn_sig = self.tcx.normalize_erasing_late_bound_regions(self.param_env, fn_sig_binder); let extra_args = &args[fn_sig.inputs().len()..]; let extra_args = - self.tcx.mk_type_list_from_iter(extra_args.iter().map(|arg| arg.layout.ty)); + self.tcx.mk_type_list_from_iter(extra_args.iter().map(|arg| arg.layout().ty)); let (fn_val, fn_abi, with_caller_location) = match *func.layout.ty.kind() { ty::FnPtr(_sig) => { @@ -83,8 +135,8 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { let fn_val = self.get_ptr_fn(fn_ptr)?; (fn_val, self.fn_abi_of_fn_ptr(fn_sig_binder, extra_args)?, false) } - ty::FnDef(def_id, substs) => { - let instance = self.resolve(def_id, substs)?; + ty::FnDef(def_id, args) => { + let instance = self.resolve(def_id, args)?; ( FnVal::Instance(instance), self.fn_abi_of_instance(instance, extra_args)?, @@ -185,6 +237,21 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { Ok(()) } + /// Evaluate the arguments of a function call + pub(super) fn eval_fn_call_arguments( + &mut self, + ops: &[mir::Operand<'tcx>], + ) -> InterpResult<'tcx, Vec<FnArg<'tcx, M::Provenance>>> { + ops.iter() + .map(|op| { + Ok(match op { + mir::Operand::Move(place) => FnArg::InPlace(self.eval_place(*place)?), + _ => FnArg::Copy(self.eval_operand(op, None)?), + }) + }) + .collect() + } + fn check_argument_compat( caller_abi: &ArgAbi<'tcx, Ty<'tcx>>, callee_abi: &ArgAbi<'tcx, Ty<'tcx>>, @@ -275,7 +342,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { fn pass_argument<'x, 'y>( &mut self, caller_args: &mut impl Iterator< - Item = (&'x OpTy<'tcx, M::Provenance>, &'y ArgAbi<'tcx, Ty<'tcx>>), + Item = (&'x FnArg<'tcx, M::Provenance>, &'y ArgAbi<'tcx, Ty<'tcx>>), >, callee_abi: &ArgAbi<'tcx, Ty<'tcx>>, callee_arg: &PlaceTy<'tcx, M::Provenance>, @@ -295,21 +362,25 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // Now, check if !Self::check_argument_compat(caller_abi, callee_abi) { let callee_ty = format!("{}", callee_arg.layout.ty); - let caller_ty = format!("{}", caller_arg.layout.ty); + let caller_ty = format!("{}", caller_arg.layout().ty); throw_ub_custom!( fluent::const_eval_incompatible_types, callee_ty = callee_ty, caller_ty = caller_ty, ) } + // We work with a copy of the argument for now; if this is in-place argument passing, we + // will later protect the source it comes from. This means the callee cannot observe if we + // did in-place of by-copy argument passing, except for pointer equality tests. + let caller_arg_copy = self.copy_fn_arg(&caller_arg)?; // Special handling for unsized parameters. - if caller_arg.layout.is_unsized() { + if caller_arg_copy.layout.is_unsized() { // `check_argument_compat` ensures that both have the same type, so we know they will use the metadata the same way. - assert_eq!(caller_arg.layout.ty, callee_arg.layout.ty); + assert_eq!(caller_arg_copy.layout.ty, callee_arg.layout.ty); // We have to properly pre-allocate the memory for the callee. - // So let's tear down some wrappers. + // So let's tear down some abstractions. // This all has to be in memory, there are no immediate unsized values. - let src = caller_arg.assert_mem_place(); + let src = caller_arg_copy.assert_mem_place(); // The destination cannot be one of these "spread args". let (dest_frame, dest_local) = callee_arg.assert_local(); // We are just initializing things, so there can't be anything here yet. @@ -319,7 +390,10 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { )); // Allocate enough memory to hold `src`. let Some((size, align)) = self.size_and_align_of_mplace(&src)? else { - span_bug!(self.cur_span(), "unsized fn arg with `extern` type tail should not be allowed") + span_bug!( + self.cur_span(), + "unsized fn arg with `extern` type tail should not be allowed" + ) }; let ptr = self.allocate_ptr(size, align, MemoryKind::Stack)?; let dest_place = @@ -331,7 +405,12 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // FIXME: Depending on the PassMode, this should reset some padding to uninitialized. (This // is true for all `copy_op`, but there are a lot of special cases for argument passing // specifically.) - self.copy_op(&caller_arg, callee_arg, /*allow_transmute*/ true) + self.copy_op(&caller_arg_copy, callee_arg, /*allow_transmute*/ true)?; + // If this was an in-place pass, protect the place it comes from for the duration of the call. + if let FnArg::InPlace(place) = caller_arg { + M::protect_in_place_function_argument(self, place)?; + } + Ok(()) } /// Call this function -- pushing the stack frame and initializing the arguments. @@ -346,7 +425,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { &mut self, fn_val: FnVal<'tcx, M::ExtraFnVal>, (caller_abi, caller_fn_abi): (Abi, &FnAbi<'tcx, Ty<'tcx>>), - args: &[OpTy<'tcx, M::Provenance>], + args: &[FnArg<'tcx, M::Provenance>], with_caller_location: bool, destination: &PlaceTy<'tcx, M::Provenance>, target: Option<mir::BasicBlock>, @@ -372,8 +451,15 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { match instance.def { ty::InstanceDef::Intrinsic(def_id) => { assert!(self.tcx.is_intrinsic(def_id)); - // caller_fn_abi is not relevant here, we interpret the arguments directly for each intrinsic. - M::call_intrinsic(self, instance, args, destination, target, unwind) + // FIXME: Should `InPlace` arguments be reset to uninit? + M::call_intrinsic( + self, + instance, + &self.copy_fn_args(args)?, + destination, + target, + unwind, + ) } ty::InstanceDef::VTableShim(..) | ty::InstanceDef::ReifyShim(..) @@ -385,10 +471,18 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { | ty::InstanceDef::ThreadLocalShim(..) | ty::InstanceDef::Item(_) => { // We need MIR for this fn - let Some((body, instance)) = - M::find_mir_or_eval_fn(self, instance, caller_abi, args, destination, target, unwind)? else { - return Ok(()); - }; + let Some((body, instance)) = M::find_mir_or_eval_fn( + self, + instance, + caller_abi, + args, + destination, + target, + unwind, + )? + else { + return Ok(()); + }; // Compute callee information using the `instance` returned by // `find_mir_or_eval_fn`. @@ -428,7 +522,13 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { "caller ABI: {:?}, args: {:#?}", caller_abi, args.iter() - .map(|arg| (arg.layout.ty, format!("{:?}", **arg))) + .map(|arg| ( + arg.layout().ty, + match arg { + FnArg::Copy(op) => format!("copy({:?})", *op), + FnArg::InPlace(place) => format!("in-place({:?})", *place), + } + )) .collect::<Vec<_>>() ); trace!( @@ -449,7 +549,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // last incoming argument. These two iterators do not have the same type, // so to keep the code paths uniform we accept an allocation // (for RustCall ABI only). - let caller_args: Cow<'_, [OpTy<'tcx, M::Provenance>]> = + let caller_args: Cow<'_, [FnArg<'tcx, M::Provenance>]> = if caller_abi == Abi::RustCall && !args.is_empty() { // Untuple let (untuple_arg, args) = args.split_last().unwrap(); @@ -458,11 +558,10 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { args.iter() .map(|a| Ok(a.clone())) .chain( - (0..untuple_arg.layout.fields.count()) - .map(|i| self.operand_field(untuple_arg, i)), + (0..untuple_arg.layout().fields.count()) + .map(|i| self.fn_arg_field(untuple_arg, i)), ) - .collect::<InterpResult<'_, Vec<OpTy<'tcx, M::Provenance>>>>( - )?, + .collect::<InterpResult<'_, Vec<_>>>()?, ) } else { // Plain arg passing @@ -523,6 +622,14 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { caller_ty = caller_ty, ) } + // Ensure the return place is aligned and dereferenceable, and protect it for + // in-place return value passing. + if let Either::Left(mplace) = destination.as_mplace_or_local() { + self.check_mplace(mplace)?; + } else { + // Nothing to do for locals, they are always properly allocated and aligned. + } + M::protect_in_place_function_argument(self, destination)?; }; match res { Err(err) => { @@ -538,7 +645,10 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // We have to implement all "object safe receivers". So we have to go search for a // pointer or `dyn Trait` type, but it could be wrapped in newtypes. So recursively // unwrap those newtypes until we are there. - let mut receiver = args[0].clone(); + // An `InPlace` does nothing here, we keep the original receiver intact. We can't + // really pass the argument in-place anyway, and we are constructing a new + // `Immediate` receiver. + let mut receiver = self.copy_fn_arg(&args[0])?; let receiver_place = loop { match receiver.layout.ty.kind() { ty::Ref(..) | ty::RawPtr(..) => { @@ -603,8 +713,12 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { .tcx .struct_tail_erasing_lifetimes(receiver_place.layout.ty, self.param_env); let ty::Dynamic(data, _, ty::Dyn) = receiver_tail.kind() else { - span_bug!(self.cur_span(), "dynamic call on non-`dyn` type {}", receiver_tail) - }; + span_bug!( + self.cur_span(), + "dynamic call on non-`dyn` type {}", + receiver_tail + ) + }; assert!(receiver_place.layout.is_unsized()); // Get the required information from the vtable. @@ -622,7 +736,9 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // Now determine the actual method to call. We can do that in two different ways and // compare them to ensure everything fits. - let Some(ty::VtblEntry::Method(fn_inst)) = self.get_vtable_entries(vptr)?.get(idx).copied() else { + let Some(ty::VtblEntry::Method(fn_inst)) = + self.get_vtable_entries(vptr)?.get(idx).copied() + else { // FIXME(fee1-dead) these could be variants of the UB info enum instead of this throw_ub_custom!(fluent::const_eval_dyn_call_not_a_method); }; @@ -632,7 +748,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { let trait_def_id = tcx.trait_of_item(def_id).unwrap(); let virtual_trait_ref = - ty::TraitRef::from_method(tcx, trait_def_id, instance.substs); + ty::TraitRef::from_method(tcx, trait_def_id, instance.args); let existential_trait_ref = ty::ExistentialTraitRef::erase_self_ty(tcx, virtual_trait_ref); let concrete_trait_ref = existential_trait_ref.with_self_ty(tcx, dyn_ty); @@ -641,18 +757,20 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { tcx, self.param_env, def_id, - instance.substs.rebase_onto(tcx, trait_def_id, concrete_trait_ref.substs), + instance.args.rebase_onto(tcx, trait_def_id, concrete_trait_ref.args), ) .unwrap(); assert_eq!(fn_inst, concrete_method); } // Adjust receiver argument. Layout can be any (thin) ptr. - args[0] = ImmTy::from_immediate( - Scalar::from_maybe_pointer(adjusted_receiver, self).into(), - self.layout_of(Ty::new_mut_ptr(self.tcx.tcx, dyn_ty))?, - ) - .into(); + args[0] = FnArg::Copy( + ImmTy::from_immediate( + Scalar::from_maybe_pointer(adjusted_receiver, self).into(), + self.layout_of(Ty::new_mut_ptr(self.tcx.tcx, dyn_ty))?, + ) + .into(), + ); trace!("Patched receiver operand to {:#?}", args[0]); // recurse with concrete function self.eval_fn_call( @@ -710,7 +828,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { self.eval_fn_call( FnVal::Instance(instance), (Abi::Rust, fn_abi), - &[arg.into()], + &[FnArg::Copy(arg.into())], false, &ret.into(), Some(target), diff --git a/compiler/rustc_const_eval/src/interpret/util.rs b/compiler/rustc_const_eval/src/interpret/util.rs index 22bdd4d2c3f..b3319442388 100644 --- a/compiler/rustc_const_eval/src/interpret/util.rs +++ b/compiler/rustc_const_eval/src/interpret/util.rs @@ -33,12 +33,12 @@ where match *ty.kind() { ty::Param(_) => ControlFlow::Break(FoundParam), - ty::Closure(def_id, substs) - | ty::Generator(def_id, substs, ..) - | ty::FnDef(def_id, substs) => { + ty::Closure(def_id, args) + | ty::Generator(def_id, args, ..) + | ty::FnDef(def_id, args) => { let instance = ty::InstanceDef::Item(def_id); let unused_params = self.tcx.unused_generic_params(instance); - for (index, subst) in substs.into_iter().enumerate() { + for (index, subst) in args.into_iter().enumerate() { let index = index .try_into() .expect("more generic parameters than can fit into a `u32`"); diff --git a/compiler/rustc_const_eval/src/interpret/visitor.rs b/compiler/rustc_const_eval/src/interpret/visitor.rs index 7a14459399c..879ae198f7e 100644 --- a/compiler/rustc_const_eval/src/interpret/visitor.rs +++ b/compiler/rustc_const_eval/src/interpret/visitor.rs @@ -13,7 +13,7 @@ use super::{InterpCx, MPlaceTy, Machine, OpTy, PlaceTy}; /// A thing that we can project into, and that has a layout. /// This wouldn't have to depend on `Machine` but with the current type inference, /// that's just more convenient to work with (avoids repeating all the `Machine` bounds). -pub trait Value<'mir, 'tcx, M: Machine<'mir, 'tcx>>: Sized { +pub trait Value<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>>: Sized { /// Gets this value's layout. fn layout(&self) -> TyAndLayout<'tcx>; @@ -54,7 +54,7 @@ pub trait Value<'mir, 'tcx, M: Machine<'mir, 'tcx>>: Sized { /// A thing that we can project into given *mutable* access to `ecx`, and that has a layout. /// This wouldn't have to depend on `Machine` but with the current type inference, /// that's just more convenient to work with (avoids repeating all the `Machine` bounds). -pub trait ValueMut<'mir, 'tcx, M: Machine<'mir, 'tcx>>: Sized { +pub trait ValueMut<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>>: Sized { /// Gets this value's layout. fn layout(&self) -> TyAndLayout<'tcx>; diff --git a/compiler/rustc_const_eval/src/transform/check_consts/check.rs b/compiler/rustc_const_eval/src/transform/check_consts/check.rs index 14540e8dfe7..d8b8fa927c7 100644 --- a/compiler/rustc_const_eval/src/transform/check_consts/check.rs +++ b/compiler/rustc_const_eval/src/transform/check_consts/check.rs @@ -8,8 +8,8 @@ use rustc_infer::infer::TyCtxtInferExt; use rustc_infer::traits::{ImplSource, Obligation, ObligationCause}; use rustc_middle::mir::visit::{MutatingUseContext, NonMutatingUseContext, PlaceContext, Visitor}; use rustc_middle::mir::*; -use rustc_middle::ty::subst::{GenericArgKind, InternalSubsts}; use rustc_middle::ty::{self, adjustment::PointerCoercion, Instance, InstanceDef, Ty, TyCtxt}; +use rustc_middle::ty::{GenericArgKind, GenericArgs}; use rustc_middle::ty::{TraitRef, TypeVisitableExt}; use rustc_mir_dataflow::{self, Analysis}; use rustc_span::{sym, Span, Symbol}; @@ -701,8 +701,8 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> { let fn_ty = func.ty(body, tcx); - let (mut callee, mut substs) = match *fn_ty.kind() { - ty::FnDef(def_id, substs) => (def_id, substs), + let (mut callee, mut fn_args) = match *fn_ty.kind() { + ty::FnDef(def_id, fn_args) => (def_id, fn_args), ty::FnPtr(_) => { self.check_op(ops::FnCallIndirect); @@ -721,7 +721,7 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> { let infcx = tcx.infer_ctxt().build(); let ocx = ObligationCtxt::new(&infcx); - let predicates = tcx.predicates_of(callee).instantiate(tcx, substs); + let predicates = tcx.predicates_of(callee).instantiate(tcx, fn_args); let cause = ObligationCause::new( terminator.source_info.span, self.body.source.def_id().expect_local(), @@ -746,7 +746,7 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> { self.check_op(ops::FnCallNonConst { caller, callee, - substs, + args: fn_args, span: *fn_span, call_source: *call_source, feature: Some(sym::const_trait_impl), @@ -754,7 +754,7 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> { return; } - let trait_ref = TraitRef::from_method(tcx, trait_id, substs); + let trait_ref = TraitRef::from_method(tcx, trait_id, fn_args); let trait_ref = trait_ref.with_constness(ty::BoundConstness::ConstIfConst); let obligation = Obligation::new(tcx, ObligationCause::dummy(), param_env, trait_ref); @@ -778,8 +778,7 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> { if trait_ref.self_ty().is_closure() && tcx.fn_trait_kind_from_def_id(trait_id).is_some() => { - let ty::Closure(closure_def_id, substs) = - *trait_ref.self_ty().kind() + let ty::Closure(closure_def_id, fn_args) = *trait_ref.self_ty().kind() else { unreachable!() }; @@ -787,7 +786,7 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> { self.check_op(ops::FnCallNonConst { caller, callee, - substs, + args: fn_args, span: *fn_span, call_source: *call_source, feature: None, @@ -803,9 +802,9 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> { .iter() .find(|did| tcx.item_name(**did) == callee_name) { - // using internal substs is ok here, since this is only + // using internal args is ok here, since this is only // used for the `resolve` call below - substs = InternalSubsts::identity_for_item(tcx, did); + fn_args = GenericArgs::identity_for_item(tcx, did); callee = did; } @@ -813,7 +812,7 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> { self.check_op(ops::FnCallNonConst { caller, callee, - substs, + args: fn_args, span: *fn_span, call_source: *call_source, feature: None, @@ -829,7 +828,7 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> { && tcx.has_attr(callee_trait, sym::const_trait) && Some(callee_trait) == tcx.trait_of_item(caller.to_def_id()) // Can only call methods when it's `<Self as TheTrait>::f`. - && tcx.types.self_param == substs.type_at(0) + && tcx.types.self_param == fn_args.type_at(0) { nonconst_call_permission = true; } @@ -856,7 +855,7 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> { self.check_op(ops::FnCallNonConst { caller, callee, - substs, + args: fn_args, span: *fn_span, call_source: *call_source, feature: None, @@ -869,7 +868,7 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> { // Resolve a trait method call to its concrete implementation, which may be in a // `const` trait impl. - let instance = Instance::resolve(tcx, param_env, callee, substs); + let instance = Instance::resolve(tcx, param_env, callee, fn_args); debug!("Resolving ({:?}) -> {:?}", callee, instance); if let Ok(Some(func)) = instance { if let InstanceDef::Item(def) = func.def { @@ -916,7 +915,7 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> { self.check_op(ops::FnCallNonConst { caller, callee, - substs, + args: fn_args, span: *fn_span, call_source: *call_source, feature: None, diff --git a/compiler/rustc_const_eval/src/transform/check_consts/mod.rs b/compiler/rustc_const_eval/src/transform/check_consts/mod.rs index 8ebfee8878c..e77fb4ea2a2 100644 --- a/compiler/rustc_const_eval/src/transform/check_consts/mod.rs +++ b/compiler/rustc_const_eval/src/transform/check_consts/mod.rs @@ -68,11 +68,11 @@ impl<'mir, 'tcx> ConstCx<'mir, 'tcx> { pub fn fn_sig(&self) -> PolyFnSig<'tcx> { let did = self.def_id().to_def_id(); if self.tcx.is_closure(did) { - let ty = self.tcx.type_of(did).subst_identity(); - let ty::Closure(_, substs) = ty.kind() else { bug!("type_of closure not ty::Closure") }; - substs.as_closure().sig() + let ty = self.tcx.type_of(did).instantiate_identity(); + let ty::Closure(_, args) = ty.kind() else { bug!("type_of closure not ty::Closure") }; + args.as_closure().sig() } else { - self.tcx.fn_sig(did).subst_identity() + self.tcx.fn_sig(did).instantiate_identity() } } } diff --git a/compiler/rustc_const_eval/src/transform/check_consts/ops.rs b/compiler/rustc_const_eval/src/transform/check_consts/ops.rs index 4eb278252c1..81337079af2 100644 --- a/compiler/rustc_const_eval/src/transform/check_consts/ops.rs +++ b/compiler/rustc_const_eval/src/transform/check_consts/ops.rs @@ -9,9 +9,9 @@ use rustc_infer::infer::TyCtxtInferExt; use rustc_infer::traits::{ImplSource, Obligation, ObligationCause}; use rustc_middle::mir::{self, CallSource}; use rustc_middle::ty::print::with_no_trimmed_paths; -use rustc_middle::ty::subst::{GenericArgKind, SubstsRef}; use rustc_middle::ty::TraitRef; use rustc_middle::ty::{suggest_constraining_type_param, Adt, Closure, FnDef, FnPtr, Param, Ty}; +use rustc_middle::ty::{GenericArgKind, GenericArgsRef}; use rustc_middle::util::{call_kind, CallDesugaringKind, CallKind}; use rustc_session::parse::feature_err; use rustc_span::symbol::sym; @@ -98,7 +98,7 @@ impl<'tcx> NonConstOp<'tcx> for FnCallIndirect { pub struct FnCallNonConst<'tcx> { pub caller: LocalDefId, pub callee: DefId, - pub substs: SubstsRef<'tcx>, + pub args: GenericArgsRef<'tcx>, pub span: Span, pub call_source: CallSource, pub feature: Option<Symbol>, @@ -110,11 +110,11 @@ impl<'tcx> NonConstOp<'tcx> for FnCallNonConst<'tcx> { ccx: &ConstCx<'_, 'tcx>, _: Span, ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> { - let FnCallNonConst { caller, callee, substs, span, call_source, feature } = *self; + let FnCallNonConst { caller, callee, args, span, call_source, feature } = *self; let ConstCx { tcx, param_env, .. } = *ccx; let diag_trait = |err, self_ty: Ty<'_>, trait_id| { - let trait_ref = TraitRef::from_method(tcx, trait_id, substs); + let trait_ref = TraitRef::from_method(tcx, trait_id, args); match self_ty.kind() { Param(param_ty) => { @@ -154,7 +154,7 @@ impl<'tcx> NonConstOp<'tcx> for FnCallNonConst<'tcx> { }; let call_kind = - call_kind(tcx, ccx.param_env, callee, substs, span, call_source.from_hir_call(), None); + call_kind(tcx, ccx.param_env, callee, args, span, call_source.from_hir_call(), None); debug!(?call_kind); @@ -226,7 +226,7 @@ impl<'tcx> NonConstOp<'tcx> for FnCallNonConst<'tcx> { let mut sugg = None; if Some(trait_id) == ccx.tcx.lang_items().eq_trait() { - match (substs[0].unpack(), substs[1].unpack()) { + match (args[0].unpack(), args[1].unpack()) { (GenericArgKind::Type(self_ty), GenericArgKind::Type(rhs_ty)) if self_ty == rhs_ty && self_ty.is_ref() @@ -297,7 +297,7 @@ impl<'tcx> NonConstOp<'tcx> for FnCallNonConst<'tcx> { .create_err(errors::NonConstFmtMacroCall { span, kind: ccx.const_kind() }), _ => ccx.tcx.sess.create_err(errors::NonConstFnCall { span, - def_path_str: ccx.tcx.def_path_str_with_substs(callee, substs), + def_path_str: ccx.tcx.def_path_str_with_args(callee, args), kind: ccx.const_kind(), }), }; diff --git a/compiler/rustc_const_eval/src/transform/check_consts/qualifs.rs b/compiler/rustc_const_eval/src/transform/check_consts/qualifs.rs index 015a4aa94cd..0ef7ace6965 100644 --- a/compiler/rustc_const_eval/src/transform/check_consts/qualifs.rs +++ b/compiler/rustc_const_eval/src/transform/check_consts/qualifs.rs @@ -7,7 +7,7 @@ use rustc_hir::LangItem; use rustc_infer::infer::TyCtxtInferExt; use rustc_middle::mir; use rustc_middle::mir::*; -use rustc_middle::ty::{self, subst::SubstsRef, AdtDef, Ty}; +use rustc_middle::ty::{self, AdtDef, GenericArgsRef, Ty}; use rustc_trait_selection::traits::{ self, ImplSource, Obligation, ObligationCause, ObligationCtxt, SelectionContext, }; @@ -72,7 +72,7 @@ pub trait Qualif { fn in_adt_inherently<'tcx>( cx: &ConstCx<'_, 'tcx>, adt: AdtDef<'tcx>, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, ) -> bool; } @@ -97,7 +97,7 @@ impl Qualif for HasMutInterior { fn in_adt_inherently<'tcx>( _cx: &ConstCx<'_, 'tcx>, adt: AdtDef<'tcx>, - _: SubstsRef<'tcx>, + _: GenericArgsRef<'tcx>, ) -> bool { // Exactly one type, `UnsafeCell`, has the `HasMutInterior` qualif inherently. // It arises structurally for all other types. @@ -127,7 +127,7 @@ impl Qualif for NeedsDrop { fn in_adt_inherently<'tcx>( cx: &ConstCx<'_, 'tcx>, adt: AdtDef<'tcx>, - _: SubstsRef<'tcx>, + _: GenericArgsRef<'tcx>, ) -> bool { adt.has_dtor(cx.tcx) } @@ -193,7 +193,7 @@ impl Qualif for NeedsNonConstDrop { fn in_adt_inherently<'tcx>( cx: &ConstCx<'_, 'tcx>, adt: AdtDef<'tcx>, - _: SubstsRef<'tcx>, + _: GenericArgsRef<'tcx>, ) -> bool { adt.has_non_const_dtor(cx.tcx) } @@ -221,9 +221,9 @@ impl Qualif for CustomEq { fn in_adt_inherently<'tcx>( cx: &ConstCx<'_, 'tcx>, def: AdtDef<'tcx>, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, ) -> bool { - let ty = Ty::new_adt(cx.tcx, def, substs); + let ty = Ty::new_adt(cx.tcx, def, args); !ty.is_structural_eq_shallow(cx.tcx) } } @@ -276,9 +276,9 @@ where Rvalue::Aggregate(kind, operands) => { // Return early if we know that the struct or enum being constructed is always // qualified. - if let AggregateKind::Adt(adt_did, _, substs, ..) = **kind { + if let AggregateKind::Adt(adt_did, _, args, ..) = **kind { let def = cx.tcx.adt_def(adt_did); - if Q::in_adt_inherently(cx, def, substs) { + if Q::in_adt_inherently(cx, def, args) { return true; } if def.is_union() && Q::in_any_value_of_ty(cx, rvalue.ty(cx.body, cx.tcx)) { @@ -360,7 +360,7 @@ where ConstantKind::Val(..) => None, }; - if let Some(mir::UnevaluatedConst { def, substs: _, promoted }) = uneval { + if let Some(mir::UnevaluatedConst { def, args: _, promoted }) = uneval { // Use qualifs of the type for the promoted. Promoteds in MIR body should be possible // only for `NeedsNonConstDrop` with precise drop checking. This is the only const // check performed after the promotion. Verify that with an assertion. diff --git a/compiler/rustc_const_eval/src/transform/promote_consts.rs b/compiler/rustc_const_eval/src/transform/promote_consts.rs index 1b39a76e460..d79c65f1d1f 100644 --- a/compiler/rustc_const_eval/src/transform/promote_consts.rs +++ b/compiler/rustc_const_eval/src/transform/promote_consts.rs @@ -16,7 +16,7 @@ use rustc_hir as hir; use rustc_middle::mir; use rustc_middle::mir::visit::{MutVisitor, MutatingUseContext, PlaceContext, Visitor}; use rustc_middle::mir::*; -use rustc_middle::ty::subst::InternalSubsts; +use rustc_middle::ty::GenericArgs; use rustc_middle::ty::{self, List, Ty, TyCtxt, TypeVisitableExt}; use rustc_span::Span; @@ -759,11 +759,7 @@ impl<'a, 'tcx> Promoter<'a, 'tcx> { let (mut rvalue, source_info) = { let statement = &mut self.source[loc.block].statements[loc.statement_index]; let StatementKind::Assign(box (_, rhs)) = &mut statement.kind else { - span_bug!( - statement.source_info.span, - "{:?} is not an assignment", - statement - ); + span_bug!(statement.source_info.span, "{:?} is not an assignment", statement); }; ( @@ -845,8 +841,8 @@ impl<'a, 'tcx> Promoter<'a, 'tcx> { let mut promoted_operand = |ty, span| { promoted.span = span; promoted.local_decls[RETURN_PLACE] = LocalDecl::new(ty, span); - let substs = tcx.erase_regions(InternalSubsts::identity_for_item(tcx, def)); - let uneval = mir::UnevaluatedConst { def, substs, promoted: Some(promoted_id) }; + let args = tcx.erase_regions(GenericArgs::identity_for_item(tcx, def)); + let uneval = mir::UnevaluatedConst { def, args, promoted: Some(promoted_id) }; Operand::Constant(Box::new(Constant { span, @@ -859,7 +855,9 @@ impl<'a, 'tcx> Promoter<'a, 'tcx> { let local_decls = &mut self.source.local_decls; let loc = candidate.location; let statement = &mut blocks[loc.block].statements[loc.statement_index]; - let StatementKind::Assign(box (_, Rvalue::Ref(region, borrow_kind, place))) = &mut statement.kind else { + let StatementKind::Assign(box (_, Rvalue::Ref(region, borrow_kind, place))) = + &mut statement.kind + else { bug!() }; diff --git a/compiler/rustc_const_eval/src/transform/validate.rs b/compiler/rustc_const_eval/src/transform/validate.rs index 4cc923cd935..ea0d90dbd51 100644 --- a/compiler/rustc_const_eval/src/transform/validate.rs +++ b/compiler/rustc_const_eval/src/transform/validate.rs @@ -214,9 +214,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { stack.clear(); stack.insert(bb); loop { - let Some(parent)= parent[bb].take() else { - break - }; + let Some(parent) = parent[bb].take() else { break }; let no_cycle = stack.insert(parent); if !no_cycle { self.fail( @@ -360,8 +358,8 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { }; let kind = match parent_ty.ty.kind() { - &ty::Alias(ty::Opaque, ty::AliasTy { def_id, substs, .. }) => { - self.tcx.type_of(def_id).subst(self.tcx, substs).kind() + &ty::Alias(ty::Opaque, ty::AliasTy { def_id, args, .. }) => { + self.tcx.type_of(def_id).instantiate(self.tcx, args).kind() } kind => kind, }; @@ -374,23 +372,23 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { }; check_equal(self, location, *f_ty); } - ty::Adt(adt_def, substs) => { + ty::Adt(adt_def, args) => { let var = parent_ty.variant_index.unwrap_or(FIRST_VARIANT); let Some(field) = adt_def.variant(var).fields.get(f) else { fail_out_of_bounds(self, location); return; }; - check_equal(self, location, field.ty(self.tcx, substs)); + check_equal(self, location, field.ty(self.tcx, args)); } - ty::Closure(_, substs) => { - let substs = substs.as_closure(); - let Some(f_ty) = substs.upvar_tys().nth(f.as_usize()) else { + ty::Closure(_, args) => { + let args = args.as_closure(); + let Some(f_ty) = args.upvar_tys().nth(f.as_usize()) else { fail_out_of_bounds(self, location); return; }; check_equal(self, location, f_ty); } - &ty::Generator(def_id, substs, _) => { + &ty::Generator(def_id, args, _) => { let f_ty = if let Some(var) = parent_ty.variant_index { let gen_body = if def_id == self.body.source.def_id() { self.body @@ -399,7 +397,10 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { }; let Some(layout) = gen_body.generator_layout() else { - self.fail(location, format!("No generator layout for {:?}", parent_ty)); + self.fail( + location, + format!("No generator layout for {:?}", parent_ty), + ); return; }; @@ -409,13 +410,16 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { }; let Some(f_ty) = layout.field_tys.get(local) else { - self.fail(location, format!("Out of bounds local {:?} for {:?}", local, parent_ty)); + self.fail( + location, + format!("Out of bounds local {:?} for {:?}", local, parent_ty), + ); return; }; f_ty.ty } else { - let Some(f_ty) = substs.as_generator().prefix_tys().nth(f.index()) else { + let Some(f_ty) = args.as_generator().prefix_tys().nth(f.index()) else { fail_out_of_bounds(self, location); return; }; @@ -730,7 +734,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { current_ty = self.tcx.normalize_erasing_regions(self.param_env, f_ty); } - ty::Adt(adt_def, substs) => { + ty::Adt(adt_def, args) => { if adt_def.is_enum() { self.fail( location, @@ -744,7 +748,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { return; }; - let f_ty = field.ty(self.tcx, substs); + let f_ty = field.ty(self.tcx, args); current_ty = self.tcx.normalize_erasing_regions(self.param_env, f_ty); } _ => { diff --git a/compiler/rustc_const_eval/src/util/type_name.rs b/compiler/rustc_const_eval/src/util/type_name.rs index 4f01e0a24a5..14a840ad1b1 100644 --- a/compiler/rustc_const_eval/src/util/type_name.rs +++ b/compiler/rustc_const_eval/src/util/type_name.rs @@ -4,8 +4,7 @@ use rustc_hir::definitions::DisambiguatedDefPathData; use rustc_middle::ty::{ self, print::{PrettyPrinter, Print, Printer}, - subst::{GenericArg, GenericArgKind}, - Ty, TyCtxt, + GenericArg, GenericArgKind, Ty, TyCtxt, }; use std::fmt::Write; @@ -56,11 +55,11 @@ impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> { } // Types with identity (print the module path). - ty::Adt(ty::AdtDef(Interned(&ty::AdtDefData { did: def_id, .. }, _)), substs) - | ty::FnDef(def_id, substs) - | ty::Alias(ty::Projection | ty::Opaque, ty::AliasTy { def_id, substs, .. }) - | ty::Closure(def_id, substs) - | ty::Generator(def_id, substs, _) => self.print_def_path(def_id, substs), + ty::Adt(ty::AdtDef(Interned(&ty::AdtDefData { did: def_id, .. }, _)), args) + | ty::FnDef(def_id, args) + | ty::Alias(ty::Projection | ty::Opaque, ty::AliasTy { def_id, args, .. }) + | ty::Closure(def_id, args) + | ty::Generator(def_id, args, _) => self.print_def_path(def_id, args), ty::Foreign(def_id) => self.print_def_path(def_id, &[]), ty::Alias(ty::Weak, _) => bug!("type_name: unexpected weak projection"), diff --git a/compiler/rustc_data_structures/src/graph/dominators/mod.rs b/compiler/rustc_data_structures/src/graph/dominators/mod.rs index a5db14d9102..85ef2de9b5e 100644 --- a/compiler/rustc_data_structures/src/graph/dominators/mod.rs +++ b/compiler/rustc_data_structures/src/graph/dominators/mod.rs @@ -176,9 +176,7 @@ pub fn dominators<G: ControlFlowGraph>(graph: &G) -> Dominators<G::Node> { // // ...this may be the case if a MirPass modifies the CFG to remove // or rearrange certain blocks/edges. - let Some(v) = real_to_pre_order[v] else { - continue - }; + let Some(v) = real_to_pre_order[v] else { continue }; // eval returns a vertex x from which semi[x] is minimum among // vertices semi[v] +> x *> v. diff --git a/compiler/rustc_data_structures/src/unord.rs b/compiler/rustc_data_structures/src/unord.rs index 2b21815b687..47c56eba7ad 100644 --- a/compiler/rustc_data_structures/src/unord.rs +++ b/compiler/rustc_data_structures/src/unord.rs @@ -31,6 +31,7 @@ use crate::{ /// /// It's still possible to do the same thing with an `Fn` by using interior mutability, /// but the chance of doing it accidentally is reduced. +#[derive(Clone)] pub struct UnordItems<T, I: Iterator<Item = T>>(I); impl<T, I: Iterator<Item = T>> UnordItems<T, I> { @@ -167,6 +168,14 @@ impl<T: Ord, I: Iterator<Item = T>> UnordItems<T, I> { } } +/// A marker trait specifying that `Self` can consume `UnordItems<_>` without +/// exposing any internal ordering. +/// +/// Note: right now this is just a marker trait. It could be extended to contain +/// some useful, common methods though, like `len`, `clear`, or the various +/// kinds of `to_sorted`. +trait UnordCollection {} + /// This is a set collection type that tries very hard to not expose /// any internal iteration. This is a useful property when trying to /// uphold the determinism invariants imposed by the query system. @@ -181,6 +190,8 @@ pub struct UnordSet<V: Eq + Hash> { inner: FxHashSet<V>, } +impl<V: Eq + Hash> UnordCollection for UnordSet<V> {} + impl<V: Eq + Hash> Default for UnordSet<V> { #[inline] fn default() -> Self { @@ -195,6 +206,11 @@ impl<V: Eq + Hash> UnordSet<V> { } #[inline] + pub fn with_capacity(capacity: usize) -> Self { + Self { inner: FxHashSet::with_capacity_and_hasher(capacity, Default::default()) } + } + + #[inline] pub fn len(&self) -> usize { self.inner.len() } @@ -258,9 +274,9 @@ impl<V: Eq + Hash> UnordSet<V> { #[inline] pub fn to_sorted_stable_ord(&self) -> Vec<V> where - V: Ord + StableOrd + Copy, + V: Ord + StableOrd + Clone, { - let mut items: Vec<V> = self.inner.iter().copied().collect(); + let mut items: Vec<V> = self.inner.iter().cloned().collect(); items.sort_unstable(); items } @@ -279,16 +295,28 @@ impl<V: Eq + Hash> UnordSet<V> { to_sorted_vec(hcx, self.inner.into_iter(), cache_sort_key, |x| x) } - // We can safely extend this UnordSet from a set of unordered values because that - // won't expose the internal ordering anywhere. #[inline] - pub fn extend_unord<I: Iterator<Item = V>>(&mut self, items: UnordItems<V, I>) { - self.inner.extend(items.0) + pub fn clear(&mut self) { + self.inner.clear(); } +} + +pub trait ExtendUnord<T> { + /// Extend this unord collection with the given `UnordItems`. + /// This method is called `extend_unord` instead of just `extend` so it + /// does not conflict with `Extend::extend`. Otherwise there would be many + /// places where the two methods would have to be explicitly disambiguated + /// via UFCS. + fn extend_unord<I: Iterator<Item = T>>(&mut self, items: UnordItems<T, I>); +} +// Note: it is important that `C` implements `UnordCollection` in addition to +// `Extend`, otherwise this impl would leak the internal iteration order of +// `items`, e.g. when calling `some_vec.extend_unord(some_unord_items)`. +impl<C: Extend<T> + UnordCollection, T> ExtendUnord<T> for C { #[inline] - pub fn clear(&mut self) { - self.inner.clear(); + fn extend_unord<I: Iterator<Item = T>>(&mut self, items: UnordItems<T, I>) { + self.extend(items.0) } } @@ -312,6 +340,12 @@ impl<V: Hash + Eq> From<FxHashSet<V>> for UnordSet<V> { } } +impl<V: Hash + Eq, I: Iterator<Item = V>> From<UnordItems<V, I>> for UnordSet<V> { + fn from(value: UnordItems<V, I>) -> Self { + UnordSet { inner: FxHashSet::from_iter(value.0) } + } +} + impl<HCX, V: Hash + Eq + HashStable<HCX>> HashStable<HCX> for UnordSet<V> { #[inline] fn hash_stable(&self, hcx: &mut HCX, hasher: &mut StableHasher) { @@ -333,6 +367,8 @@ pub struct UnordMap<K: Eq + Hash, V> { inner: FxHashMap<K, V>, } +impl<K: Eq + Hash, V> UnordCollection for UnordMap<K, V> {} + impl<K: Eq + Hash, V> Default for UnordMap<K, V> { #[inline] fn default() -> Self { @@ -363,6 +399,11 @@ impl<K: Hash + Eq, V, I: Iterator<Item = (K, V)>> From<UnordItems<(K, V), I>> fo impl<K: Eq + Hash, V> UnordMap<K, V> { #[inline] + pub fn with_capacity(capacity: usize) -> Self { + Self { inner: FxHashMap::with_capacity_and_hasher(capacity, Default::default()) } + } + + #[inline] pub fn len(&self) -> usize { self.inner.len() } @@ -428,13 +469,6 @@ impl<K: Eq + Hash, V> UnordMap<K, V> { UnordItems(self.inner.into_iter()) } - // We can safely extend this UnordMap from a set of unordered values because that - // won't expose the internal ordering anywhere. - #[inline] - pub fn extend<I: Iterator<Item = (K, V)>>(&mut self, items: UnordItems<(K, V), I>) { - self.inner.extend(items.0) - } - /// Returns the entries of this map in stable sort order (as defined by `ToStableHashKey`). /// /// The `cache_sort_key` parameter controls if [slice::sort_by_cached_key] or @@ -554,15 +588,10 @@ impl<V> UnordBag<V> { pub fn into_items(self) -> UnordItems<V, impl Iterator<Item = V>> { UnordItems(self.inner.into_iter()) } - - // We can safely extend this UnordSet from a set of unordered values because that - // won't expose the internal ordering anywhere. - #[inline] - pub fn extend<I: Iterator<Item = V>>(&mut self, items: UnordItems<V, I>) { - self.inner.extend(items.0) - } } +impl<T> UnordCollection for UnordBag<T> {} + impl<T> Extend<T> for UnordBag<T> { fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) { self.inner.extend(iter) diff --git a/compiler/rustc_driver_impl/src/lib.rs b/compiler/rustc_driver_impl/src/lib.rs index 2e26ce111f0..25c043149e8 100644 --- a/compiler/rustc_driver_impl/src/lib.rs +++ b/compiler/rustc_driver_impl/src/lib.rs @@ -279,9 +279,6 @@ fn run_compiler( let sopts = config::build_session_options(&mut early_error_handler, &matches); - // Set parallel mode before thread pool creation, which will create `Lock`s. - interface::set_thread_safe_mode(&sopts.unstable_opts); - if let Some(ref code) = matches.opt_str("explain") { handle_explain(&early_error_handler, diagnostics_registry(), code, sopts.color); return Ok(()); diff --git a/compiler/rustc_errors/src/markdown/parse.rs b/compiler/rustc_errors/src/markdown/parse.rs index 362a451fde6..d3a08da6283 100644 --- a/compiler/rustc_errors/src/markdown/parse.rs +++ b/compiler/rustc_errors/src/markdown/parse.rs @@ -272,7 +272,7 @@ fn parse_ordered_li(buf: &[u8]) -> Parsed<'_> { fn get_indented_section(buf: &[u8]) -> (&[u8], &[u8]) { let mut end = buf.len(); for (idx, window) in buf.windows(2).enumerate() { - let &[ch, next_ch] = window else {unreachable!("always 2 elements")}; + let &[ch, next_ch] = window else { unreachable!("always 2 elements") }; if idx >= buf.len().saturating_sub(2) && next_ch == b'\n' { // End of stream end = buf.len().saturating_sub(1); diff --git a/compiler/rustc_errors/src/markdown/term.rs b/compiler/rustc_errors/src/markdown/term.rs index e45ba6d2cda..88c3c8b9ff2 100644 --- a/compiler/rustc_errors/src/markdown/term.rs +++ b/compiler/rustc_errors/src/markdown/term.rs @@ -149,7 +149,7 @@ fn write_wrapping<B: io::Write>( let Some((end_idx, _ch)) = iter.nth(ch_count) else { // Write entire line buf.write_all(to_write.as_bytes())?; - cur.set(cur.get()+to_write.chars().count()); + cur.set(cur.get() + to_write.chars().count()); break; }; diff --git a/compiler/rustc_expand/src/base.rs b/compiler/rustc_expand/src/base.rs index 8a251ea29d7..4b0907cf15a 100644 --- a/compiler/rustc_expand/src/base.rs +++ b/compiler/rustc_expand/src/base.rs @@ -1366,7 +1366,7 @@ pub fn parse_macro_name_and_helper_attrs( return None; } let Some(trait_attr) = list[0].meta_item() else { - diag.emit_err(errors::NotAMetaItem {span: list[0].span()}); + diag.emit_err(errors::NotAMetaItem { span: list[0].span() }); return None; }; let trait_ident = match trait_attr.ident() { diff --git a/compiler/rustc_expand/src/config.rs b/compiler/rustc_expand/src/config.rs index 3e43eae006f..4ec5ac22e90 100644 --- a/compiler/rustc_expand/src/config.rs +++ b/compiler/rustc_expand/src/config.rs @@ -313,9 +313,10 @@ impl<'a> StripUnconfigured<'a> { /// the attribute is incorrect. pub(crate) fn expand_cfg_attr(&self, attr: &Attribute, recursive: bool) -> Vec<Attribute> { let Some((cfg_predicate, expanded_attrs)) = - rustc_parse::parse_cfg_attr(attr, &self.sess.parse_sess) else { - return vec![]; - }; + rustc_parse::parse_cfg_attr(attr, &self.sess.parse_sess) + else { + return vec![]; + }; // Lint on zero attributes in source. if expanded_attrs.is_empty() { @@ -365,7 +366,9 @@ impl<'a> StripUnconfigured<'a> { // Use the `#` in `#[cfg_attr(pred, attr)]` as the `#` token // for `attr` when we expand it to `#[attr]` let mut orig_trees = orig_tokens.into_trees(); - let TokenTree::Token(pound_token @ Token { kind: TokenKind::Pound, .. }, _) = orig_trees.next().unwrap() else { + let TokenTree::Token(pound_token @ Token { kind: TokenKind::Pound, .. }, _) = + orig_trees.next().unwrap() + else { panic!("Bad tokens for attribute {:?}", attr); }; let pound_span = pound_token.span; @@ -373,7 +376,9 @@ impl<'a> StripUnconfigured<'a> { let mut trees = vec![AttrTokenTree::Token(pound_token, Spacing::Alone)]; if attr.style == AttrStyle::Inner { // For inner attributes, we do the same thing for the `!` in `#![some_attr]` - let TokenTree::Token(bang_token @ Token { kind: TokenKind::Not, .. }, _) = orig_trees.next().unwrap() else { + let TokenTree::Token(bang_token @ Token { kind: TokenKind::Not, .. }, _) = + orig_trees.next().unwrap() + else { panic!("Bad tokens for attribute {:?}", attr); }; trees.push(AttrTokenTree::Token(bang_token, Spacing::Alone)); diff --git a/compiler/rustc_expand/src/expand.rs b/compiler/rustc_expand/src/expand.rs index 9850723a857..3b6db9fd39c 100644 --- a/compiler/rustc_expand/src/expand.rs +++ b/compiler/rustc_expand/src/expand.rs @@ -651,7 +651,8 @@ impl<'a, 'b> MacroExpander<'a, 'b> { ExpandResult::Ready(match invoc.kind { InvocationKind::Bang { mac, .. } => match ext { SyntaxExtensionKind::Bang(expander) => { - let Ok(tok_result) = expander.expand(self.cx, span, mac.args.tokens.clone()) else { + let Ok(tok_result) = expander.expand(self.cx, span, mac.args.tokens.clone()) + else { return ExpandResult::Ready(fragment_kind.dummy(span)); }; self.parse_ast_fragment(tok_result, fragment_kind, &mac.path, span) @@ -704,7 +705,8 @@ impl<'a, 'b> MacroExpander<'a, 'b> { self.cx.emit_err(UnsupportedKeyValue { span }); } let inner_tokens = attr_item.args.inner_tokens(); - let Ok(tok_result) = expander.expand(self.cx, span, inner_tokens, tokens) else { + let Ok(tok_result) = expander.expand(self.cx, span, inner_tokens, tokens) + else { return ExpandResult::Ready(fragment_kind.dummy(span)); }; self.parse_ast_fragment(tok_result, fragment_kind, &attr_item.path, span) @@ -1087,9 +1089,7 @@ impl InvocationCollectorNode for P<ast::Item> { // Work around borrow checker not seeing through `P`'s deref. let (ident, span, mut attrs) = (node.ident, node.span, mem::take(&mut node.attrs)); - let ItemKind::Mod(_, mod_kind) = &mut node.kind else { - unreachable!() - }; + let ItemKind::Mod(_, mod_kind) = &mut node.kind else { unreachable!() }; let ecx = &mut collector.cx; let (file_path, dir_path, dir_ownership) = match mod_kind { diff --git a/compiler/rustc_expand/src/mbe/diagnostics.rs b/compiler/rustc_expand/src/mbe/diagnostics.rs index 3593bed2d02..03de33dc854 100644 --- a/compiler/rustc_expand/src/mbe/diagnostics.rs +++ b/compiler/rustc_expand/src/mbe/diagnostics.rs @@ -42,7 +42,8 @@ pub(super) fn failed_to_match_macro<'cx>( return result; } - let Some(BestFailure { token, msg: label, remaining_matcher, .. }) = tracker.best_failure else { + let Some(BestFailure { token, msg: label, remaining_matcher, .. }) = tracker.best_failure + else { return DummyResult::any(sp); }; diff --git a/compiler/rustc_expand/src/mbe/metavar_expr.rs b/compiler/rustc_expand/src/mbe/metavar_expr.rs index 6e919615019..b6382dcb894 100644 --- a/compiler/rustc_expand/src/mbe/metavar_expr.rs +++ b/compiler/rustc_expand/src/mbe/metavar_expr.rs @@ -104,13 +104,10 @@ fn parse_depth<'sess>( span: Span, ) -> PResult<'sess, usize> { let Some(tt) = iter.next() else { return Ok(0) }; - let TokenTree::Token(token::Token { - kind: token::TokenKind::Literal(lit), .. - }, _) = tt else { - return Err(sess.span_diagnostic.struct_span_err( - span, - "meta-variable expression depth must be a literal" - )); + let TokenTree::Token(token::Token { kind: token::TokenKind::Literal(lit), .. }, _) = tt else { + return Err(sess + .span_diagnostic + .struct_span_err(span, "meta-variable expression depth must be a literal")); }; if let Ok(lit_kind) = LitKind::from_token_lit(*lit) && let LitKind::Int(n_u128, LitIntType::Unsuffixed) = lit_kind diff --git a/compiler/rustc_expand/src/mbe/transcribe.rs b/compiler/rustc_expand/src/mbe/transcribe.rs index d523d3eacbe..a5f83b88f7e 100644 --- a/compiler/rustc_expand/src/mbe/transcribe.rs +++ b/compiler/rustc_expand/src/mbe/transcribe.rs @@ -182,9 +182,7 @@ pub(super) fn transcribe<'a>( LockstepIterSize::Constraint(len, _) => { // We do this to avoid an extra clone above. We know that this is a // sequence already. - let mbe::TokenTree::Sequence(sp, seq) = seq else { - unreachable!() - }; + let mbe::TokenTree::Sequence(sp, seq) = seq else { unreachable!() }; // Is the repetition empty? if len == 0 { @@ -399,7 +397,9 @@ fn lockstep_iter_size( } TokenTree::MetaVarExpr(_, expr) => { let default_rslt = LockstepIterSize::Unconstrained; - let Some(ident) = expr.ident() else { return default_rslt; }; + let Some(ident) = expr.ident() else { + return default_rslt; + }; let name = MacroRulesNormalizedIdent::new(ident); match lookup_cur_matched(name, interpolations, repeats) { Some(MatchedSeq(ads)) => { diff --git a/compiler/rustc_feature/src/active.rs b/compiler/rustc_feature/src/active.rs index 5185820a727..56a2c5eff3d 100644 --- a/compiler/rustc_feature/src/active.rs +++ b/compiler/rustc_feature/src/active.rs @@ -392,13 +392,13 @@ declare_features! ( /// Allows `dyn* Trait` objects. (incomplete, dyn_star, "1.65.0", Some(102425), None), // Uses generic effect parameters for ~const bounds - (active, effects, "CURRENT_RUSTC_VERSION", Some(102090), None), + (active, effects, "1.72.0", Some(102090), None), /// Allows `X..Y` patterns. (active, exclusive_range_pattern, "1.11.0", Some(37854), None), /// Allows exhaustive pattern matching on types that contain uninhabited types. (active, exhaustive_patterns, "1.13.0", Some(51085), None), /// Allows explicit tail calls via `become` expression. - (incomplete, explicit_tail_calls, "CURRENT_RUSTC_VERSION", Some(112788), None), + (incomplete, explicit_tail_calls, "1.72.0", Some(112788), None), /// Allows using `efiapi`, `sysv64` and `win64` as calling convention /// for functions with varargs. (active, extended_varargs_abi_support, "1.65.0", Some(100189), None), @@ -445,7 +445,7 @@ declare_features! ( // Allows setting the threshold for the `large_assignments` lint. (active, large_assignments, "1.52.0", Some(83518), None), /// Allow to have type alias types for inter-crate use. - (active, lazy_type_alias, "CURRENT_RUSTC_VERSION", Some(112792), None), + (active, lazy_type_alias, "1.72.0", Some(112792), None), /// Allows `if/while p && let q = r && ...` chains. (active, let_chains, "1.37.0", Some(53667), None), /// Allows using `reason` in lint attributes and the `#[expect(lint)]` lint check. @@ -546,7 +546,7 @@ declare_features! ( /// not changed from prior instances of the same struct (RFC #2528) (active, type_changing_struct_update, "1.58.0", Some(86555), None), /// Allows using type privacy lints (`private_interfaces`, `private_bounds`, `unnameable_types`). - (active, type_privacy_lints, "CURRENT_RUSTC_VERSION", Some(48054), None), + (active, type_privacy_lints, "1.72.0", Some(48054), None), /// Enables rustc to generate code that instructs libstd to NOT ignore SIGPIPE. (active, unix_sigpipe, "1.65.0", Some(97889), None), /// Allows unsized fn parameters. diff --git a/compiler/rustc_feature/src/builtin_attrs.rs b/compiler/rustc_feature/src/builtin_attrs.rs index 36600004404..a183cfd8776 100644 --- a/compiler/rustc_feature/src/builtin_attrs.rs +++ b/compiler/rustc_feature/src/builtin_attrs.rs @@ -625,6 +625,12 @@ pub const BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[ ErrorFollowing, INTERNAL_UNSTABLE ), + rustc_attr!( + rustc_confusables, Normal, + template!(List: r#""name1", "name2", ..."#), + ErrorFollowing, + INTERNAL_UNSTABLE, + ), // Enumerates "identity-like" conversion methods to suggest on type mismatch. rustc_attr!( rustc_conversion_suggestion, Normal, template!(Word), WarnFollowing, INTERNAL_UNSTABLE @@ -812,7 +818,7 @@ pub const BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[ TEST, rustc_error, Normal, template!(Word, List: "delay_span_bug_from_inside_query"), WarnFollowingWordOnly ), - rustc_attr!(TEST, rustc_dump_user_substs, Normal, template!(Word), WarnFollowing), + rustc_attr!(TEST, rustc_dump_user_args, Normal, template!(Word), WarnFollowing), rustc_attr!(TEST, rustc_evaluate_where_clauses, Normal, template!(Word), WarnFollowing), rustc_attr!( TEST, rustc_if_this_changed, Normal, template!(Word, List: "DepNode"), DuplicatesOk diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index 6c419471de1..35ef30114b7 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -3150,7 +3150,9 @@ impl<'hir> Item<'hir> { /// Expect an [`ItemKind::ForeignMod`] or panic. #[track_caller] pub fn expect_foreign_mod(&self) -> (Abi, &'hir [ForeignItemRef]) { - let ItemKind::ForeignMod { abi, items } = self.kind else { self.expect_failed("a foreign module") }; + let ItemKind::ForeignMod { abi, items } = self.kind else { + self.expect_failed("a foreign module") + }; (abi, items) } @@ -3201,14 +3203,18 @@ impl<'hir> Item<'hir> { pub fn expect_trait( self, ) -> (IsAuto, Unsafety, &'hir Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]) { - let ItemKind::Trait(is_auto, unsafety, gen, bounds, items) = self.kind else { self.expect_failed("a trait") }; + let ItemKind::Trait(is_auto, unsafety, gen, bounds, items) = self.kind else { + self.expect_failed("a trait") + }; (is_auto, unsafety, gen, bounds, items) } /// Expect an [`ItemKind::TraitAlias`] or panic. #[track_caller] pub fn expect_trait_alias(&self) -> (&'hir Generics<'hir>, GenericBounds<'hir>) { - let ItemKind::TraitAlias(gen, bounds) = self.kind else { self.expect_failed("a trait alias") }; + let ItemKind::TraitAlias(gen, bounds) = self.kind else { + self.expect_failed("a trait alias") + }; (gen, bounds) } diff --git a/compiler/rustc_hir_analysis/src/astconv/bounds.rs b/compiler/rustc_hir_analysis/src/astconv/bounds.rs index b13de770137..30145b1a185 100644 --- a/compiler/rustc_hir_analysis/src/astconv/bounds.rs +++ b/compiler/rustc_hir_analysis/src/astconv/bounds.rs @@ -341,8 +341,8 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { // If we have an method return type bound, then we need to substitute // the method's early bound params with suitable late-bound params. let mut num_bound_vars = candidate.bound_vars().len(); - let substs = - candidate.skip_binder().substs.extend_to(tcx, assoc_item.def_id, |param, _| { + let args = + candidate.skip_binder().args.extend_to(tcx, assoc_item.def_id, |param, _| { let subst = match param.kind { ty::GenericParamDefKind::Lifetime => ty::Region::new_late_bound( tcx, @@ -422,7 +422,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { // params (and trait ref's late bound params). This logic is very similar to // `Predicate::subst_supertrait`, and it's no coincidence why. let shifted_output = tcx.shift_bound_var_indices(num_bound_vars, output); - let subst_output = ty::EarlyBinder::bind(shifted_output).subst(tcx, substs); + let subst_output = ty::EarlyBinder::bind(shifted_output).instantiate(tcx, args); let bound_vars = tcx.late_bound_vars(binding.hir_id); ty::Binder::bind_with_vars(subst_output, bound_vars) @@ -438,16 +438,16 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { infer_args: false, }; - let substs_trait_ref_and_assoc_item = self.create_substs_for_associated_item( + let args_trait_ref_and_assoc_item = self.create_args_for_associated_item( path_span, assoc_item.def_id, &item_segment, - trait_ref.substs, + trait_ref.args, ); - debug!(?substs_trait_ref_and_assoc_item); + debug!(?args_trait_ref_and_assoc_item); - tcx.mk_alias_ty(assoc_item.def_id, substs_trait_ref_and_assoc_item) + tcx.mk_alias_ty(assoc_item.def_id, args_trait_ref_and_assoc_item) }) }; @@ -533,7 +533,7 @@ impl<'tcx> dyn AstConv<'tcx> + '_ { tcx, reported, tcx.type_of(assoc_item_def_id) - .subst(tcx, projection_ty.skip_binder().substs), + .instantiate(tcx, projection_ty.skip_binder().args), ) .into(), _ => unreachable!(), diff --git a/compiler/rustc_hir_analysis/src/astconv/errors.rs b/compiler/rustc_hir_analysis/src/astconv/errors.rs index ddf99853b2e..7f4927bbb98 100644 --- a/compiler/rustc_hir_analysis/src/astconv/errors.rs +++ b/compiler/rustc_hir_analysis/src/astconv/errors.rs @@ -123,7 +123,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { let all_candidate_names: Vec<_> = all_candidates() .flat_map(|r| self.tcx().associated_items(r.def_id()).in_definition_order()) .filter_map(|item| { - if item.opt_rpitit_info.is_none() && item.kind == ty::AssocKind::Type { + if !item.is_impl_trait_in_trait() && item.kind == ty::AssocKind::Type { Some(item.name) } else { None @@ -164,7 +164,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { self.tcx().associated_items(*trait_def_id).in_definition_order() }) .filter_map(|item| { - if item.opt_rpitit_info.is_none() && item.kind == ty::AssocKind::Type { + if !item.is_impl_trait_in_trait() && item.kind == ty::AssocKind::Type { Some(item.name) } else { None @@ -247,7 +247,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { "the candidate".into() }; - let impl_ty = tcx.at(span).type_of(impl_).subst_identity(); + let impl_ty = tcx.at(span).type_of(impl_).instantiate_identity(); let note = format!("{title} is defined in an impl for the type `{impl_ty}`"); if let Some(span) = note_span { @@ -295,7 +295,9 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { let type_candidates = candidates .iter() .take(limit) - .map(|&(impl_, _)| format!("- `{}`", tcx.at(span).type_of(impl_).subst_identity())) + .map(|&(impl_, _)| { + format!("- `{}`", tcx.at(span).type_of(impl_).instantiate_identity()) + }) .collect::<Vec<_>>() .join("\n"); let additional_types = if candidates.len() > limit { @@ -356,13 +358,13 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { // `<Foo as Iterator>::Item = String`. let projection_ty = pred.skip_binder().projection_ty; - let substs_with_infer_self = tcx.mk_substs_from_iter( + let args_with_infer_self = tcx.mk_args_from_iter( std::iter::once(Ty::new_var(tcx, ty::TyVid::from_u32(0)).into()) - .chain(projection_ty.substs.iter().skip(1)), + .chain(projection_ty.args.iter().skip(1)), ); let quiet_projection_ty = - tcx.mk_alias_ty(projection_ty.def_id, substs_with_infer_self); + tcx.mk_alias_ty(projection_ty.def_id, args_with_infer_self); let term = pred.skip_binder().term; diff --git a/compiler/rustc_hir_analysis/src/astconv/generics.rs b/compiler/rustc_hir_analysis/src/astconv/generics.rs index 39d1d1f2de5..e81c61d80ed 100644 --- a/compiler/rustc_hir_analysis/src/astconv/generics.rs +++ b/compiler/rustc_hir_analysis/src/astconv/generics.rs @@ -11,7 +11,7 @@ use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::DefId; use rustc_hir::GenericArg; use rustc_middle::ty::{ - self, subst, subst::SubstsRef, GenericParamDef, GenericParamDefKind, IsSuggestable, Ty, TyCtxt, + self, GenericArgsRef, GenericParamDef, GenericParamDefKind, IsSuggestable, Ty, TyCtxt, }; use rustc_session::lint::builtin::LATE_BOUND_LIFETIME_ARGUMENTS; use rustc_span::{symbol::kw, Span}; @@ -76,7 +76,7 @@ fn generic_arg_mismatch_err( Res::Def(DefKind::TyParam, src_def_id) => { if let Some(param_local_id) = param.def_id.as_local() { let param_name = tcx.hir().ty_param_name(param_local_id); - let param_type = tcx.type_of(param.def_id).subst_identity(); + let param_type = tcx.type_of(param.def_id).instantiate_identity(); if param_type.is_suggestable(tcx, false) { err.span_suggestion( tcx.def_span(src_def_id), @@ -146,14 +146,14 @@ fn generic_arg_mismatch_err( /// /// To start, we are given the `def_id` of the thing we are /// creating the substitutions for, and a partial set of -/// substitutions `parent_substs`. In general, the substitutions +/// substitutions `parent_args`. In general, the substitutions /// for an item begin with substitutions for all the "parents" of /// that item -- e.g., for a method it might include the /// parameters from the impl. /// /// Therefore, the method begins by walking down these parents, /// starting with the outermost parent and proceed inwards until -/// it reaches `def_id`. For each parent `P`, it will check `parent_substs` +/// it reaches `def_id`. For each parent `P`, it will check `parent_args` /// first to see if the parent's substitutions are listed in there. If so, /// we can append those and move on. Otherwise, it invokes the /// three callback functions: @@ -168,15 +168,15 @@ fn generic_arg_mismatch_err( /// instantiate a `GenericArg`. /// - `inferred_kind`: if no parameter was provided, and inference is enabled, then /// creates a suitable inference variable. -pub fn create_substs_for_generic_args<'tcx, 'a>( +pub fn create_args_for_parent_generic_args<'tcx, 'a>( tcx: TyCtxt<'tcx>, def_id: DefId, - parent_substs: &[subst::GenericArg<'tcx>], + parent_args: &[ty::GenericArg<'tcx>], has_self: bool, self_ty: Option<Ty<'tcx>>, arg_count: &GenericArgCountResult, ctx: &mut impl CreateSubstsForGenericArgsCtxt<'a, 'tcx>, -) -> SubstsRef<'tcx> { +) -> GenericArgsRef<'tcx> { // Collect the segments of the path; we need to substitute arguments // for parameters throughout the entire path (wherever there are // generic parameters). @@ -191,27 +191,27 @@ pub fn create_substs_for_generic_args<'tcx, 'a>( // We manually build up the substitution, rather than using convenience // methods in `subst.rs`, so that we can iterate over the arguments and // parameters in lock-step linearly, instead of trying to match each pair. - let mut substs: SmallVec<[subst::GenericArg<'tcx>; 8]> = SmallVec::with_capacity(count); + let mut args: SmallVec<[ty::GenericArg<'tcx>; 8]> = SmallVec::with_capacity(count); // Iterate over each segment of the path. while let Some((def_id, defs)) = stack.pop() { let mut params = defs.params.iter().peekable(); // If we have already computed substitutions for parents, we can use those directly. while let Some(¶m) = params.peek() { - if let Some(&kind) = parent_substs.get(param.index as usize) { - substs.push(kind); + if let Some(&kind) = parent_args.get(param.index as usize) { + args.push(kind); params.next(); } else { break; } } - // `Self` is handled first, unless it's been handled in `parent_substs`. + // `Self` is handled first, unless it's been handled in `parent_args`. if has_self { if let Some(¶m) = params.peek() { if param.index == 0 { if let GenericParamDefKind::Type { .. } = param.kind { - substs.push( + args.push( self_ty .map(|ty| ty.into()) .unwrap_or_else(|| ctx.inferred_kind(None, param, true)), @@ -226,7 +226,7 @@ pub fn create_substs_for_generic_args<'tcx, 'a>( let (generic_args, infer_args) = ctx.args_for_def_id(def_id); let args_iter = generic_args.iter().flat_map(|generic_args| generic_args.args.iter()); - let mut args = args_iter.clone().peekable(); + let mut args_iter = args_iter.clone().peekable(); // If we encounter a type or const when we expect a lifetime, we infer the lifetimes. // If we later encounter a lifetime, we know that the arguments were provided in the @@ -239,7 +239,7 @@ pub fn create_substs_for_generic_args<'tcx, 'a>( // provided, matching them with the generic parameters we expect. // Mismatches can occur as a result of elided lifetimes, or for malformed // input. We try to handle both sensibly. - match (args.peek(), params.peek()) { + match (args_iter.peek(), params.peek()) { (Some(&arg), Some(¶m)) => { match (arg, ¶m.kind, arg_count.explicit_late_bound) { (GenericArg::Lifetime(_), GenericParamDefKind::Lifetime, _) @@ -253,8 +253,8 @@ pub fn create_substs_for_generic_args<'tcx, 'a>( GenericParamDefKind::Const { .. }, _, ) => { - substs.push(ctx.provided_kind(param, arg)); - args.next(); + args.push(ctx.provided_kind(param, arg)); + args_iter.next(); params.next(); } ( @@ -264,7 +264,7 @@ pub fn create_substs_for_generic_args<'tcx, 'a>( ) => { // We expected a lifetime argument, but got a type or const // argument. That means we're inferring the lifetimes. - substs.push(ctx.inferred_kind(None, param, infer_args)); + args.push(ctx.inferred_kind(None, param, infer_args)); force_infer_lt = Some((arg, param)); params.next(); } @@ -273,7 +273,7 @@ pub fn create_substs_for_generic_args<'tcx, 'a>( // the presence of explicit late bounds. This is most likely // due to the presence of the explicit bound so we're just going to // ignore it. - args.next(); + args_iter.next(); } (_, _, _) => { // We expected one kind of parameter, but the user provided @@ -327,7 +327,7 @@ pub fn create_substs_for_generic_args<'tcx, 'a>( // errors. In this case, we're simply going to ignore the argument // and any following arguments. The rest of the parameters will be // inferred. - while args.next().is_some() {} + while args_iter.next().is_some() {} } } } @@ -360,7 +360,7 @@ pub fn create_substs_for_generic_args<'tcx, 'a>( (None, Some(¶m)) => { // If there are fewer arguments than parameters, it means // we're inferring the remaining arguments. - substs.push(ctx.inferred_kind(Some(&substs), param, infer_args)); + args.push(ctx.inferred_kind(Some(&args), param, infer_args)); params.next(); } @@ -369,7 +369,7 @@ pub fn create_substs_for_generic_args<'tcx, 'a>( } } - tcx.mk_substs(&substs) + tcx.mk_args(&args) } /// Checks that the correct number of generic arguments have been provided. diff --git a/compiler/rustc_hir_analysis/src/astconv/mod.rs b/compiler/rustc_hir_analysis/src/astconv/mod.rs index db3d41ed247..ecbbfd92539 100644 --- a/compiler/rustc_hir_analysis/src/astconv/mod.rs +++ b/compiler/rustc_hir_analysis/src/astconv/mod.rs @@ -9,7 +9,7 @@ mod lint; mod object_safety; use crate::astconv::errors::prohibit_assoc_ty_binding; -use crate::astconv::generics::{check_generic_arg_count, create_substs_for_generic_args}; +use crate::astconv::generics::{check_generic_arg_count, create_args_for_parent_generic_args}; use crate::bounds::Bounds; use crate::collect::HirPlaceholderCollector; use crate::errors::{AmbiguousLifetimeBound, TypeofReservedKeywordUsed}; @@ -29,9 +29,10 @@ use rustc_hir::{GenericArg, GenericArgs, OpaqueTyOrigin}; use rustc_infer::infer::{InferCtxt, InferOk, TyCtxtInferExt}; use rustc_infer::traits::ObligationCause; use rustc_middle::middle::stability::AllowUnstable; -use rustc_middle::ty::subst::{self, GenericArgKind, InternalSubsts, SubstsRef}; use rustc_middle::ty::GenericParamDefKind; -use rustc_middle::ty::{self, Const, IsSuggestable, Ty, TyCtxt, TypeVisitableExt}; +use rustc_middle::ty::{ + self, Const, GenericArgKind, GenericArgsRef, IsSuggestable, Ty, TyCtxt, TypeVisitableExt, +}; use rustc_session::lint::builtin::AMBIGUOUS_ASSOCIATED_ITEMS; use rustc_span::edit_distance::find_best_match_for_name; use rustc_span::symbol::{kw, Ident, Symbol}; @@ -220,14 +221,14 @@ pub trait CreateSubstsForGenericArgsCtxt<'a, 'tcx> { &mut self, param: &ty::GenericParamDef, arg: &GenericArg<'_>, - ) -> subst::GenericArg<'tcx>; + ) -> ty::GenericArg<'tcx>; fn inferred_kind( &mut self, - substs: Option<&[subst::GenericArg<'tcx>]>, + args: Option<&[ty::GenericArg<'tcx>]>, param: &ty::GenericParamDef, infer_args: bool, - ) -> subst::GenericArg<'tcx>; + ) -> ty::GenericArg<'tcx>; } impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { @@ -291,13 +292,13 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`, /// returns an appropriate set of substitutions for this particular reference to `I`. - pub fn ast_path_substs_for_ty( + pub fn ast_path_args_for_ty( &self, span: Span, def_id: DefId, item_segment: &hir::PathSegment<'_>, - ) -> SubstsRef<'tcx> { - let (substs, _) = self.create_substs_for_ast_path( + ) -> GenericArgsRef<'tcx> { + let (args, _) = self.create_args_for_ast_path( span, def_id, &[], @@ -311,7 +312,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { prohibit_assoc_ty_binding(self.tcx(), b.span, Some((item_segment, span))); } - substs + args } /// Given the type/lifetime/const arguments provided to some path (along with @@ -330,7 +331,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { /// 2. The path in question is the path to the trait `std::ops::Index`, /// which will have been resolved to a `def_id` /// 3. The `generic_args` contains info on the `<...>` contents. The `usize` type - /// parameters are returned in the `SubstsRef`, the associated type bindings like + /// parameters are returned in the `GenericArgsRef`, the associated type bindings like /// `Output = u32` are returned from `create_assoc_bindings_for_generic_args`. /// /// Note that the type listing given here is *exactly* what the user provided. @@ -341,22 +342,22 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { /// <Vec<u8> as Iterable<u8>>::Iter::<'a> /// ``` /// - /// We have the parent substs are the substs for the parent trait: + /// We have the parent args are the args for the parent trait: /// `[Vec<u8>, u8]` and `generic_args` are the arguments for the associated - /// type itself: `['a]`. The returned `SubstsRef` concatenates these two + /// type itself: `['a]`. The returned `GenericArgsRef` concatenates these two /// lists: `[Vec<u8>, u8, 'a]`. #[instrument(level = "debug", skip(self, span), ret)] - fn create_substs_for_ast_path<'a>( + fn create_args_for_ast_path<'a>( &self, span: Span, def_id: DefId, - parent_substs: &[subst::GenericArg<'tcx>], + parent_args: &[ty::GenericArg<'tcx>], seg: &hir::PathSegment<'_>, generic_args: &'a hir::GenericArgs<'_>, infer_args: bool, self_ty: Option<Ty<'tcx>>, constness: ty::BoundConstness, - ) -> (SubstsRef<'tcx>, GenericArgCountResult) { + ) -> (GenericArgsRef<'tcx>, GenericArgCountResult) { // If the type is parameterized by this region, then replace this // region with the current anon region binding (in other words, // whatever & would get replaced with). @@ -369,7 +370,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { if generics.parent.is_some() { // The parent is a trait so it should have at least one subst // for the `Self` type. - assert!(!parent_substs.is_empty()) + assert!(!parent_args.is_empty()) } else { // This item (presumably a trait) needs a self-type. assert!(self_ty.is_some()); @@ -395,7 +396,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { // here and so associated type bindings will be handled regardless of whether there are any // non-`Self` generic parameters. if generics.params.is_empty() { - return (tcx.mk_substs(parent_substs), arg_count); + return (tcx.mk_args(parent_args), arg_count); } struct SubstsForAstPathCtxt<'a, 'tcx> { @@ -421,7 +422,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { &mut self, param: &ty::GenericParamDef, arg: &GenericArg<'_>, - ) -> subst::GenericArg<'tcx> { + ) -> ty::GenericArg<'tcx> { let tcx = self.astconv.tcx(); let mut handle_ty_args = |has_default, ty: &hir::Ty<'_>| { @@ -483,10 +484,10 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { fn inferred_kind( &mut self, - substs: Option<&[subst::GenericArg<'tcx>]>, + args: Option<&[ty::GenericArg<'tcx>]>, param: &ty::GenericParamDef, infer_args: bool, - ) -> subst::GenericArg<'tcx> { + ) -> ty::GenericArg<'tcx> { let tcx = self.astconv.tcx(); match param.kind { GenericParamDefKind::Lifetime => self @@ -506,15 +507,15 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { GenericParamDefKind::Type { has_default, .. } => { if !infer_args && has_default { // No type parameter provided, but a default exists. - let substs = substs.unwrap(); - if substs.iter().any(|arg| match arg.unpack() { + let args = args.unwrap(); + if args.iter().any(|arg| match arg.unpack() { GenericArgKind::Type(ty) => ty.references_error(), _ => false, }) { // Avoid ICE #86756 when type error recovery goes awry. return Ty::new_misc_error(tcx).into(); } - tcx.at(self.span).type_of(param.def_id).subst(tcx, substs).into() + tcx.at(self.span).type_of(param.def_id).instantiate(tcx, args).into() } else if infer_args { self.astconv.ty_infer(Some(param), self.span).into() } else { @@ -532,7 +533,9 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { return ty::Const::new_error(tcx, guar, ty).into(); } if !infer_args && has_default { - tcx.const_param_default(param.def_id).subst(tcx, substs.unwrap()).into() + tcx.const_param_default(param.def_id) + .instantiate(tcx, args.unwrap()) + .into() } else { if infer_args { self.astconv.ct_infer(ty, Some(param), self.span).into() @@ -546,7 +549,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { } } - let mut substs_ctx = SubstsForAstPathCtxt { + let mut args_ctx = SubstsForAstPathCtxt { astconv: self, def_id, span, @@ -554,14 +557,14 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { inferred_params: vec![], infer_args, }; - let substs = create_substs_for_generic_args( + let args = create_args_for_parent_generic_args( tcx, def_id, - parent_substs, + parent_args, self_ty.is_some(), self_ty, &arg_count, - &mut substs_ctx, + &mut args_ctx, ); if let ty::BoundConstness::ConstIfConst = constness @@ -570,7 +573,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { tcx.sess.emit_err(crate::errors::ConstBoundForNonConstTrait { span } ); } - (substs, arg_count) + (args, arg_count) } fn create_assoc_bindings_for_generic_args<'a>( @@ -617,21 +620,21 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { assoc_bindings } - pub fn create_substs_for_associated_item( + pub fn create_args_for_associated_item( &self, span: Span, item_def_id: DefId, item_segment: &hir::PathSegment<'_>, - parent_substs: SubstsRef<'tcx>, - ) -> SubstsRef<'tcx> { + parent_args: GenericArgsRef<'tcx>, + ) -> GenericArgsRef<'tcx> { debug!( - "create_substs_for_associated_item(span: {:?}, item_def_id: {:?}, item_segment: {:?}", + "create_args_for_associated_item(span: {:?}, item_def_id: {:?}, item_segment: {:?}", span, item_def_id, item_segment ); - let (args, _) = self.create_substs_for_ast_path( + let (args, _) = self.create_args_for_ast_path( span, item_def_id, - parent_substs, + parent_args, item_segment, item_segment.args(), item_segment.infer_args, @@ -687,7 +690,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { self_ty: Ty<'tcx>, only_self_bounds: OnlySelfBounds, ) -> GenericArgCountResult { - let (substs, arg_count) = self.create_substs_for_ast_path( + let (generic_args, arg_count) = self.create_args_for_ast_path( trait_ref_span, trait_def_id, &[], @@ -704,8 +707,10 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { let assoc_bindings = self.create_assoc_bindings_for_generic_args(args); - let poly_trait_ref = - ty::Binder::bind_with_vars(ty::TraitRef::new(tcx, trait_def_id, substs), bound_vars); + let poly_trait_ref = ty::Binder::bind_with_vars( + ty::TraitRef::new(tcx, trait_def_id, generic_args), + bound_vars, + ); debug!(?poly_trait_ref, ?assoc_bindings); bounds.push_trait_bound(tcx, poly_trait_ref, span, constness, polarity); @@ -846,7 +851,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { is_impl: bool, constness: ty::BoundConstness, ) -> ty::TraitRef<'tcx> { - let (substs, _) = self.create_substs_for_ast_trait_ref( + let (generic_args, _) = self.create_args_for_ast_trait_ref( span, trait_def_id, self_ty, @@ -857,11 +862,11 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { if let Some(b) = trait_segment.args().bindings.first() { prohibit_assoc_ty_binding(self.tcx(), b.span, Some((trait_segment, span))); } - ty::TraitRef::new(self.tcx(), trait_def_id, substs) + ty::TraitRef::new(self.tcx(), trait_def_id, generic_args) } #[instrument(level = "debug", skip(self, span))] - fn create_substs_for_ast_trait_ref<'a>( + fn create_args_for_ast_trait_ref<'a>( &self, span: Span, trait_def_id: DefId, @@ -869,10 +874,10 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { trait_segment: &'a hir::PathSegment<'a>, is_impl: bool, constness: ty::BoundConstness, - ) -> (SubstsRef<'tcx>, GenericArgCountResult) { + ) -> (GenericArgsRef<'tcx>, GenericArgCountResult) { self.complain_about_internal_fn_trait(span, trait_def_id, trait_segment, is_impl); - self.create_substs_for_ast_path( + self.create_args_for_ast_path( span, trait_def_id, &[], @@ -902,7 +907,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { did: DefId, item_segment: &hir::PathSegment<'_>, ) -> Ty<'tcx> { - let substs = self.ast_path_substs_for_ty(span, did, item_segment); + let args = self.ast_path_args_for_ty(span, did, item_segment); let ty = self.tcx().at(span).type_of(did); if matches!(self.tcx().def_kind(did), DefKind::TyAlias) @@ -911,10 +916,10 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { // Type aliases referring to types that contain opaque types (but aren't just directly // referencing a single opaque type) get encoded as a type alias that normalization will // then actually instantiate the where bounds of. - let alias_ty = self.tcx().mk_alias_ty(did, substs); + let alias_ty = self.tcx().mk_alias_ty(did, args); Ty::new_alias(self.tcx(), ty::Weak, alias_ty) } else { - ty.subst(self.tcx(), substs) + ty.instantiate(self.tcx(), args) } } @@ -1267,9 +1272,12 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { "you might have meant to specify type parameters on enum \ `{type_name}`" ); - let Some(args) = assoc_segment.args else { return; }; + let Some(args) = assoc_segment.args else { + return; + }; // Get the span of the generics args *including* the leading `::`. - let args_span = assoc_segment.ident.span.shrink_to_hi().to(args.span_ext); + let args_span = + assoc_segment.ident.span.shrink_to_hi().to(args.span_ext); if tcx.generics_of(adt_def.did()).count() == 0 { // FIXME(estebank): we could also verify that the arguments being // work for the `enum`, instead of just looking if it takes *any*. @@ -1281,49 +1289,56 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { ); return; } - let Ok(snippet) = tcx.sess.source_map().span_to_snippet(args_span) else { + let Ok(snippet) = tcx.sess.source_map().span_to_snippet(args_span) + else { err.note(msg); return; }; - let (qself_sugg_span, is_self) = if let hir::TyKind::Path( - hir::QPath::Resolved(_, path) - ) = &qself.kind { - // If the path segment already has type params, we want to overwrite - // them. - match &path.segments { - // `segment` is the previous to last element on the path, - // which would normally be the `enum` itself, while the last - // `_` `PathSegment` corresponds to the variant. - [.., hir::PathSegment { - ident, - args, - res: Res::Def(DefKind::Enum, _), - .. - }, _] => ( - // We need to include the `::` in `Type::Variant::<Args>` - // to point the span to `::<Args>`, not just `<Args>`. - ident.span.shrink_to_hi().to(args.map_or( - ident.span.shrink_to_hi(), - |a| a.span_ext)), - false, - ), - [segment] => ( - // We need to include the `::` in `Type::Variant::<Args>` - // to point the span to `::<Args>`, not just `<Args>`. - segment.ident.span.shrink_to_hi().to(segment.args.map_or( - segment.ident.span.shrink_to_hi(), - |a| a.span_ext)), - kw::SelfUpper == segment.ident.name, - ), - _ => { - err.note(msg); - return; + let (qself_sugg_span, is_self) = + if let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = + &qself.kind + { + // If the path segment already has type params, we want to overwrite + // them. + match &path.segments { + // `segment` is the previous to last element on the path, + // which would normally be the `enum` itself, while the last + // `_` `PathSegment` corresponds to the variant. + [ + .., + hir::PathSegment { + ident, + args, + res: Res::Def(DefKind::Enum, _), + .. + }, + _, + ] => ( + // We need to include the `::` in `Type::Variant::<Args>` + // to point the span to `::<Args>`, not just `<Args>`. + ident.span.shrink_to_hi().to(args + .map_or(ident.span.shrink_to_hi(), |a| a.span_ext)), + false, + ), + [segment] => ( + // We need to include the `::` in `Type::Variant::<Args>` + // to point the span to `::<Args>`, not just `<Args>`. + segment.ident.span.shrink_to_hi().to(segment + .args + .map_or(segment.ident.span.shrink_to_hi(), |a| { + a.span_ext + })), + kw::SelfUpper == segment.ident.name, + ), + _ => { + err.note(msg); + return; + } } - } - } else { - err.note(msg); - return; - }; + } else { + err.note(msg); + return; + }; let suggestion = vec![ if is_self { // Account for people writing `Self::Variant::<Args>`, where @@ -1373,7 +1388,12 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { }; self.one_bound_for_assoc_type( - || traits::supertraits(tcx, ty::Binder::dummy(trait_ref.subst_identity())), + || { + traits::supertraits( + tcx, + ty::Binder::dummy(trait_ref.instantiate_identity()), + ) + }, kw::SelfUpper, assoc_ident, span, @@ -1455,7 +1475,8 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { }; let trait_did = bound.def_id(); - let Some(assoc_ty_did) = self.lookup_assoc_ty(assoc_ident, hir_ref_id, span, trait_did) else { + let Some(assoc_ty_did) = self.lookup_assoc_ty(assoc_ident, hir_ref_id, span, trait_did) + else { // Assume that if it's not matched, there must be a const defined with the same name // but it was used in a type position. let msg = format!("found associated const `{assoc_ident}` when type was expected"); @@ -1609,8 +1630,8 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { let ocx = ObligationCtxt::new(&infcx); ocx.register_obligations(obligations.clone()); - let impl_substs = infcx.fresh_substs_for_item(span, impl_); - let impl_ty = tcx.type_of(impl_).subst(tcx, impl_substs); + let impl_args = infcx.fresh_args_for_item(span, impl_); + let impl_ty = tcx.type_of(impl_).instantiate(tcx, impl_args); let impl_ty = ocx.normalize(&cause, param_env, impl_ty); // Check that the self types can be related. @@ -1622,7 +1643,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { } // Check whether the impl imposes obligations we have to worry about. - let impl_bounds = tcx.predicates_of(impl_).instantiate(tcx, impl_substs); + let impl_bounds = tcx.predicates_of(impl_).instantiate(tcx, impl_args); let impl_bounds = ocx.normalize(&cause, param_env, impl_bounds); let impl_obligations = traits::predicates_for_generics( |_, _| cause.clone(), @@ -1654,18 +1675,17 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { if let Some((impl_, (assoc_item, def_scope))) = applicable_candidates.pop() { self.check_assoc_ty(assoc_item, name, def_scope, block, span); - // FIXME(fmease): Currently creating throwaway `parent_substs` to please - // `create_substs_for_associated_item`. Modify the latter instead (or sth. similar) to - // not require the parent substs logic. - let parent_substs = InternalSubsts::identity_for_item(tcx, impl_); - let substs = - self.create_substs_for_associated_item(span, assoc_item, segment, parent_substs); - let substs = tcx.mk_substs_from_iter( + // FIXME(fmease): Currently creating throwaway `parent_args` to please + // `create_args_for_associated_item`. Modify the latter instead (or sth. similar) to + // not require the parent args logic. + let parent_args = ty::GenericArgs::identity_for_item(tcx, impl_); + let args = self.create_args_for_associated_item(span, assoc_item, segment, parent_args); + let args = tcx.mk_args_from_iter( std::iter::once(ty::GenericArg::from(self_ty)) - .chain(substs.into_iter().skip(parent_substs.len())), + .chain(args.into_iter().skip(parent_args.len())), ); - let ty = Ty::new_alias(tcx, ty::Inherent, tcx.mk_alias_ty(assoc_item, substs)); + let ty = Ty::new_alias(tcx, ty::Inherent, tcx.mk_alias_ty(assoc_item, args)); return Ok(Some((ty, assoc_item))); } @@ -1769,9 +1789,9 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { .any(|impl_def_id| { let trait_ref = tcx.impl_trait_ref(impl_def_id); trait_ref.is_some_and(|trait_ref| { - let impl_ = trait_ref.subst( + let impl_ = trait_ref.instantiate( tcx, - infcx.fresh_substs_for_item(DUMMY_SP, impl_def_id), + infcx.fresh_args_for_item(DUMMY_SP, impl_def_id), ); let value = tcx.fold_regions(qself_ty, |_, _| tcx.lifetimes.re_erased); // FIXME: Don't bother dealing with non-lifetime binders here... @@ -1814,7 +1834,9 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { debug!("qpath_to_ty: self.item_def_id()={:?}", def_id); - let parent_def_id = def_id.as_local().map(|def_id| tcx.hir().local_def_id_to_hir_id(def_id)) + let parent_def_id = def_id + .as_local() + .map(|def_id| tcx.hir().local_def_id_to_hir_id(def_id)) .map(|hir_id| tcx.hir().get_parent_item(hir_id).to_def_id()); debug!("qpath_to_ty: parent_def_id={:?}", parent_def_id); @@ -1835,7 +1857,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { && tcx.impl_polarity(impl_def_id) != ty::ImplPolarity::Negative }) .filter_map(|impl_def_id| tcx.impl_trait_ref(impl_def_id)) - .map(|impl_| impl_.subst_identity().self_ty()) + .map(|impl_| impl_.instantiate_identity().self_ty()) // We don't care about blanket impls. .filter(|self_ty| !self_ty.has_non_region_param()) .map(|self_ty| tcx.erase_regions(self_ty).to_string()) @@ -1850,7 +1872,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { &[path_str], item_segment.ident.name, ); - return Ty::new_error(tcx,reported) + return Ty::new_error(tcx, reported); }; debug!("qpath_to_ty: self_type={:?}", self_ty); @@ -1864,16 +1886,12 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { constness, ); - let item_substs = self.create_substs_for_associated_item( - span, - item_def_id, - item_segment, - trait_ref.substs, - ); + let item_args = + self.create_args_for_associated_item(span, item_def_id, item_segment, trait_ref.args); debug!("qpath_to_ty: trait_ref={:?}", trait_ref); - Ty::new_projection(tcx, item_def_id, item_substs) + Ty::new_projection(tcx, item_def_id, item_args) } pub fn prohibit_generics<'a>( @@ -2135,8 +2153,8 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { self.prohibit_generics(item_segment.1.iter(), |err| { err.note("`impl Trait` types can't have type parameters"); }); - let substs = self.ast_path_substs_for_ty(span, did, item_segment.0); - Ty::new_opaque(tcx, did, substs) + let args = self.ast_path_args_for_ty(span, did, item_segment.0); + Ty::new_opaque(tcx, did, args) } Res::Def( DefKind::Enum @@ -2220,7 +2238,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { // `Self` in impl (we know the concrete type). assert_eq!(opt_self_ty, None); // Try to evaluate any array length constants. - let ty = tcx.at(span).type_of(def_id).subst_identity(); + let ty = tcx.at(span).type_of(def_id).instantiate_identity(); let span_of_impl = tcx.span_of_impl(def_id); self.prohibit_generics(path.segments.iter(), |err| { let def_id = match *ty.kind() { @@ -2458,7 +2476,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { } &hir::TyKind::Path(hir::QPath::LangItem(lang_item, span, _)) => { let def_id = tcx.require_lang_item(lang_item, Some(span)); - let (substs, _) = self.create_substs_for_ast_path( + let (args, _) = self.create_args_for_ast_path( span, def_id, &[], @@ -2468,7 +2486,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { None, ty::BoundConstness::NotConst, ); - tcx.at(span).type_of(def_id).subst(tcx, substs) + tcx.at(span).type_of(def_id).instantiate(tcx, args) } hir::TyKind::Array(ty, length) => { let length = match length { @@ -2481,7 +2499,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { Ty::new_array_with_const_len(tcx, self.ast_ty_to_ty(ty), length) } hir::TyKind::Typeof(e) => { - let ty_erased = tcx.type_of(e.def_id).subst_identity(); + let ty_erased = tcx.type_of(e.def_id).instantiate_identity(); let ty = tcx.fold_regions(ty_erased, |r, _| { if r.is_erased() { tcx.lifetimes.re_static } else { r } }); @@ -2523,7 +2541,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { let generics = tcx.generics_of(def_id); debug!("impl_trait_ty_to_ty: generics={:?}", generics); - let substs = InternalSubsts::for_item(tcx, def_id, |param, _| { + let args = ty::GenericArgs::for_item(tcx, def_id, |param, _| { // We use `generics.count() - lifetimes.len()` here instead of `generics.parent_count` // since return-position impl trait in trait squashes all of the generics from its source fn // into its own generics, so the opaque's "own" params isn't always just lifetimes. @@ -2537,12 +2555,12 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { tcx.mk_param_from_def(param) } }); - debug!("impl_trait_ty_to_ty: substs={:?}", substs); + debug!("impl_trait_ty_to_ty: args={:?}", args); if in_trait { - Ty::new_projection(tcx, def_id, substs) + Ty::new_projection(tcx, def_id, args) } else { - Ty::new_opaque(tcx, def_id, substs) + Ty::new_opaque(tcx, def_id, args) } } @@ -2688,7 +2706,10 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { let hir = tcx.hir(); let hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), ident, .. }) = - hir.get(fn_hir_id) else { return None }; + hir.get(fn_hir_id) + else { + return None; + }; let i = hir.get_parent(fn_hir_id).expect_item().expect_impl(); let trait_ref = self.instantiate_mono_trait_ref( @@ -2704,9 +2725,9 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { trait_ref.def_id, )?; - let fn_sig = tcx.fn_sig(assoc.def_id).subst( + let fn_sig = tcx.fn_sig(assoc.def_id).instantiate( tcx, - trait_ref.substs.extend_to(tcx, assoc.def_id, |param, _| tcx.mk_param_from_def(param)), + trait_ref.args.extend_to(tcx, assoc.def_id, |param, _| tcx.mk_param_from_def(param)), ); let fn_sig = tcx.liberate_late_bound_regions(fn_hir_id.expect_owner().to_def_id(), fn_sig); diff --git a/compiler/rustc_hir_analysis/src/astconv/object_safety.rs b/compiler/rustc_hir_analysis/src/astconv/object_safety.rs index 9227ee93451..a36ec0c5730 100644 --- a/compiler/rustc_hir_analysis/src/astconv/object_safety.rs +++ b/compiler/rustc_hir_analysis/src/astconv/object_safety.rs @@ -173,7 +173,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { tcx.associated_items(pred.def_id()) .in_definition_order() .filter(|item| item.kind == ty::AssocKind::Type) - .filter(|item| item.opt_rpitit_info.is_none()) + .filter(|item| !item.is_impl_trait_in_trait()) .map(|item| item.def_id), ); } @@ -262,8 +262,8 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { let mut missing_type_params = vec![]; let mut references_self = false; let generics = tcx.generics_of(trait_ref.def_id); - let substs: Vec<_> = trait_ref - .substs + let args: Vec<_> = trait_ref + .args .iter() .enumerate() .skip(1) // Remove `Self` for `ExistentialPredicate`. @@ -279,7 +279,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { arg }) .collect(); - let substs = tcx.mk_substs(&substs); + let args = tcx.mk_args(&args); let span = i.bottom().1; let empty_generic_args = hir_trait_bounds.iter().any(|hir_bound| { @@ -310,7 +310,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { err.emit(); } - ty::ExistentialTraitRef { def_id: trait_ref.def_id, substs } + ty::ExistentialTraitRef { def_id: trait_ref.def_id, args } }) }); @@ -325,7 +325,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { // Like for trait refs, verify that `dummy_self` did not leak inside default type // parameters. - let references_self = b.projection_ty.substs.iter().skip(1).any(|arg| { + let references_self = b.projection_ty.args.iter().skip(1).any(|arg| { if arg.walk().any(|arg| arg == dummy_self.into()) { return true; } @@ -336,9 +336,9 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { span, "trait object projection bounds reference `Self`", ); - let substs: Vec<_> = b + let args: Vec<_> = b .projection_ty - .substs + .args .iter() .map(|arg| { if arg.walk().any(|arg| arg == dummy_self.into()) { @@ -347,7 +347,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { arg }) .collect(); - b.projection_ty.substs = tcx.mk_substs(&substs); + b.projection_ty.args = tcx.mk_args(&args); } ty::ExistentialProjection::erase_self_ty(tcx, b) diff --git a/compiler/rustc_hir_analysis/src/check/check.rs b/compiler/rustc_hir_analysis/src/check/check.rs index 91c33b09082..d9e14096954 100644 --- a/compiler/rustc_hir_analysis/src/check/check.rs +++ b/compiler/rustc_hir_analysis/src/check/check.rs @@ -8,7 +8,7 @@ use rustc_attr as attr; use rustc_errors::{Applicability, ErrorGuaranteed, MultiSpan}; use rustc_hir as hir; use rustc_hir::def::{CtorKind, DefKind, Res}; -use rustc_hir::def_id::{DefId, LocalDefId}; +use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_ID}; use rustc_hir::intravisit::Visitor; use rustc_hir::{ItemKind, Node, PathSegment}; use rustc_infer::infer::opaque_types::ConstrainOpaqueTypeRegionVisitor; @@ -20,8 +20,8 @@ use rustc_middle::hir::nested_filter; use rustc_middle::middle::stability::EvalResult; use rustc_middle::traits::DefiningAnchor; use rustc_middle::ty::layout::{LayoutError, MAX_SIMD_LANES}; -use rustc_middle::ty::subst::GenericArgKind; use rustc_middle::ty::util::{Discr, IntTypeExt}; +use rustc_middle::ty::GenericArgKind; use rustc_middle::ty::{ self, AdtDef, ParamEnv, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, }; @@ -96,8 +96,8 @@ fn check_union(tcx: TyCtxt<'_>, def_id: LocalDefId) { /// Check that the fields of the `union` do not need dropping. fn check_union_fields(tcx: TyCtxt<'_>, span: Span, item_def_id: LocalDefId) -> bool { - let item_type = tcx.type_of(item_def_id).subst_identity(); - if let ty::Adt(def, substs) = item_type.kind() { + let item_type = tcx.type_of(item_def_id).instantiate_identity(); + if let ty::Adt(def, args) = item_type.kind() { assert!(def.is_union()); fn allowed_union_field<'tcx>( @@ -128,7 +128,7 @@ fn check_union_fields(tcx: TyCtxt<'_>, span: Span, item_def_id: LocalDefId) -> b let param_env = tcx.param_env(item_def_id); for field in &def.non_enum_variant().fields { - let field_ty = tcx.normalize_erasing_regions(param_env, field.ty(tcx, substs)); + let field_ty = tcx.normalize_erasing_regions(param_env, field.ty(tcx, args)); if !allowed_union_field(field_ty, tcx, param_env) { let (field_span, ty_span) = match tcx.hir().get_if_local(field.did) { @@ -163,7 +163,7 @@ fn check_static_inhabited(tcx: TyCtxt<'_>, def_id: LocalDefId) { // would be enough to check this for `extern` statics, as statics with an initializer will // have UB during initialization if they are uninhabited, but there also seems to be no good // reason to allow any statics to be uninhabited. - let ty = tcx.type_of(def_id).subst_identity(); + let ty = tcx.type_of(def_id).instantiate_identity(); let span = tcx.def_span(def_id); let layout = match tcx.layout_of(ParamEnv::reveal_all().and(ty)) { Ok(l) => l, @@ -212,16 +212,16 @@ fn check_opaque(tcx: TyCtxt<'_>, id: hir::ItemId) { return; } - let substs = InternalSubsts::identity_for_item(tcx, item.owner_id); + let args = GenericArgs::identity_for_item(tcx, item.owner_id); let span = tcx.def_span(item.owner_id.def_id); if !tcx.features().impl_trait_projections { check_opaque_for_inheriting_lifetimes(tcx, item.owner_id.def_id, span); } - if tcx.type_of(item.owner_id.def_id).subst_identity().references_error() { + if tcx.type_of(item.owner_id.def_id).instantiate_identity().references_error() { return; } - if check_opaque_for_cycles(tcx, item.owner_id.def_id, substs, span, &origin).is_err() { + if check_opaque_for_cycles(tcx, item.owner_id.def_id, args, span, &origin).is_err() { return; } @@ -305,8 +305,8 @@ pub(super) fn check_opaque_for_inheriting_lifetimes( .. }) = item.kind { - let substs = InternalSubsts::identity_for_item(tcx, def_id); - let opaque_identity_ty = Ty::new_opaque(tcx, def_id.to_def_id(), substs); + let args = GenericArgs::identity_for_item(tcx, def_id); + let opaque_identity_ty = Ty::new_opaque(tcx, def_id.to_def_id(), args); let mut visitor = ProhibitOpaqueVisitor { opaque_identity_ty, parent_count: tcx.generics_of(def_id).parent_count as u32, @@ -316,7 +316,7 @@ pub(super) fn check_opaque_for_inheriting_lifetimes( }; let prohibit_opaque = tcx .explicit_item_bounds(def_id) - .subst_identity_iter_copied() + .instantiate_identity_iter_copied() .try_for_each(|(predicate, _)| predicate.visit_with(&mut visitor)); if let Some(ty) = prohibit_opaque.break_value() { @@ -355,11 +355,11 @@ pub(super) fn check_opaque_for_inheriting_lifetimes( pub(super) fn check_opaque_for_cycles<'tcx>( tcx: TyCtxt<'tcx>, def_id: LocalDefId, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, span: Span, origin: &hir::OpaqueTyOrigin, ) -> Result<(), ErrorGuaranteed> { - if tcx.try_expand_impl_trait_type(def_id.to_def_id(), substs).is_err() { + if tcx.try_expand_impl_trait_type(def_id.to_def_id(), args).is_err() { let reported = match origin { hir::OpaqueTyOrigin::AsyncFn(..) => async_opaque_type_cycle_error(tcx, span), _ => opaque_type_cycle_error(tcx, def_id, span), @@ -404,16 +404,16 @@ fn check_opaque_meets_bounds<'tcx>( .build(); let ocx = ObligationCtxt::new(&infcx); - let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id()); - let opaque_ty = Ty::new_opaque(tcx, def_id.to_def_id(), substs); + let args = GenericArgs::identity_for_item(tcx, def_id.to_def_id()); + let opaque_ty = Ty::new_opaque(tcx, def_id.to_def_id(), args); - // `ReErased` regions appear in the "parent_substs" of closures/generators. + // `ReErased` regions appear in the "parent_args" of closures/generators. // We're ignoring them here and replacing them with fresh region variables. - // See tests in ui/type-alias-impl-trait/closure_{parent_substs,wf_outlives}.rs. + // See tests in ui/type-alias-impl-trait/closure_{parent_args,wf_outlives}.rs. // // FIXME: Consider wrapping the hidden type in an existential `Binder` and instantiating it // here rather than using ReErased. - let hidden_ty = tcx.type_of(def_id.to_def_id()).subst(tcx, substs); + let hidden_ty = tcx.type_of(def_id.to_def_id()).instantiate(tcx, args); let hidden_ty = tcx.fold_regions(hidden_ty, |re, _dbi| match re.kind() { ty::ReErased => infcx.next_region_var(RegionVariableOrigin::MiscVariable(span)), _ => re, @@ -472,7 +472,7 @@ fn check_opaque_meets_bounds<'tcx>( fn is_enum_of_nonnullable_ptr<'tcx>( tcx: TyCtxt<'tcx>, adt_def: AdtDef<'tcx>, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, ) -> bool { if adt_def.repr().inhibit_enum_layout_opt() { return false; @@ -484,14 +484,14 @@ fn is_enum_of_nonnullable_ptr<'tcx>( let (([], [field]) | ([field], [])) = (&var_one.fields.raw[..], &var_two.fields.raw[..]) else { return false; }; - matches!(field.ty(tcx, substs).kind(), ty::FnPtr(..) | ty::Ref(..)) + matches!(field.ty(tcx, args).kind(), ty::FnPtr(..) | ty::Ref(..)) } fn check_static_linkage(tcx: TyCtxt<'_>, def_id: LocalDefId) { if tcx.codegen_fn_attrs(def_id).import_linkage.is_some() { - if match tcx.type_of(def_id).subst_identity().kind() { + if match tcx.type_of(def_id).instantiate_identity().kind() { ty::RawPtr(_) => false, - ty::Adt(adt_def, substs) => !is_enum_of_nonnullable_ptr(tcx, *adt_def, *substs), + ty::Adt(adt_def, args) => !is_enum_of_nonnullable_ptr(tcx, *adt_def, *args), _ => true, } { tcx.sess.emit_err(LinkageType { span: tcx.def_span(def_id) }); @@ -525,7 +525,7 @@ fn check_item_type(tcx: TyCtxt<'_>, id: hir::ItemId) { check_impl_items_against_trait( tcx, id.owner_id.def_id, - impl_trait_ref.subst_identity(), + impl_trait_ref.instantiate_identity(), ); check_on_unimplemented(tcx, id); } @@ -541,13 +541,13 @@ fn check_item_type(tcx: TyCtxt<'_>, id: hir::ItemId) { fn_maybe_err(tcx, assoc_item.ident(tcx).span, abi); } ty::AssocKind::Type if assoc_item.defaultness(tcx).has_value() => { - let trait_substs = - InternalSubsts::identity_for_item(tcx, id.owner_id); + let trait_args = + GenericArgs::identity_for_item(tcx, id.owner_id); let _: Result<_, rustc_errors::ErrorGuaranteed> = check_type_bounds( tcx, assoc_item, assoc_item, - ty::TraitRef::new(tcx, id.owner_id.to_def_id(), trait_substs), + ty::TraitRef::new(tcx, id.owner_id.to_def_id(), trait_args), ); } _ => {} @@ -572,7 +572,7 @@ fn check_item_type(tcx: TyCtxt<'_>, id: hir::ItemId) { } } DefKind::TyAlias => { - let pty_ty = tcx.type_of(id.owner_id).subst_identity(); + let pty_ty = tcx.type_of(id.owner_id).instantiate_identity(); let generics = tcx.generics_of(id.owner_id); check_type_params_are_used(tcx, &generics, pty_ty); } @@ -886,8 +886,8 @@ fn check_impl_items_against_trait<'tcx>( } pub fn check_simd(tcx: TyCtxt<'_>, sp: Span, def_id: LocalDefId) { - let t = tcx.type_of(def_id).subst_identity(); - if let ty::Adt(def, substs) = t.kind() + let t = tcx.type_of(def_id).instantiate_identity(); + if let ty::Adt(def, args) = t.kind() && def.is_struct() { let fields = &def.non_enum_variant().fields; @@ -895,8 +895,8 @@ pub fn check_simd(tcx: TyCtxt<'_>, sp: Span, def_id: LocalDefId) { struct_span_err!(tcx.sess, sp, E0075, "SIMD vector cannot be empty").emit(); return; } - let e = fields[FieldIdx::from_u32(0)].ty(tcx, substs); - if !fields.iter().all(|f| f.ty(tcx, substs) == e) { + let e = fields[FieldIdx::from_u32(0)].ty(tcx, args); + if !fields.iter().all(|f| f.ty(tcx, args) == e) { struct_span_err!(tcx.sess, sp, E0076, "SIMD vector should be homogeneous") .span_label(sp, "SIMD elements must have the same type") .emit(); @@ -1003,7 +1003,7 @@ pub(super) fn check_packed(tcx: TyCtxt<'_>, sp: Span, def: ty::AdtDef<'_>) { if first { format!( "`{}` contains a field of type `{}`", - tcx.type_of(def.did()).subst_identity(), + tcx.type_of(def.did()).instantiate_identity(), ident ) } else { @@ -1025,7 +1025,7 @@ pub(super) fn check_packed_inner( def_id: DefId, stack: &mut Vec<DefId>, ) -> Option<Vec<(DefId, Span)>> { - if let ty::Adt(def, substs) = tcx.type_of(def_id).subst_identity().kind() { + if let ty::Adt(def, args) = tcx.type_of(def_id).instantiate_identity().kind() { if def.is_struct() || def.is_union() { if def.repr().align.is_some() { return Some(vec![(def.did(), DUMMY_SP)]); @@ -1033,7 +1033,7 @@ pub(super) fn check_packed_inner( stack.push(def_id); for field in &def.non_enum_variant().fields { - if let ty::Adt(def, _) = field.ty(tcx, substs).kind() + if let ty::Adt(def, _) = field.ty(tcx, args).kind() && !stack.contains(&def.did()) && let Some(mut defs) = check_packed_inner(tcx, def.did(), stack) { @@ -1072,7 +1072,7 @@ pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>) // For each field, figure out if it's known to be a ZST and align(1), with "known" // respecting #[non_exhaustive] attributes. let field_infos = adt.all_fields().map(|field| { - let ty = field.ty(tcx, InternalSubsts::identity_for_item(tcx, field.did)); + let ty = field.ty(tcx, GenericArgs::identity_for_item(tcx, field.did)); let param_env = tcx.param_env(field.did); let layout = tcx.layout_of(param_env.and(ty)); // We are currently checking the type this field came from, so it must be local @@ -1086,7 +1086,7 @@ pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>) fn check_non_exhaustive<'tcx>( tcx: TyCtxt<'tcx>, t: Ty<'tcx>, - ) -> ControlFlow<(&'static str, DefId, SubstsRef<'tcx>, bool)> { + ) -> ControlFlow<(&'static str, DefId, GenericArgsRef<'tcx>, bool)> { match t.kind() { ty::Tuple(list) => list.iter().try_for_each(|t| check_non_exhaustive(tcx, t)), ty::Array(ty, _) => check_non_exhaustive(tcx, *ty), @@ -1140,7 +1140,7 @@ pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>) .span_label(span, "has alignment larger than 1") .emit(); } - if incompat && let Some((descr, def_id, substs, non_exhaustive)) = non_exhaustive { + if incompat && let Some((descr, def_id, args, non_exhaustive)) = non_exhaustive { tcx.struct_span_lint_hir( REPR_TRANSPARENT_EXTERNAL_PRIVATE_FIELDS, tcx.hir().local_def_id_to_hir_id(adt.did().expect_local()), @@ -1152,7 +1152,7 @@ pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>) } else { "contains private fields" }; - let field_ty = tcx.def_path_str_with_substs(def_id, substs); + let field_ty = tcx.def_path_str_with_args(def_id, args); lint .note(format!("this {descr} contains `{field_ty}`, which {note}, \ and makes it not a breaking change to become non-zero-sized in the future.")) @@ -1378,6 +1378,9 @@ pub(super) fn check_mod_item_types(tcx: TyCtxt<'_>, module_def_id: LocalDefId) { for id in module.items() { check_item_type(tcx, id); } + if module_def_id == CRATE_DEF_ID { + super::entry::check_for_entry_fn(tcx); + } } fn async_opaque_type_cycle_error(tcx: TyCtxt<'_>, span: Span) -> ErrorGuaranteed { diff --git a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs index 22e576e345e..07f8dd948e2 100644 --- a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs +++ b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs @@ -16,7 +16,7 @@ use rustc_infer::traits::util; use rustc_middle::ty::error::{ExpectedFound, TypeError}; use rustc_middle::ty::util::ExplicitSelf; use rustc_middle::ty::{ - self, InternalSubsts, Ty, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitableExt, + self, GenericArgs, Ty, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitableExt, }; use rustc_middle::ty::{GenericParamDefKind, ToPredicate, TyCtxt}; use rustc_span::{Span, DUMMY_SP}; @@ -96,15 +96,15 @@ fn check_method_is_structurally_compatible<'tcx>( /// For this we have to show that, assuming the bounds of the impl hold, the /// bounds of `trait_m` imply the bounds of `impl_m`. /// -/// We start out with `trait_to_impl_substs`, that maps the trait +/// We start out with `trait_to_impl_args`, that maps the trait /// type parameters to impl type parameters. This is taken from the /// impl trait reference: /// /// ```rust,ignore (pseudo-Rust) -/// trait_to_impl_substs = {'t => 'j, T => &'i U, Self => Foo} +/// trait_to_impl_args = {'t => 'j, T => &'i U, Self => Foo} /// ``` /// -/// We create a mapping `dummy_substs` that maps from the impl type +/// We create a mapping `dummy_args` that maps from the impl type /// parameters to fresh types and regions. For type parameters, /// this is the identity transform, but we could as well use any /// placeholder types. For regions, we convert from bound to free @@ -112,10 +112,10 @@ fn check_method_is_structurally_compatible<'tcx>( /// declared on the impl or used in type parameter bounds). /// /// ```rust,ignore (pseudo-Rust) -/// impl_to_placeholder_substs = {'i => 'i0, U => U0, N => N0 } +/// impl_to_placeholder_args = {'i => 'i0, U => U0, N => N0 } /// ``` /// -/// Now we can apply `placeholder_substs` to the type of the impl method +/// Now we can apply `placeholder_args` to the type of the impl method /// to yield a new function type in terms of our fresh, placeholder /// types: /// @@ -125,13 +125,13 @@ fn check_method_is_structurally_compatible<'tcx>( /// /// We now want to extract and substitute the type of the *trait* /// method and compare it. To do so, we must create a compound -/// substitution by combining `trait_to_impl_substs` and -/// `impl_to_placeholder_substs`, and also adding a mapping for the method +/// substitution by combining `trait_to_impl_args` and +/// `impl_to_placeholder_args`, and also adding a mapping for the method /// type parameters. We extend the mapping to also include /// the method parameters. /// /// ```rust,ignore (pseudo-Rust) -/// trait_to_placeholder_substs = { T => &'i0 U0, Self => Foo, M => N0 } +/// trait_to_placeholder_args = { T => &'i0 U0, Self => Foo, M => N0 } /// ``` /// /// Applying this to the trait method type yields: @@ -148,8 +148,8 @@ fn check_method_is_structurally_compatible<'tcx>( /// satisfied by the implementation's method. /// /// We do this by creating a parameter environment which contains a -/// substitution corresponding to `impl_to_placeholder_substs`. We then build -/// `trait_to_placeholder_substs` and use it to convert the predicates contained +/// substitution corresponding to `impl_to_placeholder_args`. We then build +/// `trait_to_placeholder_args` and use it to convert the predicates contained /// in the `trait_m` generics to the placeholder form. /// /// Finally we register each of these predicates as an obligation and check that @@ -162,7 +162,7 @@ fn compare_method_predicate_entailment<'tcx>( impl_trait_ref: ty::TraitRef<'tcx>, check_implied_wf: CheckImpliedWfMode, ) -> Result<(), ErrorGuaranteed> { - let trait_to_impl_substs = impl_trait_ref.substs; + let trait_to_impl_args = impl_trait_ref.args; // This node-id should be used for the `body_id` field on each // `ObligationCause` (and the `FnCtxt`). @@ -182,12 +182,12 @@ fn compare_method_predicate_entailment<'tcx>( ); // Create mapping from impl to placeholder. - let impl_to_placeholder_substs = InternalSubsts::identity_for_item(tcx, impl_m.def_id); + let impl_to_placeholder_args = GenericArgs::identity_for_item(tcx, impl_m.def_id); // Create mapping from trait to placeholder. - let trait_to_placeholder_substs = - impl_to_placeholder_substs.rebase_onto(tcx, impl_m.container_id(tcx), trait_to_impl_substs); - debug!("compare_impl_method: trait_to_placeholder_substs={:?}", trait_to_placeholder_substs); + let trait_to_placeholder_args = + impl_to_placeholder_args.rebase_onto(tcx, impl_m.container_id(tcx), trait_to_impl_args); + debug!("compare_impl_method: trait_to_placeholder_args={:?}", trait_to_placeholder_args); let impl_m_predicates = tcx.predicates_of(impl_m.def_id); let trait_m_predicates = tcx.predicates_of(trait_m.def_id); @@ -211,7 +211,7 @@ fn compare_method_predicate_entailment<'tcx>( // if all constraints hold. hybrid_preds.predicates.extend( trait_m_predicates - .instantiate_own(tcx, trait_to_placeholder_substs) + .instantiate_own(tcx, trait_to_placeholder_args) .map(|(predicate, _)| predicate), ); @@ -231,7 +231,7 @@ fn compare_method_predicate_entailment<'tcx>( debug!("compare_impl_method: caller_bounds={:?}", param_env.caller_bounds()); - let impl_m_own_bounds = impl_m_predicates.instantiate_own(tcx, impl_to_placeholder_substs); + let impl_m_own_bounds = impl_m_predicates.instantiate_own(tcx, impl_to_placeholder_args); for (predicate, span) in impl_m_own_bounds { let normalize_cause = traits::ObligationCause::misc(span, impl_m_def_id); let predicate = ocx.normalize(&normalize_cause, param_env, predicate); @@ -269,7 +269,7 @@ fn compare_method_predicate_entailment<'tcx>( let unnormalized_impl_sig = infcx.instantiate_binder_with_fresh_vars( impl_m_span, infer::HigherRankedType, - tcx.fn_sig(impl_m.def_id).subst_identity(), + tcx.fn_sig(impl_m.def_id).instantiate_identity(), ); let unnormalized_impl_fty = Ty::new_fn_ptr(tcx, ty::Binder::dummy(unnormalized_impl_sig)); @@ -277,7 +277,7 @@ fn compare_method_predicate_entailment<'tcx>( let impl_sig = ocx.normalize(&norm_cause, param_env, unnormalized_impl_sig); debug!("compare_impl_method: impl_fty={:?}", impl_sig); - let trait_sig = tcx.fn_sig(trait_m.def_id).subst(tcx, trait_to_placeholder_substs); + let trait_sig = tcx.fn_sig(trait_m.def_id).instantiate(tcx, trait_to_placeholder_args); let trait_sig = tcx.liberate_late_bound_regions(impl_m.def_id, trait_sig); // Next, add all inputs and output as well-formed tys. Importantly, @@ -615,14 +615,14 @@ pub(super) fn collect_return_position_impl_trait_in_trait_tys<'tcx>( let impl_m = tcx.opt_associated_item(impl_m_def_id.to_def_id()).unwrap(); let trait_m = tcx.opt_associated_item(impl_m.trait_item_def_id.unwrap()).unwrap(); let impl_trait_ref = - tcx.impl_trait_ref(impl_m.impl_container(tcx).unwrap()).unwrap().subst_identity(); + tcx.impl_trait_ref(impl_m.impl_container(tcx).unwrap()).unwrap().instantiate_identity(); let param_env = tcx.param_env(impl_m_def_id); // First, check a few of the same things as `compare_impl_method`, // just so we don't ICE during substitution later. check_method_is_structurally_compatible(tcx, impl_m, trait_m, impl_trait_ref, true)?; - let trait_to_impl_substs = impl_trait_ref.substs; + let trait_to_impl_args = impl_trait_ref.args; let impl_m_hir_id = tcx.hir().local_def_id_to_hir_id(impl_m_def_id); let return_span = tcx.hir().fn_decl_by_hir_id(impl_m_hir_id).unwrap().output.span(); @@ -637,11 +637,11 @@ pub(super) fn collect_return_position_impl_trait_in_trait_tys<'tcx>( ); // Create mapping from impl to placeholder. - let impl_to_placeholder_substs = InternalSubsts::identity_for_item(tcx, impl_m.def_id); + let impl_to_placeholder_args = GenericArgs::identity_for_item(tcx, impl_m.def_id); // Create mapping from trait to placeholder. - let trait_to_placeholder_substs = - impl_to_placeholder_substs.rebase_onto(tcx, impl_m.container_id(tcx), trait_to_impl_substs); + let trait_to_placeholder_args = + impl_to_placeholder_args.rebase_onto(tcx, impl_m.container_id(tcx), trait_to_impl_args); let infcx = &tcx.infer_ctxt().build(); let ocx = ObligationCtxt::new(infcx); @@ -651,7 +651,10 @@ pub(super) fn collect_return_position_impl_trait_in_trait_tys<'tcx>( let impl_sig = ocx.normalize( &norm_cause, param_env, - tcx.liberate_late_bound_regions(impl_m.def_id, tcx.fn_sig(impl_m.def_id).subst_identity()), + tcx.liberate_late_bound_regions( + impl_m.def_id, + tcx.fn_sig(impl_m.def_id).instantiate_identity(), + ), ); impl_sig.error_reported()?; let impl_return_ty = impl_sig.output(); @@ -665,7 +668,7 @@ pub(super) fn collect_return_position_impl_trait_in_trait_tys<'tcx>( .instantiate_binder_with_fresh_vars( return_span, infer::HigherRankedType, - tcx.fn_sig(trait_m.def_id).subst(tcx, trait_to_placeholder_substs), + tcx.fn_sig(trait_m.def_id).instantiate(tcx, trait_to_placeholder_args), ) .fold_with(&mut collector); @@ -758,47 +761,47 @@ pub(super) fn collect_return_position_impl_trait_in_trait_tys<'tcx>( ocx.resolve_regions_and_report_errors(impl_m_def_id, &outlives_env)?; let mut collected_tys = FxHashMap::default(); - for (def_id, (ty, substs)) in collected_types { - match infcx.fully_resolve((ty, substs)) { - Ok((ty, substs)) => { + for (def_id, (ty, args)) in collected_types { + match infcx.fully_resolve((ty, args)) { + Ok((ty, args)) => { // `ty` contains free regions that we created earlier while liberating the // trait fn signature. However, projection normalization expects `ty` to // contains `def_id`'s early-bound regions. - let id_substs = InternalSubsts::identity_for_item(tcx, def_id); - debug!(?id_substs, ?substs); - let map: FxHashMap<_, _> = std::iter::zip(substs, id_substs) + let id_args = GenericArgs::identity_for_item(tcx, def_id); + debug!(?id_args, ?args); + let map: FxHashMap<_, _> = std::iter::zip(args, id_args) .skip(tcx.generics_of(trait_m.def_id).count()) .filter_map(|(a, b)| Some((a.as_region()?, b.as_region()?))) .collect(); debug!(?map); // NOTE(compiler-errors): RPITITs, like all other RPITs, have early-bound - // region substs that are synthesized during AST lowering. These are substs - // that are appended to the parent substs (trait and trait method). However, + // region args that are synthesized during AST lowering. These are args + // that are appended to the parent args (trait and trait method). However, // we're trying to infer the unsubstituted type value of the RPITIT inside - // the *impl*, so we can later use the impl's method substs to normalize + // the *impl*, so we can later use the impl's method args to normalize // an RPITIT to a concrete type (`confirm_impl_trait_in_trait_candidate`). // // Due to the design of RPITITs, during AST lowering, we have no idea that // an impl method corresponds to a trait method with RPITITs in it. Therefore, - // we don't have a list of early-bound region substs for the RPITIT in the impl. + // we don't have a list of early-bound region args for the RPITIT in the impl. // Since early region parameters are index-based, we can't just rebase these - // (trait method) early-bound region substs onto the impl, and there's no - // guarantee that the indices from the trait substs and impl substs line up. - // So to fix this, we subtract the number of trait substs and add the number of - // impl substs to *renumber* these early-bound regions to their corresponding + // (trait method) early-bound region args onto the impl, and there's no + // guarantee that the indices from the trait args and impl args line up. + // So to fix this, we subtract the number of trait args and add the number of + // impl args to *renumber* these early-bound regions to their corresponding // indices in the impl's substitutions list. // - // Also, we only need to account for a difference in trait and impl substs, + // Also, we only need to account for a difference in trait and impl args, // since we previously enforce that the trait method and impl method have the // same generics. - let num_trait_substs = trait_to_impl_substs.len(); - let num_impl_substs = tcx.generics_of(impl_m.container_id(tcx)).params.len(); + let num_trait_args = trait_to_impl_args.len(); + let num_impl_args = tcx.generics_of(impl_m.container_id(tcx)).params.len(); let ty = match ty.try_fold_with(&mut RemapHiddenTyRegions { tcx, map, - num_trait_substs, - num_impl_substs, + num_trait_args, + num_impl_args, def_id, impl_def_id: impl_m.container_id(tcx), ty, @@ -824,7 +827,7 @@ pub(super) fn collect_return_position_impl_trait_in_trait_tys<'tcx>( struct ImplTraitInTraitCollector<'a, 'tcx> { ocx: &'a ObligationCtxt<'a, 'tcx>, - types: FxHashMap<DefId, (Ty<'tcx>, ty::SubstsRef<'tcx>)>, + types: FxHashMap<DefId, (Ty<'tcx>, ty::GenericArgsRef<'tcx>)>, span: Span, param_env: ty::ParamEnv<'tcx>, body_id: LocalDefId, @@ -853,8 +856,8 @@ impl<'tcx> TypeFolder<TyCtxt<'tcx>> for ImplTraitInTraitCollector<'_, 'tcx> { if let Some((ty, _)) = self.types.get(&proj.def_id) { return *ty; } - //FIXME(RPITIT): Deny nested RPITIT in substs too - if proj.substs.has_escaping_bound_vars() { + //FIXME(RPITIT): Deny nested RPITIT in args too + if proj.args.has_escaping_bound_vars() { bug!("FIXME(RPITIT): error here"); } // Replace with infer var @@ -862,9 +865,9 @@ impl<'tcx> TypeFolder<TyCtxt<'tcx>> for ImplTraitInTraitCollector<'_, 'tcx> { span: self.span, kind: TypeVariableOriginKind::MiscVariable, }); - self.types.insert(proj.def_id, (infer_ty, proj.substs)); + self.types.insert(proj.def_id, (infer_ty, proj.args)); // Recurse into bounds - for (pred, pred_span) in self.interner().explicit_item_bounds(proj.def_id).subst_iter_copied(self.interner(), proj.substs) { + for (pred, pred_span) in self.interner().explicit_item_bounds(proj.def_id).arg_iter_copied(self.interner(), proj.args) { let pred = pred.fold_with(self); let pred = self.ocx.normalize( &ObligationCause::misc(self.span, self.body_id), @@ -893,8 +896,8 @@ impl<'tcx> TypeFolder<TyCtxt<'tcx>> for ImplTraitInTraitCollector<'_, 'tcx> { struct RemapHiddenTyRegions<'tcx> { tcx: TyCtxt<'tcx>, map: FxHashMap<ty::Region<'tcx>, ty::Region<'tcx>>, - num_trait_substs: usize, - num_impl_substs: usize, + num_trait_args: usize, + num_impl_args: usize, def_id: DefId, impl_def_id: DefId, ty: Ty<'tcx>, @@ -909,16 +912,16 @@ impl<'tcx> ty::FallibleTypeFolder<TyCtxt<'tcx>> for RemapHiddenTyRegions<'tcx> { } fn try_fold_ty(&mut self, t: Ty<'tcx>) -> Result<Ty<'tcx>, Self::Error> { - if let ty::Alias(ty::Opaque, ty::AliasTy { substs, def_id, .. }) = *t.kind() { - let mut mapped_substs = Vec::with_capacity(substs.len()); - for (arg, v) in std::iter::zip(substs, self.tcx.variances_of(def_id)) { - mapped_substs.push(match (arg.unpack(), v) { - // Skip uncaptured opaque substs + if let ty::Alias(ty::Opaque, ty::AliasTy { args, def_id, .. }) = *t.kind() { + let mut mapped_args = Vec::with_capacity(args.len()); + for (arg, v) in std::iter::zip(args, self.tcx.variances_of(def_id)) { + mapped_args.push(match (arg.unpack(), v) { + // Skip uncaptured opaque args (ty::GenericArgKind::Lifetime(_), ty::Bivariant) => arg, _ => arg.try_fold_with(self)?, }); } - Ok(Ty::new_opaque(self.tcx, def_id, self.tcx.mk_substs(&mapped_substs))) + Ok(Ty::new_opaque(self.tcx, def_id, self.tcx.mk_args(&mapped_args))) } else { t.try_super_fold_with(self) } @@ -975,7 +978,7 @@ impl<'tcx> ty::FallibleTypeFolder<TyCtxt<'tcx>> for RemapHiddenTyRegions<'tcx> { ty::EarlyBoundRegion { def_id: e.def_id, name: e.name, - index: (e.index as usize - self.num_trait_substs + self.num_impl_substs) as u32, + index: (e.index as usize - self.num_trait_args + self.num_impl_args) as u32, }, )) } @@ -1214,7 +1217,7 @@ fn compare_self_type<'tcx>( ty::ImplContainer => impl_trait_ref.self_ty(), ty::TraitContainer => tcx.types.self_param, }; - let self_arg_ty = tcx.fn_sig(method.def_id).subst_identity().input(0); + let self_arg_ty = tcx.fn_sig(method.def_id).instantiate_identity().input(0); let param_env = ty::ParamEnv::reveal_all(); let infcx = tcx.infer_ctxt().build(); @@ -1319,7 +1322,7 @@ fn compare_number_of_generics<'tcx>( // has mismatched type or const generic arguments, then the method that it's // inheriting the generics from will also have mismatched arguments, and // we'll report an error for that instead. Delay a bug for safety, though. - if trait_.opt_rpitit_info.is_some() { + if trait_.is_impl_trait_in_trait() { return Err(tcx.sess.delay_span_bug( rustc_span::DUMMY_SP, "errors comparing numbers of generics of trait/impl functions were not emitted", @@ -1738,7 +1741,7 @@ fn compare_generic_param_kinds<'tcx>( format!( "{} const parameter of type `{}`", prefix, - tcx.type_of(param.def_id).subst_identity() + tcx.type_of(param.def_id).instantiate_identity() ) } Type { .. } => format!("{} type parameter", prefix), @@ -1769,7 +1772,7 @@ pub(super) fn compare_impl_const_raw( let impl_const_item = tcx.associated_item(impl_const_item_def); let trait_const_item = tcx.associated_item(trait_const_item_def); let impl_trait_ref = - tcx.impl_trait_ref(impl_const_item.container_id(tcx)).unwrap().subst_identity(); + tcx.impl_trait_ref(impl_const_item.container_id(tcx)).unwrap().instantiate_identity(); debug!("compare_const_impl(impl_trait_ref={:?})", impl_trait_ref); let impl_c_span = tcx.def_span(impl_const_item_def.to_def_id()); @@ -1783,13 +1786,13 @@ pub(super) fn compare_impl_const_raw( // because we shouldn't really have to deal with lifetimes or // predicates. In fact some of this should probably be put into // shared functions because of DRY violations... - let trait_to_impl_substs = impl_trait_ref.substs; + let trait_to_impl_args = impl_trait_ref.args; // Create a parameter environment that represents the implementation's // method. // Compute placeholder form of impl and trait const tys. - let impl_ty = tcx.type_of(impl_const_item_def.to_def_id()).subst_identity(); - let trait_ty = tcx.type_of(trait_const_item_def).subst(tcx, trait_to_impl_substs); + let impl_ty = tcx.type_of(impl_const_item_def.to_def_id()).instantiate_identity(); + let trait_ty = tcx.type_of(trait_const_item_def).instantiate(tcx, trait_to_impl_args); let mut cause = ObligationCause::new( impl_c_span, impl_const_item_def, @@ -1885,16 +1888,16 @@ fn compare_type_predicate_entailment<'tcx>( trait_ty: ty::AssocItem, impl_trait_ref: ty::TraitRef<'tcx>, ) -> Result<(), ErrorGuaranteed> { - let impl_substs = InternalSubsts::identity_for_item(tcx, impl_ty.def_id); - let trait_to_impl_substs = - impl_substs.rebase_onto(tcx, impl_ty.container_id(tcx), impl_trait_ref.substs); + let impl_args = GenericArgs::identity_for_item(tcx, impl_ty.def_id); + let trait_to_impl_args = + impl_args.rebase_onto(tcx, impl_ty.container_id(tcx), impl_trait_ref.args); let impl_ty_predicates = tcx.predicates_of(impl_ty.def_id); let trait_ty_predicates = tcx.predicates_of(trait_ty.def_id); check_region_bounds_on_impl_item(tcx, impl_ty, trait_ty, false)?; - let impl_ty_own_bounds = impl_ty_predicates.instantiate_own(tcx, impl_substs); + let impl_ty_own_bounds = impl_ty_predicates.instantiate_own(tcx, impl_args); if impl_ty_own_bounds.len() == 0 { // Nothing to check. return Ok(()); @@ -1904,7 +1907,7 @@ fn compare_type_predicate_entailment<'tcx>( // `ObligationCause` (and the `FnCtxt`). This is what // `regionck_item` expects. let impl_ty_def_id = impl_ty.def_id.expect_local(); - debug!("compare_type_predicate_entailment: trait_to_impl_substs={:?}", trait_to_impl_substs); + debug!("compare_type_predicate_entailment: trait_to_impl_args={:?}", trait_to_impl_args); // The predicates declared by the impl definition, the trait and the // associated type in the trait are assumed. @@ -1912,7 +1915,7 @@ fn compare_type_predicate_entailment<'tcx>( let mut hybrid_preds = impl_predicates.instantiate_identity(tcx); hybrid_preds.predicates.extend( trait_ty_predicates - .instantiate_own(tcx, trait_to_impl_substs) + .instantiate_own(tcx, trait_to_impl_args) .map(|(predicate, _)| predicate), ); @@ -1990,9 +1993,9 @@ pub(super) fn check_type_bounds<'tcx>( // } // // - `impl_trait_ref` would be `<(A, B) as Foo<u32>>` - // - `normalize_impl_ty_substs` would be `[A, B, ^0.0]` (`^0.0` here is the bound var with db 0 and index 0) + // - `normalize_impl_ty_args` would be `[A, B, ^0.0]` (`^0.0` here is the bound var with db 0 and index 0) // - `normalize_impl_ty` would be `Wrapper<A, B, ^0.0>` - // - `rebased_substs` would be `[(A, B), u32, ^0.0]`, combining the substs from + // - `rebased_args` would be `[(A, B), u32, ^0.0]`, combining the args from // the *trait* with the generic associated type parameters (as bound vars). // // A note regarding the use of bound vars here: @@ -2022,9 +2025,11 @@ pub(super) fn check_type_bounds<'tcx>( // the trait (notably, that X: Eq and T: Family). let mut bound_vars: smallvec::SmallVec<[ty::BoundVariableKind; 8]> = smallvec::SmallVec::with_capacity(tcx.generics_of(impl_ty.def_id).params.len()); - // Extend the impl's identity substs with late-bound GAT vars - let normalize_impl_ty_substs = ty::InternalSubsts::identity_for_item(tcx, container_id) - .extend_to(tcx, impl_ty.def_id, |param, _| match param.kind { + // Extend the impl's identity args with late-bound GAT vars + let normalize_impl_ty_args = ty::GenericArgs::identity_for_item(tcx, container_id).extend_to( + tcx, + impl_ty.def_id, + |param, _| match param.kind { GenericParamDefKind::Type { .. } => { let kind = ty::BoundTyKind::Param(param.def_id, param.name); let bound_var = ty::BoundVariableKind::Ty(kind); @@ -2060,7 +2065,8 @@ pub(super) fn check_type_bounds<'tcx>( ) .into() } - }); + }, + ); // When checking something like // // trait X { type Y: PartialEq<<Self as X>::Y> } @@ -2070,15 +2076,14 @@ pub(super) fn check_type_bounds<'tcx>( // we want <T as X>::Y to normalize to S. This is valid because we are // checking the default value specifically here. Add this equality to the // ParamEnv for normalization specifically. - let normalize_impl_ty = tcx.type_of(impl_ty.def_id).subst(tcx, normalize_impl_ty_substs); - let rebased_substs = - normalize_impl_ty_substs.rebase_onto(tcx, container_id, impl_trait_ref.substs); + let normalize_impl_ty = tcx.type_of(impl_ty.def_id).instantiate(tcx, normalize_impl_ty_args); + let rebased_args = normalize_impl_ty_args.rebase_onto(tcx, container_id, impl_trait_ref.args); let bound_vars = tcx.mk_bound_variable_kinds(&bound_vars); let normalize_param_env = { let mut predicates = param_env.caller_bounds().iter().collect::<Vec<_>>(); match normalize_impl_ty.kind() { ty::Alias(ty::Projection, proj) - if proj.def_id == trait_ty.def_id && proj.substs == rebased_substs => + if proj.def_id == trait_ty.def_id && proj.args == rebased_args => { // Don't include this predicate if the projected type is // exactly the same as the projection. This can occur in @@ -2089,7 +2094,7 @@ pub(super) fn check_type_bounds<'tcx>( _ => predicates.push( ty::Binder::bind_with_vars( ty::ProjectionPredicate { - projection_ty: tcx.mk_alias_ty(trait_ty.def_id, rebased_substs), + projection_ty: tcx.mk_alias_ty(trait_ty.def_id, rebased_args), term: normalize_impl_ty.into(), }, bound_vars, @@ -2102,8 +2107,8 @@ pub(super) fn check_type_bounds<'tcx>( debug!(?normalize_param_env); let impl_ty_def_id = impl_ty.def_id.expect_local(); - let impl_ty_substs = InternalSubsts::identity_for_item(tcx, impl_ty.def_id); - let rebased_substs = impl_ty_substs.rebase_onto(tcx, container_id, impl_trait_ref.substs); + let impl_ty_args = GenericArgs::identity_for_item(tcx, impl_ty.def_id); + let rebased_args = impl_ty_args.rebase_onto(tcx, container_id, impl_trait_ref.args); let infcx = tcx.infer_ctxt().build(); let ocx = ObligationCtxt::new(&infcx); @@ -2111,7 +2116,7 @@ pub(super) fn check_type_bounds<'tcx>( // A synthetic impl Trait for RPITIT desugaring has no HIR, which we currently use to get the // span for an impl's associated type. Instead, for these, use the def_span for the synthesized // associated type. - let impl_ty_span = if impl_ty.opt_rpitit_info.is_some() { + let impl_ty_span = if impl_ty.is_impl_trait_in_trait() { tcx.def_span(impl_ty_def_id) } else { match tcx.hir().get_by_def_id(impl_ty_def_id) { @@ -2144,7 +2149,7 @@ pub(super) fn check_type_bounds<'tcx>( let obligations: Vec<_> = tcx .explicit_item_bounds(trait_ty.def_id) - .subst_iter_copied(tcx, rebased_substs) + .arg_iter_copied(tcx, rebased_args) .map(|(concrete_ty_bound, span)| { debug!("check_type_bounds: concrete_ty_bound = {:?}", concrete_ty_bound); traits::Obligation::new(tcx, mk_cause(span), param_env, concrete_ty_bound) diff --git a/compiler/rustc_hir_analysis/src/check/dropck.rs b/compiler/rustc_hir_analysis/src/check/dropck.rs index 13d1abe2a65..4ac3a7c23ae 100644 --- a/compiler/rustc_hir_analysis/src/check/dropck.rs +++ b/compiler/rustc_hir_analysis/src/check/dropck.rs @@ -5,8 +5,8 @@ use rustc_data_structures::fx::FxHashSet; use rustc_errors::{struct_span_err, ErrorGuaranteed}; use rustc_infer::infer::outlives::env::OutlivesEnvironment; use rustc_infer::infer::{RegionResolutionError, TyCtxtInferExt}; -use rustc_middle::ty::subst::SubstsRef; use rustc_middle::ty::util::CheckRegions; +use rustc_middle::ty::GenericArgsRef; use rustc_middle::ty::{self, TyCtxt}; use rustc_trait_selection::traits::{self, ObligationCtxt}; @@ -44,21 +44,21 @@ pub fn check_drop_impl(tcx: TyCtxt<'_>, drop_impl_did: DefId) -> Result<(), Erro })); } } - let dtor_self_type = tcx.type_of(drop_impl_did).subst_identity(); + let dtor_self_type = tcx.type_of(drop_impl_did).instantiate_identity(); match dtor_self_type.kind() { - ty::Adt(adt_def, adt_to_impl_substs) => { + ty::Adt(adt_def, adt_to_impl_args) => { ensure_drop_params_and_item_params_correspond( tcx, drop_impl_did.expect_local(), adt_def.did(), - adt_to_impl_substs, + adt_to_impl_args, )?; ensure_drop_predicates_are_implied_by_item_defn( tcx, drop_impl_did.expect_local(), adt_def.did().expect_local(), - adt_to_impl_substs, + adt_to_impl_args, ) } _ => { @@ -79,10 +79,11 @@ fn ensure_drop_params_and_item_params_correspond<'tcx>( tcx: TyCtxt<'tcx>, drop_impl_did: LocalDefId, self_type_did: DefId, - adt_to_impl_substs: SubstsRef<'tcx>, + adt_to_impl_args: GenericArgsRef<'tcx>, ) -> Result<(), ErrorGuaranteed> { - let Err(arg) = tcx.uses_unique_generic_params(adt_to_impl_substs, CheckRegions::OnlyEarlyBound) else { - return Ok(()) + let Err(arg) = tcx.uses_unique_generic_params(adt_to_impl_args, CheckRegions::OnlyEarlyBound) + else { + return Ok(()); }; let drop_impl_span = tcx.def_span(drop_impl_did); @@ -114,12 +115,12 @@ fn ensure_drop_predicates_are_implied_by_item_defn<'tcx>( tcx: TyCtxt<'tcx>, drop_impl_def_id: LocalDefId, adt_def_id: LocalDefId, - adt_to_impl_substs: SubstsRef<'tcx>, + adt_to_impl_args: GenericArgsRef<'tcx>, ) -> Result<(), ErrorGuaranteed> { let infcx = tcx.infer_ctxt().build(); let ocx = ObligationCtxt::new(&infcx); - // Take the param-env of the adt and substitute the substs that show up in + // Take the param-env of the adt and substitute the args that show up in // the implementation's self type. This gives us the assumptions that the // self ty of the implementation is allowed to know just from it being a // well-formed adt, since that's all we're allowed to assume while proving @@ -129,7 +130,7 @@ fn ensure_drop_predicates_are_implied_by_item_defn<'tcx>( // substituting it with free params, so no additional param-env normalization // can occur on top of what has been done in the param_env query itself. let param_env = ty::EarlyBinder::bind(tcx.param_env(adt_def_id)) - .subst(tcx, adt_to_impl_substs) + .instantiate(tcx, adt_to_impl_args) .with_constness(tcx.constness(drop_impl_def_id)); for (pred, span) in tcx.predicates_of(drop_impl_def_id).instantiate_identity(tcx) { diff --git a/compiler/rustc_hir_analysis/src/check/entry.rs b/compiler/rustc_hir_analysis/src/check/entry.rs new file mode 100644 index 00000000000..fcaefe0261b --- /dev/null +++ b/compiler/rustc_hir_analysis/src/check/entry.rs @@ -0,0 +1,277 @@ +use rustc_hir as hir; +use rustc_hir::Node; +use rustc_infer::infer::TyCtxtInferExt; +use rustc_middle::ty::{self, Ty, TyCtxt}; +use rustc_session::config::EntryFnType; +use rustc_span::def_id::{DefId, LocalDefId, CRATE_DEF_ID}; +use rustc_span::{symbol::sym, Span}; +use rustc_target::spec::abi::Abi; +use rustc_trait_selection::traits::error_reporting::TypeErrCtxtExt as _; +use rustc_trait_selection::traits::{self, ObligationCause, ObligationCauseCode}; + +use std::ops::Not; + +use crate::errors; +use crate::require_same_types; + +pub(crate) fn check_for_entry_fn(tcx: TyCtxt<'_>) { + match tcx.entry_fn(()) { + Some((def_id, EntryFnType::Main { .. })) => check_main_fn_ty(tcx, def_id), + Some((def_id, EntryFnType::Start)) => check_start_fn_ty(tcx, def_id), + _ => {} + } +} + +fn check_main_fn_ty(tcx: TyCtxt<'_>, main_def_id: DefId) { + let main_fnsig = tcx.fn_sig(main_def_id).instantiate_identity(); + let main_span = tcx.def_span(main_def_id); + + fn main_fn_diagnostics_def_id(tcx: TyCtxt<'_>, def_id: DefId, sp: Span) -> LocalDefId { + if let Some(local_def_id) = def_id.as_local() { + let hir_type = tcx.type_of(local_def_id).instantiate_identity(); + if !matches!(hir_type.kind(), ty::FnDef(..)) { + span_bug!(sp, "main has a non-function type: found `{}`", hir_type); + } + local_def_id + } else { + CRATE_DEF_ID + } + } + + fn main_fn_generics_params_span(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Span> { + if !def_id.is_local() { + return None; + } + let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local()); + match tcx.hir().find(hir_id) { + Some(Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, generics, _), .. })) => { + generics.params.is_empty().not().then_some(generics.span) + } + _ => { + span_bug!(tcx.def_span(def_id), "main has a non-function type"); + } + } + } + + fn main_fn_where_clauses_span(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Span> { + if !def_id.is_local() { + return None; + } + let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local()); + match tcx.hir().find(hir_id) { + Some(Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, generics, _), .. })) => { + Some(generics.where_clause_span) + } + _ => { + span_bug!(tcx.def_span(def_id), "main has a non-function type"); + } + } + } + + fn main_fn_asyncness_span(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Span> { + if !def_id.is_local() { + return None; + } + Some(tcx.def_span(def_id)) + } + + fn main_fn_return_type_span(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Span> { + if !def_id.is_local() { + return None; + } + let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local()); + match tcx.hir().find(hir_id) { + Some(Node::Item(hir::Item { kind: hir::ItemKind::Fn(fn_sig, _, _), .. })) => { + Some(fn_sig.decl.output.span()) + } + _ => { + span_bug!(tcx.def_span(def_id), "main has a non-function type"); + } + } + } + + let mut error = false; + let main_diagnostics_def_id = main_fn_diagnostics_def_id(tcx, main_def_id, main_span); + let main_fn_generics = tcx.generics_of(main_def_id); + let main_fn_predicates = tcx.predicates_of(main_def_id); + if main_fn_generics.count() != 0 || !main_fnsig.bound_vars().is_empty() { + let generics_param_span = main_fn_generics_params_span(tcx, main_def_id); + tcx.sess.emit_err(errors::MainFunctionGenericParameters { + span: generics_param_span.unwrap_or(main_span), + label_span: generics_param_span, + }); + error = true; + } else if !main_fn_predicates.predicates.is_empty() { + // generics may bring in implicit predicates, so we skip this check if generics is present. + let generics_where_clauses_span = main_fn_where_clauses_span(tcx, main_def_id); + tcx.sess.emit_err(errors::WhereClauseOnMain { + span: generics_where_clauses_span.unwrap_or(main_span), + generics_span: generics_where_clauses_span, + }); + error = true; + } + + let main_asyncness = tcx.asyncness(main_def_id); + if let hir::IsAsync::Async = main_asyncness { + let asyncness_span = main_fn_asyncness_span(tcx, main_def_id); + tcx.sess.emit_err(errors::MainFunctionAsync { span: main_span, asyncness: asyncness_span }); + error = true; + } + + for attr in tcx.get_attrs(main_def_id, sym::track_caller) { + tcx.sess.emit_err(errors::TrackCallerOnMain { span: attr.span, annotated: main_span }); + error = true; + } + + if !tcx.codegen_fn_attrs(main_def_id).target_features.is_empty() + // Calling functions with `#[target_feature]` is not unsafe on WASM, see #84988 + && !tcx.sess.target.is_like_wasm + && !tcx.sess.opts.actually_rustdoc + { + tcx.sess.emit_err(errors::TargetFeatureOnMain { main: main_span }); + error = true; + } + + if error { + return; + } + + // Main should have no WC, so empty param env is OK here. + let param_env = ty::ParamEnv::empty(); + let expected_return_type; + if let Some(term_did) = tcx.lang_items().termination() { + let return_ty = main_fnsig.output(); + let return_ty_span = main_fn_return_type_span(tcx, main_def_id).unwrap_or(main_span); + if !return_ty.bound_vars().is_empty() { + tcx.sess.emit_err(errors::MainFunctionReturnTypeGeneric { span: return_ty_span }); + error = true; + } + let return_ty = return_ty.skip_binder(); + let infcx = tcx.infer_ctxt().build(); + let cause = traits::ObligationCause::new( + return_ty_span, + main_diagnostics_def_id, + ObligationCauseCode::MainFunctionType, + ); + let ocx = traits::ObligationCtxt::new(&infcx); + let norm_return_ty = ocx.normalize(&cause, param_env, return_ty); + ocx.register_bound(cause, param_env, norm_return_ty, term_did); + let errors = ocx.select_all_or_error(); + if !errors.is_empty() { + infcx.err_ctxt().report_fulfillment_errors(&errors); + error = true; + } + // now we can take the return type of the given main function + expected_return_type = main_fnsig.output(); + } else { + // standard () main return type + expected_return_type = ty::Binder::dummy(Ty::new_unit(tcx)); + } + + if error { + return; + } + + let se_ty = Ty::new_fn_ptr( + tcx, + expected_return_type.map_bound(|expected_return_type| { + tcx.mk_fn_sig([], expected_return_type, false, hir::Unsafety::Normal, Abi::Rust) + }), + ); + + require_same_types( + tcx, + &ObligationCause::new( + main_span, + main_diagnostics_def_id, + ObligationCauseCode::MainFunctionType, + ), + param_env, + se_ty, + Ty::new_fn_ptr(tcx, main_fnsig), + ); +} + +fn check_start_fn_ty(tcx: TyCtxt<'_>, start_def_id: DefId) { + let start_def_id = start_def_id.expect_local(); + let start_id = tcx.hir().local_def_id_to_hir_id(start_def_id); + let start_span = tcx.def_span(start_def_id); + let start_t = tcx.type_of(start_def_id).instantiate_identity(); + match start_t.kind() { + ty::FnDef(..) => { + if let Some(Node::Item(it)) = tcx.hir().find(start_id) { + if let hir::ItemKind::Fn(sig, generics, _) = &it.kind { + let mut error = false; + if !generics.params.is_empty() { + tcx.sess.emit_err(errors::StartFunctionParameters { span: generics.span }); + error = true; + } + if generics.has_where_clause_predicates { + tcx.sess.emit_err(errors::StartFunctionWhere { + span: generics.where_clause_span, + }); + error = true; + } + if let hir::IsAsync::Async = sig.header.asyncness { + let span = tcx.def_span(it.owner_id); + tcx.sess.emit_err(errors::StartAsync { span: span }); + error = true; + } + + let attrs = tcx.hir().attrs(start_id); + for attr in attrs { + if attr.has_name(sym::track_caller) { + tcx.sess.emit_err(errors::StartTrackCaller { + span: attr.span, + start: start_span, + }); + error = true; + } + if attr.has_name(sym::target_feature) + // Calling functions with `#[target_feature]` is + // not unsafe on WASM, see #84988 + && !tcx.sess.target.is_like_wasm + && !tcx.sess.opts.actually_rustdoc + { + tcx.sess.emit_err(errors::StartTargetFeature { + span: attr.span, + start: start_span, + }); + error = true; + } + } + + if error { + return; + } + } + } + + let se_ty = Ty::new_fn_ptr( + tcx, + ty::Binder::dummy(tcx.mk_fn_sig( + [tcx.types.isize, Ty::new_imm_ptr(tcx, Ty::new_imm_ptr(tcx, tcx.types.u8))], + tcx.types.isize, + false, + hir::Unsafety::Normal, + Abi::Rust, + )), + ); + + require_same_types( + tcx, + &ObligationCause::new( + start_span, + start_def_id, + ObligationCauseCode::StartFunctionType, + ), + ty::ParamEnv::empty(), // start should not have any where bounds. + se_ty, + Ty::new_fn_ptr(tcx, tcx.fn_sig(start_def_id).instantiate_identity()), + ); + } + _ => { + span_bug!(start_span, "start has a non-function type: found `{}`", start_t); + } + } +} diff --git a/compiler/rustc_hir_analysis/src/check/intrinsic.rs b/compiler/rustc_hir_analysis/src/check/intrinsic.rs index 1248f991cc4..d5c9840887a 100644 --- a/compiler/rustc_hir_analysis/src/check/intrinsic.rs +++ b/compiler/rustc_hir_analysis/src/check/intrinsic.rs @@ -60,7 +60,7 @@ fn equate_intrinsic_type<'tcx>( tcx, &cause, ty::ParamEnv::empty(), // FIXME: do all intrinsics have an empty param env? - Ty::new_fn_ptr(tcx, tcx.fn_sig(it.owner_id).subst_identity()), + Ty::new_fn_ptr(tcx, tcx.fn_sig(it.owner_id).instantiate_identity()), fty, ); } @@ -155,7 +155,7 @@ pub fn check_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem<'_>) { ty::INNERMOST, ty::BoundRegion { var: ty::BoundVar::from_u32(1), kind: ty::BrEnv }, ); - let va_list_ty = tcx.type_of(did).subst(tcx, &[region.into()]); + let va_list_ty = tcx.type_of(did).instantiate(tcx, &[region.into()]); (Ty::new_ref(tcx, env_region, ty::TypeAndMut { ty: va_list_ty, mutbl }), va_list_ty) }) }; @@ -238,7 +238,7 @@ pub fn check_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem<'_>) { ty: Ty::new_adt( tcx, tcx.adt_def(option_def_id), - tcx.mk_substs_from_iter([ty::GenericArg::from(p0)].into_iter()), + tcx.mk_args_from_iter([ty::GenericArg::from(p0)].into_iter()), ), mutbl: hir::Mutability::Not, }, @@ -412,7 +412,7 @@ pub fn check_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem<'_>) { ty::Region::new_late_bound(tcx, ty::INNERMOST, br), param(0), )], - Ty::new_projection(tcx, discriminant_def_id, tcx.mk_substs(&[param(0).into()])), + Ty::new_projection(tcx, discriminant_def_id, tcx.mk_args(&[param(0).into()])), ) } diff --git a/compiler/rustc_hir_analysis/src/check/intrinsicck.rs b/compiler/rustc_hir_analysis/src/check/intrinsicck.rs index 0bb1467ef31..8423a9550ba 100644 --- a/compiler/rustc_hir_analysis/src/check/intrinsicck.rs +++ b/compiler/rustc_hir_analysis/src/check/intrinsicck.rs @@ -81,9 +81,9 @@ impl<'a, 'tcx> InlineAsmCtxt<'a, 'tcx> { ty::RawPtr(ty::TypeAndMut { ty, mutbl: _ }) if self.is_thin_ptr_ty(ty) => { Some(asm_ty_isize) } - ty::Adt(adt, substs) if adt.repr().simd() => { + ty::Adt(adt, args) if adt.repr().simd() => { let fields = &adt.non_enum_variant().fields; - let elem_ty = fields[FieldIdx::from_u32(0)].ty(self.tcx, substs); + let elem_ty = fields[FieldIdx::from_u32(0)].ty(self.tcx, args); let (size, ty) = match elem_ty.kind() { ty::Array(ty, len) => { @@ -186,18 +186,14 @@ impl<'a, 'tcx> InlineAsmCtxt<'a, 'tcx> { let Some((_, feature)) = supported_tys.iter().find(|&&(t, _)| t == asm_ty) else { let msg = format!("type `{ty}` cannot be used with this register class"); let mut err = self.tcx.sess.struct_span_err(expr.span, msg); - let supported_tys: Vec<_> = - supported_tys.iter().map(|(t, _)| t.to_string()).collect(); + let supported_tys: Vec<_> = supported_tys.iter().map(|(t, _)| t.to_string()).collect(); err.note(format!( "register class `{}` supports these types: {}", reg_class.name(), supported_tys.join(", "), )); if let Some(suggest) = reg_class.suggest_class(asm_arch, asm_ty) { - err.help(format!( - "consider using the `{}` register class instead", - suggest.name() - )); + err.help(format!("consider using the `{}` register class instead", suggest.name())); } err.emit(); return Some(asm_ty); @@ -427,7 +423,7 @@ impl<'a, 'tcx> InlineAsmCtxt<'a, 'tcx> { // Check that sym actually points to a function. Later passes // depend on this. hir::InlineAsmOperand::SymFn { anon_const } => { - let ty = self.tcx.type_of(anon_const.def_id).subst_identity(); + let ty = self.tcx.type_of(anon_const.def_id).instantiate_identity(); match ty.kind() { ty::Never | ty::Error(_) => {} ty::FnDef(..) => {} diff --git a/compiler/rustc_hir_analysis/src/check/mod.rs b/compiler/rustc_hir_analysis/src/check/mod.rs index ce2da7cb1a3..5ff33763e13 100644 --- a/compiler/rustc_hir_analysis/src/check/mod.rs +++ b/compiler/rustc_hir_analysis/src/check/mod.rs @@ -38,7 +38,7 @@ can be broken down into several distinct phases: While type checking a function, the intermediate types for the expressions, blocks, and so forth contained within the function are -stored in `fcx.node_types` and `fcx.node_substs`. These types +stored in `fcx.node_types` and `fcx.node_args`. These types may contain unresolved type variables. After type checking is complete, the functions in the writeback module are used to take the types from this table, resolve them, and then write them into their @@ -65,6 +65,7 @@ a type parameter). mod check; mod compare_impl_item; pub mod dropck; +mod entry; pub mod intrinsic; pub mod intrinsicck; mod region; @@ -80,7 +81,7 @@ use rustc_hir::intravisit::Visitor; use rustc_index::bit_set::BitSet; use rustc_middle::query::Providers; use rustc_middle::ty::{self, Ty, TyCtxt}; -use rustc_middle::ty::{InternalSubsts, SubstsRef}; +use rustc_middle::ty::{GenericArgs, GenericArgsRef}; use rustc_session::parse::feature_err; use rustc_span::source_map::DUMMY_SP; use rustc_span::symbol::{kw, Ident}; @@ -188,7 +189,7 @@ fn missing_items_err( full_impl_span: Span, ) { let missing_items = - missing_items.iter().filter(|trait_item| trait_item.opt_rpitit_info.is_none()); + missing_items.iter().filter(|trait_item| !trait_item.is_impl_trait_in_trait()); let missing_items_msg = missing_items .clone() @@ -211,7 +212,7 @@ fn missing_items_err( let snippet = suggestion_signature( tcx, trait_item, - tcx.impl_trait_ref(impl_def_id).unwrap().subst_identity(), + tcx.impl_trait_ref(impl_def_id).unwrap().instantiate_identity(), ); let code = format!("{}{}\n{}", padding, snippet, padding); if let Some(span) = tcx.hir().span_if_local(trait_item.def_id) { @@ -408,7 +409,7 @@ fn fn_sig_suggestion<'tcx>( let asyncness = if tcx.asyncness(assoc.def_id).is_async() { output = if let ty::Alias(_, alias_ty) = *output.kind() { tcx.explicit_item_bounds(alias_ty.def_id) - .subst_iter_copied(tcx, alias_ty.substs) + .arg_iter_copied(tcx, alias_ty.args) .find_map(|(bound, _)| bound.as_projection_clause()?.no_bound_vars()?.term.ty()) .unwrap_or_else(|| { span_bug!( @@ -461,10 +462,10 @@ fn suggestion_signature<'tcx>( assoc: ty::AssocItem, impl_trait_ref: ty::TraitRef<'tcx>, ) -> String { - let substs = ty::InternalSubsts::identity_for_item(tcx, assoc.def_id).rebase_onto( + let args = ty::GenericArgs::identity_for_item(tcx, assoc.def_id).rebase_onto( tcx, assoc.container_id(tcx), - impl_trait_ref.with_self_ty(tcx, tcx.types.self_param).substs, + impl_trait_ref.with_self_ty(tcx, tcx.types.self_param).args, ); match assoc.kind { @@ -472,21 +473,21 @@ fn suggestion_signature<'tcx>( tcx, tcx.liberate_late_bound_regions( assoc.def_id, - tcx.fn_sig(assoc.def_id).subst(tcx, substs), + tcx.fn_sig(assoc.def_id).instantiate(tcx, args), ), assoc.ident(tcx), - tcx.predicates_of(assoc.def_id).instantiate_own(tcx, substs), + tcx.predicates_of(assoc.def_id).instantiate_own(tcx, args), assoc, ), ty::AssocKind::Type => { let (generics, where_clauses) = bounds_from_generic_predicates( tcx, - tcx.predicates_of(assoc.def_id).instantiate_own(tcx, substs), + tcx.predicates_of(assoc.def_id).instantiate_own(tcx, args), ); format!("type {}{generics} = /* Type */{where_clauses};", assoc.name) } ty::AssocKind::Const => { - let ty = tcx.type_of(assoc.def_id).subst_identity(); + let ty = tcx.type_of(assoc.def_id).instantiate_identity(); let val = ty_kind_suggestion(ty).unwrap_or("todo!()"); format!("const {}: {} = {};", assoc.name, ty, val) } diff --git a/compiler/rustc_hir_analysis/src/check/wfcheck.rs b/compiler/rustc_hir_analysis/src/check/wfcheck.rs index d4748b7ef0b..443d072f992 100644 --- a/compiler/rustc_hir_analysis/src/check/wfcheck.rs +++ b/compiler/rustc_hir_analysis/src/check/wfcheck.rs @@ -18,7 +18,7 @@ use rustc_middle::ty::{ self, AdtKind, GenericParamDefKind, ToPredicate, Ty, TyCtxt, TypeFoldable, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, }; -use rustc_middle::ty::{GenericArgKind, InternalSubsts}; +use rustc_middle::ty::{GenericArgKind, GenericArgs}; use rustc_session::parse::feature_err; use rustc_span::symbol::{sym, Ident, Symbol}; use rustc_span::{Span, DUMMY_SP}; @@ -290,7 +290,7 @@ fn check_trait_item(tcx: TyCtxt<'_>, trait_item: &hir::TraitItem<'_>) { /// Require that the user writes where clauses on GATs for the implicit /// outlives bounds involving trait parameters in trait functions and -/// lifetimes passed as GAT substs. See `self-outlives-lint` test. +/// lifetimes passed as GAT args. See `self-outlives-lint` test. /// /// We use the following trait as an example throughout this function: /// ```rust,ignore (this code fails due to this lint) @@ -314,7 +314,7 @@ fn check_gat_where_clauses(tcx: TyCtxt<'_>, associated_items: &[hir::TraitItemRe for gat_item in associated_items { let gat_def_id = gat_item.id.owner_id; let gat_item = tcx.associated_item(gat_def_id); - // If this item is not an assoc ty, or has no substs, then it's not a GAT + // If this item is not an assoc ty, or has no args, then it's not a GAT if gat_item.kind != ty::AssocKind::Type { continue; } @@ -345,7 +345,7 @@ fn check_gat_where_clauses(tcx: TyCtxt<'_>, associated_items: &[hir::TraitItemRe // `Self::Iter<'a>` is a GAT we want to gather any potential missing bounds from. let sig: ty::FnSig<'_> = tcx.liberate_late_bound_regions( item_def_id.to_def_id(), - tcx.fn_sig(item_def_id).subst_identity(), + tcx.fn_sig(item_def_id).instantiate_identity(), ); gather_gat_bounds( tcx, @@ -374,7 +374,7 @@ fn check_gat_where_clauses(tcx: TyCtxt<'_>, associated_items: &[hir::TraitItemRe param_env, item_def_id, tcx.explicit_item_bounds(item_def_id) - .subst_identity_iter_copied() + .instantiate_identity_iter_copied() .collect::<Vec<_>>(), &FxIndexSet::default(), gat_def_id.def_id, @@ -737,7 +737,7 @@ impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for GATSubstCollector<'tcx> { fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> { match t.kind() { ty::Alias(ty::Projection, p) if p.def_id == self.gat => { - for (idx, subst) in p.substs.iter().enumerate() { + for (idx, subst) in p.args.iter().enumerate() { match subst.unpack() { GenericArgKind::Lifetime(lt) if !lt.is_late_bound() => { self.regions.insert((lt, idx)); @@ -836,7 +836,7 @@ fn check_param_wf(tcx: TyCtxt<'_>, param: &hir::GenericParam<'_>) { // Const parameters are well formed if their type is structural match. hir::GenericParamKind::Const { ty: hir_ty, default: _ } => { - let ty = tcx.type_of(param.def_id).subst_identity(); + let ty = tcx.type_of(param.def_id).instantiate_identity(); if tcx.features().adt_const_params { enter_wf_checking_ctxt(tcx, hir_ty.span, param.def_id, |wfcx| { @@ -910,17 +910,17 @@ fn check_associated_item( let self_ty = match item.container { ty::TraitContainer => tcx.types.self_param, - ty::ImplContainer => tcx.type_of(item.container_id(tcx)).subst_identity(), + ty::ImplContainer => tcx.type_of(item.container_id(tcx)).instantiate_identity(), }; match item.kind { ty::AssocKind::Const => { - let ty = tcx.type_of(item.def_id).subst_identity(); + let ty = tcx.type_of(item.def_id).instantiate_identity(); let ty = wfcx.normalize(span, Some(WellFormedLoc::Ty(item_id)), ty); wfcx.register_wf_obligation(span, loc, ty.into()); } ty::AssocKind::Fn => { - let sig = tcx.fn_sig(item.def_id).subst_identity(); + let sig = tcx.fn_sig(item.def_id).instantiate_identity(); let hir_sig = sig_if_method.expect("bad signature for method"); check_fn_or_method( wfcx, @@ -936,7 +936,7 @@ fn check_associated_item( check_associated_type_bounds(wfcx, item, span) } if item.defaultness(tcx).has_value() { - let ty = tcx.type_of(item.def_id).subst_identity(); + let ty = tcx.type_of(item.def_id).instantiate_identity(); let ty = wfcx.normalize(span, Some(WellFormedLoc::Ty(item_id)), ty); wfcx.register_wf_obligation(span, loc, ty.into()); } @@ -969,7 +969,11 @@ fn check_type_defn<'tcx>(tcx: TyCtxt<'tcx>, item: &hir::Item<'tcx>, all_sized: b let field_id = field.did.expect_local(); let hir::FieldDef { ty: hir_ty, .. } = tcx.hir().get_by_def_id(field_id).expect_field(); - let ty = wfcx.normalize(hir_ty.span, None, tcx.type_of(field.did).subst_identity()); + let ty = wfcx.normalize( + hir_ty.span, + None, + tcx.type_of(field.did).instantiate_identity(), + ); wfcx.register_wf_obligation( hir_ty.span, Some(WellFormedLoc::Ty(field_id)), @@ -981,7 +985,7 @@ fn check_type_defn<'tcx>(tcx: TyCtxt<'tcx>, item: &hir::Item<'tcx>, all_sized: b // intermediate types must be sized. let needs_drop_copy = || { packed && { - let ty = tcx.type_of(variant.tail().did).subst_identity(); + let ty = tcx.type_of(variant.tail().did).instantiate_identity(); let ty = tcx.erase_regions(ty); if ty.has_infer() { tcx.sess @@ -1003,7 +1007,11 @@ fn check_type_defn<'tcx>(tcx: TyCtxt<'tcx>, item: &hir::Item<'tcx>, all_sized: b let field_id = field.did.expect_local(); let hir::FieldDef { ty: hir_ty, .. } = tcx.hir().get_by_def_id(field_id).expect_field(); - let ty = wfcx.normalize(hir_ty.span, None, tcx.type_of(field.did).subst_identity()); + let ty = wfcx.normalize( + hir_ty.span, + None, + tcx.type_of(field.did).instantiate_identity(), + ); wfcx.register_bound( traits::ObligationCause::new( hir_ty.span, @@ -1083,16 +1091,17 @@ fn check_associated_type_bounds(wfcx: &WfCheckingCtxt<'_, '_>, item: ty::AssocIt let bounds = wfcx.tcx().explicit_item_bounds(item.def_id); debug!("check_associated_type_bounds: bounds={:?}", bounds); - let wf_obligations = bounds.subst_identity_iter_copied().flat_map(|(bound, bound_span)| { - let normalized_bound = wfcx.normalize(span, None, bound); - traits::wf::predicate_obligations( - wfcx.infcx, - wfcx.param_env, - wfcx.body_def_id, - normalized_bound.as_predicate(), - bound_span, - ) - }); + let wf_obligations = + bounds.instantiate_identity_iter_copied().flat_map(|(bound, bound_span)| { + let normalized_bound = wfcx.normalize(span, None, bound); + traits::wf::predicate_obligations( + wfcx.infcx, + wfcx.param_env, + wfcx.body_def_id, + normalized_bound.as_predicate(), + bound_span, + ) + }); wfcx.register_obligations(wf_obligations); } @@ -1105,7 +1114,7 @@ fn check_item_fn( decl: &hir::FnDecl<'_>, ) { enter_wf_checking_ctxt(tcx, span, def_id, |wfcx| { - let sig = tcx.fn_sig(def_id).subst_identity(); + let sig = tcx.fn_sig(def_id).instantiate_identity(); check_fn_or_method(wfcx, ident.span, sig, decl, def_id); }) } @@ -1125,7 +1134,7 @@ fn check_item_type( debug!("check_item_type: {:?}", item_id); enter_wf_checking_ctxt(tcx, ty_span, item_id, |wfcx| { - let ty = tcx.type_of(item_id).subst_identity(); + let ty = tcx.type_of(item_id).instantiate_identity(); let item_ty = wfcx.normalize(ty_span, Some(WellFormedLoc::Ty(item_id)), ty); let forbid_unsized = match unsized_handling { @@ -1178,7 +1187,7 @@ fn check_impl<'tcx>( // `#[rustc_reservation_impl]` impls are not real impls and // therefore don't need to be WF (the trait's `Self: Trait` predicate // won't hold). - let trait_ref = tcx.impl_trait_ref(item.owner_id).unwrap().subst_identity(); + let trait_ref = tcx.impl_trait_ref(item.owner_id).unwrap().instantiate_identity(); let trait_ref = wfcx.normalize( ast_trait_ref.path.span, Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)), @@ -1211,7 +1220,7 @@ fn check_impl<'tcx>( wfcx.register_obligations(obligations); } None => { - let self_ty = tcx.type_of(item.owner_id).subst_identity(); + let self_ty = tcx.type_of(item.owner_id).instantiate_identity(); let self_ty = wfcx.normalize( item.span, Some(WellFormedLoc::Ty(item.hir_id().expect_owner().def_id)), @@ -1256,7 +1265,7 @@ fn check_where_clauses<'tcx>(wfcx: &WfCheckingCtxt<'_, 'tcx>, span: Span, def_id match param.kind { GenericParamDefKind::Type { .. } => { if is_our_default(param) { - let ty = tcx.type_of(param.def_id).subst_identity(); + let ty = tcx.type_of(param.def_id).instantiate_identity(); // Ignore dependent defaults -- that is, where the default of one type // parameter includes another (e.g., `<T, U = T>`). In those cases, we can't // be sure if it will error or not as user might always specify the other. @@ -1272,10 +1281,10 @@ fn check_where_clauses<'tcx>(wfcx: &WfCheckingCtxt<'_, 'tcx>, span: Span, def_id GenericParamDefKind::Const { .. } => { if is_our_default(param) { // FIXME(const_generics_defaults): This - // is incorrect when dealing with unused substs, for example + // is incorrect when dealing with unused args, for example // for `struct Foo<const N: usize, const M: usize = { 1 - 2 }>` // we should eagerly error. - let default_ct = tcx.const_param_default(param.def_id).subst_identity(); + let default_ct = tcx.const_param_default(param.def_id).instantiate_identity(); if !default_ct.has_param() { wfcx.register_wf_obligation( tcx.def_span(param.def_id), @@ -1298,7 +1307,7 @@ fn check_where_clauses<'tcx>(wfcx: &WfCheckingCtxt<'_, 'tcx>, span: Span, def_id // For more examples see tests `defaults-well-formedness.rs` and `type-check-defaults.rs`. // // First we build the defaulted substitution. - let substs = InternalSubsts::for_item(tcx, def_id.to_def_id(), |param, _| { + let args = GenericArgs::for_item(tcx, def_id.to_def_id(), |param, _| { match param.kind { GenericParamDefKind::Lifetime => { // All regions are identity. @@ -1308,7 +1317,7 @@ fn check_where_clauses<'tcx>(wfcx: &WfCheckingCtxt<'_, 'tcx>, span: Span, def_id GenericParamDefKind::Type { .. } => { // If the param has a default, ... if is_our_default(param) { - let default_ty = tcx.type_of(param.def_id).subst_identity(); + let default_ty = tcx.type_of(param.def_id).instantiate_identity(); // ... and it's not a dependent default, ... if !default_ty.has_param() { // ... then substitute it with the default. @@ -1321,7 +1330,7 @@ fn check_where_clauses<'tcx>(wfcx: &WfCheckingCtxt<'_, 'tcx>, span: Span, def_id GenericParamDefKind::Const { .. } => { // If the param has a default, ... if is_our_default(param) { - let default_ct = tcx.const_param_default(param.def_id).subst_identity(); + let default_ct = tcx.const_param_default(param.def_id).instantiate_identity(); // ... and it's not a dependent default, ... if !default_ct.has_param() { // ... then substitute it with the default. @@ -1366,7 +1375,7 @@ fn check_where_clauses<'tcx>(wfcx: &WfCheckingCtxt<'_, 'tcx>, span: Span, def_id } let mut param_count = CountParams::default(); let has_region = pred.visit_with(&mut param_count).is_break(); - let substituted_pred = ty::EarlyBinder::bind(pred).subst(tcx, substs); + let substituted_pred = ty::EarlyBinder::bind(pred).instantiate(tcx, args); // Don't check non-defaulted params, dependent defaults (including lifetimes) // or preds with multiple params. if substituted_pred.has_non_region_param() || param_count.params.len() > 1 || has_region @@ -1529,7 +1538,7 @@ fn check_return_position_impl_trait_in_trait_bounds<'tcx>( // strategy, we can't just call `check_associated_item` on the new RPITITs, // because tests like `tests/ui/async-await/in-trait/implied-bounds.rs` will fail. // That's because we need to check that the bounds of the RPITIT hold using -// the special substs that we create during opaque type lowering, otherwise we're +// the special args that we create during opaque type lowering, otherwise we're // getting a bunch of early bound and free regions mixed up... Haven't looked too // deep into this, though. struct ImplTraitInTraitFinder<'a, 'tcx> { @@ -1558,7 +1567,7 @@ impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ImplTraitInTraitFinder<'_, 'tcx> { }); for (bound, bound_span) in tcx .explicit_item_bounds(opaque_ty.def_id) - .subst_iter_copied(tcx, opaque_ty.substs) + .arg_iter_copied(tcx, opaque_ty.args) { let bound = self.wfcx.normalize(bound_span, None, bound); self.wfcx.register_obligations(traits::wf::predicate_obligations( @@ -1569,7 +1578,7 @@ impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ImplTraitInTraitFinder<'_, 'tcx> { bound_span, )); // Set the debruijn index back to innermost here, since we already eagerly - // shifted the substs that we use to generate these bounds. This is unfortunately + // shifted the args that we use to generate these bounds. This is unfortunately // subtly different behavior than the `ImplTraitInTraitFinder` we use in `param_env`, // but that function doesn't actually need to normalize the bound it's visiting // (whereas we have to do so here)... @@ -1601,7 +1610,7 @@ fn check_method_receiver<'tcx>( let span = fn_sig.decl.inputs[0].span; - let sig = tcx.fn_sig(method.def_id).subst_identity(); + let sig = tcx.fn_sig(method.def_id).instantiate_identity(); let sig = tcx.liberate_late_bound_regions(method.def_id, sig); let sig = wfcx.normalize(span, None, sig); @@ -1773,9 +1782,9 @@ fn check_variances_for_type_defn<'tcx>( item: &hir::Item<'tcx>, hir_generics: &hir::Generics<'_>, ) { - let identity_substs = ty::InternalSubsts::identity_for_item(tcx, item.owner_id); + let identity_args = ty::GenericArgs::identity_for_item(tcx, item.owner_id); for field in tcx.adt_def(item.owner_id).all_fields() { - if field.ty(tcx, identity_substs).references_error() { + if field.ty(tcx, identity_args).references_error() { return; } } diff --git a/compiler/rustc_hir_analysis/src/check_unused.rs b/compiler/rustc_hir_analysis/src/check_unused.rs index 268b9ac530f..5318e637fc7 100644 --- a/compiler/rustc_hir_analysis/src/check_unused.rs +++ b/compiler/rustc_hir_analysis/src/check_unused.rs @@ -1,4 +1,4 @@ -use rustc_data_structures::unord::UnordSet; +use rustc_data_structures::unord::{ExtendUnord, UnordSet}; use rustc_hir::def::DefKind; use rustc_hir::def_id::LocalDefId; use rustc_middle::ty::TyCtxt; @@ -7,6 +7,10 @@ use rustc_session::lint; pub fn check_crate(tcx: TyCtxt<'_>) { let mut used_trait_imports: UnordSet<LocalDefId> = Default::default(); + // FIXME: Use `tcx.hir().par_body_owners()` when we implement creating `DefId`s + // for anon constants during their parents' typeck. + // Doing so at current will produce queries cycle errors because it may typeck + // on anon constants directly. for item_def_id in tcx.hir().body_owners() { let imports = tcx.used_trait_imports(item_def_id); debug!("GatherVisitor: item_def_id={:?} with imports {:#?}", item_def_id, imports); diff --git a/compiler/rustc_hir_analysis/src/coherence/builtin.rs b/compiler/rustc_hir_analysis/src/coherence/builtin.rs index 79cc43edff1..3f65adcd36e 100644 --- a/compiler/rustc_hir_analysis/src/coherence/builtin.rs +++ b/compiler/rustc_hir_analysis/src/coherence/builtin.rs @@ -57,7 +57,7 @@ impl<'tcx> Checker<'tcx> { fn visit_implementation_of_drop(tcx: TyCtxt<'_>, impl_did: LocalDefId) { // Destructors only work on local ADT types. - match tcx.type_of(impl_did).subst_identity().kind() { + match tcx.type_of(impl_did).instantiate_identity().kind() { ty::Adt(def, _) if def.did().is_local() => return, ty::Error(_) => return, _ => {} @@ -71,7 +71,7 @@ fn visit_implementation_of_drop(tcx: TyCtxt<'_>, impl_did: LocalDefId) { fn visit_implementation_of_copy(tcx: TyCtxt<'_>, impl_did: LocalDefId) { debug!("visit_implementation_of_copy: impl_did={:?}", impl_did); - let self_type = tcx.type_of(impl_did).subst_identity(); + let self_type = tcx.type_of(impl_did).instantiate_identity(); debug!("visit_implementation_of_copy: self_type={:?} (bound)", self_type); let param_env = tcx.param_env(impl_did); @@ -100,7 +100,7 @@ fn visit_implementation_of_copy(tcx: TyCtxt<'_>, impl_did: LocalDefId) { } fn visit_implementation_of_const_param_ty(tcx: TyCtxt<'_>, impl_did: LocalDefId) { - let self_type = tcx.type_of(impl_did).subst_identity(); + let self_type = tcx.type_of(impl_did).instantiate_identity(); assert!(!self_type.has_escaping_bound_vars()); let param_env = tcx.param_env(impl_did); @@ -139,13 +139,13 @@ fn visit_implementation_of_dispatch_from_dyn(tcx: TyCtxt<'_>, impl_did: LocalDef let dispatch_from_dyn_trait = tcx.require_lang_item(LangItem::DispatchFromDyn, Some(span)); - let source = tcx.type_of(impl_did).subst_identity(); + let source = tcx.type_of(impl_did).instantiate_identity(); assert!(!source.has_escaping_bound_vars()); let target = { - let trait_ref = tcx.impl_trait_ref(impl_did).unwrap().subst_identity(); + let trait_ref = tcx.impl_trait_ref(impl_did).unwrap().instantiate_identity(); assert_eq!(trait_ref.def_id, dispatch_from_dyn_trait); - trait_ref.substs.type_at(1) + trait_ref.args.type_at(1) }; debug!("visit_implementation_of_dispatch_from_dyn: {:?} -> {:?}", source, target); @@ -163,9 +163,7 @@ fn visit_implementation_of_dispatch_from_dyn(tcx: TyCtxt<'_>, impl_did: LocalDef if infcx.at(&cause, param_env).eq(DefineOpaqueTypes::No, r_a, *r_b).is_ok() && mutbl_a == *mutbl_b => {} (&RawPtr(tm_a), &RawPtr(tm_b)) if tm_a.mutbl == tm_b.mutbl => (), - (&Adt(def_a, substs_a), &Adt(def_b, substs_b)) - if def_a.is_struct() && def_b.is_struct() => - { + (&Adt(def_a, args_a), &Adt(def_b, args_b)) if def_a.is_struct() && def_b.is_struct() => { if def_a != def_b { let source_path = tcx.def_path_str(def_a.did()); let target_path = tcx.def_path_str(def_b.did()); @@ -194,8 +192,8 @@ fn visit_implementation_of_dispatch_from_dyn(tcx: TyCtxt<'_>, impl_did: LocalDef let coerced_fields = fields .iter() .filter(|field| { - let ty_a = field.ty(tcx, substs_a); - let ty_b = field.ty(tcx, substs_b); + let ty_a = field.ty(tcx, args_a); + let ty_b = field.ty(tcx, args_b); if let Ok(layout) = tcx.layout_of(param_env.and(ty_a)) { if layout.is_zst() && layout.align.abi.bytes() == 1 { @@ -250,8 +248,8 @@ fn visit_implementation_of_dispatch_from_dyn(tcx: TyCtxt<'_>, impl_did: LocalDef format!( "`{}` (`{}` to `{}`)", field.name, - field.ty(tcx, substs_a), - field.ty(tcx, substs_b), + field.ty(tcx, args_a), + field.ty(tcx, args_b), ) }) .collect::<Vec<_>>() @@ -268,7 +266,7 @@ fn visit_implementation_of_dispatch_from_dyn(tcx: TyCtxt<'_>, impl_did: LocalDef ty::TraitRef::new( tcx, dispatch_from_dyn_trait, - [field.ty(tcx, substs_a), field.ty(tcx, substs_b)], + [field.ty(tcx, args_a), field.ty(tcx, args_b)], ), )); } @@ -300,10 +298,10 @@ pub fn coerce_unsized_info<'tcx>(tcx: TyCtxt<'tcx>, impl_did: LocalDefId) -> Coe let unsize_trait = tcx.require_lang_item(LangItem::Unsize, Some(span)); - let source = tcx.type_of(impl_did).subst_identity(); - let trait_ref = tcx.impl_trait_ref(impl_did).unwrap().subst_identity(); + let source = tcx.type_of(impl_did).instantiate_identity(); + let trait_ref = tcx.impl_trait_ref(impl_did).unwrap().instantiate_identity(); assert_eq!(trait_ref.def_id, coerce_unsized_trait); - let target = trait_ref.substs.type_at(1); + let target = trait_ref.args.type_at(1); debug!("visit_implementation_of_coerce_unsized: {:?} -> {:?} (bound)", source, target); let param_env = tcx.param_env(impl_did); @@ -348,7 +346,7 @@ pub fn coerce_unsized_info<'tcx>(tcx: TyCtxt<'tcx>, impl_did: LocalDefId) -> Coe check_mutbl(mt_a, mt_b, &|ty| Ty::new_imm_ptr(tcx, ty)) } - (&ty::Adt(def_a, substs_a), &ty::Adt(def_b, substs_b)) + (&ty::Adt(def_a, args_a), &ty::Adt(def_b, args_b)) if def_a.is_struct() && def_b.is_struct() => { if def_a != def_b { @@ -411,9 +409,9 @@ pub fn coerce_unsized_info<'tcx>(tcx: TyCtxt<'tcx>, impl_did: LocalDefId) -> Coe let diff_fields = fields .iter_enumerated() .filter_map(|(i, f)| { - let (a, b) = (f.ty(tcx, substs_a), f.ty(tcx, substs_b)); + let (a, b) = (f.ty(tcx, args_a), f.ty(tcx, args_b)); - if tcx.type_of(f.did).subst_identity().is_phantom_data() { + if tcx.type_of(f.did).instantiate_identity().is_phantom_data() { // Ignore PhantomData fields return None; } diff --git a/compiler/rustc_hir_analysis/src/coherence/inherent_impls.rs b/compiler/rustc_hir_analysis/src/coherence/inherent_impls.rs index 33559020692..f5326e50614 100644 --- a/compiler/rustc_hir_analysis/src/coherence/inherent_impls.rs +++ b/compiler/rustc_hir_analysis/src/coherence/inherent_impls.rs @@ -171,7 +171,7 @@ impl<'tcx> InherentCollect<'tcx> { let id = id.owner_id.def_id; let item_span = self.tcx.def_span(id); - let self_ty = self.tcx.type_of(id).subst_identity(); + let self_ty = self.tcx.type_of(id).instantiate_identity(); match *self_ty.kind() { ty::Adt(def, _) => self.check_def_id(id, self_ty, def.did()), ty::Foreign(did) => self.check_def_id(id, self_ty, did), diff --git a/compiler/rustc_hir_analysis/src/coherence/mod.rs b/compiler/rustc_hir_analysis/src/coherence/mod.rs index 5097f43607e..fc8fab0eabc 100644 --- a/compiler/rustc_hir_analysis/src/coherence/mod.rs +++ b/compiler/rustc_hir_analysis/src/coherence/mod.rs @@ -122,7 +122,7 @@ fn coherent_trait(tcx: TyCtxt<'_>, def_id: DefId) { let impls = tcx.hir().trait_impls(def_id); for &impl_def_id in impls { - let trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap().subst_identity(); + let trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap().instantiate_identity(); check_impl(tcx, impl_def_id, trait_ref); check_object_overlap(tcx, impl_def_id, trait_ref); diff --git a/compiler/rustc_hir_analysis/src/coherence/orphan.rs b/compiler/rustc_hir_analysis/src/coherence/orphan.rs index 025bab14021..05c78f57088 100644 --- a/compiler/rustc_hir_analysis/src/coherence/orphan.rs +++ b/compiler/rustc_hir_analysis/src/coherence/orphan.rs @@ -5,8 +5,8 @@ use rustc_data_structures::fx::FxHashSet; use rustc_errors::{struct_span_err, DelayDm}; use rustc_errors::{Diagnostic, ErrorGuaranteed}; use rustc_hir as hir; -use rustc_middle::ty::subst::InternalSubsts; use rustc_middle::ty::util::CheckRegions; +use rustc_middle::ty::GenericArgs; use rustc_middle::ty::{ self, AliasKind, ImplPolarity, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, @@ -22,7 +22,7 @@ pub(crate) fn orphan_check_impl( tcx: TyCtxt<'_>, impl_def_id: LocalDefId, ) -> Result<(), ErrorGuaranteed> { - let trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap().subst_identity(); + let trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap().instantiate_identity(); trait_ref.error_reported()?; let ret = do_orphan_check_impl(tcx, trait_ref, impl_def_id); @@ -488,10 +488,10 @@ fn lint_auto_trait_impl<'tcx>( trait_ref: ty::TraitRef<'tcx>, impl_def_id: LocalDefId, ) { - assert_eq!(trait_ref.substs.len(), 1); + assert_eq!(trait_ref.args.len(), 1); let self_ty = trait_ref.self_ty(); - let (self_type_did, substs) = match self_ty.kind() { - ty::Adt(def, substs) => (def.did(), substs), + let (self_type_did, args) = match self_ty.kind() { + ty::Adt(def, args) => (def.did(), args), _ => { // FIXME: should also lint for stuff like `&i32` but // considering that auto traits are unstable, that @@ -502,9 +502,9 @@ fn lint_auto_trait_impl<'tcx>( }; // Impls which completely cover a given root type are fine as they - // disable auto impls entirely. So only lint if the substs - // are not a permutation of the identity substs. - let Err(arg) = tcx.uses_unique_generic_params(substs, CheckRegions::No) else { + // disable auto impls entirely. So only lint if the args + // are not a permutation of the identity args. + let Err(arg) = tcx.uses_unique_generic_params(args, CheckRegions::No) else { // ok return; }; @@ -585,14 +585,14 @@ fn fast_reject_auto_impl<'tcx>(tcx: TyCtxt<'tcx>, trait_def_id: DefId, self_ty: } match t.kind() { - ty::Adt(def, substs) if def.is_phantom_data() => substs.visit_with(self), - ty::Adt(def, substs) => { + ty::Adt(def, args) if def.is_phantom_data() => args.visit_with(self), + ty::Adt(def, args) => { // @lcnr: This is the only place where cycles can happen. We avoid this // by only visiting each `DefId` once. // // This will be is incorrect in subtle cases, but I don't care :) if self.seen.insert(def.did()) { - for ty in def.all_fields().map(|field| field.ty(tcx, substs)) { + for ty in def.all_fields().map(|field| field.ty(tcx, args)) { ty.visit_with(self)?; } } @@ -605,9 +605,7 @@ fn fast_reject_auto_impl<'tcx>(tcx: TyCtxt<'tcx>, trait_def_id: DefId, self_ty: } let self_ty_root = match self_ty.kind() { - ty::Adt(def, _) => { - Ty::new_adt(tcx, *def, InternalSubsts::identity_for_item(tcx, def.did())) - } + ty::Adt(def, _) => Ty::new_adt(tcx, *def, GenericArgs::identity_for_item(tcx, def.did())), _ => unimplemented!("unexpected self ty {:?}", self_ty), }; diff --git a/compiler/rustc_hir_analysis/src/coherence/unsafety.rs b/compiler/rustc_hir_analysis/src/coherence/unsafety.rs index c6b16171311..6b18b0ebe9d 100644 --- a/compiler/rustc_hir_analysis/src/coherence/unsafety.rs +++ b/compiler/rustc_hir_analysis/src/coherence/unsafety.rs @@ -12,7 +12,7 @@ pub(super) fn check_item(tcx: TyCtxt<'_>, def_id: LocalDefId) { let impl_ = item.expect_impl(); if let Some(trait_ref) = tcx.impl_trait_ref(item.owner_id) { - let trait_ref = trait_ref.subst_identity(); + let trait_ref = trait_ref.instantiate_identity(); let trait_def = tcx.trait_def(trait_ref.def_id); let unsafe_attr = impl_.generics.params.iter().find(|p| p.pure_wrt_drop).map(|_| "may_dangle"); diff --git a/compiler/rustc_hir_analysis/src/collect.rs b/compiler/rustc_hir_analysis/src/collect.rs index f47df4f215b..c160cf2df6e 100644 --- a/compiler/rustc_hir_analysis/src/collect.rs +++ b/compiler/rustc_hir_analysis/src/collect.rs @@ -401,13 +401,13 @@ impl<'tcx> AstConv<'tcx> for ItemCtxt<'tcx> { poly_trait_ref: ty::PolyTraitRef<'tcx>, ) -> Ty<'tcx> { if let Some(trait_ref) = poly_trait_ref.no_bound_vars() { - let item_substs = self.astconv().create_substs_for_associated_item( + let item_args = self.astconv().create_args_for_associated_item( span, item_def_id, item_segment, - trait_ref.substs, + trait_ref.args, ); - Ty::new_projection(self.tcx(), item_def_id, item_substs) + Ty::new_projection(self.tcx(), item_def_id, item_args) } else { // There are no late-bound regions; we can just ignore the binder. let (mut mpart_sugg, mut inferred_sugg) = (None, None); @@ -1145,8 +1145,8 @@ fn fn_sig(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::EarlyBinder<ty::PolyFnSig< } Ctor(data) | Variant(hir::Variant { data, .. }) if data.ctor().is_some() => { - let ty = tcx.type_of(tcx.hir().get_parent_item(hir_id)).subst_identity(); - let inputs = data.fields().iter().map(|f| tcx.type_of(f.def_id).subst_identity()); + let ty = tcx.type_of(tcx.hir().get_parent_item(hir_id)).instantiate_identity(); + let inputs = data.fields().iter().map(|f| tcx.type_of(f.def_id).instantiate_identity()); ty::Binder::dummy(tcx.mk_fn_sig( inputs, ty, @@ -1161,15 +1161,13 @@ fn fn_sig(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::EarlyBinder<ty::PolyFnSig< // signatures and cannot be accessed through `fn_sig`. For // example, a closure signature excludes the `self` // argument. In any case they are embedded within the - // closure type as part of the `ClosureSubsts`. + // closure type as part of the `ClosureArgs`. // // To get the signature of a closure, you should use the - // `sig` method on the `ClosureSubsts`: + // `sig` method on the `ClosureArgs`: // - // substs.as_closure().sig(def_id, tcx) - bug!( - "to get the signature of a closure, use `substs.as_closure().sig()` not `fn_sig()`", - ); + // args.as_closure().sig(def_id, tcx) + bug!("to get the signature of a closure, use `args.as_closure().sig()` not `fn_sig()`",); } x => { @@ -1266,7 +1264,7 @@ fn suggest_impl_trait<'tcx>( ) -> Option<String> { let format_as_assoc: fn(_, _, _, _, _) -> _ = |tcx: TyCtxt<'tcx>, - _: ty::SubstsRef<'tcx>, + _: ty::GenericArgsRef<'tcx>, trait_def_id: DefId, assoc_item_def_id: DefId, item_ty: Ty<'tcx>| { @@ -1276,13 +1274,15 @@ fn suggest_impl_trait<'tcx>( }; let format_as_parenthesized: fn(_, _, _, _, _) -> _ = |tcx: TyCtxt<'tcx>, - substs: ty::SubstsRef<'tcx>, + args: ty::GenericArgsRef<'tcx>, trait_def_id: DefId, _: DefId, item_ty: Ty<'tcx>| { let trait_name = tcx.item_name(trait_def_id); - let args_tuple = substs.type_at(1); - let ty::Tuple(types) = *args_tuple.kind() else { return None; }; + let args_tuple = args.type_at(1); + let ty::Tuple(types) = *args_tuple.kind() else { + return None; + }; let types = types.make_suggestable(tcx, false)?; let maybe_ret = if item_ty.is_unit() { String::new() } else { format!(" -> {item_ty}") }; @@ -1315,31 +1315,34 @@ fn suggest_impl_trait<'tcx>( format_as_parenthesized, ), ] { - let Some(trait_def_id) = trait_def_id else { continue; }; - let Some(assoc_item_def_id) = assoc_item_def_id else { continue; }; + let Some(trait_def_id) = trait_def_id else { + continue; + }; + let Some(assoc_item_def_id) = assoc_item_def_id else { + continue; + }; if tcx.def_kind(assoc_item_def_id) != DefKind::AssocTy { continue; } let param_env = tcx.param_env(def_id); let infcx = tcx.infer_ctxt().build(); - let substs = ty::InternalSubsts::for_item(tcx, trait_def_id, |param, _| { + let args = ty::GenericArgs::for_item(tcx, trait_def_id, |param, _| { if param.index == 0 { ret_ty.into() } else { infcx.var_for_def(span, param) } }); - if !infcx.type_implements_trait(trait_def_id, substs, param_env).must_apply_modulo_regions() - { + if !infcx.type_implements_trait(trait_def_id, args, param_env).must_apply_modulo_regions() { continue; } let ocx = ObligationCtxt::new(&infcx); let item_ty = ocx.normalize( &ObligationCause::misc(span, def_id), param_env, - Ty::new_projection(tcx, assoc_item_def_id, substs), + Ty::new_projection(tcx, assoc_item_def_id, args), ); // FIXME(compiler-errors): We may benefit from resolving regions here. if ocx.select_where_possible().is_empty() && let item_ty = infcx.resolve_vars_if_possible(item_ty) && let Some(item_ty) = item_ty.make_suggestable(tcx, false) - && let Some(sugg) = formatter(tcx, infcx.resolve_vars_if_possible(substs), trait_def_id, assoc_item_def_id, item_ty) + && let Some(sugg) = formatter(tcx, infcx.resolve_vars_if_possible(args), trait_def_id, assoc_item_def_id, item_ty) { return Some(sugg); } @@ -1357,7 +1360,7 @@ fn impl_trait_ref( .of_trait .as_ref() .map(|ast_trait_ref| { - let selfty = tcx.type_of(def_id).subst_identity(); + let selfty = tcx.type_of(def_id).instantiate_identity(); icx.astconv().instantiate_mono_trait_ref( ast_trait_ref, selfty, diff --git a/compiler/rustc_hir_analysis/src/collect/generics_of.rs b/compiler/rustc_hir_analysis/src/collect/generics_of.rs index ccc9f808411..edcb9527fe2 100644 --- a/compiler/rustc_hir_analysis/src/collect/generics_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/generics_of.rs @@ -68,17 +68,17 @@ pub(super) fn generics_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Generics { // ^ parent_def_id // // then we only want to return generics for params to the left of `N`. If we don't do that we - // end up with that const looking like: `ty::ConstKind::Unevaluated(def_id, substs: [N#0])`. + // end up with that const looking like: `ty::ConstKind::Unevaluated(def_id, args: [N#0])`. // - // This causes ICEs (#86580) when building the substs for Foo in `fn foo() -> Foo { .. }` as - // we substitute the defaults with the partially built substs when we build the substs. Subst'ing - // the `N#0` on the unevaluated const indexes into the empty substs we're in the process of building. + // This causes ICEs (#86580) when building the args for Foo in `fn foo() -> Foo { .. }` as + // we substitute the defaults with the partially built args when we build the args. Subst'ing + // the `N#0` on the unevaluated const indexes into the empty args we're in the process of building. // // We fix this by having this function return the parent's generics ourselves and truncating the // generics to only include non-forward declared params (with the exception of the `Self` ty) // - // For the above code example that means we want `substs: []` - // For the following struct def we want `substs: [N#0]` when generics_of is called on + // For the above code example that means we want `args: []` + // For the following struct def we want `args: [N#0]` when generics_of is called on // the def id of the `{ N + 1 }` anon const // struct Foo<const N: usize, const M: usize = { N + 1 }>; // @@ -93,7 +93,7 @@ pub(super) fn generics_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Generics { return ty::Generics { // we set the parent of these generics to be our parent's parent so that we - // dont end up with substs: [N, M, N] for the const default on a struct like this: + // dont end up with args: [N, M, N] for the const default on a struct like this: // struct Foo<const N: usize, const M: usize = { ... }>; parent: generics.parent, parent_count: generics.parent_count, diff --git a/compiler/rustc_hir_analysis/src/collect/item_bounds.rs b/compiler/rustc_hir_analysis/src/collect/item_bounds.rs index d6f33869a03..758e9dc7230 100644 --- a/compiler/rustc_hir_analysis/src/collect/item_bounds.rs +++ b/compiler/rustc_hir_analysis/src/collect/item_bounds.rs @@ -2,7 +2,7 @@ use super::ItemCtxt; use crate::astconv::{AstConv, PredicateFilter}; use rustc_hir as hir; use rustc_infer::traits::util; -use rustc_middle::ty::subst::InternalSubsts; +use rustc_middle::ty::GenericArgs; use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_span::def_id::{DefId, LocalDefId}; use rustc_span::Span; @@ -10,7 +10,7 @@ use rustc_span::Span; /// For associated types we include both bounds written on the type /// (`type X: Trait`) and predicates from the trait: `where Self::X: Trait`. /// -/// Note that this filtering is done with the items identity substs to +/// Note that this filtering is done with the items identity args to /// simplify checking that these bounds are met in impls. This means that /// a bound such as `for<'b> <Self as X<'b>>::U: Clone` can't be used, as in /// `hr-associated-type-bound-1.rs`. @@ -23,7 +23,7 @@ fn associated_type_bounds<'tcx>( let item_ty = Ty::new_projection( tcx, assoc_item_def_id.to_def_id(), - InternalSubsts::identity_for_item(tcx, assoc_item_def_id), + GenericArgs::identity_for_item(tcx, assoc_item_def_id), ); let icx = ItemCtxt::new(tcx, assoc_item_def_id); @@ -95,7 +95,7 @@ pub(super) fn explicit_item_bounds( Ty::new_projection( tcx, def_id.to_def_id(), - ty::InternalSubsts::identity_for_item(tcx, def_id), + ty::GenericArgs::identity_for_item(tcx, def_id), ), item.span, )); @@ -117,8 +117,8 @@ pub(super) fn explicit_item_bounds( span, .. }) => { - let substs = InternalSubsts::identity_for_item(tcx, def_id); - let item_ty = Ty::new_opaque(tcx, def_id.to_def_id(), substs); + let args = GenericArgs::identity_for_item(tcx, def_id); + let item_ty = Ty::new_opaque(tcx, def_id.to_def_id(), args); opaque_type_bounds(tcx, def_id, bounds, item_ty, *span) } hir::Node::Item(hir::Item { kind: hir::ItemKind::TyAlias(..), .. }) => &[], diff --git a/compiler/rustc_hir_analysis/src/collect/predicates_of.rs b/compiler/rustc_hir_analysis/src/collect/predicates_of.rs index 12936664130..1c9070600db 100644 --- a/compiler/rustc_hir_analysis/src/collect/predicates_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/predicates_of.rs @@ -8,7 +8,6 @@ use rustc_hir as hir; use rustc_hir::def::DefKind; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::intravisit::{self, Visitor}; -use rustc_middle::ty::subst::InternalSubsts; use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_middle::ty::{GenericPredicates, Generics, ImplTraitInTraitData, ToPredicate}; use rustc_span::symbol::{sym, Ident}; @@ -66,7 +65,11 @@ fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Gen Some(ImplTraitInTraitData::Trait { opaque_def_id, fn_def_id }) => { let opaque_ty_id = tcx.hir().local_def_id_to_hir_id(opaque_def_id.expect_local()); let opaque_ty_node = tcx.hir().get(opaque_ty_id); - let Node::Item(&Item { kind: ItemKind::OpaqueTy(OpaqueTy { lifetime_mapping, .. }), .. }) = opaque_ty_node else { + let Node::Item(&Item { + kind: ItemKind::OpaqueTy(OpaqueTy { lifetime_mapping, .. }), + .. + }) = opaque_ty_node + else { bug!("unexpected {opaque_ty_node:?}") }; @@ -76,10 +79,9 @@ fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Gen // both to ensure that the RPITITs are only instantiated when the // parent predicates would hold, and also so that the param-env // inherits these predicates as assumptions. - let identity_substs = InternalSubsts::identity_for_item(tcx, def_id); - predicates.extend( - tcx.explicit_predicates_of(fn_def_id).instantiate_own(tcx, identity_substs), - ); + let identity_args = ty::GenericArgs::identity_for_item(tcx, def_id); + predicates + .extend(tcx.explicit_predicates_of(fn_def_id).instantiate_own(tcx, identity_args)); // We also install bidirectional outlives predicates for the RPITIT // to keep the duplicates lifetimes from opaque lowering in sync. @@ -104,15 +106,15 @@ fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Gen let trait_assoc_predicates = tcx.explicit_predicates_of(assoc_item.trait_item_def_id.unwrap()); - let impl_assoc_identity_substs = InternalSubsts::identity_for_item(tcx, def_id); + let impl_assoc_identity_args = ty::GenericArgs::identity_for_item(tcx, def_id); let impl_def_id = tcx.parent(fn_def_id); - let impl_trait_ref_substs = - tcx.impl_trait_ref(impl_def_id).unwrap().subst_identity().substs; + let impl_trait_ref_args = + tcx.impl_trait_ref(impl_def_id).unwrap().instantiate_identity().args; - let impl_assoc_substs = - impl_assoc_identity_substs.rebase_onto(tcx, impl_def_id, impl_trait_ref_substs); + let impl_assoc_args = + impl_assoc_identity_args.rebase_onto(tcx, impl_def_id, impl_trait_ref_args); - let impl_predicates = trait_assoc_predicates.instantiate_own(tcx, impl_assoc_substs); + let impl_predicates = trait_assoc_predicates.instantiate_own(tcx, impl_assoc_args); return ty::GenericPredicates { parent: Some(impl_def_id), @@ -146,8 +148,9 @@ fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Gen Node::Item(item) => match item.kind { ItemKind::Impl(impl_) => { if impl_.defaultness.is_default() { - is_default_impl_trait = - tcx.impl_trait_ref(def_id).map(|t| ty::Binder::dummy(t.subst_identity())); + is_default_impl_trait = tcx + .impl_trait_ref(def_id) + .map(|t| ty::Binder::dummy(t.instantiate_identity())); } impl_.generics } @@ -333,8 +336,8 @@ fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Gen // in trait checking. See `setup_constraining_predicates` // for details. if let Node::Item(&Item { kind: ItemKind::Impl { .. }, .. }) = node { - let self_ty = tcx.type_of(def_id).subst_identity(); - let trait_ref = tcx.impl_trait_ref(def_id).map(ty::EarlyBinder::subst_identity); + let self_ty = tcx.type_of(def_id).instantiate_identity(); + let trait_ref = tcx.impl_trait_ref(def_id).map(ty::EarlyBinder::instantiate_identity); cgp::setup_constraining_predicates( tcx, &mut predicates, @@ -393,11 +396,13 @@ fn compute_bidirectional_outlives_predicates<'tcx>( let orig_region = icx.astconv().ast_region_to_region(&arg, None); if !matches!(orig_region.kind(), ty::ReEarlyBound(..)) { // There is no late-bound lifetime to actually match up here, since the lifetime doesn't - // show up in the opaque's parent's substs. + // show up in the opaque's parent's args. continue; } - let Some(dup_index) = generics.param_def_id_to_index(icx.tcx, dup_def.to_def_id()) else { bug!() }; + let Some(dup_index) = generics.param_def_id_to_index(icx.tcx, dup_def.to_def_id()) else { + bug!() + }; let dup_region = ty::Region::new_early_bound( tcx, @@ -493,20 +498,20 @@ pub(super) fn explicit_predicates_of<'tcx>( // Remove bounds on associated types from the predicates, they will be // returned by `explicit_item_bounds`. let predicates_and_bounds = tcx.trait_explicit_predicates_and_bounds(def_id); - let trait_identity_substs = InternalSubsts::identity_for_item(tcx, def_id); + let trait_identity_args = ty::GenericArgs::identity_for_item(tcx, def_id); let is_assoc_item_ty = |ty: Ty<'tcx>| { // For a predicate from a where clause to become a bound on an // associated type: - // * It must use the identity substs of the item. + // * It must use the identity args of the item. // * We're in the scope of the trait, so we can't name any // parameters of the GAT. That means that all we need to - // check are that the substs of the projection are the - // identity substs of the trait. + // check are that the args of the projection are the + // identity args of the trait. // * It must be an associated type for this trait (*not* a // supertrait). if let ty::Alias(ty::Projection, projection) = ty.kind() { - projection.substs == trait_identity_substs + projection.args == trait_identity_args // FIXME(return_type_notation): This check should be more robust && !tcx.is_impl_trait_in_trait(projection.def_id) && tcx.associated_item(projection.def_id).container_id(tcx) diff --git a/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs index acd0bcd8e5c..44f116ef2da 100644 --- a/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs +++ b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs @@ -749,9 +749,7 @@ impl<'a, 'tcx> Visitor<'tcx> for BoundVarContext<'a, 'tcx> { // `fn foo<'a>() -> MyAnonTy<'a> { ... }` // ^ ^this gets resolved in the current scope for lifetime in lifetimes { - let hir::GenericArg::Lifetime(lifetime) = lifetime else { - continue - }; + let hir::GenericArg::Lifetime(lifetime) = lifetime else { continue }; self.visit_lifetime(lifetime); // Check for predicates like `impl for<'a> Trait<impl OtherTrait<'a>>` @@ -759,12 +757,8 @@ impl<'a, 'tcx> Visitor<'tcx> for BoundVarContext<'a, 'tcx> { // well-supported at the moment, so this doesn't work. // In the future, this should be fixed and this error should be removed. let def = self.map.defs.get(&lifetime.hir_id).cloned(); - let Some(ResolvedArg::LateBound(_, _, def_id)) = def else { - continue - }; - let Some(def_id) = def_id.as_local() else { - continue - }; + let Some(ResolvedArg::LateBound(_, _, def_id)) = def else { continue }; + let Some(def_id) = def_id.as_local() else { continue }; let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id); // Ensure that the parent of the def is an item, not HRTB let parent_id = self.tcx.hir().parent_id(hir_id); @@ -1727,7 +1721,7 @@ impl<'a, 'tcx> BoundVarContext<'a, 'tcx> { }, )); bound_vars - .extend(self.tcx.fn_sig(assoc_fn.def_id).subst_identity().bound_vars()); + .extend(self.tcx.fn_sig(assoc_fn.def_id).instantiate_identity().bound_vars()); bound_vars } else { self.tcx.sess.delay_span_bug( @@ -2044,12 +2038,12 @@ fn is_late_bound_map( hir::Path { res: Res::Def(DefKind::TyAlias, alias_def), segments, span }, )) => { // See comments on `ConstrainedCollectorPostAstConv` for why this arm does not just consider - // substs to be unconstrained. + // args to be unconstrained. let generics = self.tcx.generics_of(alias_def); let mut walker = ConstrainedCollectorPostAstConv { arg_is_constrained: vec![false; generics.params.len()].into_boxed_slice(), }; - walker.visit_ty(self.tcx.type_of(alias_def).subst_identity()); + walker.visit_ty(self.tcx.type_of(alias_def).instantiate_identity()); match segments.last() { Some(hir::PathSegment { args: Some(args), .. }) => { diff --git a/compiler/rustc_hir_analysis/src/collect/type_of.rs b/compiler/rustc_hir_analysis/src/collect/type_of.rs index 3755342aef5..c39edaa1577 100644 --- a/compiler/rustc_hir_analysis/src/collect/type_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/type_of.rs @@ -3,7 +3,6 @@ use rustc_hir as hir; use rustc_hir::def_id::LocalDefId; use rustc_hir::HirId; use rustc_middle::ty::print::with_forced_trimmed_paths; -use rustc_middle::ty::subst::InternalSubsts; use rustc_middle::ty::util::IntTypeExt; use rustc_middle::ty::{self, ImplTraitInTraitData, IsSuggestable, Ty, TyCtxt, TypeVisitableExt}; use rustc_span::symbol::Ident; @@ -338,8 +337,8 @@ pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::EarlyBinder<Ty let output = match tcx.hir().get(hir_id) { Node::TraitItem(item) => match item.kind { TraitItemKind::Fn(..) => { - let substs = InternalSubsts::identity_for_item(tcx, def_id); - Ty::new_fn_def(tcx, def_id.to_def_id(), substs) + let args = ty::GenericArgs::identity_for_item(tcx, def_id); + Ty::new_fn_def(tcx, def_id.to_def_id(), args) } TraitItemKind::Const(ty, body_id) => body_id .and_then(|body_id| { @@ -363,8 +362,8 @@ pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::EarlyBinder<Ty Node::ImplItem(item) => match item.kind { ImplItemKind::Fn(..) => { - let substs = InternalSubsts::identity_for_item(tcx, def_id); - Ty::new_fn_def(tcx, def_id.to_def_id(), substs) + let args = ty::GenericArgs::identity_for_item(tcx, def_id); + Ty::new_fn_def(tcx, def_id.to_def_id(), args) } ImplItemKind::Const(ty, body_id) => { if is_suggestable_infer_ty(ty) { @@ -426,13 +425,13 @@ pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::EarlyBinder<Ty _ => icx.to_ty(*self_ty), }, ItemKind::Fn(..) => { - let substs = InternalSubsts::identity_for_item(tcx, def_id); - Ty::new_fn_def(tcx, def_id.to_def_id(), substs) + let args = ty::GenericArgs::identity_for_item(tcx, def_id); + Ty::new_fn_def(tcx, def_id.to_def_id(), args) } ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) => { let def = tcx.adt_def(def_id); - let substs = InternalSubsts::identity_for_item(tcx, def_id); - Ty::new_adt(tcx, def, substs) + let args = ty::GenericArgs::identity_for_item(tcx, def_id); + Ty::new_adt(tcx, def, args) } ItemKind::OpaqueTy(OpaqueTy { origin: hir::OpaqueTyOrigin::TyAlias { .. }, @@ -472,8 +471,8 @@ pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::EarlyBinder<Ty Node::ForeignItem(foreign_item) => match foreign_item.kind { ForeignItemKind::Fn(..) => { - let substs = InternalSubsts::identity_for_item(tcx, def_id); - Ty::new_fn_def(tcx, def_id.to_def_id(), substs) + let args = ty::GenericArgs::identity_for_item(tcx, def_id); + Ty::new_fn_def(tcx, def_id.to_def_id(), args) } ForeignItemKind::Static(t, _) => icx.to_ty(t), ForeignItemKind::Type => Ty::new_foreign(tcx, def_id.to_def_id()), @@ -481,11 +480,11 @@ pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::EarlyBinder<Ty Node::Ctor(def) | Node::Variant(Variant { data: def, .. }) => match def { VariantData::Unit(..) | VariantData::Struct(..) => { - tcx.type_of(tcx.hir().get_parent_item(hir_id)).subst_identity() + tcx.type_of(tcx.hir().get_parent_item(hir_id)).instantiate_identity() } VariantData::Tuple(..) => { - let substs = InternalSubsts::identity_for_item(tcx, def_id); - Ty::new_fn_def(tcx, def_id.to_def_id(), substs) + let args = ty::GenericArgs::identity_for_item(tcx, def_id); + Ty::new_fn_def(tcx, def_id.to_def_id(), args) } }, @@ -498,8 +497,8 @@ pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::EarlyBinder<Ty Node::AnonConst(_) => anon_const_type_of(tcx, def_id), Node::ConstBlock(_) => { - let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id()); - substs.as_inline_const().ty() + let args = ty::GenericArgs::identity_for_item(tcx, def_id.to_def_id()); + args.as_inline_const().ty() } Node::GenericParam(param) => match ¶m.kind { diff --git a/compiler/rustc_hir_analysis/src/impl_wf_check.rs b/compiler/rustc_hir_analysis/src/impl_wf_check.rs index d654b0be620..62f22bda9f9 100644 --- a/compiler/rustc_hir_analysis/src/impl_wf_check.rs +++ b/compiler/rustc_hir_analysis/src/impl_wf_check.rs @@ -70,7 +70,7 @@ pub fn provide(providers: &mut Providers) { fn enforce_impl_params_are_constrained(tcx: TyCtxt<'_>, impl_def_id: LocalDefId) { // Every lifetime used in an associated type must be constrained. - let impl_self_ty = tcx.type_of(impl_def_id).subst_identity(); + let impl_self_ty = tcx.type_of(impl_def_id).instantiate_identity(); if impl_self_ty.references_error() { // Don't complain about unconstrained type params when self ty isn't known due to errors. // (#36836) @@ -85,7 +85,7 @@ fn enforce_impl_params_are_constrained(tcx: TyCtxt<'_>, impl_def_id: LocalDefId) } let impl_generics = tcx.generics_of(impl_def_id); let impl_predicates = tcx.predicates_of(impl_def_id); - let impl_trait_ref = tcx.impl_trait_ref(impl_def_id).map(ty::EarlyBinder::subst_identity); + let impl_trait_ref = tcx.impl_trait_ref(impl_def_id).map(ty::EarlyBinder::instantiate_identity); let mut input_parameters = cgp::parameters_for_impl(impl_self_ty, impl_trait_ref); cgp::identify_constrained_generic_params( @@ -104,7 +104,7 @@ fn enforce_impl_params_are_constrained(tcx: TyCtxt<'_>, impl_def_id: LocalDefId) match item.kind { ty::AssocKind::Type => { if item.defaultness(tcx).has_value() { - cgp::parameters_for(&tcx.type_of(def_id).subst_identity(), true) + cgp::parameters_for(&tcx.type_of(def_id).instantiate_identity(), true) } else { vec![] } diff --git a/compiler/rustc_hir_analysis/src/impl_wf_check/min_specialization.rs b/compiler/rustc_hir_analysis/src/impl_wf_check/min_specialization.rs index c64fb469bb2..81993789bcf 100644 --- a/compiler/rustc_hir_analysis/src/impl_wf_check/min_specialization.rs +++ b/compiler/rustc_hir_analysis/src/impl_wf_check/min_specialization.rs @@ -14,15 +14,15 @@ //! To enforce this requirement on specializations we take the following //! approach: //! -//! 1. Match up the substs for `impl2` so that the implemented trait and +//! 1. Match up the args for `impl2` so that the implemented trait and //! self-type match those for `impl1`. -//! 2. Check for any direct use of `'static` in the substs of `impl2`. +//! 2. Check for any direct use of `'static` in the args of `impl2`. //! 3. Check that all of the generic parameters of `impl1` occur at most once -//! in the *unconstrained* substs for `impl2`. A parameter is constrained if +//! in the *unconstrained* args for `impl2`. A parameter is constrained if //! its value is completely determined by an associated type projection //! predicate. //! 4. Check that all predicates on `impl1` either exist on `impl2` (after -//! matching substs), or are well-formed predicates for the trait's type +//! matching args), or are well-formed predicates for the trait's type //! arguments. //! //! ## Example @@ -74,13 +74,13 @@ use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_infer::infer::outlives::env::OutlivesEnvironment; use rustc_infer::infer::TyCtxtInferExt; use rustc_infer::traits::specialization_graph::Node; -use rustc_middle::ty::subst::{GenericArg, InternalSubsts, SubstsRef}; use rustc_middle::ty::trait_def::TraitSpecializationKind; use rustc_middle::ty::{self, TyCtxt, TypeVisitableExt}; +use rustc_middle::ty::{GenericArg, GenericArgs, GenericArgsRef}; use rustc_span::{ErrorGuaranteed, Span}; use rustc_trait_selection::traits::error_reporting::TypeErrCtxtExt; use rustc_trait_selection::traits::outlives_bounds::InferCtxtExt as _; -use rustc_trait_selection::traits::{self, translate_substs_with_cause, wf, ObligationCtxt}; +use rustc_trait_selection::traits::{self, translate_args_with_cause, wf, ObligationCtxt}; pub(super) fn check_min_specialization(tcx: TyCtxt<'_>, impl_def_id: LocalDefId) { if let Some(node) = parent_specialization_node(tcx, impl_def_id) { @@ -113,20 +113,20 @@ fn check_always_applicable(tcx: TyCtxt<'_>, impl1_def_id: LocalDefId, impl2_node let span = tcx.def_span(impl1_def_id); check_has_items(tcx, impl1_def_id, impl2_node, span); - if let Ok((impl1_substs, impl2_substs)) = get_impl_substs(tcx, impl1_def_id, impl2_node) { + if let Ok((impl1_args, impl2_args)) = get_impl_args(tcx, impl1_def_id, impl2_node) { let impl2_def_id = impl2_node.def_id(); - debug!(?impl2_def_id, ?impl2_substs); + debug!(?impl2_def_id, ?impl2_args); - let parent_substs = if impl2_node.is_from_trait() { - impl2_substs.to_vec() + let parent_args = if impl2_node.is_from_trait() { + impl2_args.to_vec() } else { - unconstrained_parent_impl_substs(tcx, impl2_def_id, impl2_substs) + unconstrained_parent_impl_args(tcx, impl2_def_id, impl2_args) }; check_constness(tcx, impl1_def_id, impl2_node, span); - check_static_lifetimes(tcx, &parent_substs, span); - check_duplicate_params(tcx, impl1_substs, &parent_substs, span); - check_predicates(tcx, impl1_def_id, impl1_substs, impl2_node, impl2_substs, span); + check_static_lifetimes(tcx, &parent_args, span); + check_duplicate_params(tcx, impl1_args, &parent_args, span); + check_predicates(tcx, impl1_def_id, impl1_args, impl2_node, impl2_args, span); } } @@ -167,23 +167,23 @@ fn check_constness(tcx: TyCtxt<'_>, impl1_def_id: LocalDefId, impl2_node: Node, /// ``` /// /// Would return `S1 = [C]` and `S2 = [Vec<C>, C]`. -fn get_impl_substs( +fn get_impl_args( tcx: TyCtxt<'_>, impl1_def_id: LocalDefId, impl2_node: Node, -) -> Result<(SubstsRef<'_>, SubstsRef<'_>), ErrorGuaranteed> { +) -> Result<(GenericArgsRef<'_>, GenericArgsRef<'_>), ErrorGuaranteed> { let infcx = &tcx.infer_ctxt().build(); let ocx = ObligationCtxt::new(infcx); let param_env = tcx.param_env(impl1_def_id); let impl1_span = tcx.def_span(impl1_def_id); let assumed_wf_types = ocx.assumed_wf_types_and_report_errors(param_env, impl1_def_id)?; - let impl1_substs = InternalSubsts::identity_for_item(tcx, impl1_def_id); - let impl2_substs = translate_substs_with_cause( + let impl1_args = GenericArgs::identity_for_item(tcx, impl1_def_id); + let impl2_args = translate_args_with_cause( infcx, param_env, impl1_def_id.to_def_id(), - impl1_substs, + impl1_args, impl2_node, |_, span| { traits::ObligationCause::new( @@ -203,12 +203,12 @@ fn get_impl_substs( let implied_bounds = infcx.implied_bounds_tys(param_env, impl1_def_id, assumed_wf_types); let outlives_env = OutlivesEnvironment::with_bounds(param_env, implied_bounds); let _ = ocx.resolve_regions_and_report_errors(impl1_def_id, &outlives_env); - let Ok(impl2_substs) = infcx.fully_resolve(impl2_substs) else { + let Ok(impl2_args) = infcx.fully_resolve(impl2_args) else { let span = tcx.def_span(impl1_def_id); let guar = tcx.sess.emit_err(SubstsOnOverriddenImpl { span }); return Err(guar); }; - Ok((impl1_substs, impl2_substs)) + Ok((impl1_args, impl2_args)) } /// Returns a list of all of the unconstrained subst of the given impl. @@ -217,17 +217,17 @@ fn get_impl_substs( /// /// impl<'a, T, I> ... where &'a I: IntoIterator<Item=&'a T> /// -/// This would return the substs corresponding to `['a, I]`, because knowing +/// This would return the args corresponding to `['a, I]`, because knowing /// `'a` and `I` determines the value of `T`. -fn unconstrained_parent_impl_substs<'tcx>( +fn unconstrained_parent_impl_args<'tcx>( tcx: TyCtxt<'tcx>, impl_def_id: DefId, - impl_substs: SubstsRef<'tcx>, + impl_args: GenericArgsRef<'tcx>, ) -> Vec<GenericArg<'tcx>> { let impl_generic_predicates = tcx.predicates_of(impl_def_id); let mut unconstrained_parameters = FxHashSet::default(); let mut constrained_params = FxHashSet::default(); - let impl_trait_ref = tcx.impl_trait_ref(impl_def_id).map(ty::EarlyBinder::subst_identity); + let impl_trait_ref = tcx.impl_trait_ref(impl_def_id).map(ty::EarlyBinder::instantiate_identity); // Unfortunately the functions in `constrained_generic_parameters` don't do // what we want here. We want only a list of constrained parameters while @@ -255,7 +255,7 @@ fn unconstrained_parent_impl_substs<'tcx>( } } - impl_substs + impl_args .iter() .enumerate() .filter(|&(idx, _)| !constrained_params.contains(&(idx as u32))) @@ -264,7 +264,7 @@ fn unconstrained_parent_impl_substs<'tcx>( } /// Check that parameters of the derived impl don't occur more than once in the -/// equated substs of the base impl. +/// equated args of the base impl. /// /// For example forbid the following: /// @@ -280,19 +280,19 @@ fn unconstrained_parent_impl_substs<'tcx>( /// impl<T> Tr<T> for Vec<T> { } /// ``` /// -/// The substs for the parent impl here are `[T, Vec<T>]`, which repeats `T`, -/// but `S` is constrained in the parent impl, so `parent_substs` is only +/// The args for the parent impl here are `[T, Vec<T>]`, which repeats `T`, +/// but `S` is constrained in the parent impl, so `parent_args` is only /// `[Vec<T>]`. This means we allow this impl. fn check_duplicate_params<'tcx>( tcx: TyCtxt<'tcx>, - impl1_substs: SubstsRef<'tcx>, - parent_substs: &Vec<GenericArg<'tcx>>, + impl1_args: GenericArgsRef<'tcx>, + parent_args: &Vec<GenericArg<'tcx>>, span: Span, ) { - let mut base_params = cgp::parameters_for(parent_substs, true); + let mut base_params = cgp::parameters_for(parent_args, true); base_params.sort_by_key(|param| param.0); if let (_, [duplicate, ..]) = base_params.partition_dedup() { - let param = impl1_substs[duplicate.0 as usize]; + let param = impl1_args[duplicate.0 as usize]; tcx.sess .struct_span_err(span, format!("specializing impl repeats parameter `{}`", param)) .emit(); @@ -309,10 +309,10 @@ fn check_duplicate_params<'tcx>( /// ``` fn check_static_lifetimes<'tcx>( tcx: TyCtxt<'tcx>, - parent_substs: &Vec<GenericArg<'tcx>>, + parent_args: &Vec<GenericArg<'tcx>>, span: Span, ) { - if tcx.any_free_region_meets(parent_substs, |r| r.is_static()) { + if tcx.any_free_region_meets(parent_args, |r| r.is_static()) { tcx.sess.emit_err(errors::StaticSpecialize { span }); } } @@ -331,14 +331,14 @@ fn check_static_lifetimes<'tcx>( fn check_predicates<'tcx>( tcx: TyCtxt<'tcx>, impl1_def_id: LocalDefId, - impl1_substs: SubstsRef<'tcx>, + impl1_args: GenericArgsRef<'tcx>, impl2_node: Node, - impl2_substs: SubstsRef<'tcx>, + impl2_args: GenericArgsRef<'tcx>, span: Span, ) { let impl1_predicates: Vec<_> = traits::elaborate( tcx, - tcx.predicates_of(impl1_def_id).instantiate(tcx, impl1_substs).into_iter(), + tcx.predicates_of(impl1_def_id).instantiate(tcx, impl1_args).into_iter(), ) .collect(); @@ -350,7 +350,7 @@ fn check_predicates<'tcx>( traits::elaborate( tcx, tcx.predicates_of(impl2_node.def_id()) - .instantiate(tcx, impl2_substs) + .instantiate(tcx, impl2_args) .into_iter() .map(|(c, _s)| c.as_predicate()), ) @@ -385,7 +385,7 @@ fn check_predicates<'tcx>( .map(|(c, _span)| c.as_predicate()); // Include the well-formed predicates of the type parameters of the impl. - for arg in tcx.impl_trait_ref(impl1_def_id).unwrap().subst_identity().substs { + for arg in tcx.impl_trait_ref(impl1_def_id).unwrap().instantiate_identity().args { let infcx = &tcx.infer_ctxt().build(); let obligations = wf::obligations(infcx, tcx.param_env(impl1_def_id), impl1_def_id, 0, arg, span) diff --git a/compiler/rustc_hir_analysis/src/lib.rs b/compiler/rustc_hir_analysis/src/lib.rs index a68832d96a6..d7e62457f36 100644 --- a/compiler/rustc_hir_analysis/src/lib.rs +++ b/compiler/rustc_hir_analysis/src/lib.rs @@ -99,23 +99,20 @@ use rustc_errors::ErrorGuaranteed; use rustc_errors::{DiagnosticMessage, SubdiagnosticMessage}; use rustc_fluent_macro::fluent_messages; use rustc_hir as hir; -use rustc_hir::Node; use rustc_infer::infer::TyCtxtInferExt; use rustc_middle::middle; use rustc_middle::query::Providers; use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_middle::util; -use rustc_session::{config::EntryFnType, parse::feature_err}; -use rustc_span::def_id::{DefId, LocalDefId, CRATE_DEF_ID}; +use rustc_session::parse::feature_err; use rustc_span::{symbol::sym, Span, DUMMY_SP}; use rustc_target::spec::abi::Abi; use rustc_trait_selection::traits::error_reporting::TypeErrCtxtExt as _; -use rustc_trait_selection::traits::{self, ObligationCause, ObligationCauseCode, ObligationCtxt}; - -use std::ops::Not; +use rustc_trait_selection::traits::{self, ObligationCause, ObligationCtxt}; use astconv::{AstConv, OnlySelfBounds}; use bounds::Bounds; +use rustc_hir::def::DefKind; fluent_messages! { "../messages.ftl" } @@ -176,267 +173,6 @@ fn require_same_types<'tcx>( } } -fn check_main_fn_ty(tcx: TyCtxt<'_>, main_def_id: DefId) { - let main_fnsig = tcx.fn_sig(main_def_id).subst_identity(); - let main_span = tcx.def_span(main_def_id); - - fn main_fn_diagnostics_def_id(tcx: TyCtxt<'_>, def_id: DefId, sp: Span) -> LocalDefId { - if let Some(local_def_id) = def_id.as_local() { - let hir_type = tcx.type_of(local_def_id).subst_identity(); - if !matches!(hir_type.kind(), ty::FnDef(..)) { - span_bug!(sp, "main has a non-function type: found `{}`", hir_type); - } - local_def_id - } else { - CRATE_DEF_ID - } - } - - fn main_fn_generics_params_span(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Span> { - if !def_id.is_local() { - return None; - } - let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local()); - match tcx.hir().find(hir_id) { - Some(Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, generics, _), .. })) => { - generics.params.is_empty().not().then_some(generics.span) - } - _ => { - span_bug!(tcx.def_span(def_id), "main has a non-function type"); - } - } - } - - fn main_fn_where_clauses_span(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Span> { - if !def_id.is_local() { - return None; - } - let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local()); - match tcx.hir().find(hir_id) { - Some(Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, generics, _), .. })) => { - Some(generics.where_clause_span) - } - _ => { - span_bug!(tcx.def_span(def_id), "main has a non-function type"); - } - } - } - - fn main_fn_asyncness_span(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Span> { - if !def_id.is_local() { - return None; - } - Some(tcx.def_span(def_id)) - } - - fn main_fn_return_type_span(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Span> { - if !def_id.is_local() { - return None; - } - let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local()); - match tcx.hir().find(hir_id) { - Some(Node::Item(hir::Item { kind: hir::ItemKind::Fn(fn_sig, _, _), .. })) => { - Some(fn_sig.decl.output.span()) - } - _ => { - span_bug!(tcx.def_span(def_id), "main has a non-function type"); - } - } - } - - let mut error = false; - let main_diagnostics_def_id = main_fn_diagnostics_def_id(tcx, main_def_id, main_span); - let main_fn_generics = tcx.generics_of(main_def_id); - let main_fn_predicates = tcx.predicates_of(main_def_id); - if main_fn_generics.count() != 0 || !main_fnsig.bound_vars().is_empty() { - let generics_param_span = main_fn_generics_params_span(tcx, main_def_id); - tcx.sess.emit_err(errors::MainFunctionGenericParameters { - span: generics_param_span.unwrap_or(main_span), - label_span: generics_param_span, - }); - error = true; - } else if !main_fn_predicates.predicates.is_empty() { - // generics may bring in implicit predicates, so we skip this check if generics is present. - let generics_where_clauses_span = main_fn_where_clauses_span(tcx, main_def_id); - tcx.sess.emit_err(errors::WhereClauseOnMain { - span: generics_where_clauses_span.unwrap_or(main_span), - generics_span: generics_where_clauses_span, - }); - error = true; - } - - let main_asyncness = tcx.asyncness(main_def_id); - if let hir::IsAsync::Async = main_asyncness { - let asyncness_span = main_fn_asyncness_span(tcx, main_def_id); - tcx.sess.emit_err(errors::MainFunctionAsync { span: main_span, asyncness: asyncness_span }); - error = true; - } - - for attr in tcx.get_attrs(main_def_id, sym::track_caller) { - tcx.sess.emit_err(errors::TrackCallerOnMain { span: attr.span, annotated: main_span }); - error = true; - } - - if !tcx.codegen_fn_attrs(main_def_id).target_features.is_empty() - // Calling functions with `#[target_feature]` is not unsafe on WASM, see #84988 - && !tcx.sess.target.is_like_wasm - && !tcx.sess.opts.actually_rustdoc - { - tcx.sess.emit_err(errors::TargetFeatureOnMain { main: main_span }); - error = true; - } - - if error { - return; - } - - // Main should have no WC, so empty param env is OK here. - let param_env = ty::ParamEnv::empty(); - let expected_return_type; - if let Some(term_did) = tcx.lang_items().termination() { - let return_ty = main_fnsig.output(); - let return_ty_span = main_fn_return_type_span(tcx, main_def_id).unwrap_or(main_span); - if !return_ty.bound_vars().is_empty() { - tcx.sess.emit_err(errors::MainFunctionReturnTypeGeneric { span: return_ty_span }); - error = true; - } - let return_ty = return_ty.skip_binder(); - let infcx = tcx.infer_ctxt().build(); - let cause = traits::ObligationCause::new( - return_ty_span, - main_diagnostics_def_id, - ObligationCauseCode::MainFunctionType, - ); - let ocx = traits::ObligationCtxt::new(&infcx); - let norm_return_ty = ocx.normalize(&cause, param_env, return_ty); - ocx.register_bound(cause, param_env, norm_return_ty, term_did); - let errors = ocx.select_all_or_error(); - if !errors.is_empty() { - infcx.err_ctxt().report_fulfillment_errors(&errors); - error = true; - } - // now we can take the return type of the given main function - expected_return_type = main_fnsig.output(); - } else { - // standard () main return type - expected_return_type = ty::Binder::dummy(Ty::new_unit(tcx)); - } - - if error { - return; - } - - let se_ty = Ty::new_fn_ptr( - tcx, - expected_return_type.map_bound(|expected_return_type| { - tcx.mk_fn_sig([], expected_return_type, false, hir::Unsafety::Normal, Abi::Rust) - }), - ); - - require_same_types( - tcx, - &ObligationCause::new( - main_span, - main_diagnostics_def_id, - ObligationCauseCode::MainFunctionType, - ), - param_env, - se_ty, - Ty::new_fn_ptr(tcx, main_fnsig), - ); -} -fn check_start_fn_ty(tcx: TyCtxt<'_>, start_def_id: DefId) { - let start_def_id = start_def_id.expect_local(); - let start_id = tcx.hir().local_def_id_to_hir_id(start_def_id); - let start_span = tcx.def_span(start_def_id); - let start_t = tcx.type_of(start_def_id).subst_identity(); - match start_t.kind() { - ty::FnDef(..) => { - if let Some(Node::Item(it)) = tcx.hir().find(start_id) { - if let hir::ItemKind::Fn(sig, generics, _) = &it.kind { - let mut error = false; - if !generics.params.is_empty() { - tcx.sess.emit_err(errors::StartFunctionParameters { span: generics.span }); - error = true; - } - if generics.has_where_clause_predicates { - tcx.sess.emit_err(errors::StartFunctionWhere { - span: generics.where_clause_span, - }); - error = true; - } - if let hir::IsAsync::Async = sig.header.asyncness { - let span = tcx.def_span(it.owner_id); - tcx.sess.emit_err(errors::StartAsync { span: span }); - error = true; - } - - let attrs = tcx.hir().attrs(start_id); - for attr in attrs { - if attr.has_name(sym::track_caller) { - tcx.sess.emit_err(errors::StartTrackCaller { - span: attr.span, - start: start_span, - }); - error = true; - } - if attr.has_name(sym::target_feature) - // Calling functions with `#[target_feature]` is - // not unsafe on WASM, see #84988 - && !tcx.sess.target.is_like_wasm - && !tcx.sess.opts.actually_rustdoc - { - tcx.sess.emit_err(errors::StartTargetFeature { - span: attr.span, - start: start_span, - }); - error = true; - } - } - - if error { - return; - } - } - } - - let se_ty = Ty::new_fn_ptr( - tcx, - ty::Binder::dummy(tcx.mk_fn_sig( - [tcx.types.isize, Ty::new_imm_ptr(tcx, Ty::new_imm_ptr(tcx, tcx.types.u8))], - tcx.types.isize, - false, - hir::Unsafety::Normal, - Abi::Rust, - )), - ); - - require_same_types( - tcx, - &ObligationCause::new( - start_span, - start_def_id, - ObligationCauseCode::StartFunctionType, - ), - ty::ParamEnv::empty(), // start should not have any where bounds. - se_ty, - Ty::new_fn_ptr(tcx, tcx.fn_sig(start_def_id).subst_identity()), - ); - } - _ => { - span_bug!(start_span, "start has a non-function type: found `{}`", start_t); - } - } -} - -fn check_for_entry_fn(tcx: TyCtxt<'_>) { - match tcx.entry_fn(()) { - Some((def_id, EntryFnType::Main { .. })) => check_main_fn_ty(tcx, def_id), - Some((def_id, EntryFnType::Start)) => check_start_fn_ty(tcx, def_id), - _ => {} - } -} - pub fn provide(providers: &mut Providers) { collect::provide(providers); coherence::provide(providers); @@ -500,8 +236,18 @@ pub fn check_crate(tcx: TyCtxt<'_>) -> Result<(), ErrorGuaranteed> { tcx.hir().for_each_module(|module| tcx.ensure().check_mod_item_types(module)) }); + // FIXME: Remove this when we implement creating `DefId`s + // for anon constants during their parents' typeck. + // Typeck all body owners in parallel will produce queries + // cycle errors because it may typeck on anon constants directly. + tcx.hir().par_body_owners(|item_def_id| { + let def_kind = tcx.def_kind(item_def_id); + if !matches!(def_kind, DefKind::AnonConst) { + tcx.ensure().typeck(item_def_id); + } + }); + check_unused::check_crate(tcx); - check_for_entry_fn(tcx); if let Some(reported) = tcx.sess.has_errors() { Err(reported) } else { Ok(()) } } diff --git a/compiler/rustc_hir_analysis/src/outlives/implicit_infer.rs b/compiler/rustc_hir_analysis/src/outlives/implicit_infer.rs index 71dca918fc5..c17925471d9 100644 --- a/compiler/rustc_hir_analysis/src/outlives/implicit_infer.rs +++ b/compiler/rustc_hir_analysis/src/outlives/implicit_infer.rs @@ -46,7 +46,7 @@ pub(super) fn infer_predicates( // For field of type &'a T (reference) or Adt // (struct/enum/union) there will be outlive // requirements for adt_def. - let field_ty = tcx.type_of(field_def.did).subst_identity(); + let field_ty = tcx.type_of(field_def.did).instantiate_identity(); let field_span = tcx.def_span(field_def.did); insert_required_predicates_to_be_wf( tcx, @@ -117,7 +117,7 @@ fn insert_required_predicates_to_be_wf<'tcx>( // can load the current set of inferred and explicit // predicates from `global_inferred_outlives` and filter the // ones that are TypeOutlives. - ty::Adt(def, substs) => { + ty::Adt(def, args) => { // First check the inferred predicates // // Example 1: @@ -146,7 +146,7 @@ fn insert_required_predicates_to_be_wf<'tcx>( // get `T: 'a` (or `predicate`): let predicate = unsubstituted_predicates .rebind(*unsubstituted_predicate) - .subst(tcx, substs); + .instantiate(tcx, args); insert_outlives_predicate( tcx, predicate.0, @@ -159,11 +159,11 @@ fn insert_required_predicates_to_be_wf<'tcx>( // Check if the type has any explicit predicates that need // to be added to `required_predicates` - // let _: () = substs.region_at(0); + // let _: () = args.region_at(0); check_explicit_predicates( tcx, def.did(), - substs, + args, required_predicates, explicit_map, None, @@ -186,12 +186,11 @@ fn insert_required_predicates_to_be_wf<'tcx>( // predicates in `check_explicit_predicates` we // need to ignore checking the explicit_map for // Self type. - let substs = - ex_trait_ref.with_self_ty(tcx, tcx.types.usize).skip_binder().substs; + let args = ex_trait_ref.with_self_ty(tcx, tcx.types.usize).skip_binder().args; check_explicit_predicates( tcx, ex_trait_ref.skip_binder().def_id, - substs, + args, required_predicates, explicit_map, Some(tcx.types.self_param), @@ -206,7 +205,7 @@ fn insert_required_predicates_to_be_wf<'tcx>( check_explicit_predicates( tcx, tcx.parent(obj.def_id), - obj.substs, + obj.args, required_predicates, explicit_map, None, @@ -239,18 +238,18 @@ fn insert_required_predicates_to_be_wf<'tcx>( fn check_explicit_predicates<'tcx>( tcx: TyCtxt<'tcx>, def_id: DefId, - substs: &[GenericArg<'tcx>], + args: &[GenericArg<'tcx>], required_predicates: &mut RequiredPredicates<'tcx>, explicit_map: &mut ExplicitPredicatesMap<'tcx>, ignored_self_ty: Option<Ty<'tcx>>, ) { debug!( "check_explicit_predicates(def_id={:?}, \ - substs={:?}, \ + args={:?}, \ explicit_map={:?}, \ required_predicates={:?}, \ ignored_self_ty={:?})", - def_id, substs, explicit_map, required_predicates, ignored_self_ty, + def_id, args, explicit_map, required_predicates, ignored_self_ty, ); let explicit_predicates = explicit_map.explicit_predicates_of(tcx, def_id); @@ -278,10 +277,10 @@ fn check_explicit_predicates<'tcx>( // that is represented by the `dyn Trait`, not to the `X` type parameter // (or any other generic parameter) declared on `MyStruct`. // - // Note that we do this check for self **before** applying `substs`. In the - // case that `substs` come from a `dyn Trait` type, our caller will have + // Note that we do this check for self **before** applying `args`. In the + // case that `args` come from a `dyn Trait` type, our caller will have // included `Self = usize` as the value for `Self`. If we were - // to apply the substs, and not filter this predicate, we might then falsely + // to apply the args, and not filter this predicate, we might then falsely // conclude that e.g., `X: 'x` was a reasonable inferred requirement. // // Another similar case is where we have an inferred @@ -299,7 +298,7 @@ fn check_explicit_predicates<'tcx>( continue; } - let predicate = explicit_predicates.rebind(*outlives_predicate).subst(tcx, substs); + let predicate = explicit_predicates.rebind(*outlives_predicate).instantiate(tcx, args); debug!("predicate = {:?}", &predicate); insert_outlives_predicate(tcx, predicate.0, predicate.1, span, required_predicates); } diff --git a/compiler/rustc_hir_analysis/src/outlives/mod.rs b/compiler/rustc_hir_analysis/src/outlives/mod.rs index 48624cefe4d..be9d076bd6e 100644 --- a/compiler/rustc_hir_analysis/src/outlives/mod.rs +++ b/compiler/rustc_hir_analysis/src/outlives/mod.rs @@ -2,7 +2,7 @@ use hir::Node; use rustc_hir as hir; use rustc_hir::def_id::LocalDefId; use rustc_middle::query::Providers; -use rustc_middle::ty::subst::GenericArgKind; +use rustc_middle::ty::GenericArgKind; use rustc_middle::ty::{self, CratePredicatesMap, ToPredicate, TyCtxt}; use rustc_span::symbol::sym; use rustc_span::Span; diff --git a/compiler/rustc_hir_analysis/src/outlives/utils.rs b/compiler/rustc_hir_analysis/src/outlives/utils.rs index c5c5f63a108..a6410c944f7 100644 --- a/compiler/rustc_hir_analysis/src/outlives/utils.rs +++ b/compiler/rustc_hir_analysis/src/outlives/utils.rs @@ -1,6 +1,6 @@ use rustc_infer::infer::outlives::components::{push_outlives_components, Component}; -use rustc_middle::ty::subst::{GenericArg, GenericArgKind}; use rustc_middle::ty::{self, Region, Ty, TyCtxt}; +use rustc_middle::ty::{GenericArg, GenericArgKind}; use rustc_span::Span; use smallvec::smallvec; use std::collections::BTreeMap; diff --git a/compiler/rustc_hir_analysis/src/structured_errors/wrong_number_of_generic_args.rs b/compiler/rustc_hir_analysis/src/structured_errors/wrong_number_of_generic_args.rs index ee3457282d3..0828fe9e0f2 100644 --- a/compiler/rustc_hir_analysis/src/structured_errors/wrong_number_of_generic_args.rs +++ b/compiler/rustc_hir_analysis/src/structured_errors/wrong_number_of_generic_args.rs @@ -360,9 +360,11 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> { &[] }; ret.extend(params.iter().filter_map(|p| { - let hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Explicit } - = p.kind - else { return None }; + let hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Explicit } = + p.kind + else { + return None; + }; let hir::ParamName::Plain(name) = p.name else { return None }; Some(name.to_string()) })); @@ -793,29 +795,36 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> { num_trait_generics_except_self: usize, ) { let sm = self.tcx.sess.source_map(); - let hir::ExprKind::MethodCall(_, rcvr, args, _) = expr.kind else { return; }; + let hir::ExprKind::MethodCall(_, rcvr, args, _) = expr.kind else { + return; + }; if num_assoc_fn_excess_args != num_trait_generics_except_self { return; } - let Some(gen_args) = self.gen_args.span_ext() else { return; }; - let Ok(generics) = sm.span_to_snippet(gen_args) else { return; }; - let Ok(rcvr) = sm.span_to_snippet( - rcvr.span.find_ancestor_inside(expr.span).unwrap_or(rcvr.span) - ) else { return; }; - let Ok(rest) = - (match args { - [] => Ok(String::new()), - [arg] => sm.span_to_snippet( - arg.span.find_ancestor_inside(expr.span).unwrap_or(arg.span), - ), - [first, .., last] => { - let first_span = - first.span.find_ancestor_inside(expr.span).unwrap_or(first.span); - let last_span = - last.span.find_ancestor_inside(expr.span).unwrap_or(last.span); - sm.span_to_snippet(first_span.to(last_span)) - } - }) else { return; }; + let Some(gen_args) = self.gen_args.span_ext() else { + return; + }; + let Ok(generics) = sm.span_to_snippet(gen_args) else { + return; + }; + let Ok(rcvr) = + sm.span_to_snippet(rcvr.span.find_ancestor_inside(expr.span).unwrap_or(rcvr.span)) + else { + return; + }; + let Ok(rest) = (match args { + [] => Ok(String::new()), + [arg] => { + sm.span_to_snippet(arg.span.find_ancestor_inside(expr.span).unwrap_or(arg.span)) + } + [first, .., last] => { + let first_span = first.span.find_ancestor_inside(expr.span).unwrap_or(first.span); + let last_span = last.span.find_ancestor_inside(expr.span).unwrap_or(last.span); + sm.span_to_snippet(first_span.to(last_span)) + } + }) else { + return; + }; let comma = if args.len() > 0 { ", " } else { "" }; let trait_path = self.tcx.def_path_str(trait_def_id); let method_name = self.tcx.item_name(self.def_id); diff --git a/compiler/rustc_hir_analysis/src/variance/constraints.rs b/compiler/rustc_hir_analysis/src/variance/constraints.rs index 6f0afae1b4c..ec8889781f4 100644 --- a/compiler/rustc_hir_analysis/src/variance/constraints.rs +++ b/compiler/rustc_hir_analysis/src/variance/constraints.rs @@ -6,8 +6,8 @@ use hir::def_id::{DefId, LocalDefId}; use rustc_hir as hir; use rustc_hir::def::DefKind; -use rustc_middle::ty::subst::{GenericArgKind, SubstsRef}; use rustc_middle::ty::{self, Ty, TyCtxt}; +use rustc_middle::ty::{GenericArgKind, GenericArgsRef}; use super::terms::VarianceTerm::*; use super::terms::*; @@ -101,7 +101,7 @@ impl<'a, 'tcx> ConstraintContext<'a, 'tcx> { let inferred_start = self.terms_cx.inferred_starts[&def_id]; let current_item = &CurrentItem { inferred_start }; - match tcx.type_of(def_id).subst_identity().kind() { + match tcx.type_of(def_id).instantiate_identity().kind() { ty::Adt(def, _) => { // Not entirely obvious: constraints on structs/enums do not // affect the variance of their type parameters. See discussion @@ -112,7 +112,7 @@ impl<'a, 'tcx> ConstraintContext<'a, 'tcx> { for field in def.all_fields() { self.add_constraints_from_ty( current_item, - tcx.type_of(field.did).subst_identity(), + tcx.type_of(field.did).instantiate_identity(), self.covariant, ); } @@ -121,7 +121,7 @@ impl<'a, 'tcx> ConstraintContext<'a, 'tcx> { ty::FnDef(..) => { self.add_constraints_from_sig( current_item, - tcx.fn_sig(def_id).subst_identity(), + tcx.fn_sig(def_id).instantiate_identity(), self.covariant, ); } @@ -175,16 +175,16 @@ impl<'a, 'tcx> ConstraintContext<'a, 'tcx> { } #[instrument(level = "debug", skip(self, current))] - fn add_constraints_from_invariant_substs( + fn add_constraints_from_invariant_args( &mut self, current: &CurrentItem, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, variance: VarianceTermPtr<'a>, ) { // Trait are always invariant so we can take advantage of that. let variance_i = self.invariant(variance); - for k in substs { + for k in args { match k.unpack() { GenericArgKind::Lifetime(lt) => { self.add_constraints_from_region(current, lt, variance_i) @@ -248,12 +248,12 @@ impl<'a, 'tcx> ConstraintContext<'a, 'tcx> { } } - ty::Adt(def, substs) => { - self.add_constraints_from_substs(current, def.did(), substs, variance); + ty::Adt(def, args) => { + self.add_constraints_from_args(current, def.did(), args, variance); } ty::Alias(_, ref data) => { - self.add_constraints_from_invariant_substs(current, data.substs, variance); + self.add_constraints_from_invariant_args(current, data.args, variance); } ty::Dynamic(data, r, _) => { @@ -261,9 +261,9 @@ impl<'a, 'tcx> ConstraintContext<'a, 'tcx> { self.add_constraints_from_region(current, r, variance); if let Some(poly_trait_ref) = data.principal() { - self.add_constraints_from_invariant_substs( + self.add_constraints_from_invariant_args( current, - poly_trait_ref.skip_binder().substs, + poly_trait_ref.skip_binder().args, variance, ); } @@ -305,20 +305,20 @@ impl<'a, 'tcx> ConstraintContext<'a, 'tcx> { /// Adds constraints appropriate for a nominal type (enum, struct, /// object, etc) appearing in a context with ambient variance `variance` - fn add_constraints_from_substs( + fn add_constraints_from_args( &mut self, current: &CurrentItem, def_id: DefId, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, variance: VarianceTermPtr<'a>, ) { debug!( - "add_constraints_from_substs(def_id={:?}, substs={:?}, variance={:?})", - def_id, substs, variance + "add_constraints_from_args(def_id={:?}, args={:?}, variance={:?})", + def_id, args, variance ); // We don't record `inferred_starts` entries for empty generics. - if substs.is_empty() { + if args.is_empty() { return; } @@ -328,7 +328,7 @@ impl<'a, 'tcx> ConstraintContext<'a, 'tcx> { (None, Some(self.tcx().variances_of(def_id))) }; - for (i, k) in substs.iter().enumerate() { + for (i, k) in args.iter().enumerate() { let variance_decl = if let Some(InferredIndex(start)) = local { // Parameter on an item defined within current crate: // variance not yet inferred, so return a symbolic @@ -341,7 +341,7 @@ impl<'a, 'tcx> ConstraintContext<'a, 'tcx> { }; let variance_i = self.xform(variance, variance_decl); debug!( - "add_constraints_from_substs: variance_decl={:?} variance_i={:?}", + "add_constraints_from_args: variance_decl={:?} variance_i={:?}", variance_decl, variance_i ); match k.unpack() { @@ -368,7 +368,7 @@ impl<'a, 'tcx> ConstraintContext<'a, 'tcx> { match &c.kind() { ty::ConstKind::Unevaluated(uv) => { - self.add_constraints_from_invariant_substs(current, uv.substs, variance); + self.add_constraints_from_invariant_args(current, uv.args, variance); } _ => {} } diff --git a/compiler/rustc_hir_analysis/src/variance/mod.rs b/compiler/rustc_hir_analysis/src/variance/mod.rs index c703cb03515..199cdabb7e9 100644 --- a/compiler/rustc_hir_analysis/src/variance/mod.rs +++ b/compiler/rustc_hir_analysis/src/variance/mod.rs @@ -7,7 +7,7 @@ use rustc_arena::DroplessArena; use rustc_hir::def::DefKind; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_middle::query::Providers; -use rustc_middle::ty::{self, CrateVariancesMap, SubstsRef, Ty, TyCtxt}; +use rustc_middle::ty::{self, CrateVariancesMap, GenericArgsRef, Ty, TyCtxt}; use rustc_middle::ty::{TypeSuperVisitable, TypeVisitable}; use std::ops::ControlFlow; @@ -83,17 +83,17 @@ fn variance_of_opaque(tcx: TyCtxt<'_>, item_def_id: LocalDefId) -> &[ty::Varianc impl<'tcx> OpaqueTypeLifetimeCollector<'tcx> { #[instrument(level = "trace", skip(self), ret)] - fn visit_opaque(&mut self, def_id: DefId, substs: SubstsRef<'tcx>) -> ControlFlow<!> { + fn visit_opaque(&mut self, def_id: DefId, args: GenericArgsRef<'tcx>) -> ControlFlow<!> { if def_id != self.root_def_id && self.tcx.is_descendant_of(def_id, self.root_def_id) { let child_variances = self.tcx.variances_of(def_id); - for (a, v) in substs.iter().zip(child_variances) { + for (a, v) in args.iter().zip(child_variances) { if *v != ty::Bivariant { a.visit_with(self)?; } } ControlFlow::Continue(()) } else { - substs.visit_with(self) + args.visit_with(self) } } } @@ -110,10 +110,10 @@ fn variance_of_opaque(tcx: TyCtxt<'_>, item_def_id: LocalDefId) -> &[ty::Varianc #[instrument(level = "trace", skip(self), ret)] fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> { match t.kind() { - ty::Alias(_, ty::AliasTy { def_id, substs, .. }) + ty::Alias(_, ty::AliasTy { def_id, args, .. }) if matches!(self.tcx.def_kind(*def_id), DefKind::OpaqueTy) => { - self.visit_opaque(*def_id, substs) + self.visit_opaque(*def_id, args) } _ => t.super_visit_with(self), } @@ -144,30 +144,30 @@ fn variance_of_opaque(tcx: TyCtxt<'_>, item_def_id: LocalDefId) -> &[ty::Varianc let mut collector = OpaqueTypeLifetimeCollector { tcx, root_def_id: item_def_id.to_def_id(), variances }; - let id_substs = ty::InternalSubsts::identity_for_item(tcx, item_def_id); - for (pred, _) in tcx.explicit_item_bounds(item_def_id).subst_iter_copied(tcx, id_substs) { + let id_args = ty::GenericArgs::identity_for_item(tcx, item_def_id); + for (pred, _) in tcx.explicit_item_bounds(item_def_id).arg_iter_copied(tcx, id_args) { debug!(?pred); - // We only ignore opaque type substs if the opaque type is the outermost type. + // We only ignore opaque type args if the opaque type is the outermost type. // The opaque type may be nested within itself via recursion in e.g. // type Foo<'a> = impl PartialEq<Foo<'a>>; // which thus mentions `'a` and should thus accept hidden types that borrow 'a // instead of requiring an additional `+ 'a`. match pred.kind().skip_binder() { ty::ClauseKind::Trait(ty::TraitPredicate { - trait_ref: ty::TraitRef { def_id: _, substs, .. }, + trait_ref: ty::TraitRef { def_id: _, args, .. }, constness: _, polarity: _, }) => { - for subst in &substs[1..] { + for subst in &args[1..] { subst.visit_with(&mut collector); } } ty::ClauseKind::Projection(ty::ProjectionPredicate { - projection_ty: ty::AliasTy { substs, .. }, + projection_ty: ty::AliasTy { args, .. }, term, }) => { - for subst in &substs[1..] { + for subst in &args[1..] { subst.visit_with(&mut collector); } term.visit_with(&mut collector); diff --git a/compiler/rustc_hir_analysis/src/variance/solve.rs b/compiler/rustc_hir_analysis/src/variance/solve.rs index c27c176e35f..54da3277026 100644 --- a/compiler/rustc_hir_analysis/src/variance/solve.rs +++ b/compiler/rustc_hir_analysis/src/variance/solve.rs @@ -103,7 +103,7 @@ impl<'a, 'tcx> SolveContext<'a, 'tcx> { self.enforce_const_invariance(generics, variances); // Functions are permitted to have unused generic parameters: make those invariant. - if let ty::FnDef(..) = tcx.type_of(def_id).subst_identity().kind() { + if let ty::FnDef(..) = tcx.type_of(def_id).instantiate_identity().kind() { for variance in variances.iter_mut() { if *variance == ty::Bivariant { *variance = ty::Invariant; diff --git a/compiler/rustc_hir_typeck/Cargo.toml b/compiler/rustc_hir_typeck/Cargo.toml index 13e1ea31c4d..ce91d023a0a 100644 --- a/compiler/rustc_hir_typeck/Cargo.toml +++ b/compiler/rustc_hir_typeck/Cargo.toml @@ -9,6 +9,7 @@ edition = "2021" smallvec = { version = "1.8.1", features = ["union", "may_dangle"] } tracing = "0.1" rustc_ast = { path = "../rustc_ast" } +rustc_attr = { path = "../rustc_attr" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_errors = { path = "../rustc_errors" } rustc_graphviz = { path = "../rustc_graphviz" } diff --git a/compiler/rustc_hir_typeck/src/_match.rs b/compiler/rustc_hir_typeck/src/_match.rs index e8720a5da02..f2a43cc414d 100644 --- a/compiler/rustc_hir_typeck/src/_match.rs +++ b/compiler/rustc_hir_typeck/src/_match.rs @@ -188,11 +188,18 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let hir = self.tcx.hir(); // First, check that we're actually in the tail of a function. - let Some(body_id) = hir.maybe_body_owned_by(self.body_id) else { return; }; + let Some(body_id) = hir.maybe_body_owned_by(self.body_id) else { + return; + }; let body = hir.body(body_id); - let hir::ExprKind::Block(block, _) = body.value.kind else { return; }; - let Some(hir::Stmt { kind: hir::StmtKind::Semi(last_expr), .. }) - = block.innermost_block().stmts.last() else { return; }; + let hir::ExprKind::Block(block, _) = body.value.kind else { + return; + }; + let Some(hir::Stmt { kind: hir::StmtKind::Semi(last_expr), .. }) = + block.innermost_block().stmts.last() + else { + return; + }; if last_expr.hir_id != expr.hir_id { return; } @@ -201,7 +208,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let Some(ret) = hir .find_by_def_id(self.body_id) .and_then(|owner| owner.fn_decl()) - .map(|decl| decl.output.span()) else { return; }; + .map(|decl| decl.output.span()) + else { + return; + }; let Expectation::IsLast(stmt) = expectation else { return; }; @@ -508,9 +518,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { span, kind: TypeVariableOriginKind::OpaqueTypeInference(rpit_def_id), .. - } = self.type_var_origin(expected)? else { return None; }; + } = self.type_var_origin(expected)? + else { + return None; + }; - let Some(rpit_local_def_id) = rpit_def_id.as_local() else { return None; }; + let Some(rpit_local_def_id) = rpit_def_id.as_local() else { + return None; + }; if !matches!( self.tcx.hir().expect_item(rpit_local_def_id).expect_opaque_ty().origin, hir::OpaqueTyOrigin::FnReturn(..) @@ -520,12 +535,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let sig = self.body_fn_sig()?; - let substs = sig.output().walk().find_map(|arg| { + let args = sig.output().walk().find_map(|arg| { if let ty::GenericArgKind::Type(ty) = arg.unpack() - && let ty::Alias(ty::Opaque, ty::AliasTy { def_id, substs, .. }) = *ty.kind() + && let ty::Alias(ty::Opaque, ty::AliasTy { def_id, args, .. }) = *ty.kind() && def_id == rpit_def_id { - Some(substs) + Some(args) } else { None } @@ -536,26 +551,24 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } for ty in [first_ty, second_ty] { - for (clause, _) in self - .tcx - .explicit_item_bounds(rpit_def_id) - .subst_iter_copied(self.tcx, substs) + for (clause, _) in + self.tcx.explicit_item_bounds(rpit_def_id).arg_iter_copied(self.tcx, args) { let pred = clause.kind().rebind(match clause.kind().skip_binder() { ty::ClauseKind::Trait(trait_pred) => { // FIXME(rpitit): This will need to be fixed when we move to associated types assert!(matches!( *trait_pred.trait_ref.self_ty().kind(), - ty::Alias(_, ty::AliasTy { def_id, substs: alias_substs, .. }) - if def_id == rpit_def_id && substs == alias_substs + ty::Alias(_, ty::AliasTy { def_id, args: alias_args, .. }) + if def_id == rpit_def_id && args == alias_args )); ty::ClauseKind::Trait(trait_pred.with_self_ty(self.tcx, ty)) } ty::ClauseKind::Projection(mut proj_pred) => { assert!(matches!( *proj_pred.projection_ty.self_ty().kind(), - ty::Alias(_, ty::AliasTy { def_id, substs: alias_substs, .. }) - if def_id == rpit_def_id && substs == alias_substs + ty::Alias(_, ty::AliasTy { def_id, args: alias_args, .. }) + if def_id == rpit_def_id && args == alias_args )); proj_pred = proj_pred.with_self_ty(self.tcx, ty); ty::ClauseKind::Projection(proj_pred) diff --git a/compiler/rustc_hir_typeck/src/callee.rs b/compiler/rustc_hir_typeck/src/callee.rs index f306653c1ab..a24d1ff077f 100644 --- a/compiler/rustc_hir_typeck/src/callee.rs +++ b/compiler/rustc_hir_typeck/src/callee.rs @@ -21,7 +21,7 @@ use rustc_infer::{ use rustc_middle::ty::adjustment::{ Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability, }; -use rustc_middle::ty::SubstsRef; +use rustc_middle::ty::GenericArgsRef; use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt}; use rustc_span::def_id::LocalDefId; use rustc_span::symbol::{sym, Ident}; @@ -149,14 +149,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { return Some(CallStep::Builtin(adjusted_ty)); } - ty::Closure(def_id, substs) => { + ty::Closure(def_id, args) => { let def_id = def_id.expect_local(); // Check whether this is a call to a closure where we // haven't yet decided on whether the closure is fn vs // fnmut vs fnonce. If so, we have to defer further processing. - if self.closure_kind(substs).is_none() { - let closure_sig = substs.as_closure().sig(); + if self.closure_kind(args).is_none() { + let closure_sig = args.as_closure().sig(); let closure_sig = self.instantiate_binder_with_fresh_vars( call_expr.span, infer::FnCall, @@ -171,7 +171,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { adjusted_ty, adjustments, fn_sig: closure_sig, - closure_substs: substs, + closure_args: args, }, ); return Some(CallStep::DeferredClosure(def_id, closure_sig)); @@ -380,16 +380,16 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { expected: Expectation<'tcx>, ) -> Ty<'tcx> { let (fn_sig, def_id) = match *callee_ty.kind() { - ty::FnDef(def_id, substs) => { - self.enforce_context_effects(call_expr.hir_id, call_expr.span, def_id, substs); - let fn_sig = self.tcx.fn_sig(def_id).subst(self.tcx, substs); + ty::FnDef(def_id, args) => { + self.enforce_context_effects(call_expr.hir_id, call_expr.span, def_id, args); + let fn_sig = self.tcx.fn_sig(def_id).instantiate(self.tcx, args); // Unit testing: function items annotated with // `#[rustc_evaluate_where_clauses]` trigger special output // to let us test the trait evaluation system. if self.tcx.has_attr(def_id, sym::rustc_evaluate_where_clauses) { let predicates = self.tcx.predicates_of(def_id); - let predicates = predicates.instantiate(self.tcx, substs); + let predicates = predicates.instantiate(self.tcx, args); for (predicate, predicate_span) in predicates { let obligation = Obligation::new( self.tcx, @@ -499,15 +499,15 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { expected: Expectation<'tcx>, ) { if let [callee_expr, rest @ ..] = arg_exprs { - let Some(callee_ty) = self.typeck_results.borrow().expr_ty_adjusted_opt(callee_expr) else { + let Some(callee_ty) = self.typeck_results.borrow().expr_ty_adjusted_opt(callee_expr) + else { return; }; // First, do a probe with `IsSuggestion(true)` to avoid emitting // any strange errors. If it's successful, then we'll do a true // method lookup. - let Ok(pick) = self - .lookup_probe_for_diagnostic( + let Ok(pick) = self.lookup_probe_for_diagnostic( segment.ident, callee_ty, call_expr, @@ -751,7 +751,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { call_expr_hir: HirId, span: Span, callee_did: DefId, - callee_substs: SubstsRef<'tcx>, + callee_args: GenericArgsRef<'tcx>, ) { let tcx = self.tcx; @@ -774,18 +774,18 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let effect = match const_context { Some(hir::ConstContext::Static(_) | hir::ConstContext::Const) => tcx.consts.false_, Some(hir::ConstContext::ConstFn) => { - let substs = ty::InternalSubsts::identity_for_item(tcx, context); - substs.host_effect_param().expect("ConstContext::Maybe must have host effect param") + let args = ty::GenericArgs::identity_for_item(tcx, context); + args.host_effect_param().expect("ConstContext::Maybe must have host effect param") } None => tcx.consts.true_, }; let generics = tcx.generics_of(callee_did); - trace!(?effect, ?generics, ?callee_substs); + trace!(?effect, ?generics, ?callee_args); if let Some(idx) = generics.host_effect_index { - let param = callee_substs.const_at(idx); + let param = callee_args.const_at(idx); let cause = self.misc(span); match self.at(&cause, self.param_env).eq(infer::DefineOpaqueTypes::No, effect, param) { Ok(infer::InferOk { obligations, value: () }) => { @@ -827,7 +827,7 @@ pub struct DeferredCallResolution<'tcx> { adjusted_ty: Ty<'tcx>, adjustments: Vec<Adjustment<'tcx>>, fn_sig: ty::FnSig<'tcx>, - closure_substs: SubstsRef<'tcx>, + closure_args: GenericArgsRef<'tcx>, } impl<'a, 'tcx> DeferredCallResolution<'tcx> { @@ -836,7 +836,7 @@ impl<'a, 'tcx> DeferredCallResolution<'tcx> { // we should not be invoked until the closure kind has been // determined by upvar inference - assert!(fcx.closure_kind(self.closure_substs).is_some()); + assert!(fcx.closure_kind(self.closure_args).is_some()); // We may now know enough to figure out fn vs fnmut etc. match fcx.try_overloaded_call_traits(self.call_expr, self.adjusted_ty, None) { diff --git a/compiler/rustc_hir_typeck/src/cast.rs b/compiler/rustc_hir_typeck/src/cast.rs index 633933317c0..7597ce88f93 100644 --- a/compiler/rustc_hir_typeck/src/cast.rs +++ b/compiler/rustc_hir_typeck/src/cast.rs @@ -103,10 +103,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { Ok(match *t.kind() { ty::Slice(_) | ty::Str => Some(PointerKind::Length), ty::Dynamic(ref tty, _, ty::Dyn) => Some(PointerKind::VTable(tty.principal_def_id())), - ty::Adt(def, substs) if def.is_struct() => match def.non_enum_variant().tail_opt() { + ty::Adt(def, args) if def.is_struct() => match def.non_enum_variant().tail_opt() { None => Some(PointerKind::Thin), Some(f) => { - let field_ty = self.field_ty(span, f, substs); + let field_ty = self.field_ty(span, f, args); self.pointer_kind(field_ty, span)? } }, diff --git a/compiler/rustc_hir_typeck/src/check.rs b/compiler/rustc_hir_typeck/src/check.rs index 8b57e311fc0..53bae315d78 100644 --- a/compiler/rustc_hir_typeck/src/check.rs +++ b/compiler/rustc_hir_typeck/src/check.rs @@ -80,7 +80,7 @@ pub(super) fn check_fn<'a, 'tcx>( let va_list_did = tcx.require_lang_item(LangItem::VaList, Some(span)); let region = fcx.next_region_var(RegionVariableOrigin::MiscVariable(span)); - tcx.type_of(va_list_did).subst(tcx, &[region.into()]) + tcx.type_of(va_list_did).instantiate(tcx, &[region.into()]) }); // Add formal parameters. diff --git a/compiler/rustc_hir_typeck/src/closure.rs b/compiler/rustc_hir_typeck/src/closure.rs index 78a9ac49de2..e7df9ecf383 100644 --- a/compiler/rustc_hir_typeck/src/closure.rs +++ b/compiler/rustc_hir_typeck/src/closure.rs @@ -10,8 +10,8 @@ use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKi use rustc_infer::infer::{DefineOpaqueTypes, LateBoundRegionConversionTime}; use rustc_infer::infer::{InferOk, InferResult}; use rustc_macros::{TypeFoldable, TypeVisitable}; -use rustc_middle::ty::subst::InternalSubsts; use rustc_middle::ty::visit::{TypeVisitable, TypeVisitableExt}; +use rustc_middle::ty::GenericArgs; use rustc_middle::ty::{self, Ty, TyCtxt, TypeSuperVisitable, TypeVisitor}; use rustc_span::def_id::LocalDefId; use rustc_span::source_map::Span; @@ -93,7 +93,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { false, ); - let parent_substs = InternalSubsts::identity_for_item( + let parent_args = GenericArgs::identity_for_item( self.tcx, self.tcx.typeck_root_def_id(expr_def_id.to_def_id()), ); @@ -105,10 +105,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if let Some(GeneratorTypes { resume_ty, yield_ty, interior, movability }) = generator_types { - let generator_substs = ty::GeneratorSubsts::new( + let generator_args = ty::GeneratorArgs::new( self.tcx, - ty::GeneratorSubstsParts { - parent_substs, + ty::GeneratorArgsParts { + parent_args, resume_ty, yield_ty, return_ty: liberated_sig.output(), @@ -120,7 +120,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { return Ty::new_generator( self.tcx, expr_def_id.to_def_id(), - generator_substs.substs, + generator_args.args, movability, ); } @@ -151,17 +151,17 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }), }; - let closure_substs = ty::ClosureSubsts::new( + let closure_args = ty::ClosureArgs::new( self.tcx, - ty::ClosureSubstsParts { - parent_substs, + ty::ClosureArgsParts { + parent_args, closure_kind_ty, closure_sig_as_fn_ptr_ty: Ty::new_fn_ptr(self.tcx, sig), tupled_upvars_ty, }, ); - Ty::new_closure(self.tcx, expr_def_id.to_def_id(), closure_substs.substs) + Ty::new_closure(self.tcx, expr_def_id.to_def_id(), closure_args.args) } /// Given the expected type, figures out what it can about this closure we @@ -172,12 +172,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { expected_ty: Ty<'tcx>, ) -> (Option<ExpectedSig<'tcx>>, Option<ty::ClosureKind>) { match *expected_ty.kind() { - ty::Alias(ty::Opaque, ty::AliasTy { def_id, substs, .. }) => self + ty::Alias(ty::Opaque, ty::AliasTy { def_id, args, .. }) => self .deduce_closure_signature_from_predicates( expected_ty, self.tcx .explicit_item_bounds(def_id) - .subst_iter_copied(self.tcx, substs) + .arg_iter_copied(self.tcx, args) .map(|(c, s)| (c.as_predicate(), s)), ), ty::Dynamic(ref object_type, ..) => { @@ -315,7 +315,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } let input_tys = if is_fn { - let arg_param_ty = projection.skip_binder().projection_ty.substs.type_at(1); + let arg_param_ty = projection.skip_binder().projection_ty.args.type_at(1); let arg_param_ty = self.resolve_vars_if_possible(arg_param_ty); debug!(?arg_param_ty); @@ -717,16 +717,16 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { get_future_output(obligation.predicate, obligation.cause.span) })? } - ty::Alias(ty::Opaque, ty::AliasTy { def_id, substs, .. }) => self + ty::Alias(ty::Opaque, ty::AliasTy { def_id, args, .. }) => self .tcx .explicit_item_bounds(def_id) - .subst_iter_copied(self.tcx, substs) + .arg_iter_copied(self.tcx, args) .find_map(|(p, s)| get_future_output(p.as_predicate(), s))?, ty::Error(_) => return None, ty::Alias(ty::Projection, proj) if self.tcx.is_impl_trait_in_trait(proj.def_id) => self .tcx .explicit_item_bounds(proj.def_id) - .subst_iter_copied(self.tcx, proj.substs) + .arg_iter_copied(self.tcx, proj.args) .find_map(|(p, s)| get_future_output(p.as_predicate(), s))?, _ => span_bug!( self.tcx.def_span(expr_def_id), diff --git a/compiler/rustc_hir_typeck/src/coercion.rs b/compiler/rustc_hir_typeck/src/coercion.rs index dc58d99ed9d..3b1d9c8905b 100644 --- a/compiler/rustc_hir_typeck/src/coercion.rs +++ b/compiler/rustc_hir_typeck/src/coercion.rs @@ -51,8 +51,8 @@ use rustc_middle::ty::adjustment::{ }; use rustc_middle::ty::error::TypeError; use rustc_middle::ty::relate::RelateResult; -use rustc_middle::ty::subst::SubstsRef; use rustc_middle::ty::visit::TypeVisitableExt; +use rustc_middle::ty::GenericArgsRef; use rustc_middle::ty::{self, Ty, TypeAndMut}; use rustc_session::parse::feature_err; use rustc_span::symbol::sym; @@ -251,11 +251,11 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { // unsafe qualifier. self.coerce_from_fn_pointer(a, a_f, b) } - ty::Closure(closure_def_id_a, substs_a) => { + ty::Closure(closure_def_id_a, args_a) => { // Non-capturing closures are coercible to // function pointers or unsafe function pointers. // It cannot convert closures that require unsafe. - self.coerce_closure_to_fn(a, closure_def_id_a, substs_a, b) + self.coerce_closure_to_fn(a, closure_def_id_a, args_a, b) } _ => { // Otherwise, just use unification rules. @@ -636,9 +636,10 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { Some(ty::PredicateKind::Clause(ty::ClauseKind::Trait(trait_pred))) if traits.contains(&trait_pred.def_id()) => { + let trait_pred = self.resolve_vars_if_possible(trait_pred); if unsize_did == trait_pred.def_id() { let self_ty = trait_pred.self_ty(); - let unsize_ty = trait_pred.trait_ref.substs[1].expect_ty(); + let unsize_ty = trait_pred.trait_ref.args[1].expect_ty(); if let (ty::Dynamic(ref data_a, ..), ty::Dynamic(ref data_b, ..)) = (self_ty.kind(), unsize_ty.kind()) && data_a.principal_def_id() != data_b.principal_def_id() @@ -662,9 +663,8 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { // Uncertain or unimplemented. Ok(None) => { if trait_pred.def_id() == unsize_did { - let trait_pred = self.resolve_vars_if_possible(trait_pred); let self_ty = trait_pred.self_ty(); - let unsize_ty = trait_pred.trait_ref.substs[1].expect_ty(); + let unsize_ty = trait_pred.trait_ref.args[1].expect_ty(); debug!("coerce_unsized: ambiguous unsize case for {:?}", trait_pred); match (self_ty.kind(), unsize_ty.kind()) { (&ty::Infer(ty::TyVar(v)), ty::Dynamic(..)) @@ -916,7 +916,7 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { &self, a: Ty<'tcx>, closure_def_id_a: DefId, - substs_a: SubstsRef<'tcx>, + args_a: GenericArgsRef<'tcx>, b: Ty<'tcx>, ) -> CoerceResult<'tcx> { //! Attempts to coerce from the type of a non-capturing closure @@ -927,7 +927,7 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { match b.kind() { // At this point we haven't done capture analysis, which means - // that the ClosureSubsts just contains an inference variable instead + // that the ClosureArgs just contains an inference variable instead // of tuple of captured types. // // All we care here is if any variable is being captured and not the exact paths, @@ -944,7 +944,7 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { // `fn(arg0,arg1,...) -> _` // or // `unsafe fn(arg0,arg1,...) -> _` - let closure_sig = substs_a.as_closure().sig(); + let closure_sig = args_a.as_closure().sig(); let unsafety = fn_ty.unsafety(); let pointer_ty = Ty::new_fn_ptr(self.tcx, self.tcx.signature_unclosure(closure_sig, unsafety)); @@ -1109,10 +1109,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } // Special-case that coercion alone cannot handle: - // Function items or non-capturing closures of differing IDs or InternalSubsts. + // Function items or non-capturing closures of differing IDs or GenericArgs. let (a_sig, b_sig) = { let is_capturing_closure = |ty: Ty<'tcx>| { - if let &ty::Closure(closure_def_id, _substs) = ty.kind() { + if let &ty::Closure(closure_def_id, _args) = ty.kind() { self.tcx.upvars_mentioned(closure_def_id.expect_local()).is_some() } else { false @@ -1139,30 +1139,30 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } } } - (ty::Closure(_, substs), ty::FnDef(..)) => { + (ty::Closure(_, args), ty::FnDef(..)) => { let b_sig = new_ty.fn_sig(self.tcx); - let a_sig = self - .tcx - .signature_unclosure(substs.as_closure().sig(), b_sig.unsafety()); + let a_sig = + self.tcx.signature_unclosure(args.as_closure().sig(), b_sig.unsafety()); (Some(a_sig), Some(b_sig)) } - (ty::FnDef(..), ty::Closure(_, substs)) => { + (ty::FnDef(..), ty::Closure(_, args)) => { let a_sig = prev_ty.fn_sig(self.tcx); - let b_sig = self - .tcx - .signature_unclosure(substs.as_closure().sig(), a_sig.unsafety()); + let b_sig = + self.tcx.signature_unclosure(args.as_closure().sig(), a_sig.unsafety()); (Some(a_sig), Some(b_sig)) } - (ty::Closure(_, substs_a), ty::Closure(_, substs_b)) => ( - Some(self.tcx.signature_unclosure( - substs_a.as_closure().sig(), - hir::Unsafety::Normal, - )), - Some(self.tcx.signature_unclosure( - substs_b.as_closure().sig(), - hir::Unsafety::Normal, - )), - ), + (ty::Closure(_, args_a), ty::Closure(_, args_b)) => { + ( + Some(self.tcx.signature_unclosure( + args_a.as_closure().sig(), + hir::Unsafety::Normal, + )), + Some(self.tcx.signature_unclosure( + args_b.as_closure().sig(), + hir::Unsafety::Normal, + )), + ) + } _ => (None, None), } } @@ -1670,7 +1670,9 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { expr: &hir::Expr<'tcx>, ret_exprs: &Vec<&'tcx hir::Expr<'tcx>>, ) { - let hir::ExprKind::Loop(_, _, _, loop_span) = expr.kind else { return;}; + let hir::ExprKind::Loop(_, _, _, loop_span) = expr.kind else { + return; + }; let mut span: MultiSpan = vec![loop_span].into(); span.push_span_label(loop_span, "this might have zero elements to iterate on"); const MAXITER: usize = 3; diff --git a/compiler/rustc_hir_typeck/src/demand.rs b/compiler/rustc_hir_typeck/src/demand.rs index cc8198aab25..429c3366fed 100644 --- a/compiler/rustc_hir_typeck/src/demand.rs +++ b/compiler/rustc_hir_typeck/src/demand.rs @@ -15,7 +15,7 @@ use rustc_middle::ty::error::{ExpectedFound, TypeError}; use rustc_middle::ty::fold::BottomUpFolder; use rustc_middle::ty::print::with_no_trimmed_paths; use rustc_middle::ty::{self, Article, AssocItem, Ty, TypeAndMut, TypeFoldable}; -use rustc_span::symbol::{sym, Symbol}; +use rustc_span::symbol::sym; use rustc_span::{BytePos, Span, DUMMY_SP}; use rustc_trait_selection::infer::InferCtxtExt as _; use rustc_trait_selection::traits::ObligationCause; @@ -102,7 +102,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { found_expr: &mut &'tcx hir::Expr<'tcx>, expected_expr: &mut Option<&'tcx hir::Expr<'tcx>>, ) { - let Some(expected_expr) = expected_expr else { return; }; + let Some(expected_expr) = expected_expr else { + return; + }; if !found_expr.span.eq_ctxt(expected_expr.span) { return; @@ -121,11 +123,17 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let hir::ExprKind::Unary( hir::UnOp::Deref, hir::Expr { kind: hir::ExprKind::Path(found_path), .. }, - ) = found_expr.kind else { return; }; + ) = found_expr.kind + else { + return; + }; let hir::ExprKind::Unary( hir::UnOp::Deref, hir::Expr { kind: hir::ExprKind::Path(expected_path), .. }, - ) = expected_expr.kind else { return; }; + ) = expected_expr.kind + else { + return; + }; for (path, name, idx, var) in [ (expected_path, "left_val", 0, expected_expr), @@ -285,16 +293,26 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ) -> bool { let hir = self.tcx.hir(); - let hir::ExprKind::Path(hir::QPath::Resolved(None, p)) = expr.kind else { return false; }; - let [hir::PathSegment { ident, args: None, .. }] = p.segments else { return false; }; - let hir::def::Res::Local(local_hir_id) = p.res else { return false; }; - let hir::Node::Pat(pat) = hir.get(local_hir_id) else { return false; }; + let hir::ExprKind::Path(hir::QPath::Resolved(None, p)) = expr.kind else { + return false; + }; + let [hir::PathSegment { ident, args: None, .. }] = p.segments else { + return false; + }; + let hir::def::Res::Local(local_hir_id) = p.res else { + return false; + }; + let hir::Node::Pat(pat) = hir.get(local_hir_id) else { + return false; + }; let (init_ty_hir_id, init) = match hir.get_parent(pat.hir_id) { hir::Node::Local(hir::Local { ty: Some(ty), init, .. }) => (ty.hir_id, *init), hir::Node::Local(hir::Local { init: Some(init), .. }) => (init.hir_id, Some(*init)), _ => return false, }; - let Some(init_ty) = self.node_ty_opt(init_ty_hir_id) else { return false; }; + let Some(init_ty) = self.node_ty_opt(init_ty_hir_id) else { + return false; + }; // Locate all the usages of the relevant binding. struct FindExprs<'tcx> { @@ -413,14 +431,18 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Bindings always update their recorded type after the fact, so we // need to look at the *following* usage's type to see when the // binding became incompatible. - let [binding, next_usage] = *window else { continue; }; + let [binding, next_usage] = *window else { + continue; + }; // Don't go past the binding (always gonna be a nonsense label if so) if binding.hir_id == expr.hir_id { break; } - let Some(next_use_ty) = self.node_ty_opt(next_usage.hir_id) else { continue; }; + let Some(next_use_ty) = self.node_ty_opt(next_usage.hir_id) else { + continue; + }; // If the type is not constrained in a way making it not possible to // equate with `expected_ty` by this point, skip. @@ -634,27 +656,36 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { error: Option<TypeError<'tcx>>, ) { let parent = self.tcx.hir().parent_id(expr.hir_id); - let Some(TypeError::Sorts(ExpectedFound { expected, .. })) = error else {return;}; - let Some(hir::Node::Expr(hir::Expr { - kind: hir::ExprKind::Assign(lhs, rhs, _), .. - })) = self.tcx.hir().find(parent) else {return; }; + let Some(TypeError::Sorts(ExpectedFound { expected, .. })) = error else { + return; + }; + let Some(hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Assign(lhs, rhs, _), .. })) = + self.tcx.hir().find(parent) + else { + return; + }; if rhs.hir_id != expr.hir_id || expected.is_closure() { return; } - let hir::ExprKind::Unary(hir::UnOp::Deref, deref) = lhs.kind else { return; }; - let hir::ExprKind::MethodCall(path, base, args, _) = deref.kind else { return; }; - let Some(self_ty) = self.typeck_results.borrow().expr_ty_adjusted_opt(base) else { return; }; + let hir::ExprKind::Unary(hir::UnOp::Deref, deref) = lhs.kind else { + return; + }; + let hir::ExprKind::MethodCall(path, base, args, _) = deref.kind else { + return; + }; + let Some(self_ty) = self.typeck_results.borrow().expr_ty_adjusted_opt(base) else { + return; + }; - let Ok(pick) = self - .lookup_probe_for_diagnostic( - path.ident, - self_ty, - deref, - probe::ProbeScope::TraitsInScope, - None, - ) else { - return; - }; + let Ok(pick) = self.lookup_probe_for_diagnostic( + path.ident, + self_ty, + deref, + probe::ProbeScope::TraitsInScope, + None, + ) else { + return; + }; let in_scope_methods = self.probe_for_name_many( probe::Mode::MethodCall, path.ident, @@ -681,7 +712,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .filter(|c| c.item.def_id != pick.item.def_id) .map(|c| { let m = c.item; - let substs = ty::InternalSubsts::for_item(self.tcx, m.def_id, |param, _| { + let generic_args = ty::GenericArgs::for_item(self.tcx, m.def_id, |param, _| { self.var_for_def(deref.span, param) }); let mutability = @@ -696,7 +727,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { format!( "{}({}", with_no_trimmed_paths!( - self.tcx.def_path_str_with_substs(m.def_id, substs,) + self.tcx.def_path_str_with_args(m.def_id, generic_args,) ), mutability, ), @@ -793,8 +824,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { expected: Ty<'tcx>, found: Ty<'tcx>, ) -> bool { - let ty::Adt(e, substs_e) = expected.kind() else { return false; }; - let ty::Adt(f, substs_f) = found.kind() else { return false; }; + let ty::Adt(e, args_e) = expected.kind() else { + return false; + }; + let ty::Adt(f, args_f) = found.kind() else { + return false; + }; if e.did() != f.did() { return false; } @@ -811,8 +846,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } else { return false; } - let e = substs_e.type_at(1); - let f = substs_f.type_at(1); + let e = args_e.type_at(1); + let f = args_f.type_at(1); if self .infcx .type_implements_trait( @@ -845,7 +880,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { expected: Ty<'tcx>, expr_ty: Ty<'tcx>, ) -> bool { - if let ty::Adt(expected_adt, substs) = expected.kind() { + if let ty::Adt(expected_adt, args) = expected.kind() { if let hir::ExprKind::Field(base, ident) = expr.kind { let base_ty = self.typeck_results.borrow().expr_ty(base); if self.can_eq(self.param_env, base_ty, expected) @@ -944,7 +979,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let note_about_variant_field_privacy = (field_is_local && !field_is_accessible) .then(|| " (its field is private, but it's local to this crate and its privacy can be changed)".to_string()); - let sole_field_ty = sole_field.ty(self.tcx, substs); + let sole_field_ty = sole_field.ty(self.tcx, args); if self.can_coerce(expr_ty, sole_field_ty) { let variant_path = with_no_trimmed_paths!(self.tcx.def_path_str(variant.def_id)); @@ -962,7 +997,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .collect(); let suggestions_for = |variant: &_, ctor_kind, field_name| { - let prefix = match self.maybe_get_struct_pattern_shorthand_field(expr) { + let prefix = match self.tcx.hir().maybe_get_struct_pattern_shorthand_field(expr) { Some(ident) => format!("{ident}: "), None => String::new(), }; @@ -1037,9 +1072,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let tcx = self.tcx; let (adt, unwrap) = match expected.kind() { // In case Option<NonZero*> is wanted, but * is provided, suggest calling new - ty::Adt(adt, substs) if tcx.is_diagnostic_item(sym::Option, adt.did()) => { + ty::Adt(adt, args) if tcx.is_diagnostic_item(sym::Option, adt.did()) => { // Unwrap option - let ty::Adt(adt, _) = substs.type_at(0).kind() else { return false; }; + let ty::Adt(adt, _) = args.type_at(0).kind() else { + return false; + }; (adt, "") } @@ -1061,10 +1098,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { (sym::NonZeroI128, tcx.types.i128), ]; - let Some((s, _)) = map - .iter() - .find(|&&(s, t)| self.tcx.is_diagnostic_item(s, adt.did()) && self.can_coerce(expr_ty, t)) - else { return false; }; + let Some((s, _)) = map.iter().find(|&&(s, t)| { + self.tcx.is_diagnostic_item(s, adt.did()) && self.can_coerce(expr_ty, t) + }) else { + return false; + }; let path = self.tcx.def_path_str(adt.non_enum_variant().def_id); @@ -1152,7 +1190,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }; let local_parent = self.tcx.hir().parent_id(local_id); - let Some(Node::Param(hir::Param { hir_id: param_hir_id, .. })) = self.tcx.hir().find(local_parent) else { + let Some(Node::Param(hir::Param { hir_id: param_hir_id, .. })) = + self.tcx.hir().find(local_parent) + else { return None; }; @@ -1161,7 +1201,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { hir_id: expr_hir_id, kind: hir::ExprKind::Closure(hir::Closure { fn_decl: closure_fn_decl, .. }), .. - })) = self.tcx.hir().find(param_parent) else { + })) = self.tcx.hir().find(param_parent) + else { return None; }; @@ -1174,7 +1215,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .. })), 1, - ) = (hir, closure_params_len) else { + ) = (hir, closure_params_len) + else { return None; }; @@ -1198,39 +1240,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } } - pub(crate) fn maybe_get_struct_pattern_shorthand_field( - &self, - expr: &hir::Expr<'_>, - ) -> Option<Symbol> { - let hir = self.tcx.hir(); - let local = match expr { - hir::Expr { - kind: - hir::ExprKind::Path(hir::QPath::Resolved( - None, - hir::Path { - res: hir::def::Res::Local(_), - segments: [hir::PathSegment { ident, .. }], - .. - }, - )), - .. - } => Some(ident), - _ => None, - }?; - - match hir.find_parent(expr.hir_id)? { - Node::ExprField(field) => { - if field.ident.name == local.name && field.is_shorthand { - return Some(local.name); - } - } - _ => {} - } - - None - } - /// If the given `HirId` corresponds to a block with a trailing expression, return that expression pub(crate) fn maybe_get_block_expr( &self, @@ -1425,7 +1434,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { )); } - let prefix = match self.maybe_get_struct_pattern_shorthand_field(expr) { + let prefix = match self.tcx.hir().maybe_get_struct_pattern_shorthand_field(expr) { Some(ident) => format!("{ident}: "), None => String::new(), }; @@ -1619,7 +1628,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ) }; - let prefix = match self.maybe_get_struct_pattern_shorthand_field(expr) { + let prefix = match self.tcx.hir().maybe_get_struct_pattern_shorthand_field(expr) { Some(ident) => format!("{ident}: "), None => String::new(), }; @@ -2028,11 +2037,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if !hir::is_range_literal(expr) { return; } - let hir::ExprKind::Struct( - hir::QPath::LangItem(LangItem::Range, ..), - [start, end], - _, - ) = expr.kind else { return; }; + let hir::ExprKind::Struct(hir::QPath::LangItem(LangItem::Range, ..), [start, end], _) = + expr.kind + else { + return; + }; let parent = self.tcx.hir().parent_id(expr.hir_id); if let Some(hir::Node::ExprField(_)) = self.tcx.hir().find(parent) { // Ignore `Foo { field: a..Default::default() }` @@ -2048,8 +2057,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // cannot guide the method probe. expectation = None; } - let hir::ExprKind::Call(method_name, _) = expr.kind else { return; }; - let ty::Adt(adt, _) = checked_ty.kind() else { return; }; + let hir::ExprKind::Call(method_name, _) = expr.kind else { + return; + }; + let ty::Adt(adt, _) = checked_ty.kind() else { + return; + }; if self.tcx.lang_items().range_struct() != Some(adt.did()) { return; } @@ -2059,8 +2072,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { return; } // Check if start has method named end. - let hir::ExprKind::Path(hir::QPath::Resolved(None, p)) = method_name.kind else { return; }; - let [hir::PathSegment { ident, .. }] = p.segments else { return; }; + let hir::ExprKind::Path(hir::QPath::Resolved(None, p)) = method_name.kind else { + return; + }; + let [hir::PathSegment { ident, .. }] = p.segments else { + return; + }; let self_ty = self.typeck_results.borrow().expr_ty(start.expr); let Ok(_pick) = self.lookup_probe_for_diagnostic( *ident, @@ -2068,7 +2085,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { expr, probe::ProbeScope::AllTraits, expectation, - ) else { return; }; + ) else { + return; + }; let mut sugg = "."; let mut span = start.expr.span.between(end.expr.span); if span.lo() + BytePos(2) == span.hi() { @@ -2097,17 +2116,23 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if !checked_ty.is_unit() { return; } - let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind else { return; }; - let hir::def::Res::Local(hir_id) = path.res else { return; }; + let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind else { + return; + }; + let hir::def::Res::Local(hir_id) = path.res else { + return; + }; let Some(hir::Node::Pat(pat)) = self.tcx.hir().find(hir_id) else { return; }; - let Some(hir::Node::Local(hir::Local { - ty: None, - init: Some(init), - .. - })) = self.tcx.hir().find_parent(pat.hir_id) else { return; }; - let hir::ExprKind::Block(block, None) = init.kind else { return; }; + let Some(hir::Node::Local(hir::Local { ty: None, init: Some(init), .. })) = + self.tcx.hir().find_parent(pat.hir_id) + else { + return; + }; + let hir::ExprKind::Block(block, None) = init.kind else { + return; + }; if block.expr.is_some() { return; } @@ -2115,8 +2140,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { err.span_label(block.span, "this empty block is missing a tail expression"); return; }; - let hir::StmtKind::Semi(tail_expr) = stmt.kind else { return; }; - let Some(ty) = self.node_ty_opt(tail_expr.hir_id) else { return; }; + let hir::StmtKind::Semi(tail_expr) = stmt.kind else { + return; + }; + let Some(ty) = self.node_ty_opt(tail_expr.hir_id) else { + return; + }; if self.can_eq(self.param_env, expected_ty, ty) { err.span_suggestion_short( stmt.span.with_lo(tail_expr.span.hi()), @@ -2135,7 +2164,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { expr: &hir::Expr<'_>, checked_ty: Ty<'tcx>, ) { - let Some(hir::Node::Expr(parent_expr)) = self.tcx.hir().find_parent(expr.hir_id) else { return; }; + let Some(hir::Node::Expr(parent_expr)) = self.tcx.hir().find_parent(expr.hir_id) else { + return; + }; enum CallableKind { Function, Method, @@ -2151,7 +2182,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { return; } let fn_sig = fn_ty.fn_sig(self.tcx).skip_binder(); - let Some(&arg) = fn_sig.inputs().get(arg_idx + if matches!(kind, CallableKind::Method) { 1 } else { 0 }) else { return; }; + let Some(&arg) = fn_sig + .inputs() + .get(arg_idx + if matches!(kind, CallableKind::Method) { 1 } else { 0 }) + else { + return; + }; if matches!(arg.kind(), ty::Param(_)) && fn_sig.output().contains(arg) && self.node_ty(args[arg_idx].hir_id) == checked_ty @@ -2185,8 +2221,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }; match parent_expr.kind { hir::ExprKind::Call(fun, args) => { - let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = fun.kind else { return; }; - let hir::def::Res::Def(kind, def_id) = path.res else { return; }; + let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = fun.kind else { + return; + }; + let hir::def::Res::Def(kind, def_id) = path.res else { + return; + }; let callable_kind = if matches!(kind, hir::def::DefKind::Ctor(_, _)) { CallableKind::Constructor } else { @@ -2195,7 +2235,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { maybe_emit_help(def_id, path.segments[0].ident, args, callable_kind); } hir::ExprKind::MethodCall(method, _receiver, args, _span) => { - let Some(def_id) = self.typeck_results.borrow().type_dependent_def_id(parent_expr.hir_id) else { return; }; + let Some(def_id) = + self.typeck_results.borrow().type_dependent_def_id(parent_expr.hir_id) + else { + return; + }; maybe_emit_help(def_id, method.ident, args, CallableKind::Method) } _ => return, diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index 72b29f7b6e9..29488c9011a 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -44,7 +44,7 @@ use rustc_infer::traits::ObligationCause; use rustc_middle::middle::stability; use rustc_middle::ty::adjustment::{Adjust, Adjustment, AllowTwoPhase}; use rustc_middle::ty::error::TypeError::FieldMisMatch; -use rustc_middle::ty::subst::SubstsRef; +use rustc_middle::ty::GenericArgsRef; use rustc_middle::ty::{self, AdtKind, Ty, TypeVisitableExt}; use rustc_session::errors::ExprParenthesesNeeded; use rustc_session::parse::feature_err; @@ -593,8 +593,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // We always require that the type provided as the value for // a type parameter outlives the moment of instantiation. - let substs = self.typeck_results.borrow().node_substs(expr.hir_id); - self.add_wf_bounds(substs, expr); + let args = self.typeck_results.borrow().node_args(expr.hir_id); + self.add_wf_bounds(args, expr); ty } @@ -650,7 +650,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let mut enclosing_breakables = self.enclosing_breakables.borrow_mut(); let Some(ctxt) = enclosing_breakables.opt_find_breakable(target_id) else { // Avoid ICE when `break` is inside a closure (#65383). - return Ty::new_error_with_message(tcx, + return Ty::new_error_with_message( + tcx, expr.span, "break was outside loop, but no error was emitted", ); @@ -1280,7 +1281,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // We could add a "consider `foo::<params>`" suggestion here, but I wasn't able to // trigger this codepath causing `structurally_resolve_type` to emit an error. - self.enforce_context_effects(expr.hir_id, expr.span, method.def_id, method.substs); + self.enforce_context_effects(expr.hir_id, expr.span, method.def_id, method.args); self.write_method_call(expr.hir_id, method); Ok(method) } @@ -1390,11 +1391,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let parent_node = self.tcx.hir().parent_iter(expr.hir_id).find(|(_, node)| { !matches!(node, hir::Node::Expr(hir::Expr { kind: hir::ExprKind::AddrOf(..), .. })) }); - let Some((_, + let Some(( + _, hir::Node::Local(hir::Local { ty: Some(ty), .. }) - | hir::Node::Item(hir::Item { kind: hir::ItemKind::Const(ty, _), .. })) - ) = parent_node else { - return + | hir::Node::Item(hir::Item { kind: hir::ItemKind::Const(ty, _), .. }), + )) = parent_node + else { + return; }; if let hir::TyKind::Array(_, length) = ty.peel_refs().kind && let hir::ArrayLen::Body(hir::AnonConst { hir_id, .. }) = length @@ -1617,7 +1620,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // re-link the regions that EIfEO can erase. self.demand_eqtype(span, adt_ty_hint, adt_ty); - let ty::Adt(adt, substs) = adt_ty.kind() else { + let ty::Adt(adt, args) = adt_ty.kind() else { span_bug!(span, "non-ADT passed to check_expr_struct_fields"); }; let adt_kind = adt.adt_kind(); @@ -1646,7 +1649,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { tcx.check_stability(v_field.did, Some(expr_id), field.span, None); } - self.field_ty(field.span, v_field, substs) + self.field_ty(field.span, v_field, args) } else { error_happened = true; let guar = if let Some(prev_span) = seen_fields.get(&ident) { @@ -1678,7 +1681,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if let Some(mut diag) = diag { if idx == ast_fields.len() - 1 { if remaining_fields.is_empty() { - self.suggest_fru_from_range(field, variant, substs, &mut diag); + self.suggest_fru_from_range(field, variant, args, &mut diag); diag.emit(); } else { diag.stash(field.span, StashKey::MaybeFruTypo); @@ -1718,7 +1721,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let fru_tys = if self.tcx.features().type_changing_struct_update { if adt.is_struct() { // Make some fresh substitutions for our ADT type. - let fresh_substs = self.fresh_substs_for_item(base_expr.span, adt.did()); + let fresh_args = self.fresh_args_for_item(base_expr.span, adt.did()); // We do subtyping on the FRU fields first, so we can // learn exactly what types we expect the base expr // needs constrained to be compatible with the struct @@ -1727,13 +1730,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .fields .iter() .map(|f| { - let fru_ty = self.normalize( - expr_span, - self.field_ty(base_expr.span, f, fresh_substs), - ); + let fru_ty = self + .normalize(expr_span, self.field_ty(base_expr.span, f, fresh_args)); let ident = self.tcx.adjust_ident(f.ident(self.tcx), variant.def_id); if let Some(_) = remaining_fields.remove(&ident) { - let target_ty = self.field_ty(base_expr.span, f, substs); + let target_ty = self.field_ty(base_expr.span, f, args); let cause = self.misc(base_expr.span); match self.at(&cause, self.param_env).sup( DefineOpaqueTypes::No, @@ -1760,7 +1761,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.resolve_vars_if_possible(fru_ty) }) .collect(); - // The use of fresh substs that we have subtyped against + // The use of fresh args that we have subtyped against // our base ADT type's fields allows us to guide inference // along so that, e.g. // ``` @@ -1778,7 +1779,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // `MyStruct<'a, _, F2, C>`, as opposed to just `_`... // This is important to allow coercions to happen in // `other_struct` itself. See `coerce-in-base-expr.rs`. - let fresh_base_ty = Ty::new_adt(self.tcx, *adt, fresh_substs); + let fresh_base_ty = Ty::new_adt(self.tcx, *adt, fresh_args); self.check_expr_has_type_or_error( base_expr, self.resolve_vars_if_possible(fresh_base_ty), @@ -1810,10 +1811,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } }); match adt_ty.kind() { - ty::Adt(adt, substs) if adt.is_struct() => variant + ty::Adt(adt, args) if adt.is_struct() => variant .fields .iter() - .map(|f| self.normalize(expr_span, f.ty(self.tcx, substs))) + .map(|f| self.normalize(expr_span, f.ty(self.tcx, args))) .collect(), _ => { self.tcx @@ -1841,7 +1842,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { remaining_fields, variant, ast_fields, - substs, + args, ); } } @@ -1878,7 +1879,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { remaining_fields: FxHashMap<Ident, (FieldIdx, &ty::FieldDef)>, variant: &'tcx ty::VariantDef, ast_fields: &'tcx [hir::ExprField<'tcx>], - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, ) { let len = remaining_fields.len(); @@ -1917,7 +1918,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { err.span_label(span, format!("missing {remaining_fields_names}{truncated_fields_error}")); if let Some(last) = ast_fields.last() { - self.suggest_fru_from_range(last, variant, substs, &mut err); + self.suggest_fru_from_range(last, variant, args, &mut err); } err.emit(); @@ -1929,7 +1930,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { &self, last_expr_field: &hir::ExprField<'tcx>, variant: &ty::VariantDef, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, err: &mut Diagnostic, ) { // I don't use 'is_range_literal' because only double-sided, half-open ranges count. @@ -1942,7 +1943,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { variant.fields.iter().find(|field| field.ident(self.tcx) == last_expr_field.ident) && let range_def_id = self.tcx.lang_items().range_struct() && variant_field - .and_then(|field| field.ty(self.tcx, substs).ty_adt_def()) + .and_then(|field| field.ty(self.tcx, args).ty_adt_def()) .map(|adt| adt.did()) != range_def_id { @@ -2265,7 +2266,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { while let Some((deref_base_ty, _)) = autoderef.next() { debug!("deref_base_ty: {:?}", deref_base_ty); match deref_base_ty.kind() { - ty::Adt(base_def, substs) if !base_def.is_enum() => { + ty::Adt(base_def, args) if !base_def.is_enum() => { debug!("struct named {:?}", deref_base_ty); let body_hir_id = self.tcx.hir().local_def_id_to_hir_id(self.body_id); let (ident, def_scope) = @@ -2275,7 +2276,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .iter_enumerated() .find(|(_, f)| f.ident(self.tcx).normalize_to_macros_2_0() == ident) { - let field_ty = self.field_ty(expr.span, field, substs); + let field_ty = self.field_ty(expr.span, field, args); // Save the index of all fields regardless of their visibility in case // of error recovery. self.write_field_index(expr.hir_id, index); @@ -2416,7 +2417,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { base: &'tcx hir::Expr<'tcx>, ty: Ty<'tcx>, ) { - let Some(output_ty) = self.get_impl_future_output_ty(ty) else { return; }; + let Some(output_ty) = self.get_impl_future_output_ty(ty) else { + return; + }; let mut add_label = true; if let ty::Adt(def, _) = output_ty.kind() { // no field access on enum type @@ -2711,7 +2714,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // try to add a suggestion in case the field is a nested field of a field of the Adt let mod_id = self.tcx.parent_module(id).to_def_id(); - if let Some((fields, substs)) = + if let Some((fields, args)) = self.get_field_candidates_considering_privacy(span, expr_t, mod_id) { let candidate_fields: Vec<_> = fields @@ -2720,7 +2723,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { span, &|candidate_field, _| candidate_field.ident(self.tcx()) == field, candidate_field, - substs, + args, vec![], mod_id, ) @@ -2775,12 +2778,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { span: Span, base_ty: Ty<'tcx>, mod_id: DefId, - ) -> Option<(impl Iterator<Item = &'tcx ty::FieldDef> + 'tcx, SubstsRef<'tcx>)> { + ) -> Option<(impl Iterator<Item = &'tcx ty::FieldDef> + 'tcx, GenericArgsRef<'tcx>)> { debug!("get_field_candidates(span: {:?}, base_t: {:?}", span, base_ty); for (base_t, _) in self.autoderef(span, base_ty) { match base_t.kind() { - ty::Adt(base_def, substs) if !base_def.is_enum() => { + ty::Adt(base_def, args) if !base_def.is_enum() => { let tcx = self.tcx; let fields = &base_def.non_enum_variant().fields; // Some struct, e.g. some that impl `Deref`, have all private fields @@ -2795,7 +2798,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .filter(move |field| field.vis.is_accessible_from(mod_id, tcx)) // For compile-time reasons put a limit on number of fields we search .take(100), - substs, + args, )); } _ => {} @@ -2811,7 +2814,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { span: Span, matches: &impl Fn(&ty::FieldDef, Ty<'tcx>) -> bool, candidate_field: &ty::FieldDef, - subst: SubstsRef<'tcx>, + subst: GenericArgsRef<'tcx>, mut field_path: Vec<Ident>, mod_id: DefId, ) -> Option<Vec<Ident>> { @@ -2970,9 +2973,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.commit_if_ok(|_| { let ocx = ObligationCtxt::new(self); - let impl_substs = self.fresh_substs_for_item(base_expr.span, impl_def_id); + let impl_args = self.fresh_args_for_item(base_expr.span, impl_def_id); let impl_trait_ref = - self.tcx.impl_trait_ref(impl_def_id).unwrap().subst(self.tcx, impl_substs); + self.tcx.impl_trait_ref(impl_def_id).unwrap().instantiate(self.tcx, impl_args); let cause = self.misc(base_expr.span); // Match the impl self type against the base ty. If this fails, @@ -3004,7 +3007,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ) }, self.param_env, - self.tcx.predicates_of(impl_def_id).instantiate(self.tcx, impl_substs), + self.tcx.predicates_of(impl_def_id).instantiate(self.tcx, impl_args), )); // Normalize the output type, which we can use later on as the @@ -3012,7 +3015,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let element_ty = ocx.normalize( &cause, self.param_env, - Ty::new_projection(self.tcx, index_trait_output_def_id, impl_trait_ref.substs), + Ty::new_projection(self.tcx, index_trait_output_def_id, impl_trait_ref.args), ); let errors = ocx.select_where_possible(); @@ -3020,7 +3023,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // will still delay a span bug in `report_fulfillment_errors`. Ok::<_, NoSolution>(( self.err_ctxt().report_fulfillment_errors(&errors), - impl_trait_ref.substs.type_at(1), + impl_trait_ref.args.type_at(1), element_ty, )) }) @@ -3152,7 +3155,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let container = self.structurally_resolve_type(expr.span, current_container); match container.kind() { - ty::Adt(container_def, substs) if !container_def.is_enum() => { + ty::Adt(container_def, args) if !container_def.is_enum() => { let block = self.tcx.hir().local_def_id_to_hir_id(self.body_id); let (ident, def_scope) = self.tcx.adjust_ident_and_get_scope(field, container_def.did(), block); @@ -3162,7 +3165,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .iter_enumerated() .find(|(_, f)| f.ident(self.tcx).normalize_to_macros_2_0() == ident) { - let field_ty = self.field_ty(expr.span, field, substs); + let field_ty = self.field_ty(expr.span, field, args); // FIXME: DSTs with static alignment should be allowed self.require_type_is_sized(field_ty, expr.span, traits::MiscObligation); diff --git a/compiler/rustc_hir_typeck/src/expr_use_visitor.rs b/compiler/rustc_hir_typeck/src/expr_use_visitor.rs index 0d2e0602e1c..a59061cbf67 100644 --- a/compiler/rustc_hir_typeck/src/expr_use_visitor.rs +++ b/compiler/rustc_hir_typeck/src/expr_use_visitor.rs @@ -549,7 +549,7 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { // Select just those fields of the `with` // expression that will actually be used match with_place.place.ty().kind() { - ty::Adt(adt, substs) if adt.is_struct() => { + ty::Adt(adt, args) if adt.is_struct() => { // Consume those fields of the with expression that are needed. for (f_index, with_field) in adt.non_enum_variant().fields.iter_enumerated() { let is_mentioned = fields @@ -559,7 +559,7 @@ impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> { let field_place = self.mc.cat_projection( &*with_expr, with_place.clone(), - with_field.ty(self.tcx(), substs), + with_field.ty(self.tcx(), args), ProjectionKind::Field(f_index, FIRST_VARIANT), ); self.delegate_consume(&field_place, field_place.hir_id); diff --git a/compiler/rustc_hir_typeck/src/fallback.rs b/compiler/rustc_hir_typeck/src/fallback.rs index a76db6e73a1..5b5986a349f 100644 --- a/compiler/rustc_hir_typeck/src/fallback.rs +++ b/compiler/rustc_hir_typeck/src/fallback.rs @@ -1,8 +1,8 @@ use crate::FnCtxt; use rustc_data_structures::{ - fx::{FxHashMap, FxHashSet}, graph::WithSuccessors, graph::{iterate::DepthFirstSearch, vec_graph::VecGraph}, + unord::{UnordBag, UnordMap, UnordSet}, }; use rustc_middle::ty::{self, Ty}; @@ -83,7 +83,7 @@ impl<'tcx> FnCtxt<'_, 'tcx> { fn fallback_if_possible( &self, ty: Ty<'tcx>, - diverging_fallback: &FxHashMap<Ty<'tcx>, Ty<'tcx>>, + diverging_fallback: &UnordMap<Ty<'tcx>, Ty<'tcx>>, ) { // Careful: we do NOT shallow-resolve `ty`. We know that `ty` // is an unsolved variable, and we determine its fallback @@ -193,7 +193,7 @@ impl<'tcx> FnCtxt<'_, 'tcx> { fn calculate_diverging_fallback( &self, unsolved_variables: &[Ty<'tcx>], - ) -> FxHashMap<Ty<'tcx>, Ty<'tcx>> { + ) -> UnordMap<Ty<'tcx>, Ty<'tcx>> { debug!("calculate_diverging_fallback({:?})", unsolved_variables); // Construct a coercion graph where an edge `A -> B` indicates @@ -210,10 +210,10 @@ impl<'tcx> FnCtxt<'_, 'tcx> { // // These variables are the ones that are targets for fallback to // either `!` or `()`. - let diverging_roots: FxHashSet<ty::TyVid> = self + let diverging_roots: UnordSet<ty::TyVid> = self .diverging_type_vars .borrow() - .iter() + .items() .map(|&ty| self.shallow_resolve(ty)) .filter_map(|ty| ty.ty_vid()) .map(|vid| self.root_var(vid)) @@ -284,8 +284,7 @@ impl<'tcx> FnCtxt<'_, 'tcx> { // For each diverging variable, figure out whether it can // reach a member of N. If so, it falls back to `()`. Else // `!`. - let mut diverging_fallback = FxHashMap::default(); - diverging_fallback.reserve(diverging_vids.len()); + let mut diverging_fallback = UnordMap::with_capacity(diverging_vids.len()); for &diverging_vid in &diverging_vids { let diverging_ty = Ty::new_var(self.tcx, diverging_vid); let root_vid = self.root_var(diverging_vid); @@ -293,14 +292,19 @@ impl<'tcx> FnCtxt<'_, 'tcx> { .depth_first_search(root_vid) .any(|n| roots_reachable_from_non_diverging.visited(n)); - let mut found_infer_var_info = ty::InferVarInfo { self_in_trait: false, output: false }; + let infer_var_infos: UnordBag<_> = self + .inh + .infer_var_info + .borrow() + .items() + .filter(|&(vid, _)| self.infcx.root_var(*vid) == root_vid) + .map(|(_, info)| *info) + .collect(); - for (vid, info) in self.inh.infer_var_info.borrow().iter() { - if self.infcx.root_var(*vid) == root_vid { - found_infer_var_info.self_in_trait |= info.self_in_trait; - found_infer_var_info.output |= info.output; - } - } + let found_infer_var_info = ty::InferVarInfo { + self_in_trait: infer_var_infos.items().any(|info| info.self_in_trait), + output: infer_var_infos.items().any(|info| info.output), + }; if found_infer_var_info.self_in_trait && found_infer_var_info.output { // This case falls back to () to ensure that the code pattern in diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs index 9a80a9c9303..bd7e7a671e6 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs @@ -12,7 +12,7 @@ use rustc_hir::def_id::DefId; use rustc_hir::lang_items::LangItem; use rustc_hir::{ExprKind, GenericArg, Node, QPath}; use rustc_hir_analysis::astconv::generics::{ - check_generic_arg_count_for_call, create_substs_for_generic_args, + check_generic_arg_count_for_call, create_args_for_parent_generic_args, }; use rustc_hir_analysis::astconv::{ AstConv, CreateSubstsForGenericArgsCtxt, ExplicitLateBound, GenericArgCountMismatch, @@ -28,7 +28,7 @@ use rustc_middle::ty::visit::{TypeVisitable, TypeVisitableExt}; use rustc_middle::ty::{ self, AdtKind, CanonicalUserType, GenericParamDefKind, Ty, TyCtxt, UserType, }; -use rustc_middle::ty::{GenericArgKind, SubstsRef, UserSelfTy, UserSubsts}; +use rustc_middle::ty::{GenericArgKind, GenericArgsRef, UserArgs, UserSelfTy}; use rustc_session::lint; use rustc_span::def_id::LocalDefId; use rustc_span::hygiene::DesugaringKind; @@ -169,18 +169,18 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { #[instrument(level = "debug", skip(self))] pub fn write_method_call(&self, hir_id: hir::HirId, method: MethodCallee<'tcx>) { self.write_resolution(hir_id, Ok((DefKind::AssocFn, method.def_id))); - self.write_substs(hir_id, method.substs); + self.write_args(hir_id, method.args); } - pub fn write_substs(&self, node_id: hir::HirId, substs: SubstsRef<'tcx>) { - if !substs.is_empty() { - debug!("write_substs({:?}, {:?}) in fcx {}", node_id, substs, self.tag()); + pub fn write_args(&self, node_id: hir::HirId, args: GenericArgsRef<'tcx>) { + if !args.is_empty() { + debug!("write_args({:?}, {:?}) in fcx {}", node_id, args, self.tag()); - self.typeck_results.borrow_mut().node_substs_mut().insert(node_id, substs); + self.typeck_results.borrow_mut().node_args_mut().insert(node_id, args); } } - /// Given the substs that we just converted from the HIR, try to + /// Given the args that we just converted from the HIR, try to /// canonicalize them and store them as user-given substitutions /// (i.e., substitutions that must be respected by the NLL check). /// @@ -188,19 +188,19 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// occurred**, so that annotations like `Vec<_>` are preserved /// properly. #[instrument(skip(self), level = "debug")] - pub fn write_user_type_annotation_from_substs( + pub fn write_user_type_annotation_from_args( &self, hir_id: hir::HirId, def_id: DefId, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, user_self_ty: Option<UserSelfTy<'tcx>>, ) { debug!("fcx {}", self.tag()); - if Self::can_contain_user_lifetime_bounds((substs, user_self_ty)) { + if Self::can_contain_user_lifetime_bounds((args, user_self_ty)) { let canonicalized = self.canonicalize_user_type_annotation(UserType::TypeOf( def_id, - UserSubsts { substs, user_self_ty }, + UserArgs { args, user_self_ty }, )); debug!(?canonicalized); self.write_user_type_annotation(hir_id, canonicalized); @@ -221,7 +221,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .user_provided_types_mut() .insert(hir_id, canonical_user_type_annotation); } else { - debug!("skipping identity substs"); + debug!("skipping identity args"); } } @@ -306,12 +306,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { &self, span: Span, def_id: DefId, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, ) -> ty::InstantiatedPredicates<'tcx> { let bounds = self.tcx.predicates_of(def_id); - let result = bounds.instantiate(self.tcx, substs); + let result = bounds.instantiate(self.tcx, args); let result = self.normalize(span, result); - debug!("instantiate_bounds(bounds={:?}, substs={:?}) = {:?}", bounds, substs, result); + debug!("instantiate_bounds(bounds={:?}, args={:?}) = {:?}", bounds, args, result); result } @@ -397,11 +397,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ty.normalized } - pub(super) fn user_substs_for_adt(ty: RawTy<'tcx>) -> UserSubsts<'tcx> { + pub(super) fn user_args_for_adt(ty: RawTy<'tcx>) -> UserArgs<'tcx> { match (ty.raw.kind(), ty.normalized.kind()) { - (ty::Adt(_, substs), _) => UserSubsts { substs, user_self_ty: None }, - (_, ty::Adt(adt, substs)) => UserSubsts { - substs, + (ty::Adt(_, args), _) => UserArgs { args, user_self_ty: None }, + (_, ty::Adt(adt, args)) => UserArgs { + args, user_self_ty: Some(UserSelfTy { impl_def_id: adt.did(), self_ty: ty.raw }), }, _ => bug!("non-adt type {:?}", ty), @@ -489,9 +489,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { )); } - /// Registers obligations that all `substs` are well-formed. - pub fn add_wf_bounds(&self, substs: SubstsRef<'tcx>, expr: &hir::Expr<'_>) { - for arg in substs.iter().filter(|arg| { + /// Registers obligations that all `args` are well-formed. + pub fn add_wf_bounds(&self, args: GenericArgsRef<'tcx>, expr: &hir::Expr<'_>) { + for arg in args.iter().filter(|arg| { matches!(arg.unpack(), GenericArgKind::Type(..) | GenericArgKind::Const(..)) }) { self.register_wf_obligation(arg, expr.span, traits::WellFormed(None)); @@ -505,9 +505,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { &self, span: Span, field: &'tcx ty::FieldDef, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, ) -> Ty<'tcx> { - self.normalize(span, field.ty(self.tcx, substs)) + self.normalize(span, field.ty(self.tcx, args)) } pub(in super::super) fn resolve_rvalue_scopes(&self, def_id: DefId) { @@ -554,11 +554,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { debug!(?expr_def_id); // Create the `GeneratorWitness` type that we will unify with `interior`. - let substs = ty::InternalSubsts::identity_for_item( + let args = ty::GenericArgs::identity_for_item( self.tcx, self.tcx.typeck_root_def_id(expr_def_id.to_def_id()), ); - let witness = Ty::new_generator_witness_mir(self.tcx, expr_def_id.to_def_id(), substs); + let witness = Ty::new_generator_witness_mir(self.tcx, expr_def_id.to_def_id(), args); // Unify `interior` with `witness` and collect all the resulting obligations. let span = self.tcx.hir().body(body_id).value.span; @@ -737,7 +737,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // tests/ui/impl-trait/hidden-type-is-opaque-2.rs for examples that hit this path. if formal_ret.has_infer_types() { for ty in ret_ty.walk() { - if let ty::subst::GenericArgKind::Type(ty) = ty.unpack() + if let ty::GenericArgKind::Type(ty) = ty.unpack() && let ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }) = *ty.kind() && let Some(def_id) = def_id.as_local() && self.opaque_type_origin(def_id).is_some() { @@ -784,8 +784,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } else { self.tcx.type_of(def_id) }; - let substs = self.fresh_substs_for_item(span, def_id); - let ty = item_ty.subst(self.tcx, substs); + let args = self.fresh_args_for_item(span, def_id); + let ty = item_ty.instantiate(self.tcx, args); self.write_resolution(hir_id, Ok((def_kind, def_id))); @@ -802,9 +802,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { _ => None, }; if let Some(code) = code { - self.add_required_obligations_with_code(span, def_id, substs, move |_, _| code.clone()); + self.add_required_obligations_with_code(span, def_id, args, move |_, _| code.clone()); } else { - self.add_required_obligations_for_hir(span, def_id, substs, hir_id); + self.add_required_obligations_for_hir(span, def_id, args, hir_id); } (Res::Def(def_kind, def_id), ty) @@ -1205,8 +1205,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let has_self = path_segs.last().is_some_and(|PathSeg(def_id, _)| tcx.generics_of(*def_id).has_self); - let (res, self_ctor_substs) = if let Res::SelfCtor(impl_def_id) = res { - let ty = self.handle_raw_ty(span, tcx.at(span).type_of(impl_def_id).subst_identity()); + let (res, self_ctor_args) = if let Res::SelfCtor(impl_def_id) = res { + let ty = + self.handle_raw_ty(span, tcx.at(span).type_of(impl_def_id).instantiate_identity()); match ty.normalized.ty_adt_def() { Some(adt_def) if adt_def.has_ctor() => { let (ctor_kind, ctor_def_id) = adt_def.non_enum_variant().ctor.unwrap(); @@ -1217,9 +1218,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .emit_err(CtorIsPrivate { span, def: tcx.def_path_str(adt_def.did()) }); } let new_res = Res::Def(DefKind::Ctor(CtorOf::Struct, ctor_kind), ctor_def_id); - let user_substs = Self::user_substs_for_adt(ty); - user_self_ty = user_substs.user_self_ty; - (new_res, Some(user_substs.substs)) + let user_args = Self::user_args_for_adt(ty); + user_self_ty = user_args.user_self_ty; + (new_res, Some(user_args.args)) } _ => { let mut err = tcx.sess.struct_span_err( @@ -1324,7 +1325,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { fn inferred_kind( &mut self, - substs: Option<&[ty::GenericArg<'tcx>]>, + args: Option<&[ty::GenericArg<'tcx>]>, param: &ty::GenericParamDef, infer_args: bool, ) -> ty::GenericArg<'tcx> { @@ -1338,7 +1339,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // If we have a default, then we it doesn't matter that we're not // inferring the type arguments: we provide the default where any // is missing. - tcx.type_of(param.def_id).subst(tcx, substs.unwrap()).into() + tcx.type_of(param.def_id).instantiate(tcx, args.unwrap()).into() } else { // If no type arguments were provided, we have to infer them. // This case also occurs as a result of some malformed input, e.g. @@ -1349,7 +1350,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } GenericParamDefKind::Const { has_default } => { if !infer_args && has_default { - tcx.const_param_default(param.def_id).subst(tcx, substs.unwrap()).into() + tcx.const_param_default(param.def_id) + .instantiate(tcx, args.unwrap()) + .into() } else { self.fcx.var_for_def(self.span, param) } @@ -1358,8 +1361,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } } - let substs_raw = self_ctor_substs.unwrap_or_else(|| { - create_substs_for_generic_args( + let args_raw = self_ctor_args.unwrap_or_else(|| { + create_args_for_parent_generic_args( tcx, def_id, &[], @@ -1376,20 +1379,20 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ) }); - // First, store the "user substs" for later. - self.write_user_type_annotation_from_substs(hir_id, def_id, substs_raw, user_self_ty); + // First, store the "user args" for later. + self.write_user_type_annotation_from_args(hir_id, def_id, args_raw, user_self_ty); // Normalize only after registering type annotations. - let substs = self.normalize(span, substs_raw); + let args = self.normalize(span, args_raw); - self.add_required_obligations_for_hir(span, def_id, &substs, hir_id); + self.add_required_obligations_for_hir(span, def_id, &args, hir_id); // Substitute the values for the type parameters into the type of // the referenced item. let ty = tcx.type_of(def_id); - assert!(!substs.has_escaping_bound_vars()); + assert!(!args.has_escaping_bound_vars()); assert!(!ty.skip_binder().has_escaping_bound_vars()); - let ty_substituted = self.normalize(span, ty.subst(tcx, substs)); + let ty_substituted = self.normalize(span, ty.instantiate(tcx, args)); if let Some(UserSelfTy { impl_def_id, self_ty }) = user_self_ty { // In the case of `Foo<T>::method` and `<Foo<T>>::method`, if `method` @@ -1397,7 +1400,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // type parameters, which we can infer by unifying the provided `Self` // with the substituted impl type. // This also occurs for an enum variant on a type alias. - let impl_ty = self.normalize(span, tcx.type_of(impl_def_id).subst(tcx, substs)); + let impl_ty = self.normalize(span, tcx.type_of(impl_def_id).instantiate(tcx, args)); let self_ty = self.normalize(span, self_ty); match self.at(&self.misc(span), self.param_env).eq( DefineOpaqueTypes::No, @@ -1419,7 +1422,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } debug!("instantiate_value_path: type of {:?} is {:?}", hir_id, ty_substituted); - self.write_substs(hir_id, substs); + self.write_args(hir_id, args); (ty_substituted, res) } @@ -1429,10 +1432,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { &self, span: Span, def_id: DefId, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, hir_id: hir::HirId, ) { - self.add_required_obligations_with_code(span, def_id, substs, |idx, span| { + self.add_required_obligations_with_code(span, def_id, args, |idx, span| { if span.is_dummy() { ObligationCauseCode::ExprItemObligation(def_id, hir_id, idx) } else { @@ -1441,17 +1444,17 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }) } - #[instrument(level = "debug", skip(self, code, span, substs))] + #[instrument(level = "debug", skip(self, code, span, args))] fn add_required_obligations_with_code( &self, span: Span, def_id: DefId, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, code: impl Fn(usize, Span) -> ObligationCauseCode<'tcx>, ) { let param_env = self.param_env; - let bounds = self.instantiate_bounds(span, def_id, &substs); + let bounds = self.instantiate_bounds(span, def_id, &args); for obligation in traits::predicates_for_generics( |idx, predicate_span| { diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/adjust_fulfillment_errors.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/adjust_fulfillment_errors.rs index ed9bb4945af..15ca5808a93 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/adjust_fulfillment_errors.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/adjust_fulfillment_errors.rs @@ -14,19 +14,32 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { &self, error: &mut traits::FulfillmentError<'tcx>, ) -> bool { - let (traits::ExprItemObligation(def_id, hir_id, idx) | traits::ExprBindingObligation(def_id, _, hir_id, idx)) - = *error.obligation.cause.code().peel_derives() else { return false; }; + let (traits::ExprItemObligation(def_id, hir_id, idx) + | traits::ExprBindingObligation(def_id, _, hir_id, idx)) = + *error.obligation.cause.code().peel_derives() + else { + return false; + }; let hir = self.tcx.hir(); - let hir::Node::Expr(expr) = hir.get(hir_id) else { return false; }; + let hir::Node::Expr(expr) = hir.get(hir_id) else { + return false; + }; - let Some(unsubstituted_pred) = - self.tcx.predicates_of(def_id).instantiate_identity(self.tcx).predicates.into_iter().nth(idx) - else { return false; }; + let Some(unsubstituted_pred) = self + .tcx + .predicates_of(def_id) + .instantiate_identity(self.tcx) + .predicates + .into_iter() + .nth(idx) + else { + return false; + }; let generics = self.tcx.generics_of(def_id); - let predicate_substs = match unsubstituted_pred.kind().skip_binder() { - ty::ClauseKind::Trait(pred) => pred.trait_ref.substs.to_vec(), - ty::ClauseKind::Projection(pred) => pred.projection_ty.substs.to_vec(), + let predicate_args = match unsubstituted_pred.kind().skip_binder() { + ty::ClauseKind::Trait(pred) => pred.trait_ref.args.to_vec(), + ty::ClauseKind::Projection(pred) => pred.projection_ty.args.to_vec(), ty::ClauseKind::ConstArgHasType(arg, ty) => { vec![ty.into(), arg.into()] } @@ -35,7 +48,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }; let find_param_matching = |matches: &dyn Fn(ty::ParamTerm) -> bool| { - predicate_substs.iter().find_map(|arg| { + predicate_args.iter().find_map(|arg| { arg.walk().find_map(|arg| { if let ty::GenericArgKind::Type(ty) = arg.unpack() && let ty::Param(param_ty) = *ty.kind() @@ -225,18 +238,18 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { param_to_point_at: ty::GenericArg<'tcx>, segment: &hir::PathSegment<'tcx>, ) -> bool { - let own_substs = self + let own_args = self .tcx .generics_of(def_id) - .own_substs(ty::InternalSubsts::identity_for_item(self.tcx, def_id)); - let Some((index, _)) = own_substs - .iter() - .enumerate() - .find(|(_, arg)| **arg == param_to_point_at) else { return false }; - let Some(arg) = segment - .args() - .args - .get(index) else { return false; }; + .own_args(ty::GenericArgs::identity_for_item(self.tcx, def_id)); + let Some((index, _)) = + own_args.iter().enumerate().find(|(_, arg)| **arg == param_to_point_at) + else { + return false; + }; + let Some(arg) = segment.args().args.get(index) else { + return false; + }; error.obligation.cause.span = arg .span() .find_ancestor_in_same_ctxt(error.obligation.cause.span) @@ -258,7 +271,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { origin.kind && let generics = self.0.tcx.generics_of(self.1) && let Some(index) = generics.param_def_id_to_index(self.0.tcx, def_id) - && let Some(subst) = ty::InternalSubsts::identity_for_item(self.0.tcx, self.1) + && let Some(subst) = ty::GenericArgs::identity_for_item(self.0.tcx, self.1) .get(index as usize) { ControlFlow::Break(*subst) @@ -298,13 +311,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ) -> Option<(&'tcx hir::Expr<'tcx>, Ty<'tcx>)> { let def = self.tcx.adt_def(def_id); - let identity_substs = ty::InternalSubsts::identity_for_item(self.tcx, def_id); + let identity_args = ty::GenericArgs::identity_for_item(self.tcx, def_id); let fields_referencing_param: Vec<_> = def .variant_with_id(variant_def_id) .fields .iter() .filter(|field| { - let field_ty = field.ty(self.tcx, identity_substs); + let field_ty = field.ty(self.tcx, identity_args); find_param_in_ty(field_ty.into(), param_to_point_at) }) .collect(); @@ -315,7 +328,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // same rules that check_expr_struct uses for macro hygiene. if self.tcx.adjust_ident(expr_field.ident, variant_def_id) == field.ident(self.tcx) { - return Some((expr_field.expr, self.tcx.type_of(field.did).subst_identity())); + return Some(( + expr_field.expr, + self.tcx.type_of(field.did).instantiate_identity(), + )); } } } @@ -342,7 +358,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { receiver: Option<&'tcx hir::Expr<'tcx>>, args: &'tcx [hir::Expr<'tcx>], ) -> bool { - let ty = self.tcx.type_of(def_id).subst_identity(); + let ty = self.tcx.type_of(def_id).instantiate_identity(); if !ty.is_fn() { return false; } @@ -484,7 +500,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ty::TraitRef::new( self.tcx, obligation.impl_or_alias_def_id, - ty::InternalSubsts::identity_for_item(self.tcx, obligation.impl_or_alias_def_id), + ty::GenericArgs::identity_for_item(self.tcx, obligation.impl_or_alias_def_id), ) } else { self.tcx @@ -573,9 +589,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Find out which of `in_ty_elements` refer to `param`. // FIXME: It may be better to take the first if there are multiple, // just so that the error points to a smaller expression. - let Some((drill_expr, drill_ty)) = is_iterator_singleton(expr_elements.iter().zip( in_ty_elements.iter()).filter(|(_expr_elem, in_ty_elem)| { - find_param_in_ty((*in_ty_elem).into(), param) - })) else { + let Some((drill_expr, drill_ty)) = + is_iterator_singleton(expr_elements.iter().zip(in_ty_elements.iter()).filter( + |(_expr_elem, in_ty_elem)| find_param_in_ty((*in_ty_elem).into(), param), + )) + else { // The param is not mentioned, or it is mentioned in multiple indexes. return Err(expr); }; @@ -594,7 +612,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { { // First, confirm that this struct is the same one as in the types, and if so, // find the right variant. - let Res::Def(expr_struct_def_kind, expr_struct_def_id) = self.typeck_results.borrow().qpath_res(expr_struct_path, expr.hir_id) else { + let Res::Def(expr_struct_def_kind, expr_struct_def_id) = + self.typeck_results.borrow().qpath_res(expr_struct_path, expr.hir_id) + else { return Err(expr); }; @@ -621,16 +641,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // We need to know which of the generic parameters mentions our target param. // We expect that at least one of them does, since it is expected to be mentioned. - let Some((drill_generic_index, generic_argument_type)) = - is_iterator_singleton( - in_ty_adt_generic_args.iter().enumerate().filter( - |(_index, in_ty_generic)| { - find_param_in_ty(*in_ty_generic, param) - }, - ), - ) else { - return Err(expr); - }; + let Some((drill_generic_index, generic_argument_type)) = is_iterator_singleton( + in_ty_adt_generic_args + .iter() + .enumerate() + .filter(|(_index, in_ty_generic)| find_param_in_ty(*in_ty_generic, param)), + ) else { + return Err(expr); + }; let struct_generic_parameters: &ty::Generics = self.tcx.generics_of(in_ty_adt.did()); if drill_generic_index >= struct_generic_parameters.params.len() { @@ -703,7 +721,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }; // This is (possibly) a constructor call, like `Some(...)` or `MyStruct(a, b, c)`. - let Res::Def(expr_struct_def_kind, expr_ctor_def_id) = self.typeck_results.borrow().qpath_res(expr_callee_path, expr_callee.hir_id) else { + let Res::Def(expr_struct_def_kind, expr_ctor_def_id) = + self.typeck_results.borrow().qpath_res(expr_callee_path, expr_callee.hir_id) + else { return Err(expr); }; @@ -744,16 +764,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // We need to know which of the generic parameters mentions our target param. // We expect that at least one of them does, since it is expected to be mentioned. - let Some((drill_generic_index, generic_argument_type)) = - is_iterator_singleton( - in_ty_adt_generic_args.iter().enumerate().filter( - |(_index, in_ty_generic)| { - find_param_in_ty(*in_ty_generic, param) - }, - ), - ) else { - return Err(expr); - }; + let Some((drill_generic_index, generic_argument_type)) = is_iterator_singleton( + in_ty_adt_generic_args + .iter() + .enumerate() + .filter(|(_index, in_ty_generic)| find_param_in_ty(*in_ty_generic, param)), + ) else { + return Err(expr); + }; let struct_generic_parameters: &ty::Generics = self.tcx.generics_of(in_ty_adt.did()); if drill_generic_index >= struct_generic_parameters.params.len() { @@ -794,7 +812,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .iter() .map(|field| field.ty(self.tcx, *in_ty_adt_generic_args)) .enumerate() - .filter(|(_index, field_type)| find_param_in_ty((*field_type).into(), param)) + .filter(|(_index, field_type)| find_param_in_ty((*field_type).into(), param)), ) else { return Err(expr); }; @@ -846,7 +864,7 @@ fn find_param_in_ty<'tcx>( // This logic may seem a bit strange, but typically when // we have a projection type in a function signature, the // argument that's being passed into that signature is - // not actually constraining that projection's substs in + // not actually constraining that projection's args in // a meaningful way. So we skip it, and see improvements // in some UI tests. walk.skip_current_subtree(); diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs index 41f5fafe72f..a9610009db1 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs @@ -93,7 +93,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { expected: Expectation<'tcx>, ) -> Ty<'tcx> { let has_error = match method { - Ok(method) => method.substs.references_error() || method.sig.references_error(), + Ok(method) => method.args.references_error() || method.sig.references_error(), Err(_) => true, }; if has_error { @@ -753,11 +753,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } errors.retain(|error| { - let Error::Invalid( - provided_idx, - expected_idx, - Compatibility::Incompatible(Some(e)), - ) = error else { return true }; + let Error::Invalid(provided_idx, expected_idx, Compatibility::Incompatible(Some(e))) = + error + else { + return true; + }; let (provided_ty, provided_span) = provided_arg_tys[*provided_idx]; let trace = mk_trace(provided_span, formal_and_expected_inputs[*expected_idx], provided_ty); @@ -1366,7 +1366,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } Res::Def(DefKind::Variant, _) => match ty.normalized.ty_adt_def() { Some(adt) => { - Some((adt.variant_of_res(def), adt.did(), Self::user_substs_for_adt(ty))) + Some((adt.variant_of_res(def), adt.did(), Self::user_args_for_adt(ty))) } _ => bug!("unexpected type: {:?}", ty.normalized), }, @@ -1374,21 +1374,21 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { | Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } => match ty.normalized.ty_adt_def() { Some(adt) if !adt.is_enum() => { - Some((adt.non_enum_variant(), adt.did(), Self::user_substs_for_adt(ty))) + Some((adt.non_enum_variant(), adt.did(), Self::user_args_for_adt(ty))) } _ => None, }, _ => bug!("unexpected definition: {:?}", def), }; - if let Some((variant, did, ty::UserSubsts { substs, user_self_ty })) = variant { - debug!("check_struct_path: did={:?} substs={:?}", did, substs); + if let Some((variant, did, ty::UserArgs { args, user_self_ty })) = variant { + debug!("check_struct_path: did={:?} args={:?}", did, args); // Register type annotation. - self.write_user_type_annotation_from_substs(hir_id, did, substs, user_self_ty); + self.write_user_type_annotation_from_args(hir_id, did, args, user_self_ty); // Check bounds on type arguments used in the path. - self.add_required_obligations_for_hir(path_span, did, substs, hir_id); + self.add_required_obligations_for_hir(path_span, did, args, hir_id); Ok((variant, ty.normalized)) } else { diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs index 20b34df99b2..6a82b00211e 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs @@ -288,21 +288,23 @@ impl<'a, 'tcx> AstConv<'tcx> for FnCtxt<'a, 'tcx> { poly_trait_ref, ); - let item_substs = self.astconv().create_substs_for_associated_item( + let item_args = self.astconv().create_args_for_associated_item( span, item_def_id, item_segment, - trait_ref.substs, + trait_ref.args, ); - Ty::new_projection(self.tcx(), item_def_id, item_substs) + Ty::new_projection(self.tcx(), item_def_id, item_args) } fn probe_adt(&self, span: Span, ty: Ty<'tcx>) -> Option<ty::AdtDef<'tcx>> { match ty.kind() { ty::Adt(adt_def, _) => Some(*adt_def), // FIXME(#104767): Should we handle bound regions here? - ty::Alias(ty::Projection | ty::Inherent, _) if !ty.has_escaping_bound_vars() => { + ty::Alias(ty::Projection | ty::Inherent | ty::Weak, _) + if !ty.has_escaping_bound_vars() => + { self.normalize(span, ty).ty_adt_def() } _ => None, diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs index 79a7c016185..ec19d017c25 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs @@ -97,8 +97,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { found: Ty<'tcx>, can_satisfy: impl FnOnce(Ty<'tcx>) -> bool, ) -> bool { - let Some((def_id_or_name, output, inputs)) = self.extract_callable_info(found) - else { return false; }; + let Some((def_id_or_name, output, inputs)) = self.extract_callable_info(found) else { + return false; + }; if can_satisfy(output) { let (sugg_call, mut applicability) = match inputs.len() { 0 => ("".to_string(), Applicability::MachineApplicable), @@ -180,10 +181,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { rhs_ty: Ty<'tcx>, can_satisfy: impl FnOnce(Ty<'tcx>, Ty<'tcx>) -> bool, ) -> bool { - let Some((_, lhs_output_ty, lhs_inputs)) = self.extract_callable_info(lhs_ty) - else { return false; }; - let Some((_, rhs_output_ty, rhs_inputs)) = self.extract_callable_info(rhs_ty) - else { return false; }; + let Some((_, lhs_output_ty, lhs_inputs)) = self.extract_callable_info(lhs_ty) else { + return false; + }; + let Some((_, rhs_output_ty, rhs_inputs)) = self.extract_callable_info(rhs_ty) else { + return false; + }; if can_satisfy(lhs_output_ty, rhs_output_ty) { let mut sugg = vec![]; @@ -392,7 +395,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { vec![(expr.span.shrink_to_hi(), format!(".{}()", conversion_method.name))] }; let struct_pat_shorthand_field = - self.maybe_get_struct_pattern_shorthand_field(expr); + self.tcx.hir().maybe_get_struct_pattern_shorthand_field(expr); if let Some(name) = struct_pat_shorthand_field { sugg.insert(0, (expr.span.shrink_to_lo(), format!("{}: ", name))); } @@ -478,23 +481,23 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { found_ty: Ty<'tcx>, expected_ty: Ty<'tcx>, ) -> Option<(Ty<'tcx>, Ty<'tcx>, Option<(Ty<'tcx>, Ty<'tcx>)>)> { - let ty::Adt(found_adt, found_substs) = found_ty.peel_refs().kind() else { + let ty::Adt(found_adt, found_args) = found_ty.peel_refs().kind() else { return None; }; - let ty::Adt(expected_adt, expected_substs) = expected_ty.kind() else { + let ty::Adt(expected_adt, expected_args) = expected_ty.kind() else { return None; }; if self.tcx.is_diagnostic_item(sym::Option, found_adt.did()) && self.tcx.is_diagnostic_item(sym::Option, expected_adt.did()) { - Some((found_substs.type_at(0), expected_substs.type_at(0), None)) + Some((found_args.type_at(0), expected_args.type_at(0), None)) } else if self.tcx.is_diagnostic_item(sym::Result, found_adt.did()) && self.tcx.is_diagnostic_item(sym::Result, expected_adt.did()) { Some(( - found_substs.type_at(0), - expected_substs.type_at(0), - Some((found_substs.type_at(1), expected_substs.type_at(1))), + found_args.type_at(0), + expected_args.type_at(0), + Some((found_args.type_at(1), expected_args.type_at(1))), )) } else { None @@ -635,7 +638,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // is and we were expecting a Box, ergo Pin<Box<expected>>, we // can suggest Box::pin. let parent = self.tcx.hir().parent_id(expr.hir_id); - let Some(Node::Expr(Expr { kind: ExprKind::Call(fn_name, _), .. })) = self.tcx.hir().find(parent) else { + let Some(Node::Expr(Expr { kind: ExprKind::Call(fn_name, _), .. })) = + self.tcx.hir().find(parent) + else { return false; }; match fn_name.kind { @@ -758,9 +763,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if let Some(found) = found.make_suggestable(self.tcx, false) { err.subdiagnostic(AddReturnTypeSuggestion::Add { span, found: found.to_string() }); return true; - } else if let ty::Closure(_, substs) = found.kind() + } else if let ty::Closure(_, args) = found.kind() // FIXME(compiler-errors): Get better at printing binders... - && let closure = substs.as_closure() + && let closure = args.as_closure() && closure.sig().is_suggestable(self.tcx, false) { err.subdiagnostic(AddReturnTypeSuggestion::Add { span, found: closure.print_as_impl_trait().to_string() }); @@ -850,12 +855,18 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn( - hir::FnSig { decl: hir::FnDecl { inputs: fn_parameters, output: fn_return, .. }, .. }, + hir::FnSig { + decl: hir::FnDecl { inputs: fn_parameters, output: fn_return, .. }, + .. + }, hir::Generics { params, predicates, .. }, _body_id, ), .. - })) = fn_node else { return }; + })) = fn_node + else { + return; + }; if params.get(expected_ty_as_param.index as usize).is_none() { return; @@ -1058,7 +1069,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ) .must_apply_modulo_regions() { - let suggestion = match self.maybe_get_struct_pattern_shorthand_field(expr) { + let suggestion = match self.tcx.hir().maybe_get_struct_pattern_shorthand_field(expr) { Some(ident) => format!(": {}.clone()", ident), None => ".clone()".to_string() }; @@ -1081,15 +1092,19 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { expr_ty: Ty<'tcx>, expected_ty: Ty<'tcx>, ) -> bool { - let ty::Adt(adt_def, substs) = expr_ty.kind() else { return false; }; - let ty::Adt(expected_adt_def, expected_substs) = expected_ty.kind() else { return false; }; + let ty::Adt(adt_def, args) = expr_ty.kind() else { + return false; + }; + let ty::Adt(expected_adt_def, expected_args) = expected_ty.kind() else { + return false; + }; if adt_def != expected_adt_def { return false; } let mut suggest_copied_or_cloned = || { - let expr_inner_ty = substs.type_at(0); - let expected_inner_ty = expected_substs.type_at(0); + let expr_inner_ty = args.type_at(0); + let expected_inner_ty = expected_args.type_at(0); if let &ty::Ref(_, ty, hir::Mutability::Not) = expr_inner_ty.kind() && self.can_eq(self.param_env, ty, expected_inner_ty) { @@ -1129,7 +1144,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if let Some(result_did) = self.tcx.get_diagnostic_item(sym::Result) && adt_def.did() == result_did // Check that the error types are equal - && self.can_eq(self.param_env, substs.type_at(1), expected_substs.type_at(1)) + && self.can_eq(self.param_env, args.type_at(1), expected_args.type_at(1)) { return suggest_copied_or_cloned(); } else if let Some(option_did) = self.tcx.get_diagnostic_item(sym::Option) @@ -1205,7 +1220,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { return false; } - let ty::Adt(def, _) = expr_ty.peel_refs().kind() else { return false; }; + let ty::Adt(def, _) = expr_ty.peel_refs().kind() else { + return false; + }; if !self.tcx.is_diagnostic_item(sym::Option, def.did()) { return false; } @@ -1230,7 +1247,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { return false; } - let suggestion = match self.maybe_get_struct_pattern_shorthand_field(expr) { + let suggestion = match self.tcx.hir().maybe_get_struct_pattern_shorthand_field(expr) { Some(ident) => format!(": {}.is_some()", ident), None => ".is_some()".to_string(), }; @@ -1327,7 +1344,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { node: rustc_ast::LitKind::Int(lit, rustc_ast::LitIntType::Unsuffixed), span, }) => { - let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(*span) else { return false; }; + let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(*span) else { + return false; + }; if !(snippet.starts_with("0x") || snippet.starts_with("0X")) { return false; } @@ -1367,10 +1386,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }; // Provided expression needs to be a literal `0`. - let ExprKind::Lit(Spanned { - node: rustc_ast::LitKind::Int(0, _), - span, - }) = expr.kind else { + let ExprKind::Lit(Spanned { node: rustc_ast::LitKind::Int(0, _), span }) = expr.kind else { return false; }; @@ -1401,7 +1417,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { expr: &hir::Expr<'_>, expected_ty: Ty<'tcx>, ) -> bool { - let Some((DefKind::AssocFn, old_def_id)) = self.typeck_results.borrow().type_dependent_def(expr.hir_id) else { + let Some((DefKind::AssocFn, old_def_id)) = + self.typeck_results.borrow().type_dependent_def(expr.hir_id) + else { return false; }; let old_item_name = self.tcx.item_name(old_def_id); @@ -1457,7 +1475,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Same item return false; } - let item_ty = self.tcx.type_of(item.def_id).subst_identity(); + let item_ty = self.tcx.type_of(item.def_id).instantiate_identity(); // FIXME(compiler-errors): This check is *so* rudimentary if item_ty.has_param() { return false; @@ -1494,8 +1512,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { found_ty: Ty<'tcx>, expr: &hir::Expr<'_>, ) { - let hir::ExprKind::MethodCall(segment, callee_expr, &[], _) = expr.kind else { return; }; - let Some(clone_trait_did) = self.tcx.lang_items().clone_trait() else { return; }; + let hir::ExprKind::MethodCall(segment, callee_expr, &[], _) = expr.kind else { + return; + }; + let Some(clone_trait_did) = self.tcx.lang_items().clone_trait() else { + return; + }; let ty::Ref(_, pointee_ty, _) = found_ty.kind() else { return }; let results = self.typeck_results.borrow(); // First, look for a `Clone::clone` call diff --git a/compiler/rustc_hir_typeck/src/generator_interior/drop_ranges/cfg_build.rs b/compiler/rustc_hir_typeck/src/generator_interior/drop_ranges/cfg_build.rs index b84c4918649..b059db23bb4 100644 --- a/compiler/rustc_hir_typeck/src/generator_interior/drop_ranges/cfg_build.rs +++ b/compiler/rustc_hir_typeck/src/generator_interior/drop_ranges/cfg_build.rs @@ -6,7 +6,7 @@ use hir::{ intravisit::{self, Visitor}, Body, Expr, ExprKind, Guard, HirId, LoopIdError, }; -use rustc_data_structures::fx::{FxHashMap, FxHashSet}; +use rustc_data_structures::unord::{UnordMap, UnordSet}; use rustc_hir as hir; use rustc_index::IndexVec; use rustc_infer::infer::InferCtxt; @@ -28,7 +28,7 @@ pub(super) fn build_control_flow_graph<'tcx>( consumed_borrowed_places: ConsumedAndBorrowedPlaces, body: &'tcx Body<'tcx>, num_exprs: usize, -) -> (DropRangesBuilder, FxHashSet<HirId>) { +) -> (DropRangesBuilder, UnordSet<HirId>) { let mut drop_range_visitor = DropRangeVisitor::new( infcx, typeck_results, @@ -528,7 +528,7 @@ impl DropRangesBuilder { hir: Map<'_>, num_exprs: usize, ) -> Self { - let mut tracked_value_map = FxHashMap::<_, TrackedValueIndex>::default(); + let mut tracked_value_map = UnordMap::<_, TrackedValueIndex>::default(); let mut next = <_>::from(0u32); for value in tracked_values { for_each_consumable(hir, value, |value| { diff --git a/compiler/rustc_hir_typeck/src/generator_interior/drop_ranges/mod.rs b/compiler/rustc_hir_typeck/src/generator_interior/drop_ranges/mod.rs index ecafbd668e2..e01dcf83a38 100644 --- a/compiler/rustc_hir_typeck/src/generator_interior/drop_ranges/mod.rs +++ b/compiler/rustc_hir_typeck/src/generator_interior/drop_ranges/mod.rs @@ -17,7 +17,7 @@ use self::record_consumed_borrow::find_consumed_and_borrowed; use crate::FnCtxt; use hir::def_id::DefId; use hir::{Body, HirId, HirIdMap, Node}; -use rustc_data_structures::fx::{FxHashMap, FxHashSet}; +use rustc_data_structures::unord::{UnordMap, UnordSet}; use rustc_hir as hir; use rustc_index::bit_set::BitSet; use rustc_index::IndexVec; @@ -63,7 +63,7 @@ pub fn compute_drop_ranges<'a, 'tcx>( // If drop range tracking is not enabled, skip all the analysis and produce an // empty set of DropRanges. DropRanges { - tracked_value_map: FxHashMap::default(), + tracked_value_map: UnordMap::default(), nodes: IndexVec::new(), borrowed_temporaries: None, } @@ -182,9 +182,9 @@ impl TryFrom<&PlaceWithHirId<'_>> for TrackedValue { } pub struct DropRanges { - tracked_value_map: FxHashMap<TrackedValue, TrackedValueIndex>, + tracked_value_map: UnordMap<TrackedValue, TrackedValueIndex>, nodes: IndexVec<PostOrderId, NodeInfo>, - borrowed_temporaries: Option<FxHashSet<HirId>>, + borrowed_temporaries: Option<UnordSet<HirId>>, } impl DropRanges { @@ -227,7 +227,7 @@ struct DropRangesBuilder { /// (see NodeInfo::drop_state). The hir_id_map field stores the mapping /// from HirIds to the HirIdIndex that is used to represent that value in /// bitvector. - tracked_value_map: FxHashMap<TrackedValue, TrackedValueIndex>, + tracked_value_map: UnordMap<TrackedValue, TrackedValueIndex>, /// When building the control flow graph, we don't always know the /// post-order index of the target node at the point we encounter it. diff --git a/compiler/rustc_hir_typeck/src/generator_interior/drop_ranges/record_consumed_borrow.rs b/compiler/rustc_hir_typeck/src/generator_interior/drop_ranges/record_consumed_borrow.rs index 8ab0bd535d6..50a3bbf49d5 100644 --- a/compiler/rustc_hir_typeck/src/generator_interior/drop_ranges/record_consumed_borrow.rs +++ b/compiler/rustc_hir_typeck/src/generator_interior/drop_ranges/record_consumed_borrow.rs @@ -4,7 +4,7 @@ use crate::{ FnCtxt, }; use hir::{def_id::DefId, Body, HirId, HirIdMap}; -use rustc_data_structures::fx::FxHashSet; +use rustc_data_structures::{fx::FxIndexSet, unord::UnordSet}; use rustc_hir as hir; use rustc_middle::ty::{ParamEnv, TyCtxt}; use rustc_middle::{ @@ -30,13 +30,13 @@ pub(super) struct ConsumedAndBorrowedPlaces { /// /// Note that this set excludes "partial drops" -- for example, a statement like `drop(x.y)` is /// not considered a drop of `x`, although it would be a drop of `x.y`. - pub(super) consumed: HirIdMap<FxHashSet<TrackedValue>>, + pub(super) consumed: HirIdMap<FxIndexSet<TrackedValue>>, /// A set of hir-ids of values or variables that are borrowed at some point within the body. - pub(super) borrowed: FxHashSet<TrackedValue>, + pub(super) borrowed: UnordSet<TrackedValue>, /// A set of hir-ids of values or variables that are borrowed at some point within the body. - pub(super) borrowed_temporaries: FxHashSet<HirId>, + pub(super) borrowed_temporaries: UnordSet<HirId>, } /// Works with ExprUseVisitor to find interesting values for the drop range analysis. diff --git a/compiler/rustc_hir_typeck/src/inherited.rs b/compiler/rustc_hir_typeck/src/inherited.rs index d5619af2aae..7064484a40f 100644 --- a/compiler/rustc_hir_typeck/src/inherited.rs +++ b/compiler/rustc_hir_typeck/src/inherited.rs @@ -1,6 +1,6 @@ use super::callee::DeferredCallResolution; -use rustc_data_structures::fx::{FxHashMap, FxHashSet}; +use rustc_data_structures::unord::{UnordMap, UnordSet}; use rustc_hir as hir; use rustc_hir::def_id::LocalDefId; use rustc_hir::HirIdMap; @@ -61,9 +61,9 @@ pub struct Inherited<'tcx> { /// Whenever we introduce an adjustment from `!` into a type variable, /// we record that type variable here. This is later used to inform /// fallback. See the `fallback` module for details. - pub(super) diverging_type_vars: RefCell<FxHashSet<Ty<'tcx>>>, + pub(super) diverging_type_vars: RefCell<UnordSet<Ty<'tcx>>>, - pub(super) infer_var_info: RefCell<FxHashMap<ty::TyVid, ty::InferVarInfo>>, + pub(super) infer_var_info: RefCell<UnordMap<ty::TyVid, ty::InferVarInfo>>, } impl<'tcx> Deref for Inherited<'tcx> { diff --git a/compiler/rustc_hir_typeck/src/intrinsicck.rs b/compiler/rustc_hir_typeck/src/intrinsicck.rs index e58efc9d1e3..2d85451c9e1 100644 --- a/compiler/rustc_hir_typeck/src/intrinsicck.rs +++ b/compiler/rustc_hir_typeck/src/intrinsicck.rs @@ -11,7 +11,7 @@ use super::FnCtxt; /// If the type is `Option<T>`, it will return `T`, otherwise /// the type itself. Works on most `Option`-like types. fn unpack_option_like<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> { - let ty::Adt(def, substs) = *ty.kind() else { return ty }; + let ty::Adt(def, args) = *ty.kind() else { return ty }; if def.variants().len() == 2 && !def.repr().c() && def.repr().int.is_none() { let data_idx; @@ -28,7 +28,7 @@ fn unpack_option_like<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> { } if def.variant(data_idx).fields.len() == 1 { - return def.variant(data_idx).single_field().ty(tcx, substs); + return def.variant(data_idx).single_field().ty(tcx, args); } } diff --git a/compiler/rustc_hir_typeck/src/lib.rs b/compiler/rustc_hir_typeck/src/lib.rs index 6f82ffcfe4a..28e7f290737 100644 --- a/compiler/rustc_hir_typeck/src/lib.rs +++ b/compiler/rustc_hir_typeck/src/lib.rs @@ -6,7 +6,6 @@ #![feature(min_specialization)] #![feature(control_flow_enum)] #![feature(option_as_slice)] -#![allow(rustc::potential_query_instability)] #![recursion_limit = "256"] #[macro_use] @@ -141,11 +140,11 @@ fn has_typeck_results(tcx: TyCtxt<'_>, def_id: DefId) -> bool { } fn used_trait_imports(tcx: TyCtxt<'_>, def_id: LocalDefId) -> &UnordSet<LocalDefId> { - &*tcx.typeck(def_id).used_trait_imports + &tcx.typeck(def_id).used_trait_imports } fn typeck<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> &ty::TypeckResults<'tcx> { - let fallback = move || tcx.type_of(def_id.to_def_id()).subst_identity(); + let fallback = move || tcx.type_of(def_id.to_def_id()).instantiate_identity(); typeck_with_fallback(tcx, def_id, fallback) } @@ -195,7 +194,7 @@ fn typeck_with_fallback<'tcx>( let fn_sig = if rustc_hir_analysis::collect::get_infer_ret_ty(&decl.output).is_some() { fcx.astconv().ty_of_fn(id, header.unsafety, header.abi, decl, None, None) } else { - tcx.fn_sig(def_id).subst_identity() + tcx.fn_sig(def_id).instantiate_identity() }; check_abi(tcx, id, span, fn_sig.abi()); diff --git a/compiler/rustc_hir_typeck/src/mem_categorization.rs b/compiler/rustc_hir_typeck/src/mem_categorization.rs index a1aa090841a..0700e2e0554 100644 --- a/compiler/rustc_hir_typeck/src/mem_categorization.rs +++ b/compiler/rustc_hir_typeck/src/mem_categorization.rs @@ -595,7 +595,7 @@ impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> { fn total_fields_in_tuple(&self, pat_hir_id: hir::HirId, span: Span) -> McResult<usize> { let ty = self.typeck_results.node_type(pat_hir_id); match ty.kind() { - ty::Tuple(substs) => Ok(substs.len()), + ty::Tuple(args) => Ok(args.len()), _ => { self.tcx().sess.delay_span_bug(span, "tuple pattern not applied to a tuple"); Err(()) diff --git a/compiler/rustc_hir_typeck/src/method/confirm.rs b/compiler/rustc_hir_typeck/src/method/confirm.rs index 87edb803148..6835782b5bd 100644 --- a/compiler/rustc_hir_typeck/src/method/confirm.rs +++ b/compiler/rustc_hir_typeck/src/method/confirm.rs @@ -5,7 +5,7 @@ use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_hir::GenericArg; use rustc_hir_analysis::astconv::generics::{ - check_generic_arg_count_for_call, create_substs_for_generic_args, + check_generic_arg_count_for_call, create_args_for_parent_generic_args, }; use rustc_hir_analysis::astconv::{AstConv, CreateSubstsForGenericArgsCtxt, IsMethodCall}; use rustc_infer::infer::{self, DefineOpaqueTypes, InferOk}; @@ -13,9 +13,9 @@ use rustc_middle::traits::{ObligationCauseCode, UnifyReceiverContext}; use rustc_middle::ty::adjustment::{Adjust, Adjustment, PointerCoercion}; use rustc_middle::ty::adjustment::{AllowTwoPhase, AutoBorrow, AutoBorrowMutability}; use rustc_middle::ty::fold::TypeFoldable; -use rustc_middle::ty::subst::{self, SubstsRef}; -use rustc_middle::ty::{self, GenericParamDefKind, Ty, TyCtxt}; -use rustc_middle::ty::{InternalSubsts, UserSubsts, UserType}; +use rustc_middle::ty::{ + self, GenericArgs, GenericArgsRef, GenericParamDefKind, Ty, TyCtxt, UserArgs, UserType, +}; use rustc_span::{Span, DUMMY_SP}; use rustc_trait_selection::traits; @@ -96,13 +96,13 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { let self_ty = self.adjust_self_ty(unadjusted_self_ty, &pick); // Create substitutions for the method's type parameters. - let rcvr_substs = self.fresh_receiver_substs(self_ty, &pick); - let all_substs = self.instantiate_method_substs(&pick, segment, rcvr_substs); + let rcvr_args = self.fresh_receiver_args(self_ty, &pick); + let all_args = self.instantiate_method_args(&pick, segment, rcvr_args); - debug!("rcvr_substs={rcvr_substs:?}, all_substs={all_substs:?}"); + debug!("rcvr_args={rcvr_args:?}, all_args={all_args:?}"); // Create the final signature for the method, replacing late-bound regions. - let (method_sig, method_predicates) = self.instantiate_method_sig(&pick, all_substs); + let (method_sig, method_predicates) = self.instantiate_method_sig(&pick, all_args); // If there is a `Self: Sized` bound and `Self` is a trait object, it is possible that // something which derefs to `Self` actually implements the trait and the caller @@ -112,10 +112,10 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { // In that case, we'll error anyway, but we'll also re-run the search with all traits // in scope, and if we find another method which can be used, we'll output an // appropriate hint suggesting to import the trait. - let filler_substs = rcvr_substs + let filler_args = rcvr_args .extend_to(self.tcx, pick.item.def_id, |def, _| self.tcx.mk_param_from_def(def)); let illegal_sized_bound = self.predicates_require_illegal_sized_bound( - self.tcx.predicates_of(pick.item.def_id).instantiate(self.tcx, filler_substs), + self.tcx.predicates_of(pick.item.def_id).instantiate(self.tcx, filler_args), ); // Unify the (adjusted) self type with what the method expects. @@ -129,7 +129,7 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { "confirm: self_ty={:?} method_sig_rcvr={:?} method_sig={:?} method_predicates={:?}", self_ty, method_sig_rcvr, method_sig, method_predicates ); - self.unify_receivers(self_ty, method_sig_rcvr, &pick, all_substs); + self.unify_receivers(self_ty, method_sig_rcvr, &pick, all_args); let (method_sig, method_predicates) = self.normalize(self.span, (method_sig, method_predicates)); @@ -144,7 +144,7 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { if illegal_sized_bound.is_none() { self.add_obligations( Ty::new_fn_ptr(self.tcx, method_sig), - all_substs, + all_args, method_predicates, pick.item.def_id, ); @@ -153,7 +153,7 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { // Create the final `MethodCallee`. let callee = MethodCallee { def_id: pick.item.def_id, - substs: all_substs, + args: all_args, sig: method_sig.skip_binder(), }; ConfirmResult { callee, illegal_sized_bound } @@ -171,7 +171,8 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { // time writing the results into the various typeck results. let mut autoderef = self.autoderef(self.call_expr.span, unadjusted_self_ty); let Some((ty, n)) = autoderef.nth(pick.autoderefs) else { - return Ty::new_error_with_message(self.tcx, + return Ty::new_error_with_message( + self.tcx, rustc_span::DUMMY_SP, format!("failed autoderef {}", pick.autoderefs), ); @@ -251,11 +252,11 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { /// /// Note that this substitution may include late-bound regions from the impl level. If so, /// these are instantiated later in the `instantiate_method_sig` routine. - fn fresh_receiver_substs( + fn fresh_receiver_args( &mut self, self_ty: Ty<'tcx>, pick: &probe::Pick<'tcx>, - ) -> SubstsRef<'tcx> { + ) -> GenericArgsRef<'tcx> { match pick.kind { probe::InherentImplPick => { let impl_def_id = pick.item.container_id(self.tcx); @@ -264,7 +265,7 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { "impl {:?} is not an inherent impl", impl_def_id ); - self.fresh_substs_for_item(self.span, impl_def_id) + self.fresh_args_for_item(self.span, impl_def_id) } probe::ObjectPick => { @@ -288,7 +289,7 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { "original_poly_trait_ref={:?} upcast_trait_ref={:?} target_trait={:?}", original_poly_trait_ref, upcast_trait_ref, trait_def_id ); - upcast_trait_ref.substs + upcast_trait_ref.args }) } @@ -300,13 +301,13 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { // the process we will unify the transformed-self-type // of the method with the actual type in order to // unify some of these variables. - self.fresh_substs_for_item(self.span, trait_def_id) + self.fresh_args_for_item(self.span, trait_def_id) } probe::WhereClausePick(poly_trait_ref) => { // Where clauses can have bound regions in them. We need to instantiate // those to convert from a poly-trait-ref to a trait-ref. - self.instantiate_binder_with_fresh_vars(poly_trait_ref).substs + self.instantiate_binder_with_fresh_vars(poly_trait_ref).args } } } @@ -343,12 +344,12 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { }) } - fn instantiate_method_substs( + fn instantiate_method_args( &mut self, pick: &probe::Pick<'tcx>, seg: &hir::PathSegment<'_>, - parent_substs: SubstsRef<'tcx>, - ) -> SubstsRef<'tcx> { + parent_args: GenericArgsRef<'tcx>, + ) -> GenericArgsRef<'tcx> { // Determine the values for the generic parameters of the method. // If they were not explicitly supplied, just construct fresh // variables. @@ -365,7 +366,7 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { // Create subst for early-bound lifetime parameters, combining // parameters from the type and those from the method. - assert_eq!(generics.parent_count, parent_substs.len()); + assert_eq!(generics.parent_count, parent_args.len()); struct MethodSubstsCtxt<'a, 'tcx> { cfcx: &'a ConfirmContext<'a, 'tcx>, @@ -389,7 +390,7 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { &mut self, param: &ty::GenericParamDef, arg: &GenericArg<'_>, - ) -> subst::GenericArg<'tcx> { + ) -> ty::GenericArg<'tcx> { match (¶m.kind, arg) { (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => { self.cfcx.fcx.astconv().ast_region_to_region(lt, Some(param)).into() @@ -421,31 +422,31 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { fn inferred_kind( &mut self, - _substs: Option<&[subst::GenericArg<'tcx>]>, + _args: Option<&[ty::GenericArg<'tcx>]>, param: &ty::GenericParamDef, _infer_args: bool, - ) -> subst::GenericArg<'tcx> { + ) -> ty::GenericArg<'tcx> { self.cfcx.var_for_def(self.cfcx.span, param) } } - let substs = create_substs_for_generic_args( + let args = create_args_for_parent_generic_args( self.tcx, pick.item.def_id, - parent_substs, + parent_args, false, None, &arg_count_correct, &mut MethodSubstsCtxt { cfcx: self, pick, seg }, ); - // When the method is confirmed, the `substs` includes + // When the method is confirmed, the `args` includes // parameters from not just the method, but also the impl of // the method -- in particular, the `Self` type will be fully // resolved. However, those are not something that the "user // specified" -- i.e., those types come from the inferred type // of the receiver, not something the user wrote. So when we - // create the user-substs, we want to replace those earlier + // create the user-args, we want to replace those earlier // types with just the types that the user actually wrote -- // that is, those that appear on the *method itself*. // @@ -453,15 +454,15 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { // `foo.bar::<u32>(...)` -- the `Self` type here will be the // type of `foo` (possibly adjusted), but we don't want to // include that. We want just the `[_, u32]` part. - if !substs.is_empty() && !generics.params.is_empty() { + if !args.is_empty() && !generics.params.is_empty() { let user_type_annotation = self.probe(|_| { - let user_substs = UserSubsts { - substs: InternalSubsts::for_item(self.tcx, pick.item.def_id, |param, _| { + let user_args = UserArgs { + args: GenericArgs::for_item(self.tcx, pick.item.def_id, |param, _| { let i = param.index as usize; if i < generics.parent_count { self.fcx.var_for_def(DUMMY_SP, param) } else { - substs[i] + args[i] } }), user_self_ty: None, // not relevant here @@ -469,18 +470,18 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { self.fcx.canonicalize_user_type_annotation(UserType::TypeOf( pick.item.def_id, - user_substs, + user_args, )) }); - debug!("instantiate_method_substs: user_type_annotation={:?}", user_type_annotation); + debug!("instantiate_method_args: user_type_annotation={:?}", user_type_annotation); if !self.skip_record_for_diagnostics { self.fcx.write_user_type_annotation(self.call_expr.hir_id, user_type_annotation); } } - self.normalize(self.span, substs) + self.normalize(self.span, args) } fn unify_receivers( @@ -488,7 +489,7 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { self_ty: Ty<'tcx>, method_self_ty: Ty<'tcx>, pick: &probe::Pick<'tcx>, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, ) { debug!( "unify_receivers: self_ty={:?} method_self_ty={:?} span={:?} pick={:?}", @@ -499,7 +500,7 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { ObligationCauseCode::UnifyReceiver(Box::new(UnifyReceiverContext { assoc_item: pick.item, param_env: self.param_env, - substs, + args, })), ); match self.at(&cause, self.param_env).sup(DefineOpaqueTypes::No, method_self_ty, self_ty) { @@ -509,7 +510,7 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { Err(terr) => { // FIXME(arbitrary_self_types): We probably should limit the // situations where this can occur by adding additional restrictions - // to the feature, like the self type can't reference method substs. + // to the feature, like the self type can't reference method args. if self.tcx.features().arbitrary_self_types { self.err_ctxt() .report_mismatched_types(&cause, method_self_ty, self_ty, terr) @@ -532,19 +533,19 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { fn instantiate_method_sig( &mut self, pick: &probe::Pick<'tcx>, - all_substs: SubstsRef<'tcx>, + all_args: GenericArgsRef<'tcx>, ) -> (ty::FnSig<'tcx>, ty::InstantiatedPredicates<'tcx>) { - debug!("instantiate_method_sig(pick={:?}, all_substs={:?})", pick, all_substs); + debug!("instantiate_method_sig(pick={:?}, all_args={:?})", pick, all_args); // Instantiate the bounds on the method with the // type/early-bound-regions substitutions performed. There can // be no late-bound regions appearing here. let def_id = pick.item.def_id; - let method_predicates = self.tcx.predicates_of(def_id).instantiate(self.tcx, all_substs); + let method_predicates = self.tcx.predicates_of(def_id).instantiate(self.tcx, all_args); debug!("method_predicates after subst = {:?}", method_predicates); - let sig = self.tcx.fn_sig(def_id).subst(self.tcx, all_substs); + let sig = self.tcx.fn_sig(def_id).instantiate(self.tcx, all_args); debug!("type scheme substituted, sig={:?}", sig); let sig = self.instantiate_binder_with_fresh_vars(sig); @@ -556,18 +557,18 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { fn add_obligations( &mut self, fty: Ty<'tcx>, - all_substs: SubstsRef<'tcx>, + all_args: GenericArgsRef<'tcx>, method_predicates: ty::InstantiatedPredicates<'tcx>, def_id: DefId, ) { debug!( - "add_obligations: fty={:?} all_substs={:?} method_predicates={:?} def_id={:?}", - fty, all_substs, method_predicates, def_id + "add_obligations: fty={:?} all_args={:?} method_predicates={:?} def_id={:?}", + fty, all_args, method_predicates, def_id ); // FIXME: could replace with the following, but we already calculated `method_predicates`, // so we just call `predicates_for_generics` directly to avoid redoing work. - // `self.add_required_obligations(self.span, def_id, &all_substs);` + // `self.add_required_obligations(self.span, def_id, &all_args);` for obligation in traits::predicates_for_generics( |idx, span| { let code = if span.is_dummy() { @@ -590,10 +591,10 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { // this is a projection from a trait reference, so we have to // make sure that the trait reference inputs are well-formed. - self.add_wf_bounds(all_substs, self.call_expr); + self.add_wf_bounds(all_args, self.call_expr); // the function type must also be well-formed (this is not - // implied by the substs being well-formed because of inherent + // implied by the args being well-formed because of inherent // impls and late-bound regions - see issue #28609). self.register_wf_obligation(fty.into(), self.span, traits::WellFormed(None)); } diff --git a/compiler/rustc_hir_typeck/src/method/mod.rs b/compiler/rustc_hir_typeck/src/method/mod.rs index e52cea1889f..356e7022aea 100644 --- a/compiler/rustc_hir_typeck/src/method/mod.rs +++ b/compiler/rustc_hir_typeck/src/method/mod.rs @@ -12,7 +12,6 @@ pub use self::MethodError::*; use crate::errors::OpMethodGenericParams; use crate::FnCtxt; -use rustc_data_structures::sync::Lrc; use rustc_errors::{Applicability, Diagnostic, SubdiagnosticMessage}; use rustc_hir as hir; use rustc_hir::def::{CtorOf, DefKind, Namespace}; @@ -20,8 +19,8 @@ use rustc_hir::def_id::DefId; use rustc_infer::infer::{self, InferOk}; use rustc_middle::query::Providers; use rustc_middle::traits::ObligationCause; -use rustc_middle::ty::subst::{InternalSubsts, SubstsRef}; use rustc_middle::ty::{self, GenericParamDefKind, Ty, TypeVisitableExt}; +use rustc_middle::ty::{GenericArgs, GenericArgsRef}; use rustc_span::symbol::Ident; use rustc_span::Span; use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt; @@ -37,7 +36,7 @@ pub fn provide(providers: &mut Providers) { pub struct MethodCallee<'tcx> { /// Impl method ID, for inherent methods, or trait method ID, otherwise. pub def_id: DefId, - pub substs: SubstsRef<'tcx>, + pub args: GenericArgsRef<'tcx>, /// Instantiated method signature, i.e., it has been /// substituted, normalized, and has had late-bound @@ -190,11 +189,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.lint_dot_call_from_2018(self_ty, segment, span, call_expr, self_expr, &pick, args); - for import_id in &pick.import_ids { + for &import_id in &pick.import_ids { debug!("used_trait_import: {:?}", import_id); - Lrc::get_mut(&mut self.typeck_results.borrow_mut().used_trait_imports) - .unwrap() - .insert(*import_id); + self.typeck_results.borrow_mut().used_trait_imports.insert(import_id); } self.tcx.check_stability(pick.item.def_id, Some(call_expr.hir_id), span, None); @@ -324,9 +321,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { trait_def_id: DefId, self_ty: Ty<'tcx>, opt_input_types: Option<&[Ty<'tcx>]>, - ) -> (traits::PredicateObligation<'tcx>, &'tcx ty::List<ty::subst::GenericArg<'tcx>>) { + ) -> (traits::PredicateObligation<'tcx>, &'tcx ty::List<ty::GenericArg<'tcx>>) { // Construct a trait-reference `self_ty : Trait<input_tys>` - let substs = InternalSubsts::for_item(self.tcx, trait_def_id, |param, _| { + let args = GenericArgs::for_item(self.tcx, trait_def_id, |param, _| { match param.kind { GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => {} GenericParamDefKind::Type { .. } => { @@ -340,7 +337,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.var_for_def(cause.span, param) }); - let trait_ref = ty::TraitRef::new(self.tcx, trait_def_id, substs); + let trait_ref = ty::TraitRef::new(self.tcx, trait_def_id, args); // Construct an obligation let poly_trait_ref = ty::Binder::dummy(trait_ref); @@ -351,7 +348,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.param_env, poly_trait_ref.without_const(), ), - substs, + args, ) } @@ -369,9 +366,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self_ty: Ty<'tcx>, opt_input_types: Option<&[Ty<'tcx>]>, ) -> Option<InferOk<'tcx, MethodCallee<'tcx>>> { - let (obligation, substs) = + let (obligation, args) = self.obligation_for_method(cause, trait_def_id, self_ty, opt_input_types); - self.construct_obligation_for_trait(m_name, trait_def_id, obligation, substs) + self.construct_obligation_for_trait(m_name, trait_def_id, obligation, args) } // FIXME(#18741): it seems likely that we can consolidate some of this @@ -382,7 +379,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { m_name: Ident, trait_def_id: DefId, obligation: traits::PredicateObligation<'tcx>, - substs: &'tcx ty::List<ty::subst::GenericArg<'tcx>>, + args: &'tcx ty::List<ty::GenericArg<'tcx>>, ) -> Option<InferOk<'tcx, MethodCallee<'tcx>>> { debug!(?obligation); @@ -428,7 +425,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // N.B., instantiate late-bound regions before normalizing the // function signature so that normalization does not need to deal // with bound regions. - let fn_sig = tcx.fn_sig(def_id).subst(self.tcx, substs); + let fn_sig = tcx.fn_sig(def_id).instantiate(self.tcx, args); let fn_sig = self.instantiate_binder_with_fresh_vars(obligation.cause.span, infer::FnCall, fn_sig); @@ -447,7 +444,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // // Note that as the method comes from a trait, it should not have // any late-bound regions appearing in its bounds. - let bounds = self.tcx.predicates_of(def_id).instantiate(self.tcx, substs); + let bounds = self.tcx.predicates_of(def_id).instantiate(self.tcx, args); let InferOk { value, obligations: o } = self.at(&obligation.cause, self.param_env).normalize(bounds); @@ -480,7 +477,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ))), )); - let callee = MethodCallee { def_id, substs, sig: fn_sig }; + let callee = MethodCallee { def_id, args, sig: fn_sig }; debug!("callee = {:?}", callee); @@ -567,10 +564,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { debug!(?pick); { let mut typeck_results = self.typeck_results.borrow_mut(); - let used_trait_imports = Lrc::get_mut(&mut typeck_results.used_trait_imports).unwrap(); for import_id in pick.import_ids { debug!(used_trait_import=?import_id); - used_trait_imports.insert(import_id); + typeck_results.used_trait_imports.insert(import_id); } } diff --git a/compiler/rustc_hir_typeck/src/method/probe.rs b/compiler/rustc_hir_typeck/src/method/probe.rs index 03a3eebbdf5..9ef97243c5e 100644 --- a/compiler/rustc_hir_typeck/src/method/probe.rs +++ b/compiler/rustc_hir_typeck/src/method/probe.rs @@ -22,7 +22,7 @@ use rustc_middle::ty::AssocItem; use rustc_middle::ty::GenericParamDefKind; use rustc_middle::ty::ToPredicate; use rustc_middle::ty::{self, ParamEnvAnd, Ty, TyCtxt, TypeFoldable, TypeVisitableExt}; -use rustc_middle::ty::{InternalSubsts, SubstsRef}; +use rustc_middle::ty::{GenericArgs, GenericArgsRef}; use rustc_session::lint; use rustc_span::def_id::DefId; use rustc_span::def_id::LocalDefId; @@ -100,10 +100,10 @@ impl<'a, 'tcx> Deref for ProbeContext<'a, 'tcx> { #[derive(Debug, Clone)] pub(crate) struct Candidate<'tcx> { // Candidates are (I'm not quite sure, but they are mostly) basically - // some metadata on top of a `ty::AssocItem` (without substs). + // some metadata on top of a `ty::AssocItem` (without args). // // However, method probing wants to be able to evaluate the predicates - // for a function with the substs applied - for example, if a function + // for a function with the args applied - for example, if a function // has `where Self: Sized`, we don't want to consider it unless `Self` // is actually `Sized`, and similarly, return-type suggestions want // to consider the "actual" return type. @@ -140,7 +140,7 @@ pub(crate) struct Candidate<'tcx> { #[derive(Debug, Clone)] pub(crate) enum CandidateKind<'tcx> { InherentImplCandidate( - SubstsRef<'tcx>, + GenericArgsRef<'tcx>, // Normalize obligations Vec<traits::PredicateObligation<'tcx>>, ), @@ -738,13 +738,13 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { continue; } - let (impl_ty, impl_substs) = self.impl_ty_and_substs(impl_def_id); - let impl_ty = impl_ty.subst(self.tcx, impl_substs); + let (impl_ty, impl_args) = self.impl_ty_and_args(impl_def_id); + let impl_ty = impl_ty.instantiate(self.tcx, impl_args); debug!("impl_ty: {:?}", impl_ty); // Determine the receiver type that the method itself expects. - let (xform_self_ty, xform_ret_ty) = self.xform_self_ty(item, impl_ty, impl_substs); + let (xform_self_ty, xform_ret_ty) = self.xform_self_ty(item, impl_ty, impl_args); debug!("xform_self_ty: {:?}, xform_ret_ty: {:?}", xform_self_ty, xform_ret_ty); // We can't use normalize_associated_types_in as it will pollute the @@ -770,7 +770,7 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { xform_self_ty, xform_ret_ty, item, - kind: InherentImplCandidate(impl_substs, obligations), + kind: InherentImplCandidate(impl_args, obligations), import_ids: smallvec![], }, true, @@ -813,7 +813,7 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { let new_trait_ref = this.erase_late_bound_regions(new_trait_ref); let (xform_self_ty, xform_ret_ty) = - this.xform_self_ty(item, new_trait_ref.self_ty(), new_trait_ref.substs); + this.xform_self_ty(item, new_trait_ref.self_ty(), new_trait_ref.args); this.push_candidate( Candidate { xform_self_ty, @@ -859,7 +859,7 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { ); let (xform_self_ty, xform_ret_ty) = - this.xform_self_ty(item, trait_ref.self_ty(), trait_ref.substs); + this.xform_self_ty(item, trait_ref.self_ty(), trait_ref.args); this.push_candidate( Candidate { @@ -929,8 +929,8 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { ) -> bool { match method.kind { ty::AssocKind::Fn => self.probe(|_| { - let substs = self.fresh_substs_for_item(self.span, method.def_id); - let fty = self.tcx.fn_sig(method.def_id).subst(self.tcx, substs); + let args = self.fresh_args_for_item(self.span, method.def_id); + let fty = self.tcx.fn_sig(method.def_id).instantiate(self.tcx, args); let fty = self.instantiate_binder_with_fresh_vars(self.span, infer::FnCall, fty); if let Some(self_ty) = self_ty { @@ -954,8 +954,8 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { trait_def_id: DefId, ) { debug!("assemble_extension_candidates_for_trait(trait_def_id={:?})", trait_def_id); - let trait_substs = self.fresh_substs_for_item(self.span, trait_def_id); - let trait_ref = ty::TraitRef::new(self.tcx, trait_def_id, trait_substs); + let trait_args = self.fresh_args_for_item(self.span, trait_def_id); + let trait_ref = ty::TraitRef::new(self.tcx, trait_def_id, trait_args); if self.tcx.is_trait_alias(trait_def_id) { // For trait aliases, recursively assume all explicitly named traits are relevant @@ -977,7 +977,7 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { ); let (xform_self_ty, xform_ret_ty) = - self.xform_self_ty(item, new_trait_ref.self_ty(), new_trait_ref.substs); + self.xform_self_ty(item, new_trait_ref.self_ty(), new_trait_ref.args); self.push_candidate( Candidate { xform_self_ty, @@ -1005,7 +1005,7 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { } let (xform_self_ty, xform_ret_ty) = - self.xform_self_ty(item, trait_ref.self_ty(), trait_substs); + self.xform_self_ty(item, trait_ref.self_ty(), trait_args); self.push_candidate( Candidate { xform_self_ty, @@ -1510,7 +1510,7 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { // match as well (or at least may match, sometimes we // don't have enough information to fully evaluate). match probe.kind { - InherentImplCandidate(ref substs, ref ref_obligations) => { + InherentImplCandidate(ref args, ref ref_obligations) => { // `xform_ret_ty` hasn't been normalized yet, only `xform_self_ty`, // see the reasons mentioned in the comments in `assemble_inherent_impl_probe` // for why this is necessary @@ -1524,7 +1524,7 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { // Check whether the impl imposes obligations we have to worry about. let impl_def_id = probe.item.container_id(self.tcx); let impl_bounds = self.tcx.predicates_of(impl_def_id); - let impl_bounds = impl_bounds.instantiate(self.tcx, substs); + let impl_bounds = impl_bounds.instantiate(self.tcx, args); let InferOk { value: impl_bounds, obligations: norm_obligations } = self.fcx.at(&cause, self.param_env).normalize(impl_bounds); @@ -1843,10 +1843,10 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { &self, item: ty::AssocItem, impl_ty: Ty<'tcx>, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, ) -> (Ty<'tcx>, Option<Ty<'tcx>>) { if item.kind == ty::AssocKind::Fn && self.mode == Mode::MethodCall { - let sig = self.xform_method_sig(item.def_id, substs); + let sig = self.xform_method_sig(item.def_id, args); (sig.inputs()[0], Some(sig.output())) } else { (impl_ty, None) @@ -1854,11 +1854,11 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { } #[instrument(level = "debug", skip(self))] - fn xform_method_sig(&self, method: DefId, substs: SubstsRef<'tcx>) -> ty::FnSig<'tcx> { + fn xform_method_sig(&self, method: DefId, args: GenericArgsRef<'tcx>) -> ty::FnSig<'tcx> { let fn_sig = self.tcx.fn_sig(method); debug!(?fn_sig); - assert!(!substs.has_escaping_bound_vars()); + assert!(!args.has_escaping_bound_vars()); // It is possible for type parameters or early-bound lifetimes // to appear in the signature of `self`. The substitutions we @@ -1866,15 +1866,15 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { // method yet. So create fresh variables here for those too, // if there are any. let generics = self.tcx.generics_of(method); - assert_eq!(substs.len(), generics.parent_count as usize); + assert_eq!(args.len(), generics.parent_count as usize); let xform_fn_sig = if generics.params.is_empty() { - fn_sig.subst(self.tcx, substs) + fn_sig.instantiate(self.tcx, args) } else { - let substs = InternalSubsts::for_item(self.tcx, method, |param, _| { + let args = GenericArgs::for_item(self.tcx, method, |param, _| { let i = param.index as usize; - if i < substs.len() { - substs[i] + if i < args.len() { + args[i] } else { match param.kind { GenericParamDefKind::Lifetime => { @@ -1887,18 +1887,18 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { } } }); - fn_sig.subst(self.tcx, substs) + fn_sig.instantiate(self.tcx, args) }; self.erase_late_bound_regions(xform_fn_sig) } /// Gets the type of an impl and generate substitutions with inference vars. - fn impl_ty_and_substs( + fn impl_ty_and_args( &self, impl_def_id: DefId, - ) -> (ty::EarlyBinder<Ty<'tcx>>, SubstsRef<'tcx>) { - (self.tcx.type_of(impl_def_id), self.fresh_substs_for_item(self.span, impl_def_id)) + ) -> (ty::EarlyBinder<Ty<'tcx>>, GenericArgsRef<'tcx>) { + (self.tcx.type_of(impl_def_id), self.fresh_args_for_item(self.span, impl_def_id)) } /// Replaces late-bound-regions bound by `value` with `'static` using @@ -1938,13 +1938,21 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { /// Determine if the associated item withe the given DefId matches /// the desired name via a doc alias. fn matches_by_doc_alias(&self, def_id: DefId) -> bool { - let Some(name) = self.method_name else { return false; }; - let Some(local_def_id) = def_id.as_local() else { return false; }; + let Some(name) = self.method_name else { + return false; + }; + let Some(local_def_id) = def_id.as_local() else { + return false; + }; let hir_id = self.fcx.tcx.hir().local_def_id_to_hir_id(local_def_id); let attrs = self.fcx.tcx.hir().attrs(hir_id); for attr in attrs { - let sym::doc = attr.name_or_empty() else { continue; }; - let Some(values) = attr.meta_item_list() else { continue; }; + let sym::doc = attr.name_or_empty() else { + continue; + }; + let Some(values) = attr.meta_item_list() else { + continue; + }; for v in values { if v.name_or_empty() != sym::alias { continue; @@ -2032,8 +2040,8 @@ impl<'tcx> Candidate<'tcx> { // means they are safe to put into the // `WhereClausePick`. assert!( - !trait_ref.skip_binder().substs.has_infer() - && !trait_ref.skip_binder().substs.has_placeholders() + !trait_ref.skip_binder().args.has_infer() + && !trait_ref.skip_binder().args.has_placeholders() ); WhereClausePick(*trait_ref) diff --git a/compiler/rustc_hir_typeck/src/method/suggest.rs b/compiler/rustc_hir_typeck/src/method/suggest.rs index 5f924f30936..3d7187cb16f 100644 --- a/compiler/rustc_hir_typeck/src/method/suggest.rs +++ b/compiler/rustc_hir_typeck/src/method/suggest.rs @@ -2,12 +2,13 @@ //! found or is otherwise invalid. use crate::errors; -use crate::errors::CandidateTraitNote; -use crate::errors::NoAssociatedItem; +use crate::errors::{CandidateTraitNote, NoAssociatedItem}; use crate::Expectation; use crate::FnCtxt; use rustc_ast::ast::Mutability; -use rustc_data_structures::fx::{FxHashMap, FxHashSet}; +use rustc_attr::parse_confusables; +use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; +use rustc_data_structures::unord::UnordSet; use rustc_errors::StashKey; use rustc_errors::{ pluralize, struct_span_err, Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed, @@ -31,6 +32,7 @@ use rustc_middle::ty::fast_reject::{simplify_type, TreatParams}; use rustc_middle::ty::print::{with_crate_prefix, with_forced_trimmed_paths}; use rustc_middle::ty::IsSuggestable; use rustc_middle::ty::{self, GenericArgKind, Ty, TyCtxt, TypeVisitableExt}; +use rustc_span::def_id::DefIdSet; use rustc_span::symbol::{kw, sym, Ident}; use rustc_span::Symbol; use rustc_span::{edit_distance, source_map, ExpnKind, FileName, MacroKind, Span}; @@ -536,11 +538,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { )); } } else if !unsatisfied_predicates.is_empty() { - let mut type_params = FxHashMap::default(); + let mut type_params = FxIndexMap::default(); // Pick out the list of unimplemented traits on the receiver. // This is used for custom error messages with the `#[rustc_on_unimplemented]` attribute. - let mut unimplemented_traits = FxHashMap::default(); + let mut unimplemented_traits = FxIndexMap::default(); let mut unimplemented_traits_only = true; for (predicate, _parent_pred, cause) in unsatisfied_predicates { if let (ty::PredicateKind::Clause(ty::ClauseKind::Trait(p)), Some(cause)) = @@ -606,7 +608,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ); type_params .entry(key) - .or_insert_with(FxHashSet::default) + .or_insert_with(UnordSet::default) .insert(obligation.to_owned()); return true; } @@ -647,13 +649,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // `<Foo as Iterator>::Item = String`. let projection_ty = pred.skip_binder().projection_ty; - let substs_with_infer_self = tcx.mk_substs_from_iter( + let args_with_infer_self = tcx.mk_args_from_iter( iter::once(Ty::new_var(tcx, ty::TyVid::from_u32(0)).into()) - .chain(projection_ty.substs.iter().skip(1)), + .chain(projection_ty.args.iter().skip(1)), ); let quiet_projection_ty = - tcx.mk_alias_ty(projection_ty.def_id, substs_with_infer_self); + tcx.mk_alias_ty(projection_ty.def_id, args_with_infer_self); let term = pred.skip_binder().term; @@ -680,8 +682,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }; // Find all the requirements that come from a local `impl` block. - let mut skip_list: FxHashSet<_> = Default::default(); - let mut spanned_predicates = FxHashMap::default(); + let mut skip_list: UnordSet<_> = Default::default(); + let mut spanned_predicates = FxIndexMap::default(); for (p, parent_p, cause) in unsatisfied_predicates { // Extract the predicate span and parent def id of the cause, // if we have one. @@ -723,7 +725,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let span = self_ty.span.ctxt().outer_expn_data().call_site; let entry = spanned_predicates.entry(span); let entry = entry.or_insert_with(|| { - (FxHashSet::default(), FxHashSet::default(), Vec::new()) + (FxIndexSet::default(), FxIndexSet::default(), Vec::new()) }); entry.0.insert(span); entry.1.insert(( @@ -771,7 +773,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { skip_list.insert(p); let entry = spanned_predicates.entry(self_ty.span); let entry = entry.or_insert_with(|| { - (FxHashSet::default(), FxHashSet::default(), Vec::new()) + (FxIndexSet::default(), FxIndexSet::default(), Vec::new()) }); entry.2.push(p); if cause_span != *item_span { @@ -806,7 +808,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { skip_list.insert(p); let entry = spanned_predicates.entry(ident.span); let entry = entry.or_insert_with(|| { - (FxHashSet::default(), FxHashSet::default(), Vec::new()) + (FxIndexSet::default(), FxIndexSet::default(), Vec::new()) }); entry.0.insert(cause_span); entry.1.insert((ident.span, "")); @@ -840,7 +842,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { unsatisfied_bounds = true; } - let mut suggested_bounds = FxHashSet::default(); + let mut suggested_bounds = UnordSet::default(); // The requirements that didn't have an `impl` span to show. let mut bound_list = unsatisfied_predicates .iter() @@ -889,8 +891,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { for ((span, add_where_or_comma), obligations) in type_params.into_iter() { restrict_type_params = true; // #74886: Sort here so that the output is always the same. - let mut obligations = obligations.into_iter().collect::<Vec<_>>(); - obligations.sort(); + let obligations = obligations.to_sorted_stable_ord(); err.span_suggestion_verbose( span, format!( @@ -993,9 +994,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // different from the received one // So we avoid suggestion method with Box<Self> // for instance - self.tcx.at(span).type_of(*def_id).subst_identity() + self.tcx.at(span).type_of(*def_id).instantiate_identity() != rcvr_ty - && self.tcx.at(span).type_of(*def_id).subst_identity() + && self + .tcx + .at(span) + .type_of(*def_id) + .instantiate_identity() != rcvr_ty } (Mode::Path, false, _) => true, @@ -1018,7 +1023,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .map(|impl_item| { format!( "- `{}`", - self.tcx.at(span).type_of(*impl_item).subst_identity() + self.tcx.at(span).type_of(*impl_item).instantiate_identity() ) }) .collect::<Vec<_>>() @@ -1032,6 +1037,28 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { "the {item_kind} was found for\n{}{}", type_candidates, additional_types )); + } else { + 'outer: for inherent_impl_did in self.tcx.inherent_impls(adt.did()) { + for inherent_method in + self.tcx.associated_items(inherent_impl_did).in_definition_order() + { + if let Some(attr) = self.tcx.get_attr(inherent_method.def_id, sym::rustc_confusables) + && let Some(candidates) = parse_confusables(attr) + && candidates.contains(&item_name.name) + { + err.span_suggestion_verbose( + item_name.span, + format!( + "you might have meant to use `{}`", + inherent_method.name.as_str() + ), + inherent_method.name.as_str(), + Applicability::MaybeIncorrect, + ); + break 'outer; + } + } + } } } } else { @@ -1197,7 +1224,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { None }; - let impl_ty = self.tcx.at(span).type_of(impl_did).subst_identity(); + let impl_ty = self.tcx.at(span).type_of(impl_did).instantiate_identity(); let insertion = match self.tcx.impl_trait_ref(impl_did) { None => String::new(), @@ -1243,7 +1270,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ty::AssocKind::Fn => self .tcx .fn_sig(item.def_id) - .subst_identity() + .instantiate_identity() .inputs() .skip_binder() .get(0) @@ -1326,7 +1353,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // When the "method" is resolved through dereferencing, we really want the // original type that has the associated function for accurate suggestions. // (#61411) - let impl_ty = self.tcx.type_of(*impl_did).subst_identity(); + let impl_ty = self.tcx.type_of(*impl_did).instantiate_identity(); let target_ty = self .autoderef(sugg_span, rcvr_ty) .find(|(rcvr_ty, _)| { @@ -1335,10 +1362,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }) .map_or(impl_ty, |(ty, _)| ty) .peel_refs(); - if let ty::Adt(def, substs) = target_ty.kind() { + if let ty::Adt(def, args) = target_ty.kind() { // If there are any inferred arguments, (`{integer}`), we should replace // them with underscores to allow the compiler to infer them - let infer_substs = self.tcx.mk_substs_from_iter(substs.into_iter().map(|arg| { + let infer_args = self.tcx.mk_args_from_iter(args.into_iter().map(|arg| { if !arg.is_suggestable(self.tcx, true) { has_unsuggestable_args = true; match arg.unpack() { @@ -1368,7 +1395,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } })); - self.tcx.value_path_str_with_substs(def.did(), infer_substs) + self.tcx.value_path_str_with_args(def.did(), infer_args) } else { self.ty_to_value_string(target_ty) } @@ -1380,7 +1407,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { && let Some(assoc) = self.associated_value(*impl_did, item_name) && assoc.kind == ty::AssocKind::Fn { - let sig = self.tcx.fn_sig(assoc.def_id).subst_identity(); + let sig = self.tcx.fn_sig(assoc.def_id).instantiate_identity(); sig.inputs().skip_binder().get(0).and_then(|first| if first.peel_refs() == rcvr_ty.peel_refs() { None } else { @@ -1445,11 +1472,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ) -> bool { let tcx = self.tcx; let field_receiver = self.autoderef(span, rcvr_ty).find_map(|(ty, _)| match ty.kind() { - ty::Adt(def, substs) if !def.is_enum() => { + ty::Adt(def, args) if !def.is_enum() => { let variant = &def.non_enum_variant(); tcx.find_field_index(item_name, variant).map(|index| { let field = &variant.fields[index]; - let field_ty = field.ty(tcx, substs); + let field_ty = field.ty(tcx, args); (field, field_ty) }) } @@ -1546,7 +1573,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } let range_def_id = self.tcx.require_lang_item(lang_item.unwrap(), None); - let range_ty = self.tcx.type_of(range_def_id).subst(self.tcx, &[actual.into()]); + let range_ty = + self.tcx.type_of(range_def_id).instantiate(self.tcx, &[actual.into()]); let pick = self.lookup_probe_for_diagnostic( item_name, @@ -1699,10 +1727,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// we try to suggest `rect.area()` pub(crate) fn suggest_assoc_method_call(&self, segs: &[PathSegment<'_>]) { debug!("suggest_assoc_method_call segs: {:?}", segs); - let [seg1, seg2] = segs else { return; }; + let [seg1, seg2] = segs else { + return; + }; let Some(mut diag) = - self.tcx.sess.diagnostic().steal_diagnostic(seg1.ident.span, StashKey::CallAssocMethod) - else { return }; + self.tcx.sess.diagnostic().steal_diagnostic(seg1.ident.span, StashKey::CallAssocMethod) + else { + return; + }; let map = self.infcx.tcx.hir(); let body_id = self.tcx.hir().body_owned_by(self.body_id); @@ -1766,7 +1798,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ) { if let SelfSource::MethodCall(expr) = source && let mod_id = self.tcx.parent_module(expr.hir_id).to_def_id() - && let Some((fields, substs)) = + && let Some((fields, args)) = self.get_field_candidates_considering_privacy(span, actual, mod_id) { let call_expr = self.tcx.hir().expect_expr(self.tcx.hir().parent_id(expr.hir_id)); @@ -1801,7 +1833,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }) }, candidate_field, - substs, + args, vec![], mod_id, ) @@ -1839,18 +1871,24 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { item_name: Ident, ) { let tcx = self.tcx; - let SelfSource::MethodCall(expr) = source else { return; }; + let SelfSource::MethodCall(expr) = source else { + return; + }; let call_expr = tcx.hir().expect_expr(tcx.hir().parent_id(expr.hir_id)); - let ty::Adt(kind, substs) = actual.kind() else { return; }; + let ty::Adt(kind, args) = actual.kind() else { + return; + }; match kind.adt_kind() { ty::AdtKind::Enum => { let matching_variants: Vec<_> = kind .variants() .iter() .flat_map(|variant| { - let [field] = &variant.fields.raw[..] else { return None; }; - let field_ty = field.ty(tcx, substs); + let [field] = &variant.fields.raw[..] else { + return None; + }; + let field_ty = field.ty(tcx, args); // Skip `_`, since that'll just lead to ambiguity. if self.resolve_vars_if_possible(field_ty).is_ty_var() { @@ -1885,7 +1923,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { match &matching_variants[..] { [(_, field, pick)] => { - let self_ty = field.ty(tcx, substs); + let self_ty = field.ty(tcx, args); err.span_note( tcx.def_span(pick.item.def_id), format!("the method `{item_name}` exists on the type `{self_ty}`"), @@ -1927,15 +1965,21 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Target wrapper types - types that wrap or pretend to wrap another type, // perhaps this inner type is meant to be called? ty::AdtKind::Struct | ty::AdtKind::Union => { - let [first] = ***substs else { return; }; - let ty::GenericArgKind::Type(ty) = first.unpack() else { return; }; + let [first] = ***args else { + return; + }; + let ty::GenericArgKind::Type(ty) = first.unpack() else { + return; + }; let Ok(pick) = self.lookup_probe_for_diagnostic( item_name, ty, call_expr, ProbeScope::TraitsInScope, None, - ) else { return; }; + ) else { + return; + }; let name = self.ty_to_value_string(actual); let inner_id = kind.did(); @@ -2037,7 +2081,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ty::Adt(def, _) => Some(def.did()), _ => None, }) - .collect::<FxHashSet<_>>(); + .collect::<FxIndexSet<_>>(); let mut spans: MultiSpan = def_ids .iter() .filter_map(|def_id| { @@ -2100,7 +2144,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let Some(ty::PredicateKind::Clause(ty::ClauseKind::Trait(trait_pred))) = pred.kind().no_bound_vars() else { - continue + continue; }; let adt = match trait_pred.self_ty().ty_adt_def() { Some(adt) if adt.did().is_local() => adt, @@ -2197,7 +2241,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { item_name: Ident, expected: Expectation<'tcx>, ) { - let SelfSource::QPath(ty) = self_source else { return; }; + let SelfSource::QPath(ty) = self_source else { + return; + }; for (deref_ty, _) in self.autoderef(rustc_span::DUMMY_SP, rcvr_ty).skip(1) { if let Ok(pick) = self.probe_for_name( Mode::Path, @@ -2214,7 +2260,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // just changing the path. && pick.item.fn_has_self_parameter && let Some(self_ty) = - self.tcx.fn_sig(pick.item.def_id).subst_identity().inputs().skip_binder().get(0) + self.tcx.fn_sig(pick.item.def_id).instantiate_identity().inputs().skip_binder().get(0) && self_ty.is_ref() { let suggested_path = match deref_ty.kind() { @@ -2255,7 +2301,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// Print out the type for use in value namespace. fn ty_to_value_string(&self, ty: Ty<'tcx>) -> String { match ty.kind() { - ty::Adt(def, substs) => self.tcx.def_path_str_with_substs(def.did(), substs), + ty::Adt(def, args) => self.tcx.def_path_str_with_args(def.did(), args), _ => self.ty_to_string(ty), } } @@ -2651,7 +2697,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { Nothing, } let ast_generics = hir.get_generics(id.owner.def_id).unwrap(); - let trait_def_ids: FxHashSet<DefId> = ast_generics + let trait_def_ids: DefIdSet = ast_generics .bounds_for_param(def_id) .flat_map(|bp| bp.bounds.iter()) .filter_map(|bound| bound.trait_ref()?.trait_def_id()) @@ -2752,7 +2798,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.tcx.impl_polarity(*imp_did) == ty::ImplPolarity::Negative }) .any(|imp_did| { - let imp = self.tcx.impl_trait_ref(imp_did).unwrap().subst_identity(); + let imp = + self.tcx.impl_trait_ref(imp_did).unwrap().instantiate_identity(); let imp_simp = simplify_type(self.tcx, imp.self_ty(), TreatParams::ForLookup); imp_simp.is_some_and(|s| s == simp_rcvr_ty) @@ -2834,9 +2881,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { found: Ty<'tcx>, expected: Ty<'tcx>, ) -> bool { - let Some((_def_id_or_name, output, _inputs)) = - self.extract_callable_info(found) else { - return false; + let Some((_def_id_or_name, output, _inputs)) = self.extract_callable_info(found) else { + return false; }; if !self.can_coerce(output, expected) { diff --git a/compiler/rustc_hir_typeck/src/pat.rs b/compiler/rustc_hir_typeck/src/pat.rs index 42f4531c0ef..8bf95d4bf9a 100644 --- a/compiler/rustc_hir_typeck/src/pat.rs +++ b/compiler/rustc_hir_typeck/src/pat.rs @@ -335,8 +335,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { expected: Ty<'tcx>, mut def_bm: BindingMode, ) -> (Ty<'tcx>, BindingMode) { - let mut expected = self.resolve_vars_with_obligations(expected); - + let mut expected = self.try_structurally_resolve_type(pat.span, expected); // Peel off as many `&` or `&mut` from the scrutinee type as possible. For example, // for `match &&&mut Some(5)` the loop runs three times, aborting when it reaches // the `Some(5)` which is not of type Ref. @@ -353,7 +352,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Preserve the reference type. We'll need it later during THIR lowering. pat_adjustments.push(expected); - expected = inner_ty; + expected = self.try_structurally_resolve_type(pat.span, inner_ty); def_bm = ty::BindByReference(match def_bm { // If default binding mode is by value, make it `ref` or `ref mut` // (depending on whether we observe `&` or `&mut`). @@ -627,6 +626,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { local_ty } + /// When a variable is bound several times in a `PatKind::Or`, it'll resolve all of the + /// subsequent bindings of the same name to the first usage. Verify that all of these + /// bindings have the same type by comparing them all against the type of that first pat. fn check_binding_alt_eq_ty( &self, ba: hir::BindingAnnotation, @@ -638,7 +640,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let var_ty = self.local_ty(span, var_id); if let Some(mut err) = self.demand_eqtype_pat_diag(span, var_ty, ty, ti) { let hir = self.tcx.hir(); - let var_ty = self.resolve_vars_with_obligations(var_ty); + let var_ty = self.resolve_vars_if_possible(var_ty); let msg = format!("first introduced with type `{var_ty}` here"); err.span_label(hir.span(var_id), msg); let in_match = hir.parent_iter(var_id).any(|(_, n)| { @@ -656,7 +658,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { &mut err, span, var_ty, - self.resolve_vars_with_obligations(ty), + self.resolve_vars_if_possible(ty), ba, ); err.emit(); @@ -1092,12 +1094,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if subpats.len() == variant.fields.len() || subpats.len() < variant.fields.len() && ddpos.as_opt_usize().is_some() { - let ty::Adt(_, substs) = pat_ty.kind() else { + let ty::Adt(_, args) = pat_ty.kind() else { bug!("unexpected pattern type {:?}", pat_ty); }; for (i, subpat) in subpats.iter().enumerate_and_adjust(variant.fields.len(), ddpos) { let field = &variant.fields[FieldIdx::from_usize(i)]; - let field_ty = self.field_ty(subpat.span, field, substs); + let field_ty = self.field_ty(subpat.span, field, args); self.check_pat(subpat, field_ty, def_bm, ti); self.tcx.check_stability( @@ -1180,10 +1182,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // with the subpatterns directly in the tuple variant pattern, e.g., `V_i(p_0, .., p_N)`. let missing_parentheses = match (&expected.kind(), fields, had_err) { // #67037: only do this if we could successfully type-check the expected type against - // the tuple struct pattern. Otherwise the substs could get out of range on e.g., + // the tuple struct pattern. Otherwise the args could get out of range on e.g., // `let P() = U;` where `P != U` with `struct P<T>(T);`. - (ty::Adt(_, substs), [field], false) => { - let field_ty = self.field_ty(pat_span, field, substs); + (ty::Adt(_, args), [field], false) => { + let field_ty = self.field_ty(pat_span, field, args); match field_ty.kind() { ty::Tuple(fields) => fields.len() == subpats.len(), _ => false, @@ -1333,7 +1335,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ) -> bool { let tcx = self.tcx; - let ty::Adt(adt, substs) = adt_ty.kind() else { + let ty::Adt(adt, args) = adt_ty.kind() else { span_bug!(pat.span, "struct pattern is not an ADT"); }; @@ -1366,7 +1368,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .map(|(i, f)| { self.write_field_index(field.hir_id, *i); self.tcx.check_stability(f.did, Some(pat.hir_id), span, None); - self.field_ty(span, f, substs) + self.field_ty(span, f, args) }) .unwrap_or_else(|| { inexistent_fields.push(field); @@ -1394,7 +1396,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { &inexistent_fields, &mut unmentioned_fields, variant, - substs, + args, )) } else { None @@ -1564,7 +1566,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { inexistent_fields: &[&hir::PatField<'tcx>], unmentioned_fields: &mut Vec<(&'tcx ty::FieldDef, Ident)>, variant: &ty::VariantDef, - substs: &'tcx ty::List<ty::subst::GenericArg<'tcx>>, + args: &'tcx ty::List<ty::GenericArg<'tcx>>, ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> { let tcx = self.tcx; let (field_names, t, plural) = if inexistent_fields.len() == 1 { @@ -1634,7 +1636,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.field_ty( unmentioned_fields[0].1.span, unmentioned_fields[0].0, - substs, + args, ), ) => {} _ => { diff --git a/compiler/rustc_hir_typeck/src/place_op.rs b/compiler/rustc_hir_typeck/src/place_op.rs index fd43b475e3a..1eb84eb1637 100644 --- a/compiler/rustc_hir_typeck/src/place_op.rs +++ b/compiler/rustc_hir_typeck/src/place_op.rs @@ -392,7 +392,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // We also could not use `expr_ty_adjusted` of index_expr because reborrowing // during coercions can also cause type of index_expr to differ from `T`, // which can potentially cause regionck failure (#74933). - Some(self.typeck_results.borrow().node_substs(expr.hir_id).type_at(1)) + Some(self.typeck_results.borrow().node_args(expr.hir_id).type_at(1)) } }; let arg_tys = arg_ty.as_slice(); diff --git a/compiler/rustc_hir_typeck/src/rvalue_scopes.rs b/compiler/rustc_hir_typeck/src/rvalue_scopes.rs index 22c9e796107..091e88abe97 100644 --- a/compiler/rustc_hir_typeck/src/rvalue_scopes.rs +++ b/compiler/rustc_hir_typeck/src/rvalue_scopes.rs @@ -74,9 +74,7 @@ pub fn resolve_rvalue_scopes<'a, 'tcx>( debug!("start resolving rvalue scopes, def_id={def_id:?}"); debug!("rvalue_scope: rvalue_candidates={:?}", scope_tree.rvalue_candidates); for (&hir_id, candidate) in &scope_tree.rvalue_candidates { - let Some(Node::Expr(expr)) = hir_map.find(hir_id) else { - bug!("hir node does not exist") - }; + let Some(Node::Expr(expr)) = hir_map.find(hir_id) else { bug!("hir node does not exist") }; record_rvalue_scope(&mut rvalue_scopes, expr, candidate); } rvalue_scopes diff --git a/compiler/rustc_hir_typeck/src/upvar.rs b/compiler/rustc_hir_typeck/src/upvar.rs index 208c40a3932..f77a4d16b5f 100644 --- a/compiler/rustc_hir_typeck/src/upvar.rs +++ b/compiler/rustc_hir_typeck/src/upvar.rs @@ -33,6 +33,7 @@ use super::FnCtxt; use crate::expr_use_visitor as euv; +use rustc_data_structures::unord::{ExtendUnord, UnordSet}; use rustc_errors::{Applicability, MultiSpan}; use rustc_hir as hir; use rustc_hir::def_id::LocalDefId; @@ -41,14 +42,14 @@ use rustc_infer::infer::UpvarRegion; use rustc_middle::hir::place::{Place, PlaceBase, PlaceWithHirId, Projection, ProjectionKind}; use rustc_middle::mir::FakeReadCause; use rustc_middle::ty::{ - self, ClosureSizeProfileData, Ty, TyCtxt, TypeckResults, UpvarCapture, UpvarSubsts, + self, ClosureSizeProfileData, Ty, TyCtxt, TypeckResults, UpvarArgs, UpvarCapture, }; use rustc_session::lint; use rustc_span::sym; use rustc_span::{BytePos, Pos, Span, Symbol}; use rustc_trait_selection::infer::InferCtxtExt; -use rustc_data_structures::fx::{FxHashMap, FxHashSet}; +use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; use rustc_target::abi::FIRST_VARIANT; use std::iter; @@ -168,9 +169,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ) { // Extract the type of the closure. let ty = self.node_ty(closure_hir_id); - let (closure_def_id, substs) = match *ty.kind() { - ty::Closure(def_id, substs) => (def_id, UpvarSubsts::Closure(substs)), - ty::Generator(def_id, substs, _) => (def_id, UpvarSubsts::Generator(substs)), + let (closure_def_id, args) = match *ty.kind() { + ty::Closure(def_id, args) => (def_id, UpvarArgs::Closure(args)), + ty::Generator(def_id, args, _) => (def_id, UpvarArgs::Generator(args)), ty::Error(_) => { // #51714: skip analysis when we have already encountered type errors return; @@ -186,8 +187,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }; let closure_def_id = closure_def_id.expect_local(); - let infer_kind = if let UpvarSubsts::Closure(closure_substs) = substs { - self.closure_kind(closure_substs).is_none().then_some(closure_substs) + let infer_kind = if let UpvarArgs::Closure(closure_args) = args { + self.closure_kind(closure_args).is_none().then_some(closure_args) } else { None }; @@ -256,10 +257,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let before_feature_tys = self.final_upvar_tys(closure_def_id); - if let Some(closure_substs) = infer_kind { + if let Some(closure_args) = infer_kind { // Unify the (as yet unbound) type variable in the closure - // substs with the kind we inferred. - let closure_kind_ty = closure_substs.as_closure().kind_ty(); + // args with the kind we inferred. + let closure_kind_ty = closure_args.as_closure().kind_ty(); self.demand_eqtype(span, closure_kind.to_ty(self.tcx), closure_kind_ty); // If we have an origin, store it. @@ -294,14 +295,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Equate the type variables for the upvars with the actual types. let final_upvar_tys = self.final_upvar_tys(closure_def_id); debug!( - "analyze_closure: id={:?} substs={:?} final_upvar_tys={:?}", - closure_hir_id, substs, final_upvar_tys + "analyze_closure: id={:?} args={:?} final_upvar_tys={:?}", + closure_hir_id, args, final_upvar_tys ); // Build a tuple (U0..Un) of the final upvar types U0..Un // and unify the upvar tuple type in the closure with it: let final_tupled_upvars_type = Ty::new_tup(self.tcx, &final_upvar_tys); - self.demand_suptype(span, substs.tupled_upvars_ty(), final_tupled_upvars_type); + self.demand_suptype(span, args.tupled_upvars_ty(), final_tupled_upvars_type); let fake_reads = delegate .fake_reads @@ -644,7 +645,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { for capture in captures { match capture.info.capture_kind { ty::UpvarCapture::ByRef(_) => { - let PlaceBase::Upvar(upvar_id) = capture.place.base else { bug!("expected upvar") }; + let PlaceBase::Upvar(upvar_id) = capture.place.base else { + bug!("expected upvar") + }; let origin = UpvarRegion(upvar_id, closure_span); let upvar_region = self.next_region_var(origin); capture.region = Some(upvar_region); @@ -908,19 +911,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// Combines all the reasons for 2229 migrations fn compute_2229_migrations_reasons( &self, - auto_trait_reasons: FxHashSet<&'static str>, + auto_trait_reasons: UnordSet<&'static str>, drop_order: bool, ) -> MigrationWarningReason { - let mut reasons = MigrationWarningReason::default(); - - reasons.auto_traits.extend(auto_trait_reasons); - reasons.drop_order = drop_order; - - // `auto_trait_reasons` are in hashset order, so sort them to put the - // diagnostics we emit later in a cross-platform-consistent order. - reasons.auto_traits.sort_unstable(); - - reasons + MigrationWarningReason { + auto_traits: auto_trait_reasons.to_sorted_stable_ord(), + drop_order, + } } /// Figures out the list of root variables (and their types) that aren't completely @@ -934,7 +931,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>, var_hir_id: hir::HirId, closure_clause: hir::CaptureBy, - ) -> Option<FxHashMap<UpvarMigrationInfo, FxHashSet<&'static str>>> { + ) -> Option<FxIndexMap<UpvarMigrationInfo, UnordSet<&'static str>>> { let auto_traits_def_id = vec![ self.tcx.lang_items().clone_trait(), self.tcx.lang_items().sync_trait(), @@ -979,7 +976,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { })); } - let mut problematic_captures = FxHashMap::default(); + let mut problematic_captures = FxIndexMap::default(); // Check whether captured fields also implement the trait for capture in root_var_min_capture_list.iter() { let ty = apply_capture_kind_on_capture_ty( @@ -999,7 +996,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { })); } - let mut capture_problems = FxHashSet::default(); + let mut capture_problems = UnordSet::default(); // Checks if for any of the auto traits, one or more trait is implemented // by the root variable but not by the capture @@ -1045,7 +1042,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { min_captures: Option<&ty::RootVariableMinCaptureList<'tcx>>, closure_clause: hir::CaptureBy, var_hir_id: hir::HirId, - ) -> Option<FxHashSet<UpvarMigrationInfo>> { + ) -> Option<FxIndexSet<UpvarMigrationInfo>> { let ty = self.resolve_vars_if_possible(self.node_ty(var_hir_id)); if !ty.has_significant_drop(self.tcx, self.tcx.param_env(closure_def_id)) { @@ -1064,14 +1061,15 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // ``` debug!("no path starting from it is used"); - match closure_clause { // Only migrate if closure is a move closure hir::CaptureBy::Value => { - let mut diagnostics_info = FxHashSet::default(); - let upvars = self.tcx.upvars_mentioned(closure_def_id).expect("must be an upvar"); + let mut diagnostics_info = FxIndexSet::default(); + let upvars = + self.tcx.upvars_mentioned(closure_def_id).expect("must be an upvar"); let upvar = upvars[&var_hir_id]; - diagnostics_info.insert(UpvarMigrationInfo::CapturingNothing { use_span: upvar.span }); + diagnostics_info + .insert(UpvarMigrationInfo::CapturingNothing { use_span: upvar.span }); return Some(diagnostics_info); } hir::CaptureBy::Ref => {} @@ -1082,7 +1080,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { debug!(?root_var_min_capture_list); let mut projections_list = Vec::new(); - let mut diagnostics_info = FxHashSet::default(); + let mut diagnostics_info = FxIndexSet::default(); for captured_place in root_var_min_capture_list.iter() { match captured_place.info.capture_kind { @@ -1152,7 +1150,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }; let mut need_migrations = Vec::new(); - let mut auto_trait_migration_reasons = FxHashSet::default(); + let mut auto_trait_migration_reasons = UnordSet::default(); let mut drop_migration_needed = false; // Perform auto-trait analysis @@ -1164,7 +1162,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { { diagnostics_info } else { - FxHashMap::default() + FxIndexMap::default() }; let drop_reorder_diagnostic = if let Some(diagnostics_info) = self @@ -1178,7 +1176,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { drop_migration_needed = true; diagnostics_info } else { - FxHashSet::default() + FxIndexSet::default() }; // Combine all the captures responsible for needing migrations into one HashSet @@ -1195,7 +1193,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if let Some(reasons) = auto_trait_diagnostic.get(&captures_info) { reasons.clone() } else { - FxHashSet::default() + UnordSet::default() }; // Check if migration is needed because of drop reorder as a result of that capture @@ -1203,7 +1201,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Combine all the reasons of why the root variable should be captured as a result of // auto trait implementation issues - auto_trait_migration_reasons.extend(capture_trait_reasons.iter().copied()); + auto_trait_migration_reasons.extend_unord(capture_trait_reasons.items().copied()); diagnostics_info.push(MigrationLintNote { captures_info, @@ -1385,7 +1383,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ty::Ref(..) => unreachable!(), ty::RawPtr(..) => unreachable!(), - ty::Adt(def, substs) => { + ty::Adt(def, args) => { // Multi-variant enums are captured in entirety, // which would've been handled in the case of single empty slice in `captured_by_move_projs`. assert_eq!(def.variants().len(), 1); @@ -1412,7 +1410,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }) .collect(); - let after_field_ty = field.ty(self.tcx, substs); + let after_field_ty = field.ty(self.tcx, args); self.has_significant_drop_outside_of_captures( closure_def_id, closure_span, diff --git a/compiler/rustc_hir_typeck/src/writeback.rs b/compiler/rustc_hir_typeck/src/writeback.rs index 10645753609..cf6c7f70de3 100644 --- a/compiler/rustc_hir_typeck/src/writeback.rs +++ b/compiler/rustc_hir_typeck/src/writeback.rs @@ -4,17 +4,15 @@ use crate::FnCtxt; use hir::def_id::LocalDefId; -use rustc_data_structures::fx::FxHashMap; +use rustc_data_structures::unord::ExtendUnord; use rustc_errors::{ErrorGuaranteed, StashKey}; use rustc_hir as hir; use rustc_hir::intravisit::{self, Visitor}; use rustc_infer::infer::error_reporting::TypeAnnotationNeeded::E0282; -use rustc_middle::hir::place::Place as HirPlace; -use rustc_middle::mir::FakeReadCause; use rustc_middle::ty::adjustment::{Adjust, Adjustment, PointerCoercion}; use rustc_middle::ty::fold::{TypeFoldable, TypeFolder, TypeSuperFoldable}; use rustc_middle::ty::visit::{TypeSuperVisitable, TypeVisitable, TypeVisitableExt}; -use rustc_middle::ty::{self, ClosureSizeProfileData, Ty, TyCtxt}; +use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_span::symbol::sym; use rustc_span::Span; @@ -42,9 +40,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // This attribute causes us to dump some writeback information // in the form of errors, which is used for unit tests. - let rustc_dump_user_substs = self.tcx.has_attr(item_def_id, sym::rustc_dump_user_substs); + let rustc_dump_user_args = self.tcx.has_attr(item_def_id, sym::rustc_dump_user_args); - let mut wbcx = WritebackCx::new(self, body, rustc_dump_user_substs); + let mut wbcx = WritebackCx::new(self, body, rustc_dump_user_args); for param in body.params { wbcx.visit_node_id(param.pat.span, param.hir_id); } @@ -102,14 +100,14 @@ struct WritebackCx<'cx, 'tcx> { body: &'tcx hir::Body<'tcx>, - rustc_dump_user_substs: bool, + rustc_dump_user_args: bool, } impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { fn new( fcx: &'cx FnCtxt<'cx, 'tcx>, body: &'tcx hir::Body<'tcx>, - rustc_dump_user_substs: bool, + rustc_dump_user_args: bool, ) -> WritebackCx<'cx, 'tcx> { let owner = body.id().hir_id.owner; @@ -117,7 +115,7 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { fcx, typeck_results: ty::TypeckResults::new(owner), body, - rustc_dump_user_substs, + rustc_dump_user_args, }; // HACK: We specifically don't want the (opaque) error from tainting our @@ -154,7 +152,7 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { if inner_ty.is_scalar() { self.typeck_results.type_dependent_defs_mut().remove(e.hir_id); - self.typeck_results.node_substs_mut().remove(e.hir_id); + self.typeck_results.node_args_mut().remove(e.hir_id); } } hir::ExprKind::Binary(ref op, lhs, rhs) | hir::ExprKind::AssignOp(ref op, lhs, rhs) => { @@ -163,7 +161,7 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { if lhs_ty.is_scalar() && rhs_ty.is_scalar() { self.typeck_results.type_dependent_defs_mut().remove(e.hir_id); - self.typeck_results.node_substs_mut().remove(e.hir_id); + self.typeck_results.node_args_mut().remove(e.hir_id); match e.kind { hir::ExprKind::Binary(..) => { @@ -241,7 +239,7 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { if self.is_builtin_index(e, base_ty_inner, index_ty) { // Remove the method call record self.typeck_results.type_dependent_defs_mut().remove(e.hir_id); - self.typeck_results.node_substs_mut().remove(e.hir_id); + self.typeck_results.node_args_mut().remove(e.hir_id); if let Some(a) = self.typeck_results.adjustments_mut().get_mut(base.hir_id) { // Discard the need for a mutable borrow @@ -376,66 +374,75 @@ impl<'cx, 'tcx> Visitor<'tcx> for WritebackCx<'cx, 'tcx> { impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { fn eval_closure_size(&mut self) { - let mut res: FxHashMap<LocalDefId, ClosureSizeProfileData<'tcx>> = Default::default(); - for (&closure_def_id, data) in self.fcx.typeck_results.borrow().closure_size_eval.iter() { - let closure_hir_id = self.tcx().hir().local_def_id_to_hir_id(closure_def_id); - - let data = self.resolve(*data, &closure_hir_id); - - res.insert(closure_def_id, data); - } - - self.typeck_results.closure_size_eval = res; + self.tcx().with_stable_hashing_context(|ref hcx| { + let fcx_typeck_results = self.fcx.typeck_results.borrow(); + + self.typeck_results.closure_size_eval = fcx_typeck_results + .closure_size_eval + .to_sorted(hcx, false) + .into_iter() + .map(|(&closure_def_id, data)| { + let closure_hir_id = self.tcx().hir().local_def_id_to_hir_id(closure_def_id); + let data = self.resolve(*data, &closure_hir_id); + (closure_def_id, data) + }) + .collect(); + }) } - fn visit_min_capture_map(&mut self) { - let mut min_captures_wb = ty::MinCaptureInformationMap::with_capacity_and_hasher( - self.fcx.typeck_results.borrow().closure_min_captures.len(), - Default::default(), - ); - for (&closure_def_id, root_min_captures) in - self.fcx.typeck_results.borrow().closure_min_captures.iter() - { - let mut root_var_map_wb = ty::RootVariableMinCaptureList::with_capacity_and_hasher( - root_min_captures.len(), - Default::default(), - ); - for (var_hir_id, min_list) in root_min_captures.iter() { - let min_list_wb = min_list - .iter() - .map(|captured_place| { - let locatable = captured_place.info.path_expr_id.unwrap_or_else(|| { - self.tcx().hir().local_def_id_to_hir_id(closure_def_id) - }); - - self.resolve(captured_place.clone(), &locatable) - }) - .collect(); - root_var_map_wb.insert(*var_hir_id, min_list_wb); - } - min_captures_wb.insert(closure_def_id, root_var_map_wb); - } - self.typeck_results.closure_min_captures = min_captures_wb; + fn visit_min_capture_map(&mut self) { + self.tcx().with_stable_hashing_context(|ref hcx| { + let fcx_typeck_results = self.fcx.typeck_results.borrow(); + + self.typeck_results.closure_min_captures = fcx_typeck_results + .closure_min_captures + .to_sorted(hcx, false) + .into_iter() + .map(|(&closure_def_id, root_min_captures)| { + let root_var_map_wb = root_min_captures + .iter() + .map(|(var_hir_id, min_list)| { + let min_list_wb = min_list + .iter() + .map(|captured_place| { + let locatable = + captured_place.info.path_expr_id.unwrap_or_else(|| { + self.tcx().hir().local_def_id_to_hir_id(closure_def_id) + }); + self.resolve(captured_place.clone(), &locatable) + }) + .collect(); + (*var_hir_id, min_list_wb) + }) + .collect(); + (closure_def_id, root_var_map_wb) + }) + .collect(); + }) } fn visit_fake_reads_map(&mut self) { - let mut resolved_closure_fake_reads: FxHashMap< - LocalDefId, - Vec<(HirPlace<'tcx>, FakeReadCause, hir::HirId)>, - > = Default::default(); - for (&closure_def_id, fake_reads) in - self.fcx.typeck_results.borrow().closure_fake_reads.iter() - { - let mut resolved_fake_reads = Vec::<(HirPlace<'tcx>, FakeReadCause, hir::HirId)>::new(); - for (place, cause, hir_id) in fake_reads.iter() { - let locatable = self.tcx().hir().local_def_id_to_hir_id(closure_def_id); - - let resolved_fake_read = self.resolve(place.clone(), &locatable); - resolved_fake_reads.push((resolved_fake_read, *cause, *hir_id)); - } - resolved_closure_fake_reads.insert(closure_def_id, resolved_fake_reads); - } - self.typeck_results.closure_fake_reads = resolved_closure_fake_reads; + self.tcx().with_stable_hashing_context(move |ref hcx| { + let fcx_typeck_results = self.fcx.typeck_results.borrow(); + + self.typeck_results.closure_fake_reads = fcx_typeck_results + .closure_fake_reads + .to_sorted(hcx, true) + .into_iter() + .map(|(&closure_def_id, fake_reads)| { + let resolved_fake_reads = fake_reads + .iter() + .map(|(place, cause, hir_id)| { + let locatable = self.tcx().hir().local_def_id_to_hir_id(closure_def_id); + let resolved_fake_read = self.resolve(place.clone(), &locatable); + (resolved_fake_read, *cause, *hir_id) + }) + .collect(); + + (closure_def_id, resolved_fake_reads) + }) + .collect(); + }); } fn visit_closures(&mut self) { @@ -470,7 +477,7 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner); let common_hir_owner = fcx_typeck_results.hir_owner; - if self.rustc_dump_user_substs { + if self.rustc_dump_user_args { let sorted_user_provided_types = fcx_typeck_results.user_provided_types().items_in_stable_order(); @@ -478,7 +485,7 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { for (local_id, c_ty) in sorted_user_provided_types { let hir_id = hir::HirId { owner: common_hir_owner, local_id }; - if let ty::UserType::TypeOf(_, user_substs) = c_ty.value { + if let ty::UserType::TypeOf(_, user_args) = c_ty.value { // This is a unit-testing mechanism. let span = self.tcx().hir().span(hir_id); // We need to buffer the errors in order to guarantee a consistent @@ -486,7 +493,7 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { let err = self .tcx() .sess - .struct_span_err(span, format!("user substs: {:?}", user_substs)); + .struct_span_err(span, format!("user args: {:?}", user_args)); err.buffer(&mut errors_buffer); } } @@ -520,7 +527,7 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { let fcx_typeck_results = self.fcx.typeck_results.borrow(); assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner); - self.typeck_results.user_provided_sigs.extend( + self.typeck_results.user_provided_sigs.extend_unord( fcx_typeck_results.user_provided_sigs.items().map(|(&def_id, c_sig)| { if cfg!(debug_assertions) && c_sig.has_infer() { span_bug!( @@ -540,10 +547,15 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner); self.typeck_results.generator_interior_types = fcx_typeck_results.generator_interior_types.clone(); - for (&expr_def_id, predicates) in fcx_typeck_results.generator_interior_predicates.iter() { - let predicates = self.resolve(predicates.clone(), &self.fcx.tcx.def_span(expr_def_id)); - self.typeck_results.generator_interior_predicates.insert(expr_def_id, predicates); - } + self.tcx().with_stable_hashing_context(move |ref hcx| { + for (&expr_def_id, predicates) in + fcx_typeck_results.generator_interior_predicates.to_sorted(hcx, false).into_iter() + { + let predicates = + self.resolve(predicates.clone(), &self.fcx.tcx.def_span(expr_def_id)); + self.typeck_results.generator_interior_predicates.insert(expr_def_id, predicates); + } + }) } #[instrument(skip(self), level = "debug")] @@ -619,11 +631,11 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { debug!(?n_ty); // Resolve any substitutions - if let Some(substs) = self.fcx.typeck_results.borrow().node_substs_opt(hir_id) { - let substs = self.resolve(substs, &span); - debug!("write_substs_to_tcx({:?}, {:?})", hir_id, substs); - assert!(!substs.has_infer() && !substs.has_placeholders()); - self.typeck_results.node_substs_mut().insert(hir_id, substs); + if let Some(args) = self.fcx.typeck_results.borrow().node_args_opt(hir_id) { + let args = self.resolve(args, &span); + debug!("write_args_to_tcx({:?}, {:?})", hir_id, args); + assert!(!args.has_infer() && !args.has_placeholders()); + self.typeck_results.node_args_mut().insert(hir_id, args); } } diff --git a/compiler/rustc_incremental/src/persist/fs.rs b/compiler/rustc_incremental/src/persist/fs.rs index 7708deecec7..929a1e149b6 100644 --- a/compiler/rustc_incremental/src/persist/fs.rs +++ b/compiler/rustc_incremental/src/persist/fs.rs @@ -730,13 +730,13 @@ pub fn garbage_collect_session_directories(sess: &Session) -> io::Result<()> { debug!("garbage_collect_session_directories() - inspecting: {}", directory_name); let Ok(timestamp) = extract_timestamp_from_session_dir(directory_name) else { - debug!( - "found session-dir with malformed timestamp: {}", - crate_directory.join(directory_name).display() - ); - // Ignore it - return None; - }; + debug!( + "found session-dir with malformed timestamp: {}", + crate_directory.join(directory_name).display() + ); + // Ignore it + return None; + }; if is_finalized(directory_name) { let lock_file_path = crate_directory.join(lock_file_name); diff --git a/compiler/rustc_index/src/bit_set.rs b/compiler/rustc_index/src/bit_set.rs index 15bc3b4e388..12a7ecf8133 100644 --- a/compiler/rustc_index/src/bit_set.rs +++ b/compiler/rustc_index/src/bit_set.rs @@ -804,9 +804,7 @@ impl<'a, T: Idx> Iterator for ChunkedBitIter<'a, T> { // advance the iterator to the start of the next chunk, before proceeding in chunk sized // steps. while self.index % CHUNK_BITS != 0 { - let Some(item) = self.next() else { - return init - }; + let Some(item) = self.next() else { return init }; init = f(init, item); } let start_chunk = self.index / CHUNK_BITS; diff --git a/compiler/rustc_infer/src/errors/mod.rs b/compiler/rustc_infer/src/errors/mod.rs index 7e1fa08f23a..1ffa8633afd 100644 --- a/compiler/rustc_infer/src/errors/mod.rs +++ b/compiler/rustc_infer/src/errors/mod.rs @@ -363,7 +363,8 @@ impl AddToDiagnostic for AddLifetimeParamsSuggestion<'_> { let ( hir::Ty { kind: hir::TyKind::Ref(lifetime_sub, _), .. }, hir::Ty { kind: hir::TyKind::Ref(lifetime_sup, _), .. }, - ) = (self.ty_sub, self.ty_sup) else { + ) = (self.ty_sub, self.ty_sup) + else { return false; }; diff --git a/compiler/rustc_infer/src/infer/canonical/canonicalizer.rs b/compiler/rustc_infer/src/infer/canonical/canonicalizer.rs index e57532e2de2..1fd5d2adf80 100644 --- a/compiler/rustc_infer/src/infer/canonical/canonicalizer.rs +++ b/compiler/rustc_infer/src/infer/canonical/canonicalizer.rs @@ -11,7 +11,7 @@ use crate::infer::canonical::{ use crate::infer::InferCtxt; use rustc_middle::ty::flags::FlagComputation; use rustc_middle::ty::fold::{TypeFoldable, TypeFolder, TypeSuperFoldable}; -use rustc_middle::ty::subst::GenericArg; +use rustc_middle::ty::GenericArg; use rustc_middle::ty::{self, BoundVar, InferConst, List, Ty, TyCtxt, TypeFlags, TypeVisitableExt}; use std::sync::atomic::Ordering; diff --git a/compiler/rustc_infer/src/infer/canonical/mod.rs b/compiler/rustc_infer/src/infer/canonical/mod.rs index f765c41a367..8ca2e403043 100644 --- a/compiler/rustc_infer/src/infer/canonical/mod.rs +++ b/compiler/rustc_infer/src/infer/canonical/mod.rs @@ -25,7 +25,7 @@ use crate::infer::{ConstVariableOrigin, ConstVariableOriginKind}; use crate::infer::{InferCtxt, RegionVariableOrigin, TypeVariableOrigin, TypeVariableOriginKind}; use rustc_index::IndexVec; use rustc_middle::ty::fold::TypeFoldable; -use rustc_middle::ty::subst::GenericArg; +use rustc_middle::ty::GenericArg; use rustc_middle::ty::{self, List, Ty, TyCtxt}; use rustc_span::source_map::Span; @@ -88,7 +88,7 @@ impl<'tcx> InferCtxt<'tcx> { universe_map: impl Fn(ty::UniverseIndex) -> ty::UniverseIndex, ) -> CanonicalVarValues<'tcx> { CanonicalVarValues { - var_values: self.tcx.mk_substs_from_iter( + var_values: self.tcx.mk_args_from_iter( variables .iter() .map(|info| self.instantiate_canonical_var(span, info, &universe_map)), diff --git a/compiler/rustc_infer/src/infer/canonical/query_response.rs b/compiler/rustc_infer/src/infer/canonical/query_response.rs index 9c3ab04deae..ed101082130 100644 --- a/compiler/rustc_infer/src/infer/canonical/query_response.rs +++ b/compiler/rustc_infer/src/infer/canonical/query_response.rs @@ -25,8 +25,8 @@ use rustc_middle::arena::ArenaAllocatable; use rustc_middle::mir::ConstraintCategory; use rustc_middle::ty::fold::TypeFoldable; use rustc_middle::ty::relate::TypeRelation; -use rustc_middle::ty::subst::{GenericArg, GenericArgKind}; use rustc_middle::ty::{self, BoundVar, ToPredicate, Ty, TyCtxt}; +use rustc_middle::ty::{GenericArg, GenericArgKind}; use rustc_span::{Span, Symbol}; use std::fmt::Debug; use std::iter; @@ -484,7 +484,7 @@ impl<'tcx> InferCtxt<'tcx> { // given variable in the loop above, use that. Otherwise, use // a fresh inference variable. let result_subst = CanonicalVarValues { - var_values: self.tcx.mk_substs_from_iter( + var_values: self.tcx.mk_args_from_iter( query_response.variables.iter().enumerate().map(|(index, info)| { if info.is_existential() { match opt_values[BoundVar::new(index)] { @@ -520,7 +520,7 @@ impl<'tcx> InferCtxt<'tcx> { self.at(cause, param_env) .eq( DefineOpaqueTypes::Yes, - Ty::new_opaque(self.tcx, a.def_id.to_def_id(), a.substs), + Ty::new_opaque(self.tcx, a.def_id.to_def_id(), a.args), b, )? .obligations, diff --git a/compiler/rustc_infer/src/infer/canonical/substitute.rs b/compiler/rustc_infer/src/infer/canonical/substitute.rs index cac3b407251..f368b30fbd1 100644 --- a/compiler/rustc_infer/src/infer/canonical/substitute.rs +++ b/compiler/rustc_infer/src/infer/canonical/substitute.rs @@ -8,7 +8,7 @@ use crate::infer::canonical::{Canonical, CanonicalVarValues}; use rustc_middle::ty::fold::{FnMutDelegate, TypeFoldable}; -use rustc_middle::ty::subst::GenericArgKind; +use rustc_middle::ty::GenericArgKind; use rustc_middle::ty::{self, TyCtxt}; /// FIXME(-Ztrait-solver=next): This or public because it is shared with the diff --git a/compiler/rustc_infer/src/infer/combine.rs b/compiler/rustc_infer/src/infer/combine.rs index a9cdb8c51cf..38f8ad744a6 100644 --- a/compiler/rustc_infer/src/infer/combine.rs +++ b/compiler/rustc_infer/src/infer/combine.rs @@ -254,7 +254,7 @@ impl<'tcx> InferCtxt<'tcx> { /// in `ct` with `ct` itself. /// /// This is especially important as unevaluated consts use their parents generics. - /// They therefore often contain unused substs, making these errors far more likely. + /// They therefore often contain unused args, making these errors far more likely. /// /// A good example of this is the following: /// @@ -272,12 +272,12 @@ impl<'tcx> InferCtxt<'tcx> { /// ``` /// /// Here `3 + 4` ends up as `ConstKind::Unevaluated` which uses the generics - /// of `fn bind` (meaning that its substs contain `N`). + /// of `fn bind` (meaning that its args contain `N`). /// /// `bind(arr)` now infers that the type of `arr` must be `[u8; N]`. /// The assignment `arr = bind(arr)` now tries to equate `N` with `3 + 4`. /// - /// As `3 + 4` contains `N` in its substs, this must not succeed. + /// As `3 + 4` contains `N` in its args, this must not succeed. /// /// See `tests/ui/const-generics/occurs-check/` for more examples where this is relevant. #[instrument(level = "debug", skip(self))] diff --git a/compiler/rustc_infer/src/infer/equate.rs b/compiler/rustc_infer/src/infer/equate.rs index 495c250a77d..1dbab48fd6c 100644 --- a/compiler/rustc_infer/src/infer/equate.rs +++ b/compiler/rustc_infer/src/infer/equate.rs @@ -5,7 +5,7 @@ use super::combine::{CombineFields, ObligationEmittingRelation}; use super::Subtype; use rustc_middle::ty::relate::{self, Relate, RelateResult, TypeRelation}; -use rustc_middle::ty::subst::SubstsRef; +use rustc_middle::ty::GenericArgsRef; use rustc_middle::ty::TyVar; use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt}; @@ -43,12 +43,12 @@ impl<'tcx> TypeRelation<'tcx> for Equate<'_, '_, 'tcx> { self.a_is_expected } - fn relate_item_substs( + fn relate_item_args( &mut self, _item_def_id: DefId, - a_subst: SubstsRef<'tcx>, - b_subst: SubstsRef<'tcx>, - ) -> RelateResult<'tcx, SubstsRef<'tcx>> { + a_arg: GenericArgsRef<'tcx>, + b_arg: GenericArgsRef<'tcx>, + ) -> RelateResult<'tcx, GenericArgsRef<'tcx>> { // N.B., once we are equating types, we don't care about // variance, so don't try to lookup the variance here. This // also avoids some cycles (e.g., #41849) since looking up @@ -56,7 +56,7 @@ impl<'tcx> TypeRelation<'tcx> for Equate<'_, '_, 'tcx> { // performing trait matching (which then performs equality // unification). - relate::relate_substs(self, a_subst, b_subst) + relate::relate_args(self, a_arg, b_arg) } fn relate_with_variance<T: Relate<'tcx>>( diff --git a/compiler/rustc_infer/src/infer/error_reporting/mod.rs b/compiler/rustc_infer/src/infer/error_reporting/mod.rs index b826ced0453..bf46f9881d4 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/mod.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/mod.rs @@ -315,7 +315,7 @@ pub fn unexpected_hidden_region_diagnostic<'tcx>( ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> { let mut err = tcx.sess.create_err(errors::OpaqueCapturesLifetime { span, - opaque_ty: Ty::new_opaque(tcx, opaque_ty_key.def_id.to_def_id(), opaque_ty_key.substs), + opaque_ty: Ty::new_opaque(tcx, opaque_ty_key.def_id.to_def_id(), opaque_ty_key.args), opaque_ty_span: tcx.def_span(opaque_ty_key.def_id), }); @@ -386,16 +386,16 @@ pub fn unexpected_hidden_region_diagnostic<'tcx>( impl<'tcx> InferCtxt<'tcx> { pub fn get_impl_future_output_ty(&self, ty: Ty<'tcx>) -> Option<Ty<'tcx>> { - let (def_id, substs) = match *ty.kind() { - ty::Alias(_, ty::AliasTy { def_id, substs, .. }) + let (def_id, args) = match *ty.kind() { + ty::Alias(_, ty::AliasTy { def_id, args, .. }) if matches!(self.tcx.def_kind(def_id), DefKind::OpaqueTy) => { - (def_id, substs) + (def_id, args) } - ty::Alias(_, ty::AliasTy { def_id, substs, .. }) + ty::Alias(_, ty::AliasTy { def_id, args, .. }) if self.tcx.is_impl_trait_in_trait(def_id) => { - (def_id, substs) + (def_id, args) } _ => return None, }; @@ -403,7 +403,7 @@ impl<'tcx> InferCtxt<'tcx> { let future_trait = self.tcx.require_lang_item(LangItem::Future, None); let item_def_id = self.tcx.associated_item_def_ids(future_trait)[0]; - self.tcx.explicit_item_bounds(def_id).subst_iter_copied(self.tcx, substs).find_map( + self.tcx.explicit_item_bounds(def_id).arg_iter_copied(self.tcx, args).find_map( |(predicate, _)| { predicate .kind() @@ -573,7 +573,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { use hir::def_id::CrateNum; use rustc_hir::definitions::DisambiguatedDefPathData; use ty::print::Printer; - use ty::subst::GenericArg; + use ty::GenericArg; struct AbsolutePathPrinter<'tcx> { tcx: TyCtxt<'tcx>, @@ -711,10 +711,10 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { { // don't show type `_` if span.desugaring_kind() == Some(DesugaringKind::ForLoop) - && let ty::Adt(def, substs) = ty.kind() + && let ty::Adt(def, args) = ty.kind() && Some(def.did()) == self.tcx.get_diagnostic_item(sym::Option) { - err.span_label(span, format!("this is an iterator with items of type `{}`", substs.type_at(0))); + err.span_label(span, format!("this is an iterator with items of type `{}`", args.type_at(0))); } else { err.span_label(span, format!("this expression has type `{}`", ty)); } @@ -908,7 +908,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { value: &mut DiagnosticStyledString, other_value: &mut DiagnosticStyledString, name: String, - sub: ty::subst::SubstsRef<'tcx>, + sub: ty::GenericArgsRef<'tcx>, pos: usize, other_ty: Ty<'tcx>, ) { @@ -986,9 +986,9 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { other_path: String, other_ty: Ty<'tcx>, ) -> Option<()> { - // FIXME/HACK: Go back to `SubstsRef` to use its inherent methods, + // FIXME/HACK: Go back to `GenericArgsRef` to use its inherent methods, // ideally that shouldn't be necessary. - let sub = self.tcx.mk_substs(sub); + let sub = self.tcx.mk_args(sub); for (i, ta) in sub.types().enumerate() { if ta == other_ty { self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, other_ty); @@ -1180,9 +1180,9 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { let did1 = def1.did(); let did2 = def2.did(); let sub_no_defaults_1 = - self.tcx.generics_of(did1).own_substs_no_defaults(self.tcx, sub1); + self.tcx.generics_of(did1).own_args_no_defaults(self.tcx, sub1); let sub_no_defaults_2 = - self.tcx.generics_of(did2).own_substs_no_defaults(self.tcx, sub2); + self.tcx.generics_of(did2).own_args_no_defaults(self.tcx, sub2); let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new()); let path1 = self.tcx.def_path_str(did1); let path2 = self.tcx.def_path_str(did2); @@ -1403,11 +1403,11 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { } // When encountering tuples of the same size, highlight only the differing types - (&ty::Tuple(substs1), &ty::Tuple(substs2)) if substs1.len() == substs2.len() => { + (&ty::Tuple(args1), &ty::Tuple(args2)) if args1.len() == args2.len() => { let mut values = (DiagnosticStyledString::normal("("), DiagnosticStyledString::normal("(")); - let len = substs1.len(); - for (i, (left, right)) in substs1.iter().zip(substs2).enumerate() { + let len = args1.len(); + for (i, (left, right)) in args1.iter().zip(args2).enumerate() { let (x1, x2) = self.cmp(left, right); (values.0).0.extend(x1.0); (values.1).0.extend(x2.0); @@ -1423,35 +1423,34 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { values } - (ty::FnDef(did1, substs1), ty::FnDef(did2, substs2)) => { - let sig1 = self.tcx.fn_sig(*did1).subst(self.tcx, substs1); - let sig2 = self.tcx.fn_sig(*did2).subst(self.tcx, substs2); + (ty::FnDef(did1, args1), ty::FnDef(did2, args2)) => { + let sig1 = self.tcx.fn_sig(*did1).instantiate(self.tcx, args1); + let sig2 = self.tcx.fn_sig(*did2).instantiate(self.tcx, args2); let mut values = self.cmp_fn_sig(&sig1, &sig2); - let path1 = format!(" {{{}}}", self.tcx.def_path_str_with_substs(*did1, substs1)); - let path2 = format!(" {{{}}}", self.tcx.def_path_str_with_substs(*did2, substs2)); + let path1 = format!(" {{{}}}", self.tcx.def_path_str_with_args(*did1, args1)); + let path2 = format!(" {{{}}}", self.tcx.def_path_str_with_args(*did2, args2)); let same_path = path1 == path2; values.0.push(path1, !same_path); values.1.push(path2, !same_path); values } - (ty::FnDef(did1, substs1), ty::FnPtr(sig2)) => { - let sig1 = self.tcx.fn_sig(*did1).subst(self.tcx, substs1); + (ty::FnDef(did1, args1), ty::FnPtr(sig2)) => { + let sig1 = self.tcx.fn_sig(*did1).instantiate(self.tcx, args1); let mut values = self.cmp_fn_sig(&sig1, sig2); values.0.push_highlighted(format!( " {{{}}}", - self.tcx.def_path_str_with_substs(*did1, substs1) + self.tcx.def_path_str_with_args(*did1, args1) )); values } - (ty::FnPtr(sig1), ty::FnDef(did2, substs2)) => { - let sig2 = self.tcx.fn_sig(*did2).subst(self.tcx, substs2); + (ty::FnPtr(sig1), ty::FnDef(did2, args2)) => { + let sig2 = self.tcx.fn_sig(*did2).instantiate(self.tcx, args2); let mut values = self.cmp_fn_sig(sig1, &sig2); - values.1.push_normal(format!( - " {{{}}}", - self.tcx.def_path_str_with_substs(*did2, substs2) - )); + values + .1 + .push_normal(format!(" {{{}}}", self.tcx.def_path_str_with_args(*did2, args2))); values } @@ -2109,14 +2108,13 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { found: Ty<'tcx>, expected_fields: &List<Ty<'tcx>>, ) -> Option<TypeErrorAdditionalDiags> { - let [expected_tup_elem] = expected_fields[..] else { return None}; + let [expected_tup_elem] = expected_fields[..] else { return None }; if !self.same_type_modulo_infer(expected_tup_elem, found) { return None; } - let Ok(code) = self.tcx.sess().source_map().span_to_snippet(span) - else { return None }; + let Ok(code) = self.tcx.sess().source_map().span_to_snippet(span) else { return None }; let sugg = if code.starts_with('(') && code.ends_with(')') { let before_close = span.hi() - BytePos::from_u32(1); diff --git a/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs b/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs index bb75ecc6adb..b4d8205fd6d 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs @@ -18,7 +18,7 @@ use rustc_middle::infer::unify_key::{ConstVariableOrigin, ConstVariableOriginKin use rustc_middle::ty::adjustment::{Adjust, Adjustment, AutoBorrow}; use rustc_middle::ty::print::{FmtPrinter, PrettyPrinter, Print, Printer}; use rustc_middle::ty::{self, InferConst}; -use rustc_middle::ty::{GenericArg, GenericArgKind, SubstsRef}; +use rustc_middle::ty::{GenericArg, GenericArgKind, GenericArgsRef}; use rustc_middle::ty::{IsSuggestable, Ty, TyCtxt, TypeckResults}; use rustc_span::symbol::{kw, sym, Ident}; use rustc_span::{BytePos, Span}; @@ -162,10 +162,18 @@ fn fmt_printer<'a, 'tcx>(infcx: &'a InferCtxt<'tcx>, ns: Namespace) -> FmtPrinte let mut infcx_inner = infcx.inner.borrow_mut(); let ty_vars = infcx_inner.type_variables(); let var_origin = ty_vars.var_origin(ty_vid); - if let TypeVariableOriginKind::TypeParameterDefinition(name, _) = var_origin.kind + if let TypeVariableOriginKind::TypeParameterDefinition(name, def_id) = var_origin.kind && !var_origin.span.from_expansion() { - Some(name) + let generics = infcx.tcx.generics_of(infcx.tcx.parent(def_id)); + let idx = generics.param_def_id_to_index(infcx.tcx, def_id).unwrap(); + let generic_param_def = generics.param_at(idx as usize, infcx.tcx); + if let ty::GenericParamDefKind::Type { synthetic: true, .. } = generic_param_def.kind + { + None + } else { + Some(name) + } } else { None } @@ -218,8 +226,8 @@ fn ty_to_string<'tcx>( /// something users are familiar with. Directly printing the `fn_sig` of closures also /// doesn't work as they actually use the "rust-call" API. fn closure_as_fn_str<'tcx>(infcx: &InferCtxt<'tcx>, ty: Ty<'tcx>) -> String { - let ty::Closure(_, substs) = ty.kind() else { unreachable!() }; - let fn_sig = substs.as_closure().sig(); + let ty::Closure(_, args) = ty.kind() else { unreachable!() }; + let fn_sig = args.as_closure().sig(); let args = fn_sig .inputs() .skip_binder() @@ -411,7 +419,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { } let Some(InferSource { span, kind }) = local_visitor.infer_source else { - return self.bad_inference_failure_err(failure_span, arg_data, error_code) + return self.bad_inference_failure_err(failure_span, arg_data, error_code); }; let (source_kind, name) = kind.ty_localized_msg(self); @@ -516,9 +524,9 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { }); } } - InferSourceKind::FullyQualifiedMethodCall { receiver, successor, substs, def_id } => { + InferSourceKind::FullyQualifiedMethodCall { receiver, successor, args, def_id } => { let printer = fmt_printer(self, Namespace::ValueNS); - let def_path = printer.print_def_path(def_id, substs).unwrap().into_buffer(); + let def_path = printer.print_def_path(def_id, args).unwrap().into_buffer(); // We only care about whether we have to add `&` or `&mut ` for now. // This is the case if the last adjustment is a borrow and the @@ -651,7 +659,7 @@ enum InferSourceKind<'tcx> { /// If the method has other arguments, this is ", " and the start of the first argument, /// while for methods without arguments this is ")" and the end of the method call. successor: (&'static str, BytePos), - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, def_id: DefId, }, ClosureReturn { @@ -702,7 +710,7 @@ impl<'tcx> InferSourceKind<'tcx> { #[derive(Debug)] struct InsertableGenericArgs<'tcx> { insert_span: Span, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, generics_def_id: DefId, def_id: DefId, have_turbofish: bool, @@ -766,11 +774,11 @@ impl<'a, 'tcx> FindInferSourceVisitor<'a, 'tcx> { ty::Closure(..) => 1000, ty::FnDef(..) => 150, ty::FnPtr(..) => 30, - ty::Adt(def, substs) => { + ty::Adt(def, args) => { 5 + self .tcx .generics_of(def.did()) - .own_substs_no_defaults(self.tcx, substs) + .own_args_no_defaults(self.tcx, args) .iter() .map(|&arg| self.arg_cost(arg)) .sum::<usize>() @@ -797,8 +805,8 @@ impl<'a, 'tcx> FindInferSourceVisitor<'a, 'tcx> { }; variant_cost + generic_args.iter().map(|&arg| ctx.arg_cost(arg)).sum::<usize>() } - InferSourceKind::FullyQualifiedMethodCall { substs, .. } => { - 20 + substs.iter().map(|arg| ctx.arg_cost(arg)).sum::<usize>() + InferSourceKind::FullyQualifiedMethodCall { args, .. } => { + 20 + args.iter().map(|arg| ctx.arg_cost(arg)).sum::<usize>() } InferSourceKind::ClosureReturn { ty, should_wrap_expr, .. } => { 30 + ctx.ty_cost(ty) + if should_wrap_expr.is_some() { 10 } else { 0 } @@ -832,9 +840,9 @@ impl<'a, 'tcx> FindInferSourceVisitor<'a, 'tcx> { } } - fn node_substs_opt(&self, hir_id: HirId) -> Option<SubstsRef<'tcx>> { - let substs = self.typeck_results.node_substs_opt(hir_id); - self.infcx.resolve_vars_if_possible(substs) + fn node_args_opt(&self, hir_id: HirId) -> Option<GenericArgsRef<'tcx>> { + let args = self.typeck_results.node_args_opt(hir_id); + self.infcx.resolve_vars_if_possible(args) } fn opt_node_type(&self, hir_id: HirId) -> Option<Ty<'tcx>> { @@ -915,15 +923,15 @@ impl<'a, 'tcx> FindInferSourceVisitor<'a, 'tcx> { false } - fn expr_inferred_subst_iter( + fn expr_inferred_arg_iter( &self, expr: &'tcx hir::Expr<'tcx>, ) -> Box<dyn Iterator<Item = InsertableGenericArgs<'tcx>> + 'a> { let tcx = self.infcx.tcx; match expr.kind { hir::ExprKind::Path(ref path) => { - if let Some(substs) = self.node_substs_opt(expr.hir_id) { - return self.path_inferred_subst_iter(expr.hir_id, substs, path); + if let Some(args) = self.node_args_opt(expr.hir_id) { + return self.path_inferred_arg_iter(expr.hir_id, args, path); } } // FIXME(#98711): Ideally we would also deal with type relative @@ -935,7 +943,7 @@ impl<'a, 'tcx> FindInferSourceVisitor<'a, 'tcx> { // However, the `type_dependent_def_id` for `Self::Output` in an // impl is currently the `DefId` of `Output` in the trait definition // which makes this somewhat difficult and prevents us from just - // using `self.path_inferred_subst_iter` here. + // using `self.path_inferred_arg_iter` here. hir::ExprKind::Struct(&hir::QPath::Resolved(_self_ty, path), _, _) // FIXME(TaKO8Ki): Ideally we should support this. For that // we have to map back from the self type to the @@ -945,9 +953,9 @@ impl<'a, 'tcx> FindInferSourceVisitor<'a, 'tcx> { // a example. if !matches!(path.res, Res::Def(DefKind::TyAlias, _)) => { if let Some(ty) = self.opt_node_type(expr.hir_id) - && let ty::Adt(_, substs) = ty.kind() + && let ty::Adt(_, args) = ty.kind() { - return Box::new(self.resolved_path_inferred_subst_iter(path, substs)); + return Box::new(self.resolved_path_inferred_arg_iter(path, args)); } } hir::ExprKind::MethodCall(segment, ..) => { @@ -957,12 +965,12 @@ impl<'a, 'tcx> FindInferSourceVisitor<'a, 'tcx> { if generics.has_impl_trait() { None? } - let substs = self.node_substs_opt(expr.hir_id)?; + let args = self.node_args_opt(expr.hir_id)?; let span = tcx.hir().span(segment.hir_id); let insert_span = segment.ident.span.shrink_to_hi().with_hi(span.hi()); InsertableGenericArgs { insert_span, - substs, + args, generics_def_id: def_id, def_id, have_turbofish: false, @@ -977,10 +985,10 @@ impl<'a, 'tcx> FindInferSourceVisitor<'a, 'tcx> { Box::new(iter::empty()) } - fn resolved_path_inferred_subst_iter( + fn resolved_path_inferred_arg_iter( &self, path: &'tcx hir::Path<'tcx>, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, ) -> impl Iterator<Item = InsertableGenericArgs<'tcx>> + 'a { let tcx = self.infcx.tcx; let have_turbofish = path.segments.iter().any(|segment| { @@ -1001,7 +1009,7 @@ impl<'a, 'tcx> FindInferSourceVisitor<'a, 'tcx> { path.segments.last().unwrap().ident.span.shrink_to_hi().with_hi(path.span.hi()); InsertableGenericArgs { insert_span, - substs, + args, generics_def_id, def_id: path.res.def_id(), have_turbofish, @@ -1021,7 +1029,7 @@ impl<'a, 'tcx> FindInferSourceVisitor<'a, 'tcx> { let insert_span = segment.ident.span.shrink_to_hi().with_hi(span.hi()); Some(InsertableGenericArgs { insert_span, - substs, + args, generics_def_id, def_id: res.def_id(), have_turbofish, @@ -1030,16 +1038,16 @@ impl<'a, 'tcx> FindInferSourceVisitor<'a, 'tcx> { .chain(last_segment_using_path_data) } - fn path_inferred_subst_iter( + fn path_inferred_arg_iter( &self, hir_id: HirId, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, qpath: &'tcx hir::QPath<'tcx>, ) -> Box<dyn Iterator<Item = InsertableGenericArgs<'tcx>> + 'a> { let tcx = self.infcx.tcx; match qpath { hir::QPath::Resolved(_self_ty, path) => { - Box::new(self.resolved_path_inferred_subst_iter(path, substs)) + Box::new(self.resolved_path_inferred_arg_iter(path, args)) } hir::QPath::TypeRelative(ty, segment) => { let Some(def_id) = self.typeck_results.type_dependent_def_id(hir_id) else { @@ -1055,7 +1063,7 @@ impl<'a, 'tcx> FindInferSourceVisitor<'a, 'tcx> { let insert_span = segment.ident.span.shrink_to_hi().with_hi(span.hi()); InsertableGenericArgs { insert_span, - substs, + args, generics_def_id: def_id, def_id, have_turbofish: false, @@ -1064,10 +1072,10 @@ impl<'a, 'tcx> FindInferSourceVisitor<'a, 'tcx> { let parent_def_id = generics.parent.unwrap(); if let DefKind::Impl { .. } = tcx.def_kind(parent_def_id) { - let parent_ty = tcx.type_of(parent_def_id).subst(tcx, substs); + let parent_ty = tcx.type_of(parent_def_id).instantiate(tcx, args); match (parent_ty.kind(), &ty.kind) { ( - ty::Adt(def, substs), + ty::Adt(def, args), hir::TyKind::Path(hir::QPath::Resolved(_self_ty, path)), ) => { if tcx.res_generics_def_id(path.res) != Some(def.did()) { @@ -1084,14 +1092,13 @@ impl<'a, 'tcx> FindInferSourceVisitor<'a, 'tcx> { // so there's nothing for us to do here. Res::SelfTyParam { .. } | Res::SelfTyAlias { .. } => {} _ => warn!( - "unexpected path: def={:?} substs={:?} path={:?}", - def, substs, path, + "unexpected path: def={:?} args={:?} path={:?}", + def, args, path, ), } } else { return Box::new( - self.resolved_path_inferred_subst_iter(path, substs) - .chain(segment), + self.resolved_path_inferred_arg_iter(path, args).chain(segment), ); } } @@ -1149,9 +1156,7 @@ impl<'a, 'tcx> Visitor<'tcx> for FindInferSourceVisitor<'a, 'tcx> { continue; } - let Some(param_ty) = self.opt_node_type(param.hir_id) else { - continue - }; + let Some(param_ty) = self.opt_node_type(param.hir_id) else { continue }; if self.generic_arg_contains_target(param_ty.into()) { self.update_infer_source(InferSource { @@ -1181,27 +1186,27 @@ impl<'a, 'tcx> Visitor<'tcx> for FindInferSourceVisitor<'a, 'tcx> { _ => intravisit::walk_expr(self, expr), } - for args in self.expr_inferred_subst_iter(expr) { + for args in self.expr_inferred_arg_iter(expr) { debug!(?args); let InsertableGenericArgs { insert_span, - substs, + args, generics_def_id, def_id, have_turbofish, } = args; let generics = tcx.generics_of(generics_def_id); if let Some(mut argument_index) = generics - .own_substs(substs) + .own_args(args) .iter() .position(|&arg| self.generic_arg_contains_target(arg)) { if generics.parent.is_none() && generics.has_self { argument_index += 1; } - let substs = self.infcx.resolve_vars_if_possible(substs); - let generic_args = &generics.own_substs_no_defaults(tcx, substs) - [generics.own_counts().lifetimes..]; + let args = self.infcx.resolve_vars_if_possible(args); + let generic_args = + &generics.own_args_no_defaults(tcx, args)[generics.own_counts().lifetimes..]; let span = match expr.kind { ExprKind::MethodCall(path, ..) => path.ident.span, _ => expr.span, @@ -1224,10 +1229,10 @@ impl<'a, 'tcx> Visitor<'tcx> for FindInferSourceVisitor<'a, 'tcx> { if let Some(node_ty) = self.opt_node_type(expr.hir_id) { if let ( &ExprKind::Closure(&Closure { fn_decl, body, fn_decl_span, .. }), - ty::Closure(_, substs), + ty::Closure(_, args), ) = (&expr.kind, node_ty.kind()) { - let output = substs.as_closure().sig().output().skip_binder(); + let output = args.as_closure().sig().output().skip_binder(); if self.generic_arg_contains_target(output.into()) { let body = self.infcx.tcx.hir().body(body); let should_wrap_expr = if matches!(body.value.kind, ExprKind::Block(..)) { @@ -1253,22 +1258,22 @@ impl<'a, 'tcx> Visitor<'tcx> for FindInferSourceVisitor<'a, 'tcx> { }) .any(|generics| generics.has_impl_trait()) }; - if let ExprKind::MethodCall(path, receiver, args, span) = expr.kind - && let Some(substs) = self.node_substs_opt(expr.hir_id) - && substs.iter().any(|arg| self.generic_arg_contains_target(arg)) + if let ExprKind::MethodCall(path, receiver, method_args, span) = expr.kind + && let Some(args) = self.node_args_opt(expr.hir_id) + && args.iter().any(|arg| self.generic_arg_contains_target(arg)) && let Some(def_id) = self.typeck_results.type_dependent_def_id(expr.hir_id) && self.infcx.tcx.trait_of_item(def_id).is_some() && !has_impl_trait(def_id) { let successor = - args.get(0).map_or_else(|| (")", span.hi()), |arg| (", ", arg.span.lo())); - let substs = self.infcx.resolve_vars_if_possible(substs); + method_args.get(0).map_or_else(|| (")", span.hi()), |arg| (", ", arg.span.lo())); + let args = self.infcx.resolve_vars_if_possible(args); self.update_infer_source(InferSource { span: path.ident.span, kind: InferSourceKind::FullyQualifiedMethodCall { receiver, successor, - substs, + args, def_id, } }) diff --git a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/mismatched_static_lifetime.rs b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/mismatched_static_lifetime.rs index 2c63a390410..6901955af65 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/mismatched_static_lifetime.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/mismatched_static_lifetime.rs @@ -38,8 +38,9 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { let ObligationCauseCode::MatchImpl(parent, impl_def_id) = code else { return None; }; - let (ObligationCauseCode::BindingObligation(_, binding_span) | ObligationCauseCode::ExprBindingObligation(_, binding_span, ..)) - = *parent.code() else { + let (ObligationCauseCode::BindingObligation(_, binding_span) + | ObligationCauseCode::ExprBindingObligation(_, binding_span, ..)) = *parent.code() + else { return None; }; @@ -67,12 +68,13 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { let hir::Node::Item(hir::Item { kind: hir::ItemKind::Impl(hir::Impl { self_ty: impl_self_ty, .. }), .. - }) = impl_node else { + }) = impl_node + else { bug!("Node not an impl."); }; // Next, let's figure out the set of trait objects with implicit static bounds - let ty = self.tcx().type_of(*impl_def_id).subst_identity(); + let ty = self.tcx().type_of(*impl_def_id).instantiate_identity(); let mut v = super::static_impl_trait::TraitObjectVisitor(FxIndexSet::default()); v.visit_ty(ty); let mut traits = vec![]; diff --git a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/placeholder_error.rs b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/placeholder_error.rs index 0b3bc1ce6b3..f903f7a49ef 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/placeholder_error.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/placeholder_error.rs @@ -13,7 +13,7 @@ use rustc_hir::def::Namespace; use rustc_hir::def_id::DefId; use rustc_middle::ty::error::ExpectedFound; use rustc_middle::ty::print::{FmtPrinter, Print, RegionHighlightMode}; -use rustc_middle::ty::subst::SubstsRef; +use rustc_middle::ty::GenericArgsRef; use rustc_middle::ty::{self, RePlaceholder, Region, TyCtxt}; use std::fmt; @@ -196,11 +196,11 @@ impl<'tcx> NiceRegionError<'_, 'tcx> { sup_placeholder: Option<Region<'tcx>>, value_pairs: &ValuePairs<'tcx>, ) -> Option<DiagnosticBuilder<'tcx, ErrorGuaranteed>> { - let (expected_substs, found_substs, trait_def_id) = match value_pairs { + let (expected_args, found_args, trait_def_id) = match value_pairs { ValuePairs::TraitRefs(ExpectedFound { expected, found }) if expected.def_id == found.def_id => { - (expected.substs, found.substs, expected.def_id) + (expected.args, found.args, expected.def_id) } ValuePairs::PolyTraitRefs(ExpectedFound { expected, found }) if expected.def_id() == found.def_id() => @@ -208,7 +208,7 @@ impl<'tcx> NiceRegionError<'_, 'tcx> { // It's possible that the placeholders come from a binder // outside of this value pair. Use `no_bound_vars` as a // simple heuristic for that. - (expected.no_bound_vars()?.substs, found.no_bound_vars()?.substs, expected.def_id()) + (expected.no_bound_vars()?.args, found.no_bound_vars()?.args, expected.def_id()) } _ => return None, }; @@ -219,8 +219,8 @@ impl<'tcx> NiceRegionError<'_, 'tcx> { sub_placeholder, sup_placeholder, trait_def_id, - expected_substs, - found_substs, + expected_args, + found_args, )) } @@ -241,8 +241,8 @@ impl<'tcx> NiceRegionError<'_, 'tcx> { sub_placeholder: Option<Region<'tcx>>, sup_placeholder: Option<Region<'tcx>>, trait_def_id: DefId, - expected_substs: SubstsRef<'tcx>, - actual_substs: SubstsRef<'tcx>, + expected_args: GenericArgsRef<'tcx>, + actual_args: GenericArgsRef<'tcx>, ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> { let span = cause.span(); @@ -264,12 +264,12 @@ impl<'tcx> NiceRegionError<'_, 'tcx> { let expected_trait_ref = self.cx.resolve_vars_if_possible(ty::TraitRef::new( self.cx.tcx, trait_def_id, - expected_substs, + expected_args, )); let actual_trait_ref = self.cx.resolve_vars_if_possible(ty::TraitRef::new( self.cx.tcx, trait_def_id, - actual_substs, + actual_args, )); // Search the expected and actual trait references to see (a) @@ -413,9 +413,9 @@ impl<'tcx> NiceRegionError<'_, 'tcx> { if self_ty.value.is_closure() && self.tcx().is_fn_trait(expected_trait_ref.value.def_id) { let closure_sig = self_ty.map(|closure| { - if let ty::Closure(_, substs) = closure.kind() { + if let ty::Closure(_, args) = closure.kind() { self.tcx().signature_unclosure( - substs.as_closure().sig(), + args.as_closure().sig(), rustc_hir::Unsafety::Normal, ) } else { diff --git a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs index a9b485a6f7e..cc92bfbfdfe 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs @@ -288,7 +288,7 @@ pub fn suggest_new_region_bound( // Get the identity type for this RPIT let did = item_id.owner_id.to_def_id(); - let ty = Ty::new_opaque(tcx, did, ty::InternalSubsts::identity_for_item(tcx, did)); + let ty = Ty::new_opaque(tcx, did, ty::GenericArgs::identity_for_item(tcx, did)); if let Some(span) = opaque.bounds.iter().find_map(|arg| match arg { GenericBound::Outlives(Lifetime { @@ -493,7 +493,7 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { tcx, ctxt.param_env, ctxt.assoc_item.def_id, - self.cx.resolve_vars_if_possible(ctxt.substs), + self.cx.resolve_vars_if_possible(ctxt.args), ) else { return false; }; @@ -503,7 +503,9 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { // Get the `Ident` of the method being called and the corresponding `impl` (to point at // `Bar` in `impl Foo for dyn Bar {}` and the definition of the method being called). - let Some((ident, self_ty)) = NiceRegionError::get_impl_ident_and_self_ty_from_trait(tcx, instance.def_id(), &v.0) else { + let Some((ident, self_ty)) = + NiceRegionError::get_impl_ident_and_self_ty_from_trait(tcx, instance.def_id(), &v.0) + else { return false; }; diff --git a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/util.rs b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/util.rs index c5ef48fe3da..2775b5ded03 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/util.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/util.rs @@ -65,7 +65,7 @@ pub fn find_param_with_region<'tcx>( let owner_id = hir.body_owner(body_id); let fn_decl = hir.fn_decl_by_hir_id(owner_id).unwrap(); - let poly_fn_sig = tcx.fn_sig(id).subst_identity(); + let poly_fn_sig = tcx.fn_sig(id).instantiate_identity(); let fn_sig = tcx.liberate_late_bound_regions(id, poly_fn_sig); let body = hir.body(body_id); @@ -123,7 +123,7 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { br: ty::BoundRegionKind, hir_sig: &hir::FnSig<'_>, ) -> Option<Span> { - let fn_ty = self.tcx().type_of(scope_def_id).subst_identity(); + let fn_ty = self.tcx().type_of(scope_def_id).instantiate_identity(); if let ty::FnDef(_, _) = fn_ty.kind() { let ret_ty = fn_ty.fn_sig(self.tcx()).output(); let span = hir_sig.decl.output.span(); diff --git a/compiler/rustc_infer/src/infer/error_reporting/note.rs b/compiler/rustc_infer/src/infer/error_reporting/note.rs index e55e9e75fb6..7144084c78e 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/note.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/note.rs @@ -295,34 +295,40 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { // but right now it's not really very smart when it comes to implicit `Sized` // predicates and bounds on the trait itself. - let Some(impl_def_id) = - self.tcx.associated_item(impl_item_def_id).impl_container(self.tcx) else { return; }; - let Some(trait_ref) = self - .tcx - .impl_trait_ref(impl_def_id) - else { return; }; - let trait_substs = trait_ref - .subst_identity() + let Some(impl_def_id) = self.tcx.associated_item(impl_item_def_id).impl_container(self.tcx) + else { + return; + }; + let Some(trait_ref) = self.tcx.impl_trait_ref(impl_def_id) else { + return; + }; + let trait_args = trait_ref + .instantiate_identity() // Replace the explicit self type with `Self` for better suggestion rendering .with_self_ty(self.tcx, Ty::new_param(self.tcx, 0, kw::SelfUpper)) - .substs; - let trait_item_substs = ty::InternalSubsts::identity_for_item(self.tcx, impl_item_def_id) - .rebase_onto(self.tcx, impl_def_id, trait_substs); + .args; + let trait_item_args = ty::GenericArgs::identity_for_item(self.tcx, impl_item_def_id) + .rebase_onto(self.tcx, impl_def_id, trait_args); - let Ok(trait_predicates) = self - .tcx - .explicit_predicates_of(trait_item_def_id) - .instantiate_own(self.tcx, trait_item_substs) - .map(|(pred, _)| { - if pred.is_suggestable(self.tcx, false) { - Ok(pred.to_string()) - } else { - Err(()) - } - }) - .collect::<Result<Vec<_>, ()>>() else { return; }; + let Ok(trait_predicates) = + self.tcx + .explicit_predicates_of(trait_item_def_id) + .instantiate_own(self.tcx, trait_item_args) + .map(|(pred, _)| { + if pred.is_suggestable(self.tcx, false) { + Ok(pred.to_string()) + } else { + Err(()) + } + }) + .collect::<Result<Vec<_>, ()>>() + else { + return; + }; - let Some(generics) = self.tcx.hir().get_generics(impl_item_def_id) else { return; }; + let Some(generics) = self.tcx.hir().get_generics(impl_item_def_id) else { + return; + }; let suggestion = if trait_predicates.is_empty() { WhereClauseSuggestions::Remove { span: generics.where_clause_span } diff --git a/compiler/rustc_infer/src/infer/error_reporting/note_and_explain.rs b/compiler/rustc_infer/src/infer/error_reporting/note_and_explain.rs index 63613b59020..8e3f6b97e8f 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/note_and_explain.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/note_and_explain.rs @@ -100,9 +100,9 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { { // Synthesize the associated type restriction `Add<Output = Expected>`. // FIXME: extract this logic for use in other diagnostics. - let (trait_ref, assoc_substs) = proj.trait_ref_and_own_substs(tcx); + let (trait_ref, assoc_args) = proj.trait_ref_and_own_args(tcx); let item_name = tcx.item_name(proj.def_id); - let item_args = self.format_generic_args(assoc_substs); + let item_args = self.format_generic_args(assoc_args); // Here, we try to see if there's an existing // trait implementation that matches the one that @@ -316,7 +316,7 @@ impl<T> Trait<T> for X { ) -> bool { let tcx = self.tcx; let assoc = tcx.associated_item(proj_ty.def_id); - let (trait_ref, assoc_substs) = proj_ty.trait_ref_and_own_substs(tcx); + let (trait_ref, assoc_args) = proj_ty.trait_ref_and_own_args(tcx); if let Some(item) = tcx.hir().get_if_local(body_owner_def_id) { if let Some(hir_generics) = item.generics() { // Get the `DefId` for the type parameter corresponding to `A` in `<A as T>::Foo`. @@ -339,7 +339,7 @@ impl<T> Trait<T> for X { &trait_ref, pred.bounds, assoc, - assoc_substs, + assoc_args, ty, &msg, false, @@ -488,14 +488,14 @@ fn foo(&self) -> Self::T { String::new() } return false; }; - let (trait_ref, assoc_substs) = proj_ty.trait_ref_and_own_substs(tcx); + let (trait_ref, assoc_args) = proj_ty.trait_ref_and_own_args(tcx); self.constrain_generic_bound_associated_type_structured_suggestion( diag, &trait_ref, opaque_hir_ty.bounds, assoc, - assoc_substs, + assoc_args, ty, msg, true, @@ -527,7 +527,7 @@ fn foo(&self) -> Self::T { String::new() } && !tcx.is_doc_hidden(item.def_id) }) .filter_map(|item| { - let method = tcx.fn_sig(item.def_id).subst_identity(); + let method = tcx.fn_sig(item.def_id).instantiate_identity(); match *method.output().skip_binder().kind() { ty::Alias(ty::Projection, ty::AliasTy { def_id: item_def_id, .. }) if item_def_id == proj_ty_item_def_id => @@ -597,7 +597,7 @@ fn foo(&self) -> Self::T { String::new() } if let hir::Defaultness::Default { has_value: true } = tcx.defaultness(item.id.owner_id) { - let assoc_ty = tcx.type_of(item.id.owner_id).subst_identity(); + let assoc_ty = tcx.type_of(item.id.owner_id).instantiate_identity(); if self.infcx.can_eq(param_env, assoc_ty, found) { diag.span_label( item.span, @@ -618,7 +618,7 @@ fn foo(&self) -> Self::T { String::new() } })) => { for item in &items[..] { if let hir::AssocItemKind::Type = item.kind { - let assoc_ty = tcx.type_of(item.id.owner_id).subst_identity(); + let assoc_ty = tcx.type_of(item.id.owner_id).instantiate_identity(); if self.infcx.can_eq(param_env, assoc_ty, found) { diag.span_label(item.span, "expected this associated type"); @@ -645,7 +645,7 @@ fn foo(&self) -> Self::T { String::new() } trait_ref: &ty::TraitRef<'tcx>, bounds: hir::GenericBounds<'_>, assoc: ty::AssocItem, - assoc_substs: &[ty::GenericArg<'tcx>], + assoc_args: &[ty::GenericArg<'tcx>], ty: Ty<'tcx>, msg: impl Fn() -> String, is_bound_surely_present: bool, @@ -671,14 +671,7 @@ fn foo(&self) -> Self::T { String::new() } _ => return false, }; - self.constrain_associated_type_structured_suggestion( - diag, - span, - assoc, - assoc_substs, - ty, - msg, - ) + self.constrain_associated_type_structured_suggestion(diag, span, assoc, assoc_args, ty, msg) } /// Given a span corresponding to a bound, provide a structured suggestion to set an @@ -688,7 +681,7 @@ fn foo(&self) -> Self::T { String::new() } diag: &mut Diagnostic, span: Span, assoc: ty::AssocItem, - assoc_substs: &[ty::GenericArg<'tcx>], + assoc_args: &[ty::GenericArg<'tcx>], ty: Ty<'tcx>, msg: impl Fn() -> String, ) -> bool { @@ -702,7 +695,7 @@ fn foo(&self) -> Self::T { String::new() } let span = Span::new(pos, pos, span.ctxt(), span.parent()); (span, format!(", {} = {}", assoc.ident(tcx), ty)) } else { - let item_args = self.format_generic_args(assoc_substs); + let item_args = self.format_generic_args(assoc_args); (span.shrink_to_hi(), format!("<{}{} = {}>", assoc.ident(tcx), item_args, ty)) }; diag.span_suggestion_verbose(span, msg(), sugg, MaybeIncorrect); diff --git a/compiler/rustc_infer/src/infer/error_reporting/suggest.rs b/compiler/rustc_infer/src/infer/error_reporting/suggest.rs index 1422bdc9ea2..ce5d3791a48 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/suggest.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/suggest.rs @@ -105,7 +105,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { // Heavily inspired by `FnCtxt::suggest_compatible_variants`, with // some modifications due to that being in typeck and this being in infer. if let ObligationCauseCode::Pattern { .. } = cause.code() { - if let ty::Adt(expected_adt, substs) = exp_found.expected.kind() { + if let ty::Adt(expected_adt, args) = exp_found.expected.kind() { let compatible_variants: Vec<_> = expected_adt .variants() .iter() @@ -114,7 +114,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { }) .filter_map(|variant| { let sole_field = &variant.single_field(); - let sole_field_ty = sole_field.ty(self.tcx, substs); + let sole_field_ty = sole_field.ty(self.tcx, args); if self.same_type_modulo_infer(sole_field_ty, exp_found.found) { let variant_path = with_no_trimmed_paths!(self.tcx.def_path_str(variant.def_id)); @@ -260,7 +260,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { "suggest_accessing_field_where_appropriate(cause={:?}, exp_found={:?})", cause, exp_found ); - if let ty::Adt(expected_def, expected_substs) = exp_found.expected.kind() { + if let ty::Adt(expected_def, expected_args) = exp_found.expected.kind() { if expected_def.is_enum() { return; } @@ -270,7 +270,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { .fields .iter() .filter(|field| field.vis.is_accessible_from(field.did, self.tcx)) - .map(|field| (field.name, field.ty(self.tcx, expected_substs))) + .map(|field| (field.name, field.ty(self.tcx, expected_args))) .find(|(_, ty)| self.same_type_modulo_infer(*ty, exp_found.found)) { if let ObligationCauseCode::Pattern { span: Some(span), .. } = *cause.code() { @@ -304,12 +304,12 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { return; } match (&expected_inner.kind(), &found_inner.kind()) { - (ty::FnPtr(sig), ty::FnDef(did, substs)) => { + (ty::FnPtr(sig), ty::FnDef(did, args)) => { let expected_sig = &(self.normalize_fn_sig)(*sig); let found_sig = - &(self.normalize_fn_sig)(self.tcx.fn_sig(*did).subst(self.tcx, substs)); + &(self.normalize_fn_sig)(self.tcx.fn_sig(*did).instantiate(self.tcx, args)); - let fn_name = self.tcx.def_path_str_with_substs(*did, substs); + let fn_name = self.tcx.def_path_str_with_args(*did, args); if !self.same_type_modulo_infer(*found_sig, *expected_sig) || !sig.is_suggestable(self.tcx, true) @@ -332,11 +332,11 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { }; diag.subdiagnostic(sugg); } - (ty::FnDef(did1, substs1), ty::FnDef(did2, substs2)) => { + (ty::FnDef(did1, args1), ty::FnDef(did2, args2)) => { let expected_sig = - &(self.normalize_fn_sig)(self.tcx.fn_sig(*did1).subst(self.tcx, substs1)); + &(self.normalize_fn_sig)(self.tcx.fn_sig(*did1).instantiate(self.tcx, args1)); let found_sig = - &(self.normalize_fn_sig)(self.tcx.fn_sig(*did2).subst(self.tcx, substs2)); + &(self.normalize_fn_sig)(self.tcx.fn_sig(*did2).instantiate(self.tcx, args2)); if self.same_type_modulo_infer(*expected_sig, *found_sig) { diag.subdiagnostic(FnUniqTypes); @@ -351,7 +351,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { return; } - let fn_name = self.tcx.def_path_str_with_substs(*did2, substs2); + let fn_name = self.tcx.def_path_str_with_args(*did2, args2); let sug = if found.is_ref() { FunctionPointerSuggestion::CastBothRef { span, @@ -370,16 +370,16 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { diag.subdiagnostic(sug); } - (ty::FnDef(did, substs), ty::FnPtr(sig)) => { + (ty::FnDef(did, args), ty::FnPtr(sig)) => { let expected_sig = - &(self.normalize_fn_sig)(self.tcx.fn_sig(*did).subst(self.tcx, substs)); + &(self.normalize_fn_sig)(self.tcx.fn_sig(*did).instantiate(self.tcx, args)); let found_sig = &(self.normalize_fn_sig)(*sig); if !self.same_type_modulo_infer(*found_sig, *expected_sig) { return; } - let fn_name = self.tcx.def_path_str_with_substs(*did, substs); + let fn_name = self.tcx.def_path_str_with_args(*did, args); let casting = if expected.is_ref() { format!("&({fn_name} as {found_sig})") @@ -400,10 +400,10 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { expected: Ty<'tcx>, found: Ty<'tcx>, ) -> Option<SuggestAsRefKind> { - if let (ty::Adt(exp_def, exp_substs), ty::Ref(_, found_ty, _)) = + if let (ty::Adt(exp_def, exp_args), ty::Ref(_, found_ty, _)) = (expected.kind(), found.kind()) { - if let ty::Adt(found_def, found_substs) = *found_ty.kind() { + if let ty::Adt(found_def, found_args) = *found_ty.kind() { if exp_def == &found_def { let have_as_ref = &[ (sym::Option, SuggestAsRefKind::Option), @@ -414,7 +414,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { }) { let mut show_suggestion = true; for (exp_ty, found_ty) in - std::iter::zip(exp_substs.types(), found_substs.types()) + std::iter::zip(exp_args.types(), found_args.types()) { match *exp_ty.kind() { ty::Ref(_, exp_ty, _) => { @@ -464,52 +464,53 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { span: Span, ) -> Option<TypeErrorAdditionalDiags> { let hir = self.tcx.hir(); - if let Some(node) = self.tcx.hir().find_by_def_id(cause.body_id) && - let hir::Node::Item(hir::Item { - kind: hir::ItemKind::Fn(_sig, _, body_id), .. - }) = node { - let body = hir.body(*body_id); - - /// Find the if expression with given span - struct IfVisitor { - pub result: bool, - pub found_if: bool, - pub err_span: Span, - } + if let Some(body_id) = self.tcx.hir().maybe_body_owned_by(cause.body_id) { + let body = hir.body(body_id); + + /// Find the if expression with given span + struct IfVisitor { + pub result: bool, + pub found_if: bool, + pub err_span: Span, + } - impl<'v> Visitor<'v> for IfVisitor { - fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) { - if self.result { return; } - match ex.kind { - hir::ExprKind::If(cond, _, _) => { - self.found_if = true; - walk_expr(self, cond); - self.found_if = false; + impl<'v> Visitor<'v> for IfVisitor { + fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) { + if self.result { + return; + } + match ex.kind { + hir::ExprKind::If(cond, _, _) => { + self.found_if = true; + walk_expr(self, cond); + self.found_if = false; + } + _ => walk_expr(self, ex), } - _ => walk_expr(self, ex), } - } - fn visit_stmt(&mut self, ex: &'v hir::Stmt<'v>) { - if let hir::StmtKind::Local(hir::Local { - span, pat: hir::Pat{..}, ty: None, init: Some(_), .. - }) = &ex.kind - && self.found_if - && span.eq(&self.err_span) { - self.result = true; + fn visit_stmt(&mut self, ex: &'v hir::Stmt<'v>) { + if let hir::StmtKind::Local(hir::Local { + span, pat: hir::Pat{..}, ty: None, init: Some(_), .. + }) = &ex.kind + && self.found_if + && span.eq(&self.err_span) { + self.result = true; + } + walk_stmt(self, ex); } - walk_stmt(self, ex); - } - fn visit_body(&mut self, body: &'v hir::Body<'v>) { - hir::intravisit::walk_body(self, body); + fn visit_body(&mut self, body: &'v hir::Body<'v>) { + hir::intravisit::walk_body(self, body); + } } - } - let mut visitor = IfVisitor { err_span: span, found_if: false, result: false }; - visitor.visit_body(&body); - if visitor.result { - return Some(TypeErrorAdditionalDiags::AddLetForLetChains{span: span.shrink_to_lo()}); + let mut visitor = IfVisitor { err_span: span, found_if: false, result: false }; + visitor.visit_body(&body); + if visitor.result { + return Some(TypeErrorAdditionalDiags::AddLetForLetChains { + span: span.shrink_to_lo(), + }); } } None @@ -525,13 +526,23 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { diag: &mut Diagnostic, ) { // 0. Extract fn_decl from hir - let hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(hir::Closure { body, fn_decl, .. }), .. }) = hir else { return; }; + let hir::Node::Expr(hir::Expr { + kind: hir::ExprKind::Closure(hir::Closure { body, fn_decl, .. }), + .. + }) = hir + else { + return; + }; let hir::Body { params, .. } = self.tcx.hir().body(*body); - // 1. Get the substs of the closure. + // 1. Get the args of the closure. // 2. Assume exp_found is FnOnce / FnMut / Fn, we can extract function parameters from [1]. - let Some(expected) = exp_found.expected.skip_binder().substs.get(1) else { return; }; - let Some(found) = exp_found.found.skip_binder().substs.get(1) else { return; }; + let Some(expected) = exp_found.expected.skip_binder().args.get(1) else { + return; + }; + let Some(found) = exp_found.found.skip_binder().args.get(1) else { + return; + }; let expected = expected.unpack(); let found = found.unpack(); // 3. Extract the tuple type from Fn trait and suggest the change. @@ -620,8 +631,8 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { ty::Alias(ty::Opaque, ty::AliasTy { def_id: exp_def_id, .. }), ) if last_def_id == exp_def_id => StatementAsExpression::CorrectType, ( - ty::Alias(ty::Opaque, ty::AliasTy { def_id: last_def_id, substs: last_bounds, .. }), - ty::Alias(ty::Opaque, ty::AliasTy { def_id: exp_def_id, substs: exp_bounds, .. }), + ty::Alias(ty::Opaque, ty::AliasTy { def_id: last_def_id, args: last_bounds, .. }), + ty::Alias(ty::Opaque, ty::AliasTy { def_id: exp_def_id, args: exp_bounds, .. }), ) => { debug!( "both opaque, likely future {:?} {:?} {:?} {:?}", @@ -710,7 +721,9 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { let hir = self.tcx.hir(); for stmt in blk.stmts.iter().rev() { - let hir::StmtKind::Local(local) = &stmt.kind else { continue; }; + let hir::StmtKind::Local(local) = &stmt.kind else { + continue; + }; local.pat.walk(&mut find_compatible_candidates); } match hir.find_parent(blk.hir_id) { diff --git a/compiler/rustc_infer/src/infer/freshen.rs b/compiler/rustc_infer/src/infer/freshen.rs index 05769b7907a..689945d644c 100644 --- a/compiler/rustc_infer/src/infer/freshen.rs +++ b/compiler/rustc_infer/src/infer/freshen.rs @@ -11,7 +11,7 @@ //! //! To handle closures, freshened types also have to contain the signature and kind of any //! closure in the local inference context, as otherwise the cache key might be invalidated. -//! The way this is done is somewhat hacky - the closure signature is appended to the substs, +//! The way this is done is somewhat hacky - the closure signature is appended to the args, //! as well as the closure kind "encoded" as a type. Also, special handling is needed when //! the closure signature contains a reference to the original closure. //! diff --git a/compiler/rustc_infer/src/infer/generalize.rs b/compiler/rustc_infer/src/infer/generalize.rs index 78025016757..cf674d5dda6 100644 --- a/compiler/rustc_infer/src/infer/generalize.rs +++ b/compiler/rustc_infer/src/infer/generalize.rs @@ -173,21 +173,21 @@ where true } - fn relate_item_substs( + fn relate_item_args( &mut self, item_def_id: DefId, - a_subst: ty::SubstsRef<'tcx>, - b_subst: ty::SubstsRef<'tcx>, - ) -> RelateResult<'tcx, ty::SubstsRef<'tcx>> { + a_subst: ty::GenericArgsRef<'tcx>, + b_subst: ty::GenericArgsRef<'tcx>, + ) -> RelateResult<'tcx, ty::GenericArgsRef<'tcx>> { if self.ambient_variance == ty::Variance::Invariant { // Avoid fetching the variance if we are in an invariant // context; no need, and it can induce dependency cycles // (e.g., #41849). - relate::relate_substs(self, a_subst, b_subst) + relate::relate_args(self, a_subst, b_subst) } else { let tcx = self.tcx(); let opt_variances = tcx.variances_of(item_def_id); - relate::relate_substs_with_variances( + relate::relate_args_with_variances( self, item_def_id, opt_variances, @@ -405,16 +405,16 @@ where } // FIXME: remove this branch once `structurally_relate_consts` is fully // structural. - ty::ConstKind::Unevaluated(ty::UnevaluatedConst { def, substs }) => { - let substs = self.relate_with_variance( + ty::ConstKind::Unevaluated(ty::UnevaluatedConst { def, args }) => { + let args = self.relate_with_variance( ty::Variance::Invariant, ty::VarianceDiagInfo::default(), - substs, - substs, + args, + args, )?; Ok(ty::Const::new_unevaluated( self.tcx(), - ty::UnevaluatedConst { def, substs }, + ty::UnevaluatedConst { def, args }, c.ty(), )) } diff --git a/compiler/rustc_infer/src/infer/mod.rs b/compiler/rustc_infer/src/infer/mod.rs index fca32b73d1d..a73e84f94c4 100644 --- a/compiler/rustc_infer/src/infer/mod.rs +++ b/compiler/rustc_infer/src/infer/mod.rs @@ -30,11 +30,11 @@ use rustc_middle::ty::error::{ExpectedFound, TypeError}; use rustc_middle::ty::fold::BoundVarReplacerDelegate; use rustc_middle::ty::fold::{TypeFoldable, TypeFolder, TypeSuperFoldable}; use rustc_middle::ty::relate::RelateResult; -use rustc_middle::ty::subst::{GenericArg, GenericArgKind, InternalSubsts, SubstsRef}; use rustc_middle::ty::visit::{TypeVisitable, TypeVisitableExt}; pub use rustc_middle::ty::IntVarValue; use rustc_middle::ty::{self, GenericParamDefKind, InferConst, InferTy, Ty, TyCtxt}; use rustc_middle::ty::{ConstVid, FloatVid, IntVid, TyVid}; +use rustc_middle::ty::{GenericArg, GenericArgKind, GenericArgs, GenericArgsRef}; use rustc_span::symbol::Symbol; use rustc_span::Span; @@ -332,6 +332,39 @@ pub struct InferCtxt<'tcx> { next_trait_solver: bool, } +impl<'tcx> ty::InferCtxtLike<TyCtxt<'tcx>> for InferCtxt<'tcx> { + fn universe_of_ty(&self, ty: ty::InferTy) -> Option<ty::UniverseIndex> { + use InferTy::*; + match ty { + // FIXME(BoxyUwU): this is kind of jank and means that printing unresolved + // ty infers will give you the universe of the var it resolved to not the universe + // it actually had. It also means that if you have a `?0.1` and infer it to `u8` then + // try to print out `?0.1` it will just print `?0`. + TyVar(ty_vid) => match self.probe_ty_var(ty_vid) { + Err(universe) => Some(universe), + Ok(_) => None, + }, + IntVar(_) | FloatVar(_) | FreshTy(_) | FreshIntTy(_) | FreshFloatTy(_) => None, + } + } + + fn universe_of_ct(&self, ct: ty::InferConst<'tcx>) -> Option<ty::UniverseIndex> { + use ty::InferConst::*; + match ct { + // Same issue as with `universe_of_ty` + Var(ct_vid) => match self.probe_const_var(ct_vid) { + Err(universe) => Some(universe), + Ok(_) => None, + }, + Fresh(_) => None, + } + } + + fn universe_of_lt(&self, lt: ty::RegionVid) -> Option<ty::UniverseIndex> { + Some(self.universe_of_region_vid(lt)) + } +} + /// See the `error_reporting` module for more details. #[derive(Clone, Copy, Debug, PartialEq, Eq, TypeFoldable, TypeVisitable)] pub enum ValuePairs<'tcx> { @@ -1068,6 +1101,11 @@ impl<'tcx> InferCtxt<'tcx> { self.inner.borrow_mut().unwrap_region_constraints().universe(r) } + /// Return the universe that the region variable `r` was created in. + pub fn universe_of_region_vid(&self, vid: ty::RegionVid) -> ty::UniverseIndex { + self.inner.borrow_mut().unwrap_region_constraints().var_universe(vid) + } + /// Number of region variables created so far. pub fn num_region_vars(&self) -> usize { self.inner.borrow_mut().unwrap_region_constraints().num_region_vars() @@ -1146,8 +1184,8 @@ impl<'tcx> InferCtxt<'tcx> { /// Given a set of generics defined on a type or impl, returns a substitution mapping each /// type/region parameter to a fresh inference variable. - pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> SubstsRef<'tcx> { - InternalSubsts::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param)) + pub fn fresh_args_for_item(&self, span: Span, def_id: DefId) -> GenericArgsRef<'tcx> { + GenericArgs::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param)) } /// Returns `true` if errors have been reported since this infcx was @@ -1436,8 +1474,8 @@ impl<'tcx> InferCtxt<'tcx> { /// Obtains the latest type of the given closure; this may be a /// closure in the current function, in which case its /// `ClosureKind` may not yet be known. - pub fn closure_kind(&self, closure_substs: SubstsRef<'tcx>) -> Option<ty::ClosureKind> { - let closure_kind_ty = closure_substs.as_closure().kind_ty(); + pub fn closure_kind(&self, closure_args: GenericArgsRef<'tcx>) -> Option<ty::ClosureKind> { + let closure_kind_ty = closure_args.as_closure().kind_ty(); let closure_kind_ty = self.shallow_resolve(closure_kind_ty); closure_kind_ty.to_opt_closure_kind() } @@ -1496,7 +1534,7 @@ impl<'tcx> InferCtxt<'tcx> { /// too generic for the constant to be evaluated then `Err(ErrorHandled::TooGeneric)` is /// returned. /// - /// This handles inferences variables within both `param_env` and `substs` by + /// This handles inferences variables within both `param_env` and `args` by /// performing the operation on their respective canonical forms. #[instrument(skip(self), level = "debug")] pub fn const_eval_resolve( @@ -1505,34 +1543,34 @@ impl<'tcx> InferCtxt<'tcx> { unevaluated: ty::UnevaluatedConst<'tcx>, span: Option<Span>, ) -> EvalToValTreeResult<'tcx> { - let mut substs = self.resolve_vars_if_possible(unevaluated.substs); - debug!(?substs); + let mut args = self.resolve_vars_if_possible(unevaluated.args); + debug!(?args); - // Postpone the evaluation of constants whose substs depend on inference + // Postpone the evaluation of constants whose args depend on inference // variables let tcx = self.tcx; - if substs.has_non_region_infer() { + if args.has_non_region_infer() { if let Some(ct) = tcx.thir_abstract_const(unevaluated.def)? { - let ct = tcx.expand_abstract_consts(ct.subst(tcx, substs)); + let ct = tcx.expand_abstract_consts(ct.instantiate(tcx, args)); if let Err(e) = ct.error_reported() { return Err(ErrorHandled::Reported(e.into())); } else if ct.has_non_region_infer() || ct.has_non_region_param() { return Err(ErrorHandled::TooGeneric); } else { - substs = replace_param_and_infer_substs_with_placeholder(tcx, substs); + args = replace_param_and_infer_args_with_placeholder(tcx, args); } } else { - substs = InternalSubsts::identity_for_item(tcx, unevaluated.def); + args = GenericArgs::identity_for_item(tcx, unevaluated.def); param_env = tcx.param_env(unevaluated.def); } } let param_env_erased = tcx.erase_regions(param_env); - let substs_erased = tcx.erase_regions(substs); + let args_erased = tcx.erase_regions(args); debug!(?param_env_erased); - debug!(?substs_erased); + debug!(?args_erased); - let unevaluated = ty::UnevaluatedConst { def: unevaluated.def, substs: substs_erased }; + let unevaluated = ty::UnevaluatedConst { def: unevaluated.def, args: args_erased }; // The return value is the evaluated value which doesn't contain any reference to inference // variables, thus we don't need to substitute back the original values. @@ -1921,13 +1959,13 @@ impl RegionVariableOrigin { } } -/// Replaces substs that reference param or infer variables with suitable +/// Replaces args that reference param or infer variables with suitable /// placeholders. This function is meant to remove these param and infer -/// substs when they're not actually needed to evaluate a constant. -fn replace_param_and_infer_substs_with_placeholder<'tcx>( +/// args when they're not actually needed to evaluate a constant. +fn replace_param_and_infer_args_with_placeholder<'tcx>( tcx: TyCtxt<'tcx>, - substs: SubstsRef<'tcx>, -) -> SubstsRef<'tcx> { + args: GenericArgsRef<'tcx>, +) -> GenericArgsRef<'tcx> { struct ReplaceParamAndInferWithPlaceholder<'tcx> { tcx: TyCtxt<'tcx>, idx: u32, @@ -1985,5 +2023,5 @@ fn replace_param_and_infer_substs_with_placeholder<'tcx>( } } - substs.fold_with(&mut ReplaceParamAndInferWithPlaceholder { tcx, idx: 0 }) + args.fold_with(&mut ReplaceParamAndInferWithPlaceholder { tcx, idx: 0 }) } diff --git a/compiler/rustc_infer/src/infer/opaque_types.rs b/compiler/rustc_infer/src/infer/opaque_types.rs index 5927f79a183..90f0b4ce401 100644 --- a/compiler/rustc_infer/src/infer/opaque_types.rs +++ b/compiler/rustc_infer/src/infer/opaque_types.rs @@ -103,7 +103,7 @@ impl<'tcx> InferCtxt<'tcx> { } let (a, b) = if a_is_expected { (a, b) } else { (b, a) }; let process = |a: Ty<'tcx>, b: Ty<'tcx>, a_is_expected| match *a.kind() { - ty::Alias(ty::Opaque, ty::AliasTy { def_id, substs, .. }) if def_id.is_local() => { + ty::Alias(ty::Opaque, ty::AliasTy { def_id, args, .. }) if def_id.is_local() => { let def_id = def_id.expect_local(); match self.defining_use_anchor { DefiningAnchor::Bind(_) => { @@ -165,7 +165,7 @@ impl<'tcx> InferCtxt<'tcx> { } } Some(self.register_hidden_type( - OpaqueTypeKey { def_id, substs }, + OpaqueTypeKey { def_id, args }, cause.clone(), param_env, b, @@ -214,12 +214,12 @@ impl<'tcx> InferCtxt<'tcx> { /// fn foo<'a, 'b>(..) -> (Foo1<'a>, Foo2<'b>) { .. } /// // ^^^^ ^^ /// // | | - /// // | substs + /// // | args /// // def_id /// ``` /// /// As indicating in the comments above, each of those references - /// is (in the compiler) basically a substitution (`substs`) + /// is (in the compiler) basically a substitution (`args`) /// applied to the type of a suitable `def_id` (which identifies /// `Foo1` or `Foo2`). /// @@ -278,7 +278,7 @@ impl<'tcx> InferCtxt<'tcx> { /// /// We generally prefer to make `<=` constraints, since they /// integrate best into the region solver. To do that, we find the - /// "minimum" of all the arguments that appear in the substs: that + /// "minimum" of all the arguments that appear in the args: that /// is, some region which is less than all the others. In the case /// of `Foo1<'a>`, that would be `'a` (it's the only choice, after /// all). Then we apply that as a least bound to the variables @@ -350,7 +350,7 @@ impl<'tcx> InferCtxt<'tcx> { // opaque type definition. let choice_regions: Lrc<Vec<ty::Region<'tcx>>> = Lrc::new( opaque_type_key - .substs + .args .iter() .enumerate() .filter(|(i, _)| variances[*i] == ty::Variance::Invariant) @@ -445,28 +445,28 @@ where } match ty.kind() { - ty::Closure(_, ref substs) => { + ty::Closure(_, ref args) => { // Skip lifetime parameters of the enclosing item(s) - substs.as_closure().tupled_upvars_ty().visit_with(self); - substs.as_closure().sig_as_fn_ptr_ty().visit_with(self); + args.as_closure().tupled_upvars_ty().visit_with(self); + args.as_closure().sig_as_fn_ptr_ty().visit_with(self); } - ty::Generator(_, ref substs, _) => { + ty::Generator(_, ref args, _) => { // Skip lifetime parameters of the enclosing item(s) // Also skip the witness type, because that has no free regions. - substs.as_generator().tupled_upvars_ty().visit_with(self); - substs.as_generator().return_ty().visit_with(self); - substs.as_generator().yield_ty().visit_with(self); - substs.as_generator().resume_ty().visit_with(self); + args.as_generator().tupled_upvars_ty().visit_with(self); + args.as_generator().return_ty().visit_with(self); + args.as_generator().yield_ty().visit_with(self); + args.as_generator().resume_ty().visit_with(self); } - ty::Alias(ty::Opaque, ty::AliasTy { def_id, ref substs, .. }) => { + ty::Alias(ty::Opaque, ty::AliasTy { def_id, ref args, .. }) => { // Skip lifetime parameters that are not captures. let variances = self.tcx.variances_of(*def_id); - for (v, s) in std::iter::zip(variances, substs.iter()) { + for (v, s) in std::iter::zip(variances, args.iter()) { if *v != ty::Variance::Bivariant { s.visit_with(self); } @@ -519,7 +519,7 @@ impl<'tcx> InferCtxt<'tcx> { self.add_item_bounds_for_hidden_type( opaque_type_key.def_id.to_def_id(), - opaque_type_key.substs, + opaque_type_key.args, cause, param_env, hidden_ty, @@ -582,7 +582,7 @@ impl<'tcx> InferCtxt<'tcx> { pub fn add_item_bounds_for_hidden_type( &self, def_id: DefId, - substs: ty::SubstsRef<'tcx>, + args: ty::GenericArgsRef<'tcx>, cause: ObligationCause<'tcx>, param_env: ty::ParamEnv<'tcx>, hidden_ty: Ty<'tcx>, @@ -591,7 +591,7 @@ impl<'tcx> InferCtxt<'tcx> { let tcx = self.tcx; let item_bounds = tcx.explicit_item_bounds(def_id); - for (predicate, _) in item_bounds.subst_iter_copied(tcx, substs) { + for (predicate, _) in item_bounds.arg_iter_copied(tcx, args) { let predicate = predicate.fold_with(&mut BottomUpFolder { tcx, ty_op: |ty| match *ty.kind() { @@ -614,17 +614,18 @@ impl<'tcx> InferCtxt<'tcx> { } // Replace all other mentions of the same opaque type with the hidden type, // as the bounds must hold on the hidden type after all. - ty::Alias(ty::Opaque, ty::AliasTy { def_id: def_id2, substs: substs2, .. }) - if def_id == def_id2 && substs == substs2 => + ty::Alias(ty::Opaque, ty::AliasTy { def_id: def_id2, args: args2, .. }) + if def_id == def_id2 && args == args2 => { hidden_ty } // FIXME(RPITIT): This can go away when we move to associated types // FIXME(inherent_associated_types): Extend this to support `ty::Inherent`, too. - ty::Alias( - ty::Projection, - ty::AliasTy { def_id: def_id2, substs: substs2, .. }, - ) if def_id == def_id2 && substs == substs2 => hidden_ty, + ty::Alias(ty::Projection, ty::AliasTy { def_id: def_id2, args: args2, .. }) + if def_id == def_id2 && args == args2 => + { + hidden_ty + } _ => ty, }, lt_op: |lt| lt, diff --git a/compiler/rustc_infer/src/infer/outlives/components.rs b/compiler/rustc_infer/src/infer/outlives/components.rs index cb63d2f18b6..2ac9568f60b 100644 --- a/compiler/rustc_infer/src/infer/outlives/components.rs +++ b/compiler/rustc_infer/src/infer/outlives/components.rs @@ -3,8 +3,8 @@ // RFC for reference. use rustc_data_structures::sso::SsoHashSet; -use rustc_middle::ty::subst::{GenericArg, GenericArgKind}; use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt}; +use rustc_middle::ty::{GenericArg, GenericArgKind}; use smallvec::{smallvec, SmallVec}; #[derive(Debug)] @@ -71,15 +71,15 @@ fn compute_components<'tcx>( // in the `subtys` iterator (e.g., when encountering a // projection). match *ty.kind() { - ty::FnDef(_, substs) => { - // HACK(eddyb) ignore lifetimes found shallowly in `substs`. - // This is inconsistent with `ty::Adt` (including all substs) - // and with `ty::Closure` (ignoring all substs other than + ty::FnDef(_, args) => { + // HACK(eddyb) ignore lifetimes found shallowly in `args`. + // This is inconsistent with `ty::Adt` (including all args) + // and with `ty::Closure` (ignoring all args other than // upvars, of which a `ty::FnDef` doesn't have any), but // consistent with previous (accidental) behavior. // See https://github.com/rust-lang/rust/issues/70917 // for further background and discussion. - for child in substs { + for child in args { match child.unpack() { GenericArgKind::Type(ty) => { compute_components(tcx, ty, out, visited); @@ -97,14 +97,14 @@ fn compute_components<'tcx>( compute_components(tcx, element, out, visited); } - ty::Closure(_, ref substs) => { - let tupled_ty = substs.as_closure().tupled_upvars_ty(); + ty::Closure(_, ref args) => { + let tupled_ty = args.as_closure().tupled_upvars_ty(); compute_components(tcx, tupled_ty, out, visited); } - ty::Generator(_, ref substs, _) => { + ty::Generator(_, ref args, _) => { // Same as the closure case - let tupled_ty = substs.as_generator().tupled_upvars_ty(); + let tupled_ty = args.as_generator().tupled_upvars_ty(); compute_components(tcx, tupled_ty, out, visited); // We ignore regions in the generator interior as we don't @@ -189,7 +189,7 @@ fn compute_components<'tcx>( } } -/// Collect [Component]s for *all* the substs of `parent`. +/// Collect [Component]s for *all* the args of `parent`. /// /// This should not be used to get the components of `parent` itself. /// Use [push_outlives_components] instead. @@ -201,7 +201,7 @@ pub(super) fn compute_alias_components_recursive<'tcx>( ) { let ty::Alias(kind, alias_ty) = alias_ty.kind() else { bug!() }; let opt_variances = if *kind == ty::Opaque { tcx.variances_of(alias_ty.def_id) } else { &[] }; - for (index, child) in alias_ty.substs.iter().enumerate() { + for (index, child) in alias_ty.args.iter().enumerate() { if opt_variances.get(index) == Some(&ty::Bivariant) { continue; } @@ -225,7 +225,7 @@ pub(super) fn compute_alias_components_recursive<'tcx>( } } -/// Collect [Component]s for *all* the substs of `parent`. +/// Collect [Component]s for *all* the args of `parent`. /// /// This should not be used to get the components of `parent` itself. /// Use [push_outlives_components] instead. diff --git a/compiler/rustc_infer/src/infer/outlives/obligations.rs b/compiler/rustc_infer/src/infer/outlives/obligations.rs index 73df6d03f86..0681f414ce9 100644 --- a/compiler/rustc_infer/src/infer/outlives/obligations.rs +++ b/compiler/rustc_infer/src/infer/outlives/obligations.rs @@ -68,8 +68,8 @@ use crate::infer::{ use crate::traits::{ObligationCause, ObligationCauseCode}; use rustc_data_structures::undo_log::UndoLogs; use rustc_middle::mir::ConstraintCategory; -use rustc_middle::ty::subst::GenericArgKind; -use rustc_middle::ty::{self, Region, SubstsRef, Ty, TyCtxt, TypeVisitableExt}; +use rustc_middle::ty::GenericArgKind; +use rustc_middle::ty::{self, GenericArgsRef, Region, Ty, TyCtxt, TypeVisitableExt}; use smallvec::smallvec; use super::env::OutlivesEnvironment; @@ -279,7 +279,7 @@ where alias_ty: ty::AliasTy<'tcx>, ) { // An optimization for a common case with opaque types. - if alias_ty.substs.is_empty() { + if alias_ty.args.is_empty() { return; } @@ -348,7 +348,7 @@ where { debug!("no declared bounds"); let opt_variances = is_opaque.then(|| self.tcx.variances_of(alias_ty.def_id)); - self.substs_must_outlive(alias_ty.substs, origin, region, opt_variances); + self.args_must_outlive(alias_ty.args, origin, region, opt_variances); return; } @@ -395,15 +395,15 @@ where } #[instrument(level = "debug", skip(self))] - fn substs_must_outlive( + fn args_must_outlive( &mut self, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, origin: infer::SubregionOrigin<'tcx>, region: ty::Region<'tcx>, opt_variances: Option<&[ty::Variance]>, ) { let constraint = origin.to_constraint_category(); - for (index, k) in substs.iter().enumerate() { + for (index, k) in args.iter().enumerate() { match k.unpack() { GenericArgKind::Lifetime(lt) => { let variance = if let Some(variances) = opt_variances { diff --git a/compiler/rustc_infer/src/infer/outlives/test_type_match.rs b/compiler/rustc_infer/src/infer/outlives/test_type_match.rs index cd2462d3c31..fefa8959545 100644 --- a/compiler/rustc_infer/src/infer/outlives/test_type_match.rs +++ b/compiler/rustc_infer/src/infer/outlives/test_type_match.rs @@ -157,7 +157,7 @@ impl<'tcx> TypeRelation<'tcx> for Match<'tcx> { a: T, b: T, ) -> RelateResult<'tcx, T> { - // Opaque types substs have lifetime parameters. + // Opaque types args have lifetime parameters. // We must not check them to be equal, as we never insert anything to make them so. if variance != ty::Bivariant { self.relate(a, b) } else { Ok(a) } } diff --git a/compiler/rustc_infer/src/infer/outlives/verify.rs b/compiler/rustc_infer/src/infer/outlives/verify.rs index 1a5e2b520b8..1e1ecd3fb94 100644 --- a/compiler/rustc_infer/src/infer/outlives/verify.rs +++ b/compiler/rustc_infer/src/infer/outlives/verify.rs @@ -295,7 +295,7 @@ impl<'cx, 'tcx> VerifyBoundCx<'cx, 'tcx> { let bounds = tcx.item_bounds(alias_ty.def_id); trace!("{:#?}", bounds.skip_binder()); bounds - .subst_iter(tcx, alias_ty.substs) + .arg_iter(tcx, alias_ty.args) .filter_map(|p| p.as_type_outlives_clause()) .filter_map(|p| p.no_bound_vars()) .map(|OutlivesPredicate(_, r)| r) diff --git a/compiler/rustc_infer/src/infer/type_variable.rs b/compiler/rustc_infer/src/infer/type_variable.rs index 01c11d16345..bc83f8d3f96 100644 --- a/compiler/rustc_infer/src/infer/type_variable.rs +++ b/compiler/rustc_infer/src/infer/type_variable.rs @@ -125,7 +125,7 @@ pub enum TypeVariableOriginKind { OpaqueTypeInference(DefId), TypeParameterDefinition(Symbol, DefId), - /// One of the upvars or closure kind parameters in a `ClosureSubsts` + /// One of the upvars or closure kind parameters in a `ClosureArgs` /// (before it has been determined). // FIXME(eddyb) distinguish upvar inference variables from the rest. ClosureSynthetic, diff --git a/compiler/rustc_interface/src/interface.rs b/compiler/rustc_interface/src/interface.rs index 953c2e4b8f8..3f420f19efe 100644 --- a/compiler/rustc_interface/src/interface.rs +++ b/compiler/rustc_interface/src/interface.rs @@ -59,11 +59,6 @@ impl Compiler { } } -#[allow(rustc::bad_opt_access)] -pub fn set_thread_safe_mode(sopts: &config::UnstableOptions) { - rustc_data_structures::sync::set_dyn_thread_safe_mode(sopts.threads > 1); -} - /// Converts strings provided as `--cfg [cfgspec]` into a `crate_cfg`. pub fn parse_cfgspecs( handler: &EarlyErrorHandler, @@ -190,7 +185,8 @@ pub fn parse_check_cfg(handler: &EarlyErrorHandler, specs: Vec<String>) -> Check ExpectedValues::Some(FxHashSet::default()) }); - let ExpectedValues::Some(expected_values) = expected_values else { + let ExpectedValues::Some(expected_values) = expected_values + else { bug!("`expected_values` should be a list a values") }; @@ -288,6 +284,10 @@ pub struct Config { #[allow(rustc::bad_opt_access)] pub fn run_compiler<R: Send>(config: Config, f: impl FnOnce(&Compiler) -> R + Send) -> R { trace!("run_compiler"); + + // Set parallel mode before thread pool creation, which will create `Lock`s. + rustc_data_structures::sync::set_dyn_thread_safe_mode(config.opts.unstable_opts.threads > 1); + util::run_in_thread_pool_with_globals( config.opts.edition, config.opts.unstable_opts.threads, diff --git a/compiler/rustc_lint/src/array_into_iter.rs b/compiler/rustc_lint/src/array_into_iter.rs index bccb0a94e98..d0967ba5644 100644 --- a/compiler/rustc_lint/src/array_into_iter.rs +++ b/compiler/rustc_lint/src/array_into_iter.rs @@ -81,7 +81,7 @@ impl<'tcx> LateLintPass<'tcx> for ArrayIntoIter { let adjustments = cx.typeck_results().expr_adjustments(receiver_arg); let Some(Adjustment { kind: Adjust::Borrow(_), target }) = adjustments.last() else { - return + return; }; let types = diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index b821933e908..84aca80b0de 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -61,7 +61,7 @@ use rustc_hir::{Body, FnDecl, ForeignItemKind, GenericParamKind, Node, PatKind, use rustc_middle::lint::in_external_macro; use rustc_middle::ty::layout::{LayoutError, LayoutOf}; use rustc_middle::ty::print::with_no_trimmed_paths; -use rustc_middle::ty::subst::GenericArgKind; +use rustc_middle::ty::GenericArgKind; use rustc_middle::ty::TypeVisitableExt; use rustc_middle::ty::{self, Instance, Ty, TyCtxt, VariantDef}; use rustc_session::config::ExpectedValues; @@ -181,9 +181,11 @@ impl<'tcx> LateLintPass<'tcx> for BoxPointers { | hir::ItemKind::TyAlias(..) | hir::ItemKind::Enum(..) | hir::ItemKind::Struct(..) - | hir::ItemKind::Union(..) => { - self.check_heap_type(cx, it.span, cx.tcx.type_of(it.owner_id).subst_identity()) - } + | hir::ItemKind::Union(..) => self.check_heap_type( + cx, + it.span, + cx.tcx.type_of(it.owner_id).instantiate_identity(), + ), _ => (), } @@ -194,7 +196,7 @@ impl<'tcx> LateLintPass<'tcx> for BoxPointers { self.check_heap_type( cx, field.span, - cx.tcx.type_of(field.def_id).subst_identity(), + cx.tcx.type_of(field.def_id).instantiate_identity(), ); } } @@ -591,7 +593,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingDoc { // If the method is an impl for an item with docs_hidden, don't doc. MethodLateContext::PlainImpl => { let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id()); - let impl_ty = cx.tcx.type_of(parent).subst_identity(); + let impl_ty = cx.tcx.type_of(parent).instantiate_identity(); let outerdef = match impl_ty.kind() { ty::Adt(def, _) => Some(def.did()), ty::Foreign(def_id) => Some(*def_id), @@ -700,7 +702,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingCopyImplementations { // and recommending Copy might be a bad idea. for field in def.all_fields() { let did = field.did; - if cx.tcx.type_of(did).subst_identity().is_unsafe_ptr() { + if cx.tcx.type_of(did).instantiate_identity().is_unsafe_ptr() { return; } } @@ -793,14 +795,12 @@ impl<'tcx> LateLintPass<'tcx> for MissingDebugImplementations { _ => return, } - let Some(debug) = cx.tcx.get_diagnostic_item(sym::Debug) else { - return - }; + let Some(debug) = cx.tcx.get_diagnostic_item(sym::Debug) else { return }; if self.impling_types.is_none() { let mut impls = LocalDefIdSet::default(); cx.tcx.for_each_impl(debug, |d| { - if let Some(ty_def) = cx.tcx.type_of(d).subst_identity().ty_adt_def() { + if let Some(ty_def) = cx.tcx.type_of(d).instantiate_identity().ty_adt_def() { if let Some(def_id) = ty_def.did().as_local() { impls.insert(def_id); } @@ -1458,9 +1458,7 @@ impl TypeAliasBounds { impl<'tcx> LateLintPass<'tcx> for TypeAliasBounds { fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) { - let hir::ItemKind::TyAlias(ty, type_alias_generics) = &item.kind else { - return - }; + let hir::ItemKind::TyAlias(ty, type_alias_generics) = &item.kind else { return }; if cx.tcx.type_of(item.owner_id.def_id).skip_binder().has_opaque_types() { // Bounds are respected for `type X = impl Trait` and `type X = (impl Trait, Y);` return; @@ -2147,8 +2145,8 @@ impl<'tcx> LateLintPass<'tcx> for ExplicitOutlivesRequirements { match predicate.bounded_ty.kind { hir::TyKind::Path(hir::QPath::Resolved(None, path)) => { let Res::Def(DefKind::TyParam, def_id) = path.res else { - continue; - }; + continue; + }; let index = ty_generics.param_def_id_to_index[&def_id]; ( Self::lifetimes_outliving_type(inferred_outlives, index), @@ -2459,12 +2457,12 @@ impl<'tcx> LateLintPass<'tcx> for InvalidValue { cx: &LateContext<'tcx>, ty: Ty<'tcx>, variant: &VariantDef, - substs: ty::SubstsRef<'tcx>, + args: ty::GenericArgsRef<'tcx>, descr: &str, init: InitKind, ) -> Option<InitError> { let mut field_err = variant.fields.iter().find_map(|field| { - ty_find_init_error(cx, field.ty(cx.tcx, substs), init).map(|mut err| { + ty_find_init_error(cx, field.ty(cx.tcx, args), init).map(|mut err| { if !field.did.is_local() { err } else if err.span.is_none() { @@ -2541,14 +2539,14 @@ impl<'tcx> LateLintPass<'tcx> for InvalidValue { Some("raw pointers must be initialized".into()) } // Recurse and checks for some compound types. (but not unions) - Adt(adt_def, substs) if !adt_def.is_union() => { + Adt(adt_def, args) if !adt_def.is_union() => { // Handle structs. if adt_def.is_struct() { return variant_find_init_error( cx, ty, adt_def.non_enum_variant(), - substs, + args, "struct field", init, ); @@ -2558,7 +2556,7 @@ impl<'tcx> LateLintPass<'tcx> for InvalidValue { let mut potential_variants = adt_def.variants().iter().filter_map(|variant| { let definitely_inhabited = match variant .inhabited_predicate(cx.tcx, *adt_def) - .subst(cx.tcx, substs) + .instantiate(cx.tcx, args) .apply_any_module(cx.tcx, cx.param_env) { // Entirely skip uninhabited variants. @@ -2570,7 +2568,10 @@ impl<'tcx> LateLintPass<'tcx> for InvalidValue { Some((variant, definitely_inhabited)) }); let Some(first_variant) = potential_variants.next() else { - return Some(InitError::from("enums with no inhabited variants have no valid value").spanned(span)); + return Some( + InitError::from("enums with no inhabited variants have no valid value") + .spanned(span), + ); }; // So we have at least one potentially inhabited variant. Might we have two? let Some(second_variant) = potential_variants.next() else { @@ -2579,7 +2580,7 @@ impl<'tcx> LateLintPass<'tcx> for InvalidValue { cx, ty, &first_variant.0, - substs, + args, "field of the only potentially inhabited enum variant", init, ); @@ -2779,7 +2780,7 @@ impl ClashingExternDeclarations { // type unless the newtype makes the type non-null. let non_transparent_ty = |mut ty: Ty<'tcx>| -> Ty<'tcx> { loop { - if let ty::Adt(def, substs) = *ty.kind() { + if let ty::Adt(def, args) = *ty.kind() { let is_transparent = def.repr().transparent(); let is_non_null = crate::types::nonnull_optimization_guaranteed(tcx, def); debug!( @@ -2792,7 +2793,7 @@ impl ClashingExternDeclarations { // continue with `ty`'s non-ZST field, // otherwise `ty` is a ZST and we can return if let Some(field) = transparent_newtype_field(tcx, v) { - ty = field.ty(tcx, substs); + ty = field.ty(tcx, args); continue; } } @@ -2858,8 +2859,8 @@ impl ClashingExternDeclarations { structurally_same_type_impl( seen_types, cx, - tcx.type_of(a_did).subst_identity(), - tcx.type_of(b_did).subst_identity(), + tcx.type_of(a_did).instantiate_identity(), + tcx.type_of(b_did).instantiate_identity(), ckind, ) }, @@ -2906,8 +2907,8 @@ impl ClashingExternDeclarations { ckind, ) } - (Tuple(a_substs), Tuple(b_substs)) => { - a_substs.iter().eq_by(b_substs.iter(), |a_ty, b_ty| { + (Tuple(a_args), Tuple(b_args)) => { + a_args.iter().eq_by(b_args.iter(), |a_ty, b_ty| { structurally_same_type_impl(seen_types, cx, a_ty, b_ty, ckind) }) } @@ -2961,7 +2962,7 @@ impl<'tcx> LateLintPass<'tcx> for ClashingExternDeclarations { let tcx = cx.tcx; if let Some(existing_did) = self.insert(tcx, this_fi) { let existing_decl_ty = tcx.type_of(existing_did).skip_binder(); - let this_decl_ty = tcx.type_of(this_fi.owner_id).subst_identity(); + let this_decl_ty = tcx.type_of(this_fi.owner_id).instantiate_identity(); debug!( "ClashingExternDeclarations: Comparing existing {:?}: {:?} to this {:?}: {:?}", existing_did, existing_decl_ty, this_fi.owner_id, this_decl_ty @@ -3181,7 +3182,7 @@ impl<'tcx> LateLintPass<'tcx> for NamedAsmLabels { let mut chars = possible_label.chars(); let Some(c) = chars.next() else { // Empty string means a leading ':' in this section, which is not a label - break + break; }; // A label starts with an alphabetic character or . or _ and continues with alphanumeric characters, _, or $ if (c.is_alphabetic() || matches!(c, '.' | '_')) diff --git a/compiler/rustc_lint/src/cast_ref_to_mut.rs b/compiler/rustc_lint/src/cast_ref_to_mut.rs index 84308d48c10..82bb70bc9e7 100644 --- a/compiler/rustc_lint/src/cast_ref_to_mut.rs +++ b/compiler/rustc_lint/src/cast_ref_to_mut.rs @@ -37,7 +37,9 @@ declare_lint_pass!(CastRefToMut => [CAST_REF_TO_MUT]); impl<'tcx> LateLintPass<'tcx> for CastRefToMut { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) { - let ExprKind::Unary(UnOp::Deref, e) = &expr.kind else { return; }; + let ExprKind::Unary(UnOp::Deref, e) = &expr.kind else { + return; + }; let e = e.peel_blocks(); let e = if let ExprKind::Cast(e, t) = e.kind diff --git a/compiler/rustc_lint/src/context.rs b/compiler/rustc_lint/src/context.rs index 3761754f3ae..6522e449386 100644 --- a/compiler/rustc_lint/src/context.rs +++ b/compiler/rustc_lint/src/context.rs @@ -35,7 +35,7 @@ use rustc_middle::middle::privacy::EffectiveVisibilities; use rustc_middle::middle::stability; use rustc_middle::ty::layout::{LayoutError, LayoutOfHelpers, TyAndLayout}; use rustc_middle::ty::print::with_no_trimmed_paths; -use rustc_middle::ty::{self, print::Printer, subst::GenericArg, RegisteredTools, Ty, TyCtxt}; +use rustc_middle::ty::{self, print::Printer, GenericArg, RegisteredTools, Ty, TyCtxt}; use rustc_session::config::ExpectedValues; use rustc_session::lint::{BuiltinLintDiagnostics, LintExpectationId}; use rustc_session::lint::{FutureIncompatibleInfo, Level, Lint, LintBuffer, LintId}; @@ -956,6 +956,14 @@ pub trait LintContext: Sized { db.span_note(glob_reexport_span, format!("the name `{}` in the {} namespace is supposed to be publicly re-exported here", name, namespace)); db.span_note(private_item_span, "but the private item here shadows it".to_owned()); } + BuiltinLintDiagnostics::UnusedQualifications { path_span, unqualified_path } => { + db.span_suggestion_verbose( + path_span, + "replace it with the unqualified path", + unqualified_path, + Applicability::MachineApplicable + ); + } } // Rewrap `db`, and pass control to the user. decorate(db) @@ -1265,8 +1273,8 @@ impl<'tcx> LateContext<'tcx> { trait_ref: Option<ty::TraitRef<'tcx>>, ) -> Result<Self::Path, Self::Error> { if trait_ref.is_none() { - if let ty::Adt(def, substs) = self_ty.kind() { - return self.print_def_path(def.did(), substs); + if let ty::Adt(def, args) = self_ty.kind() { + return self.print_def_path(def.did(), args); } } diff --git a/compiler/rustc_lint/src/deref_into_dyn_supertrait.rs b/compiler/rustc_lint/src/deref_into_dyn_supertrait.rs index ccf95992a6e..851c6493daf 100644 --- a/compiler/rustc_lint/src/deref_into_dyn_supertrait.rs +++ b/compiler/rustc_lint/src/deref_into_dyn_supertrait.rs @@ -59,7 +59,7 @@ impl<'tcx> LateLintPass<'tcx> for DerefIntoDynSupertrait { // `Deref` is being implemented for `t` if let hir::ItemKind::Impl(impl_) = item.kind && let Some(trait_) = &impl_.of_trait - && let t = cx.tcx.type_of(item.owner_id).subst_identity() + && let t = cx.tcx.type_of(item.owner_id).instantiate_identity() && let opt_did @ Some(did) = trait_.trait_def_id() && opt_did == cx.tcx.lang_items().deref_trait() // `t` is `dyn t_principal` diff --git a/compiler/rustc_lint/src/enum_intrinsics_non_enums.rs b/compiler/rustc_lint/src/enum_intrinsics_non_enums.rs index 2ce28f3a049..05fe64830d1 100644 --- a/compiler/rustc_lint/src/enum_intrinsics_non_enums.rs +++ b/compiler/rustc_lint/src/enum_intrinsics_non_enums.rs @@ -51,7 +51,7 @@ fn enforce_mem_discriminant( expr_span: Span, args_span: Span, ) { - let ty_param = cx.typeck_results().node_substs(func_expr.hir_id).type_at(0); + let ty_param = cx.typeck_results().node_args(func_expr.hir_id).type_at(0); if is_non_enum(ty_param) { cx.emit_spanned_lint( ENUM_INTRINSICS_NON_ENUMS, @@ -62,7 +62,7 @@ fn enforce_mem_discriminant( } fn enforce_mem_variant_count(cx: &LateContext<'_>, func_expr: &hir::Expr<'_>, span: Span) { - let ty_param = cx.typeck_results().node_substs(func_expr.hir_id).type_at(0); + let ty_param = cx.typeck_results().node_args(func_expr.hir_id).type_at(0); if is_non_enum(ty_param) { cx.emit_spanned_lint( ENUM_INTRINSICS_NON_ENUMS, diff --git a/compiler/rustc_lint/src/for_loops_over_fallibles.rs b/compiler/rustc_lint/src/for_loops_over_fallibles.rs index 7b58bf03bbe..c299e38842a 100644 --- a/compiler/rustc_lint/src/for_loops_over_fallibles.rs +++ b/compiler/rustc_lint/src/for_loops_over_fallibles.rs @@ -51,7 +51,7 @@ impl<'tcx> LateLintPass<'tcx> for ForLoopsOverFallibles { let ty = cx.typeck_results().expr_ty(arg); - let &ty::Adt(adt, substs) = ty.kind() else { return }; + let &ty::Adt(adt, args) = ty.kind() else { return }; let (article, ty, var) = match adt.did() { did if cx.tcx.is_diagnostic_item(sym::Option, did) => ("an", "Option", "Some"), @@ -66,7 +66,7 @@ impl<'tcx> LateLintPass<'tcx> for ForLoopsOverFallibles { } else { ForLoopsOverFalliblesLoopSub::UseWhileLet { start_span: expr.span.with_hi(pat.span.lo()), end_span: pat.span.between(arg.span), var } } ; - let question_mark = suggest_question_mark(cx, adt, substs, expr.span) + let question_mark = suggest_question_mark(cx, adt, args, expr.span) .then(|| ForLoopsOverFalliblesQuestionMark { suggestion: arg.span.shrink_to_hi() }); let suggestion = ForLoopsOverFalliblesSuggestion { var, @@ -115,11 +115,13 @@ fn extract_iterator_next_call<'tcx>( fn suggest_question_mark<'tcx>( cx: &LateContext<'tcx>, adt: ty::AdtDef<'tcx>, - substs: &List<ty::GenericArg<'tcx>>, + args: &List<ty::GenericArg<'tcx>>, span: Span, ) -> bool { let Some(body_id) = cx.enclosing_body else { return false }; - let Some(into_iterator_did) = cx.tcx.get_diagnostic_item(sym::IntoIterator) else { return false }; + let Some(into_iterator_did) = cx.tcx.get_diagnostic_item(sym::IntoIterator) else { + return false; + }; if !cx.tcx.is_diagnostic_item(sym::Result, adt.did()) { return false; @@ -135,7 +137,7 @@ fn suggest_question_mark<'tcx>( } } - let ty = substs.type_at(0); + let ty = args.type_at(0); let infcx = cx.tcx.infer_ctxt().build(); let ocx = ObligationCtxt::new(&infcx); diff --git a/compiler/rustc_lint/src/internal.rs b/compiler/rustc_lint/src/internal.rs index 6f773e04a97..4b803621f71 100644 --- a/compiler/rustc_lint/src/internal.rs +++ b/compiler/rustc_lint/src/internal.rs @@ -52,20 +52,20 @@ impl LateLintPass<'_> for DefaultHashTypes { } /// Helper function for lints that check for expressions with calls and use typeck results to -/// get the `DefId` and `SubstsRef` of the function. +/// get the `DefId` and `GenericArgsRef` of the function. fn typeck_results_of_method_fn<'tcx>( cx: &LateContext<'tcx>, expr: &Expr<'_>, -) -> Option<(Span, DefId, ty::subst::SubstsRef<'tcx>)> { +) -> Option<(Span, DefId, ty::GenericArgsRef<'tcx>)> { match expr.kind { ExprKind::MethodCall(segment, ..) if let Some(def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) => { - Some((segment.ident.span, def_id, cx.typeck_results().node_substs(expr.hir_id))) + Some((segment.ident.span, def_id, cx.typeck_results().node_args(expr.hir_id))) }, _ => { match cx.typeck_results().node_type(expr.hir_id).kind() { - &ty::FnDef(def_id, substs) => Some((expr.span, def_id, substs)), + &ty::FnDef(def_id, args) => Some((expr.span, def_id, args)), _ => None, } } @@ -89,8 +89,8 @@ declare_lint_pass!(QueryStability => [POTENTIAL_QUERY_INSTABILITY]); impl LateLintPass<'_> for QueryStability { fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) { - let Some((span, def_id, substs)) = typeck_results_of_method_fn(cx, expr) else { return }; - if let Ok(Some(instance)) = ty::Instance::resolve(cx.tcx, cx.param_env, def_id, substs) { + let Some((span, def_id, args)) = typeck_results_of_method_fn(cx, expr) else { return }; + if let Ok(Some(instance)) = ty::Instance::resolve(cx.tcx, cx.param_env, def_id, args) { let def_id = instance.def_id(); if cx.tcx.has_attr(def_id, sym::rustc_lint_query_instability) { cx.emit_spanned_lint( @@ -232,7 +232,7 @@ fn is_ty_or_ty_ctxt(cx: &LateContext<'_>, path: &Path<'_>) -> Option<String> { } // Only lint on `&Ty` and `&TyCtxt` if it is used outside of a trait. Res::SelfTyAlias { alias_to: did, is_trait_impl: false, .. } => { - if let ty::Adt(adt, substs) = cx.tcx.type_of(did).subst_identity().kind() { + if let ty::Adt(adt, args) = cx.tcx.type_of(did).instantiate_identity().kind() { if let Some(name @ (sym::Ty | sym::TyCtxt)) = cx.tcx.get_diagnostic_name(adt.did()) { // NOTE: This path is currently unreachable as `Ty<'tcx>` is @@ -241,7 +241,7 @@ fn is_ty_or_ty_ctxt(cx: &LateContext<'_>, path: &Path<'_>) -> Option<String> { // // I(@lcnr) still kept this branch in so we don't miss this // if we ever change it in the future. - return Some(format!("{}<{}>", name, substs[0])); + return Some(format!("{}<{}>", name, args[0])); } } } @@ -379,9 +379,9 @@ declare_lint_pass!(Diagnostics => [ UNTRANSLATABLE_DIAGNOSTIC, DIAGNOSTIC_OUTSID impl LateLintPass<'_> for Diagnostics { fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) { - let Some((span, def_id, substs)) = typeck_results_of_method_fn(cx, expr) else { return }; - debug!(?span, ?def_id, ?substs); - let has_attr = ty::Instance::resolve(cx.tcx, cx.param_env, def_id, substs) + let Some((span, def_id, args)) = typeck_results_of_method_fn(cx, expr) else { return }; + debug!(?span, ?def_id, ?args); + let has_attr = ty::Instance::resolve(cx.tcx, cx.param_env, def_id, args) .ok() .flatten() .is_some_and(|inst| cx.tcx.has_attr(inst.def_id(), sym::rustc_lint_diagnostics)); @@ -414,7 +414,7 @@ impl LateLintPass<'_> for Diagnostics { } let mut found_diagnostic_message = false; - for ty in substs.types() { + for ty in args.types() { debug!(?ty); if let Some(adt_def) = ty.ty_adt_def() && let Some(name) = cx.tcx.get_diagnostic_name(adt_def.did()) && diff --git a/compiler/rustc_lint/src/levels.rs b/compiler/rustc_lint/src/levels.rs index 8376835f52c..c9ee2da6fdf 100644 --- a/compiler/rustc_lint/src/levels.rs +++ b/compiler/rustc_lint/src/levels.rs @@ -265,7 +265,10 @@ impl LintLevelsProvider for QueryMapExpectationsWrapper<'_> { self.specs.lint_level_id_at_node(self.tcx, LintId::of(lint), self.cur) } fn push_expectation(&mut self, id: LintExpectationId, expectation: LintExpectation) { - let LintExpectationId::Stable { attr_id: Some(attr_id), hir_id, attr_index, .. } = id else { bug!("unstable expectation id should already be mapped") }; + let LintExpectationId::Stable { attr_id: Some(attr_id), hir_id, attr_index, .. } = id + else { + bug!("unstable expectation id should already be mapped") + }; let key = LintExpectationId::Unstable { attr_id, lint_index: None }; self.unstable_to_stable_ids.entry(key).or_insert(LintExpectationId::Stable { @@ -542,7 +545,7 @@ impl<'s, P: LintLevelsProvider> LintLevelsBuilder<'s, P> { let Ok(ids) = self.store.find_lints(&lint_name) else { // errors handled in check_lint_name_cmdline above - continue + continue; }; for id in ids { // ForceWarn and Forbid cannot be overridden @@ -685,9 +688,7 @@ impl<'s, P: LintLevelsProvider> LintLevelsBuilder<'s, P> { Some(lvl) => lvl, }; - let Some(mut metas) = attr.meta_item_list() else { - continue - }; + let Some(mut metas) = attr.meta_item_list() else { continue }; if metas.is_empty() { // This emits the unused_attributes lint for `#[level()]` @@ -956,8 +957,9 @@ impl<'s, P: LintLevelsProvider> LintLevelsBuilder<'s, P> { continue; } - let LintLevelSource::Node { name: lint_attr_name, span: lint_attr_span, .. } = *src else { - continue + let LintLevelSource::Node { name: lint_attr_name, span: lint_attr_span, .. } = *src + else { + continue; }; self.emit_spanned_lint( diff --git a/compiler/rustc_lint/src/methods.rs b/compiler/rustc_lint/src/methods.rs index 4c25d94a1f3..5b63b19c53c 100644 --- a/compiler/rustc_lint/src/methods.rs +++ b/compiler/rustc_lint/src/methods.rs @@ -53,9 +53,9 @@ fn lint_cstring_as_ptr( unwrap: &rustc_hir::Expr<'_>, ) { let source_type = cx.typeck_results().expr_ty(source); - if let ty::Adt(def, substs) = source_type.kind() { + if let ty::Adt(def, args) = source_type.kind() { if cx.tcx.is_diagnostic_item(sym::Result, def.did()) { - if let ty::Adt(adt, _) = substs.type_at(0).kind() { + if let ty::Adt(adt, _) = args.type_at(0).kind() { if cx.tcx.is_diagnostic_item(sym::cstring_type, adt.did()) { cx.emit_spanned_lint( TEMPORARY_CSTRING_AS_PTR, diff --git a/compiler/rustc_lint/src/noop_method_call.rs b/compiler/rustc_lint/src/noop_method_call.rs index d56c35bb677..13f650c2008 100644 --- a/compiler/rustc_lint/src/noop_method_call.rs +++ b/compiler/rustc_lint/src/noop_method_call.rs @@ -79,8 +79,7 @@ impl<'tcx> LateLintPass<'tcx> for NoopMethodCall { // We only care about method calls corresponding to the `Clone`, `Deref` and `Borrow` // traits and ignore any other method call. - let Some((DefKind::AssocFn, did)) = - cx.typeck_results().type_dependent_def(expr.hir_id) + let Some((DefKind::AssocFn, did)) = cx.typeck_results().type_dependent_def(expr.hir_id) else { return; }; @@ -94,13 +93,11 @@ impl<'tcx> LateLintPass<'tcx> for NoopMethodCall { return; }; - let substs = cx + let args = cx .tcx - .normalize_erasing_regions(cx.param_env, cx.typeck_results().node_substs(expr.hir_id)); + .normalize_erasing_regions(cx.param_env, cx.typeck_results().node_args(expr.hir_id)); // Resolve the trait method instance. - let Ok(Some(i)) = ty::Instance::resolve(cx.tcx, cx.param_env, did, substs) else { - return - }; + let Ok(Some(i)) = ty::Instance::resolve(cx.tcx, cx.param_env, did, args) else { return }; // (Re)check that it implements the noop diagnostic. let Some(name) = cx.tcx.get_diagnostic_name(i.def_id()) else { return }; diff --git a/compiler/rustc_lint/src/opaque_hidden_inferred_bound.rs b/compiler/rustc_lint/src/opaque_hidden_inferred_bound.rs index 09a1651c2f5..d5f0290767a 100644 --- a/compiler/rustc_lint/src/opaque_hidden_inferred_bound.rs +++ b/compiler/rustc_lint/src/opaque_hidden_inferred_bound.rs @@ -68,13 +68,17 @@ declare_lint_pass!(OpaqueHiddenInferredBound => [OPAQUE_HIDDEN_INFERRED_BOUND]); impl<'tcx> LateLintPass<'tcx> for OpaqueHiddenInferredBound { fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'tcx>) { - let hir::ItemKind::OpaqueTy(opaque) = &item.kind else { return; }; + let hir::ItemKind::OpaqueTy(opaque) = &item.kind else { + return; + }; let def_id = item.owner_id.def_id.to_def_id(); let infcx = &cx.tcx.infer_ctxt().build(); // For every projection predicate in the opaque type's explicit bounds, // check that the type that we're assigning actually satisfies the bounds // of the associated type. - for (pred, pred_span) in cx.tcx.explicit_item_bounds(def_id).subst_identity_iter_copied() { + for (pred, pred_span) in + cx.tcx.explicit_item_bounds(def_id).instantiate_identity_iter_copied() + { // Liberate bound regions in the predicate since we // don't actually care about lifetimes in this check. let predicate = cx.tcx.liberate_late_bound_regions(def_id, pred.kind()); @@ -97,7 +101,7 @@ impl<'tcx> LateLintPass<'tcx> for OpaqueHiddenInferredBound { } let proj_ty = - Ty::new_projection(cx.tcx, proj.projection_ty.def_id, proj.projection_ty.substs); + Ty::new_projection(cx.tcx, proj.projection_ty.def_id, proj.projection_ty.args); // For every instance of the projection type in the bounds, // replace them with the term we're assigning to the associated // type in our opaque type. @@ -113,10 +117,15 @@ impl<'tcx> LateLintPass<'tcx> for OpaqueHiddenInferredBound { for (assoc_pred, assoc_pred_span) in cx .tcx .explicit_item_bounds(proj.projection_ty.def_id) - .subst_iter_copied(cx.tcx, &proj.projection_ty.substs) + .arg_iter_copied(cx.tcx, &proj.projection_ty.args) { let assoc_pred = assoc_pred.fold_with(proj_replacer); - let Ok(assoc_pred) = traits::fully_normalize(infcx, traits::ObligationCause::dummy(), cx.param_env, assoc_pred) else { + let Ok(assoc_pred) = traits::fully_normalize( + infcx, + traits::ObligationCause::dummy(), + cx.param_env, + assoc_pred, + ) else { continue; }; // If that predicate doesn't hold modulo regions (but passed during type-check), @@ -147,7 +156,7 @@ impl<'tcx> LateLintPass<'tcx> for OpaqueHiddenInferredBound { ty: Ty::new_opaque( cx.tcx, def_id, - ty::InternalSubsts::identity_for_item(cx.tcx, def_id), + ty::GenericArgs::identity_for_item(cx.tcx, def_id), ), proj_ty: proj_term, assoc_pred_span, diff --git a/compiler/rustc_lint/src/pass_by_value.rs b/compiler/rustc_lint/src/pass_by_value.rs index 2bb2a3aab55..cad2cd7fa4c 100644 --- a/compiler/rustc_lint/src/pass_by_value.rs +++ b/compiler/rustc_lint/src/pass_by_value.rs @@ -50,9 +50,9 @@ fn path_for_pass_by_value(cx: &LateContext<'_>, ty: &hir::Ty<'_>) -> Option<Stri return Some(format!("{}{}", name, gen_args(cx, path_segment))); } Res::SelfTyAlias { alias_to: did, is_trait_impl: false, .. } => { - if let ty::Adt(adt, substs) = cx.tcx.type_of(did).subst_identity().kind() { + if let ty::Adt(adt, args) = cx.tcx.type_of(did).instantiate_identity().kind() { if cx.tcx.has_attr(adt.did(), sym::rustc_pass_by_value) { - return Some(cx.tcx.def_path_str_with_substs(adt.did(), substs)); + return Some(cx.tcx.def_path_str_with_args(adt.did(), args)); } } } diff --git a/compiler/rustc_lint/src/traits.rs b/compiler/rustc_lint/src/traits.rs index de11208062d..56508a2a6cc 100644 --- a/compiler/rustc_lint/src/traits.rs +++ b/compiler/rustc_lint/src/traits.rs @@ -92,7 +92,7 @@ impl<'tcx> LateLintPass<'tcx> for DropTraitConstraints { let predicates = cx.tcx.explicit_predicates_of(item.owner_id); for &(predicate, span) in predicates.predicates { let ClauseKind::Trait(trait_predicate) = predicate.kind().skip_binder() else { - continue + continue; }; let def_id = trait_predicate.trait_ref.def_id; if cx.tcx.lang_items().drop_trait() == Some(def_id) { @@ -100,9 +100,7 @@ impl<'tcx> LateLintPass<'tcx> for DropTraitConstraints { if trait_predicate.trait_ref.self_ty().is_impl_trait() { continue; } - let Some(def_id) = cx.tcx.get_diagnostic_item(sym::needs_drop) else { - return - }; + let Some(def_id) = cx.tcx.get_diagnostic_item(sym::needs_drop) else { return }; cx.emit_spanned_lint( DROP_BOUNDS, span, @@ -113,15 +111,11 @@ impl<'tcx> LateLintPass<'tcx> for DropTraitConstraints { } fn check_ty(&mut self, cx: &LateContext<'_>, ty: &'tcx hir::Ty<'tcx>) { - let hir::TyKind::TraitObject(bounds, _lifetime, _syntax) = &ty.kind else { - return - }; + let hir::TyKind::TraitObject(bounds, _lifetime, _syntax) = &ty.kind else { return }; for bound in &bounds[..] { let def_id = bound.trait_ref.trait_def_id(); if cx.tcx.lang_items().drop_trait() == def_id { - let Some(def_id) = cx.tcx.get_diagnostic_item(sym::needs_drop) else { - return - }; + let Some(def_id) = cx.tcx.get_diagnostic_item(sym::needs_drop) else { return }; cx.emit_spanned_lint(DYN_DROP, bound.span, DropGlue { tcx: cx.tcx, def_id }); } } diff --git a/compiler/rustc_lint/src/types.rs b/compiler/rustc_lint/src/types.rs index 2509d493a4c..cc8a3408004 100644 --- a/compiler/rustc_lint/src/types.rs +++ b/compiler/rustc_lint/src/types.rs @@ -17,7 +17,7 @@ use rustc_errors::DiagnosticMessage; use rustc_hir as hir; use rustc_hir::{is_range_literal, Expr, ExprKind, Node}; use rustc_middle::ty::layout::{IntegerExt, LayoutOf, SizeSkeleton}; -use rustc_middle::ty::subst::SubstsRef; +use rustc_middle::ty::GenericArgsRef; use rustc_middle::ty::{ self, AdtKind, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, }; @@ -560,7 +560,10 @@ fn lint_nan<'tcx>( let expr = expr.peel_blocks().peel_borrows(); match expr.kind { ExprKind::Path(qpath) => { - let Some(def_id) = cx.typeck_results().qpath_res(&qpath, expr.hir_id).opt_def_id() else { return false; }; + let Some(def_id) = cx.typeck_results().qpath_res(&qpath, expr.hir_id).opt_def_id() + else { + return false; + }; matches!(cx.tcx.get_diagnostic_name(def_id), Some(sym::f32_nan | sym::f64_nan)) } @@ -805,7 +808,7 @@ pub fn transparent_newtype_field<'a, 'tcx>( ) -> Option<&'a ty::FieldDef> { let param_env = tcx.param_env(variant.def_id); variant.fields.iter().find(|field| { - let field_ty = tcx.type_of(field.did).subst_identity(); + let field_ty = tcx.type_of(field.did).instantiate_identity(); let is_zst = tcx.layout_of(param_env.and(field_ty)).is_ok_and(|layout| layout.is_zst()); !is_zst }) @@ -818,7 +821,7 @@ fn ty_is_known_nonnull<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, mode: CItemKi ty::FnPtr(_) => true, ty::Ref(..) => true, ty::Adt(def, _) if def.is_box() && matches!(mode, CItemKind::Definition) => true, - ty::Adt(def, substs) if def.repr().transparent() && !def.is_union() => { + ty::Adt(def, args) if def.repr().transparent() && !def.is_union() => { let marked_non_null = nonnull_optimization_guaranteed(tcx, *def); if marked_non_null { @@ -833,7 +836,7 @@ fn ty_is_known_nonnull<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, mode: CItemKi def.variants() .iter() .filter_map(|variant| transparent_newtype_field(cx.tcx, variant)) - .any(|field| ty_is_known_nonnull(cx, field.ty(tcx, substs), mode)) + .any(|field| ty_is_known_nonnull(cx, field.ty(tcx, args), mode)) } _ => false, } @@ -844,7 +847,7 @@ fn ty_is_known_nonnull<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, mode: CItemKi fn get_nullable_type<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option<Ty<'tcx>> { let tcx = cx.tcx; Some(match *ty.kind() { - ty::Adt(field_def, field_substs) => { + ty::Adt(field_def, field_args) => { let inner_field_ty = { let mut first_non_zst_ty = field_def .variants() @@ -858,7 +861,7 @@ fn get_nullable_type<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option<Ty<'t first_non_zst_ty .next_back() .expect("No non-zst fields in transparent type.") - .ty(tcx, field_substs) + .ty(tcx, field_args) }; return get_nullable_type(cx, inner_field_ty); } @@ -897,10 +900,10 @@ pub(crate) fn repr_nullable_ptr<'tcx>( ckind: CItemKind, ) -> Option<Ty<'tcx>> { debug!("is_repr_nullable_ptr(cx, ty = {:?})", ty); - if let ty::Adt(ty_def, substs) = ty.kind() { + if let ty::Adt(ty_def, args) = ty.kind() { let field_ty = match &ty_def.variants().raw[..] { [var_one, var_two] => match (&var_one.fields.raw[..], &var_two.fields.raw[..]) { - ([], [field]) | ([field], []) => field.ty(cx.tcx, substs), + ([], [field]) | ([field], []) => field.ty(cx.tcx, args), _ => return None, }, _ => return None, @@ -960,9 +963,9 @@ impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> { &self, cache: &mut FxHashSet<Ty<'tcx>>, field: &ty::FieldDef, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, ) -> FfiResult<'tcx> { - let field_ty = field.ty(self.cx.tcx, substs); + let field_ty = field.ty(self.cx.tcx, args); if field_ty.has_opaque_types() { self.check_type_for_ffi(cache, field_ty) } else { @@ -978,7 +981,7 @@ impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> { ty: Ty<'tcx>, def: ty::AdtDef<'tcx>, variant: &ty::VariantDef, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, ) -> FfiResult<'tcx> { use FfiResult::*; @@ -986,7 +989,7 @@ impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> { // Can assume that at most one field is not a ZST, so only check // that field's type for FFI-safety. if let Some(field) = transparent_newtype_field(self.cx.tcx, variant) { - return self.check_field_type_for_ffi(cache, field, substs); + return self.check_field_type_for_ffi(cache, field, args); } else { // All fields are ZSTs; this means that the type should behave // like (), which is FFI-unsafe... except if all fields are PhantomData, @@ -998,7 +1001,7 @@ impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> { // actually safe. let mut all_phantom = !variant.fields.is_empty(); for field in &variant.fields { - match self.check_field_type_for_ffi(cache, &field, substs) { + match self.check_field_type_for_ffi(cache, &field, args) { FfiSafe => { all_phantom = false; } @@ -1033,7 +1036,7 @@ impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> { } match *ty.kind() { - ty::Adt(def, substs) => { + ty::Adt(def, args) => { if def.is_box() && matches!(self.mode, CItemKind::Definition) { if ty.boxed_ty().is_sized(tcx, self.cx.param_env) { return FfiSafe; @@ -1096,7 +1099,7 @@ impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> { }; } - self.check_variant_for_ffi(cache, ty, def, def.non_enum_variant(), substs) + self.check_variant_for_ffi(cache, ty, def, def.non_enum_variant(), args) } AdtKind::Enum => { if def.variants().is_empty() { @@ -1137,7 +1140,7 @@ impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> { }; } - match self.check_variant_for_ffi(cache, ty, def, variant, substs) { + match self.check_variant_for_ffi(cache, ty, def, variant, args) { FfiSafe => (), r => return r, } @@ -1384,7 +1387,7 @@ impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> { /// For a external ABI function, argument types and the result type are walked to find fn-ptr /// types that have external ABIs, as these still need checked. fn check_fn(&mut self, def_id: LocalDefId, decl: &'tcx hir::FnDecl<'_>) { - let sig = self.cx.tcx.fn_sig(def_id).subst_identity(); + let sig = self.cx.tcx.fn_sig(def_id).instantiate_identity(); let sig = self.cx.tcx.erase_late_bound_regions(sig); for (input_ty, input_hir) in iter::zip(sig.inputs(), decl.inputs) { @@ -1402,7 +1405,7 @@ impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> { /// Check if a function's argument types and result type are "ffi-safe". fn check_foreign_fn(&mut self, def_id: LocalDefId, decl: &'tcx hir::FnDecl<'_>) { - let sig = self.cx.tcx.fn_sig(def_id).subst_identity(); + let sig = self.cx.tcx.fn_sig(def_id).instantiate_identity(); let sig = self.cx.tcx.erase_late_bound_regions(sig); for (input_ty, input_hir) in iter::zip(sig.inputs(), decl.inputs) { @@ -1415,7 +1418,7 @@ impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> { } fn check_foreign_static(&mut self, id: hir::OwnerId, span: Span) { - let ty = self.cx.tcx.type_of(id).subst_identity(); + let ty = self.cx.tcx.type_of(id).instantiate_identity(); self.check_type_for_ffi_and_report_errors(span, ty, true, false); } @@ -1521,7 +1524,7 @@ impl<'tcx> LateLintPass<'tcx> for ImproperCTypesDefinitions { self.check_ty_maybe_containing_foreign_fnptr( cx, ty, - cx.tcx.type_of(item.owner_id).subst_identity(), + cx.tcx.type_of(item.owner_id).instantiate_identity(), ); } // See `check_fn`.. @@ -1546,7 +1549,7 @@ impl<'tcx> LateLintPass<'tcx> for ImproperCTypesDefinitions { self.check_ty_maybe_containing_foreign_fnptr( cx, field.ty, - cx.tcx.type_of(field.def_id).subst_identity(), + cx.tcx.type_of(field.def_id).instantiate_identity(), ); } @@ -1581,13 +1584,13 @@ declare_lint_pass!(VariantSizeDifferences => [VARIANT_SIZE_DIFFERENCES]); impl<'tcx> LateLintPass<'tcx> for VariantSizeDifferences { fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) { if let hir::ItemKind::Enum(ref enum_definition, _) = it.kind { - let t = cx.tcx.type_of(it.owner_id).subst_identity(); + let t = cx.tcx.type_of(it.owner_id).instantiate_identity(); let ty = cx.tcx.erase_regions(t); let Ok(layout) = cx.layout_of(ty) else { return }; - let Variants::Multiple { - tag_encoding: TagEncoding::Direct, tag, ref variants, .. - } = &layout.variants else { - return + let Variants::Multiple { tag_encoding: TagEncoding::Direct, tag, ref variants, .. } = + &layout.variants + else { + return; }; let tag_size = tag.size(&cx.tcx).bytes(); @@ -1701,7 +1704,7 @@ impl InvalidAtomicOrdering { && recognized_names.contains(&method_path.ident.name) && let Some(m_def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) && let Some(impl_did) = cx.tcx.impl_of_method(m_def_id) - && let Some(adt) = cx.tcx.type_of(impl_did).subst_identity().ty_adt_def() + && let Some(adt) = cx.tcx.type_of(impl_did).instantiate_identity().ty_adt_def() // skip extension traits, only lint functions from the standard library && cx.tcx.trait_id_of_impl(impl_did).is_none() && let parent = cx.tcx.parent(adt.did()) @@ -1760,8 +1763,13 @@ impl InvalidAtomicOrdering { } fn check_atomic_compare_exchange(cx: &LateContext<'_>, expr: &Expr<'_>) { - let Some((method, args)) = Self::inherent_atomic_method_call(cx, expr, &[sym::fetch_update, sym::compare_exchange, sym::compare_exchange_weak]) - else {return }; + let Some((method, args)) = Self::inherent_atomic_method_call( + cx, + expr, + &[sym::fetch_update, sym::compare_exchange, sym::compare_exchange_weak], + ) else { + return; + }; let fail_order_arg = match method { sym::fetch_update => &args[1], diff --git a/compiler/rustc_lint/src/unused.rs b/compiler/rustc_lint/src/unused.rs index 5015b751eee..f78da284a3a 100644 --- a/compiler/rustc_lint/src/unused.rs +++ b/compiler/rustc_lint/src/unused.rs @@ -94,7 +94,9 @@ declare_lint_pass!(UnusedResults => [UNUSED_MUST_USE, UNUSED_RESULTS]); impl<'tcx> LateLintPass<'tcx> for UnusedResults { fn check_stmt(&mut self, cx: &LateContext<'_>, s: &hir::Stmt<'_>) { - let hir::StmtKind::Semi(mut expr) = s.kind else { return; }; + let hir::StmtKind::Semi(mut expr) = s.kind else { + return; + }; let mut expr_is_from_block = false; while let hir::ExprKind::Block(blk, ..) = expr.kind @@ -284,22 +286,25 @@ impl<'tcx> LateLintPass<'tcx> for UnusedResults { } ty::Adt(def, _) => is_def_must_use(cx, def.did(), span), ty::Alias(ty::Opaque, ty::AliasTy { def_id: def, .. }) => { - elaborate(cx.tcx, cx.tcx.explicit_item_bounds(def).subst_identity_iter_copied()) - // We only care about self bounds for the impl-trait - .filter_only_self() - .find_map(|(pred, _span)| { - // We only look at the `DefId`, so it is safe to skip the binder here. - if let ty::ClauseKind::Trait(ref poly_trait_predicate) = - pred.kind().skip_binder() - { - let def_id = poly_trait_predicate.trait_ref.def_id; - - is_def_must_use(cx, def_id, span) - } else { - None - } - }) - .map(|inner| MustUsePath::Opaque(Box::new(inner))) + elaborate( + cx.tcx, + cx.tcx.explicit_item_bounds(def).instantiate_identity_iter_copied(), + ) + // We only care about self bounds for the impl-trait + .filter_only_self() + .find_map(|(pred, _span)| { + // We only look at the `DefId`, so it is safe to skip the binder here. + if let ty::ClauseKind::Trait(ref poly_trait_predicate) = + pred.kind().skip_binder() + { + let def_id = poly_trait_predicate.trait_ref.def_id; + + is_def_must_use(cx, def_id, span) + } else { + None + } + }) + .map(|inner| MustUsePath::Opaque(Box::new(inner))) } ty::Dynamic(binders, _, _) => binders.iter().find_map(|predicate| { if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate.skip_binder() diff --git a/compiler/rustc_lint_defs/src/builtin.rs b/compiler/rustc_lint_defs/src/builtin.rs index 87c542dc2e2..a0f2e9aed81 100644 --- a/compiler/rustc_lint_defs/src/builtin.rs +++ b/compiler/rustc_lint_defs/src/builtin.rs @@ -4084,7 +4084,7 @@ declare_lint! { /// /// ### Explanation /// - /// The preferred location for where clauses on associated types in impls + /// The preferred location for where clauses on associated types /// is after the type. However, for most of generic associated types development, /// it was only accepted before the equals. To provide a transition period and /// further evaluate this change, both are currently accepted. At some point in diff --git a/compiler/rustc_lint_defs/src/lib.rs b/compiler/rustc_lint_defs/src/lib.rs index 5a5031b7919..f6ffd46b1fe 100644 --- a/compiler/rustc_lint_defs/src/lib.rs +++ b/compiler/rustc_lint_defs/src/lib.rs @@ -550,6 +550,12 @@ pub enum BuiltinLintDiagnostics { /// The local binding that shadows the glob reexport. private_item_span: Span, }, + UnusedQualifications { + /// The span of the unnecessarily-qualified path. + path_span: Span, + /// The replacement unqualified path. + unqualified_path: Ident, + }, } /// Lints that are buffered up early on in the `Session` before the diff --git a/compiler/rustc_llvm/llvm-wrapper/CoverageMappingWrapper.cpp b/compiler/rustc_llvm/llvm-wrapper/CoverageMappingWrapper.cpp index 87906dee4d3..80b6c0fb439 100644 --- a/compiler/rustc_llvm/llvm-wrapper/CoverageMappingWrapper.cpp +++ b/compiler/rustc_llvm/llvm-wrapper/CoverageMappingWrapper.cpp @@ -158,14 +158,9 @@ extern "C" LLVMValueRef LLVMRustCoverageCreatePGOFuncNameVar(LLVMValueRef F, con return wrap(createPGOFuncNameVar(*cast<Function>(unwrap(F)), FuncNameRef)); } -extern "C" uint64_t LLVMRustCoverageHashCString(const char *StrVal) { - StringRef StrRef(StrVal); - return IndexedInstrProf::ComputeHash(StrRef); -} - extern "C" uint64_t LLVMRustCoverageHashByteArray( const char *Bytes, - unsigned NumBytes) { + size_t NumBytes) { StringRef StrRef(Bytes, NumBytes); return IndexedInstrProf::ComputeHash(StrRef); } diff --git a/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp b/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp index c43a0272477..eb3d67e720f 100644 --- a/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp +++ b/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp @@ -667,6 +667,7 @@ LLVMRustOptimize( assert(!PGOUsePath && !PGOSampleUsePath); PGOOpt = PGOOptions(PGOGenPath, "", "", #if LLVM_VERSION_GE(17, 0) + "", FS, #endif PGOOptions::IRInstr, PGOOptions::NoCSAction, @@ -675,6 +676,7 @@ LLVMRustOptimize( assert(!PGOSampleUsePath); PGOOpt = PGOOptions(PGOUsePath, "", "", #if LLVM_VERSION_GE(17, 0) + "", FS, #endif PGOOptions::IRUse, PGOOptions::NoCSAction, @@ -682,6 +684,7 @@ LLVMRustOptimize( } else if (PGOSampleUsePath) { PGOOpt = PGOOptions(PGOSampleUsePath, "", "", #if LLVM_VERSION_GE(17, 0) + "", FS, #endif PGOOptions::SampleUse, PGOOptions::NoCSAction, @@ -689,6 +692,7 @@ LLVMRustOptimize( } else if (DebugInfoForProfiling) { PGOOpt = PGOOptions("", "", "", #if LLVM_VERSION_GE(17, 0) + "", FS, #endif PGOOptions::NoAction, PGOOptions::NoCSAction, diff --git a/compiler/rustc_llvm/llvm-wrapper/SymbolWrapper.cpp b/compiler/rustc_llvm/llvm-wrapper/SymbolWrapper.cpp index 0493d6b05d0..bf00d11edf6 100644 --- a/compiler/rustc_llvm/llvm-wrapper/SymbolWrapper.cpp +++ b/compiler/rustc_llvm/llvm-wrapper/SymbolWrapper.cpp @@ -7,6 +7,7 @@ // * https://github.com/llvm/llvm-project/blob/8ef3e895ad8ab1724e2b87cabad1dacdc7a397a3/llvm/include/llvm/Object/ArchiveWriter.h // * https://github.com/llvm/llvm-project/blob/8ef3e895ad8ab1724e2b87cabad1dacdc7a397a3/llvm/lib/Object/ArchiveWriter.cpp +#include "llvm/ADT/SmallString.h" #include "llvm/IR/LLVMContext.h" #include "llvm/Object/ObjectFile.h" diff --git a/compiler/rustc_macros/src/diagnostics/diagnostic_builder.rs b/compiler/rustc_macros/src/diagnostics/diagnostic_builder.rs index 2e6e84ad80e..e9a5cd9de97 100644 --- a/compiler/rustc_macros/src/diagnostics/diagnostic_builder.rs +++ b/compiler/rustc_macros/src/diagnostics/diagnostic_builder.rs @@ -203,14 +203,18 @@ impl<'a> DiagnosticDeriveVariantBuilder<'a> { if first && (nested.input.is_empty() || nested.input.peek(Token![,])) { self.slug.set_once(path.clone(), path.span().unwrap()); first = false; - return Ok(()) + return Ok(()); } first = false; let Ok(nested) = nested.value() else { - span_err(nested.input.span().unwrap(), "diagnostic slug must be the first argument").emit(); - return Ok(()) + span_err( + nested.input.span().unwrap(), + "diagnostic slug must be the first argument", + ) + .emit(); + return Ok(()); }; if path.is_ident("code") { @@ -221,7 +225,9 @@ impl<'a> DiagnosticDeriveVariantBuilder<'a> { #diag.code(rustc_errors::DiagnosticId::Error(#code.to_string())); }); } else { - span_err(path.span().unwrap(), "unknown argument").note("only the `code` parameter is valid after the slug").emit(); + span_err(path.span().unwrap(), "unknown argument") + .note("only the `code` parameter is valid after the slug") + .emit(); // consume the buffer so we don't have syntax errors from syn let _ = nested.parse::<TokenStream>(); diff --git a/compiler/rustc_macros/src/diagnostics/subdiagnostic.rs b/compiler/rustc_macros/src/diagnostics/subdiagnostic.rs index e8dc986914e..877e9745054 100644 --- a/compiler/rustc_macros/src/diagnostics/subdiagnostic.rs +++ b/compiler/rustc_macros/src/diagnostics/subdiagnostic.rs @@ -188,7 +188,9 @@ impl<'parent, 'a> SubdiagnosticDeriveVariantBuilder<'parent, 'a> { let mut kind_slugs = vec![]; for attr in self.variant.ast().attrs { - let Some(SubdiagnosticVariant { kind, slug, no_span }) = SubdiagnosticVariant::from_attr(attr, self)? else { + let Some(SubdiagnosticVariant { kind, slug, no_span }) = + SubdiagnosticVariant::from_attr(attr, self)? + else { // Some attributes aren't errors - like documentation comments - but also aren't // subdiagnostics. continue; diff --git a/compiler/rustc_macros/src/newtype.rs b/compiler/rustc_macros/src/newtype.rs index 415a89b0f92..72b47de1abc 100644 --- a/compiler/rustc_macros/src/newtype.rs +++ b/compiler/rustc_macros/src/newtype.rs @@ -36,7 +36,8 @@ impl Parse for Newtype { false } "max" => { - let Meta::NameValue(MetaNameValue { value: Expr::Lit(lit), .. }) = &attr.meta else { + let Meta::NameValue(MetaNameValue { value: Expr::Lit(lit), .. }) = &attr.meta + else { panic!("#[max = NUMBER] attribute requires max value"); }; @@ -47,7 +48,8 @@ impl Parse for Newtype { false } "debug_format" => { - let Meta::NameValue(MetaNameValue { value: Expr::Lit(lit), .. }) = &attr.meta else { + let Meta::NameValue(MetaNameValue { value: Expr::Lit(lit), .. }) = &attr.meta + else { panic!("#[debug_format = FMT] attribute requires a format"); }; diff --git a/compiler/rustc_metadata/src/creader.rs b/compiler/rustc_metadata/src/creader.rs index b3976d756eb..571af82d13a 100644 --- a/compiler/rustc_metadata/src/creader.rs +++ b/compiler/rustc_metadata/src/creader.rs @@ -741,7 +741,9 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { }; info!("panic runtime not found -- loading {}", name); - let Some(cnum) = self.resolve_crate(name, DUMMY_SP, CrateDepKind::Implicit) else { return; }; + let Some(cnum) = self.resolve_crate(name, DUMMY_SP, CrateDepKind::Implicit) else { + return; + }; let data = self.cstore.get_crate_data(cnum); // Sanity check the loaded crate to ensure it is indeed a panic runtime @@ -774,7 +776,9 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { self.sess.emit_err(errors::ProfilerBuiltinsNeedsCore); } - let Some(cnum) = self.resolve_crate(name, DUMMY_SP, CrateDepKind::Implicit) else { return; }; + let Some(cnum) = self.resolve_crate(name, DUMMY_SP, CrateDepKind::Implicit) else { + return; + }; let data = self.cstore.get_crate_data(cnum); // Sanity check the loaded crate to ensure it is indeed a profiler runtime diff --git a/compiler/rustc_metadata/src/locator.rs b/compiler/rustc_metadata/src/locator.rs index a89d7b464e2..a1511c4b570 100644 --- a/compiler/rustc_metadata/src/locator.rs +++ b/compiler/rustc_metadata/src/locator.rs @@ -804,8 +804,12 @@ fn get_metadata_section<'p>( } // Length of the compressed stream - this allows linkers to pad the section if they want - let Ok(len_bytes) = <[u8; 4]>::try_from(&buf[header_len..cmp::min(data_start, buf.len())]) else { - return Err(MetadataError::LoadFailure("invalid metadata length found".to_string())); + let Ok(len_bytes) = + <[u8; 4]>::try_from(&buf[header_len..cmp::min(data_start, buf.len())]) + else { + return Err(MetadataError::LoadFailure( + "invalid metadata length found".to_string(), + )); }; let compressed_len = u32::from_be_bytes(len_bytes) as usize; diff --git a/compiler/rustc_metadata/src/native_libs.rs b/compiler/rustc_metadata/src/native_libs.rs index 0dd7b119791..9e0bf81d58d 100644 --- a/compiler/rustc_metadata/src/native_libs.rs +++ b/compiler/rustc_metadata/src/native_libs.rs @@ -480,7 +480,7 @@ impl<'tcx> Collector<'tcx> { let argument_types: &List<Ty<'_>> = self.tcx.erase_late_bound_regions( self.tcx .type_of(item.id.owner_id) - .subst_identity() + .instantiate_identity() .fn_sig(self.tcx) .inputs() .map_bound(|slice| self.tcx.mk_type_list(slice)), diff --git a/compiler/rustc_metadata/src/rmeta/decoder.rs b/compiler/rustc_metadata/src/rmeta/decoder.rs index b9318aee581..8fa1d365728 100644 --- a/compiler/rustc_metadata/src/rmeta/decoder.rs +++ b/compiler/rustc_metadata/src/rmeta/decoder.rs @@ -311,8 +311,10 @@ impl<'a, 'tcx> DecodeContext<'a, 'tcx> { #[inline] fn tcx(&self) -> TyCtxt<'tcx> { let Some(tcx) = self.tcx else { - bug!("No TyCtxt found for decoding. \ - You need to explicitly pass `(crate_metadata_ref, tcx)` to `decode` instead of just `crate_metadata_ref`."); + bug!( + "No TyCtxt found for decoding. \ + You need to explicitly pass `(crate_metadata_ref, tcx)` to `decode` instead of just `crate_metadata_ref`." + ); }; tcx } @@ -448,8 +450,10 @@ impl<'a, 'tcx> Decodable<DecodeContext<'a, 'tcx>> for SyntaxContext { let cdata = decoder.cdata(); let Some(sess) = decoder.sess else { - bug!("Cannot decode SyntaxContext without Session.\ - You need to explicitly pass `(crate_metadata_ref, tcx)` to `decode` instead of just `crate_metadata_ref`."); + bug!( + "Cannot decode SyntaxContext without Session.\ + You need to explicitly pass `(crate_metadata_ref, tcx)` to `decode` instead of just `crate_metadata_ref`." + ); }; let cname = cdata.root.name(); @@ -470,8 +474,10 @@ impl<'a, 'tcx> Decodable<DecodeContext<'a, 'tcx>> for ExpnId { let local_cdata = decoder.cdata(); let Some(sess) = decoder.sess else { - bug!("Cannot decode ExpnId without Session. \ - You need to explicitly pass `(crate_metadata_ref, tcx)` to `decode` instead of just `crate_metadata_ref`."); + bug!( + "Cannot decode ExpnId without Session. \ + You need to explicitly pass `(crate_metadata_ref, tcx)` to `decode` instead of just `crate_metadata_ref`." + ); }; let cnum = CrateNum::decode(decoder); @@ -521,8 +527,10 @@ impl<'a, 'tcx> Decodable<DecodeContext<'a, 'tcx>> for Span { let hi = lo + len; let Some(sess) = decoder.sess else { - bug!("Cannot decode Span without Session. \ - You need to explicitly pass `(crate_metadata_ref, tcx)` to `decode` instead of just `crate_metadata_ref`.") + bug!( + "Cannot decode Span without Session. \ + You need to explicitly pass `(crate_metadata_ref, tcx)` to `decode` instead of just `crate_metadata_ref`." + ) }; // Index of the file in the corresponding crate's list of encoded files. diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index 01dd35b0e5b..2785732727f 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -608,7 +608,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { trace!("encoding {} further alloc ids", new_n - n); for idx in n..new_n { let id = self.interpret_allocs[idx]; - let pos = self.position() as u32; + let pos = self.position() as u64; interpret_alloc_index.push(pos); interpret::specialized_encode_alloc_id(self, tcx, id); } @@ -1136,7 +1136,7 @@ fn should_encode_type(tcx: TyCtxt<'_>, def_id: LocalDefId, def_kind: DefKind) -> // the default projection predicates in default trait methods // with RPITITs. ty::AssocItemContainer::TraitContainer => { - assoc_item.defaultness(tcx).has_value() || assoc_item.opt_rpitit_info.is_some() + assoc_item.defaultness(tcx).has_value() || assoc_item.is_impl_trait_in_trait() } } } @@ -1671,7 +1671,9 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { fn encode_info_for_macro(&mut self, def_id: LocalDefId) { let tcx = self.tcx; - let hir::ItemKind::Macro(ref macro_def, _) = tcx.hir().expect_item(def_id).kind else { bug!() }; + let hir::ItemKind::Macro(ref macro_def, _) = tcx.hir().expect_item(def_id).kind else { + bug!() + }; self.tables.is_macro_rules.set(def_id.local_def_index, macro_def.macro_rules); record!(self.tables.macro_definition[def_id.to_def_id()] <- &*macro_def.body); } @@ -1911,7 +1913,9 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { FxHashMap::default(); for id in tcx.hir().items() { - let DefKind::Impl { of_trait } = tcx.def_kind(id.owner_id) else { continue; }; + let DefKind::Impl { of_trait } = tcx.def_kind(id.owner_id) else { + continue; + }; let def_id = id.owner_id.to_def_id(); self.tables.defaultness.set_some(def_id.index, tcx.defaultness(def_id)); @@ -1920,7 +1924,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { if of_trait && let Some(trait_ref) = tcx.impl_trait_ref(def_id) { record!(self.tables.impl_trait_ref[def_id] <- trait_ref); - let trait_ref = trait_ref.subst_identity(); + let trait_ref = trait_ref.instantiate_identity(); let simplified_self_ty = fast_reject::simplify_type(self.tcx, trait_ref.self_ty(), TreatParams::AsCandidateKey); fx_hash_map diff --git a/compiler/rustc_metadata/src/rmeta/mod.rs b/compiler/rustc_metadata/src/rmeta/mod.rs index 9cffd96f4a3..f6087fbe8f6 100644 --- a/compiler/rustc_metadata/src/rmeta/mod.rs +++ b/compiler/rustc_metadata/src/rmeta/mod.rs @@ -264,7 +264,7 @@ pub(crate) struct CrateRoot { traits: LazyArray<DefIndex>, impls: LazyArray<TraitImpls>, incoherent_impls: LazyArray<IncoherentImpls>, - interpret_alloc_index: LazyArray<u32>, + interpret_alloc_index: LazyArray<u64>, proc_macro_data: Option<ProcMacroData>, tables: LazyTables, diff --git a/compiler/rustc_metadata/src/rmeta/table.rs b/compiler/rustc_metadata/src/rmeta/table.rs index a4313d79ab1..4287799a8e6 100644 --- a/compiler/rustc_metadata/src/rmeta/table.rs +++ b/compiler/rustc_metadata/src/rmeta/table.rs @@ -323,7 +323,7 @@ impl<T> FixedSizeEncoding for Option<LazyValue<T>> { impl<T> LazyArray<T> { #[inline] fn write_to_bytes_impl(self, b: &mut [u8; 8]) { - let ([position_bytes, meta_bytes],[])= b.as_chunks_mut::<4>() else { panic!() }; + let ([position_bytes, meta_bytes], []) = b.as_chunks_mut::<4>() else { panic!() }; let position = self.position.get(); let position: u32 = position.try_into().unwrap(); @@ -346,7 +346,7 @@ impl<T> FixedSizeEncoding for LazyArray<T> { #[inline] fn from_bytes(b: &[u8; 8]) -> Self { - let ([position_bytes, meta_bytes],[])= b.as_chunks::<4>() else { panic!() }; + let ([position_bytes, meta_bytes], []) = b.as_chunks::<4>() else { panic!() }; if *meta_bytes == [0; 4] { return Default::default(); } @@ -365,7 +365,7 @@ impl<T> FixedSizeEncoding for Option<LazyArray<T>> { #[inline] fn from_bytes(b: &[u8; 8]) -> Self { - let ([position_bytes, meta_bytes],[])= b.as_chunks::<4>() else { panic!() }; + let ([position_bytes, meta_bytes], []) = b.as_chunks::<4>() else { panic!() }; LazyArray::from_bytes_impl(position_bytes, meta_bytes) } diff --git a/compiler/rustc_middle/src/hir/map/mod.rs b/compiler/rustc_middle/src/hir/map/mod.rs index 6bb8e632dbe..1fd68dc5cb2 100644 --- a/compiler/rustc_middle/src/hir/map/mod.rs +++ b/compiler/rustc_middle/src/hir/map/mod.rs @@ -1103,6 +1103,33 @@ impl<'hir> Map<'hir> { _ => None, } } + + pub fn maybe_get_struct_pattern_shorthand_field(&self, expr: &Expr<'_>) -> Option<Symbol> { + let local = match expr { + Expr { + kind: + ExprKind::Path(QPath::Resolved( + None, + Path { + res: def::Res::Local(_), segments: [PathSegment { ident, .. }], .. + }, + )), + .. + } => Some(ident), + _ => None, + }?; + + match self.find_parent(expr.hir_id)? { + Node::ExprField(field) => { + if field.ident.name == local.name && field.is_shorthand { + return Some(local.name); + } + } + _ => {} + } + + None + } } impl<'hir> intravisit::Map<'hir> for Map<'hir> { diff --git a/compiler/rustc_middle/src/infer/canonical.rs b/compiler/rustc_middle/src/infer/canonical.rs index d5e8330b3f6..81823118ab8 100644 --- a/compiler/rustc_middle/src/infer/canonical.rs +++ b/compiler/rustc_middle/src/infer/canonical.rs @@ -23,7 +23,7 @@ use crate::infer::MemberConstraint; use crate::mir::ConstraintCategory; -use crate::ty::subst::GenericArg; +use crate::ty::GenericArg; use crate::ty::{self, BoundVar, List, Region, Ty, TyCtxt}; use rustc_macros::HashStable; use smallvec::SmallVec; @@ -63,7 +63,7 @@ impl<'tcx> ty::TypeFoldable<TyCtxt<'tcx>> for CanonicalVarInfos<'tcx> { #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TyDecodable, TyEncodable)] #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)] pub struct CanonicalVarValues<'tcx> { - pub var_values: ty::SubstsRef<'tcx>, + pub var_values: ty::GenericArgsRef<'tcx>, } impl CanonicalVarValues<'_> { @@ -429,7 +429,7 @@ impl<'tcx> CanonicalVarValues<'tcx> { infos: CanonicalVarInfos<'tcx>, ) -> CanonicalVarValues<'tcx> { CanonicalVarValues { - var_values: tcx.mk_substs_from_iter(infos.iter().enumerate().map( + var_values: tcx.mk_args_from_iter(infos.iter().enumerate().map( |(i, info)| -> ty::GenericArg<'tcx> { match info.kind { CanonicalVarKind::Ty(_) | CanonicalVarKind::PlaceholderTy(_) => { diff --git a/compiler/rustc_middle/src/infer/mod.rs b/compiler/rustc_middle/src/infer/mod.rs index 2db59f37f40..493bb8a6823 100644 --- a/compiler/rustc_middle/src/infer/mod.rs +++ b/compiler/rustc_middle/src/infer/mod.rs @@ -15,7 +15,7 @@ use rustc_span::Span; #[derive(Debug, Clone, PartialEq, Eq, Hash)] #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)] pub struct MemberConstraint<'tcx> { - /// The `DefId` and substs of the opaque type causing this constraint. + /// The `DefId` and args of the opaque type causing this constraint. /// Used for error reporting. pub key: OpaqueTypeKey<'tcx>, diff --git a/compiler/rustc_middle/src/lint.rs b/compiler/rustc_middle/src/lint.rs index 81c1ae4f630..20230217afc 100644 --- a/compiler/rustc_middle/src/lint.rs +++ b/compiler/rustc_middle/src/lint.rs @@ -169,26 +169,6 @@ impl TyCtxt<'_> { pub fn lint_level_at_node(self, lint: &'static Lint, id: HirId) -> (Level, LintLevelSource) { self.shallow_lint_levels_on(id.owner).lint_level_id_at_node(self, LintId::of(lint), id) } - - /// Walks upwards from `id` to find a node which might change lint levels with attributes. - /// It stops at `bound` and just returns it if reached. - pub fn maybe_lint_level_root_bounded(self, mut id: HirId, bound: HirId) -> HirId { - let hir = self.hir(); - loop { - if id == bound { - return bound; - } - - if hir.attrs(id).iter().any(|attr| Level::from_attr(attr).is_some()) { - return id; - } - let next = hir.parent_id(id); - if next == id { - bug!("lint traversal reached the root of the crate"); - } - id = next; - } - } } /// This struct represents a lint expectation and holds all required information diff --git a/compiler/rustc_middle/src/middle/exported_symbols.rs b/compiler/rustc_middle/src/middle/exported_symbols.rs index 9041da9a060..f19812619b2 100644 --- a/compiler/rustc_middle/src/middle/exported_symbols.rs +++ b/compiler/rustc_middle/src/middle/exported_symbols.rs @@ -1,4 +1,4 @@ -use crate::ty::subst::SubstsRef; +use crate::ty::GenericArgsRef; use crate::ty::{self, Ty, TyCtxt}; use rustc_hir::def_id::{DefId, LOCAL_CRATE}; use rustc_macros::HashStable; @@ -41,7 +41,7 @@ pub struct SymbolExportInfo { #[derive(Eq, PartialEq, Debug, Copy, Clone, TyEncodable, TyDecodable, HashStable)] pub enum ExportedSymbol<'tcx> { NonGeneric(DefId), - Generic(DefId, SubstsRef<'tcx>), + Generic(DefId, GenericArgsRef<'tcx>), DropGlue(Ty<'tcx>), ThreadLocalShim(DefId), NoDefId(ty::SymbolName<'tcx>), @@ -53,15 +53,15 @@ impl<'tcx> ExportedSymbol<'tcx> { pub fn symbol_name_for_local_instance(&self, tcx: TyCtxt<'tcx>) -> ty::SymbolName<'tcx> { match *self { ExportedSymbol::NonGeneric(def_id) => tcx.symbol_name(ty::Instance::mono(tcx, def_id)), - ExportedSymbol::Generic(def_id, substs) => { - tcx.symbol_name(ty::Instance::new(def_id, substs)) + ExportedSymbol::Generic(def_id, args) => { + tcx.symbol_name(ty::Instance::new(def_id, args)) } ExportedSymbol::DropGlue(ty) => { tcx.symbol_name(ty::Instance::resolve_drop_in_place(tcx, ty)) } ExportedSymbol::ThreadLocalShim(def_id) => tcx.symbol_name(ty::Instance { def: ty::InstanceDef::ThreadLocalShim(def_id), - substs: ty::InternalSubsts::empty(), + args: ty::GenericArgs::empty(), }), ExportedSymbol::NoDefId(symbol_name) => symbol_name, } diff --git a/compiler/rustc_middle/src/middle/region.rs b/compiler/rustc_middle/src/middle/region.rs index 10712e14686..c50c5e6f701 100644 --- a/compiler/rustc_middle/src/middle/region.rs +++ b/compiler/rustc_middle/src/middle/region.rs @@ -10,7 +10,7 @@ use crate::ty::TyCtxt; use rustc_data_structures::fx::{FxHashMap, FxIndexMap}; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; use rustc_hir as hir; -use rustc_hir::Node; +use rustc_hir::{HirIdMap, Node}; use rustc_macros::HashStable; use rustc_query_system::ich::StableHashingContext; use rustc_span::{Span, DUMMY_SP}; @@ -228,7 +228,7 @@ pub struct ScopeTree { /// and not the enclosing *statement*. Expressions that are not present in this /// table are not rvalue candidates. The set of rvalue candidates is computed /// during type check based on a traversal of the AST. - pub rvalue_candidates: FxHashMap<hir::HirId, RvalueCandidateType>, + pub rvalue_candidates: HirIdMap<RvalueCandidateType>, /// If there are any `yield` nested within a scope, this map /// stores the `Span` of the last one and its index in the diff --git a/compiler/rustc_middle/src/mir/interpret/error.rs b/compiler/rustc_middle/src/mir/interpret/error.rs index 2435bc59ec0..372452ea29a 100644 --- a/compiler/rustc_middle/src/mir/interpret/error.rs +++ b/compiler/rustc_middle/src/mir/interpret/error.rs @@ -22,7 +22,7 @@ pub enum ErrorHandled { /// *guaranteed* to fail. Warnings/lints *must not* produce `Reported`. Reported(ReportedErrorInfo), /// Don't emit an error, the evaluation failed because the MIR was generic - /// and the substs didn't fully monomorphize it. + /// and the args didn't fully monomorphize it. TooGeneric, } diff --git a/compiler/rustc_middle/src/mir/interpret/mod.rs b/compiler/rustc_middle/src/mir/interpret/mod.rs index 2d2cfee1b21..69c15e9cc06 100644 --- a/compiler/rustc_middle/src/mir/interpret/mod.rs +++ b/compiler/rustc_middle/src/mir/interpret/mod.rs @@ -138,7 +138,7 @@ use rustc_target::abi::{AddressSpace, Endian, HasDataLayout}; use crate::mir; use crate::ty::codec::{TyDecoder, TyEncoder}; -use crate::ty::subst::GenericArgKind; +use crate::ty::GenericArgKind; use crate::ty::{self, Instance, Ty, TyCtxt}; pub use self::error::{ @@ -274,7 +274,7 @@ pub struct AllocDecodingState { // For each `AllocId`, we keep track of which decoding state it's currently in. decoding_state: Vec<Lock<State>>, // The offsets of each allocation in the data stream. - data_offsets: Vec<u32>, + data_offsets: Vec<u64>, } impl AllocDecodingState { @@ -289,7 +289,7 @@ impl AllocDecodingState { AllocDecodingSession { state: self, session_id } } - pub fn new(data_offsets: Vec<u32>) -> Self { + pub fn new(data_offsets: Vec<u64>) -> Self { let decoding_state = std::iter::repeat_with(|| Lock::new(State::Empty)).take(data_offsets.len()).collect(); @@ -559,7 +559,7 @@ impl<'tcx> TyCtxt<'tcx> { // However, formatting code relies on function identity (see #58320), so we only do // this for generic functions. Lifetime parameters are ignored. let is_generic = instance - .substs + .args .into_iter() .any(|kind| !matches!(kind.unpack(), GenericArgKind::Lifetime(_))); if is_generic { diff --git a/compiler/rustc_middle/src/mir/interpret/queries.rs b/compiler/rustc_middle/src/mir/interpret/queries.rs index 9c97431f361..c9db0e7c11d 100644 --- a/compiler/rustc_middle/src/mir/interpret/queries.rs +++ b/compiler/rustc_middle/src/mir/interpret/queries.rs @@ -2,8 +2,8 @@ use super::{ErrorHandled, EvalToConstValueResult, EvalToValTreeResult, GlobalId} use crate::mir; use crate::query::{TyCtxtAt, TyCtxtEnsure}; -use crate::ty::subst::InternalSubsts; use crate::ty::visit::TypeVisitableExt; +use crate::ty::GenericArgs; use crate::ty::{self, TyCtxt}; use rustc_hir::def::DefKind; use rustc_hir::def_id::DefId; @@ -20,8 +20,8 @@ impl<'tcx> TyCtxt<'tcx> { // to be used. So we can't use `Instance::mono`, instead we feed unresolved substitutions // into `const_eval` which will return `ErrorHandled::ToGeneric` if any of them are // encountered. - let substs = InternalSubsts::identity_for_item(self, def_id); - let instance = ty::Instance::new(def_id, substs); + let args = GenericArgs::identity_for_item(self, def_id); + let instance = ty::Instance::new(def_id, args); let cid = GlobalId { instance, promoted: None }; let param_env = self.param_env(def_id).with_reveal_all_normalized(self); self.const_eval_global_id(param_env, cid, None) @@ -48,14 +48,14 @@ impl<'tcx> TyCtxt<'tcx> { // // When trying to evaluate constants containing inference variables, // use `Infcx::const_eval_resolve` instead. - if ct.substs.has_non_region_infer() { + if ct.args.has_non_region_infer() { bug!("did not expect inference variables here"); } match ty::Instance::resolve( self, param_env, // FIXME: maybe have a separate version for resolving mir::UnevaluatedConst? - ct.def, ct.substs, + ct.def, ct.args, ) { Ok(Some(instance)) => { let cid = GlobalId { instance, promoted: ct.promoted }; @@ -79,11 +79,11 @@ impl<'tcx> TyCtxt<'tcx> { // // When trying to evaluate constants containing inference variables, // use `Infcx::const_eval_resolve` instead. - if ct.substs.has_non_region_infer() { + if ct.args.has_non_region_infer() { bug!("did not expect inference variables here"); } - match ty::Instance::resolve(self, param_env, ct.def, ct.substs) { + match ty::Instance::resolve(self, param_env, ct.def, ct.args) { Ok(Some(instance)) => { let cid = GlobalId { instance, promoted: None }; self.const_eval_global_id_for_typeck(param_env, cid, span).inspect(|_| { @@ -94,7 +94,7 @@ impl<'tcx> TyCtxt<'tcx> { // @lcnr believes that successfully evaluating even though there are // used generic parameters is a bug of evaluation, so checking for it // here does feel somewhat sensible. - if !self.features().generic_const_exprs && ct.substs.has_non_region_param() { + if !self.features().generic_const_exprs && ct.args.has_non_region_param() { let def_kind = self.def_kind(instance.def_id()); assert!( matches!( @@ -221,8 +221,8 @@ impl<'tcx> TyCtxtEnsure<'tcx> { // to be used. So we can't use `Instance::mono`, instead we feed unresolved substitutions // into `const_eval` which will return `ErrorHandled::ToGeneric` if any of them are // encountered. - let substs = InternalSubsts::identity_for_item(self.tcx, def_id); - let instance = ty::Instance::new(def_id, substs); + let args = GenericArgs::identity_for_item(self.tcx, def_id); + let instance = ty::Instance::new(def_id, args); let cid = GlobalId { instance, promoted: None }; let param_env = self.tcx.param_env(def_id).with_reveal_all_normalized(self.tcx).with_const(); diff --git a/compiler/rustc_middle/src/mir/mod.rs b/compiler/rustc_middle/src/mir/mod.rs index 28c50587800..97f53a59fd6 100644 --- a/compiler/rustc_middle/src/mir/mod.rs +++ b/compiler/rustc_middle/src/mir/mod.rs @@ -12,7 +12,7 @@ use crate::ty::print::{FmtPrinter, Printer}; use crate::ty::visit::TypeVisitableExt; use crate::ty::{self, List, Ty, TyCtxt}; use crate::ty::{AdtDef, InstanceDef, ScalarInt, UserTypeAnnotationIndex}; -use crate::ty::{GenericArg, InternalSubsts, SubstsRef}; +use crate::ty::{GenericArg, GenericArgs, GenericArgsRef}; use rustc_data_structures::captures::Captures; use rustc_errors::{DiagnosticArgValue, DiagnosticMessage, ErrorGuaranteed, IntoDiagnosticArg}; @@ -1905,15 +1905,15 @@ impl<'tcx> Debug for Operand<'tcx> { impl<'tcx> Operand<'tcx> { /// Convenience helper to make a constant that refers to the fn - /// with given `DefId` and substs. Since this is used to synthesize + /// with given `DefId` and args. Since this is used to synthesize /// MIR, assumes `user_ty` is None. pub fn function_handle( tcx: TyCtxt<'tcx>, def_id: DefId, - substs: impl IntoIterator<Item = GenericArg<'tcx>>, + args: impl IntoIterator<Item = GenericArg<'tcx>>, span: Span, ) -> Self { - let ty = Ty::new_fn_def(tcx, def_id, substs); + let ty = Ty::new_fn_def(tcx, def_id, args); Operand::Constant(Box::new(Constant { span, user_ty: None, @@ -1981,9 +1981,9 @@ impl<'tcx> Operand<'tcx> { /// /// While this is unlikely in general, it's the normal case of what you'll /// find as the `func` in a [`TerminatorKind::Call`]. - pub fn const_fn_def(&self) -> Option<(DefId, SubstsRef<'tcx>)> { + pub fn const_fn_def(&self) -> Option<(DefId, GenericArgsRef<'tcx>)> { let const_ty = self.constant()?.literal.ty(); - if let ty::FnDef(def_id, substs) = *const_ty.kind() { Some((def_id, substs)) } else { None } + if let ty::FnDef(def_id, args) = *const_ty.kind() { Some((def_id, args)) } else { None } } } @@ -2137,12 +2137,12 @@ impl<'tcx> Debug for Rvalue<'tcx> { } } - AggregateKind::Adt(adt_did, variant, substs, _user_ty, _) => { + AggregateKind::Adt(adt_did, variant, args, _user_ty, _) => { ty::tls::with(|tcx| { let variant_def = &tcx.adt_def(adt_did).variant(variant); - let substs = tcx.lift(substs).expect("could not lift for printing"); + let args = tcx.lift(args).expect("could not lift for printing"); let name = FmtPrinter::new(tcx, Namespace::ValueNS) - .print_def_path(variant_def.def_id, substs)? + .print_def_path(variant_def.def_id, args)? .into_buffer(); match variant_def.ctor_kind() { @@ -2159,10 +2159,10 @@ impl<'tcx> Debug for Rvalue<'tcx> { }) } - AggregateKind::Closure(def_id, substs) => ty::tls::with(|tcx| { + AggregateKind::Closure(def_id, args) => ty::tls::with(|tcx| { let name = if tcx.sess.opts.unstable_opts.span_free_formats { - let substs = tcx.lift(substs).unwrap(); - format!("[closure@{}]", tcx.def_path_str_with_substs(def_id, substs),) + let args = tcx.lift(args).unwrap(); + format!("[closure@{}]", tcx.def_path_str_with_args(def_id, args),) } else { let span = tcx.def_span(def_id); format!( @@ -2493,7 +2493,7 @@ impl<'tcx> ConstantKind<'tcx> { }; debug!("expr.kind: {:?}", expr.kind); - let ty = tcx.type_of(def).subst_identity(); + let ty = tcx.type_of(def).instantiate_identity(); debug!(?ty); // FIXME(const_generics): We currently have to special case parameters because `min_const_generics` @@ -2521,23 +2521,22 @@ impl<'tcx> ConstantKind<'tcx> { } let hir_id = tcx.hir().local_def_id_to_hir_id(def); - let parent_substs = if let Some(parent_hir_id) = tcx.hir().opt_parent_id(hir_id) + let parent_args = if let Some(parent_hir_id) = tcx.hir().opt_parent_id(hir_id) && let Some(parent_did) = parent_hir_id.as_owner() { - InternalSubsts::identity_for_item(tcx, parent_did) + GenericArgs::identity_for_item(tcx, parent_did) } else { List::empty() }; - debug!(?parent_substs); + debug!(?parent_args); let did = def.to_def_id(); - let child_substs = InternalSubsts::identity_for_item(tcx, did); - let substs = - tcx.mk_substs_from_iter(parent_substs.into_iter().chain(child_substs.into_iter())); - debug!(?substs); + let child_args = GenericArgs::identity_for_item(tcx, did); + let args = tcx.mk_args_from_iter(parent_args.into_iter().chain(child_args.into_iter())); + debug!(?args); let span = tcx.def_span(def); - let uneval = UnevaluatedConst::new(did, substs); + let uneval = UnevaluatedConst::new(did, args); debug!(?span, ?param_env); match tcx.const_eval_resolve(param_env, uneval, Some(span)) { @@ -2552,7 +2551,7 @@ impl<'tcx> ConstantKind<'tcx> { Self::Unevaluated( UnevaluatedConst { def: did, - substs: InternalSubsts::identity_for_item(tcx, did), + args: GenericArgs::identity_for_item(tcx, did), promoted: None, }, ty, @@ -2578,7 +2577,7 @@ impl<'tcx> ConstantKind<'tcx> { #[derive(Hash, HashStable, TypeFoldable, TypeVisitable)] pub struct UnevaluatedConst<'tcx> { pub def: DefId, - pub substs: SubstsRef<'tcx>, + pub args: GenericArgsRef<'tcx>, pub promoted: Option<Promoted>, } @@ -2586,14 +2585,14 @@ impl<'tcx> UnevaluatedConst<'tcx> { #[inline] pub fn shrink(self) -> ty::UnevaluatedConst<'tcx> { assert_eq!(self.promoted, None); - ty::UnevaluatedConst { def: self.def, substs: self.substs } + ty::UnevaluatedConst { def: self.def, args: self.args } } } impl<'tcx> UnevaluatedConst<'tcx> { #[inline] - pub fn new(def: DefId, substs: SubstsRef<'tcx>) -> UnevaluatedConst<'tcx> { - UnevaluatedConst { def, substs, promoted: Default::default() } + pub fn new(def: DefId, args: GenericArgsRef<'tcx>) -> UnevaluatedConst<'tcx> { + UnevaluatedConst { def, args, promoted: Default::default() } } } @@ -2906,15 +2905,15 @@ fn pretty_print_const_value<'tcx>( ty::Adt(def, _) if def.variants().is_empty() => { fmt.write_str(&format!("{{unreachable(): {}}}", ty))?; } - ty::Adt(def, substs) => { + ty::Adt(def, args) => { let variant_idx = contents .variant .expect("destructed mir constant of adt without variant idx"); let variant_def = &def.variant(variant_idx); - let substs = tcx.lift(substs).unwrap(); + let args = tcx.lift(args).unwrap(); let mut cx = FmtPrinter::new(tcx, Namespace::ValueNS); cx.print_alloc_ids = true; - let cx = cx.print_value_path(variant_def.def_id, substs)?; + let cx = cx.print_value_path(variant_def.def_id, args)?; fmt.write_str(&cx.into_buffer())?; match variant_def.ctor_kind() { diff --git a/compiler/rustc_middle/src/mir/mono.rs b/compiler/rustc_middle/src/mir/mono.rs index ca735d52314..16addc2dc1e 100644 --- a/compiler/rustc_middle/src/mir/mono.rs +++ b/compiler/rustc_middle/src/mir/mono.rs @@ -1,5 +1,5 @@ use crate::dep_graph::{DepNode, WorkProduct, WorkProductId}; -use crate::ty::{subst::InternalSubsts, Instance, InstanceDef, SymbolName, TyCtxt}; +use crate::ty::{GenericArgs, Instance, InstanceDef, SymbolName, TyCtxt}; use rustc_attr::InlineAttr; use rustc_data_structures::base_n; use rustc_data_structures::fingerprint::Fingerprint; @@ -59,19 +59,26 @@ impl<'tcx> MonoItem<'tcx> { pub fn size_estimate(&self, tcx: TyCtxt<'tcx>) -> usize { match *self { MonoItem::Fn(instance) => { - // Estimate the size of a function based on how many statements - // it contains. - tcx.instance_def_size_estimate(instance.def) + match instance.def { + // "Normal" functions size estimate: the number of + // statements, plus one for the terminator. + InstanceDef::Item(..) | InstanceDef::DropGlue(..) => { + let mir = tcx.instance_mir(instance.def); + mir.basic_blocks.iter().map(|bb| bb.statements.len() + 1).sum() + } + // Other compiler-generated shims size estimate: 1 + _ => 1, + } } - // Conservatively estimate the size of a static declaration - // or assembly to be 1. + // Conservatively estimate the size of a static declaration or + // assembly item to be 1. MonoItem::Static(_) | MonoItem::GlobalAsm(_) => 1, } } pub fn is_generic_fn(&self) -> bool { match *self { - MonoItem::Fn(ref instance) => instance.substs.non_erasable_generics().next().is_some(), + MonoItem::Fn(ref instance) => instance.args.non_erasable_generics().next().is_some(), MonoItem::Static(..) | MonoItem::GlobalAsm(..) => false, } } @@ -168,14 +175,14 @@ impl<'tcx> MonoItem<'tcx> { /// which will never be accessed) in its place. pub fn is_instantiable(&self, tcx: TyCtxt<'tcx>) -> bool { debug!("is_instantiable({:?})", self); - let (def_id, substs) = match *self { - MonoItem::Fn(ref instance) => (instance.def_id(), instance.substs), - MonoItem::Static(def_id) => (def_id, InternalSubsts::empty()), + let (def_id, args) = match *self { + MonoItem::Fn(ref instance) => (instance.def_id(), instance.args), + MonoItem::Static(def_id) => (def_id, GenericArgs::empty()), // global asm never has predicates MonoItem::GlobalAsm(..) => return true, }; - !tcx.subst_and_check_impossible_predicates((def_id, &substs)) + !tcx.subst_and_check_impossible_predicates((def_id, &args)) } pub fn local_span(&self, tcx: TyCtxt<'tcx>) -> Option<Span> { @@ -216,7 +223,7 @@ impl<'tcx> fmt::Display for MonoItem<'tcx> { match *self { MonoItem::Fn(instance) => write!(f, "fn {}", instance), MonoItem::Static(def_id) => { - write!(f, "static {}", Instance::new(def_id, InternalSubsts::empty())) + write!(f, "static {}", Instance::new(def_id, GenericArgs::empty())) } MonoItem::GlobalAsm(..) => write!(f, "global_asm"), } @@ -230,7 +237,7 @@ pub struct CodegenUnit<'tcx> { /// contain something unique to this crate (e.g., a module path) /// as well as the crate name and disambiguator. name: Symbol, - items: FxHashMap<MonoItem<'tcx>, (Linkage, Visibility)>, + items: FxHashMap<MonoItem<'tcx>, MonoItemData>, size_estimate: usize, primary: bool, /// True if this is CGU is used to hold code coverage information for dead code, @@ -238,6 +245,14 @@ pub struct CodegenUnit<'tcx> { is_code_coverage_dead_code_cgu: bool, } +/// Auxiliary info about a `MonoItem`. +#[derive(Copy, Clone, PartialEq, Debug, HashStable)] +pub struct MonoItemData { + pub linkage: Linkage, + pub visibility: Visibility, + pub size_estimate: usize, +} + /// Specifies the linkage type for a `MonoItem`. /// /// See <https://llvm.org/docs/LangRef.html#linkage-types> for more details about these variants. @@ -292,12 +307,12 @@ impl<'tcx> CodegenUnit<'tcx> { } /// The order of these items is non-determinstic. - pub fn items(&self) -> &FxHashMap<MonoItem<'tcx>, (Linkage, Visibility)> { + pub fn items(&self) -> &FxHashMap<MonoItem<'tcx>, MonoItemData> { &self.items } /// The order of these items is non-determinstic. - pub fn items_mut(&mut self) -> &mut FxHashMap<MonoItem<'tcx>, (Linkage, Visibility)> { + pub fn items_mut(&mut self) -> &mut FxHashMap<MonoItem<'tcx>, MonoItemData> { &mut self.items } @@ -320,16 +335,16 @@ impl<'tcx> CodegenUnit<'tcx> { base_n::encode(hash, base_n::CASE_INSENSITIVE) } - pub fn compute_size_estimate(&mut self, tcx: TyCtxt<'tcx>) { - // Estimate the size of a codegen unit as (approximately) the number of MIR - // statements it corresponds to. - self.size_estimate = self.items.keys().map(|mi| mi.size_estimate(tcx)).sum(); + pub fn compute_size_estimate(&mut self) { + // The size of a codegen unit as the sum of the sizes of the items + // within it. + self.size_estimate = self.items.values().map(|data| data.size_estimate).sum(); } - #[inline] /// Should only be called if [`compute_size_estimate`] has previously been called. /// /// [`compute_size_estimate`]: Self::compute_size_estimate + #[inline] pub fn size_estimate(&self) -> usize { // Items are never zero-sized, so if we have items the estimate must be // non-zero, unless we forgot to call `compute_size_estimate` first. @@ -355,7 +370,7 @@ impl<'tcx> CodegenUnit<'tcx> { pub fn items_in_deterministic_order( &self, tcx: TyCtxt<'tcx>, - ) -> Vec<(MonoItem<'tcx>, (Linkage, Visibility))> { + ) -> Vec<(MonoItem<'tcx>, MonoItemData)> { // The codegen tests rely on items being process in the same order as // they appear in the file, so for local items, we sort by node_id first #[derive(PartialEq, Eq, PartialOrd, Ord)] @@ -390,7 +405,7 @@ impl<'tcx> CodegenUnit<'tcx> { ) } - let mut items: Vec<_> = self.items().iter().map(|(&i, &l)| (i, l)).collect(); + let mut items: Vec<_> = self.items().iter().map(|(&i, &data)| (i, data)).collect(); items.sort_by_cached_key(|&(i, _)| item_sort_key(tcx, i)); items } diff --git a/compiler/rustc_middle/src/mir/pretty.rs b/compiler/rustc_middle/src/mir/pretty.rs index ffa7a5400d3..8cbab31451b 100644 --- a/compiler/rustc_middle/src/mir/pretty.rs +++ b/compiler/rustc_middle/src/mir/pretty.rs @@ -477,7 +477,7 @@ impl<'tcx> Visitor<'tcx> for ExtraComments<'tcx> { ConstantKind::Ty(ct) => match ct.kind() { ty::ConstKind::Param(p) => format!("Param({})", p), ty::ConstKind::Unevaluated(uv) => { - format!("Unevaluated({}, {:?})", self.tcx.def_path_str(uv.def), uv.substs,) + format!("Unevaluated({}, {:?})", self.tcx.def_path_str(uv.def), uv.args,) } ty::ConstKind::Value(val) => format!("Value({})", fmt_valtree(&val)), ty::ConstKind::Error(_) => "Error".to_string(), @@ -491,7 +491,7 @@ impl<'tcx> Visitor<'tcx> for ExtraComments<'tcx> { format!( "Unevaluated({}, {:?}, {:?})", self.tcx.def_path_str(uv.def), - uv.substs, + uv.args, uv.promoted, ) } @@ -512,16 +512,16 @@ impl<'tcx> Visitor<'tcx> for ExtraComments<'tcx> { self.super_rvalue(rvalue, location); if let Rvalue::Aggregate(kind, _) = rvalue { match **kind { - AggregateKind::Closure(def_id, substs) => { + AggregateKind::Closure(def_id, args) => { self.push("closure"); self.push(&format!("+ def_id: {:?}", def_id)); - self.push(&format!("+ substs: {:#?}", substs)); + self.push(&format!("+ args: {:#?}", args)); } - AggregateKind::Generator(def_id, substs, movability) => { + AggregateKind::Generator(def_id, args, movability) => { self.push("generator"); self.push(&format!("+ def_id: {:?}", def_id)); - self.push(&format!("+ substs: {:#?}", substs)); + self.push(&format!("+ args: {:#?}", args)); self.push(&format!("+ movability: {:?}", movability)); } diff --git a/compiler/rustc_middle/src/mir/query.rs b/compiler/rustc_middle/src/mir/query.rs index 613b132ff2d..e8cb9860ee5 100644 --- a/compiler/rustc_middle/src/mir/query.rs +++ b/compiler/rustc_middle/src/mir/query.rs @@ -194,7 +194,7 @@ impl Debug for GeneratorLayout<'_> { } impl Debug for GenVariantPrinter { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { - let variant_name = ty::GeneratorSubsts::variant_name(self.0); + let variant_name = ty::GeneratorArgs::variant_name(self.0); if fmt.alternate() { write!(fmt, "{:9}({:?})", variant_name, self.0) } else { @@ -265,10 +265,10 @@ pub struct ConstQualifs { /// `UniversalRegions::closure_mapping`.) Note the free regions in the /// closure's signature and captures are erased. /// -/// Example: If type check produces a closure with the closure substs: +/// Example: If type check produces a closure with the closure args: /// /// ```text -/// ClosureSubsts = [ +/// ClosureArgs = [ /// 'a, // From the parent. /// 'b, /// i8, // the "closure kind" @@ -280,7 +280,7 @@ pub struct ConstQualifs { /// We would "renumber" each free region to a unique vid, as follows: /// /// ```text -/// ClosureSubsts = [ +/// ClosureArgs = [ /// '1, // From the parent. /// '2, /// i8, // the "closure kind" diff --git a/compiler/rustc_middle/src/mir/syntax.rs b/compiler/rustc_middle/src/mir/syntax.rs index 7f1d3820341..be27bf75dbd 100644 --- a/compiler/rustc_middle/src/mir/syntax.rs +++ b/compiler/rustc_middle/src/mir/syntax.rs @@ -8,7 +8,7 @@ use super::{BasicBlock, Constant, Local, SwitchTargets, UserTypeProjection}; use crate::mir::coverage::{CodeRegion, CoverageKind}; use crate::traits::Reveal; use crate::ty::adjustment::PointerCoercion; -use crate::ty::subst::SubstsRef; +use crate::ty::GenericArgsRef; use crate::ty::{self, List, Ty}; use crate::ty::{Region, UserTypeAnnotationIndex}; @@ -1050,10 +1050,6 @@ pub type PlaceElem<'tcx> = ProjectionElem<Local, Ty<'tcx>>; /// there may be other effects: if the type has a validity constraint loading the place might be UB /// if the validity constraint is not met. /// -/// **Needs clarification:** Ralf proposes that loading a place not have side-effects. -/// This is what is implemented in miri today. Are these the semantics we want for MIR? Is this -/// something we can even decide without knowing more about Rust's memory model? -/// /// **Needs clarification:** Is loading a place that has its variant index set well-formed? Miri /// currently implements it, but it seems like this may be something to check against in the /// validator. @@ -1071,6 +1067,16 @@ pub enum Operand<'tcx> { /// in [UCG#188]. You should not emit MIR that may attempt a subsequent second load of this /// place without first re-initializing it. /// + /// **Needs clarification:** The operational impact of `Move` is unclear. Currently (both in + /// Miri and codegen) it has no effect at all unless it appears in an argument to `Call`; for + /// `Call` it allows the argument to be passed to the callee "in-place", i.e. the callee might + /// just get a reference to this place instead of a full copy. Miri implements this with a + /// combination of aliasing model "protectors" and putting `uninit` into the place. Ralf + /// proposes that we don't want these semantics for `Move` in regular assignments, because + /// loading a place should not have side-effects, and the aliasing model "protectors" are + /// inherently tied to a function call. Are these the semantics we want for MIR? Is this + /// something we can even decide without knowing more about Rust's memory model? + /// /// [UCG#188]: https://github.com/rust-lang/unsafe-code-guidelines/issues/188 Move(Place<'tcx>), @@ -1262,10 +1268,10 @@ pub enum AggregateKind<'tcx> { /// active field number and is present only for union expressions /// -- e.g., for a union expression `SomeUnion { c: .. }`, the /// active field index would identity the field `c` - Adt(DefId, VariantIdx, SubstsRef<'tcx>, Option<UserTypeAnnotationIndex>, Option<FieldIdx>), + Adt(DefId, VariantIdx, GenericArgsRef<'tcx>, Option<UserTypeAnnotationIndex>, Option<FieldIdx>), - Closure(DefId, SubstsRef<'tcx>), - Generator(DefId, SubstsRef<'tcx>, hir::Movability), + Closure(DefId, GenericArgsRef<'tcx>), + Generator(DefId, GenericArgsRef<'tcx>, hir::Movability), } #[derive(Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)] diff --git a/compiler/rustc_middle/src/mir/tcx.rs b/compiler/rustc_middle/src/mir/tcx.rs index 8618a531527..f79697936d2 100644 --- a/compiler/rustc_middle/src/mir/tcx.rs +++ b/compiler/rustc_middle/src/mir/tcx.rs @@ -35,7 +35,7 @@ impl<'tcx> PlaceTy<'tcx> { #[instrument(level = "debug", skip(tcx), ret)] pub fn field_ty(self, tcx: TyCtxt<'tcx>, f: FieldIdx) -> Ty<'tcx> { match self.ty.kind() { - ty::Adt(adt_def, substs) => { + ty::Adt(adt_def, args) => { let variant_def = match self.variant_index { None => adt_def.non_enum_variant(), Some(variant_index) => { @@ -44,7 +44,7 @@ impl<'tcx> PlaceTy<'tcx> { } }; let field_def = &variant_def.fields[f]; - field_def.ty(tcx, substs) + field_def.ty(tcx, args) } ty::Tuple(tys) => tys[f.index()], _ => bug!("extracting field of non-tuple non-adt: {:?}", self), @@ -198,10 +198,10 @@ impl<'tcx> Rvalue<'tcx> { AggregateKind::Tuple => { Ty::new_tup_from_iter(tcx, ops.iter().map(|op| op.ty(local_decls, tcx))) } - AggregateKind::Adt(did, _, substs, _, _) => tcx.type_of(did).subst(tcx, substs), - AggregateKind::Closure(did, substs) => Ty::new_closure(tcx, did, substs), - AggregateKind::Generator(did, substs, movability) => { - Ty::new_generator(tcx, did, substs, movability) + AggregateKind::Adt(did, _, args, _, _) => tcx.type_of(did).instantiate(tcx, args), + AggregateKind::Closure(did, args) => Ty::new_closure(tcx, did, args), + AggregateKind::Generator(did, args, movability) => { + Ty::new_generator(tcx, did, args, movability) } }, Rvalue::ShallowInitBox(_, ty) => Ty::new_box(tcx, ty), diff --git a/compiler/rustc_middle/src/mir/visit.rs b/compiler/rustc_middle/src/mir/visit.rs index 205dc9ec746..64bc4fa7926 100644 --- a/compiler/rustc_middle/src/mir/visit.rs +++ b/compiler/rustc_middle/src/mir/visit.rs @@ -63,7 +63,7 @@ //! `is_cleanup` above. use crate::mir::*; -use crate::ty::subst::SubstsRef; +use crate::ty::GenericArgsRef; use crate::ty::{self, CanonicalUserTypeAnnotation, Ty}; use rustc_span::Span; @@ -245,12 +245,12 @@ macro_rules! make_mir_visitor { self.super_region(region); } - fn visit_substs( + fn visit_args( &mut self, - substs: & $($mutability)? SubstsRef<'tcx>, + args: & $($mutability)? GenericArgsRef<'tcx>, _: Location, ) { - self.super_substs(substs); + self.super_args(args); } fn visit_local_decl( @@ -335,7 +335,7 @@ macro_rules! make_mir_visitor { self.visit_span($(& $mutability)? *callsite_span); - let ty::Instance { def: callee_def, substs: callee_substs } = callee; + let ty::Instance { def: callee_def, args: callee_args } = callee; match callee_def { ty::InstanceDef::Item(_def_id) => {} @@ -355,7 +355,7 @@ macro_rules! make_mir_visitor { self.visit_ty($(& $mutability)? *ty, TyContext::Location(location)); } } - self.visit_substs(callee_substs, location); + self.visit_args(callee_args, location); } if let Some(inlined_parent_scope) = inlined_parent_scope { self.visit_source_scope($(& $mutability)? *inlined_parent_scope); @@ -721,24 +721,24 @@ macro_rules! make_mir_visitor { AggregateKind::Adt( _adt_def, _variant_index, - substs, - _user_substs, + args, + _user_args, _active_field_index ) => { - self.visit_substs(substs, location); + self.visit_args(args, location); } AggregateKind::Closure( _, - closure_substs + closure_args ) => { - self.visit_substs(closure_substs, location); + self.visit_args(closure_args, location); } AggregateKind::Generator( _, - generator_substs, + generator_args, _movability, ) => { - self.visit_substs(generator_substs, location); + self.visit_args(generator_args, location); } } @@ -933,7 +933,7 @@ macro_rules! make_mir_visitor { fn super_region(&mut self, _region: $(& $mutability)? ty::Region<'tcx>) { } - fn super_substs(&mut self, _substs: & $($mutability)? SubstsRef<'tcx>) { + fn super_args(&mut self, _args: & $($mutability)? GenericArgsRef<'tcx>) { } // Convenience methods diff --git a/compiler/rustc_middle/src/query/keys.rs b/compiler/rustc_middle/src/query/keys.rs index 28e699cd269..a8aec3096d5 100644 --- a/compiler/rustc_middle/src/query/keys.rs +++ b/compiler/rustc_middle/src/query/keys.rs @@ -6,8 +6,8 @@ use crate::mir::interpret::ConstValue; use crate::traits; use crate::ty::fast_reject::SimplifiedType; use crate::ty::layout::{TyAndLayout, ValidityRequirement}; -use crate::ty::subst::{GenericArg, SubstsRef}; use crate::ty::{self, Ty, TyCtxt}; +use crate::ty::{GenericArg, GenericArgsRef}; use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LOCAL_CRATE}; use rustc_hir::hir_id::{HirId, OwnerId}; use rustc_query_system::query::{DefaultCacheSelector, SingleCacheSelector, VecCacheSelector}; @@ -286,7 +286,7 @@ impl Key for (DefId, SimplifiedType) { } } -impl<'tcx> Key for SubstsRef<'tcx> { +impl<'tcx> Key for GenericArgsRef<'tcx> { type CacheSelector = DefaultCacheSelector<Self>; fn default_span(&self, _: TyCtxt<'_>) -> Span { @@ -294,7 +294,7 @@ impl<'tcx> Key for SubstsRef<'tcx> { } } -impl<'tcx> Key for (DefId, SubstsRef<'tcx>) { +impl<'tcx> Key for (DefId, GenericArgsRef<'tcx>) { type CacheSelector = DefaultCacheSelector<Self>; fn default_span(&self, tcx: TyCtxt<'_>) -> Span { @@ -310,7 +310,7 @@ impl<'tcx> Key for (ty::UnevaluatedConst<'tcx>, ty::UnevaluatedConst<'tcx>) { } } -impl<'tcx> Key for (LocalDefId, DefId, SubstsRef<'tcx>) { +impl<'tcx> Key for (LocalDefId, DefId, GenericArgsRef<'tcx>) { type CacheSelector = DefaultCacheSelector<Self>; fn default_span(&self, tcx: TyCtxt<'_>) -> Span { @@ -487,7 +487,7 @@ impl Key for (Symbol, u32, u32) { } } -impl<'tcx> Key for (DefId, Ty<'tcx>, SubstsRef<'tcx>, ty::ParamEnv<'tcx>) { +impl<'tcx> Key for (DefId, Ty<'tcx>, GenericArgsRef<'tcx>, ty::ParamEnv<'tcx>) { type CacheSelector = DefaultCacheSelector<Self>; fn default_span(&self, _tcx: TyCtxt<'_>) -> Span { diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index a059590e6ad..c304245ca39 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -44,7 +44,6 @@ use crate::traits::{ }; use crate::ty::fast_reject::SimplifiedType; use crate::ty::layout::ValidityRequirement; -use crate::ty::subst::{GenericArg, SubstsRef}; use crate::ty::util::AlwaysRequiresDrop; use crate::ty::GeneratorDiagnosticData; use crate::ty::TyCtxtFeed; @@ -52,6 +51,7 @@ use crate::ty::{ self, print::describe_as_module, CrateInherentImpls, ParamEnvAnd, Ty, TyCtxt, UnusedGenericParams, }; +use crate::ty::{GenericArg, GenericArgsRef}; use rustc_arena::TypedArena; use rustc_ast as ast; use rustc_ast::expand::{allocator::AllocatorKind, StrippedCfgItem}; @@ -1032,7 +1032,7 @@ rustc_queries! { } /// Obtain all the calls into other local functions - query mir_inliner_callees(key: ty::InstanceDef<'tcx>) -> &'tcx [(DefId, SubstsRef<'tcx>)] { + query mir_inliner_callees(key: ty::InstanceDef<'tcx>) -> &'tcx [(DefId, GenericArgsRef<'tcx>)] { fatal_cycle desc { |tcx| "computing all local function calls in `{}`", @@ -1537,7 +1537,7 @@ rustc_queries! { /// added or removed in any upstream crate. Instead use the narrower /// `upstream_monomorphizations_for`, `upstream_drop_glue_for`, or, even /// better, `Instance::upstream_monomorphization()`. - query upstream_monomorphizations(_: ()) -> &'tcx DefIdMap<FxHashMap<SubstsRef<'tcx>, CrateNum>> { + query upstream_monomorphizations(_: ()) -> &'tcx DefIdMap<FxHashMap<GenericArgsRef<'tcx>, CrateNum>> { arena_cache desc { "collecting available upstream monomorphizations" } } @@ -1550,7 +1550,7 @@ rustc_queries! { /// You likely want to call `Instance::upstream_monomorphization()` /// instead of invoking this query directly. query upstream_monomorphizations_for(def_id: DefId) - -> Option<&'tcx FxHashMap<SubstsRef<'tcx>, CrateNum>> + -> Option<&'tcx FxHashMap<GenericArgsRef<'tcx>, CrateNum>> { desc { |tcx| "collecting available upstream monomorphizations for `{}`", @@ -1560,7 +1560,7 @@ rustc_queries! { } /// Returns the upstream crate that exports drop-glue for the given - /// type (`substs` is expected to be a single-item list containing the + /// type (`args` is expected to be a single-item list containing the /// type one wants drop-glue for). /// /// This is a subset of `upstream_monomorphizations_for` in order to @@ -1574,8 +1574,8 @@ rustc_queries! { /// NOTE: This query could easily be extended to also support other /// common functions that have are large set of monomorphizations /// (like `Clone::clone` for example). - query upstream_drop_glue_for(substs: SubstsRef<'tcx>) -> Option<CrateNum> { - desc { "available upstream drop-glue for `{:?}`", substs } + query upstream_drop_glue_for(args: GenericArgsRef<'tcx>) -> Option<CrateNum> { + desc { "available upstream drop-glue for `{:?}`", args } } /// Returns a list of all `extern` blocks of a crate. @@ -2053,7 +2053,7 @@ rustc_queries! { desc { "normalizing `{:?}`", goal.value.value.value } } - query subst_and_check_impossible_predicates(key: (DefId, SubstsRef<'tcx>)) -> bool { + query subst_and_check_impossible_predicates(key: (DefId, GenericArgsRef<'tcx>)) -> bool { desc { |tcx| "checking impossible substituted predicates: `{}`", tcx.def_path_str(key.0) @@ -2080,12 +2080,6 @@ rustc_queries! { desc { "looking up supported target features" } } - /// Get an estimate of the size of an InstanceDef based on its MIR for CGU partitioning. - query instance_def_size_estimate(def: ty::InstanceDef<'tcx>) - -> usize { - desc { |tcx| "estimating size for `{}`", tcx.def_path_str(def.def_id()) } - } - query features_query(_: ()) -> &'tcx rustc_feature::Features { feedable desc { "looking up enabled feature gates" } @@ -2104,16 +2098,16 @@ rustc_queries! { } /// Attempt to resolve the given `DefId` to an `Instance`, for the - /// given generics args (`SubstsRef`), returning one of: + /// given generics args (`GenericArgsRef`), returning one of: /// * `Ok(Some(instance))` on success - /// * `Ok(None)` when the `SubstsRef` are still too generic, + /// * `Ok(None)` when the `GenericArgsRef` are still too generic, /// and therefore don't allow finding the final `Instance` /// * `Err(ErrorGuaranteed)` when the `Instance` resolution process /// couldn't complete due to errors elsewhere - this is distinct /// from `Ok(None)` to avoid misleading diagnostics when an error /// has already been/will be emitted, for the original cause query resolve_instance( - key: ty::ParamEnvAnd<'tcx, (DefId, SubstsRef<'tcx>)> + key: ty::ParamEnvAnd<'tcx, (DefId, GenericArgsRef<'tcx>)> ) -> Result<Option<ty::Instance<'tcx>>, ErrorGuaranteed> { desc { "resolving instance `{}`", ty::Instance::new(key.value.0, key.value.1) } } diff --git a/compiler/rustc_middle/src/query/on_disk_cache.rs b/compiler/rustc_middle/src/query/on_disk_cache.rs index 8751d3b7890..995b2140f61 100644 --- a/compiler/rustc_middle/src/query/on_disk_cache.rs +++ b/compiler/rustc_middle/src/query/on_disk_cache.rs @@ -104,7 +104,9 @@ struct Footer { query_result_index: EncodedDepNodeIndex, side_effects_index: EncodedDepNodeIndex, // The location of all allocations. - interpret_alloc_index: Vec<u32>, + // Most uses only need values up to u32::MAX, but benchmarking indicates that we can use a u64 + // without measurable overhead. This permits larger const allocations without ICEing. + interpret_alloc_index: Vec<u64>, // See `OnDiskCache.syntax_contexts` syntax_contexts: FxHashMap<u32, AbsoluteBytePos>, // See `OnDiskCache.expn_data` @@ -301,7 +303,7 @@ impl<'sess> OnDiskCache<'sess> { interpret_alloc_index.reserve(new_n - n); for idx in n..new_n { let id = encoder.interpret_allocs[idx]; - let pos: u32 = encoder.position().try_into().unwrap(); + let pos: u64 = encoder.position().try_into().unwrap(); interpret_alloc_index.push(pos); interpret::specialized_encode_alloc_id(&mut encoder, tcx, id); } diff --git a/compiler/rustc_middle/src/thir.rs b/compiler/rustc_middle/src/thir.rs index e9af5070e5e..e070b054720 100644 --- a/compiler/rustc_middle/src/thir.rs +++ b/compiler/rustc_middle/src/thir.rs @@ -19,8 +19,8 @@ use rustc_middle::middle::region; use rustc_middle::mir::interpret::AllocId; use rustc_middle::mir::{self, BinOp, BorrowKind, FakeReadCause, Mutability, UnOp}; use rustc_middle::ty::adjustment::PointerCoercion; -use rustc_middle::ty::subst::SubstsRef; -use rustc_middle::ty::{self, AdtDef, FnSig, List, Ty, UpvarSubsts}; +use rustc_middle::ty::GenericArgsRef; +use rustc_middle::ty::{self, AdtDef, FnSig, List, Ty, UpvarArgs}; use rustc_middle::ty::{CanonicalUserType, CanonicalUserTypeAnnotation}; use rustc_span::def_id::LocalDefId; use rustc_span::{sym, Span, Symbol, DUMMY_SP}; @@ -150,9 +150,9 @@ pub struct AdtExpr<'tcx> { pub adt_def: AdtDef<'tcx>, /// The variant of the ADT. pub variant_index: VariantIdx, - pub substs: SubstsRef<'tcx>, + pub args: GenericArgsRef<'tcx>, - /// Optional user-given substs: for something like `let x = + /// Optional user-given args: for something like `let x = /// Bar::<T> { ... }`. pub user_ty: UserTy<'tcx>, @@ -164,7 +164,7 @@ pub struct AdtExpr<'tcx> { #[derive(Clone, Debug, HashStable)] pub struct ClosureExpr<'tcx> { pub closure_id: LocalDefId, - pub substs: UpvarSubsts<'tcx>, + pub args: UpvarArgs<'tcx>, pub upvars: Box<[ExprId]>, pub movability: Option<hir::Movability>, pub fake_reads: Vec<(ExprId, FakeReadCause, hir::HirId)>, @@ -418,7 +418,7 @@ pub enum ExprKind<'tcx> { /// An inline `const` block, e.g. `const {}`. ConstBlock { did: DefId, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, }, /// An array literal constructed from one repeated element, e.g. `[1; 5]`. Repeat { @@ -466,7 +466,7 @@ pub enum ExprKind<'tcx> { /// Associated constants and named constants NamedConst { def_id: DefId, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, user_ty: UserTy<'tcx>, }, ConstParam { @@ -714,7 +714,7 @@ pub enum PatKind<'tcx> { /// multiple variants. Variant { adt_def: AdtDef<'tcx>, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, variant_index: VariantIdx, subpatterns: Vec<FieldPat<'tcx>>, }, diff --git a/compiler/rustc_middle/src/thir/visit.rs b/compiler/rustc_middle/src/thir/visit.rs index 14bc1ac0ce7..55ec17423ec 100644 --- a/compiler/rustc_middle/src/thir/visit.rs +++ b/compiler/rustc_middle/src/thir/visit.rs @@ -101,7 +101,7 @@ pub fn walk_expr<'a, 'tcx: 'a, V: Visitor<'a, 'tcx>>(visitor: &mut V, expr: &Exp } } Become { value } => visitor.visit_expr(&visitor.thir()[value]), - ConstBlock { did: _, substs: _ } => {} + ConstBlock { did: _, args: _ } => {} Repeat { value, count: _ } => { visitor.visit_expr(&visitor.thir()[value]); } @@ -115,7 +115,7 @@ pub fn walk_expr<'a, 'tcx: 'a, V: Visitor<'a, 'tcx>>(visitor: &mut V, expr: &Exp ref base, adt_def: _, variant_index: _, - substs: _, + args: _, user_ty: _, }) => { for field in &**fields { @@ -130,7 +130,7 @@ pub fn walk_expr<'a, 'tcx: 'a, V: Visitor<'a, 'tcx>>(visitor: &mut V, expr: &Exp } Closure(box ClosureExpr { closure_id: _, - substs: _, + args: _, upvars: _, movability: _, fake_reads: _, @@ -138,7 +138,7 @@ pub fn walk_expr<'a, 'tcx: 'a, V: Visitor<'a, 'tcx>>(visitor: &mut V, expr: &Exp Literal { lit: _, neg: _ } => {} NonHirLiteral { lit: _, user_ty: _ } => {} ZstLiteral { user_ty: _ } => {} - NamedConst { def_id: _, substs: _, user_ty: _ } => {} + NamedConst { def_id: _, args: _, user_ty: _ } => {} ConstParam { param: _, def_id: _ } => {} StaticRef { alloc_id: _, ty: _, def_id: _ } => {} InlineAsm(box InlineAsmExpr { ref operands, template: _, options: _, line_spans: _ }) => { @@ -227,7 +227,7 @@ pub fn walk_pat<'a, 'tcx: 'a, V: Visitor<'a, 'tcx>>(visitor: &mut V, pat: &Pat<' name: _, } => visitor.visit_pat(&subpattern), Binding { .. } | Wild => {} - Variant { subpatterns, adt_def: _, substs: _, variant_index: _ } | Leaf { subpatterns } => { + Variant { subpatterns, adt_def: _, args: _, variant_index: _ } | Leaf { subpatterns } => { for subpattern in subpatterns { visitor.visit_pat(&subpattern.pattern); } diff --git a/compiler/rustc_middle/src/traits/mod.rs b/compiler/rustc_middle/src/traits/mod.rs index c7d2e4c22d2..b7ffed57a0b 100644 --- a/compiler/rustc_middle/src/traits/mod.rs +++ b/compiler/rustc_middle/src/traits/mod.rs @@ -12,7 +12,7 @@ pub mod util; use crate::infer::canonical::Canonical; use crate::mir::ConstraintCategory; use crate::ty::abstract_const::NotConstEvaluatable; -use crate::ty::subst::SubstsRef; +use crate::ty::GenericArgsRef; use crate::ty::{self, AdtKind, Ty, TyCtxt}; use rustc_data_structures::sync::Lrc; @@ -199,7 +199,7 @@ impl<'tcx> ObligationCause<'tcx> { pub struct UnifyReceiverContext<'tcx> { pub assoc_item: ty::AssocItem, pub param_env: ty::ParamEnv<'tcx>, - pub substs: SubstsRef<'tcx>, + pub args: GenericArgsRef<'tcx>, } #[derive(Clone, PartialEq, Eq, Lift, Default, HashStable)] @@ -696,7 +696,7 @@ impl<'tcx, N> ImplSource<'tcx, N> { match self { ImplSource::UserDefined(i) => ImplSource::UserDefined(ImplSourceUserDefinedData { impl_def_id: i.impl_def_id, - substs: i.substs, + args: i.args, nested: i.nested.into_iter().map(f).collect(), }), ImplSource::Param(n, ct) => ImplSource::Param(n.into_iter().map(f).collect(), ct), @@ -729,7 +729,7 @@ impl<'tcx, N> ImplSource<'tcx, N> { #[derive(TypeFoldable, TypeVisitable)] pub struct ImplSourceUserDefinedData<'tcx, N> { pub impl_def_id: DefId, - pub substs: SubstsRef<'tcx>, + pub args: GenericArgsRef<'tcx>, pub nested: Vec<N>, } diff --git a/compiler/rustc_middle/src/traits/query.rs b/compiler/rustc_middle/src/traits/query.rs index 60a38747fdf..950a59e9695 100644 --- a/compiler/rustc_middle/src/traits/query.rs +++ b/compiler/rustc_middle/src/traits/query.rs @@ -8,7 +8,7 @@ use crate::error::DropCheckOverflow; use crate::infer::canonical::{Canonical, QueryResponse}; use crate::ty::error::TypeError; -use crate::ty::subst::GenericArg; +use crate::ty::GenericArg; use crate::ty::{self, Ty, TyCtxt}; use rustc_span::source_map::Span; @@ -132,7 +132,7 @@ impl<'tcx> DropckOutlivesResult<'tcx> { pub struct DropckConstraint<'tcx> { /// Types that are required to be alive in order for this /// type to be valid for destruction. - pub outlives: Vec<ty::subst::GenericArg<'tcx>>, + pub outlives: Vec<ty::GenericArg<'tcx>>, /// Types that could not be resolved: projections and params. pub dtorck_types: Vec<Ty<'tcx>>, diff --git a/compiler/rustc_middle/src/traits/solve/inspect.rs b/compiler/rustc_middle/src/traits/solve/inspect.rs index 527afa005b9..8698cf86022 100644 --- a/compiler/rustc_middle/src/traits/solve/inspect.rs +++ b/compiler/rustc_middle/src/traits/solve/inspect.rs @@ -32,7 +32,7 @@ pub enum GoalEvaluationKind<'tcx> { } impl Debug for GoalEvaluation<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - ProofTreeFormatter { f, on_newline: true }.format_goal_evaluation(self) + ProofTreeFormatter::new(f).format_goal_evaluation(self) } } @@ -43,7 +43,7 @@ pub struct AddedGoalsEvaluation<'tcx> { } impl Debug for AddedGoalsEvaluation<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - ProofTreeFormatter { f, on_newline: true }.format_nested_goal_evaluation(self) + ProofTreeFormatter::new(f).format_nested_goal_evaluation(self) } } @@ -58,7 +58,7 @@ pub struct GoalEvaluationStep<'tcx> { } impl Debug for GoalEvaluationStep<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - ProofTreeFormatter { f, on_newline: true }.format_evaluation_step(self) + ProofTreeFormatter::new(f).format_evaluation_step(self) } } @@ -78,6 +78,6 @@ pub enum CandidateKind<'tcx> { } impl Debug for GoalCandidate<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - ProofTreeFormatter { f, on_newline: true }.format_candidate(self) + ProofTreeFormatter::new(f).format_candidate(self) } } diff --git a/compiler/rustc_middle/src/traits/solve/inspect/format.rs b/compiler/rustc_middle/src/traits/solve/inspect/format.rs index 2ee625674fa..f19f1189e44 100644 --- a/compiler/rustc_middle/src/traits/solve/inspect/format.rs +++ b/compiler/rustc_middle/src/traits/solve/inspect/format.rs @@ -1,11 +1,19 @@ use super::*; pub(super) struct ProofTreeFormatter<'a, 'b> { - pub(super) f: &'a mut (dyn Write + 'b), - pub(super) on_newline: bool, + f: &'a mut (dyn Write + 'b), } -impl Write for ProofTreeFormatter<'_, '_> { +/// A formatter which adds 4 spaces of indentation to its input before +/// passing it on to its nested formatter. +/// +/// We can use this for arbitrary levels of indentation by nesting it. +struct Indentor<'a, 'b> { + f: &'a mut (dyn Write + 'b), + on_newline: bool, +} + +impl Write for Indentor<'_, '_> { fn write_str(&mut self, s: &str) -> std::fmt::Result { for line in s.split_inclusive("\n") { if self.on_newline { @@ -19,49 +27,52 @@ impl Write for ProofTreeFormatter<'_, '_> { } } -impl ProofTreeFormatter<'_, '_> { - fn nested(&mut self) -> ProofTreeFormatter<'_, '_> { - ProofTreeFormatter { f: self, on_newline: true } +impl<'a, 'b> ProofTreeFormatter<'a, 'b> { + pub(super) fn new(f: &'a mut (dyn Write + 'b)) -> Self { + ProofTreeFormatter { f } } - pub(super) fn format_goal_evaluation(&mut self, goal: &GoalEvaluation<'_>) -> std::fmt::Result { - let f = &mut *self.f; + fn nested<F, R>(&mut self, func: F) -> R + where + F: FnOnce(&mut ProofTreeFormatter<'_, '_>) -> R, + { + func(&mut ProofTreeFormatter { f: &mut Indentor { f: self.f, on_newline: true } }) + } + pub(super) fn format_goal_evaluation(&mut self, goal: &GoalEvaluation<'_>) -> std::fmt::Result { let goal_text = match goal.is_normalizes_to_hack { IsNormalizesToHack::Yes => "NORMALIZES-TO HACK GOAL", IsNormalizesToHack::No => "GOAL", }; - writeln!(f, "{}: {:?}", goal_text, goal.uncanonicalized_goal,)?; - writeln!(f, "CANONICALIZED: {:?}", goal.canonicalized_goal)?; + writeln!(self.f, "{}: {:?}", goal_text, goal.uncanonicalized_goal)?; + writeln!(self.f, "CANONICALIZED: {:?}", goal.canonicalized_goal)?; match &goal.kind { GoalEvaluationKind::CacheHit(CacheHit::Global) => { - writeln!(f, "GLOBAL CACHE HIT: {:?}", goal.result) + writeln!(self.f, "GLOBAL CACHE HIT: {:?}", goal.result) } GoalEvaluationKind::CacheHit(CacheHit::Provisional) => { - writeln!(f, "PROVISIONAL CACHE HIT: {:?}", goal.result) + writeln!(self.f, "PROVISIONAL CACHE HIT: {:?}", goal.result) } GoalEvaluationKind::Uncached { revisions } => { for (n, step) in revisions.iter().enumerate() { - let f = &mut *self.f; - writeln!(f, "REVISION {n}: {:?}", step.result)?; - let mut f = self.nested(); - f.format_evaluation_step(step)?; + writeln!(self.f, "REVISION {n}: {:?}", step.result)?; + self.nested(|this| this.format_evaluation_step(step))?; } - - let f = &mut *self.f; - writeln!(f, "RESULT: {:?}", goal.result) + writeln!(self.f, "RESULT: {:?}", goal.result) } }?; if goal.returned_goals.len() > 0 { - let f = &mut *self.f; - writeln!(f, "NESTED GOALS ADDED TO CALLER: [")?; - let mut f = self.nested(); - for goal in goal.returned_goals.iter() { - writeln!(f, "ADDED GOAL: {:?},", goal)?; - } + writeln!(self.f, "NESTED GOALS ADDED TO CALLER: [")?; + self.nested(|this| { + for goal in goal.returned_goals.iter() { + writeln!(this.f, "ADDED GOAL: {:?},", goal)?; + } + Ok(()) + })?; + writeln!(self.f, "]")?; } @@ -72,58 +83,53 @@ impl ProofTreeFormatter<'_, '_> { &mut self, evaluation_step: &GoalEvaluationStep<'_>, ) -> std::fmt::Result { - let f = &mut *self.f; - writeln!(f, "INSTANTIATED: {:?}", evaluation_step.instantiated_goal)?; + writeln!(self.f, "INSTANTIATED: {:?}", evaluation_step.instantiated_goal)?; for candidate in &evaluation_step.candidates { - let mut f = self.nested(); - f.format_candidate(candidate)?; + self.nested(|this| this.format_candidate(candidate))?; } - for nested_goal_evaluation in &evaluation_step.nested_goal_evaluations { - let mut f = self.nested(); - f.format_nested_goal_evaluation(nested_goal_evaluation)?; + for nested in &evaluation_step.nested_goal_evaluations { + self.nested(|this| this.format_nested_goal_evaluation(nested))?; } Ok(()) } pub(super) fn format_candidate(&mut self, candidate: &GoalCandidate<'_>) -> std::fmt::Result { - let f = &mut *self.f; - match &candidate.kind { CandidateKind::NormalizedSelfTyAssembly => { - writeln!(f, "NORMALIZING SELF TY FOR ASSEMBLY:") + writeln!(self.f, "NORMALIZING SELF TY FOR ASSEMBLY:") } CandidateKind::Candidate { name, result } => { - writeln!(f, "CANDIDATE {}: {:?}", name, result) + writeln!(self.f, "CANDIDATE {}: {:?}", name, result) } }?; - let mut f = self.nested(); - for candidate in &candidate.candidates { - f.format_candidate(candidate)?; - } - for nested_evaluations in &candidate.nested_goal_evaluations { - f.format_nested_goal_evaluation(nested_evaluations)?; - } - - Ok(()) + self.nested(|this| { + for candidate in &candidate.candidates { + this.format_candidate(candidate)?; + } + for nested in &candidate.nested_goal_evaluations { + this.format_nested_goal_evaluation(nested)?; + } + Ok(()) + }) } pub(super) fn format_nested_goal_evaluation( &mut self, nested_goal_evaluation: &AddedGoalsEvaluation<'_>, ) -> std::fmt::Result { - let f = &mut *self.f; - writeln!(f, "TRY_EVALUATE_ADDED_GOALS: {:?}", nested_goal_evaluation.result)?; + writeln!(self.f, "TRY_EVALUATE_ADDED_GOALS: {:?}", nested_goal_evaluation.result)?; for (n, revision) in nested_goal_evaluation.evaluations.iter().enumerate() { - let f = &mut *self.f; - writeln!(f, "REVISION {n}")?; - let mut f = self.nested(); - for goal_evaluation in revision { - f.format_goal_evaluation(goal_evaluation)?; - } + writeln!(self.f, "REVISION {n}")?; + self.nested(|this| { + for goal_evaluation in revision { + this.format_goal_evaluation(goal_evaluation)?; + } + Ok(()) + })?; } Ok(()) diff --git a/compiler/rustc_middle/src/traits/specialization_graph.rs b/compiler/rustc_middle/src/traits/specialization_graph.rs index dc2cd203560..18a57b6181a 100644 --- a/compiler/rustc_middle/src/traits/specialization_graph.rs +++ b/compiler/rustc_middle/src/traits/specialization_graph.rs @@ -259,7 +259,9 @@ pub fn ancestors( if let Some(reported) = specialization_graph.has_errored { Err(reported) - } else if let Err(reported) = tcx.type_of(start_from_impl).subst_identity().error_reported() { + } else if let Err(reported) = + tcx.type_of(start_from_impl).instantiate_identity().error_reported() + { Err(reported) } else { Ok(Ancestors { diff --git a/compiler/rustc_middle/src/traits/structural_impls.rs b/compiler/rustc_middle/src/traits/structural_impls.rs index a703e3c9562..e2cd118500b 100644 --- a/compiler/rustc_middle/src/traits/structural_impls.rs +++ b/compiler/rustc_middle/src/traits/structural_impls.rs @@ -26,8 +26,8 @@ impl<'tcx, N: fmt::Debug> fmt::Debug for traits::ImplSourceUserDefinedData<'tcx, fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, - "ImplSourceUserDefinedData(impl_def_id={:?}, substs={:?}, nested={:?})", - self.impl_def_id, self.substs, self.nested + "ImplSourceUserDefinedData(impl_def_id={:?}, args={:?}, nested={:?})", + self.impl_def_id, self.args, self.nested ) } } diff --git a/compiler/rustc_middle/src/ty/abstract_const.rs b/compiler/rustc_middle/src/ty/abstract_const.rs index ffee7ba28c3..0364a620810 100644 --- a/compiler/rustc_middle/src/ty/abstract_const.rs +++ b/compiler/rustc_middle/src/ty/abstract_const.rs @@ -55,8 +55,8 @@ impl<'tcx> TyCtxt<'tcx> { ty::ConstKind::Unevaluated(uv) => match self.tcx.thir_abstract_const(uv.def) { Err(e) => ty::Const::new_error(self.tcx, e, c.ty()), Ok(Some(bac)) => { - let substs = self.tcx.erase_regions(uv.substs); - let bac = bac.subst(self.tcx, substs); + let args = self.tcx.erase_regions(uv.args); + let bac = bac.instantiate(self.tcx, args); return bac.fold_with(self); } Ok(None) => c, diff --git a/compiler/rustc_middle/src/ty/assoc.rs b/compiler/rustc_middle/src/ty/assoc.rs index cce609c261e..f77a8c6712e 100644 --- a/compiler/rustc_middle/src/ty/assoc.rs +++ b/compiler/rustc_middle/src/ty/assoc.rs @@ -84,14 +84,22 @@ impl AssocItem { // late-bound regions, and we don't want method signatures to show up // `as for<'r> fn(&'r MyType)`. Pretty-printing handles late-bound // regions just fine, showing `fn(&MyType)`. - tcx.fn_sig(self.def_id).subst_identity().skip_binder().to_string() + tcx.fn_sig(self.def_id).instantiate_identity().skip_binder().to_string() } ty::AssocKind::Type => format!("type {};", self.name), ty::AssocKind::Const => { - format!("const {}: {:?};", self.name, tcx.type_of(self.def_id).subst_identity()) + format!( + "const {}: {:?};", + self.name, + tcx.type_of(self.def_id).instantiate_identity() + ) } } } + + pub fn is_impl_trait_in_trait(&self) -> bool { + self.opt_rpitit_info.is_some() + } } #[derive(Copy, Clone, PartialEq, Debug, HashStable, Eq, Hash, Encodable, Decodable)] diff --git a/compiler/rustc_middle/src/ty/closure.rs b/compiler/rustc_middle/src/ty/closure.rs index bc927374549..91eefa2c125 100644 --- a/compiler/rustc_middle/src/ty/closure.rs +++ b/compiler/rustc_middle/src/ty/closure.rs @@ -6,9 +6,10 @@ use crate::{mir, ty}; use std::fmt::Write; use crate::query::Providers; -use rustc_data_structures::fx::{FxHashMap, FxIndexMap}; +use rustc_data_structures::fx::FxIndexMap; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::{self as hir, LangItem}; +use rustc_span::def_id::LocalDefIdMap; use rustc_span::symbol::Ident; use rustc_span::{Span, Symbol}; @@ -56,12 +57,9 @@ pub enum UpvarCapture { ByRef(BorrowKind), } -pub type UpvarListMap = FxHashMap<DefId, FxIndexMap<hir::HirId, UpvarId>>; -pub type UpvarCaptureMap = FxHashMap<UpvarId, UpvarCapture>; - /// Given the closure DefId this map provides a map of root variables to minimum /// set of `CapturedPlace`s that need to be tracked to support all captures of that closure. -pub type MinCaptureInformationMap<'tcx> = FxHashMap<LocalDefId, RootVariableMinCaptureList<'tcx>>; +pub type MinCaptureInformationMap<'tcx> = LocalDefIdMap<RootVariableMinCaptureList<'tcx>>; /// Part of `MinCaptureInformationMap`; Maps a root variable to the list of `CapturedPlace`. /// Used to track the minimum set of `Place`s that need to be captured to support all diff --git a/compiler/rustc_middle/src/ty/codec.rs b/compiler/rustc_middle/src/ty/codec.rs index 6adbb44a153..b4f4f9bef8e 100644 --- a/compiler/rustc_middle/src/ty/codec.rs +++ b/compiler/rustc_middle/src/ty/codec.rs @@ -13,7 +13,7 @@ use crate::mir::{ interpret::{AllocId, ConstAllocation}, }; use crate::traits; -use crate::ty::subst::SubstsRef; +use crate::ty::GenericArgsRef; use crate::ty::{self, AdtDef, Ty}; use rustc_data_structures::fx::FxHashMap; use rustc_middle::ty::TyCtxt; @@ -254,12 +254,12 @@ impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for ty::Clause<'tcx> { } } -impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for SubstsRef<'tcx> { +impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for GenericArgsRef<'tcx> { fn decode(decoder: &mut D) -> Self { let len = decoder.read_usize(); let tcx = decoder.interner(); - tcx.mk_substs_from_iter( - (0..len).map::<ty::subst::GenericArg<'tcx>, _>(|_| Decodable::decode(decoder)), + tcx.mk_args_from_iter( + (0..len).map::<ty::GenericArg<'tcx>, _>(|_| Decodable::decode(decoder)), ) } } diff --git a/compiler/rustc_middle/src/ty/consts.rs b/compiler/rustc_middle/src/ty/consts.rs index 1cbfe99f87f..bf9f5846ed9 100644 --- a/compiler/rustc_middle/src/ty/consts.rs +++ b/compiler/rustc_middle/src/ty/consts.rs @@ -1,6 +1,6 @@ use crate::middle::resolve_bound_vars as rbv; use crate::mir::interpret::{AllocId, ConstValue, LitToConstInput, Scalar}; -use crate::ty::{self, InternalSubsts, ParamEnv, ParamEnvAnd, Ty, TyCtxt, TypeVisitableExt}; +use crate::ty::{self, GenericArgs, ParamEnv, ParamEnvAnd, Ty, TyCtxt, TypeVisitableExt}; use rustc_data_structures::intern::Interned; use rustc_error_messages::MultiSpan; use rustc_hir as hir; @@ -171,7 +171,7 @@ impl<'tcx> Const<'tcx> { tcx, ty::UnevaluatedConst { def: def.to_def_id(), - substs: InternalSubsts::identity_for_item(tcx, def.to_def_id()), + args: GenericArgs::identity_for_item(tcx, def.to_def_id()), }, ty, ), @@ -225,7 +225,7 @@ impl<'tcx> Const<'tcx> { )) => { // Use the type from the param's definition, since we can resolve it, // not the expected parameter type from WithOptConstParam. - let param_ty = tcx.type_of(def_id).subst_identity(); + let param_ty = tcx.type_of(def_id).instantiate_identity(); match tcx.named_bound_var(expr.hir_id) { Some(rbv::ResolvedArg::EarlyBound(_)) => { // Find the name and index of the const parameter by indexing the generics of @@ -406,14 +406,14 @@ impl<'tcx> Const<'tcx> { // any region variables. // HACK(eddyb) when the query key would contain inference variables, - // attempt using identity substs and `ParamEnv` instead, that will succeed + // attempt using identity args and `ParamEnv` instead, that will succeed // when the expression doesn't depend on any parameters. // FIXME(eddyb, skinny121) pass `InferCtxt` into here when it's available, so that // we can call `infcx.const_eval_resolve` which handles inference variables. let param_env_and = if (param_env, unevaluated).has_non_region_infer() { tcx.param_env(unevaluated.def).and(ty::UnevaluatedConst { def: unevaluated.def, - substs: InternalSubsts::identity_for_item(tcx, unevaluated.def), + args: GenericArgs::identity_for_item(tcx, unevaluated.def), }) } else { tcx.erase_regions(param_env) @@ -430,8 +430,8 @@ impl<'tcx> Const<'tcx> { EvalMode::Typeck => { match tcx.const_eval_resolve_for_typeck(param_env, unevaluated, None) { // NOTE(eddyb) `val` contains no lifetimes/types/consts, - // and we use the original type, so nothing from `substs` - // (which may be identity substs, see above), + // and we use the original type, so nothing from `args` + // (which may be identity args, see above), // can leak through `val` into the const we return. Ok(val) => Some(Ok(EvalResult::ValTree(val?))), Err(ErrorHandled::TooGeneric) => None, @@ -441,8 +441,8 @@ impl<'tcx> Const<'tcx> { EvalMode::Mir => { match tcx.const_eval_resolve(param_env, unevaluated.expand(), None) { // NOTE(eddyb) `val` contains no lifetimes/types/consts, - // and we use the original type, so nothing from `substs` - // (which may be identity substs, see above), + // and we use the original type, so nothing from `args` + // (which may be identity args, see above), // can leak through `val` into the const we return. Ok(val) => Some(Ok(EvalResult::ConstVal(val))), Err(ErrorHandled::TooGeneric) => None, diff --git a/compiler/rustc_middle/src/ty/consts/int.rs b/compiler/rustc_middle/src/ty/consts/int.rs index 1e43fab457e..624195cfb28 100644 --- a/compiler/rustc_middle/src/ty/consts/int.rs +++ b/compiler/rustc_middle/src/ty/consts/int.rs @@ -418,7 +418,7 @@ impl TryFrom<ScalarInt> for char { #[inline] fn try_from(int: ScalarInt) -> Result<Self, Self::Error> { - let Ok(bits) = int.to_bits(Size::from_bytes(std::mem::size_of::<char>())) else { + let Ok(bits) = int.to_bits(Size::from_bytes(std::mem::size_of::<char>())) else { return Err(CharTryFromScalarInt); }; match char::from_u32(bits.try_into().unwrap()) { diff --git a/compiler/rustc_middle/src/ty/consts/kind.rs b/compiler/rustc_middle/src/ty/consts/kind.rs index a6bf7491118..6c76075c214 100644 --- a/compiler/rustc_middle/src/ty/consts/kind.rs +++ b/compiler/rustc_middle/src/ty/consts/kind.rs @@ -1,18 +1,18 @@ use super::Const; use crate::mir; use crate::ty::abstract_const::CastKind; -use crate::ty::subst::SubstsRef; +use crate::ty::GenericArgsRef; use crate::ty::{self, List, Ty}; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; use rustc_hir::def_id::DefId; use rustc_macros::HashStable; /// An unevaluated (potentially generic) constant used in the type-system. -#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, TyEncodable, TyDecodable, Lift)] +#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, TyEncodable, TyDecodable, Lift)] #[derive(Hash, HashStable, TypeFoldable, TypeVisitable)] pub struct UnevaluatedConst<'tcx> { pub def: DefId, - pub substs: SubstsRef<'tcx>, + pub args: GenericArgsRef<'tcx>, } impl rustc_errors::IntoDiagnosticArg for UnevaluatedConst<'_> { @@ -24,18 +24,18 @@ impl rustc_errors::IntoDiagnosticArg for UnevaluatedConst<'_> { impl<'tcx> UnevaluatedConst<'tcx> { #[inline] pub fn expand(self) -> mir::UnevaluatedConst<'tcx> { - mir::UnevaluatedConst { def: self.def, substs: self.substs, promoted: None } + mir::UnevaluatedConst { def: self.def, args: self.args, promoted: None } } } impl<'tcx> UnevaluatedConst<'tcx> { #[inline] - pub fn new(def: DefId, substs: SubstsRef<'tcx>) -> UnevaluatedConst<'tcx> { - UnevaluatedConst { def, substs } + pub fn new(def: DefId, args: GenericArgsRef<'tcx>) -> UnevaluatedConst<'tcx> { + UnevaluatedConst { def, args } } } -#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash)] +#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Hash)] #[derive(HashStable, TyEncodable, TyDecodable, TypeVisitable, TypeFoldable)] pub enum Expr<'tcx> { Binop(mir::BinOp, Const<'tcx>, Const<'tcx>), diff --git a/compiler/rustc_middle/src/ty/consts/valtree.rs b/compiler/rustc_middle/src/ty/consts/valtree.rs index 8b96864ddd7..fb7bf78bafe 100644 --- a/compiler/rustc_middle/src/ty/consts/valtree.rs +++ b/compiler/rustc_middle/src/ty/consts/valtree.rs @@ -24,7 +24,7 @@ pub enum ValTree<'tcx> { Leaf(ScalarInt), //SliceOrStr(ValSlice<'tcx>), - // dont use SliceOrStr for now + // don't use SliceOrStr for now /// The fields of any kind of aggregate. Structs, tuples and arrays are represented by /// listing their fields' values in order. /// diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index 6990fbbb634..8bb13edbe95 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -30,7 +30,7 @@ use crate::ty::{ Predicate, PredicateKind, Region, RegionKind, ReprOptions, TraitObjectVisitor, Ty, TyKind, TyVid, TypeAndMut, Visibility, }; -use crate::ty::{GenericArg, InternalSubsts, SubstsRef}; +use crate::ty::{GenericArg, GenericArgs, GenericArgsRef}; use rustc_ast::{self as ast, attr}; use rustc_data_structures::fingerprint::Fingerprint; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; @@ -84,7 +84,7 @@ use std::ops::{Bound, Deref}; #[allow(rustc::usage_of_ty_tykind)] impl<'tcx> Interner for TyCtxt<'tcx> { type AdtDef = ty::AdtDef<'tcx>; - type SubstsRef = ty::SubstsRef<'tcx>; + type GenericArgsRef = ty::GenericArgsRef<'tcx>; type DefId = DefId; type Binder<T> = Binder<'tcx, T>; type Ty = Ty<'tcx>; @@ -142,7 +142,7 @@ pub struct CtxtInterners<'tcx> { // they're accessed quite often. type_: InternedSet<'tcx, WithCachedTypeInfo<TyKind<'tcx>>>, const_lists: InternedSet<'tcx, List<ty::Const<'tcx>>>, - substs: InternedSet<'tcx, InternalSubsts<'tcx>>, + args: InternedSet<'tcx, GenericArgs<'tcx>>, type_lists: InternedSet<'tcx, List<Ty<'tcx>>>, canonical_var_infos: InternedSet<'tcx, List<CanonicalVarInfo<'tcx>>>, region: InternedSet<'tcx, RegionKind<'tcx>>, @@ -167,7 +167,7 @@ impl<'tcx> CtxtInterners<'tcx> { arena, type_: Default::default(), const_lists: Default::default(), - substs: Default::default(), + args: Default::default(), type_lists: Default::default(), region: Default::default(), poly_existential_predicates: Default::default(), @@ -682,7 +682,7 @@ impl<'tcx> TyCtxt<'tcx> { /// Creates a type context and call the closure with a `TyCtxt` reference /// to the context. The closure enforces that the type context and any interned - /// value (types, substs, etc.) can only be used while `ty::tls` has a valid + /// value (types, args, etc.) can only be used while `ty::tls` has a valid /// reference to the context, to allow formatting values that need it. pub fn create_global_ctxt( s: &'tcx Session, @@ -1083,7 +1083,7 @@ impl<'tcx> TyCtxt<'tcx> { _ => return None, } - let ret_ty = self.type_of(scope_def_id).subst_identity(); + let ret_ty = self.type_of(scope_def_id).instantiate_identity(); match ret_ty.kind() { ty::FnDef(_, _) => { let sig = ret_ty.fn_sig(self); @@ -1125,7 +1125,7 @@ impl<'tcx> TyCtxt<'tcx> { self, self.lifetimes.re_static, self.type_of(self.require_lang_item(LangItem::PanicLocation, None)) - .subst(self, self.mk_substs(&[self.lifetimes.re_static.into()])), + .instantiate(self, self.mk_args(&[self.lifetimes.re_static.into()])), ) } @@ -1168,7 +1168,7 @@ impl<'tcx> TyCtxt<'tcx> { /// A trait implemented for all `X<'a>` types that can be safely and /// efficiently converted to `X<'tcx>` as long as they are part of the /// provided `TyCtxt<'tcx>`. -/// This can be done, for example, for `Ty<'tcx>` or `SubstsRef<'tcx>` +/// This can be done, for example, for `Ty<'tcx>` or `GenericArgsRef<'tcx>` /// by looking them up in their respective interners. /// /// However, this is still not the best implementation as it does @@ -1234,8 +1234,8 @@ nop_list_lift! {canonical_var_infos; CanonicalVarInfo<'a> => CanonicalVarInfo<'t nop_list_lift! {projs; ProjectionKind => ProjectionKind} nop_list_lift! {bound_variable_kinds; ty::BoundVariableKind => ty::BoundVariableKind} -// This is the impl for `&'a InternalSubsts<'a>`. -nop_list_lift! {substs; GenericArg<'a> => GenericArg<'tcx>} +// This is the impl for `&'a GenericArgs<'a>`. +nop_list_lift! {args; GenericArg<'a> => GenericArg<'tcx>} CloneLiftImpls! { Constness, @@ -1347,7 +1347,7 @@ impl<'tcx> TyCtxt<'tcx> { Foreign )?; - writeln!(fmt, "InternalSubsts interner: #{}", self.0.interners.substs.len())?; + writeln!(fmt, "GenericArgs interner: #{}", self.0.interners.args.len())?; writeln!(fmt, "Region interner: #{}", self.0.interners.region.len())?; writeln!( fmt, @@ -1503,7 +1503,7 @@ macro_rules! slice_interners { // should be used when possible, because it's faster. slice_interners!( const_lists: pub mk_const_list(Const<'tcx>), - substs: pub mk_substs(GenericArg<'tcx>), + args: pub mk_args(GenericArg<'tcx>), type_lists: pub mk_type_list(Ty<'tcx>), canonical_var_infos: pub mk_canonical_var_infos(CanonicalVarInfo<'tcx>), poly_existential_predicates: intern_poly_existential_predicates(PolyExistentialPredicate<'tcx>), @@ -1617,12 +1617,12 @@ impl<'tcx> TyCtxt<'tcx> { } #[inline(always)] - pub(crate) fn check_and_mk_substs( + pub(crate) fn check_and_mk_args( self, _def_id: DefId, - substs: impl IntoIterator<Item: Into<GenericArg<'tcx>>>, - ) -> SubstsRef<'tcx> { - let substs = substs.into_iter().map(Into::into); + args: impl IntoIterator<Item: Into<GenericArg<'tcx>>>, + ) -> GenericArgsRef<'tcx> { + let args = args.into_iter().map(Into::into); #[cfg(debug_assertions)] { let generics = self.generics_of(_def_id); @@ -1638,12 +1638,12 @@ impl<'tcx> TyCtxt<'tcx> { }; assert_eq!( (n, Some(n)), - substs.size_hint(), + args.size_hint(), "wrong number of generic parameters for {_def_id:?}: {:?}", - substs.collect::<Vec<_>>(), + args.collect::<Vec<_>>(), ); } - self.mk_substs_from_iter(substs) + self.mk_args_from_iter(args) } #[inline] @@ -1801,12 +1801,12 @@ impl<'tcx> TyCtxt<'tcx> { T::collect_and_apply(iter, |xs| self.mk_type_list(xs)) } - pub fn mk_substs_from_iter<I, T>(self, iter: I) -> T::Output + pub fn mk_args_from_iter<I, T>(self, iter: I) -> T::Output where I: Iterator<Item = T>, T: CollectAndApply<GenericArg<'tcx>, &'tcx List<GenericArg<'tcx>>>, { - T::collect_and_apply(iter, |xs| self.mk_substs(xs)) + T::collect_and_apply(iter, |xs| self.mk_args(xs)) } pub fn mk_canonical_var_infos_from_iter<I, T>(self, iter: I) -> T::Output @@ -1833,21 +1833,21 @@ impl<'tcx> TyCtxt<'tcx> { T::collect_and_apply(iter, |xs| self.mk_fields(xs)) } - pub fn mk_substs_trait( + pub fn mk_args_trait( self, self_ty: Ty<'tcx>, rest: impl IntoIterator<Item = GenericArg<'tcx>>, - ) -> SubstsRef<'tcx> { - self.mk_substs_from_iter(iter::once(self_ty.into()).chain(rest)) + ) -> GenericArgsRef<'tcx> { + self.mk_args_from_iter(iter::once(self_ty.into()).chain(rest)) } pub fn mk_alias_ty( self, def_id: DefId, - substs: impl IntoIterator<Item: Into<GenericArg<'tcx>>>, + args: impl IntoIterator<Item: Into<GenericArg<'tcx>>>, ) -> ty::AliasTy<'tcx> { - let substs = self.check_and_mk_substs(def_id, substs); - ty::AliasTy { def_id, substs, _use_mk_alias_ty_instead: () } + let args = self.check_and_mk_args(def_id, args); + ty::AliasTy { def_id, args, _use_mk_alias_ty_instead: () } } pub fn mk_bound_variable_kinds_from_iter<I, T>(self, iter: I) -> T::Output diff --git a/compiler/rustc_middle/src/ty/diagnostics.rs b/compiler/rustc_middle/src/ty/diagnostics.rs index a0b17c374e4..905e855896e 100644 --- a/compiler/rustc_middle/src/ty/diagnostics.rs +++ b/compiler/rustc_middle/src/ty/diagnostics.rs @@ -71,7 +71,7 @@ impl<'tcx> Ty<'tcx> { /// ADTs with no type arguments. pub fn is_simple_text(self) -> bool { match self.kind() { - Adt(_, substs) => substs.non_erasable_generics().next().is_none(), + Adt(_, args) => args.non_erasable_generics().next().is_none(), Ref(_, ty, _) => ty.is_simple_text(), _ => self.is_simple_ty(), } @@ -491,7 +491,7 @@ impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for IsSuggestableVisitor<'tcx> { Alias(Opaque, AliasTy { def_id, .. }) => { let parent = self.tcx.parent(def_id); - let parent_ty = self.tcx.type_of(parent).subst_identity(); + let parent_ty = self.tcx.type_of(parent).instantiate_identity(); if let DefKind::TyAlias | DefKind::AssocTy = self.tcx.def_kind(parent) && let Alias(Opaque, AliasTy { def_id: parent_opaque_def_id, .. }) = *parent_ty.kind() && parent_opaque_def_id == def_id @@ -558,8 +558,8 @@ impl<'tcx> FallibleTypeFolder<TyCtxt<'tcx>> for MakeSuggestableFolder<'tcx> { let t = match *t.kind() { Infer(InferTy::TyVar(_)) if self.infer_suggestable => t, - FnDef(def_id, substs) => { - Ty::new_fn_ptr(self.tcx, self.tcx.fn_sig(def_id).subst(self.tcx, substs)) + FnDef(def_id, args) => { + Ty::new_fn_ptr(self.tcx, self.tcx.fn_sig(def_id).instantiate(self.tcx, args)) } // FIXME(compiler-errors): We could replace these with infer, I guess. @@ -575,7 +575,7 @@ impl<'tcx> FallibleTypeFolder<TyCtxt<'tcx>> for MakeSuggestableFolder<'tcx> { Alias(Opaque, AliasTy { def_id, .. }) => { let parent = self.tcx.parent(def_id); - let parent_ty = self.tcx.type_of(parent).subst_identity(); + let parent_ty = self.tcx.type_of(parent).instantiate_identity(); if let hir::def::DefKind::TyAlias | hir::def::DefKind::AssocTy = self.tcx.def_kind(parent) && let Alias(Opaque, AliasTy { def_id: parent_opaque_def_id, .. }) = *parent_ty.kind() && parent_opaque_def_id == def_id diff --git a/compiler/rustc_middle/src/ty/fast_reject.rs b/compiler/rustc_middle/src/ty/fast_reject.rs index 76f61d9ac9c..e86ff4d26aa 100644 --- a/compiler/rustc_middle/src/ty/fast_reject.rs +++ b/compiler/rustc_middle/src/ty/fast_reject.rs @@ -1,6 +1,6 @@ use crate::mir::Mutability; -use crate::ty::subst::GenericArgKind; -use crate::ty::{self, SubstsRef, Ty, TyCtxt, TypeVisitableExt}; +use crate::ty::GenericArgKind; +use crate::ty::{self, GenericArgsRef, Ty, TyCtxt, TypeVisitableExt}; use rustc_hir::def_id::DefId; use std::fmt::Debug; use std::hash::Hash; @@ -188,12 +188,12 @@ pub struct DeepRejectCtxt { } impl DeepRejectCtxt { - pub fn substs_refs_may_unify<'tcx>( + pub fn args_refs_may_unify<'tcx>( self, - obligation_substs: SubstsRef<'tcx>, - impl_substs: SubstsRef<'tcx>, + obligation_args: GenericArgsRef<'tcx>, + impl_args: GenericArgsRef<'tcx>, ) -> bool { - iter::zip(obligation_substs, impl_substs).all(|(obl, imp)| { + iter::zip(obligation_args, impl_args).all(|(obl, imp)| { match (obl.unpack(), imp.unpack()) { // We don't fast reject based on regions for now. (GenericArgKind::Lifetime(_), GenericArgKind::Lifetime(_)) => true, @@ -258,9 +258,9 @@ impl DeepRejectCtxt { } _ => false, }, - ty::Adt(obl_def, obl_substs) => match k { - &ty::Adt(impl_def, impl_substs) => { - obl_def == impl_def && self.substs_refs_may_unify(obl_substs, impl_substs) + ty::Adt(obl_def, obl_args) => match k { + &ty::Adt(impl_def, impl_args) => { + obl_def == impl_def && self.args_refs_may_unify(obl_args, impl_args) } _ => false, }, diff --git a/compiler/rustc_middle/src/ty/flags.rs b/compiler/rustc_middle/src/ty/flags.rs index ff391794703..bbd4a623330 100644 --- a/compiler/rustc_middle/src/ty/flags.rs +++ b/compiler/rustc_middle/src/ty/flags.rs @@ -1,5 +1,5 @@ -use crate::ty::subst::{GenericArg, GenericArgKind}; use crate::ty::{self, InferConst, Ty, TypeFlags}; +use crate::ty::{GenericArg, GenericArgKind}; use std::slice; #[derive(Debug)] @@ -105,48 +105,48 @@ impl FlagComputation { self.add_flags(TypeFlags::STILL_FURTHER_SPECIALIZABLE); } - ty::Generator(_, substs, _) => { - let substs = substs.as_generator(); + ty::Generator(_, args, _) => { + let args = args.as_generator(); let should_remove_further_specializable = !self.flags.contains(TypeFlags::STILL_FURTHER_SPECIALIZABLE); - self.add_substs(substs.parent_substs()); + self.add_args(args.parent_args()); if should_remove_further_specializable { self.flags -= TypeFlags::STILL_FURTHER_SPECIALIZABLE; } - self.add_ty(substs.resume_ty()); - self.add_ty(substs.return_ty()); - self.add_ty(substs.witness()); - self.add_ty(substs.yield_ty()); - self.add_ty(substs.tupled_upvars_ty()); + self.add_ty(args.resume_ty()); + self.add_ty(args.return_ty()); + self.add_ty(args.witness()); + self.add_ty(args.yield_ty()); + self.add_ty(args.tupled_upvars_ty()); } &ty::GeneratorWitness(ts) => { self.bound_computation(ts, |flags, ts| flags.add_tys(ts)); } - ty::GeneratorWitnessMIR(_, substs) => { + ty::GeneratorWitnessMIR(_, args) => { let should_remove_further_specializable = !self.flags.contains(TypeFlags::STILL_FURTHER_SPECIALIZABLE); - self.add_substs(substs); + self.add_args(args); if should_remove_further_specializable { self.flags -= TypeFlags::STILL_FURTHER_SPECIALIZABLE; } self.add_flags(TypeFlags::HAS_TY_GENERATOR); } - &ty::Closure(_, substs) => { - let substs = substs.as_closure(); + &ty::Closure(_, args) => { + let args = args.as_closure(); let should_remove_further_specializable = !self.flags.contains(TypeFlags::STILL_FURTHER_SPECIALIZABLE); - self.add_substs(substs.parent_substs()); + self.add_args(args.parent_args()); if should_remove_further_specializable { self.flags -= TypeFlags::STILL_FURTHER_SPECIALIZABLE; } - self.add_ty(substs.sig_as_fn_ptr_ty()); - self.add_ty(substs.kind_ty()); - self.add_ty(substs.tupled_upvars_ty()); + self.add_ty(args.sig_as_fn_ptr_ty()); + self.add_ty(args.kind_ty()); + self.add_ty(args.tupled_upvars_ty()); } &ty::Bound(debruijn, _) => { @@ -172,8 +172,8 @@ impl FlagComputation { } } - &ty::Adt(_, substs) => { - self.add_substs(substs); + &ty::Adt(_, args) => { + self.add_args(args); } &ty::Alias(kind, data) => { @@ -189,7 +189,7 @@ impl FlagComputation { &ty::Dynamic(obj, r, _) => { for predicate in obj.iter() { self.bound_computation(predicate, |computation, predicate| match predicate { - ty::ExistentialPredicate::Trait(tr) => computation.add_substs(tr.substs), + ty::ExistentialPredicate::Trait(tr) => computation.add_args(tr.args), ty::ExistentialPredicate::Projection(p) => { computation.add_existential_projection(&p); } @@ -220,8 +220,8 @@ impl FlagComputation { self.add_tys(types); } - &ty::FnDef(_, substs) => { - self.add_substs(substs); + &ty::FnDef(_, args) => { + self.add_args(args); } &ty::FnPtr(fn_sig) => self.bound_computation(fn_sig, |computation, fn_sig| { @@ -238,7 +238,7 @@ impl FlagComputation { fn add_predicate_atom(&mut self, atom: ty::PredicateKind<'_>) { match atom { ty::PredicateKind::Clause(ty::ClauseKind::Trait(trait_pred)) => { - self.add_substs(trait_pred.trait_ref.substs); + self.add_args(trait_pred.trait_ref.args); } ty::PredicateKind::Clause(ty::ClauseKind::RegionOutlives(ty::OutlivesPredicate( a, @@ -274,11 +274,11 @@ impl FlagComputation { self.add_term(term); } ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(arg)) => { - self.add_substs(slice::from_ref(&arg)); + self.add_args(slice::from_ref(&arg)); } ty::PredicateKind::ObjectSafe(_def_id) => {} - ty::PredicateKind::ClosureKind(_def_id, substs, _kind) => { - self.add_substs(substs); + ty::PredicateKind::ClosureKind(_def_id, args, _kind) => { + self.add_args(args); } ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(uv)) => { self.add_const(uv); @@ -317,7 +317,7 @@ impl FlagComputation { self.add_ty(c.ty()); match c.kind() { ty::ConstKind::Unevaluated(uv) => { - self.add_substs(uv.substs); + self.add_args(uv.args); self.add_flags(TypeFlags::HAS_CT_PROJECTION); } ty::ConstKind::Infer(infer) => { @@ -365,7 +365,7 @@ impl FlagComputation { } fn add_existential_projection(&mut self, projection: &ty::ExistentialProjection<'_>) { - self.add_substs(projection.substs); + self.add_args(projection.args); match projection.term.unpack() { ty::TermKind::Ty(ty) => self.add_ty(ty), ty::TermKind::Const(ct) => self.add_const(ct), @@ -373,11 +373,11 @@ impl FlagComputation { } fn add_alias_ty(&mut self, alias_ty: ty::AliasTy<'_>) { - self.add_substs(alias_ty.substs); + self.add_args(alias_ty.args); } - fn add_substs(&mut self, substs: &[GenericArg<'_>]) { - for kind in substs { + fn add_args(&mut self, args: &[GenericArg<'_>]) { + for kind in args { match kind.unpack() { GenericArgKind::Type(ty) => self.add_ty(ty), GenericArgKind::Lifetime(lt) => self.add_region(lt), diff --git a/compiler/rustc_middle/src/ty/subst.rs b/compiler/rustc_middle/src/ty/generic_args.rs index 4d5f5b8658c..12af8456494 100644 --- a/compiler/rustc_middle/src/ty/subst.rs +++ b/compiler/rustc_middle/src/ty/generic_args.rs @@ -1,8 +1,8 @@ -// Type substitutions. +// Generic arguments. use crate::ty::codec::{TyDecoder, TyEncoder}; use crate::ty::fold::{FallibleTypeFolder, TypeFoldable, TypeFolder, TypeSuperFoldable}; -use crate::ty::sty::{ClosureSubsts, GeneratorSubsts, InlineConstSubsts}; +use crate::ty::sty::{ClosureArgs, GeneratorArgs, InlineConstArgs}; use crate::ty::visit::{TypeVisitable, TypeVisitableExt, TypeVisitor}; use crate::ty::{self, Lift, List, ParamConst, Ty, TyCtxt}; @@ -17,7 +17,6 @@ use smallvec::SmallVec; use core::intrinsics; use std::cmp::Ordering; -use std::fmt; use std::marker::PhantomData; use std::mem; use std::num::NonZeroUsize; @@ -80,16 +79,6 @@ impl<'tcx> GenericArgKind<'tcx> { } } -impl<'tcx> fmt::Debug for GenericArg<'tcx> { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self.unpack() { - GenericArgKind::Lifetime(lt) => lt.fmt(f), - GenericArgKind::Type(ty) => ty.fmt(f), - GenericArgKind::Const(ct) => ct.fmt(f), - } - } -} - impl<'tcx> Ord for GenericArg<'tcx> { fn cmp(&self, other: &GenericArg<'tcx>) -> Ordering { self.unpack().cmp(&other.unpack()) @@ -185,7 +174,7 @@ impl<'tcx> GenericArg<'tcx> { } /// Unpack the `GenericArg` as a type when it is known certainly to be a type. - /// This is true in cases where `Substs` is used in places where the kinds are known + /// This is true in cases where `GenericArgs` is used in places where the kinds are known /// to be limited (e.g. in tuples, where the only parameters are type parameters). pub fn expect_ty(self) -> Ty<'tcx> { self.as_type().unwrap_or_else(|| bug!("expected a type, but found another kind")) @@ -252,13 +241,13 @@ impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for GenericArg<'tcx> { } } -/// List of generic arguments that are gonna be used to substitute generic parameters. -pub type InternalSubsts<'tcx> = List<GenericArg<'tcx>>; +/// List of generic arguments that are gonna be used to replace generic parameters. +pub type GenericArgs<'tcx> = List<GenericArg<'tcx>>; -pub type SubstsRef<'tcx> = &'tcx InternalSubsts<'tcx>; +pub type GenericArgsRef<'tcx> = &'tcx GenericArgs<'tcx>; -impl<'tcx> InternalSubsts<'tcx> { - /// Converts substs to a type list. +impl<'tcx> GenericArgs<'tcx> { + /// Converts generic args to a type list. /// /// # Panics /// @@ -266,66 +255,71 @@ impl<'tcx> InternalSubsts<'tcx> { pub fn into_type_list(&self, tcx: TyCtxt<'tcx>) -> &'tcx List<Ty<'tcx>> { tcx.mk_type_list_from_iter(self.iter().map(|arg| match arg.unpack() { GenericArgKind::Type(ty) => ty, - _ => bug!("`into_type_list` called on substs with non-types"), + _ => bug!("`into_type_list` called on generic arg with non-types"), })) } - /// Interpret these substitutions as the substitutions of a closure type. - /// Closure substitutions have a particular structure controlled by the + /// Interpret these generic args as the args of a closure type. + /// Closure args have a particular structure controlled by the /// compiler that encodes information like the signature and closure kind; - /// see `ty::ClosureSubsts` struct for more comments. - pub fn as_closure(&'tcx self) -> ClosureSubsts<'tcx> { - ClosureSubsts { substs: self } + /// see `ty::ClosureArgs` struct for more comments. + pub fn as_closure(&'tcx self) -> ClosureArgs<'tcx> { + ClosureArgs { args: self } } - /// Interpret these substitutions as the substitutions of a generator type. - /// Generator substitutions have a particular structure controlled by the + /// Interpret these generic args as the args of a generator type. + /// Generator args have a particular structure controlled by the /// compiler that encodes information like the signature and generator kind; - /// see `ty::GeneratorSubsts` struct for more comments. - pub fn as_generator(&'tcx self) -> GeneratorSubsts<'tcx> { - GeneratorSubsts { substs: self } + /// see `ty::GeneratorArgs` struct for more comments. + pub fn as_generator(&'tcx self) -> GeneratorArgs<'tcx> { + GeneratorArgs { args: self } } - /// Interpret these substitutions as the substitutions of an inline const. - /// Inline const substitutions have a particular structure controlled by the + /// Interpret these generic args as the args of an inline const. + /// Inline const args have a particular structure controlled by the /// compiler that encodes information like the inferred type; - /// see `ty::InlineConstSubsts` struct for more comments. - pub fn as_inline_const(&'tcx self) -> InlineConstSubsts<'tcx> { - InlineConstSubsts { substs: self } + /// see `ty::InlineConstArgs` struct for more comments. + pub fn as_inline_const(&'tcx self) -> InlineConstArgs<'tcx> { + InlineConstArgs { args: self } } - /// Creates an `InternalSubsts` that maps each generic parameter to itself. - pub fn identity_for_item(tcx: TyCtxt<'tcx>, def_id: impl Into<DefId>) -> SubstsRef<'tcx> { + /// Creates an `GenericArgs` that maps each generic parameter to itself. + pub fn identity_for_item(tcx: TyCtxt<'tcx>, def_id: impl Into<DefId>) -> GenericArgsRef<'tcx> { Self::for_item(tcx, def_id.into(), |param, _| tcx.mk_param_from_def(param)) } - /// Creates an `InternalSubsts` for generic parameter definitions, + /// Creates an `GenericArgs` for generic parameter definitions, /// by calling closures to obtain each kind. - /// The closures get to observe the `InternalSubsts` as they're + /// The closures get to observe the `GenericArgs` as they're /// being built, which can be used to correctly - /// substitute defaults of generic parameters. - pub fn for_item<F>(tcx: TyCtxt<'tcx>, def_id: DefId, mut mk_kind: F) -> SubstsRef<'tcx> + /// replace defaults of generic parameters. + pub fn for_item<F>(tcx: TyCtxt<'tcx>, def_id: DefId, mut mk_kind: F) -> GenericArgsRef<'tcx> where F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>, { let defs = tcx.generics_of(def_id); let count = defs.count(); - let mut substs = SmallVec::with_capacity(count); - Self::fill_item(&mut substs, tcx, defs, &mut mk_kind); - tcx.mk_substs(&substs) + let mut args = SmallVec::with_capacity(count); + Self::fill_item(&mut args, tcx, defs, &mut mk_kind); + tcx.mk_args(&args) } - pub fn extend_to<F>(&self, tcx: TyCtxt<'tcx>, def_id: DefId, mut mk_kind: F) -> SubstsRef<'tcx> + pub fn extend_to<F>( + &self, + tcx: TyCtxt<'tcx>, + def_id: DefId, + mut mk_kind: F, + ) -> GenericArgsRef<'tcx> where F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>, { - Self::for_item(tcx, def_id, |param, substs| { - self.get(param.index as usize).cloned().unwrap_or_else(|| mk_kind(param, substs)) + Self::for_item(tcx, def_id, |param, args| { + self.get(param.index as usize).cloned().unwrap_or_else(|| mk_kind(param, args)) }) } pub fn fill_item<F>( - substs: &mut SmallVec<[GenericArg<'tcx>; 8]>, + args: &mut SmallVec<[GenericArg<'tcx>; 8]>, tcx: TyCtxt<'tcx>, defs: &ty::Generics, mk_kind: &mut F, @@ -334,38 +328,38 @@ impl<'tcx> InternalSubsts<'tcx> { { if let Some(def_id) = defs.parent { let parent_defs = tcx.generics_of(def_id); - Self::fill_item(substs, tcx, parent_defs, mk_kind); + Self::fill_item(args, tcx, parent_defs, mk_kind); } - Self::fill_single(substs, defs, mk_kind) + Self::fill_single(args, defs, mk_kind) } pub fn fill_single<F>( - substs: &mut SmallVec<[GenericArg<'tcx>; 8]>, + args: &mut SmallVec<[GenericArg<'tcx>; 8]>, defs: &ty::Generics, mk_kind: &mut F, ) where F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>, { - substs.reserve(defs.params.len()); + args.reserve(defs.params.len()); for param in &defs.params { - let kind = mk_kind(param, substs); - assert_eq!(param.index as usize, substs.len(), "{substs:#?}, {defs:#?}"); - substs.push(kind); + let kind = mk_kind(param, args); + assert_eq!(param.index as usize, args.len(), "{args:#?}, {defs:#?}"); + args.push(kind); } } - // Extend an `original_substs` list to the full number of substs expected by `def_id`, + // Extend an `original_args` list to the full number of args expected by `def_id`, // filling in the missing parameters with error ty/ct or 'static regions. pub fn extend_with_error( tcx: TyCtxt<'tcx>, def_id: DefId, - original_substs: &[GenericArg<'tcx>], - ) -> SubstsRef<'tcx> { - ty::InternalSubsts::for_item(tcx, def_id, |def, substs| { - if let Some(subst) = original_substs.get(def.index as usize) { - *subst + original_args: &[GenericArg<'tcx>], + ) -> GenericArgsRef<'tcx> { + ty::GenericArgs::for_item(tcx, def_id, |def, args| { + if let Some(arg) = original_args.get(def.index as usize) { + *arg } else { - def.to_error(tcx, substs) + def.to_error(tcx, args) } }) } @@ -421,9 +415,9 @@ impl<'tcx> InternalSubsts<'tcx> { self.type_at(def.index as usize).into() } - /// Transform from substitutions for a child of `source_ancestor` - /// (e.g., a trait or impl) to substitutions for the same child - /// in a different item, with `target_substs` as the base for + /// Transform from generic args for a child of `source_ancestor` + /// (e.g., a trait or impl) to args for the same child + /// in a different item, with `target_args` as the base for /// the target impl/trait, with the source child-specific /// parameters (e.g., method parameters) on top of that base. /// @@ -434,23 +428,23 @@ impl<'tcx> InternalSubsts<'tcx> { /// impl<U> X<U> for U { fn f<V>() {} } /// ``` /// - /// * If `self` is `[Self, S, T]`: the identity substs of `f` in the trait. + /// * If `self` is `[Self, S, T]`: the identity args of `f` in the trait. /// * If `source_ancestor` is the def_id of the trait. - /// * If `target_substs` is `[U]`, the substs for the impl. - /// * Then we will return `[U, T]`, the subst for `f` in the impl that + /// * If `target_args` is `[U]`, the args for the impl. + /// * Then we will return `[U, T]`, the arg for `f` in the impl that /// are needed for it to match the trait. pub fn rebase_onto( &self, tcx: TyCtxt<'tcx>, source_ancestor: DefId, - target_substs: SubstsRef<'tcx>, - ) -> SubstsRef<'tcx> { + target_args: GenericArgsRef<'tcx>, + ) -> GenericArgsRef<'tcx> { let defs = tcx.generics_of(source_ancestor); - tcx.mk_substs_from_iter(target_substs.iter().chain(self.iter().skip(defs.params.len()))) + tcx.mk_args_from_iter(target_args.iter().chain(self.iter().skip(defs.params.len()))) } - pub fn truncate_to(&self, tcx: TyCtxt<'tcx>, generics: &ty::Generics) -> SubstsRef<'tcx> { - tcx.mk_substs_from_iter(self.iter().take(generics.count())) + pub fn truncate_to(&self, tcx: TyCtxt<'tcx>, generics: &ty::Generics) -> GenericArgsRef<'tcx> { + tcx.mk_args_from_iter(self.iter().take(generics.count())) } pub fn host_effect_param(&'tcx self) -> Option<ty::Const<'tcx>> { @@ -458,7 +452,7 @@ impl<'tcx> InternalSubsts<'tcx> { } } -impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for SubstsRef<'tcx> { +impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for GenericArgsRef<'tcx> { fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>( self, folder: &mut F, @@ -467,16 +461,12 @@ impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for SubstsRef<'tcx> { // 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 // typically hit in 90--99.99% of cases. When folding doesn't change - // the substs, it's faster to reuse the existing substs rather than - // calling `mk_substs`. + // the args, it's faster to reuse the existing args rather than + // calling `mk_args`. match self.len() { 1 => { let param0 = self[0].try_fold_with(folder)?; - if param0 == self[0] { - Ok(self) - } else { - Ok(folder.interner().mk_substs(&[param0])) - } + if param0 == self[0] { Ok(self) } else { Ok(folder.interner().mk_args(&[param0])) } } 2 => { let param0 = self[0].try_fold_with(folder)?; @@ -484,11 +474,11 @@ impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for SubstsRef<'tcx> { if param0 == self[0] && param1 == self[1] { Ok(self) } else { - Ok(folder.interner().mk_substs(&[param0, param1])) + Ok(folder.interner().mk_args(&[param0, param1])) } } 0 => Ok(self), - _ => ty::util::fold_list(self, folder, |tcx, v| tcx.mk_substs(v)), + _ => ty::util::fold_list(self, folder, |tcx, v| tcx.mk_args(v)), } } } @@ -498,7 +488,7 @@ impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for &'tcx ty::List<Ty<'tcx>> { self, folder: &mut F, ) -> Result<Self, F::Error> { - // This code is fairly hot, though not as hot as `SubstsRef`. + // This code is fairly hot, though not as hot as `GenericArgsRef`. // // When compiling stage 2, I get the following results: // @@ -536,18 +526,18 @@ impl<'tcx, T: TypeVisitable<TyCtxt<'tcx>>> TypeVisitable<TyCtxt<'tcx>> for &'tcx } /// Similar to [`super::Binder`] except that it tracks early bound generics, i.e. `struct Foo<T>(T)` -/// needs `T` substituted immediately. This type primarily exists to avoid forgetting to call -/// `subst`. +/// needs `T` instantiated immediately. This type primarily exists to avoid forgetting to call +/// `instantiate`. /// -/// If you don't have anything to `subst`, you may be looking for -/// [`subst_identity`](EarlyBinder::subst_identity) or [`skip_binder`](EarlyBinder::skip_binder). +/// If you don't have anything to `instantiate`, you may be looking for +/// [`instantiate_identity`](EarlyBinder::instantiate_identity) or [`skip_binder`](EarlyBinder::skip_binder). #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] #[derive(Encodable, Decodable, HashStable)] pub struct EarlyBinder<T> { value: T, } -/// For early binders, you should first call `subst` before using any visitors. +/// For early binders, you should first call `instantiate` before using any visitors. impl<'tcx, T> !TypeFoldable<TyCtxt<'tcx>> for ty::EarlyBinder<T> {} impl<'tcx, T> !TypeVisitable<TyCtxt<'tcx>> for ty::EarlyBinder<T> {} @@ -591,7 +581,7 @@ impl<T> EarlyBinder<T> { /// This can be used to extract data that does not depend on generic parameters /// (e.g., getting the `DefId` of the inner value or getting the number of /// arguments of an `FnSig`). Otherwise, consider using - /// [`subst_identity`](EarlyBinder::subst_identity). + /// [`instantiate_identity`](EarlyBinder::instantiate_identity). /// /// To skip the binder on `x: &EarlyBinder<T>` to obtain `&T`, leverage /// [`EarlyBinder::as_ref`](EarlyBinder::as_ref): `x.as_ref().skip_binder()`. @@ -620,35 +610,31 @@ impl<'tcx, 's, I: IntoIterator> EarlyBinder<I> where I::Item: TypeFoldable<TyCtxt<'tcx>>, { - pub fn subst_iter( - self, - tcx: TyCtxt<'tcx>, - substs: &'s [GenericArg<'tcx>], - ) -> SubstIter<'s, 'tcx, I> { - SubstIter { it: self.value.into_iter(), tcx, substs } + pub fn arg_iter(self, tcx: TyCtxt<'tcx>, args: &'s [GenericArg<'tcx>]) -> ArgIter<'s, 'tcx, I> { + ArgIter { it: self.value.into_iter(), tcx, args } } - /// Similar to [`subst_identity`](EarlyBinder::subst_identity), + /// Similar to [`instantiate_identity`](EarlyBinder::instantiate_identity), /// but on an iterator of `TypeFoldable` values. - pub fn subst_identity_iter(self) -> I::IntoIter { + pub fn instantiate_identity_iter(self) -> I::IntoIter { self.value.into_iter() } } -pub struct SubstIter<'s, 'tcx, I: IntoIterator> { +pub struct ArgIter<'s, 'tcx, I: IntoIterator> { it: I::IntoIter, tcx: TyCtxt<'tcx>, - substs: &'s [GenericArg<'tcx>], + args: &'s [GenericArg<'tcx>], } -impl<'tcx, I: IntoIterator> Iterator for SubstIter<'_, 'tcx, I> +impl<'tcx, I: IntoIterator> Iterator for ArgIter<'_, 'tcx, I> where I::Item: TypeFoldable<TyCtxt<'tcx>>, { type Item = I::Item; fn next(&mut self) -> Option<Self::Item> { - Some(EarlyBinder { value: self.it.next()? }.subst(self.tcx, self.substs)) + Some(EarlyBinder { value: self.it.next()? }.instantiate(self.tcx, self.args)) } fn size_hint(&self) -> (usize, Option<usize>) { @@ -656,17 +642,17 @@ where } } -impl<'tcx, I: IntoIterator> DoubleEndedIterator for SubstIter<'_, 'tcx, I> +impl<'tcx, I: IntoIterator> DoubleEndedIterator for ArgIter<'_, 'tcx, I> where I::IntoIter: DoubleEndedIterator, I::Item: TypeFoldable<TyCtxt<'tcx>>, { fn next_back(&mut self) -> Option<Self::Item> { - Some(EarlyBinder { value: self.it.next_back()? }.subst(self.tcx, self.substs)) + Some(EarlyBinder { value: self.it.next_back()? }.instantiate(self.tcx, self.args)) } } -impl<'tcx, I: IntoIterator> ExactSizeIterator for SubstIter<'_, 'tcx, I> +impl<'tcx, I: IntoIterator> ExactSizeIterator for ArgIter<'_, 'tcx, I> where I::IntoIter: ExactSizeIterator, I::Item: TypeFoldable<TyCtxt<'tcx>>, @@ -678,28 +664,30 @@ where I::Item: Deref, <I::Item as Deref>::Target: Copy + TypeFoldable<TyCtxt<'tcx>>, { - pub fn subst_iter_copied( + pub fn arg_iter_copied( self, tcx: TyCtxt<'tcx>, - substs: &'s [GenericArg<'tcx>], - ) -> SubstIterCopied<'s, 'tcx, I> { - SubstIterCopied { it: self.value.into_iter(), tcx, substs } + args: &'s [GenericArg<'tcx>], + ) -> ArgIterCopied<'s, 'tcx, I> { + ArgIterCopied { it: self.value.into_iter(), tcx, args } } - /// Similar to [`subst_identity`](EarlyBinder::subst_identity), + /// Similar to [`instantiate_identity`](EarlyBinder::instantiate_identity), /// but on an iterator of values that deref to a `TypeFoldable`. - pub fn subst_identity_iter_copied(self) -> impl Iterator<Item = <I::Item as Deref>::Target> { + pub fn instantiate_identity_iter_copied( + self, + ) -> impl Iterator<Item = <I::Item as Deref>::Target> { self.value.into_iter().map(|v| *v) } } -pub struct SubstIterCopied<'a, 'tcx, I: IntoIterator> { +pub struct ArgIterCopied<'a, 'tcx, I: IntoIterator> { it: I::IntoIter, tcx: TyCtxt<'tcx>, - substs: &'a [GenericArg<'tcx>], + args: &'a [GenericArg<'tcx>], } -impl<'tcx, I: IntoIterator> Iterator for SubstIterCopied<'_, 'tcx, I> +impl<'tcx, I: IntoIterator> Iterator for ArgIterCopied<'_, 'tcx, I> where I::Item: Deref, <I::Item as Deref>::Target: Copy + TypeFoldable<TyCtxt<'tcx>>, @@ -707,7 +695,7 @@ where type Item = <I::Item as Deref>::Target; fn next(&mut self) -> Option<Self::Item> { - self.it.next().map(|value| EarlyBinder { value: *value }.subst(self.tcx, self.substs)) + self.it.next().map(|value| EarlyBinder { value: *value }.instantiate(self.tcx, self.args)) } fn size_hint(&self) -> (usize, Option<usize>) { @@ -715,18 +703,20 @@ where } } -impl<'tcx, I: IntoIterator> DoubleEndedIterator for SubstIterCopied<'_, 'tcx, I> +impl<'tcx, I: IntoIterator> DoubleEndedIterator for ArgIterCopied<'_, 'tcx, I> where I::IntoIter: DoubleEndedIterator, I::Item: Deref, <I::Item as Deref>::Target: Copy + TypeFoldable<TyCtxt<'tcx>>, { fn next_back(&mut self) -> Option<Self::Item> { - self.it.next_back().map(|value| EarlyBinder { value: *value }.subst(self.tcx, self.substs)) + self.it + .next_back() + .map(|value| EarlyBinder { value: *value }.instantiate(self.tcx, self.args)) } } -impl<'tcx, I: IntoIterator> ExactSizeIterator for SubstIterCopied<'_, 'tcx, I> +impl<'tcx, I: IntoIterator> ExactSizeIterator for ArgIterCopied<'_, 'tcx, I> where I::IntoIter: ExactSizeIterator, I::Item: Deref, @@ -757,20 +747,20 @@ impl<T: Iterator> Iterator for EarlyBinderIter<T> { } impl<'tcx, T: TypeFoldable<TyCtxt<'tcx>>> ty::EarlyBinder<T> { - pub fn subst(self, tcx: TyCtxt<'tcx>, substs: &[GenericArg<'tcx>]) -> T { - let mut folder = SubstFolder { tcx, substs, binders_passed: 0 }; + pub fn instantiate(self, tcx: TyCtxt<'tcx>, args: &[GenericArg<'tcx>]) -> T { + let mut folder = ArgFolder { tcx, args, binders_passed: 0 }; self.value.fold_with(&mut folder) } - /// Makes the identity substitution `T0 => T0, ..., TN => TN`. + /// Makes the identity replacement `T0 => T0, ..., TN => TN`. /// Conceptually, this converts universally bound variables into placeholders /// when inside of a given item. /// /// For example, consider `for<T> fn foo<T>(){ .. }`: /// - Outside of `foo`, `T` is bound (represented by the presence of `EarlyBinder`). /// - Inside of the body of `foo`, we treat `T` as a placeholder by calling - /// `subst_identity` to discharge the `EarlyBinder`. - pub fn subst_identity(self) -> T { + /// `instantiate_identity` to discharge the `EarlyBinder`. + pub fn instantiate_identity(self) -> T { self.value } @@ -783,15 +773,15 @@ impl<'tcx, T: TypeFoldable<TyCtxt<'tcx>>> ty::EarlyBinder<T> { /////////////////////////////////////////////////////////////////////////// // The actual substitution engine itself is a type folder. -struct SubstFolder<'a, 'tcx> { +struct ArgFolder<'a, 'tcx> { tcx: TyCtxt<'tcx>, - substs: &'a [GenericArg<'tcx>], + args: &'a [GenericArg<'tcx>], /// Number of region binders we have passed through while doing the substitution binders_passed: u32, } -impl<'a, 'tcx> TypeFolder<TyCtxt<'tcx>> for SubstFolder<'a, 'tcx> { +impl<'a, 'tcx> TypeFolder<TyCtxt<'tcx>> for ArgFolder<'a, 'tcx> { #[inline] fn interner(&self) -> TyCtxt<'tcx> { self.tcx @@ -810,12 +800,12 @@ impl<'a, 'tcx> TypeFolder<TyCtxt<'tcx>> for SubstFolder<'a, 'tcx> { fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> { #[cold] #[inline(never)] - fn region_param_out_of_range(data: ty::EarlyBoundRegion, substs: &[GenericArg<'_>]) -> ! { + fn region_param_out_of_range(data: ty::EarlyBoundRegion, args: &[GenericArg<'_>]) -> ! { bug!( - "Region parameter out of range when substituting in region {} (index={}, substs = {:?})", + "Region parameter out of range when substituting in region {} (index={}, args = {:?})", data.name, data.index, - substs, + args, ) } @@ -837,11 +827,11 @@ impl<'a, 'tcx> TypeFolder<TyCtxt<'tcx>> for SubstFolder<'a, 'tcx> { // the specialized routine `ty::replace_late_regions()`. match *r { ty::ReEarlyBound(data) => { - let rk = self.substs.get(data.index as usize).map(|k| k.unpack()); + let rk = self.args.get(data.index as usize).map(|k| k.unpack()); match rk { Some(GenericArgKind::Lifetime(lt)) => self.shift_region_through_binders(lt), Some(other) => region_param_invalid(data, other), - None => region_param_out_of_range(data, self.substs), + None => region_param_out_of_range(data, self.args), } } ty::ReLateBound(..) @@ -874,10 +864,10 @@ impl<'a, 'tcx> TypeFolder<TyCtxt<'tcx>> for SubstFolder<'a, 'tcx> { } } -impl<'a, 'tcx> SubstFolder<'a, 'tcx> { +impl<'a, 'tcx> ArgFolder<'a, 'tcx> { fn ty_for_param(&self, p: ty::ParamTy, source_ty: Ty<'tcx>) -> Ty<'tcx> { - // Look up the type in the substitutions. It really should be in there. - let opt_ty = self.substs.get(p.index as usize).map(|k| k.unpack()); + // Look up the type in the args. It really should be in there. + let opt_ty = self.args.get(p.index as usize).map(|k| k.unpack()); let ty = match opt_ty { Some(GenericArgKind::Type(ty)) => ty, Some(kind) => self.type_param_expected(p, source_ty, kind), @@ -891,12 +881,12 @@ impl<'a, 'tcx> SubstFolder<'a, 'tcx> { #[inline(never)] fn type_param_expected(&self, p: ty::ParamTy, ty: Ty<'tcx>, kind: GenericArgKind<'tcx>) -> ! { bug!( - "expected type for `{:?}` ({:?}/{}) but found {:?} when substituting, substs={:?}", + "expected type for `{:?}` ({:?}/{}) but found {:?} when substituting, args={:?}", p, ty, p.index, kind, - self.substs, + self.args, ) } @@ -904,17 +894,17 @@ impl<'a, 'tcx> SubstFolder<'a, 'tcx> { #[inline(never)] fn type_param_out_of_range(&self, p: ty::ParamTy, ty: Ty<'tcx>) -> ! { bug!( - "type parameter `{:?}` ({:?}/{}) out of range when substituting, substs={:?}", + "type parameter `{:?}` ({:?}/{}) out of range when substituting, args={:?}", p, ty, p.index, - self.substs, + self.args, ) } fn const_for_param(&self, p: ParamConst, source_ct: ty::Const<'tcx>) -> ty::Const<'tcx> { - // Look up the const in the substitutions. It really should be in there. - let opt_ct = self.substs.get(p.index as usize).map(|k| k.unpack()); + // Look up the const in the args. It really should be in there. + let opt_ct = self.args.get(p.index as usize).map(|k| k.unpack()); let ct = match opt_ct { Some(GenericArgKind::Const(ct)) => ct, Some(kind) => self.const_param_expected(p, source_ct, kind), @@ -933,12 +923,12 @@ impl<'a, 'tcx> SubstFolder<'a, 'tcx> { kind: GenericArgKind<'tcx>, ) -> ! { bug!( - "expected const for `{:?}` ({:?}/{}) but found {:?} when substituting substs={:?}", + "expected const for `{:?}` ({:?}/{}) but found {:?} when substituting args={:?}", p, ct, p.index, kind, - self.substs, + self.args, ) } @@ -946,11 +936,11 @@ impl<'a, 'tcx> SubstFolder<'a, 'tcx> { #[inline(never)] fn const_param_out_of_range(&self, p: ty::ParamConst, ct: ty::Const<'tcx>) -> ! { bug!( - "const parameter `{:?}` ({:?}/{}) out of range when substituting substs={:?}", + "const parameter `{:?}` ({:?}/{}) out of range when substituting args={:?}", p, ct, p.index, - self.substs, + self.args, ) } @@ -1022,13 +1012,13 @@ impl<'a, 'tcx> SubstFolder<'a, 'tcx> { } } -/// Stores the user-given substs to reach some fully qualified path +/// Stores the user-given args to reach some fully qualified path /// (e.g., `<T>::Item` or `<T as Trait>::Item`). #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TyEncodable, TyDecodable)] #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)] -pub struct UserSubsts<'tcx> { - /// The substitutions for the item as given by the user. - pub substs: SubstsRef<'tcx>, +pub struct UserArgs<'tcx> { + /// The args for the item as given by the user. + pub args: GenericArgsRef<'tcx>, /// The self type, in the case of a `<T>::Item` path (when applied /// to an inherent impl). See `UserSelfTy` below. @@ -1048,7 +1038,7 @@ pub struct UserSubsts<'tcx> { /// when you then have a path like `<Foo<&'static u32>>::method`, /// this struct would carry the `DefId` of the impl along with the /// self type `Foo<u32>`. Then we can instantiate the parameters of -/// the impl (with the substs from `UserSubsts`) and apply those to +/// the impl (with the args from `UserArgs`) and apply those to /// the self type, giving `Foo<?A>`. Finally, we unify that with /// the self type here, which contains `?A` to be `&'static u32` #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TyEncodable, TyDecodable)] diff --git a/compiler/rustc_middle/src/ty/generics.rs b/compiler/rustc_middle/src/ty/generics.rs index 6c7125c4cb7..338590717d0 100644 --- a/compiler/rustc_middle/src/ty/generics.rs +++ b/compiler/rustc_middle/src/ty/generics.rs @@ -1,5 +1,5 @@ use crate::ty; -use crate::ty::{EarlyBinder, SubstsRef}; +use crate::ty::{EarlyBinder, GenericArgsRef}; use rustc_ast as ast; use rustc_data_structures::fx::FxHashMap; use rustc_hir::def_id::DefId; @@ -97,14 +97,14 @@ impl GenericParamDef { pub fn to_error<'tcx>( &self, tcx: TyCtxt<'tcx>, - preceding_substs: &[ty::GenericArg<'tcx>], + preceding_args: &[ty::GenericArg<'tcx>], ) -> ty::GenericArg<'tcx> { match &self.kind { ty::GenericParamDefKind::Lifetime => ty::Region::new_error_misc(tcx).into(), ty::GenericParamDefKind::Type { .. } => Ty::new_misc_error(tcx).into(), ty::GenericParamDefKind::Const { .. } => ty::Const::new_misc_error( tcx, - tcx.type_of(self.def_id).subst(tcx, preceding_substs), + tcx.type_of(self.def_id).instantiate(tcx, preceding_args), ) .into(), } @@ -136,7 +136,7 @@ pub struct Generics { pub has_self: bool, pub has_late_bound_regions: Option<Span>, - // The index of the host effect when substituted. (i.e. might be index to parent substs) + // The index of the host effect when substituted. (i.e. might be index to parent args) pub host_effect_index: Option<usize>, } @@ -278,14 +278,14 @@ impl<'tcx> Generics { }) } - /// Returns the substs corresponding to the generic parameters + /// Returns the args corresponding to the generic parameters /// of this item, excluding `Self`. /// /// **This should only be used for diagnostics purposes.** - pub fn own_substs_no_defaults( + pub fn own_args_no_defaults( &'tcx self, tcx: TyCtxt<'tcx>, - substs: &'tcx [ty::GenericArg<'tcx>], + args: &'tcx [ty::GenericArg<'tcx>], ) -> &'tcx [ty::GenericArg<'tcx>] { let mut own_params = self.parent_count..self.count(); if self.has_self && self.parent.is_none() { @@ -304,22 +304,22 @@ impl<'tcx> Generics { .rev() .take_while(|param| { param.default_value(tcx).is_some_and(|default| { - default.subst(tcx, substs) == substs[param.index as usize] + default.instantiate(tcx, args) == args[param.index as usize] }) }) .count(); - &substs[own_params] + &args[own_params] } - /// Returns the substs corresponding to the generic parameters of this item, excluding `Self`. + /// Returns the args corresponding to the generic parameters of this item, excluding `Self`. /// /// **This should only be used for diagnostics purposes.** - pub fn own_substs( + pub fn own_args( &'tcx self, - substs: &'tcx [ty::GenericArg<'tcx>], + args: &'tcx [ty::GenericArg<'tcx>], ) -> &'tcx [ty::GenericArg<'tcx>] { - let own = &substs[self.parent_count..][..self.params.len()]; + let own = &args[self.parent_count..][..self.params.len()]; if self.has_self && self.parent.is_none() { &own[1..] } else { &own } } } @@ -335,19 +335,19 @@ impl<'tcx> GenericPredicates<'tcx> { pub fn instantiate( &self, tcx: TyCtxt<'tcx>, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, ) -> InstantiatedPredicates<'tcx> { let mut instantiated = InstantiatedPredicates::empty(); - self.instantiate_into(tcx, &mut instantiated, substs); + self.instantiate_into(tcx, &mut instantiated, args); instantiated } pub fn instantiate_own( &self, tcx: TyCtxt<'tcx>, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, ) -> impl Iterator<Item = (Clause<'tcx>, Span)> + DoubleEndedIterator + ExactSizeIterator { - EarlyBinder::bind(self.predicates).subst_iter_copied(tcx, substs) + EarlyBinder::bind(self.predicates).arg_iter_copied(tcx, args) } #[instrument(level = "debug", skip(self, tcx))] @@ -355,14 +355,14 @@ impl<'tcx> GenericPredicates<'tcx> { &self, tcx: TyCtxt<'tcx>, instantiated: &mut InstantiatedPredicates<'tcx>, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, ) { if let Some(def_id) = self.parent { - tcx.predicates_of(def_id).instantiate_into(tcx, instantiated, substs); + tcx.predicates_of(def_id).instantiate_into(tcx, instantiated, args); } - instantiated - .predicates - .extend(self.predicates.iter().map(|(p, _)| EarlyBinder::bind(*p).subst(tcx, substs))); + instantiated.predicates.extend( + self.predicates.iter().map(|(p, _)| EarlyBinder::bind(*p).instantiate(tcx, args)), + ); instantiated.spans.extend(self.predicates.iter().map(|(_, sp)| *sp)); } diff --git a/compiler/rustc_middle/src/ty/impls_ty.rs b/compiler/rustc_middle/src/ty/impls_ty.rs index 02baa395c3c..b03874a90e8 100644 --- a/compiler/rustc_middle/src/ty/impls_ty.rs +++ b/compiler/rustc_middle/src/ty/impls_ty.rs @@ -67,7 +67,7 @@ impl<'a> ToStableHashKey<StableHashingContext<'a>> for SimplifiedType { } } -impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for ty::subst::GenericArg<'tcx> { +impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for ty::GenericArg<'tcx> { fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) { self.unpack().hash_stable(hcx, hasher); } diff --git a/compiler/rustc_middle/src/ty/inhabitedness/inhabited_predicate.rs b/compiler/rustc_middle/src/ty/inhabitedness/inhabited_predicate.rs index 295cb146461..f278cace99d 100644 --- a/compiler/rustc_middle/src/ty/inhabitedness/inhabited_predicate.rs +++ b/compiler/rustc_middle/src/ty/inhabitedness/inhabited_predicate.rs @@ -19,7 +19,7 @@ pub enum InhabitedPredicate<'tcx> { /// type has restricted visibility. NotInModule(DefId), /// Inhabited if some generic type is inhabited. - /// These are replaced by calling [`Self::subst`]. + /// These are replaced by calling [`Self::instantiate`]. GenericType(Ty<'tcx>), /// A AND B And(&'tcx [InhabitedPredicate<'tcx>; 2]), @@ -162,14 +162,14 @@ impl<'tcx> InhabitedPredicate<'tcx> { } /// Replaces generic types with its corresponding predicate - pub fn subst(self, tcx: TyCtxt<'tcx>, substs: ty::SubstsRef<'tcx>) -> Self { - self.subst_opt(tcx, substs).unwrap_or(self) + pub fn instantiate(self, tcx: TyCtxt<'tcx>, args: ty::GenericArgsRef<'tcx>) -> Self { + self.instantiate_opt(tcx, args).unwrap_or(self) } - fn subst_opt(self, tcx: TyCtxt<'tcx>, substs: ty::SubstsRef<'tcx>) -> Option<Self> { + fn instantiate_opt(self, tcx: TyCtxt<'tcx>, args: ty::GenericArgsRef<'tcx>) -> Option<Self> { match self { Self::ConstIsZero(c) => { - let c = ty::EarlyBinder::bind(c).subst(tcx, substs); + let c = ty::EarlyBinder::bind(c).instantiate(tcx, args); let pred = match c.try_to_target_usize(tcx) { Some(0) => Self::True, Some(1..) => Self::False, @@ -178,17 +178,17 @@ impl<'tcx> InhabitedPredicate<'tcx> { Some(pred) } Self::GenericType(t) => { - Some(ty::EarlyBinder::bind(t).subst(tcx, substs).inhabited_predicate(tcx)) + Some(ty::EarlyBinder::bind(t).instantiate(tcx, args).inhabited_predicate(tcx)) } - Self::And(&[a, b]) => match a.subst_opt(tcx, substs) { - None => b.subst_opt(tcx, substs).map(|b| a.and(tcx, b)), + Self::And(&[a, b]) => match a.instantiate_opt(tcx, args) { + None => b.instantiate_opt(tcx, args).map(|b| a.and(tcx, b)), Some(InhabitedPredicate::False) => Some(InhabitedPredicate::False), - Some(a) => Some(a.and(tcx, b.subst_opt(tcx, substs).unwrap_or(b))), + Some(a) => Some(a.and(tcx, b.instantiate_opt(tcx, args).unwrap_or(b))), }, - Self::Or(&[a, b]) => match a.subst_opt(tcx, substs) { - None => b.subst_opt(tcx, substs).map(|b| a.or(tcx, b)), + Self::Or(&[a, b]) => match a.instantiate_opt(tcx, args) { + None => b.instantiate_opt(tcx, args).map(|b| a.or(tcx, b)), Some(InhabitedPredicate::True) => Some(InhabitedPredicate::True), - Some(a) => Some(a.or(tcx, b.subst_opt(tcx, substs).unwrap_or(b))), + Some(a) => Some(a.or(tcx, b.instantiate_opt(tcx, args).unwrap_or(b))), }, _ => None, } diff --git a/compiler/rustc_middle/src/ty/inhabitedness/mod.rs b/compiler/rustc_middle/src/ty/inhabitedness/mod.rs index b92d84152b4..4dac6891b30 100644 --- a/compiler/rustc_middle/src/ty/inhabitedness/mod.rs +++ b/compiler/rustc_middle/src/ty/inhabitedness/mod.rs @@ -58,7 +58,7 @@ pub(crate) fn provide(providers: &mut Providers) { } /// Returns an `InhabitedPredicate` that is generic over type parameters and -/// requires calling [`InhabitedPredicate::subst`] +/// requires calling [`InhabitedPredicate::instantiate`] fn inhabited_predicate_adt(tcx: TyCtxt<'_>, def_id: DefId) -> InhabitedPredicate<'_> { if let Some(def_id) = def_id.as_local() { if matches!(tcx.representability(def_id), ty::Representability::Infinite) { @@ -87,7 +87,7 @@ impl<'tcx> VariantDef { InhabitedPredicate::all( tcx, self.fields.iter().map(|field| { - let pred = tcx.type_of(field.did).subst_identity().inhabited_predicate(tcx); + let pred = tcx.type_of(field.did).instantiate_identity().inhabited_predicate(tcx); if adt.is_enum() { return pred; } @@ -114,8 +114,8 @@ impl<'tcx> Ty<'tcx> { Never => InhabitedPredicate::False, Param(_) | Alias(ty::Projection, _) => InhabitedPredicate::GenericType(self), // FIXME(inherent_associated_types): Most likely we can just map to `GenericType` like above. - // However it's unclear if the substs passed to `InhabitedPredicate::subst` are of the correct - // format, i.e. don't contain parent substs. If you hit this case, please verify this beforehand. + // However it's unclear if the args passed to `InhabitedPredicate::instantiate` are of the correct + // format, i.e. don't contain parent args. If you hit this case, please verify this beforehand. Alias(ty::Inherent, _) => { bug!("unimplemented: inhabitedness checking for inherent projections") } @@ -189,7 +189,7 @@ impl<'tcx> Ty<'tcx> { /// N.B. this query should only be called through `Ty::inhabited_predicate` fn inhabited_predicate_type<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> InhabitedPredicate<'tcx> { match *ty.kind() { - Adt(adt, substs) => tcx.inhabited_predicate_adt(adt.did()).subst(tcx, substs), + Adt(adt, args) => tcx.inhabited_predicate_adt(adt.did()).instantiate(tcx, args), Tuple(tys) => { InhabitedPredicate::all(tcx, tys.iter().map(|ty| ty.inhabited_predicate(tcx))) diff --git a/compiler/rustc_middle/src/ty/instance.rs b/compiler/rustc_middle/src/ty/instance.rs index ae57e954ff4..48e88daa890 100644 --- a/compiler/rustc_middle/src/ty/instance.rs +++ b/compiler/rustc_middle/src/ty/instance.rs @@ -1,7 +1,7 @@ use crate::middle::codegen_fn_attrs::CodegenFnAttrFlags; use crate::ty::print::{FmtPrinter, Printer}; use crate::ty::{self, Ty, TyCtxt, TypeFoldable, TypeSuperFoldable}; -use crate::ty::{EarlyBinder, InternalSubsts, SubstsRef, TypeVisitableExt}; +use crate::ty::{EarlyBinder, GenericArgs, GenericArgsRef, TypeVisitableExt}; use rustc_errors::ErrorGuaranteed; use rustc_hir::def::Namespace; use rustc_hir::def_id::{CrateNum, DefId}; @@ -16,13 +16,13 @@ use std::fmt; /// A monomorphized `InstanceDef`. /// /// Monomorphization happens on-the-fly and no monomorphized MIR is ever created. Instead, this type -/// simply couples a potentially generic `InstanceDef` with some substs, and codegen and const eval +/// simply couples a potentially generic `InstanceDef` with some args, and codegen and const eval /// will do all required substitution as they run. #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, TyEncodable, TyDecodable)] #[derive(HashStable, Lift, TypeFoldable, TypeVisitable)] pub struct Instance<'tcx> { pub def: InstanceDef<'tcx>, - pub substs: SubstsRef<'tcx>, + pub args: GenericArgsRef<'tcx>, } #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] @@ -115,7 +115,7 @@ impl<'tcx> Instance<'tcx> { /// lifetimes erased, allowing a `ParamEnv` to be specified for use during normalization. pub fn ty(&self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> Ty<'tcx> { let ty = tcx.type_of(self.def.def_id()); - tcx.subst_and_normalize_erasing_regions(self.substs, param_env, ty) + tcx.subst_and_normalize_erasing_regions(self.args, param_env, ty) } /// Finds a crate that contains a monomorphization of this instance that @@ -139,13 +139,13 @@ impl<'tcx> Instance<'tcx> { } // If this a non-generic instance, it cannot be a shared monomorphization. - self.substs.non_erasable_generics().next()?; + self.args.non_erasable_generics().next()?; match self.def { InstanceDef::Item(def) => tcx .upstream_monomorphizations_for(def) - .and_then(|monos| monos.get(&self.substs).cloned()), - InstanceDef::DropGlue(_, Some(_)) => tcx.upstream_drop_glue_for(self.substs), + .and_then(|monos| monos.get(&self.args).cloned()), + InstanceDef::DropGlue(_, Some(_)) => tcx.upstream_drop_glue_for(self.args), _ => None, } } @@ -265,8 +265,8 @@ impl<'tcx> InstanceDef<'tcx> { } /// Returns `true` when the MIR body associated with this instance should be monomorphized - /// by its users (e.g. codegen or miri) by substituting the `substs` from `Instance` (see - /// `Instance::substs_for_mir_body`). + /// by its users (e.g. codegen or miri) by substituting the `args` from `Instance` (see + /// `Instance::args_for_mir_body`). /// /// Otherwise, returns `false` only for some kinds of shims where the construction of the MIR /// body should perform necessary substitutions. @@ -294,10 +294,10 @@ fn fmt_instance( type_length: rustc_session::Limit, ) -> fmt::Result { ty::tls::with(|tcx| { - let substs = tcx.lift(instance.substs).expect("could not lift for printing"); + let args = tcx.lift(instance.args).expect("could not lift for printing"); let s = FmtPrinter::new_with_limit(tcx, Namespace::ValueNS, type_length) - .print_def_path(instance.def_id(), substs)? + .print_def_path(instance.def_id(), args)? .into_buffer(); f.write_str(&s) })?; @@ -333,18 +333,18 @@ impl<'tcx> fmt::Display for Instance<'tcx> { } impl<'tcx> Instance<'tcx> { - pub fn new(def_id: DefId, substs: SubstsRef<'tcx>) -> Instance<'tcx> { + pub fn new(def_id: DefId, args: GenericArgsRef<'tcx>) -> Instance<'tcx> { assert!( - !substs.has_escaping_bound_vars(), - "substs of instance {:?} not normalized for codegen: {:?}", + !args.has_escaping_bound_vars(), + "args of instance {:?} not normalized for codegen: {:?}", def_id, - substs + args ); - Instance { def: InstanceDef::Item(def_id), substs } + Instance { def: InstanceDef::Item(def_id), args } } pub fn mono(tcx: TyCtxt<'tcx>, def_id: DefId) -> Instance<'tcx> { - let substs = InternalSubsts::for_item(tcx, def_id, |param, _| match param.kind { + let args = GenericArgs::for_item(tcx, def_id, |param, _| match param.kind { ty::GenericParamDefKind::Lifetime => tcx.lifetimes.re_erased.into(), ty::GenericParamDefKind::Type { .. } => { bug!("Instance::mono: {:?} has type parameters", def_id) @@ -354,7 +354,7 @@ impl<'tcx> Instance<'tcx> { } }); - Instance::new(def_id, substs) + Instance::new(def_id, args) } #[inline] @@ -362,7 +362,7 @@ impl<'tcx> Instance<'tcx> { self.def.def_id() } - /// Resolves a `(def_id, substs)` pair to an (optional) instance -- most commonly, + /// Resolves a `(def_id, args)` pair to an (optional) instance -- most commonly, /// this is used to find the precise code that will run for a trait method invocation, /// if known. /// @@ -390,29 +390,29 @@ impl<'tcx> Instance<'tcx> { tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, def_id: DefId, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, ) -> Result<Option<Instance<'tcx>>, ErrorGuaranteed> { // All regions in the result of this query are erased, so it's // fine to erase all of the input regions. - // HACK(eddyb) erase regions in `substs` first, so that `param_env.and(...)` + // HACK(eddyb) erase regions in `args` first, so that `param_env.and(...)` // below is more likely to ignore the bounds in scope (e.g. if the only - // generic parameters mentioned by `substs` were lifetime ones). - let substs = tcx.erase_regions(substs); - tcx.resolve_instance(tcx.erase_regions(param_env.and((def_id, substs)))) + // generic parameters mentioned by `args` were lifetime ones). + let args = tcx.erase_regions(args); + tcx.resolve_instance(tcx.erase_regions(param_env.and((def_id, args)))) } pub fn expect_resolve( tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, def_id: DefId, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, ) -> Instance<'tcx> { - match ty::Instance::resolve(tcx, param_env, def_id, substs) { + match ty::Instance::resolve(tcx, param_env, def_id, args) { Ok(Some(instance)) => instance, instance => bug!( "failed to resolve instance for {}: {instance:#?}", - tcx.def_path_str_with_substs(def_id, substs) + tcx.def_path_str_with_args(def_id, args) ), } } @@ -421,12 +421,12 @@ impl<'tcx> Instance<'tcx> { tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, def_id: DefId, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, ) -> Option<Instance<'tcx>> { - debug!("resolve(def_id={:?}, substs={:?})", def_id, substs); + debug!("resolve(def_id={:?}, args={:?})", def_id, args); // Use either `resolve_closure` or `resolve_for_vtable` assert!(!tcx.is_closure(def_id), "Called `resolve_for_fn_ptr` on closure: {:?}", def_id); - Instance::resolve(tcx, param_env, def_id, substs).ok().flatten().map(|mut resolved| { + Instance::resolve(tcx, param_env, def_id, args).ok().flatten().map(|mut resolved| { match resolved.def { InstanceDef::Item(def) if resolved.def.requires_caller_location(tcx) => { debug!(" => fn pointer created for function with #[track_caller]"); @@ -447,18 +447,18 @@ impl<'tcx> Instance<'tcx> { tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, def_id: DefId, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, ) -> Option<Instance<'tcx>> { - debug!("resolve_for_vtable(def_id={:?}, substs={:?})", def_id, substs); - let fn_sig = tcx.fn_sig(def_id).subst_identity(); + debug!("resolve_for_vtable(def_id={:?}, args={:?})", def_id, args); + let fn_sig = tcx.fn_sig(def_id).instantiate_identity(); let is_vtable_shim = !fn_sig.inputs().skip_binder().is_empty() && fn_sig.input(0).skip_binder().is_param(0) && tcx.generics_of(def_id).has_self; if is_vtable_shim { debug!(" => associated item with unsizeable self: Self"); - Some(Instance { def: InstanceDef::VTableShim(def_id), substs }) + Some(Instance { def: InstanceDef::VTableShim(def_id), args }) } else { - Instance::resolve(tcx, param_env, def_id, substs).ok().flatten().map(|mut resolved| { + Instance::resolve(tcx, param_env, def_id, args).ok().flatten().map(|mut resolved| { match resolved.def { InstanceDef::Item(def) => { // We need to generate a shim when we cannot guarantee that @@ -489,12 +489,12 @@ impl<'tcx> Instance<'tcx> { { if tcx.is_closure(def) { debug!(" => vtable fn pointer created for closure with #[track_caller]: {:?} for method {:?} {:?}", - def, def_id, substs); + def, def_id, args); // Create a shim for the `FnOnce/FnMut/Fn` method we are calling // - unlike functions, invoking a closure always goes through a // trait. - resolved = Instance { def: InstanceDef::ReifyShim(def_id), substs }; + resolved = Instance { def: InstanceDef::ReifyShim(def_id), args }; } else { debug!( " => vtable fn pointer created for function with #[track_caller]: {:?}", def @@ -518,28 +518,28 @@ impl<'tcx> Instance<'tcx> { pub fn resolve_closure( tcx: TyCtxt<'tcx>, def_id: DefId, - substs: ty::SubstsRef<'tcx>, + args: ty::GenericArgsRef<'tcx>, requested_kind: ty::ClosureKind, ) -> Option<Instance<'tcx>> { - let actual_kind = substs.as_closure().kind(); + let actual_kind = args.as_closure().kind(); match needs_fn_once_adapter_shim(actual_kind, requested_kind) { - Ok(true) => Instance::fn_once_adapter_instance(tcx, def_id, substs), - _ => Some(Instance::new(def_id, substs)), + Ok(true) => Instance::fn_once_adapter_instance(tcx, def_id, args), + _ => Some(Instance::new(def_id, args)), } } pub fn resolve_drop_in_place(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> ty::Instance<'tcx> { let def_id = tcx.require_lang_item(LangItem::DropInPlace, None); - let substs = tcx.mk_substs(&[ty.into()]); - Instance::expect_resolve(tcx, ty::ParamEnv::reveal_all(), def_id, substs) + let args = tcx.mk_args(&[ty.into()]); + Instance::expect_resolve(tcx, ty::ParamEnv::reveal_all(), def_id, args) } #[instrument(level = "debug", skip(tcx), ret)] pub fn fn_once_adapter_instance( tcx: TyCtxt<'tcx>, closure_did: DefId, - substs: ty::SubstsRef<'tcx>, + args: ty::GenericArgsRef<'tcx>, ) -> Option<Instance<'tcx>> { let fn_once = tcx.require_lang_item(LangItem::FnOnce, None); let call_once = tcx @@ -552,30 +552,30 @@ impl<'tcx> Instance<'tcx> { tcx.codegen_fn_attrs(closure_did).flags.contains(CodegenFnAttrFlags::TRACK_CALLER); let def = ty::InstanceDef::ClosureOnceShim { call_once, track_caller }; - let self_ty = Ty::new_closure(tcx, closure_did, substs); + let self_ty = Ty::new_closure(tcx, closure_did, args); - let sig = substs.as_closure().sig(); + let sig = args.as_closure().sig(); let sig = tcx.try_normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), sig).ok()?; assert_eq!(sig.inputs().len(), 1); - let substs = tcx.mk_substs_trait(self_ty, [sig.inputs()[0].into()]); + let args = tcx.mk_args_trait(self_ty, [sig.inputs()[0].into()]); debug!(?self_ty, ?sig); - Some(Instance { def, substs }) + Some(Instance { def, args }) } /// Depending on the kind of `InstanceDef`, the MIR body associated with an /// instance is expressed in terms of the generic parameters of `self.def_id()`, and in other /// cases the MIR body is expressed in terms of the types found in the substitution array. /// In the former case, we want to substitute those generic types and replace them with the - /// values from the substs when monomorphizing the function body. But in the latter case, we + /// values from the args when monomorphizing the function body. But in the latter case, we /// don't want to do that substitution, since it has already been done effectively. /// - /// This function returns `Some(substs)` in the former case and `None` otherwise -- i.e., if + /// This function returns `Some(args)` in the former case and `None` otherwise -- i.e., if /// this function returns `None`, then the MIR body does not require substitution during /// codegen. - fn substs_for_mir_body(&self) -> Option<SubstsRef<'tcx>> { - self.def.has_polymorphic_mir_body().then_some(self.substs) + fn args_for_mir_body(&self) -> Option<GenericArgsRef<'tcx>> { + self.def.has_polymorphic_mir_body().then_some(self.args) } pub fn subst_mir<T>(&self, tcx: TyCtxt<'tcx>, v: EarlyBinder<&T>) -> T @@ -583,10 +583,10 @@ impl<'tcx> Instance<'tcx> { T: TypeFoldable<TyCtxt<'tcx>> + Copy, { let v = v.map_bound(|v| *v); - if let Some(substs) = self.substs_for_mir_body() { - v.subst(tcx, substs) + if let Some(args) = self.args_for_mir_body() { + v.instantiate(tcx, args) } else { - v.subst_identity() + v.instantiate_identity() } } @@ -600,8 +600,8 @@ impl<'tcx> Instance<'tcx> { where T: TypeFoldable<TyCtxt<'tcx>> + Clone, { - if let Some(substs) = self.substs_for_mir_body() { - tcx.subst_and_normalize_erasing_regions(substs, param_env, v) + if let Some(args) = self.args_for_mir_body() { + tcx.subst_and_normalize_erasing_regions(args, param_env, v) } else { tcx.normalize_erasing_regions(param_env, v.skip_binder()) } @@ -617,14 +617,14 @@ impl<'tcx> Instance<'tcx> { where T: TypeFoldable<TyCtxt<'tcx>> + Clone, { - if let Some(substs) = self.substs_for_mir_body() { - tcx.try_subst_and_normalize_erasing_regions(substs, param_env, v) + if let Some(args) = self.args_for_mir_body() { + tcx.try_subst_and_normalize_erasing_regions(args, param_env, v) } else { tcx.try_normalize_erasing_regions(param_env, v.skip_binder()) } } - /// Returns a new `Instance` where generic parameters in `instance.substs` are replaced by + /// Returns a new `Instance` where generic parameters in `instance.args` are replaced by /// identity parameters if they are determined to be unused in `instance.def`. pub fn polymorphize(self, tcx: TyCtxt<'tcx>) -> Self { debug!("polymorphize: running polymorphization analysis"); @@ -632,18 +632,18 @@ impl<'tcx> Instance<'tcx> { return self; } - let polymorphized_substs = polymorphize(tcx, self.def, self.substs); - debug!("polymorphize: self={:?} polymorphized_substs={:?}", self, polymorphized_substs); - Self { def: self.def, substs: polymorphized_substs } + let polymorphized_args = polymorphize(tcx, self.def, self.args); + debug!("polymorphize: self={:?} polymorphized_args={:?}", self, polymorphized_args); + Self { def: self.def, args: polymorphized_args } } } fn polymorphize<'tcx>( tcx: TyCtxt<'tcx>, instance: ty::InstanceDef<'tcx>, - substs: SubstsRef<'tcx>, -) -> SubstsRef<'tcx> { - debug!("polymorphize({:?}, {:?})", instance, substs); + args: GenericArgsRef<'tcx>, +) -> GenericArgsRef<'tcx> { + debug!("polymorphize({:?}, {:?})", instance, args); let unused = tcx.unused_generic_params(instance); debug!("polymorphize: unused={:?}", unused); @@ -653,9 +653,9 @@ fn polymorphize<'tcx>( // multiple mono items (and eventually symbol clashes). let def_id = instance.def_id(); let upvars_ty = if tcx.is_closure(def_id) { - Some(substs.as_closure().tupled_upvars_ty()) + Some(args.as_closure().tupled_upvars_ty()) } else if tcx.type_of(def_id).skip_binder().is_generator() { - Some(substs.as_generator().tupled_upvars_ty()) + Some(args.as_generator().tupled_upvars_ty()) } else { None }; @@ -674,22 +674,22 @@ fn polymorphize<'tcx>( fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> { debug!("fold_ty: ty={:?}", ty); match *ty.kind() { - ty::Closure(def_id, substs) => { - let polymorphized_substs = - polymorphize(self.tcx, ty::InstanceDef::Item(def_id), substs); - if substs == polymorphized_substs { + ty::Closure(def_id, args) => { + let polymorphized_args = + polymorphize(self.tcx, ty::InstanceDef::Item(def_id), args); + if args == polymorphized_args { ty } else { - Ty::new_closure(self.tcx, def_id, polymorphized_substs) + Ty::new_closure(self.tcx, def_id, polymorphized_args) } } - ty::Generator(def_id, substs, movability) => { - let polymorphized_substs = - polymorphize(self.tcx, ty::InstanceDef::Item(def_id), substs); - if substs == polymorphized_substs { + ty::Generator(def_id, args, movability) => { + let polymorphized_args = + polymorphize(self.tcx, ty::InstanceDef::Item(def_id), args); + if args == polymorphized_args { ty } else { - Ty::new_generator(self.tcx, def_id, polymorphized_substs, movability) + Ty::new_generator(self.tcx, def_id, polymorphized_args, movability) } } _ => ty.super_fold_with(self), @@ -697,7 +697,7 @@ fn polymorphize<'tcx>( } } - InternalSubsts::for_item(tcx, def_id, |param, _| { + GenericArgs::for_item(tcx, def_id, |param, _| { let is_unused = unused.is_unused(param.index); debug!("polymorphize: param={:?} is_unused={:?}", param, is_unused); match param.kind { @@ -706,7 +706,7 @@ fn polymorphize<'tcx>( // ..and has upvars.. has_upvars && // ..and this param has the same type as the tupled upvars.. - upvars_ty == Some(substs[param.index as usize].expect_ty()) => { + upvars_ty == Some(args[param.index as usize].expect_ty()) => { // ..then double-check that polymorphization marked it used.. debug_assert!(!is_unused); // ..and polymorphize any closures/generators captured as upvars. @@ -725,7 +725,7 @@ fn polymorphize<'tcx>( tcx.mk_param_from_def(param), // Otherwise, use the parameter as before. - _ => substs[param.index as usize], + _ => args[param.index as usize], } }) } diff --git a/compiler/rustc_middle/src/ty/layout.rs b/compiler/rustc_middle/src/ty/layout.rs index d95b05ef754..62805d1e8b5 100644 --- a/compiler/rustc_middle/src/ty/layout.rs +++ b/compiler/rustc_middle/src/ty/layout.rs @@ -374,7 +374,7 @@ impl<'tcx> SizeSkeleton<'tcx> { } } - ty::Adt(def, substs) => { + ty::Adt(def, args) => { // Only newtypes and enums w/ nullable pointer optimization. if def.is_union() || def.variants().is_empty() || def.variants().len() > 2 { return Err(err); @@ -385,7 +385,7 @@ impl<'tcx> SizeSkeleton<'tcx> { let i = VariantIdx::from_usize(i); let fields = def.variant(i).fields.iter().map(|field| { - SizeSkeleton::compute(field.ty(tcx, substs), tcx, param_env) + SizeSkeleton::compute(field.ty(tcx, args), tcx, param_env) }); let mut ptr = None; for field in fields { @@ -755,6 +755,8 @@ where largest_niche: None, align: tcx.data_layout.i8_align, size: Size::ZERO, + max_repr_align: None, + unadjusted_abi_align: tcx.data_layout.i8_align.abi, }) } @@ -861,9 +863,9 @@ where // offers better information than `std::ptr::metadata::VTable`, // and we rely on this layout information to trigger a panic in // `std::mem::uninitialized::<&dyn Trait>()`, for example. - if let ty::Adt(def, substs) = metadata.kind() + if let ty::Adt(def, args) = metadata.kind() && Some(def.did()) == tcx.lang_items().dyn_metadata() - && substs.type_at(0).is_trait() + && args.type_at(0).is_trait() { mk_dyn_vtable() } else { @@ -885,16 +887,15 @@ where ty::Str => TyMaybeWithLayout::Ty(tcx.types.u8), // Tuples, generators and closures. - ty::Closure(_, ref substs) => field_ty_or_layout( - TyAndLayout { ty: substs.as_closure().tupled_upvars_ty(), ..this }, + ty::Closure(_, ref args) => field_ty_or_layout( + TyAndLayout { ty: args.as_closure().tupled_upvars_ty(), ..this }, cx, i, ), - ty::Generator(def_id, ref substs, _) => match this.variants { + ty::Generator(def_id, ref args, _) => match this.variants { Variants::Single { index } => TyMaybeWithLayout::Ty( - substs - .as_generator() + args.as_generator() .state_tys(def_id, tcx) .nth(index.as_usize()) .unwrap() @@ -905,18 +906,18 @@ where if i == tag_field { return TyMaybeWithLayout::TyAndLayout(tag_layout(tag)); } - TyMaybeWithLayout::Ty(substs.as_generator().prefix_tys().nth(i).unwrap()) + TyMaybeWithLayout::Ty(args.as_generator().prefix_tys().nth(i).unwrap()) } }, ty::Tuple(tys) => TyMaybeWithLayout::Ty(tys[i]), // ADTs. - ty::Adt(def, substs) => { + ty::Adt(def, args) => { match this.variants { Variants::Single { index } => { let field = &def.variant(index).fields[FieldIdx::from_usize(i)]; - TyMaybeWithLayout::Ty(field.ty(tcx, substs)) + TyMaybeWithLayout::Ty(field.ty(tcx, args)) } // Discriminant field for enums (where applicable). diff --git a/compiler/rustc_middle/src/ty/list.rs b/compiler/rustc_middle/src/ty/list.rs index 71911a5a618..7a32cfb1085 100644 --- a/compiler/rustc_middle/src/ty/list.rs +++ b/compiler/rustc_middle/src/ty/list.rs @@ -1,6 +1,7 @@ use crate::arena::Arena; use rustc_data_structures::aligned::{align_of, Aligned}; use rustc_serialize::{Encodable, Encoder}; +use rustc_type_ir::{InferCtxtLike, OptWithInfcx}; use std::alloc::Layout; use std::cmp::Ordering; use std::fmt; @@ -119,6 +120,14 @@ impl<T: fmt::Debug> fmt::Debug for List<T> { (**self).fmt(f) } } +impl<'tcx, T: super::DebugWithInfcx<TyCtxt<'tcx>>> super::DebugWithInfcx<TyCtxt<'tcx>> for List<T> { + fn fmt<InfCtx: InferCtxtLike<TyCtxt<'tcx>>>( + this: OptWithInfcx<'_, TyCtxt<'tcx>, InfCtx, &Self>, + f: &mut core::fmt::Formatter<'_>, + ) -> core::fmt::Result { + fmt::Debug::fmt(&this.map(|this| this.as_slice()), f) + } +} impl<S: Encoder, T: Encodable<S>> Encodable<S> for List<T> { #[inline] @@ -202,6 +211,8 @@ unsafe impl<T: Sync> Sync for List<T> {} // We need this since `List` uses extern type `OpaqueListContents`. #[cfg(parallel_compiler)] use rustc_data_structures::sync::DynSync; + +use super::TyCtxt; #[cfg(parallel_compiler)] unsafe impl<T: DynSync> DynSync for List<T> {} diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index 792ee8ebb25..0411890ab51 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -28,6 +28,7 @@ use crate::ty::fast_reject::SimplifiedType; use crate::ty::util::Discr; pub use adt::*; pub use assoc::*; +pub use generic_args::*; pub use generics::*; use rustc_ast as ast; use rustc_ast::node_id::NodeMap; @@ -53,7 +54,7 @@ use rustc_span::symbol::{kw, sym, Ident, Symbol}; use rustc_span::{ExpnId, ExpnKind, Span}; use rustc_target::abi::{Align, FieldIdx, Integer, IntegerType, VariantIdx}; pub use rustc_target::abi::{ReprFlags, ReprOptions}; -pub use subst::*; +pub use rustc_type_ir::{DebugWithInfcx, InferCtxtLike, OptWithInfcx}; pub use vtable::*; use std::fmt::Debug; @@ -81,8 +82,7 @@ pub use self::binding::BindingMode::*; pub use self::closure::{ is_ancestor_or_same_capture, place_to_string_for_capture, BorrowKind, CaptureInfo, CapturedPlace, ClosureKind, ClosureTypeInfo, MinCaptureInformationMap, MinCaptureList, - RootVariableMinCaptureList, UpvarCapture, UpvarCaptureMap, UpvarId, UpvarListMap, UpvarPath, - CAPTURE_STRUCT_LOCAL, + RootVariableMinCaptureList, UpvarCapture, UpvarId, UpvarPath, CAPTURE_STRUCT_LOCAL, }; pub use self::consts::{ Const, ConstData, ConstInt, Expr, InferConst, ScalarInt, UnevaluatedConst, ValTree, @@ -97,12 +97,12 @@ pub use self::rvalue_scopes::RvalueScopes; pub use self::sty::BoundRegionKind::*; pub use self::sty::{ AliasTy, Article, Binder, BoundRegion, BoundRegionKind, BoundTy, BoundTyKind, BoundVar, - BoundVariableKind, CanonicalPolyFnSig, ClosureSubsts, ClosureSubstsParts, ConstKind, ConstVid, + BoundVariableKind, CanonicalPolyFnSig, ClosureArgs, ClosureArgsParts, ConstKind, ConstVid, EarlyBoundRegion, ExistentialPredicate, ExistentialProjection, ExistentialTraitRef, FnSig, - FreeRegion, GenSig, GeneratorSubsts, GeneratorSubstsParts, InlineConstSubsts, - InlineConstSubstsParts, ParamConst, ParamTy, PolyExistentialPredicate, - PolyExistentialProjection, PolyExistentialTraitRef, PolyFnSig, PolyGenSig, PolyTraitRef, - Region, RegionKind, RegionVid, TraitRef, TyKind, TypeAndMut, UpvarSubsts, VarianceDiagInfo, + FreeRegion, GenSig, GeneratorArgs, GeneratorArgsParts, InlineConstArgs, InlineConstArgsParts, + ParamConst, ParamTy, PolyExistentialPredicate, PolyExistentialProjection, + PolyExistentialTraitRef, PolyFnSig, PolyGenSig, PolyTraitRef, Region, RegionKind, RegionVid, + TraitRef, TyKind, TypeAndMut, UpvarArgs, VarianceDiagInfo, }; pub use self::trait_def::TraitDef; pub use self::typeck_results::{ @@ -126,7 +126,6 @@ pub mod layout; pub mod normalize_erasing_regions; pub mod print; pub mod relate; -pub mod subst; pub mod trait_def; pub mod util; pub mod visit; @@ -140,6 +139,7 @@ mod consts; mod context; mod diagnostics; mod erase_regions; +mod generic_args; mod generics; mod impls_ty; mod instance; @@ -148,7 +148,7 @@ mod opaque_types; mod parameterized; mod rvalue_scopes; mod structural_impls; -#[cfg_attr(not(bootstrap), allow(hidden_glob_reexports))] +#[allow(hidden_glob_reexports)] mod sty; mod typeck_results; @@ -676,9 +676,9 @@ pub enum PredicateKind<'tcx> { ObjectSafe(DefId), /// No direct syntax. May be thought of as `where T: FnFoo<...>` - /// for some substitutions `...` and `T` being a closure type. + /// for some generic args `...` and `T` being a closure type. /// Satisfied (or refuted) once we know the closure's kind. - ClosureKind(DefId, SubstsRef<'tcx>, ClosureKind), + ClosureKind(DefId, GenericArgsRef<'tcx>, ClosureKind), /// `T1 <: T2` /// @@ -813,15 +813,15 @@ impl<'tcx> Clause<'tcx> { // this trick achieves that). // Working through the second example: - // trait_ref: for<'x> T: Foo1<'^0.0>; substs: [T, '^0.0] - // predicate: for<'b> Self: Bar1<'a, '^0.0>; substs: [Self, 'a, '^0.0] + // trait_ref: for<'x> T: Foo1<'^0.0>; args: [T, '^0.0] + // predicate: for<'b> Self: Bar1<'a, '^0.0>; args: [Self, 'a, '^0.0] // We want to end up with: // for<'x, 'b> T: Bar1<'^0.0, '^0.1> // To do this: // 1) We must shift all bound vars in predicate by the length // of trait ref's bound vars. So, we would end up with predicate like // Self: Bar1<'a, '^0.1> - // 2) We can then apply the trait substs to this, ending up with + // 2) We can then apply the trait args to this, ending up with // T: Bar1<'^0.0, '^0.1> // 3) Finally, to create the final bound vars, we concatenate the bound // vars of the trait ref with those of the predicate: @@ -833,7 +833,7 @@ impl<'tcx> Clause<'tcx> { let shifted_pred = tcx.shift_bound_var_indices(trait_bound_vars.len(), bound_pred.skip_binder()); // 2) Self: Bar1<'a, '^0.1> -> T: Bar1<'^0.0, '^0.1> - let new = EarlyBinder::bind(shifted_pred).subst(tcx, trait_ref.skip_binder().substs); + let new = EarlyBinder::bind(shifted_pred).instantiate(tcx, trait_ref.skip_binder().args); // 3) ['x] + ['b] -> ['x, 'b] let bound_vars = tcx.mk_bound_variable_kinds_from_iter(trait_bound_vars.iter().chain(pred_bound_vars)); @@ -1079,7 +1079,7 @@ impl<'tcx> Term<'tcx> { _ => None, }, TermKind::Const(ct) => match ct.kind() { - ConstKind::Unevaluated(uv) => Some(tcx.mk_alias_ty(uv.def, uv.substs)), + ConstKind::Unevaluated(uv) => Some(tcx.mk_alias_ty(uv.def, uv.args)), _ => None, }, } @@ -1558,7 +1558,7 @@ impl<'a, 'tcx> IntoIterator for &'a InstantiatedPredicates<'tcx> { #[derive(TypeFoldable, TypeVisitable)] pub struct OpaqueTypeKey<'tcx> { pub def_id: LocalDefId, - pub substs: SubstsRef<'tcx>, + pub args: GenericArgsRef<'tcx>, } #[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable, HashStable, TyEncodable, TyDecodable)] @@ -1629,21 +1629,21 @@ impl<'tcx> OpaqueHiddenType<'tcx> { // typeck errors have subpar spans for opaque types, so delay error reporting until borrowck. ignore_errors: bool, ) -> Self { - let OpaqueTypeKey { def_id, substs } = opaque_type_key; + let OpaqueTypeKey { def_id, args } = opaque_type_key; - // Use substs to build up a reverse map from regions to their + // Use args to build up a reverse map from regions to their // identity mappings. This is necessary because of `impl // Trait` lifetimes are computed by replacing existing // lifetimes with 'static and remapping only those used in the // `impl Trait` return type, resulting in the parameters // shifting. - let id_substs = InternalSubsts::identity_for_item(tcx, def_id); - debug!(?id_substs); + let id_args = GenericArgs::identity_for_item(tcx, def_id); + debug!(?id_args); - // This zip may have several times the same lifetime in `substs` paired with a different - // lifetime from `id_substs`. Simply `collect`ing the iterator is the correct behaviour: + // This zip may have several times the same lifetime in `args` paired with a different + // lifetime from `id_args`. Simply `collect`ing the iterator is the correct behaviour: // it will pick the last one, which is the one we introduced in the impl-trait desugaring. - let map = substs.iter().zip(id_substs).collect(); + let map = args.iter().zip(id_args).collect(); debug!("map = {:#?}", map); // Convert the type from the function into a type valid outside @@ -2164,10 +2164,10 @@ impl Hash for FieldDef { } impl<'tcx> FieldDef { - /// Returns the type of this field. The resulting type is not normalized. The `subst` is + /// Returns the type of this field. The resulting type is not normalized. The `arg` is /// typically obtained via the second field of [`TyKind::Adt`]. - pub fn ty(&self, tcx: TyCtxt<'tcx>, subst: SubstsRef<'tcx>) -> Ty<'tcx> { - tcx.type_of(self.did).subst(tcx, subst) + pub fn ty(&self, tcx: TyCtxt<'tcx>, arg: GenericArgsRef<'tcx>) -> Ty<'tcx> { + tcx.type_of(self.did).instantiate(tcx, arg) } /// Computes the `Ident` of this variant by looking up the `Span` @@ -2391,8 +2391,8 @@ impl<'tcx> TyCtxt<'tcx> { let impl_trait_ref2 = self.impl_trait_ref(def_id2); // If either trait impl references an error, they're allowed to overlap, // as one of them essentially doesn't exist. - if impl_trait_ref1.is_some_and(|tr| tr.subst_identity().references_error()) - || impl_trait_ref2.is_some_and(|tr| tr.subst_identity().references_error()) + if impl_trait_ref1.is_some_and(|tr| tr.instantiate_identity().references_error()) + || impl_trait_ref2.is_some_and(|tr| tr.instantiate_identity().references_error()) { return Some(ImplOverlapKind::Permitted { marker: false }); } @@ -2712,12 +2712,16 @@ impl<'tcx> TyCtxt<'tcx> { return false; } - let Some(item) = self.opt_associated_item(def_id) else { return false; }; + let Some(item) = self.opt_associated_item(def_id) else { + return false; + }; if item.container != ty::AssocItemContainer::ImplContainer { return false; } - let Some(trait_item_def_id) = item.trait_item_def_id else { return false; }; + let Some(trait_item_def_id) = item.trait_item_def_id else { + return false; + }; return !self .associated_types_for_impl_traits_in_associated_fn(trait_item_def_id) diff --git a/compiler/rustc_middle/src/ty/normalize_erasing_regions.rs b/compiler/rustc_middle/src/ty/normalize_erasing_regions.rs index a0c8d299f48..3c2c4483c73 100644 --- a/compiler/rustc_middle/src/ty/normalize_erasing_regions.rs +++ b/compiler/rustc_middle/src/ty/normalize_erasing_regions.rs @@ -9,7 +9,7 @@ use crate::traits::query::NoSolution; use crate::ty::fold::{FallibleTypeFolder, TypeFoldable, TypeFolder}; -use crate::ty::{self, EarlyBinder, SubstsRef, Ty, TyCtxt, TypeVisitableExt}; +use crate::ty::{self, EarlyBinder, GenericArgsRef, Ty, TyCtxt, TypeVisitableExt}; #[derive(Debug, Copy, Clone, HashStable, TyEncodable, TyDecodable)] pub enum NormalizationError<'tcx> { @@ -137,7 +137,7 @@ impl<'tcx> TyCtxt<'tcx> { /// use `try_subst_and_normalize_erasing_regions` instead. pub fn subst_and_normalize_erasing_regions<T>( self, - param_substs: SubstsRef<'tcx>, + param_args: GenericArgsRef<'tcx>, param_env: ty::ParamEnv<'tcx>, value: EarlyBinder<T>, ) -> T @@ -146,12 +146,12 @@ impl<'tcx> TyCtxt<'tcx> { { debug!( "subst_and_normalize_erasing_regions(\ - param_substs={:?}, \ + param_args={:?}, \ value={:?}, \ param_env={:?})", - param_substs, value, param_env, + param_args, value, param_env, ); - let substituted = value.subst(self, param_substs); + let substituted = value.instantiate(self, param_args); self.normalize_erasing_regions(param_env, substituted) } @@ -161,7 +161,7 @@ impl<'tcx> TyCtxt<'tcx> { /// not assume that normalization succeeds. pub fn try_subst_and_normalize_erasing_regions<T>( self, - param_substs: SubstsRef<'tcx>, + param_args: GenericArgsRef<'tcx>, param_env: ty::ParamEnv<'tcx>, value: EarlyBinder<T>, ) -> Result<T, NormalizationError<'tcx>> @@ -170,12 +170,12 @@ impl<'tcx> TyCtxt<'tcx> { { debug!( "subst_and_normalize_erasing_regions(\ - param_substs={:?}, \ + param_args={:?}, \ value={:?}, \ param_env={:?})", - param_substs, value, param_env, + param_args, value, param_env, ); - let substituted = value.subst(self, param_substs); + let substituted = value.instantiate(self, param_args); self.try_normalize_erasing_regions(param_env, substituted) } } diff --git a/compiler/rustc_middle/src/ty/opaque_types.rs b/compiler/rustc_middle/src/ty/opaque_types.rs index b10921eff08..7ae8be2dab3 100644 --- a/compiler/rustc_middle/src/ty/opaque_types.rs +++ b/compiler/rustc_middle/src/ty/opaque_types.rs @@ -1,7 +1,7 @@ use crate::error::ConstNotUsedTraitAlias; use crate::ty::fold::{TypeFolder, TypeSuperFoldable}; -use crate::ty::subst::{GenericArg, GenericArgKind}; use crate::ty::{self, Ty, TyCtxt, TypeFoldable}; +use crate::ty::{GenericArg, GenericArgKind}; use rustc_data_structures::fx::FxHashMap; use rustc_span::def_id::DefId; use rustc_span::Span; @@ -49,11 +49,11 @@ impl<'tcx> ReverseMapper<'tcx> { kind.fold_with(self) } - fn fold_closure_substs( + fn fold_closure_args( &mut self, def_id: DefId, - substs: ty::SubstsRef<'tcx>, - ) -> ty::SubstsRef<'tcx> { + args: ty::GenericArgsRef<'tcx>, + ) -> ty::GenericArgsRef<'tcx> { // I am a horrible monster and I pray for death. When // we encounter a closure here, it is always a closure // from within the function that we are currently @@ -79,7 +79,7 @@ impl<'tcx> ReverseMapper<'tcx> { // during codegen. let generics = self.tcx.generics_of(def_id); - self.tcx.mk_substs_from_iter(substs.iter().enumerate().map(|(index, kind)| { + self.tcx.mk_args_from_iter(args.iter().enumerate().map(|(index, kind)| { if index < generics.parent_count { // Accommodate missing regions in the parent kinds... self.fold_kind_no_missing_regions_error(kind) @@ -148,19 +148,19 @@ impl<'tcx> TypeFolder<TyCtxt<'tcx>> for ReverseMapper<'tcx> { fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> { match *ty.kind() { - ty::Closure(def_id, substs) => { - let substs = self.fold_closure_substs(def_id, substs); - Ty::new_closure(self.tcx, def_id, substs) + ty::Closure(def_id, args) => { + let args = self.fold_closure_args(def_id, args); + Ty::new_closure(self.tcx, def_id, args) } - ty::Generator(def_id, substs, movability) => { - let substs = self.fold_closure_substs(def_id, substs); - Ty::new_generator(self.tcx, def_id, substs, movability) + ty::Generator(def_id, args, movability) => { + let args = self.fold_closure_args(def_id, args); + Ty::new_generator(self.tcx, def_id, args, movability) } - ty::GeneratorWitnessMIR(def_id, substs) => { - let substs = self.fold_closure_substs(def_id, substs); - Ty::new_generator_witness_mir(self.tcx, def_id, substs) + ty::GeneratorWitnessMIR(def_id, args) => { + let args = self.fold_closure_args(def_id, args); + Ty::new_generator_witness_mir(self.tcx, def_id, args) } ty::Param(param) => { diff --git a/compiler/rustc_middle/src/ty/parameterized.rs b/compiler/rustc_middle/src/ty/parameterized.rs index cc2b26a5e14..f1c38984296 100644 --- a/compiler/rustc_middle/src/ty/parameterized.rs +++ b/compiler/rustc_middle/src/ty/parameterized.rs @@ -52,6 +52,7 @@ trivially_parameterized_over_tcx! { usize, (), u32, + u64, bool, std::string::String, crate::metadata::ModChild, diff --git a/compiler/rustc_middle/src/ty/print/mod.rs b/compiler/rustc_middle/src/ty/print/mod.rs index 2de0a3f75dc..83a75d0c6b9 100644 --- a/compiler/rustc_middle/src/ty/print/mod.rs +++ b/compiler/rustc_middle/src/ty/print/mod.rs @@ -42,19 +42,19 @@ pub trait Printer<'tcx>: Sized { fn print_def_path( self, def_id: DefId, - substs: &'tcx [GenericArg<'tcx>], + args: &'tcx [GenericArg<'tcx>], ) -> Result<Self::Path, Self::Error> { - self.default_print_def_path(def_id, substs) + self.default_print_def_path(def_id, args) } fn print_impl_path( self, impl_def_id: DefId, - substs: &'tcx [GenericArg<'tcx>], + args: &'tcx [GenericArg<'tcx>], self_ty: Ty<'tcx>, trait_ref: Option<ty::TraitRef<'tcx>>, ) -> Result<Self::Path, Self::Error> { - self.default_print_impl_path(impl_def_id, substs, self_ty, trait_ref) + self.default_print_impl_path(impl_def_id, args, self_ty, trait_ref) } fn print_region(self, region: ty::Region<'tcx>) -> Result<Self::Region, Self::Error>; @@ -102,7 +102,7 @@ pub trait Printer<'tcx>: Sized { fn default_print_def_path( self, def_id: DefId, - substs: &'tcx [GenericArg<'tcx>], + args: &'tcx [GenericArg<'tcx>], ) -> Result<Self::Path, Self::Error> { let key = self.tcx().def_key(def_id); debug!(?key); @@ -117,25 +117,28 @@ pub trait Printer<'tcx>: Sized { let generics = self.tcx().generics_of(def_id); let self_ty = self.tcx().type_of(def_id); let impl_trait_ref = self.tcx().impl_trait_ref(def_id); - let (self_ty, impl_trait_ref) = if substs.len() >= generics.count() { + let (self_ty, impl_trait_ref) = if args.len() >= generics.count() { ( - self_ty.subst(self.tcx(), substs), - impl_trait_ref.map(|i| i.subst(self.tcx(), substs)), + self_ty.instantiate(self.tcx(), args), + impl_trait_ref.map(|i| i.instantiate(self.tcx(), args)), ) } else { - (self_ty.subst_identity(), impl_trait_ref.map(|i| i.subst_identity())) + ( + self_ty.instantiate_identity(), + impl_trait_ref.map(|i| i.instantiate_identity()), + ) }; - self.print_impl_path(def_id, substs, self_ty, impl_trait_ref) + self.print_impl_path(def_id, args, self_ty, impl_trait_ref) } _ => { let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id }; - let mut parent_substs = substs; + let mut parent_args = args; let mut trait_qualify_parent = false; - if !substs.is_empty() { + if !args.is_empty() { let generics = self.tcx().generics_of(def_id); - parent_substs = &substs[..generics.parent_count.min(substs.len())]; + parent_args = &args[..generics.parent_count.min(args.len())]; match key.disambiguated_data.data { // Closures' own generics are only captures, don't print them. @@ -148,10 +151,10 @@ pub trait Printer<'tcx>: Sized { // If we have any generic arguments to print, we do that // on top of the same path, but without its own generics. _ => { - if !generics.params.is_empty() && substs.len() >= generics.count() { - let args = generics.own_substs_no_defaults(self.tcx(), substs); + if !generics.params.is_empty() && args.len() >= generics.count() { + let args = generics.own_args_no_defaults(self.tcx(), args); return self.path_generic_args( - |cx| cx.print_def_path(def_id, parent_substs), + |cx| cx.print_def_path(def_id, parent_args), args, ); } @@ -162,7 +165,7 @@ pub trait Printer<'tcx>: Sized { // logic, instead of doing it when printing the child. trait_qualify_parent = generics.has_self && generics.parent == Some(parent_def_id) - && parent_substs.len() == generics.parent_count + && parent_args.len() == generics.parent_count && self.tcx().generics_of(parent_def_id).parent_count == 0; } @@ -172,11 +175,11 @@ pub trait Printer<'tcx>: Sized { let trait_ref = ty::TraitRef::new( cx.tcx(), parent_def_id, - parent_substs.iter().copied(), + parent_args.iter().copied(), ); cx.path_qualified(trait_ref.self_ty(), Some(trait_ref)) } else { - cx.print_def_path(parent_def_id, parent_substs) + cx.print_def_path(parent_def_id, parent_args) } }, &key.disambiguated_data, @@ -188,7 +191,7 @@ pub trait Printer<'tcx>: Sized { fn default_print_impl_path( self, impl_def_id: DefId, - _substs: &'tcx [GenericArg<'tcx>], + _args: &'tcx [GenericArg<'tcx>], self_ty: Ty<'tcx>, impl_trait_ref: Option<ty::TraitRef<'tcx>>, ) -> Result<Self::Path, Self::Error> { diff --git a/compiler/rustc_middle/src/ty/print/pretty.rs b/compiler/rustc_middle/src/ty/print/pretty.rs index 96cf36eb996..3591acdea56 100644 --- a/compiler/rustc_middle/src/ty/print/pretty.rs +++ b/compiler/rustc_middle/src/ty/print/pretty.rs @@ -224,9 +224,9 @@ pub trait PrettyPrinter<'tcx>: fn print_value_path( self, def_id: DefId, - substs: &'tcx [GenericArg<'tcx>], + args: &'tcx [GenericArg<'tcx>], ) -> Result<Self::Path, Self::Error> { - self.print_def_path(def_id, substs) + self.print_def_path(def_id, args) } fn in_binder<T>(self, value: &ty::Binder<'tcx, T>) -> Result<Self, Self::Error> @@ -679,12 +679,12 @@ pub trait PrettyPrinter<'tcx>: } p!(")") } - ty::FnDef(def_id, substs) => { + ty::FnDef(def_id, args) => { if with_no_queries() { - p!(print_def_path(def_id, substs)); + p!(print_def_path(def_id, args)); } else { - let sig = self.tcx().fn_sig(def_id).subst(self.tcx(), substs); - p!(print(sig), " {{", print_value_path(def_id, substs), "}}"); + let sig = self.tcx().fn_sig(def_id).instantiate(self.tcx(), args); + p!(print(sig), " {{", print_value_path(def_id, args), "}}"); } } ty::FnPtr(ref bare_fn) => p!(print(bare_fn)), @@ -715,8 +715,8 @@ pub trait PrettyPrinter<'tcx>: false => p!(write("{s}")), }, }, - ty::Adt(def, substs) => { - p!(print_def_path(def.did(), substs)); + ty::Adt(def, args) => { + p!(print_def_path(def.did(), args)); } ty::Dynamic(data, r, repr) => { let print_r = self.should_print_region(r); @@ -739,7 +739,7 @@ pub trait PrettyPrinter<'tcx>: if !(self.should_print_verbose() || with_no_queries()) && self.tcx().is_impl_trait_in_trait(data.def_id) { - return self.pretty_print_opaque_impl_type(data.def_id, data.substs); + return self.pretty_print_opaque_impl_type(data.def_id, data.args); } else { p!(print(data)) } @@ -751,7 +751,7 @@ pub trait PrettyPrinter<'tcx>: false => p!(write("{name}")), }, }, - ty::Alias(ty::Opaque, ty::AliasTy { def_id, substs, .. }) => { + ty::Alias(ty::Opaque, ty::AliasTy { def_id, args, .. }) => { // We use verbose printing in 'NO_QUERIES' mode, to // avoid needing to call `predicates_of`. This should // only affect certain debug messages (e.g. messages printed @@ -759,7 +759,7 @@ pub trait PrettyPrinter<'tcx>: // and should have no effect on any compiler output. if self.should_print_verbose() { // FIXME(eddyb) print this with `print_def_path`. - p!(write("Opaque({:?}, {:?})", def_id, substs)); + p!(write("Opaque({:?}, {:?})", def_id, args)); return Ok(self); } @@ -769,17 +769,17 @@ pub trait PrettyPrinter<'tcx>: // NOTE: I know we should check for NO_QUERIES here, but it's alright. // `type_of` on a type alias or assoc type should never cause a cycle. if let ty::Alias(ty::Opaque, ty::AliasTy { def_id: d, .. }) = - *self.tcx().type_of(parent).subst_identity().kind() + *self.tcx().type_of(parent).instantiate_identity().kind() { if d == def_id { // If the type alias directly starts with the `impl` of the // opaque type we're printing, then skip the `::{opaque#1}`. - p!(print_def_path(parent, substs)); + p!(print_def_path(parent, args)); return Ok(self); } } // Complex opaque type, e.g. `type Foo = (i32, impl Debug);` - p!(print_def_path(def_id, substs)); + p!(print_def_path(def_id, args)); return Ok(self); } _ => { @@ -787,13 +787,13 @@ pub trait PrettyPrinter<'tcx>: p!(print_def_path(def_id, &[])); return Ok(self); } else { - return self.pretty_print_opaque_impl_type(def_id, substs); + return self.pretty_print_opaque_impl_type(def_id, args); } } } } ty::Str => p!("str"), - ty::Generator(did, substs, movability) => { + ty::Generator(did, args, movability) => { p!(write("[")); let generator_kind = self.tcx().generator_kind(did).unwrap(); let should_print_movability = @@ -818,20 +818,20 @@ pub trait PrettyPrinter<'tcx>: self.tcx().sess.source_map().span_to_embeddable_string(span) )); } else { - p!(write("@"), print_def_path(did, substs)); + p!(write("@"), print_def_path(did, args)); } } else { - p!(print_def_path(did, substs)); + p!(print_def_path(did, args)); p!(" upvar_tys=("); - if !substs.as_generator().is_valid() { + if !args.as_generator().is_valid() { p!("unavailable"); } else { - self = self.comma_sep(substs.as_generator().upvar_tys())?; + self = self.comma_sep(args.as_generator().upvar_tys())?; } p!(")"); - if substs.as_generator().is_valid() { - p!(" ", print(substs.as_generator().witness())); + if args.as_generator().is_valid() { + p!(" ", print(args.as_generator().witness())); } } @@ -840,7 +840,7 @@ pub trait PrettyPrinter<'tcx>: ty::GeneratorWitness(types) => { p!(in_binder(&types)); } - ty::GeneratorWitnessMIR(did, substs) => { + ty::GeneratorWitnessMIR(did, args) => { p!(write("[")); if !self.tcx().sess.verbose() { p!("generator witness"); @@ -854,22 +854,22 @@ pub trait PrettyPrinter<'tcx>: self.tcx().sess.source_map().span_to_embeddable_string(span) )); } else { - p!(write("@"), print_def_path(did, substs)); + p!(write("@"), print_def_path(did, args)); } } else { - p!(print_def_path(did, substs)); + p!(print_def_path(did, args)); } p!("]") } - ty::Closure(did, substs) => { + ty::Closure(did, args) => { p!(write("[")); if !self.should_print_verbose() { p!(write("closure")); // FIXME(eddyb) should use `def_span`. if let Some(did) = did.as_local() { if self.tcx().sess.opts.unstable_opts.span_free_formats { - p!("@", print_def_path(did.to_def_id(), substs)); + p!("@", print_def_path(did.to_def_id(), args)); } else { let span = self.tcx().def_span(did); let preference = if FORCE_TRIMMED_PATH.with(|flag| flag.get()) { @@ -885,21 +885,21 @@ pub trait PrettyPrinter<'tcx>: )); } } else { - p!(write("@"), print_def_path(did, substs)); + p!(write("@"), print_def_path(did, args)); } } else { - p!(print_def_path(did, substs)); - if !substs.as_closure().is_valid() { - p!(" closure_substs=(unavailable)"); - p!(write(" substs={:?}", substs)); + p!(print_def_path(did, args)); + if !args.as_closure().is_valid() { + p!(" closure_args=(unavailable)"); + p!(write(" args={:?}", args)); } else { - p!(" closure_kind_ty=", print(substs.as_closure().kind_ty())); + p!(" closure_kind_ty=", print(args.as_closure().kind_ty())); p!( " closure_sig_as_fn_ptr_ty=", - print(substs.as_closure().sig_as_fn_ptr_ty()) + print(args.as_closure().sig_as_fn_ptr_ty()) ); p!(" upvar_tys=("); - self = self.comma_sep(substs.as_closure().upvar_tys())?; + self = self.comma_sep(args.as_closure().upvar_tys())?; p!(")"); } } @@ -915,7 +915,7 @@ pub trait PrettyPrinter<'tcx>: fn pretty_print_opaque_impl_type( mut self, def_id: DefId, - substs: &'tcx ty::List<ty::GenericArg<'tcx>>, + args: &'tcx ty::List<ty::GenericArg<'tcx>>, ) -> Result<Self::Type, Self::Error> { let tcx = self.tcx(); @@ -928,7 +928,7 @@ pub trait PrettyPrinter<'tcx>: let mut is_sized = false; let mut lifetimes = SmallVec::<[ty::Region<'tcx>; 1]>::new(); - for (predicate, _) in bounds.subst_iter_copied(tcx, substs) { + for (predicate, _) in bounds.arg_iter_copied(tcx, args) { let bound_predicate = predicate.kind(); match bound_predicate.skip_binder() { @@ -978,9 +978,9 @@ pub trait PrettyPrinter<'tcx>: define_scoped_cx!(cx); // Get the (single) generic ty (the args) of this FnOnce trait ref. let generics = tcx.generics_of(trait_ref.def_id); - let args = generics.own_substs_no_defaults(tcx, trait_ref.substs); + let own_args = generics.own_args_no_defaults(tcx, trait_ref.args); - match (entry.return_ty, args[0].expect_ty()) { + match (entry.return_ty, own_args[0].expect_ty()) { // We can only print `impl Fn() -> ()` if we have a tuple of args and we recorded // a return type. (Some(return_ty), arg_tys) if matches!(arg_tys.kind(), ty::Tuple(_)) => { @@ -1044,12 +1044,12 @@ pub trait PrettyPrinter<'tcx>: p!(print(trait_ref.print_only_trait_name())); let generics = tcx.generics_of(trait_ref.def_id); - let args = generics.own_substs_no_defaults(tcx, trait_ref.substs); + let own_args = generics.own_args_no_defaults(tcx, trait_ref.args); - if !args.is_empty() || !assoc_items.is_empty() { + if !own_args.is_empty() || !assoc_items.is_empty() { let mut first = true; - for ty in args { + for ty in own_args { if first { p!("<"); first = false; @@ -1068,8 +1068,8 @@ pub trait PrettyPrinter<'tcx>: && assoc.trait_container(tcx) == tcx.lang_items().gen_trait() && assoc.name == rustc_span::sym::Return { - if let ty::Generator(_, substs, _) = substs.type_at(0).kind() { - let return_ty = substs.as_generator().return_ty(); + if let ty::Generator(_, args, _) = args.type_at(0).kind() { + let return_ty = args.as_generator().return_ty(); if !return_ty.is_ty_var() { return_ty.into() } else { @@ -1182,7 +1182,7 @@ pub trait PrettyPrinter<'tcx>: &def_key.disambiguated_data, ) }, - &alias_ty.substs[1..], + &alias_ty.args[1..], ) } @@ -1211,7 +1211,7 @@ pub trait PrettyPrinter<'tcx>: // Special-case `Fn(...) -> ...` and re-sugar it. let fn_trait_kind = cx.tcx().fn_trait_kind_from_def_id(principal.def_id); if !cx.should_print_verbose() && fn_trait_kind.is_some() { - if let ty::Tuple(tys) = principal.substs.type_at(0).kind() { + if let ty::Tuple(tys) = principal.args.type_at(0).kind() { let mut projections = predicates.projection_bounds(); if let (Some(proj), None) = (projections.next(), projections.next()) { p!(pretty_fn_sig( @@ -1234,7 +1234,7 @@ pub trait PrettyPrinter<'tcx>: let args = cx .tcx() .generics_of(principal.def_id) - .own_substs_no_defaults(cx.tcx(), principal.substs); + .own_args_no_defaults(cx.tcx(), principal.args); let mut projections = predicates.projection_bounds(); @@ -1341,10 +1341,10 @@ pub trait PrettyPrinter<'tcx>: } match ct.kind() { - ty::ConstKind::Unevaluated(ty::UnevaluatedConst { def, substs }) => { + ty::ConstKind::Unevaluated(ty::UnevaluatedConst { def, args }) => { match self.tcx().def_kind(def) { DefKind::Const | DefKind::AssocConst => { - p!(print_value_path(def, substs)) + p!(print_value_path(def, args)) } DefKind::AnonConst => { if def.is_local() @@ -1449,7 +1449,7 @@ pub trait PrettyPrinter<'tcx>: self.tcx().try_get_global_alloc(alloc_id) { self = self.typed_value( - |this| this.print_value_path(instance.def_id(), instance.substs), + |this| this.print_value_path(instance.def_id(), instance.args), |this| this.print_type(ty), " as ", )?; @@ -1619,11 +1619,11 @@ pub trait PrettyPrinter<'tcx>: ": ", )?; } - ty::Adt(def, substs) => { + ty::Adt(def, args) => { let variant_idx = contents.variant.expect("destructed const of adt without variant idx"); let variant_def = &def.variant(variant_idx); - p!(print_value_path(variant_def.def_id, substs)); + p!(print_value_path(variant_def.def_id, args)); match variant_def.ctor_kind() { Some(CtorKind::Const) => {} Some(CtorKind::Fn) => { @@ -1673,7 +1673,7 @@ pub trait PrettyPrinter<'tcx>: fn pretty_closure_as_impl( mut self, - closure: ty::ClosureSubsts<'tcx>, + closure: ty::ClosureArgs<'tcx>, ) -> Result<Self::Const, Self::Error> { let sig = closure.sig(); let kind = closure.kind_ty().to_opt_closure_kind().unwrap_or(ty::ClosureKind::Fn); @@ -1798,29 +1798,29 @@ impl<'t> TyCtxt<'t> { /// Returns a string identifying this `DefId`. This string is /// suitable for user output. pub fn def_path_str(self, def_id: impl IntoQueryParam<DefId>) -> String { - self.def_path_str_with_substs(def_id, &[]) + self.def_path_str_with_args(def_id, &[]) } - pub fn def_path_str_with_substs( + pub fn def_path_str_with_args( self, def_id: impl IntoQueryParam<DefId>, - substs: &'t [GenericArg<'t>], + args: &'t [GenericArg<'t>], ) -> String { let def_id = def_id.into_query_param(); let ns = guess_def_namespace(self, def_id); debug!("def_path_str: def_id={:?}, ns={:?}", def_id, ns); - FmtPrinter::new(self, ns).print_def_path(def_id, substs).unwrap().into_buffer() + FmtPrinter::new(self, ns).print_def_path(def_id, args).unwrap().into_buffer() } - pub fn value_path_str_with_substs( + pub fn value_path_str_with_args( self, def_id: impl IntoQueryParam<DefId>, - substs: &'t [GenericArg<'t>], + args: &'t [GenericArg<'t>], ) -> String { let def_id = def_id.into_query_param(); let ns = guess_def_namespace(self, def_id); debug!("value_path_str: def_id={:?}, ns={:?}", def_id, ns); - FmtPrinter::new(self, ns).print_value_path(def_id, substs).unwrap().into_buffer() + FmtPrinter::new(self, ns).print_value_path(def_id, args).unwrap().into_buffer() } } @@ -1847,11 +1847,11 @@ impl<'tcx> Printer<'tcx> for FmtPrinter<'_, 'tcx> { fn print_def_path( mut self, def_id: DefId, - substs: &'tcx [GenericArg<'tcx>], + args: &'tcx [GenericArg<'tcx>], ) -> Result<Self::Path, Self::Error> { define_scoped_cx!(self); - if substs.is_empty() { + if args.is_empty() { match self.try_print_trimmed_def_path(def_id)? { (cx, true) => return Ok(cx), (cx, false) => self = cx, @@ -1900,7 +1900,7 @@ impl<'tcx> Printer<'tcx> for FmtPrinter<'_, 'tcx> { } } - self.default_print_def_path(def_id, substs) + self.default_print_def_path(def_id, args) } fn print_region(self, region: ty::Region<'tcx>) -> Result<Self::Region, Self::Error> { @@ -2044,10 +2044,10 @@ impl<'tcx> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx> { fn print_value_path( mut self, def_id: DefId, - substs: &'tcx [GenericArg<'tcx>], + args: &'tcx [GenericArg<'tcx>], ) -> Result<Self::Path, Self::Error> { let was_in_value = std::mem::replace(&mut self.in_value, true); - self = self.print_def_path(def_id, substs)?; + self = self.print_def_path(def_id, args)?; self.in_value = was_in_value; Ok(self) @@ -2695,7 +2695,7 @@ impl<'tcx> ty::PolyTraitPredicate<'tcx> { #[derive(Debug, Copy, Clone, Lift)] pub struct PrintClosureAsImpl<'tcx> { - pub closure: ty::ClosureSubsts<'tcx>, + pub closure: ty::ClosureArgs<'tcx>, } forward_display_to_print! { @@ -2771,7 +2771,7 @@ define_print_and_forward_display! { } TraitRefPrintOnlyTraitPath<'tcx> { - p!(print_def_path(self.0.def_id, self.0.substs)); + p!(print_def_path(self.0.def_id, self.0.args)); } TraitRefPrintOnlyTraitName<'tcx> { @@ -2842,7 +2842,7 @@ define_print_and_forward_display! { if let DefKind::Impl { of_trait: false } = cx.tcx().def_kind(cx.tcx().parent(self.def_id)) { p!(pretty_print_inherent_projection(self)) } else { - p!(print_def_path(self.def_id, self.substs)); + p!(print_def_path(self.def_id, self.args)); } } @@ -2891,7 +2891,7 @@ define_print_and_forward_display! { ty::PredicateKind::ObjectSafe(trait_def_id) => { p!("the trait `", print_def_path(trait_def_id, &[]), "` is object-safe") } - ty::PredicateKind::ClosureKind(closure_def_id, _closure_substs, kind) => p!( + ty::PredicateKind::ClosureKind(closure_def_id, _closure_args, kind) => p!( "the closure `", print_value_path(closure_def_id, &[]), write("` implements the trait `{}`", kind) diff --git a/compiler/rustc_middle/src/ty/relate.rs b/compiler/rustc_middle/src/ty/relate.rs index 54dedf31d9f..bf9adabdab1 100644 --- a/compiler/rustc_middle/src/ty/relate.rs +++ b/compiler/rustc_middle/src/ty/relate.rs @@ -6,7 +6,7 @@ use crate::ty::error::{ExpectedFound, TypeError}; use crate::ty::{self, Expr, ImplSubject, Term, TermKind, Ty, TyCtxt, TypeFoldable}; -use crate::ty::{GenericArg, GenericArgKind, SubstsRef}; +use crate::ty::{GenericArg, GenericArgKind, GenericArgsRef}; use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_target::spec::abi; @@ -43,23 +43,23 @@ pub trait TypeRelation<'tcx>: Sized { Relate::relate(self, a, b) } - /// Relate the two substitutions for the given item. The default + /// Relate the two args for the given item. The default /// is to look up the variance for the item and proceed /// accordingly. - fn relate_item_substs( + fn relate_item_args( &mut self, item_def_id: DefId, - a_subst: SubstsRef<'tcx>, - b_subst: SubstsRef<'tcx>, - ) -> RelateResult<'tcx, SubstsRef<'tcx>> { + a_arg: GenericArgsRef<'tcx>, + b_arg: GenericArgsRef<'tcx>, + ) -> RelateResult<'tcx, GenericArgsRef<'tcx>> { debug!( - "relate_item_substs(item_def_id={:?}, a_subst={:?}, b_subst={:?})", - item_def_id, a_subst, b_subst + "relate_item_args(item_def_id={:?}, a_arg={:?}, b_arg={:?})", + item_def_id, a_arg, b_arg ); let tcx = self.tcx(); let opt_variances = tcx.variances_of(item_def_id); - relate_substs_with_variances(self, item_def_id, opt_variances, a_subst, b_subst, true) + relate_args_with_variances(self, item_def_id, opt_variances, a_arg, b_arg, true) } /// Switch variance for the purpose of relating `a` and `b`. @@ -134,31 +134,32 @@ pub fn relate_type_and_mut<'tcx, R: TypeRelation<'tcx>>( } #[inline] -pub fn relate_substs<'tcx, R: TypeRelation<'tcx>>( +pub fn relate_args<'tcx, R: TypeRelation<'tcx>>( relation: &mut R, - a_subst: SubstsRef<'tcx>, - b_subst: SubstsRef<'tcx>, -) -> RelateResult<'tcx, SubstsRef<'tcx>> { - relation.tcx().mk_substs_from_iter(iter::zip(a_subst, b_subst).map(|(a, b)| { + a_arg: GenericArgsRef<'tcx>, + b_arg: GenericArgsRef<'tcx>, +) -> RelateResult<'tcx, GenericArgsRef<'tcx>> { + relation.tcx().mk_args_from_iter(iter::zip(a_arg, b_arg).map(|(a, b)| { relation.relate_with_variance(ty::Invariant, ty::VarianceDiagInfo::default(), a, b) })) } -pub fn relate_substs_with_variances<'tcx, R: TypeRelation<'tcx>>( +pub fn relate_args_with_variances<'tcx, R: TypeRelation<'tcx>>( relation: &mut R, ty_def_id: DefId, variances: &[ty::Variance], - a_subst: SubstsRef<'tcx>, - b_subst: SubstsRef<'tcx>, + a_arg: GenericArgsRef<'tcx>, + b_arg: GenericArgsRef<'tcx>, fetch_ty_for_diag: bool, -) -> RelateResult<'tcx, SubstsRef<'tcx>> { +) -> RelateResult<'tcx, GenericArgsRef<'tcx>> { let tcx = relation.tcx(); let mut cached_ty = None; - let params = iter::zip(a_subst, b_subst).enumerate().map(|(i, (a, b))| { + let params = iter::zip(a_arg, b_arg).enumerate().map(|(i, (a, b))| { let variance = variances[i]; let variance_info = if variance == ty::Invariant && fetch_ty_for_diag { - let ty = *cached_ty.get_or_insert_with(|| tcx.type_of(ty_def_id).subst(tcx, a_subst)); + let ty = + *cached_ty.get_or_insert_with(|| tcx.type_of(ty_def_id).instantiate(tcx, a_arg)); ty::VarianceDiagInfo::Invariant { ty, param_index: i.try_into().unwrap() } } else { ty::VarianceDiagInfo::default() @@ -166,7 +167,7 @@ pub fn relate_substs_with_variances<'tcx, R: TypeRelation<'tcx>>( relation.relate_with_variance(variance, variance_info, a, b) }); - tcx.mk_substs_from_iter(params) + tcx.mk_args_from_iter(params) } impl<'tcx> Relate<'tcx> for ty::FnSig<'tcx> { @@ -272,8 +273,8 @@ impl<'tcx> Relate<'tcx> for ty::AliasTy<'tcx> { if a.def_id != b.def_id { Err(TypeError::ProjectionMismatched(expected_found(relation, a.def_id, b.def_id))) } else { - let substs = relation.relate(a.substs, b.substs)?; - Ok(relation.tcx().mk_alias_ty(a.def_id, substs)) + let args = relation.relate(a.args, b.args)?; + Ok(relation.tcx().mk_alias_ty(a.def_id, args)) } } } @@ -293,13 +294,13 @@ impl<'tcx> Relate<'tcx> for ty::ExistentialProjection<'tcx> { a.term, b.term, )?; - let substs = relation.relate_with_variance( + let args = relation.relate_with_variance( ty::Invariant, ty::VarianceDiagInfo::default(), - a.substs, - b.substs, + a.args, + b.args, )?; - Ok(ty::ExistentialProjection { def_id: a.def_id, substs, term }) + Ok(ty::ExistentialProjection { def_id: a.def_id, args, term }) } } } @@ -314,8 +315,8 @@ impl<'tcx> Relate<'tcx> for ty::TraitRef<'tcx> { if a.def_id != b.def_id { Err(TypeError::Traits(expected_found(relation, a.def_id, b.def_id))) } else { - let substs = relate_substs(relation, a.substs, b.substs)?; - Ok(ty::TraitRef::new(relation.tcx(), a.def_id, substs)) + let args = relate_args(relation, a.args, b.args)?; + Ok(ty::TraitRef::new(relation.tcx(), a.def_id, args)) } } } @@ -330,8 +331,8 @@ impl<'tcx> Relate<'tcx> for ty::ExistentialTraitRef<'tcx> { if a.def_id != b.def_id { Err(TypeError::Traits(expected_found(relation, a.def_id, b.def_id))) } else { - let substs = relate_substs(relation, a.substs, b.substs)?; - Ok(ty::ExistentialTraitRef { def_id: a.def_id, substs }) + let args = relate_args(relation, a.args, b.args)?; + Ok(ty::ExistentialTraitRef { def_id: a.def_id, args }) } } } @@ -426,9 +427,9 @@ pub fn structurally_relate_tys<'tcx, R: TypeRelation<'tcx>>( (ty::Placeholder(p1), ty::Placeholder(p2)) if p1 == p2 => Ok(a), - (&ty::Adt(a_def, a_substs), &ty::Adt(b_def, b_substs)) if a_def == b_def => { - let substs = relation.relate_item_substs(a_def.did(), a_substs, b_substs)?; - Ok(Ty::new_adt(tcx, a_def, substs)) + (&ty::Adt(a_def, a_args), &ty::Adt(b_def, b_args)) if a_def == b_def => { + let args = relation.relate_item_args(a_def.did(), a_args, b_args)?; + Ok(Ty::new_adt(tcx, a_def, args)) } (&ty::Foreign(a_id), &ty::Foreign(b_id)) if a_id == b_id => Ok(Ty::new_foreign(tcx, a_id)), @@ -442,14 +443,14 @@ pub fn structurally_relate_tys<'tcx, R: TypeRelation<'tcx>>( Ok(Ty::new_dynamic(tcx, relation.relate(a_obj, b_obj)?, region_bound, a_repr)) } - (&ty::Generator(a_id, a_substs, movability), &ty::Generator(b_id, b_substs, _)) + (&ty::Generator(a_id, a_args, movability), &ty::Generator(b_id, b_args, _)) if a_id == b_id => { // All Generator types with the same id represent // the (anonymous) type of the same generator expression. So // all of their regions should be equated. - let substs = relation.relate(a_substs, b_substs)?; - Ok(Ty::new_generator(tcx, a_id, substs, movability)) + let args = relation.relate(a_args, b_args)?; + Ok(Ty::new_generator(tcx, a_id, args, movability)) } (&ty::GeneratorWitness(a_types), &ty::GeneratorWitness(b_types)) => { @@ -462,22 +463,22 @@ pub fn structurally_relate_tys<'tcx, R: TypeRelation<'tcx>>( Ok(Ty::new_generator_witness(tcx, types)) } - (&ty::GeneratorWitnessMIR(a_id, a_substs), &ty::GeneratorWitnessMIR(b_id, b_substs)) + (&ty::GeneratorWitnessMIR(a_id, a_args), &ty::GeneratorWitnessMIR(b_id, b_args)) if a_id == b_id => { // All GeneratorWitness types with the same id represent // the (anonymous) type of the same generator expression. So // all of their regions should be equated. - let substs = relation.relate(a_substs, b_substs)?; - Ok(Ty::new_generator_witness_mir(tcx, a_id, substs)) + let args = relation.relate(a_args, b_args)?; + Ok(Ty::new_generator_witness_mir(tcx, a_id, args)) } - (&ty::Closure(a_id, a_substs), &ty::Closure(b_id, b_substs)) if a_id == b_id => { + (&ty::Closure(a_id, a_args), &ty::Closure(b_id, b_args)) if a_id == b_id => { // All Closure types with the same id represent // the (anonymous) type of the same closure expression. So // all of their regions should be equated. - let substs = relation.relate(a_substs, b_substs)?; - Ok(Ty::new_closure(tcx, a_id, &substs)) + let args = relation.relate(a_args, b_args)?; + Ok(Ty::new_closure(tcx, a_id, &args)) } (&ty::RawPtr(a_mt), &ty::RawPtr(b_mt)) => { @@ -535,11 +536,9 @@ pub fn structurally_relate_tys<'tcx, R: TypeRelation<'tcx>>( } } - (&ty::FnDef(a_def_id, a_substs), &ty::FnDef(b_def_id, b_substs)) - if a_def_id == b_def_id => - { - let substs = relation.relate_item_substs(a_def_id, a_substs, b_substs)?; - Ok(Ty::new_fn_def(tcx, a_def_id, substs)) + (&ty::FnDef(a_def_id, a_args), &ty::FnDef(b_def_id, b_args)) if a_def_id == b_def_id => { + let args = relation.relate_item_args(a_def_id, a_args, b_args)?; + Ok(Ty::new_fn_def(tcx, a_def_id, args)) } (&ty::FnPtr(a_fty), &ty::FnPtr(b_fty)) => { @@ -547,22 +546,22 @@ pub fn structurally_relate_tys<'tcx, R: TypeRelation<'tcx>>( Ok(Ty::new_fn_ptr(tcx, fty)) } - // The substs of opaque types may not all be invariant, so we have + // The args of opaque types may not all be invariant, so we have // to treat them separately from other aliases. ( - &ty::Alias(ty::Opaque, ty::AliasTy { def_id: a_def_id, substs: a_substs, .. }), - &ty::Alias(ty::Opaque, ty::AliasTy { def_id: b_def_id, substs: b_substs, .. }), + &ty::Alias(ty::Opaque, ty::AliasTy { def_id: a_def_id, args: a_args, .. }), + &ty::Alias(ty::Opaque, ty::AliasTy { def_id: b_def_id, args: b_args, .. }), ) if a_def_id == b_def_id => { let opt_variances = tcx.variances_of(a_def_id); - let substs = relate_substs_with_variances( + let args = relate_args_with_variances( relation, a_def_id, opt_variances, - a_substs, - b_substs, + a_args, + b_args, false, // do not fetch `type_of(a_def_id)`, as it will cause a cycle )?; - Ok(Ty::new_opaque(tcx, a_def_id, substs)) + Ok(Ty::new_opaque(tcx, a_def_id, args)) } // Alias tend to mostly already be handled downstream due to normalization. @@ -618,15 +617,15 @@ pub fn structurally_relate_consts<'tcx, R: TypeRelation<'tcx>>( // be stabilized. (ty::ConstKind::Unevaluated(au), ty::ConstKind::Unevaluated(bu)) if au.def == bu.def => { assert_eq!(a.ty(), b.ty()); - let substs = relation.relate_with_variance( + let args = relation.relate_with_variance( ty::Variance::Invariant, ty::VarianceDiagInfo::default(), - au.substs, - bu.substs, + au.args, + bu.args, )?; return Ok(ty::Const::new_unevaluated( tcx, - ty::UnevaluatedConst { def: au.def, substs }, + ty::UnevaluatedConst { def: au.def, args }, a.ty(), )); } @@ -640,7 +639,7 @@ pub fn structurally_relate_consts<'tcx, R: TypeRelation<'tcx>>( // FIXME(generic_const_exprs): relating the `ty()`s is a little weird since it is supposed to // ICE If they mismatch. Unfortunately `ConstKind::Expr` is a little special and can be thought // of as being generic over the argument types, however this is implicit so these types don't get - // related when we relate the substs of the item this const arg is for. + // related when we relate the args of the item this const arg is for. let expr = match (ae, be) { (Expr::Binop(a_op, al, ar), Expr::Binop(b_op, bl, br)) if a_op == b_op => { r.relate(al.ty(), bl.ty())?; @@ -714,35 +713,35 @@ impl<'tcx> Relate<'tcx> for &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>> { } } -impl<'tcx> Relate<'tcx> for ty::ClosureSubsts<'tcx> { +impl<'tcx> Relate<'tcx> for ty::ClosureArgs<'tcx> { fn relate<R: TypeRelation<'tcx>>( relation: &mut R, - a: ty::ClosureSubsts<'tcx>, - b: ty::ClosureSubsts<'tcx>, - ) -> RelateResult<'tcx, ty::ClosureSubsts<'tcx>> { - let substs = relate_substs(relation, a.substs, b.substs)?; - Ok(ty::ClosureSubsts { substs }) + a: ty::ClosureArgs<'tcx>, + b: ty::ClosureArgs<'tcx>, + ) -> RelateResult<'tcx, ty::ClosureArgs<'tcx>> { + let args = relate_args(relation, a.args, b.args)?; + Ok(ty::ClosureArgs { args }) } } -impl<'tcx> Relate<'tcx> for ty::GeneratorSubsts<'tcx> { +impl<'tcx> Relate<'tcx> for ty::GeneratorArgs<'tcx> { fn relate<R: TypeRelation<'tcx>>( relation: &mut R, - a: ty::GeneratorSubsts<'tcx>, - b: ty::GeneratorSubsts<'tcx>, - ) -> RelateResult<'tcx, ty::GeneratorSubsts<'tcx>> { - let substs = relate_substs(relation, a.substs, b.substs)?; - Ok(ty::GeneratorSubsts { substs }) + a: ty::GeneratorArgs<'tcx>, + b: ty::GeneratorArgs<'tcx>, + ) -> RelateResult<'tcx, ty::GeneratorArgs<'tcx>> { + let args = relate_args(relation, a.args, b.args)?; + Ok(ty::GeneratorArgs { args }) } } -impl<'tcx> Relate<'tcx> for SubstsRef<'tcx> { +impl<'tcx> Relate<'tcx> for GenericArgsRef<'tcx> { fn relate<R: TypeRelation<'tcx>>( relation: &mut R, - a: SubstsRef<'tcx>, - b: SubstsRef<'tcx>, - ) -> RelateResult<'tcx, SubstsRef<'tcx>> { - relate_substs(relation, a, b) + a: GenericArgsRef<'tcx>, + b: GenericArgsRef<'tcx>, + ) -> RelateResult<'tcx, GenericArgsRef<'tcx>> { + relate_args(relation, a, b) } } diff --git a/compiler/rustc_middle/src/ty/rvalue_scopes.rs b/compiler/rustc_middle/src/ty/rvalue_scopes.rs index e79b79a25ae..17eabec257e 100644 --- a/compiler/rustc_middle/src/ty/rvalue_scopes.rs +++ b/compiler/rustc_middle/src/ty/rvalue_scopes.rs @@ -1,12 +1,12 @@ use crate::middle::region::{Scope, ScopeData, ScopeTree}; -use rustc_data_structures::fx::FxHashMap; use rustc_hir as hir; +use rustc_hir::ItemLocalMap; /// `RvalueScopes` is a mapping from sub-expressions to _extended_ lifetime as determined by /// rules laid out in `rustc_hir_analysis::check::rvalue_scopes`. #[derive(TyEncodable, TyDecodable, Clone, Debug, Default, Eq, PartialEq, HashStable)] pub struct RvalueScopes { - map: FxHashMap<hir::ItemLocalId, Option<Scope>>, + map: ItemLocalMap<Option<Scope>>, } impl RvalueScopes { diff --git a/compiler/rustc_middle/src/ty/structural_impls.rs b/compiler/rustc_middle/src/ty/structural_impls.rs index 7220d133f68..9d380a58d9f 100644 --- a/compiler/rustc_middle/src/ty/structural_impls.rs +++ b/compiler/rustc_middle/src/ty/structural_impls.rs @@ -11,13 +11,15 @@ use crate::ty::{self, AliasTy, InferConst, Lift, Term, TermKind, Ty, TyCtxt}; use rustc_hir::def::Namespace; use rustc_index::{Idx, IndexVec}; use rustc_target::abi::TyAndLayout; -use rustc_type_ir::ConstKind; +use rustc_type_ir::{ConstKind, DebugWithInfcx, InferCtxtLike, OptWithInfcx}; -use std::fmt; +use std::fmt::{self, Debug}; use std::ops::ControlFlow; use std::rc::Rc; use std::sync::Arc; +use super::{GenericArg, GenericArgKind, Region}; + impl fmt::Debug for ty::TraitDef { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { ty::tls::with(|tcx| { @@ -89,7 +91,16 @@ impl fmt::Debug for ty::FreeRegion { impl<'tcx> fmt::Debug for ty::FnSig<'tcx> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let ty::FnSig { inputs_and_output: _, c_variadic, unsafety, abi } = self; + OptWithInfcx::new_no_ctx(self).fmt(f) + } +} +impl<'tcx> DebugWithInfcx<TyCtxt<'tcx>> for ty::FnSig<'tcx> { + fn fmt<InfCtx: InferCtxtLike<TyCtxt<'tcx>>>( + this: OptWithInfcx<'_, TyCtxt<'tcx>, InfCtx, &Self>, + f: &mut core::fmt::Formatter<'_>, + ) -> core::fmt::Result { + let sig = this.data; + let ty::FnSig { inputs_and_output: _, c_variadic, unsafety, abi } = sig; write!(f, "{}", unsafety.prefix_str())?; match abi { @@ -98,15 +109,15 @@ impl<'tcx> fmt::Debug for ty::FnSig<'tcx> { }; write!(f, "fn(")?; - let inputs = self.inputs(); + let inputs = sig.inputs(); match inputs.len() { 0 if *c_variadic => write!(f, "...)")?, 0 => write!(f, ")")?, _ => { - for ty in &self.inputs()[0..(self.inputs().len() - 1)] { - write!(f, "{ty:?}, ")?; + for ty in &sig.inputs()[0..(sig.inputs().len() - 1)] { + write!(f, "{:?}, ", &this.wrap(ty))?; } - write!(f, "{:?}", self.inputs().last().unwrap())?; + write!(f, "{:?}", &this.wrap(sig.inputs().last().unwrap()))?; if *c_variadic { write!(f, "...")?; } @@ -114,9 +125,9 @@ impl<'tcx> fmt::Debug for ty::FnSig<'tcx> { } } - match self.output().kind() { + match sig.output().kind() { ty::Tuple(list) if list.is_empty() => Ok(()), - _ => write!(f, " -> {:?}", self.output()), + _ => write!(f, " -> {:?}", &this.wrap(sig.output())), } } } @@ -133,6 +144,14 @@ impl<'tcx> fmt::Debug for ty::TraitRef<'tcx> { } } +impl<'tcx> ty::DebugWithInfcx<TyCtxt<'tcx>> for Ty<'tcx> { + fn fmt<InfCtx: InferCtxtLike<TyCtxt<'tcx>>>( + this: OptWithInfcx<'_, TyCtxt<'tcx>, InfCtx, &Self>, + f: &mut core::fmt::Formatter<'_>, + ) -> core::fmt::Result { + this.data.fmt(f) + } +} impl<'tcx> fmt::Debug for Ty<'tcx> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { with_no_trimmed_paths!(fmt::Display::fmt(self, f)) @@ -203,8 +222,8 @@ impl<'tcx> fmt::Debug for ty::PredicateKind<'tcx> { ty::PredicateKind::ObjectSafe(trait_def_id) => { write!(f, "ObjectSafe({:?})", trait_def_id) } - ty::PredicateKind::ClosureKind(closure_def_id, closure_substs, kind) => { - write!(f, "ClosureKind({:?}, {:?}, {:?})", closure_def_id, closure_substs, kind) + ty::PredicateKind::ClosureKind(closure_def_id, closure_args, kind) => { + write!(f, "ClosureKind({:?}, {:?}, {:?})", closure_def_id, closure_args, kind) } ty::PredicateKind::ConstEquate(c1, c2) => write!(f, "ConstEquate({:?}, {:?})", c1, c2), ty::PredicateKind::Ambiguous => write!(f, "Ambiguous"), @@ -217,9 +236,17 @@ impl<'tcx> fmt::Debug for ty::PredicateKind<'tcx> { impl<'tcx> fmt::Debug for AliasTy<'tcx> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + OptWithInfcx::new_no_ctx(self).fmt(f) + } +} +impl<'tcx> DebugWithInfcx<TyCtxt<'tcx>> for AliasTy<'tcx> { + fn fmt<InfCtx: InferCtxtLike<TyCtxt<'tcx>>>( + this: OptWithInfcx<'_, TyCtxt<'tcx>, InfCtx, &Self>, + f: &mut core::fmt::Formatter<'_>, + ) -> core::fmt::Result { f.debug_struct("AliasTy") - .field("substs", &self.substs) - .field("def_id", &self.def_id) + .field("args", &this.map(|data| data.args)) + .field("def_id", &this.data.def_id) .finish() } } @@ -232,13 +259,93 @@ impl<'tcx> fmt::Debug for ty::InferConst<'tcx> { } } } +impl<'tcx> DebugWithInfcx<TyCtxt<'tcx>> for ty::InferConst<'tcx> { + fn fmt<InfCtx: InferCtxtLike<TyCtxt<'tcx>>>( + this: OptWithInfcx<'_, TyCtxt<'tcx>, InfCtx, &Self>, + f: &mut core::fmt::Formatter<'_>, + ) -> core::fmt::Result { + use ty::InferConst::*; + match this.infcx.and_then(|infcx| infcx.universe_of_ct(*this.data)) { + None => write!(f, "{:?}", this.data), + Some(universe) => match *this.data { + Var(vid) => write!(f, "?{}_{}c", vid.index, universe.index()), + Fresh(_) => { + unreachable!() + } + }, + } + } +} + +impl<'tcx> fmt::Debug for ty::consts::Expr<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + OptWithInfcx::new_no_ctx(self).fmt(f) + } +} +impl<'tcx> DebugWithInfcx<TyCtxt<'tcx>> for ty::consts::Expr<'tcx> { + fn fmt<InfCtx: InferCtxtLike<TyCtxt<'tcx>>>( + this: OptWithInfcx<'_, TyCtxt<'tcx>, InfCtx, &Self>, + f: &mut core::fmt::Formatter<'_>, + ) -> core::fmt::Result { + match this.data { + ty::Expr::Binop(op, lhs, rhs) => { + write!(f, "({op:?}: {:?}, {:?})", &this.wrap(lhs), &this.wrap(rhs)) + } + ty::Expr::UnOp(op, rhs) => write!(f, "({op:?}: {:?})", &this.wrap(rhs)), + ty::Expr::FunctionCall(func, args) => { + write!(f, "{:?}(", &this.wrap(func))?; + for arg in args.as_slice().iter().rev().skip(1).rev() { + write!(f, "{:?}, ", &this.wrap(arg))?; + } + if let Some(arg) = args.last() { + write!(f, "{:?}", &this.wrap(arg))?; + } + + write!(f, ")") + } + ty::Expr::Cast(cast_kind, lhs, rhs) => { + write!(f, "({cast_kind:?}: {:?}, {:?})", &this.wrap(lhs), &this.wrap(rhs)) + } + } + } +} + +impl<'tcx> fmt::Debug for ty::UnevaluatedConst<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + OptWithInfcx::new_no_ctx(self).fmt(f) + } +} +impl<'tcx> DebugWithInfcx<TyCtxt<'tcx>> for ty::UnevaluatedConst<'tcx> { + fn fmt<InfCtx: InferCtxtLike<TyCtxt<'tcx>>>( + this: OptWithInfcx<'_, TyCtxt<'tcx>, InfCtx, &Self>, + f: &mut core::fmt::Formatter<'_>, + ) -> core::fmt::Result { + f.debug_struct("UnevaluatedConst") + .field("def", &this.data.def) + .field("args", &this.wrap(this.data.args)) + .finish() + } +} impl<'tcx> fmt::Debug for ty::Const<'tcx> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + OptWithInfcx::new_no_ctx(self).fmt(f) + } +} +impl<'tcx> DebugWithInfcx<TyCtxt<'tcx>> for ty::Const<'tcx> { + fn fmt<InfCtx: InferCtxtLike<TyCtxt<'tcx>>>( + this: OptWithInfcx<'_, TyCtxt<'tcx>, InfCtx, &Self>, + f: &mut core::fmt::Formatter<'_>, + ) -> core::fmt::Result { // This reflects what `Const` looked liked before `Interned` was // introduced. We print it like this to avoid having to update expected // output in a lot of tests. - write!(f, "Const {{ ty: {:?}, kind: {:?} }}", self.ty(), self.kind()) + write!( + f, + "Const {{ ty: {:?}, kind: {:?} }}", + &this.map(|data| data.ty()), + &this.map(|data| data.kind()) + ) } } @@ -261,6 +368,66 @@ impl<T: fmt::Debug> fmt::Debug for ty::Placeholder<T> { } } +impl<'tcx> fmt::Debug for GenericArg<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self.unpack() { + GenericArgKind::Lifetime(lt) => lt.fmt(f), + GenericArgKind::Type(ty) => ty.fmt(f), + GenericArgKind::Const(ct) => ct.fmt(f), + } + } +} +impl<'tcx> DebugWithInfcx<TyCtxt<'tcx>> for GenericArg<'tcx> { + fn fmt<InfCtx: InferCtxtLike<TyCtxt<'tcx>>>( + this: OptWithInfcx<'_, TyCtxt<'tcx>, InfCtx, &Self>, + f: &mut core::fmt::Formatter<'_>, + ) -> core::fmt::Result { + match this.data.unpack() { + GenericArgKind::Lifetime(lt) => write!(f, "{:?}", &this.wrap(lt)), + GenericArgKind::Const(ct) => write!(f, "{:?}", &this.wrap(ct)), + GenericArgKind::Type(ty) => write!(f, "{:?}", &this.wrap(ty)), + } + } +} + +impl<'tcx> fmt::Debug for Region<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{:?}", self.kind()) + } +} +impl<'tcx> DebugWithInfcx<TyCtxt<'tcx>> for Region<'tcx> { + fn fmt<InfCtx: InferCtxtLike<TyCtxt<'tcx>>>( + this: OptWithInfcx<'_, TyCtxt<'tcx>, InfCtx, &Self>, + f: &mut core::fmt::Formatter<'_>, + ) -> core::fmt::Result { + write!(f, "{:?}", &this.map(|data| data.kind())) + } +} + +impl<'tcx> DebugWithInfcx<TyCtxt<'tcx>> for ty::RegionVid { + fn fmt<InfCtx: InferCtxtLike<TyCtxt<'tcx>>>( + this: OptWithInfcx<'_, TyCtxt<'tcx>, InfCtx, &Self>, + f: &mut core::fmt::Formatter<'_>, + ) -> core::fmt::Result { + match this.infcx.and_then(|infcx| infcx.universe_of_lt(*this.data)) { + Some(universe) => write!(f, "'?{}_{}", this.data.index(), universe.index()), + None => write!(f, "{:?}", this.data), + } + } +} + +impl<'tcx, T: DebugWithInfcx<TyCtxt<'tcx>>> DebugWithInfcx<TyCtxt<'tcx>> for ty::Binder<'tcx, T> { + fn fmt<InfCtx: InferCtxtLike<TyCtxt<'tcx>>>( + this: OptWithInfcx<'_, TyCtxt<'tcx>, InfCtx, &Self>, + f: &mut core::fmt::Formatter<'_>, + ) -> core::fmt::Result { + f.debug_tuple("Binder") + .field(&this.map(|data| data.as_ref().skip_binder())) + .field(&this.data.bound_vars()) + .finish() + } +} + /////////////////////////////////////////////////////////////////////////// // Atomic structs // @@ -528,26 +695,26 @@ impl<'tcx> TypeSuperFoldable<TyCtxt<'tcx>> for Ty<'tcx> { ty::RawPtr(tm) => ty::RawPtr(tm.try_fold_with(folder)?), ty::Array(typ, sz) => ty::Array(typ.try_fold_with(folder)?, sz.try_fold_with(folder)?), ty::Slice(typ) => ty::Slice(typ.try_fold_with(folder)?), - ty::Adt(tid, substs) => ty::Adt(tid, substs.try_fold_with(folder)?), + ty::Adt(tid, args) => ty::Adt(tid, args.try_fold_with(folder)?), ty::Dynamic(trait_ty, region, representation) => ty::Dynamic( trait_ty.try_fold_with(folder)?, region.try_fold_with(folder)?, representation, ), ty::Tuple(ts) => ty::Tuple(ts.try_fold_with(folder)?), - ty::FnDef(def_id, substs) => ty::FnDef(def_id, substs.try_fold_with(folder)?), + ty::FnDef(def_id, args) => ty::FnDef(def_id, args.try_fold_with(folder)?), ty::FnPtr(f) => ty::FnPtr(f.try_fold_with(folder)?), ty::Ref(r, ty, mutbl) => { ty::Ref(r.try_fold_with(folder)?, ty.try_fold_with(folder)?, mutbl) } - ty::Generator(did, substs, movability) => { - ty::Generator(did, substs.try_fold_with(folder)?, movability) + ty::Generator(did, args, movability) => { + ty::Generator(did, args.try_fold_with(folder)?, movability) } ty::GeneratorWitness(types) => ty::GeneratorWitness(types.try_fold_with(folder)?), - ty::GeneratorWitnessMIR(did, substs) => { - ty::GeneratorWitnessMIR(did, substs.try_fold_with(folder)?) + ty::GeneratorWitnessMIR(did, args) => { + ty::GeneratorWitnessMIR(did, args.try_fold_with(folder)?) } - ty::Closure(did, substs) => ty::Closure(did, substs.try_fold_with(folder)?), + ty::Closure(did, args) => ty::Closure(did, args.try_fold_with(folder)?), ty::Alias(kind, data) => ty::Alias(kind, data.try_fold_with(folder)?), ty::Bool @@ -581,22 +748,22 @@ impl<'tcx> TypeSuperVisitable<TyCtxt<'tcx>> for Ty<'tcx> { sz.visit_with(visitor) } ty::Slice(typ) => typ.visit_with(visitor), - ty::Adt(_, substs) => substs.visit_with(visitor), + ty::Adt(_, args) => args.visit_with(visitor), ty::Dynamic(ref trait_ty, ref reg, _) => { trait_ty.visit_with(visitor)?; reg.visit_with(visitor) } ty::Tuple(ts) => ts.visit_with(visitor), - ty::FnDef(_, substs) => substs.visit_with(visitor), + ty::FnDef(_, args) => args.visit_with(visitor), ty::FnPtr(ref f) => f.visit_with(visitor), ty::Ref(r, ty, _) => { r.visit_with(visitor)?; ty.visit_with(visitor) } - ty::Generator(_did, ref substs, _) => substs.visit_with(visitor), + ty::Generator(_did, ref args, _) => args.visit_with(visitor), ty::GeneratorWitness(ref types) => types.visit_with(visitor), - ty::GeneratorWitnessMIR(_did, ref substs) => substs.visit_with(visitor), - ty::Closure(_did, ref substs) => substs.visit_with(visitor), + ty::GeneratorWitnessMIR(_did, ref args) => args.visit_with(visitor), + ty::Closure(_did, ref args) => args.visit_with(visitor), ty::Alias(_, ref data) => data.visit_with(visitor), ty::Bool @@ -776,7 +943,7 @@ impl<'tcx> TypeSuperVisitable<TyCtxt<'tcx>> for ty::UnevaluatedConst<'tcx> { &self, visitor: &mut V, ) -> ControlFlow<V::BreakTy> { - self.substs.visit_with(visitor) + self.args.visit_with(visitor) } } diff --git a/compiler/rustc_middle/src/ty/sty.rs b/compiler/rustc_middle/src/ty/sty.rs index 2c4ff575755..cdb0b2240a4 100644 --- a/compiler/rustc_middle/src/ty/sty.rs +++ b/compiler/rustc_middle/src/ty/sty.rs @@ -3,13 +3,13 @@ #![allow(rustc::usage_of_ty_tykind)] use crate::infer::canonical::Canonical; -use crate::ty::subst::{GenericArg, InternalSubsts, SubstsRef}; use crate::ty::visit::ValidateBoundVars; use crate::ty::InferTy::*; use crate::ty::{ self, AdtDef, Discr, Term, Ty, TyCtxt, TypeFlags, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, }; +use crate::ty::{GenericArg, GenericArgs, GenericArgsRef}; use crate::ty::{List, ParamEnv}; use hir::def::DefKind; use polonius_engine::Atom; @@ -35,9 +35,12 @@ use std::ops::{ControlFlow, Deref, Range}; use ty::util::IntTypeExt; use rustc_type_ir::sty::TyKind::*; +use rustc_type_ir::CollectAndApply; +use rustc_type_ir::ConstKind as IrConstKind; +use rustc_type_ir::DebugWithInfcx; +use rustc_type_ir::DynKind; +use rustc_type_ir::RegionKind as IrRegionKind; use rustc_type_ir::TyKind as IrTyKind; -use rustc_type_ir::{CollectAndApply, ConstKind as IrConstKind}; -use rustc_type_ir::{DynKind, RegionKind as IrRegionKind}; use super::GenericParamDefKind; @@ -215,7 +218,7 @@ impl<'tcx> Article for TyKind<'tcx> { /// /// ## Generators /// -/// Generators are handled similarly in `GeneratorSubsts`. The set of +/// Generators are handled similarly in `GeneratorArgs`. The set of /// type parameters is similar, but `CK` and `CS` are replaced by the /// following type parameters: /// @@ -228,33 +231,30 @@ impl<'tcx> Article for TyKind<'tcx> { /// completion of the generator. /// * `GW`: The "generator witness". #[derive(Copy, Clone, PartialEq, Eq, Debug, TypeFoldable, TypeVisitable, Lift)] -pub struct ClosureSubsts<'tcx> { +pub struct ClosureArgs<'tcx> { /// Lifetime and type parameters from the enclosing function, /// concatenated with a tuple containing the types of the upvars. /// /// These are separated out because codegen wants to pass them around /// when monomorphizing. - pub substs: SubstsRef<'tcx>, + pub args: GenericArgsRef<'tcx>, } /// Struct returned by `split()`. -pub struct ClosureSubstsParts<'tcx, T> { - pub parent_substs: &'tcx [GenericArg<'tcx>], +pub struct ClosureArgsParts<'tcx, T> { + pub parent_args: &'tcx [GenericArg<'tcx>], pub closure_kind_ty: T, pub closure_sig_as_fn_ptr_ty: T, pub tupled_upvars_ty: T, } -impl<'tcx> ClosureSubsts<'tcx> { - /// Construct `ClosureSubsts` from `ClosureSubstsParts`, containing `Substs` +impl<'tcx> ClosureArgs<'tcx> { + /// Construct `ClosureArgs` from `ClosureArgsParts`, containing `Args` /// for the closure parent, alongside additional closure-specific components. - pub fn new( - tcx: TyCtxt<'tcx>, - parts: ClosureSubstsParts<'tcx, Ty<'tcx>>, - ) -> ClosureSubsts<'tcx> { - ClosureSubsts { - substs: tcx.mk_substs_from_iter( - parts.parent_substs.iter().copied().chain( + pub fn new(tcx: TyCtxt<'tcx>, parts: ClosureArgsParts<'tcx, Ty<'tcx>>) -> ClosureArgs<'tcx> { + ClosureArgs { + args: tcx.mk_args_from_iter( + parts.parent_args.iter().copied().chain( [parts.closure_kind_ty, parts.closure_sig_as_fn_ptr_ty, parts.tupled_upvars_ty] .iter() .map(|&ty| ty.into()), @@ -263,38 +263,34 @@ impl<'tcx> ClosureSubsts<'tcx> { } } - /// Divides the closure substs into their respective components. - /// The ordering assumed here must match that used by `ClosureSubsts::new` above. - fn split(self) -> ClosureSubstsParts<'tcx, GenericArg<'tcx>> { - match self.substs[..] { - [ - ref parent_substs @ .., - closure_kind_ty, - closure_sig_as_fn_ptr_ty, - tupled_upvars_ty, - ] => ClosureSubstsParts { - parent_substs, - closure_kind_ty, - closure_sig_as_fn_ptr_ty, - tupled_upvars_ty, - }, - _ => bug!("closure substs missing synthetics"), + /// Divides the closure args into their respective components. + /// The ordering assumed here must match that used by `ClosureArgs::new` above. + fn split(self) -> ClosureArgsParts<'tcx, GenericArg<'tcx>> { + match self.args[..] { + [ref parent_args @ .., closure_kind_ty, closure_sig_as_fn_ptr_ty, tupled_upvars_ty] => { + ClosureArgsParts { + parent_args, + closure_kind_ty, + closure_sig_as_fn_ptr_ty, + tupled_upvars_ty, + } + } + _ => bug!("closure args missing synthetics"), } } /// Returns `true` only if enough of the synthetic types are known to - /// allow using all of the methods on `ClosureSubsts` without panicking. + /// allow using all of the methods on `ClosureArgs` without panicking. /// /// Used primarily by `ty::print::pretty` to be able to handle closure /// types that haven't had their synthetic types substituted in. pub fn is_valid(self) -> bool { - self.substs.len() >= 3 - && matches!(self.split().tupled_upvars_ty.expect_ty().kind(), Tuple(_)) + self.args.len() >= 3 && matches!(self.split().tupled_upvars_ty.expect_ty().kind(), Tuple(_)) } /// Returns the substitutions of the closure's parent. - pub fn parent_substs(self) -> &'tcx [GenericArg<'tcx>] { - self.split().parent_substs + pub fn parent_args(self) -> &'tcx [GenericArg<'tcx>] { + self.split().parent_args } /// Returns an iterator over the list of types of captured paths by the closure. @@ -320,7 +316,7 @@ impl<'tcx> ClosureSubsts<'tcx> { /// Returns the closure kind for this closure; may return a type /// variable during inference. To get the closure kind during - /// inference, use `infcx.closure_kind(substs)`. + /// inference, use `infcx.closure_kind(args)`. pub fn kind_ty(self) -> Ty<'tcx> { self.split().closure_kind_ty.expect_ty() } @@ -328,7 +324,7 @@ impl<'tcx> ClosureSubsts<'tcx> { /// Returns the `fn` pointer type representing the closure signature for this /// closure. // FIXME(eddyb) this should be unnecessary, as the shallowly resolved - // type is known at the time of the creation of `ClosureSubsts`, + // type is known at the time of the creation of `ClosureArgs`, // see `rustc_hir_analysis::check::closure`. pub fn sig_as_fn_ptr_ty(self) -> Ty<'tcx> { self.split().closure_sig_as_fn_ptr_ty.expect_ty() @@ -357,14 +353,14 @@ impl<'tcx> ClosureSubsts<'tcx> { } } -/// Similar to `ClosureSubsts`; see the above documentation for more. +/// Similar to `ClosureArgs`; see the above documentation for more. #[derive(Copy, Clone, PartialEq, Eq, Debug, TypeFoldable, TypeVisitable, Lift)] -pub struct GeneratorSubsts<'tcx> { - pub substs: SubstsRef<'tcx>, +pub struct GeneratorArgs<'tcx> { + pub args: GenericArgsRef<'tcx>, } -pub struct GeneratorSubstsParts<'tcx, T> { - pub parent_substs: &'tcx [GenericArg<'tcx>], +pub struct GeneratorArgsParts<'tcx, T> { + pub parent_args: &'tcx [GenericArg<'tcx>], pub resume_ty: T, pub yield_ty: T, pub return_ty: T, @@ -372,16 +368,16 @@ pub struct GeneratorSubstsParts<'tcx, T> { pub tupled_upvars_ty: T, } -impl<'tcx> GeneratorSubsts<'tcx> { - /// Construct `GeneratorSubsts` from `GeneratorSubstsParts`, containing `Substs` +impl<'tcx> GeneratorArgs<'tcx> { + /// Construct `GeneratorArgs` from `GeneratorArgsParts`, containing `Args` /// for the generator parent, alongside additional generator-specific components. pub fn new( tcx: TyCtxt<'tcx>, - parts: GeneratorSubstsParts<'tcx, Ty<'tcx>>, - ) -> GeneratorSubsts<'tcx> { - GeneratorSubsts { - substs: tcx.mk_substs_from_iter( - parts.parent_substs.iter().copied().chain( + parts: GeneratorArgsParts<'tcx, Ty<'tcx>>, + ) -> GeneratorArgs<'tcx> { + GeneratorArgs { + args: tcx.mk_args_from_iter( + parts.parent_args.iter().copied().chain( [ parts.resume_ty, parts.yield_ty, @@ -396,13 +392,13 @@ impl<'tcx> GeneratorSubsts<'tcx> { } } - /// Divides the generator substs into their respective components. - /// The ordering assumed here must match that used by `GeneratorSubsts::new` above. - fn split(self) -> GeneratorSubstsParts<'tcx, GenericArg<'tcx>> { - match self.substs[..] { - [ref parent_substs @ .., resume_ty, yield_ty, return_ty, witness, tupled_upvars_ty] => { - GeneratorSubstsParts { - parent_substs, + /// Divides the generator args into their respective components. + /// The ordering assumed here must match that used by `GeneratorArgs::new` above. + fn split(self) -> GeneratorArgsParts<'tcx, GenericArg<'tcx>> { + match self.args[..] { + [ref parent_args @ .., resume_ty, yield_ty, return_ty, witness, tupled_upvars_ty] => { + GeneratorArgsParts { + parent_args, resume_ty, yield_ty, return_ty, @@ -410,23 +406,22 @@ impl<'tcx> GeneratorSubsts<'tcx> { tupled_upvars_ty, } } - _ => bug!("generator substs missing synthetics"), + _ => bug!("generator args missing synthetics"), } } /// Returns `true` only if enough of the synthetic types are known to - /// allow using all of the methods on `GeneratorSubsts` without panicking. + /// allow using all of the methods on `GeneratorArgs` without panicking. /// /// Used primarily by `ty::print::pretty` to be able to handle generator /// types that haven't had their synthetic types substituted in. pub fn is_valid(self) -> bool { - self.substs.len() >= 5 - && matches!(self.split().tupled_upvars_ty.expect_ty().kind(), Tuple(_)) + self.args.len() >= 5 && matches!(self.split().tupled_upvars_ty.expect_ty().kind(), Tuple(_)) } /// Returns the substitutions of the generator's parent. - pub fn parent_substs(self) -> &'tcx [GenericArg<'tcx>] { - self.split().parent_substs + pub fn parent_args(self) -> &'tcx [GenericArg<'tcx>] { + self.split().parent_args } /// This describes the types that can be contained in a generator. @@ -495,7 +490,7 @@ impl<'tcx> GeneratorSubsts<'tcx> { } } -impl<'tcx> GeneratorSubsts<'tcx> { +impl<'tcx> GeneratorArgs<'tcx> { /// Generator has not been resumed yet. pub const UNRESUMED: usize = 0; /// Generator has returned or is completed. @@ -574,7 +569,7 @@ impl<'tcx> GeneratorSubsts<'tcx> { let layout = tcx.generator_layout(def_id).unwrap(); layout.variant_fields.iter().map(move |variant| { variant.iter().map(move |field| { - ty::EarlyBinder::bind(layout.field_tys[*field].ty).subst(tcx, self.substs) + ty::EarlyBinder::bind(layout.field_tys[*field].ty).instantiate(tcx, self.args) }) }) } @@ -588,20 +583,20 @@ impl<'tcx> GeneratorSubsts<'tcx> { } #[derive(Debug, Copy, Clone, HashStable)] -pub enum UpvarSubsts<'tcx> { - Closure(SubstsRef<'tcx>), - Generator(SubstsRef<'tcx>), +pub enum UpvarArgs<'tcx> { + Closure(GenericArgsRef<'tcx>), + Generator(GenericArgsRef<'tcx>), } -impl<'tcx> UpvarSubsts<'tcx> { +impl<'tcx> UpvarArgs<'tcx> { /// Returns an iterator over the list of types of captured paths by the closure/generator. /// In case there was a type error in figuring out the types of the captured path, an /// empty iterator is returned. #[inline] pub fn upvar_tys(self) -> impl Iterator<Item = Ty<'tcx>> + 'tcx { let tupled_tys = match self { - UpvarSubsts::Closure(substs) => substs.as_closure().tupled_upvars_ty(), - UpvarSubsts::Generator(substs) => substs.as_generator().tupled_upvars_ty(), + UpvarArgs::Closure(args) => args.as_closure().tupled_upvars_ty(), + UpvarArgs::Generator(args) => args.as_generator().tupled_upvars_ty(), }; match tupled_tys.kind() { @@ -617,8 +612,8 @@ impl<'tcx> UpvarSubsts<'tcx> { #[inline] pub fn tupled_upvars_ty(self) -> Ty<'tcx> { match self { - UpvarSubsts::Closure(substs) => substs.as_closure().tupled_upvars_ty(), - UpvarSubsts::Generator(substs) => substs.as_generator().tupled_upvars_ty(), + UpvarArgs::Closure(args) => args.as_closure().tupled_upvars_ty(), + UpvarArgs::Generator(args) => args.as_generator().tupled_upvars_ty(), } } } @@ -635,46 +630,46 @@ impl<'tcx> UpvarSubsts<'tcx> { /// /// When the inline const is instantiated, `R` is substituted as the actual inferred /// type of the constant. The reason that `R` is represented as an extra type parameter -/// is the same reason that [`ClosureSubsts`] have `CS` and `U` as type parameters: +/// is the same reason that [`ClosureArgs`] have `CS` and `U` as type parameters: /// inline const can reference lifetimes that are internal to the creating function. #[derive(Copy, Clone, Debug)] -pub struct InlineConstSubsts<'tcx> { +pub struct InlineConstArgs<'tcx> { /// Generic parameters from the enclosing item, /// concatenated with the inferred type of the constant. - pub substs: SubstsRef<'tcx>, + pub args: GenericArgsRef<'tcx>, } /// Struct returned by `split()`. -pub struct InlineConstSubstsParts<'tcx, T> { - pub parent_substs: &'tcx [GenericArg<'tcx>], +pub struct InlineConstArgsParts<'tcx, T> { + pub parent_args: &'tcx [GenericArg<'tcx>], pub ty: T, } -impl<'tcx> InlineConstSubsts<'tcx> { - /// Construct `InlineConstSubsts` from `InlineConstSubstsParts`. +impl<'tcx> InlineConstArgs<'tcx> { + /// Construct `InlineConstArgs` from `InlineConstArgsParts`. pub fn new( tcx: TyCtxt<'tcx>, - parts: InlineConstSubstsParts<'tcx, Ty<'tcx>>, - ) -> InlineConstSubsts<'tcx> { - InlineConstSubsts { - substs: tcx.mk_substs_from_iter( - parts.parent_substs.iter().copied().chain(std::iter::once(parts.ty.into())), + parts: InlineConstArgsParts<'tcx, Ty<'tcx>>, + ) -> InlineConstArgs<'tcx> { + InlineConstArgs { + args: tcx.mk_args_from_iter( + parts.parent_args.iter().copied().chain(std::iter::once(parts.ty.into())), ), } } - /// Divides the inline const substs into their respective components. - /// The ordering assumed here must match that used by `InlineConstSubsts::new` above. - fn split(self) -> InlineConstSubstsParts<'tcx, GenericArg<'tcx>> { - match self.substs[..] { - [ref parent_substs @ .., ty] => InlineConstSubstsParts { parent_substs, ty }, - _ => bug!("inline const substs missing synthetics"), + /// Divides the inline const args into their respective components. + /// The ordering assumed here must match that used by `InlineConstArgs::new` above. + fn split(self) -> InlineConstArgsParts<'tcx, GenericArg<'tcx>> { + match self.args[..] { + [ref parent_args @ .., ty] => InlineConstArgsParts { parent_args, ty }, + _ => bug!("inline const args missing synthetics"), } } /// Returns the substitutions of the inline const's parent. - pub fn parent_substs(self) -> &'tcx [GenericArg<'tcx>] { - self.split().parent_substs + pub fn parent_args(self) -> &'tcx [GenericArg<'tcx>] { + self.split().parent_args } /// Returns the type of this inline const. @@ -694,6 +689,15 @@ pub enum ExistentialPredicate<'tcx> { AutoTrait(DefId), } +impl<'tcx> DebugWithInfcx<TyCtxt<'tcx>> for ExistentialPredicate<'tcx> { + fn fmt<InfCtx: rustc_type_ir::InferCtxtLike<TyCtxt<'tcx>>>( + this: rustc_type_ir::OptWithInfcx<'_, TyCtxt<'tcx>, InfCtx, &Self>, + f: &mut core::fmt::Formatter<'_>, + ) -> core::fmt::Result { + fmt::Debug::fmt(&this.data, f) + } +} + impl<'tcx> ExistentialPredicate<'tcx> { /// Compares via an ordering that will not change if modules are reordered or other changes are /// made to the tree. In particular, this ordering is preserved across incremental compilations. @@ -736,10 +740,9 @@ impl<'tcx> PolyExistentialPredicate<'tcx> { ty::TraitRef::new(tcx, did, [self_ty]) } else { // If this is an ill-formed auto trait, then synthesize - // new error substs for the missing generics. - let err_substs = - ty::InternalSubsts::extend_with_error(tcx, did, &[self_ty.into()]); - ty::TraitRef::new(tcx, did, err_substs) + // new error args for the missing generics. + let err_args = ty::GenericArgs::extend_with_error(tcx, did, &[self_ty.into()]); + ty::TraitRef::new(tcx, did, err_args) }; self.rebind(trait_ref).without_const().to_predicate(tcx) } @@ -815,7 +818,7 @@ impl<'tcx> List<ty::PolyExistentialPredicate<'tcx>> { /// T: Foo<U> /// ``` /// This would be represented by a trait-reference where the `DefId` is the -/// `DefId` for the trait `Foo` and the substs define `T` as parameter 0, +/// `DefId` for the trait `Foo` and the args define `T` as parameter 0, /// and `U` as parameter 1. /// /// Trait references also appear in object types like `Foo<U>`, but in @@ -824,7 +827,7 @@ impl<'tcx> List<ty::PolyExistentialPredicate<'tcx>> { #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)] pub struct TraitRef<'tcx> { pub def_id: DefId, - pub substs: SubstsRef<'tcx>, + pub args: GenericArgsRef<'tcx>, /// This field exists to prevent the creation of `TraitRef` without /// calling [`TraitRef::new`]. pub(super) _use_trait_ref_new_instead: (), @@ -834,42 +837,42 @@ impl<'tcx> TraitRef<'tcx> { pub fn new( tcx: TyCtxt<'tcx>, trait_def_id: DefId, - substs: impl IntoIterator<Item: Into<GenericArg<'tcx>>>, + args: impl IntoIterator<Item: Into<GenericArg<'tcx>>>, ) -> Self { - let substs = tcx.check_and_mk_substs(trait_def_id, substs); - Self { def_id: trait_def_id, substs, _use_trait_ref_new_instead: () } + let args = tcx.check_and_mk_args(trait_def_id, args); + Self { def_id: trait_def_id, args, _use_trait_ref_new_instead: () } } pub fn from_lang_item( tcx: TyCtxt<'tcx>, trait_lang_item: LangItem, span: Span, - substs: impl IntoIterator<Item: Into<ty::GenericArg<'tcx>>>, + args: impl IntoIterator<Item: Into<ty::GenericArg<'tcx>>>, ) -> Self { let trait_def_id = tcx.require_lang_item(trait_lang_item, Some(span)); - Self::new(tcx, trait_def_id, substs) + Self::new(tcx, trait_def_id, args) } pub fn from_method( tcx: TyCtxt<'tcx>, trait_id: DefId, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, ) -> ty::TraitRef<'tcx> { let defs = tcx.generics_of(trait_id); - ty::TraitRef::new(tcx, trait_id, tcx.mk_substs(&substs[..defs.params.len()])) + ty::TraitRef::new(tcx, trait_id, tcx.mk_args(&args[..defs.params.len()])) } /// Returns a `TraitRef` of the form `P0: Foo<P1..Pn>` where `Pi` /// are the parameters defined on trait. pub fn identity(tcx: TyCtxt<'tcx>, def_id: DefId) -> TraitRef<'tcx> { - ty::TraitRef::new(tcx, def_id, InternalSubsts::identity_for_item(tcx, def_id)) + ty::TraitRef::new(tcx, def_id, GenericArgs::identity_for_item(tcx, def_id)) } pub fn with_self_ty(self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> Self { ty::TraitRef::new( tcx, self.def_id, - [self_ty.into()].into_iter().chain(self.substs.iter().skip(1)), + [self_ty.into()].into_iter().chain(self.args.iter().skip(1)), ) } @@ -887,7 +890,7 @@ impl<'tcx> TraitRef<'tcx> { #[inline] pub fn self_ty(&self) -> Ty<'tcx> { - self.substs.type_at(0) + self.args.type_at(0) } } @@ -920,7 +923,7 @@ impl<'tcx> IntoDiagnosticArg for TraitRef<'tcx> { #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)] pub struct ExistentialTraitRef<'tcx> { pub def_id: DefId, - pub substs: SubstsRef<'tcx>, + pub args: GenericArgsRef<'tcx>, } impl<'tcx> ExistentialTraitRef<'tcx> { @@ -929,11 +932,11 @@ impl<'tcx> ExistentialTraitRef<'tcx> { trait_ref: ty::TraitRef<'tcx>, ) -> ty::ExistentialTraitRef<'tcx> { // Assert there is a Self. - trait_ref.substs.type_at(0); + trait_ref.args.type_at(0); ty::ExistentialTraitRef { def_id: trait_ref.def_id, - substs: tcx.mk_substs(&trait_ref.substs[1..]), + args: tcx.mk_args(&trait_ref.args[1..]), } } @@ -945,7 +948,7 @@ impl<'tcx> ExistentialTraitRef<'tcx> { // otherwise the escaping vars would be captured by the binder // debug_assert!(!self_ty.has_escaping_bound_vars()); - ty::TraitRef::new(tcx, self.def_id, [self_ty.into()].into_iter().chain(self.substs.iter())) + ty::TraitRef::new(tcx, self.def_id, [self_ty.into()].into_iter().chain(self.args.iter())) } } @@ -1214,7 +1217,7 @@ pub struct AliasTy<'tcx> { /// /// For RPIT the substitutions are for the generics of the function, /// while for TAIT it is used for the generic parameters of the alias. - pub substs: SubstsRef<'tcx>, + pub args: GenericArgsRef<'tcx>, /// The `DefId` of the `TraitItem` or `ImplItem` for the associated type `N` depending on whether /// this is a projection or an inherent projection or the `DefId` of the `OpaqueType` item if @@ -1252,11 +1255,11 @@ impl<'tcx> AliasTy<'tcx> { /// The following methods work only with associated type projections. impl<'tcx> AliasTy<'tcx> { pub fn self_ty(self) -> Ty<'tcx> { - self.substs.type_at(0) + self.args.type_at(0) } pub fn with_self_ty(self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> Self { - tcx.mk_alias_ty(self.def_id, [self_ty.into()].into_iter().chain(self.substs.iter().skip(1))) + tcx.mk_alias_ty(self.def_id, [self_ty.into()].into_iter().chain(self.args.iter().skip(1))) } } @@ -1269,10 +1272,10 @@ impl<'tcx> AliasTy<'tcx> { } } - /// Extracts the underlying trait reference and own substs from this projection. + /// Extracts the underlying trait reference and own args from this projection. /// For example, if this is a projection of `<T as StreamingIterator>::Item<'a>`, - /// then this function would return a `T: StreamingIterator` trait reference and `['a]` as the own substs - pub fn trait_ref_and_own_substs( + /// then this function would return a `T: StreamingIterator` trait reference and `['a]` as the own args + pub fn trait_ref_and_own_args( self, tcx: TyCtxt<'tcx>, ) -> (ty::TraitRef<'tcx>, &'tcx [ty::GenericArg<'tcx>]) { @@ -1280,8 +1283,8 @@ impl<'tcx> AliasTy<'tcx> { let trait_def_id = self.trait_def_id(tcx); let trait_generics = tcx.generics_of(trait_def_id); ( - ty::TraitRef::new(tcx, trait_def_id, self.substs.truncate_to(tcx, trait_generics)), - &self.substs[trait_generics.count()..], + ty::TraitRef::new(tcx, trait_def_id, self.args.truncate_to(tcx, trait_generics)), + &self.args[trait_generics.count()..], ) } @@ -1289,18 +1292,18 @@ impl<'tcx> AliasTy<'tcx> { /// For example, if this is a projection of `<T as Iterator>::Item`, /// then this function would return a `T: Iterator` trait reference. /// - /// WARNING: This will drop the substs for generic associated types - /// consider calling [Self::trait_ref_and_own_substs] to get those + /// WARNING: This will drop the args for generic associated types + /// consider calling [Self::trait_ref_and_own_args] to get those /// as well. pub fn trait_ref(self, tcx: TyCtxt<'tcx>) -> ty::TraitRef<'tcx> { let def_id = self.trait_def_id(tcx); - ty::TraitRef::new(tcx, def_id, self.substs.truncate_to(tcx, tcx.generics_of(def_id))) + ty::TraitRef::new(tcx, def_id, self.args.truncate_to(tcx, tcx.generics_of(def_id))) } } /// The following methods work only with inherent associated type projections. impl<'tcx> AliasTy<'tcx> { - /// Transform the substitutions to have the given `impl` substs as the base and the GAT substs on top of that. + /// Transform the substitutions to have the given `impl` args as the base and the GAT args on top of that. /// /// Does the following transformation: /// @@ -1310,14 +1313,14 @@ impl<'tcx> AliasTy<'tcx> { /// I_i impl subst /// P_j GAT subst /// ``` - pub fn rebase_substs_onto_impl( + pub fn rebase_inherent_args_onto_impl( self, - impl_substs: ty::SubstsRef<'tcx>, + impl_args: ty::GenericArgsRef<'tcx>, tcx: TyCtxt<'tcx>, - ) -> ty::SubstsRef<'tcx> { + ) -> ty::GenericArgsRef<'tcx> { debug_assert_eq!(self.kind(tcx), ty::Inherent); - tcx.mk_substs_from_iter(impl_substs.into_iter().chain(self.substs.into_iter().skip(1))) + tcx.mk_args_from_iter(impl_args.into_iter().chain(self.args.into_iter().skip(1))) } } @@ -1571,12 +1574,6 @@ impl<'tcx> Deref for Region<'tcx> { } } -impl<'tcx> fmt::Debug for Region<'tcx> { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{:?}", self.kind()) - } -} - #[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, PartialOrd, Ord)] #[derive(HashStable)] pub struct EarlyBoundRegion { @@ -1643,7 +1640,7 @@ impl From<BoundVar> for BoundTy { #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)] pub struct ExistentialProjection<'tcx> { pub def_id: DefId, - pub substs: SubstsRef<'tcx>, + pub args: GenericArgsRef<'tcx>, pub term: Term<'tcx>, } @@ -1657,8 +1654,8 @@ impl<'tcx> ExistentialProjection<'tcx> { pub fn trait_ref(&self, tcx: TyCtxt<'tcx>) -> ty::ExistentialTraitRef<'tcx> { let def_id = tcx.parent(self.def_id); let subst_count = tcx.generics_of(def_id).count() - 1; - let substs = tcx.mk_substs(&self.substs[..subst_count]); - ty::ExistentialTraitRef { def_id, substs } + let args = tcx.mk_args(&self.args[..subst_count]); + ty::ExistentialTraitRef { def_id, args } } pub fn with_self_ty( @@ -1671,7 +1668,7 @@ impl<'tcx> ExistentialProjection<'tcx> { ty::ProjectionPredicate { projection_ty: tcx - .mk_alias_ty(self.def_id, [self_ty.into()].into_iter().chain(self.substs)), + .mk_alias_ty(self.def_id, [self_ty.into()].into_iter().chain(self.args)), term: self.term, } } @@ -1681,11 +1678,11 @@ impl<'tcx> ExistentialProjection<'tcx> { projection_predicate: ty::ProjectionPredicate<'tcx>, ) -> Self { // Assert there is a Self. - projection_predicate.projection_ty.substs.type_at(0); + projection_predicate.projection_ty.args.type_at(0); Self { def_id: projection_predicate.projection_ty.def_id, - substs: tcx.mk_substs(&projection_predicate.projection_ty.substs[1..]), + args: tcx.mk_args(&projection_predicate.projection_ty.args[1..]), term: projection_predicate.term, } } @@ -1973,8 +1970,8 @@ impl<'tcx> Ty<'tcx> { } #[inline] - pub fn new_opaque(tcx: TyCtxt<'tcx>, def_id: DefId, substs: SubstsRef<'tcx>) -> Ty<'tcx> { - Ty::new_alias(tcx, ty::Opaque, tcx.mk_alias_ty(def_id, substs)) + pub fn new_opaque(tcx: TyCtxt<'tcx>, def_id: DefId, args: GenericArgsRef<'tcx>) -> Ty<'tcx> { + Ty::new_alias(tcx, ty::Opaque, tcx.mk_alias_ty(def_id, args)) } /// Constructs a `TyKind::Error` type with current `ErrorGuaranteed` @@ -2066,8 +2063,8 @@ impl<'tcx> Ty<'tcx> { } #[inline] - pub fn new_adt(tcx: TyCtxt<'tcx>, def: AdtDef<'tcx>, substs: SubstsRef<'tcx>) -> Ty<'tcx> { - Ty::new(tcx, Adt(def, substs)) + pub fn new_adt(tcx: TyCtxt<'tcx>, def: AdtDef<'tcx>, args: GenericArgsRef<'tcx>) -> Ty<'tcx> { + Ty::new(tcx, Adt(def, args)) } #[inline] @@ -2111,10 +2108,10 @@ impl<'tcx> Ty<'tcx> { pub fn new_fn_def( tcx: TyCtxt<'tcx>, def_id: DefId, - substs: impl IntoIterator<Item: Into<GenericArg<'tcx>>>, + args: impl IntoIterator<Item: Into<GenericArg<'tcx>>>, ) -> Ty<'tcx> { - let substs = tcx.check_and_mk_substs(def_id, substs); - Ty::new(tcx, FnDef(def_id, substs)) + let args = tcx.check_and_mk_args(def_id, args); + Ty::new(tcx, FnDef(def_id, args)) } #[inline] @@ -2136,38 +2133,38 @@ impl<'tcx> Ty<'tcx> { pub fn new_projection( tcx: TyCtxt<'tcx>, item_def_id: DefId, - substs: impl IntoIterator<Item: Into<GenericArg<'tcx>>>, + args: impl IntoIterator<Item: Into<GenericArg<'tcx>>>, ) -> Ty<'tcx> { - Ty::new_alias(tcx, ty::Projection, tcx.mk_alias_ty(item_def_id, substs)) + Ty::new_alias(tcx, ty::Projection, tcx.mk_alias_ty(item_def_id, args)) } #[inline] pub fn new_closure( tcx: TyCtxt<'tcx>, def_id: DefId, - closure_substs: SubstsRef<'tcx>, + closure_args: GenericArgsRef<'tcx>, ) -> Ty<'tcx> { debug_assert_eq!( - closure_substs.len(), + closure_args.len(), tcx.generics_of(tcx.typeck_root_def_id(def_id)).count() + 3, "closure constructed with incorrect substitutions" ); - Ty::new(tcx, Closure(def_id, closure_substs)) + Ty::new(tcx, Closure(def_id, closure_args)) } #[inline] pub fn new_generator( tcx: TyCtxt<'tcx>, def_id: DefId, - generator_substs: SubstsRef<'tcx>, + generator_args: GenericArgsRef<'tcx>, movability: hir::Movability, ) -> Ty<'tcx> { debug_assert_eq!( - generator_substs.len(), + generator_args.len(), tcx.generics_of(tcx.typeck_root_def_id(def_id)).count() + 5, "generator constructed with incorrect number of substitutions" ); - Ty::new(tcx, Generator(def_id, generator_substs, movability)) + Ty::new(tcx, Generator(def_id, generator_args, movability)) } #[inline] @@ -2182,9 +2179,9 @@ impl<'tcx> Ty<'tcx> { pub fn new_generator_witness_mir( tcx: TyCtxt<'tcx>, id: DefId, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, ) -> Ty<'tcx> { - Ty::new(tcx, GeneratorWitnessMIR(id, substs)) + Ty::new(tcx, GeneratorWitnessMIR(id, args)) } // misc @@ -2208,19 +2205,18 @@ impl<'tcx> Ty<'tcx> { fn new_generic_adt(tcx: TyCtxt<'tcx>, wrapper_def_id: DefId, ty_param: Ty<'tcx>) -> Ty<'tcx> { let adt_def = tcx.adt_def(wrapper_def_id); - let substs = - InternalSubsts::for_item(tcx, wrapper_def_id, |param, substs| match param.kind { - GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => bug!(), - GenericParamDefKind::Type { has_default, .. } => { - if param.index == 0 { - ty_param.into() - } else { - assert!(has_default); - tcx.type_of(param.def_id).subst(tcx, substs).into() - } + let args = GenericArgs::for_item(tcx, wrapper_def_id, |param, args| match param.kind { + GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => bug!(), + GenericParamDefKind::Type { has_default, .. } => { + if param.index == 0 { + ty_param.into() + } else { + assert!(has_default); + tcx.type_of(param.def_id).instantiate(tcx, args).into() } - }); - Ty::new(tcx, Adt(adt_def, substs)) + } + }); + Ty::new(tcx, Adt(adt_def, args)) } #[inline] @@ -2251,8 +2247,8 @@ impl<'tcx> Ty<'tcx> { pub fn new_task_context(tcx: TyCtxt<'tcx>) -> Ty<'tcx> { let context_did = tcx.require_lang_item(LangItem::Context, None); let context_adt_ref = tcx.adt_def(context_did); - let context_substs = tcx.mk_substs(&[tcx.lifetimes.re_erased.into()]); - let context_ty = Ty::new_adt(tcx, context_adt_ref, context_substs); + let context_args = tcx.mk_args(&[tcx.lifetimes.re_erased.into()]); + let context_ty = Ty::new_adt(tcx, context_adt_ref, context_args); Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, context_ty) } } @@ -2376,10 +2372,10 @@ impl<'tcx> Ty<'tcx> { pub fn simd_size_and_type(self, tcx: TyCtxt<'tcx>) -> (u64, Ty<'tcx>) { match self.kind() { - Adt(def, substs) => { + Adt(def, args) => { assert!(def.repr().simd(), "`simd_size_and_type` called on non-SIMD type"); let variant = def.non_enum_variant(); - let f0_ty = variant.fields[FieldIdx::from_u32(0)].ty(tcx, substs); + let f0_ty = variant.fields[FieldIdx::from_u32(0)].ty(tcx, args); match f0_ty.kind() { // If the first field is an array, we assume it is the only field and its @@ -2440,7 +2436,7 @@ impl<'tcx> Ty<'tcx> { /// Panics if called on any type other than `Box<T>`. pub fn boxed_ty(self) -> Ty<'tcx> { match self.kind() { - Adt(def, substs) if def.is_box() => substs.type_at(0), + Adt(def, args) if def.is_box() => args.type_at(0), _ => bug!("`boxed_ty` is called on non-box type {:?}", self), } } @@ -2604,14 +2600,14 @@ impl<'tcx> Ty<'tcx> { pub fn fn_sig(self, tcx: TyCtxt<'tcx>) -> PolyFnSig<'tcx> { match self.kind() { - FnDef(def_id, substs) => tcx.fn_sig(*def_id).subst(tcx, substs), + FnDef(def_id, args) => tcx.fn_sig(*def_id).instantiate(tcx, args), FnPtr(f) => *f, Error(_) => { // ignore errors (#54954) ty::Binder::dummy(FnSig::fake()) } Closure(..) => bug!( - "to get the signature of a closure, use `substs.as_closure().sig()` not `fn_sig()`", + "to get the signature of a closure, use `args.as_closure().sig()` not `fn_sig()`", ), _ => bug!("Ty::fn_sig() called on non-fn type: {:?}", self), } @@ -2645,7 +2641,7 @@ impl<'tcx> Ty<'tcx> { #[inline] pub fn tuple_fields(self) -> &'tcx List<Ty<'tcx>> { match self.kind() { - Tuple(substs) => substs, + Tuple(args) => args, _ => bug!("tuple_fields called on non-tuple"), } } @@ -2657,8 +2653,8 @@ impl<'tcx> Ty<'tcx> { pub fn variant_range(self, tcx: TyCtxt<'tcx>) -> Option<Range<VariantIdx>> { match self.kind() { TyKind::Adt(adt, _) => Some(adt.variant_range()), - TyKind::Generator(def_id, substs, _) => { - Some(substs.as_generator().variant_range(*def_id, tcx)) + TyKind::Generator(def_id, args, _) => { + Some(args.as_generator().variant_range(*def_id, tcx)) } _ => None, } @@ -2683,8 +2679,8 @@ impl<'tcx> Ty<'tcx> { TyKind::Adt(adt, _) if adt.is_enum() => { Some(adt.discriminant_for_variant(tcx, variant_index)) } - TyKind::Generator(def_id, substs, _) => { - Some(substs.as_generator().discriminant_for_variant(*def_id, tcx, variant_index)) + TyKind::Generator(def_id, args, _) => { + Some(args.as_generator().discriminant_for_variant(*def_id, tcx, variant_index)) } _ => None, } @@ -2694,13 +2690,13 @@ impl<'tcx> Ty<'tcx> { pub fn discriminant_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> { match self.kind() { ty::Adt(adt, _) if adt.is_enum() => adt.repr().discr_type().to_ty(tcx), - ty::Generator(_, substs, _) => substs.as_generator().discr_ty(tcx), + ty::Generator(_, args, _) => args.as_generator().discr_ty(tcx), ty::Param(_) | ty::Alias(..) | ty::Infer(ty::TyVar(_)) => { let assoc_items = tcx.associated_item_def_ids( tcx.require_lang_item(hir::LangItem::DiscriminantKind, None), ); - Ty::new_projection(tcx, assoc_items[0], tcx.mk_substs(&[self.into()])) + Ty::new_projection(tcx, assoc_items[0], tcx.mk_args(&[self.into()])) } ty::Bool @@ -2773,7 +2769,7 @@ impl<'tcx> Ty<'tcx> { ty::Str | ty::Slice(_) => (tcx.types.usize, false), ty::Dynamic(..) => { let dyn_metadata = tcx.require_lang_item(LangItem::DynMetadata, None); - (tcx.type_of(dyn_metadata).subst(tcx, &[tail.into()]), false) + (tcx.type_of(dyn_metadata).instantiate(tcx, &[tail.into()]), false) }, // type parameters only have unit metadata if they're sized, so return true @@ -2790,7 +2786,7 @@ impl<'tcx> Ty<'tcx> { } /// When we create a closure, we record its kind (i.e., what trait - /// it implements) into its `ClosureSubsts` using a type + /// it implements) into its `ClosureArgs` using a type /// parameter. This is kind of a phantom type, except that the /// most convenient thing for us to are the integral types. This /// function converts such a special type into the closure @@ -2853,7 +2849,7 @@ impl<'tcx> Ty<'tcx> { ty::Tuple(tys) => tys.iter().all(|ty| ty.is_trivially_sized(tcx)), - ty::Adt(def, _substs) => def.sized_constraint(tcx).skip_binder().is_empty(), + ty::Adt(def, _args) => def.sized_constraint(tcx).skip_binder().is_empty(), ty::Alias(..) | ty::Param(_) | ty::Placeholder(..) => false, diff --git a/compiler/rustc_middle/src/ty/trait_def.rs b/compiler/rustc_middle/src/ty/trait_def.rs index 98c70e330f1..6e55e7915c9 100644 --- a/compiler/rustc_middle/src/ty/trait_def.rs +++ b/compiler/rustc_middle/src/ty/trait_def.rs @@ -236,7 +236,7 @@ pub(super) fn trait_impls_of_provider(tcx: TyCtxt<'_>, trait_id: DefId) -> Trait for &impl_def_id in tcx.hir().trait_impls(trait_id) { let impl_def_id = impl_def_id.to_def_id(); - let impl_self_ty = tcx.type_of(impl_def_id).subst_identity(); + let impl_self_ty = tcx.type_of(impl_def_id).instantiate_identity(); if impl_self_ty.references_error() { continue; } diff --git a/compiler/rustc_middle/src/ty/typeck_results.rs b/compiler/rustc_middle/src/ty/typeck_results.rs index 8cbffa14850..327cd0a5d7b 100644 --- a/compiler/rustc_middle/src/ty/typeck_results.rs +++ b/compiler/rustc_middle/src/ty/typeck_results.rs @@ -4,13 +4,12 @@ use crate::{ traits::ObligationCause, ty::{ self, tls, BindingMode, BoundVar, CanonicalPolyFnSig, ClosureSizeProfileData, - GenericArgKind, InternalSubsts, SubstsRef, Ty, UserSubsts, + GenericArgKind, GenericArgs, GenericArgsRef, Ty, UserArgs, }, }; use rustc_data_structures::{ - fx::{FxHashMap, FxIndexMap}, - sync::Lrc, - unord::{UnordItems, UnordSet}, + fx::FxIndexMap, + unord::{ExtendUnord, UnordItems, UnordSet}, }; use rustc_errors::ErrorGuaranteed; use rustc_hir as hir; @@ -54,7 +53,7 @@ pub struct TypeckResults<'tcx> { /// of this node. This only applies to nodes that refer to entities /// parameterized by type parameters, such as generic fns, types, or /// other items. - node_substs: ItemLocalMap<SubstsRef<'tcx>>, + node_args: ItemLocalMap<GenericArgsRef<'tcx>>, /// This will either store the canonicalized types provided by the user /// or the substitutions that the user explicitly gave (if any) attached @@ -145,7 +144,7 @@ pub struct TypeckResults<'tcx> { /// This is used for warning unused imports. During type /// checking, this `Lrc` should not be cloned: it must have a ref-count /// of 1 so that we can insert things into the set mutably. - pub used_trait_imports: Lrc<UnordSet<LocalDefId>>, + pub used_trait_imports: UnordSet<LocalDefId>, /// If any errors occurred while type-checking this body, /// this field will be set to `Some(ErrorGuaranteed)`. @@ -183,7 +182,7 @@ pub struct TypeckResults<'tcx> { /// we never capture `t`. This becomes an issue when we build MIR as we require /// information on `t` in order to create place `t.0` and `t.1`. We can solve this /// issue by fake reading `t`. - pub closure_fake_reads: FxHashMap<LocalDefId, Vec<(HirPlace<'tcx>, FakeReadCause, hir::HirId)>>, + pub closure_fake_reads: LocalDefIdMap<Vec<(HirPlace<'tcx>, FakeReadCause, hir::HirId)>>, /// Tracks the rvalue scoping rules which defines finer scoping for rvalue expressions /// by applying extended parameter rules. @@ -197,7 +196,7 @@ pub struct TypeckResults<'tcx> { /// Stores the predicates that apply on generator witness types. /// formatting modified file tests/ui/generator/retain-resume-ref.rs pub generator_interior_predicates: - FxHashMap<LocalDefId, Vec<(ty::Predicate<'tcx>, ObligationCause<'tcx>)>>, + LocalDefIdMap<Vec<(ty::Predicate<'tcx>, ObligationCause<'tcx>)>>, /// We sometimes treat byte string literals (which are of type `&[u8; N]`) /// as `&[u8]`, depending on the pattern in which they are used. @@ -207,7 +206,7 @@ pub struct TypeckResults<'tcx> { /// Contains the data for evaluating the effect of feature `capture_disjoint_fields` /// on closure size. - pub closure_size_eval: FxHashMap<LocalDefId, ClosureSizeProfileData<'tcx>>, + pub closure_size_eval: LocalDefIdMap<ClosureSizeProfileData<'tcx>>, /// Container types and field indices of `offset_of!` expressions offset_of_data: ItemLocalMap<(Ty<'tcx>, Vec<FieldIdx>)>, @@ -265,7 +264,7 @@ impl<'tcx> TypeckResults<'tcx> { user_provided_types: Default::default(), user_provided_sigs: Default::default(), node_types: Default::default(), - node_substs: Default::default(), + node_args: Default::default(), adjustments: Default::default(), pat_binding_modes: Default::default(), pat_adjustments: Default::default(), @@ -273,7 +272,7 @@ impl<'tcx> TypeckResults<'tcx> { liberated_fn_sigs: Default::default(), fru_field_types: Default::default(), coercion_casts: Default::default(), - used_trait_imports: Lrc::new(Default::default()), + used_trait_imports: Default::default(), tainted_by_errors: None, concrete_opaque_types: Default::default(), closure_min_captures: Default::default(), @@ -385,18 +384,18 @@ impl<'tcx> TypeckResults<'tcx> { self.node_types.get(&id.local_id).cloned() } - pub fn node_substs_mut(&mut self) -> LocalTableInContextMut<'_, SubstsRef<'tcx>> { - LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.node_substs } + pub fn node_args_mut(&mut self) -> LocalTableInContextMut<'_, GenericArgsRef<'tcx>> { + LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.node_args } } - pub fn node_substs(&self, id: hir::HirId) -> SubstsRef<'tcx> { + pub fn node_args(&self, id: hir::HirId) -> GenericArgsRef<'tcx> { validate_hir_id_for_typeck_results(self.hir_owner, id); - self.node_substs.get(&id.local_id).cloned().unwrap_or_else(|| InternalSubsts::empty()) + self.node_args.get(&id.local_id).cloned().unwrap_or_else(|| GenericArgs::empty()) } - pub fn node_substs_opt(&self, id: hir::HirId) -> Option<SubstsRef<'tcx>> { + pub fn node_args_opt(&self, id: hir::HirId) -> Option<GenericArgsRef<'tcx>> { validate_hir_id_for_typeck_results(self.hir_owner, id); - self.node_substs.get(&id.local_id).cloned() + self.node_args.get(&id.local_id).cloned() } /// Returns the type of a pattern as a monotype. Like [`expr_ty`], this function @@ -636,7 +635,7 @@ impl<'a, V> LocalTableInContextMut<'a, V> { &mut self, items: UnordItems<(hir::HirId, V), impl Iterator<Item = (hir::HirId, V)>>, ) { - self.data.extend(items.map(|(id, value)| { + self.data.extend_unord(items.map(|(id, value)| { validate_hir_id_for_typeck_results(self.hir_owner, id); (id.local_id, value) })) @@ -671,12 +670,12 @@ impl<'tcx> CanonicalUserType<'tcx> { pub fn is_identity(&self) -> bool { match self.value { UserType::Ty(_) => false, - UserType::TypeOf(_, user_substs) => { - if user_substs.user_self_ty.is_some() { + UserType::TypeOf(_, user_args) => { + if user_args.user_self_ty.is_some() { return false; } - iter::zip(user_substs.substs, BoundVar::new(0)..).all(|(kind, cvar)| { + iter::zip(user_args.args, BoundVar::new(0)..).all(|(kind, cvar)| { match kind.unpack() { GenericArgKind::Type(ty) => match ty.kind() { ty::Bound(debruijn, b) => { @@ -721,5 +720,5 @@ pub enum UserType<'tcx> { /// The canonical type is the result of `type_of(def_id)` with the /// given substitutions applied. - TypeOf(DefId, UserSubsts<'tcx>), + TypeOf(DefId, UserArgs<'tcx>), } diff --git a/compiler/rustc_middle/src/ty/util.rs b/compiler/rustc_middle/src/ty/util.rs index e2e4a2dbdc8..b4852ab8881 100644 --- a/compiler/rustc_middle/src/ty/util.rs +++ b/compiler/rustc_middle/src/ty/util.rs @@ -7,7 +7,7 @@ use crate::ty::{ self, FallibleTypeFolder, ToPredicate, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitableExt, }; -use crate::ty::{GenericArgKind, SubstsRef}; +use crate::ty::{GenericArgKind, GenericArgsRef}; use rustc_apfloat::Float as _; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_data_structures::stable_hasher::{Hash128, HashStable, StableHasher}; @@ -226,14 +226,14 @@ impl<'tcx> TyCtxt<'tcx> { return Ty::new_error(self, reported); } match *ty.kind() { - ty::Adt(def, substs) => { + ty::Adt(def, args) => { if !def.is_struct() { break; } match def.non_enum_variant().tail_opt() { Some(field) => { f(); - ty = field.ty(self, substs); + ty = field.ty(self, args); } None => break, } @@ -301,12 +301,12 @@ impl<'tcx> TyCtxt<'tcx> { let (mut a, mut b) = (source, target); loop { match (&a.kind(), &b.kind()) { - (&ty::Adt(a_def, a_substs), &ty::Adt(b_def, b_substs)) + (&ty::Adt(a_def, a_args), &ty::Adt(b_def, b_args)) if a_def == b_def && a_def.is_struct() => { if let Some(f) = a_def.non_enum_variant().tail_opt() { - a = f.ty(self, a_substs); - b = f.ty(self, b_substs); + a = f.ty(self, a_args); + b = f.ty(self, b_args); } else { break; } @@ -349,7 +349,7 @@ impl<'tcx> TyCtxt<'tcx> { let drop_trait = self.lang_items().drop_trait()?; self.ensure().coherent_trait(drop_trait); - let ty = self.type_of(adt_did).subst_identity(); + let ty = self.type_of(adt_did).instantiate_identity(); let mut dtor_candidate = None; self.for_each_relevant_impl(drop_trait, ty, |impl_did| { if validate(self, impl_did).is_err() { @@ -358,7 +358,8 @@ impl<'tcx> TyCtxt<'tcx> { } let Some(item_id) = self.associated_item_def_ids(impl_did).first() else { - self.sess.delay_span_bug(self.def_span(impl_did), "Drop impl without drop function"); + self.sess + .delay_span_bug(self.def_span(impl_did), "Drop impl without drop function"); return; }; @@ -383,7 +384,7 @@ impl<'tcx> TyCtxt<'tcx> { /// Note that this returns only the constraints for the /// destructor of `def` itself. For the destructors of the /// contents, you need `adt_dtorck_constraint`. - pub fn destructor_constraints(self, def: ty::AdtDef<'tcx>) -> Vec<ty::subst::GenericArg<'tcx>> { + pub fn destructor_constraints(self, def: ty::AdtDef<'tcx>) -> Vec<ty::GenericArg<'tcx>> { let dtor = match def.destructor(self) { None => { debug!("destructor_constraints({:?}) - no dtor", def.did()); @@ -400,7 +401,7 @@ impl<'tcx> TyCtxt<'tcx> { // must be live. // We need to return the list of parameters from the ADTs - // generics/substs that correspond to impure parameters on the + // generics/args that correspond to impure parameters on the // impl's generics. This is a bit ugly, but conceptually simple: // // Suppose our ADT looks like the following @@ -412,21 +413,21 @@ impl<'tcx> TyCtxt<'tcx> { // impl<#[may_dangle] P0, P1, P2> Drop for S<P1, P2, P0> // // We want to return the parameters (X, Y). For that, we match - // up the item-substs <X, Y, Z> with the substs on the impl ADT, - // <P1, P2, P0>, and then look up which of the impl substs refer to + // up the item-args <X, Y, Z> with the args on the impl ADT, + // <P1, P2, P0>, and then look up which of the impl args refer to // parameters marked as pure. - let impl_substs = match *self.type_of(impl_def_id).subst_identity().kind() { - ty::Adt(def_, substs) if def_ == def => substs, + let impl_args = match *self.type_of(impl_def_id).instantiate_identity().kind() { + ty::Adt(def_, args) if def_ == def => args, _ => bug!(), }; - let item_substs = match *self.type_of(def.did()).subst_identity().kind() { - ty::Adt(def_, substs) if def_ == def => substs, + let item_args = match *self.type_of(def.did()).instantiate_identity().kind() { + ty::Adt(def_, args) if def_ == def => args, _ => bug!(), }; - let result = iter::zip(item_substs, impl_substs) + let result = iter::zip(item_args, impl_args) .filter(|&(_, k)| { match k.unpack() { GenericArgKind::Lifetime(region) => match region.kind() { @@ -459,12 +460,12 @@ impl<'tcx> TyCtxt<'tcx> { /// Checks whether each generic argument is simply a unique generic parameter. pub fn uses_unique_generic_params( self, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, ignore_regions: CheckRegions, ) -> Result<(), NotUniqueParam<'tcx>> { let mut seen = GrowableBitSet::default(); let mut seen_late = FxHashSet::default(); - for arg in substs { + for arg in args { match arg.unpack() { GenericArgKind::Lifetime(lt) => match (ignore_regions, lt.kind()) { (CheckRegions::Bound, ty::ReLateBound(di, reg)) => { @@ -510,10 +511,10 @@ impl<'tcx> TyCtxt<'tcx> { /// for better caching. pub fn uses_unique_placeholders_ignoring_regions( self, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, ) -> Result<(), NotUniqueParam<'tcx>> { let mut seen = GrowableBitSet::default(); - for arg in substs { + for arg in args { match arg.unpack() { // Ignore regions, since we can't resolve those in a canonicalized // query in the trait solver. @@ -594,7 +595,7 @@ impl<'tcx> TyCtxt<'tcx> { def_id } - /// Given the `DefId` and substs a closure, creates the type of + /// Given the `DefId` and args a closure, creates the type of /// `self` argument that the closure expects. For example, for a /// `Fn` closure, this would return a reference type `&T` where /// `T = closure_ty`. @@ -607,11 +608,11 @@ impl<'tcx> TyCtxt<'tcx> { pub fn closure_env_ty( self, closure_def_id: DefId, - closure_substs: SubstsRef<'tcx>, + closure_args: GenericArgsRef<'tcx>, env_region: ty::Region<'tcx>, ) -> Option<Ty<'tcx>> { - let closure_ty = Ty::new_closure(self, closure_def_id, closure_substs); - let closure_kind_ty = closure_substs.as_closure().kind_ty(); + let closure_ty = Ty::new_closure(self, closure_def_id, closure_args); + let closure_kind_ty = closure_args.as_closure().kind_ty(); let closure_kind = closure_kind_ty.to_opt_closure_kind()?; let env_ty = match closure_kind { ty::ClosureKind::Fn => Ty::new_imm_ref(self, env_region, closure_ty), @@ -654,7 +655,7 @@ impl<'tcx> TyCtxt<'tcx> { /// Returns the type a reference to the thread local takes in MIR. pub fn thread_local_ptr_ty(self, def_id: DefId) -> Ty<'tcx> { - let static_ty = self.type_of(def_id).subst_identity(); + let static_ty = self.type_of(def_id).instantiate_identity(); if self.is_mutable_static(def_id) { Ty::new_mut_ptr(self, static_ty) } else if self.is_foreign_item(def_id) { @@ -670,7 +671,7 @@ impl<'tcx> TyCtxt<'tcx> { // Make sure that any constants in the static's type are evaluated. let static_ty = self.normalize_erasing_regions( ty::ParamEnv::empty(), - self.type_of(def_id).subst_identity(), + self.type_of(def_id).instantiate_identity(), ); // Make sure that accesses to unsafe statics end up using raw pointers. @@ -719,7 +720,7 @@ impl<'tcx> TyCtxt<'tcx> { pub fn try_expand_impl_trait_type( self, def_id: DefId, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, ) -> Result<Ty<'tcx>, Ty<'tcx>> { let mut visitor = OpaqueTypeExpander { seen_opaque_tys: FxHashSet::default(), @@ -732,7 +733,7 @@ impl<'tcx> TyCtxt<'tcx> { tcx: self, }; - let expanded_type = visitor.expand_opaque_ty(def_id, substs).unwrap(); + let expanded_type = visitor.expand_opaque_ty(def_id, args).unwrap(); if visitor.found_recursion { Err(expanded_type) } else { Ok(expanded_type) } } @@ -799,7 +800,7 @@ struct OpaqueTypeExpander<'tcx> { seen_opaque_tys: FxHashSet<DefId>, // Cache of all expansions we've seen so far. This is a critical // optimization for some large types produced by async fn trees. - expanded_cache: FxHashMap<(DefId, SubstsRef<'tcx>), Ty<'tcx>>, + expanded_cache: FxHashMap<(DefId, GenericArgsRef<'tcx>), Ty<'tcx>>, primary_def_id: Option<DefId>, found_recursion: bool, found_any_recursion: bool, @@ -812,19 +813,19 @@ struct OpaqueTypeExpander<'tcx> { } impl<'tcx> OpaqueTypeExpander<'tcx> { - fn expand_opaque_ty(&mut self, def_id: DefId, substs: SubstsRef<'tcx>) -> Option<Ty<'tcx>> { + fn expand_opaque_ty(&mut self, def_id: DefId, args: GenericArgsRef<'tcx>) -> Option<Ty<'tcx>> { if self.found_any_recursion { return None; } - let substs = substs.fold_with(self); + let args = args.fold_with(self); if !self.check_recursion || self.seen_opaque_tys.insert(def_id) { - let expanded_ty = match self.expanded_cache.get(&(def_id, substs)) { + let expanded_ty = match self.expanded_cache.get(&(def_id, args)) { Some(expanded_ty) => *expanded_ty, None => { let generic_ty = self.tcx.type_of(def_id); - let concrete_ty = generic_ty.subst(self.tcx, substs); + let concrete_ty = generic_ty.instantiate(self.tcx, args); let expanded_ty = self.fold_ty(concrete_ty); - self.expanded_cache.insert((def_id, substs), expanded_ty); + self.expanded_cache.insert((def_id, args), expanded_ty); expanded_ty } }; @@ -841,21 +842,21 @@ impl<'tcx> OpaqueTypeExpander<'tcx> { } } - fn expand_generator(&mut self, def_id: DefId, substs: SubstsRef<'tcx>) -> Option<Ty<'tcx>> { + fn expand_generator(&mut self, def_id: DefId, args: GenericArgsRef<'tcx>) -> Option<Ty<'tcx>> { if self.found_any_recursion { return None; } - let substs = substs.fold_with(self); + let args = args.fold_with(self); if !self.check_recursion || self.seen_opaque_tys.insert(def_id) { - let expanded_ty = match self.expanded_cache.get(&(def_id, substs)) { + let expanded_ty = match self.expanded_cache.get(&(def_id, args)) { Some(expanded_ty) => *expanded_ty, None => { for bty in self.tcx.generator_hidden_types(def_id) { - let hidden_ty = bty.subst(self.tcx, substs); + let hidden_ty = bty.instantiate(self.tcx, args); self.fold_ty(hidden_ty); } - let expanded_ty = Ty::new_generator_witness_mir(self.tcx, def_id, substs); - self.expanded_cache.insert((def_id, substs), expanded_ty); + let expanded_ty = Ty::new_generator_witness_mir(self.tcx, def_id, args); + self.expanded_cache.insert((def_id, args), expanded_ty); expanded_ty } }; @@ -879,16 +880,16 @@ impl<'tcx> TypeFolder<TyCtxt<'tcx>> for OpaqueTypeExpander<'tcx> { } fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> { - let mut t = if let ty::Alias(ty::Opaque, ty::AliasTy { def_id, substs, .. }) = *t.kind() { - self.expand_opaque_ty(def_id, substs).unwrap_or(t) + let mut t = if let ty::Alias(ty::Opaque, ty::AliasTy { def_id, args, .. }) = *t.kind() { + self.expand_opaque_ty(def_id, args).unwrap_or(t) } else if t.has_opaque_types() || t.has_generators() { t.super_fold_with(self) } else { t }; if self.expand_generators { - if let ty::GeneratorWitnessMIR(def_id, substs) = *t.kind() { - t = self.expand_generator(def_id, substs).unwrap_or(t); + if let ty::GeneratorWitnessMIR(def_id, args) = *t.kind() { + t = self.expand_generator(def_id, args).unwrap_or(t); } } t diff --git a/compiler/rustc_middle/src/ty/walk.rs b/compiler/rustc_middle/src/ty/walk.rs index 04a635a6803..7c3d9ed390a 100644 --- a/compiler/rustc_middle/src/ty/walk.rs +++ b/compiler/rustc_middle/src/ty/walk.rs @@ -1,8 +1,8 @@ //! An iterator over the type substructure. //! WARNING: this does not keep track of the region depth. -use crate::ty::subst::{GenericArg, GenericArgKind}; use crate::ty::{self, Ty}; +use crate::ty::{GenericArg, GenericArgKind}; use rustc_data_structures::sso::SsoHashSet; use smallvec::SmallVec; @@ -166,33 +166,33 @@ fn push_inner<'tcx>(stack: &mut TypeWalkerStack<'tcx>, parent: GenericArg<'tcx>) stack.push(lt.into()); } ty::Alias(_, data) => { - stack.extend(data.substs.iter().rev()); + stack.extend(data.args.iter().rev()); } ty::Dynamic(obj, lt, _) => { stack.push(lt.into()); stack.extend(obj.iter().rev().flat_map(|predicate| { - let (substs, opt_ty) = match predicate.skip_binder() { - ty::ExistentialPredicate::Trait(tr) => (tr.substs, None), - ty::ExistentialPredicate::Projection(p) => (p.substs, Some(p.term)), + let (args, opt_ty) = match predicate.skip_binder() { + ty::ExistentialPredicate::Trait(tr) => (tr.args, None), + ty::ExistentialPredicate::Projection(p) => (p.args, Some(p.term)), ty::ExistentialPredicate::AutoTrait(_) => // Empty iterator { - (ty::InternalSubsts::empty(), None) + (ty::GenericArgs::empty(), None) } }; - substs.iter().rev().chain(opt_ty.map(|term| match term.unpack() { + args.iter().rev().chain(opt_ty.map(|term| match term.unpack() { ty::TermKind::Ty(ty) => ty.into(), ty::TermKind::Const(ct) => ct.into(), })) })); } - ty::Adt(_, substs) - | ty::Closure(_, substs) - | ty::Generator(_, substs, _) - | ty::GeneratorWitnessMIR(_, substs) - | ty::FnDef(_, substs) => { - stack.extend(substs.iter().rev()); + ty::Adt(_, args) + | ty::Closure(_, args) + | ty::Generator(_, args, _) + | ty::GeneratorWitnessMIR(_, args) + | ty::FnDef(_, args) => { + stack.extend(args.iter().rev()); } ty::Tuple(ts) => stack.extend(ts.iter().rev().map(GenericArg::from)), ty::GeneratorWitness(ts) => { @@ -233,7 +233,7 @@ fn push_inner<'tcx>(stack: &mut TypeWalkerStack<'tcx>, parent: GenericArg<'tcx>) }, ty::ConstKind::Unevaluated(ct) => { - stack.extend(ct.substs.iter().rev()); + stack.extend(ct.args.iter().rev()); } } } diff --git a/compiler/rustc_middle/src/util/call_kind.rs b/compiler/rustc_middle/src/util/call_kind.rs index 98d55ea6d40..4e2a2c6ae0a 100644 --- a/compiler/rustc_middle/src/util/call_kind.rs +++ b/compiler/rustc_middle/src/util/call_kind.rs @@ -2,7 +2,7 @@ //! as well as errors when attempting to call a non-const function in a const //! context. -use crate::ty::subst::SubstsRef; +use crate::ty::GenericArgsRef; use crate::ty::{AssocItemContainer, Instance, ParamEnv, Ty, TyCtxt}; use rustc_hir::def_id::DefId; use rustc_hir::{lang_items, LangItem}; @@ -43,7 +43,7 @@ pub enum CallKind<'tcx> { self_arg: Option<Ident>, desugaring: Option<(CallDesugaringKind, Ty<'tcx>)>, method_did: DefId, - method_substs: SubstsRef<'tcx>, + method_args: GenericArgsRef<'tcx>, }, /// A call to `Fn(..)::call(..)`, desugared from `my_closure(a, b, c)` FnCall { fn_trait_id: DefId, self_ty: Ty<'tcx> }, @@ -63,7 +63,7 @@ pub fn call_kind<'tcx>( tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>, method_did: DefId, - method_substs: SubstsRef<'tcx>, + method_args: GenericArgsRef<'tcx>, fn_call_span: Span, from_hir_call: bool, self_arg: Option<Ident>, @@ -92,19 +92,19 @@ pub fn call_kind<'tcx>( // an FnOnce call, an operator (e.g. `<<`), or a // deref coercion. let kind = if let Some(trait_id) = fn_call { - Some(CallKind::FnCall { fn_trait_id: trait_id, self_ty: method_substs.type_at(0) }) + Some(CallKind::FnCall { fn_trait_id: trait_id, self_ty: method_args.type_at(0) }) } else if let Some(trait_id) = operator { - Some(CallKind::Operator { self_arg, trait_id, self_ty: method_substs.type_at(0) }) + Some(CallKind::Operator { self_arg, trait_id, self_ty: method_args.type_at(0) }) } else if is_deref { let deref_target = tcx.get_diagnostic_item(sym::deref_target).and_then(|deref_target| { - Instance::resolve(tcx, param_env, deref_target, method_substs).transpose() + Instance::resolve(tcx, param_env, deref_target, method_args).transpose() }); if let Some(Ok(instance)) = deref_target { let deref_target_ty = instance.ty(tcx, param_env); Some(CallKind::DerefCoercion { deref_target: tcx.def_span(instance.def_id()), deref_target_ty, - self_ty: method_substs.type_at(0), + self_ty: method_args.type_at(0), }) } else { None @@ -119,24 +119,24 @@ pub fn call_kind<'tcx>( let desugaring = if Some(method_did) == tcx.lang_items().into_iter_fn() && fn_call_span.desugaring_kind() == Some(DesugaringKind::ForLoop) { - Some((CallDesugaringKind::ForLoopIntoIter, method_substs.type_at(0))) + Some((CallDesugaringKind::ForLoopIntoIter, method_args.type_at(0))) } else if fn_call_span.desugaring_kind() == Some(DesugaringKind::QuestionMark) { if Some(method_did) == tcx.lang_items().branch_fn() { - Some((CallDesugaringKind::QuestionBranch, method_substs.type_at(0))) + Some((CallDesugaringKind::QuestionBranch, method_args.type_at(0))) } else if Some(method_did) == tcx.lang_items().from_residual_fn() { - Some((CallDesugaringKind::QuestionFromResidual, method_substs.type_at(0))) + Some((CallDesugaringKind::QuestionFromResidual, method_args.type_at(0))) } else { None } } else if Some(method_did) == tcx.lang_items().from_output_fn() && fn_call_span.desugaring_kind() == Some(DesugaringKind::TryBlock) { - Some((CallDesugaringKind::TryBlockFromOutput, method_substs.type_at(0))) + Some((CallDesugaringKind::TryBlockFromOutput, method_args.type_at(0))) } else if fn_call_span.is_desugaring(DesugaringKind::Await) { - Some((CallDesugaringKind::Await, method_substs.type_at(0))) + Some((CallDesugaringKind::Await, method_args.type_at(0))) } else { None }; - CallKind::Normal { self_arg, desugaring, method_did, method_substs } + CallKind::Normal { self_arg, desugaring, method_did, method_args } }) } diff --git a/compiler/rustc_middle/src/util/find_self_call.rs b/compiler/rustc_middle/src/util/find_self_call.rs index 0eab0adf07e..1b845334c49 100644 --- a/compiler/rustc_middle/src/util/find_self_call.rs +++ b/compiler/rustc_middle/src/util/find_self_call.rs @@ -1,5 +1,5 @@ use crate::mir::*; -use crate::ty::subst::SubstsRef; +use crate::ty::GenericArgsRef; use crate::ty::{self, TyCtxt}; use rustc_span::def_id::DefId; @@ -11,21 +11,21 @@ pub fn find_self_call<'tcx>( body: &Body<'tcx>, local: Local, block: BasicBlock, -) -> Option<(DefId, SubstsRef<'tcx>)> { +) -> Option<(DefId, GenericArgsRef<'tcx>)> { debug!("find_self_call(local={:?}): terminator={:?}", local, &body[block].terminator); if let Some(Terminator { kind: TerminatorKind::Call { func, args, .. }, .. }) = &body[block].terminator { debug!("find_self_call: func={:?}", func); if let Operand::Constant(box Constant { literal, .. }) = func { - if let ty::FnDef(def_id, substs) = *literal.ty().kind() { + if let ty::FnDef(def_id, fn_args) = *literal.ty().kind() { if let Some(ty::AssocItem { fn_has_self_parameter: true, .. }) = tcx.opt_associated_item(def_id) { - debug!("find_self_call: args={:?}", args); + debug!("find_self_call: args={:?}", fn_args); if let [Operand::Move(self_place) | Operand::Copy(self_place), ..] = **args { if self_place.as_local() == Some(local) { - return Some((def_id, substs)); + return Some((def_id, fn_args)); } } } diff --git a/compiler/rustc_mir_build/messages.ftl b/compiler/rustc_mir_build/messages.ftl index 98156840dd8..938f3edd31b 100644 --- a/compiler/rustc_mir_build/messages.ftl +++ b/compiler/rustc_mir_build/messages.ftl @@ -312,6 +312,8 @@ mir_build_unreachable_pattern = unreachable pattern .label = unreachable pattern .catchall_label = matches any value +mir_build_unsafe_not_inherited = items do not inherit unsafety from separate enclosing items + mir_build_unsafe_op_in_unsafe_fn_borrow_of_layout_constrained_field_requires_unsafe = borrow of layout constrained field with interior mutability is unsafe and requires unsafe block (error E0133) .note = references to fields of layout constrained fields lose the constraints. Coupled with interior mutability, the field can be changed to invalid values diff --git a/compiler/rustc_mir_build/src/build/custom/parse.rs b/compiler/rustc_mir_build/src/build/custom/parse.rs index 803207d9dc6..c494929cbff 100644 --- a/compiler/rustc_mir_build/src/build/custom/parse.rs +++ b/compiler/rustc_mir_build/src/build/custom/parse.rs @@ -241,9 +241,7 @@ impl<'tcx, 'body> ParseCtxt<'tcx, 'body> { }); } - let Some(trailing) = block.expr else { - return Err(self.expr_error(expr_id, "terminator")) - }; + let Some(trailing) = block.expr else { return Err(self.expr_error(expr_id, "terminator")) }; let span = self.thir[trailing].span; let terminator = self.parse_terminator(trailing)?; data.terminator = Some(Terminator { diff --git a/compiler/rustc_mir_build/src/build/custom/parse/instruction.rs b/compiler/rustc_mir_build/src/build/custom/parse/instruction.rs index 4cb9d7babe1..295cddb1e15 100644 --- a/compiler/rustc_mir_build/src/build/custom/parse/instruction.rs +++ b/compiler/rustc_mir_build/src/build/custom/parse/instruction.rs @@ -78,7 +78,7 @@ impl<'tcx, 'body> ParseCtxt<'tcx, 'body> { span, item_description: "no arms".to_string(), expected: "at least one arm".to_string(), - }) + }); }; let otherwise = &self.thir[*otherwise]; @@ -87,7 +87,7 @@ impl<'tcx, 'body> ParseCtxt<'tcx, 'body> { span: otherwise.span, item_description: format!("{:?}", otherwise.pattern.kind), expected: "wildcard pattern".to_string(), - }) + }); }; let otherwise = self.parse_block(otherwise.body)?; @@ -100,7 +100,7 @@ impl<'tcx, 'body> ParseCtxt<'tcx, 'body> { span: arm.pattern.span, item_description: format!("{:?}", arm.pattern.kind), expected: "constant pattern".to_string(), - }) + }); }; values.push(value.eval_bits(self.tcx, self.param_env, arm.pattern.ty)); targets.push(self.parse_block(arm.body)?); @@ -192,12 +192,12 @@ impl<'tcx, 'body> ParseCtxt<'tcx, 'body> { fields.iter().map(|e| self.parse_operand(*e)).collect::<Result<_, _>>()? )) }, - ExprKind::Adt(box AdtExpr{ adt_def, variant_index, substs, fields, .. }) => { + ExprKind::Adt(box AdtExpr{ adt_def, variant_index, args, fields, .. }) => { let is_union = adt_def.is_union(); let active_field_index = is_union.then(|| fields[0].name); Ok(Rvalue::Aggregate( - Box::new(AggregateKind::Adt(adt_def.did(), *variant_index, substs, None, active_field_index)), + Box::new(AggregateKind::Adt(adt_def.did(), *variant_index, args, None, active_field_index)), fields.iter().map(|f| self.parse_operand(f.expr)).collect::<Result<_, _>>()? )) }, diff --git a/compiler/rustc_mir_build/src/build/expr/as_constant.rs b/compiler/rustc_mir_build/src/build/expr/as_constant.rs index 3fe751ae0a5..aaa37446e24 100644 --- a/compiler/rustc_mir_build/src/build/expr/as_constant.rs +++ b/compiler/rustc_mir_build/src/build/expr/as_constant.rs @@ -75,10 +75,10 @@ pub fn as_constant_inner<'tcx>( Constant { span, user_ty, literal } } - ExprKind::NamedConst { def_id, substs, ref user_ty } => { + ExprKind::NamedConst { def_id, args, ref user_ty } => { let user_ty = user_ty.as_ref().and_then(push_cuta); - let uneval = mir::UnevaluatedConst::new(def_id, substs); + let uneval = mir::UnevaluatedConst::new(def_id, args); let literal = ConstantKind::Unevaluated(uneval, ty); Constant { user_ty, span, literal } @@ -89,8 +89,8 @@ pub fn as_constant_inner<'tcx>( Constant { user_ty: None, span, literal } } - ExprKind::ConstBlock { did: def_id, substs } => { - let uneval = mir::UnevaluatedConst::new(def_id, substs); + ExprKind::ConstBlock { did: def_id, args } => { + let uneval = mir::UnevaluatedConst::new(def_id, args); let literal = ConstantKind::Unevaluated(uneval, ty); Constant { user_ty: None, span, literal } diff --git a/compiler/rustc_mir_build/src/build/expr/as_place.rs b/compiler/rustc_mir_build/src/build/expr/as_place.rs index 60acd279f9e..c122230b841 100644 --- a/compiler/rustc_mir_build/src/build/expr/as_place.rs +++ b/compiler/rustc_mir_build/src/build/expr/as_place.rs @@ -175,11 +175,8 @@ fn to_upvars_resolved_place_builder<'tcx>( projection: &[PlaceElem<'tcx>], ) -> Option<PlaceBuilder<'tcx>> { let Some((capture_index, capture)) = - find_capture_matching_projections( - &cx.upvars, - var_hir_id, - &projection, - ) else { + find_capture_matching_projections(&cx.upvars, var_hir_id, &projection) + else { let closure_span = cx.tcx.def_span(closure_def_id); if !enable_precise_capture(closure_span) { bug!( @@ -189,10 +186,7 @@ fn to_upvars_resolved_place_builder<'tcx>( projection ) } else { - debug!( - "No associated capture found for {:?}[{:#?}]", - var_hir_id, projection, - ); + debug!("No associated capture found for {:?}[{:#?}]", var_hir_id, projection,); } return None; }; diff --git a/compiler/rustc_mir_build/src/build/expr/as_rvalue.rs b/compiler/rustc_mir_build/src/build/expr/as_rvalue.rs index 32ffb990be6..7817c3d0d80 100644 --- a/compiler/rustc_mir_build/src/build/expr/as_rvalue.rs +++ b/compiler/rustc_mir_build/src/build/expr/as_rvalue.rs @@ -16,7 +16,7 @@ use rustc_middle::mir::*; use rustc_middle::thir::*; use rustc_middle::ty::cast::{mir_cast_kind, CastTy}; use rustc_middle::ty::layout::IntegerExt; -use rustc_middle::ty::{self, Ty, UpvarSubsts}; +use rustc_middle::ty::{self, Ty, UpvarArgs}; use rustc_span::Span; impl<'a, 'tcx> Builder<'a, 'tcx> { @@ -382,7 +382,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } ExprKind::Closure(box ClosureExpr { closure_id, - substs, + args, ref upvars, movability, ref fake_reads, @@ -470,19 +470,15 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { }) .collect(); - let result = match substs { - UpvarSubsts::Generator(substs) => { + let result = match args { + UpvarArgs::Generator(args) => { // We implicitly set the discriminant to 0. See // librustc_mir/transform/deaggregator.rs for details. let movability = movability.unwrap(); - Box::new(AggregateKind::Generator( - closure_id.to_def_id(), - substs, - movability, - )) + Box::new(AggregateKind::Generator(closure_id.to_def_id(), args, movability)) } - UpvarSubsts::Closure(substs) => { - Box::new(AggregateKind::Closure(closure_id.to_def_id(), substs)) + UpvarArgs::Closure(args) => { + Box::new(AggregateKind::Closure(closure_id.to_def_id(), args)) } }; block.and(Rvalue::Aggregate(result, operands)) diff --git a/compiler/rustc_mir_build/src/build/expr/into.rs b/compiler/rustc_mir_build/src/build/expr/into.rs index e30fdcbbe18..c750727903f 100644 --- a/compiler/rustc_mir_build/src/build/expr/into.rs +++ b/compiler/rustc_mir_build/src/build/expr/into.rs @@ -317,7 +317,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { ExprKind::Adt(box AdtExpr { adt_def, variant_index, - substs, + args, ref user_ty, ref fields, ref base, @@ -382,7 +382,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { let adt = Box::new(AggregateKind::Adt( adt_def.did(), variant_index, - substs, + args, user_ty, active_field_index, )); diff --git a/compiler/rustc_mir_build/src/build/matches/mod.rs b/compiler/rustc_mir_build/src/build/matches/mod.rs index 10770213c9a..6f14891cb78 100644 --- a/compiler/rustc_mir_build/src/build/matches/mod.rs +++ b/compiler/rustc_mir_build/src/build/matches/mod.rs @@ -607,9 +607,11 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { // }; // ``` if let Some(place) = initializer.try_to_place(self) { - let LocalInfo::User(BindingForm::Var( - VarBindingForm { opt_match_place: Some((ref mut match_place, _)), .. }, - )) = **self.local_decls[local].local_info.as_mut().assert_crate_local() else { + let LocalInfo::User(BindingForm::Var(VarBindingForm { + opt_match_place: Some((ref mut match_place, _)), + .. + })) = **self.local_decls[local].local_info.as_mut().assert_crate_local() + else { bug!("Let binding to non-user variable.") }; *match_place = Some(place); @@ -804,7 +806,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } } - PatKind::Variant { adt_def, substs: _, variant_index, ref subpatterns } => { + PatKind::Variant { adt_def, args: _, variant_index, ref subpatterns } => { for subpattern in subpatterns { let subpattern_user_ty = pattern_user_ty.clone().variant(adt_def, variant_index, subpattern.field); diff --git a/compiler/rustc_mir_build/src/build/matches/simplify.rs b/compiler/rustc_mir_build/src/build/matches/simplify.rs index f6b1955fdec..17ac1f4e0ce 100644 --- a/compiler/rustc_mir_build/src/build/matches/simplify.rs +++ b/compiler/rustc_mir_build/src/build/matches/simplify.rs @@ -259,13 +259,13 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } } - PatKind::Variant { adt_def, substs, variant_index, ref subpatterns } => { + PatKind::Variant { adt_def, args, variant_index, ref subpatterns } => { let irrefutable = adt_def.variants().iter_enumerated().all(|(i, v)| { i == variant_index || { self.tcx.features().exhaustive_patterns && !v .inhabited_predicate(self.tcx, adt_def) - .subst(self.tcx, substs) + .instantiate(self.tcx, args) .apply_ignore_module(self.tcx, self.param_env) } }) && (adt_def.did().is_local() diff --git a/compiler/rustc_mir_build/src/build/matches/test.rs b/compiler/rustc_mir_build/src/build/matches/test.rs index e6806177dec..275878a3919 100644 --- a/compiler/rustc_mir_build/src/build/matches/test.rs +++ b/compiler/rustc_mir_build/src/build/matches/test.rs @@ -30,7 +30,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { /// It is a bug to call this with a not-fully-simplified pattern. pub(super) fn test<'pat>(&mut self, match_pair: &MatchPair<'pat, 'tcx>) -> Test<'tcx> { match match_pair.pattern.kind { - PatKind::Variant { adt_def, substs: _, variant_index: _, subpatterns: _ } => Test { + PatKind::Variant { adt_def, args: _, variant_index: _, subpatterns: _ } => Test { span: match_pair.pattern.span, kind: TestKind::Switch { adt_def, @@ -88,7 +88,8 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { switch_ty: Ty<'tcx>, options: &mut FxIndexMap<ConstantKind<'tcx>, u128>, ) -> bool { - let Some(match_pair) = candidate.match_pairs.iter().find(|mp| mp.place == *test_place) else { + let Some(match_pair) = candidate.match_pairs.iter().find(|mp| mp.place == *test_place) + else { return false; }; @@ -126,7 +127,8 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { candidate: &Candidate<'pat, 'tcx>, variants: &mut BitSet<VariantIdx>, ) -> bool { - let Some(match_pair) = candidate.match_pairs.iter().find(|mp| mp.place == *test_place) else { + let Some(match_pair) = candidate.match_pairs.iter().find(|mp| mp.place == *test_place) + else { return false; }; @@ -865,7 +867,7 @@ fn trait_method<'tcx>( tcx: TyCtxt<'tcx>, trait_def_id: DefId, method_name: Symbol, - substs: impl IntoIterator<Item: Into<GenericArg<'tcx>>>, + args: impl IntoIterator<Item: Into<GenericArg<'tcx>>>, ) -> ConstantKind<'tcx> { // The unhygienic comparison here is acceptable because this is only // used on known traits. @@ -875,7 +877,7 @@ fn trait_method<'tcx>( .find(|item| item.kind == ty::AssocKind::Fn) .expect("trait method not found"); - let method_ty = Ty::new_fn_def(tcx, item.def_id, substs); + let method_ty = Ty::new_fn_def(tcx, item.def_id, args); ConstantKind::zero_sized(method_ty) } diff --git a/compiler/rustc_mir_build/src/build/mod.rs b/compiler/rustc_mir_build/src/build/mod.rs index d828e71c7ac..17295fe1d34 100644 --- a/compiler/rustc_mir_build/src/build/mod.rs +++ b/compiler/rustc_mir_build/src/build/mod.rs @@ -10,6 +10,7 @@ use rustc_hir as hir; use rustc_hir::def::DefKind; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::{GeneratorKind, Node}; +use rustc_index::bit_set::GrowableBitSet; use rustc_index::{Idx, IndexSlice, IndexVec}; use rustc_infer::infer::{InferCtxt, TyCtxtInferExt}; use rustc_middle::hir::place::PlaceBase as HirPlaceBase; @@ -215,6 +216,14 @@ struct Builder<'a, 'tcx> { unit_temp: Option<Place<'tcx>>, var_debug_info: Vec<VarDebugInfo<'tcx>>, + + // A cache for `maybe_lint_level_roots_bounded`. That function is called + // repeatedly, and each time it effectively traces a path through a tree + // structure from a node towards the root, doing an attribute check on each + // node along the way. This cache records which nodes trace all the way to + // the root (most of them do) and saves us from retracing many sub-paths + // many times, and rechecking many nodes. + lint_level_roots_cache: GrowableBitSet<hir::ItemLocalId>, } type CaptureMap<'tcx> = SortedIndexMultiMap<usize, hir::HirId, Capture<'tcx>>; @@ -473,7 +482,7 @@ fn construct_fn<'tcx>( let (yield_ty, return_ty) = if generator_kind.is_some() { let gen_ty = arguments[thir::UPVAR_ENV_PARAM].ty; let gen_sig = match gen_ty.kind() { - ty::Generator(_, gen_substs, ..) => gen_substs.as_generator().sig(), + ty::Generator(_, gen_args, ..) => gen_args.as_generator().sig(), _ => { span_bug!(span, "generator w/o generator type: {:?}", gen_ty) } @@ -618,11 +627,9 @@ fn construct_error(tcx: TyCtxt<'_>, def: LocalDefId, err: ErrorGuaranteed) -> Bo let num_params = match body_owner_kind { hir::BodyOwnerKind::Fn => tcx.fn_sig(def).skip_binder().inputs().skip_binder().len(), hir::BodyOwnerKind::Closure => { - let ty = tcx.type_of(def).subst_identity(); + let ty = tcx.type_of(def).instantiate_identity(); match ty.kind() { - ty::Closure(_, substs) => { - 1 + substs.as_closure().sig().inputs().skip_binder().len() - } + ty::Closure(_, args) => 1 + args.as_closure().sig().inputs().skip_binder().len(), ty::Generator(..) => 2, _ => bug!("expected closure or generator, found {ty:?}"), } @@ -725,6 +732,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { var_indices: Default::default(), unit_temp: None, var_debug_info: vec![], + lint_level_roots_cache: GrowableBitSet::new_empty(), }; assert_eq!(builder.cfg.start_new_block(), START_BLOCK); @@ -768,9 +776,9 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { closure_ty = *ty; } - let upvar_substs = match closure_ty.kind() { - ty::Closure(_, substs) => ty::UpvarSubsts::Closure(substs), - ty::Generator(_, substs, _) => ty::UpvarSubsts::Generator(substs), + let upvar_args = match closure_ty.kind() { + ty::Closure(_, args) => ty::UpvarArgs::Closure(args), + ty::Generator(_, args, _) => ty::UpvarArgs::Generator(args), _ => return, }; @@ -779,7 +787,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { // with the closure's DefId. Here, we run through that vec of UpvarIds for // the given closure and use the necessary information to create upvar // debuginfo and to fill `self.upvars`. - let capture_tys = upvar_substs.upvar_tys(); + let capture_tys = upvar_args.upvar_tys(); let tcx = self.tcx; self.upvars = tcx diff --git a/compiler/rustc_mir_build/src/build/scope.rs b/compiler/rustc_mir_build/src/build/scope.rs index 72374102c8c..a96288a11e5 100644 --- a/compiler/rustc_mir_build/src/build/scope.rs +++ b/compiler/rustc_mir_build/src/build/scope.rs @@ -90,8 +90,8 @@ use rustc_index::{IndexSlice, IndexVec}; use rustc_middle::middle::region; use rustc_middle::mir::*; use rustc_middle::thir::{Expr, LintLevel}; - use rustc_middle::ty::Ty; +use rustc_session::lint::Level; use rustc_span::{Span, DUMMY_SP}; #[derive(Debug)] @@ -760,20 +760,25 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { ) { let (current_root, parent_root) = if self.tcx.sess.opts.unstable_opts.maximal_hir_to_mir_coverage { - // Some consumers of rustc need to map MIR locations back to HIR nodes. Currently the - // the only part of rustc that tracks MIR -> HIR is the `SourceScopeLocalData::lint_root` - // field that tracks lint levels for MIR locations. Normally the number of source scopes - // is limited to the set of nodes with lint annotations. The -Zmaximal-hir-to-mir-coverage - // flag changes this behavior to maximize the number of source scopes, increasing the - // granularity of the MIR->HIR mapping. + // Some consumers of rustc need to map MIR locations back to HIR nodes. Currently + // the the only part of rustc that tracks MIR -> HIR is the + // `SourceScopeLocalData::lint_root` field that tracks lint levels for MIR + // locations. Normally the number of source scopes is limited to the set of nodes + // with lint annotations. The -Zmaximal-hir-to-mir-coverage flag changes this + // behavior to maximize the number of source scopes, increasing the granularity of + // the MIR->HIR mapping. (current_id, parent_id) } else { - // Use `maybe_lint_level_root_bounded` with `self.hir_id` as a bound - // to avoid adding Hir dependencies on our parents. - // We estimate the true lint roots here to avoid creating a lot of source scopes. + // Use `maybe_lint_level_root_bounded` to avoid adding Hir dependencies on our + // parents. We estimate the true lint roots here to avoid creating a lot of source + // scopes. ( - self.tcx.maybe_lint_level_root_bounded(current_id, self.hir_id), - self.tcx.maybe_lint_level_root_bounded(parent_id, self.hir_id), + self.maybe_lint_level_root_bounded(current_id), + if parent_id == self.hir_id { + parent_id // this is very common + } else { + self.maybe_lint_level_root_bounded(parent_id) + }, ) }; @@ -783,6 +788,50 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } } + /// Walks upwards from `orig_id` to find a node which might change lint levels with attributes. + /// It stops at `self.hir_id` and just returns it if reached. + fn maybe_lint_level_root_bounded(&mut self, orig_id: HirId) -> HirId { + // This assertion lets us just store `ItemLocalId` in the cache, rather + // than the full `HirId`. + assert_eq!(orig_id.owner, self.hir_id.owner); + + let mut id = orig_id; + let hir = self.tcx.hir(); + loop { + if id == self.hir_id { + // This is a moderately common case, mostly hit for previously unseen nodes. + break; + } + + if hir.attrs(id).iter().any(|attr| Level::from_attr(attr).is_some()) { + // This is a rare case. It's for a node path that doesn't reach the root due to an + // intervening lint level attribute. This result doesn't get cached. + return id; + } + + let next = hir.parent_id(id); + if next == id { + bug!("lint traversal reached the root of the crate"); + } + id = next; + + // This lookup is just an optimization; it can be removed without affecting + // functionality. It might seem strange to see this at the end of this loop, but the + // `orig_id` passed in to this function is almost always previously unseen, for which a + // lookup will be a miss. So we only do lookups for nodes up the parent chain, where + // cache lookups have a very high hit rate. + if self.lint_level_roots_cache.contains(id.local_id) { + break; + } + } + + // `orig_id` traced to `self_id`; record this fact. If `orig_id` is a leaf node it will + // rarely (never?) subsequently be searched for, but it's hard to know if that is the case. + // The performance wins from the cache all come from caching non-leaf nodes. + self.lint_level_roots_cache.insert(orig_id.local_id); + self.hir_id + } + /// Creates a new source scope, nested in the current one. pub(crate) fn new_source_scope( &mut self, diff --git a/compiler/rustc_mir_build/src/check_unsafety.rs b/compiler/rustc_mir_build/src/check_unsafety.rs index 6b2b140fa25..192bd4a83e3 100644 --- a/compiler/rustc_mir_build/src/check_unsafety.rs +++ b/compiler/rustc_mir_build/src/check_unsafety.rs @@ -91,7 +91,12 @@ impl<'tcx> UnsafetyVisitor<'_, 'tcx> { kind.emit_unsafe_op_in_unsafe_fn_lint(self.tcx, self.hir_context, span); } SafetyContext::Safe => { - kind.emit_requires_unsafe_err(self.tcx, span, unsafe_op_in_unsafe_fn_allowed); + kind.emit_requires_unsafe_err( + self.tcx, + span, + self.hir_context, + unsafe_op_in_unsafe_fn_allowed, + ); } } } @@ -383,7 +388,7 @@ impl<'a, 'tcx> Visitor<'a, 'tcx> for UnsafetyVisitor<'a, 'tcx> { ExprKind::Adt(box AdtExpr { adt_def, variant_index: _, - substs: _, + args: _, user_ty: _, fields: _, base: _, @@ -393,14 +398,14 @@ impl<'a, 'tcx> Visitor<'a, 'tcx> for UnsafetyVisitor<'a, 'tcx> { }, ExprKind::Closure(box ClosureExpr { closure_id, - substs: _, + args: _, upvars: _, movability: _, fake_reads: _, }) => { self.visit_inner_body(closure_id); } - ExprKind::ConstBlock { did, substs: _ } => { + ExprKind::ConstBlock { did, args: _ } => { let def_id = did.expect_local(); self.visit_inner_body(def_id); } @@ -602,98 +607,164 @@ impl UnsafeOpKind { &self, tcx: TyCtxt<'_>, span: Span, + hir_context: hir::HirId, unsafe_op_in_unsafe_fn_allowed: bool, ) { + let note_non_inherited = tcx.hir().parent_iter(hir_context).find(|(id, node)| { + if let hir::Node::Expr(block) = node + && let hir::ExprKind::Block(block, _) = block.kind + && let hir::BlockCheckMode::UnsafeBlock(_) = block.rules + { + true + } + else if let Some(sig) = tcx.hir().fn_sig_by_hir_id(*id) + && sig.header.is_unsafe() + { + true + } else { + false + } + }); + let unsafe_not_inherited_note = if let Some((id, _)) = note_non_inherited { + let span = tcx.hir().span(id); + let span = tcx.sess.source_map().guess_head_span(span); + Some(UnsafeNotInheritedNote { span }) + } else { + None + }; + match self { CallToUnsafeFunction(Some(did)) if unsafe_op_in_unsafe_fn_allowed => { tcx.sess.emit_err(CallToUnsafeFunctionRequiresUnsafeUnsafeOpInUnsafeFnAllowed { span, + unsafe_not_inherited_note, function: &tcx.def_path_str(*did), }); } CallToUnsafeFunction(Some(did)) => { tcx.sess.emit_err(CallToUnsafeFunctionRequiresUnsafe { span, + unsafe_not_inherited_note, function: &tcx.def_path_str(*did), }); } CallToUnsafeFunction(None) if unsafe_op_in_unsafe_fn_allowed => { tcx.sess.emit_err( - CallToUnsafeFunctionRequiresUnsafeNamelessUnsafeOpInUnsafeFnAllowed { span }, + CallToUnsafeFunctionRequiresUnsafeNamelessUnsafeOpInUnsafeFnAllowed { + span, + unsafe_not_inherited_note, + }, ); } CallToUnsafeFunction(None) => { - tcx.sess.emit_err(CallToUnsafeFunctionRequiresUnsafeNameless { span }); + tcx.sess.emit_err(CallToUnsafeFunctionRequiresUnsafeNameless { + span, + unsafe_not_inherited_note, + }); } UseOfInlineAssembly if unsafe_op_in_unsafe_fn_allowed => { - tcx.sess - .emit_err(UseOfInlineAssemblyRequiresUnsafeUnsafeOpInUnsafeFnAllowed { span }); + tcx.sess.emit_err(UseOfInlineAssemblyRequiresUnsafeUnsafeOpInUnsafeFnAllowed { + span, + unsafe_not_inherited_note, + }); } UseOfInlineAssembly => { - tcx.sess.emit_err(UseOfInlineAssemblyRequiresUnsafe { span }); + tcx.sess.emit_err(UseOfInlineAssemblyRequiresUnsafe { + span, + unsafe_not_inherited_note, + }); } InitializingTypeWith if unsafe_op_in_unsafe_fn_allowed => { - tcx.sess - .emit_err(InitializingTypeWithRequiresUnsafeUnsafeOpInUnsafeFnAllowed { span }); + tcx.sess.emit_err(InitializingTypeWithRequiresUnsafeUnsafeOpInUnsafeFnAllowed { + span, + unsafe_not_inherited_note, + }); } InitializingTypeWith => { - tcx.sess.emit_err(InitializingTypeWithRequiresUnsafe { span }); + tcx.sess.emit_err(InitializingTypeWithRequiresUnsafe { + span, + unsafe_not_inherited_note, + }); } UseOfMutableStatic if unsafe_op_in_unsafe_fn_allowed => { - tcx.sess - .emit_err(UseOfMutableStaticRequiresUnsafeUnsafeOpInUnsafeFnAllowed { span }); + tcx.sess.emit_err(UseOfMutableStaticRequiresUnsafeUnsafeOpInUnsafeFnAllowed { + span, + unsafe_not_inherited_note, + }); } UseOfMutableStatic => { - tcx.sess.emit_err(UseOfMutableStaticRequiresUnsafe { span }); + tcx.sess + .emit_err(UseOfMutableStaticRequiresUnsafe { span, unsafe_not_inherited_note }); } UseOfExternStatic if unsafe_op_in_unsafe_fn_allowed => { - tcx.sess - .emit_err(UseOfExternStaticRequiresUnsafeUnsafeOpInUnsafeFnAllowed { span }); + tcx.sess.emit_err(UseOfExternStaticRequiresUnsafeUnsafeOpInUnsafeFnAllowed { + span, + unsafe_not_inherited_note, + }); } UseOfExternStatic => { - tcx.sess.emit_err(UseOfExternStaticRequiresUnsafe { span }); + tcx.sess + .emit_err(UseOfExternStaticRequiresUnsafe { span, unsafe_not_inherited_note }); } DerefOfRawPointer if unsafe_op_in_unsafe_fn_allowed => { - tcx.sess - .emit_err(DerefOfRawPointerRequiresUnsafeUnsafeOpInUnsafeFnAllowed { span }); + tcx.sess.emit_err(DerefOfRawPointerRequiresUnsafeUnsafeOpInUnsafeFnAllowed { + span, + unsafe_not_inherited_note, + }); } DerefOfRawPointer => { - tcx.sess.emit_err(DerefOfRawPointerRequiresUnsafe { span }); + tcx.sess + .emit_err(DerefOfRawPointerRequiresUnsafe { span, unsafe_not_inherited_note }); } AccessToUnionField if unsafe_op_in_unsafe_fn_allowed => { - tcx.sess - .emit_err(AccessToUnionFieldRequiresUnsafeUnsafeOpInUnsafeFnAllowed { span }); + tcx.sess.emit_err(AccessToUnionFieldRequiresUnsafeUnsafeOpInUnsafeFnAllowed { + span, + unsafe_not_inherited_note, + }); } AccessToUnionField => { - tcx.sess.emit_err(AccessToUnionFieldRequiresUnsafe { span }); + tcx.sess + .emit_err(AccessToUnionFieldRequiresUnsafe { span, unsafe_not_inherited_note }); } MutationOfLayoutConstrainedField if unsafe_op_in_unsafe_fn_allowed => { tcx.sess.emit_err( MutationOfLayoutConstrainedFieldRequiresUnsafeUnsafeOpInUnsafeFnAllowed { span, + unsafe_not_inherited_note, }, ); } MutationOfLayoutConstrainedField => { - tcx.sess.emit_err(MutationOfLayoutConstrainedFieldRequiresUnsafe { span }); + tcx.sess.emit_err(MutationOfLayoutConstrainedFieldRequiresUnsafe { + span, + unsafe_not_inherited_note, + }); } BorrowOfLayoutConstrainedField if unsafe_op_in_unsafe_fn_allowed => { tcx.sess.emit_err( - BorrowOfLayoutConstrainedFieldRequiresUnsafeUnsafeOpInUnsafeFnAllowed { span }, + BorrowOfLayoutConstrainedFieldRequiresUnsafeUnsafeOpInUnsafeFnAllowed { + span, + unsafe_not_inherited_note, + }, ); } BorrowOfLayoutConstrainedField => { - tcx.sess.emit_err(BorrowOfLayoutConstrainedFieldRequiresUnsafe { span }); + tcx.sess.emit_err(BorrowOfLayoutConstrainedFieldRequiresUnsafe { + span, + unsafe_not_inherited_note, + }); } CallToFunctionWith(did) if unsafe_op_in_unsafe_fn_allowed => { tcx.sess.emit_err(CallToFunctionWithRequiresUnsafeUnsafeOpInUnsafeFnAllowed { span, + unsafe_not_inherited_note, function: &tcx.def_path_str(*did), }); } CallToFunctionWith(did) => { tcx.sess.emit_err(CallToFunctionWithRequiresUnsafe { span, + unsafe_not_inherited_note, function: &tcx.def_path_str(*did), }); } @@ -712,9 +783,7 @@ pub fn thir_check_unsafety(tcx: TyCtxt<'_>, def: LocalDefId) { return; } - let Ok((thir, expr)) = tcx.thir_body(def) else { - return - }; + let Ok((thir, expr)) = tcx.thir_body(def) else { return }; let thir = &thir.borrow(); // If `thir` is empty, a type error occurred, skip this body. if thir.exprs.is_empty() { diff --git a/compiler/rustc_mir_build/src/errors.rs b/compiler/rustc_mir_build/src/errors.rs index df00cc75cc7..820ab93851e 100644 --- a/compiler/rustc_mir_build/src/errors.rs +++ b/compiler/rustc_mir_build/src/errors.rs @@ -119,6 +119,8 @@ pub struct CallToUnsafeFunctionRequiresUnsafe<'a> { #[label] pub span: Span, pub function: &'a str, + #[subdiagnostic] + pub unsafe_not_inherited_note: Option<UnsafeNotInheritedNote>, } #[derive(Diagnostic)] @@ -128,6 +130,8 @@ pub struct CallToUnsafeFunctionRequiresUnsafeNameless { #[primary_span] #[label] pub span: Span, + #[subdiagnostic] + pub unsafe_not_inherited_note: Option<UnsafeNotInheritedNote>, } #[derive(Diagnostic)] @@ -138,6 +142,8 @@ pub struct CallToUnsafeFunctionRequiresUnsafeUnsafeOpInUnsafeFnAllowed<'a> { #[label] pub span: Span, pub function: &'a str, + #[subdiagnostic] + pub unsafe_not_inherited_note: Option<UnsafeNotInheritedNote>, } #[derive(Diagnostic)] @@ -150,6 +156,8 @@ pub struct CallToUnsafeFunctionRequiresUnsafeNamelessUnsafeOpInUnsafeFnAllowed { #[primary_span] #[label] pub span: Span, + #[subdiagnostic] + pub unsafe_not_inherited_note: Option<UnsafeNotInheritedNote>, } #[derive(Diagnostic)] @@ -159,6 +167,8 @@ pub struct UseOfInlineAssemblyRequiresUnsafe { #[primary_span] #[label] pub span: Span, + #[subdiagnostic] + pub unsafe_not_inherited_note: Option<UnsafeNotInheritedNote>, } #[derive(Diagnostic)] @@ -168,6 +178,8 @@ pub struct UseOfInlineAssemblyRequiresUnsafeUnsafeOpInUnsafeFnAllowed { #[primary_span] #[label] pub span: Span, + #[subdiagnostic] + pub unsafe_not_inherited_note: Option<UnsafeNotInheritedNote>, } #[derive(Diagnostic)] @@ -177,6 +189,8 @@ pub struct InitializingTypeWithRequiresUnsafe { #[primary_span] #[label] pub span: Span, + #[subdiagnostic] + pub unsafe_not_inherited_note: Option<UnsafeNotInheritedNote>, } #[derive(Diagnostic)] @@ -189,6 +203,8 @@ pub struct InitializingTypeWithRequiresUnsafeUnsafeOpInUnsafeFnAllowed { #[primary_span] #[label] pub span: Span, + #[subdiagnostic] + pub unsafe_not_inherited_note: Option<UnsafeNotInheritedNote>, } #[derive(Diagnostic)] @@ -198,6 +214,8 @@ pub struct UseOfMutableStaticRequiresUnsafe { #[primary_span] #[label] pub span: Span, + #[subdiagnostic] + pub unsafe_not_inherited_note: Option<UnsafeNotInheritedNote>, } #[derive(Diagnostic)] @@ -207,6 +225,8 @@ pub struct UseOfMutableStaticRequiresUnsafeUnsafeOpInUnsafeFnAllowed { #[primary_span] #[label] pub span: Span, + #[subdiagnostic] + pub unsafe_not_inherited_note: Option<UnsafeNotInheritedNote>, } #[derive(Diagnostic)] @@ -216,6 +236,8 @@ pub struct UseOfExternStaticRequiresUnsafe { #[primary_span] #[label] pub span: Span, + #[subdiagnostic] + pub unsafe_not_inherited_note: Option<UnsafeNotInheritedNote>, } #[derive(Diagnostic)] @@ -225,6 +247,8 @@ pub struct UseOfExternStaticRequiresUnsafeUnsafeOpInUnsafeFnAllowed { #[primary_span] #[label] pub span: Span, + #[subdiagnostic] + pub unsafe_not_inherited_note: Option<UnsafeNotInheritedNote>, } #[derive(Diagnostic)] @@ -234,6 +258,8 @@ pub struct DerefOfRawPointerRequiresUnsafe { #[primary_span] #[label] pub span: Span, + #[subdiagnostic] + pub unsafe_not_inherited_note: Option<UnsafeNotInheritedNote>, } #[derive(Diagnostic)] @@ -243,6 +269,8 @@ pub struct DerefOfRawPointerRequiresUnsafeUnsafeOpInUnsafeFnAllowed { #[primary_span] #[label] pub span: Span, + #[subdiagnostic] + pub unsafe_not_inherited_note: Option<UnsafeNotInheritedNote>, } #[derive(Diagnostic)] @@ -252,6 +280,8 @@ pub struct AccessToUnionFieldRequiresUnsafe { #[primary_span] #[label] pub span: Span, + #[subdiagnostic] + pub unsafe_not_inherited_note: Option<UnsafeNotInheritedNote>, } #[derive(Diagnostic)] @@ -261,6 +291,8 @@ pub struct AccessToUnionFieldRequiresUnsafeUnsafeOpInUnsafeFnAllowed { #[primary_span] #[label] pub span: Span, + #[subdiagnostic] + pub unsafe_not_inherited_note: Option<UnsafeNotInheritedNote>, } #[derive(Diagnostic)] @@ -270,6 +302,8 @@ pub struct MutationOfLayoutConstrainedFieldRequiresUnsafe { #[primary_span] #[label] pub span: Span, + #[subdiagnostic] + pub unsafe_not_inherited_note: Option<UnsafeNotInheritedNote>, } #[derive(Diagnostic)] @@ -282,6 +316,8 @@ pub struct MutationOfLayoutConstrainedFieldRequiresUnsafeUnsafeOpInUnsafeFnAllow #[primary_span] #[label] pub span: Span, + #[subdiagnostic] + pub unsafe_not_inherited_note: Option<UnsafeNotInheritedNote>, } #[derive(Diagnostic)] @@ -291,6 +327,8 @@ pub struct BorrowOfLayoutConstrainedFieldRequiresUnsafe { #[primary_span] #[label] pub span: Span, + #[subdiagnostic] + pub unsafe_not_inherited_note: Option<UnsafeNotInheritedNote>, } #[derive(Diagnostic)] @@ -303,6 +341,8 @@ pub struct BorrowOfLayoutConstrainedFieldRequiresUnsafeUnsafeOpInUnsafeFnAllowed #[primary_span] #[label] pub span: Span, + #[subdiagnostic] + pub unsafe_not_inherited_note: Option<UnsafeNotInheritedNote>, } #[derive(Diagnostic)] @@ -313,6 +353,8 @@ pub struct CallToFunctionWithRequiresUnsafe<'a> { #[label] pub span: Span, pub function: &'a str, + #[subdiagnostic] + pub unsafe_not_inherited_note: Option<UnsafeNotInheritedNote>, } #[derive(Diagnostic)] @@ -323,6 +365,15 @@ pub struct CallToFunctionWithRequiresUnsafeUnsafeOpInUnsafeFnAllowed<'a> { #[label] pub span: Span, pub function: &'a str, + #[subdiagnostic] + pub unsafe_not_inherited_note: Option<UnsafeNotInheritedNote>, +} + +#[derive(Subdiagnostic)] +#[label(mir_build_unsafe_not_inherited)] +pub struct UnsafeNotInheritedNote { + #[primary_span] + pub span: Span, } #[derive(LintDiagnostic)] diff --git a/compiler/rustc_mir_build/src/lints.rs b/compiler/rustc_mir_build/src/lints.rs index 8e41957af0e..3f0cc69ec59 100644 --- a/compiler/rustc_mir_build/src/lints.rs +++ b/compiler/rustc_mir_build/src/lints.rs @@ -4,8 +4,8 @@ use rustc_data_structures::graph::iterate::{ }; use rustc_hir::def::DefKind; use rustc_middle::mir::{self, BasicBlock, BasicBlocks, Body, Operand, TerminatorKind}; -use rustc_middle::ty::subst::{GenericArg, InternalSubsts}; use rustc_middle::ty::{self, Instance, TyCtxt}; +use rustc_middle::ty::{GenericArg, GenericArgs}; use rustc_session::lint::builtin::UNCONDITIONAL_RECURSION; use rustc_span::Span; use std::ops::ControlFlow; @@ -14,16 +14,16 @@ pub(crate) fn check<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>) { let def_id = body.source.def_id().expect_local(); if let DefKind::Fn | DefKind::AssocFn = tcx.def_kind(def_id) { - // If this is trait/impl method, extract the trait's substs. - let trait_substs = match tcx.trait_of_item(def_id.to_def_id()) { + // If this is trait/impl method, extract the trait's args. + let trait_args = match tcx.trait_of_item(def_id.to_def_id()) { Some(trait_def_id) => { - let trait_substs_count = tcx.generics_of(trait_def_id).count(); - &InternalSubsts::identity_for_item(tcx, def_id)[..trait_substs_count] + let trait_args_count = tcx.generics_of(trait_def_id).count(); + &GenericArgs::identity_for_item(tcx, def_id)[..trait_args_count] } _ => &[], }; - let mut vis = Search { tcx, body, reachable_recursive_calls: vec![], trait_substs }; + let mut vis = Search { tcx, body, reachable_recursive_calls: vec![], trait_args }; if let Some(NonRecursive) = TriColorDepthFirstSearch::new(&body.basic_blocks).run_from_start(&mut vis) { @@ -51,7 +51,7 @@ struct NonRecursive; struct Search<'mir, 'tcx> { tcx: TyCtxt<'tcx>, body: &'mir Body<'tcx>, - trait_substs: &'tcx [GenericArg<'tcx>], + trait_args: &'tcx [GenericArg<'tcx>], reachable_recursive_calls: Vec<Span>, } @@ -59,7 +59,7 @@ struct Search<'mir, 'tcx> { impl<'mir, 'tcx> Search<'mir, 'tcx> { /// Returns `true` if `func` refers to the function we are searching in. fn is_recursive_call(&self, func: &Operand<'tcx>, args: &[Operand<'tcx>]) -> bool { - let Search { tcx, body, trait_substs, .. } = *self; + let Search { tcx, body, trait_args, .. } = *self; // Resolving function type to a specific instance that is being called is expensive. To // avoid the cost we check the number of arguments first, which is sufficient to reject // most of calls as non-recursive. @@ -70,23 +70,23 @@ impl<'mir, 'tcx> Search<'mir, 'tcx> { let param_env = tcx.param_env(caller); let func_ty = func.ty(body, tcx); - if let ty::FnDef(callee, substs) = *func_ty.kind() { - let normalized_substs = tcx.normalize_erasing_regions(param_env, substs); - let (callee, call_substs) = if let Ok(Some(instance)) = - Instance::resolve(tcx, param_env, callee, normalized_substs) + if let ty::FnDef(callee, args) = *func_ty.kind() { + let normalized_args = tcx.normalize_erasing_regions(param_env, args); + let (callee, call_args) = if let Ok(Some(instance)) = + Instance::resolve(tcx, param_env, callee, normalized_args) { - (instance.def_id(), instance.substs) + (instance.def_id(), instance.args) } else { - (callee, normalized_substs) + (callee, normalized_args) }; // FIXME(#57965): Make this work across function boundaries - // If this is a trait fn, the substs on the trait have to match, or we might be + // If this is a trait fn, the args on the trait have to match, or we might be // calling into an entirely different method (for example, a call from the default // method in the trait to `<A as Trait<B>>::method`, where `A` and/or `B` are // specific types). - return callee == caller && &call_substs[..trait_substs.len()] == trait_substs; + return callee == caller && &call_args[..trait_args.len()] == trait_args; } false diff --git a/compiler/rustc_mir_build/src/thir/cx/expr.rs b/compiler/rustc_mir_build/src/thir/cx/expr.rs index 37537683f0d..711a9126c04 100644 --- a/compiler/rustc_mir_build/src/thir/cx/expr.rs +++ b/compiler/rustc_mir_build/src/thir/cx/expr.rs @@ -15,9 +15,9 @@ use rustc_middle::thir::*; use rustc_middle::ty::adjustment::{ Adjust, Adjustment, AutoBorrow, AutoBorrowMutability, PointerCoercion, }; -use rustc_middle::ty::subst::InternalSubsts; +use rustc_middle::ty::GenericArgs; use rustc_middle::ty::{ - self, AdtKind, InlineConstSubsts, InlineConstSubstsParts, ScalarInt, Ty, UpvarSubsts, UserType, + self, AdtKind, InlineConstArgs, InlineConstArgsParts, ScalarInt, Ty, UpvarArgs, UserType, }; use rustc_span::{sym, Span}; use rustc_target::abi::{FieldIdx, FIRST_VARIANT}; @@ -41,11 +41,6 @@ impl<'tcx> Cx<'tcx> { let mut expr = self.make_mirror_unadjusted(hir_expr); - let adjustment_span = match self.adjustment_span { - Some((hir_id, span)) if hir_id == hir_expr.hir_id => Some(span), - _ => None, - }; - trace!(?expr.ty); // Now apply adjustments, if any. @@ -53,12 +48,7 @@ impl<'tcx> Cx<'tcx> { for adjustment in self.typeck_results.expr_adjustments(hir_expr) { trace!(?expr, ?adjustment); let span = expr.span; - expr = self.apply_adjustment( - hir_expr, - expr, - adjustment, - adjustment_span.unwrap_or(span), - ); + expr = self.apply_adjustment(hir_expr, expr, adjustment, span); } } @@ -220,7 +210,7 @@ impl<'tcx> Cx<'tcx> { let res = self.typeck_results().qpath_res(qpath, source.hir_id); let ty = self.typeck_results().node_type(source.hir_id); - let ty::Adt(adt_def, substs) = ty.kind() else { + let ty::Adt(adt_def, args) = ty.kind() else { return ExprKind::Cast { source: self.mirror_expr(source) }; }; @@ -252,7 +242,7 @@ impl<'tcx> Cx<'tcx> { // in case we are offsetting from a computed discriminant // and not the beginning of discriminants (which is always `0`) Some(did) => { - let kind = ExprKind::NamedConst { def_id: did, substs, user_ty: None }; + let kind = ExprKind::NamedConst { def_id: did, args, user_ty: None }; let lhs = self.thir.exprs.push(Expr { temp_lifetime, ty: discr_ty, span, kind }); let bin = ExprKind::Binary { op: BinOp::Add, lhs, rhs: offset }; @@ -274,7 +264,6 @@ impl<'tcx> Cx<'tcx> { fn make_mirror_unadjusted(&mut self, expr: &'tcx hir::Expr<'tcx>) -> Expr<'tcx> { let tcx = self.tcx; let expr_ty = self.typeck_results().expr_ty(expr); - let expr_span = expr.span; let temp_lifetime = self.rvalue_scopes.temporary_scope(self.region_scope_tree, expr.hir_id.local_id); @@ -283,17 +272,11 @@ impl<'tcx> Cx<'tcx> { hir::ExprKind::MethodCall(segment, receiver, ref args, fn_span) => { // Rewrite a.b(c) into UFCS form like Trait::b(a, c) let expr = self.method_callee(expr, segment.ident.span, None); - // When we apply adjustments to the receiver, use the span of - // the overall method call for better diagnostics. args[0] - // is guaranteed to exist, since a method call always has a receiver. - let old_adjustment_span = - self.adjustment_span.replace((receiver.hir_id, expr_span)); info!("Using method span: {:?}", expr.span); let args = std::iter::once(receiver) .chain(args.iter()) .map(|expr| self.mirror_expr(expr)) .collect(); - self.adjustment_span = old_adjustment_span; ExprKind::Call { ty: expr.ty, fun: self.thir.exprs.push(expr), @@ -389,7 +372,7 @@ impl<'tcx> Cx<'tcx> { None }; if let Some((adt_def, index)) = adt_data { - let substs = self.typeck_results().node_substs(fun.hir_id); + let node_args = self.typeck_results().node_args(fun.hir_id); let user_provided_types = self.typeck_results().user_provided_types(); let user_ty = user_provided_types.get(fun.hir_id).copied().map(|mut u_ty| { @@ -410,7 +393,7 @@ impl<'tcx> Cx<'tcx> { .collect(); ExprKind::Adt(Box::new(AdtExpr { adt_def, - substs, + args: node_args, variant_index: index, fields: field_refs, user_ty, @@ -528,7 +511,7 @@ impl<'tcx> Cx<'tcx> { } hir::ExprKind::Struct(ref qpath, ref fields, ref base) => match expr_ty.kind() { - ty::Adt(adt, substs) => match adt.adt_kind() { + ty::Adt(adt, args) => match adt.adt_kind() { AdtKind::Struct | AdtKind::Union => { let user_provided_types = self.typeck_results().user_provided_types(); let user_ty = user_provided_types.get(expr.hir_id).copied().map(Box::new); @@ -536,7 +519,7 @@ impl<'tcx> Cx<'tcx> { ExprKind::Adt(Box::new(AdtExpr { adt_def: *adt, variant_index: FIRST_VARIANT, - substs, + args, user_ty, fields: self.field_refs(fields), base: base.map(|base| FruInfo { @@ -563,7 +546,7 @@ impl<'tcx> Cx<'tcx> { ExprKind::Adt(Box::new(AdtExpr { adt_def: *adt, variant_index: index, - substs, + args, user_ty, fields: self.field_refs(fields), base: None, @@ -582,10 +565,10 @@ impl<'tcx> Cx<'tcx> { hir::ExprKind::Closure { .. } => { let closure_ty = self.typeck_results().expr_ty(expr); - let (def_id, substs, movability) = match *closure_ty.kind() { - ty::Closure(def_id, substs) => (def_id, UpvarSubsts::Closure(substs), None), - ty::Generator(def_id, substs, movability) => { - (def_id, UpvarSubsts::Generator(substs), Some(movability)) + let (def_id, args, movability) = match *closure_ty.kind() { + ty::Closure(def_id, args) => (def_id, UpvarArgs::Closure(args), None), + ty::Generator(def_id, args, movability) => { + (def_id, UpvarArgs::Generator(args), Some(movability)) } _ => { span_bug!(expr.span, "closure expr w/o closure type: {:?}", closure_ty); @@ -597,7 +580,7 @@ impl<'tcx> Cx<'tcx> { .tcx .closure_captures(def_id) .iter() - .zip(substs.upvar_tys()) + .zip(args.upvar_tys()) .map(|(captured_place, ty)| { let upvars = self.capture_upvar(expr, captured_place, ty); self.thir.exprs.push(upvars) @@ -618,7 +601,7 @@ impl<'tcx> Cx<'tcx> { ExprKind::Closure(Box::new(ClosureExpr { closure_id: def_id, - substs, + args, upvars, movability, fake_reads, @@ -701,13 +684,11 @@ impl<'tcx> Cx<'tcx> { let ty = self.typeck_results().node_type(anon_const.hir_id); let did = anon_const.def_id.to_def_id(); let typeck_root_def_id = tcx.typeck_root_def_id(did); - let parent_substs = - tcx.erase_regions(InternalSubsts::identity_for_item(tcx, typeck_root_def_id)); - let substs = - InlineConstSubsts::new(tcx, InlineConstSubstsParts { parent_substs, ty }) - .substs; + let parent_args = + tcx.erase_regions(GenericArgs::identity_for_item(tcx, typeck_root_def_id)); + let args = InlineConstArgs::new(tcx, InlineConstArgsParts { parent_args, ty }).args; - ExprKind::ConstBlock { did, substs } + ExprKind::ConstBlock { did, args } } // Now comes the rote stuff: hir::ExprKind::Repeat(ref v, _) => { @@ -826,12 +807,12 @@ impl<'tcx> Cx<'tcx> { Expr { temp_lifetime, ty: expr_ty, span: expr.span, kind } } - fn user_substs_applied_to_res( + fn user_args_applied_to_res( &mut self, hir_id: hir::HirId, res: Res, ) -> Option<Box<ty::CanonicalUserType<'tcx>>> { - debug!("user_substs_applied_to_res: res={:?}", res); + debug!("user_args_applied_to_res: res={:?}", res); let user_provided_type = match res { // A reference to something callable -- e.g., a fn, method, or // a tuple-struct or tuple-variant. This has the type of a @@ -849,15 +830,15 @@ impl<'tcx> Cx<'tcx> { // this variant -- but with the substitutions given by the // user. Res::Def(DefKind::Ctor(_, CtorKind::Const), _) => { - self.user_substs_applied_to_ty_of_hir_id(hir_id).map(Box::new) + self.user_args_applied_to_ty_of_hir_id(hir_id).map(Box::new) } // `Self` is used in expression as a tuple struct constructor or a unit struct constructor - Res::SelfCtor(_) => self.user_substs_applied_to_ty_of_hir_id(hir_id).map(Box::new), + Res::SelfCtor(_) => self.user_args_applied_to_ty_of_hir_id(hir_id).map(Box::new), - _ => bug!("user_substs_applied_to_res: unexpected res {:?} at {:?}", res, hir_id), + _ => bug!("user_args_applied_to_res: unexpected res {:?} at {:?}", res, hir_id), }; - debug!("user_substs_applied_to_res: user_provided_type={:?}", user_provided_type); + debug!("user_args_applied_to_res: user_provided_type={:?}", user_provided_type); user_provided_type } @@ -876,13 +857,13 @@ impl<'tcx> Cx<'tcx> { self.typeck_results().type_dependent_def(expr.hir_id).unwrap_or_else(|| { span_bug!(expr.span, "no type-dependent def for method callee") }); - let user_ty = self.user_substs_applied_to_res(expr.hir_id, Res::Def(kind, def_id)); + let user_ty = self.user_args_applied_to_res(expr.hir_id, Res::Def(kind, def_id)); debug!("method_callee: user_ty={:?}", user_ty); ( Ty::new_fn_def( self.tcx(), def_id, - self.typeck_results().node_substs(expr.hir_id), + self.typeck_results().node_args(expr.hir_id), ), user_ty, ) @@ -909,14 +890,14 @@ impl<'tcx> Cx<'tcx> { } fn convert_path_expr(&mut self, expr: &'tcx hir::Expr<'tcx>, res: Res) -> ExprKind<'tcx> { - let substs = self.typeck_results().node_substs(expr.hir_id); + let args = self.typeck_results().node_args(expr.hir_id); match res { // A regular function, constructor function or a constant. Res::Def(DefKind::Fn, _) | Res::Def(DefKind::AssocFn, _) | Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) | Res::SelfCtor(_) => { - let user_ty = self.user_substs_applied_to_res(expr.hir_id, res); + let user_ty = self.user_args_applied_to_res(expr.hir_id, res); ExprKind::ZstLiteral { user_ty } } @@ -931,8 +912,8 @@ impl<'tcx> Cx<'tcx> { } Res::Def(DefKind::Const, def_id) | Res::Def(DefKind::AssocConst, def_id) => { - let user_ty = self.user_substs_applied_to_res(expr.hir_id, res); - ExprKind::NamedConst { def_id, substs, user_ty } + let user_ty = self.user_args_applied_to_res(expr.hir_id, res); + ExprKind::NamedConst { def_id, args, user_ty } } Res::Def(DefKind::Ctor(_, CtorKind::Const), def_id) => { @@ -943,10 +924,10 @@ impl<'tcx> Cx<'tcx> { match ty.kind() { // A unit struct/variant which is used as a value. // We return a completely different ExprKind here to account for this special case. - ty::Adt(adt_def, substs) => ExprKind::Adt(Box::new(AdtExpr { + ty::Adt(adt_def, args) => ExprKind::Adt(Box::new(AdtExpr { adt_def: *adt_def, variant_index: adt_def.variant_index_with_ctor_id(def_id), - substs, + args, user_ty, fields: Box::new([]), base: None, diff --git a/compiler/rustc_mir_build/src/thir/cx/mod.rs b/compiler/rustc_mir_build/src/thir/cx/mod.rs index e6a98d1aab0..d98cc76adfb 100644 --- a/compiler/rustc_mir_build/src/thir/cx/mod.rs +++ b/compiler/rustc_mir_build/src/thir/cx/mod.rs @@ -16,7 +16,6 @@ use rustc_hir::Node; use rustc_middle::middle::region; use rustc_middle::thir::*; use rustc_middle::ty::{self, RvalueScopes, Ty, TyCtxt}; -use rustc_span::Span; pub(crate) fn thir_body( tcx: TyCtxt<'_>, @@ -62,14 +61,6 @@ struct Cx<'tcx> { typeck_results: &'tcx ty::TypeckResults<'tcx>, rvalue_scopes: &'tcx RvalueScopes, - /// When applying adjustments to the expression - /// with the given `HirId`, use the given `Span`, - /// instead of the usual span. This is used to - /// assign the span of an overall method call - /// (e.g. `my_val.foo()`) to the adjustment expressions - /// for the receiver. - adjustment_span: Option<(HirId, Span)>, - /// False to indicate that adjustments should not be applied. Only used for `custom_mir` apply_adjustments: bool, @@ -110,7 +101,6 @@ impl<'tcx> Cx<'tcx> { typeck_results, rvalue_scopes: &typeck_results.rvalue_scopes, body_owner: def.to_def_id(), - adjustment_span: None, apply_adjustments: hir .attrs(hir_id) .iter() @@ -132,7 +122,7 @@ impl<'tcx> Cx<'tcx> { DefKind::Closure => { let closure_ty = self.typeck_results.node_type(owner_id); - let ty::Closure(closure_def_id, closure_substs) = *closure_ty.kind() else { + let ty::Closure(closure_def_id, closure_args) = *closure_ty.kind() else { bug!("closure expr does not have closure type: {:?}", closure_ty); }; @@ -144,7 +134,7 @@ impl<'tcx> Cx<'tcx> { }; let env_region = ty::Region::new_late_bound(self.tcx, ty::INNERMOST, br); let closure_env_ty = - self.tcx.closure_env_ty(closure_def_id, closure_substs, env_region).unwrap(); + self.tcx.closure_env_ty(closure_def_id, closure_args, env_region).unwrap(); let liberated_closure_env_ty = self.tcx.erase_late_bound_regions( ty::Binder::bind_with_vars(closure_env_ty, bound_vars), ); @@ -196,7 +186,7 @@ impl<'tcx> Cx<'tcx> { self.tcx .type_of(va_list_did) - .subst(self.tcx, &[self.tcx.lifetimes.re_erased.into()]) + .instantiate(self.tcx, &[self.tcx.lifetimes.re_erased.into()]) } else { fn_sig.inputs()[index] }; diff --git a/compiler/rustc_mir_build/src/thir/pattern/check_match.rs b/compiler/rustc_mir_build/src/thir/pattern/check_match.rs index ef60f08bf02..38c866c50a2 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/check_match.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/check_match.rs @@ -501,12 +501,12 @@ impl<'p, 'tcx> MatchVisitor<'_, 'p, 'tcx> { let witness_1_is_privately_uninhabited = if cx.tcx.features().exhaustive_patterns && let Some(witness_1) = witnesses.get(0) - && let ty::Adt(adt, substs) = witness_1.ty().kind() + && let ty::Adt(adt, args) = witness_1.ty().kind() && adt.is_enum() && let Constructor::Variant(variant_index) = witness_1.ctor() { let variant = adt.variant(*variant_index); - let inhabited = variant.inhabited_predicate(cx.tcx, *adt).subst(cx.tcx, substs); + let inhabited = variant.inhabited_predicate(cx.tcx, *adt).instantiate(cx.tcx, args); assert!(inhabited.apply(cx.tcx, cx.param_env, cx.module)); !inhabited.apply_ignore_module(cx.tcx, cx.param_env) } else { @@ -942,7 +942,9 @@ fn maybe_point_at_variant<'a, 'p: 'a, 'tcx: 'a>( /// This analysis is *not* subsumed by NLL. fn check_borrow_conflicts_in_at_patterns<'tcx>(cx: &MatchVisitor<'_, '_, 'tcx>, pat: &Pat<'tcx>) { // Extract `sub` in `binding @ sub`. - let PatKind::Binding { name, mode, ty, subpattern: Some(box ref sub), .. } = pat.kind else { return }; + let PatKind::Binding { name, mode, ty, subpattern: Some(box ref sub), .. } = pat.kind else { + return; + }; let is_binding_by_move = |ty: Ty<'tcx>| !ty.is_copy_modulo_regions(cx.tcx, cx.param_env); diff --git a/compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs b/compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs index 050b01294b4..251c6b4b6da 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs @@ -332,20 +332,20 @@ impl<'tcx> ConstToPat<'tcx> { tcx.sess.emit_err(err); PatKind::Wild } - ty::Adt(adt_def, substs) if adt_def.is_enum() => { + ty::Adt(adt_def, args) if adt_def.is_enum() => { let (&variant_index, fields) = cv.unwrap_branch().split_first().unwrap(); let variant_index = VariantIdx::from_u32(variant_index.unwrap_leaf().try_to_u32().ok().unwrap()); PatKind::Variant { adt_def: *adt_def, - substs, + args, variant_index, subpatterns: self.field_pats( fields.iter().copied().zip( adt_def.variants()[variant_index] .fields .iter() - .map(|field| field.ty(self.tcx(), substs)), + .map(|field| field.ty(self.tcx(), args)), ), )?, } @@ -354,9 +354,9 @@ impl<'tcx> ConstToPat<'tcx> { subpatterns: self .field_pats(cv.unwrap_branch().iter().copied().zip(fields.iter()))?, }, - ty::Adt(def, substs) => PatKind::Leaf { + ty::Adt(def, args) => PatKind::Leaf { subpatterns: self.field_pats(cv.unwrap_branch().iter().copied().zip( - def.non_enum_variant().fields.iter().map(|field| field.ty(self.tcx(), substs)), + def.non_enum_variant().fields.iter().map(|field| field.ty(self.tcx(), args)), ))?, }, ty::Slice(elem_ty) => PatKind::Slice { diff --git a/compiler/rustc_mir_build/src/thir/pattern/deconstruct_pat.rs b/compiler/rustc_mir_build/src/thir/pattern/deconstruct_pat.rs index 9df6d2f43ad..4228597cdc9 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/deconstruct_pat.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/deconstruct_pat.rs @@ -922,7 +922,7 @@ impl<'tcx> SplitWildcard<'tcx> { let kind = if cx.is_uninhabited(*sub_ty) { FixedLen(0) } else { VarLen(0, 0) }; smallvec![Slice(Slice::new(None, kind))] } - ty::Adt(def, substs) if def.is_enum() => { + ty::Adt(def, args) if def.is_enum() => { // If the enum is declared as `#[non_exhaustive]`, we treat it as if it had an // additional "unknown" constructor. // There is no point in enumerating all possible variants, because the user can't @@ -950,21 +950,19 @@ impl<'tcx> SplitWildcard<'tcx> { let is_secretly_empty = def.variants().is_empty() && !is_exhaustive_pat_feature && !pcx.is_top_level; - let mut ctors: SmallVec<[_; 1]> = def - .variants() - .iter_enumerated() - .filter(|(_, v)| { - // If `exhaustive_patterns` is enabled, we exclude variants known to be - // uninhabited. - !is_exhaustive_pat_feature - || v.inhabited_predicate(cx.tcx, *def).subst(cx.tcx, substs).apply( - cx.tcx, - cx.param_env, - cx.module, - ) - }) - .map(|(idx, _)| Variant(idx)) - .collect(); + let mut ctors: SmallVec<[_; 1]> = + def.variants() + .iter_enumerated() + .filter(|(_, v)| { + // If `exhaustive_patterns` is enabled, we exclude variants known to be + // uninhabited. + !is_exhaustive_pat_feature + || v.inhabited_predicate(cx.tcx, *def) + .instantiate(cx.tcx, args) + .apply(cx.tcx, cx.param_env, cx.module) + }) + .map(|(idx, _)| Variant(idx)) + .collect(); if is_secretly_empty || is_declared_nonexhaustive { ctors.push(NonExhaustive); @@ -1156,12 +1154,12 @@ impl<'p, 'tcx> Fields<'p, 'tcx> { ty: Ty<'tcx>, variant: &'a VariantDef, ) -> impl Iterator<Item = (FieldIdx, Ty<'tcx>)> + Captures<'a> + Captures<'p> { - let ty::Adt(adt, substs) = ty.kind() else { bug!() }; + let ty::Adt(adt, args) = ty.kind() else { bug!() }; // Whether we must not match the fields of this variant exhaustively. let is_non_exhaustive = variant.is_field_list_non_exhaustive() && !adt.did().is_local(); variant.fields.iter().enumerate().filter_map(move |(i, field)| { - let ty = field.ty(cx.tcx, substs); + let ty = field.ty(cx.tcx, args); // `field.ty()` doesn't normalize after substituting. let ty = cx.tcx.normalize_erasing_regions(cx.param_env, ty); let is_visible = adt.is_enum() || field.vis.is_accessible_from(cx.module, cx.tcx); @@ -1183,11 +1181,11 @@ impl<'p, 'tcx> Fields<'p, 'tcx> { Single | Variant(_) => match pcx.ty.kind() { ty::Tuple(fs) => Fields::wildcards_from_tys(pcx.cx, fs.iter(), pcx.span), ty::Ref(_, rty, _) => Fields::wildcards_from_tys(pcx.cx, once(*rty), pcx.span), - ty::Adt(adt, substs) => { + ty::Adt(adt, args) => { if adt.is_box() { // The only legal patterns of type `Box` (outside `std`) are `_` and box // patterns. If we're here we can assume this is a box pattern. - Fields::wildcards_from_tys(pcx.cx, once(substs.type_at(0)), pcx.span) + Fields::wildcards_from_tys(pcx.cx, once(args.type_at(0)), pcx.span) } else { let variant = &adt.variant(constructor.variant_index_for_adt(*adt)); let tys = Fields::list_variant_nonhidden_fields(pcx.cx, pcx.ty, variant) @@ -1294,7 +1292,7 @@ impl<'p, 'tcx> DeconstructedPat<'p, 'tcx> { } fields = Fields::from_iter(cx, wilds); } - ty::Adt(adt, substs) if adt.is_box() => { + ty::Adt(adt, args) if adt.is_box() => { // The only legal patterns of type `Box` (outside `std`) are `_` and box // patterns. If we're here we can assume this is a box pattern. // FIXME(Nadrieril): A `Box` can in theory be matched either with `Box(_, @@ -1311,7 +1309,7 @@ impl<'p, 'tcx> DeconstructedPat<'p, 'tcx> { let pat = if let Some(pat) = pattern { mkpat(&pat.pattern) } else { - DeconstructedPat::wildcard(substs.type_at(0), pat.span) + DeconstructedPat::wildcard(args.type_at(0), pat.span) }; ctor = Single; fields = Fields::singleton(cx, pat); @@ -1437,7 +1435,7 @@ impl<'p, 'tcx> DeconstructedPat<'p, 'tcx> { // the pattern is a box pattern. PatKind::Deref { subpattern: subpatterns.next().unwrap() } } - ty::Adt(adt_def, substs) => { + ty::Adt(adt_def, args) => { let variant_index = self.ctor.variant_index_for_adt(*adt_def); let variant = &adt_def.variant(variant_index); let subpatterns = Fields::list_variant_nonhidden_fields(cx, self.ty, variant) @@ -1446,7 +1444,7 @@ impl<'p, 'tcx> DeconstructedPat<'p, 'tcx> { .collect(); if adt_def.is_enum() { - PatKind::Variant { adt_def: *adt_def, substs, variant_index, subpatterns } + PatKind::Variant { adt_def: *adt_def, args, variant_index, subpatterns } } else { PatKind::Leaf { subpatterns } } diff --git a/compiler/rustc_mir_build/src/thir/pattern/mod.rs b/compiler/rustc_mir_build/src/thir/pattern/mod.rs index 60099592784..3c3cbbf3614 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/mod.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/mod.rs @@ -23,10 +23,10 @@ use rustc_middle::mir::interpret::{ use rustc_middle::mir::{self, ConstantKind, UserTypeProjection}; use rustc_middle::mir::{BorrowKind, Mutability}; use rustc_middle::thir::{Ascription, BindingMode, FieldPat, LocalVarId, Pat, PatKind, PatRange}; -use rustc_middle::ty::subst::{GenericArg, SubstsRef}; use rustc_middle::ty::CanonicalUserTypeAnnotation; use rustc_middle::ty::TypeVisitableExt; use rustc_middle::ty::{self, AdtDef, Region, Ty, TyCtxt, UserType}; +use rustc_middle::ty::{GenericArg, GenericArgsRef}; use rustc_span::{Span, Symbol}; use rustc_target::abi::FieldIdx; @@ -416,8 +416,8 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { let enum_id = self.tcx.parent(variant_id); let adt_def = self.tcx.adt_def(enum_id); if adt_def.is_enum() { - let substs = match ty.kind() { - ty::Adt(_, substs) | ty::FnDef(_, substs) => substs, + let args = match ty.kind() { + ty::Adt(_, args) | ty::FnDef(_, args) => args, ty::Error(_) => { // Avoid ICE (#50585) return PatKind::Wild; @@ -426,7 +426,7 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { }; PatKind::Variant { adt_def, - substs, + args, variant_index: adt_def.variant_index_with_id(variant_id), subpatterns, } @@ -460,7 +460,7 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { } }; - if let Some(user_ty) = self.user_substs_applied_to_ty_of_hir_id(hir_id) { + if let Some(user_ty) = self.user_args_applied_to_ty_of_hir_id(hir_id) { debug!("lower_variant_or_leaf: kind={:?} user_ty={:?} span={:?}", kind, user_ty, span); let annotation = CanonicalUserTypeAnnotation { user_ty: Box::new(user_ty), @@ -496,13 +496,13 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { // Use `Reveal::All` here because patterns are always monomorphic even if their function // isn't. let param_env_reveal_all = self.param_env.with_reveal_all_normalized(self.tcx); - // N.B. There is no guarantee that substs collected in typeck results are fully normalized, + // N.B. There is no guarantee that args collected in typeck results are fully normalized, // so they need to be normalized in order to pass to `Instance::resolve`, which will ICE // if given unnormalized types. - let substs = self + let args = self .tcx - .normalize_erasing_regions(param_env_reveal_all, self.typeck_results.node_substs(id)); - let instance = match ty::Instance::resolve(self.tcx, param_env_reveal_all, def_id, substs) { + .normalize_erasing_regions(param_env_reveal_all, self.typeck_results.node_args(id)); + let instance = match ty::Instance::resolve(self.tcx, param_env_reveal_all, def_id, args) { Ok(Some(i)) => i, Ok(None) => { // It should be assoc consts if there's no error but we cannot resolve it. @@ -617,16 +617,14 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { } let typeck_root_def_id = tcx.typeck_root_def_id(def_id.to_def_id()); - let parent_substs = - tcx.erase_regions(ty::InternalSubsts::identity_for_item(tcx, typeck_root_def_id)); - let substs = - ty::InlineConstSubsts::new(tcx, ty::InlineConstSubstsParts { parent_substs, ty }) - .substs; + let parent_args = + tcx.erase_regions(ty::GenericArgs::identity_for_item(tcx, typeck_root_def_id)); + let args = ty::InlineConstArgs::new(tcx, ty::InlineConstArgsParts { parent_args, ty }).args; - let uneval = mir::UnevaluatedConst { def: def_id.to_def_id(), substs, promoted: None }; - debug_assert!(!substs.has_free_regions()); + let uneval = mir::UnevaluatedConst { def: def_id.to_def_id(), args, promoted: None }; + debug_assert!(!args.has_free_regions()); - let ct = ty::UnevaluatedConst { def: def_id.to_def_id(), substs: substs }; + let ct = ty::UnevaluatedConst { def: def_id.to_def_id(), args: args }; // First try using a valtree in order to destructure the constant into a pattern. if let Ok(Some(valtree)) = self.tcx.const_eval_resolve_for_typeck(self.param_env, ct, Some(span)) @@ -754,7 +752,7 @@ macro_rules! ClonePatternFoldableImpls { ClonePatternFoldableImpls! { <'tcx> Span, FieldIdx, Mutability, Symbol, LocalVarId, usize, Region<'tcx>, Ty<'tcx>, BindingMode, AdtDef<'tcx>, - SubstsRef<'tcx>, &'tcx GenericArg<'tcx>, UserType<'tcx>, + GenericArgsRef<'tcx>, &'tcx GenericArg<'tcx>, UserType<'tcx>, UserTypeProjection, CanonicalUserTypeAnnotation<'tcx> } @@ -804,10 +802,10 @@ impl<'tcx> PatternFoldable<'tcx> for PatKind<'tcx> { is_primary, } } - PatKind::Variant { adt_def, substs, variant_index, ref subpatterns } => { + PatKind::Variant { adt_def, args, variant_index, ref subpatterns } => { PatKind::Variant { adt_def: adt_def.fold_with(folder), - substs: substs.fold_with(folder), + args: args.fold_with(folder), variant_index, subpatterns: subpatterns.fold_with(folder), } diff --git a/compiler/rustc_mir_build/src/thir/print.rs b/compiler/rustc_mir_build/src/thir/print.rs index 8d7c624a805..903dbeeadfa 100644 --- a/compiler/rustc_mir_build/src/thir/print.rs +++ b/compiler/rustc_mir_build/src/thir/print.rs @@ -427,10 +427,10 @@ impl<'a, 'tcx> ThirPrinter<'a, 'tcx> { self.print_expr(*value, depth_lvl + 2); print_indented!(self, "}", depth_lvl); } - ConstBlock { did, substs } => { + ConstBlock { did, args } => { print_indented!(self, "ConstBlock {", depth_lvl); print_indented!(self, format!("did: {:?}", did), depth_lvl + 1); - print_indented!(self, format!("substs: {:?}", substs), depth_lvl + 1); + print_indented!(self, format!("args: {:?}", args), depth_lvl + 1); print_indented!(self, "}", depth_lvl); } Repeat { value, count } => { @@ -499,11 +499,11 @@ impl<'a, 'tcx> ThirPrinter<'a, 'tcx> { ZstLiteral { user_ty } => { print_indented!(self, format!("ZstLiteral(user_ty: {:?})", user_ty), depth_lvl); } - NamedConst { def_id, substs, user_ty } => { + NamedConst { def_id, args, user_ty } => { print_indented!(self, "NamedConst {", depth_lvl); print_indented!(self, format!("def_id: {:?}", def_id), depth_lvl + 1); print_indented!(self, format!("user_ty: {:?}", user_ty), depth_lvl + 1); - print_indented!(self, format!("substs: {:?}", substs), depth_lvl + 1); + print_indented!(self, format!("args: {:?}", args), depth_lvl + 1); print_indented!(self, "}", depth_lvl); } ConstParam { param, def_id } => { @@ -560,7 +560,7 @@ impl<'a, 'tcx> ThirPrinter<'a, 'tcx> { format!("variant_index: {:?}", adt_expr.variant_index), depth_lvl + 1 ); - print_indented!(self, format!("substs: {:?}", adt_expr.substs), depth_lvl + 1); + print_indented!(self, format!("args: {:?}", adt_expr.args), depth_lvl + 1); print_indented!(self, format!("user_ty: {:?}", adt_expr.user_ty), depth_lvl + 1); for (i, field_expr) in adt_expr.fields.iter().enumerate() { @@ -662,11 +662,11 @@ impl<'a, 'tcx> ThirPrinter<'a, 'tcx> { print_indented!(self, "}", depth_lvl + 1); } - PatKind::Variant { adt_def, substs, variant_index, subpatterns } => { + PatKind::Variant { adt_def, args, variant_index, subpatterns } => { print_indented!(self, "Variant {", depth_lvl + 1); print_indented!(self, "adt_def: ", depth_lvl + 2); self.print_adt_def(*adt_def, depth_lvl + 3); - print_indented!(self, format!("substs: {:?}", substs), depth_lvl + 2); + print_indented!(self, format!("args: {:?}", args), depth_lvl + 2); print_indented!(self, format!("variant_index: {:?}", variant_index), depth_lvl + 2); if subpatterns.len() > 0 { @@ -784,11 +784,11 @@ impl<'a, 'tcx> ThirPrinter<'a, 'tcx> { } fn print_closure_expr(&mut self, expr: &ClosureExpr<'tcx>, depth_lvl: usize) { - let ClosureExpr { closure_id, substs, upvars, movability, fake_reads } = expr; + let ClosureExpr { closure_id, args, upvars, movability, fake_reads } = expr; print_indented!(self, "ClosureExpr {", depth_lvl); print_indented!(self, format!("closure_id: {:?}", closure_id), depth_lvl + 1); - print_indented!(self, format!("substs: {:?}", substs), depth_lvl + 1); + print_indented!(self, format!("args: {:?}", args), depth_lvl + 1); if upvars.len() > 0 { print_indented!(self, "upvars: [", depth_lvl + 1); diff --git a/compiler/rustc_mir_build/src/thir/util.rs b/compiler/rustc_mir_build/src/thir/util.rs index c58ed1ac0b8..9106b4d33fc 100644 --- a/compiler/rustc_mir_build/src/thir/util.rs +++ b/compiler/rustc_mir_build/src/thir/util.rs @@ -9,7 +9,7 @@ pub(crate) trait UserAnnotatedTyHelpers<'tcx> { /// Looks up the type associated with this hir-id and applies the /// user-given substitutions; the hir-id must map to a suitable /// type. - fn user_substs_applied_to_ty_of_hir_id( + fn user_args_applied_to_ty_of_hir_id( &self, hir_id: hir::HirId, ) -> Option<CanonicalUserType<'tcx>> { diff --git a/compiler/rustc_mir_dataflow/src/elaborate_drops.rs b/compiler/rustc_mir_dataflow/src/elaborate_drops.rs index 0540a5e943b..1d7d905c937 100644 --- a/compiler/rustc_mir_dataflow/src/elaborate_drops.rs +++ b/compiler/rustc_mir_dataflow/src/elaborate_drops.rs @@ -4,8 +4,8 @@ use rustc_index::Idx; use rustc_middle::mir::patch::MirPatch; use rustc_middle::mir::*; use rustc_middle::traits::Reveal; -use rustc_middle::ty::subst::SubstsRef; use rustc_middle::ty::util::IntTypeExt; +use rustc_middle::ty::GenericArgsRef; use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_target::abi::{FieldIdx, VariantIdx, FIRST_VARIANT}; use std::{fmt, iter}; @@ -263,7 +263,7 @@ where base_place: Place<'tcx>, variant_path: D::Path, variant: &'tcx ty::VariantDef, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, ) -> Vec<(Place<'tcx>, Option<D::Path>)> { variant .fields @@ -276,7 +276,7 @@ where assert_eq!(self.elaborator.param_env().reveal(), Reveal::All); let field_ty = - tcx.normalize_erasing_regions(self.elaborator.param_env(), f.ty(tcx, substs)); + tcx.normalize_erasing_regions(self.elaborator.param_env(), f.ty(tcx, args)); (tcx.mk_place_field(base_place, field, field_ty), subpath) }) @@ -414,16 +414,16 @@ where fn open_drop_for_box_contents( &mut self, adt: ty::AdtDef<'tcx>, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, succ: BasicBlock, unwind: Unwind, ) -> BasicBlock { // drop glue is sent straight to codegen // box cannot be directly dereferenced - let unique_ty = adt.non_enum_variant().fields[FieldIdx::new(0)].ty(self.tcx(), substs); + let unique_ty = adt.non_enum_variant().fields[FieldIdx::new(0)].ty(self.tcx(), args); let unique_variant = unique_ty.ty_adt_def().unwrap().non_enum_variant(); - let nonnull_ty = unique_variant.fields[FieldIdx::from_u32(0)].ty(self.tcx(), substs); - let ptr_ty = Ty::new_imm_ptr(self.tcx(), substs[0].expect_ty()); + let nonnull_ty = unique_variant.fields[FieldIdx::from_u32(0)].ty(self.tcx(), args); + let ptr_ty = Ty::new_imm_ptr(self.tcx(), args[0].expect_ty()); let unique_place = self.tcx().mk_place_field(self.place, FieldIdx::new(0), unique_ty); let nonnull_place = self.tcx().mk_place_field(unique_place, FieldIdx::new(0), nonnull_ty); @@ -436,7 +436,11 @@ where } #[instrument(level = "debug", ret)] - fn open_drop_for_adt(&mut self, adt: ty::AdtDef<'tcx>, substs: SubstsRef<'tcx>) -> BasicBlock { + fn open_drop_for_adt( + &mut self, + adt: ty::AdtDef<'tcx>, + args: GenericArgsRef<'tcx>, + ) -> BasicBlock { if adt.variants().is_empty() { return self.elaborator.patch().new_block(BasicBlockData { statements: vec![], @@ -453,7 +457,7 @@ where let contents_drop = if skip_contents { (self.succ, self.unwind) } else { - self.open_drop_for_adt_contents(adt, substs) + self.open_drop_for_adt_contents(adt, args) }; if adt.is_box() { @@ -463,7 +467,7 @@ where .1 .map(|unwind| self.destructor_call_block((unwind, Unwind::InCleanup))); - self.open_drop_for_box_contents(adt, substs, succ, unwind) + self.open_drop_for_box_contents(adt, args, succ, unwind) } else if adt.has_dtor(self.tcx()) { self.destructor_call_block(contents_drop) } else { @@ -474,7 +478,7 @@ where fn open_drop_for_adt_contents( &mut self, adt: ty::AdtDef<'tcx>, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, ) -> (BasicBlock, Unwind) { let (succ, unwind) = self.drop_ladder_bottom(); if !adt.is_enum() { @@ -482,18 +486,18 @@ where self.place, self.path, &adt.variant(FIRST_VARIANT), - substs, + args, ); self.drop_ladder(fields, succ, unwind) } else { - self.open_drop_for_multivariant(adt, substs, succ, unwind) + self.open_drop_for_multivariant(adt, args, succ, unwind) } } fn open_drop_for_multivariant( &mut self, adt: ty::AdtDef<'tcx>, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, succ: BasicBlock, unwind: Unwind, ) -> (BasicBlock, Unwind) { @@ -515,7 +519,7 @@ where self.place, ProjectionElem::Downcast(Some(variant.name), variant_index), ); - let fields = self.move_paths_for_fields(base_place, variant_path, &variant, substs); + let fields = self.move_paths_for_fields(base_place, variant_path, &variant, args); values.push(discr.val); if let Unwind::To(unwind) = unwind { // We can't use the half-ladder from the original @@ -550,7 +554,7 @@ where let have_field_with_drop_glue = variant .fields .iter() - .any(|field| field.ty(tcx, substs).needs_drop(tcx, param_env)); + .any(|field| field.ty(tcx, args).needs_drop(tcx, param_env)); if have_field_with_drop_glue { have_otherwise_with_drop_glue = true; } @@ -856,8 +860,8 @@ where fn open_drop(&mut self) -> BasicBlock { let ty = self.place_ty(self.place); match ty.kind() { - ty::Closure(_, substs) => { - let tys: Vec<_> = substs.as_closure().upvar_tys().collect(); + ty::Closure(_, args) => { + let tys: Vec<_> = args.as_closure().upvar_tys().collect(); self.open_drop_for_tuple(&tys) } // Note that `elaborate_drops` only drops the upvars of a generator, @@ -866,12 +870,12 @@ where // This should only happen for the self argument on the resume function. // It effectively only contains upvars until the generator transformation runs. // See librustc_body/transform/generator.rs for more details. - ty::Generator(_, substs, _) => { - let tys: Vec<_> = substs.as_generator().upvar_tys().collect(); + ty::Generator(_, args, _) => { + let tys: Vec<_> = args.as_generator().upvar_tys().collect(); self.open_drop_for_tuple(&tys) } ty::Tuple(fields) => self.open_drop_for_tuple(fields), - ty::Adt(def, substs) => self.open_drop_for_adt(*def, substs), + ty::Adt(def, args) => self.open_drop_for_adt(*def, args), ty::Dynamic(..) => self.complete_drop(self.succ, self.unwind), ty::Array(ety, size) => { let size = size.try_eval_target_usize(self.tcx(), self.elaborator.param_env()); diff --git a/compiler/rustc_mir_dataflow/src/impls/mod.rs b/compiler/rustc_mir_dataflow/src/impls/mod.rs index cb74bea724a..633b99a332b 100644 --- a/compiler/rustc_mir_dataflow/src/impls/mod.rs +++ b/compiler/rustc_mir_dataflow/src/impls/mod.rs @@ -321,7 +321,9 @@ impl<'tcx> GenKillAnalysis<'tcx> for MaybeInitializedPlaces<'_, 'tcx> { // Mark all places as "maybe init" if they are mutably borrowed. See #90752. for_each_mut_borrow(statement, location, |place| { - let LookupResult::Exact(mpi) = self.move_data().rev_lookup.find(place.as_ref()) else { return }; + let LookupResult::Exact(mpi) = self.move_data().rev_lookup.find(place.as_ref()) else { + return; + }; on_all_children_bits(self.tcx, self.body, self.move_data(), mpi, |child| { trans.gen(child); }) @@ -343,7 +345,9 @@ impl<'tcx> GenKillAnalysis<'tcx> for MaybeInitializedPlaces<'_, 'tcx> { } for_each_mut_borrow(terminator, location, |place| { - let LookupResult::Exact(mpi) = self.move_data().rev_lookup.find(place.as_ref()) else { return }; + let LookupResult::Exact(mpi) = self.move_data().rev_lookup.find(place.as_ref()) else { + return; + }; on_all_children_bits(self.tcx, self.body, self.move_data(), mpi, |child| { trans.gen(child); }) diff --git a/compiler/rustc_mir_dataflow/src/rustc_peek.rs b/compiler/rustc_mir_dataflow/src/rustc_peek.rs index 156231c3ae1..775c522b476 100644 --- a/compiler/rustc_mir_dataflow/src/rustc_peek.rs +++ b/compiler/rustc_mir_dataflow/src/rustc_peek.rs @@ -190,14 +190,14 @@ impl PeekCall { if let mir::TerminatorKind::Call { func: Operand::Constant(func), args, .. } = &terminator.kind { - if let ty::FnDef(def_id, substs) = *func.literal.ty().kind() { + if let ty::FnDef(def_id, fn_args) = *func.literal.ty().kind() { let name = tcx.item_name(def_id); if !tcx.is_intrinsic(def_id) || name != sym::rustc_peek { return None; } - assert_eq!(args.len(), 1); - let kind = PeekCallKind::from_arg_ty(substs.type_at(0)); + assert_eq!(fn_args.len(), 1); + let kind = PeekCallKind::from_arg_ty(fn_args.type_at(0)); let arg = match &args[0] { Operand::Copy(place) | Operand::Move(place) => { if let Some(local) = place.as_local() { diff --git a/compiler/rustc_mir_dataflow/src/value_analysis.rs b/compiler/rustc_mir_dataflow/src/value_analysis.rs index 5693e5a4a71..fd6b1dc5c07 100644 --- a/compiler/rustc_mir_dataflow/src/value_analysis.rs +++ b/compiler/rustc_mir_dataflow/src/value_analysis.rs @@ -999,14 +999,14 @@ pub fn iter_fields<'tcx>( f(None, field.into(), ty); } } - ty::Adt(def, substs) => { + ty::Adt(def, args) => { if def.is_union() { return; } for (v_index, v_def) in def.variants().iter_enumerated() { let variant = if def.is_struct() { None } else { Some(v_index) }; for (f_index, f_def) in v_def.fields.iter().enumerate() { - let field_ty = f_def.ty(tcx, substs); + let field_ty = f_def.ty(tcx, args); let field_ty = tcx .try_normalize_erasing_regions(param_env, field_ty) .unwrap_or_else(|_| tcx.erase_regions(field_ty)); @@ -1014,8 +1014,8 @@ pub fn iter_fields<'tcx>( } } } - ty::Closure(_, substs) => { - iter_fields(substs.as_closure().tupled_upvars_ty(), tcx, param_env, f); + ty::Closure(_, args) => { + iter_fields(args.as_closure().tupled_upvars_ty(), tcx, param_env, f); } _ => (), } diff --git a/compiler/rustc_mir_transform/src/check_unsafety.rs b/compiler/rustc_mir_transform/src/check_unsafety.rs index 70812761e88..58e9786ec1a 100644 --- a/compiler/rustc_mir_transform/src/check_unsafety.rs +++ b/compiler/rustc_mir_transform/src/check_unsafety.rs @@ -1,4 +1,4 @@ -use rustc_data_structures::unord::{UnordItems, UnordSet}; +use rustc_data_structures::unord::{ExtendUnord, UnordItems, UnordSet}; use rustc_hir as hir; use rustc_hir::def::DefKind; use rustc_hir::def_id::{DefId, LocalDefId}; diff --git a/compiler/rustc_mir_transform/src/const_prop.rs b/compiler/rustc_mir_transform/src/const_prop.rs index 2f2c7357b00..6437a227d47 100644 --- a/compiler/rustc_mir_transform/src/const_prop.rs +++ b/compiler/rustc_mir_transform/src/const_prop.rs @@ -14,7 +14,7 @@ use rustc_middle::mir::visit::{ }; use rustc_middle::mir::*; use rustc_middle::ty::layout::{LayoutError, LayoutOf, LayoutOfHelpers, TyAndLayout}; -use rustc_middle::ty::InternalSubsts; +use rustc_middle::ty::GenericArgs; use rustc_middle::ty::{self, ConstKind, Instance, ParamEnv, Ty, TyCtxt, TypeVisitableExt}; use rustc_span::{def_id::DefId, Span, DUMMY_SP}; use rustc_target::abi::{self, Align, HasDataLayout, Size, TargetDataLayout}; @@ -22,8 +22,8 @@ use rustc_target::spec::abi::Abi as CallAbi; use crate::MirPass; use rustc_const_eval::interpret::{ - self, compile_time_machine, AllocId, ConstAllocation, ConstValue, Frame, ImmTy, Immediate, - InterpCx, InterpResult, LocalValue, MemoryKind, OpTy, PlaceTy, Pointer, Scalar, + self, compile_time_machine, AllocId, ConstAllocation, ConstValue, FnArg, Frame, ImmTy, + Immediate, InterpCx, InterpResult, LocalValue, MemoryKind, OpTy, PlaceTy, Pointer, Scalar, StackPopCleanup, }; @@ -87,7 +87,7 @@ impl<'tcx> MirPass<'tcx> for ConstProp { return; } - let is_generator = tcx.type_of(def_id.to_def_id()).subst_identity().is_generator(); + let is_generator = tcx.type_of(def_id.to_def_id()).instantiate_identity().is_generator(); // FIXME(welseywiser) const prop doesn't work on generators because of query cycles // computing their layout. if is_generator { @@ -185,7 +185,7 @@ impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for ConstPropMachine<'mir, 'tcx> _ecx: &mut InterpCx<'mir, 'tcx, Self>, _instance: ty::Instance<'tcx>, _abi: CallAbi, - _args: &[OpTy<'tcx>], + _args: &[FnArg<'tcx>], _destination: &PlaceTy<'tcx>, _target: Option<BasicBlock>, _unwind: UnwindAction, @@ -338,7 +338,7 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> { tcx: TyCtxt<'tcx>, ) -> ConstPropagator<'mir, 'tcx> { let def_id = body.source.def_id(); - let substs = &InternalSubsts::identity_for_item(tcx, def_id); + let args = &GenericArgs::identity_for_item(tcx, def_id); let param_env = tcx.param_env_reveal_all_normalized(def_id); let can_const_prop = CanConstProp::check(tcx, param_env, body); @@ -350,7 +350,7 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> { ); let ret_layout = ecx - .layout_of(body.bound_return_ty().subst(tcx, substs)) + .layout_of(body.bound_return_ty().instantiate(tcx, args)) .ok() // Don't bother allocating memory for large values. // I don't know how return types can seem to be unsized but this happens in the @@ -366,7 +366,7 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> { .into(); ecx.push_stack_frame( - Instance::new(def_id, substs), + Instance::new(def_id, args), dummy_body, &ret, StackPopCleanup::Root { cleanup: false }, diff --git a/compiler/rustc_mir_transform/src/const_prop_lint.rs b/compiler/rustc_mir_transform/src/const_prop_lint.rs index 759650fe4db..01b945afda6 100644 --- a/compiler/rustc_mir_transform/src/const_prop_lint.rs +++ b/compiler/rustc_mir_transform/src/const_prop_lint.rs @@ -16,7 +16,7 @@ use rustc_index::bit_set::BitSet; use rustc_middle::mir::visit::Visitor; use rustc_middle::mir::*; use rustc_middle::ty::layout::{LayoutError, LayoutOf, LayoutOfHelpers, TyAndLayout}; -use rustc_middle::ty::InternalSubsts; +use rustc_middle::ty::GenericArgs; use rustc_middle::ty::{ self, ConstInt, Instance, ParamEnv, ScalarInt, Ty, TyCtxt, TypeVisitableExt, }; @@ -55,7 +55,7 @@ impl<'tcx> MirLint<'tcx> for ConstProp { return; } - let is_generator = tcx.type_of(def_id.to_def_id()).subst_identity().is_generator(); + let is_generator = tcx.type_of(def_id.to_def_id()).instantiate_identity().is_generator(); // FIXME(welseywiser) const prop doesn't work on generators because of query cycles // computing their layout. if is_generator { @@ -171,7 +171,7 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> { tcx: TyCtxt<'tcx>, ) -> ConstPropagator<'mir, 'tcx> { let def_id = body.source.def_id(); - let substs = &InternalSubsts::identity_for_item(tcx, def_id); + let args = &GenericArgs::identity_for_item(tcx, def_id); let param_env = tcx.param_env_reveal_all_normalized(def_id); let can_const_prop = CanConstProp::check(tcx, param_env, body); @@ -183,7 +183,7 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> { ); let ret_layout = ecx - .layout_of(body.bound_return_ty().subst(tcx, substs)) + .layout_of(body.bound_return_ty().instantiate(tcx, args)) .ok() // Don't bother allocating memory for large values. // I don't know how return types can seem to be unsized but this happens in the @@ -199,7 +199,7 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> { .into(); ecx.push_stack_frame( - Instance::new(def_id, substs), + Instance::new(def_id, args), dummy_body, &ret, StackPopCleanup::Root { cleanup: false }, diff --git a/compiler/rustc_mir_transform/src/copy_prop.rs b/compiler/rustc_mir_transform/src/copy_prop.rs index 3df459dfa79..47d9f52bfb5 100644 --- a/compiler/rustc_mir_transform/src/copy_prop.rs +++ b/compiler/rustc_mir_transform/src/copy_prop.rs @@ -76,9 +76,11 @@ fn fully_moved_locals(ssa: &SsaLocals, body: &Body<'_>) -> BitSet<Local> { let mut fully_moved = BitSet::new_filled(body.local_decls.len()); for (_, rvalue, _) in ssa.assignments(body) { - let (Rvalue::Use(Operand::Copy(place) | Operand::Move(place)) | Rvalue::CopyForDeref(place)) - = rvalue - else { continue }; + let (Rvalue::Use(Operand::Copy(place) | Operand::Move(place)) + | Rvalue::CopyForDeref(place)) = rvalue + else { + continue; + }; let Some(rhs) = place.as_local() else { continue }; if !ssa.is_ssa(rhs) { diff --git a/compiler/rustc_mir_transform/src/dataflow_const_prop.rs b/compiler/rustc_mir_transform/src/dataflow_const_prop.rs index 78fb196358f..7d7588fcaec 100644 --- a/compiler/rustc_mir_transform/src/dataflow_const_prop.rs +++ b/compiler/rustc_mir_transform/src/dataflow_const_prop.rs @@ -281,7 +281,7 @@ impl<'tcx> ValueAnalysis<'tcx> for ConstAnalysis<'_, 'tcx> { let FlatSet::Elem(choice) = discr_value else { // Do nothing if we don't know which branch will be taken. - return + return; }; if target.value.map(|n| n == choice).unwrap_or(!handled) { @@ -532,7 +532,7 @@ impl<'tcx, 'map, 'a> Visitor<'tcx> for OperandCollector<'tcx, 'map, 'a> { struct DummyMachine; -impl<'mir, 'tcx> rustc_const_eval::interpret::Machine<'mir, 'tcx> for DummyMachine { +impl<'mir, 'tcx: 'mir> rustc_const_eval::interpret::Machine<'mir, 'tcx> for DummyMachine { rustc_const_eval::interpret::compile_time_machine!(<'mir, 'tcx>); type MemoryKind = !; const PANIC_ON_ALLOC_FAIL: bool = true; @@ -557,7 +557,7 @@ impl<'mir, 'tcx> rustc_const_eval::interpret::Machine<'mir, 'tcx> for DummyMachi _ecx: &mut InterpCx<'mir, 'tcx, Self>, _instance: ty::Instance<'tcx>, _abi: rustc_target::spec::abi::Abi, - _args: &[rustc_const_eval::interpret::OpTy<'tcx, Self::Provenance>], + _args: &[rustc_const_eval::interpret::FnArg<'tcx, Self::Provenance>], _destination: &rustc_const_eval::interpret::PlaceTy<'tcx, Self::Provenance>, _target: Option<BasicBlock>, _unwind: UnwindAction, diff --git a/compiler/rustc_mir_transform/src/deduce_param_attrs.rs b/compiler/rustc_mir_transform/src/deduce_param_attrs.rs index a133c9d4782..60ca3dfb2da 100644 --- a/compiler/rustc_mir_transform/src/deduce_param_attrs.rs +++ b/compiler/rustc_mir_transform/src/deduce_param_attrs.rs @@ -166,7 +166,7 @@ pub fn deduced_param_attrs<'tcx>( // Codegen won't use this information for anything if all the function parameters are passed // directly. Detect that and bail, for compilation speed. - let fn_ty = tcx.type_of(def_id).subst_identity(); + let fn_ty = tcx.type_of(def_id).instantiate_identity(); if matches!(fn_ty.kind(), ty::FnDef(..)) { if fn_ty .fn_sig(tcx) diff --git a/compiler/rustc_mir_transform/src/dest_prop.rs b/compiler/rustc_mir_transform/src/dest_prop.rs index a31551cf619..b73b72c3192 100644 --- a/compiler/rustc_mir_transform/src/dest_prop.rs +++ b/compiler/rustc_mir_transform/src/dest_prop.rs @@ -218,9 +218,9 @@ impl<'tcx> MirPass<'tcx> for DestinationPropagation { if merged_locals.contains(*src) { continue; } - let Some(dest) = - candidates.iter().find(|dest| !merged_locals.contains(**dest)) else { - continue; + let Some(dest) = candidates.iter().find(|dest| !merged_locals.contains(**dest)) + else { + continue; }; if !tcx.consider_optimizing(|| { format!("{} round {}", tcx.def_path_str(def_id), round_count) @@ -601,9 +601,7 @@ impl WriteInfo { rhs: &Operand<'tcx>, body: &Body<'tcx>, ) { - let Some(rhs) = rhs.place() else { - return - }; + let Some(rhs) = rhs.place() else { return }; if let Some(pair) = places_to_candidate_pair(lhs, rhs, body) { self.skip_pair = Some(pair); } diff --git a/compiler/rustc_mir_transform/src/early_otherwise_branch.rs b/compiler/rustc_mir_transform/src/early_otherwise_branch.rs index 8a7b027ddda..319fb4eaf3e 100644 --- a/compiler/rustc_mir_transform/src/early_otherwise_branch.rs +++ b/compiler/rustc_mir_transform/src/early_otherwise_branch.rs @@ -107,9 +107,7 @@ impl<'tcx> MirPass<'tcx> for EarlyOtherwiseBranch { for i in 0..body.basic_blocks.len() { let bbs = &*body.basic_blocks; let parent = BasicBlock::from_usize(i); - let Some(opt_data) = evaluate_candidate(tcx, body, parent) else { - continue - }; + let Some(opt_data) = evaluate_candidate(tcx, body, parent) else { continue }; if !tcx.consider_optimizing(|| format!("EarlyOtherwiseBranch {:?}", &opt_data)) { break; @@ -119,10 +117,9 @@ impl<'tcx> MirPass<'tcx> for EarlyOtherwiseBranch { should_cleanup = true; - let TerminatorKind::SwitchInt { - discr: parent_op, - targets: parent_targets - } = &bbs[parent].terminator().kind else { + let TerminatorKind::SwitchInt { discr: parent_op, targets: parent_targets } = + &bbs[parent].terminator().kind + else { unreachable!() }; // Always correct since we can only switch on `Copy` types @@ -168,7 +165,8 @@ impl<'tcx> MirPass<'tcx> for EarlyOtherwiseBranch { ); let eq_new_targets = parent_targets.iter().map(|(value, child)| { - let TerminatorKind::SwitchInt{ targets, .. } = &bbs[child].terminator().kind else { + let TerminatorKind::SwitchInt { targets, .. } = &bbs[child].terminator().kind + else { unreachable!() }; (value, targets.target_for_value(value)) @@ -311,11 +309,9 @@ fn evaluate_candidate<'tcx>( parent: BasicBlock, ) -> Option<OptimizationData<'tcx>> { let bbs = &body.basic_blocks; - let TerminatorKind::SwitchInt { - targets, - discr: parent_discr, - } = &bbs[parent].terminator().kind else { - return None + let TerminatorKind::SwitchInt { targets, discr: parent_discr } = &bbs[parent].terminator().kind + else { + return None; }; let parent_ty = parent_discr.ty(body.local_decls(), tcx); let parent_dest = { @@ -332,18 +328,16 @@ fn evaluate_candidate<'tcx>( }; let (_, child) = targets.iter().next()?; let child_terminator = &bbs[child].terminator(); - let TerminatorKind::SwitchInt { - targets: child_targets, - discr: child_discr, - } = &child_terminator.kind else { - return None + let TerminatorKind::SwitchInt { targets: child_targets, discr: child_discr } = + &child_terminator.kind + else { + return None; }; let child_ty = child_discr.ty(body.local_decls(), tcx); if child_ty != parent_ty { return None; } - let Some(StatementKind::Assign(boxed)) - = &bbs[child].statements.first().map(|x| &x.kind) else { + let Some(StatementKind::Assign(boxed)) = &bbs[child].statements.first().map(|x| &x.kind) else { return None; }; let (_, Rvalue::Discriminant(child_place)) = &**boxed else { @@ -383,12 +377,8 @@ fn verify_candidate_branch<'tcx>( return false; } // ...assign the discriminant of `place` in that statement - let StatementKind::Assign(boxed) = &branch.statements[0].kind else { - return false - }; - let (discr_place, Rvalue::Discriminant(from_place)) = &**boxed else { - return false - }; + let StatementKind::Assign(boxed) = &branch.statements[0].kind else { return false }; + let (discr_place, Rvalue::Discriminant(from_place)) = &**boxed else { return false }; if *from_place != place { return false; } @@ -397,8 +387,9 @@ fn verify_candidate_branch<'tcx>( return false; } // ...terminate on a `SwitchInt` that invalidates that local - let TerminatorKind::SwitchInt{ discr: switch_op, targets, .. } = &branch.terminator().kind else { - return false + let TerminatorKind::SwitchInt { discr: switch_op, targets, .. } = &branch.terminator().kind + else { + return false; }; if *switch_op != Operand::Move(*discr_place) { return false; diff --git a/compiler/rustc_mir_transform/src/elaborate_box_derefs.rs b/compiler/rustc_mir_transform/src/elaborate_box_derefs.rs index cc0d7d51b60..e51f771e00d 100644 --- a/compiler/rustc_mir_transform/src/elaborate_box_derefs.rs +++ b/compiler/rustc_mir_transform/src/elaborate_box_derefs.rs @@ -18,9 +18,9 @@ pub fn build_ptr_tys<'tcx>( unique_did: DefId, nonnull_did: DefId, ) -> (Ty<'tcx>, Ty<'tcx>, Ty<'tcx>) { - let substs = tcx.mk_substs(&[pointee.into()]); - let unique_ty = tcx.type_of(unique_did).subst(tcx, substs); - let nonnull_ty = tcx.type_of(nonnull_did).subst(tcx, substs); + let args = tcx.mk_args(&[pointee.into()]); + let unique_ty = tcx.type_of(unique_did).instantiate(tcx, args); + let nonnull_ty = tcx.type_of(nonnull_did).instantiate(tcx, args); let ptr_ty = Ty::new_imm_ptr(tcx, pointee); (unique_ty, nonnull_ty, ptr_ty) @@ -95,7 +95,8 @@ impl<'tcx> MirPass<'tcx> for ElaborateBoxDerefs { let unique_did = tcx.adt_def(def_id).non_enum_variant().fields[FieldIdx::from_u32(0)].did; - let Some(nonnull_def) = tcx.type_of(unique_did).subst_identity().ty_adt_def() else { + let Some(nonnull_def) = tcx.type_of(unique_did).instantiate_identity().ty_adt_def() + else { span_bug!(tcx.def_span(unique_did), "expected Box to contain Unique") }; diff --git a/compiler/rustc_mir_transform/src/function_item_references.rs b/compiler/rustc_mir_transform/src/function_item_references.rs index 0b41e57be3b..fdf6ab33c82 100644 --- a/compiler/rustc_mir_transform/src/function_item_references.rs +++ b/compiler/rustc_mir_transform/src/function_item_references.rs @@ -2,7 +2,7 @@ use itertools::Itertools; use rustc_hir::def_id::DefId; use rustc_middle::mir::visit::Visitor; use rustc_middle::mir::*; -use rustc_middle::ty::{self, EarlyBinder, SubstsRef, Ty, TyCtxt}; +use rustc_middle::ty::{self, EarlyBinder, GenericArgsRef, Ty, TyCtxt}; use rustc_session::lint::builtin::FUNCTION_ITEM_REFERENCES; use rustc_span::{symbol::sym, Span}; use rustc_target::spec::abi::Abi; @@ -40,20 +40,19 @@ impl<'tcx> Visitor<'tcx> for FunctionItemRefChecker<'_, 'tcx> { { let source_info = *self.body.source_info(location); let func_ty = func.ty(self.body, self.tcx); - if let ty::FnDef(def_id, substs_ref) = *func_ty.kind() { + if let ty::FnDef(def_id, args_ref) = *func_ty.kind() { // Handle calls to `transmute` if self.tcx.is_diagnostic_item(sym::transmute, def_id) { let arg_ty = args[0].ty(self.body, self.tcx); for inner_ty in arg_ty.walk().filter_map(|arg| arg.as_type()) { - if let Some((fn_id, fn_substs)) = - FunctionItemRefChecker::is_fn_ref(inner_ty) + if let Some((fn_id, fn_args)) = FunctionItemRefChecker::is_fn_ref(inner_ty) { let span = self.nth_arg_span(&args, 0); - self.emit_lint(fn_id, fn_substs, source_info, span); + self.emit_lint(fn_id, fn_args, source_info, span); } } } else { - self.check_bound_args(def_id, substs_ref, &args, source_info); + self.check_bound_args(def_id, args_ref, &args, source_info); } } } @@ -63,11 +62,11 @@ impl<'tcx> Visitor<'tcx> for FunctionItemRefChecker<'_, 'tcx> { impl<'tcx> FunctionItemRefChecker<'_, 'tcx> { /// Emits a lint for function reference arguments bound by `fmt::Pointer` in calls to the - /// function defined by `def_id` with the substitutions `substs_ref`. + /// function defined by `def_id` with the substitutions `args_ref`. fn check_bound_args( &self, def_id: DefId, - substs_ref: SubstsRef<'tcx>, + args_ref: GenericArgsRef<'tcx>, args: &[Operand<'tcx>], source_info: SourceInfo, ) { @@ -76,15 +75,17 @@ impl<'tcx> FunctionItemRefChecker<'_, 'tcx> { for bound in bounds { if let Some(bound_ty) = self.is_pointer_trait(bound) { // Get the argument types as they appear in the function signature. - let arg_defs = self.tcx.fn_sig(def_id).subst_identity().skip_binder().inputs(); + let arg_defs = + self.tcx.fn_sig(def_id).instantiate_identity().skip_binder().inputs(); for (arg_num, arg_def) in arg_defs.iter().enumerate() { // For all types reachable from the argument type in the fn sig for inner_ty in arg_def.walk().filter_map(|arg| arg.as_type()) { // If the inner type matches the type bound by `Pointer` if inner_ty == bound_ty { // Do a substitution using the parameters from the callsite - let subst_ty = EarlyBinder::bind(inner_ty).subst(self.tcx, substs_ref); - if let Some((fn_id, fn_substs)) = + let subst_ty = + EarlyBinder::bind(inner_ty).instantiate(self.tcx, args_ref); + if let Some((fn_id, fn_args)) = FunctionItemRefChecker::is_fn_ref(subst_ty) { let mut span = self.nth_arg_span(args, arg_num); @@ -94,7 +95,7 @@ impl<'tcx> FunctionItemRefChecker<'_, 'tcx> { let callsite_ctxt = span.source_callsite().ctxt(); span = span.with_ctxt(callsite_ctxt); } - self.emit_lint(fn_id, fn_substs, source_info, span); + self.emit_lint(fn_id, fn_args, source_info, span); } } } @@ -115,8 +116,8 @@ impl<'tcx> FunctionItemRefChecker<'_, 'tcx> { } /// If a type is a reference or raw pointer to the anonymous type of a function definition, - /// returns that function's `DefId` and `SubstsRef`. - fn is_fn_ref(ty: Ty<'tcx>) -> Option<(DefId, SubstsRef<'tcx>)> { + /// returns that function's `DefId` and `GenericArgsRef`. + fn is_fn_ref(ty: Ty<'tcx>) -> Option<(DefId, GenericArgsRef<'tcx>)> { let referent_ty = match ty.kind() { ty::Ref(_, referent_ty, _) => Some(referent_ty), ty::RawPtr(ty_and_mut) => Some(&ty_and_mut.ty), @@ -124,8 +125,8 @@ impl<'tcx> FunctionItemRefChecker<'_, 'tcx> { }; referent_ty .map(|ref_ty| { - if let ty::FnDef(def_id, substs_ref) = *ref_ty.kind() { - Some((def_id, substs_ref)) + if let ty::FnDef(def_id, args_ref) = *ref_ty.kind() { + Some((def_id, args_ref)) } else { None } @@ -145,7 +146,7 @@ impl<'tcx> FunctionItemRefChecker<'_, 'tcx> { fn emit_lint( &self, fn_id: DefId, - fn_substs: SubstsRef<'tcx>, + fn_args: GenericArgsRef<'tcx>, source_info: SourceInfo, span: Span, ) { @@ -155,7 +156,7 @@ impl<'tcx> FunctionItemRefChecker<'_, 'tcx> { .assert_crate_local() .lint_root; // FIXME: use existing printing routines to print the function signature - let fn_sig = self.tcx.fn_sig(fn_id).subst(self.tcx, fn_substs); + let fn_sig = self.tcx.fn_sig(fn_id).instantiate(self.tcx, fn_args); let unsafety = fn_sig.unsafety().prefix_str(); let abi = match fn_sig.abi() { Abi::Rust => String::from(""), @@ -167,8 +168,8 @@ impl<'tcx> FunctionItemRefChecker<'_, 'tcx> { } }; let ident = self.tcx.item_name(fn_id).to_ident_string(); - let ty_params = fn_substs.types().map(|ty| format!("{}", ty)); - let const_params = fn_substs.consts().map(|c| format!("{}", c)); + let ty_params = fn_args.types().map(|ty| format!("{}", ty)); + let const_params = fn_args.consts().map(|c| format!("{}", c)); let params = ty_params.chain(const_params).join(", "); let num_args = fn_sig.inputs().map_bound(|inputs| inputs.len()).skip_binder(); let variadic = if fn_sig.c_variadic() { ", ..." } else { "" }; diff --git a/compiler/rustc_mir_transform/src/generator.rs b/compiler/rustc_mir_transform/src/generator.rs index 264bc61f1b3..eaeaff69cf3 100644 --- a/compiler/rustc_mir_transform/src/generator.rs +++ b/compiler/rustc_mir_transform/src/generator.rs @@ -65,7 +65,7 @@ use rustc_middle::mir::dump_mir; use rustc_middle::mir::visit::{MutVisitor, PlaceContext, Visitor}; use rustc_middle::mir::*; use rustc_middle::ty::{self, AdtDef, Ty, TyCtxt}; -use rustc_middle::ty::{GeneratorSubsts, SubstsRef}; +use rustc_middle::ty::{GeneratorArgs, GenericArgsRef}; use rustc_mir_dataflow::impls::{ MaybeBorrowedLocals, MaybeLiveLocals, MaybeRequiresStorage, MaybeStorageLive, }; @@ -194,11 +194,11 @@ fn replace_base<'tcx>(place: &mut Place<'tcx>, new_base: Place<'tcx>, tcx: TyCtx const SELF_ARG: Local = Local::from_u32(1); /// Generator has not been resumed yet. -const UNRESUMED: usize = GeneratorSubsts::UNRESUMED; +const UNRESUMED: usize = GeneratorArgs::UNRESUMED; /// Generator has returned / is completed. -const RETURNED: usize = GeneratorSubsts::RETURNED; +const RETURNED: usize = GeneratorArgs::RETURNED; /// Generator has panicked and is poisoned. -const POISONED: usize = GeneratorSubsts::POISONED; +const POISONED: usize = GeneratorArgs::POISONED; /// Number of variants to reserve in generator state. Corresponds to /// `UNRESUMED` (beginning of a generator) and `RETURNED`/`POISONED` @@ -223,7 +223,7 @@ struct TransformVisitor<'tcx> { tcx: TyCtxt<'tcx>, is_async_kind: bool, state_adt_ref: AdtDef<'tcx>, - state_substs: SubstsRef<'tcx>, + state_args: GenericArgsRef<'tcx>, // The type of the discriminant in the generator struct discr_ty: Ty<'tcx>, @@ -265,7 +265,7 @@ impl<'tcx> TransformVisitor<'tcx> { (false, true) => 1, // Poll::Pending }); - let kind = AggregateKind::Adt(self.state_adt_ref.did(), idx, self.state_substs, None, None); + let kind = AggregateKind::Adt(self.state_adt_ref.did(), idx, self.state_args, None, None); // `Poll::Pending` if self.is_async_kind && idx == VariantIdx::new(1) { @@ -431,8 +431,8 @@ fn make_generator_state_argument_pinned<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body let pin_did = tcx.require_lang_item(LangItem::Pin, Some(body.span)); let pin_adt_ref = tcx.adt_def(pin_did); - let substs = tcx.mk_substs(&[ref_gen_ty.into()]); - let pin_ref_gen_ty = Ty::new_adt(tcx, pin_adt_ref, substs); + let args = tcx.mk_args(&[ref_gen_ty.into()]); + let pin_ref_gen_ty = Ty::new_adt(tcx, pin_adt_ref, args); // Replace the by ref generator argument body.local_decls.raw[1].ty = pin_ref_gen_ty; @@ -1431,7 +1431,7 @@ pub(crate) fn mir_generator_witnesses<'tcx>( // The first argument is the generator type passed by value let gen_ty = body.local_decls[ty::CAPTURE_STRUCT_LOCAL].ty; - // Get the interior types and substs which typeck computed + // Get the interior types and args which typeck computed let movable = match *gen_ty.kind() { ty::Generator(_, _, movability) => movability == hir::Movability::Movable, ty::Error(_) => return None, @@ -1465,14 +1465,14 @@ impl<'tcx> MirPass<'tcx> for StateTransform { // The first argument is the generator type passed by value let gen_ty = body.local_decls.raw[1].ty; - // Get the discriminant type and substs which typeck computed + // Get the discriminant type and args which typeck computed let (discr_ty, upvars, interior, movable) = match *gen_ty.kind() { - ty::Generator(_, substs, movability) => { - let substs = substs.as_generator(); + ty::Generator(_, args, movability) => { + let args = args.as_generator(); ( - substs.discr_ty(tcx), - substs.upvar_tys().collect::<Vec<_>>(), - substs.witness(), + args.discr_ty(tcx), + args.upvar_tys().collect::<Vec<_>>(), + args.witness(), movability == hir::Movability::Movable, ) } @@ -1483,20 +1483,20 @@ impl<'tcx> MirPass<'tcx> for StateTransform { }; let is_async_kind = matches!(body.generator_kind(), Some(GeneratorKind::Async(_))); - let (state_adt_ref, state_substs) = if is_async_kind { + let (state_adt_ref, state_args) = if is_async_kind { // Compute Poll<return_ty> let poll_did = tcx.require_lang_item(LangItem::Poll, None); let poll_adt_ref = tcx.adt_def(poll_did); - let poll_substs = tcx.mk_substs(&[body.return_ty().into()]); - (poll_adt_ref, poll_substs) + let poll_args = tcx.mk_args(&[body.return_ty().into()]); + (poll_adt_ref, poll_args) } else { // Compute GeneratorState<yield_ty, return_ty> let state_did = tcx.require_lang_item(LangItem::GeneratorState, None); let state_adt_ref = tcx.adt_def(state_did); - let state_substs = tcx.mk_substs(&[yield_ty.into(), body.return_ty().into()]); - (state_adt_ref, state_substs) + let state_args = tcx.mk_args(&[yield_ty.into(), body.return_ty().into()]); + (state_adt_ref, state_args) }; - let ret_ty = Ty::new_adt(tcx, state_adt_ref, state_substs); + let ret_ty = Ty::new_adt(tcx, state_adt_ref, state_args); // We rename RETURN_PLACE which has type mir.return_ty to new_ret_local // RETURN_PLACE then is a fresh unused local with type ret_ty. @@ -1570,7 +1570,7 @@ impl<'tcx> MirPass<'tcx> for StateTransform { tcx, is_async_kind, state_adt_ref, - state_substs, + state_args, remap, storage_liveness, always_live_locals, @@ -1763,7 +1763,9 @@ fn check_suspend_tys<'tcx>(tcx: TyCtxt<'tcx>, layout: &GeneratorLayout<'tcx>, bo debug!(?decl); if !decl.ignore_for_traits && linted_tys.insert(decl.ty) { - let Some(hir_id) = decl.source_info.scope.lint_root(&body.source_scopes) else { continue }; + let Some(hir_id) = decl.source_info.scope.lint_root(&body.source_scopes) else { + continue; + }; check_must_not_suspend_ty( tcx, diff --git a/compiler/rustc_mir_transform/src/inline.rs b/compiler/rustc_mir_transform/src/inline.rs index 240beabfc1a..7860cf76247 100644 --- a/compiler/rustc_mir_transform/src/inline.rs +++ b/compiler/rustc_mir_transform/src/inline.rs @@ -105,7 +105,7 @@ struct Inliner<'tcx> { /// Caller codegen attributes. codegen_fn_attrs: &'tcx CodegenFnAttrs, /// Stack of inlined instances. - /// We only check the `DefId` and not the substs because we want to + /// We only check the `DefId` and not the args because we want to /// avoid inlining cases of polymorphic recursion. /// The number of `DefId`s is finite, so checking history is enough /// to ensure that we do not loop endlessly while inlining. @@ -329,11 +329,11 @@ impl<'tcx> Inliner<'tcx> { let terminator = bb_data.terminator(); if let TerminatorKind::Call { ref func, target, fn_span, .. } = terminator.kind { let func_ty = func.ty(caller_body, self.tcx); - if let ty::FnDef(def_id, substs) = *func_ty.kind() { - // To resolve an instance its substs have to be fully normalized. - let substs = self.tcx.try_normalize_erasing_regions(self.param_env, substs).ok()?; + if let ty::FnDef(def_id, args) = *func_ty.kind() { + // To resolve an instance its args have to be fully normalized. + let args = self.tcx.try_normalize_erasing_regions(self.param_env, args).ok()?; let callee = - Instance::resolve(self.tcx, self.param_env, def_id, substs).ok().flatten()?; + Instance::resolve(self.tcx, self.param_env, def_id, args).ok().flatten()?; if let InstanceDef::Virtual(..) | InstanceDef::Intrinsic(_) = callee.def { return None; @@ -343,7 +343,7 @@ impl<'tcx> Inliner<'tcx> { return None; } - let fn_sig = self.tcx.fn_sig(def_id).subst(self.tcx, substs); + let fn_sig = self.tcx.fn_sig(def_id).instantiate(self.tcx, args); let source_info = SourceInfo { span: fn_span, ..terminator.source_info }; return Some(CallSite { callee, fn_sig, block: bb, target, source_info }); @@ -368,7 +368,7 @@ impl<'tcx> Inliner<'tcx> { // inlining. This is to ensure that the final crate doesn't have MIR that // reference unexported symbols if callsite.callee.def_id().is_local() { - let is_generic = callsite.callee.substs.non_erasable_generics().next().is_some(); + let is_generic = callsite.callee.args.non_erasable_generics().next().is_some(); if !is_generic && !callee_attrs.requests_inline() { return Err("not exported"); } @@ -855,8 +855,8 @@ impl<'tcx> Visitor<'tcx> for CostChecker<'_, 'tcx> { }; let kind = match parent_ty.ty.kind() { - &ty::Alias(ty::Opaque, ty::AliasTy { def_id, substs, .. }) => { - self.tcx.type_of(def_id).subst(self.tcx, substs).kind() + &ty::Alias(ty::Opaque, ty::AliasTy { def_id, args, .. }) => { + self.tcx.type_of(def_id).instantiate(self.tcx, args).kind() } kind => kind, }; @@ -869,23 +869,23 @@ impl<'tcx> Visitor<'tcx> for CostChecker<'_, 'tcx> { }; check_equal(self, *f_ty); } - ty::Adt(adt_def, substs) => { + ty::Adt(adt_def, args) => { let var = parent_ty.variant_index.unwrap_or(FIRST_VARIANT); let Some(field) = adt_def.variant(var).fields.get(f) else { self.validation = Err("malformed MIR"); return; }; - check_equal(self, field.ty(self.tcx, substs)); + check_equal(self, field.ty(self.tcx, args)); } - ty::Closure(_, substs) => { - let substs = substs.as_closure(); - let Some(f_ty) = substs.upvar_tys().nth(f.as_usize()) else { + ty::Closure(_, args) => { + let args = args.as_closure(); + let Some(f_ty) = args.upvar_tys().nth(f.as_usize()) else { self.validation = Err("malformed MIR"); return; }; check_equal(self, f_ty); } - &ty::Generator(def_id, substs, _) => { + &ty::Generator(def_id, args, _) => { let f_ty = if let Some(var) = parent_ty.variant_index { let gen_body = if def_id == self.callee_body.source.def_id() { self.callee_body @@ -910,7 +910,7 @@ impl<'tcx> Visitor<'tcx> for CostChecker<'_, 'tcx> { f_ty.ty } else { - let Some(f_ty) = substs.as_generator().prefix_tys().nth(f.index()) else { + let Some(f_ty) = args.as_generator().prefix_tys().nth(f.index()) else { self.validation = Err("malformed MIR"); return; }; @@ -1130,10 +1130,10 @@ fn try_instance_mir<'tcx>( ) -> Result<&'tcx Body<'tcx>, &'static str> { match instance { ty::InstanceDef::DropGlue(_, Some(ty)) => match ty.kind() { - ty::Adt(def, substs) => { + ty::Adt(def, args) => { let fields = def.all_fields(); for field in fields { - let field_ty = field.ty(tcx, substs); + let field_ty = field.ty(tcx, args); if field_ty.has_param() && field_ty.has_projections() { return Err("cannot build drop shim for polymorphic type"); } diff --git a/compiler/rustc_mir_transform/src/inline/cycle.rs b/compiler/rustc_mir_transform/src/inline/cycle.rs index 8a10445f837..822634129fc 100644 --- a/compiler/rustc_mir_transform/src/inline/cycle.rs +++ b/compiler/rustc_mir_transform/src/inline/cycle.rs @@ -3,7 +3,7 @@ use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_middle::mir::TerminatorKind; use rustc_middle::ty::TypeVisitableExt; -use rustc_middle::ty::{self, subst::SubstsRef, InstanceDef, TyCtxt}; +use rustc_middle::ty::{self, GenericArgsRef, InstanceDef, TyCtxt}; use rustc_session::Limit; // FIXME: check whether it is cheaper to precompute the entire call graph instead of invoking @@ -43,16 +43,16 @@ pub(crate) fn mir_callgraph_reachable<'tcx>( recursion_limit: Limit, ) -> bool { trace!(%caller); - for &(callee, substs) in tcx.mir_inliner_callees(caller.def) { - let Ok(substs) = caller.try_subst_mir_and_normalize_erasing_regions( + for &(callee, args) in tcx.mir_inliner_callees(caller.def) { + let Ok(args) = caller.try_subst_mir_and_normalize_erasing_regions( tcx, param_env, - ty::EarlyBinder::bind(substs), + ty::EarlyBinder::bind(args), ) else { - trace!(?caller, ?param_env, ?substs, "cannot normalize, skipping"); + trace!(?caller, ?param_env, ?args, "cannot normalize, skipping"); continue; }; - let Ok(Some(callee)) = ty::Instance::resolve(tcx, param_env, callee, substs) else { + let Ok(Some(callee)) = ty::Instance::resolve(tcx, param_env, callee, args) else { trace!(?callee, "cannot resolve, skipping"); continue; }; @@ -147,7 +147,7 @@ pub(crate) fn mir_callgraph_reachable<'tcx>( pub(crate) fn mir_inliner_callees<'tcx>( tcx: TyCtxt<'tcx>, instance: ty::InstanceDef<'tcx>, -) -> &'tcx [(DefId, SubstsRef<'tcx>)] { +) -> &'tcx [(DefId, GenericArgsRef<'tcx>)] { let steal; let guard; let body = match (instance, instance.def_id().as_local()) { @@ -165,7 +165,7 @@ pub(crate) fn mir_inliner_callees<'tcx>( if let TerminatorKind::Call { func, .. } = &terminator.kind { let ty = func.ty(&body.local_decls, tcx); let call = match ty.kind() { - ty::FnDef(def_id, substs) => (*def_id, *substs), + ty::FnDef(def_id, args) => (*def_id, *args), _ => continue, }; calls.insert(call); diff --git a/compiler/rustc_mir_transform/src/instsimplify.rs b/compiler/rustc_mir_transform/src/instsimplify.rs index e4dc617620e..a430f8da35c 100644 --- a/compiler/rustc_mir_transform/src/instsimplify.rs +++ b/compiler/rustc_mir_transform/src/instsimplify.rs @@ -5,7 +5,7 @@ use crate::MirPass; use rustc_hir::Mutability; use rustc_middle::mir::*; use rustc_middle::ty::layout::ValidityRequirement; -use rustc_middle::ty::{self, ParamEnv, SubstsRef, Ty, TyCtxt}; +use rustc_middle::ty::{self, GenericArgsRef, ParamEnv, Ty, TyCtxt}; use rustc_span::symbol::Symbol; use rustc_target::abi::FieldIdx; @@ -163,14 +163,14 @@ impl<'tcx> InstSimplifyContext<'tcx, '_> { } // Transmuting a transparent struct/union to a field's type is a projection - if let ty::Adt(adt_def, substs) = operand_ty.kind() + if let ty::Adt(adt_def, args) = operand_ty.kind() && adt_def.repr().transparent() && (adt_def.is_struct() || adt_def.is_union()) && let Some(place) = operand.place() { let variant = adt_def.non_enum_variant(); for (i, field) in variant.fields.iter().enumerate() { - let field_ty = field.ty(self.tcx, substs); + let field_ty = field.ty(self.tcx, args); if field_ty == *cast_ty { let place = place.project_deeper(&[ProjectionElem::Field(FieldIdx::from_usize(i), *cast_ty)], self.tcx); let operand = if operand.is_move() { Operand::Move(place) } else { Operand::Copy(place) }; @@ -189,22 +189,22 @@ impl<'tcx> InstSimplifyContext<'tcx, '_> { statements: &mut Vec<Statement<'tcx>>, ) { let TerminatorKind::Call { func, args, destination, target, .. } = &mut terminator.kind - else { return }; + else { + return; + }; // It's definitely not a clone if there are multiple arguments if args.len() != 1 { return; } - let Some(destination_block) = *target - else { return }; + let Some(destination_block) = *target else { return }; // Only bother looking more if it's easy to know what we're calling - let Some((fn_def_id, fn_substs)) = func.const_fn_def() - else { return }; + let Some((fn_def_id, fn_args)) = func.const_fn_def() else { return }; // Clone needs one subst, so we can cheaply rule out other stuff - if fn_substs.len() != 1 { + if fn_args.len() != 1 { return; } @@ -212,8 +212,7 @@ impl<'tcx> InstSimplifyContext<'tcx, '_> { // doing DefId lookups to figure out what we're actually calling. let arg_ty = args[0].ty(self.local_decls, self.tcx); - let ty::Ref(_region, inner_ty, Mutability::Not) = *arg_ty.kind() - else { return }; + let ty::Ref(_region, inner_ty, Mutability::Not) = *arg_ty.kind() else { return }; if !inner_ty.is_trivially_pure_clone_copy() { return; @@ -227,15 +226,14 @@ impl<'tcx> InstSimplifyContext<'tcx, '_> { if !self.tcx.consider_optimizing(|| { format!( "InstSimplify - Call: {:?} SourceInfo: {:?}", - (fn_def_id, fn_substs), + (fn_def_id, fn_args), terminator.source_info ) }) { return; } - let Some(arg_place) = args.pop().unwrap().place() - else { return }; + let Some(arg_place) = args.pop().unwrap().place() else { return }; statements.push(Statement { source_info: terminator.source_info, @@ -254,17 +252,21 @@ impl<'tcx> InstSimplifyContext<'tcx, '_> { terminator: &mut Terminator<'tcx>, _statements: &mut Vec<Statement<'tcx>>, ) { - let TerminatorKind::Call { func, target, .. } = &mut terminator.kind else { return; }; - let Some(target_block) = target else { return; }; + let TerminatorKind::Call { func, target, .. } = &mut terminator.kind else { + return; + }; + let Some(target_block) = target else { + return; + }; let func_ty = func.ty(self.local_decls, self.tcx); - let Some((intrinsic_name, substs)) = resolve_rust_intrinsic(self.tcx, func_ty) else { + let Some((intrinsic_name, args)) = resolve_rust_intrinsic(self.tcx, func_ty) else { return; }; // The intrinsics we are interested in have one generic parameter - if substs.is_empty() { + if args.is_empty() { return; } - let ty = substs.type_at(0); + let ty = args.type_at(0); let known_is_valid = intrinsic_assert_panics(self.tcx, self.param_env, ty, intrinsic_name); match known_is_valid { @@ -295,10 +297,10 @@ fn intrinsic_assert_panics<'tcx>( fn resolve_rust_intrinsic<'tcx>( tcx: TyCtxt<'tcx>, func_ty: Ty<'tcx>, -) -> Option<(Symbol, SubstsRef<'tcx>)> { - if let ty::FnDef(def_id, substs) = *func_ty.kind() { +) -> Option<(Symbol, GenericArgsRef<'tcx>)> { + if let ty::FnDef(def_id, args) = *func_ty.kind() { if tcx.is_intrinsic(def_id) { - return Some((tcx.item_name(def_id), substs)); + return Some((tcx.item_name(def_id), args)); } } None diff --git a/compiler/rustc_mir_transform/src/large_enums.rs b/compiler/rustc_mir_transform/src/large_enums.rs index 8ed4706e172..19108dabdf4 100644 --- a/compiler/rustc_mir_transform/src/large_enums.rs +++ b/compiler/rustc_mir_transform/src/large_enums.rs @@ -48,7 +48,7 @@ impl EnumSizeOpt { alloc_cache: &mut FxHashMap<Ty<'tcx>, AllocId>, ) -> Option<(AdtDef<'tcx>, usize, AllocId)> { let adt_def = match ty.kind() { - ty::Adt(adt_def, _substs) if adt_def.is_enum() => adt_def, + ty::Adt(adt_def, _args) if adt_def.is_enum() => adt_def, _ => return None, }; let layout = tcx.layout_of(param_env.and(ty)).ok()?; diff --git a/compiler/rustc_mir_transform/src/lib.rs b/compiler/rustc_mir_transform/src/lib.rs index fa8257cf984..d419329f2d6 100644 --- a/compiler/rustc_mir_transform/src/lib.rs +++ b/compiler/rustc_mir_transform/src/lib.rs @@ -553,6 +553,7 @@ fn run_optimization_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { &normalize_array_len::NormalizeArrayLen, // has to run after `slice::len` lowering &const_goto::ConstGoto, &remove_unneeded_drops::RemoveUnneededDrops, + &ref_prop::ReferencePropagation, &sroa::ScalarReplacementOfAggregates, &match_branches::MatchBranchSimplification, // inst combine is after MatchBranchSimplification to clean up Ne(_1, false) @@ -560,7 +561,6 @@ fn run_optimization_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { &instsimplify::InstSimplify, &simplify::SimplifyLocals::BeforeConstProp, ©_prop::CopyProp, - &ref_prop::ReferencePropagation, // Perform `SeparateConstSwitch` after SSA-based analyses, as cloning blocks may // destroy the SSA property. It should still happen before const-propagation, so the // latter pass will leverage the created opportunities. diff --git a/compiler/rustc_mir_transform/src/lower_intrinsics.rs b/compiler/rustc_mir_transform/src/lower_intrinsics.rs index ce98e9b0c84..d1ecfe9f851 100644 --- a/compiler/rustc_mir_transform/src/lower_intrinsics.rs +++ b/compiler/rustc_mir_transform/src/lower_intrinsics.rs @@ -2,7 +2,7 @@ use crate::{errors, MirPass}; use rustc_middle::mir::*; -use rustc_middle::ty::subst::SubstsRef; +use rustc_middle::ty::GenericArgsRef; use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_span::symbol::{sym, Symbol}; use rustc_span::Span; @@ -19,7 +19,8 @@ impl<'tcx> MirPass<'tcx> for LowerIntrinsics { &mut terminator.kind { let func_ty = func.ty(local_decls, tcx); - let Some((intrinsic_name, substs)) = resolve_rust_intrinsic(tcx, func_ty) else { + let Some((intrinsic_name, generic_args)) = resolve_rust_intrinsic(tcx, func_ty) + else { continue; }; match intrinsic_name { @@ -149,7 +150,7 @@ impl<'tcx> MirPass<'tcx> for LowerIntrinsics { } sym::size_of | sym::min_align_of => { if let Some(target) = *target { - let tp_ty = substs.type_at(0); + let tp_ty = generic_args.type_at(0); let null_op = match intrinsic_name { sym::size_of => NullOp::SizeOf, sym::min_align_of => NullOp::AlignOf, @@ -251,7 +252,9 @@ impl<'tcx> MirPass<'tcx> for LowerIntrinsics { if let (Some(target), Some(arg)) = (*target, args[0].place()) { let ty::RawPtr(ty::TypeAndMut { ty: dest_ty, .. }) = destination.ty(local_decls, tcx).ty.kind() - else { bug!(); }; + else { + bug!(); + }; block.statements.push(Statement { source_info: terminator.source_info, @@ -315,10 +318,10 @@ impl<'tcx> MirPass<'tcx> for LowerIntrinsics { fn resolve_rust_intrinsic<'tcx>( tcx: TyCtxt<'tcx>, func_ty: Ty<'tcx>, -) -> Option<(Symbol, SubstsRef<'tcx>)> { - if let ty::FnDef(def_id, substs) = *func_ty.kind() { +) -> Option<(Symbol, GenericArgsRef<'tcx>)> { + if let ty::FnDef(def_id, args) = *func_ty.kind() { if tcx.is_intrinsic(def_id) { - return Some((tcx.item_name(def_id), substs)); + return Some((tcx.item_name(def_id), args)); } } None diff --git a/compiler/rustc_mir_transform/src/ref_prop.rs b/compiler/rustc_mir_transform/src/ref_prop.rs index bbd9f76ba5c..c17c791f9c3 100644 --- a/compiler/rustc_mir_transform/src/ref_prop.rs +++ b/compiler/rustc_mir_transform/src/ref_prop.rs @@ -71,7 +71,7 @@ pub struct ReferencePropagation; impl<'tcx> MirPass<'tcx> for ReferencePropagation { fn is_enabled(&self, sess: &rustc_session::Session) -> bool { - sess.mir_opt_level() >= 4 + sess.mir_opt_level() >= 2 } #[instrument(level = "trace", skip(self, tcx, body))] @@ -355,7 +355,10 @@ impl<'tcx> MutVisitor<'tcx> for Replacer<'tcx> { } fn visit_var_debug_info(&mut self, debuginfo: &mut VarDebugInfo<'tcx>) { - if let VarDebugInfoContents::Place(ref mut place) = debuginfo.value + // If the debuginfo is a pointer to another place: + // - if it's a reborrow, see through it; + // - if it's a direct borrow, increase `debuginfo.references`. + while let VarDebugInfoContents::Place(ref mut place) = debuginfo.value && place.projection.is_empty() && let Value::Pointer(target, _) = self.targets[place.local] && target.projection.iter().all(|p| p.can_use_in_debuginfo()) @@ -369,28 +372,37 @@ impl<'tcx> MutVisitor<'tcx> for Replacer<'tcx> { debuginfo.references = references; *place = target; self.any_replacement = true; + } else { + break } } + + // Simplify eventual projections left inside `debuginfo`. + self.super_var_debug_info(debuginfo); } fn visit_place(&mut self, place: &mut Place<'tcx>, ctxt: PlaceContext, loc: Location) { - if place.projection.first() != Some(&PlaceElem::Deref) { - return; - } - loop { - if let Value::Pointer(target, _) = self.targets[place.local] { - let perform_opt = matches!(ctxt, PlaceContext::NonUse(_)) - || self.allowed_replacements.contains(&(target.local, loc)); - - if perform_opt { - *place = target.project_deeper(&place.projection[1..], self.tcx); - self.any_replacement = true; - continue; + if place.projection.first() != Some(&PlaceElem::Deref) { + return; + } + + let Value::Pointer(target, _) = self.targets[place.local] else { return }; + + let perform_opt = match ctxt { + PlaceContext::NonUse(NonUseContext::VarDebugInfo) => { + target.projection.iter().all(|p| p.can_use_in_debuginfo()) } + PlaceContext::NonUse(_) => true, + _ => self.allowed_replacements.contains(&(target.local, loc)), + }; + + if !perform_opt { + return; } - break; + *place = target.project_deeper(&place.projection[1..], self.tcx); + self.any_replacement = true; } } diff --git a/compiler/rustc_mir_transform/src/remove_uninit_drops.rs b/compiler/rustc_mir_transform/src/remove_uninit_drops.rs index 283931de043..6f9edd07d73 100644 --- a/compiler/rustc_mir_transform/src/remove_uninit_drops.rs +++ b/compiler/rustc_mir_transform/src/remove_uninit_drops.rs @@ -1,6 +1,6 @@ use rustc_index::bit_set::ChunkedBitSet; use rustc_middle::mir::{Body, TerminatorKind}; -use rustc_middle::ty::subst::SubstsRef; +use rustc_middle::ty::GenericArgsRef; use rustc_middle::ty::{self, ParamEnv, Ty, TyCtxt, VariantDef}; use rustc_mir_dataflow::impls::MaybeInitializedPlaces; use rustc_mir_dataflow::move_paths::{LookupResult, MoveData, MovePathIndex}; @@ -38,8 +38,7 @@ impl<'tcx> MirPass<'tcx> for RemoveUninitDrops { let mut to_remove = vec![]; for (bb, block) in body.basic_blocks.iter_enumerated() { let terminator = block.terminator(); - let TerminatorKind::Drop { place, .. } = &terminator.kind - else { continue }; + let TerminatorKind::Drop { place, .. } = &terminator.kind else { continue }; maybe_inits.seek_before_primary_effect(body.terminator_loc(bb)); @@ -64,9 +63,9 @@ impl<'tcx> MirPass<'tcx> for RemoveUninitDrops { for bb in to_remove { let block = &mut body.basic_blocks_mut()[bb]; - let TerminatorKind::Drop { target, .. } - = &block.terminator().kind - else { unreachable!() }; + let TerminatorKind::Drop { target, .. } = &block.terminator().kind else { + unreachable!() + }; // Replace block terminator with `Goto`. block.terminator_mut().kind = TerminatorKind::Goto { target: *target }; @@ -99,7 +98,7 @@ fn is_needs_drop_and_init<'tcx>( // This pass is only needed for const-checking, so it doesn't handle as many cases as // `DropCtxt::open_drop`, since they aren't relevant in a const-context. match ty.kind() { - ty::Adt(adt, substs) => { + ty::Adt(adt, args) => { let dont_elaborate = adt.is_union() || adt.is_manually_drop() || adt.has_dtor(tcx); if dont_elaborate { return true; @@ -119,7 +118,7 @@ fn is_needs_drop_and_init<'tcx>( let downcast = move_path_children_matching(move_data, mpi, |x| x.is_downcast_to(vid)); let Some(dc_mpi) = downcast else { - return variant_needs_drop(tcx, param_env, substs, variant); + return variant_needs_drop(tcx, param_env, args, variant); }; dc_mpi @@ -131,7 +130,7 @@ fn is_needs_drop_and_init<'tcx>( .fields .iter() .enumerate() - .map(|(f, field)| (FieldIdx::from_usize(f), field.ty(tcx, substs), mpi)) + .map(|(f, field)| (FieldIdx::from_usize(f), field.ty(tcx, args), mpi)) .any(field_needs_drop_and_init) }) } @@ -149,11 +148,11 @@ fn is_needs_drop_and_init<'tcx>( fn variant_needs_drop<'tcx>( tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, variant: &VariantDef, ) -> bool { variant.fields.iter().any(|field| { - let f_ty = field.ty(tcx, substs); + let f_ty = field.ty(tcx, args); f_ty.needs_drop(tcx, param_env) }) } diff --git a/compiler/rustc_mir_transform/src/remove_zsts.rs b/compiler/rustc_mir_transform/src/remove_zsts.rs index 1f37f03cff1..1ba9ad87537 100644 --- a/compiler/rustc_mir_transform/src/remove_zsts.rs +++ b/compiler/rustc_mir_transform/src/remove_zsts.rs @@ -15,7 +15,7 @@ impl<'tcx> MirPass<'tcx> for RemoveZsts { fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { // Avoid query cycles (generators require optimized MIR for layout). - if tcx.type_of(body.source.def_id()).subst_identity().is_generator() { + if tcx.type_of(body.source.def_id()).instantiate_identity().is_generator() { return; } let param_env = tcx.param_env_reveal_all_normalized(body.source.def_id()); diff --git a/compiler/rustc_mir_transform/src/shim.rs b/compiler/rustc_mir_transform/src/shim.rs index b176db3c9e0..5e8ba4f544c 100644 --- a/compiler/rustc_mir_transform/src/shim.rs +++ b/compiler/rustc_mir_transform/src/shim.rs @@ -3,8 +3,8 @@ use rustc_hir::def_id::DefId; use rustc_hir::lang_items::LangItem; use rustc_middle::mir::*; use rustc_middle::query::Providers; -use rustc_middle::ty::InternalSubsts; -use rustc_middle::ty::{self, EarlyBinder, GeneratorSubsts, Ty, TyCtxt}; +use rustc_middle::ty::GenericArgs; +use rustc_middle::ty::{self, EarlyBinder, GeneratorArgs, Ty, TyCtxt}; use rustc_target::abi::{FieldIdx, VariantIdx, FIRST_VARIANT}; use rustc_index::{Idx, IndexVec}; @@ -69,9 +69,9 @@ fn make_shim<'tcx>(tcx: TyCtxt<'tcx>, instance: ty::InstanceDef<'tcx>) -> Body<' ty::InstanceDef::DropGlue(def_id, ty) => { // FIXME(#91576): Drop shims for generators aren't subject to the MIR passes at the end // of this function. Is this intentional? - if let Some(ty::Generator(gen_def_id, substs, _)) = ty.map(Ty::kind) { + if let Some(ty::Generator(gen_def_id, args, _)) = ty.map(Ty::kind) { let body = tcx.optimized_mir(*gen_def_id).generator_drop().unwrap(); - let body = EarlyBinder::bind(body.clone()).subst(tcx, substs); + let body = EarlyBinder::bind(body.clone()).instantiate(tcx, args); debug!("make_shim({:?}) = {:?}", instance, body); return body; } @@ -160,12 +160,12 @@ fn build_drop_shim<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, ty: Option<Ty<'tcx>>) assert!(!matches!(ty, Some(ty) if ty.is_generator())); - let substs = if let Some(ty) = ty { - tcx.mk_substs(&[ty.into()]) + let args = if let Some(ty) = ty { + tcx.mk_args(&[ty.into()]) } else { - InternalSubsts::identity_for_item(tcx, def_id) + GenericArgs::identity_for_item(tcx, def_id) }; - let sig = tcx.fn_sig(def_id).subst(tcx, substs); + let sig = tcx.fn_sig(def_id).instantiate(tcx, args); let sig = tcx.erase_late_bound_regions(sig); let span = tcx.def_span(def_id); @@ -377,12 +377,10 @@ fn build_clone_shim<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, self_ty: Ty<'tcx>) - match self_ty.kind() { _ if is_copy => builder.copy_shim(), - ty::Closure(_, substs) => { - builder.tuple_like_shim(dest, src, substs.as_closure().upvar_tys()) - } + ty::Closure(_, args) => builder.tuple_like_shim(dest, src, args.as_closure().upvar_tys()), ty::Tuple(..) => builder.tuple_like_shim(dest, src, self_ty.tuple_fields()), - ty::Generator(gen_def_id, substs, hir::Movability::Movable) => { - builder.generator_shim(dest, src, *gen_def_id, substs.as_generator()) + ty::Generator(gen_def_id, args, hir::Movability::Movable) => { + builder.generator_shim(dest, src, *gen_def_id, args.as_generator()) } _ => bug!("clone shim for `{:?}` which is not `Copy` and is not an aggregate", self_ty), }; @@ -404,7 +402,7 @@ impl<'tcx> CloneShimBuilder<'tcx> { // we must subst the self_ty because it's // otherwise going to be TySelf and we can't index // or access fields of a Place of type TySelf. - let sig = tcx.fn_sig(def_id).subst(tcx, &[self_ty.into()]); + let sig = tcx.fn_sig(def_id).instantiate(tcx, &[self_ty.into()]); let sig = tcx.erase_late_bound_regions(sig); let span = tcx.def_span(def_id); @@ -587,17 +585,17 @@ impl<'tcx> CloneShimBuilder<'tcx> { dest: Place<'tcx>, src: Place<'tcx>, gen_def_id: DefId, - substs: GeneratorSubsts<'tcx>, + args: GeneratorArgs<'tcx>, ) { self.block(vec![], TerminatorKind::Goto { target: self.block_index_offset(3) }, false); let unwind = self.block(vec![], TerminatorKind::Resume, true); // This will get overwritten with a switch once we know the target blocks let switch = self.block(vec![], TerminatorKind::Unreachable, false); - let unwind = self.clone_fields(dest, src, switch, unwind, substs.upvar_tys()); + let unwind = self.clone_fields(dest, src, switch, unwind, args.upvar_tys()); let target = self.block(vec![], TerminatorKind::Return, false); let unreachable = self.block(vec![], TerminatorKind::Unreachable, false); - let mut cases = Vec::with_capacity(substs.state_tys(gen_def_id, self.tcx).count()); - for (index, state_tys) in substs.state_tys(gen_def_id, self.tcx).enumerate() { + let mut cases = Vec::with_capacity(args.state_tys(gen_def_id, self.tcx).count()); + for (index, state_tys) in args.state_tys(gen_def_id, self.tcx).enumerate() { let variant_index = VariantIdx::new(index); let dest = self.tcx.mk_place_downcast_unnamed(dest, variant_index); let src = self.tcx.mk_place_downcast_unnamed(src, variant_index); @@ -613,7 +611,7 @@ impl<'tcx> CloneShimBuilder<'tcx> { cases.push((index as u128, start_block)); let _final_cleanup_block = self.clone_fields(dest, src, target, unwind, state_tys); } - let discr_ty = substs.discr_ty(self.tcx); + let discr_ty = args.discr_ty(self.tcx); let temp = self.make_place(Mutability::Mut, discr_ty); let rvalue = Rvalue::Discriminant(src); let statement = self.make_statement(StatementKind::Assign(Box::new((temp, rvalue)))); @@ -642,7 +640,7 @@ fn build_call_shim<'tcx>( // `FnPtrShim` contains the fn pointer type that a call shim is being built for - this is used // to substitute into the signature of the shim. It is not necessary for users of this // MIR body to perform further substitutions (see `InstanceDef::has_polymorphic_mir_body`). - let (sig_substs, untuple_args) = if let ty::InstanceDef::FnPtrShim(_, ty) = instance { + let (sig_args, untuple_args) = if let ty::InstanceDef::FnPtrShim(_, ty) = instance { let sig = tcx.erase_late_bound_regions(ty.fn_sig(tcx)); let untuple_args = sig.inputs(); @@ -659,11 +657,11 @@ fn build_call_shim<'tcx>( let sig = tcx.fn_sig(def_id); let sig = sig.map_bound(|sig| tcx.erase_late_bound_regions(sig)); - assert_eq!(sig_substs.is_some(), !instance.has_polymorphic_mir_body()); - let mut sig = if let Some(sig_substs) = sig_substs { - sig.subst(tcx, &sig_substs) + assert_eq!(sig_args.is_some(), !instance.has_polymorphic_mir_body()); + let mut sig = if let Some(sig_args) = sig_args { + sig.instantiate(tcx, &sig_args) } else { - sig.subst_identity() + sig.instantiate_identity() }; if let CallKind::Indirect(fnty) = call_kind { @@ -751,7 +749,7 @@ fn build_call_shim<'tcx>( // `FnDef` call with optional receiver. CallKind::Direct(def_id) => { - let ty = tcx.type_of(def_id).subst_identity(); + let ty = tcx.type_of(def_id).instantiate_identity(); ( Operand::Constant(Box::new(Constant { span, @@ -868,12 +866,12 @@ pub fn build_adt_ctor(tcx: TyCtxt<'_>, ctor_id: DefId) -> Body<'_> { // Normalize the sig. let sig = tcx .fn_sig(ctor_id) - .subst_identity() + .instantiate_identity() .no_bound_vars() .expect("LBR in ADT constructor signature"); let sig = tcx.normalize_erasing_regions(param_env, sig); - let ty::Adt(adt_def, substs) = sig.output().kind() else { + let ty::Adt(adt_def, args) = sig.output().kind() else { bug!("unexpected type for ADT ctor {:?}", sig.output()); }; @@ -896,7 +894,7 @@ pub fn build_adt_ctor(tcx: TyCtxt<'_>, ctor_id: DefId) -> Body<'_> { // return; debug!("build_ctor: variant_index={:?}", variant_index); - let kind = AggregateKind::Adt(adt_def.did(), variant_index, substs, None, None); + let kind = AggregateKind::Adt(adt_def.did(), variant_index, args, None, None); let variant = adt_def.variant(variant_index); let statement = Statement { kind: StatementKind::Assign(Box::new(( @@ -941,7 +939,7 @@ pub fn build_adt_ctor(tcx: TyCtxt<'_>, ctor_id: DefId) -> Body<'_> { fn build_fn_ptr_addr_shim<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, self_ty: Ty<'tcx>) -> Body<'tcx> { assert!(matches!(self_ty.kind(), ty::FnPtr(..)), "expected fn ptr, found {self_ty}"); let span = tcx.def_span(def_id); - let Some(sig) = tcx.fn_sig(def_id).subst(tcx, &[self_ty.into()]).no_bound_vars() else { + let Some(sig) = tcx.fn_sig(def_id).instantiate(tcx, &[self_ty.into()]).no_bound_vars() else { span_bug!(span, "FnPtr::addr with bound vars for `{self_ty}`"); }; let locals = local_decls_for_sig(&sig, span); diff --git a/compiler/rustc_mir_transform/src/simplify.rs b/compiler/rustc_mir_transform/src/simplify.rs index e59219321b7..b7a51cfd619 100644 --- a/compiler/rustc_mir_transform/src/simplify.rs +++ b/compiler/rustc_mir_transform/src/simplify.rs @@ -199,7 +199,8 @@ impl<'a, 'tcx> CfgSimplifier<'a, 'tcx> { let last = current; *start = last; while let Some((current, mut terminator)) = terminators.pop() { - let Terminator { kind: TerminatorKind::Goto { ref mut target }, .. } = terminator else { + let Terminator { kind: TerminatorKind::Goto { ref mut target }, .. } = terminator + else { unreachable!(); }; *changed |= *target != last; diff --git a/compiler/rustc_mir_transform/src/sroa.rs b/compiler/rustc_mir_transform/src/sroa.rs index 881a1547c52..e66ae8ff884 100644 --- a/compiler/rustc_mir_transform/src/sroa.rs +++ b/compiler/rustc_mir_transform/src/sroa.rs @@ -20,7 +20,7 @@ impl<'tcx> MirPass<'tcx> for ScalarReplacementOfAggregates { debug!(def_id = ?body.source.def_id()); // Avoid query cycles (generators require optimized MIR for layout). - if tcx.type_of(body.source.def_id()).subst_identity().is_generator() { + if tcx.type_of(body.source.def_id()).instantiate_identity().is_generator() { return; } @@ -64,7 +64,7 @@ fn escaping_locals<'tcx>( if ty.is_union() || ty.is_enum() { return true; } - if let ty::Adt(def, _substs) = ty.kind() { + if let ty::Adt(def, _args) = ty.kind() { if def.repr().flags.contains(ReprFlags::IS_SIMD) { // Exclude #[repr(simd)] types so that they are not de-optimized into an array return true; @@ -161,7 +161,9 @@ struct ReplacementMap<'tcx> { impl<'tcx> ReplacementMap<'tcx> { fn replace_place(&self, tcx: TyCtxt<'tcx>, place: PlaceRef<'tcx>) -> Option<Place<'tcx>> { - let &[PlaceElem::Field(f, _), ref rest @ ..] = place.projection else { return None; }; + let &[PlaceElem::Field(f, _), ref rest @ ..] = place.projection else { + return None; + }; let fields = self.fragments[place.local].as_ref()?; let (_, new_local) = fields[f]?; Some(Place { local: new_local, projection: tcx.mk_place_elems(&rest) }) diff --git a/compiler/rustc_mir_transform/src/ssa.rs b/compiler/rustc_mir_transform/src/ssa.rs index 8dc2dfe13bd..04bc461c815 100644 --- a/compiler/rustc_mir_transform/src/ssa.rs +++ b/compiler/rustc_mir_transform/src/ssa.rs @@ -266,9 +266,11 @@ fn compute_copy_classes(ssa: &mut SsaLocals, body: &Body<'_>) { let mut copies = IndexVec::from_fn_n(|l| l, body.local_decls.len()); for (local, rvalue, _) in ssa.assignments(body) { - let (Rvalue::Use(Operand::Copy(place) | Operand::Move(place)) | Rvalue::CopyForDeref(place)) - = rvalue - else { continue }; + let (Rvalue::Use(Operand::Copy(place) | Operand::Move(place)) + | Rvalue::CopyForDeref(place)) = rvalue + else { + continue; + }; let Some(rhs) = place.as_local() else { continue }; let local_ty = body.local_decls()[local].ty; diff --git a/compiler/rustc_mir_transform/src/uninhabited_enum_branching.rs b/compiler/rustc_mir_transform/src/uninhabited_enum_branching.rs index 5389b9f52eb..092bcb5c979 100644 --- a/compiler/rustc_mir_transform/src/uninhabited_enum_branching.rs +++ b/compiler/rustc_mir_transform/src/uninhabited_enum_branching.rs @@ -105,7 +105,8 @@ impl<'tcx> MirPass<'tcx> for UninhabitedEnumBranching { for bb in body.basic_blocks.indices() { trace!("processing block {:?}", bb); - let Some(discriminant_ty) = get_switched_on_type(&body.basic_blocks[bb], tcx, body) else { + let Some(discriminant_ty) = get_switched_on_type(&body.basic_blocks[bb], tcx, body) + else { continue; }; diff --git a/compiler/rustc_monomorphize/src/collector.rs b/compiler/rustc_monomorphize/src/collector.rs index 242269e9d1a..5b678d4ba78 100644 --- a/compiler/rustc_monomorphize/src/collector.rs +++ b/compiler/rustc_monomorphize/src/collector.rs @@ -178,11 +178,11 @@ use rustc_middle::mir::{self, Local, Location}; use rustc_middle::query::TyCtxtAt; use rustc_middle::ty::adjustment::{CustomCoerceUnsized, PointerCoercion}; use rustc_middle::ty::print::with_no_trimmed_paths; -use rustc_middle::ty::subst::{GenericArgKind, InternalSubsts}; use rustc_middle::ty::{ self, GenericParamDefKind, Instance, InstanceDef, Ty, TyCtxt, TypeFoldable, TypeVisitableExt, VtblEntry, }; +use rustc_middle::ty::{GenericArgKind, GenericArgs}; use rustc_middle::{middle::codegen_fn_attrs::CodegenFnAttrFlags, mir::visit::TyContext}; use rustc_session::config::EntryFnType; use rustc_session::lint::builtin::LARGE_ASSIGNMENTS; @@ -393,7 +393,7 @@ fn collect_items_rec<'tcx>( starting_item.span, MonoItem::Fn(Instance { def: InstanceDef::ThreadLocalShim(def_id), - substs: InternalSubsts::empty(), + args: GenericArgs::empty(), }), )); } @@ -555,7 +555,7 @@ fn check_recursion_limit<'tcx>( fn check_type_length_limit<'tcx>(tcx: TyCtxt<'tcx>, instance: Instance<'tcx>) { let type_length = instance - .substs + .args .iter() .flat_map(|arg| arg.walk()) .filter(|arg| match arg.unpack() { @@ -659,11 +659,11 @@ impl<'a, 'tcx> MirVisitor<'tcx> for MirUsedCollector<'a, 'tcx> { let source_ty = operand.ty(self.body, self.tcx); let source_ty = self.monomorphize(source_ty); match *source_ty.kind() { - ty::Closure(def_id, substs) => { + ty::Closure(def_id, args) => { let instance = Instance::resolve_closure( self.tcx, def_id, - substs, + args, ty::ClosureKind::FnOnce, ) .expect("failed to normalize and resolve closure during codegen"); @@ -875,12 +875,11 @@ fn visit_fn_use<'tcx>( source: Span, output: &mut MonoItems<'tcx>, ) { - if let ty::FnDef(def_id, substs) = *ty.kind() { + if let ty::FnDef(def_id, args) = *ty.kind() { let instance = if is_direct_call { - ty::Instance::expect_resolve(tcx, ty::ParamEnv::reveal_all(), def_id, substs) + ty::Instance::expect_resolve(tcx, ty::ParamEnv::reveal_all(), def_id, args) } else { - match ty::Instance::resolve_for_fn_ptr(tcx, ty::ParamEnv::reveal_all(), def_id, substs) - { + match ty::Instance::resolve_for_fn_ptr(tcx, ty::ParamEnv::reveal_all(), def_id, args) { Some(instance) => instance, _ => bug!("failed to resolve instance for {ty}"), } @@ -1043,7 +1042,7 @@ fn find_vtable_types_for_unsizing<'tcx>( // T as dyn* Trait (_, &ty::Dynamic(_, _, ty::DynStar)) => ptr_vtable(source_ty, target_ty), - (&ty::Adt(source_adt_def, source_substs), &ty::Adt(target_adt_def, target_substs)) => { + (&ty::Adt(source_adt_def, source_args), &ty::Adt(target_adt_def, target_args)) => { assert_eq!(source_adt_def, target_adt_def); let CustomCoerceUnsized::Struct(coerce_index) = @@ -1059,8 +1058,8 @@ fn find_vtable_types_for_unsizing<'tcx>( find_vtable_types_for_unsizing( tcx, - source_fields[coerce_index].ty(*tcx, source_substs), - target_fields[coerce_index].ty(*tcx, target_substs), + source_fields[coerce_index].ty(*tcx, source_args), + target_fields[coerce_index].ty(*tcx, target_args), ) } _ => bug!( @@ -1245,7 +1244,7 @@ impl<'v> RootCollector<'_, 'v> { self.tcx, ty::ParamEnv::reveal_all(), start_def_id, - self.tcx.mk_substs(&[main_ret_ty.into()]), + self.tcx.mk_args(&[main_ret_ty.into()]), ) .unwrap() .unwrap(); @@ -1292,8 +1291,8 @@ fn create_mono_items_for_default_impls<'tcx>( ) } }; - let impl_substs = InternalSubsts::for_item(tcx, item.owner_id.to_def_id(), only_region_params); - let trait_ref = trait_ref.subst(tcx, impl_substs); + let impl_args = GenericArgs::for_item(tcx, item.owner_id.to_def_id(), only_region_params); + let trait_ref = trait_ref.instantiate(tcx, impl_args); // Unlike 'lazy' monomorphization that begins by collecting items transitively // called by `main` or other global items, when eagerly monomorphizing impl @@ -1304,7 +1303,7 @@ fn create_mono_items_for_default_impls<'tcx>( // consider higher-ranked predicates such as `for<'a> &'a mut [u8]: Copy` to // be trivially false. We must now check that the impl has no impossible-to-satisfy // predicates. - if tcx.subst_and_check_impossible_predicates((item.owner_id.to_def_id(), impl_substs)) { + if tcx.subst_and_check_impossible_predicates((item.owner_id.to_def_id(), impl_args)) { return; } @@ -1322,8 +1321,8 @@ fn create_mono_items_for_default_impls<'tcx>( // As mentioned above, the method is legal to eagerly instantiate if it // only has lifetime substitutions. This is validated by - let substs = trait_ref.substs.extend_to(tcx, method.def_id, only_region_params); - let instance = ty::Instance::expect_resolve(tcx, param_env, method.def_id, substs); + let args = trait_ref.args.extend_to(tcx, method.def_id, only_region_params); + let instance = ty::Instance::expect_resolve(tcx, param_env, method.def_id, args); let mono_item = create_fn_mono_item(tcx, instance, DUMMY_SP); if mono_item.node.is_instantiable(tcx) && should_codegen_locally(tcx, &instance) { diff --git a/compiler/rustc_monomorphize/src/partitioning.rs b/compiler/rustc_monomorphize/src/partitioning.rs index da76cf2236c..54096abb2e0 100644 --- a/compiler/rustc_monomorphize/src/partitioning.rs +++ b/compiler/rustc_monomorphize/src/partitioning.rs @@ -107,7 +107,8 @@ use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags; use rustc_middle::middle::exported_symbols::{SymbolExportInfo, SymbolExportLevel}; use rustc_middle::mir; use rustc_middle::mir::mono::{ - CodegenUnit, CodegenUnitNameBuilder, InstantiationMode, Linkage, MonoItem, Visibility, + CodegenUnit, CodegenUnitNameBuilder, InstantiationMode, Linkage, MonoItem, MonoItemData, + Visibility, }; use rustc_middle::query::Providers; use rustc_middle::ty::print::{characteristic_def_id_of_type, with_no_trimmed_paths}; @@ -130,11 +131,6 @@ struct PlacedMonoItems<'tcx> { codegen_units: Vec<CodegenUnit<'tcx>>, internalization_candidates: FxHashSet<MonoItem<'tcx>>, - - /// These must be obtained when the iterator in `partition` runs. They - /// can't be obtained later because some inlined functions might not be - /// reachable. - unique_inlined_stats: (usize, usize), } // The output CGUs are sorted by name. @@ -152,11 +148,11 @@ where // Place all mono items into a codegen unit. `place_mono_items` is // responsible for initializing the CGU size estimates. - let PlacedMonoItems { mut codegen_units, internalization_candidates, unique_inlined_stats } = { + let PlacedMonoItems { mut codegen_units, internalization_candidates } = { let _prof_timer = tcx.prof.generic_activity("cgu_partitioning_place_items"); let placed = place_mono_items(cx, mono_items); - debug_dump(tcx, "PLACE", &placed.codegen_units, placed.unique_inlined_stats); + debug_dump(tcx, "PLACE", &placed.codegen_units); placed }; @@ -167,7 +163,7 @@ where { let _prof_timer = tcx.prof.generic_activity("cgu_partitioning_merge_cgus"); merge_codegen_units(cx, &mut codegen_units); - debug_dump(tcx, "MERGE", &codegen_units, unique_inlined_stats); + debug_dump(tcx, "MERGE", &codegen_units); } // Make as many symbols "internal" as possible, so LLVM has more freedom to @@ -176,7 +172,7 @@ where let _prof_timer = tcx.prof.generic_activity("cgu_partitioning_internalize_symbols"); internalize_symbols(cx, &mut codegen_units, internalization_candidates); - debug_dump(tcx, "INTERNALIZE", &codegen_units, unique_inlined_stats); + debug_dump(tcx, "INTERNALIZE", &codegen_units); } // Mark one CGU for dead code, if necessary. @@ -216,18 +212,12 @@ where let cgu_name_builder = &mut CodegenUnitNameBuilder::new(cx.tcx); let cgu_name_cache = &mut FxHashMap::default(); - let mut num_unique_inlined_items = 0; - let mut unique_inlined_items_size = 0; for mono_item in mono_items { // Handle only root items directly here. Inlined items are handled at // the bottom of the loop based on reachability. match mono_item.instantiation_mode(cx.tcx) { InstantiationMode::GloballyShared { .. } => {} - InstantiationMode::LocalCopy => { - num_unique_inlined_items += 1; - unique_inlined_items_size += mono_item.size_estimate(cx.tcx); - continue; - } + InstantiationMode::LocalCopy => continue, } let characteristic_def_id = characteristic_def_id_of_mono_item(cx.tcx, mono_item); @@ -256,8 +246,9 @@ where if visibility == Visibility::Hidden && can_be_internalized { internalization_candidates.insert(mono_item); } + let size_estimate = mono_item.size_estimate(cx.tcx); - cgu.items_mut().insert(mono_item, (linkage, visibility)); + cgu.items_mut().insert(mono_item, MonoItemData { linkage, visibility, size_estimate }); // Get all inlined items that are reachable from `mono_item` without // going via another root item. This includes drop-glue, functions from @@ -271,7 +262,11 @@ where // the `insert` will be a no-op. for inlined_item in reachable_inlined_items { // This is a CGU-private copy. - cgu.items_mut().insert(inlined_item, (Linkage::Internal, Visibility::Default)); + cgu.items_mut().entry(inlined_item).or_insert_with(|| MonoItemData { + linkage: Linkage::Internal, + visibility: Visibility::Default, + size_estimate: inlined_item.size_estimate(cx.tcx), + }); } } @@ -286,14 +281,10 @@ where codegen_units.sort_by(|a, b| a.name().as_str().cmp(b.name().as_str())); for cgu in codegen_units.iter_mut() { - cgu.compute_size_estimate(cx.tcx); + cgu.compute_size_estimate(); } - return PlacedMonoItems { - codegen_units, - internalization_candidates, - unique_inlined_stats: (num_unique_inlined_items, unique_inlined_items_size), - }; + return PlacedMonoItems { codegen_units, internalization_candidates }; fn get_reachable_inlined_items<'tcx>( tcx: TyCtxt<'tcx>, @@ -349,7 +340,7 @@ fn merge_codegen_units<'tcx>( && codegen_units.iter().any(|cgu| cgu.size_estimate() < NON_INCR_MIN_CGU_SIZE)) { // Sort small cgus to the back. - codegen_units.sort_by_cached_key(|cgu| cmp::Reverse(cgu.size_estimate())); + codegen_units.sort_by_key(|cgu| cmp::Reverse(cgu.size_estimate())); let mut smallest = codegen_units.pop().unwrap(); let second_smallest = codegen_units.last_mut().unwrap(); @@ -358,7 +349,7 @@ fn merge_codegen_units<'tcx>( // may be duplicate inlined items, in which case the destination CGU is // unaffected. Recalculate size estimates afterwards. second_smallest.items_mut().extend(smallest.items_mut().drain()); - second_smallest.compute_size_estimate(cx.tcx); + second_smallest.compute_size_estimate(); // Record that `second_smallest` now contains all the stuff that was // in `smallest` before. @@ -492,7 +483,7 @@ fn internalize_symbols<'tcx>( for cgu in codegen_units { let home_cgu = MonoItemPlacement::SingleCgu(cgu.name()); - for (item, linkage_and_visibility) in cgu.items_mut() { + for (item, data) in cgu.items_mut() { if !internalization_candidates.contains(item) { // This item is no candidate for internalizing, so skip it. continue; @@ -520,7 +511,8 @@ fn internalize_symbols<'tcx>( // If we got here, we did not find any uses from other CGUs, so // it's fine to make this monomorphization internal. - *linkage_and_visibility = (Linkage::Internal, Visibility::Default); + data.linkage = Linkage::Internal; + data.visibility = Visibility::Default; } } } @@ -537,7 +529,7 @@ fn mark_code_coverage_dead_code_cgu<'tcx>(codegen_units: &mut [CodegenUnit<'tcx> // function symbols to be included via `-u` or `/include` linker args. let dead_code_cgu = codegen_units .iter_mut() - .filter(|cgu| cgu.items().iter().any(|(_, (linkage, _))| *linkage == Linkage::External)) + .filter(|cgu| cgu.items().iter().any(|(_, data)| data.linkage == Linkage::External)) .min_by_key(|cgu| cgu.size_estimate()); // If there are no CGUs that have externally linked items, then we just @@ -572,7 +564,7 @@ fn characteristic_def_id_of_mono_item<'tcx>( // DefId, we use the location of the impl after all. if tcx.trait_of_item(def_id).is_some() { - let self_ty = instance.substs.type_at(0); + let self_ty = instance.args.type_at(0); // This is a default implementation of a trait method. return characteristic_def_id_of_type(self_ty).or(Some(def_id)); } @@ -592,7 +584,7 @@ fn characteristic_def_id_of_mono_item<'tcx>( if !tcx.sess.opts.unstable_opts.polymorphize || !instance.has_param() { // This is a method within an impl, find out what the self-type is: let impl_self_ty = tcx.subst_and_normalize_erasing_regions( - instance.substs, + instance.args, ty::ParamEnv::reveal_all(), tcx.type_of(impl_def_id), ); @@ -745,7 +737,7 @@ fn mono_item_visibility<'tcx>( return Visibility::Hidden; } - let is_generic = instance.substs.non_erasable_generics().next().is_some(); + let is_generic = instance.args.non_erasable_generics().next().is_some(); // Upstream `DefId` instances get different handling than local ones. let Some(def_id) = def_id.as_local() else { @@ -851,12 +843,7 @@ fn default_visibility(tcx: TyCtxt<'_>, id: DefId, is_generic: bool) -> Visibilit } } -fn debug_dump<'a, 'tcx: 'a>( - tcx: TyCtxt<'tcx>, - label: &str, - cgus: &[CodegenUnit<'tcx>], - (unique_inlined_items, unique_inlined_size): (usize, usize), -) { +fn debug_dump<'a, 'tcx: 'a>(tcx: TyCtxt<'tcx>, label: &str, cgus: &[CodegenUnit<'tcx>]) { let dump = move || { use std::fmt::Write; @@ -865,28 +852,36 @@ fn debug_dump<'a, 'tcx: 'a>( // Note: every unique root item is placed exactly once, so the number // of unique root items always equals the number of placed root items. + // + // Also, unreached inlined items won't be counted here. This is fine. + + let mut inlined_items = FxHashSet::default(); let mut root_items = 0; - // unique_inlined_items is passed in above. + let mut unique_inlined_items = 0; let mut placed_inlined_items = 0; let mut root_size = 0; - // unique_inlined_size is passed in above. + let mut unique_inlined_size = 0; let mut placed_inlined_size = 0; for cgu in cgus.iter() { num_cgus += 1; all_cgu_sizes.push(cgu.size_estimate()); - for (item, _) in cgu.items() { + for (item, data) in cgu.items() { match item.instantiation_mode(tcx) { InstantiationMode::GloballyShared { .. } => { root_items += 1; - root_size += item.size_estimate(tcx); + root_size += data.size_estimate; } InstantiationMode::LocalCopy => { + if inlined_items.insert(item) { + unique_inlined_items += 1; + unique_inlined_size += data.size_estimate; + } placed_inlined_items += 1; - placed_inlined_size += item.size_estimate(tcx); + placed_inlined_size += data.size_estimate; } } } @@ -928,7 +923,7 @@ fn debug_dump<'a, 'tcx: 'a>( let mean_size = size as f64 / num_items as f64; let mut placed_item_sizes: Vec<_> = - cgu.items().iter().map(|(item, _)| item.size_estimate(tcx)).collect(); + cgu.items().values().map(|data| data.size_estimate).collect(); placed_item_sizes.sort_unstable_by_key(|&n| cmp::Reverse(n)); let sizes = list(&placed_item_sizes); @@ -937,15 +932,16 @@ fn debug_dump<'a, 'tcx: 'a>( let _ = writeln!(s, " - items: {num_items}, mean size: {mean_size:.1}, sizes: {sizes}",); - for (item, linkage) in cgu.items_in_deterministic_order(tcx) { + for (item, data) in cgu.items_in_deterministic_order(tcx) { + let linkage = data.linkage; let symbol_name = item.symbol_name(tcx).name; let symbol_hash_start = symbol_name.rfind('h'); let symbol_hash = symbol_hash_start.map_or("<no hash>", |i| &symbol_name[i..]); - let size = item.size_estimate(tcx); let kind = match item.instantiation_mode(tcx) { InstantiationMode::GloballyShared { .. } => "root", InstantiationMode::LocalCopy => "inlined", }; + let size = data.size_estimate; let _ = with_no_trimmed_paths!(writeln!( s, " - {item} [{linkage:?}] [{symbol_hash}] ({kind}, size: {size})" @@ -1100,8 +1096,8 @@ fn collect_and_partition_mono_items(tcx: TyCtxt<'_>, (): ()) -> (&DefIdSet, &[Co let mut item_to_cgus: FxHashMap<_, Vec<_>> = Default::default(); for cgu in codegen_units { - for (&mono_item, &linkage) in cgu.items() { - item_to_cgus.entry(mono_item).or_default().push((cgu.name(), linkage)); + for (&mono_item, &data) in cgu.items() { + item_to_cgus.entry(mono_item).or_default().push((cgu.name(), data.linkage)); } } @@ -1114,7 +1110,7 @@ fn collect_and_partition_mono_items(tcx: TyCtxt<'_>, (): ()) -> (&DefIdSet, &[Co let cgus = item_to_cgus.get_mut(i).unwrap_or(&mut empty); cgus.sort_by_key(|(name, _)| *name); cgus.dedup(); - for &(ref cgu_name, (linkage, _)) in cgus.iter() { + for &(ref cgu_name, linkage) in cgus.iter() { output.push(' '); output.push_str(cgu_name.as_str()); diff --git a/compiler/rustc_monomorphize/src/polymorphize.rs b/compiler/rustc_monomorphize/src/polymorphize.rs index aa2ce65e4cc..d31bf2072b1 100644 --- a/compiler/rustc_monomorphize/src/polymorphize.rs +++ b/compiler/rustc_monomorphize/src/polymorphize.rs @@ -14,9 +14,8 @@ use rustc_middle::mir::{ use rustc_middle::query::Providers; use rustc_middle::ty::{ self, - subst::SubstsRef, visit::{TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor}, - Const, Ty, TyCtxt, UnusedGenericParams, + Const, GenericArgsRef, Ty, TyCtxt, UnusedGenericParams, }; use rustc_span::symbol::sym; use std::ops::ControlFlow; @@ -229,12 +228,12 @@ struct MarkUsedGenericParams<'a, 'tcx> { impl<'a, 'tcx> MarkUsedGenericParams<'a, 'tcx> { /// Invoke `unused_generic_params` on a body contained within the current item (e.g. /// a closure, generator or constant). - #[instrument(level = "debug", skip(self, def_id, substs))] - fn visit_child_body(&mut self, def_id: DefId, substs: SubstsRef<'tcx>) { + #[instrument(level = "debug", skip(self, def_id, args))] + fn visit_child_body(&mut self, def_id: DefId, args: GenericArgsRef<'tcx>) { let instance = ty::InstanceDef::Item(def_id); let unused = self.tcx.unused_generic_params(instance); debug!(?self.unused_parameters, ?unused); - for (i, arg) in substs.iter().enumerate() { + for (i, arg) in args.iter().enumerate() { let i = i.try_into().unwrap(); if unused.is_used(i) { arg.visit_with(self); @@ -252,9 +251,9 @@ impl<'a, 'tcx> Visitor<'tcx> for MarkUsedGenericParams<'a, 'tcx> { if matches!(def_kind, DefKind::Closure | DefKind::Generator) { // Skip visiting the closure/generator that is currently being processed. This only // happens because the first argument to the closure is a reference to itself and - // that will call `visit_substs`, resulting in each generic parameter captured being + // that will call `visit_args`, resulting in each generic parameter captured being // considered used by default. - debug!("skipping closure substs"); + debug!("skipping closure args"); return; } } @@ -267,12 +266,12 @@ impl<'a, 'tcx> Visitor<'tcx> for MarkUsedGenericParams<'a, 'tcx> { ConstantKind::Ty(c) => { c.visit_with(self); } - ConstantKind::Unevaluated(mir::UnevaluatedConst { def, substs: _, promoted }, ty) => { + ConstantKind::Unevaluated(mir::UnevaluatedConst { def, args: _, promoted }, ty) => { // Avoid considering `T` unused when constants are of the form: // `<Self as Foo<T>>::foo::promoted[p]` if let Some(p) = promoted { if self.def_id == def && !self.tcx.generics_of(def).has_self { - // If there is a promoted, don't look at the substs - since it will always contain + // If there is a promoted, don't look at the args - since it will always contain // the generic parameters, instead, traverse the promoted MIR. let promoted = self.tcx.promoted_mir(def); self.visit_body(&promoted[p]); @@ -303,10 +302,10 @@ impl<'a, 'tcx> TypeVisitor<TyCtxt<'tcx>> for MarkUsedGenericParams<'a, 'tcx> { self.unused_parameters.mark_used(param.index); ControlFlow::Continue(()) } - ty::ConstKind::Unevaluated(ty::UnevaluatedConst { def, substs }) + ty::ConstKind::Unevaluated(ty::UnevaluatedConst { def, args }) if matches!(self.tcx.def_kind(def), DefKind::AnonConst) => { - self.visit_child_body(def, substs); + self.visit_child_body(def, args); ControlFlow::Continue(()) } _ => c.super_visit_with(self), @@ -320,7 +319,7 @@ impl<'a, 'tcx> TypeVisitor<TyCtxt<'tcx>> for MarkUsedGenericParams<'a, 'tcx> { } match *ty.kind() { - ty::Closure(def_id, substs) | ty::Generator(def_id, substs, ..) => { + ty::Closure(def_id, args) | ty::Generator(def_id, args, ..) => { debug!(?def_id); // Avoid cycle errors with generators. if def_id == self.def_id { @@ -329,7 +328,7 @@ impl<'a, 'tcx> TypeVisitor<TyCtxt<'tcx>> for MarkUsedGenericParams<'a, 'tcx> { // Consider any generic parameters used by any closures/generators as used in the // parent. - self.visit_child_body(def_id, substs); + self.visit_child_body(def_id, args); ControlFlow::Continue(()) } ty::Param(param) => { diff --git a/compiler/rustc_monomorphize/src/util.rs b/compiler/rustc_monomorphize/src/util.rs index f6a80b0431f..a3433d3d13d 100644 --- a/compiler/rustc_monomorphize/src/util.rs +++ b/compiler/rustc_monomorphize/src/util.rs @@ -27,12 +27,12 @@ pub(crate) fn dump_closure_profile<'tcx>(tcx: TyCtxt<'tcx>, closure_instance: In typeck_results.closure_size_eval[&closure_def_id]; let before_feature_tys = tcx.subst_and_normalize_erasing_regions( - closure_instance.substs, + closure_instance.args, param_env, ty::EarlyBinder::bind(before_feature_tys), ); let after_feature_tys = tcx.subst_and_normalize_erasing_regions( - closure_instance.substs, + closure_instance.args, param_env, ty::EarlyBinder::bind(after_feature_tys), ); diff --git a/compiler/rustc_parse/src/parser/diagnostics.rs b/compiler/rustc_parse/src/parser/diagnostics.rs index 0ce6a570d25..8455803ad0c 100644 --- a/compiler/rustc_parse/src/parser/diagnostics.rs +++ b/compiler/rustc_parse/src/parser/diagnostics.rs @@ -1434,8 +1434,9 @@ impl<'a> Parser<'a> { self.inc_dec_standalone_suggest(kind, spans).emit_verbose(&mut err) } IsStandalone::Subexpr => { - let Ok(base_src) = self.span_to_snippet(base.span) - else { return help_base_case(err, base) }; + let Ok(base_src) = self.span_to_snippet(base.span) else { + return help_base_case(err, base); + }; match kind.fixity { UnaryFixity::Pre => { self.prefix_inc_dec_suggest(base_src, kind, spans).emit(&mut err) diff --git a/compiler/rustc_parse/src/parser/mod.rs b/compiler/rustc_parse/src/parser/mod.rs index c23420661fa..e4d843b7c8b 100644 --- a/compiler/rustc_parse/src/parser/mod.rs +++ b/compiler/rustc_parse/src/parser/mod.rs @@ -1289,7 +1289,9 @@ impl<'a> Parser<'a> { delimited.then(|| { // We've confirmed above that there is a delimiter so unwrapping is OK. - let TokenTree::Delimited(dspan, delim, tokens) = self.parse_token_tree() else { unreachable!() }; + let TokenTree::Delimited(dspan, delim, tokens) = self.parse_token_tree() else { + unreachable!() + }; DelimArgs { dspan, delim: MacDelimiter::from_token(delim).unwrap(), tokens } }) diff --git a/compiler/rustc_passes/messages.ftl b/compiler/rustc_passes/messages.ftl index a607e483c97..0aa3d6265dc 100644 --- a/compiler/rustc_passes/messages.ftl +++ b/compiler/rustc_passes/messages.ftl @@ -98,6 +98,9 @@ passes_collapse_debuginfo = `collapse_debuginfo` attribute should be applied to macro definitions .label = not a macro definition +passes_confusables = attribute should be applied to an inherent method + .label = not an inherent method + passes_const_impl_const_trait = const `impl`s must be for traits marked with `#[const_trait]` .note = this trait must be annotated with `#[const_trait]` @@ -266,6 +269,9 @@ passes_duplicate_lang_item_crate_depends = .first_definition_path = first definition in `{$orig_crate_name}` loaded from {$orig_path} .second_definition_path = second definition in `{$crate_name}` loaded from {$path} +passes_empty_confusables = + expected at least one confusable name + passes_export_name = attribute should be applied to a free function, impl method or static .label = not a free function, impl method or static @@ -326,6 +332,9 @@ passes_implied_feature_not_exist = passes_incorrect_do_not_recommend_location = `#[do_not_recommend]` can only be placed on trait implementations +passes_incorrect_meta_item = expected a quoted string literal +passes_incorrect_meta_item_suggestion = consider surrounding this with quotes + passes_incorrect_target = `{$name}` language item must be applied to a {$kind} with {$at_least -> [true] at least {$num} diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index f48900c3c52..4d7ebe3fefe 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -183,6 +183,7 @@ impl CheckAttrVisitor<'_> { | sym::rustc_allowed_through_unstable_modules | sym::rustc_promotable => self.check_stability_promotable(&attr, span, target), sym::link_ordinal => self.check_link_ordinal(&attr, span, target), + sym::rustc_confusables => self.check_confusables(&attr, target), _ => true, }; @@ -1432,9 +1433,9 @@ impl CheckAttrVisitor<'_> { }; let Some(ItemLike::Item(Item { - kind: ItemKind::Fn(FnSig { decl, .. }, generics, _), - .. - })) = item else { + kind: ItemKind::Fn(FnSig { decl, .. }, generics, _), .. + })) = item + else { bug!("should be a function item"); }; @@ -1985,6 +1986,46 @@ impl CheckAttrVisitor<'_> { } } + fn check_confusables(&self, attr: &Attribute, target: Target) -> bool { + match target { + Target::Method(MethodKind::Inherent) => { + let Some(meta) = attr.meta() else { + return false; + }; + let ast::MetaItem { kind: MetaItemKind::List(ref metas), .. } = meta else { + return false; + }; + + let mut candidates = Vec::new(); + + for meta in metas { + let NestedMetaItem::Lit(meta_lit) = meta else { + self.tcx.sess.emit_err(errors::IncorrectMetaItem { + span: meta.span(), + suggestion: errors::IncorrectMetaItemSuggestion { + lo: meta.span().shrink_to_lo(), + hi: meta.span().shrink_to_hi(), + }, + }); + return false; + }; + candidates.push(meta_lit.symbol); + } + + if candidates.is_empty() { + self.tcx.sess.emit_err(errors::EmptyConfusables { span: attr.span }); + return false; + } + + true + } + _ => { + self.tcx.sess.emit_err(errors::Confusables { attr_span: attr.span }); + false + } + } + } + fn check_deprecated(&self, hir_id: HirId, attr: &Attribute, _span: Span, target: Target) { match target { Target::Closure | Target::Expression | Target::Statement | Target::Arm => { @@ -2106,8 +2147,12 @@ impl CheckAttrVisitor<'_> { } let tcx = self.tcx; - let Some(token_stream_def_id) = tcx.get_diagnostic_item(sym::TokenStream) else { return; }; - let Some(token_stream) = tcx.type_of(token_stream_def_id).no_bound_vars() else { return; }; + let Some(token_stream_def_id) = tcx.get_diagnostic_item(sym::TokenStream) else { + return; + }; + let Some(token_stream) = tcx.type_of(token_stream_def_id).no_bound_vars() else { + return; + }; let def_id = hir_id.expect_owner().def_id; let param_env = ty::ParamEnv::empty(); @@ -2116,10 +2161,10 @@ impl CheckAttrVisitor<'_> { let ocx = ObligationCtxt::new(&infcx); let span = tcx.def_span(def_id); - let fresh_substs = infcx.fresh_substs_for_item(span, def_id.to_def_id()); + let fresh_args = infcx.fresh_args_for_item(span, def_id.to_def_id()); let sig = tcx.liberate_late_bound_regions( def_id.to_def_id(), - tcx.fn_sig(def_id).subst(tcx, fresh_substs), + tcx.fn_sig(def_id).instantiate(tcx, fresh_args), ); let mut cause = ObligationCause::misc(span, def_id); diff --git a/compiler/rustc_passes/src/dead.rs b/compiler/rustc_passes/src/dead.rs index d5ac1cd9ce3..fbe6fc3bee4 100644 --- a/compiler/rustc_passes/src/dead.rs +++ b/compiler/rustc_passes/src/dead.rs @@ -276,7 +276,7 @@ impl<'tcx> MarkSymbolVisitor<'tcx> { } // Avoid accessing the HIR for the synthesized associated type generated for RPITITs. - if self.tcx.opt_rpitit_info(id.to_def_id()).is_some() { + if self.tcx.is_impl_trait_in_trait(id.to_def_id()) { self.live_symbols.insert(id); continue; } @@ -304,7 +304,7 @@ impl<'tcx> MarkSymbolVisitor<'tcx> { if let Some(trait_of) = self.tcx.trait_id_of_impl(impl_of) && self.tcx.has_attr(trait_of, sym::rustc_trivial_field_reads) { - let trait_ref = self.tcx.impl_trait_ref(impl_of).unwrap().subst_identity(); + let trait_ref = self.tcx.impl_trait_ref(impl_of).unwrap().instantiate_identity(); if let ty::Adt(adt_def, _) = trait_ref.self_ty().kind() && let Some(adt_def_id) = adt_def.did().as_local() { @@ -353,7 +353,7 @@ impl<'tcx> MarkSymbolVisitor<'tcx> { //// This is done to handle the case where, for example, the static //// method of a private type is used, but the type itself is never //// called directly. - let self_ty = self.tcx.type_of(item).subst_identity(); + let self_ty = self.tcx.type_of(item).instantiate_identity(); match *self_ty.kind() { ty::Adt(def, _) => self.check_def_id(def.did()), ty::Foreign(did) => self.check_def_id(did), @@ -707,7 +707,7 @@ impl<'tcx> DeadVisitor<'tcx> { if self.live_symbols.contains(&field.did.expect_local()) { return ShouldWarnAboutField::No; } - let field_type = self.tcx.type_of(field.did).subst_identity(); + let field_type = self.tcx.type_of(field.did).instantiate_identity(); if field_type.is_phantom_data() { return ShouldWarnAboutField::No; } diff --git a/compiler/rustc_passes/src/errors.rs b/compiler/rustc_passes/src/errors.rs index 3fe7feb9dfa..eae13f86049 100644 --- a/compiler/rustc_passes/src/errors.rs +++ b/compiler/rustc_passes/src/errors.rs @@ -618,6 +618,38 @@ pub struct LinkOrdinal { } #[derive(Diagnostic)] +#[diag(passes_confusables)] +pub struct Confusables { + #[primary_span] + pub attr_span: Span, +} + +#[derive(Diagnostic)] +#[diag(passes_empty_confusables)] +pub(crate) struct EmptyConfusables { + #[primary_span] + pub span: Span, +} + +#[derive(Diagnostic)] +#[diag(passes_incorrect_meta_item, code = "E0539")] +pub(crate) struct IncorrectMetaItem { + #[primary_span] + pub span: Span, + #[subdiagnostic] + pub suggestion: IncorrectMetaItemSuggestion, +} + +#[derive(Subdiagnostic)] +#[multipart_suggestion(passes_incorrect_meta_item_suggestion, applicability = "maybe-incorrect")] +pub(crate) struct IncorrectMetaItemSuggestion { + #[suggestion_part(code = "\"")] + pub lo: Span, + #[suggestion_part(code = "\"")] + pub hi: Span, +} + +#[derive(Diagnostic)] #[diag(passes_stability_promotable)] pub struct StabilityPromotable { #[primary_span] diff --git a/compiler/rustc_passes/src/layout_test.rs b/compiler/rustc_passes/src/layout_test.rs index 098107f8f23..794dbda3688 100644 --- a/compiler/rustc_passes/src/layout_test.rs +++ b/compiler/rustc_passes/src/layout_test.rs @@ -29,7 +29,7 @@ pub fn test_layout(tcx: TyCtxt<'_>) { fn dump_layout_of(tcx: TyCtxt<'_>, item_def_id: LocalDefId, attr: &Attribute) { let tcx = tcx; let param_env = tcx.param_env(item_def_id); - let ty = tcx.type_of(item_def_id).subst_identity(); + let ty = tcx.type_of(item_def_id).instantiate_identity(); match tcx.layout_of(param_env.and(ty)) { Ok(ty_layout) => { // Check out the `#[rustc_layout(..)]` attribute to tell what to dump. diff --git a/compiler/rustc_passes/src/liveness.rs b/compiler/rustc_passes/src/liveness.rs index 803ca05b202..89c6704e416 100644 --- a/compiler/rustc_passes/src/liveness.rs +++ b/compiler/rustc_passes/src/liveness.rs @@ -747,7 +747,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { let ty = self.typeck_results.node_type(hir_id); match ty.kind() { - ty::Closure(_def_id, substs) => match substs.as_closure().kind() { + ty::Closure(_def_id, args) => match args.as_closure().kind() { ty::ClosureKind::Fn => {} ty::ClosureKind::FnMut => {} ty::ClosureKind::FnOnce => return succ, @@ -1683,12 +1683,16 @@ impl<'tcx> Liveness<'_, 'tcx> { opt_body: Option<&hir::Body<'_>>, ) -> Vec<errors::UnusedVariableStringInterp> { let mut suggs = Vec::new(); - let Some(opt_body) = opt_body else { return suggs; }; + let Some(opt_body) = opt_body else { + return suggs; + }; let mut visitor = CollectLitsVisitor { lit_exprs: vec![] }; intravisit::walk_body(&mut visitor, opt_body); for lit_expr in visitor.lit_exprs { let hir::ExprKind::Lit(litx) = &lit_expr.kind else { continue }; - let rustc_ast::LitKind::Str(syb, _) = litx.node else{ continue; }; + let rustc_ast::LitKind::Str(syb, _) = litx.node else { + continue; + }; let name_str: &str = syb.as_str(); let name_pa = format!("{{{name}}}"); if name_str.contains(&name_pa) { diff --git a/compiler/rustc_passes/src/stability.rs b/compiler/rustc_passes/src/stability.rs index b81b7ad6013..25a3d38c144 100644 --- a/compiler/rustc_passes/src/stability.rs +++ b/compiler/rustc_passes/src/stability.rs @@ -856,7 +856,9 @@ impl<'tcx> Visitor<'tcx> for Checker<'tcx> { /// See issue #94972 for details on why this is a special case fn is_unstable_reexport(tcx: TyCtxt<'_>, id: hir::HirId) -> bool { // Get the LocalDefId so we can lookup the item to check the kind. - let Some(owner) = id.as_owner() else { return false; }; + let Some(owner) = id.as_owner() else { + return false; + }; let def_id = owner.def_id; let Some(stab) = tcx.stability().local_stability(def_id) else { diff --git a/compiler/rustc_privacy/src/lib.rs b/compiler/rustc_privacy/src/lib.rs index fe23506b878..e2827252509 100644 --- a/compiler/rustc_privacy/src/lib.rs +++ b/compiler/rustc_privacy/src/lib.rs @@ -28,7 +28,7 @@ use rustc_middle::hir::nested_filter; use rustc_middle::middle::privacy::{EffectiveVisibilities, EffectiveVisibility, Level}; use rustc_middle::query::Providers; use rustc_middle::span_bug; -use rustc_middle::ty::subst::InternalSubsts; +use rustc_middle::ty::GenericArgs; use rustc_middle::ty::{self, Const, GenericParamDefKind}; use rustc_middle::ty::{TraitRef, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitor}; use rustc_session::lint; @@ -129,19 +129,19 @@ where V: DefIdVisitor<'tcx> + ?Sized, { fn visit_trait(&mut self, trait_ref: TraitRef<'tcx>) -> ControlFlow<V::BreakTy> { - let TraitRef { def_id, substs, .. } = trait_ref; + let TraitRef { def_id, args, .. } = trait_ref; self.def_id_visitor.visit_def_id(def_id, "trait", &trait_ref.print_only_trait_path())?; - if V::SHALLOW { ControlFlow::Continue(()) } else { substs.visit_with(self) } + if V::SHALLOW { ControlFlow::Continue(()) } else { args.visit_with(self) } } fn visit_projection_ty(&mut self, projection: ty::AliasTy<'tcx>) -> ControlFlow<V::BreakTy> { let tcx = self.def_id_visitor.tcx(); - let (trait_ref, assoc_substs) = projection.trait_ref_and_own_substs(tcx); + let (trait_ref, assoc_args) = projection.trait_ref_and_own_args(tcx); self.visit_trait(trait_ref)?; if V::SHALLOW { ControlFlow::Continue(()) } else { - assoc_substs.iter().try_for_each(|subst| subst.visit_with(self)) + assoc_args.iter().try_for_each(|subst| subst.visit_with(self)) } } @@ -178,7 +178,7 @@ where fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<V::BreakTy> { let tcx = self.def_id_visitor.tcx(); - // InternalSubsts are not visited here because they are visited below + // GenericArgs are not visited here because they are visited below // in `super_visit_with`. match *ty.kind() { ty::Adt(ty::AdtDef(Interned(&ty::AdtDefData { did: def_id, .. }, _)), ..) @@ -194,16 +194,16 @@ where // Something like `fn() -> Priv {my_func}` is considered a private type even if // `my_func` is public, so we need to visit signatures. if let ty::FnDef(..) = ty.kind() { - // FIXME: this should probably use `substs` from `FnDef` - tcx.fn_sig(def_id).subst_identity().visit_with(self)?; + // FIXME: this should probably use `args` from `FnDef` + tcx.fn_sig(def_id).instantiate_identity().visit_with(self)?; } - // Inherent static methods don't have self type in substs. + // Inherent static methods don't have self type in args. // Something like `fn() {my_method}` type of the method // `impl Pub<Priv> { pub fn my_method() {} }` is considered a private type, // so we need to visit the self type additionally. if let Some(assoc_item) = tcx.opt_associated_item(def_id) { if let Some(impl_def_id) = assoc_item.impl_container(tcx) { - tcx.type_of(impl_def_id).subst_identity().visit_with(self)?; + tcx.type_of(impl_def_id).instantiate_identity().visit_with(self)?; } } } @@ -219,7 +219,7 @@ where // free type aliases, but this isn't done yet. return ControlFlow::Continue(()); } - // This will also visit substs if necessary, so we don't need to recurse. + // This will also visit args if necessary, so we don't need to recurse. return self.visit_projection_ty(proj); } ty::Alias(ty::Inherent, data) => { @@ -238,11 +238,11 @@ where &LazyDefPathStr { def_id: data.def_id, tcx }, )?; - // This will also visit substs if necessary, so we don't need to recurse. + // This will also visit args if necessary, so we don't need to recurse. return if V::SHALLOW { ControlFlow::Continue(()) } else { - data.substs.iter().try_for_each(|subst| subst.visit_with(self)) + data.args.iter().try_for_each(|subst| subst.visit_with(self)) }; } ty::Dynamic(predicates, ..) => { @@ -253,10 +253,10 @@ where ty::ExistentialPredicate::Trait(trait_ref) => trait_ref, ty::ExistentialPredicate::Projection(proj) => proj.trait_ref(tcx), ty::ExistentialPredicate::AutoTrait(def_id) => { - ty::ExistentialTraitRef { def_id, substs: InternalSubsts::empty() } + ty::ExistentialTraitRef { def_id, args: GenericArgs::empty() } } }; - let ty::ExistentialTraitRef { def_id, substs: _ } = trait_ref; + let ty::ExistentialTraitRef { def_id, args: _ } = trait_ref; self.def_id_visitor.visit_def_id(def_id, "trait", &trait_ref)?; } } @@ -357,9 +357,9 @@ trait VisibilityLike: Sized { effective_visibilities: &EffectiveVisibilities, ) -> Self { let mut find = FindMin::<_, SHALLOW> { tcx, effective_visibilities, min: Self::MAX }; - find.visit(tcx.type_of(def_id).subst_identity()); + find.visit(tcx.type_of(def_id).instantiate_identity()); if let Some(trait_ref) = tcx.impl_trait_ref(def_id) { - find.visit_trait(trait_ref.subst_identity()); + find.visit_trait(trait_ref.instantiate_identity()); } find.min } @@ -727,7 +727,7 @@ impl<'tcx> Visitor<'tcx> for EmbargoVisitor<'tcx> { // Type inference is very smart sometimes. It can make an impl reachable even some // components of its type or trait are unreachable. E.g. methods of // `impl ReachableTrait<UnreachableTy> for ReachableTy<UnreachableTy> { ... }` - // can be usable from other crates (#57264). So we skip substs when calculating + // can be usable from other crates (#57264). So we skip args when calculating // reachability and consider an impl reachable if its "shallow" type and trait are // reachable. // @@ -823,13 +823,15 @@ impl ReachEverythingInTheInterfaceVisitor<'_, '_> { GenericParamDefKind::Lifetime => {} GenericParamDefKind::Type { has_default, .. } => { if has_default { - self.visit(self.ev.tcx.type_of(param.def_id).subst_identity()); + self.visit(self.ev.tcx.type_of(param.def_id).instantiate_identity()); } } GenericParamDefKind::Const { has_default } => { - self.visit(self.ev.tcx.type_of(param.def_id).subst_identity()); + self.visit(self.ev.tcx.type_of(param.def_id).instantiate_identity()); if has_default { - self.visit(self.ev.tcx.const_param_default(param.def_id).subst_identity()); + self.visit( + self.ev.tcx.const_param_default(param.def_id).instantiate_identity(), + ); } } } @@ -843,13 +845,13 @@ impl ReachEverythingInTheInterfaceVisitor<'_, '_> { } fn ty(&mut self) -> &mut Self { - self.visit(self.ev.tcx.type_of(self.item_def_id).subst_identity()); + self.visit(self.ev.tcx.type_of(self.item_def_id).instantiate_identity()); self } fn trait_ref(&mut self) -> &mut Self { if let Some(trait_ref) = self.ev.tcx.impl_trait_ref(self.item_def_id) { - self.visit_trait(trait_ref.subst_identity()); + self.visit_trait(trait_ref.instantiate_identity()); } self } @@ -1124,7 +1126,7 @@ impl<'tcx> TypePrivacyVisitor<'tcx> { let typeck_results = self.typeck_results(); let result: ControlFlow<()> = try { self.visit(typeck_results.node_type(id))?; - self.visit(typeck_results.node_substs(id))?; + self.visit(typeck_results.node_args(id))?; if let Some(adjustments) = typeck_results.adjustments().get(id) { adjustments.iter().try_for_each(|adjustment| self.visit(adjustment.target))?; } @@ -1259,7 +1261,7 @@ impl<'tcx> Visitor<'tcx> for TypePrivacyVisitor<'tcx> { // Method calls have to be checked specially. self.span = segment.ident.span; if let Some(def_id) = self.typeck_results().type_dependent_def_id(expr.hir_id) { - if self.visit(self.tcx.type_of(def_id).subst_identity()).is_break() { + if self.visit(self.tcx.type_of(def_id).instantiate_identity()).is_break() { return; } } else { @@ -1736,12 +1738,12 @@ impl SearchInterfaceForPrivateItemsVisitor<'_> { GenericParamDefKind::Lifetime => {} GenericParamDefKind::Type { has_default, .. } => { if has_default { - self.visit(self.tcx.type_of(param.def_id).subst_identity()); + self.visit(self.tcx.type_of(param.def_id).instantiate_identity()); } } // FIXME(generic_const_exprs): May want to look inside const here GenericParamDefKind::Const { .. } => { - self.visit(self.tcx.type_of(param.def_id).subst_identity()); + self.visit(self.tcx.type_of(param.def_id).instantiate_identity()); } } } @@ -1768,7 +1770,7 @@ impl SearchInterfaceForPrivateItemsVisitor<'_> { fn ty(&mut self) -> &mut Self { self.in_primary_interface = true; - self.visit(self.tcx.type_of(self.item_def_id).subst_identity()); + self.visit(self.tcx.type_of(self.item_def_id).instantiate_identity()); self } diff --git a/compiler/rustc_resolve/src/imports.rs b/compiler/rustc_resolve/src/imports.rs index d37fe783bba..526fc9c3aa5 100644 --- a/compiler/rustc_resolve/src/imports.rs +++ b/compiler/rustc_resolve/src/imports.rs @@ -1300,9 +1300,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { let ImportKind::Glob { id, is_prelude, .. } = import.kind else { unreachable!() }; let ModuleOrUniformRoot::Module(module) = import.imported_module.get().unwrap() else { - self.tcx.sess.create_err(CannotGlobImportAllCrates { - span: import.span, - }).emit(); + self.tcx.sess.create_err(CannotGlobImportAllCrates { span: import.span }).emit(); return; }; diff --git a/compiler/rustc_resolve/src/late.rs b/compiler/rustc_resolve/src/late.rs index f6c7aecf8b0..846a1ffe09b 100644 --- a/compiler/rustc_resolve/src/late.rs +++ b/compiler/rustc_resolve/src/late.rs @@ -1361,7 +1361,7 @@ impl<'a: 'ast, 'b, 'ast, 'tcx> LateResolutionVisitor<'a, 'b, 'ast, 'tcx> { fn visit_generic_params(&mut self, params: &'ast [GenericParam], add_self_upper: bool) { // For type parameter defaults, we have to ban access - // to following type parameters, as the InternalSubsts can only + // to following type parameters, as the GenericArgs can only // provide previous type parameters as they're built. We // put all the parameters on the ban list and then remove // them one by one as they are processed and become available. @@ -2460,8 +2460,11 @@ impl<'a: 'ast, 'b, 'ast, 'tcx> LateResolutionVisitor<'a, 'b, 'ast, 'tcx> { F: FnOnce(&mut Self), { debug!("with_generic_param_rib"); - let LifetimeRibKind::Generics { binder, span: generics_span, kind: generics_kind, .. } - = lifetime_kind else { panic!() }; + let LifetimeRibKind::Generics { binder, span: generics_span, kind: generics_kind, .. } = + lifetime_kind + else { + panic!() + }; let mut function_type_rib = Rib::new(kind); let mut function_value_rib = Rib::new(kind); @@ -2972,7 +2975,9 @@ impl<'a: 'ast, 'b, 'ast, 'tcx> LateResolutionVisitor<'a, 'b, 'ast, 'tcx> { F: FnOnce(Ident, String, Option<Symbol>) -> ResolutionError<'a>, { // If there is a TraitRef in scope for an impl, then the method must be in the trait. - let Some((module, _)) = self.current_trait_ref else { return; }; + let Some((module, _)) = self.current_trait_ref else { + return; + }; ident.span.normalize_to_macros_2_0_and_adjust(module.expansion); let key = BindingKey::new(ident, ns); let mut binding = self.r.resolution(module, key).try_borrow().ok().and_then(|r| r.binding); @@ -3917,11 +3922,15 @@ impl<'a: 'ast, 'b, 'ast, 'tcx> LateResolutionVisitor<'a, 'b, 'ast, 'tcx> { }; if res == unqualified_result { let lint = lint::builtin::UNUSED_QUALIFICATIONS; - self.r.lint_buffer.buffer_lint( + self.r.lint_buffer.buffer_lint_with_diagnostic( lint, finalize.node_id, finalize.path_span, "unnecessary qualification", + lint::BuiltinLintDiagnostics::UnusedQualifications { + path_span: finalize.path_span, + unqualified_path: path.last().unwrap().ident + } ) } } diff --git a/compiler/rustc_resolve/src/late/diagnostics.rs b/compiler/rustc_resolve/src/late/diagnostics.rs index 78ef72a7e34..753a1adc66d 100644 --- a/compiler/rustc_resolve/src/late/diagnostics.rs +++ b/compiler/rustc_resolve/src/late/diagnostics.rs @@ -446,20 +446,29 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> { err: &mut Diagnostic, base_error: &BaseError, ) { - let Some(ty) = self.diagnostic_metadata.current_type_path else { return; }; - let TyKind::Path(_, path) = &ty.kind else { return; }; + let Some(ty) = self.diagnostic_metadata.current_type_path else { + return; + }; + let TyKind::Path(_, path) = &ty.kind else { + return; + }; for segment in &path.segments { - let Some(params) = &segment.args else { continue; }; - let ast::GenericArgs::AngleBracketed(ref params) = params.deref() else { continue; }; + let Some(params) = &segment.args else { + continue; + }; + let ast::GenericArgs::AngleBracketed(ref params) = params.deref() else { + continue; + }; for param in ¶ms.args { - let ast::AngleBracketedArg::Constraint(constraint) = param else { continue; }; + let ast::AngleBracketedArg::Constraint(constraint) = param else { + continue; + }; let ast::AssocConstraintKind::Bound { bounds } = &constraint.kind else { continue; }; for bound in bounds { - let ast::GenericBound::Trait(trait_ref, ast::TraitBoundModifier::None) - = bound else - { + let ast::GenericBound::Trait(trait_ref, ast::TraitBoundModifier::None) = bound + else { continue; }; if base_error.span == trait_ref.span { @@ -1148,7 +1157,11 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> { &poly_trait_ref.trait_ref.path.segments[..] { if ident.span == span { - let Some(new_where_bound_predicate) = mk_where_bound_predicate(path, poly_trait_ref, ty) else { return false; }; + let Some(new_where_bound_predicate) = + mk_where_bound_predicate(path, poly_trait_ref, ty) + else { + return false; + }; err.span_suggestion_verbose( *where_span, format!("constrain the associated type to `{}`", ident), @@ -1831,7 +1844,8 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> { None, ) { Some(found) => { - let Some(sugg) = names.into_iter().find(|suggestion| suggestion.candidate == found) else { + let Some(sugg) = names.into_iter().find(|suggestion| suggestion.candidate == found) + else { return TypoCandidate::None; }; if found == name { @@ -2677,7 +2691,9 @@ fn mk_where_bound_predicate( use rustc_span::DUMMY_SP; let modified_segments = { let mut segments = path.segments.clone(); - let [preceding @ .., second_last, last] = segments.as_mut_slice() else { return None; }; + let [preceding @ .., second_last, last] = segments.as_mut_slice() else { + return None; + }; let mut segments = ThinVec::from(preceding); let added_constraint = ast::AngleBracketedArg::Constraint(ast::AssocConstraint { diff --git a/compiler/rustc_resolve/src/lib.rs b/compiler/rustc_resolve/src/lib.rs index da3d86a4718..faa672db59c 100644 --- a/compiler/rustc_resolve/src/lib.rs +++ b/compiler/rustc_resolve/src/lib.rs @@ -1871,7 +1871,10 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { } else { let crate_id = if finalize { let Some(crate_id) = - self.crate_loader(|c| c.process_path_extern(ident.name, ident.span)) else { return Some(self.dummy_binding); }; + self.crate_loader(|c| c.process_path_extern(ident.name, ident.span)) + else { + return Some(self.dummy_binding); + }; crate_id } else { self.crate_loader(|c| c.maybe_process_path_extern(ident.name))? diff --git a/compiler/rustc_smir/Cargo.toml b/compiler/rustc_smir/Cargo.toml index a6e6de5f785..80d4e7ed02f 100644 --- a/compiler/rustc_smir/Cargo.toml +++ b/compiler/rustc_smir/Cargo.toml @@ -4,14 +4,18 @@ version = "0.0.0" edition = "2021" [dependencies] -rustc_hir = { path = "../rustc_hir" } +# Use optional dependencies for rustc_* in order to support building this crate separately. +rustc_hir = { path = "../rustc_hir", optional = true } rustc_middle = { path = "../rustc_middle", optional = true } rustc_span = { path = "../rustc_span", optional = true } +rustc_target = { path = "../rustc_target", optional = true } tracing = "0.1" scoped-tls = "1.0" [features] default = [ + "rustc_hir", "rustc_middle", "rustc_span", + "rustc_target", ] diff --git a/compiler/rustc_smir/rust-toolchain.toml b/compiler/rustc_smir/rust-toolchain.toml index 157dfd620ee..d75e8e33b1c 100644 --- a/compiler/rustc_smir/rust-toolchain.toml +++ b/compiler/rustc_smir/rust-toolchain.toml @@ -1,3 +1,3 @@ [toolchain] -channel = "nightly-2023-02-28" +channel = "nightly-2023-06-14" components = [ "rustfmt", "rustc-dev" ] diff --git a/compiler/rustc_smir/src/lib.rs b/compiler/rustc_smir/src/lib.rs index fb03633b99b..6ebba56c76d 100644 --- a/compiler/rustc_smir/src/lib.rs +++ b/compiler/rustc_smir/src/lib.rs @@ -1,6 +1,6 @@ //! The WIP stable interface to rustc internals. //! -//! For more information see https://github.com/rust-lang/project-stable-mir +//! For more information see <https://github.com/rust-lang/project-stable-mir> //! //! # Note //! @@ -13,6 +13,18 @@ #![cfg_attr(not(feature = "default"), feature(rustc_private))] #![feature(local_key_cell_methods)] #![feature(ptr_metadata)] +#![feature(type_alias_impl_trait)] // Used to define opaque types. +#![feature(intra_doc_pointers)] + +// Declare extern rustc_* crates to enable building this crate separately from the compiler. +#[cfg(not(feature = "default"))] +extern crate rustc_hir; +#[cfg(not(feature = "default"))] +extern crate rustc_middle; +#[cfg(not(feature = "default"))] +extern crate rustc_span; +#[cfg(not(feature = "default"))] +extern crate rustc_target; pub mod rustc_internal; pub mod stable_mir; diff --git a/compiler/rustc_smir/src/rustc_internal/mod.rs b/compiler/rustc_smir/src/rustc_internal/mod.rs index 609a04d263c..527d5220564 100644 --- a/compiler/rustc_smir/src/rustc_internal/mod.rs +++ b/compiler/rustc_smir/src/rustc_internal/mod.rs @@ -3,6 +3,9 @@ //! For that, we define APIs that will temporarily be public to 3P that exposes rustc internal APIs //! until stable MIR is complete. +use std::fmt::Debug; +use std::string::ToString; + use crate::{ rustc_smir::Tables, stable_mir::{self, with}, @@ -24,21 +27,33 @@ pub fn crate_item(did: DefId) -> stable_mir::CrateItem { with_tables(|t| t.crate_item(did)) } +pub fn adt_def(did: DefId) -> stable_mir::ty::AdtDef { + with_tables(|t| t.adt_def(did)) +} + impl<'tcx> Tables<'tcx> { pub fn item_def_id(&self, item: &stable_mir::CrateItem) -> DefId { self.def_ids[item.0] } pub fn crate_item(&mut self, did: DefId) -> stable_mir::CrateItem { + stable_mir::CrateItem(self.create_def_id(did)) + } + + pub fn adt_def(&mut self, did: DefId) -> stable_mir::ty::AdtDef { + stable_mir::ty::AdtDef(self.create_def_id(did)) + } + + fn create_def_id(&mut self, did: DefId) -> stable_mir::DefId { // FIXME: this becomes inefficient when we have too many ids for (i, &d) in self.def_ids.iter().enumerate() { if d == did { - return stable_mir::CrateItem(i); + return i; } } let id = self.def_ids.len(); self.def_ids.push(did); - stable_mir::CrateItem(id) + id } } @@ -49,3 +64,10 @@ pub fn crate_num(item: &stable_mir::Crate) -> CrateNum { pub fn run(tcx: TyCtxt<'_>, f: impl FnOnce()) { crate::stable_mir::run(Tables { tcx, def_ids: vec![], types: vec![] }, f); } + +/// A type that provides internal information but that can still be used for debug purpose. +pub type Opaque = impl Debug + ToString + Clone; + +pub(crate) fn opaque<T: Debug>(value: &T) -> Opaque { + format!("{value:?}") +} diff --git a/compiler/rustc_smir/src/rustc_smir/mod.rs b/compiler/rustc_smir/src/rustc_smir/mod.rs index 85d5bb00c4e..6af6cfe58f1 100644 --- a/compiler/rustc_smir/src/rustc_smir/mod.rs +++ b/compiler/rustc_smir/src/rustc_smir/mod.rs @@ -7,11 +7,13 @@ //! //! For now, we are developing everything inside `rustc`, thus, we keep this module private. -use crate::stable_mir::ty::{FloatTy, IntTy, RigidTy, TyKind, UintTy}; +use crate::rustc_internal::{self, opaque}; +use crate::stable_mir::ty::{AdtSubsts, FloatTy, GenericArgKind, IntTy, RigidTy, TyKind, UintTy}; use crate::stable_mir::{self, Context}; use rustc_middle::mir; use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_span::def_id::{CrateNum, DefId, LOCAL_CRATE}; +use rustc_target::abi::FieldIdx; use tracing::debug; impl<'tcx> Context for Tables<'tcx> { @@ -92,21 +94,38 @@ impl<'tcx> Tables<'tcx> { ty::FloatTy::F32 => TyKind::RigidTy(RigidTy::Float(FloatTy::F32)), ty::FloatTy::F64 => TyKind::RigidTy(RigidTy::Float(FloatTy::F64)), }, - ty::Adt(_, _) => todo!(), + ty::Adt(adt_def, substs) => TyKind::RigidTy(RigidTy::Adt( + rustc_internal::adt_def(adt_def.did()), + AdtSubsts( + substs + .iter() + .map(|arg| match arg.unpack() { + ty::GenericArgKind::Lifetime(region) => { + GenericArgKind::Lifetime(opaque(®ion)) + } + ty::GenericArgKind::Type(ty) => { + GenericArgKind::Type(self.intern_ty(ty)) + } + ty::GenericArgKind::Const(const_) => { + GenericArgKind::Const(opaque(&const_)) + } + }) + .collect(), + ), + )), ty::Foreign(_) => todo!(), - ty::Str => todo!(), - ty::Array(_, _) => todo!(), - ty::Slice(_) => todo!(), + ty::Str => TyKind::RigidTy(RigidTy::Str), + ty::Array(ty, constant) => { + TyKind::RigidTy(RigidTy::Array(self.intern_ty(*ty), opaque(constant))) + } + ty::Slice(ty) => TyKind::RigidTy(RigidTy::Slice(self.intern_ty(*ty))), ty::RawPtr(_) => todo!(), ty::Ref(_, _, _) => todo!(), ty::FnDef(_, _) => todo!(), ty::FnPtr(_) => todo!(), - ty::Placeholder(..) => todo!(), ty::Dynamic(_, _, _) => todo!(), ty::Closure(_, _) => todo!(), ty::Generator(_, _, _) => todo!(), - ty::GeneratorWitness(_) => todo!(), - ty::GeneratorWitnessMIR(_, _) => todo!(), ty::Never => todo!(), ty::Tuple(fields) => TyKind::RigidTy(RigidTy::Tuple( fields.iter().map(|ty| self.intern_ty(ty)).collect(), @@ -114,8 +133,13 @@ impl<'tcx> Tables<'tcx> { ty::Alias(_, _) => todo!(), ty::Param(_) => todo!(), ty::Bound(_, _) => todo!(), - ty::Infer(_) => todo!(), - ty::Error(_) => todo!(), + ty::Placeholder(..) + | ty::GeneratorWitness(_) + | ty::GeneratorWitnessMIR(_, _) + | ty::Infer(_) + | ty::Error(_) => { + unreachable!(); + } } } @@ -137,8 +161,11 @@ fn smir_crate(tcx: TyCtxt<'_>, crate_num: CrateNum) -> stable_mir::Crate { stable_mir::Crate { id: crate_num.into(), name: crate_name, is_local } } -pub trait Stable { +/// Trait used to convert between an internal MIR type to a Stable MIR type. +pub(crate) trait Stable { + /// The stable representation of the type implementing Stable. type T; + /// Converts an object to the equivalent Stable MIR representation. fn stable(&self) -> Self::T; } @@ -173,12 +200,20 @@ impl<'tcx> Stable for mir::Rvalue<'tcx> { match self { Use(op) => stable_mir::mir::Rvalue::Use(op.stable()), Repeat(_, _) => todo!(), - Ref(_, _, _) => todo!(), - ThreadLocalRef(_) => todo!(), - AddressOf(_, _) => todo!(), - Len(_) => todo!(), + Ref(region, kind, place) => { + stable_mir::mir::Rvalue::Ref(opaque(region), kind.stable(), place.stable()) + } + ThreadLocalRef(def_id) => { + stable_mir::mir::Rvalue::ThreadLocalRef(rustc_internal::crate_item(*def_id)) + } + AddressOf(mutability, place) => { + stable_mir::mir::Rvalue::AddressOf(mutability.stable(), place.stable()) + } + Len(place) => stable_mir::mir::Rvalue::Len(place.stable()), Cast(_, _, _) => todo!(), - BinaryOp(_, _) => todo!(), + BinaryOp(bin_op, ops) => { + stable_mir::mir::Rvalue::BinaryOp(bin_op.stable(), ops.0.stable(), ops.1.stable()) + } CheckedBinaryOp(bin_op, ops) => stable_mir::mir::Rvalue::CheckedBinaryOp( bin_op.stable(), ops.0.stable(), @@ -186,14 +221,119 @@ impl<'tcx> Stable for mir::Rvalue<'tcx> { ), NullaryOp(_, _) => todo!(), UnaryOp(un_op, op) => stable_mir::mir::Rvalue::UnaryOp(un_op.stable(), op.stable()), - Discriminant(_) => todo!(), + Discriminant(place) => stable_mir::mir::Rvalue::Discriminant(place.stable()), Aggregate(_, _) => todo!(), ShallowInitBox(_, _) => todo!(), - CopyForDeref(_) => todo!(), + CopyForDeref(place) => stable_mir::mir::Rvalue::CopyForDeref(place.stable()), + } + } +} + +impl Stable for mir::Mutability { + type T = stable_mir::mir::Mutability; + fn stable(&self) -> Self::T { + use mir::Mutability::*; + match *self { + Not => stable_mir::mir::Mutability::Not, + Mut => stable_mir::mir::Mutability::Mut, + } + } +} + +impl Stable for mir::BorrowKind { + type T = stable_mir::mir::BorrowKind; + fn stable(&self) -> Self::T { + use mir::BorrowKind::*; + match *self { + Shared => stable_mir::mir::BorrowKind::Shared, + Shallow => stable_mir::mir::BorrowKind::Shallow, + Mut { kind } => stable_mir::mir::BorrowKind::Mut { kind: kind.stable() }, + } + } +} + +impl Stable for mir::MutBorrowKind { + type T = stable_mir::mir::MutBorrowKind; + fn stable(&self) -> Self::T { + use mir::MutBorrowKind::*; + match *self { + Default => stable_mir::mir::MutBorrowKind::Default, + TwoPhaseBorrow => stable_mir::mir::MutBorrowKind::TwoPhaseBorrow, + ClosureCapture => stable_mir::mir::MutBorrowKind::ClosureCapture, + } + } +} + +impl<'tcx> Stable for mir::NullOp<'tcx> { + type T = stable_mir::mir::NullOp; + fn stable(&self) -> Self::T { + use mir::NullOp::*; + match self { + SizeOf => stable_mir::mir::NullOp::SizeOf, + AlignOf => stable_mir::mir::NullOp::AlignOf, + OffsetOf(indices) => { + stable_mir::mir::NullOp::OffsetOf(indices.iter().map(|idx| idx.stable()).collect()) + } + } + } +} + +impl Stable for mir::CastKind { + type T = stable_mir::mir::CastKind; + fn stable(&self) -> Self::T { + use mir::CastKind::*; + match self { + PointerExposeAddress => stable_mir::mir::CastKind::PointerExposeAddress, + PointerFromExposedAddress => stable_mir::mir::CastKind::PointerFromExposedAddress, + PointerCoercion(c) => stable_mir::mir::CastKind::PointerCoercion(c.stable()), + DynStar => stable_mir::mir::CastKind::DynStar, + IntToInt => stable_mir::mir::CastKind::IntToInt, + FloatToInt => stable_mir::mir::CastKind::FloatToInt, + FloatToFloat => stable_mir::mir::CastKind::FloatToFloat, + IntToFloat => stable_mir::mir::CastKind::IntToFloat, + PtrToPtr => stable_mir::mir::CastKind::PtrToPtr, + FnPtrToPtr => stable_mir::mir::CastKind::FnPtrToPtr, + Transmute => stable_mir::mir::CastKind::Transmute, } } } +impl Stable for ty::adjustment::PointerCoercion { + type T = stable_mir::mir::PointerCoercion; + fn stable(&self) -> Self::T { + use ty::adjustment::PointerCoercion; + match self { + PointerCoercion::ReifyFnPointer => stable_mir::mir::PointerCoercion::ReifyFnPointer, + PointerCoercion::UnsafeFnPointer => stable_mir::mir::PointerCoercion::UnsafeFnPointer, + PointerCoercion::ClosureFnPointer(unsafety) => { + stable_mir::mir::PointerCoercion::ClosureFnPointer(unsafety.stable()) + } + PointerCoercion::MutToConstPointer => { + stable_mir::mir::PointerCoercion::MutToConstPointer + } + PointerCoercion::ArrayToPointer => stable_mir::mir::PointerCoercion::ArrayToPointer, + PointerCoercion::Unsize => stable_mir::mir::PointerCoercion::Unsize, + } + } +} + +impl Stable for rustc_hir::Unsafety { + type T = stable_mir::mir::Safety; + fn stable(&self) -> Self::T { + match self { + rustc_hir::Unsafety::Unsafe => stable_mir::mir::Safety::Unsafe, + rustc_hir::Unsafety::Normal => stable_mir::mir::Safety::Normal, + } + } +} + +impl Stable for FieldIdx { + type T = usize; + fn stable(&self) -> Self::T { + self.as_usize() + } +} + impl<'tcx> Stable for mir::Operand<'tcx> { type T = stable_mir::mir::Operand; fn stable(&self) -> Self::T { @@ -229,34 +369,38 @@ impl Stable for mir::UnwindAction { } } -fn rustc_assert_msg_to_msg<'tcx>( - assert_message: &rustc_middle::mir::AssertMessage<'tcx>, -) -> stable_mir::mir::AssertMessage { - use rustc_middle::mir::AssertKind; - match assert_message { - AssertKind::BoundsCheck { len, index } => { - stable_mir::mir::AssertMessage::BoundsCheck { len: len.stable(), index: index.stable() } - } - AssertKind::Overflow(bin_op, op1, op2) => { - stable_mir::mir::AssertMessage::Overflow(bin_op.stable(), op1.stable(), op2.stable()) - } - AssertKind::OverflowNeg(op) => stable_mir::mir::AssertMessage::OverflowNeg(op.stable()), - AssertKind::DivisionByZero(op) => { - stable_mir::mir::AssertMessage::DivisionByZero(op.stable()) - } - AssertKind::RemainderByZero(op) => { - stable_mir::mir::AssertMessage::RemainderByZero(op.stable()) - } - AssertKind::ResumedAfterReturn(generator) => { - stable_mir::mir::AssertMessage::ResumedAfterReturn(generator.stable()) - } - AssertKind::ResumedAfterPanic(generator) => { - stable_mir::mir::AssertMessage::ResumedAfterPanic(generator.stable()) - } - AssertKind::MisalignedPointerDereference { required, found } => { - stable_mir::mir::AssertMessage::MisalignedPointerDereference { - required: required.stable(), - found: found.stable(), +impl<'tcx> Stable for mir::AssertMessage<'tcx> { + type T = stable_mir::mir::AssertMessage; + fn stable(&self) -> Self::T { + use rustc_middle::mir::AssertKind; + match self { + AssertKind::BoundsCheck { len, index } => stable_mir::mir::AssertMessage::BoundsCheck { + len: len.stable(), + index: index.stable(), + }, + AssertKind::Overflow(bin_op, op1, op2) => stable_mir::mir::AssertMessage::Overflow( + bin_op.stable(), + op1.stable(), + op2.stable(), + ), + AssertKind::OverflowNeg(op) => stable_mir::mir::AssertMessage::OverflowNeg(op.stable()), + AssertKind::DivisionByZero(op) => { + stable_mir::mir::AssertMessage::DivisionByZero(op.stable()) + } + AssertKind::RemainderByZero(op) => { + stable_mir::mir::AssertMessage::RemainderByZero(op.stable()) + } + AssertKind::ResumedAfterReturn(generator) => { + stable_mir::mir::AssertMessage::ResumedAfterReturn(generator.stable()) + } + AssertKind::ResumedAfterPanic(generator) => { + stable_mir::mir::AssertMessage::ResumedAfterPanic(generator.stable()) + } + AssertKind::MisalignedPointerDereference { required, found } => { + stable_mir::mir::AssertMessage::MisalignedPointerDereference { + required: required.stable(), + found: found.stable(), + } } } } @@ -381,7 +525,7 @@ impl<'tcx> Stable for mir::Terminator<'tcx> { Assert { cond, expected, msg, target, unwind } => Terminator::Assert { cond: cond.stable(), expected: *expected, - msg: rustc_assert_msg_to_msg(msg), + msg: msg.stable(), target: target.as_usize(), unwind: unwind.stable(), }, diff --git a/compiler/rustc_smir/src/stable_mir/mir/body.rs b/compiler/rustc_smir/src/stable_mir/mir/body.rs index 468e915d1a0..02ac907f09a 100644 --- a/compiler/rustc_smir/src/stable_mir/mir/body.rs +++ b/compiler/rustc_smir/src/stable_mir/mir/body.rs @@ -1,4 +1,5 @@ -use crate::stable_mir::ty::Ty; +use crate::rustc_internal::Opaque; +use crate::stable_mir::{self, ty::Ty}; #[derive(Clone, Debug)] pub struct Body { @@ -136,12 +137,98 @@ pub enum Statement { Nop, } +type Region = Opaque; + // FIXME this is incomplete #[derive(Clone, Debug)] pub enum Rvalue { - Use(Operand), + /// Creates a pointer with the indicated mutability to the place. + /// + /// This is generated by pointer casts like `&v as *const _` or raw address of expressions like + /// `&raw v` or `addr_of!(v)`. + AddressOf(Mutability, Place), + + /// * `Offset` has the same semantics as [`offset`](pointer::offset), except that the second + /// parameter may be a `usize` as well. + /// * The comparison operations accept `bool`s, `char`s, signed or unsigned integers, floats, + /// raw pointers, or function pointers and return a `bool`. The types of the operands must be + /// matching, up to the usual caveat of the lifetimes in function pointers. + /// * Left and right shift operations accept signed or unsigned integers not necessarily of the + /// same type and return a value of the same type as their LHS. Like in Rust, the RHS is + /// truncated as needed. + /// * The `Bit*` operations accept signed integers, unsigned integers, or bools with matching + /// types and return a value of that type. + /// * The remaining operations accept signed integers, unsigned integers, or floats with + /// matching types and return a value of that type. + BinaryOp(BinOp, Operand, Operand), + + /// Performs essentially all of the casts that can be performed via `as`. + /// + /// This allows for casts from/to a variety of types. + Cast(CastKind, Operand, Ty), + + /// Same as `BinaryOp`, but yields `(T, bool)` with a `bool` indicating an error condition. + /// + /// For addition, subtraction, and multiplication on integers the error condition is set when + /// the infinite precision result would not be equal to the actual result. CheckedBinaryOp(BinOp, Operand, Operand), + + /// A CopyForDeref is equivalent to a read from a place. + /// When such a read happens, it is guaranteed that the only use of the returned value is a + /// deref operation, immediately followed by one or more projections. + CopyForDeref(Place), + + /// Computes the discriminant of the place, returning it as an integer of type + /// [`discriminant_ty`]. Returns zero for types without discriminant. + /// + /// The validity requirements for the underlying value are undecided for this rvalue, see + /// [#91095]. Note too that the value of the discriminant is not the same thing as the + /// variant index; use [`discriminant_for_variant`] to convert. + /// + /// [`discriminant_ty`]: rustc_middle::ty::Ty::discriminant_ty + /// [#91095]: https://github.com/rust-lang/rust/issues/91095 + /// [`discriminant_for_variant`]: rustc_middle::ty::Ty::discriminant_for_variant + Discriminant(Place), + + /// Yields the length of the place, as a `usize`. + /// + /// If the type of the place is an array, this is the array length. For slices (`[T]`, not + /// `&[T]`) this accesses the place's metadata to determine the length. This rvalue is + /// ill-formed for places of other types. + Len(Place), + + /// Creates a reference to the place. + Ref(Region, BorrowKind, Place), + + /// Transmutes a `*mut u8` into shallow-initialized `Box<T>`. + /// + /// This is different from a normal transmute because dataflow analysis will treat the box as + /// initialized but its content as uninitialized. Like other pointer casts, this in general + /// affects alias analysis. + ShallowInitBox(Operand, Ty), + + /// Creates a pointer/reference to the given thread local. + /// + /// The yielded type is a `*mut T` if the static is mutable, otherwise if the static is extern a + /// `*const T`, and if neither of those apply a `&T`. + /// + /// **Note:** This is a runtime operation that actually executes code and is in this sense more + /// like a function call. Also, eliminating dead stores of this rvalue causes `fn main() {}` to + /// SIGILL for some reason that I (JakobDegen) never got a chance to look into. + /// + /// **Needs clarification**: Are there weird additional semantics here related to the runtime + /// nature of this operation? + ThreadLocalRef(stable_mir::CrateItem), + + /// Exactly like `BinaryOp`, but less operands. + /// + /// Also does two's-complement arithmetic. Negation requires a signed integer or a float; + /// bitwise not requires a signed integer, unsigned integer, or bool. Both operation kinds + /// return a value with the same type as their operand. UnaryOp(UnOp, Operand), + + /// Yields the operand unchanged + Use(Operand), } #[derive(Clone, Debug)] @@ -157,8 +244,98 @@ pub struct Place { pub projection: String, } +type FieldIdx = usize; + #[derive(Clone, Debug)] pub struct SwitchTarget { pub value: u128, pub target: usize, } + +#[derive(Clone, Debug)] +pub enum BorrowKind { + /// Data must be immutable and is aliasable. + Shared, + + /// The immediately borrowed place must be immutable, but projections from + /// it don't need to be. For example, a shallow borrow of `a.b` doesn't + /// conflict with a mutable borrow of `a.b.c`. + Shallow, + + /// Data is mutable and not aliasable. + Mut { + /// `true` if this borrow arose from method-call auto-ref + kind: MutBorrowKind, + }, +} + +#[derive(Clone, Debug)] +pub enum MutBorrowKind { + Default, + TwoPhaseBorrow, + ClosureCapture, +} + +#[derive(Clone, Debug)] +pub enum Mutability { + Not, + Mut, +} + +#[derive(Clone, Debug)] +pub enum Safety { + Unsafe, + Normal, +} + +#[derive(Clone, Debug)] +pub enum PointerCoercion { + /// Go from a fn-item type to a fn-pointer type. + ReifyFnPointer, + + /// Go from a safe fn pointer to an unsafe fn pointer. + UnsafeFnPointer, + + /// Go from a non-capturing closure to an fn pointer or an unsafe fn pointer. + /// It cannot convert a closure that requires unsafe. + ClosureFnPointer(Safety), + + /// Go from a mut raw pointer to a const raw pointer. + MutToConstPointer, + + /// Go from `*const [T; N]` to `*const T` + ArrayToPointer, + + /// Unsize a pointer/reference value, e.g., `&[T; n]` to + /// `&[T]`. Note that the source could be a thin or fat pointer. + /// This will do things like convert thin pointers to fat + /// pointers, or convert structs containing thin pointers to + /// structs containing fat pointers, or convert between fat + /// pointers. + Unsize, +} + +#[derive(Clone, Debug)] +pub enum CastKind { + PointerExposeAddress, + PointerFromExposedAddress, + PointerCoercion(PointerCoercion), + DynStar, + IntToInt, + FloatToInt, + FloatToFloat, + IntToFloat, + PtrToPtr, + FnPtrToPtr, + Transmute, +} + +#[derive(Clone, Debug)] +pub enum NullOp { + /// Returns the size of a value of that type. + SizeOf, + /// Returns the minimum alignment of a type. + AlignOf, + /// Returns the offset of a field. + OffsetOf(Vec<FieldIdx>), +} diff --git a/compiler/rustc_smir/src/stable_mir/ty.rs b/compiler/rustc_smir/src/stable_mir/ty.rs index 3181af46e9c..e9f17f92c04 100644 --- a/compiler/rustc_smir/src/stable_mir/ty.rs +++ b/compiler/rustc_smir/src/stable_mir/ty.rs @@ -1,4 +1,5 @@ -use super::with; +use super::{with, DefId}; +use crate::rustc_internal::Opaque; #[derive(Copy, Clone, Debug)] pub struct Ty(pub usize); @@ -9,6 +10,9 @@ impl Ty { } } +type Const = Opaque; +type Region = Opaque; + #[derive(Clone, Debug)] pub enum TyKind { RigidTy(RigidTy), @@ -21,6 +25,10 @@ pub enum RigidTy { Int(IntTy), Uint(UintTy), Float(FloatTy), + Adt(AdtDef, AdtSubsts), + Str, + Array(Ty, Const), + Slice(Ty), Tuple(Vec<Ty>), } @@ -49,3 +57,18 @@ pub enum FloatTy { F32, F64, } + +#[derive(Clone, PartialEq, Eq, Debug)] +pub struct AdtDef(pub(crate) DefId); + +#[derive(Clone, Debug)] +pub struct AdtSubsts(pub Vec<GenericArgKind>); + +#[derive(Clone, Debug)] +pub enum GenericArgKind { + // FIXME add proper region + Lifetime(Region), + Type(Ty), + // FIXME add proper const + Const(Const), +} diff --git a/compiler/rustc_span/src/lib.rs b/compiler/rustc_span/src/lib.rs index 3bb9c4920c4..5c56337d1e0 100644 --- a/compiler/rustc_span/src/lib.rs +++ b/compiler/rustc_span/src/lib.rs @@ -2159,7 +2159,8 @@ where // If this is not an empty or invalid span, we want to hash the last // position that belongs to it, as opposed to hashing the first // position past it. - let Some((file, line_lo, col_lo, line_hi, col_hi)) = ctx.span_data_to_lines_and_cols(&span) else { + let Some((file, line_lo, col_lo, line_hi, col_hi)) = ctx.span_data_to_lines_and_cols(&span) + else { Hash::hash(&TAG_INVALID_SPAN, hasher); return; }; diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index d655276a991..08925761b39 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -1265,6 +1265,7 @@ symbols! { rustc_clean, rustc_coherence_is_core, rustc_coinductive, + rustc_confusables, rustc_const_stable, rustc_const_unstable, rustc_conversion_suggestion, @@ -1280,7 +1281,7 @@ symbols! { rustc_dummy, rustc_dump_env_program_clauses, rustc_dump_program_clauses, - rustc_dump_user_substs, + rustc_dump_user_args, rustc_dump_vtable, rustc_effective_visibility, rustc_error, diff --git a/compiler/rustc_symbol_mangling/src/legacy.rs b/compiler/rustc_symbol_mangling/src/legacy.rs index ec7032cd3bf..3a33568084c 100644 --- a/compiler/rustc_symbol_mangling/src/legacy.rs +++ b/compiler/rustc_symbol_mangling/src/legacy.rs @@ -2,8 +2,8 @@ use rustc_data_structures::stable_hasher::{Hash64, HashStable, StableHasher}; use rustc_hir::def_id::CrateNum; use rustc_hir::definitions::{DefPathData, DisambiguatedDefPathData}; use rustc_middle::ty::print::{PrettyPrinter, Print, Printer}; -use rustc_middle::ty::subst::{GenericArg, GenericArgKind}; use rustc_middle::ty::{self, Instance, Ty, TyCtxt, TypeVisitableExt}; +use rustc_middle::ty::{GenericArg, GenericArgKind}; use rustc_middle::util::common::record_time; use std::fmt::{self, Write}; @@ -26,7 +26,7 @@ pub(super) fn mangle<'tcx>( let key = tcx.def_key(ty_def_id); match key.disambiguated_data.data { DefPathData::TypeNs(_) | DefPathData::ValueNs(_) => { - instance_ty = tcx.type_of(ty_def_id).subst_identity(); + instance_ty = tcx.type_of(ty_def_id).instantiate_identity(); debug!(?instance_ty); break; } @@ -58,7 +58,7 @@ pub(super) fn mangle<'tcx>( def_id, if let ty::InstanceDef::DropGlue(_, _) = instance.def { // Add the name of the dropped type to the symbol name - &*instance.substs + &*instance.args } else { &[] }, @@ -95,8 +95,8 @@ fn get_symbol_hash<'tcx>( instantiating_crate: Option<CrateNum>, ) -> Hash64 { let def_id = instance.def_id(); - let substs = instance.substs; - debug!("get_symbol_hash(def_id={:?}, parameters={:?})", def_id, substs); + let args = instance.args; + debug!("get_symbol_hash(def_id={:?}, parameters={:?})", def_id, args); tcx.with_stable_hashing_context(|mut hcx| { let mut hasher = StableHasher::new(); @@ -122,7 +122,7 @@ fn get_symbol_hash<'tcx>( } // also include any type parameters (for generic items) - substs.hash_stable(hcx, &mut hasher); + args.hash_stable(hcx, &mut hasher); if let Some(instantiating_crate) = instantiating_crate { tcx.def_path_hash(instantiating_crate.as_def_id()) @@ -219,10 +219,10 @@ impl<'tcx> Printer<'tcx> for &mut SymbolPrinter<'tcx> { fn print_type(mut self, ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> { match *ty.kind() { // Print all nominal types as paths (unlike `pretty_print_type`). - ty::FnDef(def_id, substs) - | ty::Alias(ty::Projection | ty::Opaque, ty::AliasTy { def_id, substs, .. }) - | ty::Closure(def_id, substs) - | ty::Generator(def_id, substs, _) => self.print_def_path(def_id, substs), + ty::FnDef(def_id, args) + | ty::Alias(ty::Projection | ty::Opaque, ty::AliasTy { def_id, args, .. }) + | ty::Closure(def_id, args) + | ty::Generator(def_id, args, _) => self.print_def_path(def_id, args), // The `pretty_print_type` formatting of array size depends on // -Zverbose flag, so we cannot reuse it here. diff --git a/compiler/rustc_symbol_mangling/src/lib.rs b/compiler/rustc_symbol_mangling/src/lib.rs index 692542da78e..22fd1f09f3a 100644 --- a/compiler/rustc_symbol_mangling/src/lib.rs +++ b/compiler/rustc_symbol_mangling/src/lib.rs @@ -108,7 +108,7 @@ use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags; use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs; use rustc_middle::mir::mono::{InstantiationMode, MonoItem}; use rustc_middle::query::Providers; -use rustc_middle::ty::subst::SubstsRef; +use rustc_middle::ty::GenericArgsRef; use rustc_middle::ty::{self, Instance, TyCtxt}; use rustc_session::config::SymbolManglingVersion; @@ -144,7 +144,7 @@ fn symbol_name_provider<'tcx>(tcx: TyCtxt<'tcx>, instance: Instance<'tcx>) -> ty // This closure determines the instantiating crate for instances that // need an instantiating-crate-suffix for their symbol name, in order // to differentiate between local copies. - if is_generic(instance.substs) { + if is_generic(instance.args) { // For generics we might find re-usable upstream instances. If there // is one, we rely on the symbol being instantiated locally. instance.upstream_monomorphization(tcx).unwrap_or(LOCAL_CRATE) @@ -174,9 +174,9 @@ fn compute_symbol_name<'tcx>( compute_instantiating_crate: impl FnOnce() -> CrateNum, ) -> String { let def_id = instance.def_id(); - let substs = instance.substs; + let args = instance.args; - debug!("symbol_name(def_id={:?}, substs={:?})", def_id, substs); + debug!("symbol_name(def_id={:?}, args={:?})", def_id, args); if let Some(def_id) = def_id.as_local() { if tcx.proc_macro_decls_static(()) == Some(def_id) { @@ -246,7 +246,7 @@ fn compute_symbol_name<'tcx>( // the ID of the instantiating crate. This avoids symbol conflicts // in case the same instances is emitted in two crates of the same // project. - let avoid_cross_crate_conflicts = is_generic(substs) || is_globally_shared_function; + let avoid_cross_crate_conflicts = is_generic(args) || is_globally_shared_function; let instantiating_crate = avoid_cross_crate_conflicts.then(compute_instantiating_crate); @@ -278,6 +278,6 @@ fn compute_symbol_name<'tcx>( symbol } -fn is_generic(substs: SubstsRef<'_>) -> bool { - substs.non_erasable_generics().next().is_some() +fn is_generic(args: GenericArgsRef<'_>) -> bool { + args.non_erasable_generics().next().is_some() } diff --git a/compiler/rustc_symbol_mangling/src/test.rs b/compiler/rustc_symbol_mangling/src/test.rs index 985b2210745..eddfd0df318 100644 --- a/compiler/rustc_symbol_mangling/src/test.rs +++ b/compiler/rustc_symbol_mangling/src/test.rs @@ -7,7 +7,7 @@ use crate::errors::{Kind, TestOutput}; use rustc_hir::def_id::LocalDefId; use rustc_middle::ty::print::with_no_trimmed_paths; -use rustc_middle::ty::{subst::InternalSubsts, Instance, TyCtxt}; +use rustc_middle::ty::{GenericArgs, Instance, TyCtxt}; use rustc_span::symbol::{sym, Symbol}; const SYMBOL_NAME: Symbol = sym::rustc_symbol_name; @@ -57,7 +57,7 @@ impl SymbolNamesTest<'_> { let def_id = def_id.to_def_id(); let instance = Instance::new( def_id, - tcx.erase_regions(InternalSubsts::identity_for_item(tcx, def_id)), + tcx.erase_regions(GenericArgs::identity_for_item(tcx, def_id)), ); let mangled = tcx.symbol_name(instance); tcx.sess.emit_err(TestOutput { diff --git a/compiler/rustc_symbol_mangling/src/typeid/typeid_itanium_cxx_abi.rs b/compiler/rustc_symbol_mangling/src/typeid/typeid_itanium_cxx_abi.rs index 3b46275ec41..4a938ff938a 100644 --- a/compiler/rustc_symbol_mangling/src/typeid/typeid_itanium_cxx_abi.rs +++ b/compiler/rustc_symbol_mangling/src/typeid/typeid_itanium_cxx_abi.rs @@ -11,11 +11,11 @@ use core::fmt::Display; use rustc_data_structures::base_n; use rustc_data_structures::fx::FxHashMap; use rustc_hir as hir; -use rustc_middle::ty::subst::{GenericArg, GenericArgKind, SubstsRef}; use rustc_middle::ty::{ self, Const, ExistentialPredicate, FloatTy, FnSig, Instance, IntTy, List, Region, RegionKind, TermKind, Ty, TyCtxt, UintTy, }; +use rustc_middle::ty::{GenericArg, GenericArgKind, GenericArgsRef}; use rustc_span::def_id::DefId; use rustc_span::sym; use rustc_target::abi::call::{Conv, FnAbi}; @@ -212,12 +212,12 @@ fn encode_predicate<'tcx>( ty::ExistentialPredicate::Trait(trait_ref) => { let name = encode_ty_name(tcx, trait_ref.def_id); let _ = write!(s, "u{}{}", name.len(), &name); - s.push_str(&encode_substs(tcx, trait_ref.substs, dict, options)); + s.push_str(&encode_args(tcx, trait_ref.args, dict, options)); } ty::ExistentialPredicate::Projection(projection) => { let name = encode_ty_name(tcx, projection.def_id); let _ = write!(s, "u{}{}", name.len(), &name); - s.push_str(&encode_substs(tcx, projection.substs, dict, options)); + s.push_str(&encode_args(tcx, projection.args, dict, options)); match projection.term.unpack() { TermKind::Ty(ty) => s.push_str(&encode_ty(tcx, ty, dict, options)), TermKind::Const(c) => s.push_str(&encode_const(tcx, c, dict, options)), @@ -286,21 +286,21 @@ fn encode_region<'tcx>( s } -/// Encodes substs using the Itanium C++ ABI with vendor extended type qualifiers and types for Rust +/// Encodes args using the Itanium C++ ABI with vendor extended type qualifiers and types for Rust /// types that are not used at the FFI boundary. -fn encode_substs<'tcx>( +fn encode_args<'tcx>( tcx: TyCtxt<'tcx>, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, dict: &mut FxHashMap<DictKey<'tcx>, usize>, options: EncodeTyOptions, ) -> String { // [I<subst1..substN>E] as part of vendor extended type let mut s = String::new(); - let substs: Vec<GenericArg<'_>> = substs.iter().collect(); - if !substs.is_empty() { + let args: Vec<GenericArg<'_>> = args.iter().collect(); + if !args.is_empty() { s.push('I'); - for subst in substs { - match subst.unpack() { + for arg in args { + match arg.unpack() { GenericArgKind::Lifetime(region) => { s.push_str(&encode_region(tcx, region, dict, options)); } @@ -524,7 +524,7 @@ fn encode_ty<'tcx>( } // User-defined types - ty::Adt(adt_def, substs) => { + ty::Adt(adt_def, args) => { let mut s = String::new(); let def_id = adt_def.did(); if let Some(cfi_encoding) = tcx.get_attr(def_id, sym::cfi_encoding) { @@ -570,7 +570,7 @@ fn encode_ty<'tcx>( // <subst>, as vendor extended type. let name = encode_ty_name(tcx, def_id); let _ = write!(s, "u{}{}", name.len(), &name); - s.push_str(&encode_substs(tcx, substs, dict, options)); + s.push_str(&encode_args(tcx, args, dict, options)); compress(dict, DictKey::Ty(ty, TyQ::None), &mut s); } typeid.push_str(&s); @@ -608,27 +608,27 @@ fn encode_ty<'tcx>( } // Function types - ty::FnDef(def_id, substs) | ty::Closure(def_id, substs) => { + ty::FnDef(def_id, args) | ty::Closure(def_id, args) => { // u<length><name>[I<element-type1..element-typeN>E], where <element-type> is <subst>, // as vendor extended type. let mut s = String::new(); let name = encode_ty_name(tcx, *def_id); let _ = write!(s, "u{}{}", name.len(), &name); - s.push_str(&encode_substs(tcx, substs, dict, options)); + s.push_str(&encode_args(tcx, args, dict, options)); compress(dict, DictKey::Ty(ty, TyQ::None), &mut s); typeid.push_str(&s); } - ty::Generator(def_id, substs, ..) => { + ty::Generator(def_id, args, ..) => { // u<length><name>[I<element-type1..element-typeN>E], where <element-type> is <subst>, // as vendor extended type. let mut s = String::new(); let name = encode_ty_name(tcx, *def_id); let _ = write!(s, "u{}{}", name.len(), &name); - // Encode parent substs only - s.push_str(&encode_substs( + // Encode parent args only + s.push_str(&encode_args( tcx, - tcx.mk_substs(substs.as_generator().parent_substs()), + tcx.mk_args(args.as_generator().parent_args()), dict, options, )); @@ -732,18 +732,18 @@ fn transform_predicates<'tcx>( tcx.mk_poly_existential_predicates(&predicates) } -/// Transforms substs for being encoded and used in the substitution dictionary. -fn transform_substs<'tcx>( +/// Transforms args for being encoded and used in the substitution dictionary. +fn transform_args<'tcx>( tcx: TyCtxt<'tcx>, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, options: TransformTyOptions, -) -> SubstsRef<'tcx> { - let substs = substs.iter().map(|subst| match subst.unpack() { +) -> GenericArgsRef<'tcx> { + let args = args.iter().map(|arg| match arg.unpack() { GenericArgKind::Type(ty) if ty.is_c_void(tcx) => Ty::new_unit(tcx).into(), GenericArgKind::Type(ty) => transform_ty(tcx, ty, options).into(), - _ => subst, + _ => arg, }); - tcx.mk_substs_from_iter(substs) + tcx.mk_args_from_iter(args) } // Transforms a ty:Ty for being encoded and used in the substitution dictionary. It transforms all @@ -825,7 +825,7 @@ fn transform_ty<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, options: TransformTyOptio ty = Ty::new_slice(tcx, transform_ty(tcx, *ty0, options)); } - ty::Adt(adt_def, substs) => { + ty::Adt(adt_def, args) => { if ty.is_c_void(tcx) { ty = Ty::new_unit(tcx); } else if options.contains(TransformTyOptions::GENERALIZE_REPR_C) && adt_def.repr().c() @@ -840,13 +840,13 @@ fn transform_ty<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, options: TransformTyOptio let variant = adt_def.non_enum_variant(); let param_env = tcx.param_env(variant.def_id); let field = variant.fields.iter().find(|field| { - let ty = tcx.type_of(field.did).subst_identity(); + let ty = tcx.type_of(field.did).instantiate_identity(); let is_zst = tcx.layout_of(param_env.and(ty)).is_ok_and(|layout| layout.is_zst()); !is_zst }); if let Some(field) = field { - let ty0 = tcx.type_of(field.did).subst(tcx, substs); + let ty0 = tcx.type_of(field.did).instantiate(tcx, args); // Generalize any repr(transparent) user-defined type that is either a pointer // or reference, and either references itself or any other type that contains or // references itself, to avoid a reference cycle. @@ -864,25 +864,20 @@ fn transform_ty<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, options: TransformTyOptio ty = Ty::new_unit(tcx); } } else { - ty = Ty::new_adt(tcx, *adt_def, transform_substs(tcx, substs, options)); + ty = Ty::new_adt(tcx, *adt_def, transform_args(tcx, args, options)); } } - ty::FnDef(def_id, substs) => { - ty = Ty::new_fn_def(tcx, *def_id, transform_substs(tcx, substs, options)); + ty::FnDef(def_id, args) => { + ty = Ty::new_fn_def(tcx, *def_id, transform_args(tcx, args, options)); } - ty::Closure(def_id, substs) => { - ty = Ty::new_closure(tcx, *def_id, transform_substs(tcx, substs, options)); + ty::Closure(def_id, args) => { + ty = Ty::new_closure(tcx, *def_id, transform_args(tcx, args, options)); } - ty::Generator(def_id, substs, movability) => { - ty = Ty::new_generator( - tcx, - *def_id, - transform_substs(tcx, substs, options), - *movability, - ); + ty::Generator(def_id, args, movability) => { + ty = Ty::new_generator(tcx, *def_id, transform_args(tcx, args, options), *movability); } ty::Ref(region, ty0, ..) => { diff --git a/compiler/rustc_symbol_mangling/src/v0.rs b/compiler/rustc_symbol_mangling/src/v0.rs index 5e5cc6e4e4a..1846fda7c63 100644 --- a/compiler/rustc_symbol_mangling/src/v0.rs +++ b/compiler/rustc_symbol_mangling/src/v0.rs @@ -27,7 +27,7 @@ pub(super) fn mangle<'tcx>( ) -> 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 args = tcx.normalize_erasing_regions(ty::ParamEnv::reveal_all(), instance.args); let prefix = "_R"; let mut cx = &mut SymbolMangler { @@ -50,9 +50,9 @@ pub(super) fn mangle<'tcx>( }; cx = if let Some(shim_kind) = shim_kind { - cx.path_append_ns(|cx| cx.print_def_path(def_id, substs), 'S', 0, shim_kind).unwrap() + cx.path_append_ns(|cx| cx.print_def_path(def_id, args), 'S', 0, shim_kind).unwrap() } else { - cx.print_def_path(def_id, substs).unwrap() + cx.print_def_path(def_id, args).unwrap() }; if let Some(instantiating_crate) = instantiating_crate { cx = cx.print_def_path(instantiating_crate.as_def_id(), &[]).unwrap(); @@ -245,19 +245,19 @@ impl<'tcx> Printer<'tcx> for &mut SymbolMangler<'tcx> { fn print_def_path( mut self, def_id: DefId, - substs: &'tcx [GenericArg<'tcx>], + args: &'tcx [GenericArg<'tcx>], ) -> Result<Self::Path, Self::Error> { - if let Some(&i) = self.paths.get(&(def_id, substs)) { + if let Some(&i) = self.paths.get(&(def_id, args)) { return self.print_backref(i); } let start = self.out.len(); - self = self.default_print_def_path(def_id, substs)?; + self = self.default_print_def_path(def_id, args)?; // Only cache paths that do not refer to an enclosing // binder (which would change depending on context). - if !substs.iter().any(|k| k.has_escaping_bound_vars()) { - self.paths.insert((def_id, substs), start); + if !args.iter().any(|k| k.has_escaping_bound_vars()) { + self.paths.insert((def_id, args), start); } Ok(self) } @@ -265,7 +265,7 @@ impl<'tcx> Printer<'tcx> for &mut SymbolMangler<'tcx> { fn print_impl_path( mut self, impl_def_id: DefId, - substs: &'tcx [GenericArg<'tcx>], + args: &'tcx [GenericArg<'tcx>], mut self_ty: Ty<'tcx>, mut impl_trait_ref: Option<ty::TraitRef<'tcx>>, ) -> Result<Self::Path, Self::Error> { @@ -273,8 +273,8 @@ impl<'tcx> Printer<'tcx> for &mut SymbolMangler<'tcx> { let parent_def_id = DefId { index: key.parent.unwrap(), ..impl_def_id }; let mut param_env = self.tcx.param_env_reveal_all_normalized(impl_def_id); - if !substs.is_empty() { - param_env = EarlyBinder::bind(param_env).subst(self.tcx, substs); + if !args.is_empty() { + param_env = EarlyBinder::bind(param_env).instantiate(self.tcx, args); } match &mut impl_trait_ref { @@ -295,7 +295,7 @@ impl<'tcx> Printer<'tcx> for &mut SymbolMangler<'tcx> { // Encode impl generic params if the substitutions contain parameters (implying // polymorphization is enabled) and this isn't an inherent impl. - if impl_trait_ref.is_some() && substs.iter().any(|a| a.has_non_region_param()) { + if impl_trait_ref.is_some() && args.iter().any(|a| a.has_non_region_param()) { self = self.path_generic_args( |this| { this.path_append_ns( @@ -305,7 +305,7 @@ impl<'tcx> Printer<'tcx> for &mut SymbolMangler<'tcx> { "", ) }, - substs, + args, )?; } else { self.push_disambiguator(key.disambiguated_data.disambiguator as u64); @@ -315,7 +315,7 @@ impl<'tcx> Printer<'tcx> for &mut SymbolMangler<'tcx> { self = self_ty.print(self)?; if let Some(trait_ref) = impl_trait_ref { - self = self.print_def_path(trait_ref.def_id, trait_ref.substs)?; + self = self.print_def_path(trait_ref.def_id, trait_ref.args)?; } Ok(self) @@ -431,12 +431,12 @@ impl<'tcx> Printer<'tcx> for &mut SymbolMangler<'tcx> { } // Mangle all nominal types as paths. - ty::Adt(ty::AdtDef(Interned(&ty::AdtDefData { did: def_id, .. }, _)), substs) - | ty::FnDef(def_id, substs) - | ty::Alias(ty::Projection | ty::Opaque, ty::AliasTy { def_id, substs, .. }) - | ty::Closure(def_id, substs) - | ty::Generator(def_id, substs, _) => { - self = self.print_def_path(def_id, substs)?; + ty::Adt(ty::AdtDef(Interned(&ty::AdtDefData { did: def_id, .. }, _)), args) + | ty::FnDef(def_id, args) + | ty::Alias(ty::Projection | ty::Opaque, ty::AliasTy { def_id, args, .. }) + | ty::Closure(def_id, args) + | ty::Generator(def_id, args, _) => { + self = self.print_def_path(def_id, args)?; } ty::Foreign(def_id) => { self = self.print_def_path(def_id, &[])?; @@ -537,7 +537,7 @@ impl<'tcx> Printer<'tcx> for &mut SymbolMangler<'tcx> { // Use a type that can't appear in defaults of type parameters. let dummy_self = Ty::new_fresh(cx.tcx, 0); let trait_ref = trait_ref.with_self_ty(cx.tcx, dummy_self); - cx = cx.print_def_path(trait_ref.def_id, trait_ref.substs)?; + cx = cx.print_def_path(trait_ref.def_id, trait_ref.args)?; } ty::ExistentialPredicate::Projection(projection) => { let name = cx.tcx.associated_item(projection.def_id).name; @@ -679,13 +679,13 @@ impl<'tcx> Printer<'tcx> for &mut SymbolMangler<'tcx> { self.push("T"); self = print_field_list(self)?; } - ty::Adt(def, substs) => { + ty::Adt(def, args) => { let variant_idx = contents.variant.expect("destructed const of adt without variant idx"); let variant_def = &def.variant(variant_idx); self.push("V"); - self = self.print_def_path(variant_def.def_id, substs)?; + self = self.print_def_path(variant_def.def_id, args)?; match variant_def.ctor_kind() { Some(CtorKind::Const) => { @@ -750,7 +750,7 @@ impl<'tcx> Printer<'tcx> for &mut SymbolMangler<'tcx> { self.push("Y"); self = self_ty.print(self)?; - self.print_def_path(trait_ref.def_id, trait_ref.substs) + self.print_def_path(trait_ref.def_id, trait_ref.args) } fn path_append_impl( diff --git a/compiler/rustc_target/src/abi/call/aarch64.rs b/compiler/rustc_target/src/abi/call/aarch64.rs index a84988fa75c..b4c7b0f120f 100644 --- a/compiler/rustc_target/src/abi/call/aarch64.rs +++ b/compiler/rustc_target/src/abi/call/aarch64.rs @@ -1,25 +1,15 @@ use crate::abi::call::{ArgAbi, FnAbi, Reg, RegKind, Uniform}; use crate::abi::{HasDataLayout, TyAbiInterface}; -/// Given integer-types M and register width N (e.g. M=u16 and N=32 bits), the -/// `ParamExtension` policy specifies how a uM value should be treated when -/// passed via register or stack-slot of width N. See also rust-lang/rust#97463. +/// Indicates the variant of the AArch64 ABI we are compiling for. +/// Used to accommodate Apple and Microsoft's deviations from the usual AAPCS ABI. +/// +/// Corresponds to Clang's `AArch64ABIInfo::ABIKind`. #[derive(Copy, Clone, PartialEq)] -pub enum ParamExtension { - /// Indicates that when passing an i8/i16, either as a function argument or - /// as a return value, it must be sign-extended to 32 bits, and likewise a - /// u8/u16 must be zero-extended to 32-bits. (This variant is here to - /// accommodate Apple's deviation from the usual AArch64 ABI as defined by - /// ARM.) - /// - /// See also: <https://developer.apple.com/documentation/xcode/writing-arm64-code-for-apple-platforms#Pass-Arguments-to-Functions-Correctly> - ExtendTo32Bits, - - /// Indicates that no sign- nor zero-extension is performed: if a value of - /// type with bitwidth M is passed as function argument or return value, - /// then M bits are copied into the least significant M bits, and the - /// remaining bits of the register (or word of memory) are untouched. - NoExtension, +pub enum AbiKind { + AAPCS, + DarwinPCS, + Win64, } fn is_homogeneous_aggregate<'a, Ty, C>(cx: &C, arg: &mut ArgAbi<'a, Ty>) -> Option<Uniform> @@ -45,15 +35,17 @@ where }) } -fn classify_ret<'a, Ty, C>(cx: &C, ret: &mut ArgAbi<'a, Ty>, param_policy: ParamExtension) +fn classify_ret<'a, Ty, C>(cx: &C, ret: &mut ArgAbi<'a, Ty>, kind: AbiKind) where Ty: TyAbiInterface<'a, C> + Copy, C: HasDataLayout, { if !ret.layout.is_aggregate() { - match param_policy { - ParamExtension::ExtendTo32Bits => ret.extend_integer_width_to(32), - ParamExtension::NoExtension => {} + if kind == AbiKind::DarwinPCS { + // On Darwin, when returning an i8/i16, it must be sign-extended to 32 bits, + // and likewise a u8/u16 must be zero-extended to 32-bits. + // See also: <https://developer.apple.com/documentation/xcode/writing-arm64-code-for-apple-platforms#Pass-Arguments-to-Functions-Correctly> + ret.extend_integer_width_to(32) } return; } @@ -70,15 +62,17 @@ where ret.make_indirect(); } -fn classify_arg<'a, Ty, C>(cx: &C, arg: &mut ArgAbi<'a, Ty>, param_policy: ParamExtension) +fn classify_arg<'a, Ty, C>(cx: &C, arg: &mut ArgAbi<'a, Ty>, kind: AbiKind) where Ty: TyAbiInterface<'a, C> + Copy, C: HasDataLayout, { if !arg.layout.is_aggregate() { - match param_policy { - ParamExtension::ExtendTo32Bits => arg.extend_integer_width_to(32), - ParamExtension::NoExtension => {} + if kind == AbiKind::DarwinPCS { + // On Darwin, when passing an i8/i16, it must be sign-extended to 32 bits, + // and likewise a u8/u16 must be zero-extended to 32-bits. + // See also: <https://developer.apple.com/documentation/xcode/writing-arm64-code-for-apple-platforms#Pass-Arguments-to-Functions-Correctly> + arg.extend_integer_width_to(32); } return; } @@ -87,27 +81,39 @@ where return; } let size = arg.layout.size; - let bits = size.bits(); - if bits <= 128 { - arg.cast_to(Uniform { unit: Reg::i64(), total: size }); + let align = if kind == AbiKind::AAPCS { + // When passing small aggregates by value, the AAPCS ABI mandates using the unadjusted + // alignment of the type (not including `repr(align)`). + // This matches behavior of `AArch64ABIInfo::classifyArgumentType` in Clang. + // See: <https://github.com/llvm/llvm-project/blob/5e691a1c9b0ad22689d4a434ddf4fed940e58dec/clang/lib/CodeGen/TargetInfo.cpp#L5816-L5823> + arg.layout.unadjusted_abi_align + } else { + arg.layout.align.abi + }; + if size.bits() <= 128 { + if align.bits() == 128 { + arg.cast_to(Uniform { unit: Reg::i128(), total: size }); + } else { + arg.cast_to(Uniform { unit: Reg::i64(), total: size }); + } return; } arg.make_indirect(); } -pub fn compute_abi_info<'a, Ty, C>(cx: &C, fn_abi: &mut FnAbi<'a, Ty>, param_policy: ParamExtension) +pub fn compute_abi_info<'a, Ty, C>(cx: &C, fn_abi: &mut FnAbi<'a, Ty>, kind: AbiKind) where Ty: TyAbiInterface<'a, C> + Copy, C: HasDataLayout, { if !fn_abi.ret.is_ignore() { - classify_ret(cx, &mut fn_abi.ret, param_policy); + classify_ret(cx, &mut fn_abi.ret, kind); } for arg in fn_abi.args.iter_mut() { if arg.is_ignore() { continue; } - classify_arg(cx, arg, param_policy); + classify_arg(cx, arg, kind); } } diff --git a/compiler/rustc_target/src/abi/call/m68k.rs b/compiler/rustc_target/src/abi/call/m68k.rs index c1e0f54af5f..1d4649ed867 100644 --- a/compiler/rustc_target/src/abi/call/m68k.rs +++ b/compiler/rustc_target/src/abi/call/m68k.rs @@ -10,7 +10,7 @@ fn classify_ret<Ty>(ret: &mut ArgAbi<'_, Ty>) { fn classify_arg<Ty>(arg: &mut ArgAbi<'_, Ty>) { if arg.layout.is_aggregate() { - arg.make_indirect_byval(); + arg.make_indirect_byval(None); } else { arg.extend_integer_width_to(32); } diff --git a/compiler/rustc_target/src/abi/call/mod.rs b/compiler/rustc_target/src/abi/call/mod.rs index c4abf6f4b5e..03e7b3e7b40 100644 --- a/compiler/rustc_target/src/abi/call/mod.rs +++ b/compiler/rustc_target/src/abi/call/mod.rs @@ -494,9 +494,7 @@ impl<'a, Ty> ArgAbi<'a, Ty> { .set(ArgAttribute::NonNull) .set(ArgAttribute::NoUndef); attrs.pointee_size = layout.size; - // FIXME(eddyb) We should be doing this, but at least on - // i686-pc-windows-msvc, it results in wrong stack offsets. - // attrs.pointee_align = Some(layout.align.abi); + attrs.pointee_align = Some(layout.align.abi); let extra_attrs = layout.is_unsized().then_some(ArgAttributes::new()); @@ -513,11 +511,19 @@ impl<'a, Ty> ArgAbi<'a, Ty> { self.mode = Self::indirect_pass_mode(&self.layout); } - pub fn make_indirect_byval(&mut self) { + pub fn make_indirect_byval(&mut self, byval_align: Option<Align>) { self.make_indirect(); match self.mode { - PassMode::Indirect { attrs: _, extra_attrs: _, ref mut on_stack } => { + PassMode::Indirect { ref mut attrs, extra_attrs: _, ref mut on_stack } => { *on_stack = true; + + // Some platforms, like 32-bit x86, change the alignment of the type when passing + // `byval`. Account for that. + if let Some(byval_align) = byval_align { + // On all targets with byval align this is currently true, so let's assert it. + debug_assert!(byval_align >= Align::from_bytes(4).unwrap()); + attrs.pointee_align = Some(byval_align); + } } _ => unreachable!(), } @@ -644,7 +650,8 @@ impl<'a, Ty> FnAbi<'a, Ty> { { if abi == spec::abi::Abi::X86Interrupt { if let Some(arg) = self.args.first_mut() { - arg.make_indirect_byval(); + // FIXME(pcwalton): This probably should use the x86 `byval` ABI... + arg.make_indirect_byval(None); } return Ok(()); } @@ -672,12 +679,14 @@ impl<'a, Ty> FnAbi<'a, Ty> { } }, "aarch64" => { - let param_policy = if cx.target_spec().is_like_osx { - aarch64::ParamExtension::ExtendTo32Bits + let kind = if cx.target_spec().is_like_osx { + aarch64::AbiKind::DarwinPCS + } else if cx.target_spec().is_like_windows { + aarch64::AbiKind::Win64 } else { - aarch64::ParamExtension::NoExtension + aarch64::AbiKind::AAPCS }; - aarch64::compute_abi_info(cx, self, param_policy) + aarch64::compute_abi_info(cx, self, kind) } "amdgpu" => amdgpu::compute_abi_info(cx, self), "arm" => arm::compute_abi_info(cx, self), diff --git a/compiler/rustc_target/src/abi/call/wasm.rs b/compiler/rustc_target/src/abi/call/wasm.rs index 44427ee5317..0eb2309ecb2 100644 --- a/compiler/rustc_target/src/abi/call/wasm.rs +++ b/compiler/rustc_target/src/abi/call/wasm.rs @@ -36,7 +36,7 @@ where { arg.extend_integer_width_to(32); if arg.layout.is_aggregate() && !unwrap_trivial_aggregate(cx, arg) { - arg.make_indirect_byval(); + arg.make_indirect_byval(None); } } diff --git a/compiler/rustc_target/src/abi/call/x86.rs b/compiler/rustc_target/src/abi/call/x86.rs index 7c26335dcf4..b738c3133d9 100644 --- a/compiler/rustc_target/src/abi/call/x86.rs +++ b/compiler/rustc_target/src/abi/call/x86.rs @@ -1,5 +1,5 @@ use crate::abi::call::{ArgAttribute, FnAbi, PassMode, Reg, RegKind}; -use crate::abi::{HasDataLayout, TyAbiInterface}; +use crate::abi::{Abi, Align, HasDataLayout, TyAbiInterface, TyAndLayout}; use crate::spec::HasTargetSpec; #[derive(PartialEq)] @@ -53,8 +53,75 @@ where if arg.is_ignore() { continue; } - if arg.layout.is_aggregate() { - arg.make_indirect_byval(); + + // FIXME: MSVC 2015+ will pass the first 3 vector arguments in [XYZ]MM0-2 + // See https://reviews.llvm.org/D72114 for Clang behavior + + let t = cx.target_spec(); + let align_4 = Align::from_bytes(4).unwrap(); + let align_16 = Align::from_bytes(16).unwrap(); + + if t.is_like_msvc + && arg.layout.is_adt() + && let Some(max_repr_align) = arg.layout.max_repr_align + && max_repr_align > align_4 + { + // MSVC has special rules for overaligned arguments: https://reviews.llvm.org/D72114. + // Summarized here: + // - Arguments with _requested_ alignment > 4 are passed indirectly. + // - For backwards compatibility, arguments with natural alignment > 4 are still passed + // on stack (via `byval`). For example, this includes `double`, `int64_t`, + // and structs containing them, provided they lack an explicit alignment attribute. + assert!(arg.layout.align.abi >= max_repr_align, + "abi alignment {:?} less than requested alignment {max_repr_align:?}", + arg.layout.align.abi, + ); + arg.make_indirect(); + } else if arg.layout.is_aggregate() { + // We need to compute the alignment of the `byval` argument. The rules can be found in + // `X86_32ABIInfo::getTypeStackAlignInBytes` in Clang's `TargetInfo.cpp`. Summarized + // here, they are: + // + // 1. If the natural alignment of the type is <= 4, the alignment is 4. + // + // 2. Otherwise, on Linux, the alignment of any vector type is the natural alignment. + // This doesn't matter here because we only pass aggregates via `byval`, not vectors. + // + // 3. Otherwise, on Apple platforms, the alignment of anything that contains a vector + // type is 16. + // + // 4. If none of these conditions are true, the alignment is 4. + + fn contains_vector<'a, Ty, C>(cx: &C, layout: TyAndLayout<'a, Ty>) -> bool + where + Ty: TyAbiInterface<'a, C> + Copy, + { + match layout.abi { + Abi::Uninhabited | Abi::Scalar(_) | Abi::ScalarPair(..) => false, + Abi::Vector { .. } => true, + Abi::Aggregate { .. } => { + for i in 0..layout.fields.count() { + if contains_vector(cx, layout.field(cx, i)) { + return true; + } + } + false + } + } + } + + let byval_align = if arg.layout.align.abi < align_4 { + // (1.) + align_4 + } else if t.is_like_osx && contains_vector(cx, arg.layout) { + // (3.) + align_16 + } else { + // (4.) + align_4 + }; + + arg.make_indirect_byval(Some(byval_align)); } else { arg.extend_integer_width_to(32); } diff --git a/compiler/rustc_target/src/abi/call/x86_64.rs b/compiler/rustc_target/src/abi/call/x86_64.rs index b1aefaf0507..d1efe977699 100644 --- a/compiler/rustc_target/src/abi/call/x86_64.rs +++ b/compiler/rustc_target/src/abi/call/x86_64.rs @@ -213,7 +213,7 @@ where match cls_or_mem { Err(Memory) => { if is_arg { - arg.make_indirect_byval(); + arg.make_indirect_byval(None); } else { // `sret` parameter thus one less integer register available arg.make_indirect(); diff --git a/compiler/rustc_target/src/lib.rs b/compiler/rustc_target/src/lib.rs index a7b54766bc6..3307244a217 100644 --- a/compiler/rustc_target/src/lib.rs +++ b/compiler/rustc_target/src/lib.rs @@ -12,6 +12,7 @@ #![feature(associated_type_bounds)] #![feature(exhaustive_patterns)] #![feature(iter_intersperse)] +#![feature(let_chains)] #![feature(min_specialization)] #![feature(never_type)] #![feature(rustc_attrs)] diff --git a/compiler/rustc_trait_selection/src/solve/alias_relate.rs b/compiler/rustc_trait_selection/src/solve/alias_relate.rs index 422a6ee3442..73362d82306 100644 --- a/compiler/rustc_trait_selection/src/solve/alias_relate.rs +++ b/compiler/rustc_trait_selection/src/solve/alias_relate.rs @@ -65,7 +65,7 @@ impl<'tcx> EvalCtxt<'_, 'tcx> { direction, Invert::Yes, )); - // Relate via substs + // Relate via args let subst_relate_response = self .assemble_subst_relate_candidate(param_env, alias_lhs, alias_rhs, direction); candidates.extend(subst_relate_response); @@ -153,7 +153,7 @@ impl<'tcx> EvalCtxt<'_, 'tcx> { alias_rhs: ty::AliasTy<'tcx>, direction: ty::AliasRelationDirection, ) -> QueryResult<'tcx> { - self.probe_candidate("substs relate").enter(|ecx| { + self.probe_candidate("args relate").enter(|ecx| { match direction { ty::AliasRelationDirection::Equate => { ecx.eq(param_env, alias_lhs, alias_rhs)?; diff --git a/compiler/rustc_trait_selection/src/solve/assembly/mod.rs b/compiler/rustc_trait_selection/src/solve/assembly/mod.rs index 28138054ae5..1e798998895 100644 --- a/compiler/rustc_trait_selection/src/solve/assembly/mod.rs +++ b/compiler/rustc_trait_selection/src/solve/assembly/mod.rs @@ -160,8 +160,8 @@ pub(super) trait GoalKind<'tcx>: Self::probe_and_match_goal_against_assumption(ecx, goal, assumption, |ecx| { let tcx = ecx.tcx(); let ty::Dynamic(bounds, _, _) = *goal.predicate.self_ty().kind() else { - bug!("expected object type in `consider_object_bound_candidate`"); - }; + bug!("expected object type in `consider_object_bound_candidate`"); + }; ecx.add_goals( structural_traits::predicates_for_object_candidate( &ecx, @@ -352,9 +352,7 @@ impl<'tcx> EvalCtxt<'_, 'tcx> { candidates: &mut Vec<Candidate<'tcx>>, ) { let tcx = self.tcx(); - let &ty::Alias(_, projection_ty) = goal.predicate.self_ty().kind() else { - return - }; + let &ty::Alias(_, projection_ty) = goal.predicate.self_ty().kind() else { return }; let normalized_self_candidates: Result<_, NoSolution> = self.probe(|_| CandidateKind::NormalizedSelfTyAssembly).enter(|ecx| { @@ -544,7 +542,8 @@ impl<'tcx> EvalCtxt<'_, 'tcx> { ty::Alias(ty::Projection | ty::Opaque, alias_ty) => alias_ty, }; - for assumption in self.tcx().item_bounds(alias_ty.def_id).subst(self.tcx(), alias_ty.substs) + for assumption in + self.tcx().item_bounds(alias_ty.def_id).instantiate(self.tcx(), alias_ty.args) { match G::consider_alias_bound_candidate(self, goal, assumption) { Ok(result) => { diff --git a/compiler/rustc_trait_selection/src/solve/assembly/structural_traits.rs b/compiler/rustc_trait_selection/src/solve/assembly/structural_traits.rs index 3bb8cad15ab..3a1302e46ba 100644 --- a/compiler/rustc_trait_selection/src/solve/assembly/structural_traits.rs +++ b/compiler/rustc_trait_selection/src/solve/assembly/structural_traits.rs @@ -51,36 +51,36 @@ pub(in crate::solve) fn instantiate_constituent_tys_for_auto_trait<'tcx>( Ok(tys.iter().collect()) } - ty::Closure(_, ref substs) => Ok(vec![substs.as_closure().tupled_upvars_ty()]), + ty::Closure(_, ref args) => Ok(vec![args.as_closure().tupled_upvars_ty()]), - ty::Generator(_, ref substs, _) => { - let generator_substs = substs.as_generator(); - Ok(vec![generator_substs.tupled_upvars_ty(), generator_substs.witness()]) + ty::Generator(_, ref args, _) => { + let generator_args = args.as_generator(); + Ok(vec![generator_args.tupled_upvars_ty(), generator_args.witness()]) } ty::GeneratorWitness(types) => Ok(ecx.instantiate_binder_with_placeholders(types).to_vec()), - ty::GeneratorWitnessMIR(def_id, substs) => Ok(ecx + ty::GeneratorWitnessMIR(def_id, args) => Ok(ecx .tcx() .generator_hidden_types(def_id) .map(|bty| { ecx.instantiate_binder_with_placeholders(replace_erased_lifetimes_with_bound_vars( tcx, - bty.subst(tcx, substs), + bty.instantiate(tcx, args), )) }) .collect()), // For `PhantomData<T>`, we pass `T`. - ty::Adt(def, substs) if def.is_phantom_data() => Ok(vec![substs.type_at(0)]), + ty::Adt(def, args) if def.is_phantom_data() => Ok(vec![args.type_at(0)]), - ty::Adt(def, substs) => Ok(def.all_fields().map(|f| f.ty(tcx, substs)).collect()), + ty::Adt(def, args) => Ok(def.all_fields().map(|f| f.ty(tcx, args)).collect()), - ty::Alias(ty::Opaque, ty::AliasTy { def_id, substs, .. }) => { + ty::Alias(ty::Opaque, ty::AliasTy { def_id, args, .. }) => { // We can resolve the `impl Trait` to its concrete type, // which enforces a DAG between the functions requiring // the auto trait bounds in question. - Ok(vec![tcx.type_of(def_id).subst(tcx, substs)]) + Ok(vec![tcx.type_of(def_id).instantiate(tcx, args)]) } } } @@ -146,9 +146,9 @@ pub(in crate::solve) fn instantiate_constituent_tys_for_sized_trait<'tcx>( ty::Tuple(tys) => Ok(tys.to_vec()), - ty::Adt(def, substs) => { + ty::Adt(def, args) => { let sized_crit = def.sized_constraint(ecx.tcx()); - Ok(sized_crit.subst_iter_copied(ecx.tcx(), substs).collect()) + Ok(sized_crit.arg_iter_copied(ecx.tcx(), args).collect()) } } } @@ -192,11 +192,11 @@ pub(in crate::solve) fn instantiate_constituent_tys_for_copy_clone_trait<'tcx>( ty::Tuple(tys) => Ok(tys.to_vec()), - ty::Closure(_, substs) => Ok(vec![substs.as_closure().tupled_upvars_ty()]), + ty::Closure(_, args) => Ok(vec![args.as_closure().tupled_upvars_ty()]), - ty::Generator(_, substs, Movability::Movable) => { + ty::Generator(_, args, Movability::Movable) => { if ecx.tcx().features().generator_clone { - let generator = substs.as_generator(); + let generator = args.as_generator(); Ok(vec![generator.tupled_upvars_ty(), generator.witness()]) } else { Err(NoSolution) @@ -205,13 +205,13 @@ pub(in crate::solve) fn instantiate_constituent_tys_for_copy_clone_trait<'tcx>( ty::GeneratorWitness(types) => Ok(ecx.instantiate_binder_with_placeholders(types).to_vec()), - ty::GeneratorWitnessMIR(def_id, substs) => Ok(ecx + ty::GeneratorWitnessMIR(def_id, args) => Ok(ecx .tcx() .generator_hidden_types(def_id) .map(|bty| { ecx.instantiate_binder_with_placeholders(replace_erased_lifetimes_with_bound_vars( ecx.tcx(), - bty.subst(ecx.tcx(), substs), + bty.instantiate(ecx.tcx(), args), )) }) .collect()), @@ -226,13 +226,13 @@ pub(in crate::solve) fn extract_tupled_inputs_and_output_from_callable<'tcx>( ) -> Result<Option<ty::Binder<'tcx, (Ty<'tcx>, Ty<'tcx>)>>, NoSolution> { match *self_ty.kind() { // keep this in sync with assemble_fn_pointer_candidates until the old solver is removed. - ty::FnDef(def_id, substs) => { + ty::FnDef(def_id, args) => { let sig = tcx.fn_sig(def_id); if sig.skip_binder().is_fn_trait_compatible() && tcx.codegen_fn_attrs(def_id).target_features.is_empty() { Ok(Some( - sig.subst(tcx, substs) + sig.instantiate(tcx, args) .map_bound(|sig| (Ty::new_tup(tcx, sig.inputs()), sig.output())), )) } else { @@ -247,9 +247,9 @@ pub(in crate::solve) fn extract_tupled_inputs_and_output_from_callable<'tcx>( Err(NoSolution) } } - ty::Closure(_, substs) => { - let closure_substs = substs.as_closure(); - match closure_substs.kind_ty().to_opt_closure_kind() { + ty::Closure(_, args) => { + let closure_args = args.as_closure(); + match closure_args.kind_ty().to_opt_closure_kind() { // If the closure's kind doesn't extend the goal kind, // then the closure doesn't implement the trait. Some(closure_kind) => { @@ -265,7 +265,7 @@ pub(in crate::solve) fn extract_tupled_inputs_and_output_from_callable<'tcx>( } } } - Ok(Some(closure_substs.sig().map_bound(|sig| (sig.inputs()[0], sig.output())))) + Ok(Some(closure_args.sig().map_bound(|sig| (sig.inputs()[0], sig.output())))) } ty::Bool | ty::Char @@ -347,13 +347,13 @@ pub(in crate::solve) fn predicates_for_object_candidate<'tcx>( let tcx = ecx.tcx(); let mut requirements = vec![]; requirements.extend( - tcx.super_predicates_of(trait_ref.def_id).instantiate(tcx, trait_ref.substs).predicates, + tcx.super_predicates_of(trait_ref.def_id).instantiate(tcx, trait_ref.args).predicates, ); for item in tcx.associated_items(trait_ref.def_id).in_definition_order() { // FIXME(associated_const_equality): Also add associated consts to // the requirements here. if item.kind == ty::AssocKind::Type { - requirements.extend(tcx.item_bounds(item.def_id).subst_iter(tcx, trait_ref.substs)); + requirements.extend(tcx.item_bounds(item.def_id).arg_iter(tcx, trait_ref.args)); } } diff --git a/compiler/rustc_trait_selection/src/solve/eval_ctxt.rs b/compiler/rustc_trait_selection/src/solve/eval_ctxt.rs index 74dfbdddbab..6e0aa08c307 100644 --- a/compiler/rustc_trait_selection/src/solve/eval_ctxt.rs +++ b/compiler/rustc_trait_selection/src/solve/eval_ctxt.rs @@ -116,7 +116,8 @@ impl NestedGoals<'_> { #[derive(PartialEq, Eq, Debug, Hash, HashStable, Clone, Copy)] pub enum GenerateProofTree { Yes(UseGlobalCache), - No, + IfEnabled, + Never, } #[derive(PartialEq, Eq, Debug, Hash, HashStable, Clone, Copy)] @@ -202,7 +203,7 @@ impl<'a, 'tcx> EvalCtxt<'a, 'tcx> { (&tree, infcx.tcx.sess.opts.unstable_opts.dump_solver_proof_tree) { let mut lock = std::io::stdout().lock(); - let _ = lock.write_fmt(format_args!("{tree:?}")); + let _ = lock.write_fmt(format_args!("{tree:?}\n")); let _ = lock.flush(); } @@ -430,11 +431,8 @@ impl<'a, 'tcx> EvalCtxt<'a, 'tcx> { ty::PredicateKind::Coerce(predicate) => { self.compute_coerce_goal(Goal { param_env, predicate }) } - ty::PredicateKind::ClosureKind(def_id, substs, kind) => self - .compute_closure_kind_goal(Goal { - param_env, - predicate: (def_id, substs, kind), - }), + ty::PredicateKind::ClosureKind(def_id, args, kind) => self + .compute_closure_kind_goal(Goal { param_env, predicate: (def_id, args, kind) }), ty::PredicateKind::ObjectSafe(trait_def_id) => { self.compute_object_safe_goal(trait_def_id) } @@ -774,24 +772,18 @@ impl<'tcx> EvalCtxt<'_, 'tcx> { self.infcx.resolve_vars_if_possible(value) } - pub(super) fn fresh_substs_for_item(&self, def_id: DefId) -> ty::SubstsRef<'tcx> { - self.infcx.fresh_substs_for_item(DUMMY_SP, def_id) + pub(super) fn fresh_args_for_item(&self, def_id: DefId) -> ty::GenericArgsRef<'tcx> { + self.infcx.fresh_args_for_item(DUMMY_SP, def_id) } - pub(super) fn translate_substs( + pub(super) fn translate_args( &self, param_env: ty::ParamEnv<'tcx>, source_impl: DefId, - source_substs: ty::SubstsRef<'tcx>, + source_args: ty::GenericArgsRef<'tcx>, target_node: specialization_graph::Node, - ) -> ty::SubstsRef<'tcx> { - crate::traits::translate_substs( - self.infcx, - param_env, - source_impl, - source_substs, - target_node, - ) + ) -> ty::GenericArgsRef<'tcx> { + crate::traits::translate_args(self.infcx, param_env, source_impl, source_args, target_node) } pub(super) fn register_ty_outlives(&self, ty: Ty<'tcx>, lt: ty::Region<'tcx>) { @@ -863,14 +855,14 @@ impl<'tcx> EvalCtxt<'_, 'tcx> { pub(super) fn add_item_bounds_for_hidden_type( &mut self, opaque_def_id: DefId, - opaque_substs: ty::SubstsRef<'tcx>, + opaque_args: ty::GenericArgsRef<'tcx>, param_env: ty::ParamEnv<'tcx>, hidden_ty: Ty<'tcx>, ) { let mut obligations = Vec::new(); self.infcx.add_item_bounds_for_hidden_type( opaque_def_id, - opaque_substs, + opaque_args, ObligationCause::dummy(), param_env, hidden_ty, @@ -896,13 +888,13 @@ impl<'tcx> EvalCtxt<'_, 'tcx> { continue; } values.extend(self.probe_candidate("opaque type storage").enter(|ecx| { - for (a, b) in std::iter::zip(candidate_key.substs, key.substs) { + for (a, b) in std::iter::zip(candidate_key.args, key.args) { ecx.eq(param_env, a, b)?; } ecx.eq(param_env, candidate_ty, ty)?; ecx.add_item_bounds_for_hidden_type( candidate_key.def_id.to_def_id(), - candidate_key.substs, + candidate_key.args, param_env, candidate_ty, ); diff --git a/compiler/rustc_trait_selection/src/solve/eval_ctxt/canonical.rs b/compiler/rustc_trait_selection/src/solve/eval_ctxt/canonical.rs index 637d458882c..9f58e66d04e 100644 --- a/compiler/rustc_trait_selection/src/solve/eval_ctxt/canonical.rs +++ b/compiler/rustc_trait_selection/src/solve/eval_ctxt/canonical.rs @@ -111,7 +111,7 @@ impl<'tcx> EvalCtxt<'_, 'tcx> { ) -> CanonicalResponse<'tcx> { let unconstrained_response = Response { var_values: CanonicalVarValues { - var_values: self.tcx().mk_substs_from_iter(self.var_values.var_values.iter().map( + var_values: self.tcx().mk_args_from_iter(self.var_values.var_values.iter().map( |arg| -> ty::GenericArg<'tcx> { match arg.unpack() { GenericArgKind::Lifetime(_) => self.next_region_infer().into(), @@ -250,7 +250,7 @@ impl<'tcx> EvalCtxt<'_, 'tcx> { } } - let var_values = self.tcx().mk_substs_from_iter(response.variables.iter().enumerate().map( + let var_values = self.tcx().mk_args_from_iter(response.variables.iter().enumerate().map( |(index, info)| { if info.universe() != ty::UniverseIndex::ROOT { // A variable from inside a binder of the query. While ideally these shouldn't diff --git a/compiler/rustc_trait_selection/src/solve/eval_ctxt/select.rs b/compiler/rustc_trait_selection/src/solve/eval_ctxt/select.rs index bf6cbef8c3b..a6d118d8cc2 100644 --- a/compiler/rustc_trait_selection/src/solve/eval_ctxt/select.rs +++ b/compiler/rustc_trait_selection/src/solve/eval_ctxt/select.rs @@ -1,17 +1,18 @@ use std::ops::ControlFlow; +use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_infer::infer::{DefineOpaqueTypes, InferCtxt, InferOk}; use rustc_infer::traits::util::supertraits; use rustc_infer::traits::{ - Obligation, PolyTraitObligation, PredicateObligation, Selection, SelectionResult, + Obligation, PolyTraitObligation, PredicateObligation, Selection, SelectionResult, TraitEngine, }; use rustc_middle::traits::solve::{CanonicalInput, Certainty, Goal}; use rustc_middle::traits::{ ImplSource, ImplSourceObjectData, ImplSourceTraitUpcastingData, ImplSourceUserDefinedData, ObligationCause, SelectionError, }; -use rustc_middle::ty::{self, TyCtxt}; +use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_span::DUMMY_SP; use crate::solve::assembly::{BuiltinImplSource, Candidate, CandidateSource}; @@ -19,6 +20,8 @@ use crate::solve::eval_ctxt::{EvalCtxt, GenerateProofTree}; use crate::solve::inspect::ProofTreeBuilder; use crate::solve::search_graph::OverflowHandler; use crate::traits::vtable::{count_own_vtable_entries, prepare_vtable_segments, VtblSegment}; +use crate::traits::StructurallyNormalizeExt; +use crate::traits::TraitEngineExt; pub trait InferCtxtSelectExt<'tcx> { fn select_in_new_trait_solver( @@ -40,7 +43,7 @@ impl<'tcx> InferCtxtSelectExt<'tcx> for InferCtxt<'tcx> { self.instantiate_binder_with_placeholders(obligation.predicate), ); - let (result, _) = EvalCtxt::enter_root(self, GenerateProofTree::No, |ecx| { + let (result, _) = EvalCtxt::enter_root(self, GenerateProofTree::Never, |ecx| { let goal = Goal::new(ecx.tcx(), trait_goal.param_env, trait_goal.predicate); let (orig_values, canonical_goal) = ecx.canonicalize_goal(goal); let mut candidates = ecx.compute_canonical_trait_candidates(canonical_goal); @@ -113,6 +116,12 @@ impl<'tcx> InferCtxtSelectExt<'tcx> for InferCtxt<'tcx> { ), ) => rematch_object(self, goal, nested_obligations), + (Certainty::Maybe(_), CandidateSource::BuiltinImpl(BuiltinImplSource::Misc)) + if self.tcx.lang_items().unsize_trait() == Some(goal.predicate.def_id()) => + { + rematch_unsize(self, goal, nested_obligations) + } + // Technically some builtin impls have nested obligations, but if // `Certainty::Yes`, then they should've all been verified and don't // need re-checking. @@ -195,8 +204,9 @@ fn rematch_impl<'tcx>( impl_def_id: DefId, mut nested: Vec<PredicateObligation<'tcx>>, ) -> SelectionResult<'tcx, Selection<'tcx>> { - let substs = infcx.fresh_substs_for_item(DUMMY_SP, impl_def_id); - let impl_trait_ref = infcx.tcx.impl_trait_ref(impl_def_id).unwrap().subst(infcx.tcx, substs); + let args = infcx.fresh_args_for_item(DUMMY_SP, impl_def_id); + let impl_trait_ref = + infcx.tcx.impl_trait_ref(impl_def_id).unwrap().instantiate(infcx.tcx, args); nested.extend( infcx @@ -207,12 +217,12 @@ fn rematch_impl<'tcx>( ); nested.extend( - infcx.tcx.predicates_of(impl_def_id).instantiate(infcx.tcx, substs).into_iter().map( + infcx.tcx.predicates_of(impl_def_id).instantiate(infcx.tcx, args).into_iter().map( |(pred, _)| Obligation::new(infcx.tcx, ObligationCause::dummy(), goal.param_env, pred), ), ); - Ok(Some(ImplSource::UserDefined(ImplSourceUserDefinedData { impl_def_id, substs, nested }))) + Ok(Some(ImplSource::UserDefined(ImplSourceUserDefinedData { impl_def_id, args, nested }))) } fn rematch_object<'tcx>( @@ -220,25 +230,30 @@ fn rematch_object<'tcx>( goal: Goal<'tcx, ty::TraitPredicate<'tcx>>, mut nested: Vec<PredicateObligation<'tcx>>, ) -> SelectionResult<'tcx, Selection<'tcx>> { - let self_ty = goal.predicate.self_ty(); - let ty::Dynamic(data, _, source_kind) = *self_ty.kind() - else { - bug!() - }; - let source_trait_ref = data.principal().unwrap().with_self_ty(infcx.tcx, self_ty); - - let (is_upcasting, target_trait_ref_unnormalized) = if Some(goal.predicate.def_id()) - == infcx.tcx.lang_items().unsize_trait() - { - assert_eq!(source_kind, ty::Dyn, "cannot upcast dyn*"); - if let ty::Dynamic(data, _, ty::Dyn) = goal.predicate.trait_ref.substs.type_at(1).kind() { - (true, data.principal().unwrap().with_self_ty(infcx.tcx, self_ty)) + let a_ty = structurally_normalize(goal.predicate.self_ty(), infcx, goal.param_env, &mut nested); + let ty::Dynamic(data, _, source_kind) = *a_ty.kind() else { bug!() }; + let source_trait_ref = data.principal().unwrap().with_self_ty(infcx.tcx, a_ty); + + let (is_upcasting, target_trait_ref_unnormalized) = + if Some(goal.predicate.def_id()) == infcx.tcx.lang_items().unsize_trait() { + assert_eq!(source_kind, ty::Dyn, "cannot upcast dyn*"); + let b_ty = structurally_normalize( + goal.predicate.trait_ref.args.type_at(1), + infcx, + goal.param_env, + &mut nested, + ); + if let ty::Dynamic(data, _, ty::Dyn) = *b_ty.kind() { + // FIXME: We also need to ensure that the source lifetime outlives the + // target lifetime. This doesn't matter for codegen, though, and only + // *really* matters if the goal's certainty is ambiguous. + (true, data.principal().unwrap().with_self_ty(infcx.tcx, a_ty)) + } else { + bug!() + } } else { - bug!() - } - } else { - (false, ty::Binder::dummy(goal.predicate.trait_ref)) - }; + (false, ty::Binder::dummy(goal.predicate.trait_ref)) + }; let mut target_trait_ref = None; for candidate_trait_ref in supertraits(infcx.tcx, source_trait_ref) { @@ -305,3 +320,157 @@ fn rematch_object<'tcx>( ImplSource::Object(ImplSourceObjectData { vtable_base, nested }) })) } + +/// The `Unsize` trait is particularly important to coercion, so we try rematch it. +/// NOTE: This must stay in sync with `consider_builtin_unsize_candidate` in trait +/// goal assembly in the solver, both for soundness and in order to avoid ICEs. +fn rematch_unsize<'tcx>( + infcx: &InferCtxt<'tcx>, + goal: Goal<'tcx, ty::TraitPredicate<'tcx>>, + mut nested: Vec<PredicateObligation<'tcx>>, +) -> SelectionResult<'tcx, Selection<'tcx>> { + let tcx = infcx.tcx; + let a_ty = goal.predicate.self_ty(); + let b_ty = goal.predicate.trait_ref.args.type_at(1); + + match (a_ty.kind(), b_ty.kind()) { + (_, &ty::Dynamic(data, region, ty::Dyn)) => { + // Check that the type implements all of the predicates of the def-id. + // (i.e. the principal, all of the associated types match, and any auto traits) + nested.extend(data.iter().map(|pred| { + Obligation::new( + infcx.tcx, + ObligationCause::dummy(), + goal.param_env, + pred.with_self_ty(tcx, a_ty), + ) + })); + // The type must be Sized to be unsized. + let sized_def_id = tcx.require_lang_item(hir::LangItem::Sized, None); + nested.push(Obligation::new( + infcx.tcx, + ObligationCause::dummy(), + goal.param_env, + ty::TraitRef::new(tcx, sized_def_id, [a_ty]), + )); + // The type must outlive the lifetime of the `dyn` we're unsizing into. + nested.push(Obligation::new( + infcx.tcx, + ObligationCause::dummy(), + goal.param_env, + ty::Binder::dummy(ty::OutlivesPredicate(a_ty, region)), + )); + } + // `[T; n]` -> `[T]` unsizing + (&ty::Array(a_elem_ty, ..), &ty::Slice(b_elem_ty)) => { + nested.extend( + infcx + .at(&ObligationCause::dummy(), goal.param_env) + .eq(DefineOpaqueTypes::No, a_elem_ty, b_elem_ty) + .expect("expected rematch to succeed") + .into_obligations(), + ); + } + // Struct unsizing `Struct<T>` -> `Struct<U>` where `T: Unsize<U>` + (&ty::Adt(a_def, a_args), &ty::Adt(b_def, b_args)) + if a_def.is_struct() && a_def.did() == b_def.did() => + { + let unsizing_params = tcx.unsizing_params_for_adt(a_def.did()); + // We must be unsizing some type parameters. This also implies + // that the struct has a tail field. + if unsizing_params.is_empty() { + bug!("expected rematch to succeed") + } + + let tail_field = a_def + .non_enum_variant() + .fields + .raw + .last() + .expect("expected unsized ADT to have a tail field"); + let tail_field_ty = tcx.type_of(tail_field.did); + + let a_tail_ty = tail_field_ty.instantiate(tcx, a_args); + let b_tail_ty = tail_field_ty.instantiate(tcx, b_args); + + // Substitute just the unsizing params from B into A. The type after + // this substitution must be equal to B. This is so we don't unsize + // unrelated type parameters. + let new_a_args = tcx.mk_args_from_iter( + a_args + .iter() + .enumerate() + .map(|(i, a)| if unsizing_params.contains(i as u32) { b_args[i] } else { a }), + ); + let unsized_a_ty = Ty::new_adt(tcx, a_def, new_a_args); + + nested.extend( + infcx + .at(&ObligationCause::dummy(), goal.param_env) + .eq(DefineOpaqueTypes::No, unsized_a_ty, b_ty) + .expect("expected rematch to succeed") + .into_obligations(), + ); + + // Finally, we require that `TailA: Unsize<TailB>` for the tail field + // types. + nested.push(Obligation::new( + tcx, + ObligationCause::dummy(), + goal.param_env, + ty::TraitRef::new(tcx, goal.predicate.def_id(), [a_tail_ty, b_tail_ty]), + )); + } + // Tuple unsizing `(.., T)` -> `(.., U)` where `T: Unsize<U>` + (&ty::Tuple(a_tys), &ty::Tuple(b_tys)) + if a_tys.len() == b_tys.len() && !a_tys.is_empty() => + { + let (a_last_ty, a_rest_tys) = a_tys.split_last().unwrap(); + let b_last_ty = b_tys.last().unwrap(); + + // Substitute just the tail field of B., and require that they're equal. + let unsized_a_ty = + Ty::new_tup_from_iter(tcx, a_rest_tys.iter().chain([b_last_ty]).copied()); + nested.extend( + infcx + .at(&ObligationCause::dummy(), goal.param_env) + .eq(DefineOpaqueTypes::No, unsized_a_ty, b_ty) + .expect("expected rematch to succeed") + .into_obligations(), + ); + + // Similar to ADTs, require that the rest of the fields are equal. + nested.push(Obligation::new( + tcx, + ObligationCause::dummy(), + goal.param_env, + ty::TraitRef::new(tcx, goal.predicate.def_id(), [*a_last_ty, *b_last_ty]), + )); + } + // FIXME: We *could* ICE here if either: + // 1. the certainty is `Certainty::Yes`, + // 2. we're in codegen (which should mean `Certainty::Yes`). + _ => return Ok(None), + } + + Ok(Some(ImplSource::Builtin(nested))) +} + +fn structurally_normalize<'tcx>( + ty: Ty<'tcx>, + infcx: &InferCtxt<'tcx>, + param_env: ty::ParamEnv<'tcx>, + nested: &mut Vec<PredicateObligation<'tcx>>, +) -> Ty<'tcx> { + if matches!(ty.kind(), ty::Alias(..)) { + let mut engine = <dyn TraitEngine<'tcx>>::new(infcx); + let normalized_ty = infcx + .at(&ObligationCause::dummy(), param_env) + .structurally_normalize(ty, &mut *engine) + .expect("normalization shouldn't fail if we got to here"); + nested.extend(engine.pending_obligations()); + normalized_ty + } else { + ty + } +} diff --git a/compiler/rustc_trait_selection/src/solve/fulfill.rs b/compiler/rustc_trait_selection/src/solve/fulfill.rs index 88ee14c4db5..f1d3091225c 100644 --- a/compiler/rustc_trait_selection/src/solve/fulfill.rs +++ b/compiler/rustc_trait_selection/src/solve/fulfill.rs @@ -57,7 +57,7 @@ impl<'tcx> TraitEngine<'tcx> for FulfillmentCtxt<'tcx> { .map(|obligation| { let code = infcx.probe(|_| { match infcx - .evaluate_root_goal(obligation.clone().into(), GenerateProofTree::No) + .evaluate_root_goal(obligation.clone().into(), GenerateProofTree::IfEnabled) .0 { Ok((_, Certainty::Maybe(MaybeCause::Ambiguity), _)) => { @@ -96,7 +96,7 @@ impl<'tcx> TraitEngine<'tcx> for FulfillmentCtxt<'tcx> { for obligation in mem::take(&mut self.obligations) { let goal = obligation.clone().into(); let (changed, certainty, nested_goals) = - match infcx.evaluate_root_goal(goal, GenerateProofTree::No).0 { + match infcx.evaluate_root_goal(goal, GenerateProofTree::IfEnabled).0 { Ok(result) => result, Err(NoSolution) => { errors.push(FulfillmentError { diff --git a/compiler/rustc_trait_selection/src/solve/inherent_projection.rs b/compiler/rustc_trait_selection/src/solve/inherent_projection.rs new file mode 100644 index 00000000000..d10a14ff742 --- /dev/null +++ b/compiler/rustc_trait_selection/src/solve/inherent_projection.rs @@ -0,0 +1,44 @@ +use rustc_middle::traits::solve::{Certainty, Goal, QueryResult}; +use rustc_middle::ty; + +use super::EvalCtxt; + +impl<'tcx> EvalCtxt<'_, 'tcx> { + pub(super) fn normalize_inherent_associated_type( + &mut self, + goal: Goal<'tcx, ty::ProjectionPredicate<'tcx>>, + ) -> QueryResult<'tcx> { + let tcx = self.tcx(); + let inherent = goal.predicate.projection_ty; + let expected = goal.predicate.term.ty().expect("inherent consts are treated separately"); + + let impl_def_id = tcx.parent(inherent.def_id); + let impl_substs = self.fresh_args_for_item(impl_def_id); + + // Equate impl header and add impl where clauses + self.eq( + goal.param_env, + inherent.self_ty(), + tcx.type_of(impl_def_id).instantiate(tcx, impl_substs), + )?; + + // Equate IAT with the RHS of the project goal + let inherent_substs = inherent.rebase_inherent_args_onto_impl(impl_substs, tcx); + self.eq( + goal.param_env, + expected, + tcx.type_of(inherent.def_id).instantiate(tcx, inherent_substs), + ) + .expect("expected goal term to be fully unconstrained"); + + // Check both where clauses on the impl and IAT + self.add_goals( + tcx.predicates_of(inherent.def_id) + .instantiate(tcx, inherent_substs) + .into_iter() + .map(|(pred, _)| goal.with(tcx, pred)), + ); + + self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes) + } +} diff --git a/compiler/rustc_trait_selection/src/solve/inspect.rs b/compiler/rustc_trait_selection/src/solve/inspect.rs index 2d6717fdad9..cda68396321 100644 --- a/compiler/rustc_trait_selection/src/solve/inspect.rs +++ b/compiler/rustc_trait_selection/src/solve/inspect.rs @@ -200,30 +200,23 @@ impl<'tcx> ProofTreeBuilder<'tcx> { tcx: TyCtxt<'tcx>, generate_proof_tree: GenerateProofTree, ) -> ProofTreeBuilder<'tcx> { - let generate_proof_tree = match ( - tcx.sess.opts.unstable_opts.dump_solver_proof_tree, - tcx.sess.opts.unstable_opts.dump_solver_proof_tree_use_cache, - generate_proof_tree, - ) { - (_, Some(use_cache), GenerateProofTree::Yes(_)) => { - GenerateProofTree::Yes(UseGlobalCache::from_bool(use_cache)) - } - - (DumpSolverProofTree::Always, use_cache, GenerateProofTree::No) => { - let use_cache = use_cache.unwrap_or(true); - GenerateProofTree::Yes(UseGlobalCache::from_bool(use_cache)) - } - - (_, None, GenerateProofTree::Yes(_)) => generate_proof_tree, - (DumpSolverProofTree::Never, _, _) => generate_proof_tree, - (DumpSolverProofTree::OnError, _, _) => generate_proof_tree, - }; - match generate_proof_tree { - GenerateProofTree::No => ProofTreeBuilder::new_noop(), - GenerateProofTree::Yes(global_cache_disabled) => { - ProofTreeBuilder::new_root(global_cache_disabled) + GenerateProofTree::Never => ProofTreeBuilder::new_noop(), + GenerateProofTree::IfEnabled => { + let opts = &tcx.sess.opts.unstable_opts; + match opts.dump_solver_proof_tree { + DumpSolverProofTree::Always => { + let use_cache = opts.dump_solver_proof_tree_use_cache.unwrap_or(true); + ProofTreeBuilder::new_root(UseGlobalCache::from_bool(use_cache)) + } + // `OnError` is handled by reevaluating goals in error + // reporting with `GenerateProofTree::Yes`. + DumpSolverProofTree::OnError | DumpSolverProofTree::Never => { + ProofTreeBuilder::new_noop() + } + } } + GenerateProofTree::Yes(use_cache) => ProofTreeBuilder::new_root(use_cache), } } diff --git a/compiler/rustc_trait_selection/src/solve/mod.rs b/compiler/rustc_trait_selection/src/solve/mod.rs index 77809d8d2ba..7c15c3c0e8b 100644 --- a/compiler/rustc_trait_selection/src/solve/mod.rs +++ b/compiler/rustc_trait_selection/src/solve/mod.rs @@ -25,6 +25,7 @@ mod assembly; mod canonicalize; mod eval_ctxt; mod fulfill; +mod inherent_projection; pub mod inspect; mod normalize; mod opaques; @@ -37,7 +38,7 @@ pub use eval_ctxt::{ EvalCtxt, GenerateProofTree, InferCtxtEvalExt, InferCtxtSelectExt, UseGlobalCache, }; pub use fulfill::FulfillmentCtxt; -pub(crate) use normalize::deeply_normalize; +pub(crate) use normalize::{deeply_normalize, deeply_normalize_with_skipped_universes}; #[derive(Debug, Clone, Copy)] enum SolverMode { @@ -123,10 +124,10 @@ impl<'a, 'tcx> EvalCtxt<'a, 'tcx> { #[instrument(level = "debug", skip(self))] fn compute_closure_kind_goal( &mut self, - goal: Goal<'tcx, (DefId, ty::SubstsRef<'tcx>, ty::ClosureKind)>, + goal: Goal<'tcx, (DefId, ty::GenericArgsRef<'tcx>, ty::ClosureKind)>, ) -> QueryResult<'tcx> { - let (_, substs, expected_kind) = goal.predicate; - let found_kind = substs.as_closure().kind_ty().to_opt_closure_kind(); + let (_, args, expected_kind) = goal.predicate; + let found_kind = args.as_closure().kind_ty().to_opt_closure_kind(); let Some(found_kind) = found_kind else { return self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS); @@ -266,12 +267,11 @@ impl<'tcx> EvalCtxt<'_, 'tcx> { return Err(NoSolution); } - let Certainty::Maybe(maybe_cause) = responses.iter().fold( - Certainty::AMBIGUOUS, - |certainty, response| { + let Certainty::Maybe(maybe_cause) = + responses.iter().fold(Certainty::AMBIGUOUS, |certainty, response| { certainty.unify_with(response.value.certainty) - }, - ) else { + }) + else { bug!("expected flounder response to be ambiguous") }; diff --git a/compiler/rustc_trait_selection/src/solve/normalize.rs b/compiler/rustc_trait_selection/src/solve/normalize.rs index c388850d831..f51f4edb933 100644 --- a/compiler/rustc_trait_selection/src/solve/normalize.rs +++ b/compiler/rustc_trait_selection/src/solve/normalize.rs @@ -20,8 +20,22 @@ pub(crate) fn deeply_normalize<'tcx, T: TypeFoldable<TyCtxt<'tcx>>>( at: At<'_, 'tcx>, value: T, ) -> Result<T, Vec<FulfillmentError<'tcx>>> { + assert!(!value.has_escaping_bound_vars()); + deeply_normalize_with_skipped_universes(at, value, vec![]) +} + +/// Deeply normalize all aliases in `value`. This does not handle inference and expects +/// its input to be already fully resolved. +/// +/// Additionally takes a list of universes which represents the binders which have been +/// entered before passing `value` to the function. +pub(crate) fn deeply_normalize_with_skipped_universes<'tcx, T: TypeFoldable<TyCtxt<'tcx>>>( + at: At<'_, 'tcx>, + value: T, + universes: Vec<Option<UniverseIndex>>, +) -> Result<T, Vec<FulfillmentError<'tcx>>> { let fulfill_cx = FulfillmentCtxt::new(at.infcx); - let mut folder = NormalizationFolder { at, fulfill_cx, depth: 0, universes: Vec::new() }; + let mut folder = NormalizationFolder { at, fulfill_cx, depth: 0, universes }; value.try_fold_with(&mut folder) } @@ -117,7 +131,7 @@ impl<'tcx> NormalizationFolder<'_, 'tcx> { self.at.cause.clone(), self.at.param_env, ty::Binder::dummy(ty::ProjectionPredicate { - projection_ty: tcx.mk_alias_ty(uv.def, uv.substs), + projection_ty: tcx.mk_alias_ty(uv.def, uv.args), term: new_infer_ct.into(), }), ); diff --git a/compiler/rustc_trait_selection/src/solve/opaques.rs b/compiler/rustc_trait_selection/src/solve/opaques.rs index 16194f5ad69..2e537d1c358 100644 --- a/compiler/rustc_trait_selection/src/solve/opaques.rs +++ b/compiler/rustc_trait_selection/src/solve/opaques.rs @@ -26,8 +26,8 @@ impl<'tcx> EvalCtxt<'_, 'tcx> { if !self.can_define_opaque_ty(opaque_ty_def_id) { return Err(NoSolution); } - // FIXME: This may have issues when the substs contain aliases... - match self.tcx().uses_unique_placeholders_ignoring_regions(opaque_ty.substs) { + // FIXME: This may have issues when the args contain aliases... + match self.tcx().uses_unique_placeholders_ignoring_regions(opaque_ty.args) { Err(NotUniqueParam::NotParam(param)) if param.is_non_region_infer() => { return self.evaluate_added_goals_and_make_canonical_response( Certainty::AMBIGUOUS, @@ -40,7 +40,7 @@ impl<'tcx> EvalCtxt<'_, 'tcx> { } // Prefer opaques registered already. let opaque_type_key = - ty::OpaqueTypeKey { def_id: opaque_ty_def_id, substs: opaque_ty.substs }; + ty::OpaqueTypeKey { def_id: opaque_ty_def_id, args: opaque_ty.args }; let matches = self.unify_existing_opaque_tys(goal.param_env, opaque_type_key, expected); if !matches.is_empty() { @@ -54,7 +54,7 @@ impl<'tcx> EvalCtxt<'_, 'tcx> { self.insert_hidden_type(opaque_type_key, goal.param_env, expected)?; self.add_item_bounds_for_hidden_type( opaque_ty.def_id, - opaque_ty.substs, + opaque_ty.args, goal.param_env, expected, ); @@ -65,7 +65,7 @@ impl<'tcx> EvalCtxt<'_, 'tcx> { // e.g. assigning `impl Copy := NotCopy` self.add_item_bounds_for_hidden_type( opaque_ty.def_id, - opaque_ty.substs, + opaque_ty.args, goal.param_env, expected, ); @@ -73,7 +73,7 @@ impl<'tcx> EvalCtxt<'_, 'tcx> { } (Reveal::All, _) => { // FIXME: Add an assertion that opaque type storage is empty. - let actual = tcx.type_of(opaque_ty.def_id).subst(tcx, opaque_ty.substs); + let actual = tcx.type_of(opaque_ty.def_id).instantiate(tcx, opaque_ty.args); self.eq(goal.param_env, expected, actual)?; self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes) } diff --git a/compiler/rustc_trait_selection/src/solve/project_goals.rs b/compiler/rustc_trait_selection/src/solve/project_goals.rs index e53b784a756..d677fbdc7f4 100644 --- a/compiler/rustc_trait_selection/src/solve/project_goals.rs +++ b/compiler/rustc_trait_selection/src/solve/project_goals.rs @@ -48,7 +48,7 @@ impl<'tcx> EvalCtxt<'_, 'tcx> { self.merge_candidates(candidates) } ty::AssocItemContainer::ImplContainer => { - bug!("IATs not supported here yet") + self.normalize_inherent_associated_type(goal) } } } else { @@ -72,7 +72,7 @@ impl<'tcx> EvalCtxt<'_, 'tcx> { goal.param_env, ty::UnevaluatedConst::new( goal.predicate.projection_ty.def_id, - goal.predicate.projection_ty.substs, + goal.predicate.projection_ty.args, ), self.tcx() .type_of(goal.predicate.projection_ty.def_id) @@ -112,6 +112,7 @@ impl<'tcx> assembly::GoalKind<'tcx> for ProjectionPredicate<'tcx> { ) -> QueryResult<'tcx> { if let Some(projection_pred) = assumption.as_projection_clause() { if projection_pred.projection_def_id() == goal.predicate.def_id() { + let tcx = ecx.tcx(); ecx.probe_candidate("assumption").enter(|ecx| { let assumption_projection_pred = ecx.instantiate_binder_with_infer(projection_pred); @@ -122,6 +123,14 @@ impl<'tcx> assembly::GoalKind<'tcx> for ProjectionPredicate<'tcx> { )?; ecx.eq(goal.param_env, goal.predicate.term, assumption_projection_pred.term) .expect("expected goal term to be fully unconstrained"); + + // Add GAT where clauses from the trait's definition + ecx.add_goals( + tcx.predicates_of(goal.predicate.def_id()) + .instantiate_own(tcx, goal.predicate.projection_ty.args) + .map(|(pred, _)| goal.with(tcx, pred)), + ); + then(ecx) }) } else { @@ -142,93 +151,99 @@ impl<'tcx> assembly::GoalKind<'tcx> for ProjectionPredicate<'tcx> { let goal_trait_ref = goal.predicate.projection_ty.trait_ref(tcx); let impl_trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap(); let drcx = DeepRejectCtxt { treat_obligation_params: TreatParams::ForLookup }; - if !drcx.substs_refs_may_unify(goal_trait_ref.substs, impl_trait_ref.skip_binder().substs) { + if !drcx.args_refs_may_unify(goal_trait_ref.args, impl_trait_ref.skip_binder().args) { return Err(NoSolution); } - ecx.probe( - |r| CandidateKind::Candidate { name: "impl".into(), result: *r }).enter( - |ecx| { - let impl_substs = ecx.fresh_substs_for_item(impl_def_id); - let impl_trait_ref = impl_trait_ref.subst(tcx, impl_substs); - - ecx.eq(goal.param_env, goal_trait_ref, impl_trait_ref)?; - - let where_clause_bounds = tcx - .predicates_of(impl_def_id) - .instantiate(tcx, impl_substs) - .predicates - .into_iter() - .map(|pred| goal.with(tcx, pred)); - ecx.add_goals(where_clause_bounds); - - // In case the associated item is hidden due to specialization, we have to - // return ambiguity this would otherwise be incomplete, resulting in - // unsoundness during coherence (#105782). - let Some(assoc_def) = fetch_eligible_assoc_item_def( - ecx, - goal.param_env, - goal_trait_ref, - goal.predicate.def_id(), - impl_def_id - )? else { - return ecx.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS); - }; - - if !assoc_def.item.defaultness(tcx).has_value() { - let guar = tcx.sess.delay_span_bug( - tcx.def_span(assoc_def.item.def_id), - "missing value for assoc item in impl", - ); - let error_term = match assoc_def.item.kind { - ty::AssocKind::Const => ty::Const::new_error(tcx, - guar, - tcx.type_of(goal.predicate.def_id()) - .subst(tcx, goal.predicate.projection_ty.substs), - ) - .into(), - ty::AssocKind::Type => Ty::new_error(tcx,guar).into(), - ty::AssocKind::Fn => unreachable!(), - }; - ecx.eq(goal.param_env, goal.predicate.term, error_term) - .expect("expected goal term to be fully unconstrained"); - return ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes); - } + ecx.probe(|r| CandidateKind::Candidate { name: "impl".into(), result: *r }).enter(|ecx| { + let impl_args = ecx.fresh_args_for_item(impl_def_id); + let impl_trait_ref = impl_trait_ref.instantiate(tcx, impl_args); + + ecx.eq(goal.param_env, goal_trait_ref, impl_trait_ref)?; + + let where_clause_bounds = tcx + .predicates_of(impl_def_id) + .instantiate(tcx, impl_args) + .predicates + .into_iter() + .map(|pred| goal.with(tcx, pred)); + ecx.add_goals(where_clause_bounds); + + // Add GAT where clauses from the trait's definition + ecx.add_goals( + tcx.predicates_of(goal.predicate.def_id()) + .instantiate_own(tcx, goal.predicate.projection_ty.args) + .map(|(pred, _)| goal.with(tcx, pred)), + ); + + // In case the associated item is hidden due to specialization, we have to + // return ambiguity this would otherwise be incomplete, resulting in + // unsoundness during coherence (#105782). + let Some(assoc_def) = fetch_eligible_assoc_item_def( + ecx, + goal.param_env, + goal_trait_ref, + goal.predicate.def_id(), + impl_def_id, + )? + else { + return ecx.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS); + }; - // Getting the right substitutions here is complex, e.g. given: - // - a goal `<Vec<u32> as Trait<i32>>::Assoc<u64>` - // - the applicable impl `impl<T> Trait<i32> for Vec<T>` - // - and the impl which defines `Assoc` being `impl<T, U> Trait<U> for Vec<T>` - // - // We first rebase the goal substs onto the impl, going from `[Vec<u32>, i32, u64]` - // to `[u32, u64]`. - // - // And then map these substs to the substs of the defining impl of `Assoc`, going - // from `[u32, u64]` to `[u32, i32, u64]`. - let impl_substs_with_gat = goal.predicate.projection_ty.substs.rebase_onto( - tcx, - goal_trait_ref.def_id, - impl_substs, + if !assoc_def.item.defaultness(tcx).has_value() { + let guar = tcx.sess.delay_span_bug( + tcx.def_span(assoc_def.item.def_id), + "missing value for assoc item in impl", ); - let substs = ecx.translate_substs( - goal.param_env, - impl_def_id, - impl_substs_with_gat, - assoc_def.defining_node, - ); - - // Finally we construct the actual value of the associated type. - let term = match assoc_def.item.kind { - ty::AssocKind::Type => tcx.type_of(assoc_def.item.def_id).map_bound(|ty| ty.into()), - ty::AssocKind::Const => bug!("associated const projection is not supported yet"), - ty::AssocKind::Fn => unreachable!("we should never project to a fn"), + let error_term = match assoc_def.item.kind { + ty::AssocKind::Const => ty::Const::new_error( + tcx, + guar, + tcx.type_of(goal.predicate.def_id()) + .instantiate(tcx, goal.predicate.projection_ty.args), + ) + .into(), + ty::AssocKind::Type => Ty::new_error(tcx, guar).into(), + ty::AssocKind::Fn => unreachable!(), }; - - ecx.eq(goal.param_env, goal.predicate.term, term.subst(tcx, substs)) + ecx.eq(goal.param_env, goal.predicate.term, error_term) .expect("expected goal term to be fully unconstrained"); - ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes) - }, - ) + return ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes); + } + + // Getting the right args here is complex, e.g. given: + // - a goal `<Vec<u32> as Trait<i32>>::Assoc<u64>` + // - the applicable impl `impl<T> Trait<i32> for Vec<T>` + // - and the impl which defines `Assoc` being `impl<T, U> Trait<U> for Vec<T>` + // + // We first rebase the goal args onto the impl, going from `[Vec<u32>, i32, u64]` + // to `[u32, u64]`. + // + // And then map these args to the args of the defining impl of `Assoc`, going + // from `[u32, u64]` to `[u32, i32, u64]`. + let impl_args_with_gat = goal.predicate.projection_ty.args.rebase_onto( + tcx, + goal_trait_ref.def_id, + impl_args, + ); + let args = ecx.translate_args( + goal.param_env, + impl_def_id, + impl_args_with_gat, + assoc_def.defining_node, + ); + + // Finally we construct the actual value of the associated type. + let term = match assoc_def.item.kind { + ty::AssocKind::Type => tcx.type_of(assoc_def.item.def_id).map_bound(|ty| ty.into()), + ty::AssocKind::Const => bug!("associated const projection is not supported yet"), + ty::AssocKind::Fn => unreachable!("we should never project to a fn"), + }; + + ecx.eq(goal.param_env, goal.predicate.term, term.instantiate(tcx, args)) + .expect("expected goal term to be fully unconstrained"); + ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes) + }) } fn consider_auto_trait_candidate( @@ -350,7 +365,7 @@ impl<'tcx> assembly::GoalKind<'tcx> for ProjectionPredicate<'tcx> { ty::Dynamic(_, _, _) => { let dyn_metadata = tcx.require_lang_item(LangItem::DynMetadata, None); tcx.type_of(dyn_metadata) - .subst(tcx, &[ty::GenericArg::from(goal.predicate.self_ty())]) + .instantiate(tcx, &[ty::GenericArg::from(goal.predicate.self_ty())]) } ty::Alias(_, _) | ty::Param(_) | ty::Placeholder(..) => { @@ -365,20 +380,18 @@ impl<'tcx> assembly::GoalKind<'tcx> for ProjectionPredicate<'tcx> { tcx.types.unit } - ty::Adt(def, substs) if def.is_struct() => { - match def.non_enum_variant().tail_opt() { - None => tcx.types.unit, - Some(field_def) => { - let self_ty = field_def.ty(tcx, substs); - ecx.add_goal(goal.with( - tcx, - ty::Binder::dummy(goal.predicate.with_self_ty(tcx, self_ty)), - )); - return ecx - .evaluate_added_goals_and_make_canonical_response(Certainty::Yes); - } + ty::Adt(def, args) if def.is_struct() => match def.non_enum_variant().tail_opt() { + None => tcx.types.unit, + Some(field_def) => { + let self_ty = field_def.ty(tcx, args); + ecx.add_goal(goal.with( + tcx, + ty::Binder::dummy(goal.predicate.with_self_ty(tcx, self_ty)), + )); + return ecx + .evaluate_added_goals_and_make_canonical_response(Certainty::Yes); } - } + }, ty::Adt(_, _) => tcx.types.unit, ty::Tuple(elements) => match elements.last() { @@ -413,7 +426,7 @@ impl<'tcx> assembly::GoalKind<'tcx> for ProjectionPredicate<'tcx> { goal: Goal<'tcx, Self>, ) -> QueryResult<'tcx> { let self_ty = goal.predicate.self_ty(); - let ty::Generator(def_id, substs, _) = *self_ty.kind() else { + let ty::Generator(def_id, args, _) = *self_ty.kind() else { return Err(NoSolution); }; @@ -423,7 +436,7 @@ impl<'tcx> assembly::GoalKind<'tcx> for ProjectionPredicate<'tcx> { return Err(NoSolution); } - let term = substs.as_generator().return_ty().into(); + let term = args.as_generator().return_ty().into(); Self::consider_implied_clause( ecx, @@ -444,7 +457,7 @@ impl<'tcx> assembly::GoalKind<'tcx> for ProjectionPredicate<'tcx> { goal: Goal<'tcx, Self>, ) -> QueryResult<'tcx> { let self_ty = goal.predicate.self_ty(); - let ty::Generator(def_id, substs, _) = *self_ty.kind() else { + let ty::Generator(def_id, args, _) = *self_ty.kind() else { return Err(NoSolution); }; @@ -454,7 +467,7 @@ impl<'tcx> assembly::GoalKind<'tcx> for ProjectionPredicate<'tcx> { return Err(NoSolution); } - let generator = substs.as_generator(); + let generator = args.as_generator(); let name = tcx.associated_item(goal.predicate.def_id()).name; let term = if name == sym::Return { diff --git a/compiler/rustc_trait_selection/src/solve/trait_goals.rs b/compiler/rustc_trait_selection/src/solve/trait_goals.rs index ef5f25b1f7f..e7867eead15 100644 --- a/compiler/rustc_trait_selection/src/solve/trait_goals.rs +++ b/compiler/rustc_trait_selection/src/solve/trait_goals.rs @@ -39,10 +39,9 @@ impl<'tcx> assembly::GoalKind<'tcx> for TraitPredicate<'tcx> { let impl_trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap(); let drcx = DeepRejectCtxt { treat_obligation_params: TreatParams::ForLookup }; - if !drcx.substs_refs_may_unify( - goal.predicate.trait_ref.substs, - impl_trait_ref.skip_binder().substs, - ) { + if !drcx + .args_refs_may_unify(goal.predicate.trait_ref.args, impl_trait_ref.skip_binder().args) + { return Err(NoSolution); } @@ -63,13 +62,13 @@ impl<'tcx> assembly::GoalKind<'tcx> for TraitPredicate<'tcx> { }; ecx.probe_candidate("impl").enter(|ecx| { - let impl_substs = ecx.fresh_substs_for_item(impl_def_id); - let impl_trait_ref = impl_trait_ref.subst(tcx, impl_substs); + let impl_args = ecx.fresh_args_for_item(impl_def_id); + let impl_trait_ref = impl_trait_ref.instantiate(tcx, impl_args); ecx.eq(goal.param_env, goal.predicate.trait_ref, impl_trait_ref)?; let where_clause_bounds = tcx .predicates_of(impl_def_id) - .instantiate(tcx, impl_substs) + .instantiate(tcx, impl_args) .predicates .into_iter() .map(|pred| goal.with(tcx, pred)); @@ -164,7 +163,7 @@ impl<'tcx> assembly::GoalKind<'tcx> for TraitPredicate<'tcx> { ecx.probe_candidate("trait alias").enter(|ecx| { let nested_obligations = tcx .predicates_of(goal.predicate.def_id()) - .instantiate(tcx, goal.predicate.trait_ref.substs); + .instantiate(tcx, goal.predicate.trait_ref.args); ecx.add_goals(nested_obligations.predicates.into_iter().map(|p| goal.with(tcx, p))); ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes) }) @@ -337,7 +336,7 @@ impl<'tcx> assembly::GoalKind<'tcx> for TraitPredicate<'tcx> { } let self_ty = goal.predicate.self_ty(); - let ty::Generator(def_id, substs, _) = *self_ty.kind() else { + let ty::Generator(def_id, args, _) = *self_ty.kind() else { return Err(NoSolution); }; @@ -347,7 +346,7 @@ impl<'tcx> assembly::GoalKind<'tcx> for TraitPredicate<'tcx> { return Err(NoSolution); } - let generator = substs.as_generator(); + let generator = args.as_generator(); Self::consider_implied_clause( ecx, goal, @@ -369,7 +368,7 @@ impl<'tcx> assembly::GoalKind<'tcx> for TraitPredicate<'tcx> { let tcx = ecx.tcx(); let a_ty = goal.predicate.self_ty(); - let b_ty = goal.predicate.trait_ref.substs.type_at(1); + let b_ty = goal.predicate.trait_ref.args.type_at(1); if b_ty.is_ty_var() { return ecx.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS); } @@ -378,7 +377,7 @@ impl<'tcx> assembly::GoalKind<'tcx> for TraitPredicate<'tcx> { // Trait upcasting, or `dyn Trait + Auto + 'a` -> `dyn Trait + 'b` (&ty::Dynamic(_, _, ty::Dyn), &ty::Dynamic(_, _, ty::Dyn)) => { // Dyn upcasting is handled separately, since due to upcasting, - // when there are two supertraits that differ by substs, we + // when there are two supertraits that differ by args, we // may return more than one query response. Err(NoSolution) } @@ -415,7 +414,7 @@ impl<'tcx> assembly::GoalKind<'tcx> for TraitPredicate<'tcx> { ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes) } // Struct unsizing `Struct<T>` -> `Struct<U>` where `T: Unsize<U>` - (&ty::Adt(a_def, a_substs), &ty::Adt(b_def, b_substs)) + (&ty::Adt(a_def, a_args), &ty::Adt(b_def, b_args)) if a_def.is_struct() && a_def.did() == b_def.did() => { let unsizing_params = tcx.unsizing_params_for_adt(a_def.did()); @@ -428,17 +427,17 @@ impl<'tcx> assembly::GoalKind<'tcx> for TraitPredicate<'tcx> { let tail_field = a_def.non_enum_variant().tail(); let tail_field_ty = tcx.type_of(tail_field.did); - let a_tail_ty = tail_field_ty.subst(tcx, a_substs); - let b_tail_ty = tail_field_ty.subst(tcx, b_substs); + let a_tail_ty = tail_field_ty.instantiate(tcx, a_args); + let b_tail_ty = tail_field_ty.instantiate(tcx, b_args); // Substitute just the unsizing params from B into A. The type after // this substitution must be equal to B. This is so we don't unsize // unrelated type parameters. - let new_a_substs = - tcx.mk_substs_from_iter(a_substs.iter().enumerate().map(|(i, a)| { - if unsizing_params.contains(i as u32) { b_substs[i] } else { a } + let new_a_args = + tcx.mk_args_from_iter(a_args.iter().enumerate().map(|(i, a)| { + if unsizing_params.contains(i as u32) { b_args[i] } else { a } })); - let unsized_a_ty = Ty::new_adt(tcx, a_def, new_a_substs); + let unsized_a_ty = Ty::new_adt(tcx, a_def, new_a_args); // Finally, we require that `TailA: Unsize<TailB>` for the tail field // types. @@ -484,7 +483,7 @@ impl<'tcx> assembly::GoalKind<'tcx> for TraitPredicate<'tcx> { let tcx = ecx.tcx(); let a_ty = goal.predicate.self_ty(); - let b_ty = goal.predicate.trait_ref.substs.type_at(1); + let b_ty = goal.predicate.trait_ref.args.type_at(1); let ty::Dynamic(a_data, a_region, ty::Dyn) = *a_ty.kind() else { return vec![]; }; @@ -598,19 +597,17 @@ impl<'tcx> assembly::GoalKind<'tcx> for TraitPredicate<'tcx> { // Erase regions because we compute layouts in `rustc_transmute`, // which will ICE for region vars. - let substs = ecx.tcx().erase_regions(goal.predicate.trait_ref.substs); + let args = ecx.tcx().erase_regions(goal.predicate.trait_ref.args); - let Some(assume) = rustc_transmute::Assume::from_const( - ecx.tcx(), - goal.param_env, - substs.const_at(3), - ) else { + let Some(assume) = + rustc_transmute::Assume::from_const(ecx.tcx(), goal.param_env, args.const_at(3)) + else { return Err(NoSolution); }; let certainty = ecx.is_transmutable( - rustc_transmute::Types { dst: substs.type_at(0), src: substs.type_at(1) }, - substs.type_at(2), + rustc_transmute::Types { dst: args.type_at(0), src: args.type_at(1) }, + args.type_at(2), assume, )?; ecx.evaluate_added_goals_and_make_canonical_response(certainty) diff --git a/compiler/rustc_trait_selection/src/solve/weak_types.rs b/compiler/rustc_trait_selection/src/solve/weak_types.rs index b095b54c554..c7717879a4a 100644 --- a/compiler/rustc_trait_selection/src/solve/weak_types.rs +++ b/compiler/rustc_trait_selection/src/solve/weak_types.rs @@ -12,8 +12,18 @@ impl<'tcx> EvalCtxt<'_, 'tcx> { let weak_ty = goal.predicate.projection_ty; let expected = goal.predicate.term.ty().expect("no such thing as a const alias"); - let actual = tcx.type_of(weak_ty.def_id).subst(tcx, weak_ty.substs); + let actual = tcx.type_of(weak_ty.def_id).instantiate(tcx, weak_ty.args); self.eq(goal.param_env, expected, actual)?; + + // Check where clauses + self.add_goals( + tcx.predicates_of(weak_ty.def_id) + .instantiate(tcx, weak_ty.args) + .predicates + .into_iter() + .map(|pred| goal.with(tcx, pred)), + ); + self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes) } } diff --git a/compiler/rustc_trait_selection/src/traits/auto_trait.rs b/compiler/rustc_trait_selection/src/traits/auto_trait.rs index cb38d0ac847..27cd0f99f34 100644 --- a/compiler/rustc_trait_selection/src/traits/auto_trait.rs +++ b/compiler/rustc_trait_selection/src/traits/auto_trait.rs @@ -152,14 +152,9 @@ impl<'tcx> AutoTraitFinder<'tcx> { // traits::project will see that 'T: SomeTrait' is in our ParamEnv, allowing // SelectionContext to return it back to us. - let Some((new_env, user_env)) = self.evaluate_predicates( - &infcx, - trait_did, - ty, - orig_env, - orig_env, - &mut fresh_preds, - ) else { + let Some((new_env, user_env)) = + self.evaluate_predicates(&infcx, trait_did, ty, orig_env, orig_env, &mut fresh_preds) + else { return AutoTraitResult::NegativeImpl; }; @@ -329,7 +324,7 @@ impl<'tcx> AutoTraitFinder<'tcx> { } Ok(None) => {} Err(SelectionError::Unimplemented) => { - if self.is_param_no_infer(pred.skip_binder().trait_ref.substs) { + if self.is_param_no_infer(pred.skip_binder().trait_ref.args) { already_visited.remove(&pred); self.add_user_pred(&mut user_computed_preds, pred.to_predicate(self.tcx)); predicates.push_back(pred); @@ -339,7 +334,7 @@ impl<'tcx> AutoTraitFinder<'tcx> { {:?} {:?} {:?}", ty, pred, - pred.skip_binder().trait_ref.substs + pred.skip_binder().trait_ref.args ); return None; } @@ -406,17 +401,17 @@ impl<'tcx> AutoTraitFinder<'tcx> { ) = (new_pred.kind().skip_binder(), old_pred.kind().skip_binder()) { if new_trait.def_id() == old_trait.def_id() { - let new_substs = new_trait.trait_ref.substs; - let old_substs = old_trait.trait_ref.substs; + let new_args = new_trait.trait_ref.args; + let old_args = old_trait.trait_ref.args; - if !new_substs.types().eq(old_substs.types()) { + if !new_args.types().eq(old_args.types()) { // We can't compare lifetimes if the types are different, // so skip checking `old_pred`. return true; } for (new_region, old_region) in - iter::zip(new_substs.regions(), old_substs.regions()) + iter::zip(new_args.regions(), old_args.regions()) { match (*new_region, *old_region) { // If both predicates have an `ReLateBound` (a HRTB) in the @@ -569,8 +564,8 @@ impl<'tcx> AutoTraitFinder<'tcx> { finished_map } - fn is_param_no_infer(&self, substs: SubstsRef<'_>) -> bool { - self.is_of_param(substs.type_at(0)) && !substs.types().any(|t| t.has_infer_types()) + fn is_param_no_infer(&self, args: GenericArgsRef<'_>) -> bool { + self.is_of_param(args.type_at(0)) && !args.types().any(|t| t.has_infer_types()) } pub fn is_of_param(&self, ty: Ty<'_>) -> bool { @@ -641,7 +636,7 @@ impl<'tcx> AutoTraitFinder<'tcx> { // an inference variable. // Additionally, we check if we've seen this predicate before, // to avoid rendering duplicate bounds to the user. - if self.is_param_no_infer(p.skip_binder().projection_ty.substs) + if self.is_param_no_infer(p.skip_binder().projection_ty.args) && !p.term().skip_binder().has_infer_types() && is_new_pred { diff --git a/compiler/rustc_trait_selection/src/traits/coherence.rs b/compiler/rustc_trait_selection/src/traits/coherence.rs index 1b1285e1b46..039e4ec9afd 100644 --- a/compiler/rustc_trait_selection/src/traits/coherence.rs +++ b/compiler/rustc_trait_selection/src/traits/coherence.rs @@ -96,9 +96,7 @@ pub fn overlapping_impls( let impl1_ref = tcx.impl_trait_ref(impl1_def_id); let impl2_ref = tcx.impl_trait_ref(impl2_def_id); let may_overlap = match (impl1_ref, impl2_ref) { - (Some(a), Some(b)) => { - drcx.substs_refs_may_unify(a.skip_binder().substs, b.skip_binder().substs) - } + (Some(a), Some(b)) => drcx.args_refs_may_unify(a.skip_binder().args, b.skip_binder().args), (None, None) => { let self_ty1 = tcx.type_of(impl1_def_id).skip_binder(); let self_ty2 = tcx.type_of(impl2_def_id).skip_binder(); @@ -143,15 +141,15 @@ fn with_fresh_ty_vars<'cx, 'tcx>( impl_def_id: DefId, ) -> ty::ImplHeader<'tcx> { let tcx = selcx.tcx(); - let impl_substs = selcx.infcx.fresh_substs_for_item(DUMMY_SP, impl_def_id); + let impl_args = selcx.infcx.fresh_args_for_item(DUMMY_SP, impl_def_id); let header = ty::ImplHeader { impl_def_id, - self_ty: tcx.type_of(impl_def_id).subst(tcx, impl_substs), - trait_ref: tcx.impl_trait_ref(impl_def_id).map(|i| i.subst(tcx, impl_substs)), + self_ty: tcx.type_of(impl_def_id).instantiate(tcx, impl_args), + trait_ref: tcx.impl_trait_ref(impl_def_id).map(|i| i.instantiate(tcx, impl_args)), predicates: tcx .predicates_of(impl_def_id) - .instantiate(tcx, impl_substs) + .instantiate(tcx, impl_args) .iter() .map(|(c, _)| c.as_predicate()) .collect(), @@ -353,7 +351,7 @@ fn impl_intersection_has_negative_obligation( &infcx, ObligationCause::dummy(), impl_env, - tcx.impl_subject(impl1_def_id).subst_identity(), + tcx.impl_subject(impl1_def_id).instantiate_identity(), ) { Ok(s) => s, Err(err) => { @@ -367,16 +365,16 @@ fn impl_intersection_has_negative_obligation( // Attempt to prove that impl2 applies, given all of the above. let selcx = &mut SelectionContext::new(&infcx); - let impl2_substs = infcx.fresh_substs_for_item(DUMMY_SP, impl2_def_id); + let impl2_args = infcx.fresh_args_for_item(DUMMY_SP, impl2_def_id); let (subject2, normalization_obligations) = - impl_subject_and_oblig(selcx, impl_env, impl2_def_id, impl2_substs, |_, _| { + impl_subject_and_oblig(selcx, impl_env, impl2_def_id, impl2_args, |_, _| { ObligationCause::dummy() }); // do the impls unify? If not, then it's not currently possible to prove any // obligations about their intersection. let Ok(InferOk { obligations: equate_obligations, .. }) = - infcx.at(&ObligationCause::dummy(), impl_env).eq(DefineOpaqueTypes::No,subject1, subject2) + infcx.at(&ObligationCause::dummy(), impl_env).eq(DefineOpaqueTypes::No, subject1, subject2) else { debug!("explicit_disjoint: {:?} does not unify with {:?}", subject1, subject2); return false; @@ -437,8 +435,7 @@ fn prove_negated_obligation<'tcx>( let body_def_id = body_def_id.as_local().unwrap_or(CRATE_DEF_ID); let ocx = ObligationCtxt::new(&infcx); - let Ok(wf_tys) = ocx.assumed_wf_types(param_env, body_def_id) - else { + let Ok(wf_tys) = ocx.assumed_wf_types(param_env, body_def_id) else { return false; }; @@ -520,7 +517,7 @@ pub enum OrphanCheckErr<'tcx> { pub fn orphan_check(tcx: TyCtxt<'_>, impl_def_id: DefId) -> Result<(), OrphanCheckErr<'_>> { // We only except this routine to be invoked on implementations // of a trait, not inherent implementations. - let trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap().subst_identity(); + let trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap().instantiate_identity(); debug!(?trait_ref); // If the *trait* is local to the crate, ok. @@ -729,11 +726,11 @@ impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for OrphanChecker<'tcx> { // For fundamental types, we just look inside of them. ty::Ref(_, ty, _) => ty.visit_with(self), - ty::Adt(def, substs) => { + ty::Adt(def, args) => { if self.def_id_is_local(def.did()) { ControlFlow::Break(OrphanCheckEarlyExit::LocalTy(ty)) } else if def.is_fundamental() { - substs.visit_with(self) + args.visit_with(self) } else { self.found_non_local_ty(ty) } diff --git a/compiler/rustc_trait_selection/src/traits/const_evaluatable.rs b/compiler/rustc_trait_selection/src/traits/const_evaluatable.rs index 8dc13b827e5..3d0d3812d0c 100644 --- a/compiler/rustc_trait_selection/src/traits/const_evaluatable.rs +++ b/compiler/rustc_trait_selection/src/traits/const_evaluatable.rs @@ -191,7 +191,7 @@ fn satisfied_from_param_env<'tcx>( if let ty::ConstKind::Expr(e) = c.kind() { e.visit_with(self) } else { - // FIXME(generic_const_exprs): This doesn't recurse into `<T as Trait<U>>::ASSOC`'s substs. + // FIXME(generic_const_exprs): This doesn't recurse into `<T as Trait<U>>::ASSOC`'s args. // This is currently unobservable as `<T as Trait<{ U + 1 }>>::ASSOC` creates an anon const // with its own `ConstEvaluatable` bound in the param env which we will visit separately. // diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/ambiguity.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/ambiguity.rs index f785c4eaf9d..fd813ca4ecb 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/ambiguity.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/ambiguity.rs @@ -26,8 +26,8 @@ pub fn recompute_applicable_impls<'tcx>( let obligation_trait_ref = ocx.normalize(&ObligationCause::dummy(), param_env, placeholder_obligation.trait_ref); - let impl_substs = infcx.fresh_substs_for_item(DUMMY_SP, impl_def_id); - let impl_trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap().subst(tcx, impl_substs); + let impl_args = infcx.fresh_args_for_item(DUMMY_SP, impl_def_id); + let impl_trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap().instantiate(tcx, impl_args); let impl_trait_ref = ocx.normalize(&ObligationCause::dummy(), param_env, impl_trait_ref); if let Err(_) = @@ -36,7 +36,7 @@ pub fn recompute_applicable_impls<'tcx>( return false; } - let impl_predicates = tcx.predicates_of(impl_def_id).instantiate(tcx, impl_substs); + let impl_predicates = tcx.predicates_of(impl_def_id).instantiate(tcx, impl_args); ocx.register_obligations(impl_predicates.predicates.iter().map(|&predicate| { Obligation::new(tcx, ObligationCause::dummy(), param_env, predicate) })); diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs index f342180590f..a821d1be64b 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs @@ -1050,8 +1050,8 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { report_object_safety_error(self.tcx, span, trait_def_id, violations) } - ty::PredicateKind::ClosureKind(closure_def_id, closure_substs, kind) => { - let found_kind = self.closure_kind(closure_substs).unwrap(); + ty::PredicateKind::ClosureKind(closure_def_id, closure_args, kind) => { + let found_kind = self.closure_kind(closure_args).unwrap(); self.report_closure_error(&obligation, closure_def_id, found_kind, kind) } @@ -1627,19 +1627,21 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> { ty::TermKind::Ty(_) => Ty::new_projection( self.tcx, data.projection_ty.def_id, - data.projection_ty.substs, + data.projection_ty.args, ) .into(), ty::TermKind::Const(ct) => ty::Const::new_unevaluated( self.tcx, ty::UnevaluatedConst { def: data.projection_ty.def_id, - substs: data.projection_ty.substs, + args: data.projection_ty.args, }, ct.ty(), ) .into(), }; + // FIXME(-Ztrait-solver=next): For diagnostic purposes, it would be nice + // to deeply normalize this type. let normalized_term = ocx.normalize(&obligation.cause, obligation.param_env, unnormalized_term); @@ -1970,7 +1972,7 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> { traits.sort(); traits.dedup(); // FIXME: this could use a better heuristic, like just checking - // that substs[1..] is the same. + // that args[1..] is the same. let all_traits_equal = traits.len() == 1; let candidates: Vec<String> = candidates @@ -2016,7 +2018,7 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> { || self.tcx.is_automatically_derived(def_id) }) .filter_map(|def_id| self.tcx.impl_trait_ref(def_id)) - .map(ty::EarlyBinder::subst_identity) + .map(ty::EarlyBinder::instantiate_identity) .filter(|trait_ref| { let self_ty = trait_ref.self_ty(); // Avoid mentioning type parameters. @@ -2265,7 +2267,7 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> { // Pick the first substitution that still contains inference variables as the one // we're going to emit an error for. If there are none (see above), fall back to // a more general error. - let subst = data.trait_ref.substs.iter().find(|s| s.has_non_region_infer()); + let subst = data.trait_ref.args.iter().find(|s| s.has_non_region_infer()); let mut err = if let Some(subst) = subst { self.emit_inference_failure_err( @@ -2290,7 +2292,7 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> { &obligation.with(self.tcx, trait_ref), ); let has_non_region_infer = - trait_ref.skip_binder().substs.types().any(|t| !t.is_ty_or_numeric_infer()); + trait_ref.skip_binder().args.types().any(|t| !t.is_ty_or_numeric_infer()); // It doesn't make sense to talk about applicable impls if there are more // than a handful of them. if ambiguities.len() > 1 && ambiguities.len() < 10 && has_non_region_infer { @@ -2328,7 +2330,7 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> { self.suggest_fully_qualified_path(&mut err, def_id, span, trait_ref.def_id()); } - if let Some(ty::subst::GenericArgKind::Type(_)) = subst.map(|subst| subst.unpack()) + if let Some(ty::GenericArgKind::Type(_)) = subst.map(|subst| subst.unpack()) && let Some(body_id) = self.tcx.hir().maybe_body_owned_by(obligation.cause.body_id) { let mut expr_finder = FindExprBySpan::new(span); @@ -2387,7 +2389,7 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> { // Otherwise, use a placeholder comment for the implementation. let (message, impl_suggestion) = if non_blanket_impl_count == 1 {( "use the fully-qualified path to the only available implementation".to_string(), - format!("<{} as ", self.tcx.type_of(impl_def_id).subst_identity()) + format!("<{} as ", self.tcx.type_of(impl_def_id).instantiate_identity()) )} else {( format!( "use a fully-qualified path to a specific available implementation ({} found)", @@ -2464,7 +2466,7 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> { } let subst = data .projection_ty - .substs + .args .iter() .chain(Some(data.term.into_arg())) .find(|g| g.has_non_region_infer()); @@ -2706,10 +2708,17 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> { err: &mut Diagnostic, obligation: &PredicateObligation<'tcx>, ) { - let ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) = obligation.predicate.kind().skip_binder() else { return; }; + let ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) = + obligation.predicate.kind().skip_binder() + else { + return; + }; let (ObligationCauseCode::BindingObligation(item_def_id, span) - | ObligationCauseCode::ExprBindingObligation(item_def_id, span, ..)) - = *obligation.cause.code().peel_derives() else { return; }; + | ObligationCauseCode::ExprBindingObligation(item_def_id, span, ..)) = + *obligation.cause.code().peel_derives() + else { + return; + }; debug!(?pred, ?item_def_id, ?span); let (Some(node), true) = ( @@ -2820,9 +2829,9 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> { if obligated_types.iter().any(|ot| ot == &self_ty) { return true; } - if let ty::Adt(def, substs) = self_ty.kind() - && let [arg] = &substs[..] - && let ty::subst::GenericArgKind::Type(ty) = arg.unpack() + if let ty::Adt(def, args) = self_ty.kind() + && let [arg] = &args[..] + && let ty::GenericArgKind::Type(ty) = arg.unpack() && let ty::Adt(inner_def, _) = ty.kind() && inner_def == def { @@ -2874,14 +2883,20 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> { let trait_ref = self.tcx.erase_regions(self.tcx.erase_late_bound_regions(trait_ref)); let src_and_dst = rustc_transmute::Types { - dst: trait_ref.substs.type_at(0), - src: trait_ref.substs.type_at(1), + dst: trait_ref.args.type_at(0), + src: trait_ref.args.type_at(1), + }; + let scope = trait_ref.args.type_at(2); + let Some(assume) = rustc_transmute::Assume::from_const( + self.infcx.tcx, + obligation.param_env, + trait_ref.args.const_at(3), + ) else { + span_bug!( + span, + "Unable to construct rustc_transmute::Assume where it was previously possible" + ); }; - let scope = trait_ref.substs.type_at(2); - let Some(assume) = - rustc_transmute::Assume::from_const(self.infcx.tcx, obligation.param_env, trait_ref.substs.const_at(3)) else { - span_bug!(span, "Unable to construct rustc_transmute::Assume where it was previously possible"); - }; match rustc_transmute::TransmuteTypeEnv::new(self.infcx).is_transmutable( obligation.cause, @@ -2890,8 +2905,8 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> { assume, ) { Answer::No(reason) => { - let dst = trait_ref.substs.type_at(0); - let src = trait_ref.substs.type_at(1); + let dst = trait_ref.args.type_at(0); + let src = trait_ref.args.type_at(1); let err_msg = format!( "`{src}` cannot be safely transmuted into `{dst}` in the defining scope of `{scope}`" ); @@ -3058,7 +3073,7 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> { // Note any argument mismatches let given_ty = params.skip_binder(); - let expected_ty = trait_ref.skip_binder().substs.type_at(1); + let expected_ty = trait_ref.skip_binder().args.type_at(1); if let ty::Tuple(given) = given_ty.kind() && let ty::Tuple(expected) = expected_ty.kind() { @@ -3273,7 +3288,7 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> { let mut not_tupled = false; - let found = match found_trait_ref.skip_binder().substs.type_at(1).kind() { + let found = match found_trait_ref.skip_binder().args.type_at(1).kind() { ty::Tuple(ref tys) => vec![ArgKind::empty(); tys.len()], _ => { not_tupled = true; @@ -3281,7 +3296,7 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> { } }; - let expected_ty = expected_trait_ref.skip_binder().substs.type_at(1); + let expected_ty = expected_trait_ref.skip_binder().args.type_at(1); let expected = match expected_ty.kind() { ty::Tuple(ref tys) => { tys.iter().map(|t| ArgKind::from_expected_ty(t, Some(span))).collect() @@ -3554,7 +3569,7 @@ pub fn dump_proof_tree<'tcx>(o: &Obligation<'tcx, ty::Predicate<'tcx>>, infcx: & .1 .expect("proof tree should have been generated"); let mut lock = std::io::stdout().lock(); - let _ = lock.write_fmt(format_args!("{tree:?}")); + let _ = lock.write_fmt(format_args!("{tree:?}\n")); let _ = lock.flush(); }); } diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/on_unimplemented.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/on_unimplemented.rs index b16d2eb5fc1..fbe8d4a6680 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/on_unimplemented.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/on_unimplemented.rs @@ -6,7 +6,7 @@ use rustc_data_structures::fx::FxHashMap; use rustc_errors::{struct_span_err, ErrorGuaranteed}; use rustc_hir as hir; use rustc_hir::def_id::DefId; -use rustc_middle::ty::SubstsRef; +use rustc_middle::ty::GenericArgsRef; use rustc_middle::ty::{self, GenericParamDefKind, TyCtxt}; use rustc_parse_format::{ParseMode, Parser, Piece, Position}; use rustc_span::symbol::{kw, sym, Symbol}; @@ -25,7 +25,7 @@ pub trait TypeErrCtxtExt<'tcx> { &self, trait_ref: ty::PolyTraitRef<'tcx>, obligation: &PredicateObligation<'tcx>, - ) -> Option<(DefId, SubstsRef<'tcx>)>; + ) -> Option<(DefId, GenericArgsRef<'tcx>)>; /*private*/ fn describe_enclosure(&self, hir_id: hir::HirId) -> Option<&'static str>; @@ -56,7 +56,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { &self, trait_ref: ty::PolyTraitRef<'tcx>, obligation: &PredicateObligation<'tcx>, - ) -> Option<(DefId, SubstsRef<'tcx>)> { + ) -> Option<(DefId, GenericArgsRef<'tcx>)> { let tcx = self.tcx; let param_env = obligation.param_env; let trait_ref = self.instantiate_binder_with_placeholders(trait_ref); @@ -66,26 +66,23 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { let mut fuzzy_match_impls = vec![]; self.tcx.for_each_relevant_impl(trait_ref.def_id, trait_self_ty, |def_id| { - let impl_substs = self.fresh_substs_for_item(obligation.cause.span, def_id); - let impl_trait_ref = tcx.impl_trait_ref(def_id).unwrap().subst(tcx, impl_substs); + let impl_args = self.fresh_args_for_item(obligation.cause.span, def_id); + let impl_trait_ref = tcx.impl_trait_ref(def_id).unwrap().instantiate(tcx, impl_args); let impl_self_ty = impl_trait_ref.self_ty(); if self.can_eq(param_env, trait_self_ty, impl_self_ty) { - self_match_impls.push((def_id, impl_substs)); + self_match_impls.push((def_id, impl_args)); - if iter::zip( - trait_ref.substs.types().skip(1), - impl_trait_ref.substs.types().skip(1), - ) - .all(|(u, v)| self.fuzzy_match_tys(u, v, false).is_some()) + if iter::zip(trait_ref.args.types().skip(1), impl_trait_ref.args.types().skip(1)) + .all(|(u, v)| self.fuzzy_match_tys(u, v, false).is_some()) { - fuzzy_match_impls.push((def_id, impl_substs)); + fuzzy_match_impls.push((def_id, impl_args)); } } }); - let impl_def_id_and_substs = if self_match_impls.len() == 1 { + let impl_def_id_and_args = if self_match_impls.len() == 1 { self_match_impls[0] } else if fuzzy_match_impls.len() == 1 { fuzzy_match_impls[0] @@ -93,8 +90,8 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { return None; }; - tcx.has_attr(impl_def_id_and_substs.0, sym::rustc_on_unimplemented) - .then_some(impl_def_id_and_substs) + tcx.has_attr(impl_def_id_and_args.0, sym::rustc_on_unimplemented) + .then_some(impl_def_id_and_args) } /// Used to set on_unimplemented's `ItemContext` @@ -143,9 +140,9 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { trait_ref: ty::PolyTraitRef<'tcx>, obligation: &PredicateObligation<'tcx>, ) -> OnUnimplementedNote { - let (def_id, substs) = self + let (def_id, args) = self .impl_similar_to(trait_ref, obligation) - .unwrap_or_else(|| (trait_ref.def_id(), trait_ref.skip_binder().substs)); + .unwrap_or_else(|| (trait_ref.def_id(), trait_ref.skip_binder().args)); let trait_ref = trait_ref.skip_binder(); let mut flags = vec![]; @@ -192,14 +189,14 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { // signature with no type arguments resolved flags.push(( sym::_Self, - Some(self.tcx.type_of(def.did()).subst_identity().to_string()), + Some(self.tcx.type_of(def.did()).instantiate_identity().to_string()), )); } for param in generics.params.iter() { let value = match param.kind { GenericParamDefKind::Type { .. } | GenericParamDefKind::Const { .. } => { - substs[param.index as usize].to_string() + args[param.index as usize].to_string() } GenericParamDefKind::Lifetime => continue, }; @@ -207,13 +204,13 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { flags.push((name, Some(value))); if let GenericParamDefKind::Type { .. } = param.kind { - let param_ty = substs[param.index as usize].expect_ty(); + let param_ty = args[param.index as usize].expect_ty(); if let Some(def) = param_ty.ty_adt_def() { // We also want to be able to select the parameter's // original signature with no type arguments resolved flags.push(( name, - Some(self.tcx.type_of(def.did()).subst_identity().to_string()), + Some(self.tcx.type_of(def.did()).instantiate_identity().to_string()), )); } } @@ -249,7 +246,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { // signature with no type arguments resolved flags.push(( sym::_Self, - Some(format!("[{}]", self.tcx.type_of(def.did()).subst_identity())), + Some(format!("[{}]", self.tcx.type_of(def.did()).instantiate_identity())), )); } if aty.is_integral() { @@ -268,7 +265,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { if let Some(def) = aty.ty_adt_def() { // We also want to be able to select the array's type's original // signature with no type arguments resolved - let def_ty = self.tcx.type_of(def.did()).subst_identity(); + let def_ty = self.tcx.type_of(def.did()).instantiate_identity(); flags.push((sym::_Self, Some(format!("[{def_ty}; _]")))); if let Some(n) = len { flags.push((sym::_Self, Some(format!("[{def_ty}; {n}]")))); @@ -629,7 +626,7 @@ impl<'tcx> OnUnimplementedFormatString { .filter_map(|param| { let value = match param.kind { GenericParamDefKind::Type { .. } | GenericParamDefKind::Const { .. } => { - trait_ref.substs[param.index as usize].to_string() + trait_ref.args[param.index as usize].to_string() } GenericParamDefKind::Lifetime => return None, }; diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs index 9ac1ba0275c..073a2a2b1a0 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs @@ -30,7 +30,7 @@ use rustc_middle::hir::map; use rustc_middle::ty::error::TypeError::{self, Sorts}; use rustc_middle::ty::{ self, suggest_arbitrary_trait_bound, suggest_constraining_type_param, AdtKind, - GeneratorDiagnosticData, GeneratorInteriorTypeCause, InferTy, InternalSubsts, IsSuggestable, + GeneratorDiagnosticData, GeneratorInteriorTypeCause, GenericArgs, InferTy, IsSuggestable, ToPredicate, Ty, TyCtxt, TypeAndMut, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitableExt, TypeckResults, }; @@ -435,7 +435,7 @@ fn suggest_restriction<'tcx>( ) { if hir_generics.where_clause_span.from_expansion() || hir_generics.where_clause_span.desugaring_kind().is_some() - || projection.is_some_and(|projection| tcx.opt_rpitit_info(projection.def_id).is_some()) + || projection.is_some_and(|projection| tcx.is_impl_trait_in_trait(projection.def_id)) { return; } @@ -670,7 +670,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { // this that we do in `suggest_restriction` and pull the // `impl Trait` into a new generic if it shows up somewhere // else in the predicate. - if !trait_pred.skip_binder().trait_ref.substs[1..] + if !trait_pred.skip_binder().trait_ref.args[1..] .iter() .all(|g| g.is_suggestable(self.tcx, false)) { @@ -752,14 +752,20 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { trait_pred: ty::PolyTraitPredicate<'tcx>, ) -> bool { // It only make sense when suggesting dereferences for arguments - let ObligationCauseCode::FunctionArgumentObligation { arg_hir_id, call_hir_id, .. } = obligation.cause.code() - else { return false; }; - let Some(typeck_results) = &self.typeck_results - else { return false; }; - let hir::Node::Expr(expr) = self.tcx.hir().get(*arg_hir_id) - else { return false; }; - let Some(arg_ty) = typeck_results.expr_ty_adjusted_opt(expr) - else { return false; }; + let ObligationCauseCode::FunctionArgumentObligation { arg_hir_id, call_hir_id, .. } = + obligation.cause.code() + else { + return false; + }; + let Some(typeck_results) = &self.typeck_results else { + return false; + }; + let hir::Node::Expr(expr) = self.tcx.hir().get(*arg_hir_id) else { + return false; + }; + let Some(arg_ty) = typeck_results.expr_ty_adjusted_opt(expr) else { + return false; + }; let span = obligation.cause.span; let mut real_trait_pred = trait_pred; @@ -933,11 +939,11 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { trait_pred.self_ty(), ); - let Some((def_id_or_name, output, inputs)) = self.extract_callable_info( - obligation.cause.body_id, - obligation.param_env, - self_ty, - ) else { return false; }; + let Some((def_id_or_name, output, inputs)) = + self.extract_callable_info(obligation.cause.body_id, obligation.param_env, self_ty) + else { + return false; + }; // Remapping bound vars here let trait_pred_and_self = trait_pred.map_bound(|trait_pred| (trait_pred, output)); @@ -1035,26 +1041,40 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { span.remove_mark(); } let mut expr_finder = FindExprBySpan::new(span); - let Some(body_id) = self.tcx.hir().maybe_body_owned_by(obligation.cause.body_id) else { return; }; + let Some(body_id) = self.tcx.hir().maybe_body_owned_by(obligation.cause.body_id) else { + return; + }; let body = self.tcx.hir().body(body_id); expr_finder.visit_expr(body.value); - let Some(expr) = expr_finder.result else { return; }; - let Some(typeck) = &self.typeck_results else { return; }; - let Some(ty) = typeck.expr_ty_adjusted_opt(expr) else { return; }; + let Some(expr) = expr_finder.result else { + return; + }; + let Some(typeck) = &self.typeck_results else { + return; + }; + let Some(ty) = typeck.expr_ty_adjusted_opt(expr) else { + return; + }; if !ty.is_unit() { return; }; - let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind else { return; }; - let hir::def::Res::Local(hir_id) = path.res else { return; }; + let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind else { + return; + }; + let hir::def::Res::Local(hir_id) = path.res else { + return; + }; let Some(hir::Node::Pat(pat)) = self.tcx.hir().find(hir_id) else { return; }; - let Some(hir::Node::Local(hir::Local { - ty: None, - init: Some(init), - .. - })) = self.tcx.hir().find_parent(pat.hir_id) else { return; }; - let hir::ExprKind::Block(block, None) = init.kind else { return; }; + let Some(hir::Node::Local(hir::Local { ty: None, init: Some(init), .. })) = + self.tcx.hir().find_parent(pat.hir_id) + else { + return; + }; + let hir::ExprKind::Block(block, None) = init.kind else { + return; + }; if block.expr.is_some() { return; } @@ -1062,7 +1082,9 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { err.span_label(block.span, "this empty block is missing a tail expression"); return; }; - let hir::StmtKind::Semi(tail_expr) = stmt.kind else { return; }; + let hir::StmtKind::Semi(tail_expr) = stmt.kind else { + return; + }; let Some(ty) = typeck.expr_ty_opt(tail_expr) else { err.span_label(block.span, "this block is missing a tail expression"); return; @@ -1092,12 +1114,18 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { ) -> bool { let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty()); let ty = self.instantiate_binder_with_placeholders(self_ty); - let Some(generics) = self.tcx.hir().get_generics(obligation.cause.body_id) else { return false }; + let Some(generics) = self.tcx.hir().get_generics(obligation.cause.body_id) else { + return false; + }; let ty::Ref(_, inner_ty, hir::Mutability::Not) = ty.kind() else { return false }; let ty::Param(param) = inner_ty.kind() else { return false }; - let ObligationCauseCode::FunctionArgumentObligation { arg_hir_id, .. } = obligation.cause.code() else { return false }; + let ObligationCauseCode::FunctionArgumentObligation { arg_hir_id, .. } = + obligation.cause.code() + else { + return false; + }; let arg_node = self.tcx.hir().get(*arg_hir_id); - let Node::Expr(Expr { kind: hir::ExprKind::Path(_), ..}) = arg_node else { return false }; + let Node::Expr(Expr { kind: hir::ExprKind::Path(_), .. }) = arg_node else { return false }; let clone_trait = self.tcx.require_lang_item(LangItem::Clone, None); let has_clone = |ty| { @@ -1143,24 +1171,33 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { found: Ty<'tcx>, ) -> Option<(DefIdOrName, Ty<'tcx>, Vec<Ty<'tcx>>)> { // Autoderef is useful here because sometimes we box callables, etc. - let Some((def_id_or_name, output, inputs)) = (self.autoderef_steps)(found).into_iter().find_map(|(found, _)| { - match *found.kind() { - ty::FnPtr(fn_sig) => - Some((DefIdOrName::Name("function pointer"), fn_sig.output(), fn_sig.inputs())), - ty::FnDef(def_id, _) => { - let fn_sig = found.fn_sig(self.tcx); - Some((DefIdOrName::DefId(def_id), fn_sig.output(), fn_sig.inputs())) - } - ty::Closure(def_id, substs) => { - let fn_sig = substs.as_closure().sig(); - Some((DefIdOrName::DefId(def_id), fn_sig.output(), fn_sig.inputs().map_bound(|inputs| &inputs[1..]))) - } - ty::Alias(ty::Opaque, ty::AliasTy { def_id, substs, .. }) => { - self.tcx.item_bounds(def_id).subst(self.tcx, substs).iter().find_map(|pred| { - if let ty::ClauseKind::Projection(proj) = pred.kind().skip_binder() + let Some((def_id_or_name, output, inputs)) = + (self.autoderef_steps)(found).into_iter().find_map(|(found, _)| { + match *found.kind() { + ty::FnPtr(fn_sig) => Some(( + DefIdOrName::Name("function pointer"), + fn_sig.output(), + fn_sig.inputs(), + )), + ty::FnDef(def_id, _) => { + let fn_sig = found.fn_sig(self.tcx); + Some((DefIdOrName::DefId(def_id), fn_sig.output(), fn_sig.inputs())) + } + ty::Closure(def_id, args) => { + let fn_sig = args.as_closure().sig(); + Some(( + DefIdOrName::DefId(def_id), + fn_sig.output(), + fn_sig.inputs().map_bound(|inputs| &inputs[1..]), + )) + } + ty::Alias(ty::Opaque, ty::AliasTy { def_id, args, .. }) => { + self.tcx.item_bounds(def_id).instantiate(self.tcx, args).iter().find_map( + |pred| { + if let ty::ClauseKind::Projection(proj) = pred.kind().skip_binder() && Some(proj.projection_ty.def_id) == self.tcx.lang_items().fn_once_output() - // args tuple will always be substs[1] - && let ty::Tuple(args) = proj.projection_ty.substs.type_at(1).kind() + // args tuple will always be args[1] + && let ty::Tuple(args) = proj.projection_ty.args.type_at(1).kind() { Some(( DefIdOrName::DefId(def_id), @@ -1170,14 +1207,15 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { } else { None } - }) - } - ty::Dynamic(data, _, ty::Dyn) => { - data.iter().find_map(|pred| { - if let ty::ExistentialPredicate::Projection(proj) = pred.skip_binder() + }, + ) + } + ty::Dynamic(data, _, ty::Dyn) => { + data.iter().find_map(|pred| { + if let ty::ExistentialPredicate::Projection(proj) = pred.skip_binder() && Some(proj.def_id) == self.tcx.lang_items().fn_once_output() - // for existential projection, substs are shifted over by 1 - && let ty::Tuple(args) = proj.substs.type_at(0).kind() + // for existential projection, args are shifted over by 1 + && let ty::Tuple(args) = proj.args.type_at(0).kind() { Some(( DefIdOrName::Name("trait object"), @@ -1187,11 +1225,11 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { } else { None } - }) - } - ty::Param(param) => { - let generics = self.tcx.generics_of(body_id); - let name = if generics.count() > param.index as usize + }) + } + ty::Param(param) => { + let generics = self.tcx.generics_of(body_id); + let name = if generics.count() > param.index as usize && let def = generics.param_at(param.index as usize, self.tcx) && matches!(def.kind, ty::GenericParamDefKind::Type { .. }) && def.name == param.name @@ -1200,12 +1238,12 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { } else { DefIdOrName::Name("type parameter") }; - param_env.caller_bounds().iter().find_map(|pred| { - if let ty::ClauseKind::Projection(proj) = pred.kind().skip_binder() + param_env.caller_bounds().iter().find_map(|pred| { + if let ty::ClauseKind::Projection(proj) = pred.kind().skip_binder() && Some(proj.projection_ty.def_id) == self.tcx.lang_items().fn_once_output() && proj.projection_ty.self_ty() == found - // args tuple will always be substs[1] - && let ty::Tuple(args) = proj.projection_ty.substs.type_at(1).kind() + // args tuple will always be args[1] + && let ty::Tuple(args) = proj.projection_ty.args.type_at(1).kind() { Some(( name, @@ -1215,11 +1253,14 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { } else { None } - }) + }) + } + _ => None, } - _ => None, - } - }) else { return None; }; + }) + else { + return None; + }; let output = self.instantiate_binder_with_fresh_vars( DUMMY_SP, @@ -1408,11 +1449,17 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { // Issue #104961, we need to add parentheses properly for compound expressions // for example, `x.starts_with("hi".to_string() + "you")` // should be `x.starts_with(&("hi".to_string() + "you"))` - let Some(body_id) = self.tcx.hir().maybe_body_owned_by(obligation.cause.body_id) else { return false; }; + let Some(body_id) = + self.tcx.hir().maybe_body_owned_by(obligation.cause.body_id) + else { + return false; + }; let body = self.tcx.hir().body(body_id); let mut expr_finder = FindExprBySpan::new(span); expr_finder.visit_expr(body.value); - let Some(expr) = expr_finder.result else { return false; }; + let Some(expr) = expr_finder.result else { + return false; + }; let needs_parens = match expr.kind { // parenthesize if needed (Issue #46756) hir::ExprKind::Cast(_, _) | hir::ExprKind::Binary(_, _, _) => true, @@ -1463,8 +1510,12 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { self_ty: Ty<'tcx>, target_ty: Ty<'tcx>, ) { - let ty::Ref(_, object_ty, hir::Mutability::Not) = target_ty.kind() else { return; }; - let ty::Dynamic(predicates, _, ty::Dyn) = object_ty.kind() else { return; }; + let ty::Ref(_, object_ty, hir::Mutability::Not) = target_ty.kind() else { + return; + }; + let ty::Dynamic(predicates, _, ty::Dyn) = object_ty.kind() else { + return; + }; let self_ref_ty = Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_erased, self_ty); for predicate in predicates.iter() { @@ -1566,7 +1617,9 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { } // Maybe suggest removal of borrows from expressions, like in `for i in &&&foo {}`. - let Some(mut expr) = expr_finder.result else { return false; }; + let Some(mut expr) = expr_finder.result else { + return false; + }; let mut count = 0; let mut suggestions = vec![]; // Skipping binder here, remapping below @@ -1646,7 +1699,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { } if let Some(typeck_results) = &self.typeck_results && let ty = typeck_results.expr_ty_adjusted(base) - && let ty::FnDef(def_id, _substs) = ty.kind() + && let ty::FnDef(def_id, _args) = ty.kind() && let Some(hir::Node::Item(hir::Item { ident, span, vis_span, .. })) = hir.get_if_local(*def_id) { @@ -1798,7 +1851,9 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option<Span> { let hir = self.tcx.hir(); - let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, ..), .. })) = hir.find_by_def_id(obligation.cause.body_id) else { + let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, ..), .. })) = + hir.find_by_def_id(obligation.cause.body_id) + else { return None; }; @@ -1925,7 +1980,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { infcx: &InferCtxt<'tcx>, trait_ref: ty::PolyTraitRef<'tcx>, ) -> Ty<'tcx> { - let inputs = trait_ref.skip_binder().substs.type_at(1); + let inputs = trait_ref.skip_binder().args.type_at(1); let sig = match inputs.kind() { ty::Tuple(inputs) if infcx.tcx.is_fn_trait(trait_ref.def_id()) => { infcx.tcx.mk_fn_sig( @@ -2006,12 +2061,12 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { { let expected_self = self.tcx.anonymize_bound_vars(pred.kind().rebind(trait_pred.self_ty())); - let expected_substs = self + let expected_args = self .tcx - .anonymize_bound_vars(pred.kind().rebind(trait_pred.trait_ref.substs)); + .anonymize_bound_vars(pred.kind().rebind(trait_pred.trait_ref.args)); // Find another predicate whose self-type is equal to the expected self type, - // but whose substs don't match. + // but whose args don't match. let other_pred = predicates.into_iter() .enumerate() .find(|(other_idx, (pred, _))| match pred.kind().skip_binder() { @@ -2024,10 +2079,10 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { == self.tcx.anonymize_bound_vars( pred.kind().rebind(trait_pred.self_ty()), ) - // But the substs don't match (i.e. incompatible args) - && expected_substs + // But the args don't match (i.e. incompatible args) + && expected_args != self.tcx.anonymize_bound_vars( - pred.kind().rebind(trait_pred.trait_ref.substs), + pred.kind().rebind(trait_pred.trait_ref.args), ) => { true @@ -2222,7 +2277,9 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { // Only continue if a generator was found. debug!(?generator, ?trait_ref, ?target_ty); - let (Some(generator_did), Some(trait_ref), Some(target_ty)) = (generator, trait_ref, target_ty) else { + let (Some(generator_did), Some(trait_ref), Some(target_ty)) = + (generator, trait_ref, target_ty) + else { return false; }; @@ -3013,7 +3070,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { } err.note(msg.trim_end_matches(", ").to_string()) } - ty::GeneratorWitnessMIR(def_id, substs) => { + ty::GeneratorWitnessMIR(def_id, args) => { use std::fmt::Write; // FIXME: this is kind of an unusual format for rustc, can we make it more clear? @@ -3022,7 +3079,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { let mut msg = "required because it captures the following types: ".to_owned(); for bty in tcx.generator_hidden_types(*def_id) { - let ty = bty.subst(tcx, substs); + let ty = bty.instantiate(tcx, args); write!(msg, "`{}`, ", ty).unwrap(); } err.note(msg.trim_end_matches(", ").to_string()) @@ -3350,7 +3407,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { Ty::new_projection( self.tcx, item_def_id, - // Future::Output has no substs + // Future::Output has no args [trait_pred.self_ty()], ) }); @@ -3391,7 +3448,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { _ => return, }; if let ty::Float(_) = trait_ref.skip_binder().self_ty().kind() - && let ty::Infer(InferTy::IntVar(_)) = trait_ref.skip_binder().substs.type_at(1).kind() + && let ty::Infer(InferTy::IntVar(_)) = trait_ref.skip_binder().args.type_at(1).kind() { err.span_suggestion_verbose( rhs_span.shrink_to_hi(), @@ -3411,15 +3468,15 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { let Some(diagnostic_name) = self.tcx.get_diagnostic_name(trait_pred.def_id()) else { return; }; - let (adt, substs) = match trait_pred.skip_binder().self_ty().kind() { - ty::Adt(adt, substs) if adt.did().is_local() => (adt, substs), + let (adt, args) = match trait_pred.skip_binder().self_ty().kind() { + ty::Adt(adt, args) if adt.did().is_local() => (adt, args), _ => return, }; let can_derive = { let is_derivable_trait = match diagnostic_name { sym::Default => !adt.is_enum(), sym::PartialEq | sym::PartialOrd => { - let rhs_ty = trait_pred.skip_binder().trait_ref.substs.type_at(1); + let rhs_ty = trait_pred.skip_binder().trait_ref.args.type_at(1); trait_pred.skip_binder().self_ty() == rhs_ty } sym::Eq | sym::Ord | sym::Clone | sym::Copy | sym::Hash | sym::Debug => true, @@ -3428,8 +3485,8 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { is_derivable_trait && // Ensure all fields impl the trait. adt.all_fields().all(|field| { - let field_ty = field.ty(self.tcx, substs); - let trait_substs = match diagnostic_name { + let field_ty = field.ty(self.tcx, args); + let trait_args = match diagnostic_name { sym::PartialEq | sym::PartialOrd => { Some(field_ty) } @@ -3438,7 +3495,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { let trait_pred = trait_pred.map_bound_ref(|tr| ty::TraitPredicate { trait_ref: ty::TraitRef::new(self.tcx, trait_pred.def_id(), - [field_ty].into_iter().chain(trait_substs), + [field_ty].into_iter().chain(trait_args), ), ..*tr }); @@ -3473,7 +3530,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { ) { if let ObligationCauseCode::ImplDerivedObligation(_) = obligation.cause.code() && self.tcx.is_diagnostic_item(sym::SliceIndex, trait_pred.skip_binder().trait_ref.def_id) - && let ty::Slice(_) = trait_pred.skip_binder().trait_ref.substs.type_at(1).kind() + && let ty::Slice(_) = trait_pred.skip_binder().trait_ref.args.type_at(1).kind() && let ty::Ref(_, inner_ty, _) = trait_pred.skip_binder().self_ty().kind() && let ty::Uint(ty::UintTy::Usize) = inner_ty.kind() { @@ -3523,8 +3580,8 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { // trait_pred `S: Sum<<Self as Iterator>::Item>` and predicate `i32: Sum<&()>` let mut type_diffs = vec![]; if let ObligationCauseCode::ExprBindingObligation(def_id, _, _, idx) = parent_code.deref() - && let Some(node_substs) = typeck_results.node_substs_opt(call_hir_id) - && let where_clauses = self.tcx.predicates_of(def_id).instantiate(self.tcx, node_substs) + && let Some(node_args) = typeck_results.node_args_opt(call_hir_id) + && let where_clauses = self.tcx.predicates_of(def_id).instantiate(self.tcx, node_args) && let Some(where_pred) = where_clauses.predicates.get(*idx) { if let Some(where_pred) = where_pred.as_trait_clause() @@ -3538,7 +3595,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { ); let zipped = - iter::zip(where_pred.trait_ref.substs, failed_pred.trait_ref.substs); + iter::zip(where_pred.trait_ref.args, failed_pred.trait_ref.args); for (expected, actual) in zipped { self.probe(|_| { match self @@ -3617,7 +3674,9 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { let Some(typeck_results) = self.typeck_results.as_ref() else { return }; // Make sure we're dealing with the `Option` type. - let Some(option_ty_adt) = typeck_results.expr_ty_adjusted(expr).ty_adt_def() else { return }; + let Some(option_ty_adt) = typeck_results.expr_ty_adjusted(expr).ty_adt_def() else { + return; + }; if !tcx.is_diagnostic_item(sym::Option, option_ty_adt.did()) { return; } @@ -3627,7 +3686,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(ty::TraitPredicate { trait_ref, .. })) = failed_pred.kind().skip_binder() && tcx.is_fn_trait(trait_ref.def_id) - && let [self_ty, found_ty] = trait_ref.substs.as_slice() + && let [self_ty, found_ty] = trait_ref.args.as_slice() && let Some(fn_ty) = self_ty.as_type().filter(|ty| ty.is_fn()) && let fn_sig @ ty::FnSig { abi: abi::Abi::Rust, @@ -3647,7 +3706,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { // Extract `<U as Deref>::Target` assoc type and check that it is `T` && let Some(deref_target_did) = tcx.lang_items().deref_target() - && let projection = Ty::new_projection(tcx,deref_target_did, tcx.mk_substs(&[ty::GenericArg::from(found_ty)])) + && let projection = Ty::new_projection(tcx,deref_target_did, tcx.mk_args(&[ty::GenericArg::from(found_ty)])) && let InferOk { value: deref_target, obligations } = infcx.at(&ObligationCause::dummy(), param_env).normalize(projection) && obligations.iter().all(|obligation| infcx.predicate_must_hold_modulo_regions(obligation)) && infcx.can_eq(param_env, deref_target, target_ty) @@ -3749,11 +3808,17 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { while let Some(assocs_in_method) = assocs.next() { let Some(prev_assoc_in_method) = assocs.peek() else { for entry in assocs_in_method { - let Some((span, (assoc, ty))) = entry else { continue; }; - if primary_spans.is_empty() || type_diffs.iter().any(|diff| { - let Sorts(expected_found) = diff else { return false; }; - self.can_eq(param_env, expected_found.found, ty) - }) { + let Some((span, (assoc, ty))) = entry else { + continue; + }; + if primary_spans.is_empty() + || type_diffs.iter().any(|diff| { + let Sorts(expected_found) = diff else { + return false; + }; + self.can_eq(param_env, expected_found.found, ty) + }) + { // FIXME: this doesn't quite work for `Iterator::collect` // because we have `Vec<i32>` and `()`, but we'd want `i32` // to point at the `.into_iter()` call, but as long as we @@ -3781,7 +3846,9 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { let assoc = with_forced_trimmed_paths!(self.tcx.def_path_str(assoc)); if !self.can_eq(param_env, ty, *prev_ty) { if type_diffs.iter().any(|diff| { - let Sorts(expected_found) = diff else { return false; }; + let Sorts(expected_found) = diff else { + return false; + }; self.can_eq(param_env, expected_found.found, ty) }) { primary_spans.push(span); @@ -3829,15 +3896,19 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { let ocx = ObligationCtxt::new(self.infcx); let mut assocs_in_this_method = Vec::with_capacity(type_diffs.len()); for diff in type_diffs { - let Sorts(expected_found) = diff else { continue; }; - let ty::Alias(ty::Projection, proj) = expected_found.expected.kind() else { continue; }; + let Sorts(expected_found) = diff else { + continue; + }; + let ty::Alias(ty::Projection, proj) = expected_found.expected.kind() else { + continue; + }; let origin = TypeVariableOrigin { kind: TypeVariableOriginKind::TypeInference, span }; let trait_def_id = proj.trait_def_id(self.tcx); // Make `Self` be equivalent to the type of the call chain // expression we're looking at now, so that we can tell what // for example `Iterator::Item` is at this point in the chain. - let substs = InternalSubsts::for_item(self.tcx, trait_def_id, |param, _| { + let args = GenericArgs::for_item(self.tcx, trait_def_id, |param, _| { match param.kind { ty::GenericParamDefKind::Type { .. } => { if param.index == 0 { @@ -3855,7 +3926,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { // This corresponds to `<ExprTy as Iterator>::Item = _`. let projection = ty::Binder::dummy(ty::PredicateKind::Clause( ty::ClauseKind::Projection(ty::ProjectionPredicate { - projection_ty: self.tcx.mk_alias_ty(proj.def_id, substs), + projection_ty: self.tcx.mk_alias_ty(proj.def_id, args), term: ty_var.into(), }), )); @@ -3974,7 +4045,9 @@ fn hint_missing_borrow<'tcx>( }; // This could be a variant constructor, for example. - let Some(fn_decl) = found_node.fn_decl() else { return; }; + let Some(fn_decl) = found_node.fn_decl() else { + return; + }; let args = fn_decl.inputs.iter(); diff --git a/compiler/rustc_trait_selection/src/traits/fulfill.rs b/compiler/rustc_trait_selection/src/traits/fulfill.rs index cf9d9315f60..3ebf1246a41 100644 --- a/compiler/rustc_trait_selection/src/traits/fulfill.rs +++ b/compiler/rustc_trait_selection/src/traits/fulfill.rs @@ -8,7 +8,7 @@ use rustc_infer::traits::{PolyTraitObligation, SelectionError, TraitEngine}; use rustc_middle::mir::interpret::ErrorHandled; use rustc_middle::ty::abstract_const::NotConstEvaluatable; use rustc_middle::ty::error::{ExpectedFound, TypeError}; -use rustc_middle::ty::subst::SubstsRef; +use rustc_middle::ty::GenericArgsRef; use rustc_middle::ty::{self, Binder, Const, TypeVisitableExt}; use std::marker::PhantomData; @@ -410,8 +410,8 @@ impl<'a, 'tcx> ObligationProcessor for FulfillProcessor<'a, 'tcx> { } } - ty::PredicateKind::ClosureKind(_, closure_substs, kind) => { - match self.selcx.infcx.closure_kind(closure_substs) { + ty::PredicateKind::ClosureKind(_, closure_args, kind) => { + match self.selcx.infcx.closure_kind(closure_args) { Some(closure_kind) => { if closure_kind.extends(kind) { ProcessResult::Changed(vec![]) @@ -536,7 +536,7 @@ impl<'a, 'tcx> ObligationProcessor for FulfillProcessor<'a, 'tcx> { if let Ok(new_obligations) = infcx .at(&obligation.cause, obligation.param_env) .trace(c1, c2) - .eq(DefineOpaqueTypes::No, a.substs, b.substs) + .eq(DefineOpaqueTypes::No, a.args, b.args) { return ProcessResult::Changed(mk_pending( new_obligations.into_obligations(), @@ -559,31 +559,30 @@ impl<'a, 'tcx> ObligationProcessor for FulfillProcessor<'a, 'tcx> { let stalled_on = &mut pending_obligation.stalled_on; - let mut evaluate = |c: Const<'tcx>| { - if let ty::ConstKind::Unevaluated(unevaluated) = c.kind() { - match self.selcx.infcx.try_const_eval_resolve( - obligation.param_env, - unevaluated, - c.ty(), - Some(obligation.cause.span), - ) { - Ok(val) => Ok(val), - Err(e) => match e { - ErrorHandled::TooGeneric => { - stalled_on.extend( - unevaluated.substs.iter().filter_map( + let mut evaluate = + |c: Const<'tcx>| { + if let ty::ConstKind::Unevaluated(unevaluated) = c.kind() { + match self.selcx.infcx.try_const_eval_resolve( + obligation.param_env, + unevaluated, + c.ty(), + Some(obligation.cause.span), + ) { + Ok(val) => Ok(val), + Err(e) => match e { + ErrorHandled::TooGeneric => { + stalled_on.extend(unevaluated.args.iter().filter_map( TyOrConstInferVar::maybe_from_generic_arg, - ), - ); - Err(ErrorHandled::TooGeneric) - } - _ => Err(e), - }, + )); + Err(ErrorHandled::TooGeneric) + } + _ => Err(e), + }, + } + } else { + Ok(c) } - } else { - Ok(c) - } - }; + }; match (evaluate(c1), evaluate(c2)) { (Ok(c1), Ok(c2)) => { @@ -671,7 +670,7 @@ impl<'a, 'tcx> FulfillProcessor<'a, 'tcx> { stalled_on: &mut Vec<TyOrConstInferVar<'tcx>>, ) -> ProcessResult<PendingPredicateObligation<'tcx>, FulfillmentErrorCode<'tcx>> { let infcx = self.selcx.infcx; - if obligation.predicate.is_global() { + if obligation.predicate.is_global() && !self.selcx.is_intercrate() { // no type variables present, can use evaluation for better caching. // FIXME: consider caching errors too. if infcx.predicate_must_hold_considering_regions(obligation) { @@ -696,9 +695,9 @@ impl<'a, 'tcx> FulfillProcessor<'a, 'tcx> { // trait selection is because we don't have enough // information about the types in the trait. stalled_on.clear(); - stalled_on.extend(substs_infer_vars( + stalled_on.extend(args_infer_vars( &self.selcx, - trait_obligation.predicate.map_bound(|pred| pred.trait_ref.substs), + trait_obligation.predicate.map_bound(|pred| pred.trait_ref.args), )); debug!( @@ -725,7 +724,7 @@ impl<'a, 'tcx> FulfillProcessor<'a, 'tcx> { ) -> ProcessResult<PendingPredicateObligation<'tcx>, FulfillmentErrorCode<'tcx>> { let tcx = self.selcx.tcx(); - if obligation.predicate.is_global() { + if obligation.predicate.is_global() && !self.selcx.is_intercrate() { // no type variables present, can use evaluation for better caching. // FIXME: consider caching errors too. if self.selcx.infcx.predicate_must_hold_considering_regions(obligation) { @@ -753,9 +752,9 @@ impl<'a, 'tcx> FulfillProcessor<'a, 'tcx> { ProjectAndUnifyResult::Holds(os) => ProcessResult::Changed(mk_pending(os)), ProjectAndUnifyResult::FailedNormalization => { stalled_on.clear(); - stalled_on.extend(substs_infer_vars( + stalled_on.extend(args_infer_vars( &self.selcx, - project_obligation.predicate.map_bound(|pred| pred.projection_ty.substs), + project_obligation.predicate.map_bound(|pred| pred.projection_ty.args), )); ProcessResult::Unchanged } @@ -770,14 +769,14 @@ impl<'a, 'tcx> FulfillProcessor<'a, 'tcx> { } } -/// Returns the set of inference variables contained in `substs`. -fn substs_infer_vars<'a, 'tcx>( +/// Returns the set of inference variables contained in `args`. +fn args_infer_vars<'a, 'tcx>( selcx: &SelectionContext<'a, 'tcx>, - substs: ty::Binder<'tcx, SubstsRef<'tcx>>, + args: ty::Binder<'tcx, GenericArgsRef<'tcx>>, ) -> impl Iterator<Item = TyOrConstInferVar<'tcx>> { selcx .infcx - .resolve_vars_if_possible(substs) + .resolve_vars_if_possible(args) .skip_binder() // ok because this check doesn't care about regions .iter() .filter(|arg| arg.has_non_region_infer()) diff --git a/compiler/rustc_trait_selection/src/traits/misc.rs b/compiler/rustc_trait_selection/src/traits/misc.rs index e9cfd63e2ed..ab07b10c65f 100644 --- a/compiler/rustc_trait_selection/src/traits/misc.rs +++ b/compiler/rustc_trait_selection/src/traits/misc.rs @@ -43,7 +43,7 @@ pub fn type_allowed_to_implement_copy<'tcx>( self_type: Ty<'tcx>, parent_cause: ObligationCause<'tcx>, ) -> Result<(), CopyImplementationError<'tcx>> { - let (adt, substs) = match self_type.kind() { + let (adt, args) = match self_type.kind() { // These types used to have a builtin impl. // Now libcore provides that impl. ty::Uint(_) @@ -56,7 +56,7 @@ pub fn type_allowed_to_implement_copy<'tcx>( | ty::Ref(_, _, hir::Mutability::Not) | ty::Array(..) => return Ok(()), - &ty::Adt(adt, substs) => (adt, substs), + &ty::Adt(adt, args) => (adt, args), _ => return Err(CopyImplementationError::NotAnAdt), }; @@ -66,7 +66,7 @@ pub fn type_allowed_to_implement_copy<'tcx>( param_env, self_type, adt, - substs, + args, parent_cause, hir::LangItem::Copy, ) @@ -91,7 +91,7 @@ pub fn type_allowed_to_implement_const_param_ty<'tcx>( self_type: Ty<'tcx>, parent_cause: ObligationCause<'tcx>, ) -> Result<(), ConstParamTyImplementationError<'tcx>> { - let (adt, substs) = match self_type.kind() { + let (adt, args) = match self_type.kind() { // `core` provides these impls. ty::Uint(_) | ty::Int(_) @@ -103,7 +103,7 @@ pub fn type_allowed_to_implement_const_param_ty<'tcx>( | ty::Ref(.., hir::Mutability::Not) | ty::Tuple(_) => return Ok(()), - &ty::Adt(adt, substs) => (adt, substs), + &ty::Adt(adt, args) => (adt, args), _ => return Err(ConstParamTyImplementationError::NotAnAdtOrBuiltinAllowed), }; @@ -113,7 +113,7 @@ pub fn type_allowed_to_implement_const_param_ty<'tcx>( param_env, self_type, adt, - substs, + args, parent_cause, hir::LangItem::ConstParamTy, ) @@ -128,7 +128,7 @@ pub fn all_fields_implement_trait<'tcx>( param_env: ty::ParamEnv<'tcx>, self_type: Ty<'tcx>, adt: AdtDef<'tcx>, - substs: &'tcx List<GenericArg<'tcx>>, + args: &'tcx List<GenericArg<'tcx>>, parent_cause: ObligationCause<'tcx>, lang_item: LangItem, ) -> Result<(), Vec<(&'tcx ty::FieldDef, Ty<'tcx>, InfringingFieldsReason<'tcx>)>> { @@ -141,7 +141,7 @@ pub fn all_fields_implement_trait<'tcx>( let infcx = tcx.infer_ctxt().build(); let ocx = traits::ObligationCtxt::new(&infcx); - let unnormalized_ty = field.ty(tcx, substs); + let unnormalized_ty = field.ty(tcx, args); if unnormalized_ty.references_error() { continue; } @@ -154,11 +154,11 @@ pub fn all_fields_implement_trait<'tcx>( // FIXME(compiler-errors): This gives us better spans for bad // projection types like in issue-50480. - // If the ADT has substs, point to the cause we are given. + // If the ADT has args, point to the cause we are given. // If it does not, then this field probably doesn't normalize // to begin with, and point to the bad field's span instead. let normalization_cause = if field - .ty(tcx, traits::InternalSubsts::identity_for_item(tcx, adt.did())) + .ty(tcx, traits::GenericArgs::identity_for_item(tcx, adt.did())) .has_non_region_param() { parent_cause.clone() diff --git a/compiler/rustc_trait_selection/src/traits/mod.rs b/compiler/rustc_trait_selection/src/traits/mod.rs index 1af8323b6e9..1c145999184 100644 --- a/compiler/rustc_trait_selection/src/traits/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/mod.rs @@ -13,12 +13,12 @@ mod object_safety; pub mod outlives_bounds; pub mod project; pub mod query; -#[cfg_attr(not(bootstrap), allow(hidden_glob_reexports))] +#[allow(hidden_glob_reexports)] mod select; mod specialize; mod structural_match; mod structural_normalize; -#[cfg_attr(not(bootstrap), allow(hidden_glob_reexports))] +#[allow(hidden_glob_reexports)] mod util; pub mod vtable; pub mod wf; @@ -32,7 +32,7 @@ use rustc_middle::query::Providers; use rustc_middle::ty::fold::TypeFoldable; use rustc_middle::ty::visit::{TypeVisitable, TypeVisitableExt}; use rustc_middle::ty::{self, ToPredicate, Ty, TyCtxt, TypeFolder, TypeSuperVisitable}; -use rustc_middle::ty::{InternalSubsts, SubstsRef}; +use rustc_middle::ty::{GenericArgs, GenericArgsRef}; use rustc_span::def_id::DefId; use rustc_span::Span; @@ -61,13 +61,13 @@ pub use self::select::{EvaluationResult, IntercrateAmbiguityCause, OverflowError pub use self::specialize::specialization_graph::FutureCompatOverlapError; pub use self::specialize::specialization_graph::FutureCompatOverlapErrorKind; pub use self::specialize::{ - specialization_graph, translate_substs, translate_substs_with_cause, OverlapError, + specialization_graph, translate_args, translate_args_with_cause, OverlapError, }; pub use self::structural_match::search_for_structural_match_violation; pub use self::structural_normalize::StructurallyNormalizeExt; pub use self::util::elaborate; pub use self::util::{ - check_substs_compatible, supertrait_def_ids, supertraits, transitive_bounds, + check_args_compatible, supertrait_def_ids, supertraits, transitive_bounds, transitive_bounds_that_define_assoc_item, SupertraitDefIds, }; pub use self::util::{expand_trait_aliases, TraitAliasExpander}; @@ -362,12 +362,9 @@ pub fn normalize_param_env_or_error<'tcx>( "normalize_param_env_or_error: predicates=(non-outlives={:?}, outlives={:?})", predicates, outlives_predicates ); - let Ok(non_outlives_predicates) = do_normalize_predicates( - tcx, - cause.clone(), - elaborated_env, - predicates, - ) else { + let Ok(non_outlives_predicates) = + do_normalize_predicates(tcx, cause.clone(), elaborated_env, predicates) + else { // An unnormalized env is better than nothing. debug!("normalize_param_env_or_error: errored resolving non-outlives predicates"); return elaborated_env; @@ -384,12 +381,9 @@ pub fn normalize_param_env_or_error<'tcx>( unnormalized_env.reveal(), unnormalized_env.constness(), ); - let Ok(outlives_predicates) = do_normalize_predicates( - tcx, - cause, - outlives_env, - outlives_predicates, - ) else { + let Ok(outlives_predicates) = + do_normalize_predicates(tcx, cause, outlives_env, outlives_predicates) + else { // An unnormalized env is better than nothing. debug!("normalize_param_env_or_error: errored resolving outlives predicates"); return elaborated_env; @@ -460,7 +454,7 @@ pub fn impossible_predicates<'tcx>(tcx: TyCtxt<'tcx>, predicates: Vec<ty::Clause fn subst_and_check_impossible_predicates<'tcx>( tcx: TyCtxt<'tcx>, - key: (DefId, SubstsRef<'tcx>), + key: (DefId, GenericArgsRef<'tcx>), ) -> bool { debug!("subst_and_check_impossible_predicates(key={:?})", key); @@ -527,7 +521,7 @@ fn is_impossible_method(tcx: TyCtxt<'_>, (impl_def_id, trait_item_def_id): (DefI let impl_trait_ref = tcx .impl_trait_ref(impl_def_id) .expect("expected impl to correspond to trait") - .subst_identity(); + .instantiate_identity(); let param_env = tcx.param_env(impl_def_id); let mut visitor = ReferencesOnlyParentGenerics { tcx, generics, trait_item_def_id }; @@ -537,7 +531,7 @@ fn is_impossible_method(tcx: TyCtxt<'_>, (impl_def_id, trait_item_def_id): (DefI tcx, ObligationCause::dummy_with_span(*span), param_env, - ty::EarlyBinder::bind(*pred).subst(tcx, impl_trait_ref.substs), + ty::EarlyBinder::bind(*pred).instantiate(tcx, impl_trait_ref.args), ) }) }); diff --git a/compiler/rustc_trait_selection/src/traits/object_safety.rs b/compiler/rustc_trait_selection/src/traits/object_safety.rs index c31944c162e..143e8412967 100644 --- a/compiler/rustc_trait_selection/src/traits/object_safety.rs +++ b/compiler/rustc_trait_selection/src/traits/object_safety.rs @@ -17,10 +17,10 @@ use rustc_errors::{DelayDm, FatalError, MultiSpan}; use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_middle::query::Providers; -use rustc_middle::ty::subst::{GenericArg, InternalSubsts}; use rustc_middle::ty::{ self, EarlyBinder, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitor, }; +use rustc_middle::ty::{GenericArg, GenericArgs}; use rustc_middle::ty::{ToPredicate, TypeVisitableExt}; use rustc_session::lint::builtin::WHERE_CLAUSES_OBJECT_SAFETY; use rustc_span::symbol::Symbol; @@ -270,7 +270,7 @@ fn bounds_reference_self(tcx: TyCtxt<'_>, trait_def_id: DefId) -> SmallVec<[Span tcx.associated_items(trait_def_id) .in_definition_order() .filter(|item| item.kind == ty::AssocKind::Type) - .flat_map(|item| tcx.explicit_item_bounds(item.def_id).subst_identity_iter_copied()) + .flat_map(|item| tcx.explicit_item_bounds(item.def_id).instantiate_identity_iter_copied()) .filter_map(|c| predicate_references_self(tcx, c)) .collect() } @@ -284,7 +284,7 @@ fn predicate_references_self<'tcx>( match predicate.kind().skip_binder() { ty::ClauseKind::Trait(ref data) => { // In the case of a trait predicate, we can skip the "self" type. - data.trait_ref.substs[1..].iter().any(has_self_ty).then_some(sp) + data.trait_ref.args[1..].iter().any(has_self_ty).then_some(sp) } ty::ClauseKind::Projection(ref data) => { // And similarly for projections. This should be redundant with @@ -302,7 +302,7 @@ fn predicate_references_self<'tcx>( // // This is ALT2 in issue #56288, see that for discussion of the // possible alternatives. - data.projection_ty.substs[1..].iter().any(has_self_ty).then_some(sp) + data.projection_ty.args[1..].iter().any(has_self_ty).then_some(sp) } ty::ClauseKind::ConstArgHasType(_ct, ty) => has_self_ty(&ty.into()).then_some(sp), @@ -393,7 +393,7 @@ fn object_safety_violation_for_assoc_item( ty::AssocKind::Type => { if !tcx.features().generic_associated_types_extended && !tcx.generics_of(item.def_id).params.is_empty() - && item.opt_rpitit_info.is_none() + && !item.is_impl_trait_in_trait() { Some(ObjectSafetyViolation::GAT(item.name, item.ident(tcx).span)) } else { @@ -414,7 +414,7 @@ fn virtual_call_violation_for_method<'tcx>( trait_def_id: DefId, method: ty::AssocItem, ) -> Option<MethodViolationCode> { - let sig = tcx.fn_sig(method.def_id).subst_identity(); + let sig = tcx.fn_sig(method.def_id).instantiate_identity(); // The method's first parameter must be named `self` if !method.fn_has_self_parameter { @@ -586,7 +586,7 @@ fn virtual_call_violation_for_method<'tcx>( // allowed to have generic parameters so `auto trait Bound<T> {}` // would already have reported an error at the definition of the // auto trait. - if pred_trait_ref.substs.len() != 1 { + if pred_trait_ref.args.len() != 1 { tcx.sess.diagnostic().delay_span_bug( span, "auto traits cannot have generic parameters", @@ -612,11 +612,11 @@ fn receiver_for_self_ty<'tcx>( method_def_id: DefId, ) -> Ty<'tcx> { debug!("receiver_for_self_ty({:?}, {:?}, {:?})", receiver_ty, self_ty, method_def_id); - let substs = InternalSubsts::for_item(tcx, method_def_id, |param, _| { + let args = GenericArgs::for_item(tcx, method_def_id, |param, _| { if param.index == 0 { self_ty.into() } else { tcx.mk_param_from_def(param) } }); - let result = EarlyBinder::bind(receiver_ty).subst(tcx, substs); + let result = EarlyBinder::bind(receiver_ty).instantiate(tcx, args); debug!( "receiver_for_self_ty({:?}, {:?}, {:?}) = {:?}", receiver_ty, self_ty, method_def_id, result @@ -751,11 +751,11 @@ fn receiver_is_dispatchable<'tcx>( // U: Trait<Arg1, ..., ArgN> let trait_predicate = { let trait_def_id = method.trait_container(tcx).unwrap(); - let substs = InternalSubsts::for_item(tcx, trait_def_id, |param, _| { + let args = GenericArgs::for_item(tcx, trait_def_id, |param, _| { if param.index == 0 { unsized_self_ty.into() } else { tcx.mk_param_from_def(param) } }); - ty::TraitRef::new(tcx, trait_def_id, substs).to_predicate(tcx) + ty::TraitRef::new(tcx, trait_def_id, args).to_predicate(tcx) }; let caller_bounds = diff --git a/compiler/rustc_trait_selection/src/traits/outlives_bounds.rs b/compiler/rustc_trait_selection/src/traits/outlives_bounds.rs index ff55eaf13ad..339baf611f3 100644 --- a/compiler/rustc_trait_selection/src/traits/outlives_bounds.rs +++ b/compiler/rustc_trait_selection/src/traits/outlives_bounds.rs @@ -83,7 +83,8 @@ impl<'a, 'tcx: 'a> InferCtxtExt<'a, 'tcx> for InferCtxt<'tcx> { &canonical_var_values, canonical_result, &mut constraints, - ) else { + ) + else { return vec![]; }; assert_eq!(&obligations, &[]); diff --git a/compiler/rustc_trait_selection/src/traits/project.rs b/compiler/rustc_trait_selection/src/traits/project.rs index 4ccfb54ff7c..a39fc1f1771 100644 --- a/compiler/rustc_trait_selection/src/traits/project.rs +++ b/compiler/rustc_trait_selection/src/traits/project.rs @@ -1,8 +1,8 @@ //! Code for projecting associated types out of trait references. -use super::check_substs_compatible; +use super::check_args_compatible; use super::specialization_graph; -use super::translate_substs; +use super::translate_args; use super::util; use super::ImplSourceUserDefinedData; use super::MismatchedProjectionTypes; @@ -524,7 +524,7 @@ impl<'a, 'b, 'tcx> TypeFolder<TyCtxt<'tcx>> for AssocTypeNormalizer<'a, 'b, 'tcx // ``` // for<'a> fn(<T as Foo>::One<'a, Box<dyn Bar<'a, Item=<T as Foo>::Two<'a>>>>) // ``` - // We normalize the substs on the projection before the projecting, but + // We normalize the args on the projection before the projecting, but // if we're naive, we'll // replace bound vars on inner, project inner, replace placeholders on inner, // replace bound vars on outer, project outer, replace placeholders on outer @@ -539,7 +539,7 @@ impl<'a, 'b, 'tcx> TypeFolder<TyCtxt<'tcx>> for AssocTypeNormalizer<'a, 'b, 'tcx // // On the other hand, this does add a bit of complexity, since we only // replace bound vars if the current type is a `Projection` and we need - // to make sure we don't forget to fold the substs regardless. + // to make sure we don't forget to fold the args regardless. match kind { ty::Opaque => { @@ -558,9 +558,9 @@ impl<'a, 'b, 'tcx> TypeFolder<TyCtxt<'tcx>> for AssocTypeNormalizer<'a, 'b, 'tcx ); } - let substs = data.substs.fold_with(self); + let args = data.args.fold_with(self); let generic_ty = self.interner().type_of(data.def_id); - let concrete_ty = generic_ty.subst(self.interner(), substs); + let concrete_ty = generic_ty.instantiate(self.interner(), args); self.depth += 1; let folded_ty = self.fold_ty(concrete_ty); self.depth -= 1; @@ -660,11 +660,8 @@ impl<'a, 'b, 'tcx> TypeFolder<TyCtxt<'tcx>> for AssocTypeNormalizer<'a, 'b, 'tcx ty::Weak => { let infcx = self.selcx.infcx; self.obligations.extend( - infcx - .tcx - .predicates_of(data.def_id) - .instantiate_own(infcx.tcx, data.substs) - .map(|(mut predicate, span)| { + infcx.tcx.predicates_of(data.def_id).instantiate_own(infcx.tcx, data.args).map( + |(mut predicate, span)| { if data.has_escaping_bound_vars() { (predicate, ..) = BoundVarReplacer::replace_bound_vars( infcx, @@ -677,9 +674,10 @@ impl<'a, 'b, 'tcx> TypeFolder<TyCtxt<'tcx>> for AssocTypeNormalizer<'a, 'b, 'tcx ObligationCauseCode::TypeAlias(code, span, data.def_id) }); Obligation::new(infcx.tcx, cause, self.param_env, predicate) - }), + }, + ), ); - infcx.tcx.type_of(data.def_id).subst(infcx.tcx, data.substs).fold_with(self) + infcx.tcx.type_of(data.def_id).instantiate(infcx.tcx, data.args).fold_with(self) } ty::Inherent if !data.has_escaping_bound_vars() => { @@ -1337,7 +1335,7 @@ pub fn normalize_inherent_projection<'a, 'b, 'tcx>( }); } - let substs = compute_inherent_assoc_ty_substs( + let args = compute_inherent_assoc_ty_args( selcx, param_env, alias_ty, @@ -1347,7 +1345,7 @@ pub fn normalize_inherent_projection<'a, 'b, 'tcx>( ); // Register the obligations arising from the impl and from the associated type itself. - let predicates = tcx.predicates_of(alias_ty.def_id).instantiate(tcx, substs); + let predicates = tcx.predicates_of(alias_ty.def_id).instantiate(tcx, args); for (predicate, span) in predicates { let predicate = normalize_with_depth_to( selcx, @@ -1381,7 +1379,7 @@ pub fn normalize_inherent_projection<'a, 'b, 'tcx>( )); } - let ty = tcx.type_of(alias_ty.def_id).subst(tcx, substs); + let ty = tcx.type_of(alias_ty.def_id).instantiate(tcx, args); let mut ty = selcx.infcx.resolve_vars_if_possible(ty); if ty.has_projections() { @@ -1391,22 +1389,30 @@ pub fn normalize_inherent_projection<'a, 'b, 'tcx>( ty } -pub fn compute_inherent_assoc_ty_substs<'a, 'b, 'tcx>( +pub fn compute_inherent_assoc_ty_args<'a, 'b, 'tcx>( selcx: &'a mut SelectionContext<'b, 'tcx>, param_env: ty::ParamEnv<'tcx>, alias_ty: ty::AliasTy<'tcx>, cause: ObligationCause<'tcx>, depth: usize, obligations: &mut Vec<PredicateObligation<'tcx>>, -) -> ty::SubstsRef<'tcx> { +) -> ty::GenericArgsRef<'tcx> { let tcx = selcx.tcx(); let impl_def_id = tcx.parent(alias_ty.def_id); - let impl_substs = selcx.infcx.fresh_substs_for_item(cause.span, impl_def_id); + let impl_args = selcx.infcx.fresh_args_for_item(cause.span, impl_def_id); - let impl_ty = tcx.type_of(impl_def_id).subst(tcx, impl_substs); - let impl_ty = - normalize_with_depth_to(selcx, param_env, cause.clone(), depth + 1, impl_ty, obligations); + let mut impl_ty = tcx.type_of(impl_def_id).instantiate(tcx, impl_args); + if !selcx.infcx.next_trait_solver() { + impl_ty = normalize_with_depth_to( + selcx, + param_env, + cause.clone(), + depth + 1, + impl_ty, + obligations, + ); + } // Infer the generic parameters of the impl by unifying the // impl type with the self type of the projection. @@ -1423,7 +1429,7 @@ pub fn compute_inherent_assoc_ty_substs<'a, 'b, 'tcx>( } } - alias_ty.rebase_substs_onto_impl(impl_substs, tcx) + alias_ty.rebase_inherent_args_onto_impl(impl_args, tcx) } enum Projected<'tcx> { @@ -1495,20 +1501,18 @@ fn project<'cx, 'tcx>( ProjectionCandidateSet::None => { let tcx = selcx.tcx(); let term = match tcx.def_kind(obligation.predicate.def_id) { - DefKind::AssocTy => Ty::new_projection( - tcx, - obligation.predicate.def_id, - obligation.predicate.substs, - ) - .into(), + DefKind::AssocTy => { + Ty::new_projection(tcx, obligation.predicate.def_id, obligation.predicate.args) + .into() + } DefKind::AssocConst => ty::Const::new_unevaluated( tcx, ty::UnevaluatedConst::new( obligation.predicate.def_id, - obligation.predicate.substs, + obligation.predicate.args, ), tcx.type_of(obligation.predicate.def_id) - .subst(tcx, obligation.predicate.substs), + .instantiate(tcx, obligation.predicate.args), ) .into(), kind => { @@ -1567,7 +1571,7 @@ fn assemble_candidates_from_trait_def<'cx, 'tcx>( let bounds = match *obligation.predicate.self_ty().kind() { // Excluding IATs and type aliases here as they don't have meaningful item bounds. ty::Alias(ty::Projection | ty::Opaque, ref data) => { - tcx.item_bounds(data.def_id).subst(tcx, data.substs) + tcx.item_bounds(data.def_id).instantiate(tcx, data.args) } ty::Infer(ty::TyVar(_)) => { // If the self-type is an inference variable, then it MAY wind up @@ -2017,12 +2021,12 @@ fn confirm_generator_candidate<'cx, 'tcx>( obligation: &ProjectionTyObligation<'tcx>, nested: Vec<PredicateObligation<'tcx>>, ) -> Progress<'tcx> { - let ty::Generator(_, substs, _) = + let ty::Generator(_, args, _) = selcx.infcx.shallow_resolve(obligation.predicate.self_ty()).kind() else { unreachable!() }; - let gen_sig = substs.as_generator().poly_sig(); + let gen_sig = args.as_generator().poly_sig(); let Normalized { value: gen_sig, obligations } = normalize_with_depth( selcx, obligation.param_env, @@ -2054,7 +2058,7 @@ fn confirm_generator_candidate<'cx, 'tcx>( }; ty::ProjectionPredicate { - projection_ty: tcx.mk_alias_ty(obligation.predicate.def_id, trait_ref.substs), + projection_ty: tcx.mk_alias_ty(obligation.predicate.def_id, trait_ref.args), term: ty.into(), } }); @@ -2069,12 +2073,12 @@ fn confirm_future_candidate<'cx, 'tcx>( obligation: &ProjectionTyObligation<'tcx>, nested: Vec<PredicateObligation<'tcx>>, ) -> Progress<'tcx> { - let ty::Generator(_, substs, _) = + let ty::Generator(_, args, _) = selcx.infcx.shallow_resolve(obligation.predicate.self_ty()).kind() else { unreachable!() }; - let gen_sig = substs.as_generator().poly_sig(); + let gen_sig = args.as_generator().poly_sig(); let Normalized { value: gen_sig, obligations } = normalize_with_depth( selcx, obligation.param_env, @@ -2098,7 +2102,7 @@ fn confirm_future_candidate<'cx, 'tcx>( debug_assert_eq!(tcx.associated_item(obligation.predicate.def_id).name, sym::Output); ty::ProjectionPredicate { - projection_ty: tcx.mk_alias_ty(obligation.predicate.def_id, trait_ref.substs), + projection_ty: tcx.mk_alias_ty(obligation.predicate.def_id, trait_ref.args), term: return_ty.into(), } }); @@ -2115,7 +2119,7 @@ fn confirm_builtin_candidate<'cx, 'tcx>( ) -> Progress<'tcx> { let tcx = selcx.tcx(); let self_ty = obligation.predicate.self_ty(); - let substs = tcx.mk_substs(&[self_ty.into()]); + let args = tcx.mk_args(&[self_ty.into()]); let lang_items = tcx.lang_items(); let item_def_id = obligation.predicate.def_id; let trait_def_id = tcx.trait_of_item(item_def_id).unwrap(); @@ -2155,7 +2159,7 @@ fn confirm_builtin_candidate<'cx, 'tcx>( }; let predicate = - ty::ProjectionPredicate { projection_ty: tcx.mk_alias_ty(item_def_id, substs), term }; + ty::ProjectionPredicate { projection_ty: tcx.mk_alias_ty(item_def_id, args), term }; confirm_param_env_candidate(selcx, obligation, ty::Binder::dummy(predicate), false) .with_addl_obligations(obligations) @@ -2187,11 +2191,11 @@ fn confirm_closure_candidate<'cx, 'tcx>( obligation: &ProjectionTyObligation<'tcx>, nested: Vec<PredicateObligation<'tcx>>, ) -> Progress<'tcx> { - let ty::Closure(_, substs) = selcx.infcx.shallow_resolve(obligation.predicate.self_ty()).kind() + let ty::Closure(_, args) = selcx.infcx.shallow_resolve(obligation.predicate.self_ty()).kind() else { unreachable!() }; - let closure_sig = substs.as_closure().sig(); + let closure_sig = args.as_closure().sig(); let Normalized { value: closure_sig, obligations } = normalize_with_depth( selcx, obligation.param_env, @@ -2228,7 +2232,7 @@ fn confirm_callable_candidate<'cx, 'tcx>( flag, ) .map_bound(|(trait_ref, ret_type)| ty::ProjectionPredicate { - projection_ty: tcx.mk_alias_ty(fn_once_output_def_id, trait_ref.substs), + projection_ty: tcx.mk_alias_ty(fn_once_output_def_id, trait_ref.args), term: ret_type.into(), }); @@ -2312,7 +2316,7 @@ fn confirm_impl_candidate<'cx, 'tcx>( ) -> Progress<'tcx> { let tcx = selcx.tcx(); - let ImplSourceUserDefinedData { impl_def_id, substs, mut nested } = impl_impl_source; + let ImplSourceUserDefinedData { impl_def_id, args, mut nested } = impl_impl_source; let assoc_item_id = obligation.predicate.def_id; let trait_def_id = tcx.trait_id_of_impl(impl_def_id).unwrap(); @@ -2336,23 +2340,22 @@ fn confirm_impl_candidate<'cx, 'tcx>( // If we're trying to normalize `<Vec<u32> as X>::A<S>` using //`impl<T> X for Vec<T> { type A<Y> = Box<Y>; }`, then: // - // * `obligation.predicate.substs` is `[Vec<u32>, S]` - // * `substs` is `[u32]` - // * `substs` ends up as `[u32, S]` - let substs = obligation.predicate.substs.rebase_onto(tcx, trait_def_id, substs); - let substs = - translate_substs(selcx.infcx, param_env, impl_def_id, substs, assoc_ty.defining_node); + // * `obligation.predicate.args` is `[Vec<u32>, S]` + // * `args` is `[u32]` + // * `args` ends up as `[u32, S]` + let args = obligation.predicate.args.rebase_onto(tcx, trait_def_id, args); + let args = translate_args(selcx.infcx, param_env, impl_def_id, args, assoc_ty.defining_node); let ty = tcx.type_of(assoc_ty.item.def_id); let is_const = matches!(tcx.def_kind(assoc_ty.item.def_id), DefKind::AssocConst); let term: ty::EarlyBinder<ty::Term<'tcx>> = if is_const { let did = assoc_ty.item.def_id; - let identity_substs = crate::traits::InternalSubsts::identity_for_item(tcx, did); - let uv = ty::UnevaluatedConst::new(did, identity_substs); + let identity_args = crate::traits::GenericArgs::identity_for_item(tcx, did); + let uv = ty::UnevaluatedConst::new(did, identity_args); ty.map_bound(|ty| ty::Const::new_unevaluated(tcx, uv, ty).into()) } else { ty.map_bound(|ty| ty.into()) }; - if !check_substs_compatible(tcx, assoc_ty.item, substs) { + if !check_args_compatible(tcx, assoc_ty.item, args) { let err = Ty::new_error_with_message( tcx, obligation.cause.span, @@ -2361,7 +2364,7 @@ fn confirm_impl_candidate<'cx, 'tcx>( Progress { term: err.into(), obligations: nested } } else { assoc_ty_own_obligations(selcx, obligation, &mut nested); - Progress { term: term.subst(tcx, substs), obligations: nested } + Progress { term: term.instantiate(tcx, args), obligations: nested } } } @@ -2375,7 +2378,7 @@ fn assoc_ty_own_obligations<'cx, 'tcx>( let tcx = selcx.tcx(); let predicates = tcx .predicates_of(obligation.predicate.def_id) - .instantiate_own(tcx, obligation.predicate.substs); + .instantiate_own(tcx, obligation.predicate.args); for (predicate, span) in predicates { let normalized = normalize_with_depth_to( selcx, diff --git a/compiler/rustc_trait_selection/src/traits/query/dropck_outlives.rs b/compiler/rustc_trait_selection/src/traits/query/dropck_outlives.rs index 709c3f432e6..ef989d8c9d6 100644 --- a/compiler/rustc_trait_selection/src/traits/query/dropck_outlives.rs +++ b/compiler/rustc_trait_selection/src/traits/query/dropck_outlives.rs @@ -49,8 +49,8 @@ pub fn trivial_dropck_outlives<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> bool { // (T1..Tn) and closures have same properties as T1..Tn -- // check if *all* of them are trivial. ty::Tuple(tys) => tys.iter().all(|t| trivial_dropck_outlives(tcx, t)), - ty::Closure(_, ref substs) => { - trivial_dropck_outlives(tcx, substs.as_closure().tupled_upvars_ty()) + ty::Closure(_, ref args) => { + trivial_dropck_outlives(tcx, args.as_closure().tupled_upvars_ty()) } ty::Adt(def, _) => { @@ -237,8 +237,8 @@ pub fn dtorck_constraint_for_ty_inner<'tcx>( Ok::<_, NoSolution>(()) })?, - ty::Closure(_, substs) => { - if !substs.as_closure().is_valid() { + ty::Closure(_, args) => { + if !args.as_closure().is_valid() { // By the time this code runs, all type variables ought to // be fully resolved. @@ -250,14 +250,14 @@ pub fn dtorck_constraint_for_ty_inner<'tcx>( } rustc_data_structures::stack::ensure_sufficient_stack(|| { - for ty in substs.as_closure().upvar_tys() { + for ty in args.as_closure().upvar_tys() { dtorck_constraint_for_ty_inner(tcx, span, for_ty, depth + 1, ty, constraints)?; } Ok::<_, NoSolution>(()) })? } - ty::Generator(_, substs, _movability) => { + ty::Generator(_, args, _movability) => { // rust-lang/rust#49918: types can be constructed, stored // in the interior, and sit idle when generator yields // (and is subsequently dropped). @@ -281,7 +281,7 @@ pub fn dtorck_constraint_for_ty_inner<'tcx>( // derived from lifetimes attached to the upvars and resume // argument, and we *do* incorporate those here. - if !substs.as_generator().is_valid() { + if !args.as_generator().is_valid() { // By the time this code runs, all type variables ought to // be fully resolved. tcx.sess.delay_span_bug( @@ -292,28 +292,25 @@ pub fn dtorck_constraint_for_ty_inner<'tcx>( } constraints.outlives.extend( - substs - .as_generator() - .upvar_tys() - .map(|t| -> ty::subst::GenericArg<'tcx> { t.into() }), + args.as_generator().upvar_tys().map(|t| -> ty::GenericArg<'tcx> { t.into() }), ); - constraints.outlives.push(substs.as_generator().resume_ty().into()); + constraints.outlives.push(args.as_generator().resume_ty().into()); } - ty::Adt(def, substs) => { + ty::Adt(def, args) => { let DropckConstraint { dtorck_types, outlives, overflows } = tcx.at(span).adt_dtorck_constraint(def.did())?; // FIXME: we can try to recursively `dtorck_constraint_on_ty` // there, but that needs some way to handle cycles. constraints .dtorck_types - .extend(dtorck_types.iter().map(|t| EarlyBinder::bind(*t).subst(tcx, substs))); + .extend(dtorck_types.iter().map(|t| EarlyBinder::bind(*t).instantiate(tcx, args))); constraints .outlives - .extend(outlives.iter().map(|t| EarlyBinder::bind(*t).subst(tcx, substs))); + .extend(outlives.iter().map(|t| EarlyBinder::bind(*t).instantiate(tcx, args))); constraints .overflows - .extend(overflows.iter().map(|t| EarlyBinder::bind(*t).subst(tcx, substs))); + .extend(overflows.iter().map(|t| EarlyBinder::bind(*t).instantiate(tcx, args))); } // Objects must be alive in order for their destructor diff --git a/compiler/rustc_trait_selection/src/traits/query/normalize.rs b/compiler/rustc_trait_selection/src/traits/query/normalize.rs index 7fe79fd865c..d45cf94f731 100644 --- a/compiler/rustc_trait_selection/src/traits/query/normalize.rs +++ b/compiler/rustc_trait_selection/src/traits/query/normalize.rs @@ -61,8 +61,27 @@ impl<'cx, 'tcx> QueryNormalizeExt<'tcx> for At<'cx, 'tcx> { self.cause, ); + // This is actually a consequence by the way `normalize_erasing_regions` works currently. + // Because it needs to call the `normalize_generic_arg_after_erasing_regions`, it folds + // through tys and consts in a `TypeFoldable`. Importantly, it skips binders, leaving us + // with trying to normalize with escaping bound vars. + // + // Here, we just add the universes that we *would* have created had we passed through the binders. + // + // We *could* replace escaping bound vars eagerly here, but it doesn't seem really necessary. + // The rest of the code is already set up to be lazy about replacing bound vars, + // and only when we actually have to normalize. + let universes = if value.has_escaping_bound_vars() { + let mut max_visitor = + MaxEscapingBoundVarVisitor { outer_index: ty::INNERMOST, escaping: 0 }; + value.visit_with(&mut max_visitor); + vec![None; max_visitor.escaping] + } else { + vec![] + }; + if self.infcx.next_trait_solver() { - match crate::solve::deeply_normalize(self, value) { + match crate::solve::deeply_normalize_with_skipped_universes(self, value, universes) { Ok(value) => return Ok(Normalized { value, obligations: vec![] }), Err(_errors) => { return Err(NoSolution); @@ -81,27 +100,9 @@ impl<'cx, 'tcx> QueryNormalizeExt<'tcx> for At<'cx, 'tcx> { obligations: vec![], cache: SsoHashMap::new(), anon_depth: 0, - universes: vec![], + universes, }; - // This is actually a consequence by the way `normalize_erasing_regions` works currently. - // Because it needs to call the `normalize_generic_arg_after_erasing_regions`, it folds - // through tys and consts in a `TypeFoldable`. Importantly, it skips binders, leaving us - // with trying to normalize with escaping bound vars. - // - // Here, we just add the universes that we *would* have created had we passed through the binders. - // - // We *could* replace escaping bound vars eagerly here, but it doesn't seem really necessary. - // The rest of the code is already set up to be lazy about replacing bound vars, - // and only when we actually have to normalize. - if value.has_escaping_bound_vars() { - let mut max_visitor = - MaxEscapingBoundVarVisitor { outer_index: ty::INNERMOST, escaping: 0 }; - value.visit_with(&mut max_visitor); - if max_visitor.escaping > 0 { - normalizer.universes.extend((0..max_visitor.escaping).map(|_| None)); - } - } let result = value.try_fold_with(&mut normalizer); info!( "normalize::<{}>: result={:?} with {} obligations", @@ -217,7 +218,7 @@ impl<'cx, 'tcx> FallibleTypeFolder<TyCtxt<'tcx>> for QueryNormalizer<'cx, 'tcx> }; // See note in `rustc_trait_selection::traits::project` about why we - // wait to fold the substs. + // wait to fold the args. // Wrap this in a closure so we don't accidentally return from the outer function let res = match kind { @@ -227,7 +228,7 @@ impl<'cx, 'tcx> FallibleTypeFolder<TyCtxt<'tcx>> for QueryNormalizer<'cx, 'tcx> Reveal::UserFacing => ty.try_super_fold_with(self)?, Reveal::All => { - let substs = data.substs.try_fold_with(self)?; + let args = data.args.try_fold_with(self)?; let recursion_limit = self.interner().recursion_limit(); if !recursion_limit.value_within_limit(self.anon_depth) { // A closure or generator may have itself as in its upvars. @@ -243,14 +244,14 @@ impl<'cx, 'tcx> FallibleTypeFolder<TyCtxt<'tcx>> for QueryNormalizer<'cx, 'tcx> } let generic_ty = self.interner().type_of(data.def_id); - let concrete_ty = generic_ty.subst(self.interner(), substs); + let concrete_ty = generic_ty.instantiate(self.interner(), args); self.anon_depth += 1; if concrete_ty == ty { bug!( - "infinite recursion generic_ty: {:#?}, substs: {:#?}, \ + "infinite recursion generic_ty: {:#?}, args: {:#?}, \ concrete_ty: {:#?}, ty: {:#?}", generic_ty, - substs, + args, concrete_ty, ty ); diff --git a/compiler/rustc_trait_selection/src/traits/query/type_op/ascribe_user_type.rs b/compiler/rustc_trait_selection/src/traits/query/type_op/ascribe_user_type.rs index 44671a07659..420d6326553 100644 --- a/compiler/rustc_trait_selection/src/traits/query/type_op/ascribe_user_type.rs +++ b/compiler/rustc_trait_selection/src/traits/query/type_op/ascribe_user_type.rs @@ -4,7 +4,7 @@ use rustc_hir::def_id::{DefId, CRATE_DEF_ID}; use rustc_infer::traits::Obligation; use rustc_middle::traits::query::NoSolution; use rustc_middle::traits::{ObligationCause, ObligationCauseCode}; -use rustc_middle::ty::{self, ParamEnvAnd, Ty, TyCtxt, UserSelfTy, UserSubsts, UserType}; +use rustc_middle::ty::{self, ParamEnvAnd, Ty, TyCtxt, UserArgs, UserSelfTy, UserType}; pub use rustc_middle::traits::query::type_op::AscribeUserType; use rustc_span::{Span, DUMMY_SP}; @@ -47,8 +47,8 @@ pub fn type_op_ascribe_user_type_with_span<'tcx>( let span = span.unwrap_or(DUMMY_SP); match user_ty { UserType::Ty(user_ty) => relate_mir_and_user_ty(ocx, param_env, span, mir_ty, user_ty)?, - UserType::TypeOf(def_id, user_substs) => { - relate_mir_and_user_substs(ocx, param_env, span, mir_ty, def_id, user_substs)? + UserType::TypeOf(def_id, user_args) => { + relate_mir_and_user_args(ocx, param_env, span, mir_ty, def_id, user_args)? } }; Ok(()) @@ -74,20 +74,20 @@ fn relate_mir_and_user_ty<'tcx>( } #[instrument(level = "debug", skip(ocx, param_env, span))] -fn relate_mir_and_user_substs<'tcx>( +fn relate_mir_and_user_args<'tcx>( ocx: &ObligationCtxt<'_, 'tcx>, param_env: ty::ParamEnv<'tcx>, span: Span, mir_ty: Ty<'tcx>, def_id: DefId, - user_substs: UserSubsts<'tcx>, + user_args: UserArgs<'tcx>, ) -> Result<(), NoSolution> { let param_env = param_env.without_const(); - let UserSubsts { user_self_ty, substs } = user_substs; + let UserArgs { user_self_ty, args } = user_args; let tcx = ocx.infcx.tcx; let cause = ObligationCause::dummy_with_span(span); - let ty = tcx.type_of(def_id).subst(tcx, substs); + let ty = tcx.type_of(def_id).instantiate(tcx, args); let ty = ocx.normalize(&cause, param_env, ty); debug!("relate_type_and_user_type: ty of def-id is {:?}", ty); @@ -98,7 +98,7 @@ fn relate_mir_and_user_substs<'tcx>( // Also, normalize the `instantiated_predicates` // because otherwise we wind up with duplicate "type // outlives" error messages. - let instantiated_predicates = tcx.predicates_of(def_id).instantiate(tcx, substs); + let instantiated_predicates = tcx.predicates_of(def_id).instantiate(tcx, args); debug!(?instantiated_predicates); for (instantiated_predicate, predicate_span) in instantiated_predicates { @@ -116,7 +116,7 @@ fn relate_mir_and_user_substs<'tcx>( if let Some(UserSelfTy { impl_def_id, self_ty }) = user_self_ty { let self_ty = ocx.normalize(&cause, param_env, self_ty); - let impl_self_ty = tcx.type_of(impl_def_id).subst(tcx, substs); + let impl_self_ty = tcx.type_of(impl_def_id).instantiate(tcx, args); let impl_self_ty = ocx.normalize(&cause, param_env, impl_self_ty); ocx.eq(&cause, param_env, self_ty, impl_self_ty)?; @@ -128,9 +128,9 @@ fn relate_mir_and_user_substs<'tcx>( // In addition to proving the predicates, we have to // prove that `ty` is well-formed -- this is because - // the WF of `ty` is predicated on the substs being + // the WF of `ty` is predicated on the args being // well-formed, and we haven't proven *that*. We don't - // want to prove the WF of types from `substs` directly because they + // want to prove the WF of types from `args` directly because they // haven't been normalized. // // FIXME(nmatsakis): Well, perhaps we should normalize diff --git a/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs b/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs index d5f6aaa7fe9..aa195d70a9f 100644 --- a/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs +++ b/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs @@ -209,7 +209,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { obligation: &PolyTraitObligation<'tcx>, candidates: &mut SelectionCandidateSet<'tcx>, ) { - // Okay to skip binder because the substs on generator types never + // Okay to skip binder because the args on generator types never // touch bound regions, they just capture the in-scope // type/region parameters. let self_ty = obligation.self_ty().skip_binder(); @@ -261,14 +261,14 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { return; }; - // Okay to skip binder because the substs on closure types never + // Okay to skip binder because the args on closure types never // touch bound regions, they just capture the in-scope // type/region parameters match *obligation.self_ty().skip_binder().kind() { - ty::Closure(def_id, closure_substs) => { + ty::Closure(def_id, closure_args) => { let is_const = self.tcx().is_const_fn_raw(def_id); debug!(?kind, ?obligation, "assemble_unboxed_candidates"); - match self.infcx.closure_kind(closure_substs) { + match self.infcx.closure_kind(closure_args) { Some(closure_kind) => { debug!(?closure_kind, "assemble_unboxed_candidates"); if closure_kind.extends(kind) { @@ -351,7 +351,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { } let drcx = DeepRejectCtxt { treat_obligation_params: TreatParams::ForLookup }; - let obligation_substs = obligation.predicate.skip_binder().trait_ref.substs; + let obligation_args = obligation.predicate.skip_binder().trait_ref.args; self.tcx().for_each_relevant_impl( obligation.predicate.def_id(), obligation.predicate.skip_binder().trait_ref.self_ty(), @@ -360,9 +360,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { // consider a "quick reject". This avoids creating more types // and so forth that we need to. let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap(); - if !drcx - .substs_refs_may_unify(obligation_substs, impl_trait_ref.skip_binder().substs) - { + if !drcx.args_refs_may_unify(obligation_args, impl_trait_ref.skip_binder().args) { return; } if self.reject_fn_ptr_impls( @@ -374,7 +372,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { } self.infcx.probe(|_| { - if let Ok(_substs) = self.match_impl(impl_def_id, impl_trait_ref, obligation) { + if let Ok(_args) = self.match_impl(impl_def_id, impl_trait_ref, obligation) { candidates.vec.push(ImplCandidate(impl_def_id)); } }); @@ -402,8 +400,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { }; for &(predicate, _) in self.tcx().predicates_of(impl_def_id).predicates { - let ty::ClauseKind::Trait(pred) - = predicate.kind().skip_binder() else { continue }; + let ty::ClauseKind::Trait(pred) = predicate.kind().skip_binder() else { continue }; if fn_ptr_trait != pred.trait_ref.def_id { continue; } @@ -651,7 +648,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { let ty = traits::normalize_projection_type( self, param_env, - tcx.mk_alias_ty(tcx.lang_items().deref_target()?, trait_ref.substs), + tcx.mk_alias_ty(tcx.lang_items().deref_target()?, trait_ref.args), cause.clone(), 0, // We're *intentionally* throwing these away, @@ -689,7 +686,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { // Don't add any candidates if there are bound regions. return; }; - let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1); + let target = obligation.predicate.skip_binder().trait_ref.args.type_at(1); debug!(?source, ?target, "assemble_candidates_for_unsizing"); diff --git a/compiler/rustc_trait_selection/src/traits/select/confirmation.rs b/compiler/rustc_trait_selection/src/traits/select/confirmation.rs index 7adc29bbba4..2cb2895b476 100644 --- a/compiler/rustc_trait_selection/src/traits/select/confirmation.rs +++ b/compiler/rustc_trait_selection/src/traits/select/confirmation.rs @@ -13,7 +13,7 @@ use rustc_infer::infer::LateBoundRegionConversionTime::HigherRankedType; use rustc_infer::infer::{DefineOpaqueTypes, InferOk}; use rustc_middle::traits::SelectionOutputTypeParameterMismatch; use rustc_middle::ty::{ - self, Binder, GenericParamDefKind, InternalSubsts, SubstsRef, ToPolyTraitRef, ToPredicate, + self, Binder, GenericArgs, GenericArgsRef, GenericParamDefKind, ToPolyTraitRef, ToPredicate, TraitPredicate, TraitRef, Ty, TyCtxt, TypeVisitableExt, }; use rustc_span::def_id::DefId; @@ -158,15 +158,16 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { self.infcx.instantiate_binder_with_placeholders(trait_predicate).trait_ref; let placeholder_self_ty = placeholder_trait_predicate.self_ty(); let placeholder_trait_predicate = ty::Binder::dummy(placeholder_trait_predicate); - let (def_id, substs) = match *placeholder_self_ty.kind() { + let (def_id, args) = match *placeholder_self_ty.kind() { // Excluding IATs and type aliases here as they don't have meaningful item bounds. - ty::Alias(ty::Projection | ty::Opaque, ty::AliasTy { def_id, substs, .. }) => { - (def_id, substs) + ty::Alias(ty::Projection | ty::Opaque, ty::AliasTy { def_id, args, .. }) => { + (def_id, args) } _ => bug!("projection candidate for unexpected type: {:?}", placeholder_self_ty), }; - let candidate_predicate = tcx.item_bounds(def_id).map_bound(|i| i[idx]).subst(tcx, substs); + let candidate_predicate = + tcx.item_bounds(def_id).map_bound(|i| i[idx]).instantiate(tcx, args); let candidate = candidate_predicate .as_trait_clause() .expect("projection candidate is not a trait predicate") @@ -190,7 +191,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { })?); if let ty::Alias(ty::Projection, ..) = placeholder_self_ty.kind() { - let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs); + let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, args); for (predicate, _) in predicates { let normalized = normalize_with_depth_to( self, @@ -298,8 +299,8 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { .collect(), Condition::IfTransmutable { src, dst } => { let trait_def_id = obligation.predicate.def_id(); - let scope = predicate.trait_ref.substs.type_at(2); - let assume_const = predicate.trait_ref.substs.const_at(3); + let scope = predicate.trait_ref.args.type_at(2); + let assume_const = predicate.trait_ref.args.const_at(3); let make_obl = |from_ty, to_ty| { let trait_ref1 = ty::TraitRef::new( tcx, @@ -342,19 +343,19 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { let Some(assume) = rustc_transmute::Assume::from_const( self.infcx.tcx, obligation.param_env, - predicate.trait_ref.substs.const_at(3) + predicate.trait_ref.args.const_at(3), ) else { return Err(Unimplemented); }; - let dst = predicate.trait_ref.substs.type_at(0); - let src = predicate.trait_ref.substs.type_at(1); + let dst = predicate.trait_ref.args.type_at(0); + let src = predicate.trait_ref.args.type_at(1); debug!(?src, ?dst); let mut transmute_env = rustc_transmute::TransmuteTypeEnv::new(self.infcx); let maybe_transmutable = transmute_env.is_transmutable( obligation.cause.clone(), rustc_transmute::Types { dst, src }, - predicate.trait_ref.substs.type_at(2), + predicate.trait_ref.args.type_at(2), assume, ); @@ -402,7 +403,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { obligation.recursion_depth + 1, obligation.param_env, trait_def_id, - &trait_ref.substs, + &trait_ref.args, obligation.predicate, ); @@ -433,12 +434,12 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { // First, create the substitutions by matching the impl again, // this time not in a probe. - let substs = self.rematch_impl(impl_def_id, obligation); - debug!(?substs, "impl substs"); + let args = self.rematch_impl(impl_def_id, obligation); + debug!(?args, "impl args"); ensure_sufficient_stack(|| { self.vtable_impl( impl_def_id, - substs, + args, &obligation.cause, obligation.recursion_depth + 1, obligation.param_env, @@ -450,33 +451,33 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { fn vtable_impl( &mut self, impl_def_id: DefId, - substs: Normalized<'tcx, SubstsRef<'tcx>>, + args: Normalized<'tcx, GenericArgsRef<'tcx>>, cause: &ObligationCause<'tcx>, recursion_depth: usize, param_env: ty::ParamEnv<'tcx>, parent_trait_pred: ty::Binder<'tcx, ty::TraitPredicate<'tcx>>, ) -> ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>> { - debug!(?impl_def_id, ?substs, ?recursion_depth, "vtable_impl"); + debug!(?impl_def_id, ?args, ?recursion_depth, "vtable_impl"); let mut impl_obligations = self.impl_or_trait_obligations( cause, recursion_depth, param_env, impl_def_id, - &substs.value, + &args.value, parent_trait_pred, ); debug!(?impl_obligations, "vtable_impl"); // Because of RFC447, the impl-trait-ref and obligations - // are sufficient to determine the impl substs, without + // are sufficient to determine the impl args, without // relying on projections in the impl-trait-ref. // // e.g., `impl<U: Tr, V: Iterator<Item=U>> Foo<<U as Tr>::T> for V` - impl_obligations.extend(substs.obligations); + impl_obligations.extend(args.obligations); - ImplSourceUserDefinedData { impl_def_id, substs: substs.value, nested: impl_obligations } + ImplSourceUserDefinedData { impl_def_id, args: args.value, nested: impl_obligations } } fn confirm_object_candidate( @@ -531,7 +532,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { // will be checked in the code below. for super_trait in tcx .super_predicates_of(trait_predicate.def_id()) - .instantiate(tcx, trait_predicate.trait_ref.substs) + .instantiate(tcx, trait_predicate.trait_ref.args) .predicates .into_iter() { @@ -569,68 +570,65 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { // higher-ranked things. // Prevent, e.g., `dyn Iterator<Item = str>`. for bound in self.tcx().item_bounds(assoc_type).transpose_iter() { - let subst_bound = - if defs.count() == 0 { - bound.subst(tcx, trait_predicate.trait_ref.substs) - } else { - let mut substs = smallvec::SmallVec::with_capacity(defs.count()); - substs.extend(trait_predicate.trait_ref.substs.iter()); - let mut bound_vars: smallvec::SmallVec<[ty::BoundVariableKind; 8]> = - smallvec::SmallVec::with_capacity( - bound.skip_binder().kind().bound_vars().len() + defs.count(), - ); - bound_vars.extend(bound.skip_binder().kind().bound_vars().into_iter()); - InternalSubsts::fill_single(&mut substs, defs, &mut |param, _| match param - .kind - { - GenericParamDefKind::Type { .. } => { - let kind = ty::BoundTyKind::Param(param.def_id, param.name); - let bound_var = ty::BoundVariableKind::Ty(kind); - bound_vars.push(bound_var); - Ty::new_bound( - tcx, - ty::INNERMOST, - ty::BoundTy { - var: ty::BoundVar::from_usize(bound_vars.len() - 1), - kind, - }, - ) - .into() - } - GenericParamDefKind::Lifetime => { - let kind = ty::BoundRegionKind::BrNamed(param.def_id, param.name); - let bound_var = ty::BoundVariableKind::Region(kind); - bound_vars.push(bound_var); - ty::Region::new_late_bound( - tcx, - ty::INNERMOST, - ty::BoundRegion { - var: ty::BoundVar::from_usize(bound_vars.len() - 1), - kind, - }, - ) - .into() - } - GenericParamDefKind::Const { .. } => { - let bound_var = ty::BoundVariableKind::Const; - bound_vars.push(bound_var); - ty::Const::new_bound( - tcx, - ty::INNERMOST, - ty::BoundVar::from_usize(bound_vars.len() - 1), - tcx.type_of(param.def_id) - .no_bound_vars() - .expect("const parameter types cannot be generic"), - ) - .into() - } - }); - let bound_vars = tcx.mk_bound_variable_kinds(&bound_vars); - let assoc_ty_substs = tcx.mk_substs(&substs); - let bound = - bound.map_bound(|b| b.kind().skip_binder()).subst(tcx, assoc_ty_substs); - ty::Binder::bind_with_vars(bound, bound_vars).to_predicate(tcx) - }; + let subst_bound = if defs.count() == 0 { + bound.instantiate(tcx, trait_predicate.trait_ref.args) + } else { + let mut args = smallvec::SmallVec::with_capacity(defs.count()); + args.extend(trait_predicate.trait_ref.args.iter()); + let mut bound_vars: smallvec::SmallVec<[ty::BoundVariableKind; 8]> = + smallvec::SmallVec::with_capacity( + bound.skip_binder().kind().bound_vars().len() + defs.count(), + ); + bound_vars.extend(bound.skip_binder().kind().bound_vars().into_iter()); + GenericArgs::fill_single(&mut args, defs, &mut |param, _| match param.kind { + GenericParamDefKind::Type { .. } => { + let kind = ty::BoundTyKind::Param(param.def_id, param.name); + let bound_var = ty::BoundVariableKind::Ty(kind); + bound_vars.push(bound_var); + Ty::new_bound( + tcx, + ty::INNERMOST, + ty::BoundTy { + var: ty::BoundVar::from_usize(bound_vars.len() - 1), + kind, + }, + ) + .into() + } + GenericParamDefKind::Lifetime => { + let kind = ty::BoundRegionKind::BrNamed(param.def_id, param.name); + let bound_var = ty::BoundVariableKind::Region(kind); + bound_vars.push(bound_var); + ty::Region::new_late_bound( + tcx, + ty::INNERMOST, + ty::BoundRegion { + var: ty::BoundVar::from_usize(bound_vars.len() - 1), + kind, + }, + ) + .into() + } + GenericParamDefKind::Const { .. } => { + let bound_var = ty::BoundVariableKind::Const; + bound_vars.push(bound_var); + ty::Const::new_bound( + tcx, + ty::INNERMOST, + ty::BoundVar::from_usize(bound_vars.len() - 1), + tcx.type_of(param.def_id) + .no_bound_vars() + .expect("const parameter types cannot be generic"), + ) + .into() + } + }); + let bound_vars = tcx.mk_bound_variable_kinds(&bound_vars); + let assoc_ty_args = tcx.mk_args(&args); + let bound = + bound.map_bound(|b| b.kind().skip_binder()).instantiate(tcx, assoc_ty_args); + ty::Binder::bind_with_vars(bound, bound_vars).to_predicate(tcx) + }; let normalized_bound = normalize_with_depth_to( self, obligation.param_env, @@ -662,10 +660,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { let tcx = self.tcx(); - let Some(self_ty) = self - .infcx - .shallow_resolve(obligation.self_ty().no_bound_vars()) else - { + let Some(self_ty) = self.infcx.shallow_resolve(obligation.self_ty().no_bound_vars()) else { // FIXME: Ideally we'd support `for<'a> fn(&'a ()): Fn(&'a ())`, // but we do not currently. Luckily, such a bound is not // particularly useful, so we don't expect users to write @@ -688,8 +683,8 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { if obligation.is_const() && !is_const { // function is a trait method - if let ty::FnDef(def_id, substs) = self_ty.kind() && let Some(trait_id) = tcx.trait_of_item(*def_id) { - let trait_ref = TraitRef::from_method(tcx, trait_id, *substs); + if let ty::FnDef(def_id, args) = self_ty.kind() && let Some(trait_id) = tcx.trait_of_item(*def_id) { + let trait_ref = TraitRef::from_method(tcx, trait_id, *args); let poly_trait_pred = Binder::dummy(trait_ref).with_constness(ty::BoundConstness::ConstIfConst); let obligation = Obligation::new(tcx, cause.clone(), obligation.param_env, poly_trait_pred); nested.push(obligation); @@ -721,14 +716,14 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { let predicate = self.infcx.instantiate_binder_with_placeholders(obligation.predicate); let trait_ref = predicate.trait_ref; let trait_def_id = trait_ref.def_id; - let substs = trait_ref.substs; + let args = trait_ref.args; let trait_obligations = self.impl_or_trait_obligations( &obligation.cause, obligation.recursion_depth, obligation.param_env, trait_def_id, - &substs, + &args, obligation.predicate, ); @@ -741,17 +736,17 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { &mut self, obligation: &PolyTraitObligation<'tcx>, ) -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>> { - // Okay to skip binder because the substs on generator types never + // Okay to skip binder because the args on generator types never // touch bound regions, they just capture the in-scope // type/region parameters. let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder()); - let ty::Generator(generator_def_id, substs, _) = *self_ty.kind() else { + let ty::Generator(generator_def_id, args, _) = *self_ty.kind() else { bug!("closure candidate for non-closure {:?}", obligation); }; - debug!(?obligation, ?generator_def_id, ?substs, "confirm_generator_candidate"); + debug!(?obligation, ?generator_def_id, ?args, "confirm_generator_candidate"); - let gen_sig = substs.as_generator().poly_sig(); + let gen_sig = args.as_generator().poly_sig(); // NOTE: The self-type is a generator type and hence is // in fact unparameterized (or at least does not reference any @@ -780,17 +775,17 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { &mut self, obligation: &PolyTraitObligation<'tcx>, ) -> Result<Vec<PredicateObligation<'tcx>>, SelectionError<'tcx>> { - // Okay to skip binder because the substs on generator types never + // Okay to skip binder because the args on generator types never // touch bound regions, they just capture the in-scope // type/region parameters. let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder()); - let ty::Generator(generator_def_id, substs, _) = *self_ty.kind() else { + let ty::Generator(generator_def_id, args, _) = *self_ty.kind() else { bug!("closure candidate for non-closure {:?}", obligation); }; - debug!(?obligation, ?generator_def_id, ?substs, "confirm_future_candidate"); + debug!(?obligation, ?generator_def_id, ?args, "confirm_future_candidate"); - let gen_sig = substs.as_generator().poly_sig(); + let gen_sig = args.as_generator().poly_sig(); let trait_ref = super::util::future_trait_ref_and_outputs( self.tcx(), @@ -816,22 +811,22 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { .fn_trait_kind_from_def_id(obligation.predicate.def_id()) .unwrap_or_else(|| bug!("closure candidate for non-fn trait {:?}", obligation)); - // Okay to skip binder because the substs on closure types never + // Okay to skip binder because the args on closure types never // touch bound regions, they just capture the in-scope // type/region parameters. let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder()); - let ty::Closure(closure_def_id, substs) = *self_ty.kind() else { + let ty::Closure(closure_def_id, args) = *self_ty.kind() else { bug!("closure candidate for non-closure {:?}", obligation); }; - let trait_ref = self.closure_trait_ref_unnormalized(obligation, substs); + let trait_ref = self.closure_trait_ref_unnormalized(obligation, args); let mut nested = self.confirm_poly_trait_refs(obligation, trait_ref)?; debug!(?closure_def_id, ?trait_ref, ?nested, "confirm closure candidate obligations"); nested.push(obligation.with( self.tcx(), - ty::Binder::dummy(ty::PredicateKind::ClosureKind(closure_def_id, substs, kind)), + ty::Binder::dummy(ty::PredicateKind::ClosureKind(closure_def_id, args, kind)), )); Ok(nested) @@ -908,7 +903,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { // `assemble_candidates_for_unsizing` should ensure there are no late-bound // regions here. See the comment there for more details. let source = self.infcx.shallow_resolve(obligation.self_ty().no_bound_vars().unwrap()); - let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1); + let target = obligation.predicate.skip_binder().trait_ref.args.type_at(1); let target = self.infcx.shallow_resolve(target); debug!(?source, ?target, "confirm_trait_upcasting_unsize_candidate"); @@ -1011,7 +1006,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { // `assemble_candidates_for_unsizing` should ensure there are no late-bound // regions here. See the comment there for more details. let source = self.infcx.shallow_resolve(obligation.self_ty().no_bound_vars().unwrap()); - let target = obligation.predicate.skip_binder().trait_ref.substs.type_at(1); + let target = obligation.predicate.skip_binder().trait_ref.args.type_at(1); let target = self.infcx.shallow_resolve(target); debug!(?source, ?target, "confirm_builtin_unsize_candidate"); @@ -1119,7 +1114,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { } // `Struct<T>` -> `Struct<U>` - (&ty::Adt(def, substs_a), &ty::Adt(_, substs_b)) => { + (&ty::Adt(def, args_a), &ty::Adt(_, args_b)) => { let unsizing_params = tcx.unsizing_params_for_adt(def.did()); if unsizing_params.is_empty() { return Err(Unimplemented); @@ -1136,7 +1131,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { obligation.param_env, obligation.cause.clone(), obligation.recursion_depth + 1, - tail_field_ty.subst(tcx, substs_a), + tail_field_ty.instantiate(tcx, args_a), &mut nested, ); let target_tail = normalize_with_depth_to( @@ -1144,16 +1139,17 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { obligation.param_env, obligation.cause.clone(), obligation.recursion_depth + 1, - tail_field_ty.subst(tcx, substs_b), + tail_field_ty.instantiate(tcx, args_b), &mut nested, ); // Check that the source struct with the target's // unsizing parameters is equal to the target. - let substs = tcx.mk_substs_from_iter(substs_a.iter().enumerate().map(|(i, k)| { - if unsizing_params.contains(i as u32) { substs_b[i] } else { k } - })); - let new_struct = Ty::new_adt(tcx, def, substs); + let args = + tcx.mk_args_from_iter(args_a.iter().enumerate().map(|(i, k)| { + if unsizing_params.contains(i as u32) { args_b[i] } else { k } + })); + let new_struct = Ty::new_adt(tcx, def, args); let InferOk { obligations, .. } = self .infcx .at(&obligation.cause, obligation.param_env) @@ -1233,8 +1229,8 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { trait_pred.trait_ref.def_id = drop_trait; trait_pred }); - let substs = self.rematch_impl(impl_def_id, &new_obligation); - debug!(?substs, "impl substs"); + let args = self.rematch_impl(impl_def_id, &new_obligation); + debug!(?args, "impl args"); let cause = obligation.derived_cause(|derived| { ImplDerivedObligation(Box::new(ImplDerivedObligationCause { @@ -1247,7 +1243,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { let obligations = ensure_sufficient_stack(|| { self.vtable_impl( impl_def_id, - substs, + args, &cause, new_obligation.recursion_depth + 1, new_obligation.param_env, @@ -1259,7 +1255,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { // We want to confirm the ADT's fields if we have an ADT let mut stack = match *self_ty.skip_binder().kind() { - ty::Adt(def, substs) => def.all_fields().map(|f| f.ty(tcx, substs)).collect(), + ty::Adt(def, args) => def.all_fields().map(|f| f.ty(tcx, args)).collect(), _ => vec![self_ty.skip_binder()], }; @@ -1292,20 +1288,20 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { ty::Tuple(tys) => { stack.extend(tys.iter()); } - ty::Closure(_, substs) => { - stack.push(substs.as_closure().tupled_upvars_ty()); + ty::Closure(_, args) => { + stack.push(args.as_closure().tupled_upvars_ty()); } - ty::Generator(_, substs, _) => { - let generator = substs.as_generator(); + ty::Generator(_, args, _) => { + let generator = args.as_generator(); stack.extend([generator.tupled_upvars_ty(), generator.witness()]); } ty::GeneratorWitness(tys) => { stack.extend(tcx.erase_late_bound_regions(tys).to_vec()); } - ty::GeneratorWitnessMIR(def_id, substs) => { + ty::GeneratorWitnessMIR(def_id, args) => { let tcx = self.tcx(); stack.extend(tcx.generator_hidden_types(def_id).map(|bty| { - let ty = bty.subst(tcx, substs); + let ty = bty.instantiate(tcx, args); debug_assert!(!ty.has_late_bound_regions()); ty })) diff --git a/compiler/rustc_trait_selection/src/traits/select/mod.rs b/compiler/rustc_trait_selection/src/traits/select/mod.rs index 7f31ab75119..56d5d698d90 100644 --- a/compiler/rustc_trait_selection/src/traits/select/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/select/mod.rs @@ -40,7 +40,7 @@ use rustc_middle::mir::interpret::ErrorHandled; use rustc_middle::ty::abstract_const::NotConstEvaluatable; use rustc_middle::ty::fold::BottomUpFolder; use rustc_middle::ty::relate::TypeRelation; -use rustc_middle::ty::SubstsRef; +use rustc_middle::ty::GenericArgsRef; use rustc_middle::ty::{self, EarlyBinder, PolyProjectionPredicate, ToPolyTraitRef, ToPredicate}; use rustc_middle::ty::{Ty, TyCtxt, TypeFoldable, TypeVisitableExt}; use rustc_span::symbol::sym; @@ -843,8 +843,8 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { } } - ty::PredicateKind::ClosureKind(_, closure_substs, kind) => { - match self.infcx.closure_kind(closure_substs) { + ty::PredicateKind::ClosureKind(_, closure_args, kind) => { + match self.infcx.closure_kind(closure_args) { Some(closure_kind) => { if closure_kind.extends(kind) { Ok(EvaluatedToOk) @@ -895,7 +895,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { .infcx .at(&obligation.cause, obligation.param_env) .trace(c1, c2) - .eq(DefineOpaqueTypes::No, a.substs, b.substs) + .eq(DefineOpaqueTypes::No, a.args, b.args) { return self.evaluate_predicates_recursively( previous_stack, @@ -1194,7 +1194,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { // terms of `Fn` etc, but we could probably make this more // precise still. let unbound_input_types = - stack.fresh_trait_pred.skip_binder().trait_ref.substs.types().any(|ty| ty.is_fresh()); + stack.fresh_trait_pred.skip_binder().trait_ref.args.types().any(|ty| ty.is_fresh()); if unbound_input_types && stack.iter().skip(1).any(|prev| { @@ -1635,9 +1635,9 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { debug!(?placeholder_trait_predicate); let tcx = self.infcx.tcx; - let (def_id, substs) = match *placeholder_trait_predicate.trait_ref.self_ty().kind() { - ty::Alias(ty::Projection | ty::Opaque, ty::AliasTy { def_id, substs, .. }) => { - (def_id, substs) + let (def_id, args) = match *placeholder_trait_predicate.trait_ref.self_ty().kind() { + ty::Alias(ty::Projection | ty::Opaque, ty::AliasTy { def_id, args, .. }) => { + (def_id, args) } _ => { span_bug!( @@ -1648,7 +1648,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { ); } }; - let bounds = tcx.item_bounds(def_id).subst(tcx, substs); + let bounds = tcx.item_bounds(def_id).instantiate(tcx, args); // The bounds returned by `item_bounds` may contain duplicates after // normalization, so try to deduplicate when possible to avoid @@ -1785,11 +1785,11 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { if is_match { let generics = self.tcx().generics_of(obligation.predicate.def_id); // FIXME(generic-associated-types): Addresses aggressive inference in #92917. - // If this type is a GAT, and of the GAT substs resolve to something new, + // If this type is a GAT, and of the GAT args resolve to something new, // that means that we must have newly inferred something about the GAT. // We should give up in that case. if !generics.params.is_empty() - && obligation.predicate.substs[generics.parent_count..] + && obligation.predicate.args[generics.parent_count..] .iter() .any(|&p| p.has_non_region_infer() && self.infcx.shallow_resolve(p) != p) { @@ -2127,13 +2127,13 @@ impl<'tcx> SelectionContext<'_, 'tcx> { obligation.predicate.rebind(tys.last().map_or_else(Vec::new, |&last| vec![last])), ), - ty::Adt(def, substs) => { + ty::Adt(def, args) => { let sized_crit = def.sized_constraint(self.tcx()); // (*) binder moved here Where( obligation .predicate - .rebind(sized_crit.subst_iter_copied(self.tcx(), substs).collect()), + .rebind(sized_crit.arg_iter_copied(self.tcx(), args).collect()), ) } @@ -2190,20 +2190,20 @@ impl<'tcx> SelectionContext<'_, 'tcx> { Where(obligation.predicate.rebind(tys.iter().collect())) } - ty::Generator(_, substs, hir::Movability::Movable) => { + ty::Generator(_, args, hir::Movability::Movable) => { if self.tcx().features().generator_clone { let resolved_upvars = - self.infcx.shallow_resolve(substs.as_generator().tupled_upvars_ty()); + self.infcx.shallow_resolve(args.as_generator().tupled_upvars_ty()); let resolved_witness = - self.infcx.shallow_resolve(substs.as_generator().witness()); + self.infcx.shallow_resolve(args.as_generator().witness()); if resolved_upvars.is_ty_var() || resolved_witness.is_ty_var() { // Not yet resolved. Ambiguous } else { - let all = substs + let all = args .as_generator() .upvar_tys() - .chain(iter::once(substs.as_generator().witness())) + .chain(iter::once(args.as_generator().witness())) .collect::<Vec<_>>(); Where(obligation.predicate.rebind(all)) } @@ -2227,24 +2227,24 @@ impl<'tcx> SelectionContext<'_, 'tcx> { Where(ty::Binder::bind_with_vars(witness_tys.to_vec(), all_vars)) } - ty::GeneratorWitnessMIR(def_id, ref substs) => { + ty::GeneratorWitnessMIR(def_id, ref args) => { let hidden_types = bind_generator_hidden_types_above( self.infcx, def_id, - substs, + args, obligation.predicate.bound_vars(), ); Where(hidden_types) } - ty::Closure(_, substs) => { + ty::Closure(_, args) => { // (*) binder moved here - let ty = self.infcx.shallow_resolve(substs.as_closure().tupled_upvars_ty()); + let ty = self.infcx.shallow_resolve(args.as_closure().tupled_upvars_ty()); if let ty::Infer(ty::TyVar(_)) = ty.kind() { // Not yet resolved. Ambiguous } else { - Where(obligation.predicate.rebind(substs.as_closure().upvar_tys().collect())) + Where(obligation.predicate.rebind(args.as_closure().upvar_tys().collect())) } } @@ -2321,14 +2321,14 @@ impl<'tcx> SelectionContext<'_, 'tcx> { t.rebind(tys.iter().collect()) } - ty::Closure(_, ref substs) => { - let ty = self.infcx.shallow_resolve(substs.as_closure().tupled_upvars_ty()); + ty::Closure(_, ref args) => { + let ty = self.infcx.shallow_resolve(args.as_closure().tupled_upvars_ty()); t.rebind(vec![ty]) } - ty::Generator(_, ref substs, _) => { - let ty = self.infcx.shallow_resolve(substs.as_generator().tupled_upvars_ty()); - let witness = substs.as_generator().witness(); + ty::Generator(_, ref args, _) => { + let ty = self.infcx.shallow_resolve(args.as_generator().tupled_upvars_ty()); + let witness = args.as_generator().witness(); t.rebind([ty].into_iter().chain(iter::once(witness)).collect()) } @@ -2337,18 +2337,18 @@ impl<'tcx> SelectionContext<'_, 'tcx> { types.map_bound(|types| types.to_vec()) } - ty::GeneratorWitnessMIR(def_id, ref substs) => { - bind_generator_hidden_types_above(self.infcx, def_id, substs, t.bound_vars()) + ty::GeneratorWitnessMIR(def_id, ref args) => { + bind_generator_hidden_types_above(self.infcx, def_id, args, t.bound_vars()) } // For `PhantomData<T>`, we pass `T`. - ty::Adt(def, substs) if def.is_phantom_data() => t.rebind(substs.types().collect()), + ty::Adt(def, args) if def.is_phantom_data() => t.rebind(args.types().collect()), - ty::Adt(def, substs) => { - t.rebind(def.all_fields().map(|f| f.ty(self.tcx(), substs)).collect()) + ty::Adt(def, args) => { + t.rebind(def.all_fields().map(|f| f.ty(self.tcx(), args)).collect()) } - ty::Alias(ty::Opaque, ty::AliasTy { def_id, substs, .. }) => { + ty::Alias(ty::Opaque, ty::AliasTy { def_id, args, .. }) => { let ty = self.tcx().type_of(def_id); if ty.skip_binder().references_error() { return Err(SelectionError::OpaqueTypeAutoTraitLeakageUnknown(def_id)); @@ -2356,7 +2356,7 @@ impl<'tcx> SelectionContext<'_, 'tcx> { // We can resolve the `impl Trait` to its concrete type, // which enforces a DAG between the functions requiring // the auto trait bounds in question. - t.rebind(vec![ty.subst(self.tcx(), substs)]) + t.rebind(vec![ty.instantiate(self.tcx(), args)]) } }) } @@ -2428,10 +2428,10 @@ impl<'tcx> SelectionContext<'_, 'tcx> { &mut self, impl_def_id: DefId, obligation: &PolyTraitObligation<'tcx>, - ) -> Normalized<'tcx, SubstsRef<'tcx>> { + ) -> Normalized<'tcx, GenericArgsRef<'tcx>> { let impl_trait_ref = self.tcx().impl_trait_ref(impl_def_id).unwrap(); match self.match_impl(impl_def_id, impl_trait_ref, obligation) { - Ok(substs) => substs, + Ok(args) => args, Err(()) => { // FIXME: A rematch may fail when a candidate cache hit occurs // on thefreshened form of the trait predicate, but the match @@ -2447,7 +2447,7 @@ impl<'tcx> SelectionContext<'_, 'tcx> { impl_def_id, obligation ), ); - let value = self.infcx.fresh_substs_for_item(obligation.cause.span, impl_def_id); + let value = self.infcx.fresh_args_for_item(obligation.cause.span, impl_def_id); let err = Ty::new_error(self.tcx(), guar); let value = value.fold_with(&mut BottomUpFolder { tcx: self.tcx(), @@ -2466,14 +2466,14 @@ impl<'tcx> SelectionContext<'_, 'tcx> { impl_def_id: DefId, impl_trait_ref: EarlyBinder<ty::TraitRef<'tcx>>, obligation: &PolyTraitObligation<'tcx>, - ) -> Result<Normalized<'tcx, SubstsRef<'tcx>>, ()> { + ) -> Result<Normalized<'tcx, GenericArgsRef<'tcx>>, ()> { let placeholder_obligation = self.infcx.instantiate_binder_with_placeholders(obligation.predicate); let placeholder_obligation_trait_ref = placeholder_obligation.trait_ref; - let impl_substs = self.infcx.fresh_substs_for_item(obligation.cause.span, impl_def_id); + let impl_args = self.infcx.fresh_args_for_item(obligation.cause.span, impl_def_id); - let impl_trait_ref = impl_trait_ref.subst(self.tcx(), impl_substs); + let impl_trait_ref = impl_trait_ref.instantiate(self.tcx(), impl_args); if impl_trait_ref.references_error() { return Err(()); } @@ -2515,7 +2515,7 @@ impl<'tcx> SelectionContext<'_, 'tcx> { return Err(()); } - Ok(Normalized { value: impl_substs, obligations: nested_obligations }) + Ok(Normalized { value: impl_args, obligations: nested_obligations }) } /// Normalize `where_clause_trait_ref` and try to match it against @@ -2580,9 +2580,9 @@ impl<'tcx> SelectionContext<'_, 'tcx> { fn closure_trait_ref_unnormalized( &mut self, obligation: &PolyTraitObligation<'tcx>, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, ) -> ty::PolyTraitRef<'tcx> { - let closure_sig = substs.as_closure().sig(); + let closure_sig = args.as_closure().sig(); debug!(?closure_sig); @@ -2615,8 +2615,8 @@ impl<'tcx> SelectionContext<'_, 'tcx> { cause: &ObligationCause<'tcx>, recursion_depth: usize, param_env: ty::ParamEnv<'tcx>, - def_id: DefId, // of impl or trait - substs: SubstsRef<'tcx>, // for impl or trait + def_id: DefId, // of impl or trait + args: GenericArgsRef<'tcx>, // for impl or trait parent_trait_pred: ty::Binder<'tcx, ty::TraitPredicate<'tcx>>, ) -> Vec<PredicateObligation<'tcx>> { let tcx = self.tcx(); @@ -2637,7 +2637,7 @@ impl<'tcx> SelectionContext<'_, 'tcx> { // that order. let predicates = tcx.predicates_of(def_id); assert_eq!(predicates.parent, None); - let predicates = predicates.instantiate_own(tcx, substs); + let predicates = predicates.instantiate_own(tcx, args); let mut obligations = Vec::with_capacity(predicates.len()); for (index, (predicate, span)) in predicates.into_iter().enumerate() { let cause = @@ -2990,7 +2990,7 @@ pub enum ProjectionMatchesProjection { fn bind_generator_hidden_types_above<'tcx>( infcx: &InferCtxt<'tcx>, def_id: DefId, - substs: ty::SubstsRef<'tcx>, + args: ty::GenericArgsRef<'tcx>, bound_vars: &ty::List<ty::BoundVariableKind>, ) -> ty::Binder<'tcx, Vec<Ty<'tcx>>> { let tcx = infcx.tcx; @@ -3006,7 +3006,7 @@ fn bind_generator_hidden_types_above<'tcx>( // Deduplicate tys to avoid repeated work. .filter(|bty| seen_tys.insert(*bty)) .map(|bty| { - let mut ty = bty.subst(tcx, substs); + let mut ty = bty.instantiate(tcx, args); // Only remap erased regions if we use them. if considering_regions { diff --git a/compiler/rustc_trait_selection/src/traits/specialize/mod.rs b/compiler/rustc_trait_selection/src/traits/specialize/mod.rs index 96f1287416f..b61b209654c 100644 --- a/compiler/rustc_trait_selection/src/traits/specialize/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/specialize/mod.rs @@ -23,7 +23,7 @@ use rustc_data_structures::fx::FxIndexSet; use rustc_errors::{error_code, DelayDm, Diagnostic}; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_middle::ty::{self, ImplSubject, Ty, TyCtxt, TypeVisitableExt}; -use rustc_middle::ty::{InternalSubsts, SubstsRef}; +use rustc_middle::ty::{GenericArgs, GenericArgsRef}; use rustc_session::lint::builtin::COHERENCE_LEAK_CHECK; use rustc_session::lint::builtin::ORDER_DEPENDENT_TRAIT_OBJECTS; use rustc_span::{Span, DUMMY_SP}; @@ -48,7 +48,7 @@ pub struct OverlapError<'tcx> { /// When we have selected one impl, but are actually using item definitions from /// a parent impl providing a default, we need a way to translate between the /// type parameters of the two impls. Here the `source_impl` is the one we've -/// selected, and `source_substs` is a substitution of its generics. +/// selected, and `source_args` is a substitution of its generics. /// And `target_node` is the impl/trait we're actually going to get the /// definition from. The resulting substitution will map from `target_node`'s /// generics to `source_impl`'s generics as instantiated by `source_subst`. @@ -76,51 +76,46 @@ pub struct OverlapError<'tcx> { /// through associated type projection. We deal with such cases by using /// *fulfillment* to relate the two impls, requiring that all projections are /// resolved. -pub fn translate_substs<'tcx>( +pub fn translate_args<'tcx>( infcx: &InferCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, source_impl: DefId, - source_substs: SubstsRef<'tcx>, + source_args: GenericArgsRef<'tcx>, target_node: specialization_graph::Node, -) -> SubstsRef<'tcx> { - translate_substs_with_cause( - infcx, - param_env, - source_impl, - source_substs, - target_node, - |_, _| ObligationCause::dummy(), - ) +) -> GenericArgsRef<'tcx> { + translate_args_with_cause(infcx, param_env, source_impl, source_args, target_node, |_, _| { + ObligationCause::dummy() + }) } -/// Like [translate_substs], but obligations from the parent implementation +/// Like [translate_args], but obligations from the parent implementation /// are registered with the provided `ObligationCause`. /// /// This is for reporting *region* errors from those bounds. Type errors should /// not happen because the specialization graph already checks for those, and /// will result in an ICE. -pub fn translate_substs_with_cause<'tcx>( +pub fn translate_args_with_cause<'tcx>( infcx: &InferCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, source_impl: DefId, - source_substs: SubstsRef<'tcx>, + source_args: GenericArgsRef<'tcx>, target_node: specialization_graph::Node, cause: impl Fn(usize, Span) -> ObligationCause<'tcx>, -) -> SubstsRef<'tcx> { +) -> GenericArgsRef<'tcx> { debug!( - "translate_substs({:?}, {:?}, {:?}, {:?})", - param_env, source_impl, source_substs, target_node + "translate_args({:?}, {:?}, {:?}, {:?})", + param_env, source_impl, source_args, target_node ); let source_trait_ref = - infcx.tcx.impl_trait_ref(source_impl).unwrap().subst(infcx.tcx, &source_substs); + infcx.tcx.impl_trait_ref(source_impl).unwrap().instantiate(infcx.tcx, &source_args); // translate the Self and Param parts of the substitution, since those // vary across impls - let target_substs = match target_node { + let target_args = match target_node { specialization_graph::Node::Impl(target_impl) => { // no need to translate if we're targeting the impl we started with if source_impl == target_impl { - return source_substs; + return source_args; } fulfill_implication(infcx, param_env, source_trait_ref, source_impl, target_impl, cause) @@ -131,11 +126,11 @@ pub fn translate_substs_with_cause<'tcx>( ) }) } - specialization_graph::Node::Trait(..) => source_trait_ref.substs, + specialization_graph::Node::Trait(..) => source_trait_ref.args, }; // directly inherent the method generics, since those do not vary across impls - source_substs.rebase_onto(infcx.tcx, source_impl, target_substs) + source_args.rebase_onto(infcx.tcx, source_impl, target_args) } /// Is `impl1` a specialization of `impl2`? @@ -172,7 +167,7 @@ pub(super) fn specializes(tcx: TyCtxt<'_>, (impl1_def_id, impl2_def_id): (DefId, // create a parameter environment corresponding to a (placeholder) instantiation of impl1 let penv = tcx.param_env(impl1_def_id); - let impl1_trait_ref = tcx.impl_trait_ref(impl1_def_id).unwrap().subst_identity(); + let impl1_trait_ref = tcx.impl_trait_ref(impl1_def_id).unwrap().instantiate_identity(); // Create an infcx, taking the predicates of impl1 as assumptions: let infcx = tcx.infer_ctxt().build(); @@ -196,7 +191,7 @@ fn fulfill_implication<'tcx>( source_impl: DefId, target_impl: DefId, error_cause: impl Fn(usize, Span) -> ObligationCause<'tcx>, -) -> Result<SubstsRef<'tcx>, ()> { +) -> Result<GenericArgsRef<'tcx>, ()> { debug!( "fulfill_implication({:?}, trait_ref={:?} |- {:?} applies)", param_env, source_trait_ref, target_impl @@ -221,18 +216,16 @@ fn fulfill_implication<'tcx>( let source_trait = ImplSubject::Trait(source_trait_ref); let selcx = &mut SelectionContext::new(&infcx); - let target_substs = infcx.fresh_substs_for_item(DUMMY_SP, target_impl); + let target_args = infcx.fresh_args_for_item(DUMMY_SP, target_impl); let (target_trait, obligations) = - util::impl_subject_and_oblig(selcx, param_env, target_impl, target_substs, error_cause); + util::impl_subject_and_oblig(selcx, param_env, target_impl, target_args, error_cause); // do the impls unify? If not, no specialization. - let Ok(InferOk { obligations: more_obligations, .. }) = - infcx.at(&ObligationCause::dummy(), param_env).eq(DefineOpaqueTypes::No, source_trait, target_trait) + let Ok(InferOk { obligations: more_obligations, .. }) = infcx + .at(&ObligationCause::dummy(), param_env) + .eq(DefineOpaqueTypes::No, source_trait, target_trait) else { - debug!( - "fulfill_implication: {:?} does not unify with {:?}", - source_trait, target_trait - ); + debug!("fulfill_implication: {:?} does not unify with {:?}", source_trait, target_trait); return Err(()); }; @@ -261,7 +254,7 @@ fn fulfill_implication<'tcx>( // Now resolve the *substitution* we built for the target earlier, replacing // the inference variables inside with whatever we got from fulfillment. - Ok(infcx.resolve_vars_if_possible(target_substs)) + Ok(infcx.resolve_vars_if_possible(target_args)) } /// Query provider for `specialization_graph_of`. @@ -469,21 +462,21 @@ fn report_conflicting_impls<'tcx>( pub(crate) fn to_pretty_impl_header(tcx: TyCtxt<'_>, impl_def_id: DefId) -> Option<String> { use std::fmt::Write; - let trait_ref = tcx.impl_trait_ref(impl_def_id)?.subst_identity(); + let trait_ref = tcx.impl_trait_ref(impl_def_id)?.instantiate_identity(); let mut w = "impl".to_owned(); - let substs = InternalSubsts::identity_for_item(tcx, impl_def_id); + let args = GenericArgs::identity_for_item(tcx, impl_def_id); // FIXME: Currently only handles ?Sized. // Needs to support ?Move and ?DynSized when they are implemented. let mut types_without_default_bounds = FxIndexSet::default(); let sized_trait = tcx.lang_items().sized_trait(); - if !substs.is_empty() { - types_without_default_bounds.extend(substs.types()); + if !args.is_empty() { + types_without_default_bounds.extend(args.types()); w.push('<'); w.push_str( - &substs + &args .iter() .map(|k| k.to_string()) .filter(|k| k != "'_") @@ -497,7 +490,7 @@ pub(crate) fn to_pretty_impl_header(tcx: TyCtxt<'_>, impl_def_id: DefId) -> Opti w, " {} for {}", trait_ref.print_only_trait_path(), - tcx.type_of(impl_def_id).subst_identity() + tcx.type_of(impl_def_id).instantiate_identity() ) .unwrap(); diff --git a/compiler/rustc_trait_selection/src/traits/specialize/specialization_graph.rs b/compiler/rustc_trait_selection/src/traits/specialize/specialization_graph.rs index aa5c624f471..e9a592bdee7 100644 --- a/compiler/rustc_trait_selection/src/traits/specialize/specialization_graph.rs +++ b/compiler/rustc_trait_selection/src/traits/specialize/specialization_graph.rs @@ -180,7 +180,7 @@ impl<'tcx> ChildrenExt<'tcx> for Children { if le && !ge { debug!( "descending as child of TraitRef {:?}", - tcx.impl_trait_ref(possible_sibling).unwrap().subst_identity() + tcx.impl_trait_ref(possible_sibling).unwrap().instantiate_identity() ); // The impl specializes `possible_sibling`. @@ -188,7 +188,7 @@ impl<'tcx> ChildrenExt<'tcx> for Children { } else if ge && !le { debug!( "placing as parent of TraitRef {:?}", - tcx.impl_trait_ref(possible_sibling).unwrap().subst_identity() + tcx.impl_trait_ref(possible_sibling).unwrap().instantiate_identity() ); replace_children.push(possible_sibling); diff --git a/compiler/rustc_trait_selection/src/traits/structural_match.rs b/compiler/rustc_trait_selection/src/traits/structural_match.rs index 420f8c5dceb..0864e4dc841 100644 --- a/compiler/rustc_trait_selection/src/traits/structural_match.rs +++ b/compiler/rustc_trait_selection/src/traits/structural_match.rs @@ -62,8 +62,8 @@ impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for Search<'tcx> { fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<Self::BreakTy> { debug!("Search visiting ty: {:?}", ty); - let (adt_def, substs) = match *ty.kind() { - ty::Adt(adt_def, substs) => (adt_def, substs), + let (adt_def, args) = match *ty.kind() { + ty::Adt(adt_def, args) => (adt_def, args), ty::Param(_) => { return ControlFlow::Break(ty); } @@ -157,15 +157,15 @@ impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for Search<'tcx> { // instead looks directly at its fields outside // this match), so we skip super_visit_with. // - // (Must not recur on substs for `PhantomData<T>` cf + // (Must not recur on args for `PhantomData<T>` cf // rust-lang/rust#55028 and rust-lang/rust#55837; but also - // want to skip substs when only uses of generic are + // want to skip args when only uses of generic are // behind unsafe pointers `*const T`/`*mut T`.) // even though we skip super_visit_with, we must recur on // fields of ADT. let tcx = self.tcx; - adt_def.all_fields().map(|field| field.ty(tcx, substs)).try_for_each(|field_ty| { + adt_def.all_fields().map(|field| field.ty(tcx, args)).try_for_each(|field_ty| { let ty = self.tcx.normalize_erasing_regions(ty::ParamEnv::empty(), field_ty); debug!("structural-match ADT: field_ty={:?}, ty={:?}", field_ty, ty); ty.visit_with(self) diff --git a/compiler/rustc_trait_selection/src/traits/util.rs b/compiler/rustc_trait_selection/src/traits/util.rs index 302b6cacf2c..7b34908c4be 100644 --- a/compiler/rustc_trait_selection/src/traits/util.rs +++ b/compiler/rustc_trait_selection/src/traits/util.rs @@ -4,7 +4,7 @@ use rustc_data_structures::fx::FxHashSet; use rustc_errors::Diagnostic; use rustc_hir::def_id::DefId; use rustc_infer::infer::InferOk; -use rustc_middle::ty::SubstsRef; +use rustc_middle::ty::GenericArgsRef; use rustc_middle::ty::{self, ImplSubject, ToPredicate, Ty, TyCtxt, TypeVisitableExt}; use rustc_span::Span; use smallvec::SmallVec; @@ -194,24 +194,24 @@ impl Iterator for SupertraitDefIds<'_> { // Other /////////////////////////////////////////////////////////////////////////// -/// Instantiate all bound parameters of the impl subject with the given substs, +/// Instantiate all bound parameters of the impl subject with the given args, /// returning the resulting subject and all obligations that arise. /// The obligations are closed under normalization. pub fn impl_subject_and_oblig<'a, 'tcx>( selcx: &mut SelectionContext<'a, 'tcx>, param_env: ty::ParamEnv<'tcx>, impl_def_id: DefId, - impl_substs: SubstsRef<'tcx>, + impl_args: GenericArgsRef<'tcx>, cause: impl Fn(usize, Span) -> ObligationCause<'tcx>, ) -> (ImplSubject<'tcx>, impl Iterator<Item = PredicateObligation<'tcx>>) { let subject = selcx.tcx().impl_subject(impl_def_id); - let subject = subject.subst(selcx.tcx(), impl_substs); + let subject = subject.instantiate(selcx.tcx(), impl_args); let InferOk { value: subject, obligations: normalization_obligations1 } = selcx.infcx.at(&ObligationCause::dummy(), param_env).normalize(subject); let predicates = selcx.tcx().predicates_of(impl_def_id); - let predicates = predicates.instantiate(selcx.tcx(), impl_substs); + let predicates = predicates.instantiate(selcx.tcx(), impl_args); let InferOk { value: predicates, obligations: normalization_obligations2 } = selcx.infcx.at(&ObligationCause::dummy(), param_env).normalize(predicates); let impl_obligations = super::predicates_for_generics(cause, param_env, predicates); @@ -303,13 +303,13 @@ pub enum TupleArgumentsFlag { No, } -// Verify that the trait item and its implementation have compatible substs lists -pub fn check_substs_compatible<'tcx>( +// Verify that the trait item and its implementation have compatible args lists +pub fn check_args_compatible<'tcx>( tcx: TyCtxt<'tcx>, assoc_item: ty::AssocItem, - substs: ty::SubstsRef<'tcx>, + args: ty::GenericArgsRef<'tcx>, ) -> bool { - fn check_substs_compatible_inner<'tcx>( + fn check_args_compatible_inner<'tcx>( tcx: TyCtxt<'tcx>, generics: &'tcx ty::Generics, args: &'tcx [ty::GenericArg<'tcx>], @@ -322,7 +322,7 @@ pub fn check_substs_compatible<'tcx>( if let Some(parent) = generics.parent && let parent_generics = tcx.generics_of(parent) - && !check_substs_compatible_inner(tcx, parent_generics, parent_args) { + && !check_args_compatible_inner(tcx, parent_generics, parent_args) { return false; } @@ -339,7 +339,7 @@ pub fn check_substs_compatible<'tcx>( } let generics = tcx.generics_of(assoc_item.def_id); - // Chop off any additional substs (RPITIT) substs - let substs = &substs[0..generics.count().min(substs.len())]; - check_substs_compatible_inner(tcx, generics, substs) + // Chop off any additional args (RPITIT) args + let args = &args[0..generics.count().min(args.len())]; + check_args_compatible_inner(tcx, generics, args) } diff --git a/compiler/rustc_trait_selection/src/traits/vtable.rs b/compiler/rustc_trait_selection/src/traits/vtable.rs index 1f83f1f44bc..78816fed017 100644 --- a/compiler/rustc_trait_selection/src/traits/vtable.rs +++ b/compiler/rustc_trait_selection/src/traits/vtable.rs @@ -6,7 +6,7 @@ use rustc_infer::traits::util::PredicateSet; use rustc_infer::traits::ImplSource; use rustc_middle::query::Providers; use rustc_middle::ty::visit::TypeVisitableExt; -use rustc_middle::ty::InternalSubsts; +use rustc_middle::ty::GenericArgs; use rustc_middle::ty::{self, GenericParamDefKind, ToPredicate, Ty, TyCtxt, VtblEntry}; use rustc_span::{sym, Span}; use smallvec::SmallVec; @@ -241,12 +241,12 @@ fn vtable_entries<'tcx>( debug!("vtable_entries: trait_method={:?}", def_id); // 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 { + let args = trait_ref.map_bound(|trait_ref| { + GenericArgs::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] + trait_ref.args[param.index as usize] } }) }); @@ -254,14 +254,14 @@ fn vtable_entries<'tcx>( // 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); + let args = + tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), args); // 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); + let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, args); if impossible_predicates( tcx, predicates.map(|(predicate, _)| predicate).collect(), @@ -274,7 +274,7 @@ fn vtable_entries<'tcx>( tcx, ty::ParamEnv::reveal_all(), def_id, - substs, + args, ) .expect("resolution failed during building vtable representation"); VtblEntry::Method(instance) diff --git a/compiler/rustc_trait_selection/src/traits/wf.rs b/compiler/rustc_trait_selection/src/traits/wf.rs index d81722ce22a..5f6bb04fda4 100644 --- a/compiler/rustc_trait_selection/src/traits/wf.rs +++ b/compiler/rustc_trait_selection/src/traits/wf.rs @@ -2,8 +2,8 @@ use crate::infer::InferCtxt; use crate::traits; use rustc_hir as hir; use rustc_hir::lang_items::LangItem; -use rustc_middle::ty::subst::{GenericArg, GenericArgKind, SubstsRef}; use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt}; +use rustc_middle::ty::{GenericArg, GenericArgKind, GenericArgsRef}; use rustc_span::def_id::{DefId, LocalDefId, CRATE_DEF_ID}; use rustc_span::{Span, DUMMY_SP}; @@ -341,7 +341,7 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { let trait_ref = &trait_pred.trait_ref; // Negative trait predicates don't require supertraits to hold, just - // that their substs are WF. + // that their args are WF. if trait_pred.polarity == ty::ImplPolarity::Negative { self.compute_negative_trait_pred(trait_ref); return; @@ -349,9 +349,9 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { // if the trait predicate is not const, the wf obligations should not be const as well. let obligations = if trait_pred.constness == ty::BoundConstness::NotConst { - self.nominal_obligations_without_const(trait_ref.def_id, trait_ref.substs) + self.nominal_obligations_without_const(trait_ref.def_id, trait_ref.args) } else { - self.nominal_obligations(trait_ref.def_id, trait_ref.substs) + self.nominal_obligations(trait_ref.def_id, trait_ref.args) }; debug!("compute_trait_pred obligations {:?}", obligations); @@ -383,7 +383,7 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { self.out.extend( trait_ref - .substs + .args .iter() .enumerate() .filter(|(_, arg)| { @@ -416,7 +416,7 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { // Compute the obligations that are required for `trait_ref` to be WF, // given that it is a *negative* trait predicate. fn compute_negative_trait_pred(&mut self, trait_ref: &ty::TraitRef<'tcx>) { - for arg in trait_ref.substs { + for arg in trait_ref.args { self.compute(arg); } } @@ -427,7 +427,7 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { // A projection is well-formed if // // (a) its predicates hold (*) - // (b) its substs are wf + // (b) its args are wf // // (*) The predicates of an associated type include the predicates of // the trait that it's contained in. For example, given @@ -446,17 +446,17 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { // `i32: Copy` // ] // Projection types do not require const predicates. - let obligations = self.nominal_obligations_without_const(data.def_id, data.substs); + let obligations = self.nominal_obligations_without_const(data.def_id, data.args); self.out.extend(obligations); - self.compute_projection_substs(data.substs); + self.compute_projection_args(data.args); } fn compute_inherent_projection(&mut self, data: ty::AliasTy<'tcx>) { // An inherent projection is well-formed if // // (a) its predicates hold (*) - // (b) its substs are wf + // (b) its args are wf // // (*) The predicates of an inherent associated type include the // predicates of the impl that it's contained in. @@ -464,7 +464,7 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { if !data.self_ty().has_escaping_bound_vars() { // FIXME(inherent_associated_types): Should this happen inside of a snapshot? // FIXME(inherent_associated_types): This is incompatible with the new solver and lazy norm! - let substs = traits::project::compute_inherent_assoc_ty_substs( + let args = traits::project::compute_inherent_assoc_ty_args( &mut traits::SelectionContext::new(self.infcx), self.param_env, data, @@ -473,22 +473,21 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { &mut self.out, ); // Inherent projection types do not require const predicates. - let obligations = self.nominal_obligations_without_const(data.def_id, substs); + let obligations = self.nominal_obligations_without_const(data.def_id, args); self.out.extend(obligations); } - self.compute_projection_substs(data.substs); + self.compute_projection_args(data.args); } - fn compute_projection_substs(&mut self, substs: SubstsRef<'tcx>) { + fn compute_projection_args(&mut self, args: GenericArgsRef<'tcx>) { let tcx = self.tcx(); let cause = self.cause(traits::WellFormed(None)); let param_env = self.param_env; let depth = self.recursion_depth; self.out.extend( - substs - .iter() + args.iter() .filter(|arg| { matches!(arg.unpack(), GenericArgKind::Type(..) | GenericArgKind::Const(..)) }) @@ -541,7 +540,7 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { match ct.kind() { ty::ConstKind::Unevaluated(uv) => { if !ct.has_escaping_bound_vars() { - let obligations = self.nominal_obligations(uv.def, uv.substs); + let obligations = self.nominal_obligations(uv.def, uv.args); self.out.extend(obligations); let predicate = ty::Binder::dummy(ty::PredicateKind::Clause( @@ -571,7 +570,7 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { )); } ty::ConstKind::Expr(_) => { - // FIXME(generic_const_exprs): this doesnt verify that given `Expr(N + 1)` the + // FIXME(generic_const_exprs): this doesn't verify that given `Expr(N + 1)` the // trait bound `typeof(N): Add<typeof(1)>` holds. This is currently unnecessary // as `ConstKind::Expr` is only produced via normalization of `ConstKind::Unevaluated` // which means that the `DefId` would have been typeck'd elsewhere. However in @@ -661,14 +660,14 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { self.compute_inherent_projection(data); } - ty::Adt(def, substs) => { + ty::Adt(def, args) => { // WfNominalType - let obligations = self.nominal_obligations(def.did(), substs); + let obligations = self.nominal_obligations(def.did(), args); self.out.extend(obligations); } - ty::FnDef(did, substs) => { - let obligations = self.nominal_obligations_without_const(did, substs); + ty::FnDef(did, args) => { + let obligations = self.nominal_obligations_without_const(did, args); self.out.extend(obligations); } @@ -688,7 +687,7 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { } } - ty::Generator(did, substs, ..) => { + ty::Generator(did, args, ..) => { // Walk ALL the types in the generator: this will // include the upvar types as well as the yield // type. Note that this is mildly distinct from @@ -696,11 +695,11 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { // about the signature of the closure. We don't // have the problem of implied bounds here since // generators don't take arguments. - let obligations = self.nominal_obligations(did, substs); + let obligations = self.nominal_obligations(did, args); self.out.extend(obligations); } - ty::Closure(did, substs) => { + ty::Closure(did, args) => { // Only check the upvar types for WF, not the rest // of the types within. This is needed because we // capture the signature and it may not be WF @@ -723,7 +722,7 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { // fn(&'a T) }`, as discussed in #25860. walker.skip_current_subtree(); // subtree handled below // FIXME(eddyb) add the type to `walker` instead of recursing. - self.compute(substs.as_closure().tupled_upvars_ty().into()); + self.compute(args.as_closure().tupled_upvars_ty().into()); // Note that we cannot skip the generic types // types. Normally, within the fn // body where they are created, the generics will @@ -739,7 +738,7 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { // can cause compiler crashes when the user abuses unsafe // code to procure such a closure. // See tests/ui/type-alias-impl-trait/wf_check_closures.rs - let obligations = self.nominal_obligations(did, substs); + let obligations = self.nominal_obligations(did, args); self.out.extend(obligations); } @@ -748,18 +747,18 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { // types appearing in the fn signature } - ty::Alias(ty::Opaque, ty::AliasTy { def_id, substs, .. }) => { + ty::Alias(ty::Opaque, ty::AliasTy { def_id, args, .. }) => { // All of the requirements on type parameters // have already been checked for `impl Trait` in // return position. We do need to check type-alias-impl-trait though. if self.tcx().is_type_alias_impl_trait(def_id) { - let obligations = self.nominal_obligations(def_id, substs); + let obligations = self.nominal_obligations(def_id, args); self.out.extend(obligations); } } - ty::Alias(ty::Weak, ty::AliasTy { def_id, substs, .. }) => { - let obligations = self.nominal_obligations(def_id, substs); + ty::Alias(ty::Weak, ty::AliasTy { def_id, args, .. }) => { + let obligations = self.nominal_obligations(def_id, args); self.out.extend(obligations); } @@ -826,7 +825,7 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { fn nominal_obligations_inner( &mut self, def_id: DefId, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, remap_constness: bool, ) -> Vec<traits::PredicateObligation<'tcx>> { let predicates = self.tcx().predicates_of(def_id); @@ -837,7 +836,7 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { origins.extend(iter::repeat(parent).take(head.predicates.len())); } - let predicates = predicates.instantiate(self.tcx(), substs); + let predicates = predicates.instantiate(self.tcx(), args); trace!("{:#?}", predicates); debug_assert_eq!(predicates.predicates.len(), origins.len()); @@ -867,17 +866,17 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { fn nominal_obligations( &mut self, def_id: DefId, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, ) -> Vec<traits::PredicateObligation<'tcx>> { - self.nominal_obligations_inner(def_id, substs, false) + self.nominal_obligations_inner(def_id, args, false) } fn nominal_obligations_without_const( &mut self, def_id: DefId, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, ) -> Vec<traits::PredicateObligation<'tcx>> { - self.nominal_obligations_inner(def_id, substs, true) + self.nominal_obligations_inner(def_id, args, true) } fn from_object_ty( diff --git a/compiler/rustc_traits/src/dropck_outlives.rs b/compiler/rustc_traits/src/dropck_outlives.rs index f35c14eeac8..074764f0c4e 100644 --- a/compiler/rustc_traits/src/dropck_outlives.rs +++ b/compiler/rustc_traits/src/dropck_outlives.rs @@ -4,7 +4,7 @@ use rustc_infer::infer::canonical::{Canonical, QueryResponse}; use rustc_infer::infer::TyCtxtInferExt; use rustc_middle::query::Providers; use rustc_middle::traits::query::{DropckConstraint, DropckOutlivesResult}; -use rustc_middle::ty::InternalSubsts; +use rustc_middle::ty::GenericArgs; use rustc_middle::ty::TyCtxt; use rustc_trait_selection::infer::InferCtxtBuilderExt; use rustc_trait_selection::traits::query::dropck_outlives::{ @@ -41,11 +41,11 @@ pub(crate) fn adt_dtorck_constraint( } else if def.is_phantom_data() { // The first generic parameter here is guaranteed to be a type because it's // `PhantomData`. - let substs = InternalSubsts::identity_for_item(tcx, def_id); - assert_eq!(substs.len(), 1); + let args = GenericArgs::identity_for_item(tcx, def_id); + assert_eq!(args.len(), 1); let result = DropckConstraint { outlives: vec![], - dtorck_types: vec![substs.type_at(0)], + dtorck_types: vec![args.type_at(0)], overflows: vec![], }; debug!("dtorck_constraint: {:?} => {:?}", def, result); @@ -54,7 +54,7 @@ pub(crate) fn adt_dtorck_constraint( let mut result = DropckConstraint::empty(); for field in def.all_fields() { - let fty = tcx.type_of(field.did).subst_identity(); + let fty = tcx.type_of(field.did).instantiate_identity(); dtorck_constraint_for_ty_inner(tcx, span, fty, 0, fty, &mut result)?; } result.outlives.extend(tcx.destructor_constraints(def)); diff --git a/compiler/rustc_traits/src/normalize_projection_ty.rs b/compiler/rustc_traits/src/normalize_projection_ty.rs index 83828f177bc..0dbac56b47d 100644 --- a/compiler/rustc_traits/src/normalize_projection_ty.rs +++ b/compiler/rustc_traits/src/normalize_projection_ty.rs @@ -58,7 +58,7 @@ fn normalize_weak_ty<'tcx>( tcx.infer_ctxt().enter_canonical_trait_query( &goal, |ocx, ParamEnvAnd { param_env, value: goal }| { - let obligations = tcx.predicates_of(goal.def_id).instantiate_own(tcx, goal.substs).map( + let obligations = tcx.predicates_of(goal.def_id).instantiate_own(tcx, goal.args).map( |(predicate, span)| { traits::Obligation::new( tcx, @@ -69,7 +69,7 @@ fn normalize_weak_ty<'tcx>( }, ); ocx.register_obligations(obligations); - let normalized_ty = tcx.type_of(goal.def_id).subst(tcx, goal.substs); + let normalized_ty = tcx.type_of(goal.def_id).instantiate(tcx, goal.args); Ok(NormalizationResult { normalized_ty }) }, ) diff --git a/compiler/rustc_transmute/src/layout/tree.rs b/compiler/rustc_transmute/src/layout/tree.rs index be434eb7d00..8bd26818256 100644 --- a/compiler/rustc_transmute/src/layout/tree.rs +++ b/compiler/rustc_transmute/src/layout/tree.rs @@ -175,8 +175,8 @@ pub(crate) mod rustc { use rustc_middle::ty::layout::LayoutError; use rustc_middle::ty::util::Discr; use rustc_middle::ty::AdtDef; + use rustc_middle::ty::GenericArgsRef; use rustc_middle::ty::ParamEnv; - use rustc_middle::ty::SubstsRef; use rustc_middle::ty::VariantDef; use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt}; use rustc_span::ErrorGuaranteed; @@ -297,7 +297,7 @@ pub(crate) mod rustc { .fold(Tree::unit(), |tree, elt| tree.then(elt))) } - ty::Adt(adt_def, substs_ref) => { + ty::Adt(adt_def, args_ref) => { use rustc_middle::ty::AdtKind; // If the layout is ill-specified, halt. @@ -316,7 +316,7 @@ pub(crate) mod rustc { AdtKind::Struct => Self::from_repr_c_variant( ty, *adt_def, - substs_ref, + args_ref, &layout_summary, None, adt_def.non_enum_variant(), @@ -330,7 +330,7 @@ pub(crate) mod rustc { tree = tree.or(Self::from_repr_c_variant( ty, *adt_def, - substs_ref, + args_ref, &layout_summary, Some(discr), adt_def.variant(idx), @@ -351,7 +351,7 @@ pub(crate) mod rustc { let mut tree = Tree::uninhabited(); for field in adt_def.all_fields() { - let variant_ty = field.ty(tcx, substs_ref); + let variant_ty = field.ty(tcx, args_ref); let variant_layout = layout_of(tcx, variant_ty)?; let padding_needed = ty_layout.size() - variant_layout.size(); let variant = Self::def(Def::Field(field)) @@ -383,7 +383,7 @@ pub(crate) mod rustc { fn from_repr_c_variant( ty: Ty<'tcx>, adt_def: AdtDef<'tcx>, - substs_ref: SubstsRef<'tcx>, + args_ref: GenericArgsRef<'tcx>, layout_summary: &LayoutSummary, discr: Option<Discr<'tcx>>, variant_def: &'tcx VariantDef, @@ -427,7 +427,7 @@ pub(crate) mod rustc { // Next come fields. let fields_span = trace_span!("treeifying fields").entered(); for field_def in variant_def.fields.iter() { - let field_ty = field_def.ty(tcx, substs_ref); + let field_ty = field_def.ty(tcx, args_ref); let _span = trace_span!("treeifying field", field = ?field_ty).entered(); // begin with the field's visibility diff --git a/compiler/rustc_ty_utils/src/abi.rs b/compiler/rustc_ty_utils/src/abi.rs index 55484f5c72e..d0a7414b4ff 100644 --- a/compiler/rustc_ty_utils/src/abi.rs +++ b/compiler/rustc_ty_utils/src/abi.rs @@ -51,12 +51,12 @@ fn fn_sig_for_fn_abi<'tcx>( // // We normalize the `fn_sig` again after substituting at a later point. let mut sig = match *ty.kind() { - ty::FnDef(def_id, substs) => tcx + ty::FnDef(def_id, args) => tcx .fn_sig(def_id) .map_bound(|fn_sig| { tcx.normalize_erasing_regions(tcx.param_env(def_id), fn_sig) }) - .subst(tcx, substs), + .instantiate(tcx, args), _ => unreachable!(), }; @@ -71,8 +71,8 @@ fn fn_sig_for_fn_abi<'tcx>( } sig } - ty::Closure(def_id, substs) => { - let sig = substs.as_closure().sig(); + ty::Closure(def_id, args) => { + let sig = args.as_closure().sig(); let bound_vars = tcx.mk_bound_variable_kinds_from_iter( sig.bound_vars().iter().chain(iter::once(ty::BoundVariableKind::Region(ty::BrEnv))), @@ -82,7 +82,7 @@ fn fn_sig_for_fn_abi<'tcx>( kind: ty::BoundRegionKind::BrEnv, }; let env_region = ty::Region::new_late_bound(tcx, ty::INNERMOST, br); - let env_ty = tcx.closure_env_ty(def_id, substs, env_region).unwrap(); + let env_ty = tcx.closure_env_ty(def_id, args, env_region).unwrap(); let sig = sig.skip_binder(); ty::Binder::bind_with_vars( @@ -96,8 +96,8 @@ fn fn_sig_for_fn_abi<'tcx>( bound_vars, ) } - ty::Generator(did, substs, _) => { - let sig = substs.as_generator().poly_sig(); + ty::Generator(did, args, _) => { + let sig = args.as_generator().poly_sig(); let bound_vars = tcx.mk_bound_variable_kinds_from_iter( sig.bound_vars().iter().chain(iter::once(ty::BoundVariableKind::Region(ty::BrEnv))), @@ -111,8 +111,8 @@ fn fn_sig_for_fn_abi<'tcx>( let pin_did = tcx.require_lang_item(LangItem::Pin, None); let pin_adt_ref = tcx.adt_def(pin_did); - let pin_substs = tcx.mk_substs(&[env_ty.into()]); - let env_ty = Ty::new_adt(tcx, pin_adt_ref, pin_substs); + let pin_args = tcx.mk_args(&[env_ty.into()]); + let env_ty = Ty::new_adt(tcx, pin_adt_ref, pin_args); let sig = sig.skip_binder(); // The `FnSig` and the `ret_ty` here is for a generators main @@ -123,8 +123,8 @@ fn fn_sig_for_fn_abi<'tcx>( // The signature should be `Future::poll(_, &mut Context<'_>) -> Poll<Output>` let poll_did = tcx.require_lang_item(LangItem::Poll, None); let poll_adt_ref = tcx.adt_def(poll_did); - let poll_substs = tcx.mk_substs(&[sig.return_ty.into()]); - let ret_ty = Ty::new_adt(tcx, poll_adt_ref, poll_substs); + let poll_args = tcx.mk_args(&[sig.return_ty.into()]); + let ret_ty = Ty::new_adt(tcx, poll_adt_ref, poll_args); // We have to replace the `ResumeTy` that is used for type and borrow checking // with `&mut Context<'_>` which is used in codegen. @@ -145,8 +145,8 @@ fn fn_sig_for_fn_abi<'tcx>( // The signature should be `Generator::resume(_, Resume) -> GeneratorState<Yield, Return>` let state_did = tcx.require_lang_item(LangItem::GeneratorState, None); let state_adt_ref = tcx.adt_def(state_did); - let state_substs = tcx.mk_substs(&[sig.yield_ty.into(), sig.return_ty.into()]); - let ret_ty = Ty::new_adt(tcx, state_adt_ref, state_substs); + let state_args = tcx.mk_args(&[sig.yield_ty.into(), sig.return_ty.into()]); + let ret_ty = Ty::new_adt(tcx, state_adt_ref, state_args); (sig.resume_ty, ret_ty) }; diff --git a/compiler/rustc_ty_utils/src/assoc.rs b/compiler/rustc_ty_utils/src/assoc.rs index 7e22ef89ed3..4a544232174 100644 --- a/compiler/rustc_ty_utils/src/assoc.rs +++ b/compiler/rustc_ty_utils/src/assoc.rs @@ -5,7 +5,7 @@ use rustc_hir::def_id::{DefId, DefIdMap, LocalDefId}; use rustc_hir::definitions::DefPathData; use rustc_hir::intravisit::{self, Visitor}; use rustc_middle::query::Providers; -use rustc_middle::ty::{self, ImplTraitInTraitData, InternalSubsts, Ty, TyCtxt}; +use rustc_middle::ty::{self, GenericArgs, ImplTraitInTraitData, Ty, TyCtxt}; use rustc_span::symbol::kw; pub fn provide(providers: &mut Providers) { @@ -215,7 +215,9 @@ fn associated_types_for_impl_traits_in_associated_fn( } DefKind::Impl { .. } => { - let Some(trait_fn_def_id) = tcx.associated_item(fn_def_id).trait_item_def_id else { return &[] }; + let Some(trait_fn_def_id) = tcx.associated_item(fn_def_id).trait_item_def_id else { + return &[]; + }; tcx.arena.alloc_from_iter( tcx.associated_types_for_impl_traits_in_associated_fn(trait_fn_def_id).iter().map( @@ -288,7 +290,7 @@ fn associated_type_for_impl_trait_in_trait( trait_assoc_ty.type_of(ty::EarlyBinder::bind(Ty::new_opaque( tcx, opaque_ty_def_id.to_def_id(), - InternalSubsts::identity_for_item(tcx, opaque_ty_def_id), + GenericArgs::identity_for_item(tcx, opaque_ty_def_id), ))); trait_assoc_ty.is_type_alias_impl_trait(false); diff --git a/compiler/rustc_ty_utils/src/consts.rs b/compiler/rustc_ty_utils/src/consts.rs index 426c98012b3..383cc996b9e 100644 --- a/compiler/rustc_ty_utils/src/consts.rs +++ b/compiler/rustc_ty_utils/src/consts.rs @@ -42,7 +42,7 @@ pub(crate) fn destructure_const<'tcx>( (field_consts, None) } ty::Adt(def, _) if def.variants().is_empty() => bug!("unreachable"), - ty::Adt(def, substs) => { + ty::Adt(def, args) => { let (variant_idx, branches) = if def.is_enum() { let (head, rest) = branches.split_first().unwrap(); (VariantIdx::from_u32(head.unwrap_leaf().try_to_u32().unwrap()), rest) @@ -53,7 +53,7 @@ pub(crate) fn destructure_const<'tcx>( let mut field_consts = Vec::with_capacity(fields.len()); for (field, field_valtree) in iter::zip(fields, branches) { - let field_ty = field.ty(tcx, substs); + let field_ty = field.ty(tcx, args); let field_const = ty::Const::new_value(tcx, *field_valtree, field_ty); field_consts.push(field_const); } @@ -133,8 +133,8 @@ fn recurse_build<'tcx>( let val = ty::ValTree::zst(); ty::Const::new_value(tcx, val, node.ty) } - &ExprKind::NamedConst { def_id, substs, user_ty: _ } => { - let uneval = ty::UnevaluatedConst::new(def_id, substs); + &ExprKind::NamedConst { def_id, args, user_ty: _ } => { + let uneval = ty::UnevaluatedConst::new(def_id, args); ty::Const::new_unevaluated(tcx, uneval, node.ty) } ExprKind::ConstParam { param, .. } => ty::Const::new_param(tcx, *param, node.ty), @@ -174,7 +174,7 @@ fn recurse_build<'tcx>( } // `ExprKind::Use` happens when a `hir::ExprKind::Cast` is a // "coercion cast" i.e. using a coercion or is a no-op. - // This is important so that `N as usize as usize` doesnt unify with `N as usize`. (untested) + // This is important so that `N as usize as usize` doesn't unify with `N as usize`. (untested) &ExprKind::Use { source } => { let arg = recurse_build(tcx, body, source, root_span)?; ty::Const::new_expr(tcx, Expr::Cast(CastKind::Use, arg, node.ty), node.ty) @@ -306,8 +306,9 @@ impl<'a, 'tcx> IsThirPolymorphic<'a, 'tcx> { } match expr.kind { - thir::ExprKind::NamedConst { substs, .. } - | thir::ExprKind::ConstBlock { substs, .. } => substs.has_non_region_param(), + thir::ExprKind::NamedConst { args, .. } | thir::ExprKind::ConstBlock { args, .. } => { + args.has_non_region_param() + } thir::ExprKind::ConstParam { .. } => true, thir::ExprKind::Repeat { value, count } => { self.visit_expr(&self.thir()[value]); diff --git a/compiler/rustc_ty_utils/src/implied_bounds.rs b/compiler/rustc_ty_utils/src/implied_bounds.rs index 2822595a8a7..be063a097c0 100644 --- a/compiler/rustc_ty_utils/src/implied_bounds.rs +++ b/compiler/rustc_ty_utils/src/implied_bounds.rs @@ -13,7 +13,7 @@ pub fn provide(providers: &mut Providers) { fn assumed_wf_types<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> &'tcx [(Ty<'tcx>, Span)] { match tcx.def_kind(def_id) { DefKind::Fn => { - let sig = tcx.fn_sig(def_id).subst_identity(); + let sig = tcx.fn_sig(def_id).instantiate_identity(); let liberated_sig = tcx.liberate_late_bound_regions(def_id.to_def_id(), sig); tcx.arena.alloc_from_iter(itertools::zip_eq( liberated_sig.inputs_and_output, @@ -21,7 +21,7 @@ fn assumed_wf_types<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> &'tcx [(Ty<' )) } DefKind::AssocFn => { - let sig = tcx.fn_sig(def_id).subst_identity(); + let sig = tcx.fn_sig(def_id).instantiate_identity(); let liberated_sig = tcx.liberate_late_bound_regions(def_id.to_def_id(), sig); let mut assumed_wf_types: Vec<_> = tcx.assumed_wf_types(tcx.local_parent(def_id)).into(); @@ -35,8 +35,8 @@ fn assumed_wf_types<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> &'tcx [(Ty<' // Trait arguments and the self type for trait impls or only the self type for // inherent impls. let tys = match tcx.impl_trait_ref(def_id) { - Some(trait_ref) => trait_ref.skip_binder().substs.types().collect(), - None => vec![tcx.type_of(def_id).subst_identity()], + Some(trait_ref) => trait_ref.skip_binder().args.types().collect(), + None => vec![tcx.type_of(def_id).instantiate_identity()], }; let mut impl_spans = impl_spans(tcx, def_id); diff --git a/compiler/rustc_ty_utils/src/instance.rs b/compiler/rustc_ty_utils/src/instance.rs index 1d93a79e591..16b1836ba9f 100644 --- a/compiler/rustc_ty_utils/src/instance.rs +++ b/compiler/rustc_ty_utils/src/instance.rs @@ -3,19 +3,19 @@ use rustc_hir::def_id::DefId; use rustc_infer::infer::TyCtxtInferExt; use rustc_middle::query::Providers; use rustc_middle::traits::CodegenObligationError; -use rustc_middle::ty::subst::SubstsRef; +use rustc_middle::ty::GenericArgsRef; use rustc_middle::ty::{self, Instance, TyCtxt, TypeVisitableExt}; use rustc_span::sym; use rustc_trait_selection::traits; -use traits::{translate_substs, Reveal}; +use traits::{translate_args, Reveal}; use crate::errors::UnexpectedFnPtrAssociatedItem; fn resolve_instance<'tcx>( tcx: TyCtxt<'tcx>, - key: ty::ParamEnvAnd<'tcx, (DefId, SubstsRef<'tcx>)>, + key: ty::ParamEnvAnd<'tcx, (DefId, GenericArgsRef<'tcx>)>, ) -> Result<Option<Instance<'tcx>>, ErrorGuaranteed> { - let (param_env, (def, substs)) = key.into_parts(); + let (param_env, (def, args)) = key.into_parts(); let result = if let Some(trait_def_id) = tcx.trait_of_item(def) { debug!(" => associated item, attempting to find impl in param_env {:#?}", param_env); @@ -24,19 +24,19 @@ fn resolve_instance<'tcx>( def, param_env, trait_def_id, - tcx.normalize_erasing_regions(param_env, substs), + tcx.normalize_erasing_regions(param_env, args), ) } else { let ty = tcx.type_of(def); - let item_type = tcx.subst_and_normalize_erasing_regions(substs, param_env, ty); + let item_type = tcx.subst_and_normalize_erasing_regions(args, param_env, ty); let def = match *item_type.kind() { ty::FnDef(def_id, ..) if tcx.is_intrinsic(def_id) => { debug!(" => intrinsic"); ty::InstanceDef::Intrinsic(def) } - ty::FnDef(def_id, substs) if Some(def_id) == tcx.lang_items().drop_in_place_fn() => { - let ty = substs.type_at(0); + ty::FnDef(def_id, args) if Some(def_id) == tcx.lang_items().drop_in_place_fn() => { + let ty = args.type_at(0); if ty.needs_drop(tcx, param_env) { debug!(" => nontrivial drop glue"); @@ -63,7 +63,7 @@ fn resolve_instance<'tcx>( ty::InstanceDef::Item(def) } }; - Ok(Some(Instance { def, substs })) + Ok(Some(Instance { def, args })) }; debug!("inner_resolve_instance: result={:?}", result); result @@ -74,11 +74,11 @@ fn resolve_associated_item<'tcx>( trait_item_id: DefId, param_env: ty::ParamEnv<'tcx>, trait_id: DefId, - rcvr_substs: SubstsRef<'tcx>, + rcvr_args: GenericArgsRef<'tcx>, ) -> Result<Option<Instance<'tcx>>, ErrorGuaranteed> { - debug!(?trait_item_id, ?param_env, ?trait_id, ?rcvr_substs, "resolve_associated_item"); + debug!(?trait_item_id, ?param_env, ?trait_id, ?rcvr_args, "resolve_associated_item"); - let trait_ref = ty::TraitRef::from_method(tcx, trait_id, rcvr_substs); + let trait_ref = ty::TraitRef::from_method(tcx, trait_id, rcvr_args); let vtbl = match tcx.codegen_select_candidate((param_env, trait_ref)) { Ok(vtbl) => vtbl, @@ -102,9 +102,9 @@ fn resolve_associated_item<'tcx>( traits::ImplSource::UserDefined(impl_data) => { debug!( "resolving ImplSource::UserDefined: {:?}, {:?}, {:?}, {:?}", - param_env, trait_item_id, rcvr_substs, impl_data + param_env, trait_item_id, rcvr_args, impl_data ); - assert!(!rcvr_substs.has_infer()); + assert!(!rcvr_args.has_infer()); assert!(!trait_ref.has_infer()); let trait_def_id = tcx.trait_id_of_impl(impl_data.impl_def_id).unwrap(); @@ -117,15 +117,15 @@ fn resolve_associated_item<'tcx>( }); let infcx = tcx.infer_ctxt().build(); let param_env = param_env.with_reveal_all_normalized(tcx); - let substs = rcvr_substs.rebase_onto(tcx, trait_def_id, impl_data.substs); - let substs = translate_substs( + let args = rcvr_args.rebase_onto(tcx, trait_def_id, impl_data.args); + let args = translate_args( &infcx, param_env, impl_data.impl_def_id, - substs, + args, leaf_def.defining_node, ); - let substs = infcx.tcx.erase_regions(substs); + let args = infcx.tcx.erase_regions(args); // Since this is a trait item, we need to see if the item is either a trait default item // or a specialization because we can't resolve those unless we can `Reveal::All`. @@ -159,7 +159,7 @@ fn resolve_associated_item<'tcx>( return Err(guard); } - let substs = tcx.erase_regions(substs); + let args = tcx.erase_regions(args); // Check if we just resolved an associated `const` declaration from // a `trait` to an associated `const` definition in an `impl`, where @@ -175,14 +175,11 @@ fn resolve_associated_item<'tcx>( ))?; } - Some(ty::Instance::new(leaf_def.item.def_id, substs)) + Some(ty::Instance::new(leaf_def.item.def_id, args)) } traits::ImplSource::Object(ref data) => { traits::get_vtable_index_of_object_method(tcx, data, trait_item_id).map(|index| { - Instance { - def: ty::InstanceDef::Virtual(trait_item_id, index), - substs: rcvr_substs, - } + Instance { def: ty::InstanceDef::Virtual(trait_item_id, index), args: rcvr_args } }) } traits::ImplSource::Builtin(..) => { @@ -205,14 +202,14 @@ fn resolve_associated_item<'tcx>( Some(Instance { def: ty::InstanceDef::CloneShim(trait_item_id, self_ty), - substs: rcvr_substs, + args: rcvr_args, }) } else { assert_eq!(name, sym::clone_from); // Use the default `fn clone_from` from `trait Clone`. - let substs = tcx.erase_regions(rcvr_substs); - Some(ty::Instance::new(trait_item_id, substs)) + let args = tcx.erase_regions(rcvr_args); + Some(ty::Instance::new(trait_item_id, args)) } } else if Some(trait_ref.def_id) == lang_items.fn_ptr_trait() { if lang_items.fn_ptr_addr() == Some(trait_item_id) { @@ -222,7 +219,7 @@ fn resolve_associated_item<'tcx>( } Some(Instance { def: ty::InstanceDef::FnPtrAddrShim(trait_item_id, self_ty), - substs: rcvr_substs, + args: rcvr_args, }) } else { tcx.sess.emit_fatal(UnexpectedFnPtrAssociatedItem { @@ -230,20 +227,20 @@ fn resolve_associated_item<'tcx>( }) } } else if Some(trait_ref.def_id) == lang_items.future_trait() { - let ty::Generator(generator_def_id, substs, _) = *rcvr_substs.type_at(0).kind() else { + let ty::Generator(generator_def_id, args, _) = *rcvr_args.type_at(0).kind() else { bug!() }; if Some(trait_item_id) == tcx.lang_items().future_poll_fn() { // `Future::poll` is generated by the compiler. - Some(Instance { def: ty::InstanceDef::Item(generator_def_id), substs: substs }) + Some(Instance { def: ty::InstanceDef::Item(generator_def_id), args: args }) } else { // All other methods are default methods of the `Future` trait. // (this assumes that `ImplSource::Builtin` is only used for methods on `Future`) debug_assert!(tcx.defaultness(trait_item_id).has_value()); - Some(Instance::new(trait_item_id, rcvr_substs)) + Some(Instance::new(trait_item_id, rcvr_args)) } } else if Some(trait_ref.def_id) == lang_items.gen_trait() { - let ty::Generator(generator_def_id, substs, _) = *rcvr_substs.type_at(0).kind() else { + let ty::Generator(generator_def_id, args, _) = *rcvr_args.type_at(0).kind() else { bug!() }; if cfg!(debug_assertions) && tcx.item_name(trait_item_id) != sym::resume { @@ -257,7 +254,7 @@ fn resolve_associated_item<'tcx>( tcx.item_name(trait_item_id) ) } - Some(Instance { def: ty::InstanceDef::Item(generator_def_id), substs }) + Some(Instance { def: ty::InstanceDef::Item(generator_def_id), args }) } else if tcx.fn_trait_kind_from_def_id(trait_ref.def_id).is_some() { // FIXME: This doesn't check for malformed libcore that defines, e.g., // `trait Fn { fn call_once(&self) { .. } }`. This is mostly for extension @@ -275,14 +272,14 @@ fn resolve_associated_item<'tcx>( tcx.item_name(trait_item_id) ) } - match *rcvr_substs.type_at(0).kind() { - ty::Closure(closure_def_id, substs) => { + match *rcvr_args.type_at(0).kind() { + ty::Closure(closure_def_id, args) => { let trait_closure_kind = tcx.fn_trait_kind_from_def_id(trait_id).unwrap(); - Instance::resolve_closure(tcx, closure_def_id, substs, trait_closure_kind) + Instance::resolve_closure(tcx, closure_def_id, args, trait_closure_kind) } ty::FnDef(..) | ty::FnPtr(..) => Some(Instance { - def: ty::InstanceDef::FnPtrShim(trait_item_id, rcvr_substs.type_at(0)), - substs: rcvr_substs, + def: ty::InstanceDef::FnPtrShim(trait_item_id, rcvr_args.type_at(0)), + args: rcvr_args, }), _ => bug!( "no built-in definition for `{trait_ref}::{}` for non-fn type", diff --git a/compiler/rustc_ty_utils/src/layout.rs b/compiler/rustc_ty_utils/src/layout.rs index b67cd96a734..b840ff184e0 100644 --- a/compiler/rustc_ty_utils/src/layout.rs +++ b/compiler/rustc_ty_utils/src/layout.rs @@ -8,7 +8,7 @@ use rustc_middle::ty::layout::{ IntegerExt, LayoutCx, LayoutError, LayoutOf, TyAndLayout, MAX_SIMD_LANES, }; use rustc_middle::ty::{ - self, subst::SubstsRef, AdtDef, EarlyBinder, ReprOptions, Ty, TyCtxt, TypeVisitableExt, + self, AdtDef, EarlyBinder, GenericArgsRef, ReprOptions, Ty, TyCtxt, TypeVisitableExt, }; use rustc_session::{DataTypeKind, FieldInfo, FieldKind, SizeKind, VariantInfo}; use rustc_span::symbol::Symbol; @@ -258,6 +258,8 @@ fn layout_of_uncached<'tcx>( largest_niche, align: element.align, size, + max_repr_align: None, + unadjusted_abi_align: element.align.abi, }) } ty::Slice(element) => { @@ -269,6 +271,8 @@ fn layout_of_uncached<'tcx>( largest_niche: None, align: element.align, size: Size::ZERO, + max_repr_align: None, + unadjusted_abi_align: element.align.abi, }) } ty::Str => tcx.mk_layout(LayoutS { @@ -278,6 +282,8 @@ fn layout_of_uncached<'tcx>( largest_niche: None, align: dl.i8_align, size: Size::ZERO, + max_repr_align: None, + unadjusted_abi_align: dl.i8_align.abi, }), // Odd unit types. @@ -299,10 +305,10 @@ fn layout_of_uncached<'tcx>( tcx.mk_layout(unit) } - ty::Generator(def_id, substs, _) => generator_layout(cx, ty, def_id, substs)?, + ty::Generator(def_id, args, _) => generator_layout(cx, ty, def_id, args)?, - ty::Closure(_, ref substs) => { - let tys = substs.as_closure().upvar_tys(); + ty::Closure(_, ref args) => { + let tys = args.as_closure().upvar_tys(); univariant( &tys.map(|ty| Ok(cx.layout_of(ty)?.layout)).try_collect::<IndexVec<_, _>>()?, &ReprOptions::default(), @@ -322,7 +328,7 @@ fn layout_of_uncached<'tcx>( } // SIMD vector types. - ty::Adt(def, substs) if def.repr().simd() => { + ty::Adt(def, args) if def.repr().simd() => { if !def.is_struct() { // Should have yielded E0517 by now. tcx.sess.delay_span_bug( @@ -349,12 +355,12 @@ fn layout_of_uncached<'tcx>( } // Type of the first ADT field: - let f0_ty = fields[FieldIdx::from_u32(0)].ty(tcx, substs); + let f0_ty = fields[FieldIdx::from_u32(0)].ty(tcx, args); // Heterogeneous SIMD vectors are not supported: // (should be caught by typeck) for fi in fields { - if fi.ty(tcx, substs) != f0_ty { + if fi.ty(tcx, args) != f0_ty { tcx.sess.delay_span_bug( DUMMY_SP, "#[repr(simd)] was applied to an ADT with heterogeneous field type", @@ -431,11 +437,13 @@ fn layout_of_uncached<'tcx>( largest_niche: e_ly.largest_niche, size, align, + max_repr_align: None, + unadjusted_abi_align: align.abi, }) } // ADTs. - ty::Adt(def, substs) => { + ty::Adt(def, args) => { // Cache the field layouts. let variants = def .variants() @@ -443,7 +451,7 @@ fn layout_of_uncached<'tcx>( .map(|v| { v.fields .iter() - .map(|field| Ok(cx.layout_of(field.ty(tcx, substs))?.layout)) + .map(|field| Ok(cx.layout_of(field.ty(tcx, args))?.layout)) .try_collect::<IndexVec<_, _>>() }) .try_collect::<IndexVec<VariantIdx, _>>()?; @@ -482,7 +490,7 @@ fn layout_of_uncached<'tcx>( let maybe_unsized = def.is_struct() && def.non_enum_variant().tail_opt().is_some_and(|last_field| { let param_env = tcx.param_env(def.did()); - !tcx.type_of(last_field.did).subst_identity().is_sized(tcx, param_env) + !tcx.type_of(last_field.did).instantiate_identity().is_sized(tcx, param_env) }); let Some(layout) = cx.layout_of_struct_or_enum( @@ -502,7 +510,7 @@ fn layout_of_uncached<'tcx>( // If the struct tail is sized and can be unsized, check that unsizing doesn't move the fields around. if cfg!(debug_assertions) && maybe_unsized - && def.non_enum_variant().tail().ty(tcx, substs).is_sized(tcx, cx.param_env) + && def.non_enum_variant().tail().ty(tcx, args).is_sized(tcx, cx.param_env) { let mut variants = variants; let tail_replacement = cx.layout_of(Ty::new_slice(tcx, tcx.types.u8)).unwrap(); @@ -525,8 +533,13 @@ fn layout_of_uncached<'tcx>( let FieldsShape::Arbitrary { offsets: sized_offsets, .. } = &layout.fields else { bug!("unexpected FieldsShape for sized layout of {ty:?}: {:?}", layout.fields); }; - let FieldsShape::Arbitrary { offsets: unsized_offsets, .. } = &unsized_layout.fields else { - bug!("unexpected FieldsShape for unsized layout of {ty:?}: {:?}", unsized_layout.fields); + let FieldsShape::Arbitrary { offsets: unsized_offsets, .. } = + &unsized_layout.fields + else { + bug!( + "unexpected FieldsShape for unsized layout of {ty:?}: {:?}", + unsized_layout.fields + ); }; let (sized_tail, sized_fields) = sized_offsets.raw.split_last().unwrap(); @@ -691,11 +704,11 @@ fn generator_layout<'tcx>( cx: &LayoutCx<'tcx, TyCtxt<'tcx>>, ty: Ty<'tcx>, def_id: hir::def_id::DefId, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, ) -> Result<Layout<'tcx>, &'tcx LayoutError<'tcx>> { use SavedLocalEligibility::*; let tcx = cx.tcx; - let subst_field = |ty: Ty<'tcx>| EarlyBinder::bind(ty).subst(tcx, substs); + let subst_field = |ty: Ty<'tcx>| EarlyBinder::bind(ty).instantiate(tcx, args); let Some(info) = tcx.generator_layout(def_id) else { return Err(error(cx, LayoutError::Unknown(ty))); @@ -705,7 +718,7 @@ fn generator_layout<'tcx>( // Build a prefix layout, including "promoting" all ineligible // locals as part of the prefix. We compute the layout of all of // these fields at once to get optimal packing. - let tag_index = substs.as_generator().prefix_tys().count(); + let tag_index = args.as_generator().prefix_tys().count(); // `info.variant_fields` already accounts for the reserved variants, so no need to add them. let max_discr = (info.variant_fields.len() - 1) as u128; @@ -721,7 +734,7 @@ fn generator_layout<'tcx>( .map(|local| subst_field(info.field_tys[local].ty)) .map(|ty| Ty::new_maybe_uninit(tcx, ty)) .map(|ty| Ok(cx.layout_of(ty)?.layout)); - let prefix_layouts = substs + let prefix_layouts = args .as_generator() .prefix_tys() .map(|ty| Ok(cx.layout_of(ty)?.layout)) @@ -879,6 +892,8 @@ fn generator_layout<'tcx>( largest_niche: prefix.largest_niche, size, align, + max_repr_align: None, + unadjusted_abi_align: align.abi, }); debug!("generator layout ({:?}): {:#?}", ty, layout); Ok(layout) @@ -929,11 +944,11 @@ fn record_layout_for_printing_outlined<'tcx>( record(adt_kind.into(), adt_packed, opt_discr_size, variant_infos); } - ty::Generator(def_id, substs, _) => { + ty::Generator(def_id, args, _) => { debug!("print-type-size t: `{:?}` record generator", layout.ty); // Generators always have a begin/poisoned/end state with additional suspend points let (variant_infos, opt_discr_size) = - variant_info_for_generator(cx, layout, def_id, substs); + variant_info_for_generator(cx, layout, def_id, args); record(DataTypeKind::Generator, false, opt_discr_size, variant_infos); } @@ -1023,7 +1038,7 @@ fn variant_info_for_generator<'tcx>( cx: &LayoutCx<'tcx, TyCtxt<'tcx>>, layout: TyAndLayout<'tcx>, def_id: DefId, - substs: ty::SubstsRef<'tcx>, + args: ty::GenericArgsRef<'tcx>, ) -> (Vec<VariantInfo>, Option<Size>) { let Variants::Multiple { tag, ref tag_encoding, tag_field, .. } = layout.variants else { return (vec![], None); @@ -1033,7 +1048,7 @@ fn variant_info_for_generator<'tcx>( let upvar_names = cx.tcx.closure_saved_names_of_captured_variables(def_id); let mut upvars_size = Size::ZERO; - let upvar_fields: Vec<_> = substs + let upvar_fields: Vec<_> = args .as_generator() .upvar_tys() .zip(upvar_names) @@ -1108,7 +1123,7 @@ fn variant_info_for_generator<'tcx>( } VariantInfo { - name: Some(Symbol::intern(&ty::GeneratorSubsts::variant_name(variant_idx))), + name: Some(Symbol::intern(&ty::GeneratorArgs::variant_name(variant_idx))), kind: SizeKind::Exact, size: variant_size.bytes(), align: variant_layout.align.abi.bytes(), diff --git a/compiler/rustc_ty_utils/src/layout_sanity_check.rs b/compiler/rustc_ty_utils/src/layout_sanity_check.rs index c4a4cda6801..8633334381a 100644 --- a/compiler/rustc_ty_utils/src/layout_sanity_check.rs +++ b/compiler/rustc_ty_utils/src/layout_sanity_check.rs @@ -52,7 +52,7 @@ pub(super) fn sanity_check_layout<'tcx>( let mut fields = non_zst_fields(cx, layout); let Some(first) = fields.next() else { // No fields here, so this could be a primitive or enum -- either way it's not a newtype around a thing - return *layout + return *layout; }; if fields.next().is_none() { let (offset, first) = first; @@ -77,7 +77,7 @@ pub(super) fn sanity_check_layout<'tcx>( Abi::Uninhabited | Abi::Aggregate { .. }, "ABI unexpectedly missing alignment and/or size in {layout:#?}" ); - return + return; }; assert_eq!( layout.layout.align().abi, diff --git a/compiler/rustc_ty_utils/src/needs_drop.rs b/compiler/rustc_ty_utils/src/needs_drop.rs index 9d593dc5e04..3e6dfc1304f 100644 --- a/compiler/rustc_ty_utils/src/needs_drop.rs +++ b/compiler/rustc_ty_utils/src/needs_drop.rs @@ -3,8 +3,8 @@ use rustc_data_structures::fx::FxHashSet; use rustc_hir::def_id::DefId; use rustc_middle::query::Providers; -use rustc_middle::ty::subst::SubstsRef; use rustc_middle::ty::util::{needs_drop_components, AlwaysRequiresDrop}; +use rustc_middle::ty::GenericArgsRef; use rustc_middle::ty::{self, EarlyBinder, Ty, TyCtxt}; use rustc_session::Limit; use rustc_span::{sym, DUMMY_SP}; @@ -80,7 +80,7 @@ impl<'tcx, F> NeedsDropTypes<'tcx, F> { impl<'tcx, F, I> Iterator for NeedsDropTypes<'tcx, F> where - F: Fn(ty::AdtDef<'tcx>, SubstsRef<'tcx>) -> NeedsDropResult<I>, + F: Fn(ty::AdtDef<'tcx>, GenericArgsRef<'tcx>) -> NeedsDropResult<I>, I: Iterator<Item = Ty<'tcx>>, { type Item = NeedsDropResult<Ty<'tcx>>; @@ -119,15 +119,15 @@ where _ if component.is_copy_modulo_regions(tcx, self.param_env) => (), - ty::Closure(_, substs) => { - queue_type(self, substs.as_closure().tupled_upvars_ty()); + ty::Closure(_, args) => { + queue_type(self, args.as_closure().tupled_upvars_ty()); } - ty::Generator(def_id, substs, _) => { - let substs = substs.as_generator(); - queue_type(self, substs.tupled_upvars_ty()); + ty::Generator(def_id, args, _) => { + let args = args.as_generator(); + queue_type(self, args.tupled_upvars_ty()); - let witness = substs.witness(); + let witness = args.witness(); let interior_tys = match witness.kind() { &ty::GeneratorWitness(tys) => tcx.erase_late_bound_regions(tys), _ => { @@ -147,8 +147,8 @@ where // Check for a `Drop` impl and whether this is a union or // `ManuallyDrop`. If it's a struct or enum without a `Drop` // impl then check whether the field types need `Drop`. - ty::Adt(adt_def, substs) => { - let tys = match (self.adt_components)(adt_def, substs) { + ty::Adt(adt_def, args) => { + let tys = match (self.adt_components)(adt_def, args) { Err(e) => return Some(Err(e)), Ok(tys) => tys, }; @@ -210,7 +210,7 @@ fn drop_tys_helper<'tcx>( match subty.kind() { ty::Adt(adt_id, subst) => { for subty in tcx.adt_drop_tys(adt_id.did())? { - vec.push(EarlyBinder::bind(subty).subst(tcx, subst)); + vec.push(EarlyBinder::bind(subty).instantiate(tcx, subst)); } } _ => vec.push(subty), @@ -219,7 +219,7 @@ fn drop_tys_helper<'tcx>( }) } - let adt_components = move |adt_def: ty::AdtDef<'tcx>, substs: SubstsRef<'tcx>| { + let adt_components = move |adt_def: ty::AdtDef<'tcx>, args: GenericArgsRef<'tcx>| { if adt_def.is_manually_drop() { debug!("drop_tys_helper: `{:?}` is manually drop", adt_def); Ok(Vec::new()) @@ -235,7 +235,7 @@ fn drop_tys_helper<'tcx>( // Since the destructor is insignificant, we just want to make sure all of // the passed in type parameters are also insignificant. // Eg: Vec<T> dtor is insignificant when T=i32 but significant when T=Mutex. - Ok(substs.types().collect()) + Ok(args.types().collect()) } } } else if adt_def.is_union() { @@ -243,8 +243,8 @@ fn drop_tys_helper<'tcx>( Ok(Vec::new()) } else { let field_tys = adt_def.all_fields().map(|field| { - let r = tcx.type_of(field.did).subst(tcx, substs); - debug!("drop_tys_helper: Subst into {:?} with {:?} getting {:?}", field, substs, r); + let r = tcx.type_of(field.did).instantiate(tcx, args); + debug!("drop_tys_helper: Subst into {:?} with {:?} getting {:?}", field, args, r); r }); if only_significant { @@ -295,10 +295,10 @@ fn adt_drop_tys<'tcx>( // significant. let adt_has_dtor = |adt_def: ty::AdtDef<'tcx>| adt_def.destructor(tcx).map(|_| DtorType::Significant); - // `tcx.type_of(def_id)` identical to `tcx.make_adt(def, identity_substs)` + // `tcx.type_of(def_id)` identical to `tcx.make_adt(def, identity_args)` drop_tys_helper( tcx, - tcx.type_of(def_id).subst_identity(), + tcx.type_of(def_id).instantiate_identity(), tcx.param_env(def_id), adt_has_dtor, false, @@ -307,7 +307,7 @@ fn adt_drop_tys<'tcx>( .map(|components| tcx.mk_type_list(&components)) } // If `def_id` refers to a generic ADT, the queries above and below act as if they had been handed -// a `tcx.make_ty(def, identity_substs)` and as such it is legal to substitute the generic parameters +// a `tcx.make_ty(def, identity_args)` and as such it is legal to substitute the generic parameters // of the ADT into the outputted `ty`s. fn adt_significant_drop_tys( tcx: TyCtxt<'_>, @@ -315,7 +315,7 @@ fn adt_significant_drop_tys( ) -> Result<&ty::List<Ty<'_>>, AlwaysRequiresDrop> { drop_tys_helper( tcx, - tcx.type_of(def_id).subst_identity(), // identical to `tcx.make_adt(def, identity_substs)` + tcx.type_of(def_id).instantiate_identity(), // identical to `tcx.make_adt(def, identity_args)` tcx.param_env(def_id), adt_consider_insignificant_dtor(tcx), true, diff --git a/compiler/rustc_ty_utils/src/opaque_types.rs b/compiler/rustc_ty_utils/src/opaque_types.rs index 87dfacc4c2d..06a30677d20 100644 --- a/compiler/rustc_ty_utils/src/opaque_types.rs +++ b/compiler/rustc_ty_utils/src/opaque_types.rs @@ -7,7 +7,7 @@ use rustc_middle::ty::util::{CheckRegions, NotUniqueParam}; use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_middle::ty::{TypeSuperVisitable, TypeVisitable, TypeVisitor}; use rustc_span::Span; -use rustc_trait_selection::traits::check_substs_compatible; +use rustc_trait_selection::traits::check_args_compatible; use std::ops::ControlFlow; use crate::errors::{DuplicateArg, NotParam}; @@ -45,7 +45,7 @@ impl<'tcx> OpaqueTypeCollector<'tcx> { fn parent_trait_ref(&self) -> Option<ty::TraitRef<'tcx>> { let parent = self.parent()?; if matches!(self.tcx.def_kind(parent), DefKind::Impl { .. }) { - Some(self.tcx.impl_trait_ref(parent)?.subst_identity()) + Some(self.tcx.impl_trait_ref(parent)?.instantiate_identity()) } else { None } @@ -159,19 +159,19 @@ impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for OpaqueTypeCollector<'tcx> { self.opaques.push(alias_ty.def_id.expect_local()); - match self.tcx.uses_unique_generic_params(alias_ty.substs, CheckRegions::Bound) { + match self.tcx.uses_unique_generic_params(alias_ty.args, CheckRegions::Bound) { Ok(()) => { // FIXME: implement higher kinded lifetime bounds on nested opaque types. They are not // supported at all, so this is sound to do, but once we want to support them, you'll // start seeing the error below. // Collect opaque types nested within the associated type bounds of this opaque type. - // We use identity substs here, because we already know that the opaque type uses + // We use identity args here, because we already know that the opaque type uses // only generic parameters, and thus substituting would not give us more information. for (pred, span) in self .tcx .explicit_item_bounds(alias_ty.def_id) - .subst_identity_iter_copied() + .instantiate_identity_iter_copied() { trace!(?pred); self.visit_spanned(span, pred); @@ -196,7 +196,7 @@ impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for OpaqueTypeCollector<'tcx> { ty::Alias(ty::Weak, alias_ty) if alias_ty.def_id.is_local() => { self.tcx .type_of(alias_ty.def_id) - .subst(self.tcx, alias_ty.substs) + .instantiate(self.tcx, alias_ty.args) .visit_with(self)?; } ty::Alias(ty::Projection, alias_ty) => { @@ -222,22 +222,22 @@ impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for OpaqueTypeCollector<'tcx> { continue; } - let impl_substs = alias_ty.substs.rebase_onto( + let impl_args = alias_ty.args.rebase_onto( self.tcx, parent_trait_ref.def_id, - ty::InternalSubsts::identity_for_item(self.tcx, parent), + ty::GenericArgs::identity_for_item(self.tcx, parent), ); - if check_substs_compatible(self.tcx, assoc, impl_substs) { + if check_args_compatible(self.tcx, assoc, impl_args) { return self .tcx .type_of(assoc.def_id) - .subst(self.tcx, impl_substs) + .instantiate(self.tcx, impl_args) .visit_with(self); } else { self.tcx.sess.delay_span_bug( self.tcx.def_span(assoc.def_id), - "item had incorrect substs", + "item had incorrect args", ); } } @@ -250,15 +250,15 @@ impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for OpaqueTypeCollector<'tcx> { } for variant in def.variants().iter() { for field in variant.fields.iter() { - // Don't use the `ty::Adt` substs, we either - // * found the opaque in the substs + // Don't use the `ty::Adt` args, we either + // * found the opaque in the args // * will find the opaque in the unsubstituted fields // The only other situation that can occur is that after substituting, // some projection resolves to an opaque that we would have otherwise // not found. While we could substitute and walk those, that would mean we // would have to walk all substitutions of an Adt, which can quickly // degenerate into looking at an exponential number of types. - let ty = self.tcx.type_of(field.did).subst_identity(); + let ty = self.tcx.type_of(field.did).instantiate_identity(); self.visit_spanned(self.tcx.def_span(field.did), ty); } } @@ -276,7 +276,7 @@ fn opaque_types_defined_by<'tcx>(tcx: TyCtxt<'tcx>, item: LocalDefId) -> &'tcx [ match kind { // Walk over the signature of the function-like to find the opaques. DefKind::AssocFn | DefKind::Fn => { - let ty_sig = tcx.fn_sig(item).subst_identity(); + let ty_sig = tcx.fn_sig(item).instantiate_identity(); let hir_sig = tcx.hir().get_by_def_id(item).fn_sig().unwrap(); // Walk over the inputs and outputs manually in order to get good spans for them. collector.visit_spanned(hir_sig.decl.output.span(), ty_sig.output()); @@ -291,15 +291,15 @@ fn opaque_types_defined_by<'tcx>(tcx: TyCtxt<'tcx>, item: LocalDefId) -> &'tcx [ Some(ty) => ty.span, _ => tcx.def_span(item), }; - collector.visit_spanned(span, tcx.type_of(item).subst_identity()); + collector.visit_spanned(span, tcx.type_of(item).instantiate_identity()); collector.collect_body_and_predicate_taits(); } // We're also doing this for `AssocTy` for the wf checks in `check_opaque_meets_bounds` DefKind::TyAlias | DefKind::AssocTy => { - tcx.type_of(item).subst_identity().visit_with(&mut collector); + tcx.type_of(item).instantiate_identity().visit_with(&mut collector); } DefKind::OpaqueTy => { - for (pred, span) in tcx.explicit_item_bounds(item).subst_identity_iter_copied() { + for (pred, span) in tcx.explicit_item_bounds(item).instantiate_identity_iter_copied() { collector.visit_spanned(span, pred); } } diff --git a/compiler/rustc_ty_utils/src/representability.rs b/compiler/rustc_ty_utils/src/representability.rs index 0b5e27c2c74..f34e0df2c75 100644 --- a/compiler/rustc_ty_utils/src/representability.rs +++ b/compiler/rustc_ty_utils/src/representability.rs @@ -31,7 +31,7 @@ fn representability(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Representability { } Representability::Representable } - DefKind::Field => representability_ty(tcx, tcx.type_of(def_id).subst_identity()), + DefKind::Field => representability_ty(tcx, tcx.type_of(def_id).instantiate_identity()), def_kind => bug!("unexpected {def_kind:?}"), } } @@ -68,14 +68,14 @@ representability_adt_ty(Bar<..>) is in the cycle and representability(Bar) is *not* in the cycle. */ fn representability_adt_ty<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Representability { - let ty::Adt(adt, substs) = ty.kind() else { bug!("expected adt") }; + let ty::Adt(adt, args) = ty.kind() else { bug!("expected adt") }; if let Some(def_id) = adt.did().as_local() { rtry!(tcx.representability(def_id)); } // At this point, we know that the item of the ADT type is representable; // but the type parameters may cause a cycle with an upstream type let params_in_repr = tcx.params_in_repr(adt.did()); - for (i, subst) in substs.iter().enumerate() { + for (i, subst) in args.iter().enumerate() { if let ty::GenericArgKind::Type(ty) = subst.unpack() { if params_in_repr.contains(i as u32) { rtry!(representability_ty(tcx, ty)); @@ -91,7 +91,11 @@ fn params_in_repr(tcx: TyCtxt<'_>, def_id: LocalDefId) -> BitSet<u32> { let mut params_in_repr = BitSet::new_empty(generics.params.len()); for variant in adt_def.variants() { for field in variant.fields.iter() { - params_in_repr_ty(tcx, tcx.type_of(field.did).subst_identity(), &mut params_in_repr); + params_in_repr_ty( + tcx, + tcx.type_of(field.did).instantiate_identity(), + &mut params_in_repr, + ); } } params_in_repr @@ -99,9 +103,9 @@ fn params_in_repr(tcx: TyCtxt<'_>, def_id: LocalDefId) -> BitSet<u32> { fn params_in_repr_ty<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, params_in_repr: &mut BitSet<u32>) { match *ty.kind() { - ty::Adt(adt, substs) => { + ty::Adt(adt, args) => { let inner_params_in_repr = tcx.params_in_repr(adt.did()); - for (i, subst) in substs.iter().enumerate() { + for (i, subst) in args.iter().enumerate() { if let ty::GenericArgKind::Type(ty) = subst.unpack() { if inner_params_in_repr.contains(i as u32) { params_in_repr_ty(tcx, ty, params_in_repr); diff --git a/compiler/rustc_ty_utils/src/ty.rs b/compiler/rustc_ty_utils/src/ty.rs index 43e3c99fb57..f6302113e2a 100644 --- a/compiler/rustc_ty_utils/src/ty.rs +++ b/compiler/rustc_ty_utils/src/ty.rs @@ -37,12 +37,12 @@ fn sized_constraint_for_ty<'tcx>( Some(&ty) => sized_constraint_for_ty(tcx, adtdef, ty), }, - Adt(adt, substs) => { + Adt(adt, args) => { // recursive case let adt_tys = adt.sized_constraint(tcx); debug!("sized_constraint_for_ty({:?}) intermediate = {:?}", ty, adt_tys); adt_tys - .subst_iter_copied(tcx, substs) + .arg_iter_copied(tcx, args) .flat_map(|ty| sized_constraint_for_ty(tcx, adtdef, ty)) .collect() } @@ -100,12 +100,10 @@ fn adt_sized_constraint(tcx: TyCtxt<'_>, def_id: DefId) -> &[Ty<'_>] { } let def = tcx.adt_def(def_id); - let result = tcx.mk_type_list_from_iter( - def.variants() - .iter() - .filter_map(|v| v.tail_opt()) - .flat_map(|f| sized_constraint_for_ty(tcx, def, tcx.type_of(f.did).subst_identity())), - ); + let result = + tcx.mk_type_list_from_iter(def.variants().iter().filter_map(|v| v.tail_opt()).flat_map( + |f| sized_constraint_for_ty(tcx, def, tcx.type_of(f.did).instantiate_identity()), + )); debug!("adt_sized_constraint: {:?} => {:?}", def, result); @@ -133,7 +131,7 @@ fn param_env(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ParamEnv<'_> { if tcx.def_kind(def_id) == DefKind::AssocFn && tcx.associated_item(def_id).container == ty::AssocItemContainer::TraitContainer { - let sig = tcx.fn_sig(def_id).subst_identity(); + let sig = tcx.fn_sig(def_id).instantiate_identity(); // We accounted for the binder of the fn sig, so skip the binder. sig.skip_binder().visit_with(&mut ImplTraitInTraitFinder { tcx, @@ -282,7 +280,7 @@ impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ImplTraitInTraitFinder<'_, 'tcx> { // If we're lowering to associated item, install the opaque type which is just // the `type_of` of the trait's associated item. If we're using the old lowering // strategy, then just reinterpret the associated type like an opaque :^) - let default_ty = self.tcx.type_of(shifted_alias_ty.def_id).subst(self.tcx, shifted_alias_ty.substs); + let default_ty = self.tcx.type_of(shifted_alias_ty.def_id).instantiate(self.tcx, shifted_alias_ty.args); self.predicates.push( ty::Binder::bind_with_vars( @@ -299,7 +297,7 @@ impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ImplTraitInTraitFinder<'_, 'tcx> { for bound in self .tcx .item_bounds(unshifted_alias_ty.def_id) - .subst_iter(self.tcx, unshifted_alias_ty.substs) + .arg_iter(self.tcx, unshifted_alias_ty.args) { bound.visit_with(self); } @@ -313,22 +311,6 @@ fn param_env_reveal_all_normalized(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ParamE tcx.param_env(def_id).with_reveal_all_normalized(tcx) } -fn instance_def_size_estimate<'tcx>( - tcx: TyCtxt<'tcx>, - instance_def: ty::InstanceDef<'tcx>, -) -> usize { - use ty::InstanceDef; - - match instance_def { - InstanceDef::Item(..) | InstanceDef::DropGlue(..) => { - let mir = tcx.instance_mir(instance_def); - mir.basic_blocks.iter().map(|bb| bb.statements.len() + 1).sum() - } - // Estimate the size of other compiler-generated shims to be 1. - _ => 1, - } -} - /// If `def_id` is an issue 33140 hack impl, returns its self type; otherwise, returns `None`. /// /// See [`ty::ImplOverlapKind::Issue33140`] for more details. @@ -352,8 +334,8 @@ fn issue33140_self_ty(tcx: TyCtxt<'_>, def_id: DefId) -> Option<EarlyBinder<Ty<' } // impl must be `impl Trait for dyn Marker1 + Marker2 + ...` - if trait_ref.substs.len() != 1 { - debug!("issue33140_self_ty - impl has substs!"); + if trait_ref.args.len() != 1 { + debug!("issue33140_self_ty - impl has args!"); return None; } @@ -409,7 +391,7 @@ fn unsizing_params_for_adt<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> BitSet<u32 }; let mut unsizing_params = BitSet::new_empty(num_params); - for arg in tcx.type_of(tail_field.did).subst_identity().walk() { + for arg in tcx.type_of(tail_field.did).instantiate_identity().walk() { if let Some(i) = maybe_unsizing_param_idx(arg) { unsizing_params.insert(i); } @@ -418,7 +400,7 @@ fn unsizing_params_for_adt<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> BitSet<u32 // Ensure none of the other fields mention the parameters used // in unsizing. for field in prefix_fields { - for arg in tcx.type_of(field.did).subst_identity().walk() { + for arg in tcx.type_of(field.did).instantiate_identity().walk() { if let Some(i) = maybe_unsizing_param_idx(arg) { unsizing_params.remove(i); } @@ -434,7 +416,6 @@ pub fn provide(providers: &mut Providers) { adt_sized_constraint, param_env, param_env_reveal_all_normalized, - instance_def_size_estimate, issue33140_self_ty, defaultness, unsizing_params_for_adt, diff --git a/compiler/rustc_type_ir/src/lib.rs b/compiler/rustc_type_ir/src/lib.rs index 878a6b784ed..a7cd7aa2c4f 100644 --- a/compiler/rustc_type_ir/src/lib.rs +++ b/compiler/rustc_type_ir/src/lib.rs @@ -31,6 +31,7 @@ mod macros; mod structural_impls; pub use codec::*; +pub use structural_impls::{DebugWithInfcx, InferCtxtLike, OptWithInfcx}; pub use sty::*; pub use ty_info::*; @@ -39,41 +40,41 @@ pub trait HashStableContext {} pub trait Interner: Sized { type AdtDef: Clone + Debug + Hash + Ord; - type SubstsRef: Clone + Debug + Hash + Ord; + type GenericArgsRef: Clone + DebugWithInfcx<Self> + Hash + Ord; type DefId: Clone + Debug + Hash + Ord; type Binder<T>; - type Ty: Clone + Debug + Hash + Ord; - type Const: Clone + Debug + Hash + Ord; - type Region: Clone + Debug + Hash + Ord; + type Ty: Clone + DebugWithInfcx<Self> + Hash + Ord; + type Const: Clone + DebugWithInfcx<Self> + Hash + Ord; + type Region: Clone + DebugWithInfcx<Self> + Hash + Ord; type Predicate; type TypeAndMut: Clone + Debug + Hash + Ord; type Mutability: Clone + Debug + Hash + Ord; type Movability: Clone + Debug + Hash + Ord; - type PolyFnSig: Clone + Debug + Hash + Ord; - type ListBinderExistentialPredicate: Clone + Debug + Hash + Ord; - type BinderListTy: Clone + Debug + Hash + Ord; + type PolyFnSig: Clone + DebugWithInfcx<Self> + Hash + Ord; + type ListBinderExistentialPredicate: Clone + DebugWithInfcx<Self> + Hash + Ord; + type BinderListTy: Clone + DebugWithInfcx<Self> + Hash + Ord; type ListTy: Clone + Debug + Hash + Ord + IntoIterator<Item = Self::Ty>; - type AliasTy: Clone + Debug + Hash + Ord; + type AliasTy: Clone + DebugWithInfcx<Self> + Hash + Ord; type ParamTy: Clone + Debug + Hash + Ord; type BoundTy: Clone + Debug + Hash + Ord; type PlaceholderType: Clone + Debug + Hash + Ord; + type InferTy: Clone + DebugWithInfcx<Self> + Hash + Ord; type ErrorGuaranteed: Clone + Debug + Hash + Ord; type PredicateKind: Clone + Debug + Hash + PartialEq + Eq; type AllocId: Clone + Debug + Hash + Ord; - type InferConst: Clone + Debug + Hash + Ord; - type AliasConst: Clone + Debug + Hash + Ord; + type InferConst: Clone + DebugWithInfcx<Self> + Hash + Ord; + type AliasConst: Clone + DebugWithInfcx<Self> + Hash + Ord; type PlaceholderConst: Clone + Debug + Hash + Ord; type ParamConst: Clone + Debug + Hash + Ord; type BoundConst: Clone + Debug + Hash + Ord; - type InferTy: Clone + Debug + Hash + Ord; type ValueConst: Clone + Debug + Hash + Ord; - type ExprConst: Clone + Debug + Hash + Ord; + type ExprConst: Clone + DebugWithInfcx<Self> + Hash + Ord; type EarlyBoundRegion: Clone + Debug + Hash + Ord; type BoundRegion: Clone + Debug + Hash + Ord; type FreeRegion: Clone + Debug + Hash + Ord; - type RegionVid: Clone + Debug + Hash + Ord; + type RegionVid: Clone + DebugWithInfcx<Self> + Hash + Ord; type PlaceholderRegion: Clone + Debug + Hash + Ord; fn ty_and_mut_to_parts(ty_and_mut: Self::TypeAndMut) -> (Self::Ty, Self::Mutability); @@ -775,20 +776,6 @@ impl fmt::Debug for FloatVid { } } -impl fmt::Debug for InferTy { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - use InferTy::*; - match *self { - TyVar(ref v) => v.fmt(f), - IntVar(ref v) => v.fmt(f), - FloatVar(ref v) => v.fmt(f), - FreshTy(v) => write!(f, "FreshTy({v:?})"), - FreshIntTy(v) => write!(f, "FreshIntTy({v:?})"), - FreshFloatTy(v) => write!(f, "FreshFloatTy({v:?})"), - } - } -} - impl fmt::Debug for Variance { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(match *self { diff --git a/compiler/rustc_type_ir/src/structural_impls.rs b/compiler/rustc_type_ir/src/structural_impls.rs index 1e42175f6e3..1a2d6d64eb0 100644 --- a/compiler/rustc_type_ir/src/structural_impls.rs +++ b/compiler/rustc_type_ir/src/structural_impls.rs @@ -4,12 +4,13 @@ use crate::fold::{FallibleTypeFolder, TypeFoldable}; use crate::visit::{TypeVisitable, TypeVisitor}; -use crate::{ConstKind, FloatTy, IntTy, Interner, UintTy}; +use crate::{ConstKind, FloatTy, InferTy, IntTy, Interner, UintTy, UniverseIndex}; use rustc_data_structures::functor::IdFunctor; use rustc_data_structures::sync::Lrc; use rustc_index::{Idx, IndexVec}; use core::fmt; +use std::marker::PhantomData; use std::ops::ControlFlow; /////////////////////////////////////////////////////////////////////////// @@ -165,6 +166,116 @@ impl<I: Interner, T: TypeVisitable<I>, Ix: Idx> TypeVisitable<I> for IndexVec<Ix } } +/////////////////////////////////////////////////// +// Debug impls + +pub trait InferCtxtLike<I: Interner> { + fn universe_of_ty(&self, ty: I::InferTy) -> Option<UniverseIndex>; + fn universe_of_lt(&self, lt: I::RegionVid) -> Option<UniverseIndex>; + fn universe_of_ct(&self, ct: I::InferConst) -> Option<UniverseIndex>; +} + +impl<I: Interner> InferCtxtLike<I> for core::convert::Infallible { + fn universe_of_ty(&self, _ty: <I as Interner>::InferTy) -> Option<UniverseIndex> { + match *self {} + } + fn universe_of_ct(&self, _ct: <I as Interner>::InferConst) -> Option<UniverseIndex> { + match *self {} + } + fn universe_of_lt(&self, _lt: <I as Interner>::RegionVid) -> Option<UniverseIndex> { + match *self {} + } +} + +pub trait DebugWithInfcx<I: Interner>: fmt::Debug { + fn fmt<InfCtx: InferCtxtLike<I>>( + this: OptWithInfcx<'_, I, InfCtx, &Self>, + f: &mut fmt::Formatter<'_>, + ) -> fmt::Result; +} + +impl<I: Interner, T: DebugWithInfcx<I> + ?Sized> DebugWithInfcx<I> for &'_ T { + fn fmt<InfCtx: InferCtxtLike<I>>( + this: OptWithInfcx<'_, I, InfCtx, &Self>, + f: &mut fmt::Formatter<'_>, + ) -> fmt::Result { + <T as DebugWithInfcx<I>>::fmt(this.map(|&data| data), f) + } +} +impl<I: Interner, T: DebugWithInfcx<I>> DebugWithInfcx<I> for [T] { + fn fmt<InfCtx: InferCtxtLike<I>>( + this: OptWithInfcx<'_, I, InfCtx, &Self>, + f: &mut fmt::Formatter<'_>, + ) -> fmt::Result { + match f.alternate() { + true => { + write!(f, "[\n")?; + for element in this.data.iter() { + write!(f, "{:?},\n", &this.wrap(element))?; + } + write!(f, "]") + } + false => { + write!(f, "[")?; + if this.data.len() > 0 { + for element in &this.data[..(this.data.len() - 1)] { + write!(f, "{:?}, ", &this.wrap(element))?; + } + if let Some(element) = this.data.last() { + write!(f, "{:?}", &this.wrap(element))?; + } + } + write!(f, "]") + } + } + } +} + +pub struct OptWithInfcx<'a, I: Interner, InfCtx: InferCtxtLike<I>, T> { + pub data: T, + pub infcx: Option<&'a InfCtx>, + _interner: PhantomData<I>, +} + +impl<I: Interner, InfCtx: InferCtxtLike<I>, T: Copy> Copy for OptWithInfcx<'_, I, InfCtx, T> {} +impl<I: Interner, InfCtx: InferCtxtLike<I>, T: Clone> Clone for OptWithInfcx<'_, I, InfCtx, T> { + fn clone(&self) -> Self { + Self { data: self.data.clone(), infcx: self.infcx, _interner: self._interner } + } +} + +impl<'a, I: Interner, T> OptWithInfcx<'a, I, core::convert::Infallible, T> { + pub fn new_no_ctx(data: T) -> Self { + Self { data, infcx: None, _interner: PhantomData } + } +} + +impl<'a, I: Interner, InfCtx: InferCtxtLike<I>, T> OptWithInfcx<'a, I, InfCtx, T> { + pub fn new(data: T, infcx: &'a InfCtx) -> Self { + Self { data, infcx: Some(infcx), _interner: PhantomData } + } + + pub fn wrap<U>(self, u: U) -> OptWithInfcx<'a, I, InfCtx, U> { + OptWithInfcx { data: u, infcx: self.infcx, _interner: PhantomData } + } + + pub fn map<U>(self, f: impl FnOnce(T) -> U) -> OptWithInfcx<'a, I, InfCtx, U> { + OptWithInfcx { data: f(self.data), infcx: self.infcx, _interner: PhantomData } + } + + pub fn as_ref(&self) -> OptWithInfcx<'a, I, InfCtx, &T> { + OptWithInfcx { data: &self.data, infcx: self.infcx, _interner: PhantomData } + } +} + +impl<I: Interner, InfCtx: InferCtxtLike<I>, T: DebugWithInfcx<I>> fmt::Debug + for OptWithInfcx<'_, I, InfCtx, T> +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + DebugWithInfcx::fmt(self.as_ref(), f) + } +} + impl fmt::Debug for IntTy { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.name_str()) @@ -183,20 +294,60 @@ impl fmt::Debug for FloatTy { } } +impl fmt::Debug for InferTy { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + use InferTy::*; + match *self { + TyVar(ref v) => v.fmt(f), + IntVar(ref v) => v.fmt(f), + FloatVar(ref v) => v.fmt(f), + FreshTy(v) => write!(f, "FreshTy({v:?})"), + FreshIntTy(v) => write!(f, "FreshIntTy({v:?})"), + FreshFloatTy(v) => write!(f, "FreshFloatTy({v:?})"), + } + } +} +impl<I: Interner<InferTy = InferTy>> DebugWithInfcx<I> for InferTy { + fn fmt<InfCtx: InferCtxtLike<I>>( + this: OptWithInfcx<'_, I, InfCtx, &Self>, + f: &mut fmt::Formatter<'_>, + ) -> fmt::Result { + use InferTy::*; + match this.infcx.and_then(|infcx| infcx.universe_of_ty(*this.data)) { + None => write!(f, "{:?}", this.data), + Some(universe) => match *this.data { + TyVar(ty_vid) => write!(f, "?{}_{}t", ty_vid.index(), universe.index()), + IntVar(_) | FloatVar(_) | FreshTy(_) | FreshIntTy(_) | FreshFloatTy(_) => { + unreachable!() + } + }, + } + } +} + impl<I: Interner> fmt::Debug for ConstKind<I> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + OptWithInfcx::new_no_ctx(self).fmt(f) + } +} +impl<I: Interner> DebugWithInfcx<I> for ConstKind<I> { + fn fmt<InfCtx: InferCtxtLike<I>>( + this: OptWithInfcx<'_, I, InfCtx, &Self>, + f: &mut core::fmt::Formatter<'_>, + ) -> core::fmt::Result { use ConstKind::*; - match self { + + match this.data { Param(param) => write!(f, "{param:?}"), - Infer(var) => write!(f, "{var:?}"), + Infer(var) => write!(f, "{:?}", &this.wrap(var)), Bound(debruijn, var) => crate::debug_bound_var(f, *debruijn, var.clone()), Placeholder(placeholder) => write!(f, "{placeholder:?}"), Unevaluated(uv) => { - write!(f, "{uv:?}") + write!(f, "{:?}", &this.wrap(uv)) } Value(valtree) => write!(f, "{valtree:?}"), Error(_) => write!(f, "{{const error}}"), - Expr(expr) => write!(f, "{expr:?}"), + Expr(expr) => write!(f, "{:?}", &this.wrap(expr)), } } } diff --git a/compiler/rustc_type_ir/src/sty.rs b/compiler/rustc_type_ir/src/sty.rs index b696f9b9b59..b134845dab0 100644 --- a/compiler/rustc_type_ir/src/sty.rs +++ b/compiler/rustc_type_ir/src/sty.rs @@ -3,7 +3,6 @@ use std::cmp::Ordering; use std::{fmt, hash}; -use crate::DebruijnIndex; use crate::FloatTy; use crate::HashStableContext; use crate::IntTy; @@ -11,6 +10,7 @@ use crate::Interner; use crate::TyDecoder; use crate::TyEncoder; use crate::UintTy; +use crate::{DebruijnIndex, DebugWithInfcx, InferCtxtLike, OptWithInfcx}; use self::RegionKind::*; use self::TyKind::*; @@ -74,11 +74,11 @@ pub enum TyKind<I: Interner> { /// Algebraic data types (ADT). For example: structures, enumerations and unions. /// /// For example, the type `List<i32>` would be represented using the `AdtDef` - /// for `struct List<T>` and the substs `[i32]`. + /// for `struct List<T>` and the args `[i32]`. /// /// Note that generic parameters in fields only get lazily substituted - /// by using something like `adt_def.all_fields().map(|field| field.ty(tcx, substs))`. - Adt(I::AdtDef, I::SubstsRef), + /// by using something like `adt_def.all_fields().map(|field| field.ty(tcx, args))`. + Adt(I::AdtDef, I::GenericArgsRef), /// An unsized FFI type that is opaque to Rust. Written as `extern type T`. Foreign(I::DefId), @@ -110,7 +110,7 @@ pub enum TyKind<I: Interner> { /// fn foo() -> i32 { 1 } /// let bar = foo; // bar: fn() -> i32 {foo} /// ``` - FnDef(I::DefId, I::SubstsRef), + FnDef(I::DefId, I::GenericArgsRef), /// A pointer to a function. Written as `fn() -> i32`. /// @@ -130,20 +130,20 @@ pub enum TyKind<I: Interner> { /// The anonymous type of a closure. Used to represent the type of `|a| a`. /// - /// Closure substs contain both the - potentially substituted - generic parameters + /// Closure args contain both the - potentially substituted - generic parameters /// of its parent and some synthetic parameters. See the documentation for - /// `ClosureSubsts` for more details. - Closure(I::DefId, I::SubstsRef), + /// `ClosureArgs` for more details. + Closure(I::DefId, I::GenericArgsRef), /// The anonymous type of a generator. Used to represent the type of /// `|a| yield a`. /// - /// For more info about generator substs, visit the documentation for - /// `GeneratorSubsts`. - Generator(I::DefId, I::SubstsRef, I::Movability), + /// For more info about generator args, visit the documentation for + /// `GeneratorArgs`. + Generator(I::DefId, I::GenericArgsRef, I::Movability), /// A type representing the types stored inside a generator. - /// This should only appear as part of the `GeneratorSubsts`. + /// This should only appear as part of the `GeneratorArgs`. /// /// Note that the captured variables for generators are stored separately /// using a tuple in the same way as for closures. @@ -168,7 +168,7 @@ pub enum TyKind<I: Interner> { GeneratorWitness(I::BinderListTy), /// A type representing the types stored inside a generator. - /// This should only appear as part of the `GeneratorSubsts`. + /// This should only appear as part of the `GeneratorArgs`. /// /// Unlike upvars, the witness can reference lifetimes from /// inside of the generator itself. To deal with them in @@ -176,7 +176,7 @@ pub enum TyKind<I: Interner> { /// lifetimes bound by the witness itself. /// /// This variant is only using when `drop_tracking_mir` is set. - /// This contains the `DefId` and the `SubstsRef` of the generator. + /// This contains the `DefId` and the `GenericArgsRef` of the generator. /// The actual witness types are computed on MIR by the `mir_generator_witnesses` query. /// /// Looking at the following example, the witness for this generator @@ -191,7 +191,7 @@ pub enum TyKind<I: Interner> { /// } /// # ; /// ``` - GeneratorWitnessMIR(I::DefId, I::SubstsRef), + GeneratorWitnessMIR(I::DefId, I::GenericArgsRef), /// The never type `!`. Never, @@ -503,42 +503,48 @@ impl<I: Interner> hash::Hash for TyKind<I> { } } -// This is manually implemented because a derive would require `I: Debug` -impl<I: Interner> fmt::Debug for TyKind<I> { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { +impl<I: Interner> DebugWithInfcx<I> for TyKind<I> { + fn fmt<InfCtx: InferCtxtLike<I>>( + this: OptWithInfcx<'_, I, InfCtx, &Self>, + f: &mut core::fmt::Formatter<'_>, + ) -> fmt::Result { + match this.data { Bool => write!(f, "bool"), Char => write!(f, "char"), Int(i) => write!(f, "{i:?}"), Uint(u) => write!(f, "{u:?}"), Float(float) => write!(f, "{float:?}"), - Adt(d, s) => f.debug_tuple_field2_finish("Adt", d, s), + Adt(d, s) => f.debug_tuple_field2_finish("Adt", d, &this.wrap(s)), Foreign(d) => f.debug_tuple_field1_finish("Foreign", d), Str => write!(f, "str"), - Array(t, c) => write!(f, "[{t:?}; {c:?}]"), - Slice(t) => write!(f, "[{t:?}]"), + Array(t, c) => write!(f, "[{:?}; {:?}]", &this.wrap(t), &this.wrap(c)), + Slice(t) => write!(f, "[{:?}]", &this.wrap(t)), RawPtr(p) => { let (ty, mutbl) = I::ty_and_mut_to_parts(p.clone()); match I::mutability_is_mut(mutbl) { true => write!(f, "*mut "), false => write!(f, "*const "), }?; - write!(f, "{ty:?}") + write!(f, "{:?}", &this.wrap(ty)) } Ref(r, t, m) => match I::mutability_is_mut(m.clone()) { - true => write!(f, "&{r:?} mut {t:?}"), - false => write!(f, "&{r:?} {t:?}"), + true => write!(f, "&{:?} mut {:?}", &this.wrap(r), &this.wrap(t)), + false => write!(f, "&{:?} {:?}", &this.wrap(r), &this.wrap(t)), }, - FnDef(d, s) => f.debug_tuple_field2_finish("FnDef", d, s), - FnPtr(s) => write!(f, "{s:?}"), + FnDef(d, s) => f.debug_tuple_field2_finish("FnDef", d, &this.wrap(s)), + FnPtr(s) => write!(f, "{:?}", &this.wrap(s)), Dynamic(p, r, repr) => match repr { - DynKind::Dyn => write!(f, "dyn {p:?} + {r:?}"), - DynKind::DynStar => write!(f, "dyn* {p:?} + {r:?}"), + DynKind::Dyn => write!(f, "dyn {:?} + {:?}", &this.wrap(p), &this.wrap(r)), + DynKind::DynStar => { + write!(f, "dyn* {:?} + {:?}", &this.wrap(p), &this.wrap(r)) + } }, - Closure(d, s) => f.debug_tuple_field2_finish("Closure", d, s), - Generator(d, s, m) => f.debug_tuple_field3_finish("Generator", d, s, m), - GeneratorWitness(g) => f.debug_tuple_field1_finish("GeneratorWitness", g), - GeneratorWitnessMIR(d, s) => f.debug_tuple_field2_finish("GeneratorWitnessMIR", d, s), + Closure(d, s) => f.debug_tuple_field2_finish("Closure", d, &this.wrap(s)), + Generator(d, s, m) => f.debug_tuple_field3_finish("Generator", d, &this.wrap(s), m), + GeneratorWitness(g) => f.debug_tuple_field1_finish("GeneratorWitness", &this.wrap(g)), + GeneratorWitnessMIR(d, s) => { + f.debug_tuple_field2_finish("GeneratorWitnessMIR", d, &this.wrap(s)) + } Never => write!(f, "!"), Tuple(t) => { let mut iter = t.clone().into_iter(); @@ -547,35 +553,41 @@ impl<I: Interner> fmt::Debug for TyKind<I> { match iter.next() { None => return write!(f, ")"), - Some(ty) => write!(f, "{ty:?}")?, + Some(ty) => write!(f, "{:?}", &this.wrap(ty))?, }; match iter.next() { None => return write!(f, ",)"), - Some(ty) => write!(f, "{ty:?})")?, + Some(ty) => write!(f, "{:?})", &this.wrap(ty))?, } for ty in iter { - write!(f, ", {ty:?}")?; + write!(f, ", {:?}", &this.wrap(ty))?; } write!(f, ")") } - Alias(i, a) => f.debug_tuple_field2_finish("Alias", i, a), + Alias(i, a) => f.debug_tuple_field2_finish("Alias", i, &this.wrap(a)), Param(p) => write!(f, "{p:?}"), Bound(d, b) => crate::debug_bound_var(f, *d, b), Placeholder(p) => write!(f, "{p:?}"), - Infer(t) => write!(f, "{t:?}"), + Infer(t) => write!(f, "{:?}", this.wrap(t)), TyKind::Error(_) => write!(f, "{{type error}}"), } } } +// This is manually implemented because a derive would require `I: Debug` +impl<I: Interner> fmt::Debug for TyKind<I> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + OptWithInfcx::new_no_ctx(self).fmt(f) + } +} // This is manually implemented because a derive would require `I: Encodable` impl<I: Interner, E: TyEncoder> Encodable<E> for TyKind<I> where I::ErrorGuaranteed: Encodable<E>, I::AdtDef: Encodable<E>, - I::SubstsRef: Encodable<E>, + I::GenericArgsRef: Encodable<E>, I::DefId: Encodable<E>, I::Ty: Encodable<E>, I::Const: Encodable<E>, @@ -609,9 +621,9 @@ where Float(f) => e.emit_enum_variant(disc, |e| { f.encode(e); }), - Adt(adt, substs) => e.emit_enum_variant(disc, |e| { + Adt(adt, args) => e.emit_enum_variant(disc, |e| { adt.encode(e); - substs.encode(e); + args.encode(e); }), Foreign(def_id) => e.emit_enum_variant(disc, |e| { def_id.encode(e); @@ -632,9 +644,9 @@ where t.encode(e); m.encode(e); }), - FnDef(def_id, substs) => e.emit_enum_variant(disc, |e| { + FnDef(def_id, args) => e.emit_enum_variant(disc, |e| { def_id.encode(e); - substs.encode(e); + args.encode(e); }), FnPtr(polyfnsig) => e.emit_enum_variant(disc, |e| { polyfnsig.encode(e); @@ -644,25 +656,25 @@ where r.encode(e); repr.encode(e); }), - Closure(def_id, substs) => e.emit_enum_variant(disc, |e| { + Closure(def_id, args) => e.emit_enum_variant(disc, |e| { def_id.encode(e); - substs.encode(e); + args.encode(e); }), - Generator(def_id, substs, m) => e.emit_enum_variant(disc, |e| { + Generator(def_id, args, m) => e.emit_enum_variant(disc, |e| { def_id.encode(e); - substs.encode(e); + args.encode(e); m.encode(e); }), GeneratorWitness(b) => e.emit_enum_variant(disc, |e| { b.encode(e); }), - GeneratorWitnessMIR(def_id, substs) => e.emit_enum_variant(disc, |e| { + GeneratorWitnessMIR(def_id, args) => e.emit_enum_variant(disc, |e| { def_id.encode(e); - substs.encode(e); + args.encode(e); }), Never => e.emit_enum_variant(disc, |_| {}), - Tuple(substs) => e.emit_enum_variant(disc, |e| { - substs.encode(e); + Tuple(args) => e.emit_enum_variant(disc, |e| { + args.encode(e); }), Alias(k, p) => e.emit_enum_variant(disc, |e| { k.encode(e); @@ -693,7 +705,7 @@ impl<I: Interner, D: TyDecoder<I = I>> Decodable<D> for TyKind<I> where I::ErrorGuaranteed: Decodable<D>, I::AdtDef: Decodable<D>, - I::SubstsRef: Decodable<D>, + I::GenericArgsRef: Decodable<D>, I::DefId: Decodable<D>, I::Ty: Decodable<D>, I::Const: Decodable<D>, @@ -760,7 +772,7 @@ impl<CTX: HashStableContext, I: Interner> HashStable<CTX> for TyKind<I> where I::AdtDef: HashStable<CTX>, I::DefId: HashStable<CTX>, - I::SubstsRef: HashStable<CTX>, + I::GenericArgsRef: HashStable<CTX>, I::Ty: HashStable<CTX>, I::Const: HashStable<CTX>, I::TypeAndMut: HashStable<CTX>, @@ -797,9 +809,9 @@ where Float(f) => { f.hash_stable(__hcx, __hasher); } - Adt(adt, substs) => { + Adt(adt, args) => { adt.hash_stable(__hcx, __hasher); - substs.hash_stable(__hcx, __hasher); + args.hash_stable(__hcx, __hasher); } Foreign(def_id) => { def_id.hash_stable(__hcx, __hasher); @@ -820,9 +832,9 @@ where t.hash_stable(__hcx, __hasher); m.hash_stable(__hcx, __hasher); } - FnDef(def_id, substs) => { + FnDef(def_id, args) => { def_id.hash_stable(__hcx, __hasher); - substs.hash_stable(__hcx, __hasher); + args.hash_stable(__hcx, __hasher); } FnPtr(polyfnsig) => { polyfnsig.hash_stable(__hcx, __hasher); @@ -832,25 +844,25 @@ where r.hash_stable(__hcx, __hasher); repr.hash_stable(__hcx, __hasher); } - Closure(def_id, substs) => { + Closure(def_id, args) => { def_id.hash_stable(__hcx, __hasher); - substs.hash_stable(__hcx, __hasher); + args.hash_stable(__hcx, __hasher); } - Generator(def_id, substs, m) => { + Generator(def_id, args, m) => { def_id.hash_stable(__hcx, __hasher); - substs.hash_stable(__hcx, __hasher); + args.hash_stable(__hcx, __hasher); m.hash_stable(__hcx, __hasher); } GeneratorWitness(b) => { b.hash_stable(__hcx, __hasher); } - GeneratorWitnessMIR(def_id, substs) => { + GeneratorWitnessMIR(def_id, args) => { def_id.hash_stable(__hcx, __hasher); - substs.hash_stable(__hcx, __hasher); + args.hash_stable(__hcx, __hasher); } Never => {} - Tuple(substs) => { - substs.hash_stable(__hcx, __hasher); + Tuple(args) => { + args.hash_stable(__hcx, __hasher); } Alias(k, p) => { k.hash_stable(__hcx, __hasher); @@ -1155,7 +1167,7 @@ impl<I: Interner> Clone for ConstKind<I> { /// These are regions that are stored behind a binder and must be substituted /// with some concrete region before being used. There are two kind of /// bound regions: early-bound, which are bound in an item's `Generics`, -/// and are substituted by an `InternalSubsts`, and late-bound, which are part of +/// and are substituted by an `GenericArgs`, and late-bound, which are part of /// higher-ranked types (e.g., `for<'a> fn(&'a ())`), and are substituted by /// the likes of `liberate_late_bound_regions`. The distinction exists /// because higher-ranked lifetimes aren't supported in all places. See [1][2]. @@ -1356,21 +1368,23 @@ impl<I: Interner> hash::Hash for RegionKind<I> { } } -// This is manually implemented because a derive would require `I: Debug` -impl<I: Interner> fmt::Debug for RegionKind<I> { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { +impl<I: Interner> DebugWithInfcx<I> for RegionKind<I> { + fn fmt<InfCtx: InferCtxtLike<I>>( + this: OptWithInfcx<'_, I, InfCtx, &Self>, + f: &mut core::fmt::Formatter<'_>, + ) -> core::fmt::Result { + match this.data { ReEarlyBound(data) => write!(f, "ReEarlyBound({data:?})"), ReLateBound(binder_id, bound_region) => { write!(f, "ReLateBound({binder_id:?}, {bound_region:?})") } - ReFree(fr) => fr.fmt(f), + ReFree(fr) => write!(f, "{fr:?}"), ReStatic => f.write_str("ReStatic"), - ReVar(vid) => vid.fmt(f), + ReVar(vid) => write!(f, "{:?}", &this.wrap(vid)), RePlaceholder(placeholder) => write!(f, "RePlaceholder({placeholder:?})"), @@ -1380,6 +1394,11 @@ impl<I: Interner> fmt::Debug for RegionKind<I> { } } } +impl<I: Interner> fmt::Debug for RegionKind<I> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + OptWithInfcx::new_no_ctx(self).fmt(f) + } +} // This is manually implemented because a derive would require `I: Encodable` impl<I: Interner, E: TyEncoder> Encodable<E> for RegionKind<I> diff --git a/library/alloc/src/alloc.rs b/library/alloc/src/alloc.rs index e24a0fe51bd..c8751ba4911 100644 --- a/library/alloc/src/alloc.rs +++ b/library/alloc/src/alloc.rs @@ -4,11 +4,7 @@ #[cfg(not(test))] use core::intrinsics; -#[cfg(all(bootstrap, not(test)))] -use core::intrinsics::{min_align_of_val, size_of_val}; -#[cfg(all(bootstrap, not(test)))] -use core::ptr::Unique; #[cfg(not(test))] use core::ptr::{self, NonNull}; @@ -337,23 +333,6 @@ unsafe fn exchange_malloc(size: usize, align: usize) -> *mut u8 { } } -#[cfg(all(bootstrap, not(test)))] -#[lang = "box_free"] -#[inline] -// This signature has to be the same as `Box`, otherwise an ICE will happen. -// When an additional parameter to `Box` is added (like `A: Allocator`), this has to be added here as -// well. -// For example if `Box` is changed to `struct Box<T: ?Sized, A: Allocator>(Unique<T>, A)`, -// this function has to be changed to `fn box_free<T: ?Sized, A: Allocator>(Unique<T>, A)` as well. -unsafe fn box_free<T: ?Sized, A: Allocator>(ptr: Unique<T>, alloc: A) { - unsafe { - let size = size_of_val(ptr.as_ref()); - let align = min_align_of_val(ptr.as_ref()); - let layout = Layout::from_size_align_unchecked(size, align); - alloc.deallocate(From::from(ptr.cast()), layout) - } -} - // # Allocation error handler #[cfg(not(no_global_oom_handling))] diff --git a/library/alloc/src/boxed.rs b/library/alloc/src/boxed.rs index 8ef2bac9282..8697a77db3b 100644 --- a/library/alloc/src/boxed.rs +++ b/library/alloc/src/boxed.rs @@ -157,12 +157,12 @@ use core::hash::{Hash, Hasher}; use core::iter::FusedIterator; use core::marker::Tuple; use core::marker::Unsize; -use core::mem; +use core::mem::{self, SizedTypeProperties}; use core::ops::{ CoerceUnsized, Deref, DerefMut, DispatchFromDyn, Generator, GeneratorState, Receiver, }; use core::pin::Pin; -use core::ptr::{self, Unique}; +use core::ptr::{self, NonNull, Unique}; use core::task::{Context, Poll}; #[cfg(not(no_global_oom_handling))] @@ -479,8 +479,12 @@ impl<T, A: Allocator> Box<T, A> { where A: Allocator, { - let layout = Layout::new::<mem::MaybeUninit<T>>(); - let ptr = alloc.allocate(layout)?.cast(); + let ptr = if T::IS_ZST { + NonNull::dangling() + } else { + let layout = Layout::new::<mem::MaybeUninit<T>>(); + alloc.allocate(layout)?.cast() + }; unsafe { Ok(Box::from_raw_in(ptr.as_ptr(), alloc)) } } @@ -549,8 +553,12 @@ impl<T, A: Allocator> Box<T, A> { where A: Allocator, { - let layout = Layout::new::<mem::MaybeUninit<T>>(); - let ptr = alloc.allocate_zeroed(layout)?.cast(); + let ptr = if T::IS_ZST { + NonNull::dangling() + } else { + let layout = Layout::new::<mem::MaybeUninit<T>>(); + alloc.allocate_zeroed(layout)?.cast() + }; unsafe { Ok(Box::from_raw_in(ptr.as_ptr(), alloc)) } } @@ -675,14 +683,16 @@ impl<T> Box<[T]> { #[unstable(feature = "allocator_api", issue = "32838")] #[inline] pub fn try_new_uninit_slice(len: usize) -> Result<Box<[mem::MaybeUninit<T>]>, AllocError> { - unsafe { + let ptr = if T::IS_ZST || len == 0 { + NonNull::dangling() + } else { let layout = match Layout::array::<mem::MaybeUninit<T>>(len) { Ok(l) => l, Err(_) => return Err(AllocError), }; - let ptr = Global.allocate(layout)?; - Ok(RawVec::from_raw_parts_in(ptr.as_mut_ptr() as *mut _, len, Global).into_box(len)) - } + Global.allocate(layout)?.cast() + }; + unsafe { Ok(RawVec::from_raw_parts_in(ptr.as_ptr(), len, Global).into_box(len)) } } /// Constructs a new boxed slice with uninitialized contents, with the memory @@ -707,14 +717,16 @@ impl<T> Box<[T]> { #[unstable(feature = "allocator_api", issue = "32838")] #[inline] pub fn try_new_zeroed_slice(len: usize) -> Result<Box<[mem::MaybeUninit<T>]>, AllocError> { - unsafe { + let ptr = if T::IS_ZST || len == 0 { + NonNull::dangling() + } else { let layout = match Layout::array::<mem::MaybeUninit<T>>(len) { Ok(l) => l, Err(_) => return Err(AllocError), }; - let ptr = Global.allocate_zeroed(layout)?; - Ok(RawVec::from_raw_parts_in(ptr.as_mut_ptr() as *mut _, len, Global).into_box(len)) - } + Global.allocate_zeroed(layout)?.cast() + }; + unsafe { Ok(RawVec::from_raw_parts_in(ptr.as_ptr(), len, Global).into_box(len)) } } } @@ -1219,7 +1231,9 @@ unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for Box<T, A> { unsafe { let layout = Layout::for_value_raw(ptr.as_ptr()); - self.1.deallocate(From::from(ptr.cast()), layout) + if layout.size() != 0 { + self.1.deallocate(From::from(ptr.cast()), layout); + } } } } diff --git a/library/alloc/src/collections/vec_deque/mod.rs b/library/alloc/src/collections/vec_deque/mod.rs index 896da37f94c..5965ec2affa 100644 --- a/library/alloc/src/collections/vec_deque/mod.rs +++ b/library/alloc/src/collections/vec_deque/mod.rs @@ -2283,21 +2283,21 @@ impl<T, A: Allocator> VecDeque<T, A> { unsafe { slice::from_raw_parts_mut(ptr.add(self.head), self.len) } } - /// Rotates the double-ended queue `mid` places to the left. + /// Rotates the double-ended queue `n` places to the left. /// /// Equivalently, - /// - Rotates item `mid` into the first position. - /// - Pops the first `mid` items and pushes them to the end. - /// - Rotates `len() - mid` places to the right. + /// - Rotates item `n` into the first position. + /// - Pops the first `n` items and pushes them to the end. + /// - Rotates `len() - n` places to the right. /// /// # Panics /// - /// If `mid` is greater than `len()`. Note that `mid == len()` + /// If `n` is greater than `len()`. Note that `n == len()` /// does _not_ panic and is a no-op rotation. /// /// # Complexity /// - /// Takes `*O*(min(mid, len() - mid))` time and no extra space. + /// Takes `*O*(min(n, len() - n))` time and no extra space. /// /// # Examples /// @@ -2316,31 +2316,31 @@ impl<T, A: Allocator> VecDeque<T, A> { /// assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); /// ``` #[stable(feature = "vecdeque_rotate", since = "1.36.0")] - pub fn rotate_left(&mut self, mid: usize) { - assert!(mid <= self.len()); - let k = self.len - mid; - if mid <= k { - unsafe { self.rotate_left_inner(mid) } + pub fn rotate_left(&mut self, n: usize) { + assert!(n <= self.len()); + let k = self.len - n; + if n <= k { + unsafe { self.rotate_left_inner(n) } } else { unsafe { self.rotate_right_inner(k) } } } - /// Rotates the double-ended queue `k` places to the right. + /// Rotates the double-ended queue `n` places to the right. /// /// Equivalently, - /// - Rotates the first item into position `k`. - /// - Pops the last `k` items and pushes them to the front. - /// - Rotates `len() - k` places to the left. + /// - Rotates the first item into position `n`. + /// - Pops the last `n` items and pushes them to the front. + /// - Rotates `len() - n` places to the left. /// /// # Panics /// - /// If `k` is greater than `len()`. Note that `k == len()` + /// If `n` is greater than `len()`. Note that `n == len()` /// does _not_ panic and is a no-op rotation. /// /// # Complexity /// - /// Takes `*O*(min(k, len() - k))` time and no extra space. + /// Takes `*O*(min(n, len() - n))` time and no extra space. /// /// # Examples /// @@ -2359,13 +2359,13 @@ impl<T, A: Allocator> VecDeque<T, A> { /// assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); /// ``` #[stable(feature = "vecdeque_rotate", since = "1.36.0")] - pub fn rotate_right(&mut self, k: usize) { - assert!(k <= self.len()); - let mid = self.len - k; - if k <= mid { - unsafe { self.rotate_right_inner(k) } + pub fn rotate_right(&mut self, n: usize) { + assert!(n <= self.len()); + let k = self.len - n; + if n <= k { + unsafe { self.rotate_right_inner(n) } } else { - unsafe { self.rotate_left_inner(mid) } + unsafe { self.rotate_left_inner(k) } } } diff --git a/library/alloc/src/collections/vec_deque/tests.rs b/library/alloc/src/collections/vec_deque/tests.rs index 205a8ff3c19..b7fdebfa60b 100644 --- a/library/alloc/src/collections/vec_deque/tests.rs +++ b/library/alloc/src/collections/vec_deque/tests.rs @@ -351,14 +351,14 @@ fn test_rotate_left_right() { } #[test] -#[should_panic = "assertion failed: mid <= self.len()"] +#[should_panic = "assertion failed: n <= self.len()"] fn test_rotate_left_panic() { let mut tester: VecDeque<_> = (1..=10).collect(); tester.rotate_left(tester.len() + 1); } #[test] -#[should_panic = "assertion failed: k <= self.len()"] +#[should_panic = "assertion failed: n <= self.len()"] fn test_rotate_right_panic() { let mut tester: VecDeque<_> = (1..=10).collect(); tester.rotate_right(tester.len() + 1); diff --git a/library/alloc/src/raw_vec.rs b/library/alloc/src/raw_vec.rs index dfd30d99cf0..01b03de6acb 100644 --- a/library/alloc/src/raw_vec.rs +++ b/library/alloc/src/raw_vec.rs @@ -432,16 +432,26 @@ impl<T, A: Allocator> RawVec<T, A> { let (ptr, layout) = if let Some(mem) = self.current_memory() { mem } else { return Ok(()) }; // See current_memory() why this assert is here let _: () = const { assert!(mem::size_of::<T>() % mem::align_of::<T>() == 0) }; - let ptr = unsafe { - // `Layout::array` cannot overflow here because it would have - // overflowed earlier when capacity was larger. - let new_size = mem::size_of::<T>().unchecked_mul(cap); - let new_layout = Layout::from_size_align_unchecked(new_size, layout.align()); - self.alloc - .shrink(ptr, layout, new_layout) - .map_err(|_| AllocError { layout: new_layout, non_exhaustive: () })? - }; - self.set_ptr_and_cap(ptr, cap); + + // If shrinking to 0, deallocate the buffer. We don't reach this point + // for the T::IS_ZST case since current_memory() will have returned + // None. + if cap == 0 { + unsafe { self.alloc.deallocate(ptr, layout) }; + self.ptr = Unique::dangling(); + self.cap = 0; + } else { + let ptr = unsafe { + // `Layout::array` cannot overflow here because it would have + // overflowed earlier when capacity was larger. + let new_size = mem::size_of::<T>().unchecked_mul(cap); + let new_layout = Layout::from_size_align_unchecked(new_size, layout.align()); + self.alloc + .shrink(ptr, layout, new_layout) + .map_err(|_| AllocError { layout: new_layout, non_exhaustive: () })? + }; + self.set_ptr_and_cap(ptr, cap); + } Ok(()) } } diff --git a/library/alloc/src/string.rs b/library/alloc/src/string.rs index 1c6815fa941..ad7b77f5497 100644 --- a/library/alloc/src/string.rs +++ b/library/alloc/src/string.rs @@ -1873,7 +1873,7 @@ impl String { /// let static_ref: &'static mut str = x.leak(); /// assert_eq!(static_ref, "bucket"); /// ``` - #[stable(feature = "string_leak", since = "CURRENT_RUSTC_VERSION")] + #[stable(feature = "string_leak", since = "1.72.0")] #[inline] pub fn leak<'a>(self) -> &'a mut str { let slice = self.vec.leak(); diff --git a/library/alloc/tests/str.rs b/library/alloc/tests/str.rs index 0ba5d088f61..82c1a9f9ad7 100644 --- a/library/alloc/tests/str.rs +++ b/library/alloc/tests/str.rs @@ -1,4 +1,4 @@ -#![cfg_attr(not(bootstrap), allow(invalid_from_utf8))] +#![allow(invalid_from_utf8)] use std::assert_matches::assert_matches; use std::borrow::Cow; diff --git a/library/alloc/tests/vec.rs b/library/alloc/tests/vec.rs index ddd93e9a436..183dd8e6e59 100644 --- a/library/alloc/tests/vec.rs +++ b/library/alloc/tests/vec.rs @@ -2498,3 +2498,68 @@ fn test_into_flattened_size_overflow() { let v = vec![[(); usize::MAX]; 2]; let _ = v.into_flattened(); } + +#[cfg(not(bootstrap))] +#[test] +fn test_box_zero_allocator() { + use core::{alloc::AllocError, cell::RefCell}; + use std::collections::HashSet; + + // Track ZST allocations and ensure that they all have a matching free. + struct ZstTracker { + state: RefCell<(HashSet<usize>, usize)>, + } + unsafe impl Allocator for ZstTracker { + fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> { + let ptr = if layout.size() == 0 { + let mut state = self.state.borrow_mut(); + let addr = state.1; + assert!(state.0.insert(addr)); + state.1 += 1; + std::println!("allocating {addr}"); + std::ptr::invalid_mut(addr) + } else { + unsafe { std::alloc::alloc(layout) } + }; + Ok(NonNull::slice_from_raw_parts(NonNull::new(ptr).ok_or(AllocError)?, layout.size())) + } + + unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) { + if layout.size() == 0 { + let addr = ptr.as_ptr() as usize; + let mut state = self.state.borrow_mut(); + std::println!("freeing {addr}"); + assert!(state.0.remove(&addr), "ZST free that wasn't allocated"); + } else { + unsafe { std::alloc::dealloc(ptr.as_ptr(), layout) } + } + } + } + + // Start the state at 100 to avoid returning null pointers. + let alloc = ZstTracker { state: RefCell::new((HashSet::new(), 100)) }; + + // Ensure that unsizing retains the same behavior. + { + let b1: Box<[u8; 0], &ZstTracker> = Box::new_in([], &alloc); + let b2: Box<[u8], &ZstTracker> = b1.clone(); + let _b3: Box<[u8], &ZstTracker> = b2.clone(); + } + + // Ensure that shrinking doesn't leak a ZST allocation. + { + let mut v1: Vec<u8, &ZstTracker> = Vec::with_capacity_in(100, &alloc); + v1.shrink_to_fit(); + } + + // Ensure that conversion to/from vec works. + { + let v1: Vec<(), &ZstTracker> = Vec::with_capacity_in(100, &alloc); + let _b1: Box<[()], &ZstTracker> = v1.into_boxed_slice(); + let b2: Box<[()], &ZstTracker> = Box::new_in([(), (), ()], &alloc); + let _v2: Vec<(), &ZstTracker> = b2.into(); + } + + // Ensure all ZSTs have been freed. + assert!(alloc.state.borrow().0.is_empty()); +} diff --git a/library/core/src/any.rs b/library/core/src/any.rs index 09f52d692d0..277c2f76a08 100644 --- a/library/core/src/any.rs +++ b/library/core/src/any.rs @@ -697,9 +697,6 @@ impl TypeId { #[stable(feature = "rust1", since = "1.0.0")] #[rustc_const_unstable(feature = "const_type_id", issue = "77125")] pub const fn of<T: ?Sized + 'static>() -> TypeId { - #[cfg(bootstrap)] - let t = intrinsics::type_id::<T>() as u128; - #[cfg(not(bootstrap))] let t: u128 = intrinsics::type_id::<T>(); TypeId { t } } diff --git a/library/core/src/array/mod.rs b/library/core/src/array/mod.rs index 76b3589b9e4..ebd4a8c05fe 100644 --- a/library/core/src/array/mod.rs +++ b/library/core/src/array/mod.rs @@ -925,7 +925,7 @@ fn iter_next_chunk_erased<T>( // so we need to defuse the guard instead of using `?`. let initialized = guard.initialized; mem::forget(guard); - return Err(initialized) + return Err(initialized); }; // SAFETY: The loop condition ensures we have space to push the item diff --git a/library/core/src/ffi/c_str.rs b/library/core/src/ffi/c_str.rs index 3de9188baf6..39f795c1f13 100644 --- a/library/core/src/ffi/c_str.rs +++ b/library/core/src/ffi/c_str.rs @@ -377,7 +377,7 @@ impl CStr { /// assert!(cstr.is_err()); /// ``` #[stable(feature = "cstr_from_bytes", since = "1.10.0")] - #[rustc_const_stable(feature = "const_cstr_methods", since = "CURRENT_RUSTC_VERSION")] + #[rustc_const_stable(feature = "const_cstr_methods", since = "1.72.0")] pub const fn from_bytes_with_nul(bytes: &[u8]) -> Result<&Self, FromBytesWithNulError> { let nul_pos = memchr::memchr(0, bytes); match nul_pos { @@ -561,7 +561,7 @@ impl CStr { #[must_use = "this returns the result of the operation, \ without modifying the original"] #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_stable(feature = "const_cstr_methods", since = "CURRENT_RUSTC_VERSION")] + #[rustc_const_stable(feature = "const_cstr_methods", since = "1.72.0")] pub const fn to_bytes(&self) -> &[u8] { let bytes = self.to_bytes_with_nul(); // FIXME(const-hack) replace with range index @@ -590,7 +590,7 @@ impl CStr { #[must_use = "this returns the result of the operation, \ without modifying the original"] #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_stable(feature = "const_cstr_methods", since = "CURRENT_RUSTC_VERSION")] + #[rustc_const_stable(feature = "const_cstr_methods", since = "1.72.0")] pub const fn to_bytes_with_nul(&self) -> &[u8] { // SAFETY: Transmuting a slice of `c_char`s to a slice of `u8`s // is safe on all supported targets. @@ -614,7 +614,7 @@ impl CStr { /// assert_eq!(cstr.to_str(), Ok("foo")); /// ``` #[stable(feature = "cstr_to_str", since = "1.4.0")] - #[rustc_const_stable(feature = "const_cstr_methods", since = "CURRENT_RUSTC_VERSION")] + #[rustc_const_stable(feature = "const_cstr_methods", since = "1.72.0")] pub const fn to_str(&self) -> Result<&str, str::Utf8Error> { // N.B., when `CStr` is changed to perform the length check in `.to_bytes()` // instead of in `from_ptr()`, it may be worth considering if this should diff --git a/library/core/src/intrinsics.rs b/library/core/src/intrinsics.rs index 5a9a7013a19..deef68e4699 100644 --- a/library/core/src/intrinsics.rs +++ b/library/core/src/intrinsics.rs @@ -1057,23 +1057,6 @@ extern "rust-intrinsic" { #[rustc_const_unstable(feature = "const_type_id", issue = "77125")] #[rustc_safe_intrinsic] #[rustc_nounwind] - #[cfg(bootstrap)] - pub fn type_id<T: ?Sized + 'static>() -> u64; - - /// Gets an identifier which is globally unique to the specified type. This - /// function will return the same value for a type regardless of whichever - /// crate it is invoked in. - /// - /// Note that, unlike most intrinsics, this is safe to call; - /// it does not require an `unsafe` block. - /// Therefore, implementations must not require the user to uphold - /// any safety invariants. - /// - /// The stabilized version of this intrinsic is [`core::any::TypeId::of`]. - #[rustc_const_unstable(feature = "const_type_id", issue = "77125")] - #[rustc_safe_intrinsic] - #[rustc_nounwind] - #[cfg(not(bootstrap))] pub fn type_id<T: ?Sized + 'static>() -> u128; /// A guard for unsafe functions that cannot ever be executed if `T` is uninhabited: diff --git a/library/core/src/iter/adapters/flatten.rs b/library/core/src/iter/adapters/flatten.rs index d3e45456351..eee6e5bccec 100644 --- a/library/core/src/iter/adapters/flatten.rs +++ b/library/core/src/iter/adapters/flatten.rs @@ -310,7 +310,7 @@ where /// Real logic of both `Flatten` and `FlatMap` which simply delegate to /// this type. #[derive(Clone, Debug)] -#[cfg_attr(bootstrap, unstable(feature = "trusted_len", issue = "37572"))] +#[unstable(feature = "trusted_len", issue = "37572")] struct FlattenCompat<I, U> { iter: Fuse<I>, frontiter: Option<U>, @@ -464,7 +464,6 @@ where } } -#[cfg_attr(bootstrap, unstable(feature = "trusted_len", issue = "37572"))] impl<I, U> Iterator for FlattenCompat<I, U> where I: Iterator<Item: IntoIterator<IntoIter = U, Item = U::Item>>, @@ -579,7 +578,6 @@ where } } -#[cfg_attr(bootstrap, unstable(feature = "trusted_len", issue = "37572"))] impl<I, U> DoubleEndedIterator for FlattenCompat<I, U> where I: DoubleEndedIterator<Item: IntoIterator<IntoIter = U, Item = U::Item>>, @@ -649,7 +647,6 @@ where } } -#[cfg_attr(bootstrap, unstable(feature = "trusted_len", issue = "37572"))] unsafe impl<const N: usize, I, T> TrustedLen for FlattenCompat<I, <[T; N] as IntoIterator>::IntoIter> where @@ -657,7 +654,6 @@ where { } -#[cfg_attr(bootstrap, unstable(feature = "trusted_len", issue = "37572"))] unsafe impl<'a, const N: usize, I, T> TrustedLen for FlattenCompat<I, <&'a [T; N] as IntoIterator>::IntoIter> where @@ -665,7 +661,6 @@ where { } -#[cfg_attr(bootstrap, unstable(feature = "trusted_len", issue = "37572"))] unsafe impl<'a, const N: usize, I, T> TrustedLen for FlattenCompat<I, <&'a mut [T; N] as IntoIterator>::IntoIter> where diff --git a/library/core/src/iter/traits/collect.rs b/library/core/src/iter/traits/collect.rs index 0675e56358f..e0ef5071c40 100644 --- a/library/core/src/iter/traits/collect.rs +++ b/library/core/src/iter/traits/collect.rs @@ -138,8 +138,6 @@ pub trait FromIterator<A>: Sized { /// /// # Examples /// - /// Basic usage: - /// /// ``` /// let five_fives = std::iter::repeat(5).take(5); /// @@ -255,8 +253,6 @@ pub trait IntoIterator { /// /// # Examples /// - /// Basic usage: - /// /// ``` /// let v = [1, 2, 3]; /// let mut iter = v.into_iter(); @@ -363,8 +359,6 @@ pub trait Extend<A> { /// /// # Examples /// - /// Basic usage: - /// /// ``` /// // You can extend a String with some chars: /// let mut message = String::from("abc"); diff --git a/library/core/src/marker.rs b/library/core/src/marker.rs index e251015dd86..5ec751e5168 100644 --- a/library/core/src/marker.rs +++ b/library/core/src/marker.rs @@ -140,8 +140,7 @@ unsafe impl<T: Sync + ?Sized> Send for &T {} )] #[fundamental] // for Default, for example, which requires that `[T]: !Default` be evaluatable #[rustc_specialization_trait] -#[cfg_attr(not(bootstrap), rustc_deny_explicit_impl(implement_via_object = false))] -#[cfg_attr(bootstrap, rustc_deny_explicit_impl)] +#[rustc_deny_explicit_impl(implement_via_object = false)] #[rustc_coinductive] pub trait Sized { // Empty. @@ -174,8 +173,7 @@ pub trait Sized { /// [nomicon-coerce]: ../../nomicon/coercions.html #[unstable(feature = "unsize", issue = "18598")] #[lang = "unsize"] -#[cfg_attr(not(bootstrap), rustc_deny_explicit_impl(implement_via_object = false))] -#[cfg_attr(bootstrap, rustc_deny_explicit_impl)] +#[rustc_deny_explicit_impl(implement_via_object = false)] pub trait Unsize<T: ?Sized> { // Empty. } @@ -856,8 +854,7 @@ impl<T: ?Sized> StructuralEq for PhantomData<T> {} reason = "this trait is unlikely to ever be stabilized, use `mem::discriminant` instead" )] #[lang = "discriminant_kind"] -#[cfg_attr(not(bootstrap), rustc_deny_explicit_impl(implement_via_object = false))] -#[cfg_attr(bootstrap, rustc_deny_explicit_impl)] +#[rustc_deny_explicit_impl(implement_via_object = false)] pub trait DiscriminantKind { /// The type of the discriminant, which must satisfy the trait /// bounds required by `mem::Discriminant`. @@ -962,8 +959,7 @@ marker_impls! { #[unstable(feature = "const_trait_impl", issue = "67792")] #[lang = "destruct"] #[rustc_on_unimplemented(message = "can't drop `{Self}`", append_const_msg)] -#[cfg_attr(not(bootstrap), rustc_deny_explicit_impl(implement_via_object = false))] -#[cfg_attr(bootstrap, rustc_deny_explicit_impl)] +#[rustc_deny_explicit_impl(implement_via_object = false)] #[const_trait] pub trait Destruct {} @@ -974,8 +970,7 @@ pub trait Destruct {} #[unstable(feature = "tuple_trait", issue = "none")] #[lang = "tuple_trait"] #[rustc_on_unimplemented(message = "`{Self}` is not a tuple")] -#[cfg_attr(not(bootstrap), rustc_deny_explicit_impl(implement_via_object = false))] -#[cfg_attr(bootstrap, rustc_deny_explicit_impl)] +#[rustc_deny_explicit_impl(implement_via_object = false)] pub trait Tuple {} /// A marker for pointer-like types. @@ -1020,7 +1015,6 @@ marker_impls! { // FIXME(adt_const_params): Add to marker_impls call above once not in bootstrap #[unstable(feature = "adt_const_params", issue = "95174")] -#[cfg(not(bootstrap))] impl ConstParamTy for () {} /// A common trait implemented by all function pointers. @@ -1030,8 +1024,7 @@ impl ConstParamTy for () {} reason = "internal trait for implementing various traits for all function pointers" )] #[lang = "fn_ptr_trait"] -#[cfg_attr(not(bootstrap), rustc_deny_explicit_impl(implement_via_object = false))] -#[cfg_attr(bootstrap, rustc_deny_explicit_impl)] +#[rustc_deny_explicit_impl(implement_via_object = false)] pub trait FnPtr: Copy + Clone { /// Returns the address of the function pointer. #[lang = "fn_ptr_addr"] diff --git a/library/core/src/mem/transmutability.rs b/library/core/src/mem/transmutability.rs index 3805d149b70..f5cc86e7767 100644 --- a/library/core/src/mem/transmutability.rs +++ b/library/core/src/mem/transmutability.rs @@ -7,8 +7,8 @@ use crate::marker::ConstParamTy; /// notwithstanding whatever safety checks you have asked the compiler to [`Assume`] are satisfied. #[unstable(feature = "transmutability", issue = "99571")] #[lang = "transmute_trait"] -#[cfg_attr(not(bootstrap), rustc_deny_explicit_impl(implement_via_object = false))] -#[cfg_attr(bootstrap, rustc_deny_explicit_impl)] +#[rustc_deny_explicit_impl(implement_via_object = false)] +#[rustc_coinductive] pub unsafe trait BikeshedIntrinsicFrom<Src, Context, const ASSUME: Assume = { Assume::NOTHING }> where Src: ?Sized, diff --git a/library/core/src/ptr/metadata.rs b/library/core/src/ptr/metadata.rs index daaa44b1d9a..040aa069787 100644 --- a/library/core/src/ptr/metadata.rs +++ b/library/core/src/ptr/metadata.rs @@ -50,8 +50,7 @@ use crate::hash::{Hash, Hasher}; /// /// [`to_raw_parts`]: *const::to_raw_parts #[lang = "pointee_trait"] -#[cfg_attr(not(bootstrap), rustc_deny_explicit_impl(implement_via_object = false))] -#[cfg_attr(bootstrap, rustc_deny_explicit_impl)] +#[rustc_deny_explicit_impl(implement_via_object = false)] pub trait Pointee { /// The type for metadata in pointers and references to `Self`. #[lang = "metadata_type"] diff --git a/library/core/src/ptr/unique.rs b/library/core/src/ptr/unique.rs index ff7e91d3ec3..bf8b86677d5 100644 --- a/library/core/src/ptr/unique.rs +++ b/library/core/src/ptr/unique.rs @@ -33,7 +33,7 @@ use crate::ptr::NonNull; #[doc(hidden)] #[repr(transparent)] // Lang item used experimentally by Miri to define the semantics of `Unique`. -#[cfg_attr(not(bootstrap), lang = "ptr_unique")] +#[lang = "ptr_unique"] pub struct Unique<T: ?Sized> { pointer: NonNull<T>, // NOTE: this marker has no consequences for variance, but is necessary diff --git a/library/core/src/result.rs b/library/core/src/result.rs index 1ee270f4c03..51b7616ffec 100644 --- a/library/core/src/result.rs +++ b/library/core/src/result.rs @@ -749,7 +749,7 @@ impl<T, E> Result<T, E> { } /// Returns the provided default (if [`Err`]), or - /// applies a function to the contained value (if [`Ok`]), + /// applies a function to the contained value (if [`Ok`]). /// /// Arguments passed to `map_or` are eagerly evaluated; if you are passing /// the result of a function call, it is recommended to use [`map_or_else`], diff --git a/library/core/src/slice/mod.rs b/library/core/src/slice/mod.rs index e2a2428fbc2..4f13ea9790d 100644 --- a/library/core/src/slice/mod.rs +++ b/library/core/src/slice/mod.rs @@ -2957,7 +2957,7 @@ impl<T> [T] { /// elements. /// /// This sort is unstable (i.e., may reorder equal elements), in-place - /// (i.e., does not allocate), and *O*(m \* *n* \* log(*n*)) worst-case, where the key function is + /// (i.e., does not allocate), and *O*(*m* \* *n* \* log(*n*)) worst-case, where the key function is /// *O*(*m*). /// /// # Current implementation diff --git a/library/core/src/str/pattern.rs b/library/core/src/str/pattern.rs index 91ee2903aab..d5d6d60acf6 100644 --- a/library/core/src/str/pattern.rs +++ b/library/core/src/str/pattern.rs @@ -1750,7 +1750,9 @@ fn simd_contains(needle: &str, haystack: &str) -> Option<bool> { 1 } else { // try a few bytes in case first and last byte of the needle are the same - let Some(second_probe_offset) = (needle.len().saturating_sub(4)..needle.len()).rfind(|&idx| needle[idx] != first_probe) else { + let Some(second_probe_offset) = + (needle.len().saturating_sub(4)..needle.len()).rfind(|&idx| needle[idx] != first_probe) + else { // fall back to other search methods if we can't find any different bytes // since we could otherwise hit some degenerate cases return None; diff --git a/library/core/src/tuple.rs b/library/core/src/tuple.rs index ac8d04a8286..7782ace69c1 100644 --- a/library/core/src/tuple.rs +++ b/library/core/src/tuple.rs @@ -1,7 +1,6 @@ // See src/libstd/primitive_docs.rs for documentation. use crate::cmp::Ordering::{self, *}; -#[cfg(not(bootstrap))] use crate::marker::ConstParamTy; use crate::marker::{StructuralEq, StructuralPartialEq}; @@ -51,7 +50,6 @@ macro_rules! tuple_impls { maybe_tuple_doc! { $($T)+ @ #[unstable(feature = "structural_match", issue = "31434")] - #[cfg(not(bootstrap))] impl<$($T: ConstParamTy),+> ConstParamTy for ($($T,)+) {} } diff --git a/library/core/tests/manually_drop.rs b/library/core/tests/manually_drop.rs index 22d72d219a7..bbf444471ad 100644 --- a/library/core/tests/manually_drop.rs +++ b/library/core/tests/manually_drop.rs @@ -1,4 +1,4 @@ -#![cfg_attr(not(bootstrap), allow(undropped_manually_drops))] +#![allow(undropped_manually_drops)] use core::mem::ManuallyDrop; diff --git a/library/std/Cargo.toml b/library/std/Cargo.toml index eb4815d0cdf..c129a753912 100644 --- a/library/std/Cargo.toml +++ b/library/std/Cargo.toml @@ -45,7 +45,7 @@ dlmalloc = { version = "0.2.3", features = ['rustc-dep-of-std'] } fortanix-sgx-abi = { version = "0.5.0", features = ['rustc-dep-of-std'], public = true } [target.'cfg(target_os = "hermit")'.dependencies] -hermit-abi = { version = "0.3.0", features = ['rustc-dep-of-std'] } +hermit-abi = { version = "0.3.2", features = ['rustc-dep-of-std'], public = true } [target.wasm32-wasi.dependencies] wasi = { version = "0.11.0", features = ['rustc-dep-of-std'], default-features = false } diff --git a/library/std/src/collections/hash/set.rs b/library/std/src/collections/hash/set.rs index ec59634df36..959403e1644 100644 --- a/library/std/src/collections/hash/set.rs +++ b/library/std/src/collections/hash/set.rs @@ -65,8 +65,8 @@ use super::map::{map_try_reserve_error, RandomState}; /// ``` /// /// The easiest way to use `HashSet` with a custom type is to derive -/// [`Eq`] and [`Hash`]. We must also derive [`PartialEq`], this will in the -/// future be implied by [`Eq`]. +/// [`Eq`] and [`Hash`]. We must also derive [`PartialEq`], +/// which is required if [`Eq`] is derived. /// /// ``` /// use std::collections::HashSet; diff --git a/library/std/src/ffi/os_str.rs b/library/std/src/ffi/os_str.rs index fbdf7f5ecac..e7bad9d542c 100644 --- a/library/std/src/ffi/os_str.rs +++ b/library/std/src/ffi/os_str.rs @@ -1165,7 +1165,7 @@ impl<'a> From<Cow<'a, OsStr>> for OsString { } } -#[stable(feature = "str_tryfrom_osstr_impl", since = "CURRENT_RUSTC_VERSION")] +#[stable(feature = "str_tryfrom_osstr_impl", since = "1.72.0")] impl<'a> TryFrom<&'a OsStr> for &'a str { type Error = crate::str::Utf8Error; diff --git a/library/std/src/io/readbuf.rs b/library/std/src/io/readbuf.rs index 4800eeda022..1f3f80b9618 100644 --- a/library/std/src/io/readbuf.rs +++ b/library/std/src/io/readbuf.rs @@ -99,6 +99,13 @@ impl<'data> BorrowedBuf<'data> { unsafe { MaybeUninit::slice_assume_init_ref(&self.buf[0..self.filled]) } } + /// Returns a mutable reference to the filled portion of the buffer. + #[inline] + pub fn filled_mut(&mut self) -> &mut [u8] { + // SAFETY: We only slice the filled part of the buffer, which is always valid + unsafe { MaybeUninit::slice_assume_init_mut(&mut self.buf[0..self.filled]) } + } + /// Returns a cursor over the unfilled part of the buffer. #[inline] pub fn unfilled<'this>(&'this mut self) -> BorrowedCursor<'this> { diff --git a/library/std/src/sync/mpsc/mod.rs b/library/std/src/sync/mpsc/mod.rs index 71ff4237d00..c00134c8b95 100644 --- a/library/std/src/sync/mpsc/mod.rs +++ b/library/std/src/sync/mpsc/mod.rs @@ -347,7 +347,7 @@ pub struct Sender<T> { #[stable(feature = "rust1", since = "1.0.0")] unsafe impl<T: Send> Send for Sender<T> {} -#[stable(feature = "mpsc_sender_sync", since = "CURRENT_RUSTC_VERSION")] +#[stable(feature = "mpsc_sender_sync", since = "1.72.0")] unsafe impl<T: Send> Sync for Sender<T> {} /// The sending-half of Rust's synchronous [`sync_channel`] type. diff --git a/library/std/src/sys/hermit/thread.rs b/library/std/src/sys/hermit/thread.rs index 2507f706951..332151e40d0 100644 --- a/library/std/src/sys/hermit/thread.rs +++ b/library/std/src/sys/hermit/thread.rs @@ -1,6 +1,5 @@ #![allow(dead_code)] -use super::unsupported; use crate::ffi::CStr; use crate::io; use crate::mem; @@ -99,7 +98,7 @@ impl Thread { } pub fn available_parallelism() -> io::Result<NonZeroUsize> { - unsupported() + unsafe { Ok(NonZeroUsize::new_unchecked(abi::get_processor_count())) } } pub mod guard { diff --git a/library/std/src/sys/hermit/time.rs b/library/std/src/sys/hermit/time.rs index 5440d85df4a..7d91460aba3 100644 --- a/library/std/src/sys/hermit/time.rs +++ b/library/std/src/sys/hermit/time.rs @@ -40,7 +40,7 @@ impl Timespec { } fn checked_add_duration(&self, other: &Duration) -> Option<Timespec> { - let mut secs = self.tv_sec.checked_add_unsigned(other.as_secs())?; + let mut secs = self.t.tv_sec.checked_add_unsigned(other.as_secs())?; // Nano calculations can't overflow because nanos are <1B which fit // in a u32. @@ -53,7 +53,7 @@ impl Timespec { } fn checked_sub_duration(&self, other: &Duration) -> Option<Timespec> { - let mut secs = self.tv_sec.checked_sub_unsigned(other.as_secs())?; + let mut secs = self.t.tv_sec.checked_sub_unsigned(other.as_secs())?; // Similar to above, nanos can't overflow. let mut nsec = self.t.tv_nsec as i32 - other.subsec_nanos() as i32; diff --git a/src/bootstrap/bootstrap.py b/src/bootstrap/bootstrap.py index 149350e62a0..fe66b1d41bf 100644 --- a/src/bootstrap/bootstrap.py +++ b/src/bootstrap/bootstrap.py @@ -97,7 +97,7 @@ def _download(path, url, probably_big, verbose, exception): print("downloading {}".format(url), file=sys.stderr) try: - if probably_big or verbose: + if (probably_big or verbose) and "GITHUB_ACTIONS" not in os.environ: option = "-#" else: option = "-s" @@ -256,7 +256,7 @@ def default_build_triple(verbose): if uname is None: return 'x86_64-pc-windows-msvc' - kernel, cputype, processor = uname.decode(default_encoding).split() + kernel, cputype, processor = uname.decode(default_encoding).split(maxsplit=2) # The goal here is to come up with the same triple as LLVM would, # at least for the subset of platforms we're willing to target. @@ -914,12 +914,7 @@ class RustBuild(object): # preserve existing RUSTFLAGS env.setdefault("RUSTFLAGS", "") - # we need to explicitly add +xgot here so that we can successfully bootstrap - # a usable stage1 compiler - # FIXME: remove this if condition on the next bootstrap bump - # cfg(bootstrap) - if self.build_triple().startswith('mips'): - env["RUSTFLAGS"] += " -Ctarget-feature=+xgot" + target_features = [] if self.get_toml("crt-static", build_section) == "true": target_features += ["+crt-static"] diff --git a/src/bootstrap/builder.rs b/src/bootstrap/builder.rs index c0c749552e6..766c187e8e8 100644 --- a/src/bootstrap/builder.rs +++ b/src/bootstrap/builder.rs @@ -115,6 +115,43 @@ impl RunConfig<'_> { } INTERNER.intern_list(crates) } + + /// Given an `alias` selected by the `Step` and the paths passed on the command line, + /// return a list of the crates that should be built. + /// + /// Normally, people will pass *just* `library` if they pass it. + /// But it's possible (although strange) to pass something like `library std core`. + /// Build all crates anyway, as if they hadn't passed the other args. + pub fn make_run_crates(&self, alias: Alias) -> Interned<Vec<String>> { + let has_alias = + self.paths.iter().any(|set| set.assert_single_path().path.ends_with(alias.as_str())); + if !has_alias { + return self.cargo_crates_in_set(); + } + + let crates = match alias { + Alias::Library => self.builder.in_tree_crates("sysroot", Some(self.target)), + Alias::Compiler => self.builder.in_tree_crates("rustc-main", Some(self.target)), + }; + + let crate_names = crates.into_iter().map(|krate| krate.name.to_string()).collect(); + INTERNER.intern_list(crate_names) + } +} + +#[derive(Debug, Copy, Clone)] +pub enum Alias { + Library, + Compiler, +} + +impl Alias { + fn as_str(self) -> &'static str { + match self { + Alias::Library => "library", + Alias::Compiler => "compiler", + } + } } /// A description of the crates in this set, suitable for passing to `builder.info`. @@ -358,7 +395,7 @@ impl StepDescription { eprintln!( "note: if you are adding a new Step to bootstrap itself, make sure you register it with `describe!`" ); - crate::detail_exit_macro!(1); + crate::exit!(1); } } } @@ -902,21 +939,6 @@ impl<'a> Builder<'a> { Self::new_internal(build, kind, paths.to_owned()) } - /// Creates a new standalone builder for use outside of the normal process - pub fn new_standalone( - build: &mut Build, - kind: Kind, - paths: Vec<PathBuf>, - stage: Option<u32>, - ) -> Builder<'_> { - // FIXME: don't mutate `build` - if let Some(stage) = stage { - build.config.stage = stage; - } - - Self::new_internal(build, kind, paths.to_owned()) - } - pub fn execute_cli(&self) { self.run_step_descriptions(&Builder::get_step_descriptions(self.kind), &self.paths); } @@ -1338,7 +1360,7 @@ impl<'a> Builder<'a> { "error: `x.py clippy` requires a host `rustc` toolchain with the `clippy` component" ); eprintln!("help: try `rustup component add clippy`"); - crate::detail_exit_macro!(1); + crate::exit!(1); }); if !t!(std::str::from_utf8(&output.stdout)).contains("nightly") { rustflags.arg("--cfg=bootstrap"); diff --git a/src/bootstrap/builder/tests.rs b/src/bootstrap/builder/tests.rs index 31dcee58216..65b8f7fd3b7 100644 --- a/src/bootstrap/builder/tests.rs +++ b/src/bootstrap/builder/tests.rs @@ -68,13 +68,17 @@ macro_rules! std { } macro_rules! doc_std { - ($host:ident => $target:ident, stage = $stage:literal) => { + ($host:ident => $target:ident, stage = $stage:literal) => {{ + let config = configure("doc", &["A"], &["A"]); + let build = Build::new(config); + let builder = Builder::new(&build); doc::Std::new( $stage, TargetSelection::from_user(stringify!($target)), + &builder, DocumentationFormat::HTML, ) - }; + }}; } macro_rules! rustc { diff --git a/src/bootstrap/check.rs b/src/bootstrap/check.rs index 1a0f0047812..9795f22e2b5 100644 --- a/src/bootstrap/check.rs +++ b/src/bootstrap/check.rs @@ -1,10 +1,8 @@ //! Implementation of compiling the compiler and standard library, in "check"-based modes. -use crate::builder::{crate_description, Builder, Kind, RunConfig, ShouldRun, Step}; +use crate::builder::{crate_description, Alias, Builder, Kind, RunConfig, ShouldRun, Step}; use crate::cache::Interned; -use crate::compile::{ - add_to_sysroot, make_run_crates, run_cargo, rustc_cargo, rustc_cargo_env, std_cargo, -}; +use crate::compile::{add_to_sysroot, run_cargo, rustc_cargo, rustc_cargo_env, std_cargo}; use crate::config::TargetSelection; use crate::tool::{prepare_tool_cargo, SourceType}; use crate::INTERNER; @@ -89,7 +87,7 @@ impl Step for Std { } fn make_run(run: RunConfig<'_>) { - let crates = make_run_crates(&run, "library"); + let crates = run.make_run_crates(Alias::Library); run.builder.ensure(Std { target: run.target, crates }); } @@ -137,10 +135,11 @@ impl Step for Std { let hostdir = builder.sysroot_libdir(compiler, compiler.host); add_to_sysroot(&builder, &libdir, &hostdir, &libstd_stamp(builder, compiler, target)); } + drop(_guard); // don't run on std twice with x.py clippy // don't check test dependencies if we haven't built libtest - if builder.kind == Kind::Clippy || !self.crates.is_empty() { + if builder.kind == Kind::Clippy || !self.crates.iter().any(|krate| krate == "test") { return; } @@ -200,10 +199,11 @@ pub struct Rustc { impl Rustc { pub fn new(target: TargetSelection, builder: &Builder<'_>) -> Self { - let mut crates = vec![]; - for krate in builder.in_tree_crates("rustc-main", None) { - crates.push(krate.name.to_string()); - } + let crates = builder + .in_tree_crates("rustc-main", Some(target)) + .into_iter() + .map(|krate| krate.name.to_string()) + .collect(); Self { target, crates: INTERNER.intern_list(crates) } } } @@ -218,7 +218,7 @@ impl Step for Rustc { } fn make_run(run: RunConfig<'_>) { - let crates = make_run_crates(&run, "compiler"); + let crates = run.make_run_crates(Alias::Compiler); run.builder.ensure(Rustc { target: run.target, crates }); } diff --git a/src/bootstrap/clean.rs b/src/bootstrap/clean.rs index c1d867a0bd1..ea8334eaeb6 100644 --- a/src/bootstrap/clean.rs +++ b/src/bootstrap/clean.rs @@ -26,7 +26,9 @@ impl Step for CleanAll { } fn run(self, builder: &Builder<'_>) -> Self::Output { - let Subcommand::Clean { all, .. } = builder.config.cmd else { unreachable!("wrong subcommand?") }; + let Subcommand::Clean { all, .. } = builder.config.cmd else { + unreachable!("wrong subcommand?") + }; clean_default(builder.build, all) } diff --git a/src/bootstrap/compile.rs b/src/bootstrap/compile.rs index efe621bdb7d..f3d95b57a76 100644 --- a/src/bootstrap/compile.rs +++ b/src/bootstrap/compile.rs @@ -55,17 +55,6 @@ impl Std { } } -/// Given an `alias` selected by the `Step` and the paths passed on the command line, -/// return a list of the crates that should be built. -/// -/// Normally, people will pass *just* `library` if they pass it. -/// But it's possible (although strange) to pass something like `library std core`. -/// Build all crates anyway, as if they hadn't passed the other args. -pub(crate) fn make_run_crates(run: &RunConfig<'_>, alias: &str) -> Interned<Vec<String>> { - let has_alias = run.paths.iter().any(|set| set.assert_single_path().path.ends_with(alias)); - if has_alias { Default::default() } else { run.cargo_crates_in_set() } -} - impl Step for Std { type Output = (); const DEFAULT: bool = true; @@ -80,10 +69,15 @@ impl Step for Std { } fn make_run(run: RunConfig<'_>) { + // If the paths include "library", build the entire standard library. + let has_alias = + run.paths.iter().any(|set| set.assert_single_path().path.ends_with("library")); + let crates = if has_alias { Default::default() } else { run.cargo_crates_in_set() }; + run.builder.ensure(Std { compiler: run.builder.compiler(run.builder.top_stage, run.build_triple()), target: run.target, - crates: make_run_crates(&run, "library"), + crates, force_recompile: false, }); } @@ -228,13 +222,6 @@ fn copy_third_party_objects( ) -> Vec<(PathBuf, DependencyType)> { let mut target_deps = vec![]; - // FIXME: remove this in 2021 - if target == "x86_64-fortanix-unknown-sgx" { - if env::var_os("X86_FORTANIX_SGX_LIBS").is_some() { - builder.info("Warning: X86_FORTANIX_SGX_LIBS environment variable is ignored, libunwind is now compiled as part of rustbuild"); - } - } - if builder.config.sanitizers_enabled(target) && compiler.stage != 0 { // The sanitizers are only copied in stage1 or above, // to avoid creating dependency on LLVM. @@ -688,8 +675,8 @@ fn cp_rustc_component_to_ci_sysroot( contents: Vec<String>, ) { let sysroot = builder.ensure(Sysroot { compiler, force_recompile: false }); + let ci_rustc_dir = builder.config.ci_rustc_dir(); - let ci_rustc_dir = builder.out.join(&*builder.build.build.triple).join("ci-rustc"); for file in contents { let src = ci_rustc_dir.join(&file); let dst = sysroot.join(file); @@ -1424,7 +1411,7 @@ impl Step for Sysroot { // FIXME: this is wrong when compiler.host != build, but we don't support that today OsStr::new(std::env::consts::DLL_EXTENSION), ]; - let ci_rustc_dir = builder.ci_rustc_dir(builder.config.build); + let ci_rustc_dir = builder.config.ci_rustc_dir(); builder.cp_filtered(&ci_rustc_dir, &sysroot, &|path| { if path.extension().map_or(true, |ext| !filtered_extensions.contains(&ext)) { return true; @@ -1826,7 +1813,7 @@ pub fn run_cargo( }); if !ok { - crate::detail_exit_macro!(1); + crate::exit!(1); } // Ok now we need to actually find all the files listed in `toplevel`. We've diff --git a/src/bootstrap/config.rs b/src/bootstrap/config.rs index 28ae46efefe..856a73a22b5 100644 --- a/src/bootstrap/config.rs +++ b/src/bootstrap/config.rs @@ -23,7 +23,7 @@ use crate::channel::{self, GitInfo}; pub use crate::flags::Subcommand; use crate::flags::{Color, Flags, Warnings}; use crate::util::{exe, output, t}; -use build_helper::detail_exit_macro; +use build_helper::exit; use once_cell::sync::OnceCell; use semver::Version; use serde::{Deserialize, Deserializer}; @@ -646,7 +646,7 @@ macro_rules! define_config { panic!("overriding existing option") } else { eprintln!("overriding existing option: `{}`", stringify!($field)); - detail_exit_macro!(2); + exit!(2); } } else { self.$field = other.$field; @@ -745,7 +745,7 @@ impl<T> Merge for Option<T> { panic!("overriding existing option") } else { eprintln!("overriding existing option"); - detail_exit_macro!(2); + exit!(2); } } else { *self = other; @@ -1101,7 +1101,7 @@ impl Config { .and_then(|table: toml::Value| TomlConfig::deserialize(table)) .unwrap_or_else(|err| { eprintln!("failed to parse TOML configuration '{}': {err}", file.display()); - detail_exit_macro!(2); + exit!(2); }) } Self::parse_inner(args, get_toml) @@ -1135,7 +1135,7 @@ impl Config { eprintln!( "Cannot use both `llvm_bolt_profile_generate` and `llvm_bolt_profile_use` at the same time" ); - detail_exit_macro!(1); + exit!(1); } // Infer the rest of the configuration. @@ -1259,7 +1259,7 @@ impl Config { } } eprintln!("failed to parse override `{option}`: `{err}"); - detail_exit_macro!(2) + exit!(2) } toml.merge(override_toml, ReplaceOpt::Override); @@ -1375,6 +1375,25 @@ impl Config { let mut omit_git_hash = None; if let Some(rust) = toml.rust { + set(&mut config.channel, rust.channel); + + config.download_rustc_commit = config.download_ci_rustc_commit(rust.download_rustc); + // This list is incomplete, please help by expanding it! + if config.download_rustc_commit.is_some() { + // We need the channel used by the downloaded compiler to match the one we set for rustdoc; + // otherwise rustdoc-ui tests break. + let ci_channel = t!(fs::read_to_string(config.src.join("src/ci/channel"))); + let ci_channel = ci_channel.trim_end(); + if config.channel != ci_channel + && !(config.channel == "dev" && ci_channel == "nightly") + { + panic!( + "setting rust.channel={} is incompatible with download-rustc", + config.channel + ); + } + } + debug = rust.debug; debug_assertions = rust.debug_assertions; debug_assertions_std = rust.debug_assertions_std; @@ -1386,6 +1405,7 @@ impl Config { debuginfo_level_std = rust.debuginfo_level_std; debuginfo_level_tools = rust.debuginfo_level_tools; debuginfo_level_tests = rust.debuginfo_level_tests; + config.rust_split_debuginfo = rust .split_debuginfo .as_deref() @@ -1401,7 +1421,6 @@ impl Config { set(&mut config.jemalloc, rust.jemalloc); set(&mut config.test_compare_mode, rust.test_compare_mode); set(&mut config.backtrace, rust.backtrace); - set(&mut config.channel, rust.channel); config.description = rust.description; set(&mut config.rust_dist_src, rust.dist_src); set(&mut config.verbose_tests, rust.verbose_tests); @@ -1442,8 +1461,6 @@ impl Config { config.rust_codegen_units_std = rust.codegen_units_std.map(threads_from_config); config.rust_profile_use = flags.rust_profile_use.or(rust.profile_use); config.rust_profile_generate = flags.rust_profile_generate.or(rust.profile_generate); - config.download_rustc_commit = config.download_ci_rustc_commit(rust.download_rustc); - config.rust_lto = rust .lto .as_deref() @@ -1555,6 +1572,11 @@ impl Config { let mut target = Target::from_triple(&triple); if let Some(ref s) = cfg.llvm_config { + if config.download_rustc_commit.is_some() && triple == &*config.build.triple { + panic!( + "setting llvm_config for the host is incompatible with download-rustc" + ); + } target.llvm_config = Some(config.src.join(s)); } target.llvm_has_rust_patches = cfg.llvm_has_rust_patches; @@ -1720,6 +1742,18 @@ impl Config { } } + /// Runs a command, printing out nice contextual information if it fails. + /// Exits if the command failed to execute at all, otherwise returns its + /// `status.success()`. + #[deprecated = "use `Builder::try_run` instead where possible"] + pub(crate) fn try_run(&self, cmd: &mut Command) -> Result<(), ()> { + if self.dry_run() { + return Ok(()); + } + self.verbose(&format!("running: {:?}", cmd)); + build_helper::util::try_run(cmd, self.is_verbose()) + } + /// A git invocation which runs inside the source directory. /// /// Use this rather than `Command::new("git")` in order to support out-of-tree builds. @@ -1825,6 +1859,12 @@ impl Config { self.out.join(&*self.build.triple).join("ci-llvm") } + /// Directory where the extracted `rustc-dev` component is stored. + pub(crate) fn ci_rustc_dir(&self) -> PathBuf { + assert!(self.download_rustc()); + self.out.join(self.build.triple).join("ci-rustc") + } + /// Determine whether llvm should be linked dynamically. /// /// If `false`, llvm should be linked statically. @@ -1860,11 +1900,11 @@ impl Config { self.download_rustc_commit().is_some() } - pub(crate) fn download_rustc_commit(&self) -> Option<&'static str> { + pub(crate) fn download_rustc_commit(&self) -> Option<&str> { static DOWNLOAD_RUSTC: OnceCell<Option<String>> = OnceCell::new(); if self.dry_run() && DOWNLOAD_RUSTC.get().is_none() { // avoid trying to actually download the commit - return None; + return self.download_rustc_commit.as_deref(); } DOWNLOAD_RUSTC @@ -1979,7 +2019,7 @@ impl Config { "Unexpected rustc version: {}, we should use {}/{} to build source with {}", rustc_version, prev_version, source_version, source_version ); - detail_exit_macro!(1); + exit!(1); } } @@ -2015,7 +2055,7 @@ impl Config { println!("help: maybe your repository history is too shallow?"); println!("help: consider disabling `download-rustc`"); println!("help: or fetch enough history to include one upstream commit"); - crate::detail_exit_macro!(1); + crate::exit!(1); } // Warn if there were changes to the compiler or standard library since the ancestor commit. diff --git a/src/bootstrap/configure.py b/src/bootstrap/configure.py index e8eebdfb5a5..a7beb2a1767 100755 --- a/src/bootstrap/configure.py +++ b/src/bootstrap/configure.py @@ -550,6 +550,8 @@ if __name__ == "__main__": # If 'config.toml' already exists, exit the script at this point quit_if_file_exists('config.toml') + if "GITHUB_ACTIONS" in os.environ: + print("::group::Configure the build") p("processing command line") # Parse all known arguments into a configuration structure that reflects the # TOML we're going to write out @@ -572,3 +574,5 @@ if __name__ == "__main__": p("") p("run `python {}/x.py --help`".format(rust_dir)) + if "GITHUB_ACTIONS" in os.environ: + print("::endgroup::") diff --git a/src/bootstrap/dist.rs b/src/bootstrap/dist.rs index 4522819f996..8c71b7f7fc2 100644 --- a/src/bootstrap/dist.rs +++ b/src/bootstrap/dist.rs @@ -106,7 +106,12 @@ impl Step for JsonDocs { /// Builds the `rust-docs-json` installer component. fn run(self, builder: &Builder<'_>) -> Option<GeneratedTarball> { let host = self.host; - builder.ensure(crate::doc::Std::new(builder.top_stage, host, DocumentationFormat::JSON)); + builder.ensure(crate::doc::Std::new( + builder.top_stage, + host, + builder, + DocumentationFormat::JSON, + )); let dest = "share/doc/rust/json"; @@ -897,7 +902,9 @@ impl Step for Src { /// Creates the `rust-src` installer component fn run(self, builder: &Builder<'_>) -> GeneratedTarball { - builder.update_submodule(&Path::new("src/llvm-project")); + if !builder.config.dry_run() { + builder.update_submodule(&Path::new("src/llvm-project")); + } let tarball = Tarball::new_targetless(builder, "rust-src"); @@ -1074,11 +1081,7 @@ impl Step for Cargo { tarball.add_file(&cargo, "bin", 0o755); tarball.add_file(etc.join("_cargo"), "share/zsh/site-functions", 0o644); - tarball.add_renamed_file( - etc.join("cargo.bashcomp.sh"), - "src/etc/bash_completion.d", - "cargo", - ); + tarball.add_renamed_file(etc.join("cargo.bashcomp.sh"), "etc/bash_completion.d", "cargo"); tarball.add_dir(etc.join("man"), "share/man/man1"); tarball.add_legal_and_readme_to("share/doc/cargo"); diff --git a/src/bootstrap/doc.rs b/src/bootstrap/doc.rs index 5ebfe0995a8..e58f736d67f 100644 --- a/src/bootstrap/doc.rs +++ b/src/bootstrap/doc.rs @@ -11,10 +11,9 @@ use std::fs; use std::path::{Path, PathBuf}; use crate::builder::crate_description; -use crate::builder::{Builder, Compiler, Kind, RunConfig, ShouldRun, Step}; +use crate::builder::{Alias, Builder, Compiler, Kind, RunConfig, ShouldRun, Step}; use crate::cache::{Interned, INTERNER}; use crate::compile; -use crate::compile::make_run_crates; use crate::config::{Config, TargetSelection}; use crate::tool::{self, prepare_tool_cargo, SourceType, Tool}; use crate::util::{symlink_dir, t, up_to_date}; @@ -221,8 +220,11 @@ impl Step for TheBook { // build the version info page and CSS let shared_assets = builder.ensure(SharedAssets { target }); + // build the command first so we don't nest GHA groups + builder.rustdoc_cmd(compiler); + // build the redirect pages - builder.msg_doc(compiler, "book redirect pages", target); + let _guard = builder.msg_doc(compiler, "book redirect pages", target); for file in t!(fs::read_dir(builder.src.join(&relative_path).join("redirects"))) { let file = t!(file); let path = file.path(); @@ -306,7 +308,7 @@ impl Step for Standalone { fn run(self, builder: &Builder<'_>) { let target = self.target; let compiler = self.compiler; - builder.msg_doc(compiler, "standalone", target); + let _guard = builder.msg_doc(compiler, "standalone", target); let out = builder.doc_out(target); t!(fs::create_dir_all(&out)); @@ -424,8 +426,18 @@ pub struct Std { } impl Std { - pub(crate) fn new(stage: u32, target: TargetSelection, format: DocumentationFormat) -> Self { - Std { stage, target, format, crates: INTERNER.intern_list(vec![]) } + pub(crate) fn new( + stage: u32, + target: TargetSelection, + builder: &Builder<'_>, + format: DocumentationFormat, + ) -> Self { + let crates = builder + .in_tree_crates("sysroot", Some(target)) + .into_iter() + .map(|krate| krate.name.to_string()) + .collect(); + Std { stage, target, format, crates: INTERNER.intern_list(crates) } } } @@ -447,7 +459,7 @@ impl Step for Std { } else { DocumentationFormat::HTML }, - crates: make_run_crates(&run, "library"), + crates: run.make_run_crates(Alias::Library), }); } @@ -455,7 +467,7 @@ impl Step for Std { /// /// This will generate all documentation for the standard library and its /// dependencies. This is largely just a wrapper around `cargo doc`. - fn run(mut self, builder: &Builder<'_>) { + fn run(self, builder: &Builder<'_>) { let stage = self.stage; let target = self.target; let out = match self.format { @@ -493,20 +505,17 @@ impl Step for Std { return; } - // Look for library/std, library/core etc in the `x.py doc` arguments and - // open the corresponding rendered docs. - if self.crates.is_empty() { - self.crates = INTERNER.intern_list(vec!["library".to_owned()]); - }; - - for requested_crate in &*self.crates { - if requested_crate == "library" { - // For `x.py doc library --open`, open `std` by default. - let index = out.join("std").join("index.html"); - builder.open_in_browser(index); - } else if STD_PUBLIC_CRATES.iter().any(|&k| k == requested_crate) { - let index = out.join(requested_crate).join("index.html"); - builder.open_in_browser(index); + if builder.paths.iter().any(|path| path.ends_with("library")) { + // For `x.py doc library --open`, open `std` by default. + let index = out.join("std").join("index.html"); + builder.open_in_browser(index); + } else { + for requested_crate in &*self.crates { + if STD_PUBLIC_CRATES.iter().any(|&k| k == requested_crate) { + let index = out.join(requested_crate).join("index.html"); + builder.open_in_browser(index); + break; + } } } } @@ -539,9 +548,6 @@ impl DocumentationFormat { } /// Build the documentation for public standard library crates. -/// -/// `requested_crates` can be used to build only a subset of the crates. If empty, all crates will -/// be built. fn doc_std( builder: &Builder<'_>, format: DocumentationFormat, @@ -560,10 +566,6 @@ fn doc_std( let compiler = builder.compiler(stage, builder.config.build); - let description = - format!("library{} in {} format", crate_description(&requested_crates), format.as_str()); - let _guard = builder.msg_doc(compiler, &description, target); - let target_doc_dir_name = if format == DocumentationFormat::JSON { "json-doc" } else { "doc" }; let target_dir = builder.stage_out(compiler, Mode::Std).join(target.triple).join(target_doc_dir_name); @@ -592,22 +594,18 @@ fn doc_std( cargo.rustdocflag("--document-private-items").rustdocflag("--document-hidden-items"); } - // HACK: because we use `--manifest-path library/sysroot/Cargo.toml`, cargo thinks we only want to document that specific crate, not its dependencies. - // Override its default. - let built_crates = if requested_crates.is_empty() { - builder - .in_tree_crates("sysroot", None) - .into_iter() - .map(|krate| krate.name.to_string()) - .collect() - } else { - requested_crates.to_vec() - }; - - for krate in built_crates { + for krate in requested_crates { + if krate == "sysroot" { + // The sysroot crate is an implementation detail, don't include it in public docs. + continue; + } cargo.arg("-p").arg(krate); } + let description = + format!("library{} in {} format", crate_description(&requested_crates), format.as_str()); + let _guard = builder.msg_doc(compiler, &description, target); + builder.run(&mut cargo.into()); builder.cp_r(&out_dir, &out); } @@ -621,20 +619,10 @@ pub struct Rustc { impl Rustc { pub(crate) fn new(stage: u32, target: TargetSelection, builder: &Builder<'_>) -> Self { - // Find dependencies for top level crates. - let root_crates = vec![ - INTERNER.intern_str("rustc_driver"), - INTERNER.intern_str("rustc_codegen_llvm"), - INTERNER.intern_str("rustc_codegen_ssa"), - ]; - let crates: Vec<_> = root_crates - .iter() - .flat_map(|krate| { - builder - .in_tree_crates(krate, Some(target)) - .into_iter() - .map(|krate| krate.name.to_string()) - }) + let crates = builder + .in_tree_crates("rustc-main", Some(target)) + .into_iter() + .map(|krate| krate.name.to_string()) .collect(); Self { stage, target, crates: INTERNER.intern_list(crates) } } @@ -656,7 +644,7 @@ impl Step for Rustc { run.builder.ensure(Rustc { stage: run.builder.top_stage, target: run.target, - crates: make_run_crates(&run, "compiler"), + crates: run.make_run_crates(Alias::Compiler), }); } @@ -666,7 +654,7 @@ impl Step for Rustc { /// Compiler documentation is distributed separately, so we make sure /// we do not merge it with the other documentation from std, test and /// proc_macros. This is largely just a wrapper around `cargo doc`. - fn run(mut self, builder: &Builder<'_>) { + fn run(self, builder: &Builder<'_>) { let stage = self.stage; let target = self.target; @@ -726,24 +714,26 @@ impl Step for Rustc { let mut to_open = None; - if self.crates.is_empty() { - self.crates = INTERNER.intern_list(vec!["rustc_driver".to_owned()]); - }; - for krate in &*self.crates { // Create all crate output directories first to make sure rustdoc uses // relative links. // FIXME: Cargo should probably do this itself. - t!(fs::create_dir_all(out_dir.join(krate))); + let dir_name = krate.replace("-", "_"); + t!(fs::create_dir_all(out_dir.join(&*dir_name))); cargo.arg("-p").arg(krate); if to_open.is_none() { - to_open = Some(krate); + to_open = Some(dir_name); } } builder.run(&mut cargo.into()); - // Let's open the first crate documentation page: - if let Some(krate) = to_open { + + if builder.paths.iter().any(|path| path.ends_with("compiler")) { + // For `x.py doc compiler --open`, open `rustc_middle` by default. + let index = out.join("rustc_middle").join("index.html"); + builder.open_in_browser(index); + } else if let Some(krate) = to_open { + // Let's open the first crate documentation page: let index = out.join(krate).join("index.html"); builder.open_in_browser(index); } @@ -812,8 +802,6 @@ macro_rules! tool_doc { SourceType::Submodule }; - builder.msg_doc(compiler, stringify!($tool).to_lowercase(), target); - // Symlink compiler docs to the output directory of rustdoc documentation. let out_dirs = [ builder.stage_out(compiler, Mode::ToolRustc).join(target.triple).join("doc"), @@ -852,6 +840,8 @@ macro_rules! tool_doc { cargo.rustdocflag("--show-type-layout"); cargo.rustdocflag("--generate-link-to-definition"); cargo.rustdocflag("-Zunstable-options"); + + let _guard = builder.msg_doc(compiler, stringify!($tool).to_lowercase(), target); builder.run(&mut cargo.into()); } } @@ -1073,7 +1063,16 @@ impl Step for RustcBook { // config.toml), then this needs to explicitly update the dylib search // path. builder.add_rustc_lib_path(self.compiler, &mut cmd); + let doc_generator_guard = builder.msg( + Kind::Run, + self.compiler.stage, + "lint-docs", + self.compiler.host, + self.target, + ); builder.run(&mut cmd); + drop(doc_generator_guard); + // Run rustbook/mdbook to generate the HTML pages. builder.ensure(RustbookSrc { target: self.target, diff --git a/src/bootstrap/download.rs b/src/bootstrap/download.rs index cb40521dda7..1316461fde0 100644 --- a/src/bootstrap/download.rs +++ b/src/bootstrap/download.rs @@ -7,7 +7,7 @@ use std::{ process::{Command, Stdio}, }; -use build_helper::util::try_run; +use build_helper::ci::CiEnv; use once_cell::sync::OnceCell; use xz2::bufread::XzDecoder; @@ -21,6 +21,12 @@ use crate::{ static SHOULD_FIX_BINS_AND_DYLIBS: OnceCell<bool> = OnceCell::new(); +/// `Config::try_run` wrapper for this module to avoid warnings on `try_run`, since we don't have access to a `builder` yet. +fn try_run(config: &Config, cmd: &mut Command) -> Result<(), ()> { + #[allow(deprecated)] + config.try_run(cmd) +} + /// Generic helpers that are useful anywhere in bootstrap. impl Config { pub fn is_verbose(&self) -> bool { @@ -52,17 +58,6 @@ impl Config { } /// Runs a command, printing out nice contextual information if it fails. - /// Exits if the command failed to execute at all, otherwise returns its - /// `status.success()`. - pub(crate) fn try_run(&self, cmd: &mut Command) -> Result<(), ()> { - if self.dry_run() { - return Ok(()); - } - self.verbose(&format!("running: {:?}", cmd)); - try_run(cmd, self.is_verbose()) - } - - /// Runs a command, printing out nice contextual information if it fails. /// Returns false if do not execute at all, otherwise returns its /// `status.success()`. pub(crate) fn check_run(&self, cmd: &mut Command) -> bool { @@ -156,14 +151,16 @@ impl Config { ]; } "; - nix_build_succeeded = self - .try_run(Command::new("nix-build").args(&[ + nix_build_succeeded = try_run( + self, + Command::new("nix-build").args(&[ Path::new("-E"), Path::new(NIX_EXPR), Path::new("-o"), &nix_deps_dir, - ])) - .is_ok(); + ]), + ) + .is_ok(); nix_deps_dir }); if !nix_build_succeeded { @@ -188,7 +185,7 @@ impl Config { patchelf.args(&["--set-interpreter", dynamic_linker.trim_end()]); } - self.try_run(patchelf.arg(fname)).unwrap(); + let _ = try_run(self, patchelf.arg(fname)); } fn download_file(&self, url: &str, dest_path: &Path, help_on_error: &str) { @@ -213,7 +210,6 @@ impl Config { // Try curl. If that fails and we are on windows, fallback to PowerShell. let mut curl = Command::new("curl"); curl.args(&[ - "-#", "-y", "30", "-Y", @@ -224,6 +220,12 @@ impl Config { "3", "-SRf", ]); + // Don't print progress in CI; the \r wrapping looks bad and downloads don't take long enough for progress to be useful. + if CiEnv::is_ci() { + curl.arg("-s"); + } else { + curl.arg("--progress-bar"); + } curl.arg(url); let f = File::create(tempfile).unwrap(); curl.stdout(Stdio::from(f)); @@ -231,7 +233,7 @@ impl Config { if self.build.contains("windows-msvc") { eprintln!("Fallback to PowerShell"); for _ in 0..3 { - if self.try_run(Command::new("PowerShell.exe").args(&[ + if try_run(self, Command::new("PowerShell.exe").args(&[ "/nologo", "-Command", "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12;", @@ -248,7 +250,7 @@ impl Config { if !help_on_error.is_empty() { eprintln!("{}", help_on_error); } - crate::detail_exit_macro!(1); + crate::exit!(1); } } @@ -402,7 +404,11 @@ impl Config { fn ci_component_contents(&self, stamp_file: &str) -> Vec<String> { assert!(self.download_rustc()); - let ci_rustc_dir = self.out.join(&*self.build.triple).join("ci-rustc"); + if self.dry_run() { + return vec![]; + } + + let ci_rustc_dir = self.ci_rustc_dir(); let stamp_file = ci_rustc_dir.join(stamp_file); let contents_file = t!(File::open(&stamp_file), stamp_file.display().to_string()); t!(BufReader::new(contents_file).lines().collect()) @@ -419,7 +425,7 @@ impl Config { self.download_toolchain( &version, "ci-rustc", - commit, + &format!("{commit}-{}", self.llvm_assertions), &extra_components, Self::download_ci_component, ); @@ -495,8 +501,15 @@ impl Config { /// Download a single component of a CI-built toolchain (not necessarily a published nightly). // NOTE: intentionally takes an owned string to avoid downloading multiple times by accident - fn download_ci_component(&self, filename: String, prefix: &str, commit: &str) { - Self::download_component(self, DownloadSource::CI, filename, prefix, commit, "ci-rustc") + fn download_ci_component(&self, filename: String, prefix: &str, commit_with_assertions: &str) { + Self::download_component( + self, + DownloadSource::CI, + filename, + prefix, + commit_with_assertions, + "ci-rustc", + ) } fn download_component( @@ -516,11 +529,18 @@ impl Config { let bin_root = self.out.join(self.build.triple).join(destination); let tarball = cache_dir.join(&filename); let (base_url, url, should_verify) = match mode { - DownloadSource::CI => ( - self.stage0_metadata.config.artifacts_server.clone(), - format!("{key}/{filename}"), - false, - ), + DownloadSource::CI => { + let dist_server = if self.llvm_assertions { + self.stage0_metadata.config.artifacts_with_llvm_assertions_server.clone() + } else { + self.stage0_metadata.config.artifacts_server.clone() + }; + let url = format!( + "{}/{filename}", + key.strip_suffix(&format!("-{}", self.llvm_assertions)).unwrap() + ); + (dist_server, url, false) + } DownloadSource::Dist => { let dist_server = env::var("RUSTUP_DIST_SERVER") .unwrap_or(self.stage0_metadata.config.dist_server.to_string()); diff --git a/src/bootstrap/flags.rs b/src/bootstrap/flags.rs index a882336c3c4..d67aafff841 100644 --- a/src/bootstrap/flags.rs +++ b/src/bootstrap/flags.rs @@ -193,7 +193,7 @@ impl Flags { } else { panic!("No paths available for subcommand `{}`", subcommand.as_str()); } - crate::detail_exit_macro!(0); + crate::exit!(0); } Flags::parse_from(it) @@ -538,7 +538,7 @@ pub fn get_completion<G: clap_complete::Generator>(shell: G, path: &Path) -> Opt } else { std::fs::read_to_string(path).unwrap_or_else(|_| { eprintln!("couldn't read {}", path.display()); - crate::detail_exit_macro!(1) + crate::exit!(1) }) }; let mut buf = Vec::new(); diff --git a/src/bootstrap/format.rs b/src/bootstrap/format.rs index ebf068b2cb1..cfc9c4de60f 100644 --- a/src/bootstrap/format.rs +++ b/src/bootstrap/format.rs @@ -40,7 +40,7 @@ fn rustfmt(src: &Path, rustfmt: &Path, paths: &[PathBuf], check: bool) -> impl F code, run `./x.py fmt` instead.", cmd_debug, ); - crate::detail_exit_macro!(1); + crate::exit!(1); } true } @@ -66,13 +66,17 @@ fn get_rustfmt_version(build: &Builder<'_>) -> Option<(String, PathBuf)> { /// Return whether the format cache can be reused. fn verify_rustfmt_version(build: &Builder<'_>) -> bool { - let Some((version, stamp_file)) = get_rustfmt_version(build) else {return false;}; + let Some((version, stamp_file)) = get_rustfmt_version(build) else { + return false; + }; !program_out_of_date(&stamp_file, &version) } /// Updates the last rustfmt version used fn update_rustfmt_version(build: &Builder<'_>) { - let Some((version, stamp_file)) = get_rustfmt_version(build) else {return;}; + let Some((version, stamp_file)) = get_rustfmt_version(build) else { + return; + }; t!(std::fs::write(stamp_file, version)) } @@ -196,7 +200,7 @@ pub fn format(build: &Builder<'_>, check: bool, paths: &[PathBuf]) { let rustfmt_path = build.initial_rustfmt().unwrap_or_else(|| { eprintln!("./x.py fmt is not supported on this channel"); - crate::detail_exit_macro!(1); + crate::exit!(1); }); assert!(rustfmt_path.exists(), "{}", rustfmt_path.display()); let src = build.src.clone(); diff --git a/src/bootstrap/lib.rs b/src/bootstrap/lib.rs index 0a7aff62257..de43a401926 100644 --- a/src/bootstrap/lib.rs +++ b/src/bootstrap/lib.rs @@ -27,7 +27,7 @@ use std::process::{Command, Stdio}; use std::str; use build_helper::ci::{gha, CiEnv}; -use build_helper::detail_exit_macro; +use build_helper::exit; use channel::GitInfo; use config::{DryRun, Target}; use filetime::FileTime; @@ -191,7 +191,7 @@ pub enum GitRepo { /// although most functions are implemented as free functions rather than /// methods specifically on this structure itself (to make it easier to /// organize). -#[cfg_attr(not(feature = "build-metrics"), derive(Clone))] +#[derive(Clone)] pub struct Build { /// User-specified configuration from `config.toml`. config: Config, @@ -333,7 +333,6 @@ forward! { create(path: &Path, s: &str), remove(f: &Path), tempdir() -> PathBuf, - try_run(cmd: &mut Command) -> Result<(), ()>, llvm_link_shared() -> bool, download_rustc() -> bool, initial_rustfmt() -> Option<PathBuf>, @@ -617,7 +616,9 @@ impl Build { } // Save any local changes, but avoid running `git stash pop` if there are none (since it will exit with an error). + #[allow(deprecated)] // diff-index reports the modifications through the exit status let has_local_modifications = self + .config .try_run( Command::new("git") .args(&["diff-index", "--quiet", "HEAD"]) @@ -711,7 +712,7 @@ impl Build { for failure in failures.iter() { eprintln!(" - {}\n", failure); } - detail_exit_macro!(1); + exit!(1); } #[cfg(feature = "build-metrics")] @@ -822,11 +823,6 @@ impl Build { self.stage_out(compiler, mode).join(&*target.triple).join(self.cargo_dir()) } - /// Directory where the extracted `rustc-dev` component is stored. - fn ci_rustc_dir(&self, target: TargetSelection) -> PathBuf { - self.out.join(&*target.triple).join("ci-rustc") - } - /// Root output directory for LLVM compiled for `target` /// /// Note that if LLVM is configured externally then the directory returned @@ -976,12 +972,36 @@ impl Build { /// Runs a command, printing out nice contextual information if it fails. /// Exits if the command failed to execute at all, otherwise returns its /// `status.success()`. - fn try_run_quiet(&self, cmd: &mut Command) -> bool { + fn run_quiet_delaying_failure(&self, cmd: &mut Command) -> bool { if self.config.dry_run() { return true; } - self.verbose(&format!("running: {:?}", cmd)); - try_run_suppressed(cmd) + if !self.fail_fast { + self.verbose(&format!("running: {:?}", cmd)); + if !try_run_suppressed(cmd) { + let mut failures = self.delayed_failures.borrow_mut(); + failures.push(format!("{:?}", cmd)); + return false; + } + } else { + self.run_quiet(cmd); + } + true + } + + /// Runs a command, printing out contextual info if it fails, and delaying errors until the build finishes. + pub(crate) fn run_delaying_failure(&self, cmd: &mut Command) -> bool { + if !self.fail_fast { + #[allow(deprecated)] // can't use Build::try_run, that's us + if self.config.try_run(cmd).is_err() { + let mut failures = self.delayed_failures.borrow_mut(); + failures.push(format!("{:?}", cmd)); + return false; + } + } else { + self.run(cmd); + } + true } pub fn is_verbose_than(&self, level: usize) -> bool { @@ -1004,6 +1024,8 @@ impl Build { } } + #[must_use = "Groups should not be dropped until the Step finishes running"] + #[track_caller] fn msg_check( &self, what: impl Display, @@ -1012,6 +1034,8 @@ impl Build { self.msg(Kind::Check, self.config.stage, what, self.config.build, target) } + #[must_use = "Groups should not be dropped until the Step finishes running"] + #[track_caller] fn msg_doc( &self, compiler: Compiler, @@ -1021,6 +1045,8 @@ impl Build { self.msg(Kind::Doc, compiler.stage, what, compiler.host, target.into()) } + #[must_use = "Groups should not be dropped until the Step finishes running"] + #[track_caller] fn msg_build( &self, compiler: Compiler, @@ -1033,6 +1059,8 @@ impl Build { /// Return a `Group` guard for a [`Step`] that is built for each `--stage`. /// /// [`Step`]: crate::builder::Step + #[must_use = "Groups should not be dropped until the Step finishes running"] + #[track_caller] fn msg( &self, action: impl Into<Kind>, @@ -1059,6 +1087,8 @@ impl Build { /// Return a `Group` guard for a [`Step`] that is only built once and isn't affected by `--stage`. /// /// [`Step`]: crate::builder::Step + #[must_use = "Groups should not be dropped until the Step finishes running"] + #[track_caller] fn msg_unstaged( &self, action: impl Into<Kind>, @@ -1070,6 +1100,8 @@ impl Build { self.group(&msg) } + #[must_use = "Groups should not be dropped until the Step finishes running"] + #[track_caller] fn msg_sysroot_tool( &self, action: impl Into<Kind>, @@ -1088,6 +1120,7 @@ impl Build { self.group(&msg) } + #[track_caller] fn group(&self, msg: &str) -> Option<gha::Group> { match self.config.dry_run { DryRun::SelfCheck => None, @@ -1507,6 +1540,7 @@ impl Build { } } } + ret.sort_unstable_by_key(|krate| krate.name); // reproducible order needed for tests ret } @@ -1520,7 +1554,7 @@ impl Build { "Error: Unable to find the stamp file {}, did you try to keep a nonexistent build stage?", stamp.display() ); - crate::detail_exit_macro!(1); + crate::exit!(1); } let mut paths = Vec::new(); @@ -1712,7 +1746,7 @@ Alternatively, set `download-ci-llvm = true` in that `[llvm]` section to download LLVM rather than building it. " ); - detail_exit_macro!(1); + exit!(1); } } diff --git a/src/bootstrap/metrics.rs b/src/bootstrap/metrics.rs index b73df7fe822..cf8d33dfcb0 100644 --- a/src/bootstrap/metrics.rs +++ b/src/bootstrap/metrics.rs @@ -40,6 +40,13 @@ pub(crate) struct BuildMetrics { state: RefCell<MetricsState>, } +/// NOTE: this isn't really cloning anything, but `x suggest` doesn't need metrics so this is probably ok. +impl Clone for BuildMetrics { + fn clone(&self) -> Self { + Self::init() + } +} + impl BuildMetrics { pub(crate) fn init() -> Self { let state = RefCell::new(MetricsState { diff --git a/src/bootstrap/render_tests.rs b/src/bootstrap/render_tests.rs index ccd067053ef..6802bf4511b 100644 --- a/src/bootstrap/render_tests.rs +++ b/src/bootstrap/render_tests.rs @@ -30,7 +30,7 @@ pub(crate) fn try_run_tests(builder: &Builder<'_>, cmd: &mut Command, stream: bo if !run_tests(builder, cmd, stream) { if builder.fail_fast { - crate::detail_exit_macro!(1); + crate::exit!(1); } else { let mut failures = builder.delayed_failures.borrow_mut(); failures.push(format!("{cmd:?}")); diff --git a/src/bootstrap/run.rs b/src/bootstrap/run.rs index c97b7592737..4082f5bb9b1 100644 --- a/src/bootstrap/run.rs +++ b/src/bootstrap/run.rs @@ -24,11 +24,9 @@ impl Step for ExpandYamlAnchors { /// anchors in them, since GitHub Actions doesn't support them. fn run(self, builder: &Builder<'_>) { builder.info("Expanding YAML anchors in the GitHub Actions configuration"); - try_run( - builder, + builder.run_delaying_failure( &mut builder.tool_cmd(Tool::ExpandYamlAnchors).arg("generate").arg(&builder.src), - ) - .unwrap(); + ); } fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { @@ -40,19 +38,6 @@ impl Step for ExpandYamlAnchors { } } -fn try_run(builder: &Builder<'_>, cmd: &mut Command) -> Result<(), ()> { - if !builder.fail_fast { - if let Err(e) = builder.try_run(cmd) { - let mut failures = builder.delayed_failures.borrow_mut(); - failures.push(format!("{:?}", cmd)); - return Err(e); - } - } else { - builder.run(cmd); - } - Ok(()) -} - #[derive(Debug, PartialOrd, Ord, Copy, Clone, Hash, PartialEq, Eq)] pub struct BuildManifest; diff --git a/src/bootstrap/sanity.rs b/src/bootstrap/sanity.rs index 8f5ba42736b..9321fc1bcb8 100644 --- a/src/bootstrap/sanity.rs +++ b/src/bootstrap/sanity.rs @@ -104,7 +104,7 @@ You should install cmake, or set `download-ci-llvm = true` in the than building it. " ); - crate::detail_exit_macro!(1); + crate::exit!(1); } } diff --git a/src/bootstrap/setup.rs b/src/bootstrap/setup.rs index 34c6ccf1365..2075c58598d 100644 --- a/src/bootstrap/setup.rs +++ b/src/bootstrap/setup.rs @@ -203,7 +203,7 @@ fn setup_config_toml(path: &PathBuf, profile: Profile, config: &Config) { "note: this will use the configuration in {}", profile.include_path(&config.src).display() ); - crate::detail_exit_macro!(1); + crate::exit!(1); } let settings = format!( @@ -389,7 +389,7 @@ pub fn interactive_path() -> io::Result<Profile> { io::stdin().read_line(&mut input)?; if input.is_empty() { eprintln!("EOF on stdin, when expecting answer to question. Giving up."); - crate::detail_exit_macro!(1); + crate::exit!(1); } break match parse_with_abbrev(&input) { Ok(profile) => profile, diff --git a/src/bootstrap/suggest.rs b/src/bootstrap/suggest.rs index ff20ebec267..f225104bda9 100644 --- a/src/bootstrap/suggest.rs +++ b/src/bootstrap/suggest.rs @@ -4,18 +4,11 @@ use std::str::FromStr; use std::path::PathBuf; -use crate::{ - builder::{Builder, Kind}, - tool::Tool, -}; +use clap::Parser; -#[cfg(feature = "build-metrics")] -pub fn suggest(builder: &Builder<'_>, run: bool) { - panic!("`x suggest` is not supported with `build-metrics`") -} +use crate::{builder::Builder, tool::Tool}; /// Suggests a list of possible `x.py` commands to run based on modified files in branch. -#[cfg(not(feature = "build-metrics"))] pub fn suggest(builder: &Builder<'_>, run: bool) { let suggestions = builder.tool_cmd(Tool::SuggestTests).output().expect("failed to run `suggest-tests` tool"); @@ -67,12 +60,13 @@ pub fn suggest(builder: &Builder<'_>, run: bool) { if run { for sug in suggestions { - let mut build = builder.build.clone(); - - let builder = - Builder::new_standalone(&mut build, Kind::parse(&sug.0).unwrap(), sug.2, sug.1); - - builder.execute_cli() + let mut build: crate::Build = builder.build.clone(); + build.config.paths = sug.2; + build.config.cmd = crate::flags::Flags::parse_from(["x.py", sug.0]).cmd; + if let Some(stage) = sug.1 { + build.config.stage = stage; + } + build.build(); } } else { println!("help: consider using the `--run` flag to automatically run suggested tests"); diff --git a/src/bootstrap/test.rs b/src/bootstrap/test.rs index 0907291b54d..44b8c2d8c01 100644 --- a/src/bootstrap/test.rs +++ b/src/bootstrap/test.rs @@ -48,32 +48,6 @@ const MIR_OPT_BLESS_TARGET_MAPPING: &[(&str, &str)] = &[ // build for, so there is no entry for "aarch64-apple-darwin" here. ]; -fn try_run(builder: &Builder<'_>, cmd: &mut Command) -> Result<(), ()> { - if !builder.fail_fast { - if let Err(e) = builder.try_run(cmd) { - let mut failures = builder.delayed_failures.borrow_mut(); - failures.push(format!("{:?}", cmd)); - return Err(e); - } - } else { - builder.run(cmd); - } - Ok(()) -} - -fn try_run_quiet(builder: &Builder<'_>, cmd: &mut Command) -> bool { - if !builder.fail_fast { - if !builder.try_run_quiet(cmd) { - let mut failures = builder.delayed_failures.borrow_mut(); - failures.push(format!("{:?}", cmd)); - return false; - } - } else { - builder.run_quiet(cmd); - } - true -} - #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub struct CrateBootstrap { path: Interned<PathBuf>, @@ -117,14 +91,8 @@ impl Step for CrateBootstrap { SourceType::InTree, &[], ); - builder.info(&format!( - "{} {} stage0 ({})", - builder.kind.description(), - path, - bootstrap_host, - )); let crate_name = path.rsplit_once('/').unwrap().1; - run_cargo_test(cargo, &[], &[], crate_name, compiler, bootstrap_host, builder); + run_cargo_test(cargo, &[], &[], crate_name, crate_name, compiler, bootstrap_host, builder); } } @@ -163,6 +131,7 @@ You can skip linkcheck with --exclude src/tools/linkchecker" // Test the linkchecker itself. let bootstrap_host = builder.config.build; let compiler = builder.compiler(0, bootstrap_host); + let cargo = tool::prepare_tool_cargo( builder, compiler, @@ -173,7 +142,16 @@ You can skip linkcheck with --exclude src/tools/linkchecker" SourceType::InTree, &[], ); - run_cargo_test(cargo, &[], &[], "linkchecker", compiler, bootstrap_host, builder); + run_cargo_test( + cargo, + &[], + &[], + "linkchecker", + "linkchecker self tests", + compiler, + bootstrap_host, + builder, + ); if builder.doc_tests == DocTests::No { return; @@ -182,13 +160,14 @@ You can skip linkcheck with --exclude src/tools/linkchecker" // Build all the default documentation. builder.default_doc(&[]); + // Build the linkchecker before calling `msg`, since GHA doesn't support nested groups. + let mut linkchecker = builder.tool_cmd(Tool::Linkchecker); + // Run the linkchecker. + let _guard = + builder.msg(Kind::Test, compiler.stage, "Linkcheck", bootstrap_host, bootstrap_host); let _time = util::timeit(&builder); - try_run( - builder, - builder.tool_cmd(Tool::Linkchecker).arg(builder.out.join(host.triple).join("doc")), - ) - .unwrap(); + builder.run_delaying_failure(linkchecker.arg(builder.out.join(host.triple).join("doc"))); } fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { @@ -241,8 +220,9 @@ impl Step for HtmlCheck { builder.default_doc(&[]); builder.ensure(crate::doc::Rustc::new(builder.top_stage, self.target, builder)); - try_run(builder, builder.tool_cmd(Tool::HtmlChecker).arg(builder.doc_out(self.target))) - .unwrap(); + builder.run_delaying_failure( + builder.tool_cmd(Tool::HtmlChecker).arg(builder.doc_out(self.target)), + ); } } @@ -281,15 +261,13 @@ impl Step for Cargotest { let _time = util::timeit(&builder); let mut cmd = builder.tool_cmd(Tool::CargoTest); - try_run( - builder, + builder.run_delaying_failure( cmd.arg(&cargo) .arg(&out_dir) .args(builder.config.test_args()) .env("RUSTC", builder.rustc(compiler)) .env("RUSTDOC", builder.rustdoc(compiler)), - ) - .unwrap(); + ); } } @@ -409,7 +387,7 @@ impl Step for RustAnalyzer { cargo.env("SKIP_SLOW_TESTS", "1"); cargo.add_rustc_lib_path(builder, compiler); - run_cargo_test(cargo, &[], &[], "rust-analyzer", compiler, host, builder); + run_cargo_test(cargo, &[], &[], "rust-analyzer", "rust-analyzer", compiler, host, builder); } } @@ -458,7 +436,7 @@ impl Step for Rustfmt { cargo.add_rustc_lib_path(builder, compiler); - run_cargo_test(cargo, &[], &[], "rustfmt", compiler, host, builder); + run_cargo_test(cargo, &[], &[], "rustfmt", "rustfmt", compiler, host, builder); } } @@ -506,7 +484,16 @@ impl Step for RustDemangler { cargo.env("RUST_DEMANGLER_DRIVER_PATH", rust_demangler); cargo.add_rustc_lib_path(builder, compiler); - run_cargo_test(cargo, &[], &[], "rust-demangler", compiler, host, builder); + run_cargo_test( + cargo, + &[], + &[], + "rust-demangler", + "rust-demangler", + compiler, + host, + builder, + ); } } @@ -550,6 +537,13 @@ impl Miri { cargo.env("RUST_BACKTRACE", "1"); let mut cargo = Command::from(cargo); + let _guard = builder.msg( + Kind::Build, + compiler.stage + 1, + "miri sysroot", + compiler.host, + compiler.host, + ); builder.run(&mut cargo); // # Determine where Miri put its sysroot. @@ -627,6 +621,8 @@ impl Step for Miri { SourceType::InTree, &[], ); + let _guard = builder.msg_sysroot_tool(Kind::Test, compiler.stage, "miri", host, host); + cargo.add_rustc_lib_path(builder, compiler); // miri tests need to know about the stage sysroot @@ -739,7 +735,16 @@ impl Step for CompiletestTest { &[], ); cargo.allow_features("test"); - run_cargo_test(cargo, &[], &[], "compiletest", compiler, host, builder); + run_cargo_test( + cargo, + &[], + &[], + "compiletest", + "compiletest self test", + compiler, + host, + builder, + ); } } @@ -795,13 +800,16 @@ impl Step for Clippy { cargo.env("BLESS", "Gesundheit"); } - if builder.try_run(&mut cargo).is_ok() { + let _guard = builder.msg_sysroot_tool(Kind::Test, compiler.stage, "clippy", host, host); + + #[allow(deprecated)] // Clippy reports errors if it blessed the outputs + if builder.config.try_run(&mut cargo).is_ok() { // The tests succeeded; nothing to do. return; } if !builder.config.cmd.bless() { - crate::detail_exit_macro!(1); + crate::exit!(1); } } } @@ -855,7 +863,7 @@ impl Step for RustdocTheme { util::lld_flag_no_threads(self.compiler.host.contains("windows")), ); } - try_run(builder, &mut cmd).unwrap(); + builder.run_delaying_failure(&mut cmd); } } @@ -870,7 +878,8 @@ impl Step for RustdocJSStd { const ONLY_HOSTS: bool = true; fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { - run.suite_path("tests/rustdoc-js-std") + let default = run.builder.config.nodejs.is_some(); + run.suite_path("tests/rustdoc-js-std").default_condition(default) } fn make_run(run: RunConfig<'_>) { @@ -878,38 +887,42 @@ impl Step for RustdocJSStd { } fn run(self, builder: &Builder<'_>) { - if let Some(ref nodejs) = builder.config.nodejs { - let mut command = Command::new(nodejs); - command - .arg(builder.src.join("src/tools/rustdoc-js/tester.js")) - .arg("--crate-name") - .arg("std") - .arg("--resource-suffix") - .arg(&builder.version) - .arg("--doc-folder") - .arg(builder.doc_out(self.target)) - .arg("--test-folder") - .arg(builder.src.join("tests/rustdoc-js-std")); - for path in &builder.paths { - if let Some(p) = - util::is_valid_test_suite_arg(path, "tests/rustdoc-js-std", builder) - { - if !p.ends_with(".js") { - eprintln!("A non-js file was given: `{}`", path.display()); - panic!("Cannot run rustdoc-js-std tests"); - } - command.arg("--test-file").arg(path); + let nodejs = + builder.config.nodejs.as_ref().expect("need nodejs to run rustdoc-js-std tests"); + let mut command = Command::new(nodejs); + command + .arg(builder.src.join("src/tools/rustdoc-js/tester.js")) + .arg("--crate-name") + .arg("std") + .arg("--resource-suffix") + .arg(&builder.version) + .arg("--doc-folder") + .arg(builder.doc_out(self.target)) + .arg("--test-folder") + .arg(builder.src.join("tests/rustdoc-js-std")); + for path in &builder.paths { + if let Some(p) = util::is_valid_test_suite_arg(path, "tests/rustdoc-js-std", builder) { + if !p.ends_with(".js") { + eprintln!("A non-js file was given: `{}`", path.display()); + panic!("Cannot run rustdoc-js-std tests"); } + command.arg("--test-file").arg(path); } - builder.ensure(crate::doc::Std::new( - builder.top_stage, - self.target, - DocumentationFormat::HTML, - )); - builder.run(&mut command); - } else { - builder.info("No nodejs found, skipping \"tests/rustdoc-js-std\" tests"); } + builder.ensure(crate::doc::Std::new( + builder.top_stage, + self.target, + builder, + DocumentationFormat::HTML, + )); + let _guard = builder.msg( + Kind::Test, + builder.top_stage, + "rustdoc-js-std", + builder.config.build, + self.target, + ); + builder.run(&mut command); } } @@ -925,7 +938,8 @@ impl Step for RustdocJSNotStd { const ONLY_HOSTS: bool = true; fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { - run.suite_path("tests/rustdoc-js") + let default = run.builder.config.nodejs.is_some(); + run.suite_path("tests/rustdoc-js").default_condition(default) } fn make_run(run: RunConfig<'_>) { @@ -934,18 +948,14 @@ impl Step for RustdocJSNotStd { } fn run(self, builder: &Builder<'_>) { - if builder.config.nodejs.is_some() { - builder.ensure(Compiletest { - compiler: self.compiler, - target: self.target, - mode: "js-doc-test", - suite: "rustdoc-js", - path: "tests/rustdoc-js", - compare_mode: None, - }); - } else { - builder.info("No nodejs found, skipping \"tests/rustdoc-js\" tests"); - } + builder.ensure(Compiletest { + compiler: self.compiler, + target: self.target, + mode: "js-doc-test", + suite: "rustdoc-js", + path: "tests/rustdoc-js", + compare_mode: None, + }); } } @@ -1050,6 +1060,13 @@ impl Step for RustdocGUI { } let _time = util::timeit(&builder); + let _guard = builder.msg_sysroot_tool( + Kind::Test, + self.compiler.stage, + "rustdoc-gui", + self.compiler.host, + self.target, + ); crate::render_tests::try_run_tests(builder, &mut cmd, true); } } @@ -1100,13 +1117,13 @@ help: to skip test's attempt to check tidiness, pass `--exclude src/tools/tidy` PATH = inferred_rustfmt_dir.display(), CHAN = builder.config.channel, ); - crate::detail_exit_macro!(1); + crate::exit!(1); } crate::format::format(&builder, !builder.config.cmd.bless(), &[]); } builder.info("tidy check"); - try_run(builder, &mut cmd).unwrap(); + builder.run_delaying_failure(&mut cmd); builder.ensure(ExpandYamlAnchors); @@ -1123,7 +1140,7 @@ help: to skip test's attempt to check tidiness, pass `--exclude src/tools/tidy` eprintln!( "x.py completions were changed; run `x.py run generate-completions` to update them" ); - crate::detail_exit_macro!(1); + crate::exit!(1); } } } @@ -1151,11 +1168,9 @@ impl Step for ExpandYamlAnchors { /// by the user before committing CI changes. fn run(self, builder: &Builder<'_>) { builder.info("Ensuring the YAML anchors in the GitHub Actions config were expanded"); - try_run( - builder, + builder.run_delaying_failure( &mut builder.tool_cmd(Tool::ExpandYamlAnchors).arg("check").arg(&builder.src), - ) - .unwrap(); + ); } fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { @@ -1435,7 +1450,7 @@ help: to test the compiler, use `--stage 1` instead help: to test the standard library, use `--stage 0 library/std` instead note: if you're sure you want to do this, please open an issue as to why. In the meantime, you can override this with `COMPILETEST_FORCE_STAGE0=1`." ); - crate::detail_exit_macro!(1); + crate::exit!(1); } let mut compiler = self.compiler; @@ -1572,6 +1587,8 @@ note: if you're sure you want to do this, please open an issue as to why. In the if let Some(ref nodejs) = builder.config.nodejs { cmd.arg("--nodejs").arg(nodejs); + } else if mode == "js-doc-test" { + panic!("need nodejs to run js-doc-test suite"); } if let Some(ref npm) = builder.config.npm { cmd.arg("--npm").arg(npm); @@ -1893,14 +1910,6 @@ impl Step for BookTest { /// /// This uses the `rustdoc` that sits next to `compiler`. fn run(self, builder: &Builder<'_>) { - let host = self.compiler.host; - let _guard = builder.msg( - Kind::Test, - self.compiler.stage, - &format!("book {}", self.name), - host, - host, - ); // External docs are different from local because: // - Some books need pre-processing by mdbook before being tested. // - They need to save their state to toolstate. @@ -1943,12 +1952,12 @@ impl BookTest { let _guard = builder.msg( Kind::Test, compiler.stage, - format_args!("rustbook {}", self.path.display()), + format_args!("mdbook {}", self.path.display()), compiler.host, compiler.host, ); let _time = util::timeit(&builder); - let toolstate = if try_run(builder, &mut rustbook_cmd).is_ok() { + let toolstate = if builder.run_delaying_failure(&mut rustbook_cmd) { ToolState::TestPass } else { ToolState::TestFail @@ -1959,8 +1968,12 @@ impl BookTest { /// This runs `rustdoc --test` on all `.md` files in the path. fn run_local_doc(self, builder: &Builder<'_>) { let compiler = self.compiler; + let host = self.compiler.host; - builder.ensure(compile::Std::new(compiler, compiler.host)); + builder.ensure(compile::Std::new(compiler, host)); + + let _guard = + builder.msg(Kind::Test, compiler.stage, &format!("book {}", self.name), host, host); // Do a breadth-first traversal of the `src/doc` directory and just run // tests for all files that end in `*.md` @@ -2106,9 +2119,9 @@ fn markdown_test(builder: &Builder<'_>, compiler: Compiler, markdown: &Path) -> cmd.arg("--test-args").arg(test_args); if builder.config.verbose_tests { - try_run(builder, &mut cmd).is_ok() + builder.run_delaying_failure(&mut cmd) } else { - try_run_quiet(builder, &mut cmd) + builder.run_quiet_delaying_failure(&mut cmd) } } @@ -2134,7 +2147,7 @@ impl Step for RustcGuide { let src = builder.src.join(relative_path); let mut rustbook_cmd = builder.tool_cmd(Tool::Rustbook); - let toolstate = if try_run(builder, rustbook_cmd.arg("linkcheck").arg(&src)).is_ok() { + let toolstate = if builder.run_delaying_failure(rustbook_cmd.arg("linkcheck").arg(&src)) { ToolState::TestPass } else { ToolState::TestFail @@ -2185,11 +2198,12 @@ impl Step for CrateLibrustc { /// Given a `cargo test` subcommand, add the appropriate flags and run it. /// /// Returns whether the test succeeded. -fn run_cargo_test( +fn run_cargo_test<'a>( cargo: impl Into<Command>, libtest_args: &[&str], crates: &[Interned<String>], primary_crate: &str, + description: impl Into<Option<&'a str>>, compiler: Compiler, target: TargetSelection, builder: &Builder<'_>, @@ -2197,6 +2211,9 @@ fn run_cargo_test( let mut cargo = prepare_cargo_test(cargo, libtest_args, crates, primary_crate, compiler, target, builder); let _time = util::timeit(&builder); + let _group = description.into().and_then(|what| { + builder.msg_sysroot_tool(Kind::Test, compiler.stage, what, compiler.host, target) + }); #[cfg(feature = "build-metrics")] builder.metrics.begin_test_suite( @@ -2348,7 +2365,7 @@ impl Step for Crate { // `std_cargo` actually does the wrong thing: it passes `--sysroot build/host/stage2`, // but we want to use the force-recompile std we just built in `build/host/stage2-test-sysroot`. // Override it. - if builder.download_rustc() { + if builder.download_rustc() && compiler.stage > 0 { let sysroot = builder .out .join(compiler.host.triple) @@ -2362,14 +2379,16 @@ impl Step for Crate { _ => panic!("can only test libraries"), }; - let _guard = builder.msg( - builder.kind, - compiler.stage, - crate_description(&self.crates), - compiler.host, + run_cargo_test( + cargo, + &[], + &self.crates, + &self.crates[0], + &*crate_description(&self.crates), + compiler, target, + builder, ); - run_cargo_test(cargo, &[], &self.crates, &self.crates[0], compiler, target, builder); } } @@ -2462,18 +2481,12 @@ impl Step for CrateRustdoc { dylib_path.insert(0, PathBuf::from(&*libdir)); cargo.env(dylib_path_var(), env::join_paths(&dylib_path).unwrap()); - let _guard = builder.msg_sysroot_tool( - builder.kind, - compiler.stage, - "rustdoc", - compiler.host, - target, - ); run_cargo_test( cargo, &[], &[INTERNER.intern_str("rustdoc:0.0.0")], "rustdoc", + "rustdoc", compiler, target, builder, @@ -2529,13 +2542,12 @@ impl Step for CrateRustdocJsonTypes { &[] }; - let _guard = - builder.msg(builder.kind, compiler.stage, "rustdoc-json-types", compiler.host, target); run_cargo_test( cargo, libtest_args, &[INTERNER.intern_str("rustdoc-json-types")], "rustdoc-json-types", + "rustdoc-json-types", compiler, target, builder, @@ -2676,6 +2688,10 @@ impl Step for Bootstrap { /// Tests the build system itself. fn run(self, builder: &Builder<'_>) { + let host = builder.config.build; + let compiler = builder.compiler(0, host); + let _guard = builder.msg(Kind::Test, 0, "bootstrap", host, host); + let mut check_bootstrap = Command::new(&builder.python()); check_bootstrap .args(["-m", "unittest", "bootstrap_test.py"]) @@ -2684,10 +2700,8 @@ impl Step for Bootstrap { .current_dir(builder.src.join("src/bootstrap/")); // NOTE: we intentionally don't pass test_args here because the args for unittest and cargo test are mutually incompatible. // Use `python -m unittest` manually if you want to pass arguments. - try_run(builder, &mut check_bootstrap).unwrap(); + builder.run_delaying_failure(&mut check_bootstrap); - let host = builder.config.build; - let compiler = builder.compiler(0, host); let mut cmd = Command::new(&builder.initial_cargo); cmd.arg("test") .current_dir(builder.src.join("src/bootstrap")) @@ -2704,7 +2718,7 @@ impl Step for Bootstrap { } // rustbuild tests are racy on directory creation so just run them one at a time. // Since there's not many this shouldn't be a problem. - run_cargo_test(cmd, &["--test-threads=1"], &[], "bootstrap", compiler, host, builder); + run_cargo_test(cmd, &["--test-threads=1"], &[], "bootstrap", None, compiler, host, builder); } fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { @@ -2755,8 +2769,14 @@ impl Step for TierCheck { cargo.arg("--verbose"); } - builder.info("platform support check"); - try_run(builder, &mut cargo.into()).unwrap(); + let _guard = builder.msg( + Kind::Test, + self.compiler.stage, + "platform support check", + self.compiler.host, + self.compiler.host, + ); + builder.run_delaying_failure(&mut cargo.into()); } } @@ -2803,8 +2823,6 @@ impl Step for RustInstaller { /// Ensure the version placeholder replacement tool builds fn run(self, builder: &Builder<'_>) { - builder.info("test rust-installer"); - let bootstrap_host = builder.config.build; let compiler = builder.compiler(0, bootstrap_host); let cargo = tool::prepare_tool_cargo( @@ -2817,7 +2835,15 @@ impl Step for RustInstaller { SourceType::InTree, &[], ); - run_cargo_test(cargo, &[], &[], "installer", compiler, bootstrap_host, builder); + + let _guard = builder.msg( + Kind::Test, + compiler.stage, + "rust-installer", + bootstrap_host, + bootstrap_host, + ); + run_cargo_test(cargo, &[], &[], "installer", None, compiler, bootstrap_host, builder); // We currently don't support running the test.sh script outside linux(?) environments. // Eventually this should likely migrate to #[test]s in rust-installer proper rather than a @@ -2836,7 +2862,7 @@ impl Step for RustInstaller { cmd.env("CARGO", &builder.initial_cargo); cmd.env("RUSTC", &builder.initial_rustc); cmd.env("TMP_DIR", &tmpdir); - try_run(builder, &mut cmd).unwrap(); + builder.run_delaying_failure(&mut cmd); } fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { diff --git a/src/bootstrap/tool.rs b/src/bootstrap/tool.rs index 915dceae389..725f864b718 100644 --- a/src/bootstrap/tool.rs +++ b/src/bootstrap/tool.rs @@ -34,6 +34,7 @@ struct ToolBuild { } impl Builder<'_> { + #[track_caller] fn msg_tool( &self, mode: Mode, @@ -107,7 +108,8 @@ impl Step for ToolBuild { ); let mut cargo = Command::from(cargo); - let is_expected = builder.try_run(&mut cargo).is_ok(); + #[allow(deprecated)] // we check this in `is_optional_tool` in a second + let is_expected = builder.config.try_run(&mut cargo).is_ok(); builder.save_toolstate( tool, @@ -116,7 +118,7 @@ impl Step for ToolBuild { if !is_expected { if !is_optional_tool { - crate::detail_exit_macro!(1); + crate::exit!(1); } else { None } diff --git a/src/bootstrap/toolstate.rs b/src/bootstrap/toolstate.rs index 9c4d0ea265d..eb65c8bee09 100644 --- a/src/bootstrap/toolstate.rs +++ b/src/bootstrap/toolstate.rs @@ -91,7 +91,7 @@ fn print_error(tool: &str, submodule: &str) { eprintln!("If you do NOT intend to update '{}', please ensure you did not accidentally", tool); eprintln!("change the submodule at '{}'. You may ask your reviewer for the", submodule); eprintln!("proper steps."); - crate::detail_exit_macro!(3); + crate::exit!(3); } fn check_changed_files(toolstates: &HashMap<Box<str>, ToolState>) { @@ -106,7 +106,7 @@ fn check_changed_files(toolstates: &HashMap<Box<str>, ToolState>) { Ok(o) => o, Err(e) => { eprintln!("Failed to get changed files: {:?}", e); - crate::detail_exit_macro!(1); + crate::exit!(1); } }; @@ -177,7 +177,7 @@ impl Step for ToolStateCheck { } if did_error { - crate::detail_exit_macro!(1); + crate::exit!(1); } check_changed_files(&toolstates); @@ -223,7 +223,7 @@ impl Step for ToolStateCheck { } if did_error { - crate::detail_exit_macro!(1); + crate::exit!(1); } if builder.config.channel == "nightly" && env::var_os("TOOLSTATE_PUBLISH").is_some() { @@ -262,6 +262,8 @@ impl Builder<'_> { /// `rust.save-toolstates` in `config.toml`. If unspecified, nothing will be /// done. The file is updated immediately after this function completes. pub fn save_toolstate(&self, tool: &str, state: ToolState) { + use std::io::Write; + // If we're in a dry run setting we don't want to save toolstates as // that means if we e.g. panic down the line it'll look like we tested // everything (but we actually haven't). @@ -286,7 +288,8 @@ impl Builder<'_> { current_toolstates.insert(tool.into(), state); t!(file.seek(SeekFrom::Start(0))); t!(file.set_len(0)); - t!(serde_json::to_writer(file, ¤t_toolstates)); + t!(serde_json::to_writer(&file, ¤t_toolstates)); + t!(writeln!(file)); // make sure this ends in a newline } } } diff --git a/src/bootstrap/util.rs b/src/bootstrap/util.rs index b291584b300..2725813aba3 100644 --- a/src/bootstrap/util.rs +++ b/src/bootstrap/util.rs @@ -153,16 +153,6 @@ pub fn symlink_dir(config: &Config, original: &Path, link: &Path) -> io::Result< } } -/// The CI environment rustbuild is running in. This mainly affects how the logs -/// are printed. -#[derive(Copy, Clone, PartialEq, Eq, Debug)] -pub enum CiEnv { - /// Not a CI environment. - None, - /// The GitHub Actions environment, for Linux (including Docker), Windows and macOS builds. - GitHubActions, -} - pub fn forcing_clang_based_tests() -> bool { if let Some(var) = env::var_os("RUSTBUILD_FORCE_CLANG_BASED_TESTS") { match &var.to_string_lossy().to_lowercase()[..] { @@ -229,7 +219,7 @@ pub fn is_valid_test_suite_arg<'a, P: AsRef<Path>>( pub fn run(cmd: &mut Command, print_cmd_on_fail: bool) { if try_run(cmd, print_cmd_on_fail).is_err() { - crate::detail_exit_macro!(1); + crate::exit!(1); } } @@ -253,7 +243,7 @@ pub fn check_run(cmd: &mut Command, print_cmd_on_fail: bool) -> bool { pub fn run_suppressed(cmd: &mut Command) { if !try_run_suppressed(cmd) { - crate::detail_exit_macro!(1); + crate::exit!(1); } } diff --git a/src/ci/docker/run.sh b/src/ci/docker/run.sh index 4b218d57727..da9d68672c4 100755 --- a/src/ci/docker/run.sh +++ b/src/ci/docker/run.sh @@ -79,7 +79,7 @@ if [ -f "$docker_dir/$image/Dockerfile" ]; then loaded_images=$(/usr/bin/timeout -k 720 600 docker load -i /tmp/rustci_docker_cache \ | sed 's/.* sha/sha/') set -e - echo "Downloaded containers:\n$loaded_images" + printf "Downloaded containers:\n$loaded_images\n" fi dockerfile="$docker_dir/$image/Dockerfile" @@ -89,12 +89,14 @@ if [ -f "$docker_dir/$image/Dockerfile" ]; then else context="$script_dir" fi + echo "::group::Building docker image for $image" retry docker \ build \ --rm \ -t rust-ci \ -f "$dockerfile" \ "$context" + echo "::endgroup::" if [ "$CI" != "" ]; then s3url="s3://$SCCACHE_BUCKET/docker/$cksum" diff --git a/src/ci/run.sh b/src/ci/run.sh index 48fb40d6a6d..da1960fc057 100755 --- a/src/ci/run.sh +++ b/src/ci/run.sh @@ -154,13 +154,13 @@ fi # check for clock drifts. An HTTP URL is used instead of HTTPS since on Azure # Pipelines it happened that the certificates were marked as expired. datecheck() { - echo "== clock drift check ==" + echo "::group::Clock drift check" echo -n " local time: " date echo -n " network time: " curl -fs --head http://ci-caches.rust-lang.org | grep ^Date: \ | sed 's/Date: //g' || true - echo "== end clock drift check ==" + echo "::endgroup::" } datecheck trap datecheck EXIT @@ -177,6 +177,7 @@ retry make prepare # Display the CPU and memory information. This helps us know why the CI timing # is fluctuating. +echo "::group::Display CPU and Memory information" if isMacOS; then system_profiler SPHardwareDataType || true sysctl hw || true @@ -186,6 +187,7 @@ else cat /proc/meminfo || true ncpus=$(grep processor /proc/cpuinfo | wc -l) fi +echo "::endgroup::" if [ ! -z "$SCRIPT" ]; then echo "Executing ${SCRIPT}" @@ -218,4 +220,6 @@ if [ "$RUN_CHECK_WITH_PARALLEL_QUERIES" != "" ]; then CARGO_INCREMENTAL=0 ../x check fi +echo "::group::sccache stats" sccache --show-stats || true +echo "::endgroup::" diff --git a/src/doc/rustc/src/SUMMARY.md b/src/doc/rustc/src/SUMMARY.md index 4d4dc3f4996..96ee9a586de 100644 --- a/src/doc/rustc/src/SUMMARY.md +++ b/src/doc/rustc/src/SUMMARY.md @@ -36,6 +36,7 @@ - [m68k-unknown-linux-gnu](platform-support/m68k-unknown-linux-gnu.md) - [mips64-openwrt-linux-musl](platform-support/mips64-openwrt-linux-musl.md) - [mipsel-sony-psx](platform-support/mipsel-sony-psx.md) + - [mipsisa\*r6\*-unknown-linux-gnu\*](platform-support/mips-release-6.md) - [nvptx64-nvidia-cuda](platform-support/nvptx64-nvidia-cuda.md) - [riscv32imac-unknown-xous-elf](platform-support/riscv32imac-unknown-xous-elf.md) - [sparc-unknown-none-elf](./platform-support/sparc-unknown-none-elf.md) diff --git a/src/doc/rustc/src/platform-support.md b/src/doc/rustc/src/platform-support.md index 14fe7242ab9..ca8ec76f327 100644 --- a/src/doc/rustc/src/platform-support.md +++ b/src/doc/rustc/src/platform-support.md @@ -278,10 +278,10 @@ target | std | host | notes [`mipsel-sony-psx`](platform-support/mipsel-sony-psx.md) | * | | MIPS (LE) Sony PlayStation 1 (PSX) `mipsel-unknown-linux-uclibc` | ✓ | | MIPS (LE) Linux with uClibc `mipsel-unknown-none` | * | | Bare MIPS (LE) softfloat -`mipsisa32r6-unknown-linux-gnu` | ? | | -`mipsisa32r6el-unknown-linux-gnu` | ? | | -`mipsisa64r6-unknown-linux-gnuabi64` | ? | | -`mipsisa64r6el-unknown-linux-gnuabi64` | ? | | +[`mipsisa32r6-unknown-linux-gnu`](platform-support/mips-release-6.md) | ? | | 32-bit MIPS Release 6 Big Endian +[`mipsisa32r6el-unknown-linux-gnu`](platform-support/mips-release-6.md) | ? | | 32-bit MIPS Release 6 Little Endian +[`mipsisa64r6-unknown-linux-gnuabi64`](platform-support/mips-release-6.md) | ? | | 64-bit MIPS Release 6 Big Endian +[`mipsisa64r6el-unknown-linux-gnuabi64`](platform-support/mips-release-6.md) | ✓ | ✓ | 64-bit MIPS Release 6 Little Endian `msp430-none-elf` | * | | 16-bit MSP430 microcontrollers `powerpc-unknown-linux-gnuspe` | ✓ | | PowerPC SPE Linux `powerpc-unknown-linux-musl` | ? | | @@ -306,7 +306,7 @@ target | std | host | notes `riscv64gc-unknown-freebsd` | | | RISC-V FreeBSD `riscv64gc-unknown-fuchsia` | | | RISC-V Fuchsia `riscv64gc-unknown-linux-musl` | | | RISC-V Linux (kernel 4.20, musl 1.2.0) -[`riscv64gc-unknown-netbsd`](platform-support/netbsd.md) | ✓ | ? | RISC-V NetBSD +[`riscv64gc-unknown-netbsd`](platform-support/netbsd.md) | ✓ | ✓ | RISC-V NetBSD [`riscv64gc-unknown-openbsd`](platform-support/openbsd.md) | ✓ | ✓ | OpenBSD/riscv64 `s390x-unknown-linux-musl` | | | S390x Linux (kernel 3.2, MUSL) `sparc-unknown-linux-gnu` | ✓ | | 32-bit SPARC Linux diff --git a/src/doc/rustc/src/platform-support/mips-release-6.md b/src/doc/rustc/src/platform-support/mips-release-6.md new file mode 100644 index 00000000000..3f1912fc6f9 --- /dev/null +++ b/src/doc/rustc/src/platform-support/mips-release-6.md @@ -0,0 +1,181 @@ +# mipsisa\*r6\*-unknown-linux-gnu\* + +**Tier: 3** + +[MIPS Release 6](https://s3-eu-west-1.amazonaws.com/downloads-mips/documents/MD00083-2B-MIPS64INT-AFP-06.01.pdf), or simply MIPS R6, is the latest iteration of the MIPS instruction set architecture (ISA). + +MIPS R6 is experimental in nature, as there is not yet real hardware. However, Qemu emulation is available and we have two Linux distros maintained for development and evaluation purposes. This documentation describes the Rust support for MIPS R6 targets under `mipsisa*r6*-unknown-linux-gnu*`. + +The target name follow this format: `<machine>-<vendor>-<os><abi_suffix>`, where `<machine>` specifies the CPU family/model, `<vendor>` specifies the vendor and `<os>` the operating system name. The `<abi_suffix>` denotes the base ABI (32/n32/64/o64). + +| ABI suffix | Description | +|------------|------------------------------------| +| abi64 | Uses the 64-bit (64) ABI | +| abin32 | Uses the n32 ABI | +| N/A | Uses the (assumed) 32-bit (32) ABI | + +## Target Maintainers + +- [Xuan Chen](https://github.com/chenx97) <henry.chen@oss.cipunited.com> +- [Walter Ji](https://github.com/709924470) <walter.ji@oss.cipunited.com> +- [Xinhui Yang](https://github.com/Cyanoxygen) <cyan@oss.cipunited.com> +- [Lain Yang](https://github.com/Fearyncess) <lain.yang@oss.cipunited.com> + +## Requirements + +### C/C++ Toolchain + +A GNU toolchain for one of the MIPS R6 target is required. [AOSC OS](https://aosc.io/) provides working native and cross-compiling build environments. You may also supply your own a toolchain consisting of recent versions of GCC and Binutils. + +### Target libraries + +A minimum set of libraries is required to perform dynamic linking: + +- GNU glibc +- OpenSSL +- Zlib +- Linux API Headers + +This set of libraries should be installed to make up minimal target sysroot. + +For AOSC OS, You may install such a sysroot with the following commands: + +```sh +cd /tmp + +# linux+api, glibc, and file system structure are included in the toolchain. +sudo apt install gcc+cross-mips64r6el binutils+cross-mips64r6el + +# Download and extract required libraries. +wget https://repo.aosc.io/debs/pool/stable/main/z/zlib_1.2.13-0_mips64r6el.deb -O zlib.deb +wget https://repo.aosc.io/debs/pool/stable/main/o/openssl_1.1.1q-1_mips64r6el.deb -O openssl.deb + +# Extract them to your desired location. +for i in zlib openssl ; do + sudo dpkg-deb -vx $i.deb /var/ab/cross-root/mips64r6el +done + +# Workaround a possible ld bug when using -Wl,-Bdynamic. +sudo sed -i 's|/usr|=/usr|g' /var/ab/cross-root/mips64r6el/usr/lib/libc.so +``` + +For other distros, you may build them manually. + +## Building + +The following procedure outlines the build process for the MIPS64 R6 target with 64-bit (64) ABI (`mipsisa64r6el-unknown-linux-gnuabi64`). + +### Prerequisite: Disable debuginfo + +A LLVM bug makes rustc crash if debug or debug info generation is enabled. You need to edit `config.toml` to disable this: + +```toml +[rust] +debug = false +debug-info-level = 0 +``` + +### Prerequisite: Enable rustix's libc backend + +The crate `rustix` may try to link itself against MIPS R2 assembly, resulting in linkage error. To avoid this, you may force `rustix` to use its fallback `libc` backend by setting relevant `RUSTFLAGS`: + +```sh +export RUSTFLAGS="--cfg rustix_use_libc" +``` + +This will trigger warnings during build, as `-D warnings` is enabled by default. Disable `-D warnings` by editing `config.toml` to append the following: + +```toml +[rust] +deny-warnings = false +``` + +### Prerequisite: Supplying OpenSSL + +As a Tier 3 target, `openssl_sys` lacks the vendored OpenSSL library for this target. You will need to provide a prebuilt OpenSSL library to link `cargo`. Since we have a pre-configured sysroot, we can point to it directly: + +```sh +export MIPSISA64R6EL_UNKNOWN_LINUX_GNUABI64_OPENSSL_NO_VENDOR=y +export MIPSISA64R6EL_UNKNOWN_LINUX_GNUABI64_OPENSSL_DIR="/var/ab/cross-root/mips64r6el/usr" +``` + +On Debian, you may need to provide library path and include path separately: + +```sh +export MIPSISA64R6EL_UNKNOWN_LINUX_GNUABI64_OPENSSL_NO_VENDOR=y +export MIPSISA64R6EL_UNKNOWN_LINUX_GNUABI64_OPENSSL_LIB_DIR="/usr/lib/mipsisa64r6el-linux-gnuabi64/" +export MIPSISA64R6EL_UNKNOWN_LINUX_GNUABI64_OPENSSL_INCLUDE_DIR="/usr/include" +``` + +### Launching `x.py` + +```toml +[build] +target = ["mipsisa64r6el-unknown-linux-gnuabi64"] +``` + +Make sure that `mipsisa64r6el-unknown-linux-gnuabi64-gcc` is available from your executable search path (`$PATH`). + +Alternatively, you can specify the directories to all necessary toolchain executables in `config.toml`: + +```toml +[target.mipsisa64r6el-unknown-linux-gnuabi64] +# Adjust the paths below to point to your toolchain installation prefix. +cc = "/toolchain_prefix/bin/mipsisa64r6el-unknown-linux-gnuabi64-gcc" +cxx = "/toolchain_prefix/bin/mipsisa64r6el-unknown-linux-gnuabi64-g++" +ar = "/toolchain_prefix/bin/mipsisa64r6el-unknown-linux-gnuabi64-gcc-ar" +ranlib = "/toolchain_prefix/bin/mipsisa64r6el-unknown-linux-gnuabi64-ranlib" +linker = "/toolchain_prefix/bin/mipsisa64r6el-unknown-linux-gnuabi64-gcc" +``` + +Or, you can specify your cross compiler toolchain with an environment variable: + +```sh +export CROSS_COMPILE="/opt/abcross/mips64r6el/bin/mipsisa64r6el-aosc-linux-gnuabi64-" +``` + +Finally, launch the build script: + +```sh +./x.py build +``` + +### Tips + +- Avoid setting `cargo-native-static` to `false`, as this will result in a redundant artifact error while building clippy: + ```text + duplicate artifacts found when compiling a tool, this typically means that something was recompiled because a transitive dependency has different features activated than in a previous build: + + the following dependencies have different features: + syn 2.0.8 (registry+https://github.com/rust-lang/crates.io-index) + `clippy-driver` additionally enabled features {"full"} at ... + `cargo` additionally enabled features {} at ... + + to fix this you will probably want to edit the local src/tools/rustc-workspace-hack/Cargo.toml crate, as that will update the dependency graph to ensure that these crates all share the same feature set + thread 'main' panicked at 'tools should not compile multiple copies of the same crate', tool.rs:250:13 + note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace + ``` + +## Building Rust programs + +To build Rust programs for MIPS R6 targets, for instance, the `mipsisa64r6el-unknown-linux-gnuabi64` target: + +```bash +cargo build --target mipsisa64r6el-unknown-linux-gnuabi64 +``` + +## Testing + +To test a cross-compiled binary on your build system, install the Qemu user emulator that support the MIPS R6 architecture (`qemu-user-mipsel` or `qemu-user-mips64el`). GCC runtime libraries (`libgcc_s`) for the target architecture should be present in target sysroot to run the program. + +```sh +env \ + CARGO_TARGET_MIPSISA64R6EL_UNKNOWN_LINUX_GNUABI64_LINKER="/opt/abcross/mips64r6el/bin/mipsisa64r6el-aosc-linux-gnuabi64-gcc" \ + CARGO_TARGET_MIPSISA64R6EL_UNKNOWN_LINUX_GNUABI64_RUNNER="qemu-mips64el-static -L /var/ab/cross-root/mips64r6el" \ + cargo run --release \ + --target mipsisa64r6el-unknown-linux-gnuabi64 +``` + +## Tips for building Rust programs for MIPS R6 + +- Until we finalize a fix, please make sure the aforementioned workarounds for `rustix` crate and LLVM are always applied. This can be achieved by setting the relevant environment variables, and editing `Cargo.toml` before building. diff --git a/src/doc/rustdoc/src/what-is-rustdoc.md b/src/doc/rustdoc/src/what-is-rustdoc.md index 7a444d77c09..7179ee0cf03 100644 --- a/src/doc/rustdoc/src/what-is-rustdoc.md +++ b/src/doc/rustdoc/src/what-is-rustdoc.md @@ -37,7 +37,7 @@ top, with no contents. ## Configuring rustdoc There are two problems with this: first, why does it -think that our package is named "lib"? Second, why does it not have any +think that our crate is named "lib"? Second, why does it not have any contents? The first problem is due to `rustdoc` trying to be helpful; like `rustc`, diff --git a/src/doc/style-guide/src/expressions.md b/src/doc/style-guide/src/expressions.md index 40183063869..41a9eb82cb5 100644 --- a/src/doc/style-guide/src/expressions.md +++ b/src/doc/style-guide/src/expressions.md @@ -451,12 +451,11 @@ foo( #### Multi-line elements -If any element in a chain is formatted across multiple lines, then that element -and any later elements must be on their own line. Earlier elements may be kept -on a single line. E.g., +If any element in a chain is formatted across multiple lines, put that element +and any later elements on their own lines. ```rust -a.b.c()?.d +a.b.c()? .foo( an_expr, another_expr, diff --git a/src/doc/style-guide/src/items.md b/src/doc/style-guide/src/items.md index 1e0e60248bf..de31e8a8799 100644 --- a/src/doc/style-guide/src/items.md +++ b/src/doc/style-guide/src/items.md @@ -282,7 +282,7 @@ impl<T: Display, U: Debug> SomeType<T, U> { ... If the generics clause must be formatted across multiple lines, each parameter should have its own block-indented line, there should be newlines after the -opening bracket and before the closing bracket, and the should be a trailing +opening bracket and before the closing bracket, and there should be a trailing comma. ```rust diff --git a/src/librustdoc/clean/auto_trait.rs b/src/librustdoc/clean/auto_trait.rs index 92bae551644..68d636b360a 100644 --- a/src/librustdoc/clean/auto_trait.rs +++ b/src/librustdoc/clean/auto_trait.rs @@ -137,7 +137,7 @@ where pub(crate) fn get_auto_trait_impls(&mut self, item_def_id: DefId) -> Vec<Item> { let tcx = self.cx.tcx; let param_env = tcx.param_env(item_def_id); - let ty = tcx.type_of(item_def_id).subst_identity(); + let ty = tcx.type_of(item_def_id).instantiate_identity(); let f = auto_trait::AutoTraitFinder::new(tcx); debug!("get_auto_trait_impls({:?})", ty); diff --git a/src/librustdoc/clean/blanket_impl.rs b/src/librustdoc/clean/blanket_impl.rs index a3604158851..f5e02940c82 100644 --- a/src/librustdoc/clean/blanket_impl.rs +++ b/src/librustdoc/clean/blanket_impl.rs @@ -38,18 +38,22 @@ impl<'a, 'tcx> BlanketImplFinder<'a, 'tcx> { continue; } let infcx = cx.tcx.infer_ctxt().build(); - let substs = infcx.fresh_substs_for_item(DUMMY_SP, item_def_id); - let impl_ty = ty.subst(infcx.tcx, substs); - let param_env = EarlyBinder::bind(param_env).subst(infcx.tcx, substs); + let args = infcx.fresh_args_for_item(DUMMY_SP, item_def_id); + let impl_ty = ty.instantiate(infcx.tcx, args); + let param_env = EarlyBinder::bind(param_env).instantiate(infcx.tcx, args); - let impl_substs = infcx.fresh_substs_for_item(DUMMY_SP, impl_def_id); - let impl_trait_ref = trait_ref.subst(infcx.tcx, impl_substs); + let impl_args = infcx.fresh_args_for_item(DUMMY_SP, impl_def_id); + let impl_trait_ref = trait_ref.instantiate(infcx.tcx, impl_args); // Require the type the impl is implemented on to match // our type, and ignore the impl if there was a mismatch. - let Ok(eq_result) = infcx.at(&traits::ObligationCause::dummy(), param_env).eq(DefineOpaqueTypes::No, impl_trait_ref.self_ty(), impl_ty) else { - continue - }; + let Ok(eq_result) = infcx.at(&traits::ObligationCause::dummy(), param_env).eq( + DefineOpaqueTypes::No, + impl_trait_ref.self_ty(), + impl_ty, + ) else { + continue; + }; let InferOk { value: (), obligations } = eq_result; // FIXME(eddyb) ignoring `obligations` might cause false positives. drop(obligations); @@ -63,7 +67,7 @@ impl<'a, 'tcx> BlanketImplFinder<'a, 'tcx> { let predicates = cx .tcx .predicates_of(impl_def_id) - .instantiate(cx.tcx, impl_substs) + .instantiate(cx.tcx, impl_args) .predicates .into_iter() .chain(Some(ty::Binder::dummy(impl_trait_ref).to_predicate(infcx.tcx))); @@ -104,11 +108,11 @@ impl<'a, 'tcx> BlanketImplFinder<'a, 'tcx> { // the post-inference `trait_ref`, as it's more accurate. trait_: Some(clean_trait_ref_with_bindings( cx, - ty::Binder::dummy(trait_ref.subst_identity()), + ty::Binder::dummy(trait_ref.instantiate_identity()), ThinVec::new(), )), for_: clean_middle_ty( - ty::Binder::dummy(ty.subst_identity()), + ty::Binder::dummy(ty.instantiate_identity()), cx, None, None, @@ -121,7 +125,7 @@ impl<'a, 'tcx> BlanketImplFinder<'a, 'tcx> { .collect::<Vec<_>>(), polarity: ty::ImplPolarity::Positive, kind: ImplKind::Blanket(Box::new(clean_middle_ty( - ty::Binder::dummy(trait_ref.subst_identity().self_ty()), + ty::Binder::dummy(trait_ref.instantiate_identity().self_ty()), cx, None, None, diff --git a/src/librustdoc/clean/inline.rs b/src/librustdoc/clean/inline.rs index 870cfa93058..a98d466cd81 100644 --- a/src/librustdoc/clean/inline.rs +++ b/src/librustdoc/clean/inline.rs @@ -226,7 +226,7 @@ pub(crate) fn build_external_trait(cx: &mut DocContext<'_>, did: DefId) -> clean } fn build_external_function<'tcx>(cx: &mut DocContext<'tcx>, did: DefId) -> Box<clean::Function> { - let sig = cx.tcx.fn_sig(did).subst_identity(); + let sig = cx.tcx.fn_sig(did).instantiate_identity(); let late_bound_regions = sig.bound_vars().into_iter().filter_map(|var| match var { ty::BoundVariableKind::Region(ty::BrNamed(_, name)) if name != kw::UnderscoreLifetime => { @@ -279,7 +279,7 @@ fn build_union(cx: &mut DocContext<'_>, did: DefId) -> clean::Union { fn build_type_alias(cx: &mut DocContext<'_>, did: DefId) -> Box<clean::Typedef> { let predicates = cx.tcx.explicit_predicates_of(did); let type_ = clean_middle_ty( - ty::Binder::dummy(cx.tcx.type_of(did).subst_identity()), + ty::Binder::dummy(cx.tcx.type_of(did).instantiate_identity()), cx, Some(did), None, @@ -391,7 +391,7 @@ pub(crate) fn build_impl( let for_ = match &impl_item { Some(impl_) => clean_ty(impl_.self_ty, cx), None => clean_middle_ty( - ty::Binder::dummy(tcx.type_of(did).subst_identity()), + ty::Binder::dummy(tcx.type_of(did).instantiate_identity()), cx, Some(did), None, @@ -634,7 +634,7 @@ pub(crate) fn print_inlined_const(tcx: TyCtxt<'_>, did: DefId) -> String { fn build_const(cx: &mut DocContext<'_>, def_id: DefId) -> clean::Constant { clean::Constant { type_: clean_middle_ty( - ty::Binder::dummy(cx.tcx.type_of(def_id).subst_identity()), + ty::Binder::dummy(cx.tcx.type_of(def_id).instantiate_identity()), cx, Some(def_id), None, @@ -646,7 +646,7 @@ fn build_const(cx: &mut DocContext<'_>, def_id: DefId) -> clean::Constant { fn build_static(cx: &mut DocContext<'_>, did: DefId, mutable: bool) -> clean::Static { clean::Static { type_: clean_middle_ty( - ty::Binder::dummy(cx.tcx.type_of(did).subst_identity()), + ty::Binder::dummy(cx.tcx.type_of(did).instantiate_identity()), cx, Some(did), None, diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 0182d50773d..d62c4b707e1 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -24,7 +24,6 @@ use rustc_infer::infer::region_constraints::{Constraint, RegionConstraintData}; use rustc_middle::metadata::Reexport; use rustc_middle::middle::resolve_bound_vars as rbv; use rustc_middle::ty::fold::TypeFolder; -use rustc_middle::ty::InternalSubsts; use rustc_middle::ty::TypeVisitableExt; use rustc_middle::ty::{self, AdtKind, EarlyBinder, Ty, TyCtxt}; use rustc_middle::{bug, span_bug}; @@ -167,8 +166,7 @@ fn clean_generic_bound<'tcx>( let trait_ref = ty::Binder::dummy(ty::TraitRef::identity(cx.tcx, def_id)); let generic_args = clean_generic_args(generic_args, cx); - let GenericArgs::AngleBracketed { bindings, .. } = generic_args - else { + let GenericArgs::AngleBracketed { bindings, .. } = generic_args else { bug!("clean: parenthesized `GenericBound::LangItemTrait`"); }; @@ -202,7 +200,7 @@ pub(crate) fn clean_trait_ref_with_bindings<'tcx>( } inline::record_extern_fqn(cx, trait_ref.def_id(), kind); let path = - external_path(cx, trait_ref.def_id(), true, bindings, trait_ref.map_bound(|tr| tr.substs)); + external_path(cx, trait_ref.def_id(), true, bindings, trait_ref.map_bound(|tr| tr.args)); debug!(?trait_ref); @@ -240,7 +238,7 @@ fn clean_lifetime<'tcx>(lifetime: &hir::Lifetime, cx: &mut DocContext<'tcx>) -> | rbv::ResolvedArg::Free(_, node_id), ) = def { - if let Some(lt) = cx.substs.get(&node_id).and_then(|p| p.as_lt()).cloned() { + if let Some(lt) = cx.args.get(&node_id).and_then(|p| p.as_lt()).cloned() { return lt; } } @@ -251,7 +249,7 @@ pub(crate) fn clean_const<'tcx>(constant: &hir::ConstArg, cx: &mut DocContext<'t let def_id = cx.tcx.hir().body_owner_def_id(constant.value.body).to_def_id(); Constant { type_: clean_middle_ty( - ty::Binder::dummy(cx.tcx.type_of(def_id).subst_identity()), + ty::Binder::dummy(cx.tcx.type_of(def_id).instantiate_identity()), cx, Some(def_id), None, @@ -443,7 +441,7 @@ fn clean_projection<'tcx>( let bounds = cx .tcx .explicit_item_bounds(ty.skip_binder().def_id) - .subst_iter_copied(cx.tcx, ty.skip_binder().substs) + .arg_iter_copied(cx.tcx, ty.skip_binder().args) .map(|(pred, _)| pred) .collect::<Vec<_>>(); return clean_middle_opaque_bounds(cx, bounds); @@ -482,9 +480,9 @@ fn projection_to_path_segment<'tcx>( PathSegment { name: item.name, args: GenericArgs::AngleBracketed { - args: substs_to_args( + args: ty_args_to_args( cx, - ty.map_bound(|ty| &ty.substs[generics.parent_count..]), + ty.map_bound(|ty| &ty.args[generics.parent_count..]), false, None, ) @@ -505,7 +503,7 @@ fn clean_generic_param_def<'tcx>( ty::GenericParamDefKind::Type { has_default, synthetic, .. } => { let default = if has_default { Some(clean_middle_ty( - ty::Binder::dummy(cx.tcx.type_of(def.def_id).subst_identity()), + ty::Binder::dummy(cx.tcx.type_of(def.def_id).instantiate_identity()), cx, Some(def.def_id), None, @@ -539,7 +537,7 @@ fn clean_generic_param_def<'tcx>( )), default: match has_default { true => Some(Box::new( - cx.tcx.const_param_default(def.def_id).subst_identity().to_string(), + cx.tcx.const_param_default(def.def_id).instantiate_identity().to_string(), )), false => None, }, @@ -1244,7 +1242,7 @@ pub(crate) fn clean_middle_assoc_item<'tcx>( let kind = match assoc_item.kind { ty::AssocKind::Const => { let ty = clean_middle_ty( - ty::Binder::dummy(tcx.type_of(assoc_item.def_id).subst_identity()), + ty::Binder::dummy(tcx.type_of(assoc_item.def_id).instantiate_identity()), cx, Some(assoc_item.def_id), None, @@ -1261,7 +1259,7 @@ pub(crate) fn clean_middle_assoc_item<'tcx>( } } ty::AssocKind::Fn => { - let sig = tcx.fn_sig(assoc_item.def_id).subst_identity(); + let sig = tcx.fn_sig(assoc_item.def_id).instantiate_identity(); let late_bound_regions = sig.bound_vars().into_iter().filter_map(|var| match var { ty::BoundVariableKind::Region(ty::BrNamed(_, name)) @@ -1284,7 +1282,9 @@ pub(crate) fn clean_middle_assoc_item<'tcx>( if assoc_item.fn_has_self_parameter { let self_ty = match assoc_item.container { - ty::ImplContainer => tcx.type_of(assoc_item.container_id(tcx)).subst_identity(), + ty::ImplContainer => { + tcx.type_of(assoc_item.container_id(tcx)).instantiate_identity() + } ty::TraitContainer => tcx.types.self_param, }; let self_arg_ty = sig.input(0).skip_binder(); @@ -1340,7 +1340,7 @@ pub(crate) fn clean_middle_assoc_item<'tcx>( let mut predicates = tcx.explicit_predicates_of(assoc_item.def_id).predicates; if let ty::TraitContainer = assoc_item.container { let bounds = - tcx.explicit_item_bounds(assoc_item.def_id).subst_identity_iter_copied(); + tcx.explicit_item_bounds(assoc_item.def_id).instantiate_identity_iter_copied(); predicates = tcx.arena.alloc_from_iter(bounds.chain(predicates.iter().copied())); } let mut generics = clean_ty_generics( @@ -1443,7 +1443,9 @@ pub(crate) fn clean_middle_assoc_item<'tcx>( AssocTypeItem( Box::new(Typedef { type_: clean_middle_ty( - ty::Binder::dummy(tcx.type_of(assoc_item.def_id).subst_identity()), + ty::Binder::dummy( + tcx.type_of(assoc_item.def_id).instantiate_identity(), + ), cx, Some(assoc_item.def_id), None, @@ -1460,7 +1462,9 @@ pub(crate) fn clean_middle_assoc_item<'tcx>( AssocTypeItem( Box::new(Typedef { type_: clean_middle_ty( - ty::Binder::dummy(tcx.type_of(assoc_item.def_id).subst_identity()), + ty::Binder::dummy( + tcx.type_of(assoc_item.def_id).instantiate_identity(), + ), cx, Some(assoc_item.def_id), None, @@ -1486,7 +1490,7 @@ fn clean_qpath<'tcx>(hir_ty: &hir::Ty<'tcx>, cx: &mut DocContext<'tcx>) -> Type match qpath { hir::QPath::Resolved(None, path) => { if let Res::Def(DefKind::TyParam, did) = path.res { - if let Some(new_ty) = cx.substs.get(&did).and_then(|p| p.as_ty()).cloned() { + if let Some(new_ty) = cx.args.get(&did).and_then(|p| p.as_ty()).cloned() { return new_ty; } if let Some(bounds) = cx.impl_trait_bounds.remove(&did.into()) { @@ -1577,7 +1581,7 @@ fn maybe_expand_private_type_alias<'tcx>( let hir::ItemKind::TyAlias(ty, generics) = alias else { return None }; let provided_params = &path.segments.last().expect("segments were empty"); - let mut substs = DefIdMap::default(); + let mut args = DefIdMap::default(); let generic_args = provided_params.args(); let mut indices: hir::GenericParamCount = Default::default(); @@ -1601,7 +1605,7 @@ fn maybe_expand_private_type_alias<'tcx>( } else { Lifetime::elided() }; - substs.insert(param.def_id.to_def_id(), SubstParam::Lifetime(cleaned)); + args.insert(param.def_id.to_def_id(), SubstParam::Lifetime(cleaned)); } indices.lifetimes += 1; } @@ -1618,10 +1622,9 @@ fn maybe_expand_private_type_alias<'tcx>( _ => None, }); if let Some(ty) = type_ { - substs.insert(param.def_id.to_def_id(), SubstParam::Type(clean_ty(ty, cx))); + args.insert(param.def_id.to_def_id(), SubstParam::Type(clean_ty(ty, cx))); } else if let Some(default) = *default { - substs - .insert(param.def_id.to_def_id(), SubstParam::Type(clean_ty(default, cx))); + args.insert(param.def_id.to_def_id(), SubstParam::Type(clean_ty(default, cx))); } indices.types += 1; } @@ -1638,7 +1641,7 @@ fn maybe_expand_private_type_alias<'tcx>( _ => None, }); if let Some(ct) = const_ { - substs.insert( + args.insert( param.def_id.to_def_id(), SubstParam::Constant(clean_const(ct, cx)), ); @@ -1649,7 +1652,7 @@ fn maybe_expand_private_type_alias<'tcx>( } } - Some(cx.enter_alias(substs, def_id.to_def_id(), |cx| clean_ty(ty, cx))) + Some(cx.enter_alias(args, def_id.to_def_id(), |cx| clean_ty(ty, cx))) } pub(crate) fn clean_ty<'tcx>(ty: &hir::Ty<'tcx>, cx: &mut DocContext<'tcx>) -> Type { @@ -1818,14 +1821,14 @@ fn can_elide_trait_object_lifetime_bound<'tcx>( #[derive(Debug)] pub(crate) enum ContainerTy<'tcx> { Ref(ty::Region<'tcx>), - Regular { ty: DefId, substs: ty::Binder<'tcx, &'tcx [ty::GenericArg<'tcx>]>, arg: usize }, + Regular { ty: DefId, args: ty::Binder<'tcx, &'tcx [ty::GenericArg<'tcx>]>, arg: usize }, } impl<'tcx> ContainerTy<'tcx> { fn object_lifetime_default(self, tcx: TyCtxt<'tcx>) -> ObjectLifetimeDefault<'tcx> { match self { Self::Ref(region) => ObjectLifetimeDefault::Arg(region), - Self::Regular { ty: container, substs, arg: index } => { + Self::Regular { ty: container, args, arg: index } => { let (DefKind::Struct | DefKind::Union | DefKind::Enum @@ -1844,7 +1847,7 @@ impl<'tcx> ContainerTy<'tcx> { match default { rbv::ObjectLifetimeDefault::Param(lifetime) => { let index = generics.param_def_id_to_index[&lifetime]; - let arg = substs.skip_binder()[index as usize].expect_region(); + let arg = args.skip_binder()[index as usize].expect_region(); ObjectLifetimeDefault::Arg(arg) } rbv::ObjectLifetimeDefault::Empty => ObjectLifetimeDefault::Empty, @@ -1910,7 +1913,7 @@ pub(crate) fn clean_middle_ty<'tcx>( abi: sig.abi(), })) } - ty::Adt(def, substs) => { + ty::Adt(def, args) => { let did = def.did(); let kind = match def.adt_kind() { AdtKind::Struct => ItemType::Struct, @@ -1918,7 +1921,7 @@ pub(crate) fn clean_middle_ty<'tcx>( AdtKind::Enum => ItemType::Enum, }; inline::record_extern_fqn(cx, did, kind); - let path = external_path(cx, did, false, ThinVec::new(), bound_ty.rebind(substs)); + let path = external_path(cx, did, false, ThinVec::new(), bound_ty.rebind(args)); Type::Path { path } } ty::Foreign(did) => { @@ -1928,7 +1931,7 @@ pub(crate) fn clean_middle_ty<'tcx>( did, false, ThinVec::new(), - ty::Binder::dummy(InternalSubsts::empty()), + ty::Binder::dummy(ty::GenericArgs::empty()), ); Type::Path { path } } @@ -1941,10 +1944,10 @@ pub(crate) fn clean_middle_ty<'tcx>( .principal_def_id() .or_else(|| dids.next()) .unwrap_or_else(|| panic!("found trait object `{bound_ty:?}` with no traits?")); - let substs = match obj.principal() { - Some(principal) => principal.map_bound(|p| p.substs), - // marker traits have no substs. - _ => ty::Binder::dummy(InternalSubsts::empty()), + let args = match obj.principal() { + Some(principal) => principal.map_bound(|p| p.args), + // marker traits have no args. + _ => ty::Binder::dummy(ty::GenericArgs::empty()), }; inline::record_extern_fqn(cx, did, ItemType::Trait); @@ -1953,7 +1956,7 @@ pub(crate) fn clean_middle_ty<'tcx>( let mut bounds = dids .map(|did| { - let empty = ty::Binder::dummy(InternalSubsts::empty()); + let empty = ty::Binder::dummy(ty::GenericArgs::empty()); let path = external_path(cx, did, false, ThinVec::new(), empty); inline::record_extern_fqn(cx, did, ItemType::Trait); PolyTrait { trait_: path, generic_params: Vec::new() } @@ -1967,7 +1970,7 @@ pub(crate) fn clean_middle_ty<'tcx>( pb.map_bound(|pb| { pb // HACK(compiler-errors): Doesn't actually matter what self - // type we put here, because we're only using the GAT's substs. + // type we put here, because we're only using the GAT's args. .with_self_ty(cx.tcx, cx.tcx.types.self_param) .projection_ty }), @@ -1993,7 +1996,7 @@ pub(crate) fn clean_middle_ty<'tcx>( .collect(); let late_bound_regions = late_bound_regions.into_iter().collect(); - let path = external_path(cx, did, false, bindings, substs); + let path = external_path(cx, did, false, bindings, args); bounds.insert(0, PolyTrait { trait_: path, generic_params: late_bound_regions }); DynTrait(bounds, lifetime) @@ -2014,9 +2017,9 @@ pub(crate) fn clean_middle_ty<'tcx>( assoc: PathSegment { name: cx.tcx.associated_item(alias_ty.skip_binder().def_id).name, args: GenericArgs::AngleBracketed { - args: substs_to_args( + args: ty_args_to_args( cx, - alias_ty.map_bound(|ty| ty.substs.as_slice()), + alias_ty.map_bound(|ty| ty.args.as_slice()), true, None, ) @@ -2039,11 +2042,11 @@ pub(crate) fn clean_middle_ty<'tcx>( data.def_id, false, ThinVec::new(), - bound_ty.rebind(data.substs), + bound_ty.rebind(data.args), ); Type::Path { path } } else { - let ty = cx.tcx.type_of(data.def_id).subst(cx.tcx, data.substs); + let ty = cx.tcx.type_of(data.def_id).instantiate(cx.tcx, data.args); clean_middle_ty(bound_ty.rebind(ty), cx, None, None) } } @@ -2056,11 +2059,10 @@ pub(crate) fn clean_middle_ty<'tcx>( } } - ty::Alias(ty::Opaque, ty::AliasTy { def_id, substs, .. }) => { + ty::Alias(ty::Opaque, ty::AliasTy { def_id, args, .. }) => { // If it's already in the same alias, don't get an infinite loop. if cx.current_type_aliases.contains_key(&def_id) { - let path = - external_path(cx, def_id, false, ThinVec::new(), bound_ty.rebind(substs)); + let path = external_path(cx, def_id, false, ThinVec::new(), bound_ty.rebind(args)); Type::Path { path } } else { *cx.current_type_aliases.entry(def_id).or_insert(0) += 1; @@ -2069,7 +2071,7 @@ pub(crate) fn clean_middle_ty<'tcx>( let bounds = cx .tcx .explicit_item_bounds(def_id) - .subst_iter_copied(cx.tcx, substs) + .arg_iter_copied(cx.tcx, args) .map(|(bound, _)| bound) .collect::<Vec<_>>(); let ty = clean_middle_opaque_bounds(cx, bounds); @@ -2162,7 +2164,7 @@ pub(crate) fn clean_middle_field<'tcx>(field: &ty::FieldDef, cx: &mut DocContext field.did, field.name, clean_middle_ty( - ty::Binder::dummy(cx.tcx.type_of(field.did).subst_identity()), + ty::Binder::dummy(cx.tcx.type_of(field.did).instantiate_identity()), cx, Some(field.did), None, @@ -2563,7 +2565,7 @@ fn clean_impl<'tcx>( let type_alias = for_.def_id(&cx.cache).and_then(|alias_def_id: DefId| match tcx.def_kind(alias_def_id) { DefKind::TyAlias => Some(clean_middle_ty( - ty::Binder::dummy(tcx.type_of(def_id).subst_identity()), + ty::Binder::dummy(tcx.type_of(def_id).instantiate_identity()), cx, Some(def_id.to_def_id()), None, diff --git a/src/librustdoc/clean/simplify.rs b/src/librustdoc/clean/simplify.rs index 65b1b72adc1..d53b038019b 100644 --- a/src/librustdoc/clean/simplify.rs +++ b/src/librustdoc/clean/simplify.rs @@ -47,7 +47,9 @@ pub(crate) fn where_clauses(cx: &DocContext<'_>, clauses: Vec<WP>) -> ThinVec<WP // Look for equality predicates on associated types that can be merged into // general bound predicates. equalities.retain(|(lhs, rhs, bound_params)| { - let Some((ty, trait_did, name)) = lhs.projection() else { return true; }; + let Some((ty, trait_did, name)) = lhs.projection() else { + return true; + }; let Some((bounds, _)) = tybounds.get_mut(ty) else { return true }; merge_bounds(cx, bounds, bound_params.clone(), trait_did, name, rhs) }); diff --git a/src/librustdoc/clean/types.rs b/src/librustdoc/clean/types.rs index 26139d52769..cfe62407fd3 100644 --- a/src/librustdoc/clean/types.rs +++ b/src/librustdoc/clean/types.rs @@ -451,11 +451,7 @@ impl Item { pub(crate) fn links(&self, cx: &Context<'_>) -> Vec<RenderedLink> { use crate::html::format::{href, link_tooltip}; - let Some(links) = cx.cache() - .intra_doc_links - .get(&self.item_id) else { - return vec![] - }; + let Some(links) = cx.cache().intra_doc_links.get(&self.item_id) else { return vec![] }; links .iter() .filter_map(|ItemLink { link: s, link_text, page_id: id, ref fragment }| { @@ -484,11 +480,9 @@ impl Item { /// the link text, but does need to know which `[]`-bracketed names /// are actually links. pub(crate) fn link_names(&self, cache: &Cache) -> Vec<RenderedLink> { - let Some(links) = cache - .intra_doc_links - .get(&self.item_id) else { - return vec![]; - }; + let Some(links) = cache.intra_doc_links.get(&self.item_id) else { + return vec![]; + }; links .iter() .map(|ItemLink { link: s, link_text, .. }| RenderedLink { @@ -1227,7 +1221,7 @@ pub(crate) enum GenericBound { impl GenericBound { pub(crate) fn maybe_sized(cx: &mut DocContext<'_>) -> GenericBound { let did = cx.tcx.require_lang_item(LangItem::Sized, None); - let empty = ty::Binder::dummy(ty::InternalSubsts::empty()); + let empty = ty::Binder::dummy(ty::GenericArgs::empty()); let path = external_path(cx, did, false, ThinVec::new(), empty); inline::record_extern_fqn(cx, did, ItemType::Trait); GenericBound::TraitBound( diff --git a/src/librustdoc/clean/utils.rs b/src/librustdoc/clean/utils.rs index f375f0efbd1..df9da9e7c7f 100644 --- a/src/librustdoc/clean/utils.rs +++ b/src/librustdoc/clean/utils.rs @@ -16,8 +16,7 @@ use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::{DefId, LOCAL_CRATE}; use rustc_middle::mir; use rustc_middle::mir::interpret::ConstValue; -use rustc_middle::ty::subst::{GenericArgKind, SubstsRef}; -use rustc_middle::ty::{self, TyCtxt}; +use rustc_middle::ty::{self, GenericArgKind, GenericArgsRef, TyCtxt}; use rustc_span::symbol::{kw, sym, Symbol}; use std::fmt::Write as _; use std::mem; @@ -54,8 +53,7 @@ pub(crate) fn krate(cx: &mut DocContext<'_>) -> Crate { let primitives = local_crate.primitives(cx.tcx); let keywords = local_crate.keywords(cx.tcx); { - let ItemKind::ModuleItem(ref mut m) = *module.kind - else { unreachable!() }; + let ItemKind::ModuleItem(ref mut m) = *module.kind else { unreachable!() }; m.items.extend(primitives.iter().map(|&(def_id, prim)| { Item::from_def_id_and_parts( def_id, @@ -72,20 +70,16 @@ pub(crate) fn krate(cx: &mut DocContext<'_>) -> Crate { Crate { module, external_traits: cx.external_traits.clone() } } -pub(crate) fn substs_to_args<'tcx>( +pub(crate) fn ty_args_to_args<'tcx>( cx: &mut DocContext<'tcx>, - substs: ty::Binder<'tcx, &'tcx [ty::subst::GenericArg<'tcx>]>, + args: ty::Binder<'tcx, &'tcx [ty::GenericArg<'tcx>]>, mut skip_first: bool, container: Option<DefId>, ) -> Vec<GenericArg> { let mut ret_val = - Vec::with_capacity(substs.skip_binder().len().saturating_sub(if skip_first { - 1 - } else { - 0 - })); + Vec::with_capacity(args.skip_binder().len().saturating_sub(if skip_first { 1 } else { 0 })); - ret_val.extend(substs.iter().enumerate().filter_map(|(index, kind)| { + ret_val.extend(args.iter().enumerate().filter_map(|(index, kind)| { match kind.skip_binder().unpack() { GenericArgKind::Lifetime(lt) => { Some(GenericArg::Lifetime(clean_middle_region(lt).unwrap_or(Lifetime::elided()))) @@ -100,7 +94,7 @@ pub(crate) fn substs_to_args<'tcx>( None, container.map(|container| crate::clean::ContainerTy::Regular { ty: container, - substs, + args, arg: index, }), ))), @@ -117,12 +111,12 @@ fn external_generic_args<'tcx>( did: DefId, has_self: bool, bindings: ThinVec<TypeBinding>, - substs: ty::Binder<'tcx, SubstsRef<'tcx>>, + ty_args: ty::Binder<'tcx, GenericArgsRef<'tcx>>, ) -> GenericArgs { - let args = substs_to_args(cx, substs.map_bound(|substs| &substs[..]), has_self, Some(did)); + let args = ty_args_to_args(cx, ty_args.map_bound(|args| &args[..]), has_self, Some(did)); if cx.tcx.fn_trait_kind_from_def_id(did).is_some() { - let ty = substs + let ty = ty_args .iter() .nth(if has_self { 1 } else { 0 }) .unwrap() @@ -150,7 +144,7 @@ pub(super) fn external_path<'tcx>( did: DefId, has_self: bool, bindings: ThinVec<TypeBinding>, - substs: ty::Binder<'tcx, SubstsRef<'tcx>>, + args: ty::Binder<'tcx, GenericArgsRef<'tcx>>, ) -> Path { let def_kind = cx.tcx.def_kind(did); let name = cx.tcx.item_name(did); @@ -158,7 +152,7 @@ pub(super) fn external_path<'tcx>( res: Res::Def(def_kind, did), segments: thin_vec![PathSegment { name, - args: external_generic_args(cx, did, has_self, bindings, substs), + args: external_generic_args(cx, did, has_self, bindings, args), }], } } @@ -253,7 +247,7 @@ pub(crate) fn name_from_pat(p: &hir::Pat<'_>) -> Symbol { pub(crate) fn print_const(cx: &DocContext<'_>, n: ty::Const<'_>) -> String { match n.kind() { - ty::ConstKind::Unevaluated(ty::UnevaluatedConst { def, substs: _ }) => { + ty::ConstKind::Unevaluated(ty::UnevaluatedConst { def, args: _ }) => { let s = if let Some(def) = def.as_local() { print_const_expr(cx.tcx, cx.tcx.hir().body_owned_by(def)) } else { @@ -278,7 +272,7 @@ pub(crate) fn print_evaluated_const( underscores_and_type: bool, ) -> Option<String> { tcx.const_eval_poly(def_id).ok().and_then(|val| { - let ty = tcx.type_of(def_id).subst_identity(); + let ty = tcx.type_of(def_id).instantiate_identity(); match (val, ty.kind()) { (_, &ty::Ref(..)) => None, (ConstValue::Scalar(_), &ty::Adt(_, _)) => None, diff --git a/src/librustdoc/core.rs b/src/librustdoc/core.rs index 9687b8b1887..1bd40aea823 100644 --- a/src/librustdoc/core.rs +++ b/src/librustdoc/core.rs @@ -45,7 +45,7 @@ pub(crate) struct DocContext<'tcx> { // The current set of parameter substitutions, // for expanding type aliases at the HIR level: /// Table `DefId` of type, lifetime, or const parameter -> substituted type, lifetime, or const - pub(crate) substs: DefIdMap<clean::SubstParam>, + pub(crate) args: DefIdMap<clean::SubstParam>, pub(crate) current_type_aliases: DefIdMap<usize>, /// Table synthetic type parameter for `impl Trait` in argument position -> bounds pub(crate) impl_trait_bounds: FxHashMap<ImplTraitParam, Vec<clean::GenericBound>>, @@ -85,17 +85,17 @@ impl<'tcx> DocContext<'tcx> { /// the substitutions for a type alias' RHS. pub(crate) fn enter_alias<F, R>( &mut self, - substs: DefIdMap<clean::SubstParam>, + args: DefIdMap<clean::SubstParam>, def_id: DefId, f: F, ) -> R where F: FnOnce(&mut Self) -> R, { - let old_substs = mem::replace(&mut self.substs, substs); + let old_args = mem::replace(&mut self.args, args); *self.current_type_aliases.entry(def_id).or_insert(0) += 1; let r = f(self); - self.substs = old_substs; + self.args = old_args; if let Some(count) = self.current_type_aliases.get_mut(&def_id) { *count -= 1; if *count == 0 { @@ -340,7 +340,7 @@ pub(crate) fn run_global_ctxt( param_env: ParamEnv::empty(), external_traits: Default::default(), active_extern_traits: Default::default(), - substs: Default::default(), + args: Default::default(), current_type_aliases: Default::default(), impl_trait_bounds: Default::default(), generated_synthetics: Default::default(), diff --git a/src/librustdoc/doctest.rs b/src/librustdoc/doctest.rs index 217257316c8..6047cf23350 100644 --- a/src/librustdoc/doctest.rs +++ b/src/librustdoc/doctest.rs @@ -653,8 +653,7 @@ pub(crate) fn make_test( (found_main, found_extern_crate, found_macro) }) }); - let Ok((already_has_main, already_has_extern_crate, found_macro)) = result - else { + let Ok((already_has_main, already_has_extern_crate, found_macro)) = result else { // If the parser panicked due to a fatal error, pass the test code through unchanged. // The error will be reported during compilation. return (s.to_owned(), 0, false); diff --git a/src/librustdoc/formats/cache.rs b/src/librustdoc/formats/cache.rs index dac762e9ff9..6b48936cc59 100644 --- a/src/librustdoc/formats/cache.rs +++ b/src/librustdoc/formats/cache.rs @@ -473,7 +473,7 @@ impl<'a, 'tcx> DocFolder for CacheBuilder<'a, 'tcx> { | clean::BorrowedRef { type_: box clean::Type::Path { ref path }, .. } => { dids.insert(path.def_id()); if let Some(generics) = path.generics() && - let ty::Adt(adt, _) = self.tcx.type_of(path.def_id()).subst_identity().kind() && + let ty::Adt(adt, _) = self.tcx.type_of(path.def_id()).instantiate_identity().kind() && adt.is_fundamental() { for ty in generics { if let Some(did) = ty.def_id(self.cache) { diff --git a/src/librustdoc/formats/renderer.rs b/src/librustdoc/formats/renderer.rs index 6f9cc026675..c49f1a4d37e 100644 --- a/src/librustdoc/formats/renderer.rs +++ b/src/librustdoc/formats/renderer.rs @@ -77,8 +77,11 @@ pub(crate) fn run_format<'tcx, T: FormatRenderer<'tcx>>( prof.generic_activity_with_arg("render_mod_item", item.name.unwrap().to_string()); cx.mod_item_in(&item)?; - let (clean::StrippedItem(box clean::ModuleItem(module)) | clean::ModuleItem(module)) = *item.kind - else { unreachable!() }; + let (clean::StrippedItem(box clean::ModuleItem(module)) | clean::ModuleItem(module)) = + *item.kind + else { + unreachable!() + }; for it in module.items { debug!("Adding {:?} to worklist", it.name); work.push((cx.make_child_renderer(), it)); diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index 54c0cd2ef7f..1099c68b004 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -771,9 +771,10 @@ pub(crate) fn href_relative_parts<'fqp>( pub(crate) fn link_tooltip(did: DefId, fragment: &Option<UrlFragment>, cx: &Context<'_>) -> String { let cache = cx.cache(); - let Some((fqp, shortty)) = cache.paths.get(&did) - .or_else(|| cache.external_paths.get(&did)) - else { return String::new() }; + let Some((fqp, shortty)) = cache.paths.get(&did).or_else(|| cache.external_paths.get(&did)) + else { + return String::new(); + }; let mut buf = Buffer::new(); let fqp = if *shortty == ItemType::Primitive { // primitives are documented in a crate, but not actually part of it diff --git a/src/librustdoc/html/highlight.rs b/src/librustdoc/html/highlight.rs index c94968b4817..a99ac0f4e05 100644 --- a/src/librustdoc/html/highlight.rs +++ b/src/librustdoc/html/highlight.rs @@ -928,13 +928,11 @@ fn string_without_closing_tag<T: Display>( href_context: &Option<HrefContext<'_, '_>>, open_tag: bool, ) -> Option<&'static str> { - let Some(klass) = klass - else { + let Some(klass) = klass else { write!(out, "{}", text).unwrap(); return None; }; - let Some(def_span) = klass.get_span() - else { + let Some(def_span) = klass.get_span() else { if !open_tag { write!(out, "{}", text).unwrap(); return None; @@ -988,6 +986,11 @@ fn string_without_closing_tag<T: Display>( ) .ok() .map(|(url, _, _)| url), + LinkFromSrc::Doc(def_id) => { + format::href_with_root_path(*def_id, context, Some(&href_context.root_path)) + .ok() + .map(|(doc_link, _, _)| doc_link) + } } }) { diff --git a/src/librustdoc/html/render/context.rs b/src/librustdoc/html/render/context.rs index 4c476263635..aa72af001df 100644 --- a/src/librustdoc/html/render/context.rs +++ b/src/librustdoc/html/render/context.rs @@ -805,8 +805,11 @@ impl<'tcx> FormatRenderer<'tcx> for Context<'tcx> { // Render sidebar-items.js used throughout this module. if !self.render_redirect_pages { - let (clean::StrippedItem(box clean::ModuleItem(ref module)) | clean::ModuleItem(ref module)) = *item.kind - else { unreachable!() }; + let (clean::StrippedItem(box clean::ModuleItem(ref module)) + | clean::ModuleItem(ref module)) = *item.kind + else { + unreachable!() + }; let items = self.build_sidebar_items(module); let js_dst = self.dst.join(&format!("sidebar-items{}.js", self.shared.resource_suffix)); let v = format!("window.SIDEBAR_ITEMS = {};", serde_json::to_string(&items).unwrap()); diff --git a/src/librustdoc/html/render/mod.rs b/src/librustdoc/html/render/mod.rs index f923f905451..575ce6aa99a 100644 --- a/src/librustdoc/html/render/mod.rs +++ b/src/librustdoc/html/render/mod.rs @@ -1821,9 +1821,9 @@ fn render_rightside( ); if let Some(l) = src_href { if has_stability { - write!(rightside, " · <a class=\"srclink\" href=\"{}\">source</a>", l) + write!(rightside, " · <a class=\"src\" href=\"{}\">source</a>", l) } else { - write!(rightside, "<a class=\"srclink rightside\" href=\"{}\">source</a>", l) + write!(rightside, "<a class=\"src rightside\" href=\"{}\">source</a>", l) } } if has_stability && has_src_ref { @@ -1988,7 +1988,9 @@ pub(crate) fn get_filtered_impls_for_reference<'a>( ) -> (Vec<&'a Impl>, Vec<&'a Impl>, Vec<&'a Impl>) { let def_id = it.item_id.expect_def_id(); // If the reference primitive is somehow not defined, exit early. - let Some(v) = shared.cache.impls.get(&def_id) else { return (Vec::new(), Vec::new(), Vec::new()) }; + let Some(v) = shared.cache.impls.get(&def_id) else { + return (Vec::new(), Vec::new(), Vec::new()); + }; // Since there is no "direct implementation" on the reference primitive type, we filter out // every implementation which isn't a trait implementation. let traits = v.iter().filter(|i| i.inner_impl().trait_.is_some()); diff --git a/src/librustdoc/html/render/span_map.rs b/src/librustdoc/html/render/span_map.rs index eb9262f472b..ac587bf6008 100644 --- a/src/librustdoc/html/render/span_map.rs +++ b/src/librustdoc/html/render/span_map.rs @@ -1,11 +1,11 @@ -use crate::clean::{self, PrimitiveType}; +use crate::clean::{self, rustc_span, PrimitiveType}; use crate::html::sources; use rustc_data_structures::fx::FxHashMap; use rustc_hir::def::{DefKind, Res}; -use rustc_hir::def_id::DefId; +use rustc_hir::def_id::{DefId, LOCAL_CRATE}; use rustc_hir::intravisit::{self, Visitor}; -use rustc_hir::{ExprKind, HirId, Mod, Node}; +use rustc_hir::{ExprKind, HirId, Item, ItemKind, Mod, Node}; use rustc_middle::hir::nested_filter; use rustc_middle::ty::TyCtxt; use rustc_span::hygiene::MacroKind; @@ -25,6 +25,7 @@ pub(crate) enum LinkFromSrc { Local(clean::Span), External(DefId), Primitive(PrimitiveType), + Doc(DefId), } /// This function will do at most two things: @@ -65,24 +66,43 @@ struct SpanMapVisitor<'tcx> { impl<'tcx> SpanMapVisitor<'tcx> { /// This function is where we handle `hir::Path` elements and add them into the "span map". fn handle_path(&mut self, path: &rustc_hir::Path<'_>) { - let info = match path.res { + match path.res { // FIXME: For now, we handle `DefKind` if it's not a `DefKind::TyParam`. // Would be nice to support them too alongside the other `DefKind` // (such as primitive types!). - Res::Def(kind, def_id) if kind != DefKind::TyParam => Some(def_id), - Res::Local(_) => None, + Res::Def(kind, def_id) if kind != DefKind::TyParam => { + let link = if def_id.as_local().is_some() { + LinkFromSrc::Local(rustc_span(def_id, self.tcx)) + } else { + LinkFromSrc::External(def_id) + }; + self.matches.insert(path.span, link); + } + Res::Local(_) => { + if let Some(span) = self.tcx.hir().res_span(path.res) { + self.matches.insert(path.span, LinkFromSrc::Local(clean::Span::new(span))); + } + } Res::PrimTy(p) => { // FIXME: Doesn't handle "path-like" primitives like arrays or tuples. self.matches.insert(path.span, LinkFromSrc::Primitive(PrimitiveType::from(p))); - return; } - Res::Err => return, - _ => return, - }; - if let Some(span) = self.tcx.hir().res_span(path.res) { - self.matches.insert(path.span, LinkFromSrc::Local(clean::Span::new(span))); - } else if let Some(def_id) = info { - self.matches.insert(path.span, LinkFromSrc::External(def_id)); + Res::Err => {} + _ => {} + } + } + + /// Used to generate links on items' definition to go to their documentation page. + pub(crate) fn extract_info_from_hir_id(&mut self, hir_id: HirId) { + if let Some(Node::Item(item)) = self.tcx.hir().find(hir_id) { + if let Some(span) = self.tcx.def_ident_span(item.owner_id) { + let cspan = clean::Span::new(span); + // If the span isn't from the current crate, we ignore it. + if cspan.inner().is_dummy() || cspan.cnum(self.tcx.sess) != LOCAL_CRATE { + return; + } + self.matches.insert(span, LinkFromSrc::Doc(item.owner_id.to_def_id())); + } } } @@ -117,10 +137,13 @@ impl<'tcx> SpanMapVisitor<'tcx> { _ => return true, }; let link_from_src = match data.macro_def_id { - Some(macro_def_id) if macro_def_id.is_local() => { - LinkFromSrc::Local(clean::Span::new(data.def_site)) + Some(macro_def_id) => { + if macro_def_id.is_local() { + LinkFromSrc::Local(clean::Span::new(data.def_site)) + } else { + LinkFromSrc::External(macro_def_id) + } } - Some(macro_def_id) => LinkFromSrc::External(macro_def_id), None => return true, }; let new_span = data.call_site; @@ -160,6 +183,9 @@ impl<'tcx> Visitor<'tcx> for SpanMapVisitor<'tcx> { LinkFromSrc::Local(clean::Span::new(m.spans.inner_span)), ); } + } else { + // If it's a "mod foo {}", we want to look to its documentation page. + self.extract_info_from_hir_id(id); } intravisit::walk_mod(self, m, id); } @@ -176,13 +202,12 @@ impl<'tcx> Visitor<'tcx> for SpanMapVisitor<'tcx> { .tcx .typeck_body(hir.maybe_body_owned_by(body_id).expect("a body which isn't a body")); if let Some(def_id) = typeck_results.type_dependent_def_id(expr.hir_id) { - self.matches.insert( - segment.ident.span, - match hir.span_if_local(def_id) { - Some(span) => LinkFromSrc::Local(clean::Span::new(span)), - None => LinkFromSrc::External(def_id), - }, - ); + let link = if def_id.as_local().is_some() { + LinkFromSrc::Local(rustc_span(def_id, self.tcx)) + } else { + LinkFromSrc::External(def_id) + }; + self.matches.insert(segment.ident.span, link); } } else if self.handle_macro(expr.span) { // We don't want to go deeper into the macro. @@ -190,4 +215,28 @@ impl<'tcx> Visitor<'tcx> for SpanMapVisitor<'tcx> { } intravisit::walk_expr(self, expr); } + + fn visit_item(&mut self, item: &'tcx Item<'tcx>) { + match item.kind { + ItemKind::Static(_, _, _) + | ItemKind::Const(_, _) + | ItemKind::Fn(_, _, _) + | ItemKind::Macro(_, _) + | ItemKind::TyAlias(_, _) + | ItemKind::Enum(_, _) + | ItemKind::Struct(_, _) + | ItemKind::Union(_, _) + | ItemKind::Trait(_, _, _, _, _) + | ItemKind::TraitAlias(_, _) => self.extract_info_from_hir_id(item.hir_id()), + ItemKind::Impl(_) + | ItemKind::Use(_, _) + | ItemKind::ExternCrate(_) + | ItemKind::ForeignMod { .. } + | ItemKind::GlobalAsm(_) + | ItemKind::OpaqueTy(_) + // We already have "visit_mod" above so no need to check it here. + | ItemKind::Mod(_) => {} + } + intravisit::walk_item(self, item); + } } diff --git a/src/librustdoc/html/render/type_layout.rs b/src/librustdoc/html/render/type_layout.rs index 0bc32ea5a20..377daaeb9d4 100644 --- a/src/librustdoc/html/render/type_layout.rs +++ b/src/librustdoc/html/render/type_layout.rs @@ -39,7 +39,7 @@ pub(crate) fn document_type_layout<'a, 'cx: 'a>( let tcx = cx.tcx(); let param_env = tcx.param_env(ty_def_id); - let ty = tcx.type_of(ty_def_id).subst_identity(); + let ty = tcx.type_of(ty_def_id).instantiate_identity(); let type_layout = tcx.layout_of(param_env.and(ty)); let variants = diff --git a/src/librustdoc/html/render/write_shared.rs b/src/librustdoc/html/render/write_shared.rs index 54749e9a317..3f41765a5af 100644 --- a/src/librustdoc/html/render/write_shared.rs +++ b/src/librustdoc/html/render/write_shared.rs @@ -270,7 +270,7 @@ pub(super) fn write_shared( hierarchy.add_path(source); } let hierarchy = Rc::try_unwrap(hierarchy).unwrap(); - let dst = cx.dst.join(&format!("source-files{}.js", cx.shared.resource_suffix)); + let dst = cx.dst.join(&format!("src-files{}.js", cx.shared.resource_suffix)); let make_sources = || { let (mut all_sources, _krates) = try_err!(collect_json(&dst, krate.name(cx.tcx()).as_str()), &dst); @@ -286,12 +286,12 @@ pub(super) fn write_shared( .replace("\\\"", "\\\\\"") )); all_sources.sort(); - let mut v = String::from("var sourcesIndex = JSON.parse('{\\\n"); + let mut v = String::from("var srcIndex = JSON.parse('{\\\n"); v.push_str(&all_sources.join(",\\\n")); - v.push_str("\\\n}');\ncreateSourceSidebar();\n"); + v.push_str("\\\n}');\ncreateSrcSidebar();\n"); Ok(v.into_bytes()) }; - write_invocation_specific("source-files.js", &make_sources)?; + write_invocation_specific("src-files.js", &make_sources)?; } // Update the search index and crate list. diff --git a/src/librustdoc/html/sources.rs b/src/librustdoc/html/sources.rs index a26fa374912..3e3fc8a0e72 100644 --- a/src/librustdoc/html/sources.rs +++ b/src/librustdoc/html/sources.rs @@ -227,7 +227,7 @@ impl SourceCollector<'_, '_> { let desc = format!("Source of the Rust file `{}`.", filename.prefer_remapped()); let page = layout::Page { title: &title, - css_class: "source", + css_class: "src", root_path: &root_path, static_root_path: shared.static_root_path.as_deref(), description: &desc, diff --git a/src/librustdoc/html/static/css/noscript.css b/src/librustdoc/html/static/css/noscript.css index 54e8b6561f3..93aa11a5852 100644 --- a/src/librustdoc/html/static/css/noscript.css +++ b/src/librustdoc/html/static/css/noscript.css @@ -19,7 +19,7 @@ nav.sub { display: none; } -.source .sidebar { +.src .sidebar { display: none; } diff --git a/src/librustdoc/html/static/css/rustdoc.css b/src/librustdoc/html/static/css/rustdoc.css index b7f455259ef..9209915895a 100644 --- a/src/librustdoc/html/static/css/rustdoc.css +++ b/src/librustdoc/html/static/css/rustdoc.css @@ -194,7 +194,7 @@ h1, h2, h3, h4, h5, h6, .item-name > a, .out-of-band, span.since, -a.srclink, +a.src, #help-button > a, summary.hideme, .scraped-example-list, @@ -206,7 +206,7 @@ ul.all-items { #toggle-all-docs, a.anchor, .small-section-header a, -#source-sidebar a, +#src-sidebar a, .rust a, .sidebar h2 a, .sidebar h3 a, @@ -315,7 +315,7 @@ main { min-width: 0; /* avoid growing beyond the size limit */ } -.source main { +.src main { padding: 15px; } @@ -350,10 +350,10 @@ pre.item-decl { contain: initial; } -.source .content pre { +.src .content pre { padding: 20px; } -.rustdoc.source .example-wrap pre.src-line-numbers { +.rustdoc.src .example-wrap pre.src-line-numbers { padding: 20px 0 20px 4px; } @@ -392,7 +392,7 @@ img { left: 0; } -.rustdoc.source .sidebar { +.rustdoc.src .sidebar { flex-basis: 50px; border-right: 1px solid; overflow-x: hidden; @@ -402,7 +402,7 @@ img { } .sidebar, .mobile-topbar, .sidebar-menu-toggle, -#src-sidebar-toggle, #source-sidebar { +#src-sidebar-toggle, #src-sidebar { background-color: var(--sidebar-background-color); } @@ -410,16 +410,16 @@ img { background-color: var(--sidebar-background-color-hover); } -.source .sidebar > *:not(#src-sidebar-toggle) { +.src .sidebar > *:not(#src-sidebar-toggle) { visibility: hidden; } -.source-sidebar-expanded .source .sidebar { +.src-sidebar-expanded .src .sidebar { overflow-y: auto; flex-basis: 300px; } -.source-sidebar-expanded .source .sidebar > *:not(#src-sidebar-toggle) { +.src-sidebar-expanded .src .sidebar > *:not(#src-sidebar-toggle) { visibility: visible; } @@ -544,7 +544,7 @@ ul.block, .block li { flex-grow: 1; } -.rustdoc:not(.source) .example-wrap pre { +.rustdoc:not(.src) .example-wrap pre { overflow: auto hidden; } @@ -619,7 +619,7 @@ ul.block, .block li { } .docblock code, .docblock-short code, -pre, .rustdoc.source .example-wrap { +pre, .rustdoc.src .example-wrap { background-color: var(--code-block-background-color); } @@ -676,7 +676,7 @@ nav.sub { height: 34px; flex-grow: 1; } -.source nav.sub { +.src nav.sub { margin: 0 0 15px 0; } @@ -1074,7 +1074,7 @@ pre.rust .doccomment { color: var(--code-highlight-doc-comment-color); } -.rustdoc.source .example-wrap pre.rust a { +.rustdoc.src .example-wrap pre.rust a { background: var(--codeblock-link-background); } @@ -1301,22 +1301,22 @@ a.tooltip:hover::after { align-items: stretch; z-index: 10; } -#source-sidebar { +#src-sidebar { width: 100%; overflow: auto; } -#source-sidebar > .title { +#src-sidebar > .title { font-size: 1.5rem; text-align: center; border-bottom: 1px solid var(--border-color); margin-bottom: 6px; } -#source-sidebar div.files > a:hover, details.dir-entry summary:hover, -#source-sidebar div.files > a:focus, details.dir-entry summary:focus { - background-color: var(--source-sidebar-background-hover); +#src-sidebar div.files > a:hover, details.dir-entry summary:hover, +#src-sidebar div.files > a:focus, details.dir-entry summary:focus { + background-color: var(--src-sidebar-background-hover); } -#source-sidebar div.files > a.selected { - background-color: var(--source-sidebar-background-selected); +#src-sidebar div.files > a.selected { + background-color: var(--src-sidebar-background-selected); } #src-sidebar-toggle > button { font-size: inherit; @@ -1562,7 +1562,7 @@ However, it's not needed with smaller screen width because the doc/code block is /* WARNING: RUSTDOC_MOBILE_BREAKPOINT MEDIA QUERY If you update this line, then you also need to update the line with the same warning -in source-script.js +in src-script.js */ @media (max-width: 700px) { /* When linking to an item with an `id` (for instance, by clicking a link in the sidebar, @@ -1619,8 +1619,8 @@ in source-script.js /* The source view uses a different design for the sidebar toggle, and doesn't have a topbar, so don't bump down the main content or the sidebar. */ - .source main, - .rustdoc.source .sidebar { + .src main, + .rustdoc.src .sidebar { top: 0; padding: 0; height: 100vh; @@ -1628,8 +1628,8 @@ in source-script.js } .sidebar.shown, - .source-sidebar-expanded .source .sidebar, - .rustdoc:not(.source) .sidebar:focus-within { + .src-sidebar-expanded .src .sidebar, + .rustdoc:not(.src) .sidebar:focus-within { left: 0; } @@ -1709,7 +1709,7 @@ in source-script.js border-left: 0; } - .source-sidebar-expanded #src-sidebar-toggle { + .src-sidebar-expanded #src-sidebar-toggle { left: unset; top: unset; width: unset; @@ -1749,7 +1749,7 @@ in source-script.js display: inline; } - .source-sidebar-expanded .source .sidebar { + .src-sidebar-expanded .src .sidebar { max-width: 100vw; width: 100vw; } @@ -1769,7 +1769,7 @@ in source-script.js margin-left: 34px; } - .source nav.sub { + .src nav.sub { margin: 0; padding: var(--nav-sub-mobile-padding); } @@ -1792,7 +1792,7 @@ in source-script.js } @media print { - nav.sidebar, nav.sub, .out-of-band, a.srclink, #copy-path, + nav.sidebar, nav.sub, .out-of-band, a.src, #copy-path, details.toggle[open] > summary::before, details.toggle > summary::before, details.toggle.top-doc > summary { display: none; diff --git a/src/librustdoc/html/static/css/themes/ayu.css b/src/librustdoc/html/static/css/themes/ayu.css index 7145baad256..d8dae51eb1b 100644 --- a/src/librustdoc/html/static/css/themes/ayu.css +++ b/src/librustdoc/html/static/css/themes/ayu.css @@ -89,8 +89,8 @@ Original by Dempfi (https://github.com/dempfi/ayu) --crate-search-div-hover-filter: invert(98%) sepia(12%) saturate(81%) hue-rotate(343deg) brightness(113%) contrast(76%); --crate-search-hover-border: #e0e0e0; - --source-sidebar-background-selected: #14191f; - --source-sidebar-background-hover: #14191f; + --src-sidebar-background-selected: #14191f; + --src-sidebar-background-hover: #14191f; --table-alt-row-background-color: #191f26; --codeblock-link-background: #333; --scrape-example-toggle-line-background: #999; @@ -107,7 +107,7 @@ Original by Dempfi (https://github.com/dempfi/ayu) h1, h2, h3, h4, h1 a, .sidebar h2 a, .sidebar h3 a, -#source-sidebar > .title { +#src-sidebar > .title { color: #fff; } h4 { @@ -124,15 +124,15 @@ h4 { .docblock pre > code, pre, pre > code, .item-info code, -.rustdoc.source .example-wrap { +.rustdoc.src .example-wrap { color: #e6e1cf; } .sidebar .current, .sidebar a:hover, -#source-sidebar div.files > a:hover, details.dir-entry summary:hover, -#source-sidebar div.files > a:focus, details.dir-entry summary:focus, -#source-sidebar div.files > a.selected { +#src-sidebar div.files > a:hover, details.dir-entry summary:hover, +#src-sidebar div.files > a:focus, details.dir-entry summary:focus, +#src-sidebar div.files > a.selected { color: #ffb44c; } diff --git a/src/librustdoc/html/static/css/themes/dark.css b/src/librustdoc/html/static/css/themes/dark.css index 3c1186a5649..b653f61d536 100644 --- a/src/librustdoc/html/static/css/themes/dark.css +++ b/src/librustdoc/html/static/css/themes/dark.css @@ -84,8 +84,8 @@ --crate-search-div-hover-filter: invert(69%) sepia(60%) saturate(6613%) hue-rotate(184deg) brightness(100%) contrast(91%); --crate-search-hover-border: #2196f3; - --source-sidebar-background-selected: #333; - --source-sidebar-background-hover: #444; + --src-sidebar-background-selected: #333; + --src-sidebar-background-hover: #444; --table-alt-row-background-color: #2A2A2A; --codeblock-link-background: #333; --scrape-example-toggle-line-background: #999; diff --git a/src/librustdoc/html/static/css/themes/light.css b/src/librustdoc/html/static/css/themes/light.css index f8c287137de..6be25fc0544 100644 --- a/src/librustdoc/html/static/css/themes/light.css +++ b/src/librustdoc/html/static/css/themes/light.css @@ -81,8 +81,8 @@ --crate-search-div-hover-filter: invert(44%) sepia(18%) saturate(23%) hue-rotate(317deg) brightness(96%) contrast(93%); --crate-search-hover-border: #717171; - --source-sidebar-background-selected: #fff; - --source-sidebar-background-hover: #e0e0e0; + --src-sidebar-background-selected: #fff; + --src-sidebar-background-hover: #e0e0e0; --table-alt-row-background-color: #F5F5F5; --codeblock-link-background: #eee; --scrape-example-toggle-line-background: #ccc; diff --git a/src/librustdoc/html/static/js/source-script.js b/src/librustdoc/html/static/js/src-script.js index 6eb99136040..679c2341f02 100644 --- a/src/librustdoc/html/static/js/source-script.js +++ b/src/librustdoc/html/static/js/src-script.js @@ -1,5 +1,5 @@ // From rust: -/* global sourcesIndex */ +/* global srcIndex */ // Local js definitions: /* global addClass, getCurrentValue, onEachLazy, removeClass, browserSupportsHistoryApi */ @@ -74,11 +74,11 @@ function createDirEntry(elem, parent, fullPath, hasFoundFile) { function toggleSidebar() { const child = this.parentNode.children[0]; if (child.innerText === ">") { - addClass(document.documentElement, "source-sidebar-expanded"); + addClass(document.documentElement, "src-sidebar-expanded"); child.innerText = "<"; updateLocalStorage("source-sidebar-show", "true"); } else { - removeClass(document.documentElement, "source-sidebar-expanded"); + removeClass(document.documentElement, "src-sidebar-expanded"); child.innerText = ">"; updateLocalStorage("source-sidebar-show", "false"); } @@ -101,16 +101,16 @@ function createSidebarToggle() { return sidebarToggle; } -// This function is called from "source-files.js", generated in `html/render/write_shared.rs`. +// This function is called from "src-files.js", generated in `html/render/write_shared.rs`. // eslint-disable-next-line no-unused-vars -function createSourceSidebar() { +function createSrcSidebar() { const container = document.querySelector("nav.sidebar"); const sidebarToggle = createSidebarToggle(); container.insertBefore(sidebarToggle, container.firstChild); const sidebar = document.createElement("div"); - sidebar.id = "source-sidebar"; + sidebar.id = "src-sidebar"; let hasFoundFile = false; @@ -118,9 +118,9 @@ function createSourceSidebar() { title.className = "title"; title.innerText = "Files"; sidebar.appendChild(title); - Object.keys(sourcesIndex).forEach(key => { - sourcesIndex[key][NAME_OFFSET] = key; - hasFoundFile = createDirEntry(sourcesIndex[key], sidebar, "", hasFoundFile); + Object.keys(srcIndex).forEach(key => { + srcIndex[key][NAME_OFFSET] = key; + hasFoundFile = createDirEntry(srcIndex[key], sidebar, "", hasFoundFile); }); container.appendChild(sidebar); @@ -133,7 +133,7 @@ function createSourceSidebar() { const lineNumbersRegex = /^#?(\d+)(?:-(\d+))?$/; -function highlightSourceLines(match) { +function highlightSrcLines(match) { if (typeof match === "undefined") { match = window.location.hash.match(lineNumbersRegex); } @@ -172,7 +172,7 @@ function highlightSourceLines(match) { } } -const handleSourceHighlight = (function() { +const handleSrcHighlight = (function() { let prev_line_id = 0; const set_fragment = name => { @@ -180,7 +180,7 @@ const handleSourceHighlight = (function() { y = window.scrollY; if (browserSupportsHistoryApi()) { history.replaceState(null, null, "#" + name); - highlightSourceLines(); + highlightSrcLines(); } else { location.replace("#" + name); } @@ -221,15 +221,15 @@ const handleSourceHighlight = (function() { window.addEventListener("hashchange", () => { const match = window.location.hash.match(lineNumbersRegex); if (match) { - return highlightSourceLines(match); + return highlightSrcLines(match); } }); onEachLazy(document.getElementsByClassName("src-line-numbers"), el => { - el.addEventListener("click", handleSourceHighlight); + el.addEventListener("click", handleSrcHighlight); }); -highlightSourceLines(); +highlightSrcLines(); -window.createSourceSidebar = createSourceSidebar; +window.createSrcSidebar = createSrcSidebar; })(); diff --git a/src/librustdoc/html/static/js/storage.js b/src/librustdoc/html/static/js/storage.js index 71961f6f2a9..af3ca42a6c0 100644 --- a/src/librustdoc/html/static/js/storage.js +++ b/src/librustdoc/html/static/js/storage.js @@ -185,7 +185,7 @@ updateTheme(); if (getSettingValue("source-sidebar-show") === "true") { // At this point in page load, `document.body` is not available yet. // Set a class on the `<html>` element instead. - addClass(document.documentElement, "source-sidebar-expanded"); + addClass(document.documentElement, "src-sidebar-expanded"); } // If we navigate away (for example to a settings page), and then use the back or diff --git a/src/librustdoc/html/static_files.rs b/src/librustdoc/html/static_files.rs index 767b974cc91..5d2e4b073c1 100644 --- a/src/librustdoc/html/static_files.rs +++ b/src/librustdoc/html/static_files.rs @@ -97,7 +97,7 @@ static_files! { main_js => "static/js/main.js", search_js => "static/js/search.js", settings_js => "static/js/settings.js", - source_script_js => "static/js/source-script.js", + src_script_js => "static/js/src-script.js", storage_js => "static/js/storage.js", scrape_examples_js => "static/js/scrape-examples.js", wheel_svg => "static/images/wheel.svg", diff --git a/src/librustdoc/html/templates/page.html b/src/librustdoc/html/templates/page.html index d4ec9c34b6f..60ccfe4da44 100644 --- a/src/librustdoc/html/templates/page.html +++ b/src/librustdoc/html/templates/page.html @@ -42,9 +42,9 @@ <script src="{{static_root_path|safe}}{{files.storage_js}}"></script> {# #} {% if page.css_class.contains("crate") %} <script defer src="{{page.root_path|safe}}crates{{page.resource_suffix}}.js"></script> {# #} - {% else if page.css_class == "source" %} - <script defer src="{{static_root_path|safe}}{{files.source_script_js}}"></script> {# #} - <script defer src="{{page.root_path|safe}}source-files{{page.resource_suffix}}.js"></script> {# #} + {% else if page.css_class == "src" %} + <script defer src="{{static_root_path|safe}}{{files.src_script_js}}"></script> {# #} + <script defer src="{{page.root_path|safe}}src-files{{page.resource_suffix}}.js"></script> {# #} {% else if !page.css_class.contains("mod") %} <script defer src="sidebar-items{{page.resource_suffix}}.js"></script> {# #} {% endif %} @@ -85,7 +85,7 @@ </div> {# #} <![endif]--> {# #} {{ layout.external_html.before_content|safe }} - {% if page.css_class != "source" %} + {% if page.css_class != "src" %} <nav class="mobile-topbar"> {# #} <button class="sidebar-menu-toggle">☰</button> {# #} <a class="logo-container" href="{{page.root_path|safe}}{{krate_with_trailing_slash|safe}}index.html"> {# #} @@ -99,7 +99,7 @@ </nav> {# #} {% endif %} <nav class="sidebar"> {# #} - {% if page.css_class != "source" %} + {% if page.css_class != "src" %} <a class="logo-container" href="{{page.root_path|safe}}{{krate_with_trailing_slash|safe}}index.html"> {# #} {% if !layout.logo.is_empty() %} <img src="{{layout.logo}}" alt="logo"> {# #} @@ -111,9 +111,9 @@ {{ sidebar|safe }} </nav> {# #} <main> {# #} - {% if page.css_class != "source" %}<div class="width-limiter">{% endif %} + {% if page.css_class != "src" %}<div class="width-limiter">{% endif %} <nav class="sub"> {# #} - {% if page.css_class == "source" %} + {% if page.css_class == "src" %} <a class="sub-logo-container" href="{{page.root_path|safe}}{{krate_with_trailing_slash|safe}}index.html"> {# #} {% if !layout.logo.is_empty() %} <img src="{{layout.logo}}" alt="logo"> {# #} @@ -144,7 +144,7 @@ </form> {# #} </nav> {# #} <section id="main-content" class="content">{{ content|safe }}</section> {# #} - {% if page.css_class != "source" %}</div>{% endif %} + {% if page.css_class != "src" %}</div>{% endif %} </main> {# #} {{ layout.external_html.after_content|safe }} </body> {# #} diff --git a/src/librustdoc/html/templates/print_item.html b/src/librustdoc/html/templates/print_item.html index 68a295ae095..1d215c26968 100644 --- a/src/librustdoc/html/templates/print_item.html +++ b/src/librustdoc/html/templates/print_item.html @@ -18,7 +18,7 @@ {% endif %} {% match src_href %} {% when Some with (href) %} - <a class="srclink" href="{{href|safe}}">source</a> · {#+ #} + <a class="src" href="{{href|safe}}">source</a> · {#+ #} {% else %} {% endmatch %} <button id="toggle-all-docs" title="collapse all docs"> {# #} diff --git a/src/librustdoc/lib.rs b/src/librustdoc/lib.rs index f28deae791a..36d087a7d5b 100644 --- a/src/librustdoc/lib.rs +++ b/src/librustdoc/lib.rs @@ -744,9 +744,6 @@ fn main_args(handler: &mut EarlyErrorHandler, at_args: &[String]) -> MainResult } }; - // Set parallel mode before error handler creation, which will create `Lock`s. - interface::set_thread_safe_mode(&options.unstable_opts); - let diag = core::new_handler( options.error_format, None, diff --git a/src/librustdoc/passes/check_doc_test_visibility.rs b/src/librustdoc/passes/check_doc_test_visibility.rs index b6cd897d317..1aa12e3ced2 100644 --- a/src/librustdoc/passes/check_doc_test_visibility.rs +++ b/src/librustdoc/passes/check_doc_test_visibility.rs @@ -106,8 +106,7 @@ pub(crate) fn should_have_doc_example(cx: &DocContext<'_>, item: &clean::Item) - } pub(crate) fn look_for_tests<'tcx>(cx: &DocContext<'tcx>, dox: &str, item: &Item) { - let Some(hir_id) = DocContext::as_local_hir_id(cx.tcx, item.item_id) - else { + let Some(hir_id) = DocContext::as_local_hir_id(cx.tcx, item.item_id) else { // If non-local, no need to check anything. return; }; diff --git a/src/librustdoc/passes/collect_intra_doc_links.rs b/src/librustdoc/passes/collect_intra_doc_links.rs index ca511d956b9..91f3729bfa2 100644 --- a/src/librustdoc/passes/collect_intra_doc_links.rs +++ b/src/librustdoc/passes/collect_intra_doc_links.rs @@ -298,7 +298,7 @@ impl<'a, 'tcx> LinkCollector<'a, 'tcx> { let ty_res = self.resolve_path(&path, TypeNS, item_id, module_id).ok_or_else(no_res)?; match ty_res { - Res::Def(DefKind::Enum, did) => match tcx.type_of(did).subst_identity().kind() { + Res::Def(DefKind::Enum, did) => match tcx.type_of(did).instantiate_identity().kind() { ty::Adt(def, _) if def.is_enum() => { if let Some(variant) = def.variants().iter().find(|v| v.name == variant_name) && let Some(field) = variant.fields.iter().find(|f| f.name == variant_field_name) { @@ -493,7 +493,7 @@ impl<'a, 'tcx> LinkCollector<'a, 'tcx> { /// This is used for resolving type aliases. fn def_id_to_res(&self, ty_id: DefId) -> Option<Res> { use PrimitiveType::*; - Some(match *self.cx.tcx.type_of(ty_id).subst_identity().kind() { + Some(match *self.cx.tcx.type_of(ty_id).instantiate_identity().kind() { ty::Bool => Res::Primitive(Bool), ty::Char => Res::Primitive(Char), ty::Int(ity) => Res::Primitive(ity.into()), @@ -601,7 +601,7 @@ impl<'a, 'tcx> LinkCollector<'a, 'tcx> { debug!("looking for associated item named {} for item {:?}", item_name, did); // Checks if item_name is a variant of the `SomeItem` enum if ns == TypeNS && def_kind == DefKind::Enum { - match tcx.type_of(did).subst_identity().kind() { + match tcx.type_of(did).instantiate_identity().kind() { ty::Adt(adt_def, _) => { for variant in adt_def.variants() { if variant.name == item_name { @@ -635,7 +635,7 @@ impl<'a, 'tcx> LinkCollector<'a, 'tcx> { // To handle that properly resolve() would have to support // something like [`ambi_fn`](<SomeStruct as SomeTrait>::ambi_fn) assoc_items = resolve_associated_trait_item( - tcx.type_of(did).subst_identity(), + tcx.type_of(did).instantiate_identity(), module_id, item_name, ns, @@ -671,7 +671,7 @@ impl<'a, 'tcx> LinkCollector<'a, 'tcx> { // they also look like associated items (`module::Type::Variant`), // because they are real Rust syntax (unlike the intra-doc links // field syntax) and are handled by the compiler's resolver. - let def = match tcx.type_of(did).subst_identity().kind() { + let def = match tcx.type_of(did).instantiate_identity().kind() { ty::Adt(def, _) if !def.is_enum() => def, _ => return Vec::new(), }; @@ -1610,8 +1610,7 @@ fn report_diagnostic( DiagnosticInfo { item, ori_link: _, dox, link_range }: &DiagnosticInfo<'_>, decorate: impl FnOnce(&mut Diagnostic, Option<rustc_span::Span>, MarkdownLinkRange), ) { - let Some(hir_id) = DocContext::as_local_hir_id(tcx, item.item_id) - else { + let Some(hir_id) = DocContext::as_local_hir_id(tcx, item.item_id) else { // If non-local, no need to check anything. info!("ignoring warning from parent crate: {}", msg); return; @@ -1811,7 +1810,7 @@ fn resolution_failure( Res::Primitive(_) => None, }; let is_struct_variant = |did| { - if let ty::Adt(def, _) = tcx.type_of(did).subst_identity().kind() + if let ty::Adt(def, _) = tcx.type_of(did).instantiate_identity().kind() && def.is_enum() && let Some(variant) = def.variants().iter().find(|v| v.name == res.name(tcx)) { // ctor is `None` if variant is a struct diff --git a/src/librustdoc/passes/collect_trait_impls.rs b/src/librustdoc/passes/collect_trait_impls.rs index fbf827cce09..ff89d4e0887 100644 --- a/src/librustdoc/passes/collect_trait_impls.rs +++ b/src/librustdoc/passes/collect_trait_impls.rs @@ -103,11 +103,11 @@ pub(crate) fn collect_trait_impls(mut krate: Crate, cx: &mut DocContext<'_>) -> // nothing to do with the inherent impl. // // Rustdoc currently uses these `impl` block as a source of - // the `Ty`, as well as the `ParamEnv`, `SubstsRef`, and + // the `Ty`, as well as the `ParamEnv`, `GenericArgsRef`, and // `Generics`. To avoid relying on the `impl` block, these // things would need to be created from wholecloth, in a // form that is valid for use in type inference. - let ty = tcx.type_of(def_id).subst_identity(); + let ty = tcx.type_of(def_id).instantiate_identity(); match ty.kind() { ty::Slice(ty) | ty::Ref(_, ty, _) diff --git a/src/librustdoc/passes/lint/bare_urls.rs b/src/librustdoc/passes/lint/bare_urls.rs index e9cee92d22b..5658b31d9bb 100644 --- a/src/librustdoc/passes/lint/bare_urls.rs +++ b/src/librustdoc/passes/lint/bare_urls.rs @@ -13,11 +13,10 @@ use std::mem; use std::sync::LazyLock; pub(super) fn visit_item(cx: &DocContext<'_>, item: &Item) { - let Some(hir_id) = DocContext::as_local_hir_id(cx.tcx, item.item_id) - else { - // If non-local, no need to check anything. - return; - }; + let Some(hir_id) = DocContext::as_local_hir_id(cx.tcx, item.item_id) else { + // If non-local, no need to check anything. + return; + }; let dox = item.doc_value(); if !dox.is_empty() { let report_diag = diff --git a/src/librustdoc/passes/lint/check_code_block_syntax.rs b/src/librustdoc/passes/lint/check_code_block_syntax.rs index f489f5081da..369a8069593 100644 --- a/src/librustdoc/passes/lint/check_code_block_syntax.rs +++ b/src/librustdoc/passes/lint/check_code_block_syntax.rs @@ -67,12 +67,11 @@ fn check_rust_syntax( return; } - let Some(local_id) = item.item_id.as_def_id().and_then(|x| x.as_local()) - else { - // We don't need to check the syntax for other crates so returning - // without doing anything should not be a problem. - return; - }; + let Some(local_id) = item.item_id.as_def_id().and_then(|x| x.as_local()) else { + // We don't need to check the syntax for other crates so returning + // without doing anything should not be a problem. + return; + }; let empty_block = code_block.lang_string == Default::default() && code_block.is_fenced; let is_ignore = code_block.lang_string.ignore != markdown::Ignore::None; diff --git a/src/librustdoc/passes/lint/html_tags.rs b/src/librustdoc/passes/lint/html_tags.rs index 5273f52bc6f..24f452b216c 100644 --- a/src/librustdoc/passes/lint/html_tags.rs +++ b/src/librustdoc/passes/lint/html_tags.rs @@ -14,7 +14,9 @@ pub(crate) fn visit_item(cx: &DocContext<'_>, item: &Item) { let tcx = cx.tcx; let Some(hir_id) = DocContext::as_local_hir_id(tcx, item.item_id) // If non-local, no need to check anything. - else { return }; + else { + return; + }; let dox = item.doc_value(); if !dox.is_empty() { let report_diag = |msg: String, range: &Range<usize>, is_open_tag: bool| { diff --git a/src/librustdoc/passes/propagate_doc_cfg.rs b/src/librustdoc/passes/propagate_doc_cfg.rs index 8a33e51b3be..95273a225a9 100644 --- a/src/librustdoc/passes/propagate_doc_cfg.rs +++ b/src/librustdoc/passes/propagate_doc_cfg.rs @@ -38,8 +38,9 @@ impl<'a, 'tcx> CfgPropagator<'a, 'tcx> { _ => return, }; - let Some(def_id) = item.item_id.as_def_id().and_then(|def_id| def_id.as_local()) - else { return }; + let Some(def_id) = item.item_id.as_def_id().and_then(|def_id| def_id.as_local()) else { + return; + }; if check_parent { let expected_parent = self.cx.tcx.opt_local_parent(def_id); diff --git a/src/librustdoc/scrape_examples.rs b/src/librustdoc/scrape_examples.rs index d2fa7769bbd..647d8358840 100644 --- a/src/librustdoc/scrape_examples.rs +++ b/src/librustdoc/scrape_examples.rs @@ -169,7 +169,7 @@ where }; let ident_span = path.ident.span; - (tcx.type_of(def_id).subst_identity(), call_span, ident_span) + (tcx.type_of(def_id).instantiate_identity(), call_span, ident_span) } _ => { return; diff --git a/src/stage0.json b/src/stage0.json index 89ad4e0a649..5f54504b8ea 100644 --- a/src/stage0.json +++ b/src/stage0.json @@ -17,419 +17,379 @@ "tool is executed." ], "compiler": { - "date": "2023-05-30", + "date": "2023-07-12", "version": "beta" }, "rustfmt": { - "date": "2023-05-30", + "date": "2023-07-13", "version": "nightly" }, "checksums_sha256": { - "dist/2023-05-30/cargo-beta-aarch64-apple-darwin.tar.gz": "ec0ef9ab4514f493675cf7c6c8539d29d4d9035813f3c2fe11df9f41cacb254f", - "dist/2023-05-30/cargo-beta-aarch64-apple-darwin.tar.xz": "1a9aa0848d79f7e8d13ed96e9df068a95c98056eaf569e1f5baa8ed02b1bd610", - "dist/2023-05-30/cargo-beta-aarch64-pc-windows-msvc.tar.gz": "4617ed30df22b2fc97b02d70bffd2f08e6bffacffee5f6f7bf73799372320802", - "dist/2023-05-30/cargo-beta-aarch64-pc-windows-msvc.tar.xz": "a7ea7ded3eceae4a3ffd21ab3b2af0e7e63e686e1d696508f05b764af5d071b0", - "dist/2023-05-30/cargo-beta-aarch64-unknown-linux-gnu.tar.gz": "05cd8f23b86bf8bf755d9300a344bcc6332398c81ec490a1afea8a3cfa489138", - "dist/2023-05-30/cargo-beta-aarch64-unknown-linux-gnu.tar.xz": "fc260df9c4fc721cf55edb2d10626b51232a566ccdf0fff76859542937aa8e3a", - "dist/2023-05-30/cargo-beta-aarch64-unknown-linux-musl.tar.gz": "be257b324db5f97e58d56c51c1da184689aeb53052731992454101abba5e69ba", - "dist/2023-05-30/cargo-beta-aarch64-unknown-linux-musl.tar.xz": "d12a3399e8a59121cd70620c735a2c3b33ca12d88db8b20f7f150f640ca2c3d6", - "dist/2023-05-30/cargo-beta-arm-unknown-linux-gnueabi.tar.gz": "f917a6722192bdac52994306033db82afa7aed3f7f0659bd3edfa125aad26286", - "dist/2023-05-30/cargo-beta-arm-unknown-linux-gnueabi.tar.xz": "d19e74b6dcca36100f667f752a3e61c0f4c0376f065d925dac1a04f35a2e2df7", - "dist/2023-05-30/cargo-beta-arm-unknown-linux-gnueabihf.tar.gz": "4ee94ac076f491a725cfb0bd1fd562e76ba0c877f1ab3964289a93cf4d50e907", - "dist/2023-05-30/cargo-beta-arm-unknown-linux-gnueabihf.tar.xz": "c054bece6c071b1c2633e59f7193e25ed3e29ab1b6cad5e62d9ec71304f92cc3", - "dist/2023-05-30/cargo-beta-armv7-unknown-linux-gnueabihf.tar.gz": "15ed708ecbf86769a5d3e64e2263f0c534db30f793ede9f4ea6e04fa6b462d5f", - "dist/2023-05-30/cargo-beta-armv7-unknown-linux-gnueabihf.tar.xz": "b11e35f7ccf65d9ee224d4695e0f769f52ed1e87f32221ab62a79d1e818dab88", - "dist/2023-05-30/cargo-beta-i686-pc-windows-gnu.tar.gz": "62509f8a6c096ea442ddfbc46c16942e905cfb5017b1cf85dc94f812da243bd2", - "dist/2023-05-30/cargo-beta-i686-pc-windows-gnu.tar.xz": "cfb63865159c01bfa1b4db6368219f255aacc9bbd94c2d04633cd705d53c6fbe", - "dist/2023-05-30/cargo-beta-i686-pc-windows-msvc.tar.gz": "81c5f9e12449ce7c7dca6a32ba18fa232df19085acf5650bfbed65e228c06b57", - "dist/2023-05-30/cargo-beta-i686-pc-windows-msvc.tar.xz": "acbac0d53c7ab771f3ae91c8461304ba811f8a067575c148e207311f425d694f", - "dist/2023-05-30/cargo-beta-i686-unknown-linux-gnu.tar.gz": "0bb73bb2d3abf4065cb559e022332c6ce9d6b2223c074b974fbc39450e46e345", - "dist/2023-05-30/cargo-beta-i686-unknown-linux-gnu.tar.xz": "11622821b4b11a02c9262daf4aa35aa2b71407362079557be604c72962175bf7", - "dist/2023-05-30/cargo-beta-loongarch64-unknown-linux-gnu.tar.gz": "1f7c1a3d0879d6a04396cc31ca2e41dde5f9ca8cef360c9c44b32b909f4e8d4c", - "dist/2023-05-30/cargo-beta-loongarch64-unknown-linux-gnu.tar.xz": "8952d2e179a80ee8257d89cfd417a6df50edc07c22c0d6e3ae55a7838cf51ba9", - "dist/2023-05-30/cargo-beta-mips-unknown-linux-gnu.tar.gz": "931a2f303b97bd21498e51370392e9ebc66d6cdbfaf537035245988781173b45", - "dist/2023-05-30/cargo-beta-mips-unknown-linux-gnu.tar.xz": "ce71db299106759857ba00ab57bc275bdb4817576a51333b8bfd6a9f1d7b8010", - "dist/2023-05-30/cargo-beta-mips64-unknown-linux-gnuabi64.tar.gz": "3f32c9a97da50ee98a2b60e8e3f5140941d12d3374a9926f169081d3b6ab6a51", - "dist/2023-05-30/cargo-beta-mips64-unknown-linux-gnuabi64.tar.xz": "568732ec25848560ed886d0742fcc5c84f6aef8dba16d530853aaddc3196553c", - "dist/2023-05-30/cargo-beta-mips64el-unknown-linux-gnuabi64.tar.gz": "b9dafe965f6ee947b57b70ceb7317d9996ed35c11c761be45194e0415d41fd05", - "dist/2023-05-30/cargo-beta-mips64el-unknown-linux-gnuabi64.tar.xz": "32226b19d7d6d46a99c7ca1b4d20e4228071ea9062bea564083633a2723c495e", - "dist/2023-05-30/cargo-beta-mipsel-unknown-linux-gnu.tar.gz": "69f8b8dccd7bce10f5c753b0e41f46ba6f29b32499a7b1e16ddcdfd9a592b5fa", - "dist/2023-05-30/cargo-beta-mipsel-unknown-linux-gnu.tar.xz": "95e7e39eef157e060dda4ed8613a78d1eba5065a1a8189d887a81a12ab432d27", - "dist/2023-05-30/cargo-beta-powerpc-unknown-linux-gnu.tar.gz": "613a81e9fec3814e4e5467dbcff0bb83e29b450733c4b36d8442fd2e8c5dc24a", - "dist/2023-05-30/cargo-beta-powerpc-unknown-linux-gnu.tar.xz": "2983b7fb28441408b53a49aeb3a7089c555460c31bb91b0a11d17f448c677de8", - "dist/2023-05-30/cargo-beta-powerpc64-unknown-linux-gnu.tar.gz": "e63195ba700e4ab778e772ca935c4d3e42ce18474f3180226d254b0874cb65f9", - "dist/2023-05-30/cargo-beta-powerpc64-unknown-linux-gnu.tar.xz": "eaaba4a4c35cdf30ba6225f652415312cf8d8a1d7edd2e4216f2379099b6d8c8", - "dist/2023-05-30/cargo-beta-powerpc64le-unknown-linux-gnu.tar.gz": "22c14003af58c489f07e52419edd2cfd50d8e2ed147a25f648855629d9f56478", - "dist/2023-05-30/cargo-beta-powerpc64le-unknown-linux-gnu.tar.xz": "2e513a599b7779dc37367e8ee28943b1568c296ba2b2e697f22b6cfabbb062c8", - "dist/2023-05-30/cargo-beta-riscv64gc-unknown-linux-gnu.tar.gz": "eb75f2008324c4956cc14989692904c20f412a30311a82f2a085516706f9e2a3", - "dist/2023-05-30/cargo-beta-riscv64gc-unknown-linux-gnu.tar.xz": "5cfe6a533005c70aaf14f86cdba51245272b0cb2c04a74a03da69744b18d40b8", - "dist/2023-05-30/cargo-beta-s390x-unknown-linux-gnu.tar.gz": "b37acb2fca2ec79e72f9ed5b87eba157a629ca1e3fa044d0caf6fd665451d09b", - "dist/2023-05-30/cargo-beta-s390x-unknown-linux-gnu.tar.xz": "cd590ac88ea46e6f347c1d433a3ffd661c4766504eae7197d06de69f3303ff07", - "dist/2023-05-30/cargo-beta-x86_64-apple-darwin.tar.gz": "a8db5d95e0d8ab4cfe323165abd423d17e1545d1b99bb2e8bf4b197ca2471e84", - "dist/2023-05-30/cargo-beta-x86_64-apple-darwin.tar.xz": "95ceb8066879807752f9f7a70aeb2e9d08991659f49d64249b04c2b1ea545ac6", - "dist/2023-05-30/cargo-beta-x86_64-pc-windows-gnu.tar.gz": "2971558e43ee1e6a8c6ce5277b902a537d7f6d31ce714702e89efc468cf8dfde", - "dist/2023-05-30/cargo-beta-x86_64-pc-windows-gnu.tar.xz": "6ad42cca05e6c752424c3725516e24e9b1051e201b3ef0c2e1d8ec2e44973717", - "dist/2023-05-30/cargo-beta-x86_64-pc-windows-msvc.tar.gz": "c5f0cf8ebd206dfc39c0c889ae8670a6b6b2fb55cdbfeee3ba8b2ec72daf6135", - "dist/2023-05-30/cargo-beta-x86_64-pc-windows-msvc.tar.xz": "90d13c515e737193858f48901d8f150c5528a09e2a1c8a08987140f2ad8fbc03", - "dist/2023-05-30/cargo-beta-x86_64-unknown-freebsd.tar.gz": "a183226ff05ac8d16baf03c81a9281f42e1de5a0b270b1592ba785397e4d32da", - "dist/2023-05-30/cargo-beta-x86_64-unknown-freebsd.tar.xz": "96984a716ac37b2888181b00939c975a544cdf21a0dc1db5bcd5b4468e28eeab", - "dist/2023-05-30/cargo-beta-x86_64-unknown-illumos.tar.gz": "997cc3167983b80bbd8d323a61d718022ff0fd9827299379166e7240b0fbb2ff", - "dist/2023-05-30/cargo-beta-x86_64-unknown-illumos.tar.xz": "6f1c276cfc53f17cae1e1fdf372275a39c60a3d4c543dbed553222557707c6e9", - "dist/2023-05-30/cargo-beta-x86_64-unknown-linux-gnu.tar.gz": "a5075bdb4ca1b4a5b5cc734a131277967a5a34c9915afa52e3275da60e87993b", - "dist/2023-05-30/cargo-beta-x86_64-unknown-linux-gnu.tar.xz": "417b88bae9f028c94ee0563baf421abf8a18ceffe35d731ad9736f71d6a1b34b", - "dist/2023-05-30/cargo-beta-x86_64-unknown-linux-musl.tar.gz": "495b66a5e9dd3987c02f004eb8e3515b84dc132b274e726df36359cc9974f4a9", - "dist/2023-05-30/cargo-beta-x86_64-unknown-linux-musl.tar.xz": "faeb090c8e1d15b20c256eb7b326de2375812ffc7984e8c11e28a0add3fddec5", - "dist/2023-05-30/cargo-beta-x86_64-unknown-netbsd.tar.gz": "adc9720e065861ff8aeeec8ffdc231161755e603301521982f6ef405d2d12c95", - "dist/2023-05-30/cargo-beta-x86_64-unknown-netbsd.tar.xz": "2def53546856b6cce7ddfce00329fe05be0f649f0b8421168fbab85d9c23715d", - "dist/2023-05-30/rust-std-beta-aarch64-apple-darwin.tar.gz": "ebd92098d173efea06a3e2d2edec299483fc77925427417e182800567ff6d642", - "dist/2023-05-30/rust-std-beta-aarch64-apple-darwin.tar.xz": "028c6269d40f8adf897b5e6b61387ce49cb1c2c82244965d48efa68ca71d74e1", - "dist/2023-05-30/rust-std-beta-aarch64-apple-ios-sim.tar.gz": "ea5654c6a23488e56c0b1c8c8c655c449bcadc9c3676db9ff37ef3fe742c4f9e", - "dist/2023-05-30/rust-std-beta-aarch64-apple-ios-sim.tar.xz": "9b0542cd5aa8ab4df51e41800e99563a8a3d6a202d32008a9166ba29d40c7ce5", - "dist/2023-05-30/rust-std-beta-aarch64-apple-ios.tar.gz": "ff1bd99fa25176ccb5fe5ef9dca6bf902094c6b6f2ba1985481c1a0fb58cbc7d", - "dist/2023-05-30/rust-std-beta-aarch64-apple-ios.tar.xz": "3009eb898a50aebf7fda060b5abf1098271061431f732542e2d1e2bd98e17f60", - "dist/2023-05-30/rust-std-beta-aarch64-linux-android.tar.gz": "15ee7baf5a04c9651abc176b3d6679104a395c128724256aadaaf1174d76dbab", - "dist/2023-05-30/rust-std-beta-aarch64-linux-android.tar.xz": "93ffc5e6252ba061966338ebae85c1addea410cb1c6cc34936c86376a4ae264b", - "dist/2023-05-30/rust-std-beta-aarch64-pc-windows-msvc.tar.gz": "c13e9ef9c5c2088f7b7d111861bc1c6e11b2e2e26e5e43f44fcdb1629f1a5183", - "dist/2023-05-30/rust-std-beta-aarch64-pc-windows-msvc.tar.xz": "e19e125a06f6c1cfe719cc2c1e1925609c315c368e95fd32d75ace3f1dfdad32", - "dist/2023-05-30/rust-std-beta-aarch64-unknown-fuchsia.tar.gz": "2d8e20471633b28d5fac2f443ddfce59f84c49e87065f6538924c4484054aa85", - "dist/2023-05-30/rust-std-beta-aarch64-unknown-fuchsia.tar.xz": "bec968d53659373451860525922b6833204e0e61efa192739d59fe64fc8fd8e1", - "dist/2023-05-30/rust-std-beta-aarch64-unknown-linux-gnu.tar.gz": "4092203bfab27e32bd3fe2254cb91cd70d332a613a1d2286fbe985036c6f96ea", - "dist/2023-05-30/rust-std-beta-aarch64-unknown-linux-gnu.tar.xz": "a288efac80a2692858669537daa6b2657470dc4124541654a22d9ff415ad0389", - "dist/2023-05-30/rust-std-beta-aarch64-unknown-linux-musl.tar.gz": "d4e1d2ccec8e8ff63f77ea678864d2ec569da5c8a7ae625b820827fd5b4bc193", - "dist/2023-05-30/rust-std-beta-aarch64-unknown-linux-musl.tar.xz": "a14a29b6d213a1e744d7e9273c674cc97de9266764ecdb62ec1b9ab7dc2c81be", - "dist/2023-05-30/rust-std-beta-aarch64-unknown-none-softfloat.tar.gz": "cc8facb1c53ee1cf734933fb997c3eee57a6a0ac2fec8af571e01ad01c09e023", - "dist/2023-05-30/rust-std-beta-aarch64-unknown-none-softfloat.tar.xz": "d84cac6b97e396bcb64f2c794f0b2ebe73217a07a46e2a85a8b6ce73ebf279ce", - "dist/2023-05-30/rust-std-beta-aarch64-unknown-none.tar.gz": "e119575ce29c103ca82134e216ae3a77b01252ca7348212bab36ccb5d785e6b0", - "dist/2023-05-30/rust-std-beta-aarch64-unknown-none.tar.xz": "21472aa2b47a16e479f8759bbd206090169586fb29ab0f976b47fc7bc62c81b8", - "dist/2023-05-30/rust-std-beta-aarch64-unknown-uefi.tar.gz": "699727b60d15a4386659c8679aa612455b4a57fbd0901172d7daa7fc5ca253a7", - "dist/2023-05-30/rust-std-beta-aarch64-unknown-uefi.tar.xz": "95949ba372aa947c1bac030805af76644a99d6098442054bada9278b5c8f0722", - "dist/2023-05-30/rust-std-beta-arm-linux-androideabi.tar.gz": "765a7f836bff1ed7b10816a0ace2cdeb0b9aa383fbaa90fd0fba203093b4255c", - "dist/2023-05-30/rust-std-beta-arm-linux-androideabi.tar.xz": "66b909b5a4e6a19f4b45ca5396353437da76a350c994696d25e5b617b54e7df6", - "dist/2023-05-30/rust-std-beta-arm-unknown-linux-gnueabi.tar.gz": "43f2e2230c405809115bac27ff1b344ec7da7e410728c88092e021688819aa61", - "dist/2023-05-30/rust-std-beta-arm-unknown-linux-gnueabi.tar.xz": "8eb6821edf96ad1ead828a95513e8ed8deafe1f1697cc965e6e9830175ce41a3", - "dist/2023-05-30/rust-std-beta-arm-unknown-linux-gnueabihf.tar.gz": "7fcc7ccc6d705636bbd37096707358eaeb192179409983a6c3681a2664446ef9", - "dist/2023-05-30/rust-std-beta-arm-unknown-linux-gnueabihf.tar.xz": "506f392a315b45d458111b30bc3d13b266a43ed1890418e8c85e02e9eb0cd284", - "dist/2023-05-30/rust-std-beta-arm-unknown-linux-musleabi.tar.gz": "6b42b38873821320ec597ec44767ec03d87068389a61360aa566347506ad2a8e", - "dist/2023-05-30/rust-std-beta-arm-unknown-linux-musleabi.tar.xz": "33324c183092e505b77a76a0ea6d0e169838dd76e96a8ad94b142843449ec9e3", - "dist/2023-05-30/rust-std-beta-arm-unknown-linux-musleabihf.tar.gz": "414e4834f232862cc6b371716f014a7384e23fa4d4997b25ca77ba03ce4acda3", - "dist/2023-05-30/rust-std-beta-arm-unknown-linux-musleabihf.tar.xz": "bf60815516d3dd2d4452de0985dd95a615b905789669dcfe225eb2fa6b26c3d8", - "dist/2023-05-30/rust-std-beta-armebv7r-none-eabi.tar.gz": "132fa87ff6c7d9a94871edbc2a9634f96bf16ea46b04978680ea25855530b9ab", - "dist/2023-05-30/rust-std-beta-armebv7r-none-eabi.tar.xz": "1c2d6404ac467cff3ffb2f440a807b35532d03469730131b53b4ddd9e7f43f57", - "dist/2023-05-30/rust-std-beta-armebv7r-none-eabihf.tar.gz": "92c3b59c2cd7324d27edb928292017f27a9e88d12a5e5cc66a851be35481a29a", - "dist/2023-05-30/rust-std-beta-armebv7r-none-eabihf.tar.xz": "b545ba9763df61d95faa14e59124fab46d09ae95707e9686f325459140abb950", - "dist/2023-05-30/rust-std-beta-armv5te-unknown-linux-gnueabi.tar.gz": "2accb0f63c0ffb0aa0db99c05e5eedee369348d2a571df1b87689225cdb61d44", - "dist/2023-05-30/rust-std-beta-armv5te-unknown-linux-gnueabi.tar.xz": "fae4c7f7549789f51c1ee7037fa6142ec8ace96d8438ed964bf15f9241948fab", - "dist/2023-05-30/rust-std-beta-armv5te-unknown-linux-musleabi.tar.gz": "414978972ee622cfaf64dfd4fbe3cb5ec5e2d8436f129a75283d98fadf17f595", - "dist/2023-05-30/rust-std-beta-armv5te-unknown-linux-musleabi.tar.xz": "abc1719b2b29ad091a11d9515e633dadb98a665fb209a47e291a490d4e79f6c9", - "dist/2023-05-30/rust-std-beta-armv7-linux-androideabi.tar.gz": "c1159cab2a4bbb24e2ab7135d449583dd0e2f1fb329b7420aea69b005c9556a9", - "dist/2023-05-30/rust-std-beta-armv7-linux-androideabi.tar.xz": "b37e60b73d802535e2832351a344c3180bfe931cd14a03df5ea8bee8bd2f3f3e", - "dist/2023-05-30/rust-std-beta-armv7-unknown-linux-gnueabi.tar.gz": "65b9809fcda771576c1586c239d5dfaf960c2968e4ba09473f4d304b2684eeb1", - "dist/2023-05-30/rust-std-beta-armv7-unknown-linux-gnueabi.tar.xz": "331788bfc44fdeb49d85ef84591c400b95f7939661a722aaf36728617b86ce6d", - "dist/2023-05-30/rust-std-beta-armv7-unknown-linux-gnueabihf.tar.gz": "b932fd571a95f97e9a5dac39c99cfe488f2d29f9e86e9e2821b16df33cabc6a3", - "dist/2023-05-30/rust-std-beta-armv7-unknown-linux-gnueabihf.tar.xz": "7427c8103ecb0d0cf3f211f8700f0cf2bf6969e982ff599c20de87027224a814", - "dist/2023-05-30/rust-std-beta-armv7-unknown-linux-musleabi.tar.gz": "1206cf83b0bdf96bb1fb2c074c4078f99242d6eb273321e8090ed2cedb760c14", - "dist/2023-05-30/rust-std-beta-armv7-unknown-linux-musleabi.tar.xz": "5f1ac81a4508e6f2fb9b931cb556cb2d45ebe88e90eeeb7c25690a0f9448a0e1", - "dist/2023-05-30/rust-std-beta-armv7-unknown-linux-musleabihf.tar.gz": "a833ab5f38416ee1d94565db936dd0f351ff4313456f6faecf581e07508080e5", - "dist/2023-05-30/rust-std-beta-armv7-unknown-linux-musleabihf.tar.xz": "ba7c2dc66a19a960bf4e914cc30f8c40cde435d4da11e4dc44208cb950c67892", - "dist/2023-05-30/rust-std-beta-armv7a-none-eabi.tar.gz": "34ca46fc29871e03490d17df73e55f250699204cfb1ea0d72427434212c4f7e6", - "dist/2023-05-30/rust-std-beta-armv7a-none-eabi.tar.xz": "d6b58d542f3219e5075794588c2183a7849530b6ea174dd8cdcf1cc289c4c13e", - "dist/2023-05-30/rust-std-beta-armv7r-none-eabi.tar.gz": "ff262f5ac8cb94feaccfac8715f6a97a1edbf59e8778add720ec356203e2f9b7", - "dist/2023-05-30/rust-std-beta-armv7r-none-eabi.tar.xz": "ae386368da77e529eeb40c1d123bca34b07d65cc359d790949f257a541abdf91", - "dist/2023-05-30/rust-std-beta-armv7r-none-eabihf.tar.gz": "26e123410afb4c0aa7c110c12d31ad00b99f6ffc042745de2bca34b86e04c685", - "dist/2023-05-30/rust-std-beta-armv7r-none-eabihf.tar.xz": "ce3400eba477600cc4675b7d91366ca80e82ce656b62f83cea532b60248ad7d8", - "dist/2023-05-30/rust-std-beta-asmjs-unknown-emscripten.tar.gz": "6874686cdc7e9d1842cf59c1d55570379cd0f3933da55683435b7b36178ca106", - "dist/2023-05-30/rust-std-beta-asmjs-unknown-emscripten.tar.xz": "1a8cf6d6d86101c84e456667d9bb9866039b81e833e6b7bdbc227e6af540fccf", - "dist/2023-05-30/rust-std-beta-i586-pc-windows-msvc.tar.gz": "7f121cf6edf07b54e731e863d5c3ec92da88e39e88057e96b07f31a1cc16cb8b", - "dist/2023-05-30/rust-std-beta-i586-pc-windows-msvc.tar.xz": "a3c8dd03a35b272045fffd57d773064556637241ecd83218c78d9f20c5200b12", - "dist/2023-05-30/rust-std-beta-i586-unknown-linux-gnu.tar.gz": "5a3475ae3f6974ff33e7372867e1cfd6c944dab4af52e4daabdd471d270effd0", - "dist/2023-05-30/rust-std-beta-i586-unknown-linux-gnu.tar.xz": "4f2c386aa8f2689f88069ac96a88eb72bd56c6f3d3f002e7dd095fba3d0cd8ca", - "dist/2023-05-30/rust-std-beta-i586-unknown-linux-musl.tar.gz": "2659f824119c5abff708e1e282915a291989a98eb7710676a24adfe52c851f93", - "dist/2023-05-30/rust-std-beta-i586-unknown-linux-musl.tar.xz": "07960cf2f28f52eaf8351573da0e3964481f0cfa5502ab5b5e3ea4ad535dcd6e", - "dist/2023-05-30/rust-std-beta-i686-linux-android.tar.gz": "ef4eea9c214eea6a4d1425fcee382f0553a66d6d17ce33c3949d7df24e76d1d8", - "dist/2023-05-30/rust-std-beta-i686-linux-android.tar.xz": "3e54d56aab895defcab4c31d7fa0ed731387fae0a5df4ed56511173a20f4ab9b", - "dist/2023-05-30/rust-std-beta-i686-pc-windows-gnu.tar.gz": "92b09c74bc552e01f68d0090316287026340c92bd8804cffd5d2bbbe44124822", - "dist/2023-05-30/rust-std-beta-i686-pc-windows-gnu.tar.xz": "2f96ceb5fed911b830553e354bcc47cc6f1983e22a4b1227e61983308e184457", - "dist/2023-05-30/rust-std-beta-i686-pc-windows-msvc.tar.gz": "2251b6cdd4d9d7cd2990efa1641e93ca8fb51e7228eb95305a468e61c4a53d3e", - "dist/2023-05-30/rust-std-beta-i686-pc-windows-msvc.tar.xz": "e4c00779bea04c7e5a2f859900325355d64e9ef6cfbc452a3a8e5fd20b440518", - "dist/2023-05-30/rust-std-beta-i686-unknown-freebsd.tar.gz": "b731321a1a2beddb2d64009e77b883d97e679bcca8ae454e9e5b33a72461c220", - "dist/2023-05-30/rust-std-beta-i686-unknown-freebsd.tar.xz": "2d99b9633fb37ad1f017539f65dbea5644b6d85a44e657a48f71766b306cc172", - "dist/2023-05-30/rust-std-beta-i686-unknown-linux-gnu.tar.gz": "1782c79086dff3dc53d15894a6c3bec8dd87f457fab73c472c302eded6258d10", - "dist/2023-05-30/rust-std-beta-i686-unknown-linux-gnu.tar.xz": "8eb6afcc2fe17a383212f24e09db66ce37e0662925039f87a47bb50f44d4b671", - "dist/2023-05-30/rust-std-beta-i686-unknown-linux-musl.tar.gz": "4890d5adbee68aaac44e23b84487a4db6a602438d14b046bca23193273130485", - "dist/2023-05-30/rust-std-beta-i686-unknown-linux-musl.tar.xz": "9b00cdfc7890ca8a169556b2af8b690f59a17b49f44669a64fb0a27e42ba45a2", - "dist/2023-05-30/rust-std-beta-i686-unknown-uefi.tar.gz": "f672aa10394ec1f4998a29fd4e871d5da4057de5a67ef1e88e99fbf044485572", - "dist/2023-05-30/rust-std-beta-i686-unknown-uefi.tar.xz": "5da375bff19cbd2b6c550514b5452005cb1cb19c29f41e3efbe1652b367ee9ee", - "dist/2023-05-30/rust-std-beta-loongarch64-unknown-linux-gnu.tar.gz": "e52febf6ff0bead6c72efdf5afbda8951a8a52ec87980fe42179d624b21b51fc", - "dist/2023-05-30/rust-std-beta-loongarch64-unknown-linux-gnu.tar.xz": "a1b218f627223d60c231441752ae1696612471e90a3367a471ffe367309ec4e3", - "dist/2023-05-30/rust-std-beta-mips-unknown-linux-gnu.tar.gz": "1cade6c46209e8cf605794d18c6c8a2d0cdfd81b154802f0e916f5b59688f77e", - "dist/2023-05-30/rust-std-beta-mips-unknown-linux-gnu.tar.xz": "98cbb0c41f140acea077cae5145a28153f0d5f06e6009cad73064365d3bc373b", - "dist/2023-05-30/rust-std-beta-mips-unknown-linux-musl.tar.gz": "cfaedf4168ab803720bccf508ff04fef073d5b73ab6d9a27aaa5473edfe85b2a", - "dist/2023-05-30/rust-std-beta-mips-unknown-linux-musl.tar.xz": "7a9b2ab5dd58f61c1656081d0606ab60fade1e3f7c2d91d40b6dbb8255359df1", - "dist/2023-05-30/rust-std-beta-mips64-unknown-linux-gnuabi64.tar.gz": "670990fab0d668344d8b0b67a7613415c1fe596f73b2bc800e2f8acefed5a447", - "dist/2023-05-30/rust-std-beta-mips64-unknown-linux-gnuabi64.tar.xz": "3fd409a760598d6b830f4469c474a2d50e0332886f5e90bd6d80960cb593f948", - "dist/2023-05-30/rust-std-beta-mips64-unknown-linux-muslabi64.tar.gz": "2d583489021ea04e11a1c19743c29f77622cb95102122d16cbc77d24d6e6de8c", - "dist/2023-05-30/rust-std-beta-mips64-unknown-linux-muslabi64.tar.xz": "4a340a6d2292256b2f370931b74490afc07570c58f95a5a97be6840c6a426e3e", - "dist/2023-05-30/rust-std-beta-mips64el-unknown-linux-gnuabi64.tar.gz": "7a19789581b82f31c90a83d604a2894e82ce309b26598b0acb028f8ba749aa39", - "dist/2023-05-30/rust-std-beta-mips64el-unknown-linux-gnuabi64.tar.xz": "2507a916346c53dd44dc590334630eacd5b4c5a57a240a936203a73b4e96d507", - "dist/2023-05-30/rust-std-beta-mips64el-unknown-linux-muslabi64.tar.gz": "4b676b406389acc80c61fe89dbf4f8439436c8ef5f2e4a7f36202a9a48ddd487", - "dist/2023-05-30/rust-std-beta-mips64el-unknown-linux-muslabi64.tar.xz": "83ad872a06bd1cace948d542e1a69210f550abe536d74b0dbf036cc02d7c05a1", - "dist/2023-05-30/rust-std-beta-mipsel-unknown-linux-gnu.tar.gz": "31bc6097eec7ac51e5e923199aec47fb129f34dc472b3ba3d2398c4481aaf12b", - "dist/2023-05-30/rust-std-beta-mipsel-unknown-linux-gnu.tar.xz": "68bffca2afe433a435e8712174efbd61b628e5dacdbf151713f7b43c67804e57", - "dist/2023-05-30/rust-std-beta-mipsel-unknown-linux-musl.tar.gz": "34520ba878f3ab24d86f965d7470292df65deed971d1a3f1b078c3e4b353ead3", - "dist/2023-05-30/rust-std-beta-mipsel-unknown-linux-musl.tar.xz": "8ef5dffe7ed584ea59a8d1114f15d1eeb2bd598239fb3d2bc3efbbbe3da36c44", - "dist/2023-05-30/rust-std-beta-nvptx64-nvidia-cuda.tar.gz": "2297e2cb62b5d1085318d19334f55277e547b0d7bed86a29f60859f5e029d259", - "dist/2023-05-30/rust-std-beta-nvptx64-nvidia-cuda.tar.xz": "3f012c0cc6c7adad8e08f40c697c0248938103e5a1949c07d1139ef3d5a8cf9d", - "dist/2023-05-30/rust-std-beta-powerpc-unknown-linux-gnu.tar.gz": "8438185ba380e24cdae232aad740e9cc580e2bc4eb4b4aacc006a66e3b846ea0", - "dist/2023-05-30/rust-std-beta-powerpc-unknown-linux-gnu.tar.xz": "c751381d33ada7720f3aa10a242a26055806e56cfbc2348c2f21fb2b767f46df", - "dist/2023-05-30/rust-std-beta-powerpc64-unknown-linux-gnu.tar.gz": "1923978ae0a1130fea64fa35ef3aa9c5808b8d8a4af89cd78e0a3edf448404b9", - "dist/2023-05-30/rust-std-beta-powerpc64-unknown-linux-gnu.tar.xz": "36481e7b876977c357c1171d2bf4641f55ca7df70288c5aae0e94bd37380928d", - "dist/2023-05-30/rust-std-beta-powerpc64le-unknown-linux-gnu.tar.gz": "965b9ee397d3ae5fe783c89e9b587dfbef1d3a572ad1503dfa997cb0016444ec", - "dist/2023-05-30/rust-std-beta-powerpc64le-unknown-linux-gnu.tar.xz": "5963b85d5e8e41d86fd6447ad99ba0a3b36d07657c935fbd810c259d1bb6ccc1", - "dist/2023-05-30/rust-std-beta-riscv32i-unknown-none-elf.tar.gz": "c38b5bce61132789809aaed43151739ccde285186d42882f411610170ab3bded", - "dist/2023-05-30/rust-std-beta-riscv32i-unknown-none-elf.tar.xz": "973389204e68468825084d29934c6d89ef3215563402cad62d0630764e0f7adf", - "dist/2023-05-30/rust-std-beta-riscv32imac-unknown-none-elf.tar.gz": "39153c0171d86611ebfe77f0cd2d26ae9a432910778b86163fcd29ef633ce8a3", - "dist/2023-05-30/rust-std-beta-riscv32imac-unknown-none-elf.tar.xz": "1f90107007322dd3167c0a11bf50ab3c939f52fee06ac8cf737891cef7be030e", - "dist/2023-05-30/rust-std-beta-riscv32imc-unknown-none-elf.tar.gz": "ea75cc8c20192334d3f22719fcd67343d64c04a64cb1750f2182548b34643368", - "dist/2023-05-30/rust-std-beta-riscv32imc-unknown-none-elf.tar.xz": "2c48229fa6c41d68535590f8993c0dc45325d890fadad0c6ebcc7a0afa1c77a4", - "dist/2023-05-30/rust-std-beta-riscv64gc-unknown-linux-gnu.tar.gz": "041dd4a64a699968a487c22893c11ef0944b6e920cdd23f2c904e3cfd847700b", - "dist/2023-05-30/rust-std-beta-riscv64gc-unknown-linux-gnu.tar.xz": "6a5558581221b88a4e99ba3231bb0c35445537b1e0f1f0b6e02345297df9f1ee", - "dist/2023-05-30/rust-std-beta-riscv64gc-unknown-none-elf.tar.gz": "08830dfee466dd7e295489c2ab2b954e4d88001f851a5c96ed19de158c594490", - "dist/2023-05-30/rust-std-beta-riscv64gc-unknown-none-elf.tar.xz": "2a0bd37a0250ecaebe522df54201dd0b70fadcac9df01dfd70f681fa27385627", - "dist/2023-05-30/rust-std-beta-riscv64imac-unknown-none-elf.tar.gz": "b7c82cdf881d8d5052e365cbeb1966bc4c59627692619642617d4cf9fc8dd02d", - "dist/2023-05-30/rust-std-beta-riscv64imac-unknown-none-elf.tar.xz": "da29b033566bb1f97a98851fba1b41818d4a3a41d65713e4f1644e0ff43e0ef0", - "dist/2023-05-30/rust-std-beta-s390x-unknown-linux-gnu.tar.gz": "731fdf689c118040eb79917fe194a7691f82b5c68246d99496f21fc8d095c6f2", - "dist/2023-05-30/rust-std-beta-s390x-unknown-linux-gnu.tar.xz": "a7dfdbc15fcf1311b813b0ca8fe07270b28d1b0e7a87bb64663aa3999367430b", - "dist/2023-05-30/rust-std-beta-sparc64-unknown-linux-gnu.tar.gz": "445d91c3240b79d86d48e47f3553a14375932c9751fe4c917357e34890b86830", - "dist/2023-05-30/rust-std-beta-sparc64-unknown-linux-gnu.tar.xz": "6fbcf8e4e09a93216053781c20d2879660cac129d078ed610cb1e6db72d9d59c", - "dist/2023-05-30/rust-std-beta-sparcv9-sun-solaris.tar.gz": "e45cece10a961fc046adf7721f920e592bc7c0c5c276bb55bfc6b6c8fb95486e", - "dist/2023-05-30/rust-std-beta-sparcv9-sun-solaris.tar.xz": "b3778ff0a994f38133e49a448c091e51fbfe90a3fcf4ddcf209a3b49bd9c1c8f", - "dist/2023-05-30/rust-std-beta-thumbv6m-none-eabi.tar.gz": "5625a51ff41dd444d32d653c329139c906edf26e20782765feaf0168b4fce643", - "dist/2023-05-30/rust-std-beta-thumbv6m-none-eabi.tar.xz": "4a2ca2f8f99f297fa2b17c423b8c850476fb80a2bd19e6fd914f2efa813e13c1", - "dist/2023-05-30/rust-std-beta-thumbv7em-none-eabi.tar.gz": "26189595572717cf9721394f4f604a7c81cc9066813bda81e0eb8508075d4510", - "dist/2023-05-30/rust-std-beta-thumbv7em-none-eabi.tar.xz": "f4f88f6a85761207a3c1496ce3cbd87608de99febc74e01ac0851577c33ec248", - "dist/2023-05-30/rust-std-beta-thumbv7em-none-eabihf.tar.gz": "246b7f137c982e32d3f80e34c8e26a4ff64072b8f01d012fede280a1c356ec0b", - "dist/2023-05-30/rust-std-beta-thumbv7em-none-eabihf.tar.xz": "14904ce77090bacee8727529a2cbefc14ec2ba21a94e90e15b04841e562c7100", - "dist/2023-05-30/rust-std-beta-thumbv7m-none-eabi.tar.gz": "d02b075118d4aa29e7a842c95b7f5fb7f438f8d11c8c6ef3059a812993862811", - "dist/2023-05-30/rust-std-beta-thumbv7m-none-eabi.tar.xz": "564352083d92236466aaa6742b0df362f6dca5ea30696ab0b7c68da7b2c1ea05", - "dist/2023-05-30/rust-std-beta-thumbv7neon-linux-androideabi.tar.gz": "6f339f2a9491ac5cfee317fbb6539a14b0f1d6cf6cc8ccf1091f3493bd5d3e06", - "dist/2023-05-30/rust-std-beta-thumbv7neon-linux-androideabi.tar.xz": "475593fcb658f7e01610c2aa9cbf76f3db7b1306c6697ea40626ae51dfab3b28", - "dist/2023-05-30/rust-std-beta-thumbv7neon-unknown-linux-gnueabihf.tar.gz": "fdb20a3f739747105e72718b2a2e79a23b2dc603153ad8feca51a4f6791edb22", - "dist/2023-05-30/rust-std-beta-thumbv7neon-unknown-linux-gnueabihf.tar.xz": "ed9fae43e824c70ecf1efde92a45a3c85781b2913597ed0d60e75c7410145968", - "dist/2023-05-30/rust-std-beta-thumbv8m.base-none-eabi.tar.gz": "68f91796bdc580170716ec00be393c939359657b6f5aeba7c3e88ca0d068f8b9", - "dist/2023-05-30/rust-std-beta-thumbv8m.base-none-eabi.tar.xz": "2c014f52137862b2e7355812aee142ace2b4770c25dadac8f8e99239d82d7ca3", - "dist/2023-05-30/rust-std-beta-thumbv8m.main-none-eabi.tar.gz": "d2b691c5a6b11b5489898673e3d69aaaeccd2b97b0856421b1aa5c91fd48c5af", - "dist/2023-05-30/rust-std-beta-thumbv8m.main-none-eabi.tar.xz": "ff61566f1d84d80c0263d58cb4016201e2694278bcd9233ca2cafd19c47fc61c", - "dist/2023-05-30/rust-std-beta-thumbv8m.main-none-eabihf.tar.gz": "04c29db24b00c9e377f22266ad0bdb3126febfb39a35f83143ec7e2e052cf7c2", - "dist/2023-05-30/rust-std-beta-thumbv8m.main-none-eabihf.tar.xz": "651a8fb666a1412bffe84d39e92e01ba3fea6687d92f90ba0e3a4bdfbcea8dc0", - "dist/2023-05-30/rust-std-beta-wasm32-unknown-emscripten.tar.gz": "f4ea3e81bbaa7e6569c18e0f111aeca8a5cbf565403f7c0fa9c2da0858ee9548", - "dist/2023-05-30/rust-std-beta-wasm32-unknown-emscripten.tar.xz": "14ac309023a66949fbd3110eb7f53035abb54f79711e848f382e2953a702eb5b", - "dist/2023-05-30/rust-std-beta-wasm32-unknown-unknown.tar.gz": "4bc81b56c91e6771154d30cdae66c8f09d5c1e47ead91e59a1d98c9c7f2eefa8", - "dist/2023-05-30/rust-std-beta-wasm32-unknown-unknown.tar.xz": "b32619fbbdd47c901c41f385b3a6c1766f5439d8f6fef36409e1a8ba4ad5d847", - "dist/2023-05-30/rust-std-beta-wasm32-wasi.tar.gz": "c505c26f333208c5b38229b4fcf60621748303ff23193254e321386348328afb", - "dist/2023-05-30/rust-std-beta-wasm32-wasi.tar.xz": "f2b675fc1f95c5c3cfc78e10ad9b1322d920d429ae98b47580b7a1a7536dbba1", - "dist/2023-05-30/rust-std-beta-x86_64-apple-darwin.tar.gz": "e58d900bf9a1fde7867470c2c87b41c8ba8cdcef6b9653899c53d21f7b16d43a", - "dist/2023-05-30/rust-std-beta-x86_64-apple-darwin.tar.xz": "4cf95d2f670c00906e89ed8539bc90a45f0398bae84916409a26ceedfbd5b9ad", - "dist/2023-05-30/rust-std-beta-x86_64-apple-ios.tar.gz": "a5f8ab9c9d2d4a71aacf2221e06494bbc0ff9076d3c7dadbd0d4473f6e900c79", - "dist/2023-05-30/rust-std-beta-x86_64-apple-ios.tar.xz": "b3d6b2795c0d50aa8f1665579f1e3a1e056071cd50f4a464863608739c8fa62b", - "dist/2023-05-30/rust-std-beta-x86_64-fortanix-unknown-sgx.tar.gz": "08157017fa1d7a64078a7b2a3e7662b0f76174de3bbd1ca80bed40ec5dcb7407", - "dist/2023-05-30/rust-std-beta-x86_64-fortanix-unknown-sgx.tar.xz": "0588ec9de11c46a0cb705690e2182fe5acfd0d33e71f29dde9798f9025c137e0", - "dist/2023-05-30/rust-std-beta-x86_64-linux-android.tar.gz": "9aa164600f3adfdcf369b23e69f9f5c81757f21b9fef1419bc06d2b9474e4120", - "dist/2023-05-30/rust-std-beta-x86_64-linux-android.tar.xz": "635c8d4edf68790079eacac7d5754fe7ab431787dd01ebec7184c03e65e78c4a", - "dist/2023-05-30/rust-std-beta-x86_64-pc-solaris.tar.gz": "622e359c4178cf626fe63f95164915ec4289c5898851a9282da9780b847e8414", - "dist/2023-05-30/rust-std-beta-x86_64-pc-solaris.tar.xz": "ab2b95f4104691d44d455f4e5391b187b712b632cd0ec11baf1d29291814d770", - "dist/2023-05-30/rust-std-beta-x86_64-pc-windows-gnu.tar.gz": "08f28724ee08b13705911c5c9be7773f8ac935329fa37548b8d46118fc5e244b", - "dist/2023-05-30/rust-std-beta-x86_64-pc-windows-gnu.tar.xz": "fa3fcd87e50aae6f1893b65b027ae6f705f7c42cba63cebfca1e49dd3c2af966", - "dist/2023-05-30/rust-std-beta-x86_64-pc-windows-msvc.tar.gz": "c208ad4e8ea70e45b6d76b7a88491a33f30f1415043a26ad96908faefdb37eb7", - "dist/2023-05-30/rust-std-beta-x86_64-pc-windows-msvc.tar.xz": "afa64e5bccb5138d86349f8564f82dcdcf009e7bd07121d193ead9864f2ca1f5", - "dist/2023-05-30/rust-std-beta-x86_64-sun-solaris.tar.gz": "e2d8fa74156623a3cdc944b1e0eb5683b661dbbecd779b5621777413d4918fb4", - "dist/2023-05-30/rust-std-beta-x86_64-sun-solaris.tar.xz": "2a75d1d8918febceaaaf8ea4c89827798099ab69063878a71afaef5ae17691bf", - "dist/2023-05-30/rust-std-beta-x86_64-unknown-freebsd.tar.gz": "24cf8f9bad86110308215d52aa9ac3b0dffb8640508e718d14ee9928fc68f59c", - "dist/2023-05-30/rust-std-beta-x86_64-unknown-freebsd.tar.xz": "0babdccec106b4cd20574c9722b36e407a1d028856989ff5e390172876ab3e28", - "dist/2023-05-30/rust-std-beta-x86_64-unknown-fuchsia.tar.gz": "0a983d8fe5aa649452f93cf4566d59b091d79da1e325f2da6b0844ef842f7a7c", - "dist/2023-05-30/rust-std-beta-x86_64-unknown-fuchsia.tar.xz": "7bf8fa91b5ecce8744e29a47740f52a57c8faf1fa4e125736103890189cc23b9", - "dist/2023-05-30/rust-std-beta-x86_64-unknown-illumos.tar.gz": "f90b0c2fb060f84b53052852478b474d587f8c51ff1750df5922f2ea8b66fe2f", - "dist/2023-05-30/rust-std-beta-x86_64-unknown-illumos.tar.xz": "6075598069ed92e26615e49bdc6f8c571d7f194462588b941f5479b0ab137994", - "dist/2023-05-30/rust-std-beta-x86_64-unknown-linux-gnu.tar.gz": "8c9a48ec0db55f07200bc73b292a5ee7a603b6b924eb4a1044609d854e820554", - "dist/2023-05-30/rust-std-beta-x86_64-unknown-linux-gnu.tar.xz": "0bcda45a340128c3e69ec0d10b08ea11edd764870e5a8fcd741a42949a025325", - "dist/2023-05-30/rust-std-beta-x86_64-unknown-linux-gnux32.tar.gz": "0f8b6583c8dc192253c480aee8c743013758b7ddfacb08e957c57d1feabd5824", - "dist/2023-05-30/rust-std-beta-x86_64-unknown-linux-gnux32.tar.xz": "a8086bb72e9ce9b9013dac6ea159fc15147a4d1658b5e11d9910f1486828796e", - "dist/2023-05-30/rust-std-beta-x86_64-unknown-linux-musl.tar.gz": "f801f8382e5439a98115c0ce8a1ead8acc983f01a09bb4c6ec3add9324f16334", - "dist/2023-05-30/rust-std-beta-x86_64-unknown-linux-musl.tar.xz": "69cb7620f271d64db234166fc9db37f4b5d60b6f4b9da43d02d21baa31c5da67", - "dist/2023-05-30/rust-std-beta-x86_64-unknown-netbsd.tar.gz": "2cf6c1f646286ecf2fe0a0e8f7eb079e7402dddb556273bc2d12be61b5ee6341", - "dist/2023-05-30/rust-std-beta-x86_64-unknown-netbsd.tar.xz": "0a4845f220640f00b3e0a1d0957050e0c7258867f6f8d6e174277d3659214d46", - "dist/2023-05-30/rust-std-beta-x86_64-unknown-none.tar.gz": "9a1fb11c9a5264232ba1ad2d3c89d1dfb9c135d000b812135932521932ba1b86", - "dist/2023-05-30/rust-std-beta-x86_64-unknown-none.tar.xz": "5598a18d71f1c82e796c136ba4d09b38e24e201ca199752959f0eb094cc49c30", - "dist/2023-05-30/rust-std-beta-x86_64-unknown-redox.tar.gz": "6ec43ffac6b70a67e08308d4869334131025c9acb0e2036a072e9e594ec46acd", - "dist/2023-05-30/rust-std-beta-x86_64-unknown-redox.tar.xz": "eb801580d8ea50d2f7a9a9d78d9a3c10bd3596c84740b3c8b610a86157942b50", - "dist/2023-05-30/rust-std-beta-x86_64-unknown-uefi.tar.gz": "051700f1977665f3b8119af984ece787ed84838d0ae0443bfd475d91d76f1202", - "dist/2023-05-30/rust-std-beta-x86_64-unknown-uefi.tar.xz": "1db1d6eff963a7d1667d1f5542de5484105d39436c0c502044222d7f749299ea", - "dist/2023-05-30/rustc-beta-aarch64-apple-darwin.tar.gz": "63ec87aa7b1d457171503247004d7d046dd951992ae175423986c55f7f44aaeb", - "dist/2023-05-30/rustc-beta-aarch64-apple-darwin.tar.xz": "aea483c5546a038aa6381cd458f9c43d5e2e5365f3d3a296ccd3e96f90bd3fdd", - "dist/2023-05-30/rustc-beta-aarch64-pc-windows-msvc.tar.gz": "35e4e8c6099820f63e46ae916d9c8aa3178164856a3cde479634f0837860bf3d", - "dist/2023-05-30/rustc-beta-aarch64-pc-windows-msvc.tar.xz": "7232af5edf68a4d93ba7a065f2cef5b36f43d6dae76c8141c4624dd25ac17230", - "dist/2023-05-30/rustc-beta-aarch64-unknown-linux-gnu.tar.gz": "c08cd6ee05e23bf777c47f8eb4a66feeb85b88175360720737d96789a82906d5", - "dist/2023-05-30/rustc-beta-aarch64-unknown-linux-gnu.tar.xz": "025108e1db08c5f908e36f7cc5965175a008561cefbddf313501fed7bf583a44", - "dist/2023-05-30/rustc-beta-aarch64-unknown-linux-musl.tar.gz": "d41cec2d6001c6dc8079f4cae54c720a10288c86f6cd8e1cd362df9688ddd975", - "dist/2023-05-30/rustc-beta-aarch64-unknown-linux-musl.tar.xz": "81ca14bd6bd18958c9c9dc27e32dabd2a2076120d860721663fbc7339d096986", - "dist/2023-05-30/rustc-beta-arm-unknown-linux-gnueabi.tar.gz": "260fc42ec007adac4e885feb978f32e2624f30a87f4d91c929c3932be0dbe53c", - "dist/2023-05-30/rustc-beta-arm-unknown-linux-gnueabi.tar.xz": "f4b3455e84d6174a3950410cb25e753d82332ce696f9be606e6b454c279034e1", - "dist/2023-05-30/rustc-beta-arm-unknown-linux-gnueabihf.tar.gz": "9f9447025db2233c4d97d92b35eae50b02db262c6b41898fa73599c245fef3e8", - "dist/2023-05-30/rustc-beta-arm-unknown-linux-gnueabihf.tar.xz": "0db7a3acc6c06a41ebe93b35c62f55dc8f2526fb41e1fe546fea7746505c37a1", - "dist/2023-05-30/rustc-beta-armv7-unknown-linux-gnueabihf.tar.gz": "843cbc007c36850a40f4e5f0b186b2b8bf84f74385272cc2dd3e748ecfd92181", - "dist/2023-05-30/rustc-beta-armv7-unknown-linux-gnueabihf.tar.xz": "d56d7f0be082fe314eb85640779600fb3b74bc0f3d412a4d2c26d40671d0b116", - "dist/2023-05-30/rustc-beta-i686-pc-windows-gnu.tar.gz": "e2f140b4f0682fd4725862daefde019e58b3033ce1d967ec2d75a578871a36ec", - "dist/2023-05-30/rustc-beta-i686-pc-windows-gnu.tar.xz": "2424c4a395970e4570bd9c76396986ab68b3b81de91abc9ebe9c723b6c076d8f", - "dist/2023-05-30/rustc-beta-i686-pc-windows-msvc.tar.gz": "401c558d7866ad3583ab2e193bf804cff46e465d8584e6b857748edb4ef6e9e3", - "dist/2023-05-30/rustc-beta-i686-pc-windows-msvc.tar.xz": "ff328d754f1219ce9cdc2208d4f0feeaf88a2f1eb10cb65217ad26132ecfa67a", - "dist/2023-05-30/rustc-beta-i686-unknown-linux-gnu.tar.gz": "04daee6f6de28ba19ad4a0bfb83e13833e436ef381f322b4442776df885c320c", - "dist/2023-05-30/rustc-beta-i686-unknown-linux-gnu.tar.xz": "9ea5210272aba4d012cf195e9b36756987962700cc16911de6b17455f4fec37b", - "dist/2023-05-30/rustc-beta-loongarch64-unknown-linux-gnu.tar.gz": "fb3a38a21abc89987606fcf970a748ec007b4eac2a780c9bfc78a24855dd5068", - "dist/2023-05-30/rustc-beta-loongarch64-unknown-linux-gnu.tar.xz": "be03d9685ef05f5f0a5c4d2f5d1abbb4168703641c47bf449b8cead28c660b36", - "dist/2023-05-30/rustc-beta-mips-unknown-linux-gnu.tar.gz": "51f8f6efcfc6c09e41fb1c7bf49316650aa6fc4fba6765e9eb0f0da218a327ae", - "dist/2023-05-30/rustc-beta-mips-unknown-linux-gnu.tar.xz": "724ac99cebbc5dfa8e5ca2d9f32c0611f0df035b9dcd79861d9c8b6151f36d17", - "dist/2023-05-30/rustc-beta-mips64-unknown-linux-gnuabi64.tar.gz": "897e21ad58b01784523a18eb3e96286b956c3d62c3f8876f9831dc22543fa0f1", - "dist/2023-05-30/rustc-beta-mips64-unknown-linux-gnuabi64.tar.xz": "fc72123993f195910034bbc99c8099b473f77ed15345b2a2cc45669680a157b1", - "dist/2023-05-30/rustc-beta-mips64el-unknown-linux-gnuabi64.tar.gz": "be642818250e94732c1f989568ea96a35befdf3be8ef5a8136de40880b9a86bf", - "dist/2023-05-30/rustc-beta-mips64el-unknown-linux-gnuabi64.tar.xz": "fdb42ce19f669f5a38021abb3d88edacf0d6220dd18521aa0427f683ec1ef003", - "dist/2023-05-30/rustc-beta-mipsel-unknown-linux-gnu.tar.gz": "47540dea37ba2885dcf8ab3456ac0e0bd193f3b40f81ea425e6acf2559a573a5", - "dist/2023-05-30/rustc-beta-mipsel-unknown-linux-gnu.tar.xz": "dacbb89acdf4fc587e2cccde96b14c113637f6691c1f5857322dd98b148b442f", - "dist/2023-05-30/rustc-beta-powerpc-unknown-linux-gnu.tar.gz": "7cf4ab6c270bea85e065b26883350173f703e266ae865e753ea45ec53775e042", - "dist/2023-05-30/rustc-beta-powerpc-unknown-linux-gnu.tar.xz": "4e06df0b3820503d92a4ef4782cdea2ed95b60ac4efa75e1736b8dcf360e865e", - "dist/2023-05-30/rustc-beta-powerpc64-unknown-linux-gnu.tar.gz": "50e5879a296bd61545d0ed2558a28e328ad9eef6df906ec8a6ab17e98c4fc053", - "dist/2023-05-30/rustc-beta-powerpc64-unknown-linux-gnu.tar.xz": "76e3e8028b6c03ece804984d3df4baf995cd09e50bebacf038fe389133f77f25", - "dist/2023-05-30/rustc-beta-powerpc64le-unknown-linux-gnu.tar.gz": "45070a86b9efe5a885c67dbb089a219aa7adb5b9ae7a37d115a37f75833ee598", - "dist/2023-05-30/rustc-beta-powerpc64le-unknown-linux-gnu.tar.xz": "02e957f9078c32d0504e15a688cefd50850428b0dad4f748a55ccba2a738c826", - "dist/2023-05-30/rustc-beta-riscv64gc-unknown-linux-gnu.tar.gz": "2ee8579fc0acd71b7a0ec40efecd7bd298e24c0453821c85d502e7eff4820ea1", - "dist/2023-05-30/rustc-beta-riscv64gc-unknown-linux-gnu.tar.xz": "758e35e9a4f1fcda8cd110cae717542768acf9f7cfef38bf8d75480b2b2e25db", - "dist/2023-05-30/rustc-beta-s390x-unknown-linux-gnu.tar.gz": "d3c0fbd03833f28500403d8f7f196989fa83a0c493c7c74d435c1c201912ecea", - "dist/2023-05-30/rustc-beta-s390x-unknown-linux-gnu.tar.xz": "d2a8e1690a1420dc3f55d43d7b190cda605f46a82882990e74157b98793e4fed", - "dist/2023-05-30/rustc-beta-x86_64-apple-darwin.tar.gz": "6f3d3069dc85d3d7e533904f79ebfa00e2276896ba469b75461c833aa3a1ac7a", - "dist/2023-05-30/rustc-beta-x86_64-apple-darwin.tar.xz": "b6e3b9eb821f861eb3c9f5687595fb9a8007f09b230f8eb38223903783658632", - "dist/2023-05-30/rustc-beta-x86_64-pc-windows-gnu.tar.gz": "cad6269683cc3b08ae9c0dff61ea9cee963d0654aaf60caaa4294fd8592a08a8", - "dist/2023-05-30/rustc-beta-x86_64-pc-windows-gnu.tar.xz": "b4cc887327b822c0dc5efb5c14e7f0d4539860f75f2af5f24755479db84b436b", - "dist/2023-05-30/rustc-beta-x86_64-pc-windows-msvc.tar.gz": "f6c7cb74987f13219e62389f99a409e998a340ffdd37e59b990fa5a2209d0fd5", - "dist/2023-05-30/rustc-beta-x86_64-pc-windows-msvc.tar.xz": "06b3fc13a7a0b938026bddbd08babb5c005f6ece5384aadf265710983243d561", - "dist/2023-05-30/rustc-beta-x86_64-unknown-freebsd.tar.gz": "635dfded9a7f4637af3ba390906f48f01ae1b426658bd7a7e8276db38c77fb3a", - "dist/2023-05-30/rustc-beta-x86_64-unknown-freebsd.tar.xz": "f385fe29efd16b08d8f0a7c71450a7880d640992d762f941468ecf57d6d6cd35", - "dist/2023-05-30/rustc-beta-x86_64-unknown-illumos.tar.gz": "832780952af4ff0b23b52e0654a68e314354b3a7ad6594aede927956172857d2", - "dist/2023-05-30/rustc-beta-x86_64-unknown-illumos.tar.xz": "262c369de160013c9a226fbeb3f2f351355ac76c7aec3dc9c4e3b85bdee7259f", - "dist/2023-05-30/rustc-beta-x86_64-unknown-linux-gnu.tar.gz": "08ec1e016baa2772f97dc4f51bad2fba9a31f4e78435ae62d0dc19751a1d79e3", - "dist/2023-05-30/rustc-beta-x86_64-unknown-linux-gnu.tar.xz": "6708643e5941765593ab043de8ebde6488473ea870ba863a3192e1a738b17ae2", - "dist/2023-05-30/rustc-beta-x86_64-unknown-linux-musl.tar.gz": "64cadba75ace2843303aba0c71dc1dfe27a7fe5bcf6dcbd0ba852b6b4b09eac8", - "dist/2023-05-30/rustc-beta-x86_64-unknown-linux-musl.tar.xz": "8357a30ac45ad29724adb68db201f05b9257de0712ffef2562ae9bbc7e2376e5", - "dist/2023-05-30/rustc-beta-x86_64-unknown-netbsd.tar.gz": "fb7e20647326cd2a9672d58c37f3e140c0072877f3d0a7fdfa3f728c0e1763e4", - "dist/2023-05-30/rustc-beta-x86_64-unknown-netbsd.tar.xz": "6eafb794492243f1a5698f3516f5c5813a9b4014693e46d2fcc6a20de7d3a58e", - "dist/2023-05-30/rustc-nightly-aarch64-apple-darwin.tar.gz": "237b8472a6b69ad9a3d07f28a4c8db5558774777d5f049e73f3ee47daf0ba8ff", - "dist/2023-05-30/rustc-nightly-aarch64-apple-darwin.tar.xz": "2bdb744db0e37fe83763742b4fdc8d8892a46a25620485cf3ef0241278aca7cc", - "dist/2023-05-30/rustc-nightly-aarch64-pc-windows-msvc.tar.gz": "ed67050963449f6f2ef9e64de33281cf689511aee424f345941793fcccbd9197", - "dist/2023-05-30/rustc-nightly-aarch64-pc-windows-msvc.tar.xz": "b90717f1d715a4488cfb95036521f21fbcf5b9f0b1c488ef44ac7854acfc9210", - "dist/2023-05-30/rustc-nightly-aarch64-unknown-linux-gnu.tar.gz": "cc459d7779d32fcf51f24fc365806446bf4f3c2b4614e59181dd0696eab48f01", - "dist/2023-05-30/rustc-nightly-aarch64-unknown-linux-gnu.tar.xz": "e2420872b825bd3930c426b9fd876ef1660aa7558e661175c03f5b07c1f91208", - "dist/2023-05-30/rustc-nightly-aarch64-unknown-linux-musl.tar.gz": "e1f1b869afa2554b2ae4981eaccf35329314161c8f427484dfb45852e6dd7e66", - "dist/2023-05-30/rustc-nightly-aarch64-unknown-linux-musl.tar.xz": "9f0813f8fa69d2422f234fe78c3672cf229dcaeebbd8aad83cc1242b2033c012", - "dist/2023-05-30/rustc-nightly-arm-unknown-linux-gnueabi.tar.gz": "91a0bec37e3660f14be05799c4ff5241e7b0baee6d38bcc6aba446209b984d37", - "dist/2023-05-30/rustc-nightly-arm-unknown-linux-gnueabi.tar.xz": "fe2798b1d67928cb05525faa420241fddacf828a6ecd07ef6374605bbb6eb07a", - "dist/2023-05-30/rustc-nightly-arm-unknown-linux-gnueabihf.tar.gz": "3906c8a388e57687d1bf13dcc6e22a51bc1af46bcc6731215477b80a446129fe", - "dist/2023-05-30/rustc-nightly-arm-unknown-linux-gnueabihf.tar.xz": "b1f20ad4a1ea551e5e34aeb6a159e66da03bfb6a2814e0a1f44c1676b579361c", - "dist/2023-05-30/rustc-nightly-armv7-unknown-linux-gnueabihf.tar.gz": "69c08682db15fd941c843950811b0f367854a5f6bfeff17a810f5b2536063e2b", - "dist/2023-05-30/rustc-nightly-armv7-unknown-linux-gnueabihf.tar.xz": "3fa01eb5238dcde32a33183d2022f8f81eb8bdfc29af837e581ccac796add69f", - "dist/2023-05-30/rustc-nightly-i686-pc-windows-gnu.tar.gz": "71af89dd66588905acc5491f837da118570180176a6f6d485e3f5585cfa308b6", - "dist/2023-05-30/rustc-nightly-i686-pc-windows-gnu.tar.xz": "790ba712d9b4adcc6ae5d3735386909e942ea570152a10ab4b460de5df04a7d8", - "dist/2023-05-30/rustc-nightly-i686-pc-windows-msvc.tar.gz": "211744f84b1e1f184b3c868c971967d0af434135dbf5445826c4a291b67ba890", - "dist/2023-05-30/rustc-nightly-i686-pc-windows-msvc.tar.xz": "bf3699f00cdfa130563e524513bf5b227ebf67f5807c1206bc642e69b6acd515", - "dist/2023-05-30/rustc-nightly-i686-unknown-linux-gnu.tar.gz": "0a16de5d417bd0c2d548e9389615137dbca6ec0c9f77c48e57af5cecc446fd6e", - "dist/2023-05-30/rustc-nightly-i686-unknown-linux-gnu.tar.xz": "a621cec29e1199050f533c671949164fe608ce1a2639645dec09f7c3a662afa0", - "dist/2023-05-30/rustc-nightly-loongarch64-unknown-linux-gnu.tar.gz": "4e9dd9734ebf981cbbc116b0dc29ab69957e8ee746aa25f71abc33553db2dc6b", - "dist/2023-05-30/rustc-nightly-loongarch64-unknown-linux-gnu.tar.xz": "78b5580e81ee5b5f327be718fd09bd0711271a8bba52efff1cd4ce68c4f5cd4f", - "dist/2023-05-30/rustc-nightly-mips-unknown-linux-gnu.tar.gz": "889308ffa2f866dc34327c0f20195e33a3c1e8124a19635918b0a8e5220ea56d", - "dist/2023-05-30/rustc-nightly-mips-unknown-linux-gnu.tar.xz": "74da26ff0692a4cb1c84f3cd42c9a8c756cb588eaa40cfbfc6dbc9cbc5f018e9", - "dist/2023-05-30/rustc-nightly-mips64-unknown-linux-gnuabi64.tar.gz": "1aec9abde4a1e9e042191b06848d262848c54b448ddba00c9c736207953140b3", - "dist/2023-05-30/rustc-nightly-mips64-unknown-linux-gnuabi64.tar.xz": "a046b49cb6ec60ecaa8ed60f6c77b60b3d0cfa76cfd7e48b6b2a808e4d8a8e51", - "dist/2023-05-30/rustc-nightly-mips64el-unknown-linux-gnuabi64.tar.gz": "e6dfbe2df31c26d0df8ae413f41705039bc41f567dc8f4e81b9e908a61157d08", - "dist/2023-05-30/rustc-nightly-mips64el-unknown-linux-gnuabi64.tar.xz": "b4285b27d8ee3325ce4cc3755182d159376fbe93aa14d3adfeb06b5fb20ebdce", - "dist/2023-05-30/rustc-nightly-mipsel-unknown-linux-gnu.tar.gz": "62de5f6093791c80744267f492a0ba58f998f3e826933a396e21efba7e88ea1d", - "dist/2023-05-30/rustc-nightly-mipsel-unknown-linux-gnu.tar.xz": "3240f8ffa7bef40dfb2a19a1029a4b5733403c9cc94bcf7f0a66e0134e2b93fe", - "dist/2023-05-30/rustc-nightly-powerpc-unknown-linux-gnu.tar.gz": "49f9fa5a9d3c07365a29d0dd0ac94df9ef8c7f9713724a39ade6040bb1a4a627", - "dist/2023-05-30/rustc-nightly-powerpc-unknown-linux-gnu.tar.xz": "285b2c228c4a37dc6f5ced5c585631e2166b43c0b76bb794139f0aa690013a13", - "dist/2023-05-30/rustc-nightly-powerpc64-unknown-linux-gnu.tar.gz": "bcd1c9b4d1efd109bf29b2005f35931b92f9675ced5b71a6dcfb10bac1ed87af", - "dist/2023-05-30/rustc-nightly-powerpc64-unknown-linux-gnu.tar.xz": "7f61eef3681bb1bcc285910e596c4e11c62aca0ed1d7eb9de75fa0822ca89ecb", - "dist/2023-05-30/rustc-nightly-powerpc64le-unknown-linux-gnu.tar.gz": "278473fbd38e2d395257f90bc84010e44ade32cb35a249fa0d32e92c174e9776", - "dist/2023-05-30/rustc-nightly-powerpc64le-unknown-linux-gnu.tar.xz": "215a805efcfc898e3ae7cfeda427e10d252434175d8eb70613664ac84c1e38ff", - "dist/2023-05-30/rustc-nightly-riscv64gc-unknown-linux-gnu.tar.gz": "3ba38b376d5c58324221466dddc95ce0917f7bcf6a7cca8c187ff999abd8f74d", - "dist/2023-05-30/rustc-nightly-riscv64gc-unknown-linux-gnu.tar.xz": "d52cba02774a256db1cd40ef3c9fee10431f8ef9a738553373474bb629d8c108", - "dist/2023-05-30/rustc-nightly-s390x-unknown-linux-gnu.tar.gz": "4dca59e9d10f07e60bb8f522f4b97c2a8de8e186679bdc8e85a105bfba80c38d", - "dist/2023-05-30/rustc-nightly-s390x-unknown-linux-gnu.tar.xz": "e0d07c8f2605600d88d901dc2837c01266d28064f57e1ba7a3946a59a249b37d", - "dist/2023-05-30/rustc-nightly-x86_64-apple-darwin.tar.gz": "aef9c49ef3496a23567eef639f54131fd54fdedc092d39d89c7da8e41f97b100", - "dist/2023-05-30/rustc-nightly-x86_64-apple-darwin.tar.xz": "c78201af204ed99ae67c5f8747a1495b58e6a2b2c92a9290e703553c0fc4820a", - "dist/2023-05-30/rustc-nightly-x86_64-pc-windows-gnu.tar.gz": "70ff64b7f28be159fec7e518d3787e836c1a7f5a88177742215e46269a29b4aa", - "dist/2023-05-30/rustc-nightly-x86_64-pc-windows-gnu.tar.xz": "939bf932d60e2d343d4e00bbc48e10eb57755de14729795bd6965cf23eed74f5", - "dist/2023-05-30/rustc-nightly-x86_64-pc-windows-msvc.tar.gz": "e20748dcca42a84031bf2eae7a61d3b0619c383dca274287824a15c982b42bf3", - "dist/2023-05-30/rustc-nightly-x86_64-pc-windows-msvc.tar.xz": "4687e53fcbe7487647b876b36efca97f9b83389f35d317a76b601d43edd54c00", - "dist/2023-05-30/rustc-nightly-x86_64-unknown-freebsd.tar.gz": "c662f8f489ec8be2ed2066140a7b40ef92ac393103e2de43a683918ec81c3ab1", - "dist/2023-05-30/rustc-nightly-x86_64-unknown-freebsd.tar.xz": "b350dd8bd95563cf9a422bac6fd4ac44d21186324a9cda4998e5b676c9646b7e", - "dist/2023-05-30/rustc-nightly-x86_64-unknown-illumos.tar.gz": "18396eaa0c44555bfd550018671a4ca07a2c890e08ab8a6e71e224256f01bc61", - "dist/2023-05-30/rustc-nightly-x86_64-unknown-illumos.tar.xz": "97af9014bdd6b758b7dfaacc868f91c62729ddc70f6b766f78926d46098dc610", - "dist/2023-05-30/rustc-nightly-x86_64-unknown-linux-gnu.tar.gz": "9bb5775dce7c5659ba983c1581290f3d29cab54e2e28fbeb0a89b076bce24969", - "dist/2023-05-30/rustc-nightly-x86_64-unknown-linux-gnu.tar.xz": "9a2bf45136801dbb04b2cb6f7db45b731ff38d9f285c55270a2399184a422e5e", - "dist/2023-05-30/rustc-nightly-x86_64-unknown-linux-musl.tar.gz": "355e65949a17cb71b582e3a3a51a4a68c25fa1f07c5d02604869d0e1a3e83274", - "dist/2023-05-30/rustc-nightly-x86_64-unknown-linux-musl.tar.xz": "afbd2923484621716ff241998b6c4c6c3d7023e00c1f1bf94ac15e3072c15c91", - "dist/2023-05-30/rustc-nightly-x86_64-unknown-netbsd.tar.gz": "d9d79bff98b3a5bd95aab8735a3656c494d2d275afbe313f1d1adececb82f1e0", - "dist/2023-05-30/rustc-nightly-x86_64-unknown-netbsd.tar.xz": "a92f1dea5d4f811bd81a297e6b45c5253948956fa835efcbfb3174ca45cbc812", - "dist/2023-05-30/rustfmt-nightly-aarch64-apple-darwin.tar.gz": "59b1ecc2a0cc0dd289f58e14ec8d812cba3906a486b53d991e9d61fb1aace497", - "dist/2023-05-30/rustfmt-nightly-aarch64-apple-darwin.tar.xz": "89c70ea18ce719c8171190cca97b3f5c641999ef54952b4f0f426c05c63af698", - "dist/2023-05-30/rustfmt-nightly-aarch64-pc-windows-msvc.tar.gz": "164378266ab65a8d6464e914ff2dca848d6f044362bc81c38b260e52e1856147", - "dist/2023-05-30/rustfmt-nightly-aarch64-pc-windows-msvc.tar.xz": "b44fdc2708def8e02cf7f39e228c6698c2e0eee217cc02d60ee731859826b544", - "dist/2023-05-30/rustfmt-nightly-aarch64-unknown-linux-gnu.tar.gz": "0d34a3f499eb7d2819090c4b923df26462d12f6261327a03a3df61af3346467f", - "dist/2023-05-30/rustfmt-nightly-aarch64-unknown-linux-gnu.tar.xz": "add3cde0b9771e78c35f9eae1d91fe1aec94e5b255e3d741c80916dabf23d214", - "dist/2023-05-30/rustfmt-nightly-aarch64-unknown-linux-musl.tar.gz": "95f05d6549a3618e49b1607a04f9814aa55cb393b8c662a67dbd0909b65d9e45", - "dist/2023-05-30/rustfmt-nightly-aarch64-unknown-linux-musl.tar.xz": "e4e8ab74aa90355142d16d677452a6b17b99fe2c26c3e7d19541c00d316a9a1c", - "dist/2023-05-30/rustfmt-nightly-arm-unknown-linux-gnueabi.tar.gz": "891fcd1496565388160c70030f098eae9725423a726d25cb95f81c8a5e9a7fd0", - "dist/2023-05-30/rustfmt-nightly-arm-unknown-linux-gnueabi.tar.xz": "330afd31d6ef259a73f365bd57c2c8cc27f972f475519b880065ef9bbbef4417", - "dist/2023-05-30/rustfmt-nightly-arm-unknown-linux-gnueabihf.tar.gz": "32087f3a53706c8daeea8ee80afb16e60968cd653404e7ed98322d998b83582d", - "dist/2023-05-30/rustfmt-nightly-arm-unknown-linux-gnueabihf.tar.xz": "e2fe133066904154fa773a4731efbf77d46631413b77beea6ecb8f3617b0dedb", - "dist/2023-05-30/rustfmt-nightly-armv7-unknown-linux-gnueabihf.tar.gz": "df28a8a4b90c71b9542f1327d3138d9b13caddd5bd7a3738b09aafa75480f20f", - "dist/2023-05-30/rustfmt-nightly-armv7-unknown-linux-gnueabihf.tar.xz": "c9dabd1e26f6c94e3a2162c02bd83cc6c80cf41f075d970480fd8fa6c94f170d", - "dist/2023-05-30/rustfmt-nightly-i686-pc-windows-gnu.tar.gz": "b3eaa34bc2441a227de9646a1f90480cb934592e919944e2feae31be0d048f1e", - "dist/2023-05-30/rustfmt-nightly-i686-pc-windows-gnu.tar.xz": "dd3efd26ddf45d4366fa6c6f024e0223329c378887b636be70d89951feeb223d", - "dist/2023-05-30/rustfmt-nightly-i686-pc-windows-msvc.tar.gz": "50c1f997d3b7b47f0eea36397252646fe97c484345afe3c08938915bf46b1286", - "dist/2023-05-30/rustfmt-nightly-i686-pc-windows-msvc.tar.xz": "8da362db734f58f99d3616b3a6d0e2e0976f634bc457143fd627993a2a43cd41", - "dist/2023-05-30/rustfmt-nightly-i686-unknown-linux-gnu.tar.gz": "bb6b790c57de3157370ec6dfb3d5c6a3e47d4a7f483d716c04ddeb6a1d370470", - "dist/2023-05-30/rustfmt-nightly-i686-unknown-linux-gnu.tar.xz": "e83bea6b615680a2d1aff31a0302fceefe970d4d801d61c76bb59d61e16235ba", - "dist/2023-05-30/rustfmt-nightly-loongarch64-unknown-linux-gnu.tar.gz": "3c45423d2fee0fb2218e80760910f0f3344f67cb867e746e2bc825f74a4dad35", - "dist/2023-05-30/rustfmt-nightly-loongarch64-unknown-linux-gnu.tar.xz": "c3fbb683e848927b800933799d93ce9f47e3712a650e0b2462830e91fd62ec2d", - "dist/2023-05-30/rustfmt-nightly-mips-unknown-linux-gnu.tar.gz": "f795bf82973e3d6ae90d5bfd17c3a2326dd91c787d5638fd5e0d3091fc2bd738", - "dist/2023-05-30/rustfmt-nightly-mips-unknown-linux-gnu.tar.xz": "404217de3ead2226ba192fc2ee3a9928653272dd1b05774ae735bdf2db9596e0", - "dist/2023-05-30/rustfmt-nightly-mips64-unknown-linux-gnuabi64.tar.gz": "f62319f4429680866c6c55c9928f864fcd478dd71b16909186aa9a14d6d4b4e6", - "dist/2023-05-30/rustfmt-nightly-mips64-unknown-linux-gnuabi64.tar.xz": "caf648cf2d71b67393ef068715f974f43aa6d80eb6a6040b31d496d64d31b12e", - "dist/2023-05-30/rustfmt-nightly-mips64el-unknown-linux-gnuabi64.tar.gz": "e11962a76505c523d210bafa0a87e10f09bf28350149a11091222678acef9b2b", - "dist/2023-05-30/rustfmt-nightly-mips64el-unknown-linux-gnuabi64.tar.xz": "daadb0973b1acded5fbc32ba2aa4974ff25ca2cd90afa5eaecdea51ef55bf154", - "dist/2023-05-30/rustfmt-nightly-mipsel-unknown-linux-gnu.tar.gz": "c501a1fd769e826eac68ba1bb14feb384236f7d87f5d3fe1d6f2373b0fb3f966", - "dist/2023-05-30/rustfmt-nightly-mipsel-unknown-linux-gnu.tar.xz": "c1af630b9367b3c93d5bec0a5b4d7c3befa0d3036ca3fdd5d453b04bb74e239c", - "dist/2023-05-30/rustfmt-nightly-powerpc-unknown-linux-gnu.tar.gz": "cbda874bd604c078fe023a3c4dd480cc537a3dfdf0bc5eb8f55a1e5a21691915", - "dist/2023-05-30/rustfmt-nightly-powerpc-unknown-linux-gnu.tar.xz": "d795e96e1303d1a0057aabc079b0258a54361bdcf2359b2c096966098e950e57", - "dist/2023-05-30/rustfmt-nightly-powerpc64-unknown-linux-gnu.tar.gz": "5b699b2d9c77548d4ada3847996e0f4cf94446cb553ad9447aca2673e99c4948", - "dist/2023-05-30/rustfmt-nightly-powerpc64-unknown-linux-gnu.tar.xz": "39d7f7df56f1c5a92b41ad2e40ab570bee861006cdf9b93aa11b967906c60828", - "dist/2023-05-30/rustfmt-nightly-powerpc64le-unknown-linux-gnu.tar.gz": "c745fd0580669e901d56e81050b6447e4cf7743da32e6ea95607511d9c3201d1", - "dist/2023-05-30/rustfmt-nightly-powerpc64le-unknown-linux-gnu.tar.xz": "b360a343cb0f9e36ca9fe03d77047d600a16907416fa1e5c0cb7a4611fc5c3f2", - "dist/2023-05-30/rustfmt-nightly-riscv64gc-unknown-linux-gnu.tar.gz": "5a98c28cc95008522ace67fd15a9e5d71b1b969f0ec2410aaadfeda618aed1be", - "dist/2023-05-30/rustfmt-nightly-riscv64gc-unknown-linux-gnu.tar.xz": "5197422b4ef7ce51777c020f74a5fb7edc01339fcb9b31bbf9781195639794fa", - "dist/2023-05-30/rustfmt-nightly-s390x-unknown-linux-gnu.tar.gz": "6f6acce9edb006b355770f3934eba4c15b10f205164e49c587b6f9e60924ed99", - "dist/2023-05-30/rustfmt-nightly-s390x-unknown-linux-gnu.tar.xz": "1e1ebec2d56706f37afaaa23ed940e8953b5207280e83bfd0acce4a149416911", - "dist/2023-05-30/rustfmt-nightly-x86_64-apple-darwin.tar.gz": "c1ea49dac64b7872dd194db925cda89efa596808d993dedacc8be042d529c2de", - "dist/2023-05-30/rustfmt-nightly-x86_64-apple-darwin.tar.xz": "ddf1cd4e32ce497187f79f34edf346f6db31e9d50d2cf1870fc1f2edfbadbcdd", - "dist/2023-05-30/rustfmt-nightly-x86_64-pc-windows-gnu.tar.gz": "cb5d566d5b6dc6f94cd7015ad1d8074edc0fdff67e4099df7adaf0251f729d8d", - "dist/2023-05-30/rustfmt-nightly-x86_64-pc-windows-gnu.tar.xz": "086ef160c92e5c3eaf887b2f28d54562e7916be4758b7b9798019f5aa23f02b1", - "dist/2023-05-30/rustfmt-nightly-x86_64-pc-windows-msvc.tar.gz": "5447f33f134487147df663680741f94e2d58c45495dee33e16052bacf74975de", - "dist/2023-05-30/rustfmt-nightly-x86_64-pc-windows-msvc.tar.xz": "78104f5ecb2ac790c3958a5331316580991c7a03f1258a72b7c43f660f955461", - "dist/2023-05-30/rustfmt-nightly-x86_64-unknown-freebsd.tar.gz": "e3da153242be44fd656f4bfe33371cf7b874e220698cedac207f14ce790c7a66", - "dist/2023-05-30/rustfmt-nightly-x86_64-unknown-freebsd.tar.xz": "cc9c83b6dade84d6dcf390701d7cbd2613915d9af68b08e68b9ff1d72e742248", - "dist/2023-05-30/rustfmt-nightly-x86_64-unknown-illumos.tar.gz": "e0d3aeb40a6139c56000d5b8a8693aafad105d05ccb8cebb026e383da59baae6", - "dist/2023-05-30/rustfmt-nightly-x86_64-unknown-illumos.tar.xz": "96981188f60cf8dc05a6b39788f0348b57d3972961b0a2d0b5759dbfc4c7d345", - "dist/2023-05-30/rustfmt-nightly-x86_64-unknown-linux-gnu.tar.gz": "dfed96134506c80e8c503719c7502310b17bee6d3c963764af9dc70c5721795f", - "dist/2023-05-30/rustfmt-nightly-x86_64-unknown-linux-gnu.tar.xz": "36fb2a16bba51b765be6c82b57fccc6664699d3e476d7cd3d56c71b80c6f2c78", - "dist/2023-05-30/rustfmt-nightly-x86_64-unknown-linux-musl.tar.gz": "b0ea71d0f3fb18f95fe0801261ff28e9b25ff9078d8cf1c2122ac515841af2ee", - "dist/2023-05-30/rustfmt-nightly-x86_64-unknown-linux-musl.tar.xz": "9f03b6aab46560698e507796541d0c0347c5bffb4fb984ea6c7dc73f479c8d81", - "dist/2023-05-30/rustfmt-nightly-x86_64-unknown-netbsd.tar.gz": "0c473e1e4cd1b8096e03f10d13f8e640e88a002ec798790c7423074ff49168c8", - "dist/2023-05-30/rustfmt-nightly-x86_64-unknown-netbsd.tar.xz": "6da959be0b1c6d1fb6e56ad88672ee817b8827b8210cefd897e5aca085b2c32d" + "dist/2023-07-12/cargo-beta-aarch64-apple-darwin.tar.gz": "2abd085e1805419ca8ae0227f7f974790beac8f4f0dcfaa6e57857f6b79a96b3", + "dist/2023-07-12/cargo-beta-aarch64-apple-darwin.tar.xz": "f28bfa89ae8b20a06a90fcb2a34840a8473c504986742ff111e4c0722507ce35", + "dist/2023-07-12/cargo-beta-aarch64-pc-windows-msvc.tar.gz": "50206cd7b01c9f978f433660c30de8b3f8799eb19ef371e88236065719732322", + "dist/2023-07-12/cargo-beta-aarch64-pc-windows-msvc.tar.xz": "6359961e60f32569af03bdddc0e6e996f0b22d124a3c21272a44c0e1cd5ce414", + "dist/2023-07-12/cargo-beta-aarch64-unknown-linux-gnu.tar.gz": "be5e354a88c9ca8cb696d7383670279d8933f1bf4bf1599a5c4f17d884b05707", + "dist/2023-07-12/cargo-beta-aarch64-unknown-linux-gnu.tar.xz": "6180ee4c1087044ba9e1c7b8ddc289b75824e34ed88dd153b63ee8674d8b3405", + "dist/2023-07-12/cargo-beta-aarch64-unknown-linux-musl.tar.gz": "9632cff665c36d62eeae355e9322c3bea2bc09efd6fadf49dca603bd54545c6f", + "dist/2023-07-12/cargo-beta-aarch64-unknown-linux-musl.tar.xz": "b91560ef397310ffd96179201b696b8eeb4713787174b37517aa043690740dbc", + "dist/2023-07-12/cargo-beta-arm-unknown-linux-gnueabi.tar.gz": "d0654b7f734262cd7d6bb8924a063f9f48f2510f8a5a58d050efba90fde40204", + "dist/2023-07-12/cargo-beta-arm-unknown-linux-gnueabi.tar.xz": "6271ded5e5e50697626d67f0d6faa54f0d0daa6aa61a3e98354c62a74f1bb87e", + "dist/2023-07-12/cargo-beta-arm-unknown-linux-gnueabihf.tar.gz": "6a9b804c6217f8a76d72fc10a7b9566d00c36dff5eb9df238c56bc7d26b4f0d0", + "dist/2023-07-12/cargo-beta-arm-unknown-linux-gnueabihf.tar.xz": "f2b67e0a7bd0b304f89e4b938c46c7551f34f40d87f0909a07363fcd903ab3b9", + "dist/2023-07-12/cargo-beta-armv7-unknown-linux-gnueabihf.tar.gz": "c0fbf9d4d7638dc4ae6cc5d136a69cbce0ec5c3c31bd8103a6e2783c27690b0d", + "dist/2023-07-12/cargo-beta-armv7-unknown-linux-gnueabihf.tar.xz": "cb67aea7aa1295d5bdfbfde784300b779a7bc350af864bc2ee8d7b268648c6e5", + "dist/2023-07-12/cargo-beta-i686-pc-windows-gnu.tar.gz": "4a4bfb185e226d1b6c310fc25ff5b13bab088fa4d98425b90878aa0446ee22bf", + "dist/2023-07-12/cargo-beta-i686-pc-windows-gnu.tar.xz": "d265ad80a372223d9c99a1d3232d379287d847ea1c3afde29f320d3950198e9b", + "dist/2023-07-12/cargo-beta-i686-pc-windows-msvc.tar.gz": "6c566bdb668e6ac7b068c285b7fe2e3cf7d0f4f065663165f2a9e4256b78e4cf", + "dist/2023-07-12/cargo-beta-i686-pc-windows-msvc.tar.xz": "c70d668d38fe9946a887ab18bb08ca74d2a8e36f6ead9d78deae55b532abef34", + "dist/2023-07-12/cargo-beta-i686-unknown-linux-gnu.tar.gz": "82d996b76d6ce55d64c82a33d3278c609bcbbef854c94d98cd4c5290958d542f", + "dist/2023-07-12/cargo-beta-i686-unknown-linux-gnu.tar.xz": "cf06a97a9e60e8936482da06a659f3eb4133d0ea3b5498e45b160fbd513e3d2e", + "dist/2023-07-12/cargo-beta-loongarch64-unknown-linux-gnu.tar.gz": "816c8112da3efdc27e8930944a6560ae8e8597755af22d8af4b2bbe910f08a93", + "dist/2023-07-12/cargo-beta-loongarch64-unknown-linux-gnu.tar.xz": "c59fc50e68d9d2afbc725ea420db701593bfa074abd7b97e3c7dfc676e0647b0", + "dist/2023-07-12/cargo-beta-powerpc-unknown-linux-gnu.tar.gz": "d7327116f5fc8ab665fdb086fda93af287de6ff91c2762e1867b0e40acda231a", + "dist/2023-07-12/cargo-beta-powerpc-unknown-linux-gnu.tar.xz": "24ec8fd09995c20e216b071c86405b0e3a1cd038c66700b47321188d09cb83a0", + "dist/2023-07-12/cargo-beta-powerpc64-unknown-linux-gnu.tar.gz": "f937ff68855c59bafb3412761cf8f6a0c0d91c9729000a4ea58eed53569803b3", + "dist/2023-07-12/cargo-beta-powerpc64-unknown-linux-gnu.tar.xz": "b51d94d00ce0af91a8abe2ea152b2331689fc1799d212c11ac4ca0fc4dca652c", + "dist/2023-07-12/cargo-beta-powerpc64le-unknown-linux-gnu.tar.gz": "5ed88bc49511d1e2496eab00ef4ea5677868113e83aac6e1e61fdb5b9f56f1b5", + "dist/2023-07-12/cargo-beta-powerpc64le-unknown-linux-gnu.tar.xz": "a5b9594e97947abba39877fb0e99bf329d5447e7a7d557dab994c24e381ced12", + "dist/2023-07-12/cargo-beta-riscv64gc-unknown-linux-gnu.tar.gz": "c269533aeec8a1cdc25e3a3057ea8c9da571d7f3617cba9f1fe0c4193ab38f70", + "dist/2023-07-12/cargo-beta-riscv64gc-unknown-linux-gnu.tar.xz": "7094f76b4f7d1d1d34a5214b531ccecca4b2ad09fb23b534d334bece2718c78c", + "dist/2023-07-12/cargo-beta-s390x-unknown-linux-gnu.tar.gz": "012a515e3acab001cd72ef38144edd0372a6d813912990dc5409f340bd4856e8", + "dist/2023-07-12/cargo-beta-s390x-unknown-linux-gnu.tar.xz": "fceb8dc2356b8dfa4009e60d8a0742c940553beed385a0b6ba1526fc329f36cc", + "dist/2023-07-12/cargo-beta-x86_64-apple-darwin.tar.gz": "5dd74b549dd46809b8f56d8ed5052303bd64b14f5583bc89379624f6a22836b4", + "dist/2023-07-12/cargo-beta-x86_64-apple-darwin.tar.xz": "f0b33f85cd5585e272a90736e3d188d7f53886a97a75aaae5f4d6dda85867baa", + "dist/2023-07-12/cargo-beta-x86_64-pc-windows-gnu.tar.gz": "be049bb6fc3f7b079b425ecd8fcbeae3cae29c8a32a290f70d5f2a7522d67b87", + "dist/2023-07-12/cargo-beta-x86_64-pc-windows-gnu.tar.xz": "b04f7c83691abcefb5fb985013ec8d98fe4ce773d0b3291127efb1b00a7ab08e", + "dist/2023-07-12/cargo-beta-x86_64-pc-windows-msvc.tar.gz": "c1b853dec72570534a64c7f94e0008057a2365b0f060d17b84bdef19080b6bbb", + "dist/2023-07-12/cargo-beta-x86_64-pc-windows-msvc.tar.xz": "146d305a0fc14a1b7bb6586dd3130d09b72d2497ddbc10c3e739444bded037ca", + "dist/2023-07-12/cargo-beta-x86_64-unknown-freebsd.tar.gz": "235948cf05dcfef80e21e66f5b08ddab18eb8f14b2ea8fcbeed22cdad8611868", + "dist/2023-07-12/cargo-beta-x86_64-unknown-freebsd.tar.xz": "28008794b923bb103f46a0a24bf66ce5f43a647ed5b4fefc649b8734a2f80ffb", + "dist/2023-07-12/cargo-beta-x86_64-unknown-illumos.tar.gz": "7d6a9f53a0e5758e7155c7cba0385c6ab7e0cee7f98a62172c108dca909a2188", + "dist/2023-07-12/cargo-beta-x86_64-unknown-illumos.tar.xz": "3314f50099b488cd027074241bde9fa0a12a6ca6f14afa9f0db5dd62080c318c", + "dist/2023-07-12/cargo-beta-x86_64-unknown-linux-gnu.tar.gz": "2632324d31641f783528bbfa98b6b16738d4ba59933a7919360bde5279092c5a", + "dist/2023-07-12/cargo-beta-x86_64-unknown-linux-gnu.tar.xz": "0057a55a30c38002b03c032a0f742dd326236f25b67b3c3d791661ef6f653c1b", + "dist/2023-07-12/cargo-beta-x86_64-unknown-linux-musl.tar.gz": "03b787105749e431e1c043fe7e019984a602a6a7ec382f78e1b960a5fe7466d9", + "dist/2023-07-12/cargo-beta-x86_64-unknown-linux-musl.tar.xz": "5ccf1875d484d41a8e6828f4c96d1915c644e99369dae73a161fd10a97937ff6", + "dist/2023-07-12/cargo-beta-x86_64-unknown-netbsd.tar.gz": "2df957be57157dc20ee4ec1434c5c8ef57b2f61d9ca681510f9cac397cd31f8d", + "dist/2023-07-12/cargo-beta-x86_64-unknown-netbsd.tar.xz": "5cecc38b971653fc6ae1f393080723350dde6e17597f2da6bb76788f23402bf4", + "dist/2023-07-12/rust-std-beta-aarch64-apple-darwin.tar.gz": "e6008a3c5b826be78f6dbde565c0b148339d7e37bec0adde575e91a065903955", + "dist/2023-07-12/rust-std-beta-aarch64-apple-darwin.tar.xz": "735118e8d1ab40d504e345e0b5d844b90d0b04689ff4f5dda9c6f141944eb9af", + "dist/2023-07-12/rust-std-beta-aarch64-apple-ios-sim.tar.gz": "7b930f3a915d98be424d7ccde639f0350cdfb97422367b8a336f5688704ecf35", + "dist/2023-07-12/rust-std-beta-aarch64-apple-ios-sim.tar.xz": "4dd1e2ff92a85a76108d2f90b37245f7851c214454386aed053b528a31d0f46b", + "dist/2023-07-12/rust-std-beta-aarch64-apple-ios.tar.gz": "8415958461754cb3f9e86e9f47f2bbd26395e89a9bbbc21dbc54572a59c72b24", + "dist/2023-07-12/rust-std-beta-aarch64-apple-ios.tar.xz": "e88fd506a62568b49a5be056e9aeb4a9db6833216cf68adafc24769b0942eb4a", + "dist/2023-07-12/rust-std-beta-aarch64-linux-android.tar.gz": "41489a5701378265ace4a15b7ea9107fc5579c0bc3967e075e4c8769d3b0ac61", + "dist/2023-07-12/rust-std-beta-aarch64-linux-android.tar.xz": "86bb3088f26f3fd9c83220ea6d39135fc002d36696dc15c56d754065b13105c3", + "dist/2023-07-12/rust-std-beta-aarch64-pc-windows-msvc.tar.gz": "621bfd6e6253f35fe78321f3f8f45cd2fb0e290502f4b659d75b9e401a5b06da", + "dist/2023-07-12/rust-std-beta-aarch64-pc-windows-msvc.tar.xz": "2fb251d461489dfa8721ef12ff212aa77fc9a0a6e6952c22cdb8ff36eee39fe2", + "dist/2023-07-12/rust-std-beta-aarch64-unknown-fuchsia.tar.gz": "879f1ab511497baeb614d263e6bcb105bd084c8aa190ffbdd565fd14c87c7a48", + "dist/2023-07-12/rust-std-beta-aarch64-unknown-fuchsia.tar.xz": "c40816547ad6ecac58c13c21540239c7ba87b4970a2bbc2f3d9c64aef1f22f82", + "dist/2023-07-12/rust-std-beta-aarch64-unknown-linux-gnu.tar.gz": "d53b23527d184087adb14574b4a1f2a4e1fa387a271c080af2c7aa96c0ef2033", + "dist/2023-07-12/rust-std-beta-aarch64-unknown-linux-gnu.tar.xz": "7122261bd5a72b8426d2325a88fda0983e24cf58882c24eea85ab9f8861fecf7", + "dist/2023-07-12/rust-std-beta-aarch64-unknown-linux-musl.tar.gz": "6b5326823ce3564f9f67db5d9193349df8001adec9849b7bdf01ea06b342f5b3", + "dist/2023-07-12/rust-std-beta-aarch64-unknown-linux-musl.tar.xz": "10a89967e1600ac7e857715c9d61991710b88dfa3da8b117fc5be2c2fac26859", + "dist/2023-07-12/rust-std-beta-aarch64-unknown-none-softfloat.tar.gz": "ddd5ed0c6aa3499f40e9ce18a43627f8e1f33be3ac056d109045d2df65128cca", + "dist/2023-07-12/rust-std-beta-aarch64-unknown-none-softfloat.tar.xz": "c6c61e5e2fe43ade33fb21683d382d4f101071e14dd18f4dec5b16b792b35850", + "dist/2023-07-12/rust-std-beta-aarch64-unknown-none.tar.gz": "1cff4acc6b0889450c00a67dec433f274c6f141bd047ff530f573d46a3bcaaff", + "dist/2023-07-12/rust-std-beta-aarch64-unknown-none.tar.xz": "1528aada81564d7359bc80f6c15e98e29d1685057ba83e57ef59952e870a1042", + "dist/2023-07-12/rust-std-beta-aarch64-unknown-uefi.tar.gz": "e2e2fc8f4b037fda67a80024b6fe73f5b616376b4def317ccd6e78e2b4776859", + "dist/2023-07-12/rust-std-beta-aarch64-unknown-uefi.tar.xz": "3ecfd0f3ecbd2bb5e4bbed886d127fa33893360f898041a384afef4629693dbd", + "dist/2023-07-12/rust-std-beta-arm-linux-androideabi.tar.gz": "0be665812e347a20cc097918e362904088afcc8b45c741b1da29f9e991d9c3d0", + "dist/2023-07-12/rust-std-beta-arm-linux-androideabi.tar.xz": "9a65ff8ec3a03afd1cf5bba933eaa602e3e9f29a003be9f8835b21c2e5b8d26a", + "dist/2023-07-12/rust-std-beta-arm-unknown-linux-gnueabi.tar.gz": "5e1387faf662f7c227b075cc5b860f064864a1ebd1ce85ab5840fb136f38ff69", + "dist/2023-07-12/rust-std-beta-arm-unknown-linux-gnueabi.tar.xz": "4bb9dc22d45b34620120ab5f4aacd2799181f4bb006f40a83cead84b582ed669", + "dist/2023-07-12/rust-std-beta-arm-unknown-linux-gnueabihf.tar.gz": "d7996b74fe236e453bff636361389f6183194784f4b997d144fd456d4b55257e", + "dist/2023-07-12/rust-std-beta-arm-unknown-linux-gnueabihf.tar.xz": "578a99158925d329a57b74d82524d3c97fef1d9a801c39f5b03366aa60d217a6", + "dist/2023-07-12/rust-std-beta-arm-unknown-linux-musleabi.tar.gz": "a02bbe42972483d2ff5b26e1948f9d5d3c9512019f5cba0514b57a248847afc3", + "dist/2023-07-12/rust-std-beta-arm-unknown-linux-musleabi.tar.xz": "37fcc7982aabbd77c76f1886feaac1fc87fc4a1ad35edb80a5be381c88f65125", + "dist/2023-07-12/rust-std-beta-arm-unknown-linux-musleabihf.tar.gz": "52622b53c8fa0d16090d59543432e7d531f7eb6812730b79aeb96a8d1c993290", + "dist/2023-07-12/rust-std-beta-arm-unknown-linux-musleabihf.tar.xz": "a5af3735e6337c79c45a1b0d538c3627cd89ddd4d5d40d75e711d86004dbfe8b", + "dist/2023-07-12/rust-std-beta-armebv7r-none-eabi.tar.gz": "8fd0e463083548198255142e617a726f2b6a055665e534755e8b879e420041fc", + "dist/2023-07-12/rust-std-beta-armebv7r-none-eabi.tar.xz": "2b407208e51a8f3f82ede1a98ec33d12345f3c7f2ae1ddf25232dcd30aca915e", + "dist/2023-07-12/rust-std-beta-armebv7r-none-eabihf.tar.gz": "57ea6af7f77135d9f5d8541139caa562d8901a167e77e3de0a75b427090a60ce", + "dist/2023-07-12/rust-std-beta-armebv7r-none-eabihf.tar.xz": "7a14e34060161073191d858c2450b5dd69d827261c6fc5f56a003753232bec32", + "dist/2023-07-12/rust-std-beta-armv5te-unknown-linux-gnueabi.tar.gz": "03d0ba0d24e07788aa7fb9c85515f82a697fb224a52a904f96970f8f329849e1", + "dist/2023-07-12/rust-std-beta-armv5te-unknown-linux-gnueabi.tar.xz": "fb55245b1c7e6f074d8120d7b28e25a6882a3ef8c8afe4c7601078f385644eda", + "dist/2023-07-12/rust-std-beta-armv5te-unknown-linux-musleabi.tar.gz": "d1fb9a2001db3060ceb6d6deb0e0f35db7da5d47b0d174c2f4d5ba9a82ad22f1", + "dist/2023-07-12/rust-std-beta-armv5te-unknown-linux-musleabi.tar.xz": "8e0ec621b890b455988a931bc8eabc96840faf2fc7b311776aa06a1b55a4f554", + "dist/2023-07-12/rust-std-beta-armv7-linux-androideabi.tar.gz": "96d01a8dc88041d804e33fcca5d64ca10503a855a394606533aacc1e142289e1", + "dist/2023-07-12/rust-std-beta-armv7-linux-androideabi.tar.xz": "75c42686a8f379f19971235855e24ae7ce0b5d91768c00532857d304f45e5cef", + "dist/2023-07-12/rust-std-beta-armv7-unknown-linux-gnueabi.tar.gz": "a097e5fdd835551e969c4e1d6cf767633d79101709362a9a26d3056bf8ecd32c", + "dist/2023-07-12/rust-std-beta-armv7-unknown-linux-gnueabi.tar.xz": "f056e2c6cbb40ba34598a60901c959b828d086a84ceba03f9eaa3d7f48b7c6c6", + "dist/2023-07-12/rust-std-beta-armv7-unknown-linux-gnueabihf.tar.gz": "1995003b8ef8ee5dbee66d46a1233d6fe0182ccb6b9c14c976cc40e5099324ef", + "dist/2023-07-12/rust-std-beta-armv7-unknown-linux-gnueabihf.tar.xz": "08d9e6293cd3a89d6e42b0939c668a58ac010603fd4eee9775dde468a33bd0dd", + "dist/2023-07-12/rust-std-beta-armv7-unknown-linux-musleabi.tar.gz": "092d13520760e9540663ffc08e17be223a815e2dd7c0899033fe6676edb74264", + "dist/2023-07-12/rust-std-beta-armv7-unknown-linux-musleabi.tar.xz": "9e7d6923f8c90c779767eb40a55ef958420737679a5065e2a5ca49a6e34dacc5", + "dist/2023-07-12/rust-std-beta-armv7-unknown-linux-musleabihf.tar.gz": "c232cde2921c0c2d1a0f8fab64ddcae2b7dd7ed5cbf180370ece302949826a88", + "dist/2023-07-12/rust-std-beta-armv7-unknown-linux-musleabihf.tar.xz": "7681e242675bb765a1aacd3c8ebc6894eeb709ce7d85e5ff94cd63e52eb4e989", + "dist/2023-07-12/rust-std-beta-armv7a-none-eabi.tar.gz": "4a777b4a7e8b157d78aaab73ae4e9185821a7887dbad68612db3b5bd7428729b", + "dist/2023-07-12/rust-std-beta-armv7a-none-eabi.tar.xz": "d823b49c8d4b2615223b68cf6b6ac22836551aa5c1df0f68e1336c2be7ffe7ec", + "dist/2023-07-12/rust-std-beta-armv7r-none-eabi.tar.gz": "12e8242d480dc45108e615cb5625a07b77054a88fff72dce51c313e57a3ec8ef", + "dist/2023-07-12/rust-std-beta-armv7r-none-eabi.tar.xz": "0cef6562f5ee0850fdfbf0be00e18a5643a951d169df00b4e068c932fe04b048", + "dist/2023-07-12/rust-std-beta-armv7r-none-eabihf.tar.gz": "71818e3855455bf6cc3fc2f04b7ebbf95e32f28f636d08d9513ab1be88aece49", + "dist/2023-07-12/rust-std-beta-armv7r-none-eabihf.tar.xz": "b4bcb177e8fb157e50b93e07144889127b218804ede359d542ccdb0a0fc8a4a0", + "dist/2023-07-12/rust-std-beta-asmjs-unknown-emscripten.tar.gz": "d16b2accc56ee37e2e527e0371a689530d30a6ff316bbb85664710419a5effca", + "dist/2023-07-12/rust-std-beta-asmjs-unknown-emscripten.tar.xz": "6b828e1b7941d6a9ed085051c378227c99ebc5b4899dfd222c368b2edaa6f7fd", + "dist/2023-07-12/rust-std-beta-i586-pc-windows-msvc.tar.gz": "d35e870fb7cda230cebf82d6e4241f0535e534c861fed1a5158f47f8a18bb33b", + "dist/2023-07-12/rust-std-beta-i586-pc-windows-msvc.tar.xz": "36404cc649e16efbdf0fb6afdf2130af1ab46618ee8130c431370be618d7e182", + "dist/2023-07-12/rust-std-beta-i586-unknown-linux-gnu.tar.gz": "682e74d110324cf0f53121f7b8ef0bd6e5bc355b2fd1d2eb183bee85d26a3bf0", + "dist/2023-07-12/rust-std-beta-i586-unknown-linux-gnu.tar.xz": "1ea30b0d14e7a5a82aee09b8e4ba87856158b31ec6b83e77929e2e9784698d43", + "dist/2023-07-12/rust-std-beta-i586-unknown-linux-musl.tar.gz": "b83d3652bd440b91ab2b145cd0ea3108203ccaa9beeea099220cd76d92a7f64f", + "dist/2023-07-12/rust-std-beta-i586-unknown-linux-musl.tar.xz": "ab78b6ca9136606d48afe42ce32e5a96cc07d4ea61856a500a9c7dd837983288", + "dist/2023-07-12/rust-std-beta-i686-linux-android.tar.gz": "5522933a886774ef4c490a8d928834d35c5a31b9066a8ec3b9b80de7d121dc37", + "dist/2023-07-12/rust-std-beta-i686-linux-android.tar.xz": "896cf7f6b611b676d40c9c20aafed11d7746a349a55658d03a8c6d197595006d", + "dist/2023-07-12/rust-std-beta-i686-pc-windows-gnu.tar.gz": "bcf7eca5717e3643a4f6a1ca4412bbf0466c0ffe0075eda441a0ed9060b0aacc", + "dist/2023-07-12/rust-std-beta-i686-pc-windows-gnu.tar.xz": "89fe6ed9068cb187eeb8c372dc04b7a10d6c9289d2374f0c59eaf6234fbd438b", + "dist/2023-07-12/rust-std-beta-i686-pc-windows-msvc.tar.gz": "8d381d2b4370a454793e66828e75a006093277e890d38e7e94582f094c390539", + "dist/2023-07-12/rust-std-beta-i686-pc-windows-msvc.tar.xz": "25f0bb9b88de1d2f54d1b42a23569dbcab7b37885f2b8a78665739352af9fbf7", + "dist/2023-07-12/rust-std-beta-i686-unknown-freebsd.tar.gz": "435e26724e1799d2330e4d5262ba2995c46d601917fa3d1e0afefe989903eebe", + "dist/2023-07-12/rust-std-beta-i686-unknown-freebsd.tar.xz": "87afb9db4d7f02e23ab7531fa57c574fedbf2b6232260006b59ef40bca15e06b", + "dist/2023-07-12/rust-std-beta-i686-unknown-linux-gnu.tar.gz": "ceb59a15be998cb908f1a59460475b569e02bedab180396713e0d8418d55c909", + "dist/2023-07-12/rust-std-beta-i686-unknown-linux-gnu.tar.xz": "3fcb9e8f60eeeba76558976ff06cdfd5ecbf2294c603af2398e044d2e04429e8", + "dist/2023-07-12/rust-std-beta-i686-unknown-linux-musl.tar.gz": "c6a77d8f3c9eb6ce6e91a7e8fad8fba84c8b13f4bce9e565a65b01f307c005ac", + "dist/2023-07-12/rust-std-beta-i686-unknown-linux-musl.tar.xz": "b01833d247e906c8b1e4c0c9ca5b4c37dd4166824693cc6d4a85ab881e482854", + "dist/2023-07-12/rust-std-beta-i686-unknown-uefi.tar.gz": "1ffc65c298d91782a9f2b772f82e411d8e164e0a245b1eb0e2f81382f378076d", + "dist/2023-07-12/rust-std-beta-i686-unknown-uefi.tar.xz": "68b511d1a3685ea45644a0d40f5b456cef34ba48719947789f7330984a027699", + "dist/2023-07-12/rust-std-beta-loongarch64-unknown-linux-gnu.tar.gz": "0cd83da690cb1870b77c918f029273cced0d03f204fa42c4eec8930e6fcea8ba", + "dist/2023-07-12/rust-std-beta-loongarch64-unknown-linux-gnu.tar.xz": "9e215a989ed9e2f1c4581c1f38c475564b46f6b90dde91b63b88290cb7866a48", + "dist/2023-07-12/rust-std-beta-mips-unknown-linux-musl.tar.gz": "e66d3f598c38536f2db2e42b8b231acddc04c3edbb017d37adfd77a3378bf6c3", + "dist/2023-07-12/rust-std-beta-mips-unknown-linux-musl.tar.xz": "f030f5412e912004239febcb88c8fc489a7d35b95c02b750ba582a7ff895b79a", + "dist/2023-07-12/rust-std-beta-mips64-unknown-linux-muslabi64.tar.gz": "903649d2da11a054ffbeb440beb5c0f668bbc4a3c8f931a47b559659aba0eacd", + "dist/2023-07-12/rust-std-beta-mips64-unknown-linux-muslabi64.tar.xz": "ef1656bf4bd5b1fb90fdd1348808b81fb4b6da470966864ba823979890a1bb31", + "dist/2023-07-12/rust-std-beta-mips64el-unknown-linux-muslabi64.tar.gz": "e2f37ad36fb7ec9d15a85c467ffb1af69a14f8a073a105e0341c5bf7f2feaa13", + "dist/2023-07-12/rust-std-beta-mips64el-unknown-linux-muslabi64.tar.xz": "fcd15fe90bfb887fef0a83d1371283a965edfef029924d060ea4775be83669ce", + "dist/2023-07-12/rust-std-beta-mipsel-unknown-linux-musl.tar.gz": "8025e30f46c2f350a028c32be6b07472b40ce0dce8b4339753eeee391ff1639e", + "dist/2023-07-12/rust-std-beta-mipsel-unknown-linux-musl.tar.xz": "430eba57898d01285ae9b4351e5fca4179d638501b8004a559b2aec9daeaac20", + "dist/2023-07-12/rust-std-beta-nvptx64-nvidia-cuda.tar.gz": "f87733ff046a233cb9e68793dc3fbdf04cf8f639d1ec8e80f78d495dd168ab9f", + "dist/2023-07-12/rust-std-beta-nvptx64-nvidia-cuda.tar.xz": "d5756b6d7852bfe305283ac59cff20985e94f85f03bbb1c220d8e1b28b93392f", + "dist/2023-07-12/rust-std-beta-powerpc-unknown-linux-gnu.tar.gz": "e193958bfd05581adc4e08599940f8dd77c565724c188bb331c61a1d2a030379", + "dist/2023-07-12/rust-std-beta-powerpc-unknown-linux-gnu.tar.xz": "497b919f34d29412406202724fb20500d22cbc838df05128bc259826b4698f6a", + "dist/2023-07-12/rust-std-beta-powerpc64-unknown-linux-gnu.tar.gz": "499a17483bc7fbfdb3bd234c683eda4cb8e5270deb43c66253ad265cb72df0a3", + "dist/2023-07-12/rust-std-beta-powerpc64-unknown-linux-gnu.tar.xz": "8d209a47b988c987c93c32066d2f80bfa522e23f172bf8ac7a9c166408e98136", + "dist/2023-07-12/rust-std-beta-powerpc64le-unknown-linux-gnu.tar.gz": "1795b4a2621f718915267eda5184d417406390490946f9295f3096322d4136cd", + "dist/2023-07-12/rust-std-beta-powerpc64le-unknown-linux-gnu.tar.xz": "facdc96f065df0dfe2396445b44ed640a4e9922220dfe5c79df93b650bb8c982", + "dist/2023-07-12/rust-std-beta-riscv32i-unknown-none-elf.tar.gz": "fe297caa7916f58c7483103ee88641f02c75955e652b262e35b0f53efe3163d0", + "dist/2023-07-12/rust-std-beta-riscv32i-unknown-none-elf.tar.xz": "f0c06945c158f4613e336420c869c1b4f35d1a867c11dd227f9fee2f1b5dfaf3", + "dist/2023-07-12/rust-std-beta-riscv32imac-unknown-none-elf.tar.gz": "ef8c7b0bd6055cfbeafdf36e3569804d4513cf0bf9e49f0a621860c0f203160b", + "dist/2023-07-12/rust-std-beta-riscv32imac-unknown-none-elf.tar.xz": "96c16adbaddc9711e51ed1d626d4cc4c41f58b7e498987697b8f5177c577c2c6", + "dist/2023-07-12/rust-std-beta-riscv32imc-unknown-none-elf.tar.gz": "5835365c7ebf66026d5ca60aff4c161991f49b0bf7ac626d95a8bd28b04fe759", + "dist/2023-07-12/rust-std-beta-riscv32imc-unknown-none-elf.tar.xz": "07cf34b72aba65becbed5a0465f5b0a2154427100a8520af99d9b64af2ad8483", + "dist/2023-07-12/rust-std-beta-riscv64gc-unknown-linux-gnu.tar.gz": "8241523fbcfee63cd6c62c19b7198f0a6fe8038dd886eed410b05903739105c3", + "dist/2023-07-12/rust-std-beta-riscv64gc-unknown-linux-gnu.tar.xz": "78006dd24bf206104c0c2b1c54e8281234f6758ceff28fdbd5a39f280bd09bd4", + "dist/2023-07-12/rust-std-beta-riscv64gc-unknown-none-elf.tar.gz": "be35239b3c6f35d9616055f92c0cdd014d1b55d62424d4aaf8e42930b0ce9e25", + "dist/2023-07-12/rust-std-beta-riscv64gc-unknown-none-elf.tar.xz": "8f4bad99a3eefb9e46453425a48e47e6669e8ed1e3de3de07769e6faaca5af34", + "dist/2023-07-12/rust-std-beta-riscv64imac-unknown-none-elf.tar.gz": "2523a411d75ba8bd18aa41438039f5c27dc7eb62a0cfa8f3e625d2f50a2258ec", + "dist/2023-07-12/rust-std-beta-riscv64imac-unknown-none-elf.tar.xz": "6fbfc96c33502a4cc6484ed8899a9c9de011cb41f4656773f2a3b19b342ba6ac", + "dist/2023-07-12/rust-std-beta-s390x-unknown-linux-gnu.tar.gz": "c653216ff5ad0ffd50e7dfe5682c1ca51bbfa5d3bc8194cb8144ae80e617ead7", + "dist/2023-07-12/rust-std-beta-s390x-unknown-linux-gnu.tar.xz": "306f4a01fe16a5cf72fdc687bcb520b14e60b1b3b3bacb4a2073a2bda0714a1c", + "dist/2023-07-12/rust-std-beta-sparc64-unknown-linux-gnu.tar.gz": "ed071c2f96c5ef162aa7865ff4c45432c0a30bcf09311202b9a96d29102d98c7", + "dist/2023-07-12/rust-std-beta-sparc64-unknown-linux-gnu.tar.xz": "63a2579ef0aa3342f7998803705a6e574891e135090c85c9894f767dd60b780a", + "dist/2023-07-12/rust-std-beta-sparcv9-sun-solaris.tar.gz": "1dbf5fac46eff7e390e2577041c3c8f462e36eb0bf71f97e5273a934d4f99d08", + "dist/2023-07-12/rust-std-beta-sparcv9-sun-solaris.tar.xz": "81d66825005b0a501dddd22db16d7d783a7d1114a735c6734c447b469f67f1b3", + "dist/2023-07-12/rust-std-beta-thumbv6m-none-eabi.tar.gz": "e8a6fcd3fd68770ac582531ed12e9b11e4aac808c9ffd6eef2e15e01737717f8", + "dist/2023-07-12/rust-std-beta-thumbv6m-none-eabi.tar.xz": "08d11f9af0acbb3f01e8d36cd209f4164e1e7c0b1896add89e96d09895eb81f2", + "dist/2023-07-12/rust-std-beta-thumbv7em-none-eabi.tar.gz": "904f54943102586198c83d779102d5d913f35b743fc5258d7a435eb8a414faaa", + "dist/2023-07-12/rust-std-beta-thumbv7em-none-eabi.tar.xz": "80d4be9cee0123fdecf5f92a550323e4864b00800df5be48e7a5992330b09a9d", + "dist/2023-07-12/rust-std-beta-thumbv7em-none-eabihf.tar.gz": "9c887c04608167e70ac66c7ca28f2adcb5b3111cd308203cb91c1e3d54910d60", + "dist/2023-07-12/rust-std-beta-thumbv7em-none-eabihf.tar.xz": "0ae9f88cca6bafbb4fd6fcfa6c17550f0f478b38c8d061b276e10e5c8dc41510", + "dist/2023-07-12/rust-std-beta-thumbv7m-none-eabi.tar.gz": "9a6d40873beb20ea62a5a211cbec6df52dbb886b3c30d8b46086711c9d46f9ce", + "dist/2023-07-12/rust-std-beta-thumbv7m-none-eabi.tar.xz": "cdea56ba84ffdb31dde025073149e79a58f245f281a8cd2584c3032b649b8489", + "dist/2023-07-12/rust-std-beta-thumbv7neon-linux-androideabi.tar.gz": "dc7b75d01d002b0e373737b0cccd7be2d396dee45f3da5174bf7bf94ae492949", + "dist/2023-07-12/rust-std-beta-thumbv7neon-linux-androideabi.tar.xz": "c602afb2b5d6c4b6319f90297102c9d8c192e53e1b55a047c37b1d8280ce7100", + "dist/2023-07-12/rust-std-beta-thumbv7neon-unknown-linux-gnueabihf.tar.gz": "0af441e446e4f7b1dad0593eb91d0bff30698fe66b0355928f95d08044aab4f1", + "dist/2023-07-12/rust-std-beta-thumbv7neon-unknown-linux-gnueabihf.tar.xz": "3119430271c51189b66b2f033db32c6969f767985165270a9012a7535a89840e", + "dist/2023-07-12/rust-std-beta-thumbv8m.base-none-eabi.tar.gz": "87599a0c69951178be32f649f86a14c466771657d3d065e15749372daecc255b", + "dist/2023-07-12/rust-std-beta-thumbv8m.base-none-eabi.tar.xz": "a3dc1e688fa5bf81a5563831bf7a50b699392566da5dcdd35f773965c63d3c76", + "dist/2023-07-12/rust-std-beta-thumbv8m.main-none-eabi.tar.gz": "93056ded57a786931d0727c3c22a0e18c3939591848d1781b60d4235cb9a909d", + "dist/2023-07-12/rust-std-beta-thumbv8m.main-none-eabi.tar.xz": "a20c785842f9edcc85f7ded87c5c15de1ff96f9e268055ed4b9bcfa79034df93", + "dist/2023-07-12/rust-std-beta-thumbv8m.main-none-eabihf.tar.gz": "a2382c5801287d9657ef1bb1ed8032b3f43fe4d0541529ed31aba967ec93a1b9", + "dist/2023-07-12/rust-std-beta-thumbv8m.main-none-eabihf.tar.xz": "eaf0252d5ff159b8fd6788e63077ae1b87d7d529509d4c137452771477b8ff87", + "dist/2023-07-12/rust-std-beta-wasm32-unknown-emscripten.tar.gz": "d6f4ecbcfcdc8f67a2bd0fadb955d716cfc030f7d1af1d05d71a2fcc16a8fd6e", + "dist/2023-07-12/rust-std-beta-wasm32-unknown-emscripten.tar.xz": "1c7a720a53ef38055b23f078212d6fbfce39d715d4f12c2254d4ebd1c1cd1f4d", + "dist/2023-07-12/rust-std-beta-wasm32-unknown-unknown.tar.gz": "aa3c539b1ba267233b0310e5d8f8a97ed8a75ea6db96ff93fdcb4e7416be6609", + "dist/2023-07-12/rust-std-beta-wasm32-unknown-unknown.tar.xz": "dc3cbf54d1d46945e192d0f8b8d88cb77211d0d64d3f11a0d85b280d46dec35d", + "dist/2023-07-12/rust-std-beta-wasm32-wasi.tar.gz": "5731012231903dcf24ac529dcb3b08c598dc32857e3daefb636fdfd9c8e8cb83", + "dist/2023-07-12/rust-std-beta-wasm32-wasi.tar.xz": "5afac33b9009665436b2f522f6b26543f1287fd1972d6d3c3c74e2de8b1ef791", + "dist/2023-07-12/rust-std-beta-x86_64-apple-darwin.tar.gz": "30f925d5e75433e29e9448568bf4182902c02deb8eea53cc2645e1d530b8c327", + "dist/2023-07-12/rust-std-beta-x86_64-apple-darwin.tar.xz": "627d5378da2c26482f7461f82ec792987e67affafea079565b57bd86792058e7", + "dist/2023-07-12/rust-std-beta-x86_64-apple-ios.tar.gz": "db07a73405b8cc49c95c7d19c6a51e3aa88a1d7fda722e82e883efb12a763230", + "dist/2023-07-12/rust-std-beta-x86_64-apple-ios.tar.xz": "6ff23b2d7d8b0df0ea8475ca26775c094857166df94688595b6f0a5d58f8bdfa", + "dist/2023-07-12/rust-std-beta-x86_64-fortanix-unknown-sgx.tar.gz": "103628b332971a4ac1998ebb9dd8e258f78de85510e12b78e4d9e7c0e61e8747", + "dist/2023-07-12/rust-std-beta-x86_64-fortanix-unknown-sgx.tar.xz": "ce708d121273e40785975a5bca01fc1f51caf713ca1b5144e9aadd053f153ae7", + "dist/2023-07-12/rust-std-beta-x86_64-linux-android.tar.gz": "f949c2945a7458d2196d59b6f7fb15236182cfb0df20b7a07b3db63cd882915e", + "dist/2023-07-12/rust-std-beta-x86_64-linux-android.tar.xz": "d8106d2042e18ac1401e8735229adeaf24b276a3cfd2f9e8f9b67a14c2f64dd9", + "dist/2023-07-12/rust-std-beta-x86_64-pc-solaris.tar.gz": "b9e46bfa7576b0af27ce97106d8d243a5536de4e195c70a49c7df959c3c51f6d", + "dist/2023-07-12/rust-std-beta-x86_64-pc-solaris.tar.xz": "07489a82384a92becfc5ddfa1c2154613d32bed30409e64f520b06b52219a620", + "dist/2023-07-12/rust-std-beta-x86_64-pc-windows-gnu.tar.gz": "44c447c64aea3a471bcde4e2908c812e4f7cac949f29273037e42b1d19deef8a", + "dist/2023-07-12/rust-std-beta-x86_64-pc-windows-gnu.tar.xz": "c12b7a419935c6a6fc8fff4133e6abbc51ac579085e9ac503899ca0b65918d56", + "dist/2023-07-12/rust-std-beta-x86_64-pc-windows-msvc.tar.gz": "ae163e45e5470117db8c363badf7bafcb54755c016d7f83d04d969f63ba219a8", + "dist/2023-07-12/rust-std-beta-x86_64-pc-windows-msvc.tar.xz": "b64d506318824b764a0b5cf75768d4c1ca43773863c70aa73fb2d0df654d2690", + "dist/2023-07-12/rust-std-beta-x86_64-sun-solaris.tar.gz": "12bed740d7c0a3a5b2e85a8ae377ca97341e7eed5eb7d0b347a5d2ad362e5d21", + "dist/2023-07-12/rust-std-beta-x86_64-sun-solaris.tar.xz": "887930cc08da83c766ccdcc59bc6e983fff512dffedd911eaead1d4c5611dfab", + "dist/2023-07-12/rust-std-beta-x86_64-unknown-freebsd.tar.gz": "778967f9f2e2802970e9b24a8edefc815746a200eddca4c400c5c615b8eb98e9", + "dist/2023-07-12/rust-std-beta-x86_64-unknown-freebsd.tar.xz": "3b24a6ec9d65b2838d9985a210e6f9d39cd880830e03a90c472f6b2b9ff18e30", + "dist/2023-07-12/rust-std-beta-x86_64-unknown-fuchsia.tar.gz": "402b86e5b082e07c214023d412773c27733ac1493e5f559c52bbce7dc56c895b", + "dist/2023-07-12/rust-std-beta-x86_64-unknown-fuchsia.tar.xz": "571cee5f07dd3b4f053ef5f4e830bbae0ce2f95004e2ff13e029d27a7956b338", + "dist/2023-07-12/rust-std-beta-x86_64-unknown-illumos.tar.gz": "5bac95d69f03e59390023ed50084f20ee5ec2757a2890fc2486fe71cf7028d47", + "dist/2023-07-12/rust-std-beta-x86_64-unknown-illumos.tar.xz": "0a9a8fa23076619ec7e7ec60a293a46989cd0c7e4d3ef8ac76f5521747702ef2", + "dist/2023-07-12/rust-std-beta-x86_64-unknown-linux-gnu.tar.gz": "227fd782a16425da1d63b4475351764298859ddcc50a2786b4ab0126a63fe559", + "dist/2023-07-12/rust-std-beta-x86_64-unknown-linux-gnu.tar.xz": "2a7a6b36b2138daf5b97e307bd7f440d1b962f5c51a6bbec61f56b0bb909365d", + "dist/2023-07-12/rust-std-beta-x86_64-unknown-linux-gnux32.tar.gz": "a909474b87ff6abd09f4be16deb3210eec24cb1668eeddf1ffe683a542aa64e0", + "dist/2023-07-12/rust-std-beta-x86_64-unknown-linux-gnux32.tar.xz": "3ec154062ae28ecdb79cb2adb06db0acb9bc2633906318f9457b9e349a249237", + "dist/2023-07-12/rust-std-beta-x86_64-unknown-linux-musl.tar.gz": "108f9407bf5f7d2360d4d007a63792f1b5c2f03bf492cb553bcd36110d4f9ac6", + "dist/2023-07-12/rust-std-beta-x86_64-unknown-linux-musl.tar.xz": "8764f19bd2ee50000789433c9d1ba4771c3ed8f5f93d478998bb329013d4c1d0", + "dist/2023-07-12/rust-std-beta-x86_64-unknown-netbsd.tar.gz": "0c95d624aede0298da1e08e4ce65f358f34eabccc47903dda65298f70b3d08c1", + "dist/2023-07-12/rust-std-beta-x86_64-unknown-netbsd.tar.xz": "982bb81104b7ecfe0ef5a29e2e8047ba22691fea55449651b8cb2592798b34b1", + "dist/2023-07-12/rust-std-beta-x86_64-unknown-none.tar.gz": "023f68b3c2f26e2fe9d3bd8a176853c1ab7b82158d3c68181411bf9a3dbc02bf", + "dist/2023-07-12/rust-std-beta-x86_64-unknown-none.tar.xz": "b5203c4036b38d9bd41d87e662212b4a0dd2098f42ce016146ef781d864d5d16", + "dist/2023-07-12/rust-std-beta-x86_64-unknown-redox.tar.gz": "79c54bdd460dfce0be833185e27b698a18a50bc63706eed5ad6a55fd43f00cc3", + "dist/2023-07-12/rust-std-beta-x86_64-unknown-redox.tar.xz": "994752c9b73fa13fdda515296329e1b687dc98197401a5db4e93bdd00ef1a3a6", + "dist/2023-07-12/rust-std-beta-x86_64-unknown-uefi.tar.gz": "254008e9f38d1420d9f6c68563c0475ed26128cf7918749aae19054b658f5eea", + "dist/2023-07-12/rust-std-beta-x86_64-unknown-uefi.tar.xz": "63eb6b43d7c526413907af2ae261135ab6cd30ba6d82ba92fbca8c9df7dbfbb9", + "dist/2023-07-12/rustc-beta-aarch64-apple-darwin.tar.gz": "361629903acc59fd7b9e23381ba10adcbac9b2ac1f9fa8ac995a6b7b34c73a72", + "dist/2023-07-12/rustc-beta-aarch64-apple-darwin.tar.xz": "74d498d2cc984cd1dbef636b3feecb81adea0e7ba581b4b27364ec4f26a81f76", + "dist/2023-07-12/rustc-beta-aarch64-pc-windows-msvc.tar.gz": "be27c9217645d381c43014133e6654cd699bc3695310fcf3669d254d03c855c1", + "dist/2023-07-12/rustc-beta-aarch64-pc-windows-msvc.tar.xz": "54850fa60693e3b353ac186695eca1714d96bf4a26528bc221754a4ef41dcd13", + "dist/2023-07-12/rustc-beta-aarch64-unknown-linux-gnu.tar.gz": "ff73babf1ca49c0d7bc61691ebead9d88fe60475e0daa99be57fc63d80c54db1", + "dist/2023-07-12/rustc-beta-aarch64-unknown-linux-gnu.tar.xz": "006bc3e8ad7e08112b9bd1b217f78795f251ff5c40845263eafaa24cda564fb7", + "dist/2023-07-12/rustc-beta-aarch64-unknown-linux-musl.tar.gz": "e0d2afd64d312b174f877503dec692effa0f828a14801363bc639308e964815d", + "dist/2023-07-12/rustc-beta-aarch64-unknown-linux-musl.tar.xz": "2100939e2080fad8040434e0d5afb38238a583deb9d2d87983ce3509d1f34fd5", + "dist/2023-07-12/rustc-beta-arm-unknown-linux-gnueabi.tar.gz": "b34aebfdafa0d27ceb2bf1494de0894dff09ceee7f924f805f55bee64c9144e3", + "dist/2023-07-12/rustc-beta-arm-unknown-linux-gnueabi.tar.xz": "b79fdc2786057e5267b3b00b4903786f16a522aadc2f3dd8bb8456e42400862c", + "dist/2023-07-12/rustc-beta-arm-unknown-linux-gnueabihf.tar.gz": "e2e86e88c21e02fd16e5cc78a8de023af33a52d9b5006dd6884de5d97459ca1c", + "dist/2023-07-12/rustc-beta-arm-unknown-linux-gnueabihf.tar.xz": "9e3d480fbd3387aca0acd8c63a45d91e2148117fd5dc532885328ab39cbc9d11", + "dist/2023-07-12/rustc-beta-armv7-unknown-linux-gnueabihf.tar.gz": "b08a6627dc24f348cc6eb9c89a63099ffdc1e71d562ccce0a7906ef279b4cccf", + "dist/2023-07-12/rustc-beta-armv7-unknown-linux-gnueabihf.tar.xz": "57d4513f8dfe30a2a62886d931ac317d956fa723b4d72c458f77c4be28144ec2", + "dist/2023-07-12/rustc-beta-i686-pc-windows-gnu.tar.gz": "6950bca30824403a94c1a272d4bf7a5771dfe608c20a3045ea6a48a5ad789851", + "dist/2023-07-12/rustc-beta-i686-pc-windows-gnu.tar.xz": "7891a4ca20a622138c5008824c01c6de7b5b4306381375d95b3063518eb7883b", + "dist/2023-07-12/rustc-beta-i686-pc-windows-msvc.tar.gz": "cbf66d5ed4dbae45e1738c4ea3879886ec59062bc59be93b2b526c49634fabe5", + "dist/2023-07-12/rustc-beta-i686-pc-windows-msvc.tar.xz": "01d52825cd5d184028f6fa2b47d061254e500324c43db0c7ee4cfede9f801791", + "dist/2023-07-12/rustc-beta-i686-unknown-linux-gnu.tar.gz": "04f9d64cde2749214fbfa849c72df4bece1c0c9bd485933acf41e4b38bb90976", + "dist/2023-07-12/rustc-beta-i686-unknown-linux-gnu.tar.xz": "387b72fec91c8afbf088819248b8333198a1588ff2ef3fced9dc75a0d28152ac", + "dist/2023-07-12/rustc-beta-loongarch64-unknown-linux-gnu.tar.gz": "d6d6d499f388395cf0234ecbc250ad8c17201388502cc0b1d4dcd145938edf59", + "dist/2023-07-12/rustc-beta-loongarch64-unknown-linux-gnu.tar.xz": "2f83df3cd76a236ed170b9b9eece1be1297f2159226d6ca13826ed345ebc25ba", + "dist/2023-07-12/rustc-beta-powerpc-unknown-linux-gnu.tar.gz": "fde554a543eba35030ff0b4c3402b5c24c372a7071d1e489797106b51392caeb", + "dist/2023-07-12/rustc-beta-powerpc-unknown-linux-gnu.tar.xz": "7d8dae3414126ed8d34dffa577d59b236d1b04dd9aaeee8e83bf50ef3269cceb", + "dist/2023-07-12/rustc-beta-powerpc64-unknown-linux-gnu.tar.gz": "558622fcbf845cc05114680d20edb596f243304b5d540f8df3c575d0c2c681ce", + "dist/2023-07-12/rustc-beta-powerpc64-unknown-linux-gnu.tar.xz": "4716b40dfa7ad351e9c476742d119167b30c5c4c2b2316808d6587ff0de69c7c", + "dist/2023-07-12/rustc-beta-powerpc64le-unknown-linux-gnu.tar.gz": "c97ad88f524cda10fc59e083f543b603a84e47c4cff2af51bd6294b0c04fa52b", + "dist/2023-07-12/rustc-beta-powerpc64le-unknown-linux-gnu.tar.xz": "0cba6173edc10993176e466b2f0c353551b7f544d499eca90e143c40bd855288", + "dist/2023-07-12/rustc-beta-riscv64gc-unknown-linux-gnu.tar.gz": "0d0a9cf77521a372271e6c37b7ca9b1ea879e1f8ccbad07e88a047268fbffb02", + "dist/2023-07-12/rustc-beta-riscv64gc-unknown-linux-gnu.tar.xz": "8f5e09fb6febc5965ec762d88ab812385ec133a732f006c6a61aedd3be6a7ce1", + "dist/2023-07-12/rustc-beta-s390x-unknown-linux-gnu.tar.gz": "35fdc9549f2ae6545458ca9a899a2e6ecca33864709f28c3479bf547b86bd843", + "dist/2023-07-12/rustc-beta-s390x-unknown-linux-gnu.tar.xz": "4f3ef47d674787313ce445ae453661302df3cd5c36e4f135b4cbf1ebd60a1e3d", + "dist/2023-07-12/rustc-beta-x86_64-apple-darwin.tar.gz": "ac623b79329ffae330e76d79a9ca741962725a072e045b8b7d9b2d6fee5a57b3", + "dist/2023-07-12/rustc-beta-x86_64-apple-darwin.tar.xz": "439cce8c9f3d614a8eefa45bc42723a15e9dfdefa83cb48f1751ba8aaf1fccb6", + "dist/2023-07-12/rustc-beta-x86_64-pc-windows-gnu.tar.gz": "4f91add8c303b2c82ff9d2c5bb0723b298e0e1f5ddca524af9c1fde490d0d346", + "dist/2023-07-12/rustc-beta-x86_64-pc-windows-gnu.tar.xz": "cda1396c2eddf49e42cab04fe152b4edea0d9ef61ebe987307962a1c5dd1e55b", + "dist/2023-07-12/rustc-beta-x86_64-pc-windows-msvc.tar.gz": "993f06513b965731fdd678208985a85b0edb94887df4f4518b8190f1bb9c9faa", + "dist/2023-07-12/rustc-beta-x86_64-pc-windows-msvc.tar.xz": "7a41f05c27619407a4a4ae6acf5ad567f2504d4b8e7462e0fc409513b3086dc3", + "dist/2023-07-12/rustc-beta-x86_64-unknown-freebsd.tar.gz": "19ab69319c2c52580e447cc22471fb18a25b06849c1fe79783eb067e0f75f1c7", + "dist/2023-07-12/rustc-beta-x86_64-unknown-freebsd.tar.xz": "684cbc8205f08c9e7aa6de7fc72422dbc87d5e842367f0c3e40f2206f3bd1045", + "dist/2023-07-12/rustc-beta-x86_64-unknown-illumos.tar.gz": "af31123f89adca1858eea5e5f00e42913aeeda1dbc7572d557a7ae132928f3f7", + "dist/2023-07-12/rustc-beta-x86_64-unknown-illumos.tar.xz": "e4f711e5b81663ddc2d5b5f85b74488bcbd0535c8e170fb99e3fbe7d6931e937", + "dist/2023-07-12/rustc-beta-x86_64-unknown-linux-gnu.tar.gz": "6f781b40006f6552a0f4642808950ac570d6b4a17e15bcb373a385ac5f822bb3", + "dist/2023-07-12/rustc-beta-x86_64-unknown-linux-gnu.tar.xz": "af7d049238fdf1d538059b918d5ab0e3751ada2f3a339a7479a295d08b5aa963", + "dist/2023-07-12/rustc-beta-x86_64-unknown-linux-musl.tar.gz": "bbcfa001617d591fb663b55f1c072c5bd1c5ae57a245a00d6fcbe02ab52ef4e7", + "dist/2023-07-12/rustc-beta-x86_64-unknown-linux-musl.tar.xz": "56ecccd46000dcfda0996da364509b7b2a739132693f776d63f9b1d74fb8c546", + "dist/2023-07-12/rustc-beta-x86_64-unknown-netbsd.tar.gz": "181b946f424be9a5430f79d56c80324e2a72ed638e571fbfc7d1af370d4aaf11", + "dist/2023-07-12/rustc-beta-x86_64-unknown-netbsd.tar.xz": "2bc9406b45f14e2efb47c9475ae89a3ec9ce780c402d27f11c4a6217a5845258", + "dist/2023-07-13/rustc-nightly-aarch64-apple-darwin.tar.gz": "4298aa816d4a6c1004e4a480f77e0d321a47c4b5e2048ed705a5a7d632a43bcc", + "dist/2023-07-13/rustc-nightly-aarch64-apple-darwin.tar.xz": "0758cf22ed98bba897ad3bff5c3fc49367d3fea25185e1b39cea417941c7ce42", + "dist/2023-07-13/rustc-nightly-aarch64-pc-windows-msvc.tar.gz": "0db596a386aac8d2d35293e8466a710498102ca6d68a16d60ebbfffa2cc67950", + "dist/2023-07-13/rustc-nightly-aarch64-pc-windows-msvc.tar.xz": "6a51533a6bdf3ec705fb7d09f076e67393b4090159ce6bfc8ab9a4abbda1b421", + "dist/2023-07-13/rustc-nightly-aarch64-unknown-linux-gnu.tar.gz": "c6dd529410c4ceb5ef851380e1f12581fe0d2240b9224bf4727f4ef0dd93f7ab", + "dist/2023-07-13/rustc-nightly-aarch64-unknown-linux-gnu.tar.xz": "7b3d71fd596292c3989c2e8982fe2d488f90449e68114be331f7589b296b9b1d", + "dist/2023-07-13/rustc-nightly-aarch64-unknown-linux-musl.tar.gz": "8551f98fb1030ff712a68b97cc1c67bbb19ec51748f92ac7d149b0d1e2f08ada", + "dist/2023-07-13/rustc-nightly-aarch64-unknown-linux-musl.tar.xz": "853b80262a5e58dd8c831a42f0efb229e5eb8516c6d4ddafc02152e2e55b6706", + "dist/2023-07-13/rustc-nightly-arm-unknown-linux-gnueabi.tar.gz": "d04649a98a7410594bd4ac776a638d7312838e0b15cdf53236b953406a1bcf87", + "dist/2023-07-13/rustc-nightly-arm-unknown-linux-gnueabi.tar.xz": "6319a00b08efdac3a379d587d8c11507a79446e9ef2421f6539af9a734ec2ce5", + "dist/2023-07-13/rustc-nightly-arm-unknown-linux-gnueabihf.tar.gz": "9739f7d186d5a92d9e775bda150ad1893fa14720f2e3662d61220d125a68868e", + "dist/2023-07-13/rustc-nightly-arm-unknown-linux-gnueabihf.tar.xz": "818fc51517ad026bda8c3eefa3065d3d6d9e465f600398404987e9c8420ba933", + "dist/2023-07-13/rustc-nightly-armv7-unknown-linux-gnueabihf.tar.gz": "557e197ddd49d62e271108c8c0f17618d58c6b77841aee75cf190a260de8b522", + "dist/2023-07-13/rustc-nightly-armv7-unknown-linux-gnueabihf.tar.xz": "a60b73f673e80f02ff1c1151e63d883b8e390ec447cb3154b1fd4ac4b4b9af78", + "dist/2023-07-13/rustc-nightly-i686-pc-windows-gnu.tar.gz": "31fe306c7b547d1e595d82b7195d972a3e8dbcace6bf786557d0ff14b7f3a243", + "dist/2023-07-13/rustc-nightly-i686-pc-windows-gnu.tar.xz": "32dcb5830ae51effd7f8bc6c2dc8c61863952c1eb34a3f6a5e5a7ca1e632660c", + "dist/2023-07-13/rustc-nightly-i686-pc-windows-msvc.tar.gz": "4ecb180c07b1f1f15f51508e0d2290204052ce98be2203c8d2257f620b0a3c32", + "dist/2023-07-13/rustc-nightly-i686-pc-windows-msvc.tar.xz": "e9a6e85dc43561d644988e862db6d3af53b14397e8aff1b162fe6f29c65062ed", + "dist/2023-07-13/rustc-nightly-i686-unknown-linux-gnu.tar.gz": "4fdb462e10993e386f03396f98379bdfe45d60c38bce2102243d566d4eb0178d", + "dist/2023-07-13/rustc-nightly-i686-unknown-linux-gnu.tar.xz": "759d1c97a06baa0f7d56705a0d4b4bd954057d140b1a28e34db1d2a59c85307a", + "dist/2023-07-13/rustc-nightly-loongarch64-unknown-linux-gnu.tar.gz": "5f0ebf7b582bb3e8112e8287a33966670f33c46db6fc4569963a7aa0c1b6daf7", + "dist/2023-07-13/rustc-nightly-loongarch64-unknown-linux-gnu.tar.xz": "044f6d651b03b1c74bd5ed86139119ed0cfd4643576860770a784557c864388d", + "dist/2023-07-13/rustc-nightly-powerpc-unknown-linux-gnu.tar.gz": "9fef5ebfd5b50d256d85e24ecfe3953da80bce799c83eb8f453e70b20424274e", + "dist/2023-07-13/rustc-nightly-powerpc-unknown-linux-gnu.tar.xz": "8d3c75ae12ef9273279c5c715680e0ec5035bbc642ac3e6e9d5e31f718b4d625", + "dist/2023-07-13/rustc-nightly-powerpc64-unknown-linux-gnu.tar.gz": "acb5e2e805023eaf2403385d26f1bf6fa91dc505f2a030bb3ef1b1c415cd2251", + "dist/2023-07-13/rustc-nightly-powerpc64-unknown-linux-gnu.tar.xz": "7bbb565705d19c01404e519c3b15db717678995f5ec5fbb572937ae7ee2efded", + "dist/2023-07-13/rustc-nightly-powerpc64le-unknown-linux-gnu.tar.gz": "9af44902fc657866446dfa52a8e5f561e69e555c49c0e6f32d739b4a6af98a59", + "dist/2023-07-13/rustc-nightly-powerpc64le-unknown-linux-gnu.tar.xz": "f9e877a64286b78876f33f7506086118653d01674333c59907e8cdf71c4e95a2", + "dist/2023-07-13/rustc-nightly-riscv64gc-unknown-linux-gnu.tar.gz": "c5a1fb8c5f3a69adadac4a7c0f8734cc14b8ce1e383530419a095c4db6645b11", + "dist/2023-07-13/rustc-nightly-riscv64gc-unknown-linux-gnu.tar.xz": "521e7be385877a0f4069435efa9308fc5d33e4f90294270a7f8df9327ce222c1", + "dist/2023-07-13/rustc-nightly-s390x-unknown-linux-gnu.tar.gz": "55d9efc83614e5fcc4a7ccd0581a95a66ada4577198b25b0f4e7067ee72cdbd9", + "dist/2023-07-13/rustc-nightly-s390x-unknown-linux-gnu.tar.xz": "6c88031cd1d59fb6c2f971b3ca9aea2e029f8481cd41824ffdb67a085feab5f1", + "dist/2023-07-13/rustc-nightly-x86_64-apple-darwin.tar.gz": "b75c6defcd94b930ced62a7ee18000a68cf6bf255479ead60395ca3158f2f198", + "dist/2023-07-13/rustc-nightly-x86_64-apple-darwin.tar.xz": "ea1dc2985f708823719589fb029de961b179cf19bb228a4745cc26a47415a5de", + "dist/2023-07-13/rustc-nightly-x86_64-pc-windows-gnu.tar.gz": "c1602297eab6a276aa367b2f85d004d236d26cd4b4133e4cffb941ef3c858c74", + "dist/2023-07-13/rustc-nightly-x86_64-pc-windows-gnu.tar.xz": "06965d8332f0fc167886f6e9a3ff9a558aa3513711ea309bab5f30185a9afee7", + "dist/2023-07-13/rustc-nightly-x86_64-pc-windows-msvc.tar.gz": "80c3d27142473a89beb1969cbfdba7281ca237ec8f2a5b20c75eeb14c5e2e771", + "dist/2023-07-13/rustc-nightly-x86_64-pc-windows-msvc.tar.xz": "52fe4134ef2ab35ffa251669a30ca6c9aa94a3ca97238f46f9aad0b2b9dac70f", + "dist/2023-07-13/rustc-nightly-x86_64-unknown-freebsd.tar.gz": "837f628f7775d13b661c1e7dd7a1de649264abca247aeeb6cbab05faaf7e83c2", + "dist/2023-07-13/rustc-nightly-x86_64-unknown-freebsd.tar.xz": "732a597647702c2672f559c83a8e829c36dcb8fe92bf8abdcc1cf2526ba2d8af", + "dist/2023-07-13/rustc-nightly-x86_64-unknown-illumos.tar.gz": "07eed9287f36cc6650838e27b7148c26d588b96b522e1b72f58ceebec4b0dd87", + "dist/2023-07-13/rustc-nightly-x86_64-unknown-illumos.tar.xz": "70cb988d67159941502900f803e29bdb53f81057d68393965ebd63fe42e2cba4", + "dist/2023-07-13/rustc-nightly-x86_64-unknown-linux-gnu.tar.gz": "adbe0dd7ba4df92f199118943bc25d3a467d6c1d3249817b74e05c7d59a76846", + "dist/2023-07-13/rustc-nightly-x86_64-unknown-linux-gnu.tar.xz": "c999ab64cbbed8bc2853b717190d6d4aac871363c7182e06c5144e50d34621b5", + "dist/2023-07-13/rustc-nightly-x86_64-unknown-linux-musl.tar.gz": "1bc5368592390eee2478d48f75fbeb5e9f3f8e4fc2f6e3e6952fa08e7c8f46f6", + "dist/2023-07-13/rustc-nightly-x86_64-unknown-linux-musl.tar.xz": "15559729aefc45dcc1b28333e6166a2fe5b1e0d30521b9a1ecd80134c859ed85", + "dist/2023-07-13/rustc-nightly-x86_64-unknown-netbsd.tar.gz": "f918703cc31c800e35d739ef146733de486a6fbb2a0c78f993352a1242352f0b", + "dist/2023-07-13/rustc-nightly-x86_64-unknown-netbsd.tar.xz": "777d69d7190825ea83dc44712d0372b1a225b3e4fde66d1b9ac4ea981d54a031", + "dist/2023-07-13/rustfmt-nightly-aarch64-apple-darwin.tar.gz": "998a5c80bfb2450869e6975aeb178104f3424df6b88fccb9c549ff95fb0a62e7", + "dist/2023-07-13/rustfmt-nightly-aarch64-apple-darwin.tar.xz": "84f8e77132b4ce46086907bbaa3bbfbe151400d8110f075cbaa31e80616d9891", + "dist/2023-07-13/rustfmt-nightly-aarch64-pc-windows-msvc.tar.gz": "63a8b8302007b9052a0016200332e85b24f758960eca25ba7ffb7f8d5c6ed409", + "dist/2023-07-13/rustfmt-nightly-aarch64-pc-windows-msvc.tar.xz": "291d17a39390b1259d47e8b1c9495d80817e12854cb3ede2a91b50a8c7a998f4", + "dist/2023-07-13/rustfmt-nightly-aarch64-unknown-linux-gnu.tar.gz": "c5c5d47c25fecaed410f1c0004e30abbc436b5dc85110f657f1ddc87b10933da", + "dist/2023-07-13/rustfmt-nightly-aarch64-unknown-linux-gnu.tar.xz": "c7da897bf78cc051fa0028b93253348ad4b89c3dec9782d093db98b1814cd828", + "dist/2023-07-13/rustfmt-nightly-aarch64-unknown-linux-musl.tar.gz": "2be878ea50ad540b17658dd29bec4124c43654f4668c62e7a4b2c7b5ad07155b", + "dist/2023-07-13/rustfmt-nightly-aarch64-unknown-linux-musl.tar.xz": "b355c1bd4140205c613c539021e0194535fb3c94b3eba2a2dd6ae314a7bca891", + "dist/2023-07-13/rustfmt-nightly-arm-unknown-linux-gnueabi.tar.gz": "84e711b5e26487bad148d9968ac7236fddddd050761a3069ce10a8e222a860a1", + "dist/2023-07-13/rustfmt-nightly-arm-unknown-linux-gnueabi.tar.xz": "fff567ecf3c426558c8cd84776870d833511049dbc531ed5e71733694afe5f70", + "dist/2023-07-13/rustfmt-nightly-arm-unknown-linux-gnueabihf.tar.gz": "61b48838a1f0097a8060f4a01e3b5ee2acdf409ca681ee7c78c120ee59a82e1a", + "dist/2023-07-13/rustfmt-nightly-arm-unknown-linux-gnueabihf.tar.xz": "687576f050b1266236e986557eea10fe4354d6be3ab930c5874aac9accc19a7f", + "dist/2023-07-13/rustfmt-nightly-armv7-unknown-linux-gnueabihf.tar.gz": "003e572ef26cc1f39449fc7c488be6ba4fc180a432512036c2035c5249b5a7ae", + "dist/2023-07-13/rustfmt-nightly-armv7-unknown-linux-gnueabihf.tar.xz": "dad6a37c9054bad090e3fc69679ef61cf95f16063623aba72f8002a95d548020", + "dist/2023-07-13/rustfmt-nightly-i686-pc-windows-gnu.tar.gz": "707a6ea9565d9c65b0aa3eac205659c41c70da0f6301d04caa4291716e70aa18", + "dist/2023-07-13/rustfmt-nightly-i686-pc-windows-gnu.tar.xz": "0546e09197a129dbf27b93ff6e0d84d0dc1a4b40e49ec131e29cd2c3636a950c", + "dist/2023-07-13/rustfmt-nightly-i686-pc-windows-msvc.tar.gz": "d7a15e31b67f1897a2968d58b0578fd6489e55709cea5747b9b49f5aa2e4d62b", + "dist/2023-07-13/rustfmt-nightly-i686-pc-windows-msvc.tar.xz": "5b1bfa464636528d7245b7524fe471fdafc2bd088efc5d99823a5d3b31afd48f", + "dist/2023-07-13/rustfmt-nightly-i686-unknown-linux-gnu.tar.gz": "ab7d0ac3cbf01cdfd0aba52d869208469d49193a81ba59502d08a377cea883f1", + "dist/2023-07-13/rustfmt-nightly-i686-unknown-linux-gnu.tar.xz": "f18f262a288c55b72b434abbb0d304eb6bae7db27fccfb2bdca6eef9078c0f68", + "dist/2023-07-13/rustfmt-nightly-loongarch64-unknown-linux-gnu.tar.gz": "6e95d58a682e0f924b71d40827f156e3a52b5c90bf3347b4b67c275f1e372537", + "dist/2023-07-13/rustfmt-nightly-loongarch64-unknown-linux-gnu.tar.xz": "c68cf075f8eba37e424a1ad79c87963070b20fb38c0e140bbf9733368e45077d", + "dist/2023-07-13/rustfmt-nightly-powerpc-unknown-linux-gnu.tar.gz": "f41f9f8f383b12ab0d93b63647aef8e57431475ccb41675d69071a69fdebb6fc", + "dist/2023-07-13/rustfmt-nightly-powerpc-unknown-linux-gnu.tar.xz": "ce097e23de16a0f0208fd669c71c372dcc99ab3114af573cc38b1b58ed5b10d0", + "dist/2023-07-13/rustfmt-nightly-powerpc64-unknown-linux-gnu.tar.gz": "6fd13a4f75c4d3ce82a7d7e54051c308d7a18be89c829ab0fe313c6735c74a8d", + "dist/2023-07-13/rustfmt-nightly-powerpc64-unknown-linux-gnu.tar.xz": "66c363a6804f279ea8ac52db85b6ad37b3075f59a6cf2f9be213f2849a76880f", + "dist/2023-07-13/rustfmt-nightly-powerpc64le-unknown-linux-gnu.tar.gz": "480fef935283819bfa03c8d4ccc9300bc1c6669371c4ba41af2e8e3bd547e8cb", + "dist/2023-07-13/rustfmt-nightly-powerpc64le-unknown-linux-gnu.tar.xz": "a3eb16f78498a99dda46398befbb0d4a876e62b9db9b344e472ba072c8583846", + "dist/2023-07-13/rustfmt-nightly-riscv64gc-unknown-linux-gnu.tar.gz": "607a0582cd382a04c8131cb03cfc48092eac953953aeafa06dbe84889553eea5", + "dist/2023-07-13/rustfmt-nightly-riscv64gc-unknown-linux-gnu.tar.xz": "0bf682b38cef792c1514b2277c8a933c27d87197895b83c3a67684ebed134ea4", + "dist/2023-07-13/rustfmt-nightly-s390x-unknown-linux-gnu.tar.gz": "1579084ae15cfc842f587e1e208693cdf7fcfe76dd818efb3b98d01a39b1f93b", + "dist/2023-07-13/rustfmt-nightly-s390x-unknown-linux-gnu.tar.xz": "361ad2ecb131f2c0ed773c864c02f59d960264fd86cf3397e81b58bb9d0237a3", + "dist/2023-07-13/rustfmt-nightly-x86_64-apple-darwin.tar.gz": "429150699fc23b90bb034b2b06dbc27f74f0fcd467225afc012ac7dd639228c6", + "dist/2023-07-13/rustfmt-nightly-x86_64-apple-darwin.tar.xz": "31468dbf051c1edcd69873264c28e046d5d6e1867ba9255b8a0e97905b536fcf", + "dist/2023-07-13/rustfmt-nightly-x86_64-pc-windows-gnu.tar.gz": "38e8742bb196216409e474e07deaac2d2a842d1372f3b7e1ad24c039cc0fb609", + "dist/2023-07-13/rustfmt-nightly-x86_64-pc-windows-gnu.tar.xz": "8287a9058332bc41f7b83788d5c3af2bfdca6986301e3d97cdb583b619967c2e", + "dist/2023-07-13/rustfmt-nightly-x86_64-pc-windows-msvc.tar.gz": "db584715b7df3be2d97878cc45102474b551e13604e71485dd14e68dfe3706f0", + "dist/2023-07-13/rustfmt-nightly-x86_64-pc-windows-msvc.tar.xz": "6fd6ee9dca05b8560536c738cb0b4020aa37397acc4a1888f4fed5a89e461d8f", + "dist/2023-07-13/rustfmt-nightly-x86_64-unknown-freebsd.tar.gz": "8bccffaf50ff3d3ea7197f0a5b2fa075996afe9de602821a5638ee5d7c56e610", + "dist/2023-07-13/rustfmt-nightly-x86_64-unknown-freebsd.tar.xz": "0ee2812579304231d29c32d32e5b908751e369ce7776b9773a3cf89d5fdb00d0", + "dist/2023-07-13/rustfmt-nightly-x86_64-unknown-illumos.tar.gz": "9f26ef23056f20f722f3616632cad8d03428248f126c83ed682ab4f67268e7df", + "dist/2023-07-13/rustfmt-nightly-x86_64-unknown-illumos.tar.xz": "1265d7f28cf332db9f467d02f0a77ffdfa926bbf7ad5d148cb04ec888abcfc49", + "dist/2023-07-13/rustfmt-nightly-x86_64-unknown-linux-gnu.tar.gz": "74a5d268d82c39eb2b23b5324ce978647e59591e586f7c52d9187d7843990e1e", + "dist/2023-07-13/rustfmt-nightly-x86_64-unknown-linux-gnu.tar.xz": "4b16832cd24285705a29e3e9aaec554675852200763bffc6124005211c38f37e", + "dist/2023-07-13/rustfmt-nightly-x86_64-unknown-linux-musl.tar.gz": "0cd34367c1ee4a61cf7bf26591aa65de6651c0a0912afdd1f08cea60da35ea91", + "dist/2023-07-13/rustfmt-nightly-x86_64-unknown-linux-musl.tar.xz": "5321648a640b3ab57d329a1ec5e83f30825c2a8ca73a4135c1c003726d86b28b", + "dist/2023-07-13/rustfmt-nightly-x86_64-unknown-netbsd.tar.gz": "298c887d59f8f1a7a4d02335224fa1b9b3ccdf540fe5bbf00417d083352c4149", + "dist/2023-07-13/rustfmt-nightly-x86_64-unknown-netbsd.tar.xz": "f0e6bc108a89407273790d228d51351046183a4eefd64631879cba6fa72c60d4" } } diff --git a/src/tools/build_helper/src/ci.rs b/src/tools/build_helper/src/ci.rs index 893195b69c2..b70ea5ec113 100644 --- a/src/tools/build_helper/src/ci.rs +++ b/src/tools/build_helper/src/ci.rs @@ -36,15 +36,25 @@ impl CiEnv { } pub mod gha { + use std::sync::atomic::{AtomicBool, Ordering}; + + static GROUP_ACTIVE: AtomicBool = AtomicBool::new(false); + /// All github actions log messages from this call to the Drop of the return value /// will be grouped and hidden by default in logs. Note that nesting these does /// not really work. + #[track_caller] pub fn group(name: impl std::fmt::Display) -> Group { if std::env::var_os("GITHUB_ACTIONS").is_some() { eprintln!("::group::{name}"); } else { eprintln!("{name}") } + // https://github.com/actions/toolkit/issues/1001 + assert!( + !GROUP_ACTIVE.swap(true, Ordering::Relaxed), + "nested groups are not supported by GHA!" + ); Group(()) } @@ -57,6 +67,10 @@ pub mod gha { if std::env::var_os("GITHUB_ACTIONS").is_some() { eprintln!("::endgroup::"); } + assert!( + GROUP_ACTIVE.swap(false, Ordering::Relaxed), + "group dropped but no group active!" + ); } } } diff --git a/src/tools/build_helper/src/git.rs b/src/tools/build_helper/src/git.rs index 168633c8f63..66876e02c19 100644 --- a/src/tools/build_helper/src/git.rs +++ b/src/tools/build_helper/src/git.rs @@ -94,7 +94,9 @@ pub fn get_git_modified_files( git_dir: Option<&Path>, extensions: &Vec<&str>, ) -> Result<Option<Vec<String>>, String> { - let Ok(updated_master) = updated_master_branch(git_dir) else { return Ok(None); }; + let Ok(updated_master) = updated_master_branch(git_dir) else { + return Ok(None); + }; let git = || { let mut git = Command::new("git"); @@ -119,7 +121,9 @@ pub fn get_git_modified_files( /// Returns the files that haven't been added to git yet. pub fn get_git_untracked_files(git_dir: Option<&Path>) -> Result<Option<Vec<String>>, String> { - let Ok(_updated_master) = updated_master_branch(git_dir) else { return Ok(None); }; + let Ok(_updated_master) = updated_master_branch(git_dir) else { + return Ok(None); + }; let mut git = Command::new("git"); if let Some(git_dir) = git_dir { git.current_dir(git_dir); diff --git a/src/tools/build_helper/src/util.rs b/src/tools/build_helper/src/util.rs index 11b8a228b8a..5801a8648f2 100644 --- a/src/tools/build_helper/src/util.rs +++ b/src/tools/build_helper/src/util.rs @@ -1,10 +1,12 @@ use std::process::Command; /// Invokes `build_helper::util::detail_exit` with `cfg!(test)` +/// +/// This is a macro instead of a function so that it uses `cfg(test)` in the *calling* crate, not in build helper. #[macro_export] -macro_rules! detail_exit_macro { +macro_rules! exit { ($code:expr) => { - build_helper::util::detail_exit($code, cfg!(test)); + $crate::util::detail_exit($code, cfg!(test)); }; } diff --git a/src/tools/cargo b/src/tools/cargo -Subproject 45782b6b8afd1da042d45c2daeec9c0744f72cc +Subproject 694a579566a9a1482b20aff8a68f0e4edd99bd2 diff --git a/src/tools/clippy/clippy_lints/src/assertions_on_result_states.rs b/src/tools/clippy/clippy_lints/src/assertions_on_result_states.rs index f6d6c23bb6e..2980c9d6db3 100644 --- a/src/tools/clippy/clippy_lints/src/assertions_on_result_states.rs +++ b/src/tools/clippy/clippy_lints/src/assertions_on_result_states.rs @@ -47,7 +47,7 @@ impl<'tcx> LateLintPass<'tcx> for AssertionsOnResultStates { && let result_type_with_refs = cx.typeck_results().expr_ty(recv) && let result_type = result_type_with_refs.peel_refs() && is_type_diagnostic_item(cx, result_type, sym::Result) - && let ty::Adt(_, substs) = result_type.kind() + && let ty::Adt(_, args) = result_type.kind() { if !is_copy(cx, result_type) { if result_type_with_refs != result_type { @@ -61,7 +61,7 @@ impl<'tcx> LateLintPass<'tcx> for AssertionsOnResultStates { let semicolon = if is_expr_final_block_expr(cx.tcx, e) {";"} else {""}; let mut app = Applicability::MachineApplicable; match method_segment.ident.as_str() { - "is_ok" if type_suitable_to_unwrap(cx, substs.type_at(1)) => { + "is_ok" if type_suitable_to_unwrap(cx, args.type_at(1)) => { span_lint_and_sugg( cx, ASSERTIONS_ON_RESULT_STATES, @@ -75,7 +75,7 @@ impl<'tcx> LateLintPass<'tcx> for AssertionsOnResultStates { app, ); } - "is_err" if type_suitable_to_unwrap(cx, substs.type_at(0)) => { + "is_err" if type_suitable_to_unwrap(cx, args.type_at(0)) => { span_lint_and_sugg( cx, ASSERTIONS_ON_RESULT_STATES, diff --git a/src/tools/clippy/clippy_lints/src/bool_assert_comparison.rs b/src/tools/clippy/clippy_lints/src/bool_assert_comparison.rs index e8775b08144..d984fddc57a 100644 --- a/src/tools/clippy/clippy_lints/src/bool_assert_comparison.rs +++ b/src/tools/clippy/clippy_lints/src/bool_assert_comparison.rs @@ -61,7 +61,7 @@ fn is_impl_not_trait_with_bool_out<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) - ) }) .map_or(false, |assoc_item| { - let proj = Ty::new_projection(cx.tcx,assoc_item.def_id, cx.tcx.mk_substs_trait(ty, [])); + let proj = Ty::new_projection(cx.tcx,assoc_item.def_id, cx.tcx.mk_args_trait(ty, [])); let nty = cx.tcx.normalize_erasing_regions(cx.param_env, proj); nty.is_bool() diff --git a/src/tools/clippy/clippy_lints/src/casts/as_ptr_cast_mut.rs b/src/tools/clippy/clippy_lints/src/casts/as_ptr_cast_mut.rs index 1633ffd589c..fa1550a0ef9 100644 --- a/src/tools/clippy/clippy_lints/src/casts/as_ptr_cast_mut.rs +++ b/src/tools/clippy/clippy_lints/src/casts/as_ptr_cast_mut.rs @@ -17,7 +17,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, cast_expr: &Expr<'_>, && let ExprKind::MethodCall(method_name, receiver, [], _) = cast_expr.peel_blocks().kind && method_name.ident.name == rustc_span::sym::as_ptr && let Some(as_ptr_did) = cx.typeck_results().type_dependent_def_id(cast_expr.peel_blocks().hir_id) - && let as_ptr_sig = cx.tcx.fn_sig(as_ptr_did).subst_identity() + && let as_ptr_sig = cx.tcx.fn_sig(as_ptr_did).instantiate_identity() && let Some(first_param_ty) = as_ptr_sig.skip_binder().inputs().iter().next() && let ty::Ref(_, _, Mutability::Not) = first_param_ty.kind() && let Some(recv) = snippet_opt(cx, receiver.span) diff --git a/src/tools/clippy/clippy_lints/src/casts/cast_ptr_alignment.rs b/src/tools/clippy/clippy_lints/src/casts/cast_ptr_alignment.rs index 6c8ee296c75..5bf467efa0f 100644 --- a/src/tools/clippy/clippy_lints/src/casts/cast_ptr_alignment.rs +++ b/src/tools/clippy/clippy_lints/src/casts/cast_ptr_alignment.rs @@ -66,7 +66,7 @@ fn is_used_as_unaligned(cx: &LateContext<'_>, e: &Expr<'_>) -> bool { if matches!(name.ident.as_str(), "read_unaligned" | "write_unaligned") && let Some(def_id) = cx.typeck_results().type_dependent_def_id(parent.hir_id) && let Some(def_id) = cx.tcx.impl_of_method(def_id) - && cx.tcx.type_of(def_id).subst_identity().is_unsafe_ptr() + && cx.tcx.type_of(def_id).instantiate_identity().is_unsafe_ptr() { true } else { diff --git a/src/tools/clippy/clippy_lints/src/copy_iterator.rs b/src/tools/clippy/clippy_lints/src/copy_iterator.rs index 0fc11523298..5d04ad0112d 100644 --- a/src/tools/clippy/clippy_lints/src/copy_iterator.rs +++ b/src/tools/clippy/clippy_lints/src/copy_iterator.rs @@ -43,7 +43,7 @@ impl<'tcx> LateLintPass<'tcx> for CopyIterator { of_trait: Some(ref trait_ref), .. }) = item.kind; - let ty = cx.tcx.type_of(item.owner_id).subst_identity(); + let ty = cx.tcx.type_of(item.owner_id).instantiate_identity(); if is_copy(cx, ty); if let Some(trait_id) = trait_ref.trait_def_id(); if cx.tcx.is_diagnostic_item(sym::Iterator, trait_id); diff --git a/src/tools/clippy/clippy_lints/src/default.rs b/src/tools/clippy/clippy_lints/src/default.rs index 80c22742ba4..763ad0264ad 100644 --- a/src/tools/clippy/clippy_lints/src/default.rs +++ b/src/tools/clippy/clippy_lints/src/default.rs @@ -150,7 +150,7 @@ impl<'tcx> LateLintPass<'tcx> for Default { .fields .iter() .all(|field| { - is_copy(cx, cx.tcx.type_of(field.did).subst_identity()) + is_copy(cx, cx.tcx.type_of(field.did).instantiate_identity()) }); if !has_drop(cx, binding_type) || all_fields_are_copy; then { @@ -219,11 +219,11 @@ impl<'tcx> LateLintPass<'tcx> for Default { // give correct suggestion if generics are involved (see #6944) let binding_type = if_chain! { - if let ty::Adt(adt_def, substs) = binding_type.kind(); - if !substs.is_empty(); + if let ty::Adt(adt_def, args) = binding_type.kind(); + if !args.is_empty(); then { let adt_def_ty_name = cx.tcx.item_name(adt_def.did()); - let generic_args = substs.iter().collect::<Vec<_>>(); + let generic_args = args.iter().collect::<Vec<_>>(); let tys_str = generic_args .iter() .map(ToString::to_string) diff --git a/src/tools/clippy/clippy_lints/src/default_numeric_fallback.rs b/src/tools/clippy/clippy_lints/src/default_numeric_fallback.rs index e53a9877b20..9217edcef07 100644 --- a/src/tools/clippy/clippy_lints/src/default_numeric_fallback.rs +++ b/src/tools/clippy/clippy_lints/src/default_numeric_fallback.rs @@ -141,7 +141,7 @@ impl<'a, 'tcx> Visitor<'tcx> for NumericFallbackVisitor<'a, 'tcx> { ExprKind::MethodCall(_, receiver, args, _) => { if let Some(def_id) = self.cx.typeck_results().type_dependent_def_id(expr.hir_id) { - let fn_sig = self.cx.tcx.fn_sig(def_id).subst_identity().skip_binder(); + let fn_sig = self.cx.tcx.fn_sig(def_id).instantiate_identity().skip_binder(); for (expr, bound) in iter::zip(std::iter::once(*receiver).chain(args.iter()), fn_sig.inputs()) { self.ty_bounds.push((*bound).into()); self.visit_expr(expr); @@ -167,7 +167,7 @@ impl<'a, 'tcx> Visitor<'tcx> for NumericFallbackVisitor<'a, 'tcx> { .iter() .find_map(|f_def| { if f_def.ident(self.cx.tcx) == field.ident - { Some(self.cx.tcx.type_of(f_def.did).subst_identity()) } + { Some(self.cx.tcx.type_of(f_def.did).instantiate_identity()) } else { None } }); self.ty_bounds.push(bound.into()); @@ -213,9 +213,9 @@ impl<'a, 'tcx> Visitor<'tcx> for NumericFallbackVisitor<'a, 'tcx> { fn fn_sig_opt<'tcx>(cx: &LateContext<'tcx>, hir_id: HirId) -> Option<PolyFnSig<'tcx>> { let node_ty = cx.typeck_results().node_type_opt(hir_id)?; - // We can't use `Ty::fn_sig` because it automatically performs substs, this may result in FNs. + // We can't use `Ty::fn_sig` because it automatically performs args, this may result in FNs. match node_ty.kind() { - ty::FnDef(def_id, _) => Some(cx.tcx.fn_sig(*def_id).subst_identity()), + ty::FnDef(def_id, _) => Some(cx.tcx.fn_sig(*def_id).instantiate_identity()), ty::FnPtr(fn_sig) => Some(*fn_sig), _ => None, } diff --git a/src/tools/clippy/clippy_lints/src/dereference.rs b/src/tools/clippy/clippy_lints/src/dereference.rs index 73556c1053e..0e7efd53390 100644 --- a/src/tools/clippy/clippy_lints/src/dereference.rs +++ b/src/tools/clippy/clippy_lints/src/dereference.rs @@ -739,7 +739,7 @@ fn walk_parents<'tcx>( span, .. }) if span.ctxt() == ctxt => { - let ty = cx.tcx.type_of(owner_id.def_id).subst_identity(); + let ty = cx.tcx.type_of(owner_id.def_id).instantiate_identity(); Some(ty_auto_deref_stability(cx.tcx, cx.param_env, ty, precedence).position_for_result(cx)) }, @@ -763,7 +763,7 @@ fn walk_parents<'tcx>( }) if span.ctxt() == ctxt => { let output = cx .tcx - .erase_late_bound_regions(cx.tcx.fn_sig(owner_id).subst_identity().output()); + .erase_late_bound_regions(cx.tcx.fn_sig(owner_id).instantiate_identity().output()); Some(ty_auto_deref_stability(cx.tcx, cx.param_env, output, precedence).position_for_result(cx)) }, @@ -785,7 +785,7 @@ fn walk_parents<'tcx>( cx.tcx, // Use the param_env of the target type. cx.tcx.param_env(adt.did()), - cx.tcx.type_of(field_def.did).subst_identity(), + cx.tcx.type_of(field_def.did).instantiate_identity(), precedence, ) .position_for_arg() @@ -808,7 +808,7 @@ fn walk_parents<'tcx>( } else { let output = cx .tcx - .erase_late_bound_regions(cx.tcx.fn_sig(owner_id).subst_identity().output()); + .erase_late_bound_regions(cx.tcx.fn_sig(owner_id).instantiate_identity().output()); ty_auto_deref_stability(cx.tcx, cx.param_env, output, precedence).position_for_result(cx) }, ) @@ -879,9 +879,9 @@ fn walk_parents<'tcx>( && let ty::Ref(_, sub_ty, _) = *arg_ty.kind() && let subs = cx .typeck_results() - .node_substs_opt(parent.hir_id).map(|subs| &subs[1..]).unwrap_or_default() + .node_args_opt(parent.hir_id).map(|subs| &subs[1..]).unwrap_or_default() && let impl_ty = if cx.tcx.fn_sig(fn_id) - .subst_identity() + .instantiate_identity() .skip_binder() .inputs()[0].is_ref() { @@ -905,7 +905,7 @@ fn walk_parents<'tcx>( return Some(Position::MethodReceiver); } args.iter().position(|arg| arg.hir_id == child_id).map(|i| { - let ty = cx.tcx.fn_sig(fn_id).subst_identity().input(i + 1); + let ty = cx.tcx.fn_sig(fn_id).instantiate_identity().input(i + 1); // `e.hir_id == child_id` for https://github.com/rust-lang/rust-clippy/issues/9739 // `method.args.is_none()` for https://github.com/rust-lang/rust-clippy/issues/9782 if e.hir_id == child_id @@ -1124,10 +1124,10 @@ fn needless_borrow_impl_arg_position<'tcx>( let sized_trait_def_id = cx.tcx.lang_items().sized_trait(); let Some(callee_def_id) = fn_def_id(cx, parent) else { return Position::Other(precedence) }; - let fn_sig = cx.tcx.fn_sig(callee_def_id).subst_identity().skip_binder(); - let substs_with_expr_ty = cx + let fn_sig = cx.tcx.fn_sig(callee_def_id).instantiate_identity().skip_binder(); + let args_with_expr_ty = cx .typeck_results() - .node_substs(if let ExprKind::Call(callee, _) = parent.kind { + .node_args(if let ExprKind::Call(callee, _) = parent.kind { callee.hir_id } else { parent.hir_id @@ -1181,9 +1181,9 @@ fn needless_borrow_impl_arg_position<'tcx>( return Position::Other(precedence); } - // `substs_with_referent_ty` can be constructed outside of `check_referent` because the same + // `args_with_referent_ty` can be constructed outside of `check_referent` because the same // elements are modified each time `check_referent` is called. - let mut substs_with_referent_ty = substs_with_expr_ty.to_vec(); + let mut args_with_referent_ty = args_with_expr_ty.to_vec(); let mut check_reference_and_referent = |reference, referent| { let referent_ty = cx.typeck_results().expr_ty(referent); @@ -1207,7 +1207,7 @@ fn needless_borrow_impl_arg_position<'tcx>( fn_sig, arg_index, &projection_predicates, - &mut substs_with_referent_ty, + &mut args_with_referent_ty, ) { return false; } @@ -1216,14 +1216,14 @@ fn needless_borrow_impl_arg_position<'tcx>( if let ClauseKind::Trait(trait_predicate) = predicate.kind().skip_binder() && cx.tcx.is_diagnostic_item(sym::IntoIterator, trait_predicate.trait_ref.def_id) && let ty::Param(param_ty) = trait_predicate.self_ty().kind() - && let GenericArgKind::Type(ty) = substs_with_referent_ty[param_ty.index as usize].unpack() + && let GenericArgKind::Type(ty) = args_with_referent_ty[param_ty.index as usize].unpack() && ty.is_array() && !msrv.meets(msrvs::ARRAY_INTO_ITERATOR) { return false; } - let predicate = EarlyBinder::bind(predicate).subst(cx.tcx, &substs_with_referent_ty); + let predicate = EarlyBinder::bind(predicate).instantiate(cx.tcx, &args_with_referent_ty); let obligation = Obligation::new(cx.tcx, ObligationCause::dummy(), cx.param_env, predicate); let infcx = cx.tcx.infer_ctxt().build(); infcx.predicate_must_hold_modulo_regions(&obligation) @@ -1252,7 +1252,7 @@ fn has_ref_mut_self_method(cx: &LateContext<'_>, trait_def_id: DefId) -> bool { .in_definition_order() .any(|assoc_item| { if assoc_item.fn_has_self_parameter { - let self_ty = cx.tcx.fn_sig(assoc_item.def_id).subst_identity().skip_binder().inputs()[0]; + let self_ty = cx.tcx.fn_sig(assoc_item.def_id).instantiate_identity().skip_binder().inputs()[0]; matches!(self_ty.kind(), ty::Ref(_, _, Mutability::Mut)) } else { false @@ -1323,7 +1323,7 @@ fn referent_used_exactly_once<'tcx>( } } -// Iteratively replaces `param_ty` with `new_ty` in `substs`, and similarly for each resulting +// Iteratively replaces `param_ty` with `new_ty` in `args`, and similarly for each resulting // projected type that is a type parameter. Returns `false` if replacing the types would have an // effect on the function signature beyond substituting `new_ty` for `param_ty`. // See: https://github.com/rust-lang/rust-clippy/pull/9136#discussion_r927212757 @@ -1334,11 +1334,11 @@ fn replace_types<'tcx>( fn_sig: FnSig<'tcx>, arg_index: usize, projection_predicates: &[ProjectionPredicate<'tcx>], - substs: &mut [ty::GenericArg<'tcx>], + args: &mut [ty::GenericArg<'tcx>], ) -> bool { - let mut replaced = BitSet::new_empty(substs.len()); + let mut replaced = BitSet::new_empty(args.len()); - let mut deque = VecDeque::with_capacity(substs.len()); + let mut deque = VecDeque::with_capacity(args.len()); deque.push_back((param_ty, new_ty)); while let Some((param_ty, new_ty)) = deque.pop_front() { @@ -1352,7 +1352,7 @@ fn replace_types<'tcx>( return false; } - substs[param_ty.index as usize] = ty::GenericArg::from(new_ty); + args[param_ty.index as usize] = ty::GenericArg::from(new_ty); // The `replaced.insert(...)` check provides some protection against infinite loops. if replaced.insert(param_ty.index) { @@ -1367,7 +1367,7 @@ fn replace_types<'tcx>( )); if let Ok(projected_ty) = cx.tcx.try_normalize_erasing_regions(cx.param_env, projection) - && substs[term_param_ty.index as usize] != ty::GenericArg::from(projected_ty) + && args[term_param_ty.index as usize] != ty::GenericArg::from(projected_ty) { deque.push_back((*term_param_ty, projected_ty)); } @@ -1442,7 +1442,7 @@ fn ty_auto_deref_stability<'tcx>( ty::Adt(..) if ty.has_placeholders() || ty.has_opaque_types() => { Position::ReborrowStable(precedence).into() }, - ty::Adt(_, substs) if substs.has_non_region_param() => { + ty::Adt(_, args) if args.has_non_region_param() => { TyPosition::new_deref_stable_for_result(precedence, ty) }, ty::Bool diff --git a/src/tools/clippy/clippy_lints/src/derivable_impls.rs b/src/tools/clippy/clippy_lints/src/derivable_impls.rs index 020ffe7f8fa..71b5104bed8 100644 --- a/src/tools/clippy/clippy_lints/src/derivable_impls.rs +++ b/src/tools/clippy/clippy_lints/src/derivable_impls.rs @@ -10,7 +10,7 @@ use rustc_hir::{ }; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty::adjustment::{Adjust, PointerCoercion}; -use rustc_middle::ty::{self, Adt, AdtDef, SubstsRef, Ty, TypeckResults}; +use rustc_middle::ty::{self, Adt, AdtDef, GenericArgsRef, Ty, TypeckResults}; use rustc_session::{declare_tool_lint, impl_lint_pass}; use rustc_span::sym; @@ -80,7 +80,7 @@ fn is_path_self(e: &Expr<'_>) -> bool { fn contains_trait_object(ty: Ty<'_>) -> bool { match ty.kind() { ty::Ref(_, ty, _) => contains_trait_object(*ty), - ty::Adt(def, substs) => def.is_box() && substs[0].as_type().map_or(false, contains_trait_object), + ty::Adt(def, args) => def.is_box() && args[0].as_type().map_or(false, contains_trait_object), ty::Dynamic(..) => true, _ => false, } @@ -92,18 +92,18 @@ fn check_struct<'tcx>( self_ty: &hir::Ty<'_>, func_expr: &Expr<'_>, adt_def: AdtDef<'_>, - substs: SubstsRef<'_>, + ty_args: GenericArgsRef<'_>, typeck_results: &'tcx TypeckResults<'tcx>, ) { if let TyKind::Path(QPath::Resolved(_, p)) = self_ty.kind { if let Some(PathSegment { args, .. }) = p.segments.last() { let args = args.map(|a| a.args).unwrap_or(&[]); - // substs contains the generic parameters of the type declaration, while args contains the arguments + // ty_args contains the generic parameters of the type declaration, while args contains the arguments // used at instantiation time. If both len are not equal, it means that some parameters were not // provided (which means that the default values were used); in this case we will not risk // suggesting too broad a rewrite. We won't either if any argument is a type or a const. - if substs.len() != args.len() || args.iter().any(|arg| !matches!(arg, GenericArg::Lifetime(_))) { + if ty_args.len() != args.len() || args.iter().any(|arg| !matches!(arg, GenericArg::Lifetime(_))) { return; } } @@ -214,7 +214,7 @@ impl<'tcx> LateLintPass<'tcx> for DerivableImpls { if let Some(Node::ImplItem(impl_item)) = cx.tcx.hir().find(impl_item_hir); if let ImplItemKind::Fn(_, b) = &impl_item.kind; if let Body { value: func_expr, .. } = cx.tcx.hir().body(*b); - if let &Adt(adt_def, substs) = cx.tcx.type_of(item.owner_id).subst_identity().kind(); + if let &Adt(adt_def, args) = cx.tcx.type_of(item.owner_id).instantiate_identity().kind(); if let attrs = cx.tcx.hir().attrs(item.hir_id()); if !attrs.iter().any(|attr| attr.doc_str().is_some()); if let child_attrs = cx.tcx.hir().attrs(impl_item_hir); @@ -222,7 +222,7 @@ impl<'tcx> LateLintPass<'tcx> for DerivableImpls { then { if adt_def.is_struct() { - check_struct(cx, item, self_ty, func_expr, adt_def, substs, cx.tcx.typeck_body(*b)); + check_struct(cx, item, self_ty, func_expr, adt_def, args, cx.tcx.typeck_body(*b)); } else if adt_def.is_enum() && self.msrv.meets(msrvs::DEFAULT_ENUM_ATTRIBUTE) { check_enum(cx, item, func_expr, adt_def); } diff --git a/src/tools/clippy/clippy_lints/src/derive.rs b/src/tools/clippy/clippy_lints/src/derive.rs index a005a360e9c..78e7f93e2bf 100644 --- a/src/tools/clippy/clippy_lints/src/derive.rs +++ b/src/tools/clippy/clippy_lints/src/derive.rs @@ -211,7 +211,7 @@ impl<'tcx> LateLintPass<'tcx> for Derive { .. }) = item.kind { - let ty = cx.tcx.type_of(item.owner_id).subst_identity(); + let ty = cx.tcx.type_of(item.owner_id).instantiate_identity(); let is_automatically_derived = cx.tcx.has_attr(item.owner_id, sym::automatically_derived); check_hash_peq(cx, item.span, trait_ref, ty, is_automatically_derived); @@ -252,7 +252,7 @@ fn check_hash_peq<'tcx>( // Only care about `impl PartialEq<Foo> for Foo` // For `impl PartialEq<B> for A, input_types is [A, B] - if trait_ref.subst_identity().substs.type_at(1) == ty { + if trait_ref.instantiate_identity().args.type_at(1) == ty { span_lint_and_then( cx, DERIVED_HASH_WITH_MANUAL_EQ, @@ -300,7 +300,7 @@ fn check_ord_partial_ord<'tcx>( // Only care about `impl PartialOrd<Foo> for Foo` // For `impl PartialOrd<B> for A, input_types is [A, B] - if trait_ref.subst_identity().substs.type_at(1) == ty { + if trait_ref.instantiate_identity().args.type_at(1) == ty { let mess = if partial_ord_is_automatically_derived { "you are implementing `Ord` explicitly but have derived `PartialOrd`" } else { @@ -347,7 +347,7 @@ fn check_copy_clone<'tcx>(cx: &LateContext<'tcx>, item: &Item<'_>, trait_ref: &h let has_copy_impl = cx.tcx.all_local_trait_impls(()).get(©_id).map_or(false, |impls| { impls .iter() - .any(|&id| matches!(cx.tcx.type_of(id).subst_identity().kind(), ty::Adt(adt, _) if ty_adt.did() == adt.did())) + .any(|&id| matches!(cx.tcx.type_of(id).instantiate_identity().kind(), ty::Adt(adt, _) if ty_adt.did() == adt.did())) }); if !has_copy_impl { return; @@ -464,7 +464,7 @@ impl<'tcx> Visitor<'tcx> for UnsafeVisitor<'_, 'tcx> { /// Implementation of the `DERIVE_PARTIAL_EQ_WITHOUT_EQ` lint. fn check_partial_eq_without_eq<'tcx>(cx: &LateContext<'tcx>, span: Span, trait_ref: &hir::TraitRef<'_>, ty: Ty<'tcx>) { if_chain! { - if let ty::Adt(adt, substs) = ty.kind(); + if let ty::Adt(adt, args) = ty.kind(); if cx.tcx.visibility(adt.did()).is_public(); if let Some(eq_trait_def_id) = cx.tcx.get_diagnostic_item(sym::Eq); if let Some(def_id) = trait_ref.trait_def_id(); @@ -474,7 +474,7 @@ fn check_partial_eq_without_eq<'tcx>(cx: &LateContext<'tcx>, span: Span, trait_r // If all of our fields implement `Eq`, we can implement `Eq` too if adt .all_fields() - .map(|f| f.ty(cx.tcx, substs)) + .map(|f| f.ty(cx.tcx, args)) .all(|ty| implements_trait_with_env(cx.tcx, param_env, ty, eq_trait_def_id, [])); then { span_lint_and_sugg( diff --git a/src/tools/clippy/clippy_lints/src/empty_enum.rs b/src/tools/clippy/clippy_lints/src/empty_enum.rs index d94664daa56..1701d061128 100644 --- a/src/tools/clippy/clippy_lints/src/empty_enum.rs +++ b/src/tools/clippy/clippy_lints/src/empty_enum.rs @@ -49,7 +49,7 @@ impl<'tcx> LateLintPass<'tcx> for EmptyEnum { } if let ItemKind::Enum(..) = item.kind { - let ty = cx.tcx.type_of(item.owner_id).subst_identity(); + let ty = cx.tcx.type_of(item.owner_id).instantiate_identity(); let adt = ty.ty_adt_def().expect("already checked whether this is an enum"); if adt.variants().is_empty() { span_lint_and_help( diff --git a/src/tools/clippy/clippy_lints/src/enum_clike.rs b/src/tools/clippy/clippy_lints/src/enum_clike.rs index d85650712db..96c5c7fc509 100644 --- a/src/tools/clippy/clippy_lints/src/enum_clike.rs +++ b/src/tools/clippy/clippy_lints/src/enum_clike.rs @@ -45,7 +45,7 @@ impl<'tcx> LateLintPass<'tcx> for UnportableVariant { for var in def.variants { if let Some(anon_const) = &var.disr_expr { let def_id = cx.tcx.hir().body_owner_def_id(anon_const.body); - let mut ty = cx.tcx.type_of(def_id.to_def_id()).subst_identity(); + let mut ty = cx.tcx.type_of(def_id.to_def_id()).instantiate_identity(); let constant = cx .tcx .const_eval_poly(def_id.to_def_id()) diff --git a/src/tools/clippy/clippy_lints/src/eta_reduction.rs b/src/tools/clippy/clippy_lints/src/eta_reduction.rs index 58e62d1f3d3..22e10accd35 100644 --- a/src/tools/clippy/clippy_lints/src/eta_reduction.rs +++ b/src/tools/clippy/clippy_lints/src/eta_reduction.rs @@ -11,7 +11,7 @@ use rustc_hir::{Closure, Expr, ExprKind, Param, PatKind, Unsafety}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty::adjustment::{Adjust, Adjustment, AutoBorrow}; use rustc_middle::ty::binding::BindingMode; -use rustc_middle::ty::{self, EarlyBinder, SubstsRef, Ty, TypeVisitableExt}; +use rustc_middle::ty::{self, EarlyBinder, GenericArgsRef, Ty, TypeVisitableExt}; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::symbol::sym; @@ -108,18 +108,18 @@ impl<'tcx> LateLintPass<'tcx> for EtaReduction { if check_inputs(cx, body.params, None, args); let callee_ty = cx.typeck_results().expr_ty_adjusted(callee); let call_ty = cx.typeck_results().type_dependent_def_id(body.value.hir_id) - .map_or(callee_ty, |id| cx.tcx.type_of(id).subst_identity()); + .map_or(callee_ty, |id| cx.tcx.type_of(id).instantiate_identity()); if check_sig(cx, closure_ty, call_ty); - let substs = cx.typeck_results().node_substs(callee.hir_id); + let args = cx.typeck_results().node_args(callee.hir_id); // This fixes some false positives that I don't entirely understand - if substs.is_empty() || !cx.typeck_results().expr_ty(expr).has_late_bound_regions(); + if args.is_empty() || !cx.typeck_results().expr_ty(expr).has_late_bound_regions(); // A type param function ref like `T::f` is not 'static, however // it is if cast like `T::f as fn()`. This seems like a rustc bug. - if !substs.types().any(|t| matches!(t.kind(), ty::Param(_))); + if !args.types().any(|t| matches!(t.kind(), ty::Param(_))); let callee_ty_unadjusted = cx.typeck_results().expr_ty(callee).peel_refs(); if !is_type_diagnostic_item(cx, callee_ty_unadjusted, sym::Arc); if !is_type_diagnostic_item(cx, callee_ty_unadjusted, sym::Rc); - if let ty::Closure(_, substs) = *closure_ty.kind(); + if let ty::Closure(_, args) = *closure_ty.kind(); // Don't lint if this is an inclusive range expression. // They desugar to a call to `RangeInclusiveNew` which would have odd suggestions. (#10684) if !matches!(higher::Range::hir(body.value), Some(higher::Range { @@ -131,7 +131,7 @@ impl<'tcx> LateLintPass<'tcx> for EtaReduction { span_lint_and_then(cx, REDUNDANT_CLOSURE, expr.span, "redundant closure", |diag| { if let Some(mut snippet) = snippet_opt(cx, callee.span) { if let Some(fn_mut_id) = cx.tcx.lang_items().fn_mut_trait() - && let args = cx.tcx.erase_late_bound_regions(substs.as_closure().sig()).inputs() + && let args = cx.tcx.erase_late_bound_regions(args.as_closure().sig()).inputs() && implements_trait( cx, callee_ty.peel_refs(), @@ -160,12 +160,12 @@ impl<'tcx> LateLintPass<'tcx> for EtaReduction { if let ExprKind::MethodCall(path, receiver, args, _) = body.value.kind; if check_inputs(cx, body.params, Some(receiver), args); let method_def_id = cx.typeck_results().type_dependent_def_id(body.value.hir_id).unwrap(); - let substs = cx.typeck_results().node_substs(body.value.hir_id); - let call_ty = cx.tcx.type_of(method_def_id).subst(cx.tcx, substs); + let args = cx.typeck_results().node_args(body.value.hir_id); + let call_ty = cx.tcx.type_of(method_def_id).instantiate(cx.tcx, args); if check_sig(cx, closure_ty, call_ty); then { span_lint_and_then(cx, REDUNDANT_CLOSURE_FOR_METHOD_CALLS, expr.span, "redundant closure", |diag| { - let name = get_ufcs_type_name(cx, method_def_id, substs); + let name = get_ufcs_type_name(cx, method_def_id, args); diag.span_suggestion( expr.span, "replace the closure with the method itself", @@ -228,14 +228,14 @@ fn check_sig<'tcx>(cx: &LateContext<'tcx>, closure_ty: Ty<'tcx>, call_ty: Ty<'tc if !closure_ty.has_late_bound_regions() { return true; } - let ty::Closure(_, substs) = closure_ty.kind() else { + let ty::Closure(_, args) = closure_ty.kind() else { return false; }; - let closure_sig = cx.tcx.signature_unclosure(substs.as_closure().sig(), Unsafety::Normal); + let closure_sig = cx.tcx.signature_unclosure(args.as_closure().sig(), Unsafety::Normal); cx.tcx.erase_late_bound_regions(closure_sig) == cx.tcx.erase_late_bound_regions(call_sig) } -fn get_ufcs_type_name<'tcx>(cx: &LateContext<'tcx>, method_def_id: DefId, substs: SubstsRef<'tcx>) -> String { +fn get_ufcs_type_name<'tcx>(cx: &LateContext<'tcx>, method_def_id: DefId, args: GenericArgsRef<'tcx>) -> String { let assoc_item = cx.tcx.associated_item(method_def_id); let def_id = assoc_item.container_id(cx.tcx); match assoc_item.container { @@ -251,7 +251,7 @@ fn get_ufcs_type_name<'tcx>(cx: &LateContext<'tcx>, method_def_id: DefId, substs | ty::Ref(..) | ty::Slice(_) | ty::Tuple(_) => { - format!("<{}>", EarlyBinder::bind(ty).subst(cx.tcx, substs)) + format!("<{}>", EarlyBinder::bind(ty).instantiate(cx.tcx, args)) }, _ => ty.to_string(), } diff --git a/src/tools/clippy/clippy_lints/src/from_over_into.rs b/src/tools/clippy/clippy_lints/src/from_over_into.rs index 92d67ef359d..35061fc64c9 100644 --- a/src/tools/clippy/clippy_lints/src/from_over_into.rs +++ b/src/tools/clippy/clippy_lints/src/from_over_into.rs @@ -76,9 +76,9 @@ impl<'tcx> LateLintPass<'tcx> for FromOverInto { && let Some(into_trait_seg) = hir_trait_ref.path.segments.last() // `impl Into<target_ty> for self_ty` && let Some(GenericArgs { args: [GenericArg::Type(target_ty)], .. }) = into_trait_seg.args - && let Some(middle_trait_ref) = cx.tcx.impl_trait_ref(item.owner_id).map(ty::EarlyBinder::subst_identity) + && let Some(middle_trait_ref) = cx.tcx.impl_trait_ref(item.owner_id).map(ty::EarlyBinder::instantiate_identity) && cx.tcx.is_diagnostic_item(sym::Into, middle_trait_ref.def_id) - && !matches!(middle_trait_ref.substs.type_at(1).kind(), ty::Alias(ty::Opaque, _)) + && !matches!(middle_trait_ref.args.type_at(1).kind(), ty::Alias(ty::Opaque, _)) { span_lint_and_then( cx, diff --git a/src/tools/clippy/clippy_lints/src/functions/must_use.rs b/src/tools/clippy/clippy_lints/src/functions/must_use.rs index d0ad2628264..1b173de856b 100644 --- a/src/tools/clippy/clippy_lints/src/functions/must_use.rs +++ b/src/tools/clippy/clippy_lints/src/functions/must_use.rs @@ -198,14 +198,14 @@ fn is_mutable_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>, tys: &mut DefIdSet) match *ty.kind() { // primitive types are never mutable ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Str => false, - ty::Adt(adt, substs) => { + ty::Adt(adt, args) => { tys.insert(adt.did()) && !ty.is_freeze(cx.tcx, cx.param_env) || KNOWN_WRAPPER_TYS .iter() .any(|&sym| cx.tcx.is_diagnostic_item(sym, adt.did())) - && substs.types().any(|ty| is_mutable_ty(cx, ty, tys)) + && args.types().any(|ty| is_mutable_ty(cx, ty, tys)) }, - ty::Tuple(substs) => substs.iter().any(|ty| is_mutable_ty(cx, ty, tys)), + ty::Tuple(args) => args.iter().any(|ty| is_mutable_ty(cx, ty, tys)), ty::Array(ty, _) | ty::Slice(ty) => is_mutable_ty(cx, ty, tys), ty::RawPtr(ty::TypeAndMut { ty, mutbl }) | ty::Ref(_, ty, mutbl) => { mutbl == hir::Mutability::Mut || is_mutable_ty(cx, ty, tys) diff --git a/src/tools/clippy/clippy_lints/src/functions/result.rs b/src/tools/clippy/clippy_lints/src/functions/result.rs index fa2a9b30c05..90fc0d4f662 100644 --- a/src/tools/clippy/clippy_lints/src/functions/result.rs +++ b/src/tools/clippy/clippy_lints/src/functions/result.rs @@ -21,11 +21,11 @@ fn result_err_ty<'tcx>( ) -> Option<(&'tcx hir::Ty<'tcx>, Ty<'tcx>)> { if !in_external_macro(cx.sess(), item_span) && let hir::FnRetTy::Return(hir_ty) = decl.output - && let ty = cx.tcx.erase_late_bound_regions(cx.tcx.fn_sig(id).subst_identity().output()) + && let ty = cx.tcx.erase_late_bound_regions(cx.tcx.fn_sig(id).instantiate_identity().output()) && is_type_diagnostic_item(cx, ty, sym::Result) - && let ty::Adt(_, substs) = ty.kind() + && let ty::Adt(_, args) = ty.kind() { - let err_ty = substs.type_at(1); + let err_ty = args.type_at(1); Some((hir_ty, err_ty)) } else { None diff --git a/src/tools/clippy/clippy_lints/src/future_not_send.rs b/src/tools/clippy/clippy_lints/src/future_not_send.rs index 818ebd1134d..e54429aee8e 100644 --- a/src/tools/clippy/clippy_lints/src/future_not_send.rs +++ b/src/tools/clippy/clippy_lints/src/future_not_send.rs @@ -63,10 +63,10 @@ impl<'tcx> LateLintPass<'tcx> for FutureNotSend { return; } let ret_ty = return_ty(cx, cx.tcx.hir().local_def_id_to_hir_id(fn_def_id).expect_owner()); - if let ty::Alias(ty::Opaque, AliasTy { def_id, substs, .. }) = *ret_ty.kind() { + if let ty::Alias(ty::Opaque, AliasTy { def_id, args, .. }) = *ret_ty.kind() { let preds = cx.tcx.explicit_item_bounds(def_id); let mut is_future = false; - for (p, _span) in preds.subst_iter_copied(cx.tcx, substs) { + for (p, _span) in preds.arg_iter_copied(cx.tcx, args) { if let Some(trait_pred) = p.as_trait_clause() { if Some(trait_pred.skip_binder().trait_ref.def_id) == cx.tcx.lang_items().future_trait() { is_future = true; diff --git a/src/tools/clippy/clippy_lints/src/implicit_saturating_sub.rs b/src/tools/clippy/clippy_lints/src/implicit_saturating_sub.rs index 1e99b6faa6c..b99d4544681 100644 --- a/src/tools/clippy/clippy_lints/src/implicit_saturating_sub.rs +++ b/src/tools/clippy/clippy_lints/src/implicit_saturating_sub.rs @@ -102,7 +102,7 @@ impl<'tcx> LateLintPass<'tcx> for ImplicitSaturatingSub { if let Some(const_id) = cx.typeck_results().type_dependent_def_id(cond_num_val.hir_id); if let Some(impl_id) = cx.tcx.impl_of_method(const_id); if let None = cx.tcx.impl_trait_ref(impl_id); // An inherent impl - if cx.tcx.type_of(impl_id).subst_identity().is_integral(); + if cx.tcx.type_of(impl_id).instantiate_identity().is_integral(); then { print_lint_and_sugg(cx, var_name, expr) } @@ -115,7 +115,7 @@ impl<'tcx> LateLintPass<'tcx> for ImplicitSaturatingSub { if let Some(func_id) = cx.typeck_results().type_dependent_def_id(func.hir_id); if let Some(impl_id) = cx.tcx.impl_of_method(func_id); if let None = cx.tcx.impl_trait_ref(impl_id); // An inherent impl - if cx.tcx.type_of(impl_id).subst_identity().is_integral(); + if cx.tcx.type_of(impl_id).instantiate_identity().is_integral(); then { print_lint_and_sugg(cx, var_name, expr) } diff --git a/src/tools/clippy/clippy_lints/src/inherent_impl.rs b/src/tools/clippy/clippy_lints/src/inherent_impl.rs index 7c41699f307..3ac40401e89 100644 --- a/src/tools/clippy/clippy_lints/src/inherent_impl.rs +++ b/src/tools/clippy/clippy_lints/src/inherent_impl.rs @@ -66,7 +66,7 @@ impl<'tcx> LateLintPass<'tcx> for MultipleInherentImpl { ) }) { for impl_id in impl_ids.iter().map(|id| id.expect_local()) { - let impl_ty = cx.tcx.type_of(impl_id).subst_identity(); + let impl_ty = cx.tcx.type_of(impl_id).instantiate_identity(); match type_map.entry(impl_ty) { Entry::Vacant(e) => { // Store the id for the first impl block of this type. The span is retrieved lazily. diff --git a/src/tools/clippy/clippy_lints/src/iter_not_returning_iterator.rs b/src/tools/clippy/clippy_lints/src/iter_not_returning_iterator.rs index c924d7361ce..bb100ec632e 100644 --- a/src/tools/clippy/clippy_lints/src/iter_not_returning_iterator.rs +++ b/src/tools/clippy/clippy_lints/src/iter_not_returning_iterator.rs @@ -68,7 +68,7 @@ fn check_sig(cx: &LateContext<'_>, name: &str, sig: &FnSig<'_>, fn_id: LocalDefI if sig.decl.implicit_self.has_implicit_self() { let ret_ty = cx .tcx - .erase_late_bound_regions(cx.tcx.fn_sig(fn_id).subst_identity().output()); + .erase_late_bound_regions(cx.tcx.fn_sig(fn_id).instantiate_identity().output()); let ret_ty = cx .tcx .try_normalize_erasing_regions(cx.param_env, ret_ty) diff --git a/src/tools/clippy/clippy_lints/src/large_enum_variant.rs b/src/tools/clippy/clippy_lints/src/large_enum_variant.rs index 1c99bd2f3d0..693218f8a9c 100644 --- a/src/tools/clippy/clippy_lints/src/large_enum_variant.rs +++ b/src/tools/clippy/clippy_lints/src/large_enum_variant.rs @@ -83,7 +83,7 @@ impl<'tcx> LateLintPass<'tcx> for LargeEnumVariant { return; } if let ItemKind::Enum(ref def, _) = item.kind { - let ty = cx.tcx.type_of(item.owner_id).subst_identity(); + let ty = cx.tcx.type_of(item.owner_id).instantiate_identity(); let Adt(adt, subst) = ty.kind() else { panic!("already checked whether this is an enum") }; @@ -169,8 +169,8 @@ impl<'tcx> LateLintPass<'tcx> for LargeEnumVariant { } fn maybe_copy<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool { - if let Adt(_def, substs) = ty.kind() - && substs.types().next().is_some() + if let Adt(_def, args) = ty.kind() + && args.types().next().is_some() && let Some(copy_trait) = cx.tcx.lang_items().copy_trait() { return cx.tcx.non_blanket_impls_for_ty(copy_trait, ty).next().is_some(); diff --git a/src/tools/clippy/clippy_lints/src/len_zero.rs b/src/tools/clippy/clippy_lints/src/len_zero.rs index 17bd89efaee..83fa25c795a 100644 --- a/src/tools/clippy/clippy_lints/src/len_zero.rs +++ b/src/tools/clippy/clippy_lints/src/len_zero.rs @@ -145,7 +145,7 @@ impl<'tcx> LateLintPass<'tcx> for LenZero { if let Some(local_id) = ty_id.as_local(); let ty_hir_id = cx.tcx.hir().local_def_id_to_hir_id(local_id); if !is_lint_allowed(cx, LEN_WITHOUT_IS_EMPTY, ty_hir_id); - if let Some(output) = parse_len_output(cx, cx.tcx.fn_sig(item.owner_id).subst_identity().skip_binder()); + if let Some(output) = parse_len_output(cx, cx.tcx.fn_sig(item.owner_id).instantiate_identity().skip_binder()); then { let (name, kind) = match cx.tcx.hir().find(ty_hir_id) { Some(Node::ForeignItem(x)) => (x.ident.name, "extern type"), @@ -425,7 +425,7 @@ fn check_for_is_empty( if !(is_empty.fn_has_self_parameter && check_is_empty_sig( cx, - cx.tcx.fn_sig(is_empty.def_id).subst_identity().skip_binder(), + cx.tcx.fn_sig(is_empty.def_id).instantiate_identity().skip_binder(), self_kind, output, )) => diff --git a/src/tools/clippy/clippy_lints/src/let_underscore.rs b/src/tools/clippy/clippy_lints/src/let_underscore.rs index e6614180920..b7a47002080 100644 --- a/src/tools/clippy/clippy_lints/src/let_underscore.rs +++ b/src/tools/clippy/clippy_lints/src/let_underscore.rs @@ -5,7 +5,7 @@ use clippy_utils::{is_must_use_func_call, paths}; use rustc_hir::{Local, PatKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::lint::in_external_macro; -use rustc_middle::ty::subst::GenericArgKind; +use rustc_middle::ty::GenericArgKind; use rustc_middle::ty::IsSuggestable; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::{BytePos, Span}; diff --git a/src/tools/clippy/clippy_lints/src/loops/explicit_iter_loop.rs b/src/tools/clippy/clippy_lints/src/loops/explicit_iter_loop.rs index 5c5a4cfce88..a84a0a6eeb8 100644 --- a/src/tools/clippy/clippy_lints/src/loops/explicit_iter_loop.rs +++ b/src/tools/clippy/clippy_lints/src/loops/explicit_iter_loop.rs @@ -125,7 +125,7 @@ fn is_ref_iterable<'tcx>( } let res_ty = cx.tcx.erase_regions(EarlyBinder::bind(req_res_ty) - .subst(cx.tcx, typeck.node_substs(call_expr.hir_id))); + .instantiate(cx.tcx, typeck.node_args(call_expr.hir_id))); let mutbl = if let ty::Ref(_, _, mutbl) = *req_self_ty.kind() { Some(mutbl) } else { diff --git a/src/tools/clippy/clippy_lints/src/loops/missing_spin_loop.rs b/src/tools/clippy/clippy_lints/src/loops/missing_spin_loop.rs index 8412875b11b..0e49f08d898 100644 --- a/src/tools/clippy/clippy_lints/src/loops/missing_spin_loop.rs +++ b/src/tools/clippy/clippy_lints/src/loops/missing_spin_loop.rs @@ -35,7 +35,7 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, cond: &'tcx Expr<'_>, body: &' if let ExprKind::Block(Block { stmts: [], expr: None, ..}, _) = body.kind; if let ExprKind::MethodCall(method, callee, ..) = unpack_cond(cond).kind; if [sym::load, sym::compare_exchange, sym::compare_exchange_weak].contains(&method.ident.name); - if let ty::Adt(def, _substs) = cx.typeck_results().expr_ty(callee).kind(); + if let ty::Adt(def, _args) = cx.typeck_results().expr_ty(callee).kind(); if cx.tcx.is_diagnostic_item(sym::AtomicBool, def.did()); then { span_lint_and_sugg( diff --git a/src/tools/clippy/clippy_lints/src/loops/needless_range_loop.rs b/src/tools/clippy/clippy_lints/src/loops/needless_range_loop.rs index cb446567506..2c20e9e8693 100644 --- a/src/tools/clippy/clippy_lints/src/loops/needless_range_loop.rs +++ b/src/tools/clippy/clippy_lints/src/loops/needless_range_loop.rs @@ -370,7 +370,7 @@ impl<'a, 'tcx> Visitor<'tcx> for VarVisitor<'a, 'tcx> { ExprKind::MethodCall(_, receiver, args, _) => { let def_id = self.cx.typeck_results().type_dependent_def_id(expr.hir_id).unwrap(); for (ty, expr) in iter::zip( - self.cx.tcx.fn_sig(def_id).subst_identity().inputs().skip_binder(), + self.cx.tcx.fn_sig(def_id).instantiate_identity().inputs().skip_binder(), std::iter::once(receiver).chain(args.iter()), ) { self.prefer_mutable = false; diff --git a/src/tools/clippy/clippy_lints/src/manual_bits.rs b/src/tools/clippy/clippy_lints/src/manual_bits.rs index 4629b22d171..6c7c57ba1d6 100644 --- a/src/tools/clippy/clippy_lints/src/manual_bits.rs +++ b/src/tools/clippy/clippy_lints/src/manual_bits.rs @@ -110,7 +110,7 @@ fn get_size_of_ty<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option< if let Some(def_id) = cx.qpath_res(count_func_qpath, count_func.hir_id).opt_def_id(); if cx.tcx.is_diagnostic_item(sym::mem_size_of, def_id); then { - cx.typeck_results().node_substs(count_func.hir_id).types().next().map(|resolved_ty| (*real_ty, resolved_ty)) + cx.typeck_results().node_args(count_func.hir_id).types().next().map(|resolved_ty| (*real_ty, resolved_ty)) } else { None } diff --git a/src/tools/clippy/clippy_lints/src/manual_slice_size_calculation.rs b/src/tools/clippy/clippy_lints/src/manual_slice_size_calculation.rs index 703a6b25840..f97600b53e4 100644 --- a/src/tools/clippy/clippy_lints/src/manual_slice_size_calculation.rs +++ b/src/tools/clippy/clippy_lints/src/manual_slice_size_calculation.rs @@ -92,7 +92,7 @@ fn simplify_half<'tcx>( && let ExprKind::Path(ref func_qpath) = func.kind && let Some(def_id) = cx.qpath_res(func_qpath, func.hir_id).opt_def_id() && cx.tcx.is_diagnostic_item(sym::mem_size_of, def_id) - && let Some(ty2) = cx.typeck_results().node_substs(func.hir_id).types().next() + && let Some(ty2) = cx.typeck_results().node_args(func.hir_id).types().next() // T1 == T2? && *ty1 == ty2 { diff --git a/src/tools/clippy/clippy_lints/src/map_unit_fn.rs b/src/tools/clippy/clippy_lints/src/map_unit_fn.rs index edcab6968cb..75605fb3091 100644 --- a/src/tools/clippy/clippy_lints/src/map_unit_fn.rs +++ b/src/tools/clippy/clippy_lints/src/map_unit_fn.rs @@ -104,7 +104,7 @@ fn is_unit_function(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> bool { let ty = cx.typeck_results().expr_ty(expr); if let ty::FnDef(id, _) = *ty.kind() { - if let Some(fn_type) = cx.tcx.fn_sig(id).subst_identity().no_bound_vars() { + if let Some(fn_type) = cx.tcx.fn_sig(id).instantiate_identity().no_bound_vars() { return is_unit_type(fn_type.output()); } } diff --git a/src/tools/clippy/clippy_lints/src/matches/match_as_ref.rs b/src/tools/clippy/clippy_lints/src/matches/match_as_ref.rs index 2818f030b7a..29c6e11134f 100644 --- a/src/tools/clippy/clippy_lints/src/matches/match_as_ref.rs +++ b/src/tools/clippy/clippy_lints/src/matches/match_as_ref.rs @@ -27,10 +27,10 @@ pub(crate) fn check(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>], expr: let input_ty = cx.typeck_results().expr_ty(ex); let cast = if_chain! { - if let ty::Adt(_, substs) = input_ty.kind(); - let input_ty = substs.type_at(0); - if let ty::Adt(_, substs) = output_ty.kind(); - let output_ty = substs.type_at(0); + if let ty::Adt(_, args) = input_ty.kind(); + let input_ty = args.type_at(0); + if let ty::Adt(_, args) = output_ty.kind(); + let output_ty = args.type_at(0); if let ty::Ref(_, output_ty, _) = *output_ty.kind(); if input_ty != output_ty; then { diff --git a/src/tools/clippy/clippy_lints/src/matches/redundant_pattern_match.rs b/src/tools/clippy/clippy_lints/src/matches/redundant_pattern_match.rs index 479cfd83512..039c2134cf8 100644 --- a/src/tools/clippy/clippy_lints/src/matches/redundant_pattern_match.rs +++ b/src/tools/clippy/clippy_lints/src/matches/redundant_pattern_match.rs @@ -12,7 +12,7 @@ use rustc_hir::def::{DefKind, Res}; use rustc_hir::LangItem::{self, OptionNone, OptionSome, PollPending, PollReady, ResultErr, ResultOk}; use rustc_hir::{Arm, Expr, ExprKind, Node, Pat, PatKind, QPath, UnOp}; use rustc_lint::LateContext; -use rustc_middle::ty::{self, subst::GenericArgKind, Ty}; +use rustc_middle::ty::{self, GenericArgKind, Ty}; use rustc_span::{sym, Symbol}; pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { diff --git a/src/tools/clippy/clippy_lints/src/matches/rest_pat_in_fully_bound_struct.rs b/src/tools/clippy/clippy_lints/src/matches/rest_pat_in_fully_bound_struct.rs index d06bcdaa27f..4efe93d4b54 100644 --- a/src/tools/clippy/clippy_lints/src/matches/rest_pat_in_fully_bound_struct.rs +++ b/src/tools/clippy/clippy_lints/src/matches/rest_pat_in_fully_bound_struct.rs @@ -10,7 +10,7 @@ pub(crate) fn check(cx: &LateContext<'_>, pat: &Pat<'_>) { if !pat.span.from_expansion(); if let PatKind::Struct(QPath::Resolved(_, path), fields, true) = pat.kind; if let Some(def_id) = path.res.opt_def_id(); - let ty = cx.tcx.type_of(def_id).subst_identity(); + let ty = cx.tcx.type_of(def_id).instantiate_identity(); if let ty::Adt(def, _) = ty.kind(); if def.is_struct() || def.is_union(); if fields.len() == def.non_enum_variant().fields.len(); diff --git a/src/tools/clippy/clippy_lints/src/matches/significant_drop_in_scrutinee.rs b/src/tools/clippy/clippy_lints/src/matches/significant_drop_in_scrutinee.rs index 37528d9f7f2..02500fac293 100644 --- a/src/tools/clippy/clippy_lints/src/matches/significant_drop_in_scrutinee.rs +++ b/src/tools/clippy/clippy_lints/src/matches/significant_drop_in_scrutinee.rs @@ -6,7 +6,7 @@ use rustc_errors::{Applicability, Diagnostic}; use rustc_hir::intravisit::{walk_expr, Visitor}; use rustc_hir::{Arm, Expr, ExprKind, MatchSource}; use rustc_lint::{LateContext, LintContext}; -use rustc_middle::ty::subst::GenericArgKind; +use rustc_middle::ty::GenericArgKind; use rustc_middle::ty::{Ty, TypeAndMut}; use rustc_span::Span; diff --git a/src/tools/clippy/clippy_lints/src/methods/bytes_count_to_len.rs b/src/tools/clippy/clippy_lints/src/methods/bytes_count_to_len.rs index 46a20ad412b..649fc46e4ad 100644 --- a/src/tools/clippy/clippy_lints/src/methods/bytes_count_to_len.rs +++ b/src/tools/clippy/clippy_lints/src/methods/bytes_count_to_len.rs @@ -17,7 +17,7 @@ pub(super) fn check<'tcx>( if_chain! { if let Some(bytes_id) = cx.typeck_results().type_dependent_def_id(count_recv.hir_id); if let Some(impl_id) = cx.tcx.impl_of_method(bytes_id); - if cx.tcx.type_of(impl_id).subst_identity().is_str(); + if cx.tcx.type_of(impl_id).instantiate_identity().is_str(); let ty = cx.typeck_results().expr_ty(bytes_recv).peel_refs(); if ty.is_str() || is_type_lang_item(cx, ty, hir::LangItem::String); then { diff --git a/src/tools/clippy/clippy_lints/src/methods/case_sensitive_file_extension_comparisons.rs b/src/tools/clippy/clippy_lints/src/methods/case_sensitive_file_extension_comparisons.rs index 7711aa78b23..fb10f782f7a 100644 --- a/src/tools/clippy/clippy_lints/src/methods/case_sensitive_file_extension_comparisons.rs +++ b/src/tools/clippy/clippy_lints/src/methods/case_sensitive_file_extension_comparisons.rs @@ -30,7 +30,7 @@ pub(super) fn check<'tcx>( if_chain! { if let Some(method_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id); if let Some(impl_id) = cx.tcx.impl_of_method(method_id); - if cx.tcx.type_of(impl_id).subst_identity().is_str(); + if cx.tcx.type_of(impl_id).instantiate_identity().is_str(); if let ExprKind::Lit(Spanned { node: LitKind::Str(ext_literal, ..), ..}) = arg.kind; if (2..=6).contains(&ext_literal.as_str().len()); let ext_str = ext_literal.as_str(); diff --git a/src/tools/clippy/clippy_lints/src/methods/err_expect.rs b/src/tools/clippy/clippy_lints/src/methods/err_expect.rs index ae03da0d3f9..4ab06bf2ae8 100644 --- a/src/tools/clippy/clippy_lints/src/methods/err_expect.rs +++ b/src/tools/clippy/clippy_lints/src/methods/err_expect.rs @@ -47,7 +47,7 @@ pub(super) fn check( /// Given a `Result<T, E>` type, return its data (`T`). fn get_data_type<'a>(cx: &LateContext<'_>, ty: Ty<'a>) -> Option<Ty<'a>> { match ty.kind() { - ty::Adt(_, substs) if is_type_diagnostic_item(cx, ty, sym::Result) => substs.types().next(), + ty::Adt(_, args) if is_type_diagnostic_item(cx, ty, sym::Result) => args.types().next(), _ => None, } } diff --git a/src/tools/clippy/clippy_lints/src/methods/expect_fun_call.rs b/src/tools/clippy/clippy_lints/src/methods/expect_fun_call.rs index 92d21bb8932..9af11f08c26 100644 --- a/src/tools/clippy/clippy_lints/src/methods/expect_fun_call.rs +++ b/src/tools/clippy/clippy_lints/src/methods/expect_fun_call.rs @@ -70,7 +70,7 @@ pub(super) fn check<'tcx>( if let hir::ExprKind::Path(ref p) = fun.kind { match cx.qpath_res(p, fun.hir_id) { hir::def::Res::Def(hir::def::DefKind::Fn | hir::def::DefKind::AssocFn, def_id) => matches!( - cx.tcx.fn_sig(def_id).subst_identity().output().skip_binder().kind(), + cx.tcx.fn_sig(def_id).instantiate_identity().output().skip_binder().kind(), ty::Ref(re, ..) if re.is_static(), ), _ => false, @@ -84,7 +84,7 @@ pub(super) fn check<'tcx>( .type_dependent_def_id(arg.hir_id) .map_or(false, |method_id| { matches!( - cx.tcx.fn_sig(method_id).subst_identity().output().skip_binder().kind(), + cx.tcx.fn_sig(method_id).instantiate_identity().output().skip_binder().kind(), ty::Ref(re, ..) if re.is_static() ) }) diff --git a/src/tools/clippy/clippy_lints/src/methods/flat_map_option.rs b/src/tools/clippy/clippy_lints/src/methods/flat_map_option.rs index 615bde94133..4737a101345 100644 --- a/src/tools/clippy/clippy_lints/src/methods/flat_map_option.rs +++ b/src/tools/clippy/clippy_lints/src/methods/flat_map_option.rs @@ -15,7 +15,7 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>, arg } let arg_ty = cx.typeck_results().expr_ty_adjusted(arg); let sig = match arg_ty.kind() { - ty::Closure(_, substs) => substs.as_closure().sig(), + ty::Closure(_, args) => args.as_closure().sig(), _ if arg_ty.is_fn() => arg_ty.fn_sig(cx.tcx), _ => return, }; diff --git a/src/tools/clippy/clippy_lints/src/methods/get_first.rs b/src/tools/clippy/clippy_lints/src/methods/get_first.rs index 945bbf53bcf..ee063adac64 100644 --- a/src/tools/clippy/clippy_lints/src/methods/get_first.rs +++ b/src/tools/clippy/clippy_lints/src/methods/get_first.rs @@ -19,7 +19,7 @@ pub(super) fn check<'tcx>( if_chain! { if let Some(method_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id); if let Some(impl_id) = cx.tcx.impl_of_method(method_id); - if cx.tcx.type_of(impl_id).subst_identity().is_slice(); + if cx.tcx.type_of(impl_id).instantiate_identity().is_slice(); if let Some(_) = is_slice_of_primitives(cx, recv); if let hir::ExprKind::Lit(Spanned { node: LitKind::Int(0, _), .. }) = arg.kind; then { diff --git a/src/tools/clippy/clippy_lints/src/methods/implicit_clone.rs b/src/tools/clippy/clippy_lints/src/methods/implicit_clone.rs index 5a78a416877..043425300d8 100644 --- a/src/tools/clippy/clippy_lints/src/methods/implicit_clone.rs +++ b/src/tools/clippy/clippy_lints/src/methods/implicit_clone.rs @@ -54,7 +54,7 @@ pub fn is_clone_like(cx: &LateContext<'_>, method_name: &str, method_def_id: hir .tcx .impl_of_method(method_def_id) .filter(|&impl_did| { - cx.tcx.type_of(impl_did).subst_identity().is_slice() && cx.tcx.impl_trait_ref(impl_did).is_none() + cx.tcx.type_of(impl_did).instantiate_identity().is_slice() && cx.tcx.impl_trait_ref(impl_did).is_none() }) .is_some(), _ => false, diff --git a/src/tools/clippy/clippy_lints/src/methods/inefficient_to_string.rs b/src/tools/clippy/clippy_lints/src/methods/inefficient_to_string.rs index 424482859ee..37da52dc733 100644 --- a/src/tools/clippy/clippy_lints/src/methods/inefficient_to_string.rs +++ b/src/tools/clippy/clippy_lints/src/methods/inefficient_to_string.rs @@ -23,9 +23,9 @@ pub fn check( if args.is_empty() && method_name == sym::to_string; if let Some(to_string_meth_did) = cx.typeck_results().type_dependent_def_id(expr.hir_id); if match_def_path(cx, to_string_meth_did, &paths::TO_STRING_METHOD); - if let Some(substs) = cx.typeck_results().node_substs_opt(expr.hir_id); + if let Some(args) = cx.typeck_results().node_args_opt(expr.hir_id); let arg_ty = cx.typeck_results().expr_ty_adjusted(receiver); - let self_ty = substs.type_at(0); + let self_ty = args.type_at(0); let (deref_self_ty, deref_count) = walk_ptrs_ty_depth(self_ty); if deref_count >= 1; if specializes_tostring(cx, deref_self_ty); @@ -64,8 +64,8 @@ fn specializes_tostring(cx: &LateContext<'_>, ty: Ty<'_>) -> bool { return true; } - if let ty::Adt(adt, substs) = ty.kind() { - cx.tcx.is_diagnostic_item(sym::Cow, adt.did()) && substs.type_at(1).is_str() + if let ty::Adt(adt, args) = ty.kind() { + cx.tcx.is_diagnostic_item(sym::Cow, adt.did()) && args.type_at(1).is_str() } else { false } diff --git a/src/tools/clippy/clippy_lints/src/methods/manual_ok_or.rs b/src/tools/clippy/clippy_lints/src/methods/manual_ok_or.rs index b9a0ec77996..3031193e531 100644 --- a/src/tools/clippy/clippy_lints/src/methods/manual_ok_or.rs +++ b/src/tools/clippy/clippy_lints/src/methods/manual_ok_or.rs @@ -21,7 +21,7 @@ pub(super) fn check<'tcx>( if_chain! { if let Some(method_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id); if let Some(impl_id) = cx.tcx.impl_of_method(method_id); - if is_type_diagnostic_item(cx, cx.tcx.type_of(impl_id).subst_identity(), sym::Option); + if is_type_diagnostic_item(cx, cx.tcx.type_of(impl_id).instantiate_identity(), sym::Option); if let ExprKind::Call(err_path, [err_arg]) = or_expr.kind; if is_res_lang_ctor(cx, path_res(cx, err_path), ResultErr); if is_ok_wrapping(cx, map_expr); diff --git a/src/tools/clippy/clippy_lints/src/methods/map_clone.rs b/src/tools/clippy/clippy_lints/src/methods/map_clone.rs index 2b26ef01410..880efe60c1a 100644 --- a/src/tools/clippy/clippy_lints/src/methods/map_clone.rs +++ b/src/tools/clippy/clippy_lints/src/methods/map_clone.rs @@ -19,7 +19,7 @@ pub(super) fn check(cx: &LateContext<'_>, e: &hir::Expr<'_>, recv: &hir::Expr<'_ if_chain! { if let Some(method_id) = cx.typeck_results().type_dependent_def_id(e.hir_id); if cx.tcx.impl_of_method(method_id) - .map_or(false, |id| is_type_diagnostic_item(cx, cx.tcx.type_of(id).subst_identity(), sym::Option)) + .map_or(false, |id| is_type_diagnostic_item(cx, cx.tcx.type_of(id).instantiate_identity(), sym::Option)) || is_diag_trait_item(cx, method_id, sym::Iterator); if let hir::ExprKind::Closure(&hir::Closure{ body, .. }) = arg.kind; then { diff --git a/src/tools/clippy/clippy_lints/src/methods/map_collect_result_unit.rs b/src/tools/clippy/clippy_lints/src/methods/map_collect_result_unit.rs index a0300d27870..042bab805b8 100644 --- a/src/tools/clippy/clippy_lints/src/methods/map_collect_result_unit.rs +++ b/src/tools/clippy/clippy_lints/src/methods/map_collect_result_unit.rs @@ -15,8 +15,8 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, iter: &hir::Expr let collect_ret_ty = cx.typeck_results().expr_ty(expr); if_chain! { if is_type_diagnostic_item(cx, collect_ret_ty, sym::Result); - if let ty::Adt(_, substs) = collect_ret_ty.kind(); - if let Some(result_t) = substs.types().next(); + if let ty::Adt(_, args) = collect_ret_ty.kind(); + if let Some(result_t) = args.types().next(); if result_t.is_unit(); // get parts for snippet then { diff --git a/src/tools/clippy/clippy_lints/src/methods/map_err_ignore.rs b/src/tools/clippy/clippy_lints/src/methods/map_err_ignore.rs index a5beb291f32..fbb83c8ce56 100644 --- a/src/tools/clippy/clippy_lints/src/methods/map_err_ignore.rs +++ b/src/tools/clippy/clippy_lints/src/methods/map_err_ignore.rs @@ -9,7 +9,7 @@ use super::MAP_ERR_IGNORE; pub(super) fn check(cx: &LateContext<'_>, e: &Expr<'_>, arg: &Expr<'_>) { if let Some(method_id) = cx.typeck_results().type_dependent_def_id(e.hir_id) && let Some(impl_id) = cx.tcx.impl_of_method(method_id) - && is_type_diagnostic_item(cx, cx.tcx.type_of(impl_id).subst_identity(), sym::Result) + && is_type_diagnostic_item(cx, cx.tcx.type_of(impl_id).instantiate_identity(), sym::Result) && let ExprKind::Closure(&Closure { capture_clause: CaptureBy::Ref, body, diff --git a/src/tools/clippy/clippy_lints/src/methods/map_flatten.rs b/src/tools/clippy/clippy_lints/src/methods/map_flatten.rs index 361ffcb5ef3..950902d455b 100644 --- a/src/tools/clippy/clippy_lints/src/methods/map_flatten.rs +++ b/src/tools/clippy/clippy_lints/src/methods/map_flatten.rs @@ -59,7 +59,7 @@ fn is_map_to_option(cx: &LateContext<'_>, map_arg: &Expr<'_>) -> bool { match map_closure_ty.kind() { ty::Closure(_, _) | ty::FnDef(_, _) | ty::FnPtr(_) => { let map_closure_sig = match map_closure_ty.kind() { - ty::Closure(_, substs) => substs.as_closure().sig(), + ty::Closure(_, args) => args.as_closure().sig(), _ => map_closure_ty.fn_sig(cx.tcx), }; let map_closure_return_ty = cx.tcx.erase_late_bound_regions(map_closure_sig.output()); diff --git a/src/tools/clippy/clippy_lints/src/methods/mod.rs b/src/tools/clippy/clippy_lints/src/methods/mod.rs index 24dbe8c1d75..9ab78c6f8e0 100644 --- a/src/tools/clippy/clippy_lints/src/methods/mod.rs +++ b/src/tools/clippy/clippy_lints/src/methods/mod.rs @@ -3508,11 +3508,11 @@ impl<'tcx> LateLintPass<'tcx> for Methods { let name = impl_item.ident.name.as_str(); let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id()).def_id; let item = cx.tcx.hir().expect_item(parent); - let self_ty = cx.tcx.type_of(item.owner_id).subst_identity(); + let self_ty = cx.tcx.type_of(item.owner_id).instantiate_identity(); let implements_trait = matches!(item.kind, hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. })); if let hir::ImplItemKind::Fn(ref sig, id) = impl_item.kind { - let method_sig = cx.tcx.fn_sig(impl_item.owner_id).subst_identity(); + let method_sig = cx.tcx.fn_sig(impl_item.owner_id).instantiate_identity(); let method_sig = cx.tcx.erase_late_bound_regions(method_sig); let first_arg_ty_opt = method_sig.inputs().iter().next().copied(); // if this impl block implements a trait, lint in trait definition instead @@ -4113,8 +4113,8 @@ impl SelfKind { } else if ty.is_box() { ty.boxed_ty() == parent_ty } else if is_type_diagnostic_item(cx, ty, sym::Rc) || is_type_diagnostic_item(cx, ty, sym::Arc) { - if let ty::Adt(_, substs) = ty.kind() { - substs.types().next().map_or(false, |t| t == parent_ty) + if let ty::Adt(_, args) = ty.kind() { + args.types().next().map_or(false, |t| t == parent_ty) } else { false } diff --git a/src/tools/clippy/clippy_lints/src/methods/mut_mutex_lock.rs b/src/tools/clippy/clippy_lints/src/methods/mut_mutex_lock.rs index d0aa39d0627..fe024ee8dff 100644 --- a/src/tools/clippy/clippy_lints/src/methods/mut_mutex_lock.rs +++ b/src/tools/clippy/clippy_lints/src/methods/mut_mutex_lock.rs @@ -15,7 +15,7 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, ex: &'tcx Expr<'tcx>, recv: &' if let ty::Ref(_, _, Mutability::Mut) = cx.typeck_results().expr_ty(recv).kind(); if let Some(method_id) = cx.typeck_results().type_dependent_def_id(ex.hir_id); if let Some(impl_id) = cx.tcx.impl_of_method(method_id); - if is_type_diagnostic_item(cx, cx.tcx.type_of(impl_id).subst_identity(), sym::Mutex); + if is_type_diagnostic_item(cx, cx.tcx.type_of(impl_id).instantiate_identity(), sym::Mutex); then { span_lint_and_sugg( cx, diff --git a/src/tools/clippy/clippy_lints/src/methods/needless_collect.rs b/src/tools/clippy/clippy_lints/src/methods/needless_collect.rs index 8ca7af8107f..f34f1cf2704 100644 --- a/src/tools/clippy/clippy_lints/src/methods/needless_collect.rs +++ b/src/tools/clippy/clippy_lints/src/methods/needless_collect.rs @@ -163,7 +163,7 @@ fn check_collect_into_intoiterator<'tcx>( // that contains `collect_expr` let inputs = cx .tcx - .liberate_late_bound_regions(id, cx.tcx.fn_sig(id).subst_identity()) + .liberate_late_bound_regions(id, cx.tcx.fn_sig(id).instantiate_identity()) .inputs(); // map IntoIterator generic bounds to their signature @@ -201,7 +201,7 @@ fn check_collect_into_intoiterator<'tcx>( /// Checks if the given method call matches the expected signature of `([&[mut]] self) -> bool` fn is_is_empty_sig(cx: &LateContext<'_>, call_id: HirId) -> bool { cx.typeck_results().type_dependent_def_id(call_id).map_or(false, |id| { - let sig = cx.tcx.fn_sig(id).subst_identity().skip_binder(); + let sig = cx.tcx.fn_sig(id).instantiate_identity().skip_binder(); sig.inputs().len() == 1 && sig.output().is_bool() }) } @@ -215,7 +215,7 @@ fn iterates_same_ty<'tcx>(cx: &LateContext<'tcx>, iter_ty: Ty<'tcx>, collect_ty: && let Some(into_iter_item_proj) = make_projection(cx.tcx, into_iter_trait, item, [collect_ty]) && let Ok(into_iter_item_ty) = cx.tcx.try_normalize_erasing_regions( cx.param_env, - Ty::new_projection(cx.tcx,into_iter_item_proj.def_id, into_iter_item_proj.substs) + Ty::new_projection(cx.tcx,into_iter_item_proj.def_id, into_iter_item_proj.args) ) { iter_item_ty == into_iter_item_ty @@ -229,7 +229,7 @@ fn iterates_same_ty<'tcx>(cx: &LateContext<'tcx>, iter_ty: Ty<'tcx>, collect_ty: fn is_contains_sig(cx: &LateContext<'_>, call_id: HirId, iter_expr: &Expr<'_>) -> bool { let typeck = cx.typeck_results(); if let Some(id) = typeck.type_dependent_def_id(call_id) - && let sig = cx.tcx.fn_sig(id).subst_identity() + && let sig = cx.tcx.fn_sig(id).instantiate_identity() && sig.skip_binder().output().is_bool() && let [_, search_ty] = *sig.skip_binder().inputs() && let ty::Ref(_, search_ty, Mutability::Not) = *cx.tcx.erase_late_bound_regions(sig.rebind(search_ty)).kind() @@ -237,11 +237,11 @@ fn is_contains_sig(cx: &LateContext<'_>, call_id: HirId, iter_expr: &Expr<'_>) - && let Some(iter_item) = cx.tcx .associated_items(iter_trait) .find_by_name_and_kind(cx.tcx, Ident::with_dummy_span(Symbol::intern("Item")), AssocKind::Type, iter_trait) - && let substs = cx.tcx.mk_substs(&[GenericArg::from(typeck.expr_ty_adjusted(iter_expr))]) - && let proj_ty = Ty::new_projection(cx.tcx,iter_item.def_id, substs) + && let args = cx.tcx.mk_args(&[GenericArg::from(typeck.expr_ty_adjusted(iter_expr))]) + && let proj_ty = Ty::new_projection(cx.tcx,iter_item.def_id, args) && let Ok(item_ty) = cx.tcx.try_normalize_erasing_regions(cx.param_env, proj_ty) { - item_ty == EarlyBinder::bind(search_ty).subst(cx.tcx, cx.typeck_results().node_substs(call_id)) + item_ty == EarlyBinder::bind(search_ty).instantiate(cx.tcx, cx.typeck_results().node_args(call_id)) } else { false } diff --git a/src/tools/clippy/clippy_lints/src/methods/ok_expect.rs b/src/tools/clippy/clippy_lints/src/methods/ok_expect.rs index 646fc4a7bcf..f2ef42933df 100644 --- a/src/tools/clippy/clippy_lints/src/methods/ok_expect.rs +++ b/src/tools/clippy/clippy_lints/src/methods/ok_expect.rs @@ -33,7 +33,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, recv: &hir::Expr /// Given a `Result<T, E>` type, return its error type (`E`). fn get_error_type<'a>(cx: &LateContext<'_>, ty: Ty<'a>) -> Option<Ty<'a>> { match ty.kind() { - ty::Adt(_, substs) if is_type_diagnostic_item(cx, ty, sym::Result) => substs.types().nth(1), + ty::Adt(_, args) if is_type_diagnostic_item(cx, ty, sym::Result) => args.types().nth(1), _ => None, } } diff --git a/src/tools/clippy/clippy_lints/src/methods/open_options.rs b/src/tools/clippy/clippy_lints/src/methods/open_options.rs index bd625a6914c..1c664e76d74 100644 --- a/src/tools/clippy/clippy_lints/src/methods/open_options.rs +++ b/src/tools/clippy/clippy_lints/src/methods/open_options.rs @@ -11,7 +11,7 @@ use super::NONSENSICAL_OPEN_OPTIONS; pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>, recv: &'tcx Expr<'_>) { if let Some(method_id) = cx.typeck_results().type_dependent_def_id(e.hir_id) && let Some(impl_id) = cx.tcx.impl_of_method(method_id) - && match_type(cx, cx.tcx.type_of(impl_id).subst_identity(), &paths::OPEN_OPTIONS) + && match_type(cx, cx.tcx.type_of(impl_id).instantiate_identity(), &paths::OPEN_OPTIONS) { let mut options = Vec::new(); get_open_options(cx, recv, &mut options); diff --git a/src/tools/clippy/clippy_lints/src/methods/path_buf_push_overwrite.rs b/src/tools/clippy/clippy_lints/src/methods/path_buf_push_overwrite.rs index 0284d9dea30..1c07d2a3a59 100644 --- a/src/tools/clippy/clippy_lints/src/methods/path_buf_push_overwrite.rs +++ b/src/tools/clippy/clippy_lints/src/methods/path_buf_push_overwrite.rs @@ -14,7 +14,7 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, arg: &'t if_chain! { if let Some(method_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id); if let Some(impl_id) = cx.tcx.impl_of_method(method_id); - if is_type_diagnostic_item(cx, cx.tcx.type_of(impl_id).subst_identity(), sym::PathBuf); + if is_type_diagnostic_item(cx, cx.tcx.type_of(impl_id).instantiate_identity(), sym::PathBuf); if let ExprKind::Lit(lit) = arg.kind; if let LitKind::Str(ref path_lit, _) = lit.node; if let pushed_path = Path::new(path_lit.as_str()); diff --git a/src/tools/clippy/clippy_lints/src/methods/stable_sort_primitive.rs b/src/tools/clippy/clippy_lints/src/methods/stable_sort_primitive.rs index b5fd0ad8ce5..0f4c97022db 100644 --- a/src/tools/clippy/clippy_lints/src/methods/stable_sort_primitive.rs +++ b/src/tools/clippy/clippy_lints/src/methods/stable_sort_primitive.rs @@ -10,7 +10,7 @@ use super::STABLE_SORT_PRIMITIVE; pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>, recv: &'tcx Expr<'_>) { if let Some(method_id) = cx.typeck_results().type_dependent_def_id(e.hir_id) && let Some(impl_id) = cx.tcx.impl_of_method(method_id) - && cx.tcx.type_of(impl_id).subst_identity().is_slice() + && cx.tcx.type_of(impl_id).instantiate_identity().is_slice() && let Some(slice_type) = is_slice_of_primitives(cx, recv) { span_lint_and_then( diff --git a/src/tools/clippy/clippy_lints/src/methods/suspicious_splitn.rs b/src/tools/clippy/clippy_lints/src/methods/suspicious_splitn.rs index 90ca66bd70c..3cb2719e4a0 100644 --- a/src/tools/clippy/clippy_lints/src/methods/suspicious_splitn.rs +++ b/src/tools/clippy/clippy_lints/src/methods/suspicious_splitn.rs @@ -13,7 +13,7 @@ pub(super) fn check(cx: &LateContext<'_>, method_name: &str, expr: &Expr<'_>, se if let Some(call_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id); if let Some(impl_id) = cx.tcx.impl_of_method(call_id); if cx.tcx.impl_trait_ref(impl_id).is_none(); - let self_ty = cx.tcx.type_of(impl_id).subst_identity(); + let self_ty = cx.tcx.type_of(impl_id).instantiate_identity(); if self_ty.is_slice() || self_ty.is_str(); then { // Ignore empty slice and string literals when used with a literal count. diff --git a/src/tools/clippy/clippy_lints/src/methods/unnecessary_sort_by.rs b/src/tools/clippy/clippy_lints/src/methods/unnecessary_sort_by.rs index 67618f7038a..e62a65a2712 100644 --- a/src/tools/clippy/clippy_lints/src/methods/unnecessary_sort_by.rs +++ b/src/tools/clippy/clippy_lints/src/methods/unnecessary_sort_by.rs @@ -6,7 +6,7 @@ use if_chain::if_chain; use rustc_errors::Applicability; use rustc_hir::{Closure, Expr, ExprKind, Mutability, Param, Pat, PatKind, Path, PathSegment, QPath}; use rustc_lint::LateContext; -use rustc_middle::ty::{self, subst::GenericArgKind}; +use rustc_middle::ty::{self, GenericArgKind}; use rustc_span::sym; use rustc_span::symbol::Ident; use std::iter; @@ -118,7 +118,7 @@ fn detect_lint(cx: &LateContext<'_>, expr: &Expr<'_>, recv: &Expr<'_>, arg: &Exp if_chain! { if let Some(method_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id); if let Some(impl_id) = cx.tcx.impl_of_method(method_id); - if cx.tcx.type_of(impl_id).subst_identity().is_slice(); + if cx.tcx.type_of(impl_id).instantiate_identity().is_slice(); if let ExprKind::Closure(&Closure { body, .. }) = arg.kind; if let closure_body = cx.tcx.hir().body(body); if let &[ diff --git a/src/tools/clippy/clippy_lints/src/methods/unnecessary_to_owned.rs b/src/tools/clippy/clippy_lints/src/methods/unnecessary_to_owned.rs index 6bd5e9e88c8..21e2638e5b9 100644 --- a/src/tools/clippy/clippy_lints/src/methods/unnecessary_to_owned.rs +++ b/src/tools/clippy/clippy_lints/src/methods/unnecessary_to_owned.rs @@ -13,7 +13,7 @@ use rustc_infer::infer::TyCtxtInferExt; use rustc_lint::LateContext; use rustc_middle::mir::Mutability; use rustc_middle::ty::adjustment::{Adjust, Adjustment, OverloadedDeref}; -use rustc_middle::ty::subst::{GenericArg, GenericArgKind, SubstsRef}; +use rustc_middle::ty::{GenericArg, GenericArgKind, GenericArgsRef}; use rustc_middle::ty::{self, ClauseKind, EarlyBinder, ParamTy, ProjectionPredicate, TraitPredicate, Ty}; use rustc_span::{sym, Symbol}; use rustc_trait_selection::traits::{query::evaluate_obligation::InferCtxtExt as _, Obligation, ObligationCause}; @@ -250,8 +250,8 @@ fn check_other_call_arg<'tcx>( ) -> bool { if_chain! { if let Some((maybe_call, maybe_arg)) = skip_addr_of_ancestors(cx, expr); - if let Some((callee_def_id, _, recv, call_args)) = get_callee_substs_and_args(cx, maybe_call); - let fn_sig = cx.tcx.fn_sig(callee_def_id).subst_identity().skip_binder(); + if let Some((callee_def_id, _, recv, call_args)) = get_callee_generic_args_and_args(cx, maybe_call); + let fn_sig = cx.tcx.fn_sig(callee_def_id).instantiate_identity().skip_binder(); if let Some(i) = recv.into_iter().chain(call_args).position(|arg| arg.hir_id == maybe_arg.hir_id); if let Some(input) = fn_sig.inputs().get(i); let (input, n_refs) = peel_mid_ty_refs(*input); @@ -315,26 +315,26 @@ fn skip_addr_of_ancestors<'tcx>( } /// Checks whether an expression is a function or method call and, if so, returns its `DefId`, -/// `Substs`, and arguments. -fn get_callee_substs_and_args<'tcx>( +/// `GenericArgs`, and arguments. +fn get_callee_generic_args_and_args<'tcx>( cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>, -) -> Option<(DefId, SubstsRef<'tcx>, Option<&'tcx Expr<'tcx>>, &'tcx [Expr<'tcx>])> { +) -> Option<(DefId, GenericArgsRef<'tcx>, Option<&'tcx Expr<'tcx>>, &'tcx [Expr<'tcx>])> { if_chain! { if let ExprKind::Call(callee, args) = expr.kind; let callee_ty = cx.typeck_results().expr_ty(callee); if let ty::FnDef(callee_def_id, _) = callee_ty.kind(); then { - let substs = cx.typeck_results().node_substs(callee.hir_id); - return Some((*callee_def_id, substs, None, args)); + let generic_args = cx.typeck_results().node_args(callee.hir_id); + return Some((*callee_def_id, generic_args, None, args)); } } if_chain! { if let ExprKind::MethodCall(_, recv, args, _) = expr.kind; if let Some(method_def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id); then { - let substs = cx.typeck_results().node_substs(expr.hir_id); - return Some((method_def_id, substs, Some(recv), args)); + let generic_args = cx.typeck_results().node_args(expr.hir_id); + return Some((method_def_id, generic_args, Some(recv), args)); } } None @@ -388,17 +388,17 @@ fn can_change_type<'a>(cx: &LateContext<'a>, mut expr: &'a Expr<'a>, mut ty: Ty< } } Node::Expr(parent_expr) => { - if let Some((callee_def_id, call_substs, recv, call_args)) = get_callee_substs_and_args(cx, parent_expr) + if let Some((callee_def_id, call_generic_args, recv, call_args)) = get_callee_generic_args_and_args(cx, parent_expr) { - // FIXME: the `subst_identity()` below seems incorrect, since we eventually + // FIXME: the `instantiate_identity()` below seems incorrect, since we eventually // call `tcx.try_subst_and_normalize_erasing_regions` further down // (i.e., we are explicitly not in the identity context). - let fn_sig = cx.tcx.fn_sig(callee_def_id).subst_identity().skip_binder(); + let fn_sig = cx.tcx.fn_sig(callee_def_id).instantiate_identity().skip_binder(); if let Some(arg_index) = recv.into_iter().chain(call_args).position(|arg| arg.hir_id == expr.hir_id) && let Some(param_ty) = fn_sig.inputs().get(arg_index) && let ty::Param(ParamTy { index: param_index , ..}) = param_ty.kind() // https://github.com/rust-lang/rust-clippy/issues/9504 and https://github.com/rust-lang/rust-clippy/issues/10021 - && (*param_index as usize) < call_substs.len() + && (*param_index as usize) < call_generic_args.len() { if fn_sig .inputs() @@ -422,8 +422,8 @@ fn can_change_type<'a>(cx: &LateContext<'a>, mut expr: &'a Expr<'a>, mut ty: Ty< } }); - let new_subst = cx.tcx.mk_substs_from_iter( - call_substs.iter() + let new_subst = cx.tcx.mk_args_from_iter( + call_generic_args.iter() .enumerate() .map(|(i, t)| if i == (*param_index as usize) { @@ -433,7 +433,7 @@ fn can_change_type<'a>(cx: &LateContext<'a>, mut expr: &'a Expr<'a>, mut ty: Ty< })); if trait_predicates.any(|predicate| { - let predicate = EarlyBinder::bind(predicate).subst(cx.tcx, new_subst); + let predicate = EarlyBinder::bind(predicate).instantiate(cx.tcx, new_subst); let obligation = Obligation::new(cx.tcx, ObligationCause::dummy(), cx.param_env, predicate); !cx.tcx.infer_ctxt().build().predicate_must_hold_modulo_regions(&obligation) }) { @@ -500,8 +500,8 @@ fn is_to_string_on_string_like<'a>( return false; } - if let Some(substs) = cx.typeck_results().node_substs_opt(call_expr.hir_id) - && let [generic_arg] = substs.as_slice() + if let Some(args) = cx.typeck_results().node_args_opt(call_expr.hir_id) + && let [generic_arg] = args.as_slice() && let GenericArgKind::Type(ty) = generic_arg.unpack() && let Some(deref_trait_id) = cx.tcx.get_diagnostic_item(sym::Deref) && let Some(as_ref_trait_id) = cx.tcx.get_diagnostic_item(sym::AsRef) diff --git a/src/tools/clippy/clippy_lints/src/methods/utils.rs b/src/tools/clippy/clippy_lints/src/methods/utils.rs index c96d6922697..9f1f73e6021 100644 --- a/src/tools/clippy/clippy_lints/src/methods/utils.rs +++ b/src/tools/clippy/clippy_lints/src/methods/utils.rs @@ -143,7 +143,7 @@ impl<'cx, 'tcx> Visitor<'tcx> for CloneOrCopyVisitor<'cx, 'tcx> { if_chain! { if args.iter().all(|arg| !self.is_binding(arg)); if let Some(method_def_id) = self.cx.typeck_results().type_dependent_def_id(parent.hir_id); - let method_ty = self.cx.tcx.type_of(method_def_id).subst_identity(); + let method_ty = self.cx.tcx.type_of(method_def_id).instantiate_identity(); let self_ty = method_ty.fn_sig(self.cx.tcx).input(0).skip_binder(); if matches!(self_ty.kind(), ty::Ref(_, _, Mutability::Not)); then { diff --git a/src/tools/clippy/clippy_lints/src/methods/vec_resize_to_zero.rs b/src/tools/clippy/clippy_lints/src/methods/vec_resize_to_zero.rs index b0cfc163fd0..73072718678 100644 --- a/src/tools/clippy/clippy_lints/src/methods/vec_resize_to_zero.rs +++ b/src/tools/clippy/clippy_lints/src/methods/vec_resize_to_zero.rs @@ -20,7 +20,7 @@ pub(super) fn check<'tcx>( if_chain! { if let Some(method_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id); if let Some(impl_id) = cx.tcx.impl_of_method(method_id); - if is_type_diagnostic_item(cx, cx.tcx.type_of(impl_id).subst_identity(), sym::Vec); + if is_type_diagnostic_item(cx, cx.tcx.type_of(impl_id).instantiate_identity(), sym::Vec); if let ExprKind::Lit(Spanned { node: LitKind::Int(0, _), .. }) = count_arg.kind; if let ExprKind::Lit(Spanned { node: LitKind::Int(..), .. }) = default_arg.kind; then { diff --git a/src/tools/clippy/clippy_lints/src/mut_key.rs b/src/tools/clippy/clippy_lints/src/mut_key.rs index 309f67521a3..5878f899541 100644 --- a/src/tools/clippy/clippy_lints/src/mut_key.rs +++ b/src/tools/clippy/clippy_lints/src/mut_key.rs @@ -139,7 +139,7 @@ impl MutableKeyType { } fn check_sig(&self, cx: &LateContext<'_>, fn_def_id: LocalDefId, decl: &hir::FnDecl<'_>) { - let fn_sig = cx.tcx.fn_sig(fn_def_id).subst_identity(); + let fn_sig = cx.tcx.fn_sig(fn_def_id).instantiate_identity(); for (hir_ty, ty) in iter::zip(decl.inputs, fn_sig.inputs().skip_binder()) { self.check_ty_(cx, hir_ty.span, *ty); } @@ -150,7 +150,7 @@ impl MutableKeyType { // generics (because the compiler cannot ensure immutability for unknown types). fn check_ty_<'tcx>(&self, cx: &LateContext<'tcx>, span: Span, ty: Ty<'tcx>) { let ty = ty.peel_refs(); - if let Adt(def, substs) = ty.kind() { + if let Adt(def, args) = ty.kind() { let is_keyed_type = [sym::HashMap, sym::BTreeMap, sym::HashSet, sym::BTreeSet] .iter() .any(|diag_item| cx.tcx.is_diagnostic_item(*diag_item, def.did())); @@ -158,7 +158,7 @@ impl MutableKeyType { return; } - let subst_ty = substs.type_at(0); + let subst_ty = args.type_at(0); // Determines if a type contains interior mutability which would affect its implementation of // [`Hash`] or [`Ord`]. if is_interior_mut_ty(cx, subst_ty) diff --git a/src/tools/clippy/clippy_lints/src/mut_reference.rs b/src/tools/clippy/clippy_lints/src/mut_reference.rs index e91aac41bc4..4b20aecad4a 100644 --- a/src/tools/clippy/clippy_lints/src/mut_reference.rs +++ b/src/tools/clippy/clippy_lints/src/mut_reference.rs @@ -51,8 +51,8 @@ impl<'tcx> LateLintPass<'tcx> for UnnecessaryMutPassed { }, ExprKind::MethodCall(path, receiver, arguments, _) => { let def_id = cx.typeck_results().type_dependent_def_id(e.hir_id).unwrap(); - let substs = cx.typeck_results().node_substs(e.hir_id); - let method_type = cx.tcx.type_of(def_id).subst(cx.tcx, substs); + let args = cx.typeck_results().node_args(e.hir_id); + let method_type = cx.tcx.type_of(def_id).instantiate(cx.tcx, args); check_arguments( cx, std::iter::once(receiver).chain(arguments.iter()).collect(), diff --git a/src/tools/clippy/clippy_lints/src/needless_pass_by_value.rs b/src/tools/clippy/clippy_lints/src/needless_pass_by_value.rs index f11d5773d04..55b6e1606ee 100644 --- a/src/tools/clippy/clippy_lints/src/needless_pass_by_value.rs +++ b/src/tools/clippy/clippy_lints/src/needless_pass_by_value.rs @@ -140,7 +140,7 @@ impl<'tcx> LateLintPass<'tcx> for NeedlessPassByValue { ctx }; - let fn_sig = cx.tcx.fn_sig(fn_def_id).subst_identity(); + let fn_sig = cx.tcx.fn_sig(fn_def_id).instantiate_identity(); let fn_sig = cx.tcx.liberate_late_bound_regions(fn_def_id.to_def_id(), fn_sig); for (idx, ((input, &ty), arg)) in decl.inputs.iter().zip(fn_sig.inputs()).zip(body.params).enumerate() { @@ -170,7 +170,7 @@ impl<'tcx> LateLintPass<'tcx> for NeedlessPassByValue { !preds.is_empty() && { let ty_empty_region = Ty::new_imm_ref(cx.tcx,cx.tcx.lifetimes.re_erased, ty); preds.iter().all(|t| { - let ty_params = t.trait_ref.substs.iter().skip(1).collect::<Vec<_>>(); + let ty_params = t.trait_ref.args.iter().skip(1).collect::<Vec<_>>(); implements_trait(cx, ty_empty_region, t.def_id(), &ty_params) }) }, diff --git a/src/tools/clippy/clippy_lints/src/new_without_default.rs b/src/tools/clippy/clippy_lints/src/new_without_default.rs index 653b1a8a05f..cf7cd671dca 100644 --- a/src/tools/clippy/clippy_lints/src/new_without_default.rs +++ b/src/tools/clippy/clippy_lints/src/new_without_default.rs @@ -98,14 +98,14 @@ impl<'tcx> LateLintPass<'tcx> for NewWithoutDefault { if name == sym::new; if cx.effective_visibilities.is_reachable(impl_item.owner_id.def_id); let self_def_id = cx.tcx.hir().get_parent_item(id.into()); - let self_ty = cx.tcx.type_of(self_def_id).subst_identity(); + let self_ty = cx.tcx.type_of(self_def_id).instantiate_identity(); if self_ty == return_ty(cx, id); if let Some(default_trait_id) = cx.tcx.get_diagnostic_item(sym::Default); then { if self.impling_types.is_none() { let mut impls = HirIdSet::default(); cx.tcx.for_each_impl(default_trait_id, |d| { - let ty = cx.tcx.type_of(d).subst_identity(); + let ty = cx.tcx.type_of(d).instantiate_identity(); if let Some(ty_def) = ty.ty_adt_def() { if let Some(local_def_id) = ty_def.did().as_local() { impls.insert(cx.tcx.hir().local_def_id_to_hir_id(local_def_id)); @@ -119,7 +119,7 @@ impl<'tcx> LateLintPass<'tcx> for NewWithoutDefault { // generics if_chain! { if let Some(ref impling_types) = self.impling_types; - let self_def = cx.tcx.type_of(self_def_id).subst_identity(); + let self_def = cx.tcx.type_of(self_def_id).instantiate_identity(); if let Some(self_def) = self_def.ty_adt_def(); if let Some(self_local_did) = self_def.did().as_local(); let self_id = cx.tcx.hir().local_def_id_to_hir_id(self_local_did); diff --git a/src/tools/clippy/clippy_lints/src/non_copy_const.rs b/src/tools/clippy/clippy_lints/src/non_copy_const.rs index 75f1e95276a..12d4f33d428 100644 --- a/src/tools/clippy/clippy_lints/src/non_copy_const.rs +++ b/src/tools/clippy/clippy_lints/src/non_copy_const.rs @@ -158,7 +158,7 @@ fn is_value_unfrozen_raw<'tcx>( val.unwrap_branch().iter().any(|field| inner(cx, *field, ty)) }, ty::Adt(def, _) if def.is_union() => false, - ty::Adt(def, substs) if def.is_enum() => { + ty::Adt(def, args) if def.is_enum() => { let (&variant_index, fields) = val.unwrap_branch().split_first().unwrap(); let variant_index = VariantIdx::from_u32(variant_index.unwrap_leaf().try_to_u32().ok().unwrap()); @@ -166,10 +166,10 @@ fn is_value_unfrozen_raw<'tcx>( def.variants()[variant_index] .fields .iter() - .map(|field| field.ty(cx.tcx, substs))).any(|(field, ty)| inner(cx, field, ty)) + .map(|field| field.ty(cx.tcx, args))).any(|(field, ty)| inner(cx, field, ty)) } - ty::Adt(def, substs) => { - val.unwrap_branch().iter().zip(def.non_enum_variant().fields.iter().map(|field| field.ty(cx.tcx, substs))).any(|(field, ty)| inner(cx, *field, ty)) + ty::Adt(def, args) => { + val.unwrap_branch().iter().zip(def.non_enum_variant().fields.iter().map(|field| field.ty(cx.tcx, args))).any(|(field, ty)| inner(cx, *field, ty)) } ty::Tuple(tys) => val.unwrap_branch().iter().zip(tys).any(|(field, ty)| inner(cx, *field, ty)), _ => false, @@ -206,8 +206,8 @@ fn is_value_unfrozen_raw<'tcx>( fn is_value_unfrozen_poly<'tcx>(cx: &LateContext<'tcx>, body_id: BodyId, ty: Ty<'tcx>) -> bool { let def_id = body_id.hir_id.owner.to_def_id(); - let substs = ty::InternalSubsts::identity_for_item(cx.tcx, def_id); - let instance = ty::Instance::new(def_id, substs); + let args = ty::GenericArgs::identity_for_item(cx.tcx, def_id); + let instance = ty::Instance::new(def_id, args); let cid = rustc_middle::mir::interpret::GlobalId { instance, promoted: None }; let param_env = cx.tcx.param_env(def_id).with_reveal_all_normalized(cx.tcx); let result = cx.tcx.const_eval_global_id_for_typeck(param_env, cid, None); @@ -215,9 +215,9 @@ fn is_value_unfrozen_poly<'tcx>(cx: &LateContext<'tcx>, body_id: BodyId, ty: Ty< } fn is_value_unfrozen_expr<'tcx>(cx: &LateContext<'tcx>, hir_id: HirId, def_id: DefId, ty: Ty<'tcx>) -> bool { - let substs = cx.typeck_results().node_substs(hir_id); + let args = cx.typeck_results().node_args(hir_id); - let result = const_eval_resolve(cx.tcx, cx.param_env, ty::UnevaluatedConst::new(def_id, substs), None); + let result = const_eval_resolve(cx.tcx, cx.param_env, ty::UnevaluatedConst::new(def_id, args), None); is_value_unfrozen_raw(cx, result, ty) } @@ -228,7 +228,7 @@ pub fn const_eval_resolve<'tcx>( ct: ty::UnevaluatedConst<'tcx>, span: Option<Span>, ) -> EvalToValTreeResult<'tcx> { - match ty::Instance::resolve(tcx, param_env, ct.def, ct.substs) { + match ty::Instance::resolve(tcx, param_env, ct.def, ct.args) { Ok(Some(instance)) => { let cid = GlobalId { instance, promoted: None }; tcx.const_eval_global_id_for_typeck(param_env, cid, span) @@ -347,7 +347,7 @@ impl<'tcx> LateLintPass<'tcx> for NonCopyConst { // and, in that case, the definition is *not* generic. cx.tcx.normalize_erasing_regions( cx.tcx.param_env(of_trait_def_id), - cx.tcx.type_of(of_assoc_item).subst_identity(), + cx.tcx.type_of(of_assoc_item).instantiate_identity(), ), )) .is_err(); diff --git a/src/tools/clippy/clippy_lints/src/non_send_fields_in_send_ty.rs b/src/tools/clippy/clippy_lints/src/non_send_fields_in_send_ty.rs index 7eaa7db78a4..c5e777c2070 100644 --- a/src/tools/clippy/clippy_lints/src/non_send_fields_in_send_ty.rs +++ b/src/tools/clippy/clippy_lints/src/non_send_fields_in_send_ty.rs @@ -7,7 +7,7 @@ use rustc_hir::def_id::DefId; use rustc_hir::{FieldDef, Item, ItemKind, Node}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::lint::in_external_macro; -use rustc_middle::ty::{self, subst::GenericArgKind, Ty}; +use rustc_middle::ty::{self, GenericArgKind, Ty}; use rustc_session::{declare_tool_lint, impl_lint_pass}; use rustc_span::sym; @@ -90,8 +90,8 @@ impl<'tcx> LateLintPass<'tcx> for NonSendFieldInSendTy { if send_trait == trait_id; if hir_impl.polarity == ImplPolarity::Positive; if let Some(ty_trait_ref) = cx.tcx.impl_trait_ref(item.owner_id); - if let self_ty = ty_trait_ref.subst_identity().self_ty(); - if let ty::Adt(adt_def, impl_trait_substs) = self_ty.kind(); + if let self_ty = ty_trait_ref.instantiate_identity().self_ty(); + if let ty::Adt(adt_def, impl_trait_args) = self_ty.kind(); then { let mut non_send_fields = Vec::new(); @@ -104,7 +104,7 @@ impl<'tcx> LateLintPass<'tcx> for NonSendFieldInSendTy { .as_local() .map(|local_def_id| hir_map.local_def_id_to_hir_id(local_def_id)); if !is_lint_allowed(cx, NON_SEND_FIELDS_IN_SEND_TY, field_hir_id); - if let field_ty = field.ty(cx.tcx, impl_trait_substs); + if let field_ty = field.ty(cx.tcx, impl_trait_args); if !ty_allowed_in_send(cx, field_ty, send_trait); if let Node::Field(field_def) = hir_map.get(field_hir_id); then { @@ -206,10 +206,10 @@ fn ty_allowed_with_raw_pointer_heuristic<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'t .iter() .all(|ty| ty_allowed_with_raw_pointer_heuristic(cx, ty, send_trait)), ty::Array(ty, _) | ty::Slice(ty) => ty_allowed_with_raw_pointer_heuristic(cx, *ty, send_trait), - ty::Adt(_, substs) => { + ty::Adt(_, args) => { if contains_pointer_like(cx, ty) { // descends only if ADT contains any raw pointers - substs.iter().all(|generic_arg| match generic_arg.unpack() { + args.iter().all(|generic_arg| match generic_arg.unpack() { GenericArgKind::Type(ty) => ty_allowed_with_raw_pointer_heuristic(cx, ty, send_trait), // Lifetimes and const generics are not solid part of ADT and ignored GenericArgKind::Lifetime(_) | GenericArgKind::Const(_) => true, @@ -224,7 +224,7 @@ fn ty_allowed_with_raw_pointer_heuristic<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'t } } -/// Checks if the type contains any pointer-like types in substs (including nested ones) +/// Checks if the type contains any pointer-like types in args (including nested ones) fn contains_pointer_like<'tcx>(cx: &LateContext<'tcx>, target_ty: Ty<'tcx>) -> bool { for ty_node in target_ty.walk() { if let GenericArgKind::Type(inner_ty) = ty_node.unpack() { diff --git a/src/tools/clippy/clippy_lints/src/only_used_in_recursion.rs b/src/tools/clippy/clippy_lints/src/only_used_in_recursion.rs index 8b77a5c99f7..3615c7ec9bf 100644 --- a/src/tools/clippy/clippy_lints/src/only_used_in_recursion.rs +++ b/src/tools/clippy/clippy_lints/src/only_used_in_recursion.rs @@ -7,7 +7,7 @@ use rustc_hir::def_id::DefId; use rustc_hir::hir_id::HirIdMap; use rustc_hir::{Body, Expr, ExprKind, HirId, ImplItem, ImplItemKind, Node, PatKind, TraitItem, TraitItemKind}; use rustc_lint::{LateContext, LateLintPass}; -use rustc_middle::ty::subst::{EarlyBinder, GenericArgKind, SubstsRef}; +use rustc_middle::ty::{EarlyBinder, GenericArgKind, GenericArgsRef}; use rustc_middle::ty::{self, ConstKind}; use rustc_session::{declare_tool_lint, impl_lint_pass}; use rustc_span::symbol::{kw, Ident}; @@ -90,7 +90,7 @@ impl_lint_pass!(OnlyUsedInRecursion => [ONLY_USED_IN_RECURSION]); enum FnKind { Fn, TraitFn, - // This is a hack. Ideally we would store a `SubstsRef<'tcx>` type here, but a lint pass must be `'static`. + // This is a hack. Ideally we would store a `GenericArgsRef<'tcx>` type here, but a lint pass must be `'static`. // Substitutions are, however, interned. This allows us to store the pointer as a `usize` when comparing for // equality. ImplTraitFn(usize), @@ -244,12 +244,12 @@ impl<'tcx> LateLintPass<'tcx> for OnlyUsedInRecursion { })) => { #[allow(trivial_casts)] if let Some(Node::Item(item)) = get_parent_node(cx.tcx, owner_id.into()) - && let Some(trait_ref) = cx.tcx.impl_trait_ref(item.owner_id).map(EarlyBinder::subst_identity) + && let Some(trait_ref) = cx.tcx.impl_trait_ref(item.owner_id).map(EarlyBinder::instantiate_identity) && let Some(trait_item_id) = cx.tcx.associated_item(owner_id).trait_item_def_id { ( trait_item_id, - FnKind::ImplTraitFn(cx.tcx.erase_regions(trait_ref.substs) as *const _ as usize), + FnKind::ImplTraitFn(cx.tcx.erase_regions(trait_ref.args) as *const _ as usize), usize::from(sig.decl.implicit_self.has_implicit_self()), ) } else { @@ -289,7 +289,7 @@ impl<'tcx> LateLintPass<'tcx> for OnlyUsedInRecursion { ExprKind::Call(callee, args) if path_def_id(cx, callee).map_or(false, |id| { id == param.fn_id - && has_matching_substs(param.fn_kind, typeck.node_substs(callee.hir_id)) + && has_matching_args(param.fn_kind, typeck.node_args(callee.hir_id)) }) => { if let Some(idx) = args.iter().position(|arg| arg.hir_id == child_id) { @@ -300,7 +300,7 @@ impl<'tcx> LateLintPass<'tcx> for OnlyUsedInRecursion { ExprKind::MethodCall(_, receiver, args, _) if typeck.type_dependent_def_id(parent.hir_id).map_or(false, |id| { id == param.fn_id - && has_matching_substs(param.fn_kind, typeck.node_substs(parent.hir_id)) + && has_matching_args(param.fn_kind, typeck.node_args(parent.hir_id)) }) => { if let Some(idx) = iter::once(receiver).chain(args).position(|arg| arg.hir_id == child_id) { @@ -381,15 +381,15 @@ impl<'tcx> LateLintPass<'tcx> for OnlyUsedInRecursion { } } -fn has_matching_substs(kind: FnKind, substs: SubstsRef<'_>) -> bool { +fn has_matching_args(kind: FnKind, args: GenericArgsRef<'_>) -> bool { match kind { FnKind::Fn => true, - FnKind::TraitFn => substs.iter().enumerate().all(|(idx, subst)| match subst.unpack() { + FnKind::TraitFn => args.iter().enumerate().all(|(idx, subst)| match subst.unpack() { GenericArgKind::Lifetime(_) => true, GenericArgKind::Type(ty) => matches!(*ty.kind(), ty::Param(ty) if ty.index as usize == idx), GenericArgKind::Const(c) => matches!(c.kind(), ConstKind::Param(c) if c.index as usize == idx), }), #[allow(trivial_casts)] - FnKind::ImplTraitFn(expected_substs) => substs as *const _ as usize == expected_substs, + FnKind::ImplTraitFn(expected_args) => args as *const _ as usize == expected_args, } } diff --git a/src/tools/clippy/clippy_lints/src/pass_by_ref_or_value.rs b/src/tools/clippy/clippy_lints/src/pass_by_ref_or_value.rs index eab725de17f..7b4812e98d8 100644 --- a/src/tools/clippy/clippy_lints/src/pass_by_ref_or_value.rs +++ b/src/tools/clippy/clippy_lints/src/pass_by_ref_or_value.rs @@ -143,7 +143,7 @@ impl<'tcx> PassByRefOrValue { return; } - let fn_sig = cx.tcx.fn_sig(def_id).subst_identity(); + let fn_sig = cx.tcx.fn_sig(def_id).instantiate_identity(); let fn_body = cx.enclosing_body.map(|id| cx.tcx.hir().body(id)); // Gather all the lifetimes found in the output type which may affect whether diff --git a/src/tools/clippy/clippy_lints/src/ptr.rs b/src/tools/clippy/clippy_lints/src/ptr.rs index 32213718b27..eb7c008c7a4 100644 --- a/src/tools/clippy/clippy_lints/src/ptr.rs +++ b/src/tools/clippy/clippy_lints/src/ptr.rs @@ -166,7 +166,7 @@ impl<'tcx> LateLintPass<'tcx> for Ptr { check_mut_from_ref(cx, sig, None); for arg in check_fn_args( cx, - cx.tcx.fn_sig(item.owner_id).subst_identity().skip_binder().inputs(), + cx.tcx.fn_sig(item.owner_id).instantiate_identity().skip_binder().inputs(), sig.decl.inputs, &sig.decl.output, &[], @@ -220,7 +220,7 @@ impl<'tcx> LateLintPass<'tcx> for Ptr { check_mut_from_ref(cx, sig, Some(body)); let decl = sig.decl; - let sig = cx.tcx.fn_sig(item_id).subst_identity().skip_binder(); + let sig = cx.tcx.fn_sig(item_id).instantiate_identity().skip_binder(); let lint_args: Vec<_> = check_fn_args(cx, sig.inputs(), decl.inputs, &decl.output, body.params) .filter(|arg| !is_trait_item || arg.mutability() == Mutability::Not) .collect(); @@ -423,7 +423,7 @@ fn check_fn_args<'cx, 'tcx: 'cx>( .enumerate() .filter_map(move |(i, (ty, hir_ty))| { if let ty::Ref(_, ty, mutability) = *ty.kind() - && let ty::Adt(adt, substs) = *ty.kind() + && let ty::Adt(adt, args) = *ty.kind() && let TyKind::Ref(lt, ref ty) = hir_ty.kind && let TyKind::Path(QPath::Resolved(None, path)) = ty.ty.kind // Check that the name as typed matches the actual name of the type. @@ -443,7 +443,7 @@ fn check_fn_args<'cx, 'tcx: 'cx>( } else { None }), - substs.type_at(0), + args.type_at(0), ), ), _ if Some(adt.did()) == cx.tcx.lang_items().string() => ( @@ -496,7 +496,7 @@ fn check_fn_args<'cx, 'tcx: 'cx>( } let ty_name = - snippet_opt(cx, ty.span()).unwrap_or_else(|| substs.type_at(1).to_string()); + snippet_opt(cx, ty.span()).unwrap_or_else(|| args.type_at(1).to_string()); span_lint_hir_and_then( cx, @@ -659,7 +659,7 @@ fn check_ptr_arg_usage<'tcx>(cx: &LateContext<'tcx>, body: &'tcx Body<'_>, args: return; }; - match *self.cx.tcx.fn_sig(id).subst_identity().skip_binder().inputs()[i] + match *self.cx.tcx.fn_sig(id).instantiate_identity().skip_binder().inputs()[i] .peel_refs() .kind() { @@ -725,7 +725,7 @@ fn matches_preds<'tcx>( let infcx = cx.tcx.infer_ctxt().build(); preds.iter().all(|&p| match cx.tcx.erase_late_bound_regions(p) { ExistentialPredicate::Trait(p) => infcx - .type_implements_trait(p.def_id, [ty.into()].into_iter().chain(p.substs.iter()), cx.param_env) + .type_implements_trait(p.def_id, [ty.into()].into_iter().chain(p.args.iter()), cx.param_env) .must_apply_modulo_regions(), ExistentialPredicate::Projection(p) => infcx.predicate_must_hold_modulo_regions(&Obligation::new( cx.tcx, diff --git a/src/tools/clippy/clippy_lints/src/redundant_slicing.rs b/src/tools/clippy/clippy_lints/src/redundant_slicing.rs index c70ce83a9c4..2b65c08d25d 100644 --- a/src/tools/clippy/clippy_lints/src/redundant_slicing.rs +++ b/src/tools/clippy/clippy_lints/src/redundant_slicing.rs @@ -9,7 +9,7 @@ use rustc_hir::{BorrowKind, Expr, ExprKind, LangItem, Mutability}; use rustc_lint::{LateContext, LateLintPass, Lint}; use rustc_middle::ty::Ty; use rustc_middle::ty::adjustment::{Adjust, AutoBorrow, AutoBorrowMutability}; -use rustc_middle::ty::subst::GenericArg; +use rustc_middle::ty::GenericArg; use rustc_session::{declare_lint_pass, declare_tool_lint}; declare_clippy_lint! { @@ -135,7 +135,7 @@ impl<'tcx> LateLintPass<'tcx> for RedundantSlicing { } else if let Some(target_id) = cx.tcx.lang_items().deref_target() { if let Ok(deref_ty) = cx.tcx.try_normalize_erasing_regions( cx.param_env, - Ty::new_projection(cx.tcx,target_id, cx.tcx.mk_substs(&[GenericArg::from(indexed_ty)])), + Ty::new_projection(cx.tcx,target_id, cx.tcx.mk_args(&[GenericArg::from(indexed_ty)])), ) { if deref_ty == expr_ty { let snip = snippet_with_context(cx, indexed.span, ctxt, "..", &mut app).0; diff --git a/src/tools/clippy/clippy_lints/src/returns.rs b/src/tools/clippy/clippy_lints/src/returns.rs index 958351ad81b..4977df6c83f 100644 --- a/src/tools/clippy/clippy_lints/src/returns.rs +++ b/src/tools/clippy/clippy_lints/src/returns.rs @@ -9,7 +9,7 @@ use rustc_hir::intravisit::FnKind; use rustc_hir::{Block, Body, Expr, ExprKind, FnDecl, LangItem, MatchSource, PatKind, QPath, StmtKind}; use rustc_lint::{LateContext, LateLintPass, LintContext}; use rustc_middle::lint::in_external_macro; -use rustc_middle::ty::{self, subst::GenericArgKind, Ty}; +use rustc_middle::ty::{self, GenericArgKind, Ty}; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::def_id::LocalDefId; use rustc_span::source_map::Span; @@ -333,7 +333,7 @@ fn last_statement_borrows<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) && cx .tcx .fn_sig(def_id) - .subst_identity() + .instantiate_identity() .skip_binder() .output() .walk() diff --git a/src/tools/clippy/clippy_lints/src/self_named_constructors.rs b/src/tools/clippy/clippy_lints/src/self_named_constructors.rs index beca203c868..b92014f68b3 100644 --- a/src/tools/clippy/clippy_lints/src/self_named_constructors.rs +++ b/src/tools/clippy/clippy_lints/src/self_named_constructors.rs @@ -53,7 +53,7 @@ impl<'tcx> LateLintPass<'tcx> for SelfNamedConstructors { let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id()).def_id; let item = cx.tcx.hir().expect_item(parent); - let self_ty = cx.tcx.type_of(item.owner_id).subst_identity(); + let self_ty = cx.tcx.type_of(item.owner_id).instantiate_identity(); let ret_ty = return_ty(cx, impl_item.owner_id); // Do not check trait impls diff --git a/src/tools/clippy/clippy_lints/src/significant_drop_tightening.rs b/src/tools/clippy/clippy_lints/src/significant_drop_tightening.rs index fffa8a380c2..1493ad44ee5 100644 --- a/src/tools/clippy/clippy_lints/src/significant_drop_tightening.rs +++ b/src/tools/clippy/clippy_lints/src/significant_drop_tightening.rs @@ -10,7 +10,7 @@ use rustc_hir::{ intravisit::{walk_expr, Visitor}, }; use rustc_lint::{LateContext, LateLintPass, LintContext}; -use rustc_middle::ty::{subst::GenericArgKind, Ty, TypeAndMut}; +use rustc_middle::ty::{GenericArgKind, Ty, TypeAndMut}; use rustc_session::{declare_tool_lint, impl_lint_pass}; use rustc_span::{symbol::Ident, Span, DUMMY_SP}; use std::borrow::Cow; diff --git a/src/tools/clippy/clippy_lints/src/size_of_in_element_count.rs b/src/tools/clippy/clippy_lints/src/size_of_in_element_count.rs index ac4e29e9dfd..80c834066bb 100644 --- a/src/tools/clippy/clippy_lints/src/size_of_in_element_count.rs +++ b/src/tools/clippy/clippy_lints/src/size_of_in_element_count.rs @@ -47,7 +47,7 @@ fn get_size_of_ty<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, inverted: if let Some(def_id) = cx.qpath_res(count_func_qpath, count_func.hir_id).opt_def_id(); if matches!(cx.tcx.get_diagnostic_name(def_id), Some(sym::mem_size_of | sym::mem_size_of_val)); then { - cx.typeck_results().node_substs(count_func.hir_id).types().next() + cx.typeck_results().node_args(count_func.hir_id).types().next() } else { None } @@ -101,7 +101,7 @@ fn get_pointee_ty_and_count_expr<'tcx>( if FUNCTIONS.iter().any(|func_path| match_def_path(cx, def_id, func_path)); // Get the pointee type - if let Some(pointee_ty) = cx.typeck_results().node_substs(func.hir_id).types().next(); + if let Some(pointee_ty) = cx.typeck_results().node_args(func.hir_id).types().next(); then { return Some((pointee_ty, count)); } diff --git a/src/tools/clippy/clippy_lints/src/transmute/transmute_undefined_repr.rs b/src/tools/clippy/clippy_lints/src/transmute/transmute_undefined_repr.rs index 5e24213d07f..9e5d7662426 100644 --- a/src/tools/clippy/clippy_lints/src/transmute/transmute_undefined_repr.rs +++ b/src/tools/clippy/clippy_lints/src/transmute/transmute_undefined_repr.rs @@ -3,7 +3,7 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::ty::is_c_void; use rustc_hir::Expr; use rustc_lint::LateContext; -use rustc_middle::ty::SubstsRef; +use rustc_middle::ty::GenericArgsRef; use rustc_middle::ty::{self, IntTy, Ty, TypeAndMut, UintTy}; #[expect(clippy::too_many_lines)] @@ -268,12 +268,12 @@ fn reduce_ty<'tcx>(cx: &LateContext<'tcx>, mut ty: Ty<'tcx>) -> ReducedTy<'tcx> } ReducedTy::UnorderedFields(ty) }, - ty::Adt(def, substs) if def.is_struct() => { + ty::Adt(def, args) if def.is_struct() => { let mut iter = def .non_enum_variant() .fields .iter() - .map(|f| cx.tcx.type_of(f.did).subst(cx.tcx, substs)); + .map(|f| cx.tcx.type_of(f.did).instantiate(cx.tcx, args)); let Some(sized_ty) = iter.find(|&ty| !is_zero_sized_ty(cx, ty)) else { return ReducedTy::TypeErasure { raw_ptr_only: false }; }; @@ -322,7 +322,7 @@ fn is_size_pair(ty: Ty<'_>) -> bool { } } -fn same_except_params<'tcx>(subs1: SubstsRef<'tcx>, subs2: SubstsRef<'tcx>) -> bool { +fn same_except_params<'tcx>(subs1: GenericArgsRef<'tcx>, subs2: GenericArgsRef<'tcx>) -> bool { // TODO: check const parameters as well. Currently this will consider `Array<5>` the same as // `Array<6>` for (ty1, ty2) in subs1.types().zip(subs2.types()).filter(|(ty1, ty2)| ty1 != ty2) { diff --git a/src/tools/clippy/clippy_lints/src/transmute/unsound_collection_transmute.rs b/src/tools/clippy/clippy_lints/src/transmute/unsound_collection_transmute.rs index b1445311b71..891fefc17a6 100644 --- a/src/tools/clippy/clippy_lints/src/transmute/unsound_collection_transmute.rs +++ b/src/tools/clippy/clippy_lints/src/transmute/unsound_collection_transmute.rs @@ -10,7 +10,7 @@ use rustc_span::symbol::sym; /// Returns `true` if it's triggered, otherwise returns `false`. pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>, from_ty: Ty<'tcx>, to_ty: Ty<'tcx>) -> bool { match (&from_ty.kind(), &to_ty.kind()) { - (ty::Adt(from_adt, from_substs), ty::Adt(to_adt, to_substs)) => { + (ty::Adt(from_adt, from_args), ty::Adt(to_adt, to_args)) => { if from_adt.did() != to_adt.did() { return false; } @@ -28,9 +28,9 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>, from_ty: Ty ) { return false; } - if from_substs + if from_args .types() - .zip(to_substs.types()) + .zip(to_args.types()) .any(|(from_ty, to_ty)| is_layout_incompatible(cx, from_ty, to_ty)) { span_lint( diff --git a/src/tools/clippy/clippy_lints/src/uninit_vec.rs b/src/tools/clippy/clippy_lints/src/uninit_vec.rs index 1ab0162a881..6756df8e716 100644 --- a/src/tools/clippy/clippy_lints/src/uninit_vec.rs +++ b/src/tools/clippy/clippy_lints/src/uninit_vec.rs @@ -88,7 +88,7 @@ fn handle_uninit_vec_pair<'tcx>( if let Some((set_len_self, call_span)) = extract_set_len_self(cx, maybe_set_len); if vec.location.eq_expr(cx, set_len_self); if let ty::Ref(_, vec_ty, _) = cx.typeck_results().expr_ty_adjusted(set_len_self).kind(); - if let ty::Adt(_, substs) = vec_ty.kind(); + if let ty::Adt(_, args) = vec_ty.kind(); // `#[allow(...)]` attribute can be set on enclosing unsafe block of `set_len()` if !is_lint_allowed(cx, UNINIT_VEC, maybe_set_len.hir_id); then { @@ -96,7 +96,7 @@ fn handle_uninit_vec_pair<'tcx>( // with_capacity / reserve -> set_len // Check T of Vec<T> - if !is_uninit_value_valid_for_ty(cx, substs.type_at(0)) { + if !is_uninit_value_valid_for_ty(cx, args.type_at(0)) { // FIXME: #7698, false positive of the internal lints #[expect(clippy::collapsible_span_lint_calls)] span_lint_and_then( diff --git a/src/tools/clippy/clippy_lints/src/unit_return_expecting_ord.rs b/src/tools/clippy/clippy_lints/src/unit_return_expecting_ord.rs index 99a1d197678..dd829ded0d0 100644 --- a/src/tools/clippy/clippy_lints/src/unit_return_expecting_ord.rs +++ b/src/tools/clippy/clippy_lints/src/unit_return_expecting_ord.rs @@ -65,7 +65,7 @@ fn get_projection_pred<'tcx>( generics.predicates.iter().find_map(|(proj_pred, _)| { if let ClauseKind::Projection(pred) = proj_pred.kind().skip_binder() { let projection_pred = cx.tcx.erase_late_bound_regions(proj_pred.kind().rebind(pred)); - if projection_pred.projection_ty.substs == trait_pred.trait_ref.substs { + if projection_pred.projection_ty.args == trait_pred.trait_ref.args { return Some(projection_pred); } } @@ -76,7 +76,7 @@ fn get_projection_pred<'tcx>( fn get_args_to_check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> Vec<(usize, String)> { let mut args_to_check = Vec::new(); if let Some(def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) { - let fn_sig = cx.tcx.fn_sig(def_id).subst_identity(); + let fn_sig = cx.tcx.fn_sig(def_id).instantiate_identity(); let generics = cx.tcx.predicates_of(def_id); let fn_mut_preds = get_trait_predicates_for_trait_id(cx, generics, cx.tcx.lang_items().fn_mut_trait()); let ord_preds = get_trait_predicates_for_trait_id(cx, generics, cx.tcx.get_diagnostic_item(sym::Ord)); @@ -120,8 +120,8 @@ fn get_args_to_check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> Ve fn check_arg<'tcx>(cx: &LateContext<'tcx>, arg: &'tcx Expr<'tcx>) -> Option<(Span, Option<Span>)> { if_chain! { if let ExprKind::Closure(&Closure { body, fn_decl_span, .. }) = arg.kind; - if let ty::Closure(_def_id, substs) = &cx.typeck_results().node_type(arg.hir_id).kind(); - let ret_ty = substs.as_closure().sig().output(); + if let ty::Closure(_def_id, args) = &cx.typeck_results().node_type(arg.hir_id).kind(); + let ret_ty = args.as_closure().sig().output(); let ty = cx.tcx.erase_late_bound_regions(ret_ty); if ty.is_unit(); then { diff --git a/src/tools/clippy/clippy_lints/src/unit_types/let_unit_value.rs b/src/tools/clippy/clippy_lints/src/unit_types/let_unit_value.rs index cc7c2b039f2..704d7abd7e5 100644 --- a/src/tools/clippy/clippy_lints/src/unit_types/let_unit_value.rs +++ b/src/tools/clippy/clippy_lints/src/unit_types/let_unit_value.rs @@ -161,7 +161,7 @@ fn needs_inferred_result_ty( }, _ => return false, }; - let sig = cx.tcx.fn_sig(id).subst_identity().skip_binder(); + let sig = cx.tcx.fn_sig(id).instantiate_identity().skip_binder(); if let ty::Param(output_ty) = *sig.output().kind() { let args: Vec<&Expr<'_>> = if let Some(receiver) = receiver { std::iter::once(receiver).chain(args.iter()).collect() diff --git a/src/tools/clippy/clippy_lints/src/unnamed_address.rs b/src/tools/clippy/clippy_lints/src/unnamed_address.rs index 0f5cdb6aaea..dea8a1e35bb 100644 --- a/src/tools/clippy/clippy_lints/src/unnamed_address.rs +++ b/src/tools/clippy/clippy_lints/src/unnamed_address.rs @@ -97,7 +97,7 @@ impl LateLintPass<'_> for UnnamedAddress { if let ExprKind::Path(ref func_qpath) = func.kind; if let Some(def_id) = cx.qpath_res(func_qpath, func.hir_id).opt_def_id(); if match_def_path(cx, def_id, &paths::PTR_EQ); - let ty_param = cx.typeck_results().node_substs(func.hir_id).type_at(0); + let ty_param = cx.typeck_results().node_args(func.hir_id).type_at(0); if ty_param.is_trait(); then { span_lint_and_help( diff --git a/src/tools/clippy/clippy_lints/src/use_self.rs b/src/tools/clippy/clippy_lints/src/use_self.rs index 5a02987453c..81dc426b389 100644 --- a/src/tools/clippy/clippy_lints/src/use_self.rs +++ b/src/tools/clippy/clippy_lints/src/use_self.rs @@ -145,7 +145,7 @@ impl<'tcx> LateLintPass<'tcx> for UseSelf { then { // `self_ty` is the semantic self type of `impl <trait> for <type>`. This cannot be // `Self`. - let self_ty = impl_trait_ref.subst_identity().self_ty(); + let self_ty = impl_trait_ref.instantiate_identity().self_ty(); // `trait_method_sig` is the signature of the function, how it is declared in the // trait, not in the impl of the trait. @@ -154,7 +154,7 @@ impl<'tcx> LateLintPass<'tcx> for UseSelf { .associated_item(impl_item.owner_id) .trait_item_def_id .expect("impl method matches a trait method"); - let trait_method_sig = cx.tcx.fn_sig(trait_method).subst_identity(); + let trait_method_sig = cx.tcx.fn_sig(trait_method).instantiate_identity(); let trait_method_sig = cx.tcx.erase_late_bound_regions(trait_method_sig); // `impl_inputs_outputs` is an iterator over the types (`hir::Ty`) declared in the @@ -226,7 +226,7 @@ impl<'tcx> LateLintPass<'tcx> for UseSelf { } else { hir_ty_to_ty(cx.tcx, hir_ty) }; - if same_type_and_consts(ty, cx.tcx.type_of(impl_id).subst_identity()); + if same_type_and_consts(ty, cx.tcx.type_of(impl_id).instantiate_identity()); then { span_lint(cx, hir_ty.span); } @@ -238,7 +238,7 @@ impl<'tcx> LateLintPass<'tcx> for UseSelf { if !expr.span.from_expansion(); if self.msrv.meets(msrvs::TYPE_ALIAS_ENUM_VARIANTS); if let Some(&StackItem::Check { impl_id, .. }) = self.stack.last(); - if cx.typeck_results().expr_ty(expr) == cx.tcx.type_of(impl_id).subst_identity(); + if cx.typeck_results().expr_ty(expr) == cx.tcx.type_of(impl_id).instantiate_identity(); then {} else { return; } } match expr.kind { @@ -262,7 +262,7 @@ impl<'tcx> LateLintPass<'tcx> for UseSelf { if let PatKind::Path(QPath::Resolved(_, path)) | PatKind::TupleStruct(QPath::Resolved(_, path), _, _) | PatKind::Struct(QPath::Resolved(_, path), _, _) = pat.kind; - if cx.typeck_results().pat_ty(pat) == cx.tcx.type_of(impl_id).subst_identity(); + if cx.typeck_results().pat_ty(pat) == cx.tcx.type_of(impl_id).instantiate_identity(); then { check_path(cx, path); } diff --git a/src/tools/clippy/clippy_lints/src/useless_conversion.rs b/src/tools/clippy/clippy_lints/src/useless_conversion.rs index b6c11cfb355..98f7bfb4ba1 100644 --- a/src/tools/clippy/clippy_lints/src/useless_conversion.rs +++ b/src/tools/clippy/clippy_lints/src/useless_conversion.rs @@ -227,8 +227,8 @@ impl<'tcx> LateLintPass<'tcx> for UselessConversion { let a = cx.typeck_results().expr_ty(e); let b = cx.typeck_results().expr_ty(recv); if is_type_diagnostic_item(cx, a, sym::Result); - if let ty::Adt(_, substs) = a.kind(); - if let Some(a_type) = substs.types().next(); + if let ty::Adt(_, args) = a.kind(); + if let Some(a_type) = args.types().next(); if same_type_and_consts(a_type, b); then { @@ -255,8 +255,8 @@ impl<'tcx> LateLintPass<'tcx> for UselessConversion { if_chain! { if match_def_path(cx, def_id, &paths::TRY_FROM); if is_type_diagnostic_item(cx, a, sym::Result); - if let ty::Adt(_, substs) = a.kind(); - if let Some(a_type) = substs.types().next(); + if let ty::Adt(_, args) = a.kind(); + if let Some(a_type) = args.types().next(); if same_type_and_consts(a_type, b); then { diff --git a/src/tools/clippy/clippy_lints/src/utils/internal_lints/interning_defined_symbol.rs b/src/tools/clippy/clippy_lints/src/utils/internal_lints/interning_defined_symbol.rs index dced9fcf9ab..da8654d9388 100644 --- a/src/tools/clippy/clippy_lints/src/utils/internal_lints/interning_defined_symbol.rs +++ b/src/tools/clippy/clippy_lints/src/utils/internal_lints/interning_defined_symbol.rs @@ -78,7 +78,7 @@ impl<'tcx> LateLintPass<'tcx> for InterningDefinedSymbol { for item in cx.tcx.module_children(def_id) { if_chain! { if let Res::Def(DefKind::Const, item_def_id) = item.res; - let ty = cx.tcx.type_of(item_def_id).subst_identity(); + let ty = cx.tcx.type_of(item_def_id).instantiate_identity(); if match_type(cx, ty, &paths::SYMBOL); if let Ok(ConstValue::Scalar(value)) = cx.tcx.const_eval_poly(item_def_id); if let Ok(value) = value.to_u32(); diff --git a/src/tools/clippy/clippy_lints/src/utils/internal_lints/msrv_attr_impl.rs b/src/tools/clippy/clippy_lints/src/utils/internal_lints/msrv_attr_impl.rs index 09f0f0d0adb..bf835f89cfc 100644 --- a/src/tools/clippy/clippy_lints/src/utils/internal_lints/msrv_attr_impl.rs +++ b/src/tools/clippy/clippy_lints/src/utils/internal_lints/msrv_attr_impl.rs @@ -7,7 +7,7 @@ use rustc_errors::Applicability; use rustc_hir as hir; use rustc_hir_analysis::hir_ty_to_ty; use rustc_lint::{LateContext, LateLintPass, LintContext}; -use rustc_middle::ty::{self, subst::GenericArgKind}; +use rustc_middle::ty::{self, GenericArgKind}; use rustc_session::{declare_lint_pass, declare_tool_lint}; declare_clippy_lint! { @@ -39,7 +39,7 @@ impl LateLintPass<'_> for MsrvAttrImpl { if self_ty_def.all_fields().any(|f| { cx.tcx .type_of(f.did) - .subst_identity() + .instantiate_identity() .walk() .filter(|t| matches!(t.unpack(), GenericArgKind::Type(_))) .any(|t| match_type(cx, t.expect_ty(), &paths::MSRV)) diff --git a/src/tools/clippy/clippy_lints/src/utils/internal_lints/unnecessary_def_path.rs b/src/tools/clippy/clippy_lints/src/utils/internal_lints/unnecessary_def_path.rs index 00842376628..f66f33fee16 100644 --- a/src/tools/clippy/clippy_lints/src/utils/internal_lints/unnecessary_def_path.rs +++ b/src/tools/clippy/clippy_lints/src/utils/internal_lints/unnecessary_def_path.rs @@ -229,11 +229,11 @@ fn path_to_matched_type(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> Option<Ve Res::Def(DefKind::Static(_), def_id) => read_mir_alloc_def_path( cx, cx.tcx.eval_static_initializer(def_id).ok()?.inner(), - cx.tcx.type_of(def_id).subst_identity(), + cx.tcx.type_of(def_id).instantiate_identity(), ), Res::Def(DefKind::Const, def_id) => match cx.tcx.const_eval_poly(def_id).ok()? { ConstValue::ByRef { alloc, offset } if offset.bytes() == 0 => { - read_mir_alloc_def_path(cx, alloc.inner(), cx.tcx.type_of(def_id).subst_identity()) + read_mir_alloc_def_path(cx, alloc.inner(), cx.tcx.type_of(def_id).instantiate_identity()) }, _ => None, }, diff --git a/src/tools/clippy/clippy_lints/src/vec.rs b/src/tools/clippy/clippy_lints/src/vec.rs index 2a594e750b9..d1bf292d711 100644 --- a/src/tools/clippy/clippy_lints/src/vec.rs +++ b/src/tools/clippy/clippy_lints/src/vec.rs @@ -230,8 +230,8 @@ fn size_of(cx: &LateContext<'_>, expr: &Expr<'_>) -> u64 { /// Returns the item type of the vector (i.e., the `T` in `Vec<T>`). fn vec_type(ty: Ty<'_>) -> Ty<'_> { - if let ty::Adt(_, substs) = ty.kind() { - substs.type_at(0) + if let ty::Adt(_, args) = ty.kind() { + args.type_at(0) } else { panic!("The type of `vec!` is a not a struct?"); } diff --git a/src/tools/clippy/clippy_lints/src/zero_sized_map_values.rs b/src/tools/clippy/clippy_lints/src/zero_sized_map_values.rs index 93e4b023c5c..002304f8840 100644 --- a/src/tools/clippy/clippy_lints/src/zero_sized_map_values.rs +++ b/src/tools/clippy/clippy_lints/src/zero_sized_map_values.rs @@ -51,8 +51,8 @@ impl LateLintPass<'_> for ZeroSizedMapValues { if !in_trait_impl(cx, hir_ty.hir_id); let ty = ty_from_hir_ty(cx, hir_ty); if is_type_diagnostic_item(cx, ty, sym::HashMap) || is_type_diagnostic_item(cx, ty, sym::BTreeMap); - if let Adt(_, substs) = ty.kind(); - let ty = substs.type_at(1); + if let Adt(_, args) = ty.kind(); + let ty = args.type_at(1); // Fixes https://github.com/rust-lang/rust-clippy/issues/7447 because of // https://github.com/rust-lang/rust/blob/master/compiler/rustc_middle/src/ty/sty.rs#L968 if !ty.has_escaping_bound_vars(); diff --git a/src/tools/clippy/clippy_utils/src/consts.rs b/src/tools/clippy/clippy_utils/src/consts.rs index d1cfdc49658..4832a38eceb 100644 --- a/src/tools/clippy/clippy_utils/src/consts.rs +++ b/src/tools/clippy/clippy_utils/src/consts.rs @@ -12,7 +12,7 @@ use rustc_lint::LateContext; use rustc_middle::mir; use rustc_middle::mir::interpret::Scalar; use rustc_middle::ty::{self, EarlyBinder, FloatTy, ScalarInt, Ty, TyCtxt}; -use rustc_middle::ty::{List, SubstsRef}; +use rustc_middle::ty::{List, GenericArgsRef}; use rustc_middle::{bug, span_bug}; use rustc_span::symbol::{Ident, Symbol}; use rustc_span::SyntaxContext; @@ -327,7 +327,7 @@ pub struct ConstEvalLateContext<'a, 'tcx> { typeck_results: &'a ty::TypeckResults<'tcx>, param_env: ty::ParamEnv<'tcx>, source: ConstantSource, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, } impl<'a, 'tcx> ConstEvalLateContext<'a, 'tcx> { @@ -337,7 +337,7 @@ impl<'a, 'tcx> ConstEvalLateContext<'a, 'tcx> { typeck_results, param_env: lcx.param_env, source: ConstantSource::Local, - substs: List::empty(), + args: List::empty(), } } @@ -473,16 +473,16 @@ impl<'a, 'tcx> ConstEvalLateContext<'a, 'tcx> { return None; } - let substs = self.typeck_results.node_substs(id); - let substs = if self.substs.is_empty() { - substs + let args = self.typeck_results.node_args(id); + let args = if self.args.is_empty() { + args } else { - EarlyBinder::bind(substs).subst(self.lcx.tcx, self.substs) + EarlyBinder::bind(args).instantiate(self.lcx.tcx, self.args) }; let result = self .lcx .tcx - .const_eval_resolve(self.param_env, mir::UnevaluatedConst::new(def_id, substs), None) + .const_eval_resolve(self.param_env, mir::UnevaluatedConst::new(def_id, args), None) .ok() .map(|val| rustc_middle::mir::ConstantKind::from_value(val, ty))?; let result = miri_to_const(self.lcx, result)?; diff --git a/src/tools/clippy/clippy_utils/src/eager_or_lazy.rs b/src/tools/clippy/clippy_utils/src/eager_or_lazy.rs index 4a845ca63b4..94b9006ed50 100644 --- a/src/tools/clippy/clippy_utils/src/eager_or_lazy.rs +++ b/src/tools/clippy/clippy_utils/src/eager_or_lazy.rs @@ -51,7 +51,7 @@ fn fn_eagerness(cx: &LateContext<'_>, fn_id: DefId, name: Symbol, have_one_arg: let name = name.as_str(); let ty = match cx.tcx.impl_of_method(fn_id) { - Some(id) => cx.tcx.type_of(id).subst_identity(), + Some(id) => cx.tcx.type_of(id).instantiate_identity(), None => return Lazy, }; @@ -72,7 +72,7 @@ fn fn_eagerness(cx: &LateContext<'_>, fn_id: DefId, name: Symbol, have_one_arg: .variants() .iter() .flat_map(|v| v.fields.iter()) - .any(|x| matches!(cx.tcx.type_of(x.did).subst_identity().peel_refs().kind(), ty::Param(_))) + .any(|x| matches!(cx.tcx.type_of(x.did).instantiate_identity().peel_refs().kind(), ty::Param(_))) && all_predicates_of(cx.tcx, fn_id).all(|(pred, _)| match pred.kind().skip_binder() { ty::ClauseKind::Trait(pred) => cx.tcx.trait_def(pred.trait_ref.def_id).is_marker, _ => true, @@ -80,7 +80,7 @@ fn fn_eagerness(cx: &LateContext<'_>, fn_id: DefId, name: Symbol, have_one_arg: && subs.types().all(|x| matches!(x.peel_refs().kind(), ty::Param(_))) { // Limit the function to either `(self) -> bool` or `(&self) -> bool` - match &**cx.tcx.fn_sig(fn_id).subst_identity().skip_binder().inputs_and_output { + match &**cx.tcx.fn_sig(fn_id).instantiate_identity().skip_binder().inputs_and_output { [arg, res] if !arg.is_mutable_ptr() && arg.peel_refs() == ty && res.is_bool() => NoChange, _ => Lazy, } diff --git a/src/tools/clippy/clippy_utils/src/lib.rs b/src/tools/clippy/clippy_utils/src/lib.rs index 727b59f1f43..5eed5ddf9e3 100644 --- a/src/tools/clippy/clippy_utils/src/lib.rs +++ b/src/tools/clippy/clippy_utils/src/lib.rs @@ -305,7 +305,7 @@ pub fn match_trait_method(cx: &LateContext<'_>, expr: &Expr<'_>, path: &[&str]) /// Checks if a method is defined in an impl of a diagnostic item pub fn is_diag_item_method(cx: &LateContext<'_>, def_id: DefId, diag_item: Symbol) -> bool { if let Some(impl_did) = cx.tcx.impl_of_method(def_id) { - if let Some(adt) = cx.tcx.type_of(impl_did).subst_identity().ty_adt_def() { + if let Some(adt) = cx.tcx.type_of(impl_did).instantiate_identity().ty_adt_def() { return cx.tcx.is_diagnostic_item(diag_item, adt.did()); } } @@ -812,7 +812,7 @@ fn is_default_equivalent_ctor(cx: &LateContext<'_>, def_id: DefId, path: &QPath< if let QPath::TypeRelative(_, method) = path { if method.ident.name == sym::new { if let Some(impl_did) = cx.tcx.impl_of_method(def_id) { - if let Some(adt) = cx.tcx.type_of(impl_did).subst_identity().ty_adt_def() { + if let Some(adt) = cx.tcx.type_of(impl_did).instantiate_identity().ty_adt_def() { return std_types_symbols.iter().any(|&symbol| { cx.tcx.is_diagnostic_item(symbol, adt.did()) || Some(adt.did()) == cx.tcx.lang_items().string() }); @@ -1377,7 +1377,7 @@ pub fn get_enclosing_loop_or_multi_call_closure<'tcx>( .chain(args.iter()) .position(|arg| arg.hir_id == id)?; let id = cx.typeck_results().type_dependent_def_id(e.hir_id)?; - let ty = cx.tcx.fn_sig(id).subst_identity().skip_binder().inputs()[i]; + let ty = cx.tcx.fn_sig(id).instantiate_identity().skip_binder().inputs()[i]; ty_is_fn_once_param(cx.tcx, ty, cx.tcx.param_env(id).caller_bounds()).then_some(()) }, _ => None, @@ -1639,13 +1639,13 @@ pub fn is_direct_expn_of(span: Span, name: &str) -> Option<Span> { /// Convenience function to get the return type of a function. pub fn return_ty<'tcx>(cx: &LateContext<'tcx>, fn_def_id: hir::OwnerId) -> Ty<'tcx> { - let ret_ty = cx.tcx.fn_sig(fn_def_id).subst_identity().output(); + let ret_ty = cx.tcx.fn_sig(fn_def_id).instantiate_identity().output(); cx.tcx.erase_late_bound_regions(ret_ty) } /// Convenience function to get the nth argument type of a function. pub fn nth_arg<'tcx>(cx: &LateContext<'tcx>, fn_def_id: hir::OwnerId, nth: usize) -> Ty<'tcx> { - let arg = cx.tcx.fn_sig(fn_def_id).subst_identity().input(nth); + let arg = cx.tcx.fn_sig(fn_def_id).instantiate_identity().input(nth); cx.tcx.erase_late_bound_regions(arg) } diff --git a/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs b/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs index fbf4ab2722e..515f80e0edf 100644 --- a/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs +++ b/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs @@ -15,7 +15,7 @@ use rustc_middle::mir::{ Terminator, TerminatorKind, }; use rustc_middle::traits::{ImplSource, ObligationCause}; -use rustc_middle::ty::subst::GenericArgKind; +use rustc_middle::ty::GenericArgKind; use rustc_middle::ty::{self, adjustment::PointerCoercion, Ty, TyCtxt}; use rustc_middle::ty::{BoundConstness, TraitRef}; use rustc_semver::RustcVersion; @@ -35,7 +35,7 @@ pub fn is_min_const_fn<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>, msrv: &Msrv) // impl trait is gone in MIR, so check the return type manually check_ty( tcx, - tcx.fn_sig(def_id).subst_identity().output().skip_binder(), + tcx.fn_sig(def_id).instantiate_identity().output().skip_binder(), body.local_decls.iter().next().unwrap().source_info.span, )?; diff --git a/src/tools/clippy/clippy_utils/src/sugg.rs b/src/tools/clippy/clippy_utils/src/sugg.rs index cf781e18cd6..3953a7d8fa7 100644 --- a/src/tools/clippy/clippy_utils/src/sugg.rs +++ b/src/tools/clippy/clippy_utils/src/sugg.rs @@ -877,7 +877,7 @@ impl<'tcx> DerefDelegate<'_, 'tcx> { .cx .typeck_results() .type_dependent_def_id(parent_expr.hir_id) - .map(|did| self.cx.tcx.fn_sig(did).subst_identity().skip_binder()) + .map(|did| self.cx.tcx.fn_sig(did).instantiate_identity().skip_binder()) { std::iter::once(receiver) .chain(call_args.iter()) diff --git a/src/tools/clippy/clippy_utils/src/ty.rs b/src/tools/clippy/clippy_utils/src/ty.rs index d650cbe0b13..7687d361923 100644 --- a/src/tools/clippy/clippy_utils/src/ty.rs +++ b/src/tools/clippy/clippy_utils/src/ty.rs @@ -17,7 +17,7 @@ use rustc_lint::LateContext; use rustc_middle::mir::interpret::{ConstValue, Scalar}; use rustc_middle::ty::{ self, layout::ValidityRequirement, AdtDef, AliasTy, AssocKind, Binder, BoundRegion, FnSig, IntTy, List, ParamEnv, - Region, RegionKind, SubstsRef, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, + Region, RegionKind, GenericArgsRef, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, UintTy, VariantDef, VariantDiscr, }; use rustc_middle::ty::{GenericArg, GenericArgKind}; @@ -90,14 +90,14 @@ pub fn contains_ty_adt_constructor_opaque<'tcx>(cx: &LateContext<'tcx>, ty: Ty<' return false; } - for (predicate, _span) in cx.tcx.explicit_item_bounds(def_id).subst_identity_iter_copied() { + for (predicate, _span) in cx.tcx.explicit_item_bounds(def_id).instantiate_identity_iter_copied() { match predicate.kind().skip_binder() { // For `impl Trait<U>`, it will register a predicate of `T: Trait<U>`, so we go through // and check substitutions to find `U`. ty::ClauseKind::Trait(trait_predicate) => { if trait_predicate .trait_ref - .substs + .args .types() .skip(1) // Skip the implicit `Self` generic parameter .any(|ty| contains_ty_adt_constructor_opaque_inner(cx, ty, needle, seen)) @@ -237,7 +237,7 @@ pub fn implements_trait_with_env<'tcx>( kind: TypeVariableOriginKind::MiscVariable, span: DUMMY_SP, }; - let ty_params = tcx.mk_substs_from_iter( + let ty_params = tcx.mk_args_from_iter( ty_params .into_iter() .map(|arg| arg.unwrap_or_else(|| infcx.next_ty_var(orig).into())), @@ -265,7 +265,7 @@ pub fn is_must_use_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool { // because we don't want to lint functions returning empty arrays is_must_use_ty(cx, *ty) }, - ty::Tuple(substs) => substs.iter().any(|ty| is_must_use_ty(cx, ty)), + ty::Tuple(args) => args.iter().any(|ty| is_must_use_ty(cx, ty)), ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }) => { for (predicate, _) in cx.tcx.explicit_item_bounds(def_id).skip_binder() { if let ty::ClauseKind::Trait(trait_predicate) = predicate.kind().skip_binder() { @@ -314,11 +314,11 @@ fn is_normalizable_helper<'tcx>( let cause = rustc_middle::traits::ObligationCause::dummy(); let result = if infcx.at(&cause, param_env).query_normalize(ty).is_ok() { match ty.kind() { - ty::Adt(def, substs) => def.variants().iter().all(|variant| { + ty::Adt(def, args) => def.variants().iter().all(|variant| { variant .fields .iter() - .all(|field| is_normalizable_helper(cx, param_env, field.ty(cx.tcx, substs), cache)) + .all(|field| is_normalizable_helper(cx, param_env, field.ty(cx.tcx, args), cache)) }), _ => ty.walk().all(|generic_arg| match generic_arg.unpack() { GenericArgKind::Type(inner_ty) if inner_ty != ty => { @@ -517,14 +517,14 @@ pub fn walk_ptrs_ty_depth(ty: Ty<'_>) -> (Ty<'_>, usize) { /// otherwise returns `false` pub fn same_type_and_consts<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool { match (&a.kind(), &b.kind()) { - (&ty::Adt(did_a, substs_a), &ty::Adt(did_b, substs_b)) => { + (&ty::Adt(did_a, args_a), &ty::Adt(did_b, args_b)) => { if did_a != did_b { return false; } - substs_a + args_a .iter() - .zip(substs_b.iter()) + .zip(args_b.iter()) .all(|(arg_a, arg_b)| match (arg_a.unpack(), arg_b.unpack()) { (GenericArgKind::Const(inner_a), GenericArgKind::Const(inner_b)) => inner_a == inner_b, (GenericArgKind::Type(type_a), GenericArgKind::Type(type_b)) => { @@ -643,7 +643,7 @@ impl<'tcx> ExprFnSig<'tcx> { /// If the expression is function like, get the signature for it. pub fn expr_sig<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'_>) -> Option<ExprFnSig<'tcx>> { if let Res::Def(DefKind::Fn | DefKind::Ctor(_, CtorKind::Fn) | DefKind::AssocFn, id) = path_res(cx, expr) { - Some(ExprFnSig::Sig(cx.tcx.fn_sig(id).subst_identity(), Some(id))) + Some(ExprFnSig::Sig(cx.tcx.fn_sig(id).instantiate_identity(), Some(id))) } else { ty_sig(cx, cx.typeck_results().expr_ty_adjusted(expr).peel_refs()) } @@ -661,11 +661,11 @@ pub fn ty_sig<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option<ExprFnSig<'t .and_then(|id| cx.tcx.hir().fn_decl_by_hir_id(cx.tcx.hir().local_def_id_to_hir_id(id))); Some(ExprFnSig::Closure(decl, subs.as_closure().sig())) }, - ty::FnDef(id, subs) => Some(ExprFnSig::Sig(cx.tcx.fn_sig(id).subst(cx.tcx, subs), Some(id))), - ty::Alias(ty::Opaque, ty::AliasTy { def_id, substs, .. }) => sig_from_bounds( + ty::FnDef(id, subs) => Some(ExprFnSig::Sig(cx.tcx.fn_sig(id).instantiate(cx.tcx, subs), Some(id))), + ty::Alias(ty::Opaque, ty::AliasTy { def_id, args, .. }) => sig_from_bounds( cx, ty, - cx.tcx.item_bounds(def_id).subst_iter(cx.tcx, substs), + cx.tcx.item_bounds(def_id).arg_iter(cx.tcx, args), cx.tcx.opt_parent(def_id), ), ty::FnPtr(sig) => Some(ExprFnSig::Sig(sig, None)), @@ -681,7 +681,7 @@ pub fn ty_sig<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option<ExprFnSig<'t .projection_bounds() .find(|p| lang_items.fn_once_output().map_or(false, |id| id == p.item_def_id())) .map(|p| p.map_bound(|p| p.term.ty().unwrap())); - Some(ExprFnSig::Trait(bound.map_bound(|b| b.substs.type_at(0)), output, None)) + Some(ExprFnSig::Trait(bound.map_bound(|b| b.args.type_at(0)), output, None)) }, _ => None, } @@ -713,7 +713,7 @@ fn sig_from_bounds<'tcx>( || lang_items.fn_once_trait() == Some(p.def_id())) && p.self_ty() == ty => { - let i = pred.kind().rebind(p.trait_ref.substs.type_at(1)); + let i = pred.kind().rebind(p.trait_ref.args.type_at(1)); if inputs.map_or(false, |inputs| i != inputs) { // Multiple different fn trait impls. Is this even allowed? return None; @@ -744,7 +744,7 @@ fn sig_for_projection<'tcx>(cx: &LateContext<'tcx>, ty: AliasTy<'tcx>) -> Option for (pred, _) in cx .tcx .explicit_item_bounds(ty.def_id) - .subst_iter_copied(cx.tcx, ty.substs) + .arg_iter_copied(cx.tcx, ty.args) { match pred.kind().skip_binder() { ty::ClauseKind::Trait(p) @@ -752,7 +752,7 @@ fn sig_for_projection<'tcx>(cx: &LateContext<'tcx>, ty: AliasTy<'tcx>) -> Option || lang_items.fn_mut_trait() == Some(p.def_id()) || lang_items.fn_once_trait() == Some(p.def_id())) => { - let i = pred.kind().rebind(p.trait_ref.substs.type_at(1)); + let i = pred.kind().rebind(p.trait_ref.args.type_at(1)); if inputs.map_or(false, |inputs| inputs != i) { // Multiple different fn trait impls. Is this even allowed? @@ -793,7 +793,7 @@ impl core::ops::Add<u32> for EnumValue { #[expect(clippy::cast_possible_truncation, clippy::cast_possible_wrap)] pub fn read_explicit_enum_value(tcx: TyCtxt<'_>, id: DefId) -> Option<EnumValue> { if let Ok(ConstValue::Scalar(Scalar::Int(value))) = tcx.const_eval_poly(id) { - match tcx.type_of(id).subst_identity().kind() { + match tcx.type_of(id).instantiate_identity().kind() { ty::Int(_) => Some(EnumValue::Signed(match value.size().bytes() { 1 => i128::from(value.assert_bits(Size::from_bytes(1)) as u8 as i8), 2 => i128::from(value.assert_bits(Size::from_bytes(2)) as u16 as i16), @@ -927,7 +927,7 @@ pub fn adt_and_variant_of_res<'tcx>(cx: &LateContext<'tcx>, res: Res) -> Option< Some((adt, adt.variant_with_id(var_id))) }, Res::SelfCtor(id) => { - let adt = cx.tcx.type_of(id).subst_identity().ty_adt_def().unwrap(); + let adt = cx.tcx.type_of(id).instantiate_identity().ty_adt_def().unwrap(); Some((adt, adt.non_enum_variant())) }, _ => None, @@ -1025,13 +1025,13 @@ pub fn make_projection<'tcx>( tcx: TyCtxt<'tcx>, container_id: DefId, assoc_ty: Symbol, - substs: impl IntoIterator<Item = impl Into<GenericArg<'tcx>>>, + args: impl IntoIterator<Item = impl Into<GenericArg<'tcx>>>, ) -> Option<AliasTy<'tcx>> { fn helper<'tcx>( tcx: TyCtxt<'tcx>, container_id: DefId, assoc_ty: Symbol, - substs: SubstsRef<'tcx>, + args: GenericArgsRef<'tcx>, ) -> Option<AliasTy<'tcx>> { let Some(assoc_item) = tcx .associated_items(container_id) @@ -1052,18 +1052,18 @@ pub fn make_projection<'tcx>( .map(|x| &x.kind); debug_assert!( - generic_count == substs.len(), - "wrong number of substs for `{:?}`: found `{}` expected `{generic_count}`.\n\ + generic_count == args.len(), + "wrong number of args for `{:?}`: found `{}` expected `{generic_count}`.\n\ note: the expected parameters are: {:#?}\n\ - the given arguments are: `{substs:#?}`", + the given arguments are: `{args:#?}`", assoc_item.def_id, - substs.len(), + args.len(), params.map(ty::GenericParamDefKind::descr).collect::<Vec<_>>(), ); if let Some((idx, (param, arg))) = params .clone() - .zip(substs.iter().map(GenericArg::unpack)) + .zip(args.iter().map(GenericArg::unpack)) .enumerate() .find(|(_, (param, arg))| { !matches!( @@ -1078,20 +1078,20 @@ pub fn make_projection<'tcx>( false, "mismatched subst type at index {idx}: expected a {}, found `{arg:?}`\n\ note: the expected parameters are {:#?}\n\ - the given arguments are {substs:#?}", + the given arguments are {args:#?}", param.descr(), params.map(ty::GenericParamDefKind::descr).collect::<Vec<_>>() ); } } - Some(tcx.mk_alias_ty(assoc_item.def_id, substs)) + Some(tcx.mk_alias_ty(assoc_item.def_id, args)) } helper( tcx, container_id, assoc_ty, - tcx.mk_substs_from_iter(substs.into_iter().map(Into::into)), + tcx.mk_args_from_iter(args.into_iter().map(Into::into)), ) } @@ -1106,25 +1106,25 @@ pub fn make_normalized_projection<'tcx>( param_env: ParamEnv<'tcx>, container_id: DefId, assoc_ty: Symbol, - substs: impl IntoIterator<Item = impl Into<GenericArg<'tcx>>>, + args: impl IntoIterator<Item = impl Into<GenericArg<'tcx>>>, ) -> Option<Ty<'tcx>> { fn helper<'tcx>(tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>, ty: AliasTy<'tcx>) -> Option<Ty<'tcx>> { #[cfg(debug_assertions)] if let Some((i, subst)) = ty - .substs + .args .iter() .enumerate() .find(|(_, subst)| subst.has_late_bound_regions()) { debug_assert!( false, - "substs contain late-bound region at index `{i}` which can't be normalized.\n\ + "args contain late-bound region at index `{i}` which can't be normalized.\n\ use `TyCtxt::erase_late_bound_regions`\n\ note: subst is `{subst:#?}`", ); return None; } - match tcx.try_normalize_erasing_regions(param_env, Ty::new_projection(tcx,ty.def_id, ty.substs)) { + match tcx.try_normalize_erasing_regions(param_env, Ty::new_projection(tcx,ty.def_id, ty.args)) { Ok(ty) => Some(ty), Err(e) => { debug_assert!(false, "failed to normalize type `{ty}`: {e:#?}"); @@ -1132,7 +1132,7 @@ pub fn make_normalized_projection<'tcx>( }, } } - helper(tcx, param_env, make_projection(tcx, container_id, assoc_ty, substs)?) + helper(tcx, param_env, make_projection(tcx, container_id, assoc_ty, args)?) } /// Check if given type has inner mutability such as [`std::cell::Cell`] or [`std::cell::RefCell`] @@ -1147,7 +1147,7 @@ pub fn is_interior_mut_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool { && is_interior_mut_ty(cx, inner_ty) }, ty::Tuple(fields) => fields.iter().any(|ty| is_interior_mut_ty(cx, ty)), - ty::Adt(def, substs) => { + ty::Adt(def, args) => { // Special case for collections in `std` who's impl of `Hash` or `Ord` delegates to // that of their type parameters. Note: we don't include `HashSet` and `HashMap` // because they have no impl for `Hash` or `Ord`. @@ -1168,7 +1168,7 @@ pub fn is_interior_mut_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool { let is_box = Some(def_id) == cx.tcx.lang_items().owned_box(); if is_std_collection || is_box { // The type is mutable if any of its type parameters are - substs.types().any(|ty| is_interior_mut_ty(cx, ty)) + args.types().any(|ty| is_interior_mut_ty(cx, ty)) } else { !ty.has_escaping_bound_vars() && cx.tcx.layout_of(cx.param_env.and(ty)).is_ok() @@ -1184,19 +1184,19 @@ pub fn make_normalized_projection_with_regions<'tcx>( param_env: ParamEnv<'tcx>, container_id: DefId, assoc_ty: Symbol, - substs: impl IntoIterator<Item = impl Into<GenericArg<'tcx>>>, + args: impl IntoIterator<Item = impl Into<GenericArg<'tcx>>>, ) -> Option<Ty<'tcx>> { fn helper<'tcx>(tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>, ty: AliasTy<'tcx>) -> Option<Ty<'tcx>> { #[cfg(debug_assertions)] if let Some((i, subst)) = ty - .substs + .args .iter() .enumerate() .find(|(_, subst)| subst.has_late_bound_regions()) { debug_assert!( false, - "substs contain late-bound region at index `{i}` which can't be normalized.\n\ + "args contain late-bound region at index `{i}` which can't be normalized.\n\ use `TyCtxt::erase_late_bound_regions`\n\ note: subst is `{subst:#?}`", ); @@ -1207,7 +1207,7 @@ pub fn make_normalized_projection_with_regions<'tcx>( .infer_ctxt() .build() .at(&cause, param_env) - .query_normalize(Ty::new_projection(tcx,ty.def_id, ty.substs)) + .query_normalize(Ty::new_projection(tcx,ty.def_id, ty.args)) { Ok(ty) => Some(ty.value), Err(e) => { @@ -1216,7 +1216,7 @@ pub fn make_normalized_projection_with_regions<'tcx>( }, } } - helper(tcx, param_env, make_projection(tcx, container_id, assoc_ty, substs)?) + helper(tcx, param_env, make_projection(tcx, container_id, assoc_ty, args)?) } pub fn normalize_with_regions<'tcx>(tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> { diff --git a/src/tools/clippy/tests/ui/crashes/ice-6256.rs b/src/tools/clippy/tests/ui/crashes/ice-6256.rs index 1d336b3cdc0..bb488c2dcb3 100644 --- a/src/tools/clippy/tests/ui/crashes/ice-6256.rs +++ b/src/tools/clippy/tests/ui/crashes/ice-6256.rs @@ -1,5 +1,5 @@ // originally from rustc ./tests/ui/regions/issue-78262.rs -// ICE: to get the signature of a closure, use substs.as_closure().sig() not fn_sig() +// ICE: to get the signature of a closure, use args.as_closure().sig() not fn_sig() #![allow(clippy::upper_case_acronyms)] trait TT {} diff --git a/src/tools/clippy/tests/ui/empty_line_after_doc_comments.rs b/src/tools/clippy/tests/ui/empty_line_after_doc_comments.rs index 83db2a07d33..cc36ce5f487 100644 --- a/src/tools/clippy/tests/ui/empty_line_after_doc_comments.rs +++ b/src/tools/clippy/tests/ui/empty_line_after_doc_comments.rs @@ -1,4 +1,7 @@ //@aux-build:proc_macro_attr.rs:proc-macro +// Flaky test, see https://github.com/rust-lang/rust/issues/113585. +//@ignore-32bit +//@ignore-64bit #![warn(clippy::empty_line_after_doc_comments)] #![allow(clippy::assertions_on_constants)] #![feature(custom_inner_attributes)] diff --git a/src/tools/clippy/tests/ui/empty_line_after_outer_attribute.rs b/src/tools/clippy/tests/ui/empty_line_after_outer_attribute.rs index b2d7ddae427..bc54e0fd2de 100644 --- a/src/tools/clippy/tests/ui/empty_line_after_outer_attribute.rs +++ b/src/tools/clippy/tests/ui/empty_line_after_outer_attribute.rs @@ -1,4 +1,7 @@ //@aux-build:proc_macro_attr.rs:proc-macro +// Flaky test, see https://github.com/rust-lang/rust/issues/113585. +//@ignore-32bit +//@ignore-64bit #![warn(clippy::empty_line_after_outer_attr)] #![allow(clippy::assertions_on_constants)] #![feature(custom_inner_attributes)] diff --git a/src/tools/clippy/tests/ui/eta.fixed b/src/tools/clippy/tests/ui/eta.fixed index bf44bcb564e..db7bd99e0ae 100644 --- a/src/tools/clippy/tests/ui/eta.fixed +++ b/src/tools/clippy/tests/ui/eta.fixed @@ -331,7 +331,7 @@ impl dyn TestTrait + '_ { } // https://github.com/rust-lang/rust-clippy/issues/7746 -fn angle_brackets_and_substs() { +fn angle_brackets_and_args() { let array_opt: Option<&[u8; 3]> = Some(&[4, 8, 7]); array_opt.map(<[u8; 3]>::as_slice); diff --git a/src/tools/clippy/tests/ui/eta.rs b/src/tools/clippy/tests/ui/eta.rs index b2af4bf0953..52fc17686fd 100644 --- a/src/tools/clippy/tests/ui/eta.rs +++ b/src/tools/clippy/tests/ui/eta.rs @@ -331,7 +331,7 @@ impl dyn TestTrait + '_ { } // https://github.com/rust-lang/rust-clippy/issues/7746 -fn angle_brackets_and_substs() { +fn angle_brackets_and_args() { let array_opt: Option<&[u8; 3]> = Some(&[4, 8, 7]); array_opt.map(|a| a.as_slice()); diff --git a/src/tools/clippy/tests/ui/needless_arbitrary_self_type_unfixable.rs b/src/tools/clippy/tests/ui/needless_arbitrary_self_type_unfixable.rs index 876f16a3854..321aa69a1a5 100644 --- a/src/tools/clippy/tests/ui/needless_arbitrary_self_type_unfixable.rs +++ b/src/tools/clippy/tests/ui/needless_arbitrary_self_type_unfixable.rs @@ -1,4 +1,7 @@ //@aux-build:proc_macro_attr.rs:proc-macro +// Flaky test, see https://github.com/rust-lang/rust/issues/113585. +//@ignore-32bit +//@ignore-64bit #![warn(clippy::needless_arbitrary_self_type)] diff --git a/src/tools/collect-license-metadata/src/path_tree.rs b/src/tools/collect-license-metadata/src/path_tree.rs index 68b6cef6432..709d91897e6 100644 --- a/src/tools/collect-license-metadata/src/path_tree.rs +++ b/src/tools/collect-license-metadata/src/path_tree.rs @@ -155,7 +155,10 @@ impl Node<LicenseId> { name: child_name, children: child_children, license: child_license, - } = child else { continue }; + } = child + else { + continue; + }; if child_license != license { continue; diff --git a/src/tools/compiletest/src/header.rs b/src/tools/compiletest/src/header.rs index ad10c3e07ce..d67e9aaaa6e 100644 --- a/src/tools/compiletest/src/header.rs +++ b/src/tools/compiletest/src/header.rs @@ -541,16 +541,15 @@ impl TestProps { } fn update_pass_mode(&mut self, ln: &str, revision: Option<&str>, config: &Config) { - let check_no_run = |s| { - if config.mode != Mode::Ui && config.mode != Mode::Incremental { - panic!("`{}` header is only supported in UI and incremental tests", s); - } - if config.mode == Mode::Incremental - && !revision.map_or(false, |r| r.starts_with("cfail")) - && !self.revisions.iter().all(|r| r.starts_with("cfail")) - { - panic!("`{}` header is only supported in `cfail` incremental tests", s); + let check_no_run = |s| match (config.mode, s) { + (Mode::Ui, _) => (), + (Mode::Codegen, "build-pass") => (), + (Mode::Incremental, _) => { + if revision.is_some() && !self.revisions.iter().all(|r| r.starts_with("cfail")) { + panic!("`{s}` header is only supported in `cfail` incremental tests") + } } + (mode, _) => panic!("`{s}` header is not supported in `{mode}` tests"), }; let pass_mode = if config.parse_name_directive(ln, "check-pass") { check_no_run("check-pass"); @@ -559,9 +558,7 @@ impl TestProps { check_no_run("build-pass"); Some(PassMode::Build) } else if config.parse_name_directive(ln, "run-pass") { - if config.mode != Mode::Ui { - panic!("`run-pass` header is only supported in UI tests") - } + check_no_run("run-pass"); Some(PassMode::Run) } else { None @@ -599,7 +596,10 @@ pub fn line_directive<'line>( if ln.starts_with('[') { // A comment like `//[foo]` is specific to revision `foo` let Some(close_brace) = ln.find(']') else { - panic!("malformed condition directive: expected `{}[foo]`, found `{}`", comment, ln); + panic!( + "malformed condition directive: expected `{}[foo]`, found `{}`", + comment, ln + ); }; let lncfg = &ln[1..close_brace]; diff --git a/src/tools/compiletest/src/runtest.rs b/src/tools/compiletest/src/runtest.rs index ac19fe078f0..b91e1b09330 100644 --- a/src/tools/compiletest/src/runtest.rs +++ b/src/tools/compiletest/src/runtest.rs @@ -2752,6 +2752,10 @@ impl<'test> TestCx<'test> { self.fatal_proc_rec("compilation failed!", &proc_res); } + if let Some(PassMode::Build) = self.pass_mode() { + return; + } + let output_path = self.output_base_name().with_extension("ll"); let proc_res = self.verify_with_filecheck(&output_path); if !proc_res.status.success() { diff --git a/src/tools/jsondocck/src/cache.rs b/src/tools/jsondocck/src/cache.rs index f9e54232750..50697d46b8c 100644 --- a/src/tools/jsondocck/src/cache.rs +++ b/src/tools/jsondocck/src/cache.rs @@ -15,8 +15,10 @@ impl Cache { /// Create a new cache, used to read files only once and otherwise store their contents. pub fn new(config: &Config) -> Cache { let root = Path::new(&config.doc_dir); - let filename = Path::new(&config.template).file_stem().unwrap(); - let file_path = root.join(&Path::with_extension(Path::new(filename), "json")); + // `filename` needs to replace `-` with `_` to be sure the JSON path will always be valid. + let filename = + Path::new(&config.template).file_stem().unwrap().to_str().unwrap().replace('-', "_"); + let file_path = root.join(&Path::with_extension(Path::new(&filename), "json")); let content = fs::read_to_string(&file_path).expect("failed to read JSON file"); Cache { diff --git a/src/tools/jsondoclint/src/main.rs b/src/tools/jsondoclint/src/main.rs index ee163ddfdd9..aaaba78cb46 100644 --- a/src/tools/jsondoclint/src/main.rs +++ b/src/tools/jsondoclint/src/main.rs @@ -1,4 +1,5 @@ use std::io::{BufWriter, Write}; +use std::path::{Path, PathBuf}; use anyhow::{bail, Result}; use clap::Parser; @@ -25,7 +26,7 @@ enum ErrorKind { #[derive(Debug, Serialize)] struct JsonOutput { - path: String, + path: PathBuf, errors: Vec<Error>, } @@ -45,6 +46,12 @@ struct Cli { fn main() -> Result<()> { let Cli { path, verbose, json_output } = Cli::parse(); + // We convert `-` into `_` for the file name to be sure the JSON path will always be correct. + let path = Path::new(&path); + let filename = path.file_name().unwrap().to_str().unwrap().replace('-', "_"); + let parent = path.parent().unwrap(); + let path = parent.join(&filename); + let contents = fs::read_to_string(&path)?; let krate: Crate = serde_json::from_str(&contents)?; assert_eq!(krate.format_version, FORMAT_VERSION); @@ -101,7 +108,7 @@ fn main() -> Result<()> { ErrorKind::Custom(msg) => eprintln!("{}: {}", err.id.0, msg), } } - bail!("Errors validating json {path}"); + bail!("Errors validating json {}", path.display()); } Ok(()) diff --git a/src/tools/lint-docs/src/groups.rs b/src/tools/lint-docs/src/groups.rs index b11fb287cf4..5be8ef7996b 100644 --- a/src/tools/lint-docs/src/groups.rs +++ b/src/tools/lint-docs/src/groups.rs @@ -39,7 +39,6 @@ impl<'a> LintExtractor<'a> { fn collect_groups(&self) -> Result<LintGroups, Box<dyn Error>> { let mut result = BTreeMap::new(); let mut cmd = Command::new(self.rustc_path); - cmd.env_remove("LD_LIBRARY_PATH"); cmd.arg("-Whelp"); let output = cmd.output().map_err(|e| format!("failed to run command {:?}\n{}", cmd, e))?; if !output.status.success() { diff --git a/src/tools/lint-docs/src/lib.rs b/src/tools/lint-docs/src/lib.rs index fe29b9abda3..b7c8b9ed2e3 100644 --- a/src/tools/lint-docs/src/lib.rs +++ b/src/tools/lint-docs/src/lib.rs @@ -403,12 +403,6 @@ impl<'a> LintExtractor<'a> { fs::write(&tempfile, source) .map_err(|e| format!("failed to write {}: {}", tempfile.display(), e))?; let mut cmd = Command::new(self.rustc_path); - // NOTE: bootstrap sets `LD_LIBRARY_PATH` for building lint-docs itself. - // Unfortunately, lint-docs is a bootstrap tool while rustc is built from source, - // and sometimes the paths conflict. In particular, when using `download-rustc`, - // the LLVM versions can differ between `ci-llvm` and `ci-rustc-sysroot`. - // Unset LD_LIBRARY_PATH here so it doesn't interfere with running the compiler. - cmd.env_remove("LD_LIBRARY_PATH"); if options.contains(&"edition2015") { cmd.arg("--edition=2015"); } else { diff --git a/src/tools/miri/rust-version b/src/tools/miri/rust-version index 02b0dd16f91..3bef3be2a53 100644 --- a/src/tools/miri/rust-version +++ b/src/tools/miri/rust-version @@ -1 +1 @@ -d4096e0412ac5de785d739a0aa2b1c1c7b9d3b7d +33a2c2487ac5d9927830ea4c1844335c6b9f77db diff --git a/src/tools/miri/src/borrow_tracker/mod.rs b/src/tools/miri/src/borrow_tracker/mod.rs index faa23fd2620..fcfa8f64570 100644 --- a/src/tools/miri/src/borrow_tracker/mod.rs +++ b/src/tools/miri/src/borrow_tracker/mod.rs @@ -74,7 +74,7 @@ pub struct FrameState { impl VisitTags for FrameState { fn visit_tags(&self, _visit: &mut dyn FnMut(BorTag)) { - // `protected_tags` are fine to GC. + // `protected_tags` are already recorded by `GlobalStateInner`. } } @@ -108,9 +108,12 @@ pub struct GlobalStateInner { } impl VisitTags for GlobalStateInner { - fn visit_tags(&self, _visit: &mut dyn FnMut(BorTag)) { - // The only candidate is base_ptr_tags, and that does not need visiting since we don't ever - // GC the bottommost tag. + fn visit_tags(&self, visit: &mut dyn FnMut(BorTag)) { + for &tag in self.protected_tags.keys() { + visit(tag); + } + // The only other candidate is base_ptr_tags, and that does not need visiting since we don't ever + // GC the bottommost/root tag. } } @@ -302,12 +305,12 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { } } - fn retag_return_place(&mut self) -> InterpResult<'tcx> { + fn protect_place(&mut self, place: &MPlaceTy<'tcx, Provenance>) -> InterpResult<'tcx> { let this = self.eval_context_mut(); let method = this.machine.borrow_tracker.as_ref().unwrap().borrow().borrow_tracker_method; match method { - BorrowTrackerMethod::StackedBorrows => this.sb_retag_return_place(), - BorrowTrackerMethod::TreeBorrows => this.tb_retag_return_place(), + BorrowTrackerMethod::StackedBorrows => this.sb_protect_place(place), + BorrowTrackerMethod::TreeBorrows => this.tb_protect_place(place), } } diff --git a/src/tools/miri/src/borrow_tracker/stacked_borrows/diagnostics.rs b/src/tools/miri/src/borrow_tracker/stacked_borrows/diagnostics.rs index de307a3c5f5..5ec8d80fb32 100644 --- a/src/tools/miri/src/borrow_tracker/stacked_borrows/diagnostics.rs +++ b/src/tools/miri/src/borrow_tracker/stacked_borrows/diagnostics.rs @@ -189,7 +189,7 @@ struct RetagOp { #[derive(Debug, Clone, Copy, PartialEq)] pub enum RetagCause { Normal, - FnReturnPlace, + InPlaceFnPassing, FnEntry, TwoPhase, } @@ -501,7 +501,7 @@ impl RetagCause { match self { RetagCause::Normal => "retag", RetagCause::FnEntry => "function-entry retag", - RetagCause::FnReturnPlace => "return-place retag", + RetagCause::InPlaceFnPassing => "in-place function argument/return passing protection", RetagCause::TwoPhase => "two-phase retag", } .to_string() diff --git a/src/tools/miri/src/borrow_tracker/stacked_borrows/mod.rs b/src/tools/miri/src/borrow_tracker/stacked_borrows/mod.rs index ca0f69450c9..15a7d72edf1 100644 --- a/src/tools/miri/src/borrow_tracker/stacked_borrows/mod.rs +++ b/src/tools/miri/src/borrow_tracker/stacked_borrows/mod.rs @@ -994,35 +994,25 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { } } - /// After a stack frame got pushed, retag the return place so that we are sure - /// it does not alias with anything. + /// Protect a place so that it cannot be used any more for the duration of the current function + /// call. /// - /// This is a HACK because there is nothing in MIR that would make the retag - /// explicit. Also see <https://github.com/rust-lang/rust/issues/71117>. - fn sb_retag_return_place(&mut self) -> InterpResult<'tcx> { + /// This is used to ensure soundness of in-place function argument/return passing. + fn sb_protect_place(&mut self, place: &MPlaceTy<'tcx, Provenance>) -> InterpResult<'tcx> { let this = self.eval_context_mut(); - let return_place = &this.frame().return_place; - if return_place.layout.is_zst() { - // There may not be any memory here, nothing to do. - return Ok(()); - } - // We need this to be in-memory to use tagged pointers. - let return_place = this.force_allocation(&return_place.clone())?; - // We have to turn the place into a pointer to use the existing code. + // We have to turn the place into a pointer to use the usual retagging logic. // (The pointer type does not matter, so we use a raw pointer.) - let ptr_layout = this.layout_of(Ty::new_mut_ptr(this.tcx.tcx, return_place.layout.ty))?; - let val = ImmTy::from_immediate(return_place.to_ref(this), ptr_layout); - // Reborrow it. With protection! That is part of the point. + let ptr_layout = this.layout_of(Ty::new_mut_ptr(this.tcx.tcx, place.layout.ty))?; + let ptr = ImmTy::from_immediate(place.to_ref(this), ptr_layout); + // Reborrow it. With protection! That is the entire point. let new_perm = NewPermission::Uniform { perm: Permission::Unique, access: Some(AccessKind::Write), protector: Some(ProtectorKind::StrongProtector), }; - let val = this.sb_retag_reference(&val, new_perm, RetagCause::FnReturnPlace)?; - // And use reborrowed pointer for return place. - let return_place = this.ref_to_mplace(&val)?; - this.frame_mut().return_place = return_place.into(); + let _new_ptr = this.sb_retag_reference(&ptr, new_perm, RetagCause::InPlaceFnPassing)?; + // We just throw away `new_ptr`, so nobody can access this memory while it is protected. Ok(()) } diff --git a/src/tools/miri/src/borrow_tracker/tree_borrows/mod.rs b/src/tools/miri/src/borrow_tracker/tree_borrows/mod.rs index e134b739888..2afd45829bd 100644 --- a/src/tools/miri/src/borrow_tracker/tree_borrows/mod.rs +++ b/src/tools/miri/src/borrow_tracker/tree_borrows/mod.rs @@ -178,7 +178,7 @@ trait EvalContextPrivExt<'mir: 'ecx, 'tcx: 'mir, 'ecx>: crate::MiriInterpCxExt<' &mut self, place: &MPlaceTy<'tcx, Provenance>, // parent tag extracted from here ptr_size: Size, - new_perm: Option<NewPermission>, + new_perm: NewPermission, new_tag: BorTag, ) -> InterpResult<'tcx, Option<(AllocId, BorTag)>> { let this = self.eval_context_mut(); @@ -256,10 +256,6 @@ trait EvalContextPrivExt<'mir: 'ecx, 'tcx: 'mir, 'ecx>: crate::MiriInterpCxExt<' ptr_size.bytes() ); - let Some(new_perm) = new_perm else { - return Ok(Some((alloc_id, orig_tag))); - }; - if let Some(protect) = new_perm.protector { // We register the protection in two different places. // This makes creating a protector slower, but checking whether a tag @@ -305,7 +301,7 @@ trait EvalContextPrivExt<'mir: 'ecx, 'tcx: 'mir, 'ecx>: crate::MiriInterpCxExt<' fn tb_retag_reference( &mut self, val: &ImmTy<'tcx, Provenance>, - new_perm: Option<NewPermission>, + new_perm: NewPermission, ) -> InterpResult<'tcx, ImmTy<'tcx, Provenance>> { let this = self.eval_context_mut(); // We want a place for where the ptr *points to*, so we get one. @@ -317,7 +313,7 @@ trait EvalContextPrivExt<'mir: 'ecx, 'tcx: 'mir, 'ecx>: crate::MiriInterpCxExt<' // - if the pointer is not reborrowed (raw pointer) or if `zero_size` is set // then we override the size to do a zero-length reborrow. let reborrow_size = match new_perm { - Some(NewPermission { zero_size: false, .. }) => + NewPermission { zero_size: false, .. } => this.size_and_align_of_mplace(&place)? .map(|(size, _)| size) .unwrap_or(place.layout.size), @@ -374,7 +370,11 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { NewPermission::from_ref_ty(pointee, mutability, kind, this), _ => None, }; - this.tb_retag_reference(val, new_perm) + if let Some(new_perm) = new_perm { + this.tb_retag_reference(val, new_perm) + } else { + Ok(val.clone()) + } } /// Retag all pointers that are stored in this place. @@ -405,9 +405,11 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { place: &PlaceTy<'tcx, Provenance>, new_perm: Option<NewPermission>, ) -> InterpResult<'tcx> { - let val = self.ecx.read_immediate(&self.ecx.place_to_op(place)?)?; - let val = self.ecx.tb_retag_reference(&val, new_perm)?; - self.ecx.write_immediate(*val, place)?; + if let Some(new_perm) = new_perm { + let val = self.ecx.read_immediate(&self.ecx.place_to_op(place)?)?; + let val = self.ecx.tb_retag_reference(&val, new_perm)?; + self.ecx.write_immediate(*val, place)?; + } Ok(()) } } @@ -493,37 +495,25 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { } } - /// After a stack frame got pushed, retag the return place so that we are sure - /// it does not alias with anything. + /// Protect a place so that it cannot be used any more for the duration of the current function + /// call. /// - /// This is a HACK because there is nothing in MIR that would make the retag - /// explicit. Also see <https://github.com/rust-lang/rust/issues/71117>. - fn tb_retag_return_place(&mut self) -> InterpResult<'tcx> { + /// This is used to ensure soundness of in-place function argument/return passing. + fn tb_protect_place(&mut self, place: &MPlaceTy<'tcx, Provenance>) -> InterpResult<'tcx> { let this = self.eval_context_mut(); - //this.debug_hint_location(); - let return_place = &this.frame().return_place; - if return_place.layout.is_zst() { - // There may not be any memory here, nothing to do. - return Ok(()); - } - // We need this to be in-memory to use tagged pointers. - let return_place = this.force_allocation(&return_place.clone())?; - // We have to turn the place into a pointer to use the existing code. + // We have to turn the place into a pointer to use the usual retagging logic. // (The pointer type does not matter, so we use a raw pointer.) - let ptr_layout = this.layout_of(Ty::new_mut_ptr(this.tcx.tcx, return_place.layout.ty))?; - let val = ImmTy::from_immediate(return_place.to_ref(this), ptr_layout); - // Reborrow it. With protection! That is part of the point. - // FIXME: do we truly want a 2phase borrow here? - let new_perm = Some(NewPermission { - initial_state: Permission::new_unique_2phase(/*freeze*/ false), + let ptr_layout = this.layout_of(Ty::new_mut_ptr(this.tcx.tcx, place.layout.ty))?; + let ptr = ImmTy::from_immediate(place.to_ref(this), ptr_layout); + // Reborrow it. With protection! That is the entire point. + let new_perm = NewPermission { + initial_state: Permission::new_active(), zero_size: false, protector: Some(ProtectorKind::StrongProtector), - }); - let val = this.tb_retag_reference(&val, new_perm)?; - // And use reborrowed pointer for return place. - let return_place = this.ref_to_mplace(&val)?; - this.frame_mut().return_place = return_place.into(); + }; + let _new_ptr = this.tb_retag_reference(&ptr, new_perm)?; + // We just throw away `new_ptr`, so nobody can access this memory while it is protected. Ok(()) } diff --git a/src/tools/miri/src/borrow_tracker/tree_borrows/perms.rs b/src/tools/miri/src/borrow_tracker/tree_borrows/perms.rs index 6b1e722b65e..362070f1857 100644 --- a/src/tools/miri/src/borrow_tracker/tree_borrows/perms.rs +++ b/src/tools/miri/src/borrow_tracker/tree_borrows/perms.rs @@ -138,6 +138,11 @@ impl Permission { Self { inner: Reserved { ty_is_freeze } } } + /// Default initial permission for return place. + pub fn new_active() -> Self { + Self { inner: Active } + } + /// Default initial permission of a reborrowed shared reference pub fn new_frozen() -> Self { Self { inner: Frozen } diff --git a/src/tools/miri/src/eval.rs b/src/tools/miri/src/eval.rs index aba7dd5a9fe..ed3d741db1c 100644 --- a/src/tools/miri/src/eval.rs +++ b/src/tools/miri/src/eval.rs @@ -380,7 +380,7 @@ pub fn create_ecx<'mir, 'tcx: 'mir>( tcx, ty::ParamEnv::reveal_all(), start_id, - tcx.mk_substs(&[ty::subst::GenericArg::from(main_ret_ty)]), + tcx.mk_args(&[ty::GenericArg::from(main_ret_ty)]), ) .unwrap() .unwrap(); diff --git a/src/tools/miri/src/lib.rs b/src/tools/miri/src/lib.rs index 7e92dc7a0c7..5327c2f24e0 100644 --- a/src/tools/miri/src/lib.rs +++ b/src/tools/miri/src/lib.rs @@ -43,15 +43,17 @@ // Needed for rustdoc from bootstrap (with `-Znormalize-docs`). #![recursion_limit = "256"] +extern crate either; // the one from rustc + extern crate rustc_apfloat; extern crate rustc_ast; -extern crate rustc_errors; -#[macro_use] -extern crate rustc_middle; extern crate rustc_const_eval; extern crate rustc_data_structures; +extern crate rustc_errors; extern crate rustc_hir; extern crate rustc_index; +#[macro_use] +extern crate rustc_middle; extern crate rustc_session; extern crate rustc_span; extern crate rustc_target; diff --git a/src/tools/miri/src/machine.rs b/src/tools/miri/src/machine.rs index ac2bad22119..a8f89d56f6d 100644 --- a/src/tools/miri/src/machine.rs +++ b/src/tools/miri/src/machine.rs @@ -7,6 +7,7 @@ use std::fmt; use std::path::Path; use std::process; +use either::Either; use rand::rngs::StdRng; use rand::SeedableRng; @@ -533,7 +534,7 @@ impl<'mir, 'tcx> MiriMachine<'mir, 'tcx> { let target = &tcx.sess.target; match target.arch.as_ref() { "wasm32" | "wasm64" => 64 * 1024, // https://webassembly.github.io/spec/core/exec/runtime.html#memory-instances - "aarch64" => + "aarch64" => { if target.options.vendor.as_ref() == "apple" { // No "definitive" source, but see: // https://www.wwdcnotes.com/notes/wwdc20/10214/ @@ -541,7 +542,8 @@ impl<'mir, 'tcx> MiriMachine<'mir, 'tcx> { 16 * 1024 } else { 4 * 1024 - }, + } + } _ => 4 * 1024, } }; @@ -892,7 +894,7 @@ impl<'mir, 'tcx> Machine<'mir, 'tcx> for MiriMachine<'mir, 'tcx> { ecx: &mut MiriInterpCx<'mir, 'tcx>, instance: ty::Instance<'tcx>, abi: Abi, - args: &[OpTy<'tcx, Provenance>], + args: &[FnArg<'tcx, Provenance>], dest: &PlaceTy<'tcx, Provenance>, ret: Option<mir::BasicBlock>, unwind: mir::UnwindAction, @@ -905,12 +907,13 @@ impl<'mir, 'tcx> Machine<'mir, 'tcx> for MiriMachine<'mir, 'tcx> { ecx: &mut MiriInterpCx<'mir, 'tcx>, fn_val: Dlsym, abi: Abi, - args: &[OpTy<'tcx, Provenance>], + args: &[FnArg<'tcx, Provenance>], dest: &PlaceTy<'tcx, Provenance>, ret: Option<mir::BasicBlock>, _unwind: mir::UnwindAction, ) -> InterpResult<'tcx> { - ecx.call_dlsym(fn_val, abi, args, dest, ret) + let args = ecx.copy_fn_args(args)?; // FIXME: Should `InPlace` arguments be reset to uninit? + ecx.call_dlsym(fn_val, abi, &args, dest, ret) } #[inline(always)] @@ -969,7 +972,7 @@ impl<'mir, 'tcx> Machine<'mir, 'tcx> for MiriMachine<'mir, 'tcx> { panic!("extern_statics cannot contain wildcards") }; let (shim_size, shim_align, _kind) = ecx.get_alloc_info(alloc_id); - let def_ty = ecx.tcx.type_of(def_id).subst_identity(); + let def_ty = ecx.tcx.type_of(def_id).instantiate_identity(); let extern_decl_layout = ecx.tcx.layout_of(ty::ParamEnv::empty().and(def_ty)).unwrap(); if extern_decl_layout.size != shim_size || extern_decl_layout.align.abi != shim_align { throw_unsup_format!( @@ -1206,6 +1209,25 @@ impl<'mir, 'tcx> Machine<'mir, 'tcx> for MiriMachine<'mir, 'tcx> { Ok(()) } + fn protect_in_place_function_argument( + ecx: &mut InterpCx<'mir, 'tcx, Self>, + place: &PlaceTy<'tcx, Provenance>, + ) -> InterpResult<'tcx> { + // We do need to write `uninit` so that even after the call ends, the former contents of + // this place cannot be observed any more. + ecx.write_uninit(place)?; + // If we have a borrow tracker, we also have it set up protection so that all reads *and + // writes* during this call are insta-UB. + if ecx.machine.borrow_tracker.is_some() { + if let Either::Left(place) = place.as_mplace_or_local() { + ecx.protect_place(&place)?; + } else { + // Locals that don't have their address taken are as protected as they can ever be. + } + } + Ok(()) + } + #[inline(always)] fn init_frame_extra( ecx: &mut InterpCx<'mir, 'tcx, Self>, @@ -1288,8 +1310,17 @@ impl<'mir, 'tcx> Machine<'mir, 'tcx> for MiriMachine<'mir, 'tcx> { let stack_len = ecx.active_thread_stack().len(); ecx.active_thread_mut().set_top_user_relevant_frame(stack_len - 1); } - if ecx.machine.borrow_tracker.is_some() { - ecx.retag_return_place()?; + Ok(()) + } + + fn before_stack_pop( + ecx: &InterpCx<'mir, 'tcx, Self>, + frame: &Frame<'mir, 'tcx, Self::Provenance, Self::FrameExtra>, + ) -> InterpResult<'tcx> { + // We want this *before* the return value copy, because the return place itself is protected + // until we do `end_call` here. + if let Some(borrow_tracker) = &ecx.machine.borrow_tracker { + borrow_tracker.borrow_mut().end_call(&frame.extra); } Ok(()) } @@ -1308,9 +1339,6 @@ impl<'mir, 'tcx> Machine<'mir, 'tcx> for MiriMachine<'mir, 'tcx> { ecx.active_thread_mut().recompute_top_user_relevant_frame(); } let timing = frame.extra.timing.take(); - if let Some(borrow_tracker) = &ecx.machine.borrow_tracker { - borrow_tracker.borrow_mut().end_call(&frame.extra); - } let res = ecx.handle_stack_pop_unwind(frame.extra, unwinding); if let Some(profiler) = ecx.machine.profiler.as_ref() { profiler.finish_recording_interval_event(timing.unwrap()); diff --git a/src/tools/miri/src/shims/mod.rs b/src/tools/miri/src/shims/mod.rs index a423a0786b7..1027b24e301 100644 --- a/src/tools/miri/src/shims/mod.rs +++ b/src/tools/miri/src/shims/mod.rs @@ -31,7 +31,7 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { &mut self, instance: ty::Instance<'tcx>, abi: Abi, - args: &[OpTy<'tcx, Provenance>], + args: &[FnArg<'tcx, Provenance>], dest: &PlaceTy<'tcx, Provenance>, ret: Option<mir::BasicBlock>, unwind: mir::UnwindAction, @@ -41,7 +41,8 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { // There are some more lang items we want to hook that CTFE does not hook (yet). if this.tcx.lang_items().align_offset_fn() == Some(instance.def.def_id()) { - let [ptr, align] = check_arg_count(args)?; + let args = this.copy_fn_args(args)?; + let [ptr, align] = check_arg_count(&args)?; if this.align_offset(ptr, align, dest, ret, unwind)? { return Ok(None); } @@ -55,7 +56,8 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { // to run extra MIR), and Ok(Some(body)) if we found MIR to run for the // foreign function // Any needed call to `goto_block` will be performed by `emulate_foreign_item`. - return this.emulate_foreign_item(instance.def_id(), abi, args, dest, ret, unwind); + let args = this.copy_fn_args(args)?; // FIXME: Should `InPlace` arguments be reset to uninit? + return this.emulate_foreign_item(instance.def_id(), abi, &args, dest, ret, unwind); } // Otherwise, load the MIR. diff --git a/src/tools/miri/tests/fail/box-cell-alias.stderr b/src/tools/miri/tests/fail/box-cell-alias.stderr index fc946d6d39b..8c68261aaf7 100644 --- a/src/tools/miri/tests/fail/box-cell-alias.stderr +++ b/src/tools/miri/tests/fail/box-cell-alias.stderr @@ -2,7 +2,7 @@ error: Undefined Behavior: trying to retag from <TAG> for SharedReadWrite permis --> $DIR/box-cell-alias.rs:LL:CC | LL | unsafe { (*ptr).set(20) }; - | ^^^^^^^^^^^^^^ + | ^^^^^^ | | | trying to retag from <TAG> for SharedReadWrite permission at ALLOC[0x0], but that tag does not exist in the borrow stack for this location | this error occurs as part of retag at ALLOC[0x0..0x1] diff --git a/src/tools/miri/tests/fail/dangling_pointers/dangling_zst_deref.rs b/src/tools/miri/tests/fail/dangling_pointers/dangling_zst_deref.rs index 534d7d5f42f..e749eb896e2 100644 --- a/src/tools/miri/tests/fail/dangling_pointers/dangling_zst_deref.rs +++ b/src/tools/miri/tests/fail/dangling_pointers/dangling_zst_deref.rs @@ -1,6 +1,5 @@ // Make sure we find these even with many checks disabled. -// Some optimizations remove ZST accesses, thus masking this UB. -//@compile-flags: -Zmir-opt-level=0 -Zmiri-disable-alignment-check -Zmiri-disable-stacked-borrows -Zmiri-disable-validation +//@compile-flags: -Zmiri-disable-alignment-check -Zmiri-disable-stacked-borrows -Zmiri-disable-validation fn main() { let p = { diff --git a/src/tools/miri/tests/fail/dangling_pointers/dyn_size.rs b/src/tools/miri/tests/fail/dangling_pointers/dyn_size.rs index 54f353ebebe..87ca8a6077c 100644 --- a/src/tools/miri/tests/fail/dangling_pointers/dyn_size.rs +++ b/src/tools/miri/tests/fail/dangling_pointers/dyn_size.rs @@ -1,5 +1,5 @@ -// should find the bug even without these, but gets masked by optimizations -//@compile-flags: -Zmiri-disable-validation -Zmiri-disable-stacked-borrows -Zmir-opt-level=0 +// should find the bug even without these +//@compile-flags: -Zmiri-disable-validation -Zmiri-disable-stacked-borrows struct SliceWithHead(u8, [u8]); diff --git a/src/tools/miri/tests/fail/dangling_pointers/maybe_null_pointer_deref_zst.rs b/src/tools/miri/tests/fail/dangling_pointers/maybe_null_pointer_deref_zst.rs index a48a3189db2..73d0b120680 100644 --- a/src/tools/miri/tests/fail/dangling_pointers/maybe_null_pointer_deref_zst.rs +++ b/src/tools/miri/tests/fail/dangling_pointers/maybe_null_pointer_deref_zst.rs @@ -1,6 +1,3 @@ -// Some optimizations remove ZST accesses, thus masking this UB. -//@compile-flags: -Zmir-opt-level=0 - fn main() { // This pointer *could* be NULL so we cannot load from it, not even at ZST let ptr = (&0u8 as *const u8).wrapping_sub(0x800) as *const (); diff --git a/src/tools/miri/tests/fail/dangling_pointers/maybe_null_pointer_write_zst.rs b/src/tools/miri/tests/fail/dangling_pointers/maybe_null_pointer_write_zst.rs index 449c65d218a..5537207ae42 100644 --- a/src/tools/miri/tests/fail/dangling_pointers/maybe_null_pointer_write_zst.rs +++ b/src/tools/miri/tests/fail/dangling_pointers/maybe_null_pointer_write_zst.rs @@ -1,6 +1,3 @@ -// Some optimizations remove ZST accesses, thus masking this UB. -//@compile-flags: -Zmir-opt-level=0 - fn main() { // This pointer *could* be NULL so we cannot load from it, not even at ZST. // Not using the () type here, as writes of that type do not even have MIR generated. diff --git a/src/tools/miri/tests/fail/dangling_pointers/null_pointer_deref_zst.rs b/src/tools/miri/tests/fail/dangling_pointers/null_pointer_deref_zst.rs index d6a607c61cb..4cb805db095 100644 --- a/src/tools/miri/tests/fail/dangling_pointers/null_pointer_deref_zst.rs +++ b/src/tools/miri/tests/fail/dangling_pointers/null_pointer_deref_zst.rs @@ -1,6 +1,3 @@ -// Some optimizations remove ZST accesses, thus masking this UB. -//@compile-flags: -Zmir-opt-level=0 - #[allow(deref_nullptr)] fn main() { let x: () = unsafe { *std::ptr::null() }; //~ ERROR: dereferencing pointer failed: null pointer is a dangling pointer diff --git a/src/tools/miri/tests/fail/dangling_pointers/null_pointer_write_zst.rs b/src/tools/miri/tests/fail/dangling_pointers/null_pointer_write_zst.rs index 21344208130..ec34c631a46 100644 --- a/src/tools/miri/tests/fail/dangling_pointers/null_pointer_write_zst.rs +++ b/src/tools/miri/tests/fail/dangling_pointers/null_pointer_write_zst.rs @@ -1,6 +1,3 @@ -// Some optimizations remove ZST accesses, thus masking this UB. -//@compile-flags: -Zmir-opt-level=0 - #[allow(deref_nullptr)] fn main() { // Not using the () type here, as writes of that type do not even have MIR generated. diff --git a/src/tools/miri/tests/fail/dangling_pointers/stack_temporary.rs b/src/tools/miri/tests/fail/dangling_pointers/stack_temporary.rs index 1373773f68d..c193d5fe0b3 100644 --- a/src/tools/miri/tests/fail/dangling_pointers/stack_temporary.rs +++ b/src/tools/miri/tests/fail/dangling_pointers/stack_temporary.rs @@ -1,5 +1,5 @@ -// This should fail even without validation, but some MIR opts mask the error -//@compile-flags: -Zmiri-disable-validation -Zmir-opt-level=0 +// This should fail even without validation +//@compile-flags: -Zmiri-disable-validation unsafe fn make_ref<'a>(x: *mut i32) -> &'a mut i32 { &mut *x diff --git a/src/tools/miri/tests/fail/dangling_pointers/storage_dead_dangling.rs b/src/tools/miri/tests/fail/dangling_pointers/storage_dead_dangling.rs index 366930a831c..f9983f48c61 100644 --- a/src/tools/miri/tests/fail/dangling_pointers/storage_dead_dangling.rs +++ b/src/tools/miri/tests/fail/dangling_pointers/storage_dead_dangling.rs @@ -1,5 +1,5 @@ -// This should fail even without validation, but some MIR opts mask the error -//@compile-flags: -Zmiri-disable-validation -Zmir-opt-level=0 -Zmiri-permissive-provenance +// This should fail even without validation +//@compile-flags: -Zmiri-disable-validation -Zmiri-permissive-provenance static mut LEAK: usize = 0; diff --git a/src/tools/miri/tests/fail/data_race/read_write_race_stack.rs b/src/tools/miri/tests/fail/data_race/read_write_race_stack.rs index 40224ced12d..c3e5c401d87 100644 --- a/src/tools/miri/tests/fail/data_race/read_write_race_stack.rs +++ b/src/tools/miri/tests/fail/data_race/read_write_race_stack.rs @@ -1,7 +1,4 @@ -//@compile-flags: -Zmir-opt-level=0 -Zmiri-disable-weak-memory-emulation -Zmiri-preemption-rate=0 -Zmiri-disable-stacked-borrows - -// Note: mir-opt-level set to 0 to prevent the read of stack_var in thread 1 -// from being optimized away and preventing the detection of the data-race. +//@compile-flags: -Zmiri-disable-weak-memory-emulation -Zmiri-preemption-rate=0 -Zmiri-disable-stacked-borrows use std::ptr::null_mut; use std::sync::atomic::{AtomicPtr, Ordering}; diff --git a/src/tools/miri/tests/fail/erroneous_const.rs b/src/tools/miri/tests/fail/erroneous_const.rs index d37837c7193..65f7aafc3cc 100644 --- a/src/tools/miri/tests/fail/erroneous_const.rs +++ b/src/tools/miri/tests/fail/erroneous_const.rs @@ -1,7 +1,5 @@ //! Make sure we detect erroneous constants post-monomorphization even when they are unused. //! (https://github.com/rust-lang/miri/issues/1382) -// Inlining changes the error location -//@compile-flags: -Zmir-opt-level=0 #![feature(never_type)] struct PrintName<T>(T); diff --git a/src/tools/miri/tests/fail/function_calls/arg_inplace_mutate.rs b/src/tools/miri/tests/fail/function_calls/arg_inplace_mutate.rs new file mode 100644 index 00000000000..625a8bda8af --- /dev/null +++ b/src/tools/miri/tests/fail/function_calls/arg_inplace_mutate.rs @@ -0,0 +1,34 @@ +//@revisions: stack tree +//@[tree]compile-flags: -Zmiri-tree-borrows +#![feature(custom_mir, core_intrinsics)] +use std::intrinsics::mir::*; + +pub struct S(i32); + +#[custom_mir(dialect = "runtime", phase = "optimized")] +fn main() { + mir! { + let unit: (); + { + let non_copy = S(42); + let ptr = std::ptr::addr_of_mut!(non_copy); + // Inside `callee`, the first argument and `*ptr` are basically + // aliasing places! + Call(unit, after_call, callee(Move(*ptr), ptr)) + } + after_call = { + Return() + } + + } +} + +pub fn callee(x: S, ptr: *mut S) { + // With the setup above, if `x` is indeed moved in + // (i.e. we actually just get a pointer to the underlying storage), + // then writing to `ptr` will change the value stored in `x`! + unsafe { ptr.write(S(0)) }; + //~[stack]^ ERROR: not granting access + //~[tree]| ERROR: /write access .* forbidden/ + assert_eq!(x.0, 42); +} diff --git a/src/tools/miri/tests/fail/function_calls/arg_inplace_mutate.stack.stderr b/src/tools/miri/tests/fail/function_calls/arg_inplace_mutate.stack.stderr new file mode 100644 index 00000000000..471dc1dd6dd --- /dev/null +++ b/src/tools/miri/tests/fail/function_calls/arg_inplace_mutate.stack.stderr @@ -0,0 +1,37 @@ +error: Undefined Behavior: not granting access to tag <TAG> because that would remove [Unique for <TAG>] which is strongly protected because it is an argument of call ID + --> $DIR/arg_inplace_mutate.rs:LL:CC + | +LL | unsafe { ptr.write(S(0)) }; + | ^^^^^^^^^^^^^^^ not granting access to tag <TAG> because that would remove [Unique for <TAG>] which is strongly protected because it is an argument of call ID + | + = help: this indicates a potential bug in the program: it performed an invalid operation, but the Stacked Borrows rules it violated are still experimental + = help: see https://github.com/rust-lang/unsafe-code-guidelines/blob/master/wip/stacked-borrows.md for further information +help: <TAG> was created by a SharedReadWrite retag at offsets [0x0..0x4] + --> $DIR/arg_inplace_mutate.rs:LL:CC + | +LL | / mir! { +LL | | let unit: (); +LL | | { +LL | | let non_copy = S(42); +... | +LL | | +LL | | } + | |_____^ +help: <TAG> is this argument + --> $DIR/arg_inplace_mutate.rs:LL:CC + | +LL | unsafe { ptr.write(S(0)) }; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: BACKTRACE (of the first span): + = note: inside `callee` at $DIR/arg_inplace_mutate.rs:LL:CC +note: inside `main` + --> $DIR/arg_inplace_mutate.rs:LL:CC + | +LL | Call(unit, after_call, callee(Move(*ptr), ptr)) + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: this error originates in the macro `::core::intrinsics::mir::__internal_remove_let` which comes from the expansion of the macro `mir` (in Nightly builds, run with -Z macro-backtrace for more info) + +note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace + +error: aborting due to previous error + diff --git a/src/tools/miri/tests/fail/function_calls/arg_inplace_mutate.tree.stderr b/src/tools/miri/tests/fail/function_calls/arg_inplace_mutate.tree.stderr new file mode 100644 index 00000000000..35c02cc2ebd --- /dev/null +++ b/src/tools/miri/tests/fail/function_calls/arg_inplace_mutate.tree.stderr @@ -0,0 +1,39 @@ +error: Undefined Behavior: write access through <TAG> (root of the allocation) is forbidden + --> $DIR/arg_inplace_mutate.rs:LL:CC + | +LL | unsafe { ptr.write(S(0)) }; + | ^^^^^^^^^^^^^^^ write access through <TAG> (root of the allocation) is forbidden + | + = help: this indicates a potential bug in the program: it performed an invalid operation, but the Tree Borrows rules it violated are still experimental + = help: the accessed tag <TAG> (root of the allocation) is foreign to the protected tag <TAG> (i.e., it is not a child) + = help: this foreign write access would cause the protected tag <TAG> to transition from Active to Disabled + = help: this transition would be a loss of read and write permissions, which is not allowed for protected tags +help: the accessed tag <TAG> was created here + --> $DIR/arg_inplace_mutate.rs:LL:CC + | +LL | / mir! { +LL | | let unit: (); +LL | | { +LL | | let non_copy = S(42); +... | +LL | | +LL | | } + | |_____^ +help: the protected tag <TAG> was created here, in the initial state Active + --> $DIR/arg_inplace_mutate.rs:LL:CC + | +LL | unsafe { ptr.write(S(0)) }; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: BACKTRACE (of the first span): + = note: inside `callee` at $DIR/arg_inplace_mutate.rs:LL:CC +note: inside `main` + --> $DIR/arg_inplace_mutate.rs:LL:CC + | +LL | Call(unit, after_call, callee(Move(*ptr), ptr)) + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: this error originates in the macro `::core::intrinsics::mir::__internal_remove_let` which comes from the expansion of the macro `mir` (in Nightly builds, run with -Z macro-backtrace for more info) + +note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace + +error: aborting due to previous error + diff --git a/src/tools/miri/tests/fail/function_calls/arg_inplace_observe_after.rs b/src/tools/miri/tests/fail/function_calls/arg_inplace_observe_after.rs new file mode 100644 index 00000000000..093b55759fd --- /dev/null +++ b/src/tools/miri/tests/fail/function_calls/arg_inplace_observe_after.rs @@ -0,0 +1,27 @@ +#![feature(custom_mir, core_intrinsics)] +use std::intrinsics::mir::*; + +pub struct S(i32); + +#[custom_mir(dialect = "runtime", phase = "optimized")] +fn main() { + mir! { + let unit: (); + let _observe: i32; + { + let non_copy = S(42); + // This could change `non_copy` in-place + Call(unit, after_call, change_arg(Move(non_copy))) + } + after_call = { + // So now we must not be allowed to observe non-copy again. + _observe = non_copy.0; //~ERROR: uninitialized + Return() + } + + } +} + +pub fn change_arg(mut x: S) { + x.0 = 0; +} diff --git a/src/tools/miri/tests/fail/function_calls/arg_inplace_observe_after.stderr b/src/tools/miri/tests/fail/function_calls/arg_inplace_observe_after.stderr new file mode 100644 index 00000000000..5d9a3af0c8a --- /dev/null +++ b/src/tools/miri/tests/fail/function_calls/arg_inplace_observe_after.stderr @@ -0,0 +1,15 @@ +error: Undefined Behavior: using uninitialized data, but this operation requires initialized memory + --> $DIR/arg_inplace_observe_after.rs:LL:CC + | +LL | _observe = non_copy.0; + | ^^^^^^^^^^^^^^^^^^^^^ using uninitialized data, but this operation requires initialized memory + | + = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior + = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information + = note: BACKTRACE: + = note: inside `main` at $DIR/arg_inplace_observe_after.rs:LL:CC + +note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace + +error: aborting due to previous error + diff --git a/src/tools/miri/tests/fail/function_calls/arg_inplace_observe_during.none.stderr b/src/tools/miri/tests/fail/function_calls/arg_inplace_observe_during.none.stderr new file mode 100644 index 00000000000..baa91484793 --- /dev/null +++ b/src/tools/miri/tests/fail/function_calls/arg_inplace_observe_during.none.stderr @@ -0,0 +1,20 @@ +error: Undefined Behavior: using uninitialized data, but this operation requires initialized memory + --> $DIR/arg_inplace_observe_during.rs:LL:CC + | +LL | unsafe { ptr.read() }; + | ^^^^^^^^^^ using uninitialized data, but this operation requires initialized memory + | + = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior + = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information + = note: BACKTRACE: + = note: inside `change_arg` at $DIR/arg_inplace_observe_during.rs:LL:CC +note: inside `main` + --> $DIR/arg_inplace_observe_during.rs:LL:CC + | +LL | Call(unit, after_call, change_arg(Move(*ptr), ptr)) + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace + +error: aborting due to previous error + diff --git a/src/tools/miri/tests/fail/function_calls/arg_inplace_observe_during.rs b/src/tools/miri/tests/fail/function_calls/arg_inplace_observe_during.rs new file mode 100644 index 00000000000..2e57872db96 --- /dev/null +++ b/src/tools/miri/tests/fail/function_calls/arg_inplace_observe_during.rs @@ -0,0 +1,34 @@ +//@revisions: stack tree none +//@[tree]compile-flags: -Zmiri-tree-borrows +//@[none]compile-flags: -Zmiri-disable-stacked-borrows +#![feature(custom_mir, core_intrinsics)] +use std::intrinsics::mir::*; + +pub struct S(i32); + +#[custom_mir(dialect = "runtime", phase = "optimized")] +fn main() { + mir! { + let unit: (); + { + let non_copy = S(42); + let ptr = std::ptr::addr_of_mut!(non_copy); + // This could change `non_copy` in-place + Call(unit, after_call, change_arg(Move(*ptr), ptr)) + } + after_call = { + Return() + } + + } +} + +pub fn change_arg(mut x: S, ptr: *mut S) { + x.0 = 0; + // If `x` got passed in-place, we'd see the write through `ptr`! + // Make sure we are not allowed to do that read. + unsafe { ptr.read() }; + //~[stack]^ ERROR: not granting access + //~[tree]| ERROR: /read access .* forbidden/ + //~[none]| ERROR: uninitialized +} diff --git a/src/tools/miri/tests/fail/function_calls/arg_inplace_observe_during.stack.stderr b/src/tools/miri/tests/fail/function_calls/arg_inplace_observe_during.stack.stderr new file mode 100644 index 00000000000..a842d3a8044 --- /dev/null +++ b/src/tools/miri/tests/fail/function_calls/arg_inplace_observe_during.stack.stderr @@ -0,0 +1,37 @@ +error: Undefined Behavior: not granting access to tag <TAG> because that would remove [Unique for <TAG>] which is strongly protected because it is an argument of call ID + --> $DIR/arg_inplace_observe_during.rs:LL:CC + | +LL | unsafe { ptr.read() }; + | ^^^^^^^^^^ not granting access to tag <TAG> because that would remove [Unique for <TAG>] which is strongly protected because it is an argument of call ID + | + = help: this indicates a potential bug in the program: it performed an invalid operation, but the Stacked Borrows rules it violated are still experimental + = help: see https://github.com/rust-lang/unsafe-code-guidelines/blob/master/wip/stacked-borrows.md for further information +help: <TAG> was created by a SharedReadWrite retag at offsets [0x0..0x4] + --> $DIR/arg_inplace_observe_during.rs:LL:CC + | +LL | / mir! { +LL | | let unit: (); +LL | | { +LL | | let non_copy = S(42); +... | +LL | | +LL | | } + | |_____^ +help: <TAG> is this argument + --> $DIR/arg_inplace_observe_during.rs:LL:CC + | +LL | x.0 = 0; + | ^^^^^^^ + = note: BACKTRACE (of the first span): + = note: inside `change_arg` at $DIR/arg_inplace_observe_during.rs:LL:CC +note: inside `main` + --> $DIR/arg_inplace_observe_during.rs:LL:CC + | +LL | Call(unit, after_call, change_arg(Move(*ptr), ptr)) + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: this error originates in the macro `::core::intrinsics::mir::__internal_remove_let` which comes from the expansion of the macro `mir` (in Nightly builds, run with -Z macro-backtrace for more info) + +note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace + +error: aborting due to previous error + diff --git a/src/tools/miri/tests/fail/function_calls/arg_inplace_observe_during.tree.stderr b/src/tools/miri/tests/fail/function_calls/arg_inplace_observe_during.tree.stderr new file mode 100644 index 00000000000..cbd76c38f62 --- /dev/null +++ b/src/tools/miri/tests/fail/function_calls/arg_inplace_observe_during.tree.stderr @@ -0,0 +1,39 @@ +error: Undefined Behavior: read access through <TAG> (root of the allocation) is forbidden + --> $DIR/arg_inplace_observe_during.rs:LL:CC + | +LL | unsafe { ptr.read() }; + | ^^^^^^^^^^ read access through <TAG> (root of the allocation) is forbidden + | + = help: this indicates a potential bug in the program: it performed an invalid operation, but the Tree Borrows rules it violated are still experimental + = help: the accessed tag <TAG> (root of the allocation) is foreign to the protected tag <TAG> (i.e., it is not a child) + = help: this foreign read access would cause the protected tag <TAG> to transition from Active to Frozen + = help: this transition would be a loss of write permissions, which is not allowed for protected tags +help: the accessed tag <TAG> was created here + --> $DIR/arg_inplace_observe_during.rs:LL:CC + | +LL | / mir! { +LL | | let unit: (); +LL | | { +LL | | let non_copy = S(42); +... | +LL | | +LL | | } + | |_____^ +help: the protected tag <TAG> was created here, in the initial state Active + --> $DIR/arg_inplace_observe_during.rs:LL:CC + | +LL | x.0 = 0; + | ^^^^^^^ + = note: BACKTRACE (of the first span): + = note: inside `change_arg` at $DIR/arg_inplace_observe_during.rs:LL:CC +note: inside `main` + --> $DIR/arg_inplace_observe_during.rs:LL:CC + | +LL | Call(unit, after_call, change_arg(Move(*ptr), ptr)) + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: this error originates in the macro `::core::intrinsics::mir::__internal_remove_let` which comes from the expansion of the macro `mir` (in Nightly builds, run with -Z macro-backtrace for more info) + +note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace + +error: aborting due to previous error + diff --git a/src/tools/miri/tests/fail/function_calls/return_pointer_aliasing.none.stderr b/src/tools/miri/tests/fail/function_calls/return_pointer_aliasing.none.stderr new file mode 100644 index 00000000000..9d9dfc89f89 --- /dev/null +++ b/src/tools/miri/tests/fail/function_calls/return_pointer_aliasing.none.stderr @@ -0,0 +1,20 @@ +error: Undefined Behavior: using uninitialized data, but this operation requires initialized memory + --> $DIR/return_pointer_aliasing.rs:LL:CC + | +LL | unsafe { ptr.read() }; + | ^^^^^^^^^^ using uninitialized data, but this operation requires initialized memory + | + = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior + = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information + = note: BACKTRACE: + = note: inside `myfun` at $DIR/return_pointer_aliasing.rs:LL:CC +note: inside `main` + --> $DIR/return_pointer_aliasing.rs:LL:CC + | +LL | Call(*ptr, after_call, myfun(ptr)) + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace + +error: aborting due to previous error + diff --git a/src/tools/miri/tests/fail/function_calls/return_pointer_aliasing.rs b/src/tools/miri/tests/fail/function_calls/return_pointer_aliasing.rs new file mode 100644 index 00000000000..829809102fa --- /dev/null +++ b/src/tools/miri/tests/fail/function_calls/return_pointer_aliasing.rs @@ -0,0 +1,34 @@ +//@revisions: stack tree none +//@[tree]compile-flags: -Zmiri-tree-borrows +//@[none]compile-flags: -Zmiri-disable-stacked-borrows +#![feature(raw_ref_op)] +#![feature(core_intrinsics)] +#![feature(custom_mir)] + +use std::intrinsics::mir::*; + +#[custom_mir(dialect = "runtime", phase = "optimized")] +pub fn main() { + mir! { + { + let x = 0; + let ptr = &raw mut x; + // We arrange for `myfun` to have a pointer that aliases + // its return place. Even just reading from that pointer is UB. + Call(*ptr, after_call, myfun(ptr)) + } + + after_call = { + Return() + } + } +} + +fn myfun(ptr: *mut i32) -> i32 { + unsafe { ptr.read() }; + //~[stack]^ ERROR: not granting access + //~[tree]| ERROR: /read access .* forbidden/ + //~[none]| ERROR: uninitialized + // Without an aliasing model, reads are "fine" but at least they return uninit data. + 13 +} diff --git a/src/tools/miri/tests/fail/function_calls/return_pointer_aliasing.stack.stderr b/src/tools/miri/tests/fail/function_calls/return_pointer_aliasing.stack.stderr new file mode 100644 index 00000000000..d486dcb95df --- /dev/null +++ b/src/tools/miri/tests/fail/function_calls/return_pointer_aliasing.stack.stderr @@ -0,0 +1,37 @@ +error: Undefined Behavior: not granting access to tag <TAG> because that would remove [Unique for <TAG>] which is strongly protected because it is an argument of call ID + --> $DIR/return_pointer_aliasing.rs:LL:CC + | +LL | unsafe { ptr.read() }; + | ^^^^^^^^^^ not granting access to tag <TAG> because that would remove [Unique for <TAG>] which is strongly protected because it is an argument of call ID + | + = help: this indicates a potential bug in the program: it performed an invalid operation, but the Stacked Borrows rules it violated are still experimental + = help: see https://github.com/rust-lang/unsafe-code-guidelines/blob/master/wip/stacked-borrows.md for further information +help: <TAG> was created by a SharedReadWrite retag at offsets [0x0..0x4] + --> $DIR/return_pointer_aliasing.rs:LL:CC + | +LL | / mir! { +LL | | { +LL | | let x = 0; +LL | | let ptr = &raw mut x; +... | +LL | | } +LL | | } + | |_____^ +help: <TAG> is this argument + --> $DIR/return_pointer_aliasing.rs:LL:CC + | +LL | unsafe { ptr.read() }; + | ^^^^^^^^^^^^^^^^^^^^^ + = note: BACKTRACE (of the first span): + = note: inside `myfun` at $DIR/return_pointer_aliasing.rs:LL:CC +note: inside `main` + --> $DIR/return_pointer_aliasing.rs:LL:CC + | +LL | Call(*ptr, after_call, myfun(ptr)) + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: this error originates in the macro `::core::intrinsics::mir::__internal_remove_let` which comes from the expansion of the macro `mir` (in Nightly builds, run with -Z macro-backtrace for more info) + +note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace + +error: aborting due to previous error + diff --git a/src/tools/miri/tests/fail/function_calls/return_pointer_aliasing.tree.stderr b/src/tools/miri/tests/fail/function_calls/return_pointer_aliasing.tree.stderr new file mode 100644 index 00000000000..c2c9de3f4ee --- /dev/null +++ b/src/tools/miri/tests/fail/function_calls/return_pointer_aliasing.tree.stderr @@ -0,0 +1,39 @@ +error: Undefined Behavior: read access through <TAG> (root of the allocation) is forbidden + --> $DIR/return_pointer_aliasing.rs:LL:CC + | +LL | unsafe { ptr.read() }; + | ^^^^^^^^^^ read access through <TAG> (root of the allocation) is forbidden + | + = help: this indicates a potential bug in the program: it performed an invalid operation, but the Tree Borrows rules it violated are still experimental + = help: the accessed tag <TAG> (root of the allocation) is foreign to the protected tag <TAG> (i.e., it is not a child) + = help: this foreign read access would cause the protected tag <TAG> to transition from Active to Frozen + = help: this transition would be a loss of write permissions, which is not allowed for protected tags +help: the accessed tag <TAG> was created here + --> $DIR/return_pointer_aliasing.rs:LL:CC + | +LL | / mir! { +LL | | { +LL | | let x = 0; +LL | | let ptr = &raw mut x; +... | +LL | | } +LL | | } + | |_____^ +help: the protected tag <TAG> was created here, in the initial state Active + --> $DIR/return_pointer_aliasing.rs:LL:CC + | +LL | unsafe { ptr.read() }; + | ^^^^^^^^^^^^^^^^^^^^^ + = note: BACKTRACE (of the first span): + = note: inside `myfun` at $DIR/return_pointer_aliasing.rs:LL:CC +note: inside `main` + --> $DIR/return_pointer_aliasing.rs:LL:CC + | +LL | Call(*ptr, after_call, myfun(ptr)) + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + = note: this error originates in the macro `::core::intrinsics::mir::__internal_remove_let` which comes from the expansion of the macro `mir` (in Nightly builds, run with -Z macro-backtrace for more info) + +note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace + +error: aborting due to previous error + diff --git a/src/tools/miri/tests/fail/stacked_borrows/illegal_read7.stderr b/src/tools/miri/tests/fail/stacked_borrows/illegal_read7.stderr index b76446d60f6..1a9d551431c 100644 --- a/src/tools/miri/tests/fail/stacked_borrows/illegal_read7.stderr +++ b/src/tools/miri/tests/fail/stacked_borrows/illegal_read7.stderr @@ -2,7 +2,7 @@ error: Undefined Behavior: trying to retag from <TAG> for SharedReadWrite permis --> $DIR/illegal_read7.rs:LL:CC | LL | let _val = *x.get_mut(); - | ^^^^^^^^^^^ + | ^ | | | trying to retag from <TAG> for SharedReadWrite permission at ALLOC[0x0], but that tag does not exist in the borrow stack for this location | this error occurs as part of two-phase retag at ALLOC[0x0..0x4] diff --git a/src/tools/miri/tests/fail/stacked_borrows/interior_mut1.stderr b/src/tools/miri/tests/fail/stacked_borrows/interior_mut1.stderr index da55e724fd8..ba8977c5674 100644 --- a/src/tools/miri/tests/fail/stacked_borrows/interior_mut1.stderr +++ b/src/tools/miri/tests/fail/stacked_borrows/interior_mut1.stderr @@ -2,7 +2,7 @@ error: Undefined Behavior: trying to retag from <TAG> for SharedReadWrite permis --> $DIR/interior_mut1.rs:LL:CC | LL | let _val = *inner_shr.get(); - | ^^^^^^^^^^^^^^^ + | ^^^^^^^^^ | | | trying to retag from <TAG> for SharedReadWrite permission at ALLOC[0x0], but that tag does not exist in the borrow stack for this location | this error occurs as part of retag at ALLOC[0x0..0x4] diff --git a/src/tools/miri/tests/fail/stacked_borrows/interior_mut2.stderr b/src/tools/miri/tests/fail/stacked_borrows/interior_mut2.stderr index 8c8a96cbbbd..97ebe72bf29 100644 --- a/src/tools/miri/tests/fail/stacked_borrows/interior_mut2.stderr +++ b/src/tools/miri/tests/fail/stacked_borrows/interior_mut2.stderr @@ -2,7 +2,7 @@ error: Undefined Behavior: trying to retag from <TAG> for SharedReadWrite permis --> $DIR/interior_mut2.rs:LL:CC | LL | let _val = *inner_shr.get(); - | ^^^^^^^^^^^^^^^ + | ^^^^^^^^^ | | | trying to retag from <TAG> for SharedReadWrite permission at ALLOC[0x0], but that tag does not exist in the borrow stack for this location | this error occurs as part of retag at ALLOC[0x0..0x4] diff --git a/src/tools/miri/tests/fail/stacked_borrows/shared_rw_borrows_are_weak1.stderr b/src/tools/miri/tests/fail/stacked_borrows/shared_rw_borrows_are_weak1.stderr index 589e1291ba7..10f97180b75 100644 --- a/src/tools/miri/tests/fail/stacked_borrows/shared_rw_borrows_are_weak1.stderr +++ b/src/tools/miri/tests/fail/stacked_borrows/shared_rw_borrows_are_weak1.stderr @@ -2,7 +2,7 @@ error: Undefined Behavior: trying to retag from <TAG> for SharedReadWrite permis --> $DIR/shared_rw_borrows_are_weak1.rs:LL:CC | LL | y.get_mut(); - | ^^^^^^^^^^^ + | ^ | | | trying to retag from <TAG> for SharedReadWrite permission at ALLOC[0x0], but that tag does not exist in the borrow stack for this location | this error occurs as part of two-phase retag at ALLOC[0x0..0x4] diff --git a/src/tools/miri/tests/fail/tree_borrows/fnentry_invalidation.stderr b/src/tools/miri/tests/fail/tree_borrows/fnentry_invalidation.stderr index 227c465b8f0..0f1e7735a0e 100644 --- a/src/tools/miri/tests/fail/tree_borrows/fnentry_invalidation.stderr +++ b/src/tools/miri/tests/fail/tree_borrows/fnentry_invalidation.stderr @@ -21,7 +21,7 @@ help: the accessed tag <TAG> later transitioned to Frozen due to a reborrow (act --> $DIR/fnentry_invalidation.rs:LL:CC | LL | x.do_bad(); - | ^^^^^^^^^^ + | ^ = help: this transition corresponds to a loss of write permissions = note: BACKTRACE (of the first span): = note: inside `main` at $DIR/fnentry_invalidation.rs:LL:CC diff --git a/src/tools/miri/tests/fail/tree_borrows/write-during-2phase.stderr b/src/tools/miri/tests/fail/tree_borrows/write-during-2phase.stderr index ce71468425f..3a82d028704 100644 --- a/src/tools/miri/tests/fail/tree_borrows/write-during-2phase.stderr +++ b/src/tools/miri/tests/fail/tree_borrows/write-during-2phase.stderr @@ -9,15 +9,8 @@ LL | fn add(&mut self, n: u64) -> u64 { help: the accessed tag <TAG> was created here, in the initial state Reserved --> $DIR/write-during-2phase.rs:LL:CC | -LL | let _res = f.add(unsafe { - | ________________^ -LL | | let n = f.0; -LL | | // This is the access at fault, but it's not immediately apparent because -LL | | // the reference that got invalidated is not under a Protector. -LL | | *inner = 42; -LL | | n -LL | | }); - | |______^ +LL | let _res = f.add(unsafe { + | ^ help: the accessed tag <TAG> later transitioned to Disabled due to a foreign write access at offsets [0x0..0x8] --> $DIR/write-during-2phase.rs:LL:CC | diff --git a/src/tools/miri/tests/fail/unaligned_pointers/dyn_alignment.rs b/src/tools/miri/tests/fail/unaligned_pointers/dyn_alignment.rs index 6d31ded75c6..b5a9b2bf18e 100644 --- a/src/tools/miri/tests/fail/unaligned_pointers/dyn_alignment.rs +++ b/src/tools/miri/tests/fail/unaligned_pointers/dyn_alignment.rs @@ -1,5 +1,6 @@ -// should find the bug even without validation and stacked borrows, but gets masked by optimizations -//@compile-flags: -Zmiri-disable-validation -Zmiri-disable-stacked-borrows -Zmir-opt-level=0 -Cdebug-assertions=no +// should find the bug even without, but gets masked by optimizations +//@compile-flags: -Zmiri-disable-stacked-borrows -Cdebug-assertions=no +//@normalize-stderr-test: "but found [0-9]+" -> "but found $$ALIGN" #[repr(align(256))] #[derive(Debug)] @@ -19,6 +20,6 @@ fn main() { (&mut ptr as *mut _ as *mut *const u8).write(&buf as *const _ as *const u8); } // Re-borrow that. This should be UB. - let _ptr = &*ptr; //~ERROR: alignment 256 is required + let _ptr = &*ptr; //~ERROR: required 256 byte alignment } } diff --git a/src/tools/miri/tests/fail/unaligned_pointers/dyn_alignment.stderr b/src/tools/miri/tests/fail/unaligned_pointers/dyn_alignment.stderr index a900b46612b..503721b9551 100644 --- a/src/tools/miri/tests/fail/unaligned_pointers/dyn_alignment.stderr +++ b/src/tools/miri/tests/fail/unaligned_pointers/dyn_alignment.stderr @@ -1,8 +1,8 @@ -error: Undefined Behavior: accessing memory with alignment ALIGN, but alignment ALIGN is required +error: Undefined Behavior: constructing invalid value: encountered an unaligned reference (required 256 byte alignment but found $ALIGN) --> $DIR/dyn_alignment.rs:LL:CC | LL | let _ptr = &*ptr; - | ^^^^^ accessing memory with alignment ALIGN, but alignment ALIGN is required + | ^^^^^ constructing invalid value: encountered an unaligned reference (required 256 byte alignment but found $ALIGN) | = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information diff --git a/src/tools/miri/tests/fail/unaligned_pointers/unaligned_ptr_zst.rs b/src/tools/miri/tests/fail/unaligned_pointers/unaligned_ptr_zst.rs index 04dbe3fd8d4..289536287a9 100644 --- a/src/tools/miri/tests/fail/unaligned_pointers/unaligned_ptr_zst.rs +++ b/src/tools/miri/tests/fail/unaligned_pointers/unaligned_ptr_zst.rs @@ -1,6 +1,5 @@ // This should fail even without validation -// Some optimizations remove ZST accesses, thus masking this UB. -//@compile-flags: -Zmir-opt-level=0 -Zmiri-disable-validation -Cdebug-assertions=no +//@compile-flags: -Zmiri-disable-validation -Cdebug-assertions=no fn main() { // Try many times as this might work by chance. diff --git a/src/tools/miri/tests/fail/validity/nonzero.rs b/src/tools/miri/tests/fail/validity/nonzero.rs index 384c94a5569..7cba90bc15d 100644 --- a/src/tools/miri/tests/fail/validity/nonzero.rs +++ b/src/tools/miri/tests/fail/validity/nonzero.rs @@ -1,5 +1,3 @@ -// gets masked by optimizations -//@compile-flags: -Zmir-opt-level=0 #![feature(rustc_attrs)] #![allow(unused_attributes)] diff --git a/src/tools/miri/tests/fail/zst2.rs b/src/tools/miri/tests/fail/zst2.rs index 82470866f17..1d3e8ea9d00 100644 --- a/src/tools/miri/tests/fail/zst2.rs +++ b/src/tools/miri/tests/fail/zst2.rs @@ -1,6 +1,3 @@ -// Some optimizations remove ZST accesses, thus masking this UB. -//@compile-flags: -Zmir-opt-level=0 - fn main() { // Not using the () type here, as writes of that type do not even have MIR generated. // Also not assigning directly as that's array initialization, not assignment. diff --git a/src/tools/miri/tests/fail/zst3.rs b/src/tools/miri/tests/fail/zst3.rs index a511f38998f..454bef25f22 100644 --- a/src/tools/miri/tests/fail/zst3.rs +++ b/src/tools/miri/tests/fail/zst3.rs @@ -1,6 +1,3 @@ -// Some optimizations remove ZST accesses, thus masking this UB. -//@compile-flags: -Zmir-opt-level=0 - fn main() { // Not using the () type here, as writes of that type do not even have MIR generated. // Also not assigning directly as that's array initialization, not assignment. diff --git a/src/tools/miri/tests/pass/function_calls/return_place_on_heap.rs b/src/tools/miri/tests/pass/function_calls/return_place_on_heap.rs new file mode 100644 index 00000000000..dcfebd0f82b --- /dev/null +++ b/src/tools/miri/tests/pass/function_calls/return_place_on_heap.rs @@ -0,0 +1,25 @@ +#![feature(raw_ref_op)] +#![feature(core_intrinsics)] +#![feature(custom_mir)] + +use std::intrinsics::mir::*; + +// Make sure calls with the return place "on the heap" work. +#[custom_mir(dialect = "runtime", phase = "optimized")] +pub fn main() { + mir! { + { + let x = 0; + let ptr = &raw mut x; + Call(*ptr, after_call, myfun()) + } + + after_call = { + Return() + } + } +} + +fn myfun() -> i32 { + 13 +} diff --git a/src/tools/opt-dist/src/main.rs b/src/tools/opt-dist/src/main.rs index 39fa7e1fb2a..6fc3c3b64a8 100644 --- a/src/tools/opt-dist/src/main.rs +++ b/src/tools/opt-dist/src/main.rs @@ -7,7 +7,10 @@ use crate::tests::run_tests; use crate::timer::Timer; use crate::training::{gather_llvm_bolt_profiles, gather_llvm_profiles, gather_rustc_profiles}; use crate::utils::io::reset_directory; -use crate::utils::{clear_llvm_files, format_env_variables, print_free_disk_space}; +use crate::utils::{ + clear_llvm_files, format_env_variables, print_binary_sizes, print_free_disk_space, + with_log_group, +}; mod environment; mod exec; @@ -27,7 +30,8 @@ fn execute_pipeline( dist_args: Vec<String>, ) -> anyhow::Result<()> { reset_directory(&env.opt_artifacts())?; - env.prepare_rustc_perf()?; + + with_log_group("Building rustc-perf", || env.prepare_rustc_perf())?; // Stage 1: Build PGO instrumented rustc // We use a normal build of LLVM, because gathering PGO profiles for LLVM and `rustc` at the @@ -139,12 +143,17 @@ fn main() -> anyhow::Result<()> { .init(); let mut build_args: Vec<String> = std::env::args().skip(1).collect(); - log::info!("Running optimized build pipeline with args `{}`", build_args.join(" ")); - log::info!("Environment values\n{}", format_env_variables()); + println!("Running optimized build pipeline with args `{}`", build_args.join(" ")); - if let Ok(config) = std::fs::read_to_string("config.toml") { - log::info!("Contents of `config.toml`:\n{config}"); - } + with_log_group("Environment values", || { + println!("Environment values\n{}", format_env_variables()); + }); + + with_log_group("Printing config.toml", || { + if let Ok(config) = std::fs::read_to_string("config.toml") { + println!("Contents of `config.toml`:\n{config}"); + } + }); // Skip components that are not needed for try builds to speed them up if is_try_build() { @@ -170,6 +179,8 @@ fn main() -> anyhow::Result<()> { log::info!("Timer results\n{}", timer.format_stats()); print_free_disk_space()?; + result.context("Optimized build pipeline has failed")?; + print_binary_sizes(env.as_ref())?; - result.context("Optimized build pipeline has failed") + Ok(()) } diff --git a/src/tools/opt-dist/src/training.rs b/src/tools/opt-dist/src/training.rs index 10f4a603695..951bc6f9264 100644 --- a/src/tools/opt-dist/src/training.rs +++ b/src/tools/opt-dist/src/training.rs @@ -1,6 +1,7 @@ use crate::environment::Environment; use crate::exec::{cmd, CmdBuilder}; use crate::utils::io::{count_files, delete_directory}; +use crate::utils::with_log_group; use anyhow::Context; use camino::{Utf8Path, Utf8PathBuf}; use humansize::BINARY; @@ -108,9 +109,11 @@ pub fn gather_llvm_profiles( ) -> anyhow::Result<LlvmPGOProfile> { log::info!("Running benchmarks with PGO instrumented LLVM"); - init_compiler_benchmarks(env, &["Debug", "Opt"], &["Full"], LLVM_PGO_CRATES) - .run() - .context("Cannot gather LLVM PGO profiles")?; + with_log_group("Running benchmarks", || { + init_compiler_benchmarks(env, &["Debug", "Opt"], &["Full"], LLVM_PGO_CRATES) + .run() + .context("Cannot gather LLVM PGO profiles") + })?; let merged_profile = env.opt_artifacts().join("llvm-pgo.profdata"); log::info!("Merging LLVM PGO profiles to {merged_profile}"); @@ -141,10 +144,12 @@ pub fn gather_rustc_profiles( // Here we're profiling the `rustc` frontend, so we also include `Check`. // The benchmark set includes various stress tests that put the frontend under pressure. - init_compiler_benchmarks(env, &["Check", "Debug", "Opt"], &["All"], RUSTC_PGO_CRATES) - .env("LLVM_PROFILE_FILE", profile_template.as_str()) - .run() - .context("Cannot gather rustc PGO profiles")?; + with_log_group("Running benchmarks", || { + init_compiler_benchmarks(env, &["Check", "Debug", "Opt"], &["All"], RUSTC_PGO_CRATES) + .env("LLVM_PROFILE_FILE", profile_template.as_str()) + .run() + .context("Cannot gather rustc PGO profiles") + })?; let merged_profile = env.opt_artifacts().join("rustc-pgo.profdata"); log::info!("Merging Rustc PGO profiles to {merged_profile}"); @@ -164,9 +169,11 @@ pub struct LlvmBoltProfile(pub Utf8PathBuf); pub fn gather_llvm_bolt_profiles(env: &dyn Environment) -> anyhow::Result<LlvmBoltProfile> { log::info!("Running benchmarks with BOLT instrumented LLVM"); - init_compiler_benchmarks(env, &["Check", "Debug", "Opt"], &["Full"], LLVM_BOLT_CRATES) - .run() - .context("Cannot gather LLVM BOLT profiles")?; + with_log_group("Running benchmarks", || { + init_compiler_benchmarks(env, &["Check", "Debug", "Opt"], &["Full"], LLVM_BOLT_CRATES) + .run() + .context("Cannot gather LLVM BOLT profiles") + })?; let merged_profile = env.opt_artifacts().join("bolt.profdata"); let profile_root = Utf8PathBuf::from("/tmp/prof.fdata"); @@ -178,10 +185,12 @@ pub fn gather_llvm_bolt_profiles(env: &dyn Environment) -> anyhow::Result<LlvmBo let mut merge_args = vec!["merge-fdata"]; merge_args.extend(profiles.iter().map(|p| p.to_str().unwrap())); - cmd(&merge_args) - .redirect_output(merged_profile.clone()) - .run() - .context("Cannot merge BOLT profiles")?; + with_log_group("Merging BOLT profiles", || { + cmd(&merge_args) + .redirect_output(merged_profile.clone()) + .run() + .context("Cannot merge BOLT profiles") + })?; log::info!("LLVM BOLT statistics"); log::info!( diff --git a/src/tools/opt-dist/src/utils/io.rs b/src/tools/opt-dist/src/utils/io.rs index 43546e5fcfa..aab078067af 100644 --- a/src/tools/opt-dist/src/utils/io.rs +++ b/src/tools/opt-dist/src/utils/io.rs @@ -1,5 +1,5 @@ use anyhow::Context; -use camino::Utf8Path; +use camino::{Utf8Path, Utf8PathBuf}; use fs_extra::dir::CopyOptions; use std::fs::File; @@ -46,3 +46,17 @@ pub fn unpack_archive(path: &Utf8Path, dest_dir: &Utf8Path) -> anyhow::Result<() archive.unpack(dest_dir.as_std_path())?; Ok(()) } + +/// Returns paths in the given `dir` (non-recursively), optionally with the given `suffix`. +/// The `suffix` should contain the leading dot. +pub fn get_files_from_dir( + dir: &Utf8Path, + suffix: Option<&str>, +) -> anyhow::Result<Vec<Utf8PathBuf>> { + let path = format!("{dir}/*{}", suffix.unwrap_or("")); + + Ok(glob::glob(&path)? + .into_iter() + .map(|p| p.map(|p| Utf8PathBuf::from_path_buf(p).unwrap())) + .collect::<Result<Vec<_>, _>>()?) +} diff --git a/src/tools/opt-dist/src/utils/mod.rs b/src/tools/opt-dist/src/utils/mod.rs index 9305d4989aa..9a3df15e302 100644 --- a/src/tools/opt-dist/src/utils/mod.rs +++ b/src/tools/opt-dist/src/utils/mod.rs @@ -1,8 +1,8 @@ pub mod io; use crate::environment::Environment; -use crate::utils::io::delete_directory; -use humansize::BINARY; +use crate::utils::io::{delete_directory, get_files_from_dir}; +use humansize::{format_size, BINARY}; use sysinfo::{DiskExt, RefreshKind, System, SystemExt}; pub fn format_env_variables() -> String { @@ -25,6 +25,28 @@ pub fn print_free_disk_space() -> anyhow::Result<()> { Ok(()) } +pub fn print_binary_sizes(env: &dyn Environment) -> anyhow::Result<()> { + use std::fmt::Write; + + let root = env.build_artifacts().join("stage2"); + + let mut files = get_files_from_dir(&root.join("bin"), None)?; + files.extend(get_files_from_dir(&root.join("lib"), Some(".so"))?); + files.sort_unstable(); + + let mut output = String::new(); + for file in files { + let size = std::fs::metadata(file.as_std_path())?.len(); + let size_formatted = format_size(size, BINARY); + let name = format!("{}:", file.file_name().unwrap()); + writeln!(output, "{name:<50}{size_formatted:>10}")?; + } + + log::info!("Rustc artifact size\n{output}"); + + Ok(()) +} + pub fn clear_llvm_files(env: &dyn Environment) -> anyhow::Result<()> { // Bootstrap currently doesn't support rebuilding LLVM when PGO options // change (or any other llvm-related options); so just clear out the relevant @@ -34,3 +56,20 @@ pub fn clear_llvm_files(env: &dyn Environment) -> anyhow::Result<()> { delete_directory(&env.build_artifacts().join("lld"))?; Ok(()) } + +/// Wraps all output produced within the `func` closure in a CI output group, if we're running in +/// CI. +pub fn with_log_group<F: FnOnce() -> R, R>(group: &str, func: F) -> R { + if is_in_ci() { + println!("::group::{group}"); + let result = func(); + println!("::endgroup::"); + result + } else { + func() + } +} + +fn is_in_ci() -> bool { + std::env::var("GITHUB_ACTIONS").is_ok() +} diff --git a/src/tools/tidy/src/deps.rs b/src/tools/tidy/src/deps.rs index 2c237c418b1..9f0f0d86c8b 100644 --- a/src/tools/tidy/src/deps.rs +++ b/src/tools/tidy/src/deps.rs @@ -56,6 +56,9 @@ const EXCEPTIONS_CARGO: &[(&str, &str)] = &[ // tidy-alphabetical-start ("bitmaps", "MPL-2.0+"), ("bytesize", "Apache-2.0"), + ("ciborium", "Apache-2.0"), + ("ciborium-io", "Apache-2.0"), + ("ciborium-ll", "Apache-2.0"), ("dunce", "CC0-1.0 OR MIT-0 OR Apache-2.0"), ("fiat-crypto", "MIT OR Apache-2.0 OR BSD-1-Clause"), ("im-rc", "MPL-2.0+"), diff --git a/src/tools/tidy/src/ui_tests.rs b/src/tools/tidy/src/ui_tests.rs index 55bf38110a6..c3a63952841 100644 --- a/src/tools/tidy/src/ui_tests.rs +++ b/src/tools/tidy/src/ui_tests.rs @@ -10,7 +10,7 @@ use std::path::{Path, PathBuf}; const ENTRY_LIMIT: usize = 900; // FIXME: The following limits should be reduced eventually. -const ISSUES_ENTRY_LIMIT: usize = 1896; +const ISSUES_ENTRY_LIMIT: usize = 1894; const ROOT_ENTRY_LIMIT: usize = 870; const EXPECTED_TEST_FILE_EXTENSIONS: &[&str] = &[ diff --git a/tests/codegen/aarch64-struct-align-128.rs b/tests/codegen/aarch64-struct-align-128.rs new file mode 100644 index 00000000000..bf34717786d --- /dev/null +++ b/tests/codegen/aarch64-struct-align-128.rs @@ -0,0 +1,150 @@ +// Test that structs aligned to 128 bits are passed with the correct ABI on aarch64. + +// revisions:linux darwin windows +//[linux] compile-flags: --target aarch64-unknown-linux-gnu +//[darwin] compile-flags: --target aarch64-apple-darwin +//[windows] compile-flags: --target aarch64-pc-windows-msvc +//[linux] needs-llvm-components: aarch64 +//[darwin] needs-llvm-components: aarch64 +//[windows] needs-llvm-components: aarch64 + +#![feature(no_core, lang_items)] +#![crate_type = "lib"] +#![no_core] + +#[lang="sized"] +trait Sized { } +#[lang="freeze"] +trait Freeze { } +#[lang="copy"] +trait Copy { } + + + +// Passed as `[i64 x 2]`, since it's an aggregate with size <= 128 bits, align < 128 bits. +#[repr(C)] +pub struct Align8 { + pub a: u64, + pub b: u64, +} + +// repr(transparent), so same as above. +#[repr(transparent)] +pub struct Transparent8 { + a: Align8 +} + +// Passed as `[i64 x 2]`, since it's an aggregate with size <= 128 bits, align < 128 bits. +#[repr(C)] +pub struct Wrapped8 { + a: Align8, +} + +extern "C" { + // linux: declare void @test_8([2 x i64], [2 x i64], [2 x i64]) + // darwin: declare void @test_8([2 x i64], [2 x i64], [2 x i64]) + // windows: declare void @test_8([2 x i64], [2 x i64], [2 x i64]) + fn test_8(a: Align8, b: Transparent8, c: Wrapped8); +} + + + +// Passed as `i128`, since it's an aggregate with size <= 128 bits, align = 128 bits. +// EXCEPT on Linux, where there's a special case to use its unadjusted alignment, +// making it the same as `Align8`, so it's be passed as `[i64 x 2]`. +#[repr(C)] +#[repr(align(16))] +pub struct Align16 { + pub a: u64, + pub b: u64, +} + +// repr(transparent), so same as above. +#[repr(transparent)] +pub struct Transparent16 { + a: Align16 +} + +// Passed as `i128`, since it's an aggregate with size <= 128 bits, align = 128 bits. +// On Linux, the "unadjustedness" doesn't recurse into fields, so this is passed as `i128`. +#[repr(C)] +pub struct Wrapped16 { + pub a: Align16, +} + +extern "C" { + // linux: declare void @test_16([2 x i64], [2 x i64], i128) + // darwin: declare void @test_16(i128, i128, i128) + // windows: declare void @test_16(i128, i128, i128) + fn test_16(a: Align16, b: Transparent16, c: Wrapped16); +} + + + +// Passed as `i128`, since it's an aggregate with size <= 128 bits, align = 128 bits. +#[repr(C)] +pub struct I128 { + pub a: i128, +} + +// repr(transparent), so same as above. +#[repr(transparent)] +pub struct TransparentI128 { + a: I128 +} + +// Passed as `i128`, since it's an aggregate with size <= 128 bits, align = 128 bits. +#[repr(C)] +pub struct WrappedI128 { + pub a: I128 +} + +extern "C" { + // linux: declare void @test_i128(i128, i128, i128) + // darwin: declare void @test_i128(i128, i128, i128) + // windows: declare void @test_i128(i128, i128, i128) + fn test_i128(a: I128, b: TransparentI128, c: WrappedI128); +} + + + +// Passed as `[2 x i64]`, since it's an aggregate with size <= 128 bits, align < 128 bits. +// Note that the Linux special case does not apply, because packing is not considered "adjustment". +#[repr(C)] +#[repr(packed)] +pub struct Packed { + pub a: i128, +} + +// repr(transparent), so same as above. +#[repr(transparent)] +pub struct TransparentPacked { + a: Packed +} + +// Passed as `[2 x i64]`, since it's an aggregate with size <= 128 bits, align < 128 bits. +#[repr(C)] +pub struct WrappedPacked { + pub a: Packed +} + +extern "C" { + // linux: declare void @test_packed([2 x i64], [2 x i64], [2 x i64]) + // darwin: declare void @test_packed([2 x i64], [2 x i64], [2 x i64]) + // windows: declare void @test_packed([2 x i64], [2 x i64], [2 x i64]) + fn test_packed(a: Packed, b: TransparentPacked, c: WrappedPacked); +} + + + +pub unsafe fn main( + a1: Align8, a2: Transparent8, a3: Wrapped8, + b1: Align16, b2: Transparent16, b3: Wrapped16, + c1: I128, c2: TransparentI128, c3: WrappedI128, + d1: Packed, d2: TransparentPacked, d3: WrappedPacked, +) { + test_8(a1, a2, a3); + test_16(b1, b2, b3); + test_i128(c1, c2, c3); + test_packed(d1, d2, d3); +} diff --git a/tests/codegen/addr-of-mutate.rs b/tests/codegen/addr-of-mutate.rs index bea1aad2352..6dfc1825015 100644 --- a/tests/codegen/addr-of-mutate.rs +++ b/tests/codegen/addr-of-mutate.rs @@ -6,7 +6,7 @@ // Test for the absence of `readonly` on the argument when it is mutated via `&raw const`. // See <https://github.com/rust-lang/rust/issues/111502>. -// CHECK: i8 @foo(ptr noalias nocapture noundef dereferenceable(128) %x) +// CHECK: i8 @foo(ptr noalias nocapture noundef align 1 dereferenceable(128) %x) #[no_mangle] pub fn foo(x: [u8; 128]) -> u8 { let ptr = core::ptr::addr_of!(x).cast_mut(); @@ -16,7 +16,7 @@ pub fn foo(x: [u8; 128]) -> u8 { x[0] } -// CHECK: i1 @second(ptr noalias nocapture noundef dereferenceable({{[0-9]+}}) %a_ptr_and_b) +// CHECK: i1 @second(ptr noalias nocapture noundef align {{[0-9]+}} dereferenceable({{[0-9]+}}) %a_ptr_and_b) #[no_mangle] pub unsafe fn second(a_ptr_and_b: (*mut (i32, bool), (i64, bool))) -> bool { let b_bool_ptr = core::ptr::addr_of!(a_ptr_and_b.1.1).cast_mut(); @@ -25,7 +25,7 @@ pub unsafe fn second(a_ptr_and_b: (*mut (i32, bool), (i64, bool))) -> bool { } // If going through a deref (and there are no other mutating accesses), then `readonly` is fine. -// CHECK: i1 @third(ptr noalias nocapture noundef readonly dereferenceable({{[0-9]+}}) %a_ptr_and_b) +// CHECK: i1 @third(ptr noalias nocapture noundef readonly align {{[0-9]+}} dereferenceable({{[0-9]+}}) %a_ptr_and_b) #[no_mangle] pub unsafe fn third(a_ptr_and_b: (*mut (i32, bool), (i64, bool))) -> bool { let b_bool_ptr = core::ptr::addr_of!((*a_ptr_and_b.0).1).cast_mut(); diff --git a/tests/codegen/align-byval-vector.rs b/tests/codegen/align-byval-vector.rs new file mode 100644 index 00000000000..3c8be659671 --- /dev/null +++ b/tests/codegen/align-byval-vector.rs @@ -0,0 +1,58 @@ +// revisions:x86-linux x86-darwin + +//[x86-linux] compile-flags: --target i686-unknown-linux-gnu +//[x86-linux] needs-llvm-components: x86 +//[x86-darwin] compile-flags: --target i686-apple-darwin +//[x86-darwin] needs-llvm-components: x86 + +// Tests that aggregates containing vector types get their alignment increased to 16 on Darwin. + +#![feature(no_core, lang_items, repr_simd, simd_ffi)] +#![crate_type = "lib"] +#![no_std] +#![no_core] +#![allow(non_camel_case_types)] + +#[lang = "sized"] +trait Sized {} +#[lang = "freeze"] +trait Freeze {} +#[lang = "copy"] +trait Copy {} + +#[repr(simd)] +pub struct i32x4(i32, i32, i32, i32); + +#[repr(C)] +pub struct Foo { + a: i32x4, + b: i8, +} + +// This tests that we recursively check for vector types, not just at the top level. +#[repr(C)] +pub struct DoubleFoo { + one: Foo, + two: Foo, +} + +extern "C" { + // x86-linux: declare void @f({{.*}}byval(%Foo) align 4{{.*}}) + // x86-darwin: declare void @f({{.*}}byval(%Foo) align 16{{.*}}) + fn f(foo: Foo); + + // x86-linux: declare void @g({{.*}}byval(%DoubleFoo) align 4{{.*}}) + // x86-darwin: declare void @g({{.*}}byval(%DoubleFoo) align 16{{.*}}) + fn g(foo: DoubleFoo); +} + +pub fn main() { + unsafe { f(Foo { a: i32x4(1, 2, 3, 4), b: 0 }) } + + unsafe { + g(DoubleFoo { + one: Foo { a: i32x4(1, 2, 3, 4), b: 0 }, + two: Foo { a: i32x4(1, 2, 3, 4), b: 0 }, + }) + } +} diff --git a/tests/codegen/align-byval.rs b/tests/codegen/align-byval.rs new file mode 100644 index 00000000000..e2446e02ef4 --- /dev/null +++ b/tests/codegen/align-byval.rs @@ -0,0 +1,342 @@ +// ignore-tidy-linelength +// revisions:m68k wasm x86_64-linux x86_64-windows i686-linux i686-windows + +//[m68k] compile-flags: --target m68k-unknown-linux-gnu +//[m68k] needs-llvm-components: m68k +//[wasm] compile-flags: --target wasm32-unknown-emscripten +//[wasm] needs-llvm-components: webassembly +//[x86_64-linux] compile-flags: --target x86_64-unknown-linux-gnu +//[x86_64-linux] needs-llvm-components: x86 +//[x86_64-windows] compile-flags: --target x86_64-pc-windows-msvc +//[x86_64-windows] needs-llvm-components: x86 +//[i686-linux] compile-flags: --target i686-unknown-linux-gnu +//[i686-linux] needs-llvm-components: x86 +//[i686-windows] compile-flags: --target i686-pc-windows-msvc +//[i686-windows] needs-llvm-components: x86 + +// Tests that `byval` alignment is properly specified (#80127). +// The only targets that use `byval` are m68k, wasm, x86-64, and x86. +// Note also that Windows mandates a by-ref ABI here, so it does not use byval. + +#![feature(no_core, lang_items)] +#![crate_type = "lib"] +#![no_std] +#![no_core] + +#[lang="sized"] trait Sized { } +#[lang="freeze"] trait Freeze { } +#[lang="copy"] trait Copy { } + +impl Copy for i32 {} +impl Copy for i64 {} + +// This struct can be represented as a pair, so it exercises the OperandValue::Pair +// codepath in `codegen_argument`. +#[repr(C)] +pub struct NaturalAlign1 { + a: i8, + b: i8, +} + +// This struct cannot be represented as an immediate, so it exercises the OperandValue::Ref +// codepath in `codegen_argument`. +#[repr(C)] +pub struct NaturalAlign2 { + a: [i16; 16], + b: i16, +} + +#[repr(C)] +#[repr(align(4))] +pub struct ForceAlign4 { + a: [i8; 16], + b: i8, +} + +// On i686-windows, this is passed on stack using `byval` +#[repr(C)] +pub struct NaturalAlign8 { + a: i64, + b: i64, + c: i64 +} + +// On i686-windows, this is passed by reference (because alignment is >4 and requested/forced), +// even though it has the exact same layout as `NaturalAlign8`! +#[repr(C)] +#[repr(align(8))] +pub struct ForceAlign8 { + a: i64, + b: i64, + c: i64 +} + +// On i686-windows, this is passed on stack, because requested alignment is <=4. +#[repr(C)] +#[repr(align(4))] +pub struct LowerFA8 { + a: i64, + b: i64, + c: i64 +} + +// On i686-windows, this is passed by reference, because it contains a field with +// requested/forced alignment. +#[repr(C)] +pub struct WrappedFA8 { + a: ForceAlign8 +} + +// On i686-windows, this has the same ABI as ForceAlign8, i.e. passed by reference. +#[repr(transparent)] +pub struct TransparentFA8 { + _0: (), + a: ForceAlign8 +} + +#[repr(C)] +#[repr(align(16))] +pub struct ForceAlign16 { + a: [i32; 16], + b: i8 +} + +// CHECK-LABEL: @call_na1 +#[no_mangle] +pub unsafe fn call_na1(x: NaturalAlign1) { + // CHECK: start: + + // m68k: [[ALLOCA:%[a-z0-9+]]] = alloca { i8, i8 }, align 1 + // m68k: call void @natural_align_1({{.*}}byval({ i8, i8 }) align 1{{.*}} [[ALLOCA]]) + + // wasm: [[ALLOCA:%[a-z0-9+]]] = alloca { i8, i8 }, align 1 + // wasm: call void @natural_align_1({{.*}}byval({ i8, i8 }) align 1{{.*}} [[ALLOCA]]) + + // x86_64-linux: call void @natural_align_1(i16 + + // x86_64-windows: call void @natural_align_1(i16 + + // i686-linux: [[ALLOCA:%[a-z0-9+]]] = alloca { i8, i8 }, align 4 + // i686-linux: call void @natural_align_1({{.*}}byval({ i8, i8 }) align 4{{.*}} [[ALLOCA]]) + + // i686-windows: [[ALLOCA:%[a-z0-9+]]] = alloca { i8, i8 }, align 4 + // i686-windows: call void @natural_align_1({{.*}}byval({ i8, i8 }) align 4{{.*}} [[ALLOCA]]) + natural_align_1(x); +} + +// CHECK-LABEL: @call_na2 +#[no_mangle] +pub unsafe fn call_na2(x: NaturalAlign2) { + // CHECK: start: + + // m68k-NEXT: call void @natural_align_2 + // wasm-NEXT: call void @natural_align_2 + // x86_64-linux-NEXT: call void @natural_align_2 + // x86_64-windows-NEXT: call void @natural_align_2 + + // i686-linux: [[ALLOCA:%[0-9]+]] = alloca %NaturalAlign2, align 4 + // i686-linux: call void @natural_align_2({{.*}}byval(%NaturalAlign2) align 4{{.*}} [[ALLOCA]]) + + // i686-windows: [[ALLOCA:%[0-9]+]] = alloca %NaturalAlign2, align 4 + // i686-windows: call void @natural_align_2({{.*}}byval(%NaturalAlign2) align 4{{.*}} [[ALLOCA]]) + natural_align_2(x); +} + +// CHECK-LABEL: @call_fa4 +#[no_mangle] +pub unsafe fn call_fa4(x: ForceAlign4) { + // CHECK: start: + // CHECK-NEXT: call void @force_align_4 + force_align_4(x); +} + +// CHECK-LABEL: @call_na8 +#[no_mangle] +pub unsafe fn call_na8(x: NaturalAlign8) { + // CHECK: start: + // CHECK-NEXT: call void @natural_align_8 + natural_align_8(x); +} + +// CHECK-LABEL: @call_fa8 +#[no_mangle] +pub unsafe fn call_fa8(x: ForceAlign8) { + // CHECK: start: + // CHECK-NEXT: call void @force_align_8 + force_align_8(x); +} + +// CHECK-LABEL: @call_lfa8 +#[no_mangle] +pub unsafe fn call_lfa8(x: LowerFA8) { + // CHECK: start: + // CHECK-NEXT: call void @lower_fa8 + lower_fa8(x); +} + +// CHECK-LABEL: @call_wfa8 +#[no_mangle] +pub unsafe fn call_wfa8(x: WrappedFA8) { + // CHECK: start: + // CHECK-NEXT: call void @wrapped_fa8 + wrapped_fa8(x); +} + +// CHECK-LABEL: @call_tfa8 +#[no_mangle] +pub unsafe fn call_tfa8(x: TransparentFA8) { + // CHECK: start: + // CHECK-NEXT: call void @transparent_fa8 + transparent_fa8(x); +} + +// CHECK-LABEL: @call_fa16 +#[no_mangle] +pub unsafe fn call_fa16(x: ForceAlign16) { + // CHECK: start: + // CHECK-NEXT: call void @force_align_16 + force_align_16(x); +} + +extern "C" { + // m68k: declare void @natural_align_1({{.*}}byval({ i8, i8 }) align 1{{.*}}) + + // wasm: declare void @natural_align_1({{.*}}byval({ i8, i8 }) align 1{{.*}}) + + // x86_64-linux: declare void @natural_align_1(i16) + + // x86_64-windows: declare void @natural_align_1(i16) + + // i686-linux: declare void @natural_align_1({{.*}}byval({ i8, i8 }) align 4{{.*}}) + + // i686-windows: declare void @natural_align_1({{.*}}byval({ i8, i8 }) align 4{{.*}}) + fn natural_align_1(x: NaturalAlign1); + + // m68k: declare void @natural_align_2({{.*}}byval(%NaturalAlign2) align 2{{.*}}) + + // wasm: declare void @natural_align_2({{.*}}byval(%NaturalAlign2) align 2{{.*}}) + + // x86_64-linux: declare void @natural_align_2({{.*}}byval(%NaturalAlign2) align 2{{.*}}) + + // x86_64-windows: declare void @natural_align_2( + // x86_64-windows-NOT: byval + // x86_64-windows-SAME: align 2{{.*}}) + + // i686-linux: declare void @natural_align_2({{.*}}byval(%NaturalAlign2) align 4{{.*}}) + + // i686-windows: declare void @natural_align_2({{.*}}byval(%NaturalAlign2) align 4{{.*}}) + fn natural_align_2(x: NaturalAlign2); + + // m68k: declare void @force_align_4({{.*}}byval(%ForceAlign4) align 4{{.*}}) + + // wasm: declare void @force_align_4({{.*}}byval(%ForceAlign4) align 4{{.*}}) + + // x86_64-linux: declare void @force_align_4({{.*}}byval(%ForceAlign4) align 4{{.*}}) + + // x86_64-windows: declare void @force_align_4( + // x86_64-windows-NOT: byval + // x86_64-windows-SAME: align 4{{.*}}) + + // i686-linux: declare void @force_align_4({{.*}}byval(%ForceAlign4) align 4{{.*}}) + + // i686-windows: declare void @force_align_4({{.*}}byval(%ForceAlign4) align 4{{.*}}) + fn force_align_4(x: ForceAlign4); + + // m68k: declare void @natural_align_8({{.*}}byval(%NaturalAlign8) align 4{{.*}}) + + // wasm: declare void @natural_align_8({{.*}}byval(%NaturalAlign8) align 8{{.*}}) + + // x86_64-linux: declare void @natural_align_8({{.*}}byval(%NaturalAlign8) align 8{{.*}}) + + // x86_64-windows: declare void @natural_align_8( + // x86_64-windows-NOT: byval + // x86_64-windows-SAME: align 8{{.*}}) + + // i686-linux: declare void @natural_align_8({{.*}}byval(%NaturalAlign8) align 4{{.*}}) + + // i686-windows: declare void @natural_align_8({{.*}}byval(%NaturalAlign8) align 4{{.*}}) + fn natural_align_8(x: NaturalAlign8); + + // m68k: declare void @force_align_8({{.*}}byval(%ForceAlign8) align 8{{.*}}) + + // wasm: declare void @force_align_8({{.*}}byval(%ForceAlign8) align 8{{.*}}) + + // x86_64-linux: declare void @force_align_8({{.*}}byval(%ForceAlign8) align 8{{.*}}) + + // x86_64-windows: declare void @force_align_8( + // x86_64-windows-NOT: byval + // x86_64-windows-SAME: align 8{{.*}}) + + // i686-linux: declare void @force_align_8({{.*}}byval(%ForceAlign8) align 4{{.*}}) + + // i686-windows: declare void @force_align_8( + // i686-windows-NOT: byval + // i686-windows-SAME: align 8{{.*}}) + fn force_align_8(x: ForceAlign8); + + // m68k: declare void @lower_fa8({{.*}}byval(%LowerFA8) align 4{{.*}}) + + // wasm: declare void @lower_fa8({{.*}}byval(%LowerFA8) align 8{{.*}}) + + // x86_64-linux: declare void @lower_fa8({{.*}}byval(%LowerFA8) align 8{{.*}}) + + // x86_64-windows: declare void @lower_fa8( + // x86_64-windows-NOT: byval + // x86_64-windows-SAME: align 8{{.*}}) + + // i686-linux: declare void @lower_fa8({{.*}}byval(%LowerFA8) align 4{{.*}}) + + // i686-windows: declare void @lower_fa8({{.*}}byval(%LowerFA8) align 4{{.*}}) + fn lower_fa8(x: LowerFA8); + + // m68k: declare void @wrapped_fa8({{.*}}byval(%WrappedFA8) align 8{{.*}}) + + // wasm: declare void @wrapped_fa8({{.*}}byval(%WrappedFA8) align 8{{.*}}) + + // x86_64-linux: declare void @wrapped_fa8({{.*}}byval(%WrappedFA8) align 8{{.*}}) + + // x86_64-windows: declare void @wrapped_fa8( + // x86_64-windows-NOT: byval + // x86_64-windows-SAME: align 8{{.*}}) + + // i686-linux: declare void @wrapped_fa8({{.*}}byval(%WrappedFA8) align 4{{.*}}) + + // i686-windows: declare void @wrapped_fa8( + // i686-windows-NOT: byval + // i686-windows-SAME: align 8{{.*}}) + fn wrapped_fa8(x: WrappedFA8); + + // m68k: declare void @transparent_fa8({{.*}}byval(%TransparentFA8) align 8{{.*}}) + + // wasm: declare void @transparent_fa8({{.*}}byval(%TransparentFA8) align 8{{.*}}) + + // x86_64-linux: declare void @transparent_fa8({{.*}}byval(%TransparentFA8) align 8{{.*}}) + + // x86_64-windows: declare void @transparent_fa8( + // x86_64-windows-NOT: byval + // x86_64-windows-SAME: align 8{{.*}}) + + // i686-linux: declare void @transparent_fa8({{.*}}byval(%TransparentFA8) align 4{{.*}}) + + // i686-windows: declare void @transparent_fa8( + // i686-windows-NOT: byval + // i686-windows-SAME: align 8{{.*}}) + fn transparent_fa8(x: TransparentFA8); + + // m68k: declare void @force_align_16({{.*}}byval(%ForceAlign16) align 16{{.*}}) + + // wasm: declare void @force_align_16({{.*}}byval(%ForceAlign16) align 16{{.*}}) + + // x86_64-linux: declare void @force_align_16({{.*}}byval(%ForceAlign16) align 16{{.*}}) + + // x86_64-windows: declare void @force_align_16( + // x86_64-windows-NOT: byval + // x86_64-windows-SAME: align 16{{.*}}) + + // i686-linux: declare void @force_align_16({{.*}}byval(%ForceAlign16) align 4{{.*}}) + + // i686-windows: declare void @force_align_16( + // i686-windows-NOT: byval + // i686-windows-SAME: align 16{{.*}}) + fn force_align_16(x: ForceAlign16); +} diff --git a/tests/codegen/array-map.rs b/tests/codegen/array-map.rs index 24f3f43d078..4d218e6a951 100644 --- a/tests/codegen/array-map.rs +++ b/tests/codegen/array-map.rs @@ -30,7 +30,6 @@ pub fn short_integer_map(x: [u32; 8]) -> [u32; 8] { pub fn long_integer_map(x: [u32; 512]) -> [u32; 512] { // CHECK: start: // CHECK-NEXT: alloca [512 x i32] - // CHECK-NEXT: alloca %"core::mem::manually_drop::ManuallyDrop<[u32; 512]>" // CHECK-NOT: alloca // CHECK: mul <{{[0-9]+}} x i32> // CHECK: add <{{[0-9]+}} x i32> diff --git a/tests/codegen/function-arguments-noopt.rs b/tests/codegen/function-arguments-noopt.rs index 35f31eba3b1..f99cc8fb415 100644 --- a/tests/codegen/function-arguments-noopt.rs +++ b/tests/codegen/function-arguments-noopt.rs @@ -42,7 +42,7 @@ pub fn borrow_call(x: &i32, f: fn(&i32) -> &i32) -> &i32 { f(x) } -// CHECK: void @struct_({{%S\*|ptr}} sret(%S){{( %_0)?}}, {{%S\*|ptr}} %x) +// CHECK: void @struct_({{%S\*|ptr}} sret(%S) align 4{{( %_0)?}}, {{%S\*|ptr}} align 4 %x) #[no_mangle] pub fn struct_(x: S) -> S { x @@ -51,7 +51,7 @@ pub fn struct_(x: S) -> S { // CHECK-LABEL: @struct_call #[no_mangle] pub fn struct_call(x: S, f: fn(S) -> S) -> S { - // CHECK: call void %f({{%S\*|ptr}} sret(%S){{( %_0)?}}, {{%S\*|ptr}} %{{.+}}) + // CHECK: call void %f({{%S\*|ptr}} sret(%S) align 4{{( %_0)?}}, {{%S\*|ptr}} align 4 %{{.+}}) f(x) } diff --git a/tests/codegen/function-arguments.rs b/tests/codegen/function-arguments.rs index ccf4a5de327..2f047f10311 100644 --- a/tests/codegen/function-arguments.rs +++ b/tests/codegen/function-arguments.rs @@ -142,7 +142,7 @@ pub fn mutable_notunpin_borrow(_: &mut NotUnpin) { pub fn notunpin_borrow(_: &NotUnpin) { } -// CHECK: @indirect_struct({{%S\*|ptr}} noalias nocapture noundef readonly dereferenceable(32) %_1) +// CHECK: @indirect_struct({{%S\*|ptr}} noalias nocapture noundef readonly align 4 dereferenceable(32) %_1) #[no_mangle] pub fn indirect_struct(_: S) { } @@ -188,7 +188,7 @@ pub fn notunpin_box(x: Box<NotUnpin>) -> Box<NotUnpin> { x } -// CHECK: @struct_return({{%S\*|ptr}} noalias nocapture noundef sret(%S) dereferenceable(32){{( %_0)?}}) +// CHECK: @struct_return({{%S\*|ptr}} noalias nocapture noundef sret(%S) align 4 dereferenceable(32){{( %_0)?}}) #[no_mangle] pub fn struct_return() -> S { S { diff --git a/tests/codegen/iter-repeat-n-trivial-drop.rs b/tests/codegen/iter-repeat-n-trivial-drop.rs index 24059f190ac..65a0f7e7ffb 100644 --- a/tests/codegen/iter-repeat-n-trivial-drop.rs +++ b/tests/codegen/iter-repeat-n-trivial-drop.rs @@ -33,7 +33,7 @@ pub fn iter_repeat_n_next(it: &mut std::iter::RepeatN<NotCopy>) -> Option<NotCop // CHECK: [[EMPTY]]: // CHECK-NOT: br - // CHECK: phi i16 [ undef, %start ], [ %[[VAL]], %[[NOT_EMPTY]] ] + // CHECK: phi i16 [ %[[VAL]], %[[NOT_EMPTY]] ], [ undef, %start ] // CHECK-NOT: br // CHECK: ret diff --git a/tests/codegen/simd-wide-sum.rs b/tests/codegen/simd-wide-sum.rs index db2aa20bde7..3116f9597bc 100644 --- a/tests/codegen/simd-wide-sum.rs +++ b/tests/codegen/simd-wide-sum.rs @@ -1,6 +1,11 @@ +// revisions: llvm mir-opt3 // compile-flags: -C opt-level=3 -Z merge-functions=disabled --edition=2021 // only-x86_64 // ignore-debug: the debug assertions get in the way +// [mir-opt3]compile-flags: -Zmir-opt-level=3 +// [mir-opt3]build-pass + +// mir-opt3 is a regression test for https://github.com/rust-lang/rust/issues/98016 #![crate_type = "lib"] #![feature(portable_simd)] @@ -47,9 +52,8 @@ pub fn wider_reduce_iter(x: Simd<u8, N>) -> u16 { #[no_mangle] // CHECK-LABEL: @wider_reduce_into_iter pub fn wider_reduce_into_iter(x: Simd<u8, N>) -> u16 { - // FIXME MIR inlining messes up LLVM optimizations. - // WOULD-CHECK: zext <8 x i8> - // WOULD-CHECK-SAME: to <8 x i16> - // WOULD-CHECK: call i16 @llvm.vector.reduce.add.v8i16(<8 x i16> + // CHECK: zext <8 x i8> + // CHECK-SAME: to <8 x i16> + // CHECK: call i16 @llvm.vector.reduce.add.v8i16(<8 x i16> x.to_array().into_iter().map(u16::from).sum() } diff --git a/tests/codegen/slice-init.rs b/tests/codegen/slice-init.rs index 794b773a776..d80628cb1d4 100644 --- a/tests/codegen/slice-init.rs +++ b/tests/codegen/slice-init.rs @@ -8,7 +8,7 @@ pub fn zero_sized_elem() { // CHECK-NOT: br label %repeat_loop_header{{.*}} // CHECK-NOT: call void @llvm.memset.p0 let x = [(); 4]; - drop(&x); + opaque(&x); } // CHECK-LABEL: @zero_len_array @@ -17,7 +17,7 @@ pub fn zero_len_array() { // CHECK-NOT: br label %repeat_loop_header{{.*}} // CHECK-NOT: call void @llvm.memset.p0 let x = [4; 0]; - drop(&x); + opaque(&x); } // CHECK-LABEL: @byte_array @@ -26,7 +26,7 @@ pub fn byte_array() { // CHECK: call void @llvm.memset.{{.+}}({{i8\*|ptr}} {{.*}}, i8 7, i{{[0-9]+}} 4 // CHECK-NOT: br label %repeat_loop_header{{.*}} let x = [7u8; 4]; - drop(&x); + opaque(&x); } #[allow(dead_code)] @@ -42,7 +42,7 @@ pub fn byte_enum_array() { // CHECK: call void @llvm.memset.{{.+}}({{i8\*|ptr}} {{.*}}, i8 {{.*}}, i{{[0-9]+}} 4 // CHECK-NOT: br label %repeat_loop_header{{.*}} let x = [Init::Memset; 4]; - drop(&x); + opaque(&x); } // CHECK-LABEL: @zeroed_integer_array @@ -51,7 +51,7 @@ pub fn zeroed_integer_array() { // CHECK: call void @llvm.memset.{{.+}}({{i8\*|ptr}} {{.*}}, i8 0, i{{[0-9]+}} 16 // CHECK-NOT: br label %repeat_loop_header{{.*}} let x = [0u32; 4]; - drop(&x); + opaque(&x); } // CHECK-LABEL: @nonzero_integer_array @@ -60,5 +60,9 @@ pub fn nonzero_integer_array() { // CHECK: br label %repeat_loop_header{{.*}} // CHECK-NOT: call void @llvm.memset.p0 let x = [0x1a_2b_3c_4d_u32; 4]; - drop(&x); + opaque(&x); } + +// Use an opaque function to prevent rustc from removing useless drops. +#[inline(never)] +pub fn opaque(_: impl Sized) {} diff --git a/tests/codegen/slice-ref-equality.rs b/tests/codegen/slice-ref-equality.rs index 8f0adab35e7..c91e5bc3cd0 100644 --- a/tests/codegen/slice-ref-equality.rs +++ b/tests/codegen/slice-ref-equality.rs @@ -44,48 +44,48 @@ pub fn is_zero_array(data: &[u8; 4]) -> bool { // equality for non-byte types also just emit a `bcmp`, not a loop. // CHECK-LABEL: @eq_slice_of_nested_u8( -// CHECK-SAME: [[USIZE:i16|i32|i64]] noundef %1 -// CHECK-SAME: [[USIZE]] noundef %3 +// CHECK-SAME: [[USIZE:i16|i32|i64]] noundef %x.1 +// CHECK-SAME: [[USIZE]] noundef %y.1 #[no_mangle] fn eq_slice_of_nested_u8(x: &[[u8; 3]], y: &[[u8; 3]]) -> bool { - // CHECK: icmp eq [[USIZE]] %1, %3 - // CHECK: %[[BYTES:.+]] = mul nsw [[USIZE]] %1, 3 + // CHECK: icmp eq [[USIZE]] %x.1, %y.1 + // CHECK: %[[BYTES:.+]] = mul nsw [[USIZE]] %x.1, 3 // CHECK: tail call{{( noundef)?}} i32 @{{bcmp|memcmp}}({{i8\*|ptr}} // CHECK-SAME: , [[USIZE]]{{( noundef)?}} %[[BYTES]]) x == y } // CHECK-LABEL: @eq_slice_of_i32( -// CHECK-SAME: [[USIZE:i16|i32|i64]] noundef %1 -// CHECK-SAME: [[USIZE]] noundef %3 +// CHECK-SAME: [[USIZE:i16|i32|i64]] noundef %x.1 +// CHECK-SAME: [[USIZE]] noundef %y.1 #[no_mangle] fn eq_slice_of_i32(x: &[i32], y: &[i32]) -> bool { - // CHECK: icmp eq [[USIZE]] %1, %3 - // CHECK: %[[BYTES:.+]] = shl nsw [[USIZE]] %1, 2 + // CHECK: icmp eq [[USIZE]] %x.1, %y.1 + // CHECK: %[[BYTES:.+]] = shl nsw [[USIZE]] %x.1, 2 // CHECK: tail call{{( noundef)?}} i32 @{{bcmp|memcmp}}({{i32\*|ptr}} // CHECK-SAME: , [[USIZE]]{{( noundef)?}} %[[BYTES]]) x == y } // CHECK-LABEL: @eq_slice_of_nonzero( -// CHECK-SAME: [[USIZE:i16|i32|i64]] noundef %1 -// CHECK-SAME: [[USIZE]] noundef %3 +// CHECK-SAME: [[USIZE:i16|i32|i64]] noundef %x.1 +// CHECK-SAME: [[USIZE]] noundef %y.1 #[no_mangle] fn eq_slice_of_nonzero(x: &[NonZeroU32], y: &[NonZeroU32]) -> bool { - // CHECK: icmp eq [[USIZE]] %1, %3 - // CHECK: %[[BYTES:.+]] = shl nsw [[USIZE]] %1, 2 + // CHECK: icmp eq [[USIZE]] %x.1, %y.1 + // CHECK: %[[BYTES:.+]] = shl nsw [[USIZE]] %x.1, 2 // CHECK: tail call{{( noundef)?}} i32 @{{bcmp|memcmp}}({{i32\*|ptr}} // CHECK-SAME: , [[USIZE]]{{( noundef)?}} %[[BYTES]]) x == y } // CHECK-LABEL: @eq_slice_of_option_of_nonzero( -// CHECK-SAME: [[USIZE:i16|i32|i64]] noundef %1 -// CHECK-SAME: [[USIZE]] noundef %3 +// CHECK-SAME: [[USIZE:i16|i32|i64]] noundef %x.1 +// CHECK-SAME: [[USIZE]] noundef %y.1 #[no_mangle] fn eq_slice_of_option_of_nonzero(x: &[Option<NonZeroI16>], y: &[Option<NonZeroI16>]) -> bool { - // CHECK: icmp eq [[USIZE]] %1, %3 - // CHECK: %[[BYTES:.+]] = shl nsw [[USIZE]] %1, 1 + // CHECK: icmp eq [[USIZE]] %x.1, %y.1 + // CHECK: %[[BYTES:.+]] = shl nsw [[USIZE]] %x.1, 1 // CHECK: tail call{{( noundef)?}} i32 @{{bcmp|memcmp}}({{i16\*|ptr}} // CHECK-SAME: , [[USIZE]]{{( noundef)?}} %[[BYTES]]) x == y diff --git a/tests/incremental/hashes/call_expressions.rs b/tests/incremental/hashes/call_expressions.rs index 65df2e8292a..a42cf6aa477 100644 --- a/tests/incremental/hashes/call_expressions.rs +++ b/tests/incremental/hashes/call_expressions.rs @@ -162,7 +162,7 @@ pub fn change_to_ufcs() { } #[cfg(not(any(cfail1,cfail4)))] -#[rustc_clean(cfg="cfail2", except="hir_owner_nodes,optimized_mir,typeck")] +#[rustc_clean(cfg="cfail2", except="hir_owner_nodes,typeck")] #[rustc_clean(cfg="cfail3")] #[rustc_clean(cfg="cfail5", except="hir_owner_nodes,optimized_mir,typeck")] #[rustc_clean(cfg="cfail6")] diff --git a/tests/mir-opt/casts.redundant.InstSimplify.diff b/tests/mir-opt/casts.redundant.InstSimplify.diff index ff6d11c4596..f5ea78aecbe 100644 --- a/tests/mir-opt/casts.redundant.InstSimplify.diff +++ b/tests/mir-opt/casts.redundant.InstSimplify.diff @@ -7,7 +7,7 @@ let mut _2: *const &u8; let mut _3: *const &u8; scope 1 (inlined generic_cast::<&u8, &u8>) { - debug x => _3; + debug x => _1; } bb0: { diff --git a/tests/mir-opt/copy-prop/mutate_through_pointer.rs b/tests/mir-opt/copy-prop/mutate_through_pointer.rs index da142e33948..753787089b5 100644 --- a/tests/mir-opt/copy-prop/mutate_through_pointer.rs +++ b/tests/mir-opt/copy-prop/mutate_through_pointer.rs @@ -1,3 +1,5 @@ +// unit-test: CopyProp +// // This attempts to mutate `a` via a pointer derived from `addr_of!(a)`. That is UB // according to Miri. However, the decision to make this UB - and to allow // rustc to rely on that fact for the purpose of optimizations - has not been diff --git a/tests/mir-opt/inline/unwrap_unchecked.unwrap_unchecked.Inline.panic-abort.diff b/tests/mir-opt/inline/unwrap_unchecked.unwrap_unchecked.Inline.panic-abort.diff index e3c57347392..486f276b21c 100644 --- a/tests/mir-opt/inline/unwrap_unchecked.unwrap_unchecked.Inline.panic-abort.diff +++ b/tests/mir-opt/inline/unwrap_unchecked.unwrap_unchecked.Inline.panic-abort.diff @@ -7,8 +7,7 @@ let mut _2: std::option::Option<T>; + scope 1 (inlined #[track_caller] Option::<T>::unwrap_unchecked) { + debug self => _2; -+ let mut _3: &std::option::Option<T>; -+ let mut _4: isize; ++ let mut _3: isize; + scope 2 { + debug val => _0; + } @@ -21,7 +20,7 @@ + } + } + scope 4 (inlined Option::<T>::is_some) { -+ debug self => _3; ++ debug self => &_2; + } + } @@ -29,9 +28,8 @@ StorageLive(_2); _2 = move _1; - _0 = Option::<T>::unwrap_unchecked(move _2) -> [return: bb1, unwind unreachable]; -+ StorageLive(_3); -+ _4 = discriminant(_2); -+ switchInt(move _4) -> [1: bb2, otherwise: bb1]; ++ _3 = discriminant(_2); ++ switchInt(move _3) -> [1: bb2, otherwise: bb1]; } bb1: { @@ -40,7 +38,6 @@ + + bb2: { + _0 = move ((_2 as Some).0: T); -+ StorageDead(_3); StorageDead(_2); return; } diff --git a/tests/mir-opt/inline/unwrap_unchecked.unwrap_unchecked.Inline.panic-unwind.diff b/tests/mir-opt/inline/unwrap_unchecked.unwrap_unchecked.Inline.panic-unwind.diff index fc638cb3ace..1c3aa537946 100644 --- a/tests/mir-opt/inline/unwrap_unchecked.unwrap_unchecked.Inline.panic-unwind.diff +++ b/tests/mir-opt/inline/unwrap_unchecked.unwrap_unchecked.Inline.panic-unwind.diff @@ -7,8 +7,7 @@ let mut _2: std::option::Option<T>; + scope 1 (inlined #[track_caller] Option::<T>::unwrap_unchecked) { + debug self => _2; -+ let mut _3: &std::option::Option<T>; -+ let mut _4: isize; ++ let mut _3: isize; + scope 2 { + debug val => _0; + } @@ -21,7 +20,7 @@ + } + } + scope 4 (inlined Option::<T>::is_some) { -+ debug self => _3; ++ debug self => &_2; + } + } @@ -29,9 +28,8 @@ StorageLive(_2); _2 = move _1; - _0 = Option::<T>::unwrap_unchecked(move _2) -> [return: bb1, unwind: bb2]; -+ StorageLive(_3); -+ _4 = discriminant(_2); -+ switchInt(move _4) -> [1: bb2, otherwise: bb1]; ++ _3 = discriminant(_2); ++ switchInt(move _3) -> [1: bb2, otherwise: bb1]; } bb1: { @@ -44,7 +42,6 @@ - resume; + bb2: { + _0 = move ((_2 as Some).0: T); -+ StorageDead(_3); + StorageDead(_2); + return; } diff --git a/tests/mir-opt/inline/unwrap_unchecked.unwrap_unchecked.PreCodegen.after.panic-abort.mir b/tests/mir-opt/inline/unwrap_unchecked.unwrap_unchecked.PreCodegen.after.panic-abort.mir index fcc4d43ced6..82238626798 100644 --- a/tests/mir-opt/inline/unwrap_unchecked.unwrap_unchecked.PreCodegen.after.panic-abort.mir +++ b/tests/mir-opt/inline/unwrap_unchecked.unwrap_unchecked.PreCodegen.after.panic-abort.mir @@ -6,7 +6,6 @@ fn unwrap_unchecked(_1: Option<T>) -> T { scope 1 (inlined #[track_caller] Option::<T>::unwrap_unchecked) { debug self => _1; let mut _2: isize; - let mut _3: &std::option::Option<T>; scope 2 { debug val => _0; } @@ -19,19 +18,17 @@ fn unwrap_unchecked(_1: Option<T>) -> T { } } scope 4 (inlined Option::<T>::is_some) { - debug self => _3; + debug self => &_1; } } bb0: { - StorageLive(_3); _2 = discriminant(_1); switchInt(move _2) -> [1: bb1, otherwise: bb2]; } bb1: { _0 = move ((_1 as Some).0: T); - StorageDead(_3); return; } diff --git a/tests/mir-opt/inline/unwrap_unchecked.unwrap_unchecked.PreCodegen.after.panic-unwind.mir b/tests/mir-opt/inline/unwrap_unchecked.unwrap_unchecked.PreCodegen.after.panic-unwind.mir index fcc4d43ced6..82238626798 100644 --- a/tests/mir-opt/inline/unwrap_unchecked.unwrap_unchecked.PreCodegen.after.panic-unwind.mir +++ b/tests/mir-opt/inline/unwrap_unchecked.unwrap_unchecked.PreCodegen.after.panic-unwind.mir @@ -6,7 +6,6 @@ fn unwrap_unchecked(_1: Option<T>) -> T { scope 1 (inlined #[track_caller] Option::<T>::unwrap_unchecked) { debug self => _1; let mut _2: isize; - let mut _3: &std::option::Option<T>; scope 2 { debug val => _0; } @@ -19,19 +18,17 @@ fn unwrap_unchecked(_1: Option<T>) -> T { } } scope 4 (inlined Option::<T>::is_some) { - debug self => _3; + debug self => &_1; } } bb0: { - StorageLive(_3); _2 = discriminant(_1); switchInt(move _2) -> [1: bb1, otherwise: bb2]; } bb1: { _0 = move ((_1 as Some).0: T); - StorageDead(_3); return; } diff --git a/tests/mir-opt/issue_76432.test.SimplifyComparisonIntegral.panic-abort.diff b/tests/mir-opt/issue_76432.test.SimplifyComparisonIntegral.panic-abort.diff index 1cc44ce06cf..b647455aeec 100644 --- a/tests/mir-opt/issue_76432.test.SimplifyComparisonIntegral.panic-abort.diff +++ b/tests/mir-opt/issue_76432.test.SimplifyComparisonIntegral.panic-abort.diff @@ -6,20 +6,16 @@ let mut _0: (); let _2: &[T]; let mut _3: &[T; 3]; - let _4: &[T; 3]; - let _5: [T; 3]; + let _4: [T; 3]; + let mut _5: T; let mut _6: T; let mut _7: T; - let mut _8: T; + let mut _8: usize; let mut _9: usize; - let mut _10: usize; - let mut _11: bool; - let mut _15: !; + let mut _10: bool; + let mut _11: !; scope 1 { debug v => _2; - let _12: &T; - let _13: &T; - let _14: &T; scope 2 { debug v1 => &(*_2)[0 of 3]; debug v2 => &(*_2)[1 of 3]; @@ -28,26 +24,26 @@ } bb0: { - StorageLive(_2); - StorageLive(_5); - _5 = [_1, _1, _1]; - _4 = &_5; - _2 = _4 as &[T] (PointerCoercion(Unsize)); - _9 = Len((*_2)); - _10 = const 3_usize; -- _11 = Eq(move _9, const 3_usize); -- switchInt(move _11) -> [0: bb1, otherwise: bb2]; + StorageLive(_3); + StorageLive(_4); + _4 = [_1, _1, _1]; + _3 = &_4; + _2 = move _3 as &[T] (PointerCoercion(Unsize)); + StorageDead(_3); + _8 = Len((*_2)); + _9 = const 3_usize; +- _10 = Eq(move _8, const 3_usize); +- switchInt(move _10) -> [0: bb1, otherwise: bb2]; + nop; -+ switchInt(move _9) -> [3: bb2, otherwise: bb1]; ++ switchInt(move _8) -> [3: bb2, otherwise: bb1]; } bb1: { - _15 = core::panicking::panic(const "internal error: entered unreachable code") -> unwind unreachable; + _11 = core::panicking::panic(const "internal error: entered unreachable code") -> unwind unreachable; } bb2: { - StorageDead(_5); - StorageDead(_2); + StorageDead(_4); return; } } diff --git a/tests/mir-opt/issue_76432.test.SimplifyComparisonIntegral.panic-unwind.diff b/tests/mir-opt/issue_76432.test.SimplifyComparisonIntegral.panic-unwind.diff index b708f667438..b02be61d031 100644 --- a/tests/mir-opt/issue_76432.test.SimplifyComparisonIntegral.panic-unwind.diff +++ b/tests/mir-opt/issue_76432.test.SimplifyComparisonIntegral.panic-unwind.diff @@ -6,20 +6,16 @@ let mut _0: (); let _2: &[T]; let mut _3: &[T; 3]; - let _4: &[T; 3]; - let _5: [T; 3]; + let _4: [T; 3]; + let mut _5: T; let mut _6: T; let mut _7: T; - let mut _8: T; + let mut _8: usize; let mut _9: usize; - let mut _10: usize; - let mut _11: bool; - let mut _15: !; + let mut _10: bool; + let mut _11: !; scope 1 { debug v => _2; - let _12: &T; - let _13: &T; - let _14: &T; scope 2 { debug v1 => &(*_2)[0 of 3]; debug v2 => &(*_2)[1 of 3]; @@ -28,26 +24,26 @@ } bb0: { - StorageLive(_2); - StorageLive(_5); - _5 = [_1, _1, _1]; - _4 = &_5; - _2 = _4 as &[T] (PointerCoercion(Unsize)); - _9 = Len((*_2)); - _10 = const 3_usize; -- _11 = Eq(move _9, const 3_usize); -- switchInt(move _11) -> [0: bb1, otherwise: bb2]; + StorageLive(_3); + StorageLive(_4); + _4 = [_1, _1, _1]; + _3 = &_4; + _2 = move _3 as &[T] (PointerCoercion(Unsize)); + StorageDead(_3); + _8 = Len((*_2)); + _9 = const 3_usize; +- _10 = Eq(move _8, const 3_usize); +- switchInt(move _10) -> [0: bb1, otherwise: bb2]; + nop; -+ switchInt(move _9) -> [3: bb2, otherwise: bb1]; ++ switchInt(move _8) -> [3: bb2, otherwise: bb1]; } bb1: { - _15 = core::panicking::panic(const "internal error: entered unreachable code") -> unwind continue; + _11 = core::panicking::panic(const "internal error: entered unreachable code") -> unwind continue; } bb2: { - StorageDead(_5); - StorageDead(_2); + StorageDead(_4); return; } } diff --git a/tests/mir-opt/issue_99325.main.built.after.mir b/tests/mir-opt/issue_99325.main.built.after.mir index 0fe66d3fb70..aef89c7f9f7 100644 --- a/tests/mir-opt/issue_99325.main.built.after.mir +++ b/tests/mir-opt/issue_99325.main.built.after.mir @@ -1,8 +1,8 @@ // MIR for `main` after built | User Type Annotations -| 0: user_ty: Canonical { value: TypeOf(DefId(0:3 ~ issue_99325[22bb]::function_with_bytes), UserSubsts { substs: [Const { ty: &'static [u8; 4], kind: Branch([Leaf(0x41), Leaf(0x41), Leaf(0x41), Leaf(0x41)]) }], user_self_ty: None }), max_universe: U0, variables: [] }, span: $DIR/issue_99325.rs:10:16: 10:46, inferred_ty: fn() -> &'static [u8] {function_with_bytes::<&*b"AAAA">} -| 1: user_ty: Canonical { value: TypeOf(DefId(0:3 ~ issue_99325[22bb]::function_with_bytes), UserSubsts { substs: [Const { ty: &'static [u8; 4], kind: UnevaluatedConst { def: DefId(0:8 ~ issue_99325[22bb]::main::{constant#1}), substs: [] } }], user_self_ty: None }), max_universe: U0, variables: [] }, span: $DIR/issue_99325.rs:11:16: 11:68, inferred_ty: fn() -> &'static [u8] {function_with_bytes::<&*b"AAAA">} +| 0: user_ty: Canonical { value: TypeOf(DefId(0:3 ~ issue_99325[22bb]::function_with_bytes), UserArgs { args: [Const { ty: &'static [u8; 4], kind: Branch([Leaf(0x41), Leaf(0x41), Leaf(0x41), Leaf(0x41)]) }], user_self_ty: None }), max_universe: U0, variables: [] }, span: $DIR/issue_99325.rs:10:16: 10:46, inferred_ty: fn() -> &'static [u8] {function_with_bytes::<&*b"AAAA">} +| 1: user_ty: Canonical { value: TypeOf(DefId(0:3 ~ issue_99325[22bb]::function_with_bytes), UserArgs { args: [Const { ty: &'static [u8; 4], kind: UnevaluatedConst { def: DefId(0:8 ~ issue_99325[22bb]::main::{constant#1}), args: [] } }], user_self_ty: None }), max_universe: U0, variables: [] }, span: $DIR/issue_99325.rs:11:16: 11:68, inferred_ty: fn() -> &'static [u8] {function_with_bytes::<&*b"AAAA">} | fn main() -> () { let mut _0: (); diff --git a/tests/mir-opt/issues/issue_59352.num_to_digit.PreCodegen.after.panic-abort.mir b/tests/mir-opt/issues/issue_59352.num_to_digit.PreCodegen.after.panic-abort.mir index 787f9ee095f..9743e192462 100644 --- a/tests/mir-opt/issues/issue_59352.num_to_digit.PreCodegen.after.panic-abort.mir +++ b/tests/mir-opt/issues/issue_59352.num_to_digit.PreCodegen.after.panic-abort.mir @@ -3,57 +3,53 @@ fn num_to_digit(_1: char) -> u32 { debug num => _1; let mut _0: u32; - let mut _5: std::option::Option<u32>; + let mut _4: std::option::Option<u32>; scope 1 (inlined char::methods::<impl char>::is_digit) { debug self => _1; debug radix => const 8_u32; let _2: std::option::Option<u32>; - let mut _3: &std::option::Option<u32>; scope 2 (inlined Option::<u32>::is_some) { - debug self => _3; - let mut _4: isize; + debug self => &_2; + let mut _3: isize; } } scope 3 (inlined #[track_caller] Option::<u32>::unwrap) { - debug self => _5; - let mut _6: isize; - let mut _7: !; + debug self => _4; + let mut _5: isize; + let mut _6: !; scope 4 { debug val => _0; } } bb0: { - StorageLive(_3); StorageLive(_2); _2 = char::methods::<impl char>::to_digit(_1, const 8_u32) -> [return: bb1, unwind unreachable]; } bb1: { - _3 = &_2; - _4 = discriminant((*_3)); - StorageDead(_3); + _3 = discriminant(_2); StorageDead(_2); - switchInt(move _4) -> [1: bb2, otherwise: bb7]; + switchInt(move _3) -> [1: bb2, otherwise: bb7]; } bb2: { - StorageLive(_5); - _5 = char::methods::<impl char>::to_digit(_1, const 8_u32) -> [return: bb3, unwind unreachable]; + StorageLive(_4); + _4 = char::methods::<impl char>::to_digit(_1, const 8_u32) -> [return: bb3, unwind unreachable]; } bb3: { - _6 = discriminant(_5); - switchInt(move _6) -> [0: bb4, 1: bb5, otherwise: bb6]; + _5 = discriminant(_4); + switchInt(move _5) -> [0: bb4, 1: bb5, otherwise: bb6]; } bb4: { - _7 = core::panicking::panic(const "called `Option::unwrap()` on a `None` value") -> unwind unreachable; + _6 = core::panicking::panic(const "called `Option::unwrap()` on a `None` value") -> unwind unreachable; } bb5: { - _0 = move ((_5 as Some).0: u32); - StorageDead(_5); + _0 = move ((_4 as Some).0: u32); + StorageDead(_4); goto -> bb8; } diff --git a/tests/mir-opt/issues/issue_59352.num_to_digit.PreCodegen.after.panic-unwind.mir b/tests/mir-opt/issues/issue_59352.num_to_digit.PreCodegen.after.panic-unwind.mir index 43a1a1eed20..e89d6eb4d50 100644 --- a/tests/mir-opt/issues/issue_59352.num_to_digit.PreCodegen.after.panic-unwind.mir +++ b/tests/mir-opt/issues/issue_59352.num_to_digit.PreCodegen.after.panic-unwind.mir @@ -3,57 +3,53 @@ fn num_to_digit(_1: char) -> u32 { debug num => _1; let mut _0: u32; - let mut _5: std::option::Option<u32>; + let mut _4: std::option::Option<u32>; scope 1 (inlined char::methods::<impl char>::is_digit) { debug self => _1; debug radix => const 8_u32; let _2: std::option::Option<u32>; - let mut _3: &std::option::Option<u32>; scope 2 (inlined Option::<u32>::is_some) { - debug self => _3; - let mut _4: isize; + debug self => &_2; + let mut _3: isize; } } scope 3 (inlined #[track_caller] Option::<u32>::unwrap) { - debug self => _5; - let mut _6: isize; - let mut _7: !; + debug self => _4; + let mut _5: isize; + let mut _6: !; scope 4 { debug val => _0; } } bb0: { - StorageLive(_3); StorageLive(_2); _2 = char::methods::<impl char>::to_digit(_1, const 8_u32) -> [return: bb1, unwind continue]; } bb1: { - _3 = &_2; - _4 = discriminant((*_3)); - StorageDead(_3); + _3 = discriminant(_2); StorageDead(_2); - switchInt(move _4) -> [1: bb2, otherwise: bb7]; + switchInt(move _3) -> [1: bb2, otherwise: bb7]; } bb2: { - StorageLive(_5); - _5 = char::methods::<impl char>::to_digit(_1, const 8_u32) -> [return: bb3, unwind continue]; + StorageLive(_4); + _4 = char::methods::<impl char>::to_digit(_1, const 8_u32) -> [return: bb3, unwind continue]; } bb3: { - _6 = discriminant(_5); - switchInt(move _6) -> [0: bb4, 1: bb5, otherwise: bb6]; + _5 = discriminant(_4); + switchInt(move _5) -> [0: bb4, 1: bb5, otherwise: bb6]; } bb4: { - _7 = core::panicking::panic(const "called `Option::unwrap()` on a `None` value") -> unwind continue; + _6 = core::panicking::panic(const "called `Option::unwrap()` on a `None` value") -> unwind continue; } bb5: { - _0 = move ((_5 as Some).0: u32); - StorageDead(_5); + _0 = move ((_4 as Some).0: u32); + StorageDead(_4); goto -> bb8; } diff --git a/tests/mir-opt/pre-codegen/checked_ops.step_forward.PreCodegen.after.mir b/tests/mir-opt/pre-codegen/checked_ops.step_forward.PreCodegen.after.mir index 98c267e8e71..9be41bff3ca 100644 --- a/tests/mir-opt/pre-codegen/checked_ops.step_forward.PreCodegen.after.mir +++ b/tests/mir-opt/pre-codegen/checked_ops.step_forward.PreCodegen.after.mir @@ -8,42 +8,38 @@ fn step_forward(_1: u32, _2: usize) -> u32 { debug start => _1; debug n => _2; let _3: std::option::Option<u32>; - let mut _4: &std::option::Option<u32>; - let mut _7: bool; - let mut _8: u32; + let mut _6: bool; + let mut _7: u32; scope 2 { } scope 3 (inlined Option::<u32>::is_none) { - debug self => _4; - let mut _6: bool; + debug self => &_3; + let mut _5: bool; scope 4 (inlined Option::<u32>::is_some) { - debug self => _4; - let mut _5: isize; + debug self => &_3; + let mut _4: isize; } } scope 5 (inlined core::num::<impl u32>::wrapping_add) { debug self => _1; - debug rhs => _8; + debug rhs => _7; } } bb0: { - StorageLive(_7); - StorageLive(_4); + StorageLive(_6); StorageLive(_3); _3 = <u32 as Step>::forward_checked(_1, _2) -> [return: bb1, unwind continue]; } bb1: { - _4 = &_3; - StorageLive(_6); - _5 = discriminant((*_4)); - _6 = Eq(_5, const 1_isize); - _7 = Not(move _6); - StorageDead(_6); + StorageLive(_5); + _4 = discriminant(_3); + _5 = Eq(_4, const 1_isize); + _6 = Not(move _5); + StorageDead(_5); StorageDead(_3); - StorageDead(_4); - switchInt(move _7) -> [0: bb3, otherwise: bb2]; + switchInt(move _6) -> [0: bb3, otherwise: bb2]; } bb2: { @@ -51,11 +47,11 @@ fn step_forward(_1: u32, _2: usize) -> u32 { } bb3: { + StorageDead(_6); + StorageLive(_7); + _7 = _2 as u32 (IntToInt); + _0 = Add(_1, _7); StorageDead(_7); - StorageLive(_8); - _8 = _2 as u32 (IntToInt); - _0 = Add(_1, _8); - StorageDead(_8); return; } } diff --git a/tests/mir-opt/pre-codegen/loops.filter_mapped.PreCodegen.after.mir b/tests/mir-opt/pre-codegen/loops.filter_mapped.PreCodegen.after.mir index 3b49cb711b7..07a57a7b578 100644 --- a/tests/mir-opt/pre-codegen/loops.filter_mapped.PreCodegen.after.mir +++ b/tests/mir-opt/pre-codegen/loops.filter_mapped.PreCodegen.after.mir @@ -7,20 +7,19 @@ fn filter_mapped(_1: impl Iterator<Item = T>, _2: impl Fn(T) -> Option<U>) -> () let mut _3: std::iter::FilterMap<impl Iterator<Item = T>, impl Fn(T) -> Option<U>>; let mut _4: std::iter::FilterMap<impl Iterator<Item = T>, impl Fn(T) -> Option<U>>; let mut _5: std::iter::FilterMap<impl Iterator<Item = T>, impl Fn(T) -> Option<U>>; - let mut _6: &mut std::iter::FilterMap<impl Iterator<Item = T>, impl Fn(T) -> Option<U>>; - let mut _9: std::option::Option<U>; - let mut _10: isize; - let _12: (); + let mut _8: std::option::Option<U>; + let mut _9: isize; + let _11: (); scope 1 { debug iter => _5; - let _11: U; + let _10: U; scope 2 { - debug x => _11; + debug x => _10; } scope 4 (inlined <FilterMap<impl Iterator<Item = T>, impl Fn(T) -> Option<U>> as Iterator>::next) { - debug self => _6; - let mut _7: &mut impl Iterator<Item = T>; - let mut _8: &mut impl Fn(T) -> Option<U>; + debug self => &_5; + let mut _6: &mut impl Iterator<Item = T>; + let mut _7: &mut impl Fn(T) -> Option<U>; } } scope 3 (inlined <FilterMap<impl Iterator<Item = T>, impl Fn(T) -> Option<U>> as IntoIterator>::into_iter) { @@ -42,24 +41,23 @@ fn filter_mapped(_1: impl Iterator<Item = T>, _2: impl Fn(T) -> Option<U>) -> () } bb2: { - StorageLive(_9); - _6 = &mut _5; - StorageLive(_7); - _7 = &mut ((*_6).0: impl Iterator<Item = T>); StorageLive(_8); - _8 = &mut ((*_6).1: impl Fn(T) -> Option<U>); - _9 = <impl Iterator<Item = T> as Iterator>::find_map::<U, &mut impl Fn(T) -> Option<U>>(move _7, move _8) -> [return: bb3, unwind: bb9]; + StorageLive(_6); + _6 = &mut (_5.0: impl Iterator<Item = T>); + StorageLive(_7); + _7 = &mut (_5.1: impl Fn(T) -> Option<U>); + _8 = <impl Iterator<Item = T> as Iterator>::find_map::<U, &mut impl Fn(T) -> Option<U>>(move _6, move _7) -> [return: bb3, unwind: bb9]; } bb3: { - StorageDead(_8); StorageDead(_7); - _10 = discriminant(_9); - switchInt(move _10) -> [0: bb4, 1: bb6, otherwise: bb8]; + StorageDead(_6); + _9 = discriminant(_8); + switchInt(move _9) -> [0: bb4, 1: bb6, otherwise: bb8]; } bb4: { - StorageDead(_9); + StorageDead(_8); drop(_5) -> [return: bb5, unwind continue]; } @@ -70,12 +68,12 @@ fn filter_mapped(_1: impl Iterator<Item = T>, _2: impl Fn(T) -> Option<U>) -> () } bb6: { - _11 = move ((_9 as Some).0: U); - _12 = opaque::<U>(move _11) -> [return: bb7, unwind: bb9]; + _10 = move ((_8 as Some).0: U); + _11 = opaque::<U>(move _10) -> [return: bb7, unwind: bb9]; } bb7: { - StorageDead(_9); + StorageDead(_8); goto -> bb2; } diff --git a/tests/mir-opt/pre-codegen/loops.int_range.PreCodegen.after.mir b/tests/mir-opt/pre-codegen/loops.int_range.PreCodegen.after.mir index 40bb3a37c58..99dc9600e41 100644 --- a/tests/mir-opt/pre-codegen/loops.int_range.PreCodegen.after.mir +++ b/tests/mir-opt/pre-codegen/loops.int_range.PreCodegen.after.mir @@ -4,111 +4,95 @@ fn int_range(_1: usize, _2: usize) -> () { debug start => _1; debug end => _2; let mut _0: (); - let mut _3: std::ops::Range<usize>; - let mut _4: std::ops::Range<usize>; - let mut _5: &mut std::ops::Range<usize>; - let mut _11: std::option::Option<usize>; - let mut _14: isize; - let _16: (); + let mut _3: usize; + let mut _6: std::option::Option<usize>; + let mut _9: isize; + let _11: (); scope 1 { - debug iter => _4; - let _15: usize; + debug iter => std::ops::Range<usize>{ .0 => _3, .1 => _2, }; + let _10: usize; scope 2 { - debug i => _15; + debug i => _10; } scope 4 (inlined iter::range::<impl Iterator for std::ops::Range<usize>>::next) { - debug self => _5; + debug self => &std::ops::Range<usize>{ .0 => _3, .1 => _2, }; scope 5 (inlined <std::ops::Range<usize> as iter::range::RangeIteratorImpl>::spec_next) { - debug self => _5; - let mut _6: &usize; - let mut _7: &usize; - let mut _10: bool; - let _12: usize; - let mut _13: usize; + debug self => &std::ops::Range<usize>{ .0 => _3, .1 => _2, }; + let mut _5: bool; + let _7: usize; + let mut _8: usize; scope 6 { - debug old => _12; + debug old => _7; scope 7 { } } scope 8 (inlined cmp::impls::<impl PartialOrd for usize>::lt) { - debug self => _6; - debug other => _7; - let mut _8: usize; - let mut _9: usize; + debug self => &_3; + debug other => &_2; + let mut _4: usize; } } } } scope 3 (inlined <std::ops::Range<usize> as IntoIterator>::into_iter) { - debug self => _3; + debug self => std::ops::Range<usize>{ .0 => _1, .1 => _2, }; } bb0: { - _3 = std::ops::Range::<usize> { start: _1, end: _2 }; - StorageLive(_4); - _4 = move _3; + StorageLive(_3); + _3 = _1; goto -> bb1; } bb1: { - StorageLive(_11); - _5 = &mut _4; - StorageLive(_12); - StorageLive(_10); StorageLive(_6); - _6 = &((*_5).0: usize); StorageLive(_7); - _7 = &((*_5).1: usize); - StorageLive(_8); - _8 = (*_6); - StorageLive(_9); - _9 = (*_7); - _10 = Lt(move _8, move _9); - StorageDead(_9); - StorageDead(_8); - StorageDead(_7); - StorageDead(_6); - switchInt(move _10) -> [0: bb2, otherwise: bb3]; + StorageLive(_5); + StorageLive(_4); + _4 = _3; + _5 = Lt(move _4, _2); + StorageDead(_4); + switchInt(move _5) -> [0: bb2, otherwise: bb3]; } bb2: { - _11 = Option::<usize>::None; + _6 = Option::<usize>::None; goto -> bb5; } bb3: { - _12 = ((*_5).0: usize); - StorageLive(_13); - _13 = <usize as Step>::forward_unchecked(_12, const 1_usize) -> [return: bb4, unwind continue]; + _7 = _3; + StorageLive(_8); + _8 = <usize as Step>::forward_unchecked(_7, const 1_usize) -> [return: bb4, unwind continue]; } bb4: { - ((*_5).0: usize) = move _13; - StorageDead(_13); - _11 = Option::<usize>::Some(_12); + _3 = move _8; + StorageDead(_8); + _6 = Option::<usize>::Some(_7); goto -> bb5; } bb5: { - StorageDead(_10); - StorageDead(_12); - _14 = discriminant(_11); - switchInt(move _14) -> [0: bb6, 1: bb7, otherwise: bb9]; + StorageDead(_5); + StorageDead(_7); + _9 = discriminant(_6); + switchInt(move _9) -> [0: bb6, 1: bb7, otherwise: bb9]; } bb6: { - StorageDead(_11); - StorageDead(_4); + StorageDead(_6); + StorageDead(_3); return; } bb7: { - _15 = ((_11 as Some).0: usize); - _16 = opaque::<usize>(_15) -> [return: bb8, unwind continue]; + _10 = ((_6 as Some).0: usize); + _11 = opaque::<usize>(_10) -> [return: bb8, unwind continue]; } bb8: { - StorageDead(_11); + StorageDead(_6); goto -> bb1; } diff --git a/tests/mir-opt/pre-codegen/loops.mapped.PreCodegen.after.mir b/tests/mir-opt/pre-codegen/loops.mapped.PreCodegen.after.mir index e4e1d052e73..2614160363e 100644 --- a/tests/mir-opt/pre-codegen/loops.mapped.PreCodegen.after.mir +++ b/tests/mir-opt/pre-codegen/loops.mapped.PreCodegen.after.mir @@ -38,11 +38,13 @@ fn mapped(_1: impl Iterator<Item = T>, _2: impl Fn(T) -> U) -> () { bb2: { StorageLive(_7); + StorageLive(_6); _6 = &mut _5; - _7 = <Map<impl Iterator<Item = T>, impl Fn(T) -> U> as Iterator>::next(_6) -> [return: bb3, unwind: bb9]; + _7 = <Map<impl Iterator<Item = T>, impl Fn(T) -> U> as Iterator>::next(move _6) -> [return: bb3, unwind: bb9]; } bb3: { + StorageDead(_6); _8 = discriminant(_7); switchInt(move _8) -> [0: bb4, 1: bb6, otherwise: bb8]; } diff --git a/tests/mir-opt/pre-codegen/loops.vec_move.PreCodegen.after.mir b/tests/mir-opt/pre-codegen/loops.vec_move.PreCodegen.after.mir index 1b5f2a0884b..8eff46fb931 100644 --- a/tests/mir-opt/pre-codegen/loops.vec_move.PreCodegen.after.mir +++ b/tests/mir-opt/pre-codegen/loops.vec_move.PreCodegen.after.mir @@ -30,11 +30,13 @@ fn vec_move(_1: Vec<impl Sized>) -> () { bb2: { StorageLive(_5); + StorageLive(_4); _4 = &mut _3; - _5 = <std::vec::IntoIter<impl Sized> as Iterator>::next(_4) -> [return: bb3, unwind: bb9]; + _5 = <std::vec::IntoIter<impl Sized> as Iterator>::next(move _4) -> [return: bb3, unwind: bb9]; } bb3: { + StorageDead(_4); _6 = discriminant(_5); switchInt(move _6) -> [0: bb4, 1: bb6, otherwise: bb8]; } diff --git a/tests/mir-opt/pre-codegen/mem_replace.mem_replace.PreCodegen.after.mir b/tests/mir-opt/pre-codegen/mem_replace.mem_replace.PreCodegen.after.mir index dde7a618881..eeb2e3a1b03 100644 --- a/tests/mir-opt/pre-codegen/mem_replace.mem_replace.PreCodegen.after.mir +++ b/tests/mir-opt/pre-codegen/mem_replace.mem_replace.PreCodegen.after.mir @@ -7,26 +7,24 @@ fn mem_replace(_1: &mut u32, _2: u32) -> u32 { scope 1 (inlined std::mem::replace::<u32>) { debug dest => _1; debug src => _2; - let mut _3: *const u32; - let mut _4: *mut u32; scope 2 { scope 3 { debug result => _0; scope 7 (inlined std::ptr::write::<u32>) { - debug dst => _4; + debug dst => _1; debug src => _2; scope 8 { scope 9 (inlined std::ptr::write::runtime::<u32>) { - debug dst => _4; + debug dst => _1; } } } } scope 4 (inlined std::ptr::read::<u32>) { - debug src => _3; + debug src => _1; scope 5 { scope 6 (inlined std::ptr::read::runtime::<u32>) { - debug src => _3; + debug src => _1; } } } @@ -34,14 +32,8 @@ fn mem_replace(_1: &mut u32, _2: u32) -> u32 { } bb0: { - StorageLive(_3); - _3 = &raw const (*_1); - _0 = (*_3); - StorageDead(_3); - StorageLive(_4); - _4 = &raw mut (*_1); - (*_4) = _2; - StorageDead(_4); + _0 = (*_1); + (*_1) = _2; return; } } diff --git a/tests/mir-opt/pre-codegen/range_iter.forward_loop.PreCodegen.after.panic-abort.mir b/tests/mir-opt/pre-codegen/range_iter.forward_loop.PreCodegen.after.panic-abort.mir index 2344a3c0f83..cdaa3cfc995 100644 --- a/tests/mir-opt/pre-codegen/range_iter.forward_loop.PreCodegen.after.panic-abort.mir +++ b/tests/mir-opt/pre-codegen/range_iter.forward_loop.PreCodegen.after.panic-abort.mir @@ -5,103 +5,87 @@ fn forward_loop(_1: u32, _2: u32, _3: impl Fn(u32)) -> () { debug end => _2; debug f => _3; let mut _0: (); - let mut _4: std::ops::Range<u32>; - let mut _5: std::ops::Range<u32>; - let mut _6: &mut std::ops::Range<u32>; - let mut _12: std::option::Option<u32>; - let mut _15: isize; - let mut _17: &impl Fn(u32); - let mut _18: (u32,); - let _19: (); + let mut _4: u32; + let mut _7: std::option::Option<u32>; + let mut _10: isize; + let mut _12: &impl Fn(u32); + let mut _13: (u32,); + let _14: (); scope 1 { - debug iter => _5; - let _16: u32; + debug iter => std::ops::Range<u32>{ .0 => _4, .1 => _2, }; + let _11: u32; scope 2 { - debug x => _16; + debug x => _11; } scope 4 (inlined iter::range::<impl Iterator for std::ops::Range<u32>>::next) { - debug self => _6; + debug self => &std::ops::Range<u32>{ .0 => _4, .1 => _2, }; scope 5 (inlined <std::ops::Range<u32> as iter::range::RangeIteratorImpl>::spec_next) { - debug self => _6; - let mut _7: &u32; - let mut _8: &u32; - let mut _11: bool; - let _13: u32; - let mut _14: u32; + debug self => &std::ops::Range<u32>{ .0 => _4, .1 => _2, }; + let mut _6: bool; + let _8: u32; + let mut _9: u32; scope 6 { - debug old => _13; + debug old => _8; scope 7 { } } scope 8 (inlined cmp::impls::<impl PartialOrd for u32>::lt) { - debug self => _7; - debug other => _8; - let mut _9: u32; - let mut _10: u32; + debug self => &_4; + debug other => &_2; + let mut _5: u32; } } } } scope 3 (inlined <std::ops::Range<u32> as IntoIterator>::into_iter) { - debug self => _4; + debug self => std::ops::Range<u32>{ .0 => _1, .1 => _2, }; } bb0: { - _4 = std::ops::Range::<u32> { start: _1, end: _2 }; - StorageLive(_5); - _5 = move _4; + StorageLive(_4); + _4 = _1; goto -> bb1; } bb1: { - StorageLive(_12); - _6 = &mut _5; - StorageLive(_13); - StorageLive(_11); StorageLive(_7); - _7 = &((*_6).0: u32); StorageLive(_8); - _8 = &((*_6).1: u32); - StorageLive(_9); - _9 = (*_7); - StorageLive(_10); - _10 = (*_8); - _11 = Lt(move _9, move _10); - StorageDead(_10); - StorageDead(_9); - StorageDead(_8); - StorageDead(_7); - switchInt(move _11) -> [0: bb2, otherwise: bb3]; + StorageLive(_6); + StorageLive(_5); + _5 = _4; + _6 = Lt(move _5, _2); + StorageDead(_5); + switchInt(move _6) -> [0: bb2, otherwise: bb3]; } bb2: { - _12 = Option::<u32>::None; + _7 = Option::<u32>::None; goto -> bb5; } bb3: { - _13 = ((*_6).0: u32); - StorageLive(_14); - _14 = <u32 as Step>::forward_unchecked(_13, const 1_usize) -> [return: bb4, unwind unreachable]; + _8 = _4; + StorageLive(_9); + _9 = <u32 as Step>::forward_unchecked(_8, const 1_usize) -> [return: bb4, unwind unreachable]; } bb4: { - ((*_6).0: u32) = move _14; - StorageDead(_14); - _12 = Option::<u32>::Some(_13); + _4 = move _9; + StorageDead(_9); + _7 = Option::<u32>::Some(_8); goto -> bb5; } bb5: { - StorageDead(_11); - StorageDead(_13); - _15 = discriminant(_12); - switchInt(move _15) -> [0: bb6, 1: bb8, otherwise: bb10]; + StorageDead(_6); + StorageDead(_8); + _10 = discriminant(_7); + switchInt(move _10) -> [0: bb6, 1: bb8, otherwise: bb10]; } bb6: { - StorageDead(_12); - StorageDead(_5); + StorageDead(_7); + StorageDead(_4); drop(_3) -> [return: bb7, unwind unreachable]; } @@ -110,18 +94,18 @@ fn forward_loop(_1: u32, _2: u32, _3: impl Fn(u32)) -> () { } bb8: { - _16 = ((_12 as Some).0: u32); - StorageLive(_17); - _17 = &_3; - StorageLive(_18); - _18 = (_16,); - _19 = <impl Fn(u32) as Fn<(u32,)>>::call(move _17, move _18) -> [return: bb9, unwind unreachable]; + _11 = ((_7 as Some).0: u32); + StorageLive(_12); + _12 = &_3; + StorageLive(_13); + _13 = (_11,); + _14 = <impl Fn(u32) as Fn<(u32,)>>::call(move _12, move _13) -> [return: bb9, unwind unreachable]; } bb9: { - StorageDead(_18); - StorageDead(_17); + StorageDead(_13); StorageDead(_12); + StorageDead(_7); goto -> bb1; } diff --git a/tests/mir-opt/pre-codegen/range_iter.forward_loop.PreCodegen.after.panic-unwind.mir b/tests/mir-opt/pre-codegen/range_iter.forward_loop.PreCodegen.after.panic-unwind.mir index fbe16dc3cd4..c4e56ea3b23 100644 --- a/tests/mir-opt/pre-codegen/range_iter.forward_loop.PreCodegen.after.panic-unwind.mir +++ b/tests/mir-opt/pre-codegen/range_iter.forward_loop.PreCodegen.after.panic-unwind.mir @@ -5,103 +5,87 @@ fn forward_loop(_1: u32, _2: u32, _3: impl Fn(u32)) -> () { debug end => _2; debug f => _3; let mut _0: (); - let mut _4: std::ops::Range<u32>; - let mut _5: std::ops::Range<u32>; - let mut _6: &mut std::ops::Range<u32>; - let mut _12: std::option::Option<u32>; - let mut _15: isize; - let mut _17: &impl Fn(u32); - let mut _18: (u32,); - let _19: (); + let mut _4: u32; + let mut _7: std::option::Option<u32>; + let mut _10: isize; + let mut _12: &impl Fn(u32); + let mut _13: (u32,); + let _14: (); scope 1 { - debug iter => _5; - let _16: u32; + debug iter => std::ops::Range<u32>{ .0 => _4, .1 => _2, }; + let _11: u32; scope 2 { - debug x => _16; + debug x => _11; } scope 4 (inlined iter::range::<impl Iterator for std::ops::Range<u32>>::next) { - debug self => _6; + debug self => &std::ops::Range<u32>{ .0 => _4, .1 => _2, }; scope 5 (inlined <std::ops::Range<u32> as iter::range::RangeIteratorImpl>::spec_next) { - debug self => _6; - let mut _7: &u32; - let mut _8: &u32; - let mut _11: bool; - let _13: u32; - let mut _14: u32; + debug self => &std::ops::Range<u32>{ .0 => _4, .1 => _2, }; + let mut _6: bool; + let _8: u32; + let mut _9: u32; scope 6 { - debug old => _13; + debug old => _8; scope 7 { } } scope 8 (inlined cmp::impls::<impl PartialOrd for u32>::lt) { - debug self => _7; - debug other => _8; - let mut _9: u32; - let mut _10: u32; + debug self => &_4; + debug other => &_2; + let mut _5: u32; } } } } scope 3 (inlined <std::ops::Range<u32> as IntoIterator>::into_iter) { - debug self => _4; + debug self => std::ops::Range<u32>{ .0 => _1, .1 => _2, }; } bb0: { - _4 = std::ops::Range::<u32> { start: _1, end: _2 }; - StorageLive(_5); - _5 = move _4; + StorageLive(_4); + _4 = _1; goto -> bb1; } bb1: { - StorageLive(_12); - _6 = &mut _5; - StorageLive(_13); - StorageLive(_11); StorageLive(_7); - _7 = &((*_6).0: u32); StorageLive(_8); - _8 = &((*_6).1: u32); - StorageLive(_9); - _9 = (*_7); - StorageLive(_10); - _10 = (*_8); - _11 = Lt(move _9, move _10); - StorageDead(_10); - StorageDead(_9); - StorageDead(_8); - StorageDead(_7); - switchInt(move _11) -> [0: bb2, otherwise: bb3]; + StorageLive(_6); + StorageLive(_5); + _5 = _4; + _6 = Lt(move _5, _2); + StorageDead(_5); + switchInt(move _6) -> [0: bb2, otherwise: bb3]; } bb2: { - _12 = Option::<u32>::None; + _7 = Option::<u32>::None; goto -> bb5; } bb3: { - _13 = ((*_6).0: u32); - StorageLive(_14); - _14 = <u32 as Step>::forward_unchecked(_13, const 1_usize) -> [return: bb4, unwind: bb11]; + _8 = _4; + StorageLive(_9); + _9 = <u32 as Step>::forward_unchecked(_8, const 1_usize) -> [return: bb4, unwind: bb11]; } bb4: { - ((*_6).0: u32) = move _14; - StorageDead(_14); - _12 = Option::<u32>::Some(_13); + _4 = move _9; + StorageDead(_9); + _7 = Option::<u32>::Some(_8); goto -> bb5; } bb5: { - StorageDead(_11); - StorageDead(_13); - _15 = discriminant(_12); - switchInt(move _15) -> [0: bb6, 1: bb8, otherwise: bb10]; + StorageDead(_6); + StorageDead(_8); + _10 = discriminant(_7); + switchInt(move _10) -> [0: bb6, 1: bb8, otherwise: bb10]; } bb6: { - StorageDead(_12); - StorageDead(_5); + StorageDead(_7); + StorageDead(_4); drop(_3) -> [return: bb7, unwind continue]; } @@ -110,18 +94,18 @@ fn forward_loop(_1: u32, _2: u32, _3: impl Fn(u32)) -> () { } bb8: { - _16 = ((_12 as Some).0: u32); - StorageLive(_17); - _17 = &_3; - StorageLive(_18); - _18 = (_16,); - _19 = <impl Fn(u32) as Fn<(u32,)>>::call(move _17, move _18) -> [return: bb9, unwind: bb11]; + _11 = ((_7 as Some).0: u32); + StorageLive(_12); + _12 = &_3; + StorageLive(_13); + _13 = (_11,); + _14 = <impl Fn(u32) as Fn<(u32,)>>::call(move _12, move _13) -> [return: bb9, unwind: bb11]; } bb9: { - StorageDead(_18); - StorageDead(_17); + StorageDead(_13); StorageDead(_12); + StorageDead(_7); goto -> bb1; } diff --git a/tests/mir-opt/pre-codegen/range_iter.inclusive_loop.PreCodegen.after.panic-abort.mir b/tests/mir-opt/pre-codegen/range_iter.inclusive_loop.PreCodegen.after.panic-abort.mir index 9737c9a87c7..8d306858b43 100644 --- a/tests/mir-opt/pre-codegen/range_iter.inclusive_loop.PreCodegen.after.panic-abort.mir +++ b/tests/mir-opt/pre-codegen/range_iter.inclusive_loop.PreCodegen.after.panic-abort.mir @@ -40,11 +40,13 @@ fn inclusive_loop(_1: u32, _2: u32, _3: impl Fn(u32)) -> () { bb1: { StorageLive(_7); + StorageLive(_6); _6 = &mut _5; _7 = <RangeInclusive<u32> as iter::range::RangeInclusiveIteratorImpl>::spec_next(_6) -> [return: bb2, unwind unreachable]; } bb2: { + StorageDead(_6); _8 = discriminant(_7); switchInt(move _8) -> [0: bb3, 1: bb5, otherwise: bb7]; } diff --git a/tests/mir-opt/pre-codegen/range_iter.inclusive_loop.PreCodegen.after.panic-unwind.mir b/tests/mir-opt/pre-codegen/range_iter.inclusive_loop.PreCodegen.after.panic-unwind.mir index 04d6da1d9bd..e92c054c838 100644 --- a/tests/mir-opt/pre-codegen/range_iter.inclusive_loop.PreCodegen.after.panic-unwind.mir +++ b/tests/mir-opt/pre-codegen/range_iter.inclusive_loop.PreCodegen.after.panic-unwind.mir @@ -40,11 +40,13 @@ fn inclusive_loop(_1: u32, _2: u32, _3: impl Fn(u32)) -> () { bb1: { StorageLive(_7); + StorageLive(_6); _6 = &mut _5; _7 = <RangeInclusive<u32> as iter::range::RangeInclusiveIteratorImpl>::spec_next(_6) -> [return: bb2, unwind: bb8]; } bb2: { + StorageDead(_6); _8 = discriminant(_7); switchInt(move _8) -> [0: bb3, 1: bb5, otherwise: bb7]; } diff --git a/tests/mir-opt/pre-codegen/range_iter.range_iter_next.PreCodegen.after.panic-abort.mir b/tests/mir-opt/pre-codegen/range_iter.range_iter_next.PreCodegen.after.panic-abort.mir index 1dfd00bf314..14fd049ede8 100644 --- a/tests/mir-opt/pre-codegen/range_iter.range_iter_next.PreCodegen.after.panic-abort.mir +++ b/tests/mir-opt/pre-codegen/range_iter.range_iter_next.PreCodegen.after.panic-abort.mir @@ -7,42 +7,34 @@ fn range_iter_next(_1: &mut std::ops::Range<u32>) -> Option<u32> { debug self => _1; scope 2 (inlined <std::ops::Range<u32> as iter::range::RangeIteratorImpl>::spec_next) { debug self => _1; - let mut _2: &u32; - let mut _3: &u32; - let mut _6: bool; - let _7: u32; - let mut _8: u32; + let mut _4: bool; + let _5: u32; + let mut _6: u32; scope 3 { - debug old => _7; + debug old => _5; scope 4 { } } scope 5 (inlined cmp::impls::<impl PartialOrd for u32>::lt) { - debug self => _2; - debug other => _3; - let mut _4: u32; - let mut _5: u32; + debug self => &((*_1).0: u32); + debug other => &((*_1).1: u32); + let mut _2: u32; + let mut _3: u32; } } } bb0: { - StorageLive(_7); - StorageLive(_6); + StorageLive(_5); + StorageLive(_4); StorageLive(_2); - _2 = &((*_1).0: u32); + _2 = ((*_1).0: u32); StorageLive(_3); - _3 = &((*_1).1: u32); - StorageLive(_4); - _4 = (*_2); - StorageLive(_5); - _5 = (*_3); - _6 = Lt(move _4, move _5); - StorageDead(_5); - StorageDead(_4); + _3 = ((*_1).1: u32); + _4 = Lt(move _2, move _3); StorageDead(_3); StorageDead(_2); - switchInt(move _6) -> [0: bb1, otherwise: bb2]; + switchInt(move _4) -> [0: bb1, otherwise: bb2]; } bb1: { @@ -51,21 +43,21 @@ fn range_iter_next(_1: &mut std::ops::Range<u32>) -> Option<u32> { } bb2: { - _7 = ((*_1).0: u32); - StorageLive(_8); - _8 = <u32 as Step>::forward_unchecked(_7, const 1_usize) -> [return: bb3, unwind unreachable]; + _5 = ((*_1).0: u32); + StorageLive(_6); + _6 = <u32 as Step>::forward_unchecked(_5, const 1_usize) -> [return: bb3, unwind unreachable]; } bb3: { - ((*_1).0: u32) = move _8; - StorageDead(_8); - _0 = Option::<u32>::Some(_7); + ((*_1).0: u32) = move _6; + StorageDead(_6); + _0 = Option::<u32>::Some(_5); goto -> bb4; } bb4: { - StorageDead(_6); - StorageDead(_7); + StorageDead(_4); + StorageDead(_5); return; } } diff --git a/tests/mir-opt/pre-codegen/range_iter.range_iter_next.PreCodegen.after.panic-unwind.mir b/tests/mir-opt/pre-codegen/range_iter.range_iter_next.PreCodegen.after.panic-unwind.mir index 65870f693c0..668a2ac1e20 100644 --- a/tests/mir-opt/pre-codegen/range_iter.range_iter_next.PreCodegen.after.panic-unwind.mir +++ b/tests/mir-opt/pre-codegen/range_iter.range_iter_next.PreCodegen.after.panic-unwind.mir @@ -7,42 +7,34 @@ fn range_iter_next(_1: &mut std::ops::Range<u32>) -> Option<u32> { debug self => _1; scope 2 (inlined <std::ops::Range<u32> as iter::range::RangeIteratorImpl>::spec_next) { debug self => _1; - let mut _2: &u32; - let mut _3: &u32; - let mut _6: bool; - let _7: u32; - let mut _8: u32; + let mut _4: bool; + let _5: u32; + let mut _6: u32; scope 3 { - debug old => _7; + debug old => _5; scope 4 { } } scope 5 (inlined cmp::impls::<impl PartialOrd for u32>::lt) { - debug self => _2; - debug other => _3; - let mut _4: u32; - let mut _5: u32; + debug self => &((*_1).0: u32); + debug other => &((*_1).1: u32); + let mut _2: u32; + let mut _3: u32; } } } bb0: { - StorageLive(_7); - StorageLive(_6); + StorageLive(_5); + StorageLive(_4); StorageLive(_2); - _2 = &((*_1).0: u32); + _2 = ((*_1).0: u32); StorageLive(_3); - _3 = &((*_1).1: u32); - StorageLive(_4); - _4 = (*_2); - StorageLive(_5); - _5 = (*_3); - _6 = Lt(move _4, move _5); - StorageDead(_5); - StorageDead(_4); + _3 = ((*_1).1: u32); + _4 = Lt(move _2, move _3); StorageDead(_3); StorageDead(_2); - switchInt(move _6) -> [0: bb1, otherwise: bb2]; + switchInt(move _4) -> [0: bb1, otherwise: bb2]; } bb1: { @@ -51,21 +43,21 @@ fn range_iter_next(_1: &mut std::ops::Range<u32>) -> Option<u32> { } bb2: { - _7 = ((*_1).0: u32); - StorageLive(_8); - _8 = <u32 as Step>::forward_unchecked(_7, const 1_usize) -> [return: bb3, unwind continue]; + _5 = ((*_1).0: u32); + StorageLive(_6); + _6 = <u32 as Step>::forward_unchecked(_5, const 1_usize) -> [return: bb3, unwind continue]; } bb3: { - ((*_1).0: u32) = move _8; - StorageDead(_8); - _0 = Option::<u32>::Some(_7); + ((*_1).0: u32) = move _6; + StorageDead(_6); + _0 = Option::<u32>::Some(_5); goto -> bb4; } bb4: { - StorageDead(_6); - StorageDead(_7); + StorageDead(_4); + StorageDead(_5); return; } } diff --git a/tests/mir-opt/pre-codegen/slice_filter.variant_a-{closure#0}.PreCodegen.after.mir b/tests/mir-opt/pre-codegen/slice_filter.variant_a-{closure#0}.PreCodegen.after.mir index 499bee2ae40..f9b0c85c852 100644 --- a/tests/mir-opt/pre-codegen/slice_filter.variant_a-{closure#0}.PreCodegen.after.mir +++ b/tests/mir-opt/pre-codegen/slice_filter.variant_a-{closure#0}.PreCodegen.after.mir @@ -3,214 +3,138 @@ fn variant_a::{closure#0}(_1: &mut [closure@$DIR/slice_filter.rs:7:25: 7:39], _2: &&(usize, usize, usize, usize)) -> bool { let mut _0: bool; let mut _3: &(usize, usize, usize, usize); - let _4: &usize; + let mut _4: &(usize, usize, usize, usize); let mut _5: &(usize, usize, usize, usize); - let _6: &usize; - let mut _7: &(usize, usize, usize, usize); - let _8: &usize; - let mut _9: &(usize, usize, usize, usize); - let _10: &usize; - let mut _11: &&usize; - let _12: &usize; - let mut _13: &&usize; - let mut _18: bool; - let mut _19: bool; - let mut _20: &&usize; - let _21: &usize; - let mut _22: &&usize; - let mut _27: bool; - let mut _28: &&usize; - let _29: &usize; - let mut _30: &&usize; - let mut _35: bool; - let mut _36: bool; - let mut _37: &&usize; - let _38: &usize; - let mut _39: &&usize; - let mut _44: bool; + let mut _6: &(usize, usize, usize, usize); + let mut _9: bool; + let mut _10: bool; + let mut _13: bool; + let mut _16: bool; + let mut _17: bool; + let mut _20: bool; scope 1 { - debug a => _4; - debug b => _6; - debug c => _8; - debug d => _10; + debug a => &((*_3).0: usize); + debug b => &((*_4).1: usize); + debug c => &((*_5).2: usize); + debug d => &((*_6).3: usize); scope 2 (inlined cmp::impls::<impl PartialOrd for &usize>::le) { - debug self => _11; - debug other => _13; - let mut _14: &usize; - let mut _15: &usize; + debug self => &&((*_3).0: usize); + debug other => &&((*_5).2: usize); scope 3 (inlined cmp::impls::<impl PartialOrd for usize>::le) { - debug self => _14; - debug other => _15; - let mut _16: usize; - let mut _17: usize; + debug self => &((*_3).0: usize); + debug other => &((*_5).2: usize); + let mut _7: usize; + let mut _8: usize; } } scope 4 (inlined cmp::impls::<impl PartialOrd for &usize>::le) { - debug self => _28; - debug other => _30; - let mut _31: &usize; - let mut _32: &usize; + debug self => &&((*_5).2: usize); + debug other => &&((*_3).0: usize); scope 5 (inlined cmp::impls::<impl PartialOrd for usize>::le) { - debug self => _31; - debug other => _32; - let mut _33: usize; - let mut _34: usize; + debug self => &((*_5).2: usize); + debug other => &((*_3).0: usize); + let mut _14: usize; + let mut _15: usize; } } scope 6 (inlined cmp::impls::<impl PartialOrd for &usize>::le) { - debug self => _20; - debug other => _22; - let mut _23: &usize; - let mut _24: &usize; + debug self => &&((*_6).3: usize); + debug other => &&((*_4).1: usize); scope 7 (inlined cmp::impls::<impl PartialOrd for usize>::le) { - debug self => _23; - debug other => _24; - let mut _25: usize; - let mut _26: usize; + debug self => &((*_6).3: usize); + debug other => &((*_4).1: usize); + let mut _11: usize; + let mut _12: usize; } } scope 8 (inlined cmp::impls::<impl PartialOrd for &usize>::le) { - debug self => _37; - debug other => _39; - let mut _40: &usize; - let mut _41: &usize; + debug self => &&((*_4).1: usize); + debug other => &&((*_6).3: usize); scope 9 (inlined cmp::impls::<impl PartialOrd for usize>::le) { - debug self => _40; - debug other => _41; - let mut _42: usize; - let mut _43: usize; + debug self => &((*_4).1: usize); + debug other => &((*_6).3: usize); + let mut _18: usize; + let mut _19: usize; } } } bb0: { - StorageLive(_4); _3 = deref_copy (*_2); - _4 = &((*_3).0: usize); - StorageLive(_6); + _4 = deref_copy (*_2); _5 = deref_copy (*_2); - _6 = &((*_5).1: usize); - StorageLive(_8); - _7 = deref_copy (*_2); - _8 = &((*_7).2: usize); + _6 = deref_copy (*_2); StorageLive(_10); - _9 = deref_copy (*_2); - _10 = &((*_9).3: usize); - StorageLive(_19); - StorageLive(_18); - StorageLive(_11); - _11 = &_4; - StorageLive(_13); - StorageLive(_12); - _12 = _8; - _13 = &_12; - _14 = deref_copy (*_11); - _15 = deref_copy (*_13); - StorageLive(_16); - _16 = (*_14); - StorageLive(_17); - _17 = (*_15); - _18 = Le(move _16, move _17); - StorageDead(_17); - StorageDead(_16); - StorageDead(_12); - StorageDead(_13); - StorageDead(_11); - switchInt(move _18) -> [0: bb1, otherwise: bb2]; + StorageLive(_9); + StorageLive(_7); + _7 = ((*_3).0: usize); + StorageLive(_8); + _8 = ((*_5).2: usize); + _9 = Le(move _7, move _8); + StorageDead(_8); + StorageDead(_7); + switchInt(move _9) -> [0: bb1, otherwise: bb2]; } bb1: { - _19 = const false; + _10 = const false; goto -> bb3; } bb2: { - StorageLive(_27); - StorageLive(_20); - _20 = &_10; - StorageLive(_22); - StorageLive(_21); - _21 = _6; - _22 = &_21; - _23 = deref_copy (*_20); - _24 = deref_copy (*_22); - StorageLive(_25); - _25 = (*_23); - StorageLive(_26); - _26 = (*_24); - _27 = Le(move _25, move _26); - StorageDead(_26); - StorageDead(_25); - StorageDead(_21); - StorageDead(_22); - StorageDead(_20); - _19 = move _27; + StorageLive(_13); + StorageLive(_11); + _11 = ((*_6).3: usize); + StorageLive(_12); + _12 = ((*_4).1: usize); + _13 = Le(move _11, move _12); + StorageDead(_12); + StorageDead(_11); + _10 = move _13; goto -> bb3; } bb3: { - StorageDead(_27); - StorageDead(_18); - switchInt(move _19) -> [0: bb4, otherwise: bb8]; + StorageDead(_13); + StorageDead(_9); + switchInt(move _10) -> [0: bb4, otherwise: bb8]; } bb4: { - StorageLive(_36); - StorageLive(_35); - StorageLive(_28); - _28 = &_8; - StorageLive(_30); - StorageLive(_29); - _29 = _4; - _30 = &_29; - _31 = deref_copy (*_28); - _32 = deref_copy (*_30); - StorageLive(_33); - _33 = (*_31); - StorageLive(_34); - _34 = (*_32); - _35 = Le(move _33, move _34); - StorageDead(_34); - StorageDead(_33); - StorageDead(_29); - StorageDead(_30); - StorageDead(_28); - switchInt(move _35) -> [0: bb5, otherwise: bb6]; + StorageLive(_17); + StorageLive(_16); + StorageLive(_14); + _14 = ((*_5).2: usize); + StorageLive(_15); + _15 = ((*_3).0: usize); + _16 = Le(move _14, move _15); + StorageDead(_15); + StorageDead(_14); + switchInt(move _16) -> [0: bb5, otherwise: bb6]; } bb5: { - _36 = const false; + _17 = const false; goto -> bb7; } bb6: { - StorageLive(_44); - StorageLive(_37); - _37 = &_6; - StorageLive(_39); - StorageLive(_38); - _38 = _10; - _39 = &_38; - _40 = deref_copy (*_37); - _41 = deref_copy (*_39); - StorageLive(_42); - _42 = (*_40); - StorageLive(_43); - _43 = (*_41); - _44 = Le(move _42, move _43); - StorageDead(_43); - StorageDead(_42); - StorageDead(_38); - StorageDead(_39); - StorageDead(_37); - _36 = move _44; + StorageLive(_20); + StorageLive(_18); + _18 = ((*_4).1: usize); + StorageLive(_19); + _19 = ((*_6).3: usize); + _20 = Le(move _18, move _19); + StorageDead(_19); + StorageDead(_18); + _17 = move _20; goto -> bb7; } bb7: { - StorageDead(_44); - StorageDead(_35); - _0 = move _36; + StorageDead(_20); + StorageDead(_16); + _0 = move _17; goto -> bb9; } @@ -220,12 +144,8 @@ fn variant_a::{closure#0}(_1: &mut [closure@$DIR/slice_filter.rs:7:25: 7:39], _2 } bb9: { - StorageDead(_36); - StorageDead(_19); + StorageDead(_17); StorageDead(_10); - StorageDead(_8); - StorageDead(_6); - StorageDead(_4); return; } } diff --git a/tests/mir-opt/pre-codegen/slice_index.slice_get_mut_usize.PreCodegen.after.panic-abort.mir b/tests/mir-opt/pre-codegen/slice_index.slice_get_mut_usize.PreCodegen.after.panic-abort.mir index 65416d09053..07a58309ee4 100644 --- a/tests/mir-opt/pre-codegen/slice_index.slice_get_mut_usize.PreCodegen.after.panic-abort.mir +++ b/tests/mir-opt/pre-codegen/slice_index.slice_get_mut_usize.PreCodegen.after.panic-abort.mir @@ -10,38 +10,37 @@ fn slice_get_mut_usize(_1: &mut [u32], _2: usize) -> Option<&mut u32> { scope 2 (inlined <usize as SliceIndex<[u32]>>::get_mut) { debug self => _2; debug slice => _1; - let mut _3: &[u32]; - let mut _4: usize; - let mut _5: bool; - let mut _6: *mut [u32]; - let mut _8: *mut u32; - let mut _9: &mut u32; + let mut _3: usize; + let mut _4: bool; + let mut _5: *mut [u32]; + let mut _7: *mut u32; + let mut _8: &mut u32; scope 3 { scope 4 (inlined <usize as SliceIndex<[u32]>>::get_unchecked_mut) { debug self => _2; - debug slice => _6; - let mut _7: *mut u32; + debug slice => _5; + let mut _6: *mut u32; scope 5 { debug this => _2; scope 6 { scope 7 (inlined <usize as SliceIndex<[T]>>::get_unchecked_mut::runtime::<u32>) { debug this => _2; - debug slice => _6; + debug slice => _5; scope 8 (inlined ptr::mut_ptr::<impl *mut [u32]>::len) { - debug self => _6; - let mut _10: *const [u32]; + debug self => _5; + let mut _9: *const [u32]; scope 9 (inlined std::ptr::metadata::<[u32]>) { - debug ptr => _10; + debug ptr => _9; scope 10 { } } } } scope 11 (inlined ptr::mut_ptr::<impl *mut [u32]>::as_mut_ptr) { - debug self => _6; + debug self => _5; } scope 12 (inlined ptr::mut_ptr::<impl *mut u32>::add) { - debug self => _7; + debug self => _6; debug count => _2; scope 13 { } @@ -54,16 +53,13 @@ fn slice_get_mut_usize(_1: &mut [u32], _2: usize) -> Option<&mut u32> { } bb0: { - StorageLive(_9); - StorageLive(_5); + StorageLive(_7); StorageLive(_4); StorageLive(_3); - _3 = &(*_1); - _4 = Len((*_3)); + _3 = Len((*_1)); + _4 = Lt(_2, move _3); StorageDead(_3); - _5 = Lt(_2, move _4); - StorageDead(_4); - switchInt(move _5) -> [0: bb1, otherwise: bb2]; + switchInt(move _4) -> [0: bb1, otherwise: bb2]; } bb1: { @@ -73,24 +69,24 @@ fn slice_get_mut_usize(_1: &mut [u32], _2: usize) -> Option<&mut u32> { bb2: { StorageLive(_8); + StorageLive(_5); + _5 = &raw mut (*_1); + StorageLive(_9); StorageLive(_6); - _6 = &raw mut (*_1); - StorageLive(_10); - StorageLive(_7); - _7 = _6 as *mut u32 (PtrToPtr); - _8 = Offset(_7, _2); - StorageDead(_7); - StorageDead(_10); + _6 = _5 as *mut u32 (PtrToPtr); + _7 = Offset(_6, _2); StorageDead(_6); - _9 = &mut (*_8); - _0 = Option::<&mut u32>::Some(_9); + StorageDead(_9); + StorageDead(_5); + _8 = &mut (*_7); + _0 = Option::<&mut u32>::Some(move _8); StorageDead(_8); goto -> bb3; } bb3: { - StorageDead(_5); - StorageDead(_9); + StorageDead(_4); + StorageDead(_7); return; } } diff --git a/tests/mir-opt/pre-codegen/slice_index.slice_get_mut_usize.PreCodegen.after.panic-unwind.mir b/tests/mir-opt/pre-codegen/slice_index.slice_get_mut_usize.PreCodegen.after.panic-unwind.mir index 65416d09053..07a58309ee4 100644 --- a/tests/mir-opt/pre-codegen/slice_index.slice_get_mut_usize.PreCodegen.after.panic-unwind.mir +++ b/tests/mir-opt/pre-codegen/slice_index.slice_get_mut_usize.PreCodegen.after.panic-unwind.mir @@ -10,38 +10,37 @@ fn slice_get_mut_usize(_1: &mut [u32], _2: usize) -> Option<&mut u32> { scope 2 (inlined <usize as SliceIndex<[u32]>>::get_mut) { debug self => _2; debug slice => _1; - let mut _3: &[u32]; - let mut _4: usize; - let mut _5: bool; - let mut _6: *mut [u32]; - let mut _8: *mut u32; - let mut _9: &mut u32; + let mut _3: usize; + let mut _4: bool; + let mut _5: *mut [u32]; + let mut _7: *mut u32; + let mut _8: &mut u32; scope 3 { scope 4 (inlined <usize as SliceIndex<[u32]>>::get_unchecked_mut) { debug self => _2; - debug slice => _6; - let mut _7: *mut u32; + debug slice => _5; + let mut _6: *mut u32; scope 5 { debug this => _2; scope 6 { scope 7 (inlined <usize as SliceIndex<[T]>>::get_unchecked_mut::runtime::<u32>) { debug this => _2; - debug slice => _6; + debug slice => _5; scope 8 (inlined ptr::mut_ptr::<impl *mut [u32]>::len) { - debug self => _6; - let mut _10: *const [u32]; + debug self => _5; + let mut _9: *const [u32]; scope 9 (inlined std::ptr::metadata::<[u32]>) { - debug ptr => _10; + debug ptr => _9; scope 10 { } } } } scope 11 (inlined ptr::mut_ptr::<impl *mut [u32]>::as_mut_ptr) { - debug self => _6; + debug self => _5; } scope 12 (inlined ptr::mut_ptr::<impl *mut u32>::add) { - debug self => _7; + debug self => _6; debug count => _2; scope 13 { } @@ -54,16 +53,13 @@ fn slice_get_mut_usize(_1: &mut [u32], _2: usize) -> Option<&mut u32> { } bb0: { - StorageLive(_9); - StorageLive(_5); + StorageLive(_7); StorageLive(_4); StorageLive(_3); - _3 = &(*_1); - _4 = Len((*_3)); + _3 = Len((*_1)); + _4 = Lt(_2, move _3); StorageDead(_3); - _5 = Lt(_2, move _4); - StorageDead(_4); - switchInt(move _5) -> [0: bb1, otherwise: bb2]; + switchInt(move _4) -> [0: bb1, otherwise: bb2]; } bb1: { @@ -73,24 +69,24 @@ fn slice_get_mut_usize(_1: &mut [u32], _2: usize) -> Option<&mut u32> { bb2: { StorageLive(_8); + StorageLive(_5); + _5 = &raw mut (*_1); + StorageLive(_9); StorageLive(_6); - _6 = &raw mut (*_1); - StorageLive(_10); - StorageLive(_7); - _7 = _6 as *mut u32 (PtrToPtr); - _8 = Offset(_7, _2); - StorageDead(_7); - StorageDead(_10); + _6 = _5 as *mut u32 (PtrToPtr); + _7 = Offset(_6, _2); StorageDead(_6); - _9 = &mut (*_8); - _0 = Option::<&mut u32>::Some(_9); + StorageDead(_9); + StorageDead(_5); + _8 = &mut (*_7); + _0 = Option::<&mut u32>::Some(move _8); StorageDead(_8); goto -> bb3; } bb3: { - StorageDead(_5); - StorageDead(_9); + StorageDead(_4); + StorageDead(_7); return; } } diff --git a/tests/mir-opt/pre-codegen/slice_index.slice_get_unchecked_mut_range.PreCodegen.after.panic-abort.mir b/tests/mir-opt/pre-codegen/slice_index.slice_get_unchecked_mut_range.PreCodegen.after.panic-abort.mir index e07e2bb7bfe..2f5d356a26d 100644 --- a/tests/mir-opt/pre-codegen/slice_index.slice_get_unchecked_mut_range.PreCodegen.after.panic-abort.mir +++ b/tests/mir-opt/pre-codegen/slice_index.slice_get_unchecked_mut_range.PreCodegen.after.panic-abort.mir @@ -61,7 +61,6 @@ fn slice_get_unchecked_mut_range(_1: &mut [u32], _2: std::ops::Range<usize>) -> bb0: { _3 = move (_2.0: usize); _4 = move (_2.1: usize); - StorageLive(_13); StorageLive(_5); _5 = &raw mut (*_1); StorageLive(_14); @@ -92,7 +91,6 @@ fn slice_get_unchecked_mut_range(_1: &mut [u32], _2: std::ops::Range<usize>) -> StorageDead(_15); StorageDead(_5); _0 = &mut (*_13); - StorageDead(_13); return; } } diff --git a/tests/mir-opt/pre-codegen/slice_index.slice_get_unchecked_mut_range.PreCodegen.after.panic-unwind.mir b/tests/mir-opt/pre-codegen/slice_index.slice_get_unchecked_mut_range.PreCodegen.after.panic-unwind.mir index e07e2bb7bfe..2f5d356a26d 100644 --- a/tests/mir-opt/pre-codegen/slice_index.slice_get_unchecked_mut_range.PreCodegen.after.panic-unwind.mir +++ b/tests/mir-opt/pre-codegen/slice_index.slice_get_unchecked_mut_range.PreCodegen.after.panic-unwind.mir @@ -61,7 +61,6 @@ fn slice_get_unchecked_mut_range(_1: &mut [u32], _2: std::ops::Range<usize>) -> bb0: { _3 = move (_2.0: usize); _4 = move (_2.1: usize); - StorageLive(_13); StorageLive(_5); _5 = &raw mut (*_1); StorageLive(_14); @@ -92,7 +91,6 @@ fn slice_get_unchecked_mut_range(_1: &mut [u32], _2: std::ops::Range<usize>) -> StorageDead(_15); StorageDead(_5); _0 = &mut (*_13); - StorageDead(_13); return; } } diff --git a/tests/mir-opt/pre-codegen/slice_iter.enumerated_loop.PreCodegen.after.panic-abort.mir b/tests/mir-opt/pre-codegen/slice_iter.enumerated_loop.PreCodegen.after.panic-abort.mir index d1ab16697a6..2cf81d86267 100644 --- a/tests/mir-opt/pre-codegen/slice_iter.enumerated_loop.PreCodegen.after.panic-abort.mir +++ b/tests/mir-opt/pre-codegen/slice_iter.enumerated_loop.PreCodegen.after.panic-abort.mir @@ -152,11 +152,13 @@ fn enumerated_loop(_1: &[T], _2: impl Fn(usize, &T)) -> () { bb4: { StorageLive(_17); + StorageLive(_16); _16 = &mut _15; - _17 = <Enumerate<std::slice::Iter<'_, T>> as Iterator>::next(_16) -> [return: bb5, unwind unreachable]; + _17 = <Enumerate<std::slice::Iter<'_, T>> as Iterator>::next(move _16) -> [return: bb5, unwind unreachable]; } bb5: { + StorageDead(_16); _18 = discriminant(_17); switchInt(move _18) -> [0: bb6, 1: bb8, otherwise: bb10]; } diff --git a/tests/mir-opt/pre-codegen/slice_iter.enumerated_loop.PreCodegen.after.panic-unwind.mir b/tests/mir-opt/pre-codegen/slice_iter.enumerated_loop.PreCodegen.after.panic-unwind.mir index 03751f7fdf7..6985806ec93 100644 --- a/tests/mir-opt/pre-codegen/slice_iter.enumerated_loop.PreCodegen.after.panic-unwind.mir +++ b/tests/mir-opt/pre-codegen/slice_iter.enumerated_loop.PreCodegen.after.panic-unwind.mir @@ -152,11 +152,13 @@ fn enumerated_loop(_1: &[T], _2: impl Fn(usize, &T)) -> () { bb4: { StorageLive(_17); + StorageLive(_16); _16 = &mut _15; - _17 = <Enumerate<std::slice::Iter<'_, T>> as Iterator>::next(_16) -> [return: bb5, unwind: bb11]; + _17 = <Enumerate<std::slice::Iter<'_, T>> as Iterator>::next(move _16) -> [return: bb5, unwind: bb11]; } bb5: { + StorageDead(_16); _18 = discriminant(_17); switchInt(move _18) -> [0: bb6, 1: bb8, otherwise: bb10]; } diff --git a/tests/mir-opt/pre-codegen/slice_iter.forward_loop.PreCodegen.after.panic-abort.mir b/tests/mir-opt/pre-codegen/slice_iter.forward_loop.PreCodegen.after.panic-abort.mir index db971e10f32..a4b8460e98e 100644 --- a/tests/mir-opt/pre-codegen/slice_iter.forward_loop.PreCodegen.after.panic-abort.mir +++ b/tests/mir-opt/pre-codegen/slice_iter.forward_loop.PreCodegen.after.panic-abort.mir @@ -140,11 +140,13 @@ fn forward_loop(_1: &[T], _2: impl Fn(&T)) -> () { bb4: { StorageLive(_16); + StorageLive(_15); _15 = &mut _14; - _16 = <std::slice::Iter<'_, T> as Iterator>::next(_15) -> [return: bb5, unwind unreachable]; + _16 = <std::slice::Iter<'_, T> as Iterator>::next(move _15) -> [return: bb5, unwind unreachable]; } bb5: { + StorageDead(_15); _17 = discriminant(_16); switchInt(move _17) -> [0: bb6, 1: bb8, otherwise: bb10]; } diff --git a/tests/mir-opt/pre-codegen/slice_iter.forward_loop.PreCodegen.after.panic-unwind.mir b/tests/mir-opt/pre-codegen/slice_iter.forward_loop.PreCodegen.after.panic-unwind.mir index 74597799168..58f312b1aac 100644 --- a/tests/mir-opt/pre-codegen/slice_iter.forward_loop.PreCodegen.after.panic-unwind.mir +++ b/tests/mir-opt/pre-codegen/slice_iter.forward_loop.PreCodegen.after.panic-unwind.mir @@ -140,11 +140,13 @@ fn forward_loop(_1: &[T], _2: impl Fn(&T)) -> () { bb4: { StorageLive(_16); + StorageLive(_15); _15 = &mut _14; - _16 = <std::slice::Iter<'_, T> as Iterator>::next(_15) -> [return: bb5, unwind: bb11]; + _16 = <std::slice::Iter<'_, T> as Iterator>::next(move _15) -> [return: bb5, unwind: bb11]; } bb5: { + StorageDead(_15); _17 = discriminant(_16); switchInt(move _17) -> [0: bb6, 1: bb8, otherwise: bb10]; } diff --git a/tests/mir-opt/pre-codegen/slice_iter.range_loop.PreCodegen.after.panic-abort.mir b/tests/mir-opt/pre-codegen/slice_iter.range_loop.PreCodegen.after.panic-abort.mir index 00177033bbf..901381f070b 100644 --- a/tests/mir-opt/pre-codegen/slice_iter.range_loop.PreCodegen.after.panic-abort.mir +++ b/tests/mir-opt/pre-codegen/slice_iter.range_loop.PreCodegen.after.panic-abort.mir @@ -5,112 +5,95 @@ fn range_loop(_1: &[T], _2: impl Fn(usize, &T)) -> () { debug f => _2; let mut _0: (); let mut _3: usize; - let mut _4: std::ops::Range<usize>; - let mut _5: std::ops::Range<usize>; - let mut _6: &mut std::ops::Range<usize>; - let mut _12: std::option::Option<usize>; - let mut _15: isize; - let mut _17: usize; - let mut _18: bool; - let mut _20: &impl Fn(usize, &T); - let mut _21: (usize, &T); - let _22: (); + let mut _4: usize; + let mut _7: std::option::Option<usize>; + let mut _10: isize; + let mut _12: usize; + let mut _13: bool; + let mut _15: &impl Fn(usize, &T); + let mut _16: (usize, &T); + let _17: (); + let mut _18: usize; scope 1 { - debug iter => _5; - let _16: usize; + debug iter => std::ops::Range<usize>{ .0 => _4, .1 => _3, }; + let _11: usize; scope 2 { - debug i => _16; - let _19: &T; + debug i => _11; + let _14: &T; scope 3 { - debug x => _19; + debug x => _14; } } scope 5 (inlined iter::range::<impl Iterator for std::ops::Range<usize>>::next) { - debug self => _6; + debug self => &std::ops::Range<usize>{ .0 => _4, .1 => _3, }; scope 6 (inlined <std::ops::Range<usize> as iter::range::RangeIteratorImpl>::spec_next) { - debug self => _6; - let mut _7: &usize; - let mut _8: &usize; - let mut _11: bool; - let _13: usize; - let mut _14: usize; + debug self => &std::ops::Range<usize>{ .0 => _4, .1 => _3, }; + let mut _6: bool; + let _8: usize; + let mut _9: usize; scope 7 { - debug old => _13; + debug old => _8; scope 8 { } } scope 9 (inlined cmp::impls::<impl PartialOrd for usize>::lt) { - debug self => _7; - debug other => _8; - let mut _9: usize; - let mut _10: usize; + debug self => &_4; + debug other => &_3; + let mut _5: usize; } } } } scope 4 (inlined <std::ops::Range<usize> as IntoIterator>::into_iter) { - debug self => _4; + debug self => std::ops::Range<usize>{ .0 => _18, .1 => _3, }; } bb0: { - StorageLive(_3); _3 = Len((*_1)); - _4 = std::ops::Range::<usize> { start: const 0_usize, end: move _3 }; - StorageDead(_3); - StorageLive(_5); - _5 = move _4; + StorageLive(_4); + _4 = const 0_usize; goto -> bb1; } bb1: { - StorageLive(_12); - _6 = &mut _5; - StorageLive(_13); - StorageLive(_11); StorageLive(_7); - _7 = &((*_6).0: usize); StorageLive(_8); - _8 = &((*_6).1: usize); - StorageLive(_9); - _9 = (*_7); - StorageLive(_10); - _10 = (*_8); - _11 = Lt(move _9, move _10); - StorageDead(_10); - StorageDead(_9); - StorageDead(_8); - StorageDead(_7); - switchInt(move _11) -> [0: bb2, otherwise: bb3]; + StorageLive(_6); + StorageLive(_5); + _5 = _4; + _6 = Lt(move _5, _3); + StorageDead(_5); + switchInt(move _6) -> [0: bb2, otherwise: bb3]; } bb2: { - _12 = Option::<usize>::None; + _7 = Option::<usize>::None; goto -> bb5; } bb3: { - _13 = ((*_6).0: usize); - StorageLive(_14); - _14 = <usize as Step>::forward_unchecked(_13, const 1_usize) -> [return: bb4, unwind unreachable]; + _8 = _4; + StorageLive(_9); + _9 = <usize as Step>::forward_unchecked(_8, const 1_usize) -> [return: bb4, unwind unreachable]; } bb4: { - ((*_6).0: usize) = move _14; - StorageDead(_14); - _12 = Option::<usize>::Some(_13); + _4 = move _9; + StorageDead(_9); + _7 = Option::<usize>::Some(_8); goto -> bb5; } bb5: { - StorageDead(_11); - StorageDead(_13); - _15 = discriminant(_12); - switchInt(move _15) -> [0: bb6, 1: bb8, otherwise: bb11]; + StorageDead(_6); + StorageDead(_8); + _10 = discriminant(_7); + switchInt(move _10) -> [0: bb6, 1: bb8, otherwise: bb11]; } bb6: { - StorageDead(_12); - StorageDead(_5); + StorageDead(_7); + StorageDead(_4); drop(_2) -> [return: bb7, unwind unreachable]; } @@ -119,25 +102,25 @@ fn range_loop(_1: &[T], _2: impl Fn(usize, &T)) -> () { } bb8: { - _16 = ((_12 as Some).0: usize); - _17 = Len((*_1)); - _18 = Lt(_16, _17); - assert(move _18, "index out of bounds: the length is {} but the index is {}", move _17, _16) -> [success: bb9, unwind unreachable]; + _11 = ((_7 as Some).0: usize); + _12 = Len((*_1)); + _13 = Lt(_11, _12); + assert(move _13, "index out of bounds: the length is {} but the index is {}", move _12, _11) -> [success: bb9, unwind unreachable]; } bb9: { - _19 = &(*_1)[_16]; - StorageLive(_20); - _20 = &_2; - StorageLive(_21); - _21 = (_16, _19); - _22 = <impl Fn(usize, &T) as Fn<(usize, &T)>>::call(move _20, move _21) -> [return: bb10, unwind unreachable]; + _14 = &(*_1)[_11]; + StorageLive(_15); + _15 = &_2; + StorageLive(_16); + _16 = (_11, _14); + _17 = <impl Fn(usize, &T) as Fn<(usize, &T)>>::call(move _15, move _16) -> [return: bb10, unwind unreachable]; } bb10: { - StorageDead(_21); - StorageDead(_20); - StorageDead(_12); + StorageDead(_16); + StorageDead(_15); + StorageDead(_7); goto -> bb1; } diff --git a/tests/mir-opt/pre-codegen/slice_iter.range_loop.PreCodegen.after.panic-unwind.mir b/tests/mir-opt/pre-codegen/slice_iter.range_loop.PreCodegen.after.panic-unwind.mir index 3423c5d865d..a47a73395cf 100644 --- a/tests/mir-opt/pre-codegen/slice_iter.range_loop.PreCodegen.after.panic-unwind.mir +++ b/tests/mir-opt/pre-codegen/slice_iter.range_loop.PreCodegen.after.panic-unwind.mir @@ -5,112 +5,95 @@ fn range_loop(_1: &[T], _2: impl Fn(usize, &T)) -> () { debug f => _2; let mut _0: (); let mut _3: usize; - let mut _4: std::ops::Range<usize>; - let mut _5: std::ops::Range<usize>; - let mut _6: &mut std::ops::Range<usize>; - let mut _12: std::option::Option<usize>; - let mut _15: isize; - let mut _17: usize; - let mut _18: bool; - let mut _20: &impl Fn(usize, &T); - let mut _21: (usize, &T); - let _22: (); + let mut _4: usize; + let mut _7: std::option::Option<usize>; + let mut _10: isize; + let mut _12: usize; + let mut _13: bool; + let mut _15: &impl Fn(usize, &T); + let mut _16: (usize, &T); + let _17: (); + let mut _18: usize; scope 1 { - debug iter => _5; - let _16: usize; + debug iter => std::ops::Range<usize>{ .0 => _4, .1 => _3, }; + let _11: usize; scope 2 { - debug i => _16; - let _19: &T; + debug i => _11; + let _14: &T; scope 3 { - debug x => _19; + debug x => _14; } } scope 5 (inlined iter::range::<impl Iterator for std::ops::Range<usize>>::next) { - debug self => _6; + debug self => &std::ops::Range<usize>{ .0 => _4, .1 => _3, }; scope 6 (inlined <std::ops::Range<usize> as iter::range::RangeIteratorImpl>::spec_next) { - debug self => _6; - let mut _7: &usize; - let mut _8: &usize; - let mut _11: bool; - let _13: usize; - let mut _14: usize; + debug self => &std::ops::Range<usize>{ .0 => _4, .1 => _3, }; + let mut _6: bool; + let _8: usize; + let mut _9: usize; scope 7 { - debug old => _13; + debug old => _8; scope 8 { } } scope 9 (inlined cmp::impls::<impl PartialOrd for usize>::lt) { - debug self => _7; - debug other => _8; - let mut _9: usize; - let mut _10: usize; + debug self => &_4; + debug other => &_3; + let mut _5: usize; } } } } scope 4 (inlined <std::ops::Range<usize> as IntoIterator>::into_iter) { - debug self => _4; + debug self => std::ops::Range<usize>{ .0 => _18, .1 => _3, }; } bb0: { - StorageLive(_3); _3 = Len((*_1)); - _4 = std::ops::Range::<usize> { start: const 0_usize, end: move _3 }; - StorageDead(_3); - StorageLive(_5); - _5 = move _4; + StorageLive(_4); + _4 = const 0_usize; goto -> bb1; } bb1: { - StorageLive(_12); - _6 = &mut _5; - StorageLive(_13); - StorageLive(_11); StorageLive(_7); - _7 = &((*_6).0: usize); StorageLive(_8); - _8 = &((*_6).1: usize); - StorageLive(_9); - _9 = (*_7); - StorageLive(_10); - _10 = (*_8); - _11 = Lt(move _9, move _10); - StorageDead(_10); - StorageDead(_9); - StorageDead(_8); - StorageDead(_7); - switchInt(move _11) -> [0: bb2, otherwise: bb3]; + StorageLive(_6); + StorageLive(_5); + _5 = _4; + _6 = Lt(move _5, _3); + StorageDead(_5); + switchInt(move _6) -> [0: bb2, otherwise: bb3]; } bb2: { - _12 = Option::<usize>::None; + _7 = Option::<usize>::None; goto -> bb5; } bb3: { - _13 = ((*_6).0: usize); - StorageLive(_14); - _14 = <usize as Step>::forward_unchecked(_13, const 1_usize) -> [return: bb4, unwind: bb12]; + _8 = _4; + StorageLive(_9); + _9 = <usize as Step>::forward_unchecked(_8, const 1_usize) -> [return: bb4, unwind: bb12]; } bb4: { - ((*_6).0: usize) = move _14; - StorageDead(_14); - _12 = Option::<usize>::Some(_13); + _4 = move _9; + StorageDead(_9); + _7 = Option::<usize>::Some(_8); goto -> bb5; } bb5: { - StorageDead(_11); - StorageDead(_13); - _15 = discriminant(_12); - switchInt(move _15) -> [0: bb6, 1: bb8, otherwise: bb11]; + StorageDead(_6); + StorageDead(_8); + _10 = discriminant(_7); + switchInt(move _10) -> [0: bb6, 1: bb8, otherwise: bb11]; } bb6: { - StorageDead(_12); - StorageDead(_5); + StorageDead(_7); + StorageDead(_4); drop(_2) -> [return: bb7, unwind continue]; } @@ -119,25 +102,25 @@ fn range_loop(_1: &[T], _2: impl Fn(usize, &T)) -> () { } bb8: { - _16 = ((_12 as Some).0: usize); - _17 = Len((*_1)); - _18 = Lt(_16, _17); - assert(move _18, "index out of bounds: the length is {} but the index is {}", move _17, _16) -> [success: bb9, unwind: bb12]; + _11 = ((_7 as Some).0: usize); + _12 = Len((*_1)); + _13 = Lt(_11, _12); + assert(move _13, "index out of bounds: the length is {} but the index is {}", move _12, _11) -> [success: bb9, unwind: bb12]; } bb9: { - _19 = &(*_1)[_16]; - StorageLive(_20); - _20 = &_2; - StorageLive(_21); - _21 = (_16, _19); - _22 = <impl Fn(usize, &T) as Fn<(usize, &T)>>::call(move _20, move _21) -> [return: bb10, unwind: bb12]; + _14 = &(*_1)[_11]; + StorageLive(_15); + _15 = &_2; + StorageLive(_16); + _16 = (_11, _14); + _17 = <impl Fn(usize, &T) as Fn<(usize, &T)>>::call(move _15, move _16) -> [return: bb10, unwind: bb12]; } bb10: { - StorageDead(_21); - StorageDead(_20); - StorageDead(_12); + StorageDead(_16); + StorageDead(_15); + StorageDead(_7); goto -> bb1; } diff --git a/tests/mir-opt/pre-codegen/slice_iter.reverse_loop.PreCodegen.after.panic-abort.mir b/tests/mir-opt/pre-codegen/slice_iter.reverse_loop.PreCodegen.after.panic-abort.mir index e546140e0c1..b550711aa41 100644 --- a/tests/mir-opt/pre-codegen/slice_iter.reverse_loop.PreCodegen.after.panic-abort.mir +++ b/tests/mir-opt/pre-codegen/slice_iter.reverse_loop.PreCodegen.after.panic-abort.mir @@ -7,21 +7,20 @@ fn reverse_loop(_1: &[T], _2: impl Fn(&T)) -> () { let mut _13: std::slice::Iter<'_, T>; let mut _14: std::iter::Rev<std::slice::Iter<'_, T>>; let mut _15: std::iter::Rev<std::slice::Iter<'_, T>>; - let mut _16: &mut std::iter::Rev<std::slice::Iter<'_, T>>; - let mut _18: std::option::Option<&T>; - let mut _19: isize; - let mut _21: &impl Fn(&T); - let mut _22: (&T,); - let _23: (); + let mut _17: std::option::Option<&T>; + let mut _18: isize; + let mut _20: &impl Fn(&T); + let mut _21: (&T,); + let _22: (); scope 1 { debug iter => _15; - let _20: &T; + let _19: &T; scope 2 { - debug x => _20; + debug x => _19; } scope 25 (inlined <Rev<std::slice::Iter<'_, T>> as Iterator>::next) { - debug self => _16; - let mut _17: &mut std::slice::Iter<'_, T>; + debug self => &_15; + let mut _16: &mut std::slice::Iter<'_, T>; } } scope 3 (inlined core::slice::<impl [T]>::iter) { @@ -49,15 +48,15 @@ fn reverse_loop(_1: &[T], _2: impl Fn(&T)) -> () { debug ptr => _9; scope 16 (inlined ptr::mut_ptr::<impl *mut T>::is_null) { debug self => _9; - let mut _24: *mut u8; + let mut _23: *mut u8; scope 17 { scope 18 (inlined ptr::mut_ptr::<impl *mut T>::is_null::runtime_impl) { - debug ptr => _24; + debug ptr => _23; scope 19 (inlined ptr::mut_ptr::<impl *mut u8>::addr) { - debug self => _24; + debug self => _23; scope 20 { scope 21 (inlined ptr::mut_ptr::<impl *mut u8>::cast::<()>) { - debug self => _24; + debug self => _23; } } } @@ -132,10 +131,10 @@ fn reverse_loop(_1: &[T], _2: impl Fn(&T)) -> () { StorageLive(_9); _9 = _4 as *mut T (PtrToPtr); StorageLive(_10); - StorageLive(_24); + StorageLive(_23); _10 = _9 as *const T (PointerCoercion(MutToConstPointer)); _11 = NonNull::<T> { pointer: _10 }; - StorageDead(_24); + StorageDead(_23); StorageDead(_10); StorageDead(_9); StorageLive(_12); @@ -153,21 +152,20 @@ fn reverse_loop(_1: &[T], _2: impl Fn(&T)) -> () { } bb4: { - StorageLive(_18); - _16 = &mut _15; StorageLive(_17); - _17 = &mut ((*_16).0: std::slice::Iter<'_, T>); - _18 = <std::slice::Iter<'_, T> as DoubleEndedIterator>::next_back(move _17) -> [return: bb5, unwind unreachable]; + StorageLive(_16); + _16 = &mut (_15.0: std::slice::Iter<'_, T>); + _17 = <std::slice::Iter<'_, T> as DoubleEndedIterator>::next_back(move _16) -> [return: bb5, unwind unreachable]; } bb5: { - StorageDead(_17); - _19 = discriminant(_18); - switchInt(move _19) -> [0: bb6, 1: bb8, otherwise: bb10]; + StorageDead(_16); + _18 = discriminant(_17); + switchInt(move _18) -> [0: bb6, 1: bb8, otherwise: bb10]; } bb6: { - StorageDead(_18); + StorageDead(_17); StorageDead(_15); drop(_2) -> [return: bb7, unwind unreachable]; } @@ -177,18 +175,18 @@ fn reverse_loop(_1: &[T], _2: impl Fn(&T)) -> () { } bb8: { - _20 = ((_18 as Some).0: &T); + _19 = ((_17 as Some).0: &T); + StorageLive(_20); + _20 = &_2; StorageLive(_21); - _21 = &_2; - StorageLive(_22); - _22 = (_20,); - _23 = <impl Fn(&T) as Fn<(&T,)>>::call(move _21, move _22) -> [return: bb9, unwind unreachable]; + _21 = (_19,); + _22 = <impl Fn(&T) as Fn<(&T,)>>::call(move _20, move _21) -> [return: bb9, unwind unreachable]; } bb9: { - StorageDead(_22); StorageDead(_21); - StorageDead(_18); + StorageDead(_20); + StorageDead(_17); goto -> bb4; } diff --git a/tests/mir-opt/pre-codegen/slice_iter.reverse_loop.PreCodegen.after.panic-unwind.mir b/tests/mir-opt/pre-codegen/slice_iter.reverse_loop.PreCodegen.after.panic-unwind.mir index 551cac46bdf..23444241cd2 100644 --- a/tests/mir-opt/pre-codegen/slice_iter.reverse_loop.PreCodegen.after.panic-unwind.mir +++ b/tests/mir-opt/pre-codegen/slice_iter.reverse_loop.PreCodegen.after.panic-unwind.mir @@ -7,21 +7,20 @@ fn reverse_loop(_1: &[T], _2: impl Fn(&T)) -> () { let mut _13: std::slice::Iter<'_, T>; let mut _14: std::iter::Rev<std::slice::Iter<'_, T>>; let mut _15: std::iter::Rev<std::slice::Iter<'_, T>>; - let mut _16: &mut std::iter::Rev<std::slice::Iter<'_, T>>; - let mut _18: std::option::Option<&T>; - let mut _19: isize; - let mut _21: &impl Fn(&T); - let mut _22: (&T,); - let _23: (); + let mut _17: std::option::Option<&T>; + let mut _18: isize; + let mut _20: &impl Fn(&T); + let mut _21: (&T,); + let _22: (); scope 1 { debug iter => _15; - let _20: &T; + let _19: &T; scope 2 { - debug x => _20; + debug x => _19; } scope 25 (inlined <Rev<std::slice::Iter<'_, T>> as Iterator>::next) { - debug self => _16; - let mut _17: &mut std::slice::Iter<'_, T>; + debug self => &_15; + let mut _16: &mut std::slice::Iter<'_, T>; } } scope 3 (inlined core::slice::<impl [T]>::iter) { @@ -49,15 +48,15 @@ fn reverse_loop(_1: &[T], _2: impl Fn(&T)) -> () { debug ptr => _9; scope 16 (inlined ptr::mut_ptr::<impl *mut T>::is_null) { debug self => _9; - let mut _24: *mut u8; + let mut _23: *mut u8; scope 17 { scope 18 (inlined ptr::mut_ptr::<impl *mut T>::is_null::runtime_impl) { - debug ptr => _24; + debug ptr => _23; scope 19 (inlined ptr::mut_ptr::<impl *mut u8>::addr) { - debug self => _24; + debug self => _23; scope 20 { scope 21 (inlined ptr::mut_ptr::<impl *mut u8>::cast::<()>) { - debug self => _24; + debug self => _23; } } } @@ -132,10 +131,10 @@ fn reverse_loop(_1: &[T], _2: impl Fn(&T)) -> () { StorageLive(_9); _9 = _4 as *mut T (PtrToPtr); StorageLive(_10); - StorageLive(_24); + StorageLive(_23); _10 = _9 as *const T (PointerCoercion(MutToConstPointer)); _11 = NonNull::<T> { pointer: _10 }; - StorageDead(_24); + StorageDead(_23); StorageDead(_10); StorageDead(_9); StorageLive(_12); @@ -153,21 +152,20 @@ fn reverse_loop(_1: &[T], _2: impl Fn(&T)) -> () { } bb4: { - StorageLive(_18); - _16 = &mut _15; StorageLive(_17); - _17 = &mut ((*_16).0: std::slice::Iter<'_, T>); - _18 = <std::slice::Iter<'_, T> as DoubleEndedIterator>::next_back(move _17) -> [return: bb5, unwind: bb11]; + StorageLive(_16); + _16 = &mut (_15.0: std::slice::Iter<'_, T>); + _17 = <std::slice::Iter<'_, T> as DoubleEndedIterator>::next_back(move _16) -> [return: bb5, unwind: bb11]; } bb5: { - StorageDead(_17); - _19 = discriminant(_18); - switchInt(move _19) -> [0: bb6, 1: bb8, otherwise: bb10]; + StorageDead(_16); + _18 = discriminant(_17); + switchInt(move _18) -> [0: bb6, 1: bb8, otherwise: bb10]; } bb6: { - StorageDead(_18); + StorageDead(_17); StorageDead(_15); drop(_2) -> [return: bb7, unwind continue]; } @@ -177,18 +175,18 @@ fn reverse_loop(_1: &[T], _2: impl Fn(&T)) -> () { } bb8: { - _20 = ((_18 as Some).0: &T); + _19 = ((_17 as Some).0: &T); + StorageLive(_20); + _20 = &_2; StorageLive(_21); - _21 = &_2; - StorageLive(_22); - _22 = (_20,); - _23 = <impl Fn(&T) as Fn<(&T,)>>::call(move _21, move _22) -> [return: bb9, unwind: bb11]; + _21 = (_19,); + _22 = <impl Fn(&T) as Fn<(&T,)>>::call(move _20, move _21) -> [return: bb9, unwind: bb11]; } bb9: { - StorageDead(_22); StorageDead(_21); - StorageDead(_18); + StorageDead(_20); + StorageDead(_17); goto -> bb4; } diff --git a/tests/mir-opt/pre-codegen/spans.outer.PreCodegen.after.panic-abort.mir b/tests/mir-opt/pre-codegen/spans.outer.PreCodegen.after.panic-abort.mir index b9329520bab..ed7107e53ef 100644 --- a/tests/mir-opt/pre-codegen/spans.outer.PreCodegen.after.panic-abort.mir +++ b/tests/mir-opt/pre-codegen/spans.outer.PreCodegen.after.panic-abort.mir @@ -3,17 +3,19 @@ fn outer(_1: u8) -> u8 { debug v => _1; // in scope 0 at $DIR/spans.rs:10:14: 10:15 let mut _0: u8; // return place in scope 0 at $DIR/spans.rs:10:24: 10:26 - let _2: &u8; // in scope 0 at $DIR/spans.rs:11:11: 11:13 + let mut _2: &u8; // in scope 0 at $DIR/spans.rs:11:11: 11:13 bb0: { + StorageLive(_2); // scope 0 at $DIR/spans.rs:11:11: 11:13 _2 = &_1; // scope 0 at $DIR/spans.rs:11:11: 11:13 - _0 = inner(_2) -> [return: bb1, unwind unreachable]; // scope 0 at $DIR/spans.rs:11:5: 11:14 + _0 = inner(move _2) -> [return: bb1, unwind unreachable]; // scope 0 at $DIR/spans.rs:11:5: 11:14 // mir::Constant // + span: $DIR/spans.rs:11:5: 11:10 // + literal: Const { ty: for<'a> fn(&'a u8) -> u8 {inner}, val: Value(<ZST>) } } bb1: { + StorageDead(_2); // scope 0 at $DIR/spans.rs:11:13: 11:14 return; // scope 0 at $DIR/spans.rs:12:2: 12:2 } } diff --git a/tests/mir-opt/pre-codegen/spans.outer.PreCodegen.after.panic-unwind.mir b/tests/mir-opt/pre-codegen/spans.outer.PreCodegen.after.panic-unwind.mir index 1e20b1be56b..dc436dc2650 100644 --- a/tests/mir-opt/pre-codegen/spans.outer.PreCodegen.after.panic-unwind.mir +++ b/tests/mir-opt/pre-codegen/spans.outer.PreCodegen.after.panic-unwind.mir @@ -3,17 +3,19 @@ fn outer(_1: u8) -> u8 { debug v => _1; // in scope 0 at $DIR/spans.rs:10:14: 10:15 let mut _0: u8; // return place in scope 0 at $DIR/spans.rs:10:24: 10:26 - let _2: &u8; // in scope 0 at $DIR/spans.rs:11:11: 11:13 + let mut _2: &u8; // in scope 0 at $DIR/spans.rs:11:11: 11:13 bb0: { + StorageLive(_2); // scope 0 at $DIR/spans.rs:11:11: 11:13 _2 = &_1; // scope 0 at $DIR/spans.rs:11:11: 11:13 - _0 = inner(_2) -> [return: bb1, unwind continue]; // scope 0 at $DIR/spans.rs:11:5: 11:14 + _0 = inner(move _2) -> [return: bb1, unwind continue]; // scope 0 at $DIR/spans.rs:11:5: 11:14 // mir::Constant // + span: $DIR/spans.rs:11:5: 11:10 // + literal: Const { ty: for<'a> fn(&'a u8) -> u8 {inner}, val: Value(<ZST>) } } bb1: { + StorageDead(_2); // scope 0 at $DIR/spans.rs:11:13: 11:14 return; // scope 0 at $DIR/spans.rs:12:2: 12:2 } } diff --git a/tests/run-coverage/partial_eq.coverage b/tests/run-coverage/partial_eq.coverage index a77175af663..be4f23ec0ba 100644 --- a/tests/run-coverage/partial_eq.coverage +++ b/tests/run-coverage/partial_eq.coverage @@ -36,7 +36,7 @@ 35| | did: DefId(0:101 ~ autocfg[c44a]::version::{impl#2}::partial_cmp), 36| | const_param_did: None 37| | }), - 38| | substs: [] + 38| | args: [] 39| | }' 40| |The `PartialOrd` derived by `Version` happened to generate a MIR that generated coverage 41| |without a code region associated with any `Counter`. Code regions were associated with at least diff --git a/tests/run-coverage/partial_eq.rs b/tests/run-coverage/partial_eq.rs index 4ceaba9b111..dd8b42c18ce 100644 --- a/tests/run-coverage/partial_eq.rs +++ b/tests/run-coverage/partial_eq.rs @@ -35,7 +35,7 @@ thread 'rustc' panicked at 'No counters provided the source_hash for function: did: DefId(0:101 ~ autocfg[c44a]::version::{impl#2}::partial_cmp), const_param_did: None }), - substs: [] + args: [] }' The `PartialOrd` derived by `Version` happened to generate a MIR that generated coverage without a code region associated with any `Counter`. Code regions were associated with at least diff --git a/tests/run-make-fulldeps/issue-19371/foo.rs b/tests/run-make-fulldeps/issue-19371/foo.rs index 9cca6200050..d4959247d1c 100644 --- a/tests/run-make-fulldeps/issue-19371/foo.rs +++ b/tests/run-make-fulldeps/issue-19371/foo.rs @@ -68,6 +68,6 @@ fn compile(code: String, output: PathBuf, sysroot: PathBuf) { let ongoing_codegen = queries.ongoing_codegen()?; queries.linker(ongoing_codegen) }); - linker.unwrap().link(); + linker.unwrap().link().unwrap(); }); } diff --git a/tests/run-make/extern-fn-explicit-align/Makefile b/tests/run-make/extern-fn-explicit-align/Makefile new file mode 100644 index 00000000000..3cbbf383996 --- /dev/null +++ b/tests/run-make/extern-fn-explicit-align/Makefile @@ -0,0 +1,6 @@ +# ignore-cross-compile +include ../tools.mk + +all: $(call NATIVE_STATICLIB,test) + $(RUSTC) test.rs + $(call RUN,test) || exit 1 diff --git a/tests/run-make/extern-fn-explicit-align/test.c b/tests/run-make/extern-fn-explicit-align/test.c new file mode 100644 index 00000000000..a3db3442aaf --- /dev/null +++ b/tests/run-make/extern-fn-explicit-align/test.c @@ -0,0 +1,93 @@ +#include <assert.h> +#include <stdbool.h> +#include <stdint.h> +#include <string.h> + +struct BoolAndU32 +{ + bool a; + uint32_t b; +}; + +#ifdef _MSC_VER +__declspec(align(16)) +struct TwoU64s +{ + uint64_t a; + uint64_t b; +}; +#else +struct __attribute__((aligned(16))) TwoU64s +{ + uint64_t a; + uint64_t b; +}; +#endif + +struct WrappedU64s +{ + struct TwoU64s a; +}; + +#ifdef _MSC_VER +__declspec(align(1)) +struct LowerAlign +{ + uint64_t a; + uint64_t b; +}; +#else +struct __attribute__((aligned(1))) LowerAlign +{ + uint64_t a; + uint64_t b; +}; +#endif + +#pragma pack(push, 1) +struct Packed +{ + uint64_t a; + uint64_t b; +}; +#pragma pack(pop) + +int32_t many_args( + void *a, + void *b, + const char *c, + uint64_t d, + bool e, + struct BoolAndU32 f, + void *g, + struct TwoU64s h, + void *i, + struct WrappedU64s j, + void *k, + struct LowerAlign l, + void *m, + struct Packed n, + const char *o) +{ + assert(!a); + assert(!b); + assert(!c); + assert(d == 42); + assert(e); + assert(f.a); + assert(f.b == 1337); + assert(!g); + assert(h.a == 1); + assert(h.b == 2); + assert(!i); + assert(j.a.a == 3); + assert(j.a.b == 4); + assert(!k); + assert(l.a == 5); + assert(l.b == 6); + assert(!m); + assert(n.a == 7); + assert(n.b == 8); + assert(strcmp(o, "Hello world") == 0); + return 0; +} diff --git a/tests/run-make/extern-fn-explicit-align/test.rs b/tests/run-make/extern-fn-explicit-align/test.rs new file mode 100644 index 00000000000..846622de3cd --- /dev/null +++ b/tests/run-make/extern-fn-explicit-align/test.rs @@ -0,0 +1,89 @@ +// Issue #80127: Passing structs via FFI should work with explicit alignment. + +use std::ffi::{CStr, c_char}; +use std::ptr::null_mut; + +#[repr(C)] +pub struct BoolAndU32 { + pub a: bool, + pub b: u32, +} + +#[repr(C)] +#[repr(align(16))] +pub struct TwoU64s { + pub a: u64, + pub b: u64, +} + +#[repr(C)] +pub struct WrappedU64s { + pub a: TwoU64s +} + +#[repr(C)] +// Even though requesting align 1 can never change the alignment, it still affects the ABI +// on some platforms like i686-windows. +#[repr(align(1))] +pub struct LowerAlign { + pub a: u64, + pub b: u64, +} + +#[repr(C)] +#[repr(packed)] +pub struct Packed { + pub a: u64, + pub b: u64, +} + +#[link(name = "test", kind = "static")] +extern "C" { + fn many_args( + a: *mut (), + b: *mut (), + c: *const c_char, + d: u64, + e: bool, + f: BoolAndU32, + g: *mut (), + h: TwoU64s, + i: *mut (), + j: WrappedU64s, + k: *mut (), + l: LowerAlign, + m: *mut (), + n: Packed, + o: *const c_char, + ) -> i32; +} + +const STRING: &CStr = unsafe { CStr::from_bytes_with_nul_unchecked(b"Hello world\0") }; + +fn main() { + let bool_and_u32 = BoolAndU32 { a: true, b: 1337 }; + let two_u64s = TwoU64s { a: 1, b: 2 }; + let wrapped = WrappedU64s { a: TwoU64s { a: 3, b: 4 } }; + let lower = LowerAlign { a: 5, b: 6 }; + let packed = Packed { a: 7, b: 8 }; + let string = STRING; + unsafe { + many_args( + null_mut(), + null_mut(), + null_mut(), + 42, + true, + bool_and_u32, + null_mut(), + two_u64s, + null_mut(), + wrapped, + null_mut(), + lower, + null_mut(), + packed, + string.as_ptr(), + ); + } +} diff --git a/tests/run-make/extern-fn-struct-passing-abi/test.c b/tests/run-make/extern-fn-struct-passing-abi/test.c index 136b07129e1..2cff776d86c 100644 --- a/tests/run-make/extern-fn-struct-passing-abi/test.c +++ b/tests/run-make/extern-fn-struct-passing-abi/test.c @@ -28,6 +28,14 @@ struct Huge { int32_t e; }; +struct Huge64 { + int64_t a; + int64_t b; + int64_t c; + int64_t d; + int64_t e; +}; + struct FloatPoint { double x; double y; @@ -152,6 +160,21 @@ void byval_rect_with_many_huge(struct Huge a, struct Huge b, struct Huge c, assert(g.d == 420); } +// System V x86_64 ABI: +// a, b, d, e, f should be byval pointer (on the stack) +// g passed via register (fixes #41375) +// +// i686-windows ABI: +// a, b, d, e, f, g should be byval pointer +void byval_rect_with_many_huge64(struct Huge64 a, struct Huge64 b, struct Huge64 c, + struct Huge64 d, struct Huge64 e, struct Huge64 f, + struct Rect g) { + assert(g.a == 1234); + assert(g.b == 4567); + assert(g.c == 7890); + assert(g.d == 4209); +} + // System V x86_64 & Win64 ABI: // a, b should be in registers // s should be split across 2 integer registers @@ -279,6 +302,19 @@ struct Huge huge_struct(struct Huge s) { return s; } +// System V x86_64 & i686-windows ABI: +// s should be byval pointer +// return should in a hidden sret pointer +struct Huge64 huge64_struct(struct Huge64 s) { + assert(s.a == 1234); + assert(s.b == 1335); + assert(s.c == 1436); + assert(s.d == 1537); + assert(s.e == 1638); + + return s; +} + // System V x86_64 ABI: // p should be in registers // return should be in registers diff --git a/tests/run-make/extern-fn-struct-passing-abi/test.rs b/tests/run-make/extern-fn-struct-passing-abi/test.rs index afe0f52ef0b..99e079f98a8 100644 --- a/tests/run-make/extern-fn-struct-passing-abi/test.rs +++ b/tests/run-make/extern-fn-struct-passing-abi/test.rs @@ -38,6 +38,16 @@ struct Huge { #[derive(Clone, Copy, Debug, PartialEq)] #[repr(C)] +struct Huge64 { + a: i64, + b: i64, + c: i64, + d: i64, + e: i64, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +#[repr(C)] struct FloatPoint { x: f64, y: f64, @@ -79,6 +89,12 @@ extern "C" { fn byval_rect_with_many_huge(a: Huge, b: Huge, c: Huge, d: Huge, e: Huge, f: Huge, g: Rect); + fn byval_rect_with_many_huge64( + a: Huge64, b: Huge64, c: Huge64, + d: Huge64, e: Huge64, f: Huge64, + g: Rect, + ); + fn split_rect(a: i32, b: i32, s: Rect); fn split_rect_floats(a: f32, b: f32, s: FloatRect); @@ -95,6 +111,8 @@ extern "C" { fn huge_struct(s: Huge) -> Huge; + fn huge64_struct(s: Huge64) -> Huge64; + fn float_point(p: FloatPoint) -> FloatPoint; fn float_one(f: FloatOne) -> FloatOne; @@ -107,6 +125,7 @@ fn main() { let t = BiggerRect { s: s, a: 27834, b: 7657 }; let u = FloatRect { a: 3489, b: 3490, c: 8. }; let v = Huge { a: 5647, b: 5648, c: 5649, d: 5650, e: 5651 }; + let w = Huge64 { a: 1234, b: 1335, c: 1436, d: 1537, e: 1638 }; let p = FloatPoint { x: 5., y: -3. }; let f1 = FloatOne { x: 7. }; let i = IntOdd { a: 1, b: 2, c: 3 }; @@ -117,12 +136,14 @@ fn main() { byval_rect_floats(1., 2., 3., 4., 5., 6., 7., s, u); byval_rect_with_float(1, 2, 3.0, 4, 5, 6, s); byval_rect_with_many_huge(v, v, v, v, v, v, Rect { a: 123, b: 456, c: 789, d: 420 }); + byval_rect_with_many_huge64(w, w, w, w, w, w, Rect { a: 1234, b: 4567, c: 7890, d: 4209 }); split_rect(1, 2, s); split_rect_floats(1., 2., u); split_rect_with_floats(1, 2, 3.0, 4, 5.0, 6, s); split_and_byval_rect(1, 2, 3, s, s); split_rect(1, 2, s); assert_eq!(huge_struct(v), v); + assert_eq!(huge64_struct(w), w); assert_eq!(split_ret_byval_struct(1, 2, s), s); assert_eq!(sret_byval_struct(1, 2, 3, 4, s), t); assert_eq!(sret_split_struct(1, 2, s), t); diff --git a/tests/run-make/print-native-static-libs/Makefile b/tests/run-make/print-native-static-libs/Makefile index 98e72d7696f..a16c8b0f2a4 100644 --- a/tests/run-make/print-native-static-libs/Makefile +++ b/tests/run-make/print-native-static-libs/Makefile @@ -5,7 +5,7 @@ include ../tools.mk all: $(RUSTC) --crate-type rlib -lbar_cli bar.rs - $(RUSTC) foo.rs -lfoo_cli --crate-type staticlib --print native-static-libs 2>&1 \ + $(RUSTC) foo.rs -lfoo_cli -lfoo_cli --crate-type staticlib --print native-static-libs 2>&1 \ | grep 'note: native-static-libs: ' \ | sed 's/note: native-static-libs: \(.*\)/\1/' > $(TMPDIR)/libs.txt @@ -13,3 +13,7 @@ all: cat $(TMPDIR)/libs.txt | grep -F "systemd" # in foo.rs cat $(TMPDIR)/libs.txt | grep -F "bar_cli" cat $(TMPDIR)/libs.txt | grep -F "foo_cli" + + # make sure that foo_cli and glib-2.0 are not consecutively present + cat $(TMPDIR)/libs.txt | grep -Fv "foo_cli -lfoo_cli" + cat $(TMPDIR)/libs.txt | grep -Fv "glib-2.0 -lglib-2.0" diff --git a/tests/run-make/print-native-static-libs/bar.rs b/tests/run-make/print-native-static-libs/bar.rs index a563bbc2a22..cd9c1c453e5 100644 --- a/tests/run-make/print-native-static-libs/bar.rs +++ b/tests/run-make/print-native-static-libs/bar.rs @@ -3,6 +3,7 @@ pub extern "C" fn my_bar_add(left: i32, right: i32) -> i32 { // Obviously makes no sense but... unsafe { g_free(std::ptr::null_mut()); + g_free2(std::ptr::null_mut()); } left + right } @@ -11,3 +12,8 @@ pub extern "C" fn my_bar_add(left: i32, right: i32) -> i32 { extern "C" { fn g_free(p: *mut ()); } + +#[link(name = "glib-2.0")] +extern "C" { + fn g_free2(p: *mut ()); +} diff --git a/tests/run-make/short-ice/check.sh b/tests/run-make/short-ice/check.sh index 96cd8fe86bc..a13b7eeca8f 100644 --- a/tests/run-make/short-ice/check.sh +++ b/tests/run-make/short-ice/check.sh @@ -28,8 +28,8 @@ echo "rustc_query_count_full: $rustc_query_count_full" ## and marks are in pairs. if [ $short -lt $full ] && [ $begin_count -eq $end_count ] && - [ $(($rustc_query_count + 10)) -lt $rustc_query_count_full ] && - [ $rustc_query_count_full -gt 10 ]; then + [ $(($rustc_query_count + 5)) -lt $rustc_query_count_full ] && + [ $rustc_query_count_full -gt 5 ]; then exit 0 else exit 1 diff --git a/tests/rustdoc-gui/anchors.goml b/tests/rustdoc-gui/anchors.goml index e9b77296917..30b83f0da38 100644 --- a/tests/rustdoc-gui/anchors.goml +++ b/tests/rustdoc-gui/anchors.goml @@ -17,34 +17,34 @@ define-function: ( assert-css: (".main-heading h1 a:nth-of-type(1)", {"color": |main_heading_color|}) assert-css: (".main-heading a:nth-of-type(2)", {"color": |main_heading_type_color|}) assert-css: ( - ".rightside .srclink", + ".rightside a.src", {"color": |src_link_color|, "text-decoration": "none solid " + |src_link_color|}, ALL, ) compare-elements-css: ( - ".rightside .srclink", - ".rightside.srclink", + ".rightside a.src", + "a.rightside.src", ["color", "text-decoration"], ) compare-elements-css: ( - ".main-heading .srclink", - ".rightside.srclink", + ".main-heading a.src", + "a.rightside.src", ["color", "text-decoration"], ) - move-cursor-to: ".main-heading .srclink" + move-cursor-to: ".main-heading a.src" assert-css: ( - ".main-heading .srclink", + ".main-heading a.src", {"color": |src_link_color|, "text-decoration": "underline solid " + |src_link_color|}, ) - move-cursor-to: ".impl-items .rightside .srclink" + move-cursor-to: ".impl-items .rightside a.src" assert-css: ( - ".impl-items .rightside .srclink", + ".impl-items .rightside a.src", {"color": |src_link_color|, "text-decoration": "none solid " + |src_link_color|}, ) - move-cursor-to: ".impl-items .rightside.srclink" + move-cursor-to: ".impl-items a.rightside.src" assert-css: ( - ".impl-items .rightside.srclink", + ".impl-items a.rightside.src", {"color": |src_link_color|, "text-decoration": "none solid " + |src_link_color|}, ) diff --git a/tests/rustdoc-gui/basic-code.goml b/tests/rustdoc-gui/basic-code.goml index e372f711974..22ac5316184 100644 --- a/tests/rustdoc-gui/basic-code.goml +++ b/tests/rustdoc-gui/basic-code.goml @@ -1,6 +1,6 @@ // Small test to ensure the "src-line-numbers" element is only present once on // the page. go-to: "file://" + |DOC_PATH| + "/test_docs/index.html" -click: ".srclink" +click: "a.src" wait-for: ".src-line-numbers" assert-count: (".src-line-numbers", 1) diff --git a/tests/rustdoc-gui/code-sidebar-toggle.goml b/tests/rustdoc-gui/code-sidebar-toggle.goml index 28c3712f307..d1efa45dc1d 100644 --- a/tests/rustdoc-gui/code-sidebar-toggle.goml +++ b/tests/rustdoc-gui/code-sidebar-toggle.goml @@ -1,7 +1,7 @@ // This test checks that the source code pages sidebar toggle is working as expected. go-to: "file://" + |DOC_PATH| + "/test_docs/index.html" -click: ".srclink" +click: "a.src" wait-for: "#src-sidebar-toggle" click: "#src-sidebar-toggle" expect-failure: true -assert-css: ("#source-sidebar", { "left": "-300px" }) +assert-css: ("#src-sidebar", { "left": "-300px" }) diff --git a/tests/rustdoc-gui/headings.goml b/tests/rustdoc-gui/headings.goml index 089e2203a04..102b699b1dd 100644 --- a/tests/rustdoc-gui/headings.goml +++ b/tests/rustdoc-gui/headings.goml @@ -194,27 +194,27 @@ call-function: ( "check-colors", { "theme": "ayu", - "heading_color": "rgb(255, 255, 255)", - "small_heading_color": "rgb(197, 197, 197)", - "heading_border_color": "rgb(92, 103, 115)", + "heading_color": "#fff", + "small_heading_color": "#c5c5c5", + "heading_border_color": "#5c6773", }, ) call-function: ( "check-colors", { "theme": "dark", - "heading_color": "rgb(221, 221, 221)", - "small_heading_color": "rgb(221, 221, 221)", - "heading_border_color": "rgb(210, 210, 210)", + "heading_color": "#ddd", + "small_heading_color": "#ddd", + "heading_border_color": "#d2d2d2", }, ) call-function: ( "check-colors", { "theme": "light", - "heading_color": "rgb(0, 0, 0)", - "small_heading_color": "rgb(0, 0, 0)", - "heading_border_color": "rgb(221, 221, 221)", + "heading_color": "black", + "small_heading_color": "black", + "heading_border_color": "#ddd", }, ) @@ -224,7 +224,7 @@ define-function: ( block { set-local-storage: {"rustdoc-theme": |theme|} reload: - assert-css: (".since", {"color": "rgb(128, 128, 128)"}, ALL) + assert-css: (".since", {"color": "#808080"}, ALL) }, ) diff --git a/tests/rustdoc-gui/jump-to-def-background.goml b/tests/rustdoc-gui/jump-to-def-background.goml index 6adc36b0edb..fa7ed3586dd 100644 --- a/tests/rustdoc-gui/jump-to-def-background.goml +++ b/tests/rustdoc-gui/jump-to-def-background.goml @@ -1,4 +1,4 @@ -// We check the background color on the jump to definition links in the source code page. +// We check the background color on the jump to definition links in the src code page. go-to: "file://" + |DOC_PATH| + "/src/link_to_definition/lib.rs.html" define-function: ( @@ -10,7 +10,7 @@ define-function: ( // We reload the page so the local storage settings are being used. reload: assert-css: ( - "body.source .example-wrap pre.rust a", + "body.src .example-wrap pre.rust a", {"background-color": |background_color|}, ALL, ) diff --git a/tests/rustdoc-gui/sidebar-source-code-display.goml b/tests/rustdoc-gui/sidebar-source-code-display.goml index 0c680bcc9fb..33210c9fdc9 100644 --- a/tests/rustdoc-gui/sidebar-source-code-display.goml +++ b/tests/rustdoc-gui/sidebar-source-code-display.goml @@ -40,7 +40,7 @@ define-function: ( reload: wait-for-css: ("#src-sidebar-toggle", {"visibility": "visible"}) assert-css: ( - "#source-sidebar details[open] > .files a.selected", + "#src-sidebar details[open] > .files a.selected", {"color": |color_hover|, "background-color": |background|}, ) @@ -62,58 +62,58 @@ define-function: ( // Without hover or focus. assert-css: ( - "#source-sidebar details[open] > .files a:not(.selected)", + "#src-sidebar details[open] > .files a:not(.selected)", {"color": |color|, "background-color": |background_toggle|}, ) // With focus. - focus: "#source-sidebar details[open] > .files a:not(.selected)" + focus: "#src-sidebar details[open] > .files a:not(.selected)" wait-for-css: ( - "#source-sidebar details[open] > .files a:not(.selected):focus", + "#src-sidebar details[open] > .files a:not(.selected):focus", {"color": |color_hover|, "background-color": |background_hover|}, ) focus: ".search-input" // With hover. - move-cursor-to: "#source-sidebar details[open] > .files a:not(.selected)" + move-cursor-to: "#src-sidebar details[open] > .files a:not(.selected)" assert-css: ( - "#source-sidebar details[open] > .files a:not(.selected):hover", + "#src-sidebar details[open] > .files a:not(.selected):hover", {"color": |color_hover|, "background-color": |background_hover|}, ) // Without hover or focus. assert-css: ( - "#source-sidebar .dir-entry summary", + "#src-sidebar .dir-entry summary", {"color": |color|, "background-color": |background_toggle|}, ) // With focus. - focus: "#source-sidebar .dir-entry summary" + focus: "#src-sidebar .dir-entry summary" wait-for-css: ( - "#source-sidebar .dir-entry summary:focus", + "#src-sidebar .dir-entry summary:focus", {"color": |color_hover|, "background-color": |background_hover|}, ) focus: ".search-input" // With hover. - move-cursor-to: "#source-sidebar .dir-entry summary" + move-cursor-to: "#src-sidebar .dir-entry summary" assert-css: ( - "#source-sidebar .dir-entry summary:hover", + "#src-sidebar .dir-entry summary:hover", {"color": |color_hover|, "background-color": |background_hover|}, ) // Without hover or focus. assert-css: ( - "#source-sidebar details[open] > .folders > details > summary", + "#src-sidebar details[open] > .folders > details > summary", {"color": |color|, "background-color": |background_toggle|}, ) // With focus. - focus: "#source-sidebar details[open] > .folders > details > summary" + focus: "#src-sidebar details[open] > .folders > details > summary" wait-for-css: ( - "#source-sidebar details[open] > .folders > details > summary:focus", + "#src-sidebar details[open] > .folders > details > summary:focus", {"color": |color_hover|, "background-color": |background_hover|}, ) focus: ".search-input" // With hover. - move-cursor-to: "#source-sidebar details[open] > .folders > details > summary" + move-cursor-to: "#src-sidebar details[open] > .folders > details > summary" assert-css: ( - "#source-sidebar details[open] > .folders > details > summary:hover", + "#src-sidebar details[open] > .folders > details > summary:hover", {"color": |color_hover|, "background-color": |background_hover|}, ) }, @@ -190,16 +190,16 @@ assert-window-property: {"pageYOffset": "2542"} // make it the current selection. set-window-size: (500, 700) click: "#src-sidebar-toggle" -wait-for-css: ("#source-sidebar", {"visibility": "visible"}) +wait-for-css: ("#src-sidebar", {"visibility": "visible"}) assert-local-storage: {"rustdoc-source-sidebar-show": "true"} click: ".sidebar a.selected" go-to: "file://" + |DOC_PATH| + "/src/test_docs/lib.rs.html" -wait-for-css: ("#source-sidebar", {"visibility": "hidden"}) +wait-for-css: ("#src-sidebar", {"visibility": "hidden"}) assert-local-storage: {"rustdoc-source-sidebar-show": "false"} // Resize back to desktop size, to check that the sidebar doesn't spontaneously open. set-window-size: (1000, 1000) -wait-for-css: ("#source-sidebar", {"visibility": "hidden"}) +wait-for-css: ("#src-sidebar", {"visibility": "hidden"}) assert-local-storage: {"rustdoc-source-sidebar-show": "false"} click: "#src-sidebar-toggle" -wait-for-css: ("#source-sidebar", {"visibility": "visible"}) +wait-for-css: ("#src-sidebar", {"visibility": "visible"}) assert-local-storage: {"rustdoc-source-sidebar-show": "true"} diff --git a/tests/rustdoc-gui/sidebar-source-code.goml b/tests/rustdoc-gui/sidebar-source-code.goml index 2cb88817884..69c589741cb 100644 --- a/tests/rustdoc-gui/sidebar-source-code.goml +++ b/tests/rustdoc-gui/sidebar-source-code.goml @@ -14,7 +14,7 @@ define-function: ( } reload: // Checking results colors. - assert-css: (".source .sidebar", { + assert-css: (".src .sidebar", { "color": |color|, "background-color": |background_color| }, ALL) @@ -53,8 +53,8 @@ assert-css: ("nav.sidebar", {"width": "50px"}) // We now click on the button to expand the sidebar. click: (10, 10) // We wait for the sidebar to be expanded. -wait-for-css: (".source-sidebar-expanded nav.sidebar", {"width": "300px"}) -assert-css: (".source-sidebar-expanded nav.sidebar a", {"font-size": "14px"}) +wait-for-css: (".src-sidebar-expanded nav.sidebar", {"width": "300px"}) +assert-css: (".src-sidebar-expanded nav.sidebar a", {"font-size": "14px"}) // We collapse the sidebar. click: (10, 10) // We ensure that the class has been removed. @@ -66,24 +66,24 @@ go-to: "file://" + |DOC_PATH| + "/src/lib2/another_folder/sub_mod/mod.rs.html" // First we expand the sidebar again. click: (10, 10) // We wait for the sidebar to be expanded. -wait-for-css: (".source-sidebar-expanded nav.sidebar", {"width": "300px"}) +wait-for-css: (".src-sidebar-expanded nav.sidebar", {"width": "300px"}) assert: "//*[@class='dir-entry' and @open]/*[text()='lib2']" assert: "//*[@class='dir-entry' and @open]/*[text()='another_folder']" assert: "//*[@class='dir-entry' and @open]/*[text()='sub_mod']" // Only "another_folder" should be "open" in "lib2". assert: "//*[@class='dir-entry' and not(@open)]/*[text()='another_mod']" // All other trees should be collapsed. -assert-count: ("//*[@id='source-sidebar']/details[not(text()='lib2') and not(@open)]", 9) +assert-count: ("//*[@id='src-sidebar']/details[not(text()='lib2') and not(@open)]", 9) // We now switch to mobile mode. set-window-size: (600, 600) -wait-for-css: (".source-sidebar-expanded nav.sidebar", {"left": "0px"}) +wait-for-css: (".src-sidebar-expanded nav.sidebar", {"left": "0px"}) // We collapse the sidebar. click: (10, 10) // We check that the sidebar has been moved off-screen. assert-css: ("nav.sidebar", {"left": "-1000px"}) // We ensure that the class has been removed. -assert-false: ".source-sidebar-expanded" +assert-false: ".src-sidebar-expanded" assert: "nav.sidebar" // Check that the topbar is not visible diff --git a/tests/rustdoc-gui/source-anchor-scroll.goml b/tests/rustdoc-gui/source-anchor-scroll.goml index 67f1497e70c..0e4913cafb2 100644 --- a/tests/rustdoc-gui/source-anchor-scroll.goml +++ b/tests/rustdoc-gui/source-anchor-scroll.goml @@ -7,11 +7,11 @@ set-window-size: (600, 800) // We check that the scroll is at the top first. assert-property: ("html", {"scrollTop": "0"}) -click: '//a[text() = "barbar"]' +click: '//a[text() = "barbar" and @href="#5-7"]' assert-property: ("html", {"scrollTop": "149"}) -click: '//a[text() = "bar"]' +click: '//a[text() = "bar" and @href="#28-36"]' assert-property: ("html", {"scrollTop": "180"}) -click: '//a[text() = "sub_fn"]' +click: '//a[text() = "sub_fn" and @href="#2-4"]' assert-property: ("html", {"scrollTop": "77"}) // We now check that clicking on lines doesn't change the scroll diff --git a/tests/rustdoc-gui/source-code-page.goml b/tests/rustdoc-gui/source-code-page.goml index f8f73398d9b..f19e3ce80e1 100644 --- a/tests/rustdoc-gui/source-code-page.goml +++ b/tests/rustdoc-gui/source-code-page.goml @@ -98,26 +98,26 @@ assert-document-property: ({"URL": "/lib.rs.html"}, ENDS_WITH) // First we "open" it. click: "#src-sidebar-toggle" -assert: ".source-sidebar-expanded" +assert: ".src-sidebar-expanded" // We check that the first entry of the sidebar is collapsed -assert-property: ("#source-sidebar details:first-of-type", {"open": "false"}) -assert-text: ("#source-sidebar details:first-of-type > summary", "extend_css") +assert-property: ("#src-sidebar details:first-of-type", {"open": "false"}) +assert-text: ("#src-sidebar details:first-of-type > summary", "extend_css") // We now click on it. -click: "#source-sidebar details:first-of-type > summary" -assert-property: ("#source-sidebar details:first-of-type", {"open": "true"}) +click: "#src-sidebar details:first-of-type > summary" +assert-property: ("#src-sidebar details:first-of-type", {"open": "true"}) // And now we collapse it again. -click: "#source-sidebar details:first-of-type > summary" -assert-property: ("#source-sidebar details:first-of-type", {"open": "false"}) +click: "#src-sidebar details:first-of-type > summary" +assert-property: ("#src-sidebar details:first-of-type", {"open": "false"}) // And open it again, since it'll be the reference we use to check positions. -click: "#source-sidebar details:first-of-type > summary" -assert-property: ("#source-sidebar details:first-of-type", {"open": "true"}) +click: "#src-sidebar details:first-of-type > summary" +assert-property: ("#src-sidebar details:first-of-type", {"open": "true"}) // Check the sidebar directory entries have a marker and spacing (desktop). store-property: ( - "#source-sidebar > details:first-of-type.dir-entry[open] > .files > a", + "#src-sidebar > details:first-of-type.dir-entry[open] > .files > a", {"offsetHeight": link_height}, ) define-function: ( @@ -125,28 +125,28 @@ define-function: ( (x, y), block { assert: "details:first-of-type.dir-entry[open] > summary::marker" - assert-css: ("#source-sidebar > details:first-of-type.dir-entry", {"padding-left": "4px"}) + assert-css: ("#src-sidebar > details:first-of-type.dir-entry", {"padding-left": "4px"}) // This check ensures that the summary is only one line. assert-property: ( - "#source-sidebar > details:first-of-type.dir-entry[open] > summary", + "#src-sidebar > details:first-of-type.dir-entry[open] > summary", {"offsetHeight": |link_height|} ) assert-position: ( - "#source-sidebar > details:first-of-type.dir-entry[open] > summary", + "#src-sidebar > details:first-of-type.dir-entry[open] > summary", {"x": |x|, "y": |y|} ) assert-property: ( - "#source-sidebar > details:first-of-type.dir-entry[open] > .files > a", + "#src-sidebar > details:first-of-type.dir-entry[open] > .files > a", {"offsetHeight": |link_height|} ) assert-position: ( - "#source-sidebar > details:first-of-type.dir-entry[open] > .files > a", + "#src-sidebar > details:first-of-type.dir-entry[open] > .files > a", // left margin {"x": |x| + 27, "y": |y| + |link_height|} ) } ) -store-property: ("#source-sidebar > .title", { +store-property: ("#src-sidebar > .title", { "offsetHeight": source_sidebar_title_height, "offsetTop": source_sidebar_title_y, }) @@ -175,7 +175,7 @@ assert-property: ("#main-content", {"offsetTop": 76}) // 21 = 76 - 34 - 21 // Check the sidebar directory entries have a marker and spacing (tablet). -store-property: ("#source-sidebar > .title", { +store-property: ("#src-sidebar > .title", { "offsetHeight": source_sidebar_title_height, "offsetTop": source_sidebar_title_y, }) @@ -189,7 +189,7 @@ set-window-size: (450, 700) assert-css: ("nav.sub", {"flex-direction": "column"}) // Check the sidebar directory entries have a marker and spacing (phone). -store-property: ("#source-sidebar > .title", { +store-property: ("#src-sidebar > .title", { "offsetHeight": source_sidebar_title_height, "offsetTop": source_sidebar_title_y, }) diff --git a/tests/rustdoc-gui/src-font-size.goml b/tests/rustdoc-gui/src-font-size.goml index ff30bcdf2a2..f23387d73d3 100644 --- a/tests/rustdoc-gui/src-font-size.goml +++ b/tests/rustdoc-gui/src-font-size.goml @@ -4,13 +4,13 @@ go-to: "file://" + |DOC_PATH| + "/test_docs/struct.Foo.html" show-text: true // Check the impl headers. -assert-css: (".impl .srclink", {"font-size": "16px", "font-weight": 400}, ALL) +assert-css: (".impl a.src", {"font-size": "16px", "font-weight": 400}, ALL) assert-css: (".impl .code-header", {"font-size": "18px", "font-weight": 600}, ALL) // Check the impl items. -assert-css: (".impl-items .srclink", {"font-size": "16px", "font-weight": 400}, ALL) +assert-css: (".impl-items a.src", {"font-size": "16px", "font-weight": 400}, ALL) assert-css: (".impl-items .code-header", {"font-size": "16px", "font-weight": 600}, ALL) // Check that we can click on source link store-document-property: {"URL": url} -click: ".impl-items .srclink" +click: ".impl-items a.src" assert-document-property-false: {"URL": |url|} diff --git a/tests/rustdoc-json/traits/private_supertrait.rs b/tests/rustdoc-json/traits/private_supertrait.rs new file mode 100644 index 00000000000..49238e5e88b --- /dev/null +++ b/tests/rustdoc-json/traits/private_supertrait.rs @@ -0,0 +1,15 @@ +// ignore-tidy-linelength + +#![feature(no_core)] +#![no_core] + + +// @!has "$.index[*][?(@.name == 'sealed')]" +mod sealed { + // @set sealed_id = "$.index[*][?(@.name=='Sealed')].id" + pub trait Sealed {} +} + +// @count "$.index[*][?(@.name=='Trait')].inner.trait.bounds[*]" 1 +// @is "$.index[*][?(@.name=='Trait')].inner.trait.bounds[0].trait_bound.trait.id" $sealed_id +pub trait Trait: sealed::Sealed {} diff --git a/tests/rustdoc/anchors.no_const_anchor.html b/tests/rustdoc/anchors.no_const_anchor.html index a8587829d3e..06673d87406 100644 --- a/tests/rustdoc/anchors.no_const_anchor.html +++ b/tests/rustdoc/anchors.no_const_anchor.html @@ -1 +1 @@ -<section id="associatedconstant.YOLO" class="method"><a class="srclink rightside" href="../src/foo/anchors.rs.html#16">source</a><h4 class="code-header">const <a href="#associatedconstant.YOLO" class="constant">YOLO</a>: <a class="primitive" href="{{channel}}/std/primitive.u32.html">u32</a></h4></section> \ No newline at end of file +<section id="associatedconstant.YOLO" class="method"><a class="src rightside" href="../src/foo/anchors.rs.html#16">source</a><h4 class="code-header">const <a href="#associatedconstant.YOLO" class="constant">YOLO</a>: <a class="primitive" href="{{channel}}/std/primitive.u32.html">u32</a></h4></section> \ No newline at end of file diff --git a/tests/rustdoc/anchors.no_const_anchor2.html b/tests/rustdoc/anchors.no_const_anchor2.html index 4c5e45fea2d..73c3d0a807b 100644 --- a/tests/rustdoc/anchors.no_const_anchor2.html +++ b/tests/rustdoc/anchors.no_const_anchor2.html @@ -1 +1 @@ -<section id="associatedconstant.X" class="associatedconstant"><a class="srclink rightside" href="../src/foo/anchors.rs.html#42">source</a><h4 class="code-header">pub const <a href="#associatedconstant.X" class="constant">X</a>: <a class="primitive" href="{{channel}}/std/primitive.i32.html">i32</a> = 0i32</h4></section> \ No newline at end of file +<section id="associatedconstant.X" class="associatedconstant"><a class="src rightside" href="../src/foo/anchors.rs.html#42">source</a><h4 class="code-header">pub const <a href="#associatedconstant.X" class="constant">X</a>: <a class="primitive" href="{{channel}}/std/primitive.i32.html">i32</a> = 0i32</h4></section> \ No newline at end of file diff --git a/tests/rustdoc/anchors.no_method_anchor.html b/tests/rustdoc/anchors.no_method_anchor.html index 44957a5b71a..e8b61caa1c1 100644 --- a/tests/rustdoc/anchors.no_method_anchor.html +++ b/tests/rustdoc/anchors.no_method_anchor.html @@ -1 +1 @@ -<section id="method.new" class="method"><a class="srclink rightside" href="../src/foo/anchors.rs.html#48">source</a><h4 class="code-header">pub fn <a href="#method.new" class="fn">new</a>() -> Self</h4></section> \ No newline at end of file +<section id="method.new" class="method"><a class="src rightside" href="../src/foo/anchors.rs.html#48">source</a><h4 class="code-header">pub fn <a href="#method.new" class="fn">new</a>() -> Self</h4></section> \ No newline at end of file diff --git a/tests/rustdoc/anchors.no_trait_method_anchor.html b/tests/rustdoc/anchors.no_trait_method_anchor.html index 75c2caf87a8..abdb17c27dc 100644 --- a/tests/rustdoc/anchors.no_trait_method_anchor.html +++ b/tests/rustdoc/anchors.no_trait_method_anchor.html @@ -1 +1 @@ -<section id="method.bar" class="method"><a class="srclink rightside" href="../src/foo/anchors.rs.html#23">source</a><h4 class="code-header">fn <a href="#method.bar" class="fn">bar</a>()</h4></section> \ No newline at end of file +<section id="method.bar" class="method"><a class="src rightside" href="../src/foo/anchors.rs.html#23">source</a><h4 class="code-header">fn <a href="#method.bar" class="fn">bar</a>()</h4></section> \ No newline at end of file diff --git a/tests/rustdoc/anchors.no_tymethod_anchor.html b/tests/rustdoc/anchors.no_tymethod_anchor.html index 38575eadfa9..23f4277c5b5 100644 --- a/tests/rustdoc/anchors.no_tymethod_anchor.html +++ b/tests/rustdoc/anchors.no_tymethod_anchor.html @@ -1 +1 @@ -<section id="tymethod.foo" class="method"><a class="srclink rightside" href="../src/foo/anchors.rs.html#20">source</a><h4 class="code-header">fn <a href="#tymethod.foo" class="fn">foo</a>()</h4></section> \ No newline at end of file +<section id="tymethod.foo" class="method"><a class="src rightside" href="../src/foo/anchors.rs.html#20">source</a><h4 class="code-header">fn <a href="#tymethod.foo" class="fn">foo</a>()</h4></section> \ No newline at end of file diff --git a/tests/rustdoc/anchors.no_type_anchor.html b/tests/rustdoc/anchors.no_type_anchor.html index dd65d98fee6..62b9295508f 100644 --- a/tests/rustdoc/anchors.no_type_anchor.html +++ b/tests/rustdoc/anchors.no_type_anchor.html @@ -1 +1 @@ -<section id="associatedtype.T" class="method"><a class="srclink rightside" href="../src/foo/anchors.rs.html#13">source</a><h4 class="code-header">type <a href="#associatedtype.T" class="associatedtype">T</a></h4></section> \ No newline at end of file +<section id="associatedtype.T" class="method"><a class="src rightside" href="../src/foo/anchors.rs.html#13">source</a><h4 class="code-header">type <a href="#associatedtype.T" class="associatedtype">T</a></h4></section> \ No newline at end of file diff --git a/tests/rustdoc/check-source-code-urls-to-def.rs b/tests/rustdoc/check-source-code-urls-to-def.rs index 41b9d41fa44..b803c7e9e86 100644 --- a/tests/rustdoc/check-source-code-urls-to-def.rs +++ b/tests/rustdoc/check-source-code-urls-to-def.rs @@ -14,10 +14,10 @@ extern crate source_code; #[path = "auxiliary/source-code-bar.rs"] pub mod bar; -// @count - '//pre[@class="rust"]//a[@href="auxiliary/source-code-bar.rs.html#5"]' 4 +// @count - '//pre[@class="rust"]//a[@href="auxiliary/source-code-bar.rs.html#5-7"]' 4 use bar::Bar; -// @has - '//pre[@class="rust"]//a[@href="auxiliary/source-code-bar.rs.html#13"]' 'self' -// @has - '//pre[@class="rust"]//a[@href="auxiliary/source-code-bar.rs.html#14"]' 'Trait' +// @has - '//pre[@class="rust"]//a[@href="auxiliary/source-code-bar.rs.html#13-17"]' 'self' +// @has - '//pre[@class="rust"]//a[@href="auxiliary/source-code-bar.rs.html#14-16"]' 'Trait' use bar::sub::{self, Trait}; pub struct Foo; @@ -32,7 +32,8 @@ fn babar() {} // @has - '//pre[@class="rust"]//a/@href' '/primitive.u32.html' // @has - '//pre[@class="rust"]//a/@href' '/primitive.str.html' // @count - '//pre[@class="rust"]//a[@href="#23"]' 5 -// @has - '//pre[@class="rust"]//a[@href="../../source_code/struct.SourceCode.html"]' 'source_code::SourceCode' +// @has - '//pre[@class="rust"]//a[@href="../../source_code/struct.SourceCode.html"]' \ +// 'source_code::SourceCode' pub fn foo(a: u32, b: &str, c: String, d: Foo, e: bar::Bar, f: source_code::SourceCode) { let x = 12; let y: Foo = Foo; @@ -42,15 +43,15 @@ pub fn foo(a: u32, b: &str, c: String, d: Foo, e: bar::Bar, f: source_code::Sour y.hello(); } -// @has - '//pre[@class="rust"]//a[@href="auxiliary/source-code-bar.rs.html#14"]' 'bar::sub::Trait' -// @has - '//pre[@class="rust"]//a[@href="auxiliary/source-code-bar.rs.html#14"]' 'Trait' +// @has - '//pre[@class="rust"]//a[@href="auxiliary/source-code-bar.rs.html#14-16"]' 'bar::sub::Trait' +// @has - '//pre[@class="rust"]//a[@href="auxiliary/source-code-bar.rs.html#14-16"]' 'Trait' pub fn foo2<T: bar::sub::Trait, V: Trait>(t: &T, v: &V, b: bool) {} pub trait AnotherTrait {} pub trait WhyNot {} -// @has - '//pre[@class="rust"]//a[@href="#49"]' 'AnotherTrait' -// @has - '//pre[@class="rust"]//a[@href="#50"]' 'WhyNot' +// @has - '//pre[@class="rust"]//a[@href="#50"]' 'AnotherTrait' +// @has - '//pre[@class="rust"]//a[@href="#51"]' 'WhyNot' pub fn foo3<T, V>(t: &T, v: &V) where T: AnotherTrait, @@ -59,7 +60,7 @@ where pub trait AnotherTrait2 {} -// @has - '//pre[@class="rust"]//a[@href="#60"]' 'AnotherTrait2' +// @has - '//pre[@class="rust"]//a[@href="#61"]' 'AnotherTrait2' pub fn foo4() { let x: Vec<AnotherTrait2> = Vec::new(); } diff --git a/tests/rustdoc/ensure-src-link.rs b/tests/rustdoc/ensure-src-link.rs index c65387080f1..f99c4c4d988 100644 --- a/tests/rustdoc/ensure-src-link.rs +++ b/tests/rustdoc/ensure-src-link.rs @@ -2,5 +2,5 @@ // This test ensures that the [src] link is present on traits items. -// @has foo/trait.Iterator.html '//*[@id="method.zip"]//a[@class="srclink rightside"]' "source" +// @has foo/trait.Iterator.html '//*[@id="method.zip"]//a[@class="src rightside"]' "source" pub use std::iter::Iterator; diff --git a/tests/rustdoc/jump-to-def-doc-links.rs b/tests/rustdoc/jump-to-def-doc-links.rs new file mode 100644 index 00000000000..014d5803299 --- /dev/null +++ b/tests/rustdoc/jump-to-def-doc-links.rs @@ -0,0 +1,51 @@ +// compile-flags: -Zunstable-options --generate-link-to-definition + +#![crate_name = "foo"] + +// @has 'src/foo/jump-to-def-doc-links.rs.html' + +// @has - '//a[@href="../../foo/struct.Bar.html"]' 'Bar' +// @has - '//a[@href="../../foo/struct.Foo.html"]' 'Foo' +pub struct Bar; pub struct Foo; + +// @has - '//a[@href="../../foo/enum.Enum.html"]' 'Enum' +pub enum Enum { + Variant1(String), + Variant2(u8), +} + +// @has - '//a[@href="../../foo/struct.Struct.html"]' 'Struct' +pub struct Struct { + pub a: u8, + b: Foo, +} + +impl Struct { + pub fn foo() {} + pub fn foo2(&self) {} + fn bar() {} + fn bar(&self) {} +} + +// @has - '//a[@href="../../foo/trait.Trait.html"]' 'Trait' +pub trait Trait { + fn foo(); +} + +impl Trait for Struct { + fn foo() {} +} + +// @has - '//a[@href="../../foo/union.Union.html"]' 'Union' +pub union Union { + pub a: u16, + pub f: u32, +} + +// @has - '//a[@href="../../foo/fn.bar.html"]' 'bar' +pub fn bar(b: Bar) { + let x = Foo; +} + +// @has - '//a[@href="../../foo/bar/index.html"]' 'bar' +pub mod bar {} diff --git a/tests/rustdoc/source-file.rs b/tests/rustdoc/source-file.rs index 4e166479063..16d4cbe3a34 100644 --- a/tests/rustdoc/source-file.rs +++ b/tests/rustdoc/source-file.rs @@ -1,5 +1,5 @@ #![crate_name = "foo"] -// @hasraw source-files.js source-file.rs +// @hasraw src-files.js source-file.rs pub struct Foo; diff --git a/tests/rustdoc/src-links-auto-impls.rs b/tests/rustdoc/src-links-auto-impls.rs index 953563833c9..1c8d1573192 100644 --- a/tests/rustdoc/src-links-auto-impls.rs +++ b/tests/rustdoc/src-links-auto-impls.rs @@ -2,11 +2,11 @@ // @has foo/struct.Unsized.html // @has - '//*[@id="impl-Sized-for-Unsized"]/h3[@class="code-header"]' 'impl !Sized for Unsized' -// @!has - '//*[@id="impl-Sized-for-Unsized"]//a[@class="srclink"]' 'source' +// @!has - '//*[@id="impl-Sized-for-Unsized"]//a[@class="src"]' 'source' // @has - '//*[@id="impl-Sync-for-Unsized"]/h3[@class="code-header"]' 'impl Sync for Unsized' -// @!has - '//*[@id="impl-Sync-for-Unsized"]//a[@class="srclink"]' 'source' +// @!has - '//*[@id="impl-Sync-for-Unsized"]//a[@class="src"]' 'source' // @has - '//*[@id="impl-Any-for-Unsized"]/h3[@class="code-header"]' 'impl<T> Any for T' -// @has - '//*[@id="impl-Any-for-Unsized"]//a[@class="srclink rightside"]' 'source' +// @has - '//*[@id="impl-Any-for-Unsized"]//a[@class="src rightside"]' 'source' pub struct Unsized { data: [u8], } diff --git a/tests/rustdoc/static-root-path.rs b/tests/rustdoc/static-root-path.rs index 86928b0fb0a..3148ea047b7 100644 --- a/tests/rustdoc/static-root-path.rs +++ b/tests/rustdoc/static-root-path.rs @@ -8,10 +8,10 @@ pub struct SomeStruct; // @has src/static_root_path/static-root-path.rs.html -// @matchesraw - '"/cache/source-script-' -// @!matchesraw - '"\.\./\.\./source-script' -// @matchesraw - '"\.\./\.\./source-files.js"' -// @!matchesraw - '"/cache/source-files\.js"' +// @matchesraw - '"/cache/src-script-' +// @!matchesraw - '"\.\./\.\./src-script' +// @matchesraw - '"\.\./\.\./src-files.js"' +// @!matchesraw - '"/cache/src-files\.js"' // @has settings.html // @matchesraw - '/cache/settings-' diff --git a/tests/ui-fulldeps/missing-rustc-driver-error.rs b/tests/ui-fulldeps/missing-rustc-driver-error.rs index 654cd6f6dc9..b627a207c98 100644 --- a/tests/ui-fulldeps/missing-rustc-driver-error.rs +++ b/tests/ui-fulldeps/missing-rustc-driver-error.rs @@ -1,8 +1,8 @@ // Test that we get the following hint when trying to use a compiler crate without rustc_driver. // error-pattern: try adding `extern crate rustc_driver;` at the top level of this crate // compile-flags: --emit link -// The exactly list of required crates depends on the target. as such only test Unix targets. -// only-unix +// normalize-stderr-test ".*crate .* required.*\n\n" -> "" +// normalize-stderr-test: "aborting due to [0-9]+" -> "aborting due to NUMBER" #![feature(rustc_private)] diff --git a/tests/ui-fulldeps/missing-rustc-driver-error.stderr b/tests/ui-fulldeps/missing-rustc-driver-error.stderr index 939e888e5cb..d7bf27d6349 100644 --- a/tests/ui-fulldeps/missing-rustc-driver-error.stderr +++ b/tests/ui-fulldeps/missing-rustc-driver-error.stderr @@ -2,15 +2,5 @@ error: crate `rustc_serialize` required to be available in rlib format, but was | = help: try adding `extern crate rustc_driver;` at the top level of this crate -error: crate `smallvec` required to be available in rlib format, but was not found in this form - -error: crate `thin_vec` required to be available in rlib format, but was not found in this form - -error: crate `indexmap` required to be available in rlib format, but was not found in this form - -error: crate `hashbrown` required to be available in rlib format, but was not found in this form - -error: crate `equivalent` required to be available in rlib format, but was not found in this form - -error: aborting due to 6 previous errors +error: aborting due to NUMBER previous errors diff --git a/tests/ui/array-slice-vec/vec-mut-iter-borrow.stderr b/tests/ui/array-slice-vec/vec-mut-iter-borrow.stderr index 0ec263c850e..679fd899773 100644 --- a/tests/ui/array-slice-vec/vec-mut-iter-borrow.stderr +++ b/tests/ui/array-slice-vec/vec-mut-iter-borrow.stderr @@ -7,7 +7,7 @@ LL | for x in &mut xs { | first mutable borrow occurs here | first borrow later used here LL | xs.push(1) - | ^^^^^^^^^^ second mutable borrow occurs here + | ^^ second mutable borrow occurs here error: aborting due to previous error diff --git a/tests/ui/associated-consts/issue-105330.stderr b/tests/ui/associated-consts/issue-105330.stderr index bbafc55dac3..e9fe3a5e514 100644 --- a/tests/ui/associated-consts/issue-105330.stderr +++ b/tests/ui/associated-consts/issue-105330.stderr @@ -39,6 +39,12 @@ error[E0562]: `impl Trait` only allowed in function and inherent method return t LL | impl TraitWAssocConst for impl Demo { | ^^^^^^^^^ +error[E0131]: `main` function is not allowed to have generic parameters + --> $DIR/issue-105330.rs:17:8 + | +LL | fn main<A: TraitWAssocConst<A=32>>() { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ `main` cannot have generic parameters + error[E0277]: the trait bound `Demo: TraitWAssocConst` is not satisfied --> $DIR/issue-105330.rs:12:11 | @@ -101,12 +107,6 @@ note: required by a bound in `foo` LL | fn foo<A: TraitWAssocConst<A=32>>() { | ^^^^ required by this bound in `foo` -error[E0131]: `main` function is not allowed to have generic parameters - --> $DIR/issue-105330.rs:17:8 - | -LL | fn main<A: TraitWAssocConst<A=32>>() { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ `main` cannot have generic parameters - error: aborting due to 11 previous errors Some errors have detailed explanations: E0131, E0271, E0277, E0404, E0562, E0618, E0658. diff --git a/tests/ui/associated-inherent-types/inference.rs b/tests/ui/associated-inherent-types/inference.rs index ebd8e1d5594..66f879c5a71 100644 --- a/tests/ui/associated-inherent-types/inference.rs +++ b/tests/ui/associated-inherent-types/inference.rs @@ -1,5 +1,7 @@ // Testing inference capabilities. // check-pass +// revisions: current next +//[next] compile-flags: -Ztrait-solver=next #![feature(inherent_associated_types)] #![allow(incomplete_features)] diff --git a/tests/ui/async-await/clone-suggestion.stderr b/tests/ui/async-await/clone-suggestion.stderr index c02206f6f9b..b5c8ef6993d 100644 --- a/tests/ui/async-await/clone-suggestion.stderr +++ b/tests/ui/async-await/clone-suggestion.stderr @@ -13,7 +13,7 @@ note: `into_future` takes ownership of the receiver `self`, which moves `f` help: you can `clone` the value and consume it, but this might not be your desired behavior | LL | f.clone().await; - | ++++++++ + | ++++++++ error: aborting due to previous error diff --git a/tests/ui/async-await/issue-61452.stderr b/tests/ui/async-await/issue-61452.stderr index bf504432880..3f623ba8ad2 100644 --- a/tests/ui/async-await/issue-61452.stderr +++ b/tests/ui/async-await/issue-61452.stderr @@ -2,7 +2,7 @@ error[E0596]: cannot borrow `x` as mutable, as it is not declared as mutable --> $DIR/issue-61452.rs:4:5 | LL | x.take(); - | ^^^^^^^^ cannot borrow as mutable + | ^ cannot borrow as mutable | help: consider changing this to be mutable | diff --git a/tests/ui/async-await/issues/issue-61187.stderr b/tests/ui/async-await/issues/issue-61187.stderr index e58f7454689..203b17550a0 100644 --- a/tests/ui/async-await/issues/issue-61187.stderr +++ b/tests/ui/async-await/issues/issue-61187.stderr @@ -2,7 +2,7 @@ error[E0596]: cannot borrow `data` as mutable, as it is not declared as mutable --> $DIR/issue-61187.rs:6:5 | LL | data.reverse(); - | ^^^^^^^^^^^^^^ cannot borrow as mutable + | ^^^^ cannot borrow as mutable | help: consider changing this to be mutable | diff --git a/tests/ui/attributes/auxiliary/rustc_confusables_across_crate.rs b/tests/ui/attributes/auxiliary/rustc_confusables_across_crate.rs new file mode 100644 index 00000000000..2fb2d3ad4c4 --- /dev/null +++ b/tests/ui/attributes/auxiliary/rustc_confusables_across_crate.rs @@ -0,0 +1,11 @@ +#![feature(rustc_attrs)] + +pub struct BTreeSet; + +impl BTreeSet { + #[rustc_confusables("push", "test_b")] + pub fn insert(&self) {} + + #[rustc_confusables("pulled")] + pub fn pull(&self) {} +} diff --git a/tests/ui/attributes/rustc_confusables.rs b/tests/ui/attributes/rustc_confusables.rs new file mode 100644 index 00000000000..352e91d065f --- /dev/null +++ b/tests/ui/attributes/rustc_confusables.rs @@ -0,0 +1,47 @@ +// aux-build: rustc_confusables_across_crate.rs + +#![feature(rustc_attrs)] + +extern crate rustc_confusables_across_crate; + +use rustc_confusables_across_crate::BTreeSet; + +fn main() { + // Misspellings (similarly named methods) take precedence over `rustc_confusables`. + let x = BTreeSet {}; + x.inser(); + //~^ ERROR no method named + //~| HELP there is a method with a similar name + x.foo(); + //~^ ERROR no method named + x.push(); + //~^ ERROR no method named + //~| HELP you might have meant to use `insert` + x.test(); + //~^ ERROR no method named + x.pulled(); + //~^ ERROR no method named + //~| HELP there is a method with a similar name +} + +struct Bar; + +impl Bar { + #[rustc_confusables()] + //~^ ERROR expected at least one confusable name + fn baz() {} + + #[rustc_confusables] + //~^ ERROR malformed `rustc_confusables` attribute input + //~| HELP must be of the form + fn qux() {} + + #[rustc_confusables(invalid_meta_item)] + //~^ ERROR expected a quoted string literal + //~| HELP consider surrounding this with quotes + fn quux() {} +} + +#[rustc_confusables("blah")] +//~^ ERROR attribute should be applied to an inherent method +fn not_inherent_impl_method() {} diff --git a/tests/ui/attributes/rustc_confusables.stderr b/tests/ui/attributes/rustc_confusables.stderr new file mode 100644 index 00000000000..9fd4470cdbb --- /dev/null +++ b/tests/ui/attributes/rustc_confusables.stderr @@ -0,0 +1,68 @@ +error: malformed `rustc_confusables` attribute input + --> $DIR/rustc_confusables.rs:34:5 + | +LL | #[rustc_confusables] + | ^^^^^^^^^^^^^^^^^^^^ help: must be of the form: `#[rustc_confusables("name1", "name2", ...)]` + +error: attribute should be applied to an inherent method + --> $DIR/rustc_confusables.rs:45:1 + | +LL | #[rustc_confusables("blah")] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: expected at least one confusable name + --> $DIR/rustc_confusables.rs:30:5 + | +LL | #[rustc_confusables()] + | ^^^^^^^^^^^^^^^^^^^^^^ + +error[E0539]: expected a quoted string literal + --> $DIR/rustc_confusables.rs:39:25 + | +LL | #[rustc_confusables(invalid_meta_item)] + | ^^^^^^^^^^^^^^^^^ + | +help: consider surrounding this with quotes + | +LL | #[rustc_confusables("invalid_meta_item")] + | + + + +error[E0599]: no method named `inser` found for struct `rustc_confusables_across_crate::BTreeSet` in the current scope + --> $DIR/rustc_confusables.rs:12:7 + | +LL | x.inser(); + | ^^^^^ help: there is a method with a similar name: `insert` + +error[E0599]: no method named `foo` found for struct `rustc_confusables_across_crate::BTreeSet` in the current scope + --> $DIR/rustc_confusables.rs:15:7 + | +LL | x.foo(); + | ^^^ method not found in `BTreeSet` + +error[E0599]: no method named `push` found for struct `rustc_confusables_across_crate::BTreeSet` in the current scope + --> $DIR/rustc_confusables.rs:17:7 + | +LL | x.push(); + | ^^^^ method not found in `BTreeSet` + | +help: you might have meant to use `insert` + | +LL | x.insert(); + | ~~~~~~ + +error[E0599]: no method named `test` found for struct `rustc_confusables_across_crate::BTreeSet` in the current scope + --> $DIR/rustc_confusables.rs:20:7 + | +LL | x.test(); + | ^^^^ method not found in `BTreeSet` + +error[E0599]: no method named `pulled` found for struct `rustc_confusables_across_crate::BTreeSet` in the current scope + --> $DIR/rustc_confusables.rs:22:7 + | +LL | x.pulled(); + | ^^^^^^ help: there is a method with a similar name: `pull` + +error: aborting due to 9 previous errors + +Some errors have detailed explanations: E0539, E0599. +For more information about an error, try `rustc --explain E0539`. diff --git a/tests/ui/binop/binop-move-semantics.stderr b/tests/ui/binop/binop-move-semantics.stderr index 8645169b98a..1dd8c9a87d4 100644 --- a/tests/ui/binop/binop-move-semantics.stderr +++ b/tests/ui/binop/binop-move-semantics.stderr @@ -27,7 +27,7 @@ LL | x | - value moved here LL | + LL | x.clone(); - | ^^^^^^^^^ value borrowed here after move + | ^ value borrowed here after move | help: consider cloning the value if the performance cost is acceptable | diff --git a/tests/ui/borrowck/borrow-tuple-fields.stderr b/tests/ui/borrowck/borrow-tuple-fields.stderr index d7d3efe492c..e324ebfb50f 100644 --- a/tests/ui/borrowck/borrow-tuple-fields.stderr +++ b/tests/ui/borrowck/borrow-tuple-fields.stderr @@ -9,7 +9,7 @@ LL | let y = x; | ^ move out of `x` occurs here LL | LL | r.use_ref(); - | ----------- borrow later used here + | - borrow later used here error[E0502]: cannot borrow `x.0` as mutable because it is also borrowed as immutable --> $DIR/borrow-tuple-fields.rs:18:13 @@ -19,7 +19,7 @@ LL | let a = &x.0; LL | let b = &mut x.0; | ^^^^^^^^ mutable borrow occurs here LL | a.use_ref(); - | ----------- immutable borrow later used here + | - immutable borrow later used here error[E0499]: cannot borrow `x.0` as mutable more than once at a time --> $DIR/borrow-tuple-fields.rs:23:13 @@ -29,7 +29,7 @@ LL | let a = &mut x.0; LL | let b = &mut x.0; | ^^^^^^^^ second mutable borrow occurs here LL | a.use_ref(); - | ----------- first borrow later used here + | - first borrow later used here error[E0505]: cannot move out of `x` because it is borrowed --> $DIR/borrow-tuple-fields.rs:28:13 @@ -41,7 +41,7 @@ LL | let r = &x.0; LL | let y = x; | ^ move out of `x` occurs here LL | r.use_ref(); - | ----------- borrow later used here + | - borrow later used here error[E0502]: cannot borrow `x.0` as mutable because it is also borrowed as immutable --> $DIR/borrow-tuple-fields.rs:33:13 @@ -51,7 +51,7 @@ LL | let a = &x.0; LL | let b = &mut x.0; | ^^^^^^^^ mutable borrow occurs here LL | a.use_ref(); - | ----------- immutable borrow later used here + | - immutable borrow later used here error[E0499]: cannot borrow `x.0` as mutable more than once at a time --> $DIR/borrow-tuple-fields.rs:38:13 @@ -61,7 +61,7 @@ LL | let a = &mut x.0; LL | let b = &mut x.0; | ^^^^^^^^ second mutable borrow occurs here LL | a.use_mut(); - | ----------- first borrow later used here + | - first borrow later used here error: aborting due to 6 previous errors diff --git a/tests/ui/borrowck/borrowck-argument.stderr b/tests/ui/borrowck/borrowck-argument.stderr index 1c992dfcceb..8ad5623c8b8 100644 --- a/tests/ui/borrowck/borrowck-argument.stderr +++ b/tests/ui/borrowck/borrowck-argument.stderr @@ -2,7 +2,7 @@ error[E0596]: cannot borrow `arg` as mutable, as it is not declared as mutable --> $DIR/borrowck-argument.rs:10:5 | LL | arg.mutate(); - | ^^^^^^^^^^^^ cannot borrow as mutable + | ^^^ cannot borrow as mutable | help: consider changing this to be mutable | @@ -13,7 +13,7 @@ error[E0596]: cannot borrow `arg` as mutable, as it is not declared as mutable --> $DIR/borrowck-argument.rs:15:9 | LL | arg.mutate(); - | ^^^^^^^^^^^^ cannot borrow as mutable + | ^^^ cannot borrow as mutable | help: consider changing this to be mutable | @@ -24,7 +24,7 @@ error[E0596]: cannot borrow `arg` as mutable, as it is not declared as mutable --> $DIR/borrowck-argument.rs:21:9 | LL | arg.mutate(); - | ^^^^^^^^^^^^ cannot borrow as mutable + | ^^^ cannot borrow as mutable | help: consider changing this to be mutable | @@ -35,7 +35,7 @@ error[E0596]: cannot borrow `arg` as mutable, as it is not declared as mutable --> $DIR/borrowck-argument.rs:32:17 | LL | (|arg: S| { arg.mutate() })(s); - | ^^^^^^^^^^^^ cannot borrow as mutable + | ^^^ cannot borrow as mutable | help: consider changing this to be mutable | diff --git a/tests/ui/borrowck/borrowck-auto-mut-ref-to-immut-var.stderr b/tests/ui/borrowck/borrowck-auto-mut-ref-to-immut-var.stderr index 19ef0301a2d..25d642c30dd 100644 --- a/tests/ui/borrowck/borrowck-auto-mut-ref-to-immut-var.stderr +++ b/tests/ui/borrowck/borrowck-auto-mut-ref-to-immut-var.stderr @@ -2,7 +2,7 @@ error[E0596]: cannot borrow `x` as mutable, as it is not declared as mutable --> $DIR/borrowck-auto-mut-ref-to-immut-var.rs:15:5 | LL | x.printme(); - | ^^^^^^^^^^^ cannot borrow as mutable + | ^ cannot borrow as mutable | help: consider changing this to be mutable | diff --git a/tests/ui/borrowck/borrowck-borrow-immut-deref-of-box-as-mut.stderr b/tests/ui/borrowck/borrowck-borrow-immut-deref-of-box-as-mut.stderr index 3c28ff56e41..a61fdbf6c8f 100644 --- a/tests/ui/borrowck/borrowck-borrow-immut-deref-of-box-as-mut.stderr +++ b/tests/ui/borrowck/borrowck-borrow-immut-deref-of-box-as-mut.stderr @@ -2,7 +2,7 @@ error[E0596]: cannot borrow `*a` as mutable, as `a` is not declared as mutable --> $DIR/borrowck-borrow-immut-deref-of-box-as-mut.rs:12:5 | LL | a.foo(); - | ^^^^^^^ cannot borrow as mutable + | ^ cannot borrow as mutable | help: consider changing this to be mutable | diff --git a/tests/ui/borrowck/borrowck-borrow-mut-object-twice.stderr b/tests/ui/borrowck/borrowck-borrow-mut-object-twice.stderr index 42b6c34cd2f..fa0ae318e72 100644 --- a/tests/ui/borrowck/borrowck-borrow-mut-object-twice.stderr +++ b/tests/ui/borrowck/borrowck-borrow-mut-object-twice.stderr @@ -2,11 +2,11 @@ error[E0499]: cannot borrow `*x` as mutable more than once at a time --> $DIR/borrowck-borrow-mut-object-twice.rs:13:5 | LL | let y = x.f1(); - | ------ first mutable borrow occurs here + | - first mutable borrow occurs here LL | x.f2(); - | ^^^^^^ second mutable borrow occurs here + | ^ second mutable borrow occurs here LL | y.use_ref(); - | ----------- first borrow later used here + | - first borrow later used here error: aborting due to previous error diff --git a/tests/ui/borrowck/borrowck-borrow-overloaded-auto-deref.stderr b/tests/ui/borrowck/borrowck-borrow-overloaded-auto-deref.stderr index fdf6568d839..426d5bc4726 100644 --- a/tests/ui/borrowck/borrowck-borrow-overloaded-auto-deref.stderr +++ b/tests/ui/borrowck/borrowck-borrow-overloaded-auto-deref.stderr @@ -58,7 +58,7 @@ error[E0596]: cannot borrow data in an `Rc` as mutable --> $DIR/borrowck-borrow-overloaded-auto-deref.rs:72:5 | LL | x.set(0, 0); - | ^^^^^^^^^^^ cannot borrow as mutable + | ^ cannot borrow as mutable | = help: trait `DerefMut` is required to modify through a dereference, but it is not implemented for `Rc<Point>` @@ -66,7 +66,7 @@ error[E0596]: cannot borrow data in an `Rc` as mutable --> $DIR/borrowck-borrow-overloaded-auto-deref.rs:76:5 | LL | x.set(0, 0); - | ^^^^^^^^^^^ cannot borrow as mutable + | ^ cannot borrow as mutable | = help: trait `DerefMut` is required to modify through a dereference, but it is not implemented for `Rc<Point>` @@ -74,7 +74,7 @@ error[E0596]: cannot borrow data in an `Rc` as mutable --> $DIR/borrowck-borrow-overloaded-auto-deref.rs:84:5 | LL | x.y_mut() - | ^^^^^^^^^ cannot borrow as mutable + | ^ cannot borrow as mutable | = help: trait `DerefMut` is required to modify through a dereference, but it is not implemented for `Rc<Point>` @@ -82,7 +82,7 @@ error[E0596]: cannot borrow data in an `Rc` as mutable --> $DIR/borrowck-borrow-overloaded-auto-deref.rs:88:5 | LL | x.y_mut() - | ^^^^^^^^^ cannot borrow as mutable + | ^ cannot borrow as mutable | = help: trait `DerefMut` is required to modify through a dereference, but it is not implemented for `Rc<Point>` @@ -90,7 +90,7 @@ error[E0596]: cannot borrow data in an `Rc` as mutable --> $DIR/borrowck-borrow-overloaded-auto-deref.rs:92:6 | LL | *x.y_mut() = 3; - | ^^^^^^^^^ cannot borrow as mutable + | ^ cannot borrow as mutable | = help: trait `DerefMut` is required to modify through a dereference, but it is not implemented for `Rc<Point>` @@ -98,7 +98,7 @@ error[E0596]: cannot borrow data in an `Rc` as mutable --> $DIR/borrowck-borrow-overloaded-auto-deref.rs:96:6 | LL | *x.y_mut() = 3; - | ^^^^^^^^^ cannot borrow as mutable + | ^ cannot borrow as mutable | = help: trait `DerefMut` is required to modify through a dereference, but it is not implemented for `Rc<Point>` @@ -106,7 +106,7 @@ error[E0596]: cannot borrow data in an `Rc` as mutable --> $DIR/borrowck-borrow-overloaded-auto-deref.rs:100:6 | LL | *x.y_mut() = 3; - | ^^^^^^^^^ cannot borrow as mutable + | ^ cannot borrow as mutable | = help: trait `DerefMut` is required to modify through a dereference, but it is not implemented for `Rc<Point>` diff --git a/tests/ui/borrowck/borrowck-borrowed-uniq-rvalue.stderr b/tests/ui/borrowck/borrowck-borrowed-uniq-rvalue.stderr index c62d5f903c8..7ee840b34c5 100644 --- a/tests/ui/borrowck/borrowck-borrowed-uniq-rvalue.stderr +++ b/tests/ui/borrowck/borrowck-borrowed-uniq-rvalue.stderr @@ -7,7 +7,7 @@ LL | buggy_map.insert(42, &*Box::new(1)); | creates a temporary value which is freed while still in use ... LL | buggy_map.insert(43, &*tmp); - | --------------------------- borrow later used here + | --------- borrow later used here | help: consider using a `let` binding to create a longer lived value | diff --git a/tests/ui/borrowck/borrowck-closures-unique-imm.stderr b/tests/ui/borrowck/borrowck-closures-unique-imm.stderr index 0c5fd39b718..b8bbb31a355 100644 --- a/tests/ui/borrowck/borrowck-closures-unique-imm.stderr +++ b/tests/ui/borrowck/borrowck-closures-unique-imm.stderr @@ -6,7 +6,7 @@ LL | let p = &this.x; LL | &mut this.x; | ^^^^^^^^^^^ mutable borrow occurs here LL | p.use_ref(); - | ----------- immutable borrow later used here + | - immutable borrow later used here error: aborting due to previous error diff --git a/tests/ui/borrowck/borrowck-describe-lvalue.stderr b/tests/ui/borrowck/borrowck-describe-lvalue.stderr index cb29c9fdac3..11f2e42d42b 100644 --- a/tests/ui/borrowck/borrowck-describe-lvalue.stderr +++ b/tests/ui/borrowck/borrowck-describe-lvalue.stderr @@ -45,7 +45,7 @@ error[E0503]: cannot use `f.x` because it was mutably borrowed --> $DIR/borrowck-describe-lvalue.rs:37:9 | LL | let x = f.x(); - | ----- `f` is borrowed here + | - `f` is borrowed here LL | f.x; | ^^^ use of borrowed `f` LL | drop(x); @@ -55,7 +55,7 @@ error[E0503]: cannot use `g.0` because it was mutably borrowed --> $DIR/borrowck-describe-lvalue.rs:44:9 | LL | let x = g.x(); - | ----- `g` is borrowed here + | - `g` is borrowed here LL | g.0; | ^^^ use of borrowed `g` LL | drop(x); @@ -75,7 +75,7 @@ error[E0503]: cannot use `e.0` because it was mutably borrowed --> $DIR/borrowck-describe-lvalue.rs:59:20 | LL | let x = e.x(); - | ----- `e` is borrowed here + | - `e` is borrowed here LL | match e { LL | Baz::X(value) => value | ^^^^^ use of borrowed `e` @@ -97,7 +97,7 @@ error[E0503]: cannot use `f.x` because it was mutably borrowed --> $DIR/borrowck-describe-lvalue.rs:74:9 | LL | let x = f.x(); - | ----- `*f` is borrowed here + | - `*f` is borrowed here LL | f.x; | ^^^ use of borrowed `*f` LL | drop(x); @@ -107,7 +107,7 @@ error[E0503]: cannot use `g.0` because it was mutably borrowed --> $DIR/borrowck-describe-lvalue.rs:81:9 | LL | let x = g.x(); - | ----- `*g` is borrowed here + | - `*g` is borrowed here LL | g.0; | ^^^ use of borrowed `*g` LL | drop(x); @@ -127,7 +127,7 @@ error[E0503]: cannot use `e.0` because it was mutably borrowed --> $DIR/borrowck-describe-lvalue.rs:96:20 | LL | let x = e.x(); - | ----- `*e` is borrowed here + | - `*e` is borrowed here LL | match *e { LL | Baz::X(value) => value | ^^^^^ use of borrowed `*e` diff --git a/tests/ui/borrowck/borrowck-insert-during-each.stderr b/tests/ui/borrowck/borrowck-insert-during-each.stderr index 99d08e905d5..a1ac45795fa 100644 --- a/tests/ui/borrowck/borrowck-insert-during-each.stderr +++ b/tests/ui/borrowck/borrowck-insert-during-each.stderr @@ -16,17 +16,15 @@ LL | | }) error[E0500]: closure requires unique access to `f` but it is already borrowed --> $DIR/borrowck-insert-during-each.rs:18:9 | -LL | f.foo( - | - --- first borrow later used by call - | _____| - | | -LL | | -LL | | |a| { - | | ^^^ closure construction occurs here -LL | | f.n.insert(*a); - | | --- second borrow occurs due to use of `f` in closure -LL | | }) - | |__________- borrow occurs here +LL | f.foo( + | - --- first borrow later used by call + | | + | borrow occurs here +LL | +LL | |a| { + | ^^^ closure construction occurs here +LL | f.n.insert(*a); + | --- second borrow occurs due to use of `f` in closure error: aborting due to 2 previous errors diff --git a/tests/ui/borrowck/borrowck-issue-2657-1.stderr b/tests/ui/borrowck/borrowck-issue-2657-1.stderr index 390bb9384f8..4ea4eb8f007 100644 --- a/tests/ui/borrowck/borrowck-issue-2657-1.stderr +++ b/tests/ui/borrowck/borrowck-issue-2657-1.stderr @@ -6,7 +6,7 @@ LL | Some(ref _y) => { LL | let _a = x; | ^ move out of `x` occurs here LL | _y.use_ref(); - | ------------ borrow later used here + | -- borrow later used here error: aborting due to previous error diff --git a/tests/ui/borrowck/borrowck-lend-flow-if.stderr b/tests/ui/borrowck/borrowck-lend-flow-if.stderr index e47efc0e0b3..68a82bdb57c 100644 --- a/tests/ui/borrowck/borrowck-lend-flow-if.stderr +++ b/tests/ui/borrowck/borrowck-lend-flow-if.stderr @@ -7,7 +7,7 @@ LL | } LL | borrow_mut(&mut *v); | ^^^^^^^ mutable borrow occurs here LL | _w.use_ref(); - | ------------ immutable borrow later used here + | -- immutable borrow later used here error: aborting due to previous error diff --git a/tests/ui/borrowck/borrowck-lend-flow.stderr b/tests/ui/borrowck/borrowck-lend-flow.stderr index 40c14f54cb8..07b11b3e728 100644 --- a/tests/ui/borrowck/borrowck-lend-flow.stderr +++ b/tests/ui/borrowck/borrowck-lend-flow.stderr @@ -6,7 +6,7 @@ LL | let _w = &v; LL | borrow_mut(&mut *v); | ^^^^^^^ mutable borrow occurs here LL | _w.use_ref(); - | ------------ immutable borrow later used here + | -- immutable borrow later used here error: aborting due to previous error diff --git a/tests/ui/borrowck/borrowck-loan-blocks-move-cc.stderr b/tests/ui/borrowck/borrowck-loan-blocks-move-cc.stderr index 6eabfff9054..86479043a06 100644 --- a/tests/ui/borrowck/borrowck-loan-blocks-move-cc.stderr +++ b/tests/ui/borrowck/borrowck-loan-blocks-move-cc.stderr @@ -12,7 +12,7 @@ LL | println!("v={}", *v); | -- move occurs due to use in closure LL | }); LL | w.use_ref(); - | ----------- borrow later used here + | - borrow later used here error[E0505]: cannot move out of `v` because it is borrowed --> $DIR/borrowck-loan-blocks-move-cc.rs:24:19 @@ -28,7 +28,7 @@ LL | println!("v={}", *v); | -- move occurs due to use in closure LL | }); LL | w.use_ref(); - | ----------- borrow later used here + | - borrow later used here error: aborting due to 2 previous errors diff --git a/tests/ui/borrowck/borrowck-loan-blocks-move.stderr b/tests/ui/borrowck/borrowck-loan-blocks-move.stderr index 38e06fa0187..de8da490c2e 100644 --- a/tests/ui/borrowck/borrowck-loan-blocks-move.stderr +++ b/tests/ui/borrowck/borrowck-loan-blocks-move.stderr @@ -8,7 +8,7 @@ LL | let w = &v; LL | take(v); | ^ move out of `v` occurs here LL | w.use_ref(); - | ----------- borrow later used here + | - borrow later used here error: aborting due to previous error diff --git a/tests/ui/borrowck/borrowck-loan-in-overloaded-op.stderr b/tests/ui/borrowck/borrowck-loan-in-overloaded-op.stderr index e1b99162088..93622a0c5f6 100644 --- a/tests/ui/borrowck/borrowck-loan-in-overloaded-op.stderr +++ b/tests/ui/borrowck/borrowck-loan-in-overloaded-op.stderr @@ -4,7 +4,7 @@ error[E0382]: borrow of moved value: `x` LL | let x = Foo(Box::new(3)); | - move occurs because `x` has type `Foo`, which does not implement the `Copy` trait LL | let _y = {x} + x.clone(); // the `{x}` forces a move to occur - | - ^^^^^^^^^ value borrowed here after move + | - ^ value borrowed here after move | | | value moved here | diff --git a/tests/ui/borrowck/borrowck-loan-rcvr-overloaded-op.stderr b/tests/ui/borrowck/borrowck-loan-rcvr-overloaded-op.stderr index f1640d3b777..bb90b2d15df 100644 --- a/tests/ui/borrowck/borrowck-loan-rcvr-overloaded-op.stderr +++ b/tests/ui/borrowck/borrowck-loan-rcvr-overloaded-op.stderr @@ -17,7 +17,7 @@ LL | let q = &mut p; | ------ mutable borrow occurs here ... LL | p.times(3); - | ^^^^^^^^^^ immutable borrow occurs here + | ^ immutable borrow occurs here LL | LL | *q + 3; // OK to use the new alias `q` | -- mutable borrow later used here diff --git a/tests/ui/borrowck/borrowck-loan-rcvr.stderr b/tests/ui/borrowck/borrowck-loan-rcvr.stderr index 1d6bd4e2ec8..317423ecf61 100644 --- a/tests/ui/borrowck/borrowck-loan-rcvr.stderr +++ b/tests/ui/borrowck/borrowck-loan-rcvr.stderr @@ -1,15 +1,13 @@ error[E0502]: cannot borrow `p` as mutable because it is also borrowed as immutable --> $DIR/borrowck-loan-rcvr.rs:23:14 | -LL | p.blockm(|| { - | - ------ ^^ mutable borrow occurs here - | | | - | _____| immutable borrow later used by call - | | -LL | | p.x = 10; - | | --- second borrow occurs due to use of `p` in closure -LL | | }) - | |______- immutable borrow occurs here +LL | p.blockm(|| { + | - ------ ^^ mutable borrow occurs here + | | | + | | immutable borrow later used by call + | immutable borrow occurs here +LL | p.x = 10; + | --- second borrow occurs due to use of `p` in closure error[E0502]: cannot borrow `p` as immutable because it is also borrowed as mutable --> $DIR/borrowck-loan-rcvr.rs:34:5 @@ -17,7 +15,7 @@ error[E0502]: cannot borrow `p` as immutable because it is also borrowed as muta LL | let l = &mut p; | ------ mutable borrow occurs here LL | p.impurem(); - | ^^^^^^^^^^^ immutable borrow occurs here + | ^ immutable borrow occurs here LL | LL | l.x += 1; | -------- mutable borrow later used here diff --git a/tests/ui/borrowck/borrowck-move-from-subpath-of-borrowed-path.stderr b/tests/ui/borrowck/borrowck-move-from-subpath-of-borrowed-path.stderr index bd94f1a4299..4f0202f3832 100644 --- a/tests/ui/borrowck/borrowck-move-from-subpath-of-borrowed-path.stderr +++ b/tests/ui/borrowck/borrowck-move-from-subpath-of-borrowed-path.stderr @@ -9,7 +9,7 @@ LL | LL | let z = *a; | ^^ move out of `*a` occurs here LL | b.use_ref(); - | ----------- borrow later used here + | - borrow later used here error: aborting due to previous error diff --git a/tests/ui/borrowck/borrowck-move-mut-base-ptr.stderr b/tests/ui/borrowck/borrowck-move-mut-base-ptr.stderr index cdad20c52bf..e1e3c7f8aaa 100644 --- a/tests/ui/borrowck/borrowck-move-mut-base-ptr.stderr +++ b/tests/ui/borrowck/borrowck-move-mut-base-ptr.stderr @@ -9,7 +9,7 @@ LL | let t1 = t0; | ^^ move out of `t0` occurs here LL | *t1 = 22; LL | p.use_ref(); - | ----------- borrow later used here + | - borrow later used here error: aborting due to previous error diff --git a/tests/ui/borrowck/borrowck-move-out-of-overloaded-auto-deref.stderr b/tests/ui/borrowck/borrowck-move-out-of-overloaded-auto-deref.stderr index 87135f0bb43..934dd8df1d2 100644 --- a/tests/ui/borrowck/borrowck-move-out-of-overloaded-auto-deref.stderr +++ b/tests/ui/borrowck/borrowck-move-out-of-overloaded-auto-deref.stderr @@ -2,9 +2,8 @@ error[E0507]: cannot move out of an `Rc` --> $DIR/borrowck-move-out-of-overloaded-auto-deref.rs:4:14 | LL | let _x = Rc::new(vec![1, 2]).into_iter(); - | ^^^^^^^^^^^^^^^^^^^^----------- - | | | - | | value moved due to this method call + | ^^^^^^^^^^^^^^^^^^^ ----------- value moved due to this method call + | | | move occurs because value has type `Vec<i32>`, which does not implement the `Copy` trait | note: `into_iter` takes ownership of the receiver `self`, which moves value @@ -12,7 +11,7 @@ note: `into_iter` takes ownership of the receiver `self`, which moves value help: you can `clone` the value and consume it, but this might not be your desired behavior | LL | let _x = Rc::new(vec![1, 2]).clone().into_iter(); - | ++++++++ + | ++++++++ error: aborting due to previous error diff --git a/tests/ui/borrowck/borrowck-mut-borrow-linear-errors.stderr b/tests/ui/borrowck/borrowck-mut-borrow-linear-errors.stderr index d2b845619c7..3653de0e8ab 100644 --- a/tests/ui/borrowck/borrowck-mut-borrow-linear-errors.stderr +++ b/tests/ui/borrowck/borrowck-mut-borrow-linear-errors.stderr @@ -5,9 +5,8 @@ LL | 1 => { addr.push(&mut x); } | ^^^^^^ second mutable borrow occurs here LL | 2 => { addr.push(&mut x); } LL | _ => { addr.push(&mut x); } - | ----------------- - | | | - | | first mutable borrow occurs here + | ---- ------ first mutable borrow occurs here + | | | first borrow later used here error[E0499]: cannot borrow `x` as mutable more than once at a time @@ -16,18 +15,16 @@ error[E0499]: cannot borrow `x` as mutable more than once at a time LL | 2 => { addr.push(&mut x); } | ^^^^^^ second mutable borrow occurs here LL | _ => { addr.push(&mut x); } - | ----------------- - | | | - | | first mutable borrow occurs here + | ---- ------ first mutable borrow occurs here + | | | first borrow later used here error[E0499]: cannot borrow `x` as mutable more than once at a time --> $DIR/borrowck-mut-borrow-linear-errors.rs:12:30 | LL | _ => { addr.push(&mut x); } - | ----------^^^^^^- - | | | - | | `x` was mutably borrowed here in the previous iteration of the loop + | ---- ^^^^^^ `x` was mutably borrowed here in the previous iteration of the loop + | | | first borrow used here, in later iteration of loop error: aborting due to 3 previous errors diff --git a/tests/ui/borrowck/borrowck-mut-borrow-of-mut-base-ptr.stderr b/tests/ui/borrowck/borrowck-mut-borrow-of-mut-base-ptr.stderr index ef811b84905..f2baee09376 100644 --- a/tests/ui/borrowck/borrowck-mut-borrow-of-mut-base-ptr.stderr +++ b/tests/ui/borrowck/borrowck-mut-borrow-of-mut-base-ptr.stderr @@ -7,7 +7,7 @@ LL | let mut t2 = &mut t0; | ^^^^^^^ mutable borrow occurs here LL | **t2 += 1; // Mutates `*t0` LL | p.use_ref(); - | ----------- immutable borrow later used here + | - immutable borrow later used here error[E0499]: cannot borrow `t0` as mutable more than once at a time --> $DIR/borrowck-mut-borrow-of-mut-base-ptr.rs:19:18 @@ -18,7 +18,7 @@ LL | let mut t2 = &mut t0; | ^^^^^^^ second mutable borrow occurs here LL | **t2 += 1; // Mutates `*t0` but not through `*p` LL | p.use_mut(); - | ----------- first borrow later used here + | - first borrow later used here error: aborting due to 2 previous errors diff --git a/tests/ui/borrowck/borrowck-object-lifetime.stderr b/tests/ui/borrowck/borrowck-object-lifetime.stderr index 215ed760ae1..cf94c74dec2 100644 --- a/tests/ui/borrowck/borrowck-object-lifetime.stderr +++ b/tests/ui/borrowck/borrowck-object-lifetime.stderr @@ -2,21 +2,21 @@ error[E0502]: cannot borrow `*x` as mutable because it is also borrowed as immut --> $DIR/borrowck-object-lifetime.rs:20:13 | LL | let y = x.borrowed(); - | ------------ immutable borrow occurs here + | - immutable borrow occurs here LL | let z = x.mut_borrowed(); | ^^^^^^^^^^^^^^^^ mutable borrow occurs here LL | y.use_ref(); - | ----------- immutable borrow later used here + | - immutable borrow later used here error[E0502]: cannot borrow `x` as mutable because it is also borrowed as immutable --> $DIR/borrowck-object-lifetime.rs:26:13 | LL | let y = x.borrowed(); - | ------------ immutable borrow occurs here + | - immutable borrow occurs here LL | let z = &mut x; | ^^^^^^ mutable borrow occurs here LL | y.use_ref(); - | ----------- immutable borrow later used here + | - immutable borrow later used here error: aborting due to 2 previous errors diff --git a/tests/ui/borrowck/borrowck-overloaded-index-autoderef.stderr b/tests/ui/borrowck/borrowck-overloaded-index-autoderef.stderr index fb7af50bcb5..2e7a6778dbc 100644 --- a/tests/ui/borrowck/borrowck-overloaded-index-autoderef.stderr +++ b/tests/ui/borrowck/borrowck-overloaded-index-autoderef.stderr @@ -6,7 +6,7 @@ LL | let p = &mut f[&s]; LL | let q = &f[&s]; | ^ immutable borrow occurs here LL | p.use_mut(); - | ----------- mutable borrow later used here + | - mutable borrow later used here error[E0499]: cannot borrow `*f` as mutable more than once at a time --> $DIR/borrowck-overloaded-index-autoderef.rs:43:18 @@ -16,7 +16,7 @@ LL | let p = &mut f[&s]; LL | let q = &mut f[&s]; | ^ second mutable borrow occurs here LL | p.use_mut(); - | ----------- first borrow later used here + | - first borrow later used here error[E0499]: cannot borrow `f.foo` as mutable more than once at a time --> $DIR/borrowck-overloaded-index-autoderef.rs:53:18 @@ -26,7 +26,7 @@ LL | let p = &mut f.foo[&s]; LL | let q = &mut f.foo[&s]; | ^^^^^ second mutable borrow occurs here LL | p.use_mut(); - | ----------- first borrow later used here + | - first borrow later used here error[E0502]: cannot borrow `f.foo` as mutable because it is also borrowed as immutable --> $DIR/borrowck-overloaded-index-autoderef.rs:65:18 @@ -36,7 +36,7 @@ LL | let p = &f.foo[&s]; LL | let q = &mut f.foo[&s]; | ^^^^^ mutable borrow occurs here LL | p.use_ref(); - | ----------- immutable borrow later used here + | - immutable borrow later used here error[E0506]: cannot assign to `f.foo` because it is borrowed --> $DIR/borrowck-overloaded-index-autoderef.rs:71:5 @@ -46,7 +46,7 @@ LL | let p = &f.foo[&s]; LL | f.foo = g; | ^^^^^^^^^ `f.foo` is assigned to here but it was already borrowed LL | p.use_ref(); - | ----------- borrow later used here + | - borrow later used here error[E0506]: cannot assign to `*f` because it is borrowed --> $DIR/borrowck-overloaded-index-autoderef.rs:77:5 @@ -56,7 +56,7 @@ LL | let p = &f.foo[&s]; LL | *f = g; | ^^^^^^ `*f` is assigned to here but it was already borrowed LL | p.use_ref(); - | ----------- borrow later used here + | - borrow later used here error[E0506]: cannot assign to `f.foo` because it is borrowed --> $DIR/borrowck-overloaded-index-autoderef.rs:83:5 @@ -66,7 +66,7 @@ LL | let p = &mut f.foo[&s]; LL | f.foo = g; | ^^^^^^^^^ `f.foo` is assigned to here but it was already borrowed LL | p.use_mut(); - | ----------- borrow later used here + | - borrow later used here error[E0506]: cannot assign to `*f` because it is borrowed --> $DIR/borrowck-overloaded-index-autoderef.rs:89:5 @@ -76,7 +76,7 @@ LL | let p = &mut f.foo[&s]; LL | *f = g; | ^^^^^^ `*f` is assigned to here but it was already borrowed LL | p.use_mut(); - | ----------- borrow later used here + | - borrow later used here error: aborting due to 8 previous errors diff --git a/tests/ui/borrowck/borrowck-report-with-custom-diagnostic.stderr b/tests/ui/borrowck/borrowck-report-with-custom-diagnostic.stderr index d05996413dd..db73d4c04ac 100644 --- a/tests/ui/borrowck/borrowck-report-with-custom-diagnostic.stderr +++ b/tests/ui/borrowck/borrowck-report-with-custom-diagnostic.stderr @@ -8,7 +8,7 @@ LL | let z = &x; | ^^ immutable borrow occurs here ... LL | y.use_mut(); - | ----------- mutable borrow later used here + | - mutable borrow later used here error[E0502]: cannot borrow `x` as mutable because it is also borrowed as immutable --> $DIR/borrowck-report-with-custom-diagnostic.rs:21:21 @@ -20,7 +20,7 @@ LL | let z = &mut x; | ^^^^^^ mutable borrow occurs here ... LL | y.use_ref(); - | ----------- immutable borrow later used here + | - immutable borrow later used here error[E0499]: cannot borrow `x` as mutable more than once at a time --> $DIR/borrowck-report-with-custom-diagnostic.rs:36:17 @@ -32,7 +32,7 @@ LL | let z = &mut x; | ^^^^^^ second mutable borrow occurs here ... LL | y.use_mut(); - | ----------- first borrow later used here + | - first borrow later used here error: aborting due to 3 previous errors diff --git a/tests/ui/borrowck/borrowck-swap-mut-base-ptr.stderr b/tests/ui/borrowck/borrowck-swap-mut-base-ptr.stderr index b39215b9aab..1c55953c91f 100644 --- a/tests/ui/borrowck/borrowck-swap-mut-base-ptr.stderr +++ b/tests/ui/borrowck/borrowck-swap-mut-base-ptr.stderr @@ -7,7 +7,7 @@ LL | swap(&mut t0, &mut t1); | ^^^^^^^ mutable borrow occurs here LL | *t1 = 22; LL | p.use_ref(); - | ----------- immutable borrow later used here + | - immutable borrow later used here error: aborting due to previous error diff --git a/tests/ui/borrowck/borrowck-union-borrow-nested.stderr b/tests/ui/borrowck/borrowck-union-borrow-nested.stderr index a87a14e7cab..f2e549cd88c 100644 --- a/tests/ui/borrowck/borrowck-union-borrow-nested.stderr +++ b/tests/ui/borrowck/borrowck-union-borrow-nested.stderr @@ -6,7 +6,7 @@ LL | let ra = &mut u.s.a; LL | let b = u.c; | ^^^ use of borrowed `u.s.a` LL | ra.use_mut(); - | ------------ borrow later used here + | -- borrow later used here error: aborting due to previous error diff --git a/tests/ui/borrowck/borrowck-uniq-via-lend.stderr b/tests/ui/borrowck/borrowck-uniq-via-lend.stderr index 6dbe4c74b58..923edc8edae 100644 --- a/tests/ui/borrowck/borrowck-uniq-via-lend.stderr +++ b/tests/ui/borrowck/borrowck-uniq-via-lend.stderr @@ -6,7 +6,7 @@ LL | let w = &mut v; LL | borrow(&*v); | ^^^ immutable borrow occurs here LL | w.use_mut(); - | ----------- mutable borrow later used here + | - mutable borrow later used here error[E0502]: cannot borrow `*v` as immutable because it is also borrowed as mutable --> $DIR/borrowck-uniq-via-lend.rs:53:12 @@ -16,7 +16,7 @@ LL | x = &mut v; LL | borrow(&*v); | ^^^ immutable borrow occurs here LL | x.use_mut(); - | ----------- mutable borrow later used here + | - mutable borrow later used here error: aborting due to 2 previous errors diff --git a/tests/ui/borrowck/borrowck-vec-pattern-loan-from-mut.stderr b/tests/ui/borrowck/borrowck-vec-pattern-loan-from-mut.stderr index eb0f24b9b7a..5141fcc1bb2 100644 --- a/tests/ui/borrowck/borrowck-vec-pattern-loan-from-mut.stderr +++ b/tests/ui/borrowck/borrowck-vec-pattern-loan-from-mut.stderr @@ -5,9 +5,8 @@ LL | let vb: &mut [isize] = &mut v; | ------ first mutable borrow occurs here ... LL | v.push(tail[0] + tail[1]); - | ^^^^^^^-------^^^^^^^^^^^ - | | | - | | first borrow later used here + | ^ ------- first borrow later used here + | | | second mutable borrow occurs here error: aborting due to previous error diff --git a/tests/ui/borrowck/borrowck-vec-pattern-nesting.stderr b/tests/ui/borrowck/borrowck-vec-pattern-nesting.stderr index 70b9e4f4433..024cb006c26 100644 --- a/tests/ui/borrowck/borrowck-vec-pattern-nesting.stderr +++ b/tests/ui/borrowck/borrowck-vec-pattern-nesting.stderr @@ -8,7 +8,7 @@ LL | vec[0] = Box::new(4); | ^^^^^^ `vec[_]` is assigned to here but it was already borrowed LL | LL | _a.use_ref(); - | ------------ borrow later used here + | -- borrow later used here error[E0506]: cannot assign to `vec[_]` because it is borrowed --> $DIR/borrowck-vec-pattern-nesting.rs:23:13 @@ -20,7 +20,7 @@ LL | vec[0] = Box::new(4); | ^^^^^^ `vec[_]` is assigned to here but it was already borrowed LL | LL | _b.use_ref(); - | ------------ borrow later used here + | -- borrow later used here error[E0508]: cannot move out of type `[Box<isize>]`, a non-copy slice --> $DIR/borrowck-vec-pattern-nesting.rs:34:11 diff --git a/tests/ui/borrowck/clone-span-on-try-operator.fixed b/tests/ui/borrowck/clone-span-on-try-operator.fixed new file mode 100644 index 00000000000..52f66e43a93 --- /dev/null +++ b/tests/ui/borrowck/clone-span-on-try-operator.fixed @@ -0,0 +1,11 @@ +// run-rustfix + +#[derive(Clone)] +struct Foo; +impl Foo { + fn foo(self) {} +} +fn main() { + let foo = &Foo; + (*foo).clone().foo(); //~ ERROR cannot move out +} diff --git a/tests/ui/borrowck/clone-span-on-try-operator.rs b/tests/ui/borrowck/clone-span-on-try-operator.rs new file mode 100644 index 00000000000..031a35e2026 --- /dev/null +++ b/tests/ui/borrowck/clone-span-on-try-operator.rs @@ -0,0 +1,11 @@ +// run-rustfix + +#[derive(Clone)] +struct Foo; +impl Foo { + fn foo(self) {} +} +fn main() { + let foo = &Foo; + (*foo).foo(); //~ ERROR cannot move out +} diff --git a/tests/ui/borrowck/clone-span-on-try-operator.stderr b/tests/ui/borrowck/clone-span-on-try-operator.stderr new file mode 100644 index 00000000000..85785e67072 --- /dev/null +++ b/tests/ui/borrowck/clone-span-on-try-operator.stderr @@ -0,0 +1,21 @@ +error[E0507]: cannot move out of `*foo` which is behind a shared reference + --> $DIR/clone-span-on-try-operator.rs:10:5 + | +LL | (*foo).foo(); + | ^^^^^^ ----- `*foo` moved due to this method call + | | + | move occurs because `*foo` has type `Foo`, which does not implement the `Copy` trait + | +note: `Foo::foo` takes ownership of the receiver `self`, which moves `*foo` + --> $DIR/clone-span-on-try-operator.rs:6:12 + | +LL | fn foo(self) {} + | ^^^^ +help: you can `clone` the value and consume it, but this might not be your desired behavior + | +LL | (*foo).clone().foo(); + | ++++++++ + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0507`. diff --git a/tests/ui/borrowck/copy-suggestion-region-vid.rs b/tests/ui/borrowck/copy-suggestion-region-vid.rs index dff95283459..3c5b887ce17 100644 --- a/tests/ui/borrowck/copy-suggestion-region-vid.rs +++ b/tests/ui/borrowck/copy-suggestion-region-vid.rs @@ -1,3 +1,4 @@ +//@run-rustfix pub struct DataStruct(); pub struct HelperStruct<'n> { diff --git a/tests/ui/borrowck/copy-suggestion-region-vid.stderr b/tests/ui/borrowck/copy-suggestion-region-vid.stderr index 1685acf8718..b344aa66405 100644 --- a/tests/ui/borrowck/copy-suggestion-region-vid.stderr +++ b/tests/ui/borrowck/copy-suggestion-region-vid.stderr @@ -1,13 +1,18 @@ error[E0382]: borrow of moved value: `helpers` - --> $DIR/copy-suggestion-region-vid.rs:12:43 + --> $DIR/copy-suggestion-region-vid.rs:13:43 | LL | let helpers = [vec![], vec![]]; | ------- move occurs because `helpers` has type `[Vec<&i64>; 2]`, which does not implement the `Copy` trait LL | LL | HelperStruct { helpers, is_empty: helpers[0].is_empty() } - | ------- ^^^^^^^^^^^^^^^^^^^^^ value borrowed here after move + | ------- ^^^^^^^^^^ value borrowed here after move | | | value moved here + | +help: consider cloning the value if the performance cost is acceptable + | +LL | HelperStruct { helpers: helpers.clone(), is_empty: helpers[0].is_empty() } + | +++++++++++++++++ error: aborting due to previous error diff --git a/tests/ui/borrowck/index-mut-help-with-impl.stderr b/tests/ui/borrowck/index-mut-help-with-impl.stderr index 69dca7e7b56..89391f4099a 100644 --- a/tests/ui/borrowck/index-mut-help-with-impl.stderr +++ b/tests/ui/borrowck/index-mut-help-with-impl.stderr @@ -2,7 +2,7 @@ error[E0596]: cannot borrow data in a `&` reference as mutable --> $DIR/index-mut-help-with-impl.rs:9:5 | LL | Index::index(&v, 1..2).make_ascii_uppercase(); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot borrow as mutable + | ^^^^^^^^^^^^^^^^^^^^^^ cannot borrow as mutable error: aborting due to previous error diff --git a/tests/ui/borrowck/index-mut-help.stderr b/tests/ui/borrowck/index-mut-help.stderr index f42d7e01554..fde2b5dc076 100644 --- a/tests/ui/borrowck/index-mut-help.stderr +++ b/tests/ui/borrowck/index-mut-help.stderr @@ -2,13 +2,10 @@ error[E0596]: cannot borrow data in an index of `HashMap<&str, String>` as mutab --> $DIR/index-mut-help.rs:10:5 | LL | map["peter"].clear(); - | ^^^^^^^^^^^^^^^^^^^^ cannot borrow as mutable + | ^^^^^^^^^^^^ cannot borrow as mutable | = help: trait `IndexMut` is required to modify indexed content, but it is not implemented for `HashMap<&str, String>` -help: to modify a `HashMap<&str, String>` use `.get_mut()` - | -LL | map.get_mut("peter").map(|val| val.clear()); - | ~~~~~~~~~ ~~~~~~~~~~~~~~~ + + = help: to modify a `HashMap<&str, String>`, use `.get_mut()`, `.insert()` or the entry API error[E0594]: cannot assign to data in an index of `HashMap<&str, String>` --> $DIR/index-mut-help.rs:11:5 diff --git a/tests/ui/borrowck/issue-109271-pass-self-into-closure.stderr b/tests/ui/borrowck/issue-109271-pass-self-into-closure.stderr index 25974e0d008..4e3bf1d7042 100644 --- a/tests/ui/borrowck/issue-109271-pass-self-into-closure.stderr +++ b/tests/ui/borrowck/issue-109271-pass-self-into-closure.stderr @@ -26,9 +26,8 @@ error[E0499]: cannot borrow `v` as mutable more than once at a time --> $DIR/issue-109271-pass-self-into-closure.rs:21:12 | LL | v.call(|(), this: &mut S| v.set()); - | -------^^^^^^^^^^^^^^^^^^--------- - | | | | | - | | | | second borrow occurs due to use of `v` in closure + | - ---- ^^^^^^^^^^^^^^^^^^ - second borrow occurs due to use of `v` in closure + | | | | | | | second mutable borrow occurs here | | first borrow later used by call | first mutable borrow occurs here @@ -63,21 +62,14 @@ LL ~ S::get(&this); error[E0499]: cannot borrow `v` as mutable more than once at a time --> $DIR/issue-109271-pass-self-into-closure.rs:25:12 | -LL | v.call(|(), this: &mut S| { - | - ---- ^^^^^^^^^^^^^^^^^^ second mutable borrow occurs here - | | | - | _____| first borrow later used by call - | | -LL | | -LL | | -LL | | -LL | | _ = v; -LL | | v.set(); - | | - second borrow occurs due to use of `v` in closure -... | -LL | | _ = v.add(3); -LL | | }); - | |______- first mutable borrow occurs here +LL | v.call(|(), this: &mut S| { + | - ---- ^^^^^^^^^^^^^^^^^^ second mutable borrow occurs here + | | | + | | first borrow later used by call + | first mutable borrow occurs here +... +LL | v.set(); + | - second borrow occurs due to use of `v` in closure error: aborting due to 5 previous errors diff --git a/tests/ui/borrowck/issue-42344.stderr b/tests/ui/borrowck/issue-42344.stderr index 29b4c8c38d7..5cffa1b5121 100644 --- a/tests/ui/borrowck/issue-42344.stderr +++ b/tests/ui/borrowck/issue-42344.stderr @@ -2,7 +2,7 @@ error[E0596]: cannot borrow `*TAB[_]` as mutable, as `TAB` is an immutable stati --> $DIR/issue-42344.rs:4:5 | LL | TAB[0].iter_mut(); - | ^^^^^^^^^^^^^^^^^ cannot borrow as mutable + | ^^^^^^ cannot borrow as mutable error: aborting due to previous error diff --git a/tests/ui/borrowck/issue-47646.stderr b/tests/ui/borrowck/issue-47646.stderr index 84cf9237a56..d82e1f908cb 100644 --- a/tests/ui/borrowck/issue-47646.stderr +++ b/tests/ui/borrowck/issue-47646.stderr @@ -2,7 +2,7 @@ error[E0502]: cannot borrow `heap` as immutable because it is also borrowed as m --> $DIR/issue-47646.rs:9:30 | LL | let borrow = heap.peek_mut(); - | --------------- mutable borrow occurs here + | ---- mutable borrow occurs here LL | LL | match (borrow, ()) { | ------------ a temporary with access to the mutable borrow is created here ... diff --git a/tests/ui/borrowck/issue-51117.stderr b/tests/ui/borrowck/issue-51117.stderr index ef1a16ea953..f8a9608ad37 100644 --- a/tests/ui/borrowck/issue-51117.stderr +++ b/tests/ui/borrowck/issue-51117.stderr @@ -4,7 +4,7 @@ error[E0499]: cannot borrow `*bar` as mutable more than once at a time LL | Some(baz) => { | --- first mutable borrow occurs here LL | bar.take(); - | ^^^^^^^^^^ second mutable borrow occurs here + | ^^^ second mutable borrow occurs here LL | drop(baz); | --- first borrow later used here diff --git a/tests/ui/borrowck/issue-81365-10.stderr b/tests/ui/borrowck/issue-81365-10.stderr index d0986e9f922..2bbde82fafd 100644 --- a/tests/ui/borrowck/issue-81365-10.stderr +++ b/tests/ui/borrowck/issue-81365-10.stderr @@ -2,7 +2,7 @@ error[E0506]: cannot assign to `self.container_field` because it is borrowed --> $DIR/issue-81365-10.rs:21:9 | LL | let first = &self.deref().target_field; - | ------------ `self.container_field` is borrowed here + | ---- `self.container_field` is borrowed here LL | self.container_field = true; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ `self.container_field` is assigned to here but it was already borrowed LL | first; diff --git a/tests/ui/borrowck/issue-81365-5.stderr b/tests/ui/borrowck/issue-81365-5.stderr index c00e48288ba..094cec021e4 100644 --- a/tests/ui/borrowck/issue-81365-5.stderr +++ b/tests/ui/borrowck/issue-81365-5.stderr @@ -2,7 +2,7 @@ error[E0506]: cannot assign to `self.container_field` because it is borrowed --> $DIR/issue-81365-5.rs:28:9 | LL | let first = self.get(); - | ---------- `self.container_field` is borrowed here + | ---- `self.container_field` is borrowed here LL | self.container_field = true; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ `self.container_field` is assigned to here but it was already borrowed LL | first; diff --git a/tests/ui/borrowck/issue-82032.stderr b/tests/ui/borrowck/issue-82032.stderr index 25f343117a3..f272477a9f5 100644 --- a/tests/ui/borrowck/issue-82032.stderr +++ b/tests/ui/borrowck/issue-82032.stderr @@ -7,7 +7,7 @@ LL | for v in self.0.values() { | | help: use mutable method: `values_mut()` | this iterator yields `&` references LL | v.flush(); - | ^^^^^^^^^ `v` is a `&` reference, so the data it refers to cannot be borrowed as mutable + | ^ `v` is a `&` reference, so the data it refers to cannot be borrowed as mutable error: aborting due to previous error diff --git a/tests/ui/borrowck/issue-85581.stderr b/tests/ui/borrowck/issue-85581.stderr index 59ca4867fd7..29c0429f2a0 100644 --- a/tests/ui/borrowck/issue-85581.stderr +++ b/tests/ui/borrowck/issue-85581.stderr @@ -7,7 +7,7 @@ LL | match heap.peek_mut() { | first mutable borrow occurs here | a temporary with access to the first borrow is created here ... LL | Some(_) => { heap.pop(); }, - | ^^^^^^^^^^ second mutable borrow occurs here + | ^^^^ second mutable borrow occurs here ... LL | } | - ... and the first borrow might be used here, when that temporary is dropped and runs the destructor for type `Option<PeekMut<'_, i32>>` diff --git a/tests/ui/borrowck/issue-85765-closure.rs b/tests/ui/borrowck/issue-85765-closure.rs new file mode 100644 index 00000000000..f2d1dd0fbc3 --- /dev/null +++ b/tests/ui/borrowck/issue-85765-closure.rs @@ -0,0 +1,31 @@ +fn main() { + let _ = || { + let mut test = Vec::new(); + let rofl: &Vec<Vec<i32>> = &mut test; + //~^ HELP consider changing this binding's type + rofl.push(Vec::new()); + //~^ ERROR cannot borrow `*rofl` as mutable, as it is behind a `&` reference + //~| NOTE `rofl` is a `&` reference, so the data it refers to cannot be borrowed as mutable + + let mut mutvar = 42; + let r = &mutvar; + //~^ HELP consider changing this to be a mutable reference + *r = 0; + //~^ ERROR cannot assign to `*r`, which is behind a `&` reference + //~| NOTE `r` is a `&` reference, so the data it refers to cannot be written + + #[rustfmt::skip] + let x: &usize = &mut{0}; + //~^ HELP consider changing this binding's type + *x = 1; + //~^ ERROR cannot assign to `*x`, which is behind a `&` reference + //~| NOTE `x` is a `&` reference, so the data it refers to cannot be written + + #[rustfmt::skip] + let y: &usize = &mut(0); + //~^ HELP consider changing this binding's type + *y = 1; + //~^ ERROR cannot assign to `*y`, which is behind a `&` reference + //~| NOTE `y` is a `&` reference, so the data it refers to cannot be written + }; +} diff --git a/tests/ui/borrowck/issue-85765-closure.stderr b/tests/ui/borrowck/issue-85765-closure.stderr new file mode 100644 index 00000000000..936ddd67bcd --- /dev/null +++ b/tests/ui/borrowck/issue-85765-closure.stderr @@ -0,0 +1,48 @@ +error[E0596]: cannot borrow `*rofl` as mutable, as it is behind a `&` reference + --> $DIR/issue-85765-closure.rs:6:9 + | +LL | rofl.push(Vec::new()); + | ^^^^ `rofl` is a `&` reference, so the data it refers to cannot be borrowed as mutable + | +help: consider changing this binding's type + | +LL | let rofl: &mut Vec<Vec<i32>> = &mut test; + | ~~~~~~~~~~~~~~~~~~ + +error[E0594]: cannot assign to `*r`, which is behind a `&` reference + --> $DIR/issue-85765-closure.rs:13:9 + | +LL | *r = 0; + | ^^^^^^ `r` is a `&` reference, so the data it refers to cannot be written + | +help: consider changing this to be a mutable reference + | +LL | let r = &mut mutvar; + | +++ + +error[E0594]: cannot assign to `*x`, which is behind a `&` reference + --> $DIR/issue-85765-closure.rs:20:9 + | +LL | *x = 1; + | ^^^^^^ `x` is a `&` reference, so the data it refers to cannot be written + | +help: consider changing this binding's type + | +LL | let x: &mut usize = &mut{0}; + | ~~~~~~~~~~ + +error[E0594]: cannot assign to `*y`, which is behind a `&` reference + --> $DIR/issue-85765-closure.rs:27:9 + | +LL | *y = 1; + | ^^^^^^ `y` is a `&` reference, so the data it refers to cannot be written + | +help: consider changing this binding's type + | +LL | let y: &mut usize = &mut(0); + | ~~~~~~~~~~ + +error: aborting due to 4 previous errors + +Some errors have detailed explanations: E0594, E0596. +For more information about an error, try `rustc --explain E0594`. diff --git a/tests/ui/borrowck/issue-85765.stderr b/tests/ui/borrowck/issue-85765.stderr index 2985a658fdd..57900bfb612 100644 --- a/tests/ui/borrowck/issue-85765.stderr +++ b/tests/ui/borrowck/issue-85765.stderr @@ -2,7 +2,7 @@ error[E0596]: cannot borrow `*rofl` as mutable, as it is behind a `&` reference --> $DIR/issue-85765.rs:5:5 | LL | rofl.push(Vec::new()); - | ^^^^^^^^^^^^^^^^^^^^^ `rofl` is a `&` reference, so the data it refers to cannot be borrowed as mutable + | ^^^^ `rofl` is a `&` reference, so the data it refers to cannot be borrowed as mutable | help: consider changing this binding's type | diff --git a/tests/ui/borrowck/issue-91206.stderr b/tests/ui/borrowck/issue-91206.stderr index 6653d497873..30f83656518 100644 --- a/tests/ui/borrowck/issue-91206.stderr +++ b/tests/ui/borrowck/issue-91206.stderr @@ -2,7 +2,7 @@ error[E0596]: cannot borrow `*inner` as mutable, as it is behind a `&` reference --> $DIR/issue-91206.rs:13:5 | LL | inner.clear(); - | ^^^^^^^^^^^^^ `inner` is a `&` reference, so the data it refers to cannot be borrowed as mutable + | ^^^^^ `inner` is a `&` reference, so the data it refers to cannot be borrowed as mutable | help: consider specifying this binding's type | diff --git a/tests/ui/borrowck/issue-93078.stderr b/tests/ui/borrowck/issue-93078.stderr index 771a652a173..bcbcbe72412 100644 --- a/tests/ui/borrowck/issue-93078.stderr +++ b/tests/ui/borrowck/issue-93078.stderr @@ -2,7 +2,7 @@ error[E0596]: cannot borrow `self` as mutable, as it is not declared as mutable --> $DIR/issue-93078.rs:11:9 | LL | self.modify(); - | ^^^^^^^^^^^^^ cannot borrow as mutable + | ^^^^ cannot borrow as mutable | = note: as `Self` may be unsized, this call attempts to take `&mut &mut self` = note: however, `&mut self` expands to `self: &mut Self`, therefore `self` cannot be borrowed mutably diff --git a/tests/ui/borrowck/many-mutable-borrows.stderr b/tests/ui/borrowck/many-mutable-borrows.stderr index aa0cbcffd95..0f808ac9276 100644 --- a/tests/ui/borrowck/many-mutable-borrows.stderr +++ b/tests/ui/borrowck/many-mutable-borrows.stderr @@ -4,23 +4,23 @@ error[E0596]: cannot borrow `v` as mutable, as it is not declared as mutable LL | let v = Vec::new(); | ^ not mutable LL | v.push(0); - | --------- cannot borrow as mutable + | - cannot borrow as mutable LL | v.push(0); - | --------- cannot borrow as mutable + | - cannot borrow as mutable LL | v.push(0); - | --------- cannot borrow as mutable + | - cannot borrow as mutable LL | v.push(0); - | --------- cannot borrow as mutable + | - cannot borrow as mutable LL | v.push(0); - | --------- cannot borrow as mutable + | - cannot borrow as mutable LL | v.push(0); - | --------- cannot borrow as mutable + | - cannot borrow as mutable LL | v.push(0); - | --------- cannot borrow as mutable + | - cannot borrow as mutable LL | v.push(0); - | --------- cannot borrow as mutable + | - cannot borrow as mutable LL | v.push(0); - | --------- cannot borrow as mutable + | - cannot borrow as mutable | = note: ...and 5 other attempted mutable borrows help: consider changing this to be mutable diff --git a/tests/ui/borrowck/mut-borrow-of-mut-ref.stderr b/tests/ui/borrowck/mut-borrow-of-mut-ref.stderr index c6f75b1c0d0..f448e009b0e 100644 --- a/tests/ui/borrowck/mut-borrow-of-mut-ref.stderr +++ b/tests/ui/borrowck/mut-borrow-of-mut-ref.stderr @@ -47,7 +47,7 @@ error[E0596]: cannot borrow `f` as mutable, as it is not declared as mutable --> $DIR/mut-borrow-of-mut-ref.rs:34:5 | LL | f.bar(); - | ^^^^^^^ cannot borrow as mutable + | ^ cannot borrow as mutable | help: consider making the binding mutable | diff --git a/tests/ui/borrowck/mut-borrow-outside-loop.stderr b/tests/ui/borrowck/mut-borrow-outside-loop.stderr index e6895b27f35..4fcb693f1bf 100644 --- a/tests/ui/borrowck/mut-borrow-outside-loop.stderr +++ b/tests/ui/borrowck/mut-borrow-outside-loop.stderr @@ -6,7 +6,7 @@ LL | let first = &mut void; LL | let second = &mut void; | ^^^^^^^^^ second mutable borrow occurs here LL | first.use_mut(); - | --------------- first borrow later used here + | ----- first borrow later used here error[E0499]: cannot borrow `inner_void` as mutable more than once at a time --> $DIR/mut-borrow-outside-loop.rs:15:28 @@ -17,7 +17,7 @@ LL | let inner_second = &mut inner_void; | ^^^^^^^^^^^^^^^ second mutable borrow occurs here LL | inner_second.use_mut(); LL | inner_first.use_mut(); - | --------------------- first borrow later used here + | ----------- first borrow later used here error: aborting due to 2 previous errors diff --git a/tests/ui/borrowck/suggest-as-ref-on-mut-closure.stderr b/tests/ui/borrowck/suggest-as-ref-on-mut-closure.stderr index 4621d879351..bada08368fc 100644 --- a/tests/ui/borrowck/suggest-as-ref-on-mut-closure.stderr +++ b/tests/ui/borrowck/suggest-as-ref-on-mut-closure.stderr @@ -2,9 +2,8 @@ error[E0507]: cannot move out of `*cb` which is behind a mutable reference --> $DIR/suggest-as-ref-on-mut-closure.rs:7:5 | LL | cb.map(|cb| cb()); - | ^^^-------------- - | | | - | | `*cb` moved due to this method call + | ^^ -------------- `*cb` moved due to this method call + | | | help: consider calling `.as_ref()` or `.as_mut()` to borrow the type's contents | move occurs because `*cb` has type `Option<&mut dyn FnMut()>`, which does not implement the `Copy` trait | diff --git a/tests/ui/borrowck/suggest-local-var-double-mut.stderr b/tests/ui/borrowck/suggest-local-var-double-mut.stderr index 3a43c18a7ed..8bec0788f02 100644 --- a/tests/ui/borrowck/suggest-local-var-double-mut.stderr +++ b/tests/ui/borrowck/suggest-local-var-double-mut.stderr @@ -2,9 +2,8 @@ error[E0499]: cannot borrow `*self` as mutable more than once at a time --> $DIR/suggest-local-var-double-mut.rs:12:22 | LL | self.foo(self.bar()); - | ---------^^^^^^^^^^- - | | | | - | | | second mutable borrow occurs here + | ---- --- ^^^^ second mutable borrow occurs here + | | | | | first borrow later used by call | first mutable borrow occurs here | diff --git a/tests/ui/borrowck/suggest-local-var-for-vector.stderr b/tests/ui/borrowck/suggest-local-var-for-vector.stderr index 615fffcd578..ea92d76b4ec 100644 --- a/tests/ui/borrowck/suggest-local-var-for-vector.stderr +++ b/tests/ui/borrowck/suggest-local-var-for-vector.stderr @@ -2,7 +2,7 @@ error[E0502]: cannot borrow `vec` as immutable because it is also borrowed as mu --> $DIR/suggest-local-var-for-vector.rs:3:9 | LL | vec[vec.len() - 1] = 123; - | ----^^^^^^^^^----- + | ----^^^----------- | | | | | immutable borrow occurs here | mutable borrow occurs here diff --git a/tests/ui/borrowck/suggest-local-var-imm-and-mut.stderr b/tests/ui/borrowck/suggest-local-var-imm-and-mut.stderr index eb934e7b72b..1ef643e2142 100644 --- a/tests/ui/borrowck/suggest-local-var-imm-and-mut.stderr +++ b/tests/ui/borrowck/suggest-local-var-imm-and-mut.stderr @@ -2,9 +2,8 @@ error[E0502]: cannot borrow `*self` as mutable because it is also borrowed as im --> $DIR/suggest-local-var-imm-and-mut.rs:12:22 | LL | self.foo(self.bar()); - | ---------^^^^^^^^^^- - | | | | - | | | mutable borrow occurs here + | ---- --- ^^^^^^^^^^ mutable borrow occurs here + | | | | | immutable borrow later used by call | immutable borrow occurs here diff --git a/tests/ui/borrowck/suggest-storing-local-var-for-vector.stderr b/tests/ui/borrowck/suggest-storing-local-var-for-vector.stderr index e3a16eddfd5..6007beb7753 100644 --- a/tests/ui/borrowck/suggest-storing-local-var-for-vector.stderr +++ b/tests/ui/borrowck/suggest-storing-local-var-for-vector.stderr @@ -2,7 +2,7 @@ error[E0502]: cannot borrow `vec` as immutable because it is also borrowed as mu --> $DIR/suggest-storing-local-var-for-vector.rs:3:9 | LL | vec[vec.len() - 1] = 123; - | ----^^^^^^^^^----- + | ----^^^----------- | | | | | immutable borrow occurs here | mutable borrow occurs here diff --git a/tests/ui/borrowck/two-phase-across-loop.stderr b/tests/ui/borrowck/two-phase-across-loop.stderr index 22f9b39dfee..d7c0210cc77 100644 --- a/tests/ui/borrowck/two-phase-across-loop.stderr +++ b/tests/ui/borrowck/two-phase-across-loop.stderr @@ -2,9 +2,8 @@ error[E0499]: cannot borrow `foo` as mutable more than once at a time --> $DIR/two-phase-across-loop.rs:17:22 | LL | strings.push(foo.get_string()); - | -------------^^^^^^^^^^^^^^^^- - | | | - | | `foo` was mutably borrowed here in the previous iteration of the loop + | ------- ^^^ `foo` was mutably borrowed here in the previous iteration of the loop + | | | first borrow used here, in later iteration of loop error: aborting due to previous error diff --git a/tests/ui/borrowck/two-phase-cannot-nest-mut-self-calls.stderr b/tests/ui/borrowck/two-phase-cannot-nest-mut-self-calls.stderr index 21b0eddb902..2c3f1c18a08 100644 --- a/tests/ui/borrowck/two-phase-cannot-nest-mut-self-calls.stderr +++ b/tests/ui/borrowck/two-phase-cannot-nest-mut-self-calls.stderr @@ -1,18 +1,13 @@ error[E0502]: cannot borrow `vec` as mutable because it is also borrowed as immutable --> $DIR/two-phase-cannot-nest-mut-self-calls.rs:14:9 | -LL | vec.get({ - | - --- immutable borrow later used by call - | _____| - | | -LL | | -LL | | vec.push(2); - | | ^^^^^^^^^^^ mutable borrow occurs here -LL | | -LL | | -LL | | 0 -LL | | }); - | |______- immutable borrow occurs here +LL | vec.get({ + | --- --- immutable borrow later used by call + | | + | immutable borrow occurs here +LL | +LL | vec.push(2); + | ^^^^^^^^^^^ mutable borrow occurs here error: aborting due to previous error diff --git a/tests/ui/borrowck/two-phase-multi-mut.stderr b/tests/ui/borrowck/two-phase-multi-mut.stderr index 2e53e17a31b..33fa4a3a150 100644 --- a/tests/ui/borrowck/two-phase-multi-mut.stderr +++ b/tests/ui/borrowck/two-phase-multi-mut.stderr @@ -12,9 +12,8 @@ error[E0499]: cannot borrow `foo` as mutable more than once at a time --> $DIR/two-phase-multi-mut.rs:11:16 | LL | foo.method(&mut foo); - | -----------^^^^^^^^- - | | | | - | | | second mutable borrow occurs here + | --- ------ ^^^^^^^^ second mutable borrow occurs here + | | | | | first borrow later used by call | first mutable borrow occurs here diff --git a/tests/ui/borrowck/two-phase-sneaky.stderr b/tests/ui/borrowck/two-phase-sneaky.stderr index 117d7ceaeef..4db970c1da0 100644 --- a/tests/ui/borrowck/two-phase-sneaky.stderr +++ b/tests/ui/borrowck/two-phase-sneaky.stderr @@ -7,7 +7,7 @@ LL | v[0].push_str({ | first mutable borrow occurs here LL | LL | v.push(format!("foo")); - | ^^^^^^^^^^^^^^^^^^^^^^ second mutable borrow occurs here + | ^ second mutable borrow occurs here error: aborting due to previous error diff --git a/tests/ui/borrowck/two-phase-surprise-no-conflict.stderr b/tests/ui/borrowck/two-phase-surprise-no-conflict.stderr index e75094d4f13..9f9d4bd8d6c 100644 --- a/tests/ui/borrowck/two-phase-surprise-no-conflict.stderr +++ b/tests/ui/borrowck/two-phase-surprise-no-conflict.stderr @@ -13,7 +13,7 @@ error[E0502]: cannot borrow `*self` as mutable because it is also borrowed as im --> $DIR/two-phase-surprise-no-conflict.rs:57:17 | LL | self.hash_expr(&self.cx_mut.body(eid).value); - | ^^^^^---------^^---------------------^^^^^^^ + | ^^^^^---------^^-----------^^^^^^^^^^^^^^^^^ | | | | | | | immutable borrow occurs here | | immutable borrow later used by call @@ -23,9 +23,8 @@ error[E0499]: cannot borrow `reg.sess_mut` as mutable more than once at a time --> $DIR/two-phase-surprise-no-conflict.rs:119:51 | LL | reg.register_static(Box::new(TrivialPass::new(&mut reg.sess_mut))); - | ----------------------------------------------^^^^^^^^^^^^^^^^^--- - | | | | - | | | second mutable borrow occurs here + | --- --------------- ^^^^^^^^^^^^^^^^^ second mutable borrow occurs here + | | | | | first borrow later used by call | first mutable borrow occurs here @@ -33,9 +32,8 @@ error[E0499]: cannot borrow `reg.sess_mut` as mutable more than once at a time --> $DIR/two-phase-surprise-no-conflict.rs:122:54 | LL | reg.register_bound(Box::new(TrivialPass::new_mut(&mut reg.sess_mut))); - | -------------------------------------------------^^^^^^^^^^^^^^^^^--- - | | | | - | | | second mutable borrow occurs here + | --- -------------- ^^^^^^^^^^^^^^^^^ second mutable borrow occurs here + | | | | | first borrow later used by call | first mutable borrow occurs here @@ -43,9 +41,8 @@ error[E0499]: cannot borrow `reg.sess_mut` as mutable more than once at a time --> $DIR/two-phase-surprise-no-conflict.rs:125:53 | LL | reg.register_univ(Box::new(TrivialPass::new_mut(&mut reg.sess_mut))); - | ------------------------------------------------^^^^^^^^^^^^^^^^^--- - | | | | - | | | second mutable borrow occurs here + | --- ------------- ^^^^^^^^^^^^^^^^^ second mutable borrow occurs here + | | | | | first borrow later used by call | first mutable borrow occurs here @@ -53,9 +50,8 @@ error[E0499]: cannot borrow `reg.sess_mut` as mutable more than once at a time --> $DIR/two-phase-surprise-no-conflict.rs:128:44 | LL | reg.register_ref(&TrivialPass::new_mut(&mut reg.sess_mut)); - | ---------------------------------------^^^^^^^^^^^^^^^^^-- - | | | | - | | | second mutable borrow occurs here + | --- ------------ ^^^^^^^^^^^^^^^^^ second mutable borrow occurs here + | | | | | first borrow later used by call | first mutable borrow occurs here @@ -106,9 +102,8 @@ error[E0499]: cannot borrow `reg.sess_mut` as mutable more than once at a time --> $DIR/two-phase-surprise-no-conflict.rs:154:54 | LL | reg.register_bound(Box::new(CapturePass::new_mut(&mut reg.sess_mut))); - | -------------------------------------------------^^^^^^^^^^^^^^^^^--- - | | | | - | | | second mutable borrow occurs here + | --- -------------- ^^^^^^^^^^^^^^^^^ second mutable borrow occurs here + | | | | | first borrow later used by call | first mutable borrow occurs here @@ -129,9 +124,8 @@ error[E0499]: cannot borrow `reg.sess_mut` as mutable more than once at a time --> $DIR/two-phase-surprise-no-conflict.rs:158:53 | LL | reg.register_univ(Box::new(CapturePass::new_mut(&mut reg.sess_mut))); - | ------------------------------------------------^^^^^^^^^^^^^^^^^--- - | | | | - | | | second mutable borrow occurs here + | --- ------------- ^^^^^^^^^^^^^^^^^ second mutable borrow occurs here + | | | | | first borrow later used by call | first mutable borrow occurs here @@ -149,9 +143,8 @@ error[E0499]: cannot borrow `reg.sess_mut` as mutable more than once at a time --> $DIR/two-phase-surprise-no-conflict.rs:162:44 | LL | reg.register_ref(&CapturePass::new_mut(&mut reg.sess_mut)); - | ---------------------------------------^^^^^^^^^^^^^^^^^-- - | | | | - | | | second mutable borrow occurs here + | --- ------------ ^^^^^^^^^^^^^^^^^ second mutable borrow occurs here + | | | | | first borrow later used by call | first mutable borrow occurs here diff --git a/tests/ui/borrowck/unboxed-closures-move-upvar-from-non-once-ref-closure.stderr b/tests/ui/borrowck/unboxed-closures-move-upvar-from-non-once-ref-closure.stderr index f033d53bf8e..a2f6365b74e 100644 --- a/tests/ui/borrowck/unboxed-closures-move-upvar-from-non-once-ref-closure.stderr +++ b/tests/ui/borrowck/unboxed-closures-move-upvar-from-non-once-ref-closure.stderr @@ -15,7 +15,7 @@ note: `into_iter` takes ownership of the receiver `self`, which moves `y` help: you can `clone` the value and consume it, but this might not be your desired behavior | LL | y.clone().into_iter(); - | ++++++++ + | ++++++++ error: aborting due to previous error diff --git a/tests/ui/box/leak-alloc.stderr b/tests/ui/box/leak-alloc.stderr index 5140b58934a..feda8841fc8 100644 --- a/tests/ui/box/leak-alloc.stderr +++ b/tests/ui/box/leak-alloc.stderr @@ -4,7 +4,7 @@ error[E0505]: cannot move out of `alloc` because it is borrowed LL | let alloc = Alloc {}; | ----- binding `alloc` declared here LL | let boxed = Box::new_in(10, alloc.by_ref()); - | -------------- borrow of `alloc` occurs here + | ----- borrow of `alloc` occurs here LL | let theref = Box::leak(boxed); LL | drop(alloc); | ^^^^^ move out of `alloc` occurs here diff --git a/tests/ui/btreemap/btreemap-index-mut-2.rs b/tests/ui/btreemap/btreemap-index-mut-2.rs new file mode 100644 index 00000000000..fe676210a1b --- /dev/null +++ b/tests/ui/btreemap/btreemap-index-mut-2.rs @@ -0,0 +1,8 @@ +use std::collections::BTreeMap; + +fn main() { + let _ = || { + let mut map = BTreeMap::<u32, u32>::new(); + map[&0] = 1; //~ ERROR cannot assign + }; +} diff --git a/tests/ui/btreemap/btreemap-index-mut-2.stderr b/tests/ui/btreemap/btreemap-index-mut-2.stderr new file mode 100644 index 00000000000..c8d4fd59550 --- /dev/null +++ b/tests/ui/btreemap/btreemap-index-mut-2.stderr @@ -0,0 +1,19 @@ +error[E0594]: cannot assign to data in an index of `BTreeMap<u32, u32>` + --> $DIR/btreemap-index-mut-2.rs:6:9 + | +LL | map[&0] = 1; + | ^^^^^^^^^^^ cannot assign + | + = help: trait `IndexMut` is required to modify indexed content, but it is not implemented for `BTreeMap<u32, u32>` +help: to modify a `BTreeMap<u32, u32>`, use `.get_mut()`, `.insert()` or the entry API + | +LL | map.insert(&0, 1); + | ~~~~~~~~ ~ + +LL | map.get_mut(&0).map(|val| { *val = 1; }); + | ~~~~~~~~~ ~~~~~~~~~~~~~~~~~~ ++++ +LL | let val = map.entry(&0).or_insert(1); + | +++++++++ ~~~~~~~ ~~~~~~~~~~~~ + + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0594`. diff --git a/tests/ui/cannot-mutate-captured-non-mut-var.stderr b/tests/ui/cannot-mutate-captured-non-mut-var.stderr index 06b5ca407db..2d6e83c9e82 100644 --- a/tests/ui/cannot-mutate-captured-non-mut-var.stderr +++ b/tests/ui/cannot-mutate-captured-non-mut-var.stderr @@ -12,7 +12,7 @@ error[E0596]: cannot borrow `s` as mutable, as it is not declared as mutable LL | let s = std::io::stdin(); | - help: consider changing this to be mutable: `mut s` LL | to_fn_once(move|| { s.read_to_end(&mut Vec::new()); }); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot borrow as mutable + | ^ cannot borrow as mutable error: aborting due to 2 previous errors diff --git a/tests/ui/closures/binder/nested-closures-regions.stderr b/tests/ui/closures/binder/nested-closures-regions.stderr index 381aadb1564..a30339ac67b 100644 --- a/tests/ui/closures/binder/nested-closures-regions.stderr +++ b/tests/ui/closures/binder/nested-closures-regions.stderr @@ -4,7 +4,7 @@ note: external requirements LL | for<'a> || -> () { for<'c> |_: &'a ()| -> () {}; }; | ^^^^^^^^^^^^^^^^^^^^^^^^^ | - = note: defining type: main::{closure#0}::{closure#0} with closure substs [ + = note: defining type: main::{closure#0}::{closure#0} with closure args [ i8, extern "rust-call" fn((&(),)), (), @@ -21,7 +21,7 @@ note: no external requirements LL | for<'a> || -> () { for<'c> |_: &'a ()| -> () {}; }; | ^^^^^^^^^^^^^^^^ | - = note: defining type: main::{closure#0} with closure substs [ + = note: defining type: main::{closure#0} with closure args [ i8, extern "rust-call" fn(()), (), diff --git a/tests/ui/closures/print/closure-print-generic-trim-off-verbose-2.stderr b/tests/ui/closures/print/closure-print-generic-trim-off-verbose-2.stderr index 381bb0c084a..49453b0538b 100644 --- a/tests/ui/closures/print/closure-print-generic-trim-off-verbose-2.stderr +++ b/tests/ui/closures/print/closure-print-generic-trim-off-verbose-2.stderr @@ -9,7 +9,7 @@ LL | let c1 : () = c; | expected due to this | = note: expected unit type `()` - found closure `[mod1::f<T>::{closure#0} closure_substs=(unavailable) substs=[T, ?16t, extern "rust-call" fn(()), ?15t]]` + found closure `[mod1::f<T>::{closure#0} closure_args=(unavailable) args=[T, ?16t, extern "rust-call" fn(()), ?15t]]` help: use parentheses to call this closure | LL | let c1 : () = c(); diff --git a/tests/ui/closures/print/closure-print-generic-verbose-2.stderr b/tests/ui/closures/print/closure-print-generic-verbose-2.stderr index 2a4d16c48dc..d2deba3dd84 100644 --- a/tests/ui/closures/print/closure-print-generic-verbose-2.stderr +++ b/tests/ui/closures/print/closure-print-generic-verbose-2.stderr @@ -9,7 +9,7 @@ LL | let c1 : () = c; | expected due to this | = note: expected unit type `()` - found closure `[f<T>::{closure#0} closure_substs=(unavailable) substs=[T, ?16t, extern "rust-call" fn(()), ?15t]]` + found closure `[f<T>::{closure#0} closure_args=(unavailable) args=[T, ?16t, extern "rust-call" fn(()), ?15t]]` help: use parentheses to call this closure | LL | let c1 : () = c(); diff --git a/tests/ui/closures/print/closure-print-verbose.stderr b/tests/ui/closures/print/closure-print-verbose.stderr index 9e219435e5c..acc81f5e466 100644 --- a/tests/ui/closures/print/closure-print-verbose.stderr +++ b/tests/ui/closures/print/closure-print-verbose.stderr @@ -7,7 +7,7 @@ LL | let foo: fn(u8) -> u8 = |v: u8| { a += v; a }; | expected due to this | = note: expected fn pointer `fn(u8) -> u8` - found closure `[main::{closure#0} closure_substs=(unavailable) substs=[i8, extern "rust-call" fn((u8,)) -> u8, ?6t]]` + found closure `[main::{closure#0} closure_args=(unavailable) args=[i8, extern "rust-call" fn((u8,)) -> u8, ?6t]]` note: closures can only be coerced to `fn` types if they do not capture any variables --> $DIR/closure-print-verbose.rs:10:39 | diff --git a/tests/ui/codemap_tests/issue-11715.stderr b/tests/ui/codemap_tests/issue-11715.stderr index a6b2b2e50a3..d0c29c768eb 100644 --- a/tests/ui/codemap_tests/issue-11715.stderr +++ b/tests/ui/codemap_tests/issue-11715.stderr @@ -7,7 +7,7 @@ LL | let z = &mut x; | ^^^^^^ second mutable borrow occurs here LL | z.use_mut(); LL | y.use_mut(); - | ----------- first borrow later used here + | - first borrow later used here error: aborting due to previous error diff --git a/tests/ui/codemap_tests/one_line.stderr b/tests/ui/codemap_tests/one_line.stderr index 6fe6e26135b..75fbbada72c 100644 --- a/tests/ui/codemap_tests/one_line.stderr +++ b/tests/ui/codemap_tests/one_line.stderr @@ -2,9 +2,8 @@ error[E0499]: cannot borrow `v` as mutable more than once at a time --> $DIR/one_line.rs:3:12 | LL | v.push(v.pop().unwrap()); - | -------^^^^^^^---------- - | | | | - | | | second mutable borrow occurs here + | - ---- ^ second mutable borrow occurs here + | | | | | first borrow later used by call | first mutable borrow occurs here | diff --git a/tests/ui/codemap_tests/tab_3.stderr b/tests/ui/codemap_tests/tab_3.stderr index 17bea2f366f..b17159be6e0 100644 --- a/tests/ui/codemap_tests/tab_3.stderr +++ b/tests/ui/codemap_tests/tab_3.stderr @@ -15,7 +15,7 @@ note: `into_iter` takes ownership of the receiver `self`, which moves `some_vec` help: you can `clone` the value and consume it, but this might not be your desired behavior | LL | some_vec.clone().into_iter(); - | ++++++++ + | ++++++++ error: aborting due to previous error diff --git a/tests/ui/coherence/coherence-doesnt-use-infcx-evaluate.rs b/tests/ui/coherence/coherence-doesnt-use-infcx-evaluate.rs new file mode 100644 index 00000000000..063826f1d54 --- /dev/null +++ b/tests/ui/coherence/coherence-doesnt-use-infcx-evaluate.rs @@ -0,0 +1,24 @@ +// check-pass +// issue: 113415 + +// Makes sure that coherence doesn't call any of the `predicate_may_hold`-esque fns, +// since they are using a different infcx which doesn't preserve the intercrate flag. + +#![feature(specialization)] +//~^ WARN the feature `specialization` is incomplete + +trait Assoc { + type Output; +} + +default impl<T> Assoc for T { + type Output = bool; +} + +impl Assoc for u8 {} + +trait Foo {} +impl Foo for u32 {} +impl Foo for <u8 as Assoc>::Output {} + +fn main() {} diff --git a/tests/ui/coherence/coherence-doesnt-use-infcx-evaluate.stderr b/tests/ui/coherence/coherence-doesnt-use-infcx-evaluate.stderr new file mode 100644 index 00000000000..56eb21cd20f --- /dev/null +++ b/tests/ui/coherence/coherence-doesnt-use-infcx-evaluate.stderr @@ -0,0 +1,12 @@ +warning: the feature `specialization` is incomplete and may not be safe to use and/or cause compiler crashes + --> $DIR/coherence-doesnt-use-infcx-evaluate.rs:7:12 + | +LL | #![feature(specialization)] + | ^^^^^^^^^^^^^^ + | + = note: see issue #31844 <https://github.com/rust-lang/rust/issues/31844> for more information + = help: consider using `min_specialization` instead, which is more stable and complete + = note: `#[warn(incomplete_features)]` on by default + +warning: 1 warning emitted + diff --git a/tests/ui/const-generics/const-generic-default-wont-borrowck.stderr b/tests/ui/const-generics/const-generic-default-wont-borrowck.stderr index 0ed370b83c5..a345c48b088 100644 --- a/tests/ui/const-generics/const-generic-default-wont-borrowck.stderr +++ b/tests/ui/const-generics/const-generic-default-wont-borrowck.stderr @@ -2,7 +2,7 @@ error[E0381]: used binding `s` isn't initialized --> $DIR/const-generic-default-wont-borrowck.rs:2:26 | LL | let s: &'static str; s.len() - | - ^^^^^^^ `*s` used here but it isn't initialized + | - ^ `*s` used here but it isn't initialized | | | binding declared here but left uninitialized | diff --git a/tests/ui/const-generics/generic_const_exprs/issue-109141.stderr b/tests/ui/const-generics/generic_const_exprs/issue-109141.stderr index f61edd60e3b..8b8489ac2bc 100644 --- a/tests/ui/const-generics/generic_const_exprs/issue-109141.stderr +++ b/tests/ui/const-generics/generic_const_exprs/issue-109141.stderr @@ -13,7 +13,7 @@ error[E0596]: cannot borrow `*self.0` as mutable, as it is behind a `&` referenc --> $DIR/issue-109141.rs:6:9 | LL | self.0.iter_mut() - | ^^^^^^^^^^^^^^^^^ `self` is a `&` reference, so the data it refers to cannot be borrowed as mutable + | ^^^^^^ `self` is a `&` reference, so the data it refers to cannot be borrowed as mutable | help: consider changing this to be a mutable reference | diff --git a/tests/ui/const-generics/issues/issue-67375.full.stderr b/tests/ui/const-generics/issues/issue-67375.full.stderr index 0cf69879a5c..13cb8d1cd68 100644 --- a/tests/ui/const-generics/issues/issue-67375.full.stderr +++ b/tests/ui/const-generics/issues/issue-67375.full.stderr @@ -2,7 +2,7 @@ error: overly complex generic constant --> $DIR/issue-67375.rs:7:17 | LL | inner: [(); { [|_: &T| {}; 0].len() }], - | ^^---------------------^^ + | ^^---------------^^^^^^^^ | | | pointer casts are not allowed in generic constants | diff --git a/tests/ui/const-generics/late-bound-vars/in_closure.stderr b/tests/ui/const-generics/late-bound-vars/in_closure.stderr index 557fbea2e05..9dc5ea1f16a 100644 --- a/tests/ui/const-generics/late-bound-vars/in_closure.stderr +++ b/tests/ui/const-generics/late-bound-vars/in_closure.stderr @@ -6,8 +6,7 @@ error: query stack during panic: #4 [eval_to_allocation_raw] const-evaluating + checking `test::{closure#0}::{constant#1}` #5 [eval_to_valtree] evaluating type-level constant #6 [typeck] type-checking `test` -#7 [used_trait_imports] finding used_trait_imports `test` -#8 [analysis] running analysis passes on this crate +#7 [analysis] running analysis passes on this crate end of query stack error: aborting due to previous error diff --git a/tests/ui/const-generics/late-bound-vars/simple.stderr b/tests/ui/const-generics/late-bound-vars/simple.stderr index c0568f5a5cf..c9f2164b635 100644 --- a/tests/ui/const-generics/late-bound-vars/simple.stderr +++ b/tests/ui/const-generics/late-bound-vars/simple.stderr @@ -6,8 +6,7 @@ error: query stack during panic: #4 [eval_to_allocation_raw] const-evaluating + checking `test::{constant#1}` #5 [eval_to_valtree] evaluating type-level constant #6 [typeck] type-checking `test` -#7 [used_trait_imports] finding used_trait_imports `test` -#8 [analysis] running analysis passes on this crate +#7 [analysis] running analysis passes on this crate end of query stack error: aborting due to previous error diff --git a/tests/ui/const-generics/transmute-fail.stderr b/tests/ui/const-generics/transmute-fail.stderr index 9e308620a9c..12644b9f36d 100644 --- a/tests/ui/const-generics/transmute-fail.stderr +++ b/tests/ui/const-generics/transmute-fail.stderr @@ -16,18 +16,6 @@ LL | std::mem::transmute(v) = note: source type: `[[u32; H]; W]` (this type does not have a fixed size) = note: target type: `[[u32; W]; H]` (size can vary because of [u32; W]) -error[E0308]: mismatched types - --> $DIR/transmute-fail.rs:12:53 - | -LL | fn bar<const W: bool, const H: usize>(v: [[u32; H]; W]) -> [[u32; W]; H] { - | ^ expected `usize`, found `bool` - -error[E0308]: mismatched types - --> $DIR/transmute-fail.rs:12:67 - | -LL | fn bar<const W: bool, const H: usize>(v: [[u32; H]; W]) -> [[u32; W]; H] { - | ^ expected `usize`, found `bool` - error[E0512]: cannot transmute between types of different sizes, or dependently-sized types --> $DIR/transmute-fail.rs:23:5 | @@ -46,6 +34,18 @@ LL | std::mem::transmute(v) = note: source type: `[[[u32; 8888888]; 9999999]; 777777777]` (values of the type `[[u32; 8888888]; 9999999]` are too big for the current architecture) = note: target type: `[[[u32; 9999999]; 777777777]; 8888888]` (values of the type `[[u32; 9999999]; 777777777]` are too big for the current architecture) +error[E0308]: mismatched types + --> $DIR/transmute-fail.rs:12:53 + | +LL | fn bar<const W: bool, const H: usize>(v: [[u32; H]; W]) -> [[u32; W]; H] { + | ^ expected `usize`, found `bool` + +error[E0308]: mismatched types + --> $DIR/transmute-fail.rs:12:67 + | +LL | fn bar<const W: bool, const H: usize>(v: [[u32; H]; W]) -> [[u32; W]; H] { + | ^ expected `usize`, found `bool` + error: aborting due to 6 previous errors Some errors have detailed explanations: E0308, E0512. diff --git a/tests/ui/const-generics/type_mismatch.stderr b/tests/ui/const-generics/type_mismatch.stderr index 394dd44d40d..07476ae76c6 100644 --- a/tests/ui/const-generics/type_mismatch.stderr +++ b/tests/ui/const-generics/type_mismatch.stderr @@ -11,12 +11,6 @@ LL | fn bar<const N: u8>() -> [u8; N] {} | ^^^^^^^^^^^ required by this bound in `bar` error[E0308]: mismatched types - --> $DIR/type_mismatch.rs:2:11 - | -LL | bar::<N>() - | ^ expected `u8`, found `usize` - -error[E0308]: mismatched types --> $DIR/type_mismatch.rs:6:26 | LL | fn bar<const N: u8>() -> [u8; N] {} @@ -25,6 +19,12 @@ LL | fn bar<const N: u8>() -> [u8; N] {} | implicitly returns `()` as its body has no tail or `return` expression error[E0308]: mismatched types + --> $DIR/type_mismatch.rs:2:11 + | +LL | bar::<N>() + | ^ expected `u8`, found `usize` + +error[E0308]: mismatched types --> $DIR/type_mismatch.rs:6:31 | LL | fn bar<const N: u8>() -> [u8; N] {} diff --git a/tests/ui/consts/const_let_assign3.stderr b/tests/ui/consts/const_let_assign3.stderr index b550ac54573..89073f975e8 100644 --- a/tests/ui/consts/const_let_assign3.stderr +++ b/tests/ui/consts/const_let_assign3.stderr @@ -11,7 +11,7 @@ error[E0658]: mutable references are not allowed in constants --> $DIR/const_let_assign3.rs:14:5 | LL | s.foo(3); - | ^^^^^^^^ + | ^ | = note: see issue #57349 <https://github.com/rust-lang/rust/issues/57349> for more information = help: add `#![feature(const_mut_refs)]` to the crate attributes to enable diff --git a/tests/ui/did_you_mean/issue-34126.stderr b/tests/ui/did_you_mean/issue-34126.stderr index 5343acea4ad..9f792070628 100644 --- a/tests/ui/did_you_mean/issue-34126.stderr +++ b/tests/ui/did_you_mean/issue-34126.stderr @@ -19,9 +19,8 @@ error[E0502]: cannot borrow `self` as mutable because it is also borrowed as imm --> $DIR/issue-34126.rs:6:18 | LL | self.run(&mut self); - | ---------^^^^^^^^^- - | | | | - | | | mutable borrow occurs here + | ---- --- ^^^^^^^^^ mutable borrow occurs here + | | | | | immutable borrow later used by call | immutable borrow occurs here diff --git a/tests/ui/did_you_mean/issue-35937.stderr b/tests/ui/did_you_mean/issue-35937.stderr index 1670da55957..3081f2cec90 100644 --- a/tests/ui/did_you_mean/issue-35937.stderr +++ b/tests/ui/did_you_mean/issue-35937.stderr @@ -2,7 +2,7 @@ error[E0596]: cannot borrow `f.v` as mutable, as `f` is not declared as mutable --> $DIR/issue-35937.rs:7:5 | LL | f.v.push("cat".to_string()); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot borrow as mutable + | ^^^ cannot borrow as mutable | help: consider changing this to be mutable | diff --git a/tests/ui/did_you_mean/issue-38147-1.stderr b/tests/ui/did_you_mean/issue-38147-1.stderr index 74fb1c2eca3..790ad54a547 100644 --- a/tests/ui/did_you_mean/issue-38147-1.stderr +++ b/tests/ui/did_you_mean/issue-38147-1.stderr @@ -2,7 +2,7 @@ error[E0596]: cannot borrow `*self.s` as mutable, as it is behind a `&` referenc --> $DIR/issue-38147-1.rs:17:9 | LL | self.s.push('x'); - | ^^^^^^^^^^^^^^^^ `self` is a `&` reference, so the data it refers to cannot be borrowed as mutable + | ^^^^^^ `self` is a `&` reference, so the data it refers to cannot be borrowed as mutable | help: consider changing this to be a mutable reference | diff --git a/tests/ui/did_you_mean/issue-38147-2.stderr b/tests/ui/did_you_mean/issue-38147-2.stderr index 7c287a7dbfa..d708be3d32f 100644 --- a/tests/ui/did_you_mean/issue-38147-2.stderr +++ b/tests/ui/did_you_mean/issue-38147-2.stderr @@ -2,7 +2,7 @@ error[E0596]: cannot borrow `*self.s` as mutable, as it is behind a `&` referenc --> $DIR/issue-38147-2.rs:9:9 | LL | self.s.push('x'); - | ^^^^^^^^^^^^^^^^ cannot borrow as mutable + | ^^^^^^ cannot borrow as mutable | help: consider changing this to be mutable | @@ -13,7 +13,7 @@ error[E0596]: cannot borrow `*self.longer_name` as mutable, as it is behind a `& --> $DIR/issue-38147-2.rs:12:9 | LL | self.longer_name.push(13); - | ^^^^^^^^^^^^^^^^^^^^^^^^^ cannot borrow as mutable + | ^^^^^^^^^^^^^^^^ cannot borrow as mutable | help: consider changing this to be mutable | diff --git a/tests/ui/did_you_mean/issue-38147-3.stderr b/tests/ui/did_you_mean/issue-38147-3.stderr index 94ffe17f101..5b32b5a782c 100644 --- a/tests/ui/did_you_mean/issue-38147-3.stderr +++ b/tests/ui/did_you_mean/issue-38147-3.stderr @@ -2,7 +2,7 @@ error[E0596]: cannot borrow `*self.s` as mutable, as it is behind a `&` referenc --> $DIR/issue-38147-3.rs:7:9 | LL | self.s.push('x'); - | ^^^^^^^^^^^^^^^^ cannot borrow as mutable + | ^^^^^^ cannot borrow as mutable | help: consider changing this to be mutable | diff --git a/tests/ui/did_you_mean/issue-38147-4.stderr b/tests/ui/did_you_mean/issue-38147-4.stderr index 43647fa562b..38ab3c54d01 100644 --- a/tests/ui/did_you_mean/issue-38147-4.stderr +++ b/tests/ui/did_you_mean/issue-38147-4.stderr @@ -2,7 +2,7 @@ error[E0596]: cannot borrow `*f.s` as mutable, as it is behind a `&` reference --> $DIR/issue-38147-4.rs:6:5 | LL | f.s.push('x'); - | ^^^^^^^^^^^^^ `f` is a `&` reference, so the data it refers to cannot be borrowed as mutable + | ^^^ `f` is a `&` reference, so the data it refers to cannot be borrowed as mutable | help: consider changing this to be a mutable reference | diff --git a/tests/ui/did_you_mean/issue-40823.stderr b/tests/ui/did_you_mean/issue-40823.stderr index ba94a570256..6f1ed355438 100644 --- a/tests/ui/did_you_mean/issue-40823.stderr +++ b/tests/ui/did_you_mean/issue-40823.stderr @@ -2,7 +2,7 @@ error[E0596]: cannot borrow `*buf` as mutable, as it is behind a `&` reference --> $DIR/issue-40823.rs:3:5 | LL | buf.iter_mut(); - | ^^^^^^^^^^^^^^ `buf` is a `&` reference, so the data it refers to cannot be borrowed as mutable + | ^^^ `buf` is a `&` reference, so the data it refers to cannot be borrowed as mutable | help: consider changing this to be a mutable reference | diff --git a/tests/ui/dropck/drop-with-active-borrows-1.stderr b/tests/ui/dropck/drop-with-active-borrows-1.stderr index 4585b22974c..0409ffa02b1 100644 --- a/tests/ui/dropck/drop-with-active-borrows-1.stderr +++ b/tests/ui/dropck/drop-with-active-borrows-1.stderr @@ -4,7 +4,7 @@ error[E0505]: cannot move out of `a` because it is borrowed LL | let a = "".to_string(); | - binding `a` declared here LL | let b: Vec<&str> = a.lines().collect(); - | --------- borrow of `a` occurs here + | - borrow of `a` occurs here LL | drop(a); | ^ move out of `a` occurs here LL | for s in &b { diff --git a/tests/ui/dropck/drop-with-active-borrows-2.stderr b/tests/ui/dropck/drop-with-active-borrows-2.stderr index 24650dfac02..ffec9306b77 100644 --- a/tests/ui/dropck/drop-with-active-borrows-2.stderr +++ b/tests/ui/dropck/drop-with-active-borrows-2.stderr @@ -2,7 +2,7 @@ error[E0515]: cannot return value referencing local variable `raw_lines` --> $DIR/drop-with-active-borrows-2.rs:3:5 | LL | raw_lines.iter().map(|l| l.trim()).collect() - | ----------------^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ---------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | | | returns a value referencing data owned by the current function | `raw_lines` is borrowed here diff --git a/tests/ui/dyn-star/llvm-old-style-ptrs.rs b/tests/ui/dyn-star/llvm-old-style-ptrs.rs index d35519632be..4c042a53979 100644 --- a/tests/ui/dyn-star/llvm-old-style-ptrs.rs +++ b/tests/ui/dyn-star/llvm-old-style-ptrs.rs @@ -3,6 +3,8 @@ // (opaque-pointers flag is called force-opaque-pointers in LLVM 13...) // min-llvm-version: 14.0 +// (the ability to disable opaque pointers has been removed in LLVM 17) +// ignore-llvm-version: 17 - 99 // This test can be removed once non-opaque pointers are gone from LLVM, maybe. diff --git a/tests/ui/error-codes/E0161.base.stderr b/tests/ui/error-codes/E0161.base.stderr index 15d98b657a2..ae82e6702e6 100644 --- a/tests/ui/error-codes/E0161.base.stderr +++ b/tests/ui/error-codes/E0161.base.stderr @@ -2,7 +2,7 @@ error[E0161]: cannot move a value of type `dyn Bar` --> $DIR/E0161.rs:16:5 | LL | x.f(); - | ^^^^^ the size of `dyn Bar` cannot be statically determined + | ^ the size of `dyn Bar` cannot be statically determined error: aborting due to previous error diff --git a/tests/ui/error-codes/E0499.stderr b/tests/ui/error-codes/E0499.stderr index af5a1e18633..d56baf72272 100644 --- a/tests/ui/error-codes/E0499.stderr +++ b/tests/ui/error-codes/E0499.stderr @@ -7,7 +7,7 @@ LL | let mut a = &mut i; | ^^^^^^ second mutable borrow occurs here LL | a.use_mut(); LL | x.use_mut(); - | ----------- first borrow later used here + | - first borrow later used here error: aborting due to previous error diff --git a/tests/ui/error-codes/E0502.stderr b/tests/ui/error-codes/E0502.stderr index 94cc89754db..cade6d71852 100644 --- a/tests/ui/error-codes/E0502.stderr +++ b/tests/ui/error-codes/E0502.stderr @@ -6,7 +6,7 @@ LL | let ref y = a; LL | bar(a); | ^^^^^^ mutable borrow occurs here LL | y.use_ref(); - | ----------- immutable borrow later used here + | - immutable borrow later used here error: aborting due to previous error diff --git a/tests/ui/error-codes/E0503.stderr b/tests/ui/error-codes/E0503.stderr index 2f02e3b1a61..275abb23f53 100644 --- a/tests/ui/error-codes/E0503.stderr +++ b/tests/ui/error-codes/E0503.stderr @@ -6,7 +6,7 @@ LL | let _borrow = &mut value; LL | let _sum = value + 1; | ^^^^^ use of borrowed `value` LL | _borrow.use_mut(); - | ----------------- borrow later used here + | ------- borrow later used here error: aborting due to previous error diff --git a/tests/ui/error-codes/E0505.stderr b/tests/ui/error-codes/E0505.stderr index 2ecb4a75c43..1a85e031705 100644 --- a/tests/ui/error-codes/E0505.stderr +++ b/tests/ui/error-codes/E0505.stderr @@ -9,7 +9,7 @@ LL | let _ref_to_val: &Value = &x; LL | eat(x); | ^ move out of `x` occurs here LL | _ref_to_val.use_ref(); - | --------------------- borrow later used here + | ----------- borrow later used here error: aborting due to previous error diff --git a/tests/ui/error-codes/E0507.stderr b/tests/ui/error-codes/E0507.stderr index 03630f38987..08993951622 100644 --- a/tests/ui/error-codes/E0507.stderr +++ b/tests/ui/error-codes/E0507.stderr @@ -2,9 +2,8 @@ error[E0507]: cannot move out of dereference of `Ref<'_, TheDarkKnight>` --> $DIR/E0507.rs:12:5 | LL | x.borrow().nothing_is_true(); - | ^^^^^^^^^^^----------------- - | | | - | | value moved due to this method call + | ^^^^^^^^^^ ----------------- value moved due to this method call + | | | move occurs because value has type `TheDarkKnight`, which does not implement the `Copy` trait | note: `TheDarkKnight::nothing_is_true` takes ownership of the receiver `self`, which moves value diff --git a/tests/ui/generator/dropck-resume.stderr b/tests/ui/generator/dropck-resume.stderr index b0756eb5589..ecf92e7e3ae 100644 --- a/tests/ui/generator/dropck-resume.stderr +++ b/tests/ui/generator/dropck-resume.stderr @@ -5,7 +5,7 @@ LL | let z = &mut y; | ------ mutable borrow occurs here ... LL | r = y.as_ref().unwrap(); - | ^^^^^^^^^^ immutable borrow occurs here + | ^ immutable borrow occurs here LL | LL | } | - mutable borrow might be used here, when `g` is dropped and runs the destructor for generator diff --git a/tests/ui/generator/dropck.stderr b/tests/ui/generator/dropck.stderr index b9a3a124acb..246ac99f83f 100644 --- a/tests/ui/generator/dropck.stderr +++ b/tests/ui/generator/dropck.stderr @@ -5,7 +5,7 @@ LL | let (mut gen, cell); | ---- binding `cell` declared here LL | cell = Box::new(RefCell::new(0)); LL | let ref_ = Box::leak(Box::new(Some(cell.borrow_mut()))); - | ^^^^^^^^^^^^^^^^^ borrowed value does not live long enough + | ^^^^ borrowed value does not live long enough ... LL | } | - diff --git a/tests/ui/hashmap/hashmap-iter-value-lifetime.stderr b/tests/ui/hashmap/hashmap-iter-value-lifetime.stderr index d6e7a1d45f0..de2591329c8 100644 --- a/tests/ui/hashmap/hashmap-iter-value-lifetime.stderr +++ b/tests/ui/hashmap/hashmap-iter-value-lifetime.stderr @@ -2,7 +2,7 @@ error[E0502]: cannot borrow `my_stuff` as mutable because it is also borrowed as --> $DIR/hashmap-iter-value-lifetime.rs:7:5 | LL | let (_, thing) = my_stuff.iter().next().unwrap(); - | --------------- immutable borrow occurs here + | -------- immutable borrow occurs here LL | LL | my_stuff.clear(); | ^^^^^^^^^^^^^^^^ mutable borrow occurs here diff --git a/tests/ui/hashmap/hashmap-lifetimes.stderr b/tests/ui/hashmap/hashmap-lifetimes.stderr index d1bcd53ae3b..497c7d1216c 100644 --- a/tests/ui/hashmap/hashmap-lifetimes.stderr +++ b/tests/ui/hashmap/hashmap-lifetimes.stderr @@ -2,7 +2,7 @@ error[E0502]: cannot borrow `my_stuff` as mutable because it is also borrowed as --> $DIR/hashmap-lifetimes.rs:6:5 | LL | let mut it = my_stuff.iter(); - | --------------- immutable borrow occurs here + | -------- immutable borrow occurs here LL | my_stuff.insert(1, 43); | ^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here LL | it; diff --git a/tests/ui/higher-ranked/trait-bounds/hrtb-debruijn-in-receiver.stderr b/tests/ui/higher-ranked/trait-bounds/hrtb-debruijn-in-receiver.stderr index fa391ecba8a..70d5b3c2ec5 100644 --- a/tests/ui/higher-ranked/trait-bounds/hrtb-debruijn-in-receiver.stderr +++ b/tests/ui/higher-ranked/trait-bounds/hrtb-debruijn-in-receiver.stderr @@ -2,9 +2,9 @@ error[E0499]: cannot borrow `foo` as mutable more than once at a time --> $DIR/hrtb-debruijn-in-receiver.rs:17:5 | LL | foo.insert(); - | ------------ first mutable borrow occurs here + | --- first mutable borrow occurs here LL | foo.insert(); - | ^^^^^^^^^^^^ + | ^^^ | | | second mutable borrow occurs here | first borrow later used here diff --git a/tests/ui/hygiene/fields-numeric-borrowck.stderr b/tests/ui/hygiene/fields-numeric-borrowck.stderr index bc13aa62f4d..fb90825c0d9 100644 --- a/tests/ui/hygiene/fields-numeric-borrowck.stderr +++ b/tests/ui/hygiene/fields-numeric-borrowck.stderr @@ -7,7 +7,7 @@ LL | let S { 0: ref mut borrow2 } = s; | ^^^^^^^^^^^^^^^ second mutable borrow occurs here ... LL | borrow1.use_mut(); - | ----------------- first borrow later used here + | ------- first borrow later used here error: aborting due to previous error diff --git a/tests/ui/hygiene/panic-location.run.stderr b/tests/ui/hygiene/panic-location.run.stderr index a7252a40027..55923cc5f6f 100644 --- a/tests/ui/hygiene/panic-location.run.stderr +++ b/tests/ui/hygiene/panic-location.run.stderr @@ -1,2 +1,2 @@ -thread 'main' panicked at 'capacity overflow', library/alloc/src/raw_vec.rs:524:5 +thread 'main' panicked at 'capacity overflow', library/alloc/src/raw_vec.rs:534:5 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace diff --git a/tests/ui/impl-trait/issue-102605.stderr b/tests/ui/impl-trait/issue-102605.stderr index dfe18e43eee..dcb22797173 100644 --- a/tests/ui/impl-trait/issue-102605.stderr +++ b/tests/ui/impl-trait/issue-102605.stderr @@ -1,3 +1,11 @@ +error[E0277]: `main` has invalid return type `Option<()>` + --> $DIR/issue-102605.rs:11:14 + | +LL | fn main() -> Option<()> { + | ^^^^^^^^^^ `main` can only return types that implement `Termination` + | + = help: consider using `()`, or a `Result` + error[E0308]: mismatched types --> $DIR/issue-102605.rs:13:20 | @@ -25,14 +33,6 @@ help: try wrapping the expression in `Err` LL | convert_result(Err(foo())) | ++++ + -error[E0277]: `main` has invalid return type `Option<()>` - --> $DIR/issue-102605.rs:11:14 - | -LL | fn main() -> Option<()> { - | ^^^^^^^^^^ `main` can only return types that implement `Termination` - | - = help: consider using `()`, or a `Result` - error: aborting due to 2 previous errors Some errors have detailed explanations: E0277, E0308. diff --git a/tests/ui/inference/issue-113354.fixed b/tests/ui/inference/issue-113354.fixed new file mode 100644 index 00000000000..804db985ae1 --- /dev/null +++ b/tests/ui/inference/issue-113354.fixed @@ -0,0 +1,4 @@ +//run-rustfix +fn main() { + let _ = || { while let Some(_) = Some(1) { } }; //~ ERROR mismatched types +} diff --git a/tests/ui/inference/issue-113354.rs b/tests/ui/inference/issue-113354.rs new file mode 100644 index 00000000000..ec33d1f8b84 --- /dev/null +++ b/tests/ui/inference/issue-113354.rs @@ -0,0 +1,4 @@ +//run-rustfix +fn main() { + let _ = || { while Some(_) = Some(1) { } }; //~ ERROR mismatched types +} diff --git a/tests/ui/inference/issue-113354.stderr b/tests/ui/inference/issue-113354.stderr new file mode 100644 index 00000000000..045a5aa7bf0 --- /dev/null +++ b/tests/ui/inference/issue-113354.stderr @@ -0,0 +1,14 @@ +error[E0308]: mismatched types + --> $DIR/issue-113354.rs:3:24 + | +LL | let _ = || { while Some(_) = Some(1) { } }; + | ^^^^^^^^^^^^^^^^^ expected `bool`, found `()` + | +help: consider adding `let` + | +LL | let _ = || { while let Some(_) = Some(1) { } }; + | +++ + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0308`. diff --git a/tests/ui/inference/need_type_info/issue-113264-incorrect-impl-trait-in-path-suggestion.rs b/tests/ui/inference/need_type_info/issue-113264-incorrect-impl-trait-in-path-suggestion.rs new file mode 100644 index 00000000000..5a893f2d8ad --- /dev/null +++ b/tests/ui/inference/need_type_info/issue-113264-incorrect-impl-trait-in-path-suggestion.rs @@ -0,0 +1,12 @@ +trait T {} + +struct S {} + +impl S { + fn owo(&self, _: Option<&impl T>) {} +} + +fn main() { + (S {}).owo(None) + //~^ ERROR type annotations needed +} diff --git a/tests/ui/inference/need_type_info/issue-113264-incorrect-impl-trait-in-path-suggestion.stderr b/tests/ui/inference/need_type_info/issue-113264-incorrect-impl-trait-in-path-suggestion.stderr new file mode 100644 index 00000000000..0ec219415ab --- /dev/null +++ b/tests/ui/inference/need_type_info/issue-113264-incorrect-impl-trait-in-path-suggestion.stderr @@ -0,0 +1,14 @@ +error[E0282]: type annotations needed + --> $DIR/issue-113264-incorrect-impl-trait-in-path-suggestion.rs:10:16 + | +LL | (S {}).owo(None) + | ^^^^ cannot infer type of the type parameter `T` declared on the enum `Option` + | +help: consider specifying the generic argument + | +LL | (S {}).owo(None::<&_>) + | ++++++ + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0282`. diff --git a/tests/ui/issues/issue-13497-2.stderr b/tests/ui/issues/issue-13497-2.stderr index a365e24e27e..8ad921027e2 100644 --- a/tests/ui/issues/issue-13497-2.stderr +++ b/tests/ui/issues/issue-13497-2.stderr @@ -1,11 +1,13 @@ error[E0515]: cannot return value referencing local variable `rawLines` --> $DIR/issue-13497-2.rs:3:5 | -LL | // rawLines -LL | || .iter().map(|l| l.trim()).collect() - | ||_______________-___________________________^ returns a value referencing data owned by the current function - | |_______________| - | `rawLines` is borrowed here +LL | rawLines + | ^------- + | | + | _____`rawLines` is borrowed here + | | +LL | | .iter().map(|l| l.trim()).collect() + | |___________________________________________^ returns a value referencing data owned by the current function error: aborting due to previous error diff --git a/tests/ui/issues/issue-21600.stderr b/tests/ui/issues/issue-21600.stderr index ea304f9367b..f7905934424 100644 --- a/tests/ui/issues/issue-21600.stderr +++ b/tests/ui/issues/issue-21600.stderr @@ -5,7 +5,7 @@ LL | fn call_it<F>(f: F) where F: Fn() { f(); } | - change this to accept `FnMut` instead of `Fn` ... LL | call_it(|| x.gen_mut()); - | ------- -- ^^^^^^^^^^^ cannot borrow as mutable + | ------- -- ^ cannot borrow as mutable | | | | | in this closure | expects `Fn` instead of `FnMut` diff --git a/tests/ui/issues/issue-41726.stderr b/tests/ui/issues/issue-41726.stderr index b05c1fb14ef..7c87fde540d 100644 --- a/tests/ui/issues/issue-41726.stderr +++ b/tests/ui/issues/issue-41726.stderr @@ -2,13 +2,10 @@ error[E0596]: cannot borrow data in an index of `HashMap<String, Vec<String>>` a --> $DIR/issue-41726.rs:5:9 | LL | things[src.as_str()].sort(); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot borrow as mutable + | ^^^^^^^^^^^^^^^^^^^^ cannot borrow as mutable | = help: trait `IndexMut` is required to modify indexed content, but it is not implemented for `HashMap<String, Vec<String>>` -help: to modify a `HashMap<String, Vec<String>>` use `.get_mut()` - | -LL | things.get_mut(src.as_str()).map(|val| val.sort()); - | ~~~~~~~~~ ~~~~~~~~~~~~~~~ + + = help: to modify a `HashMap<String, Vec<String>>`, use `.get_mut()`, `.insert()` or the entry API error: aborting due to previous error diff --git a/tests/ui/issues/issue-42106.stderr b/tests/ui/issues/issue-42106.stderr index 73cf8652f6d..d5a9d233bc9 100644 --- a/tests/ui/issues/issue-42106.stderr +++ b/tests/ui/issues/issue-42106.stderr @@ -4,9 +4,9 @@ error[E0502]: cannot borrow `*collection` as mutable because it is also borrowed LL | let _a = &collection; | ----------- immutable borrow occurs here LL | collection.swap(1, 2); - | ^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here + | ^^^^^^^^^^ mutable borrow occurs here LL | _a.use_ref(); - | ------------ immutable borrow later used here + | -- immutable borrow later used here error: aborting due to previous error diff --git a/tests/ui/issues/issue-44405.stderr b/tests/ui/issues/issue-44405.stderr index 626cb2999e1..1fd69f6e777 100644 --- a/tests/ui/issues/issue-44405.stderr +++ b/tests/ui/issues/issue-44405.stderr @@ -2,7 +2,7 @@ error[E0596]: cannot borrow data in an index of `Container` as mutable --> $DIR/issue-44405.rs:21:5 | LL | container[&mut val].test(); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot borrow as mutable + | ^^^^^^^^^^^^^^^^^^^ cannot borrow as mutable | = help: trait `IndexMut` is required to modify indexed content, but it is not implemented for `Container` diff --git a/tests/ui/issues/issue-52126-assign-op-invariance.stderr b/tests/ui/issues/issue-52126-assign-op-invariance.stderr index 2d3b48832c5..316e755f42a 100644 --- a/tests/ui/issues/issue-52126-assign-op-invariance.stderr +++ b/tests/ui/issues/issue-52126-assign-op-invariance.stderr @@ -4,7 +4,7 @@ error[E0597]: `line` does not live long enough LL | for line in vec!["123456789".to_string(), "12345678".to_string()] { | ---- binding `line` declared here LL | let v: Vec<&str> = line.split_whitespace().collect(); - | ^^^^^^^^^^^^^^^^^^^^^^^ borrowed value does not live long enough + | ^^^^ borrowed value does not live long enough ... LL | acc += cnt2; | --- borrow later used here diff --git a/tests/ui/issues/issue-61108.stderr b/tests/ui/issues/issue-61108.stderr index 3aaf5fb3f3e..dd87b62664b 100644 --- a/tests/ui/issues/issue-61108.stderr +++ b/tests/ui/issues/issue-61108.stderr @@ -7,7 +7,7 @@ LL | for l in bad_letters { | ----------- `bad_letters` moved due to this implicit call to `.into_iter()` ... LL | bad_letters.push('s'); - | ^^^^^^^^^^^^^^^^^^^^^ value borrowed here after move + | ^^^^^^^^^^^ value borrowed here after move | note: `into_iter` takes ownership of the receiver `self`, which moves `bad_letters` --> $SRC_DIR/core/src/iter/traits/collect.rs:LL:COL diff --git a/tests/ui/issues/issue-81584.stderr b/tests/ui/issues/issue-81584.stderr index 54973cfa34e..d57f1b778df 100644 --- a/tests/ui/issues/issue-81584.stderr +++ b/tests/ui/issues/issue-81584.stderr @@ -2,7 +2,7 @@ error[E0515]: cannot return value referencing function parameter `y` --> $DIR/issue-81584.rs:5:22 | LL | .map(|y| y.iter().map(|x| x + 1)) - | --------^^^^^^^^^^^^^^^ + | -^^^^^^^^^^^^^^^^^^^^^^ | | | returns a value referencing data owned by the current function | `y` is borrowed here diff --git a/tests/ui/layout/debug.stderr b/tests/ui/layout/debug.stderr index b9fa1b299e9..eeffb3c5f64 100644 --- a/tests/ui/layout/debug.stderr +++ b/tests/ui/layout/debug.stderr @@ -53,6 +53,8 @@ error: layout_of(E) = Layout { variants: Single { index: 0, }, + max_repr_align: None, + unadjusted_abi_align: Align(1 bytes), }, Layout { size: Size(12 bytes), @@ -77,9 +79,13 @@ error: layout_of(E) = Layout { variants: Single { index: 1, }, + max_repr_align: None, + unadjusted_abi_align: Align(4 bytes), }, ], }, + max_repr_align: None, + unadjusted_abi_align: Align(4 bytes), } --> $DIR/debug.rs:7:1 | @@ -124,6 +130,8 @@ error: layout_of(S) = Layout { variants: Single { index: 0, }, + max_repr_align: None, + unadjusted_abi_align: Align(4 bytes), } --> $DIR/debug.rs:10:1 | @@ -146,6 +154,8 @@ error: layout_of(U) = Layout { variants: Single { index: 0, }, + max_repr_align: None, + unadjusted_abi_align: Align(4 bytes), } --> $DIR/debug.rs:13:1 | @@ -237,6 +247,8 @@ error: layout_of(std::result::Result<i32, i32>) = Layout { variants: Single { index: 0, }, + max_repr_align: None, + unadjusted_abi_align: Align(4 bytes), }, Layout { size: Size(8 bytes), @@ -272,9 +284,13 @@ error: layout_of(std::result::Result<i32, i32>) = Layout { variants: Single { index: 1, }, + max_repr_align: None, + unadjusted_abi_align: Align(4 bytes), }, ], }, + max_repr_align: None, + unadjusted_abi_align: Align(4 bytes), } --> $DIR/debug.rs:16:1 | @@ -301,6 +317,8 @@ error: layout_of(i32) = Layout { variants: Single { index: 0, }, + max_repr_align: None, + unadjusted_abi_align: Align(4 bytes), } --> $DIR/debug.rs:19:1 | @@ -323,6 +341,8 @@ error: layout_of(V) = Layout { variants: Single { index: 0, }, + max_repr_align: None, + unadjusted_abi_align: Align(2 bytes), } --> $DIR/debug.rs:22:1 | @@ -345,6 +365,8 @@ error: layout_of(W) = Layout { variants: Single { index: 0, }, + max_repr_align: None, + unadjusted_abi_align: Align(2 bytes), } --> $DIR/debug.rs:28:1 | @@ -367,6 +389,8 @@ error: layout_of(Y) = Layout { variants: Single { index: 0, }, + max_repr_align: None, + unadjusted_abi_align: Align(2 bytes), } --> $DIR/debug.rs:34:1 | @@ -389,6 +413,8 @@ error: layout_of(P1) = Layout { variants: Single { index: 0, }, + max_repr_align: None, + unadjusted_abi_align: Align(1 bytes), } --> $DIR/debug.rs:41:1 | @@ -411,6 +437,8 @@ error: layout_of(P2) = Layout { variants: Single { index: 0, }, + max_repr_align: None, + unadjusted_abi_align: Align(1 bytes), } --> $DIR/debug.rs:45:1 | @@ -433,6 +461,8 @@ error: layout_of(P3) = Layout { variants: Single { index: 0, }, + max_repr_align: None, + unadjusted_abi_align: Align(1 bytes), } --> $DIR/debug.rs:53:1 | @@ -455,6 +485,8 @@ error: layout_of(P4) = Layout { variants: Single { index: 0, }, + max_repr_align: None, + unadjusted_abi_align: Align(1 bytes), } --> $DIR/debug.rs:57:1 | @@ -482,6 +514,8 @@ error: layout_of(P5) = Layout { variants: Single { index: 0, }, + max_repr_align: None, + unadjusted_abi_align: Align(1 bytes), } --> $DIR/debug.rs:61:1 | @@ -509,6 +543,8 @@ error: layout_of(std::mem::MaybeUninit<u8>) = Layout { variants: Single { index: 0, }, + max_repr_align: None, + unadjusted_abi_align: Align(1 bytes), } --> $DIR/debug.rs:64:1 | diff --git a/tests/ui/layout/hexagon-enum.stderr b/tests/ui/layout/hexagon-enum.stderr index d850dd69c96..a2ad4a1ab58 100644 --- a/tests/ui/layout/hexagon-enum.stderr +++ b/tests/ui/layout/hexagon-enum.stderr @@ -59,9 +59,13 @@ error: layout_of(A) = Layout { variants: Single { index: 0, }, + max_repr_align: None, + unadjusted_abi_align: Align(1 bytes), }, ], }, + max_repr_align: None, + unadjusted_abi_align: Align(1 bytes), } --> $DIR/hexagon-enum.rs:16:1 | @@ -129,9 +133,13 @@ error: layout_of(B) = Layout { variants: Single { index: 0, }, + max_repr_align: None, + unadjusted_abi_align: Align(1 bytes), }, ], }, + max_repr_align: None, + unadjusted_abi_align: Align(1 bytes), } --> $DIR/hexagon-enum.rs:20:1 | @@ -199,9 +207,13 @@ error: layout_of(C) = Layout { variants: Single { index: 0, }, + max_repr_align: None, + unadjusted_abi_align: Align(2 bytes), }, ], }, + max_repr_align: None, + unadjusted_abi_align: Align(2 bytes), } --> $DIR/hexagon-enum.rs:24:1 | @@ -269,9 +281,13 @@ error: layout_of(P) = Layout { variants: Single { index: 0, }, + max_repr_align: None, + unadjusted_abi_align: Align(4 bytes), }, ], }, + max_repr_align: None, + unadjusted_abi_align: Align(4 bytes), } --> $DIR/hexagon-enum.rs:28:1 | @@ -339,9 +355,13 @@ error: layout_of(T) = Layout { variants: Single { index: 0, }, + max_repr_align: None, + unadjusted_abi_align: Align(4 bytes), }, ], }, + max_repr_align: None, + unadjusted_abi_align: Align(4 bytes), } --> $DIR/hexagon-enum.rs:34:1 | diff --git a/tests/ui/layout/issue-96158-scalarpair-payload-might-be-uninit.stderr b/tests/ui/layout/issue-96158-scalarpair-payload-might-be-uninit.stderr index 8c7c915350f..d3ba1a295b1 100644 --- a/tests/ui/layout/issue-96158-scalarpair-payload-might-be-uninit.stderr +++ b/tests/ui/layout/issue-96158-scalarpair-payload-might-be-uninit.stderr @@ -81,6 +81,8 @@ error: layout_of(MissingPayloadField) = Layout { variants: Single { index: 0, }, + max_repr_align: None, + unadjusted_abi_align: Align(1 bytes), }, Layout { size: Size(1 bytes), @@ -99,9 +101,13 @@ error: layout_of(MissingPayloadField) = Layout { variants: Single { index: 1, }, + max_repr_align: None, + unadjusted_abi_align: Align(1 bytes), }, ], }, + max_repr_align: None, + unadjusted_abi_align: Align(1 bytes), } --> $DIR/issue-96158-scalarpair-payload-might-be-uninit.rs:16:1 | @@ -193,6 +199,8 @@ error: layout_of(CommonPayloadField) = Layout { variants: Single { index: 0, }, + max_repr_align: None, + unadjusted_abi_align: Align(1 bytes), }, Layout { size: Size(2 bytes), @@ -228,9 +236,13 @@ error: layout_of(CommonPayloadField) = Layout { variants: Single { index: 1, }, + max_repr_align: None, + unadjusted_abi_align: Align(1 bytes), }, ], }, + max_repr_align: None, + unadjusted_abi_align: Align(1 bytes), } --> $DIR/issue-96158-scalarpair-payload-might-be-uninit.rs:25:1 | @@ -320,6 +332,8 @@ error: layout_of(CommonPayloadFieldIsMaybeUninit) = Layout { variants: Single { index: 0, }, + max_repr_align: None, + unadjusted_abi_align: Align(1 bytes), }, Layout { size: Size(2 bytes), @@ -354,9 +368,13 @@ error: layout_of(CommonPayloadFieldIsMaybeUninit) = Layout { variants: Single { index: 1, }, + max_repr_align: None, + unadjusted_abi_align: Align(1 bytes), }, ], }, + max_repr_align: None, + unadjusted_abi_align: Align(1 bytes), } --> $DIR/issue-96158-scalarpair-payload-might-be-uninit.rs:33:1 | @@ -462,6 +480,8 @@ error: layout_of(NicheFirst) = Layout { variants: Single { index: 0, }, + max_repr_align: None, + unadjusted_abi_align: Align(1 bytes), }, Layout { size: Size(0 bytes), @@ -480,6 +500,8 @@ error: layout_of(NicheFirst) = Layout { variants: Single { index: 1, }, + max_repr_align: None, + unadjusted_abi_align: Align(1 bytes), }, Layout { size: Size(0 bytes), @@ -498,9 +520,13 @@ error: layout_of(NicheFirst) = Layout { variants: Single { index: 2, }, + max_repr_align: None, + unadjusted_abi_align: Align(1 bytes), }, ], }, + max_repr_align: None, + unadjusted_abi_align: Align(1 bytes), } --> $DIR/issue-96158-scalarpair-payload-might-be-uninit.rs:41:1 | @@ -606,6 +632,8 @@ error: layout_of(NicheSecond) = Layout { variants: Single { index: 0, }, + max_repr_align: None, + unadjusted_abi_align: Align(1 bytes), }, Layout { size: Size(0 bytes), @@ -624,6 +652,8 @@ error: layout_of(NicheSecond) = Layout { variants: Single { index: 1, }, + max_repr_align: None, + unadjusted_abi_align: Align(1 bytes), }, Layout { size: Size(0 bytes), @@ -642,9 +672,13 @@ error: layout_of(NicheSecond) = Layout { variants: Single { index: 2, }, + max_repr_align: None, + unadjusted_abi_align: Align(1 bytes), }, ], }, + max_repr_align: None, + unadjusted_abi_align: Align(1 bytes), } --> $DIR/issue-96158-scalarpair-payload-might-be-uninit.rs:50:1 | diff --git a/tests/ui/layout/issue-96185-overaligned-enum.stderr b/tests/ui/layout/issue-96185-overaligned-enum.stderr index de6177c8dfc..c539eb453d9 100644 --- a/tests/ui/layout/issue-96185-overaligned-enum.stderr +++ b/tests/ui/layout/issue-96185-overaligned-enum.stderr @@ -53,6 +53,10 @@ error: layout_of(Aligned1) = Layout { variants: Single { index: 0, }, + max_repr_align: Some( + Align(8 bytes), + ), + unadjusted_abi_align: Align(1 bytes), }, Layout { size: Size(8 bytes), @@ -71,9 +75,17 @@ error: layout_of(Aligned1) = Layout { variants: Single { index: 1, }, + max_repr_align: Some( + Align(8 bytes), + ), + unadjusted_abi_align: Align(1 bytes), }, ], }, + max_repr_align: Some( + Align(8 bytes), + ), + unadjusted_abi_align: Align(1 bytes), } --> $DIR/issue-96185-overaligned-enum.rs:8:1 | @@ -141,6 +153,10 @@ error: layout_of(Aligned2) = Layout { variants: Single { index: 0, }, + max_repr_align: Some( + Align(1 bytes), + ), + unadjusted_abi_align: Align(1 bytes), }, Layout { size: Size(1 bytes), @@ -159,9 +175,17 @@ error: layout_of(Aligned2) = Layout { variants: Single { index: 1, }, + max_repr_align: Some( + Align(1 bytes), + ), + unadjusted_abi_align: Align(1 bytes), }, ], }, + max_repr_align: Some( + Align(1 bytes), + ), + unadjusted_abi_align: Align(1 bytes), } --> $DIR/issue-96185-overaligned-enum.rs:16:1 | diff --git a/tests/ui/layout/thumb-enum.stderr b/tests/ui/layout/thumb-enum.stderr index 227bd950b66..6f6ab498206 100644 --- a/tests/ui/layout/thumb-enum.stderr +++ b/tests/ui/layout/thumb-enum.stderr @@ -59,9 +59,13 @@ error: layout_of(A) = Layout { variants: Single { index: 0, }, + max_repr_align: None, + unadjusted_abi_align: Align(1 bytes), }, ], }, + max_repr_align: None, + unadjusted_abi_align: Align(1 bytes), } --> $DIR/thumb-enum.rs:16:1 | @@ -129,9 +133,13 @@ error: layout_of(B) = Layout { variants: Single { index: 0, }, + max_repr_align: None, + unadjusted_abi_align: Align(1 bytes), }, ], }, + max_repr_align: None, + unadjusted_abi_align: Align(1 bytes), } --> $DIR/thumb-enum.rs:20:1 | @@ -199,9 +207,13 @@ error: layout_of(C) = Layout { variants: Single { index: 0, }, + max_repr_align: None, + unadjusted_abi_align: Align(2 bytes), }, ], }, + max_repr_align: None, + unadjusted_abi_align: Align(2 bytes), } --> $DIR/thumb-enum.rs:24:1 | @@ -269,9 +281,13 @@ error: layout_of(P) = Layout { variants: Single { index: 0, }, + max_repr_align: None, + unadjusted_abi_align: Align(4 bytes), }, ], }, + max_repr_align: None, + unadjusted_abi_align: Align(4 bytes), } --> $DIR/thumb-enum.rs:28:1 | @@ -339,9 +355,13 @@ error: layout_of(T) = Layout { variants: Single { index: 0, }, + max_repr_align: None, + unadjusted_abi_align: Align(4 bytes), }, ], }, + max_repr_align: None, + unadjusted_abi_align: Align(4 bytes), } --> $DIR/thumb-enum.rs:34:1 | diff --git a/tests/ui/layout/zero-sized-array-enum-niche.stderr b/tests/ui/layout/zero-sized-array-enum-niche.stderr index a3e82070e0f..df9f1cc8d10 100644 --- a/tests/ui/layout/zero-sized-array-enum-niche.stderr +++ b/tests/ui/layout/zero-sized-array-enum-niche.stderr @@ -57,6 +57,8 @@ error: layout_of(std::result::Result<[u32; 0], bool>) = Layout { variants: Single { index: 0, }, + max_repr_align: None, + unadjusted_abi_align: Align(4 bytes), }, Layout { size: Size(2 bytes), @@ -88,9 +90,13 @@ error: layout_of(std::result::Result<[u32; 0], bool>) = Layout { variants: Single { index: 1, }, + max_repr_align: None, + unadjusted_abi_align: Align(1 bytes), }, ], }, + max_repr_align: None, + unadjusted_abi_align: Align(4 bytes), } --> $DIR/zero-sized-array-enum-niche.rs:13:1 | @@ -156,6 +162,8 @@ error: layout_of(MultipleAlignments) = Layout { variants: Single { index: 0, }, + max_repr_align: None, + unadjusted_abi_align: Align(2 bytes), }, Layout { size: Size(4 bytes), @@ -178,6 +186,8 @@ error: layout_of(MultipleAlignments) = Layout { variants: Single { index: 1, }, + max_repr_align: None, + unadjusted_abi_align: Align(4 bytes), }, Layout { size: Size(2 bytes), @@ -209,9 +219,13 @@ error: layout_of(MultipleAlignments) = Layout { variants: Single { index: 2, }, + max_repr_align: None, + unadjusted_abi_align: Align(1 bytes), }, ], }, + max_repr_align: None, + unadjusted_abi_align: Align(4 bytes), } --> $DIR/zero-sized-array-enum-niche.rs:21:1 | @@ -277,6 +291,8 @@ error: layout_of(std::result::Result<[u32; 0], Packed<std::num::NonZeroU16>>) = variants: Single { index: 0, }, + max_repr_align: None, + unadjusted_abi_align: Align(4 bytes), }, Layout { size: Size(3 bytes), @@ -308,9 +324,13 @@ error: layout_of(std::result::Result<[u32; 0], Packed<std::num::NonZeroU16>>) = variants: Single { index: 1, }, + max_repr_align: None, + unadjusted_abi_align: Align(1 bytes), }, ], }, + max_repr_align: None, + unadjusted_abi_align: Align(4 bytes), } --> $DIR/zero-sized-array-enum-niche.rs:37:1 | @@ -380,6 +400,8 @@ error: layout_of(std::result::Result<[u32; 0], Packed<U16IsZero>>) = Layout { variants: Single { index: 0, }, + max_repr_align: None, + unadjusted_abi_align: Align(4 bytes), }, Layout { size: Size(2 bytes), @@ -411,9 +433,13 @@ error: layout_of(std::result::Result<[u32; 0], Packed<U16IsZero>>) = Layout { variants: Single { index: 1, }, + max_repr_align: None, + unadjusted_abi_align: Align(1 bytes), }, ], }, + max_repr_align: None, + unadjusted_abi_align: Align(4 bytes), } --> $DIR/zero-sized-array-enum-niche.rs:44:1 | diff --git a/tests/ui/lifetimes/borrowck-let-suggestion.stderr b/tests/ui/lifetimes/borrowck-let-suggestion.stderr index 987b051b111..38fd92d7619 100644 --- a/tests/ui/lifetimes/borrowck-let-suggestion.stderr +++ b/tests/ui/lifetimes/borrowck-let-suggestion.stderr @@ -7,7 +7,7 @@ LL | let mut x = vec![1].iter(); | creates a temporary value which is freed while still in use LL | LL | x.use_mut(); - | ----------- borrow later used here + | - borrow later used here | = note: consider using a `let` binding to create a longer lived value = note: this error originates in the macro `vec` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/tests/ui/lifetimes/lifetime-errors/ex3-both-anon-regions-using-fn-items.stderr b/tests/ui/lifetimes/lifetime-errors/ex3-both-anon-regions-using-fn-items.stderr index cc2447b1877..cb629d2e3d3 100644 --- a/tests/ui/lifetimes/lifetime-errors/ex3-both-anon-regions-using-fn-items.stderr +++ b/tests/ui/lifetimes/lifetime-errors/ex3-both-anon-regions-using-fn-items.stderr @@ -1,3 +1,14 @@ +error[E0596]: cannot borrow `y` as mutable, as it is not declared as mutable + --> $DIR/ex3-both-anon-regions-using-fn-items.rs:2:3 + | +LL | y.push(z); + | ^ cannot borrow as mutable + | +help: consider changing this to be mutable + | +LL | fn foo(x:fn(&u8, &u8), mut y: Vec<&u8>, z: &u8) { + | +++ + error: lifetime may not live long enough --> $DIR/ex3-both-anon-regions-using-fn-items.rs:2:3 | @@ -13,17 +24,6 @@ help: consider introducing a named lifetime parameter LL | fn foo<'a>(x:fn(&u8, &u8), y: Vec<&'a u8>, z: &'a u8) { | ++++ ++ ++ -error[E0596]: cannot borrow `y` as mutable, as it is not declared as mutable - --> $DIR/ex3-both-anon-regions-using-fn-items.rs:2:3 - | -LL | y.push(z); - | ^^^^^^^^^ cannot borrow as mutable - | -help: consider changing this to be mutable - | -LL | fn foo(x:fn(&u8, &u8), mut y: Vec<&u8>, z: &u8) { - | +++ - error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0596`. diff --git a/tests/ui/lifetimes/lifetime-errors/ex3-both-anon-regions-using-trait-objects.stderr b/tests/ui/lifetimes/lifetime-errors/ex3-both-anon-regions-using-trait-objects.stderr index 2ba5afa808d..05f9308124b 100644 --- a/tests/ui/lifetimes/lifetime-errors/ex3-both-anon-regions-using-trait-objects.stderr +++ b/tests/ui/lifetimes/lifetime-errors/ex3-both-anon-regions-using-trait-objects.stderr @@ -1,3 +1,14 @@ +error[E0596]: cannot borrow `y` as mutable, as it is not declared as mutable + --> $DIR/ex3-both-anon-regions-using-trait-objects.rs:2:3 + | +LL | y.push(z); + | ^ cannot borrow as mutable + | +help: consider changing this to be mutable + | +LL | fn foo(x:Box<dyn Fn(&u8, &u8)> , mut y: Vec<&u8>, z: &u8) { + | +++ + error: lifetime may not live long enough --> $DIR/ex3-both-anon-regions-using-trait-objects.rs:2:3 | @@ -13,17 +24,6 @@ help: consider introducing a named lifetime parameter LL | fn foo<'a>(x:Box<dyn Fn(&u8, &u8)> , y: Vec<&'a u8>, z: &'a u8) { | ++++ ++ ++ -error[E0596]: cannot borrow `y` as mutable, as it is not declared as mutable - --> $DIR/ex3-both-anon-regions-using-trait-objects.rs:2:3 - | -LL | y.push(z); - | ^^^^^^^^^ cannot borrow as mutable - | -help: consider changing this to be mutable - | -LL | fn foo(x:Box<dyn Fn(&u8, &u8)> , mut y: Vec<&u8>, z: &u8) { - | +++ - error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0596`. diff --git a/tests/ui/lint/lint-qualification.stderr b/tests/ui/lint/lint-qualification.stderr index 149a782d97c..d09cb78c4f0 100644 --- a/tests/ui/lint/lint-qualification.stderr +++ b/tests/ui/lint/lint-qualification.stderr @@ -9,6 +9,10 @@ note: the lint level is defined here | LL | #![deny(unused_qualifications)] | ^^^^^^^^^^^^^^^^^^^^^ +help: replace it with the unqualified path + | +LL | bar(); + | ~~~ error: aborting due to previous error diff --git a/tests/ui/lint/unaligned_references.stderr b/tests/ui/lint/unaligned_references.stderr index 5f9cecadbff..d3abc37669f 100644 --- a/tests/ui/lint/unaligned_references.stderr +++ b/tests/ui/lint/unaligned_references.stderr @@ -52,7 +52,7 @@ error[E0793]: reference to packed field is unaligned --> $DIR/unaligned_references.rs:40:17 | LL | let _ = good.data.clone(); - | ^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^ | = note: packed structs are only aligned by one byte, and many modern architectures penalize unaligned field accesses = note: creating a misaligned reference is undefined behavior (even if that reference is never dereferenced) diff --git a/tests/ui/liveness/liveness-move-call-arg-2.rs b/tests/ui/liveness/liveness-move-call-arg-2.rs new file mode 100644 index 00000000000..b93535c89b1 --- /dev/null +++ b/tests/ui/liveness/liveness-move-call-arg-2.rs @@ -0,0 +1,12 @@ +fn take(_x: Box<isize>) {} + + +fn main() { + let _ = || { + let x: Box<isize> = Box::new(25); + + loop { + take(x); //~ ERROR use of moved value: `x` + } + }; +} diff --git a/tests/ui/liveness/liveness-move-call-arg-2.stderr b/tests/ui/liveness/liveness-move-call-arg-2.stderr new file mode 100644 index 00000000000..479a086a80c --- /dev/null +++ b/tests/ui/liveness/liveness-move-call-arg-2.stderr @@ -0,0 +1,26 @@ +error[E0382]: use of moved value: `x` + --> $DIR/liveness-move-call-arg-2.rs:9:18 + | +LL | let x: Box<isize> = Box::new(25); + | - move occurs because `x` has type `Box<isize>`, which does not implement the `Copy` trait +LL | +LL | loop { + | ---- inside of this loop +LL | take(x); + | ^ value moved here, in previous iteration of loop + | +note: consider changing this parameter type in function `take` to borrow instead if owning the value isn't necessary + --> $DIR/liveness-move-call-arg-2.rs:1:13 + | +LL | fn take(_x: Box<isize>) {} + | ---- ^^^^^^^^^^ this parameter takes ownership of the value + | | + | in this function +help: consider cloning the value if the performance cost is acceptable + | +LL | take(x.clone()); + | ++++++++ + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0382`. diff --git a/tests/ui/macros/format-args-temporaries-in-write.stderr b/tests/ui/macros/format-args-temporaries-in-write.stderr index 520b2ce5052..e05246cfbe3 100644 --- a/tests/ui/macros/format-args-temporaries-in-write.stderr +++ b/tests/ui/macros/format-args-temporaries-in-write.stderr @@ -4,7 +4,7 @@ error[E0597]: `mutex` does not live long enough LL | let mutex = Mutex; | ----- binding `mutex` declared here LL | write!(Out, "{}", mutex.lock()) /* no semicolon */ - | ^^^^^^^^^^^^ + | ^^^^^------- | | | borrowed value does not live long enough | a temporary with access to the borrow is created here ... @@ -21,7 +21,7 @@ error[E0597]: `mutex` does not live long enough LL | let mutex = Mutex; | ----- binding `mutex` declared here LL | writeln!(Out, "{}", mutex.lock()) /* no semicolon */ - | ^^^^^^^^^^^^ + | ^^^^^------- | | | borrowed value does not live long enough | a temporary with access to the borrow is created here ... diff --git a/tests/ui/macros/issue-19163.stderr b/tests/ui/macros/issue-19163.stderr index ae1ae14266f..af509aa59d4 100644 --- a/tests/ui/macros/issue-19163.stderr +++ b/tests/ui/macros/issue-19163.stderr @@ -1,10 +1,8 @@ error[E0596]: cannot borrow data in a `&` reference as mutable - --> $DIR/issue-19163.rs:9:5 + --> $DIR/issue-19163.rs:9:14 | LL | mywrite!(&v, "Hello world"); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot borrow as mutable - | - = note: this error originates in the macro `mywrite` (in Nightly builds, run with -Z macro-backtrace for more info) + | ^^ cannot borrow as mutable error: aborting due to previous error diff --git a/tests/ui/match/issue-74050-end-span.stderr b/tests/ui/match/issue-74050-end-span.stderr index 0b3425f2b1a..0dafeae870e 100644 --- a/tests/ui/match/issue-74050-end-span.stderr +++ b/tests/ui/match/issue-74050-end-span.stderr @@ -6,7 +6,7 @@ LL | let _arg = match args.next() { LL | Some(arg) => { | --- binding `arg` declared here LL | match arg.to_str() { - | ^^^^^^^^^^^^ borrowed value does not live long enough + | ^^^ borrowed value does not live long enough ... LL | } | - `arg` dropped here while still borrowed diff --git a/tests/ui/methods/method-self-arg-2.stderr b/tests/ui/methods/method-self-arg-2.stderr index b98f7a78661..946e71ee5b9 100644 --- a/tests/ui/methods/method-self-arg-2.stderr +++ b/tests/ui/methods/method-self-arg-2.stderr @@ -6,7 +6,7 @@ LL | let y = &mut x; LL | Foo::bar(&x); | ^^ immutable borrow occurs here LL | y.use_mut(); - | ----------- mutable borrow later used here + | - mutable borrow later used here error[E0499]: cannot borrow `x` as mutable more than once at a time --> $DIR/method-self-arg-2.rs:20:14 @@ -16,7 +16,7 @@ LL | let y = &mut x; LL | Foo::baz(&mut x); | ^^^^^^ second mutable borrow occurs here LL | y.use_mut(); - | ----------- first borrow later used here + | - first borrow later used here error: aborting due to 2 previous errors diff --git a/tests/ui/moves/move-fn-self-receiver.stderr b/tests/ui/moves/move-fn-self-receiver.stderr index 91d237b1d1a..c91a8b5efac 100644 --- a/tests/ui/moves/move-fn-self-receiver.stderr +++ b/tests/ui/moves/move-fn-self-receiver.stderr @@ -12,7 +12,7 @@ note: `into_iter` takes ownership of the receiver `self`, which moves `val.0` help: you can `clone` the value and consume it, but this might not be your desired behavior | LL | val.0.clone().into_iter().next(); - | ++++++++ + | ++++++++ error[E0382]: use of moved value: `foo` --> $DIR/move-fn-self-receiver.rs:34:5 @@ -78,7 +78,7 @@ error[E0505]: cannot move out of `mut_foo` because it is borrowed LL | let mut mut_foo = Foo; | ----------- binding `mut_foo` declared here LL | let ret = mut_foo.use_mut_self(); - | ---------------------- borrow of `mut_foo` occurs here + | ------- borrow of `mut_foo` occurs here LL | mut_foo; | ^^^^^^^ move out of `mut_foo` occurs here LL | ret; @@ -102,7 +102,7 @@ LL | fn use_rc_self(self: Rc<Self>) {} help: you can `clone` the value and consume it, but this might not be your desired behavior | LL | rc_foo.clone().use_rc_self(); - | ++++++++ + | ++++++++ error[E0382]: use of moved value: `foo_add` --> $DIR/move-fn-self-receiver.rs:59:5 @@ -145,7 +145,7 @@ LL | explicit_into_iter; help: you can `clone` the value and consume it, but this might not be your desired behavior | LL | for _val in explicit_into_iter.clone().into_iter() {} - | ++++++++ + | ++++++++ error[E0382]: use of moved value: `container` --> $DIR/move-fn-self-receiver.rs:71:5 diff --git a/tests/ui/moves/moves-based-on-type-access-to-field.stderr b/tests/ui/moves/moves-based-on-type-access-to-field.stderr index a28f324aafa..73901866396 100644 --- a/tests/ui/moves/moves-based-on-type-access-to-field.stderr +++ b/tests/ui/moves/moves-based-on-type-access-to-field.stderr @@ -13,7 +13,7 @@ note: `into_iter` takes ownership of the receiver `self`, which moves `x` help: you can `clone` the value and consume it, but this might not be your desired behavior | LL | consume(x.clone().into_iter().next().unwrap()); - | ++++++++ + | ++++++++ error: aborting due to previous error diff --git a/tests/ui/moves/moves-based-on-type-exprs.stderr b/tests/ui/moves/moves-based-on-type-exprs.stderr index ab7c2745688..45f7d4063a5 100644 --- a/tests/ui/moves/moves-based-on-type-exprs.stderr +++ b/tests/ui/moves/moves-based-on-type-exprs.stderr @@ -165,7 +165,7 @@ note: `into_iter` takes ownership of the receiver `self`, which moves `x` help: you can `clone` the value and consume it, but this might not be your desired behavior | LL | let _y = x.clone().into_iter().next().unwrap(); - | ++++++++ + | ++++++++ error[E0382]: borrow of moved value: `x` --> $DIR/moves-based-on-type-exprs.rs:83:11 @@ -182,7 +182,7 @@ note: `into_iter` takes ownership of the receiver `self`, which moves `x` help: you can `clone` the value and consume it, but this might not be your desired behavior | LL | let _y = [x.clone().into_iter().next().unwrap(); 1]; - | ++++++++ + | ++++++++ error: aborting due to 11 previous errors diff --git a/tests/ui/moves/pin-mut-reborrow-infer-var-issue-107419.stderr b/tests/ui/moves/pin-mut-reborrow-infer-var-issue-107419.stderr index 7e513b73c21..a184482a446 100644 --- a/tests/ui/moves/pin-mut-reborrow-infer-var-issue-107419.stderr +++ b/tests/ui/moves/pin-mut-reborrow-infer-var-issue-107419.stderr @@ -13,7 +13,7 @@ note: `Pin::<&'a mut T>::get_mut` takes ownership of the receiver `self`, which help: consider reborrowing the `Pin` instead of moving it | LL | foo(r.as_mut().get_mut()); - | +++++++++ + | +++++++++ error: aborting due to previous error diff --git a/tests/ui/moves/pin-mut-reborrow.stderr b/tests/ui/moves/pin-mut-reborrow.stderr index 16fa4bacc2d..4bf207e7e98 100644 --- a/tests/ui/moves/pin-mut-reborrow.stderr +++ b/tests/ui/moves/pin-mut-reborrow.stderr @@ -16,7 +16,7 @@ LL | fn foo(self: Pin<&mut Self>) {} help: consider reborrowing the `Pin` instead of moving it | LL | foo.as_mut().foo(); - | +++++++++ + | +++++++++ error: aborting due to previous error diff --git a/tests/ui/moves/suggest-clone.stderr b/tests/ui/moves/suggest-clone.stderr index cbb3dfea3ba..065acf904a4 100644 --- a/tests/ui/moves/suggest-clone.stderr +++ b/tests/ui/moves/suggest-clone.stderr @@ -2,9 +2,8 @@ error[E0507]: cannot move out of `*foo` which is behind a shared reference --> $DIR/suggest-clone.rs:10:5 | LL | foo.foo(); - | ^^^^----- - | | | - | | `*foo` moved due to this method call + | ^^^ ----- `*foo` moved due to this method call + | | | move occurs because `*foo` has type `Foo`, which does not implement the `Copy` trait | note: `Foo::foo` takes ownership of the receiver `self`, which moves `*foo` @@ -15,7 +14,7 @@ LL | fn foo(self) {} help: you can `clone` the value and consume it, but this might not be your desired behavior | LL | foo.clone().foo(); - | ++++++++ + | ++++++++ error: aborting due to previous error diff --git a/tests/ui/mut/mut-cant-alias.stderr b/tests/ui/mut/mut-cant-alias.stderr index 6046c076f2e..d56e45db13d 100644 --- a/tests/ui/mut/mut-cant-alias.stderr +++ b/tests/ui/mut/mut-cant-alias.stderr @@ -6,7 +6,7 @@ LL | let b1 = &mut *b; LL | let b2 = &mut *b; | ^ second mutable borrow occurs here LL | b1.use_mut(); - | ------------ first borrow later used here + | -- first borrow later used here error: aborting due to previous error diff --git a/tests/ui/mut/mut-suggestion.stderr b/tests/ui/mut/mut-suggestion.stderr index d89c8b41304..1521ae4c5ea 100644 --- a/tests/ui/mut/mut-suggestion.stderr +++ b/tests/ui/mut/mut-suggestion.stderr @@ -2,7 +2,7 @@ error[E0596]: cannot borrow `arg` as mutable, as it is not declared as mutable --> $DIR/mut-suggestion.rs:12:5 | LL | arg.mutate(); - | ^^^^^^^^^^^^ cannot borrow as mutable + | ^^^ cannot borrow as mutable | help: consider changing this to be mutable | @@ -13,7 +13,7 @@ error[E0596]: cannot borrow `local` as mutable, as it is not declared as mutable --> $DIR/mut-suggestion.rs:20:5 | LL | local.mutate(); - | ^^^^^^^^^^^^^^ cannot borrow as mutable + | ^^^^^ cannot borrow as mutable | help: consider changing this to be mutable | diff --git a/tests/ui/nll/closure-access-spans.stderr b/tests/ui/nll/closure-access-spans.stderr index 035dd5a5610..3e98fbd5e1d 100644 --- a/tests/ui/nll/closure-access-spans.stderr +++ b/tests/ui/nll/closure-access-spans.stderr @@ -8,7 +8,7 @@ LL | || x; | | | immutable borrow occurs here LL | r.use_mut(); - | ----------- mutable borrow later used here + | - mutable borrow later used here error[E0499]: cannot borrow `x` as mutable more than once at a time --> $DIR/closure-access-spans.rs:11:5 @@ -20,7 +20,7 @@ LL | || x = 2; | | | second mutable borrow occurs here LL | r.use_mut(); - | ----------- first borrow later used here + | - first borrow later used here error[E0500]: closure requires unique access to `x` but it is already borrowed --> $DIR/closure-access-spans.rs:17:5 @@ -32,7 +32,7 @@ LL | || *x = 2; | | | closure construction occurs here LL | r.use_mut(); - | ----------- first borrow later used here + | - first borrow later used here error[E0503]: cannot use `x` because it was mutably borrowed --> $DIR/closure-access-spans.rs:23:13 @@ -42,7 +42,7 @@ LL | let r = &mut x; LL | move || x; | ^ use of borrowed `x` LL | r.use_ref(); - | ----------- borrow later used here + | - borrow later used here error[E0505]: cannot move out of `x` because it is borrowed --> $DIR/closure-access-spans.rs:29:5 @@ -56,7 +56,7 @@ LL | || x; | | | move out of `x` occurs here LL | r.use_ref(); - | ----------- borrow later used here + | - borrow later used here error[E0382]: borrow of moved value: `x` --> $DIR/closure-access-spans.rs:35:5 diff --git a/tests/ui/nll/closure-borrow-spans.stderr b/tests/ui/nll/closure-borrow-spans.stderr index cf0df5834cc..cac22c2ecda 100644 --- a/tests/ui/nll/closure-borrow-spans.stderr +++ b/tests/ui/nll/closure-borrow-spans.stderr @@ -8,7 +8,7 @@ LL | let f = || x.len(); LL | let y = x; | ^ move out of `x` occurs here LL | f.use_ref(); - | ----------- borrow later used here + | - borrow later used here error[E0502]: cannot borrow `x` as mutable because it is also borrowed as immutable --> $DIR/closure-borrow-spans.rs:11:13 @@ -20,7 +20,7 @@ LL | let f = || x; LL | let y = &mut x; | ^^^^^^ mutable borrow occurs here LL | f.use_ref(); - | ----------- immutable borrow later used here + | - immutable borrow later used here error[E0597]: `x` does not live long enough --> $DIR/closure-borrow-spans.rs:19:16 @@ -32,7 +32,7 @@ LL | f = || x; LL | } | - `x` dropped here while still borrowed LL | f.use_ref(); - | ----------- borrow later used here + | - borrow later used here error[E0506]: cannot assign to `x` because it is borrowed --> $DIR/closure-borrow-spans.rs:26:5 @@ -44,7 +44,7 @@ LL | let f = || x; LL | x = 1; | ^^^^^ `x` is assigned to here but it was already borrowed LL | f.use_ref(); - | ----------- borrow later used here + | - borrow later used here error[E0503]: cannot use `x` because it was mutably borrowed --> $DIR/closure-borrow-spans.rs:32:13 @@ -56,7 +56,7 @@ LL | let f = || x = 0; LL | let y = x; | ^ use of borrowed `x` LL | f.use_ref(); - | ----------- borrow later used here + | - borrow later used here error[E0502]: cannot borrow `x` as immutable because it is also borrowed as mutable --> $DIR/closure-borrow-spans.rs:38:13 @@ -68,7 +68,7 @@ LL | let f = || x = 0; LL | let y = &x; | ^^ immutable borrow occurs here LL | f.use_ref(); - | ----------- mutable borrow later used here + | - mutable borrow later used here error[E0499]: cannot borrow `x` as mutable more than once at a time --> $DIR/closure-borrow-spans.rs:44:13 @@ -80,7 +80,7 @@ LL | let f = || x = 0; LL | let y = &mut x; | ^^^^^^ second mutable borrow occurs here LL | f.use_ref(); - | ----------- first borrow later used here + | - first borrow later used here error[E0597]: `x` does not live long enough --> $DIR/closure-borrow-spans.rs:52:16 @@ -92,7 +92,7 @@ LL | f = || x = 0; LL | } | - `x` dropped here while still borrowed LL | f.use_ref(); - | ----------- borrow later used here + | - borrow later used here error[E0506]: cannot assign to `x` because it is borrowed --> $DIR/closure-borrow-spans.rs:59:5 @@ -104,7 +104,7 @@ LL | let f = || x = 0; LL | x = 1; | ^^^^^ `x` is assigned to here but it was already borrowed LL | f.use_ref(); - | ----------- borrow later used here + | - borrow later used here error[E0505]: cannot move out of `x` because it is borrowed --> $DIR/closure-borrow-spans.rs:65:13 @@ -116,7 +116,7 @@ LL | let f = || *x = 0; LL | let y = x; | ^ move out of `x` occurs here LL | f.use_ref(); - | ----------- borrow later used here + | - borrow later used here error[E0501]: cannot borrow `x` as immutable because previous closure requires unique access --> $DIR/closure-borrow-spans.rs:71:13 @@ -128,7 +128,7 @@ LL | let f = || *x = 0; LL | let y = &x; | ^^ second borrow occurs here LL | f.use_ref(); - | ----------- first borrow later used here + | - first borrow later used here error[E0501]: cannot borrow `x` as mutable because previous closure requires unique access --> $DIR/closure-borrow-spans.rs:77:13 @@ -140,7 +140,7 @@ LL | let f = || *x = 0; LL | let y = &mut x; | ^^^^^^ second borrow occurs here LL | f.use_ref(); - | ----------- first borrow later used here + | - first borrow later used here error[E0597]: `x` does not live long enough --> $DIR/closure-borrow-spans.rs:86:16 @@ -152,7 +152,7 @@ LL | f = || *x = 0; LL | } | - `x` dropped here while still borrowed LL | f.use_ref(); - | ----------- borrow later used here + | - borrow later used here error[E0506]: cannot assign to `*x` because it is borrowed --> $DIR/closure-borrow-spans.rs:93:5 @@ -164,7 +164,7 @@ LL | let f = || *x = 0; LL | *x = 1; | ^^^^^^ `*x` is assigned to here but it was already borrowed LL | f.use_ref(); - | ----------- borrow later used here + | - borrow later used here error: aborting due to 14 previous errors diff --git a/tests/ui/nll/closure-requirements/escape-argument-callee.stderr b/tests/ui/nll/closure-requirements/escape-argument-callee.stderr index 61233fd8407..1e3a5328d3d 100644 --- a/tests/ui/nll/closure-requirements/escape-argument-callee.stderr +++ b/tests/ui/nll/closure-requirements/escape-argument-callee.stderr @@ -4,7 +4,7 @@ note: no external requirements LL | let mut closure = expect_sig(|p, y| *p = y); | ^^^^^^ | - = note: defining type: test::{closure#0} with closure substs [ + = note: defining type: test::{closure#0} with closure args [ i16, for<Region(BrAnon(None)), Region(BrAnon(None)), Region(BrAnon(None))> extern "rust-call" fn((&ReLateBound(DebruijnIndex(0), BoundRegion { var: 0, kind: BrAnon(None) }) mut &ReLateBound(DebruijnIndex(0), BoundRegion { var: 1, kind: BrAnon(None) }) i32, &ReLateBound(DebruijnIndex(0), BoundRegion { var: 2, kind: BrAnon(None) }) i32)), (), diff --git a/tests/ui/nll/closure-requirements/escape-argument.stderr b/tests/ui/nll/closure-requirements/escape-argument.stderr index 61e2a1ea6f0..bc4ba93f884 100644 --- a/tests/ui/nll/closure-requirements/escape-argument.stderr +++ b/tests/ui/nll/closure-requirements/escape-argument.stderr @@ -4,7 +4,7 @@ note: no external requirements LL | let mut closure = expect_sig(|p, y| *p = y); | ^^^^^^ | - = note: defining type: test::{closure#0} with closure substs [ + = note: defining type: test::{closure#0} with closure args [ i16, for<Region(BrAnon(None)), Region(BrAnon(None))> extern "rust-call" fn((&ReLateBound(DebruijnIndex(0), BoundRegion { var: 0, kind: BrAnon(None) }) mut &ReLateBound(DebruijnIndex(0), BoundRegion { var: 1, kind: BrAnon(None) }) i32, &ReLateBound(DebruijnIndex(0), BoundRegion { var: 1, kind: BrAnon(None) }) i32)), (), diff --git a/tests/ui/nll/closure-requirements/escape-upvar-nested.stderr b/tests/ui/nll/closure-requirements/escape-upvar-nested.stderr index c00a31ef8e1..727df1cf890 100644 --- a/tests/ui/nll/closure-requirements/escape-upvar-nested.stderr +++ b/tests/ui/nll/closure-requirements/escape-upvar-nested.stderr @@ -4,7 +4,7 @@ note: external requirements LL | let mut closure1 = || p = &y; | ^^ | - = note: defining type: test::{closure#0}::{closure#0} with closure substs [ + = note: defining type: test::{closure#0}::{closure#0} with closure args [ i16, extern "rust-call" fn(()), (&'?1 mut &'?2 i32, &'?3 i32), @@ -18,7 +18,7 @@ note: external requirements LL | let mut closure = || { | ^^ | - = note: defining type: test::{closure#0} with closure substs [ + = note: defining type: test::{closure#0} with closure args [ i16, extern "rust-call" fn(()), (&'?1 mut &'?2 i32, &'?3 i32), diff --git a/tests/ui/nll/closure-requirements/escape-upvar-ref.stderr b/tests/ui/nll/closure-requirements/escape-upvar-ref.stderr index 2d67e6e7d72..ff638f2a1ec 100644 --- a/tests/ui/nll/closure-requirements/escape-upvar-ref.stderr +++ b/tests/ui/nll/closure-requirements/escape-upvar-ref.stderr @@ -4,7 +4,7 @@ note: external requirements LL | let mut closure = || p = &y; | ^^ | - = note: defining type: test::{closure#0} with closure substs [ + = note: defining type: test::{closure#0} with closure args [ i16, extern "rust-call" fn(()), (&'?1 mut &'?2 i32, &'?3 i32), diff --git a/tests/ui/nll/closure-requirements/propagate-approximated-fail-no-postdom.stderr b/tests/ui/nll/closure-requirements/propagate-approximated-fail-no-postdom.stderr index ba42576d403..f8383cc42a2 100644 --- a/tests/ui/nll/closure-requirements/propagate-approximated-fail-no-postdom.stderr +++ b/tests/ui/nll/closure-requirements/propagate-approximated-fail-no-postdom.stderr @@ -4,7 +4,7 @@ note: no external requirements LL | |_outlives1, _outlives2, _outlives3, x, y| { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | - = note: defining type: supply::{closure#0} with closure substs [ + = note: defining type: supply::{closure#0} with closure args [ i16, for<Region(BrAnon(None)), Region(BrAnon(None))> extern "rust-call" fn((std::cell::Cell<&'?1 &ReLateBound(DebruijnIndex(0), BoundRegion { var: 0, kind: BrAnon(None) }) u32>, std::cell::Cell<&'?2 &ReLateBound(DebruijnIndex(0), BoundRegion { var: 0, kind: BrAnon(None) }) u32>, std::cell::Cell<&ReLateBound(DebruijnIndex(0), BoundRegion { var: 1, kind: BrAnon(None) }) &'?3 u32>, std::cell::Cell<&ReLateBound(DebruijnIndex(0), BoundRegion { var: 0, kind: BrAnon(None) }) u32>, std::cell::Cell<&ReLateBound(DebruijnIndex(0), BoundRegion { var: 1, kind: BrAnon(None) }) u32>)), (), diff --git a/tests/ui/nll/closure-requirements/propagate-approximated-ref.stderr b/tests/ui/nll/closure-requirements/propagate-approximated-ref.stderr index 9dd6e02081f..113173d8f76 100644 --- a/tests/ui/nll/closure-requirements/propagate-approximated-ref.stderr +++ b/tests/ui/nll/closure-requirements/propagate-approximated-ref.stderr @@ -4,7 +4,7 @@ note: external requirements LL | establish_relationships(&cell_a, &cell_b, |_outlives1, _outlives2, x, y| { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | - = note: defining type: supply::{closure#0} with closure substs [ + = note: defining type: supply::{closure#0} with closure args [ i16, for<Region(BrAnon(None)), Region(BrAnon(None)), Region(BrAnon(None)), Region(BrAnon(None)), Region(BrAnon(None)), Region(BrAnon(None))> extern "rust-call" fn((&ReLateBound(DebruijnIndex(0), BoundRegion { var: 0, kind: BrAnon(None) }) std::cell::Cell<&'?1 &ReLateBound(DebruijnIndex(0), BoundRegion { var: 1, kind: BrAnon(None) }) u32>, &ReLateBound(DebruijnIndex(0), BoundRegion { var: 2, kind: BrAnon(None) }) std::cell::Cell<&ReLateBound(DebruijnIndex(0), BoundRegion { var: 3, kind: BrAnon(None) }) &'?2 u32>, &ReLateBound(DebruijnIndex(0), BoundRegion { var: 4, kind: BrAnon(None) }) std::cell::Cell<&ReLateBound(DebruijnIndex(0), BoundRegion { var: 1, kind: BrAnon(None) }) u32>, &ReLateBound(DebruijnIndex(0), BoundRegion { var: 5, kind: BrAnon(None) }) std::cell::Cell<&ReLateBound(DebruijnIndex(0), BoundRegion { var: 3, kind: BrAnon(None) }) u32>)), (), diff --git a/tests/ui/nll/closure-requirements/propagate-approximated-shorter-to-static-comparing-against-free.stderr b/tests/ui/nll/closure-requirements/propagate-approximated-shorter-to-static-comparing-against-free.stderr index e2f5576d395..ba15199ab5a 100644 --- a/tests/ui/nll/closure-requirements/propagate-approximated-shorter-to-static-comparing-against-free.stderr +++ b/tests/ui/nll/closure-requirements/propagate-approximated-shorter-to-static-comparing-against-free.stderr @@ -4,7 +4,7 @@ note: no external requirements LL | foo(cell, |cell_a, cell_x| { | ^^^^^^^^^^^^^^^^ | - = note: defining type: case1::{closure#0} with closure substs [ + = note: defining type: case1::{closure#0} with closure args [ i32, for<Region(BrAnon(None))> extern "rust-call" fn((std::cell::Cell<&'?1 u32>, std::cell::Cell<&ReLateBound(DebruijnIndex(0), BoundRegion { var: 0, kind: BrAnon(None) }) u32>)), (), @@ -34,7 +34,7 @@ note: external requirements LL | foo(cell, |cell_a, cell_x| { | ^^^^^^^^^^^^^^^^ | - = note: defining type: case2::{closure#0} with closure substs [ + = note: defining type: case2::{closure#0} with closure args [ i32, for<Region(BrAnon(None))> extern "rust-call" fn((std::cell::Cell<&'?1 u32>, std::cell::Cell<&ReLateBound(DebruijnIndex(0), BoundRegion { var: 0, kind: BrAnon(None) }) u32>)), (), diff --git a/tests/ui/nll/closure-requirements/propagate-approximated-shorter-to-static-no-bound.stderr b/tests/ui/nll/closure-requirements/propagate-approximated-shorter-to-static-no-bound.stderr index 383fb471ad3..f2bf83c6c59 100644 --- a/tests/ui/nll/closure-requirements/propagate-approximated-shorter-to-static-no-bound.stderr +++ b/tests/ui/nll/closure-requirements/propagate-approximated-shorter-to-static-no-bound.stderr @@ -4,7 +4,7 @@ note: external requirements LL | establish_relationships(&cell_a, &cell_b, |_outlives, x, y| { | ^^^^^^^^^^^^^^^^^ | - = note: defining type: supply::{closure#0} with closure substs [ + = note: defining type: supply::{closure#0} with closure args [ i16, for<Region(BrAnon(None)), Region(BrAnon(None)), Region(BrAnon(None)), Region(BrAnon(None)), Region(BrAnon(None))> extern "rust-call" fn((&ReLateBound(DebruijnIndex(0), BoundRegion { var: 0, kind: BrAnon(None) }) std::cell::Cell<&'?1 &ReLateBound(DebruijnIndex(0), BoundRegion { var: 1, kind: BrAnon(None) }) u32>, &ReLateBound(DebruijnIndex(0), BoundRegion { var: 2, kind: BrAnon(None) }) std::cell::Cell<&ReLateBound(DebruijnIndex(0), BoundRegion { var: 1, kind: BrAnon(None) }) u32>, &ReLateBound(DebruijnIndex(0), BoundRegion { var: 3, kind: BrAnon(None) }) std::cell::Cell<&ReLateBound(DebruijnIndex(0), BoundRegion { var: 4, kind: BrAnon(None) }) u32>)), (), diff --git a/tests/ui/nll/closure-requirements/propagate-approximated-shorter-to-static-wrong-bound.stderr b/tests/ui/nll/closure-requirements/propagate-approximated-shorter-to-static-wrong-bound.stderr index ac346c0b110..2734326ed64 100644 --- a/tests/ui/nll/closure-requirements/propagate-approximated-shorter-to-static-wrong-bound.stderr +++ b/tests/ui/nll/closure-requirements/propagate-approximated-shorter-to-static-wrong-bound.stderr @@ -4,7 +4,7 @@ note: external requirements LL | establish_relationships(&cell_a, &cell_b, |_outlives1, _outlives2, x, y| { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | - = note: defining type: supply::{closure#0} with closure substs [ + = note: defining type: supply::{closure#0} with closure args [ i16, for<Region(BrAnon(None)), Region(BrAnon(None)), Region(BrAnon(None)), Region(BrAnon(None)), Region(BrAnon(None)), Region(BrAnon(None))> extern "rust-call" fn((&ReLateBound(DebruijnIndex(0), BoundRegion { var: 0, kind: BrAnon(None) }) std::cell::Cell<&'?1 &ReLateBound(DebruijnIndex(0), BoundRegion { var: 1, kind: BrAnon(None) }) u32>, &ReLateBound(DebruijnIndex(0), BoundRegion { var: 2, kind: BrAnon(None) }) std::cell::Cell<&'?2 &ReLateBound(DebruijnIndex(0), BoundRegion { var: 3, kind: BrAnon(None) }) u32>, &ReLateBound(DebruijnIndex(0), BoundRegion { var: 4, kind: BrAnon(None) }) std::cell::Cell<&ReLateBound(DebruijnIndex(0), BoundRegion { var: 1, kind: BrAnon(None) }) u32>, &ReLateBound(DebruijnIndex(0), BoundRegion { var: 5, kind: BrAnon(None) }) std::cell::Cell<&ReLateBound(DebruijnIndex(0), BoundRegion { var: 3, kind: BrAnon(None) }) u32>)), (), diff --git a/tests/ui/nll/closure-requirements/propagate-approximated-val.stderr b/tests/ui/nll/closure-requirements/propagate-approximated-val.stderr index b217ae19773..5ab321eb666 100644 --- a/tests/ui/nll/closure-requirements/propagate-approximated-val.stderr +++ b/tests/ui/nll/closure-requirements/propagate-approximated-val.stderr @@ -4,7 +4,7 @@ note: external requirements LL | establish_relationships(cell_a, cell_b, |outlives1, outlives2, x, y| { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | - = note: defining type: test::{closure#0} with closure substs [ + = note: defining type: test::{closure#0} with closure args [ i16, for<Region(BrAnon(None)), Region(BrAnon(None))> extern "rust-call" fn((std::cell::Cell<&'?1 &ReLateBound(DebruijnIndex(0), BoundRegion { var: 0, kind: BrAnon(None) }) u32>, std::cell::Cell<&ReLateBound(DebruijnIndex(0), BoundRegion { var: 1, kind: BrAnon(None) }) &'?2 u32>, std::cell::Cell<&ReLateBound(DebruijnIndex(0), BoundRegion { var: 0, kind: BrAnon(None) }) u32>, std::cell::Cell<&ReLateBound(DebruijnIndex(0), BoundRegion { var: 1, kind: BrAnon(None) }) u32>)), (), diff --git a/tests/ui/nll/closure-requirements/propagate-despite-same-free-region.stderr b/tests/ui/nll/closure-requirements/propagate-despite-same-free-region.stderr index f31478b6d1c..595fd5ff565 100644 --- a/tests/ui/nll/closure-requirements/propagate-despite-same-free-region.stderr +++ b/tests/ui/nll/closure-requirements/propagate-despite-same-free-region.stderr @@ -4,7 +4,7 @@ note: external requirements LL | |_outlives1, _outlives2, x, y| { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | - = note: defining type: supply::{closure#0} with closure substs [ + = note: defining type: supply::{closure#0} with closure args [ i16, for<Region(BrAnon(None)), Region(BrAnon(None))> extern "rust-call" fn((std::cell::Cell<&'?1 &ReLateBound(DebruijnIndex(0), BoundRegion { var: 0, kind: BrAnon(None) }) u32>, std::cell::Cell<&ReLateBound(DebruijnIndex(0), BoundRegion { var: 1, kind: BrAnon(None) }) &'?2 u32>, std::cell::Cell<&ReLateBound(DebruijnIndex(0), BoundRegion { var: 0, kind: BrAnon(None) }) u32>, std::cell::Cell<&ReLateBound(DebruijnIndex(0), BoundRegion { var: 1, kind: BrAnon(None) }) u32>)), (), diff --git a/tests/ui/nll/closure-requirements/propagate-fail-to-approximate-longer-no-bounds.stderr b/tests/ui/nll/closure-requirements/propagate-fail-to-approximate-longer-no-bounds.stderr index 1509ade87fa..62b0e3eed85 100644 --- a/tests/ui/nll/closure-requirements/propagate-fail-to-approximate-longer-no-bounds.stderr +++ b/tests/ui/nll/closure-requirements/propagate-fail-to-approximate-longer-no-bounds.stderr @@ -4,7 +4,7 @@ note: no external requirements LL | establish_relationships(&cell_a, &cell_b, |_outlives, x, y| { | ^^^^^^^^^^^^^^^^^ | - = note: defining type: supply::{closure#0} with closure substs [ + = note: defining type: supply::{closure#0} with closure args [ i16, for<Region(BrAnon(None)), Region(BrAnon(None)), Region(BrAnon(None)), Region(BrAnon(None)), Region(BrAnon(None))> extern "rust-call" fn((&ReLateBound(DebruijnIndex(0), BoundRegion { var: 0, kind: BrAnon(None) }) std::cell::Cell<&ReLateBound(DebruijnIndex(0), BoundRegion { var: 1, kind: BrAnon(None) }) &'?1 u32>, &ReLateBound(DebruijnIndex(0), BoundRegion { var: 2, kind: BrAnon(None) }) std::cell::Cell<&ReLateBound(DebruijnIndex(0), BoundRegion { var: 3, kind: BrAnon(None) }) u32>, &ReLateBound(DebruijnIndex(0), BoundRegion { var: 4, kind: BrAnon(None) }) std::cell::Cell<&ReLateBound(DebruijnIndex(0), BoundRegion { var: 1, kind: BrAnon(None) }) u32>)), (), diff --git a/tests/ui/nll/closure-requirements/propagate-fail-to-approximate-longer-wrong-bounds.stderr b/tests/ui/nll/closure-requirements/propagate-fail-to-approximate-longer-wrong-bounds.stderr index c85a9872e21..6f2044d621e 100644 --- a/tests/ui/nll/closure-requirements/propagate-fail-to-approximate-longer-wrong-bounds.stderr +++ b/tests/ui/nll/closure-requirements/propagate-fail-to-approximate-longer-wrong-bounds.stderr @@ -4,7 +4,7 @@ note: no external requirements LL | establish_relationships(&cell_a, &cell_b, |_outlives1, _outlives2, x, y| { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | - = note: defining type: supply::{closure#0} with closure substs [ + = note: defining type: supply::{closure#0} with closure args [ i16, for<Region(BrAnon(None)), Region(BrAnon(None)), Region(BrAnon(None)), Region(BrAnon(None)), Region(BrAnon(None)), Region(BrAnon(None))> extern "rust-call" fn((&ReLateBound(DebruijnIndex(0), BoundRegion { var: 0, kind: BrAnon(None) }) std::cell::Cell<&ReLateBound(DebruijnIndex(0), BoundRegion { var: 1, kind: BrAnon(None) }) &'?1 u32>, &ReLateBound(DebruijnIndex(0), BoundRegion { var: 2, kind: BrAnon(None) }) std::cell::Cell<&ReLateBound(DebruijnIndex(0), BoundRegion { var: 3, kind: BrAnon(None) }) &'?2 u32>, &ReLateBound(DebruijnIndex(0), BoundRegion { var: 4, kind: BrAnon(None) }) std::cell::Cell<&ReLateBound(DebruijnIndex(0), BoundRegion { var: 1, kind: BrAnon(None) }) u32>, &ReLateBound(DebruijnIndex(0), BoundRegion { var: 5, kind: BrAnon(None) }) std::cell::Cell<&ReLateBound(DebruijnIndex(0), BoundRegion { var: 3, kind: BrAnon(None) }) u32>)), (), diff --git a/tests/ui/nll/closure-requirements/propagate-from-trait-match.stderr b/tests/ui/nll/closure-requirements/propagate-from-trait-match.stderr index 05e274ab220..1aa7de1e137 100644 --- a/tests/ui/nll/closure-requirements/propagate-from-trait-match.stderr +++ b/tests/ui/nll/closure-requirements/propagate-from-trait-match.stderr @@ -4,7 +4,7 @@ note: external requirements LL | establish_relationships(value, |value| { | ^^^^^^^ | - = note: defining type: supply::<'?1, T>::{closure#0} with closure substs [ + = note: defining type: supply::<'?1, T>::{closure#0} with closure args [ i32, extern "rust-call" fn((T,)), (), diff --git a/tests/ui/nll/closure-requirements/return-wrong-bound-region.stderr b/tests/ui/nll/closure-requirements/return-wrong-bound-region.stderr index 4e34ba51659..7635f2ede0a 100644 --- a/tests/ui/nll/closure-requirements/return-wrong-bound-region.stderr +++ b/tests/ui/nll/closure-requirements/return-wrong-bound-region.stderr @@ -4,7 +4,7 @@ note: no external requirements LL | expect_sig(|a, b| b); // ought to return `a` | ^^^^^^ | - = note: defining type: test::{closure#0} with closure substs [ + = note: defining type: test::{closure#0} with closure args [ i16, for<Region(BrAnon(None)), Region(BrAnon(None))> extern "rust-call" fn((&ReLateBound(DebruijnIndex(0), BoundRegion { var: 0, kind: BrAnon(None) }) i32, &ReLateBound(DebruijnIndex(0), BoundRegion { var: 1, kind: BrAnon(None) }) i32)) -> &ReLateBound(DebruijnIndex(0), BoundRegion { var: 0, kind: BrAnon(None) }) i32, (), diff --git a/tests/ui/nll/closures-in-loops.stderr b/tests/ui/nll/closures-in-loops.stderr index 1c1a31d356d..2c1008c516c 100644 --- a/tests/ui/nll/closures-in-loops.stderr +++ b/tests/ui/nll/closures-in-loops.stderr @@ -13,9 +13,8 @@ error[E0499]: cannot borrow `x` as mutable more than once at a time --> $DIR/closures-in-loops.rs:13:16 | LL | v.push(|| x = String::new()); - | -------^^------------------- - | | | | - | | | borrows occur due to use of `x` in closure + | - ^^ - borrows occur due to use of `x` in closure + | | | | | `x` was mutably borrowed here in the previous iteration of the loop | first borrow used here, in later iteration of loop @@ -23,9 +22,8 @@ error[E0524]: two closures require unique access to `x` at the same time --> $DIR/closures-in-loops.rs:20:16 | LL | v.push(|| *x = String::new()); - | -------^^-------------------- - | | | | - | | | borrows occur due to use of `x` in closure + | - ^^ -- borrows occur due to use of `x` in closure + | | | | | closures are constructed here in different iterations of loop | first borrow used here, in later iteration of loop diff --git a/tests/ui/nll/get_default.stderr b/tests/ui/nll/get_default.stderr index 6998c04336e..af79771e7e1 100644 --- a/tests/ui/nll/get_default.stderr +++ b/tests/ui/nll/get_default.stderr @@ -5,7 +5,7 @@ LL | fn ok(map: &mut Map) -> &String { | - let's call the lifetime of this reference `'1` LL | loop { LL | match map.get() { - | --------- immutable borrow occurs here + | --- immutable borrow occurs here LL | Some(v) => { LL | return v; | - returning this value requires that `*map` is borrowed for `'1` @@ -20,7 +20,7 @@ LL | fn err(map: &mut Map) -> &String { | - let's call the lifetime of this reference `'1` LL | loop { LL | match map.get() { - | --------- immutable borrow occurs here + | --- immutable borrow occurs here LL | Some(v) => { LL | map.set(String::new()); // Both AST and MIR error here | ^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here @@ -35,7 +35,7 @@ LL | fn err(map: &mut Map) -> &String { | - let's call the lifetime of this reference `'1` LL | loop { LL | match map.get() { - | --------- immutable borrow occurs here + | --- immutable borrow occurs here ... LL | return v; | - returning this value requires that `*map` is borrowed for `'1` diff --git a/tests/ui/nll/issue-46589.stderr b/tests/ui/nll/issue-46589.stderr index 60ef3f7b85e..82cd364eeff 100644 --- a/tests/ui/nll/issue-46589.stderr +++ b/tests/ui/nll/issue-46589.stderr @@ -2,10 +2,10 @@ error[E0499]: cannot borrow `**other` as mutable more than once at a time --> $DIR/issue-46589.rs:23:21 | LL | *other = match (*other).get_self() { - | ------------------- first mutable borrow occurs here + | -------- first mutable borrow occurs here LL | Some(s) => s, LL | None => (*other).new_self() - | ^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^ | | | second mutable borrow occurs here | first borrow later used here diff --git a/tests/ui/nll/issue-51191.stderr b/tests/ui/nll/issue-51191.stderr index 27b1f8705ff..c14056c3a83 100644 --- a/tests/ui/nll/issue-51191.stderr +++ b/tests/ui/nll/issue-51191.stderr @@ -48,7 +48,7 @@ error[E0596]: cannot borrow data in a `&` reference as mutable --> $DIR/issue-51191.rs:22:9 | LL | (&mut self).bar(); - | ^^^^^^^^^^^^^^^^^ cannot borrow as mutable + | ^^^^^^^^^^^ cannot borrow as mutable error[E0596]: cannot borrow `self` as mutable, as it is not declared as mutable --> $DIR/issue-51191.rs:28:9 diff --git a/tests/ui/nll/issue-52669.stderr b/tests/ui/nll/issue-52669.stderr index 807b95f7e13..db53e444b9e 100644 --- a/tests/ui/nll/issue-52669.stderr +++ b/tests/ui/nll/issue-52669.stderr @@ -7,7 +7,7 @@ LL | a.b = B; LL | foo(a); | - value moved here LL | a.b.clone() - | ^^^^^^^^^^^ value borrowed here after move + | ^^^ value borrowed here after move error: aborting due to previous error diff --git a/tests/ui/nll/issue-53773.stderr b/tests/ui/nll/issue-53773.stderr index 90cba2a145f..fc185d42d5f 100644 --- a/tests/ui/nll/issue-53773.stderr +++ b/tests/ui/nll/issue-53773.stderr @@ -2,7 +2,9 @@ error[E0713]: borrow may still be in use when destructor runs --> $DIR/issue-53773.rs:41:22 | LL | members.push(child.raw); - | -------------^^^^^^^^^- borrow later used here + | ------- ^^^^^^^^^ + | | + | borrow later used here LL | LL | } | - here, drop of `child` needs exclusive access to `*child.raw`, because the type `C<'_>` implements the `Drop` trait diff --git a/tests/ui/nll/issue-54556-niconii.stderr b/tests/ui/nll/issue-54556-niconii.stderr index d41d462f2bc..ad0a2d1e324 100644 --- a/tests/ui/nll/issue-54556-niconii.stderr +++ b/tests/ui/nll/issue-54556-niconii.stderr @@ -5,7 +5,7 @@ LL | let counter = Mutex; | ------- binding `counter` declared here LL | LL | if let Ok(_) = counter.lock() { } - | ^^^^^^^^^^^^^^ + | ^^^^^^^------- | | | borrowed value does not live long enough | a temporary with access to the borrow is created here ... diff --git a/tests/ui/nll/issue-62007-assign-const-index.stderr b/tests/ui/nll/issue-62007-assign-const-index.stderr index 12e28aa3fba..0db9fe62c38 100644 --- a/tests/ui/nll/issue-62007-assign-const-index.stderr +++ b/tests/ui/nll/issue-62007-assign-const-index.stderr @@ -17,7 +17,7 @@ LL | fn to_refs<T>(mut list: [&mut List<T>; 2]) -> Vec<&mut T> { | - let's call the lifetime of this reference `'1` ... LL | if let Some(n) = list[0].next.as_mut() { - | ^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^--------- | | | `list[_].next` was mutably borrowed here in the previous iteration of the loop | argument requires that `list[_].next` is borrowed for `'1` diff --git a/tests/ui/nll/issue-62007-assign-differing-fields.stderr b/tests/ui/nll/issue-62007-assign-differing-fields.stderr index 4488431fc57..f1af2e855af 100644 --- a/tests/ui/nll/issue-62007-assign-differing-fields.stderr +++ b/tests/ui/nll/issue-62007-assign-differing-fields.stderr @@ -17,7 +17,7 @@ LL | fn to_refs<'a, T>(mut list: (&'a mut List<T>, &'a mut List<T>)) -> Vec<&'a | -- lifetime `'a` defined here ... LL | if let Some(n) = (list.0).next.as_mut() { - | ^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^--------- | | | `list.0.next` was mutably borrowed here in the previous iteration of the loop | argument requires that `list.0.next` is borrowed for `'a` diff --git a/tests/ui/nll/loan_ends_mid_block_vec.stderr b/tests/ui/nll/loan_ends_mid_block_vec.stderr index 22c72af61d6..c0b97bea348 100644 --- a/tests/ui/nll/loan_ends_mid_block_vec.stderr +++ b/tests/ui/nll/loan_ends_mid_block_vec.stderr @@ -5,7 +5,7 @@ LL | let slice = &mut data; | --------- first mutable borrow occurs here LL | capitalize(slice); LL | data.push('d'); - | ^^^^^^^^^^^^^^ second mutable borrow occurs here + | ^^^^ second mutable borrow occurs here ... LL | capitalize(slice); | ----- first borrow later used here @@ -17,7 +17,7 @@ LL | let slice = &mut data; | --------- first mutable borrow occurs here ... LL | data.push('e'); - | ^^^^^^^^^^^^^^ second mutable borrow occurs here + | ^^^^ second mutable borrow occurs here ... LL | capitalize(slice); | ----- first borrow later used here @@ -29,7 +29,7 @@ LL | let slice = &mut data; | --------- first mutable borrow occurs here ... LL | data.push('f'); - | ^^^^^^^^^^^^^^ second mutable borrow occurs here + | ^^^^ second mutable borrow occurs here LL | LL | capitalize(slice); | ----- first borrow later used here diff --git a/tests/ui/nll/polonius/assignment-to-differing-field.stderr b/tests/ui/nll/polonius/assignment-to-differing-field.stderr index afa1b934439..acac47eac4f 100644 --- a/tests/ui/nll/polonius/assignment-to-differing-field.stderr +++ b/tests/ui/nll/polonius/assignment-to-differing-field.stderr @@ -17,7 +17,7 @@ LL | fn assignment_to_field_projection<'a, T>( | -- lifetime `'a` defined here ... LL | if let Some(n) = (list.0).next.as_mut() { - | ^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^--------- | | | `list.0.next` was mutably borrowed here in the previous iteration of the loop | argument requires that `list.0.next` is borrowed for `'a` @@ -41,7 +41,7 @@ LL | fn assignment_through_projection_chain<'a, T>( | -- lifetime `'a` defined here ... LL | if let Some(n) = ((((list.0).0).0).0).0.next.as_mut() { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^--------- | | | `list.0.0.0.0.0.next` was mutably borrowed here in the previous iteration of the loop | argument requires that `list.0.0.0.0.0.next` is borrowed for `'a` diff --git a/tests/ui/nll/return_from_loop.stderr b/tests/ui/nll/return_from_loop.stderr index bd2b8b15859..efd56ea2dd5 100644 --- a/tests/ui/nll/return_from_loop.stderr +++ b/tests/ui/nll/return_from_loop.stderr @@ -5,10 +5,10 @@ LL | let value = &mut my_struct.field; | -------------------- first mutable borrow occurs here LL | loop { LL | my_struct.field.push_str("Hello, world!"); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ second mutable borrow occurs here + | ^^^^^^^^^^^^^^^ second mutable borrow occurs here LL | LL | value.len(); - | ----------- first borrow later used here + | ----- first borrow later used here error: aborting due to previous error diff --git a/tests/ui/nll/ty-outlives/projection-no-regions-closure.stderr b/tests/ui/nll/ty-outlives/projection-no-regions-closure.stderr index 4eefb180ee5..433024c30bb 100644 --- a/tests/ui/nll/ty-outlives/projection-no-regions-closure.stderr +++ b/tests/ui/nll/ty-outlives/projection-no-regions-closure.stderr @@ -4,7 +4,7 @@ note: external requirements LL | with_signature(x, |mut y| Box::new(y.next())) | ^^^^^^^ | - = note: defining type: no_region::<'?1, T>::{closure#0} with closure substs [ + = note: defining type: no_region::<'?1, T>::{closure#0} with closure args [ i32, extern "rust-call" fn((std::boxed::Box<T>,)) -> std::boxed::Box<(dyn Anything + '?2)>, (), @@ -37,7 +37,7 @@ note: external requirements LL | with_signature(x, |mut y| Box::new(y.next())) | ^^^^^^^ | - = note: defining type: correct_region::<'?1, T>::{closure#0} with closure substs [ + = note: defining type: correct_region::<'?1, T>::{closure#0} with closure args [ i32, extern "rust-call" fn((std::boxed::Box<T>,)) -> std::boxed::Box<(dyn Anything + '?2)>, (), @@ -61,7 +61,7 @@ note: external requirements LL | with_signature(x, |mut y| Box::new(y.next())) | ^^^^^^^ | - = note: defining type: wrong_region::<'?1, '?2, T>::{closure#0} with closure substs [ + = note: defining type: wrong_region::<'?1, '?2, T>::{closure#0} with closure args [ i32, extern "rust-call" fn((std::boxed::Box<T>,)) -> std::boxed::Box<(dyn Anything + '?3)>, (), @@ -94,7 +94,7 @@ note: external requirements LL | with_signature(x, |mut y| Box::new(y.next())) | ^^^^^^^ | - = note: defining type: outlives_region::<'?1, '?2, T>::{closure#0} with closure substs [ + = note: defining type: outlives_region::<'?1, '?2, T>::{closure#0} with closure args [ i32, extern "rust-call" fn((std::boxed::Box<T>,)) -> std::boxed::Box<(dyn Anything + '?3)>, (), diff --git a/tests/ui/nll/ty-outlives/projection-one-region-closure.stderr b/tests/ui/nll/ty-outlives/projection-one-region-closure.stderr index 986c2bd2182..ebdce7bc108 100644 --- a/tests/ui/nll/ty-outlives/projection-one-region-closure.stderr +++ b/tests/ui/nll/ty-outlives/projection-one-region-closure.stderr @@ -4,7 +4,7 @@ note: external requirements LL | with_signature(cell, t, |cell, t| require(cell, t)); | ^^^^^^^^^ | - = note: defining type: no_relationships_late::<'?1, T>::{closure#0} with closure substs [ + = note: defining type: no_relationships_late::<'?1, T>::{closure#0} with closure args [ i32, extern "rust-call" fn((std::cell::Cell<&'?2 ()>, T)), (), @@ -54,7 +54,7 @@ note: external requirements LL | with_signature(cell, t, |cell, t| require(cell, t)); | ^^^^^^^^^ | - = note: defining type: no_relationships_early::<'?1, '?2, T>::{closure#0} with closure substs [ + = note: defining type: no_relationships_early::<'?1, '?2, T>::{closure#0} with closure args [ i32, extern "rust-call" fn((std::cell::Cell<&'?3 ()>, T)), (), @@ -104,7 +104,7 @@ note: external requirements LL | with_signature(cell, t, |cell, t| require(cell, t)); | ^^^^^^^^^ | - = note: defining type: projection_outlives::<'?1, '?2, T>::{closure#0} with closure substs [ + = note: defining type: projection_outlives::<'?1, '?2, T>::{closure#0} with closure args [ i32, extern "rust-call" fn((std::cell::Cell<&'?3 ()>, T)), (), @@ -129,7 +129,7 @@ note: external requirements LL | with_signature(cell, t, |cell, t| require(cell, t)); | ^^^^^^^^^ | - = note: defining type: elements_outlive::<'?1, '?2, T>::{closure#0} with closure substs [ + = note: defining type: elements_outlive::<'?1, '?2, T>::{closure#0} with closure args [ i32, extern "rust-call" fn((std::cell::Cell<&'?3 ()>, T)), (), diff --git a/tests/ui/nll/ty-outlives/projection-one-region-trait-bound-closure.stderr b/tests/ui/nll/ty-outlives/projection-one-region-trait-bound-closure.stderr index 25cc60d8141..52040663e00 100644 --- a/tests/ui/nll/ty-outlives/projection-one-region-trait-bound-closure.stderr +++ b/tests/ui/nll/ty-outlives/projection-one-region-trait-bound-closure.stderr @@ -4,7 +4,7 @@ note: external requirements LL | with_signature(cell, t, |cell, t| require(cell, t)); | ^^^^^^^^^ | - = note: defining type: no_relationships_late::<'?1, T>::{closure#0} with closure substs [ + = note: defining type: no_relationships_late::<'?1, T>::{closure#0} with closure args [ i32, extern "rust-call" fn((std::cell::Cell<&'?2 ()>, T)), (), @@ -42,7 +42,7 @@ note: external requirements LL | with_signature(cell, t, |cell, t| require(cell, t)); | ^^^^^^^^^ | - = note: defining type: no_relationships_early::<'?1, '?2, T>::{closure#0} with closure substs [ + = note: defining type: no_relationships_early::<'?1, '?2, T>::{closure#0} with closure args [ i32, extern "rust-call" fn((std::cell::Cell<&'?3 ()>, T)), (), @@ -80,7 +80,7 @@ note: external requirements LL | with_signature(cell, t, |cell, t| require(cell, t)); | ^^^^^^^^^ | - = note: defining type: projection_outlives::<'?1, '?2, T>::{closure#0} with closure substs [ + = note: defining type: projection_outlives::<'?1, '?2, T>::{closure#0} with closure args [ i32, extern "rust-call" fn((std::cell::Cell<&'?3 ()>, T)), (), @@ -105,7 +105,7 @@ note: external requirements LL | with_signature(cell, t, |cell, t| require(cell, t)); | ^^^^^^^^^ | - = note: defining type: elements_outlive::<'?1, '?2, T>::{closure#0} with closure substs [ + = note: defining type: elements_outlive::<'?1, '?2, T>::{closure#0} with closure args [ i32, extern "rust-call" fn((std::cell::Cell<&'?3 ()>, T)), (), @@ -130,7 +130,7 @@ note: external requirements LL | with_signature(cell, t, |cell, t| require(cell, t)); | ^^^^^^^^^ | - = note: defining type: one_region::<'?1, T>::{closure#0} with closure substs [ + = note: defining type: one_region::<'?1, T>::{closure#0} with closure args [ i32, extern "rust-call" fn((std::cell::Cell<&'?2 ()>, T)), (), diff --git a/tests/ui/nll/ty-outlives/projection-one-region-trait-bound-static-closure.stderr b/tests/ui/nll/ty-outlives/projection-one-region-trait-bound-static-closure.stderr index 5a092d7b849..97be61b77a8 100644 --- a/tests/ui/nll/ty-outlives/projection-one-region-trait-bound-static-closure.stderr +++ b/tests/ui/nll/ty-outlives/projection-one-region-trait-bound-static-closure.stderr @@ -4,7 +4,7 @@ note: no external requirements LL | with_signature(cell, t, |cell, t| require(cell, t)); | ^^^^^^^^^ | - = note: defining type: no_relationships_late::<'?1, T>::{closure#0} with closure substs [ + = note: defining type: no_relationships_late::<'?1, T>::{closure#0} with closure args [ i32, extern "rust-call" fn((std::cell::Cell<&'?2 ()>, T)), (), @@ -27,7 +27,7 @@ note: no external requirements LL | with_signature(cell, t, |cell, t| require(cell, t)); | ^^^^^^^^^ | - = note: defining type: no_relationships_early::<'?1, '?2, T>::{closure#0} with closure substs [ + = note: defining type: no_relationships_early::<'?1, '?2, T>::{closure#0} with closure args [ i32, extern "rust-call" fn((std::cell::Cell<&'?3 ()>, T)), (), @@ -50,7 +50,7 @@ note: no external requirements LL | with_signature(cell, t, |cell, t| require(cell, t)); | ^^^^^^^^^ | - = note: defining type: projection_outlives::<'?1, '?2, T>::{closure#0} with closure substs [ + = note: defining type: projection_outlives::<'?1, '?2, T>::{closure#0} with closure args [ i32, extern "rust-call" fn((std::cell::Cell<&'?3 ()>, T)), (), @@ -73,7 +73,7 @@ note: no external requirements LL | with_signature(cell, t, |cell, t| require(cell, t)); | ^^^^^^^^^ | - = note: defining type: elements_outlive::<'?1, '?2, T>::{closure#0} with closure substs [ + = note: defining type: elements_outlive::<'?1, '?2, T>::{closure#0} with closure args [ i32, extern "rust-call" fn((std::cell::Cell<&'?3 ()>, T)), (), @@ -96,7 +96,7 @@ note: no external requirements LL | with_signature(cell, t, |cell, t| require(cell, t)); | ^^^^^^^^^ | - = note: defining type: one_region::<'?1, T>::{closure#0} with closure substs [ + = note: defining type: one_region::<'?1, T>::{closure#0} with closure args [ i32, extern "rust-call" fn((std::cell::Cell<&'?2 ()>, T)), (), diff --git a/tests/ui/nll/ty-outlives/projection-two-region-trait-bound-closure.stderr b/tests/ui/nll/ty-outlives/projection-two-region-trait-bound-closure.stderr index 51283aa8828..dbad8e47846 100644 --- a/tests/ui/nll/ty-outlives/projection-two-region-trait-bound-closure.stderr +++ b/tests/ui/nll/ty-outlives/projection-two-region-trait-bound-closure.stderr @@ -4,7 +4,7 @@ note: external requirements LL | with_signature(cell, t, |cell, t| require(cell, t)); | ^^^^^^^^^ | - = note: defining type: no_relationships_late::<'?1, '?2, T>::{closure#0} with closure substs [ + = note: defining type: no_relationships_late::<'?1, '?2, T>::{closure#0} with closure args [ i32, extern "rust-call" fn((std::cell::Cell<&'?3 ()>, T)), (), @@ -38,7 +38,7 @@ note: external requirements LL | with_signature(cell, t, |cell, t| require(cell, t)); | ^^^^^^^^^ | - = note: defining type: no_relationships_early::<'?1, '?2, '?3, T>::{closure#0} with closure substs [ + = note: defining type: no_relationships_early::<'?1, '?2, '?3, T>::{closure#0} with closure args [ i32, extern "rust-call" fn((std::cell::Cell<&'?4 ()>, T)), (), @@ -72,7 +72,7 @@ note: external requirements LL | with_signature(cell, t, |cell, t| require(cell, t)); | ^^^^^^^^^ | - = note: defining type: projection_outlives::<'?1, '?2, '?3, T>::{closure#0} with closure substs [ + = note: defining type: projection_outlives::<'?1, '?2, '?3, T>::{closure#0} with closure args [ i32, extern "rust-call" fn((std::cell::Cell<&'?4 ()>, T)), (), @@ -97,7 +97,7 @@ note: external requirements LL | with_signature(cell, t, |cell, t| require(cell, t)); | ^^^^^^^^^ | - = note: defining type: elements_outlive1::<'?1, '?2, '?3, T>::{closure#0} with closure substs [ + = note: defining type: elements_outlive1::<'?1, '?2, '?3, T>::{closure#0} with closure args [ i32, extern "rust-call" fn((std::cell::Cell<&'?4 ()>, T)), (), @@ -122,7 +122,7 @@ note: external requirements LL | with_signature(cell, t, |cell, t| require(cell, t)); | ^^^^^^^^^ | - = note: defining type: elements_outlive2::<'?1, '?2, '?3, T>::{closure#0} with closure substs [ + = note: defining type: elements_outlive2::<'?1, '?2, '?3, T>::{closure#0} with closure args [ i32, extern "rust-call" fn((std::cell::Cell<&'?4 ()>, T)), (), @@ -147,7 +147,7 @@ note: external requirements LL | with_signature(cell, t, |cell, t| require(cell, t)); | ^^^^^^^^^ | - = note: defining type: two_regions::<'?1, T>::{closure#0} with closure substs [ + = note: defining type: two_regions::<'?1, T>::{closure#0} with closure args [ i32, extern "rust-call" fn((std::cell::Cell<&'?2 ()>, T)), (), @@ -188,7 +188,7 @@ note: external requirements LL | with_signature(cell, t, |cell, t| require(cell, t)); | ^^^^^^^^^ | - = note: defining type: two_regions_outlive::<'?1, '?2, T>::{closure#0} with closure substs [ + = note: defining type: two_regions_outlive::<'?1, '?2, T>::{closure#0} with closure args [ i32, extern "rust-call" fn((std::cell::Cell<&'?3 ()>, T)), (), @@ -213,7 +213,7 @@ note: external requirements LL | with_signature(cell, t, |cell, t| require(cell, t)); | ^^^^^^^^^ | - = note: defining type: one_region::<'?1, T>::{closure#0} with closure substs [ + = note: defining type: one_region::<'?1, T>::{closure#0} with closure args [ i32, extern "rust-call" fn((std::cell::Cell<&'?2 ()>, T)), (), diff --git a/tests/ui/nll/ty-outlives/ty-param-closure-approximate-lower-bound.stderr b/tests/ui/nll/ty-outlives/ty-param-closure-approximate-lower-bound.stderr index 04616f9b702..660211fe21a 100644 --- a/tests/ui/nll/ty-outlives/ty-param-closure-approximate-lower-bound.stderr +++ b/tests/ui/nll/ty-outlives/ty-param-closure-approximate-lower-bound.stderr @@ -4,7 +4,7 @@ note: external requirements LL | twice(cell, value, |a, b| invoke(a, b)); | ^^^^^^ | - = note: defining type: generic::<T>::{closure#0} with closure substs [ + = note: defining type: generic::<T>::{closure#0} with closure args [ i16, for<Region(BrAnon(None)), Region(BrAnon(None))> extern "rust-call" fn((std::option::Option<std::cell::Cell<&'?1 &ReLateBound(DebruijnIndex(0), BoundRegion { var: 0, kind: BrAnon(None) }) ()>>, &ReLateBound(DebruijnIndex(0), BoundRegion { var: 1, kind: BrAnon(None) }) T)), (), @@ -26,7 +26,7 @@ note: external requirements LL | twice(cell, value, |a, b| invoke(a, b)); | ^^^^^^ | - = note: defining type: generic_fail::<T>::{closure#0} with closure substs [ + = note: defining type: generic_fail::<T>::{closure#0} with closure args [ i16, for<Region(BrAnon(None)), Region(BrAnon(None))> extern "rust-call" fn((std::option::Option<std::cell::Cell<&'?1 &ReLateBound(DebruijnIndex(0), BoundRegion { var: 0, kind: BrAnon(None) }) ()>>, &ReLateBound(DebruijnIndex(0), BoundRegion { var: 1, kind: BrAnon(None) }) T)), (), diff --git a/tests/ui/nll/ty-outlives/ty-param-closure-outlives-from-return-type.stderr b/tests/ui/nll/ty-outlives/ty-param-closure-outlives-from-return-type.stderr index d580774ff8c..ddad1d205e7 100644 --- a/tests/ui/nll/ty-outlives/ty-param-closure-outlives-from-return-type.stderr +++ b/tests/ui/nll/ty-outlives/ty-param-closure-outlives-from-return-type.stderr @@ -4,7 +4,7 @@ note: external requirements LL | with_signature(x, |y| y) | ^^^ | - = note: defining type: no_region::<'?1, T>::{closure#0} with closure substs [ + = note: defining type: no_region::<'?1, T>::{closure#0} with closure args [ i32, extern "rust-call" fn((std::boxed::Box<T>,)) -> std::boxed::Box<(dyn std::fmt::Debug + '?2)>, (), diff --git a/tests/ui/nll/ty-outlives/ty-param-closure-outlives-from-where-clause.stderr b/tests/ui/nll/ty-outlives/ty-param-closure-outlives-from-where-clause.stderr index 3d4c11a3c54..bb455e9aed0 100644 --- a/tests/ui/nll/ty-outlives/ty-param-closure-outlives-from-where-clause.stderr +++ b/tests/ui/nll/ty-outlives/ty-param-closure-outlives-from-where-clause.stderr @@ -4,7 +4,7 @@ note: external requirements LL | with_signature(a, b, |x, y| { | ^^^^^^ | - = note: defining type: no_region::<T>::{closure#0} with closure substs [ + = note: defining type: no_region::<T>::{closure#0} with closure args [ i32, extern "rust-call" fn((std::cell::Cell<&'?1 ()>, T)), (), @@ -38,7 +38,7 @@ note: external requirements LL | with_signature(a, b, |x, y| { | ^^^^^^ | - = note: defining type: correct_region::<'?1, T>::{closure#0} with closure substs [ + = note: defining type: correct_region::<'?1, T>::{closure#0} with closure args [ i32, extern "rust-call" fn((std::cell::Cell<&'?2 ()>, T)), (), @@ -62,7 +62,7 @@ note: external requirements LL | with_signature(a, b, |x, y| { | ^^^^^^ | - = note: defining type: wrong_region::<'?1, T>::{closure#0} with closure substs [ + = note: defining type: wrong_region::<'?1, T>::{closure#0} with closure args [ i32, extern "rust-call" fn((std::cell::Cell<&'?2 ()>, T)), (), @@ -98,7 +98,7 @@ note: external requirements LL | with_signature(a, b, |x, y| { | ^^^^^^ | - = note: defining type: outlives_region::<'?1, '?2, T>::{closure#0} with closure substs [ + = note: defining type: outlives_region::<'?1, '?2, T>::{closure#0} with closure args [ i32, extern "rust-call" fn((std::cell::Cell<&'?3 ()>, T)), (), diff --git a/tests/ui/nll/user-annotations/dump-adt-brace-struct.rs b/tests/ui/nll/user-annotations/dump-adt-brace-struct.rs index ccda9129dab..1d0b0d55af6 100644 --- a/tests/ui/nll/user-annotations/dump-adt-brace-struct.rs +++ b/tests/ui/nll/user-annotations/dump-adt-brace-struct.rs @@ -8,7 +8,7 @@ struct SomeStruct<T> { t: T } -#[rustc_dump_user_substs] +#[rustc_dump_user_args] fn main() { SomeStruct { t: 22 }; // Nothing given, no annotation. diff --git a/tests/ui/nll/user-annotations/dump-adt-brace-struct.stderr b/tests/ui/nll/user-annotations/dump-adt-brace-struct.stderr index 5860621909c..7809b2470fe 100644 --- a/tests/ui/nll/user-annotations/dump-adt-brace-struct.stderr +++ b/tests/ui/nll/user-annotations/dump-adt-brace-struct.stderr @@ -1,4 +1,4 @@ -error: user substs: UserSubsts { substs: [&ReStatic u32], user_self_ty: None } +error: user args: UserArgs { args: [&ReStatic u32], user_self_ty: None } --> $DIR/dump-adt-brace-struct.rs:19:5 | LL | SomeStruct::<&'static u32> { t: &22 }; diff --git a/tests/ui/nll/user-annotations/dump-fn-method.rs b/tests/ui/nll/user-annotations/dump-fn-method.rs index 148d63d848f..9bdbbc37caa 100644 --- a/tests/ui/nll/user-annotations/dump-fn-method.rs +++ b/tests/ui/nll/user-annotations/dump-fn-method.rs @@ -15,7 +15,7 @@ impl<S, T> Bazoom<T> for S { fn foo<'a, T>(_: T) { } -#[rustc_dump_user_substs] +#[rustc_dump_user_args] fn main() { // Here: nothing is given, so we don't have any annotation. let x = foo; diff --git a/tests/ui/nll/user-annotations/dump-fn-method.stderr b/tests/ui/nll/user-annotations/dump-fn-method.stderr index d139efa888f..1daf4982511 100644 --- a/tests/ui/nll/user-annotations/dump-fn-method.stderr +++ b/tests/ui/nll/user-annotations/dump-fn-method.stderr @@ -1,22 +1,22 @@ -error: user substs: UserSubsts { substs: [&ReStatic u32], user_self_ty: None } +error: user args: UserArgs { args: [&ReStatic u32], user_self_ty: None } --> $DIR/dump-fn-method.rs:29:13 | LL | let x = foo::<&'static u32>; | ^^^^^^^^^^^^^^^^^^^ -error: user substs: UserSubsts { substs: [^0, u32, ^1], user_self_ty: None } +error: user args: UserArgs { args: [^0, u32, ^1], user_self_ty: None } --> $DIR/dump-fn-method.rs:35:13 | LL | let x = <_ as Bazoom<u32>>::method::<_>; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error: user substs: UserSubsts { substs: [u8, &ReStatic u16, u32], user_self_ty: None } +error: user args: UserArgs { args: [u8, &ReStatic u16, u32], user_self_ty: None } --> $DIR/dump-fn-method.rs:44:13 | LL | let x = <u8 as Bazoom<&'static u16>>::method::<u32>; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error: user substs: UserSubsts { substs: [^0, ^1, u32], user_self_ty: None } +error: user args: UserArgs { args: [^0, ^1, u32], user_self_ty: None } --> $DIR/dump-fn-method.rs:52:5 | LL | y.method::<u32>(44, 66); diff --git a/tests/ui/object-safety/object-safety-by-value-self-use.stderr b/tests/ui/object-safety/object-safety-by-value-self-use.stderr index 94fdcdf263a..17f4cb4d4a8 100644 --- a/tests/ui/object-safety/object-safety-by-value-self-use.stderr +++ b/tests/ui/object-safety/object-safety-by-value-self-use.stderr @@ -2,7 +2,7 @@ error[E0161]: cannot move a value of type `dyn Bar` --> $DIR/object-safety-by-value-self-use.rs:15:5 | LL | t.bar() - | ^^^^^^^ the size of `dyn Bar` cannot be statically determined + | ^ the size of `dyn Bar` cannot be statically determined error: aborting due to previous error diff --git a/tests/ui/panics/abort-on-panic.rs b/tests/ui/panics/abort-on-panic.rs index 1f6ad64c071..7fbee85ffd1 100644 --- a/tests/ui/panics/abort-on-panic.rs +++ b/tests/ui/panics/abort-on-panic.rs @@ -1,4 +1,6 @@ // run-pass +// revisions: current next +//[next] compile-flags: -Ztrait-solver=next #![allow(unused_must_use)] #![feature(c_unwind)] diff --git a/tests/ui/privacy/privacy2.rs b/tests/ui/privacy/privacy2.rs index c8fa436bd14..212bc003e07 100644 --- a/tests/ui/privacy/privacy2.rs +++ b/tests/ui/privacy/privacy2.rs @@ -1,3 +1,5 @@ +// compile-flags: -Zdeduplicate-diagnostics=yes + #![feature(start, no_core)] #![no_core] // makes debugging this test *a lot* easier (during resolve) diff --git a/tests/ui/privacy/privacy2.stderr b/tests/ui/privacy/privacy2.stderr index c2a33ce1f59..e7135d3fd8a 100644 --- a/tests/ui/privacy/privacy2.stderr +++ b/tests/ui/privacy/privacy2.stderr @@ -1,22 +1,22 @@ error[E0432]: unresolved import `bar::foo` - --> $DIR/privacy2.rs:17:9 + --> $DIR/privacy2.rs:19:9 | LL | use bar::foo; | ^^^^^^^^ no `foo` in `bar` error[E0603]: function import `foo` is private - --> $DIR/privacy2.rs:23:20 + --> $DIR/privacy2.rs:25:20 | LL | use bar::glob::foo; | ^^^ private function import | note: the function import `foo` is defined here... - --> $DIR/privacy2.rs:10:13 + --> $DIR/privacy2.rs:12:13 | LL | use foo; | ^^^ note: ...and refers to the function `foo` which is defined here - --> $DIR/privacy2.rs:14:1 + --> $DIR/privacy2.rs:16:1 | LL | pub fn foo() {} | ^^^^^^^^^^^^ consider importing it directly diff --git a/tests/ui/privacy/privacy3.rs b/tests/ui/privacy/privacy3.rs index 5a7cd76a98f..3466f5bb1d2 100644 --- a/tests/ui/privacy/privacy3.rs +++ b/tests/ui/privacy/privacy3.rs @@ -1,3 +1,5 @@ +// compile-flags: -Zdeduplicate-diagnostics=yes + #![feature(start, no_core)] #![no_core] // makes debugging this test *a lot* easier (during resolve) diff --git a/tests/ui/privacy/privacy3.stderr b/tests/ui/privacy/privacy3.stderr index 22c1e48b07d..df66c84751b 100644 --- a/tests/ui/privacy/privacy3.stderr +++ b/tests/ui/privacy/privacy3.stderr @@ -1,5 +1,5 @@ error[E0432]: unresolved import `bar::gpriv` - --> $DIR/privacy3.rs:18:9 + --> $DIR/privacy3.rs:20:9 | LL | use bar::gpriv; | ^^^^^^^^^^ no `gpriv` in `bar` diff --git a/tests/ui/proc-macro/allowed-attr-stmt-expr.stdout b/tests/ui/proc-macro/allowed-attr-stmt-expr.stdout index 091862de30f..4f8730053ee 100644 --- a/tests/ui/proc-macro/allowed-attr-stmt-expr.stdout +++ b/tests/ui/proc-macro/allowed-attr-stmt-expr.stdout @@ -19,17 +19,17 @@ PRINT-ATTR INPUT (DEBUG): TokenStream [ Punct { ch: '#', spacing: Alone, - span: $DIR/allowed-attr-stmt-expr.rs:35:9: 35:10 (#11), + span: $DIR/allowed-attr-stmt-expr.rs:35:9: 35:10 (#10), }, Group { delimiter: Bracket, stream: TokenStream [ Ident { ident: "rustc_dummy", - span: $DIR/allowed-attr-stmt-expr.rs:35:11: 35:22 (#11), + span: $DIR/allowed-attr-stmt-expr.rs:35:11: 35:22 (#10), }, ], - span: $DIR/allowed-attr-stmt-expr.rs:35:10: 35:23 (#11), + span: $DIR/allowed-attr-stmt-expr.rs:35:10: 35:23 (#10), }, Ident { ident: "struct", @@ -206,17 +206,17 @@ PRINT-ATTR INPUT (DEBUG): TokenStream [ Punct { ch: '#', spacing: Alone, - span: $DIR/allowed-attr-stmt-expr.rs:35:9: 35:10 (#32), + span: $DIR/allowed-attr-stmt-expr.rs:35:9: 35:10 (#31), }, Group { delimiter: Bracket, stream: TokenStream [ Ident { ident: "rustc_dummy", - span: $DIR/allowed-attr-stmt-expr.rs:35:11: 35:22 (#32), + span: $DIR/allowed-attr-stmt-expr.rs:35:11: 35:22 (#31), }, ], - span: $DIR/allowed-attr-stmt-expr.rs:35:10: 35:23 (#32), + span: $DIR/allowed-attr-stmt-expr.rs:35:10: 35:23 (#31), }, Punct { ch: '#', diff --git a/tests/ui/proc-macro/attr-stmt-expr.stdout b/tests/ui/proc-macro/attr-stmt-expr.stdout index f9b2305c735..c6d77e0ed0c 100644 --- a/tests/ui/proc-macro/attr-stmt-expr.stdout +++ b/tests/ui/proc-macro/attr-stmt-expr.stdout @@ -3,17 +3,17 @@ PRINT-ATTR INPUT (DEBUG): TokenStream [ Punct { ch: '#', spacing: Alone, - span: $DIR/attr-stmt-expr.rs:33:9: 33:10 (#8), + span: $DIR/attr-stmt-expr.rs:33:9: 33:10 (#7), }, Group { delimiter: Bracket, stream: TokenStream [ Ident { ident: "rustc_dummy", - span: $DIR/attr-stmt-expr.rs:33:11: 33:22 (#8), + span: $DIR/attr-stmt-expr.rs:33:11: 33:22 (#7), }, ], - span: $DIR/attr-stmt-expr.rs:33:10: 33:23 (#8), + span: $DIR/attr-stmt-expr.rs:33:10: 33:23 (#7), }, Ident { ident: "struct", @@ -190,17 +190,17 @@ PRINT-ATTR INPUT (DEBUG): TokenStream [ Punct { ch: '#', spacing: Alone, - span: $DIR/attr-stmt-expr.rs:33:9: 33:10 (#29), + span: $DIR/attr-stmt-expr.rs:33:9: 33:10 (#28), }, Group { delimiter: Bracket, stream: TokenStream [ Ident { ident: "rustc_dummy", - span: $DIR/attr-stmt-expr.rs:33:11: 33:22 (#29), + span: $DIR/attr-stmt-expr.rs:33:11: 33:22 (#28), }, ], - span: $DIR/attr-stmt-expr.rs:33:10: 33:23 (#29), + span: $DIR/attr-stmt-expr.rs:33:10: 33:23 (#28), }, Punct { ch: '#', diff --git a/tests/ui/proc-macro/capture-macro-rules-invoke.stdout b/tests/ui/proc-macro/capture-macro-rules-invoke.stdout index b88fbd3e897..01d71ff989b 100644 --- a/tests/ui/proc-macro/capture-macro-rules-invoke.stdout +++ b/tests/ui/proc-macro/capture-macro-rules-invoke.stdout @@ -8,7 +8,7 @@ PRINT-BANG INPUT (DEBUG): TokenStream [ span: $DIR/capture-macro-rules-invoke.rs:36:24: 36:28 (#0), }, ], - span: $DIR/capture-macro-rules-invoke.rs:21:21: 21:26 (#4), + span: $DIR/capture-macro-rules-invoke.rs:21:21: 21:26 (#3), }, ] PRINT-BANG INPUT (DISPLAY): 1 + 1, { "a" }, let a = 1;, String, my_name, 'a, my_val = 30, @@ -37,12 +37,12 @@ PRINT-BANG INPUT (DEBUG): TokenStream [ span: $DIR/capture-macro-rules-invoke.rs:38:17: 38:18 (#0), }, ], - span: $DIR/capture-macro-rules-invoke.rs:14:29: 14:34 (#8), + span: $DIR/capture-macro-rules-invoke.rs:14:29: 14:34 (#7), }, Punct { ch: ',', spacing: Alone, - span: $DIR/capture-macro-rules-invoke.rs:14:34: 14:35 (#8), + span: $DIR/capture-macro-rules-invoke.rs:14:34: 14:35 (#7), }, Group { delimiter: None, @@ -60,12 +60,12 @@ PRINT-BANG INPUT (DEBUG): TokenStream [ span: $DIR/capture-macro-rules-invoke.rs:39:13: 39:20 (#0), }, ], - span: $DIR/capture-macro-rules-invoke.rs:14:36: 14:42 (#8), + span: $DIR/capture-macro-rules-invoke.rs:14:36: 14:42 (#7), }, Punct { ch: ',', spacing: Alone, - span: $DIR/capture-macro-rules-invoke.rs:14:42: 14:43 (#8), + span: $DIR/capture-macro-rules-invoke.rs:14:42: 14:43 (#7), }, Group { delimiter: None, @@ -90,12 +90,12 @@ PRINT-BANG INPUT (DEBUG): TokenStream [ span: $DIR/capture-macro-rules-invoke.rs:40:21: 40:22 (#0), }, ], - span: $DIR/capture-macro-rules-invoke.rs:14:44: 14:49 (#8), + span: $DIR/capture-macro-rules-invoke.rs:14:44: 14:49 (#7), }, Punct { ch: ',', spacing: Alone, - span: $DIR/capture-macro-rules-invoke.rs:14:49: 14:50 (#8), + span: $DIR/capture-macro-rules-invoke.rs:14:49: 14:50 (#7), }, Group { delimiter: None, @@ -105,12 +105,12 @@ PRINT-BANG INPUT (DEBUG): TokenStream [ span: $DIR/capture-macro-rules-invoke.rs:41:13: 41:19 (#0), }, ], - span: $DIR/capture-macro-rules-invoke.rs:14:51: 14:54 (#8), + span: $DIR/capture-macro-rules-invoke.rs:14:51: 14:54 (#7), }, Punct { ch: ',', spacing: Alone, - span: $DIR/capture-macro-rules-invoke.rs:14:54: 14:55 (#8), + span: $DIR/capture-macro-rules-invoke.rs:14:54: 14:55 (#7), }, Ident { ident: "my_name", @@ -119,7 +119,7 @@ PRINT-BANG INPUT (DEBUG): TokenStream [ Punct { ch: ',', spacing: Alone, - span: $DIR/capture-macro-rules-invoke.rs:14:62: 14:63 (#8), + span: $DIR/capture-macro-rules-invoke.rs:14:62: 14:63 (#7), }, Group { delimiter: None, @@ -134,12 +134,12 @@ PRINT-BANG INPUT (DEBUG): TokenStream [ span: $DIR/capture-macro-rules-invoke.rs:43:13: 43:15 (#0), }, ], - span: $DIR/capture-macro-rules-invoke.rs:15:29: 15:38 (#8), + span: $DIR/capture-macro-rules-invoke.rs:15:29: 15:38 (#7), }, Punct { ch: ',', spacing: Alone, - span: $DIR/capture-macro-rules-invoke.rs:15:38: 15:39 (#8), + span: $DIR/capture-macro-rules-invoke.rs:15:38: 15:39 (#7), }, Group { delimiter: None, @@ -160,12 +160,12 @@ PRINT-BANG INPUT (DEBUG): TokenStream [ span: $DIR/capture-macro-rules-invoke.rs:44:22: 44:24 (#0), }, ], - span: $DIR/capture-macro-rules-invoke.rs:15:40: 15:45 (#8), + span: $DIR/capture-macro-rules-invoke.rs:15:40: 15:45 (#7), }, Punct { ch: ',', spacing: Alone, - span: $DIR/capture-macro-rules-invoke.rs:15:45: 15:46 (#8), + span: $DIR/capture-macro-rules-invoke.rs:15:45: 15:46 (#7), }, Group { delimiter: None, @@ -203,12 +203,12 @@ PRINT-BANG INPUT (DEBUG): TokenStream [ span: $DIR/capture-macro-rules-invoke.rs:45:26: 45:32 (#0), }, ], - span: $DIR/capture-macro-rules-invoke.rs:15:47: 15:52 (#8), + span: $DIR/capture-macro-rules-invoke.rs:15:47: 15:52 (#7), }, Punct { ch: ',', spacing: Alone, - span: $DIR/capture-macro-rules-invoke.rs:15:52: 15:53 (#8), + span: $DIR/capture-macro-rules-invoke.rs:15:52: 15:53 (#7), }, Group { delimiter: None, @@ -246,12 +246,12 @@ PRINT-BANG INPUT (DEBUG): TokenStream [ span: $DIR/capture-macro-rules-invoke.rs:46:16: 46:31 (#0), }, ], - span: $DIR/capture-macro-rules-invoke.rs:15:54: 15:58 (#8), + span: $DIR/capture-macro-rules-invoke.rs:15:54: 15:58 (#7), }, Punct { ch: ',', spacing: Alone, - span: $DIR/capture-macro-rules-invoke.rs:15:58: 15:59 (#8), + span: $DIR/capture-macro-rules-invoke.rs:15:58: 15:59 (#7), }, Group { delimiter: Bracket, @@ -274,7 +274,7 @@ PRINT-BANG INPUT (DEBUG): TokenStream [ Punct { ch: ',', spacing: Alone, - span: $DIR/capture-macro-rules-invoke.rs:15:63: 15:64 (#8), + span: $DIR/capture-macro-rules-invoke.rs:15:63: 15:64 (#7), }, Group { delimiter: None, @@ -291,7 +291,7 @@ PRINT-BANG INPUT (DEBUG): TokenStream [ span: $DIR/capture-macro-rules-invoke.rs:48:14: 48:16 (#0), }, ], - span: $DIR/capture-macro-rules-invoke.rs:15:65: 15:69 (#8), + span: $DIR/capture-macro-rules-invoke.rs:15:65: 15:69 (#7), }, ] PRINT-BANG INPUT (DISPLAY): (a, b) @@ -319,6 +319,6 @@ PRINT-BANG INPUT (DEBUG): TokenStream [ span: $DIR/capture-macro-rules-invoke.rs:52:26: 52:32 (#0), }, ], - span: $DIR/capture-macro-rules-invoke.rs:27:21: 27:25 (#12), + span: $DIR/capture-macro-rules-invoke.rs:27:21: 27:25 (#11), }, ] diff --git a/tests/ui/proc-macro/capture-unglued-token.stdout b/tests/ui/proc-macro/capture-unglued-token.stdout index 7e6b540332c..a0d2178f000 100644 --- a/tests/ui/proc-macro/capture-unglued-token.stdout +++ b/tests/ui/proc-macro/capture-unglued-token.stdout @@ -23,6 +23,6 @@ PRINT-BANG INPUT (DEBUG): TokenStream [ span: $DIR/capture-unglued-token.rs:19:30: 19:31 (#0), }, ], - span: $DIR/capture-unglued-token.rs:15:42: 15:48 (#4), + span: $DIR/capture-unglued-token.rs:15:42: 15:48 (#3), }, ] diff --git a/tests/ui/proc-macro/dollar-crate-issue-57089.stdout b/tests/ui/proc-macro/dollar-crate-issue-57089.stdout index 2622c005d93..de4f0c000b6 100644 --- a/tests/ui/proc-macro/dollar-crate-issue-57089.stdout +++ b/tests/ui/proc-macro/dollar-crate-issue-57089.stdout @@ -2,79 +2,79 @@ PRINT-BANG INPUT (DISPLAY): struct M($crate :: S) ; PRINT-BANG INPUT (DEBUG): TokenStream [ Ident { ident: "struct", - span: $DIR/dollar-crate-issue-57089.rs:17:13: 17:19 (#4), + span: $DIR/dollar-crate-issue-57089.rs:17:13: 17:19 (#3), }, Ident { ident: "M", - span: $DIR/dollar-crate-issue-57089.rs:17:20: 17:21 (#4), + span: $DIR/dollar-crate-issue-57089.rs:17:20: 17:21 (#3), }, Group { delimiter: Parenthesis, stream: TokenStream [ Ident { ident: "$crate", - span: $DIR/dollar-crate-issue-57089.rs:17:22: 17:28 (#4), + span: $DIR/dollar-crate-issue-57089.rs:17:22: 17:28 (#3), }, Punct { ch: ':', spacing: Joint, - span: $DIR/dollar-crate-issue-57089.rs:17:28: 17:29 (#4), + span: $DIR/dollar-crate-issue-57089.rs:17:28: 17:29 (#3), }, Punct { ch: ':', spacing: Alone, - span: $DIR/dollar-crate-issue-57089.rs:17:29: 17:30 (#4), + span: $DIR/dollar-crate-issue-57089.rs:17:29: 17:30 (#3), }, Ident { ident: "S", - span: $DIR/dollar-crate-issue-57089.rs:17:30: 17:31 (#4), + span: $DIR/dollar-crate-issue-57089.rs:17:30: 17:31 (#3), }, ], - span: $DIR/dollar-crate-issue-57089.rs:17:21: 17:32 (#4), + span: $DIR/dollar-crate-issue-57089.rs:17:21: 17:32 (#3), }, Punct { ch: ';', spacing: Alone, - span: $DIR/dollar-crate-issue-57089.rs:17:32: 17:33 (#4), + span: $DIR/dollar-crate-issue-57089.rs:17:32: 17:33 (#3), }, ] PRINT-ATTR INPUT (DISPLAY): struct A($crate :: S) ; PRINT-ATTR INPUT (DEBUG): TokenStream [ Ident { ident: "struct", - span: $DIR/dollar-crate-issue-57089.rs:21:9: 21:15 (#4), + span: $DIR/dollar-crate-issue-57089.rs:21:9: 21:15 (#3), }, Ident { ident: "A", - span: $DIR/dollar-crate-issue-57089.rs:21:16: 21:17 (#4), + span: $DIR/dollar-crate-issue-57089.rs:21:16: 21:17 (#3), }, Group { delimiter: Parenthesis, stream: TokenStream [ Ident { ident: "$crate", - span: $DIR/dollar-crate-issue-57089.rs:21:18: 21:24 (#4), + span: $DIR/dollar-crate-issue-57089.rs:21:18: 21:24 (#3), }, Punct { ch: ':', spacing: Joint, - span: $DIR/dollar-crate-issue-57089.rs:21:24: 21:25 (#4), + span: $DIR/dollar-crate-issue-57089.rs:21:24: 21:25 (#3), }, Punct { ch: ':', spacing: Alone, - span: $DIR/dollar-crate-issue-57089.rs:21:25: 21:26 (#4), + span: $DIR/dollar-crate-issue-57089.rs:21:25: 21:26 (#3), }, Ident { ident: "S", - span: $DIR/dollar-crate-issue-57089.rs:21:26: 21:27 (#4), + span: $DIR/dollar-crate-issue-57089.rs:21:26: 21:27 (#3), }, ], - span: $DIR/dollar-crate-issue-57089.rs:21:17: 21:28 (#4), + span: $DIR/dollar-crate-issue-57089.rs:21:17: 21:28 (#3), }, Punct { ch: ';', spacing: Alone, - span: $DIR/dollar-crate-issue-57089.rs:21:28: 21:29 (#4), + span: $DIR/dollar-crate-issue-57089.rs:21:28: 21:29 (#3), }, ] diff --git a/tests/ui/proc-macro/dollar-crate-issue-62325.stdout b/tests/ui/proc-macro/dollar-crate-issue-62325.stdout index a91908239c3..c7e72bf4ff5 100644 --- a/tests/ui/proc-macro/dollar-crate-issue-62325.stdout +++ b/tests/ui/proc-macro/dollar-crate-issue-62325.stdout @@ -2,109 +2,109 @@ PRINT-ATTR INPUT (DISPLAY): struct A(identity! ($crate :: S)) ; PRINT-ATTR INPUT (DEBUG): TokenStream [ Ident { ident: "struct", - span: $DIR/dollar-crate-issue-62325.rs:19:5: 19:11 (#4), + span: $DIR/dollar-crate-issue-62325.rs:19:5: 19:11 (#3), }, Ident { ident: "A", - span: $DIR/dollar-crate-issue-62325.rs:19:12: 19:13 (#4), + span: $DIR/dollar-crate-issue-62325.rs:19:12: 19:13 (#3), }, Group { delimiter: Parenthesis, stream: TokenStream [ Ident { ident: "identity", - span: $DIR/dollar-crate-issue-62325.rs:19:14: 19:22 (#4), + span: $DIR/dollar-crate-issue-62325.rs:19:14: 19:22 (#3), }, Punct { ch: '!', spacing: Alone, - span: $DIR/dollar-crate-issue-62325.rs:19:22: 19:23 (#4), + span: $DIR/dollar-crate-issue-62325.rs:19:22: 19:23 (#3), }, Group { delimiter: Parenthesis, stream: TokenStream [ Ident { ident: "$crate", - span: $DIR/dollar-crate-issue-62325.rs:19:24: 19:30 (#4), + span: $DIR/dollar-crate-issue-62325.rs:19:24: 19:30 (#3), }, Punct { ch: ':', spacing: Joint, - span: $DIR/dollar-crate-issue-62325.rs:19:30: 19:31 (#4), + span: $DIR/dollar-crate-issue-62325.rs:19:30: 19:31 (#3), }, Punct { ch: ':', spacing: Alone, - span: $DIR/dollar-crate-issue-62325.rs:19:31: 19:32 (#4), + span: $DIR/dollar-crate-issue-62325.rs:19:31: 19:32 (#3), }, Ident { ident: "S", - span: $DIR/dollar-crate-issue-62325.rs:19:32: 19:33 (#4), + span: $DIR/dollar-crate-issue-62325.rs:19:32: 19:33 (#3), }, ], - span: $DIR/dollar-crate-issue-62325.rs:19:23: 19:34 (#4), + span: $DIR/dollar-crate-issue-62325.rs:19:23: 19:34 (#3), }, ], - span: $DIR/dollar-crate-issue-62325.rs:19:13: 19:35 (#4), + span: $DIR/dollar-crate-issue-62325.rs:19:13: 19:35 (#3), }, Punct { ch: ';', spacing: Alone, - span: $DIR/dollar-crate-issue-62325.rs:19:35: 19:36 (#4), + span: $DIR/dollar-crate-issue-62325.rs:19:35: 19:36 (#3), }, ] PRINT-ATTR INPUT (DISPLAY): struct B(identity! ($crate :: S)) ; PRINT-ATTR INPUT (DEBUG): TokenStream [ Ident { ident: "struct", - span: $DIR/auxiliary/dollar-crate-external.rs:21:5: 21:11 (#12), + span: $DIR/auxiliary/dollar-crate-external.rs:21:5: 21:11 (#11), }, Ident { ident: "B", - span: $DIR/auxiliary/dollar-crate-external.rs:21:12: 21:13 (#12), + span: $DIR/auxiliary/dollar-crate-external.rs:21:12: 21:13 (#11), }, Group { delimiter: Parenthesis, stream: TokenStream [ Ident { ident: "identity", - span: $DIR/auxiliary/dollar-crate-external.rs:21:14: 21:22 (#12), + span: $DIR/auxiliary/dollar-crate-external.rs:21:14: 21:22 (#11), }, Punct { ch: '!', spacing: Alone, - span: $DIR/auxiliary/dollar-crate-external.rs:21:22: 21:23 (#12), + span: $DIR/auxiliary/dollar-crate-external.rs:21:22: 21:23 (#11), }, Group { delimiter: Parenthesis, stream: TokenStream [ Ident { ident: "$crate", - span: $DIR/auxiliary/dollar-crate-external.rs:21:24: 21:30 (#12), + span: $DIR/auxiliary/dollar-crate-external.rs:21:24: 21:30 (#11), }, Punct { ch: ':', spacing: Joint, - span: $DIR/auxiliary/dollar-crate-external.rs:21:30: 21:31 (#12), + span: $DIR/auxiliary/dollar-crate-external.rs:21:30: 21:31 (#11), }, Punct { ch: ':', spacing: Alone, - span: $DIR/auxiliary/dollar-crate-external.rs:21:31: 21:32 (#12), + span: $DIR/auxiliary/dollar-crate-external.rs:21:31: 21:32 (#11), }, Ident { ident: "S", - span: $DIR/auxiliary/dollar-crate-external.rs:21:32: 21:33 (#12), + span: $DIR/auxiliary/dollar-crate-external.rs:21:32: 21:33 (#11), }, ], - span: $DIR/auxiliary/dollar-crate-external.rs:21:23: 21:34 (#12), + span: $DIR/auxiliary/dollar-crate-external.rs:21:23: 21:34 (#11), }, ], - span: $DIR/auxiliary/dollar-crate-external.rs:21:13: 21:35 (#12), + span: $DIR/auxiliary/dollar-crate-external.rs:21:13: 21:35 (#11), }, Punct { ch: ';', spacing: Alone, - span: $DIR/auxiliary/dollar-crate-external.rs:21:35: 21:36 (#12), + span: $DIR/auxiliary/dollar-crate-external.rs:21:35: 21:36 (#11), }, ] diff --git a/tests/ui/proc-macro/dollar-crate.stdout b/tests/ui/proc-macro/dollar-crate.stdout index 4e169d47e1a..0f5f87ceca2 100644 --- a/tests/ui/proc-macro/dollar-crate.stdout +++ b/tests/ui/proc-macro/dollar-crate.stdout @@ -2,239 +2,239 @@ PRINT-BANG INPUT (DISPLAY): struct M($crate :: S) ; PRINT-BANG INPUT (DEBUG): TokenStream [ Ident { ident: "struct", - span: $DIR/dollar-crate.rs:20:17: 20:23 (#4), + span: $DIR/dollar-crate.rs:20:17: 20:23 (#3), }, Ident { ident: "M", - span: $DIR/dollar-crate.rs:20:24: 20:25 (#4), + span: $DIR/dollar-crate.rs:20:24: 20:25 (#3), }, Group { delimiter: Parenthesis, stream: TokenStream [ Ident { ident: "$crate", - span: $DIR/dollar-crate.rs:20:26: 20:32 (#4), + span: $DIR/dollar-crate.rs:20:26: 20:32 (#3), }, Punct { ch: ':', spacing: Joint, - span: $DIR/dollar-crate.rs:20:32: 20:33 (#4), + span: $DIR/dollar-crate.rs:20:32: 20:33 (#3), }, Punct { ch: ':', spacing: Alone, - span: $DIR/dollar-crate.rs:20:33: 20:34 (#4), + span: $DIR/dollar-crate.rs:20:33: 20:34 (#3), }, Ident { ident: "S", - span: $DIR/dollar-crate.rs:20:34: 20:35 (#4), + span: $DIR/dollar-crate.rs:20:34: 20:35 (#3), }, ], - span: $DIR/dollar-crate.rs:20:25: 20:36 (#4), + span: $DIR/dollar-crate.rs:20:25: 20:36 (#3), }, Punct { ch: ';', spacing: Alone, - span: $DIR/dollar-crate.rs:20:36: 20:37 (#4), + span: $DIR/dollar-crate.rs:20:36: 20:37 (#3), }, ] PRINT-ATTR INPUT (DISPLAY): struct A($crate :: S) ; PRINT-ATTR INPUT (DEBUG): TokenStream [ Ident { ident: "struct", - span: $DIR/dollar-crate.rs:24:13: 24:19 (#4), + span: $DIR/dollar-crate.rs:24:13: 24:19 (#3), }, Ident { ident: "A", - span: $DIR/dollar-crate.rs:24:20: 24:21 (#4), + span: $DIR/dollar-crate.rs:24:20: 24:21 (#3), }, Group { delimiter: Parenthesis, stream: TokenStream [ Ident { ident: "$crate", - span: $DIR/dollar-crate.rs:24:22: 24:28 (#4), + span: $DIR/dollar-crate.rs:24:22: 24:28 (#3), }, Punct { ch: ':', spacing: Joint, - span: $DIR/dollar-crate.rs:24:28: 24:29 (#4), + span: $DIR/dollar-crate.rs:24:28: 24:29 (#3), }, Punct { ch: ':', spacing: Alone, - span: $DIR/dollar-crate.rs:24:29: 24:30 (#4), + span: $DIR/dollar-crate.rs:24:29: 24:30 (#3), }, Ident { ident: "S", - span: $DIR/dollar-crate.rs:24:30: 24:31 (#4), + span: $DIR/dollar-crate.rs:24:30: 24:31 (#3), }, ], - span: $DIR/dollar-crate.rs:24:21: 24:32 (#4), + span: $DIR/dollar-crate.rs:24:21: 24:32 (#3), }, Punct { ch: ';', spacing: Alone, - span: $DIR/dollar-crate.rs:24:32: 24:33 (#4), + span: $DIR/dollar-crate.rs:24:32: 24:33 (#3), }, ] PRINT-DERIVE INPUT (DISPLAY): struct D($crate :: S) ; PRINT-DERIVE INPUT (DEBUG): TokenStream [ Ident { ident: "struct", - span: $DIR/dollar-crate.rs:27:13: 27:19 (#4), + span: $DIR/dollar-crate.rs:27:13: 27:19 (#3), }, Ident { ident: "D", - span: $DIR/dollar-crate.rs:27:20: 27:21 (#4), + span: $DIR/dollar-crate.rs:27:20: 27:21 (#3), }, Group { delimiter: Parenthesis, stream: TokenStream [ Ident { ident: "$crate", - span: $DIR/dollar-crate.rs:27:22: 27:28 (#4), + span: $DIR/dollar-crate.rs:27:22: 27:28 (#3), }, Punct { ch: ':', spacing: Joint, - span: $DIR/dollar-crate.rs:27:28: 27:29 (#4), + span: $DIR/dollar-crate.rs:27:28: 27:29 (#3), }, Punct { ch: ':', spacing: Alone, - span: $DIR/dollar-crate.rs:27:29: 27:30 (#4), + span: $DIR/dollar-crate.rs:27:29: 27:30 (#3), }, Ident { ident: "S", - span: $DIR/dollar-crate.rs:27:30: 27:31 (#4), + span: $DIR/dollar-crate.rs:27:30: 27:31 (#3), }, ], - span: $DIR/dollar-crate.rs:27:21: 27:32 (#4), + span: $DIR/dollar-crate.rs:27:21: 27:32 (#3), }, Punct { ch: ';', spacing: Alone, - span: $DIR/dollar-crate.rs:27:32: 27:33 (#4), + span: $DIR/dollar-crate.rs:27:32: 27:33 (#3), }, ] PRINT-BANG INPUT (DISPLAY): struct M($crate :: S) ; PRINT-BANG INPUT (DEBUG): TokenStream [ Ident { ident: "struct", - span: $DIR/auxiliary/dollar-crate-external.rs:7:13: 7:19 (#15), + span: $DIR/auxiliary/dollar-crate-external.rs:7:13: 7:19 (#14), }, Ident { ident: "M", - span: $DIR/auxiliary/dollar-crate-external.rs:7:20: 7:21 (#15), + span: $DIR/auxiliary/dollar-crate-external.rs:7:20: 7:21 (#14), }, Group { delimiter: Parenthesis, stream: TokenStream [ Ident { ident: "$crate", - span: $DIR/auxiliary/dollar-crate-external.rs:7:22: 7:28 (#15), + span: $DIR/auxiliary/dollar-crate-external.rs:7:22: 7:28 (#14), }, Punct { ch: ':', spacing: Joint, - span: $DIR/auxiliary/dollar-crate-external.rs:7:28: 7:29 (#15), + span: $DIR/auxiliary/dollar-crate-external.rs:7:28: 7:29 (#14), }, Punct { ch: ':', spacing: Alone, - span: $DIR/auxiliary/dollar-crate-external.rs:7:29: 7:30 (#15), + span: $DIR/auxiliary/dollar-crate-external.rs:7:29: 7:30 (#14), }, Ident { ident: "S", - span: $DIR/auxiliary/dollar-crate-external.rs:7:30: 7:31 (#15), + span: $DIR/auxiliary/dollar-crate-external.rs:7:30: 7:31 (#14), }, ], - span: $DIR/auxiliary/dollar-crate-external.rs:7:21: 7:32 (#15), + span: $DIR/auxiliary/dollar-crate-external.rs:7:21: 7:32 (#14), }, Punct { ch: ';', spacing: Alone, - span: $DIR/auxiliary/dollar-crate-external.rs:7:32: 7:33 (#15), + span: $DIR/auxiliary/dollar-crate-external.rs:7:32: 7:33 (#14), }, ] PRINT-ATTR INPUT (DISPLAY): struct A($crate :: S) ; PRINT-ATTR INPUT (DEBUG): TokenStream [ Ident { ident: "struct", - span: $DIR/auxiliary/dollar-crate-external.rs:11:9: 11:15 (#15), + span: $DIR/auxiliary/dollar-crate-external.rs:11:9: 11:15 (#14), }, Ident { ident: "A", - span: $DIR/auxiliary/dollar-crate-external.rs:11:16: 11:17 (#15), + span: $DIR/auxiliary/dollar-crate-external.rs:11:16: 11:17 (#14), }, Group { delimiter: Parenthesis, stream: TokenStream [ Ident { ident: "$crate", - span: $DIR/auxiliary/dollar-crate-external.rs:11:18: 11:24 (#15), + span: $DIR/auxiliary/dollar-crate-external.rs:11:18: 11:24 (#14), }, Punct { ch: ':', spacing: Joint, - span: $DIR/auxiliary/dollar-crate-external.rs:11:24: 11:25 (#15), + span: $DIR/auxiliary/dollar-crate-external.rs:11:24: 11:25 (#14), }, Punct { ch: ':', spacing: Alone, - span: $DIR/auxiliary/dollar-crate-external.rs:11:25: 11:26 (#15), + span: $DIR/auxiliary/dollar-crate-external.rs:11:25: 11:26 (#14), }, Ident { ident: "S", - span: $DIR/auxiliary/dollar-crate-external.rs:11:26: 11:27 (#15), + span: $DIR/auxiliary/dollar-crate-external.rs:11:26: 11:27 (#14), }, ], - span: $DIR/auxiliary/dollar-crate-external.rs:11:17: 11:28 (#15), + span: $DIR/auxiliary/dollar-crate-external.rs:11:17: 11:28 (#14), }, Punct { ch: ';', spacing: Alone, - span: $DIR/auxiliary/dollar-crate-external.rs:11:28: 11:29 (#15), + span: $DIR/auxiliary/dollar-crate-external.rs:11:28: 11:29 (#14), }, ] PRINT-DERIVE INPUT (DISPLAY): struct D($crate :: S) ; PRINT-DERIVE INPUT (DEBUG): TokenStream [ Ident { ident: "struct", - span: $DIR/auxiliary/dollar-crate-external.rs:14:9: 14:15 (#15), + span: $DIR/auxiliary/dollar-crate-external.rs:14:9: 14:15 (#14), }, Ident { ident: "D", - span: $DIR/auxiliary/dollar-crate-external.rs:14:16: 14:17 (#15), + span: $DIR/auxiliary/dollar-crate-external.rs:14:16: 14:17 (#14), }, Group { delimiter: Parenthesis, stream: TokenStream [ Ident { ident: "$crate", - span: $DIR/auxiliary/dollar-crate-external.rs:14:18: 14:24 (#15), + span: $DIR/auxiliary/dollar-crate-external.rs:14:18: 14:24 (#14), }, Punct { ch: ':', spacing: Joint, - span: $DIR/auxiliary/dollar-crate-external.rs:14:24: 14:25 (#15), + span: $DIR/auxiliary/dollar-crate-external.rs:14:24: 14:25 (#14), }, Punct { ch: ':', spacing: Alone, - span: $DIR/auxiliary/dollar-crate-external.rs:14:25: 14:26 (#15), + span: $DIR/auxiliary/dollar-crate-external.rs:14:25: 14:26 (#14), }, Ident { ident: "S", - span: $DIR/auxiliary/dollar-crate-external.rs:14:26: 14:27 (#15), + span: $DIR/auxiliary/dollar-crate-external.rs:14:26: 14:27 (#14), }, ], - span: $DIR/auxiliary/dollar-crate-external.rs:14:17: 14:28 (#15), + span: $DIR/auxiliary/dollar-crate-external.rs:14:17: 14:28 (#14), }, Punct { ch: ';', spacing: Alone, - span: $DIR/auxiliary/dollar-crate-external.rs:14:28: 14:29 (#15), + span: $DIR/auxiliary/dollar-crate-external.rs:14:28: 14:29 (#14), }, ] diff --git a/tests/ui/proc-macro/expand-to-derive.stdout b/tests/ui/proc-macro/expand-to-derive.stdout index a6437982a37..39f00918329 100644 --- a/tests/ui/proc-macro/expand-to-derive.stdout +++ b/tests/ui/proc-macro/expand-to-derive.stdout @@ -6,35 +6,35 @@ PRINT-DERIVE INPUT (DISPLAY): struct Foo PRINT-DERIVE INPUT (DEBUG): TokenStream [ Ident { ident: "struct", - span: $DIR/expand-to-derive.rs:16:9: 16:15 (#4), + span: $DIR/expand-to-derive.rs:16:9: 16:15 (#3), }, Ident { ident: "Foo", - span: $DIR/expand-to-derive.rs:16:16: 16:19 (#4), + span: $DIR/expand-to-derive.rs:16:16: 16:19 (#3), }, Group { delimiter: Brace, stream: TokenStream [ Ident { ident: "field", - span: $DIR/expand-to-derive.rs:18:13: 18:18 (#4), + span: $DIR/expand-to-derive.rs:18:13: 18:18 (#3), }, Punct { ch: ':', spacing: Alone, - span: $DIR/expand-to-derive.rs:18:18: 18:19 (#4), + span: $DIR/expand-to-derive.rs:18:18: 18:19 (#3), }, Group { delimiter: Bracket, stream: TokenStream [ Ident { ident: "bool", - span: $DIR/expand-to-derive.rs:18:21: 18:25 (#4), + span: $DIR/expand-to-derive.rs:18:21: 18:25 (#3), }, Punct { ch: ';', spacing: Alone, - span: $DIR/expand-to-derive.rs:18:25: 18:26 (#4), + span: $DIR/expand-to-derive.rs:18:25: 18:26 (#3), }, Group { delimiter: Brace, @@ -90,15 +90,15 @@ PRINT-DERIVE INPUT (DEBUG): TokenStream [ kind: Integer, symbol: "0", suffix: None, - span: $DIR/expand-to-derive.rs:20:17: 20:18 (#4), + span: $DIR/expand-to-derive.rs:20:17: 20:18 (#3), }, ], - span: $DIR/expand-to-derive.rs:18:27: 21:14 (#4), + span: $DIR/expand-to-derive.rs:18:27: 21:14 (#3), }, ], - span: $DIR/expand-to-derive.rs:18:20: 21:15 (#4), + span: $DIR/expand-to-derive.rs:18:20: 21:15 (#3), }, ], - span: $DIR/expand-to-derive.rs:16:20: 22:10 (#4), + span: $DIR/expand-to-derive.rs:16:20: 22:10 (#3), }, ] diff --git a/tests/ui/proc-macro/expr-stmt-nonterminal-tokens.stdout b/tests/ui/proc-macro/expr-stmt-nonterminal-tokens.stdout index 686d53e8876..40181efc0b8 100644 --- a/tests/ui/proc-macro/expr-stmt-nonterminal-tokens.stdout +++ b/tests/ui/proc-macro/expr-stmt-nonterminal-tokens.stdout @@ -3,39 +3,39 @@ PRINT-DERIVE DEEP-RE-COLLECTED (DISPLAY): enum E { V = { let _ = #[allow(warning PRINT-DERIVE INPUT (DEBUG): TokenStream [ Ident { ident: "enum", - span: #4 bytes(299..303), + span: #3 bytes(299..303), }, Ident { ident: "E", - span: #4 bytes(304..305), + span: #3 bytes(304..305), }, Group { delimiter: Brace, stream: TokenStream [ Ident { ident: "V", - span: #4 bytes(320..321), + span: #3 bytes(320..321), }, Punct { ch: '=', spacing: Alone, - span: #4 bytes(322..323), + span: #3 bytes(322..323), }, Group { delimiter: Brace, stream: TokenStream [ Ident { ident: "let", - span: #4 bytes(326..329), + span: #3 bytes(326..329), }, Ident { ident: "_", - span: #4 bytes(330..331), + span: #3 bytes(330..331), }, Punct { ch: '=', spacing: Alone, - span: #4 bytes(332..333), + span: #3 bytes(332..333), }, Group { delimiter: None, @@ -97,29 +97,29 @@ PRINT-DERIVE INPUT (DEBUG): TokenStream [ span: #0 bytes(560..561), }, ], - span: #4 bytes(334..339), + span: #3 bytes(334..339), }, Punct { ch: ';', spacing: Alone, - span: #4 bytes(339..340), + span: #3 bytes(339..340), }, Literal { kind: Integer, symbol: "0", suffix: None, - span: #4 bytes(341..342), + span: #3 bytes(341..342), }, ], - span: #4 bytes(324..344), + span: #3 bytes(324..344), }, Punct { ch: ',', spacing: Alone, - span: #4 bytes(344..345), + span: #3 bytes(344..345), }, ], - span: #4 bytes(306..355), + span: #3 bytes(306..355), }, ] PRINT-DERIVE INPUT (DISPLAY): enum E { V = { let _ = { 0; } ; 0 }, } @@ -127,39 +127,39 @@ PRINT-DERIVE DEEP-RE-COLLECTED (DISPLAY): enum E { V = { let _ = { 0 } ; 0 }, } PRINT-DERIVE INPUT (DEBUG): TokenStream [ Ident { ident: "enum", - span: #8 bytes(423..427), + span: #7 bytes(423..427), }, Ident { ident: "E", - span: #8 bytes(428..429), + span: #7 bytes(428..429), }, Group { delimiter: Brace, stream: TokenStream [ Ident { ident: "V", - span: #8 bytes(444..445), + span: #7 bytes(444..445), }, Punct { ch: '=', spacing: Alone, - span: #8 bytes(446..447), + span: #7 bytes(446..447), }, Group { delimiter: Brace, stream: TokenStream [ Ident { ident: "let", - span: #8 bytes(450..453), + span: #7 bytes(450..453), }, Ident { ident: "_", - span: #8 bytes(454..455), + span: #7 bytes(454..455), }, Punct { ch: '=', spacing: Alone, - span: #8 bytes(456..457), + span: #7 bytes(456..457), }, Group { delimiter: Brace, @@ -174,71 +174,71 @@ PRINT-DERIVE INPUT (DEBUG): TokenStream [ span: #0 bytes(578..579), }, ], - span: #8 bytes(460..465), + span: #7 bytes(460..465), }, ], - span: #8 bytes(458..467), + span: #7 bytes(458..467), }, Punct { ch: ';', spacing: Alone, - span: #8 bytes(467..468), + span: #7 bytes(467..468), }, Literal { kind: Integer, symbol: "0", suffix: None, - span: #8 bytes(469..470), + span: #7 bytes(469..470), }, ], - span: #8 bytes(448..472), + span: #7 bytes(448..472), }, Punct { ch: ',', spacing: Alone, - span: #8 bytes(472..473), + span: #7 bytes(472..473), }, ], - span: #8 bytes(430..483), + span: #7 bytes(430..483), }, ] PRINT-DERIVE INPUT (DISPLAY): enum E { V = { let _ = { {} } ; 0 }, } PRINT-DERIVE INPUT (DEBUG): TokenStream [ Ident { ident: "enum", - span: #12 bytes(423..427), + span: #11 bytes(423..427), }, Ident { ident: "E", - span: #12 bytes(428..429), + span: #11 bytes(428..429), }, Group { delimiter: Brace, stream: TokenStream [ Ident { ident: "V", - span: #12 bytes(444..445), + span: #11 bytes(444..445), }, Punct { ch: '=', spacing: Alone, - span: #12 bytes(446..447), + span: #11 bytes(446..447), }, Group { delimiter: Brace, stream: TokenStream [ Ident { ident: "let", - span: #12 bytes(450..453), + span: #11 bytes(450..453), }, Ident { ident: "_", - span: #12 bytes(454..455), + span: #11 bytes(454..455), }, Punct { ch: '=', spacing: Alone, - span: #12 bytes(456..457), + span: #11 bytes(456..457), }, Group { delimiter: Brace, @@ -252,32 +252,32 @@ PRINT-DERIVE INPUT (DEBUG): TokenStream [ span: #0 bytes(596..598), }, ], - span: #12 bytes(460..465), + span: #11 bytes(460..465), }, ], - span: #12 bytes(458..467), + span: #11 bytes(458..467), }, Punct { ch: ';', spacing: Alone, - span: #12 bytes(467..468), + span: #11 bytes(467..468), }, Literal { kind: Integer, symbol: "0", suffix: None, - span: #12 bytes(469..470), + span: #11 bytes(469..470), }, ], - span: #12 bytes(448..472), + span: #11 bytes(448..472), }, Punct { ch: ',', spacing: Alone, - span: #12 bytes(472..473), + span: #11 bytes(472..473), }, ], - span: #12 bytes(430..483), + span: #11 bytes(430..483), }, ] PRINT-DERIVE INPUT (DISPLAY): enum E { V = { let _ = { PATH; } ; 0 }, } @@ -285,39 +285,39 @@ PRINT-DERIVE DEEP-RE-COLLECTED (DISPLAY): enum E { V = { let _ = { PATH } ; 0 }, PRINT-DERIVE INPUT (DEBUG): TokenStream [ Ident { ident: "enum", - span: #16 bytes(423..427), + span: #15 bytes(423..427), }, Ident { ident: "E", - span: #16 bytes(428..429), + span: #15 bytes(428..429), }, Group { delimiter: Brace, stream: TokenStream [ Ident { ident: "V", - span: #16 bytes(444..445), + span: #15 bytes(444..445), }, Punct { ch: '=', spacing: Alone, - span: #16 bytes(446..447), + span: #15 bytes(446..447), }, Group { delimiter: Brace, stream: TokenStream [ Ident { ident: "let", - span: #16 bytes(450..453), + span: #15 bytes(450..453), }, Ident { ident: "_", - span: #16 bytes(454..455), + span: #15 bytes(454..455), }, Punct { ch: '=', spacing: Alone, - span: #16 bytes(456..457), + span: #15 bytes(456..457), }, Group { delimiter: Brace, @@ -330,32 +330,32 @@ PRINT-DERIVE INPUT (DEBUG): TokenStream [ span: #0 bytes(615..619), }, ], - span: #16 bytes(460..465), + span: #15 bytes(460..465), }, ], - span: #16 bytes(458..467), + span: #15 bytes(458..467), }, Punct { ch: ';', spacing: Alone, - span: #16 bytes(467..468), + span: #15 bytes(467..468), }, Literal { kind: Integer, symbol: "0", suffix: None, - span: #16 bytes(469..470), + span: #15 bytes(469..470), }, ], - span: #16 bytes(448..472), + span: #15 bytes(448..472), }, Punct { ch: ',', spacing: Alone, - span: #16 bytes(472..473), + span: #15 bytes(472..473), }, ], - span: #16 bytes(430..483), + span: #15 bytes(430..483), }, ] PRINT-DERIVE INPUT (DISPLAY): enum E { V = { let _ = { 0 + 1; } ; 0 }, } @@ -363,39 +363,39 @@ PRINT-DERIVE DEEP-RE-COLLECTED (DISPLAY): enum E { V = { let _ = { 0 + 1 } ; 0 } PRINT-DERIVE INPUT (DEBUG): TokenStream [ Ident { ident: "enum", - span: #20 bytes(423..427), + span: #19 bytes(423..427), }, Ident { ident: "E", - span: #20 bytes(428..429), + span: #19 bytes(428..429), }, Group { delimiter: Brace, stream: TokenStream [ Ident { ident: "V", - span: #20 bytes(444..445), + span: #19 bytes(444..445), }, Punct { ch: '=', spacing: Alone, - span: #20 bytes(446..447), + span: #19 bytes(446..447), }, Group { delimiter: Brace, stream: TokenStream [ Ident { ident: "let", - span: #20 bytes(450..453), + span: #19 bytes(450..453), }, Ident { ident: "_", - span: #20 bytes(454..455), + span: #19 bytes(454..455), }, Punct { ch: '=', spacing: Alone, - span: #20 bytes(456..457), + span: #19 bytes(456..457), }, Group { delimiter: Brace, @@ -421,32 +421,32 @@ PRINT-DERIVE INPUT (DEBUG): TokenStream [ span: #0 bytes(640..641), }, ], - span: #20 bytes(460..465), + span: #19 bytes(460..465), }, ], - span: #20 bytes(458..467), + span: #19 bytes(458..467), }, Punct { ch: ';', spacing: Alone, - span: #20 bytes(467..468), + span: #19 bytes(467..468), }, Literal { kind: Integer, symbol: "0", suffix: None, - span: #20 bytes(469..470), + span: #19 bytes(469..470), }, ], - span: #20 bytes(448..472), + span: #19 bytes(448..472), }, Punct { ch: ',', spacing: Alone, - span: #20 bytes(472..473), + span: #19 bytes(472..473), }, ], - span: #20 bytes(430..483), + span: #19 bytes(430..483), }, ] PRINT-DERIVE INPUT (DISPLAY): enum E { V = { let _ = { PATH + 1; } ; 0 }, } @@ -454,39 +454,39 @@ PRINT-DERIVE DEEP-RE-COLLECTED (DISPLAY): enum E { V = { let _ = { PATH + 1 } ; PRINT-DERIVE INPUT (DEBUG): TokenStream [ Ident { ident: "enum", - span: #24 bytes(423..427), + span: #23 bytes(423..427), }, Ident { ident: "E", - span: #24 bytes(428..429), + span: #23 bytes(428..429), }, Group { delimiter: Brace, stream: TokenStream [ Ident { ident: "V", - span: #24 bytes(444..445), + span: #23 bytes(444..445), }, Punct { ch: '=', spacing: Alone, - span: #24 bytes(446..447), + span: #23 bytes(446..447), }, Group { delimiter: Brace, stream: TokenStream [ Ident { ident: "let", - span: #24 bytes(450..453), + span: #23 bytes(450..453), }, Ident { ident: "_", - span: #24 bytes(454..455), + span: #23 bytes(454..455), }, Punct { ch: '=', spacing: Alone, - span: #24 bytes(456..457), + span: #23 bytes(456..457), }, Group { delimiter: Brace, @@ -510,31 +510,31 @@ PRINT-DERIVE INPUT (DEBUG): TokenStream [ span: #0 bytes(665..666), }, ], - span: #24 bytes(460..465), + span: #23 bytes(460..465), }, ], - span: #24 bytes(458..467), + span: #23 bytes(458..467), }, Punct { ch: ';', spacing: Alone, - span: #24 bytes(467..468), + span: #23 bytes(467..468), }, Literal { kind: Integer, symbol: "0", suffix: None, - span: #24 bytes(469..470), + span: #23 bytes(469..470), }, ], - span: #24 bytes(448..472), + span: #23 bytes(448..472), }, Punct { ch: ',', spacing: Alone, - span: #24 bytes(472..473), + span: #23 bytes(472..473), }, ], - span: #24 bytes(430..483), + span: #23 bytes(430..483), }, ] diff --git a/tests/ui/proc-macro/input-interpolated.stdout b/tests/ui/proc-macro/input-interpolated.stdout index 34566c78019..6a8789b2c41 100644 --- a/tests/ui/proc-macro/input-interpolated.stdout +++ b/tests/ui/proc-macro/input-interpolated.stdout @@ -9,7 +9,7 @@ PRINT-ATTR INPUT (DISPLAY): const A : u8 = 0 ; PRINT-ATTR INPUT (DEBUG): TokenStream [ Ident { ident: "const", - span: #4 bytes(416..421), + span: #3 bytes(416..421), }, Ident { ident: "A", @@ -18,34 +18,34 @@ PRINT-ATTR INPUT (DEBUG): TokenStream [ Punct { ch: ':', spacing: Alone, - span: #4 bytes(424..425), + span: #3 bytes(424..425), }, Ident { ident: "u8", - span: #4 bytes(426..428), + span: #3 bytes(426..428), }, Punct { ch: '=', spacing: Alone, - span: #4 bytes(429..430), + span: #3 bytes(429..430), }, Literal { kind: Integer, symbol: "0", suffix: None, - span: #4 bytes(431..432), + span: #3 bytes(431..432), }, Punct { ch: ';', spacing: Alone, - span: #4 bytes(432..433), + span: #3 bytes(432..433), }, ] PRINT-DERIVE INPUT (DISPLAY): struct A {} PRINT-DERIVE INPUT (DEBUG): TokenStream [ Ident { ident: "struct", - span: #4 bytes(468..474), + span: #3 bytes(468..474), }, Ident { ident: "A", @@ -54,6 +54,6 @@ PRINT-DERIVE INPUT (DEBUG): TokenStream [ Group { delimiter: Brace, stream: TokenStream [], - span: #4 bytes(478..480), + span: #3 bytes(478..480), }, ] diff --git a/tests/ui/proc-macro/issue-75734-pp-paren.stdout b/tests/ui/proc-macro/issue-75734-pp-paren.stdout index 0fda6654ff3..2f7c013e958 100644 --- a/tests/ui/proc-macro/issue-75734-pp-paren.stdout +++ b/tests/ui/proc-macro/issue-75734-pp-paren.stdout @@ -118,17 +118,17 @@ PRINT-BANG INPUT (DEBUG): TokenStream [ span: $DIR/issue-75734-pp-paren.rs:25:16: 25:17 (#0), }, ], - span: $DIR/issue-75734-pp-paren.rs:17:21: 17:25 (#7), + span: $DIR/issue-75734-pp-paren.rs:17:21: 17:25 (#6), }, Punct { ch: '*', spacing: Alone, - span: $DIR/issue-75734-pp-paren.rs:17:26: 17:27 (#7), + span: $DIR/issue-75734-pp-paren.rs:17:26: 17:27 (#6), }, Literal { kind: Integer, symbol: "2", suffix: None, - span: $DIR/issue-75734-pp-paren.rs:17:28: 17:29 (#7), + span: $DIR/issue-75734-pp-paren.rs:17:28: 17:29 (#6), }, ] diff --git a/tests/ui/proc-macro/issue-78675-captured-inner-attrs.stdout b/tests/ui/proc-macro/issue-78675-captured-inner-attrs.stdout index 60a400a5dea..ae5e9400809 100644 --- a/tests/ui/proc-macro/issue-78675-captured-inner-attrs.stdout +++ b/tests/ui/proc-macro/issue-78675-captured-inner-attrs.stdout @@ -5,12 +5,12 @@ PRINT-BANG DEEP-RE-COLLECTED (DISPLAY): foo! { #[fake_attr] mod bar { #! [doc = PRINT-BANG INPUT (DEBUG): TokenStream [ Ident { ident: "foo", - span: $DIR/issue-78675-captured-inner-attrs.rs:20:9: 20:12 (#4), + span: $DIR/issue-78675-captured-inner-attrs.rs:20:9: 20:12 (#3), }, Punct { ch: '!', spacing: Alone, - span: $DIR/issue-78675-captured-inner-attrs.rs:20:12: 20:13 (#4), + span: $DIR/issue-78675-captured-inner-attrs.rs:20:12: 20:13 (#3), }, Group { delimiter: Brace, @@ -18,17 +18,17 @@ PRINT-BANG INPUT (DEBUG): TokenStream [ Punct { ch: '#', spacing: Alone, - span: $DIR/issue-78675-captured-inner-attrs.rs:21:13: 21:14 (#4), + span: $DIR/issue-78675-captured-inner-attrs.rs:21:13: 21:14 (#3), }, Group { delimiter: Bracket, stream: TokenStream [ Ident { ident: "fake_attr", - span: $DIR/issue-78675-captured-inner-attrs.rs:21:15: 21:24 (#4), + span: $DIR/issue-78675-captured-inner-attrs.rs:21:15: 21:24 (#3), }, ], - span: $DIR/issue-78675-captured-inner-attrs.rs:21:14: 21:25 (#4), + span: $DIR/issue-78675-captured-inner-attrs.rs:21:14: 21:25 (#3), }, Group { delimiter: None, @@ -79,9 +79,9 @@ PRINT-BANG INPUT (DEBUG): TokenStream [ span: $DIR/issue-78675-captured-inner-attrs.rs:27:13: 29:6 (#0), }, ], - span: $DIR/issue-78675-captured-inner-attrs.rs:22:13: 22:18 (#4), + span: $DIR/issue-78675-captured-inner-attrs.rs:22:13: 22:18 (#3), }, ], - span: $DIR/issue-78675-captured-inner-attrs.rs:20:14: 23:10 (#4), + span: $DIR/issue-78675-captured-inner-attrs.rs:20:14: 23:10 (#3), }, ] diff --git a/tests/ui/proc-macro/issue-80760-empty-stmt.stdout b/tests/ui/proc-macro/issue-80760-empty-stmt.stdout index 4b7ed874307..82f52e4bc48 100644 --- a/tests/ui/proc-macro/issue-80760-empty-stmt.stdout +++ b/tests/ui/proc-macro/issue-80760-empty-stmt.stdout @@ -9,6 +9,6 @@ PRINT-BANG INPUT (DEBUG): TokenStream [ span: $DIR/issue-80760-empty-stmt.rs:25:17: 25:18 (#0), }, ], - span: $DIR/issue-80760-empty-stmt.rs:13:21: 13:23 (#4), + span: $DIR/issue-80760-empty-stmt.rs:13:21: 13:23 (#3), }, ] diff --git a/tests/ui/proc-macro/macro-rules-derive-cfg.stdout b/tests/ui/proc-macro/macro-rules-derive-cfg.stdout index 74641058ef3..aee0f966d0f 100644 --- a/tests/ui/proc-macro/macro-rules-derive-cfg.stdout +++ b/tests/ui/proc-macro/macro-rules-derive-cfg.stdout @@ -10,76 +10,76 @@ PRINT-DERIVE INPUT (DISPLAY): struct Foo PRINT-DERIVE INPUT (DEBUG): TokenStream [ Ident { ident: "struct", - span: $DIR/macro-rules-derive-cfg.rs:17:9: 17:15 (#4), + span: $DIR/macro-rules-derive-cfg.rs:17:9: 17:15 (#3), }, Ident { ident: "Foo", - span: $DIR/macro-rules-derive-cfg.rs:17:16: 17:19 (#4), + span: $DIR/macro-rules-derive-cfg.rs:17:16: 17:19 (#3), }, Group { delimiter: Brace, stream: TokenStream [ Ident { ident: "val", - span: $DIR/macro-rules-derive-cfg.rs:18:13: 18:16 (#4), + span: $DIR/macro-rules-derive-cfg.rs:18:13: 18:16 (#3), }, Punct { ch: ':', spacing: Alone, - span: $DIR/macro-rules-derive-cfg.rs:18:16: 18:17 (#4), + span: $DIR/macro-rules-derive-cfg.rs:18:16: 18:17 (#3), }, Group { delimiter: Bracket, stream: TokenStream [ Ident { ident: "bool", - span: $DIR/macro-rules-derive-cfg.rs:18:19: 18:23 (#4), + span: $DIR/macro-rules-derive-cfg.rs:18:19: 18:23 (#3), }, Punct { ch: ';', spacing: Alone, - span: $DIR/macro-rules-derive-cfg.rs:18:23: 18:24 (#4), + span: $DIR/macro-rules-derive-cfg.rs:18:23: 18:24 (#3), }, Group { delimiter: Brace, stream: TokenStream [ Ident { ident: "let", - span: $DIR/macro-rules-derive-cfg.rs:19:17: 19:20 (#4), + span: $DIR/macro-rules-derive-cfg.rs:19:17: 19:20 (#3), }, Ident { ident: "a", - span: $DIR/macro-rules-derive-cfg.rs:19:21: 19:22 (#4), + span: $DIR/macro-rules-derive-cfg.rs:19:21: 19:22 (#3), }, Punct { ch: '=', spacing: Alone, - span: $DIR/macro-rules-derive-cfg.rs:19:23: 19:24 (#4), + span: $DIR/macro-rules-derive-cfg.rs:19:23: 19:24 (#3), }, Punct { ch: '#', spacing: Alone, - span: $DIR/macro-rules-derive-cfg.rs:19:25: 19:26 (#4), + span: $DIR/macro-rules-derive-cfg.rs:19:25: 19:26 (#3), }, Group { delimiter: Bracket, stream: TokenStream [ Ident { ident: "rustc_dummy", - span: $DIR/macro-rules-derive-cfg.rs:19:48: 19:59 (#4), + span: $DIR/macro-rules-derive-cfg.rs:19:48: 19:59 (#3), }, Group { delimiter: Parenthesis, stream: TokenStream [ Ident { ident: "first", - span: $DIR/macro-rules-derive-cfg.rs:19:60: 19:65 (#4), + span: $DIR/macro-rules-derive-cfg.rs:19:60: 19:65 (#3), }, ], - span: $DIR/macro-rules-derive-cfg.rs:19:59: 19:66 (#4), + span: $DIR/macro-rules-derive-cfg.rs:19:59: 19:66 (#3), }, ], - span: $DIR/macro-rules-derive-cfg.rs:19:25: 19:26 (#4), + span: $DIR/macro-rules-derive-cfg.rs:19:25: 19:26 (#3), }, Punct { ch: '#', @@ -151,21 +151,21 @@ PRINT-DERIVE INPUT (DEBUG): TokenStream [ Punct { ch: ';', spacing: Alone, - span: $DIR/macro-rules-derive-cfg.rs:19:74: 19:75 (#4), + span: $DIR/macro-rules-derive-cfg.rs:19:74: 19:75 (#3), }, Literal { kind: Integer, symbol: "0", suffix: None, - span: $DIR/macro-rules-derive-cfg.rs:20:17: 20:18 (#4), + span: $DIR/macro-rules-derive-cfg.rs:20:17: 20:18 (#3), }, ], - span: $DIR/macro-rules-derive-cfg.rs:18:25: 21:14 (#4), + span: $DIR/macro-rules-derive-cfg.rs:18:25: 21:14 (#3), }, ], - span: $DIR/macro-rules-derive-cfg.rs:18:18: 21:15 (#4), + span: $DIR/macro-rules-derive-cfg.rs:18:18: 21:15 (#3), }, ], - span: $DIR/macro-rules-derive-cfg.rs:17:20: 22:10 (#4), + span: $DIR/macro-rules-derive-cfg.rs:17:20: 22:10 (#3), }, ] diff --git a/tests/ui/proc-macro/meta-macro-hygiene.stdout b/tests/ui/proc-macro/meta-macro-hygiene.stdout index 6b7b0c819cc..17b69daa4f0 100644 --- a/tests/ui/proc-macro/meta-macro-hygiene.stdout +++ b/tests/ui/proc-macro/meta-macro-hygiene.stdout @@ -1,6 +1,6 @@ -Def site: $DIR/auxiliary/make-macro.rs:7:9: 7:56 (#5) -Input: TokenStream [Ident { ident: "$crate", span: $DIR/meta-macro-hygiene.rs:24:37: 24:43 (#4) }, Punct { ch: ':', spacing: Joint, span: $DIR/meta-macro-hygiene.rs:24:43: 24:44 (#4) }, Punct { ch: ':', spacing: Alone, span: $DIR/meta-macro-hygiene.rs:24:44: 24:45 (#4) }, Ident { ident: "dummy", span: $DIR/meta-macro-hygiene.rs:24:45: 24:50 (#4) }, Punct { ch: '!', spacing: Alone, span: $DIR/meta-macro-hygiene.rs:24:50: 24:51 (#4) }, Group { delimiter: Parenthesis, stream: TokenStream [], span: $DIR/meta-macro-hygiene.rs:24:51: 24:53 (#4) }] -Respanned: TokenStream [Ident { ident: "$crate", span: $DIR/auxiliary/make-macro.rs:7:9: 7:56 (#5) }, Punct { ch: ':', spacing: Joint, span: $DIR/auxiliary/make-macro.rs:7:9: 7:56 (#5) }, Punct { ch: ':', spacing: Alone, span: $DIR/auxiliary/make-macro.rs:7:9: 7:56 (#5) }, Ident { ident: "dummy", span: $DIR/auxiliary/make-macro.rs:7:9: 7:56 (#5) }, Punct { ch: '!', spacing: Alone, span: $DIR/auxiliary/make-macro.rs:7:9: 7:56 (#5) }, Group { delimiter: Parenthesis, stream: TokenStream [], span: $DIR/auxiliary/make-macro.rs:7:9: 7:56 (#5) }] +Def site: $DIR/auxiliary/make-macro.rs:7:9: 7:56 (#4) +Input: TokenStream [Ident { ident: "$crate", span: $DIR/meta-macro-hygiene.rs:24:37: 24:43 (#3) }, Punct { ch: ':', spacing: Joint, span: $DIR/meta-macro-hygiene.rs:24:43: 24:44 (#3) }, Punct { ch: ':', spacing: Alone, span: $DIR/meta-macro-hygiene.rs:24:44: 24:45 (#3) }, Ident { ident: "dummy", span: $DIR/meta-macro-hygiene.rs:24:45: 24:50 (#3) }, Punct { ch: '!', spacing: Alone, span: $DIR/meta-macro-hygiene.rs:24:50: 24:51 (#3) }, Group { delimiter: Parenthesis, stream: TokenStream [], span: $DIR/meta-macro-hygiene.rs:24:51: 24:53 (#3) }] +Respanned: TokenStream [Ident { ident: "$crate", span: $DIR/auxiliary/make-macro.rs:7:9: 7:56 (#4) }, Punct { ch: ':', spacing: Joint, span: $DIR/auxiliary/make-macro.rs:7:9: 7:56 (#4) }, Punct { ch: ':', spacing: Alone, span: $DIR/auxiliary/make-macro.rs:7:9: 7:56 (#4) }, Ident { ident: "dummy", span: $DIR/auxiliary/make-macro.rs:7:9: 7:56 (#4) }, Punct { ch: '!', spacing: Alone, span: $DIR/auxiliary/make-macro.rs:7:9: 7:56 (#4) }, Group { delimiter: Parenthesis, stream: TokenStream [], span: $DIR/auxiliary/make-macro.rs:7:9: 7:56 (#4) }] #![feature /* 0#0 */(prelude_import)] // aux-build:make-macro.rs // aux-build:meta-macro.rs @@ -18,8 +18,7 @@ Respanned: TokenStream [Ident { ident: "$crate", span: $DIR/auxiliary/make-macro use core /* 0#1 */::prelude /* 0#1 */::rust_2018 /* 0#1 */::*; #[macro_use /* 0#1 */] extern crate core /* 0#1 */; -#[macro_use /* 0#1 */] -extern crate compiler_builtins /* 0#1 */; +extern crate compiler_builtins /* 442 */ as _ /* 0#1 */; // Don't load unnecessary hygiene information from std extern crate std /* 0#0 */; @@ -47,23 +46,21 @@ Expansions: crate0::{{expn0}}: parent: crate0::{{expn0}}, call_site_ctxt: #0, def_site_ctxt: #0, kind: Root crate0::{{expn1}}: parent: crate0::{{expn0}}, call_site_ctxt: #0, def_site_ctxt: #0, kind: AstPass(StdImports) crate0::{{expn2}}: parent: crate0::{{expn0}}, call_site_ctxt: #0, def_site_ctxt: #0, kind: Macro(Bang, "produce_it") -crate0::{{expn3}}: parent: crate0::{{expn2}}, call_site_ctxt: #4, def_site_ctxt: #0, kind: Macro(Bang, "meta_macro::print_def_site") -crate0::{{expn4}}: parent: crate0::{{expn3}}, call_site_ctxt: #5, def_site_ctxt: #0, kind: Macro(Bang, "$crate::dummy") +crate0::{{expn3}}: parent: crate0::{{expn2}}, call_site_ctxt: #3, def_site_ctxt: #0, kind: Macro(Bang, "meta_macro::print_def_site") +crate0::{{expn4}}: parent: crate0::{{expn3}}, call_site_ctxt: #4, def_site_ctxt: #0, kind: Macro(Bang, "$crate::dummy") crate1::{{expnNNN}}: parent: crate0::{{expn0}}, call_site_ctxt: #0, def_site_ctxt: #0, kind: Macro(Attr, "derive") crate1::{{expnNNN}}: parent: crate0::{{expn0}}, call_site_ctxt: #0, def_site_ctxt: #0, kind: Macro(Attr, "derive") crate1::{{expnNNN}}: parent: crate0::{{expn0}}, call_site_ctxt: #0, def_site_ctxt: #0, kind: Macro(Bang, "include") -crate2::{{expn1}}: parent: crate0::{{expn0}}, call_site_ctxt: #0, def_site_ctxt: #0, kind: AstPass(StdImports) SyntaxContexts: #0: parent: #0, outer_mark: (crate0::{{expn0}}, Opaque) #1: parent: #0, outer_mark: (crate0::{{expn1}}, Opaque) #2: parent: #0, outer_mark: (crate0::{{expn1}}, Transparent) -#3: parent: #0, outer_mark: (crate2::{{expn1}}, Opaque) -#4: parent: #0, outer_mark: (crate0::{{expn2}}, SemiTransparent) -#5: parent: #0, outer_mark: (crate0::{{expn3}}, Opaque) -#6: parent: #4, outer_mark: (crate0::{{expn3}}, Transparent) -#7: parent: #0, outer_mark: (crate0::{{expn3}}, SemiTransparent) -#8: parent: #0, outer_mark: (crate0::{{expn4}}, Opaque) -#9: parent: #5, outer_mark: (crate0::{{expn4}}, Transparent) -#10: parent: #5, outer_mark: (crate0::{{expn4}}, SemiTransparent) +#3: parent: #0, outer_mark: (crate0::{{expn2}}, SemiTransparent) +#4: parent: #0, outer_mark: (crate0::{{expn3}}, Opaque) +#5: parent: #3, outer_mark: (crate0::{{expn3}}, Transparent) +#6: parent: #0, outer_mark: (crate0::{{expn3}}, SemiTransparent) +#7: parent: #0, outer_mark: (crate0::{{expn4}}, Opaque) +#8: parent: #4, outer_mark: (crate0::{{expn4}}, Transparent) +#9: parent: #4, outer_mark: (crate0::{{expn4}}, SemiTransparent) */ diff --git a/tests/ui/proc-macro/meta-macro.stdout b/tests/ui/proc-macro/meta-macro.stdout index 662682d40b2..b2d20c23722 100644 --- a/tests/ui/proc-macro/meta-macro.stdout +++ b/tests/ui/proc-macro/meta-macro.stdout @@ -1,3 +1,3 @@ -Def site: $DIR/auxiliary/make-macro.rs:7:9: 7:56 (#4) +Def site: $DIR/auxiliary/make-macro.rs:7:9: 7:56 (#3) Input: TokenStream [] Respanned: TokenStream [] diff --git a/tests/ui/proc-macro/nested-macro-rules.stdout b/tests/ui/proc-macro/nested-macro-rules.stdout index 31113904041..829cfdc0c33 100644 --- a/tests/ui/proc-macro/nested-macro-rules.stdout +++ b/tests/ui/proc-macro/nested-macro-rules.stdout @@ -2,45 +2,45 @@ PRINT-BANG INPUT (DISPLAY): FirstStruct PRINT-BANG INPUT (DEBUG): TokenStream [ Ident { ident: "FirstStruct", - span: $DIR/auxiliary/nested-macro-rules.rs:16:14: 16:25 (#7), + span: $DIR/auxiliary/nested-macro-rules.rs:16:14: 16:25 (#6), }, ] PRINT-ATTR INPUT (DISPLAY): struct FirstAttrStruct {} PRINT-ATTR INPUT (DEBUG): TokenStream [ Ident { ident: "struct", - span: $DIR/auxiliary/nested-macro-rules.rs:10:32: 10:38 (#6), + span: $DIR/auxiliary/nested-macro-rules.rs:10:32: 10:38 (#5), }, Ident { ident: "FirstAttrStruct", - span: $DIR/auxiliary/nested-macro-rules.rs:16:27: 16:42 (#7), + span: $DIR/auxiliary/nested-macro-rules.rs:16:27: 16:42 (#6), }, Group { delimiter: Brace, stream: TokenStream [], - span: $DIR/auxiliary/nested-macro-rules.rs:10:57: 10:59 (#6), + span: $DIR/auxiliary/nested-macro-rules.rs:10:57: 10:59 (#5), }, ] PRINT-BANG INPUT (DISPLAY): SecondStruct PRINT-BANG INPUT (DEBUG): TokenStream [ Ident { ident: "SecondStruct", - span: $DIR/nested-macro-rules.rs:21:38: 21:50 (#16), + span: $DIR/nested-macro-rules.rs:21:38: 21:50 (#15), }, ] PRINT-ATTR INPUT (DISPLAY): struct SecondAttrStruct {} PRINT-ATTR INPUT (DEBUG): TokenStream [ Ident { ident: "struct", - span: $DIR/auxiliary/nested-macro-rules.rs:10:32: 10:38 (#15), + span: $DIR/auxiliary/nested-macro-rules.rs:10:32: 10:38 (#14), }, Ident { ident: "SecondAttrStruct", - span: $DIR/nested-macro-rules.rs:21:52: 21:68 (#16), + span: $DIR/nested-macro-rules.rs:21:52: 21:68 (#15), }, Group { delimiter: Brace, stream: TokenStream [], - span: $DIR/auxiliary/nested-macro-rules.rs:10:57: 10:59 (#15), + span: $DIR/auxiliary/nested-macro-rules.rs:10:57: 10:59 (#14), }, ] diff --git a/tests/ui/proc-macro/nested-nonterminal-tokens.stdout b/tests/ui/proc-macro/nested-nonterminal-tokens.stdout index a3d24dd26fe..4c5550bb077 100644 --- a/tests/ui/proc-macro/nested-nonterminal-tokens.stdout +++ b/tests/ui/proc-macro/nested-nonterminal-tokens.stdout @@ -16,45 +16,45 @@ PRINT-BANG INPUT (DEBUG): TokenStream [ span: $DIR/nested-nonterminal-tokens.rs:25:26: 25:27 (#0), }, ], - span: $DIR/nested-nonterminal-tokens.rs:17:41: 17:43 (#4), + span: $DIR/nested-nonterminal-tokens.rs:17:41: 17:43 (#3), }, Punct { ch: '+', spacing: Alone, - span: $DIR/nested-nonterminal-tokens.rs:17:44: 17:45 (#4), + span: $DIR/nested-nonterminal-tokens.rs:17:44: 17:45 (#3), }, Literal { kind: Integer, symbol: "1", suffix: None, - span: $DIR/nested-nonterminal-tokens.rs:17:46: 17:47 (#4), + span: $DIR/nested-nonterminal-tokens.rs:17:46: 17:47 (#3), }, ], - span: $DIR/nested-nonterminal-tokens.rs:18:41: 18:43 (#5), + span: $DIR/nested-nonterminal-tokens.rs:18:41: 18:43 (#4), }, Punct { ch: '+', spacing: Alone, - span: $DIR/nested-nonterminal-tokens.rs:18:44: 18:45 (#5), + span: $DIR/nested-nonterminal-tokens.rs:18:44: 18:45 (#4), }, Literal { kind: Integer, symbol: "2", suffix: None, - span: $DIR/nested-nonterminal-tokens.rs:18:46: 18:47 (#5), + span: $DIR/nested-nonterminal-tokens.rs:18:46: 18:47 (#4), }, ], - span: $DIR/nested-nonterminal-tokens.rs:20:21: 20:23 (#6), + span: $DIR/nested-nonterminal-tokens.rs:20:21: 20:23 (#5), }, Punct { ch: '+', spacing: Alone, - span: $DIR/nested-nonterminal-tokens.rs:20:24: 20:25 (#6), + span: $DIR/nested-nonterminal-tokens.rs:20:24: 20:25 (#5), }, Literal { kind: Integer, symbol: "3", suffix: None, - span: $DIR/nested-nonterminal-tokens.rs:20:26: 20:27 (#6), + span: $DIR/nested-nonterminal-tokens.rs:20:26: 20:27 (#5), }, ] diff --git a/tests/ui/proc-macro/nodelim-groups.stdout b/tests/ui/proc-macro/nodelim-groups.stdout index 6b410f0bfb7..cdf851b535a 100644 --- a/tests/ui/proc-macro/nodelim-groups.stdout +++ b/tests/ui/proc-macro/nodelim-groups.stdout @@ -4,7 +4,7 @@ PRINT-BANG INPUT (DEBUG): TokenStream [ kind: Str, symbol: "hi", suffix: None, - span: $DIR/nodelim-groups.rs:16:42: 16:46 (#4), + span: $DIR/nodelim-groups.rs:16:42: 16:46 (#3), }, Group { delimiter: None, @@ -44,7 +44,7 @@ PRINT-BANG INPUT (DEBUG): TokenStream [ span: $DIR/nodelim-groups.rs:20:27: 20:28 (#0), }, ], - span: $DIR/nodelim-groups.rs:16:47: 16:51 (#4), + span: $DIR/nodelim-groups.rs:16:47: 16:51 (#3), }, Group { delimiter: Parenthesis, @@ -53,21 +53,21 @@ PRINT-BANG INPUT (DEBUG): TokenStream [ kind: Integer, symbol: "1", suffix: None, - span: $DIR/nodelim-groups.rs:16:53: 16:54 (#4), + span: $DIR/nodelim-groups.rs:16:53: 16:54 (#3), }, Punct { ch: '+', spacing: Alone, - span: $DIR/nodelim-groups.rs:16:55: 16:56 (#4), + span: $DIR/nodelim-groups.rs:16:55: 16:56 (#3), }, Literal { kind: Integer, symbol: "1", suffix: None, - span: $DIR/nodelim-groups.rs:16:57: 16:58 (#4), + span: $DIR/nodelim-groups.rs:16:57: 16:58 (#3), }, ], - span: $DIR/nodelim-groups.rs:16:52: 16:59 (#4), + span: $DIR/nodelim-groups.rs:16:52: 16:59 (#3), }, ] PRINT-BANG INPUT (DISPLAY): "hi" "hello".len() + "world".len() (1 + 1) @@ -76,7 +76,7 @@ PRINT-BANG INPUT (DEBUG): TokenStream [ kind: Str, symbol: "hi", suffix: None, - span: $DIR/nodelim-groups.rs:16:42: 16:46 (#9), + span: $DIR/nodelim-groups.rs:16:42: 16:46 (#8), }, Group { delimiter: None, @@ -105,12 +105,12 @@ PRINT-BANG INPUT (DEBUG): TokenStream [ span: $DIR/nodelim-groups.rs:21:28: 21:30 (#0), }, ], - span: $DIR/nodelim-groups.rs:15:49: 15:54 (#8), + span: $DIR/nodelim-groups.rs:15:49: 15:54 (#7), }, Punct { ch: '+', spacing: Alone, - span: $DIR/nodelim-groups.rs:15:55: 15:56 (#8), + span: $DIR/nodelim-groups.rs:15:55: 15:56 (#7), }, Group { delimiter: None, @@ -136,10 +136,10 @@ PRINT-BANG INPUT (DEBUG): TokenStream [ span: $DIR/nodelim-groups.rs:21:44: 21:46 (#0), }, ], - span: $DIR/nodelim-groups.rs:15:57: 15:62 (#8), + span: $DIR/nodelim-groups.rs:15:57: 15:62 (#7), }, ], - span: $DIR/nodelim-groups.rs:16:47: 16:51 (#9), + span: $DIR/nodelim-groups.rs:16:47: 16:51 (#8), }, Group { delimiter: Parenthesis, @@ -148,20 +148,20 @@ PRINT-BANG INPUT (DEBUG): TokenStream [ kind: Integer, symbol: "1", suffix: None, - span: $DIR/nodelim-groups.rs:16:53: 16:54 (#9), + span: $DIR/nodelim-groups.rs:16:53: 16:54 (#8), }, Punct { ch: '+', spacing: Alone, - span: $DIR/nodelim-groups.rs:16:55: 16:56 (#9), + span: $DIR/nodelim-groups.rs:16:55: 16:56 (#8), }, Literal { kind: Integer, symbol: "1", suffix: None, - span: $DIR/nodelim-groups.rs:16:57: 16:58 (#9), + span: $DIR/nodelim-groups.rs:16:57: 16:58 (#8), }, ], - span: $DIR/nodelim-groups.rs:16:52: 16:59 (#9), + span: $DIR/nodelim-groups.rs:16:52: 16:59 (#8), }, ] diff --git a/tests/ui/proc-macro/nonterminal-expansion.stdout b/tests/ui/proc-macro/nonterminal-expansion.stdout index 4d884348f2c..b2557af18ca 100644 --- a/tests/ui/proc-macro/nonterminal-expansion.stdout +++ b/tests/ui/proc-macro/nonterminal-expansion.stdout @@ -3,12 +3,12 @@ PRINT-ATTR_ARGS RE-COLLECTED (DISPLAY): a, line! (), b PRINT-ATTR_ARGS INPUT (DEBUG): TokenStream [ Ident { ident: "a", - span: $DIR/nonterminal-expansion.rs:13:27: 13:28 (#4), + span: $DIR/nonterminal-expansion.rs:13:27: 13:28 (#3), }, Punct { ch: ',', spacing: Alone, - span: $DIR/nonterminal-expansion.rs:13:28: 13:29 (#4), + span: $DIR/nonterminal-expansion.rs:13:28: 13:29 (#3), }, Group { delimiter: None, @@ -28,15 +28,15 @@ PRINT-ATTR_ARGS INPUT (DEBUG): TokenStream [ span: $DIR/nonterminal-expansion.rs:19:24: 19:26 (#0), }, ], - span: $DIR/nonterminal-expansion.rs:13:30: 13:35 (#4), + span: $DIR/nonterminal-expansion.rs:13:30: 13:35 (#3), }, Punct { ch: ',', spacing: Alone, - span: $DIR/nonterminal-expansion.rs:13:35: 13:36 (#4), + span: $DIR/nonterminal-expansion.rs:13:35: 13:36 (#3), }, Ident { ident: "b", - span: $DIR/nonterminal-expansion.rs:13:37: 13:38 (#4), + span: $DIR/nonterminal-expansion.rs:13:37: 13:38 (#3), }, ] diff --git a/tests/ui/proc-macro/nonterminal-recollect-attr.stdout b/tests/ui/proc-macro/nonterminal-recollect-attr.stdout index 6824395ae40..e722ee97d4c 100644 --- a/tests/ui/proc-macro/nonterminal-recollect-attr.stdout +++ b/tests/ui/proc-macro/nonterminal-recollect-attr.stdout @@ -5,30 +5,30 @@ First recollected: TokenStream [ }, Ident { ident: "struct", - span: $DIR/nonterminal-recollect-attr.rs:14:12: 14:18 (#4), + span: $DIR/nonterminal-recollect-attr.rs:14:12: 14:18 (#3), }, Ident { ident: "Foo", - span: $DIR/nonterminal-recollect-attr.rs:14:19: 14:22 (#4), + span: $DIR/nonterminal-recollect-attr.rs:14:19: 14:22 (#3), }, Group { delimiter: Brace, stream: TokenStream [ Ident { ident: "field", - span: $DIR/nonterminal-recollect-attr.rs:15:13: 15:18 (#4), + span: $DIR/nonterminal-recollect-attr.rs:15:13: 15:18 (#3), }, Punct { ch: ':', spacing: Alone, - span: $DIR/nonterminal-recollect-attr.rs:15:18: 15:19 (#4), + span: $DIR/nonterminal-recollect-attr.rs:15:18: 15:19 (#3), }, Ident { ident: "u8", - span: $DIR/nonterminal-recollect-attr.rs:15:20: 15:22 (#4), + span: $DIR/nonterminal-recollect-attr.rs:15:20: 15:22 (#3), }, ], - span: $DIR/nonterminal-recollect-attr.rs:14:23: 16:10 (#4), + span: $DIR/nonterminal-recollect-attr.rs:14:23: 16:10 (#3), }, ] Second recollected: TokenStream [ @@ -38,29 +38,29 @@ Second recollected: TokenStream [ }, Ident { ident: "struct", - span: $DIR/nonterminal-recollect-attr.rs:14:12: 14:18 (#4), + span: $DIR/nonterminal-recollect-attr.rs:14:12: 14:18 (#3), }, Ident { ident: "Foo", - span: $DIR/nonterminal-recollect-attr.rs:14:19: 14:22 (#4), + span: $DIR/nonterminal-recollect-attr.rs:14:19: 14:22 (#3), }, Group { delimiter: Brace, stream: TokenStream [ Ident { ident: "field", - span: $DIR/nonterminal-recollect-attr.rs:15:13: 15:18 (#4), + span: $DIR/nonterminal-recollect-attr.rs:15:13: 15:18 (#3), }, Punct { ch: ':', spacing: Alone, - span: $DIR/nonterminal-recollect-attr.rs:15:18: 15:19 (#4), + span: $DIR/nonterminal-recollect-attr.rs:15:18: 15:19 (#3), }, Ident { ident: "u8", - span: $DIR/nonterminal-recollect-attr.rs:15:20: 15:22 (#4), + span: $DIR/nonterminal-recollect-attr.rs:15:20: 15:22 (#3), }, ], - span: $DIR/nonterminal-recollect-attr.rs:14:23: 16:10 (#4), + span: $DIR/nonterminal-recollect-attr.rs:14:23: 16:10 (#3), }, ] diff --git a/tests/ui/proc-macro/nonterminal-token-hygiene.stdout b/tests/ui/proc-macro/nonterminal-token-hygiene.stdout index c08e5308138..76d54ab2f13 100644 --- a/tests/ui/proc-macro/nonterminal-token-hygiene.stdout +++ b/tests/ui/proc-macro/nonterminal-token-hygiene.stdout @@ -6,19 +6,19 @@ PRINT-BANG INPUT (DEBUG): TokenStream [ stream: TokenStream [ Ident { ident: "struct", - span: $DIR/nonterminal-token-hygiene.rs:31:5: 31:11 (#5), + span: $DIR/nonterminal-token-hygiene.rs:31:5: 31:11 (#4), }, Ident { ident: "S", - span: $DIR/nonterminal-token-hygiene.rs:31:12: 31:13 (#5), + span: $DIR/nonterminal-token-hygiene.rs:31:12: 31:13 (#4), }, Punct { ch: ';', spacing: Alone, - span: $DIR/nonterminal-token-hygiene.rs:31:13: 31:14 (#5), + span: $DIR/nonterminal-token-hygiene.rs:31:13: 31:14 (#4), }, ], - span: $DIR/nonterminal-token-hygiene.rs:21:27: 21:32 (#6), + span: $DIR/nonterminal-token-hygiene.rs:21:27: 21:32 (#5), }, ] #![feature /* 0#0 */(prelude_import)] @@ -39,8 +39,7 @@ PRINT-BANG INPUT (DEBUG): TokenStream [ use ::core /* 0#1 */::prelude /* 0#1 */::rust_2015 /* 0#1 */::*; #[macro_use /* 0#1 */] extern crate core /* 0#2 */; -#[macro_use /* 0#1 */] -extern crate compiler_builtins /* 0#2 */; +extern crate compiler_builtins /* 442 */ as _ /* 0#2 */; // Don't load unnecessary hygiene information from std extern crate std /* 0#0 */; @@ -59,9 +58,9 @@ macro_rules! outer } struct S /* 0#0 */; -macro inner /* 0#4 */ { () => { print_bang! { struct S; } } } +macro inner /* 0#3 */ { () => { print_bang! { struct S; } } } -struct S /* 0#5 */; +struct S /* 0#4 */; // OK, not a duplicate definition of `S` fn main /* 0#0 */() {} @@ -71,22 +70,20 @@ Expansions: crate0::{{expn0}}: parent: crate0::{{expn0}}, call_site_ctxt: #0, def_site_ctxt: #0, kind: Root crate0::{{expn1}}: parent: crate0::{{expn0}}, call_site_ctxt: #0, def_site_ctxt: #0, kind: AstPass(StdImports) crate0::{{expn2}}: parent: crate0::{{expn0}}, call_site_ctxt: #0, def_site_ctxt: #0, kind: Macro(Bang, "outer") -crate0::{{expn3}}: parent: crate0::{{expn2}}, call_site_ctxt: #4, def_site_ctxt: #4, kind: Macro(Bang, "inner") -crate0::{{expn4}}: parent: crate0::{{expn3}}, call_site_ctxt: #6, def_site_ctxt: #0, kind: Macro(Bang, "print_bang") +crate0::{{expn3}}: parent: crate0::{{expn2}}, call_site_ctxt: #3, def_site_ctxt: #3, kind: Macro(Bang, "inner") +crate0::{{expn4}}: parent: crate0::{{expn3}}, call_site_ctxt: #5, def_site_ctxt: #0, kind: Macro(Bang, "print_bang") crate1::{{expnNNN}}: parent: crate0::{{expn0}}, call_site_ctxt: #0, def_site_ctxt: #0, kind: Macro(Attr, "derive") crate1::{{expnNNN}}: parent: crate0::{{expn0}}, call_site_ctxt: #0, def_site_ctxt: #0, kind: Macro(Attr, "derive") crate1::{{expnNNN}}: parent: crate0::{{expn0}}, call_site_ctxt: #0, def_site_ctxt: #0, kind: Macro(Bang, "include") -crate2::{{expn1}}: parent: crate0::{{expn0}}, call_site_ctxt: #0, def_site_ctxt: #0, kind: AstPass(StdImports) SyntaxContexts: #0: parent: #0, outer_mark: (crate0::{{expn0}}, Opaque) #1: parent: #0, outer_mark: (crate0::{{expn1}}, Opaque) #2: parent: #0, outer_mark: (crate0::{{expn1}}, Transparent) -#3: parent: #0, outer_mark: (crate2::{{expn1}}, Opaque) -#4: parent: #0, outer_mark: (crate0::{{expn2}}, SemiTransparent) -#5: parent: #0, outer_mark: (crate0::{{expn3}}, Opaque) -#6: parent: #4, outer_mark: (crate0::{{expn3}}, Opaque) -#7: parent: #0, outer_mark: (crate0::{{expn4}}, Opaque) -#8: parent: #6, outer_mark: (crate0::{{expn4}}, Transparent) -#9: parent: #5, outer_mark: (crate0::{{expn4}}, SemiTransparent) +#3: parent: #0, outer_mark: (crate0::{{expn2}}, SemiTransparent) +#4: parent: #0, outer_mark: (crate0::{{expn3}}, Opaque) +#5: parent: #3, outer_mark: (crate0::{{expn3}}, Opaque) +#6: parent: #0, outer_mark: (crate0::{{expn4}}, Opaque) +#7: parent: #5, outer_mark: (crate0::{{expn4}}, Transparent) +#8: parent: #4, outer_mark: (crate0::{{expn4}}, SemiTransparent) */ diff --git a/tests/ui/regions/region-object-lifetime-5.rs b/tests/ui/regions/region-object-lifetime-5.rs index ad359367168..307bbcbd58d 100644 --- a/tests/ui/regions/region-object-lifetime-5.rs +++ b/tests/ui/regions/region-object-lifetime-5.rs @@ -8,7 +8,7 @@ trait Foo { // Here, the object is bounded by an anonymous lifetime and returned // as `&'static`, so you get an error. fn owned_receiver(x: Box<dyn Foo>) -> &'static () { - x.borrowed() //~ ERROR cannot return reference to local data `*x` + x.borrowed() //~ ERROR cannot return value referencing local data `*x` } fn main() {} diff --git a/tests/ui/regions/region-object-lifetime-5.stderr b/tests/ui/regions/region-object-lifetime-5.stderr index b82b58c7a8e..b86f6e3a2a1 100644 --- a/tests/ui/regions/region-object-lifetime-5.stderr +++ b/tests/ui/regions/region-object-lifetime-5.stderr @@ -1,8 +1,11 @@ -error[E0515]: cannot return reference to local data `*x` +error[E0515]: cannot return value referencing local data `*x` --> $DIR/region-object-lifetime-5.rs:11:5 | LL | x.borrowed() - | ^^^^^^^^^^^^ returns a reference to data owned by the current function + | -^^^^^^^^^^^ + | | + | returns a value referencing data owned by the current function + | `*x` is borrowed here error: aborting due to previous error diff --git a/tests/ui/resolve/bad-expr-path.stderr b/tests/ui/resolve/bad-expr-path.stderr index 8261e8e53b0..411130913c8 100644 --- a/tests/ui/resolve/bad-expr-path.stderr +++ b/tests/ui/resolve/bad-expr-path.stderr @@ -10,12 +10,6 @@ error[E0425]: cannot find value `arguments` in module `m1` LL | log(debug, m1::arguments); | ^^^^^^^^^ not found in `m1` -error[E0425]: cannot find function `log` in this scope - --> $DIR/bad-expr-path.rs:4:5 - | -LL | log(debug, m1::arguments); - | ^^^ not found in this scope - error[E0580]: `main` function has wrong type --> $DIR/bad-expr-path.rs:3:1 | @@ -25,6 +19,12 @@ LL | fn main(arguments: Vec<String>) { = note: expected fn pointer `fn()` found fn pointer `fn(Vec<String>)` +error[E0425]: cannot find function `log` in this scope + --> $DIR/bad-expr-path.rs:4:5 + | +LL | log(debug, m1::arguments); + | ^^^ not found in this scope + error: aborting due to 4 previous errors Some errors have detailed explanations: E0425, E0580. diff --git a/tests/ui/resolve/bad-expr-path2.stderr b/tests/ui/resolve/bad-expr-path2.stderr index 6e11296d9fc..af3ca99c510 100644 --- a/tests/ui/resolve/bad-expr-path2.stderr +++ b/tests/ui/resolve/bad-expr-path2.stderr @@ -10,12 +10,6 @@ error[E0423]: expected value, found module `m1::arguments` LL | log(debug, m1::arguments); | ^^^^^^^^^^^^^ not a value -error[E0425]: cannot find function `log` in this scope - --> $DIR/bad-expr-path2.rs:6:5 - | -LL | log(debug, m1::arguments); - | ^^^ not found in this scope - error[E0580]: `main` function has wrong type --> $DIR/bad-expr-path2.rs:5:1 | @@ -25,6 +19,12 @@ LL | fn main(arguments: Vec<String>) { = note: expected fn pointer `fn()` found fn pointer `fn(Vec<String>)` +error[E0425]: cannot find function `log` in this scope + --> $DIR/bad-expr-path2.rs:6:5 + | +LL | log(debug, m1::arguments); + | ^^^ not found in this scope + error: aborting due to 4 previous errors Some errors have detailed explanations: E0423, E0425, E0580. diff --git a/tests/ui/resolve/unused-qualifications-suggestion.fixed b/tests/ui/resolve/unused-qualifications-suggestion.fixed new file mode 100644 index 00000000000..0d4b9007c7b --- /dev/null +++ b/tests/ui/resolve/unused-qualifications-suggestion.fixed @@ -0,0 +1,23 @@ +// run-rustfix + +#![deny(unused_qualifications)] + +mod foo { + pub fn bar() {} +} + +mod baz { + pub mod qux { + pub fn quux() {} + } +} + +fn main() { + use foo::bar; + bar(); + //~^ ERROR unnecessary qualification + + use baz::qux::quux; + quux(); + //~^ ERROR unnecessary qualification +} diff --git a/tests/ui/resolve/unused-qualifications-suggestion.rs b/tests/ui/resolve/unused-qualifications-suggestion.rs new file mode 100644 index 00000000000..f6722e96537 --- /dev/null +++ b/tests/ui/resolve/unused-qualifications-suggestion.rs @@ -0,0 +1,23 @@ +// run-rustfix + +#![deny(unused_qualifications)] + +mod foo { + pub fn bar() {} +} + +mod baz { + pub mod qux { + pub fn quux() {} + } +} + +fn main() { + use foo::bar; + foo::bar(); + //~^ ERROR unnecessary qualification + + use baz::qux::quux; + baz::qux::quux(); + //~^ ERROR unnecessary qualification +} diff --git a/tests/ui/resolve/unused-qualifications-suggestion.stderr b/tests/ui/resolve/unused-qualifications-suggestion.stderr new file mode 100644 index 00000000000..c8e91e07295 --- /dev/null +++ b/tests/ui/resolve/unused-qualifications-suggestion.stderr @@ -0,0 +1,29 @@ +error: unnecessary qualification + --> $DIR/unused-qualifications-suggestion.rs:17:5 + | +LL | foo::bar(); + | ^^^^^^^^ + | +note: the lint level is defined here + --> $DIR/unused-qualifications-suggestion.rs:3:9 + | +LL | #![deny(unused_qualifications)] + | ^^^^^^^^^^^^^^^^^^^^^ +help: replace it with the unqualified path + | +LL | bar(); + | ~~~ + +error: unnecessary qualification + --> $DIR/unused-qualifications-suggestion.rs:21:5 + | +LL | baz::qux::quux(); + | ^^^^^^^^^^^^^^ + | +help: replace it with the unqualified path + | +LL | quux(); + | ~~~~ + +error: aborting due to 2 previous errors + diff --git a/tests/ui/rfcs/rfc-2005-default-binding-mode/borrowck-issue-49631.stderr b/tests/ui/rfcs/rfc-2005-default-binding-mode/borrowck-issue-49631.stderr index b7c0b0bb6b9..04572920ee4 100644 --- a/tests/ui/rfcs/rfc-2005-default-binding-mode/borrowck-issue-49631.stderr +++ b/tests/ui/rfcs/rfc-2005-default-binding-mode/borrowck-issue-49631.stderr @@ -2,7 +2,7 @@ error[E0502]: cannot borrow `foo` as mutable because it is also borrowed as immu --> $DIR/borrowck-issue-49631.rs:20:9 | LL | while let Some(Ok(string)) = foo.get() { - | --------- immutable borrow occurs here + | --- immutable borrow occurs here LL | foo.mutate(); | ^^^^^^^^^^^^ mutable borrow occurs here LL | diff --git a/tests/ui/sanitize/address.rs b/tests/ui/sanitize/address.rs index 5b2cea87560..1faab1fd2fc 100644 --- a/tests/ui/sanitize/address.rs +++ b/tests/ui/sanitize/address.rs @@ -1,11 +1,12 @@ // needs-sanitizer-support // needs-sanitizer-address +// ignore-cross-compile // // compile-flags: -Z sanitizer=address -O -g // // run-fail // error-pattern: AddressSanitizer: stack-buffer-overflow -// error-pattern: 'xs' (line 13) <== Memory access at offset +// error-pattern: 'xs' (line 14) <== Memory access at offset use std::hint::black_box; diff --git a/tests/ui/sanitize/badfree.rs b/tests/ui/sanitize/badfree.rs index 095a6f4697b..c8d1ce7dff2 100644 --- a/tests/ui/sanitize/badfree.rs +++ b/tests/ui/sanitize/badfree.rs @@ -1,5 +1,6 @@ // needs-sanitizer-support // needs-sanitizer-address +// ignore-cross-compile // // compile-flags: -Z sanitizer=address -O // diff --git a/tests/ui/sanitize/issue-72154-lifetime-markers.rs b/tests/ui/sanitize/issue-72154-lifetime-markers.rs index b2e182238ce..3d9c51daa65 100644 --- a/tests/ui/sanitize/issue-72154-lifetime-markers.rs +++ b/tests/ui/sanitize/issue-72154-lifetime-markers.rs @@ -5,6 +5,7 @@ // // needs-sanitizer-support // needs-sanitizer-address +// ignore-cross-compile // // compile-flags: -Copt-level=0 -Zsanitizer=address // run-pass diff --git a/tests/ui/sanitize/new-llvm-pass-manager-thin-lto.rs b/tests/ui/sanitize/new-llvm-pass-manager-thin-lto.rs index 33e18e35522..052a40598a8 100644 --- a/tests/ui/sanitize/new-llvm-pass-manager-thin-lto.rs +++ b/tests/ui/sanitize/new-llvm-pass-manager-thin-lto.rs @@ -4,6 +4,7 @@ // // needs-sanitizer-support // needs-sanitizer-address +// ignore-cross-compile // // no-prefer-dynamic // revisions: opt0 opt1 diff --git a/tests/ui/sanitize/use-after-scope.rs b/tests/ui/sanitize/use-after-scope.rs index 30be2ae6f09..de63eea194b 100644 --- a/tests/ui/sanitize/use-after-scope.rs +++ b/tests/ui/sanitize/use-after-scope.rs @@ -1,5 +1,6 @@ // needs-sanitizer-support // needs-sanitizer-address +// ignore-cross-compile // // compile-flags: -Zsanitizer=address // run-fail diff --git a/tests/ui/span/borrowck-borrow-overloaded-auto-deref-mut.stderr b/tests/ui/span/borrowck-borrow-overloaded-auto-deref-mut.stderr index 80c5f9da40c..4aad8843759 100644 --- a/tests/ui/span/borrowck-borrow-overloaded-auto-deref-mut.stderr +++ b/tests/ui/span/borrowck-borrow-overloaded-auto-deref-mut.stderr @@ -66,7 +66,7 @@ error[E0596]: cannot borrow `x` as mutable, as it is not declared as mutable --> $DIR/borrowck-borrow-overloaded-auto-deref-mut.rs:109:5 | LL | x.set(0, 0); - | ^^^^^^^^^^^ cannot borrow as mutable + | ^ cannot borrow as mutable | help: consider changing this to be mutable | @@ -77,7 +77,7 @@ error[E0596]: cannot borrow `*x` as mutable, as it is behind a `&` reference --> $DIR/borrowck-borrow-overloaded-auto-deref-mut.rs:121:5 | LL | x.y_mut() - | ^^^^^^^^^ `x` is a `&` reference, so the data it refers to cannot be borrowed as mutable + | ^ `x` is a `&` reference, so the data it refers to cannot be borrowed as mutable | help: consider changing this to be a mutable reference | @@ -88,7 +88,7 @@ error[E0596]: cannot borrow `x` as mutable, as it is not declared as mutable --> $DIR/borrowck-borrow-overloaded-auto-deref-mut.rs:129:6 | LL | *x.y_mut() = 3; - | ^^^^^^^^^ cannot borrow as mutable + | ^ cannot borrow as mutable | help: consider changing this to be mutable | @@ -99,7 +99,7 @@ error[E0596]: cannot borrow `*x` as mutable, as it is behind a `&` reference --> $DIR/borrowck-borrow-overloaded-auto-deref-mut.rs:133:6 | LL | *x.y_mut() = 3; - | ^^^^^^^^^ `x` is a `&` reference, so the data it refers to cannot be borrowed as mutable + | ^ `x` is a `&` reference, so the data it refers to cannot be borrowed as mutable | help: consider changing this to be a mutable reference | diff --git a/tests/ui/span/borrowck-call-is-borrow-issue-12224.stderr b/tests/ui/span/borrowck-call-is-borrow-issue-12224.stderr index 99c8fa1f932..ba8da2e7560 100644 --- a/tests/ui/span/borrowck-call-is-borrow-issue-12224.stderr +++ b/tests/ui/span/borrowck-call-is-borrow-issue-12224.stderr @@ -25,7 +25,7 @@ error[E0596]: cannot borrow `f.f` as mutable, as it is behind a `&` reference --> $DIR/borrowck-call-is-borrow-issue-12224.rs:34:5 | LL | f.f.call_mut(()) - | ^^^^^^^^^^^^^^^^ `f` is a `&` reference, so the data it refers to cannot be borrowed as mutable + | ^^^ `f` is a `&` reference, so the data it refers to cannot be borrowed as mutable | help: consider changing this to be a mutable reference | diff --git a/tests/ui/span/borrowck-call-method-from-mut-aliasable.stderr b/tests/ui/span/borrowck-call-method-from-mut-aliasable.stderr index 328197ae9f4..3f033f5e47b 100644 --- a/tests/ui/span/borrowck-call-method-from-mut-aliasable.stderr +++ b/tests/ui/span/borrowck-call-method-from-mut-aliasable.stderr @@ -2,7 +2,7 @@ error[E0596]: cannot borrow `*x` as mutable, as it is behind a `&` reference --> $DIR/borrowck-call-method-from-mut-aliasable.rs:17:5 | LL | x.h(); - | ^^^^^ `x` is a `&` reference, so the data it refers to cannot be borrowed as mutable + | ^ `x` is a `&` reference, so the data it refers to cannot be borrowed as mutable | help: consider changing this to be a mutable reference | diff --git a/tests/ui/span/borrowck-fn-in-const-b.stderr b/tests/ui/span/borrowck-fn-in-const-b.stderr index 17fdcc622f7..92987802629 100644 --- a/tests/ui/span/borrowck-fn-in-const-b.stderr +++ b/tests/ui/span/borrowck-fn-in-const-b.stderr @@ -2,7 +2,7 @@ error[E0596]: cannot borrow `*x` as mutable, as it is behind a `&` reference --> $DIR/borrowck-fn-in-const-b.rs:7:9 | LL | x.push(format!("this is broken")); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `x` is a `&` reference, so the data it refers to cannot be borrowed as mutable + | ^ `x` is a `&` reference, so the data it refers to cannot be borrowed as mutable | help: consider changing this to be a mutable reference | diff --git a/tests/ui/span/borrowck-let-suggestion-suffixes.stderr b/tests/ui/span/borrowck-let-suggestion-suffixes.stderr index 545b235a552..78cadc8c694 100644 --- a/tests/ui/span/borrowck-let-suggestion-suffixes.stderr +++ b/tests/ui/span/borrowck-let-suggestion-suffixes.stderr @@ -39,7 +39,7 @@ LL | v4.push(&id('y')); | creates a temporary value which is freed while still in use ... LL | v4.use_ref(); - | ------------ borrow later used here + | -- borrow later used here | = note: consider using a `let` binding to create a longer lived value diff --git a/tests/ui/span/borrowck-object-mutability.stderr b/tests/ui/span/borrowck-object-mutability.stderr index 805a8034c18..e4b5c8ce71f 100644 --- a/tests/ui/span/borrowck-object-mutability.stderr +++ b/tests/ui/span/borrowck-object-mutability.stderr @@ -2,7 +2,7 @@ error[E0596]: cannot borrow `*x` as mutable, as it is behind a `&` reference --> $DIR/borrowck-object-mutability.rs:8:5 | LL | x.borrowed_mut(); - | ^^^^^^^^^^^^^^^^ `x` is a `&` reference, so the data it refers to cannot be borrowed as mutable + | ^ `x` is a `&` reference, so the data it refers to cannot be borrowed as mutable | help: consider changing this to be a mutable reference | @@ -13,7 +13,7 @@ error[E0596]: cannot borrow `*x` as mutable, as `x` is not declared as mutable --> $DIR/borrowck-object-mutability.rs:18:5 | LL | x.borrowed_mut(); - | ^^^^^^^^^^^^^^^^ cannot borrow as mutable + | ^ cannot borrow as mutable | help: consider changing this to be mutable | diff --git a/tests/ui/span/destructor-restrictions.stderr b/tests/ui/span/destructor-restrictions.stderr index 281248626c8..b923cee5f0e 100644 --- a/tests/ui/span/destructor-restrictions.stderr +++ b/tests/ui/span/destructor-restrictions.stderr @@ -4,7 +4,7 @@ error[E0597]: `*a` does not live long enough LL | let a = Box::new(RefCell::new(4)); | - binding `a` declared here LL | *a.borrow() + 1 - | ^^^^^^^^^^ + | ^--------- | | | borrowed value does not live long enough | a temporary with access to the borrow is created here ... diff --git a/tests/ui/span/issue-23338-locals-die-before-temps-of-body.stderr b/tests/ui/span/issue-23338-locals-die-before-temps-of-body.stderr index e1a377203e2..421c2256699 100644 --- a/tests/ui/span/issue-23338-locals-die-before-temps-of-body.stderr +++ b/tests/ui/span/issue-23338-locals-die-before-temps-of-body.stderr @@ -4,7 +4,7 @@ error[E0597]: `y` does not live long enough LL | let y = x; | - binding `y` declared here LL | y.borrow().clone() - | ^^^^^^^^^^ + | ^--------- | | | borrowed value does not live long enough | a temporary with access to the borrow is created here ... @@ -27,7 +27,7 @@ error[E0597]: `y` does not live long enough LL | let y = x; | - binding `y` declared here LL | y.borrow().clone() - | ^^^^^^^^^^ + | ^--------- | | | borrowed value does not live long enough | a temporary with access to the borrow is created here ... diff --git a/tests/ui/span/issue-36537.stderr b/tests/ui/span/issue-36537.stderr index 6c330c1a094..8dfee8d644b 100644 --- a/tests/ui/span/issue-36537.stderr +++ b/tests/ui/span/issue-36537.stderr @@ -9,7 +9,7 @@ LL | p = &a; LL | } | - `a` dropped here while still borrowed LL | p.use_ref(); - | ----------- borrow later used here + | - borrow later used here error: aborting due to previous error diff --git a/tests/ui/span/issue-40157.stderr b/tests/ui/span/issue-40157.stderr index a0afd33f7c7..2168767178d 100644 --- a/tests/ui/span/issue-40157.stderr +++ b/tests/ui/span/issue-40157.stderr @@ -2,7 +2,7 @@ error[E0597]: `foo` does not live long enough --> $DIR/issue-40157.rs:2:53 | LL | {println!("{:?}", match { let foo = vec![1, 2]; foo.get(1) } { x => x });} - | --- ^^^^^^^^^^ - `foo` dropped here while still borrowed + | --- ^^^ - `foo` dropped here while still borrowed | | | | | borrowed value does not live long enough | binding `foo` declared here diff --git a/tests/ui/span/mut-arg-hint.stderr b/tests/ui/span/mut-arg-hint.stderr index 06011eac674..df782280b8a 100644 --- a/tests/ui/span/mut-arg-hint.stderr +++ b/tests/ui/span/mut-arg-hint.stderr @@ -2,7 +2,7 @@ error[E0596]: cannot borrow `*a` as mutable, as it is behind a `&` reference --> $DIR/mut-arg-hint.rs:3:9 | LL | a.push_str("bar"); - | ^^^^^^^^^^^^^^^^^ `a` is a `&` reference, so the data it refers to cannot be borrowed as mutable + | ^ `a` is a `&` reference, so the data it refers to cannot be borrowed as mutable | help: consider changing this to be a mutable reference | @@ -13,7 +13,7 @@ error[E0596]: cannot borrow `*a` as mutable, as it is behind a `&` reference --> $DIR/mut-arg-hint.rs:8:5 | LL | a.push_str("foo"); - | ^^^^^^^^^^^^^^^^^ `a` is a `&` reference, so the data it refers to cannot be borrowed as mutable + | ^ `a` is a `&` reference, so the data it refers to cannot be borrowed as mutable | help: consider changing this to be a mutable reference | @@ -24,7 +24,7 @@ error[E0596]: cannot borrow `*a` as mutable, as it is behind a `&` reference --> $DIR/mut-arg-hint.rs:15:9 | LL | a.push_str("foo"); - | ^^^^^^^^^^^^^^^^^ `a` is a `&` reference, so the data it refers to cannot be borrowed as mutable + | ^ `a` is a `&` reference, so the data it refers to cannot be borrowed as mutable | help: consider changing this to be a mutable reference | diff --git a/tests/ui/span/mut-ptr-cant-outlive-ref.stderr b/tests/ui/span/mut-ptr-cant-outlive-ref.stderr index be56f9489c7..395b6ec6791 100644 --- a/tests/ui/span/mut-ptr-cant-outlive-ref.stderr +++ b/tests/ui/span/mut-ptr-cant-outlive-ref.stderr @@ -9,7 +9,7 @@ LL | } | - `b` dropped here while still borrowed LL | LL | p.use_ref(); - | ----------- borrow later used here + | - borrow later used here error: aborting due to previous error diff --git a/tests/ui/span/regionck-unboxed-closure-lifetimes.stderr b/tests/ui/span/regionck-unboxed-closure-lifetimes.stderr index fb3fad6ae90..9b5ec84614c 100644 --- a/tests/ui/span/regionck-unboxed-closure-lifetimes.stderr +++ b/tests/ui/span/regionck-unboxed-closure-lifetimes.stderr @@ -9,7 +9,7 @@ LL | let c_ref = &c; LL | } | - `c` dropped here while still borrowed LL | f.use_mut(); - | ----------- borrow later used here + | - borrow later used here error: aborting due to previous error diff --git a/tests/ui/span/regions-escape-loop-via-vec.stderr b/tests/ui/span/regions-escape-loop-via-vec.stderr index 532ac3606c5..18c6cd48093 100644 --- a/tests/ui/span/regions-escape-loop-via-vec.stderr +++ b/tests/ui/span/regions-escape-loop-via-vec.stderr @@ -7,7 +7,7 @@ LL | while x < 10 { | ^ use of borrowed `x` LL | let mut z = x; LL | _y.push(&mut z); - | --------------- borrow later used here + | -- borrow later used here error[E0503]: cannot use `x` because it was mutably borrowed --> $DIR/regions-escape-loop-via-vec.rs:6:21 @@ -18,7 +18,7 @@ LL | while x < 10 { LL | let mut z = x; | ^ use of borrowed `x` LL | _y.push(&mut z); - | --------------- borrow later used here + | -- borrow later used here error[E0597]: `z` does not live long enough --> $DIR/regions-escape-loop-via-vec.rs:7:17 @@ -26,7 +26,9 @@ error[E0597]: `z` does not live long enough LL | let mut z = x; | ----- binding `z` declared here LL | _y.push(&mut z); - | ^^^^^^ borrowed value does not live long enough + | -- ^^^^^^ borrowed value does not live long enough + | | + | borrow later used here ... LL | } | - `z` dropped here while still borrowed @@ -38,7 +40,7 @@ LL | let mut _y = vec![&mut x]; | ------ `x` is borrowed here ... LL | _y.push(&mut z); - | --------------- borrow later used here + | -- borrow later used here LL | LL | x += 1; | ^^^^^^ use of borrowed `x` diff --git a/tests/ui/span/send-is-not-static-std-sync.stderr b/tests/ui/span/send-is-not-static-std-sync.stderr index 7dfe94bca60..eaba415adaa 100644 --- a/tests/ui/span/send-is-not-static-std-sync.stderr +++ b/tests/ui/span/send-is-not-static-std-sync.stderr @@ -10,7 +10,7 @@ LL | drop(y); | ^ move out of `y` occurs here ... LL | *lock.lock().unwrap() = &z; - | ----------- borrow later used here + | ---- borrow later used here error[E0597]: `z` does not live long enough --> $DIR/send-is-not-static-std-sync.rs:16:33 @@ -23,7 +23,7 @@ LL | } | - `z` dropped here while still borrowed LL | LL | lock.use_ref(); // (Mutex is #[may_dangle] so its dtor does not use `z` => needs explicit use) - | -------------- borrow later used here + | ---- borrow later used here error[E0505]: cannot move out of `y` because it is borrowed --> $DIR/send-is-not-static-std-sync.rs:27:10 @@ -37,7 +37,7 @@ LL | drop(y); | ^ move out of `y` occurs here ... LL | *lock.write().unwrap() = &z; - | ------------ borrow later used here + | ---- borrow later used here error[E0597]: `z` does not live long enough --> $DIR/send-is-not-static-std-sync.rs:30:34 @@ -50,7 +50,7 @@ LL | } | - `z` dropped here while still borrowed LL | LL | lock.use_ref(); // (RwLock is #[may_dangle] so its dtor does not use `z` => needs explicit use) - | -------------- borrow later used here + | ---- borrow later used here error[E0505]: cannot move out of `y` because it is borrowed --> $DIR/send-is-not-static-std-sync.rs:43:10 @@ -64,7 +64,7 @@ LL | drop(y); | ^ move out of `y` occurs here ... LL | tx.send(&z).unwrap(); - | ----------- borrow later used here + | -- borrow later used here error[E0597]: `z` does not live long enough --> $DIR/send-is-not-static-std-sync.rs:46:17 diff --git a/tests/ui/span/slice-borrow.stderr b/tests/ui/span/slice-borrow.stderr index b70bf69d688..b271c9ae6f6 100644 --- a/tests/ui/span/slice-borrow.stderr +++ b/tests/ui/span/slice-borrow.stderr @@ -7,7 +7,7 @@ LL | let x: &[isize] = &vec![1, 2, 3, 4, 5]; LL | } | - temporary value is freed at the end of this statement LL | y.use_ref(); - | ----------- borrow later used here + | - borrow later used here | = note: consider using a `let` binding to create a longer lived value = note: this error originates in the macro `vec` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/tests/ui/suggestions/impl-on-dyn-trait-with-implicit-static-bound-needing-more-suggestions.rs b/tests/ui/suggestions/impl-on-dyn-trait-with-implicit-static-bound-needing-more-suggestions.rs index 711cbbd381a..255cab06070 100644 --- a/tests/ui/suggestions/impl-on-dyn-trait-with-implicit-static-bound-needing-more-suggestions.rs +++ b/tests/ui/suggestions/impl-on-dyn-trait-with-implicit-static-bound-needing-more-suggestions.rs @@ -18,7 +18,7 @@ mod bav { impl Bar for i32 {} fn use_it<'a>(val: Box<dyn ObjectTrait<Assoc = i32>>) -> impl OtherTrait<'a> { - val.use_self() //~ ERROR cannot return reference to function parameter + val.use_self() //~ ERROR cannot return value referencing function parameter } } diff --git a/tests/ui/suggestions/impl-on-dyn-trait-with-implicit-static-bound-needing-more-suggestions.stderr b/tests/ui/suggestions/impl-on-dyn-trait-with-implicit-static-bound-needing-more-suggestions.stderr index 2dc300ac76f..a7e03f491b9 100644 --- a/tests/ui/suggestions/impl-on-dyn-trait-with-implicit-static-bound-needing-more-suggestions.stderr +++ b/tests/ui/suggestions/impl-on-dyn-trait-with-implicit-static-bound-needing-more-suggestions.stderr @@ -1,20 +1,29 @@ -error[E0515]: cannot return reference to function parameter `val` +error[E0515]: cannot return value referencing function parameter `val` --> $DIR/impl-on-dyn-trait-with-implicit-static-bound-needing-more-suggestions.rs:21:9 | LL | val.use_self() - | ^^^^^^^^^^^^^^ returns a reference to data owned by the current function + | ---^^^^^^^^^^^ + | | + | returns a value referencing data owned by the current function + | `val` is borrowed here -error[E0515]: cannot return reference to function parameter `val` +error[E0515]: cannot return value referencing function parameter `val` --> $DIR/impl-on-dyn-trait-with-implicit-static-bound-needing-more-suggestions.rs:43:9 | LL | val.use_self() - | ^^^^^^^^^^^^^^ returns a reference to data owned by the current function + | ---^^^^^^^^^^^ + | | + | returns a value referencing data owned by the current function + | `val` is borrowed here -error[E0515]: cannot return reference to function parameter `val` +error[E0515]: cannot return value referencing function parameter `val` --> $DIR/impl-on-dyn-trait-with-implicit-static-bound-needing-more-suggestions.rs:109:9 | LL | val.use_self() - | ^^^^^^^^^^^^^^ returns a reference to data owned by the current function + | ---^^^^^^^^^^^ + | | + | returns a value referencing data owned by the current function + | `val` is borrowed here error: aborting due to 3 previous errors diff --git a/tests/ui/suggestions/issue-102972.stderr b/tests/ui/suggestions/issue-102972.stderr index 03f9dbb6c89..3303d6bbc3f 100644 --- a/tests/ui/suggestions/issue-102972.stderr +++ b/tests/ui/suggestions/issue-102972.stderr @@ -7,10 +7,7 @@ LL | for _c in chars.by_ref() { | first mutable borrow occurs here | first borrow later used here LL | chars.next(); - | ^^^^^^^^^^^^ second mutable borrow occurs here - | - = note: a for loop advances the iterator for you, the result is stored in `_c`. - = help: if you want to call `next` on a iterator within the loop, consider using `while let`. + | ^^^^^ second mutable borrow occurs here error[E0382]: borrow of moved value: `iter` --> $DIR/issue-102972.rs:12:9 @@ -20,10 +17,8 @@ LL | let mut iter = v.iter(); LL | for _i in iter { | ---- `iter` moved due to this implicit call to `.into_iter()` LL | iter.next(); - | ^^^^^^^^^^^ value borrowed here after move + | ^^^^ value borrowed here after move | - = note: a for loop advances the iterator for you, the result is stored in `_i`. - = help: if you want to call `next` on a iterator within the loop, consider using `while let`. note: `into_iter` takes ownership of the receiver `self`, which moves `iter` --> $SRC_DIR/core/src/iter/traits/collect.rs:LL:COL diff --git a/tests/ui/suggestions/option-content-move.stderr b/tests/ui/suggestions/option-content-move.stderr index 474a72093c6..5060606d842 100644 --- a/tests/ui/suggestions/option-content-move.stderr +++ b/tests/ui/suggestions/option-content-move.stderr @@ -12,7 +12,7 @@ note: `Option::<T>::unwrap` takes ownership of the receiver `self`, which moves help: you can `clone` the value and consume it, but this might not be your desired behavior | LL | if selection.1.clone().unwrap().contains(selection.0) { - | ++++++++ + | ++++++++ error[E0507]: cannot move out of `selection.1` which is behind a shared reference --> $DIR/option-content-move.rs:27:20 @@ -28,7 +28,7 @@ note: `Result::<T, E>::unwrap` takes ownership of the receiver `self`, which mov help: you can `clone` the value and consume it, but this might not be your desired behavior | LL | if selection.1.clone().unwrap().contains(selection.0) { - | ++++++++ + | ++++++++ error: aborting due to 2 previous errors diff --git a/tests/ui/suggestions/suggest-mut-method-for-loop-closure.rs b/tests/ui/suggestions/suggest-mut-method-for-loop-closure.rs new file mode 100644 index 00000000000..e4721ba0193 --- /dev/null +++ b/tests/ui/suggestions/suggest-mut-method-for-loop-closure.rs @@ -0,0 +1,19 @@ +use std::collections::HashMap; +struct X(usize); +struct Y { + v: u32, +} + +fn main() { + let _ = || { + let mut buzz = HashMap::new(); + buzz.insert("a", Y { v: 0 }); + + for mut t in buzz.values() { + //~^ HELP + //~| SUGGESTION values_mut() + t.v += 1; + //~^ ERROR cannot assign + } + }; +} diff --git a/tests/ui/suggestions/suggest-mut-method-for-loop-closure.stderr b/tests/ui/suggestions/suggest-mut-method-for-loop-closure.stderr new file mode 100644 index 00000000000..8a2df8d7cc1 --- /dev/null +++ b/tests/ui/suggestions/suggest-mut-method-for-loop-closure.stderr @@ -0,0 +1,15 @@ +error[E0594]: cannot assign to `t.v`, which is behind a `&` reference + --> $DIR/suggest-mut-method-for-loop-closure.rs:15:13 + | +LL | for mut t in buzz.values() { + | ------------- + | | | + | | help: use mutable method: `values_mut()` + | this iterator yields `&` references +... +LL | t.v += 1; + | ^^^^^^^^ `t` is a `&` reference, so the data it refers to cannot be written + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0594`. diff --git a/tests/ui/thir-print/thir-flat-const-variant.stdout b/tests/ui/thir-print/thir-flat-const-variant.stdout index 1b76f07c318..7bddc925996 100644 --- a/tests/ui/thir-print/thir-flat-const-variant.stdout +++ b/tests/ui/thir-print/thir-flat-const-variant.stdout @@ -35,7 +35,7 @@ Thir { AdtExpr { adt_def: Foo, variant_index: 0, - substs: [], + args: [], user_ty: None, fields: [ FieldExpr { @@ -120,7 +120,7 @@ Thir { AdtExpr { adt_def: Foo, variant_index: 0, - substs: [], + args: [], user_ty: None, fields: [ FieldExpr { @@ -205,7 +205,7 @@ Thir { AdtExpr { adt_def: Foo, variant_index: 0, - substs: [], + args: [], user_ty: None, fields: [ FieldExpr { @@ -290,7 +290,7 @@ Thir { AdtExpr { adt_def: Foo, variant_index: 0, - substs: [], + args: [], user_ty: None, fields: [ FieldExpr { diff --git a/tests/ui/thir-print/thir-tree-match.stdout b/tests/ui/thir-print/thir-tree-match.stdout index eea04c0951d..3fc130f0176 100644 --- a/tests/ui/thir-print/thir-tree-match.stdout +++ b/tests/ui/thir-print/thir-tree-match.stdout @@ -106,7 +106,7 @@ body: variants: [VariantDef { def_id: DefId(0:11 ~ thir_tree_match[fcf8]::Foo::FooOne), ctor: Some((Fn, DefId(0:12 ~ thir_tree_match[fcf8]::Foo::FooOne::{constructor#0}))), name: "FooOne", discr: Relative(0), fields: [FieldDef { did: DefId(0:13 ~ thir_tree_match[fcf8]::Foo::FooOne::0), name: "0", vis: Restricted(DefId(0:0 ~ thir_tree_match[fcf8])) }], flags: NO_VARIANT_FLAGS }, VariantDef { def_id: DefId(0:14 ~ thir_tree_match[fcf8]::Foo::FooTwo), ctor: Some((Const, DefId(0:15 ~ thir_tree_match[fcf8]::Foo::FooTwo::{constructor#0}))), name: "FooTwo", discr: Relative(1), fields: [], flags: NO_VARIANT_FLAGS }] flags: IS_ENUM repr: ReprOptions { int: None, align: None, pack: None, flags: (empty), field_shuffle_seed: 3477539199540094892 } - substs: [] + args: [] variant_index: 0 subpatterns: [ Pat: { @@ -120,7 +120,7 @@ body: variants: [VariantDef { def_id: DefId(0:4 ~ thir_tree_match[fcf8]::Bar::First), ctor: Some((Const, DefId(0:5 ~ thir_tree_match[fcf8]::Bar::First::{constructor#0}))), name: "First", discr: Relative(0), fields: [], flags: NO_VARIANT_FLAGS }, VariantDef { def_id: DefId(0:6 ~ thir_tree_match[fcf8]::Bar::Second), ctor: Some((Const, DefId(0:7 ~ thir_tree_match[fcf8]::Bar::Second::{constructor#0}))), name: "Second", discr: Relative(1), fields: [], flags: NO_VARIANT_FLAGS }, VariantDef { def_id: DefId(0:8 ~ thir_tree_match[fcf8]::Bar::Third), ctor: Some((Const, DefId(0:9 ~ thir_tree_match[fcf8]::Bar::Third::{constructor#0}))), name: "Third", discr: Relative(2), fields: [], flags: NO_VARIANT_FLAGS }] flags: IS_ENUM repr: ReprOptions { int: None, align: None, pack: None, flags: (empty), field_shuffle_seed: 10333377570083945360 } - substs: [] + args: [] variant_index: 0 subpatterns: [] } @@ -179,7 +179,7 @@ body: variants: [VariantDef { def_id: DefId(0:11 ~ thir_tree_match[fcf8]::Foo::FooOne), ctor: Some((Fn, DefId(0:12 ~ thir_tree_match[fcf8]::Foo::FooOne::{constructor#0}))), name: "FooOne", discr: Relative(0), fields: [FieldDef { did: DefId(0:13 ~ thir_tree_match[fcf8]::Foo::FooOne::0), name: "0", vis: Restricted(DefId(0:0 ~ thir_tree_match[fcf8])) }], flags: NO_VARIANT_FLAGS }, VariantDef { def_id: DefId(0:14 ~ thir_tree_match[fcf8]::Foo::FooTwo), ctor: Some((Const, DefId(0:15 ~ thir_tree_match[fcf8]::Foo::FooTwo::{constructor#0}))), name: "FooTwo", discr: Relative(1), fields: [], flags: NO_VARIANT_FLAGS }] flags: IS_ENUM repr: ReprOptions { int: None, align: None, pack: None, flags: (empty), field_shuffle_seed: 3477539199540094892 } - substs: [] + args: [] variant_index: 0 subpatterns: [ Pat: { @@ -242,7 +242,7 @@ body: variants: [VariantDef { def_id: DefId(0:11 ~ thir_tree_match[fcf8]::Foo::FooOne), ctor: Some((Fn, DefId(0:12 ~ thir_tree_match[fcf8]::Foo::FooOne::{constructor#0}))), name: "FooOne", discr: Relative(0), fields: [FieldDef { did: DefId(0:13 ~ thir_tree_match[fcf8]::Foo::FooOne::0), name: "0", vis: Restricted(DefId(0:0 ~ thir_tree_match[fcf8])) }], flags: NO_VARIANT_FLAGS }, VariantDef { def_id: DefId(0:14 ~ thir_tree_match[fcf8]::Foo::FooTwo), ctor: Some((Const, DefId(0:15 ~ thir_tree_match[fcf8]::Foo::FooTwo::{constructor#0}))), name: "FooTwo", discr: Relative(1), fields: [], flags: NO_VARIANT_FLAGS }] flags: IS_ENUM repr: ReprOptions { int: None, align: None, pack: None, flags: (empty), field_shuffle_seed: 3477539199540094892 } - substs: [] + args: [] variant_index: 1 subpatterns: [] } diff --git a/tests/ui/traits/issue-24010.rs b/tests/ui/traits/issue-24010.rs index f1818533487..fd7d6751d5c 100644 --- a/tests/ui/traits/issue-24010.rs +++ b/tests/ui/traits/issue-24010.rs @@ -1,4 +1,6 @@ // run-pass +// revisions: classic next +//[next] compile-flags: -Ztrait-solver=next trait Foo: Fn(i32) -> i32 + Send {} diff --git a/tests/ui/traits/new-solver/alias-bound-unsound.rs b/tests/ui/traits/new-solver/alias-bound-unsound.rs index 959f1afa04e..38d83d289f1 100644 --- a/tests/ui/traits/new-solver/alias-bound-unsound.rs +++ b/tests/ui/traits/new-solver/alias-bound-unsound.rs @@ -16,12 +16,17 @@ trait Foo { impl Foo for () { type Item = String where String: Copy; + //~^ ERROR overflow evaluating the requirement `<() as Foo>::Item: Copy` } fn main() { let x = String::from("hello, world"); drop(<() as Foo>::copy_me(&x)); - //~^ ERROR the type `&<() as Foo>::Item` is not well-formed - //~| ERROR `<() as Foo>::Item` is not well-formed + //~^ ERROR overflow evaluating the requirement `<() as Foo>::Item: Sized` + //~| ERROR overflow evaluating the requirement `<() as Foo>::Item == _` + //~| ERROR overflow evaluating the requirement `<() as Foo>::Item well-formed` + //~| ERROR overflow evaluating the requirement `String <: <() as Foo>::Item` + //~| ERROR overflow evaluating the requirement `&<() as Foo>::Item well-formed` + //~| ERROR type annotations needed println!("{x}"); } diff --git a/tests/ui/traits/new-solver/alias-bound-unsound.stderr b/tests/ui/traits/new-solver/alias-bound-unsound.stderr index 5800e2c4340..abc6677c132 100644 --- a/tests/ui/traits/new-solver/alias-bound-unsound.stderr +++ b/tests/ui/traits/new-solver/alias-bound-unsound.stderr @@ -1,14 +1,69 @@ -error: the type `&<() as Foo>::Item` is not well-formed - --> $DIR/alias-bound-unsound.rs:23:31 +error[E0275]: overflow evaluating the requirement `<() as Foo>::Item: Copy` + --> $DIR/alias-bound-unsound.rs:18:17 + | +LL | type Item = String where String: Copy; + | ^^^^^^ + | + = help: consider increasing the recursion limit by adding a `#![recursion_limit = "256"]` attribute to your crate (`alias_bound_unsound`) +note: required by a bound in `Foo::Item` + --> $DIR/alias-bound-unsound.rs:8:16 + | +LL | type Item: Copy + | ^^^^ required by this bound in `Foo::Item` + +error[E0282]: type annotations needed + --> $DIR/alias-bound-unsound.rs:24:5 + | +LL | drop(<() as Foo>::copy_me(&x)); + | ^^^^ cannot infer type of the type parameter `T` declared on the function `drop` + | +help: consider specifying the generic argument + | +LL | drop::<T>(<() as Foo>::copy_me(&x)); + | +++++ + +error[E0275]: overflow evaluating the requirement `&<() as Foo>::Item well-formed` + --> $DIR/alias-bound-unsound.rs:24:31 | LL | drop(<() as Foo>::copy_me(&x)); | ^^ + | + = help: consider increasing the recursion limit by adding a `#![recursion_limit = "256"]` attribute to your crate (`alias_bound_unsound`) -error: the type `<() as Foo>::Item` is not well-formed - --> $DIR/alias-bound-unsound.rs:23:10 +error[E0275]: overflow evaluating the requirement `String <: <() as Foo>::Item` + --> $DIR/alias-bound-unsound.rs:24:31 + | +LL | drop(<() as Foo>::copy_me(&x)); + | ^^ + | + = help: consider increasing the recursion limit by adding a `#![recursion_limit = "256"]` attribute to your crate (`alias_bound_unsound`) + +error[E0275]: overflow evaluating the requirement `<() as Foo>::Item well-formed` + --> $DIR/alias-bound-unsound.rs:24:10 + | +LL | drop(<() as Foo>::copy_me(&x)); + | ^^^^^^^^^^^^^^^^^^^^^^^^ + | + = help: consider increasing the recursion limit by adding a `#![recursion_limit = "256"]` attribute to your crate (`alias_bound_unsound`) + +error[E0275]: overflow evaluating the requirement `<() as Foo>::Item == _` + --> $DIR/alias-bound-unsound.rs:24:10 | LL | drop(<() as Foo>::copy_me(&x)); | ^^^^^^^^^^^^^^^^^^^^^^^^ + | + = help: consider increasing the recursion limit by adding a `#![recursion_limit = "256"]` attribute to your crate (`alias_bound_unsound`) + +error[E0275]: overflow evaluating the requirement `<() as Foo>::Item: Sized` + --> $DIR/alias-bound-unsound.rs:24:10 + | +LL | drop(<() as Foo>::copy_me(&x)); + | ^^^^^^^^^^^^^^^^^^^^ + | + = help: consider increasing the recursion limit by adding a `#![recursion_limit = "256"]` attribute to your crate (`alias_bound_unsound`) + = note: the return type of a function must have a statically known size -error: aborting due to 2 previous errors +error: aborting due to 7 previous errors +Some errors have detailed explanations: E0275, E0282. +For more information about an error, try `rustc --explain E0275`. diff --git a/tests/ui/traits/new-solver/escaping-bound-vars-in-writeback-normalization.rs b/tests/ui/traits/new-solver/escaping-bound-vars-in-writeback-normalization.rs new file mode 100644 index 00000000000..29784c32a1b --- /dev/null +++ b/tests/ui/traits/new-solver/escaping-bound-vars-in-writeback-normalization.rs @@ -0,0 +1,18 @@ +// compile-flags: -Ztrait-solver=next +// check-pass + +trait Trivial { + type Assoc; +} + +impl<T: ?Sized> Trivial for T { + type Assoc = (); +} + +fn main() { + // During writeback, we call `normalize_erasing_regions`, which will walk past + // the `for<'a>` binder and try to normalize `<&'a () as Trivial>::Assoc` directly. + // We need to handle this case in the new deep normalizer similarly to how it + // is handled in the old solver. + let x: Option<for<'a> fn(<&'a () as Trivial>::Assoc)> = None; +} diff --git a/tests/ui/traits/new-solver/trait-upcast-lhs-needs-normalization.rs b/tests/ui/traits/new-solver/trait-upcast-lhs-needs-normalization.rs new file mode 100644 index 00000000000..79114b93b78 --- /dev/null +++ b/tests/ui/traits/new-solver/trait-upcast-lhs-needs-normalization.rs @@ -0,0 +1,18 @@ +// check-pass +// compile-flags: -Ztrait-solver=next + +pub trait A {} +pub trait B: A {} + +pub trait Mirror { + type Assoc: ?Sized; +} +impl<T: ?Sized> Mirror for T { + type Assoc = T; +} + +pub fn foo<'a>(x: &'a <dyn B + 'static as Mirror>::Assoc) -> &'a (dyn A + 'static) { + x +} + +fn main() {} diff --git a/tests/ui/traits/new-solver/unsize-although-ambiguous.rs b/tests/ui/traits/new-solver/unsize-although-ambiguous.rs new file mode 100644 index 00000000000..431988a5fff --- /dev/null +++ b/tests/ui/traits/new-solver/unsize-although-ambiguous.rs @@ -0,0 +1,13 @@ +// check-pass +// compile-flags: -Ztrait-solver=next + +use std::fmt::Display; + +fn box_dyn_display(_: Box<dyn Display>) {} + +fn main() { + // During coercion, we don't necessarily know whether `{integer}` implements + // `Display`. Before, that would cause us to bail out in the coercion loop when + // checking `{integer}: Unsize<dyn Display>`. + box_dyn_display(Box::new(1)); +} diff --git a/tests/ui/issues/issue-11515.stderr b/tests/ui/traits/trait-upcasting/issue-11515.current.stderr index accd47f0f5f..97d66cccb25 100644 --- a/tests/ui/issues/issue-11515.stderr +++ b/tests/ui/traits/trait-upcasting/issue-11515.current.stderr @@ -1,5 +1,5 @@ error[E0658]: cannot cast `dyn Fn()` to `dyn FnMut()`, trait upcasting coercion is experimental - --> $DIR/issue-11515.rs:9:38 + --> $DIR/issue-11515.rs:10:38 | LL | let test = Box::new(Test { func: closure }); | ^^^^^^^ diff --git a/tests/ui/traits/trait-upcasting/issue-11515.next.stderr b/tests/ui/traits/trait-upcasting/issue-11515.next.stderr new file mode 100644 index 00000000000..97d66cccb25 --- /dev/null +++ b/tests/ui/traits/trait-upcasting/issue-11515.next.stderr @@ -0,0 +1,13 @@ +error[E0658]: cannot cast `dyn Fn()` to `dyn FnMut()`, trait upcasting coercion is experimental + --> $DIR/issue-11515.rs:10:38 + | +LL | let test = Box::new(Test { func: closure }); + | ^^^^^^^ + | + = note: see issue #65991 <https://github.com/rust-lang/rust/issues/65991> for more information + = help: add `#![feature(trait_upcasting)]` to the crate attributes to enable + = note: required when coercing `Box<(dyn Fn() + 'static)>` into `Box<(dyn FnMut() + 'static)>` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0658`. diff --git a/tests/ui/issues/issue-11515.rs b/tests/ui/traits/trait-upcasting/issue-11515.rs index b5c942f96a7..723f3a24fd4 100644 --- a/tests/ui/issues/issue-11515.rs +++ b/tests/ui/traits/trait-upcasting/issue-11515.rs @@ -1,9 +1,10 @@ +// revisions: current next +//[next] compile-flags: -Ztrait-solver=next + struct Test { func: Box<dyn FnMut() + 'static>, } - - fn main() { let closure: Box<dyn Fn() + 'static> = Box::new(|| ()); let test = Box::new(Test { func: closure }); //~ ERROR trait upcasting coercion is experimental [E0658] diff --git a/tests/ui/transmutability/references/recursive-wrapper-types-bit-compatible.rs b/tests/ui/transmutability/references/recursive-wrapper-types-bit-compatible.rs index 3ea80173afa..709d8cdc762 100644 --- a/tests/ui/transmutability/references/recursive-wrapper-types-bit-compatible.rs +++ b/tests/ui/transmutability/references/recursive-wrapper-types-bit-compatible.rs @@ -1,5 +1,4 @@ -// check-fail -// FIXME(bryangarza): Change to check-pass when coinduction is supported for BikeshedIntrinsicFrom +// check-pass #![feature(transmutability)] mod assert { @@ -22,5 +21,5 @@ mod assert { fn main() { #[repr(C)] struct A(bool, &'static A); #[repr(C)] struct B(u8, &'static B); - assert::is_maybe_transmutable::<&'static A, &'static B>(); //~ ERROR overflow evaluating the requirement + assert::is_maybe_transmutable::<&'static A, &'static B>(); } diff --git a/tests/ui/transmutability/references/recursive-wrapper-types-bit-compatible.stderr b/tests/ui/transmutability/references/recursive-wrapper-types-bit-compatible.stderr deleted file mode 100644 index fae332e6af9..00000000000 --- a/tests/ui/transmutability/references/recursive-wrapper-types-bit-compatible.stderr +++ /dev/null @@ -1,25 +0,0 @@ -error[E0275]: overflow evaluating the requirement `B: BikeshedIntrinsicFrom<A, assert::Context, Assume { alignment: true, lifetimes: false, safety: true, validity: false }>` - --> $DIR/recursive-wrapper-types-bit-compatible.rs:25:5 - | -LL | assert::is_maybe_transmutable::<&'static A, &'static B>(); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | -note: required by a bound in `is_maybe_transmutable` - --> $DIR/recursive-wrapper-types-bit-compatible.rs:11:14 - | -LL | pub fn is_maybe_transmutable<Src, Dst>() - | --------------------- required by a bound in this function -LL | where -LL | Dst: BikeshedIntrinsicFrom<Src, Context, { - | ______________^ -LL | | Assume { -LL | | alignment: true, -LL | | lifetimes: false, -... | -LL | | } -LL | | }> - | |__________^ required by this bound in `is_maybe_transmutable` - -error: aborting due to previous error - -For more information about this error, try `rustc --explain E0275`. diff --git a/tests/ui/transmutability/references/recursive-wrapper-types.rs b/tests/ui/transmutability/references/recursive-wrapper-types.rs index 59d1ad84a5d..090c1fea6db 100644 --- a/tests/ui/transmutability/references/recursive-wrapper-types.rs +++ b/tests/ui/transmutability/references/recursive-wrapper-types.rs @@ -1,5 +1,4 @@ -// check-fail -// FIXME(bryangarza): Change to check-pass when coinduction is supported for BikeshedIntrinsicFrom +// check-pass #![feature(transmutability)] mod assert { @@ -22,6 +21,6 @@ mod assert { fn main() { #[repr(C)] struct A(&'static B); #[repr(C)] struct B(&'static A); - assert::is_maybe_transmutable::<&'static A, &'static B>(); //~ overflow evaluating the requirement + assert::is_maybe_transmutable::<&'static A, &'static B>(); assert::is_maybe_transmutable::<&'static B, &'static A>(); } diff --git a/tests/ui/transmutability/references/recursive-wrapper-types.stderr b/tests/ui/transmutability/references/recursive-wrapper-types.stderr deleted file mode 100644 index 35a60c22643..00000000000 --- a/tests/ui/transmutability/references/recursive-wrapper-types.stderr +++ /dev/null @@ -1,25 +0,0 @@ -error[E0275]: overflow evaluating the requirement `A: BikeshedIntrinsicFrom<B, assert::Context, Assume { alignment: true, lifetimes: false, safety: true, validity: false }>` - --> $DIR/recursive-wrapper-types.rs:25:5 - | -LL | assert::is_maybe_transmutable::<&'static A, &'static B>(); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | -note: required by a bound in `is_maybe_transmutable` - --> $DIR/recursive-wrapper-types.rs:11:14 - | -LL | pub fn is_maybe_transmutable<Src, Dst>() - | --------------------- required by a bound in this function -LL | where -LL | Dst: BikeshedIntrinsicFrom<Src, Context, { - | ______________^ -LL | | Assume { -LL | | alignment: true, -LL | | lifetimes: false, -... | -LL | | } -LL | | }> - | |__________^ required by this bound in `is_maybe_transmutable` - -error: aborting due to previous error - -For more information about this error, try `rustc --explain E0275`. diff --git a/tests/ui/type-alias/lazy-type-alias-enum-variant.rs b/tests/ui/type-alias/lazy-type-alias-enum-variant.rs new file mode 100644 index 00000000000..78c3159d1c2 --- /dev/null +++ b/tests/ui/type-alias/lazy-type-alias-enum-variant.rs @@ -0,0 +1,17 @@ +// Regression test for issue #113736. +// check-pass + +#![feature(lazy_type_alias)] + +enum Enum { + Unit, + Tuple(), + Struct {}, +} + +fn main() { + type Alias = Enum; + let _ = Alias::Unit; + let _ = Alias::Tuple(); + let _ = Alias::Struct {}; +} diff --git a/tests/ui/unop-move-semantics.stderr b/tests/ui/unop-move-semantics.stderr index e47785c465a..b6de7976ac9 100644 --- a/tests/ui/unop-move-semantics.stderr +++ b/tests/ui/unop-move-semantics.stderr @@ -7,7 +7,7 @@ LL | !x; | -- `x` moved due to usage in operator LL | LL | x.clone(); - | ^^^^^^^^^ value borrowed here after move + | ^ value borrowed here after move | note: calling this operator moves the left-hand side --> $SRC_DIR/core/src/ops/bit.rs:LL:COL diff --git a/tests/ui/unsafe/unsafe-not-inherited.stderr b/tests/ui/unsafe/unsafe-not-inherited.mirunsafeck.stderr index 3bc5ca5c9d1..5536efbc6f4 100644 --- a/tests/ui/unsafe/unsafe-not-inherited.stderr +++ b/tests/ui/unsafe/unsafe-not-inherited.mirunsafeck.stderr @@ -1,5 +1,5 @@ error[E0133]: use of mutable static is unsafe and requires unsafe function or block - --> $DIR/unsafe-not-inherited.rs:6:31 + --> $DIR/unsafe-not-inherited.rs:8:31 | LL | unsafe {static BAR: u64 = FOO;} | ------ ^^^ use of mutable static @@ -9,7 +9,7 @@ LL | unsafe {static BAR: u64 = FOO;} = note: mutable statics can be mutated by multiple threads: aliasing violations or data races will cause undefined behavior error[E0133]: call to unsafe function is unsafe and requires unsafe function or block - --> $DIR/unsafe-not-inherited.rs:18:13 + --> $DIR/unsafe-not-inherited.rs:20:13 | LL | unsafe { | ------ items do not inherit unsafety from separate enclosing items diff --git a/tests/ui/unsafe/unsafe-not-inherited.rs b/tests/ui/unsafe/unsafe-not-inherited.rs index 6d797caa0f9..f9d9a595714 100644 --- a/tests/ui/unsafe/unsafe-not-inherited.rs +++ b/tests/ui/unsafe/unsafe-not-inherited.rs @@ -1,3 +1,5 @@ +// revisions: mirunsafeck thirunsafeck +// [thirunsafeck]compile-flags: -Z thir-unsafeck #![allow(unused, dead_code)] static mut FOO: u64 = 0; diff --git a/tests/ui/unsafe/unsafe-not-inherited.thirunsafeck.stderr b/tests/ui/unsafe/unsafe-not-inherited.thirunsafeck.stderr new file mode 100644 index 00000000000..88ea2e6d1fe --- /dev/null +++ b/tests/ui/unsafe/unsafe-not-inherited.thirunsafeck.stderr @@ -0,0 +1,24 @@ +error[E0133]: use of mutable static is unsafe and requires unsafe function or block + --> $DIR/unsafe-not-inherited.rs:8:31 + | +LL | unsafe {static BAR: u64 = FOO;} + | ------ ^^^ use of mutable static + | | + | items do not inherit unsafety from separate enclosing items + | + = note: mutable statics can be mutated by multiple threads: aliasing violations or data races will cause undefined behavior + +error[E0133]: call to unsafe function `unsafe_call` is unsafe and requires unsafe function or block + --> $DIR/unsafe-not-inherited.rs:20:13 + | +LL | unsafe { + | ------ items do not inherit unsafety from separate enclosing items +... +LL | unsafe_call(); + | ^^^^^^^^^^^^^ call to unsafe function + | + = note: consult the function's documentation for information on how to avoid undefined behavior + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0133`. diff --git a/tests/ui/use/use-after-move-implicity-coerced-object.stderr b/tests/ui/use/use-after-move-implicity-coerced-object.stderr index dfa0c04836e..84487a8d0dc 100644 --- a/tests/ui/use/use-after-move-implicity-coerced-object.stderr +++ b/tests/ui/use/use-after-move-implicity-coerced-object.stderr @@ -8,7 +8,7 @@ LL | l.push(n); | - value moved here LL | LL | let x = n.to_string(); - | ^^^^^^^^^^^^^ value borrowed here after move + | ^ value borrowed here after move | note: consider changing this parameter type in method `push` to borrow instead if owning the value isn't necessary --> $DIR/use-after-move-implicity-coerced-object.rs:17:27 diff --git a/tests/ui/parser/type-alias-where-fixable.fixed b/tests/ui/where-clauses/where-clause-placement-assoc-type-in-impl.fixed index 2f47c0d91fa..2f47c0d91fa 100644 --- a/tests/ui/parser/type-alias-where-fixable.fixed +++ b/tests/ui/where-clauses/where-clause-placement-assoc-type-in-impl.fixed diff --git a/tests/ui/parser/type-alias-where-fixable.rs b/tests/ui/where-clauses/where-clause-placement-assoc-type-in-impl.rs index b20aa9398b5..b20aa9398b5 100644 --- a/tests/ui/parser/type-alias-where-fixable.rs +++ b/tests/ui/where-clauses/where-clause-placement-assoc-type-in-impl.rs diff --git a/tests/ui/parser/type-alias-where-fixable.stderr b/tests/ui/where-clauses/where-clause-placement-assoc-type-in-impl.stderr index f0acb388b97..b4de051845f 100644 --- a/tests/ui/parser/type-alias-where-fixable.stderr +++ b/tests/ui/where-clauses/where-clause-placement-assoc-type-in-impl.stderr @@ -1,5 +1,5 @@ warning: where clause not allowed here - --> $DIR/type-alias-where-fixable.rs:13:16 + --> $DIR/where-clause-placement-assoc-type-in-impl.rs:13:16 | LL | type Assoc where u32: Copy = (); | ^^^^^^^^^^^^^^^ @@ -13,7 +13,7 @@ LL + type Assoc = () where u32: Copy; | warning: where clause not allowed here - --> $DIR/type-alias-where-fixable.rs:16:17 + --> $DIR/where-clause-placement-assoc-type-in-impl.rs:16:17 | LL | type Assoc2 where u32: Copy = () where i32: Copy; | ^^^^^^^^^^^^^^^ @@ -26,7 +26,7 @@ LL + type Assoc2 = () where i32: Copy, u32: Copy; | warning: where clause not allowed here - --> $DIR/type-alias-where-fixable.rs:24:17 + --> $DIR/where-clause-placement-assoc-type-in-impl.rs:24:17 | LL | type Assoc2 where u32: Copy, i32: Copy = (); | ^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/tests/ui/where-clauses/where-clause-placement-assoc-type-in-trait.fixed b/tests/ui/where-clauses/where-clause-placement-assoc-type-in-trait.fixed new file mode 100644 index 00000000000..d171eba50b7 --- /dev/null +++ b/tests/ui/where-clauses/where-clause-placement-assoc-type-in-trait.fixed @@ -0,0 +1,15 @@ +// check-pass +// run-rustfix + +#![feature(associated_type_defaults)] + +trait Trait { + // Not fine, suggests moving. + type Assoc = () where u32: Copy; + //~^ WARNING where clause not allowed here + // Not fine, suggests moving `u32: Copy` + type Assoc2 = () where i32: Copy, u32: Copy; + //~^ WARNING where clause not allowed here +} + +fn main() {} diff --git a/tests/ui/where-clauses/where-clause-placement-assoc-type-in-trait.rs b/tests/ui/where-clauses/where-clause-placement-assoc-type-in-trait.rs new file mode 100644 index 00000000000..59afee65794 --- /dev/null +++ b/tests/ui/where-clauses/where-clause-placement-assoc-type-in-trait.rs @@ -0,0 +1,15 @@ +// check-pass +// run-rustfix + +#![feature(associated_type_defaults)] + +trait Trait { + // Not fine, suggests moving. + type Assoc where u32: Copy = (); + //~^ WARNING where clause not allowed here + // Not fine, suggests moving `u32: Copy` + type Assoc2 where u32: Copy = () where i32: Copy; + //~^ WARNING where clause not allowed here +} + +fn main() {} diff --git a/tests/ui/where-clauses/where-clause-placement-assoc-type-in-trait.stderr b/tests/ui/where-clauses/where-clause-placement-assoc-type-in-trait.stderr new file mode 100644 index 00000000000..a81cb8c8cd6 --- /dev/null +++ b/tests/ui/where-clauses/where-clause-placement-assoc-type-in-trait.stderr @@ -0,0 +1,29 @@ +warning: where clause not allowed here + --> $DIR/where-clause-placement-assoc-type-in-trait.rs:8:16 + | +LL | type Assoc where u32: Copy = (); + | ^^^^^^^^^^^^^^^ + | + = note: see issue #89122 <https://github.com/rust-lang/rust/issues/89122> for more information + = note: `#[warn(deprecated_where_clause_location)]` on by default +help: move it to the end of the type declaration + | +LL - type Assoc where u32: Copy = (); +LL + type Assoc = () where u32: Copy; + | + +warning: where clause not allowed here + --> $DIR/where-clause-placement-assoc-type-in-trait.rs:11:17 + | +LL | type Assoc2 where u32: Copy = () where i32: Copy; + | ^^^^^^^^^^^^^^^ + | + = note: see issue #89122 <https://github.com/rust-lang/rust/issues/89122> for more information +help: move it to the end of the type declaration + | +LL - type Assoc2 where u32: Copy = () where i32: Copy; +LL + type Assoc2 = () where i32: Copy, u32: Copy; + | + +warning: 2 warnings emitted + diff --git a/tests/ui/parser/type-alias-where.rs b/tests/ui/where-clauses/where-clause-placement-type-alias.rs index 62e301cb408..62e301cb408 100644 --- a/tests/ui/parser/type-alias-where.rs +++ b/tests/ui/where-clauses/where-clause-placement-type-alias.rs diff --git a/tests/ui/parser/type-alias-where.stderr b/tests/ui/where-clauses/where-clause-placement-type-alias.stderr index fb838179266..b3c155a48dd 100644 --- a/tests/ui/parser/type-alias-where.stderr +++ b/tests/ui/where-clauses/where-clause-placement-type-alias.stderr @@ -1,5 +1,5 @@ error: where clauses are not allowed after the type for type aliases - --> $DIR/type-alias-where.rs:6:15 + --> $DIR/where-clause-placement-type-alias.rs:6:15 | LL | type Bar = () where u32: Copy; | ^^^^^^^^^^^^^^^ @@ -7,7 +7,7 @@ LL | type Bar = () where u32: Copy; = note: see issue #89122 <https://github.com/rust-lang/rust/issues/89122> for more information error: where clauses are not allowed after the type for type aliases - --> $DIR/type-alias-where.rs:8:15 + --> $DIR/where-clause-placement-type-alias.rs:8:15 | LL | type Baz = () where; | ^^^^^ diff --git a/triagebot.toml b/triagebot.toml index da9d167bd3e..1a435ff074e 100644 --- a/triagebot.toml +++ b/triagebot.toml @@ -264,7 +264,7 @@ exclude_labels = [ [autolabel."WG-trait-system-refactor"] trigger_files = [ "compiler/rustc_trait_selection/src/solve", - "compiler/rustc_middle/src/traits/solve.rs" + "compiler/rustc_middle/src/traits/solve" ] [notify-zulip."I-prioritize"] |
