diff options
91 files changed, 369 insertions, 283 deletions
diff --git a/RELEASES.md b/RELEASES.md index 59d04d4ba76..01c57ab9170 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -44,6 +44,7 @@ Stabilized APIs - [`Result::unwrap_unchecked`] - [`Result::unwrap_err_unchecked`] - [`NonZero{unsigned}::is_power_of_two`] +- [`File::options`] These APIs are now usable in const contexts: @@ -141,6 +142,7 @@ and related tools. [`Result::unwrap_unchecked`]: https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.unwrap_unchecked [`Result::unwrap_err_unchecked`]: https://doc.rust-lang.org/stable/std/result/enum.Result.html#method.unwrap_err_unchecked [`NonZero{unsigned}::is_power_of_two`]: https://doc.rust-lang.org/stable/std/num/struct.NonZeroU8.html#method.is_power_of_two +[`File::options`]: https://doc.rust-lang.org/stable/std/fs/struct.File.html#method.options [`unix::process::ExitStatusExt::core_dumped`]: https://doc.rust-lang.org/stable/std/os/unix/process/trait.ExitStatusExt.html#tymethod.core_dumped [`unix::process::ExitStatusExt::stopped_signal`]: https://doc.rust-lang.org/stable/std/os/unix/process/trait.ExitStatusExt.html#tymethod.stopped_signal [`unix::process::ExitStatusExt::continued`]: https://doc.rust-lang.org/stable/std/os/unix/process/trait.ExitStatusExt.html#tymethod.continued @@ -2588,6 +2590,11 @@ Language - [Visibility modifiers (e.g. `pub`) are now syntactically allowed on trait items and enum variants.][66183] These are still rejected semantically, but can be seen and parsed by procedural macros and conditional compilation. +- [You can now define a Rust `extern "C"` function with `Box<T>` and use `T*` as the corresponding + type on the C side.][62514] Please see [the documentation][box-memory-layout] for more information, + including the important caveat about preferring to avoid `Box<T>` in Rust signatures for functions defined in C. + +[box-memory-layout]: https://doc.rust-lang.org/std/boxed/index.html#memory-layout Compiler -------- @@ -2662,6 +2669,7 @@ Compatibility Notes [54733]: https://github.com/rust-lang/rust/pull/54733/ [61351]: https://github.com/rust-lang/rust/pull/61351/ +[62514]: https://github.com/rust-lang/rust/pull/62514/ [67255]: https://github.com/rust-lang/rust/pull/67255/ [66661]: https://github.com/rust-lang/rust/pull/66661/ [66771]: https://github.com/rust-lang/rust/pull/66771/ diff --git a/compiler/rustc_borrowck/src/diagnostics/mod.rs b/compiler/rustc_borrowck/src/diagnostics/mod.rs index e2eb125981f..84acfbf941d 100644 --- a/compiler/rustc_borrowck/src/diagnostics/mod.rs +++ b/compiler/rustc_borrowck/src/diagnostics/mod.rs @@ -372,7 +372,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { } else { def.non_enum_variant() }; - variant.fields[field.index()].ident.to_string() + variant.fields[field.index()].name.to_string() } ty::Tuple(_) => field.index().to_string(), ty::Ref(_, ty, _) | ty::RawPtr(ty::TypeAndMut { ty, .. }) => { diff --git a/compiler/rustc_builtin_macros/src/asm.rs b/compiler/rustc_builtin_macros/src/asm.rs index 1a93b9be99e..caf8ac77df1 100644 --- a/compiler/rustc_builtin_macros/src/asm.rs +++ b/compiler/rustc_builtin_macros/src/asm.rs @@ -16,13 +16,13 @@ use rustc_target::asm::InlineAsmArch; use smallvec::smallvec; pub struct AsmArgs { - templates: Vec<P<ast::Expr>>, - operands: Vec<(ast::InlineAsmOperand, Span)>, + pub templates: Vec<P<ast::Expr>>, + pub operands: Vec<(ast::InlineAsmOperand, Span)>, named_args: FxHashMap<Symbol, usize>, reg_args: FxHashSet<usize>, - clobber_abis: Vec<(Symbol, Span)>, + pub clobber_abis: Vec<(Symbol, Span)>, options: ast::InlineAsmOptions, - options_spans: Vec<Span>, + pub options_spans: Vec<Span>, } fn parse_args<'a>( diff --git a/compiler/rustc_codegen_cranelift/src/debuginfo/mod.rs b/compiler/rustc_codegen_cranelift/src/debuginfo/mod.rs index 638b025be22..8e203b8cfa0 100644 --- a/compiler/rustc_codegen_cranelift/src/debuginfo/mod.rs +++ b/compiler/rustc_codegen_cranelift/src/debuginfo/mod.rs @@ -174,7 +174,7 @@ impl<'tcx> DebugContext<'tcx> { field_entry.set( gimli::DW_AT_name, - AttributeValue::String(field_def.ident.as_str().to_string().into_bytes()), + AttributeValue::String(field_def.name.as_str().to_string().into_bytes()), ); field_entry.set( gimli::DW_AT_data_member_location, diff --git a/compiler/rustc_codegen_gcc/src/type_of.rs b/compiler/rustc_codegen_gcc/src/type_of.rs index 9c39c8f91a1..281e49fa8a3 100644 --- a/compiler/rustc_codegen_gcc/src/type_of.rs +++ b/compiler/rustc_codegen_gcc/src/type_of.rs @@ -57,7 +57,7 @@ pub fn uncached_gcc_type<'gcc, 'tcx>(cx: &CodegenCx<'gcc, 'tcx>, layout: TyAndLa (layout.ty.kind(), &layout.variants) { if def.is_enum() && !def.variants.is_empty() { - write!(&mut name, "::{}", def.variants[index].ident).unwrap(); + write!(&mut name, "::{}", def.variants[index].name).unwrap(); } } if let (&ty::Generator(_, _, _), &Variants::Single { index }) = diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs b/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs index 60ff18af0a9..5c02e3d0fa7 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs @@ -1300,7 +1300,7 @@ impl<'tcx> StructMemberDescriptionFactory<'tcx> { let name = if self.variant.ctor_kind == CtorKind::Fn { format!("__{}", i) } else { - f.ident.to_string() + f.name.to_string() }; let field = layout.field(cx, i); MemberDescription { @@ -1480,7 +1480,7 @@ impl<'tcx> UnionMemberDescriptionFactory<'tcx> { .map(|(i, f)| { let field = self.layout.field(cx, i); MemberDescription { - name: f.ident.to_string(), + name: f.name.to_string(), type_metadata: type_metadata(cx, field.ty, self.span), offset: Size::ZERO, size: field.size, @@ -1950,7 +1950,7 @@ enum VariantInfo<'a, 'tcx> { impl<'tcx> VariantInfo<'_, 'tcx> { fn map_struct_name<R>(&self, f: impl FnOnce(&str) -> R) -> R { match self { - VariantInfo::Adt(variant) => f(variant.ident.as_str()), + VariantInfo::Adt(variant) => f(variant.name.as_str()), VariantInfo::Generator { variant_index, .. } => { f(&GeneratorSubsts::variant_name(*variant_index)) } @@ -1959,7 +1959,7 @@ impl<'tcx> VariantInfo<'_, 'tcx> { fn variant_name(&self) -> String { match self { - VariantInfo::Adt(variant) => variant.ident.to_string(), + VariantInfo::Adt(variant) => variant.name.to_string(), VariantInfo::Generator { variant_index, .. } => { // Since GDB currently prints out the raw discriminant along // with every variant, make each variant name be just the value @@ -1973,7 +1973,7 @@ impl<'tcx> VariantInfo<'_, 'tcx> { fn field_name(&self, i: usize) -> String { let field_name = match *self { VariantInfo::Adt(variant) if variant.ctor_kind != CtorKind::Fn => { - Some(variant.fields[i].ident.name) + Some(variant.fields[i].name) } VariantInfo::Generator { generator_layout, @@ -2063,7 +2063,7 @@ fn prepare_enum_metadata<'ll, 'tcx>( let enumerators_metadata: Vec<_> = match enum_type.kind() { ty::Adt(def, _) => iter::zip(def.discriminants(tcx), &def.variants) .map(|((_, discr), v)| { - let name = v.ident.as_str(); + let name = v.name.as_str(); let is_unsigned = match discr.ty.kind() { ty::Int(_) => false, ty::Uint(_) => true, diff --git a/compiler/rustc_codegen_llvm/src/intrinsic.rs b/compiler/rustc_codegen_llvm/src/intrinsic.rs index 07d49b6e729..1e795efa2e1 100644 --- a/compiler/rustc_codegen_llvm/src/intrinsic.rs +++ b/compiler/rustc_codegen_llvm/src/intrinsic.rs @@ -791,7 +791,7 @@ fn get_rust_try_fn<'ll, 'tcx>( ))); // `unsafe fn(unsafe fn(*mut i8) -> (), *mut i8, unsafe fn(*mut i8, *mut i8) -> ()) -> i32` let rust_fn_sig = ty::Binder::dummy(cx.tcx.mk_fn_sig( - vec![try_fn_ty, i8p, catch_fn_ty].into_iter(), + [try_fn_ty, i8p, catch_fn_ty].into_iter(), tcx.types.i32, false, hir::Unsafety::Unsafe, diff --git a/compiler/rustc_codegen_llvm/src/type_of.rs b/compiler/rustc_codegen_llvm/src/type_of.rs index f8c919ec2aa..81d0603bc52 100644 --- a/compiler/rustc_codegen_llvm/src/type_of.rs +++ b/compiler/rustc_codegen_llvm/src/type_of.rs @@ -49,7 +49,7 @@ fn uncached_llvm_type<'a, 'tcx>( (layout.ty.kind(), &layout.variants) { if def.is_enum() && !def.variants.is_empty() { - write!(&mut name, "::{}", def.variants[index].ident).unwrap(); + write!(&mut name, "::{}", def.variants[index].name).unwrap(); } } if let (&ty::Generator(_, _, _), &Variants::Single { index }) = diff --git a/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs b/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs index 93bb1aee25f..9ecab82dd2e 100644 --- a/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs +++ b/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs @@ -409,14 +409,14 @@ fn push_debuginfo_type_name<'tcx>( let max = dataful_discriminant_range.end; let max = tag.value.size(&tcx).truncate(max); - let dataful_variant_name = def.variants[*dataful_variant].ident.as_str(); + let dataful_variant_name = def.variants[*dataful_variant].name.as_str(); output.push_str(&format!(", {}, {}, {}", min, max, dataful_variant_name)); } else if let Variants::Single { index: variant_idx } = &layout.variants { // Uninhabited enums can't be constructed and should never need to be visualized so // skip this step for them. if def.variants.len() != 0 { - let variant = def.variants[*variant_idx].ident.as_str(); + let variant = def.variants[*variant_idx].name.as_str(); output.push_str(&format!(", {}", variant)); } diff --git a/compiler/rustc_const_eval/src/interpret/validity.rs b/compiler/rustc_const_eval/src/interpret/validity.rs index 5a398c2f45a..9dc7930fc51 100644 --- a/compiler/rustc_const_eval/src/interpret/validity.rs +++ b/compiler/rustc_const_eval/src/interpret/validity.rs @@ -267,14 +267,14 @@ impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValidityVisitor<'rt, 'mir, ' match layout.variants { Variants::Single { index } => { // Inside a variant - PathElem::Field(def.variants[index].fields[field].ident.name) + PathElem::Field(def.variants[index].fields[field].name) } Variants::Multiple { .. } => bug!("we handled variants above"), } } // other ADTs - ty::Adt(def, _) => PathElem::Field(def.non_enum_variant().fields[field].ident.name), + ty::Adt(def, _) => PathElem::Field(def.non_enum_variant().fields[field].name), // arrays/slices ty::Array(..) | ty::Slice(..) => PathElem::ArrayElem(field), @@ -726,7 +726,7 @@ impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValueVisitor<'mir, 'tcx, M> new_op: &OpTy<'tcx, M::PointerTag>, ) -> InterpResult<'tcx> { let name = match old_op.layout.ty.kind() { - ty::Adt(adt, _) => PathElem::Variant(adt.variants[variant_id].ident.name), + ty::Adt(adt, _) => PathElem::Variant(adt.variants[variant_id].name), // Generators also have variants ty::Generator(..) => PathElem::GeneratorState(variant_id), _ => bug!("Unexpected type with variant: {:?}", old_op.layout.ty), 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 dd749c03934..de4824eb667 100644 --- a/compiler/rustc_const_eval/src/transform/check_consts/check.rs +++ b/compiler/rustc_const_eval/src/transform/check_consts/check.rs @@ -810,7 +810,7 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> { param_env, Binder::dummy(TraitPredicate { trait_ref, - constness: ty::BoundConstness::ConstIfConst, + constness: ty::BoundConstness::NotConst, polarity: ty::ImplPolarity::Positive, }), ); @@ -829,6 +829,10 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> { return; } Ok(Some(ImplSource::UserDefined(data))) => { + if let hir::Constness::NotConst = tcx.impl_constness(data.impl_def_id) { + self.check_op(ops::FnCallNonConst(None)); + return; + } let callee_name = tcx.item_name(callee); if let Some(&did) = tcx .associated_item_def_ids(data.impl_def_id) diff --git a/compiler/rustc_data_structures/src/thin_vec/tests.rs b/compiler/rustc_data_structures/src/thin_vec/tests.rs index 5abfd939373..0221b9912bb 100644 --- a/compiler/rustc_data_structures/src/thin_vec/tests.rs +++ b/compiler/rustc_data_structures/src/thin_vec/tests.rs @@ -10,8 +10,8 @@ impl<T> ThinVec<T> { fn test_from_iterator() { assert_eq!(std::iter::empty().collect::<ThinVec<String>>().into_vec(), Vec::<String>::new()); assert_eq!(std::iter::once(42).collect::<ThinVec<_>>().into_vec(), vec![42]); - assert_eq!(vec![1, 2].into_iter().collect::<ThinVec<_>>().into_vec(), vec![1, 2]); - assert_eq!(vec![1, 2, 3].into_iter().collect::<ThinVec<_>>().into_vec(), vec![1, 2, 3]); + assert_eq!([1, 2].into_iter().collect::<ThinVec<_>>().into_vec(), vec![1, 2]); + assert_eq!([1, 2, 3].into_iter().collect::<ThinVec<_>>().into_vec(), vec![1, 2, 3]); } #[test] diff --git a/compiler/rustc_data_structures/src/vec_map/tests.rs b/compiler/rustc_data_structures/src/vec_map/tests.rs index 9083de85982..458b60077dc 100644 --- a/compiler/rustc_data_structures/src/vec_map/tests.rs +++ b/compiler/rustc_data_structures/src/vec_map/tests.rs @@ -14,7 +14,7 @@ fn test_from_iterator() { ); assert_eq!(std::iter::once((42, true)).collect::<VecMap<_, _>>().into_vec(), vec![(42, true)]); assert_eq!( - vec![(1, true), (2, false)].into_iter().collect::<VecMap<_, _>>().into_vec(), + [(1, true), (2, false)].into_iter().collect::<VecMap<_, _>>().into_vec(), vec![(1, true), (2, false)] ); } @@ -41,7 +41,7 @@ fn test_insert() { #[test] fn test_get() { - let v = vec![(1, true), (2, false)].into_iter().collect::<VecMap<_, _>>(); + let v = [(1, true), (2, false)].into_iter().collect::<VecMap<_, _>>(); assert_eq!(v.get(&1), Some(&true)); assert_eq!(v.get(&2), Some(&false)); assert_eq!(v.get(&3), None); diff --git a/compiler/rustc_errors/src/json.rs b/compiler/rustc_errors/src/json.rs index dde978cd8c6..c2af2b2a86d 100644 --- a/compiler/rustc_errors/src/json.rs +++ b/compiler/rustc_errors/src/json.rs @@ -455,7 +455,7 @@ impl DiagnosticSpan { let backtrace_step = backtrace.next().map(|bt| { let call_site = Self::from_span_full(bt.call_site, false, None, None, backtrace, je); let def_site_span = - Self::from_span_full(bt.def_site, false, None, None, vec![].into_iter(), je); + Self::from_span_full(bt.def_site, false, None, None, [].into_iter(), je); Box::new(DiagnosticSpanMacroExpansion { span: call_site, macro_decl_name: bt.kind.descr(), diff --git a/compiler/rustc_expand/src/proc_macro_server.rs b/compiler/rustc_expand/src/proc_macro_server.rs index 56564656556..efbe0b65715 100644 --- a/compiler/rustc_expand/src/proc_macro_server.rs +++ b/compiler/rustc_expand/src/proc_macro_server.rs @@ -158,7 +158,7 @@ impl FromInternal<(TreeAndSpacing, &'_ mut Vec<Self>, &mut Rustc<'_, '_>)> for ch in data.as_str().chars() { escaped.extend(ch.escape_debug()); } - let stream = vec![ + let stream = [ Ident(sym::doc, false), Eq, TokenKind::lit(token::Str, Symbol::intern(&escaped), None), @@ -221,7 +221,7 @@ impl ToInternal<TokenStream> for TokenTree<Group, Punct, Ident, Literal> { let integer = TokenKind::lit(token::Integer, symbol, suffix); let a = tokenstream::TokenTree::token(minus, span); let b = tokenstream::TokenTree::token(integer, span); - return vec![a, b].into_iter().collect(); + return [a, b].into_iter().collect(); } TokenTree::Literal(self::Literal { lit: token::Lit { kind: token::Float, symbol, suffix }, @@ -232,7 +232,7 @@ impl ToInternal<TokenStream> for TokenTree<Group, Punct, Ident, Literal> { let float = TokenKind::lit(token::Float, symbol, suffix); let a = tokenstream::TokenTree::token(minus, span); let b = tokenstream::TokenTree::token(float, span); - return vec![a, b].into_iter().collect(); + return [a, b].into_iter().collect(); } TokenTree::Literal(self::Literal { lit, span }) => { return tokenstream::TokenTree::token(Literal(lit), span).into(); diff --git a/compiler/rustc_graphviz/src/tests.rs b/compiler/rustc_graphviz/src/tests.rs index a297bac86c4..154bae4cb05 100644 --- a/compiler/rustc_graphviz/src/tests.rs +++ b/compiler/rustc_graphviz/src/tests.rs @@ -56,7 +56,7 @@ impl NodeLabels<&'static str> { match self { UnlabelledNodes(len) => vec![None; len], AllNodesLabelled(lbls) => lbls.into_iter().map(Some).collect(), - SomeNodesLabelled(lbls) => lbls.into_iter().collect(), + SomeNodesLabelled(lbls) => lbls, } } diff --git a/compiler/rustc_incremental/src/persist/fs/tests.rs b/compiler/rustc_incremental/src/persist/fs/tests.rs index 652ef6bcdce..184796948b6 100644 --- a/compiler/rustc_incremental/src/persist/fs/tests.rs +++ b/compiler/rustc_incremental/src/persist/fs/tests.rs @@ -13,7 +13,7 @@ fn test_all_except_most_recent() { .keys() .cloned() .collect::<FxHashSet<PathBuf>>(), - vec![PathBuf::from("1"), PathBuf::from("2"), PathBuf::from("3"), PathBuf::from("4"),] + [PathBuf::from("1"), PathBuf::from("2"), PathBuf::from("3"), PathBuf::from("4"),] .into_iter() .collect::<FxHashSet<PathBuf>>() ); @@ -40,7 +40,7 @@ fn test_find_source_directory_in_iter() { // Find newest assert_eq!( find_source_directory_in_iter( - vec![ + [ PathBuf::from("crate-dir/s-3234-0000-svh"), PathBuf::from("crate-dir/s-2234-0000-svh"), PathBuf::from("crate-dir/s-1234-0000-svh") @@ -54,7 +54,7 @@ fn test_find_source_directory_in_iter() { // Filter out "-working" assert_eq!( find_source_directory_in_iter( - vec![ + [ PathBuf::from("crate-dir/s-3234-0000-working"), PathBuf::from("crate-dir/s-2234-0000-svh"), PathBuf::from("crate-dir/s-1234-0000-svh") @@ -66,12 +66,12 @@ fn test_find_source_directory_in_iter() { ); // Handle empty - assert_eq!(find_source_directory_in_iter(vec![].into_iter(), &already_visited), None); + assert_eq!(find_source_directory_in_iter([].into_iter(), &already_visited), None); // Handle only working assert_eq!( find_source_directory_in_iter( - vec![ + [ PathBuf::from("crate-dir/s-3234-0000-working"), PathBuf::from("crate-dir/s-2234-0000-working"), PathBuf::from("crate-dir/s-1234-0000-working") diff --git a/compiler/rustc_infer/src/infer/error_reporting/mod.rs b/compiler/rustc_infer/src/infer/error_reporting/mod.rs index f0c73d0c2f3..6d39dadc7ba 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/mod.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/mod.rs @@ -771,7 +771,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { self.suggest_boxing_for_return_impl_trait( err, ret_sp, - vec![then, else_sp].into_iter(), + [then, else_sp].into_iter(), ); } } @@ -807,11 +807,8 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { ); let sugg = arm_spans .flat_map(|sp| { - vec![ - (sp.shrink_to_lo(), "Box::new(".to_string()), - (sp.shrink_to_hi(), ")".to_string()), - ] - .into_iter() + [(sp.shrink_to_lo(), "Box::new(".to_string()), (sp.shrink_to_hi(), ")".to_string())] + .into_iter() }) .collect::<Vec<_>>(); err.multipart_suggestion( @@ -1924,7 +1921,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { .fields .iter() .filter(|field| field.vis.is_accessible_from(field.did, self.tcx)) - .map(|field| (field.ident.name, field.ty(self.tcx, expected_substs))) + .map(|field| (field.name, field.ty(self.tcx, expected_substs))) .find(|(_, ty)| same_type_modulo_infer(ty, exp_found.found)) { if let ObligationCauseCode::Pattern { span: Some(span), .. } = *cause.code() { 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 9cf6cde2591..8bb0e8b960c 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 @@ -540,8 +540,8 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { // error[E0284]: type annotations needed // --> file.rs:2:5 // | - // 2 | vec![Ok(2)].into_iter().collect()?; - // | ^^^^^^^ cannot infer type + // 2 | [Ok(2)].into_iter().collect()?; + // | ^^^^^^^ cannot infer type // | // = note: cannot resolve `<_ as std::ops::Try>::Ok == _` if span.contains(*call_span) { *call_span } else { span } diff --git a/compiler/rustc_metadata/src/rmeta/decoder.rs b/compiler/rustc_metadata/src/rmeta/decoder.rs index e39ea46c0c0..3ec384193c3 100644 --- a/compiler/rustc_metadata/src/rmeta/decoder.rs +++ b/compiler/rustc_metadata/src/rmeta/decoder.rs @@ -862,7 +862,7 @@ impl<'a, 'tcx> CrateMetadataRef<'a> { let ctor_did = data.ctor.map(|index| self.local_def_id(index)); ty::VariantDef::new( - self.item_ident(index, sess), + self.item_ident(index, sess).name, variant_did, ctor_did, data.discr, @@ -874,7 +874,7 @@ impl<'a, 'tcx> CrateMetadataRef<'a> { .decode(self) .map(|index| ty::FieldDef { did: self.local_def_id(index), - ident: self.item_ident(index, sess), + name: self.item_ident(index, sess).name, vis: self.get_visibility(index), }) .collect(), diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index 2e556275fb5..fa1752aaec3 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -1052,7 +1052,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { assert!(f.did.is_local()); f.did.index })); - self.encode_ident_span(def_id, variant.ident); + self.encode_ident_span(def_id, variant.ident(tcx)); self.encode_item_type(def_id); if variant.ctor_kind == CtorKind::Fn { // FIXME(eddyb) encode signature only in `encode_enum_variant_ctor`. @@ -1138,7 +1138,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { debug!("EncodeContext::encode_field({:?})", def_id); record!(self.tables.kind[def_id] <- EntryKind::Field); - self.encode_ident_span(def_id, field.ident); + self.encode_ident_span(def_id, field.ident(self.tcx)); self.encode_item_type(def_id); } diff --git a/compiler/rustc_middle/src/mir/mod.rs b/compiler/rustc_middle/src/mir/mod.rs index 52ef380001c..6d1d9dd9720 100644 --- a/compiler/rustc_middle/src/mir/mod.rs +++ b/compiler/rustc_middle/src/mir/mod.rs @@ -2439,7 +2439,7 @@ impl<'tcx> Debug for Rvalue<'tcx> { CtorKind::Fictive => { let mut struct_fmt = fmt.debug_struct(&name); for (field, place) in iter::zip(&variant_def.fields, places) { - struct_fmt.field(field.ident.as_str(), place); + struct_fmt.field(field.name.as_str(), place); } struct_fmt.finish() } @@ -2785,7 +2785,7 @@ impl UserTypeProjection { field: Field, ) -> Self { self.projs.push(ProjectionElem::Downcast( - Some(adt_def.variants[variant_index].ident.name), + Some(adt_def.variants[variant_index].name), variant_index, )); self.projs.push(ProjectionElem::Field(field, ())); diff --git a/compiler/rustc_middle/src/thir.rs b/compiler/rustc_middle/src/thir.rs index 8d6fd1e729d..d2e3ce97d12 100644 --- a/compiler/rustc_middle/src/thir.rs +++ b/compiler/rustc_middle/src/thir.rs @@ -726,7 +726,7 @@ impl<'tcx> fmt::Display for Pat<'tcx> { }; if let Some(variant) = variant { - write!(f, "{}", variant.ident)?; + write!(f, "{}", variant.name)?; // Only for Adt we can have `S {...}`, // which we handle separately here. @@ -738,7 +738,7 @@ impl<'tcx> fmt::Display for Pat<'tcx> { if let PatKind::Wild = *p.pattern.kind { continue; } - let name = variant.fields[p.field.index()].ident; + let name = variant.fields[p.field.index()].name; write!(f, "{}{}: {}", start_or_comma(), name, p.pattern)?; printed += 1; } diff --git a/compiler/rustc_middle/src/ty/closure.rs b/compiler/rustc_middle/src/ty/closure.rs index 771acc29649..c463d9a02f7 100644 --- a/compiler/rustc_middle/src/ty/closure.rs +++ b/compiler/rustc_middle/src/ty/closure.rs @@ -178,7 +178,7 @@ impl<'tcx> CapturedPlace<'tcx> { write!( &mut symbol, "__{}", - def.variants[variant].fields[idx as usize].ident.name.as_str(), + def.variants[variant].fields[idx as usize].name.as_str(), ) .unwrap(); } @@ -344,7 +344,7 @@ pub fn place_to_string_for_capture<'tcx>(tcx: TyCtxt<'tcx>, place: &HirPlace<'tc curr_string = format!( "{}.{}", curr_string, - def.variants[variant].fields[idx as usize].ident.name.as_str() + def.variants[variant].fields[idx as usize].name.as_str() ); } ty::Tuple(_) => { diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index 86ad573b5d7..0c4e3becabe 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -2452,7 +2452,7 @@ impl<'tcx> TyCtxt<'tcx> { ) -> Place<'tcx> { self.mk_place_elem( place, - PlaceElem::Downcast(Some(adt_def.variants[variant_index].ident.name), variant_index), + PlaceElem::Downcast(Some(adt_def.variants[variant_index].name), variant_index), ) } diff --git a/compiler/rustc_middle/src/ty/layout.rs b/compiler/rustc_middle/src/ty/layout.rs index 196fe7ce1b6..4e6b2acb67f 100644 --- a/compiler/rustc_middle/src/ty/layout.rs +++ b/compiler/rustc_middle/src/ty/layout.rs @@ -10,7 +10,7 @@ use rustc_hir::lang_items::LangItem; use rustc_index::bit_set::BitSet; use rustc_index::vec::{Idx, IndexVec}; use rustc_session::{config::OptLevel, DataTypeKind, FieldInfo, SizeKind, VariantInfo}; -use rustc_span::symbol::{Ident, Symbol}; +use rustc_span::symbol::Symbol; use rustc_span::{Span, DUMMY_SP}; use rustc_target::abi::call::{ ArgAbi, ArgAttribute, ArgAttributes, ArgExtension, Conv, FnAbi, PassMode, Reg, RegKind, @@ -1810,7 +1810,7 @@ impl<'tcx> LayoutCx<'tcx, TyCtxt<'tcx>> { let adt_kind = adt_def.adt_kind(); let adt_packed = adt_def.repr.pack.is_some(); - let build_variant_info = |n: Option<Ident>, flds: &[Symbol], layout: TyAndLayout<'tcx>| { + let build_variant_info = |n: Option<Symbol>, flds: &[Symbol], layout: TyAndLayout<'tcx>| { let mut min_size = Size::ZERO; let field_info: Vec<_> = flds .iter() @@ -1845,15 +1845,15 @@ impl<'tcx> LayoutCx<'tcx, TyCtxt<'tcx>> { if !adt_def.variants.is_empty() && layout.fields != FieldsShape::Primitive { debug!( "print-type-size `{:#?}` variant {}", - layout, adt_def.variants[index].ident + layout, adt_def.variants[index].name ); let variant_def = &adt_def.variants[index]; - let fields: Vec<_> = variant_def.fields.iter().map(|f| f.ident.name).collect(); + let fields: Vec<_> = variant_def.fields.iter().map(|f| f.name).collect(); record( adt_kind.into(), adt_packed, None, - vec![build_variant_info(Some(variant_def.ident), &fields, layout)], + vec![build_variant_info(Some(variant_def.name), &fields, layout)], ); } else { // (This case arises for *empty* enums; so give it @@ -1872,10 +1872,9 @@ impl<'tcx> LayoutCx<'tcx, TyCtxt<'tcx>> { .variants .iter_enumerated() .map(|(i, variant_def)| { - let fields: Vec<_> = - variant_def.fields.iter().map(|f| f.ident.name).collect(); + let fields: Vec<_> = variant_def.fields.iter().map(|f| f.name).collect(); build_variant_info( - Some(variant_def.ident), + Some(variant_def.name), &fields, layout.for_variant(self, i), ) diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index 16adf93b69a..2b079696be2 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -1504,8 +1504,7 @@ pub struct VariantDef { /// If this variant is a struct variant, then this is `None`. pub ctor_def_id: Option<DefId>, /// Variant or struct name. - #[stable_hasher(project(name))] - pub ident: Ident, + pub name: Symbol, /// Discriminant of this variant. pub discr: VariantDiscr, /// Fields of this variant. @@ -1534,7 +1533,7 @@ impl VariantDef { /// If someone speeds up attribute loading to not be a performance concern, they can /// remove this hack and use the constructor `DefId` everywhere. pub fn new( - ident: Ident, + name: Symbol, variant_did: Option<DefId>, ctor_def_id: Option<DefId>, discr: VariantDiscr, @@ -1546,9 +1545,9 @@ impl VariantDef { is_field_list_non_exhaustive: bool, ) -> Self { debug!( - "VariantDef::new(ident = {:?}, variant_did = {:?}, ctor_def_id = {:?}, discr = {:?}, + "VariantDef::new(name = {:?}, variant_did = {:?}, ctor_def_id = {:?}, discr = {:?}, fields = {:?}, ctor_kind = {:?}, adt_kind = {:?}, parent_did = {:?})", - ident, variant_did, ctor_def_id, discr, fields, ctor_kind, adt_kind, parent_did, + name, variant_did, ctor_def_id, discr, fields, ctor_kind, adt_kind, parent_did, ); let mut flags = VariantFlags::NO_VARIANT_FLAGS; @@ -1563,7 +1562,7 @@ impl VariantDef { VariantDef { def_id: variant_did.unwrap_or(parent_did), ctor_def_id, - ident, + name, discr, fields, ctor_kind, @@ -1582,6 +1581,11 @@ impl VariantDef { pub fn is_recovered(&self) -> bool { self.flags.intersects(VariantFlags::IS_RECOVERED) } + + /// Computes the `Ident` of this variant by looking up the `Span` + pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident { + Ident::new(self.name, tcx.def_ident_span(self.def_id).unwrap()) + } } #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)] @@ -1600,8 +1604,7 @@ pub enum VariantDiscr { #[derive(Debug, HashStable, TyEncodable, TyDecodable)] pub struct FieldDef { pub did: DefId, - #[stable_hasher(project(name))] - pub ident: Ident, + pub name: Symbol, pub vis: Visibility, } @@ -1776,6 +1779,11 @@ impl<'tcx> FieldDef { pub fn ty(&self, tcx: TyCtxt<'tcx>, subst: SubstsRef<'tcx>) -> Ty<'tcx> { tcx.type_of(self.did).subst(tcx, subst) } + + /// Computes the `Ident` of this variant by looking up the `Span` + pub fn ident(&self, tcx: TyCtxt<'_>) -> Ident { + Ident::new(self.name, tcx.def_ident_span(self.did).unwrap()) + } } pub type Attributes<'tcx> = &'tcx [ast::Attribute]; @@ -1892,7 +1900,10 @@ impl<'tcx> TyCtxt<'tcx> { } pub fn find_field_index(self, ident: Ident, variant: &VariantDef) -> Option<usize> { - variant.fields.iter().position(|field| self.hygienic_eq(ident, field.ident, variant.def_id)) + variant + .fields + .iter() + .position(|field| self.hygienic_eq(ident, field.ident(self), variant.def_id)) } /// Returns `true` if the impls are the same polarity and the trait either diff --git a/compiler/rustc_middle/src/ty/print/pretty.rs b/compiler/rustc_middle/src/ty/print/pretty.rs index c6454f3e0d0..350386f8d93 100644 --- a/compiler/rustc_middle/src/ty/print/pretty.rs +++ b/compiler/rustc_middle/src/ty/print/pretty.rs @@ -1475,7 +1475,7 @@ pub trait PrettyPrinter<'tcx>: if !first { p!(", "); } - p!(write("{}: ", field_def.ident), print(field)); + p!(write("{}: ", field_def.name), print(field)); first = false; } p!(" }}"); 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 c6a34ece245..b3126b72bb8 100644 --- a/compiler/rustc_mir_build/src/build/expr/as_place.rs +++ b/compiler/rustc_mir_build/src/build/expr/as_place.rs @@ -336,10 +336,7 @@ impl<'tcx> PlaceBuilder<'tcx> { } crate fn downcast(self, adt_def: &'tcx AdtDef, variant_index: VariantIdx) -> Self { - self.project(PlaceElem::Downcast( - Some(adt_def.variants[variant_index].ident.name), - variant_index, - )) + self.project(PlaceElem::Downcast(Some(adt_def.variants[variant_index].name), variant_index)) } fn index(self, index: Local) -> Self { diff --git a/compiler/rustc_mir_build/src/build/matches/test.rs b/compiler/rustc_mir_build/src/build/matches/test.rs index a01df2372a0..7ed5d1d67ab 100644 --- a/compiler/rustc_mir_build/src/build/matches/test.rs +++ b/compiler/rustc_mir_build/src/build/matches/test.rs @@ -754,10 +754,8 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { // So, if we have a match-pattern like `x @ Enum::Variant(P1, P2)`, // we want to create a set of derived match-patterns like // `(x as Variant).0 @ P1` and `(x as Variant).1 @ P1`. - let elem = ProjectionElem::Downcast( - Some(adt_def.variants[variant_index].ident.name), - variant_index, - ); + let elem = + ProjectionElem::Downcast(Some(adt_def.variants[variant_index].name), variant_index); let downcast_place = match_pair.place.project(elem); // `(x as Variant)` let consequent_match_pairs = subpatterns.iter().map(|subpattern| { // e.g., `(x as Variant).0` 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 7a4fd6ffc4a..0980c669f33 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/check_match.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/check_match.rs @@ -327,7 +327,7 @@ fn check_for_bindings_named_same_as_variants( if let ty::Adt(edef, _) = pat_ty.kind() { if edef.is_enum() && edef.variants.iter().any(|variant| { - variant.ident == ident && variant.ctor_kind == CtorKind::Const + variant.ident(cx.tcx) == ident && variant.ctor_kind == CtorKind::Const }) { let variant_count = edef.variants.len(); @@ -627,7 +627,7 @@ fn maybe_point_at_variant<'a, 'p: 'a, 'tcx: 'a>( continue; } } - let sp = def.variants[*variant_index].ident.span; + let sp = def.variants[*variant_index].ident(cx.tcx).span; if covered.contains(&sp) { // Don't point at variants that have already been covered due to other patterns to avoid // visual clutter. 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 368e3957dd0..801c8778bff 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/deconstruct_pat.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/deconstruct_pat.rs @@ -1648,7 +1648,7 @@ impl<'p, 'tcx> fmt::Debug for DeconstructedPat<'p, 'tcx> { }; if let Some(variant) = variant { - write!(f, "{}", variant.ident)?; + write!(f, "{}", variant.name)?; } // Without `cx`, we can't know which field corresponds to which, so we can't diff --git a/compiler/rustc_mir_dataflow/src/elaborate_drops.rs b/compiler/rustc_mir_dataflow/src/elaborate_drops.rs index 11856f6e047..501bc96401a 100644 --- a/compiler/rustc_mir_dataflow/src/elaborate_drops.rs +++ b/compiler/rustc_mir_dataflow/src/elaborate_drops.rs @@ -491,7 +491,7 @@ where if let Some(variant_path) = subpath { let base_place = tcx.mk_place_elem( self.place, - ProjectionElem::Downcast(Some(variant.ident.name), variant_index), + ProjectionElem::Downcast(Some(variant.name), variant_index), ); let fields = self.move_paths_for_fields(base_place, variant_path, &variant, substs); values.push(discr.val); diff --git a/compiler/rustc_parse/src/parser/diagnostics.rs b/compiler/rustc_parse/src/parser/diagnostics.rs index 9677e7642b8..4121a759c37 100644 --- a/compiler/rustc_parse/src/parser/diagnostics.rs +++ b/compiler/rustc_parse/src/parser/diagnostics.rs @@ -550,8 +550,8 @@ impl<'a> Parser<'a> { /// a diagnostic to suggest removing them. /// /// ```ignore (diagnostic) - /// let _ = vec![1, 2, 3].into_iter().collect::<Vec<usize>>>>(); - /// ^^ help: remove extra angle brackets + /// let _ = [1, 2, 3].into_iter().collect::<Vec<usize>>>>(); + /// ^^ help: remove extra angle brackets /// ``` /// /// If `true` is returned, then trailing brackets were recovered, tokens were consumed diff --git a/compiler/rustc_privacy/src/lib.rs b/compiler/rustc_privacy/src/lib.rs index e93cd813db5..45da5f81224 100644 --- a/compiler/rustc_privacy/src/lib.rs +++ b/compiler/rustc_privacy/src/lib.rs @@ -903,7 +903,7 @@ impl<'tcx> NamePrivacyVisitor<'tcx> { let def_id = self.tcx.adjust_ident_and_get_scope(ident, def.did, hir_id).1; if !field.vis.is_accessible_from(def_id, self.tcx) { let label = if in_update_syntax { - format!("field `{}` is private", field.ident) + format!("field `{}` is private", field.name) } else { "private field".to_string() }; @@ -913,7 +913,7 @@ impl<'tcx> NamePrivacyVisitor<'tcx> { span, E0451, "field `{}` of {} `{}` is private", - field.ident, + field.name, def.variant_descr(), self.tcx.def_path_str(def.did) ) diff --git a/compiler/rustc_span/src/def_id.rs b/compiler/rustc_span/src/def_id.rs index 24d2a8ac073..0bba918994c 100644 --- a/compiler/rustc_span/src/def_id.rs +++ b/compiler/rustc_span/src/def_id.rs @@ -221,10 +221,17 @@ impl<D: Decoder> Decodable<D> for DefIndex { #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Copy)] // On below-64 bit systems we can simply use the derived `Hash` impl #[cfg_attr(not(target_pointer_width = "64"), derive(Hash))] -// Note that the order is essential here, see below why +#[repr(C)] +// We guarantee field order. Note that the order is essential here, see below why. pub struct DefId { + // cfg-ing the order of fields so that the `DefIndex` which is high entropy always ends up in + // the lower bits no matter the endianness. This allows the compiler to turn that `Hash` impl + // into a direct call to 'u64::hash(_)`. + #[cfg(not(all(target_pointer_width = "64", target_endian = "big")))] pub index: DefIndex, pub krate: CrateNum, + #[cfg(all(target_pointer_width = "64", target_endian = "big"))] + pub index: DefIndex, } // On 64-bit systems, we can hash the whole `DefId` as one `u64` instead of two `u32`s. This diff --git a/compiler/rustc_target/src/spec/avr_gnu_base.rs b/compiler/rustc_target/src/spec/avr_gnu_base.rs index 2cb2661a526..a6c1b344d70 100644 --- a/compiler/rustc_target/src/spec/avr_gnu_base.rs +++ b/compiler/rustc_target/src/spec/avr_gnu_base.rs @@ -17,12 +17,10 @@ pub fn target(target_cpu: String) -> Target { linker: Some("avr-gcc".to_owned()), executables: true, eh_frame_header: false, - pre_link_args: vec![(LinkerFlavor::Gcc, vec![format!("-mmcu={}", target_cpu)])] - .into_iter() - .collect(), - late_link_args: vec![(LinkerFlavor::Gcc, vec!["-lgcc".to_owned()])] + pre_link_args: [(LinkerFlavor::Gcc, vec![format!("-mmcu={}", target_cpu)])] .into_iter() .collect(), + late_link_args: [(LinkerFlavor::Gcc, vec!["-lgcc".to_owned()])].into_iter().collect(), max_atomic_width: Some(0), atomic_cas: false, ..TargetOptions::default() diff --git a/compiler/rustc_target/src/spec/mod.rs b/compiler/rustc_target/src/spec/mod.rs index ca1949b9f75..2c149318730 100644 --- a/compiler/rustc_target/src/spec/mod.rs +++ b/compiler/rustc_target/src/spec/mod.rs @@ -574,15 +574,15 @@ impl ToJson for StackProbeType { fn to_json(&self) -> Json { Json::Object(match self { StackProbeType::None => { - vec![(String::from("kind"), "none".to_json())].into_iter().collect() + [(String::from("kind"), "none".to_json())].into_iter().collect() } StackProbeType::Inline => { - vec![(String::from("kind"), "inline".to_json())].into_iter().collect() + [(String::from("kind"), "inline".to_json())].into_iter().collect() } StackProbeType::Call => { - vec![(String::from("kind"), "call".to_json())].into_iter().collect() + [(String::from("kind"), "call".to_json())].into_iter().collect() } - StackProbeType::InlineOrCall { min_llvm_version_for_inline } => vec![ + StackProbeType::InlineOrCall { min_llvm_version_for_inline } => [ (String::from("kind"), "inline-or-call".to_json()), ( String::from("min-llvm-version-for-inline"), 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 a9ae0ec53c7..72878b6cb38 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs @@ -2247,7 +2247,7 @@ pub fn recursive_type_with_infinite_size_error( spans .iter() .flat_map(|&span| { - vec![ + [ (span.shrink_to_lo(), "Box<".to_string()), (span.shrink_to_hi(), ">".to_string()), ] 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 0f276718c16..8704c4c7469 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs @@ -1226,7 +1226,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { .returns .iter() .flat_map(|expr| { - vec![ + [ (expr.span.shrink_to_lo(), "Box::new(".to_string()), (expr.span.shrink_to_hi(), ")".to_string()), ] diff --git a/compiler/rustc_trait_selection/src/traits/select/mod.rs b/compiler/rustc_trait_selection/src/traits/select/mod.rs index fa88c8ee370..bb3b3203a7c 100644 --- a/compiler/rustc_trait_selection/src/traits/select/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/select/mod.rs @@ -1953,7 +1953,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { ty::Generator(_, ref substs, _) => { let ty = self.infcx.shallow_resolve(substs.as_generator().tupled_upvars_ty()); let witness = substs.as_generator().witness(); - t.rebind(vec![ty].into_iter().chain(iter::once(witness)).collect()) + t.rebind([ty].into_iter().chain(iter::once(witness)).collect()) } ty::GeneratorWitness(types) => { diff --git a/compiler/rustc_typeck/src/astconv/mod.rs b/compiler/rustc_typeck/src/astconv/mod.rs index 8226ffbccc4..17cf3667611 100644 --- a/compiler/rustc_typeck/src/astconv/mod.rs +++ b/compiler/rustc_typeck/src/astconv/mod.rs @@ -1727,7 +1727,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { let variant_def = adt_def .variants .iter() - .find(|vd| tcx.hygienic_eq(assoc_ident, vd.ident, adt_def.did)); + .find(|vd| tcx.hygienic_eq(assoc_ident, vd.ident(tcx), adt_def.did)); if let Some(variant_def) = variant_def { if permit_variants { tcx.check_stability(variant_def.def_id, Some(hir_ref_id), span, None); @@ -1786,7 +1786,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { &adt_def .variants .iter() - .map(|variant| variant.ident.name) + .map(|variant| variant.name) .collect::<Vec<Symbol>>(), assoc_ident.name, None, diff --git a/compiler/rustc_typeck/src/check/check.rs b/compiler/rustc_typeck/src/check/check.rs index dcf42e1aefe..de560d50795 100644 --- a/compiler/rustc_typeck/src/check/check.rs +++ b/compiler/rustc_typeck/src/check/check.rs @@ -626,6 +626,7 @@ pub(super) fn check_opaque_for_cycles<'tcx>( /// /// Without this check the above code is incorrectly accepted: we would ICE if /// some tried, for example, to clone an `Option<X<&mut ()>>`. +#[instrument(level = "debug", skip(tcx))] fn check_opaque_meets_bounds<'tcx>( tcx: TyCtxt<'tcx>, def_id: LocalDefId, @@ -633,17 +634,14 @@ fn check_opaque_meets_bounds<'tcx>( span: Span, origin: &hir::OpaqueTyOrigin, ) { - match origin { - // Checked when type checking the function containing them. - hir::OpaqueTyOrigin::FnReturn(..) | hir::OpaqueTyOrigin::AsyncFn(..) => return, - // Can have different predicates to their defining use - hir::OpaqueTyOrigin::TyAlias => {} - } - let hir_id = tcx.hir().local_def_id_to_hir_id(def_id); - let param_env = tcx.param_env(def_id); + let defining_use_anchor = match *origin { + hir::OpaqueTyOrigin::FnReturn(did) | hir::OpaqueTyOrigin::AsyncFn(did) => did, + hir::OpaqueTyOrigin::TyAlias => def_id, + }; + let param_env = tcx.param_env(defining_use_anchor); - tcx.infer_ctxt().enter(move |infcx| { + tcx.infer_ctxt().with_opaque_type_inference(defining_use_anchor).enter(move |infcx| { let inh = Inherited::new(infcx, def_id); let infcx = &inh.infcx; let opaque_ty = tcx.mk_opaque(def_id.to_def_id(), substs); @@ -656,16 +654,15 @@ fn check_opaque_meets_bounds<'tcx>( let opaque_type_map = infcx.inner.borrow().opaque_types.clone(); for (OpaqueTypeKey { def_id, substs }, opaque_defn) in opaque_type_map { - match infcx - .at(&misc_cause, param_env) - .eq(opaque_defn.concrete_ty, tcx.type_of(def_id).subst(tcx, substs)) - { + let hidden_type = tcx.type_of(def_id).subst(tcx, substs); + trace!(?hidden_type); + match infcx.at(&misc_cause, param_env).eq(opaque_defn.concrete_ty, hidden_type) { Ok(infer_ok) => inh.register_infer_ok_obligations(infer_ok), Err(ty_err) => tcx.sess.delay_span_bug( - opaque_defn.definition_span, + span, &format!( - "could not unify `{}` with revealed type:\n{}", - opaque_defn.concrete_ty, ty_err, + "could not check bounds on revealed type `{}`:\n{}", + hidden_type, ty_err, ), ), } @@ -678,10 +675,17 @@ fn check_opaque_meets_bounds<'tcx>( infcx.report_fulfillment_errors(&errors, None, false); } - // Finally, resolve all regions. This catches wily misuses of - // lifetime parameters. - let fcx = FnCtxt::new(&inh, param_env, hir_id); - fcx.regionck_item(hir_id, span, FxHashSet::default()); + match origin { + // Checked when type checking the function containing them. + hir::OpaqueTyOrigin::FnReturn(..) | hir::OpaqueTyOrigin::AsyncFn(..) => return, + // Can have different predicates to their defining use + hir::OpaqueTyOrigin::TyAlias => { + // Finally, resolve all regions. This catches wily misuses of + // lifetime parameters. + let fcx = FnCtxt::new(&inh, param_env, hir_id); + fcx.regionck_item(hir_id, span, FxHashSet::default()); + } + } }); } @@ -1173,7 +1177,7 @@ pub(super) fn check_packed_inner( if let ty::Adt(def, _) = field.ty(tcx, substs).kind() { if !stack.contains(&def.did) { if let Some(mut defs) = check_packed_inner(tcx, def.did, stack) { - defs.push((def.did, field.ident.span)); + defs.push((def.did, field.ident(tcx).span)); return Some(defs); } } diff --git a/compiler/rustc_typeck/src/check/coercion.rs b/compiler/rustc_typeck/src/check/coercion.rs index 6192c77d6c6..01221e5dfa9 100644 --- a/compiler/rustc_typeck/src/check/coercion.rs +++ b/compiler/rustc_typeck/src/check/coercion.rs @@ -1667,10 +1667,10 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { ], Applicability::MachineApplicable, ); - let sugg = vec![sp, cause.span] + let sugg = [sp, cause.span] .into_iter() .flat_map(|sp| { - vec![ + [ (sp.shrink_to_lo(), "Box::new(".to_string()), (sp.shrink_to_hi(), ")".to_string()), ] diff --git a/compiler/rustc_typeck/src/check/expr.rs b/compiler/rustc_typeck/src/check/expr.rs index 621938c9b78..14180526d84 100644 --- a/compiler/rustc_typeck/src/check/expr.rs +++ b/compiler/rustc_typeck/src/check/expr.rs @@ -1376,7 +1376,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .fields .iter() .enumerate() - .map(|(i, field)| (field.ident.normalize_to_macros_2_0(), (i, field))) + .map(|(i, field)| (field.ident(tcx).normalize_to_macros_2_0(), (i, field))) .collect::<FxHashMap<_, _>>(); let mut seen_fields = FxHashMap::default(); @@ -1457,7 +1457,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { expr_span, self.field_ty(base_expr.span, f, base_subs), ); - let ident = self.tcx.adjust_ident(f.ident, variant.def_id); + 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); @@ -1475,10 +1477,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { &cause, target_ty, fru_ty, - FieldMisMatch( - variant.ident.name, - ident.name, - ), + FieldMisMatch(variant.name, ident.name), ) .emit(), } @@ -1665,7 +1664,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { "{} `{}::{}` has no field named `{}`", kind_name, actual, - variant.ident, + variant.name, field.ident ), _ => struct_span_err!( @@ -1680,15 +1679,17 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }, ty, ); + + let variant_ident_span = self.tcx.def_ident_span(variant.def_id).unwrap(); match variant.ctor_kind { CtorKind::Fn => match ty.kind() { ty::Adt(adt, ..) if adt.is_enum() => { err.span_label( - variant.ident.span, + variant_ident_span, format!( "`{adt}::{variant}` defined here", adt = ty, - variant = variant.ident, + variant = variant.name, ), ); err.span_label(field.ident.span, "field does not exist"); @@ -1697,18 +1698,18 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { &format!( "`{adt}::{variant}` is a tuple {kind_name}, use the appropriate syntax", adt = ty, - variant = variant.ident, + variant = variant.name, ), format!( "{adt}::{variant}(/* fields */)", adt = ty, - variant = variant.ident, + variant = variant.name, ), Applicability::HasPlaceholders, ); } _ => { - err.span_label(variant.ident.span, format!("`{adt}` defined here", adt = ty)); + err.span_label(variant_ident_span, format!("`{adt}` defined here", adt = ty)); err.span_label(field.ident.span, "field does not exist"); err.span_suggestion_verbose( expr_span, @@ -1740,7 +1741,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if adt.is_enum() { err.span_label( field.ident.span, - format!("`{}::{}` does not have this field", ty, variant.ident), + format!("`{}::{}` does not have this field", ty, variant.name), ); } else { err.span_label( @@ -1775,12 +1776,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .iter() .filter_map(|field| { // ignore already set fields and private fields from non-local crates - if skip.iter().any(|&x| x == field.ident.name) + if skip.iter().any(|&x| x == field.name) || (!variant.def_id.is_local() && !field.vis.is_public()) { None } else { - Some(field.ident.name) + Some(field.name) } }) .collect::<Vec<Symbol>>(); @@ -1795,11 +1796,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .filter(|field| { let def_scope = self .tcx - .adjust_ident_and_get_scope(field.ident, variant.def_id, self.body_id) + .adjust_ident_and_get_scope(field.ident(self.tcx), variant.def_id, self.body_id) .1; field.vis.is_accessible_from(def_scope, self.tcx) }) - .map(|field| field.ident.name) + .map(|field| field.name) .collect() } @@ -1834,8 +1835,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let (ident, def_scope) = self.tcx.adjust_ident_and_get_scope(field, base_def.did, self.body_id); let fields = &base_def.non_enum_variant().fields; - if let Some(index) = - fields.iter().position(|f| f.ident.normalize_to_macros_2_0() == ident) + if let Some(index) = fields + .iter() + .position(|f| f.ident(self.tcx).normalize_to_macros_2_0() == ident) { let field = &fields[index]; let field_ty = self.field_ty(expr.span, field, substs); @@ -1916,7 +1918,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if let ty::Adt(def, _) = output_ty.kind() { // no field access on enum type if !def.is_enum() { - if def.non_enum_variant().fields.iter().any(|field| field.ident == field_ident) { + if def + .non_enum_variant() + .fields + .iter() + .any(|field| field.ident(self.tcx) == field_ident) + { add_label = false; err.span_label( field_ident.span, @@ -2075,7 +2082,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .unwrap() .fields .iter() - .any(|f| f.ident == field) + .any(|f| f.ident(self.tcx) == field) { if let Some(dot_loc) = expr_snippet.rfind('.') { found = true; @@ -2262,7 +2269,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { span, candidate_field, field_path ); - if candidate_field.ident == target_field { + if candidate_field.ident(self.tcx) == target_field { Some(field_path) } else if field_path.len() > 3 { // For compile-time reasons and to avoid infinite recursion we only check for fields @@ -2271,11 +2278,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } else { // recursively search fields of `candidate_field` if it's a ty::Adt - field_path.push(candidate_field.ident.normalize_to_macros_2_0()); + field_path.push(candidate_field.ident(self.tcx).normalize_to_macros_2_0()); let field_ty = candidate_field.ty(self.tcx, subst); if let Some((nested_fields, subst)) = self.get_field_candidates(span, &field_ty) { for field in nested_fields.iter() { - let ident = field.ident.normalize_to_macros_2_0(); + let ident = field.ident(self.tcx).normalize_to_macros_2_0(); if ident == target_field { return Some(field_path); } else { diff --git a/compiler/rustc_typeck/src/check/method/mod.rs b/compiler/rustc_typeck/src/check/method/mod.rs index f7f4c52c2a1..ac3e09318e5 100644 --- a/compiler/rustc_typeck/src/check/method/mod.rs +++ b/compiler/rustc_typeck/src/check/method/mod.rs @@ -482,7 +482,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let variant_def = adt_def .variants .iter() - .find(|vd| tcx.hygienic_eq(method_name, vd.ident, adt_def.did)); + .find(|vd| tcx.hygienic_eq(method_name, vd.ident(tcx), adt_def.did)); if let Some(variant_def) = variant_def { // Braced variants generate unusable names in value namespace (reserved for // possible future use), so variants resolved as associated items may refer to diff --git a/compiler/rustc_typeck/src/check/method/suggest.rs b/compiler/rustc_typeck/src/check/method/suggest.rs index 1a6fcbc57bf..7cda27041a2 100644 --- a/compiler/rustc_typeck/src/check/method/suggest.rs +++ b/compiler/rustc_typeck/src/check/method/suggest.rs @@ -997,7 +997,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if unsatisfied_predicates.is_empty() && actual.is_enum() { let adt_def = actual.ty_adt_def().expect("enum is not an ADT"); if let Some(suggestion) = lev_distance::find_best_match_for_name( - &adt_def.variants.iter().map(|s| s.ident.name).collect::<Vec<_>>(), + &adt_def.variants.iter().map(|s| s.name).collect::<Vec<_>>(), item_name.name, None, ) { diff --git a/compiler/rustc_typeck/src/check/pat.rs b/compiler/rustc_typeck/src/check/pat.rs index ec06e0b1126..17b97d4cad1 100644 --- a/compiler/rustc_typeck/src/check/pat.rs +++ b/compiler/rustc_typeck/src/check/pat.rs @@ -1029,7 +1029,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let field_def_spans = if fields.is_empty() { vec![res_span] } else { - fields.iter().map(|f| f.ident.span).collect() + fields.iter().map(|f| f.ident(self.tcx).span).collect() }; let last_field_def_span = *field_def_spans.last().unwrap(); @@ -1231,7 +1231,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .fields .iter() .enumerate() - .map(|(i, field)| (field.ident.normalize_to_macros_2_0(), (i, field))) + .map(|(i, field)| (field.ident(self.tcx).normalize_to_macros_2_0(), (i, field))) .collect::<FxHashMap<_, _>>(); // Keep track of which fields have already appeared in the pattern. @@ -1272,7 +1272,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let mut unmentioned_fields = variant .fields .iter() - .map(|field| (field, field.ident.normalize_to_macros_2_0())) + .map(|field| (field, field.ident(self.tcx).normalize_to_macros_2_0())) .filter(|(_, ident)| !used_fields.contains_key(ident)) .collect::<Vec<_>>(); @@ -1579,7 +1579,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { fields: &[hir::PatField<'_>], variant: &VariantDef, ) -> String { - let variant_field_idents = variant.fields.iter().map(|f| f.ident).collect::<Vec<Ident>>(); + let variant_field_idents = + variant.fields.iter().map(|f| f.ident(self.tcx)).collect::<Vec<Ident>>(); fields .iter() .map(|field| { diff --git a/compiler/rustc_typeck/src/coherence/builtin.rs b/compiler/rustc_typeck/src/coherence/builtin.rs index d5494c5a685..dff6b7b58a0 100644 --- a/compiler/rustc_typeck/src/coherence/builtin.rs +++ b/compiler/rustc_typeck/src/coherence/builtin.rs @@ -199,7 +199,7 @@ fn visit_implementation_of_dispatch_from_dyn<'tcx>(tcx: TyCtxt<'tcx>, impl_did: ) .note(&format!( "extra field `{}` of type `{}` is not allowed", - field.ident, ty_a, + field.name, ty_a, )) .emit(); @@ -235,7 +235,7 @@ fn visit_implementation_of_dispatch_from_dyn<'tcx>(tcx: TyCtxt<'tcx>, impl_did: .map(|field| { format!( "`{}` (`{}` to `{}`)", - field.ident, + field.name, field.ty(tcx, substs_a), field.ty(tcx, substs_b), ) @@ -479,7 +479,7 @@ pub fn coerce_unsized_info<'tcx>(tcx: TyCtxt<'tcx>, impl_did: DefId) -> CoerceUn diff_fields .iter() .map(|&(i, a, b)| { - format!("`{}` (`{}` to `{}`)", fields[i].ident, a, b) + format!("`{}` (`{}` to `{}`)", fields[i].name, a, b) }) .collect::<Vec<_>>() .join(", ") diff --git a/compiler/rustc_typeck/src/collect.rs b/compiler/rustc_typeck/src/collect.rs index ccf8d1d9cea..3cccdb27448 100644 --- a/compiler/rustc_typeck/src/collect.rs +++ b/compiler/rustc_typeck/src/collect.rs @@ -994,7 +994,7 @@ fn convert_variant( seen_fields.insert(f.ident.normalize_to_macros_2_0(), f.span); } - ty::FieldDef { did: fid.to_def_id(), ident: f.ident, vis: tcx.visibility(fid) } + ty::FieldDef { did: fid.to_def_id(), name: f.ident.name, vis: tcx.visibility(fid) } }) .collect(); let recovered = match def { @@ -1002,7 +1002,7 @@ fn convert_variant( _ => false, }; ty::VariantDef::new( - ident, + ident.name, variant_did.map(LocalDefId::to_def_id), ctor_did.map(LocalDefId::to_def_id), discr, diff --git a/compiler/rustc_typeck/src/variance/terms.rs b/compiler/rustc_typeck/src/variance/terms.rs index d7f9df668bf..36fbfc21ff5 100644 --- a/compiler/rustc_typeck/src/variance/terms.rs +++ b/compiler/rustc_typeck/src/variance/terms.rs @@ -86,7 +86,7 @@ pub fn determine_parameters_to_be_inferred<'a, 'tcx>( fn lang_items(tcx: TyCtxt<'_>) -> Vec<(hir::HirId, Vec<ty::Variance>)> { let lang_items = tcx.lang_items(); - let all = vec![ + let all = [ (lang_items.phantom_data(), vec![ty::Covariant]), (lang_items.unsafe_cell_type(), vec![ty::Invariant]), ]; diff --git a/library/alloc/src/collections/btree/map/tests.rs b/library/alloc/src/collections/btree/map/tests.rs index c95aeeaa605..b39b5409ae4 100644 --- a/library/alloc/src/collections/btree/map/tests.rs +++ b/library/alloc/src/collections/btree/map/tests.rs @@ -728,7 +728,7 @@ fn test_range_large() { #[test] fn test_range_inclusive_max_value() { let max = usize::MAX; - let map: BTreeMap<_, _> = vec![(max, 0)].into_iter().collect(); + let map: BTreeMap<_, _> = [(max, 0)].into_iter().collect(); assert_eq!(map.range(max..=max).collect::<Vec<_>>(), &[(&max, &0)]); } @@ -2128,7 +2128,7 @@ fn test_into_iter_drop_leak_height_1() { #[test] fn test_into_keys() { - let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')]; + let vec = [(1, 'a'), (2, 'b'), (3, 'c')]; let map: BTreeMap<_, _> = vec.into_iter().collect(); let keys: Vec<_> = map.into_keys().collect(); diff --git a/library/alloc/src/collections/vec_deque/mod.rs b/library/alloc/src/collections/vec_deque/mod.rs index 075becfb7d1..1259c53bfab 100644 --- a/library/alloc/src/collections/vec_deque/mod.rs +++ b/library/alloc/src/collections/vec_deque/mod.rs @@ -669,7 +669,7 @@ impl<T, A: Allocator> VecDeque<T, A> { /// ``` /// use std::collections::VecDeque; /// - /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect(); + /// let mut buf: VecDeque<i32> = [1].into_iter().collect(); /// buf.reserve_exact(10); /// assert!(buf.capacity() >= 11); /// ``` @@ -692,7 +692,7 @@ impl<T, A: Allocator> VecDeque<T, A> { /// ``` /// use std::collections::VecDeque; /// - /// let mut buf: VecDeque<i32> = vec![1].into_iter().collect(); + /// let mut buf: VecDeque<i32> = [1].into_iter().collect(); /// buf.reserve(10); /// assert!(buf.capacity() >= 11); /// ``` @@ -1153,7 +1153,7 @@ impl<T, A: Allocator> VecDeque<T, A> { /// ``` /// use std::collections::VecDeque; /// - /// let v: VecDeque<_> = vec![1, 2, 3].into_iter().collect(); + /// let v: VecDeque<_> = [1, 2, 3].into_iter().collect(); /// let range = v.range(2..).copied().collect::<VecDeque<_>>(); /// assert_eq!(range, [3]); /// @@ -1188,7 +1188,7 @@ impl<T, A: Allocator> VecDeque<T, A> { /// ``` /// use std::collections::VecDeque; /// - /// let mut v: VecDeque<_> = vec![1, 2, 3].into_iter().collect(); + /// let mut v: VecDeque<_> = [1, 2, 3].into_iter().collect(); /// for v in v.range_mut(2..) { /// *v *= 2; /// } @@ -1235,7 +1235,7 @@ impl<T, A: Allocator> VecDeque<T, A> { /// ``` /// use std::collections::VecDeque; /// - /// let mut v: VecDeque<_> = vec![1, 2, 3].into_iter().collect(); + /// let mut v: VecDeque<_> = [1, 2, 3].into_iter().collect(); /// let drained = v.drain(2..).collect::<VecDeque<_>>(); /// assert_eq!(drained, [3]); /// assert_eq!(v, [1, 2]); @@ -2025,7 +2025,7 @@ impl<T, A: Allocator> VecDeque<T, A> { /// ``` /// use std::collections::VecDeque; /// - /// let mut buf: VecDeque<_> = vec![1, 2, 3].into_iter().collect(); + /// let mut buf: VecDeque<_> = [1, 2, 3].into_iter().collect(); /// let buf2 = buf.split_off(1); /// assert_eq!(buf, [1]); /// assert_eq!(buf2, [2, 3]); @@ -2091,8 +2091,8 @@ impl<T, A: Allocator> VecDeque<T, A> { /// ``` /// use std::collections::VecDeque; /// - /// let mut buf: VecDeque<_> = vec![1, 2].into_iter().collect(); - /// let mut buf2: VecDeque<_> = vec![3, 4].into_iter().collect(); + /// let mut buf: VecDeque<_> = [1, 2].into_iter().collect(); + /// let mut buf2: VecDeque<_> = [3, 4].into_iter().collect(); /// buf.append(&mut buf2); /// assert_eq!(buf, [1, 2, 3, 4]); /// assert_eq!(buf2, []); diff --git a/library/alloc/tests/linked_list.rs b/library/alloc/tests/linked_list.rs index afcb9e03fd0..5f5bd9af2fe 100644 --- a/library/alloc/tests/linked_list.rs +++ b/library/alloc/tests/linked_list.rs @@ -304,7 +304,7 @@ fn test_show() { let list: LinkedList<_> = (0..10).collect(); assert_eq!(format!("{:?}", list), "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]"); - let list: LinkedList<_> = vec!["just", "one", "test", "more"].iter().cloned().collect(); + let list: LinkedList<_> = ["just", "one", "test", "more"].into_iter().collect(); assert_eq!(format!("{:?}", list), "[\"just\", \"one\", \"test\", \"more\"]"); } @@ -336,7 +336,7 @@ fn test_extend() { assert_eq!(a.len(), 4); assert!(a.iter().eq(&[1, 2, 3, 4])); - let b: LinkedList<_> = vec![5, 6, 7].into_iter().collect(); + let b: LinkedList<_> = [5, 6, 7].into_iter().collect(); a.extend(b); // specializes to `append` assert_eq!(a.len(), 7); @@ -375,7 +375,7 @@ fn drain_filter_empty() { #[test] fn drain_filter_zst() { - let mut list: LinkedList<_> = vec![(), (), (), (), ()].into_iter().collect(); + let mut list: LinkedList<_> = [(), (), (), (), ()].into_iter().collect(); let initial_len = list.len(); let mut count = 0; @@ -398,7 +398,7 @@ fn drain_filter_zst() { #[test] fn drain_filter_false() { - let mut list: LinkedList<_> = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10].into_iter().collect(); + let mut list: LinkedList<_> = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].into_iter().collect(); let initial_len = list.len(); let mut count = 0; @@ -421,7 +421,7 @@ fn drain_filter_false() { #[test] fn drain_filter_true() { - let mut list: LinkedList<_> = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10].into_iter().collect(); + let mut list: LinkedList<_> = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].into_iter().collect(); let initial_len = list.len(); let mut count = 0; @@ -447,7 +447,7 @@ fn drain_filter_true() { fn drain_filter_complex() { { // [+xxx++++++xxxxx++++x+x++] - let mut list = vec![ + let mut list = [ 1, 2, 4, 6, 7, 9, 11, 13, 15, 17, 18, 20, 22, 24, 26, 27, 29, 31, 33, 34, 35, 36, 37, 39, ] @@ -467,11 +467,10 @@ fn drain_filter_complex() { { // [xxx++++++xxxxx++++x+x++] - let mut list = vec![ - 2, 4, 6, 7, 9, 11, 13, 15, 17, 18, 20, 22, 24, 26, 27, 29, 31, 33, 34, 35, 36, 37, 39, - ] - .into_iter() - .collect::<LinkedList<_>>(); + let mut list = + [2, 4, 6, 7, 9, 11, 13, 15, 17, 18, 20, 22, 24, 26, 27, 29, 31, 33, 34, 35, 36, 37, 39] + .into_iter() + .collect::<LinkedList<_>>(); let removed = list.drain_filter(|x| *x % 2 == 0).collect::<Vec<_>>(); assert_eq!(removed.len(), 10); @@ -487,7 +486,7 @@ fn drain_filter_complex() { { // [xxx++++++xxxxx++++x+x] let mut list = - vec![2, 4, 6, 7, 9, 11, 13, 15, 17, 18, 20, 22, 24, 26, 27, 29, 31, 33, 34, 35, 36] + [2, 4, 6, 7, 9, 11, 13, 15, 17, 18, 20, 22, 24, 26, 27, 29, 31, 33, 34, 35, 36] .into_iter() .collect::<LinkedList<_>>(); @@ -504,7 +503,7 @@ fn drain_filter_complex() { { // [xxxxxxxxxx+++++++++++] - let mut list = vec![2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19] + let mut list = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19] .into_iter() .collect::<LinkedList<_>>(); @@ -518,7 +517,7 @@ fn drain_filter_complex() { { // [+++++++++++xxxxxxxxxx] - let mut list = vec![1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20] + let mut list = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20] .into_iter() .collect::<LinkedList<_>>(); diff --git a/library/alloc/tests/string.rs b/library/alloc/tests/string.rs index 7be137131ff..893283e5a24 100644 --- a/library/alloc/tests/string.rs +++ b/library/alloc/tests/string.rs @@ -489,7 +489,7 @@ fn test_from_iterator() { b.extend(u.chars()); assert_eq!(s, b); - let c: String = vec![t, u].into_iter().collect(); + let c: String = [t, u].into_iter().collect(); assert_eq!(s, c); let mut d = t.to_string(); diff --git a/library/alloc/tests/vec.rs b/library/alloc/tests/vec.rs index 77314282532..705914b4497 100644 --- a/library/alloc/tests/vec.rs +++ b/library/alloc/tests/vec.rs @@ -449,10 +449,10 @@ fn zero_sized_values() { #[test] fn test_partition() { - assert_eq!(vec![].into_iter().partition(|x: &i32| *x < 3), (vec![], vec![])); - assert_eq!(vec![1, 2, 3].into_iter().partition(|x| *x < 4), (vec![1, 2, 3], vec![])); - assert_eq!(vec![1, 2, 3].into_iter().partition(|x| *x < 2), (vec![1], vec![2, 3])); - assert_eq!(vec![1, 2, 3].into_iter().partition(|x| *x < 0), (vec![], vec![1, 2, 3])); + assert_eq!([].into_iter().partition(|x: &i32| *x < 3), (vec![], vec![])); + assert_eq!([1, 2, 3].into_iter().partition(|x| *x < 4), (vec![1, 2, 3], vec![])); + assert_eq!([1, 2, 3].into_iter().partition(|x| *x < 2), (vec![1], vec![2, 3])); + assert_eq!([1, 2, 3].into_iter().partition(|x| *x < 0), (vec![], vec![1, 2, 3])); } #[test] @@ -924,7 +924,7 @@ fn test_into_iter_debug() { #[test] fn test_into_iter_count() { - assert_eq!(vec![1, 2, 3].into_iter().count(), 3); + assert_eq!([1, 2, 3].into_iter().count(), 3); } #[test] @@ -933,7 +933,7 @@ fn test_into_iter_clone() { let v: Vec<i32> = it.collect(); assert_eq!(&v[..], slice); } - let mut it = vec![1, 2, 3].into_iter(); + let mut it = [1, 2, 3].into_iter(); iter_equal(it.clone(), &[1, 2, 3]); assert_eq!(it.next(), Some(1)); let mut it = it.rev(); @@ -972,7 +972,7 @@ fn test_into_iter_leak() { #[test] fn test_into_iter_advance_by() { - let mut i = vec![1, 2, 3, 4, 5].into_iter(); + let mut i = [1, 2, 3, 4, 5].into_iter(); i.advance_by(0).unwrap(); i.advance_back_by(0).unwrap(); assert_eq!(i.as_slice(), [1, 2, 3, 4, 5]); @@ -1799,7 +1799,7 @@ fn test_stable_pointers() { assert_eq!(*v0, 13); next_then_drop(v.splice(5..8, vec![1])); // replacement is smaller than original range assert_eq!(*v0, 13); - next_then_drop(v.splice(5..6, vec![1; 10].into_iter().filter(|_| true))); // lower bound not exact + next_then_drop(v.splice(5..6, [1; 10].into_iter().filter(|_| true))); // lower bound not exact assert_eq!(*v0, 13); // spare_capacity_mut diff --git a/library/alloc/tests/vec_deque.rs b/library/alloc/tests/vec_deque.rs index ddfb4c00c26..18954f094c6 100644 --- a/library/alloc/tests/vec_deque.rs +++ b/library/alloc/tests/vec_deque.rs @@ -927,8 +927,8 @@ fn test_as_mut_slices() { #[test] fn test_append() { - let mut a: VecDeque<_> = vec![1, 2, 3].into_iter().collect(); - let mut b: VecDeque<_> = vec![4, 5, 6].into_iter().collect(); + let mut a: VecDeque<_> = [1, 2, 3].into_iter().collect(); + let mut b: VecDeque<_> = [4, 5, 6].into_iter().collect(); // normal append a.append(&mut b); @@ -1209,7 +1209,7 @@ fn test_try_reserve() { { // Same basic idea, but with non-zero len - let mut ten_bytes: VecDeque<u8> = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10].into_iter().collect(); + let mut ten_bytes: VecDeque<u8> = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].into_iter().collect(); if let Err(CapacityOverflow) = ten_bytes.try_reserve(MAX_CAP - 10).map_err(|e| e.kind()) { panic!("isize::MAX shouldn't trigger an overflow!"); @@ -1240,7 +1240,7 @@ fn test_try_reserve() { { // Same basic idea, but with interesting type size - let mut ten_u32s: VecDeque<u32> = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10].into_iter().collect(); + let mut ten_u32s: VecDeque<u32> = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].into_iter().collect(); if let Err(CapacityOverflow) = ten_u32s.try_reserve(MAX_CAP / 4 - 10).map_err(|e| e.kind()) { @@ -1322,7 +1322,7 @@ fn test_try_reserve_exact() { } { - let mut ten_bytes: VecDeque<u8> = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10].into_iter().collect(); + let mut ten_bytes: VecDeque<u8> = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].into_iter().collect(); if let Err(CapacityOverflow) = ten_bytes.try_reserve_exact(MAX_CAP - 10).map_err(|e| e.kind()) @@ -1355,7 +1355,7 @@ fn test_try_reserve_exact() { } { - let mut ten_u32s: VecDeque<u32> = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10].into_iter().collect(); + let mut ten_u32s: VecDeque<u32> = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].into_iter().collect(); if let Err(CapacityOverflow) = ten_u32s.try_reserve_exact(MAX_CAP / 4 - 10).map_err(|e| e.kind()) diff --git a/library/core/src/convert/mod.rs b/library/core/src/convert/mod.rs index d40f69f8b35..3a149afd771 100644 --- a/library/core/src/convert/mod.rs +++ b/library/core/src/convert/mod.rs @@ -91,7 +91,7 @@ pub use num::FloatToInt; /// ```rust /// use std::convert::identity; /// -/// let iter = vec![Some(1), None, Some(3)].into_iter(); +/// let iter = [Some(1), None, Some(3)].into_iter(); /// let filtered = iter.filter_map(identity).collect::<Vec<_>>(); /// assert_eq!(vec![1, 3], filtered); /// ``` diff --git a/library/core/src/intrinsics.rs b/library/core/src/intrinsics.rs index 4ecc3b0c7f8..acbb612352b 100644 --- a/library/core/src/intrinsics.rs +++ b/library/core/src/intrinsics.rs @@ -961,7 +961,7 @@ extern "rust-intrinsic" { /// Below are common applications of `transmute` which can be replaced with safer /// constructs. /// - /// Turning raw bytes(`&[u8]`) to `u32`, `f64`, etc.: + /// Turning raw bytes (`&[u8]`) into `u32`, `f64`, etc.: /// /// ``` /// let raw_bytes = [0x78, 0x56, 0x34, 0x12]; diff --git a/library/core/src/iter/adapters/map.rs b/library/core/src/iter/adapters/map.rs index 449650a22f4..b2ed82508dd 100644 --- a/library/core/src/iter/adapters/map.rs +++ b/library/core/src/iter/adapters/map.rs @@ -19,7 +19,7 @@ use crate::ops::Try; /// you can also [`map`] backwards: /// /// ```rust -/// let v: Vec<i32> = vec![1, 2, 3].into_iter().map(|x| x + 1).rev().collect(); +/// let v: Vec<i32> = [1, 2, 3].into_iter().map(|x| x + 1).rev().collect(); /// /// assert_eq!(v, [4, 3, 2]); /// ``` @@ -32,7 +32,7 @@ use crate::ops::Try; /// ```rust /// let mut c = 0; /// -/// for pair in vec!['a', 'b', 'c'].into_iter() +/// for pair in ['a', 'b', 'c'].into_iter() /// .map(|letter| { c += 1; (letter, c) }) { /// println!("{:?}", pair); /// } @@ -49,7 +49,7 @@ use crate::ops::Try; /// ```rust /// let mut c = 0; /// -/// for pair in vec!['a', 'b', 'c'].into_iter() +/// for pair in ['a', 'b', 'c'].into_iter() /// .map(|letter| { c += 1; (letter, c) }) /// .rev() { /// println!("{:?}", pair); diff --git a/library/core/src/iter/traits/collect.rs b/library/core/src/iter/traits/collect.rs index 26c97b8ed78..fc14620a2df 100644 --- a/library/core/src/iter/traits/collect.rs +++ b/library/core/src/iter/traits/collect.rs @@ -124,7 +124,7 @@ pub trait FromIterator<A>: Sized { /// Basic usage: /// /// ``` -/// let v = vec![1, 2, 3]; +/// let v = [1, 2, 3]; /// let mut iter = v.into_iter(); /// /// assert_eq!(Some(1), iter.next()); @@ -215,7 +215,7 @@ pub trait IntoIterator { /// Basic usage: /// /// ``` - /// let v = vec![1, 2, 3]; + /// let v = [1, 2, 3]; /// let mut iter = v.into_iter(); /// /// assert_eq!(Some(1), iter.next()); diff --git a/library/core/src/iter/traits/iterator.rs b/library/core/src/iter/traits/iterator.rs index 2049adafa2f..1d947297463 100644 --- a/library/core/src/iter/traits/iterator.rs +++ b/library/core/src/iter/traits/iterator.rs @@ -590,7 +590,7 @@ pub trait Iterator { /// #[derive(PartialEq, Debug)] /// struct NotClone(usize); /// - /// let v = vec![NotClone(0), NotClone(1), NotClone(2)]; + /// let v = [NotClone(0), NotClone(1), NotClone(2)]; /// let mut it = v.into_iter().intersperse_with(|| NotClone(99)); /// /// assert_eq!(it.next(), Some(NotClone(0))); // The first element from `v`. @@ -1270,7 +1270,7 @@ pub trait Iterator { /// `take` will limit itself to the size of the underlying iterator: /// /// ``` - /// let v = vec![1, 2]; + /// let v = [1, 2]; /// let mut iter = v.into_iter().take(5); /// assert_eq!(iter.next(), Some(1)); /// assert_eq!(iter.next(), Some(2)); @@ -1604,7 +1604,7 @@ pub trait Iterator { /// Basic usage: /// /// ``` - /// let mut words = vec!["hello", "world", "of", "Rust"].into_iter(); + /// let mut words = ["hello", "world", "of", "Rust"].into_iter(); /// /// // Take the first two words. /// let hello_world: Vec<_> = words.by_ref().take(2).collect(); @@ -2700,7 +2700,7 @@ pub trait Iterator { /// incomparable. You can work around this by using [`Iterator::reduce`]: /// ``` /// assert_eq!( - /// vec![2.4, f32::NAN, 1.3] + /// [2.4, f32::NAN, 1.3] /// .into_iter() /// .reduce(f32::max) /// .unwrap(), @@ -2738,7 +2738,7 @@ pub trait Iterator { /// incomparable. You can work around this by using [`Iterator::reduce`]: /// ``` /// assert_eq!( - /// vec![2.4, f32::NAN, 1.3] + /// [2.4, f32::NAN, 1.3] /// .into_iter() /// .reduce(f32::min) /// .unwrap(), diff --git a/library/core/src/option.rs b/library/core/src/option.rs index 1ec119a71e4..8adfb6f4bcf 100644 --- a/library/core/src/option.rs +++ b/library/core/src/option.rs @@ -270,7 +270,7 @@ //! let mut bt = BTreeMap::new(); //! bt.insert(20u8, "foo"); //! bt.insert(42u8, "bar"); -//! let res = vec![0u8, 1, 11, 200, 22] +//! let res = [0u8, 1, 11, 200, 22] //! .into_iter() //! .map(|x| { //! // `checked_sub()` returns `None` on error @@ -390,10 +390,10 @@ //! [impl-FromIterator]: Option#impl-FromIterator%3COption%3CA%3E%3E //! //! ``` -//! let v = vec![Some(2), Some(4), None, Some(8)]; +//! let v = [Some(2), Some(4), None, Some(8)]; //! let res: Option<Vec<_>> = v.into_iter().collect(); //! assert_eq!(res, None); -//! let v = vec![Some(2), Some(4), Some(8)]; +//! let v = [Some(2), Some(4), Some(8)]; //! let res: Option<Vec<_>> = v.into_iter().collect(); //! assert_eq!(res, Some(vec![2, 4, 8])); //! ``` @@ -407,10 +407,10 @@ //! [impl-Sum]: Option#impl-Sum%3COption%3CU%3E%3E //! //! ``` -//! let v = vec![None, Some(1), Some(2), Some(3)]; +//! let v = [None, Some(1), Some(2), Some(3)]; //! let res: Option<i32> = v.into_iter().sum(); //! assert_eq!(res, None); -//! let v = vec![Some(1), Some(2), Some(21)]; +//! let v = [Some(1), Some(2), Some(21)]; //! let res: Option<i32> = v.into_iter().product(); //! assert_eq!(res, Some(42)); //! ``` diff --git a/library/core/src/result.rs b/library/core/src/result.rs index 575fd2b42d2..b8f0d84746c 100644 --- a/library/core/src/result.rs +++ b/library/core/src/result.rs @@ -436,7 +436,7 @@ //! # use std::str::FromStr; //! let mut results = vec![]; //! let mut errs = vec![]; -//! let nums: Vec<_> = vec!["17", "not a number", "99", "-27", "768"] +//! let nums: Vec<_> = ["17", "not a number", "99", "-27", "768"] //! .into_iter() //! .map(u8::from_str) //! // Save clones of the raw `Result` values to inspect @@ -462,10 +462,10 @@ //! [impl-FromIterator]: Result#impl-FromIterator%3CResult%3CA%2C%20E%3E%3E //! //! ``` -//! let v = vec![Ok(2), Ok(4), Err("err!"), Ok(8)]; +//! let v = [Ok(2), Ok(4), Err("err!"), Ok(8)]; //! let res: Result<Vec<_>, &str> = v.into_iter().collect(); //! assert_eq!(res, Err("err!")); -//! let v = vec![Ok(2), Ok(4), Ok(8)]; +//! let v = [Ok(2), Ok(4), Ok(8)]; //! let res: Result<Vec<_>, &str> = v.into_iter().collect(); //! assert_eq!(res, Ok(vec![2, 4, 8])); //! ``` @@ -479,10 +479,10 @@ //! [impl-Sum]: Result#impl-Sum%3CResult%3CU%2C%20E%3E%3E //! //! ``` -//! let v = vec![Err("error!"), Ok(1), Ok(2), Ok(3), Err("foo")]; +//! let v = [Err("error!"), Ok(1), Ok(2), Ok(3), Err("foo")]; //! let res: Result<i32, &str> = v.into_iter().sum(); //! assert_eq!(res, Err("error!")); -//! let v: Vec<Result<i32, &str>> = vec![Ok(1), Ok(2), Ok(21)]; +//! let v = [Ok(1), Ok(2), Ok(21)]; //! let res: Result<i32, &str> = v.into_iter().product(); //! assert_eq!(res, Ok(42)); //! ``` diff --git a/library/core/tests/iter/adapters/intersperse.rs b/library/core/tests/iter/adapters/intersperse.rs index b336c03b5ad..72ae59b6b2f 100644 --- a/library/core/tests/iter/adapters/intersperse.rs +++ b/library/core/tests/iter/adapters/intersperse.rs @@ -74,7 +74,7 @@ fn test_intersperse_with() { struct NotClone { u: u32, } - let r = vec![NotClone { u: 0 }, NotClone { u: 1 }] + let r = [NotClone { u: 0 }, NotClone { u: 1 }] .into_iter() .intersperse_with(|| NotClone { u: 2 }) .collect::<Vec<_>>(); @@ -120,7 +120,7 @@ fn test_intersperse_fold() { #[test] fn test_intersperse_collect_string() { - let contents = vec![1, 2, 3]; + let contents = [1, 2, 3]; let contents_string = contents .into_iter() diff --git a/library/core/tests/iter/adapters/peekable.rs b/library/core/tests/iter/adapters/peekable.rs index 390414d4aa2..c1a1c29b609 100644 --- a/library/core/tests/iter/adapters/peekable.rs +++ b/library/core/tests/iter/adapters/peekable.rs @@ -144,7 +144,7 @@ fn test_iterator_peekable_rfold() { #[test] fn test_iterator_peekable_next_if_eq() { // first, try on references - let xs = vec!["Heart", "of", "Gold"]; + let xs = ["Heart", "of", "Gold"]; let mut it = xs.into_iter().peekable(); // try before `peek()` assert_eq!(it.next_if_eq(&"trillian"), None); @@ -157,7 +157,7 @@ fn test_iterator_peekable_next_if_eq() { assert_eq!(it.next(), Some("Gold")); // make sure comparison works for owned values - let xs = vec![String::from("Ludicrous"), "speed".into()]; + let xs = [String::from("Ludicrous"), "speed".into()]; let mut it = xs.into_iter().peekable(); // make sure basic functionality works assert_eq!(it.next_if_eq("Ludicrous"), Some("Ludicrous".into())); @@ -167,7 +167,7 @@ fn test_iterator_peekable_next_if_eq() { #[test] fn test_iterator_peekable_mut() { - let mut it = vec![1, 2, 3].into_iter().peekable(); + let mut it = [1, 2, 3].into_iter().peekable(); if let Some(p) = it.peek_mut() { if *p == 1 { *p = 5; diff --git a/library/core/tests/iter/traits/iterator.rs b/library/core/tests/iter/traits/iterator.rs index d38bca1e3b3..bb4da831412 100644 --- a/library/core/tests/iter/traits/iterator.rs +++ b/library/core/tests/iter/traits/iterator.rs @@ -456,25 +456,25 @@ fn test_find_map() { #[test] fn test_try_reduce() { - let v: Vec<usize> = vec![1, 2, 3, 4, 5]; + let v = [1usize, 2, 3, 4, 5]; let sum = v.into_iter().try_reduce(|x, y| x.checked_add(y)); assert_eq!(sum, Some(Some(15))); - let v: Vec<usize> = vec![1, 2, 3, 4, 5, usize::MAX]; + let v = [1, 2, 3, 4, 5, usize::MAX]; let sum = v.into_iter().try_reduce(|x, y| x.checked_add(y)); assert_eq!(sum, None); - let v: Vec<usize> = Vec::new(); + let v: [usize; 0] = []; let sum = v.into_iter().try_reduce(|x, y| x.checked_add(y)); assert_eq!(sum, Some(None)); - let v = vec!["1", "2", "3", "4", "5"]; + let v = ["1", "2", "3", "4", "5"]; let max = v.into_iter().try_reduce(|x, y| { if x.parse::<usize>().ok()? > y.parse::<usize>().ok()? { Some(x) } else { Some(y) } }); assert_eq!(max, Some(Some("5"))); - let v = vec!["1", "2", "3", "4", "5"]; + let v = ["1", "2", "3", "4", "5"]; let max: Result<Option<_>, <usize as std::str::FromStr>::Err> = v.into_iter().try_reduce(|x, y| { if x.parse::<usize>()? > y.parse::<usize>()? { Ok(x) } else { Ok(y) } diff --git a/library/std/src/collections/hash/map/tests.rs b/library/std/src/collections/hash/map/tests.rs index d9b20aee2d2..eac884bfe0f 100644 --- a/library/std/src/collections/hash/map/tests.rs +++ b/library/std/src/collections/hash/map/tests.rs @@ -420,8 +420,8 @@ fn test_iterate() { #[test] fn test_keys() { - let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')]; - let map: HashMap<_, _> = vec.into_iter().collect(); + let pairs = [(1, 'a'), (2, 'b'), (3, 'c')]; + let map: HashMap<_, _> = pairs.into_iter().collect(); let keys: Vec<_> = map.keys().cloned().collect(); assert_eq!(keys.len(), 3); assert!(keys.contains(&1)); @@ -431,8 +431,8 @@ fn test_keys() { #[test] fn test_values() { - let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')]; - let map: HashMap<_, _> = vec.into_iter().collect(); + let pairs = [(1, 'a'), (2, 'b'), (3, 'c')]; + let map: HashMap<_, _> = pairs.into_iter().collect(); let values: Vec<_> = map.values().cloned().collect(); assert_eq!(values.len(), 3); assert!(values.contains(&'a')); @@ -442,8 +442,8 @@ fn test_values() { #[test] fn test_values_mut() { - let vec = vec![(1, 1), (2, 2), (3, 3)]; - let mut map: HashMap<_, _> = vec.into_iter().collect(); + let pairs = [(1, 1), (2, 2), (3, 3)]; + let mut map: HashMap<_, _> = pairs.into_iter().collect(); for value in map.values_mut() { *value = (*value) * 2 } @@ -456,8 +456,8 @@ fn test_values_mut() { #[test] fn test_into_keys() { - let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')]; - let map: HashMap<_, _> = vec.into_iter().collect(); + let pairs = [(1, 'a'), (2, 'b'), (3, 'c')]; + let map: HashMap<_, _> = pairs.into_iter().collect(); let keys: Vec<_> = map.into_keys().collect(); assert_eq!(keys.len(), 3); @@ -468,8 +468,8 @@ fn test_into_keys() { #[test] fn test_into_values() { - let vec = vec![(1, 'a'), (2, 'b'), (3, 'c')]; - let map: HashMap<_, _> = vec.into_iter().collect(); + let pairs = [(1, 'a'), (2, 'b'), (3, 'c')]; + let map: HashMap<_, _> = pairs.into_iter().collect(); let values: Vec<_> = map.into_values().collect(); assert_eq!(values.len(), 3); diff --git a/library/std/src/collections/mod.rs b/library/std/src/collections/mod.rs index 8b004525b46..b5e81deb480 100644 --- a/library/std/src/collections/mod.rs +++ b/library/std/src/collections/mod.rs @@ -232,7 +232,7 @@ //! ``` //! use std::collections::VecDeque; //! -//! let vec = vec![1, 2, 3, 4]; +//! let vec = [1, 2, 3, 4]; //! let buf: VecDeque<_> = vec.into_iter().collect(); //! ``` //! diff --git a/library/std/src/error.rs b/library/std/src/error.rs index ea0c230fa42..526a1b92b19 100644 --- a/library/std/src/error.rs +++ b/library/std/src/error.rs @@ -606,21 +606,21 @@ impl Error for time::FromSecsError {} // Copied from `any.rs`. impl dyn Error + 'static { - /// Returns `true` if the boxed type is the same as `T` + /// Returns `true` if the inner type is the same as `T`. #[stable(feature = "error_downcast", since = "1.3.0")] #[inline] pub fn is<T: Error + 'static>(&self) -> bool { // Get `TypeId` of the type this function is instantiated with. let t = TypeId::of::<T>(); - // Get `TypeId` of the type in the trait object. - let boxed = self.type_id(private::Internal); + // Get `TypeId` of the type in the trait object (`self`). + let concrete = self.type_id(private::Internal); // Compare both `TypeId`s on equality. - t == boxed + t == concrete } - /// Returns some reference to the boxed value if it is of type `T`, or + /// Returns some reference to the inner value if it is of type `T`, or /// `None` if it isn't. #[stable(feature = "error_downcast", since = "1.3.0")] #[inline] @@ -632,7 +632,7 @@ impl dyn Error + 'static { } } - /// Returns some mutable reference to the boxed value if it is of type `T`, or + /// Returns some mutable reference to the inner value if it is of type `T`, or /// `None` if it isn't. #[stable(feature = "error_downcast", since = "1.3.0")] #[inline] diff --git a/library/std/src/fs.rs b/library/std/src/fs.rs index dae85027b6c..a00b5e12323 100644 --- a/library/std/src/fs.rs +++ b/library/std/src/fs.rs @@ -356,9 +356,10 @@ impl File { /// open or create a file with specific options if `open()` or `create()` /// are not appropriate. /// - /// It is equivalent to `OpenOptions::new()` but allows you to write more - /// readable code. Instead of `OpenOptions::new().read(true).open("foo.txt")` - /// you can write `File::options().read(true).open("foo.txt")`. This + /// It is equivalent to `OpenOptions::new()`, but allows you to write more + /// readable code. Instead of + /// `OpenOptions::new().append(true).open("example.log")`, + /// you can write `File::options().append(true).open("example.log")`. This /// also avoids the need to import `OpenOptions`. /// /// See the [`OpenOptions::new`] function for more details. @@ -369,7 +370,7 @@ impl File { /// use std::fs::File; /// /// fn main() -> std::io::Result<()> { - /// let mut f = File::options().read(true).open("foo.txt")?; + /// let mut f = File::options().append(true).open("example.log")?; /// Ok(()) /// } /// ``` diff --git a/library/std/src/keyword_docs.rs b/library/std/src/keyword_docs.rs index a370485102e..35d230eee96 100644 --- a/library/std/src/keyword_docs.rs +++ b/library/std/src/keyword_docs.rs @@ -2172,7 +2172,7 @@ mod use_keyword {} /// i.next().unwrap_or_else(I::Item::default) /// } /// -/// assert_eq!(first_or_default(vec![1, 2, 3].into_iter()), 1); +/// assert_eq!(first_or_default([1, 2, 3].into_iter()), 1); /// assert_eq!(first_or_default(Vec::<i32>::new().into_iter()), 0); /// ``` /// diff --git a/library/std/src/time.rs b/library/std/src/time.rs index 86cc93c4453..b6867e68df7 100644 --- a/library/std/src/time.rs +++ b/library/std/src/time.rs @@ -54,7 +54,7 @@ pub use core::time::FromSecsError; /// instant when created, and are often useful for tasks such as measuring /// benchmarks or timing how long an operation takes. /// -/// Note, however, that instants are not guaranteed to be **steady**. In other +/// Note, however, that instants are **not** guaranteed to be **steady**. In other /// words, each tick of the underlying clock might not be the same length (e.g. /// some seconds may be longer than others). An instant may jump forwards or /// experience time dilation (slow down or speed up), but it will never go diff --git a/library/test/src/tests.rs b/library/test/src/tests.rs index 718613895de..7f0b6193d09 100644 --- a/library/test/src/tests.rs +++ b/library/test/src/tests.rs @@ -493,7 +493,7 @@ pub fn exclude_should_panic_option() { #[test] pub fn exact_filter_match() { fn tests() -> Vec<TestDescAndFn> { - vec!["base", "base::test", "base::test1", "base::test2"] + ["base", "base::test", "base::test1", "base::test2"] .into_iter() .map(|name| TestDescAndFn { desc: TestDesc { diff --git a/src/ci/docker/scripts/musl-toolchain.sh b/src/ci/docker/scripts/musl-toolchain.sh index 3c17f316d1f..e358b8139d7 100644 --- a/src/ci/docker/scripts/musl-toolchain.sh +++ b/src/ci/docker/scripts/musl-toolchain.sh @@ -48,7 +48,9 @@ cd musl-cross-make git checkout a54eb56f33f255dfca60be045f12a5cfaf5a72a9 # Fix the cfi detection script in musl's configure so cfi is generated -# when debug info is asked for. +# when debug info is asked for. This patch is derived from +# https://git.musl-libc.org/cgit/musl/commit/?id=c4d4028dde90562f631edf559fbc42d8ec1b29de. +# When we upgrade to a version that includes this commit, we can remove the patch. mkdir patches/musl-1.1.24 cp ../musl-patch-configure.diff patches/musl-1.1.24/0001-fix-cfi-detection.diff diff --git a/src/doc/rustdoc/src/documentation-tests.md b/src/doc/rustdoc/src/documentation-tests.md index aea55d4f4b6..534fd19b52e 100644 --- a/src/doc/rustdoc/src/documentation-tests.md +++ b/src/doc/rustdoc/src/documentation-tests.md @@ -335,7 +335,8 @@ panic during execution. If the code doesn't panic, the test will fail. The `no_run` attribute will compile your code but not run it. This is important for examples such as "Here's how to retrieve a web page," which you would want to ensure compiles, but might be run in a test -environment that has no network access. +environment that has no network access. This attribute can also be +used to demonstrate code snippets that can cause Undefined Behavior. ```rust /// ```no_run diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index d80e79d164a..5d1e9d6754e 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -1618,7 +1618,7 @@ impl Clean<Item> for hir::FieldDef<'_> { impl Clean<Item> for ty::FieldDef { fn clean(&self, cx: &mut DocContext<'_>) -> Item { - clean_field(self.did, self.ident.name, cx.tcx.type_of(self.did).clean(cx), cx) + clean_field(self.did, self.name, cx.tcx.type_of(self.did).clean(cx), cx) } } @@ -1689,7 +1689,7 @@ impl Clean<Item> for ty::VariantDef { }), }; let what_rustc_thinks = - Item::from_def_id_and_parts(self.def_id, Some(self.ident.name), VariantItem(kind), cx); + Item::from_def_id_and_parts(self.def_id, Some(self.name), VariantItem(kind), cx); // don't show `pub` for variants, which always inherit visibility Item { visibility: Inherited, ..what_rustc_thinks } } diff --git a/src/librustdoc/html/render/context.rs b/src/librustdoc/html/render/context.rs index 2ae203e0d2f..40453de8405 100644 --- a/src/librustdoc/html/render/context.rs +++ b/src/librustdoc/html/render/context.rs @@ -665,7 +665,7 @@ impl<'tcx> FormatRenderer<'tcx> for Context<'tcx> { _ => unreachable!(), }; let items = self.build_sidebar_items(module); - let js_dst = self.dst.join("sidebar-items.js"); + let js_dst = self.dst.join(&format!("sidebar-items{}.js", self.shared.resource_suffix)); let v = format!("initSidebarItems({});", serde_json::to_string(&items).unwrap()); scx.fs.write(js_dst, v)?; } diff --git a/src/librustdoc/html/render/mod.rs b/src/librustdoc/html/render/mod.rs index 2038e338186..d63df4e4130 100644 --- a/src/librustdoc/html/render/mod.rs +++ b/src/librustdoc/html/render/mod.rs @@ -1827,7 +1827,11 @@ fn print_sidebar(cx: &Context<'_>, it: &clean::Item, buffer: &mut Buffer) { ty = it.type_(), path = relpath ); - write!(buffer, "<script defer src=\"{}sidebar-items.js\"></script>", relpath); + write!( + buffer, + "<script defer src=\"{}sidebar-items{}.js\"></script>", + relpath, cx.shared.resource_suffix + ); // Closes sidebar-elems div. buffer.write_str("</div>"); } diff --git a/src/librustdoc/html/render/print_item.rs b/src/librustdoc/html/render/print_item.rs index 9f2830ba542..4f7bb39213b 100644 --- a/src/librustdoc/html/render/print_item.rs +++ b/src/librustdoc/html/render/print_item.rs @@ -1557,7 +1557,7 @@ fn render_union( } if it.has_stripped_fields().unwrap() { - write!(w, " // some fields omitted\n{}", tab); + write!(w, " /* private fields */\n{}", tab); } if toggle { toggle_close(w); @@ -1613,13 +1613,11 @@ fn render_struct( if has_visible_fields { if it.has_stripped_fields().unwrap() { - write!(w, "\n{} // some fields omitted", tab); + write!(w, "\n{} /* private fields */", tab); } write!(w, "\n{}", tab); } else if it.has_stripped_fields().unwrap() { - // If there are no visible fields we can just display - // `{ /* fields omitted */ }` to save space. - write!(w, " /* fields omitted */ "); + write!(w, " /* private fields */ "); } if toggle { toggle_close(w); @@ -1776,8 +1774,8 @@ fn document_type_layout(w: &mut Buffer, cx: &Context<'_>, ty_def_id: DefId) { }; for (index, layout) in variants.iter_enumerated() { - let ident = adt.variants[index].ident; - write!(w, "<li><code>{name}</code>: ", name = ident); + let name = adt.variants[index].name; + write!(w, "<li><code>{name}</code>: ", name = name); write_size_of_layout(w, layout, tag_size); writeln!(w, "</li>"); } diff --git a/src/librustdoc/passes/collect_intra_doc_links.rs b/src/librustdoc/passes/collect_intra_doc_links.rs index 9d1a8b3f80f..af62232e792 100644 --- a/src/librustdoc/passes/collect_intra_doc_links.rs +++ b/src/librustdoc/passes/collect_intra_doc_links.rs @@ -399,7 +399,7 @@ impl<'a, 'tcx> LinkCollector<'a, 'tcx> { match tcx.type_of(did).kind() { ty::Adt(def, _) if def.is_enum() => { if let Some(field) = - def.all_fields().find(|f| f.ident.name == variant_field_name) + def.all_fields().find(|f| f.ident(tcx).name == variant_field_name) { Ok((ty_res, Some(ItemFragment(FragmentKind::VariantField, field.did)))) } else { @@ -774,7 +774,7 @@ impl<'a, 'tcx> LinkCollector<'a, 'tcx> { .non_enum_variant() .fields .iter() - .find(|item| item.ident.name == item_name)?; + .find(|item| item.ident(tcx).name == item_name)?; Some((root_res, ItemFragment(FragmentKind::StructField, field.did))) } Res::Def(DefKind::Trait, did) => tcx diff --git a/src/test/rustdoc/structfields.rs b/src/test/rustdoc/structfields.rs index 6de198453cd..7e1cada4b98 100644 --- a/src/test/rustdoc/structfields.rs +++ b/src/test/rustdoc/structfields.rs @@ -2,7 +2,7 @@ pub struct Foo { // @has - //pre "pub a: ()" pub a: (), - // @has - //pre "// some fields omitted" + // @has - //pre "/* private fields */" // @!has - //pre "b: ()" b: (), // @!has - //pre "c: usize" @@ -16,7 +16,7 @@ pub struct Foo { pub struct Bar { // @has - //pre "pub a: ()" pub a: (), - // @!has - //pre "// some fields omitted" + // @!has - //pre "/* private fields */" } // @has structfields/enum.Qux.html @@ -29,11 +29,11 @@ pub enum Qux { b: (), // @has - //pre "c: usize" c: usize, - // @has - //pre "// some fields omitted" + // @has - //pre "/* private fields */" }, } -// @has structfields/struct.Baz.html //pre "pub struct Baz { /* fields omitted */ }" +// @has structfields/struct.Baz.html //pre "pub struct Baz { /* private fields */ }" pub struct Baz { x: u8, #[doc(hidden)] diff --git a/src/test/rustdoc/toggle-item-contents.rs b/src/test/rustdoc/toggle-item-contents.rs index 937646987dd..c1df4613e35 100644 --- a/src/test/rustdoc/toggle-item-contents.rs +++ b/src/test/rustdoc/toggle-item-contents.rs @@ -55,7 +55,7 @@ pub union Union { // @has 'toggle_item_contents/struct.PrivStruct.html' // @count - '//details[@class="rustdoc-toggle type-contents-toggle"]' 0 -// @has - '//div[@class="docblock item-decl"]' 'fields omitted' +// @has - '//div[@class="docblock item-decl"]' '/* private fields */' pub struct PrivStruct { a: usize, b: usize, diff --git a/src/test/rustdoc/union.rs b/src/test/rustdoc/union.rs index 89186227732..5a788eb1b1c 100644 --- a/src/test/rustdoc/union.rs +++ b/src/test/rustdoc/union.rs @@ -2,7 +2,7 @@ pub union U { // @has - //pre "pub a: u8" pub a: u8, - // @has - //pre "// some fields omitted" + // @has - //pre "/* private fields */" // @!has - //pre "b: u16" b: u16, } diff --git a/src/test/ui/rfc-2632-const-trait-impl/default-method-body-is-const-same-trait-ck.rs b/src/test/ui/rfc-2632-const-trait-impl/default-method-body-is-const-same-trait-ck.rs new file mode 100644 index 00000000000..cccb856c2f6 --- /dev/null +++ b/src/test/ui/rfc-2632-const-trait-impl/default-method-body-is-const-same-trait-ck.rs @@ -0,0 +1,17 @@ +#![feature(const_fn_trait_bound)] +#![feature(const_trait_impl)] + +pub trait Tr { + #[default_method_body_is_const] + fn a(&self) {} + + #[default_method_body_is_const] + fn b(&self) { + ().a() + //~^ ERROR calls in constant functions are limited + } +} + +impl Tr for () {} + +fn main() {} diff --git a/src/test/ui/rfc-2632-const-trait-impl/default-method-body-is-const-same-trait-ck.stderr b/src/test/ui/rfc-2632-const-trait-impl/default-method-body-is-const-same-trait-ck.stderr new file mode 100644 index 00000000000..91f4d2fd4b0 --- /dev/null +++ b/src/test/ui/rfc-2632-const-trait-impl/default-method-body-is-const-same-trait-ck.stderr @@ -0,0 +1,9 @@ +error[E0015]: calls in constant functions are limited to constant functions, tuple structs and tuple variants + --> $DIR/default-method-body-is-const-same-trait-ck.rs:10:9 + | +LL | ().a() + | ^^^^^^ + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0015`. diff --git a/src/test/ui/type-alias-impl-trait/issue-57611-trait-alias.nll.stderr b/src/test/ui/type-alias-impl-trait/issue-57611-trait-alias.nll.stderr index 8c9cb742fac..a4ccae4eb7e 100644 --- a/src/test/ui/type-alias-impl-trait/issue-57611-trait-alias.nll.stderr +++ b/src/test/ui/type-alias-impl-trait/issue-57611-trait-alias.nll.stderr @@ -10,5 +10,29 @@ error: higher-ranked subtype error LL | |x| x | ^^^^^ -error: aborting due to 2 previous errors +error[E0308]: mismatched types + --> $DIR/issue-57611-trait-alias.rs:17:16 + | +LL | type Bar = impl Baz<Self, Self>; + | ^^^^^^^^^^^^^^^^^^^^ one type is more general than the other + | + = note: expected type `for<'r> Fn<(&'r X,)>` + found type `Fn<(&'static X,)>` +note: this closure does not fulfill the lifetime requirements + --> $DIR/issue-57611-trait-alias.rs:21:9 + | +LL | |x| x + | ^^^^^ + +error: implementation of `FnOnce` is not general enough + --> $DIR/issue-57611-trait-alias.rs:17:16 + | +LL | type Bar = impl Baz<Self, Self>; + | ^^^^^^^^^^^^^^^^^^^^ implementation of `FnOnce` is not general enough + | + = note: closure with signature `fn(&'static X) -> &'static X` must implement `FnOnce<(&'0 X,)>`, for any lifetime `'0`... + = note: ...but it actually implements `FnOnce<(&'static X,)>` + +error: aborting due to 4 previous errors +For more information about this error, try `rustc --explain E0308`. diff --git a/src/tools/clippy/clippy_lints/src/default.rs b/src/tools/clippy/clippy_lints/src/default.rs index a0b137efe22..6422f5aabe5 100644 --- a/src/tools/clippy/clippy_lints/src/default.rs +++ b/src/tools/clippy/clippy_lints/src/default.rs @@ -198,7 +198,7 @@ impl LateLintPass<'_> for Default { let ext_with_default = !variant .fields .iter() - .all(|field| assigned_fields.iter().any(|(a, _)| a == &field.ident.name)); + .all(|field| assigned_fields.iter().any(|(a, _)| a == &field.name)); let field_list = assigned_fields .into_iter() 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 3573ea5f026..15215ac15cd 100644 --- a/src/tools/clippy/clippy_lints/src/default_numeric_fallback.rs +++ b/src/tools/clippy/clippy_lints/src/default_numeric_fallback.rs @@ -161,7 +161,7 @@ impl<'a, 'tcx> Visitor<'tcx> for NumericFallbackVisitor<'a, 'tcx> { fields_def .iter() .find_map(|f_def| { - if f_def.ident == field.ident + if f_def.ident(self.cx.tcx) == field.ident { Some(self.cx.tcx.type_of(f_def.did)) } else { None } }); diff --git a/src/tools/clippy/clippy_lints/src/inconsistent_struct_constructor.rs b/src/tools/clippy/clippy_lints/src/inconsistent_struct_constructor.rs index 1debdef9d86..388bb3727f9 100644 --- a/src/tools/clippy/clippy_lints/src/inconsistent_struct_constructor.rs +++ b/src/tools/clippy/clippy_lints/src/inconsistent_struct_constructor.rs @@ -76,7 +76,7 @@ impl LateLintPass<'_> for InconsistentStructConstructor { then { let mut def_order_map = FxHashMap::default(); for (idx, field) in variant.fields.iter().enumerate() { - def_order_map.insert(field.ident.name, idx); + def_order_map.insert(field.name, idx); } if is_consistent_order(fields, &def_order_map) { diff --git a/src/tools/clippy/clippy_lints/src/matches.rs b/src/tools/clippy/clippy_lints/src/matches.rs index 22970507f96..5fa8f249e70 100644 --- a/src/tools/clippy/clippy_lints/src/matches.rs +++ b/src/tools/clippy/clippy_lints/src/matches.rs @@ -1136,7 +1136,7 @@ fn check_wild_enum_match(cx: &LateContext<'_>, ex: &Expr<'_>, arms: &[Arm<'_>]) s.push_str("::"); s }, - variant.ident.name, + variant.name, match variant.ctor_kind { CtorKind::Fn if variant.fields.len() == 1 => "(_)", CtorKind::Fn => "(..)", |
